rule: fmt: support pulling meta from the rule instance

This commit is contained in:
William Ballenthin
2020-06-21 16:57:58 -06:00
parent 23037ad763
commit 07daf3d46b
2 changed files with 29 additions and 1 deletions

View File

@@ -533,11 +533,18 @@ class Rule(object):
# - ordering the meta elements
# - indenting the nested items with two spaces
#
# updates to the rule will be synced for meta fields,
# but not for rule logic.
# programmatic generation of rules is not yet supported.
definition = yaml.load(self.definition)
# definition retains a reference to `meta`,
# so we're updating that in place.
meta = definition["rule"]["meta"]
definition["rule"]["meta"] = self.meta
meta = self.meta
meta["name"] = self.name
meta["scope"] = self.scope
def move_to_end(m, k):
# ruamel.yaml uses an ordereddict-like structure to track maps (CommentedMap).

View File

@@ -70,3 +70,24 @@ def test_rule_reformat_order():
- number: 2''')
assert capa.rules.Rule.from_yaml(rule).to_yaml() == EXPECTED
def test_rule_reformat_meta_update():
rule = textwrap.dedent('''\
rule:
meta:
author: user@domain.com
examples:
- foo1234
- bar5678
scope: function
name: AAAA
features:
- and:
- number: 1
- number: 2''')
rule = capa.rules.Rule.from_yaml(rule)
rule.name = "test rule"
assert rule.to_yaml() == EXPECTED