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

waketzheng / fast-dev-cli / 20691318514

04 Jan 2026 10:09AM UTC coverage: 87.228% (-0.01%) from 87.238%
20691318514

push

github

waketzheng
docs: update changelog

963 of 1104 relevant lines covered (87.23%)

4.36 hits per line

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

87.22
/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
        try:
5✔
174
            return self.run() == 0
5✔
175
        except FileNotFoundError:
×
176
            return False
×
177

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

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

200

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

207

208
def check_call(cmd: str) -> bool:
5✔
209
    return Shell(cmd).check_call()
5✔
210

211

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

217

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

227

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

231

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

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

274

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

284

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

294

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

331

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

337

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

343

344
class DryRun:
5✔
345
    def __init__(self, _exit: bool = False, dry: bool = False) -> None:
5✔
346
        self.dry = _ensure_bool(dry)
5✔
347
        self._exit = _exit
5✔
348

349
    def gen(self) -> str:
5✔
350
        raise NotImplementedError
5✔
351

352
    def run(self) -> None:
5✔
353
        exit_if_run_failed(self.gen(), _exit=self._exit, dry=self.dry)
5✔
354

355

356
class BumpUp(DryRun):
5✔
357
    class PartChoices(StrEnum):
5✔
358
        patch = "patch"
5✔
359
        minor = "minor"
5✔
360
        major = "major"
5✔
361

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

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

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

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

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

460
        return TOML_FILE
5✔
461

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

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

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

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

551

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

576

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

602

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

614

615
class Project:
5✔
616
    path_depth = 5
5✔
617
    _tool: ToolName | None = None
5✔
618

619
    @staticmethod
5✔
620
    def is_poetry_v2(text: str) -> bool:
5✔
621
        return 'build-backend = "poetry' in text
5✔
622

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

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

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

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

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

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

744
    @staticmethod
5✔
745
    def python_exec_dir() -> Path:
5✔
746
        return Path(sys.executable).parent
5✔
747

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

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

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

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

804

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

812
    class DevFlag(StrEnum):
5✔
813
        new = "[tool.poetry.group.dev.dependencies]"
5✔
814
        old = "[tool.poetry.dev-dependencies]"
5✔
815

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

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

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

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

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

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

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

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

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

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

981

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

996

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

1003
    @staticmethod
5✔
1004
    def has_v_prefix() -> bool:
5✔
1005
        return "v" in capture_cmd_output("git tag")
5✔
1006

1007
    def should_push(self) -> bool:
5✔
1008
        return "git push" in self.git_status
5✔
1009

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

1022
    @cached_property
5✔
1023
    def git_status(self) -> str:
5✔
1024
        return capture_cmd_output("git status")
5✔
1025

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

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

1039

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

1051

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

1082
    @staticmethod
5✔
1083
    def check_lint_tool_installed() -> bool:
5✔
1084
        try:
5✔
1085
            return check_call("ruff --version")
5✔
1086
        except FileNotFoundError:
×
1087
            # Windows may raise FileNotFoundError when ruff not installed
1088
            return False
×
1089

1090
    @staticmethod
5✔
1091
    def missing_mypy_exec() -> bool:
5✔
1092
        return shutil.which("mypy") is None
5✔
1093

1094
    @staticmethod
5✔
1095
    def prefer_dmypy(paths: str, tools: list[str], use_dmypy: bool = False) -> bool:
5✔
1096
        return (
5✔
1097
            paths == "."
1098
            and any(t.startswith("mypy") for t in tools)
1099
            and (use_dmypy or load_bool("FASTDEVCLI_DMYPY"))
1100
        )
1101

1102
    @staticmethod
5✔
1103
    def get_package_name() -> str:
5✔
1104
        root = Project.get_work_dir(allow_cwd=True)
5✔
1105
        module_name = root.name.replace("-", "_").replace(" ", "_")
5✔
1106
        package_maybe = (module_name, "src")
5✔
1107
        for name in package_maybe:
5✔
1108
            if root.joinpath(name).is_dir():
5✔
1109
                return name
5✔
1110
        return "."
5✔
1111

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

1223
    def gen(self) -> str:
5✔
1224
        paths = "."
5✔
1225
        if args := self.args:
5✔
1226
            ps = args.split() if isinstance(args, str) else [str(i) for i in args]
5✔
1227
            if len(ps) == 1:
5✔
1228
                paths = ps[0]
5✔
1229
                if (
5✔
1230
                    paths != "."
1231
                    # `Path("a.").suffix` got "." in py3.14 and got "" with py<3.14
1232
                    and (p := Path(paths)).suffix in ("", ".")
1233
                    and not p.exists()
1234
                ):
1235
                    # e.g.:
1236
                    # stem -> stem.py
1237
                    # me. -> me.py
1238
                    if paths.endswith("."):
×
1239
                        p = p.with_name(paths[:-1])
×
1240
                    for suffix in (".py", ".html"):
×
1241
                        p = p.with_suffix(suffix)
×
1242
                        if p.exists():
×
1243
                            paths = p.name
×
1244
                            break
×
1245
            else:
1246
                paths = " ".join(ps)
×
1247
        return self.to_cmd(
5✔
1248
            paths,
1249
            self.check_only,
1250
            self._bandit,
1251
            self._skip_mypy,
1252
            self._use_dmypy,
1253
            tool=self._tool,
1254
            with_prefix=self._prefix,
1255
            ruff_check_up=self._up,
1256
            ruff_check_sim=self._sim,
1257
            mypy_strict=self._strict,
1258
            prefer_ty=self._ty,
1259
        )
1260

1261

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

1265

1266
def lint(
5✔
1267
    files: list[str] | str | None = None,
1268
    dry: bool = False,
1269
    bandit: bool = False,
1270
    skip_mypy: bool = False,
1271
    dmypy: bool = False,
1272
    tool: str = ToolOption.default,
1273
    prefix: bool = False,
1274
    up: bool = False,
1275
    sim: bool = True,
1276
    strict: bool = False,
1277
    ty: bool = False,
1278
) -> None:
1279
    if files is None:
5✔
1280
        files = parse_files(sys.argv[1:])
5✔
1281
    if files and files[0] == "lint":
5✔
1282
        files = files[1:]
5✔
1283
    LintCode(
5✔
1284
        files,
1285
        dry=dry,
1286
        skip_mypy=skip_mypy,
1287
        bandit=bandit,
1288
        dmypy=dmypy,
1289
        tool=tool,
1290
        prefix=prefix,
1291
        up=up,
1292
        sim=sim,
1293
        strict=strict,
1294
        ty=ty,
1295
    ).run()
1296

1297

1298
def check(
5✔
1299
    files: list[str] | str | None = None,
1300
    dry: bool = False,
1301
    bandit: bool = False,
1302
    skip_mypy: bool = False,
1303
    dmypy: bool = False,
1304
    tool: str = ToolOption.default,
1305
    up: bool = False,
1306
    sim: bool = True,
1307
    strict: bool = False,
1308
    ty: bool = False,
1309
) -> None:
1310
    LintCode(
5✔
1311
        files,
1312
        check_only=True,
1313
        _exit=True,
1314
        dry=dry,
1315
        bandit=bandit,
1316
        skip_mypy=skip_mypy,
1317
        dmypy=dmypy,
1318
        tool=tool,
1319
        up=up,
1320
        sim=sim,
1321
        strict=strict,
1322
        ty=ty,
1323
    ).run()
1324

1325

1326
@cli.command(name="lint")
5✔
1327
def make_style(
5✔
1328
    files: list[str] | None = typer.Argument(default=None),  # noqa:B008
1329
    check_only: bool = Option(False, "--check-only", "-c"),
1330
    bandit: bool = Option(False, "--bandit", help="Run `bandit -r <package_dir>`"),
1331
    prefix: bool = Option(
1332
        False,
1333
        "--prefix",
1334
        help="Run lint command with tool prefix, e.g.: pdm run ruff ...",
1335
    ),
1336
    skip_mypy: bool = Option(False, "--skip-mypy"),
1337
    use_dmypy: bool = Option(
1338
        False, "--dmypy", help="Use `dmypy run` instead of `mypy`"
1339
    ),
1340
    tool: str = ToolOption,
1341
    dry: bool = DryOption,
1342
    up: bool = Option(False, help="Whether ruff check with --extend-select=UP"),
1343
    sim: bool = Option(True, help="Whether ruff check with --extend-select=SIM"),
1344
    strict: bool = Option(False, help="Whether run mypy with --strict"),
1345
    ty: bool = Option(False, help="Whether use ty instead of mypy"),
1346
) -> None:
1347
    """Run: ruff check/format to reformat code and then mypy to check"""
1348
    if getattr(files, "default", files) is None:
5✔
1349
        files = ["."]
5✔
1350
    elif isinstance(files, str):
5✔
1351
        files = [files]
5✔
1352
    skip = _ensure_bool(skip_mypy)
5✔
1353
    dmypy = _ensure_bool(use_dmypy)
5✔
1354
    bandit = _ensure_bool(bandit)
5✔
1355
    prefix = _ensure_bool(prefix)
5✔
1356
    tool = _ensure_str(tool)
5✔
1357
    up = _ensure_bool(up)
5✔
1358
    sim = _ensure_bool(sim)
5✔
1359
    strict = _ensure_bool(strict)
5✔
1360
    kwargs = {"dry": dry, "skip_mypy": skip, "dmypy": dmypy, "bandit": bandit}
5✔
1361
    run = check if _ensure_bool(check_only) else functools.partial(lint, prefix=prefix)
5✔
1362
    run(files, tool=tool, up=up, sim=sim, strict=strict, ty=ty, **kwargs)
5✔
1363

1364

1365
@cli.command(name="check")
5✔
1366
def only_check(
5✔
1367
    bandit: bool = Option(False, "--bandit", help="Run `bandit -r <package_dir>`"),
1368
    skip_mypy: bool = Option(False, "--skip-mypy"),
1369
    dry: bool = DryOption,
1370
    up: bool = Option(False, help="Whether ruff check with --extend-select=UP"),
1371
    sim: bool = Option(True, help="Whether ruff check with --extend-select=SIM"),
1372
    strict: bool = Option(False, help="Whether run mypy with --strict"),
1373
    ty: bool = Option(False, help="Whether use ty instead of mypy"),
1374
) -> None:
1375
    """Check code style without reformat"""
1376
    bandit = _ensure_bool(bandit)
5✔
1377
    up = _ensure_bool(up)
5✔
1378
    sim = _ensure_bool(sim)
5✔
1379
    skip_mypy = _ensure_bool(skip_mypy)
5✔
1380
    check(dry=dry, bandit=bandit, skip_mypy=skip_mypy, up=up, sim=sim, ty=ty)
5✔
1381

1382

1383
class Sync(DryRun):
5✔
1384
    def __init__(
5✔
1385
        self, filename: str, extras: str, save: bool, dry: bool = False
1386
    ) -> None:
1387
        self.filename = filename
5✔
1388
        self.extras = extras
5✔
1389
        self._save = save
5✔
1390
        super().__init__(dry=dry)
5✔
1391

1392
    def gen(self) -> str:
5✔
1393
        extras, save = self.extras, self._save
5✔
1394
        should_remove = not Path.cwd().joinpath(self.filename).exists()
5✔
1395
        if not (tool := Project.get_manage_tool()):
5✔
1396
            if should_remove or not is_venv():
5✔
1397
                raise EnvError("There project is not managed by uv/pdm/poetry!")
5✔
1398
            return f"python -m pip install -r {self.filename}"
5✔
1399
        prefix = "" if is_venv() else f"{tool} run "
5✔
1400
        ensure_pip = " {1}python -m ensurepip && {1}python -m pip install -U pip &&"
5✔
1401
        export_cmd = "uv export --no-hashes --all-extras --frozen"
5✔
1402
        if tool in ("poetry", "pdm"):
5✔
1403
            export_cmd = f"{tool} export --without-hashes --with=dev"
5✔
1404
            if tool == "poetry":
5✔
1405
                ensure_pip = ""
5✔
1406
                if not UpgradeDependencies.should_with_dev():
5✔
1407
                    export_cmd = export_cmd.replace(" --with=dev", "")
5✔
1408
                if extras and isinstance(extras, str | list):
5✔
1409
                    export_cmd += f" --{extras=}".replace("'", '"')
5✔
1410
            elif check_call(prefix + "python -m pip --version"):
5✔
1411
                ensure_pip = ""
5✔
1412
        elif check_call(prefix + "python -m pip --version"):
5✔
1413
            ensure_pip = ""
5✔
1414
        install_cmd = (
5✔
1415
            f"{{2}} -o {{0}} &&{ensure_pip} {{1}}python -m pip install -r {{0}}"
1416
        )
1417
        if should_remove and not save:
5✔
1418
            install_cmd += " && rm -f {0}"
5✔
1419
        return install_cmd.format(self.filename, prefix, export_cmd)
5✔
1420

1421

1422
@cli.command()
5✔
1423
def sync(
5✔
1424
    filename: str = "dev_requirements.txt",
1425
    extras: str = Option("", "--extras", "-E"),
1426
    save: bool = Option(
1427
        False, "--save", "-s", help="Whether save the requirement file"
1428
    ),
1429
    dry: bool = DryOption,
1430
) -> None:
1431
    """Export dependencies by poetry to a txt file then install by pip."""
1432
    Sync(filename, extras, save, dry=dry).run()
5✔
1433

1434

1435
def _should_run_test_script(path: Path = Path("scripts")) -> Path | None:
5✔
1436
    for name in ("test.sh", "test.py"):
5✔
1437
        if (file := path / name).exists():
5✔
1438
            return file
5✔
1439
    return None
5✔
1440

1441

1442
def test(dry: bool, ignore_script: bool = False) -> None:
5✔
1443
    cwd = Path.cwd()
5✔
1444
    root = Project.get_work_dir(cwd=cwd, allow_cwd=True)
5✔
1445
    script_dir = root / "scripts"
5✔
1446
    if not _ensure_bool(ignore_script) and (
5✔
1447
        test_script := _should_run_test_script(script_dir)
1448
    ):
1449
        cmd = test_script.relative_to(root).as_posix()
5✔
1450
        if test_script.suffix == ".py":
5✔
1451
            cmd = "python " + cmd
5✔
1452
        if cwd != root:
5✔
1453
            cmd = f"cd {root} && " + cmd
5✔
1454
    else:
1455
        cmd = 'coverage run -m pytest -s && coverage report --omit="tests/*" -m'
5✔
1456
        if not is_venv() or not check_call("coverage --version"):
5✔
1457
            sep = " && "
5✔
1458
            prefix = f"{tool} run " if (tool := Project.get_manage_tool()) else ""
5✔
1459
            cmd = sep.join(prefix + i for i in cmd.split(sep))
5✔
1460
    exit_if_run_failed(cmd, dry=dry)
5✔
1461

1462

1463
@cli.command(name="test")
5✔
1464
def coverage_test(
5✔
1465
    dry: bool = DryOption,
1466
    ignore_script: bool = Option(False, "--ignore-script", "-i"),
1467
) -> None:
1468
    """Run unittest by pytest and report coverage"""
1469
    return test(dry, ignore_script)
5✔
1470

1471

1472
class Publish:
5✔
1473
    class CommandEnum(StrEnum):
5✔
1474
        poetry = "poetry publish --build"
5✔
1475
        pdm = "pdm publish"
5✔
1476
        uv = "uv build && uv publish"
5✔
1477
        twine = "python -m build && twine upload"
5✔
1478

1479
    @classmethod
5✔
1480
    def gen(cls) -> str:
5✔
1481
        if tool := Project.get_manage_tool():
5✔
1482
            return cls.CommandEnum[tool]
5✔
1483
        return cls.CommandEnum.twine
5✔
1484

1485

1486
@cli.command()
5✔
1487
def upload(
5✔
1488
    dry: bool = DryOption,
1489
) -> None:
1490
    """Shortcut for package publish"""
1491
    cmd = Publish.gen()
5✔
1492
    exit_if_run_failed(cmd, dry=dry)
5✔
1493

1494

1495
def dev(
5✔
1496
    port: int | None | OptionInfo,
1497
    host: str | None | OptionInfo,
1498
    file: str | None | ArgumentInfo = None,
1499
    dry: bool = False,
1500
) -> None:
1501
    cmd = "fastapi dev"
5✔
1502
    no_port_yet = True
5✔
1503
    if file is not None:
5✔
1504
        try:
5✔
1505
            port = int(str(file))
5✔
1506
        except ValueError:
5✔
1507
            cmd += f" {file}"
5✔
1508
        else:
1509
            if port != 8000:
5✔
1510
                cmd += f" --port={port}"
5✔
1511
                no_port_yet = False
5✔
1512
    if no_port_yet and (port := getattr(port, "default", port)) and str(port) != "8000":
5✔
1513
        cmd += f" --port={port}"
5✔
1514
    if (host := getattr(host, "default", host)) and host not in (
5✔
1515
        "localhost",
1516
        "127.0.0.1",
1517
    ):
1518
        cmd += f" --host={host}"
5✔
1519
    exit_if_run_failed(cmd, dry=dry)
5✔
1520

1521

1522
@cli.command(name="dev")
5✔
1523
def runserver(
5✔
1524
    file_or_port: str | None = typer.Argument(default=None),
1525
    port: int | None = Option(None, "-p", "--port"),
1526
    host: str | None = Option(None, "-h", "--host"),
1527
    dry: bool = DryOption,
1528
) -> None:
1529
    """Start a fastapi server(only for fastapi>=0.111.0)"""
1530
    if getattr(file_or_port, "default", file_or_port):
5✔
1531
        dev(port, host, file=file_or_port, dry=dry)
5✔
1532
    else:
1533
        dev(port, host, dry=dry)
5✔
1534

1535

1536
@cli.command(name="exec")
5✔
1537
def run_by_subprocess(cmd: str, dry: bool = DryOption) -> None:
5✔
1538
    """Run cmd by subprocess, auto set shell=True when cmd contains '|>'"""
1539
    try:
5✔
1540
        rc = run_and_echo(cmd, verbose=True, dry=_ensure_bool(dry))
5✔
1541
    except FileNotFoundError as e:
5✔
1542
        command = cmd.split()[0]
5✔
1543
        if e.filename == command or (
5✔
1544
            e.filename is None and "系统找不到指定的文件" in str(e)
1545
        ):
1546
            echo(f"Command not found: {command}")
5✔
1547
            raise Exit(1) from None
5✔
1548
        raise e
×
1549
    else:
1550
        if rc:
5✔
1551
            raise Exit(rc)
5✔
1552

1553

1554
class MakeDeps(DryRun):
5✔
1555
    def __init__(
5✔
1556
        self,
1557
        tool: str,
1558
        prod: bool = False,
1559
        dry: bool = False,
1560
        active: bool = True,
1561
        inexact: bool = True,
1562
    ) -> None:
1563
        self._tool = tool
5✔
1564
        self._prod = prod
5✔
1565
        self._active = active
5✔
1566
        self._inexact = inexact
5✔
1567
        super().__init__(dry=dry)
5✔
1568

1569
    def should_ensure_pip(self) -> bool:
5✔
1570
        return True
5✔
1571

1572
    def should_upgrade_pip(self) -> bool:
5✔
1573
        return True
×
1574

1575
    def get_groups(self) -> list[str]:
5✔
1576
        if self._prod:
5✔
1577
            return []
5✔
1578
        return ["dev"]
5✔
1579

1580
    def gen(self) -> str:
5✔
1581
        if self._tool == "pdm":
5✔
1582
            return "pdm install --frozen " + ("--prod" if self._prod else "-G :all")
5✔
1583
        elif self._tool == "uv":
5✔
1584
            uv_sync = "uv sync" + " --inexact" * self._inexact
5✔
1585
            if self._active:
5✔
1586
                uv_sync += " --active"
5✔
1587
            return uv_sync + ("" if self._prod else " --all-extras --all-groups")
5✔
1588
        elif self._tool == "poetry":
5✔
1589
            return "poetry install " + (
5✔
1590
                "--only=main" if self._prod else "--all-extras --all-groups"
1591
            )
1592
        else:
1593
            cmd = "python -m pip install -e ."
5✔
1594
            if gs := self.get_groups():
5✔
1595
                cmd += " " + " ".join(f"--group {g}" for g in gs)
5✔
1596
            upgrade = "python -m pip install --upgrade pip"
5✔
1597
            if self.should_ensure_pip():
5✔
1598
                cmd = f"python -m ensurepip && {upgrade} && {cmd}"
5✔
1599
            elif self.should_upgrade_pip():
×
1600
                cmd = "{upgrade} && {cmd}"
×
1601
            return cmd
5✔
1602

1603

1604
@cli.command(name="deps")
5✔
1605
def make_deps(
5✔
1606
    prod: bool = Option(
1607
        False,
1608
        "--prod",
1609
        help="Only instead production dependencies.",
1610
    ),
1611
    tool: str = ToolOption,
1612
    use_uv: bool = Option(False, "--uv", help="Use `uv` to install deps"),
1613
    use_pdm: bool = Option(False, "--pdm", help="Use `pdm` to install deps"),
1614
    use_pip: bool = Option(False, "--pip", help="Use `pip` to install deps"),
1615
    use_poetry: bool = Option(False, "--poetry", help="Use `poetry` to install deps"),
1616
    active: bool = Option(
1617
        True, help="Add `--active` to uv sync command(Only work for uv project)"
1618
    ),
1619
    inexact: bool = Option(
1620
        True, help="Add `--inexact` to uv sync command(Only work for uv project)"
1621
    ),
1622
    dry: bool = DryOption,
1623
) -> None:
1624
    """Run: ruff check/format to reformat code and then mypy to check"""
1625
    if use_uv + use_pdm + use_pip + use_poetry > 1:
×
1626
        raise UsageError("`--uv/--pdm/--pip/--poetry` can only choose one!")
×
1627
    if use_uv:
×
1628
        tool = "uv"
×
1629
    elif use_pdm:
×
1630
        tool = "pdm"
×
1631
    elif use_pip:
×
1632
        tool = "pip"
×
1633
    elif use_poetry:
×
1634
        tool = "poetry"
×
1635
    elif tool == ToolOption.default:
×
1636
        tool = Project.get_manage_tool(cache=True) or "pip"
×
1637
    MakeDeps(tool, prod, active=active, inexact=inexact, dry=dry).run()
×
1638

1639

1640
class UvPypi(DryRun):
5✔
1641
    PYPI = "https://pypi.org/simple"
5✔
1642
    HOST = "https://files.pythonhosted.org"
5✔
1643

1644
    def __init__(
5✔
1645
        self, lock_file: Path, dry: bool, verbose: bool, quiet: bool, slim: bool = False
1646
    ) -> None:
1647
        super().__init__(dry=dry)
5✔
1648
        self.lock_file = lock_file
5✔
1649
        self._verbose = _ensure_bool(verbose)
5✔
1650
        self._quiet = _ensure_bool(quiet)
5✔
1651
        self._slim = _ensure_bool(slim)
5✔
1652

1653
    def run(self) -> None:
5✔
1654
        try:
5✔
1655
            rc = self.update_lock(
5✔
1656
                self.lock_file, self._verbose, self._quiet, self._slim
1657
            )
1658
        except ValueError as e:
×
1659
            secho(str(e), fg=typer.colors.RED)
×
1660
            raise Exit(1) from e
×
1661
        else:
1662
            if rc != 0:
5✔
1663
                raise Exit(rc)
5✔
1664

1665
    @classmethod
5✔
1666
    def update_lock(
5✔
1667
        cls, p: Path, verbose: bool, quiet: bool, slim: bool = False
1668
    ) -> int:
1669
        text = p.read_text("utf-8")
5✔
1670
        registry_pattern = r'(registry = ")(.*?)"'
5✔
1671
        replace_registry = functools.partial(
5✔
1672
            re.sub, registry_pattern, rf'\1{cls.PYPI}"'
1673
        )
1674
        registry_urls = {i[1] for i in re.findall(registry_pattern, text)}
5✔
1675
        download_pattern = r'(url = ")(https?://.*?)(/packages/.*?\.)(gz|whl)"'
5✔
1676
        replace_host = functools.partial(
5✔
1677
            re.sub, download_pattern, rf'\1{cls.HOST}\3\4"'
1678
        )
1679
        download_hosts = {i[1] for i in re.findall(download_pattern, text)}
5✔
1680
        if not registry_urls:
5✔
1681
            raise ValueError(f"Failed to find pattern {registry_pattern!r} in {p}")
×
1682
        if len(registry_urls) == 1:
5✔
1683
            current_registry = registry_urls.pop()
5✔
1684
            if current_registry == cls.PYPI:
5✔
1685
                if download_hosts == {cls.HOST}:
5✔
1686
                    if verbose:
5✔
1687
                        echo(f"Registry of {p} is {cls.PYPI}, no need to change.")
5✔
1688
                    return 0
5✔
1689
            else:
1690
                text = replace_registry(text)
5✔
1691
                if verbose:
5✔
1692
                    echo(f"{current_registry} --> {cls.PYPI}")
×
1693
        else:
1694
            # TODO: ask each one to confirm replace
1695
            text = replace_registry(text)
×
1696
            if verbose:
×
1697
                for current_registry in sorted(registry_urls):
×
1698
                    echo(f"{current_registry} --> {cls.PYPI}")
×
1699
        if len(download_hosts) == 1:
5✔
1700
            current_host = download_hosts.pop()
5✔
1701
            if current_host != cls.HOST:
5✔
1702
                text = replace_host(text)
5✔
1703
                if verbose:
5✔
1704
                    print(current_host, "-->", cls.HOST)
×
1705
        elif download_hosts:
×
1706
            # TODO: ask each one to confirm replace
1707
            text = replace_host(text)
×
1708
            if verbose:
×
1709
                for current_host in sorted(download_hosts):
×
1710
                    echo(f"{current_host} --> {cls.HOST}")
×
1711
        return cls.slim_and_write(cast(str, text), slim, p, verbose, quiet)
5✔
1712

1713
    @staticmethod
5✔
1714
    def slim_and_write(
5✔
1715
        text: str, slim: bool, p: Path, verbose: bool, quiet: bool
1716
    ) -> int:
1717
        if slim:
5✔
1718
            pattern = r', size = \d+, upload-time = ".*?"'
5✔
1719
            text = re.sub(pattern, "", text)
5✔
1720
        size = p.write_text(text, encoding="utf-8")
5✔
1721
        if verbose:
5✔
1722
            echo(f"Updated {p} with {size} bytes.")
×
1723
        if quiet:
5✔
1724
            return 0
5✔
1725
        return 1
5✔
1726

1727

1728
@cli.command()
5✔
1729
def pypi(
5✔
1730
    file: str | None = typer.Argument(default=None),
1731
    dry: bool = DryOption,
1732
    verbose: bool = False,
1733
    quiet: bool = False,
1734
    slim: bool = False,
1735
) -> None:
1736
    """Change registry of uv.lock to be pypi.org"""
1737
    if not (p := Path(_ensure_str(file) or "uv.lock")).exists() and not (
5✔
1738
        (p := Project.get_work_dir() / p.name).exists()
1739
    ):
1740
        yellow_warn(f"{p.name!r} not found!")
5✔
1741
        return
5✔
1742
    UvPypi(p, dry, verbose, quiet, slim).run()
5✔
1743

1744

1745
def version_callback(value: bool) -> None:
5✔
1746
    if value:
5✔
1747
        echo("Fast Dev Cli Version: " + typer.style(__version__, bold=True))
5✔
1748
        raise Exit()
5✔
1749

1750

1751
@cli.callback()
1752
def common(
1753
    version: bool = Option(
1754
        None,
1755
        "--version",
1756
        "-V",
1757
        callback=version_callback,
1758
        is_eager=True,
1759
        help="Show the version of this tool",
1760
    ),
1761
) -> None: ...
1762

1763

1764
def main() -> None:
5✔
1765
    cli()
5✔
1766

1767

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