OLD | NEW |
(Empty) | |
| 1 #!/usr/bin/python |
| 2 # git-cl -- a git-command for integrating reviews on Rietveld |
| 3 # Copyright (C) 2008 Evan Martin <martine@danga.com> |
| 4 |
| 5 import errno |
| 6 import logging |
| 7 import optparse |
| 8 import os |
| 9 import re |
| 10 import subprocess |
| 11 import sys |
| 12 import tempfile |
| 13 import textwrap |
| 14 import upload |
| 15 import urllib2 |
| 16 |
| 17 try: |
| 18 import readline |
| 19 except ImportError: |
| 20 pass |
| 21 |
| 22 try: |
| 23 # Add the parent directory in case it's a depot_tools checkout. |
| 24 depot_tools_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 25 sys.path.append(depot_tools_path) |
| 26 import breakpad |
| 27 except ImportError: |
| 28 pass |
| 29 |
| 30 DEFAULT_SERVER = 'http://codereview.appspot.com' |
| 31 PREDCOMMIT_HOOK = '.git/hooks/pre-cl-dcommit' |
| 32 PREUPLOAD_HOOK = '.git/hooks/pre-cl-upload' |
| 33 DESCRIPTION_BACKUP_FILE = '~/.git_cl_description_backup' |
| 34 |
| 35 def DieWithError(message): |
| 36 print >>sys.stderr, message |
| 37 sys.exit(1) |
| 38 |
| 39 |
| 40 def Popen(cmd, **kwargs): |
| 41 """Wrapper for subprocess.Popen() that logs and watch for cygwin issues""" |
| 42 logging.info('Popen: ' + ' '.join(cmd)) |
| 43 try: |
| 44 return subprocess.Popen(cmd, **kwargs) |
| 45 except OSError, e: |
| 46 if e.errno == errno.EAGAIN and sys.platform == 'cygwin': |
| 47 DieWithError( |
| 48 'Visit ' |
| 49 'http://code.google.com/p/chromium/wiki/CygwinDllRemappingFailure to ' |
| 50 'learn how to fix this error; you need to rebase your cygwin dlls') |
| 51 raise |
| 52 |
| 53 |
| 54 def RunCommand(cmd, error_ok=False, error_message=None, |
| 55 redirect_stdout=True, swallow_stderr=False): |
| 56 if redirect_stdout: |
| 57 stdout = subprocess.PIPE |
| 58 else: |
| 59 stdout = None |
| 60 if swallow_stderr: |
| 61 stderr = subprocess.PIPE |
| 62 else: |
| 63 stderr = None |
| 64 proc = Popen(cmd, stdout=stdout, stderr=stderr) |
| 65 output = proc.communicate()[0] |
| 66 if not error_ok and proc.returncode != 0: |
| 67 DieWithError('Command "%s" failed.\n' % (' '.join(cmd)) + |
| 68 (error_message or output or '')) |
| 69 return output |
| 70 |
| 71 |
| 72 def RunGit(args, **kwargs): |
| 73 cmd = ['git'] + args |
| 74 return RunCommand(cmd, **kwargs) |
| 75 |
| 76 |
| 77 def RunGitWithCode(args): |
| 78 proc = Popen(['git'] + args, stdout=subprocess.PIPE) |
| 79 output = proc.communicate()[0] |
| 80 return proc.returncode, output |
| 81 |
| 82 |
| 83 def usage(more): |
| 84 def hook(fn): |
| 85 fn.usage_more = more |
| 86 return fn |
| 87 return hook |
| 88 |
| 89 |
| 90 def FixUrl(server): |
| 91 """Fix a server url to defaults protocol to http:// if none is specified.""" |
| 92 if not server: |
| 93 return server |
| 94 if not re.match(r'[a-z]+\://.*', server): |
| 95 return 'http://' + server |
| 96 return server |
| 97 |
| 98 |
| 99 class Settings(object): |
| 100 def __init__(self): |
| 101 self.default_server = None |
| 102 self.cc = None |
| 103 self.root = None |
| 104 self.is_git_svn = None |
| 105 self.svn_branch = None |
| 106 self.tree_status_url = None |
| 107 self.viewvc_url = None |
| 108 self.updated = False |
| 109 |
| 110 def LazyUpdateIfNeeded(self): |
| 111 """Updates the settings from a codereview.settings file, if available.""" |
| 112 if not self.updated: |
| 113 cr_settings_file = FindCodereviewSettingsFile() |
| 114 if cr_settings_file: |
| 115 LoadCodereviewSettingsFromFile(cr_settings_file) |
| 116 self.updated = True |
| 117 |
| 118 def GetDefaultServerUrl(self, error_ok=False): |
| 119 if not self.default_server: |
| 120 self.LazyUpdateIfNeeded() |
| 121 self.default_server = FixUrl(self._GetConfig('rietveld.server', |
| 122 error_ok=True)) |
| 123 if error_ok: |
| 124 return self.default_server |
| 125 if not self.default_server: |
| 126 error_message = ('Could not find settings file. You must configure ' |
| 127 'your review setup by running "git cl config".') |
| 128 self.default_server = FixUrl(self._GetConfig( |
| 129 'rietveld.server', error_message=error_message)) |
| 130 return self.default_server |
| 131 |
| 132 def GetCCList(self): |
| 133 """Return the users cc'd on this CL. |
| 134 |
| 135 Return is a string suitable for passing to gcl with the --cc flag. |
| 136 """ |
| 137 if self.cc is None: |
| 138 self.cc = self._GetConfig('rietveld.cc', error_ok=True) |
| 139 more_cc = self._GetConfig('rietveld.extracc', error_ok=True) |
| 140 if more_cc is not None: |
| 141 self.cc += ',' + more_cc |
| 142 return self.cc |
| 143 |
| 144 def GetRoot(self): |
| 145 if not self.root: |
| 146 self.root = os.path.abspath(RunGit(['rev-parse', '--show-cdup']).strip()) |
| 147 return self.root |
| 148 |
| 149 def GetIsGitSvn(self): |
| 150 """Return true if this repo looks like it's using git-svn.""" |
| 151 if self.is_git_svn is None: |
| 152 # If you have any "svn-remote.*" config keys, we think you're using svn. |
| 153 self.is_git_svn = RunGitWithCode( |
| 154 ['config', '--get-regexp', r'^svn-remote\.'])[0] == 0 |
| 155 return self.is_git_svn |
| 156 |
| 157 def GetSVNBranch(self): |
| 158 if self.svn_branch is None: |
| 159 if not self.GetIsGitSvn(): |
| 160 DieWithError('Repo doesn\'t appear to be a git-svn repo.') |
| 161 |
| 162 # Try to figure out which remote branch we're based on. |
| 163 # Strategy: |
| 164 # 1) find all git-svn branches and note their svn URLs. |
| 165 # 2) iterate through our branch history and match up the URLs. |
| 166 |
| 167 # regexp matching the git-svn line that contains the URL. |
| 168 git_svn_re = re.compile(r'^\s*git-svn-id: (\S+)@', re.MULTILINE) |
| 169 |
| 170 # Get the refname and svn url for all refs/remotes/*. |
| 171 remotes = RunGit(['for-each-ref', '--format=%(refname)', |
| 172 'refs/remotes']).splitlines() |
| 173 svn_refs = {} |
| 174 for ref in remotes: |
| 175 match = git_svn_re.search(RunGit(['cat-file', '-p', ref])) |
| 176 # Prefer origin/HEAD over all others. |
| 177 if match and (match.group(1) not in svn_refs or |
| 178 ref == "refs/remotes/origin/HEAD"): |
| 179 svn_refs[match.group(1)] = ref |
| 180 |
| 181 if len(svn_refs) == 1: |
| 182 # Only one svn branch exists -- seems like a good candidate. |
| 183 self.svn_branch = svn_refs.values()[0] |
| 184 elif len(svn_refs) > 1: |
| 185 # We have more than one remote branch available. We don't |
| 186 # want to go through all of history, so read a line from the |
| 187 # pipe at a time. |
| 188 # The -100 is an arbitrary limit so we don't search forever. |
| 189 cmd = ['git', 'log', '-100', '--pretty=medium'] |
| 190 proc = Popen(cmd, stdout=subprocess.PIPE) |
| 191 for line in proc.stdout: |
| 192 match = git_svn_re.match(line) |
| 193 if match: |
| 194 url = match.group(1) |
| 195 if url in svn_refs: |
| 196 self.svn_branch = svn_refs[url] |
| 197 proc.stdout.close() # Cut pipe. |
| 198 break |
| 199 |
| 200 if not self.svn_branch: |
| 201 DieWithError('Can\'t guess svn branch -- try specifying it on the ' |
| 202 'command line') |
| 203 |
| 204 return self.svn_branch |
| 205 |
| 206 def GetTreeStatusUrl(self, error_ok=False): |
| 207 if not self.tree_status_url: |
| 208 error_message = ('You must configure your tree status URL by running ' |
| 209 '"git cl config".') |
| 210 self.tree_status_url = self._GetConfig('rietveld.tree-status-url', |
| 211 error_ok=error_ok, |
| 212 error_message=error_message) |
| 213 return self.tree_status_url |
| 214 |
| 215 def GetViewVCUrl(self): |
| 216 if not self.viewvc_url: |
| 217 self.viewvc_url = self._GetConfig('rietveld.viewvc-url', error_ok=True) |
| 218 return self.viewvc_url |
| 219 |
| 220 def _GetConfig(self, param, **kwargs): |
| 221 self.LazyUpdateIfNeeded() |
| 222 return RunGit(['config', param], **kwargs).strip() |
| 223 |
| 224 |
| 225 settings = Settings() |
| 226 |
| 227 |
| 228 did_migrate_check = False |
| 229 def CheckForMigration(): |
| 230 """Migrate from the old issue format, if found. |
| 231 |
| 232 We used to store the branch<->issue mapping in a file in .git, but it's |
| 233 better to store it in the .git/config, since deleting a branch deletes that |
| 234 branch's entry there. |
| 235 """ |
| 236 |
| 237 # Don't run more than once. |
| 238 global did_migrate_check |
| 239 if did_migrate_check: |
| 240 return |
| 241 |
| 242 gitdir = RunGit(['rev-parse', '--git-dir']).strip() |
| 243 storepath = os.path.join(gitdir, 'cl-mapping') |
| 244 if os.path.exists(storepath): |
| 245 print "old-style git-cl mapping file (%s) found; migrating." % storepath |
| 246 store = open(storepath, 'r') |
| 247 for line in store: |
| 248 branch, issue = line.strip().split() |
| 249 RunGit(['config', 'branch.%s.rietveldissue' % ShortBranchName(branch), |
| 250 issue]) |
| 251 store.close() |
| 252 os.remove(storepath) |
| 253 did_migrate_check = True |
| 254 |
| 255 |
| 256 def ShortBranchName(branch): |
| 257 """Convert a name like 'refs/heads/foo' to just 'foo'.""" |
| 258 return branch.replace('refs/heads/', '') |
| 259 |
| 260 |
| 261 class Changelist(object): |
| 262 def __init__(self, branchref=None): |
| 263 # Poke settings so we get the "configure your server" message if necessary. |
| 264 settings.GetDefaultServerUrl() |
| 265 self.branchref = branchref |
| 266 if self.branchref: |
| 267 self.branch = ShortBranchName(self.branchref) |
| 268 else: |
| 269 self.branch = None |
| 270 self.rietveld_server = None |
| 271 self.upstream_branch = None |
| 272 self.has_issue = False |
| 273 self.issue = None |
| 274 self.has_description = False |
| 275 self.description = None |
| 276 self.has_patchset = False |
| 277 self.patchset = None |
| 278 |
| 279 def GetBranch(self): |
| 280 """Returns the short branch name, e.g. 'master'.""" |
| 281 if not self.branch: |
| 282 self.branchref = RunGit(['symbolic-ref', 'HEAD']).strip() |
| 283 self.branch = ShortBranchName(self.branchref) |
| 284 return self.branch |
| 285 |
| 286 def GetBranchRef(self): |
| 287 """Returns the full branch name, e.g. 'refs/heads/master'.""" |
| 288 self.GetBranch() # Poke the lazy loader. |
| 289 return self.branchref |
| 290 |
| 291 def FetchUpstreamTuple(self): |
| 292 """Returns a tuple containg remote and remote ref, |
| 293 e.g. 'origin', 'refs/heads/master' |
| 294 """ |
| 295 remote = '.' |
| 296 branch = self.GetBranch() |
| 297 upstream_branch = RunGit(['config', 'branch.%s.merge' % branch], |
| 298 error_ok=True).strip() |
| 299 if upstream_branch: |
| 300 remote = RunGit(['config', 'branch.%s.remote' % branch]).strip() |
| 301 else: |
| 302 # Fall back on trying a git-svn upstream branch. |
| 303 if settings.GetIsGitSvn(): |
| 304 upstream_branch = settings.GetSVNBranch() |
| 305 else: |
| 306 # Else, try to guess the origin remote. |
| 307 remote_branches = RunGit(['branch', '-r']).split() |
| 308 if 'origin/master' in remote_branches: |
| 309 # Fall back on origin/master if it exits. |
| 310 remote = 'origin' |
| 311 upstream_branch = 'refs/heads/master' |
| 312 elif 'origin/trunk' in remote_branches: |
| 313 # Fall back on origin/trunk if it exists. Generally a shared |
| 314 # git-svn clone |
| 315 remote = 'origin' |
| 316 upstream_branch = 'refs/heads/trunk' |
| 317 else: |
| 318 DieWithError("""Unable to determine default branch to diff against. |
| 319 Either pass complete "git diff"-style arguments, like |
| 320 git cl upload origin/master |
| 321 or verify this branch is set up to track another (via the --track argument to |
| 322 "git checkout -b ...").""") |
| 323 |
| 324 return remote, upstream_branch |
| 325 |
| 326 def GetUpstreamBranch(self): |
| 327 if self.upstream_branch is None: |
| 328 remote, upstream_branch = self.FetchUpstreamTuple() |
| 329 if remote is not '.': |
| 330 upstream_branch = upstream_branch.replace('heads', 'remotes/' + remote) |
| 331 self.upstream_branch = upstream_branch |
| 332 return self.upstream_branch |
| 333 |
| 334 def GetRemoteUrl(self): |
| 335 """Return the configured remote URL, e.g. 'git://example.org/foo.git/'. |
| 336 |
| 337 Returns None if there is no remote. |
| 338 """ |
| 339 remote = self.FetchUpstreamTuple()[0] |
| 340 if remote == '.': |
| 341 return None |
| 342 return RunGit(['config', 'remote.%s.url' % remote], error_ok=True).strip() |
| 343 |
| 344 def GetIssue(self): |
| 345 if not self.has_issue: |
| 346 CheckForMigration() |
| 347 issue = RunGit(['config', self._IssueSetting()], error_ok=True).strip() |
| 348 if issue: |
| 349 self.issue = issue |
| 350 self.rietveld_server = FixUrl(RunGit( |
| 351 ['config', self._RietveldServer()], error_ok=True).strip()) |
| 352 else: |
| 353 self.issue = None |
| 354 if not self.rietveld_server: |
| 355 self.rietveld_server = settings.GetDefaultServerUrl() |
| 356 self.has_issue = True |
| 357 return self.issue |
| 358 |
| 359 def GetRietveldServer(self): |
| 360 self.GetIssue() |
| 361 return self.rietveld_server |
| 362 |
| 363 def GetIssueURL(self): |
| 364 """Get the URL for a particular issue.""" |
| 365 return '%s/%s' % (self.GetRietveldServer(), self.GetIssue()) |
| 366 |
| 367 def GetDescription(self, pretty=False): |
| 368 if not self.has_description: |
| 369 if self.GetIssue(): |
| 370 path = '/' + self.GetIssue() + '/description' |
| 371 rpc_server = self._RpcServer() |
| 372 self.description = rpc_server.Send(path).strip() |
| 373 self.has_description = True |
| 374 if pretty: |
| 375 wrapper = textwrap.TextWrapper() |
| 376 wrapper.initial_indent = wrapper.subsequent_indent = ' ' |
| 377 return wrapper.fill(self.description) |
| 378 return self.description |
| 379 |
| 380 def GetPatchset(self): |
| 381 if not self.has_patchset: |
| 382 patchset = RunGit(['config', self._PatchsetSetting()], |
| 383 error_ok=True).strip() |
| 384 if patchset: |
| 385 self.patchset = patchset |
| 386 else: |
| 387 self.patchset = None |
| 388 self.has_patchset = True |
| 389 return self.patchset |
| 390 |
| 391 def SetPatchset(self, patchset): |
| 392 """Set this branch's patchset. If patchset=0, clears the patchset.""" |
| 393 if patchset: |
| 394 RunGit(['config', self._PatchsetSetting(), str(patchset)]) |
| 395 else: |
| 396 RunGit(['config', '--unset', self._PatchsetSetting()], |
| 397 swallow_stderr=True, error_ok=True) |
| 398 self.has_patchset = False |
| 399 |
| 400 def SetIssue(self, issue): |
| 401 """Set this branch's issue. If issue=0, clears the issue.""" |
| 402 if issue: |
| 403 RunGit(['config', self._IssueSetting(), str(issue)]) |
| 404 if self.rietveld_server: |
| 405 RunGit(['config', self._RietveldServer(), self.rietveld_server]) |
| 406 else: |
| 407 RunGit(['config', '--unset', self._IssueSetting()]) |
| 408 self.SetPatchset(0) |
| 409 self.has_issue = False |
| 410 |
| 411 def CloseIssue(self): |
| 412 rpc_server = self._RpcServer() |
| 413 # Newer versions of Rietveld require us to pass an XSRF token to POST, so |
| 414 # we fetch it from the server. (The version used by Chromium has been |
| 415 # modified so the token isn't required when closing an issue.) |
| 416 xsrf_token = rpc_server.Send('/xsrf_token', |
| 417 extra_headers={'X-Requesting-XSRF-Token': '1'}) |
| 418 |
| 419 # You cannot close an issue with a GET. |
| 420 # We pass an empty string for the data so it is a POST rather than a GET. |
| 421 data = [("description", self.description), |
| 422 ("xsrf_token", xsrf_token)] |
| 423 ctype, body = upload.EncodeMultipartFormData(data, []) |
| 424 rpc_server.Send('/' + self.GetIssue() + '/close', body, ctype) |
| 425 |
| 426 def _RpcServer(self): |
| 427 """Returns an upload.RpcServer() to access this review's rietveld instance. |
| 428 """ |
| 429 server = self.GetRietveldServer() |
| 430 return upload.GetRpcServer(server, save_cookies=True) |
| 431 |
| 432 def _IssueSetting(self): |
| 433 """Return the git setting that stores this change's issue.""" |
| 434 return 'branch.%s.rietveldissue' % self.GetBranch() |
| 435 |
| 436 def _PatchsetSetting(self): |
| 437 """Return the git setting that stores this change's most recent patchset.""" |
| 438 return 'branch.%s.rietveldpatchset' % self.GetBranch() |
| 439 |
| 440 def _RietveldServer(self): |
| 441 """Returns the git setting that stores this change's rietveld server.""" |
| 442 return 'branch.%s.rietveldserver' % self.GetBranch() |
| 443 |
| 444 |
| 445 def GetCodereviewSettingsInteractively(): |
| 446 """Prompt the user for settings.""" |
| 447 server = settings.GetDefaultServerUrl(error_ok=True) |
| 448 prompt = 'Rietveld server (host[:port])' |
| 449 prompt += ' [%s]' % (server or DEFAULT_SERVER) |
| 450 newserver = raw_input(prompt + ': ') |
| 451 if not server and not newserver: |
| 452 newserver = DEFAULT_SERVER |
| 453 if newserver and newserver != server: |
| 454 RunGit(['config', 'rietveld.server', newserver]) |
| 455 |
| 456 def SetProperty(initial, caption, name): |
| 457 prompt = caption |
| 458 if initial: |
| 459 prompt += ' ("x" to clear) [%s]' % initial |
| 460 new_val = raw_input(prompt + ': ') |
| 461 if new_val == 'x': |
| 462 RunGit(['config', '--unset-all', 'rietveld.' + name], error_ok=True) |
| 463 elif new_val and new_val != initial: |
| 464 RunGit(['config', 'rietveld.' + name, new_val]) |
| 465 |
| 466 SetProperty(settings.GetCCList(), 'CC list', 'cc') |
| 467 SetProperty(settings.GetTreeStatusUrl(error_ok=True), 'Tree status URL', |
| 468 'tree-status-url') |
| 469 SetProperty(settings.GetViewVCUrl(), 'ViewVC URL', 'viewvc-url') |
| 470 |
| 471 # TODO: configure a default branch to diff against, rather than this |
| 472 # svn-based hackery. |
| 473 |
| 474 |
| 475 def FindCodereviewSettingsFile(filename='codereview.settings'): |
| 476 """Finds the given file starting in the cwd and going up. |
| 477 |
| 478 Only looks up to the top of the repository unless an |
| 479 'inherit-review-settings-ok' file exists in the root of the repository. |
| 480 """ |
| 481 inherit_ok_file = 'inherit-review-settings-ok' |
| 482 cwd = os.getcwd() |
| 483 root = os.path.abspath(RunGit(['rev-parse', '--show-cdup']).strip()) |
| 484 if os.path.isfile(os.path.join(root, inherit_ok_file)): |
| 485 root = '/' |
| 486 while True: |
| 487 if filename in os.listdir(cwd): |
| 488 if os.path.isfile(os.path.join(cwd, filename)): |
| 489 return open(os.path.join(cwd, filename)) |
| 490 if cwd == root: |
| 491 break |
| 492 cwd = os.path.dirname(cwd) |
| 493 |
| 494 |
| 495 def LoadCodereviewSettingsFromFile(fileobj): |
| 496 """Parse a codereview.settings file and updates hooks.""" |
| 497 def DownloadToFile(url, filename): |
| 498 filename = os.path.join(settings.GetRoot(), filename) |
| 499 contents = urllib2.urlopen(url).read() |
| 500 fileobj = open(filename, 'w') |
| 501 fileobj.write(contents) |
| 502 fileobj.close() |
| 503 os.chmod(filename, 0755) |
| 504 return 0 |
| 505 |
| 506 keyvals = {} |
| 507 for line in fileobj.read().splitlines(): |
| 508 if not line or line.startswith("#"): |
| 509 continue |
| 510 k, v = line.split(": ", 1) |
| 511 keyvals[k] = v |
| 512 |
| 513 def GetProperty(name): |
| 514 return keyvals.get(name) |
| 515 |
| 516 def SetProperty(name, setting, unset_error_ok=False): |
| 517 fullname = 'rietveld.' + name |
| 518 if setting in keyvals: |
| 519 RunGit(['config', fullname, keyvals[setting]]) |
| 520 else: |
| 521 RunGit(['config', '--unset-all', fullname], error_ok=unset_error_ok) |
| 522 |
| 523 SetProperty('server', 'CODE_REVIEW_SERVER') |
| 524 # Only server setting is required. Other settings can be absent. |
| 525 # In that case, we ignore errors raised during option deletion attempt. |
| 526 SetProperty('cc', 'CC_LIST', unset_error_ok=True) |
| 527 SetProperty('tree-status-url', 'STATUS', unset_error_ok=True) |
| 528 SetProperty('viewvc-url', 'VIEW_VC', unset_error_ok=True) |
| 529 |
| 530 if 'PUSH_URL_CONFIG' in keyvals and 'ORIGIN_URL_CONFIG' in keyvals: |
| 531 #should be of the form |
| 532 #PUSH_URL_CONFIG: url.ssh://gitrw.chromium.org.pushinsteadof |
| 533 #ORIGIN_URL_CONFIG: http://src.chromium.org/git |
| 534 RunGit(['config', keyvals['PUSH_URL_CONFIG'], |
| 535 keyvals['ORIGIN_URL_CONFIG']]) |
| 536 |
| 537 # Update the hooks if the local hook files aren't present already. |
| 538 if GetProperty('GITCL_PREUPLOAD') and not os.path.isfile(PREUPLOAD_HOOK): |
| 539 DownloadToFile(GetProperty('GITCL_PREUPLOAD'), PREUPLOAD_HOOK) |
| 540 if GetProperty('GITCL_PREDCOMMIT') and not os.path.isfile(PREDCOMMIT_HOOK): |
| 541 DownloadToFile(GetProperty('GITCL_PREDCOMMIT'), PREDCOMMIT_HOOK) |
| 542 return 0 |
| 543 |
| 544 |
| 545 @usage('[repo root containing codereview.settings]') |
| 546 def CMDconfig(parser, args): |
| 547 """edit configuration for this tree""" |
| 548 |
| 549 (options, args) = parser.parse_args(args) |
| 550 if len(args) == 0: |
| 551 GetCodereviewSettingsInteractively() |
| 552 return 0 |
| 553 |
| 554 url = args[0] |
| 555 if not url.endswith('codereview.settings'): |
| 556 url = os.path.join(url, 'codereview.settings') |
| 557 |
| 558 # Load code review settings and download hooks (if available). |
| 559 LoadCodereviewSettingsFromFile(urllib2.urlopen(url)) |
| 560 return 0 |
| 561 |
| 562 |
| 563 def CMDstatus(parser, args): |
| 564 """show status of changelists""" |
| 565 parser.add_option('--field', |
| 566 help='print only specific field (desc|id|patch|url)') |
| 567 (options, args) = parser.parse_args(args) |
| 568 |
| 569 # TODO: maybe make show_branches a flag if necessary. |
| 570 show_branches = not options.field |
| 571 |
| 572 if show_branches: |
| 573 branches = RunGit(['for-each-ref', '--format=%(refname)', 'refs/heads']) |
| 574 if branches: |
| 575 print 'Branches associated with reviews:' |
| 576 for branch in sorted(branches.splitlines()): |
| 577 cl = Changelist(branchref=branch) |
| 578 print " %10s: %s" % (cl.GetBranch(), cl.GetIssue()) |
| 579 |
| 580 cl = Changelist() |
| 581 if options.field: |
| 582 if options.field.startswith('desc'): |
| 583 print cl.GetDescription() |
| 584 elif options.field == 'id': |
| 585 issueid = cl.GetIssue() |
| 586 if issueid: |
| 587 print issueid |
| 588 elif options.field == 'patch': |
| 589 patchset = cl.GetPatchset() |
| 590 if patchset: |
| 591 print patchset |
| 592 elif options.field == 'url': |
| 593 url = cl.GetIssueURL() |
| 594 if url: |
| 595 print url |
| 596 else: |
| 597 print |
| 598 print 'Current branch:', |
| 599 if not cl.GetIssue(): |
| 600 print 'no issue assigned.' |
| 601 return 0 |
| 602 print cl.GetBranch() |
| 603 print 'Issue number:', cl.GetIssue(), '(%s)' % cl.GetIssueURL() |
| 604 print 'Issue description:' |
| 605 print cl.GetDescription(pretty=True) |
| 606 return 0 |
| 607 |
| 608 |
| 609 @usage('[issue_number]') |
| 610 def CMDissue(parser, args): |
| 611 """Set or display the current code review issue number. |
| 612 |
| 613 Pass issue number 0 to clear the current issue. |
| 614 """ |
| 615 (options, args) = parser.parse_args(args) |
| 616 |
| 617 cl = Changelist() |
| 618 if len(args) > 0: |
| 619 try: |
| 620 issue = int(args[0]) |
| 621 except ValueError: |
| 622 DieWithError('Pass a number to set the issue or none to list it.\n' |
| 623 'Maybe you want to run git cl status?') |
| 624 cl.SetIssue(issue) |
| 625 print 'Issue number:', cl.GetIssue(), '(%s)' % cl.GetIssueURL() |
| 626 return 0 |
| 627 |
| 628 |
| 629 def CreateDescriptionFromLog(args): |
| 630 """Pulls out the commit log to use as a base for the CL description.""" |
| 631 log_args = [] |
| 632 if len(args) == 1 and not args[0].endswith('.'): |
| 633 log_args = [args[0] + '..'] |
| 634 elif len(args) == 1 and args[0].endswith('...'): |
| 635 log_args = [args[0][:-1]] |
| 636 elif len(args) == 2: |
| 637 log_args = [args[0] + '..' + args[1]] |
| 638 else: |
| 639 log_args = args[:] # Hope for the best! |
| 640 return RunGit(['log', '--pretty=format:%s\n\n%b'] + log_args) |
| 641 |
| 642 |
| 643 def UserEditedLog(starting_text): |
| 644 """Given some starting text, let the user edit it and return the result.""" |
| 645 editor = os.getenv('EDITOR', 'vi') |
| 646 |
| 647 (file_handle, filename) = tempfile.mkstemp() |
| 648 fileobj = os.fdopen(file_handle, 'w') |
| 649 fileobj.write(starting_text) |
| 650 fileobj.close() |
| 651 |
| 652 ret = subprocess.call(editor + ' ' + filename, shell=True) |
| 653 if ret != 0: |
| 654 os.remove(filename) |
| 655 return |
| 656 |
| 657 fileobj = open(filename) |
| 658 text = fileobj.read() |
| 659 fileobj.close() |
| 660 os.remove(filename) |
| 661 stripcomment_re = re.compile(r'^#.*$', re.MULTILINE) |
| 662 return stripcomment_re.sub('', text).strip() |
| 663 |
| 664 |
| 665 def RunHook(hook, upstream_branch, error_ok=False): |
| 666 """Run a given hook if it exists. By default, we fail on errors.""" |
| 667 hook = '%s/%s' % (settings.GetRoot(), hook) |
| 668 if not os.path.exists(hook): |
| 669 return |
| 670 return RunCommand([hook, upstream_branch], error_ok=error_ok, |
| 671 redirect_stdout=False) |
| 672 |
| 673 |
| 674 def CMDpresubmit(parser, args): |
| 675 """run presubmit tests on the current changelist""" |
| 676 parser.add_option('--upload', action='store_true', |
| 677 help='Run upload hook instead of the push/dcommit hook') |
| 678 (options, args) = parser.parse_args(args) |
| 679 |
| 680 # Make sure index is up-to-date before running diff-index. |
| 681 RunGit(['update-index', '--refresh', '-q'], error_ok=True) |
| 682 if RunGit(['diff-index', 'HEAD']): |
| 683 # TODO(maruel): Is this really necessary? |
| 684 print 'Cannot presubmit with a dirty tree. You must commit locally first.' |
| 685 return 1 |
| 686 |
| 687 if args: |
| 688 base_branch = args[0] |
| 689 else: |
| 690 # Default to diffing against the "upstream" branch. |
| 691 base_branch = Changelist().GetUpstreamBranch() |
| 692 |
| 693 if options.upload: |
| 694 print '*** Presubmit checks for UPLOAD would report: ***' |
| 695 return not RunHook(PREUPLOAD_HOOK, upstream_branch=base_branch, |
| 696 error_ok=True) |
| 697 else: |
| 698 print '*** Presubmit checks for DCOMMIT would report: ***' |
| 699 return not RunHook(PREDCOMMIT_HOOK, upstream_branch=base_branch, |
| 700 error_ok=True) |
| 701 |
| 702 |
| 703 @usage('[args to "git diff"]') |
| 704 def CMDupload(parser, args): |
| 705 """upload the current changelist to codereview""" |
| 706 parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks', |
| 707 help='bypass upload presubmit hook') |
| 708 parser.add_option('-m', dest='message', help='message for patch') |
| 709 parser.add_option('-r', '--reviewers', |
| 710 help='reviewer email addresses') |
| 711 parser.add_option('--send-mail', action='store_true', |
| 712 help='send email to reviewer immediately') |
| 713 parser.add_option("--emulate_svn_auto_props", action="store_true", |
| 714 dest="emulate_svn_auto_props", |
| 715 help="Emulate Subversion's auto properties feature.") |
| 716 parser.add_option("--desc_from_logs", action="store_true", |
| 717 dest="from_logs", |
| 718 help="""Squashes git commit logs into change description and |
| 719 uses message as subject""") |
| 720 (options, args) = parser.parse_args(args) |
| 721 |
| 722 # Make sure index is up-to-date before running diff-index. |
| 723 RunGit(['update-index', '--refresh', '-q'], error_ok=True) |
| 724 if RunGit(['diff-index', 'HEAD']): |
| 725 print 'Cannot upload with a dirty tree. You must commit locally first.' |
| 726 return 1 |
| 727 |
| 728 cl = Changelist() |
| 729 if args: |
| 730 base_branch = args[0] |
| 731 else: |
| 732 # Default to diffing against the "upstream" branch. |
| 733 base_branch = cl.GetUpstreamBranch() |
| 734 args = [base_branch + "..."] |
| 735 |
| 736 if not options.bypass_hooks: |
| 737 RunHook(PREUPLOAD_HOOK, upstream_branch=base_branch, error_ok=False) |
| 738 |
| 739 # --no-ext-diff is broken in some versions of Git, so try to work around |
| 740 # this by overriding the environment (but there is still a problem if the |
| 741 # git config key "diff.external" is used). |
| 742 env = os.environ.copy() |
| 743 if 'GIT_EXTERNAL_DIFF' in env: |
| 744 del env['GIT_EXTERNAL_DIFF'] |
| 745 subprocess.call(['git', 'diff', '--no-ext-diff', '--stat', '-M'] + args, |
| 746 env=env) |
| 747 |
| 748 upload_args = ['--assume_yes'] # Don't ask about untracked files. |
| 749 upload_args.extend(['--server', cl.GetRietveldServer()]) |
| 750 if options.reviewers: |
| 751 upload_args.extend(['--reviewers', options.reviewers]) |
| 752 upload_args.extend(['--cc', settings.GetCCList()]) |
| 753 if options.emulate_svn_auto_props: |
| 754 upload_args.append('--emulate_svn_auto_props') |
| 755 if options.send_mail: |
| 756 if not options.reviewers: |
| 757 DieWithError("Must specify reviewers to send email.") |
| 758 upload_args.append('--send_mail') |
| 759 if options.from_logs and not options.message: |
| 760 print 'Must set message for subject line if using desc_from_logs' |
| 761 return 1 |
| 762 |
| 763 change_desc = None |
| 764 |
| 765 if cl.GetIssue(): |
| 766 if options.message: |
| 767 upload_args.extend(['--message', options.message]) |
| 768 upload_args.extend(['--issue', cl.GetIssue()]) |
| 769 print ("This branch is associated with issue %s. " |
| 770 "Adding patch to that issue." % cl.GetIssue()) |
| 771 else: |
| 772 log_desc = CreateDescriptionFromLog(args) |
| 773 if options.from_logs: |
| 774 # Uses logs as description and message as subject. |
| 775 subject = options.message |
| 776 change_desc = subject + '\n\n' + log_desc |
| 777 else: |
| 778 initial_text = """# Enter a description of the change. |
| 779 # This will displayed on the codereview site. |
| 780 # The first line will also be used as the subject of the review. |
| 781 """ |
| 782 if 'BUG=' not in log_desc: |
| 783 log_desc += '\nBUG=' |
| 784 if 'TEST=' not in log_desc: |
| 785 log_desc += '\nTEST=' |
| 786 change_desc = UserEditedLog(initial_text + log_desc) |
| 787 subject = '' |
| 788 if change_desc: |
| 789 subject = change_desc.splitlines()[0] |
| 790 if not change_desc: |
| 791 print "Description is empty; aborting." |
| 792 return 1 |
| 793 upload_args.extend(['--message', subject]) |
| 794 upload_args.extend(['--description', change_desc]) |
| 795 |
| 796 # Include the upstream repo's URL in the change -- this is useful for |
| 797 # projects that have their source spread across multiple repos. |
| 798 remote_url = None |
| 799 if settings.GetIsGitSvn(): |
| 800 data = RunGit(['svn', 'info']) |
| 801 if data: |
| 802 keys = dict(line.split(': ', 1) for line in data.splitlines() |
| 803 if ': ' in line) |
| 804 remote_url = keys.get('URL', None) |
| 805 else: |
| 806 if cl.GetRemoteUrl() and '/' in cl.GetUpstreamBranch(): |
| 807 remote_url = (cl.GetRemoteUrl() + '@' |
| 808 + cl.GetUpstreamBranch().split('/')[-1]) |
| 809 if remote_url: |
| 810 upload_args.extend(['--base_url', remote_url]) |
| 811 |
| 812 try: |
| 813 issue, patchset = upload.RealMain(['upload'] + upload_args + args) |
| 814 except: |
| 815 # If we got an exception after the user typed a description for their |
| 816 # change, back up the description before re-raising. |
| 817 if change_desc: |
| 818 backup_path = os.path.expanduser(DESCRIPTION_BACKUP_FILE) |
| 819 print '\nGot exception while uploading -- saving description to %s\n' \ |
| 820 % backup_path |
| 821 backup_file = open(backup_path, 'w') |
| 822 backup_file.write(change_desc) |
| 823 backup_file.close() |
| 824 raise |
| 825 |
| 826 if not cl.GetIssue(): |
| 827 cl.SetIssue(issue) |
| 828 cl.SetPatchset(patchset) |
| 829 return 0 |
| 830 |
| 831 |
| 832 def SendUpstream(parser, args, cmd): |
| 833 """Common code for CmdPush and CmdDCommit |
| 834 |
| 835 Squashed commit into a single. |
| 836 Updates changelog with metadata (e.g. pointer to review). |
| 837 Pushes/dcommits the code upstream. |
| 838 Updates review and closes. |
| 839 """ |
| 840 parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks', |
| 841 help='bypass upload presubmit hook') |
| 842 parser.add_option('-m', dest='message', |
| 843 help="override review description") |
| 844 parser.add_option('-f', action='store_true', dest='force', |
| 845 help="force yes to questions (don't prompt)") |
| 846 parser.add_option('-c', dest='contributor', |
| 847 help="external contributor for patch (appended to " + |
| 848 "description and used as author for git). Should be " + |
| 849 "formatted as 'First Last <email@example.com>'") |
| 850 parser.add_option('--tbr', action='store_true', dest='tbr', |
| 851 help="short for 'to be reviewed', commit branch " + |
| 852 "even without uploading for review") |
| 853 (options, args) = parser.parse_args(args) |
| 854 cl = Changelist() |
| 855 |
| 856 if not args or cmd == 'push': |
| 857 # Default to merging against our best guess of the upstream branch. |
| 858 args = [cl.GetUpstreamBranch()] |
| 859 |
| 860 base_branch = args[0] |
| 861 |
| 862 if RunGit(['diff-index', 'HEAD']): |
| 863 print 'Cannot %s with a dirty tree. You must commit locally first.' % cmd |
| 864 return 1 |
| 865 |
| 866 # This rev-list syntax means "show all commits not in my branch that |
| 867 # are in base_branch". |
| 868 upstream_commits = RunGit(['rev-list', '^' + cl.GetBranchRef(), |
| 869 base_branch]).splitlines() |
| 870 if upstream_commits: |
| 871 print ('Base branch "%s" has %d commits ' |
| 872 'not in this branch.' % (base_branch, len(upstream_commits))) |
| 873 print 'Run "git merge %s" before attempting to %s.' % (base_branch, cmd) |
| 874 return 1 |
| 875 |
| 876 if cmd == 'dcommit': |
| 877 # This is the revision `svn dcommit` will commit on top of. |
| 878 svn_head = RunGit(['log', '--grep=^git-svn-id:', '-1', |
| 879 '--pretty=format:%H']) |
| 880 extra_commits = RunGit(['rev-list', '^' + svn_head, base_branch]) |
| 881 if extra_commits: |
| 882 print ('This branch has %d additional commits not upstreamed yet.' |
| 883 % len(extra_commits.splitlines())) |
| 884 print ('Upstream "%s" or rebase this branch on top of the upstream trunk ' |
| 885 'before attempting to %s.' % (base_branch, cmd)) |
| 886 return 1 |
| 887 |
| 888 if not options.force and not options.bypass_hooks: |
| 889 RunHook(PREDCOMMIT_HOOK, upstream_branch=base_branch, error_ok=False) |
| 890 |
| 891 if cmd == 'dcommit': |
| 892 # Check the tree status if the tree status URL is set. |
| 893 status = GetTreeStatus() |
| 894 if 'closed' == status: |
| 895 print ('The tree is closed. Please wait for it to reopen. Use ' |
| 896 '"git cl dcommit -f" to commit on a closed tree.') |
| 897 return 1 |
| 898 elif 'unknown' == status: |
| 899 print ('Unable to determine tree status. Please verify manually and ' |
| 900 'use "git cl dcommit -f" to commit on a closed tree.') |
| 901 |
| 902 description = options.message |
| 903 if not options.tbr: |
| 904 # It is important to have these checks early. Not only for user |
| 905 # convenience, but also because the cl object then caches the correct values |
| 906 # of these fields even as we're juggling branches for setting up the commit. |
| 907 if not cl.GetIssue(): |
| 908 print 'Current issue unknown -- has this branch been uploaded?' |
| 909 print 'Use --tbr to commit without review.' |
| 910 return 1 |
| 911 |
| 912 if not description: |
| 913 description = cl.GetDescription() |
| 914 |
| 915 if not description: |
| 916 print 'No description set.' |
| 917 print 'Visit %s/edit to set it.' % (cl.GetIssueURL()) |
| 918 return 1 |
| 919 |
| 920 description += "\n\nReview URL: %s" % cl.GetIssueURL() |
| 921 else: |
| 922 if not description: |
| 923 # Submitting TBR. See if there's already a description in Rietveld, else |
| 924 # create a template description. Eitherway, give the user a chance to edit |
| 925 # it to fill in the TBR= field. |
| 926 if cl.GetIssue(): |
| 927 description = cl.GetDescription() |
| 928 |
| 929 if not description: |
| 930 description = """# Enter a description of the change. |
| 931 # This will be used as the change log for the commit. |
| 932 |
| 933 """ |
| 934 description += CreateDescriptionFromLog(args) |
| 935 |
| 936 description = UserEditedLog(description + '\nTBR=') |
| 937 |
| 938 if not description: |
| 939 print "Description empty; aborting." |
| 940 return 1 |
| 941 |
| 942 if options.contributor: |
| 943 if not re.match('^.*\s<\S+@\S+>$', options.contributor): |
| 944 print "Please provide contibutor as 'First Last <email@example.com>'" |
| 945 return 1 |
| 946 description += "\nPatch from %s." % options.contributor |
| 947 print 'Description:', repr(description) |
| 948 |
| 949 branches = [base_branch, cl.GetBranchRef()] |
| 950 if not options.force: |
| 951 subprocess.call(['git', 'diff', '--stat'] + branches) |
| 952 raw_input("About to commit; enter to confirm.") |
| 953 |
| 954 # We want to squash all this branch's commits into one commit with the |
| 955 # proper description. |
| 956 # We do this by doing a "merge --squash" into a new commit branch, then |
| 957 # dcommitting that. |
| 958 MERGE_BRANCH = 'git-cl-commit' |
| 959 # Delete the merge branch if it already exists. |
| 960 if RunGitWithCode(['show-ref', '--quiet', '--verify', |
| 961 'refs/heads/' + MERGE_BRANCH])[0] == 0: |
| 962 RunGit(['branch', '-D', MERGE_BRANCH]) |
| 963 |
| 964 # We might be in a directory that's present in this branch but not in the |
| 965 # trunk. Move up to the top of the tree so that git commands that expect a |
| 966 # valid CWD won't fail after we check out the merge branch. |
| 967 rel_base_path = RunGit(['rev-parse', '--show-cdup']).strip() |
| 968 if rel_base_path: |
| 969 os.chdir(rel_base_path) |
| 970 |
| 971 # Stuff our change into the merge branch. |
| 972 # We wrap in a try...finally block so if anything goes wrong, |
| 973 # we clean up the branches. |
| 974 try: |
| 975 RunGit(['checkout', '-q', '-b', MERGE_BRANCH, base_branch]) |
| 976 RunGit(['merge', '--squash', cl.GetBranchRef()]) |
| 977 if options.contributor: |
| 978 RunGit(['commit', '--author', options.contributor, '-m', description]) |
| 979 else: |
| 980 RunGit(['commit', '-m', description]) |
| 981 if cmd == 'push': |
| 982 # push the merge branch. |
| 983 remote, branch = cl.FetchUpstreamTuple() |
| 984 retcode, output = RunGitWithCode( |
| 985 ['push', '--porcelain', remote, 'HEAD:%s' % branch]) |
| 986 logging.debug(output) |
| 987 else: |
| 988 # dcommit the merge branch. |
| 989 output = RunGit(['svn', 'dcommit', '--no-rebase']) |
| 990 finally: |
| 991 # And then swap back to the original branch and clean up. |
| 992 RunGit(['checkout', '-q', cl.GetBranch()]) |
| 993 RunGit(['branch', '-D', MERGE_BRANCH]) |
| 994 |
| 995 if cl.GetIssue(): |
| 996 if cmd == 'dcommit' and 'Committed r' in output: |
| 997 revision = re.match('.*?\nCommitted r(\\d+)', output, re.DOTALL).group(1) |
| 998 elif cmd == 'push' and retcode == 0: |
| 999 revision = output.splitlines()[1].split('\t')[2].split('..')[1] |
| 1000 else: |
| 1001 return 1 |
| 1002 viewvc_url = settings.GetViewVCUrl() |
| 1003 if viewvc_url and revision: |
| 1004 cl.description += ('\n\nCommitted: ' + viewvc_url + revision) |
| 1005 print ('Closing issue ' |
| 1006 '(you may be prompted for your codereview password)...') |
| 1007 cl.CloseIssue() |
| 1008 cl.SetIssue(0) |
| 1009 return 0 |
| 1010 |
| 1011 |
| 1012 @usage('[upstream branch to apply against]') |
| 1013 def CMDdcommit(parser, args): |
| 1014 """commit the current changelist via git-svn""" |
| 1015 if not settings.GetIsGitSvn(): |
| 1016 print('This doesn\'t appear to be an SVN repository.') |
| 1017 print('Are you sure you didn\'t mean \'git cl push\'?') |
| 1018 raw_input('[Press enter to dcommit or ctrl-C to quit]') |
| 1019 return SendUpstream(parser, args, 'dcommit') |
| 1020 |
| 1021 |
| 1022 @usage('[upstream branch to apply against]') |
| 1023 def CMDpush(parser, args): |
| 1024 """commit the current changelist via git""" |
| 1025 if settings.GetIsGitSvn(): |
| 1026 print('This appears to be an SVN repository.') |
| 1027 print('Are you sure you didn\'t mean \'git cl dcommit\'?') |
| 1028 raw_input('[Press enter to push or ctrl-C to quit]') |
| 1029 return SendUpstream(parser, args, 'push') |
| 1030 |
| 1031 |
| 1032 @usage('<patch url or issue id>') |
| 1033 def CMDpatch(parser, args): |
| 1034 """patch in a code review""" |
| 1035 parser.add_option('-b', dest='newbranch', |
| 1036 help='create a new branch off trunk for the patch') |
| 1037 parser.add_option('-f', action='store_true', dest='force', |
| 1038 help='with -b, clobber any existing branch') |
| 1039 parser.add_option('--reject', action='store_true', dest='reject', |
| 1040 help='allow failed patches and spew .rej files') |
| 1041 parser.add_option('-n', '--no-commit', action='store_true', dest='nocommit', |
| 1042 help="don't commit after patch applies") |
| 1043 (options, args) = parser.parse_args(args) |
| 1044 if len(args) != 1: |
| 1045 parser.print_help() |
| 1046 return 1 |
| 1047 input = args[0] |
| 1048 |
| 1049 if re.match(r'\d+', input): |
| 1050 # Input is an issue id. Figure out the URL. |
| 1051 issue = input |
| 1052 server = settings.GetDefaultServerUrl() |
| 1053 fetch = urllib2.urlopen('%s/%s' % (server, issue)).read() |
| 1054 m = re.search(r'/download/issue[0-9]+_[0-9]+.diff', fetch) |
| 1055 if not m: |
| 1056 DieWithError('Must pass an issue ID or full URL for ' |
| 1057 '\'Download raw patch set\'') |
| 1058 url = '%s%s' % (server, m.group(0).strip()) |
| 1059 else: |
| 1060 # Assume it's a URL to the patch. Default to http. |
| 1061 input = FixUrl(input) |
| 1062 match = re.match(r'.*?/issue(\d+)_\d+.diff', input) |
| 1063 if match: |
| 1064 issue = match.group(1) |
| 1065 url = input |
| 1066 else: |
| 1067 DieWithError('Must pass an issue ID or full URL for ' |
| 1068 '\'Download raw patch set\'') |
| 1069 |
| 1070 if options.newbranch: |
| 1071 if options.force: |
| 1072 RunGit(['branch', '-D', options.newbranch], |
| 1073 swallow_stderr=True, error_ok=True) |
| 1074 RunGit(['checkout', '-b', options.newbranch, |
| 1075 Changelist().GetUpstreamBranch()]) |
| 1076 |
| 1077 # Switch up to the top-level directory, if necessary, in preparation for |
| 1078 # applying the patch. |
| 1079 top = RunGit(['rev-parse', '--show-cdup']).strip() |
| 1080 if top: |
| 1081 os.chdir(top) |
| 1082 |
| 1083 patch_data = urllib2.urlopen(url).read() |
| 1084 # Git patches have a/ at the beginning of source paths. We strip that out |
| 1085 # with a sed script rather than the -p flag to patch so we can feed either |
| 1086 # Git or svn-style patches into the same apply command. |
| 1087 # re.sub() should be used but flags=re.MULTILINE is only in python 2.7. |
| 1088 sed_proc = Popen(['sed', '-e', 's|^--- a/|--- |; s|^+++ b/|+++ |'], |
| 1089 stdin=subprocess.PIPE, stdout=subprocess.PIPE) |
| 1090 patch_data = sed_proc.communicate(patch_data)[0] |
| 1091 if sed_proc.returncode: |
| 1092 DieWithError('Git patch mungling failed.') |
| 1093 logging.info(patch_data) |
| 1094 # We use "git apply" to apply the patch instead of "patch" so that we can |
| 1095 # pick up file adds. |
| 1096 # The --index flag means: also insert into the index (so we catch adds). |
| 1097 cmd = ['git', 'apply', '--index', '-p0'] |
| 1098 if options.reject: |
| 1099 cmd.append('--reject') |
| 1100 patch_proc = Popen(cmd, stdin=subprocess.PIPE) |
| 1101 patch_proc.communicate(patch_data) |
| 1102 if patch_proc.returncode: |
| 1103 DieWithError('Failed to apply the patch') |
| 1104 |
| 1105 # If we had an issue, commit the current state and register the issue. |
| 1106 if not options.nocommit: |
| 1107 RunGit(['commit', '-m', 'patch from issue %s' % issue]) |
| 1108 cl = Changelist() |
| 1109 cl.SetIssue(issue) |
| 1110 print "Committed patch." |
| 1111 else: |
| 1112 print "Patch applied to index." |
| 1113 return 0 |
| 1114 |
| 1115 |
| 1116 def CMDrebase(parser, args): |
| 1117 """rebase current branch on top of svn repo""" |
| 1118 # Provide a wrapper for git svn rebase to help avoid accidental |
| 1119 # git svn dcommit. |
| 1120 # It's the only command that doesn't use parser at all since we just defer |
| 1121 # execution to git-svn. |
| 1122 RunGit(['svn', 'rebase'] + args, redirect_stdout=False) |
| 1123 return 0 |
| 1124 |
| 1125 |
| 1126 def GetTreeStatus(): |
| 1127 """Fetches the tree status and returns either 'open', 'closed', |
| 1128 'unknown' or 'unset'.""" |
| 1129 url = settings.GetTreeStatusUrl(error_ok=True) |
| 1130 if url: |
| 1131 status = urllib2.urlopen(url).read().lower() |
| 1132 if status.find('closed') != -1 or status == '0': |
| 1133 return 'closed' |
| 1134 elif status.find('open') != -1 or status == '1': |
| 1135 return 'open' |
| 1136 return 'unknown' |
| 1137 |
| 1138 return 'unset' |
| 1139 |
| 1140 def GetTreeStatusReason(): |
| 1141 """Fetches the tree status from a json url and returns the message |
| 1142 with the reason for the tree to be opened or closed.""" |
| 1143 # Don't import it at file level since simplejson is not installed by default |
| 1144 # on python 2.5 and it is only used for git-cl tree which isn't often used, |
| 1145 # forcing everyone to install simplejson isn't efficient. |
| 1146 try: |
| 1147 import simplejson as json |
| 1148 except ImportError: |
| 1149 try: |
| 1150 import json |
| 1151 # Some versions of python2.5 have an incomplete json module. Check to make |
| 1152 # sure loads exists. |
| 1153 json.loads |
| 1154 except (ImportError, AttributeError): |
| 1155 print >> sys.stderr, 'Please install simplejson' |
| 1156 sys.exit(1) |
| 1157 |
| 1158 json_url = 'http://chromium-status.appspot.com/current?format=json' |
| 1159 connection = urllib2.urlopen(json_url) |
| 1160 status = json.loads(connection.read()) |
| 1161 connection.close() |
| 1162 return status['message'] |
| 1163 |
| 1164 def CMDtree(parser, args): |
| 1165 """show the status of the tree""" |
| 1166 (options, args) = parser.parse_args(args) |
| 1167 status = GetTreeStatus() |
| 1168 if 'unset' == status: |
| 1169 print 'You must configure your tree status URL by running "git cl config".' |
| 1170 return 2 |
| 1171 |
| 1172 print "The tree is %s" % status |
| 1173 print |
| 1174 print GetTreeStatusReason() |
| 1175 if status != 'open': |
| 1176 return 1 |
| 1177 return 0 |
| 1178 |
| 1179 |
| 1180 def CMDupstream(parser, args): |
| 1181 """print the name of the upstream branch, if any""" |
| 1182 (options, args) = parser.parse_args(args) |
| 1183 cl = Changelist() |
| 1184 print cl.GetUpstreamBranch() |
| 1185 return 0 |
| 1186 |
| 1187 |
| 1188 def Command(name): |
| 1189 return getattr(sys.modules[__name__], 'CMD' + name, None) |
| 1190 |
| 1191 |
| 1192 def CMDhelp(parser, args): |
| 1193 """print list of commands or help for a specific command""" |
| 1194 (options, args) = parser.parse_args(args) |
| 1195 if len(args) == 1: |
| 1196 return main(args + ['--help']) |
| 1197 parser.print_help() |
| 1198 return 0 |
| 1199 |
| 1200 |
| 1201 def GenUsage(parser, command): |
| 1202 """Modify an OptParse object with the function's documentation.""" |
| 1203 obj = Command(command) |
| 1204 more = getattr(obj, 'usage_more', '') |
| 1205 if command == 'help': |
| 1206 command = '<command>' |
| 1207 else: |
| 1208 # OptParser.description prefer nicely non-formatted strings. |
| 1209 parser.description = re.sub('[\r\n ]{2,}', ' ', obj.__doc__) |
| 1210 parser.set_usage('usage: %%prog %s [options] %s' % (command, more)) |
| 1211 |
| 1212 |
| 1213 def main(argv): |
| 1214 """Doesn't parse the arguments here, just find the right subcommand to |
| 1215 execute.""" |
| 1216 # Do it late so all commands are listed. |
| 1217 CMDhelp.usage_more = ('\n\nCommands are:\n' + '\n'.join([ |
| 1218 ' %-10s %s' % (fn[3:], Command(fn[3:]).__doc__.split('\n')[0].strip()) |
| 1219 for fn in dir(sys.modules[__name__]) if fn.startswith('CMD')])) |
| 1220 |
| 1221 # Create the option parse and add --verbose support. |
| 1222 parser = optparse.OptionParser() |
| 1223 parser.add_option('-v', '--verbose', action='store_true') |
| 1224 old_parser_args = parser.parse_args |
| 1225 def Parse(args): |
| 1226 options, args = old_parser_args(args) |
| 1227 if options.verbose: |
| 1228 logging.basicConfig(level=logging.DEBUG) |
| 1229 else: |
| 1230 logging.basicConfig(level=logging.WARNING) |
| 1231 return options, args |
| 1232 parser.parse_args = Parse |
| 1233 |
| 1234 if argv: |
| 1235 command = Command(argv[0]) |
| 1236 if command: |
| 1237 # "fix" the usage and the description now that we know the subcommand. |
| 1238 GenUsage(parser, argv[0]) |
| 1239 try: |
| 1240 return command(parser, argv[1:]) |
| 1241 except urllib2.HTTPError, e: |
| 1242 if e.code != 500: |
| 1243 raise |
| 1244 DieWithError( |
| 1245 ('AppEngine is misbehaving and returned HTTP %d, again. Keep faith ' |
| 1246 'and retry or visit go/isgaeup.\n%s') % (e.code, str(e))) |
| 1247 |
| 1248 # Not a known command. Default to help. |
| 1249 GenUsage(parser, 'help') |
| 1250 return CMDhelp(parser, argv) |
| 1251 |
| 1252 |
| 1253 if __name__ == '__main__': |
| 1254 sys.exit(main(sys.argv[1:])) |
OLD | NEW |