Example #1
0
	def __str__(self):
		zsh.eval('_POWERLINE_PARSER_STATE="${(%):-%_}"')
		zsh.eval('_POWERLINE_SHORTENED_PATH="${(%):-%~}"')
		segment_info = {
			'args': self.args,
			'environ': environ,
			'client_id': 1,
			'local_theme': self.theme,
			'parser_state': zsh.getvalue('_POWERLINE_PARSER_STATE'),
			'shortened_path': zsh.getvalue('_POWERLINE_SHORTENED_PATH'),
		}
		zsh.setvalue('_POWERLINE_PARSER_STATE', None)
		zsh.setvalue('_POWERLINE_SHORTENED_PATH', None)
		try:
			zle_rprompt_indent = zsh.getvalue('ZLE_RPROMPT_INDENT')
		except IndexError:
			zle_rprompt_indent = 1
		r = ''
		if self.above:
			for line in self.powerline.render_above_lines(
				width=zsh.columns() - zle_rprompt_indent,
				segment_info=segment_info,
			):
				r += line + '\n'
		r += self.powerline.render(
			width=zsh.columns(),
			side=self.side,
			segment_info=segment_info,
		)
		if type(r) is not str:
			if type(r) is bytes:
				return r.decode(get_preferred_output_encoding(), 'replace')
			else:
				return r.encode(get_preferred_output_encoding(), 'replace')
		return r
Example #2
0
 def __str__(self):
     zsh.eval('_POWERLINE_PARSER_STATE="${(%):-%_}"')
     zsh.eval('_POWERLINE_SHORTENED_PATH="${(%):-%~}"')
     segment_info = {
         'args': self.args,
         'environ': environ,
         'client_id': 1,
         'local_theme': self.theme,
         'parser_state': zsh.getvalue('_POWERLINE_PARSER_STATE'),
         'shortened_path': zsh.getvalue('_POWERLINE_SHORTENED_PATH'),
     }
     zsh.setvalue('_POWERLINE_PARSER_STATE', None)
     zsh.setvalue('_POWERLINE_SHORTENED_PATH', None)
     r = ''
     if self.above:
         for line in self.powerline.render_above_lines(
                 width=zsh.columns() - 1,
                 segment_info=segment_info,
         ):
             r += line + '\n'
     r += self.powerline.render(
         width=zsh.columns(),
         side=self.side,
         segment_info=segment_info,
     )
     if type(r) is not str:
         if type(r) is bytes:
             return r.decode(get_preferred_output_encoding(), 'replace')
         else:
             return r.encode(get_preferred_output_encoding(), 'replace')
     return r
Example #3
0
 def summary(self):
     description = self._repo()['.'].description()
     try:
         summary = description[:description.index('\n')].strip()
     except ValueError:
         summary = description.strip()
     return summary.decode(get_preferred_output_encoding())
Example #4
0
def safe_unicode(s):
    '''Return unicode instance without raising an exception.

    Order of assumptions:
    * ASCII string or unicode object
    * UTF-8 string
    * Object with __str__() or __repr__() method that returns UTF-8 string or
      unicode object (depending on python version)
    * String in powerline.lib.encoding.get_preferred_output_encoding() encoding
    * If everything failed use safe_unicode on last exception with which
      everything failed
    '''
    try:
        try:
            if type(s) is bytes:
                return unicode(s, 'ascii')
            else:
                return unicode(s)
        except UnicodeDecodeError:
            try:
                return unicode(s, 'utf-8')
            except TypeError:
                return unicode(str(s), 'utf-8')
            except UnicodeDecodeError:
                return unicode(s, get_preferred_output_encoding())
    except Exception as e:
        return safe_unicode(e)
Example #5
0
def safe_unicode(s):
	'''Return unicode instance without raising an exception.

	Order of assumptions:
	* ASCII string or unicode object
	* UTF-8 string
	* Object with __str__() or __repr__() method that returns UTF-8 string or 
	  unicode object (depending on python version)
	* String in powerline.lib.encoding.get_preferred_output_encoding() encoding
	* If everything failed use safe_unicode on last exception with which 
	  everything failed
	'''
	try:
		try:
			if type(s) is bytes:
				return unicode(s, 'ascii')
			else:
				return unicode(s)
		except UnicodeDecodeError:
			try:
				return unicode(s, 'utf-8')
			except TypeError:
				return unicode(str(s), 'utf-8')
			except UnicodeDecodeError:
				return unicode(s, get_preferred_output_encoding())
	except Exception as e:
		return safe_unicode(e)
Example #6
0
def create_powerline_logger(args):
    config = get_main_config(args)
    common_config = finish_common_config(get_preferred_output_encoding(),
                                         config['common'])
    logger = create_logger(common_config)
    return PowerlineLogger(use_daemon_threads=True,
                           logger=logger,
                           ext='config')
Example #7
0
	def __str__(self):
		zsh.eval('_POWERLINE_PARSER_STATE="${(%):-%_}"')
		zsh.eval('_POWERLINE_SHORTENED_PATH="${(%):-%~}"')
		try:
			mode = u(zsh.getvalue('_POWERLINE_MODE'))
		except IndexError:
			mode = None
		try:
			default_mode = u(zsh.getvalue('_POWERLINE_DEFAULT_MODE'))
		except IndexError:
			default_mode = None
		segment_info = {
			'args': self.args,
			'environ': environ,
			'client_id': 1,
			'local_theme': self.theme,
			'parser_state': zsh.getvalue('_POWERLINE_PARSER_STATE'),
			'shortened_path': zsh.getvalue('_POWERLINE_SHORTENED_PATH'),
			'mode': mode,
			'default_mode': default_mode,
		}
		zsh.setvalue('_POWERLINE_PARSER_STATE', None)
		zsh.setvalue('_POWERLINE_SHORTENED_PATH', None)
		try:
			zle_rprompt_indent = zsh.getvalue('ZLE_RPROMPT_INDENT')
		except IndexError:
			zle_rprompt_indent = 1
		r = ''
		if self.above:
			for line in self.powerline.render_above_lines(
				width=zsh.columns() - zle_rprompt_indent,
				segment_info=segment_info,
			):
				r += line + '\n'
		r += self.powerline.render(
			width=zsh.columns(),
			side=self.side,
			segment_info=segment_info,
			mode=mode,
		)
		if type(r) is not str:
			if type(r) is bytes:
				return r.decode(get_preferred_output_encoding(), 'replace')
			else:
				return r.encode(get_preferred_output_encoding(), 'replace')
		return r
Example #8
0
	def __str__(self):
		parser_state = u(zsh_expand('${(%):-%_}'))
		shortened_path = u(zsh_expand('${(%):-%~}'))
		try:
			mode = u(zsh.getvalue('_POWERLINE_MODE'))
		except IndexError:
			mode = None
		try:
			default_mode = u(zsh.getvalue('_POWERLINE_DEFAULT_MODE'))
		except IndexError:
			default_mode = None
		segment_info = {
			'args': self.args,
			'environ': environ,
			'client_id': 1,
			'local_theme': self.theme,
			'parser_state': parser_state,
			'shortened_path': shortened_path,
			'mode': mode,
			'default_mode': default_mode,
		}
		try:
			zle_rprompt_indent = zsh.getvalue('ZLE_RPROMPT_INDENT')
		except IndexError:
			zle_rprompt_indent = 1
		r = ''
		if self.above:
			for line in self.powerline.render_above_lines(
				width=zsh.columns() - zle_rprompt_indent,
				segment_info=segment_info,
			):
				if line:
					r += line + '\n'
		r += self.powerline.render(
			width=zsh.columns(),
			side=self.side,
			segment_info=segment_info,
			mode=mode,
		)
		if type(r) is not str:
			if type(r) is bytes:
				return r.decode(get_preferred_output_encoding(), 'replace')
			else:
				return r.encode(get_preferred_output_encoding(), 'replace')
		return r
Example #9
0
 def __new__(cls, s, encoding=None):
     encoding = (encoding or getattr(s, 'encoding', None)
                 or get_preferred_output_encoding())
     if isinstance(s, unicode):
         self = unicode.__new__(cls, s)
     else:
         self = unicode.__new__(cls, s, encoding, 'replace')
     self.encoding = encoding
     return self
Example #10
0
		def __new__(cls, s, encoding=None):
			encoding = (
				encoding
				or getattr(s, 'encoding', None)
				or get_preferred_output_encoding()
			)
			if isinstance(s, unicode):
				self = unicode.__new__(cls, s)
			else:
				self = unicode.__new__(cls, s, encoding, 'replace')
			self.encoding = encoding
			return self
Example #11
0
def out_u(s):
	'''Return unicode string suitable for displaying

	Unlike other functions assumes get_preferred_output_encoding() first. Unlike 
	u() does not throw exceptions for invalid unicode strings. Unlike 
	safe_unicode() does throw an exception if object is not a string.
	'''
	if isinstance(s, unicode):
		return s
	elif isinstance(s, bytes):
		return unicode(s, get_preferred_output_encoding(), 'powerline_decode_error')
	else:
		raise TypeError('Expected unicode or bytes instance, got {0}'.format(repr(type(s))))
Example #12
0
def out_u(s):
	'''Return unicode string suitable for displaying

	Unlike other functions assumes get_preferred_output_encoding() first. Unlike 
	u() does not throw exceptions for invalid unicode strings. Unlike 
	safe_unicode() does throw an exception if object is not a string.
	'''
	if isinstance(s, unicode):
		return s
	elif isinstance(s, bytes):
		return unicode(s, get_preferred_output_encoding(), 'powerline_decode_error')
	else:
		raise TypeError('Expected unicode or bytes instance, got {0}'.format(repr(type(s))))
Example #13
0
def run_cmd(pl, cmd, stdin=None, strip=True):
	'''Run command and return its stdout, stripped

	If running command fails returns None and logs failure to ``pl`` argument.

	:param PowerlineLogger pl:
		Logger used to log failures.
	:param list cmd:
		Command which will be run.
	:param str stdin:
		String passed to command. May be None.
	:param bool strip:
		True if the result should be stripped.
	'''
	try:
		p = Popen(cmd, shell=False, stdout=PIPE, stdin=PIPE)
	except OSError as e:
		pl.exception('Could not execute command ({0}): {1}', e, cmd)
		return None
	else:
		stdout, err = p.communicate(
			stdin if stdin is None else stdin.encode(get_preferred_output_encoding()))
		stdout = stdout.decode(get_preferred_input_encoding())
	return stdout.strip() if strip else stdout
Example #14
0
def run_cmd(pl, cmd, stdin=None, strip=True):
    '''Run command and return its stdout, stripped

    If running command fails returns None and logs failure to ``pl`` argument.

    :param PowerlineLogger pl:
        Logger used to log failures.
    :param list cmd:
        Command which will be run.
    :param str stdin:
        String passed to command. May be None.
    :param bool strip:
        True if the result should be stripped.
    '''
    try:
        p = Popen(cmd, shell=False, stdout=PIPE, stdin=PIPE)
    except OSError as e:
        pl.exception('Could not execute command ({0}): {1}', e, cmd)
        return None
    else:
        stdout, err = p.communicate(stdin if stdin is None else stdin.
                                    encode(get_preferred_output_encoding()))
        stdout = stdout.decode(get_preferred_input_encoding())
    return stdout.strip() if strip else stdout
Example #15
0
def create_powerline_logger(args):
	config = get_main_config(args)
	common_config = finish_common_config(get_preferred_output_encoding(), config['common'])
	logger = create_logger(common_config)
	return PowerlineLogger(use_daemon_threads=True, logger=logger, ext='config')
Example #16
0
def create_powerline_logger(args):
    config = get_main_config(args)
    common_config = finish_common_config(get_preferred_output_encoding(),
                                         config['common'])
    logger, pl, get_module_attr = create_logger(common_config)
    return pl
Example #17
0
def create_powerline_logger(args):
	config = get_main_config(args)
	common_config = finish_common_config(get_preferred_output_encoding(), config['common'])
	logger, pl, get_module_attr = create_logger(common_config)
	return pl
Example #18
0
        try:
            return func(*args, **kwargs)
        except EnvironmentError as e:
            if getattr(e, 'errno', None) == errno.EINTR:
                continue
            raise


try:
    eintr_retry_call(sock.connect, address)
except Exception:
    # Run the powerline renderer
    args = ['powerline-render'] + sys.argv[1:]
    os.execvp('powerline-render', args)

fenc = get_preferred_output_encoding()


def tobytes(s):
    if isinstance(s, bytes):
        return s
    else:
        return s.encode(fenc)


args = [tobytes('%x' % (len(sys.argv) - 1))]
args.extend((tobytes(s) for s in sys.argv[1:]))

try:
    cwd = os.getcwd()
except EnvironmentError:
Example #19
0
		try:
			return func(*args, **kwargs)
		except EnvironmentError as e:
			if getattr(e, 'errno', None) == errno.EINTR:
				continue
			raise


try:
	eintr_retry_call(sock.connect, address)
except Exception:
	# Run the powerline renderer
	args = ['powerline-render'] + sys.argv[1:]
	os.execvp('powerline-render', args)

fenc = get_preferred_output_encoding()


def tobytes(s):
	if isinstance(s, bytes):
		return s
	else:
		return s.encode(fenc)


args = [tobytes('%x' % (len(sys.argv) - 1))]
args.extend((tobytes(s) for s in sys.argv[1:]))


try:
	cwd = os.getcwd()
Example #20
0
 def echoerr(**kwargs):
     stream = kwargs.pop('stream', sys.stderr)
     stream.write('\n')
     stream.write((format_error(**kwargs) + '\n').encode(
         get_preferred_output_encoding()))
Example #21
0
	def echoerr(**kwargs):
		stream = kwargs.pop('stream', sys.stderr)
		stream.write('\n')
		stream.write((format_error(**kwargs) + '\n').encode(get_preferred_output_encoding()))