start experimental work on branch detection
[fast-export/barak.git] / p4-fast-export.py
blob01bf5baf9a50f161587b5ad370a6485db6065123
1 #!/usr/bin/python
3 # p4-fast-export.py
5 # Author: Simon Hausmann <hausmann@kde.org>
6 # License: MIT <http://www.opensource.org/licenses/mit-license.php>
8 # TODO:
9 # - support integrations (at least p4i)
10 # - support p4 submit (hah!)
12 import os, string, sys, time
13 import marshal, popen2, getopt
15 branch = "refs/heads/master"
16 prefix = previousDepotPath = os.popen("git-repo-config --get p4.depotpath").read()
17 detectBranches = False
18 if len(prefix) != 0:
19 prefix = prefix[:-1]
21 try:
22 opts, args = getopt.getopt(sys.argv[1:], "", [ "branch=", "detect-branches" ])
23 except getopt.GetoptError:
24 print "fixme, syntax error"
25 sys.exit(1)
27 for o, a in opts:
28 if o == "--branch":
29 branch = "refs/heads/" + a
30 elif o == "--detect-branches":
31 detectBranches = True
33 if len(args) == 0 and len(prefix) != 0:
34 print "[using previously specified depot path %s]" % prefix
35 elif len(args) != 1:
36 print "usage: %s //depot/path[@revRange]" % sys.argv[0]
37 print "\n example:"
38 print " %s //depot/my/project/ -- to import the current head"
39 print " %s //depot/my/project/@all -- to import everything"
40 print " %s //depot/my/project/@1,6 -- to import only from revision 1 to 6"
41 print ""
42 print " (a ... is not needed in the path p4 specification, it's added implicitly)"
43 print ""
44 sys.exit(1)
45 else:
46 if len(prefix) != 0 and prefix != args[0]:
47 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (prefix, args[0])
48 sys.exit(1)
49 prefix = args[0]
51 changeRange = ""
52 revision = ""
53 users = {}
54 initialParent = ""
55 lastChange = ""
56 initialTag = ""
58 if prefix.find("@") != -1:
59 atIdx = prefix.index("@")
60 changeRange = prefix[atIdx:]
61 if changeRange == "@all":
62 changeRange = ""
63 elif changeRange.find(",") == -1:
64 revision = changeRange
65 changeRange = ""
66 prefix = prefix[0:atIdx]
67 elif prefix.find("#") != -1:
68 hashIdx = prefix.index("#")
69 revision = prefix[hashIdx:]
70 prefix = prefix[0:hashIdx]
71 elif len(previousDepotPath) == 0:
72 revision = "#head"
74 if prefix.endswith("..."):
75 prefix = prefix[:-3]
77 if not prefix.endswith("/"):
78 prefix += "/"
80 def p4CmdList(cmd):
81 pipe = os.popen("p4 -G %s" % cmd, "rb")
82 result = []
83 try:
84 while True:
85 entry = marshal.load(pipe)
86 result.append(entry)
87 except EOFError:
88 pass
89 pipe.close()
90 return result
92 def p4Cmd(cmd):
93 list = p4CmdList(cmd)
94 result = {}
95 for entry in list:
96 result.update(entry)
97 return result;
99 def extractFilesFromCommit(commit):
100 files = []
101 fnum = 0
102 while commit.has_key("depotFile%s" % fnum):
103 path = commit["depotFile%s" % fnum]
104 if not path.startswith(prefix):
105 print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, prefix, change)
106 continue
108 file = {}
109 file["path"] = path
110 file["rev"] = commit["rev%s" % fnum]
111 file["action"] = commit["action%s" % fnum]
112 file["type"] = commit["type%s" % fnum]
113 files.append(file)
114 fnum = fnum + 1
115 return files
117 def branchesForCommit(files):
118 branches = set()
120 for file in files:
121 relativePath = file["path"][len(prefix):]
122 # strip off the filename
123 relativePath = relativePath[0:relativePath.rfind("/")]
125 if len(branches) == 0:
126 branches.add(relativePath)
127 continue
129 ###### this needs more testing :)
130 knownBranch = False
131 for branch in branches:
132 if relativePath == branch:
133 knownBranch = True
134 break
135 if relativePath.startswith(branch):
136 knownBranch = True
137 break
138 if branch.startswith(relativePath):
139 branches.remove(branch)
140 break
142 if not knownBranch:
143 branches.add(relativePath)
145 return branches
147 def commit(details, files, branch, prefix):
148 global initialParent
149 global users
150 global lastChange
152 epoch = details["time"]
153 author = details["user"]
155 gitStream.write("commit %s\n" % branch)
156 committer = ""
157 if author in users:
158 committer = "%s %s %s" % (users[author], epoch, tz)
159 else:
160 committer = "%s <a@b> %s %s" % (author, epoch, tz)
162 gitStream.write("committer %s\n" % committer)
164 gitStream.write("data <<EOT\n")
165 gitStream.write(details["desc"])
166 gitStream.write("\n[ imported from %s; change %s ]\n" % (prefix, details["change"]))
167 gitStream.write("EOT\n\n")
169 if len(initialParent) > 0:
170 gitStream.write("from %s\n" % initialParent)
171 initialParent = ""
173 for file in files:
174 path = file["path"]
175 rev = file["rev"]
176 depotPath = path + "#" + rev
177 relPath = path[len(prefix):]
178 action = file["action"]
180 if action == "delete":
181 gitStream.write("D %s\n" % relPath)
182 else:
183 mode = 644
184 if file["type"].startswith("x"):
185 mode = 755
187 data = os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
189 gitStream.write("M %s inline %s\n" % (mode, relPath))
190 gitStream.write("data %s\n" % len(data))
191 gitStream.write(data)
192 gitStream.write("\n")
194 gitStream.write("\n")
196 lastChange = details["change"]
198 def getUserMap():
199 users = {}
201 for output in p4CmdList("users"):
202 if not output.has_key("User"):
203 continue
204 users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
205 return users
207 users = getUserMap()
209 if len(changeRange) == 0:
210 try:
211 sout, sin, serr = popen2.popen3("git-name-rev --tags `git-rev-parse %s`" % branch)
212 output = sout.read()
213 if output.endswith("\n"):
214 output = output[:-1]
215 tagIdx = output.index(" tags/p4/")
216 caretIdx = output.find("^")
217 endPos = len(output)
218 if caretIdx != -1:
219 endPos = caretIdx
220 rev = int(output[tagIdx + 9 : endPos]) + 1
221 changeRange = "@%s,#head" % rev
222 initialParent = os.popen("git-rev-parse %s" % branch).read()[:-1]
223 initialTag = "p4/%s" % (int(rev) - 1)
224 except:
225 pass
227 sys.stderr.write("\n")
229 tz = - time.timezone / 36
230 tzsign = ("%s" % tz)[0]
231 if tzsign != '+' and tzsign != '-':
232 tz = "+" + ("%s" % tz)
234 gitOutput, gitStream, gitError = popen2.popen3("git-fast-import")
236 if len(revision) > 0:
237 print "Doing initial import of %s from revision %s" % (prefix, revision)
239 details = { "user" : "git perforce import user", "time" : int(time.time()) }
240 details["desc"] = "Initial import of %s from the state at revision %s" % (prefix, revision)
241 details["change"] = revision
242 newestRevision = 0
244 fileCnt = 0
245 for info in p4CmdList("files %s...%s" % (prefix, revision)):
246 change = int(info["change"])
247 if change > newestRevision:
248 newestRevision = change
250 if info["action"] == "delete":
251 continue
253 for prop in [ "depotFile", "rev", "action", "type" ]:
254 details["%s%s" % (prop, fileCnt)] = info[prop]
256 fileCnt = fileCnt + 1
258 details["change"] = newestRevision
260 try:
261 commit(details, extractFilesFromCommit(details), branch, prefix)
262 except:
263 print gitError.read()
265 else:
266 output = os.popen("p4 changes %s...%s" % (prefix, changeRange)).readlines()
268 changes = []
269 for line in output:
270 changeNum = line.split(" ")[1]
271 changes.append(changeNum)
273 changes.reverse()
275 if len(changes) == 0:
276 print "no changes to import!"
277 sys.exit(1)
279 cnt = 1
280 for change in changes:
281 description = p4Cmd("describe %s" % change)
283 sys.stdout.write("\rimporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
284 sys.stdout.flush()
285 cnt = cnt + 1
287 try:
288 files = extractFilesFromCommit(description)
289 if detectBranches:
290 for branch in branchesForCommit(files):
291 branchPrefix = prefix + branch + "/"
292 branch = "refs/heads/" + branch
293 commit(description, files, branch, branchPrefix)
294 else:
295 commit(description, files, branch, prefix)
296 except:
297 print gitError.read()
298 sys.exit(1)
300 print ""
302 gitStream.write("reset refs/tags/p4/%s\n" % lastChange)
303 gitStream.write("from %s\n\n" % branch);
306 gitStream.close()
307 gitOutput.close()
308 gitError.close()
310 os.popen("git-repo-config p4.depotpath %s" % prefix).read()
311 if len(initialTag) > 0:
312 os.popen("git tag -d %s" % initialTag).read()
314 sys.exit(0)