plcdiff 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- plcdiff/__init__.py +21 -0
- plcdiff/__main__.py +3 -0
- plcdiff/_xml.py +41 -0
- plcdiff/cli.py +158 -0
- plcdiff/diff.py +172 -0
- plcdiff/gitutil.py +130 -0
- plcdiff/l5x.py +286 -0
- plcdiff/loader.py +43 -0
- plcdiff/model.py +64 -0
- plcdiff/plcopen.py +291 -0
- plcdiff/py.typed +0 -0
- plcdiff/render.py +36 -0
- plcdiff/report.py +128 -0
- plcdiff-0.1.0.dist-info/METADATA +180 -0
- plcdiff-0.1.0.dist-info/RECORD +18 -0
- plcdiff-0.1.0.dist-info/WHEEL +4 -0
- plcdiff-0.1.0.dist-info/entry_points.txt +2 -0
- plcdiff-0.1.0.dist-info/licenses/LICENSE +21 -0
plcdiff/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Readable diffs for PLC program exports (Rockwell L5X, PLCopen XML)."""
|
|
2
|
+
|
|
3
|
+
from plcdiff.diff import Change, diff_documents
|
|
4
|
+
from plcdiff.loader import UnsupportedFormat, load, loads
|
|
5
|
+
from plcdiff.model import Block, Document, Entry
|
|
6
|
+
from plcdiff.render import render
|
|
7
|
+
|
|
8
|
+
__version__ = "0.1.0"
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"Block",
|
|
12
|
+
"Change",
|
|
13
|
+
"Document",
|
|
14
|
+
"Entry",
|
|
15
|
+
"UnsupportedFormat",
|
|
16
|
+
"__version__",
|
|
17
|
+
"diff_documents",
|
|
18
|
+
"load",
|
|
19
|
+
"loads",
|
|
20
|
+
"render",
|
|
21
|
+
]
|
plcdiff/__main__.py
ADDED
plcdiff/_xml.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Small ElementTree helpers shared by the format parsers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import xml.etree.ElementTree as ET
|
|
6
|
+
from collections.abc import Iterator
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def local(tag: str) -> str:
|
|
10
|
+
"""Strip an ``{namespace}`` prefix from an element tag."""
|
|
11
|
+
return tag.rsplit("}", 1)[-1]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def children(el: ET.Element | None, name: str) -> Iterator[ET.Element]:
|
|
15
|
+
if el is None:
|
|
16
|
+
return
|
|
17
|
+
for child in el:
|
|
18
|
+
if local(child.tag) == name:
|
|
19
|
+
yield child
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def child(el: ET.Element | None, *names: str) -> ET.Element | None:
|
|
23
|
+
"""Follow a path of child names, ignoring namespaces."""
|
|
24
|
+
cur = el
|
|
25
|
+
for name in names:
|
|
26
|
+
if cur is None:
|
|
27
|
+
return None
|
|
28
|
+
cur = next(children(cur, name), None)
|
|
29
|
+
return cur
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def text(el: ET.Element | None) -> str:
|
|
33
|
+
"""All text inside an element, with surrounding whitespace removed."""
|
|
34
|
+
if el is None:
|
|
35
|
+
return ""
|
|
36
|
+
return "".join(el.itertext()).strip()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def oneline(value: str) -> str:
|
|
40
|
+
"""Collapse whitespace so free text fits on one diff line."""
|
|
41
|
+
return " ".join(value.split())
|
plcdiff/cli.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Command line interface: ``plcdiff textconv|diff|git|install``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
from collections.abc import Sequence
|
|
9
|
+
|
|
10
|
+
from plcdiff import __version__
|
|
11
|
+
from plcdiff.diff import BlockDiff, diff_documents
|
|
12
|
+
from plcdiff.gitutil import DEFAULT_PATTERNS, GitError, changed_files, install
|
|
13
|
+
from plcdiff.loader import UnsupportedFormat, load, loads
|
|
14
|
+
from plcdiff.render import render
|
|
15
|
+
from plcdiff.report import json_report, markdown_report, text_report
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _use_color(choice: str) -> bool:
|
|
19
|
+
if choice == "always":
|
|
20
|
+
return True
|
|
21
|
+
if choice == "never" or os.environ.get("NO_COLOR"):
|
|
22
|
+
return False
|
|
23
|
+
return sys.stdout.isatty()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _report(fmt: str, diffs: list[BlockDiff], old: str, new: str, color: bool) -> str:
|
|
27
|
+
if fmt == "markdown":
|
|
28
|
+
return markdown_report(diffs, old, new)
|
|
29
|
+
if fmt == "json":
|
|
30
|
+
return json_report(diffs, old, new)
|
|
31
|
+
return text_report(diffs, old, new, color=color)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def cmd_textconv(args: argparse.Namespace) -> int:
|
|
35
|
+
data = open(args.file, "rb").read() # noqa: SIM115
|
|
36
|
+
try:
|
|
37
|
+
doc = loads(data, name=args.file, include_values=not args.no_values)
|
|
38
|
+
except UnsupportedFormat:
|
|
39
|
+
# Never break `git diff`: hand unknown files through untouched.
|
|
40
|
+
sys.stdout.buffer.write(data)
|
|
41
|
+
return 0
|
|
42
|
+
sys.stdout.write(render(doc))
|
|
43
|
+
return 0
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def cmd_diff(args: argparse.Namespace) -> int:
|
|
47
|
+
try:
|
|
48
|
+
old = load(args.old, include_values=not args.no_values)
|
|
49
|
+
new = load(args.new, include_values=not args.no_values)
|
|
50
|
+
except (UnsupportedFormat, OSError) as exc:
|
|
51
|
+
print(f"plcdiff: {exc}", file=sys.stderr)
|
|
52
|
+
return 2
|
|
53
|
+
diffs = diff_documents(old, new)
|
|
54
|
+
sys.stdout.write(_report(args.format, diffs, args.old, args.new, _use_color(args.color)))
|
|
55
|
+
return 1 if (args.exit_code and diffs) else 0
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def cmd_git(args: argparse.Namespace) -> int:
|
|
59
|
+
try:
|
|
60
|
+
files = changed_files(args.range, args.paths or None)
|
|
61
|
+
except GitError as exc:
|
|
62
|
+
print(f"plcdiff: {exc}", file=sys.stderr)
|
|
63
|
+
return 2
|
|
64
|
+
color = _use_color(args.color)
|
|
65
|
+
any_change = False
|
|
66
|
+
parts: list[str] = []
|
|
67
|
+
for f in files:
|
|
68
|
+
try:
|
|
69
|
+
old = loads(f.old, f.old_path, include_values=not args.no_values)
|
|
70
|
+
new = loads(f.new, f.path, include_values=not args.no_values)
|
|
71
|
+
except UnsupportedFormat:
|
|
72
|
+
continue # an .xml file that is not a PLC export
|
|
73
|
+
diffs = diff_documents(old, new)
|
|
74
|
+
if not diffs:
|
|
75
|
+
continue
|
|
76
|
+
any_change = True
|
|
77
|
+
label_old = f"a/{f.old_path}"
|
|
78
|
+
label_new = f"b/{f.path}"
|
|
79
|
+
parts.append(_report(args.format, diffs, label_old, label_new, color))
|
|
80
|
+
if not parts:
|
|
81
|
+
parts.append(
|
|
82
|
+
"### plcdiff\n\nNo PLC program changes.\n"
|
|
83
|
+
if args.format == "markdown"
|
|
84
|
+
else ("[]\n" if args.format == "json" else "No PLC program changes.\n")
|
|
85
|
+
)
|
|
86
|
+
if args.format == "json" and len(parts) > 1:
|
|
87
|
+
sys.stdout.write("[\n" + ",\n".join(p.strip() for p in parts) + "\n]\n")
|
|
88
|
+
else:
|
|
89
|
+
sys.stdout.write("\n".join(parts))
|
|
90
|
+
return 1 if (args.exit_code and any_change) else 0
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def cmd_install(args: argparse.Namespace) -> int:
|
|
94
|
+
try:
|
|
95
|
+
for line in install(global_=args.global_, patterns=tuple(args.pattern or DEFAULT_PATTERNS)):
|
|
96
|
+
print(line)
|
|
97
|
+
except GitError as exc:
|
|
98
|
+
print(f"plcdiff: {exc}", file=sys.stderr)
|
|
99
|
+
return 2
|
|
100
|
+
print("Done. `git diff` and `git log -p` now show PLC exports rung by rung.")
|
|
101
|
+
return 0
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
105
|
+
p = argparse.ArgumentParser(
|
|
106
|
+
prog="plcdiff",
|
|
107
|
+
description="Readable diffs for PLC program exports (Rockwell L5X, PLCopen XML).",
|
|
108
|
+
)
|
|
109
|
+
p.add_argument("--version", action="version", version=f"plcdiff {__version__}")
|
|
110
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
111
|
+
|
|
112
|
+
def common(sp: argparse.ArgumentParser, formats: bool = True) -> None:
|
|
113
|
+
sp.add_argument(
|
|
114
|
+
"--no-values", action="store_true", help="ignore tag values (only declarations)"
|
|
115
|
+
)
|
|
116
|
+
if formats:
|
|
117
|
+
sp.add_argument("-f", "--format", choices=["text", "markdown", "json"], default="text")
|
|
118
|
+
sp.add_argument("--color", choices=["auto", "always", "never"], default="auto")
|
|
119
|
+
sp.add_argument(
|
|
120
|
+
"--exit-code", action="store_true", help="exit 1 when there are changes"
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
sp = sub.add_parser("textconv", help="print a diff-friendly text view (git textconv)")
|
|
124
|
+
sp.add_argument("file")
|
|
125
|
+
common(sp, formats=False)
|
|
126
|
+
sp.set_defaults(func=cmd_textconv)
|
|
127
|
+
|
|
128
|
+
sp = sub.add_parser("diff", help="semantic diff of two export files")
|
|
129
|
+
sp.add_argument("old")
|
|
130
|
+
sp.add_argument("new")
|
|
131
|
+
common(sp)
|
|
132
|
+
sp.set_defaults(func=cmd_diff)
|
|
133
|
+
|
|
134
|
+
sp = sub.add_parser("git", help="semantic diff of PLC files changed in a git range")
|
|
135
|
+
sp.add_argument("range", nargs="?", help="A..B, A (vs. working tree) or empty (HEAD)")
|
|
136
|
+
sp.add_argument("paths", nargs="*", help="limit to these paths")
|
|
137
|
+
common(sp)
|
|
138
|
+
sp.set_defaults(func=cmd_git)
|
|
139
|
+
|
|
140
|
+
sp = sub.add_parser("install", help="register plcdiff as a git diff driver")
|
|
141
|
+
sp.add_argument("--global", dest="global_", action="store_true", help="for all repos")
|
|
142
|
+
sp.add_argument(
|
|
143
|
+
"--pattern",
|
|
144
|
+
action="append",
|
|
145
|
+
help="file pattern to map (repeatable, default *.L5X *.l5x); e.g. 'plc/*.xml'",
|
|
146
|
+
)
|
|
147
|
+
sp.set_defaults(func=cmd_install)
|
|
148
|
+
return p
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
152
|
+
args = build_parser().parse_args(argv)
|
|
153
|
+
code: int = args.func(args)
|
|
154
|
+
return code
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
if __name__ == "__main__": # pragma: no cover
|
|
158
|
+
raise SystemExit(main())
|
plcdiff/diff.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""Semantic comparison of two :class:`~plcdiff.model.Document` objects."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import difflib
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Literal
|
|
9
|
+
|
|
10
|
+
from plcdiff.model import Block, Document, Entry
|
|
11
|
+
from plcdiff.render import ordered
|
|
12
|
+
|
|
13
|
+
Op = Literal["added", "removed", "changed"]
|
|
14
|
+
|
|
15
|
+
# One ladder instruction with (possibly nested) operands, or a branch marker.
|
|
16
|
+
_INSTRUCTION = re.compile(r"[A-Za-z_][\w.:]*\((?:[^()]|\([^()]*\))*\)|[\[\],]")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class Change:
|
|
21
|
+
"""One added, removed or changed tag / rung / line."""
|
|
22
|
+
|
|
23
|
+
op: Op
|
|
24
|
+
unit: str
|
|
25
|
+
old: Entry | None = None
|
|
26
|
+
new: Entry | None = None
|
|
27
|
+
old_index: int | None = None
|
|
28
|
+
new_index: int | None = None
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def name(self) -> str:
|
|
32
|
+
entry = self.new or self.old
|
|
33
|
+
if entry is not None and entry.key is not None:
|
|
34
|
+
return f"{self.unit} {entry.key}" if entry.key else "Description"
|
|
35
|
+
base = 0 if self.unit == "Rung" else 1
|
|
36
|
+
if self.new_index is not None and self.old_index is not None:
|
|
37
|
+
if self.old_index != self.new_index:
|
|
38
|
+
return f"{self.unit} {self.new_index + base} (was {self.old_index + base})"
|
|
39
|
+
return f"{self.unit} {self.new_index + base}"
|
|
40
|
+
index = self.new_index if self.new_index is not None else self.old_index
|
|
41
|
+
return f"{self.unit} {(index or 0) + base}"
|
|
42
|
+
|
|
43
|
+
def instruction_delta(self) -> tuple[list[str], list[str]]:
|
|
44
|
+
"""For changed rungs: instructions that were added and removed."""
|
|
45
|
+
if self.unit != "Rung" or self.old is None or self.new is None:
|
|
46
|
+
return [], []
|
|
47
|
+
a = [t for t in _INSTRUCTION.findall(self.old.text) if t not in "[],"]
|
|
48
|
+
b = [t for t in _INSTRUCTION.findall(self.new.text) if t not in "[],"]
|
|
49
|
+
added: list[str] = []
|
|
50
|
+
removed: list[str] = []
|
|
51
|
+
sm = difflib.SequenceMatcher(a=a, b=b, autojunk=False)
|
|
52
|
+
for tag, i1, i2, j1, j2 in sm.get_opcodes():
|
|
53
|
+
if tag in ("replace", "delete"):
|
|
54
|
+
removed += a[i1:i2]
|
|
55
|
+
if tag in ("replace", "insert"):
|
|
56
|
+
added += b[j1:j2]
|
|
57
|
+
return added, removed
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class BlockDiff:
|
|
62
|
+
title: str
|
|
63
|
+
status: Literal["added", "removed", "changed"]
|
|
64
|
+
changes: list[Change] = field(default_factory=list)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _keyed(old: Block | None, new: Block | None, unit: str) -> list[Change]:
|
|
68
|
+
a = {e.key: e for e in (ordered(old) if old else [])}
|
|
69
|
+
b = {e.key: e for e in (ordered(new) if new else [])}
|
|
70
|
+
changes: list[Change] = []
|
|
71
|
+
for key in sorted(a.keys() | b.keys(), key=lambda k: ((k or "").lower(), k or "")):
|
|
72
|
+
ea, eb = a.get(key), b.get(key)
|
|
73
|
+
if ea is None and eb is not None:
|
|
74
|
+
changes.append(Change("added", unit, new=eb))
|
|
75
|
+
elif eb is None and ea is not None:
|
|
76
|
+
changes.append(Change("removed", unit, old=ea))
|
|
77
|
+
elif ea is not None and eb is not None and not ea.same_as(eb):
|
|
78
|
+
changes.append(Change("changed", unit, old=ea, new=eb))
|
|
79
|
+
return changes
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _sequence(old: Block | None, new: Block | None, unit: str) -> list[Change]:
|
|
83
|
+
a = old.entries if old else []
|
|
84
|
+
b = new.entries if new else []
|
|
85
|
+
sm = difflib.SequenceMatcher(
|
|
86
|
+
a=[(e.text, e.note) for e in a], b=[(e.text, e.note) for e in b], autojunk=False
|
|
87
|
+
)
|
|
88
|
+
changes: list[Change] = []
|
|
89
|
+
for tag, i1, i2, j1, j2 in sm.get_opcodes():
|
|
90
|
+
if tag == "equal":
|
|
91
|
+
continue
|
|
92
|
+
if tag == "replace":
|
|
93
|
+
paired = min(i2 - i1, j2 - j1)
|
|
94
|
+
for k in range(paired):
|
|
95
|
+
changes.append(Change("changed", unit, a[i1 + k], b[j1 + k], i1 + k, j1 + k))
|
|
96
|
+
for i in range(i1 + paired, i2):
|
|
97
|
+
changes.append(Change("removed", unit, old=a[i], old_index=i))
|
|
98
|
+
for j in range(j1 + paired, j2):
|
|
99
|
+
changes.append(Change("added", unit, new=b[j], new_index=j))
|
|
100
|
+
elif tag == "delete":
|
|
101
|
+
for i in range(i1, i2):
|
|
102
|
+
changes.append(Change("removed", unit, old=a[i], old_index=i))
|
|
103
|
+
elif tag == "insert":
|
|
104
|
+
for j in range(j1, j2):
|
|
105
|
+
changes.append(Change("added", unit, new=b[j], new_index=j))
|
|
106
|
+
return changes
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def diff_documents(old: Document, new: Document) -> list[BlockDiff]:
|
|
110
|
+
"""Compare two documents block by block, in the order of the new one."""
|
|
111
|
+
a = old.by_title()
|
|
112
|
+
b = new.by_title()
|
|
113
|
+
titles = [blk.title for blk in new.blocks]
|
|
114
|
+
titles += [blk.title for blk in old.blocks if blk.title not in b]
|
|
115
|
+
result: list[BlockDiff] = []
|
|
116
|
+
for title in titles:
|
|
117
|
+
ba, bb = a.get(title), b.get(title)
|
|
118
|
+
ref = bb or ba
|
|
119
|
+
assert ref is not None
|
|
120
|
+
fn = _sequence if ref.kind == "sequence" else _keyed
|
|
121
|
+
changes = fn(ba, bb, ref.unit)
|
|
122
|
+
if not changes:
|
|
123
|
+
continue
|
|
124
|
+
status: Literal["added", "removed", "changed"] = (
|
|
125
|
+
"added" if ba is None else "removed" if bb is None else "changed"
|
|
126
|
+
)
|
|
127
|
+
result.append(BlockDiff(title, status, changes))
|
|
128
|
+
return _drop_values_of_new_tags(result)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
_BASE_NAME = re.compile(r"^[^.\[]+")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _drop_values_of_new_tags(diffs: list[BlockDiff]) -> list[BlockDiff]:
|
|
135
|
+
"""A new or deleted tag already says it all; skip its individual values."""
|
|
136
|
+
gone_or_new: dict[str, set[str]] = {}
|
|
137
|
+
for d in diffs:
|
|
138
|
+
for c in d.changes:
|
|
139
|
+
if c.unit == "Tag" and c.op in ("added", "removed"):
|
|
140
|
+
entry = c.new or c.old
|
|
141
|
+
if entry is not None and entry.key:
|
|
142
|
+
gone_or_new.setdefault(d.title + " (values)", set()).add(entry.key)
|
|
143
|
+
out: list[BlockDiff] = []
|
|
144
|
+
for d in diffs:
|
|
145
|
+
skip = gone_or_new.get(d.title)
|
|
146
|
+
if skip:
|
|
147
|
+
kept = []
|
|
148
|
+
for c in d.changes:
|
|
149
|
+
entry = c.new or c.old
|
|
150
|
+
m = _BASE_NAME.match(entry.key or "") if entry is not None else None
|
|
151
|
+
if c.op != "changed" and m and m.group(0) in skip:
|
|
152
|
+
continue
|
|
153
|
+
kept.append(c)
|
|
154
|
+
d.changes = kept
|
|
155
|
+
if d.changes:
|
|
156
|
+
out.append(d)
|
|
157
|
+
return out
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def summarize(diffs: list[BlockDiff]) -> str:
|
|
161
|
+
"""``3 rungs changed, 1 tag added`` style one-liner."""
|
|
162
|
+
if not diffs:
|
|
163
|
+
return "no changes"
|
|
164
|
+
counts: dict[tuple[str, str], int] = {}
|
|
165
|
+
for d in diffs:
|
|
166
|
+
for c in d.changes:
|
|
167
|
+
counts[(c.unit, c.op)] = counts.get((c.unit, c.op), 0) + 1
|
|
168
|
+
parts = []
|
|
169
|
+
for (unit, op), n in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])):
|
|
170
|
+
noun = unit.lower() + ("s" if n != 1 else "")
|
|
171
|
+
parts.append(f"{n} {noun} {op}")
|
|
172
|
+
return ", ".join(parts)
|
plcdiff/gitutil.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Git integration: textconv driver setup and diffing a revision range."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import subprocess
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from plcdiff.loader import looks_supported
|
|
11
|
+
|
|
12
|
+
DRIVER = "plcdiff"
|
|
13
|
+
DEFAULT_PATTERNS = ("*.L5X", "*.l5x")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class GitError(RuntimeError):
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def git(*args: str, cwd: str | Path | None = None, check: bool = True) -> bytes:
|
|
21
|
+
proc = subprocess.run(["git", *args], cwd=cwd, capture_output=True, check=False)
|
|
22
|
+
if check and proc.returncode != 0:
|
|
23
|
+
raise GitError(proc.stderr.decode(errors="replace").strip() or f"git {args[0]} failed")
|
|
24
|
+
return proc.stdout
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def repo_root(cwd: str | Path | None = None) -> Path:
|
|
28
|
+
return Path(git("rev-parse", "--show-toplevel", cwd=cwd).decode().strip())
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def install(
|
|
32
|
+
global_: bool = False,
|
|
33
|
+
patterns: tuple[str, ...] = DEFAULT_PATTERNS,
|
|
34
|
+
cwd: str | Path | None = None,
|
|
35
|
+
command: str = "plcdiff textconv",
|
|
36
|
+
) -> list[str]:
|
|
37
|
+
"""Register the textconv driver and map file patterns to it.
|
|
38
|
+
|
|
39
|
+
Returns human-readable lines describing what was changed.
|
|
40
|
+
"""
|
|
41
|
+
scope = ["--global"] if global_ else []
|
|
42
|
+
git("config", *scope, f"diff.{DRIVER}.textconv", command, cwd=cwd)
|
|
43
|
+
git("config", *scope, f"diff.{DRIVER}.cachetextconv", "true", cwd=cwd)
|
|
44
|
+
flag = " --global" if global_ else ""
|
|
45
|
+
done = [f'git config{flag} diff.{DRIVER}.textconv "{command}"']
|
|
46
|
+
if global_:
|
|
47
|
+
attr_path = git("config", "--global", "core.attributesFile", cwd=cwd, check=False)
|
|
48
|
+
target = (
|
|
49
|
+
Path(attr_path.decode().strip()).expanduser()
|
|
50
|
+
if attr_path.strip()
|
|
51
|
+
else _config_home() / "git" / "attributes"
|
|
52
|
+
)
|
|
53
|
+
else:
|
|
54
|
+
target = repo_root(cwd) / ".gitattributes"
|
|
55
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
56
|
+
existing = target.read_text(encoding="utf-8") if target.exists() else ""
|
|
57
|
+
lines = existing.splitlines()
|
|
58
|
+
added = []
|
|
59
|
+
for pattern in patterns:
|
|
60
|
+
line = f"{pattern} diff={DRIVER}"
|
|
61
|
+
if line not in lines:
|
|
62
|
+
lines.append(line)
|
|
63
|
+
added.append(line)
|
|
64
|
+
if added:
|
|
65
|
+
target.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
66
|
+
done.append(f"added to {target}: " + "; ".join(added))
|
|
67
|
+
else:
|
|
68
|
+
done.append(f"{target} already maps {', '.join(patterns)}")
|
|
69
|
+
return done
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _config_home() -> Path:
|
|
73
|
+
"""Where git looks for global attributes: $XDG_CONFIG_HOME or $HOME/.config."""
|
|
74
|
+
xdg = os.environ.get("XDG_CONFIG_HOME")
|
|
75
|
+
if xdg:
|
|
76
|
+
return Path(xdg)
|
|
77
|
+
home = os.environ.get("HOME")
|
|
78
|
+
return (Path(home) if home else Path.home()) / ".config"
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass
|
|
82
|
+
class FileChange:
|
|
83
|
+
path: str
|
|
84
|
+
old_path: str
|
|
85
|
+
old: bytes
|
|
86
|
+
new: bytes
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _show(rev: str, path: str, cwd: str | Path | None) -> bytes:
|
|
90
|
+
return git("show", f"{rev}:{path}", cwd=cwd, check=False)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def changed_files(
|
|
94
|
+
rev_range: str | None, paths: list[str] | None = None, cwd: str | Path | None = None
|
|
95
|
+
) -> list[FileChange]:
|
|
96
|
+
"""Supported files changed in ``A..B``, ``A`` (vs. working tree) or HEAD vs. tree."""
|
|
97
|
+
if rev_range and ".." in rev_range:
|
|
98
|
+
base, _, head = rev_range.partition("..")
|
|
99
|
+
base = base.lstrip(".") or "HEAD"
|
|
100
|
+
head = head.lstrip(".") or "HEAD"
|
|
101
|
+
else:
|
|
102
|
+
base, head = rev_range or "HEAD", ""
|
|
103
|
+
args = ["diff", "--name-status", "-M", "-z", base]
|
|
104
|
+
if head:
|
|
105
|
+
args.append(head)
|
|
106
|
+
if paths:
|
|
107
|
+
args += ["--", *paths]
|
|
108
|
+
raw = git(*args, cwd=cwd).decode("utf-8", errors="replace").split("\0")
|
|
109
|
+
root = repo_root(cwd)
|
|
110
|
+
out: list[FileChange] = []
|
|
111
|
+
i = 0
|
|
112
|
+
while i < len(raw) and raw[i]:
|
|
113
|
+
status = raw[i]
|
|
114
|
+
if status.startswith(("R", "C")):
|
|
115
|
+
old_path, new_path = raw[i + 1], raw[i + 2]
|
|
116
|
+
i += 3
|
|
117
|
+
else:
|
|
118
|
+
old_path = new_path = raw[i + 1]
|
|
119
|
+
i += 2
|
|
120
|
+
if not looks_supported(new_path):
|
|
121
|
+
continue
|
|
122
|
+
old = b"" if status.startswith("A") else _show(base, old_path, root)
|
|
123
|
+
if status.startswith("D"):
|
|
124
|
+
new = b""
|
|
125
|
+
elif head:
|
|
126
|
+
new = _show(head, new_path, root)
|
|
127
|
+
else:
|
|
128
|
+
new = (root / new_path).read_bytes()
|
|
129
|
+
out.append(FileChange(new_path, old_path, old, new))
|
|
130
|
+
return out
|