1
|
|
|
import logging |
2
|
|
|
from pathlib import Path |
3
|
|
|
|
4
|
|
|
import yorm |
5
|
|
|
from yorm.types import String, List, AttributeDictionary |
6
|
|
|
import delegator |
7
|
|
|
|
8
|
|
|
|
9
|
|
|
log = logging.getLogger(__name__) |
10
|
|
|
|
11
|
|
|
|
12
|
|
|
class Variable: |
13
|
|
|
|
14
|
|
|
def __init__(self, name, value): |
15
|
|
|
assert name |
16
|
|
|
self.name = name |
17
|
|
|
self.value = value |
18
|
|
|
|
19
|
|
|
def __repr__(self): |
20
|
|
|
return f"<variable: {self}>" |
21
|
|
|
|
22
|
|
|
def __str__(self): |
23
|
|
|
return f"{self.name}={self.value}" |
24
|
|
|
|
25
|
|
|
@classmethod |
26
|
|
|
def from_env(cls, line): |
27
|
|
|
line = line.strip() |
28
|
|
|
if not line: |
29
|
|
|
log.debug("Skipped blank line") |
30
|
|
|
return None |
31
|
|
|
|
32
|
|
|
if '=' not in line: |
33
|
|
|
log.info("Skipped line without '=': %r", line) |
34
|
|
|
return None |
35
|
|
|
|
36
|
|
|
name, value = line.split('=', 1) |
37
|
|
|
variable = cls(name, value) |
38
|
|
|
log.info("Loaded variable: %s", variable) |
39
|
|
|
|
40
|
|
|
return variable |
41
|
|
|
|
42
|
|
|
|
43
|
|
|
@yorm.attr(name=String) |
44
|
|
|
@yorm.attr(command=String) |
45
|
|
|
class Environment(AttributeDictionary): |
46
|
|
|
|
47
|
|
|
def __init__(self, name, command="env"): |
48
|
|
|
super().__init__() |
49
|
|
|
self.name = name |
50
|
|
|
self.command = command |
51
|
|
|
self.variables = [] |
52
|
|
|
|
53
|
|
|
def __str__(self): |
54
|
|
|
return self.name |
55
|
|
|
|
56
|
|
|
def fetch(self): |
57
|
|
|
self.variables = [] |
58
|
|
|
result = delegator.run(self.command) |
59
|
|
|
for line in result.out.splitlines(): |
60
|
|
|
variable = Variable.from_env(line) |
61
|
|
|
if variable: |
62
|
|
|
self.variables.append(variable) |
63
|
|
|
|
64
|
|
|
|
65
|
|
|
@yorm.attr(files=List.of_type(String)) |
66
|
|
|
@yorm.attr(environments=List.of_type(Environment)) |
67
|
|
|
@yorm.sync("{self.root}/{self.filename}", auto_create=False, auto_save=False) |
68
|
|
|
class Config(yorm.ModelMixin): |
69
|
|
|
|
70
|
|
|
def __init__(self, filename="env-diff.yml", root=None): |
71
|
|
|
self.root = root or Path.cwd() |
72
|
|
|
self.filename = filename |
73
|
|
|
self.files = [] |
74
|
|
|
self.environments = [] |
75
|
|
|
|
76
|
|
|
def __str__(self): |
77
|
|
|
return str(self.path) |
78
|
|
|
|
79
|
|
|
@property |
80
|
|
|
def path(self): |
81
|
|
|
return Path(self.root, self.filename) |
82
|
|
|
|