def run_in_pager(cmd_class): class wrapped_cmd_class(cmd_class): __doc__ = cmd_class.__doc__ def run(self, **kwargs): setup_pager() cmd_class.run(self, **kwargs) wrapped_cmd_class.__name__ = cmd_class.__name__ register_command(wrapped_cmd_class, decorate=True)
def test_replace_utf8(self): def bzr(*args, **kwargs): kwargs["encoding"] = "utf-8" return self.run_bzr(*args, **kwargs)[0] register_command(cmd_echo_replace) try: self.assertEqual("foo", bzr("echo-replace foo")) self.assertEqual(u"foo\xb5".encode("utf-8"), bzr(["echo-replace", u"foo\xb5"])) finally: plugin_cmds.remove("echo-replace")
def test_strict_utf8(self): def bzr(*args, **kwargs): kwargs['encoding'] = 'utf-8' return self.run_bzr(*args, **kwargs)[0] register_command(cmd_echo_strict) try: self.assertEqual('foo', bzr('echo-strict foo')) self.assertEqual(u'foo\xb5'.encode('utf-8'), bzr(['echo-strict', u'foo\xb5'])) finally: plugin_cmds.remove('echo-strict')
def test_replace_ascii(self): def bzr(*args, **kwargs): kwargs['encoding'] = 'ascii' return self.run_bzr(*args, **kwargs)[0] register_command(cmd_echo_replace) try: self.assertEqual('foo', bzr('echo-replace foo')) # ascii can't encode \xb5 self.assertEqual('foo?', bzr(['echo-replace', u'foo\xb5'])) finally: plugin_cmds.pop('echo-replace')
def test_replace_utf8(self): def bzr(*args, **kwargs): kwargs['encoding'] = 'utf-8' return self.run_bzr(*args, **kwargs)[0] register_command(cmd_echo_replace) try: self.assertEqual('foo', bzr('echo-replace foo')) self.assertEqual(u'foo\xb5'.encode('utf-8'), bzr(['echo-replace', u'foo\xb5'])) finally: plugin_cmds.pop('echo-replace')
def test_strict_ascii(self): def bzr(*args, **kwargs): kwargs["encoding"] = "ascii" return self.run_bzr(*args, **kwargs)[0] register_command(cmd_echo_strict) try: self.assertEqual("foo", bzr("echo-strict foo")) # ascii can't encode \xb5 self.assertRaises(UnicodeEncodeError, bzr, ["echo-strict", u"foo\xb5"]) finally: plugin_cmds.remove("echo-strict")
def test_replace_ascii(self): def bzr(*args, **kwargs): kwargs["encoding"] = "ascii" return self.run_bzr(*args, **kwargs)[0] register_command(cmd_echo_replace) try: self.assertEqual("foo", bzr("echo-replace foo")) # ascii can't encode \xb5 self.assertEqual("foo?", bzr(["echo-replace", u"foo\xb5"])) finally: plugin_cmds.remove("echo-replace")
def test_strict_ascii(self): def bzr(*args, **kwargs): kwargs['encoding'] = 'ascii' return self.run_bzr(*args, **kwargs)[0] register_command(cmd_echo_strict) try: self.assertEqual('foo', bzr('echo-strict foo')) # ascii can't encode \xb5 self.assertRaises(UnicodeEncodeError, bzr, ['echo-strict', u'foo\xb5']) finally: plugin_cmds.pop('echo-strict')
def test_exact(self): def bzr(*args, **kwargs): return self.run_bzr(*args, **kwargs)[0] register_command(cmd_echo_exact) try: self.assertEqual("foo", bzr("echo-exact foo")) # Exact should fail to decode the string self.assertRaises(UnicodeEncodeError, bzr, ["echo-exact", u"foo\xb5"]) # Previously a non-ascii bytestring was also tested, as 'exact' # outputs bytes untouched, but needed buggy argv parsing to work finally: plugin_cmds.remove("echo-exact")
def test_exact(self): def bzr(*args, **kwargs): return self.run_bzr(*args, **kwargs)[0] register_command(cmd_echo_exact) try: self.assertEqual('foo', bzr('echo-exact foo')) # Exact should fail to decode the string self.assertRaises(UnicodeEncodeError, bzr, ['echo-exact', u'foo\xb5']) # Previously a non-ascii bytestring was also tested, as 'exact' # outputs bytes untouched, but needed buggy argv parsing to work finally: plugin_cmds.remove('echo-exact')
def test_exact(self): def bzr(*args, **kwargs): return self.run_bzr(*args, **kwargs)[0] register_command(cmd_echo_exact) try: self.assertEqual('foo', bzr('echo-exact foo')) # This is cheating a little bit, because 'foo\xb5' shouldn't # get past main() self.assertEqual('foo\xb5', bzr('echo-exact foo\xb5')) # Exact should fail to decode the string self.assertRaises(UnicodeEncodeError, bzr, ['echo-exact', u'foo\xb5']) finally: plugin_cmds.pop('echo-exact')
def run(self, *args, **kwargs): """ Choose which diff tool (external or builtin) to run. """ from controller import Controller if 'using' in kwargs: # Run the specified external diff tool: return Controller().run(*args, **kwargs) else: # Run the builtin diff command normally: return super(cmd_diff, self).run(*args, **kwargs) def help(self): """ Return help message for this class, including text from superclass. """ from inspect import getdoc return getdoc(super(cmd_diff, self)) + '\n\n' + getdoc(self) # End class cmd_diff # Initialize the plugin: version_info = (0, 91, 0, 'final', 0) # Register the new command provided by this plugin: commands.register_command(cmd_diff, decorate=False) # The End.
run_vimdiff(vimdiff_args, to_file, from_file) def write_old_to_temp(tree, file_id, rev_no): # we want the same suffix as before so syntax highlighting works from tempfile import NamedTemporaryFile from os.path import splitext, basename if not tree.has_id(file_id): raise BzrError("file {%s} wasn't in the basis version %s" % (file_id, tree)) old_filename = tree.id2path(file_id) name_base, name_suffix = splitext(basename(old_filename)) basis_tmp = NamedTemporaryFile(suffix=('.%s.tmp%s' % (rev_no, name_suffix)), prefix=name_base) basis_tmp.write(tree.get_file_text(file_id)) basis_tmp.flush() try: os.chmod(basis_tmp.name, 0444) except OSError: pass return basis_tmp def run_vimdiff(vimdiff_args, new_file_path, old_file_path): import subprocess sub = subprocess.call(vimdiff_args + [new_file_path, old_file_path]) register_command(cmd_gvimdiff) register_command(cmd_vimdiff)
provider = provider_class() for name, (source, url) in provider.get_bookmarks().items(): bookmarks.setdefault(source, {})[name] = url for source, items in sorted(bookmarks.items()): self.outf.write('%s:\n' % (source,)) for name, url in sorted(items.items()): self.outf.write(' %-20s %s\n' % (name, url)) # Don't run any tests on BookmarkTransport as it is not intended to be # a full implementation of Transport, just redirects. def get_test_permutations(): return [] try: from bzrlib.directory_service import directories directories.register( 'bookmark:', BookmarkDirectory) directories.register( 'bm:', BookmarkDirectory) except ImportError: register_transport( 'bookmark:', bookmark_transport_indirect) register_transport( 'bm:', bookmark_transport_indirect) register_command(cmd_bookmark) register_command(cmd_bookmarks)
# we cant just return self.iter_matches(), because # it will be consumed by the end, and we dont want # to call it twice. So lets create a list of files. files_to_rename = [] for old_name, new_name in self.iter_matches(): print 'R', old_name, '=>', new_name files_to_rename.append((old_name, new_name)) if files_to_rename: total = len(files_to_rename) if total > 1: question = 'Rename this %s files [y/N]? ' % total else: question = 'Rename this file [y/N]? ' if raw_input(question).lower() not in ('y', 'yes'): print 'Canceled.' files_to_rename = None return files_to_rename def rename_files(self, files): for old_name, new_name in files: if not self.dry_run: self.wt.rename_one(old_name, new_name) register_command(cmd_multi_rename)
from difftodo import get_comments_from_diff, todos_from_comments class cmd_todo(Command): """Find the TODO items added to a branch. """ takes_args = ['location?'] def run(self): revision = _parse_revision_str('submit:') diff_data = get_trees_and_branches_to_diff_locked( None, revision, None, None, self.add_cleanup, apply_view=True) (old_tree, new_tree, old_branch, new_branch, specific_files, extra_trees) = diff_data stream = StringIO() show_diff_trees( old_tree, new_tree, stream, old_label='', new_label='', extra_trees=extra_trees) stream.seek(0) patches = parse_patches(stream) comments = get_comments_from_diff(patches) tags = ('XXX', 'TODO') number = -1 for number, todo in enumerate(todos_from_comments(comments, tags)): print todo print "Things to do: %s" % (number + 1) register_command(cmd_todo)
to_basename = basename(to_location) if from_basename == to_basename: raise BzrError('basename of source and destination is equal') to_branch_path = join(dirname(from_branch_path), to_basename) # make branch print >> self.outf, 'Create branch: %s => %s' % (from_branch_path, to_branch_path) builtins.cmd_branch.run(self, from_branch_path, to_branch_path, **kw) # make lightweight chekout source = Branch.open(to_branch_path) revision_id = source.last_revision() try: os.mkdir(to_location) except OSError, e: if e.errno == errno.EEXIST: raise errors.BzrCommandError( 'Target directory "%s" already' ' exists.' % to_location) if e.errno == errno.ENOENT: raise errors.BzrCommandError( 'Parent of "%s" does not exist.' % to_location) else: raise source.create_checkout(to_location, revision_id, lightweight) else: builtins.cmd_branch.run(self, from_location, to_location, **kw) register_command(cmd_branch)
def run(self): providers = [LocationBookmarkProvider, GlobalBookmarkProvider] bookmarks = {} for provider_class in providers: provider = provider_class() for name, (source, url) in provider.get_bookmarks().items(): bookmarks.setdefault(source, {})[name] = url for source, items in sorted(bookmarks.items()): self.outf.write('%s:\n' % (source, )) for name, url in sorted(items.items()): self.outf.write(' %-20s %s\n' % (name, url)) # Don't run any tests on BookmarkTransport as it is not intended to be # a full implementation of Transport, just redirects. def get_test_permutations(): return [] try: from bzrlib.directory_service import directories directories.register('bookmark:', BookmarkDirectory) directories.register('bm:', BookmarkDirectory) except ImportError: register_transport('bookmark:', bookmark_transport_indirect) register_transport('bm:', bookmark_transport_indirect) register_command(cmd_bookmark) register_command(cmd_bookmarks)
def log(self, filename): "Write the current bisect log to a file." self._check() bisect_log = BisectLog() bisect_log.change_file_name(filename) bisect_log.save() def replay(self, filename): """Apply the given log file to a clean state, so the state is exactly as it was when the log was saved.""" self.reset() bisect_log = BisectLog(filename) bisect_log.change_file_name(bisect_info_path) bisect_log.save() bisect_log.bisect() register_command(cmd_bisect) def test_suite(): "Set up the test suite for the plugin." from bzrlib.plugins.bisect import tests return tests.test_suite()
if revision == None: # looks like user specified a limit revision = _get_revision_from_limit(-limit - 1) bd = bzrdir.BzrDir.open_containing('.')[0] br = bd.open_branch() if find != None: _list_files(find, verbose, revision, br, self.name()) return for filename in file_list: _undelete_file(filename, verbose, revision, br, self.name()) def test_suite(): import tests import tests.basic import tests.blackbox from unittest import TestSuite result = TestSuite() result.addTest(tests.blackbox.test_suite()) result.addTest(tests.basic.test_suite()) return result register_command(cmd_undelete)
except UnsupportedFormatError, e: print '='*50 print 'Branch at %s' % root print 'in an unsupported format' print e print r = pull_branch(br_dir, verbose=verbose, overwrite=overwrite) retcode = max(retcode, r) except KeyboardInterrupt: raise except Exception, e: import traceback traceback.print_exc() print 'failed while updating: %s' % (root,) retcode = 3 return retcode def test_suite(): from unittest import TestSuite, TestLoader import test_update_mirrors suite = TestSuite() suite.addTest(TestLoader().loadTestsFromModule(test_update_mirrors)) return suite register_command(cmd_update_mirrors)
seen_new_branch.seen) lp_server.start_server() try: old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS lp_transport = get_transport(lp_server.get_url()) host, port = self.get_host_and_port(port) lockdir._DEFAULT_TIMEOUT_SECONDS = 0 try: protocol(lp_transport, host, port, inet) finally: lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout finally: lp_server.stop_server() register_command(cmd_launchpad_server) class LPForkingService(object): """A service that can be asked to start a new bzr subprocess via fork. The basic idea is that bootstrapping time is long. Most of this is time spent during import of all needed libraries (lp.*). For example, the original 'lp-serve' command could take 2.5s just to start up, before any actual actions could be performed. This class provides a service sitting on a socket, which can then be requested to fork and run a given bzr command. Clients connect to the socket and make a single request, which then receives a response. The possible requests are:
import paramiko version = paramiko.__version__ except ImportError: version = 'None' self._print('Paramiko', version) # pycrypto try: import Crypto version = Crypto.__version__ except ImportError: version = 'None' self._print('PyCrypto', version) def _print(self, name, version): print "%-20s %s" % ("%s:" % name, version) def _windows_version(self): import sys major, minor, build, platform, text = sys.getwindowsversion() ver = '%d.%d.%d' % (major, minor, build) if platform == 2: return 'Windows NT/2000/XP %s %s' % (ver, text) elif platform == 1: return 'Windows 9x/ME %s %s' % (ver, text) #/class cmd_dependencies register_command(cmd_dependencies)
new_dirs.add(relpath + '/' + path) relpaths.add(relpath + '/' + path) # gather all dirs wm = WatchManager() added_flag = False handler = ProcessClose() handler._bzr_wm = wm notifier = Notifier(wm, handler) # read and process events try: while True: if new_dirs: for path in new_dirs: wm.add_watch(root + '/' + path, dir_mask) new_dirs = set() notifier.process_events() if notifier.check_events(): notifier.read_events() finally: notifier.stop() def test_suite(): import bzrlib.plugins.branchfeed.tests return bzrlib.plugins.branchfeed.tests.test_suite() install_hooks() if feedgen: register_command(cmd_feedgen)
def pull_component(comp, directory): aggregate_vcs.pull_component(comp, _find_sb(directory)) def push_component(comp, directory): aggregate_vcs.push_component(comp, _find_sb(directory)) def revert_component(comp, directory, revision): aggregate_vcs.revert_component(comp, _find_sb(directory), revision) def revno_component(comp, directory, tree=False): aggregate_vcs.show_component_revno(comp, _find_sb(directory), tree=tree) def status_component(comp, directory, revision=None): aggregate_vcs.show_component_status(comp, _find_sb(directory), revision=revision) def tags_component(comp, directory): aggregate_vcs.show_component_tags(comp, _find_sb(directory)) def tag_info_component(comp, directory, tag): has_tag, same_revision = aggregate_vcs.get_component_tag_info(comp, _find_sb(directory), tag) aggregate_vcs.print_tag_info(has_tag, same_revision, tag) def update_component(comp, directory): aggregate_vcs.update_component(comp, _find_sb(directory)) def tag_component(comp, tag, directory): aggrecate_vcs.tag_component(comp, tag, directory) register_command(cmd_sandbox) register_command(cmd_component)
present underneath the subdirectory SUBDIR. """ takes_args = ['location', 'subdir?'] takes_options = [] def run(self, location, subdir=None): if not subdir: # default to same name as source dir import os subdir = os.path.basename(location) import merge_into conflicts = merge_into.merge_into_helper(location, subdir) if not conflicts: self.outf.write('merge-into successful\n') else: self.outf.write('merge-into conflicts: %s\n' % (conflicts,)) return 1 commands.register_command(cmd_merge_into) def load_tests(standard_tests, module, loader): standard_tests.addTests(loader.loadTestsFromModuleNames( [__name__ + '.' + x for x in [ 'test_merge_into', 'test_bb_merge_into', ]])) return standard_tests
rev_id, quiet=quiet) if full: uploader.upload_full_tree() else: uploader.upload_tree() # We uploaded successfully, remember it if get_upload_location(branch) is None or remember: set_upload_location(branch, to_transport.base) if auto is not None: set_upload_auto(branch, auto) commands.register_command(cmd_upload) from bzrlib.plugins.upload.auto_upload_hook import auto_upload_hook if hasattr(branch.Branch.hooks, "install_named_hook"): branch.Branch.hooks.install_named_hook( 'post_change_branch_tip', auto_upload_hook, 'Auto upload code from a branch when it is changed.') auto_hook_available = True else: auto_hook_available = False def load_tests(basic_tests, module, loader): # This module shouldn't define any tests but I don't know how to report # that. I prefer to update basic_tests with the other tests to detect
return list(self.iter_matches()) # we cant just return self.iter_matches(), because # it will be consumed by the end, and we dont want # to call it twice. So lets create a list of files. files_to_rename = [] for old_name, new_name in self.iter_matches(): print 'R', old_name, '=>', new_name files_to_rename.append((old_name, new_name)) if files_to_rename: total = len(files_to_rename) if total > 1: question = 'Rename this %s files [y/N]? ' % total else: question = 'Rename this file [y/N]? ' if raw_input(question).lower() not in ('y', 'yes'): print 'Canceled.' files_to_rename = None return files_to_rename def rename_files(self, files): for old_name, new_name in files: if not self.dry_run: self.wt.rename_one(old_name, new_name) register_command(cmd_multi_rename)
sys.stdout = tmp_stdout diff_output.seek(0) diffstat_output = str(DiffStat(diff_output.readlines(), stat_dir, colour=colour)) if len(diffstat_output): print diffstat_output return retval class cmd_diffstat(cmd_diff): """diffstat - show stats about changes to the working tree""" takes_args = ['file*'] takes_options = ['revision', Option('dir-only', help='Only list directories')] aliases = ['ds'] def run(self, revision=None, dir_only=False, file_list=None): return cmd_diff().run(file_list=file_list, stat=True, stat_dir=dir_only, revision=revision) register_command(cmd_diffstat) diff_class = register_command(cmd_diff, decorate=True) def test_suite(): import tests return tests.test_suite()
# resource.setrlimit(resource.RLIMIT_AS, (four_gig, four_gig)) # seen_new_branch = hooks.SetProcTitleHook() # if protocol is None: # protocol = transport_server_registry.get() # lp_server = get_lp_server( # int(user_id), codehosting_endpoint_url, branch_directory, # seen_new_branch.seen) # lp_server.start_server() # try: # old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS # lp_transport = get_transport(lp_server.get_url()) # host, port = self.get_host_and_port(port) # lockdir._DEFAULT_TIMEOUT_SECONDS = 0 # try: # protocol(lp_transport, host, port, inet) # finally: # lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout # finally: # lp_server.stop_server() register_command(cmd_anvil_server) def load_tests(standard_tests, module, loader): standard_tests.addTests(loader.loadTestsFromModuleNames( [__name__ + '.' + x for x in [ 'test_lpserve', ]])) return standard_tests
from qctlib.gui_logic import CommitTool from qctlib.vcs.bzr import qctVcsBzr def local_path(path): if path.startswith("file://"): return urlutils.local_path_from_url(path) else: return urlutils.unescape(path) try: branch = WorkingTree.open_containing(u'.')[0].branch except NoWorkingTree: branch = Branch.open_containing(u'.')[0] branch_root = branch.bzrdir.root_transport.base # print "Branch root at " + branch_root os.chdir(local_path(branch_root)) vcs = qctVcsBzr() if vcs.initRepo(None) != 0: return try: app = QtGui.QApplication([]) dialog = CommitTool(vcs) dialog.show() app.exec_() except SystemExit: pass register_command(cmd_qct)
from bzrlib.plugins.git.server import BzrBackend from bzrlib.trace import warning import os warning("server support in bzr-git is experimental.") if directory is None: directory = os.getcwd() backend = BzrBackend(directory) server = TCPGitServer(backend, 'localhost') server.serve_forever() register_command(cmd_git_serve) class cmd_git_import(Command): """Import all branches from a git repository. """ takes_args = ["src_location", "dest_location"] def run(self, src_location, dest_location): from bzrlib.bzrdir import BzrDir, format_registry from bzrlib.errors import NoRepositoryPresent, NotBranchError from bzrlib.repository import Repository source_repo = Repository.open(src_location) format = format_registry.make_bzrdir('rich-root-pack')
pass except: pass if len(branches) < 1: raise Exception('not enough branches') except Exception as e: transport = bzrlib.transport.get_transport(repositorylocation) branches = [] branchnames = transport.list_dir('') for branchname in branchnames: try: components = [c for c in transport.list_dir(branchname) if _VALID_COMP_NAME_PAT.match(c)] for component in components: possibleaspects = transport.list_dir('/'.join([branchname, component])) for aspect in possibleaspects: if not aspect.startswith('.'): ## subdirs = transport.list_dir('/'.join((branch, component, aspect))) ## print subdirs ## if '.bzr' in subdirs: branches.append('%s\t%s\t%s\t%s' % (branchname, component, aspect, '')) except: pass branches.sort(key=string.lower) for b in branches: print b register_command(cmd_fast_branches)
Although we backup files like `bzr revert`, this is experimental so make backups before running this! This has Usage example: /tmp/bzr$ bzr remove-trailing-whitespace bzr /tmp/bzr/bzrlib$ bzr remove-trailing-whitespace *.py" """ takes_args = ['name_pattern*'] def run(self, name_pattern_list=None): if not name_pattern_list: raise errors.BzrCommandError("this command requires at least one " "NAME_PATTERN") import text_checker text_checker.remove_trailing_whitespace(name_pattern_list) commands.register_command(cmd_commit, decorate=True) commands.register_command(cmd_text_check_info, decorate=True) commands.register_command(cmd_remove_trailing_whitespace, decorate=True) branch.Branch.hooks.install_named_hook('pre_commit', pre_commit_hook, 'text-check') def test_suite(): from bzrlib.tests.TestUtil import TestLoader import tests return TestLoader().loadTestsFromModule(tests)
except errors.NotBranchError: src_repo = bzrdir.open_repository() repo_config = LocationConfig(src_repo.bzrdir.root_transport.base) if destination is None: destination = repo_config.get_user_option('public_repository') if destination is None: raise errors.BzrCommandError('No destination specified') dst_repo = BzrDir.open(destination).open_repository() if remember or (repo_config.get_user_option('public_repository') is None): repo_config.set_user_option('public_repository', dst_repo.bzrdir.root_transport.base) pb = ui_factory.nested_progress_bar() try: repo_push(src_repo, dst_repo, pb=pb, overwrite=overwrite) finally: pb.finished() register_command(cmd_repo_push) def test_suite(): from bzrlib.tests.TestUtil import TestLoader import test return TestLoader().loadTestsFromModule(test)
unknowns.append([abspath, kind]) else: unknowns.append([path, kind]) return unknowns def _compare_files(self, file_id, path): old_lines = self.basis_tree.get_file(file_id).readlines() new_lines = self.tree.get_file_byname(path).readlines() total = len(old_lines) + len(new_lines) if total: from bzrlib.patiencediff import PatienceSequenceMatcher matcher = PatienceSequenceMatcher(None, old_lines, new_lines) matched = sum(b[2] for b in matcher.get_matching_blocks()) ratio = 2.0 * matched / total else: ratio = 1.0 return ratio register_command(cmd_automv) def test_suite(): from bzrlib.tests import TestUtil suite = TestUtil.TestSuite() loader = TestUtil.TestLoader() testmod_names = ['test_automv'] suite.addTest(loader.loadTestsFromModuleNames( ["%s.%s" % (__name__, name) for name in testmod_names])) return suite
def revno_component(comp, directory, tree=False): aggregate_vcs.show_component_revno(comp, _find_sb(directory), tree=tree) def status_component(comp, directory, revision=None): aggregate_vcs.show_component_status(comp, _find_sb(directory), revision=revision) def tags_component(comp, directory): aggregate_vcs.show_component_tags(comp, _find_sb(directory)) def tag_info_component(comp, directory, tag): has_tag, same_revision = aggregate_vcs.get_component_tag_info( comp, _find_sb(directory), tag) aggregate_vcs.print_tag_info(has_tag, same_revision, tag) def update_component(comp, directory): aggregate_vcs.update_component(comp, _find_sb(directory)) def tag_component(comp, tag, directory): aggrecate_vcs.tag_component(comp, tag, directory) register_command(cmd_sandbox) register_command(cmd_component)
# -*- coding: UTF-8 -*- # Copyright (C) 2008 Erik Bågfors <*****@*****.**> # # GNU GPL v2. # """external merge plugin for bzr""" try: from bzrlib.commands import plugin_cmds plugin_cmds.register_lazy('cmd_extmerge', ['emerge'], 'bzrlib.plugins.extmerge.extmerge') except AttributeError: from bzrlib.commands import register_command from extmerge import cmd_extmerge register_command(cmd_extmerge)
current.show_rev_log() def log(self, filename): "Write the current bisect log to a file." self._check() bisect_log = BisectLog() bisect_log.change_file_name(filename) bisect_log.save() def replay(self, filename): """Apply the given log file to a clean state, so the state is exactly as it was when the log was saved.""" self.reset() bisect_log = BisectLog(filename) bisect_log.change_file_name(bisect_info_path) bisect_log.save() bisect_log.bisect() register_command(cmd_bisect) def test_suite(): "Set up the test suite for the plugin." from bzrlib.plugins.bisect import tests return tests.test_suite()
""" takes_args = ['location', 'subdir?'] takes_options = [] def run(self, location, subdir=None): if not subdir: # default to same name as source dir import os subdir = os.path.basename(location) import merge_into conflicts = merge_into.merge_into_helper(location, subdir) if not conflicts: self.outf.write('merge-into successful\n') else: self.outf.write('merge-into conflicts: %s\n' % (conflicts, )) return 1 commands.register_command(cmd_merge_into) def load_tests(standard_tests, module, loader): standard_tests.addTests( loader.loadTestsFromModuleNames([ __name__ + '.' + x for x in [ 'test_merge_into', 'test_bb_merge_into', ] ])) return standard_tests
import os from bzrlib.builtins import tree_files from bzrlib.commands import Command, display_command, register_command from bzrlib.errors import PointlessCommit from bzrlib.option import Option class cmd_snapshot(Command): """Take a snapshot committing the current status. """ takes_args = ['location*'] takes_options = [Option('message', type=unicode, short_name='m', help="Description of the new revision.")] aliases = ['sn', 'snap'] @display_command def run(self, location_list=['.'], message=None): for location in location_list: #print location tree, _ = tree_files([location]) for relpath in tree.unknowns(): abspath = os.path.join(location, relpath) tree.smart_add([abspath]) try: tree.commit(message, allow_pointless=False, strict=True) except PointlessCommit: pass register_command(cmd_snapshot)
except UnsupportedFormatError, e: print '=' * 50 print 'Branch at %s' % root print 'in an unsupported format' print e print r = pull_branch(br_dir, verbose=verbose, overwrite=overwrite) retcode = max(retcode, r) except KeyboardInterrupt: raise except Exception, e: import traceback traceback.print_exc() print 'failed while updating: %s' % (root, ) retcode = 3 return retcode def test_suite(): from unittest import TestSuite, TestLoader import test_update_mirrors suite = TestSuite() suite.addTest(TestLoader().loadTestsFromModule(test_update_mirrors)) return suite register_command(cmd_update_mirrors)
revision = _get_revision_from_limit(cmd_undelete.DEFAULT_LIMIT) if revision == None: # looks like user specified a limit revision = _get_revision_from_limit(-limit - 1) bd = bzrdir.BzrDir.open_containing('.')[0] br = bd.open_branch() if find != None: _list_files(find, verbose, revision, br, self.name()) return for filename in file_list: _undelete_file(filename, verbose, revision, br, self.name()) def test_suite(): import tests import tests.basic import tests.blackbox from unittest import TestSuite result = TestSuite() result.addTest(tests.blackbox.test_suite()) result.addTest(tests.basic.test_suite()) return result register_command(cmd_undelete)
"""bzr touch""" import os from bzrlib.commands import Command, register_command from bzrlib.workingtree import WorkingTree version_info = (1, 1) # Ripped straight from GNU touch(1) FLAGS = os.O_WRONLY | os.O_CREAT | os.O_NONBLOCK | os.O_NOCTTY class cmd_touch(Command): """Basically: touch <file> && bzr add <file>.""" takes_args = ['file*'] def run(self, file_list): wt = WorkingTree.open_containing('.') # Create the files if they don't exist. for filename in file_list: filepath = os.path.join(os.getcwd(), filename) fd = os.open(filepath, FLAGS, 0666) os.close(fd) wt[0].smart_add(file_list, recurse=False) register_command(cmd_touch)
lp_server = get_lp_server(int(user_id), codehosting_endpoint_url, branch_directory, seen_new_branch.seen) lp_server.start_server() try: old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS lp_transport = get_transport(lp_server.get_url()) host, port = self.get_host_and_port(port) lockdir._DEFAULT_TIMEOUT_SECONDS = 0 try: protocol(lp_transport, host, port, inet) finally: lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout finally: lp_server.stop_server() register_command(cmd_launchpad_server) class LPForkingService(object): """A service that can be asked to start a new bzr subprocess via fork. The basic idea is that bootstrapping time is long. Most of this is time spent during import of all needed libraries (lp.*). For example, the original 'lp-serve' command could take 2.5s just to start up, before any actual actions could be performed. This class provides a service sitting on a socket, which can then be requested to fork and run a given bzr command. Clients connect to the socket and make a single request, which then receives a response. The possible requests are:
service = LaunchpadService() # This gives back the xmlrpc url that can be used for future # operations on the branch. It's not so useful to print to the # user since they can't do anything with it from a web browser; it # might be nice for the server to tell us about an html url as # well. else: # Run on service entirely in memory service = DryRunLaunchpadService() service.gather_user_credentials() branch_object_url = rego.submit(service) if link_bug: link_bug_url = linko.submit(service) print 'Branch registered.' register_command(cmd_register_branch) class cmd_launchpad_login(Command): """Show or set the Launchpad user ID. When communicating with Launchpad, some commands need to know your Launchpad user ID. This command can be used to set or show the user ID that Bazaar will use for such communication. :Examples: Show the Launchpad ID of the current user:: bzr launchpad-login Set the Launchpad ID of the current user to 'bob'::
try: import paramiko version = paramiko.__version__ except ImportError: version = 'None' self._print('Paramiko', version) # pycrypto try: import Crypto version = Crypto.__version__ except ImportError: version = 'None' self._print('PyCrypto', version) def _print(self, name, version): print "%-20s %s" % ("%s:" % name, version) def _windows_version(self): import sys major, minor, build, platform, text = sys.getwindowsversion() ver = '%d.%d.%d' % (major, minor, build) if platform == 2: return 'Windows NT/2000/XP %s %s' % (ver, text) elif platform == 1: return 'Windows 9x/ME %s %s' % (ver, text) #/class cmd_dependencies register_command(cmd_dependencies)
def write_old_to_temp(tree, file_id, rev_no): # we want the same suffix as before so syntax highlighting works from tempfile import NamedTemporaryFile from os.path import splitext, basename if not tree.has_id(file_id): raise BzrError("file {%s} wasn't in the basis version %s" % (file_id, tree)) old_filename = tree.id2path(file_id) name_base, name_suffix = splitext(basename(old_filename)) basis_tmp = NamedTemporaryFile(suffix=('.%s.tmp%s' % (rev_no, name_suffix)), prefix=name_base) basis_tmp.write(tree.get_file_text(file_id)) basis_tmp.flush() try: os.chmod(basis_tmp.name, 0444) except OSError: pass return basis_tmp def run_vimdiff(vimdiff_args, new_file_path, old_file_path): import subprocess sub = subprocess.call(vimdiff_args + [new_file_path, old_file_path]) register_command(cmd_gvimdiff) register_command(cmd_vimdiff)
] aliases = ['ds'] def run(self, revision=None, dir_only=False, file_list=None, no_color=False): return cmd_diff().run(file_list=file_list, stat=True, stat_dir=dir_only, revision=revision, no_color=no_color) register_command(cmd_diffstat) diff_class = register_command(cmd_diff, decorate=True) try: from bzrlib.plugins import qbzr except ImportError: qbzr = None if qbzr is not None: plugin_cmds.register_lazy('cmd_qdiffstat', [], 'bzrlib.plugins.diffstat.qdiffstat') def test_suite(): import tests return tests.test_suite()
from dulwich.server import TCPGitServer from bzrlib.plugins.git.server import BzrBackend from bzrlib.trace import warning import os warning("server support in bzr-git is experimental.") if directory is None: directory = os.getcwd() backend = BzrBackend(directory) server = TCPGitServer(backend, 'localhost') server.serve_forever() register_command(cmd_git_serve) class cmd_git_import(Command): """Import all branches from a git repository. """ takes_args = ["src_location", "dest_location"] def run(self, src_location, dest_location): from bzrlib.bzrdir import BzrDir, format_registry from bzrlib.errors import NoRepositoryPresent, NotBranchError from bzrlib.repository import Repository source_repo = Repository.open(src_location) format = format_registry.make_bzrdir('rich-root-pack')