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

waketzheng / fast-dev-cli / 17542515724

08 Sep 2025 04:30AM UTC coverage: 91.489% (-0.1%) from 91.604%
17542515724

push

github

waketzheng
Fixing test error

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

48 existing lines in 1 file now uncovered.

860 of 940 relevant lines covered (91.49%)

5.48 hits per line

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

91.48
/fast_dev_cli/cli.py
1
from __future__ import annotations
6✔
2

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

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

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

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

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

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

44
    import tomli as tomllib
45

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

49

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

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

64

65
class FastDevCliError(Exception): ...
6✔
66

67

68
class ShellCommandError(FastDevCliError): ...
6✔
69

70

71
def poetry_module_name(name: str) -> str:
6✔
72
    """Get module name that generated by `poetry new`"""
73
    try:
6✔
74
        from packaging.utils import canonicalize_name
6✔
UNCOV
75
    except ImportError:
×
76

77
        def canonicalize_name(s: str) -> str:  # type:ignore[misc]
×
UNCOV
78
            return re.sub(r"[-_.]+", "-", s)
×
79

80
    return canonicalize_name(name).replace("-", "_").replace(" ", "_")
6✔
81

82

83
def is_emoji(char: str) -> bool:
6✔
84
    try:
6✔
85
        import emoji
6✔
86
    except ImportError:
×
UNCOV
87
        pass
×
88
    else:
89
        return emoji.is_emoji(char)
6✔
90
    if re.match(r"[\w\d\s]", char):
×
91
        return False
×
UNCOV
92
    return not "\u4e00" <= char <= "\u9fff"  # Chinese character
×
93

94

95
def yellow_warn(msg: str) -> None:
6✔
96
    secho(msg, fg="yellow")
6✔
97

98

99
def load_bool(name: str, default: bool = False) -> bool:
6✔
100
    if not (v := os.getenv(name)):
6✔
101
        return default
6✔
102
    if (lower := v.lower()) in ("0", "false", "f", "off", "no", "n"):
6✔
103
        return False
6✔
104
    elif lower in ("1", "true", "t", "on", "yes", "y"):
6✔
105
        return True
6✔
106
    secho(f"WARNING: can not convert value({v!r}) of {name} to bool!")
6✔
107
    return default
6✔
108

109

110
def is_venv() -> bool:
6✔
111
    """Whether in a virtual environment(also work for poetry)"""
112
    return hasattr(sys, "real_prefix") or (
6✔
113
        hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix
114
    )
115

116

117
def _run_shell(cmd: list[str] | str, **kw: Any) -> subprocess.CompletedProcess[str]:
6✔
118
    if isinstance(cmd, str):
6✔
119
        kw.setdefault("shell", True)
6✔
120
    return subprocess.run(cmd, **kw)  # nosec:B603
6✔
121

122

123
def run_and_echo(
6✔
124
    cmd: str, *, dry: bool = False, verbose: bool = True, **kw: Any
125
) -> int:
126
    """Run shell command with subprocess and print it"""
127
    if verbose:
6✔
128
        echo(f"--> {cmd}")
6✔
129
    if dry:
6✔
130
        return 0
6✔
131
    command: list[str] | str = cmd
6✔
132
    if "shell" not in kw and not (set(cmd) & {"|", ">", "&"}):
6✔
133
        command = shlex.split(cmd)
6✔
134
    return _run_shell(command, **kw).returncode
6✔
135

136

137
def check_call(cmd: str) -> bool:
6✔
138
    r = _run_shell(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
6✔
139
    return r.returncode == 0
6✔
140

141

142
def capture_cmd_output(
6✔
143
    command: list[str] | str, *, raises: bool = False, **kw: Any
144
) -> str:
145
    if isinstance(command, str) and not kw.get("shell"):
6✔
146
        command = shlex.split(command)
6✔
147
    r = _run_shell(command, capture_output=True, encoding="utf-8", **kw)
6✔
148
    if raises and r.returncode != 0:
6✔
149
        raise ShellCommandError(r.stderr)
6✔
150
    return r.stdout.strip() or r.stderr
6✔
151

152

153
def _parse_version(line: str, pattern: re.Pattern[str]) -> str:
6✔
154
    return pattern.sub("", line).split("#")[0].strip(" '\"")
6✔
155

156

157
def read_version_from_file(
6✔
158
    package_name: str, work_dir: Path | None = None, toml_text: str | None = None
159
) -> str:
160
    if not package_name and toml_text:
6✔
161
        pattern = re.compile(r"version\s*=")
6✔
162
        for line in toml_text.splitlines():
6✔
163
            if pattern.match(line):
6✔
164
                return _parse_version(line, pattern)
6✔
165
    version_file = BumpUp.parse_filename(toml_text, work_dir, package_name)
6✔
166
    if version_file == TOML_FILE:
6✔
167
        if toml_text is None:
6✔
168
            toml_text = Project.load_toml_text()
6✔
169
        context = tomllib.loads(toml_text)
6✔
170
        with contextlib.suppress(KeyError):
6✔
171
            return cast(str, context["project"]["version"])
6✔
172
        with contextlib.suppress(KeyError):  # Poetry V1
6✔
173
            return cast(str, context["tool"]["poetry"]["version"])
6✔
174
        secho(f"WARNING: can not find 'version' item in {version_file}!")
6✔
175
        return "0.0.0"
6✔
176
    pattern = re.compile(r"__version__\s*=")
6✔
177
    for line in Path(version_file).read_text("utf-8").splitlines():
6✔
178
        if pattern.match(line):
6✔
179
            return _parse_version(line, pattern)
6✔
180
    # TODO: remove or refactor the following lines.
181
    if work_dir is None:
×
182
        work_dir = Project.get_work_dir()
×
183
    package_dir = work_dir / package_name
×
UNCOV
184
    if (
×
185
        not (init_file := package_dir / "__init__.py").exists()
186
        and not (init_file := work_dir / "src" / package_name / init_file.name).exists()
187
        and not (init_file := work_dir / "app" / init_file.name).exists()
188
    ):
189
        secho("WARNING: __init__.py file does not exist!")
×
UNCOV
190
        return "0.0.0"
×
191

192
    pattern = re.compile(r"__version__\s*=")
×
193
    for line in init_file.read_text("utf-8").splitlines():
×
194
        if pattern.match(line):
×
195
            return _parse_version(line, pattern)
×
196
    secho(f"WARNING: can not find '__version__' var in {init_file}!")
×
UNCOV
197
    return "0.0.0"
×
198

199

200
@overload
201
def get_current_version(
202
    verbose: bool = False,
203
    is_poetry: bool | None = None,
204
    package_name: str | None = None,
205
    *,
206
    check_version: Literal[False] = False,
207
) -> str: ...
208

209

210
@overload
211
def get_current_version(
212
    verbose: bool = False,
213
    is_poetry: bool | None = None,
214
    package_name: str | None = None,
215
    *,
216
    check_version: Literal[True] = True,
217
) -> tuple[bool, str]: ...
218

219

220
def get_current_version(
6✔
221
    verbose: bool = False,
222
    is_poetry: bool | None = None,
223
    package_name: str | None = None,
224
    *,
225
    check_version: bool = False,
226
) -> str | tuple[bool, str]:
227
    if is_poetry is True or Project.manage_by_poetry():
6✔
228
        cmd = ["poetry", "version", "-s"]
6✔
229
        if verbose:
6✔
230
            echo(f"--> {' '.join(cmd)}")
6✔
231
        if out := capture_cmd_output(cmd, raises=True):
6✔
232
            out = out.splitlines()[-1].strip().split()[-1]
6✔
233
        if check_version:
6✔
234
            return True, out
6✔
235
        return out
6✔
236
    toml_text = work_dir = None
6✔
237
    if package_name is None:
6✔
238
        work_dir = Project.get_work_dir()
6✔
239
        toml_text = Project.load_toml_text()
6✔
240
        doc = tomllib.loads(toml_text)
6✔
241
        project_name = doc.get("project", {}).get("name", work_dir.name)
6✔
242
        package_name = re.sub(r"[- ]", "_", project_name)
6✔
243
    local_version = read_version_from_file(package_name, work_dir, toml_text)
6✔
244
    try:
6✔
245
        installed_version = importlib_metadata.version(package_name)
6✔
246
    except importlib_metadata.PackageNotFoundError:
6✔
247
        installed_version = ""
6✔
248
    current_version = local_version or installed_version
6✔
249
    if not current_version:
6✔
UNCOV
250
        raise FastDevCliError(f"Failed to get current version of {package_name!r}")
×
251
    if check_version:
6✔
252
        is_conflict = bool(local_version) and local_version != installed_version
6✔
253
        return is_conflict, current_version
6✔
254
    return current_version
6✔
255

256

257
def _ensure_bool(value: bool | OptionInfo) -> bool:
6✔
258
    if not isinstance(value, bool):
6✔
259
        value = getattr(value, "default", False)
6✔
260
    return value
6✔
261

262

263
def _ensure_str(value: str | OptionInfo | None) -> str:
6✔
264
    if not isinstance(value, str):
6✔
265
        value = getattr(value, "default", "")
6✔
266
    return value
6✔
267

268

269
def exit_if_run_failed(
6✔
270
    cmd: str,
271
    env: dict[str, str] | None = None,
272
    _exit: bool = False,
273
    dry: bool = False,
274
    **kw: Any,
275
) -> subprocess.CompletedProcess[str]:
276
    run_and_echo(cmd, dry=True)
6✔
277
    if _ensure_bool(dry):
6✔
278
        return subprocess.CompletedProcess("", 0)
6✔
279
    if env is not None:
6✔
280
        env = {**os.environ, **env}
6✔
281
    r = _run_shell(cmd, env=env, **kw)
6✔
282
    if rc := r.returncode:
6✔
283
        if _exit:
6✔
284
            sys.exit(rc)
6✔
285
        raise Exit(rc)
6✔
286
    return r
6✔
287

288

289
class DryRun:
6✔
290
    def __init__(self, _exit: bool = False, dry: bool = False) -> None:
6✔
291
        self.dry = _ensure_bool(dry)
6✔
292
        self._exit = _exit
6✔
293

294
    def gen(self) -> str:
6✔
295
        raise NotImplementedError
6✔
296

297
    def run(self) -> None:
6✔
298
        exit_if_run_failed(self.gen(), _exit=self._exit, dry=self.dry)
6✔
299

300

301
class BumpUp(DryRun):
6✔
302
    class PartChoices(StrEnum):
6✔
303
        patch = "patch"
6✔
304
        minor = "minor"
6✔
305
        major = "major"
6✔
306

307
    def __init__(
6✔
308
        self,
309
        commit: bool,
310
        part: str,
311
        filename: str | None = None,
312
        dry: bool = False,
313
        no_sync: bool = False,
314
        emoji: bool | None = None,
315
    ) -> None:
316
        self.commit = commit
6✔
317
        self.part = part
6✔
318
        if filename is None:
6✔
319
            filename = self.parse_filename()
6✔
320
        self.filename = filename
6✔
321
        self._no_sync = no_sync
6✔
322
        self._emoji = emoji
6✔
323
        super().__init__(dry=dry)
6✔
324

325
    @staticmethod
6✔
326
    def get_last_commit_message(raises: bool = False) -> str:
6✔
327
        cmd = 'git show --pretty=format:"%s" -s HEAD'
6✔
328
        return capture_cmd_output(cmd, raises=raises)
6✔
329

330
    @classmethod
6✔
331
    def should_add_emoji(cls) -> bool:
6✔
332
        """
333
        If last commit message is startswith emoji,
334
        add a ⬆️ flag at the prefix of bump up commit message.
335
        """
336
        try:
6✔
337
            first_char = cls.get_last_commit_message(raises=True)[0]
6✔
338
        except (IndexError, ShellCommandError):
6✔
339
            return False
6✔
340
        else:
341
            return is_emoji(first_char)
6✔
342

343
    @staticmethod
6✔
344
    def parse_filename(
6✔
345
        toml_text: str | None = None,
346
        work_dir: Path | None = None,
347
        package_name: str | None = None,
348
    ) -> str:
349
        if toml_text is None:
6✔
350
            toml_text = Project.load_toml_text()
6✔
351
        context = tomllib.loads(toml_text)
6✔
352
        by_version_plugin = False
6✔
353
        try:
6✔
354
            ver = context["project"]["version"]
6✔
355
        except KeyError:
6✔
356
            pass
6✔
357
        else:
358
            if isinstance(ver, str):
6✔
359
                if ver in ("0", "0.0.0"):
6✔
360
                    by_version_plugin = True
6✔
361
                elif re.match(r"\d+\.\d+\.\d+", ver):
6✔
362
                    return TOML_FILE
6✔
363
        if not by_version_plugin:
6✔
364
            try:
6✔
365
                version_value = context["tool"]["poetry"]["version"]
6✔
366
            except KeyError:
6✔
367
                if not Project.manage_by_poetry():
6✔
368
                    if work_dir is None:
6✔
369
                        work_dir = Project.get_work_dir()
6✔
370
                    for tool in ("pdm", "hatch"):
6✔
371
                        with contextlib.suppress(KeyError):
6✔
372
                            version_path = cast(
6✔
373
                                str, context["tool"][tool]["version"]["path"]
374
                            )
375
                            if (
6✔
376
                                Path(version_path).exists()
377
                                or work_dir.joinpath(version_path).exists()
378
                            ):
379
                                return version_path
6✔
380
                    # version = { source = "file", path = "fast_dev_cli/__init__.py" }
381
                    v_key = "version = "
6✔
382
                    p_key = 'path = "'
6✔
383
                    for line in toml_text.splitlines():
6✔
384
                        if not line.startswith(v_key):
×
385
                            continue
×
386
                        if p_key in (value := line.split(v_key, 1)[-1].split("#")[0]):
×
387
                            filename = value.split(p_key, 1)[-1].split('"')[0]
×
388
                            if work_dir.joinpath(filename).exists():
×
UNCOV
389
                                return filename
×
390
            else:
391
                by_version_plugin = version_value in ("0", "0.0.0", "init")
6✔
392
        if by_version_plugin:
6✔
393
            try:
6✔
394
                package_item = context["tool"]["poetry"]["packages"]
6✔
395
            except KeyError:
6✔
396
                try:
6✔
397
                    project_name = context["project"]["name"]
6✔
398
                except KeyError:
6✔
399
                    packages = []
6✔
400
                else:
UNCOV
401
                    packages = [(poetry_module_name(project_name), "")]
×
402
            else:
403
                packages = [
6✔
404
                    (j, i.get("from", ""))
405
                    for i in package_item
406
                    if (j := i.get("include"))
407
                ]
408
            # In case of managed by `poetry-plugin-version`
409
            cwd = Path.cwd()
6✔
410
            pattern = re.compile(r"__version__\s*=\s*['\"]")
6✔
411
            ds: list[Path] = []
6✔
412
            if package_name is not None:
6✔
UNCOV
413
                packages.insert(0, (package_name, ""))
×
414
            for package_name, source_dir in packages:
6✔
415
                ds.append(cwd / package_name)
6✔
416
                ds.append(cwd / "src" / package_name)
6✔
417
                if source_dir and source_dir != "src":
6✔
418
                    ds.append(cwd / source_dir / package_name)
6✔
419
            module_name = poetry_module_name(cwd.name)
6✔
420
            ds.extend([cwd / module_name, cwd / "src" / module_name, cwd])
6✔
421
            for d in ds:
6✔
422
                init_file = d / "__init__.py"
6✔
423
                if (
6✔
424
                    init_file.exists() and pattern.search(init_file.read_text("utf8"))
425
                ) or (
426
                    (init_file := init_file.with_name("__version__.py")).exists()
427
                    and pattern.search(init_file.read_text("utf8"))
428
                ):
429
                    break
6✔
430
            else:
431
                raise ParseError("Version file not found! Where are you now?")
6✔
432
            return os.path.relpath(init_file, cwd)
6✔
433

434
        return TOML_FILE
6✔
435

436
    def get_part(self, s: str) -> str:
6✔
437
        choices: dict[str, str] = {}
6✔
438
        for i, p in enumerate(self.PartChoices, 1):
6✔
439
            v = str(p)
6✔
440
            choices.update({str(i): v, v: v})
6✔
441
        try:
6✔
442
            return choices[s]
6✔
443
        except KeyError as e:
6✔
444
            echo(f"Invalid part: {s!r}")
6✔
445
            raise Exit(1) from e
6✔
446

447
    def gen(self) -> str:
6✔
448
        should_sync, _version = get_current_version(check_version=True)
6✔
449
        filename = self.filename
6✔
450
        echo(f"Current version(@{filename}): {_version}")
6✔
451
        if self.part:
6✔
452
            part = self.get_part(self.part)
6✔
453
        else:
454
            part = "patch"
6✔
455
            if a := input("Which one?").strip():
6✔
456
                part = self.get_part(a)
6✔
457
        self.part = part
6✔
458
        parse = r'--parse "(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)"'
6✔
459
        cmd = f'bumpversion {parse} --current-version="{_version}" {part} {filename}'
6✔
460
        if self.commit:
6✔
461
            if part != "patch":
6✔
462
                cmd += " --tag"
6✔
463
            cmd += " --commit"
6✔
464
            if self._emoji or (self._emoji is None and self.should_add_emoji()):
6✔
465
                cmd += " --message-emoji=1"
6✔
466
            if not load_bool("DONT_GIT_PUSH"):
6✔
467
                cmd += " && git push && git push --tags && git log -1"
6✔
468
        else:
469
            cmd += " --allow-dirty"
6✔
470
        if should_sync and not self._no_sync and (sync := Project.get_sync_command()):
6✔
471
            cmd = f"{sync} && " + cmd
6✔
472
        return cmd
6✔
473

474
    def run(self) -> None:
6✔
475
        super().run()
6✔
476
        if not self.commit and not self.dry:
6✔
477
            new_version = get_current_version(True)
6✔
478
            echo(new_version)
6✔
479
            if self.part != "patch":
6✔
480
                echo("You may want to pin tag by `fast tag`")
6✔
481

482

483
@cli.command()
6✔
484
def version() -> None:
6✔
485
    """Show the version of this tool"""
486
    echo("Fast Dev Cli Version: " + typer.style(__version__, fg=typer.colors.BLUE))
6✔
487
    with contextlib.suppress(FileNotFoundError, KeyError):
6✔
488
        toml_text = Project.load_toml_text()
6✔
489
        doc = tomllib.loads(toml_text)
6✔
490
        version_file = doc["tool"]["pdm"]["version"]["path"]
6✔
491
        text = Project.get_work_dir().joinpath(version_file).read_text()
6✔
492
        varname = "__version__"
6✔
493
        for line in text.splitlines():
6✔
494
            if line.strip().startswith(varname):
6✔
495
                value = line.split("=", 1)[-1].strip().strip('"').strip("'")
6✔
496
                styled = typer.style(value, bold=True)
6✔
497
                echo(f"Version value in {version_file}: " + styled)
6✔
498
                break
6✔
499

500

501
@cli.command(name="bump")
6✔
502
def bump_version(
6✔
503
    part: BumpUp.PartChoices,
504
    commit: bool = Option(
505
        False, "--commit", "-c", help="Whether run `git commit` after version changed"
506
    ),
507
    emoji: Optional[bool] = Option(
508
        None, "--emoji", help="Whether add emoji prefix to commit message"
509
    ),
510
    no_sync: bool = Option(
511
        False, "--no-sync", help="Do not run sync command to update version"
512
    ),
513
    dry: bool = DryOption,
514
) -> None:
515
    """Bump up version string in pyproject.toml"""
516
    if emoji is not None:
6✔
517
        emoji = _ensure_bool(emoji)
6✔
518
    return BumpUp(
6✔
519
        _ensure_bool(commit),
520
        getattr(part, "value", part),
521
        no_sync=_ensure_bool(no_sync),
522
        emoji=emoji,
523
        dry=dry,
524
    ).run()
525

526

527
def bump() -> None:
6✔
528
    part, commit = "", False
6✔
529
    if args := sys.argv[2:]:
6✔
530
        if "-c" in args or "--commit" in args:
6✔
531
            commit = True
6✔
532
        for a in args:
6✔
533
            if not a.startswith("-"):
6✔
534
                part = a
6✔
535
                break
6✔
536
    return BumpUp(commit, part, no_sync="--no-sync" in args, dry="--dry" in args).run()
6✔
537

538

539
class EnvError(Exception):
6✔
540
    """Raise when expected to be managed by poetry, but toml file not found."""
541

542

543
class Project:
6✔
544
    path_depth = 5
6✔
545
    _tool: ToolName | None = None
6✔
546

547
    @staticmethod
6✔
548
    def is_poetry_v2(text: str) -> bool:
6✔
549
        return 'build-backend = "poetry' in text
6✔
550

551
    @staticmethod
6✔
552
    def work_dir(
6✔
553
        name: str, parent: Path, depth: int, be_file: bool = False
554
    ) -> Path | None:
555
        for _ in range(depth):
6✔
556
            if (f := parent.joinpath(name)).exists():
6✔
557
                if be_file:
6✔
558
                    return f
6✔
559
                return parent
6✔
560
            parent = parent.parent
6✔
561
        return None
6✔
562

563
    @classmethod
6✔
564
    def get_work_dir(
6✔
565
        cls: type[Self],
566
        name: str = TOML_FILE,
567
        cwd: Path | None = None,
568
        allow_cwd: bool = False,
569
        be_file: bool = False,
570
    ) -> Path:
571
        cwd = cwd or Path.cwd()
6✔
572
        if d := cls.work_dir(name, cwd, cls.path_depth, be_file):
6✔
573
            return d
6✔
574
        if allow_cwd:
6✔
575
            return cls.get_root_dir(cwd)
6✔
576
        raise EnvError(f"{name} not found! Make sure this is a python project.")
6✔
577

578
    @classmethod
6✔
579
    def load_toml_text(cls: type[Self], name: str = TOML_FILE) -> str:
6✔
580
        toml_file = cls.get_work_dir(name, be_file=True)
6✔
581
        return toml_file.read_text("utf8")
6✔
582

583
    @classmethod
6✔
584
    def manage_by_poetry(cls: type[Self], cache: bool = False) -> bool:
6✔
585
        return cls.get_manage_tool(cache=cache) == "poetry"
6✔
586

587
    @classmethod
6✔
588
    def get_manage_tool(cls: type[Self], cache: bool = False) -> ToolName | None:
6✔
589
        if cache and cls._tool:
6✔
590
            return cls._tool
6✔
591
        try:
6✔
592
            text = cls.load_toml_text()
6✔
593
        except EnvError:
6✔
594
            pass
6✔
595
        else:
596
            with contextlib.suppress(KeyError, tomllib.TOMLDecodeError):
6✔
597
                doc = tomllib.loads(text)
6✔
598
                backend = doc["build-system"]["build-backend"]
6✔
599
                if "poetry" in backend:
6✔
600
                    cls._tool = "poetry"
6✔
601
                    return cls._tool
6✔
602
                elif "pdm" in backend:
6✔
603
                    cls._tool = "pdm"
6✔
604
                    work_dir = cls.get_work_dir(allow_cwd=True)
6✔
605
                    if not Path(work_dir, "pdm.lock").exists() and (
6✔
606
                        "[tool.uv]" in text or Path(work_dir, "uv.lock").exists()
607
                    ):
UNCOV
608
                        cls._tool = "uv"
×
609
                    return cls._tool
6✔
610
            for name in get_args(ToolName):
6✔
611
                if f"[tool.{name}]" in text:
6✔
612
                    cls._tool = cast(ToolName, name)
6✔
613
                    return cls._tool
6✔
614
            # Poetry 2.0 default to not include the '[tool.poetry]' section
615
            if cls.is_poetry_v2(text):
6✔
616
                cls._tool = "poetry"
×
UNCOV
617
                return cls._tool
×
618
        return None
6✔
619

620
    @staticmethod
6✔
621
    def python_exec_dir() -> Path:
6✔
622
        return Path(sys.executable).parent
6✔
623

624
    @classmethod
6✔
625
    def get_root_dir(cls: type[Self], cwd: Path | None = None) -> Path:
6✔
626
        root = cwd or Path.cwd()
6✔
627
        venv_parent = cls.python_exec_dir().parent.parent
6✔
628
        if root.is_relative_to(venv_parent):
6✔
629
            root = venv_parent
6✔
630
        return root
6✔
631

632
    @classmethod
6✔
633
    def is_pdm_project(cls, strict: bool = True, cache: bool = False) -> bool:
6✔
634
        if cls.get_manage_tool(cache=cache) != "pdm":
6✔
635
            return False
6✔
636
        if strict:
×
637
            lock_file = cls.get_work_dir() / "pdm.lock"
×
638
            return lock_file.exists()
×
UNCOV
639
        return True
×
640

641
    @classmethod
6✔
642
    def get_sync_command(cls, prod: bool = True, doc: dict | None = None) -> str:
6✔
643
        if cls.is_pdm_project():
6✔
UNCOV
644
            return "pdm sync" + " --prod" * prod
×
645
        elif cls.manage_by_poetry(cache=True):
6✔
646
            cmd = "poetry install"
6✔
647
            if prod:
6✔
648
                if doc is None:
6✔
649
                    doc = tomllib.loads(cls.load_toml_text())
6✔
650
                if doc.get("project", {}).get("dependencies") or any(
6✔
651
                    i != "python"
652
                    for i in doc.get("tool", {})
653
                    .get("poetry", {})
654
                    .get("dependencies", [])
655
                ):
UNCOV
656
                    cmd += " --only=main"
×
657
            return cmd
6✔
658
        elif cls.get_manage_tool(cache=True) == "uv":
×
659
            return "uv sync --inexact" + " --no-dev" * prod
×
UNCOV
660
        return ""
×
661

662
    @classmethod
6✔
663
    def sync_dependencies(cls, prod: bool = True) -> None:
6✔
664
        if cmd := cls.get_sync_command():
×
UNCOV
665
            run_and_echo(cmd)
×
666

667

668
class ParseError(Exception):
6✔
669
    """Raise this if parse dependence line error"""
670

671
    pass
6✔
672

673

674
class UpgradeDependencies(Project, DryRun):
6✔
675
    def __init__(
6✔
676
        self, _exit: bool = False, dry: bool = False, tool: ToolName = "poetry"
677
    ) -> None:
678
        super().__init__(_exit, dry)
6✔
679
        self._tool = tool
6✔
680

681
    class DevFlag(StrEnum):
6✔
682
        new = "[tool.poetry.group.dev.dependencies]"
6✔
683
        old = "[tool.poetry.dev-dependencies]"
6✔
684

685
    @staticmethod
6✔
686
    def parse_value(version_info: str, key: str) -> str:
6✔
687
        """Pick out the value for key in version info.
688

689
        Example::
690
            >>> s= 'typer = {extras = ["all"], version = "^0.9.0", optional = true}'
691
            >>> UpgradeDependencies.parse_value(s, 'extras')
692
            'all'
693
            >>> UpgradeDependencies.parse_value(s, 'optional')
694
            'true'
695
            >>> UpgradeDependencies.parse_value(s, 'version')
696
            '^0.9.0'
697
        """
698
        sep = key + " = "
6✔
699
        rest = version_info.split(sep, 1)[-1].strip(" =")
6✔
700
        if rest.startswith("["):
6✔
701
            rest = rest[1:].split("]")[0]
6✔
702
        elif rest.startswith('"'):
6✔
703
            rest = rest[1:].split('"')[0]
6✔
704
        else:
705
            rest = rest.split(",")[0].split("}")[0]
6✔
706
        return rest.strip().replace('"', "")
6✔
707

708
    @staticmethod
6✔
709
    def no_need_upgrade(version_info: str, line: str) -> bool:
6✔
710
        if (v := version_info.replace(" ", "")).startswith("{url="):
6✔
711
            echo(f"No need to upgrade for: {line}")
6✔
712
            return True
6✔
713
        if (f := "version=") in v:
6✔
714
            v = v.split(f)[1].strip('"').split('"')[0]
6✔
715
        if v == "*":
6✔
716
            echo(f"Skip wildcard line: {line}")
6✔
717
            return True
6✔
718
        elif v == "[":
6✔
719
            echo(f"Skip complex dependence: {line}")
6✔
720
            return True
6✔
721
        elif v.startswith(">") or v.startswith("<") or v[0].isdigit():
6✔
722
            echo(f"Ignore bigger/smaller/equal: {line}")
6✔
723
            return True
6✔
724
        return False
6✔
725

726
    @classmethod
6✔
727
    def build_args(
6✔
728
        cls: type[Self], package_lines: list[str]
729
    ) -> tuple[list[str], dict[str, list[str]]]:
730
        args: list[str] = []  # ['typer[all]', 'fastapi']
6✔
731
        specials: dict[str, list[str]] = {}  # {'--platform linux': ['gunicorn']}
6✔
732
        for no, line in enumerate(package_lines, 1):
6✔
733
            if (
6✔
734
                not (m := line.strip())
735
                or m.startswith("#")
736
                or m == "]"
737
                or (m.startswith("{") and m.strip(",").endswith("}"))
738
            ):
739
                continue
6✔
740
            try:
6✔
741
                package, version_info = m.split("=", 1)
6✔
742
            except ValueError as e:
6✔
743
                raise ParseError(f"Failed to separate by '='@line {no}: {m}") from e
6✔
744
            if (package := package.strip()).lower() == "python":
6✔
745
                continue
6✔
746
            if cls.no_need_upgrade(version_info := version_info.strip(' "'), line):
6✔
747
                continue
6✔
748
            if (extras_tip := "extras") in version_info:
6✔
749
                package += "[" + cls.parse_value(version_info, extras_tip) + "]"
6✔
750
            item = f'"{package}@latest"'
6✔
751
            key = None
6✔
752
            if (pf := "platform") in version_info:
6✔
753
                platform = cls.parse_value(version_info, pf)
6✔
754
                key = f"--{pf}={platform}"
6✔
755
            if (sc := "source") in version_info:
6✔
756
                source = cls.parse_value(version_info, sc)
6✔
757
                key = ("" if key is None else (key + " ")) + f"--{sc}={source}"
6✔
758
            if "optional = true" in version_info:
6✔
759
                key = ("" if key is None else (key + " ")) + "--optional"
6✔
760
            if key is not None:
6✔
761
                specials[key] = specials.get(key, []) + [item]
6✔
762
            else:
763
                args.append(item)
6✔
764
        return args, specials
6✔
765

766
    @classmethod
6✔
767
    def should_with_dev(cls: type[Self]) -> bool:
6✔
768
        text = cls.load_toml_text()
6✔
769
        return cls.DevFlag.new in text or cls.DevFlag.old in text
6✔
770

771
    @staticmethod
6✔
772
    def parse_item(toml_str: str) -> list[str]:
6✔
773
        lines: list[str] = []
6✔
774
        for line in toml_str.splitlines():
6✔
775
            if (line := line.strip()).startswith("["):
6✔
776
                if lines:
6✔
777
                    break
6✔
778
            elif line:
6✔
779
                lines.append(line)
6✔
780
        return lines
6✔
781

782
    @classmethod
6✔
783
    def get_args(
6✔
784
        cls: type[Self], toml_text: str | None = None
785
    ) -> tuple[list[str], list[str], list[list[str]], str]:
786
        if toml_text is None:
6✔
787
            toml_text = cls.load_toml_text()
6✔
788
        main_title = "[tool.poetry.dependencies]"
6✔
789
        if (no_main_deps := main_title not in toml_text) and not cls.is_poetry_v2(
6✔
790
            toml_text
791
        ):
792
            raise EnvError(
6✔
793
                f"{main_title} not found! Make sure this is a poetry project."
794
            )
795
        text = toml_text.split(main_title)[-1]
6✔
796
        dev_flag = "--group dev"
6✔
797
        new_flag, old_flag = cls.DevFlag.new, cls.DevFlag.old
6✔
798
        if (dev_title := getattr(new_flag, "value", new_flag)) not in text:
6✔
799
            dev_title = getattr(old_flag, "value", old_flag)  # For poetry<=1.2
6✔
800
            dev_flag = "--dev"
6✔
801
        others: list[list[str]] = []
6✔
802
        try:
6✔
803
            main_toml, dev_toml = text.split(dev_title)
6✔
804
        except ValueError:
6✔
805
            dev_toml = ""
6✔
806
            main_toml = text
6✔
807
        mains = [] if no_main_deps else cls.parse_item(main_toml)
6✔
808
        devs = cls.parse_item(dev_toml)
6✔
809
        prod_packs, specials = cls.build_args(mains)
6✔
810
        if specials:
6✔
811
            others.extend([[k] + v for k, v in specials.items()])
6✔
812
        dev_packs, specials = cls.build_args(devs)
6✔
813
        if specials:
6✔
814
            others.extend([[k] + v + [dev_flag] for k, v in specials.items()])
6✔
815
        return prod_packs, dev_packs, others, dev_flag
6✔
816

817
    @classmethod
6✔
818
    def gen_cmd(cls: type[Self]) -> str:
6✔
819
        main_args, dev_args, others, dev_flags = cls.get_args()
6✔
820
        return cls.to_cmd(main_args, dev_args, others, dev_flags)
6✔
821

822
    @staticmethod
6✔
823
    def to_cmd(
6✔
824
        main_args: list[str],
825
        dev_args: list[str],
826
        others: list[list[str]],
827
        dev_flags: str,
828
    ) -> str:
829
        command = "poetry add "
6✔
830
        _upgrade = ""
6✔
831
        if main_args:
6✔
832
            _upgrade = command + " ".join(main_args)
6✔
833
        if dev_args:
6✔
834
            if _upgrade:
6✔
835
                _upgrade += " && "
6✔
836
            _upgrade += command + dev_flags + " " + " ".join(dev_args)
6✔
837
        for single in others:
6✔
838
            _upgrade += f" && poetry add {' '.join(single)}"
6✔
839
        return _upgrade
6✔
840

841
    def gen(self) -> str:
6✔
842
        if self._tool == "uv":
6✔
843
            up = "uv lock --upgrade --verbose"
6✔
844
            deps = "uv sync --inexact --frozen --all-groups --all-extras"
6✔
845
            return f"{up} && {deps}"
6✔
846
        elif self._tool == "pdm":
6✔
847
            return "pdm update --verbose && pdm sync -G :all --frozen"
6✔
848
        return self.gen_cmd() + " && poetry lock && poetry update"
6✔
849

850

851
@cli.command()
6✔
852
def upgrade(
6✔
853
    tool: str = ToolOption,
854
    dry: bool = DryOption,
855
) -> None:
856
    """Upgrade dependencies in pyproject.toml to latest versions"""
857
    if not (tool := _ensure_str(tool)) or tool == ToolOption.default:
6✔
858
        tool = Project.get_manage_tool() or "uv"
6✔
859
    if tool in get_args(ToolName):
6✔
860
        UpgradeDependencies(dry=dry, tool=cast(ToolName, tool)).run()
6✔
861
    else:
862
        secho(f"Unknown tool {tool!r}", fg=typer.colors.YELLOW)
6✔
863
        raise typer.Exit(1)
6✔
864

865

866
class GitTag(DryRun):
6✔
867
    def __init__(self, message: str, dry: bool, no_sync: bool = False) -> None:
6✔
868
        self.message = message
6✔
869
        self._no_sync = no_sync
6✔
870
        super().__init__(dry=dry)
6✔
871

872
    @staticmethod
6✔
873
    def has_v_prefix() -> bool:
6✔
874
        return "v" in capture_cmd_output("git tag")
6✔
875

876
    def should_push(self) -> bool:
6✔
877
        return "git push" in self.git_status
6✔
878

879
    def gen(self) -> str:
6✔
880
        should_sync, _version = get_current_version(verbose=False, check_version=True)
6✔
881
        if self.has_v_prefix():
6✔
882
            # Add `v` at prefix to compare with bumpversion tool
883
            _version = "v" + _version
6✔
884
        cmd = f"git tag -a {_version} -m {self.message!r} && git push --tags"
6✔
885
        if self.should_push():
6✔
886
            cmd += " && git push"
6✔
887
        if should_sync and not self._no_sync and (sync := Project.get_sync_command()):
6✔
UNCOV
888
            cmd = f"{sync} && " + cmd
×
889
        return cmd
6✔
890

891
    @cached_property
6✔
892
    def git_status(self) -> str:
6✔
893
        return capture_cmd_output("git status")
6✔
894

895
    def mark_tag(self) -> bool:
6✔
896
        if not re.search(r"working (tree|directory) clean", self.git_status) and (
6✔
897
            "无文件要提交,干净的工作区" not in self.git_status
898
        ):
899
            run_and_echo("git status")
6✔
900
            echo("ERROR: Please run git commit to make sure working tree is clean!")
6✔
901
            return False
6✔
902
        return bool(super().run())
6✔
903

904
    def run(self) -> None:
6✔
905
        if self.mark_tag() and not self.dry:
6✔
906
            echo("You may want to publish package:\n poetry publish --build")
6✔
907

908

909
@cli.command()
6✔
910
def tag(
6✔
911
    message: str = Option("", "-m", "--message"),
912
    no_sync: bool = Option(
913
        False, "--no-sync", help="Do not run sync command to update version"
914
    ),
915
    dry: bool = DryOption,
916
) -> None:
917
    """Run shell command: git tag -a <current-version-in-pyproject.toml> -m {message}"""
918
    GitTag(message, dry=dry, no_sync=_ensure_bool(no_sync)).run()
6✔
919

920

921
class LintCode(DryRun):
6✔
922
    def __init__(
6✔
923
        self,
924
        args: list[str] | str | None,
925
        check_only: bool = False,
926
        _exit: bool = False,
927
        dry: bool = False,
928
        bandit: bool = False,
929
        skip_mypy: bool = False,
930
        dmypy: bool = False,
931
        tool: str = ToolOption.default,
932
        prefix: bool = False,
933
    ) -> None:
934
        self.args = args
6✔
935
        self.check_only = check_only
6✔
936
        self._bandit = bandit
6✔
937
        self._skip_mypy = skip_mypy
6✔
938
        self._use_dmypy = dmypy
6✔
939
        self._tool = tool
6✔
940
        self._prefix = prefix
6✔
941
        super().__init__(_exit, dry)
6✔
942

943
    @staticmethod
6✔
944
    def check_lint_tool_installed() -> bool:
6✔
945
        return check_call("ruff --version")
6✔
946

947
    @staticmethod
6✔
948
    def missing_mypy_exec() -> bool:
6✔
949
        return shutil.which("mypy") is None
6✔
950

951
    @staticmethod
6✔
952
    def prefer_dmypy(paths: str, tools: list[str], use_dmypy: bool = False) -> bool:
6✔
953
        return (
6✔
954
            paths == "."
955
            and any(t.startswith("mypy") for t in tools)
956
            and (use_dmypy or load_bool("FASTDEVCLI_DMYPY"))
957
        )
958

959
    @staticmethod
6✔
960
    def get_package_name() -> str:
6✔
961
        root = Project.get_work_dir(allow_cwd=True)
6✔
962
        module_name = root.name.replace("-", "_").replace(" ", "_")
6✔
963
        package_maybe = (module_name, "src")
6✔
964
        for name in package_maybe:
6✔
965
            if root.joinpath(name).is_dir():
6✔
966
                return name
6✔
967
        return "."
6✔
968

969
    @classmethod
6✔
970
    def to_cmd(
6✔
971
        cls: type[Self],
972
        paths: str = ".",
973
        check_only: bool = False,
974
        bandit: bool = False,
975
        skip_mypy: bool = False,
976
        use_dmypy: bool = False,
977
        tool: str = ToolOption.default,
978
        with_prefix: bool = False,
979
    ) -> str:
980
        if paths != "." and all(i.endswith(".html") for i in paths.split()):
6✔
981
            return f"prettier -w {paths}"
6✔
982
        cmd = ""
6✔
983
        tools = ["ruff format", "ruff check --extend-select=I,B,SIM --fix", "mypy"]
6✔
984
        if check_only:
6✔
985
            tools[0] += " --check"
6✔
986
        if check_only or load_bool("NO_FIX"):
6✔
987
            tools[1] = tools[1].replace(" --fix", "")
6✔
988
        if skip_mypy or load_bool("SKIP_MYPY") or load_bool("FASTDEVCLI_NO_MYPY"):
6✔
989
            # Sometimes mypy is too slow
990
            tools = tools[:-1]
6✔
991
        elif load_bool("IGNORE_MISSING_IMPORTS"):
6✔
992
            tools[-1] += " --ignore-missing-imports"
6✔
993
        lint_them = " && ".join(
6✔
994
            "{0}{" + str(i) + "} {1}" for i in range(2, len(tools) + 2)
995
        )
996
        if ruff_exists := cls.check_lint_tool_installed():
6✔
997
            # `ruff <command>` get the same result with `pdm run ruff <command>`
998
            # While `mypy .`(installed global and env not activated),
999
            #   does not the same as `pdm run mypy .`
1000
            lint_them = " && ".join(
6✔
1001
                ("" if tool.startswith("ruff") else "{0}")
1002
                + (
1003
                    "{%d} {1}" % i  # noqa: UP031
1004
                )
1005
                for i, tool in enumerate(tools, 2)
1006
            )
1007
        prefix = ""
6✔
1008
        should_run_by_tool = with_prefix
6✔
1009
        if not should_run_by_tool:
6✔
1010
            if is_venv() and Path(sys.argv[0]).parent != Path.home().joinpath(
6✔
1011
                ".local/bin"
1012
            ):
1013
                if not ruff_exists:
6✔
1014
                    should_run_by_tool = True
6✔
1015
                    command = "pipx install ruff"
6✔
1016
                    if shutil.which("pipx") is None:
6✔
UNCOV
1017
                        ensure_pipx = "pip install --user pipx\n  pipx ensurepath\n  "
×
UNCOV
1018
                        command = ensure_pipx + command
×
1019
                    yellow_warn(
6✔
1020
                        "You may need to run the following command"
1021
                        f" to install ruff:\n\n  {command}\n"
1022
                    )
1023
                elif "mypy" in str(tools) and cls.missing_mypy_exec():
6✔
1024
                    should_run_by_tool = True
6✔
1025
                    if check_call('python -c "import fast_dev_cli"'):
6✔
1026
                        command = 'python -m pip install -U "fast-dev-cli"'
6✔
1027
                        yellow_warn(
6✔
1028
                            "You may need to run the following command"
1029
                            f" to install lint tools:\n\n  {command}\n"
1030
                        )
1031
            else:
1032
                should_run_by_tool = True
6✔
1033
        if should_run_by_tool and tool:
6✔
1034
            if tool == ToolOption.default:
6✔
1035
                tool = Project.get_manage_tool() or ""
6✔
1036
            if tool:
6✔
1037
                prefix = (
6✔
1038
                    bin_dir
1039
                    if tool == "uv" and Path(bin_dir := ".venv/bin/").exists()
1040
                    else (tool + " run ")
1041
                )
1042
        if cls.prefer_dmypy(paths, tools, use_dmypy=use_dmypy):
6✔
1043
            tools[-1] = "dmypy run"
6✔
1044
        cmd += lint_them.format(prefix, paths, *tools)
6✔
1045
        if bandit or load_bool("FASTDEVCLI_BANDIT"):
6✔
1046
            command = prefix + "bandit"
6✔
1047
            if Path("pyproject.toml").exists():
6✔
1048
                toml_text = Project.load_toml_text()
6✔
1049
                if "[tool.bandit" in toml_text:
6✔
1050
                    command += " -c pyproject.toml"
6✔
1051
            if paths == "." and " -c " not in command:
6✔
1052
                paths = cls.get_package_name()
6✔
1053
            command += f" -r {paths}"
6✔
1054
            cmd += " && " + command
6✔
1055
        return cmd
6✔
1056

1057
    def gen(self) -> str:
6✔
1058
        if isinstance(args := self.args, str):
6✔
1059
            args = args.split()
6✔
1060
        paths = " ".join(map(str, args)) if args else "."
6✔
1061
        return self.to_cmd(
6✔
1062
            paths,
1063
            self.check_only,
1064
            self._bandit,
1065
            self._skip_mypy,
1066
            self._use_dmypy,
1067
            tool=self._tool,
1068
            with_prefix=self._prefix,
1069
        )
1070

1071

1072
def parse_files(args: list[str] | tuple[str, ...]) -> list[str]:
6✔
1073
    return [i for i in args if not i.startswith("-")]
6✔
1074

1075

1076
def lint(
6✔
1077
    files: list[str] | str | None = None,
1078
    dry: bool = False,
1079
    bandit: bool = False,
1080
    skip_mypy: bool = False,
1081
    dmypy: bool = False,
1082
    tool: str = ToolOption.default,
1083
    prefix: bool = False,
1084
) -> None:
1085
    if files is None:
6✔
1086
        files = parse_files(sys.argv[1:])
6✔
1087
    if files and files[0] == "lint":
6✔
1088
        files = files[1:]
6✔
1089
    LintCode(
6✔
1090
        files,
1091
        dry=dry,
1092
        skip_mypy=skip_mypy,
1093
        bandit=bandit,
1094
        dmypy=dmypy,
1095
        tool=tool,
1096
        prefix=prefix,
1097
    ).run()
1098

1099

1100
def check(
6✔
1101
    files: list[str] | str | None = None,
1102
    dry: bool = False,
1103
    bandit: bool = False,
1104
    skip_mypy: bool = False,
1105
    dmypy: bool = False,
1106
    tool: str = ToolOption.default,
1107
) -> None:
1108
    LintCode(
6✔
1109
        files,
1110
        check_only=True,
1111
        _exit=True,
1112
        dry=dry,
1113
        bandit=bandit,
1114
        skip_mypy=skip_mypy,
1115
        dmypy=dmypy,
1116
        tool=tool,
1117
    ).run()
1118

1119

1120
@cli.command(name="lint")
6✔
1121
def make_style(
6✔
1122
    files: Optional[list[str]] = typer.Argument(default=None),  # noqa:B008
1123
    check_only: bool = Option(False, "--check-only", "-c"),
1124
    bandit: bool = Option(False, "--bandit", help="Run `bandit -r <package_dir>`"),
1125
    prefix: bool = Option(
1126
        False,
1127
        "--prefix",
1128
        help="Run lint command with tool prefix, e.g.: pdm run ruff ...",
1129
    ),
1130
    skip_mypy: bool = Option(False, "--skip-mypy"),
1131
    use_dmypy: bool = Option(
1132
        False, "--dmypy", help="Use `dmypy run` instead of `mypy`"
1133
    ),
1134
    tool: str = ToolOption,
1135
    dry: bool = DryOption,
1136
) -> None:
1137
    """Run: ruff check/format to reformat code and then mypy to check"""
1138
    if getattr(files, "default", files) is None:
6✔
1139
        files = ["."]
6✔
1140
    elif isinstance(files, str):
6✔
1141
        files = [files]
6✔
1142
    skip = _ensure_bool(skip_mypy)
6✔
1143
    dmypy = _ensure_bool(use_dmypy)
6✔
1144
    bandit = _ensure_bool(bandit)
6✔
1145
    prefix = _ensure_bool(prefix)
6✔
1146
    tool = _ensure_str(tool)
6✔
1147
    if _ensure_bool(check_only):
6✔
1148
        check(files, dry=dry, skip_mypy=skip, dmypy=dmypy, bandit=bandit, tool=tool)
6✔
1149
    else:
1150
        lint(
6✔
1151
            files,
1152
            dry=dry,
1153
            skip_mypy=skip,
1154
            dmypy=dmypy,
1155
            bandit=bandit,
1156
            tool=tool,
1157
            prefix=prefix,
1158
        )
1159

1160

1161
@cli.command(name="check")
6✔
1162
def only_check(
6✔
1163
    bandit: bool = Option(False, "--bandit", help="Run `bandit -r <package_dir>`"),
1164
    skip_mypy: bool = Option(False, "--skip-mypy"),
1165
    dry: bool = DryOption,
1166
) -> None:
1167
    """Check code style without reformat"""
1168
    check(dry=dry, bandit=bandit, skip_mypy=_ensure_bool(skip_mypy))
6✔
1169

1170

1171
class Sync(DryRun):
6✔
1172
    def __init__(
6✔
1173
        self, filename: str, extras: str, save: bool, dry: bool = False
1174
    ) -> None:
1175
        self.filename = filename
6✔
1176
        self.extras = extras
6✔
1177
        self._save = save
6✔
1178
        super().__init__(dry=dry)
6✔
1179

1180
    def gen(self) -> str:
6✔
1181
        extras, save = self.extras, self._save
6✔
1182
        should_remove = not Path.cwd().joinpath(self.filename).exists()
6✔
1183
        if not (tool := Project.get_manage_tool()):
6✔
1184
            if should_remove or not is_venv():
6✔
1185
                raise EnvError("There project is not managed by uv/pdm/poetry!")
6✔
1186
            return f"python -m pip install -r {self.filename}"
6✔
1187
        prefix = "" if is_venv() else f"{tool} run "
6✔
1188
        ensure_pip = " {1}python -m ensurepip && {1}python -m pip install -U pip &&"
6✔
1189
        export_cmd = "uv export --no-hashes --all-extras --frozen"
6✔
1190
        if tool in ("poetry", "pdm"):
6✔
1191
            export_cmd = f"{tool} export --without-hashes --with=dev"
6✔
1192
            if tool == "poetry":
6✔
1193
                ensure_pip = ""
6✔
1194
                if not UpgradeDependencies.should_with_dev():
6✔
1195
                    export_cmd = export_cmd.replace(" --with=dev", "")
6✔
1196
                if extras and isinstance(extras, (str, list)):
6✔
1197
                    export_cmd += f" --{extras=}".replace("'", '"')
6✔
1198
            elif check_call(prefix + "python -m pip --version"):
6✔
1199
                ensure_pip = ""
6✔
1200
        elif check_call(prefix + "python -m pip --version"):
6✔
1201
            ensure_pip = ""
6✔
1202
        install_cmd = (
6✔
1203
            f"{{2}} -o {{0}} &&{ensure_pip} {{1}}python -m pip install -r {{0}}"
1204
        )
1205
        if should_remove and not save:
6✔
1206
            install_cmd += " && rm -f {0}"
6✔
1207
        return install_cmd.format(self.filename, prefix, export_cmd)
6✔
1208

1209

1210
@cli.command()
6✔
1211
def sync(
6✔
1212
    filename: str = "dev_requirements.txt",
1213
    extras: str = Option("", "--extras", "-E"),
1214
    save: bool = Option(
1215
        False, "--save", "-s", help="Whether save the requirement file"
1216
    ),
1217
    dry: bool = DryOption,
1218
) -> None:
1219
    """Export dependencies by poetry to a txt file then install by pip."""
1220
    Sync(filename, extras, save, dry=dry).run()
6✔
1221

1222

1223
def _should_run_test_script(path: Path = Path("scripts")) -> Path | None:
6✔
1224
    for name in ("test.sh", "test.py"):
6✔
1225
        if (file := path / name).exists():
6✔
1226
            return file
6✔
1227
    return None
6✔
1228

1229

1230
def test(dry: bool, ignore_script: bool = False) -> None:
6✔
1231
    cwd = Path.cwd()
6✔
1232
    root = Project.get_work_dir(cwd=cwd, allow_cwd=True)
6✔
1233
    script_dir = root / "scripts"
6✔
1234
    if not _ensure_bool(ignore_script) and (
6✔
1235
        test_script := _should_run_test_script(script_dir)
1236
    ):
1237
        cmd = f"{os.path.relpath(test_script, root)}"
6✔
1238
        if cwd != root:
6✔
1239
            cmd = f"cd {root} && " + cmd
6✔
1240
    else:
1241
        cmd = 'coverage run -m pytest -s && coverage report --omit="tests/*" -m'
6✔
1242
        if not is_venv() or not check_call("coverage --version"):
6✔
1243
            sep = " && "
6✔
1244
            prefix = f"{tool} run " if (tool := Project.get_manage_tool()) else ""
6✔
1245
            cmd = sep.join(prefix + i for i in cmd.split(sep))
6✔
1246
    exit_if_run_failed(cmd, dry=dry)
6✔
1247

1248

1249
@cli.command(name="test")
6✔
1250
def coverage_test(
6✔
1251
    dry: bool = DryOption,
1252
    ignore_script: bool = Option(False, "--ignore-script", "-i"),
1253
) -> None:
1254
    """Run unittest by pytest and report coverage"""
1255
    return test(dry, ignore_script)
6✔
1256

1257

1258
class Publish:
6✔
1259
    class CommandEnum(StrEnum):
6✔
1260
        poetry = "poetry publish --build"
6✔
1261
        pdm = "pdm publish"
6✔
1262
        uv = "uv build && uv publish"
6✔
1263
        twine = "python -m build && twine upload"
6✔
1264

1265
    @classmethod
6✔
1266
    def gen(cls) -> str:
6✔
1267
        if tool := Project.get_manage_tool():
6✔
1268
            return cls.CommandEnum[tool]
6✔
1269
        return cls.CommandEnum.twine
6✔
1270

1271

1272
@cli.command()
6✔
1273
def upload(
6✔
1274
    dry: bool = DryOption,
1275
) -> None:
1276
    """Shortcut for package publish"""
1277
    cmd = Publish.gen()
6✔
1278
    exit_if_run_failed(cmd, dry=dry)
6✔
1279

1280

1281
def dev(
6✔
1282
    port: int | None | OptionInfo,
1283
    host: str | None | OptionInfo,
1284
    file: str | None | ArgumentInfo = None,
1285
    dry: bool = False,
1286
) -> None:
1287
    cmd = "fastapi dev"
6✔
1288
    no_port_yet = True
6✔
1289
    if file is not None:
6✔
1290
        try:
6✔
1291
            port = int(str(file))
6✔
1292
        except ValueError:
6✔
1293
            cmd += f" {file}"
6✔
1294
        else:
1295
            if port != 8000:
6✔
1296
                cmd += f" --port={port}"
6✔
1297
                no_port_yet = False
6✔
1298
    if no_port_yet and (port := getattr(port, "default", port)) and str(port) != "8000":
6✔
1299
        cmd += f" --port={port}"
6✔
1300
    if (host := getattr(host, "default", host)) and host not in (
6✔
1301
        "localhost",
1302
        "127.0.0.1",
1303
    ):
1304
        cmd += f" --host={host}"
6✔
1305
    exit_if_run_failed(cmd, dry=dry)
6✔
1306

1307

1308
@cli.command(name="dev")
6✔
1309
def runserver(
6✔
1310
    file_or_port: Optional[str] = typer.Argument(default=None),
1311
    port: Optional[int] = Option(None, "-p", "--port"),
1312
    host: Optional[str] = Option(None, "-h", "--host"),
1313
    dry: bool = DryOption,
1314
) -> None:
1315
    """Start a fastapi server(only for fastapi>=0.111.0)"""
1316
    if getattr(file_or_port, "default", file_or_port):
6✔
1317
        dev(port, host, file=file_or_port, dry=dry)
6✔
1318
    else:
1319
        dev(port, host, dry=dry)
6✔
1320

1321

1322
@cli.command(name="exec")
6✔
1323
def run_by_subprocess(cmd: str, dry: bool = DryOption) -> None:
6✔
1324
    """Run cmd by subprocess, auto set shell=True when cmd contains '|>'"""
1325
    try:
6✔
1326
        rc = run_and_echo(cmd, verbose=True, dry=_ensure_bool(dry))
6✔
1327
    except FileNotFoundError as e:
6✔
1328
        if e.filename == cmd.split()[0]:
6✔
1329
            echo(f"Command not found: {e.filename}")
6✔
1330
            raise Exit(1) from None
6✔
1331
        raise e
1✔
1332
    else:
1333
        if rc:
6✔
1334
            raise Exit(rc)
6✔
1335

1336

1337
class MakeDeps(DryRun):
6✔
1338
    def __init__(self, tool: str, prod: bool = False, dry: bool = False) -> None:
6✔
1339
        self._tool = tool
6✔
1340
        self._prod = prod
6✔
1341
        super().__init__(dry=dry)
6✔
1342

1343
    def should_ensure_pip(self) -> bool:
6✔
1344
        return True
6✔
1345

1346
    def should_upgrade_pip(self) -> bool:
6✔
UNCOV
1347
        return True
×
1348

1349
    def get_groups(self) -> list[str]:
6✔
1350
        if self._prod:
6✔
1351
            return []
6✔
1352
        return ["dev"]
6✔
1353

1354
    def gen(self) -> str:
6✔
1355
        if self._tool == "pdm":
6✔
1356
            return "pdm sync " + ("--prod" if self._prod else "-G :all")
6✔
1357
        elif self._tool == "uv":
6✔
1358
            return "uv sync --inexact --active" + (
6✔
1359
                "" if self._prod else " --all-extras --all-groups"
1360
            )
1361
        elif self._tool == "poetry":
6✔
1362
            return "poetry install " + (
6✔
1363
                "--only=main" if self._prod else "--all-extras --all-groups"
1364
            )
1365
        else:
1366
            cmd = "python -m pip install -e ."
6✔
1367
            if gs := self.get_groups():
6✔
1368
                cmd += " " + " ".join(f"--group {g}" for g in gs)
6✔
1369
            upgrade = "python -m pip install --upgrade pip"
6✔
1370
            if self.should_ensure_pip():
6✔
1371
                cmd = f"python -m ensurepip && {upgrade} && {cmd}"
6✔
UNCOV
1372
            elif self.should_upgrade_pip():
×
UNCOV
1373
                cmd = "{upgrade} && {cmd}"
×
1374
            return cmd
6✔
1375

1376

1377
@cli.command(name="deps")
6✔
1378
def make_deps(
6✔
1379
    prod: bool = Option(
1380
        False,
1381
        "--prod",
1382
        help="Only instead production dependencies.",
1383
    ),
1384
    tool: str = ToolOption,
1385
    use_uv: bool = Option(False, "--uv", help="Use `uv` to install deps"),
1386
    use_pdm: bool = Option(False, "--pdm", help="Use `pdm` to install deps"),
1387
    use_pip: bool = Option(False, "--pip", help="Use `pip` to install deps"),
1388
    use_poetry: bool = Option(False, "--poetry", help="Use `poetry` to install deps"),
1389
    dry: bool = DryOption,
1390
) -> None:
1391
    """Run: ruff check/format to reformat code and then mypy to check"""
1392
    if use_uv + use_pdm + use_pip + use_poetry > 1:
×
1393
        raise UsageError("`--uv/--pdm/--pip/--poetry` can only choose one!")
×
UNCOV
1394
    if use_uv:
×
UNCOV
1395
        tool = "uv"
×
UNCOV
1396
    elif use_pdm:
×
UNCOV
1397
        tool = "pdm"
×
UNCOV
1398
    elif use_pip:
×
UNCOV
1399
        tool = "pip"
×
UNCOV
1400
    elif use_poetry:
×
UNCOV
1401
        tool = "poetry"
×
UNCOV
1402
    elif tool == ToolOption.default:
×
UNCOV
1403
        tool = Project.get_manage_tool(cache=True) or "pip"
×
UNCOV
1404
    MakeDeps(tool, prod, dry=dry).run()
×
1405

1406

1407
class UvPypi(DryRun):
6✔
1408
    PYPI = "https://pypi.org/simple"
6✔
1409
    HOST = "https://files.pythonhosted.org"
6✔
1410

1411
    def __init__(self, lock_file: Path, dry: bool, verbose: bool, quiet: bool) -> None:
6✔
1412
        super().__init__(dry=dry)
6✔
1413
        self.lock_file = lock_file
6✔
1414
        self._verbose = _ensure_bool(verbose)
6✔
1415
        self._quiet = _ensure_bool(quiet)
6✔
1416

1417
    def run(self) -> None:
6✔
1418
        try:
6✔
1419
            rc = self.update_lock(self.lock_file, self._verbose, self._quiet)
6✔
UNCOV
1420
        except ValueError as e:
×
UNCOV
1421
            secho(str(e), fg=typer.colors.RED)
×
UNCOV
1422
            raise Exit(1) from e
×
1423
        else:
1424
            if rc != 0:
6✔
1425
                raise Exit(rc)
6✔
1426

1427
    @classmethod
6✔
1428
    def update_lock(cls, p: Path, verbose: bool, quiet: bool) -> int:
6✔
1429
        text = p.read_text("utf-8")
6✔
1430
        registry_pattern = r'(registry = ")(.*?)"'
6✔
1431
        replace_registry = functools.partial(
6✔
1432
            re.sub, registry_pattern, rf'\1{cls.PYPI}"'
1433
        )
1434
        registry_urls = {i[1] for i in re.findall(registry_pattern, text)}
6✔
1435
        download_pattern = r'(url = ")(https?://.*?)(/packages/.*?\.)(gz|whl)"'
6✔
1436
        replace_host = functools.partial(
6✔
1437
            re.sub, download_pattern, rf'\1{cls.HOST}\3\4"'
1438
        )
1439
        download_hosts = {i[1] for i in re.findall(download_pattern, text)}
6✔
1440
        if not registry_urls:
6✔
1441
            raise ValueError(f"Failed to find pattern {registry_pattern!r} in {p}")
×
1442
        if len(registry_urls) == 1:
6✔
1443
            current_registry = registry_urls.pop()
6✔
1444
            if current_registry == cls.PYPI:
6✔
1445
                if download_hosts == {cls.HOST}:
6✔
1446
                    if verbose:
6✔
1447
                        echo(f"Registry of {p} is {cls.PYPI}, no need to change.")
×
1448
                    return 0
6✔
1449
            else:
1450
                text = replace_registry(text)
6✔
1451
                if verbose:
6✔
UNCOV
1452
                    echo(f"{current_registry} --> {cls.PYPI}")
×
1453
        else:
1454
            # TODO: ask each one to confirm replace
UNCOV
1455
            text = replace_registry(text)
×
1456
            if verbose:
×
1457
                for current_registry in sorted(registry_urls):
×
1458
                    echo(f"{current_registry} --> {cls.PYPI}")
×
1459
        if len(download_hosts) == 1:
6✔
1460
            current_host = download_hosts.pop()
6✔
1461
            if current_host != cls.HOST:
6✔
1462
                text = replace_host(text)
6✔
1463
                if verbose:
6✔
UNCOV
1464
                    print(current_host, "-->", cls.HOST)
×
UNCOV
1465
        elif download_hosts:
×
1466
            # TODO: ask each one to confirm replace
UNCOV
1467
            text = replace_host(text)
×
UNCOV
1468
            if verbose:
×
UNCOV
1469
                for current_host in sorted(download_hosts):
×
UNCOV
1470
                    echo(f"{current_host} --> {cls.HOST}")
×
1471
        size = p.write_text(text, encoding="utf-8")
6✔
1472
        if verbose:
6✔
UNCOV
1473
            echo(f"Updated {p} with {size} bytes.")
×
1474
        if quiet:
6✔
1475
            return 0
6✔
1476
        return 1
6✔
1477

1478

1479
@cli.command()
6✔
1480
def pypi(
6✔
1481
    file: Optional[str] = typer.Argument(default=None),
1482
    dry: bool = DryOption,
1483
    verbose: bool = False,
1484
    quiet: bool = False,
1485
) -> None:
1486
    """Change registry of uv.lock to be pypi.org"""
1487
    if not (p := Path(_ensure_str(file) or "uv.lock")).exists() and not (
6✔
1488
        (p := Project.get_work_dir() / p.name).exists()
1489
    ):
1490
        yellow_warn(f"{p.name!r} not found!")
6✔
1491
        return
6✔
1492
    UvPypi(p, dry, verbose, quiet).run()
6✔
1493

1494

1495
def version_callback(value: bool) -> None:
6✔
1496
    if value:
6✔
1497
        echo("Fast Dev Cli Version: " + typer.style(__version__, bold=True))
6✔
1498
        raise Exit()
6✔
1499

1500

1501
@cli.callback()
6✔
1502
def common(
6✔
1503
    version: bool = Option(
1504
        None,
1505
        "--version",
1506
        "-V",
1507
        callback=version_callback,
1508
        is_eager=True,
1509
        help="Show the version of this tool",
1510
    ),
1511
) -> None:
UNCOV
1512
    pass
×
1513

1514

1515
def main() -> None:
6✔
1516
    cli()
6✔
1517

1518

1519
if __name__ == "__main__":  # pragma: no cover
1520
    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