Code cleanups.
[fast-export.git] / contrib / fast-import / p4-fast-export.py
blob07d6e53852c2d76b0b16b91450eeec0c5e2d9cde
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 if len(prefix) != 0:
18 prefix = prefix[:-1]
20 try:
21 opts, args = getopt.getopt(sys.argv[1:], "", [ "branch=" ])
22 except getopt.GetoptError:
23 print "fixme, syntax error"
24 sys.exit(1)
26 for o, a in opts:
27 if o == "--branch":
28 branch = "refs/heads/" + a
30 if len(args) == 0 and len(prefix) != 0:
31 print "[using previously specified depot path %s]" % prefix
32 elif len(args) != 1:
33 print "usage: %s //depot/path[@revRange]" % sys.argv[0]
34 print "\n example:"
35 print " %s //depot/my/project/ -- to import the current head"
36 print " %s //depot/my/project/@all -- to import everything"
37 print " %s //depot/my/project/@1,6 -- to import only from revision 1 to 6"
38 print ""
39 print " (a ... is not needed in the path p4 specification, it's added implicitly)"
40 print ""
41 sys.exit(1)
42 else:
43 if len(prefix) != 0 and prefix != args[0]:
44 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (prefix, args[0])
45 sys.exit(1)
46 prefix = args[0]
48 changeRange = ""
49 revision = ""
50 users = {}
51 initialParent = ""
52 lastChange = ""
53 initialTag = ""
55 if prefix.find("@") != -1:
56 atIdx = prefix.index("@")
57 changeRange = prefix[atIdx:]
58 if changeRange == "@all":
59 changeRange = ""
60 elif changeRange.find(",") == -1:
61 revision = changeRange
62 changeRange = ""
63 prefix = prefix[0:atIdx]
64 elif prefix.find("#") != -1:
65 hashIdx = prefix.index("#")
66 revision = prefix[hashIdx:]
67 prefix = prefix[0:hashIdx]
68 elif len(previousDepotPath) == 0:
69 revision = "#head"
71 if prefix.endswith("..."):
72 prefix = prefix[:-3]
74 if not prefix.endswith("/"):
75 prefix += "/"
77 def p4CmdList(cmd):
78 pipe = os.popen("p4 -G %s" % cmd, "rb")
79 result = []
80 try:
81 while True:
82 entry = marshal.load(pipe)
83 result.append(entry)
84 except EOFError:
85 pass
86 pipe.close()
87 return result
89 def p4Cmd(cmd):
90 list = p4CmdList(cmd)
91 result = {}
92 for entry in list:
93 result.update(entry)
94 return result;
96 def extractFilesFromCommit(commit):
97 files = []
98 fnum = 0
99 while commit.has_key("depotFile%s" % fnum):
100 file = {}
101 file["path"] = commit["depotFile%s" % fnum]
102 file["rev"] = commit["rev%s" % fnum]
103 file["action"] = commit["action%s" % fnum]
104 file["type"] = commit["type%s" % fnum]
105 files.append(file)
106 fnum = fnum + 1
107 return files
109 def commit(details, files, branch):
110 global initialParent
111 global users
112 global lastChange
114 epoch = details["time"]
115 author = details["user"]
117 gitStream.write("commit %s\n" % branch)
118 committer = ""
119 if author in users:
120 committer = "%s %s %s" % (users[author], epoch, tz)
121 else:
122 committer = "%s <a@b> %s %s" % (author, epoch, tz)
124 gitStream.write("committer %s\n" % committer)
126 gitStream.write("data <<EOT\n")
127 gitStream.write(details["desc"])
128 gitStream.write("\n[ imported from %s; change %s ]\n" % (prefix, details["change"]))
129 gitStream.write("EOT\n\n")
131 if len(initialParent) > 0:
132 gitStream.write("from %s\n" % initialParent)
133 initialParent = ""
135 for file in files:
136 path = file["path"]
137 if not path.startswith(prefix):
138 print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, prefix, change)
139 continue
141 rev = file["rev"]
142 depotPath = path + "#" + rev
143 relPath = path[len(prefix):]
144 action = file["action"]
146 if action == "delete":
147 gitStream.write("D %s\n" % relPath)
148 else:
149 mode = 644
150 if file["type"].startswith("x"):
151 mode = 755
153 data = os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
155 gitStream.write("M %s inline %s\n" % (mode, relPath))
156 gitStream.write("data %s\n" % len(data))
157 gitStream.write(data)
158 gitStream.write("\n")
160 gitStream.write("\n")
162 lastChange = details["change"]
164 def getUserMap():
165 users = {}
167 for output in p4CmdList("users"):
168 if not output.has_key("User"):
169 continue
170 users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
171 return users
173 users = getUserMap()
175 if len(changeRange) == 0:
176 try:
177 sout, sin, serr = popen2.popen3("git-name-rev --tags `git-rev-parse %s`" % branch)
178 output = sout.read()
179 if output.endswith("\n"):
180 output = output[:-1]
181 tagIdx = output.index(" tags/p4/")
182 caretIdx = output.find("^")
183 endPos = len(output)
184 if caretIdx != -1:
185 endPos = caretIdx
186 rev = int(output[tagIdx + 9 : endPos]) + 1
187 changeRange = "@%s,#head" % rev
188 initialParent = os.popen("git-rev-parse %s" % branch).read()[:-1]
189 initialTag = "p4/%s" % (int(rev) - 1)
190 except:
191 pass
193 sys.stderr.write("\n")
195 tz = - time.timezone / 36
196 tzsign = ("%s" % tz)[0]
197 if tzsign != '+' and tzsign != '-':
198 tz = "+" + ("%s" % tz)
200 gitOutput, gitStream, gitError = popen2.popen3("git-fast-import")
202 if len(revision) > 0:
203 print "Doing initial import of %s from revision %s" % (prefix, revision)
205 details = { "user" : "git perforce import user", "time" : int(time.time()) }
206 details["desc"] = "Initial import of %s from the state at revision %s" % (prefix, revision)
207 details["change"] = revision
208 newestRevision = 0
210 fileCnt = 0
211 for info in p4CmdList("files %s...%s" % (prefix, revision)):
212 change = int(info["change"])
213 if change > newestRevision:
214 newestRevision = change
216 if info["action"] == "delete":
217 continue
219 for prop in [ "depotFile", "rev", "action", "type" ]:
220 details["%s%s" % (prop, fileCnt)] = info[prop]
222 fileCnt = fileCnt + 1
224 details["change"] = newestRevision
226 try:
227 commit(details, extractFilesFromCommit(details), branch)
228 except:
229 print gitError.read()
231 else:
232 output = os.popen("p4 changes %s...%s" % (prefix, changeRange)).readlines()
234 changes = []
235 for line in output:
236 changeNum = line.split(" ")[1]
237 changes.append(changeNum)
239 changes.reverse()
241 if len(changes) == 0:
242 print "no changes to import!"
243 sys.exit(1)
245 cnt = 1
246 for change in changes:
247 description = p4Cmd("describe %s" % change)
249 sys.stdout.write("\rimporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
250 sys.stdout.flush()
251 cnt = cnt + 1
253 try:
254 commit(description, extractFilesFromCommit(description), branch)
255 except:
256 print gitError.read()
257 sys.exit(1)
259 print ""
261 gitStream.write("reset refs/tags/p4/%s\n" % lastChange)
262 gitStream.write("from %s\n\n" % branch);
265 gitStream.close()
266 gitOutput.close()
267 gitError.close()
269 os.popen("git-repo-config p4.depotpath %s" % prefix).read()
270 if len(initialTag) > 0:
271 os.popen("git tag -d %s" % initialTag).read()
273 sys.exit(0)