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

waketzheng / fast-dev-cli / 20686992064

04 Jan 2026 03:31AM UTC coverage: 87.238% (+0.2%) from 87.008%
20686992064

push

github

waketzheng
Bump version: 0.19.5 → 0.19.6

1 of 1 new or added line in 1 file covered. (100.0%)

14 existing lines in 1 file now uncovered.

957 of 1097 relevant lines covered (87.24%)

4.36 hits per line

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

87.23
/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()
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
    ) -> None:
1068
        self.args = args
5✔
1069
        self.check_only = check_only
5✔
1070
        self._bandit = bandit
5✔
1071
        self._skip_mypy = skip_mypy
5✔
1072
        self._use_dmypy = dmypy
5✔
1073
        self._tool = tool
5✔
1074
        self._prefix = prefix
5✔
1075
        self._up = up
5✔
1076
        self._sim = sim
5✔
1077
        self._strict = strict
5✔
1078
        super().__init__(_exit, dry)
5✔
1079

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

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

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

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

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

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

1254

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

1258

1259
def lint(
5✔
1260
    files: list[str] | str | None = None,
1261
    dry: bool = False,
1262
    bandit: bool = False,
1263
    skip_mypy: bool = False,
1264
    dmypy: bool = False,
1265
    tool: str = ToolOption.default,
1266
    prefix: bool = False,
1267
    up: bool = False,
1268
    sim: bool = True,
1269
    strict: bool = False,
1270
) -> None:
1271
    if files is None:
5✔
1272
        files = parse_files(sys.argv[1:])
5✔
1273
    if files and files[0] == "lint":
5✔
1274
        files = files[1:]
5✔
1275
    LintCode(
5✔
1276
        files,
1277
        dry=dry,
1278
        skip_mypy=skip_mypy,
1279
        bandit=bandit,
1280
        dmypy=dmypy,
1281
        tool=tool,
1282
        prefix=prefix,
1283
        up=up,
1284
        sim=sim,
1285
        strict=strict,
1286
    ).run()
1287

1288

1289
def check(
5✔
1290
    files: list[str] | str | None = None,
1291
    dry: bool = False,
1292
    bandit: bool = False,
1293
    skip_mypy: bool = False,
1294
    dmypy: bool = False,
1295
    tool: str = ToolOption.default,
1296
    up: bool = False,
1297
    sim: bool = True,
1298
    strict: bool = False,
1299
) -> None:
1300
    LintCode(
5✔
1301
        files,
1302
        check_only=True,
1303
        _exit=True,
1304
        dry=dry,
1305
        bandit=bandit,
1306
        skip_mypy=skip_mypy,
1307
        dmypy=dmypy,
1308
        tool=tool,
1309
        up=up,
1310
        sim=sim,
1311
        strict=strict,
1312
    ).run()
1313

1314

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

1352

1353
@cli.command(name="check")
5✔
1354
def only_check(
5✔
1355
    bandit: bool = Option(False, "--bandit", help="Run `bandit -r <package_dir>`"),
1356
    skip_mypy: bool = Option(False, "--skip-mypy"),
1357
    dry: bool = DryOption,
1358
    up: bool = Option(False, help="Whether ruff check with --extend-select=UP"),
1359
    sim: bool = Option(True, help="Whether ruff check with --extend-select=SIM"),
1360
    strict: bool = Option(False, help="Whether run mypy with --strict"),
1361
) -> None:
1362
    """Check code style without reformat"""
1363
    bandit = _ensure_bool(bandit)
5✔
1364
    up = _ensure_bool(up)
5✔
1365
    sim = _ensure_bool(sim)
5✔
1366
    check(dry=dry, bandit=bandit, skip_mypy=_ensure_bool(skip_mypy), up=up, sim=sim)
5✔
1367

1368

1369
class Sync(DryRun):
5✔
1370
    def __init__(
5✔
1371
        self, filename: str, extras: str, save: bool, dry: bool = False
1372
    ) -> None:
1373
        self.filename = filename
5✔
1374
        self.extras = extras
5✔
1375
        self._save = save
5✔
1376
        super().__init__(dry=dry)
5✔
1377

1378
    def gen(self) -> str:
5✔
1379
        extras, save = self.extras, self._save
5✔
1380
        should_remove = not Path.cwd().joinpath(self.filename).exists()
5✔
1381
        if not (tool := Project.get_manage_tool()):
5✔
1382
            if should_remove or not is_venv():
5✔
1383
                raise EnvError("There project is not managed by uv/pdm/poetry!")
5✔
1384
            return f"python -m pip install -r {self.filename}"
5✔
1385
        prefix = "" if is_venv() else f"{tool} run "
5✔
1386
        ensure_pip = " {1}python -m ensurepip && {1}python -m pip install -U pip &&"
5✔
1387
        export_cmd = "uv export --no-hashes --all-extras --frozen"
5✔
1388
        if tool in ("poetry", "pdm"):
5✔
1389
            export_cmd = f"{tool} export --without-hashes --with=dev"
5✔
1390
            if tool == "poetry":
5✔
1391
                ensure_pip = ""
5✔
1392
                if not UpgradeDependencies.should_with_dev():
5✔
1393
                    export_cmd = export_cmd.replace(" --with=dev", "")
5✔
1394
                if extras and isinstance(extras, str | list):
5✔
1395
                    export_cmd += f" --{extras=}".replace("'", '"')
5✔
1396
            elif check_call(prefix + "python -m pip --version"):
5✔
1397
                ensure_pip = ""
5✔
1398
        elif check_call(prefix + "python -m pip --version"):
5✔
1399
            ensure_pip = ""
5✔
1400
        install_cmd = (
5✔
1401
            f"{{2}} -o {{0}} &&{ensure_pip} {{1}}python -m pip install -r {{0}}"
1402
        )
1403
        if should_remove and not save:
5✔
1404
            install_cmd += " && rm -f {0}"
5✔
1405
        return install_cmd.format(self.filename, prefix, export_cmd)
5✔
1406

1407

1408
@cli.command()
5✔
1409
def sync(
5✔
1410
    filename: str = "dev_requirements.txt",
1411
    extras: str = Option("", "--extras", "-E"),
1412
    save: bool = Option(
1413
        False, "--save", "-s", help="Whether save the requirement file"
1414
    ),
1415
    dry: bool = DryOption,
1416
) -> None:
1417
    """Export dependencies by poetry to a txt file then install by pip."""
1418
    Sync(filename, extras, save, dry=dry).run()
5✔
1419

1420

1421
def _should_run_test_script(path: Path = Path("scripts")) -> Path | None:
5✔
1422
    for name in ("test.sh", "test.py"):
5✔
1423
        if (file := path / name).exists():
5✔
1424
            return file
5✔
1425
    return None
5✔
1426

1427

1428
def test(dry: bool, ignore_script: bool = False) -> None:
5✔
1429
    cwd = Path.cwd()
5✔
1430
    root = Project.get_work_dir(cwd=cwd, allow_cwd=True)
5✔
1431
    script_dir = root / "scripts"
5✔
1432
    if not _ensure_bool(ignore_script) and (
5✔
1433
        test_script := _should_run_test_script(script_dir)
1434
    ):
1435
        cmd = test_script.relative_to(root).as_posix()
5✔
1436
        if test_script.suffix == ".py":
5✔
1437
            cmd = "python " + cmd
5✔
1438
        if cwd != root:
5✔
1439
            cmd = f"cd {root} && " + cmd
5✔
1440
    else:
1441
        cmd = 'coverage run -m pytest -s && coverage report --omit="tests/*" -m'
5✔
1442
        if not is_venv() or not check_call("coverage --version"):
5✔
1443
            sep = " && "
5✔
1444
            prefix = f"{tool} run " if (tool := Project.get_manage_tool()) else ""
5✔
1445
            cmd = sep.join(prefix + i for i in cmd.split(sep))
5✔
1446
    exit_if_run_failed(cmd, dry=dry)
5✔
1447

1448

1449
@cli.command(name="test")
5✔
1450
def coverage_test(
5✔
1451
    dry: bool = DryOption,
1452
    ignore_script: bool = Option(False, "--ignore-script", "-i"),
1453
) -> None:
1454
    """Run unittest by pytest and report coverage"""
1455
    return test(dry, ignore_script)
5✔
1456

1457

1458
class Publish:
5✔
1459
    class CommandEnum(StrEnum):
5✔
1460
        poetry = "poetry publish --build"
5✔
1461
        pdm = "pdm publish"
5✔
1462
        uv = "uv build && uv publish"
5✔
1463
        twine = "python -m build && twine upload"
5✔
1464

1465
    @classmethod
5✔
1466
    def gen(cls) -> str:
5✔
1467
        if tool := Project.get_manage_tool():
5✔
1468
            return cls.CommandEnum[tool]
5✔
1469
        return cls.CommandEnum.twine
5✔
1470

1471

1472
@cli.command()
5✔
1473
def upload(
5✔
1474
    dry: bool = DryOption,
1475
) -> None:
1476
    """Shortcut for package publish"""
1477
    cmd = Publish.gen()
5✔
1478
    exit_if_run_failed(cmd, dry=dry)
5✔
1479

1480

1481
def dev(
5✔
1482
    port: int | None | OptionInfo,
1483
    host: str | None | OptionInfo,
1484
    file: str | None | ArgumentInfo = None,
1485
    dry: bool = False,
1486
) -> None:
1487
    cmd = "fastapi dev"
5✔
1488
    no_port_yet = True
5✔
1489
    if file is not None:
5✔
1490
        try:
5✔
1491
            port = int(str(file))
5✔
1492
        except ValueError:
5✔
1493
            cmd += f" {file}"
5✔
1494
        else:
1495
            if port != 8000:
5✔
1496
                cmd += f" --port={port}"
5✔
1497
                no_port_yet = False
5✔
1498
    if no_port_yet and (port := getattr(port, "default", port)) and str(port) != "8000":
5✔
1499
        cmd += f" --port={port}"
5✔
1500
    if (host := getattr(host, "default", host)) and host not in (
5✔
1501
        "localhost",
1502
        "127.0.0.1",
1503
    ):
1504
        cmd += f" --host={host}"
5✔
1505
    exit_if_run_failed(cmd, dry=dry)
5✔
1506

1507

1508
@cli.command(name="dev")
5✔
1509
def runserver(
5✔
1510
    file_or_port: str | None = typer.Argument(default=None),
1511
    port: int | None = Option(None, "-p", "--port"),
1512
    host: str | None = Option(None, "-h", "--host"),
1513
    dry: bool = DryOption,
1514
) -> None:
1515
    """Start a fastapi server(only for fastapi>=0.111.0)"""
1516
    if getattr(file_or_port, "default", file_or_port):
5✔
1517
        dev(port, host, file=file_or_port, dry=dry)
5✔
1518
    else:
1519
        dev(port, host, dry=dry)
5✔
1520

1521

1522
@cli.command(name="exec")
5✔
1523
def run_by_subprocess(cmd: str, dry: bool = DryOption) -> None:
5✔
1524
    """Run cmd by subprocess, auto set shell=True when cmd contains '|>'"""
1525
    try:
5✔
1526
        rc = run_and_echo(cmd, verbose=True, dry=_ensure_bool(dry))
5✔
1527
    except FileNotFoundError as e:
5✔
1528
        command = cmd.split()[0]
5✔
1529
        if e.filename == command or (
5✔
1530
            e.filename is None and "系统找不到指定的文件" in str(e)
1531
        ):
1532
            echo(f"Command not found: {command}")
5✔
1533
            raise Exit(1) from None
5✔
1534
        raise e
×
1535
    else:
1536
        if rc:
5✔
1537
            raise Exit(rc)
5✔
1538

1539

1540
class MakeDeps(DryRun):
5✔
1541
    def __init__(
5✔
1542
        self,
1543
        tool: str,
1544
        prod: bool = False,
1545
        dry: bool = False,
1546
        active: bool = True,
1547
        inexact: bool = True,
1548
    ) -> None:
1549
        self._tool = tool
5✔
1550
        self._prod = prod
5✔
1551
        self._active = active
5✔
1552
        self._inexact = inexact
5✔
1553
        super().__init__(dry=dry)
5✔
1554

1555
    def should_ensure_pip(self) -> bool:
5✔
1556
        return True
5✔
1557

1558
    def should_upgrade_pip(self) -> bool:
5✔
1559
        return True
×
1560

1561
    def get_groups(self) -> list[str]:
5✔
1562
        if self._prod:
5✔
1563
            return []
5✔
1564
        return ["dev"]
5✔
1565

1566
    def gen(self) -> str:
5✔
1567
        if self._tool == "pdm":
5✔
1568
            return "pdm install --frozen " + ("--prod" if self._prod else "-G :all")
5✔
1569
        elif self._tool == "uv":
5✔
1570
            uv_sync = "uv sync" + " --inexact" * self._inexact
5✔
1571
            if self._active:
5✔
1572
                uv_sync += " --active"
5✔
1573
            return uv_sync + ("" if self._prod else " --all-extras --all-groups")
5✔
1574
        elif self._tool == "poetry":
5✔
1575
            return "poetry install " + (
5✔
1576
                "--only=main" if self._prod else "--all-extras --all-groups"
1577
            )
1578
        else:
1579
            cmd = "python -m pip install -e ."
5✔
1580
            if gs := self.get_groups():
5✔
1581
                cmd += " " + " ".join(f"--group {g}" for g in gs)
5✔
1582
            upgrade = "python -m pip install --upgrade pip"
5✔
1583
            if self.should_ensure_pip():
5✔
1584
                cmd = f"python -m ensurepip && {upgrade} && {cmd}"
5✔
1585
            elif self.should_upgrade_pip():
×
1586
                cmd = "{upgrade} && {cmd}"
×
1587
            return cmd
5✔
1588

1589

1590
@cli.command(name="deps")
5✔
1591
def make_deps(
5✔
1592
    prod: bool = Option(
1593
        False,
1594
        "--prod",
1595
        help="Only instead production dependencies.",
1596
    ),
1597
    tool: str = ToolOption,
1598
    use_uv: bool = Option(False, "--uv", help="Use `uv` to install deps"),
1599
    use_pdm: bool = Option(False, "--pdm", help="Use `pdm` to install deps"),
1600
    use_pip: bool = Option(False, "--pip", help="Use `pip` to install deps"),
1601
    use_poetry: bool = Option(False, "--poetry", help="Use `poetry` to install deps"),
1602
    active: bool = Option(
1603
        True, help="Add `--active` to uv sync command(Only work for uv project)"
1604
    ),
1605
    inexact: bool = Option(
1606
        True, help="Add `--inexact` to uv sync command(Only work for uv project)"
1607
    ),
1608
    dry: bool = DryOption,
1609
) -> None:
1610
    """Run: ruff check/format to reformat code and then mypy to check"""
1611
    if use_uv + use_pdm + use_pip + use_poetry > 1:
×
1612
        raise UsageError("`--uv/--pdm/--pip/--poetry` can only choose one!")
×
1613
    if use_uv:
×
1614
        tool = "uv"
×
1615
    elif use_pdm:
×
1616
        tool = "pdm"
×
1617
    elif use_pip:
×
1618
        tool = "pip"
×
1619
    elif use_poetry:
×
1620
        tool = "poetry"
×
1621
    elif tool == ToolOption.default:
×
1622
        tool = Project.get_manage_tool(cache=True) or "pip"
×
1623
    MakeDeps(tool, prod, active=active, inexact=inexact, dry=dry).run()
×
1624

1625

1626
class UvPypi(DryRun):
5✔
1627
    PYPI = "https://pypi.org/simple"
5✔
1628
    HOST = "https://files.pythonhosted.org"
5✔
1629

1630
    def __init__(
5✔
1631
        self, lock_file: Path, dry: bool, verbose: bool, quiet: bool, slim: bool = False
1632
    ) -> None:
1633
        super().__init__(dry=dry)
5✔
1634
        self.lock_file = lock_file
5✔
1635
        self._verbose = _ensure_bool(verbose)
5✔
1636
        self._quiet = _ensure_bool(quiet)
5✔
1637
        self._slim = _ensure_bool(slim)
5✔
1638

1639
    def run(self) -> None:
5✔
1640
        try:
5✔
1641
            rc = self.update_lock(
5✔
1642
                self.lock_file, self._verbose, self._quiet, self._slim
1643
            )
UNCOV
1644
        except ValueError as e:
×
UNCOV
1645
            secho(str(e), fg=typer.colors.RED)
×
UNCOV
1646
            raise Exit(1) from e
×
1647
        else:
1648
            if rc != 0:
5✔
1649
                raise Exit(rc)
5✔
1650

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

1707

1708
@cli.command()
5✔
1709
def pypi(
5✔
1710
    file: str | None = typer.Argument(default=None),
1711
    dry: bool = DryOption,
1712
    verbose: bool = False,
1713
    quiet: bool = False,
1714
    slim: bool = False,
1715
) -> None:
1716
    """Change registry of uv.lock to be pypi.org"""
1717
    if not (p := Path(_ensure_str(file) or "uv.lock")).exists() and not (
5✔
1718
        (p := Project.get_work_dir() / p.name).exists()
1719
    ):
1720
        yellow_warn(f"{p.name!r} not found!")
5✔
1721
        return
5✔
1722
    UvPypi(p, dry, verbose, quiet, slim).run()
5✔
1723

1724

1725
def version_callback(value: bool) -> None:
5✔
1726
    if value:
5✔
1727
        echo("Fast Dev Cli Version: " + typer.style(__version__, bold=True))
5✔
1728
        raise Exit()
5✔
1729

1730

1731
@cli.callback()
1732
def common(
1733
    version: bool = Option(
1734
        None,
1735
        "--version",
1736
        "-V",
1737
        callback=version_callback,
1738
        is_eager=True,
1739
        help="Show the version of this tool",
1740
    ),
1741
) -> None: ...
1742

1743

1744
def main() -> None:
5✔
1745
    cli()
5✔
1746

1747

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