xml-fmt 1.0.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.
xml_fmt/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """XML formatter."""
xml_fmt/__main__.py ADDED
@@ -0,0 +1,160 @@
1
+ """Format XMLs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+ from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError, Namespace
8
+ from difflib import unified_diff
9
+ from importlib.metadata import version
10
+ from pathlib import Path
11
+ from typing import TYPE_CHECKING
12
+ from xml.etree.ElementTree import XML, indent, tostring # noqa: S405
13
+
14
+ if TYPE_CHECKING:
15
+ from collections.abc import Iterable, Sequence
16
+
17
+
18
+ class Options(Namespace):
19
+ """Options for pyproject-fmt tool."""
20
+
21
+ inputs: list[Path | None]
22
+ stdout: bool
23
+ check: bool
24
+ no_print_diff: bool
25
+
26
+ indent: str
27
+ expand_empty_elements: bool
28
+
29
+
30
+ def run(args: Sequence[str] | None = None) -> int:
31
+ """
32
+ Run the formatter.
33
+
34
+ :param args: command line arguments, by default use sys.argv[1:]
35
+ :return: exit code - 0 means already formatted correctly, otherwise 1
36
+ """ # noqa: DOC201
37
+ parser = _build_cli()
38
+ opts = Options()
39
+ parser.parse_args(args=args, namespace=opts)
40
+ results = [_handle_one(filename, opts) for filename in opts.inputs]
41
+ return 1 if any(results) else 0 # exit with non success on change
42
+
43
+
44
+ class _Formatter(ArgumentDefaultsHelpFormatter):
45
+ def __init__(self, prog: str) -> None:
46
+ super().__init__(prog, max_help_position=29, width=240)
47
+
48
+
49
+ def _build_cli() -> ArgumentParser:
50
+ parser = ArgumentParser(formatter_class=_Formatter, prog="xml-fmt")
51
+ parser.add_argument(
52
+ "-V",
53
+ "--version",
54
+ action="version",
55
+ help="version of the project",
56
+ version=f"%(prog)s ({version('xml-fmt')})",
57
+ )
58
+
59
+ mode_group = parser.add_argument_group("run mode")
60
+ mode = mode_group.add_mutually_exclusive_group()
61
+ msg = "print the formatted XML to the stdout, implied if reading from stdin"
62
+ mode.add_argument("-s", "--stdout", action="store_true", help=msg)
63
+ msg = "check and fail if any input would be formatted, printing any diffs"
64
+ mode.add_argument("--check", action="store_true", help=msg)
65
+ mode_group.add_argument(
66
+ "-n",
67
+ "--no-print-diff",
68
+ action="store_true",
69
+ help="controls if to print diff - when running in check mode",
70
+ )
71
+
72
+ format_group = parser.add_argument_group("formatting behavior")
73
+ format_group.add_argument("--indent", default=" ", help="indentation characters to use - two space by default")
74
+ format_group.add_argument(
75
+ "--expand-empty-elements",
76
+ action="store_true",
77
+ help="controls if empty XML elements should be collapsed into a self closing element or expanded",
78
+ )
79
+
80
+ msg = "XML (XSD) file(s) to format, use '-' to read from stdin"
81
+ parser.add_argument("inputs", nargs="+", type=_path_creator, help=msg)
82
+ return parser
83
+
84
+
85
+ def _path_creator(argument: str) -> Path | None:
86
+ if argument == "-":
87
+ return None # stdin, no further validation needed
88
+ path = Path(argument).absolute()
89
+ if not path.exists():
90
+ msg = "path does not exist"
91
+ raise ArgumentTypeError(msg)
92
+ if not path.is_file():
93
+ msg = "path is not a file"
94
+ raise ArgumentTypeError(msg)
95
+ if not os.access(path, os.R_OK):
96
+ msg = "cannot read path"
97
+ raise ArgumentTypeError(msg)
98
+ if not os.access(path, os.W_OK):
99
+ msg = "cannot write path"
100
+ raise ArgumentTypeError(msg)
101
+ return path
102
+
103
+
104
+ def _handle_one(filename: Path | None, opts: Options) -> bool:
105
+ before = sys.stdin.read() if filename is None else filename.read_text(encoding="utf-8")
106
+ formatted = _format(before, opts)
107
+
108
+ changed = before != formatted
109
+ if filename is None or opts.stdout: # when reading from stdin or writing to stdout, print new format
110
+ print(formatted, end="") # noqa: T201
111
+ return changed
112
+
113
+ if before != formatted and not opts.check:
114
+ filename.write_text(formatted, encoding="utf-8")
115
+ if opts.no_print_diff:
116
+ return changed
117
+ try:
118
+ name = str(filename.relative_to(Path.cwd()))
119
+ except ValueError:
120
+ name = str(filename)
121
+ diff: Iterable[str] = []
122
+ if changed:
123
+ diff = unified_diff(before.splitlines(), formatted.splitlines(), fromfile=name, tofile=name)
124
+
125
+ if diff:
126
+ diff = _color_diff(diff)
127
+ print("\n".join(diff)) # print diff on change # noqa: T201
128
+ else:
129
+ print(f"no change for {name}") # noqa: T201
130
+ return changed
131
+
132
+
133
+ def _format(raw: str, opts: Options) -> str:
134
+ element = XML(raw)
135
+ indent(element, opts.indent)
136
+ return tostring(
137
+ element,
138
+ encoding="unicode",
139
+ xml_declaration=True,
140
+ short_empty_elements=not opts.expand_empty_elements,
141
+ )
142
+
143
+
144
+ GREEN = "\u001b[32m"
145
+ RED = "\u001b[31m"
146
+ RESET = "\u001b[0m"
147
+
148
+
149
+ def _color_diff(diff: Iterable[str]) -> Iterable[str]:
150
+ for line in diff:
151
+ if line.startswith("+"):
152
+ yield f"{GREEN}{line}{RESET}"
153
+ elif line.startswith("-"):
154
+ yield f"{RED}{line}{RESET}"
155
+ else:
156
+ yield line
157
+
158
+
159
+ if __name__ == "__main__":
160
+ raise SystemExit(run(sys.argv[1:]))
xml_fmt/py.typed ADDED
File without changes
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.4
2
+ Name: xml-fmt
3
+ Version: 1.0.0
4
+ Summary: Run pre-commit with uv
5
+ Project-URL: Bug Tracker, https://github.com/tox-dev/xml-fmt/issues
6
+ Project-URL: Changelog, https://github.com/tox-dev/xml-fmt/releases
7
+ Project-URL: Documentation, https://github.com/tox-dev/xml-fmt/
8
+ Project-URL: Source Code, https://github.com/tox-dev/xml-fmt
9
+ Author-email: Bernat Gabor <gaborjbernat@gmail.com>
10
+ License: Permission is hereby granted, free of charge, to any person obtaining a
11
+ copy of this software and associated documentation files (the
12
+ "Software"), to deal in the Software without restriction, including
13
+ without limitation the rights to use, copy, modify, merge, publish,
14
+ distribute, sublicense, and/or sell copies of the Software, and to
15
+ permit persons to whom the Software is furnished to do so, subject to
16
+ the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included
19
+ in all copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
22
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
24
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
25
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
26
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
27
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28
+ License-File: LICENSE.txt
29
+ Keywords: XML,format
30
+ Classifier: License :: OSI Approved :: MIT License
31
+ Classifier: Operating System :: OS Independent
32
+ Classifier: Programming Language :: Python
33
+ Classifier: Programming Language :: Python :: 3 :: Only
34
+ Classifier: Programming Language :: Python :: 3.9
35
+ Classifier: Programming Language :: Python :: 3.10
36
+ Classifier: Programming Language :: Python :: 3.11
37
+ Classifier: Programming Language :: Python :: 3.12
38
+ Classifier: Programming Language :: Python :: 3.13
39
+ Requires-Python: >=3.9
40
+ Description-Content-Type: text/markdown
41
+
42
+ # xml-fmt
43
+
44
+ [![PyPI](https://img.shields.io/pypi/v/xml-fmt?style=flat-square)](https://pypi.org/project/xml-fmt)
45
+ [![PyPI - Implementation](https://img.shields.io/pypi/implementation/xml-fmt?style=flat-square)](https://pypi.org/project/xml-fmt)
46
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/xml-fmt?style=flat-square)](https://pypi.org/project/xml-fmt)
47
+ [![Downloads](https://static.pepy.tech/badge/xml-fmt/month)](https://pepy.tech/project/xml-fmt)
48
+ [![PyPI - License](https://img.shields.io/pypi/l/xml-fmt?style=flat-square)](https://opensource.org/licenses/MIT)
49
+ [![check](https://github.com/tox-dev/xml-fmt/actions/workflows/check.yaml/badge.svg)](https://github.com/tox-dev/xml-fmt/actions/workflows/check.yaml)
50
+
51
+ ### Using `xml-fmt` with pre-commit
52
+
53
+ Add it to your `.pre-commit-config.yaml`:
54
+
55
+ ```yaml
56
+ - repo: https://github.com/tox-dev/xml-fmt
57
+ rev: "" # Use the sha / tag you want to point at
58
+ hooks:
59
+ - id: pyproject-fmt
60
+ ```
@@ -0,0 +1,8 @@
1
+ xml_fmt/__init__.py,sha256=SmqF7Gms74MVptctdxAxgIIIeHdldmGICJacIX1w-rA,21
2
+ xml_fmt/__main__.py,sha256=GvPv4-ucoVzvZ_37MtFx89fyfC92CaHZgMu-sU5hpag,5011
3
+ xml_fmt/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ xml_fmt-1.0.0.dist-info/METADATA,sha256=fP7rUhPai7trj-wQJ1gbjP8ByfEeWFZiS6krEztuO04,3077
5
+ xml_fmt-1.0.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
6
+ xml_fmt-1.0.0.dist-info/entry_points.txt,sha256=Uq24L5CeU3mvfWGN77E_I97n_Vwurmh5uTsGXDrJH4c,49
7
+ xml_fmt-1.0.0.dist-info/licenses/LICENSE.txt,sha256=kOJeH68qSq6o2V7o5_VziwUqGswMnFgGgQH5Mahr1Yg,1023
8
+ xml_fmt-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ xml-fmt = xml_fmt.__main__:run
@@ -0,0 +1,18 @@
1
+ Permission is hereby granted, free of charge, to any person obtaining a
2
+ copy of this software and associated documentation files (the
3
+ "Software"), to deal in the Software without restriction, including
4
+ without limitation the rights to use, copy, modify, merge, publish,
5
+ distribute, sublicense, and/or sell copies of the Software, and to
6
+ permit persons to whom the Software is furnished to do so, subject to
7
+ the following conditions:
8
+
9
+ The above copyright notice and this permission notice shall be included
10
+ in all copies or substantial portions of the Software.
11
+
12
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
15
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
16
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
17
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
18
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.