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

waketzheng / fast-dev-cli / 17172872241

23 Aug 2025 03:09AM UTC coverage: 92.94% (-1.6%) from 94.505%
17172872241

push

github

waketzheng
tests: remove unused pytest fixtures

803 of 864 relevant lines covered (92.94%)

5.57 hits per line

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

92.93
/fast_dev_cli/cli.py
1
from __future__ import annotations
6✔
2

3
import contextlib
6✔
4
import importlib.metadata as importlib_metadata
6✔
5
import os
6✔
6
import re
6✔
7
import shlex
6✔
8
import subprocess  # nosec:B404
6✔
9
import sys
6✔
10
from functools import cached_property
6✔
11
from pathlib import Path
6✔
12
from typing import (
6✔
13
    TYPE_CHECKING,
14
    Any,
15
    Literal,
16
    # Optional is required by Option generated by typer
17
    Optional,
18
    cast,
19
    get_args,
20
    overload,
21
)
22

23
import typer
6✔
24
from click import UsageError
6✔
25
from typer import Exit, Option, echo, secho
6✔
26
from typer.models import ArgumentInfo, OptionInfo
6✔
27

28
try:
6✔
29
    from . import __version__
6✔
30
except ImportError:  # pragma: no cover
31
    from importlib import import_module as _import  # For local unittest
32

33
    __version__ = _import(Path(__file__).parent.name).__version__
34

35
if sys.version_info >= (3, 11):  # pragma: no cover
36
    from enum import StrEnum
37

38
    import tomllib
39
else:  # pragma: no cover
40
    from enum import Enum
41

42
    import tomli as tomllib
43

44
    class StrEnum(str, Enum):
45
        __str__ = str.__str__
46

47

48
if TYPE_CHECKING:
49
    if sys.version_info >= (3, 11):
50
        from typing import Self
51
    else:
52
        from typing_extensions import Self
53

54
cli = typer.Typer(no_args_is_help=True)
6✔
55
DryOption = Option(False, "--dry", help="Only print, not really run shell command")
6✔
56
TOML_FILE = "pyproject.toml"
6✔
57
ToolName = Literal["poetry", "pdm", "uv"]
6✔
58
ToolOption = Option(
6✔
59
    "auto", "--tool", help="Explicit declare manage tool (default to auto detect)"
60
)
61

62

63
class FastDevCliError(Exception): ...
6✔
64

65

66
class ShellCommandError(FastDevCliError): ...
6✔
67

68

69
def poetry_module_name(name: str) -> str:
6✔
70
    """Get module name that generated by `poetry new`"""
71
    try:
6✔
72
        from packaging.utils import canonicalize_name
6✔
73
    except ImportError:
×
74

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

78
    return canonicalize_name(name).replace("-", "_").replace(" ", "_")
6✔
79

80

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

92

93
def yellow_warn(msg: str) -> None:
6✔
94
    secho(msg, fg="yellow")
6✔
95

96

97
def load_bool(name: str, default: bool = False) -> bool:
6✔
98
    if not (v := os.getenv(name)):
6✔
99
        return default
6✔
100
    if (lower := v.lower()) in ("0", "false", "f", "off", "no", "n"):
6✔
101
        return False
6✔
102
    elif lower in ("1", "true", "t", "on", "yes", "y"):
6✔
103
        return True
6✔
104
    secho(f"WARNING: can not convert value({v!r}) of {name} to bool!")
6✔
105
    return default
6✔
106

107

108
def is_venv() -> bool:
6✔
109
    """Whether in a virtual environment(also work for poetry)"""
110
    return hasattr(sys, "real_prefix") or (
6✔
111
        hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix
112
    )
113

114

115
def _run_shell(cmd: list[str] | str, **kw: Any) -> subprocess.CompletedProcess[str]:
6✔
116
    if isinstance(cmd, str):
6✔
117
        kw.setdefault("shell", True)
6✔
118
    return subprocess.run(cmd, **kw)  # nosec:B603
6✔
119

120

121
def run_and_echo(
6✔
122
    cmd: str, *, dry: bool = False, verbose: bool = True, **kw: Any
123
) -> int:
124
    """Run shell command with subprocess and print it"""
125
    if verbose:
6✔
126
        echo(f"--> {cmd}")
6✔
127
    if dry:
6✔
128
        return 0
6✔
129
    command: list[str] | str = cmd
6✔
130
    if "shell" not in kw and not (set(cmd) & {"|", ">", "&"}):
6✔
131
        command = shlex.split(cmd)
6✔
132
    return _run_shell(command, **kw).returncode
6✔
133

134

135
def check_call(cmd: str) -> bool:
6✔
136
    r = _run_shell(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
6✔
137
    return r.returncode == 0
6✔
138

139

140
def capture_cmd_output(
6✔
141
    command: list[str] | str, *, raises: bool = False, **kw: Any
142
) -> str:
143
    if isinstance(command, str) and not kw.get("shell"):
6✔
144
        command = shlex.split(command)
6✔
145
    r = _run_shell(command, capture_output=True, encoding="utf-8", **kw)
6✔
146
    if raises and r.returncode != 0:
6✔
147
        raise ShellCommandError(r.stderr)
6✔
148
    return r.stdout.strip() or r.stderr
6✔
149

150

151
def _parse_version(line: str, pattern: re.Pattern[str]) -> str:
6✔
152
    return pattern.sub("", line).split("#")[0].strip(" '\"")
6✔
153

154

155
def read_version_from_file(
6✔
156
    package_name: str, work_dir: Path | None = None, toml_text: str | None = None
157
) -> str:
158
    if not package_name and toml_text:
6✔
159
        pattern = re.compile(r"version\s*=")
6✔
160
        for line in toml_text.splitlines():
6✔
161
            if pattern.match(line):
6✔
162
                return _parse_version(line, pattern)
6✔
163
    version_file = BumpUp.parse_filename(toml_text, work_dir, package_name)
6✔
164
    if version_file == TOML_FILE:
6✔
165
        if toml_text is None:
6✔
166
            toml_text = Project.load_toml_text()
6✔
167
        context = tomllib.loads(toml_text)
6✔
168
        with contextlib.suppress(KeyError):
6✔
169
            return cast(str, context["project"]["version"])
6✔
170
        with contextlib.suppress(KeyError):  # Poetry V1
6✔
171
            return cast(str, context["tool"]["poetry"]["version"])
6✔
172
        secho(f"WARNING: can not find 'version' item in {version_file}!")
6✔
173
        return "0.0.0"
6✔
174
    pattern = re.compile(r"__version__\s*=")
6✔
175
    for line in Path(version_file).read_text("utf-8").splitlines():
6✔
176
        if pattern.match(line):
6✔
177
            return _parse_version(line, pattern)
6✔
178
    # TODO: remove or refactor the following lines.
179
    if work_dir is None:
×
180
        work_dir = Project.get_work_dir()
×
181
    package_dir = work_dir / package_name
×
182
    if (
×
183
        not (init_file := package_dir / "__init__.py").exists()
184
        and not (init_file := work_dir / "src" / package_name / init_file.name).exists()
185
        and not (init_file := work_dir / "app" / init_file.name).exists()
186
    ):
187
        secho("WARNING: __init__.py file does not exist!")
×
188
        return "0.0.0"
×
189

190
    pattern = re.compile(r"__version__\s*=")
×
191
    for line in init_file.read_text("utf-8").splitlines():
×
192
        if pattern.match(line):
×
193
            return _parse_version(line, pattern)
×
194
    secho(f"WARNING: can not find '__version__' var in {init_file}!")
×
195
    return "0.0.0"
×
196

197

198
@overload
199
def get_current_version(
200
    verbose: bool = False,
201
    is_poetry: bool | None = None,
202
    package_name: str | None = None,
203
    *,
204
    check_version: Literal[False] = False,
205
) -> str: ...
206

207

208
@overload
209
def get_current_version(
210
    verbose: bool = False,
211
    is_poetry: bool | None = None,
212
    package_name: str | None = None,
213
    *,
214
    check_version: Literal[True] = True,
215
) -> tuple[bool, str]: ...
216

217

218
def get_current_version(
6✔
219
    verbose: bool = False,
220
    is_poetry: bool | None = None,
221
    package_name: str | None = None,
222
    *,
223
    check_version: bool = False,
224
) -> str | tuple[bool, str]:
225
    if is_poetry is True or Project.manage_by_poetry():
6✔
226
        cmd = ["poetry", "version", "-s"]
6✔
227
        if verbose:
6✔
228
            echo(f"--> {' '.join(cmd)}")
6✔
229
        if out := capture_cmd_output(cmd, raises=True):
6✔
230
            out = out.splitlines()[-1].strip().split()[-1]
6✔
231
        if check_version:
6✔
232
            return True, out
6✔
233
        return out
6✔
234
    toml_text = work_dir = None
6✔
235
    if package_name is None:
6✔
236
        work_dir = Project.get_work_dir()
6✔
237
        toml_text = Project.load_toml_text()
6✔
238
        doc = tomllib.loads(toml_text)
6✔
239
        project_name = doc.get("project", {}).get("name", work_dir.name)
6✔
240
        package_name = re.sub(r"[- ]", "_", project_name)
6✔
241
    local_version = read_version_from_file(package_name, work_dir, toml_text)
6✔
242
    try:
6✔
243
        installed_version = importlib_metadata.version(package_name)
6✔
244
    except importlib_metadata.PackageNotFoundError:
6✔
245
        installed_version = ""
6✔
246
    current_version = local_version or installed_version
6✔
247
    if not current_version:
6✔
248
        raise FastDevCliError(f"Failed to get current version of {package_name!r}")
×
249
    if check_version:
6✔
250
        is_conflict = bool(local_version) and local_version != installed_version
6✔
251
        return is_conflict, current_version
6✔
252
    return current_version
6✔
253

254

255
def _ensure_bool(value: bool | OptionInfo) -> bool:
6✔
256
    if not isinstance(value, bool):
6✔
257
        value = getattr(value, "default", False)
6✔
258
    return value
6✔
259

260

261
def _ensure_str(value: str | OptionInfo) -> str:
6✔
262
    if not isinstance(value, str):
6✔
263
        value = getattr(value, "default", "")
6✔
264
    return value
6✔
265

266

267
def exit_if_run_failed(
6✔
268
    cmd: str,
269
    env: dict[str, str] | None = None,
270
    _exit: bool = False,
271
    dry: bool = False,
272
    **kw: Any,
273
) -> subprocess.CompletedProcess[str]:
274
    run_and_echo(cmd, dry=True)
6✔
275
    if _ensure_bool(dry):
6✔
276
        return subprocess.CompletedProcess("", 0)
6✔
277
    if env is not None:
6✔
278
        env = {**os.environ, **env}
6✔
279
    r = _run_shell(cmd, env=env, **kw)
6✔
280
    if rc := r.returncode:
6✔
281
        if _exit:
6✔
282
            sys.exit(rc)
6✔
283
        raise Exit(rc)
6✔
284
    return r
6✔
285

286

287
class DryRun:
6✔
288
    def __init__(self, _exit: bool = False, dry: bool = False) -> None:
6✔
289
        self.dry = dry
6✔
290
        self._exit = _exit
6✔
291

292
    def gen(self) -> str:
6✔
293
        raise NotImplementedError
6✔
294

295
    def run(self) -> None:
6✔
296
        exit_if_run_failed(self.gen(), _exit=self._exit, dry=self.dry)
6✔
297

298

299
class BumpUp(DryRun):
6✔
300
    class PartChoices(StrEnum):
6✔
301
        patch = "patch"
6✔
302
        minor = "minor"
6✔
303
        major = "major"
6✔
304

305
    def __init__(
6✔
306
        self,
307
        commit: bool,
308
        part: str,
309
        filename: str | None = None,
310
        dry: bool = False,
311
        no_sync: bool = False,
312
        emoji: bool | None = None,
313
    ) -> None:
314
        self.commit = commit
6✔
315
        self.part = part
6✔
316
        if filename is None:
6✔
317
            filename = self.parse_filename()
6✔
318
        self.filename = filename
6✔
319
        self._no_sync = no_sync
6✔
320
        self._emoji = emoji
6✔
321
        super().__init__(dry=dry)
6✔
322

323
    @staticmethod
6✔
324
    def get_last_commit_message(raises: bool = False) -> str:
6✔
325
        cmd = 'git show --pretty=format:"%s" -s HEAD'
6✔
326
        return capture_cmd_output(cmd, raises=raises)
6✔
327

328
    @classmethod
6✔
329
    def should_add_emoji(cls) -> bool:
6✔
330
        """
331
        If last commit message is startswith emoji,
332
        add a ⬆️ flag at the prefix of bump up commit message.
333
        """
334
        try:
6✔
335
            first_char = cls.get_last_commit_message(raises=True)[0]
6✔
336
        except (IndexError, ShellCommandError):
6✔
337
            return False
6✔
338
        else:
339
            return is_emoji(first_char)
6✔
340

341
    @staticmethod
6✔
342
    def parse_filename(
6✔
343
        toml_text: str | None = None,
344
        work_dir: Path | None = None,
345
        package_name: str | None = None,
346
    ) -> str:
347
        if toml_text is None:
6✔
348
            toml_text = Project.load_toml_text()
6✔
349
        context = tomllib.loads(toml_text)
6✔
350
        by_version_plugin = False
6✔
351
        try:
6✔
352
            ver = context["project"]["version"]
6✔
353
        except KeyError:
6✔
354
            pass
6✔
355
        else:
356
            if isinstance(ver, str):
6✔
357
                if ver in ("0", "0.0.0"):
6✔
358
                    by_version_plugin = True
6✔
359
                elif re.match(r"\d+\.\d+\.\d+", ver):
6✔
360
                    return TOML_FILE
6✔
361
        if not by_version_plugin:
6✔
362
            try:
6✔
363
                version_value = context["tool"]["poetry"]["version"]
6✔
364
            except KeyError:
6✔
365
                if not Project.manage_by_poetry():
6✔
366
                    if work_dir is None:
6✔
367
                        work_dir = Project.get_work_dir()
6✔
368
                    for tool in ("pdm", "hatch"):
6✔
369
                        with contextlib.suppress(KeyError):
6✔
370
                            version_path = cast(
6✔
371
                                str, context["tool"][tool]["version"]["path"]
372
                            )
373
                            if (
6✔
374
                                Path(version_path).exists()
375
                                or work_dir.joinpath(version_path).exists()
376
                            ):
377
                                return version_path
6✔
378
                    # version = { source = "file", path = "fast_dev_cli/__init__.py" }
379
                    v_key = "version = "
6✔
380
                    p_key = 'path = "'
6✔
381
                    for line in toml_text.splitlines():
6✔
382
                        if not line.startswith(v_key):
×
383
                            continue
×
384
                        if p_key in (value := line.split(v_key, 1)[-1].split("#")[0]):
×
385
                            filename = value.split(p_key, 1)[-1].split('"')[0]
×
386
                            if work_dir.joinpath(filename).exists():
×
387
                                return filename
×
388
            else:
389
                by_version_plugin = version_value in ("0", "0.0.0", "init")
6✔
390
        if by_version_plugin:
6✔
391
            try:
6✔
392
                package_item = context["tool"]["poetry"]["packages"]
6✔
393
            except KeyError:
6✔
394
                try:
6✔
395
                    project_name = context["project"]["name"]
6✔
396
                except KeyError:
6✔
397
                    packages = []
6✔
398
                else:
399
                    packages = [(poetry_module_name(project_name), "")]
×
400
            else:
401
                packages = [
6✔
402
                    (j, i.get("from", ""))
403
                    for i in package_item
404
                    if (j := i.get("include"))
405
                ]
406
            # In case of managed by `poetry-plugin-version`
407
            cwd = Path.cwd()
6✔
408
            pattern = re.compile(r"__version__\s*=\s*['\"]")
6✔
409
            ds: list[Path] = []
6✔
410
            if package_name is not None:
6✔
411
                packages.insert(0, (package_name, ""))
×
412
            for package_name, source_dir in packages:
6✔
413
                ds.append(cwd / package_name)
6✔
414
                ds.append(cwd / "src" / package_name)
6✔
415
                if source_dir and source_dir != "src":
6✔
416
                    ds.append(cwd / source_dir / package_name)
6✔
417
            module_name = poetry_module_name(cwd.name)
6✔
418
            ds.extend([cwd / module_name, cwd / "src" / module_name, cwd])
6✔
419
            for d in ds:
6✔
420
                init_file = d / "__init__.py"
6✔
421
                if (
6✔
422
                    init_file.exists() and pattern.search(init_file.read_text("utf8"))
423
                ) or (
424
                    (init_file := init_file.with_name("__version__.py")).exists()
425
                    and pattern.search(init_file.read_text("utf8"))
426
                ):
427
                    break
6✔
428
            else:
429
                raise ParseError("Version file not found! Where are you now?")
6✔
430
            return os.path.relpath(init_file, cwd)
6✔
431

432
        return TOML_FILE
6✔
433

434
    def get_part(self, s: str) -> str:
6✔
435
        choices: dict[str, str] = {}
6✔
436
        for i, p in enumerate(self.PartChoices, 1):
6✔
437
            v = str(p)
6✔
438
            choices.update({str(i): v, v: v})
6✔
439
        try:
6✔
440
            return choices[s]
6✔
441
        except KeyError as e:
6✔
442
            echo(f"Invalid part: {s!r}")
6✔
443
            raise Exit(1) from e
6✔
444

445
    def gen(self) -> str:
6✔
446
        should_sync, _version = get_current_version(check_version=True)
6✔
447
        filename = self.filename
6✔
448
        echo(f"Current version(@{filename}): {_version}")
6✔
449
        if self.part:
6✔
450
            part = self.get_part(self.part)
6✔
451
        else:
452
            part = "patch"
6✔
453
            if a := input("Which one?").strip():
6✔
454
                part = self.get_part(a)
6✔
455
        self.part = part
6✔
456
        parse = r'--parse "(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)"'
6✔
457
        cmd = f'bumpversion {parse} --current-version="{_version}" {part} {filename}'
6✔
458
        if self.commit:
6✔
459
            if part != "patch":
6✔
460
                cmd += " --tag"
6✔
461
            cmd += " --commit"
6✔
462
            if self._emoji or (self._emoji is None and self.should_add_emoji()):
6✔
463
                cmd += " --message-emoji=1"
6✔
464
            if not load_bool("DONT_GIT_PUSH"):
6✔
465
                cmd += " && git push && git push --tags && git log -1"
6✔
466
        else:
467
            cmd += " --allow-dirty"
6✔
468
        if should_sync and not self._no_sync and (sync := Project.get_sync_command()):
6✔
469
            cmd = f"{sync} && " + cmd
6✔
470
        return cmd
6✔
471

472
    def run(self) -> None:
6✔
473
        super().run()
6✔
474
        if not self.commit and not self.dry:
6✔
475
            new_version = get_current_version(True)
6✔
476
            echo(new_version)
6✔
477
            if self.part != "patch":
6✔
478
                echo("You may want to pin tag by `fast tag`")
6✔
479

480

481
@cli.command()
6✔
482
def version() -> None:
6✔
483
    """Show the version of this tool"""
484
    echo("Fast Dev Cli Version: " + typer.style(__version__, fg=typer.colors.BLUE))
6✔
485
    with contextlib.suppress(FileNotFoundError, KeyError):
6✔
486
        toml_text = Project.load_toml_text()
6✔
487
        doc = tomllib.loads(toml_text)
6✔
488
        version_file = doc["tool"]["pdm"]["version"]["path"]
6✔
489
        text = Project.get_work_dir().joinpath(version_file).read_text()
6✔
490
        varname = "__version__"
6✔
491
        for line in text.splitlines():
6✔
492
            if line.strip().startswith(varname):
6✔
493
                value = line.split("=", 1)[-1].strip().strip('"').strip("'")
6✔
494
                styled = typer.style(value, bold=True)
6✔
495
                echo(f"Version value in {version_file}: " + styled)
6✔
496
                break
6✔
497

498

499
@cli.command(name="bump")
6✔
500
def bump_version(
6✔
501
    part: BumpUp.PartChoices,
502
    commit: bool = Option(
503
        False, "--commit", "-c", help="Whether run `git commit` after version changed"
504
    ),
505
    emoji: Optional[bool] = Option(
506
        None, "--emoji", help="Whether add emoji prefix to commit message"
507
    ),
508
    no_sync: bool = Option(
509
        False, "--no-sync", help="Do not run sync command to update version"
510
    ),
511
    dry: bool = DryOption,
512
) -> None:
513
    """Bump up version string in pyproject.toml"""
514
    if emoji is not None:
6✔
515
        emoji = _ensure_bool(emoji)
6✔
516
    return BumpUp(
6✔
517
        _ensure_bool(commit),
518
        getattr(part, "value", part),
519
        no_sync=_ensure_bool(no_sync),
520
        emoji=emoji,
521
        dry=dry,
522
    ).run()
523

524

525
def bump() -> None:
6✔
526
    part, commit = "", False
6✔
527
    if args := sys.argv[2:]:
6✔
528
        if "-c" in args or "--commit" in args:
6✔
529
            commit = True
6✔
530
        for a in args:
6✔
531
            if not a.startswith("-"):
6✔
532
                part = a
6✔
533
                break
6✔
534
    return BumpUp(commit, part, no_sync="--no-sync" in args, dry="--dry" in args).run()
6✔
535

536

537
class EnvError(Exception):
6✔
538
    """Raise when expected to be managed by poetry, but toml file not found."""
539

540

541
class Project:
6✔
542
    path_depth = 5
6✔
543
    _tool: ToolName | None = None
6✔
544

545
    @staticmethod
6✔
546
    def is_poetry_v2(text: str) -> bool:
6✔
547
        return 'build-backend = "poetry' in text
6✔
548

549
    @staticmethod
6✔
550
    def work_dir(
6✔
551
        name: str, parent: Path, depth: int, be_file: bool = False
552
    ) -> Path | None:
553
        for _ in range(depth):
6✔
554
            if (f := parent.joinpath(name)).exists():
6✔
555
                if be_file:
6✔
556
                    return f
6✔
557
                return parent
6✔
558
            parent = parent.parent
6✔
559
        return None
6✔
560

561
    @classmethod
6✔
562
    def get_work_dir(
6✔
563
        cls: type[Self],
564
        name: str = TOML_FILE,
565
        cwd: Path | None = None,
566
        allow_cwd: bool = False,
567
        be_file: bool = False,
568
    ) -> Path:
569
        cwd = cwd or Path.cwd()
6✔
570
        if d := cls.work_dir(name, cwd, cls.path_depth, be_file):
6✔
571
            return d
6✔
572
        if allow_cwd:
6✔
573
            return cls.get_root_dir(cwd)
6✔
574
        raise EnvError(f"{name} not found! Make sure this is a python project.")
6✔
575

576
    @classmethod
6✔
577
    def load_toml_text(cls: type[Self], name: str = TOML_FILE) -> str:
6✔
578
        toml_file = cls.get_work_dir(name, be_file=True)
6✔
579
        return toml_file.read_text("utf8")
6✔
580

581
    @classmethod
6✔
582
    def manage_by_poetry(cls: type[Self], cache: bool = False) -> bool:
6✔
583
        return cls.get_manage_tool(cache=cache) == "poetry"
6✔
584

585
    @classmethod
6✔
586
    def get_manage_tool(cls: type[Self], cache: bool = False) -> ToolName | None:
6✔
587
        if cache and cls._tool:
6✔
588
            return cls._tool
6✔
589
        try:
6✔
590
            text = cls.load_toml_text()
6✔
591
        except EnvError:
6✔
592
            pass
6✔
593
        else:
594
            with contextlib.suppress(KeyError, tomllib.TOMLDecodeError):
6✔
595
                doc = tomllib.loads(text)
6✔
596
                backend = doc["build-system"]["build-backend"]
6✔
597
                if "poetry" in backend:
6✔
598
                    cls._tool = "poetry"
6✔
599
                    return cls._tool
6✔
600
                elif "pdm" in backend:
6✔
601
                    cls._tool = "pdm"
6✔
602
                    work_dir = cls.get_work_dir(allow_cwd=True)
6✔
603
                    if not Path(work_dir, "pdm.lock").exists() and (
6✔
604
                        "[tool.uv]" in text or Path(work_dir, "uv.lock").exists()
605
                    ):
606
                        cls._tool = "uv"
×
607
                    return cls._tool
6✔
608
            for name in get_args(ToolName):
6✔
609
                if f"[tool.{name}]" in text:
6✔
610
                    cls._tool = cast(ToolName, name)
6✔
611
                    return cls._tool
6✔
612
            # Poetry 2.0 default to not include the '[tool.poetry]' section
613
            if cls.is_poetry_v2(text):
6✔
614
                cls._tool = "poetry"
×
615
                return cls._tool
×
616
        return None
6✔
617

618
    @staticmethod
6✔
619
    def python_exec_dir() -> Path:
6✔
620
        return Path(sys.executable).parent
6✔
621

622
    @classmethod
6✔
623
    def get_root_dir(cls: type[Self], cwd: Path | None = None) -> Path:
6✔
624
        root = cwd or Path.cwd()
6✔
625
        venv_parent = cls.python_exec_dir().parent.parent
6✔
626
        if root.is_relative_to(venv_parent):
6✔
627
            root = venv_parent
6✔
628
        return root
6✔
629

630
    @classmethod
6✔
631
    def is_pdm_project(cls, strict: bool = True, cache: bool = False) -> bool:
6✔
632
        if cls.get_manage_tool(cache=cache) != "pdm":
6✔
633
            return False
6✔
634
        if strict:
×
635
            lock_file = cls.get_work_dir() / "pdm.lock"
×
636
            return lock_file.exists()
×
637
        return True
×
638

639
    @classmethod
6✔
640
    def get_sync_command(cls, prod: bool = True, doc: dict | None = None) -> str:
6✔
641
        if cls.is_pdm_project():
6✔
642
            return "pdm sync" + " --prod" * prod
×
643
        elif cls.manage_by_poetry(cache=True):
6✔
644
            cmd = "poetry install"
6✔
645
            if prod:
6✔
646
                if doc is None:
6✔
647
                    doc = tomllib.loads(cls.load_toml_text())
6✔
648
                if doc.get("project", {}).get("dependencies") or any(
6✔
649
                    i != "python"
650
                    for i in doc.get("tool", {})
651
                    .get("poetry", {})
652
                    .get("dependencies", [])
653
                ):
654
                    cmd += " --only=main"
×
655
            return cmd
6✔
656
        elif cls.get_manage_tool(cache=True) == "uv":
×
657
            return "uv sync --inexact" + " --no-dev" * prod
×
658
        return ""
×
659

660
    @classmethod
6✔
661
    def sync_dependencies(cls, prod: bool = True) -> None:
6✔
662
        if cmd := cls.get_sync_command():
×
663
            run_and_echo(cmd)
×
664

665

666
class ParseError(Exception):
6✔
667
    """Raise this if parse dependence line error"""
668

669
    pass
6✔
670

671

672
class UpgradeDependencies(Project, DryRun):
6✔
673
    def __init__(
6✔
674
        self, _exit: bool = False, dry: bool = False, tool: ToolName = "poetry"
675
    ) -> None:
676
        super().__init__(_exit, dry)
6✔
677
        self._tool = tool
6✔
678

679
    class DevFlag(StrEnum):
6✔
680
        new = "[tool.poetry.group.dev.dependencies]"
6✔
681
        old = "[tool.poetry.dev-dependencies]"
6✔
682

683
    @staticmethod
6✔
684
    def parse_value(version_info: str, key: str) -> str:
6✔
685
        """Pick out the value for key in version info.
686

687
        Example::
688
            >>> s= 'typer = {extras = ["all"], version = "^0.9.0", optional = true}'
689
            >>> UpgradeDependencies.parse_value(s, 'extras')
690
            'all'
691
            >>> UpgradeDependencies.parse_value(s, 'optional')
692
            'true'
693
            >>> UpgradeDependencies.parse_value(s, 'version')
694
            '^0.9.0'
695
        """
696
        sep = key + " = "
6✔
697
        rest = version_info.split(sep, 1)[-1].strip(" =")
6✔
698
        if rest.startswith("["):
6✔
699
            rest = rest[1:].split("]")[0]
6✔
700
        elif rest.startswith('"'):
6✔
701
            rest = rest[1:].split('"')[0]
6✔
702
        else:
703
            rest = rest.split(",")[0].split("}")[0]
6✔
704
        return rest.strip().replace('"', "")
6✔
705

706
    @staticmethod
6✔
707
    def no_need_upgrade(version_info: str, line: str) -> bool:
6✔
708
        if (v := version_info.replace(" ", "")).startswith("{url="):
6✔
709
            echo(f"No need to upgrade for: {line}")
6✔
710
            return True
6✔
711
        if (f := "version=") in v:
6✔
712
            v = v.split(f)[1].strip('"').split('"')[0]
6✔
713
        if v == "*":
6✔
714
            echo(f"Skip wildcard line: {line}")
6✔
715
            return True
6✔
716
        elif v == "[":
6✔
717
            echo(f"Skip complex dependence: {line}")
6✔
718
            return True
6✔
719
        elif v.startswith(">") or v.startswith("<") or v[0].isdigit():
6✔
720
            echo(f"Ignore bigger/smaller/equal: {line}")
6✔
721
            return True
6✔
722
        return False
6✔
723

724
    @classmethod
6✔
725
    def build_args(
6✔
726
        cls: type[Self], package_lines: list[str]
727
    ) -> tuple[list[str], dict[str, list[str]]]:
728
        args: list[str] = []  # ['typer[all]', 'fastapi']
6✔
729
        specials: dict[str, list[str]] = {}  # {'--platform linux': ['gunicorn']}
6✔
730
        for no, line in enumerate(package_lines, 1):
6✔
731
            if (
6✔
732
                not (m := line.strip())
733
                or m.startswith("#")
734
                or m == "]"
735
                or (m.startswith("{") and m.strip(",").endswith("}"))
736
            ):
737
                continue
6✔
738
            try:
6✔
739
                package, version_info = m.split("=", 1)
6✔
740
            except ValueError as e:
6✔
741
                raise ParseError(f"Failed to separate by '='@line {no}: {m}") from e
6✔
742
            if (package := package.strip()).lower() == "python":
6✔
743
                continue
6✔
744
            if cls.no_need_upgrade(version_info := version_info.strip(' "'), line):
6✔
745
                continue
6✔
746
            if (extras_tip := "extras") in version_info:
6✔
747
                package += "[" + cls.parse_value(version_info, extras_tip) + "]"
6✔
748
            item = f'"{package}@latest"'
6✔
749
            key = None
6✔
750
            if (pf := "platform") in version_info:
6✔
751
                platform = cls.parse_value(version_info, pf)
6✔
752
                key = f"--{pf}={platform}"
6✔
753
            if (sc := "source") in version_info:
6✔
754
                source = cls.parse_value(version_info, sc)
6✔
755
                key = ("" if key is None else (key + " ")) + f"--{sc}={source}"
6✔
756
            if "optional = true" in version_info:
6✔
757
                key = ("" if key is None else (key + " ")) + "--optional"
6✔
758
            if key is not None:
6✔
759
                specials[key] = specials.get(key, []) + [item]
6✔
760
            else:
761
                args.append(item)
6✔
762
        return args, specials
6✔
763

764
    @classmethod
6✔
765
    def should_with_dev(cls: type[Self]) -> bool:
6✔
766
        text = cls.load_toml_text()
6✔
767
        return cls.DevFlag.new in text or cls.DevFlag.old in text
6✔
768

769
    @staticmethod
6✔
770
    def parse_item(toml_str: str) -> list[str]:
6✔
771
        lines: list[str] = []
6✔
772
        for line in toml_str.splitlines():
6✔
773
            if (line := line.strip()).startswith("["):
6✔
774
                if lines:
6✔
775
                    break
6✔
776
            elif line:
6✔
777
                lines.append(line)
6✔
778
        return lines
6✔
779

780
    @classmethod
6✔
781
    def get_args(
6✔
782
        cls: type[Self], toml_text: str | None = None
783
    ) -> tuple[list[str], list[str], list[list[str]], str]:
784
        if toml_text is None:
6✔
785
            toml_text = cls.load_toml_text()
6✔
786
        main_title = "[tool.poetry.dependencies]"
6✔
787
        if (no_main_deps := main_title not in toml_text) and not cls.is_poetry_v2(
6✔
788
            toml_text
789
        ):
790
            raise EnvError(
6✔
791
                f"{main_title} not found! Make sure this is a poetry project."
792
            )
793
        text = toml_text.split(main_title)[-1]
6✔
794
        dev_flag = "--group dev"
6✔
795
        new_flag, old_flag = cls.DevFlag.new, cls.DevFlag.old
6✔
796
        if (dev_title := getattr(new_flag, "value", new_flag)) not in text:
6✔
797
            dev_title = getattr(old_flag, "value", old_flag)  # For poetry<=1.2
6✔
798
            dev_flag = "--dev"
6✔
799
        others: list[list[str]] = []
6✔
800
        try:
6✔
801
            main_toml, dev_toml = text.split(dev_title)
6✔
802
        except ValueError:
6✔
803
            dev_toml = ""
6✔
804
            main_toml = text
6✔
805
        mains = [] if no_main_deps else cls.parse_item(main_toml)
6✔
806
        devs = cls.parse_item(dev_toml)
6✔
807
        prod_packs, specials = cls.build_args(mains)
6✔
808
        if specials:
6✔
809
            others.extend([[k] + v for k, v in specials.items()])
6✔
810
        dev_packs, specials = cls.build_args(devs)
6✔
811
        if specials:
6✔
812
            others.extend([[k] + v + [dev_flag] for k, v in specials.items()])
6✔
813
        return prod_packs, dev_packs, others, dev_flag
6✔
814

815
    @classmethod
6✔
816
    def gen_cmd(cls: type[Self]) -> str:
6✔
817
        main_args, dev_args, others, dev_flags = cls.get_args()
6✔
818
        return cls.to_cmd(main_args, dev_args, others, dev_flags)
6✔
819

820
    @staticmethod
6✔
821
    def to_cmd(
6✔
822
        main_args: list[str],
823
        dev_args: list[str],
824
        others: list[list[str]],
825
        dev_flags: str,
826
    ) -> str:
827
        command = "poetry add "
6✔
828
        _upgrade = ""
6✔
829
        if main_args:
6✔
830
            _upgrade = command + " ".join(main_args)
6✔
831
        if dev_args:
6✔
832
            if _upgrade:
6✔
833
                _upgrade += " && "
6✔
834
            _upgrade += command + dev_flags + " " + " ".join(dev_args)
6✔
835
        for single in others:
6✔
836
            _upgrade += f" && poetry add {' '.join(single)}"
6✔
837
        return _upgrade
6✔
838

839
    def gen(self) -> str:
6✔
840
        if self._tool == "uv":
6✔
841
            up = "uv lock --upgrade --verbose"
6✔
842
            deps = "uv sync --inexact --frozen --all-groups --all-extras"
6✔
843
            return f"{up} && {deps}"
6✔
844
        elif self._tool == "pdm":
6✔
845
            return "pdm update --verbose && pdm sync -G :all --frozen"
6✔
846
        return self.gen_cmd() + " && poetry lock && poetry update"
6✔
847

848

849
@cli.command()
6✔
850
def upgrade(
6✔
851
    tool: str = ToolOption,
852
    dry: bool = DryOption,
853
) -> None:
854
    """Upgrade dependencies in pyproject.toml to latest versions"""
855
    if not (tool := _ensure_str(tool)) or tool == ToolOption.default:
6✔
856
        tool = Project.get_manage_tool() or "uv"
6✔
857
    if tool in get_args(ToolName):
6✔
858
        UpgradeDependencies(dry=dry, tool=cast(ToolName, tool)).run()
6✔
859
    else:
860
        secho(f"Unknown tool {tool!r}", fg=typer.colors.YELLOW)
6✔
861
        raise typer.Exit(1)
6✔
862

863

864
class GitTag(DryRun):
6✔
865
    def __init__(self, message: str, dry: bool, no_sync: bool = False) -> None:
6✔
866
        self.message = message
6✔
867
        self._no_sync = no_sync
6✔
868
        super().__init__(dry=dry)
6✔
869

870
    @staticmethod
6✔
871
    def has_v_prefix() -> bool:
6✔
872
        return "v" in capture_cmd_output("git tag")
6✔
873

874
    def should_push(self) -> bool:
6✔
875
        return "git push" in self.git_status
6✔
876

877
    def gen(self) -> str:
6✔
878
        should_sync, _version = get_current_version(verbose=False, check_version=True)
6✔
879
        if self.has_v_prefix():
6✔
880
            # Add `v` at prefix to compare with bumpversion tool
881
            _version = "v" + _version
6✔
882
        cmd = f"git tag -a {_version} -m {self.message!r} && git push --tags"
6✔
883
        if self.should_push():
6✔
884
            cmd += " && git push"
6✔
885
        if should_sync and not self._no_sync and (sync := Project.get_sync_command()):
6✔
886
            cmd = f"{sync} && " + cmd
×
887
        return cmd
6✔
888

889
    @cached_property
6✔
890
    def git_status(self) -> str:
6✔
891
        return capture_cmd_output("git status")
6✔
892

893
    def mark_tag(self) -> bool:
6✔
894
        if not re.search(r"working (tree|directory) clean", self.git_status) and (
6✔
895
            "无文件要提交,干净的工作区" not in self.git_status
896
        ):
897
            run_and_echo("git status")
6✔
898
            echo("ERROR: Please run git commit to make sure working tree is clean!")
6✔
899
            return False
6✔
900
        return bool(super().run())
6✔
901

902
    def run(self) -> None:
6✔
903
        if self.mark_tag() and not self.dry:
6✔
904
            echo("You may want to publish package:\n poetry publish --build")
6✔
905

906

907
@cli.command()
6✔
908
def tag(
6✔
909
    message: str = Option("", "-m", "--message"),
910
    no_sync: bool = Option(
911
        False, "--no-sync", help="Do not run sync command to update version"
912
    ),
913
    dry: bool = DryOption,
914
) -> None:
915
    """Run shell command: git tag -a <current-version-in-pyproject.toml> -m {message}"""
916
    GitTag(message, dry=dry, no_sync=_ensure_bool(no_sync)).run()
6✔
917

918

919
class LintCode(DryRun):
6✔
920
    def __init__(
6✔
921
        self,
922
        args: list[str] | str | None,
923
        check_only: bool = False,
924
        _exit: bool = False,
925
        dry: bool = False,
926
        bandit: bool = False,
927
        skip_mypy: bool = False,
928
        dmypy: bool = False,
929
        tool: str = ToolOption.default,
930
        prefix: bool = False,
931
    ) -> None:
932
        self.args = args
6✔
933
        self.check_only = check_only
6✔
934
        self._bandit = bandit
6✔
935
        self._skip_mypy = skip_mypy
6✔
936
        self._use_dmypy = dmypy
6✔
937
        self._tool = tool
6✔
938
        self._prefix = prefix
6✔
939
        super().__init__(_exit, dry)
6✔
940

941
    @staticmethod
6✔
942
    def check_lint_tool_installed() -> bool:
6✔
943
        return check_call("ruff --version")
6✔
944

945
    @staticmethod
6✔
946
    def prefer_dmypy(paths: str, tools: list[str], use_dmypy: bool = False) -> bool:
6✔
947
        return (
6✔
948
            paths == "."
949
            and any(t.startswith("mypy") for t in tools)
950
            and (use_dmypy or load_bool("FASTDEVCLI_DMYPY"))
951
        )
952

953
    @staticmethod
6✔
954
    def get_package_name() -> str:
6✔
955
        root = Project.get_work_dir(allow_cwd=True)
6✔
956
        module_name = root.name.replace("-", "_").replace(" ", "_")
6✔
957
        package_maybe = (module_name, "src")
6✔
958
        for name in package_maybe:
6✔
959
            if root.joinpath(name).is_dir():
6✔
960
                return name
6✔
961
        return "."
6✔
962

963
    @classmethod
6✔
964
    def to_cmd(
6✔
965
        cls: type[Self],
966
        paths: str = ".",
967
        check_only: bool = False,
968
        bandit: bool = False,
969
        skip_mypy: bool = False,
970
        use_dmypy: bool = False,
971
        tool: str = ToolOption.default,
972
        with_prefix: bool = False,
973
    ) -> str:
974
        if paths != "." and all(i.endswith(".html") for i in paths.split()):
6✔
975
            return f"prettier -w {paths}"
6✔
976
        cmd = ""
6✔
977
        tools = ["ruff format", "ruff check --extend-select=I,B,SIM --fix", "mypy"]
6✔
978
        if check_only:
6✔
979
            tools[0] += " --check"
6✔
980
        if check_only or load_bool("NO_FIX"):
6✔
981
            tools[1] = tools[1].replace(" --fix", "")
6✔
982
        if skip_mypy or load_bool("SKIP_MYPY") or load_bool("FASTDEVCLI_NO_MYPY"):
6✔
983
            # Sometimes mypy is too slow
984
            tools = tools[:-1]
6✔
985
        elif load_bool("IGNORE_MISSING_IMPORTS"):
6✔
986
            tools[-1] += " --ignore-missing-imports"
6✔
987
        lint_them = " && ".join(
6✔
988
            "{0}{" + str(i) + "} {1}" for i in range(2, len(tools) + 2)
989
        )
990
        if ruff_exists := cls.check_lint_tool_installed():
6✔
991
            # `ruff <command>` get the same result with `pdm run ruff <command>`
992
            # While `mypy .`(installed global and env not activated),
993
            #   does not the same as `pdm run mypy .`
994
            lint_them = " && ".join(
6✔
995
                ("" if tool.startswith("ruff") else "{0}")
996
                + (
997
                    "{%d} {1}" % i  # noqa: UP031
998
                )
999
                for i, tool in enumerate(tools, 2)
1000
            )
1001
        prefix = ""
6✔
1002
        should_run_by_tool = with_prefix
6✔
1003
        if not should_run_by_tool:
6✔
1004
            if is_venv() and Path(sys.argv[0]).parent != Path.home().joinpath(
6✔
1005
                ".local/bin"
1006
            ):
1007
                if not ruff_exists:
6✔
1008
                    should_run_by_tool = True
6✔
1009
                    if check_call('python -c "import fast_dev_cli"'):
6✔
1010
                        command = 'python -m pip install -U "fast-dev-cli"'
6✔
1011
                        yellow_warn(
6✔
1012
                            "You may need to run the following command"
1013
                            f" to install lint tools:\n\n  {command}\n"
1014
                        )
1015
            else:
1016
                should_run_by_tool = True
6✔
1017
        if should_run_by_tool and tool:
6✔
1018
            if tool == ToolOption.default:
6✔
1019
                tool = Project.get_manage_tool() or ""
6✔
1020
            if tool:
6✔
1021
                prefix = (
6✔
1022
                    bin_dir
1023
                    if tool == "uv" and Path(bin_dir := ".venv/bin/").exists()
1024
                    else (tool + " run ")
1025
                )
1026
        if cls.prefer_dmypy(paths, tools, use_dmypy=use_dmypy):
6✔
1027
            tools[-1] = "dmypy run"
6✔
1028
        cmd += lint_them.format(prefix, paths, *tools)
6✔
1029
        if bandit or load_bool("FASTDEVCLI_BANDIT"):
6✔
1030
            command = prefix + "bandit"
6✔
1031
            if Path("pyproject.toml").exists():
6✔
1032
                toml_text = Project.load_toml_text()
6✔
1033
                if "[tool.bandit" in toml_text:
6✔
1034
                    command += " -c pyproject.toml"
6✔
1035
            if paths == "." and " -c " not in command:
6✔
1036
                paths = cls.get_package_name()
6✔
1037
            command += f" -r {paths}"
6✔
1038
            cmd += " && " + command
6✔
1039
        return cmd
6✔
1040

1041
    def gen(self) -> str:
6✔
1042
        if isinstance(args := self.args, str):
6✔
1043
            args = args.split()
6✔
1044
        paths = " ".join(map(str, args)) if args else "."
6✔
1045
        return self.to_cmd(
6✔
1046
            paths,
1047
            self.check_only,
1048
            self._bandit,
1049
            self._skip_mypy,
1050
            self._use_dmypy,
1051
            tool=self._tool,
1052
            with_prefix=self._prefix,
1053
        )
1054

1055

1056
def parse_files(args: list[str] | tuple[str, ...]) -> list[str]:
6✔
1057
    return [i for i in args if not i.startswith("-")]
6✔
1058

1059

1060
def lint(
6✔
1061
    files: list[str] | str | None = None,
1062
    dry: bool = False,
1063
    bandit: bool = False,
1064
    skip_mypy: bool = False,
1065
    dmypy: bool = False,
1066
    tool: str = ToolOption.default,
1067
    prefix: bool = False,
1068
) -> None:
1069
    if files is None:
6✔
1070
        files = parse_files(sys.argv[1:])
6✔
1071
    if files and files[0] == "lint":
6✔
1072
        files = files[1:]
6✔
1073
    LintCode(
6✔
1074
        files,
1075
        dry=dry,
1076
        skip_mypy=skip_mypy,
1077
        bandit=bandit,
1078
        dmypy=dmypy,
1079
        tool=tool,
1080
        prefix=prefix,
1081
    ).run()
1082

1083

1084
def check(
6✔
1085
    files: list[str] | str | None = None,
1086
    dry: bool = False,
1087
    bandit: bool = False,
1088
    skip_mypy: bool = False,
1089
    dmypy: bool = False,
1090
    tool: str = ToolOption.default,
1091
) -> None:
1092
    LintCode(
6✔
1093
        files,
1094
        check_only=True,
1095
        _exit=True,
1096
        dry=dry,
1097
        bandit=bandit,
1098
        skip_mypy=skip_mypy,
1099
        dmypy=dmypy,
1100
        tool=tool,
1101
    ).run()
1102

1103

1104
@cli.command(name="lint")
6✔
1105
def make_style(
6✔
1106
    files: Optional[list[str]] = typer.Argument(default=None),  # noqa:B008
1107
    check_only: bool = Option(False, "--check-only", "-c"),
1108
    bandit: bool = Option(False, "--bandit", help="Run `bandit -r <package_dir>`"),
1109
    prefix: bool = Option(
1110
        False,
1111
        "--prefix",
1112
        help="Run lint command with tool prefix, e.g.: pdm run ruff ...",
1113
    ),
1114
    skip_mypy: bool = Option(False, "--skip-mypy"),
1115
    use_dmypy: bool = Option(
1116
        False, "--dmypy", help="Use `dmypy run` instead of `mypy`"
1117
    ),
1118
    tool: str = ToolOption,
1119
    dry: bool = DryOption,
1120
) -> None:
1121
    """Run: ruff check/format to reformat code and then mypy to check"""
1122
    if getattr(files, "default", files) is None:
6✔
1123
        files = ["."]
6✔
1124
    elif isinstance(files, str):
6✔
1125
        files = [files]
6✔
1126
    skip = _ensure_bool(skip_mypy)
6✔
1127
    dmypy = _ensure_bool(use_dmypy)
6✔
1128
    bandit = _ensure_bool(bandit)
6✔
1129
    prefix = _ensure_bool(prefix)
6✔
1130
    tool = _ensure_str(tool)
6✔
1131
    if _ensure_bool(check_only):
6✔
1132
        check(files, dry=dry, skip_mypy=skip, dmypy=dmypy, bandit=bandit, tool=tool)
6✔
1133
    else:
1134
        lint(
6✔
1135
            files,
1136
            dry=dry,
1137
            skip_mypy=skip,
1138
            dmypy=dmypy,
1139
            bandit=bandit,
1140
            tool=tool,
1141
            prefix=prefix,
1142
        )
1143

1144

1145
@cli.command(name="check")
6✔
1146
def only_check(
6✔
1147
    bandit: bool = Option(False, "--bandit", help="Run `bandit -r <package_dir>`"),
1148
    skip_mypy: bool = Option(False, "--skip-mypy"),
1149
    dry: bool = DryOption,
1150
) -> None:
1151
    """Check code style without reformat"""
1152
    check(dry=dry, bandit=bandit, skip_mypy=_ensure_bool(skip_mypy))
6✔
1153

1154

1155
class Sync(DryRun):
6✔
1156
    def __init__(
6✔
1157
        self, filename: str, extras: str, save: bool, dry: bool = False
1158
    ) -> None:
1159
        self.filename = filename
6✔
1160
        self.extras = extras
6✔
1161
        self._save = save
6✔
1162
        super().__init__(dry=dry)
6✔
1163

1164
    def gen(self) -> str:
6✔
1165
        extras, save = self.extras, self._save
6✔
1166
        should_remove = not Path.cwd().joinpath(self.filename).exists()
6✔
1167
        if not (tool := Project.get_manage_tool()):
6✔
1168
            if should_remove or not is_venv():
6✔
1169
                raise EnvError("There project is not managed by uv/pdm/poetry!")
6✔
1170
            return f"python -m pip install -r {self.filename}"
6✔
1171
        prefix = "" if is_venv() else f"{tool} run "
6✔
1172
        ensure_pip = " {1}python -m ensurepip && {1}python -m pip install -U pip &&"
6✔
1173
        export_cmd = "uv export --no-hashes --all-extras --frozen"
6✔
1174
        if tool in ("poetry", "pdm"):
6✔
1175
            export_cmd = f"{tool} export --without-hashes --with=dev"
6✔
1176
            if tool == "poetry":
6✔
1177
                ensure_pip = ""
6✔
1178
                if not UpgradeDependencies.should_with_dev():
6✔
1179
                    export_cmd = export_cmd.replace(" --with=dev", "")
6✔
1180
                if extras and isinstance(extras, (str, list)):
6✔
1181
                    export_cmd += f" --{extras=}".replace("'", '"')
6✔
1182
            elif check_call(prefix + "python -m pip --version"):
6✔
1183
                ensure_pip = ""
6✔
1184
        elif check_call(prefix + "python -m pip --version"):
6✔
1185
            ensure_pip = ""
6✔
1186
        install_cmd = (
6✔
1187
            f"{{2}} -o {{0}} &&{ensure_pip} {{1}}python -m pip install -r {{0}}"
1188
        )
1189
        if should_remove and not save:
6✔
1190
            install_cmd += " && rm -f {0}"
6✔
1191
        return install_cmd.format(self.filename, prefix, export_cmd)
6✔
1192

1193

1194
@cli.command()
6✔
1195
def sync(
6✔
1196
    filename: str = "dev_requirements.txt",
1197
    extras: str = Option("", "--extras", "-E"),
1198
    save: bool = Option(
1199
        False, "--save", "-s", help="Whether save the requirement file"
1200
    ),
1201
    dry: bool = DryOption,
1202
) -> None:
1203
    """Export dependencies by poetry to a txt file then install by pip."""
1204
    Sync(filename, extras, save, dry=dry).run()
6✔
1205

1206

1207
def _should_run_test_script(path: Path = Path("scripts")) -> Path | None:
6✔
1208
    for name in ("test.sh", "test.py"):
6✔
1209
        if (file := path / name).exists():
6✔
1210
            return file
6✔
1211
    return None
6✔
1212

1213

1214
def test(dry: bool, ignore_script: bool = False) -> None:
6✔
1215
    cwd = Path.cwd()
6✔
1216
    root = Project.get_work_dir(cwd=cwd, allow_cwd=True)
6✔
1217
    script_dir = root / "scripts"
6✔
1218
    if not _ensure_bool(ignore_script) and (
6✔
1219
        test_script := _should_run_test_script(script_dir)
1220
    ):
1221
        cmd = f"{os.path.relpath(test_script, root)}"
6✔
1222
        if cwd != root:
6✔
1223
            cmd = f"cd {root} && " + cmd
6✔
1224
    else:
1225
        cmd = 'coverage run -m pytest -s && coverage report --omit="tests/*" -m'
6✔
1226
        if not is_venv() or not check_call("coverage --version"):
6✔
1227
            sep = " && "
6✔
1228
            prefix = f"{tool} run " if (tool := Project.get_manage_tool()) else ""
6✔
1229
            cmd = sep.join(prefix + i for i in cmd.split(sep))
6✔
1230
    exit_if_run_failed(cmd, dry=dry)
6✔
1231

1232

1233
@cli.command(name="test")
6✔
1234
def coverage_test(
6✔
1235
    dry: bool = DryOption,
1236
    ignore_script: bool = Option(False, "--ignore-script", "-i"),
1237
) -> None:
1238
    """Run unittest by pytest and report coverage"""
1239
    return test(dry, ignore_script)
6✔
1240

1241

1242
class Publish:
6✔
1243
    class CommandEnum(StrEnum):
6✔
1244
        poetry = "poetry publish --build"
6✔
1245
        pdm = "pdm publish"
6✔
1246
        uv = "uv build && uv publish"
6✔
1247
        twine = "python -m build && twine upload"
6✔
1248

1249
    @classmethod
6✔
1250
    def gen(cls) -> str:
6✔
1251
        if tool := Project.get_manage_tool():
6✔
1252
            return cls.CommandEnum[tool]
6✔
1253
        return cls.CommandEnum.twine
6✔
1254

1255

1256
@cli.command()
6✔
1257
def upload(
6✔
1258
    dry: bool = DryOption,
1259
) -> None:
1260
    """Shortcut for package publish"""
1261
    cmd = Publish.gen()
6✔
1262
    exit_if_run_failed(cmd, dry=dry)
6✔
1263

1264

1265
def dev(
6✔
1266
    port: int | None | OptionInfo,
1267
    host: str | None | OptionInfo,
1268
    file: str | None | ArgumentInfo = None,
1269
    dry: bool = False,
1270
) -> None:
1271
    cmd = "fastapi dev"
6✔
1272
    no_port_yet = True
6✔
1273
    if file is not None:
6✔
1274
        try:
6✔
1275
            port = int(str(file))
6✔
1276
        except ValueError:
6✔
1277
            cmd += f" {file}"
6✔
1278
        else:
1279
            if port != 8000:
6✔
1280
                cmd += f" --port={port}"
6✔
1281
                no_port_yet = False
6✔
1282
    if no_port_yet and (port := getattr(port, "default", port)) and str(port) != "8000":
6✔
1283
        cmd += f" --port={port}"
6✔
1284
    if (host := getattr(host, "default", host)) and host not in (
6✔
1285
        "localhost",
1286
        "127.0.0.1",
1287
    ):
1288
        cmd += f" --host={host}"
6✔
1289
    exit_if_run_failed(cmd, dry=dry)
6✔
1290

1291

1292
@cli.command(name="dev")
6✔
1293
def runserver(
6✔
1294
    file_or_port: Optional[str] = typer.Argument(default=None),
1295
    port: Optional[int] = Option(None, "-p", "--port"),
1296
    host: Optional[str] = Option(None, "-h", "--host"),
1297
    dry: bool = DryOption,
1298
) -> None:
1299
    """Start a fastapi server(only for fastapi>=0.111.0)"""
1300
    if getattr(file_or_port, "default", file_or_port):
6✔
1301
        dev(port, host, file=file_or_port, dry=dry)
6✔
1302
    else:
1303
        dev(port, host, dry=dry)
6✔
1304

1305

1306
@cli.command(name="exec")
6✔
1307
def run_by_subprocess(cmd: str, dry: bool = DryOption) -> None:
6✔
1308
    """Run cmd by subprocess, auto set shell=True when cmd contains '|>'"""
1309
    try:
6✔
1310
        rc = run_and_echo(cmd, verbose=True, dry=_ensure_bool(dry))
6✔
1311
    except FileNotFoundError as e:
6✔
1312
        if e.filename == cmd.split()[0]:
6✔
1313
            echo(f"Command not found: {e.filename}")
6✔
1314
            raise Exit(1) from None
6✔
1315
        raise e
1✔
1316
    else:
1317
        if rc:
6✔
1318
            raise Exit(rc)
6✔
1319

1320

1321
class MakeDeps(DryRun):
6✔
1322
    def __init__(self, tool: str, prod: bool = False, dry: bool = False) -> None:
6✔
1323
        self._tool = tool
6✔
1324
        self._prod = prod
6✔
1325
        super().__init__(dry=dry)
6✔
1326

1327
    def should_ensure_pip(self) -> bool:
6✔
1328
        return True
6✔
1329

1330
    def should_upgrade_pip(self) -> bool:
6✔
1331
        return True
×
1332

1333
    def get_groups(self) -> list[str]:
6✔
1334
        if self._prod:
6✔
1335
            return []
6✔
1336
        return ["dev"]
6✔
1337

1338
    def gen(self) -> str:
6✔
1339
        if self._tool == "pdm":
6✔
1340
            return "pdm sync " + ("--prod" if self._prod else "-G :all")
6✔
1341
        elif self._tool == "uv":
6✔
1342
            return "uv sync --inexact --active" + (
6✔
1343
                "" if self._prod else " --all-extras --all-groups"
1344
            )
1345
        elif self._tool == "poetry":
6✔
1346
            return "poetry install " + (
6✔
1347
                "--only=main" if self._prod else "--all-extras --all-groups"
1348
            )
1349
        else:
1350
            cmd = "python -m pip install -e ."
6✔
1351
            if gs := self.get_groups():
6✔
1352
                cmd += " " + " ".join(f"--group {g}" for g in gs)
6✔
1353
            upgrade = "python -m pip install --upgrade pip"
6✔
1354
            if self.should_ensure_pip():
6✔
1355
                cmd = f"python -m ensurepip && {upgrade} && {cmd}"
6✔
1356
            elif self.should_upgrade_pip():
×
1357
                cmd = "{upgrade} && {cmd}"
×
1358
            return cmd
6✔
1359

1360

1361
@cli.command(name="deps")
6✔
1362
def make_deps(
6✔
1363
    prod: bool = Option(
1364
        False,
1365
        "--prod",
1366
        help="Only instead production dependencies.",
1367
    ),
1368
    tool: str = ToolOption,
1369
    use_uv: bool = Option(False, "--uv", help="Use `uv` to install deps"),
1370
    use_pdm: bool = Option(False, "--pdm", help="Use `pdm` to install deps"),
1371
    use_pip: bool = Option(False, "--pip", help="Use `pip` to install deps"),
1372
    use_poetry: bool = Option(False, "--poetry", help="Use `poetry` to install deps"),
1373
    dry: bool = DryOption,
1374
) -> None:
1375
    """Run: ruff check/format to reformat code and then mypy to check"""
1376
    if use_uv + use_pdm + use_pip + use_poetry > 1:
×
1377
        raise UsageError("`--uv/--pdm/--pip/--poetry` can only choose one!")
×
1378
    if use_uv:
×
1379
        tool = "uv"
×
1380
    elif use_pdm:
×
1381
        tool = "pdm"
×
1382
    elif use_pip:
×
1383
        tool = "pip"
×
1384
    elif use_poetry:
×
1385
        tool = "poetry"
×
1386
    elif tool == ToolOption.default:
×
1387
        tool = Project.get_manage_tool(cache=True) or "pip"
×
1388
    MakeDeps(tool, prod, dry=dry).run()
×
1389

1390

1391
def version_callback(value: bool) -> None:
6✔
1392
    if value:
6✔
1393
        echo("Fast Dev Cli Version: " + typer.style(__version__, bold=True))
6✔
1394
        raise Exit()
6✔
1395

1396

1397
@cli.callback()
6✔
1398
def common(
6✔
1399
    version: bool = Option(
1400
        None,
1401
        "--version",
1402
        "-V",
1403
        callback=version_callback,
1404
        is_eager=True,
1405
        help="Show the version of this tool",
1406
    ),
1407
) -> None:
1408
    pass
×
1409

1410

1411
def main() -> None:
6✔
1412
    cli()
6✔
1413

1414

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