Skip to content
This repository was archived by the owner on Oct 17, 2024. It is now read-only.

Commit a850ed6

Browse files
committed
Allow setting max column width and simplify cli and config
Signed-off-by: Bernát Gábor <[email protected]>
1 parent 7261f7c commit a850ed6

File tree

11 files changed

+108
-133
lines changed

11 files changed

+108
-133
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,6 @@ dist
77

88
/target
99
/pyproject-*.toml
10-
/src/pyproject_fmt/_lib.cpython-*
10+
/src/pyproject_fmt/_lib.abi3*
1111
/tarpaulin-report.html
12+
/build_rs_cov.profraw

Cargo.toml

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,7 @@ edition = "2021"
1010
[lib]
1111
name = "_lib"
1212
path = "rust/src/main.rs"
13-
crate-type = [
14-
"cdylib",
15-
]
13+
crate-type = ["cdylib"]
1614

1715
[dependencies]
1816
taplo = { version = "0.13.0" } # formatter
@@ -21,12 +19,8 @@ lexical-sort = { version = "0.3.1" }
2119
regex = { version = "1.10.4" }
2220

2321
[features]
24-
extension-module = [
25-
"pyo3/extension-module",
26-
]
27-
default = [
28-
"extension-module",
29-
]
22+
extension-module = ["pyo3/extension-module"]
23+
default = ["extension-module"]
3024

3125
[lints.clippy]
3226
all = "warn"

rust/src/main.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ mod helpers;
2121
#[must_use]
2222
pub fn format_toml(
2323
content: &str,
24+
column_width: usize,
2425
indent: usize,
2526
keep_full_version: bool,
2627
max_supported_python: (u8, u8),
@@ -48,7 +49,7 @@ pub fn format_toml(
4849
compact_arrays: false, // do not compact for easier diffs
4950
compact_inline_tables: false, // do not compact for easier diffs
5051
compact_entries: false, // do not compact for easier diffs
51-
column_width: 1, // always expand arrays per https://github.com/tamasfe/taplo/issues/390
52+
column_width, // always expand arrays per https://github.com/tamasfe/taplo/issues/390
5253
indent_tables: false,
5354
indent_entries: false,
5455
inline_table_expand: true,
@@ -62,10 +63,13 @@ pub fn format_toml(
6263
format_syntax(root_ast, options)
6364
}
6465

66+
/// # Errors
67+
///
68+
/// Will return `PyErr` if an error is raised during formatting.
6569
#[pymodule]
6670
#[pyo3(name = "_lib")]
6771
#[cfg(not(tarpaulin_include))]
68-
fn _lib(m: &Bound<'_, PyModule>) -> PyResult<()> {
72+
pub fn _lib(m: &Bound<'_, PyModule>) -> PyResult<()> {
6973
m.add_function(wrap_pyfunction!(format_toml, m)?)?;
7074
Ok(())
7175
}
@@ -156,7 +160,7 @@ mod tests {
156160
#[case] keep_full_version: bool,
157161
#[case] max_supported_python: (u8, u8),
158162
) {
159-
let got = format_toml(start, indent, keep_full_version, max_supported_python, (3, 8));
163+
let got = format_toml(start, 1, indent, keep_full_version, max_supported_python, (3, 8));
160164
assert_eq!(got, expected);
161165
}
162166
}

src/pyproject_fmt/__main__.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@
88
from typing import TYPE_CHECKING, Iterable, Sequence
99

1010
from pyproject_fmt._lib import format_toml
11-
from pyproject_fmt.cli import PyProjectFmtNamespace, cli_args
11+
from pyproject_fmt.cli import cli_args
1212

1313
if TYPE_CHECKING:
14-
from pyproject_fmt.config import Config
14+
from pyproject_fmt.cli import Config
1515

1616
GREEN = "\u001b[32m"
1717
RED = "\u001b[31m"
@@ -33,21 +33,22 @@ def color_diff(diff: Iterable[str]) -> Iterable[str]:
3333
yield line
3434

3535

36-
def _handle_one(config: Config, opts: PyProjectFmtNamespace) -> bool:
36+
def _handle_one(config: Config) -> bool:
3737
formatted = format_toml(
3838
config.toml,
39+
column_width=config.column_width,
3940
indent=config.indent,
4041
keep_full_version=config.keep_full_version,
4142
max_supported_python=(config.max_supported_python.major, config.max_supported_python.minor),
4243
min_supported_python=(config.min_supported_python.major, config.min_supported_python.minor),
4344
)
4445
before = config.toml
4546
changed = before != formatted
46-
if opts.stdout: # stdout just prints new format to stdout
47+
if config.stdout: # stdout just prints new format to stdout
4748
print(formatted, end="") # noqa: T201
4849
return changed
4950

50-
if before != formatted and not opts.check:
51+
if before != formatted and not config.check:
5152
config.pyproject_toml.write_text(formatted, encoding="utf-8")
5253
try:
5354
name = str(config.pyproject_toml.relative_to(Path.cwd()))
@@ -72,8 +73,8 @@ def run(args: Sequence[str] | None = None) -> int:
7273
:param args: CLI arguments
7374
:return: exit code
7475
"""
75-
opts = cli_args(sys.argv[1:] if args is None else args)
76-
results = [_handle_one(config, opts) for config in opts.configs]
76+
configs = cli_args(sys.argv[1:] if args is None else args)
77+
results = [_handle_one(config) for config in configs]
7778
return 1 if any(results) else 0 # exit with non success on change
7879

7980

src/pyproject_fmt/_lib.pyi

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
def format_toml(
1+
def format_toml( # noqa: PLR0913
22
content: str,
33
*,
4+
column_width: int,
45
indent: int,
56
keep_full_version: bool,
67
max_supported_python: tuple[int, int],

src/pyproject_fmt/cli.py

Lines changed: 76 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,14 @@
22

33
from __future__ import annotations
44

5+
import sys
6+
from dataclasses import dataclass
7+
8+
if sys.version_info >= (3, 11): # pragma: >=3.11 cover
9+
import tomllib
10+
else: # pragma: <3.11 cover
11+
import tomli as tomllib
12+
513
import os
614
from argparse import (
715
ArgumentDefaultsHelpFormatter,
@@ -15,33 +23,39 @@
1523

1624
from packaging.version import Version
1725

18-
from .config import DEFAULT_INDENT, DEFAULT_MAX_SUPPORTED_PYTHON, DEFAULT_MIN_SUPPORTED_PYTHON, Config
19-
2026

2127
class PyProjectFmtNamespace(Namespace):
2228
"""Options for pyproject-fmt tool."""
2329

2430
inputs: list[Path]
2531
stdout: bool
2632
check: bool
33+
34+
column_width: int
2735
indent: int
2836
keep_full_version: bool
2937
max_supported_python: Version
3038
min_supported_python: Version
3139

40+
41+
@dataclass(frozen=True)
42+
class Config:
43+
"""Configuration flags for the formatting."""
44+
45+
pyproject_toml: Path
46+
stdout: bool # push to standard out
47+
check: bool # check only
48+
49+
column_width: int #: maximum column width
50+
indent: int #: indentation to apply
51+
keep_full_version: bool #: whether to keep full dependency versions
52+
max_supported_python: Version #: the maximum supported Python version
53+
min_supported_python: Version #: the minimum supported Python version
54+
3255
@property
33-
def configs(self) -> list[Config]:
34-
""":return: configurations"""
35-
return [
36-
Config.from_file(
37-
filename=toml,
38-
indent=self.indent,
39-
keep_full_version=self.keep_full_version,
40-
max_supported_python=self.max_supported_python,
41-
min_supported_python=self.min_supported_python,
42-
)
43-
for toml in self.inputs
44-
]
56+
def toml(self) -> str:
57+
""":return: the toml files content"""
58+
return self.pyproject_toml.read_text(encoding="utf-8")
4559

4660

4761
def pyproject_toml_path_creator(argument: str) -> Path:
@@ -88,43 +102,84 @@ def _build_cli() -> ArgumentParser:
88102
group.add_argument("--check", action="store_true", help=msg)
89103
msg = "keep full dependency versions. For example do not change version 1.0.0 to 1"
90104
parser.add_argument("--keep-full-version", action="store_true", help=msg)
105+
parser.add_argument(
106+
"--column-width",
107+
type=int,
108+
default=1,
109+
help="max column width in the file",
110+
)
91111
parser.add_argument(
92112
"--indent",
93113
type=int,
94-
default=DEFAULT_INDENT,
114+
default=2,
95115
help="number of spaces to indent",
96116
)
97117
parser.add_argument(
98118
"--min-supported-python",
99119
type=Version,
100-
default=DEFAULT_MIN_SUPPORTED_PYTHON,
120+
default="3.8",
101121
help="latest Python version the project supports (e.g. 3.8)",
102122
)
103123
parser.add_argument(
104124
"--max-supported-python",
105125
type=Version,
106-
default=DEFAULT_MAX_SUPPORTED_PYTHON,
126+
default="3.12",
107127
help="latest Python version the project supports (e.g. 3.13)",
108128
)
109129
msg = "pyproject.toml file(s) to format"
110130
parser.add_argument("inputs", nargs="+", type=pyproject_toml_path_creator, help=msg)
111131
return parser
112132

113133

114-
def cli_args(args: Sequence[str]) -> PyProjectFmtNamespace:
134+
def cli_args(args: Sequence[str]) -> list[Config]:
115135
"""
116136
Load the tools options.
117137
118138
:param args: CLI arguments
119139
:return: the parsed options
120140
"""
121141
parser = _build_cli()
122-
result = PyProjectFmtNamespace()
123-
parser.parse_args(namespace=result, args=args)
124-
return result
142+
opt = PyProjectFmtNamespace()
143+
parser.parse_args(namespace=opt, args=args)
144+
res = []
145+
for pyproject_toml in opt.inputs:
146+
column_width = opt.column_width
147+
indent = opt.indent
148+
keep_full_version = opt.keep_full_version
149+
max_supported_python = opt.max_supported_python
150+
min_supported_python = opt.min_supported_python
151+
with pyproject_toml.open("rb") as file_handler:
152+
config = tomllib.load(file_handler)
153+
if "tool" in config and "pyproject-fmt" in config["tool"]:
154+
for key, entry in config["tool"]["pyproject-fmt"].items():
155+
if key == "column_width":
156+
column_width = int(entry)
157+
elif key == "indent":
158+
indent = int(entry)
159+
elif key == "keep_full_version":
160+
keep_full_version = bool(entry)
161+
elif key == "max_supported_python":
162+
max_supported_python = Version(entry)
163+
elif key == "min_supported_python": # pragma: no branch
164+
min_supported_python = Version(entry)
165+
res.append(
166+
Config(
167+
pyproject_toml=pyproject_toml,
168+
stdout=opt.stdout,
169+
check=opt.check,
170+
column_width=column_width,
171+
indent=indent,
172+
keep_full_version=keep_full_version,
173+
max_supported_python=max_supported_python,
174+
min_supported_python=min_supported_python,
175+
)
176+
)
177+
178+
return res
125179

126180

127181
__all__ = [
182+
"Config",
128183
"PyProjectFmtNamespace",
129184
"cli_args",
130185
]

src/pyproject_fmt/config.py

Lines changed: 0 additions & 88 deletions
This file was deleted.

tests/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,11 @@ def __call__(
99
start: str,
1010
expected: str,
1111
*,
12+
column_width: int = ...,
1213
indent: int = ...,
1314
keep_full_version: bool = ...,
1415
max_supported_python: tuple[int, int] = ...,
16+
min_supported_python: tuple[int, int] = ...,
1517
) -> None: ...
1618

1719

0 commit comments

Comments
 (0)