-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinventory_diff.py
More file actions
49 lines (44 loc) · 1.67 KB
/
Copy pathinventory_diff.py
File metadata and controls
49 lines (44 loc) · 1.67 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
from pathlib import Path
import csv
import json
def load_json(path):
try:
x=json.loads(Path(path).read_text(encoding="utf-8") or "[]")
return x if isinstance(x,list) else ([x] if x else [])
except Exception:
return []
def keyed(items, fields):
out={}
for x in items:
if isinstance(x,dict):
out[tuple(str(x.get(f,"")) for f in fields)]=x
return out
def csv_rows(path):
try:
with Path(path).open("r",encoding="utf-8-sig",errors="replace",newline="") as f:
return list(csv.DictReader(f))
except Exception:
return []
def diff(before,after,fields):
b=keyed(before,fields)
a=keyed(after,fields)
return {
"added":[a[k] for k in a.keys()-b.keys()],
"removed":[b[k] for k in b.keys()-a.keys()],
"changed":[{"before":b[k],"after":a[k]} for k in a.keys()&b.keys() if a[k]!=b[k]]
}
def create_diff(session):
s=Path(session)
inv=s/"inventory"
tasks_b=csv_rows(inv/"tasks_before.csv")
tasks_a=csv_rows(inv/"tasks_after.csv")
task_fields=[]
if tasks_b:
keys=list(tasks_b[0].keys())
task_fields=[next((k for k in keys if k.lower() in ("taskname","task name","görev adı")),keys[0])]
result={
"services":diff(load_json(inv/"services_before.json"),load_json(inv/"services_after.json"),["Name"]),
"autoruns":diff(load_json(inv/"autoruns_before.json"),load_json(inv/"autoruns_after.json"),["Key","Name"]),
"scheduled_tasks":diff(tasks_b,tasks_a,task_fields) if task_fields else {"added":[],"removed":[],"changed":[]}
}
(inv/"diff.json").write_text(json.dumps(result,indent=2,ensure_ascii=False),encoding="utf-8")