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

waketzheng / fast-dev-cli / 29259240402

13 Jul 2026 02:43PM UTC coverage: 85.019% (-0.04%) from 85.062%
29259240402

push

github

waketzheng
chore: update justfile

1101 of 1295 relevant lines covered (85.02%)

4.25 hits per line

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

85.01
/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, Annotated, 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.expand_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.expand_user(command)
5✔
156
        return command
5✔
157

158
    @staticmethod
5✔
159
    def expand_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
    all_lines = Path(version_file).read_text("utf-8").strip().splitlines()
5✔
259
    for line in all_lines:
5✔
260
        if pattern.match(line):
5✔
261
            return _parse_version(line, pattern)
5✔
262
    else:
263
        pattern = re.compile(r"VERSION\s*=")
×
264
        for line in all_lines:
×
265
            if pattern.match(line):
×
266
                return _parse_version(line, pattern)
×
267
        secho(f"WARNING: can not find version pattern in {version_file}!")
×
268
        return "0.0.0"
×
269

270

271
def _get_frontend_version() -> tuple[Path, str] | None:
5✔
272
    try:
×
273
        frontend_version_file = Project.get_work_dir("package.json", be_file=True)
×
274
    except EnvError:
×
275
        return None
×
276
    try:
×
277
        from asynctor.jsons import json_loads
×
278
    except ImportError:
×
279
        from json import loads as json_loads  # type:ignore[assignment]
×
280
    content = frontend_version_file.read_bytes()
×
281
    metadata: dict[str, str] = json_loads(content)  # type:ignore
×
282
    try:
×
283
        current_version = metadata["version"]
×
284
    except (KeyError, TypeError):
×
285
        return None
×
286
    with contextlib.suppress(ValueError):
×
287
        frontend_version_file = frontend_version_file.relative_to(Path.cwd())
×
288
    return frontend_version_file, current_version
×
289

290

291
@overload
292
def get_current_version(
293
    verbose: bool = False,
294
    is_poetry: bool | None = None,
295
    package_name: str | None = None,
296
    *,
297
    check_version: Literal[False] = False,
298
) -> str: ...
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[True],
308
) -> tuple[bool, str]: ...
309

310

311
def get_current_version(
5✔
312
    verbose: bool = False,
313
    is_poetry: bool | None = None,
314
    package_name: str | None = None,
315
    *,
316
    check_version: bool = False,
317
) -> str | tuple[bool, str]:
318
    if is_poetry is True or Project.manage_by_poetry():
5✔
319
        out = _get_poetry_project_version(verbose)
5✔
320
        if check_version:
5✔
321
            return True, out
5✔
322
        return out
5✔
323
    toml_text = work_dir = None
5✔
324
    if package_name is None:
5✔
325
        try:
5✔
326
            work_dir = Project.get_work_dir()
5✔
327
        except EnvError as e:
×
328
            if (res := _get_frontend_version()) is None:
×
329
                raise e
×
330
            current_version = res[1]
×
331
            if check_version:
×
332
                return False, current_version
×
333
            return current_version
×
334
        else:
335
            toml_text = Project.load_toml_text()
5✔
336
            doc = tomllib.loads(toml_text)
5✔
337
            project_name = doc.get("project", {}).get("name", work_dir.name)
5✔
338
            package_name = re.sub(r"[- ]", "_", project_name)
5✔
339
    local_version = read_version_from_file(package_name, work_dir, toml_text)
5✔
340
    try:
5✔
341
        installed_version = importlib_metadata.version(package_name)
5✔
342
    except importlib_metadata.PackageNotFoundError:
5✔
343
        installed_version = ""
5✔
344
    current_version = local_version or installed_version
5✔
345
    if not current_version:
5✔
346
        raise FastDevCliError(f"Failed to get current version of {package_name!r}")
×
347
    if check_version:
5✔
348
        is_conflict = bool(local_version) and local_version != installed_version
5✔
349
        return is_conflict, current_version
5✔
350
    return current_version
5✔
351

352

353
def _get_poetry_project_version(verbose: bool) -> str:
5✔
354
    cmd = ["poetry", "version", "-s"]
5✔
355
    if verbose:
5✔
356
        echo(f"--> {' '.join(cmd)}")
5✔
357
    if out := capture_cmd_output(cmd, raises=True):
5✔
358
        out = out.splitlines()[-1].strip().split()[-1]
5✔
359
    return out
5✔
360

361

362
def _ensure_bool(value: bool | OptionInfo) -> bool:
5✔
363
    if isinstance(value, bool):
5✔
364
        return value
5✔
365
    return bool(getattr(value, "default", False))
5✔
366

367

368
def _ensure_str(value: str | OptionInfo | None) -> str | None:
5✔
369
    if isinstance(value, str) or value is None:
5✔
370
        return value
5✔
371
    return getattr(value, "default", "")
5✔
372

373

374
class DryRun:
5✔
375
    def __init__(self, _exit: bool = False, dry: bool = False) -> None:
5✔
376
        self.dry = _ensure_bool(dry)
5✔
377
        self._exit = _exit
5✔
378

379
    def gen(self) -> str:
5✔
380
        raise NotImplementedError
5✔
381

382
    def run(self) -> None:
5✔
383
        exit_if_run_failed(self.gen(), _exit=self._exit, dry=self.dry)
5✔
384

385

386
class BumpUp(DryRun):
5✔
387
    class PartChoices(StrEnum):
5✔
388
        patch = "patch"
5✔
389
        minor = "minor"
5✔
390
        major = "major"
5✔
391

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

416
    @staticmethod
5✔
417
    def get_last_commit_message(raises: bool = False) -> str:
5✔
418
        cmd = 'git show --pretty=format:"%s" -s HEAD'
5✔
419
        return capture_cmd_output(cmd, raises=raises)
5✔
420

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

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

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

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

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

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

590
    def run(self) -> None:
5✔
591
        super().run()
5✔
592
        if not self.commit and not self.dry:
5✔
593
            new_version = get_current_version(True)
5✔
594
            echo(new_version)
5✔
595
            if self.part != "patch":
5✔
596
                echo("You may want to pin tag by `fast tag`")
5✔
597

598

599
def _echo_version(version_file: Any, value: str) -> None:
5✔
600
    styled = typer.style(value, bold=True)
5✔
601
    echo(f"Version value in {version_file}: " + styled)
5✔
602

603

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

633

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

659

660
def bump() -> None:
5✔
661
    part, commit = "", False
5✔
662
    if args := sys.argv[2:]:
5✔
663
        if "-c" in args or "--commit" in args:
5✔
664
            commit = True
5✔
665
        for a in args:
5✔
666
            if not a.startswith("-"):
5✔
667
                part = a
5✔
668
                break
5✔
669
    return BumpUp(commit, part, no_sync="--no-sync" in args, dry="--dry" in args).run()
5✔
670

671

672
class Project:
5✔
673
    path_depth = 5
5✔
674
    _tool: ToolName | None = None
5✔
675

676
    @staticmethod
5✔
677
    def is_poetry_v2(text: str) -> bool:
5✔
678
        return 'build-backend = "poetry' in text
5✔
679

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

693
    @staticmethod
5✔
694
    def work_dir(
5✔
695
        name: str, parent: Path, depth: int, be_file: bool = False
696
    ) -> Path | None:
697
        for _ in range(depth):
5✔
698
            if (f := parent.joinpath(name)).exists():
5✔
699
                if be_file:
5✔
700
                    return f
5✔
701
                return parent
5✔
702
            parent = parent.parent
5✔
703
        return None
5✔
704

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

720
    @classmethod
5✔
721
    def load_toml_text(cls: type[Self], name: str = TOML_FILE) -> str:
5✔
722
        toml_file = cls.get_work_dir(name, be_file=True)
5✔
723
        return toml_file.read_text("utf8")
5✔
724

725
    @classmethod
5✔
726
    def manage_by_poetry(cls: type[Self], cache: bool = False) -> bool:
5✔
727
        return cls.get_manage_tool(cache=cache) == "poetry"
5✔
728

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

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

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

813
    @staticmethod
5✔
814
    def python_exec_dir() -> Path:
5✔
815
        return Path(sys.executable).parent
5✔
816

817
    @classmethod
5✔
818
    def get_root_dir(cls: type[Self], cwd: Path | None = None) -> Path:
5✔
819
        root = cwd or Path.cwd()
5✔
820
        venv_parent = cls.python_exec_dir().parent.parent
5✔
821
        if root.is_relative_to(venv_parent):
5✔
822
            root = venv_parent
5✔
823
        return root
5✔
824

825
    @classmethod
5✔
826
    def is_pdm_project(cls, strict: bool = True, cache: bool = False) -> bool:
5✔
827
        if cls.get_manage_tool(cache=cache) != "pdm":
5✔
828
            return False
5✔
829
        if strict:
×
830
            lock_file = cls.get_work_dir() / "pdm.lock"
×
831
            return lock_file.exists()
×
832
        return True
×
833

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

868
    @classmethod
5✔
869
    def sync_dependencies(cls, prod: bool = True) -> None:
5✔
870
        if cmd := cls.get_sync_command():
×
871
            run_and_echo(cmd)
×
872

873

874
class UpgradeDependencies(Project, DryRun):
5✔
875
    def __init__(
5✔
876
        self, _exit: bool = False, dry: bool = False, tool: ToolName = "poetry"
877
    ) -> None:
878
        super().__init__(_exit, dry)
5✔
879
        self._tool = tool
5✔
880

881
    class DevFlag(StrEnum):
5✔
882
        new = "[tool.poetry.group.dev.dependencies]"
5✔
883
        old = "[tool.poetry.dev-dependencies]"
5✔
884

885
    @staticmethod
5✔
886
    def parse_value(version_info: str, key: str) -> str:
5✔
887
        """Pick out the value for key in version info.
888

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

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

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

966
    @classmethod
5✔
967
    def should_with_dev(cls: type[Self]) -> bool:
5✔
968
        text = cls.load_toml_text()
5✔
969
        return cls.DevFlag.new in text or cls.DevFlag.old in text
5✔
970

971
    @staticmethod
5✔
972
    def parse_item(toml_str: str) -> list[str]:
5✔
973
        lines: list[str] = []
5✔
974
        for line in toml_str.splitlines():
5✔
975
            if (line := line.strip()).startswith("["):
5✔
976
                if lines:
5✔
977
                    break
5✔
978
            elif line:
5✔
979
                lines.append(line)
5✔
980
        return lines
5✔
981

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

1017
    @classmethod
5✔
1018
    def gen_cmd(cls: type[Self]) -> str:
5✔
1019
        main_args, dev_args, others, dev_flags = cls.get_args()
5✔
1020
        return cls.to_cmd(main_args, dev_args, others, dev_flags)
5✔
1021

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

1041
    def gen(self) -> str:
5✔
1042
        if self._tool == "uv":
5✔
1043
            up = "uv lock --upgrade --verbose"
5✔
1044
            deps = "uv sync --inexact --frozen --all-groups --all-extras"
5✔
1045
            return f"{up} && {deps}"
5✔
1046
        elif self._tool == "pdm":
5✔
1047
            return "pdm update --verbose && pdm install -G :all --frozen"
5✔
1048
        return self.gen_cmd() + " && poetry lock && poetry update"
5✔
1049

1050

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

1065

1066
class GitTag(DryRun):
5✔
1067
    def __init__(self, message: str, dry: bool, no_sync: bool = False) -> None:
5✔
1068
        self.message = message
5✔
1069
        self._no_sync = no_sync
5✔
1070
        super().__init__(dry=dry)
5✔
1071

1072
    @staticmethod
5✔
1073
    def has_v_prefix() -> bool:
5✔
1074
        return "v" in capture_cmd_output("git tag")
5✔
1075

1076
    def should_push(self) -> bool:
5✔
1077
        return "git push" in self.git_status
5✔
1078

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

1091
    @cached_property
5✔
1092
    def git_status(self) -> str:
5✔
1093
        return capture_cmd_output("git status")
5✔
1094

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

1104
    def run(self) -> None:
5✔
1105
        if self.mark_tag() and not self.dry:
5✔
1106
            echo("You may want to publish package:\n pdm publish")
5✔
1107

1108

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

1120

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

1153
    @staticmethod
5✔
1154
    def check_lint_tool_installed() -> bool:
5✔
1155
        try:
5✔
1156
            return check_call("ruff --version")
5✔
1157
        except FileNotFoundError:
×
1158
            # Windows may raise FileNotFoundError when ruff not installed
1159
            return False
×
1160

1161
    @staticmethod
5✔
1162
    def missing_mypy_exec() -> bool:
5✔
1163
        return shutil.which("mypy") is None
5✔
1164

1165
    @staticmethod
5✔
1166
    def prefer_dmypy(paths: str, tools: list[str], use_dmypy: bool = False) -> bool:
5✔
1167
        return (
5✔
1168
            paths == "."
1169
            and any(t.startswith("mypy") for t in tools)
1170
            and (use_dmypy or load_bool("FASTDEVCLI_DMYPY"))
1171
        )
1172

1173
    @staticmethod
5✔
1174
    def get_package_name() -> str:
5✔
1175
        root = Project.get_work_dir(allow_cwd=True)
5✔
1176
        module_name = root.name.replace("-", "_").replace(" ", "_")
5✔
1177
        package_maybe = (module_name, "src")
5✔
1178
        for name in package_maybe:
5✔
1179
            if root.joinpath(name).is_dir():
5✔
1180
                return name
5✔
1181
        return "."
5✔
1182

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

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

1339

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

1343

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

1377

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

1405

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

1450

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

1468

1469
class Sync(DryRun):
5✔
1470
    def __init__(
5✔
1471
        self, filename: str, extras: str, save: bool, dry: bool = False
1472
    ) -> None:
1473
        self.filename = filename
5✔
1474
        self.extras = extras
5✔
1475
        self._save = save
5✔
1476
        super().__init__(dry=dry)
5✔
1477

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

1509

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

1522

1523
def _should_run_test_script(path: Path = Path("scripts")) -> Path | None:
5✔
1524
    for name in ("test.sh", "test.py"):
5✔
1525
        if (file := path / name).exists():
5✔
1526
            return file
5✔
1527
    return None
5✔
1528

1529

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

1550

1551
@cli.command(name="test")
5✔
1552
def coverage_test(
5✔
1553
    dry: bool = DryOption,
1554
    ignore_script: bool = Option(False, "--ignore-script", "-i"),
1555
) -> None:
1556
    """Run unittest by pytest and report coverage"""
1557
    return test(dry, ignore_script)
5✔
1558

1559

1560
class Publish:
5✔
1561
    class CommandEnum(StrEnum):
5✔
1562
        poetry = "poetry publish --build"
5✔
1563
        pdm = "pdm publish"
5✔
1564
        uv = "uv build && uv publish"
5✔
1565
        twine = "python -m build && twine upload"
5✔
1566

1567
    @classmethod
5✔
1568
    def gen(cls) -> str:
5✔
1569
        if tool := Project.get_manage_tool():
5✔
1570
            return cls.CommandEnum[tool]
5✔
1571
        return cls.CommandEnum.twine
5✔
1572

1573

1574
@cli.command()
5✔
1575
def upload(
5✔
1576
    dry: bool = DryOption,
1577
) -> None:
1578
    """Shortcut for package publish"""
1579
    cmd = Publish.gen()
5✔
1580
    exit_if_run_failed(cmd, dry=dry)
5✔
1581

1582

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

1596

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

1623

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

1649

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

1669

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

1688

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

1706

1707
class MakeDeps(DryRun):
5✔
1708
    def __init__(
5✔
1709
        self,
1710
        tool: str,
1711
        prod: bool = False,
1712
        dry: bool = False,
1713
        active: bool = False,
1714
        inexact: bool = False,
1715
        no_dev: bool = False,
1716
        verbose: bool = False,
1717
        frozen: bool = False,
1718
        no_extra: list[str] | None = None,
1719
        no_group: list[str] | None = None,
1720
    ) -> None:
1721
        self._tool = tool
5✔
1722
        self._prod = prod
5✔
1723
        self._active = active or load_bool("FASTDEVCLI_DEPS_ACTIVE")
5✔
1724
        self._inexact = inexact or load_bool("FASTDEVCLI_DEPS_INEXACT")
5✔
1725
        self._verbose = verbose
5✔
1726
        self._frozen = frozen
5✔
1727
        self._no_dev = no_dev
5✔
1728
        self._no_extra = no_extra
5✔
1729
        self._no_group = no_group
5✔
1730
        super().__init__(dry=dry)
5✔
1731

1732
    def should_ensure_pip(self) -> bool:
5✔
1733
        return True
5✔
1734

1735
    def should_upgrade_pip(self) -> bool:
5✔
1736
        return True
5✔
1737

1738
    def get_groups(self) -> list[str]:
5✔
1739
        if self._prod:
5✔
1740
            return []
5✔
1741
        return ["dev"]
5✔
1742

1743
    def gen(self) -> str:
5✔
1744
        cmd = self._gen()
5✔
1745
        if self._verbose:
5✔
1746
            cmd += " --verbose"
×
1747
        if self._no_dev:
5✔
1748
            opt = " --no-dev"
×
1749
            if opt not in cmd:
×
1750
                cmd += opt
×
1751
        if self._no_extra:
5✔
1752
            cmd += " " + " ".join(f"--no-extra {i}" for i in self._no_extra)
×
1753
        if self._no_group:
5✔
1754
            cmd += " " + " ".join(f"--no-group {i}" for i in self._no_group)
×
1755
        if self._frozen:
5✔
1756
            cmd += " --frozen"
×
1757
        if opts := os.getenv("FASTDEVCLI_DEPS_OPTS"):
5✔
1758
            cmd += " " + opts.strip()
×
1759
        return cmd
5✔
1760

1761
    def get_package_name(self) -> str:
5✔
1762
        with contextlib.suppress(FileNotFoundError, KeyError):
5✔
1763
            try:
5✔
1764
                toml_text = Project.load_toml_text()
5✔
1765
            except EnvError:
×
1766
                return ""
×
1767
            doc = tomllib.loads(toml_text)
5✔
1768
            tool_section = doc["tool"]
5✔
1769
            uv_package = tool_section.get("uv", {}).get("package")
5✔
1770
            if uv_package is not None:
5✔
1771
                return doc["project"]["name"] if uv_package else ""
×
1772
            match doc["build-system"]["build-backend"]:
5✔
1773
                case "pdm.backend":
5✔
1774
                    if not tool_section.get("pdm", {}).get("distribution", True):
5✔
1775
                        return ""
×
1776
                case x if x.startswith("poetry"):
×
1777
                    if not tool_section.get("poetry", {}).get("package-mode", True):
×
1778
                        return ""
×
1779
            return doc["project"]["name"]
5✔
1780
        return ""
×
1781

1782
    def _gen(self) -> str:
5✔
1783
        if self._tool == "pdm":
5✔
1784
            return "pdm install --frozen " + ("--prod" if self._prod else "-G :all")
5✔
1785
        elif self._tool == "uv":
5✔
1786
            uv_sync = "uv sync"
5✔
1787
            if project := self.get_package_name():
5✔
1788
                uv_sync += f" --reinstall-package={project}"
5✔
1789
            uv_sync += " --inexact" * self._inexact + " --active" * self._active
5✔
1790
            return uv_sync + (
5✔
1791
                " --no-dev" if self._prod else " --all-extras --all-groups"
1792
            )
1793
        elif self._tool == "poetry":
5✔
1794
            return "poetry install " + (
5✔
1795
                "--only=main" if self._prod else "--all-extras --all-groups"
1796
            )
1797
        else:
1798
            cmd = "python -m pip install -e ."
5✔
1799
            if gs := self.get_groups():
5✔
1800
                cmd += " " + " ".join(f"--group {g}" for g in gs)
5✔
1801
            upgrade = "python -m pip install --upgrade pip"
5✔
1802
            if self.should_ensure_pip():
5✔
1803
                cmd = f"python -m ensurepip && {upgrade} && {cmd}"
5✔
1804
            elif self.should_upgrade_pip():
5✔
1805
                cmd = f"{upgrade} && {cmd}"
5✔
1806
            return cmd
5✔
1807

1808

1809
@cli.command(name="deps")
5✔
1810
def make_deps(
5✔
1811
    prod: bool = Option(
1812
        False,
1813
        "--prod",
1814
        help="Only instead production dependencies.",
1815
    ),
1816
    tool: str = ToolOption,
1817
    use_uv: bool = Option(False, "--uv", help="Use `uv` to install deps"),
1818
    use_pdm: bool = Option(False, "--pdm", help="Use `pdm` to install deps"),
1819
    use_pip: bool = Option(False, "--pip", help="Use `pip` to install deps"),
1820
    use_poetry: bool = Option(False, "--poetry", help="Use `poetry` to install deps"),
1821
    active: bool = Option(
1822
        False, help="Add `--active` to uv sync command(Only work for uv project)"
1823
    ),
1824
    inexact: bool = Option(
1825
        False, help="Add `--inexact` to uv sync command(Only work for uv project)"
1826
    ),
1827
    no_dev: bool = Option(False, "--no-dev"),
1828
    no_extra: Annotated[list[str] | None, Option()] = None,
1829
    no_group: Annotated[list[str] | None, Option()] = None,
1830
    frozen: bool = Option(False, "--frozen", "--frozen-lockfile", "--no-lock"),
1831
    verbose: bool = Option(False, "--verbose"),
1832
    dry: bool = DryOption,
1833
) -> None:
1834
    """Run: ruff check/format to reformat code and then mypy to check"""
1835
    if use_uv + use_pdm + use_pip + use_poetry > 1:
×
1836
        raise typer.BadParameter(
×
1837
            "can only choose one",
1838
            param_hint=("--uv", "--pdm", "--pip", "--poetry"),
1839
        )
1840
    if use_uv:
×
1841
        tool = "uv"
×
1842
    elif use_pdm:
×
1843
        tool = "pdm"
×
1844
    elif use_pip:
×
1845
        tool = "pip"
×
1846
    elif use_poetry:
×
1847
        tool = "poetry"
×
1848
    elif tool == ToolOption.default:
×
1849
        tool = Project.get_manage_tool(cache=True) or "pip"
×
1850
    bool_opts = {
×
1851
        "active": active,
1852
        "inexact": inexact,
1853
        "no_dev": no_dev,
1854
        "verbose": verbose,
1855
        "frozen": frozen,
1856
        "dry": dry,
1857
    }
1858
    MakeDeps(tool, prod, no_extra=no_extra, no_group=no_group, **bool_opts).run()
×
1859

1860

1861
class UvPypi(DryRun):
5✔
1862
    PYPI = "https://pypi.org/simple"
5✔
1863
    HOST = "https://files.pythonhosted.org"
5✔
1864

1865
    def __init__(
5✔
1866
        self,
1867
        lock_file: Path,
1868
        dry: bool,
1869
        verbose: bool,
1870
        quiet: bool,
1871
        slim: bool = False,
1872
        reverse: bool = False,
1873
    ) -> None:
1874
        super().__init__(dry=dry)
5✔
1875
        self.lock_file = lock_file
5✔
1876
        self._verbose = _ensure_bool(verbose)
5✔
1877
        self._quiet = _ensure_bool(quiet)
5✔
1878
        self._slim = _ensure_bool(slim)
5✔
1879
        self._reverse = _ensure_bool(reverse)
5✔
1880

1881
    def run(self) -> None:
5✔
1882
        try:
5✔
1883
            rc = self.update_lock(
5✔
1884
                self.lock_file, self._verbose, self._quiet, self._slim, self._reverse
1885
            )
1886
        except ValueError as e:
×
1887
            secho(str(e), fg=typer.colors.RED)
×
1888
            raise Exit(1) from e
×
1889
        else:
1890
            if rc != 0:
5✔
1891
                raise Exit(rc)
5✔
1892

1893
    @staticmethod
5✔
1894
    def get_target_content(
5✔
1895
        text: str, verbose: bool, target_registry, target_host: str
1896
    ) -> str | None:
1897
        registry_pattern = r'(registry = ")(.*?)"'
5✔
1898
        registry_urls = {i[1] for i in re.findall(registry_pattern, text)}
5✔
1899
        download_pattern = r'(url = ")(https?://.*?)(/packages/.*?\.)(gz|whl|zip)"'
5✔
1900
        download_hosts = {i[1] for i in re.findall(download_pattern, text)}
5✔
1901
        if not registry_urls:
5✔
1902
            raise ValueError(
×
1903
                f"Failed to find pattern {registry_pattern!r} in uv lock file"
1904
            )
1905

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

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

1912
        if len(registry_urls) == 1:
5✔
1913
            current_registry = registry_urls.pop()
5✔
1914
            if current_registry == target_registry:
5✔
1915
                if download_hosts == {target_host}:
5✔
1916
                    return None
5✔
1917
            else:
1918
                text = replace_registry(text)
5✔
1919
                if verbose:
5✔
1920
                    echo(f"{current_registry} --> {target_registry}")
5✔
1921
        else:
1922
            # TODO: ask each one to confirm replace
1923
            text = replace_registry(text)
×
1924
            if verbose:
×
1925
                for current_registry in sorted(registry_urls):
×
1926
                    echo(f"{current_registry} --> {target_registry}")
×
1927
        if len(download_hosts) == 1:
5✔
1928
            current_host = download_hosts.pop()
5✔
1929
            if current_host != target_host:
5✔
1930
                text = replace_host(text)
5✔
1931
                if verbose:
5✔
1932
                    echo(f"{current_host} --> {target_host}")
5✔
1933
        elif download_hosts:
×
1934
            # TODO: ask each one to confirm replace
1935
            text = replace_host(text)
×
1936
            if verbose:
×
1937
                for current_host in sorted(download_hosts):
×
1938
                    echo(f"{current_host} --> {target_host}")
×
1939
        return text
5✔
1940

1941
    @classmethod
5✔
1942
    def update_lock(
5✔
1943
        cls,
1944
        p: Path,
1945
        verbose: bool,
1946
        quiet: bool,
1947
        slim: bool = False,
1948
        reverse: bool = False,
1949
    ) -> int:
1950
        text = p.read_text("utf-8")
5✔
1951
        target_register, target_host = cls.PYPI, cls.HOST
5✔
1952
        if reverse:
5✔
1953
            try:
5✔
1954
                target_register, target_host = cls.get_register_from_uv_config()
5✔
1955
            except FileNotFoundError:
5✔
1956
                if verbose:
5✔
1957
                    echo("Skip register reverse as global uv config file not found.")
5✔
1958
                if quiet:
5✔
1959
                    return 0
5✔
1960
                return 1
×
1961
        new_text = cls.get_target_content(text, verbose, target_register, target_host)
5✔
1962
        if new_text is None:
5✔
1963
            if verbose:
5✔
1964
                echo(f"Registry of {p} is {target_register}, no need to change.")
5✔
1965
            return 0
5✔
1966
        return cls.slim_and_write(new_text, slim, p, verbose, quiet)
5✔
1967

1968
    @classmethod
5✔
1969
    def get_register_from_uv_config(cls) -> tuple[str, str]:
5✔
1970
        config_file = cls.get_uv_config_file()
5✔
1971
        text = config_file.read_text("utf-8")
5✔
1972
        doc = tomllib.loads(text)
5✔
1973
        index_url = doc["index"][0]["url"]
5✔
1974
        return index_url, index_url.replace("/simple", "").rstrip("/")
5✔
1975

1976
    @staticmethod
5✔
1977
    def get_uv_config_file() -> Path:
5✔
1978
        config_dir = "AppData/Roaming" if is_windows() else ".config"
5✔
1979
        return Path.home() / config_dir / "uv/uv.toml"
5✔
1980

1981
    @staticmethod
5✔
1982
    def slim_and_write(
5✔
1983
        text: str, slim: bool, p: Path, verbose: bool, quiet: bool
1984
    ) -> int:
1985
        if slim:
5✔
1986
            pattern = r', size = \d+, upload-time = ".*?"'
5✔
1987
            text = re.sub(pattern, "", text)
5✔
1988
        size = p.write_text(text, encoding="utf-8")
5✔
1989
        if verbose:
5✔
1990
            echo(f"Updated {p} with {size} bytes.")
5✔
1991
        if quiet:
5✔
1992
            return 0
5✔
1993
        return 1
5✔
1994

1995

1996
@cli.command()
5✔
1997
def pypi(
5✔
1998
    file: str | None = typer.Argument(default=None),
1999
    dry: bool = DryOption,
2000
    verbose: bool = False,
2001
    quiet: bool = False,
2002
    slim: bool = False,
2003
    reverse: bool = False,
2004
) -> None:
2005
    """Change registry of uv.lock to be pypi.org"""
2006
    if not (p := Path(_ensure_str(file) or "uv.lock")).exists() and not (
5✔
2007
        (p := Project.get_work_dir() / p.name).exists()
2008
    ):
2009
        yellow_warn(f"{p.name!r} not found!")
5✔
2010
        return
5✔
2011
    UvPypi(p, dry, verbose, quiet, slim, reverse).run()
5✔
2012

2013

2014
def version_callback(value: bool) -> None:
5✔
2015
    if value:
5✔
2016
        echo("Fast Dev Cli Version: " + typer.style(__version__, bold=True))
5✔
2017
        raise Exit()
5✔
2018

2019

2020
@cli.callback()
2021
def common(
2022
    version: bool = Option(
2023
        None,
2024
        "--version",
2025
        "-V",
2026
        callback=version_callback,
2027
        is_eager=True,
2028
        help="Show the version of this tool",
2029
    ),
2030
) -> None: ...
2031

2032

2033
def main() -> None:
5✔
2034
    cli()
5✔
2035

2036

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

© 2026 Coveralls, Inc