• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

waketzheng / fast-dev-cli / 18552405204

16 Oct 2025 04:37AM UTC coverage: 88.933% (-0.2%) from 89.13%
18552405204

push

github

waketzheng
feat: drop support for Python3.9

1 of 1 new or added line in 1 file covered. (100.0%)

2 existing lines in 1 file now uncovered.

900 of 1012 relevant lines covered (88.93%)

4.45 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

88.92
/fast_dev_cli/cli.py
1
from __future__ import annotations
5✔
2

3
import contextlib
5✔
4
import functools
5✔
5
import importlib.metadata as importlib_metadata
5✔
6
import os
5✔
7
import platform
5✔
8
import re
5✔
9
import shlex
5✔
10
import shutil
5✔
11
import subprocess  # nosec:B404
5✔
12
import sys
5✔
13
from functools import cached_property
5✔
14
from pathlib import Path
5✔
15
from typing import (
5✔
16
    TYPE_CHECKING,
17
    Any,
18
    Literal,
19
    # Optional is required by Option generated by typer
20
    Optional,
21
    cast,
22
    get_args,
23
    overload,
24
)
25

26
import typer
5✔
27
from click import UsageError
5✔
28
from typer import Exit, Option, echo, secho
5✔
29
from typer.models import ArgumentInfo, OptionInfo
5✔
30

31
try:
5✔
32
    from . import __version__
5✔
33
except ImportError:  # pragma: no cover
34
    from importlib import import_module as _import  # For local unittest
35

36
    __version__ = _import(Path(__file__).parent.name).__version__
37

38
if sys.version_info >= (3, 11):  # pragma: no cover
39
    from enum import StrEnum
40

41
    import tomllib
42
else:  # pragma: no cover
43
    from enum import Enum
44

45
    import tomli as tomllib
46

47
    class StrEnum(str, Enum):
48
        __str__ = str.__str__
49

50

51
if TYPE_CHECKING:
52
    if sys.version_info >= (3, 11):
53
        from typing import Self
54
    else:
55
        from typing_extensions import Self
56

57
cli = typer.Typer(no_args_is_help=True)
5✔
58
DryOption = Option(False, "--dry", help="Only print, not really run shell command")
5✔
59
TOML_FILE = "pyproject.toml"
5✔
60
ToolName = Literal["poetry", "pdm", "uv"]
5✔
61
ToolOption = Option(
5✔
62
    "auto", "--tool", help="Explicit declare manage tool (default to auto detect)"
63
)
64

65

66
class FastDevCliError(Exception):
5✔
67
    """Basic exception of this library, all custom exceptions inherit from it"""
68

69

70
class ShellCommandError(FastDevCliError):
5✔
71
    """Raise if cmd command returncode is not zero"""
72

73

74
class ParseError(FastDevCliError):
5✔
75
    """Raise this if parse dependence line error"""
76

77

78
class EnvError(FastDevCliError):
5✔
79
    """Raise when expected to be managed by poetry, but toml file not found."""
80

81

82
def poetry_module_name(name: str) -> str:
5✔
83
    """Get module name that generated by `poetry new`"""
84
    try:
5✔
85
        from packaging.utils import canonicalize_name
5✔
86
    except ImportError:
×
87

88
        def canonicalize_name(s: str) -> str:  # type:ignore[misc]
×
89
            return re.sub(r"[-_.]+", "-", s)
×
90

91
    return canonicalize_name(name).replace("-", "_").replace(" ", "_")
5✔
92

93

94
def is_emoji(char: str) -> bool:
5✔
95
    try:
5✔
96
        import emoji
5✔
97
    except ImportError:
×
98
        pass
×
99
    else:
100
        return emoji.is_emoji(char)
5✔
101
    if re.match(r"[\w\d\s]", char):
×
102
        return False
×
103
    return not "\u4e00" <= char <= "\u9fff"  # Chinese character
×
104

105

106
@functools.cache
5✔
107
def is_windows() -> bool:
5✔
108
    return platform.system() == "Windows"
5✔
109

110

111
def yellow_warn(msg: str) -> None:
5✔
112
    if is_windows() and (encoding := sys.stdout.encoding) != "utf-8":
5✔
113
        msg = msg.encode(encoding, errors="ignore").decode(encoding)
×
114
    secho(msg, fg="yellow")
5✔
115

116

117
def load_bool(name: str, default: bool = False) -> bool:
5✔
118
    if not (v := os.getenv(name)):
5✔
119
        return default
5✔
120
    if (lower := v.lower()) in ("0", "false", "f", "off", "no", "n"):
5✔
121
        return False
5✔
122
    elif lower in ("1", "true", "t", "on", "yes", "y"):
5✔
123
        return True
5✔
124
    secho(f"WARNING: can not convert value({v!r}) of {name} to bool!")
5✔
125
    return default
5✔
126

127

128
def is_venv() -> bool:
5✔
129
    """Whether in a virtual environment(also work for poetry)"""
130
    return hasattr(sys, "real_prefix") or (
5✔
131
        hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix
132
    )
133

134

135
class Shell:
5✔
136
    def __init__(self, cmd: list[str] | str, **kw: Any) -> None:
5✔
137
        self._cmd = cmd
5✔
138
        self._kw = kw
5✔
139

140
    @staticmethod
5✔
141
    def run_by_subprocess(
5✔
142
        cmd: list[str] | str, **kw: Any
143
    ) -> subprocess.CompletedProcess[str]:
144
        if isinstance(cmd, str):
5✔
145
            kw.setdefault("shell", True)
5✔
146
        return subprocess.run(cmd, **kw)  # nosec:B603
5✔
147

148
    @property
5✔
149
    def command(self) -> list[str] | str:
5✔
150
        command: list[str] | str = self._cmd
5✔
151
        if (
5✔
152
            isinstance(command, str)
153
            and "shell" not in self._kw
154
            and not (set(self._cmd) & {"|", ">", "&"})
155
        ):
156
            command = shlex.split(command)
5✔
157
        return command
5✔
158

159
    def _run(self) -> subprocess.CompletedProcess[str]:
5✔
160
        return self.run_by_subprocess(self.command, **self._kw)
5✔
161

162
    def run(self, verbose: bool = False, dry: bool = False) -> int:
5✔
163
        if verbose:
5✔
164
            echo(f"--> {self._cmd}")
5✔
165
        if dry:
5✔
166
            return 0
5✔
167
        return self._run().returncode
5✔
168

169
    def check_call(self) -> bool:
5✔
170
        self._kw.update(stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
5✔
171
        return self.run() == 0
5✔
172

173
    def capture_output(self, raises: bool = False) -> str:
5✔
174
        self._kw.update(capture_output=True, encoding="utf-8")
5✔
175
        r = self._run()
5✔
176
        if raises and r.returncode != 0:
5✔
177
            raise ShellCommandError(r.stderr)
5✔
178
        return (r.stdout or r.stderr or "").strip()
5✔
179

180
    def finish(
5✔
181
        self, env: dict[str, str] | None = None, _exit: bool = False, dry=False
182
    ) -> subprocess.CompletedProcess[str]:
183
        self.run(verbose=True, dry=True)
5✔
184
        if _ensure_bool(dry):
5✔
185
            return subprocess.CompletedProcess("", 0)
5✔
186
        if env is not None:
5✔
187
            self._kw["env"] = {**os.environ, **env}
5✔
188
        r = self._run()
5✔
189
        if rc := r.returncode:
5✔
190
            if _exit:
5✔
191
                sys.exit(rc)
5✔
192
            raise Exit(rc)
5✔
193
        return r
5✔
194

195

196
def run_and_echo(
5✔
197
    cmd: str, *, dry: bool = False, verbose: bool = True, **kw: Any
198
) -> int:
199
    """Run shell command with subprocess and print it"""
200
    return Shell(cmd, **kw).run(verbose=verbose, dry=dry)
5✔
201

202

203
def check_call(cmd: str) -> bool:
5✔
204
    return Shell(cmd).check_call()
5✔
205

206

207
def capture_cmd_output(
5✔
208
    command: list[str] | str, *, raises: bool = False, **kw: Any
209
) -> str:
210
    return Shell(command, **kw).capture_output(raises=raises)
5✔
211

212

213
def exit_if_run_failed(
5✔
214
    cmd: str,
215
    env: dict[str, str] | None = None,
216
    _exit: bool = False,
217
    dry: bool = False,
218
    **kw: Any,
219
) -> subprocess.CompletedProcess[str]:
220
    return Shell(cmd, **kw).finish(env=env, _exit=_exit, dry=dry)
5✔
221

222

223
def _parse_version(line: str, pattern: re.Pattern[str]) -> str:
5✔
224
    return pattern.sub("", line).split("#")[0].strip().strip(" '\"")
5✔
225

226

227
def read_version_from_file(
5✔
228
    package_name: str, work_dir: Path | None = None, toml_text: str | None = None
229
) -> str:
230
    if not package_name and toml_text:
5✔
231
        pattern = re.compile(r"version\s*=")
5✔
232
        for line in toml_text.splitlines():
5✔
233
            if pattern.match(line):
5✔
234
                return _parse_version(line, pattern)
5✔
235
    version_file = BumpUp.parse_filename(toml_text, work_dir, package_name)
5✔
236
    if version_file == TOML_FILE:
5✔
237
        if toml_text is None:
5✔
238
            toml_text = Project.load_toml_text()
5✔
239
        context = tomllib.loads(toml_text)
5✔
240
        with contextlib.suppress(KeyError):
5✔
241
            return cast(str, context["project"]["version"])
5✔
242
        with contextlib.suppress(KeyError):  # Poetry V1
5✔
243
            return cast(str, context["tool"]["poetry"]["version"])
5✔
244
        secho(f"WARNING: can not find 'version' item in {version_file}!")
5✔
245
        return "0.0.0"
5✔
246
    pattern = re.compile(r"__version__\s*=")
5✔
247
    for line in Path(version_file).read_text("utf-8").splitlines():
5✔
248
        if pattern.match(line):
5✔
249
            return _parse_version(line, pattern)
5✔
250
    # TODO: remove or refactor the following lines.
251
    if work_dir is None:
×
252
        work_dir = Project.get_work_dir()
×
253
    package_dir = work_dir / package_name
×
254
    if (
×
255
        not (init_file := package_dir / "__init__.py").exists()
256
        and not (init_file := work_dir / "src" / package_name / init_file.name).exists()
257
        and not (init_file := work_dir / "app" / init_file.name).exists()
258
    ):
259
        secho("WARNING: __init__.py file does not exist!")
×
260
        return "0.0.0"
×
261

262
    pattern = re.compile(r"__version__\s*=")
×
263
    for line in init_file.read_text("utf-8").splitlines():
×
264
        if pattern.match(line):
×
265
            return _parse_version(line, pattern)
×
266
    secho(f"WARNING: can not find '__version__' var in {init_file}!")
×
267
    return "0.0.0"
×
268

269

270
@overload
271
def get_current_version(
272
    verbose: bool = False,
273
    is_poetry: bool | None = None,
274
    package_name: str | None = None,
275
    *,
276
    check_version: Literal[False] = False,
277
) -> str: ...
278

279

280
@overload
281
def get_current_version(
282
    verbose: bool = False,
283
    is_poetry: bool | None = None,
284
    package_name: str | None = None,
285
    *,
286
    check_version: Literal[True] = True,
287
) -> tuple[bool, str]: ...
288

289

290
def get_current_version(
5✔
291
    verbose: bool = False,
292
    is_poetry: bool | None = None,
293
    package_name: str | None = None,
294
    *,
295
    check_version: bool = False,
296
) -> str | tuple[bool, str]:
297
    if is_poetry is True or Project.manage_by_poetry():
5✔
298
        cmd = ["poetry", "version", "-s"]
5✔
299
        if verbose:
5✔
300
            echo(f"--> {' '.join(cmd)}")
5✔
301
        if out := capture_cmd_output(cmd, raises=True):
5✔
302
            out = out.splitlines()[-1].strip().split()[-1]
5✔
303
        if check_version:
5✔
304
            return True, out
5✔
305
        return out
5✔
306
    toml_text = work_dir = None
5✔
307
    if package_name is None:
5✔
308
        work_dir = Project.get_work_dir()
5✔
309
        toml_text = Project.load_toml_text()
5✔
310
        doc = tomllib.loads(toml_text)
5✔
311
        project_name = doc.get("project", {}).get("name", work_dir.name)
5✔
312
        package_name = re.sub(r"[- ]", "_", project_name)
5✔
313
    local_version = read_version_from_file(package_name, work_dir, toml_text)
5✔
314
    try:
5✔
315
        installed_version = importlib_metadata.version(package_name)
5✔
316
    except importlib_metadata.PackageNotFoundError:
5✔
317
        installed_version = ""
5✔
318
    current_version = local_version or installed_version
5✔
319
    if not current_version:
5✔
320
        raise FastDevCliError(f"Failed to get current version of {package_name!r}")
×
321
    if check_version:
5✔
322
        is_conflict = bool(local_version) and local_version != installed_version
5✔
323
        return is_conflict, current_version
5✔
324
    return current_version
5✔
325

326

327
def _ensure_bool(value: bool | OptionInfo) -> bool:
5✔
328
    if not isinstance(value, bool):
5✔
329
        value = getattr(value, "default", False)
5✔
330
    return value
5✔
331

332

333
def _ensure_str(value: str | OptionInfo | None) -> str:
5✔
334
    if not isinstance(value, str):
5✔
335
        value = getattr(value, "default", "")
5✔
336
    return value
5✔
337

338

339
class DryRun:
5✔
340
    def __init__(self, _exit: bool = False, dry: bool = False) -> None:
5✔
341
        self.dry = _ensure_bool(dry)
5✔
342
        self._exit = _exit
5✔
343

344
    def gen(self) -> str:
5✔
345
        raise NotImplementedError
5✔
346

347
    def run(self) -> None:
5✔
348
        exit_if_run_failed(self.gen(), _exit=self._exit, dry=self.dry)
5✔
349

350

351
class BumpUp(DryRun):
5✔
352
    class PartChoices(StrEnum):
5✔
353
        patch = "patch"
5✔
354
        minor = "minor"
5✔
355
        major = "major"
5✔
356

357
    def __init__(
5✔
358
        self,
359
        commit: bool,
360
        part: str,
361
        filename: str | None = None,
362
        dry: bool = False,
363
        no_sync: bool = False,
364
        emoji: bool | None = None,
365
    ) -> None:
366
        self.commit = commit
5✔
367
        self.part = part
5✔
368
        if filename is None:
5✔
369
            filename = self.parse_filename()
5✔
370
        self.filename = filename
5✔
371
        self._no_sync = no_sync
5✔
372
        self._emoji = emoji
5✔
373
        super().__init__(dry=dry)
5✔
374

375
    @staticmethod
5✔
376
    def get_last_commit_message(raises: bool = False) -> str:
5✔
377
        cmd = 'git show --pretty=format:"%s" -s HEAD'
5✔
378
        return capture_cmd_output(cmd, raises=raises)
5✔
379

380
    @classmethod
5✔
381
    def should_add_emoji(cls) -> bool:
5✔
382
        """
383
        If last commit message is startswith emoji,
384
        add a ⬆️ flag at the prefix of bump up commit message.
385
        """
386
        try:
5✔
387
            first_char = cls.get_last_commit_message(raises=True)[0]
5✔
388
        except (IndexError, ShellCommandError):
5✔
389
            return False
5✔
390
        else:
391
            return is_emoji(first_char)
5✔
392

393
    @staticmethod
5✔
394
    def parse_filename(
5✔
395
        toml_text: str | None = None,
396
        work_dir: Path | None = None,
397
        package_name: str | None = None,
398
    ) -> str:
399
        if toml_text is None:
5✔
400
            toml_text = Project.load_toml_text()
5✔
401
        context = tomllib.loads(toml_text)
5✔
402
        by_version_plugin = False
5✔
403
        try:
5✔
404
            ver = context["project"]["version"]
5✔
405
        except KeyError:
5✔
406
            pass
5✔
407
        else:
408
            if isinstance(ver, str):
5✔
409
                if ver in ("0", "0.0.0"):
5✔
410
                    by_version_plugin = True
5✔
411
                elif re.match(r"\d+\.\d+\.\d+", ver):
5✔
412
                    return TOML_FILE
5✔
413
        if not by_version_plugin:
5✔
414
            try:
5✔
415
                version_value = context["tool"]["poetry"]["version"]
5✔
416
            except KeyError:
5✔
417
                if not Project.manage_by_poetry():
5✔
418
                    if work_dir is None:
5✔
419
                        work_dir = Project.get_work_dir()
5✔
420
                    for tool in ("pdm", "hatch"):
5✔
421
                        with contextlib.suppress(KeyError):
5✔
422
                            version_path = cast(
5✔
423
                                str, context["tool"][tool]["version"]["path"]
424
                            )
425
                            if (
5✔
426
                                Path(version_path).exists()
427
                                or work_dir.joinpath(version_path).exists()
428
                            ):
429
                                return version_path
5✔
430
                    # version = { source = "file", path = "fast_dev_cli/__init__.py" }
431
                    v_key = "version = "
5✔
432
                    p_key = 'path = "'
5✔
433
                    for line in toml_text.splitlines():
5✔
434
                        if not line.startswith(v_key):
×
435
                            continue
×
436
                        if p_key in (value := line.split(v_key, 1)[-1].split("#")[0]):
×
437
                            filename = value.split(p_key, 1)[-1].split('"')[0]
×
438
                            if work_dir.joinpath(filename).exists():
×
439
                                return filename
×
440
            else:
441
                by_version_plugin = version_value in ("0", "0.0.0", "init")
5✔
442
        if by_version_plugin:
5✔
443
            try:
5✔
444
                package_item = context["tool"]["poetry"]["packages"]
5✔
445
            except KeyError:
5✔
446
                try:
5✔
447
                    project_name = context["project"]["name"]
5✔
448
                except KeyError:
5✔
449
                    packages = []
5✔
450
                else:
451
                    packages = [(poetry_module_name(project_name), "")]
×
452
            else:
453
                packages = [
5✔
454
                    (j, i.get("from", ""))
455
                    for i in package_item
456
                    if (j := i.get("include"))
457
                ]
458
            # In case of managed by `poetry-plugin-version`
459
            cwd = Path.cwd()
5✔
460
            pattern = re.compile(r"__version__\s*=\s*['\"]")
5✔
461
            ds: list[Path] = []
5✔
462
            if package_name is not None:
5✔
463
                packages.insert(0, (package_name, ""))
×
464
            for package_name, source_dir in packages:
5✔
465
                ds.append(cwd / package_name)
5✔
466
                ds.append(cwd / "src" / package_name)
5✔
467
                if source_dir and source_dir != "src":
5✔
468
                    ds.append(cwd / source_dir / package_name)
5✔
469
            module_name = poetry_module_name(cwd.name)
5✔
470
            ds.extend([cwd / module_name, cwd / "src" / module_name, cwd])
5✔
471
            for d in ds:
5✔
472
                init_file = d / "__init__.py"
5✔
473
                if (
5✔
474
                    init_file.exists() and pattern.search(init_file.read_text("utf8"))
475
                ) or (
476
                    (init_file := init_file.with_name("__version__.py")).exists()
477
                    and pattern.search(init_file.read_text("utf8"))
478
                ):
479
                    break
5✔
480
            else:
481
                raise ParseError("Version file not found! Where are you now?")
5✔
482
            return os.path.relpath(init_file, cwd)
5✔
483

484
        return TOML_FILE
5✔
485

486
    def get_part(self, s: str) -> str:
5✔
487
        choices: dict[str, str] = {}
5✔
488
        for i, p in enumerate(self.PartChoices, 1):
5✔
489
            v = str(p)
5✔
490
            choices.update({str(i): v, v: v})
5✔
491
        try:
5✔
492
            return choices[s]
5✔
493
        except KeyError as e:
5✔
494
            echo(f"Invalid part: {s!r}")
5✔
495
            raise Exit(1) from e
5✔
496

497
    def gen(self) -> str:
5✔
498
        should_sync, _version = get_current_version(check_version=True)
5✔
499
        filename = self.filename
5✔
500
        echo(f"Current version(@{filename}): {_version}")
5✔
501
        if self.part:
5✔
502
            part = self.get_part(self.part)
5✔
503
        else:
504
            part = "patch"
5✔
505
            if a := input("Which one?").strip():
5✔
506
                part = self.get_part(a)
5✔
507
        self.part = part
5✔
508
        parse = r'--parse "(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)"'
5✔
509
        cmd = f'bumpversion {parse} --current-version="{_version}" {part} {filename}'
5✔
510
        if self.commit:
5✔
511
            if part != "patch":
5✔
512
                cmd += " --tag"
5✔
513
            cmd += " --commit"
5✔
514
            if self._emoji or (self._emoji is None and self.should_add_emoji()):
5✔
515
                cmd += " --message-emoji=1"
5✔
516
            if not load_bool("DONT_GIT_PUSH"):
5✔
517
                cmd += " && git push && git push --tags && git log -1"
5✔
518
        else:
519
            cmd += " --allow-dirty"
5✔
520
        if should_sync and not self._no_sync and (sync := Project.get_sync_command()):
5✔
521
            cmd = f"{sync} && " + cmd
5✔
522
        return cmd
5✔
523

524
    def run(self) -> None:
5✔
525
        super().run()
5✔
526
        if not self.commit and not self.dry:
5✔
527
            new_version = get_current_version(True)
5✔
528
            echo(new_version)
5✔
529
            if self.part != "patch":
5✔
530
                echo("You may want to pin tag by `fast tag`")
5✔
531

532

533
@cli.command()
5✔
534
def version() -> None:
5✔
535
    """Show the version of this tool"""
536
    echo("Fast Dev Cli Version: " + typer.style(__version__, fg=typer.colors.BLUE))
5✔
537
    with contextlib.suppress(FileNotFoundError, KeyError):
5✔
538
        toml_text = Project.load_toml_text()
5✔
539
        doc = tomllib.loads(toml_text)
5✔
540
        if value := doc.get("project", {}).get("version", ""):
5✔
541
            styled = typer.style(value, bold=True, fg=typer.colors.CYAN)
×
542
            if project_name := doc["project"].get("name", ""):
×
543
                echo(f"{project_name} version: " + styled)
×
544
            else:
545
                echo(f"Got Version from {TOML_FILE}: " + styled)
×
546
            return
×
547
        version_file = doc["tool"]["pdm"]["version"]["path"]
5✔
548
        text = Project.get_work_dir().joinpath(version_file).read_text()
5✔
549
        varname = "__version__"
5✔
550
        for line in text.splitlines():
5✔
551
            if line.strip().startswith(varname):
5✔
552
                value = line.split("=", 1)[-1].strip().strip('"').strip("'")
5✔
553
                styled = typer.style(value, bold=True)
5✔
554
                echo(f"Version value in {version_file}: " + styled)
5✔
555
                break
5✔
556

557

558
@cli.command(name="bump")
5✔
559
def bump_version(
5✔
560
    part: BumpUp.PartChoices,
561
    commit: bool = Option(
562
        False, "--commit", "-c", help="Whether run `git commit` after version changed"
563
    ),
564
    emoji: Optional[bool] = Option(
565
        None, "--emoji", help="Whether add emoji prefix to commit message"
566
    ),
567
    no_sync: bool = Option(
568
        False, "--no-sync", help="Do not run sync command to update version"
569
    ),
570
    dry: bool = DryOption,
571
) -> None:
572
    """Bump up version string in pyproject.toml"""
573
    if emoji is not None:
5✔
574
        emoji = _ensure_bool(emoji)
5✔
575
    return BumpUp(
5✔
576
        _ensure_bool(commit),
577
        getattr(part, "value", part),
578
        no_sync=_ensure_bool(no_sync),
579
        emoji=emoji,
580
        dry=dry,
581
    ).run()
582

583

584
def bump() -> None:
5✔
585
    part, commit = "", False
5✔
586
    if args := sys.argv[2:]:
5✔
587
        if "-c" in args or "--commit" in args:
5✔
588
            commit = True
5✔
589
        for a in args:
5✔
590
            if not a.startswith("-"):
5✔
591
                part = a
5✔
592
                break
5✔
593
    return BumpUp(commit, part, no_sync="--no-sync" in args, dry="--dry" in args).run()
5✔
594

595

596
class Project:
5✔
597
    path_depth = 5
5✔
598
    _tool: ToolName | None = None
5✔
599

600
    @staticmethod
5✔
601
    def is_poetry_v2(text: str) -> bool:
5✔
602
        return 'build-backend = "poetry' in text
5✔
603

604
    @staticmethod
5✔
605
    def get_poetry_version(command: str = "poetry") -> str:
5✔
606
        pattern = r"(\d+\.\d+\.\d+)"
5✔
607
        text = capture_cmd_output(f"{command} --version")
5✔
608
        for expr in (
5✔
609
            rf"Poetry \(version {pattern}\)",
610
            rf"Poetry.*version.*{pattern}.*\)",
611
            rf"{pattern}",
612
        ):
613
            if m := re.search(expr, text):
5✔
614
                return m.group(1)
5✔
615
        return ""
×
616

617
    @staticmethod
5✔
618
    def work_dir(
5✔
619
        name: str, parent: Path, depth: int, be_file: bool = False
620
    ) -> Path | None:
621
        for _ in range(depth):
5✔
622
            if (f := parent.joinpath(name)).exists():
5✔
623
                if be_file:
5✔
624
                    return f
5✔
625
                return parent
5✔
626
            parent = parent.parent
5✔
627
        return None
5✔
628

629
    @classmethod
5✔
630
    def get_work_dir(
5✔
631
        cls: type[Self],
632
        name: str = TOML_FILE,
633
        cwd: Path | None = None,
634
        allow_cwd: bool = False,
635
        be_file: bool = False,
636
    ) -> Path:
637
        cwd = cwd or Path.cwd()
5✔
638
        if d := cls.work_dir(name, cwd, cls.path_depth, be_file):
5✔
639
            return d
5✔
640
        if allow_cwd:
5✔
641
            return cls.get_root_dir(cwd)
5✔
642
        raise EnvError(f"{name} not found! Make sure this is a python project.")
5✔
643

644
    @classmethod
5✔
645
    def load_toml_text(cls: type[Self], name: str = TOML_FILE) -> str:
5✔
646
        toml_file = cls.get_work_dir(name, be_file=True)
5✔
647
        return toml_file.read_text("utf8")
5✔
648

649
    @classmethod
5✔
650
    def manage_by_poetry(cls: type[Self], cache: bool = False) -> bool:
5✔
651
        return cls.get_manage_tool(cache=cache) == "poetry"
5✔
652

653
    @classmethod
5✔
654
    def get_manage_tool(cls: type[Self], cache: bool = False) -> ToolName | None:
5✔
655
        if cache and cls._tool:
5✔
656
            return cls._tool
5✔
657
        try:
5✔
658
            text = cls.load_toml_text()
5✔
659
        except EnvError:
5✔
660
            return None
5✔
661
        with contextlib.suppress(KeyError, tomllib.TOMLDecodeError):
5✔
662
            doc = tomllib.loads(text)
5✔
663
            backend = doc["build-system"]["build-backend"]
5✔
664
            if "poetry" in backend:
5✔
665
                cls._tool = "poetry"
5✔
666
                return cls._tool
5✔
667
            work_dir = cls.get_work_dir(allow_cwd=True)
5✔
668
            uv_lock_exists = Path(work_dir, "uv.lock").exists()
5✔
669
            if "pdm" in backend:
5✔
670
                cls._tool = "pdm"
5✔
671
                if not Path(work_dir, "pdm.lock").exists() and (
5✔
672
                    uv_lock_exists or "[tool.uv]" in text
673
                ):
674
                    cls._tool = "uv"
×
675
                return cls._tool
5✔
676
            elif uv_lock_exists:
×
677
                cls._tool = "uv"
×
UNCOV
678
                return cls._tool
×
679
        for name in get_args(ToolName):
5✔
680
            if f"[tool.{name}]" in text:
5✔
681
                cls._tool = cast(ToolName, name)
5✔
682
                return cls._tool
5✔
683
        # Poetry 2.0 default to not include the '[tool.poetry]' section
684
        if cls.is_poetry_v2(text):
5✔
685
            cls._tool = "poetry"
×
686
            return cls._tool
×
687
        return None
5✔
688

689
    @staticmethod
5✔
690
    def python_exec_dir() -> Path:
5✔
691
        return Path(sys.executable).parent
5✔
692

693
    @classmethod
5✔
694
    def get_root_dir(cls: type[Self], cwd: Path | None = None) -> Path:
5✔
695
        root = cwd or Path.cwd()
5✔
696
        venv_parent = cls.python_exec_dir().parent.parent
5✔
697
        if root.is_relative_to(venv_parent):
5✔
698
            root = venv_parent
5✔
699
        return root
5✔
700

701
    @classmethod
5✔
702
    def is_pdm_project(cls, strict: bool = True, cache: bool = False) -> bool:
5✔
703
        if cls.get_manage_tool(cache=cache) != "pdm":
5✔
704
            return False
5✔
705
        if strict:
×
706
            lock_file = cls.get_work_dir() / "pdm.lock"
×
707
            return lock_file.exists()
×
708
        return True
×
709

710
    @classmethod
5✔
711
    def get_sync_command(cls, prod: bool = True, doc: dict | None = None) -> str:
5✔
712
        if cls.is_pdm_project():
5✔
713
            return "pdm install --frozen" + " --prod" * prod
×
714
        elif cls.manage_by_poetry(cache=True):
5✔
715
            cmd = "poetry install"
5✔
716
            if prod:
5✔
717
                if doc is None:
5✔
718
                    doc = tomllib.loads(cls.load_toml_text())
5✔
719
                if doc.get("project", {}).get("dependencies") or any(
5✔
720
                    i != "python"
721
                    for i in doc.get("tool", {})
722
                    .get("poetry", {})
723
                    .get("dependencies", [])
724
                ):
725
                    cmd += " --only=main"
×
726
            return cmd
5✔
727
        elif cls.get_manage_tool(cache=True) == "uv":
×
728
            return "uv sync --inexact" + " --no-dev" * prod
×
729
        return ""
×
730

731
    @classmethod
5✔
732
    def sync_dependencies(cls, prod: bool = True) -> None:
5✔
733
        if cmd := cls.get_sync_command():
×
734
            run_and_echo(cmd)
×
735

736

737
class UpgradeDependencies(Project, DryRun):
5✔
738
    def __init__(
5✔
739
        self, _exit: bool = False, dry: bool = False, tool: ToolName = "poetry"
740
    ) -> None:
741
        super().__init__(_exit, dry)
5✔
742
        self._tool = tool
5✔
743

744
    class DevFlag(StrEnum):
5✔
745
        new = "[tool.poetry.group.dev.dependencies]"
5✔
746
        old = "[tool.poetry.dev-dependencies]"
5✔
747

748
    @staticmethod
5✔
749
    def parse_value(version_info: str, key: str) -> str:
5✔
750
        """Pick out the value for key in version info.
751

752
        Example::
753
            >>> s= 'typer = {extras = ["all"], version = "^0.9.0", optional = true}'
754
            >>> UpgradeDependencies.parse_value(s, 'extras')
755
            'all'
756
            >>> UpgradeDependencies.parse_value(s, 'optional')
757
            'true'
758
            >>> UpgradeDependencies.parse_value(s, 'version')
759
            '^0.9.0'
760
        """
761
        sep = key + " = "
5✔
762
        rest = version_info.split(sep, 1)[-1].strip(" =")
5✔
763
        if rest.startswith("["):
5✔
764
            rest = rest[1:].split("]")[0]
5✔
765
        elif rest.startswith('"'):
5✔
766
            rest = rest[1:].split('"')[0]
5✔
767
        else:
768
            rest = rest.split(",")[0].split("}")[0]
5✔
769
        return rest.strip().replace('"', "")
5✔
770

771
    @staticmethod
5✔
772
    def no_need_upgrade(version_info: str, line: str) -> bool:
5✔
773
        if (v := version_info.replace(" ", "")).startswith("{url="):
5✔
774
            echo(f"No need to upgrade for: {line}")
5✔
775
            return True
5✔
776
        if (f := "version=") in v:
5✔
777
            v = v.split(f)[1].strip('"').split('"')[0]
5✔
778
        if v == "*":
5✔
779
            echo(f"Skip wildcard line: {line}")
5✔
780
            return True
5✔
781
        elif v == "[":
5✔
782
            echo(f"Skip complex dependence: {line}")
5✔
783
            return True
5✔
784
        elif v.startswith(">") or v.startswith("<") or v[0].isdigit():
5✔
785
            echo(f"Ignore bigger/smaller/equal: {line}")
5✔
786
            return True
5✔
787
        return False
5✔
788

789
    @classmethod
5✔
790
    def build_args(
5✔
791
        cls: type[Self], package_lines: list[str]
792
    ) -> tuple[list[str], dict[str, list[str]]]:
793
        args: list[str] = []  # ['typer[all]', 'fastapi']
5✔
794
        specials: dict[str, list[str]] = {}  # {'--platform linux': ['gunicorn']}
5✔
795
        for no, line in enumerate(package_lines, 1):
5✔
796
            if (
5✔
797
                not (m := line.strip())
798
                or m.startswith("#")
799
                or m == "]"
800
                or (m.startswith("{") and m.strip(",").endswith("}"))
801
            ):
802
                continue
5✔
803
            try:
5✔
804
                package, version_info = m.split("=", 1)
5✔
805
            except ValueError as e:
5✔
806
                raise ParseError(f"Failed to separate by '='@line {no}: {m}") from e
5✔
807
            if (package := package.strip()).lower() == "python":
5✔
808
                continue
5✔
809
            if cls.no_need_upgrade(version_info := version_info.strip(' "'), line):
5✔
810
                continue
5✔
811
            if (extras_tip := "extras") in version_info:
5✔
812
                package += "[" + cls.parse_value(version_info, extras_tip) + "]"
5✔
813
            item = f'"{package}@latest"'
5✔
814
            key = None
5✔
815
            if (pf := "platform") in version_info:
5✔
816
                platform = cls.parse_value(version_info, pf)
5✔
817
                key = f"--{pf}={platform}"
5✔
818
            if (sc := "source") in version_info:
5✔
819
                source = cls.parse_value(version_info, sc)
5✔
820
                key = ("" if key is None else (key + " ")) + f"--{sc}={source}"
5✔
821
            if "optional = true" in version_info:
5✔
822
                key = ("" if key is None else (key + " ")) + "--optional"
5✔
823
            if key is not None:
5✔
824
                specials[key] = specials.get(key, []) + [item]
5✔
825
            else:
826
                args.append(item)
5✔
827
        return args, specials
5✔
828

829
    @classmethod
5✔
830
    def should_with_dev(cls: type[Self]) -> bool:
5✔
831
        text = cls.load_toml_text()
5✔
832
        return cls.DevFlag.new in text or cls.DevFlag.old in text
5✔
833

834
    @staticmethod
5✔
835
    def parse_item(toml_str: str) -> list[str]:
5✔
836
        lines: list[str] = []
5✔
837
        for line in toml_str.splitlines():
5✔
838
            if (line := line.strip()).startswith("["):
5✔
839
                if lines:
5✔
840
                    break
5✔
841
            elif line:
5✔
842
                lines.append(line)
5✔
843
        return lines
5✔
844

845
    @classmethod
5✔
846
    def get_args(
5✔
847
        cls: type[Self], toml_text: str | None = None
848
    ) -> tuple[list[str], list[str], list[list[str]], str]:
849
        if toml_text is None:
5✔
850
            toml_text = cls.load_toml_text()
5✔
851
        main_title = "[tool.poetry.dependencies]"
5✔
852
        if (no_main_deps := main_title not in toml_text) and not cls.is_poetry_v2(
5✔
853
            toml_text
854
        ):
855
            raise EnvError(
5✔
856
                f"{main_title} not found! Make sure this is a poetry project."
857
            )
858
        text = toml_text.split(main_title)[-1]
5✔
859
        dev_flag = "--group dev"
5✔
860
        new_flag, old_flag = cls.DevFlag.new, cls.DevFlag.old
5✔
861
        if (dev_title := getattr(new_flag, "value", new_flag)) not in text:
5✔
862
            dev_title = getattr(old_flag, "value", old_flag)  # For poetry<=1.2
5✔
863
            dev_flag = "--dev"
5✔
864
        others: list[list[str]] = []
5✔
865
        try:
5✔
866
            main_toml, dev_toml = text.split(dev_title)
5✔
867
        except ValueError:
5✔
868
            dev_toml = ""
5✔
869
            main_toml = text
5✔
870
        mains = [] if no_main_deps else cls.parse_item(main_toml)
5✔
871
        devs = cls.parse_item(dev_toml)
5✔
872
        prod_packs, specials = cls.build_args(mains)
5✔
873
        if specials:
5✔
874
            others.extend([[k] + v for k, v in specials.items()])
5✔
875
        dev_packs, specials = cls.build_args(devs)
5✔
876
        if specials:
5✔
877
            others.extend([[k] + v + [dev_flag] for k, v in specials.items()])
5✔
878
        return prod_packs, dev_packs, others, dev_flag
5✔
879

880
    @classmethod
5✔
881
    def gen_cmd(cls: type[Self]) -> str:
5✔
882
        main_args, dev_args, others, dev_flags = cls.get_args()
5✔
883
        return cls.to_cmd(main_args, dev_args, others, dev_flags)
5✔
884

885
    @staticmethod
5✔
886
    def to_cmd(
5✔
887
        main_args: list[str],
888
        dev_args: list[str],
889
        others: list[list[str]],
890
        dev_flags: str,
891
    ) -> str:
892
        command = "poetry add "
5✔
893
        _upgrade = ""
5✔
894
        if main_args:
5✔
895
            _upgrade = command + " ".join(main_args)
5✔
896
        if dev_args:
5✔
897
            if _upgrade:
5✔
898
                _upgrade += " && "
5✔
899
            _upgrade += command + dev_flags + " " + " ".join(dev_args)
5✔
900
        for single in others:
5✔
901
            _upgrade += f" && poetry add {' '.join(single)}"
5✔
902
        return _upgrade
5✔
903

904
    def gen(self) -> str:
5✔
905
        if self._tool == "uv":
5✔
906
            up = "uv lock --upgrade --verbose"
5✔
907
            deps = "uv sync --inexact --frozen --all-groups --all-extras"
5✔
908
            return f"{up} && {deps}"
5✔
909
        elif self._tool == "pdm":
5✔
910
            return "pdm update --verbose && pdm install -G :all --frozen"
5✔
911
        return self.gen_cmd() + " && poetry lock && poetry update"
5✔
912

913

914
@cli.command()
5✔
915
def upgrade(
5✔
916
    tool: str = ToolOption,
917
    dry: bool = DryOption,
918
) -> None:
919
    """Upgrade dependencies in pyproject.toml to latest versions"""
920
    if not (tool := _ensure_str(tool)) or tool == ToolOption.default:
5✔
921
        tool = Project.get_manage_tool() or "uv"
5✔
922
    if tool in get_args(ToolName):
5✔
923
        UpgradeDependencies(dry=dry, tool=cast(ToolName, tool)).run()
5✔
924
    else:
925
        secho(f"Unknown tool {tool!r}", fg=typer.colors.YELLOW)
5✔
926
        raise typer.Exit(1)
5✔
927

928

929
class GitTag(DryRun):
5✔
930
    def __init__(self, message: str, dry: bool, no_sync: bool = False) -> None:
5✔
931
        self.message = message
5✔
932
        self._no_sync = no_sync
5✔
933
        super().__init__(dry=dry)
5✔
934

935
    @staticmethod
5✔
936
    def has_v_prefix() -> bool:
5✔
937
        return "v" in capture_cmd_output("git tag")
5✔
938

939
    def should_push(self) -> bool:
5✔
940
        return "git push" in self.git_status
5✔
941

942
    def gen(self) -> str:
5✔
943
        should_sync, _version = get_current_version(verbose=False, check_version=True)
5✔
944
        if self.has_v_prefix():
5✔
945
            # Add `v` at prefix to compare with bumpversion tool
946
            _version = "v" + _version
5✔
947
        cmd = f"git tag -a {_version} -m {self.message!r} && git push --tags"
5✔
948
        if self.should_push():
5✔
949
            cmd += " && git push"
5✔
950
        if should_sync and not self._no_sync and (sync := Project.get_sync_command()):
5✔
951
            cmd = f"{sync} && " + cmd
×
952
        return cmd
5✔
953

954
    @cached_property
5✔
955
    def git_status(self) -> str:
5✔
956
        return capture_cmd_output("git status")
5✔
957

958
    def mark_tag(self) -> bool:
5✔
959
        if not re.search(r"working (tree|directory) clean", self.git_status) and (
5✔
960
            "无文件要提交,干净的工作区" not in self.git_status
961
        ):
962
            run_and_echo("git status")
5✔
963
            echo("ERROR: Please run git commit to make sure working tree is clean!")
5✔
964
            return False
5✔
965
        return bool(super().run())
5✔
966

967
    def run(self) -> None:
5✔
968
        if self.mark_tag() and not self.dry:
5✔
969
            echo("You may want to publish package:\n poetry publish --build")
5✔
970

971

972
@cli.command()
5✔
973
def tag(
5✔
974
    message: str = Option("", "-m", "--message"),
975
    no_sync: bool = Option(
976
        False, "--no-sync", help="Do not run sync command to update version"
977
    ),
978
    dry: bool = DryOption,
979
) -> None:
980
    """Run shell command: git tag -a <current-version-in-pyproject.toml> -m {message}"""
981
    GitTag(message, dry=dry, no_sync=_ensure_bool(no_sync)).run()
5✔
982

983

984
class LintCode(DryRun):
5✔
985
    def __init__(
5✔
986
        self,
987
        args: list[str] | str | None,
988
        check_only: bool = False,
989
        _exit: bool = False,
990
        dry: bool = False,
991
        bandit: bool = False,
992
        skip_mypy: bool = False,
993
        dmypy: bool = False,
994
        tool: str = ToolOption.default,
995
        prefix: bool = False,
996
    ) -> None:
997
        self.args = args
5✔
998
        self.check_only = check_only
5✔
999
        self._bandit = bandit
5✔
1000
        self._skip_mypy = skip_mypy
5✔
1001
        self._use_dmypy = dmypy
5✔
1002
        self._tool = tool
5✔
1003
        self._prefix = prefix
5✔
1004
        super().__init__(_exit, dry)
5✔
1005

1006
    @staticmethod
5✔
1007
    def check_lint_tool_installed() -> bool:
5✔
1008
        try:
5✔
1009
            return check_call("ruff --version")
5✔
1010
        except FileNotFoundError:
×
1011
            # Windows may raise FileNotFoundError when ruff not installed
1012
            return False
×
1013

1014
    @staticmethod
5✔
1015
    def missing_mypy_exec() -> bool:
5✔
1016
        return shutil.which("mypy") is None
5✔
1017

1018
    @staticmethod
5✔
1019
    def prefer_dmypy(paths: str, tools: list[str], use_dmypy: bool = False) -> bool:
5✔
1020
        return (
5✔
1021
            paths == "."
1022
            and any(t.startswith("mypy") for t in tools)
1023
            and (use_dmypy or load_bool("FASTDEVCLI_DMYPY"))
1024
        )
1025

1026
    @staticmethod
5✔
1027
    def get_package_name() -> str:
5✔
1028
        root = Project.get_work_dir(allow_cwd=True)
5✔
1029
        module_name = root.name.replace("-", "_").replace(" ", "_")
5✔
1030
        package_maybe = (module_name, "src")
5✔
1031
        for name in package_maybe:
5✔
1032
            if root.joinpath(name).is_dir():
5✔
1033
                return name
5✔
1034
        return "."
5✔
1035

1036
    @classmethod
5✔
1037
    def to_cmd(
5✔
1038
        cls: type[Self],
1039
        paths: str = ".",
1040
        check_only: bool = False,
1041
        bandit: bool = False,
1042
        skip_mypy: bool = False,
1043
        use_dmypy: bool = False,
1044
        tool: str = ToolOption.default,
1045
        with_prefix: bool = False,
1046
    ) -> str:
1047
        if paths != "." and all(i.endswith(".html") for i in paths.split()):
5✔
1048
            return f"prettier -w {paths}"
5✔
1049
        cmd = ""
5✔
1050
        tools = ["ruff format", "ruff check --extend-select=I,B,SIM --fix", "mypy"]
5✔
1051
        if check_only:
5✔
1052
            tools[0] += " --check"
5✔
1053
        if check_only or load_bool("NO_FIX"):
5✔
1054
            tools[1] = tools[1].replace(" --fix", "")
5✔
1055
        if skip_mypy or load_bool("SKIP_MYPY") or load_bool("FASTDEVCLI_NO_MYPY"):
5✔
1056
            # Sometimes mypy is too slow
1057
            tools = tools[:-1]
5✔
1058
        elif load_bool("IGNORE_MISSING_IMPORTS"):
5✔
1059
            tools[-1] += " --ignore-missing-imports"
5✔
1060
        lint_them = " && ".join(
5✔
1061
            "{0}{" + str(i) + "} {1}" for i in range(2, len(tools) + 2)
1062
        )
1063
        if ruff_exists := cls.check_lint_tool_installed():
5✔
1064
            # `ruff <command>` get the same result with `pdm run ruff <command>`
1065
            # While `mypy .`(installed global and env not activated),
1066
            #   does not the same as `pdm run mypy .`
1067
            lint_them = " && ".join(
5✔
1068
                ("" if tool.startswith("ruff") else "{0}")
1069
                + (
1070
                    "{%d} {1}" % i  # noqa: UP031
1071
                )
1072
                for i, tool in enumerate(tools, 2)
1073
            )
1074
        prefix = ""
5✔
1075
        should_run_by_tool = with_prefix
5✔
1076
        if not should_run_by_tool:
5✔
1077
            if is_venv() and Path(sys.argv[0]).parent != Path.home().joinpath(
5✔
1078
                ".local/bin"
1079
            ):  # Virtual environment activated and fast-dev-cli is installed in it
1080
                if not ruff_exists:
5✔
1081
                    should_run_by_tool = True
5✔
1082
                    command = "pipx install ruff"
5✔
1083
                    if shutil.which("pipx") is None:
5✔
1084
                        ensure_pipx = "pip install --user pipx\n  pipx ensurepath\n  "
×
1085
                        command = ensure_pipx + command
×
1086
                    yellow_warn(
5✔
1087
                        "You may need to run the following command"
1088
                        f" to install ruff:\n\n  {command}\n"
1089
                    )
1090
                elif "mypy" in str(tools) and cls.missing_mypy_exec():
5✔
1091
                    should_run_by_tool = True
5✔
1092
                    if check_call('python -c "import fast_dev_cli"'):
5✔
1093
                        command = 'python -m pip install -U "fast-dev-cli"'
5✔
1094
                        yellow_warn(
5✔
1095
                            "You may need to run the following command"
1096
                            f" to install lint tools:\n\n  {command}\n"
1097
                        )
1098
            elif tool == ToolOption.default:
×
1099
                root = Project.get_work_dir(allow_cwd=True)
×
1100
                if py := shutil.which("python"):
×
1101
                    try:
×
1102
                        Path(py).relative_to(root)
×
1103
                    except ValueError:
×
1104
                        # Virtual environment not activated
1105
                        should_run_by_tool = True
×
1106
            else:
1107
                should_run_by_tool = True
×
1108
        if should_run_by_tool and tool:
5✔
1109
            if tool == ToolOption.default:
5✔
1110
                tool = Project.get_manage_tool() or ""
5✔
1111
            if tool:
5✔
1112
                prefix = tool + " run "
5✔
1113
                if tool == "uv":
5✔
1114
                    if is_windows():
×
1115
                        prefix += "--no-sync "
×
1116
                    elif Path(bin_dir := ".venv/bin/").exists():
×
1117
                        prefix = bin_dir
×
1118
        if cls.prefer_dmypy(paths, tools, use_dmypy=use_dmypy):
5✔
1119
            tools[-1] = "dmypy run"
5✔
1120
        cmd += lint_them.format(prefix, paths, *tools)
5✔
1121
        if bandit or load_bool("FASTDEVCLI_BANDIT"):
5✔
1122
            command = prefix + "bandit"
5✔
1123
            if Path("pyproject.toml").exists():
5✔
1124
                toml_text = Project.load_toml_text()
5✔
1125
                if "[tool.bandit" in toml_text:
5✔
1126
                    command += " -c pyproject.toml"
5✔
1127
            if paths == "." and " -c " not in command:
5✔
1128
                paths = cls.get_package_name()
5✔
1129
            command += f" -r {paths}"
5✔
1130
            cmd += " && " + command
5✔
1131
        return cmd
5✔
1132

1133
    def gen(self) -> str:
5✔
1134
        paths = "."
5✔
1135
        if args := self.args:
5✔
1136
            ps = args.split() if isinstance(args, str) else [str(i) for i in args]
5✔
1137
            if len(ps) == 1:
5✔
1138
                paths = ps[0]
5✔
1139
                if (
5✔
1140
                    paths != "."
1141
                    # `Path("a.").suffix` got "." in py3.14 and got "" with py<3.14
1142
                    and (p := Path(paths)).suffix in ("", ".")
1143
                    and not p.exists()
1144
                ):
1145
                    # e.g.:
1146
                    # stem -> stem.py
1147
                    # me. -> me.py
1148
                    if paths.endswith("."):
×
1149
                        p = p.with_name(paths[:-1])
×
1150
                    for suffix in (".py", ".html"):
×
1151
                        p = p.with_suffix(suffix)
×
1152
                        if p.exists():
×
1153
                            paths = p.name
×
1154
                            break
×
1155
            else:
1156
                paths = " ".join(ps)
×
1157
        return self.to_cmd(
5✔
1158
            paths,
1159
            self.check_only,
1160
            self._bandit,
1161
            self._skip_mypy,
1162
            self._use_dmypy,
1163
            tool=self._tool,
1164
            with_prefix=self._prefix,
1165
        )
1166

1167

1168
def parse_files(args: list[str] | tuple[str, ...]) -> list[str]:
5✔
1169
    return [i for i in args if not i.startswith("-")]
5✔
1170

1171

1172
def lint(
5✔
1173
    files: list[str] | str | None = None,
1174
    dry: bool = False,
1175
    bandit: bool = False,
1176
    skip_mypy: bool = False,
1177
    dmypy: bool = False,
1178
    tool: str = ToolOption.default,
1179
    prefix: bool = False,
1180
) -> None:
1181
    if files is None:
5✔
1182
        files = parse_files(sys.argv[1:])
5✔
1183
    if files and files[0] == "lint":
5✔
1184
        files = files[1:]
5✔
1185
    LintCode(
5✔
1186
        files,
1187
        dry=dry,
1188
        skip_mypy=skip_mypy,
1189
        bandit=bandit,
1190
        dmypy=dmypy,
1191
        tool=tool,
1192
        prefix=prefix,
1193
    ).run()
1194

1195

1196
def check(
5✔
1197
    files: list[str] | str | None = None,
1198
    dry: bool = False,
1199
    bandit: bool = False,
1200
    skip_mypy: bool = False,
1201
    dmypy: bool = False,
1202
    tool: str = ToolOption.default,
1203
) -> None:
1204
    LintCode(
5✔
1205
        files,
1206
        check_only=True,
1207
        _exit=True,
1208
        dry=dry,
1209
        bandit=bandit,
1210
        skip_mypy=skip_mypy,
1211
        dmypy=dmypy,
1212
        tool=tool,
1213
    ).run()
1214

1215

1216
@cli.command(name="lint")
5✔
1217
def make_style(
5✔
1218
    files: Optional[list[str]] = typer.Argument(default=None),  # noqa:B008
1219
    check_only: bool = Option(False, "--check-only", "-c"),
1220
    bandit: bool = Option(False, "--bandit", help="Run `bandit -r <package_dir>`"),
1221
    prefix: bool = Option(
1222
        False,
1223
        "--prefix",
1224
        help="Run lint command with tool prefix, e.g.: pdm run ruff ...",
1225
    ),
1226
    skip_mypy: bool = Option(False, "--skip-mypy"),
1227
    use_dmypy: bool = Option(
1228
        False, "--dmypy", help="Use `dmypy run` instead of `mypy`"
1229
    ),
1230
    tool: str = ToolOption,
1231
    dry: bool = DryOption,
1232
) -> None:
1233
    """Run: ruff check/format to reformat code and then mypy to check"""
1234
    if getattr(files, "default", files) is None:
5✔
1235
        files = ["."]
5✔
1236
    elif isinstance(files, str):
5✔
1237
        files = [files]
5✔
1238
    skip = _ensure_bool(skip_mypy)
5✔
1239
    dmypy = _ensure_bool(use_dmypy)
5✔
1240
    bandit = _ensure_bool(bandit)
5✔
1241
    prefix = _ensure_bool(prefix)
5✔
1242
    tool = _ensure_str(tool)
5✔
1243
    kwargs = {"dry": dry, "skip_mypy": skip, "dmypy": dmypy, "bandit": bandit}
5✔
1244
    if _ensure_bool(check_only):
5✔
1245
        check(files, tool=tool, **kwargs)
5✔
1246
    else:
1247
        lint(files, prefix=prefix, tool=tool, **kwargs)
5✔
1248

1249

1250
@cli.command(name="check")
5✔
1251
def only_check(
5✔
1252
    bandit: bool = Option(False, "--bandit", help="Run `bandit -r <package_dir>`"),
1253
    skip_mypy: bool = Option(False, "--skip-mypy"),
1254
    dry: bool = DryOption,
1255
) -> None:
1256
    """Check code style without reformat"""
1257
    check(dry=dry, bandit=bandit, skip_mypy=_ensure_bool(skip_mypy))
5✔
1258

1259

1260
class Sync(DryRun):
5✔
1261
    def __init__(
5✔
1262
        self, filename: str, extras: str, save: bool, dry: bool = False
1263
    ) -> None:
1264
        self.filename = filename
5✔
1265
        self.extras = extras
5✔
1266
        self._save = save
5✔
1267
        super().__init__(dry=dry)
5✔
1268

1269
    def gen(self) -> str:
5✔
1270
        extras, save = self.extras, self._save
5✔
1271
        should_remove = not Path.cwd().joinpath(self.filename).exists()
5✔
1272
        if not (tool := Project.get_manage_tool()):
5✔
1273
            if should_remove or not is_venv():
5✔
1274
                raise EnvError("There project is not managed by uv/pdm/poetry!")
5✔
1275
            return f"python -m pip install -r {self.filename}"
5✔
1276
        prefix = "" if is_venv() else f"{tool} run "
5✔
1277
        ensure_pip = " {1}python -m ensurepip && {1}python -m pip install -U pip &&"
5✔
1278
        export_cmd = "uv export --no-hashes --all-extras --frozen"
5✔
1279
        if tool in ("poetry", "pdm"):
5✔
1280
            export_cmd = f"{tool} export --without-hashes --with=dev"
5✔
1281
            if tool == "poetry":
5✔
1282
                ensure_pip = ""
5✔
1283
                if not UpgradeDependencies.should_with_dev():
5✔
1284
                    export_cmd = export_cmd.replace(" --with=dev", "")
5✔
1285
                if extras and isinstance(extras, str | list):
5✔
1286
                    export_cmd += f" --{extras=}".replace("'", '"')
5✔
1287
            elif check_call(prefix + "python -m pip --version"):
5✔
1288
                ensure_pip = ""
5✔
1289
        elif check_call(prefix + "python -m pip --version"):
5✔
1290
            ensure_pip = ""
5✔
1291
        install_cmd = (
5✔
1292
            f"{{2}} -o {{0}} &&{ensure_pip} {{1}}python -m pip install -r {{0}}"
1293
        )
1294
        if should_remove and not save:
5✔
1295
            install_cmd += " && rm -f {0}"
5✔
1296
        return install_cmd.format(self.filename, prefix, export_cmd)
5✔
1297

1298

1299
@cli.command()
5✔
1300
def sync(
5✔
1301
    filename: str = "dev_requirements.txt",
1302
    extras: str = Option("", "--extras", "-E"),
1303
    save: bool = Option(
1304
        False, "--save", "-s", help="Whether save the requirement file"
1305
    ),
1306
    dry: bool = DryOption,
1307
) -> None:
1308
    """Export dependencies by poetry to a txt file then install by pip."""
1309
    Sync(filename, extras, save, dry=dry).run()
5✔
1310

1311

1312
def _should_run_test_script(path: Path = Path("scripts")) -> Path | None:
5✔
1313
    for name in ("test.sh", "test.py"):
5✔
1314
        if (file := path / name).exists():
5✔
1315
            return file
5✔
1316
    return None
5✔
1317

1318

1319
def test(dry: bool, ignore_script: bool = False) -> None:
5✔
1320
    cwd = Path.cwd()
5✔
1321
    root = Project.get_work_dir(cwd=cwd, allow_cwd=True)
5✔
1322
    script_dir = root / "scripts"
5✔
1323
    if not _ensure_bool(ignore_script) and (
5✔
1324
        test_script := _should_run_test_script(script_dir)
1325
    ):
1326
        cmd = test_script.relative_to(root).as_posix()
5✔
1327
        if test_script.suffix == ".py":
5✔
1328
            cmd = "python " + cmd
5✔
1329
        if cwd != root:
5✔
1330
            cmd = f"cd {root} && " + cmd
5✔
1331
    else:
1332
        cmd = 'coverage run -m pytest -s && coverage report --omit="tests/*" -m'
5✔
1333
        if not is_venv() or not check_call("coverage --version"):
5✔
1334
            sep = " && "
5✔
1335
            prefix = f"{tool} run " if (tool := Project.get_manage_tool()) else ""
5✔
1336
            cmd = sep.join(prefix + i for i in cmd.split(sep))
5✔
1337
    exit_if_run_failed(cmd, dry=dry)
5✔
1338

1339

1340
@cli.command(name="test")
5✔
1341
def coverage_test(
5✔
1342
    dry: bool = DryOption,
1343
    ignore_script: bool = Option(False, "--ignore-script", "-i"),
1344
) -> None:
1345
    """Run unittest by pytest and report coverage"""
1346
    return test(dry, ignore_script)
5✔
1347

1348

1349
class Publish:
5✔
1350
    class CommandEnum(StrEnum):
5✔
1351
        poetry = "poetry publish --build"
5✔
1352
        pdm = "pdm publish"
5✔
1353
        uv = "uv build && uv publish"
5✔
1354
        twine = "python -m build && twine upload"
5✔
1355

1356
    @classmethod
5✔
1357
    def gen(cls) -> str:
5✔
1358
        if tool := Project.get_manage_tool():
5✔
1359
            return cls.CommandEnum[tool]
5✔
1360
        return cls.CommandEnum.twine
5✔
1361

1362

1363
@cli.command()
5✔
1364
def upload(
5✔
1365
    dry: bool = DryOption,
1366
) -> None:
1367
    """Shortcut for package publish"""
1368
    cmd = Publish.gen()
5✔
1369
    exit_if_run_failed(cmd, dry=dry)
5✔
1370

1371

1372
def dev(
5✔
1373
    port: int | None | OptionInfo,
1374
    host: str | None | OptionInfo,
1375
    file: str | None | ArgumentInfo = None,
1376
    dry: bool = False,
1377
) -> None:
1378
    cmd = "fastapi dev"
5✔
1379
    no_port_yet = True
5✔
1380
    if file is not None:
5✔
1381
        try:
5✔
1382
            port = int(str(file))
5✔
1383
        except ValueError:
5✔
1384
            cmd += f" {file}"
5✔
1385
        else:
1386
            if port != 8000:
5✔
1387
                cmd += f" --port={port}"
5✔
1388
                no_port_yet = False
5✔
1389
    if no_port_yet and (port := getattr(port, "default", port)) and str(port) != "8000":
5✔
1390
        cmd += f" --port={port}"
5✔
1391
    if (host := getattr(host, "default", host)) and host not in (
5✔
1392
        "localhost",
1393
        "127.0.0.1",
1394
    ):
1395
        cmd += f" --host={host}"
5✔
1396
    exit_if_run_failed(cmd, dry=dry)
5✔
1397

1398

1399
@cli.command(name="dev")
5✔
1400
def runserver(
5✔
1401
    file_or_port: Optional[str] = typer.Argument(default=None),
1402
    port: Optional[int] = Option(None, "-p", "--port"),
1403
    host: Optional[str] = Option(None, "-h", "--host"),
1404
    dry: bool = DryOption,
1405
) -> None:
1406
    """Start a fastapi server(only for fastapi>=0.111.0)"""
1407
    if getattr(file_or_port, "default", file_or_port):
5✔
1408
        dev(port, host, file=file_or_port, dry=dry)
5✔
1409
    else:
1410
        dev(port, host, dry=dry)
5✔
1411

1412

1413
@cli.command(name="exec")
5✔
1414
def run_by_subprocess(cmd: str, dry: bool = DryOption) -> None:
5✔
1415
    """Run cmd by subprocess, auto set shell=True when cmd contains '|>'"""
1416
    try:
5✔
1417
        rc = run_and_echo(cmd, verbose=True, dry=_ensure_bool(dry))
5✔
1418
    except FileNotFoundError as e:
5✔
1419
        command = cmd.split()[0]
5✔
1420
        if e.filename == command or (
5✔
1421
            e.filename is None and "系统找不到指定的文件" in str(e)
1422
        ):
1423
            echo(f"Command not found: {command}")
5✔
1424
            raise Exit(1) from None
5✔
UNCOV
1425
        raise e
×
1426
    else:
1427
        if rc:
5✔
1428
            raise Exit(rc)
5✔
1429

1430

1431
class MakeDeps(DryRun):
5✔
1432
    def __init__(
5✔
1433
        self,
1434
        tool: str,
1435
        prod: bool = False,
1436
        dry: bool = False,
1437
        active: bool = True,
1438
        inexact: bool = True,
1439
    ) -> None:
1440
        self._tool = tool
5✔
1441
        self._prod = prod
5✔
1442
        self._active = active
5✔
1443
        self._inexact = inexact
5✔
1444
        super().__init__(dry=dry)
5✔
1445

1446
    def should_ensure_pip(self) -> bool:
5✔
1447
        return True
5✔
1448

1449
    def should_upgrade_pip(self) -> bool:
5✔
1450
        return True
×
1451

1452
    def get_groups(self) -> list[str]:
5✔
1453
        if self._prod:
5✔
1454
            return []
5✔
1455
        return ["dev"]
5✔
1456

1457
    def gen(self) -> str:
5✔
1458
        if self._tool == "pdm":
5✔
1459
            return "pdm install --frozen " + ("--prod" if self._prod else "-G :all")
5✔
1460
        elif self._tool == "uv":
5✔
1461
            uv_sync = "uv sync" + " --inexact" * self._inexact
5✔
1462
            if self._active:
5✔
1463
                uv_sync += " --active"
5✔
1464
            return uv_sync + ("" if self._prod else " --all-extras --all-groups")
5✔
1465
        elif self._tool == "poetry":
5✔
1466
            return "poetry install " + (
5✔
1467
                "--only=main" if self._prod else "--all-extras --all-groups"
1468
            )
1469
        else:
1470
            cmd = "python -m pip install -e ."
5✔
1471
            if gs := self.get_groups():
5✔
1472
                cmd += " " + " ".join(f"--group {g}" for g in gs)
5✔
1473
            upgrade = "python -m pip install --upgrade pip"
5✔
1474
            if self.should_ensure_pip():
5✔
1475
                cmd = f"python -m ensurepip && {upgrade} && {cmd}"
5✔
1476
            elif self.should_upgrade_pip():
×
1477
                cmd = "{upgrade} && {cmd}"
×
1478
            return cmd
5✔
1479

1480

1481
@cli.command(name="deps")
5✔
1482
def make_deps(
5✔
1483
    prod: bool = Option(
1484
        False,
1485
        "--prod",
1486
        help="Only instead production dependencies.",
1487
    ),
1488
    tool: str = ToolOption,
1489
    use_uv: bool = Option(False, "--uv", help="Use `uv` to install deps"),
1490
    use_pdm: bool = Option(False, "--pdm", help="Use `pdm` to install deps"),
1491
    use_pip: bool = Option(False, "--pip", help="Use `pip` to install deps"),
1492
    use_poetry: bool = Option(False, "--poetry", help="Use `poetry` to install deps"),
1493
    active: bool = Option(
1494
        True, help="Add `--active` to uv sync command(Only work for uv project)"
1495
    ),
1496
    inexact: bool = Option(
1497
        True, help="Add `--inexact` to uv sync command(Only work for uv project)"
1498
    ),
1499
    dry: bool = DryOption,
1500
) -> None:
1501
    """Run: ruff check/format to reformat code and then mypy to check"""
1502
    if use_uv + use_pdm + use_pip + use_poetry > 1:
×
1503
        raise UsageError("`--uv/--pdm/--pip/--poetry` can only choose one!")
×
1504
    if use_uv:
×
1505
        tool = "uv"
×
1506
    elif use_pdm:
×
1507
        tool = "pdm"
×
1508
    elif use_pip:
×
1509
        tool = "pip"
×
1510
    elif use_poetry:
×
1511
        tool = "poetry"
×
1512
    elif tool == ToolOption.default:
×
1513
        tool = Project.get_manage_tool(cache=True) or "pip"
×
1514
    MakeDeps(tool, prod, active=active, inexact=inexact, dry=dry).run()
×
1515

1516

1517
class UvPypi(DryRun):
5✔
1518
    PYPI = "https://pypi.org/simple"
5✔
1519
    HOST = "https://files.pythonhosted.org"
5✔
1520

1521
    def __init__(self, lock_file: Path, dry: bool, verbose: bool, quiet: bool) -> None:
5✔
1522
        super().__init__(dry=dry)
5✔
1523
        self.lock_file = lock_file
5✔
1524
        self._verbose = _ensure_bool(verbose)
5✔
1525
        self._quiet = _ensure_bool(quiet)
5✔
1526

1527
    def run(self) -> None:
5✔
1528
        try:
5✔
1529
            rc = self.update_lock(self.lock_file, self._verbose, self._quiet)
5✔
1530
        except ValueError as e:
×
1531
            secho(str(e), fg=typer.colors.RED)
×
1532
            raise Exit(1) from e
×
1533
        else:
1534
            if rc != 0:
5✔
1535
                raise Exit(rc)
5✔
1536

1537
    @classmethod
5✔
1538
    def update_lock(cls, p: Path, verbose: bool, quiet: bool) -> int:
5✔
1539
        text = p.read_text("utf-8")
5✔
1540
        registry_pattern = r'(registry = ")(.*?)"'
5✔
1541
        replace_registry = functools.partial(
5✔
1542
            re.sub, registry_pattern, rf'\1{cls.PYPI}"'
1543
        )
1544
        registry_urls = {i[1] for i in re.findall(registry_pattern, text)}
5✔
1545
        download_pattern = r'(url = ")(https?://.*?)(/packages/.*?\.)(gz|whl)"'
5✔
1546
        replace_host = functools.partial(
5✔
1547
            re.sub, download_pattern, rf'\1{cls.HOST}\3\4"'
1548
        )
1549
        download_hosts = {i[1] for i in re.findall(download_pattern, text)}
5✔
1550
        if not registry_urls:
5✔
1551
            raise ValueError(f"Failed to find pattern {registry_pattern!r} in {p}")
×
1552
        if len(registry_urls) == 1:
5✔
1553
            current_registry = registry_urls.pop()
5✔
1554
            if current_registry == cls.PYPI:
5✔
1555
                if download_hosts == {cls.HOST}:
5✔
1556
                    if verbose:
5✔
1557
                        echo(f"Registry of {p} is {cls.PYPI}, no need to change.")
×
1558
                    return 0
5✔
1559
            else:
1560
                text = replace_registry(text)
5✔
1561
                if verbose:
5✔
1562
                    echo(f"{current_registry} --> {cls.PYPI}")
×
1563
        else:
1564
            # TODO: ask each one to confirm replace
1565
            text = replace_registry(text)
×
1566
            if verbose:
×
1567
                for current_registry in sorted(registry_urls):
×
1568
                    echo(f"{current_registry} --> {cls.PYPI}")
×
1569
        if len(download_hosts) == 1:
5✔
1570
            current_host = download_hosts.pop()
5✔
1571
            if current_host != cls.HOST:
5✔
1572
                text = replace_host(text)
5✔
1573
                if verbose:
5✔
1574
                    print(current_host, "-->", cls.HOST)
×
1575
        elif download_hosts:
×
1576
            # TODO: ask each one to confirm replace
1577
            text = replace_host(text)
×
1578
            if verbose:
×
1579
                for current_host in sorted(download_hosts):
×
1580
                    echo(f"{current_host} --> {cls.HOST}")
×
1581
        size = p.write_text(text, encoding="utf-8")
5✔
1582
        if verbose:
5✔
1583
            echo(f"Updated {p} with {size} bytes.")
×
1584
        if quiet:
5✔
1585
            return 0
5✔
1586
        return 1
5✔
1587

1588

1589
@cli.command()
5✔
1590
def pypi(
5✔
1591
    file: Optional[str] = typer.Argument(default=None),
1592
    dry: bool = DryOption,
1593
    verbose: bool = False,
1594
    quiet: bool = False,
1595
) -> None:
1596
    """Change registry of uv.lock to be pypi.org"""
1597
    if not (p := Path(_ensure_str(file) or "uv.lock")).exists() and not (
5✔
1598
        (p := Project.get_work_dir() / p.name).exists()
1599
    ):
1600
        yellow_warn(f"{p.name!r} not found!")
5✔
1601
        return
5✔
1602
    UvPypi(p, dry, verbose, quiet).run()
5✔
1603

1604

1605
def version_callback(value: bool) -> None:
5✔
1606
    if value:
5✔
1607
        echo("Fast Dev Cli Version: " + typer.style(__version__, bold=True))
5✔
1608
        raise Exit()
5✔
1609

1610

1611
@cli.callback()
1612
def common(
1613
    version: bool = Option(
1614
        None,
1615
        "--version",
1616
        "-V",
1617
        callback=version_callback,
1618
        is_eager=True,
1619
        help="Show the version of this tool",
1620
    ),
1621
) -> None: ...
1622

1623

1624
def main() -> None:
5✔
1625
    cli()
5✔
1626

1627

1628
if __name__ == "__main__":  # pragma: no cover
1629
    main()
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc