def run_bzr_decode(self, args, encoding=None, fail=False, retcode=None, working_dir=None): """Run brz 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_raw(args, encoding=encoding, retcode=retcode, working_dir=working_dir)[0] return out.decode(encoding) except UnicodeError as e: if not fail: raise else: # This command, run from the regular command line, will give a # traceback to the user. That's not really good for a situation # that can be provoked just by the interaction of their input data # and locale, as some of these are. What would be better? if fail: self.fail("Expected UnicodeError not raised")
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('BRZ_HOME', uni_val) self.permit_source_tree_branch_repo() out = self.run_bzr_raw("version")[0] self.assertTrue(len(out) > 0) self.assertContainsRe(out, br"(?m)^ Breezy configuration: " + str_val)
def setUp(self): super(TestNonAscii, self).setUp() self._check_can_encode_paths() self.overrideAttr(osutils, '_cached_user_encoding', self.encoding) email = self.info['committer'] + ' <*****@*****.**>' if sys.version_info[0] == 2: self.overrideEnv('BRZ_EMAIL', email.encode( osutils.get_user_encoding())) else: self.overrideEnv('BRZ_EMAIL', email) self.create_base()
def test_unicode_brz_log(self): uni_val = u"\xa7" enc = osutils.get_user_encoding() try: str_val = uni_val.encode(enc) except UnicodeEncodeError: self.skipTest( "Test string %r unrepresentable in user encoding %s" % (uni_val, enc)) brz_log = os.path.join(self.test_base_dir, uni_val) self.overrideEnv("BRZ_LOG", brz_log) out, err = self.run_bzr_subprocess("version") uni_out = out.decode(enc) self.assertContainsRe(uni_out, u"(?m)^ Breezy log file: .*/\xa7$")
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 = list(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 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 breezy 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"] = breezy.__version__ result["bzr-lib-path"] = breezy.__path__ # is breezy 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 config_dir = osutils.normpath(bedding.config_dir()) if not isinstance(config_dir, str): config_dir = config_dir.decode(osutils.get_user_encoding()) result["brz-config-dir"] = config_dir result["brz-log-file"] = trace._brz_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"] = breezy._format_version_tuple(sys.version_info) result["python-lib-dir"] = os.path.dirname(os.__file__) return result
def test_cmd_dailydeb_with_nonascii_maintainer_in_changelog(self): user_enc = osutils.get_user_encoding() try: os.environ["DEBFULLNAME"] = u"Micha\u25c8 Sawicz".encode(user_enc) except UnicodeEncodeError: self.skip("Need user encoding other than %r to test maintainer " "name from environment" % (user_enc, )) self.make_simple_package("source") self.build_tree_contents([("test.recipe", "# bzr-builder format 0.1 " "deb-version 1\nsource 1\n")]) out, err = self.run_bzr("dailydeb -q test.recipe working") new_cl_contents = ("package (1) unstable; urgency=low\n\n" " * Auto build.\n\n" " -- Micha\xe2\x97\x88 Sawicz <*****@*****.**> ") actual_cl_contents = self._get_file_contents( "working/test-1/debian/changelog") self.assertStartsWith(actual_cl_contents, new_cl_contents)
def complete(self, words, cword=-1): """Perform a bash completion. :param words: a list of words representing the current command. :param cword: the current word to complete, defaults to the last one. """ if self.script is None: self.script = self.get_script() proc = subprocess.Popen([features.bash_feature.path, '--noprofile'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={'PYTHONPATH': ':'.join(sys.path)}) if cword < 0: cword = len(words) + cword encoding = osutils.get_user_encoding() input = b'%s\n' % self.script.encode(encoding) input += (b'COMP_WORDS=( %s )\n' % b' '.join([ b"'" + w.replace("'", "'\\''").encode(encoding) + b"'" for w in words ])) input += b'COMP_CWORD=%d\n' % cword input += b'%s\n' % getattr(self, 'script_name', '_brz').encode(encoding) input += b'echo ${#COMPREPLY[*]}\n' input += b"IFS=$'\\n'\n" input += b'echo "${COMPREPLY[*]}"\n' (out, err) = proc.communicate(input) if b'' != err: raise AssertionError('Unexpected error message:\n%s' % err) self.assertEqual(b'', err, 'No messages to standard error') #import sys #print >>sys.stdout, '---\n%s\n---\n%s\n---\n' % (input, out) lines = out.split(b'\n') nlines = int(lines[0]) del lines[0] self.assertEqual(b'', lines[-1], 'Newline at end') del lines[-1] if nlines == 0 and len(lines) == 1 and lines[0] == b'': del lines[0] self.assertEqual(nlines, len(lines), 'No newlines in generated words') self.completion_result = {l.decode(encoding) for l in lines} return self.completion_result
try: substitute_changelog_vars(base_branch, None, cl) except SubstitutionUnavailable, e: raise errors.BzrCommandError( "No previous changelog to " "take the upstream version from as %s was " "used: %s: %s." % (e.name, e.reason, reason)) # Use debian packaging environment variables # or default values if they don't exist if author_name is None or author_email is None: author_name, author_email = get_maintainer() # The python-debian package breaks compatibility at version 0.1.20 by # switching to expecting (but not checking for) unicode rather than # bytestring inputs. Detect this and decode environment if needed. if getattr(changelog.Changelog, "__unicode__", None) is not None: enc = osutils.get_user_encoding() author_name = author_name.decode(enc) author_email = author_email.decode(enc) author = "%s <%s>" % (author_name, author_email) date = utils.formatdate(localtime=True) version = base_branch.deb_version if append_version is not None: version += append_version try: changelog.Version(version) except (changelog.VersionError, ValueError), e: raise errors.BzrCommandError("Invalid deb-version: %s: %s" % (version, e)) cl.new_block(package=package, version=version,
def report_exception(exc_info=None, type=MAIN_LOAD_METHOD, window=None, ui_mode=False): """Report an exception. The error is reported to the console or a message box, depending on the type. """ # We only want one error to show if the user chose Close global closing_due_to_error # 0.20 special: We check hasattr() first to work around # <http://bugs.python.org/issue4230> if closing_due_to_error or (hasattr(window, 'closing_due_to_error') and window.closing_due_to_error): return if exc_info is None: exc_info = sys.exc_info() exc_type, exc_object, exc_tb = exc_info # Don't show error for StopException if isinstance(exc_object, StopException): # Do we maybe want to log this? return # RJLRJL check for bzr / brz issues msg_box = ((type == MAIN_LOAD_METHOD and (window and window.ui_mode or ui_mode)) or not type == MAIN_LOAD_METHOD) pdb = os.environ.get('BZR_PDB') if pdb: msg_box = False if msg_box: err_file = StringIO() else: err_file = sys.stderr # always tell bzr to report it, so it ends up in the log. # See https://bugs.launchpad.net/bzr/+bug/785695 error_type = _breezy_report_exception(exc_info, err_file) backtrace = traceback.format_exception(*exc_info) mutter(''.join(backtrace)) if (type == MAIN_LOAD_METHOD and window): window.ret_code = error_type # XXX This is very similar to breezy.commands.exception_to_return_code. # We shoud get bzr to refactor so that that this is reuseable. if pdb: # With out this - pyQt shows lot of warnings. see: # http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#using-pyqt-from-the-python-shell QtCore.pyqtRemoveInputHook() print('**** entering debugger') tb = exc_info[2] import pdb if sys.version_info[:2] < (2, 6): # XXX: we want to do # pdb.post_mortem(tb) # but because pdb.post_mortem gives bad results for tracebacks # from inside generators, we do it manually. # (http://bugs.python.org/issue4150, fixed in Python 2.6) # Setup pdb on the traceback p = pdb.Pdb() p.reset() p.setup(tb.tb_frame, tb) # Point the debugger at the deepest frame of the stack p.curindex = len(p.stack) - 1 p.curframe = p.stack[p.curindex][0] # Start the pdb prompt. p.print_stack_entry(p.stack[p.curindex]) p.execRcLines() p.cmdloop() else: pdb.post_mortem(tb) close = True if msg_box: if isinstance(exc_object, errors.LockContention): msg_box = create_lockerror_dialog(error_type, window) elif error_type == errors.EXIT_INTERNAL_ERROR: # this is a copy of breezy.trace.report_bug # but we seperate the message, and the trace back, # and addes a hyper link to the filebug page. traceback_file = StringIO() _breezy_print_exception(exc_info, traceback_file) traceback_file.write('\n') traceback_file.write( 'brz %s on python %s (%s)\n' % (breezy.__version__, breezy._format_version_tuple(sys.version_info), sys.platform)) traceback_file.write('arguments: %r\n' % sys.argv) traceback_file.write( 'encoding: %r, fsenc: %r, lang: %r\n' % (osutils.get_user_encoding(), sys.getfilesystemencoding(), os.environ.get('LANG'))) traceback_file.write("plugins:\n") for name, a_plugin in sorted(plugin.plugins().items()): traceback_file.write( " %-20s %s [%s]\n" % (name, a_plugin.path(), a_plugin.__version__)) msg_box = ErrorReport(gettext("Error"), True, traceback_file.getvalue(), exc_info, type, window) else: msg_box = ErrorReport(gettext("Error"), False, err_file.getvalue(), exc_info, type, window) # RJLRJL check for bzr / brz issues if window is None: icon = QtGui.QIcon() icon.addFile(":/bzr-16.png", QtCore.QSize(16, 16)) icon.addFile(":/bzr-32.png", QtCore.QSize(32, 32)) icon.addFile(":/bzr-48.png", QtCore.QSize(48, 48)) msg_box.setWindowIcon(icon) msg_box.exec_() if not msg_box.result() == QtWidgets.QMessageBox.Close: close = False if close: if window is None: closing_due_to_error = True QtCore.QCoreApplication.instance().quit() else: window.closing_due_to_error = True window.close() return error_type
def add_autobuild_changelog_entry(base_branch, basedir, package, distribution=None, author_name=None, author_email=None, append_version=None): """Add a new changelog entry for an autobuild. :param base_branch: Recipe base branch :param basedir: Base working directory :param package: package name :param distribution: Optional distribution (defaults to last entry distribution) :param author_name: Name of the build requester :param author_email: Email of the build requester :param append_version: Optional version suffix to add """ debian_dir = os.path.join(basedir, "debian") if not os.path.exists(debian_dir): os.makedirs(debian_dir) cl_path = os.path.join(debian_dir, "changelog") file_found = False if os.path.exists(cl_path): file_found = True cl_f = open(cl_path) try: contents = cl_f.read() finally: cl_f.close() cl = changelog.Changelog(file=contents) else: cl = changelog.Changelog() if len(cl._blocks) > 0: if distribution is None: distribution = cl._blocks[0].distributions.split()[0] else: if file_found: if len(contents.strip()) > 0: reason = ("debian/changelog didn't contain any " "parseable stanzas") else: reason = "debian/changelog was empty" else: reason = "debian/changelog was not present" if distribution is None: distribution = DEFAULT_UBUNTU_DISTRIBUTION if base_branch.format in (0.1, 0.2, 0.3): try: substitute_changelog_vars(base_branch, None, cl) except SubstitutionUnavailable as e: raise errors.BzrCommandError( "No previous changelog to " "take the upstream version from as %s was " "used: %s: %s." % (e.name, e.reason, reason)) # Use debian packaging environment variables # or default values if they don't exist if author_name is None or author_email is None: author_name, author_email = changelog.get_maintainer() # The python-debian package breaks compatibility at version 0.1.20 by # switching to expecting (but not checking for) unicode rather than # bytestring inputs. Detect this and decode environment if needed. if getattr(changelog.Changelog, "__unicode__", None) is not None: enc = osutils.get_user_encoding() author_name = author_name.decode(enc) author_email = author_email.decode(enc) author = "%s <%s>" % (author_name, author_email) date = utils.formatdate(localtime=True) version = base_branch.deb_version if append_version is not None: version += append_version try: changelog.Version(version) except (changelog.VersionError, ValueError) as e: raise errors.BzrCommandError("Invalid deb-version: %s: %s" % (version, e)) cl.new_block(package=package, version=version, distributions=distribution, urgency="low", changes=['', ' * Auto build.', ''], author=author, date=date) with open(cl_path, 'w') as cl_f: cl.write_to_open_file(cl_f)