Esempio n. 1
0
def initialize_formatter(config):
    """Return the initialized output formatter based upon the configuration."""
    if config.json:  # pylint: disable=R1705
        return formatters.JsonFormatter()
    elif config.severity:  # pylint: disable=R1705
        return formatters.SeverityFormatter(config.colored)
    return formatters.Formatter(config.colored)
Esempio n. 2
0
def run(args=None):
    # Wrap `sys.stdout` in an object that automatically encodes an unicode
    # string into utf-8, in Python 2 only. The default encoding for Python 3
    # is already utf-8.
    if sys.version_info[0] < 3:
        sys.stdout = codecs.getwriter('utf-8')(sys.stdout)

    parser = optparse.OptionParser("%prog [options] init.sls [state ...]",
                                   version='{} {}'.format(NAME, VERSION))

    parser.add_option('-L',
                      dest='listrules',
                      default=False,
                      action='store_true',
                      help="list all the rules")
    parser.add_option('-r',
                      action='append',
                      dest='rulesdir',
                      default=[],
                      type='str',
                      help="specify one or more rules directories using "
                      "one or more -r arguments. Any -r flags override "
                      "the default rules in %s, unless -R is also used." %
                      default_rulesdir)
    parser.add_option('-R',
                      action='store_true',
                      default=False,
                      dest='use_default_rules',
                      help="Use default rules in %s in addition to any extra "
                      "rules directories specified with -r. There is "
                      "no need to specify this if no -r flags are used." %
                      default_rulesdir)
    parser.add_option('-t',
                      dest='tags',
                      action='append',
                      default=[],
                      help="only check rules whose id/tags match these values")
    parser.add_option('-T',
                      dest='listtags',
                      action='store_true',
                      help="list all the tags")
    parser.add_option('-v',
                      dest='verbosity',
                      action='count',
                      help="Increase verbosity level",
                      default=0)
    parser.add_option('-x',
                      dest='skip_list',
                      default=[],
                      action='append',
                      help="only check rules whose id/tags do not " +
                      "match these values")
    parser.add_option('--nocolor',
                      '--nocolour',
                      dest='colored',
                      default=hasattr(sys.stdout, 'isatty')
                      and sys.stdout.isatty(),
                      action='store_false',
                      help="disable colored output")
    parser.add_option('--force-color',
                      '--force-colour',
                      dest='colored',
                      action='store_true',
                      help="Try force colored output (relying on salt's code)")
    parser.add_option('--exclude',
                      dest='exclude_paths',
                      action='append',
                      help='path to directories or files to skip. This option'
                      ' is repeatable.',
                      default=[])
    parser.add_option('--json',
                      dest='json',
                      action='store_true',
                      default=False,
                      help='parse the output as JSON')
    parser.add_option('--severity',
                      dest='severity',
                      action='store_true',
                      default=False,
                      help='add the severity to the standard output')
    parser.add_option(
        '-c',
        help='Specify configuration file to use.  Defaults to ".salt-lint"')
    (options, parsed_args
     ) = parser.parse_args(args if args is not None else sys.argv[1:])

    stdin_state = None
    states = set(parsed_args)
    matches = []
    checked_files = set()

    # Read input from stdin
    if not sys.stdin.isatty():
        stdin_state = tempfile.NamedTemporaryFile('w',
                                                  suffix='.sls',
                                                  delete=False)
        stdin_state.write(sys.stdin.read())
        stdin_state.flush()
        states.add(stdin_state.name)

    # Read, parse and validate the configuration
    options_dict = vars(options)
    try:
        config = SaltLintConfig(options_dict)
    except SaltLintConfigError as exc:
        print(exc)
        return 2

    # Show a help message on the screen
    if not states and not (options.listrules or options.listtags):
        parser.print_help(file=sys.stderr)
        return 1

    # Collect the rules from the configution
    rules = RulesCollection(config)
    for rulesdir in config.rulesdirs:
        rules.extend(RulesCollection.create_from_directory(rulesdir, config))

    # Show the rules listing
    if options.listrules:
        print(rules)
        return 0

    # Show the tags listing
    if options.listtags:
        print(rules.listtags())
        return 0

    # Define the formatter
    if config.json:
        formatter = formatters.JsonFormatter()
    elif config.severity:
        formatter = formatters.SeverityFormatter(config.colored)
    else:
        formatter = formatters.Formatter(config.colored)

    for state in states:
        runner = Runner(rules, state, config, checked_files)
        matches.extend(runner.run())

    # Sort the matches
    matches.sort(key=lambda x: (x.filename, x.linenumber, x.rule.id))

    # Show the matches on the screen
    formatter.process(matches)

    # Delete stdin temporary file
    if stdin_state:
        os.unlink(stdin_state.name)

    # Return the exit code
    if matches:
        return 2

    return 0
Esempio n. 3
0
def run(args=None):
    formatter = formatters.Formatter()

    parser = optparse.OptionParser("%prog [options] init.sls [state ...]",
                                   version='{} {}'.format(NAME, VERSION))

    parser.add_option('-L', dest='listrules', default=False,
                      action='store_true', help="list all the rules")
    parser.add_option('-r', action='append', dest='rulesdir',
                      default=[], type='str',
                      help="specify one or more rules directories using "
                           "one or more -r arguments. Any -r flags override "
                           "the default rules in %s, unless -R is also used."
                           % default_rulesdir)
    parser.add_option('-R', action='store_true',
                      default=False,
                      dest='use_default_rules',
                      help="Use default rules in %s in addition to any extra "
                           "rules directories specified with -r. There is "
                           "no need to specify this if no -r flags are used."
                           % default_rulesdir)
    parser.add_option('-t', dest='tags',
                      action='append',
                      default=[],
                      help="only check rules whose id/tags match these values")
    parser.add_option('-T', dest='listtags', action='store_true',
                      help="list all the tags")
    parser.add_option('-v', dest='verbosity', action='count',
                      help="Increase verbosity level",
                      default=0)
    parser.add_option('-x', dest='skip_list', default=[], action='append',
                      help="only check rules whose id/tags do not " +
                      "match these values")
    parser.add_option('--nocolor', dest='colored',
                      default=hasattr(sys.stdout, 'isatty') and sys.stdout.isatty(),
                      action='store_false',
                      help="disable colored output")
    parser.add_option('--force-color', dest='colored',
                      action='store_true',
                      help="Try force colored output (relying on salt's code)")
    parser.add_option('--exclude', dest='exclude_paths', action='append',
                      help='path to directories or files to skip. This option'
                           ' is repeatable.',
                      default=[])
    parser.add_option('-c', help='Specify configuration file to use.  Defaults to ".salt-lint"')
    (options, parsed_args) = parser.parse_args(args if args is not None else sys.argv[1:])

    # Read, parse and validate the configration
    options_dict = vars(options)
    try:
        config = SaltLintConfig(options_dict)
    except SaltLintConfigError as exc:
        print(exc)
        return 2

    # Show a help message on the screen
    if len(parsed_args) == 0 and not (options.listrules or options.listtags):
        parser.print_help(file=sys.stderr)
        return 1

    # Collect the rules from the configution
    rules = RulesCollection(config)
    for rulesdir in config.rulesdirs:
        rules.extend(RulesCollection.create_from_directory(rulesdir, config))

    # Show the rules listing
    if options.listrules:
        print(rules)
        return 0

    # Show the tags listing
    if options.listtags:
        print(rules.listtags())
        return 0

    states = set(parsed_args)
    matches = list()
    checked_files = set()
    for state in states:
        runner = Runner(rules, state, config, checked_files)
        matches.extend(runner.run())

    # Sort the matches
    matches.sort(key=lambda x: (x.filename, x.linenumber, x.rule.id))

    # Show the matches on the screen
    for match in matches:
        print(formatter.format(match, config.colored).encode('utf-8'))

    # Return the exit code
    if len(matches):
        return 2
    else:
        return 0
Esempio n. 4
0
def main():

    formatter = formatters.Formatter()

    parser = optparse.OptionParser("%prog [options] init.sls [state ...]",
                                   version="%prog " + __version__)

    parser.add_option('-L', dest='listrules', default=False,
                      action='store_true', help="list all the rules")
    parser.add_option('-r', action='append', dest='rulesdir',
                      default=[], type='str',
                      help="specify one or more rules directories using "
                           "one or more -r arguments. Any -r flags override "
                           "the default rules in %s, unless -R is also used."
                           % saltlint.default_rulesdir)
    parser.add_option('-R', action='store_true',
                      default=False,
                      dest='use_default_rules',
                      help="Use default rules in %s in addition to any extra "
                           "rules directories specified with -r. There is "
                           "no need to specify this if no -r flags are used."
                           % saltlint.default_rulesdir)
    parser.add_option('-t', dest='tags',
                      action='append',
                      default=[],
                      help="only check rules whose id/tags match these values")
    parser.add_option('-T', dest='listtags', action='store_true',
                      help="list all the tags")
    parser.add_option('-v', dest='verbosity', action='count',
                      help="Increase verbosity level",
                      default=0)
    parser.add_option('-x', dest='skip_list', default=[], action='append',
                      help="only check rules whose id/tags do not " +
                      "match these values")
    parser.add_option('--nocolor', dest='colored',
                      default=hasattr(sys.stdout, 'isatty') and sys.stdout.isatty(),
                      action='store_false',
                      help="disable colored output")
    parser.add_option('--force-color', dest='colored',
                      action='store_true',
                      help="Try force colored output (relying on salt's code)")
    parser.add_option('--exclude', dest='exclude_paths', action='append',
                      help='path to directories or files to skip. This option'
                           ' is repeatable.',
                      default=[])
    parser.add_option('-c', help='Specify configuration file to use.  Defaults to ".salt-lint"')
    options, args = parser.parse_args(sys.argv[1:])

    config = load_config(options.c)

    if config:
        # TODO parse configuration options

        if 'verbosity' in config:
            options.verbosity = options.verbosity + config['verbosity']

        if 'exclude_paths' in config:
            options.exclude_paths = options.exclude_paths + config['exclude_paths']

        if 'skip_list' in config:
            options.skip_list = options.skip_list + config['skip_list']

        if 'tags' in config:
            options.tags = options.tags + config['tags']

        if 'use_default_rules' in config:
            options.use_default_rules = options.use_default_rules or config['use_default_rules']

        if 'rulesdir' in config:
            options.rulesdir = options.rulesdir + config['rulesdir']

    if len(args) == 0 and not (options.listrules or options.listtags):
        parser.print_help(file=sys.stderr)
        return 1

    if options.use_default_rules:
        rulesdirs = options.rulesdir + [saltlint.default_rulesdir]
    else:
        rulesdirs = options.rulesdir or [saltlint.default_rulesdir]

    rules = RulesCollection()
    for rulesdir in rulesdirs:
        rules.extend(RulesCollection.create_from_directory(rulesdir))

    if options.listrules:
        print(rules)
        return 0

    if options.listtags:
        print(rules.listtags())
        return 0

    if isinstance(options.tags, six.string_types):
        options.tags = options.tags.split(',')

    skip = set()
    for s in options.skip_list:
        skip.update(str(s).split(','))
    options.skip_list = frozenset(skip)

    states = set(args)
    matches = list()
    checked_files = set()
    for state in states:
        runner = saltlint.Runner(rules, state, options.tags,
                                 options.skip_list, options.exclude_paths,
                                 options.verbosity, checked_files)
        matches.extend(runner.run())

    matches.sort(key=lambda x: (x.filename, x.linenumber, x.rule.id))

    for match in matches:
        print(formatter.format(match, options.colored))

    if len(matches):
        return 2
    else:
        return 0