Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,26 @@
# image
*.tar
images/capy/dist/

# data
data/

# macOS
.DS_Store
.AppleDouble
.LSOverride
._*
**/.___*
**/._*
.Spotlight-V100
.Trashes
.fseventsd
.TemporaryItems
.AppleDB
.AppleDesktop
.apdisk
Icon?
.com.apple.timemachine.donotpresent
.VolumeIcon.icns
.cursor

77 changes: 73 additions & 4 deletions cli/localci/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from __future__ import annotations

import logging
import sys
from typing import Any

import click

Expand All @@ -19,15 +19,77 @@
ConfigFileNotFoundError,
ConfigIOError,
ConfigValidationError,
LocalCIError,
)
from localci.utils.output import configure_console, console, print_error
from localci.utils.crash import crash_log_display_path, log_crash
from localci.utils.output import configure_console, print_error

# ---------------------------------------------------------------------------
# Catch-all exception handling
# ---------------------------------------------------------------------------


class CatchAllGroup(click.Group):
"""Click group that catches unhandled exceptions at the CLI entry point."""

def invoke(self, ctx: click.Context) -> Any:
try:
return super().invoke(ctx)
except (click.exceptions.Exit, click.ClickException):
raise
except LocalCIError as exc:
if _is_debug(ctx):
raise
print_error(str(exc))
ctx.exit(1)
except Exception as exc:
if _is_debug(ctx):
raise
log_path = log_crash(exc)
_print_unhandled_error(exc, log_path is not None)
ctx.exit(2)
Comment thread
henry0816191 marked this conversation as resolved.


def _is_debug(ctx: click.Context) -> bool:
"""Return True when ``--debug`` was passed on the CLI."""
obj = ctx.obj
return bool(obj is not None and obj.get("debug"))

Comment thread
henry0816191 marked this conversation as resolved.

def _print_unhandled_error(exc: BaseException, crash_log_written: bool) -> None:
"""Print a user-friendly message for an unhandled internal error."""
if crash_log_written:
attach_hint = (
f"Please file a bug report and attach {crash_log_display_path()} "
"(contains the full traceback)."
)
else:
attach_hint = (
"Please file a bug report; the full traceback was printed to stderr "
"(crash log could not be written)."
)
messages = [
"An unexpected internal error occurred.",
f"{type(exc).__name__}: {exc}",
attach_hint,
]
try:
for msg in messages:
print_error(msg)
except Exception:
for msg in messages:
click.echo(msg, err=True)
Comment thread
henry0816191 marked this conversation as resolved.


# ---------------------------------------------------------------------------
# Root CLI group
# ---------------------------------------------------------------------------


@click.group(context_settings={"help_option_names": ["-h", "--help"]})
@click.group(
cls=CatchAllGroup,
context_settings={"help_option_names": ["-h", "--help"]},
)
@click.option(
"--config",
"-c",
Expand All @@ -36,9 +98,14 @@
default=None,
help="Path to config file (.localci.yml).",
)
@click.option("--verbose", "-v", is_flag=True, help="Enable verbose/debug output.")
@click.option("--verbose", "-v", is_flag=True, help="Enable verbose logging.")
@click.option("--quiet", "-q", is_flag=True, help="Suppress non-essential output.")
@click.option("--no-color", is_flag=True, help="Disable coloured output.")
@click.option(
"--debug",
Comment thread
henry0816191 marked this conversation as resolved.
is_flag=True,
help="Show full tracebacks instead of friendly errors.",
)
@click.version_option(version=__version__, prog_name="localci")
@click.pass_context
def cli(
Expand All @@ -47,9 +114,11 @@ def cli(
verbose: bool,
quiet: bool,
no_color: bool,
debug: bool,
) -> None:
"""Local CI - Run GitHub Actions workflows locally."""
ctx.ensure_object(dict)
ctx.obj["debug"] = debug

# Configure Rich console early so all downstream output respects flags.
configure_console(no_color=no_color, quiet=quiet)
Expand Down
62 changes: 62 additions & 0 deletions cli/localci/utils/crash.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""Crash log utilities for unhandled CLI exceptions."""

from __future__ import annotations

import platform
import sys
import traceback
from datetime import datetime, timezone
from pathlib import Path

from localci import __version__
from localci.utils.paths import localci_home

CRASH_LOG_NAME = "crash.log"


def crash_log_path() -> Path:
"""Return the path to the crash log file (``~/.localci/crash.log``)."""
return localci_home() / CRASH_LOG_NAME


def crash_log_display_path() -> str:
"""Return a short user-facing path for the crash log (e.g. ``~/.localci/crash.log``)."""
path = crash_log_path()
# Canonical layout: always show ~/.localci/crash.log (avoids long paths / terminal wrap).
if path.name == CRASH_LOG_NAME and path.parent.name == ".localci":
return f"~/.localci/{CRASH_LOG_NAME}"
try:
rel = path.relative_to(Path.home())
return "~/" + rel.as_posix()
except ValueError:
return str(path)


def _build_crash_report(exc: BaseException) -> str:
return "".join(
[
f"timestamp: {datetime.now(timezone.utc).isoformat()}\n",
f"localci_version: {__version__}\n",
f"python_version: {sys.version}\n",
f"platform: {platform.platform()}\n",
"\n",
"traceback:\n",
*traceback.format_exception(type(exc), exc, exc.__traceback__),
]
)


def log_crash(exc: BaseException) -> Path | None:
"""Write a full crash report for *exc* and return the log file path.

On write failure, prints the report to stderr and returns ``None``.
"""
path = crash_log_path()
report = _build_crash_report(exc)
try:
path.write_text(report, encoding="utf-8")
return path
except OSError:
sys.stderr.write(f"Could not write crash log to {path}:\n")
sys.stderr.write(report)
return None
Loading
Loading