Return a data structure of the rules in the conf file

    CLI Example:

    .. code-block:: bash

        salt '*' nftables.get_saved_rules
480448
def get_saved_rules(conf_file=None):
    '''
    

    '''
    if _conf() and not conf_file:
        conf_file = _conf()

    with salt.utils.files.fopen(conf_file) as fp_:
        lines = salt.utils.data.decode(fp_.readlines())
    rules = []
    for line in lines:
        tmpline = line.strip()
        if not tmpline:
            continue
        if tmpline.startswith('#'):
            continue
        rules.append(line)
    return rules
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
260878
def get_rules(family='ipv4'):
    '''
    

    '''
    nft_family = _NFTABLES_FAMILIES[family]
    rules = []
    cmd = '{0} --numeric --numeric --numeric ' \
          'list tables {1}'. format(_nftables_cmd(),
                                    nft_family)
    out = __salt__['cmd.run'](cmd, python_shell=False)
    if not out:
        return rules

    tables = re.split('\n+', out)
    for table in tables:
        table_name = table.split(' ')[1]
        cmd = '{0} --numeric --numeric --numeric ' \
              'list table {1} {2}'.format(_nftables_cmd(),
                                          nft_family, table_name)
        out = __salt__['cmd.run'](cmd, python_shell=False)
        rules.append(out)
    return rules
377521
protected function _rules() {
		$rules = new Rules();

		$files = array(
			$this->config,
			Libraries::get('li3_quality', 'path') . '/config/syntax.json'
		);
		foreach ($files as $file) {
			if (file_exists($file)) {
				$this->out("Loading configuration file `{$file}`...");
				$config = json_decode(file_get_contents($file), true) + array(
					'name' => null,
					'rules' => array(),
					'options' => array()
				);
				break;
			}
		}

		foreach ($config['rules'] as $ruleName) {
			$class = Libraries::locate('rules.syntax', $ruleName);
			$rules->add(new $class());
		}
		if ($config['options']) {
			$rules->options($config['options']);
		}
		return $rules;
	}
994109
def from_raw(self, rule_ids, outputs, raw_rules):
        
        self._rule_pool = [([], [])] + raw_rules
        self._rule_list = []
        for i, idx in enumerate(rule_ids):
            rule = Rule([Clause(f, c) for f, c in zip(*self._rule_pool[idx])], outputs[i])
            self._rule_list.append(rule)
            # self._rule_list.append(rule_str2rule(_rule_name, outputs[i]))
        self._rule_ids = rule_ids
        self._rule_outputs = outputs
1055205
function getRule(commitlintConfig, ruleName) {
	const rule = commitlintConfig.rules[ruleName];

	if (rule) {
		return {
			raw: rule,
			level: rule[0],
			applicable: rule[1],
			value: rule[2],
		};
	}
}
358791
def get_ruleset_dirs():
    

    ruleset_dirs = []

    cwd_rulesets = os.path.join(".", RULESET_DIRECTORY_NAME)
    if os.path.isdir(cwd_rulesets):
        logger.debug("Ruleset directory found in current directory ('{}').".format(cwd_rulesets))
        ruleset_dirs.append(cwd_rulesets)

    if "VIRTUAL_ENV" in os.environ:
        venv_local_share = os.path.join(os.environ["VIRTUAL_ENV"],
                                        RULESET_DIRECTORY)
        if os.path.isdir(venv_local_share):
            logger.debug("Virtual env ruleset directory found ('{}').".format(venv_local_share))
            ruleset_dirs.append(venv_local_share)

    local_share = os.path.join(os.path.expanduser("~"),
                               ".local",
                               RULESET_DIRECTORY)
    if os.path.isdir(local_share):
        logger.debug("Local ruleset directory found ('{}').".format(local_share))
        ruleset_dirs.append(local_share)

    usr_local_share = os.path.join("/usr/local", RULESET_DIRECTORY)
    if os.path.isdir(usr_local_share):
        logger.debug("Global ruleset directory found ('{}').".format(usr_local_share))
        ruleset_dirs.append(usr_local_share)

    if not ruleset_dirs:
        msg = "Ruleset directory cannot be found."
        logger.warning(msg)
        raise ColinRulesetException(msg)

    return ruleset_dirs
94796
def get_rules_table(rules):
    
    table = formatting.Table(['#', 'action', 'protocol', 'src_ip', 'src_mask',
                              'dest', 'dest_mask'])
    table.sortby = '#'
    for rule in rules:
        table.add_row([
            rule['orderValue'],
            rule['action'],
            rule['protocol'],
            rule['sourceIpAddress'],
            utils.lookup(rule, 'sourceIpSubnetMask'),
            '%s:%s-%s' % (rule['destinationIpAddress'],
                          rule['destinationPortRangeStart'],
                          rule['destinationPortRangeEnd']),
            utils.lookup(rule, 'destinationIpSubnetMask')])
    return table
946506
def get_standard_fwl_rules(self, firewall_id):
        

        svc = self.client['Network_Component_Firewall']
        return svc.getRules(id=firewall_id, mask=RULE_MASK)
1198558
def _file_dict(self, fn_):
        '''
        
        '''
        if not os.path.isfile(fn_):
            err = 'The referenced file, {0} is not available.'.format(fn_)
            sys.stderr.write(err + '\n')
            sys.exit(42)
        with salt.utils.files.fopen(fn_, 'r') as fp_:
            data = fp_.read()
        return {fn_: data}
702244
def get_line_pattern_rules(declarations, dirs):
    
    property_map = {'line-pattern-file': 'file', 'line-pattern-width': 'width',
                    'line-pattern-height': 'height', 'line-pattern-type': 'type',
                    'line-pattern-meta-output': 'meta-output', 'line-pattern-meta-writer': 'meta-writer'}

    
    property_names = property_map.keys()
    
    # a place to put rules
    rules = []
    
    for (filter, values) in filtered_property_declarations(declarations, property_names):
    
        line_pattern_file, line_pattern_type, line_pattern_width, line_pattern_height \
            = values.has_key('line-pattern-file') \
            and post_process_symbolizer_image_file(str(values['line-pattern-file'].value), dirs) \
            or (None, None, None, None)
        
        line_pattern_width = values.has_key('line-pattern-width') and values['line-pattern-width'].value or line_pattern_width
        line_pattern_height = values.has_key('line-pattern-height') and values['line-pattern-height'].value or line_pattern_height
        symbolizer = line_pattern_file and output.LinePatternSymbolizer(line_pattern_file, line_pattern_type, line_pattern_width, line_pattern_height)
        
        if symbolizer:
            rules.append(make_rule(filter, symbolizer))
    
    return rules
1235730
def list_rules(self, chainname):
        
        data = self.__run([self.__iptables_save, '-t', self.__name, '-c'])
        return netfilter.parser.parse_rules(data, chainname)
1237853
def conf_files(self):
        
        for attr in dir(self):
            field = getattr(self, attr)
            if isinstance(field, ConfFile):
                yield field
899922
def load_rules(root='fmn.rules'):
    

    module = __import__(root, fromlist=[root.split('.')[0]])

    hinting_helpers = fmn.lib.hinting.__dict__.values()

    rules = {}
    for name in dir(module):
        obj = getattr(module, name)

        # Ignore non-callables.
        if not callable(obj):
            continue

        # Ignore our decorator and its friends
        if obj in hinting_helpers:
            continue

        doc = inspect.getdoc(obj)

        # It's crazy, but inspect (stdlib!) doesn't return unicode objs on py2.
        if doc and hasattr(doc, 'decode'):
            doc = doc.decode('utf-8')

        if doc:
            # If we have a docstring, then mark it up beautifully for display
            # in the web app.
            # FWIW, this should probably be moved into fmn.web since nowhere
            # else are we going to want HTML... we'll still want raw .rst.
            title, doc_as_rst = doc.split('\n', 1)
            doc = docutils.examples.html_parts(doc_as_rst)['body']
            soup = bs4.BeautifulSoup(doc, 'html5lib')
            doc_no_links = ''.join(map(six.text_type, strip_anchor_tags(soup)))
            doc = markupsafe.Markup(doc)
            doc_no_links = markupsafe.Markup(doc_no_links)
        else:
            title = "UNDOCUMENTED"
            doc = "No docs for %s:%s %r" % (root, name, obj)
            doc_no_links = doc

        rules[name] = {
            'func': obj,
            'submodule': obj.__module__.split('.')[-1],
            'title': title.strip(),
            'doc': doc.strip(),
            'doc-no-links': doc_no_links.strip(),
            'args': inspect.getargspec(obj)[0],
            'datanommer-hints': getattr(obj, 'hints', {}),
            'hints-invertible': getattr(obj, 'hinting_invertible', True),
            'hints-callable': getattr(obj, 'hinting_callable', None),
        }

    rules = OrderedDict(
        sorted(rules.items(), key=lambda x: x[1]['title'])
    )

    return {root: rules}
460878
private List<RuleSource> readRulesDirectory(File rulesDirectory) throws MojoExecutionException {
        if (rulesDirectory.exists() && !rulesDirectory.isDirectory()) {
            throw new MojoExecutionException(rulesDirectory.getAbsolutePath() + " does not exist or is not a directory.");
        }
        getLog().info("Reading rules from directory " + rulesDirectory.getAbsolutePath());
        try {
            return FileRuleSource.getRuleSources(rulesDirectory);
        } catch (IOException e) {
            throw new MojoExecutionException("Cannot read rulesDirectory: " + rulesDirectory.getAbsolutePath(), e);
        }
    }
1213487
def config():
    '''
    
    '''
    if 'conf_file' not in __opts__:
        return {}
    if os.path.isdir(__opts__['conf_file']):
        if salt.utils.platform.is_proxy():
            gfn = os.path.join(
                    __opts__['conf_file'],
                    'proxy.d',
                    __opts__['id'],
                    'grains'
                    )
        else:
            gfn = os.path.join(
                    __opts__['conf_file'],
                    'grains'
                    )
    else:
        if salt.utils.platform.is_proxy():
            gfn = os.path.join(
                    os.path.dirname(__opts__['conf_file']),
                    'proxy.d',
                    __opts__['id'],
                    'grains'
                    )
        else:
            gfn = os.path.join(
                    os.path.dirname(__opts__['conf_file']),
                    'grains'
                    )
    if os.path.isfile(gfn):
        log.debug('Loading static grains from %s', gfn)
        with salt.utils.files.fopen(gfn, 'rb') as fp_:
            try:
                return salt.utils.data.decode(salt.utils.yaml.safe_load(fp_))
            except Exception:
                log.warning("Bad syntax in grains file! Skipping.")
                return {}
    return {}
846565
def get_conf_update(self):
        
        dyn_conf = self.get_collection_rules()

        if not dyn_conf:
            return self.get_conf_file()

        version = dyn_conf.get('version', None)
        if version is None:
            raise ValueError("ERROR: Could not find version in json")

        dyn_conf['file'] = self.collection_rules_file
        logger.debug("Success reading config")
        config_hash = hashlib.sha1(json.dumps(dyn_conf).encode('utf-8')).hexdigest()
        logger.debug('sha1 of config: %s', config_hash)
        return dyn_conf