set marks for fast-import
[fast-export/rorcz.git] / p4-fast-export.py
blob488533b07e094d5f94e0ae516d9c657ef76a25a4
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 knownBranches = set()
16 branch = "refs/heads/master"
17 globalPrefix = previousDepotPath = os.popen("git-repo-config --get p4.depotpath").read()
18 detectBranches = False
19 if len(globalPrefix) != 0:
20 globalPrefix = globalPrefix[:-1]
22 try:
23 opts, args = getopt.getopt(sys.argv[1:], "", [ "branch=", "detect-branches" ])
24 except getopt.GetoptError:
25 print "fixme, syntax error"
26 sys.exit(1)
28 for o, a in opts:
29 if o == "--branch":
30 branch = "refs/heads/" + a
31 elif o == "--detect-branches":
32 detectBranches = True
34 if len(args) == 0 and len(globalPrefix) != 0:
35 print "[using previously specified depot path %s]" % globalPrefix
36 elif len(args) != 1:
37 print "usage: %s //depot/path[@revRange]" % sys.argv[0]
38 print "\n example:"
39 print " %s //depot/my/project/ -- to import the current head"
40 print " %s //depot/my/project/@all -- to import everything"
41 print " %s //depot/my/project/@1,6 -- to import only from revision 1 to 6"
42 print ""
43 print " (a ... is not needed in the path p4 specification, it's added implicitly)"
44 print ""
45 sys.exit(1)
46 else:
47 if len(globalPrefix) != 0 and globalPrefix != args[0]:
48 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (globalPrefix, args[0])
49 sys.exit(1)
50 globalPrefix = args[0]
52 changeRange = ""
53 revision = ""
54 users = {}
55 initialParent = ""
56 lastChange = ""
57 initialTag = ""
59 if globalPrefix.find("@") != -1:
60 atIdx = globalPrefix.index("@")
61 changeRange = globalPrefix[atIdx:]
62 if changeRange == "@all":
63 changeRange = ""
64 elif changeRange.find(",") == -1:
65 revision = changeRange
66 changeRange = ""
67 globalPrefix = globalPrefix[0:atIdx]
68 elif globalPrefix.find("#") != -1:
69 hashIdx = globalPrefix.index("#")
70 revision = globalPrefix[hashIdx:]
71 globalPrefix = globalPrefix[0:hashIdx]
72 elif len(previousDepotPath) == 0:
73 revision = "#head"
75 if globalPrefix.endswith("..."):
76 globalPrefix = globalPrefix[:-3]
78 if not globalPrefix.endswith("/"):
79 globalPrefix += "/"
81 def p4CmdList(cmd):
82 pipe = os.popen("p4 -G %s" % cmd, "rb")
83 result = []
84 try:
85 while True:
86 entry = marshal.load(pipe)
87 result.append(entry)
88 except EOFError:
89 pass
90 pipe.close()
91 return result
93 def p4Cmd(cmd):
94 list = p4CmdList(cmd)
95 result = {}
96 for entry in list:
97 result.update(entry)
98 return result;
100 def extractFilesFromCommit(commit):
101 files = []
102 fnum = 0
103 while commit.has_key("depotFile%s" % fnum):
104 path = commit["depotFile%s" % fnum]
105 if not path.startswith(globalPrefix):
106 print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, globalPrefix, change)
107 continue
109 file = {}
110 file["path"] = path
111 file["rev"] = commit["rev%s" % fnum]
112 file["action"] = commit["action%s" % fnum]
113 file["type"] = commit["type%s" % fnum]
114 files.append(file)
115 fnum = fnum + 1
116 return files
118 def branchesForCommit(files):
119 branches = set()
121 for file in files:
122 relativePath = file["path"][len(globalPrefix):]
123 # strip off the filename
124 relativePath = relativePath[0:relativePath.rfind("/")]
126 if len(branches) == 0:
127 branches.add(relativePath)
128 continue
130 ###### this needs more testing :)
131 knownBranch = False
132 for branch in branches:
133 if relativePath == branch:
134 knownBranch = True
135 break
136 if relativePath.startswith(branch):
137 knownBranch = True
138 break
139 if branch.startswith(relativePath):
140 branches.remove(branch)
141 break
143 if not knownBranch:
144 branches.add(relativePath)
146 return branches
148 def commit(details, files, branch, branchPrefix):
149 global initialParent
150 global users
151 global lastChange
153 epoch = details["time"]
154 author = details["user"]
156 gitStream.write("commit %s\n" % branch)
157 gitStream.write("mark :%s\n" % details["change"])
158 committer = ""
159 if author in users:
160 committer = "%s %s %s" % (users[author], epoch, tz)
161 else:
162 committer = "%s <a@b> %s %s" % (author, epoch, tz)
164 gitStream.write("committer %s\n" % committer)
166 gitStream.write("data <<EOT\n")
167 gitStream.write(details["desc"])
168 gitStream.write("\n[ imported from %s; change %s ]\n" % (branchPrefix, details["change"]))
169 gitStream.write("EOT\n\n")
171 if len(initialParent) > 0:
172 gitStream.write("from %s\n" % initialParent)
173 initialParent = ""
175 mergedBranches = set()
177 for file in files:
178 path = file["path"]
179 if not path.startswith(branchPrefix):
180 continue
181 action = file["action"]
182 if action != "integrate" and action != "branch":
183 continue
184 rev = file["rev"]
185 depotPath = path + "#" + rev
187 log = p4CmdList("filelog \"%s\"" % depotPath)
188 if len(log) != 1:
189 print "eek! I got confused by the filelog of %s" % depotPath
190 sys.exit(1);
192 log = log[0]
193 if log["action0"] != action:
194 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath, log["action0"], action)
195 sys.exit(1);
197 if not log["how0,0"].endswith(" from"):
198 print "eek! file %s was not branched but instead: %s" % (depotPath, log["how0,0"])
199 sys.exit(1);
201 source = log["file0,0"]
202 if source.startswith(branchPrefix):
203 continue
205 relPath = source[len(globalPrefix):]
207 for branch in knownBranches:
208 if relPath.startswith(branch) and branch not in mergedBranches:
209 gitStream.write("merge refs/heads/%s\n" % branch)
210 mergedBranches.add(branch)
211 break
213 for file in files:
214 path = file["path"]
215 if not path.startswith(branchPrefix):
216 print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, change)
217 continue
218 rev = file["rev"]
219 depotPath = path + "#" + rev
220 relPath = path[len(branchPrefix):]
221 action = file["action"]
223 if action == "delete":
224 gitStream.write("D %s\n" % relPath)
225 else:
226 mode = 644
227 if file["type"].startswith("x"):
228 mode = 755
230 data = os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
232 gitStream.write("M %s inline %s\n" % (mode, relPath))
233 gitStream.write("data %s\n" % len(data))
234 gitStream.write(data)
235 gitStream.write("\n")
237 gitStream.write("\n")
239 lastChange = details["change"]
241 def getUserMap():
242 users = {}
244 for output in p4CmdList("users"):
245 if not output.has_key("User"):
246 continue
247 users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
248 return users
250 users = getUserMap()
252 if len(changeRange) == 0:
253 try:
254 sout, sin, serr = popen2.popen3("git-name-rev --tags `git-rev-parse %s`" % branch)
255 output = sout.read()
256 if output.endswith("\n"):
257 output = output[:-1]
258 tagIdx = output.index(" tags/p4/")
259 caretIdx = output.find("^")
260 endPos = len(output)
261 if caretIdx != -1:
262 endPos = caretIdx
263 rev = int(output[tagIdx + 9 : endPos]) + 1
264 changeRange = "@%s,#head" % rev
265 initialParent = os.popen("git-rev-parse %s" % branch).read()[:-1]
266 initialTag = "p4/%s" % (int(rev) - 1)
267 except:
268 pass
270 sys.stderr.write("\n")
272 tz = - time.timezone / 36
273 tzsign = ("%s" % tz)[0]
274 if tzsign != '+' and tzsign != '-':
275 tz = "+" + ("%s" % tz)
277 gitOutput, gitStream, gitError = popen2.popen3("git-fast-import")
279 if len(revision) > 0:
280 print "Doing initial import of %s from revision %s" % (globalPrefix, revision)
282 details = { "user" : "git perforce import user", "time" : int(time.time()) }
283 details["desc"] = "Initial import of %s from the state at revision %s" % (globalPrefix, revision)
284 details["change"] = revision
285 newestRevision = 0
287 fileCnt = 0
288 for info in p4CmdList("files %s...%s" % (globalPrefix, revision)):
289 change = int(info["change"])
290 if change > newestRevision:
291 newestRevision = change
293 if info["action"] == "delete":
294 continue
296 for prop in [ "depotFile", "rev", "action", "type" ]:
297 details["%s%s" % (prop, fileCnt)] = info[prop]
299 fileCnt = fileCnt + 1
301 details["change"] = newestRevision
303 try:
304 commit(details, extractFilesFromCommit(details), branch, globalPrefix)
305 except:
306 print gitError.read()
308 else:
309 output = os.popen("p4 changes %s...%s" % (globalPrefix, changeRange)).readlines()
311 changes = []
312 for line in output:
313 changeNum = line.split(" ")[1]
314 changes.append(changeNum)
316 changes.reverse()
318 if len(changes) == 0:
319 print "no changes to import!"
320 sys.exit(1)
322 cnt = 1
323 for change in changes:
324 description = p4Cmd("describe %s" % change)
326 sys.stdout.write("\rimporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
327 sys.stdout.flush()
328 cnt = cnt + 1
330 try:
331 files = extractFilesFromCommit(description)
332 if detectBranches:
333 for branch in branchesForCommit(files):
334 knownBranches.add(branch)
335 branchPrefix = globalPrefix + branch + "/"
336 branch = "refs/heads/" + branch
337 commit(description, files, branch, branchPrefix)
338 else:
339 commit(description, files, branch, globalPrefix)
340 except:
341 print gitError.read()
342 sys.exit(1)
344 print ""
346 gitStream.write("reset refs/tags/p4/%s\n" % lastChange)
347 gitStream.write("from %s\n\n" % branch);
350 gitStream.close()
351 gitOutput.close()
352 gitError.close()
354 os.popen("git-repo-config p4.depotpath %s" % globalPrefix).read()
355 if len(initialTag) > 0:
356 os.popen("git tag -d %s" % initialTag).read()
358 sys.exit(0)