Exemplo n.º 1
0
    def execute_dump(self):
        '''
        Shows the current settings, merges assible.cfg if specified
        '''
        # FIXME: deal with plugins, not just base config
        text = []
        defaults = self.config.get_configuration_definitions().copy()
        for setting in self.config.data.get_settings():
            if setting.name in defaults:
                defaults[setting.name] = setting

        for setting in sorted(defaults):
            if isinstance(defaults[setting], Setting):
                if defaults[setting].origin == 'default':
                    color = 'green'
                else:
                    color = 'yellow'
                msg = "%s(%s) = %s" % (setting, defaults[setting].origin,
                                       defaults[setting].value)
            else:
                color = 'green'
                msg = "%s(%s) = %s" % (setting, 'default',
                                       defaults[setting].get('default'))
            if not context.CLIARGS['only_changed'] or color == 'yellow':
                text.append(stringc(msg, color))

        self.pager(to_text('\n'.join(text), errors='surrogate_or_strict'))
Exemplo n.º 2
0
    def get_credentials(self):
        display.display(u'\n\n' + "We need your " + stringc("GitHub login", 'bright cyan') +
                        " to identify you.", screen_only=True)
        display.display("This information will " + stringc("not be sent to Galaxy", 'bright cyan') +
                        ", only to " + stringc("api.github.com.", "yellow"), screen_only=True)
        display.display("The password will not be displayed." + u'\n\n', screen_only=True)
        display.display("Use " + stringc("--github-token", 'yellow') +
                        " if you do not want to enter your password." + u'\n\n', screen_only=True)

        try:
            self.github_username = input("GitHub Username: "******"Password for %s: " % self.github_username)
        except Exception:
            pass

        if not self.github_username or not self.github_password:
            raise AssibleError("Invalid GitHub credentials. Username and password are required.")
Exemplo n.º 3
0
 def set_prompt(self):
     login_user = self.remote_user or getpass.getuser()
     self.selected = self.inventory.list_hosts(self.cwd)
     prompt = "%s@%s (%d)[f:%s]" % (login_user, self.cwd, len(
         self.selected), self.forks)
     if self.become and self.become_user in [None, 'root']:
         prompt += "# "
         color = C.COLOR_ERROR
     else:
         prompt += "$ "
         color = self.NORMAL_PROMPT
     self.prompt = stringc(prompt, color, wrap_nonvisible_chars=True)
Exemplo n.º 4
0
 def helpdefault(self, module_name):
     if module_name in self.modules:
         in_path = module_loader.find_plugin(module_name)
         if in_path:
             oc, a, _, _ = plugin_docs.get_docstring(
                 in_path, fragment_loader)
             if oc:
                 display.display(oc['short_description'])
                 display.display('Parameters:')
                 for opt in oc['options'].keys():
                     display.display('  ' +
                                     stringc(opt, self.NORMAL_PROMPT) +
                                     ' ' +
                                     oc['options'][opt]['description'][0])
             else:
                 display.error('No documentation found for %s.' %
                               module_name)
         else:
             display.error(
                 '%s is not a valid command, use ? to list all valid commands.'
                 % module_name)
Exemplo n.º 5
0
    def display(self,
                msg,
                color=None,
                stderr=False,
                screen_only=False,
                log_only=False,
                newline=True):
        """ Display a message to the user

        Note: msg *must* be a unicode string to prevent UnicodeError tracebacks.
        """

        nocolor = msg

        if not log_only:

            has_newline = msg.endswith(u'\n')
            if has_newline:
                msg2 = msg[:-1]
            else:
                msg2 = msg

            if color:
                msg2 = stringc(msg2, color)

            if has_newline or newline:
                msg2 = msg2 + u'\n'

            msg2 = to_bytes(msg2,
                            encoding=self._output_encoding(stderr=stderr))
            if sys.version_info >= (3, ):
                # Convert back to text string on python3
                # We first convert to a byte string so that we get rid of
                # characters that are invalid in the user's locale
                msg2 = to_text(msg2,
                               self._output_encoding(stderr=stderr),
                               errors='replace')

            # Note: After Display() class is refactored need to update the log capture
            # code in 'bin/assible-connection' (and other relevant places).
            if not stderr:
                fileobj = sys.stdout
            else:
                fileobj = sys.stderr

            fileobj.write(msg2)

            try:
                fileobj.flush()
            except IOError as e:
                # Ignore EPIPE in case fileobj has been prematurely closed, eg.
                # when piping to "head -n1"
                if e.errno != errno.EPIPE:
                    raise

        if logger and not screen_only:
            # We first convert to a byte string so that we get rid of
            # color and characters that are invalid in the user's locale
            msg2 = to_bytes(nocolor.lstrip(u'\n'))

            if sys.version_info >= (3, ):
                # Convert back to text string on python3
                msg2 = to_text(msg2, self._output_encoding(stderr=stderr))

            lvl = logging.INFO
            if color:
                # set logger level based on color (not great)
                try:
                    lvl = color_to_log_level[color]
                except KeyError:
                    # this should not happen, but JIC
                    raise AssibleAssertionError(
                        'Invalid color supplied to display: %s' % color)
            # actually log
            logger.log(lvl, msg2)
Exemplo n.º 6
0
    def _get_diff(self, difflist):

        if not isinstance(difflist, list):
            difflist = [difflist]

        ret = []
        for diff in difflist:
            if 'dst_binary' in diff:
                ret.append(
                    u"diff skipped: destination file appears to be binary\n")
            if 'src_binary' in diff:
                ret.append(u"diff skipped: source file appears to be binary\n")
            if 'dst_larger' in diff:
                ret.append(
                    u"diff skipped: destination file size is greater than %d\n"
                    % diff['dst_larger'])
            if 'src_larger' in diff:
                ret.append(
                    u"diff skipped: source file size is greater than %d\n" %
                    diff['src_larger'])
            if 'before' in diff and 'after' in diff:
                # format complex structures into 'files'
                for x in ['before', 'after']:
                    if isinstance(diff[x], MutableMapping):
                        diff[x] = self._serialize_diff(diff[x])
                    elif diff[x] is None:
                        diff[x] = ''
                if 'before_header' in diff:
                    before_header = u"before: %s" % diff['before_header']
                else:
                    before_header = u'before'
                if 'after_header' in diff:
                    after_header = u"after: %s" % diff['after_header']
                else:
                    after_header = u'after'
                before_lines = diff['before'].splitlines(True)
                after_lines = diff['after'].splitlines(True)
                if before_lines and not before_lines[-1].endswith(u'\n'):
                    before_lines[-1] += u'\n\\ No newline at end of file\n'
                if after_lines and not after_lines[-1].endswith('\n'):
                    after_lines[-1] += u'\n\\ No newline at end of file\n'
                differ = difflib.unified_diff(before_lines,
                                              after_lines,
                                              fromfile=before_header,
                                              tofile=after_header,
                                              fromfiledate=u'',
                                              tofiledate=u'',
                                              n=C.DIFF_CONTEXT)
                difflines = list(differ)
                if len(difflines) >= 3 and sys.version_info[:2] == (2, 6):
                    # difflib in Python 2.6 adds trailing spaces after
                    # filenames in the -- before/++ after headers.
                    difflines[0] = difflines[0].replace(u' \n', u'\n')
                    difflines[1] = difflines[1].replace(u' \n', u'\n')
                    # it also treats empty files differently
                    difflines[2] = difflines[2].replace(u'-1,0',
                                                        u'-0,0').replace(
                                                            u'+1,0', u'+0,0')
                has_diff = False
                for line in difflines:
                    has_diff = True
                    if line.startswith(u'+'):
                        line = stringc(line, C.COLOR_DIFF_ADD)
                    elif line.startswith(u'-'):
                        line = stringc(line, C.COLOR_DIFF_REMOVE)
                    elif line.startswith(u'@@'):
                        line = stringc(line, C.COLOR_DIFF_LINES)
                    ret.append(line)
                if has_diff:
                    ret.append('\n')
            if 'prepared' in diff:
                ret.append(diff['prepared'])
        return u''.join(ret)