Skip to content

Commit

Permalink
Convert over to use attr
Browse files Browse the repository at this point in the history
Make the class a bit easier to use, with built-in generated methods from
attr
  • Loading branch information
garethr committed Oct 28, 2019
1 parent 4b49976 commit dabba5e
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 13 deletions.
2 changes: 1 addition & 1 deletion cli.py
Expand Up @@ -39,7 +39,7 @@ def build(files, lib):

with open(f"{name}.yaml", "w") as template:
click.echo(f'{head} Saving to "{name}.yaml"')
template.write(ct.yaml)
template.write(ct.yaml())


cli.add_command(build)
Expand Down
11 changes: 10 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 21 additions & 9 deletions policytool/models.py
@@ -1,5 +1,6 @@
from typing import List

import attr
import yaml


Expand All @@ -9,15 +10,27 @@ def str_presenter(dumper, data):
return dumper.represent_scalar("tag:yaml.org,2002:str", data)


@attr.s(auto_attribs=True)
class ConstraintTemplate(object):
def __init__(self, kind: str, rego: str, libs: List[str] = []):
self.name = kind.lower()
self.kind = kind
self.list_kind = f"{kind}List"
self.plural = self.name
self.singular = self.name.rstrip("s")
self.rego = rego
self.libs = libs
kind: str
rego: str
libs: List[str] = attr.Factory(list)

@property
def name(self):
return self.kind.lower()

@property
def plural(self):
return self.name

@property
def singular(self):
return self.name.rstrip("s")

@property
def list_kind(self):
return f"{self.kind}List"

@property
def _template(self):
Expand Down Expand Up @@ -45,7 +58,6 @@ def _template(self):
temp["spec"]["targets"][0]["libs"] = self.libs
return temp

@property
def yaml(self):
yaml.add_representer(str, str_presenter)
return yaml.dump(self._template)
2 changes: 1 addition & 1 deletion policytool/test_models.py
Expand Up @@ -44,7 +44,7 @@ def test_default_libs(self, template):

def test_yaml(self, template):
assert (
template.yaml
template.yaml()
== """apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
Expand Down
3 changes: 2 additions & 1 deletion pyproject.toml
Expand Up @@ -5,13 +5,14 @@ license = "Apache-2.0"
description = "A set of utilities and classes for working with Open Policy Agent based tools, including Gatekeeper and Conftest"
authors = ["Gareth Rushgrove <gareth@morethanseven.net>"]
readme = "README.md"
repository = "https://github.com/garethr/policytool
repository = "https://github.com/garethr/policytool"

[tool.poetry.dependencies]
python = "^3.7"
PyYAML = "^5.1"
click = "^7.0"
colorama = "^0.4.1"
attr = "^0.3.1"

[tool.poetry.scripts]
policytool = "cli:cli"
Expand Down

0 comments on commit dabba5e

Please sign in to comment.