A method that takes the ShellCheck summary and parses any violations found
353547
def parse_files(shellcheck_summary)
      shellcheck_summary.each do |element|
        file = element[:file]
        @files.add(file)
        level = element[:level]

        message = format_violation(file, element)

        if level == 'error'
          @error_count += 1
          fail(message, sticky: false)
        else
          if level == 'warning'
            @warning_count += 1
          elsif level == 'info'
            @info_count += 1
          else
            @style_count += 1
          end
          warn(message, sticky: false)
        end
      end
    end
568851
function check(result, test) {

  const CHECKERS = [ _checkExitCode, _checkOutput, _checkStdout, _checkStderr ];
  var errors = [];

  CHECKERS.forEach(function (checker) {
    var error = checker(result, test);
    if (error) {
      errors.push(error);
    }
  });
  
  return errors;
}
74538
function checkCommand (command, errorCallback) {
    var exec = command
    var args = this.argsExecutable
    var shell = false
    if (this.win) {
      // Arguments have to be manually quoted
      exec = `"${exec}"`
      args = args.map(a => `"${a}"`)
      shell = true
    }

    this.log.verbose(`- executing "${command}" to get executable path`)
    this.run(exec, args, shell, function (err, execPath) {
      // Possible outcomes:
      // - Error: not in PATH, not executable or execution fails
      // - Gibberish: the next command to check version will fail
      // - Absolute path to executable
      if (err) {
        this.addLog(`- "${command}" is not in PATH or produced an error`)
        return errorCallback(err)
      }
      this.addLog(`- executable path is "${execPath}"`)
      this.checkExecPath(execPath, errorCallback)
    }.bind(this))
  }
392470
def get_checks(options):
    """"""
    sys.path.append(proselint_path)
    checks = []
    check_names = [key for (key, val)
                   in list(options["checks"].items()) if val]

    for check_name in check_names:
        module = importlib.import_module("checks." + check_name)
        for d in dir(module):
            if re.match("check", d):
                checks.append(getattr(module, d))

    return checks
633671
def _process_dupe_code_violation(self, lines, current_line, message):
        
        src_paths = []
        message_match = self.dupe_code_violation_regex.match(message)
        if message_match:
            for _ in range(int(message_match.group(1))):
                current_line += 1
                match = self.multi_line_violation_regex.match(
                    lines[current_line]
                )
                src_path, l_number = match.groups()
                src_paths.append(('%s.py' % src_path, l_number))
        return src_paths
1301106
function main(env, print, cb) {
    var dir = env.opts.directory || path.resolve(env.cwd, 'artifacts/jslint'),
        lines = [],
        count = 0,
        total = 0;

    function perOffense(o) {
        var evidence = o.evidence.trim();

        count += 1;
        total += 1;

        lines.push(fmt('  #%d %d,%d: %s', count, o.line, o.col, o.msg));
        if (evidence) {
            lines.push('     ' + evidence);
        }
    }

    /**
     * invoked by lintifier.doneYet()
     * @param {object|string|null} offenses
     * @param {string} msg "Done. no lint found..."
     */
    function reporter(offenses, msg) {
        var files,
            summary,
            writeErr;

        if (('string' === typeof offenses) || offenses instanceof Error) {
            cb(offenses);
            return;
        }

        function perFile(pathname) {
            count = 0;
            lines.push(pathname);
            offenses[pathname].forEach(perOffense);
            lines.push(''); // blank line
        }

        if (offenses) {
            // accumulate report in lines array
            files = Object.keys(offenses);
            files.forEach(perFile);
            summary = getSummary(total, files.length);

            if (env.opts.print) {
                lines.unshift('JSLint Report', '');
                print(lines.join(EOL));

            } else {
                writeErr = writeHtmlFile(dir, getHtml(lines, summary));
            }

            // has errors
            cb(writeErr || summary);

        } else {
            // is lint free
            cb(null, msg);
        }
    }

    return reporter;
}
244863
def check(target, ruleset, ruleset_file, debug, json, stat, skip, tag, verbose,
          checks_paths, target_type, timeout, pull, insecure):
    
    if ruleset and ruleset_file:
        raise click.BadOptionUsage(
            "Options '--ruleset' and '--file-ruleset' cannot be used together.")

    if json and not os.path.isdir(os.path.dirname(os.path.realpath(json.name))):
        raise click.BadOptionUsage(
            "Parent directory for the json output file does not exist.")

    try:
        if not debug:
            logging.basicConfig(stream=six.StringIO())

        log_level = _get_log_level(debug=debug,
                                   verbose=verbose)
        results = run(
            target=target,
            ruleset_name=ruleset,
            ruleset_file=ruleset_file,
            logging_level=log_level,
            tags=tag,
            pull=pull,
            checks_paths=checks_paths,
            target_type=target_type,
            timeout=timeout,
            insecure=insecure,
            skips=skip
        )
        _print_results(results=results, stat=stat, verbose=verbose)

        if json:
            results.save_json_to_file(file=json)

        if not results.ok:
            sys.exit(1)
        elif results.fail:
            sys.exit(3)

    except ColinException as ex:
        logger.error("An error occurred: %r", ex)
        if debug:
            raise
        else:
            raise click.ClickException(str(ex))
    except Exception as ex:
        logger.error("An error occurred: %r", ex)
        if debug:
            raise
        else:
            raise click.ClickException(str(ex))
709333
def qa(ctx):
    ''''''
    header('Performing static analysis')
    info('Python static analysis')
    flake8_results = lrun('flake8 udata --jobs 1', pty=True, warn=True)
    info('JavaScript static analysis')
    eslint_results = lrun('npm -s run lint', pty=True, warn=True)
    if flake8_results.failed or eslint_results.failed:
        exit(flake8_results.return_code or eslint_results.return_code)
    print(green('OK'))
1355508
def _check_command_result(self):
        """"""
        if self.commandResult.startswith('/bin/bash'):
            raise UtilError('%s' % self.commandResult.split(' ', 1)[1])
        if self.commandResult.startswith('/bin/mv'):
            raise UtilError('%s' % self.commandResult.split(' ', 1)[1])
        if self.commandResult.startswith('/bin/ls'):
            raise UtilError('%s' % self.commandResult.split(' ', 1)[1])
        if self.commandResult.startswith('/bin/rm'):
            raise UtilError('%s' % self.commandResult.split(' ', 1)[1])
        if 'invalid option' in self.commandResult:
            raise UtilError('%s' % self.commandResult)
        if 'Invalid option' in self.commandResult:
            raise UtilError('%s' % self.commandResult)
        if 'usage: /usr/bin/get_dossier' in self.commandResult:
            raise UtilError('%s' % self.commandResult)
485215
def _check_std(self, paths, cmd_pieces):
        
        cmd_pieces.extend(paths)
        process = Popen(cmd_pieces, stdout=PIPE, stderr=PIPE)
        out, err = process.communicate()
        lines = out.strip().splitlines() + err.strip().splitlines()
        result = []
        for line in lines:
            match = self.tool_err_re.match(line)
            if not match:
                if self.break_on_tool_re_mismatch:
                    raise ValueError(
                        'Unexpected `%s` output: %r' % (
                            ' '.join(cmd_pieces),
                            paths,
                            line))
                continue
            vals = match.groupdict()

            # All tools should at least give us line numbers, but only
            # some give column numbers.
            vals['lineno'] = int(vals['lineno'])
            vals['colno'] = \
                int(vals['colno']) if vals['colno'] is not None else ''

            result.append(vals)
        return result
684204
def action_verify_checksum(self, ids):
        """"""
        try:
            count = 0
            for file_id in ids:
                f = FileInstance.query.filter_by(
                    id=uuid.UUID(file_id)).one_or_none()
                if f is None:
                    raise ValueError(_("Cannot find file instance."))
                verify_checksum.delay(file_id)
                count += 1
            if count > 0:
                flash(_('Fixity check(s) sent to queue.'), 'success')
        except Exception as exc:
            if not self.handle_view_exception(exc):
                raise
            current_app.logger.exception(str(exc))  # pragma: no cover
            flash(_('Failed to run fixity checks.'),
                  'error')
197192
def main(directories):
    ''''''
    msg = 'Checking module "{}" from directory "{}" for coding errors.'
    api_checker = ApiChecker()
    resource_checker = ResourceChecker()
    errors = []
    modules = []
    for loader, mname, _ in pkgutil.walk_packages(directories):
        sys.path.append(os.path.abspath(loader.path))
        log.info(msg.format(mname, loader.path))
        modules.append(mname)
        import_module(mname)
    for api in Api:
        if api.__module__.split('.')[-1] not in modules:
            continue
        log.debug('Anlysing Api class: {}'.format(api.__name__))
        errors.extend(api_checker(api))
    for res in Resource:
        if res.__module__.split('.')[-1] not in modules:
            continue
        log.debug('Anlysing Resource class: {}'.format(res.__name__))
        errors.extend(resource_checker(res))
    else:
        log.info('All modules tested, no problem detected.')
    return errors
329797
def _run_check_cmd(self, low_data):
        '''
        
        '''
        ret = {'result': False}
        cmd_opts = {}
        if 'shell' in self.opts['grains']:
            cmd_opts['shell'] = self.opts['grains'].get('shell')
        for entry in low_data['check_cmd']:
            cmd = self.functions['cmd.retcode'](
                entry, ignore_retcode=True, python_shell=True, **cmd_opts)
            log.debug('Last command return code: %s', cmd)
            if cmd == 0 and ret['result'] is False:
                ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
            elif cmd != 0:
                ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
                return ret
        return ret
964502
def resolve(checks, lazy, quiet):
    
    root = get_root()
    if 'all' in checks:
        checks = os.listdir(root)

    for check_name in sorted(checks):
        pinned_reqs_file = os.path.join(root, check_name, 'requirements.in')
        resolved_reqs_file = os.path.join(root, check_name, 'requirements.txt')

        if os.path.isfile(pinned_reqs_file):
            if not quiet:
                echo_info('Check `{}`:'.format(check_name))

            if not quiet:
                echo_waiting('    Resolving dependencies...')

            pre_packages = read_packages(resolved_reqs_file)
            result = resolve_requirements(pinned_reqs_file, resolved_reqs_file, lazy=lazy)
            if result.code:
                abort(result.stdout + result.stderr)

            if not quiet:
                post_packages = read_packages(resolved_reqs_file)
                display_package_changes(pre_packages, post_packages, indent='    ')
229421
private State checkA(State state) throws DatatypeException, IOException {
        if (state.context.length() == 0) {
            state = appendToContext(state);
        }
        state.current = state.reader.read();
        state = appendToContext(state);
        state = skipSpaces(state);
        boolean expectNumber = true;

        for (;;) {
            switch (state.current) {
                default:
                    if (expectNumber)
                        reportNonNumber('A', state.current, state.context);
                    return state;

                case '+':
                case '-':
                case '.':
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                    break;
            }

            state = checkArg('A', "rx radius", state);
            state = skipCommaSpaces(state);
            state = checkArg('A', "ry radius", state);
            state = skipCommaSpaces(state);
            state = checkArg('A', "x-axis-rotation", state);
            state = skipCommaSpaces(state);

            switch (state.current) {
                default:
                    reportUnexpected("\u201c0\u201d or \u201c1\u201d for"
                            + " large-arc-flag for \u201cA\u201d" + " command",
                            state.current, state.context);
                    state = skipSubPath(state);
                    return state;
                case '0':
                case '1':
                    break;
            }

            state.current = state.reader.read();
            state = appendToContext(state);
            state = skipCommaSpaces(state);

            switch (state.current) {
                default:
                    reportUnexpected("\u201c0\u201d or \u201c1\u201d for"
                            + " sweep-flag for \u201cA\u201d" + " command",
                            state.current, state.context);
                    state = skipSubPath(state);
                    return state;
                case '0':
                case '1':
                    break;
            }

            state.current = state.reader.read();
            state = appendToContext(state);
            state = skipCommaSpaces(state);

            state = checkArg('A', "x coordinate", state);
            state = skipCommaSpaces(state);
            state = checkArg('A', "y coordinate", state);

            state = skipCommaSpaces2(state);
            expectNumber = state.skipped;
        }
    }
1147404
private static void checkViolations(List<String> givenViolations,
			List<String> expectedValidationViolations) {

		/*
		 * check if number of expected violations matches the given violations
		 */
		Assert.assertEquals(
				String.format(
						"number of expected validation violations (%s) does not match the number of given violations (%s)",
						StringUtils.join(expectedValidationViolations,
								LIST_DELIMITER), StringUtils.join(
								givenViolations, LIST_DELIMITER)),
				expectedValidationViolations.size(), givenViolations.size());

		/*
		 * check if the set of given violations matches the expected violations
		 */
		boolean listsAreCongruent = true;

		List<String> givenButNotExpected = new ArrayList<String>();

		for (String givenViolation : givenViolations) {

			if (!expectedValidationViolations.contains(givenViolation)) {
				listsAreCongruent = false;
				givenButNotExpected.add(givenViolation);
			}
		}

		Assert.assertTrue(
				String.format(
						"the violations (%s) where given but not expected: all given violations (%s), all expected violations (%s)",
						StringUtils.join(givenButNotExpected, LIST_DELIMITER),
						StringUtils.join(givenViolations, LIST_DELIMITER),
						StringUtils.join(expectedValidationViolations,
								LIST_DELIMITER)), listsAreCongruent);
	}
838501
def check_errors(self):
        '''
        
        '''
        errors = ERROR_PATTTERN.findall(self.out)
        # "errors" is a list of tuples
        if errors:
            self.log.error('! Errors occurred:')

            self.log.error('\n'.join(
                [error.replace('\r', '').strip() for error
                 in chain(*errors) if error.strip()]
            ))

            self.log.error('! See "%s.log" for details.' % self.project_name)

            if self.opt.exit_on_error:
                self.log.error('! Exiting...')
                sys.exit(1)