def edit_commit_message(infotext, ignoreline=DEFAULT_IGNORE_LINE, start_message=None): """Let the user edit a commit message in a temp file. This is run if they don't give a message or message-containing file on the command line. :param infotext: Text to be displayed at bottom of message for the user's reference; currently similar to 'bzr status'. :param ignoreline: The separator to use above the infotext. :param start_message: The text to place above the separator, if any. This will not be removed from the message after the user has edited it. :return: commit message or None. """ if not start_message is None: start_message = start_message.encode(osutils.get_user_encoding()) infotext = infotext.encode(osutils.get_user_encoding(), 'replace') return edit_commit_message_encoded(infotext, ignoreline, start_message)
def report_bug_legacy(exc_info, err_file): """Report a bug by just printing a message to the user.""" trace.print_exception(exc_info, err_file) err_file.write('\n') import textwrap def print_wrapped(l): err_file.write(textwrap.fill(l, width=78, subsequent_indent=' ') + '\n') print_wrapped('bzr %s on python %s (%s)\n' % \ (bzrlib.__version__, bzrlib._format_version_tuple(sys.version_info), platform.platform(aliased=1))) print_wrapped('arguments: %r\n' % sys.argv) print_wrapped(textwrap.fill( 'plugins: ' + plugin.format_concise_plugin_list(), width=78, subsequent_indent=' ', ) + '\n') print_wrapped( 'encoding: %r, fsenc: %r, lang: %r\n' % ( osutils.get_user_encoding(), sys.getfilesystemencoding(), os.environ.get('LANG'))) # We used to show all the plugins here, but it's too verbose. err_file.write( "\n" "*** Bazaar has encountered an internal error. This probably indicates a\n" " bug in Bazaar. You can help us fix it by filing a bug report at\n" " https://bugs.launchpad.net/bzr/+filebug\n" " including this traceback and a description of the problem.\n" )
def report_bug_legacy(exc_info, err_file): """Report a bug by just printing a message to the user.""" trace.print_exception(exc_info, err_file) err_file.write('\n') import textwrap def print_wrapped(l): err_file.write( textwrap.fill(l, width=78, subsequent_indent=' ') + '\n') print_wrapped('bzr %s on python %s (%s)\n' % \ (bzrlib.__version__, bzrlib._format_version_tuple(sys.version_info), platform.platform(aliased=1))) print_wrapped('arguments: %r\n' % sys.argv) print_wrapped( textwrap.fill( 'plugins: ' + plugin.format_concise_plugin_list(), width=78, subsequent_indent=' ', ) + '\n') print_wrapped('encoding: %r, fsenc: %r, lang: %r\n' % (osutils.get_user_encoding(), sys.getfilesystemencoding(), os.environ.get('LANG'))) # We used to show all the plugins here, but it's too verbose. err_file.write( "\n" "*** Bazaar has encountered an internal error. This probably indicates a\n" " bug in Bazaar. You can help us fix it by filing a bug report at\n" " https://bugs.launchpad.net/bzr/+filebug\n" " including this traceback and a description of the problem.\n")
def test_user_cp0(self): def f(): return 'cp0' locale.getpreferredencoding = f self.assertEquals('ascii', osutils.get_user_encoding(use_cache=False)) self.assertEquals('', sys.stderr.getvalue())
def show_version(show_config=True, show_copyright=True, to_file=None): if to_file is None: to_file = sys.stdout to_file.write("Bazaar (bzr) %s\n" % bzrlib.__version__) # is bzrlib itself in a branch? src_tree = _get_bzr_source_tree() if src_tree: src_revision_id = src_tree.last_revision() revno = src_tree.branch.revision_id_to_revno(src_revision_id) to_file.write(" from bzr checkout %s\n" % (src_tree.basedir,)) to_file.write(" revision: %s\n" % (revno,)) to_file.write(" revid: %s\n" % (src_revision_id,)) to_file.write(" branch nick: %s\n" % (src_tree.branch.nick,)) to_file.write(" Python interpreter: ") # show path to python interpreter # (bzr.exe use python interpreter from pythonXY.dll # but sys.executable point to bzr.exe itself) # however, sys.frozen exists if running from bzr.exe # see http://www.py2exe.org/index.cgi/Py2exeEnvironment if getattr(sys, 'frozen', None) is None: # if not bzr.exe to_file.write(sys.executable + ' ') else: # pythonXY.dll basedir = os.path.dirname(sys.executable) python_dll = "python%d%d.dll" % sys.version_info[:2] to_file.write(os.path.join(basedir, python_dll) + ' ') # and now version of python interpreter to_file.write(bzrlib._format_version_tuple(sys.version_info)) to_file.write('\n') to_file.write(" Python standard library:" + ' ') to_file.write(os.path.dirname(os.__file__) + '\n') to_file.write(" Platform: %s\n" % platform.platform(aliased=1).decode('utf-8')) to_file.write(" bzrlib: ") if len(bzrlib.__path__) > 1: # print repr, which is a good enough way of making it clear it's # more than one element (eg ['/foo/bar', '/foo/bzr']) to_file.write(repr(bzrlib.__path__) + '\n') else: to_file.write(bzrlib.__path__[0] + '\n') if show_config: config_dir = osutils.normpath(config.config_dir()) # use native slashes if not isinstance(config_dir, unicode): config_dir = config_dir.decode(osutils.get_user_encoding()) to_file.write(" Bazaar configuration: %s\n" % (config_dir,)) to_file.write(" Bazaar log file: ") to_file.write(trace._bzr_log_filename + '\n') if show_copyright: to_file.write('\n') to_file.write(bzrlib.__copyright__ + '\n') to_file.write("http://bazaar.canonical.com/\n") to_file.write('\n') to_file.write("bzr comes with ABSOLUTELY NO WARRANTY. bzr is free software, and\n") to_file.write("you may use, modify and redistribute it under the terms of the GNU\n") to_file.write("General Public License version 2 or later.\n") to_file.write("\nBazaar is part of the GNU Project to produce a free operating " "system.\n") to_file.write('\n')
def test_unsupported_encoding_commit_message(self): self.overrideEnv('LANG', 'C') # LANG env variable has no effect on Windows # but some characters anyway cannot be represented # in default user encoding char = probe_bad_non_ascii(osutils.get_user_encoding()) if char is None: raise TestSkipped('Cannot find suitable non-ascii character ' 'for user_encoding (%s)' % osutils.get_user_encoding()) self.make_fake_editor(message=char) working_tree = self.make_uncommitted_tree() self.assertRaises(errors.BadCommitMessageEncoding, msgeditor.edit_commit_message, '')
def test_normalize_url_files(self): # Test that local paths are properly normalized normalize_url = urlutils.normalize_url def norm_file(expected, path): url = normalize_url(path) self.assertStartsWith(url, 'file:///') if sys.platform == 'win32': url = url[len('file:///C:'):] else: url = url[len('file://'):] self.assertEndsWith(url, expected) norm_file('path/to/foo', 'path/to/foo') norm_file('/path/to/foo', '/path/to/foo') norm_file('path/to/foo', '../path/to/foo') # Local paths are assumed to *not* be escaped at all try: u'uni/\xb5'.encode(osutils.get_user_encoding()) except UnicodeError: # locale cannot handle unicode pass else: norm_file('uni/%C2%B5', u'uni/\xb5') norm_file('uni/%25C2%25B5', u'uni/%C2%B5') norm_file('uni/%20b', u'uni/ b') # All the crazy characters get escaped in local paths => file:/// urls # The ' ' character must not be at the end, because on win32 # it gets stripped off by ntpath.abspath norm_file('%27%20%3B/%3F%3A%40%26%3D%2B%24%2C%23', "' ;/?:@&=+$,#")
def test_get_user_encoding(self): self._encoding = 'user_encoding' fake_codec.add('user_encoding') self.assertEqual( 'iso8859-1', # fake_codec maps to latin-1 osutils.get_user_encoding()) self.assertEqual('', sys.stderr.getvalue())
def setUp(self): super(TestNonAscii, self).setUp() self._check_can_encode_paths() self.overrideAttr(osutils, '_cached_user_encoding', self.encoding) email = self.info['committer'] + ' <*****@*****.**>' self.overrideEnv('BZR_EMAIL', email.encode(osutils.get_user_encoding())) self.create_base()
def test_user_empty(self): """Running bzr from a vim script gives '' for a preferred locale""" def f(): return '' locale.getpreferredencoding = f self.assertEquals('ascii', osutils.get_user_encoding(use_cache=False)) self.assertEquals('', sys.stderr.getvalue())
def test_get_user_encoding(self): def f(): return 'user_encoding' locale.getpreferredencoding = f fake_codec.add('user_encoding') self.assertEquals('user_encoding', osutils.get_user_encoding(use_cache=False)) self.assertEquals('', sys.stderr.getvalue())
def test_user_cp_unknown(self): def f(): return 'cp-unknown' locale.getpreferredencoding = f self.assertEquals('ascii', osutils.get_user_encoding(use_cache=False)) self.assertEquals( 'bzr: warning: unknown encoding cp-unknown.' ' Continuing with ascii encoding.\n', sys.stderr.getvalue())
def test_local_appdata_matches_environment(self): # LOCALAPPDATA typically only exists on Vista, so we only attempt to # compare when it exists. lad = win32utils.get_local_appdata_location() env = os.environ.get("LOCALAPPDATA") if env: # XXX - See bug 262874, which asserts the correct encoding is 'mbcs' encoding = osutils.get_user_encoding() self.assertPathsEqual(lad, env.decode(encoding))
def test_unicode(self): """A non-ascii variable is returned as unicode""" unicode_val = u"\xa7" # non-ascii character present in many encodings try: bytes_val = unicode_val.encode(osutils.get_user_encoding()) except UnicodeEncodeError: self.skip("Couldn't encode non-ascii string to place in environ") os.environ["TEST"] = bytes_val self.assertEqual(unicode_val, win32utils.get_environ_unicode("TEST"))
def test_user_cp_unknown(self): def f(): return 'cp-unknown' locale.getpreferredencoding = f self.assertEquals('ascii', osutils.get_user_encoding(use_cache=False)) self.assertEquals('bzr: warning: unknown encoding cp-unknown.' ' Continuing with ascii encoding.\n', sys.stderr.getvalue())
def get_environ_unicode(key, default=None): """Get `key` from environment as unicode or `default` if unset Fallback version that should basically never be needed. """ from bzrlib import osutils try: return os.environ[key].decode(osutils.get_user_encoding()) except KeyError: return default
def test_appdata_matches_environment(self): # Typically the APPDATA environment variable will match # get_appdata_location # XXX - See bug 262874, which asserts the correct encoding is 'mbcs', encoding = osutils.get_user_encoding() env_val = os.environ.get("APPDATA", None) if not env_val: raise TestSkipped("No APPDATA environment variable exists") self.assertPathsEqual(win32utils.get_appdata_location(), env_val.decode(encoding))
def test_unicode_bzr_home(self): uni_val, str_val = probe_unicode_in_user_encoding() if uni_val is None: raise TestSkipped('Cannot find a unicode character that works in' ' encoding %s' % (osutils.get_user_encoding(),)) self.overrideEnv('BZR_HOME', str_val) self.permit_source_tree_branch_repo() out = self.run_bzr("version")[0] self.assertTrue(len(out) > 0) self.assertContainsRe(out, r"(?m)^ Bazaar configuration: " + str_val)
def test_unicode_bzr_home(self): uni_val, str_val = probe_unicode_in_user_encoding() if uni_val is None: raise TestSkipped('Cannot find a unicode character that works in' ' encoding %s' % (osutils.get_user_encoding(), )) self.overrideEnv('BZR_HOME', str_val) self.permit_source_tree_branch_repo() out = self.run_bzr("version")[0] self.assertTrue(len(out) > 0) self.assertContainsRe(out, r"(?m)^ Bazaar configuration: " + str_val)
def _encode_safe(self, u): """Encode possible unicode string argument to 8-bit string in user_encoding. Unencodable characters will be replaced with '?'. :param u: possible unicode string. :return: encoded string if u is unicode, u itself otherwise. """ if isinstance(u, unicode): return u.encode(osutils.get_user_encoding(), 'replace') return u
def test_user_locale_error(self): def f(): raise locale.Error, 'unsupported locale' locale.getpreferredencoding = f os.environ['LANG'] = 'BOGUS' self.assertEquals('ascii', osutils.get_user_encoding(use_cache=False)) self.assertEquals('bzr: warning: unsupported locale\n' ' Could not determine what text encoding to use.\n' ' This error usually means your Python interpreter\n' ' doesn\'t support the locale set by $LANG (BOGUS)\n' ' Continuing with ascii encoding.\n', sys.stderr.getvalue())
def test_user_locale_error(self): def f(): raise locale.Error, 'unsupported locale' locale.getpreferredencoding = f os.environ['LANG'] = 'BOGUS' self.assertEquals('ascii', osutils.get_user_encoding(use_cache=False)) self.assertEquals( 'bzr: warning: unsupported locale\n' ' Could not determine what text encoding to use.\n' ' This error usually means your Python interpreter\n' ' doesn\'t support the locale set by $LANG (BOGUS)\n' ' Continuing with ascii encoding.\n', sys.stderr.getvalue())
def test_commandline_is_8bit(self): claws = mail_client.Claws(None) cmdline = claws._get_compose_commandline(u'*****@*****.**', u'\xb5cosm of fun!', u'file%') subject_string = urlutils.quote(u'\xb5cosm of fun!'.encode( osutils.get_user_encoding(), 'replace')) self.assertEqual([ '--compose', 'mailto:[email protected]?subject=%s' % subject_string, '--attach', 'file%' ], cmdline) for item in cmdline: self.assertFalse(isinstance(item, unicode), 'Command-line item %r is unicode!' % item)
def test_unicode_bzr_log(self): uni_val = u"\xa7" enc = osutils.get_user_encoding() try: str_val = uni_val.encode(enc) except UnicodeEncodeError: self.skip("Test string %r unrepresentable in user encoding %s" % (uni_val, enc)) self.overrideEnv('BZR_HOME', self.test_base_dir) self.overrideEnv("BZR_LOG", os.path.join(self.test_base_dir, uni_val).encode(enc)) out, err = self.run_bzr_subprocess("version") uni_out = out.decode(enc) self.assertContainsRe(uni_out, u"(?m)^ Bazaar log file: .*/\xa7$")
def test_unicode_bzr_log(self): uni_val = u"\xa7" enc = osutils.get_user_encoding() try: str_val = uni_val.encode(enc) except UnicodeEncodeError: self.skip("Test string %r unrepresentable in user encoding %s" % ( uni_val, enc)) self.overrideEnv('BZR_HOME', self.test_base_dir) self.overrideEnv("BZR_LOG", os.path.join(self.test_base_dir, uni_val).encode(enc)) out, err = self.run_bzr_subprocess("version") uni_out = out.decode(enc) self.assertContainsRe(uni_out, u"(?m)^ Bazaar log file: .*/\xa7$")
def run(self, from_location, to_location, revision=None): branch = Branch.open_containing('.')[0] root = local_path_from_url(branch.base) # select what do it if isdir(pathjoin(root, to_location, '.bzr')) or isdir(pathjoin(root, to_location, '.svn')): if branch.get_bound_location(): cmd = ['update', to_location] else: cmd = ['pull', from_location, '--directory', to_location] else: if branch.get_bound_location(): cmd = ['checkout', from_location, to_location] else: cmd = ['branch', from_location, to_location] # command branch don't create recursive directory dirs = to_location.rpartition('/') if dirs[0] != '' and not isdir(dirs[0]): os.makedirs(dirs[0].encode(get_user_encoding())) # if use revision options but not for 'update' if revision is not None:# and cmd[0] != 'update': cmd += ['--revision', revision[0].user_spec] note('Add external ' + ' '.join(cmd)) run_bzr_catch_user_errors(cmd) bzrmeta = pathjoin(root, '.bzrmeta') if not isdir(bzrmeta): os.mkdir(bzrmeta) # add new branch to config and snapshot files line = from_location + ' ' + self._quoted_if_need(to_location) if revision: line += ' ' + revision[0].user_spec self._add_to_file(root, externals.CONFIG_PATH, line) self._add_to_file(root, externals.SNAPSHOT_PATH, line) # add ignore mask from bzrlib import IGNORE_FILENAME self._add_to_file(root, IGNORE_FILENAME, './' + to_location) # add config files to repository cmd = ['add', '.bzrignore', '.bzrmeta/externals', '.bzrmeta/externals-snapshot'] run_bzr_catch_user_errors(cmd)
def test_unsupported_encoding_commit_message(self): self.overrideEnv("LANG", "C") # LANG env variable has no effect on Windows # but some characters anyway cannot be represented # in default user encoding char = probe_bad_non_ascii(osutils.get_user_encoding()) if char is None: raise TestSkipped( "Cannot find suitable non-ascii character " "for user_encoding (%s)" % osutils.get_user_encoding() ) self.make_fake_editor(message=char) working_tree = self.make_uncommitted_tree() self.assertRaises(errors.BadCommitMessageEncoding, msgeditor.edit_commit_message, "")
def test_commandline_is_8bit(self): claws = mail_client.Claws(None) cmdline = claws._get_compose_commandline( u'*****@*****.**', u'\xb5cosm of fun!', u'file%') subject_string = urlutils.quote( u'\xb5cosm of fun!'.encode(osutils.get_user_encoding(), 'replace')) self.assertEqual( ['--compose', 'mailto:[email protected]?subject=%s' % subject_string, '--attach', 'file%'], cmdline) for item in cmdline: self.assertFalse(isinstance(item, unicode), 'Command-line item %r is unicode!' % item)
def init_encodings(self, initial_encoding=None): _encodings = UniqueList() if initial_encoding: _encodings.append(initial_encoding) _encodings.append(get_user_encoding()) _encodings.append(get_terminal_encoding()) _encodings += python_encodings self.encodings = filter(is_valid_encoding, _encodings) if initial_encoding: if initial_encoding not in self.encodings: self.encodings.insert(0, initial_encoding) else: initial_encoding = 'utf-8' self._encoding = initial_encoding
def _encode_path(self, path, kind): """Encode unicode path in user encoding. :param path: possible unicode path. :param kind: path kind ('executable' or 'attachment'). :return: encoded path if path is unicode, path itself otherwise. :raise: UnableEncodePath. """ if isinstance(path, unicode): try: return path.encode(osutils.get_user_encoding()) except UnicodeEncodeError: raise errors.UnableEncodePath(path, kind) return path
def get_sys_info(): """Get the system information. :return: a dictionary mapping fields to values. Field names are: * bzr-version - version of Bazaar * bzr-lib-path - paths to bzrlib roots (a list) * bzr-source-tree - source tree holding Bazaar (None or a Tree object) * bzr-config-dir - configuration directory holding bazaar.conf, etc. * bzr-log-file - path to bzr.log file * python-file - path to Python interpreter * python-version - version of Python interpreter * python-lib-dir - path to Python standard library """ result = {} # Bazaar installation result["bzr-version"] = bzrlib.__version__ result["bzr-lib-path"] = bzrlib.__path__ # is bzrlib itself in a branch? source_tree = None #_get_bzr_source_tree() if source_tree: result["bzr-source-tree"] = _source_tree_details() else: result["bzr-source-tree"] = None # Bazaar configuration config_dir = os.path.normpath(config.config_dir()) # use native slashes if not isinstance(config_dir, unicode): config_dir = config_dir.decode(osutils.get_user_encoding()) result["bzr-config-dir"] = config_dir result["bzr-log-file"] = trace._bzr_log_filename # Python installation # (bzr.exe use python interpreter from pythonXY.dll # but sys.executable point to bzr.exe itself) if not hasattr(sys, 'frozen'): # check for bzr.exe # python executable py_file = sys.executable else: # pythonXY.dll basedir = os.path.dirname(sys.executable) python_dll = "python%d%d.dll" % sys.version_info[:2] py_file = os.path.join(basedir, python_dll) result["python-file"] = py_file result["python-version"] = bzrlib._format_version_tuple(sys.version_info) result["python-lib-dir"] = os.path.dirname(os.__file__) return result
def run_bzr_decode(self, args, encoding=None, fail=False, retcode=None, working_dir=None): """Run bzr and decode the output into a particular encoding. Returns a string containing the stdout output from bzr. :param fail: If true, the operation is expected to fail with a UnicodeError. """ if encoding is None: encoding = osutils.get_user_encoding() try: out = self.run_bzr(args, output_encoding=encoding, encoding=encoding, retcode=retcode, working_dir=working_dir)[0] return out.decode(encoding) except UnicodeError, e: if not fail: raise
def pull(self): if disable_hooks: return # need use merged config from repository and working tree # because new added external branch from repository or working tree # need pull/update for correct snapshot self.read_config() self.read_config_from_repository() if len(self.config) == 0: return for location, path, revision in self.branch_iterator(): if location == path: # not create feature branch for directory above the root continue # select what do it if isdir(pathjoin(path, '.bzr')) or isdir(pathjoin(path, '.svn')): if self.bound: cmd = ['update', path] else: cmd = ['pull', location, '--directory', path] else: if self.bound: cmd = ['checkout', location, path] else: cmd = ['branch', location, path] # command branch don't create recursive directory dirs = path.rpartition('/') if dirs[0] != '' and not isdir(dirs[0]): os.makedirs(dirs[0].encode(get_user_encoding())) # if use revision options but not for 'update' if revision is not None:# and cmd[0] != 'update': cmd += ['--revision', revision] self.adjust_verbosity(cmd) self._report(cmd) run_bzr_catch_user_errors(cmd)
def test_unable_encode_path(self): err = errors.UnableEncodePath('foo', 'executable') self.assertEquals( "Unable to encode executable path 'foo' in " "user encoding " + osutils.get_user_encoding(), str(err))
def _ensure_unicode(s): if s and type(s) != unicode: from bzrlib import osutils s = s.decode(osutils.get_user_encoding()) return s
def show_version(show_config=True, show_copyright=True, to_file=None): if to_file is None: to_file = sys.stdout to_file.write("Bazaar (bzr) %s\n" % bzrlib.__version__) # is bzrlib itself in a branch? src_tree = _get_bzr_source_tree() if src_tree: src_revision_id = src_tree.last_revision() revno = src_tree.branch.revision_id_to_revno(src_revision_id) to_file.write(" from bzr checkout %s\n" % (src_tree.basedir, )) to_file.write(" revision: %s\n" % (revno, )) to_file.write(" revid: %s\n" % (src_revision_id, )) to_file.write(" branch nick: %s\n" % (src_tree.branch.nick, )) to_file.write(" Python interpreter: ") # show path to python interpreter # (bzr.exe use python interpreter from pythonXY.dll # but sys.executable point to bzr.exe itself) # however, sys.frozen exists if running from bzr.exe # see http://www.py2exe.org/index.cgi/Py2exeEnvironment if getattr(sys, 'frozen', None) is None: # if not bzr.exe to_file.write(sys.executable + ' ') else: # pythonXY.dll basedir = os.path.dirname(sys.executable) python_dll = "python%d%d.dll" % sys.version_info[:2] to_file.write(os.path.join(basedir, python_dll) + ' ') # and now version of python interpreter to_file.write(bzrlib._format_version_tuple(sys.version_info)) to_file.write('\n') to_file.write(" Python standard library:" + ' ') to_file.write(os.path.dirname(os.__file__) + '\n') to_file.write(" Platform: %s\n" % platform.platform(aliased=1).decode('utf-8')) to_file.write(" bzrlib: ") if len(bzrlib.__path__) > 1: # print repr, which is a good enough way of making it clear it's # more than one element (eg ['/foo/bar', '/foo/bzr']) to_file.write(repr(bzrlib.__path__) + '\n') else: to_file.write(bzrlib.__path__[0] + '\n') if show_config: config_dir = osutils.normpath( config.config_dir()) # use native slashes if not isinstance(config_dir, unicode): config_dir = config_dir.decode(osutils.get_user_encoding()) to_file.write(" Bazaar configuration: %s\n" % (config_dir, )) to_file.write(" Bazaar log file: ") to_file.write(trace._bzr_log_filename + '\n') if show_copyright: to_file.write('\n') to_file.write(bzrlib.__copyright__ + '\n') to_file.write("http://bazaar.canonical.com/\n") to_file.write('\n') to_file.write( "bzr comes with ABSOLUTELY NO WARRANTY. bzr is free software, and\n" ) to_file.write( "you may use, modify and redistribute it under the terms of the GNU\n" ) to_file.write("General Public License version 2 or later.\n") to_file.write( "\nBazaar is part of the GNU Project to produce a free operating " "system.\n") to_file.write('\n')
def _write_apport_report_to_file(exc_info): import traceback from apport.report import Report exc_type, exc_object, exc_tb = exc_info pr = Report() # add_proc_info sets the ExecutablePath, InterpreterPath, etc. pr.add_proc_info() # It also adds ProcMaps which for us is rarely useful and mostly noise, so # let's remove it. del pr['ProcMaps'] pr.add_user_info() # Package and SourcePackage are needed so that apport will report about even # non-packaged versions of bzr; also this reports on their packaged # dependencies which is useful. pr['SourcePackage'] = 'bzr' pr['Package'] = 'bzr' pr['CommandLine'] = pprint.pformat(sys.argv) pr['BzrVersion'] = bzrlib.__version__ pr['PythonVersion'] = bzrlib._format_version_tuple(sys.version_info) pr['Platform'] = platform.platform(aliased=1) pr['UserEncoding'] = osutils.get_user_encoding() pr['FileSystemEncoding'] = sys.getfilesystemencoding() pr['Locale'] = os.environ.get('LANG', 'C') pr['BzrPlugins'] = _format_plugin_list() pr['PythonLoadedModules'] = _format_module_list() pr['BzrDebugFlags'] = pprint.pformat(debug.debug_flags) # actually we'd rather file directly against the upstream product, but # apport does seem to count on there being one in there; we might need to # redirect it elsewhere anyhow pr['SourcePackage'] = 'bzr' pr['Package'] = 'bzr' # tell apport to file directly against the bzr package using # <https://bugs.launchpad.net/bzr/+bug/391015> # # XXX: unfortunately apport may crash later if the crashdb definition # file isn't present pr['CrashDb'] = 'bzr' tb_file = StringIO() traceback.print_exception(exc_type, exc_object, exc_tb, file=tb_file) pr['Traceback'] = tb_file.getvalue() _attach_log_tail(pr) # We want to use the 'bzr' crashdb so that it gets sent directly upstream, # which is a reasonable default for most internal errors. However, if we # set it here then apport will crash later if it doesn't know about that # crashdb. Instead, we rely on the bzr package installing both a # source hook telling crashes to go to this crashdb, and a crashdb # configuration describing it. # these may contain some sensitive info (smtp_passwords) # TODO: strip that out and attach the rest # #attach_file_if_exists(report, # os.path.join(dot_bzr, 'bazaar.conf', 'BzrConfig') #attach_file_if_exists(report, # os.path.join(dot_bzr, 'locations.conf', 'BzrLocations') # strip username, hostname, etc pr.anonymize() if pr.check_ignored(): # eg configured off in ~/.apport-ignore.xml return None else: crash_file_name, crash_file = _open_crash_file() pr.write(crash_file) crash_file.close() return crash_file_name
def show_missing_xml(self, other_branch=None, reverse=False, mine_only=False, theirs_only=False, log_format=None, long=False, short=False, line=False, show_ids=False, verbose=False, this=False, other=False): """output missing info as xml""" if this: mine_only = this if other: theirs_only = other local_branch = Branch.open_containing(u".")[0] parent = local_branch.get_parent() if other_branch is None: other_branch = parent if other_branch is None: raise errors.BzrCommandError("No peer location known" " or specified.") display_url = urlutils.unescape_for_display(other_branch, self.outf.encoding) remote_branch = Branch.open(other_branch) if remote_branch.base == local_branch.base: remote_branch = local_branch local_branch.lock_read() try: remote_branch.lock_read() self.outf.write('<?xml version="1.0" encoding="%s"?>' % \ osutils.get_user_encoding()) self.outf.write('<missing>') try: self.outf.write('<last_location>' + display_url + \ '</last_location>') local_extra, remote_extra = find_unmerged(local_branch, remote_branch) if log_format is None: registry = log_formatter_registry log_format = registry.get_default(local_branch) if reverse is False: local_extra.reverse() remote_extra.reverse() if local_extra and not theirs_only: self.outf.write('<extra_revisions size="%d">' % len(local_extra)) if local_extra > 0: lf = log_format(to_file=self.outf, show_ids=show_ids, show_timezone='original') showlogs(self, iter_log_revisions(local_extra, local_branch.repository, verbose), lf) self.outf.write('</extra_revisions>') if remote_extra and not mine_only: self.outf.write('<missing_revisions size="%d">' % len(remote_extra)) if remote_extra > 0: lf = log_format(to_file=self.outf, show_ids=show_ids, show_timezone='original') showlogs(self, iter_log_revisions(remote_extra, remote_branch.repository, verbose), lf) self.outf.write('</missing_revisions>') if not remote_extra and not local_extra: status_code = 0 # self.outf.write("Branches are up to date.\n") else: status_code = 1 finally: remote_branch.unlock() finally: self.outf.write('</missing>') local_branch.unlock() if not status_code and parent is None and other_branch is not None: local_branch.lock_write() try: # handle race conditions - a parent might be set while we run. if local_branch.get_parent() is None: local_branch.set_parent(remote_branch.base) finally: local_branch.unlock() return status_code
def test_user_cp_unknown(self): self._encoding = 'cp-unknown' self.assertEqual('ascii', osutils.get_user_encoding()) self.assertEqual( 'bzr: warning: unknown encoding cp-unknown.' ' Continuing with ascii encoding.\n', sys.stderr.getvalue())
def test_unable_encode_path(self): err = errors.UnableEncodePath('foo', 'executable') self.assertEquals("Unable to encode executable path 'foo' in " "user encoding " + osutils.get_user_encoding(), str(err))
def test_user_cp0(self): self._encoding = 'cp0' self.assertEquals('ascii', osutils.get_user_encoding()) self.assertEquals('', sys.stderr.getvalue())
def show_missing_xml(self, other_branch=None, reverse=False, mine_only=False, theirs_only=False, log_format=None, long=False, short=False, line=False, show_ids=False, verbose=False, this=False, other=False): """output missing info as xml""" if this: mine_only = this if other: theirs_only = other local_branch = Branch.open_containing(u".")[0] parent = local_branch.get_parent() if other_branch is None: other_branch = parent if other_branch is None: raise errors.BzrCommandError("No peer location known" " or specified.") display_url = urlutils.unescape_for_display(other_branch, self.outf.encoding) remote_branch = Branch.open(other_branch) if remote_branch.base == local_branch.base: remote_branch = local_branch local_branch.lock_read() try: remote_branch.lock_read() self.outf.write('<?xml version="1.0" encoding="%s"?>' % \ osutils.get_user_encoding()) self.outf.write('<missing>') try: self.outf.write('<last_location>' + display_url + \ '</last_location>') local_extra, remote_extra = find_unmerged(local_branch, remote_branch) if log_format is None: registry = log_formatter_registry log_format = registry.get_default(local_branch) if reverse is False: local_extra.reverse() remote_extra.reverse() if local_extra and not theirs_only: self.outf.write('<extra_revisions size="%d">' % len(local_extra)) if local_extra > 0: lf = log_format(to_file=self.outf, show_ids=show_ids, show_timezone='original') showlogs( self, iter_log_revisions(local_extra, local_branch.repository, verbose), lf) self.outf.write('</extra_revisions>') if remote_extra and not mine_only: self.outf.write('<missing_revisions size="%d">' % len(remote_extra)) if remote_extra > 0: lf = log_format(to_file=self.outf, show_ids=show_ids, show_timezone='original') showlogs( self, iter_log_revisions(remote_extra, remote_branch.repository, verbose), lf) self.outf.write('</missing_revisions>') if not remote_extra and not local_extra: status_code = 0 # self.outf.write("Branches are up to date.\n") else: status_code = 1 finally: remote_branch.unlock() finally: self.outf.write('</missing>') local_branch.unlock() if not status_code and parent is None and other_branch is not None: local_branch.lock_write() try: # handle race conditions - a parent might be set while we run. if local_branch.get_parent() is None: local_branch.set_parent(remote_branch.base) finally: local_branch.unlock() return status_code
def test_user_cp_unknown(self): self._encoding = 'cp-unknown' self.assertEquals('ascii', osutils.get_user_encoding()) self.assertEquals('bzr: warning: unknown encoding cp-unknown.' ' Continuing with ascii encoding.\n', sys.stderr.getvalue())
def test_user_empty(self): """Running bzr from a vim script gives '' for a preferred locale""" self._encoding = '' self.assertEquals('ascii', osutils.get_user_encoding()) self.assertEquals('', sys.stderr.getvalue())
def test_user_cp0(self): self._encoding = 'cp0' self.assertEqual('ascii', osutils.get_user_encoding()) self.assertEqual('', sys.stderr.getvalue())
"""bzr library""" import time # Keep track of when bzrlib was first imported, so that we can give rough # timestamps relative to program start in the log file kept by bzrlib.trace. _start_time = time.time() from bzrlib.osutils import get_user_encoding IGNORE_FILENAME = ".bzrignore" # XXX: Compatibility. This should probably be deprecated user_encoding = get_user_encoding() __copyright__ = "Copyright 2005, 2006, 2007, 2008 Canonical Ltd." # same format as sys.version_info: "A tuple containing the five components of # the version number: major, minor, micro, releaselevel, and serial. All # values except releaselevel are integers; the release level is 'alpha', # 'beta', 'candidate', or 'final'. The version_info value corresponding to the # Python version 2.0 is (2, 0, 0, 'final', 0)." Additionally we use a # releaselevel of 'dev' for unreleased under-development code. version_info = (1, 6, 1, 'final', 0) # API compatibility version: bzrlib is currently API compatible with 1.6.
def test_get_user_encoding(self): self._encoding = 'user_encoding' fake_codec.add('user_encoding') self.assertEquals('iso8859-1', # fake_codec maps to latin-1 osutils.get_user_encoding()) self.assertEquals('', sys.stderr.getvalue())
def test_user_empty(self): """Running bzr from a vim script gives '' for a preferred locale""" self._encoding = '' self.assertEqual('ascii', osutils.get_user_encoding()) self.assertEqual('', sys.stderr.getvalue())