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

waketzheng / fast-dev-cli / 19524307970

20 Nov 2025 03:11AM UTC coverage: 87.305% (-0.06%) from 87.361%
19524307970

push

github

waketzheng
docs: update changelog and readme

949 of 1087 relevant lines covered (87.3%)

4.36 hits per line

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

87.29
/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 click import UsageError
5✔
19
from typer import Exit, Option, echo, secho
5✔
20
from typer.models import ArgumentInfo, OptionInfo
5✔
21

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

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

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

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

36
    import tomli as tomllib
37

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

41

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

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

56

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

60

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

64

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

68

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

72

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

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

82
    return canonicalize_name(name).replace("-", "_").replace(" ", "_")
5✔
83

84

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

96

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

101

102
def yellow_warn(msg: str) -> None:
5✔
103
    if is_windows() and (encoding := sys.stdout.encoding) != "utf-8":
5✔
104
        msg = msg.encode(encoding, errors="ignore").decode(encoding)
×
105
    secho(msg, fg="yellow")
5✔
106

107

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

118

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

125

126
class Shell:
5✔
127
    def __init__(self, cmd: list[str] | str, **kw: Any) -> None:
5✔
128
        self._cmd = cmd
5✔
129
        self._kw = kw
5✔
130

131
    @staticmethod
5✔
132
    def run_by_subprocess(
5✔
133
        cmd: list[str] | str, **kw: Any
134
    ) -> subprocess.CompletedProcess[str]:
135
        if isinstance(cmd, str):
5✔
136
            kw.setdefault("shell", True)
5✔
137
        return subprocess.run(cmd, **kw)  # nosec:B603
5✔
138

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

152
    @staticmethod
5✔
153
    def extend_user(cs: list[str]) -> list[str]:
5✔
154
        if cs[0] == "echo":
5✔
155
            return cs
5✔
156
        for i, c in enumerate(cs):
5✔
157
            if c.startswith("~"):
5✔
158
                cs[i] = os.path.expanduser(c)
×
159
        return cs
5✔
160

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

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

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

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

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

197

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

204

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

208

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

214

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

224

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

228

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

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

271

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

281

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

291

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

328

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

334

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

340

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

346
    def gen(self) -> str:
5✔
347
        raise NotImplementedError
5✔
348

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

352

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

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

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

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

395
    @staticmethod
5✔
396
    def parse_dynamic_version(
5✔
397
        toml_text: str,
398
        context: dict,
399
        work_dir: Path | None = None,
400
    ) -> str | None:
401
        if work_dir is None:
5✔
402
            work_dir = Project.get_work_dir()
5✔
403
        for tool in ("pdm", "hatch"):
5✔
404
            with contextlib.suppress(KeyError):
5✔
405
                version_path = cast(str, context["tool"][tool]["version"]["path"])
5✔
406
                if (
5✔
407
                    Path(version_path).exists()
408
                    or work_dir.joinpath(version_path).exists()
409
                ):
410
                    return version_path
5✔
411
        # version = { source = "file", path = "fast_dev_cli/__init__.py" }
412
        v_key = "version = "
5✔
413
        p_key = 'path = "'
5✔
414
        for line in toml_text.splitlines():
5✔
415
            if not line.startswith(v_key):
×
416
                continue
×
417
            if p_key in (value := line.split(v_key, 1)[-1].split("#")[0]):
×
418
                filename = value.split(p_key, 1)[-1].split('"')[0]
×
419
                if work_dir.joinpath(filename).exists():
×
420
                    return filename
×
421
        return None
5✔
422

423
    @classmethod
5✔
424
    def parse_filename(
5✔
425
        cls,
426
        toml_text: str | None = None,
427
        work_dir: Path | None = None,
428
        package_name: str | None = None,
429
    ) -> str:
430
        if toml_text is None:
5✔
431
            toml_text = Project.load_toml_text()
5✔
432
        context = tomllib.loads(toml_text)
5✔
433
        by_version_plugin = False
5✔
434
        try:
5✔
435
            ver = context["project"]["version"]
5✔
436
        except KeyError:
5✔
437
            pass
5✔
438
        else:
439
            if isinstance(ver, str):
5✔
440
                if ver in ("0", "0.0.0"):
5✔
441
                    by_version_plugin = True
5✔
442
                elif re.match(r"\d+\.\d+\.\d+", ver):
5✔
443
                    return TOML_FILE
5✔
444
        if not by_version_plugin:
5✔
445
            try:
5✔
446
                version_value = context["tool"]["poetry"]["version"]
5✔
447
            except KeyError:
5✔
448
                if not Project.manage_by_poetry() and (
5✔
449
                    filename := cls.parse_dynamic_version(toml_text, context, work_dir)
450
                ):
451
                    return filename
5✔
452
            else:
453
                by_version_plugin = version_value in ("0", "0.0.0", "init")
5✔
454
        if by_version_plugin:
5✔
455
            return cls.parse_plugin_version(context, package_name)
5✔
456

457
        return TOML_FILE
5✔
458

459
    @staticmethod
5✔
460
    def parse_plugin_version(context: dict, package_name: str | None) -> str:
5✔
461
        try:
5✔
462
            package_item = context["tool"]["poetry"]["packages"]
5✔
463
        except KeyError:
5✔
464
            try:
5✔
465
                project_name = context["project"]["name"]
5✔
466
            except KeyError:
5✔
467
                packages = []
5✔
468
            else:
469
                packages = [(poetry_module_name(project_name), "")]
×
470
        else:
471
            packages = [
5✔
472
                (j, i.get("from", "")) for i in package_item if (j := i.get("include"))
473
            ]
474
        # In case of managed by `poetry-plugin-version`
475
        cwd = Path.cwd()
5✔
476
        pattern = re.compile(r"__version__\s*=\s*['\"]")
5✔
477
        ds: list[Path] = []
5✔
478
        if package_name is not None:
5✔
479
            packages.insert(0, (package_name, ""))
×
480
        for package_name, source_dir in packages:
5✔
481
            ds.append(cwd / package_name)
5✔
482
            ds.append(cwd / "src" / package_name)
5✔
483
            if source_dir and source_dir != "src":
5✔
484
                ds.append(cwd / source_dir / package_name)
5✔
485
        module_name = poetry_module_name(cwd.name)
5✔
486
        ds.extend([cwd / module_name, cwd / "src" / module_name, cwd])
5✔
487
        for d in ds:
5✔
488
            init_file = d / "__init__.py"
5✔
489
            if (init_file.exists() and pattern.search(init_file.read_text("utf8"))) or (
5✔
490
                (init_file := init_file.with_name("__version__.py")).exists()
491
                and pattern.search(init_file.read_text("utf8"))
492
            ):
493
                break
5✔
494
        else:
495
            raise ParseError("Version file not found! Where are you now?")
5✔
496
        return os.path.relpath(init_file, cwd)
5✔
497

498
    def get_part(self, s: str) -> str:
5✔
499
        choices: dict[str, str] = {}
5✔
500
        for i, p in enumerate(self.PartChoices, 1):
5✔
501
            v = str(p)
5✔
502
            choices.update({str(i): v, v: v})
5✔
503
        try:
5✔
504
            return choices[s]
5✔
505
        except KeyError as e:
5✔
506
            echo(f"Invalid part: {s!r}")
5✔
507
            raise Exit(1) from e
5✔
508

509
    def gen(self) -> str:
5✔
510
        should_sync, _version = get_current_version(check_version=True)
5✔
511
        filename = self.filename
5✔
512
        echo(f"Current version(@{filename}): {_version}")
5✔
513
        if self.part:
5✔
514
            part = self.get_part(self.part)
5✔
515
        else:
516
            part = "patch"
5✔
517
            if a := input("Which one?").strip():
5✔
518
                part = self.get_part(a)
5✔
519
        self.part = part
5✔
520
        parse = r'--parse "(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)"'
5✔
521
        cmd = f'bumpversion {parse} --current-version="{_version}" {part} {filename}'
5✔
522
        if self.commit:
5✔
523
            if part != "patch":
5✔
524
                cmd += " --tag"
5✔
525
            cmd += " --commit"
5✔
526
            if self._emoji or (self._emoji is None and self.should_add_emoji()):
5✔
527
                cmd += " --message-emoji=1"
5✔
528
            if not load_bool("DONT_GIT_PUSH"):
5✔
529
                cmd += " && git push && git push --tags && git log -1"
5✔
530
        else:
531
            cmd += " --allow-dirty"
5✔
532
        if (
5✔
533
            should_sync
534
            and not self._no_sync
535
            and (sync := Project.get_sync_command(only_me=True))
536
        ):
537
            cmd = f"{sync} && " + cmd
5✔
538
        return cmd
5✔
539

540
    def run(self) -> None:
5✔
541
        super().run()
5✔
542
        if not self.commit and not self.dry:
5✔
543
            new_version = get_current_version(True)
5✔
544
            echo(new_version)
5✔
545
            if self.part != "patch":
5✔
546
                echo("You may want to pin tag by `fast tag`")
5✔
547

548

549
@cli.command()
5✔
550
def version() -> None:
5✔
551
    """Show the version of this tool"""
552
    echo("Fast Dev Cli Version: " + typer.style(__version__, fg=typer.colors.BLUE))
5✔
553
    with contextlib.suppress(FileNotFoundError, KeyError):
5✔
554
        toml_text = Project.load_toml_text()
5✔
555
        doc = tomllib.loads(toml_text)
5✔
556
        if value := doc.get("project", {}).get("version", ""):
5✔
557
            styled = typer.style(value, bold=True, fg=typer.colors.CYAN)
×
558
            if project_name := doc["project"].get("name", ""):
×
559
                echo(f"{project_name} version: " + styled)
×
560
            else:
561
                echo(f"Got Version from {TOML_FILE}: " + styled)
×
562
            return
×
563
        version_file = doc["tool"]["pdm"]["version"]["path"]
5✔
564
        text = Project.get_work_dir().joinpath(version_file).read_text()
5✔
565
        varname = "__version__"
5✔
566
        for line in text.splitlines():
5✔
567
            if line.strip().startswith(varname):
5✔
568
                value = line.split("=", 1)[-1].strip().strip('"').strip("'")
5✔
569
                styled = typer.style(value, bold=True)
5✔
570
                echo(f"Version value in {version_file}: " + styled)
5✔
571
                break
5✔
572

573

574
@cli.command(name="bump")
5✔
575
def bump_version(
5✔
576
    part: BumpUp.PartChoices,
577
    commit: bool = Option(
578
        False, "--commit", "-c", help="Whether run `git commit` after version changed"
579
    ),
580
    emoji: bool | None = Option(
581
        None, "--emoji", help="Whether add emoji prefix to commit message"
582
    ),
583
    no_sync: bool = Option(
584
        False, "--no-sync", help="Do not run sync command to update version"
585
    ),
586
    dry: bool = DryOption,
587
) -> None:
588
    """Bump up version string in pyproject.toml"""
589
    if emoji is not None:
5✔
590
        emoji = _ensure_bool(emoji)
5✔
591
    return BumpUp(
5✔
592
        _ensure_bool(commit),
593
        getattr(part, "value", part),
594
        no_sync=_ensure_bool(no_sync),
595
        emoji=emoji,
596
        dry=dry,
597
    ).run()
598

599

600
def bump() -> None:
5✔
601
    part, commit = "", False
5✔
602
    if args := sys.argv[2:]:
5✔
603
        if "-c" in args or "--commit" in args:
5✔
604
            commit = True
5✔
605
        for a in args:
5✔
606
            if not a.startswith("-"):
5✔
607
                part = a
5✔
608
                break
5✔
609
    return BumpUp(commit, part, no_sync="--no-sync" in args, dry="--dry" in args).run()
5✔
610

611

612
class Project:
5✔
613
    path_depth = 5
5✔
614
    _tool: ToolName | None = None
5✔
615

616
    @staticmethod
5✔
617
    def is_poetry_v2(text: str) -> bool:
5✔
618
        return 'build-backend = "poetry' in text
5✔
619

620
    @staticmethod
5✔
621
    def get_poetry_version(command: str = "poetry") -> str:
5✔
622
        pattern = r"(\d+\.\d+\.\d+)"
5✔
623
        text = capture_cmd_output(f"{command} --version")
5✔
624
        for expr in (
5✔
625
            rf"Poetry \(version {pattern}\)",
626
            rf"Poetry.*version.*{pattern}.*\)",
627
            rf"{pattern}",
628
        ):
629
            if m := re.search(expr, text):
5✔
630
                return m.group(1)
5✔
631
        return ""
×
632

633
    @staticmethod
5✔
634
    def work_dir(
5✔
635
        name: str, parent: Path, depth: int, be_file: bool = False
636
    ) -> Path | None:
637
        for _ in range(depth):
5✔
638
            if (f := parent.joinpath(name)).exists():
5✔
639
                if be_file:
5✔
640
                    return f
5✔
641
                return parent
5✔
642
            parent = parent.parent
5✔
643
        return None
5✔
644

645
    @classmethod
5✔
646
    def get_work_dir(
5✔
647
        cls: type[Self],
648
        name: str = TOML_FILE,
649
        cwd: Path | None = None,
650
        allow_cwd: bool = False,
651
        be_file: bool = False,
652
    ) -> Path:
653
        cwd = cwd or Path.cwd()
5✔
654
        if d := cls.work_dir(name, cwd, cls.path_depth, be_file):
5✔
655
            return d
5✔
656
        if allow_cwd:
5✔
657
            return cls.get_root_dir(cwd)
5✔
658
        raise EnvError(f"{name} not found! Make sure this is a python project.")
5✔
659

660
    @classmethod
5✔
661
    def load_toml_text(cls: type[Self], name: str = TOML_FILE) -> str:
5✔
662
        toml_file = cls.get_work_dir(name, be_file=True)
5✔
663
        return toml_file.read_text("utf8")
5✔
664

665
    @classmethod
5✔
666
    def manage_by_poetry(cls: type[Self], cache: bool = False) -> bool:
5✔
667
        return cls.get_manage_tool(cache=cache) == "poetry"
5✔
668

669
    @classmethod
5✔
670
    def get_manage_tool(cls: type[Self], cache: bool = False) -> ToolName | None:
5✔
671
        if cache and cls._tool:
5✔
672
            return cls._tool
5✔
673
        try:
5✔
674
            text = cls.load_toml_text()
5✔
675
        except EnvError:
5✔
676
            return None
5✔
677
        backend = ""
5✔
678
        skip_uv = load_bool("FASTDEVCLI_SKIP_UV")
5✔
679
        with contextlib.suppress(KeyError, tomllib.TOMLDecodeError):
5✔
680
            doc = tomllib.loads(text)
5✔
681
            backend = doc["build-system"]["build-backend"]
5✔
682
            if skip_uv:
5✔
683
                for t in ("pdm", "poetry"):
×
684
                    if t in backend:
×
685
                        cls._tool = t
×
686
                        return cls._tool
×
687
        work_dir: Path | None = None
5✔
688
        uv_lock_exists: bool | None = None
5✔
689
        if skip_uv:
5✔
690
            for name in ("pdm", "poetry"):
×
691
                if f"[tool.{name}]" in text:
×
692
                    cls._tool = cast(ToolName, name)
×
693
                    return cls._tool
×
694
            work_dir = cls.get_work_dir(allow_cwd=True)
×
695
            for name in ("pdm", "poetry"):
×
696
                if Path(work_dir, f"{name}.lock").exists():
×
697
                    cls._tool = cast(ToolName, name)
×
698
                    return cls._tool
×
699
            if uv_lock_exists := Path(work_dir, "uv.lock").exists():
×
700
                # Use pdm when uv is not available for uv managed project
701
                cls._tool = "pdm"
×
702
                return cls._tool
×
703
            return None
×
704
        if work_dir is None:
5✔
705
            work_dir = cls.get_work_dir(allow_cwd=True)
5✔
706
        if uv_lock_exists is None:
5✔
707
            uv_lock_exists = Path(work_dir, "uv.lock").exists()
5✔
708
        if uv_lock_exists:
5✔
709
            cls._tool = "uv"
5✔
710
            return cls._tool
5✔
711
        pdm_lock_exists = Path(work_dir, "pdm.lock").exists()
5✔
712
        poetry_lock_exists = Path(work_dir, "poetry.lock").exists()
5✔
713
        match pdm_lock_exists + poetry_lock_exists:
5✔
714
            case 1:
5✔
715
                cls._tool = "pdm" if pdm_lock_exists else "poetry"
5✔
716
                return cls._tool
5✔
717
            case _ as x:
5✔
718
                if backend:
5✔
719
                    for t in ("pdm", "poetry"):
5✔
720
                        if t in backend:
5✔
721
                            cls._tool = cast(ToolName, t)
5✔
722
                            return cls._tool
5✔
723
                for name in ("pdm", "poetry"):
5✔
724
                    if f"[tool.{name}]" in text:
5✔
725
                        cls._tool = cast(ToolName, name)
5✔
726
                        return cls._tool
5✔
727
                if x == 2:
5✔
728
                    cls._tool = (
×
729
                        "poetry" if load_bool("FASTDEVCLI_PREFER_POETRY") else "pdm"
730
                    )
731
                    return cls._tool
1✔
732
        if "[tool.uv]" in text or load_bool("FASTDEVCLI_PREFER_uv"):
5✔
733
            cls._tool = "uv"
5✔
734
            return cls._tool
5✔
735
        # Poetry 2.0 default to not include the '[tool.poetry]' section
736
        if cls.is_poetry_v2(text):
5✔
737
            cls._tool = "poetry"
×
738
            return cls._tool
×
739
        return None
5✔
740

741
    @staticmethod
5✔
742
    def python_exec_dir() -> Path:
5✔
743
        return Path(sys.executable).parent
5✔
744

745
    @classmethod
5✔
746
    def get_root_dir(cls: type[Self], cwd: Path | None = None) -> Path:
5✔
747
        root = cwd or Path.cwd()
5✔
748
        venv_parent = cls.python_exec_dir().parent.parent
5✔
749
        if root.is_relative_to(venv_parent):
5✔
750
            root = venv_parent
5✔
751
        return root
5✔
752

753
    @classmethod
5✔
754
    def is_pdm_project(cls, strict: bool = True, cache: bool = False) -> bool:
5✔
755
        if cls.get_manage_tool(cache=cache) != "pdm":
5✔
756
            return False
5✔
757
        if strict:
×
758
            lock_file = cls.get_work_dir() / "pdm.lock"
×
759
            return lock_file.exists()
×
760
        return True
×
761

762
    @classmethod
5✔
763
    def get_sync_command(
5✔
764
        cls, prod: bool = True, doc: dict | None = None, only_me: bool = False
765
    ) -> str:
766
        pdm_i = "pdm install --frozen" + " --prod" * prod
5✔
767
        if cls.is_pdm_project():
5✔
768
            return pdm_i
×
769
        elif cls.manage_by_poetry(cache=True):
5✔
770
            cmd = "poetry install"
5✔
771
            if prod:
5✔
772
                if doc is None:
5✔
773
                    doc = tomllib.loads(cls.load_toml_text())
5✔
774
                if doc.get("project", {}).get("dependencies") or any(
5✔
775
                    i != "python"
776
                    for i in doc.get("tool", {})
777
                    .get("poetry", {})
778
                    .get("dependencies", [])
779
                ):
780
                    cmd += " --only=main"
×
781
            return cmd
5✔
782
        elif cls.get_manage_tool(cache=True) == "uv":
×
783
            install_me = "uv pip install -e ."
×
784
            if doc is None:
×
785
                doc = tomllib.loads(cls.load_toml_text())
×
786
            is_distribution = (
×
787
                doc.get("tool", {}).get("pdm", {}).get("distribution") is not False
788
            )
789
            if only_me:
×
790
                return install_me if is_distribution else pdm_i
×
791
            cmd = "uv sync --inexact" + " --no-dev" * prod
×
792
            if is_distribution:
×
793
                cmd += f" && {install_me}"
×
794
        return ""
×
795

796
    @classmethod
5✔
797
    def sync_dependencies(cls, prod: bool = True) -> None:
5✔
798
        if cmd := cls.get_sync_command():
×
799
            run_and_echo(cmd)
×
800

801

802
class UpgradeDependencies(Project, DryRun):
5✔
803
    def __init__(
5✔
804
        self, _exit: bool = False, dry: bool = False, tool: ToolName = "poetry"
805
    ) -> None:
806
        super().__init__(_exit, dry)
5✔
807
        self._tool = tool
5✔
808

809
    class DevFlag(StrEnum):
5✔
810
        new = "[tool.poetry.group.dev.dependencies]"
5✔
811
        old = "[tool.poetry.dev-dependencies]"
5✔
812

813
    @staticmethod
5✔
814
    def parse_value(version_info: str, key: str) -> str:
5✔
815
        """Pick out the value for key in version info.
816

817
        Example::
818
            >>> s= 'typer = {extras = ["all"], version = "^0.9.0", optional = true}'
819
            >>> UpgradeDependencies.parse_value(s, 'extras')
820
            'all'
821
            >>> UpgradeDependencies.parse_value(s, 'optional')
822
            'true'
823
            >>> UpgradeDependencies.parse_value(s, 'version')
824
            '^0.9.0'
825
        """
826
        sep = key + " = "
5✔
827
        rest = version_info.split(sep, 1)[-1].strip(" =")
5✔
828
        if rest.startswith("["):
5✔
829
            rest = rest[1:].split("]")[0]
5✔
830
        elif rest.startswith('"'):
5✔
831
            rest = rest[1:].split('"')[0]
5✔
832
        else:
833
            rest = rest.split(",")[0].split("}")[0]
5✔
834
        return rest.strip().replace('"', "")
5✔
835

836
    @staticmethod
5✔
837
    def no_need_upgrade(version_info: str, line: str) -> bool:
5✔
838
        if (v := version_info.replace(" ", "")).startswith("{url="):
5✔
839
            echo(f"No need to upgrade for: {line}")
5✔
840
            return True
5✔
841
        if (f := "version=") in v:
5✔
842
            v = v.split(f)[1].strip('"').split('"')[0]
5✔
843
        if v == "*":
5✔
844
            echo(f"Skip wildcard line: {line}")
5✔
845
            return True
5✔
846
        elif v == "[":
5✔
847
            echo(f"Skip complex dependence: {line}")
5✔
848
            return True
5✔
849
        elif v.startswith(">") or v.startswith("<") or v[0].isdigit():
5✔
850
            echo(f"Ignore bigger/smaller/equal: {line}")
5✔
851
            return True
5✔
852
        return False
5✔
853

854
    @classmethod
5✔
855
    def build_args(
5✔
856
        cls: type[Self], package_lines: list[str]
857
    ) -> tuple[list[str], dict[str, list[str]]]:
858
        args: list[str] = []  # ['typer[all]', 'fastapi']
5✔
859
        specials: dict[str, list[str]] = {}  # {'--platform linux': ['gunicorn']}
5✔
860
        for no, line in enumerate(package_lines, 1):
5✔
861
            if (
5✔
862
                not (m := line.strip())
863
                or m.startswith("#")
864
                or m == "]"
865
                or (m.startswith("{") and m.strip(",").endswith("}"))
866
            ):
867
                continue
5✔
868
            try:
5✔
869
                package, version_info = m.split("=", 1)
5✔
870
            except ValueError as e:
5✔
871
                raise ParseError(f"Failed to separate by '='@line {no}: {m}") from e
5✔
872
            if (package := package.strip()).lower() == "python":
5✔
873
                continue
5✔
874
            if cls.no_need_upgrade(version_info := version_info.strip(' "'), line):
5✔
875
                continue
5✔
876
            if (extras_tip := "extras") in version_info:
5✔
877
                package += "[" + cls.parse_value(version_info, extras_tip) + "]"
5✔
878
            item = f'"{package}@latest"'
5✔
879
            key = None
5✔
880
            if (pf := "platform") in version_info:
5✔
881
                platform = cls.parse_value(version_info, pf)
5✔
882
                key = f"--{pf}={platform}"
5✔
883
            if (sc := "source") in version_info:
5✔
884
                source = cls.parse_value(version_info, sc)
5✔
885
                key = ("" if key is None else (key + " ")) + f"--{sc}={source}"
5✔
886
            if "optional = true" in version_info:
5✔
887
                key = ("" if key is None else (key + " ")) + "--optional"
5✔
888
            if key is not None:
5✔
889
                specials[key] = specials.get(key, []) + [item]
5✔
890
            else:
891
                args.append(item)
5✔
892
        return args, specials
5✔
893

894
    @classmethod
5✔
895
    def should_with_dev(cls: type[Self]) -> bool:
5✔
896
        text = cls.load_toml_text()
5✔
897
        return cls.DevFlag.new in text or cls.DevFlag.old in text
5✔
898

899
    @staticmethod
5✔
900
    def parse_item(toml_str: str) -> list[str]:
5✔
901
        lines: list[str] = []
5✔
902
        for line in toml_str.splitlines():
5✔
903
            if (line := line.strip()).startswith("["):
5✔
904
                if lines:
5✔
905
                    break
5✔
906
            elif line:
5✔
907
                lines.append(line)
5✔
908
        return lines
5✔
909

910
    @classmethod
5✔
911
    def get_args(
5✔
912
        cls: type[Self], toml_text: str | None = None
913
    ) -> tuple[list[str], list[str], list[list[str]], str]:
914
        if toml_text is None:
5✔
915
            toml_text = cls.load_toml_text()
5✔
916
        main_title = "[tool.poetry.dependencies]"
5✔
917
        if (no_main_deps := main_title not in toml_text) and not cls.is_poetry_v2(
5✔
918
            toml_text
919
        ):
920
            raise EnvError(
5✔
921
                f"{main_title} not found! Make sure this is a poetry project."
922
            )
923
        text = toml_text.split(main_title)[-1]
5✔
924
        dev_flag = "--group dev"
5✔
925
        new_flag, old_flag = cls.DevFlag.new, cls.DevFlag.old
5✔
926
        if (dev_title := getattr(new_flag, "value", new_flag)) not in text:
5✔
927
            dev_title = getattr(old_flag, "value", old_flag)  # For poetry<=1.2
5✔
928
            dev_flag = "--dev"
5✔
929
        others: list[list[str]] = []
5✔
930
        try:
5✔
931
            main_toml, dev_toml = text.split(dev_title)
5✔
932
        except ValueError:
5✔
933
            dev_toml = ""
5✔
934
            main_toml = text
5✔
935
        mains = [] if no_main_deps else cls.parse_item(main_toml)
5✔
936
        devs = cls.parse_item(dev_toml)
5✔
937
        prod_packs, specials = cls.build_args(mains)
5✔
938
        if specials:
5✔
939
            others.extend([[k] + v for k, v in specials.items()])
5✔
940
        dev_packs, specials = cls.build_args(devs)
5✔
941
        if specials:
5✔
942
            others.extend([[k] + v + [dev_flag] for k, v in specials.items()])
5✔
943
        return prod_packs, dev_packs, others, dev_flag
5✔
944

945
    @classmethod
5✔
946
    def gen_cmd(cls: type[Self]) -> str:
5✔
947
        main_args, dev_args, others, dev_flags = cls.get_args()
5✔
948
        return cls.to_cmd(main_args, dev_args, others, dev_flags)
5✔
949

950
    @staticmethod
5✔
951
    def to_cmd(
5✔
952
        main_args: list[str],
953
        dev_args: list[str],
954
        others: list[list[str]],
955
        dev_flags: str,
956
    ) -> str:
957
        command = "poetry add "
5✔
958
        _upgrade = ""
5✔
959
        if main_args:
5✔
960
            _upgrade = command + " ".join(main_args)
5✔
961
        if dev_args:
5✔
962
            if _upgrade:
5✔
963
                _upgrade += " && "
5✔
964
            _upgrade += command + dev_flags + " " + " ".join(dev_args)
5✔
965
        for single in others:
5✔
966
            _upgrade += f" && poetry add {' '.join(single)}"
5✔
967
        return _upgrade
5✔
968

969
    def gen(self) -> str:
5✔
970
        if self._tool == "uv":
5✔
971
            up = "uv lock --upgrade --verbose"
5✔
972
            deps = "uv sync --inexact --frozen --all-groups --all-extras"
5✔
973
            return f"{up} && {deps}"
5✔
974
        elif self._tool == "pdm":
5✔
975
            return "pdm update --verbose && pdm install -G :all --frozen"
5✔
976
        return self.gen_cmd() + " && poetry lock && poetry update"
5✔
977

978

979
@cli.command()
5✔
980
def upgrade(
5✔
981
    tool: str = ToolOption,
982
    dry: bool = DryOption,
983
) -> None:
984
    """Upgrade dependencies in pyproject.toml to latest versions"""
985
    if not (tool := _ensure_str(tool)) or tool == ToolOption.default:
5✔
986
        tool = Project.get_manage_tool() or "uv"
5✔
987
    if tool in get_args(ToolName):
5✔
988
        UpgradeDependencies(dry=dry, tool=cast(ToolName, tool)).run()
5✔
989
    else:
990
        secho(f"Unknown tool {tool!r}", fg=typer.colors.YELLOW)
5✔
991
        raise typer.Exit(1)
5✔
992

993

994
class GitTag(DryRun):
5✔
995
    def __init__(self, message: str, dry: bool, no_sync: bool = False) -> None:
5✔
996
        self.message = message
5✔
997
        self._no_sync = no_sync
5✔
998
        super().__init__(dry=dry)
5✔
999

1000
    @staticmethod
5✔
1001
    def has_v_prefix() -> bool:
5✔
1002
        return "v" in capture_cmd_output("git tag")
5✔
1003

1004
    def should_push(self) -> bool:
5✔
1005
        return "git push" in self.git_status
5✔
1006

1007
    def gen(self) -> str:
5✔
1008
        should_sync, _version = get_current_version(verbose=False, check_version=True)
5✔
1009
        if self.has_v_prefix():
5✔
1010
            # Add `v` at prefix to compare with bumpversion tool
1011
            _version = "v" + _version
5✔
1012
        cmd = f"git tag -a {_version} -m {self.message!r} && git push --tags"
5✔
1013
        if self.should_push():
5✔
1014
            cmd += " && git push"
5✔
1015
        if should_sync and not self._no_sync and (sync := Project.get_sync_command()):
5✔
1016
            cmd = f"{sync} && " + cmd
×
1017
        return cmd
5✔
1018

1019
    @cached_property
5✔
1020
    def git_status(self) -> str:
5✔
1021
        return capture_cmd_output("git status")
5✔
1022

1023
    def mark_tag(self) -> bool:
5✔
1024
        if not re.search(r"working (tree|directory) clean", self.git_status) and (
5✔
1025
            "无文件要提交,干净的工作区" not in self.git_status
1026
        ):
1027
            run_and_echo("git status")
5✔
1028
            echo("ERROR: Please run git commit to make sure working tree is clean!")
5✔
1029
            return False
5✔
1030
        return bool(super().run())
5✔
1031

1032
    def run(self) -> None:
5✔
1033
        if self.mark_tag() and not self.dry:
5✔
1034
            echo("You may want to publish package:\n poetry publish --build")
5✔
1035

1036

1037
@cli.command()
5✔
1038
def tag(
5✔
1039
    message: str = Option("", "-m", "--message"),
1040
    no_sync: bool = Option(
1041
        False, "--no-sync", help="Do not run sync command to update version"
1042
    ),
1043
    dry: bool = DryOption,
1044
) -> None:
1045
    """Run shell command: git tag -a <current-version-in-pyproject.toml> -m {message}"""
1046
    GitTag(message, dry=dry, no_sync=_ensure_bool(no_sync)).run()
5✔
1047

1048

1049
class LintCode(DryRun):
5✔
1050
    def __init__(
5✔
1051
        self,
1052
        args: list[str] | str | None,
1053
        check_only: bool = False,
1054
        _exit: bool = False,
1055
        dry: bool = False,
1056
        bandit: bool = False,
1057
        skip_mypy: bool = False,
1058
        dmypy: bool = False,
1059
        tool: str = ToolOption.default,
1060
        prefix: bool = False,
1061
        up: bool = False,
1062
        sim: bool = True,
1063
    ) -> None:
1064
        self.args = args
5✔
1065
        self.check_only = check_only
5✔
1066
        self._bandit = bandit
5✔
1067
        self._skip_mypy = skip_mypy
5✔
1068
        self._use_dmypy = dmypy
5✔
1069
        self._tool = tool
5✔
1070
        self._prefix = prefix
5✔
1071
        self._up = up
5✔
1072
        self._sim = sim
5✔
1073
        super().__init__(_exit, dry)
5✔
1074

1075
    @staticmethod
5✔
1076
    def check_lint_tool_installed() -> bool:
5✔
1077
        try:
5✔
1078
            return check_call("ruff --version")
5✔
1079
        except FileNotFoundError:
×
1080
            # Windows may raise FileNotFoundError when ruff not installed
1081
            return False
×
1082

1083
    @staticmethod
5✔
1084
    def missing_mypy_exec() -> bool:
5✔
1085
        return shutil.which("mypy") is None
5✔
1086

1087
    @staticmethod
5✔
1088
    def prefer_dmypy(paths: str, tools: list[str], use_dmypy: bool = False) -> bool:
5✔
1089
        return (
5✔
1090
            paths == "."
1091
            and any(t.startswith("mypy") for t in tools)
1092
            and (use_dmypy or load_bool("FASTDEVCLI_DMYPY"))
1093
        )
1094

1095
    @staticmethod
5✔
1096
    def get_package_name() -> str:
5✔
1097
        root = Project.get_work_dir(allow_cwd=True)
5✔
1098
        module_name = root.name.replace("-", "_").replace(" ", "_")
5✔
1099
        package_maybe = (module_name, "src")
5✔
1100
        for name in package_maybe:
5✔
1101
            if root.joinpath(name).is_dir():
5✔
1102
                return name
5✔
1103
        return "."
5✔
1104

1105
    @classmethod
5✔
1106
    def to_cmd(
5✔
1107
        cls: type[Self],
1108
        paths: str = ".",
1109
        check_only: bool = False,
1110
        bandit: bool = False,
1111
        skip_mypy: bool = False,
1112
        use_dmypy: bool = False,
1113
        tool: str = ToolOption.default,
1114
        with_prefix: bool = False,
1115
        ruff_check_up: bool = False,
1116
        ruff_check_sim: bool = True,
1117
    ) -> str:
1118
        if paths != "." and all(i.endswith(".html") for i in paths.split()):
5✔
1119
            return f"prettier -w {paths}"
5✔
1120
        cmd = ""
5✔
1121
        tools = ["ruff format", "ruff check --extend-select=I,B,SIM --fix", "mypy"]
5✔
1122
        if check_only:
5✔
1123
            tools[0] += " --check"
5✔
1124
        if check_only or load_bool("NO_FIX"):
5✔
1125
            tools[1] = tools[1].replace(" --fix", "")
5✔
1126
        if ruff_check_up or load_bool("FASTDEVCLI_UP"):
5✔
1127
            tools[1] = tools[1].replace(",SIM", ",SIM,UP")
×
1128
        if not ruff_check_sim or load_bool("FASTDEVCLI_NO_SIM"):
5✔
1129
            tools[1] = tools[1].replace(",SIM", "")
×
1130
        if skip_mypy or load_bool("SKIP_MYPY") or load_bool("FASTDEVCLI_NO_MYPY"):
5✔
1131
            # Sometimes mypy is too slow
1132
            tools = tools[:-1]
5✔
1133
        elif load_bool("IGNORE_MISSING_IMPORTS"):
5✔
1134
            tools[-1] += " --ignore-missing-imports"
5✔
1135
        lint_them = " && ".join(
5✔
1136
            "{0}{" + str(i) + "} {1}" for i in range(2, len(tools) + 2)
1137
        )
1138
        if ruff_exists := cls.check_lint_tool_installed():
5✔
1139
            # `ruff <command>` get the same result with `pdm run ruff <command>`
1140
            # While `mypy .`(installed global and env not activated),
1141
            #   does not the same as `pdm run mypy .`
1142
            lint_them = " && ".join(
5✔
1143
                ("" if tool.startswith("ruff") else "{0}")
1144
                + (
1145
                    "{%d} {1}" % i  # noqa: UP031
1146
                )
1147
                for i, tool in enumerate(tools, 2)
1148
            )
1149
        prefix = ""
5✔
1150
        should_run_by_tool = with_prefix
5✔
1151
        if not should_run_by_tool:
5✔
1152
            if is_venv() and Path(sys.argv[0]).parent != Path.home().joinpath(
5✔
1153
                ".local/bin"
1154
            ):  # Virtual environment activated and fast-dev-cli is installed in it
1155
                if not ruff_exists:
5✔
1156
                    should_run_by_tool = True
5✔
1157
                    command = "pipx install ruff"
5✔
1158
                    if shutil.which("pipx") is None:
5✔
1159
                        ensure_pipx = "pip install --user pipx\n  pipx ensurepath\n  "
×
1160
                        command = ensure_pipx + command
×
1161
                    yellow_warn(
5✔
1162
                        "You may need to run the following command"
1163
                        f" to install ruff:\n\n  {command}\n"
1164
                    )
1165
                elif "mypy" in str(tools) and cls.missing_mypy_exec():
5✔
1166
                    should_run_by_tool = True
5✔
1167
                    if check_call('python -c "import fast_dev_cli"'):
5✔
1168
                        command = 'python -m pip install -U "fast-dev-cli"'
5✔
1169
                        yellow_warn(
5✔
1170
                            "You may need to run the following command"
1171
                            f" to install lint tools:\n\n  {command}\n"
1172
                        )
1173
            elif tool == ToolOption.default:
×
1174
                root = Project.get_work_dir(allow_cwd=True)
×
1175
                if py := shutil.which("python"):
×
1176
                    try:
×
1177
                        Path(py).relative_to(root)
×
1178
                    except ValueError:
×
1179
                        # Virtual environment not activated
1180
                        should_run_by_tool = True
×
1181
            else:
1182
                should_run_by_tool = True
×
1183
        if should_run_by_tool and tool:
5✔
1184
            if tool == ToolOption.default:
5✔
1185
                tool = Project.get_manage_tool() or ""
5✔
1186
            if tool:
5✔
1187
                prefix = tool + " run "
5✔
1188
                if tool == "uv":
5✔
1189
                    if is_windows():
×
1190
                        prefix += "--no-sync "
×
1191
                    elif Path(bin_dir := ".venv/bin/").exists():
×
1192
                        prefix = bin_dir
×
1193
        if cls.prefer_dmypy(paths, tools, use_dmypy=use_dmypy):
5✔
1194
            tools[-1] = "dmypy run"
5✔
1195
        cmd += lint_them.format(prefix, paths, *tools)
5✔
1196
        if bandit or load_bool("FASTDEVCLI_BANDIT"):
5✔
1197
            command = prefix + "bandit"
5✔
1198
            if Path("pyproject.toml").exists():
5✔
1199
                toml_text = Project.load_toml_text()
5✔
1200
                if "[tool.bandit" in toml_text:
5✔
1201
                    command += " -c pyproject.toml"
5✔
1202
            if paths == "." and " -c " not in command:
5✔
1203
                paths = cls.get_package_name()
5✔
1204
            command += f" -r {paths}"
5✔
1205
            cmd += " && " + command
5✔
1206
        return cmd
5✔
1207

1208
    def gen(self) -> str:
5✔
1209
        paths = "."
5✔
1210
        if args := self.args:
5✔
1211
            ps = args.split() if isinstance(args, str) else [str(i) for i in args]
5✔
1212
            if len(ps) == 1:
5✔
1213
                paths = ps[0]
5✔
1214
                if (
5✔
1215
                    paths != "."
1216
                    # `Path("a.").suffix` got "." in py3.14 and got "" with py<3.14
1217
                    and (p := Path(paths)).suffix in ("", ".")
1218
                    and not p.exists()
1219
                ):
1220
                    # e.g.:
1221
                    # stem -> stem.py
1222
                    # me. -> me.py
1223
                    if paths.endswith("."):
×
1224
                        p = p.with_name(paths[:-1])
×
1225
                    for suffix in (".py", ".html"):
×
1226
                        p = p.with_suffix(suffix)
×
1227
                        if p.exists():
×
1228
                            paths = p.name
×
1229
                            break
×
1230
            else:
1231
                paths = " ".join(ps)
×
1232
        return self.to_cmd(
5✔
1233
            paths,
1234
            self.check_only,
1235
            self._bandit,
1236
            self._skip_mypy,
1237
            self._use_dmypy,
1238
            tool=self._tool,
1239
            with_prefix=self._prefix,
1240
            ruff_check_up=self._up,
1241
            ruff_check_sim=self._sim,
1242
        )
1243

1244

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

1248

1249
def lint(
5✔
1250
    files: list[str] | str | None = None,
1251
    dry: bool = False,
1252
    bandit: bool = False,
1253
    skip_mypy: bool = False,
1254
    dmypy: bool = False,
1255
    tool: str = ToolOption.default,
1256
    prefix: bool = False,
1257
    up: bool = False,
1258
    sim: bool = True,
1259
) -> None:
1260
    if files is None:
5✔
1261
        files = parse_files(sys.argv[1:])
5✔
1262
    if files and files[0] == "lint":
5✔
1263
        files = files[1:]
5✔
1264
    LintCode(
5✔
1265
        files,
1266
        dry=dry,
1267
        skip_mypy=skip_mypy,
1268
        bandit=bandit,
1269
        dmypy=dmypy,
1270
        tool=tool,
1271
        prefix=prefix,
1272
        up=up,
1273
        sim=sim,
1274
    ).run()
1275

1276

1277
def check(
5✔
1278
    files: list[str] | str | None = None,
1279
    dry: bool = False,
1280
    bandit: bool = False,
1281
    skip_mypy: bool = False,
1282
    dmypy: bool = False,
1283
    tool: str = ToolOption.default,
1284
    up: bool = False,
1285
    sim: bool = True,
1286
) -> None:
1287
    LintCode(
5✔
1288
        files,
1289
        check_only=True,
1290
        _exit=True,
1291
        dry=dry,
1292
        bandit=bandit,
1293
        skip_mypy=skip_mypy,
1294
        dmypy=dmypy,
1295
        tool=tool,
1296
        up=up,
1297
        sim=sim,
1298
    ).run()
1299

1300

1301
@cli.command(name="lint")
5✔
1302
def make_style(
5✔
1303
    files: list[str] | None = typer.Argument(default=None),  # noqa:B008
1304
    check_only: bool = Option(False, "--check-only", "-c"),
1305
    bandit: bool = Option(False, "--bandit", help="Run `bandit -r <package_dir>`"),
1306
    prefix: bool = Option(
1307
        False,
1308
        "--prefix",
1309
        help="Run lint command with tool prefix, e.g.: pdm run ruff ...",
1310
    ),
1311
    skip_mypy: bool = Option(False, "--skip-mypy"),
1312
    use_dmypy: bool = Option(
1313
        False, "--dmypy", help="Use `dmypy run` instead of `mypy`"
1314
    ),
1315
    tool: str = ToolOption,
1316
    dry: bool = DryOption,
1317
    up: bool = Option(False, help="Whether ruff check with --extend-select=UP"),
1318
    sim: bool = Option(True, help="Whether ruff check with --extend-select=SIM"),
1319
) -> None:
1320
    """Run: ruff check/format to reformat code and then mypy to check"""
1321
    if getattr(files, "default", files) is None:
5✔
1322
        files = ["."]
5✔
1323
    elif isinstance(files, str):
5✔
1324
        files = [files]
5✔
1325
    skip = _ensure_bool(skip_mypy)
5✔
1326
    dmypy = _ensure_bool(use_dmypy)
5✔
1327
    bandit = _ensure_bool(bandit)
5✔
1328
    prefix = _ensure_bool(prefix)
5✔
1329
    tool = _ensure_str(tool)
5✔
1330
    up = _ensure_bool(up)
5✔
1331
    sim = _ensure_bool(sim)
5✔
1332
    kwargs = {"dry": dry, "skip_mypy": skip, "dmypy": dmypy, "bandit": bandit}
5✔
1333
    if _ensure_bool(check_only):
5✔
1334
        check(files, tool=tool, up=up, sim=sim, **kwargs)
5✔
1335
    else:
1336
        lint(files, prefix=prefix, tool=tool, up=up, sim=sim, **kwargs)
5✔
1337

1338

1339
@cli.command(name="check")
5✔
1340
def only_check(
5✔
1341
    bandit: bool = Option(False, "--bandit", help="Run `bandit -r <package_dir>`"),
1342
    skip_mypy: bool = Option(False, "--skip-mypy"),
1343
    dry: bool = DryOption,
1344
    up: bool = Option(False, help="Whether ruff check with --extend-select=UP"),
1345
    sim: bool = Option(True, help="Whether ruff check with --extend-select=SIM"),
1346
) -> None:
1347
    """Check code style without reformat"""
1348
    bandit = _ensure_bool(bandit)
5✔
1349
    up = _ensure_bool(up)
5✔
1350
    sim = _ensure_bool(sim)
5✔
1351
    check(dry=dry, bandit=bandit, skip_mypy=_ensure_bool(skip_mypy), up=up, sim=sim)
5✔
1352

1353

1354
class Sync(DryRun):
5✔
1355
    def __init__(
5✔
1356
        self, filename: str, extras: str, save: bool, dry: bool = False
1357
    ) -> None:
1358
        self.filename = filename
5✔
1359
        self.extras = extras
5✔
1360
        self._save = save
5✔
1361
        super().__init__(dry=dry)
5✔
1362

1363
    def gen(self) -> str:
5✔
1364
        extras, save = self.extras, self._save
5✔
1365
        should_remove = not Path.cwd().joinpath(self.filename).exists()
5✔
1366
        if not (tool := Project.get_manage_tool()):
5✔
1367
            if should_remove or not is_venv():
5✔
1368
                raise EnvError("There project is not managed by uv/pdm/poetry!")
5✔
1369
            return f"python -m pip install -r {self.filename}"
5✔
1370
        prefix = "" if is_venv() else f"{tool} run "
5✔
1371
        ensure_pip = " {1}python -m ensurepip && {1}python -m pip install -U pip &&"
5✔
1372
        export_cmd = "uv export --no-hashes --all-extras --frozen"
5✔
1373
        if tool in ("poetry", "pdm"):
5✔
1374
            export_cmd = f"{tool} export --without-hashes --with=dev"
5✔
1375
            if tool == "poetry":
5✔
1376
                ensure_pip = ""
5✔
1377
                if not UpgradeDependencies.should_with_dev():
5✔
1378
                    export_cmd = export_cmd.replace(" --with=dev", "")
5✔
1379
                if extras and isinstance(extras, str | list):
5✔
1380
                    export_cmd += f" --{extras=}".replace("'", '"')
5✔
1381
            elif check_call(prefix + "python -m pip --version"):
5✔
1382
                ensure_pip = ""
5✔
1383
        elif check_call(prefix + "python -m pip --version"):
5✔
1384
            ensure_pip = ""
5✔
1385
        install_cmd = (
5✔
1386
            f"{{2}} -o {{0}} &&{ensure_pip} {{1}}python -m pip install -r {{0}}"
1387
        )
1388
        if should_remove and not save:
5✔
1389
            install_cmd += " && rm -f {0}"
5✔
1390
        return install_cmd.format(self.filename, prefix, export_cmd)
5✔
1391

1392

1393
@cli.command()
5✔
1394
def sync(
5✔
1395
    filename: str = "dev_requirements.txt",
1396
    extras: str = Option("", "--extras", "-E"),
1397
    save: bool = Option(
1398
        False, "--save", "-s", help="Whether save the requirement file"
1399
    ),
1400
    dry: bool = DryOption,
1401
) -> None:
1402
    """Export dependencies by poetry to a txt file then install by pip."""
1403
    Sync(filename, extras, save, dry=dry).run()
5✔
1404

1405

1406
def _should_run_test_script(path: Path = Path("scripts")) -> Path | None:
5✔
1407
    for name in ("test.sh", "test.py"):
5✔
1408
        if (file := path / name).exists():
5✔
1409
            return file
5✔
1410
    return None
5✔
1411

1412

1413
def test(dry: bool, ignore_script: bool = False) -> None:
5✔
1414
    cwd = Path.cwd()
5✔
1415
    root = Project.get_work_dir(cwd=cwd, allow_cwd=True)
5✔
1416
    script_dir = root / "scripts"
5✔
1417
    if not _ensure_bool(ignore_script) and (
5✔
1418
        test_script := _should_run_test_script(script_dir)
1419
    ):
1420
        cmd = test_script.relative_to(root).as_posix()
5✔
1421
        if test_script.suffix == ".py":
5✔
1422
            cmd = "python " + cmd
5✔
1423
        if cwd != root:
5✔
1424
            cmd = f"cd {root} && " + cmd
5✔
1425
    else:
1426
        cmd = 'coverage run -m pytest -s && coverage report --omit="tests/*" -m'
5✔
1427
        if not is_venv() or not check_call("coverage --version"):
5✔
1428
            sep = " && "
5✔
1429
            prefix = f"{tool} run " if (tool := Project.get_manage_tool()) else ""
5✔
1430
            cmd = sep.join(prefix + i for i in cmd.split(sep))
5✔
1431
    exit_if_run_failed(cmd, dry=dry)
5✔
1432

1433

1434
@cli.command(name="test")
5✔
1435
def coverage_test(
5✔
1436
    dry: bool = DryOption,
1437
    ignore_script: bool = Option(False, "--ignore-script", "-i"),
1438
) -> None:
1439
    """Run unittest by pytest and report coverage"""
1440
    return test(dry, ignore_script)
5✔
1441

1442

1443
class Publish:
5✔
1444
    class CommandEnum(StrEnum):
5✔
1445
        poetry = "poetry publish --build"
5✔
1446
        pdm = "pdm publish"
5✔
1447
        uv = "uv build && uv publish"
5✔
1448
        twine = "python -m build && twine upload"
5✔
1449

1450
    @classmethod
5✔
1451
    def gen(cls) -> str:
5✔
1452
        if tool := Project.get_manage_tool():
5✔
1453
            return cls.CommandEnum[tool]
5✔
1454
        return cls.CommandEnum.twine
5✔
1455

1456

1457
@cli.command()
5✔
1458
def upload(
5✔
1459
    dry: bool = DryOption,
1460
) -> None:
1461
    """Shortcut for package publish"""
1462
    cmd = Publish.gen()
5✔
1463
    exit_if_run_failed(cmd, dry=dry)
5✔
1464

1465

1466
def dev(
5✔
1467
    port: int | None | OptionInfo,
1468
    host: str | None | OptionInfo,
1469
    file: str | None | ArgumentInfo = None,
1470
    dry: bool = False,
1471
) -> None:
1472
    cmd = "fastapi dev"
5✔
1473
    no_port_yet = True
5✔
1474
    if file is not None:
5✔
1475
        try:
5✔
1476
            port = int(str(file))
5✔
1477
        except ValueError:
5✔
1478
            cmd += f" {file}"
5✔
1479
        else:
1480
            if port != 8000:
5✔
1481
                cmd += f" --port={port}"
5✔
1482
                no_port_yet = False
5✔
1483
    if no_port_yet and (port := getattr(port, "default", port)) and str(port) != "8000":
5✔
1484
        cmd += f" --port={port}"
5✔
1485
    if (host := getattr(host, "default", host)) and host not in (
5✔
1486
        "localhost",
1487
        "127.0.0.1",
1488
    ):
1489
        cmd += f" --host={host}"
5✔
1490
    exit_if_run_failed(cmd, dry=dry)
5✔
1491

1492

1493
@cli.command(name="dev")
5✔
1494
def runserver(
5✔
1495
    file_or_port: str | None = typer.Argument(default=None),
1496
    port: int | None = Option(None, "-p", "--port"),
1497
    host: str | None = Option(None, "-h", "--host"),
1498
    dry: bool = DryOption,
1499
) -> None:
1500
    """Start a fastapi server(only for fastapi>=0.111.0)"""
1501
    if getattr(file_or_port, "default", file_or_port):
5✔
1502
        dev(port, host, file=file_or_port, dry=dry)
5✔
1503
    else:
1504
        dev(port, host, dry=dry)
5✔
1505

1506

1507
@cli.command(name="exec")
5✔
1508
def run_by_subprocess(cmd: str, dry: bool = DryOption) -> None:
5✔
1509
    """Run cmd by subprocess, auto set shell=True when cmd contains '|>'"""
1510
    try:
5✔
1511
        rc = run_and_echo(cmd, verbose=True, dry=_ensure_bool(dry))
5✔
1512
    except FileNotFoundError as e:
5✔
1513
        command = cmd.split()[0]
5✔
1514
        if e.filename == command or (
5✔
1515
            e.filename is None and "系统找不到指定的文件" in str(e)
1516
        ):
1517
            echo(f"Command not found: {command}")
5✔
1518
            raise Exit(1) from None
5✔
1519
        raise e
×
1520
    else:
1521
        if rc:
5✔
1522
            raise Exit(rc)
5✔
1523

1524

1525
class MakeDeps(DryRun):
5✔
1526
    def __init__(
5✔
1527
        self,
1528
        tool: str,
1529
        prod: bool = False,
1530
        dry: bool = False,
1531
        active: bool = True,
1532
        inexact: bool = True,
1533
    ) -> None:
1534
        self._tool = tool
5✔
1535
        self._prod = prod
5✔
1536
        self._active = active
5✔
1537
        self._inexact = inexact
5✔
1538
        super().__init__(dry=dry)
5✔
1539

1540
    def should_ensure_pip(self) -> bool:
5✔
1541
        return True
5✔
1542

1543
    def should_upgrade_pip(self) -> bool:
5✔
1544
        return True
×
1545

1546
    def get_groups(self) -> list[str]:
5✔
1547
        if self._prod:
5✔
1548
            return []
5✔
1549
        return ["dev"]
5✔
1550

1551
    def gen(self) -> str:
5✔
1552
        if self._tool == "pdm":
5✔
1553
            return "pdm install --frozen " + ("--prod" if self._prod else "-G :all")
5✔
1554
        elif self._tool == "uv":
5✔
1555
            uv_sync = "uv sync" + " --inexact" * self._inexact
5✔
1556
            if self._active:
5✔
1557
                uv_sync += " --active"
5✔
1558
            return uv_sync + ("" if self._prod else " --all-extras --all-groups")
5✔
1559
        elif self._tool == "poetry":
5✔
1560
            return "poetry install " + (
5✔
1561
                "--only=main" if self._prod else "--all-extras --all-groups"
1562
            )
1563
        else:
1564
            cmd = "python -m pip install -e ."
5✔
1565
            if gs := self.get_groups():
5✔
1566
                cmd += " " + " ".join(f"--group {g}" for g in gs)
5✔
1567
            upgrade = "python -m pip install --upgrade pip"
5✔
1568
            if self.should_ensure_pip():
5✔
1569
                cmd = f"python -m ensurepip && {upgrade} && {cmd}"
5✔
1570
            elif self.should_upgrade_pip():
×
1571
                cmd = "{upgrade} && {cmd}"
×
1572
            return cmd
5✔
1573

1574

1575
@cli.command(name="deps")
5✔
1576
def make_deps(
5✔
1577
    prod: bool = Option(
1578
        False,
1579
        "--prod",
1580
        help="Only instead production dependencies.",
1581
    ),
1582
    tool: str = ToolOption,
1583
    use_uv: bool = Option(False, "--uv", help="Use `uv` to install deps"),
1584
    use_pdm: bool = Option(False, "--pdm", help="Use `pdm` to install deps"),
1585
    use_pip: bool = Option(False, "--pip", help="Use `pip` to install deps"),
1586
    use_poetry: bool = Option(False, "--poetry", help="Use `poetry` to install deps"),
1587
    active: bool = Option(
1588
        True, help="Add `--active` to uv sync command(Only work for uv project)"
1589
    ),
1590
    inexact: bool = Option(
1591
        True, help="Add `--inexact` to uv sync command(Only work for uv project)"
1592
    ),
1593
    dry: bool = DryOption,
1594
) -> None:
1595
    """Run: ruff check/format to reformat code and then mypy to check"""
1596
    if use_uv + use_pdm + use_pip + use_poetry > 1:
×
1597
        raise UsageError("`--uv/--pdm/--pip/--poetry` can only choose one!")
×
1598
    if use_uv:
×
1599
        tool = "uv"
×
1600
    elif use_pdm:
×
1601
        tool = "pdm"
×
1602
    elif use_pip:
×
1603
        tool = "pip"
×
1604
    elif use_poetry:
×
1605
        tool = "poetry"
×
1606
    elif tool == ToolOption.default:
×
1607
        tool = Project.get_manage_tool(cache=True) or "pip"
×
1608
    MakeDeps(tool, prod, active=active, inexact=inexact, dry=dry).run()
×
1609

1610

1611
class UvPypi(DryRun):
5✔
1612
    PYPI = "https://pypi.org/simple"
5✔
1613
    HOST = "https://files.pythonhosted.org"
5✔
1614

1615
    def __init__(self, lock_file: Path, dry: bool, verbose: bool, quiet: bool) -> None:
5✔
1616
        super().__init__(dry=dry)
5✔
1617
        self.lock_file = lock_file
5✔
1618
        self._verbose = _ensure_bool(verbose)
5✔
1619
        self._quiet = _ensure_bool(quiet)
5✔
1620

1621
    def run(self) -> None:
5✔
1622
        try:
5✔
1623
            rc = self.update_lock(self.lock_file, self._verbose, self._quiet)
5✔
1624
        except ValueError as e:
×
1625
            secho(str(e), fg=typer.colors.RED)
×
1626
            raise Exit(1) from e
×
1627
        else:
1628
            if rc != 0:
5✔
1629
                raise Exit(rc)
5✔
1630

1631
    @classmethod
5✔
1632
    def update_lock(cls, p: Path, verbose: bool, quiet: bool) -> int:
5✔
1633
        text = p.read_text("utf-8")
5✔
1634
        registry_pattern = r'(registry = ")(.*?)"'
5✔
1635
        replace_registry = functools.partial(
5✔
1636
            re.sub, registry_pattern, rf'\1{cls.PYPI}"'
1637
        )
1638
        registry_urls = {i[1] for i in re.findall(registry_pattern, text)}
5✔
1639
        download_pattern = r'(url = ")(https?://.*?)(/packages/.*?\.)(gz|whl)"'
5✔
1640
        replace_host = functools.partial(
5✔
1641
            re.sub, download_pattern, rf'\1{cls.HOST}\3\4"'
1642
        )
1643
        download_hosts = {i[1] for i in re.findall(download_pattern, text)}
5✔
1644
        if not registry_urls:
5✔
1645
            raise ValueError(f"Failed to find pattern {registry_pattern!r} in {p}")
×
1646
        if len(registry_urls) == 1:
5✔
1647
            current_registry = registry_urls.pop()
5✔
1648
            if current_registry == cls.PYPI:
5✔
1649
                if download_hosts == {cls.HOST}:
5✔
1650
                    if verbose:
5✔
1651
                        echo(f"Registry of {p} is {cls.PYPI}, no need to change.")
×
1652
                    return 0
5✔
1653
            else:
1654
                text = replace_registry(text)
5✔
1655
                if verbose:
5✔
1656
                    echo(f"{current_registry} --> {cls.PYPI}")
×
1657
        else:
1658
            # TODO: ask each one to confirm replace
1659
            text = replace_registry(text)
×
1660
            if verbose:
×
1661
                for current_registry in sorted(registry_urls):
×
1662
                    echo(f"{current_registry} --> {cls.PYPI}")
×
1663
        if len(download_hosts) == 1:
5✔
1664
            current_host = download_hosts.pop()
5✔
1665
            if current_host != cls.HOST:
5✔
1666
                text = replace_host(text)
5✔
1667
                if verbose:
5✔
1668
                    print(current_host, "-->", cls.HOST)
×
1669
        elif download_hosts:
×
1670
            # TODO: ask each one to confirm replace
1671
            text = replace_host(text)
×
1672
            if verbose:
×
1673
                for current_host in sorted(download_hosts):
×
1674
                    echo(f"{current_host} --> {cls.HOST}")
×
1675
        size = p.write_text(text, encoding="utf-8")
5✔
1676
        if verbose:
5✔
1677
            echo(f"Updated {p} with {size} bytes.")
×
1678
        if quiet:
5✔
1679
            return 0
5✔
1680
        return 1
5✔
1681

1682

1683
@cli.command()
5✔
1684
def pypi(
5✔
1685
    file: str | None = typer.Argument(default=None),
1686
    dry: bool = DryOption,
1687
    verbose: bool = False,
1688
    quiet: bool = False,
1689
) -> None:
1690
    """Change registry of uv.lock to be pypi.org"""
1691
    if not (p := Path(_ensure_str(file) or "uv.lock")).exists() and not (
5✔
1692
        (p := Project.get_work_dir() / p.name).exists()
1693
    ):
1694
        yellow_warn(f"{p.name!r} not found!")
5✔
1695
        return
5✔
1696
    UvPypi(p, dry, verbose, quiet).run()
5✔
1697

1698

1699
def version_callback(value: bool) -> None:
5✔
1700
    if value:
5✔
1701
        echo("Fast Dev Cli Version: " + typer.style(__version__, bold=True))
5✔
1702
        raise Exit()
5✔
1703

1704

1705
@cli.callback()
1706
def common(
1707
    version: bool = Option(
1708
        None,
1709
        "--version",
1710
        "-V",
1711
        callback=version_callback,
1712
        is_eager=True,
1713
        help="Show the version of this tool",
1714
    ),
1715
) -> None: ...
1716

1717

1718
def main() -> None:
5✔
1719
    cli()
5✔
1720

1721

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