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

waketzheng / fast-dev-cli / 29545491676

17 Jul 2026 12:41AM UTC coverage: 84.615% (-0.4%) from 85.019%
29545491676

push

github

waketzheng
Bump version: 0.24.1 → 0.24.2

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

97 existing lines in 1 file now uncovered.

1111 of 1313 relevant lines covered (84.62%)

4.23 hits per line

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

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

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

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

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

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

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

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

35
    import tomli as tomllib
36

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

40

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

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

55

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

59

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

63

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

67

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

71

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

82

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

94

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

99

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

107

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

113

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

125

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

132

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

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

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

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

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

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

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

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

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

207

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

214

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

218

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

224

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

234

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

238

239
def read_version_from_file(
5✔
240
    package_name: str, work_dir: Path | None = None, toml_text: str | None = None
241
) -> str:
242
    if not package_name and toml_text:
5✔
243
        pattern = re.compile(r"version\s*=")
5✔
244
        for line in toml_text.splitlines():
5✔
245
            if pattern.match(line):
5✔
246
                return _parse_version(line, pattern)
5✔
247
    version_file = BumpUp.parse_filename(toml_text, work_dir, package_name)
5✔
248
    if version_file == TOML_FILE:
5✔
249
        if toml_text is None:
5✔
250
            toml_text = Project.load_toml_text()
5✔
251
        context = tomllib.loads(toml_text)
5✔
252
        with contextlib.suppress(KeyError):
5✔
253
            return cast(str, context["project"]["version"])
5✔
254
        with contextlib.suppress(KeyError):  # Poetry V1
5✔
255
            return cast(str, context["tool"]["poetry"]["version"])
5✔
256
        secho(f"WARNING: can not find 'version' item in {version_file}!")
5✔
257
        return "0.0.0"
5✔
258
    pattern = re.compile(r"__version__\s*=")
5✔
259
    all_lines = Path(version_file).read_text("utf-8").strip().splitlines()
5✔
260
    for line in all_lines:
5✔
261
        if pattern.match(line):
5✔
262
            return _parse_version(line, pattern)
5✔
263
    else:
264
        pattern = re.compile(r"VERSION\s*=")
×
265
        for line in all_lines:
×
266
            if pattern.match(line):
×
267
                return _parse_version(line, pattern)
×
268
        secho(f"WARNING: can not find version pattern in {version_file}!")
×
UNCOV
269
        return "0.0.0"
×
270

271

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

291

292
@overload
293
def get_current_version(
294
    verbose: bool = False,
295
    is_poetry: bool | None = None,
296
    package_name: str | None = None,
297
    *,
298
    check_version: Literal[False] = False,
299
) -> str: ...
300

301

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

311

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

353

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

362

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

368

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

374

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

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

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

386

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

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

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

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

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

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

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

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

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

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

599

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

604

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

634

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

660

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

672

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

874

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

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

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

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

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

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

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

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

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

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

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

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

1051

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

1066

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

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

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

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

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

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

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

1109

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

1121

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

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

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

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

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

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

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

1340

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

1344

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

1378

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

1406

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

1451

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

1469

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

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

1510

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

1523

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

1530

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

1551

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

1560

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

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

1574

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

1583

1584
def should_use_just() -> bool:
5✔
1585
    if shutil.which("just") is None or load_bool("FASTDEVCLI_IGNORE_JUST_DEV"):
5✔
1586
        return False
5✔
1587
    d = Path.cwd()
5✔
1588
    for _ in range(5):
5✔
1589
        f = d / "justfile"
5✔
1590
        if f.exists():
5✔
1591
            return _prefer_just_dev(f)
5✔
1592
        if d.joinpath("pyproject.toml").exists():
×
1593
            break
×
1594
    return False
×
1595

1596

1597
def _prefer_just_dev(f: Path) -> bool:
5✔
1598
    text = f.read_text(encoding="utf-8")
5✔
1599
    lines = text.splitlines()
5✔
1600
    dev_recipe = "dev *args:"
5✔
1601
    re_import = re.compile(r"import[?]? ")
5✔
1602
    has_import = False
5✔
1603
    for i, line in enumerate(lines):
5✔
1604
        if line.startswith(dev_recipe):
5✔
1605
            # Avoid cycle callback
1606
            return "fast dev" not in lines[i + 1]
5✔
1607
        elif not has_import and re_import.match(line):
5✔
1608
            has_import = True
×
1609
    if has_import:
×
1610
        recipes = capture_cmd_output("just --list").splitlines()
×
1611
        for recipe in recipes:
×
1612
            recipe = recipe.strip()
×
1613
            if recipe.startswith(dev_recipe):
×
UNCOV
1614
                return "fast dev" not in recipe
×
UNCOV
1615
    return False
×
1616

1617

1618
def _parse_serve_file(uvicorn, filename: str, cmd: str, args: list) -> str:
5✔
1619
    if m := re.search(r"(.*):(\d+)$", filename):
5✔
1620
        h, p = m.group(1), m.group(2)
5✔
1621
        if h and "--host" not in str(args):
5✔
1622
            if h == "0":
5✔
1623
                args.append("--host=0.0.0.0")
5✔
1624
            else:
1625
                args.append(f"--host={h}")
5✔
1626
        args.append(f"--port={p}")
5✔
1627
        if uvicorn:
5✔
UNCOV
1628
            p = Path("main.py")
×
UNCOV
1629
            if p.exists():
×
UNCOV
1630
                cmd += " main:app"
×
UNCOV
1631
            elif Path("app", p.name).exists():
×
UNCOV
1632
                cmd += " app.main:app"
×
UNCOV
1633
            elif Path("app.py").exists():
×
UNCOV
1634
                cmd += " app:app"
×
1635
        return cmd
5✔
1636
    if uvicorn and ((filepath := Path(filename)).is_file() or filepath.suffix == ".py"):
5✔
1637
        filename = filepath.stem + ":app"
5✔
1638
        parent_names = [j for i in filepath.parents if (j := i.name)]
5✔
1639
        if parent_names:
5✔
1640
            filename = ".".join([*parent_names[::-1], filename])
5✔
1641
    cmd += " " + filename
5✔
1642
    return cmd
5✔
1643

1644

1645
def _runserver(uvicorn, host, port, file) -> tuple[str, list[str]]:
5✔
1646
    cmd = "uvicorn" if uvicorn else "fastapi dev"
5✔
1647
    args = []
5✔
1648
    if (host := getattr(host, "default", host)) and host not in (
5✔
1649
        "localhost",
1650
        "127.0.0.1",
1651
    ):
1652
        args.append(f"--host={host}")
5✔
1653
    no_port_yet = True
5✔
1654
    if file is not None:
5✔
1655
        filename = str(file)
5✔
1656
        try:
5✔
1657
            port = int(filename)
5✔
1658
        except ValueError:
5✔
1659
            cmd = _parse_serve_file(uvicorn, filename, cmd, args)
5✔
1660
        else:
1661
            if port != 8000:
5✔
1662
                args.append(f"--port={port}")
5✔
1663
                no_port_yet = False
5✔
1664
    if no_port_yet and (port := getattr(port, "default", port)) and str(port) != "8000":
5✔
1665
        args.append(f"--port={port}")
5✔
1666
    if shutil.which("pdm") is not None:
5✔
1667
        cmd = "pdm run " + cmd
5✔
1668
    return cmd, args
5✔
1669

1670

1671
def dev(
5✔
1672
    port: int | None | OptionInfo,
1673
    host: str | None | OptionInfo,
1674
    fastapi: bool | None = None,
1675
    uvicorn: bool | None = None,
1676
    prod: bool | None = None,
1677
    reload: bool | None = None,
1678
    file: str | None | ArgumentInfo = None,
1679
    dry: bool = False,
1680
) -> None:
1681
    if should_use_just():
5✔
UNCOV
1682
        args = [i for i in sys.argv[2:] if i != "--dry"]
×
UNCOV
1683
        cmd = "just dev"
×
1684
    else:
1685
        cmd, args = _runserver(uvicorn, host, port, file)
5✔
1686
    if args:
5✔
1687
        cmd += " " + " ".join(args)
5✔
1688
    exit_if_run_failed(cmd, dry=dry)
5✔
1689

1690

1691
@cli.command(name="dev")
5✔
1692
def runserver(
5✔
1693
    file_or_port: str | None = typer.Argument(default=None),
1694
    port: int | None = Option(None, "-p", "--port"),
1695
    host: str | None = Option(None, "-h", "--host"),
1696
    fastapi: bool | None = None,
1697
    uvicorn: bool | None = None,
1698
    prod: bool | None = None,
1699
    reload: bool | None = None,
1700
    dry: bool = DryOption,
1701
) -> None:
1702
    """Start a fastapi server(only for fastapi>=0.111.0)"""
1703
    f = functools.partial(dev, port, host, fastapi, uvicorn, prod, reload, dry=dry)
5✔
1704
    if getattr(file_or_port, "default", file_or_port):
5✔
1705
        f(file=file_or_port)
5✔
1706
    else:
1707
        f()
5✔
1708

1709

1710
@cli.command(name="exec")
5✔
1711
def run_by_subprocess(cmd: str, dry: bool = DryOption) -> None:
5✔
1712
    """Run cmd by subprocess, auto set shell=True when cmd contains '|>'"""
1713
    try:
5✔
1714
        rc = run_and_echo(cmd, verbose=True, dry=_ensure_bool(dry))
5✔
1715
    except FileNotFoundError as e:
5✔
1716
        command = cmd.split()[0]
5✔
1717
        if e.filename == command or (
5✔
1718
            e.filename is None and "系统找不到指定的文件" in str(e)
1719
        ):
1720
            echo(f"Command not found: {command}")
5✔
1721
            raise Exit(1) from None
5✔
UNCOV
1722
        raise e
×
1723
    else:
1724
        if rc:
5✔
1725
            raise Exit(rc)
5✔
1726

1727

1728
class MakeDeps(DryRun):
5✔
1729
    def __init__(
5✔
1730
        self,
1731
        tool: str,
1732
        prod: bool = False,
1733
        dry: bool = False,
1734
        active: bool = False,
1735
        inexact: bool = False,
1736
        no_dev: bool = False,
1737
        verbose: bool = False,
1738
        frozen: bool = False,
1739
        no_extra: list[str] | None = None,
1740
        no_group: list[str] | None = None,
1741
    ) -> None:
1742
        self._tool = tool
5✔
1743
        self._prod = prod
5✔
1744
        self._active = active or load_bool("FASTDEVCLI_DEPS_ACTIVE")
5✔
1745
        self._inexact = inexact or load_bool("FASTDEVCLI_DEPS_INEXACT")
5✔
1746
        self._verbose = verbose
5✔
1747
        self._frozen = frozen
5✔
1748
        self._no_dev = no_dev
5✔
1749
        self._no_extra = no_extra
5✔
1750
        self._no_group = no_group
5✔
1751
        super().__init__(dry=dry)
5✔
1752

1753
    def should_ensure_pip(self) -> bool:
5✔
1754
        return True
5✔
1755

1756
    def should_upgrade_pip(self) -> bool:
5✔
1757
        return True
5✔
1758

1759
    def get_groups(self) -> list[str]:
5✔
1760
        if self._prod:
5✔
1761
            return []
5✔
1762
        return ["dev"]
5✔
1763

1764
    def gen(self) -> str:
5✔
1765
        cmd = self._gen()
5✔
1766
        if self._verbose:
5✔
UNCOV
1767
            cmd += " --verbose"
×
1768
        if self._no_dev:
5✔
UNCOV
1769
            opt = " --no-dev"
×
UNCOV
1770
            if opt not in cmd:
×
1771
                cmd += opt
×
1772
        if self._no_extra:
5✔
UNCOV
1773
            cmd += " " + " ".join(f"--no-extra {i}" for i in self._no_extra)
×
1774
        if self._no_group:
5✔
1775
            cmd += " " + " ".join(f"--no-group {i}" for i in self._no_group)
×
1776
        if self._frozen:
5✔
1777
            cmd += " --frozen"
×
1778
        if opts := os.getenv("FASTDEVCLI_DEPS_OPTS"):
5✔
UNCOV
1779
            cmd += " " + opts.strip()
×
1780
        return cmd
5✔
1781

1782
    def get_package_name(self) -> str:
5✔
1783
        with contextlib.suppress(FileNotFoundError, KeyError):
5✔
1784
            try:
5✔
1785
                toml_text = Project.load_toml_text()
5✔
UNCOV
1786
            except EnvError:
×
UNCOV
1787
                return ""
×
1788
            doc = tomllib.loads(toml_text)
5✔
1789
            tool_section = doc["tool"]
5✔
1790
            uv_package = tool_section.get("uv", {}).get("package")
5✔
1791
            if uv_package is not None:
5✔
UNCOV
1792
                return doc["project"]["name"] if uv_package else ""
×
1793
            match doc["build-system"]["build-backend"]:
5✔
1794
                case "pdm.backend":
5✔
1795
                    if not tool_section.get("pdm", {}).get("distribution", True):
5✔
UNCOV
1796
                        return ""
×
UNCOV
1797
                case x if x.startswith("poetry"):
×
UNCOV
1798
                    if not tool_section.get("poetry", {}).get("package-mode", True):
×
UNCOV
1799
                        return ""
×
1800
            return doc["project"]["name"]
5✔
UNCOV
1801
        return ""
×
1802

1803
    def _gen(self) -> str:
5✔
1804
        if self._tool == "pdm":
5✔
1805
            return "pdm install --frozen " + ("--prod" if self._prod else "-G :all")
5✔
1806
        elif self._tool == "uv":
5✔
1807
            uv_sync = "uv sync"
5✔
1808
            if project := self.get_package_name():
5✔
1809
                uv_sync += f" --reinstall-package={project}"
5✔
1810
            uv_sync += " --inexact" * self._inexact + " --active" * self._active
5✔
1811
            return uv_sync + (
5✔
1812
                " --no-dev" if self._prod else " --all-extras --all-groups"
1813
            )
1814
        elif self._tool == "poetry":
5✔
1815
            return "poetry install " + (
5✔
1816
                "--only=main" if self._prod else "--all-extras --all-groups"
1817
            )
1818
        else:
1819
            cmd = "python -m pip install -e ."
5✔
1820
            if gs := self.get_groups():
5✔
1821
                cmd += " " + " ".join(f"--group {g}" for g in gs)
5✔
1822
            upgrade = "python -m pip install --upgrade pip"
5✔
1823
            if self.should_ensure_pip():
5✔
1824
                cmd = f"python -m ensurepip && {upgrade} && {cmd}"
5✔
1825
            elif self.should_upgrade_pip():
5✔
1826
                cmd = f"{upgrade} && {cmd}"
5✔
1827
            return cmd
5✔
1828

1829

1830
@cli.command(name="deps")
5✔
1831
def make_deps(
5✔
1832
    prod: bool = Option(
1833
        False,
1834
        "--prod",
1835
        help="Only instead production dependencies.",
1836
    ),
1837
    tool: str = ToolOption,
1838
    use_uv: bool = Option(False, "--uv", help="Use `uv` to install deps"),
1839
    use_pdm: bool = Option(False, "--pdm", help="Use `pdm` to install deps"),
1840
    use_pip: bool = Option(False, "--pip", help="Use `pip` to install deps"),
1841
    use_poetry: bool = Option(False, "--poetry", help="Use `poetry` to install deps"),
1842
    active: bool = Option(
1843
        False, help="Add `--active` to uv sync command(Only work for uv project)"
1844
    ),
1845
    inexact: bool = Option(
1846
        False, help="Add `--inexact` to uv sync command(Only work for uv project)"
1847
    ),
1848
    no_dev: bool = Option(False, "--no-dev"),
1849
    no_extra: Annotated[list[str] | None, Option()] = None,
1850
    no_group: Annotated[list[str] | None, Option()] = None,
1851
    frozen: bool = Option(False, "--frozen", "--frozen-lockfile", "--no-lock"),
1852
    verbose: bool = Option(False, "--verbose"),
1853
    dry: bool = DryOption,
1854
) -> None:
1855
    """Run: ruff check/format to reformat code and then mypy to check"""
UNCOV
1856
    if use_uv + use_pdm + use_pip + use_poetry > 1:
×
UNCOV
1857
        raise typer.BadParameter(
×
1858
            "can only choose one",
1859
            param_hint=("--uv", "--pdm", "--pip", "--poetry"),
1860
        )
UNCOV
1861
    if use_uv:
×
UNCOV
1862
        tool = "uv"
×
UNCOV
1863
    elif use_pdm:
×
UNCOV
1864
        tool = "pdm"
×
UNCOV
1865
    elif use_pip:
×
UNCOV
1866
        tool = "pip"
×
UNCOV
1867
    elif use_poetry:
×
UNCOV
1868
        tool = "poetry"
×
UNCOV
1869
    elif tool == ToolOption.default:
×
UNCOV
1870
        tool = Project.get_manage_tool(cache=True) or "pip"
×
UNCOV
1871
    bool_opts = {
×
1872
        "active": active,
1873
        "inexact": inexact,
1874
        "no_dev": no_dev,
1875
        "verbose": verbose,
1876
        "frozen": frozen,
1877
        "dry": dry,
1878
    }
UNCOV
1879
    MakeDeps(tool, prod, no_extra=no_extra, no_group=no_group, **bool_opts).run()
×
1880

1881

1882
class UvPypi(DryRun):
5✔
1883
    PYPI = "https://pypi.org/simple"
5✔
1884
    HOST = "https://files.pythonhosted.org"
5✔
1885

1886
    def __init__(
5✔
1887
        self,
1888
        lock_file: Path,
1889
        dry: bool,
1890
        verbose: bool,
1891
        quiet: bool,
1892
        slim: bool = False,
1893
        reverse: bool = False,
1894
    ) -> None:
1895
        super().__init__(dry=dry)
5✔
1896
        self.lock_file = lock_file
5✔
1897
        self._verbose = _ensure_bool(verbose)
5✔
1898
        self._quiet = _ensure_bool(quiet)
5✔
1899
        self._slim = _ensure_bool(slim)
5✔
1900
        self._reverse = _ensure_bool(reverse)
5✔
1901

1902
    def run(self) -> None:
5✔
1903
        try:
5✔
1904
            rc = self.update_lock(
5✔
1905
                self.lock_file, self._verbose, self._quiet, self._slim, self._reverse
1906
            )
UNCOV
1907
        except ValueError as e:
×
UNCOV
1908
            secho(str(e), fg=typer.colors.RED)
×
UNCOV
1909
            raise Exit(1) from e
×
1910
        else:
1911
            if rc != 0:
5✔
1912
                raise Exit(rc)
5✔
1913

1914
    @staticmethod
5✔
1915
    def get_target_content(
5✔
1916
        text: str, verbose: bool, target_registry, target_host: str
1917
    ) -> str | None:
1918
        registry_pattern = r'(registry = ")(.*?)"'
5✔
1919
        registry_urls = {i[1] for i in re.findall(registry_pattern, text)}
5✔
1920
        download_pattern = r'(url = ")(https?://.*?)(/packages/.*?\.)(gz|whl|zip)"'
5✔
1921
        download_hosts = {i[1] for i in re.findall(download_pattern, text)}
5✔
1922
        if not registry_urls:
5✔
1923
            raise ValueError(
×
1924
                f"Failed to find pattern {registry_pattern!r} in uv lock file"
1925
            )
1926

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

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

1933
        if len(registry_urls) == 1:
5✔
1934
            current_registry = registry_urls.pop()
5✔
1935
            if current_registry == target_registry:
5✔
1936
                if download_hosts == {target_host}:
5✔
1937
                    return None
5✔
1938
            else:
1939
                text = replace_registry(text)
5✔
1940
                if verbose:
5✔
1941
                    echo(f"{current_registry} --> {target_registry}")
5✔
1942
        else:
1943
            # TODO: ask each one to confirm replace
UNCOV
1944
            text = replace_registry(text)
×
UNCOV
1945
            if verbose:
×
UNCOV
1946
                for current_registry in sorted(registry_urls):
×
UNCOV
1947
                    echo(f"{current_registry} --> {target_registry}")
×
1948
        if len(download_hosts) == 1:
5✔
1949
            current_host = download_hosts.pop()
5✔
1950
            if current_host != target_host:
5✔
1951
                text = replace_host(text)
5✔
1952
                if verbose:
5✔
1953
                    echo(f"{current_host} --> {target_host}")
5✔
UNCOV
1954
        elif download_hosts:
×
1955
            # TODO: ask each one to confirm replace
UNCOV
1956
            text = replace_host(text)
×
UNCOV
1957
            if verbose:
×
UNCOV
1958
                for current_host in sorted(download_hosts):
×
UNCOV
1959
                    echo(f"{current_host} --> {target_host}")
×
1960
        return text
5✔
1961

1962
    @classmethod
5✔
1963
    def update_lock(
5✔
1964
        cls,
1965
        p: Path,
1966
        verbose: bool,
1967
        quiet: bool,
1968
        slim: bool = False,
1969
        reverse: bool = False,
1970
    ) -> int:
1971
        text = p.read_text("utf-8")
5✔
1972
        target_register, target_host = cls.PYPI, cls.HOST
5✔
1973
        if reverse:
5✔
1974
            try:
5✔
1975
                target_register, target_host = cls.get_register_from_uv_config()
5✔
1976
            except FileNotFoundError:
5✔
1977
                if verbose:
5✔
1978
                    echo("Skip register reverse as global uv config file not found.")
5✔
1979
                if quiet:
5✔
1980
                    return 0
5✔
UNCOV
1981
                return 1
×
1982
        new_text = cls.get_target_content(text, verbose, target_register, target_host)
5✔
1983
        if new_text is None:
5✔
1984
            if verbose:
5✔
1985
                echo(f"Registry of {p} is {target_register}, no need to change.")
5✔
1986
            return 0
5✔
1987
        return cls.slim_and_write(new_text, slim, p, verbose, quiet)
5✔
1988

1989
    @classmethod
5✔
1990
    def get_register_from_uv_config(cls) -> tuple[str, str]:
5✔
1991
        config_file = cls.get_uv_config_file()
5✔
1992
        text = config_file.read_text("utf-8")
5✔
1993
        doc = tomllib.loads(text)
5✔
1994
        index_url = doc["index"][0]["url"]
5✔
1995
        return index_url, index_url.replace("/simple", "").rstrip("/")
5✔
1996

1997
    @staticmethod
5✔
1998
    def get_uv_config_file() -> Path:
5✔
1999
        config_dir = "AppData/Roaming" if is_windows() else ".config"
5✔
2000
        return Path.home() / config_dir / "uv/uv.toml"
5✔
2001

2002
    @staticmethod
5✔
2003
    def slim_and_write(
5✔
2004
        text: str, slim: bool, p: Path, verbose: bool, quiet: bool
2005
    ) -> int:
2006
        if slim:
5✔
2007
            pattern = r', size = \d+, upload-time = ".*?"'
5✔
2008
            text = re.sub(pattern, "", text)
5✔
2009
        size = p.write_text(text, encoding="utf-8")
5✔
2010
        if verbose:
5✔
2011
            echo(f"Updated {p} with {size} bytes.")
5✔
2012
        if quiet:
5✔
2013
            return 0
5✔
2014
        return 1
5✔
2015

2016

2017
@cli.command()
5✔
2018
def pypi(
5✔
2019
    file: str | None = typer.Argument(default=None),
2020
    dry: bool = DryOption,
2021
    verbose: bool = False,
2022
    quiet: bool = False,
2023
    slim: bool = False,
2024
    reverse: bool = False,
2025
) -> None:
2026
    """Change registry of uv.lock to be pypi.org"""
2027
    if not (p := Path(_ensure_str(file) or "uv.lock")).exists() and not (
5✔
2028
        (p := Project.get_work_dir() / p.name).exists()
2029
    ):
2030
        yellow_warn(f"{p.name!r} not found!")
5✔
2031
        return
5✔
2032
    UvPypi(p, dry, verbose, quiet, slim, reverse).run()
5✔
2033

2034

2035
def version_callback(value: bool) -> None:
5✔
2036
    if value:
5✔
2037
        echo("Fast Dev Cli Version: " + typer.style(__version__, bold=True))
5✔
2038
        raise Exit()
5✔
2039

2040

2041
@cli.callback()
2042
def common(
2043
    version: bool = Option(
2044
        None,
2045
        "--version",
2046
        "-V",
2047
        callback=version_callback,
2048
        is_eager=True,
2049
        help="Show the version of this tool",
2050
    ),
2051
) -> None: ...
2052

2053

2054
def main() -> None:
5✔
2055
    cli()
5✔
2056

2057

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

© 2026 Coveralls, Inc