-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathcontext.py
More file actions
97 lines (75 loc) · 2.32 KB
/
context.py
File metadata and controls
97 lines (75 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# -*- coding: utf-8 -*-
# This file is part of the CloudBlue Connect connect-cli.
# Copyright (c) 2025 CloudBlue. All rights reserved.
import inspect
import json
import sys
class Context(dict):
context_file_name = None
@classmethod
def create_from_file(cls, filename=None):
ctx = cls()
try:
ctx.load(filename)
except FileNotFoundError:
pass
return ctx
@classmethod
def create(cls, args=None, filename=None, **kwargs):
ctx = cls()
try:
ctx.load(filename)
except FileNotFoundError:
pass
if args:
ctx.parse_args(args)
if kwargs:
for k, v in kwargs.items():
if v is not None:
ctx[k] = v
return ctx
def parse_args(self, args):
for k, v in [a.split('=') for a in args]:
self[k] = v
def load(self, filename=None):
if filename is None:
filename = self.__class__.context_file_name
if filename:
with open(filename) as f:
print(f'Loading context from {filename}', file=sys.stderr)
self.clear()
for k, v in json.load(f).items():
self[k] = v
def save(self, filename=None):
if filename is None:
filename = self.__class__.context_file_name
if filename:
with open(filename, 'w') as f:
print(f'Saving context into {filename}', file=sys.stderr)
json.dump(self, f, indent=4)
def __str__(self):
return json.dumps(self, indent=4)
def __getattr__(self, item):
if item in self:
return self[item]
raise KeyError(item)
def __setattr__(self, key, value):
self[key] = value
def __ior__(self, kv):
key, value = kv
if isinstance(value, dict):
if key not in self:
self[key] = {}
self[key].update(value)
else:
if not isinstance(value, list):
value = [value]
if key not in self:
self[key] = []
self[key].extend(value)
return self
def __or__(self, step):
if inspect.isclass(step):
step = step()
step.do(context=self)
return self