rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
gclient_utils.RemoveDirectory(checkout_path)
gclient_utils.RemoveDirectory(self.checkout_path)
def update(self, options, args, file_list): """Runs svn to update or transparently checkout the working copy.
command = ['update', checkout_path]
command = ['update', self.checkout_path]
def update(self, options, args, file_list): """Runs svn to update or transparently checkout the working copy.
checkout_path = os.path.join(self._root_dir, self.relpath)
def updatesingle(self, options, args, file_list): checkout_path = os.path.join(self._root_dir, self.relpath) filename = args.pop() if scm.SVN.AssertVersion("1.5")[0]: if not os.path.exists(os.path.join(checkout_path, '.svn')): # Create an empty checkout and then update the one file we want. Future # operations will only apply to the one file we checked out. command = ["checkout", "--depth", "empty", self.url, checkout_path] self._Run(command, options, cwd=self._root_dir) if os.path.exists(os.path.join(checkout_path, filename)): os.remove(os.path.join(checkout_path, filename)) command = ["update", filename] self._RunAndGetFileList(command, options, file_list) # After the initial checkout, we can use update as if it were any other # dep. self.update(options, args, file_list) else: # If the installed version of SVN doesn't support --depth, fallback to # just exporting the file. This has the downside that revision # information is not stored next to the file, so we will have to # re-export the file every time we sync. if not os.path.exists(checkout_path): os.makedirs(checkout_path) command = ["export", os.path.join(self.url, filename), os.path.join(checkout_path, filename)] command = self._AddAdditionalUpdateFlags(command, options, options.revision) self._Run(command, options, cwd=self._root_dir)
if not os.path.exists(os.path.join(checkout_path, '.svn')):
if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
def updatesingle(self, options, args, file_list): checkout_path = os.path.join(self._root_dir, self.relpath) filename = args.pop() if scm.SVN.AssertVersion("1.5")[0]: if not os.path.exists(os.path.join(checkout_path, '.svn')): # Create an empty checkout and then update the one file we want. Future # operations will only apply to the one file we checked out. command = ["checkout", "--depth", "empty", self.url, checkout_path] self._Run(command, options, cwd=self._root_dir) if os.path.exists(os.path.join(checkout_path, filename)): os.remove(os.path.join(checkout_path, filename)) command = ["update", filename] self._RunAndGetFileList(command, options, file_list) # After the initial checkout, we can use update as if it were any other # dep. self.update(options, args, file_list) else: # If the installed version of SVN doesn't support --depth, fallback to # just exporting the file. This has the downside that revision # information is not stored next to the file, so we will have to # re-export the file every time we sync. if not os.path.exists(checkout_path): os.makedirs(checkout_path) command = ["export", os.path.join(self.url, filename), os.path.join(checkout_path, filename)] command = self._AddAdditionalUpdateFlags(command, options, options.revision) self._Run(command, options, cwd=self._root_dir)
command = ["checkout", "--depth", "empty", self.url, checkout_path]
command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
def updatesingle(self, options, args, file_list): checkout_path = os.path.join(self._root_dir, self.relpath) filename = args.pop() if scm.SVN.AssertVersion("1.5")[0]: if not os.path.exists(os.path.join(checkout_path, '.svn')): # Create an empty checkout and then update the one file we want. Future # operations will only apply to the one file we checked out. command = ["checkout", "--depth", "empty", self.url, checkout_path] self._Run(command, options, cwd=self._root_dir) if os.path.exists(os.path.join(checkout_path, filename)): os.remove(os.path.join(checkout_path, filename)) command = ["update", filename] self._RunAndGetFileList(command, options, file_list) # After the initial checkout, we can use update as if it were any other # dep. self.update(options, args, file_list) else: # If the installed version of SVN doesn't support --depth, fallback to # just exporting the file. This has the downside that revision # information is not stored next to the file, so we will have to # re-export the file every time we sync. if not os.path.exists(checkout_path): os.makedirs(checkout_path) command = ["export", os.path.join(self.url, filename), os.path.join(checkout_path, filename)] command = self._AddAdditionalUpdateFlags(command, options, options.revision) self._Run(command, options, cwd=self._root_dir)
if os.path.exists(os.path.join(checkout_path, filename)): os.remove(os.path.join(checkout_path, filename))
if os.path.exists(os.path.join(self.checkout_path, filename)): os.remove(os.path.join(self.checkout_path, filename))
def updatesingle(self, options, args, file_list): checkout_path = os.path.join(self._root_dir, self.relpath) filename = args.pop() if scm.SVN.AssertVersion("1.5")[0]: if not os.path.exists(os.path.join(checkout_path, '.svn')): # Create an empty checkout and then update the one file we want. Future # operations will only apply to the one file we checked out. command = ["checkout", "--depth", "empty", self.url, checkout_path] self._Run(command, options, cwd=self._root_dir) if os.path.exists(os.path.join(checkout_path, filename)): os.remove(os.path.join(checkout_path, filename)) command = ["update", filename] self._RunAndGetFileList(command, options, file_list) # After the initial checkout, we can use update as if it were any other # dep. self.update(options, args, file_list) else: # If the installed version of SVN doesn't support --depth, fallback to # just exporting the file. This has the downside that revision # information is not stored next to the file, so we will have to # re-export the file every time we sync. if not os.path.exists(checkout_path): os.makedirs(checkout_path) command = ["export", os.path.join(self.url, filename), os.path.join(checkout_path, filename)] command = self._AddAdditionalUpdateFlags(command, options, options.revision) self._Run(command, options, cwd=self._root_dir)
if not os.path.exists(checkout_path): os.makedirs(checkout_path)
if not os.path.exists(self.checkout_path): os.makedirs(self.checkout_path)
def updatesingle(self, options, args, file_list): checkout_path = os.path.join(self._root_dir, self.relpath) filename = args.pop() if scm.SVN.AssertVersion("1.5")[0]: if not os.path.exists(os.path.join(checkout_path, '.svn')): # Create an empty checkout and then update the one file we want. Future # operations will only apply to the one file we checked out. command = ["checkout", "--depth", "empty", self.url, checkout_path] self._Run(command, options, cwd=self._root_dir) if os.path.exists(os.path.join(checkout_path, filename)): os.remove(os.path.join(checkout_path, filename)) command = ["update", filename] self._RunAndGetFileList(command, options, file_list) # After the initial checkout, we can use update as if it were any other # dep. self.update(options, args, file_list) else: # If the installed version of SVN doesn't support --depth, fallback to # just exporting the file. This has the downside that revision # information is not stored next to the file, so we will have to # re-export the file every time we sync. if not os.path.exists(checkout_path): os.makedirs(checkout_path) command = ["export", os.path.join(self.url, filename), os.path.join(checkout_path, filename)] command = self._AddAdditionalUpdateFlags(command, options, options.revision) self._Run(command, options, cwd=self._root_dir)
os.path.join(checkout_path, filename)]
os.path.join(self.checkout_path, filename)]
def updatesingle(self, options, args, file_list): checkout_path = os.path.join(self._root_dir, self.relpath) filename = args.pop() if scm.SVN.AssertVersion("1.5")[0]: if not os.path.exists(os.path.join(checkout_path, '.svn')): # Create an empty checkout and then update the one file we want. Future # operations will only apply to the one file we checked out. command = ["checkout", "--depth", "empty", self.url, checkout_path] self._Run(command, options, cwd=self._root_dir) if os.path.exists(os.path.join(checkout_path, filename)): os.remove(os.path.join(checkout_path, filename)) command = ["update", filename] self._RunAndGetFileList(command, options, file_list) # After the initial checkout, we can use update as if it were any other # dep. self.update(options, args, file_list) else: # If the installed version of SVN doesn't support --depth, fallback to # just exporting the file. This has the downside that revision # information is not stored next to the file, so we will have to # re-export the file every time we sync. if not os.path.exists(checkout_path): os.makedirs(checkout_path) command = ["export", os.path.join(self.url, filename), os.path.join(checkout_path, filename)] command = self._AddAdditionalUpdateFlags(command, options, options.revision) self._Run(command, options, cwd=self._root_dir)
path = os.path.join(self._root_dir, self.relpath) if not os.path.isdir(path):
if not os.path.isdir(self.checkout_path):
def revert(self, options, args, file_list): """Reverts local modifications. Subversion specific.
for file_status in scm.SVN.CaptureStatus(path): file_path = os.path.join(path, file_status[1])
for file_status in scm.SVN.CaptureStatus(self.checkout_path): file_path = os.path.join(self.checkout_path, file_status[1])
def revert(self, options, args, file_list): """Reverts local modifications. Subversion specific.
path = os.path.join(self._root_dir, self.relpath)
def status(self, options, args, file_list): """Display status information.""" path = os.path.join(self._root_dir, self.relpath) command = ['status'] + args if not os.path.isdir(path): # svn status won't work if the directory doesn't exist. options.stdout.write( ('\n________ couldn\'t run \'%s\' in \'%s\':\nThe directory ' 'does not exist.') % (' '.join(command), path)) # There's no file list to retrieve. else: self._RunAndGetFileList(command, options, file_list)
if not os.path.isdir(path):
if not os.path.isdir(self.checkout_path):
def status(self, options, args, file_list): """Display status information.""" path = os.path.join(self._root_dir, self.relpath) command = ['status'] + args if not os.path.isdir(path): # svn status won't work if the directory doesn't exist. options.stdout.write( ('\n________ couldn\'t run \'%s\' in \'%s\':\nThe directory ' 'does not exist.') % (' '.join(command), path)) # There's no file list to retrieve. else: self._RunAndGetFileList(command, options, file_list)
'does not exist.') % (' '.join(command), path))
'does not exist.') % (' '.join(command), self.checkout_path))
def status(self, options, args, file_list): """Display status information.""" path = os.path.join(self._root_dir, self.relpath) command = ['status'] + args if not os.path.isdir(path): # svn status won't work if the directory doesn't exist. options.stdout.write( ('\n________ couldn\'t run \'%s\' in \'%s\':\nThe directory ' 'does not exist.') % (' '.join(command), path)) # There's no file list to retrieve. else: self._RunAndGetFileList(command, options, file_list)
kwargs.setdefault('cwd', os.path.join(self._root_dir, self.relpath))
kwargs.setdefault('cwd', self.checkout_path)
def _Run(self, args, options, **kwargs): """Runs a commands that goes to stdout.""" kwargs.setdefault('cwd', os.path.join(self._root_dir, self.relpath)) gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args, always=options.verbose, stdout=options.stdout, **kwargs)
cwd = cwd or os.path.join(self._root_dir, self.relpath)
cwd = cwd or self.checkout_path
def _RunAndGetFileList(self, args, options, file_list, cwd=None): """Runs a commands that goes to stdout and grabs the file listed.""" cwd = cwd or os.path.join(self._root_dir, self.relpath) scm.SVN.RunAndGetFileList(options.verbose, args, cwd=cwd, file_list=file_list, stdout=options.stdout)
match = re.search(r"svn://.*/(.*)", branch_url)
match = re.search(r"^[a-z]+://.*/(.*)", branch_url)
def checkoutRevision(url, revision, branch_url, revert=False): files_info = getFileInfo(url, revision) paths = getBestMergePaths2(files_info, revision) export_map = getBestExportPathsMap2(files_info, revision) command = 'svn checkout -N ' + branch_url print command os.system(command) match = re.search(r"svn://.*/(.*)", branch_url) if match: os.chdir(match.group(1)) # This line is extremely important due to the way svn behaves in the # set-depths action. If parents aren't handled before children, the child # directories get clobbered and the merge step fails. paths.sort() # Checkout the directories that already exist for path in paths: if (export_map.has_key(path) and not revert): print "Exclude new directory " + path continue subpaths = path.split('/') subpaths.pop(0) base = '' for subpath in subpaths: base += '/' + subpath # This logic ensures that you don't empty out any directories if not os.path.exists("." + base): command = ('svn update --depth empty ' + "." + base) print command os.system(command) if (revert): files = getAllFilesInRevision(files_info) else: files = getExistingFilesInRevision(files_info) for f in files: # Prevent the tool from clobbering the src directory if (f == ""): continue command = ('svn up ".' + f + '"') print command os.system(command)
tree = dict((d.name, d) for d in self.tree(False)) if self.name in tree: raise gclient_utils.Error( 'Dependency %s specified more than once:\n %s\nvs\n %s' % (self.name, tree[self.name].hierarchy(), self.hierarchy()))
def __init__(self, parent, name, url, safesync_url=None, custom_deps=None, custom_vars=None, deps_file=None): GClientKeywords.__init__(self) self.parent = parent self.name = name self.url = url self.parsed_url = None # These 2 are only set in .gclient and not in DEPS files. self.safesync_url = safesync_url self.custom_vars = custom_vars or {} self.custom_deps = custom_deps or {} self.deps_hooks = [] self.dependencies = [] self.deps_file = deps_file or self.DEPS_FILE # A cache of the files affected by the current operation, necessary for # hooks. self._file_list = [] # If it is not set to True, the dependency wasn't processed for its child # dependency, i.e. its DEPS wasn't read. self.deps_parsed = False # A direct reference is dependency that is referenced by a deps, deps_os or # solution. A indirect one is one that was loaded with From() or that # exceeded recursion limit. self.direct_reference = False
__pychecker__ = 'unusednames=args,file_list,options'
__pychecker__ = 'unusednames=options,args,file_list'
def cleanup(self, options, args, file_list): """Cleanup working copy.""" __pychecker__ = 'unusednames=args,file_list,options' self._Run(['prune'], redirect_stdout=False) self._Run(['fsck'], redirect_stdout=False) self._Run(['gc'], redirect_stdout=False)
__pychecker__ = 'unusednames=args,file_list,options'
__pychecker__ = 'unusednames=options,args,file_list'
def diff(self, options, args, file_list): __pychecker__ = 'unusednames=args,file_list,options' merge_base = self._Run(['merge-base', 'HEAD', 'origin']) self._Run(['diff', merge_base], redirect_stdout=False)
__pychecker__ = 'unusednames=file_list,options'
__pychecker__ = 'unusednames=options,file_list'
def export(self, options, args, file_list): """Export a clean directory tree into the given path.
__pychecker__ = 'unusednames=file_list,options'
__pychecker__ = 'unusednames=options,file_list'
def pack(self, options, args, file_list): """Generates a patch file which can be applied to the root of the repository.
__pychecker__ = 'unusednames=args,file_list,options'
__pychecker__ = 'unusednames=options,args,file_list'
def revinfo(self, options, args, file_list): """Display revision""" __pychecker__ = 'unusednames=args,file_list,options' return self._Run(['rev-parse', 'HEAD'])
__pychecker__ = 'unusednames=args,options'
__pychecker__ = 'unusednames=options,args'
def status(self, options, args, file_list): """Display status information.""" __pychecker__ = 'unusednames=args,options' if not os.path.isdir(self.checkout_path): print('\n________ couldn\'t run status in %s:\nThe directory ' 'does not exist.' % self.checkout_path) else: merge_base = self._Run(['merge-base', 'HEAD', 'origin']) self._Run(['diff', '--name-status', merge_base], redirect_stdout=False) files = self._Run(['diff', '--name-only', merge_base]).split() file_list.extend([os.path.join(self.checkout_path, f) for f in files])
if revision is not None:
if revision:
def DiffItem(filename, full_move=False, revision=None): """Diffs a single file.
def __init__(self, relpath):
def __init__(self, relpath, stdout):
def __init__(self, relpath): # Note that we always use '/' as the path separator to be # consistent with svn's cygwin-style output on Windows self._relpath = relpath.replace("\\", "/") self._current_file = "" self._replacement_file = ""
def ReplaceAndPrint(self, line): print(line.replace(self._current_file, self._replacement_file))
def _Replace(self, line): return line.replace(self._current_file, self._replacement_file)
def ReplaceAndPrint(self, line): print(line.replace(self._current_file, self._replacement_file))
self.ReplaceAndPrint(line)
line = self._Replace(line)
def Filter(self, line): if (line.startswith(self.index_string)): self.SetCurrentFile(line[len(self.index_string):]) self.ReplaceAndPrint(line) else: if (line.startswith(self.original_prefix) or line.startswith(self.working_prefix)): self.ReplaceAndPrint(line) else: print line
self.ReplaceAndPrint(line) else: print line
line = self._Replace(line) self._stdout.write(line + '\n')
def Filter(self, line): if (line.startswith(self.index_string)): self.SetCurrentFile(line[len(self.index_string):]) self.ReplaceAndPrint(line) else: if (line.startswith(self.original_prefix) or line.startswith(self.working_prefix)): self.ReplaceAndPrint(line) else: print line
print("\n_____ %s%s" % (self.relpath, rev_str))
options.stdout.write("\n_____ %s%s\n" % (self.relpath, rev_str))
def update(self, options, args, file_list): """Runs git to update or transparently checkout the working copy.
self._Clone(revision, url, options.verbose)
self._Clone(revision, url, options)
def update(self, options, args, file_list): """Runs git to update or transparently checkout the working copy.
print ""
options.stdout.write('\n')
def update(self, options, args, file_list): """Runs git to update or transparently checkout the working copy.
print str(e) print "Sleeping 15 seconds and retrying..."
options.stdout.write(str(e) + '\n') options.stdout.write('Sleeping 15 seconds and retrying...\n')
def update(self, options, args, file_list): """Runs git to update or transparently checkout the working copy.
print remote_output.strip()
options.stdout.write(remote_output.strip() + '\n')
def update(self, options, args, file_list): """Runs git to update or transparently checkout the working copy.
print remote_err.strip()
options.stdout.write(remote_err.strip() + '\n')
def update(self, options, args, file_list): """Runs git to update or transparently checkout the working copy.
self._CheckDetachedHead(rev_str)
self._CheckDetachedHead(rev_str, options)
def update(self, options, args, file_list): """Runs git to update or transparently checkout the working copy.
print("\n_____ %s%s" % (self.relpath, rev_str))
options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
def update(self, options, args, file_list): """Runs git to update or transparently checkout the working copy.
self._AttemptRebase(upstream_branch, files, verbose=options.verbose,
self._AttemptRebase(upstream_branch, files, options,
def update(self, options, args, file_list): """Runs git to update or transparently checkout the working copy.
self._AttemptRebase(upstream_branch, files=files, verbose=options.verbose, printed_path=printed_path)
self._AttemptRebase(upstream_branch, files, options, printed_path=printed_path)
def update(self, options, args, file_list): """Runs git to update or transparently checkout the working copy.
print "Trying fast-forward merge to branch : %s" % upstream_branch
options.stdout.write('Trying fast-forward merge to branch : %s\n' % upstream_branch)
def update(self, options, args, file_list): """Runs git to update or transparently checkout the working copy.
print "Skipping %s" % self.relpath
options.stdout.write('Skipping %s\n' % self.relpath)
def update(self, options, args, file_list): """Runs git to update or transparently checkout the working copy.
print "Input not recognized"
options.stdout.write('Input not recognized\n')
def update(self, options, args, file_list): """Runs git to update or transparently checkout the working copy.
print e.stderr
options.stdout.write(e.stderr + '\n')
def update(self, options, args, file_list): """Runs git to update or transparently checkout the working copy.
print "Merge produced error output:\n%s" % merge_err.strip()
options.stdout.write('Merge produced error output:\n%s\n' % merge_err.strip())
def update(self, options, args, file_list): """Runs git to update or transparently checkout the working copy.
print "Checked out revision %s" % self.revinfo(options, (), None)
options.stdout.write('Checked out revision %s\n' % self.revinfo(options, (), None))
def update(self, options, args, file_list): """Runs git to update or transparently checkout the working copy.
print("\n_____ %s is missing, synching instead" % self.relpath)
options.stdout.write('\n_____ %s is missing, synching instead\n' % self.relpath)
def revert(self, options, args, file_list): """Reverts local modifications.
print('\n________ couldn\'t run status in %s:\nThe directory ' 'does not exist.' % self.checkout_path)
options.stdout.write( ('\n________ couldn\'t run status in %s:\nThe directory ' 'does not exist.\n') % self.checkout_path)
def status(self, options, args, file_list): """Display status information.""" if not os.path.isdir(self.checkout_path): print('\n________ couldn\'t run status in %s:\nThe directory ' 'does not exist.' % self.checkout_path) else: merge_base = self._Run(['merge-base', 'HEAD', 'origin']) self._Run(['diff', '--name-status', merge_base], redirect_stdout=False) files = self._Run(['diff', '--name-only', merge_base]).split() file_list.extend([os.path.join(self.checkout_path, f) for f in files])
def _Clone(self, revision, url, verbose=False):
def _Clone(self, revision, url, options):
def _Clone(self, revision, url, verbose=False): """Clone a git repository from the given URL.
if not verbose:
if not options.verbose:
def _Clone(self, revision, url, verbose=False): """Clone a git repository from the given URL.
print ""
options.stdout.write('\n')
def _Clone(self, revision, url, verbose=False): """Clone a git repository from the given URL.
if verbose:
if options.verbose:
def _Clone(self, revision, url, verbose=False): """Clone a git repository from the given URL.
print str(e) print "Retrying..."
options.stdout.write(str(e) + '\n') options.stdout.write('Retrying...\n')
def _Clone(self, revision, url, verbose=False): """Clone a git repository from the given URL.
print \ "Checked out %s to a detached HEAD. Before making any commits\n" \ "in this repo, you should use 'git checkout <branch>' to switch to\n" \ "an existing branch or use 'git checkout origin -b <branch>' to\n" \ "create a new branch for your work." % revision def _AttemptRebase(self, upstream, files, verbose=False, newbase=None,
options.stdout.write( ('Checked out %s to a detached HEAD. Before making any commits\n' 'in this repo, you should use \'git checkout <branch>\' to switch to\n' 'an existing branch or use \'git checkout origin -b <branch>\' to\n' 'create a new branch for your work.') % revision) def _AttemptRebase(self, upstream, files, options, newbase=None,
def _Clone(self, revision, url, verbose=False): """Clone a git repository from the given URL.
print "\n_____ %s : Attempting rebase onto %s..." % (self.relpath, revision)
options.stdout.write('\n_____ %s : Attempting rebase onto %s...\n' % ( self.relpath, revision))
def _AttemptRebase(self, upstream, files, verbose=False, newbase=None, branch=None, printed_path=False): """Attempt to rebase onto either upstream or, if specified, newbase.""" files.extend(self._Run(['diff', upstream, '--name-only']).split()) revision = upstream if newbase: revision = newbase if not printed_path: print "\n_____ %s : Attempting rebase onto %s..." % (self.relpath, revision) printed_path = True else: print "Attempting rebase onto %s..." % revision
print "Attempting rebase onto %s..." % revision
options.stdout.write('Attempting rebase onto %s...\n' % revision)
def _AttemptRebase(self, upstream, files, verbose=False, newbase=None, branch=None, printed_path=False): """Attempt to rebase onto either upstream or, if specified, newbase.""" files.extend(self._Run(['diff', upstream, '--name-only']).split()) revision = upstream if newbase: revision = newbase if not printed_path: print "\n_____ %s : Attempting rebase onto %s..." % (self.relpath, revision) printed_path = True else: print "Attempting rebase onto %s..." % revision
if verbose:
if options.verbose:
def _AttemptRebase(self, upstream, files, verbose=False, newbase=None, branch=None, printed_path=False): """Attempt to rebase onto either upstream or, if specified, newbase.""" files.extend(self._Run(['diff', upstream, '--name-only']).split()) revision = upstream if newbase: revision = newbase if not printed_path: print "\n_____ %s : Attempting rebase onto %s..." % (self.relpath, revision) printed_path = True else: print "Attempting rebase onto %s..." % revision
print "\n%s" % e.stderr.strip()
options.stdout.write('\n%s\n' % e.stderr.strip())
def _AttemptRebase(self, upstream, files, verbose=False, newbase=None, branch=None, printed_path=False): """Attempt to rebase onto either upstream or, if specified, newbase.""" files.extend(self._Run(['diff', upstream, '--name-only']).split()) revision = upstream if newbase: revision = newbase if not printed_path: print "\n_____ %s : Attempting rebase onto %s..." % (self.relpath, revision) printed_path = True else: print "Attempting rebase onto %s..." % revision
print e.stdout.strip() print "Rebase produced error output:\n%s" % e.stderr.strip()
options.stdout.write(e.stdout.strip() + '\n') options.stdout.write('Rebase produced error output:\n%s\n' % e.stderr.strip())
def _AttemptRebase(self, upstream, files, verbose=False, newbase=None, branch=None, printed_path=False): """Attempt to rebase onto either upstream or, if specified, newbase.""" files.extend(self._Run(['diff', upstream, '--name-only']).split()) revision = upstream if newbase: revision = newbase if not printed_path: print "\n_____ %s : Attempting rebase onto %s..." % (self.relpath, revision) printed_path = True else: print "Attempting rebase onto %s..." % revision
print "Rebase produced error output:\n%s" % rebase_err.strip() if not verbose:
options.stdout.write('Rebase produced error output:\n%s\n' % rebase_err.strip()) if not options.verbose:
def _AttemptRebase(self, upstream, files, verbose=False, newbase=None, branch=None, printed_path=False): """Attempt to rebase onto either upstream or, if specified, newbase.""" files.extend(self._Run(['diff', upstream, '--name-only']).split()) revision = upstream if newbase: revision = newbase if not printed_path: print "\n_____ %s : Attempting rebase onto %s..." % (self.relpath, revision) printed_path = True else: print "Attempting rebase onto %s..." % revision
print ""
options.stdout.write('\n')
def _AttemptRebase(self, upstream, files, verbose=False, newbase=None, branch=None, printed_path=False): """Attempt to rebase onto either upstream or, if specified, newbase.""" files.extend(self._Run(['diff', upstream, '--name-only']).split()) revision = upstream if newbase: revision = newbase if not printed_path: print "\n_____ %s : Attempting rebase onto %s..." % (self.relpath, revision) printed_path = True else: print "Attempting rebase onto %s..." % revision
def _CheckDetachedHead(self, rev_str):
def _CheckDetachedHead(self, rev_str, options):
def _CheckDetachedHead(self, rev_str): # HEAD is detached. Make sure it is safe to move away from (i.e., it is # reference by a commit). If not, error out -- most likely a rebase is # in progress, try to detect so we can give a better error. try: _, _ = scm.GIT.Capture( ['name-rev', '--no-undefined', 'HEAD'], self.checkout_path, print_error=False) except gclient_utils.CheckCallError: # Commit is not contained by any rev. See if the user is rebasing: if self._IsRebasing(): # Punt to the user raise gclient_utils.Error('\n____ %s%s\n' '\tAlready in a conflict, i.e. (no branch).\n' '\tFix the conflict and run gclient again.\n' '\tOr to abort run:\n\t\tgit-rebase --abort\n' '\tSee man git-rebase for details.\n' % (self.relpath, rev_str)) # Let's just save off the commit so we can proceed. name = "saved-by-gclient-" + self._Run(["rev-parse", "--short", "HEAD"]) self._Run(["branch", name]) print ("\n_____ found an unreferenced commit and saved it as '%s'" % name)
print ("\n_____ found an unreferenced commit and saved it as '%s'" % name)
options.stdout.write( '\n_____ found an unreferenced commit and saved it as \'%s\'\n' % name)
def _CheckDetachedHead(self, rev_str): # HEAD is detached. Make sure it is safe to move away from (i.e., it is # reference by a commit). If not, error out -- most likely a rebase is # in progress, try to detect so we can give a better error. try: _, _ = scm.GIT.Capture( ['name-rev', '--no-undefined', 'HEAD'], self.checkout_path, print_error=False) except gclient_utils.CheckCallError: # Commit is not contained by any rev. See if the user is rebasing: if self._IsRebasing(): # Punt to the user raise gclient_utils.Error('\n____ %s%s\n' '\tAlready in a conflict, i.e. (no branch).\n' '\tFix the conflict and run gclient again.\n' '\tOr to abort run:\n\t\tgit-rebase --abort\n' '\tSee man git-rebase for details.\n' % (self.relpath, rev_str)) # Let's just save off the commit so we can proceed. name = "saved-by-gclient-" + self._Run(["rev-parse", "--short", "HEAD"]) self._Run(["branch", name]) print ("\n_____ found an unreferenced commit and saved it as '%s'" % name)
filterer = DiffFilterer(self.relpath)
filterer = DiffFilterer(self.relpath, options.stdout)
def pack(self, options, args, file_list): """Generates a patch file which can be applied to the root of the repository.""" path = os.path.join(self._root_dir, self.relpath) if not os.path.isdir(path): raise gclient_utils.Error('Directory %s is not present.' % path) command = ['svn', 'diff', '-x', '--ignore-eol-style'] command.extend(args)
print("________ found .git directory; skipping %s" % self.relpath)
options.stdout.write('________ found .git directory; skipping %s\n' % self.relpath)
def update(self, options, args, file_list): """Runs svn to update or transparently checkout the working copy.
print('\n_____ relocating %s to a new checkout' % self.relpath)
options.stdout.write('\n_____ relocating %s to a new checkout\n' % self.relpath)
def update(self, options, args, file_list): """Runs svn to update or transparently checkout the working copy.
print('\n_____ switching %s to a new checkout' % self.relpath)
options.stdout.write('\n_____ switching %s to a new checkout\n' % self.relpath)
def update(self, options, args, file_list): """Runs svn to update or transparently checkout the working copy.
print('\n_____ %s%s' % (self.relpath, rev_str))
options.stdout.write('\n_____ %s%s\n' % (self.relpath, rev_str))
def update(self, options, args, file_list): """Runs svn to update or transparently checkout the working copy.
print("\n_____ %s is missing, synching instead" % self.relpath)
options.stdout.write('\n_____ %s is missing, synching instead\n' % self.relpath)
def revert(self, options, args, file_list): """Reverts local modifications. Subversion specific.
print(file_path)
options.stdout.write(file_path + '\n')
def revert(self, options, args, file_list): """Reverts local modifications. Subversion specific.
print("\n________ couldn't run \'%s\' in \'%s\':\nThe directory " "does not exist." % (' '.join(command), path))
options.stdout.write( ('\n________ couldn\'t run \'%s\' in \'%s\':\nThe directory ' 'does not exist.') % (' '.join(command), path))
def status(self, options, args, file_list): """Display status information.""" path = os.path.join(self._root_dir, self.relpath) command = ['status'] + args if not os.path.isdir(path): # svn status won't work if the directory doesn't exist. print("\n________ couldn't run \'%s\' in \'%s\':\nThe directory " "does not exist." % (' '.join(command), path)) # There's no file list to retrieve. else: self._RunAndGetFileList(command, options, file_list)
command = ['diff']
command = ['diff', '-x', '--ignore-eol-style']
def pack(self, options, args, file_list): """Generates a patch file which can be applied to the root of the repository.""" path = os.path.join(self._root_dir, self.relpath) if not os.path.isdir(path): raise gclient_utils.Error('Directory %s is not present.' % path) command = ['diff'] command.extend(args)
if not content_array[0].startswith('svn: File not found:'): continue
if (content_array[0].startswith('svn: File not found:') or content_array[0].endswith('path not found')): break
def GetCachedFile(filename, max_age=60*60*24*3, use_root=False): """Retrieves a file from the repository and caches it in GetCacheDir() for max_age seconds. use_root: If False, look up the arborescence for the first match, otherwise go directory to the root repository. Note: The cache will be inconsistent if the same file is retrieved with both use_root=True and use_root=False. Don't be stupid. """ if filename not in FILES_CACHE: # Don't try to look up twice. FILES_CACHE[filename] = None # First we check if we have a cached version. try: cached_file = os.path.join(GetCacheDir(), filename) except gclient_utils.Error: return None if (not os.path.exists(cached_file) or (time.time() - os.stat(cached_file).st_mtime) > max_age): dir_info = SVN.CaptureInfo('.') repo_root = dir_info['Repository Root'] if use_root: url_path = repo_root else: url_path = dir_info['URL'] while True: # Look in the repository at the current level for the file. for _ in range(5): content = None try: # Take advantage of the fact that svn won't output to stderr in case # of success but will do in case of failure so don't mind putting # stderr into content_array. content_array = [] svn_path = url_path + '/' + filename args = ['svn', 'cat', svn_path] if sys.platform != 'darwin': # MacOSX 10.5.2 has a bug with svn 1.4.4 that will trigger the # 'Can\'t get username or password' and can be fixed easily. # The fix doesn't work if the user upgraded to svn 1.6.x. Bleh. # I don't have time to fix their broken stuff. args.append('--non-interactive') gclient_utils.CheckCallAndFilter( args, cwd='.', filter_fn=content_array.append) # Exit the loop if the file was found. Override content. content = '\n'.join(content_array) break except gclient_utils.Error: if content_array[0].startswith( 'svn: Can\'t get username or password'): ErrorExit('Your svn credentials expired. Please run svn update ' 'to fix the cached credentials') if content_array[0].startswith('svn: Can\'t get password'): ErrorExit('If are using a Mac and svn --version shows 1.4.x, ' 'please hack gcl.py to remove --non-interactive usage, it\'s' 'a bug on your installed copy') if not content_array[0].startswith('svn: File not found:'): # Try again. continue if content: break if url_path == repo_root: # Reached the root. Abandoning search. break # Go up one level to try again. url_path = os.path.dirname(url_path) if content is not None or filename != CODEREVIEW_SETTINGS_FILE: # Write a cached version even if there isn't a file, so we don't try to # fetch it each time. codereview.settings must always be present so do # not cache negative. gclient_utils.FileWrite(cached_file, content or '') else: content = gclient_utils.FileRead(cached_file, 'r') # Keep the content cached in memory. FILES_CACHE[filename] = content return FILES_CACHE[filename]
help="sync deps for the specified (comma-separated) " "platform(s); 'all' will sync all platforms")
help="override deps for the specified (comma-separated) " "platform(s); 'all' will process all deps_os " "references")
def CMDstatus(parser, args): """Show modification status for every dependencies.""" parser.add_option("--deps", dest="deps_os", metavar="OS_LIST", help="sync deps for the specified (comma-separated) " "platform(s); 'all' will sync all platforms") (options, args) = parser.parse_args(args) client = GClient.LoadCurrentConfig(options) if not client: raise gclient_utils.Error("client not configured; see 'gclient config'") if options.verbose: # Print out the .gclient file. This is longer than if we just printed the # client dict, but more legible, and it might contain helpful comments. print(client.ConfigContent()) return client.RunOnDeps('status', args)
help="sync deps for the specified (comma-separated) " "platform(s); 'all' will sync all platforms")
help="override deps for the specified (comma-separated) " "platform(s); 'all' will process all deps_os " "references")
def CMDsync(parser, args): """Checkout/update all modules.""" parser.add_option("--force", action="store_true", help="force update even for unchanged modules") parser.add_option("--nohooks", action="store_true", help="don't run hooks after the update is complete") parser.add_option("-r", "--revision", action="append", dest="revisions", metavar="REV", default=[], help="Enforces revision/hash for the primary solution. " "To modify a secondary solution, use it at least once " "for the primary solution and then use the format " "solution@rev/hash, e.g. -r src@123") parser.add_option("--head", action="store_true", help="skips any safesync_urls specified in " "configured solutions and sync to head instead") parser.add_option("--delete_unversioned_trees", action="store_true", help="delete any unexpected unversioned trees " "that are in the checkout") parser.add_option("--reset", action="store_true", help="resets any local changes before updating (git only)") parser.add_option("--deps", dest="deps_os", metavar="OS_LIST", help="sync deps for the specified (comma-separated) " "platform(s); 'all' will sync all platforms") parser.add_option("--manually_grab_svn_rev", action="store_true", help="Skip svn up whenever possible by requesting " "actual HEAD revision from the repository") (options, args) = parser.parse_args(args) client = GClient.LoadCurrentConfig(options) if not client: raise gclient_utils.Error("client not configured; see 'gclient config'") if not options.head: solutions = client.GetVar('solutions') if solutions: first = True for s in solutions: if s.get('safesync_url', None): # rip through revisions and make sure we're not over-riding # something that was explicitly passed has_key = False r_first = True for r in options.revisions: if (first and r_first) or r.split('@', 1)[0] == s['name']: has_key = True break r_first = False if not has_key: handle = urllib.urlopen(s['safesync_url']) rev = handle.read().strip() handle.close() if len(rev): options.revisions.append(s['name']+'@'+rev) first = False if options.verbose: # Print out the .gclient file. This is longer than if we just printed the # client dict, but more legible, and it might contain helpful comments. print(client.ConfigContent()) return client.RunOnDeps('update', args)
help="sync deps for the specified (comma-separated) " "platform(s); 'all' will sync all platforms")
help="override deps for the specified (comma-separated) " "platform(s); 'all' will process all deps_os " "references")
def CMDrevert(parser, args): """Revert all modifications in every dependencies.""" parser.add_option("--deps", dest="deps_os", metavar="OS_LIST", help="sync deps for the specified (comma-separated) " "platform(s); 'all' will sync all platforms") parser.add_option("--nohooks", action="store_true", help="don't run hooks after the revert is complete") (options, args) = parser.parse_args(args) # --force is implied. options.force = True client = GClient.LoadCurrentConfig(options) if not client: raise gclient_utils.Error("client not configured; see 'gclient config'") return client.RunOnDeps('revert', args)
help="sync deps for the specified (comma-separated) " "platform(s); 'all' will sync all platforms")
help="override deps for the specified (comma-separated) " "platform(s); 'all' will process all deps_os " "references")
def CMDrunhooks(parser, args): """Runs hooks for files that have been modified in the local working copy.""" parser.add_option("--deps", dest="deps_os", metavar="OS_LIST", help="sync deps for the specified (comma-separated) " "platform(s); 'all' will sync all platforms") parser.add_option("--force", action="store_true", default=True, help="Deprecated. No effect.") (options, args) = parser.parse_args(args) client = GClient.LoadCurrentConfig(options) if not client: raise gclient_utils.Error("client not configured; see 'gclient config'") if options.verbose: # Print out the .gclient file. This is longer than if we just printed the # client dict, but more legible, and it might contain helpful comments. print(client.ConfigContent()) options.force = True options.nohooks = False return client.RunOnDeps('runhooks', args)
options.deps_os = None
def CMDrevinfo(parser, args): """Outputs details for every dependencies.""" parser.add_option("--snapshot", action="store_true", help="create a snapshot file of the current " "version of all repositories") (options, args) = parser.parse_args(args) client = GClient.LoadCurrentConfig(options) options.deps_os = None if not client: raise gclient_utils.Error("client not configured; see 'gclient config'") client.PrintRevInfo() return 0
elif os.path.isfile(file_path):
elif os.path.isfile(file_path) or os.path.islink(file_path):
def revert(self, options, args, file_list): """Reverts local modifications. Subversion specific.
entries = {} entries_deps_content = {}
def PrintRevInfo(self): """Output revision info mapping for the client and its dependencies. This allows the capture of an overall "revision" for the source tree that can be used to reproduce the same tree in the future. The actual output contains enough information (source paths, svn server urls and revisions) that it can be used either to generate external svn commands (without gclient) or as input to gclient's --rev option (with some massaging of the data).
if name in entries:
if name in solution_names:
def GetURLAndRev(name, original_url): url, revision = gclient_utils.SplitUrlRevision(original_url) if not revision: if revision_overrides.has_key(name): return (url, revision_overrides[name]) else: scm = gclient_scm.CreateSCM(solution["url"], self._root_dir, name) return (url, scm.revinfo(self._options, [], None)) else: if revision_overrides.has_key(name): return (url, revision_overrides[name]) else: return (url, revision)
deps = self._ParseAllDeps(entries, entries_deps_content) deps_to_process = deps.keys() deps_to_process.sort() for d in deps_to_process: if type(deps[d]) == str: (url, rev) = GetURLAndRev(d, deps[d]) entries[d] = "%s@%s" % (url, rev) for d in deps_to_process: if type(deps[d]) != str: deps_parent_url = entries[deps[d].module_name] if deps_parent_url.find("@") < 0: raise gclient_utils.Error("From %s missing revisioned url" % deps[d].module_name) content = gclient_utils.FileRead(os.path.join(self._root_dir, deps[d].module_name, self._options.deps_file)) sub_deps = self._ParseSolutionDeps(deps[d].module_name, content, {}) (url, rev) = GetURLAndRev(d, sub_deps[d]) entries[d] = "%s@%s" % (url, rev) print(";\n".join(["%s: %s" % (x, entries[x]) for x in sorted(entries.keys())]))
deps = self._ParseAllDeps(entries, entries_deps_content) deps_to_process = deps.keys() deps_to_process.sort() for d in deps_to_process: if type(deps[d]) == str: (url, rev) = GetURLAndRev(d, deps[d]) entries[d] = "%s@%s" % (url, rev) for d in deps_to_process: if type(deps[d]) != str: deps_parent_url = entries[deps[d].module_name] if deps_parent_url.find("@") < 0: raise gclient_utils.Error("From %s missing revisioned url" % deps[d].module_name) content = gclient_utils.FileRead(os.path.join( self._root_dir, deps[d].module_name, self._options.deps_file)) sub_deps = self._ParseSolutionDeps(deps[d].module_name, content, {}) (url, rev) = GetURLAndRev(d, sub_deps[d]) entries[d] = "%s@%s" % (url, rev) if self._options.snapshot: url = entries.pop(name) custom_deps = ",\n ".join(["\"%s\": \"%s\"" % (x, entries[x]) for x in sorted(entries.keys())]) new_gclient += DEFAULT_SNAPSHOT_SOLUTION_TEXT % { 'solution_name': name, 'solution_url': url, 'safesync_url' : "", 'solution_deps': custom_deps, } else: print(";\n".join(["%s: %s" % (x, entries[x]) for x in sorted(entries.keys())])) if self._options.snapshot: config = DEFAULT_SNAPSHOT_FILE_TEXT % {'solution_list': new_gclient} snapclient = GClient(self._root_dir, self._options) snapclient.SetConfig(config) print(snapclient._config_content)
def GetURLAndRev(name, original_url): url, revision = gclient_utils.SplitUrlRevision(original_url) if not revision: if revision_overrides.has_key(name): return (url, revision_overrides[name]) else: scm = gclient_scm.CreateSCM(solution["url"], self._root_dir, name) return (url, scm.revinfo(self._options, [], None)) else: if revision_overrides.has_key(name): return (url, revision_overrides[name]) else: return (url, revision)
options.entries_filename = ".gclient_entries"
if options.gclientfile: options.config_filename = options.gclientfile options.entries_filename = options.config_filename + "_entries"
def Main(argv): """Parse command line arguments and dispatch command.""" option_parser = optparse.OptionParser(usage=DEFAULT_USAGE_TEXT, version=__version__) option_parser.disable_interspersed_args() option_parser.add_option("", "--force", action="store_true", default=False, help=("(update/sync only) force update even " "for modules which haven't changed")) option_parser.add_option("", "--nohooks", action="store_true", default=False, help=("(update/sync/revert only) prevent the hooks from " "running")) option_parser.add_option("", "--revision", action="append", dest="revisions", metavar="REV", default=[], help=("(update/sync only) sync to a specific " "revision, can be used multiple times for " "each solution, e.g. --revision=src@123, " "--revision=internal@32")) option_parser.add_option("", "--deps", default=None, dest="deps_os", metavar="OS_LIST", help=("(update/sync only) sync deps for the " "specified (comma-separated) platform(s); " "'all' will sync all platforms")) option_parser.add_option("", "--reset", action="store_true", default=False, help=("(update/sync only) resets any local changes " "before updating (git only)")) option_parser.add_option("", "--spec", default=None, help=("(config only) create a gclient file " "containing the provided string")) option_parser.add_option("-v", "--verbose", action="count", default=0, help="produce additional output for diagnostics") option_parser.add_option("", "--manually_grab_svn_rev", action="store_true", default=False, help="Skip svn up whenever possible by requesting " "actual HEAD revision from the repository") option_parser.add_option("", "--head", action="store_true", default=False, help=("skips any safesync_urls specified in " "configured solutions")) option_parser.add_option("", "--delete_unversioned_trees", action="store_true", default=False, help=("on update, delete any unexpected " "unversioned trees that are in the checkout")) if len(argv) < 2: # Users don't need to be told to use the 'help' command. option_parser.print_help() return 1 # Add manual support for --version as first argument. if argv[1] == '--version': option_parser.print_version() return 0 # Add manual support for --help as first argument. if argv[1] == '--help': argv[1] = 'help' command = argv[1] options, args = option_parser.parse_args(argv[2:]) if len(argv) < 3 and command == "help": option_parser.print_help() return 0 if options.verbose > 1: logging.basicConfig(level=logging.DEBUG) # Files used for configuration and state saving. options.config_filename = os.environ.get("GCLIENT_FILE", ".gclient") options.entries_filename = ".gclient_entries" options.deps_file = "DEPS" options.platform = sys.platform return DispatchCommand(command, options, args)
except gclient_utils.CheckCallError:
except gclient_utils.CheckCallError, e:
def update(self, options, args, file_list): """Runs git to update or transparently checkout the working copy.
f = open("drover.properties") exec(f) f.close()
FILE_PATTERN = file_pattern_ execfile("drover.properties")
def drover(options, args): revision = options.revert or options.merge # Initialize some variables used below. They can be overwritten by # the drover.properties file. BASE_URL = "svn://svn.chromium.org/chrome" TRUNK_URL = BASE_URL + "/trunk/src" BRANCH_URL = BASE_URL + "/branches/$branch/src" SKIP_CHECK_WORKING = True PROMPT_FOR_AUTHOR = False DEFAULT_WORKING = "drover_" + str(revision) if options.branch: DEFAULT_WORKING += ("_" + options.branch) if not isMinimumSVNVersion(1, 5): print "You need to use at least SVN version 1.5.x" return 1 # Override the default properties if there is a drover.properties file. global file_pattern_ if os.path.exists("drover.properties"): f = open("drover.properties") exec(f) f.close() if FILE_PATTERN: file_pattern_ = FILE_PATTERN if options.revert and options.branch: url = BRANCH_URL.replace("$branch", options.branch) elif options.merge and options.sbranch: url = BRANCH_URL.replace("$branch", options.sbranch) else: url = TRUNK_URL working = options.workdir or DEFAULT_WORKING if options.local: working = os.getcwd() if not inCheckoutRoot(working): print "'%s' appears not to be the root of a working copy" % working return 1 if (isSVNDirty() and not prompt("Working copy contains uncommitted files. Continue?")): return 1 command = 'svn log ' + url + " -r "+str(revision) + " -v" os.system(command) if not (options.revertbot or prompt("Is this the correct revision?")): return 0 if (os.path.exists(working)) and not options.local: if not (options.revertbot or SKIP_CHECK_WORKING or prompt("Working directory: '%s' already exists, clobber?" % working)): return 0 gclient_utils.RemoveDirectory(working) if not options.local: os.makedirs(working) os.chdir(working) if options.merge: action = "Merge" if not options.local: branch_url = BRANCH_URL.replace("$branch", options.branch) # Checkout everything but stuff that got added into a new dir checkoutRevision(url, revision, branch_url) # Merge everything that changed mergeRevision(url, revision) # "Export" files that were added from the source and add them to branch exportRevision(url, revision) # Delete directories that were deleted (file deletes are handled in the # merge). deleteRevision(url, revision) elif options.revert: action = "Revert" if options.branch: url = BRANCH_URL.replace("$branch", options.branch) checkoutRevision(url, revision, url, True) revertRevision(url, revision) revertExportRevision(url, revision) # Check the base url so we actually find the author who made the change if options.auditor: author = options.auditor else: author = getAuthor(url, revision) if not author: author = getAuthor(TRUNK_URL, revision) filename = str(revision)+".txt" out = open(filename,"w") out.write(action +" " + str(revision) + " - ") out.write(getRevisionLog(url, revision)) if (author): out.write("\nTBR=" + author) out.close() change_cmd = 'change ' + str(revision) + " " + filename if options.revertbot: change_cmd += ' --silent' runGcl(change_cmd) os.unlink(filename) if options.local: return 0 print author print revision print ("gcl upload " + str(revision) + " --send_mail --no_presubmit --reviewers=" + author) if options.revertbot or prompt("Would you like to upload?"): if PROMPT_FOR_AUTHOR: author = text_prompt("Enter new author or press enter to accept default", author) if options.revertbot and options.revertbot_reviewers: author += "," author += options.revertbot_reviewers gclUpload(revision, author) else: print "Deleting the changelist." print "gcl delete " + str(revision) runGcl("delete " + str(revision)) return 0 # We commit if the reverbot is set to commit automatically, or if this is # not the revertbot and the user agrees. if options.revertbot_commit or (not options.revertbot and prompt("Would you like to commit?")): print "gcl commit " + str(revision) + " --no_presubmit --force" return runGcl("commit " + str(revision) + " --no_presubmit --force") else: return 0
dir_info = SVN.CaptureInfo(".") repo_root = dir_info["Repository Root"]
dir_info = SVN.CaptureInfo('.') repo_root = dir_info['Repository Root']
def GetCachedFile(filename, max_age=60*60*24*3, use_root=False): """Retrieves a file from the repository and caches it in GetCacheDir() for max_age seconds. use_root: If False, look up the arborescence for the first match, otherwise go directory to the root repository. Note: The cache will be inconsistent if the same file is retrieved with both use_root=True and use_root=False. Don't be stupid. """ if filename not in FILES_CACHE: # Don't try to look up twice. FILES_CACHE[filename] = None # First we check if we have a cached version. try: cached_file = os.path.join(GetCacheDir(), filename) except gclient_utils.Error: return None if (not os.path.exists(cached_file) or (time.time() - os.stat(cached_file).st_mtime) > max_age): dir_info = SVN.CaptureInfo(".") repo_root = dir_info["Repository Root"] if use_root: url_path = repo_root else: url_path = dir_info["URL"] while True: # Look in the repository at the current level for the file. for _ in range(5): content = "" try: # Take advantage of the fact that svn won't output to stderr in case # of success but will do in case of failure so don't mind putting # stderr into content_array. content_array = [] svn_path = url_path + "/" + filename args = ['cat', svn_path] if sys.platform != 'darwin': # MacOSX 10.5.2 has a bug with svn 1.4.4 that will trigger the # 'Can\'t get username or password' and can be fixed easily. # The fix doesn't work if the user upgraded to svn 1.6.x. Bleh. # I don't have time to fix their broken stuff. args.append('--non-interactive') SVN.RunAndFilterOutput(args, cwd='.', filter_fn=content_array.append) # Exit the loop if the file was found. Override content. content = '\n'.join(content_array) break except gclient_utils.Error: if content_array[0].startswith( 'svn: Can\'t get username or password'): ErrorExit('Your svn credentials expired. Please run svn update ' 'to fix the cached credentials') if content_array[0].startswith('svn: Can\'t get password'): ErrorExit('If are using a Mac and svn --version shows 1.4.x, ' 'please hack gcl.py to remove --non-interactive usage, it\'s' 'a bug on your installed copy') if not content_array[0].startswith('svn: File not found:'): # Try again. continue if content: break if url_path == repo_root: # Reached the root. Abandoning search. break # Go up one level to try again. url_path = os.path.dirname(url_path) # Write a cached version even if there isn't a file, so we don't try to # fetch it each time. gclient_utils.FileWrite(cached_file, content) else: content = gclient_utils.FileRead(cached_file, 'r') # Keep the content cached in memory. FILES_CACHE[filename] = content return FILES_CACHE[filename]
url_path = dir_info["URL"]
url_path = dir_info['URL']
def GetCachedFile(filename, max_age=60*60*24*3, use_root=False): """Retrieves a file from the repository and caches it in GetCacheDir() for max_age seconds. use_root: If False, look up the arborescence for the first match, otherwise go directory to the root repository. Note: The cache will be inconsistent if the same file is retrieved with both use_root=True and use_root=False. Don't be stupid. """ if filename not in FILES_CACHE: # Don't try to look up twice. FILES_CACHE[filename] = None # First we check if we have a cached version. try: cached_file = os.path.join(GetCacheDir(), filename) except gclient_utils.Error: return None if (not os.path.exists(cached_file) or (time.time() - os.stat(cached_file).st_mtime) > max_age): dir_info = SVN.CaptureInfo(".") repo_root = dir_info["Repository Root"] if use_root: url_path = repo_root else: url_path = dir_info["URL"] while True: # Look in the repository at the current level for the file. for _ in range(5): content = "" try: # Take advantage of the fact that svn won't output to stderr in case # of success but will do in case of failure so don't mind putting # stderr into content_array. content_array = [] svn_path = url_path + "/" + filename args = ['cat', svn_path] if sys.platform != 'darwin': # MacOSX 10.5.2 has a bug with svn 1.4.4 that will trigger the # 'Can\'t get username or password' and can be fixed easily. # The fix doesn't work if the user upgraded to svn 1.6.x. Bleh. # I don't have time to fix their broken stuff. args.append('--non-interactive') SVN.RunAndFilterOutput(args, cwd='.', filter_fn=content_array.append) # Exit the loop if the file was found. Override content. content = '\n'.join(content_array) break except gclient_utils.Error: if content_array[0].startswith( 'svn: Can\'t get username or password'): ErrorExit('Your svn credentials expired. Please run svn update ' 'to fix the cached credentials') if content_array[0].startswith('svn: Can\'t get password'): ErrorExit('If are using a Mac and svn --version shows 1.4.x, ' 'please hack gcl.py to remove --non-interactive usage, it\'s' 'a bug on your installed copy') if not content_array[0].startswith('svn: File not found:'): # Try again. continue if content: break if url_path == repo_root: # Reached the root. Abandoning search. break # Go up one level to try again. url_path = os.path.dirname(url_path) # Write a cached version even if there isn't a file, so we don't try to # fetch it each time. gclient_utils.FileWrite(cached_file, content) else: content = gclient_utils.FileRead(cached_file, 'r') # Keep the content cached in memory. FILES_CACHE[filename] = content return FILES_CACHE[filename]
content = ""
content = None
def GetCachedFile(filename, max_age=60*60*24*3, use_root=False): """Retrieves a file from the repository and caches it in GetCacheDir() for max_age seconds. use_root: If False, look up the arborescence for the first match, otherwise go directory to the root repository. Note: The cache will be inconsistent if the same file is retrieved with both use_root=True and use_root=False. Don't be stupid. """ if filename not in FILES_CACHE: # Don't try to look up twice. FILES_CACHE[filename] = None # First we check if we have a cached version. try: cached_file = os.path.join(GetCacheDir(), filename) except gclient_utils.Error: return None if (not os.path.exists(cached_file) or (time.time() - os.stat(cached_file).st_mtime) > max_age): dir_info = SVN.CaptureInfo(".") repo_root = dir_info["Repository Root"] if use_root: url_path = repo_root else: url_path = dir_info["URL"] while True: # Look in the repository at the current level for the file. for _ in range(5): content = "" try: # Take advantage of the fact that svn won't output to stderr in case # of success but will do in case of failure so don't mind putting # stderr into content_array. content_array = [] svn_path = url_path + "/" + filename args = ['cat', svn_path] if sys.platform != 'darwin': # MacOSX 10.5.2 has a bug with svn 1.4.4 that will trigger the # 'Can\'t get username or password' and can be fixed easily. # The fix doesn't work if the user upgraded to svn 1.6.x. Bleh. # I don't have time to fix their broken stuff. args.append('--non-interactive') SVN.RunAndFilterOutput(args, cwd='.', filter_fn=content_array.append) # Exit the loop if the file was found. Override content. content = '\n'.join(content_array) break except gclient_utils.Error: if content_array[0].startswith( 'svn: Can\'t get username or password'): ErrorExit('Your svn credentials expired. Please run svn update ' 'to fix the cached credentials') if content_array[0].startswith('svn: Can\'t get password'): ErrorExit('If are using a Mac and svn --version shows 1.4.x, ' 'please hack gcl.py to remove --non-interactive usage, it\'s' 'a bug on your installed copy') if not content_array[0].startswith('svn: File not found:'): # Try again. continue if content: break if url_path == repo_root: # Reached the root. Abandoning search. break # Go up one level to try again. url_path = os.path.dirname(url_path) # Write a cached version even if there isn't a file, so we don't try to # fetch it each time. gclient_utils.FileWrite(cached_file, content) else: content = gclient_utils.FileRead(cached_file, 'r') # Keep the content cached in memory. FILES_CACHE[filename] = content return FILES_CACHE[filename]
svn_path = url_path + "/" + filename
svn_path = url_path + '/' + filename
def GetCachedFile(filename, max_age=60*60*24*3, use_root=False): """Retrieves a file from the repository and caches it in GetCacheDir() for max_age seconds. use_root: If False, look up the arborescence for the first match, otherwise go directory to the root repository. Note: The cache will be inconsistent if the same file is retrieved with both use_root=True and use_root=False. Don't be stupid. """ if filename not in FILES_CACHE: # Don't try to look up twice. FILES_CACHE[filename] = None # First we check if we have a cached version. try: cached_file = os.path.join(GetCacheDir(), filename) except gclient_utils.Error: return None if (not os.path.exists(cached_file) or (time.time() - os.stat(cached_file).st_mtime) > max_age): dir_info = SVN.CaptureInfo(".") repo_root = dir_info["Repository Root"] if use_root: url_path = repo_root else: url_path = dir_info["URL"] while True: # Look in the repository at the current level for the file. for _ in range(5): content = "" try: # Take advantage of the fact that svn won't output to stderr in case # of success but will do in case of failure so don't mind putting # stderr into content_array. content_array = [] svn_path = url_path + "/" + filename args = ['cat', svn_path] if sys.platform != 'darwin': # MacOSX 10.5.2 has a bug with svn 1.4.4 that will trigger the # 'Can\'t get username or password' and can be fixed easily. # The fix doesn't work if the user upgraded to svn 1.6.x. Bleh. # I don't have time to fix their broken stuff. args.append('--non-interactive') SVN.RunAndFilterOutput(args, cwd='.', filter_fn=content_array.append) # Exit the loop if the file was found. Override content. content = '\n'.join(content_array) break except gclient_utils.Error: if content_array[0].startswith( 'svn: Can\'t get username or password'): ErrorExit('Your svn credentials expired. Please run svn update ' 'to fix the cached credentials') if content_array[0].startswith('svn: Can\'t get password'): ErrorExit('If are using a Mac and svn --version shows 1.4.x, ' 'please hack gcl.py to remove --non-interactive usage, it\'s' 'a bug on your installed copy') if not content_array[0].startswith('svn: File not found:'): # Try again. continue if content: break if url_path == repo_root: # Reached the root. Abandoning search. break # Go up one level to try again. url_path = os.path.dirname(url_path) # Write a cached version even if there isn't a file, so we don't try to # fetch it each time. gclient_utils.FileWrite(cached_file, content) else: content = gclient_utils.FileRead(cached_file, 'r') # Keep the content cached in memory. FILES_CACHE[filename] = content return FILES_CACHE[filename]
gclient_utils.FileWrite(cached_file, content)
if content is not None or filename != CODEREVIEW_SETTINGS_FILE: gclient_utils.FileWrite(cached_file, content or '')
def GetCachedFile(filename, max_age=60*60*24*3, use_root=False): """Retrieves a file from the repository and caches it in GetCacheDir() for max_age seconds. use_root: If False, look up the arborescence for the first match, otherwise go directory to the root repository. Note: The cache will be inconsistent if the same file is retrieved with both use_root=True and use_root=False. Don't be stupid. """ if filename not in FILES_CACHE: # Don't try to look up twice. FILES_CACHE[filename] = None # First we check if we have a cached version. try: cached_file = os.path.join(GetCacheDir(), filename) except gclient_utils.Error: return None if (not os.path.exists(cached_file) or (time.time() - os.stat(cached_file).st_mtime) > max_age): dir_info = SVN.CaptureInfo(".") repo_root = dir_info["Repository Root"] if use_root: url_path = repo_root else: url_path = dir_info["URL"] while True: # Look in the repository at the current level for the file. for _ in range(5): content = "" try: # Take advantage of the fact that svn won't output to stderr in case # of success but will do in case of failure so don't mind putting # stderr into content_array. content_array = [] svn_path = url_path + "/" + filename args = ['cat', svn_path] if sys.platform != 'darwin': # MacOSX 10.5.2 has a bug with svn 1.4.4 that will trigger the # 'Can\'t get username or password' and can be fixed easily. # The fix doesn't work if the user upgraded to svn 1.6.x. Bleh. # I don't have time to fix their broken stuff. args.append('--non-interactive') SVN.RunAndFilterOutput(args, cwd='.', filter_fn=content_array.append) # Exit the loop if the file was found. Override content. content = '\n'.join(content_array) break except gclient_utils.Error: if content_array[0].startswith( 'svn: Can\'t get username or password'): ErrorExit('Your svn credentials expired. Please run svn update ' 'to fix the cached credentials') if content_array[0].startswith('svn: Can\'t get password'): ErrorExit('If are using a Mac and svn --version shows 1.4.x, ' 'please hack gcl.py to remove --non-interactive usage, it\'s' 'a bug on your installed copy') if not content_array[0].startswith('svn: File not found:'): # Try again. continue if content: break if url_path == repo_root: # Reached the root. Abandoning search. break # Go up one level to try again. url_path = os.path.dirname(url_path) # Write a cached version even if there isn't a file, so we don't try to # fetch it each time. gclient_utils.FileWrite(cached_file, content) else: content = gclient_utils.FileRead(cached_file, 'r') # Keep the content cached in memory. FILES_CACHE[filename] = content return FILES_CACHE[filename]
socket.getfqdn().endswith('.google.com')):
socket.getfqdn().endswith('.google.com') and not 'NO_BREAKPAD' in os.environ):
def Register(): """Registers the callback at exit. Calling it multiple times is no-op.""" global _REGISTERED if _REGISTERED: return _REGISTERED = True atexit.register(CheckForException)
'and retry or visit go/isgaeup.\n%s') % (e.code, e.reason)
'and retry or visit go/isgaeup.\n%s') % (e.code, str(e))
def main(argv): if not argv: argv = ['help'] command = Command(argv[0]) # Help can be run from anywhere. if command == CMDhelp: return command(argv[1:]) try: GetRepositoryRoot() except gclient_utils.Error: print >> sys.stderr, 'To use gcl, you need to be in a subversion checkout.' return 1 # Create the directories where we store information about changelists if it # doesn't exist. try: if not os.path.exists(GetInfoDir()): os.mkdir(GetInfoDir()) if not os.path.exists(GetChangesDir()): os.mkdir(GetChangesDir()) if not os.path.exists(GetCacheDir()): os.mkdir(GetCacheDir()) if command: return command(argv[1:]) # Unknown command, try to pass that to svn return CMDpassthru(argv) except gclient_utils.Error, e: print >> sys.stderr, 'Got an exception' print >> sys.stderr, str(e) return 1 except urllib2.HTTPError, e: if e.code != 500: raise print >> sys.stderr, ( 'AppEngine is misbehaving and returned HTTP %d, again. Keep faith ' 'and retry or visit go/isgaeup.\n%s') % (e.code, e.reason) return 1
if (filter(lambda x: '502 Bad Gateway' in x, failure) or (len(failure) and len(file_list) > previous_list_len)): if args[0] == 'checkout':
if args[0] == 'checkout': if len(file_list) == previous_list_len: for x in failure: if ('502 Bad Gateway' in x or 'svn: REPORT of \'/svn/!svn/vcc/default\': 200 OK' in x): if os.path.isdir(args[2]): chromium_utils.RemoveDirectory(args[2]) break else: raise else:
def CaptureMatchingLines(line): match = compiled_pattern.search(line) if match: file_list.append(match.group(1)) if line.startswith('svn: '): failure.append(line)
print "Sleeping 15 seconds and retrying...." time.sleep(15) continue raise
else: if len(file_list) == previous_list_len: for x in failure: if ('502 Bad Gateway' in x or 'svn: REPORT of \'/svn/!svn/vcc/default\': 200 OK' in x): break else: raise else: pass print "Sleeping 15 seconds and retrying...." time.sleep(15) continue
def CaptureMatchingLines(line): match = compiled_pattern.search(line) if match: file_list.append(match.group(1)) if line.startswith('svn: '): failure.append(line)
self._long_text.encode('ascii', 'replace'))
long_text)
def _Handle(self, output_stream, input_stream, may_prompt=True): """Writes this result to the output stream.
if issue == "None":
try: description = gcl.GetIssueDescription(int(issue)) except ValueError:
def __init__(self, commit=None, upstream_branch=None): self.commit = commit self.verbose = None self.default_presubmit = None self.may_prompt = None
else: description = gcl.GetIssueDescription(int(issue))
def __init__(self, commit=None, upstream_branch=None): self.commit = commit self.verbose = None self.default_presubmit = None self.may_prompt = None
failure.append(True)
failure.append(line)
def CaptureMatchingLines(line): match = compiled_pattern.search(line) if match: file_list.append(match.group(1)) if line.startswith('svn: '): # We can't raise an exception. We can't alias a variable. Use a cheap # way. failure.append(True)
print 'Do you want to send a crash report [y/N]? ', if sys.stdin.read(1).lower() != 'y': return
def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'): print 'Do you want to send a crash report [y/N]? ', if sys.stdin.read(1).lower() != 'y': return print 'Sending crash report ...' try: params = { 'args': sys.argv, 'stack': stack, 'user': getpass.getuser(), } request = urllib.urlopen(url, urllib.urlencode(params)) print request.read() request.close() except IOError: print('There was a failure while trying to send the stack trace. Too bad.')
if in_byte == '\n' and filter_fn: filter_fn(in_line)
if in_byte == '\n': if filter_fn: filter_fn(in_line)
def SubprocessCallAndFilter(command, in_directory, print_messages, print_stdout, fail_status=None, filter_fn=None): """Runs command, a list, in directory in_directory. If print_messages is true, a message indicating what is being done is printed to stdout. If print_messages is false, the message is printed only if we actually need to print something else as well, so you can get the context of the output. If print_messages is false and print_stdout is false, no output at all is generated. Also, if print_stdout is true, the command's stdout is also forwarded to stdout. If a filter_fn function is specified, it is expected to take a single string argument, and it will be called with each line of the subprocess's output. Each line has had the trailing newline character trimmed. If the command fails, as indicated by a nonzero exit status, gclient will exit with an exit status of fail_status. If fail_status is None (the default), gclient will raise an Error exception. """ logging.debug(command) if print_messages: print('\n________ running \'%s\' in \'%s\'' % (' '.join(command), in_directory)) # *Sigh*: Windows needs shell=True, or else it won't search %PATH% for the # executable, but shell=True makes subprocess on Linux fail when it's called # with a list because it only tries to execute the first item in the list. kid = subprocess.Popen(command, bufsize=0, cwd=in_directory, shell=(sys.platform == 'win32'), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # Also, we need to forward stdout to prevent weird re-ordering of output. # This has to be done on a per byte basis to make sure it is not buffered: # normally buffering is done for each line, but if svn requests input, no # end-of-line character is output after the prompt and it would not show up. in_byte = kid.stdout.read(1) in_line = '' while in_byte: if in_byte != '\r': if print_stdout: if not print_messages: print('\n________ running \'%s\' in \'%s\'' % (' '.join(command), in_directory)) print_messages = True sys.stdout.write(in_byte) if in_byte != '\n': in_line += in_byte if in_byte == '\n' and filter_fn: filter_fn(in_line) in_line = '' in_byte = kid.stdout.read(1) rv = kid.wait() if rv: msg = 'failed to run command: %s' % ' '.join(command) if fail_status != None: print >>sys.stderr, msg sys.exit(fail_status) raise Error(msg)
root, entries = gclient_utils.GetGClientRootAndEntries()
root_and_entries = gclient_utils.GetGClientRootAndEntries() if not root_and_entries: print >> sys.stderr, ( 'You need to run gclient sync at least once to use \'recurse\'.\n' 'This is because .gclient_entries needs to exist and be up to date.') return 1 root, entries = root_and_entries
def CMDrecurse(parser, args): """Operates on all the entries. Runs a shell command on all entries. """ # Stop parsing at the first non-arg so that these go through to the command parser.disable_interspersed_args() parser.add_option('-s', '--scm', action='append', default=[], help='choose scm types to operate upon') options, args = parser.parse_args(args) root, entries = gclient_utils.GetGClientRootAndEntries() scm_set = set() for scm in options.scm: scm_set.update(scm.split(',')) # Pass in the SCM type as an env variable env = os.environ.copy() for path, url in entries.iteritems(): scm = gclient_scm.GetScmName(url) if scm_set and scm not in scm_set: continue cwd = os.path.normpath(os.path.join(root, path)) if scm: env['GCLIENT_SCM'] = scm if url: env['GCLIENT_URL'] = url gclient_utils.Popen(args, cwd=cwd, env=env).communicate() return 0
data = [("description", self.description),]
xsrf_token = self.SendToRietveld( '/xsrf_token', extra_headers={'X-Requesting-XSRF-Token': '1'}) data = [("description", self.description), ("xsrf_token", xsrf_token)]
def CloseIssue(self): """Closes the Rietveld issue for this changelist.""" data = [("description", self.description),] ctype, body = upload.EncodeMultipartFormData(data, []) self.SendToRietveld('/%d/close' % self.issue, body, ctype)