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 host = re.match(r'[a-z]+\://(.*)', server).group(1) |
| 431 return upload.GetRpcServer(server, host_override=host, save_cookies=True) |
| 432 |
| 433 def _IssueSetting(self): |
| 434 """Return the git setting that stores this change's issue.""" |
| 435 return 'branch.%s.rietveldissue' % self.GetBranch() |
| 436 |
| 437 def _PatchsetSetting(self): |
| 438 """Return the git setting that stores this change's most recent patchset.""" |
| 439 return 'branch.%s.rietveldpatchset' % self.GetBranch() |
| 440 |
| 441 def _RietveldServer(self): |
| 442 """Returns the git setting that stores this change's rietveld server.""" |
| 443 return 'branch.%s.rietveldserver' % self.GetBranch() |
| 444 |
| 445 |
| 446 def GetCodereviewSettingsInteractively(): |
| 447 """Prompt the user for settings.""" |
| 448 server = settings.GetDefaultServerUrl(error_ok=True) |
| 449 prompt = 'Rietveld server (host[:port])' |
| 450 prompt += ' [%s]' % (server or DEFAULT_SERVER) |
| 451 newserver = raw_input(prompt + ': ') |
| 452 if not server and not newserver: |
| 453 newserver = DEFAULT_SERVER |
| 454 if newserver and newserver != server: |
| 455 RunGit(['config', 'rietveld.server', newserver]) |
| 456 |
| 457 def SetProperty(initial, caption, name): |
| 458 prompt = caption |
| 459 if initial: |
| 460 prompt += ' ("x" to clear) [%s]' % initial |
| 461 new_val = raw_input(prompt + ': ') |
| 462 if new_val == 'x': |
| 463 RunGit(['config', '--unset-all', 'rietveld.' + name], error_ok=True) |
| 464 elif new_val and new_val != initial: |
| 465 RunGit(['config', 'rietveld.' + name, new_val]) |
| 466 |
| 467 SetProperty(settings.GetCCList(), 'CC list', 'cc') |
| 468 SetProperty(settings.GetTreeStatusUrl(error_ok=True), 'Tree status URL', |
| 469 'tree-status-url') |
| 470 SetProperty(settings.GetViewVCUrl(), 'ViewVC URL', 'viewvc-url') |
| 471 |
| 472 # TODO: configure a default branch to diff against, rather than this |
| 473 # svn-based hackery. |
| 474 |
| 475 |
| 476 def FindCodereviewSettingsFile(filename='codereview.settings'): |
| 477 """Finds the given file starting in the cwd and going up. |
| 478 |
| 479 Only looks up to the top of the repository unless an |
| 480 'inherit-review-settings-ok' file exists in the root of the repository. |
| 481 """ |
| 482 inherit_ok_file = 'inherit-review-settings-ok' |
| 483 cwd = os.getcwd() |
| 484 root = os.path.abspath(RunGit(['rev-parse', '--show-cdup']).strip()) |
| 485 if os.path.isfile(os.path.join(root, inherit_ok_file)): |
| 486 root = '/' |
| 487 while True: |
| 488 if filename in os.listdir(cwd): |
| 489 if os.path.isfile(os.path.join(cwd, filename)): |
| 490 return open(os.path.join(cwd, filename)) |
| 491 if cwd == root: |
| 492 break |
| 493 cwd = os.path.dirname(cwd) |
| 494 |
| 495 |
| 496 def LoadCodereviewSettingsFromFile(fileobj): |
| 497 """Parse a codereview.settings file and updates hooks.""" |
| 498 def DownloadToFile(url, filename): |
| 499 filename = os.path.join(settings.GetRoot(), filename) |
| 500 contents = urllib2.urlopen(url).read() |
| 501 fileobj = open(filename, 'w') |
| 502 fileobj.write(contents) |
| 503 fileobj.close() |
| 504 os.chmod(filename, 0755) |
| 505 return 0 |
| 506 |
| 507 keyvals = {} |
| 508 for line in fileobj.read().splitlines(): |
| 509 if not line or line.startswith("#"): |
| 510 continue |
| 511 k, v = line.split(": ", 1) |
| 512 keyvals[k] = v |
| 513 |
| 514 def GetProperty(name): |
| 515 return keyvals.get(name) |
| 516 |
| 517 def SetProperty(name, setting, unset_error_ok=False): |
| 518 fullname = 'rietveld.' + name |
| 519 if setting in keyvals: |
| 520 RunGit(['config', fullname, keyvals[setting]]) |
| 521 else: |
| 522 RunGit(['config', '--unset-all', fullname], error_ok=unset_error_ok) |
| 523 |
| 524 SetProperty('server', 'CODE_REVIEW_SERVER') |
| 525 # Only server setting is required. Other settings can be absent. |
| 526 # In that case, we ignore errors raised during option deletion attempt. |
| 527 SetProperty('cc', 'CC_LIST', unset_error_ok=True) |
| 528 SetProperty('tree-status-url', 'STATUS', unset_error_ok=True) |
| 529 SetProperty('viewvc-url', 'VIEW_VC', unset_error_ok=True) |
| 530 |
| 531 if 'PUSH_URL_CONFIG' in keyvals and 'ORIGIN_URL_CONFIG' in keyvals: |
| 532 #should be of the form |
| 533 #PUSH_URL_CONFIG: url.ssh://gitrw.chromium.org.pushinsteadof |
| 534 #ORIGIN_URL_CONFIG: http://src.chromium.org/git |
| 535 RunGit(['config', keyvals['PUSH_URL_CONFIG'], |
| 536 keyvals['ORIGIN_URL_CONFIG']]) |
| 537 |
| 538 # Update the hooks if the local hook files aren't present already. |
| 539 if GetProperty('GITCL_PREUPLOAD') and not os.path.isfile(PREUPLOAD_HOOK): |
| 540 DownloadToFile(GetProperty('GITCL_PREUPLOAD'), PREUPLOAD_HOOK) |
| 541 if GetProperty('GITCL_PREDCOMMIT') and not os.path.isfile(PREDCOMMIT_HOOK): |
| 542 DownloadToFile(GetProperty('GITCL_PREDCOMMIT'), PREDCOMMIT_HOOK) |
| 543 return 0 |
| 544 |
| 545 |
| 546 @usage('[repo root containing codereview.settings]') |
| 547 def CMDconfig(parser, args): |
| 548 """edit configuration for this tree""" |
| 549 |
| 550 (options, args) = parser.parse_args(args) |
| 551 if len(args) == 0: |
| 552 GetCodereviewSettingsInteractively() |
| 553 return 0 |
| 554 |
| 555 url = args[0] |
| 556 if not url.endswith('codereview.settings'): |
| 557 url = os.path.join(url, 'codereview.settings') |
| 558 |
| 559 # Load code review settings and download hooks (if available). |
| 560 LoadCodereviewSettingsFromFile(urllib2.urlopen(url)) |
| 561 return 0 |
| 562 |
| 563 |
| 564 def CMDstatus(parser, args): |
| 565 """show status of changelists""" |
| 566 parser.add_option('--field', |
| 567 help='print only specific field (desc|id|patch|url)') |
| 568 (options, args) = parser.parse_args(args) |
| 569 |
| 570 # TODO: maybe make show_branches a flag if necessary. |
| 571 show_branches = not options.field |
| 572 |
| 573 if show_branches: |
| 574 branches = RunGit(['for-each-ref', '--format=%(refname)', 'refs/heads']) |
| 575 if branches: |
| 576 print 'Branches associated with reviews:' |
| 577 for branch in sorted(branches.splitlines()): |
| 578 cl = Changelist(branchref=branch) |
| 579 print " %10s: %s" % (cl.GetBranch(), cl.GetIssue()) |
| 580 |
| 581 cl = Changelist() |
| 582 if options.field: |
| 583 if options.field.startswith('desc'): |
| 584 print cl.GetDescription() |
| 585 elif options.field == 'id': |
| 586 issueid = cl.GetIssue() |
| 587 if issueid: |
| 588 print issueid |
| 589 elif options.field == 'patch': |
| 590 patchset = cl.GetPatchset() |
| 591 if patchset: |
| 592 print patchset |
| 593 elif options.field == 'url': |
| 594 url = cl.GetIssueURL() |
| 595 if url: |
| 596 print url |
| 597 else: |
| 598 print |
| 599 print 'Current branch:', |
| 600 if not cl.GetIssue(): |
| 601 print 'no issue assigned.' |
| 602 return 0 |
| 603 print cl.GetBranch() |
| 604 print 'Issue number:', cl.GetIssue(), '(%s)' % cl.GetIssueURL() |
| 605 print 'Issue description:' |
| 606 print cl.GetDescription(pretty=True) |
| 607 return 0 |
| 608 |
| 609 |
| 610 @usage('[issue_number]') |
| 611 def CMDissue(parser, args): |
| 612 """Set or display the current code review issue number. |
| 613 |
| 614 Pass issue number 0 to clear the current issue. |
| 615 """ |
| 616 (options, args) = parser.parse_args(args) |
| 617 |
| 618 cl = Changelist() |
| 619 if len(args) > 0: |
| 620 try: |
| 621 issue = int(args[0]) |
| 622 except ValueError: |
| 623 DieWithError('Pass a number to set the issue or none to list it.\n' |
| 624 'Maybe you want to run git cl status?') |
| 625 cl.SetIssue(issue) |
| 626 print 'Issue number:', cl.GetIssue(), '(%s)' % cl.GetIssueURL() |
| 627 return 0 |
| 628 |
| 629 |
| 630 def CreateDescriptionFromLog(args): |
| 631 """Pulls out the commit log to use as a base for the CL description.""" |
| 632 log_args = [] |
| 633 if len(args) == 1 and not args[0].endswith('.'): |
| 634 log_args = [args[0] + '..'] |
| 635 elif len(args) == 1 and args[0].endswith('...'): |
| 636 log_args = [args[0][:-1]] |
| 637 elif len(args) == 2: |
| 638 log_args = [args[0] + '..' + args[1]] |
| 639 else: |
| 640 log_args = args[:] # Hope for the best! |
| 641 return RunGit(['log', '--pretty=format:%s\n\n%b'] + log_args) |
| 642 |
| 643 |
| 644 def UserEditedLog(starting_text): |
| 645 """Given some starting text, let the user edit it and return the result.""" |
| 646 editor = os.getenv('EDITOR', 'vi') |
| 647 |
| 648 (file_handle, filename) = tempfile.mkstemp() |
| 649 fileobj = os.fdopen(file_handle, 'w') |
| 650 fileobj.write(starting_text) |
| 651 fileobj.close() |
| 652 |
| 653 ret = subprocess.call(editor + ' ' + filename, shell=True) |
| 654 if ret != 0: |
| 655 os.remove(filename) |
| 656 return |
| 657 |
| 658 fileobj = open(filename) |
| 659 text = fileobj.read() |
| 660 fileobj.close() |
| 661 os.remove(filename) |
| 662 stripcomment_re = re.compile(r'^#.*$', re.MULTILINE) |
| 663 return stripcomment_re.sub('', text).strip() |
| 664 |
| 665 |
| 666 def RunHook(hook, upstream_branch, error_ok=False): |
| 667 """Run a given hook if it exists. By default, we fail on errors.""" |
| 668 hook = '%s/%s' % (settings.GetRoot(), hook) |
| 669 if not os.path.exists(hook): |
| 670 return |
| 671 return RunCommand([hook, upstream_branch], error_ok=error_ok, |
| 672 redirect_stdout=False) |
| 673 |
| 674 |
| 675 def CMDpresubmit(parser, args): |
| 676 """run presubmit tests on the current changelist""" |
| 677 parser.add_option('--upload', action='store_true', |
| 678 help='Run upload hook instead of the push/dcommit hook') |
| 679 (options, args) = parser.parse_args(args) |
| 680 |
| 681 # Make sure index is up-to-date before running diff-index. |
| 682 RunGit(['update-index', '--refresh', '-q'], error_ok=True) |
| 683 if RunGit(['diff-index', 'HEAD']): |
| 684 # TODO(maruel): Is this really necessary? |
| 685 print 'Cannot presubmit with a dirty tree. You must commit locally first.' |
| 686 return 1 |
| 687 |
| 688 if args: |
| 689 base_branch = args[0] |
| 690 else: |
| 691 # Default to diffing against the "upstream" branch. |
| 692 base_branch = Changelist().GetUpstreamBranch() |
| 693 |
| 694 if options.upload: |
| 695 print '*** Presubmit checks for UPLOAD would report: ***' |
| 696 return not RunHook(PREUPLOAD_HOOK, upstream_branch=base_branch, |
| 697 error_ok=True) |
| 698 else: |
| 699 print '*** Presubmit checks for DCOMMIT would report: ***' |
| 700 return not RunHook(PREDCOMMIT_HOOK, upstream_branch=base_branch, |
| 701 error_ok=True) |
| 702 |
| 703 |
| 704 @usage('[args to "git diff"]') |
| 705 def CMDupload(parser, args): |
| 706 """upload the current changelist to codereview""" |
| 707 parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks', |
| 708 help='bypass upload presubmit hook') |
| 709 parser.add_option('-m', dest='message', help='message for patch') |
| 710 parser.add_option('-r', '--reviewers', |
| 711 help='reviewer email addresses') |
| 712 parser.add_option('--send-mail', action='store_true', |
| 713 help='send email to reviewer immediately') |
| 714 parser.add_option("--emulate_svn_auto_props", action="store_true", |
| 715 dest="emulate_svn_auto_props", |
| 716 help="Emulate Subversion's auto properties feature.") |
| 717 parser.add_option("--desc_from_logs", action="store_true", |
| 718 dest="from_logs", |
| 719 help="""Squashes git commit logs into change description and |
| 720 uses message as subject""") |
| 721 (options, args) = parser.parse_args(args) |
| 722 |
| 723 # Make sure index is up-to-date before running diff-index. |
| 724 RunGit(['update-index', '--refresh', '-q'], error_ok=True) |
| 725 if RunGit(['diff-index', 'HEAD']): |
| 726 print 'Cannot upload with a dirty tree. You must commit locally first.' |
| 727 return 1 |
| 728 |
| 729 cl = Changelist() |
| 730 if args: |
| 731 base_branch = args[0] |
| 732 else: |
| 733 # Default to diffing against the "upstream" branch. |
| 734 base_branch = cl.GetUpstreamBranch() |
| 735 args = [base_branch + "..."] |
| 736 |
| 737 if not options.bypass_hooks: |
| 738 RunHook(PREUPLOAD_HOOK, upstream_branch=base_branch, error_ok=False) |
| 739 |
| 740 # --no-ext-diff is broken in some versions of Git, so try to work around |
| 741 # this by overriding the environment (but there is still a problem if the |
| 742 # git config key "diff.external" is used). |
| 743 env = os.environ.copy() |
| 744 if 'GIT_EXTERNAL_DIFF' in env: |
| 745 del env['GIT_EXTERNAL_DIFF'] |
| 746 subprocess.call(['git', 'diff', '--no-ext-diff', '--stat', '-M'] + args, |
| 747 env=env) |
| 748 |
| 749 upload_args = ['--assume_yes'] # Don't ask about untracked files. |
| 750 upload_args.extend(['--server', cl.GetRietveldServer()]) |
| 751 if options.reviewers: |
| 752 upload_args.extend(['--reviewers', options.reviewers]) |
| 753 upload_args.extend(['--cc', settings.GetCCList()]) |
| 754 if options.emulate_svn_auto_props: |
| 755 upload_args.append('--emulate_svn_auto_props') |
| 756 if options.send_mail: |
| 757 if not options.reviewers: |
| 758 DieWithError("Must specify reviewers to send email.") |
| 759 upload_args.append('--send_mail') |
| 760 if options.from_logs and not options.message: |
| 761 print 'Must set message for subject line if using desc_from_logs' |
| 762 return 1 |
| 763 |
| 764 change_desc = None |
| 765 |
| 766 if cl.GetIssue(): |
| 767 if options.message: |
| 768 upload_args.extend(['--message', options.message]) |
| 769 upload_args.extend(['--issue', cl.GetIssue()]) |
| 770 print ("This branch is associated with issue %s. " |
| 771 "Adding patch to that issue." % cl.GetIssue()) |
| 772 else: |
| 773 log_desc = CreateDescriptionFromLog(args) |
| 774 if options.from_logs: |
| 775 # Uses logs as description and message as subject. |
| 776 subject = options.message |
| 777 change_desc = subject + '\n\n' + log_desc |
| 778 else: |
| 779 initial_text = """# Enter a description of the change. |
| 780 # This will displayed on the codereview site. |
| 781 # The first line will also be used as the subject of the review. |
| 782 """ |
| 783 if 'BUG=' not in log_desc: |
| 784 log_desc += '\nBUG=' |
| 785 if 'TEST=' not in log_desc: |
| 786 log_desc += '\nTEST=' |
| 787 change_desc = UserEditedLog(initial_text + log_desc) |
| 788 subject = '' |
| 789 if change_desc: |
| 790 subject = change_desc.splitlines()[0] |
| 791 if not change_desc: |
| 792 print "Description is empty; aborting." |
| 793 return 1 |
| 794 upload_args.extend(['--message', subject]) |
| 795 upload_args.extend(['--description', change_desc]) |
| 796 |
| 797 # Include the upstream repo's URL in the change -- this is useful for |
| 798 # projects that have their source spread across multiple repos. |
| 799 remote_url = None |
| 800 if settings.GetIsGitSvn(): |
| 801 data = RunGit(['svn', 'info']) |
| 802 if data: |
| 803 keys = dict(line.split(': ', 1) for line in data.splitlines() |
| 804 if ': ' in line) |
| 805 remote_url = keys.get('URL', None) |
| 806 else: |
| 807 remote_url = cl.GetRemoteUrl() + '@' + cl.GetUpstreamBranch().split('/')[-1] |
| 808 if remote_url: |
| 809 upload_args.extend(['--base_url', remote_url]) |
| 810 |
| 811 try: |
| 812 issue, patchset = upload.RealMain(['upload'] + upload_args + args) |
| 813 except: |
| 814 # If we got an exception after the user typed a description for their |
| 815 # change, back up the description before re-raising. |
| 816 if change_desc: |
| 817 backup_path = os.path.expanduser(DESCRIPTION_BACKUP_FILE) |
| 818 print '\nGot exception while uploading -- saving description to %s\n' \ |
| 819 % backup_path |
| 820 backup_file = open(backup_path, 'w') |
| 821 backup_file.write(change_desc) |
| 822 backup_file.close() |
| 823 raise |
| 824 |
| 825 if not cl.GetIssue(): |
| 826 cl.SetIssue(issue) |
| 827 cl.SetPatchset(patchset) |
| 828 return 0 |
| 829 |
| 830 |
| 831 def SendUpstream(parser, args, cmd): |
| 832 """Common code for CmdPush and CmdDCommit |
| 833 |
| 834 Squashed commit into a single. |
| 835 Updates changelog with metadata (e.g. pointer to review). |
| 836 Pushes/dcommits the code upstream. |
| 837 Updates review and closes. |
| 838 """ |
| 839 parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks', |
| 840 help='bypass upload presubmit hook') |
| 841 parser.add_option('-m', dest='message', |
| 842 help="override review description") |
| 843 parser.add_option('-f', action='store_true', dest='force', |
| 844 help="force yes to questions (don't prompt)") |
| 845 parser.add_option('-c', dest='contributor', |
| 846 help="external contributor for patch (appended to " + |
| 847 "description and used as author for git). Should be " + |
| 848 "formatted as 'First Last <email@example.com>'") |
| 849 parser.add_option('--tbr', action='store_true', dest='tbr', |
| 850 help="short for 'to be reviewed', commit branch " + |
| 851 "even without uploading for review") |
| 852 (options, args) = parser.parse_args(args) |
| 853 cl = Changelist() |
| 854 |
| 855 if not args or cmd == 'push': |
| 856 # Default to merging against our best guess of the upstream branch. |
| 857 args = [cl.GetUpstreamBranch()] |
| 858 |
| 859 base_branch = args[0] |
| 860 |
| 861 if RunGit(['diff-index', 'HEAD']): |
| 862 print 'Cannot %s with a dirty tree. You must commit locally first.' % cmd |
| 863 return 1 |
| 864 |
| 865 # This rev-list syntax means "show all commits not in my branch that |
| 866 # are in base_branch". |
| 867 upstream_commits = RunGit(['rev-list', '^' + cl.GetBranchRef(), |
| 868 base_branch]).splitlines() |
| 869 if upstream_commits: |
| 870 print ('Base branch "%s" has %d commits ' |
| 871 'not in this branch.' % (base_branch, len(upstream_commits))) |
| 872 print 'Run "git merge %s" before attempting to %s.' % (base_branch, cmd) |
| 873 return 1 |
| 874 |
| 875 if cmd == 'dcommit': |
| 876 # This is the revision `svn dcommit` will commit on top of. |
| 877 svn_head = RunGit(['log', '--grep=^git-svn-id:', '-1', |
| 878 '--pretty=format:%H']) |
| 879 extra_commits = RunGit(['rev-list', '^' + svn_head, base_branch]) |
| 880 if extra_commits: |
| 881 print ('This branch has %d additional commits not upstreamed yet.' |
| 882 % len(extra_commits.splitlines())) |
| 883 print ('Upstream "%s" or rebase this branch on top of the upstream trunk ' |
| 884 'before attempting to %s.' % (base_branch, cmd)) |
| 885 return 1 |
| 886 |
| 887 if not options.force and not options.bypass_hooks: |
| 888 RunHook(PREDCOMMIT_HOOK, upstream_branch=base_branch, error_ok=False) |
| 889 |
| 890 if cmd == 'dcommit': |
| 891 # Check the tree status if the tree status URL is set. |
| 892 status = GetTreeStatus() |
| 893 if 'closed' == status: |
| 894 print ('The tree is closed. Please wait for it to reopen. Use ' |
| 895 '"git cl dcommit -f" to commit on a closed tree.') |
| 896 return 1 |
| 897 elif 'unknown' == status: |
| 898 print ('Unable to determine tree status. Please verify manually and ' |
| 899 'use "git cl dcommit -f" to commit on a closed tree.') |
| 900 |
| 901 description = options.message |
| 902 if not options.tbr: |
| 903 # It is important to have these checks early. Not only for user |
| 904 # convenience, but also because the cl object then caches the correct values |
| 905 # of these fields even as we're juggling branches for setting up the commit. |
| 906 if not cl.GetIssue(): |
| 907 print 'Current issue unknown -- has this branch been uploaded?' |
| 908 print 'Use --tbr to commit without review.' |
| 909 return 1 |
| 910 |
| 911 if not description: |
| 912 description = cl.GetDescription() |
| 913 |
| 914 if not description: |
| 915 print 'No description set.' |
| 916 print 'Visit %s/edit to set it.' % (cl.GetIssueURL()) |
| 917 return 1 |
| 918 |
| 919 description += "\n\nReview URL: %s" % cl.GetIssueURL() |
| 920 else: |
| 921 if not description: |
| 922 # Submitting TBR. See if there's already a description in Rietveld, else |
| 923 # create a template description. Eitherway, give the user a chance to edit |
| 924 # it to fill in the TBR= field. |
| 925 if cl.GetIssue(): |
| 926 description = cl.GetDescription() |
| 927 |
| 928 if not description: |
| 929 description = """# Enter a description of the change. |
| 930 # This will be used as the change log for the commit. |
| 931 |
| 932 """ |
| 933 description += CreateDescriptionFromLog(args) |
| 934 |
| 935 description = UserEditedLog(description + '\nTBR=') |
| 936 |
| 937 if not description: |
| 938 print "Description empty; aborting." |
| 939 return 1 |
| 940 |
| 941 if options.contributor: |
| 942 if not re.match('^.*\s<\S+@\S+>$', options.contributor): |
| 943 print "Please provide contibutor as 'First Last <email@example.com>'" |
| 944 return 1 |
| 945 description += "\nPatch from %s." % options.contributor |
| 946 print 'Description:', repr(description) |
| 947 |
| 948 branches = [base_branch, cl.GetBranchRef()] |
| 949 if not options.force: |
| 950 subprocess.call(['git', 'diff', '--stat'] + branches) |
| 951 raw_input("About to commit; enter to confirm.") |
| 952 |
| 953 # We want to squash all this branch's commits into one commit with the |
| 954 # proper description. |
| 955 # We do this by doing a "merge --squash" into a new commit branch, then |
| 956 # dcommitting that. |
| 957 MERGE_BRANCH = 'git-cl-commit' |
| 958 # Delete the merge branch if it already exists. |
| 959 if RunGitWithCode(['show-ref', '--quiet', '--verify', |
| 960 'refs/heads/' + MERGE_BRANCH])[0] == 0: |
| 961 RunGit(['branch', '-D', MERGE_BRANCH]) |
| 962 |
| 963 # We might be in a directory that's present in this branch but not in the |
| 964 # trunk. Move up to the top of the tree so that git commands that expect a |
| 965 # valid CWD won't fail after we check out the merge branch. |
| 966 rel_base_path = RunGit(['rev-parse', '--show-cdup']).strip() |
| 967 if rel_base_path: |
| 968 os.chdir(rel_base_path) |
| 969 |
| 970 # Stuff our change into the merge branch. |
| 971 # We wrap in a try...finally block so if anything goes wrong, |
| 972 # we clean up the branches. |
| 973 try: |
| 974 RunGit(['checkout', '-q', '-b', MERGE_BRANCH, base_branch]) |
| 975 RunGit(['merge', '--squash', cl.GetBranchRef()]) |
| 976 if options.contributor: |
| 977 RunGit(['commit', '--author', options.contributor, '-m', description]) |
| 978 else: |
| 979 RunGit(['commit', '-m', description]) |
| 980 if cmd == 'push': |
| 981 # push the merge branch. |
| 982 remote, branch = cl.FetchUpstreamTuple() |
| 983 retcode, output = RunGitWithCode( |
| 984 ['push', '--porcelain', remote, 'HEAD:%s' % branch]) |
| 985 logging.debug(output) |
| 986 else: |
| 987 # dcommit the merge branch. |
| 988 output = RunGit(['svn', 'dcommit', '--no-rebase']) |
| 989 finally: |
| 990 # And then swap back to the original branch and clean up. |
| 991 RunGit(['checkout', '-q', cl.GetBranch()]) |
| 992 RunGit(['branch', '-D', MERGE_BRANCH]) |
| 993 |
| 994 if cl.GetIssue(): |
| 995 if cmd == 'dcommit' and 'Committed r' in output: |
| 996 revision = re.match('.*?\nCommitted r(\\d+)', output, re.DOTALL).group(1) |
| 997 elif cmd == 'push' and retcode == 0: |
| 998 revision = output.splitlines()[1].split('\t')[2].split('..')[1] |
| 999 else: |
| 1000 return 1 |
| 1001 viewvc_url = settings.GetViewVCUrl() |
| 1002 if viewvc_url and revision: |
| 1003 cl.description += ('\n\nCommitted: ' + viewvc_url + revision) |
| 1004 print ('Closing issue ' |
| 1005 '(you may be prompted for your codereview password)...') |
| 1006 cl.CloseIssue() |
| 1007 cl.SetIssue(0) |
| 1008 return 0 |
| 1009 |
| 1010 |
| 1011 @usage('[upstream branch to apply against]') |
| 1012 def CMDdcommit(parser, args): |
| 1013 """commit the current changelist via git-svn""" |
| 1014 if not settings.GetIsGitSvn(): |
| 1015 print('This doesn\'t appear to be an SVN repository.') |
| 1016 print('Are you sure you didn\'t mean \'git cl push\'?') |
| 1017 raw_input('[Press enter to dcommit or ctrl-C to quit]') |
| 1018 return SendUpstream(parser, args, 'dcommit') |
| 1019 |
| 1020 |
| 1021 @usage('[upstream branch to apply against]') |
| 1022 def CMDpush(parser, args): |
| 1023 """commit the current changelist via git""" |
| 1024 if settings.GetIsGitSvn(): |
| 1025 print('This appears to be an SVN repository.') |
| 1026 print('Are you sure you didn\'t mean \'git cl dcommit\'?') |
| 1027 raw_input('[Press enter to push or ctrl-C to quit]') |
| 1028 return SendUpstream(parser, args, 'push') |
| 1029 |
| 1030 |
| 1031 @usage('<patch url or issue id>') |
| 1032 def CMDpatch(parser, args): |
| 1033 """patch in a code review""" |
| 1034 parser.add_option('-b', dest='newbranch', |
| 1035 help='create a new branch off trunk for the patch') |
| 1036 parser.add_option('-f', action='store_true', dest='force', |
| 1037 help='with -b, clobber any existing branch') |
| 1038 parser.add_option('--reject', action='store_true', dest='reject', |
| 1039 help='allow failed patches and spew .rej files') |
| 1040 parser.add_option('-n', '--no-commit', action='store_true', dest='nocommit', |
| 1041 help="don't commit after patch applies") |
| 1042 (options, args) = parser.parse_args(args) |
| 1043 if len(args) != 1: |
| 1044 parser.print_help() |
| 1045 return 1 |
| 1046 input = args[0] |
| 1047 |
| 1048 if re.match(r'\d+', input): |
| 1049 # Input is an issue id. Figure out the URL. |
| 1050 issue = input |
| 1051 server = settings.GetDefaultServerUrl() |
| 1052 fetch = urllib2.urlopen('%s/%s' % (server, issue)).read() |
| 1053 m = re.search(r'/download/issue[0-9]+_[0-9]+.diff', fetch) |
| 1054 if not m: |
| 1055 DieWithError('Must pass an issue ID or full URL for ' |
| 1056 '\'Download raw patch set\'') |
| 1057 url = '%s%s' % (server, m.group(0).strip()) |
| 1058 else: |
| 1059 # Assume it's a URL to the patch. Default to http. |
| 1060 input = FixUrl(input) |
| 1061 match = re.match(r'.*?/issue(\d+)_\d+.diff', input) |
| 1062 if match: |
| 1063 issue = match.group(1) |
| 1064 url = input |
| 1065 else: |
| 1066 DieWithError('Must pass an issue ID or full URL for ' |
| 1067 '\'Download raw patch set\'') |
| 1068 |
| 1069 if options.newbranch: |
| 1070 if options.force: |
| 1071 RunGit(['branch', '-D', options.newbranch], |
| 1072 swallow_stderr=True, error_ok=True) |
| 1073 RunGit(['checkout', '-b', options.newbranch, |
| 1074 Changelist().GetUpstreamBranch()]) |
| 1075 |
| 1076 # Switch up to the top-level directory, if necessary, in preparation for |
| 1077 # applying the patch. |
| 1078 top = RunGit(['rev-parse', '--show-cdup']).strip() |
| 1079 if top: |
| 1080 os.chdir(top) |
| 1081 |
| 1082 patch_data = urllib2.urlopen(url).read() |
| 1083 # Git patches have a/ at the beginning of source paths. We strip that out |
| 1084 # with a sed script rather than the -p flag to patch so we can feed either |
| 1085 # Git or svn-style patches into the same apply command. |
| 1086 # re.sub() should be used but flags=re.MULTILINE is only in python 2.7. |
| 1087 sed_proc = Popen(['sed', '-e', 's|^--- a/|--- |; s|^+++ b/|+++ |'], |
| 1088 stdin=subprocess.PIPE, stdout=subprocess.PIPE) |
| 1089 patch_data = sed_proc.communicate(patch_data)[0] |
| 1090 if sed_proc.returncode: |
| 1091 DieWithError('Git patch mungling failed.') |
| 1092 logging.info(patch_data) |
| 1093 # We use "git apply" to apply the patch instead of "patch" so that we can |
| 1094 # pick up file adds. |
| 1095 # The --index flag means: also insert into the index (so we catch adds). |
| 1096 cmd = ['git', 'apply', '--index', '-p0'] |
| 1097 if options.reject: |
| 1098 cmd.append('--reject') |
| 1099 patch_proc = Popen(cmd, stdin=subprocess.PIPE) |
| 1100 patch_proc.communicate(patch_data) |
| 1101 if patch_proc.returncode: |
| 1102 DieWithError('Failed to apply the patch') |
| 1103 |
| 1104 # If we had an issue, commit the current state and register the issue. |
| 1105 if not options.nocommit: |
| 1106 RunGit(['commit', '-m', 'patch from issue %s' % issue]) |
| 1107 cl = Changelist() |
| 1108 cl.SetIssue(issue) |
| 1109 print "Committed patch." |
| 1110 else: |
| 1111 print "Patch applied to index." |
| 1112 return 0 |
| 1113 |
| 1114 |
| 1115 def CMDrebase(parser, args): |
| 1116 """rebase current branch on top of svn repo""" |
| 1117 # Provide a wrapper for git svn rebase to help avoid accidental |
| 1118 # git svn dcommit. |
| 1119 # It's the only command that doesn't use parser at all since we just defer |
| 1120 # execution to git-svn. |
| 1121 RunGit(['svn', 'rebase'] + args, redirect_stdout=False) |
| 1122 return 0 |
| 1123 |
| 1124 |
| 1125 def GetTreeStatus(): |
| 1126 """Fetches the tree status and returns either 'open', 'closed', |
| 1127 'unknown' or 'unset'.""" |
| 1128 url = settings.GetTreeStatusUrl(error_ok=True) |
| 1129 if url: |
| 1130 status = urllib2.urlopen(url).read().lower() |
| 1131 if status.find('closed') != -1 or status == '0': |
| 1132 return 'closed' |
| 1133 elif status.find('open') != -1 or status == '1': |
| 1134 return 'open' |
| 1135 return 'unknown' |
| 1136 |
| 1137 return 'unset' |
| 1138 |
| 1139 def GetTreeStatusReason(): |
| 1140 """Fetches the tree status from a json url and returns the message |
| 1141 with the reason for the tree to be opened or closed.""" |
| 1142 # Don't import it at file level since simplejson is not installed by default |
| 1143 # on python 2.5 and it is only used for git-cl tree which isn't often used, |
| 1144 # forcing everyone to install simplejson isn't efficient. |
| 1145 try: |
| 1146 import simplejson as json |
| 1147 except ImportError: |
| 1148 try: |
| 1149 import json |
| 1150 # Some versions of python2.5 have an incomplete json module. Check to make |
| 1151 # sure loads exists. |
| 1152 json.loads |
| 1153 except (ImportError, AttributeError): |
| 1154 print >> sys.stderr, 'Please install simplejson' |
| 1155 sys.exit(1) |
| 1156 |
| 1157 json_url = 'http://chromium-status.appspot.com/current?format=json' |
| 1158 connection = urllib2.urlopen(json_url) |
| 1159 status = json.loads(connection.read()) |
| 1160 connection.close() |
| 1161 return status['message'] |
| 1162 |
| 1163 def CMDtree(parser, args): |
| 1164 """show the status of the tree""" |
| 1165 (options, args) = parser.parse_args(args) |
| 1166 status = GetTreeStatus() |
| 1167 if 'unset' == status: |
| 1168 print 'You must configure your tree status URL by running "git cl config".' |
| 1169 return 2 |
| 1170 |
| 1171 print "The tree is %s" % status |
| 1172 print |
| 1173 print GetTreeStatusReason() |
| 1174 if status != 'open': |
| 1175 return 1 |
| 1176 return 0 |
| 1177 |
| 1178 |
| 1179 def CMDupstream(parser, args): |
| 1180 """print the name of the upstream branch, if any""" |
| 1181 (options, args) = parser.parse_args(args) |
| 1182 cl = Changelist() |
| 1183 print cl.GetUpstreamBranch() |
| 1184 return 0 |
| 1185 |
| 1186 |
| 1187 def Command(name): |
| 1188 return getattr(sys.modules[__name__], 'CMD' + name, None) |
| 1189 |
| 1190 |
| 1191 def CMDhelp(parser, args): |
| 1192 """print list of commands or help for a specific command""" |
| 1193 (options, args) = parser.parse_args(args) |
| 1194 if len(args) == 1: |
| 1195 return main(args + ['--help']) |
| 1196 parser.print_help() |
| 1197 return 0 |
| 1198 |
| 1199 |
| 1200 def GenUsage(parser, command): |
| 1201 """Modify an OptParse object with the function's documentation.""" |
| 1202 obj = Command(command) |
| 1203 more = getattr(obj, 'usage_more', '') |
| 1204 if command == 'help': |
| 1205 command = '<command>' |
| 1206 else: |
| 1207 # OptParser.description prefer nicely non-formatted strings. |
| 1208 parser.description = re.sub('[\r\n ]{2,}', ' ', obj.__doc__) |
| 1209 parser.set_usage('usage: %%prog %s [options] %s' % (command, more)) |
| 1210 |
| 1211 |
| 1212 def main(argv): |
| 1213 """Doesn't parse the arguments here, just find the right subcommand to |
| 1214 execute.""" |
| 1215 # Do it late so all commands are listed. |
| 1216 CMDhelp.usage_more = ('\n\nCommands are:\n' + '\n'.join([ |
| 1217 ' %-10s %s' % (fn[3:], Command(fn[3:]).__doc__.split('\n')[0].strip()) |
| 1218 for fn in dir(sys.modules[__name__]) if fn.startswith('CMD')])) |
| 1219 |
| 1220 # Create the option parse and add --verbose support. |
| 1221 parser = optparse.OptionParser() |
| 1222 parser.add_option('-v', '--verbose', action='store_true') |
| 1223 old_parser_args = parser.parse_args |
| 1224 def Parse(args): |
| 1225 options, args = old_parser_args(args) |
| 1226 if options.verbose: |
| 1227 logging.basicConfig(level=logging.DEBUG) |
| 1228 else: |
| 1229 logging.basicConfig(level=logging.WARNING) |
| 1230 return options, args |
| 1231 parser.parse_args = Parse |
| 1232 |
| 1233 if argv: |
| 1234 command = Command(argv[0]) |
| 1235 if command: |
| 1236 # "fix" the usage and the description now that we know the subcommand. |
| 1237 GenUsage(parser, argv[0]) |
| 1238 try: |
| 1239 return command(parser, argv[1:]) |
| 1240 except urllib2.HTTPError, e: |
| 1241 if e.code != 500: |
| 1242 raise |
| 1243 DieWithError( |
| 1244 ('AppEngine is misbehaving and returned HTTP %d, again. Keep faith ' |
| 1245 'and retry or visit go/isgaeup.\n%s') % (e.code, str(e))) |
| 1246 |
| 1247 # Not a known command. Default to help. |
| 1248 GenUsage(parser, 'help') |
| 1249 return CMDhelp(parser, argv) |
| 1250 |
| 1251 |
| 1252 if __name__ == '__main__': |
| 1253 sys.exit(main(sys.argv[1:])) |
OLD | NEW |