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

waketzheng / fast-dev-cli / 17573005466

09 Sep 2025 05:43AM UTC coverage: 91.392% (-0.1%) from 91.489%
17573005466

push

github

waketzheng
chore: upgrade deps

860 of 941 relevant lines covered (91.39%)

5.47 hits per line

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

91.38
/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
    """Basic exception of this library, all custom exceptions inherit from it"""
67

68

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

72

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

76

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

80

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

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

90
    return canonicalize_name(name).replace("-", "_").replace(" ", "_")
6✔
91

92

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

104

105
def yellow_warn(msg: str) -> None:
6✔
106
    secho(msg, fg="yellow")
6✔
107

108

109
def load_bool(name: str, default: bool = False) -> bool:
6✔
110
    if not (v := os.getenv(name)):
6✔
111
        return default
6✔
112
    if (lower := v.lower()) in ("0", "false", "f", "off", "no", "n"):
6✔
113
        return False
6✔
114
    elif lower in ("1", "true", "t", "on", "yes", "y"):
6✔
115
        return True
6✔
116
    secho(f"WARNING: can not convert value({v!r}) of {name} to bool!")
6✔
117
    return default
6✔
118

119

120
def is_venv() -> bool:
6✔
121
    """Whether in a virtual environment(also work for poetry)"""
122
    return hasattr(sys, "real_prefix") or (
6✔
123
        hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix
124
    )
125

126

127
def _run_shell(cmd: list[str] | str, **kw: Any) -> subprocess.CompletedProcess[str]:
6✔
128
    if isinstance(cmd, str):
6✔
129
        kw.setdefault("shell", True)
6✔
130
    return subprocess.run(cmd, **kw)  # nosec:B603
6✔
131

132

133
def run_and_echo(
6✔
134
    cmd: str, *, dry: bool = False, verbose: bool = True, **kw: Any
135
) -> int:
136
    """Run shell command with subprocess and print it"""
137
    if verbose:
6✔
138
        echo(f"--> {cmd}")
6✔
139
    if dry:
6✔
140
        return 0
6✔
141
    command: list[str] | str = cmd
6✔
142
    if "shell" not in kw and not (set(cmd) & {"|", ">", "&"}):
6✔
143
        command = shlex.split(cmd)
6✔
144
    return _run_shell(command, **kw).returncode
6✔
145

146

147
def check_call(cmd: str) -> bool:
6✔
148
    r = _run_shell(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
6✔
149
    return r.returncode == 0
6✔
150

151

152
def capture_cmd_output(
6✔
153
    command: list[str] | str, *, raises: bool = False, **kw: Any
154
) -> str:
155
    if isinstance(command, str) and not kw.get("shell"):
6✔
156
        command = shlex.split(command)
6✔
157
    r = _run_shell(command, capture_output=True, encoding="utf-8", **kw)
6✔
158
    if raises and r.returncode != 0:
6✔
159
        raise ShellCommandError(r.stderr)
6✔
160
    return r.stdout.strip() or r.stderr
6✔
161

162

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

166

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

202
    pattern = re.compile(r"__version__\s*=")
×
203
    for line in init_file.read_text("utf-8").splitlines():
×
204
        if pattern.match(line):
×
205
            return _parse_version(line, pattern)
×
206
    secho(f"WARNING: can not find '__version__' var in {init_file}!")
×
207
    return "0.0.0"
×
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[False] = False,
217
) -> str: ...
218

219

220
@overload
221
def get_current_version(
222
    verbose: bool = False,
223
    is_poetry: bool | None = None,
224
    package_name: str | None = None,
225
    *,
226
    check_version: Literal[True] = True,
227
) -> tuple[bool, str]: ...
228

229

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

266

267
def _ensure_bool(value: bool | OptionInfo) -> bool:
6✔
268
    if not isinstance(value, bool):
6✔
269
        value = getattr(value, "default", False)
6✔
270
    return value
6✔
271

272

273
def _ensure_str(value: str | OptionInfo | None) -> str:
6✔
274
    if not isinstance(value, str):
6✔
275
        value = getattr(value, "default", "")
6✔
276
    return value
6✔
277

278

279
def exit_if_run_failed(
6✔
280
    cmd: str,
281
    env: dict[str, str] | None = None,
282
    _exit: bool = False,
283
    dry: bool = False,
284
    **kw: Any,
285
) -> subprocess.CompletedProcess[str]:
286
    run_and_echo(cmd, dry=True)
6✔
287
    if _ensure_bool(dry):
6✔
288
        return subprocess.CompletedProcess("", 0)
6✔
289
    if env is not None:
6✔
290
        env = {**os.environ, **env}
6✔
291
    r = _run_shell(cmd, env=env, **kw)
6✔
292
    if rc := r.returncode:
6✔
293
        if _exit:
6✔
294
            sys.exit(rc)
6✔
295
        raise Exit(rc)
6✔
296
    return r
6✔
297

298

299
class DryRun:
6✔
300
    def __init__(self, _exit: bool = False, dry: bool = False) -> None:
6✔
301
        self.dry = _ensure_bool(dry)
6✔
302
        self._exit = _exit
6✔
303

304
    def gen(self) -> str:
6✔
305
        raise NotImplementedError
6✔
306

307
    def run(self) -> None:
6✔
308
        exit_if_run_failed(self.gen(), _exit=self._exit, dry=self.dry)
6✔
309

310

311
class BumpUp(DryRun):
6✔
312
    class PartChoices(StrEnum):
6✔
313
        patch = "patch"
6✔
314
        minor = "minor"
6✔
315
        major = "major"
6✔
316

317
    def __init__(
6✔
318
        self,
319
        commit: bool,
320
        part: str,
321
        filename: str | None = None,
322
        dry: bool = False,
323
        no_sync: bool = False,
324
        emoji: bool | None = None,
325
    ) -> None:
326
        self.commit = commit
6✔
327
        self.part = part
6✔
328
        if filename is None:
6✔
329
            filename = self.parse_filename()
6✔
330
        self.filename = filename
6✔
331
        self._no_sync = no_sync
6✔
332
        self._emoji = emoji
6✔
333
        super().__init__(dry=dry)
6✔
334

335
    @staticmethod
6✔
336
    def get_last_commit_message(raises: bool = False) -> str:
6✔
337
        cmd = 'git show --pretty=format:"%s" -s HEAD'
6✔
338
        return capture_cmd_output(cmd, raises=raises)
6✔
339

340
    @classmethod
6✔
341
    def should_add_emoji(cls) -> bool:
6✔
342
        """
343
        If last commit message is startswith emoji,
344
        add a ⬆️ flag at the prefix of bump up commit message.
345
        """
346
        try:
6✔
347
            first_char = cls.get_last_commit_message(raises=True)[0]
6✔
348
        except (IndexError, ShellCommandError):
6✔
349
            return False
6✔
350
        else:
351
            return is_emoji(first_char)
6✔
352

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

444
        return TOML_FILE
6✔
445

446
    def get_part(self, s: str) -> str:
6✔
447
        choices: dict[str, str] = {}
6✔
448
        for i, p in enumerate(self.PartChoices, 1):
6✔
449
            v = str(p)
6✔
450
            choices.update({str(i): v, v: v})
6✔
451
        try:
6✔
452
            return choices[s]
6✔
453
        except KeyError as e:
6✔
454
            echo(f"Invalid part: {s!r}")
6✔
455
            raise Exit(1) from e
6✔
456

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

484
    def run(self) -> None:
6✔
485
        super().run()
6✔
486
        if not self.commit and not self.dry:
6✔
487
            new_version = get_current_version(True)
6✔
488
            echo(new_version)
6✔
489
            if self.part != "patch":
6✔
490
                echo("You may want to pin tag by `fast tag`")
6✔
491

492

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

510

511
@cli.command(name="bump")
6✔
512
def bump_version(
6✔
513
    part: BumpUp.PartChoices,
514
    commit: bool = Option(
515
        False, "--commit", "-c", help="Whether run `git commit` after version changed"
516
    ),
517
    emoji: Optional[bool] = Option(
518
        None, "--emoji", help="Whether add emoji prefix to commit message"
519
    ),
520
    no_sync: bool = Option(
521
        False, "--no-sync", help="Do not run sync command to update version"
522
    ),
523
    dry: bool = DryOption,
524
) -> None:
525
    """Bump up version string in pyproject.toml"""
526
    if emoji is not None:
6✔
527
        emoji = _ensure_bool(emoji)
6✔
528
    return BumpUp(
6✔
529
        _ensure_bool(commit),
530
        getattr(part, "value", part),
531
        no_sync=_ensure_bool(no_sync),
532
        emoji=emoji,
533
        dry=dry,
534
    ).run()
535

536

537
def bump() -> None:
6✔
538
    part, commit = "", False
6✔
539
    if args := sys.argv[2:]:
6✔
540
        if "-c" in args or "--commit" in args:
6✔
541
            commit = True
6✔
542
        for a in args:
6✔
543
            if not a.startswith("-"):
6✔
544
                part = a
6✔
545
                break
6✔
546
    return BumpUp(commit, part, no_sync="--no-sync" in args, dry="--dry" in args).run()
6✔
547

548

549
class Project:
6✔
550
    path_depth = 5
6✔
551
    _tool: ToolName | None = None
6✔
552

553
    @staticmethod
6✔
554
    def is_poetry_v2(text: str) -> bool:
6✔
555
        return 'build-backend = "poetry' in text
6✔
556

557
    @staticmethod
6✔
558
    def work_dir(
6✔
559
        name: str, parent: Path, depth: int, be_file: bool = False
560
    ) -> Path | None:
561
        for _ in range(depth):
6✔
562
            if (f := parent.joinpath(name)).exists():
6✔
563
                if be_file:
6✔
564
                    return f
6✔
565
                return parent
6✔
566
            parent = parent.parent
6✔
567
        return None
6✔
568

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

584
    @classmethod
6✔
585
    def load_toml_text(cls: type[Self], name: str = TOML_FILE) -> str:
6✔
586
        toml_file = cls.get_work_dir(name, be_file=True)
6✔
587
        return toml_file.read_text("utf8")
6✔
588

589
    @classmethod
6✔
590
    def manage_by_poetry(cls: type[Self], cache: bool = False) -> bool:
6✔
591
        return cls.get_manage_tool(cache=cache) == "poetry"
6✔
592

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

629
    @staticmethod
6✔
630
    def python_exec_dir() -> Path:
6✔
631
        return Path(sys.executable).parent
6✔
632

633
    @classmethod
6✔
634
    def get_root_dir(cls: type[Self], cwd: Path | None = None) -> Path:
6✔
635
        root = cwd or Path.cwd()
6✔
636
        venv_parent = cls.python_exec_dir().parent.parent
6✔
637
        if root.is_relative_to(venv_parent):
6✔
638
            root = venv_parent
6✔
639
        return root
6✔
640

641
    @classmethod
6✔
642
    def is_pdm_project(cls, strict: bool = True, cache: bool = False) -> bool:
6✔
643
        if cls.get_manage_tool(cache=cache) != "pdm":
6✔
644
            return False
6✔
645
        if strict:
×
646
            lock_file = cls.get_work_dir() / "pdm.lock"
×
647
            return lock_file.exists()
×
648
        return True
×
649

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

671
    @classmethod
6✔
672
    def sync_dependencies(cls, prod: bool = True) -> None:
6✔
673
        if cmd := cls.get_sync_command():
×
674
            run_and_echo(cmd)
×
675

676

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

684
    class DevFlag(StrEnum):
6✔
685
        new = "[tool.poetry.group.dev.dependencies]"
6✔
686
        old = "[tool.poetry.dev-dependencies]"
6✔
687

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

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

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

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

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

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

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

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

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

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

853

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

868

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

875
    @staticmethod
6✔
876
    def has_v_prefix() -> bool:
6✔
877
        return "v" in capture_cmd_output("git tag")
6✔
878

879
    def should_push(self) -> bool:
6✔
880
        return "git push" in self.git_status
6✔
881

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

894
    @cached_property
6✔
895
    def git_status(self) -> str:
6✔
896
        return capture_cmd_output("git status")
6✔
897

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

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

911

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

923

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

946
    @staticmethod
6✔
947
    def check_lint_tool_installed() -> bool:
6✔
948
        return check_call("ruff --version")
6✔
949

950
    @staticmethod
6✔
951
    def missing_mypy_exec() -> bool:
6✔
952
        return shutil.which("mypy") is None
6✔
953

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

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

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

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

1074

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

1078

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

1102

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

1122

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

1156

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

1166

1167
class Sync(DryRun):
6✔
1168
    def __init__(
6✔
1169
        self, filename: str, extras: str, save: bool, dry: bool = False
1170
    ) -> None:
1171
        self.filename = filename
6✔
1172
        self.extras = extras
6✔
1173
        self._save = save
6✔
1174
        super().__init__(dry=dry)
6✔
1175

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

1205

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

1218

1219
def _should_run_test_script(path: Path = Path("scripts")) -> Path | None:
6✔
1220
    for name in ("test.sh", "test.py"):
6✔
1221
        if (file := path / name).exists():
6✔
1222
            return file
6✔
1223
    return None
6✔
1224

1225

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

1244

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

1253

1254
class Publish:
6✔
1255
    class CommandEnum(StrEnum):
6✔
1256
        poetry = "poetry publish --build"
6✔
1257
        pdm = "pdm publish"
6✔
1258
        uv = "uv build && uv publish"
6✔
1259
        twine = "python -m build && twine upload"
6✔
1260

1261
    @classmethod
6✔
1262
    def gen(cls) -> str:
6✔
1263
        if tool := Project.get_manage_tool():
6✔
1264
            return cls.CommandEnum[tool]
6✔
1265
        return cls.CommandEnum.twine
6✔
1266

1267

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

1276

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

1303

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

1317

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

1332

1333
class MakeDeps(DryRun):
6✔
1334
    def __init__(self, tool: str, prod: bool = False, dry: bool = False) -> None:
6✔
1335
        self._tool = tool
6✔
1336
        self._prod = prod
6✔
1337
        super().__init__(dry=dry)
6✔
1338

1339
    def should_ensure_pip(self) -> bool:
6✔
1340
        return True
6✔
1341

1342
    def should_upgrade_pip(self) -> bool:
6✔
1343
        return True
×
1344

1345
    def get_groups(self) -> list[str]:
6✔
1346
        if self._prod:
6✔
1347
            return []
6✔
1348
        return ["dev"]
6✔
1349

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

1372

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

1402

1403
class UvPypi(DryRun):
6✔
1404
    PYPI = "https://pypi.org/simple"
6✔
1405
    HOST = "https://files.pythonhosted.org"
6✔
1406

1407
    def __init__(self, lock_file: Path, dry: bool, verbose: bool, quiet: bool) -> None:
6✔
1408
        super().__init__(dry=dry)
6✔
1409
        self.lock_file = lock_file
6✔
1410
        self._verbose = _ensure_bool(verbose)
6✔
1411
        self._quiet = _ensure_bool(quiet)
6✔
1412

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

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

1474

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

1490

1491
def version_callback(value: bool) -> None:
6✔
1492
    if value:
6✔
1493
        echo("Fast Dev Cli Version: " + typer.style(__version__, bold=True))
6✔
1494
        raise Exit()
6✔
1495

1496

1497
@cli.callback()
1498
def common(
1499
    version: bool = Option(
1500
        None,
1501
        "--version",
1502
        "-V",
1503
        callback=version_callback,
1504
        is_eager=True,
1505
        help="Show the version of this tool",
1506
    ),
1507
) -> None: ...
1508

1509

1510
def main() -> None:
6✔
1511
    cli()
6✔
1512

1513

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