Execute the checks: rules for a given build.yml file.
481908
def check(path=None, env='default'):
    
    # TODO: add files=<list of files> to check only a subset...
    # also useful for 'quilt build' to exclude certain files?
    # (if not, then require dry_run=True if files!=None/all)
    build("dry_run/dry_run", path=path, dry_run=True, env=env)
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))
284216
def check(self, _):
        """"""

        try:
            import yaml
        except:
            return True
        try:
            yaml.safe_load(self.recipes)
        except Exception as e:
            raise RADLParseException("Invalid YAML code: %s." % e, line=self.line)
        return True
30352
def build(check, sdist):
    """"""
    if check in get_valid_checks():
        check_dir = os.path.join(get_root(), check)
    else:
        check_dir = resolve_path(check)
        if not dir_exists(check_dir):
            abort('`{}` is not an Agent-based Integration or Python package'.format(check))

        check = basepath(check_dir)

    echo_waiting('Building `{}`...'.format(check))

    dist_dir = os.path.join(check_dir, 'dist')
    remove_path(dist_dir)

    result = build_package(check_dir, sdist)
    if result.code != 0:
        abort(result.stdout, result.code)

    echo_info('Build done, artifact(s) in: {}'.format(dist_dir))
    echo_success('Success!')
287334
def run(self, files, working_area):
        

        # Ensure that dictionary is ordered by check declaration order (via self.check_names)
        # NOTE: Requires CPython 3.6. If we need to support older versions of Python, replace with OrderedDict.
        results = {name: None for name in self.check_names}
        checks_root = working_area.parent
        with futures.ProcessPoolExecutor() as executor:

            # Start all checks that have no dependencies
            not_done = set(executor.submit(run_check(name, self.checks_spec, checks_root))
                           for name, _ in self.child_map[None])
            not_passed = []

            while not_done:
                done, not_done = futures.wait(not_done, return_when=futures.FIRST_COMPLETED)
                for future in done:
                    # Get result from completed check
                    result, state = future.result()
                    results[result.name] = result
                    if result.passed:
                        # Dispatch dependent checks
                        for child_name, _ in self.child_map[result.name]:
                            not_done.add(executor.submit(
                                run_check(child_name, self.checks_spec, checks_root, state)))
                    else:
                        not_passed.append(result.name)

        for name in not_passed:
            self._skip_children(name, results)

        return results.values()
766311
def run(config, path=None, stop_on_error=True, just_tests=False):
    """"""
    if path is None:
        path = os.getcwd()
    prep(config, path=path)

    models = __import__('models')
    tests = __import__('tests')
    suites = __import__('suites')

    print('\n')
    for x in ['models', 'tests', 'suites']:
        module = __import__(x)
        assert hasattr(module, x), "'%s' module requires attribute '%s'" %\
                                   (x, x)

    if just_tests:
        for test in tests.tests:
            _run(test, models, stop_on_error)

    else:
        for suite in suites.suites:
            _run(suite, models, stop_on_error)
1226624
def execute(self):  # pylint: disable=no-self-use
        """"""
        if os.path.isfile('runway.yml'):
            print('Runway config already present')
            sys.exit(1)
        with open('runway.yml', 'w') as stream:
            stream.write("""---
deployments:
  - modules:
      - nameofmyfirstmodulefolder
      - nameofmysecondmodulefolder
      # - etc...
    regions:
      - us-east-1
""")
        print('runway.yml generated')
        print('See additional getting started information at '
              'https://docs.onica.com/projects/runway/en/latest/how_to_use.html')
208242
def run(path, code=None, params=None, **meta):
        
        import _ast

        builtins = params.get("builtins", "")

        if builtins:
            builtins = builtins.split(",")

        tree = compile(code, path, "exec", _ast.PyCF_ONLY_AST)
        w = checker.Checker(tree, path, builtins=builtins)
        w.messages = sorted(w.messages, key=lambda m: m.lineno)
        return [{
            'lnum': m.lineno,
            'text': m.message % m.message_args,
            'type': m.message[0]
        } for m in w.messages]
546180
def process_rules(self, path: Path, system: System):
        """"""
        self.context.update({
            'system': system,
        })
        document = FileSystem.load_yaml(path, required=True)
        for module, rules in document.items():
            click.secho('process: {0}'.format(module), fg='green')
            self._process_rules(rules, system)
36209
def execute_rule(rule, matches, context):
    
    if rule.enabled(context):
        log(rule.log_level, "Checking rule condition: %s", rule)
        when_response = rule.when(matches, context)
        if when_response:
            log(rule.log_level, "Rule was triggered: %s", when_response)
            log(rule.log_level, "Running rule consequence: %s %s", rule, when_response)
            rule.then(matches, when_response, context)
            return when_response
    else:
        log(rule.log_level, "Rule is disabled: %s", rule)
1323611
def validate_yaml(yaml_in, yaml_fn):
    """"""
    try:
        import yamllint.linter as linter
        from yamllint.config import YamlLintConfig
    except ImportError:
        return
    conf = """{"extends": "relaxed",
               "rules": {"trailing-spaces": {"level": "warning"},
                         "new-lines": {"level": "warning"},
                         "new-line-at-end-of-file": {"level": "warning"}}}"""
    if utils.file_exists(yaml_in):
        with open(yaml_in) as in_handle:
            yaml_in = in_handle.read()
    out = linter.run(yaml_in, YamlLintConfig(conf))

    for problem in out:
        msg = '%(fn)s:%(line)s:%(col)s: [%(level)s] %(msg)s' % {'fn': yaml_fn,
                                                                'line': problem.line,
                                                                'col': problem.column,
                                                                'level': problem.level,
                                                                'msg': problem.message}
        if problem.level == "error":
            raise ValueError(msg)
631463
public void execute() throws BuildException {
    log.debug("projectname=" + getProjectName());
    log.debug("src/srcdir=" + getSrcdir());
    log.debug("destdir=" + getDestdir());
    log.debug("failOnError=" + getFailOnError());
    log.debug("checkedArithmetic=" + isCheckedArithmetic());
    log.debug("scriptExtensions=" + getScriptExtensions());
    log.debug("_compileClasspath=" + _compileClasspath);

    if(isCheckedArithmetic()) {
      System.setProperty("checkedArithmetic", "true");
    }
    
    ICompilerDriver driver = new SoutCompilerDriver();
    IGosuCompiler gosuc = new gw.lang.gosuc.simple.GosuCompiler();

    List<String> classpath = new ArrayList<>();
    classpath.addAll(Arrays.asList(_compileClasspath.list()));
    classpath.addAll( GosucUtil.getJreJars());

    String startupMsg = "Initializing Gosu compiler";
    if(!getProjectName().isEmpty()) {
      startupMsg += " for " + getProjectName();
    }
    log.info(startupMsg);
    log.debug("\tsourceFolders:" + Arrays.asList(getSrcdir().list()));
    log.debug("\tclasspath:" + classpath);
    log.debug("\toutputPath:" + getDestdir().getAbsolutePath());

    List<String> sourceRoots = Arrays.asList(getSrcdir().list());
    for (String sourceRootName : sourceRoots) {
      File sourceRoot = getProject().resolveFile(sourceRootName);
      if (!sourceRoot.exists()) {
        throw new BuildException("srcdir \"" + sourceRoot.getPath() + "\" does not exist!", getLocation());
      }
      DirectoryScanner ds = this.getDirectoryScanner(sourceRoot);
      String[] files = ds.getIncludedFiles();
      if( hasSelectors() ) { 
        // we have explicit includes/excludes criteria nested in a <src> element; no need to call scanDir
        // this is the typical use case when ant is invoked dynamically by gradle
        for( String relativeFilename : files ) {
          compileList.add( new File( sourceRoot, relativeFilename ) );
        }
      } else {
        // <src> element was not used - instead we have an explicit list of srcDir elements 
        // and optionally additionalscriptextensions specified in addition to the defaults
        scanDir(sourceRoot, _destDir != null ? _destDir : sourceRoot, files);
      }
    }
    
    gosuc.initializeGosu( sourceRoots, classpath, getDestdir().getAbsolutePath() );

    log.debug("About to compile these files:");
    for(File file : compileList) {
      log.debug("\t" + file.getAbsolutePath());
    }
    
    for(File file : compileList) {
      try {
        gosuc.compile(file, driver);
      } catch (Exception e) {
        log.error(e.getMessage());
        throw new BuildException(e);
      }
    }

    gosuc.uninitializeGosu();

    List<String> warnings = ((SoutCompilerDriver) driver).getWarnings();
    boolean errorsInCompilation = ((SoutCompilerDriver) driver).hasErrors();
    List<String> errors = ((SoutCompilerDriver) driver).getErrors();
    
    List<String> warningMessages = new ArrayList<>();
    List<String> errorMessages = new ArrayList<>();
   
    warnings.forEach(warning -> warningMessages.add("[WARNING] " + warning));
    int numWarnings = warningMessages.size();

    int numErrors = 0;
    if(errorsInCompilation) {
      errors.forEach(error -> errorMessages.add("[ERROR] " + error));
      numErrors = errorMessages.size();
    }

    boolean hasWarningsOrErrors = numWarnings > 0 || errorsInCompilation;
    StringBuilder sb;
    sb = new StringBuilder();
    sb.append(getProjectName().isEmpty() ? "Gosu compilation" : getProjectName());
    sb.append(" completed");
    if(hasWarningsOrErrors) {
      sb.append(" with ");
      if(numWarnings > 0) {
        sb.append(numWarnings).append(" warning").append(numWarnings == 1 ? "" : 's');
      }
      if(errorsInCompilation) {
        sb.append(numWarnings > 0 ? " and " : "");
        sb.append(numErrors).append(" error").append(numErrors == 1 ? "" : 's');
      }
    } else {
      sb.append(" successfully.");
    }

    if(hasWarningsOrErrors) {
      log.warn(sb.toString());
    } else {
      log.info(sb.toString());
    }

    //log at most 100 warnings or errors
    warningMessages.subList(0, Math.min(warningMessages.size(), 100)).forEach(log::info);
    errorMessages.subList(0, Math.min(errorMessages.size(), 100)).forEach(log::error);

    if(errorsInCompilation) {
      if(getFailOnError()) {
        buildError("Gosu compilation failed with errors; see compiler output for details.");
      } else {
        log.warn("Gosu Compiler: Ignoring compilation failure(s) as 'failOnError' was set to false");
      }
    }
    
  }
1019351
def validate(config):
    """"""
    with open(config) as fh:
        content = fh.read()

    try:
        data = yaml.safe_load(content)
    except Exception:
        log.error("config file: %s is not valid yaml", config)
        raise

    try:
        jsonschema.validate(data, CONFIG_SCHEMA)
    except Exception:
        log.error("config file: %s is not valid", config)
        raise

    log.info("config file valid, accounts:%d", len(data['accounts']))
    return data
436759
def validate_yaml_file(schema: dict, yaml_file: Path):
    

    with yaml_file.open() as f:
        data = yaml.load(f)

    jsonschema.validate(data, schema)
1015201
private function checkFile()
    {
        // check File
        if ($this->file === null
            || strlen($this->file) == 0
        ) {
            throw new BuildException('[FileSize] You must specify an input file.', $this->file);
        }

        if (!is_readable($this->file)) {
            throw new BuildException(
                sprintf(
                    '[FileSize] Input file does not exist or is not readable: %s',
                    $this->file
                )
            );
        }
    }
790735
def run(self):
        

        if len(self.filename_checks) == 0:
            message = "N401 no configuration found for {}, " \
                      "please provide filename configuration in a flake8 config".format(self.name)
            yield (0, 0, message, type(self))

        rule_funcs = [rules.rule_n5xx]

        for rule_func in rule_funcs:
            for rule_name, configured_rule in self.filename_checks.items():
                for err in rule_func(self.filename, rule_name, configured_rule, type(self)):
                    yield err
402580
private static function load_yml( $yml_file ) {
		if ( ! $yml_file ) {
			return array();
		}

		$config = Spyc::YAMLLoad( $yml_file );

		// Make sure config-file-relative paths are made absolute.
		$yml_file_dir = dirname( $yml_file );

		if ( isset( $config['path'] ) ) {
			self::absolutize( $config['path'], $yml_file_dir );
		}

		if ( isset( $config['require'] ) ) {
			self::arrayify( $config['require'] );
			$config['require'] = \WP_CLI\Utils\expand_globs( $config['require'] );
			foreach ( $config['require'] as &$path ) {
				self::absolutize( $path, $yml_file_dir );
			}
		}

		// Backwards compat
		// Command 'core config' was moved to 'config create'.
		if ( isset( $config['core config'] ) ) {
			$config['config create'] = $config['core config'];
			unset( $config['core config'] );
		}
		// Command 'checksum core' was moved to 'core verify-checksums'.
		if ( isset( $config['checksum core'] ) ) {
			$config['core verify-checksums'] = $config['checksum core'];
			unset( $config['checksum core'] );
		}
		// Command 'checksum plugin' was moved to 'plugin verify-checksums'.
		if ( isset( $config['checksum plugin'] ) ) {
			$config['plugin verify-checksums'] = $config['checksum plugin'];
			unset( $config['checksum plugin'] );
		}

		return $config;
	}