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