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