]>
Commit | Line | Data |
---|---|---|
86949eef SH |
1 | #!/usr/bin/env python |
2 | # | |
3 | # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git. | |
4 | # | |
c8cbbee9 SH |
5 | # Author: Simon Hausmann <simon@lst.de> |
6 | # Copyright: 2007 Simon Hausmann <simon@lst.de> | |
83dce55a | 7 | # 2007 Trolltech ASA |
86949eef SH |
8 | # License: MIT <http://www.opensource.org/licenses/mit-license.php> |
9 | # | |
10 | ||
08483580 | 11 | import optparse, sys, os, marshal, popen2, subprocess, shelve |
25df95cc | 12 | import tempfile, getopt, sha, os.path, time, platform |
ce6f33c8 | 13 | import re |
8b41a97f | 14 | |
b984733c | 15 | from sets import Set; |
4f5cf76a | 16 | |
4addad22 | 17 | verbose = False |
86949eef | 18 | |
86dff6b6 HWN |
19 | def die(msg): |
20 | if verbose: | |
21 | raise Exception(msg) | |
22 | else: | |
23 | sys.stderr.write(msg + "\n") | |
24 | sys.exit(1) | |
25 | ||
bce4c5fc | 26 | def write_pipe(c, str): |
4addad22 | 27 | if verbose: |
86dff6b6 | 28 | sys.stderr.write('Writing pipe: %s\n' % c) |
b016d397 | 29 | |
bce4c5fc | 30 | pipe = os.popen(c, 'w') |
b016d397 | 31 | val = pipe.write(str) |
bce4c5fc | 32 | if pipe.close(): |
86dff6b6 | 33 | die('Command failed: %s' % c) |
b016d397 HWN |
34 | |
35 | return val | |
36 | ||
4addad22 HWN |
37 | def read_pipe(c, ignore_error=False): |
38 | if verbose: | |
86dff6b6 | 39 | sys.stderr.write('Reading pipe: %s\n' % c) |
8b41a97f | 40 | |
bce4c5fc | 41 | pipe = os.popen(c, 'rb') |
b016d397 | 42 | val = pipe.read() |
4addad22 | 43 | if pipe.close() and not ignore_error: |
86dff6b6 | 44 | die('Command failed: %s' % c) |
b016d397 HWN |
45 | |
46 | return val | |
47 | ||
48 | ||
bce4c5fc | 49 | def read_pipe_lines(c): |
4addad22 | 50 | if verbose: |
86dff6b6 | 51 | sys.stderr.write('Reading pipe: %s\n' % c) |
b016d397 | 52 | ## todo: check return status |
bce4c5fc | 53 | pipe = os.popen(c, 'rb') |
b016d397 | 54 | val = pipe.readlines() |
bce4c5fc | 55 | if pipe.close(): |
86dff6b6 | 56 | die('Command failed: %s' % c) |
b016d397 HWN |
57 | |
58 | return val | |
caace111 | 59 | |
6754a299 | 60 | def system(cmd): |
4addad22 | 61 | if verbose: |
bb6e09b2 | 62 | sys.stderr.write("executing %s\n" % cmd) |
6754a299 HWN |
63 | if os.system(cmd) != 0: |
64 | die("command failed: %s" % cmd) | |
65 | ||
b9fc6ea9 DB |
66 | def isP4Exec(kind): |
67 | """Determine if a Perforce 'kind' should have execute permission | |
68 | ||
69 | 'p4 help filetypes' gives a list of the types. If it starts with 'x', | |
70 | or x follows one of a few letters. Otherwise, if there is an 'x' after | |
71 | a plus sign, it is also executable""" | |
72 | return (re.search(r"(^[cku]?x)|\+.*x", kind) != None) | |
73 | ||
9f90c733 | 74 | def p4CmdList(cmd, stdin=None, stdin_mode='w+b'): |
86949eef | 75 | cmd = "p4 -G %s" % cmd |
6a49f8e2 HWN |
76 | if verbose: |
77 | sys.stderr.write("Opening pipe: %s\n" % cmd) | |
9f90c733 SL |
78 | |
79 | # Use a temporary file to avoid deadlocks without | |
80 | # subprocess.communicate(), which would put another copy | |
81 | # of stdout into memory. | |
82 | stdin_file = None | |
83 | if stdin is not None: | |
84 | stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode) | |
85 | stdin_file.write(stdin) | |
86 | stdin_file.flush() | |
87 | stdin_file.seek(0) | |
88 | ||
89 | p4 = subprocess.Popen(cmd, shell=True, | |
90 | stdin=stdin_file, | |
91 | stdout=subprocess.PIPE) | |
86949eef SH |
92 | |
93 | result = [] | |
94 | try: | |
95 | while True: | |
9f90c733 | 96 | entry = marshal.load(p4.stdout) |
86949eef SH |
97 | result.append(entry) |
98 | except EOFError: | |
99 | pass | |
9f90c733 SL |
100 | exitCode = p4.wait() |
101 | if exitCode != 0: | |
ac3e0d79 SH |
102 | entry = {} |
103 | entry["p4ExitCode"] = exitCode | |
104 | result.append(entry) | |
86949eef SH |
105 | |
106 | return result | |
107 | ||
108 | def p4Cmd(cmd): | |
109 | list = p4CmdList(cmd) | |
110 | result = {} | |
111 | for entry in list: | |
112 | result.update(entry) | |
113 | return result; | |
114 | ||
cb2c9db5 SH |
115 | def p4Where(depotPath): |
116 | if not depotPath.endswith("/"): | |
117 | depotPath += "/" | |
118 | output = p4Cmd("where %s..." % depotPath) | |
dc524036 SH |
119 | if output["code"] == "error": |
120 | return "" | |
cb2c9db5 SH |
121 | clientPath = "" |
122 | if "path" in output: | |
123 | clientPath = output.get("path") | |
124 | elif "data" in output: | |
125 | data = output.get("data") | |
126 | lastSpace = data.rfind(" ") | |
127 | clientPath = data[lastSpace + 1:] | |
128 | ||
129 | if clientPath.endswith("..."): | |
130 | clientPath = clientPath[:-3] | |
131 | return clientPath | |
132 | ||
86949eef | 133 | def currentGitBranch(): |
b25b2065 | 134 | return read_pipe("git name-rev HEAD").split(" ")[1].strip() |
86949eef | 135 | |
4f5cf76a | 136 | def isValidGitDir(path): |
bb6e09b2 HWN |
137 | if (os.path.exists(path + "/HEAD") |
138 | and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")): | |
4f5cf76a SH |
139 | return True; |
140 | return False | |
141 | ||
463e8af6 | 142 | def parseRevision(ref): |
b25b2065 | 143 | return read_pipe("git rev-parse %s" % ref).strip() |
463e8af6 | 144 | |
6ae8de88 SH |
145 | def extractLogMessageFromGitCommit(commit): |
146 | logMessage = "" | |
b016d397 HWN |
147 | |
148 | ## fixme: title is first line of commit, not 1st paragraph. | |
6ae8de88 | 149 | foundTitle = False |
b016d397 | 150 | for log in read_pipe_lines("git cat-file commit %s" % commit): |
6ae8de88 SH |
151 | if not foundTitle: |
152 | if len(log) == 1: | |
1c094184 | 153 | foundTitle = True |
6ae8de88 SH |
154 | continue |
155 | ||
156 | logMessage += log | |
157 | return logMessage | |
158 | ||
bb6e09b2 | 159 | def extractSettingsGitLog(log): |
6ae8de88 SH |
160 | values = {} |
161 | for line in log.split("\n"): | |
162 | line = line.strip() | |
6326aa58 HWN |
163 | m = re.search (r"^ *\[git-p4: (.*)\]$", line) |
164 | if not m: | |
165 | continue | |
166 | ||
167 | assignments = m.group(1).split (':') | |
168 | for a in assignments: | |
169 | vals = a.split ('=') | |
170 | key = vals[0].strip() | |
171 | val = ('='.join (vals[1:])).strip() | |
172 | if val.endswith ('\"') and val.startswith('"'): | |
173 | val = val[1:-1] | |
174 | ||
175 | values[key] = val | |
176 | ||
845b42cb SH |
177 | paths = values.get("depot-paths") |
178 | if not paths: | |
179 | paths = values.get("depot-path") | |
a3fdd579 SH |
180 | if paths: |
181 | values['depot-paths'] = paths.split(',') | |
bb6e09b2 | 182 | return values |
6ae8de88 | 183 | |
8136a639 | 184 | def gitBranchExists(branch): |
bb6e09b2 HWN |
185 | proc = subprocess.Popen(["git", "rev-parse", branch], |
186 | stderr=subprocess.PIPE, stdout=subprocess.PIPE); | |
caace111 | 187 | return proc.wait() == 0; |
8136a639 | 188 | |
01265103 | 189 | def gitConfig(key): |
4addad22 | 190 | return read_pipe("git config %s" % key, ignore_error=True).strip() |
01265103 | 191 | |
062410bb SH |
192 | def p4BranchesInGit(branchesAreInRemotes = True): |
193 | branches = {} | |
194 | ||
195 | cmdline = "git rev-parse --symbolic " | |
196 | if branchesAreInRemotes: | |
197 | cmdline += " --remotes" | |
198 | else: | |
199 | cmdline += " --branches" | |
200 | ||
201 | for line in read_pipe_lines(cmdline): | |
202 | line = line.strip() | |
203 | ||
204 | ## only import to p4/ | |
205 | if not line.startswith('p4/') or line == "p4/HEAD": | |
206 | continue | |
207 | branch = line | |
208 | ||
209 | # strip off p4 | |
210 | branch = re.sub ("^p4/", "", line) | |
211 | ||
212 | branches[branch] = parseRevision(line) | |
213 | return branches | |
214 | ||
9ceab363 | 215 | def findUpstreamBranchPoint(head = "HEAD"): |
86506fe5 SH |
216 | branches = p4BranchesInGit() |
217 | # map from depot-path to branch name | |
218 | branchByDepotPath = {} | |
219 | for branch in branches.keys(): | |
220 | tip = branches[branch] | |
221 | log = extractLogMessageFromGitCommit(tip) | |
222 | settings = extractSettingsGitLog(log) | |
223 | if settings.has_key("depot-paths"): | |
224 | paths = ",".join(settings["depot-paths"]) | |
225 | branchByDepotPath[paths] = "remotes/p4/" + branch | |
226 | ||
27d2d811 | 227 | settings = None |
27d2d811 SH |
228 | parent = 0 |
229 | while parent < 65535: | |
9ceab363 | 230 | commit = head + "~%s" % parent |
27d2d811 SH |
231 | log = extractLogMessageFromGitCommit(commit) |
232 | settings = extractSettingsGitLog(log) | |
86506fe5 SH |
233 | if settings.has_key("depot-paths"): |
234 | paths = ",".join(settings["depot-paths"]) | |
235 | if branchByDepotPath.has_key(paths): | |
236 | return [branchByDepotPath[paths], settings] | |
27d2d811 | 237 | |
86506fe5 | 238 | parent = parent + 1 |
27d2d811 | 239 | |
86506fe5 | 240 | return ["", settings] |
27d2d811 | 241 | |
5ca44617 SH |
242 | def createOrUpdateBranchesFromOrigin(localRefPrefix = "refs/remotes/p4/", silent=True): |
243 | if not silent: | |
244 | print ("Creating/updating branch(es) in %s based on origin branch(es)" | |
245 | % localRefPrefix) | |
246 | ||
247 | originPrefix = "origin/p4/" | |
248 | ||
249 | for line in read_pipe_lines("git rev-parse --symbolic --remotes"): | |
250 | line = line.strip() | |
251 | if (not line.startswith(originPrefix)) or line.endswith("HEAD"): | |
252 | continue | |
253 | ||
254 | headName = line[len(originPrefix):] | |
255 | remoteHead = localRefPrefix + headName | |
256 | originHead = line | |
257 | ||
258 | original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead)) | |
259 | if (not original.has_key('depot-paths') | |
260 | or not original.has_key('change')): | |
261 | continue | |
262 | ||
263 | update = False | |
264 | if not gitBranchExists(remoteHead): | |
265 | if verbose: | |
266 | print "creating %s" % remoteHead | |
267 | update = True | |
268 | else: | |
269 | settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead)) | |
270 | if settings.has_key('change') > 0: | |
271 | if settings['depot-paths'] == original['depot-paths']: | |
272 | originP4Change = int(original['change']) | |
273 | p4Change = int(settings['change']) | |
274 | if originP4Change > p4Change: | |
275 | print ("%s (%s) is newer than %s (%s). " | |
276 | "Updating p4 branch from origin." | |
277 | % (originHead, originP4Change, | |
278 | remoteHead, p4Change)) | |
279 | update = True | |
280 | else: | |
281 | print ("Ignoring: %s was imported from %s while " | |
282 | "%s was imported from %s" | |
283 | % (originHead, ','.join(original['depot-paths']), | |
284 | remoteHead, ','.join(settings['depot-paths']))) | |
285 | ||
286 | if update: | |
287 | system("git update-ref %s %s" % (remoteHead, originHead)) | |
288 | ||
289 | def originP4BranchesExist(): | |
290 | return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master") | |
291 | ||
4f6432d8 SH |
292 | def p4ChangesForPaths(depotPaths, changeRange): |
293 | assert depotPaths | |
294 | output = read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p, changeRange) | |
295 | for p in depotPaths])) | |
296 | ||
297 | changes = [] | |
298 | for line in output: | |
299 | changeNum = line.split(" ")[1] | |
300 | changes.append(int(changeNum)) | |
301 | ||
302 | changes.sort() | |
303 | return changes | |
304 | ||
b984733c SH |
305 | class Command: |
306 | def __init__(self): | |
307 | self.usage = "usage: %prog [options]" | |
8910ac0e | 308 | self.needsGit = True |
b984733c SH |
309 | |
310 | class P4Debug(Command): | |
86949eef | 311 | def __init__(self): |
6ae8de88 | 312 | Command.__init__(self) |
86949eef | 313 | self.options = [ |
b1ce9447 HWN |
314 | optparse.make_option("--verbose", dest="verbose", action="store_true", |
315 | default=False), | |
4addad22 | 316 | ] |
c8c39116 | 317 | self.description = "A tool to debug the output of p4 -G." |
8910ac0e | 318 | self.needsGit = False |
b1ce9447 | 319 | self.verbose = False |
86949eef SH |
320 | |
321 | def run(self, args): | |
b1ce9447 | 322 | j = 0 |
86949eef | 323 | for output in p4CmdList(" ".join(args)): |
b1ce9447 HWN |
324 | print 'Element: %d' % j |
325 | j += 1 | |
86949eef | 326 | print output |
b984733c | 327 | return True |
86949eef | 328 | |
5834684d SH |
329 | class P4RollBack(Command): |
330 | def __init__(self): | |
331 | Command.__init__(self) | |
332 | self.options = [ | |
0c66a783 SH |
333 | optparse.make_option("--verbose", dest="verbose", action="store_true"), |
334 | optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true") | |
5834684d SH |
335 | ] |
336 | self.description = "A tool to debug the multi-branch import. Don't use :)" | |
52102d47 | 337 | self.verbose = False |
0c66a783 | 338 | self.rollbackLocalBranches = False |
5834684d SH |
339 | |
340 | def run(self, args): | |
341 | if len(args) != 1: | |
342 | return False | |
343 | maxChange = int(args[0]) | |
0c66a783 | 344 | |
ad192f28 | 345 | if "p4ExitCode" in p4Cmd("changes -m 1"): |
66a2f523 SH |
346 | die("Problems executing p4"); |
347 | ||
0c66a783 SH |
348 | if self.rollbackLocalBranches: |
349 | refPrefix = "refs/heads/" | |
b016d397 | 350 | lines = read_pipe_lines("git rev-parse --symbolic --branches") |
0c66a783 SH |
351 | else: |
352 | refPrefix = "refs/remotes/" | |
b016d397 | 353 | lines = read_pipe_lines("git rev-parse --symbolic --remotes") |
0c66a783 SH |
354 | |
355 | for line in lines: | |
356 | if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"): | |
b25b2065 HWN |
357 | line = line.strip() |
358 | ref = refPrefix + line | |
5834684d | 359 | log = extractLogMessageFromGitCommit(ref) |
bb6e09b2 HWN |
360 | settings = extractSettingsGitLog(log) |
361 | ||
362 | depotPaths = settings['depot-paths'] | |
363 | change = settings['change'] | |
364 | ||
5834684d | 365 | changed = False |
52102d47 | 366 | |
6326aa58 HWN |
367 | if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange) |
368 | for p in depotPaths]))) == 0: | |
52102d47 SH |
369 | print "Branch %s did not exist at change %s, deleting." % (ref, maxChange) |
370 | system("git update-ref -d %s `git rev-parse %s`" % (ref, ref)) | |
371 | continue | |
372 | ||
bb6e09b2 | 373 | while change and int(change) > maxChange: |
5834684d | 374 | changed = True |
52102d47 SH |
375 | if self.verbose: |
376 | print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange) | |
5834684d SH |
377 | system("git update-ref %s \"%s^\"" % (ref, ref)) |
378 | log = extractLogMessageFromGitCommit(ref) | |
bb6e09b2 HWN |
379 | settings = extractSettingsGitLog(log) |
380 | ||
381 | ||
382 | depotPaths = settings['depot-paths'] | |
383 | change = settings['change'] | |
5834684d SH |
384 | |
385 | if changed: | |
52102d47 | 386 | print "%s rewound to %s" % (ref, change) |
5834684d SH |
387 | |
388 | return True | |
389 | ||
711544b0 | 390 | class P4Submit(Command): |
4f5cf76a | 391 | def __init__(self): |
b984733c | 392 | Command.__init__(self) |
4f5cf76a SH |
393 | self.options = [ |
394 | optparse.make_option("--continue", action="store_false", dest="firstTime"), | |
4addad22 | 395 | optparse.make_option("--verbose", dest="verbose", action="store_true"), |
4f5cf76a SH |
396 | optparse.make_option("--origin", dest="origin"), |
397 | optparse.make_option("--reset", action="store_true", dest="reset"), | |
4f5cf76a | 398 | optparse.make_option("--log-substitutions", dest="substFile"), |
04219c04 | 399 | optparse.make_option("--dry-run", action="store_true"), |
c1b296b9 | 400 | optparse.make_option("--direct", dest="directSubmit", action="store_true"), |
cb4f1280 | 401 | optparse.make_option("--trust-me-like-a-fool", dest="trustMeLikeAFool", action="store_true"), |
4f5cf76a SH |
402 | ] |
403 | self.description = "Submit changes from git to the perforce depot." | |
c9b50e63 | 404 | self.usage += " [name of git branch to submit into perforce depot]" |
4f5cf76a SH |
405 | self.firstTime = True |
406 | self.reset = False | |
407 | self.interactive = True | |
408 | self.dryRun = False | |
409 | self.substFile = "" | |
410 | self.firstTime = True | |
9512497b | 411 | self.origin = "" |
c1b296b9 | 412 | self.directSubmit = False |
cb4f1280 | 413 | self.trustMeLikeAFool = False |
b0d10df7 | 414 | self.verbose = False |
f7baba8b | 415 | self.isWindows = (platform.system() == "Windows") |
4f5cf76a SH |
416 | |
417 | self.logSubstitutions = {} | |
418 | self.logSubstitutions["<enter description here>"] = "%log%" | |
419 | self.logSubstitutions["\tDetails:"] = "\tDetails: %log%" | |
420 | ||
421 | def check(self): | |
422 | if len(p4CmdList("opened ...")) > 0: | |
423 | die("You have files opened with perforce! Close them before starting the sync.") | |
424 | ||
425 | def start(self): | |
426 | if len(self.config) > 0 and not self.reset: | |
cebdf5af HWN |
427 | die("Cannot start sync. Previous sync config found at %s\n" |
428 | "If you want to start submitting again from scratch " | |
429 | "maybe you want to call git-p4 submit --reset" % self.configFile) | |
4f5cf76a SH |
430 | |
431 | commits = [] | |
c1b296b9 SH |
432 | if self.directSubmit: |
433 | commits.append("0") | |
434 | else: | |
b016d397 | 435 | for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)): |
b25b2065 | 436 | commits.append(line.strip()) |
c1b296b9 | 437 | commits.reverse() |
4f5cf76a SH |
438 | |
439 | self.config["commits"] = commits | |
440 | ||
4f5cf76a SH |
441 | def prepareLogMessage(self, template, message): |
442 | result = "" | |
443 | ||
444 | for line in template.split("\n"): | |
445 | if line.startswith("#"): | |
446 | result += line + "\n" | |
447 | continue | |
448 | ||
449 | substituted = False | |
450 | for key in self.logSubstitutions.keys(): | |
451 | if line.find(key) != -1: | |
452 | value = self.logSubstitutions[key] | |
453 | value = value.replace("%log%", message) | |
454 | if value != "@remove@": | |
455 | result += line.replace(key, value) + "\n" | |
456 | substituted = True | |
457 | break | |
458 | ||
459 | if not substituted: | |
460 | result += line + "\n" | |
461 | ||
462 | return result | |
463 | ||
ea99c3ae SH |
464 | def prepareSubmitTemplate(self): |
465 | # remove lines in the Files section that show changes to files outside the depot path we're committing into | |
466 | template = "" | |
467 | inFilesSection = False | |
468 | for line in read_pipe_lines("p4 change -o"): | |
469 | if inFilesSection: | |
470 | if line.startswith("\t"): | |
471 | # path starts and ends with a tab | |
472 | path = line[1:] | |
473 | lastTab = path.rfind("\t") | |
474 | if lastTab != -1: | |
475 | path = path[:lastTab] | |
476 | if not path.startswith(self.depotPath): | |
477 | continue | |
478 | else: | |
479 | inFilesSection = False | |
480 | else: | |
481 | if line.startswith("Files:"): | |
482 | inFilesSection = True | |
483 | ||
484 | template += line | |
485 | ||
486 | return template | |
487 | ||
7cb5cbef | 488 | def applyCommit(self, id): |
c1b296b9 SH |
489 | if self.directSubmit: |
490 | print "Applying local change in working directory/index" | |
491 | diff = self.diffStatus | |
492 | else: | |
b016d397 HWN |
493 | print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id)) |
494 | diff = read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)) | |
4f5cf76a SH |
495 | filesToAdd = set() |
496 | filesToDelete = set() | |
d336c158 | 497 | editedFiles = set() |
4f5cf76a SH |
498 | for line in diff: |
499 | modifier = line[0] | |
500 | path = line[1:].strip() | |
501 | if modifier == "M": | |
d336c158 SH |
502 | system("p4 edit \"%s\"" % path) |
503 | editedFiles.add(path) | |
4f5cf76a SH |
504 | elif modifier == "A": |
505 | filesToAdd.add(path) | |
506 | if path in filesToDelete: | |
507 | filesToDelete.remove(path) | |
508 | elif modifier == "D": | |
509 | filesToDelete.add(path) | |
510 | if path in filesToAdd: | |
511 | filesToAdd.remove(path) | |
512 | else: | |
513 | die("unknown modifier %s for %s" % (modifier, path)) | |
514 | ||
c1b296b9 SH |
515 | if self.directSubmit: |
516 | diffcmd = "cat \"%s\"" % self.diffFile | |
517 | else: | |
518 | diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id) | |
47a130b7 | 519 | patchcmd = diffcmd + " | git apply " |
c1b296b9 SH |
520 | tryPatchCmd = patchcmd + "--check -" |
521 | applyPatchCmd = patchcmd + "--check --apply -" | |
51a2640a | 522 | |
47a130b7 | 523 | if os.system(tryPatchCmd) != 0: |
51a2640a SH |
524 | print "Unfortunately applying the change failed!" |
525 | print "What do you want to do?" | |
526 | response = "x" | |
527 | while response != "s" and response != "a" and response != "w": | |
cebdf5af HWN |
528 | response = raw_input("[s]kip this patch / [a]pply the patch forcibly " |
529 | "and with .rej files / [w]rite the patch to a file (patch.txt) ") | |
51a2640a SH |
530 | if response == "s": |
531 | print "Skipping! Good luck with the next patches..." | |
532 | return | |
533 | elif response == "a": | |
47a130b7 | 534 | os.system(applyPatchCmd) |
51a2640a SH |
535 | if len(filesToAdd) > 0: |
536 | print "You may also want to call p4 add on the following files:" | |
537 | print " ".join(filesToAdd) | |
538 | if len(filesToDelete): | |
539 | print "The following files should be scheduled for deletion with p4 delete:" | |
540 | print " ".join(filesToDelete) | |
cebdf5af HWN |
541 | die("Please resolve and submit the conflict manually and " |
542 | + "continue afterwards with git-p4 submit --continue") | |
51a2640a SH |
543 | elif response == "w": |
544 | system(diffcmd + " > patch.txt") | |
545 | print "Patch saved to patch.txt in %s !" % self.clientPath | |
cebdf5af HWN |
546 | die("Please resolve and submit the conflict manually and " |
547 | "continue afterwards with git-p4 submit --continue") | |
51a2640a | 548 | |
47a130b7 | 549 | system(applyPatchCmd) |
4f5cf76a SH |
550 | |
551 | for f in filesToAdd: | |
e6b711f0 | 552 | system("p4 add \"%s\"" % f) |
4f5cf76a | 553 | for f in filesToDelete: |
e6b711f0 SH |
554 | system("p4 revert \"%s\"" % f) |
555 | system("p4 delete \"%s\"" % f) | |
4f5cf76a | 556 | |
c1b296b9 SH |
557 | logMessage = "" |
558 | if not self.directSubmit: | |
559 | logMessage = extractLogMessageFromGitCommit(id) | |
560 | logMessage = logMessage.replace("\n", "\n\t") | |
f7baba8b MSO |
561 | if self.isWindows: |
562 | logMessage = logMessage.replace("\n", "\r\n") | |
b25b2065 | 563 | logMessage = logMessage.strip() |
4f5cf76a | 564 | |
ea99c3ae | 565 | template = self.prepareSubmitTemplate() |
4f5cf76a SH |
566 | |
567 | if self.interactive: | |
568 | submitTemplate = self.prepareLogMessage(template, logMessage) | |
b016d397 | 569 | diff = read_pipe("p4 diff -du ...") |
4f5cf76a SH |
570 | |
571 | for newFile in filesToAdd: | |
572 | diff += "==== new file ====\n" | |
573 | diff += "--- /dev/null\n" | |
574 | diff += "+++ %s\n" % newFile | |
575 | f = open(newFile, "r") | |
576 | for line in f.readlines(): | |
577 | diff += "+" + line | |
578 | f.close() | |
579 | ||
25df95cc SH |
580 | separatorLine = "######## everything below this line is just the diff #######" |
581 | if platform.system() == "Windows": | |
582 | separatorLine += "\r" | |
583 | separatorLine += "\n" | |
4f5cf76a SH |
584 | |
585 | response = "e" | |
cb4f1280 SH |
586 | if self.trustMeLikeAFool: |
587 | response = "y" | |
588 | ||
53150250 | 589 | firstIteration = True |
4f5cf76a | 590 | while response == "e": |
53150250 | 591 | if not firstIteration: |
d336c158 | 592 | response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ") |
53150250 | 593 | firstIteration = False |
4f5cf76a SH |
594 | if response == "e": |
595 | [handle, fileName] = tempfile.mkstemp() | |
596 | tmpFile = os.fdopen(handle, "w+") | |
53150250 | 597 | tmpFile.write(submitTemplate + separatorLine + diff) |
4f5cf76a | 598 | tmpFile.close() |
25df95cc SH |
599 | defaultEditor = "vi" |
600 | if platform.system() == "Windows": | |
601 | defaultEditor = "notepad" | |
602 | editor = os.environ.get("EDITOR", defaultEditor); | |
4f5cf76a | 603 | system(editor + " " + fileName) |
25df95cc | 604 | tmpFile = open(fileName, "rb") |
53150250 | 605 | message = tmpFile.read() |
4f5cf76a SH |
606 | tmpFile.close() |
607 | os.remove(fileName) | |
53150250 | 608 | submitTemplate = message[:message.index(separatorLine)] |
f7baba8b MSO |
609 | if self.isWindows: |
610 | submitTemplate = submitTemplate.replace("\r\n", "\n") | |
4f5cf76a SH |
611 | |
612 | if response == "y" or response == "yes": | |
613 | if self.dryRun: | |
614 | print submitTemplate | |
615 | raw_input("Press return to continue...") | |
616 | else: | |
7944f142 SH |
617 | if self.directSubmit: |
618 | print "Submitting to git first" | |
619 | os.chdir(self.oldWorkingDirectory) | |
b016d397 | 620 | write_pipe("git commit -a -F -", submitTemplate) |
7944f142 SH |
621 | os.chdir(self.clientPath) |
622 | ||
b016d397 | 623 | write_pipe("p4 submit -i", submitTemplate) |
d336c158 SH |
624 | elif response == "s": |
625 | for f in editedFiles: | |
626 | system("p4 revert \"%s\"" % f); | |
627 | for f in filesToAdd: | |
628 | system("p4 revert \"%s\"" % f); | |
629 | system("rm %s" %f) | |
630 | for f in filesToDelete: | |
631 | system("p4 delete \"%s\"" % f); | |
632 | return | |
4f5cf76a SH |
633 | else: |
634 | print "Not submitting!" | |
635 | self.interactive = False | |
636 | else: | |
637 | fileName = "submit.txt" | |
638 | file = open(fileName, "w+") | |
639 | file.write(self.prepareLogMessage(template, logMessage)) | |
640 | file.close() | |
cebdf5af HWN |
641 | print ("Perforce submit template written as %s. " |
642 | + "Please review/edit and then use p4 submit -i < %s to submit directly!" | |
643 | % (fileName, fileName)) | |
4f5cf76a SH |
644 | |
645 | def run(self, args): | |
c9b50e63 SH |
646 | if len(args) == 0: |
647 | self.master = currentGitBranch() | |
4280e533 | 648 | if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master): |
c9b50e63 SH |
649 | die("Detecting current git branch failed!") |
650 | elif len(args) == 1: | |
651 | self.master = args[0] | |
652 | else: | |
653 | return False | |
654 | ||
27d2d811 | 655 | [upstream, settings] = findUpstreamBranchPoint() |
ea99c3ae | 656 | self.depotPath = settings['depot-paths'][0] |
27d2d811 SH |
657 | if len(self.origin) == 0: |
658 | self.origin = upstream | |
a3fdd579 SH |
659 | |
660 | if self.verbose: | |
661 | print "Origin branch is " + self.origin | |
9512497b | 662 | |
ea99c3ae | 663 | if len(self.depotPath) == 0: |
9512497b SH |
664 | print "Internal error: cannot locate perforce depot path from existing branches" |
665 | sys.exit(128) | |
666 | ||
ea99c3ae | 667 | self.clientPath = p4Where(self.depotPath) |
9512497b | 668 | |
51a2640a | 669 | if len(self.clientPath) == 0: |
ea99c3ae | 670 | print "Error: Cannot locate perforce checkout of %s in client view" % self.depotPath |
9512497b SH |
671 | sys.exit(128) |
672 | ||
ea99c3ae | 673 | print "Perforce checkout for depot path %s located at %s" % (self.depotPath, self.clientPath) |
7944f142 | 674 | self.oldWorkingDirectory = os.getcwd() |
c1b296b9 SH |
675 | |
676 | if self.directSubmit: | |
b016d397 | 677 | self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD") |
cbf5efa6 SH |
678 | if len(self.diffStatus) == 0: |
679 | print "No changes in working directory to submit." | |
680 | return True | |
b016d397 | 681 | patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD") |
b86f7378 | 682 | self.diffFile = self.gitdir + "/p4-git-diff" |
c1b296b9 SH |
683 | f = open(self.diffFile, "wb") |
684 | f.write(patch) | |
685 | f.close(); | |
686 | ||
51a2640a | 687 | os.chdir(self.clientPath) |
31f9ec12 SH |
688 | print "Syncronizing p4 checkout..." |
689 | system("p4 sync ...") | |
9512497b | 690 | |
4f5cf76a SH |
691 | if self.reset: |
692 | self.firstTime = True | |
693 | ||
694 | if len(self.substFile) > 0: | |
695 | for line in open(self.substFile, "r").readlines(): | |
b25b2065 | 696 | tokens = line.strip().split("=") |
4f5cf76a SH |
697 | self.logSubstitutions[tokens[0]] = tokens[1] |
698 | ||
4f5cf76a | 699 | self.check() |
b86f7378 | 700 | self.configFile = self.gitdir + "/p4-git-sync.cfg" |
4f5cf76a SH |
701 | self.config = shelve.open(self.configFile, writeback=True) |
702 | ||
703 | if self.firstTime: | |
704 | self.start() | |
705 | ||
706 | commits = self.config.get("commits", []) | |
707 | ||
708 | while len(commits) > 0: | |
709 | self.firstTime = False | |
710 | commit = commits[0] | |
711 | commits = commits[1:] | |
712 | self.config["commits"] = commits | |
7cb5cbef | 713 | self.applyCommit(commit) |
4f5cf76a SH |
714 | if not self.interactive: |
715 | break | |
716 | ||
717 | self.config.close() | |
718 | ||
c1b296b9 SH |
719 | if self.directSubmit: |
720 | os.remove(self.diffFile) | |
721 | ||
4f5cf76a SH |
722 | if len(commits) == 0: |
723 | if self.firstTime: | |
724 | print "No changes found to apply between %s and current HEAD" % self.origin | |
725 | else: | |
726 | print "All changes applied!" | |
7944f142 | 727 | os.chdir(self.oldWorkingDirectory) |
14594f4b SH |
728 | |
729 | sync = P4Sync() | |
730 | sync.run([]) | |
731 | ||
732 | response = raw_input("Do you want to rebase current HEAD from Perforce now using git-p4 rebase? [y]es/[n]o ") | |
80b5910f | 733 | if response == "y" or response == "yes": |
80b5910f | 734 | rebase = P4Rebase() |
14594f4b | 735 | rebase.rebase() |
4f5cf76a SH |
736 | os.remove(self.configFile) |
737 | ||
b984733c SH |
738 | return True |
739 | ||
711544b0 | 740 | class P4Sync(Command): |
b984733c SH |
741 | def __init__(self): |
742 | Command.__init__(self) | |
743 | self.options = [ | |
744 | optparse.make_option("--branch", dest="branch"), | |
745 | optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"), | |
746 | optparse.make_option("--changesfile", dest="changesFile"), | |
747 | optparse.make_option("--silent", dest="silent", action="store_true"), | |
ef48f909 | 748 | optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"), |
a028a98e | 749 | optparse.make_option("--verbose", dest="verbose", action="store_true"), |
d2c6dd30 HWN |
750 | optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false", |
751 | help="Import into refs/heads/ , not refs/remotes"), | |
8b41a97f | 752 | optparse.make_option("--max-changes", dest="maxChanges"), |
86dff6b6 HWN |
753 | optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true', |
754 | help="Keep entire BRANCH/DIR/SUBDIR prefix during import") | |
b984733c SH |
755 | ] |
756 | self.description = """Imports from Perforce into a git repository.\n | |
757 | example: | |
758 | //depot/my/project/ -- to import the current head | |
759 | //depot/my/project/@all -- to import everything | |
760 | //depot/my/project/@1,6 -- to import only from revision 1 to 6 | |
761 | ||
762 | (a ... is not needed in the path p4 specification, it's added implicitly)""" | |
763 | ||
764 | self.usage += " //depot/path[@revRange]" | |
b984733c | 765 | self.silent = False |
b984733c SH |
766 | self.createdBranches = Set() |
767 | self.committedChanges = Set() | |
569d1bd4 | 768 | self.branch = "" |
b984733c | 769 | self.detectBranches = False |
cb53e1f8 | 770 | self.detectLabels = False |
b984733c | 771 | self.changesFile = "" |
01265103 | 772 | self.syncWithOrigin = True |
4b97ffb1 | 773 | self.verbose = False |
a028a98e | 774 | self.importIntoRemotes = True |
01a9c9c5 | 775 | self.maxChanges = "" |
c1f9197f | 776 | self.isWindows = (platform.system() == "Windows") |
8b41a97f | 777 | self.keepRepoPath = False |
6326aa58 | 778 | self.depotPaths = None |
3c699645 | 779 | self.p4BranchesInGit = [] |
b984733c | 780 | |
01265103 SH |
781 | if gitConfig("git-p4.syncFromOrigin") == "false": |
782 | self.syncWithOrigin = False | |
783 | ||
b984733c SH |
784 | def extractFilesFromCommit(self, commit): |
785 | files = [] | |
786 | fnum = 0 | |
787 | while commit.has_key("depotFile%s" % fnum): | |
788 | path = commit["depotFile%s" % fnum] | |
6326aa58 HWN |
789 | |
790 | found = [p for p in self.depotPaths | |
791 | if path.startswith (p)] | |
792 | if not found: | |
b984733c SH |
793 | fnum = fnum + 1 |
794 | continue | |
795 | ||
796 | file = {} | |
797 | file["path"] = path | |
798 | file["rev"] = commit["rev%s" % fnum] | |
799 | file["action"] = commit["action%s" % fnum] | |
800 | file["type"] = commit["type%s" % fnum] | |
801 | files.append(file) | |
802 | fnum = fnum + 1 | |
803 | return files | |
804 | ||
6326aa58 | 805 | def stripRepoPath(self, path, prefixes): |
8b41a97f | 806 | if self.keepRepoPath: |
6326aa58 HWN |
807 | prefixes = [re.sub("^(//[^/]+/).*", r'\1', prefixes[0])] |
808 | ||
809 | for p in prefixes: | |
810 | if path.startswith(p): | |
811 | path = path[len(p):] | |
8b41a97f | 812 | |
6326aa58 | 813 | return path |
6754a299 | 814 | |
71b112d4 | 815 | def splitFilesIntoBranches(self, commit): |
d5904674 | 816 | branches = {} |
71b112d4 SH |
817 | fnum = 0 |
818 | while commit.has_key("depotFile%s" % fnum): | |
819 | path = commit["depotFile%s" % fnum] | |
6326aa58 HWN |
820 | found = [p for p in self.depotPaths |
821 | if path.startswith (p)] | |
822 | if not found: | |
71b112d4 SH |
823 | fnum = fnum + 1 |
824 | continue | |
825 | ||
826 | file = {} | |
827 | file["path"] = path | |
828 | file["rev"] = commit["rev%s" % fnum] | |
829 | file["action"] = commit["action%s" % fnum] | |
830 | file["type"] = commit["type%s" % fnum] | |
831 | fnum = fnum + 1 | |
832 | ||
6326aa58 | 833 | relPath = self.stripRepoPath(path, self.depotPaths) |
b984733c | 834 | |
4b97ffb1 | 835 | for branch in self.knownBranches.keys(): |
6754a299 HWN |
836 | |
837 | # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2 | |
838 | if relPath.startswith(branch + "/"): | |
d5904674 SH |
839 | if branch not in branches: |
840 | branches[branch] = [] | |
71b112d4 | 841 | branches[branch].append(file) |
6555b2cc | 842 | break |
b984733c SH |
843 | |
844 | return branches | |
845 | ||
6a49f8e2 HWN |
846 | ## Should move this out, doesn't use SELF. |
847 | def readP4Files(self, files): | |
b1ce9447 | 848 | files = [f for f in files |
982bb8a3 | 849 | if f['action'] != 'delete'] |
6a49f8e2 | 850 | |
b1ce9447 | 851 | if not files: |
f2eda79f HWN |
852 | return |
853 | ||
78800190 SL |
854 | filedata = p4CmdList('-x - print', |
855 | stdin='\n'.join(['%s#%s' % (f['path'], f['rev']) | |
856 | for f in files]), | |
857 | stdin_mode='w+') | |
858 | if "p4ExitCode" in filedata[0]: | |
859 | die("Problems executing p4. Error: [%d]." | |
860 | % (filedata[0]['p4ExitCode'])); | |
6a49f8e2 | 861 | |
d2c6dd30 HWN |
862 | j = 0; |
863 | contents = {} | |
b1ce9447 | 864 | while j < len(filedata): |
d2c6dd30 | 865 | stat = filedata[j] |
b1ce9447 HWN |
866 | j += 1 |
867 | text = '' | |
7530a40c HWN |
868 | while j < len(filedata) and filedata[j]['code'] in ('text', |
869 | 'binary'): | |
b1ce9447 HWN |
870 | text += filedata[j]['data'] |
871 | j += 1 | |
6a49f8e2 | 872 | |
1b9a4684 HWN |
873 | |
874 | if not stat.has_key('depotFile'): | |
875 | sys.stderr.write("p4 print fails with: %s\n" % repr(stat)) | |
876 | continue | |
877 | ||
b1ce9447 | 878 | contents[stat['depotFile']] = text |
6a49f8e2 | 879 | |
d2c6dd30 HWN |
880 | for f in files: |
881 | assert not f.has_key('data') | |
882 | f['data'] = contents[f['path']] | |
6a49f8e2 | 883 | |
6326aa58 | 884 | def commit(self, details, files, branch, branchPrefixes, parent = ""): |
b984733c SH |
885 | epoch = details["time"] |
886 | author = details["user"] | |
887 | ||
4b97ffb1 SH |
888 | if self.verbose: |
889 | print "commit into %s" % branch | |
890 | ||
96e07dd2 HWN |
891 | # start with reading files; if that fails, we should not |
892 | # create a commit. | |
893 | new_files = [] | |
894 | for f in files: | |
895 | if [p for p in branchPrefixes if f['path'].startswith(p)]: | |
896 | new_files.append (f) | |
897 | else: | |
898 | sys.stderr.write("Ignoring file outside of prefix: %s\n" % path) | |
899 | files = new_files | |
900 | self.readP4Files(files) | |
901 | ||
902 | ||
903 | ||
904 | ||
b984733c | 905 | self.gitStream.write("commit %s\n" % branch) |
6a49f8e2 | 906 | # gitStream.write("mark :%s\n" % details["change"]) |
b984733c SH |
907 | self.committedChanges.add(int(details["change"])) |
908 | committer = "" | |
b607e71e SH |
909 | if author not in self.users: |
910 | self.getUserMapFromPerforceServer() | |
b984733c | 911 | if author in self.users: |
0828ab14 | 912 | committer = "%s %s %s" % (self.users[author], epoch, self.tz) |
b984733c | 913 | else: |
0828ab14 | 914 | committer = "%s <a@b> %s %s" % (author, epoch, self.tz) |
b984733c SH |
915 | |
916 | self.gitStream.write("committer %s\n" % committer) | |
917 | ||
918 | self.gitStream.write("data <<EOT\n") | |
919 | self.gitStream.write(details["desc"]) | |
6581de09 SH |
920 | self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s" |
921 | % (','.join (branchPrefixes), details["change"])) | |
922 | if len(details['options']) > 0: | |
923 | self.gitStream.write(": options = %s" % details['options']) | |
924 | self.gitStream.write("]\nEOT\n\n") | |
b984733c SH |
925 | |
926 | if len(parent) > 0: | |
4b97ffb1 SH |
927 | if self.verbose: |
928 | print "parent %s" % parent | |
b984733c SH |
929 | self.gitStream.write("from %s\n" % parent) |
930 | ||
6a49f8e2 | 931 | for file in files: |
b984733c | 932 | if file["type"] == "apple": |
6a49f8e2 | 933 | print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path'] |
b984733c SH |
934 | continue |
935 | ||
6a49f8e2 HWN |
936 | relPath = self.stripRepoPath(file['path'], branchPrefixes) |
937 | if file["action"] == "delete": | |
b984733c SH |
938 | self.gitStream.write("D %s\n" % relPath) |
939 | else: | |
6a49f8e2 | 940 | data = file['data'] |
b984733c | 941 | |
74276ec6 | 942 | mode = "644" |
b9fc6ea9 | 943 | if isP4Exec(file["type"]): |
74276ec6 SH |
944 | mode = "755" |
945 | elif file["type"] == "symlink": | |
946 | mode = "120000" | |
947 | # p4 print on a symlink contains "target\n", so strip it off | |
948 | data = data[:-1] | |
949 | ||
c1f9197f MSO |
950 | if self.isWindows and file["type"].endswith("text"): |
951 | data = data.replace("\r\n", "\n") | |
952 | ||
74276ec6 | 953 | self.gitStream.write("M %s inline %s\n" % (mode, relPath)) |
b984733c SH |
954 | self.gitStream.write("data %s\n" % len(data)) |
955 | self.gitStream.write(data) | |
956 | self.gitStream.write("\n") | |
957 | ||
958 | self.gitStream.write("\n") | |
959 | ||
1f4ba1cb SH |
960 | change = int(details["change"]) |
961 | ||
9bda3a85 | 962 | if self.labels.has_key(change): |
1f4ba1cb SH |
963 | label = self.labels[change] |
964 | labelDetails = label[0] | |
965 | labelRevisions = label[1] | |
71b112d4 SH |
966 | if self.verbose: |
967 | print "Change %s is labelled %s" % (change, labelDetails) | |
1f4ba1cb | 968 | |
6326aa58 HWN |
969 | files = p4CmdList("files " + ' '.join (["%s...@%s" % (p, change) |
970 | for p in branchPrefixes])) | |
1f4ba1cb SH |
971 | |
972 | if len(files) == len(labelRevisions): | |
973 | ||
974 | cleanedFiles = {} | |
975 | for info in files: | |
976 | if info["action"] == "delete": | |
977 | continue | |
978 | cleanedFiles[info["depotFile"]] = info["rev"] | |
979 | ||
980 | if cleanedFiles == labelRevisions: | |
981 | self.gitStream.write("tag tag_%s\n" % labelDetails["label"]) | |
982 | self.gitStream.write("from %s\n" % branch) | |
983 | ||
984 | owner = labelDetails["Owner"] | |
985 | tagger = "" | |
986 | if author in self.users: | |
987 | tagger = "%s %s %s" % (self.users[owner], epoch, self.tz) | |
988 | else: | |
989 | tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz) | |
990 | self.gitStream.write("tagger %s\n" % tagger) | |
991 | self.gitStream.write("data <<EOT\n") | |
992 | self.gitStream.write(labelDetails["Description"]) | |
993 | self.gitStream.write("EOT\n\n") | |
994 | ||
995 | else: | |
a46668fa | 996 | if not self.silent: |
cebdf5af HWN |
997 | print ("Tag %s does not match with change %s: files do not match." |
998 | % (labelDetails["label"], change)) | |
1f4ba1cb SH |
999 | |
1000 | else: | |
a46668fa | 1001 | if not self.silent: |
cebdf5af HWN |
1002 | print ("Tag %s does not match with change %s: file count is different." |
1003 | % (labelDetails["label"], change)) | |
b984733c | 1004 | |
183b8ef8 | 1005 | def getUserCacheFilename(self): |
b2d2d16a SH |
1006 | home = os.environ.get("HOME", os.environ.get("USERPROFILE")) |
1007 | return home + "/.gitp4-usercache.txt" | |
183b8ef8 | 1008 | |
b607e71e | 1009 | def getUserMapFromPerforceServer(self): |
ebd81168 SH |
1010 | if self.userMapFromPerforceServer: |
1011 | return | |
b984733c SH |
1012 | self.users = {} |
1013 | ||
1014 | for output in p4CmdList("users"): | |
1015 | if not output.has_key("User"): | |
1016 | continue | |
1017 | self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">" | |
1018 | ||
183b8ef8 HWN |
1019 | |
1020 | s = '' | |
1021 | for (key, val) in self.users.items(): | |
1022 | s += "%s\t%s\n" % (key, val) | |
1023 | ||
1024 | open(self.getUserCacheFilename(), "wb").write(s) | |
ebd81168 | 1025 | self.userMapFromPerforceServer = True |
b607e71e SH |
1026 | |
1027 | def loadUserMapFromCache(self): | |
1028 | self.users = {} | |
ebd81168 | 1029 | self.userMapFromPerforceServer = False |
b607e71e | 1030 | try: |
183b8ef8 | 1031 | cache = open(self.getUserCacheFilename(), "rb") |
b607e71e SH |
1032 | lines = cache.readlines() |
1033 | cache.close() | |
1034 | for line in lines: | |
b25b2065 | 1035 | entry = line.strip().split("\t") |
b607e71e SH |
1036 | self.users[entry[0]] = entry[1] |
1037 | except IOError: | |
1038 | self.getUserMapFromPerforceServer() | |
1039 | ||
1f4ba1cb SH |
1040 | def getLabels(self): |
1041 | self.labels = {} | |
1042 | ||
6326aa58 | 1043 | l = p4CmdList("labels %s..." % ' '.join (self.depotPaths)) |
10c3211b | 1044 | if len(l) > 0 and not self.silent: |
6326aa58 | 1045 | print "Finding files belonging to labels in %s" % `self.depotPath` |
01ce1fe9 SH |
1046 | |
1047 | for output in l: | |
1f4ba1cb SH |
1048 | label = output["label"] |
1049 | revisions = {} | |
1050 | newestChange = 0 | |
71b112d4 SH |
1051 | if self.verbose: |
1052 | print "Querying files for label %s" % label | |
6326aa58 HWN |
1053 | for file in p4CmdList("files " |
1054 | + ' '.join (["%s...@%s" % (p, label) | |
1055 | for p in self.depotPaths])): | |
1f4ba1cb SH |
1056 | revisions[file["depotFile"]] = file["rev"] |
1057 | change = int(file["change"]) | |
1058 | if change > newestChange: | |
1059 | newestChange = change | |
1060 | ||
9bda3a85 SH |
1061 | self.labels[newestChange] = [output, revisions] |
1062 | ||
1063 | if self.verbose: | |
1064 | print "Label changes: %s" % self.labels.keys() | |
1f4ba1cb | 1065 | |
86dff6b6 HWN |
1066 | def guessProjectName(self): |
1067 | for p in self.depotPaths: | |
6e5295c4 SH |
1068 | if p.endswith("/"): |
1069 | p = p[:-1] | |
1070 | p = p[p.strip().rfind("/") + 1:] | |
1071 | if not p.endswith("/"): | |
1072 | p += "/" | |
1073 | return p | |
86dff6b6 | 1074 | |
4b97ffb1 | 1075 | def getBranchMapping(self): |
6555b2cc SH |
1076 | lostAndFoundBranches = set() |
1077 | ||
4b97ffb1 SH |
1078 | for info in p4CmdList("branches"): |
1079 | details = p4Cmd("branch -o %s" % info["branch"]) | |
1080 | viewIdx = 0 | |
1081 | while details.has_key("View%s" % viewIdx): | |
1082 | paths = details["View%s" % viewIdx].split(" ") | |
1083 | viewIdx = viewIdx + 1 | |
1084 | # require standard //depot/foo/... //depot/bar/... mapping | |
1085 | if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."): | |
1086 | continue | |
1087 | source = paths[0] | |
1088 | destination = paths[1] | |
6509e19c SH |
1089 | ## HACK |
1090 | if source.startswith(self.depotPaths[0]) and destination.startswith(self.depotPaths[0]): | |
1091 | source = source[len(self.depotPaths[0]):-4] | |
1092 | destination = destination[len(self.depotPaths[0]):-4] | |
6555b2cc | 1093 | |
1a2edf4e SH |
1094 | if destination in self.knownBranches: |
1095 | if not self.silent: | |
1096 | print "p4 branch %s defines a mapping from %s to %s" % (info["branch"], source, destination) | |
1097 | print "but there exists another mapping from %s to %s already!" % (self.knownBranches[destination], destination) | |
1098 | continue | |
1099 | ||
6555b2cc SH |
1100 | self.knownBranches[destination] = source |
1101 | ||
1102 | lostAndFoundBranches.discard(destination) | |
1103 | ||
29bdbac1 | 1104 | if source not in self.knownBranches: |
6555b2cc SH |
1105 | lostAndFoundBranches.add(source) |
1106 | ||
1107 | ||
1108 | for branch in lostAndFoundBranches: | |
1109 | self.knownBranches[branch] = branch | |
29bdbac1 SH |
1110 | |
1111 | def listExistingP4GitBranches(self): | |
144ff46b SH |
1112 | # branches holds mapping from name to commit |
1113 | branches = p4BranchesInGit(self.importIntoRemotes) | |
1114 | self.p4BranchesInGit = branches.keys() | |
1115 | for branch in branches.keys(): | |
1116 | self.initialParents[self.refPrefix + branch] = branches[branch] | |
4b97ffb1 | 1117 | |
bb6e09b2 HWN |
1118 | def updateOptionDict(self, d): |
1119 | option_keys = {} | |
1120 | if self.keepRepoPath: | |
1121 | option_keys['keepRepoPath'] = 1 | |
1122 | ||
1123 | d["options"] = ' '.join(sorted(option_keys.keys())) | |
1124 | ||
1125 | def readOptions(self, d): | |
1126 | self.keepRepoPath = (d.has_key('options') | |
1127 | and ('keepRepoPath' in d['options'])) | |
6326aa58 | 1128 | |
8134f69c SH |
1129 | def gitRefForBranch(self, branch): |
1130 | if branch == "main": | |
1131 | return self.refPrefix + "master" | |
1132 | ||
1133 | if len(branch) <= 0: | |
1134 | return branch | |
1135 | ||
1136 | return self.refPrefix + self.projectName + branch | |
1137 | ||
1ca3d710 SH |
1138 | def gitCommitByP4Change(self, ref, change): |
1139 | if self.verbose: | |
1140 | print "looking in ref " + ref + " for change %s using bisect..." % change | |
1141 | ||
1142 | earliestCommit = "" | |
1143 | latestCommit = parseRevision(ref) | |
1144 | ||
1145 | while True: | |
1146 | if self.verbose: | |
1147 | print "trying: earliest %s latest %s" % (earliestCommit, latestCommit) | |
1148 | next = read_pipe("git rev-list --bisect %s %s" % (latestCommit, earliestCommit)).strip() | |
1149 | if len(next) == 0: | |
1150 | if self.verbose: | |
1151 | print "argh" | |
1152 | return "" | |
1153 | log = extractLogMessageFromGitCommit(next) | |
1154 | settings = extractSettingsGitLog(log) | |
1155 | currentChange = int(settings['change']) | |
1156 | if self.verbose: | |
1157 | print "current change %s" % currentChange | |
1158 | ||
1159 | if currentChange == change: | |
1160 | if self.verbose: | |
1161 | print "found %s" % next | |
1162 | return next | |
1163 | ||
1164 | if currentChange < change: | |
1165 | earliestCommit = "^%s" % next | |
1166 | else: | |
1167 | latestCommit = "%s" % next | |
1168 | ||
1169 | return "" | |
1170 | ||
1171 | def importNewBranch(self, branch, maxChange): | |
1172 | # make fast-import flush all changes to disk and update the refs using the checkpoint | |
1173 | # command so that we can try to find the branch parent in the git history | |
1174 | self.gitStream.write("checkpoint\n\n"); | |
1175 | self.gitStream.flush(); | |
1176 | branchPrefix = self.depotPaths[0] + branch + "/" | |
1177 | range = "@1,%s" % maxChange | |
1178 | #print "prefix" + branchPrefix | |
1179 | changes = p4ChangesForPaths([branchPrefix], range) | |
1180 | if len(changes) <= 0: | |
1181 | return False | |
1182 | firstChange = changes[0] | |
1183 | #print "first change in branch: %s" % firstChange | |
1184 | sourceBranch = self.knownBranches[branch] | |
1185 | sourceDepotPath = self.depotPaths[0] + sourceBranch | |
1186 | sourceRef = self.gitRefForBranch(sourceBranch) | |
1187 | #print "source " + sourceBranch | |
1188 | ||
1189 | branchParentChange = int(p4Cmd("changes -m 1 %s...@1,%s" % (sourceDepotPath, firstChange))["change"]) | |
1190 | #print "branch parent: %s" % branchParentChange | |
1191 | gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange) | |
1192 | if len(gitParent) > 0: | |
1193 | self.initialParents[self.gitRefForBranch(branch)] = gitParent | |
1194 | #print "parent git commit: %s" % gitParent | |
1195 | ||
1196 | self.importChanges(changes) | |
1197 | return True | |
1198 | ||
e87f37ae SH |
1199 | def importChanges(self, changes): |
1200 | cnt = 1 | |
1201 | for change in changes: | |
1202 | description = p4Cmd("describe %s" % change) | |
1203 | self.updateOptionDict(description) | |
1204 | ||
1205 | if not self.silent: | |
1206 | sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes))) | |
1207 | sys.stdout.flush() | |
1208 | cnt = cnt + 1 | |
1209 | ||
1210 | try: | |
1211 | if self.detectBranches: | |
1212 | branches = self.splitFilesIntoBranches(description) | |
1213 | for branch in branches.keys(): | |
1214 | ## HACK --hwn | |
1215 | branchPrefix = self.depotPaths[0] + branch + "/" | |
1216 | ||
1217 | parent = "" | |
1218 | ||
1219 | filesForCommit = branches[branch] | |
1220 | ||
1221 | if self.verbose: | |
1222 | print "branch is %s" % branch | |
1223 | ||
1224 | self.updatedBranches.add(branch) | |
1225 | ||
1226 | if branch not in self.createdBranches: | |
1227 | self.createdBranches.add(branch) | |
1228 | parent = self.knownBranches[branch] | |
1229 | if parent == branch: | |
1230 | parent = "" | |
1ca3d710 SH |
1231 | else: |
1232 | fullBranch = self.projectName + branch | |
1233 | if fullBranch not in self.p4BranchesInGit: | |
1234 | if not self.silent: | |
1235 | print("\n Importing new branch %s" % fullBranch); | |
1236 | if self.importNewBranch(branch, change - 1): | |
1237 | parent = "" | |
1238 | self.p4BranchesInGit.append(fullBranch) | |
1239 | if not self.silent: | |
1240 | print("\n Resuming with change %s" % change); | |
1241 | ||
1242 | if self.verbose: | |
1243 | print "parent determined through known branches: %s" % parent | |
e87f37ae | 1244 | |
8134f69c SH |
1245 | branch = self.gitRefForBranch(branch) |
1246 | parent = self.gitRefForBranch(parent) | |
e87f37ae SH |
1247 | |
1248 | if self.verbose: | |
1249 | print "looking for initial parent for %s; current parent is %s" % (branch, parent) | |
1250 | ||
1251 | if len(parent) == 0 and branch in self.initialParents: | |
1252 | parent = self.initialParents[branch] | |
1253 | del self.initialParents[branch] | |
1254 | ||
1255 | self.commit(description, filesForCommit, branch, [branchPrefix], parent) | |
1256 | else: | |
1257 | files = self.extractFilesFromCommit(description) | |
1258 | self.commit(description, files, self.branch, self.depotPaths, | |
1259 | self.initialParent) | |
1260 | self.initialParent = "" | |
1261 | except IOError: | |
1262 | print self.gitError.read() | |
1263 | sys.exit(1) | |
1264 | ||
c208a243 SH |
1265 | def importHeadRevision(self, revision): |
1266 | print "Doing initial import of %s from revision %s into %s" % (' '.join(self.depotPaths), revision, self.branch) | |
1267 | ||
1268 | details = { "user" : "git perforce import user", "time" : int(time.time()) } | |
1269 | details["desc"] = ("Initial import of %s from the state at revision %s" | |
1270 | % (' '.join(self.depotPaths), revision)) | |
1271 | details["change"] = revision | |
1272 | newestRevision = 0 | |
1273 | ||
1274 | fileCnt = 0 | |
1275 | for info in p4CmdList("files " | |
1276 | + ' '.join(["%s...%s" | |
1277 | % (p, revision) | |
1278 | for p in self.depotPaths])): | |
1279 | ||
1280 | if info['code'] == 'error': | |
1281 | sys.stderr.write("p4 returned an error: %s\n" | |
1282 | % info['data']) | |
1283 | sys.exit(1) | |
1284 | ||
1285 | ||
1286 | change = int(info["change"]) | |
1287 | if change > newestRevision: | |
1288 | newestRevision = change | |
1289 | ||
1290 | if info["action"] == "delete": | |
1291 | # don't increase the file cnt, otherwise details["depotFile123"] will have gaps! | |
1292 | #fileCnt = fileCnt + 1 | |
1293 | continue | |
1294 | ||
1295 | for prop in ["depotFile", "rev", "action", "type" ]: | |
1296 | details["%s%s" % (prop, fileCnt)] = info[prop] | |
1297 | ||
1298 | fileCnt = fileCnt + 1 | |
1299 | ||
1300 | details["change"] = newestRevision | |
1301 | self.updateOptionDict(details) | |
1302 | try: | |
1303 | self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPaths) | |
1304 | except IOError: | |
1305 | print "IO error with git fast-import. Is your git version recent enough?" | |
1306 | print self.gitError.read() | |
1307 | ||
1308 | ||
b984733c | 1309 | def run(self, args): |
6326aa58 | 1310 | self.depotPaths = [] |
179caebf SH |
1311 | self.changeRange = "" |
1312 | self.initialParent = "" | |
6326aa58 | 1313 | self.previousDepotPaths = [] |
ce6f33c8 | 1314 | |
29bdbac1 SH |
1315 | # map from branch depot path to parent branch |
1316 | self.knownBranches = {} | |
1317 | self.initialParents = {} | |
5ca44617 | 1318 | self.hasOrigin = originP4BranchesExist() |
a43ff00c SH |
1319 | if not self.syncWithOrigin: |
1320 | self.hasOrigin = False | |
29bdbac1 | 1321 | |
a028a98e SH |
1322 | if self.importIntoRemotes: |
1323 | self.refPrefix = "refs/remotes/p4/" | |
1324 | else: | |
db775559 | 1325 | self.refPrefix = "refs/heads/p4/" |
a028a98e | 1326 | |
cebdf5af HWN |
1327 | if self.syncWithOrigin and self.hasOrigin: |
1328 | if not self.silent: | |
1329 | print "Syncing with origin first by calling git fetch origin" | |
1330 | system("git fetch origin") | |
10f880f8 | 1331 | |
569d1bd4 | 1332 | if len(self.branch) == 0: |
db775559 | 1333 | self.branch = self.refPrefix + "master" |
a028a98e | 1334 | if gitBranchExists("refs/heads/p4") and self.importIntoRemotes: |
48df6fd8 | 1335 | system("git update-ref %s refs/heads/p4" % self.branch) |
48df6fd8 | 1336 | system("git branch -D p4"); |
faf1bd20 | 1337 | # create it /after/ importing, when master exists |
0058a33a | 1338 | if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes and gitBranchExists(self.branch): |
a3c55c09 | 1339 | system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch)) |
967f72e2 | 1340 | |
6a49f8e2 HWN |
1341 | # TODO: should always look at previous commits, |
1342 | # merge with previous imports, if possible. | |
1343 | if args == []: | |
d414c74a | 1344 | if self.hasOrigin: |
5ca44617 | 1345 | createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent) |
abcd790f SH |
1346 | self.listExistingP4GitBranches() |
1347 | ||
1348 | if len(self.p4BranchesInGit) > 1: | |
1349 | if not self.silent: | |
1350 | print "Importing from/into multiple branches" | |
1351 | self.detectBranches = True | |
967f72e2 | 1352 | |
29bdbac1 SH |
1353 | if self.verbose: |
1354 | print "branches: %s" % self.p4BranchesInGit | |
1355 | ||
1356 | p4Change = 0 | |
1357 | for branch in self.p4BranchesInGit: | |
cebdf5af | 1358 | logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch) |
bb6e09b2 HWN |
1359 | |
1360 | settings = extractSettingsGitLog(logMsg) | |
29bdbac1 | 1361 | |
bb6e09b2 HWN |
1362 | self.readOptions(settings) |
1363 | if (settings.has_key('depot-paths') | |
1364 | and settings.has_key ('change')): | |
1365 | change = int(settings['change']) + 1 | |
29bdbac1 SH |
1366 | p4Change = max(p4Change, change) |
1367 | ||
bb6e09b2 HWN |
1368 | depotPaths = sorted(settings['depot-paths']) |
1369 | if self.previousDepotPaths == []: | |
6326aa58 | 1370 | self.previousDepotPaths = depotPaths |
29bdbac1 | 1371 | else: |
6326aa58 HWN |
1372 | paths = [] |
1373 | for (prev, cur) in zip(self.previousDepotPaths, depotPaths): | |
583e1707 | 1374 | for i in range(0, min(len(cur), len(prev))): |
6326aa58 | 1375 | if cur[i] <> prev[i]: |
583e1707 | 1376 | i = i - 1 |
6326aa58 HWN |
1377 | break |
1378 | ||
583e1707 | 1379 | paths.append (cur[:i + 1]) |
6326aa58 HWN |
1380 | |
1381 | self.previousDepotPaths = paths | |
29bdbac1 SH |
1382 | |
1383 | if p4Change > 0: | |
bb6e09b2 | 1384 | self.depotPaths = sorted(self.previousDepotPaths) |
d5904674 | 1385 | self.changeRange = "@%s,#head" % p4Change |
330f53b8 SH |
1386 | if not self.detectBranches: |
1387 | self.initialParent = parseRevision(self.branch) | |
341dc1c1 | 1388 | if not self.silent and not self.detectBranches: |
967f72e2 | 1389 | print "Performing incremental import into %s git branch" % self.branch |
569d1bd4 | 1390 | |
f9162f6a SH |
1391 | if not self.branch.startswith("refs/"): |
1392 | self.branch = "refs/heads/" + self.branch | |
179caebf | 1393 | |
6326aa58 | 1394 | if len(args) == 0 and self.depotPaths: |
b984733c | 1395 | if not self.silent: |
6326aa58 | 1396 | print "Depot paths: %s" % ' '.join(self.depotPaths) |
b984733c | 1397 | else: |
6326aa58 | 1398 | if self.depotPaths and self.depotPaths != args: |
cebdf5af | 1399 | print ("previous import used depot path %s and now %s was specified. " |
6326aa58 HWN |
1400 | "This doesn't work!" % (' '.join (self.depotPaths), |
1401 | ' '.join (args))) | |
b984733c | 1402 | sys.exit(1) |
6326aa58 | 1403 | |
bb6e09b2 | 1404 | self.depotPaths = sorted(args) |
b984733c | 1405 | |
1c49fc19 | 1406 | revision = "" |
b984733c | 1407 | self.users = {} |
b984733c | 1408 | |
6326aa58 HWN |
1409 | newPaths = [] |
1410 | for p in self.depotPaths: | |
1411 | if p.find("@") != -1: | |
1412 | atIdx = p.index("@") | |
1413 | self.changeRange = p[atIdx:] | |
1414 | if self.changeRange == "@all": | |
1415 | self.changeRange = "" | |
6a49f8e2 | 1416 | elif ',' not in self.changeRange: |
1c49fc19 | 1417 | revision = self.changeRange |
6326aa58 | 1418 | self.changeRange = "" |
7fcff9de | 1419 | p = p[:atIdx] |
6326aa58 HWN |
1420 | elif p.find("#") != -1: |
1421 | hashIdx = p.index("#") | |
1c49fc19 | 1422 | revision = p[hashIdx:] |
7fcff9de | 1423 | p = p[:hashIdx] |
6326aa58 | 1424 | elif self.previousDepotPaths == []: |
1c49fc19 | 1425 | revision = "#head" |
6326aa58 HWN |
1426 | |
1427 | p = re.sub ("\.\.\.$", "", p) | |
1428 | if not p.endswith("/"): | |
1429 | p += "/" | |
1430 | ||
1431 | newPaths.append(p) | |
1432 | ||
1433 | self.depotPaths = newPaths | |
1434 | ||
b984733c | 1435 | |
b607e71e | 1436 | self.loadUserMapFromCache() |
cb53e1f8 SH |
1437 | self.labels = {} |
1438 | if self.detectLabels: | |
1439 | self.getLabels(); | |
b984733c | 1440 | |
4b97ffb1 | 1441 | if self.detectBranches: |
df450923 SH |
1442 | ## FIXME - what's a P4 projectName ? |
1443 | self.projectName = self.guessProjectName() | |
1444 | ||
1445 | if not self.hasOrigin: | |
1446 | self.getBranchMapping(); | |
29bdbac1 SH |
1447 | if self.verbose: |
1448 | print "p4-git branches: %s" % self.p4BranchesInGit | |
1449 | print "initial parents: %s" % self.initialParents | |
1450 | for b in self.p4BranchesInGit: | |
1451 | if b != "master": | |
6326aa58 HWN |
1452 | |
1453 | ## FIXME | |
29bdbac1 SH |
1454 | b = b[len(self.projectName):] |
1455 | self.createdBranches.add(b) | |
4b97ffb1 | 1456 | |
f291b4e3 | 1457 | self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60)) |
b984733c | 1458 | |
cebdf5af | 1459 | importProcess = subprocess.Popen(["git", "fast-import"], |
6326aa58 HWN |
1460 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
1461 | stderr=subprocess.PIPE); | |
08483580 SH |
1462 | self.gitOutput = importProcess.stdout |
1463 | self.gitStream = importProcess.stdin | |
1464 | self.gitError = importProcess.stderr | |
b984733c | 1465 | |
1c49fc19 | 1466 | if revision: |
c208a243 | 1467 | self.importHeadRevision(revision) |
b984733c SH |
1468 | else: |
1469 | changes = [] | |
1470 | ||
0828ab14 | 1471 | if len(self.changesFile) > 0: |
b984733c SH |
1472 | output = open(self.changesFile).readlines() |
1473 | changeSet = Set() | |
1474 | for line in output: | |
1475 | changeSet.add(int(line)) | |
1476 | ||
1477 | for change in changeSet: | |
1478 | changes.append(change) | |
1479 | ||
1480 | changes.sort() | |
1481 | else: | |
29bdbac1 | 1482 | if self.verbose: |
86dff6b6 | 1483 | print "Getting p4 changes for %s...%s" % (', '.join(self.depotPaths), |
6326aa58 | 1484 | self.changeRange) |
4f6432d8 | 1485 | changes = p4ChangesForPaths(self.depotPaths, self.changeRange) |
b984733c | 1486 | |
01a9c9c5 | 1487 | if len(self.maxChanges) > 0: |
7fcff9de | 1488 | changes = changes[:min(int(self.maxChanges), len(changes))] |
01a9c9c5 | 1489 | |
b984733c | 1490 | if len(changes) == 0: |
0828ab14 | 1491 | if not self.silent: |
341dc1c1 | 1492 | print "No changes to import!" |
1f52af6c | 1493 | return True |
b984733c | 1494 | |
a9d1a27a SH |
1495 | if not self.silent and not self.detectBranches: |
1496 | print "Import destination: %s" % self.branch | |
1497 | ||
341dc1c1 SH |
1498 | self.updatedBranches = set() |
1499 | ||
e87f37ae | 1500 | self.importChanges(changes) |
b984733c | 1501 | |
341dc1c1 SH |
1502 | if not self.silent: |
1503 | print "" | |
1504 | if len(self.updatedBranches) > 0: | |
1505 | sys.stdout.write("Updated branches: ") | |
1506 | for b in self.updatedBranches: | |
1507 | sys.stdout.write("%s " % b) | |
1508 | sys.stdout.write("\n") | |
b984733c | 1509 | |
b984733c | 1510 | self.gitStream.close() |
29bdbac1 SH |
1511 | if importProcess.wait() != 0: |
1512 | die("fast-import failed: %s" % self.gitError.read()) | |
b984733c SH |
1513 | self.gitOutput.close() |
1514 | self.gitError.close() | |
1515 | ||
b984733c SH |
1516 | return True |
1517 | ||
01ce1fe9 SH |
1518 | class P4Rebase(Command): |
1519 | def __init__(self): | |
1520 | Command.__init__(self) | |
01265103 | 1521 | self.options = [ ] |
cebdf5af HWN |
1522 | self.description = ("Fetches the latest revision from perforce and " |
1523 | + "rebases the current work (branch) against it") | |
68c42153 | 1524 | self.verbose = False |
01ce1fe9 SH |
1525 | |
1526 | def run(self, args): | |
1527 | sync = P4Sync() | |
1528 | sync.run([]) | |
d7e3868c | 1529 | |
14594f4b SH |
1530 | return self.rebase() |
1531 | ||
1532 | def rebase(self): | |
d7e3868c SH |
1533 | [upstream, settings] = findUpstreamBranchPoint() |
1534 | if len(upstream) == 0: | |
1535 | die("Cannot find upstream branchpoint for rebase") | |
1536 | ||
1537 | # the branchpoint may be p4/foo~3, so strip off the parent | |
1538 | upstream = re.sub("~[0-9]+$", "", upstream) | |
1539 | ||
1540 | print "Rebasing the current branch onto %s" % upstream | |
b25b2065 | 1541 | oldHead = read_pipe("git rev-parse HEAD").strip() |
d7e3868c | 1542 | system("git rebase %s" % upstream) |
1f52af6c | 1543 | system("git diff-tree --stat --summary -M %s HEAD" % oldHead) |
01ce1fe9 SH |
1544 | return True |
1545 | ||
f9a3a4f7 SH |
1546 | class P4Clone(P4Sync): |
1547 | def __init__(self): | |
1548 | P4Sync.__init__(self) | |
1549 | self.description = "Creates a new git repository and imports from Perforce into it" | |
bb6e09b2 HWN |
1550 | self.usage = "usage: %prog [options] //depot/path[@revRange]" |
1551 | self.options.append( | |
1552 | optparse.make_option("--destination", dest="cloneDestination", | |
1553 | action='store', default=None, | |
1554 | help="where to leave result of the clone")) | |
1555 | self.cloneDestination = None | |
f9a3a4f7 | 1556 | self.needsGit = False |
f9a3a4f7 | 1557 | |
6a49f8e2 HWN |
1558 | def defaultDestination(self, args): |
1559 | ## TODO: use common prefix of args? | |
1560 | depotPath = args[0] | |
1561 | depotDir = re.sub("(@[^@]*)$", "", depotPath) | |
1562 | depotDir = re.sub("(#[^#]*)$", "", depotDir) | |
1563 | depotDir = re.sub(r"\.\.\.$,", "", depotDir) | |
1564 | depotDir = re.sub(r"/$", "", depotDir) | |
1565 | return os.path.split(depotDir)[1] | |
1566 | ||
f9a3a4f7 SH |
1567 | def run(self, args): |
1568 | if len(args) < 1: | |
1569 | return False | |
bb6e09b2 HWN |
1570 | |
1571 | if self.keepRepoPath and not self.cloneDestination: | |
1572 | sys.stderr.write("Must specify destination for --keep-path\n") | |
1573 | sys.exit(1) | |
f9a3a4f7 | 1574 | |
6326aa58 | 1575 | depotPaths = args |
5e100b5c SH |
1576 | |
1577 | if not self.cloneDestination and len(depotPaths) > 1: | |
1578 | self.cloneDestination = depotPaths[-1] | |
1579 | depotPaths = depotPaths[:-1] | |
1580 | ||
6326aa58 HWN |
1581 | for p in depotPaths: |
1582 | if not p.startswith("//"): | |
1583 | return False | |
f9a3a4f7 | 1584 | |
bb6e09b2 | 1585 | if not self.cloneDestination: |
98ad4faf | 1586 | self.cloneDestination = self.defaultDestination(args) |
f9a3a4f7 | 1587 | |
86dff6b6 | 1588 | print "Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination) |
c3bf3f13 KG |
1589 | if not os.path.exists(self.cloneDestination): |
1590 | os.makedirs(self.cloneDestination) | |
bb6e09b2 | 1591 | os.chdir(self.cloneDestination) |
f9a3a4f7 | 1592 | system("git init") |
b86f7378 | 1593 | self.gitdir = os.getcwd() + "/.git" |
6326aa58 | 1594 | if not P4Sync.run(self, depotPaths): |
f9a3a4f7 | 1595 | return False |
f9a3a4f7 | 1596 | if self.branch != "master": |
8f9b2e08 SH |
1597 | if gitBranchExists("refs/remotes/p4/master"): |
1598 | system("git branch master refs/remotes/p4/master") | |
1599 | system("git checkout -f") | |
1600 | else: | |
1601 | print "Could not detect main branch. No checkout/master branch created." | |
86dff6b6 | 1602 | |
f9a3a4f7 SH |
1603 | return True |
1604 | ||
09d89de2 SH |
1605 | class P4Branches(Command): |
1606 | def __init__(self): | |
1607 | Command.__init__(self) | |
1608 | self.options = [ ] | |
1609 | self.description = ("Shows the git branches that hold imports and their " | |
1610 | + "corresponding perforce depot paths") | |
1611 | self.verbose = False | |
1612 | ||
1613 | def run(self, args): | |
5ca44617 SH |
1614 | if originP4BranchesExist(): |
1615 | createOrUpdateBranchesFromOrigin() | |
1616 | ||
09d89de2 SH |
1617 | cmdline = "git rev-parse --symbolic " |
1618 | cmdline += " --remotes" | |
1619 | ||
1620 | for line in read_pipe_lines(cmdline): | |
1621 | line = line.strip() | |
1622 | ||
1623 | if not line.startswith('p4/') or line == "p4/HEAD": | |
1624 | continue | |
1625 | branch = line | |
1626 | ||
1627 | log = extractLogMessageFromGitCommit("refs/remotes/%s" % branch) | |
1628 | settings = extractSettingsGitLog(log) | |
1629 | ||
1630 | print "%s <= %s (%s)" % (branch, ",".join(settings["depot-paths"]), settings["change"]) | |
1631 | return True | |
1632 | ||
b984733c SH |
1633 | class HelpFormatter(optparse.IndentedHelpFormatter): |
1634 | def __init__(self): | |
1635 | optparse.IndentedHelpFormatter.__init__(self) | |
1636 | ||
1637 | def format_description(self, description): | |
1638 | if description: | |
1639 | return description + "\n" | |
1640 | else: | |
1641 | return "" | |
4f5cf76a | 1642 | |
86949eef SH |
1643 | def printUsage(commands): |
1644 | print "usage: %s <command> [options]" % sys.argv[0] | |
1645 | print "" | |
1646 | print "valid commands: %s" % ", ".join(commands) | |
1647 | print "" | |
1648 | print "Try %s <command> --help for command specific help." % sys.argv[0] | |
1649 | print "" | |
1650 | ||
1651 | commands = { | |
b86f7378 HWN |
1652 | "debug" : P4Debug, |
1653 | "submit" : P4Submit, | |
1654 | "sync" : P4Sync, | |
1655 | "rebase" : P4Rebase, | |
1656 | "clone" : P4Clone, | |
09d89de2 SH |
1657 | "rollback" : P4RollBack, |
1658 | "branches" : P4Branches | |
86949eef SH |
1659 | } |
1660 | ||
86949eef | 1661 | |
bb6e09b2 HWN |
1662 | def main(): |
1663 | if len(sys.argv[1:]) == 0: | |
1664 | printUsage(commands.keys()) | |
1665 | sys.exit(2) | |
4f5cf76a | 1666 | |
bb6e09b2 HWN |
1667 | cmd = "" |
1668 | cmdName = sys.argv[1] | |
1669 | try: | |
b86f7378 HWN |
1670 | klass = commands[cmdName] |
1671 | cmd = klass() | |
bb6e09b2 HWN |
1672 | except KeyError: |
1673 | print "unknown command %s" % cmdName | |
1674 | print "" | |
1675 | printUsage(commands.keys()) | |
1676 | sys.exit(2) | |
1677 | ||
1678 | options = cmd.options | |
b86f7378 | 1679 | cmd.gitdir = os.environ.get("GIT_DIR", None) |
bb6e09b2 HWN |
1680 | |
1681 | args = sys.argv[2:] | |
1682 | ||
1683 | if len(options) > 0: | |
1684 | options.append(optparse.make_option("--git-dir", dest="gitdir")) | |
1685 | ||
1686 | parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName), | |
1687 | options, | |
1688 | description = cmd.description, | |
1689 | formatter = HelpFormatter()) | |
1690 | ||
1691 | (cmd, args) = parser.parse_args(sys.argv[2:], cmd); | |
1692 | global verbose | |
1693 | verbose = cmd.verbose | |
1694 | if cmd.needsGit: | |
b86f7378 HWN |
1695 | if cmd.gitdir == None: |
1696 | cmd.gitdir = os.path.abspath(".git") | |
1697 | if not isValidGitDir(cmd.gitdir): | |
1698 | cmd.gitdir = read_pipe("git rev-parse --git-dir").strip() | |
1699 | if os.path.exists(cmd.gitdir): | |
bb6e09b2 HWN |
1700 | cdup = read_pipe("git rev-parse --show-cdup").strip() |
1701 | if len(cdup) > 0: | |
1702 | os.chdir(cdup); | |
e20a9e53 | 1703 | |
b86f7378 HWN |
1704 | if not isValidGitDir(cmd.gitdir): |
1705 | if isValidGitDir(cmd.gitdir + "/.git"): | |
1706 | cmd.gitdir += "/.git" | |
bb6e09b2 | 1707 | else: |
b86f7378 | 1708 | die("fatal: cannot locate git repository at %s" % cmd.gitdir) |
e20a9e53 | 1709 | |
b86f7378 | 1710 | os.environ["GIT_DIR"] = cmd.gitdir |
86949eef | 1711 | |
bb6e09b2 HWN |
1712 | if not cmd.run(args): |
1713 | parser.print_help() | |
4f5cf76a | 1714 | |
4f5cf76a | 1715 | |
bb6e09b2 HWN |
1716 | if __name__ == '__main__': |
1717 | main() |