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

waketzheng / fast-dev-cli / 28276263691

27 Jun 2026 02:38AM UTC coverage: 85.507% (+0.2%) from 85.342%
28276263691

push

github

waketzheng
refactor: break down long function into smaller units

44 of 51 new or added lines in 1 file covered. (86.27%)

1062 of 1242 relevant lines covered (85.51%)

4.27 hits per line

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

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

3
import contextlib
5✔
4
import functools
5✔
5
import importlib.metadata as importlib_metadata
5✔
6
import os
5✔
7
import platform
5✔
8
import re
5✔
9
import shlex
5✔
10
import shutil
5✔
11
import subprocess  # nosec:B404
5✔
12
import sys
5✔
13
from functools import cached_property
5✔
14
from pathlib import Path
5✔
15
from typing import TYPE_CHECKING, Any, Literal, cast, get_args, overload
5✔
16

17
import typer
5✔
18
from typer import Exit, Option, echo, secho
5✔
19
from typer.models import ArgumentInfo, OptionInfo
5✔
20

21
try:
5✔
22
    from . import __version__
5✔
23
except ImportError:  # pragma: no cover
24
    from importlib import import_module as _import  # For local unittest
25

26
    __version__ = _import(Path(__file__).parent.name).__version__
27

28
if sys.version_info >= (3, 11):  # pragma: no cover
29
    from enum import StrEnum
30

31
    import tomllib
32
else:  # pragma: no cover
33
    from enum import Enum
34

35
    import tomli as tomllib
36

37
    class StrEnum(str, Enum):
38
        __str__ = str.__str__
39

40

41
if TYPE_CHECKING:
42
    if sys.version_info >= (3, 11):
43
        from typing import Self
44
    else:
45
        from typing_extensions import Self
46

47
cli = typer.Typer(no_args_is_help=True)
5✔
48
DryOption = Option(False, "--dry", help="Only print, not really run shell command")
5✔
49
TOML_FILE = "pyproject.toml"
5✔
50
ToolName = Literal["uv", "pdm", "poetry"]
5✔
51
ToolOption = Option(
5✔
52
    "auto", "--tool", help="Explicit declare manage tool (default to auto detect)"
53
)
54

55

56
class FastDevCliError(Exception):
5✔
57
    """Basic exception of this library, all custom exceptions inherit from it"""
58

59

60
class ShellCommandError(FastDevCliError):
5✔
61
    """Raise if cmd command returncode is not zero"""
62

63

64
class ParseError(FastDevCliError):
5✔
65
    """Raise this if parse dependence line error"""
66

67

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

71

72
def poetry_module_name(name: str) -> str:
5✔
73
    """Get module name that generated by `poetry new`"""
74
    try:
5✔
75
        from packaging.utils import canonicalize_name
5✔
76
    except ImportError:
×
77
        module_name = re.sub(r"[-_.]+", "-", name)
×
78
    else:
79
        module_name = canonicalize_name(name)
5✔
80
    return module_name.replace("-", "_").replace(" ", "_")
5✔
81

82

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

94

95
@functools.cache
5✔
96
def is_windows() -> bool:
5✔
97
    return platform.system() == "Windows"
5✔
98

99

100
@functools.cache
5✔
101
def prefer_uv_tool() -> bool:
5✔
102
    if shutil.which("uv") is None:
5✔
103
        return False
×
104
    cmd = "uv tool list"
5✔
105
    return Shell(cmd).capture_output() != "No tools installed"
5✔
106

107

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

113

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

124

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

131

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

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

145
    @property
5✔
146
    def command(self) -> list[str] | str:
5✔
147
        command: list[str] | str = self._cmd
5✔
148
        if isinstance(command, str):
5✔
149
            cs = shlex.split(command)
5✔
150
            if "shell" not in self._kw and not (set(self._cmd) & {"|", ">", "&"}):
5✔
151
                command = self.extend_user(cs)
5✔
152
            elif any(i.startswith("~") for i in cs):
5✔
153
                command = re.sub(r" ~", " " + os.path.expanduser("~"), command)
×
154
        else:
155
            command = self.extend_user(command)
5✔
156
        return command
5✔
157

158
    @staticmethod
5✔
159
    def extend_user(cs: list[str]) -> list[str]:
5✔
160
        if cs[0] == "echo":
5✔
161
            return cs
5✔
162
        for i, c in enumerate(cs):
5✔
163
            if c.startswith("~"):
5✔
164
                cs[i] = os.path.expanduser(c)
×
165
        return cs
5✔
166

167
    def _run(self) -> subprocess.CompletedProcess[str]:
5✔
168
        return self.run_by_subprocess(self.command, **self._kw)
5✔
169

170
    def run(self, verbose: bool = False, dry: bool = False) -> int:
5✔
171
        if verbose:
5✔
172
            echo(f"--> {self._cmd}")
5✔
173
        if dry:
5✔
174
            return 0
5✔
175
        return self._run().returncode
5✔
176

177
    def check_call(self) -> bool:
5✔
178
        self._kw.update(stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
5✔
179
        try:
5✔
180
            return self.run() == 0
5✔
181
        except FileNotFoundError:
×
182
            return False
×
183

184
    def capture_output(self, raises: bool = False) -> str:
5✔
185
        self._kw.update(capture_output=True, encoding="utf-8")
5✔
186
        r = self._run()
5✔
187
        if raises and r.returncode != 0:
5✔
188
            raise ShellCommandError(r.stderr)
5✔
189
        return (r.stdout or r.stderr or "").strip()
5✔
190

191
    def finish(
5✔
192
        self, env: dict[str, str] | None = None, _exit: bool = False, dry: bool = False
193
    ) -> subprocess.CompletedProcess[str]:
194
        self.run(verbose=True, dry=True)
5✔
195
        if _ensure_bool(dry):
5✔
196
            return subprocess.CompletedProcess("", 0)
5✔
197
        if env is not None:
5✔
198
            self._kw["env"] = {**os.environ, **env}
5✔
199
        r = self._run()
5✔
200
        if rc := r.returncode:
5✔
201
            if _exit:
5✔
202
                sys.exit(rc)
5✔
203
            raise Exit(rc)
5✔
204
        return r
5✔
205

206

207
def run_and_echo(
5✔
208
    cmd: str, *, dry: bool = False, verbose: bool = True, **kw: Any
209
) -> int:
210
    """Run shell command with subprocess and print it"""
211
    return Shell(cmd, **kw).run(verbose=verbose, dry=dry)
5✔
212

213

214
def check_call(cmd: str) -> bool:
5✔
215
    return Shell(cmd).check_call()
5✔
216

217

218
def capture_cmd_output(
5✔
219
    command: list[str] | str, *, raises: bool = False, **kw: Any
220
) -> str:
221
    return Shell(command, **kw).capture_output(raises=raises)
5✔
222

223

224
def exit_if_run_failed(
5✔
225
    cmd: str,
226
    env: dict[str, str] | None = None,
227
    _exit: bool = False,
228
    dry: bool = False,
229
    **kw: Any,
230
) -> subprocess.CompletedProcess[str]:
231
    return Shell(cmd, **kw).finish(env=env, _exit=_exit, dry=dry)
5✔
232

233

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

237

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

273
    pattern = re.compile(r"__version__\s*=")
×
274
    for line in init_file.read_text("utf-8").splitlines():
×
275
        if pattern.match(line):
×
276
            return _parse_version(line, pattern)
×
277
    secho(f"WARNING: can not find '__version__' var in {init_file}!")
×
278
    return "0.0.0"
×
279

280

281
def _get_frontend_version() -> tuple[Path, str] | None:
5✔
282
    try:
×
283
        frontend_version_file = Project.get_work_dir("package.json", be_file=True)
×
284
    except EnvError:
×
285
        return None
×
286
    try:
×
287
        from asynctor.jsons import json_loads
×
288
    except ImportError:
×
289
        from json import loads as json_loads  # type:ignore[assignment]
×
290
    content = frontend_version_file.read_bytes()
×
291
    metadata: dict[str, str] = json_loads(content)  # type:ignore
×
292
    try:
×
293
        current_version = metadata["version"]
×
294
    except (KeyError, TypeError):
×
295
        return None
×
296
    with contextlib.suppress(ValueError):
×
297
        frontend_version_file = frontend_version_file.relative_to(Path.cwd())
×
298
    return frontend_version_file, current_version
×
299

300

301
@overload
302
def get_current_version(
303
    verbose: bool = False,
304
    is_poetry: bool | None = None,
305
    package_name: str | None = None,
306
    *,
307
    check_version: Literal[False] = False,
308
) -> str: ...
309

310

311
@overload
312
def get_current_version(
313
    verbose: bool = False,
314
    is_poetry: bool | None = None,
315
    package_name: str | None = None,
316
    *,
317
    check_version: Literal[True],
318
) -> tuple[bool, str]: ...
319

320

321
def get_current_version(
5✔
322
    verbose: bool = False,
323
    is_poetry: bool | None = None,
324
    package_name: str | None = None,
325
    *,
326
    check_version: bool = False,
327
) -> str | tuple[bool, str]:
328
    if is_poetry is True or Project.manage_by_poetry():
5✔
329
        cmd = ["poetry", "version", "-s"]
5✔
330
        if verbose:
5✔
331
            echo(f"--> {' '.join(cmd)}")
5✔
332
        if out := capture_cmd_output(cmd, raises=True):
5✔
333
            out = out.splitlines()[-1].strip().split()[-1]
5✔
334
        if check_version:
5✔
335
            return True, out
5✔
336
        return out
5✔
337
    toml_text = work_dir = None
5✔
338
    if package_name is None:
5✔
339
        try:
5✔
340
            work_dir = Project.get_work_dir()
5✔
341
        except EnvError as e:
×
342
            if (res := _get_frontend_version()) is None:
×
343
                raise e
×
344
            current_version = res[1]
×
345
            if check_version:
×
346
                return False, current_version
×
347
            return current_version
×
348
        else:
349
            toml_text = Project.load_toml_text()
5✔
350
            doc = tomllib.loads(toml_text)
5✔
351
            project_name = doc.get("project", {}).get("name", work_dir.name)
5✔
352
            package_name = re.sub(r"[- ]", "_", project_name)
5✔
353
    local_version = read_version_from_file(package_name, work_dir, toml_text)
5✔
354
    try:
5✔
355
        installed_version = importlib_metadata.version(package_name)
5✔
356
    except importlib_metadata.PackageNotFoundError:
5✔
357
        installed_version = ""
5✔
358
    current_version = local_version or installed_version
5✔
359
    if not current_version:
5✔
360
        raise FastDevCliError(f"Failed to get current version of {package_name!r}")
×
361
    if check_version:
5✔
362
        is_conflict = bool(local_version) and local_version != installed_version
5✔
363
        return is_conflict, current_version
5✔
364
    return current_version
5✔
365

366

367
def _ensure_bool(value: bool | OptionInfo) -> bool:
5✔
368
    if isinstance(value, bool):
5✔
369
        return value
5✔
370
    return bool(getattr(value, "default", False))
5✔
371

372

373
def _ensure_str(value: str | OptionInfo | None) -> str | None:
5✔
374
    if isinstance(value, str) or value is None:
5✔
375
        return value
5✔
376
    return getattr(value, "default", "")
5✔
377

378

379
class DryRun:
5✔
380
    def __init__(self, _exit: bool = False, dry: bool = False) -> None:
5✔
381
        self.dry = _ensure_bool(dry)
5✔
382
        self._exit = _exit
5✔
383

384
    def gen(self) -> str:
5✔
385
        raise NotImplementedError
5✔
386

387
    def run(self) -> None:
5✔
388
        exit_if_run_failed(self.gen(), _exit=self._exit, dry=self.dry)
5✔
389

390

391
class BumpUp(DryRun):
5✔
392
    class PartChoices(StrEnum):
5✔
393
        patch = "patch"
5✔
394
        minor = "minor"
5✔
395
        major = "major"
5✔
396

397
    def __init__(
5✔
398
        self,
399
        commit: bool,
400
        part: str,
401
        filename: str | None = None,
402
        dry: bool = False,
403
        no_sync: bool = False,
404
        emoji: bool | None = None,
405
    ) -> None:
406
        self.commit = commit
5✔
407
        self.part = part
5✔
408
        if filename is None:
5✔
409
            try:
5✔
410
                filename = self.parse_filename()
5✔
411
            except EnvError:
5✔
412
                if (res := _get_frontend_version()) is not None:
×
413
                    filename = res[0].name
×
414
                else:
415
                    raise
×
416
        self.filename = filename
5✔
417
        self._no_sync = no_sync
5✔
418
        self._emoji = emoji
5✔
419
        super().__init__(dry=dry)
5✔
420

421
    @staticmethod
5✔
422
    def get_last_commit_message(raises: bool = False) -> str:
5✔
423
        cmd = 'git show --pretty=format:"%s" -s HEAD'
5✔
424
        return capture_cmd_output(cmd, raises=raises)
5✔
425

426
    @classmethod
5✔
427
    def should_add_emoji(cls) -> bool:
5✔
428
        """
429
        If last commit message is startswith emoji,
430
        add a ⬆️ flag at the prefix of bump up commit message.
431
        """
432
        try:
5✔
433
            first_char = cls.get_last_commit_message(raises=True)[0]
5✔
434
        except (IndexError, ShellCommandError):
5✔
435
            return False
5✔
436
        else:
437
            return is_emoji(first_char)
5✔
438

439
    @staticmethod
5✔
440
    def parse_dynamic_version(
5✔
441
        toml_text: str,
442
        context: dict[str, Any],
443
        work_dir: Path | None = None,
444
    ) -> str | None:
445
        if work_dir is None:
5✔
446
            work_dir = Project.get_work_dir()
5✔
447
        for tool in ("pdm", "hatch"):
5✔
448
            with contextlib.suppress(KeyError):
5✔
449
                version_path = cast(str, context["tool"][tool]["version"]["path"])
5✔
450
                if (
5✔
451
                    Path(version_path).exists()
452
                    or work_dir.joinpath(version_path).exists()
453
                ):
454
                    return version_path
5✔
455
        # version = { source = "file", path = "fast_dev_cli/__init__.py" }
456
        v_key = "version = "
5✔
457
        p_key = 'path = "'
5✔
458
        for line in toml_text.splitlines():
5✔
459
            if not line.startswith(v_key):
×
460
                continue
×
461
            if p_key in (value := line.split(v_key, 1)[-1].split("#")[0]):
×
462
                filename = value.split(p_key, 1)[-1].split('"')[0]
×
463
                if work_dir.joinpath(filename).exists():
×
464
                    return filename
×
465
        return None
5✔
466

467
    @classmethod
5✔
468
    def parse_filename(
5✔
469
        cls,
470
        toml_text: str | None = None,
471
        work_dir: Path | None = None,
472
        package_name: str | None = None,
473
    ) -> str:
474
        if toml_text is None:
5✔
475
            toml_text = Project.load_toml_text()
5✔
476
        context = tomllib.loads(toml_text)
5✔
477
        by_version_plugin = False
5✔
478
        try:
5✔
479
            ver = context["project"]["version"]
5✔
480
        except KeyError:
5✔
481
            pass
5✔
482
        else:
483
            if isinstance(ver, str):
5✔
484
                if ver in ("0", "0.0.0"):
5✔
485
                    by_version_plugin = True
5✔
486
                elif re.match(r"\d+\.\d+\.\d+", ver):
5✔
487
                    return TOML_FILE
5✔
488
        if not by_version_plugin:
5✔
489
            try:
5✔
490
                version_value = context["tool"]["poetry"]["version"]
5✔
491
            except KeyError:
5✔
492
                if not Project.manage_by_poetry() and (
5✔
493
                    filename := cls.parse_dynamic_version(toml_text, context, work_dir)
494
                ):
495
                    return filename
5✔
496
            else:
497
                by_version_plugin = version_value in ("0", "0.0.0", "init")
5✔
498
        if by_version_plugin:
5✔
499
            return cls.parse_plugin_version(context, package_name)
5✔
500

501
        return TOML_FILE
5✔
502

503
    @staticmethod
5✔
504
    def parse_plugin_version(context: dict[str, Any], package_name: str | None) -> str:
5✔
505
        try:
5✔
506
            package_item = context["tool"]["poetry"]["packages"]
5✔
507
        except KeyError:
5✔
508
            try:
5✔
509
                project_name = context["project"]["name"]
5✔
510
            except KeyError:
5✔
511
                packages: list[tuple[str, str]] = []
5✔
512
            else:
513
                packages = [(poetry_module_name(project_name), "")]
×
514
        else:
515
            packages = [
5✔
516
                (j, i.get("from", "")) for i in package_item if (j := i.get("include"))
517
            ]
518
        # In case of managed by `poetry-plugin-version`
519
        cwd = Path.cwd()
5✔
520
        pattern = re.compile(r"__version__\s*=\s*['\"]")
5✔
521
        ds: list[Path] = []
5✔
522
        if package_name is not None:
5✔
523
            packages.insert(0, (package_name, ""))
×
524
        for package_name, source_dir in packages:
5✔
525
            ds.append(cwd / package_name)
5✔
526
            ds.append(cwd / "src" / package_name)
5✔
527
            if source_dir and source_dir != "src":
5✔
528
                ds.append(cwd / source_dir / package_name)
5✔
529
        module_name = poetry_module_name(cwd.name)
5✔
530
        ds.extend([cwd / module_name, cwd / "src" / module_name, cwd])
5✔
531
        for d in ds:
5✔
532
            init_file = d / "__init__.py"
5✔
533
            if (init_file.exists() and pattern.search(init_file.read_text("utf8"))) or (
5✔
534
                (init_file := init_file.with_name("__version__.py")).exists()
535
                and pattern.search(init_file.read_text("utf8"))
536
            ):
537
                break
5✔
538
        else:
539
            raise ParseError("Version file not found! Where are you now?")
5✔
540
        return os.path.relpath(init_file, cwd)
5✔
541

542
    def get_part(self, s: str) -> str:
5✔
543
        choices: dict[str, str] = {}
5✔
544
        for i, p in enumerate(self.PartChoices, 1):
5✔
545
            v = str(p)
5✔
546
            choices.update({str(i): v, v: v})
5✔
547
        try:
5✔
548
            return choices[s]
5✔
549
        except KeyError as e:
5✔
550
            echo(f"Invalid part: {s!r}")
5✔
551
            raise Exit(1) from e
5✔
552

553
    def gen(self) -> str:
5✔
554
        should_sync, _version = get_current_version(check_version=True)
5✔
555
        filename = self.filename
5✔
556
        echo(f"Current version(@{filename}): {_version}")
5✔
557
        if self.part:
5✔
558
            part = self.get_part(self.part)
5✔
559
        else:
560
            part = "patch"
5✔
561
            if a := input("Which one?").strip():
5✔
562
                part = self.get_part(a)
5✔
563
        self.part = part
5✔
564
        parse = r'--parse "(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)"'
5✔
565
        cmd = f'bumpversion {parse} --current-version="{_version}" {part} {filename}'
5✔
566
        if self.commit:
5✔
567
            if part != "patch":
5✔
568
                cmd += " --tag"
5✔
569
            cmd += " --commit"
5✔
570
            if self._emoji or (self._emoji is None and self.should_add_emoji()):
5✔
571
                cmd += " --message-emoji=1"
5✔
572
            if not load_bool("DONT_GIT_PUSH"):
5✔
573
                cmd += " && git push && git push --tags && git log -1"
5✔
574
        else:
575
            cmd += " --allow-dirty"
5✔
576
        if (
5✔
577
            should_sync
578
            and not self._no_sync
579
            and (sync := Project.get_sync_command(only_me=True))
580
        ):
581
            cmd = f"{sync} && " + cmd
5✔
582
        return cmd
5✔
583

584
    def run(self) -> None:
5✔
585
        super().run()
5✔
586
        if not self.commit and not self.dry:
5✔
587
            new_version = get_current_version(True)
5✔
588
            echo(new_version)
5✔
589
            if self.part != "patch":
5✔
590
                echo("You may want to pin tag by `fast tag`")
5✔
591

592

593
def _echo_version(version_file: Any, value: str) -> None:
5✔
594
    styled = typer.style(value, bold=True)
5✔
595
    echo(f"Version value in {version_file}: " + styled)
5✔
596

597

598
@cli.command()
5✔
599
def version() -> None:
5✔
600
    """Show the version of this tool"""
601
    echo("Fast Dev Cli Version: " + typer.style(__version__, fg=typer.colors.BLUE))
5✔
602
    with contextlib.suppress(FileNotFoundError, KeyError):
5✔
603
        try:
5✔
604
            toml_text = Project.load_toml_text()
5✔
605
        except EnvError:
×
606
            if (res := _get_frontend_version()) is not None:
×
607
                _echo_version(*res)
×
608
                return
×
609
            raise
×
610
        doc = tomllib.loads(toml_text)
5✔
611
        if value := doc.get("project", {}).get("version", ""):
5✔
612
            styled = typer.style(value, bold=True, fg=typer.colors.CYAN)
×
613
            if project_name := doc["project"].get("name", ""):
×
614
                echo(f"{project_name} version: " + styled)
×
615
            else:
616
                echo(f"Got Version from {TOML_FILE}: " + styled)
×
617
            return
×
618
        version_file = doc["tool"]["pdm"]["version"]["path"]
5✔
619
        text = Project.get_work_dir().joinpath(version_file).read_text(encoding="utf-8")
5✔
620
        varname = "__version__"
5✔
621
        for line in text.splitlines():
5✔
622
            if line.strip().startswith(varname):
5✔
623
                value = line.split("=", 1)[-1].strip().strip('"').strip("'")
5✔
624
                _echo_version(version_file, value)
5✔
625
                break
5✔
626

627

628
@cli.command(name="bump")
5✔
629
def bump_version(
5✔
630
    part: BumpUp.PartChoices,
631
    commit: bool = Option(
632
        False, "--commit", "-c", help="Whether run `git commit` after version changed"
633
    ),
634
    emoji: bool | None = Option(
635
        None, "--emoji", help="Whether add emoji prefix to commit message"
636
    ),
637
    no_sync: bool = Option(
638
        False, "--no-sync", help="Do not run sync command to update version"
639
    ),
640
    dry: bool = DryOption,
641
) -> None:
642
    """Bump up version string in pyproject.toml"""
643
    if emoji is not None:
5✔
644
        emoji = _ensure_bool(emoji)
5✔
645
    return BumpUp(
5✔
646
        _ensure_bool(commit),
647
        getattr(part, "value", part),
648
        no_sync=_ensure_bool(no_sync),
649
        emoji=emoji,
650
        dry=dry,
651
    ).run()
652

653

654
def bump() -> None:
5✔
655
    part, commit = "", False
5✔
656
    if args := sys.argv[2:]:
5✔
657
        if "-c" in args or "--commit" in args:
5✔
658
            commit = True
5✔
659
        for a in args:
5✔
660
            if not a.startswith("-"):
5✔
661
                part = a
5✔
662
                break
5✔
663
    return BumpUp(commit, part, no_sync="--no-sync" in args, dry="--dry" in args).run()
5✔
664

665

666
class Project:
5✔
667
    path_depth = 5
5✔
668
    _tool: ToolName | None = None
5✔
669

670
    @staticmethod
5✔
671
    def is_poetry_v2(text: str) -> bool:
5✔
672
        return 'build-backend = "poetry' in text
5✔
673

674
    @staticmethod
5✔
675
    def get_poetry_version(command: str = "poetry") -> str:
5✔
676
        pattern = r"(\d+\.\d+\.\d+)"
5✔
677
        text = capture_cmd_output(f"{command} --version")
5✔
678
        for expr in (
5✔
679
            rf"Poetry \(version {pattern}\)",
680
            rf"Poetry.*version.*{pattern}.*\)",
681
            rf"{pattern}",
682
        ):
683
            if m := re.search(expr, text):
5✔
684
                return m.group(1)
5✔
685
        return ""
×
686

687
    @staticmethod
5✔
688
    def work_dir(
5✔
689
        name: str, parent: Path, depth: int, be_file: bool = False
690
    ) -> Path | None:
691
        for _ in range(depth):
5✔
692
            if (f := parent.joinpath(name)).exists():
5✔
693
                if be_file:
5✔
694
                    return f
5✔
695
                return parent
5✔
696
            parent = parent.parent
5✔
697
        return None
5✔
698

699
    @classmethod
5✔
700
    def get_work_dir(
5✔
701
        cls: type[Self],
702
        name: str = TOML_FILE,
703
        cwd: Path | None = None,
704
        allow_cwd: bool = False,
705
        be_file: bool = False,
706
    ) -> Path:
707
        cwd = cwd or Path.cwd()
5✔
708
        if d := cls.work_dir(name, cwd, cls.path_depth, be_file):
5✔
709
            return d
5✔
710
        if allow_cwd:
5✔
711
            return cls.get_root_dir(cwd)
5✔
712
        raise EnvError(f"{name} not found! Make sure this is a python project.")
5✔
713

714
    @classmethod
5✔
715
    def load_toml_text(cls: type[Self], name: str = TOML_FILE) -> str:
5✔
716
        toml_file = cls.get_work_dir(name, be_file=True)
5✔
717
        return toml_file.read_text("utf8")
5✔
718

719
    @classmethod
5✔
720
    def manage_by_poetry(cls: type[Self], cache: bool = False) -> bool:
5✔
721
        return cls.get_manage_tool(cache=cache) == "poetry"
5✔
722

723
    @classmethod
5✔
724
    def get_manage_tool(cls: type[Self], cache: bool = False) -> ToolName | None:
5✔
725
        if cache and cls._tool:
5✔
726
            return cls._tool
5✔
727
        try:
5✔
728
            text = cls.load_toml_text()
5✔
729
        except EnvError:
5✔
730
            return None
5✔
731
        backend = ""
5✔
732
        skip_uv = load_bool("FASTDEVCLI_SKIP_UV")
5✔
733
        with contextlib.suppress(KeyError, tomllib.TOMLDecodeError):
5✔
734
            doc = tomllib.loads(text)
5✔
735
            backend = doc["build-system"]["build-backend"]
5✔
736
            if skip_uv:
5✔
737
                for t in ("pdm", "poetry"):
×
738
                    if t in backend:
×
739
                        cls._tool = t
×
740
                        return cls._tool
×
741
        return cls._get_manage_tool(text, backend, skip_uv)
5✔
742

743
    @classmethod
5✔
744
    def _get_manage_tool(
5✔
745
        cls: type[Self], text: str, backend: str, skip_uv: bool
746
    ) -> ToolName | None:
747
        work_dir: Path | None = None
5✔
748
        uv_lock_exists: bool | None = None
5✔
749
        if skip_uv:
5✔
750
            for name in ("pdm", "poetry"):
×
751
                if f"[tool.{name}]" in text:
×
752
                    cls._tool = cast(ToolName, name)
×
753
                    return cls._tool
×
754
            work_dir = cls.get_work_dir(allow_cwd=True)
×
755
            for name in ("pdm", "poetry"):
×
756
                if Path(work_dir, f"{name}.lock").exists():
×
757
                    cls._tool = cast(ToolName, name)
×
758
                    return cls._tool
×
759
            if uv_lock_exists := Path(work_dir, "uv.lock").exists():
×
760
                # Use pdm when uv is not available for uv managed project
761
                cls._tool = "pdm"
×
762
                return cls._tool
×
763
            return None
×
764
        if work_dir is None:
5✔
765
            work_dir = cls.get_work_dir(allow_cwd=True)
5✔
766
        if uv_lock_exists is None:
5✔
767
            uv_lock_exists = Path(work_dir, "uv.lock").exists()
5✔
768
        if uv_lock_exists:
5✔
769
            cls._tool = "uv"
5✔
770
            return cls._tool
5✔
771
        return cls._parse_manage_tool(work_dir, text, backend)
5✔
772

773
    @classmethod
5✔
774
    def _parse_manage_tool(
5✔
775
        cls: type[Self], work_dir: Path, text: str, backend: str
776
    ) -> ToolName | None:
777
        pdm_lock_exists = Path(work_dir, "pdm.lock").exists()
5✔
778
        poetry_lock_exists = Path(work_dir, "poetry.lock").exists()
5✔
779
        match pdm_lock_exists + poetry_lock_exists:
5✔
780
            case 1:
5✔
781
                cls._tool = "pdm" if pdm_lock_exists else "poetry"
×
782
                return cls._tool
×
783
            case _ as x:
5✔
784
                if backend:
5✔
785
                    for t in ("pdm", "poetry"):
5✔
786
                        if t in backend:
5✔
787
                            cls._tool = cast(ToolName, t)
5✔
788
                            return cls._tool
5✔
789
                for name in ("pdm", "poetry"):
5✔
790
                    if f"[tool.{name}]" in text:
5✔
791
                        cls._tool = cast(ToolName, name)
5✔
792
                        return cls._tool
5✔
793
                if x == 2:
5✔
794
                    cls._tool = (
×
795
                        "poetry" if load_bool("FASTDEVCLI_PREFER_POETRY") else "pdm"
796
                    )
797
                    return cls._tool
1✔
798
        if "[tool.uv]" in text or load_bool("FASTDEVCLI_PREFER_uv"):
5✔
799
            cls._tool = "uv"
5✔
800
            return cls._tool
5✔
801
        # Poetry 2.0 default to not include the '[tool.poetry]' section
802
        if cls.is_poetry_v2(text):
5✔
803
            cls._tool = "poetry"
×
804
            return cls._tool
×
805
        return None
5✔
806

807
    @staticmethod
5✔
808
    def python_exec_dir() -> Path:
5✔
809
        return Path(sys.executable).parent
5✔
810

811
    @classmethod
5✔
812
    def get_root_dir(cls: type[Self], cwd: Path | None = None) -> Path:
5✔
813
        root = cwd or Path.cwd()
5✔
814
        venv_parent = cls.python_exec_dir().parent.parent
5✔
815
        if root.is_relative_to(venv_parent):
5✔
816
            root = venv_parent
5✔
817
        return root
5✔
818

819
    @classmethod
5✔
820
    def is_pdm_project(cls, strict: bool = True, cache: bool = False) -> bool:
5✔
821
        if cls.get_manage_tool(cache=cache) != "pdm":
5✔
822
            return False
5✔
823
        if strict:
×
824
            lock_file = cls.get_work_dir() / "pdm.lock"
×
825
            return lock_file.exists()
×
826
        return True
×
827

828
    @classmethod
5✔
829
    def get_sync_command(
5✔
830
        cls, prod: bool = True, doc: dict[str, Any] | None = None, only_me: bool = False
831
    ) -> str:
832
        pdm_i = "pdm install --frozen" + " --prod" * prod
5✔
833
        if cls.is_pdm_project():
5✔
834
            return pdm_i
×
835
        elif cls.manage_by_poetry(cache=True):
5✔
836
            cmd = "poetry install"
5✔
837
            if prod:
5✔
838
                if doc is None:
5✔
839
                    doc = tomllib.loads(cls.load_toml_text())
5✔
840
                if doc.get("project", {}).get("dependencies") or any(
5✔
841
                    i != "python"
842
                    for i in doc.get("tool", {})
843
                    .get("poetry", {})
844
                    .get("dependencies", [])
845
                ):
846
                    cmd += " --only=main"
×
847
            return cmd
5✔
848
        elif cls.get_manage_tool(cache=True) == "uv":
×
849
            install_me = "uv pip install -e ."
×
850
            if doc is None:
×
851
                doc = tomllib.loads(cls.load_toml_text())
×
852
            is_distribution = (
×
853
                doc.get("tool", {}).get("pdm", {}).get("distribution") is not False
854
            )
855
            if only_me:
×
856
                return install_me if is_distribution else pdm_i
×
857
            cmd = "uv sync --inexact" + " --no-dev" * prod
×
858
            if is_distribution:
×
859
                cmd += f" && {install_me}"
×
860
        return ""
×
861

862
    @classmethod
5✔
863
    def sync_dependencies(cls, prod: bool = True) -> None:
5✔
864
        if cmd := cls.get_sync_command():
×
865
            run_and_echo(cmd)
×
866

867

868
class UpgradeDependencies(Project, DryRun):
5✔
869
    def __init__(
5✔
870
        self, _exit: bool = False, dry: bool = False, tool: ToolName = "poetry"
871
    ) -> None:
872
        super().__init__(_exit, dry)
5✔
873
        self._tool = tool
5✔
874

875
    class DevFlag(StrEnum):
5✔
876
        new = "[tool.poetry.group.dev.dependencies]"
5✔
877
        old = "[tool.poetry.dev-dependencies]"
5✔
878

879
    @staticmethod
5✔
880
    def parse_value(version_info: str, key: str) -> str:
5✔
881
        """Pick out the value for key in version info.
882

883
        Example::
884
            >>> s= 'typer = {extras = ["all"], version = "^0.9.0", optional = true}'
885
            >>> UpgradeDependencies.parse_value(s, 'extras')
886
            'all'
887
            >>> UpgradeDependencies.parse_value(s, 'optional')
888
            'true'
889
            >>> UpgradeDependencies.parse_value(s, 'version')
890
            '^0.9.0'
891
        """
892
        sep = key + " = "
5✔
893
        rest = version_info.split(sep, 1)[-1].strip(" =")
5✔
894
        if rest.startswith("["):
5✔
895
            rest = rest[1:].split("]")[0]
5✔
896
        elif rest.startswith('"'):
5✔
897
            rest = rest[1:].split('"')[0]
5✔
898
        else:
899
            rest = rest.split(",")[0].split("}")[0]
5✔
900
        return rest.strip().replace('"', "")
5✔
901

902
    @staticmethod
5✔
903
    def no_need_upgrade(version_info: str, line: str) -> bool:
5✔
904
        if (v := version_info.replace(" ", "")).startswith("{url="):
5✔
905
            echo(f"No need to upgrade for: {line}")
5✔
906
            return True
5✔
907
        if (f := "version=") in v:
5✔
908
            v = v.split(f)[1].strip('"').split('"')[0]
5✔
909
        if v == "*":
5✔
910
            echo(f"Skip wildcard line: {line}")
5✔
911
            return True
5✔
912
        elif v == "[":
5✔
913
            echo(f"Skip complex dependence: {line}")
5✔
914
            return True
5✔
915
        elif v.startswith(">") or v.startswith("<") or v[0].isdigit():
5✔
916
            echo(f"Ignore bigger/smaller/equal: {line}")
5✔
917
            return True
5✔
918
        return False
5✔
919

920
    @classmethod
5✔
921
    def build_args(
5✔
922
        cls: type[Self], package_lines: list[str]
923
    ) -> tuple[list[str], dict[str, list[str]]]:
924
        args: list[str] = []  # ['typer[all]', 'fastapi']
5✔
925
        specials: dict[str, list[str]] = {}  # {'--platform linux': ['gunicorn']}
5✔
926
        for no, line in enumerate(package_lines, 1):
5✔
927
            if (
5✔
928
                not (m := line.strip())
929
                or m.startswith("#")
930
                or m == "]"
931
                or (m.startswith("{") and m.strip(",").endswith("}"))
932
            ):
933
                continue
5✔
934
            try:
5✔
935
                package, version_info = m.split("=", 1)
5✔
936
            except ValueError as e:
5✔
937
                raise ParseError(f"Failed to separate by '='@line {no}: {m}") from e
5✔
938
            if (package := package.strip()).lower() == "python":
5✔
939
                continue
5✔
940
            if cls.no_need_upgrade(version_info := version_info.strip(' "'), line):
5✔
941
                continue
5✔
942
            if (extras_tip := "extras") in version_info:
5✔
943
                package += "[" + cls.parse_value(version_info, extras_tip) + "]"
5✔
944
            item = f'"{package}@latest"'
5✔
945
            key = None
5✔
946
            if (pf := "platform") in version_info:
5✔
947
                platform = cls.parse_value(version_info, pf)
5✔
948
                key = f"--{pf}={platform}"
5✔
949
            if (sc := "source") in version_info:
5✔
950
                source = cls.parse_value(version_info, sc)
5✔
951
                key = ("" if key is None else (key + " ")) + f"--{sc}={source}"
5✔
952
            if "optional = true" in version_info:
5✔
953
                key = ("" if key is None else (key + " ")) + "--optional"
5✔
954
            if key is not None:
5✔
955
                specials[key] = specials.get(key, []) + [item]
5✔
956
            else:
957
                args.append(item)
5✔
958
        return args, specials
5✔
959

960
    @classmethod
5✔
961
    def should_with_dev(cls: type[Self]) -> bool:
5✔
962
        text = cls.load_toml_text()
5✔
963
        return cls.DevFlag.new in text or cls.DevFlag.old in text
5✔
964

965
    @staticmethod
5✔
966
    def parse_item(toml_str: str) -> list[str]:
5✔
967
        lines: list[str] = []
5✔
968
        for line in toml_str.splitlines():
5✔
969
            if (line := line.strip()).startswith("["):
5✔
970
                if lines:
5✔
971
                    break
5✔
972
            elif line:
5✔
973
                lines.append(line)
5✔
974
        return lines
5✔
975

976
    @classmethod
5✔
977
    def get_args(
5✔
978
        cls: type[Self], toml_text: str | None = None
979
    ) -> tuple[list[str], list[str], list[list[str]], str]:
980
        if toml_text is None:
5✔
981
            toml_text = cls.load_toml_text()
5✔
982
        main_title = "[tool.poetry.dependencies]"
5✔
983
        if (no_main_deps := main_title not in toml_text) and not cls.is_poetry_v2(
5✔
984
            toml_text
985
        ):
986
            raise EnvError(
5✔
987
                f"{main_title} not found! Make sure this is a poetry project."
988
            )
989
        text = toml_text.split(main_title)[-1]
5✔
990
        dev_flag = "--group dev"
5✔
991
        new_flag, old_flag = cls.DevFlag.new, cls.DevFlag.old
5✔
992
        if (dev_title := getattr(new_flag, "value", new_flag)) not in text:
5✔
993
            dev_title = getattr(old_flag, "value", old_flag)  # For poetry<=1.2
5✔
994
            dev_flag = "--dev"
5✔
995
        others: list[list[str]] = []
5✔
996
        try:
5✔
997
            main_toml, dev_toml = text.split(dev_title)
5✔
998
        except ValueError:
5✔
999
            dev_toml = ""
5✔
1000
            main_toml = text
5✔
1001
        mains = [] if no_main_deps else cls.parse_item(main_toml)
5✔
1002
        devs = cls.parse_item(dev_toml)
5✔
1003
        prod_packs, specials = cls.build_args(mains)
5✔
1004
        if specials:
5✔
1005
            others.extend([[k] + v for k, v in specials.items()])
5✔
1006
        dev_packs, specials = cls.build_args(devs)
5✔
1007
        if specials:
5✔
1008
            others.extend([[k] + v + [dev_flag] for k, v in specials.items()])
5✔
1009
        return prod_packs, dev_packs, others, dev_flag
5✔
1010

1011
    @classmethod
5✔
1012
    def gen_cmd(cls: type[Self]) -> str:
5✔
1013
        main_args, dev_args, others, dev_flags = cls.get_args()
5✔
1014
        return cls.to_cmd(main_args, dev_args, others, dev_flags)
5✔
1015

1016
    @staticmethod
5✔
1017
    def to_cmd(
5✔
1018
        main_args: list[str],
1019
        dev_args: list[str],
1020
        others: list[list[str]],
1021
        dev_flags: str,
1022
    ) -> str:
1023
        command = "poetry add "
5✔
1024
        _upgrade = ""
5✔
1025
        if main_args:
5✔
1026
            _upgrade = command + " ".join(main_args)
5✔
1027
        if dev_args:
5✔
1028
            if _upgrade:
5✔
1029
                _upgrade += " && "
5✔
1030
            _upgrade += command + dev_flags + " " + " ".join(dev_args)
5✔
1031
        for single in others:
5✔
1032
            _upgrade += f" && poetry add {' '.join(single)}"
5✔
1033
        return _upgrade
5✔
1034

1035
    def gen(self) -> str:
5✔
1036
        if self._tool == "uv":
5✔
1037
            up = "uv lock --upgrade --verbose"
5✔
1038
            deps = "uv sync --inexact --frozen --all-groups --all-extras"
5✔
1039
            return f"{up} && {deps}"
5✔
1040
        elif self._tool == "pdm":
5✔
1041
            return "pdm update --verbose && pdm install -G :all --frozen"
5✔
1042
        return self.gen_cmd() + " && poetry lock && poetry update"
5✔
1043

1044

1045
@cli.command()
5✔
1046
def upgrade(
5✔
1047
    tool: str = ToolOption,
1048
    dry: bool = DryOption,
1049
) -> None:
1050
    """Upgrade dependencies in pyproject.toml to latest versions"""
1051
    if not (tool := _ensure_str(tool) or "") or tool == ToolOption.default:
5✔
1052
        tool = Project.get_manage_tool() or "uv"
5✔
1053
    if tool in get_args(ToolName):
5✔
1054
        UpgradeDependencies(dry=dry, tool=cast(ToolName, tool)).run()
5✔
1055
    else:
1056
        secho(f"Unknown tool {tool!r}", fg=typer.colors.YELLOW)
5✔
1057
        raise typer.Exit(1)
5✔
1058

1059

1060
class GitTag(DryRun):
5✔
1061
    def __init__(self, message: str, dry: bool, no_sync: bool = False) -> None:
5✔
1062
        self.message = message
5✔
1063
        self._no_sync = no_sync
5✔
1064
        super().__init__(dry=dry)
5✔
1065

1066
    @staticmethod
5✔
1067
    def has_v_prefix() -> bool:
5✔
1068
        return "v" in capture_cmd_output("git tag")
5✔
1069

1070
    def should_push(self) -> bool:
5✔
1071
        return "git push" in self.git_status
5✔
1072

1073
    def gen(self) -> str:
5✔
1074
        should_sync, _version = get_current_version(verbose=False, check_version=True)
5✔
1075
        if self.has_v_prefix():
5✔
1076
            # Add `v` at prefix to compare with bumpversion tool
1077
            _version = "v" + _version
5✔
1078
        cmd = f"git tag -a {_version} -m {self.message!r} && git push --tags"
5✔
1079
        if self.should_push():
5✔
1080
            cmd += " && git push"
5✔
1081
        if should_sync and not self._no_sync and (sync := Project.get_sync_command()):
5✔
1082
            cmd = f"{sync} && " + cmd
×
1083
        return cmd
5✔
1084

1085
    @cached_property
5✔
1086
    def git_status(self) -> str:
5✔
1087
        return capture_cmd_output("git status")
5✔
1088

1089
    def mark_tag(self) -> bool:
5✔
1090
        if not re.search(r"working (tree|directory) clean", self.git_status) and (
5✔
1091
            "无文件要提交,干净的工作区" not in self.git_status
1092
        ):
1093
            run_and_echo("git status")
5✔
1094
            echo("ERROR: Please run git commit to make sure working tree is clean!")
5✔
1095
            return False
5✔
1096
        return bool(super().run())
5✔
1097

1098
    def run(self) -> None:
5✔
1099
        if self.mark_tag() and not self.dry:
5✔
1100
            echo("You may want to publish package:\n pdm publish")
5✔
1101

1102

1103
@cli.command()
5✔
1104
def tag(
5✔
1105
    message: str = Option("", "-m", "--message"),
1106
    no_sync: bool = Option(
1107
        False, "--no-sync", help="Do not run sync command to update version"
1108
    ),
1109
    dry: bool = DryOption,
1110
) -> None:
1111
    """Run shell command: git tag -a <current-version-in-pyproject.toml> -m {message}"""
1112
    GitTag(message, dry=dry, no_sync=_ensure_bool(no_sync)).run()
5✔
1113

1114

1115
class LintCode(DryRun):
5✔
1116
    def __init__(
5✔
1117
        self,
1118
        args: list[str] | str | None,
1119
        check_only: bool = False,
1120
        _exit: bool = False,
1121
        dry: bool = False,
1122
        bandit: bool = False,
1123
        skip_mypy: bool = False,
1124
        dmypy: bool = False,
1125
        tool: str = ToolOption.default,
1126
        prefix: bool = False,
1127
        up: bool = False,
1128
        sim: bool = True,
1129
        strict: bool = False,
1130
        ty: bool = False,
1131
        fix: bool = True,
1132
    ) -> None:
1133
        self.args = args
5✔
1134
        self.check_only = check_only
5✔
1135
        self._bandit = bandit
5✔
1136
        self._skip_mypy = skip_mypy
5✔
1137
        self._use_dmypy = dmypy
5✔
1138
        self._tool = tool
5✔
1139
        self._prefix = prefix
5✔
1140
        self._up = up
5✔
1141
        self._sim = sim
5✔
1142
        self._strict = strict
5✔
1143
        self._ty = _ensure_bool(ty)
5✔
1144
        self._fix = _ensure_bool(fix)
5✔
1145
        super().__init__(_exit, dry)
5✔
1146

1147
    @staticmethod
5✔
1148
    def check_lint_tool_installed() -> bool:
5✔
1149
        try:
5✔
1150
            return check_call("ruff --version")
5✔
1151
        except FileNotFoundError:
×
1152
            # Windows may raise FileNotFoundError when ruff not installed
1153
            return False
×
1154

1155
    @staticmethod
5✔
1156
    def missing_mypy_exec() -> bool:
5✔
1157
        return shutil.which("mypy") is None
5✔
1158

1159
    @staticmethod
5✔
1160
    def prefer_dmypy(paths: str, tools: list[str], use_dmypy: bool = False) -> bool:
5✔
1161
        return (
5✔
1162
            paths == "."
1163
            and any(t.startswith("mypy") for t in tools)
1164
            and (use_dmypy or load_bool("FASTDEVCLI_DMYPY"))
1165
        )
1166

1167
    @staticmethod
5✔
1168
    def get_package_name() -> str:
5✔
1169
        root = Project.get_work_dir(allow_cwd=True)
5✔
1170
        module_name = root.name.replace("-", "_").replace(" ", "_")
5✔
1171
        package_maybe = (module_name, "src")
5✔
1172
        for name in package_maybe:
5✔
1173
            if root.joinpath(name).is_dir():
5✔
1174
                return name
5✔
1175
        return "."
5✔
1176

1177
    @classmethod
5✔
1178
    def to_cmd(
5✔
1179
        cls: type[Self],
1180
        paths: str = ".",
1181
        check_only: bool = False,
1182
        bandit: bool = False,
1183
        skip_mypy: bool = False,
1184
        use_dmypy: bool = False,
1185
        tool: str = ToolOption.default,
1186
        with_prefix: bool = False,
1187
        ruff_check_up: bool = False,
1188
        ruff_check_sim: bool = True,
1189
        mypy_strict: bool = False,
1190
        prefer_ty: bool = False,
1191
        ruff_check_fix: bool = True,
1192
    ) -> str:
1193
        if paths != "." and all(i.endswith(".html") for i in paths.split()):
5✔
1194
            return f"prettier -w {paths}"
5✔
1195
        ruff_rules = ["I", "B"]
5✔
1196
        if ruff_check_sim and not load_bool("FASTDEVCLI_NO_SIM"):
5✔
1197
            ruff_rules.append("SIM")
5✔
1198
        if ruff_check_up or load_bool("FASTDEVCLI_UP"):
5✔
1199
            ruff_rules.append("UP")
×
1200
        ruff_check = "ruff check --extend-select=" + ",".join(ruff_rules)
5✔
1201
        if (
5✔
1202
            ruff_check_fix
1203
            and not check_only
1204
            and (not load_bool("NO_FIX") and not load_bool("FASTDEVCLI_NO_FIX"))
1205
        ):
1206
            ruff_check += " --fix"
5✔
1207
        tools = ["ruff format", ruff_check, "mypy"]
5✔
1208
        if check_only:
5✔
1209
            tools[0] += " --check"
5✔
1210
        if skip_mypy or load_bool("SKIP_MYPY") or load_bool("FASTDEVCLI_NO_MYPY"):
5✔
1211
            # Sometimes mypy is too slow
1212
            tools = tools[:-1]
5✔
1213
        else:
1214
            if prefer_ty or load_bool("FASTDEVCLI_TY"):
5✔
1215
                tools[-1] = "ty check"
×
1216
            else:
1217
                if load_bool("IGNORE_MISSING_IMPORTS"):
5✔
1218
                    tools[-1] += " --ignore-missing-imports"
5✔
1219
                if mypy_strict or load_bool("FASTDEVCLI_STRICT"):
5✔
1220
                    tools[-1] += " --strict"
×
1221
        ruff_exists = cls.check_lint_tool_installed()
5✔
1222
        prefix = ""
5✔
1223
        should_run_by_tool = with_prefix
5✔
1224
        requires_mypy = any(tool.startswith("mypy") for tool in tools)
5✔
1225
        if requires_mypy and not should_run_by_tool:
5✔
1226
            if is_venv() and Path(sys.argv[0]).parent != Path.home().joinpath(
5✔
1227
                ".local/bin"
1228
            ):  # Virtual environment activated and fast-dev-cli is installed in it
1229
                if not ruff_exists:
5✔
1230
                    should_run_by_tool = True
5✔
1231
                    command = "pipx install ruff"
5✔
1232
                    if shutil.which("pipx") is None:
5✔
1233
                        ensure_pipx = "pip install --user pipx\n  pipx ensurepath\n  "
×
1234
                        command = ensure_pipx + command
×
1235
                    elif prefer_uv_tool():
5✔
1236
                        command = "uv tool install ruff"
5✔
1237
                    yellow_warn(
5✔
1238
                        "You may need to run the following command"
1239
                        f" to install ruff:\n\n  {command}\n"
1240
                    )
1241
                elif cls.missing_mypy_exec():
5✔
1242
                    should_run_by_tool = True
5✔
1243
                    if check_call('python -c "import fast_dev_cli"'):
5✔
1244
                        command = "python -m pip install -U mypy"
5✔
1245
                        yellow_warn(
5✔
1246
                            "You may need to run the following command"
1247
                            f" to install lint tools:\n\n  {command}\n"
1248
                        )
1249
            elif tool == ToolOption.default:
×
1250
                root = Project.get_work_dir(allow_cwd=True)
×
1251
                if py := shutil.which("python"):
×
1252
                    try:
×
1253
                        Path(py).relative_to(root)
×
1254
                    except ValueError:
×
1255
                        # Virtual environment not activated
1256
                        should_run_by_tool = True
×
1257
            else:
1258
                should_run_by_tool = True
×
1259
        if should_run_by_tool and tool:
5✔
1260
            if tool == ToolOption.default:
5✔
1261
                tool = Project.get_manage_tool() or ""
5✔
1262
            if tool:
5✔
1263
                prefix = tool + " run "
5✔
1264
                if tool == "uv":
5✔
1265
                    if is_windows():
5✔
1266
                        prefix += "--no-sync "
×
1267
                    elif Path(bin_dir := ".venv/bin/").exists():
5✔
1268
                        prefix = bin_dir
5✔
1269
        if cls.prefer_dmypy(paths, tools, use_dmypy=use_dmypy):
5✔
1270
            tools[-1] = "dmypy run"
5✔
1271
        cmd = " && ".join(
5✔
1272
            (
1273
                tool
1274
                # `ruff <command>` get the same result with `pdm run ruff <command>`.
1275
                # Other tools should run inside the selected environment.
1276
                if ruff_exists and tool.startswith("ruff")
1277
                else prefix + tool
1278
            )
1279
            + f" {paths}"
1280
            for tool in tools
1281
        )
1282
        if bandit or load_bool("FASTDEVCLI_BANDIT"):
5✔
1283
            command = prefix + "bandit"
5✔
1284
            if Path("pyproject.toml").exists():
5✔
1285
                toml_text = Project.load_toml_text()
5✔
1286
                if "[tool.bandit" in toml_text:
5✔
1287
                    command += " -c pyproject.toml"
5✔
1288
            if paths == "." and " -c " not in command:
5✔
1289
                paths = cls.get_package_name()
5✔
1290
            command += f" -r {paths}"
5✔
1291
            cmd += " && " + command
5✔
1292
        return cmd
5✔
1293

1294
    def gen(self) -> str:
5✔
1295
        paths = "."
5✔
1296
        if args := self.args:
5✔
1297
            ps = args.split() if isinstance(args, str) else [str(i) for i in args]
5✔
1298
            if len(ps) == 1:
5✔
1299
                paths = ps[0]
5✔
1300
                if (
5✔
1301
                    paths != "."
1302
                    # `Path("a.").suffix` got "." in py3.14 and got "" with py<3.14
1303
                    and (p := Path(paths)).suffix in ("", ".")
1304
                    and not p.exists()
1305
                ):
1306
                    # e.g.:
1307
                    # stem -> stem.py
1308
                    # me. -> me.py
1309
                    if paths.endswith("."):
×
1310
                        p = p.with_name(paths[:-1])
×
1311
                    for suffix in (".py", ".html"):
×
1312
                        p = p.with_suffix(suffix)
×
1313
                        if p.exists():
×
1314
                            paths = p.name
×
1315
                            break
×
1316
            else:
1317
                paths = " ".join(ps)
×
1318
        return self.to_cmd(
5✔
1319
            paths,
1320
            self.check_only,
1321
            self._bandit,
1322
            self._skip_mypy,
1323
            self._use_dmypy,
1324
            tool=self._tool,
1325
            with_prefix=self._prefix,
1326
            ruff_check_up=self._up,
1327
            ruff_check_sim=self._sim,
1328
            mypy_strict=self._strict,
1329
            prefer_ty=self._ty,
1330
            ruff_check_fix=self._fix,
1331
        )
1332

1333

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

1337

1338
def lint(
5✔
1339
    files: list[str] | str | None = None,
1340
    dry: bool = False,
1341
    bandit: bool = False,
1342
    skip_mypy: bool = False,
1343
    dmypy: bool = False,
1344
    tool: str = ToolOption.default,
1345
    prefix: bool = False,
1346
    up: bool = False,
1347
    sim: bool = True,
1348
    strict: bool = False,
1349
    ty: bool = False,
1350
    fix: bool = True,
1351
) -> None:
1352
    if files is None:
5✔
1353
        files = parse_files(sys.argv[1:])
5✔
1354
    if files and files[0] == "lint":
5✔
1355
        files = files[1:]
5✔
1356
    LintCode(
5✔
1357
        files,
1358
        dry=dry,
1359
        skip_mypy=skip_mypy,
1360
        bandit=bandit,
1361
        dmypy=dmypy,
1362
        tool=tool,
1363
        prefix=prefix,
1364
        up=up,
1365
        sim=sim,
1366
        strict=strict,
1367
        ty=ty,
1368
        fix=fix,
1369
    ).run()
1370

1371

1372
def check(
5✔
1373
    files: list[str] | str | None = None,
1374
    dry: bool = False,
1375
    bandit: bool = False,
1376
    skip_mypy: bool = False,
1377
    dmypy: bool = False,
1378
    tool: str = ToolOption.default,
1379
    up: bool = False,
1380
    sim: bool = True,
1381
    strict: bool = False,
1382
    ty: bool = False,
1383
) -> None:
1384
    LintCode(
5✔
1385
        files,
1386
        check_only=True,
1387
        _exit=True,
1388
        dry=dry,
1389
        bandit=bandit,
1390
        skip_mypy=skip_mypy,
1391
        dmypy=dmypy,
1392
        tool=tool,
1393
        up=up,
1394
        sim=sim,
1395
        strict=strict,
1396
        ty=ty,
1397
    ).run()
1398

1399

1400
@cli.command(name="lint")
5✔
1401
def make_style(
5✔
1402
    files: list[str] | None = typer.Argument(default=None),  # noqa:B008
1403
    check_only: bool = Option(False, "--check-only", "-c"),
1404
    bandit: bool = Option(False, "--bandit", help="Run `bandit -r <package_dir>`"),
1405
    prefix: bool = Option(
1406
        False,
1407
        "--prefix",
1408
        help="Run lint command with tool prefix, e.g.: pdm run ruff ...",
1409
    ),
1410
    skip_mypy: bool = Option(False, "--skip-mypy"),
1411
    use_dmypy: bool = Option(
1412
        False, "--dmypy", help="Use `dmypy run` instead of `mypy`"
1413
    ),
1414
    tool: str = ToolOption,
1415
    dry: bool = DryOption,
1416
    up: bool = Option(False, help="Whether ruff check with --extend-select=UP"),
1417
    sim: bool = Option(True, help="Whether ruff check with --extend-select=SIM"),
1418
    strict: bool = Option(False, help="Whether run mypy with --strict"),
1419
    ty: bool = Option(False, help="Whether use ty instead of mypy"),
1420
    fix: bool | None = Option(None, help="Whether ruff check with --fix"),
1421
) -> None:
1422
    """Run: ruff check/format to reformat code and then mypy to check"""
1423
    if getattr(files, "default", files) is None:
5✔
1424
        files = ["."]
5✔
1425
    elif isinstance(files, str):
5✔
1426
        files = [files]
5✔
1427
    skip = _ensure_bool(skip_mypy)
5✔
1428
    dmypy = _ensure_bool(use_dmypy)
5✔
1429
    bandit = _ensure_bool(bandit)
5✔
1430
    tool = _ensure_str(tool) or ""
5✔
1431
    up = _ensure_bool(up)
5✔
1432
    sim = _ensure_bool(sim)
5✔
1433
    strict = _ensure_bool(strict)
5✔
1434
    kwargs = {"dry": dry, "skip_mypy": skip, "dmypy": dmypy, "bandit": bandit}
5✔
1435
    if _ensure_bool(check_only):
5✔
1436
        run = check
5✔
1437
    else:
1438
        prefix = _ensure_bool(prefix)
5✔
1439
        if fix is None or not isinstance(fix, bool):
5✔
1440
            fix = load_bool("FASTDEVCLI_FIX", True)
5✔
1441
        run = functools.partial(lint, prefix=prefix, fix=fix)
5✔
1442
    run(files, tool=tool, up=up, sim=sim, strict=strict, ty=ty, **kwargs)
5✔
1443

1444

1445
@cli.command(name="check")
5✔
1446
def only_check(
5✔
1447
    bandit: bool = Option(False, "--bandit", help="Run `bandit -r <package_dir>`"),
1448
    skip_mypy: bool = Option(False, "--skip-mypy"),
1449
    dry: bool = DryOption,
1450
    up: bool = Option(False, help="Whether ruff check with --extend-select=UP"),
1451
    sim: bool = Option(True, help="Whether ruff check with --extend-select=SIM"),
1452
    strict: bool = Option(False, help="Whether run mypy with --strict"),
1453
    ty: bool = Option(False, help="Whether use ty instead of mypy"),
1454
) -> None:
1455
    """Check code style without reformat"""
1456
    bandit = _ensure_bool(bandit)
5✔
1457
    up = _ensure_bool(up)
5✔
1458
    sim = _ensure_bool(sim)
5✔
1459
    skip_mypy = _ensure_bool(skip_mypy)
5✔
1460
    check(dry=dry, bandit=bandit, skip_mypy=skip_mypy, up=up, sim=sim, ty=ty)
5✔
1461

1462

1463
class Sync(DryRun):
5✔
1464
    def __init__(
5✔
1465
        self, filename: str, extras: str, save: bool, dry: bool = False
1466
    ) -> None:
1467
        self.filename = filename
5✔
1468
        self.extras = extras
5✔
1469
        self._save = save
5✔
1470
        super().__init__(dry=dry)
5✔
1471

1472
    def gen(self) -> str:
5✔
1473
        extras, save = self.extras, self._save
5✔
1474
        should_remove = not Path.cwd().joinpath(self.filename).exists()
5✔
1475
        if not (tool := Project.get_manage_tool()):
5✔
1476
            if should_remove or not is_venv():
5✔
1477
                raise EnvError("There project is not managed by uv/pdm/poetry!")
5✔
1478
            return f"python -m pip install -r {self.filename}"
5✔
1479
        prefix = ""
5✔
1480
        if not is_venv():
5✔
1481
            prefix = f"{tool} run " + "--no-sync " * (tool == "uv")
5✔
1482
        ensure_pip = " {1}python -m ensurepip && {1}python -m pip install -U pip &&"
5✔
1483
        export_cmd = "uv export --no-hashes --all-extras --all-groups --frozen"
5✔
1484
        if tool in ("poetry", "pdm"):
5✔
1485
            export_cmd = f"{tool} export --without-hashes --with=dev"
5✔
1486
            if tool == "poetry":
5✔
1487
                ensure_pip = ""
5✔
1488
                if not UpgradeDependencies.should_with_dev():
5✔
1489
                    export_cmd = export_cmd.replace(" --with=dev", "")
5✔
1490
                if extras and isinstance(extras, str | list):
5✔
1491
                    export_cmd += f" --{extras=}".replace("'", '"')
5✔
1492
            elif check_call(prefix + "python -m pip --version"):
×
1493
                ensure_pip = ""
×
1494
        elif check_call(prefix + "python -m pip --version"):
5✔
1495
            ensure_pip = ""
5✔
1496
        install_cmd = (
5✔
1497
            f"{{2}} -o {{0}} &&{ensure_pip} {{1}}python -m pip install -r {{0}}"
1498
        )
1499
        if should_remove and not save:
5✔
1500
            install_cmd += " && rm -f {0}"
5✔
1501
        return install_cmd.format(self.filename, prefix, export_cmd)
5✔
1502

1503

1504
@cli.command()
5✔
1505
def sync(
5✔
1506
    filename: str = "dev_requirements.txt",
1507
    extras: str = Option("", "--extras", "-E"),
1508
    save: bool = Option(
1509
        False, "--save", "-s", help="Whether save the requirement file"
1510
    ),
1511
    dry: bool = DryOption,
1512
) -> None:
1513
    """Export dependencies by poetry to a txt file then install by pip."""
1514
    Sync(filename, extras, save, dry=dry).run()
5✔
1515

1516

1517
def _should_run_test_script(path: Path = Path("scripts")) -> Path | None:
5✔
1518
    for name in ("test.sh", "test.py"):
5✔
1519
        if (file := path / name).exists():
5✔
1520
            return file
5✔
1521
    return None
5✔
1522

1523

1524
def test(dry: bool, ignore_script: bool = False) -> None:
5✔
1525
    cwd = Path.cwd()
5✔
1526
    root = Project.get_work_dir(cwd=cwd, allow_cwd=True)
5✔
1527
    script_dir = root / "scripts"
5✔
1528
    if not _ensure_bool(ignore_script) and (
5✔
1529
        test_script := _should_run_test_script(script_dir)
1530
    ):
1531
        cmd = test_script.relative_to(root).as_posix()
5✔
1532
        if test_script.suffix == ".py":
5✔
1533
            cmd = "python " + cmd
5✔
1534
        if cwd != root:
5✔
1535
            cmd = f"cd {root} && " + cmd
5✔
1536
    else:
1537
        cmd = 'coverage run -m pytest -s && coverage report --omit="tests/*" -m'
5✔
1538
        if not is_venv() or not check_call("coverage --version"):
5✔
1539
            sep = " && "
5✔
1540
            prefix = f"{tool} run " if (tool := Project.get_manage_tool()) else ""
5✔
1541
            cmd = sep.join(prefix + i for i in cmd.split(sep))
5✔
1542
    exit_if_run_failed(cmd, dry=dry)
5✔
1543

1544

1545
@cli.command(name="test")
5✔
1546
def coverage_test(
5✔
1547
    dry: bool = DryOption,
1548
    ignore_script: bool = Option(False, "--ignore-script", "-i"),
1549
) -> None:
1550
    """Run unittest by pytest and report coverage"""
1551
    return test(dry, ignore_script)
5✔
1552

1553

1554
class Publish:
5✔
1555
    class CommandEnum(StrEnum):
5✔
1556
        poetry = "poetry publish --build"
5✔
1557
        pdm = "pdm publish"
5✔
1558
        uv = "uv build && uv publish"
5✔
1559
        twine = "python -m build && twine upload"
5✔
1560

1561
    @classmethod
5✔
1562
    def gen(cls) -> str:
5✔
1563
        if tool := Project.get_manage_tool():
5✔
1564
            return cls.CommandEnum[tool]
5✔
1565
        return cls.CommandEnum.twine
5✔
1566

1567

1568
@cli.command()
5✔
1569
def upload(
5✔
1570
    dry: bool = DryOption,
1571
) -> None:
1572
    """Shortcut for package publish"""
1573
    cmd = Publish.gen()
5✔
1574
    exit_if_run_failed(cmd, dry=dry)
5✔
1575

1576

1577
def should_use_just() -> bool:
5✔
1578
    if shutil.which("just") is None:
5✔
1579
        return False
5✔
1580
    d = Path.cwd()
5✔
1581
    for _ in range(5):
5✔
1582
        f = d / "justfile"
5✔
1583
        if f.exists():
5✔
1584
            text = f.read_text(encoding="utf-8")
5✔
1585
            return any(i.startswith("dev *args:") for i in text.splitlines())
5✔
1586
        if d.joinpath("pyproject.toml").exists():
×
1587
            break
×
1588
    return False
×
1589

1590

1591
def _parse_serve_file(uvicorn, filename: str, cmd: str, args: list) -> str:
5✔
1592
    if m := re.search(r"(.*):(\d+)$", filename):
5✔
1593
        h, p = m.group(1), m.group(2)
5✔
1594
        if h and "--host" not in str(args):
5✔
1595
            if h == "0":
5✔
1596
                args.append("--host=0.0.0.0")
5✔
1597
            else:
1598
                args.append(f"--host={h}")
5✔
1599
        args.append(f"--port={p}")
5✔
1600
        if uvicorn:
5✔
NEW
1601
            p = Path("main.py")
×
NEW
1602
            if p.exists():
×
NEW
1603
                cmd += " main:app"
×
NEW
1604
            elif Path("app", p.name).exists():
×
NEW
1605
                cmd += " app.main:app"
×
NEW
1606
            elif Path("app.py").exists():
×
NEW
1607
                cmd += " app:app"
×
1608
        return cmd
5✔
1609
    if uvicorn and ((filepath := Path(filename)).is_file() or filepath.suffix == ".py"):
5✔
1610
        filename = filepath.stem + ":app"
5✔
1611
        parent_names = [j for i in filepath.parents if (j := i.name)]
5✔
1612
        if parent_names:
5✔
1613
            filename = ".".join([*parent_names[::-1], filename])
5✔
1614
    cmd += " " + filename
5✔
1615
    return cmd
5✔
1616

1617

1618
def _runserver(uvicorn, host, port, file) -> tuple[str, list[str]]:
5✔
1619
    cmd = "uvicorn" if uvicorn else "fastapi dev"
5✔
1620
    args = []
5✔
1621
    if (host := getattr(host, "default", host)) and host not in (
5✔
1622
        "localhost",
1623
        "127.0.0.1",
1624
    ):
1625
        args.append(f"--host={host}")
5✔
1626
    no_port_yet = True
5✔
1627
    if file is not None:
5✔
1628
        filename = str(file)
5✔
1629
        try:
5✔
1630
            port = int(filename)
5✔
1631
        except ValueError:
5✔
1632
            cmd = _parse_serve_file(uvicorn, filename, cmd, args)
5✔
1633
        else:
1634
            if port != 8000:
5✔
1635
                args.append(f"--port={port}")
5✔
1636
                no_port_yet = False
5✔
1637
    if no_port_yet and (port := getattr(port, "default", port)) and str(port) != "8000":
5✔
1638
        args.append(f"--port={port}")
5✔
1639
    if shutil.which("pdm") is not None:
5✔
1640
        cmd = "pdm run " + cmd
5✔
1641
    return cmd, args
5✔
1642

1643

1644
def dev(
5✔
1645
    port: int | None | OptionInfo,
1646
    host: str | None | OptionInfo,
1647
    fastapi: bool | None = None,
1648
    uvicorn: bool | None = None,
1649
    prod: bool | None = None,
1650
    reload: bool | None = None,
1651
    file: str | None | ArgumentInfo = None,
1652
    dry: bool = False,
1653
) -> None:
1654
    if should_use_just():
5✔
1655
        args = [i for i in sys.argv[2:] if i != "--dry"]
×
1656
        cmd = "just dev"
×
1657
    else:
1658
        cmd, args = _runserver(uvicorn, host, port, file)
5✔
1659
    if args:
5✔
1660
        cmd += " " + " ".join(args)
5✔
1661
    exit_if_run_failed(cmd, dry=dry)
5✔
1662

1663

1664
@cli.command(name="dev")
5✔
1665
def runserver(
5✔
1666
    file_or_port: str | None = typer.Argument(default=None),
1667
    port: int | None = Option(None, "-p", "--port"),
1668
    host: str | None = Option(None, "-h", "--host"),
1669
    fastapi: bool | None = None,
1670
    uvicorn: bool | None = None,
1671
    prod: bool | None = None,
1672
    reload: bool | None = None,
1673
    dry: bool = DryOption,
1674
) -> None:
1675
    """Start a fastapi server(only for fastapi>=0.111.0)"""
1676
    f = functools.partial(dev, port, host, fastapi, uvicorn, prod, reload, dry=dry)
5✔
1677
    if getattr(file_or_port, "default", file_or_port):
5✔
1678
        f(file=file_or_port)
5✔
1679
    else:
1680
        f()
5✔
1681

1682

1683
@cli.command(name="exec")
5✔
1684
def run_by_subprocess(cmd: str, dry: bool = DryOption) -> None:
5✔
1685
    """Run cmd by subprocess, auto set shell=True when cmd contains '|>'"""
1686
    try:
5✔
1687
        rc = run_and_echo(cmd, verbose=True, dry=_ensure_bool(dry))
5✔
1688
    except FileNotFoundError as e:
5✔
1689
        command = cmd.split()[0]
5✔
1690
        if e.filename == command or (
5✔
1691
            e.filename is None and "系统找不到指定的文件" in str(e)
1692
        ):
1693
            echo(f"Command not found: {command}")
5✔
1694
            raise Exit(1) from None
5✔
1695
        raise e
×
1696
    else:
1697
        if rc:
5✔
1698
            raise Exit(rc)
5✔
1699

1700

1701
class MakeDeps(DryRun):
5✔
1702
    def __init__(
5✔
1703
        self,
1704
        tool: str,
1705
        prod: bool = False,
1706
        dry: bool = False,
1707
        active: bool = True,
1708
        inexact: bool = True,
1709
    ) -> None:
1710
        self._tool = tool
5✔
1711
        self._prod = prod
5✔
1712
        self._active = active
5✔
1713
        self._inexact = inexact
5✔
1714
        super().__init__(dry=dry)
5✔
1715

1716
    def should_ensure_pip(self) -> bool:
5✔
1717
        return True
5✔
1718

1719
    def should_upgrade_pip(self) -> bool:
5✔
1720
        return True
5✔
1721

1722
    def get_groups(self) -> list[str]:
5✔
1723
        if self._prod:
5✔
1724
            return []
5✔
1725
        return ["dev"]
5✔
1726

1727
    def gen(self) -> str:
5✔
1728
        if self._tool == "pdm":
5✔
1729
            return "pdm install --frozen " + ("--prod" if self._prod else "-G :all")
5✔
1730
        elif self._tool == "uv":
5✔
1731
            uv_sync = "uv sync" + " --inexact" * self._inexact
5✔
1732
            if self._active:
5✔
1733
                uv_sync += " --active"
5✔
1734
            return uv_sync + ("" if self._prod else " --all-extras --all-groups")
5✔
1735
        elif self._tool == "poetry":
5✔
1736
            return "poetry install " + (
5✔
1737
                "--only=main" if self._prod else "--all-extras --all-groups"
1738
            )
1739
        else:
1740
            cmd = "python -m pip install -e ."
5✔
1741
            if gs := self.get_groups():
5✔
1742
                cmd += " " + " ".join(f"--group {g}" for g in gs)
5✔
1743
            upgrade = "python -m pip install --upgrade pip"
5✔
1744
            if self.should_ensure_pip():
5✔
1745
                cmd = f"python -m ensurepip && {upgrade} && {cmd}"
5✔
1746
            elif self.should_upgrade_pip():
5✔
1747
                cmd = f"{upgrade} && {cmd}"
5✔
1748
            return cmd
5✔
1749

1750

1751
@cli.command(name="deps")
5✔
1752
def make_deps(
5✔
1753
    prod: bool = Option(
1754
        False,
1755
        "--prod",
1756
        help="Only instead production dependencies.",
1757
    ),
1758
    tool: str = ToolOption,
1759
    use_uv: bool = Option(False, "--uv", help="Use `uv` to install deps"),
1760
    use_pdm: bool = Option(False, "--pdm", help="Use `pdm` to install deps"),
1761
    use_pip: bool = Option(False, "--pip", help="Use `pip` to install deps"),
1762
    use_poetry: bool = Option(False, "--poetry", help="Use `poetry` to install deps"),
1763
    active: bool = Option(
1764
        True, help="Add `--active` to uv sync command(Only work for uv project)"
1765
    ),
1766
    inexact: bool = Option(
1767
        True, help="Add `--inexact` to uv sync command(Only work for uv project)"
1768
    ),
1769
    dry: bool = DryOption,
1770
) -> None:
1771
    """Run: ruff check/format to reformat code and then mypy to check"""
1772
    if use_uv + use_pdm + use_pip + use_poetry > 1:
×
1773
        raise typer.BadParameter(
×
1774
            "can only choose one",
1775
            param_hint=("--uv", "--pdm", "--pip", "--poetry"),
1776
        )
1777
    if use_uv:
×
1778
        tool = "uv"
×
1779
    elif use_pdm:
×
1780
        tool = "pdm"
×
1781
    elif use_pip:
×
1782
        tool = "pip"
×
1783
    elif use_poetry:
×
1784
        tool = "poetry"
×
1785
    elif tool == ToolOption.default:
×
1786
        tool = Project.get_manage_tool(cache=True) or "pip"
×
1787
    MakeDeps(tool, prod, active=active, inexact=inexact, dry=dry).run()
×
1788

1789

1790
class UvPypi(DryRun):
5✔
1791
    PYPI = "https://pypi.org/simple"
5✔
1792
    HOST = "https://files.pythonhosted.org"
5✔
1793

1794
    def __init__(
5✔
1795
        self,
1796
        lock_file: Path,
1797
        dry: bool,
1798
        verbose: bool,
1799
        quiet: bool,
1800
        slim: bool = False,
1801
        reverse: bool = False,
1802
    ) -> None:
1803
        super().__init__(dry=dry)
5✔
1804
        self.lock_file = lock_file
5✔
1805
        self._verbose = _ensure_bool(verbose)
5✔
1806
        self._quiet = _ensure_bool(quiet)
5✔
1807
        self._slim = _ensure_bool(slim)
5✔
1808
        self._reverse = _ensure_bool(reverse)
5✔
1809

1810
    def run(self) -> None:
5✔
1811
        try:
5✔
1812
            rc = self.update_lock(
5✔
1813
                self.lock_file, self._verbose, self._quiet, self._slim, self._reverse
1814
            )
1815
        except ValueError as e:
×
1816
            secho(str(e), fg=typer.colors.RED)
×
1817
            raise Exit(1) from e
×
1818
        else:
1819
            if rc != 0:
5✔
1820
                raise Exit(rc)
5✔
1821

1822
    @staticmethod
5✔
1823
    def get_target_content(
5✔
1824
        text: str, verbose: bool, target_registry, target_host: str
1825
    ) -> str | None:
1826
        registry_pattern = r'(registry = ")(.*?)"'
5✔
1827
        registry_urls = {i[1] for i in re.findall(registry_pattern, text)}
5✔
1828
        download_pattern = r'(url = ")(https?://.*?)(/packages/.*?\.)(gz|whl|zip)"'
5✔
1829
        download_hosts = {i[1] for i in re.findall(download_pattern, text)}
5✔
1830
        if not registry_urls:
5✔
1831
            raise ValueError(
×
1832
                f"Failed to find pattern {registry_pattern!r} in uv lock file"
1833
            )
1834

1835
        def replace_registry(s: str) -> str:
5✔
1836
            return re.sub(registry_pattern, rf'\1{target_registry}"', s)
5✔
1837

1838
        def replace_host(s: str) -> str:
5✔
1839
            return re.sub(download_pattern, rf'\1{target_host}\3\4"', s)
5✔
1840

1841
        if len(registry_urls) == 1:
5✔
1842
            current_registry = registry_urls.pop()
5✔
1843
            if current_registry == target_registry:
5✔
1844
                if download_hosts == {target_host}:
5✔
1845
                    return None
5✔
1846
            else:
1847
                text = replace_registry(text)
5✔
1848
                if verbose:
5✔
1849
                    echo(f"{current_registry} --> {target_registry}")
5✔
1850
        else:
1851
            # TODO: ask each one to confirm replace
1852
            text = replace_registry(text)
×
1853
            if verbose:
×
1854
                for current_registry in sorted(registry_urls):
×
1855
                    echo(f"{current_registry} --> {target_registry}")
×
1856
        if len(download_hosts) == 1:
5✔
1857
            current_host = download_hosts.pop()
5✔
1858
            if current_host != target_host:
5✔
1859
                text = replace_host(text)
5✔
1860
                if verbose:
5✔
1861
                    echo(f"{current_host} --> {target_host}")
5✔
1862
        elif download_hosts:
×
1863
            # TODO: ask each one to confirm replace
1864
            text = replace_host(text)
×
1865
            if verbose:
×
1866
                for current_host in sorted(download_hosts):
×
1867
                    echo(f"{current_host} --> {target_host}")
×
1868
        return text
5✔
1869

1870
    @classmethod
5✔
1871
    def update_lock(
5✔
1872
        cls,
1873
        p: Path,
1874
        verbose: bool,
1875
        quiet: bool,
1876
        slim: bool = False,
1877
        reverse: bool = False,
1878
    ) -> int:
1879
        text = p.read_text("utf-8")
5✔
1880
        target_register, target_host = cls.PYPI, cls.HOST
5✔
1881
        if reverse:
5✔
1882
            try:
5✔
1883
                target_register, target_host = cls.get_register_from_uv_config()
5✔
1884
            except FileNotFoundError:
5✔
1885
                if verbose:
5✔
1886
                    echo("Skip register reverse as global uv config file not found.")
5✔
1887
                if quiet:
5✔
1888
                    return 0
5✔
1889
                return 1
×
1890
        new_text = cls.get_target_content(text, verbose, target_register, target_host)
5✔
1891
        if new_text is None:
5✔
1892
            if verbose:
5✔
1893
                echo(f"Registry of {p} is {target_register}, no need to change.")
5✔
1894
            return 0
5✔
1895
        return cls.slim_and_write(new_text, slim, p, verbose, quiet)
5✔
1896

1897
    @classmethod
5✔
1898
    def get_register_from_uv_config(cls) -> tuple[str, str]:
5✔
1899
        config_file = cls.get_uv_config_file()
5✔
1900
        text = config_file.read_text("utf-8")
5✔
1901
        doc = tomllib.loads(text)
5✔
1902
        index_url = doc["index"][0]["url"]
5✔
1903
        return index_url, index_url.replace("/simple", "").rstrip("/")
5✔
1904

1905
    @staticmethod
5✔
1906
    def get_uv_config_file() -> Path:
5✔
1907
        config_dir = "AppData/Roaming" if is_windows() else ".config"
5✔
1908
        return Path.home() / config_dir / "uv/uv.toml"
5✔
1909

1910
    @staticmethod
5✔
1911
    def slim_and_write(
5✔
1912
        text: str, slim: bool, p: Path, verbose: bool, quiet: bool
1913
    ) -> int:
1914
        if slim:
5✔
1915
            pattern = r', size = \d+, upload-time = ".*?"'
5✔
1916
            text = re.sub(pattern, "", text)
5✔
1917
        size = p.write_text(text, encoding="utf-8")
5✔
1918
        if verbose:
5✔
1919
            echo(f"Updated {p} with {size} bytes.")
5✔
1920
        if quiet:
5✔
1921
            return 0
5✔
1922
        return 1
5✔
1923

1924

1925
@cli.command()
5✔
1926
def pypi(
5✔
1927
    file: str | None = typer.Argument(default=None),
1928
    dry: bool = DryOption,
1929
    verbose: bool = False,
1930
    quiet: bool = False,
1931
    slim: bool = False,
1932
    reverse: bool = False,
1933
) -> None:
1934
    """Change registry of uv.lock to be pypi.org"""
1935
    if not (p := Path(_ensure_str(file) or "uv.lock")).exists() and not (
5✔
1936
        (p := Project.get_work_dir() / p.name).exists()
1937
    ):
1938
        yellow_warn(f"{p.name!r} not found!")
5✔
1939
        return
5✔
1940
    UvPypi(p, dry, verbose, quiet, slim, reverse).run()
5✔
1941

1942

1943
def version_callback(value: bool) -> None:
5✔
1944
    if value:
5✔
1945
        echo("Fast Dev Cli Version: " + typer.style(__version__, bold=True))
5✔
1946
        raise Exit()
5✔
1947

1948

1949
@cli.callback()
1950
def common(
1951
    version: bool = Option(
1952
        None,
1953
        "--version",
1954
        "-V",
1955
        callback=version_callback,
1956
        is_eager=True,
1957
        help="Show the version of this tool",
1958
    ),
1959
) -> None: ...
1960

1961

1962
def main() -> None:
5✔
1963
    cli()
5✔
1964

1965

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