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

waketzheng / fast-dev-cli / 18804644459

25 Oct 2025 02:48PM UTC coverage: 88.046% (+0.08%) from 87.966%
18804644459

push

github

waketzheng
refactor: separate  to three functions as it's to long

42 of 50 new or added lines in 1 file covered. (84.0%)

91 existing lines in 1 file now uncovered.

928 of 1054 relevant lines covered (88.05%)

4.4 hits per line

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

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

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

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

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

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

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

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

36
    import tomli as tomllib
37

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

41

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

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

56

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

60

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

64

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

68

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

72

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

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

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

84

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

96

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

101

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

107

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

118

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

125

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

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

139
    @property
5✔
140
    def command(self) -> list[str] | str:
5✔
141
        command: list[str] | str = self._cmd
5✔
142
        if (
5✔
143
            isinstance(command, str)
144
            and "shell" not in self._kw
145
            and not (set(self._cmd) & {"|", ">", "&"})
146
        ):
147
            command = shlex.split(command)
5✔
148
        return command
5✔
149

150
    def _run(self) -> subprocess.CompletedProcess[str]:
5✔
151
        return self.run_by_subprocess(self.command, **self._kw)
5✔
152

153
    def run(self, verbose: bool = False, dry: bool = False) -> int:
5✔
154
        if verbose:
5✔
155
            echo(f"--> {self._cmd}")
5✔
156
        if dry:
5✔
157
            return 0
5✔
158
        return self._run().returncode
5✔
159

160
    def check_call(self) -> bool:
5✔
161
        self._kw.update(stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
5✔
162
        return self.run() == 0
5✔
163

164
    def capture_output(self, raises: bool = False) -> str:
5✔
165
        self._kw.update(capture_output=True, encoding="utf-8")
5✔
166
        r = self._run()
5✔
167
        if raises and r.returncode != 0:
5✔
168
            raise ShellCommandError(r.stderr)
5✔
169
        return (r.stdout or r.stderr or "").strip()
5✔
170

171
    def finish(
5✔
172
        self, env: dict[str, str] | None = None, _exit: bool = False, dry=False
173
    ) -> subprocess.CompletedProcess[str]:
174
        self.run(verbose=True, dry=True)
5✔
175
        if _ensure_bool(dry):
5✔
176
            return subprocess.CompletedProcess("", 0)
5✔
177
        if env is not None:
5✔
178
            self._kw["env"] = {**os.environ, **env}
5✔
179
        r = self._run()
5✔
180
        if rc := r.returncode:
5✔
181
            if _exit:
5✔
182
                sys.exit(rc)
5✔
183
            raise Exit(rc)
5✔
184
        return r
5✔
185

186

187
def run_and_echo(
5✔
188
    cmd: str, *, dry: bool = False, verbose: bool = True, **kw: Any
189
) -> int:
190
    """Run shell command with subprocess and print it"""
191
    return Shell(cmd, **kw).run(verbose=verbose, dry=dry)
5✔
192

193

194
def check_call(cmd: str) -> bool:
5✔
195
    return Shell(cmd).check_call()
5✔
196

197

198
def capture_cmd_output(
5✔
199
    command: list[str] | str, *, raises: bool = False, **kw: Any
200
) -> str:
201
    return Shell(command, **kw).capture_output(raises=raises)
5✔
202

203

204
def exit_if_run_failed(
5✔
205
    cmd: str,
206
    env: dict[str, str] | None = None,
207
    _exit: bool = False,
208
    dry: bool = False,
209
    **kw: Any,
210
) -> subprocess.CompletedProcess[str]:
211
    return Shell(cmd, **kw).finish(env=env, _exit=_exit, dry=dry)
5✔
212

213

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

217

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

253
    pattern = re.compile(r"__version__\s*=")
×
254
    for line in init_file.read_text("utf-8").splitlines():
×
UNCOV
255
        if pattern.match(line):
×
UNCOV
256
            return _parse_version(line, pattern)
×
UNCOV
257
    secho(f"WARNING: can not find '__version__' var in {init_file}!")
×
UNCOV
258
    return "0.0.0"
×
259

260

261
@overload
262
def get_current_version(
263
    verbose: bool = False,
264
    is_poetry: bool | None = None,
265
    package_name: str | None = None,
266
    *,
267
    check_version: Literal[False] = False,
268
) -> str: ...
269

270

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

280

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

317

318
def _ensure_bool(value: bool | OptionInfo) -> bool:
5✔
319
    if not isinstance(value, bool):
5✔
320
        value = getattr(value, "default", False)
5✔
321
    return value
5✔
322

323

324
def _ensure_str(value: str | OptionInfo | None) -> str:
5✔
325
    if not isinstance(value, str):
5✔
326
        value = getattr(value, "default", "")
5✔
327
    return value
5✔
328

329

330
class DryRun:
5✔
331
    def __init__(self, _exit: bool = False, dry: bool = False) -> None:
5✔
332
        self.dry = _ensure_bool(dry)
5✔
333
        self._exit = _exit
5✔
334

335
    def gen(self) -> str:
5✔
336
        raise NotImplementedError
5✔
337

338
    def run(self) -> None:
5✔
339
        exit_if_run_failed(self.gen(), _exit=self._exit, dry=self.dry)
5✔
340

341

342
class BumpUp(DryRun):
5✔
343
    class PartChoices(StrEnum):
5✔
344
        patch = "patch"
5✔
345
        minor = "minor"
5✔
346
        major = "major"
5✔
347

348
    def __init__(
5✔
349
        self,
350
        commit: bool,
351
        part: str,
352
        filename: str | None = None,
353
        dry: bool = False,
354
        no_sync: bool = False,
355
        emoji: bool | None = None,
356
    ) -> None:
357
        self.commit = commit
5✔
358
        self.part = part
5✔
359
        if filename is None:
5✔
360
            filename = self.parse_filename()
5✔
361
        self.filename = filename
5✔
362
        self._no_sync = no_sync
5✔
363
        self._emoji = emoji
5✔
364
        super().__init__(dry=dry)
5✔
365

366
    @staticmethod
5✔
367
    def get_last_commit_message(raises: bool = False) -> str:
5✔
368
        cmd = 'git show --pretty=format:"%s" -s HEAD'
5✔
369
        return capture_cmd_output(cmd, raises=raises)
5✔
370

371
    @classmethod
5✔
372
    def should_add_emoji(cls) -> bool:
5✔
373
        """
374
        If last commit message is startswith emoji,
375
        add a ⬆️ flag at the prefix of bump up commit message.
376
        """
377
        try:
5✔
378
            first_char = cls.get_last_commit_message(raises=True)[0]
5✔
379
        except (IndexError, ShellCommandError):
5✔
380
            return False
5✔
381
        else:
382
            return is_emoji(first_char)
5✔
383

384
    @staticmethod
5✔
385
    def parse_dynamic_version(
5✔
386
        toml_text: str,
387
        context: dict,
388
        work_dir: Path | None = None,
389
    ) -> str | None:
390
        if work_dir is None:
5✔
391
            work_dir = Project.get_work_dir()
5✔
392
        for tool in ("pdm", "hatch"):
5✔
393
            with contextlib.suppress(KeyError):
5✔
394
                version_path = cast(str, context["tool"][tool]["version"]["path"])
5✔
395
                if (
5✔
396
                    Path(version_path).exists()
397
                    or work_dir.joinpath(version_path).exists()
398
                ):
399
                    return version_path
5✔
400
        # version = { source = "file", path = "fast_dev_cli/__init__.py" }
401
        v_key = "version = "
5✔
402
        p_key = 'path = "'
5✔
403
        for line in toml_text.splitlines():
5✔
NEW
404
            if not line.startswith(v_key):
×
NEW
405
                continue
×
NEW
406
            if p_key in (value := line.split(v_key, 1)[-1].split("#")[0]):
×
NEW
407
                filename = value.split(p_key, 1)[-1].split('"')[0]
×
NEW
408
                if work_dir.joinpath(filename).exists():
×
NEW
409
                    return filename
×
410
        return None
5✔
411

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

446
        return TOML_FILE
5✔
447

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

487
    def get_part(self, s: str) -> str:
5✔
488
        choices: dict[str, str] = {}
5✔
489
        for i, p in enumerate(self.PartChoices, 1):
5✔
490
            v = str(p)
5✔
491
            choices.update({str(i): v, v: v})
5✔
492
        try:
5✔
493
            return choices[s]
5✔
494
        except KeyError as e:
5✔
495
            echo(f"Invalid part: {s!r}")
5✔
496
            raise Exit(1) from e
5✔
497

498
    def gen(self) -> str:
5✔
499
        should_sync, _version = get_current_version(check_version=True)
5✔
500
        filename = self.filename
5✔
501
        echo(f"Current version(@{filename}): {_version}")
5✔
502
        if self.part:
5✔
503
            part = self.get_part(self.part)
5✔
504
        else:
505
            part = "patch"
5✔
506
            if a := input("Which one?").strip():
5✔
507
                part = self.get_part(a)
5✔
508
        self.part = part
5✔
509
        parse = r'--parse "(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)"'
5✔
510
        cmd = f'bumpversion {parse} --current-version="{_version}" {part} {filename}'
5✔
511
        if self.commit:
5✔
512
            if part != "patch":
5✔
513
                cmd += " --tag"
5✔
514
            cmd += " --commit"
5✔
515
            if self._emoji or (self._emoji is None and self.should_add_emoji()):
5✔
516
                cmd += " --message-emoji=1"
5✔
517
            if not load_bool("DONT_GIT_PUSH"):
5✔
518
                cmd += " && git push && git push --tags && git log -1"
5✔
519
        else:
520
            cmd += " --allow-dirty"
5✔
521
        if should_sync and not self._no_sync and (sync := Project.get_sync_command()):
5✔
522
            cmd = f"{sync} && " + cmd
5✔
523
        return cmd
5✔
524

525
    def run(self) -> None:
5✔
526
        super().run()
5✔
527
        if not self.commit and not self.dry:
5✔
528
            new_version = get_current_version(True)
5✔
529
            echo(new_version)
5✔
530
            if self.part != "patch":
5✔
531
                echo("You may want to pin tag by `fast tag`")
5✔
532

533

534
@cli.command()
5✔
535
def version() -> None:
5✔
536
    """Show the version of this tool"""
537
    echo("Fast Dev Cli Version: " + typer.style(__version__, fg=typer.colors.BLUE))
5✔
538
    with contextlib.suppress(FileNotFoundError, KeyError):
5✔
539
        toml_text = Project.load_toml_text()
5✔
540
        doc = tomllib.loads(toml_text)
5✔
541
        if value := doc.get("project", {}).get("version", ""):
5✔
UNCOV
542
            styled = typer.style(value, bold=True, fg=typer.colors.CYAN)
×
UNCOV
543
            if project_name := doc["project"].get("name", ""):
×
UNCOV
544
                echo(f"{project_name} version: " + styled)
×
545
            else:
UNCOV
546
                echo(f"Got Version from {TOML_FILE}: " + styled)
×
UNCOV
547
            return
×
548
        version_file = doc["tool"]["pdm"]["version"]["path"]
5✔
549
        text = Project.get_work_dir().joinpath(version_file).read_text()
5✔
550
        varname = "__version__"
5✔
551
        for line in text.splitlines():
5✔
552
            if line.strip().startswith(varname):
5✔
553
                value = line.split("=", 1)[-1].strip().strip('"').strip("'")
5✔
554
                styled = typer.style(value, bold=True)
5✔
555
                echo(f"Version value in {version_file}: " + styled)
5✔
556
                break
5✔
557

558

559
@cli.command(name="bump")
5✔
560
def bump_version(
5✔
561
    part: BumpUp.PartChoices,
562
    commit: bool = Option(
563
        False, "--commit", "-c", help="Whether run `git commit` after version changed"
564
    ),
565
    emoji: bool | None = Option(
566
        None, "--emoji", help="Whether add emoji prefix to commit message"
567
    ),
568
    no_sync: bool = Option(
569
        False, "--no-sync", help="Do not run sync command to update version"
570
    ),
571
    dry: bool = DryOption,
572
) -> None:
573
    """Bump up version string in pyproject.toml"""
574
    if emoji is not None:
5✔
575
        emoji = _ensure_bool(emoji)
5✔
576
    return BumpUp(
5✔
577
        _ensure_bool(commit),
578
        getattr(part, "value", part),
579
        no_sync=_ensure_bool(no_sync),
580
        emoji=emoji,
581
        dry=dry,
582
    ).run()
583

584

585
def bump() -> None:
5✔
586
    part, commit = "", False
5✔
587
    if args := sys.argv[2:]:
5✔
588
        if "-c" in args or "--commit" in args:
5✔
589
            commit = True
5✔
590
        for a in args:
5✔
591
            if not a.startswith("-"):
5✔
592
                part = a
5✔
593
                break
5✔
594
    return BumpUp(commit, part, no_sync="--no-sync" in args, dry="--dry" in args).run()
5✔
595

596

597
class Project:
5✔
598
    path_depth = 5
5✔
599
    _tool: ToolName | None = None
5✔
600

601
    @staticmethod
5✔
602
    def is_poetry_v2(text: str) -> bool:
5✔
603
        return 'build-backend = "poetry' in text
5✔
604

605
    @staticmethod
5✔
606
    def get_poetry_version(command: str = "poetry") -> str:
5✔
607
        pattern = r"(\d+\.\d+\.\d+)"
5✔
608
        text = capture_cmd_output(f"{command} --version")
5✔
609
        for expr in (
5✔
610
            rf"Poetry \(version {pattern}\)",
611
            rf"Poetry.*version.*{pattern}.*\)",
612
            rf"{pattern}",
613
        ):
614
            if m := re.search(expr, text):
5✔
615
                return m.group(1)
5✔
UNCOV
616
        return ""
×
617

618
    @staticmethod
5✔
619
    def work_dir(
5✔
620
        name: str, parent: Path, depth: int, be_file: bool = False
621
    ) -> Path | None:
622
        for _ in range(depth):
5✔
623
            if (f := parent.joinpath(name)).exists():
5✔
624
                if be_file:
5✔
625
                    return f
5✔
626
                return parent
5✔
627
            parent = parent.parent
5✔
628
        return None
5✔
629

630
    @classmethod
5✔
631
    def get_work_dir(
5✔
632
        cls: type[Self],
633
        name: str = TOML_FILE,
634
        cwd: Path | None = None,
635
        allow_cwd: bool = False,
636
        be_file: bool = False,
637
    ) -> Path:
638
        cwd = cwd or Path.cwd()
5✔
639
        if d := cls.work_dir(name, cwd, cls.path_depth, be_file):
5✔
640
            return d
5✔
641
        if allow_cwd:
5✔
642
            return cls.get_root_dir(cwd)
5✔
643
        raise EnvError(f"{name} not found! Make sure this is a python project.")
5✔
644

645
    @classmethod
5✔
646
    def load_toml_text(cls: type[Self], name: str = TOML_FILE) -> str:
5✔
647
        toml_file = cls.get_work_dir(name, be_file=True)
5✔
648
        return toml_file.read_text("utf8")
5✔
649

650
    @classmethod
5✔
651
    def manage_by_poetry(cls: type[Self], cache: bool = False) -> bool:
5✔
652
        return cls.get_manage_tool(cache=cache) == "poetry"
5✔
653

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

726
    @staticmethod
5✔
727
    def python_exec_dir() -> Path:
5✔
728
        return Path(sys.executable).parent
5✔
729

730
    @classmethod
5✔
731
    def get_root_dir(cls: type[Self], cwd: Path | None = None) -> Path:
5✔
732
        root = cwd or Path.cwd()
5✔
733
        venv_parent = cls.python_exec_dir().parent.parent
5✔
734
        if root.is_relative_to(venv_parent):
5✔
735
            root = venv_parent
5✔
736
        return root
5✔
737

738
    @classmethod
5✔
739
    def is_pdm_project(cls, strict: bool = True, cache: bool = False) -> bool:
5✔
740
        if cls.get_manage_tool(cache=cache) != "pdm":
5✔
741
            return False
5✔
UNCOV
742
        if strict:
×
UNCOV
743
            lock_file = cls.get_work_dir() / "pdm.lock"
×
UNCOV
744
            return lock_file.exists()
×
UNCOV
745
        return True
×
746

747
    @classmethod
5✔
748
    def get_sync_command(cls, prod: bool = True, doc: dict | None = None) -> str:
5✔
749
        if cls.is_pdm_project():
5✔
UNCOV
750
            return "pdm install --frozen" + " --prod" * prod
×
751
        elif cls.manage_by_poetry(cache=True):
5✔
752
            cmd = "poetry install"
5✔
753
            if prod:
5✔
754
                if doc is None:
5✔
755
                    doc = tomllib.loads(cls.load_toml_text())
5✔
756
                if doc.get("project", {}).get("dependencies") or any(
5✔
757
                    i != "python"
758
                    for i in doc.get("tool", {})
759
                    .get("poetry", {})
760
                    .get("dependencies", [])
761
                ):
UNCOV
762
                    cmd += " --only=main"
×
763
            return cmd
5✔
UNCOV
764
        elif cls.get_manage_tool(cache=True) == "uv":
×
UNCOV
765
            return "uv sync --inexact" + " --no-dev" * prod
×
UNCOV
766
        return ""
×
767

768
    @classmethod
5✔
769
    def sync_dependencies(cls, prod: bool = True) -> None:
5✔
UNCOV
770
        if cmd := cls.get_sync_command():
×
771
            run_and_echo(cmd)
×
772

773

774
class UpgradeDependencies(Project, DryRun):
5✔
775
    def __init__(
5✔
776
        self, _exit: bool = False, dry: bool = False, tool: ToolName = "poetry"
777
    ) -> None:
778
        super().__init__(_exit, dry)
5✔
779
        self._tool = tool
5✔
780

781
    class DevFlag(StrEnum):
5✔
782
        new = "[tool.poetry.group.dev.dependencies]"
5✔
783
        old = "[tool.poetry.dev-dependencies]"
5✔
784

785
    @staticmethod
5✔
786
    def parse_value(version_info: str, key: str) -> str:
5✔
787
        """Pick out the value for key in version info.
788

789
        Example::
790
            >>> s= 'typer = {extras = ["all"], version = "^0.9.0", optional = true}'
791
            >>> UpgradeDependencies.parse_value(s, 'extras')
792
            'all'
793
            >>> UpgradeDependencies.parse_value(s, 'optional')
794
            'true'
795
            >>> UpgradeDependencies.parse_value(s, 'version')
796
            '^0.9.0'
797
        """
798
        sep = key + " = "
5✔
799
        rest = version_info.split(sep, 1)[-1].strip(" =")
5✔
800
        if rest.startswith("["):
5✔
801
            rest = rest[1:].split("]")[0]
5✔
802
        elif rest.startswith('"'):
5✔
803
            rest = rest[1:].split('"')[0]
5✔
804
        else:
805
            rest = rest.split(",")[0].split("}")[0]
5✔
806
        return rest.strip().replace('"', "")
5✔
807

808
    @staticmethod
5✔
809
    def no_need_upgrade(version_info: str, line: str) -> bool:
5✔
810
        if (v := version_info.replace(" ", "")).startswith("{url="):
5✔
811
            echo(f"No need to upgrade for: {line}")
5✔
812
            return True
5✔
813
        if (f := "version=") in v:
5✔
814
            v = v.split(f)[1].strip('"').split('"')[0]
5✔
815
        if v == "*":
5✔
816
            echo(f"Skip wildcard line: {line}")
5✔
817
            return True
5✔
818
        elif v == "[":
5✔
819
            echo(f"Skip complex dependence: {line}")
5✔
820
            return True
5✔
821
        elif v.startswith(">") or v.startswith("<") or v[0].isdigit():
5✔
822
            echo(f"Ignore bigger/smaller/equal: {line}")
5✔
823
            return True
5✔
824
        return False
5✔
825

826
    @classmethod
5✔
827
    def build_args(
5✔
828
        cls: type[Self], package_lines: list[str]
829
    ) -> tuple[list[str], dict[str, list[str]]]:
830
        args: list[str] = []  # ['typer[all]', 'fastapi']
5✔
831
        specials: dict[str, list[str]] = {}  # {'--platform linux': ['gunicorn']}
5✔
832
        for no, line in enumerate(package_lines, 1):
5✔
833
            if (
5✔
834
                not (m := line.strip())
835
                or m.startswith("#")
836
                or m == "]"
837
                or (m.startswith("{") and m.strip(",").endswith("}"))
838
            ):
839
                continue
5✔
840
            try:
5✔
841
                package, version_info = m.split("=", 1)
5✔
842
            except ValueError as e:
5✔
843
                raise ParseError(f"Failed to separate by '='@line {no}: {m}") from e
5✔
844
            if (package := package.strip()).lower() == "python":
5✔
845
                continue
5✔
846
            if cls.no_need_upgrade(version_info := version_info.strip(' "'), line):
5✔
847
                continue
5✔
848
            if (extras_tip := "extras") in version_info:
5✔
849
                package += "[" + cls.parse_value(version_info, extras_tip) + "]"
5✔
850
            item = f'"{package}@latest"'
5✔
851
            key = None
5✔
852
            if (pf := "platform") in version_info:
5✔
853
                platform = cls.parse_value(version_info, pf)
5✔
854
                key = f"--{pf}={platform}"
5✔
855
            if (sc := "source") in version_info:
5✔
856
                source = cls.parse_value(version_info, sc)
5✔
857
                key = ("" if key is None else (key + " ")) + f"--{sc}={source}"
5✔
858
            if "optional = true" in version_info:
5✔
859
                key = ("" if key is None else (key + " ")) + "--optional"
5✔
860
            if key is not None:
5✔
861
                specials[key] = specials.get(key, []) + [item]
5✔
862
            else:
863
                args.append(item)
5✔
864
        return args, specials
5✔
865

866
    @classmethod
5✔
867
    def should_with_dev(cls: type[Self]) -> bool:
5✔
868
        text = cls.load_toml_text()
5✔
869
        return cls.DevFlag.new in text or cls.DevFlag.old in text
5✔
870

871
    @staticmethod
5✔
872
    def parse_item(toml_str: str) -> list[str]:
5✔
873
        lines: list[str] = []
5✔
874
        for line in toml_str.splitlines():
5✔
875
            if (line := line.strip()).startswith("["):
5✔
876
                if lines:
5✔
877
                    break
5✔
878
            elif line:
5✔
879
                lines.append(line)
5✔
880
        return lines
5✔
881

882
    @classmethod
5✔
883
    def get_args(
5✔
884
        cls: type[Self], toml_text: str | None = None
885
    ) -> tuple[list[str], list[str], list[list[str]], str]:
886
        if toml_text is None:
5✔
887
            toml_text = cls.load_toml_text()
5✔
888
        main_title = "[tool.poetry.dependencies]"
5✔
889
        if (no_main_deps := main_title not in toml_text) and not cls.is_poetry_v2(
5✔
890
            toml_text
891
        ):
892
            raise EnvError(
5✔
893
                f"{main_title} not found! Make sure this is a poetry project."
894
            )
895
        text = toml_text.split(main_title)[-1]
5✔
896
        dev_flag = "--group dev"
5✔
897
        new_flag, old_flag = cls.DevFlag.new, cls.DevFlag.old
5✔
898
        if (dev_title := getattr(new_flag, "value", new_flag)) not in text:
5✔
899
            dev_title = getattr(old_flag, "value", old_flag)  # For poetry<=1.2
5✔
900
            dev_flag = "--dev"
5✔
901
        others: list[list[str]] = []
5✔
902
        try:
5✔
903
            main_toml, dev_toml = text.split(dev_title)
5✔
904
        except ValueError:
5✔
905
            dev_toml = ""
5✔
906
            main_toml = text
5✔
907
        mains = [] if no_main_deps else cls.parse_item(main_toml)
5✔
908
        devs = cls.parse_item(dev_toml)
5✔
909
        prod_packs, specials = cls.build_args(mains)
5✔
910
        if specials:
5✔
911
            others.extend([[k] + v for k, v in specials.items()])
5✔
912
        dev_packs, specials = cls.build_args(devs)
5✔
913
        if specials:
5✔
914
            others.extend([[k] + v + [dev_flag] for k, v in specials.items()])
5✔
915
        return prod_packs, dev_packs, others, dev_flag
5✔
916

917
    @classmethod
5✔
918
    def gen_cmd(cls: type[Self]) -> str:
5✔
919
        main_args, dev_args, others, dev_flags = cls.get_args()
5✔
920
        return cls.to_cmd(main_args, dev_args, others, dev_flags)
5✔
921

922
    @staticmethod
5✔
923
    def to_cmd(
5✔
924
        main_args: list[str],
925
        dev_args: list[str],
926
        others: list[list[str]],
927
        dev_flags: str,
928
    ) -> str:
929
        command = "poetry add "
5✔
930
        _upgrade = ""
5✔
931
        if main_args:
5✔
932
            _upgrade = command + " ".join(main_args)
5✔
933
        if dev_args:
5✔
934
            if _upgrade:
5✔
935
                _upgrade += " && "
5✔
936
            _upgrade += command + dev_flags + " " + " ".join(dev_args)
5✔
937
        for single in others:
5✔
938
            _upgrade += f" && poetry add {' '.join(single)}"
5✔
939
        return _upgrade
5✔
940

941
    def gen(self) -> str:
5✔
942
        if self._tool == "uv":
5✔
943
            up = "uv lock --upgrade --verbose"
5✔
944
            deps = "uv sync --inexact --frozen --all-groups --all-extras"
5✔
945
            return f"{up} && {deps}"
5✔
946
        elif self._tool == "pdm":
5✔
947
            return "pdm update --verbose && pdm install -G :all --frozen"
5✔
948
        return self.gen_cmd() + " && poetry lock && poetry update"
5✔
949

950

951
@cli.command()
5✔
952
def upgrade(
5✔
953
    tool: str = ToolOption,
954
    dry: bool = DryOption,
955
) -> None:
956
    """Upgrade dependencies in pyproject.toml to latest versions"""
957
    if not (tool := _ensure_str(tool)) or tool == ToolOption.default:
5✔
958
        tool = Project.get_manage_tool() or "uv"
5✔
959
    if tool in get_args(ToolName):
5✔
960
        UpgradeDependencies(dry=dry, tool=cast(ToolName, tool)).run()
5✔
961
    else:
962
        secho(f"Unknown tool {tool!r}", fg=typer.colors.YELLOW)
5✔
963
        raise typer.Exit(1)
5✔
964

965

966
class GitTag(DryRun):
5✔
967
    def __init__(self, message: str, dry: bool, no_sync: bool = False) -> None:
5✔
968
        self.message = message
5✔
969
        self._no_sync = no_sync
5✔
970
        super().__init__(dry=dry)
5✔
971

972
    @staticmethod
5✔
973
    def has_v_prefix() -> bool:
5✔
974
        return "v" in capture_cmd_output("git tag")
5✔
975

976
    def should_push(self) -> bool:
5✔
977
        return "git push" in self.git_status
5✔
978

979
    def gen(self) -> str:
5✔
980
        should_sync, _version = get_current_version(verbose=False, check_version=True)
5✔
981
        if self.has_v_prefix():
5✔
982
            # Add `v` at prefix to compare with bumpversion tool
983
            _version = "v" + _version
5✔
984
        cmd = f"git tag -a {_version} -m {self.message!r} && git push --tags"
5✔
985
        if self.should_push():
5✔
986
            cmd += " && git push"
5✔
987
        if should_sync and not self._no_sync and (sync := Project.get_sync_command()):
5✔
UNCOV
988
            cmd = f"{sync} && " + cmd
×
989
        return cmd
5✔
990

991
    @cached_property
5✔
992
    def git_status(self) -> str:
5✔
993
        return capture_cmd_output("git status")
5✔
994

995
    def mark_tag(self) -> bool:
5✔
996
        if not re.search(r"working (tree|directory) clean", self.git_status) and (
5✔
997
            "无文件要提交,干净的工作区" not in self.git_status
998
        ):
999
            run_and_echo("git status")
5✔
1000
            echo("ERROR: Please run git commit to make sure working tree is clean!")
5✔
1001
            return False
5✔
1002
        return bool(super().run())
5✔
1003

1004
    def run(self) -> None:
5✔
1005
        if self.mark_tag() and not self.dry:
5✔
1006
            echo("You may want to publish package:\n poetry publish --build")
5✔
1007

1008

1009
@cli.command()
5✔
1010
def tag(
5✔
1011
    message: str = Option("", "-m", "--message"),
1012
    no_sync: bool = Option(
1013
        False, "--no-sync", help="Do not run sync command to update version"
1014
    ),
1015
    dry: bool = DryOption,
1016
) -> None:
1017
    """Run shell command: git tag -a <current-version-in-pyproject.toml> -m {message}"""
1018
    GitTag(message, dry=dry, no_sync=_ensure_bool(no_sync)).run()
5✔
1019

1020

1021
class LintCode(DryRun):
5✔
1022
    def __init__(
5✔
1023
        self,
1024
        args: list[str] | str | None,
1025
        check_only: bool = False,
1026
        _exit: bool = False,
1027
        dry: bool = False,
1028
        bandit: bool = False,
1029
        skip_mypy: bool = False,
1030
        dmypy: bool = False,
1031
        tool: str = ToolOption.default,
1032
        prefix: bool = False,
1033
    ) -> None:
1034
        self.args = args
5✔
1035
        self.check_only = check_only
5✔
1036
        self._bandit = bandit
5✔
1037
        self._skip_mypy = skip_mypy
5✔
1038
        self._use_dmypy = dmypy
5✔
1039
        self._tool = tool
5✔
1040
        self._prefix = prefix
5✔
1041
        super().__init__(_exit, dry)
5✔
1042

1043
    @staticmethod
5✔
1044
    def check_lint_tool_installed() -> bool:
5✔
1045
        try:
5✔
1046
            return check_call("ruff --version")
5✔
UNCOV
1047
        except FileNotFoundError:
×
1048
            # Windows may raise FileNotFoundError when ruff not installed
UNCOV
1049
            return False
×
1050

1051
    @staticmethod
5✔
1052
    def missing_mypy_exec() -> bool:
5✔
1053
        return shutil.which("mypy") is None
5✔
1054

1055
    @staticmethod
5✔
1056
    def prefer_dmypy(paths: str, tools: list[str], use_dmypy: bool = False) -> bool:
5✔
1057
        return (
5✔
1058
            paths == "."
1059
            and any(t.startswith("mypy") for t in tools)
1060
            and (use_dmypy or load_bool("FASTDEVCLI_DMYPY"))
1061
        )
1062

1063
    @staticmethod
5✔
1064
    def get_package_name() -> str:
5✔
1065
        root = Project.get_work_dir(allow_cwd=True)
5✔
1066
        module_name = root.name.replace("-", "_").replace(" ", "_")
5✔
1067
        package_maybe = (module_name, "src")
5✔
1068
        for name in package_maybe:
5✔
1069
            if root.joinpath(name).is_dir():
5✔
1070
                return name
5✔
1071
        return "."
5✔
1072

1073
    @classmethod
5✔
1074
    def to_cmd(
5✔
1075
        cls: type[Self],
1076
        paths: str = ".",
1077
        check_only: bool = False,
1078
        bandit: bool = False,
1079
        skip_mypy: bool = False,
1080
        use_dmypy: bool = False,
1081
        tool: str = ToolOption.default,
1082
        with_prefix: bool = False,
1083
    ) -> str:
1084
        if paths != "." and all(i.endswith(".html") for i in paths.split()):
5✔
1085
            return f"prettier -w {paths}"
5✔
1086
        cmd = ""
5✔
1087
        tools = ["ruff format", "ruff check --extend-select=I,B,SIM --fix", "mypy"]
5✔
1088
        if check_only:
5✔
1089
            tools[0] += " --check"
5✔
1090
        if check_only or load_bool("NO_FIX"):
5✔
1091
            tools[1] = tools[1].replace(" --fix", "")
5✔
1092
        if skip_mypy or load_bool("SKIP_MYPY") or load_bool("FASTDEVCLI_NO_MYPY"):
5✔
1093
            # Sometimes mypy is too slow
1094
            tools = tools[:-1]
5✔
1095
        elif load_bool("IGNORE_MISSING_IMPORTS"):
5✔
1096
            tools[-1] += " --ignore-missing-imports"
5✔
1097
        lint_them = " && ".join(
5✔
1098
            "{0}{" + str(i) + "} {1}" for i in range(2, len(tools) + 2)
1099
        )
1100
        if ruff_exists := cls.check_lint_tool_installed():
5✔
1101
            # `ruff <command>` get the same result with `pdm run ruff <command>`
1102
            # While `mypy .`(installed global and env not activated),
1103
            #   does not the same as `pdm run mypy .`
1104
            lint_them = " && ".join(
5✔
1105
                ("" if tool.startswith("ruff") else "{0}")
1106
                + (
1107
                    "{%d} {1}" % i  # noqa: UP031
1108
                )
1109
                for i, tool in enumerate(tools, 2)
1110
            )
1111
        prefix = ""
5✔
1112
        should_run_by_tool = with_prefix
5✔
1113
        if not should_run_by_tool:
5✔
1114
            if is_venv() and Path(sys.argv[0]).parent != Path.home().joinpath(
5✔
1115
                ".local/bin"
1116
            ):  # Virtual environment activated and fast-dev-cli is installed in it
1117
                if not ruff_exists:
5✔
1118
                    should_run_by_tool = True
5✔
1119
                    command = "pipx install ruff"
5✔
1120
                    if shutil.which("pipx") is None:
5✔
UNCOV
1121
                        ensure_pipx = "pip install --user pipx\n  pipx ensurepath\n  "
×
UNCOV
1122
                        command = ensure_pipx + command
×
1123
                    yellow_warn(
5✔
1124
                        "You may need to run the following command"
1125
                        f" to install ruff:\n\n  {command}\n"
1126
                    )
1127
                elif "mypy" in str(tools) and cls.missing_mypy_exec():
5✔
1128
                    should_run_by_tool = True
5✔
1129
                    if check_call('python -c "import fast_dev_cli"'):
5✔
1130
                        command = 'python -m pip install -U "fast-dev-cli"'
5✔
1131
                        yellow_warn(
5✔
1132
                            "You may need to run the following command"
1133
                            f" to install lint tools:\n\n  {command}\n"
1134
                        )
UNCOV
1135
            elif tool == ToolOption.default:
×
UNCOV
1136
                root = Project.get_work_dir(allow_cwd=True)
×
UNCOV
1137
                if py := shutil.which("python"):
×
UNCOV
1138
                    try:
×
UNCOV
1139
                        Path(py).relative_to(root)
×
UNCOV
1140
                    except ValueError:
×
1141
                        # Virtual environment not activated
UNCOV
1142
                        should_run_by_tool = True
×
1143
            else:
1144
                should_run_by_tool = True
×
1145
        if should_run_by_tool and tool:
5✔
1146
            if tool == ToolOption.default:
5✔
1147
                tool = Project.get_manage_tool() or ""
5✔
1148
            if tool:
5✔
1149
                prefix = tool + " run "
5✔
1150
                if tool == "uv":
5✔
1151
                    if is_windows():
×
UNCOV
1152
                        prefix += "--no-sync "
×
1153
                    elif Path(bin_dir := ".venv/bin/").exists():
×
UNCOV
1154
                        prefix = bin_dir
×
1155
        if cls.prefer_dmypy(paths, tools, use_dmypy=use_dmypy):
5✔
1156
            tools[-1] = "dmypy run"
5✔
1157
        cmd += lint_them.format(prefix, paths, *tools)
5✔
1158
        if bandit or load_bool("FASTDEVCLI_BANDIT"):
5✔
1159
            command = prefix + "bandit"
5✔
1160
            if Path("pyproject.toml").exists():
5✔
1161
                toml_text = Project.load_toml_text()
5✔
1162
                if "[tool.bandit" in toml_text:
5✔
1163
                    command += " -c pyproject.toml"
5✔
1164
            if paths == "." and " -c " not in command:
5✔
1165
                paths = cls.get_package_name()
5✔
1166
            command += f" -r {paths}"
5✔
1167
            cmd += " && " + command
5✔
1168
        return cmd
5✔
1169

1170
    def gen(self) -> str:
5✔
1171
        paths = "."
5✔
1172
        if args := self.args:
5✔
1173
            ps = args.split() if isinstance(args, str) else [str(i) for i in args]
5✔
1174
            if len(ps) == 1:
5✔
1175
                paths = ps[0]
5✔
1176
                if (
5✔
1177
                    paths != "."
1178
                    # `Path("a.").suffix` got "." in py3.14 and got "" with py<3.14
1179
                    and (p := Path(paths)).suffix in ("", ".")
1180
                    and not p.exists()
1181
                ):
1182
                    # e.g.:
1183
                    # stem -> stem.py
1184
                    # me. -> me.py
UNCOV
1185
                    if paths.endswith("."):
×
UNCOV
1186
                        p = p.with_name(paths[:-1])
×
UNCOV
1187
                    for suffix in (".py", ".html"):
×
UNCOV
1188
                        p = p.with_suffix(suffix)
×
UNCOV
1189
                        if p.exists():
×
UNCOV
1190
                            paths = p.name
×
UNCOV
1191
                            break
×
1192
            else:
UNCOV
1193
                paths = " ".join(ps)
×
1194
        return self.to_cmd(
5✔
1195
            paths,
1196
            self.check_only,
1197
            self._bandit,
1198
            self._skip_mypy,
1199
            self._use_dmypy,
1200
            tool=self._tool,
1201
            with_prefix=self._prefix,
1202
        )
1203

1204

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

1208

1209
def lint(
5✔
1210
    files: list[str] | str | None = None,
1211
    dry: bool = False,
1212
    bandit: bool = False,
1213
    skip_mypy: bool = False,
1214
    dmypy: bool = False,
1215
    tool: str = ToolOption.default,
1216
    prefix: bool = False,
1217
) -> None:
1218
    if files is None:
5✔
1219
        files = parse_files(sys.argv[1:])
5✔
1220
    if files and files[0] == "lint":
5✔
1221
        files = files[1:]
5✔
1222
    LintCode(
5✔
1223
        files,
1224
        dry=dry,
1225
        skip_mypy=skip_mypy,
1226
        bandit=bandit,
1227
        dmypy=dmypy,
1228
        tool=tool,
1229
        prefix=prefix,
1230
    ).run()
1231

1232

1233
def check(
5✔
1234
    files: list[str] | str | None = None,
1235
    dry: bool = False,
1236
    bandit: bool = False,
1237
    skip_mypy: bool = False,
1238
    dmypy: bool = False,
1239
    tool: str = ToolOption.default,
1240
) -> None:
1241
    LintCode(
5✔
1242
        files,
1243
        check_only=True,
1244
        _exit=True,
1245
        dry=dry,
1246
        bandit=bandit,
1247
        skip_mypy=skip_mypy,
1248
        dmypy=dmypy,
1249
        tool=tool,
1250
    ).run()
1251

1252

1253
@cli.command(name="lint")
5✔
1254
def make_style(
5✔
1255
    files: list[str] | None = typer.Argument(default=None),  # noqa:B008
1256
    check_only: bool = Option(False, "--check-only", "-c"),
1257
    bandit: bool = Option(False, "--bandit", help="Run `bandit -r <package_dir>`"),
1258
    prefix: bool = Option(
1259
        False,
1260
        "--prefix",
1261
        help="Run lint command with tool prefix, e.g.: pdm run ruff ...",
1262
    ),
1263
    skip_mypy: bool = Option(False, "--skip-mypy"),
1264
    use_dmypy: bool = Option(
1265
        False, "--dmypy", help="Use `dmypy run` instead of `mypy`"
1266
    ),
1267
    tool: str = ToolOption,
1268
    dry: bool = DryOption,
1269
) -> None:
1270
    """Run: ruff check/format to reformat code and then mypy to check"""
1271
    if getattr(files, "default", files) is None:
5✔
1272
        files = ["."]
5✔
1273
    elif isinstance(files, str):
5✔
1274
        files = [files]
5✔
1275
    skip = _ensure_bool(skip_mypy)
5✔
1276
    dmypy = _ensure_bool(use_dmypy)
5✔
1277
    bandit = _ensure_bool(bandit)
5✔
1278
    prefix = _ensure_bool(prefix)
5✔
1279
    tool = _ensure_str(tool)
5✔
1280
    kwargs = {"dry": dry, "skip_mypy": skip, "dmypy": dmypy, "bandit": bandit}
5✔
1281
    if _ensure_bool(check_only):
5✔
1282
        check(files, tool=tool, **kwargs)
5✔
1283
    else:
1284
        lint(files, prefix=prefix, tool=tool, **kwargs)
5✔
1285

1286

1287
@cli.command(name="check")
5✔
1288
def only_check(
5✔
1289
    bandit: bool = Option(False, "--bandit", help="Run `bandit -r <package_dir>`"),
1290
    skip_mypy: bool = Option(False, "--skip-mypy"),
1291
    dry: bool = DryOption,
1292
) -> None:
1293
    """Check code style without reformat"""
1294
    check(dry=dry, bandit=bandit, skip_mypy=_ensure_bool(skip_mypy))
5✔
1295

1296

1297
class Sync(DryRun):
5✔
1298
    def __init__(
5✔
1299
        self, filename: str, extras: str, save: bool, dry: bool = False
1300
    ) -> None:
1301
        self.filename = filename
5✔
1302
        self.extras = extras
5✔
1303
        self._save = save
5✔
1304
        super().__init__(dry=dry)
5✔
1305

1306
    def gen(self) -> str:
5✔
1307
        extras, save = self.extras, self._save
5✔
1308
        should_remove = not Path.cwd().joinpath(self.filename).exists()
5✔
1309
        if not (tool := Project.get_manage_tool()):
5✔
1310
            if should_remove or not is_venv():
5✔
1311
                raise EnvError("There project is not managed by uv/pdm/poetry!")
5✔
1312
            return f"python -m pip install -r {self.filename}"
5✔
1313
        prefix = "" if is_venv() else f"{tool} run "
5✔
1314
        ensure_pip = " {1}python -m ensurepip && {1}python -m pip install -U pip &&"
5✔
1315
        export_cmd = "uv export --no-hashes --all-extras --frozen"
5✔
1316
        if tool in ("poetry", "pdm"):
5✔
1317
            export_cmd = f"{tool} export --without-hashes --with=dev"
5✔
1318
            if tool == "poetry":
5✔
1319
                ensure_pip = ""
5✔
1320
                if not UpgradeDependencies.should_with_dev():
5✔
1321
                    export_cmd = export_cmd.replace(" --with=dev", "")
5✔
1322
                if extras and isinstance(extras, str | list):
5✔
1323
                    export_cmd += f" --{extras=}".replace("'", '"')
5✔
1324
            elif check_call(prefix + "python -m pip --version"):
5✔
1325
                ensure_pip = ""
5✔
1326
        elif check_call(prefix + "python -m pip --version"):
5✔
1327
            ensure_pip = ""
5✔
1328
        install_cmd = (
5✔
1329
            f"{{2}} -o {{0}} &&{ensure_pip} {{1}}python -m pip install -r {{0}}"
1330
        )
1331
        if should_remove and not save:
5✔
1332
            install_cmd += " && rm -f {0}"
5✔
1333
        return install_cmd.format(self.filename, prefix, export_cmd)
5✔
1334

1335

1336
@cli.command()
5✔
1337
def sync(
5✔
1338
    filename: str = "dev_requirements.txt",
1339
    extras: str = Option("", "--extras", "-E"),
1340
    save: bool = Option(
1341
        False, "--save", "-s", help="Whether save the requirement file"
1342
    ),
1343
    dry: bool = DryOption,
1344
) -> None:
1345
    """Export dependencies by poetry to a txt file then install by pip."""
1346
    Sync(filename, extras, save, dry=dry).run()
5✔
1347

1348

1349
def _should_run_test_script(path: Path = Path("scripts")) -> Path | None:
5✔
1350
    for name in ("test.sh", "test.py"):
5✔
1351
        if (file := path / name).exists():
5✔
1352
            return file
5✔
1353
    return None
5✔
1354

1355

1356
def test(dry: bool, ignore_script: bool = False) -> None:
5✔
1357
    cwd = Path.cwd()
5✔
1358
    root = Project.get_work_dir(cwd=cwd, allow_cwd=True)
5✔
1359
    script_dir = root / "scripts"
5✔
1360
    if not _ensure_bool(ignore_script) and (
5✔
1361
        test_script := _should_run_test_script(script_dir)
1362
    ):
1363
        cmd = test_script.relative_to(root).as_posix()
5✔
1364
        if test_script.suffix == ".py":
5✔
1365
            cmd = "python " + cmd
5✔
1366
        if cwd != root:
5✔
1367
            cmd = f"cd {root} && " + cmd
5✔
1368
    else:
1369
        cmd = 'coverage run -m pytest -s && coverage report --omit="tests/*" -m'
5✔
1370
        if not is_venv() or not check_call("coverage --version"):
5✔
1371
            sep = " && "
5✔
1372
            prefix = f"{tool} run " if (tool := Project.get_manage_tool()) else ""
5✔
1373
            cmd = sep.join(prefix + i for i in cmd.split(sep))
5✔
1374
    exit_if_run_failed(cmd, dry=dry)
5✔
1375

1376

1377
@cli.command(name="test")
5✔
1378
def coverage_test(
5✔
1379
    dry: bool = DryOption,
1380
    ignore_script: bool = Option(False, "--ignore-script", "-i"),
1381
) -> None:
1382
    """Run unittest by pytest and report coverage"""
1383
    return test(dry, ignore_script)
5✔
1384

1385

1386
class Publish:
5✔
1387
    class CommandEnum(StrEnum):
5✔
1388
        poetry = "poetry publish --build"
5✔
1389
        pdm = "pdm publish"
5✔
1390
        uv = "uv build && uv publish"
5✔
1391
        twine = "python -m build && twine upload"
5✔
1392

1393
    @classmethod
5✔
1394
    def gen(cls) -> str:
5✔
1395
        if tool := Project.get_manage_tool():
5✔
1396
            return cls.CommandEnum[tool]
5✔
1397
        return cls.CommandEnum.twine
5✔
1398

1399

1400
@cli.command()
5✔
1401
def upload(
5✔
1402
    dry: bool = DryOption,
1403
) -> None:
1404
    """Shortcut for package publish"""
1405
    cmd = Publish.gen()
5✔
1406
    exit_if_run_failed(cmd, dry=dry)
5✔
1407

1408

1409
def dev(
5✔
1410
    port: int | None | OptionInfo,
1411
    host: str | None | OptionInfo,
1412
    file: str | None | ArgumentInfo = None,
1413
    dry: bool = False,
1414
) -> None:
1415
    cmd = "fastapi dev"
5✔
1416
    no_port_yet = True
5✔
1417
    if file is not None:
5✔
1418
        try:
5✔
1419
            port = int(str(file))
5✔
1420
        except ValueError:
5✔
1421
            cmd += f" {file}"
5✔
1422
        else:
1423
            if port != 8000:
5✔
1424
                cmd += f" --port={port}"
5✔
1425
                no_port_yet = False
5✔
1426
    if no_port_yet and (port := getattr(port, "default", port)) and str(port) != "8000":
5✔
1427
        cmd += f" --port={port}"
5✔
1428
    if (host := getattr(host, "default", host)) and host not in (
5✔
1429
        "localhost",
1430
        "127.0.0.1",
1431
    ):
1432
        cmd += f" --host={host}"
5✔
1433
    exit_if_run_failed(cmd, dry=dry)
5✔
1434

1435

1436
@cli.command(name="dev")
5✔
1437
def runserver(
5✔
1438
    file_or_port: str | None = typer.Argument(default=None),
1439
    port: int | None = Option(None, "-p", "--port"),
1440
    host: str | None = Option(None, "-h", "--host"),
1441
    dry: bool = DryOption,
1442
) -> None:
1443
    """Start a fastapi server(only for fastapi>=0.111.0)"""
1444
    if getattr(file_or_port, "default", file_or_port):
5✔
1445
        dev(port, host, file=file_or_port, dry=dry)
5✔
1446
    else:
1447
        dev(port, host, dry=dry)
5✔
1448

1449

1450
@cli.command(name="exec")
5✔
1451
def run_by_subprocess(cmd: str, dry: bool = DryOption) -> None:
5✔
1452
    """Run cmd by subprocess, auto set shell=True when cmd contains '|>'"""
1453
    try:
5✔
1454
        rc = run_and_echo(cmd, verbose=True, dry=_ensure_bool(dry))
5✔
1455
    except FileNotFoundError as e:
5✔
1456
        command = cmd.split()[0]
5✔
1457
        if e.filename == command or (
5✔
1458
            e.filename is None and "系统找不到指定的文件" in str(e)
1459
        ):
1460
            echo(f"Command not found: {command}")
5✔
1461
            raise Exit(1) from None
5✔
UNCOV
1462
        raise e
×
1463
    else:
1464
        if rc:
5✔
1465
            raise Exit(rc)
5✔
1466

1467

1468
class MakeDeps(DryRun):
5✔
1469
    def __init__(
5✔
1470
        self,
1471
        tool: str,
1472
        prod: bool = False,
1473
        dry: bool = False,
1474
        active: bool = True,
1475
        inexact: bool = True,
1476
    ) -> None:
1477
        self._tool = tool
5✔
1478
        self._prod = prod
5✔
1479
        self._active = active
5✔
1480
        self._inexact = inexact
5✔
1481
        super().__init__(dry=dry)
5✔
1482

1483
    def should_ensure_pip(self) -> bool:
5✔
1484
        return True
5✔
1485

1486
    def should_upgrade_pip(self) -> bool:
5✔
UNCOV
1487
        return True
×
1488

1489
    def get_groups(self) -> list[str]:
5✔
1490
        if self._prod:
5✔
1491
            return []
5✔
1492
        return ["dev"]
5✔
1493

1494
    def gen(self) -> str:
5✔
1495
        if self._tool == "pdm":
5✔
1496
            return "pdm install --frozen " + ("--prod" if self._prod else "-G :all")
5✔
1497
        elif self._tool == "uv":
5✔
1498
            uv_sync = "uv sync" + " --inexact" * self._inexact
5✔
1499
            if self._active:
5✔
1500
                uv_sync += " --active"
5✔
1501
            return uv_sync + ("" if self._prod else " --all-extras --all-groups")
5✔
1502
        elif self._tool == "poetry":
5✔
1503
            return "poetry install " + (
5✔
1504
                "--only=main" if self._prod else "--all-extras --all-groups"
1505
            )
1506
        else:
1507
            cmd = "python -m pip install -e ."
5✔
1508
            if gs := self.get_groups():
5✔
1509
                cmd += " " + " ".join(f"--group {g}" for g in gs)
5✔
1510
            upgrade = "python -m pip install --upgrade pip"
5✔
1511
            if self.should_ensure_pip():
5✔
1512
                cmd = f"python -m ensurepip && {upgrade} && {cmd}"
5✔
UNCOV
1513
            elif self.should_upgrade_pip():
×
UNCOV
1514
                cmd = "{upgrade} && {cmd}"
×
1515
            return cmd
5✔
1516

1517

1518
@cli.command(name="deps")
5✔
1519
def make_deps(
5✔
1520
    prod: bool = Option(
1521
        False,
1522
        "--prod",
1523
        help="Only instead production dependencies.",
1524
    ),
1525
    tool: str = ToolOption,
1526
    use_uv: bool = Option(False, "--uv", help="Use `uv` to install deps"),
1527
    use_pdm: bool = Option(False, "--pdm", help="Use `pdm` to install deps"),
1528
    use_pip: bool = Option(False, "--pip", help="Use `pip` to install deps"),
1529
    use_poetry: bool = Option(False, "--poetry", help="Use `poetry` to install deps"),
1530
    active: bool = Option(
1531
        True, help="Add `--active` to uv sync command(Only work for uv project)"
1532
    ),
1533
    inexact: bool = Option(
1534
        True, help="Add `--inexact` to uv sync command(Only work for uv project)"
1535
    ),
1536
    dry: bool = DryOption,
1537
) -> None:
1538
    """Run: ruff check/format to reformat code and then mypy to check"""
UNCOV
1539
    if use_uv + use_pdm + use_pip + use_poetry > 1:
×
UNCOV
1540
        raise UsageError("`--uv/--pdm/--pip/--poetry` can only choose one!")
×
UNCOV
1541
    if use_uv:
×
UNCOV
1542
        tool = "uv"
×
UNCOV
1543
    elif use_pdm:
×
UNCOV
1544
        tool = "pdm"
×
UNCOV
1545
    elif use_pip:
×
UNCOV
1546
        tool = "pip"
×
UNCOV
1547
    elif use_poetry:
×
1548
        tool = "poetry"
×
1549
    elif tool == ToolOption.default:
×
1550
        tool = Project.get_manage_tool(cache=True) or "pip"
×
1551
    MakeDeps(tool, prod, active=active, inexact=inexact, dry=dry).run()
×
1552

1553

1554
class UvPypi(DryRun):
5✔
1555
    PYPI = "https://pypi.org/simple"
5✔
1556
    HOST = "https://files.pythonhosted.org"
5✔
1557

1558
    def __init__(self, lock_file: Path, dry: bool, verbose: bool, quiet: bool) -> None:
5✔
1559
        super().__init__(dry=dry)
5✔
1560
        self.lock_file = lock_file
5✔
1561
        self._verbose = _ensure_bool(verbose)
5✔
1562
        self._quiet = _ensure_bool(quiet)
5✔
1563

1564
    def run(self) -> None:
5✔
1565
        try:
5✔
1566
            rc = self.update_lock(self.lock_file, self._verbose, self._quiet)
5✔
UNCOV
1567
        except ValueError as e:
×
UNCOV
1568
            secho(str(e), fg=typer.colors.RED)
×
UNCOV
1569
            raise Exit(1) from e
×
1570
        else:
1571
            if rc != 0:
5✔
1572
                raise Exit(rc)
5✔
1573

1574
    @classmethod
5✔
1575
    def update_lock(cls, p: Path, verbose: bool, quiet: bool) -> int:
5✔
1576
        text = p.read_text("utf-8")
5✔
1577
        registry_pattern = r'(registry = ")(.*?)"'
5✔
1578
        replace_registry = functools.partial(
5✔
1579
            re.sub, registry_pattern, rf'\1{cls.PYPI}"'
1580
        )
1581
        registry_urls = {i[1] for i in re.findall(registry_pattern, text)}
5✔
1582
        download_pattern = r'(url = ")(https?://.*?)(/packages/.*?\.)(gz|whl)"'
5✔
1583
        replace_host = functools.partial(
5✔
1584
            re.sub, download_pattern, rf'\1{cls.HOST}\3\4"'
1585
        )
1586
        download_hosts = {i[1] for i in re.findall(download_pattern, text)}
5✔
1587
        if not registry_urls:
5✔
UNCOV
1588
            raise ValueError(f"Failed to find pattern {registry_pattern!r} in {p}")
×
1589
        if len(registry_urls) == 1:
5✔
1590
            current_registry = registry_urls.pop()
5✔
1591
            if current_registry == cls.PYPI:
5✔
1592
                if download_hosts == {cls.HOST}:
5✔
1593
                    if verbose:
5✔
UNCOV
1594
                        echo(f"Registry of {p} is {cls.PYPI}, no need to change.")
×
1595
                    return 0
5✔
1596
            else:
1597
                text = replace_registry(text)
5✔
1598
                if verbose:
5✔
UNCOV
1599
                    echo(f"{current_registry} --> {cls.PYPI}")
×
1600
        else:
1601
            # TODO: ask each one to confirm replace
UNCOV
1602
            text = replace_registry(text)
×
1603
            if verbose:
×
UNCOV
1604
                for current_registry in sorted(registry_urls):
×
UNCOV
1605
                    echo(f"{current_registry} --> {cls.PYPI}")
×
1606
        if len(download_hosts) == 1:
5✔
1607
            current_host = download_hosts.pop()
5✔
1608
            if current_host != cls.HOST:
5✔
1609
                text = replace_host(text)
5✔
1610
                if verbose:
5✔
1611
                    print(current_host, "-->", cls.HOST)
×
1612
        elif download_hosts:
×
1613
            # TODO: ask each one to confirm replace
1614
            text = replace_host(text)
×
UNCOV
1615
            if verbose:
×
UNCOV
1616
                for current_host in sorted(download_hosts):
×
UNCOV
1617
                    echo(f"{current_host} --> {cls.HOST}")
×
1618
        size = p.write_text(text, encoding="utf-8")
5✔
1619
        if verbose:
5✔
1620
            echo(f"Updated {p} with {size} bytes.")
×
1621
        if quiet:
5✔
1622
            return 0
5✔
1623
        return 1
5✔
1624

1625

1626
@cli.command()
5✔
1627
def pypi(
5✔
1628
    file: str | None = typer.Argument(default=None),
1629
    dry: bool = DryOption,
1630
    verbose: bool = False,
1631
    quiet: bool = False,
1632
) -> None:
1633
    """Change registry of uv.lock to be pypi.org"""
1634
    if not (p := Path(_ensure_str(file) or "uv.lock")).exists() and not (
5✔
1635
        (p := Project.get_work_dir() / p.name).exists()
1636
    ):
1637
        yellow_warn(f"{p.name!r} not found!")
5✔
1638
        return
5✔
1639
    UvPypi(p, dry, verbose, quiet).run()
5✔
1640

1641

1642
def version_callback(value: bool) -> None:
5✔
1643
    if value:
5✔
1644
        echo("Fast Dev Cli Version: " + typer.style(__version__, bold=True))
5✔
1645
        raise Exit()
5✔
1646

1647

1648
@cli.callback()
1649
def common(
1650
    version: bool = Option(
1651
        None,
1652
        "--version",
1653
        "-V",
1654
        callback=version_callback,
1655
        is_eager=True,
1656
        help="Show the version of this tool",
1657
    ),
1658
) -> None: ...
1659

1660

1661
def main() -> None:
5✔
1662
    cli()
5✔
1663

1664

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