Function bodies 119 total
FormatTool.execute method · python · L33-L41 (9 LOC)repo_tools/format.py
def execute(self, ctx: ToolContext, args: dict[str, Any]) -> None:
root = ctx.workspace_root
verify = args.get("verify", False)
backends = args.get("backends")
if backends:
self._run_configured_backends(root, backends, verify, ctx)
else:
self._run_auto_detect(root, verify, ctx)FormatTool._run_auto_detect method · python · L43-L51 (9 LOC)repo_tools/format.py
def _run_auto_detect(self, root: Path, verify: bool, ctx: ToolContext) -> None:
"""Auto-detect formatters from repo contents."""
clang_format_file = root / ".clang-format"
if clang_format_file.exists():
self._run_clang_format(root, verify, ctx)
# Python auto-detection
if any((root / marker).exists() for marker in ("pyproject.toml", "setup.py", "ruff.toml")):
self._run_python_formatter(root, verify, "ruff")FormatTool._run_configured_backends method · python · L53-L65 (13 LOC)repo_tools/format.py
def _run_configured_backends(
self, root: Path, backends: list[dict[str, Any]], verify: bool, ctx: ToolContext,
) -> None:
for backend in backends:
backend_type = backend.get("type", "")
if backend_type == "clang-format":
extensions = set(backend.get("extensions", _CLANG_FORMAT_EXTENSIONS))
self._run_clang_format(root, verify, ctx, extensions)
elif backend_type == "python":
tool_name = backend.get("tool", "ruff")
self._run_python_formatter(root, verify, tool_name)
else:
logger.warning(f"Unknown format backend: {backend_type}")FormatTool._run_clang_format method · python · L67-L108 (42 LOC)repo_tools/format.py
def _run_clang_format(
self,
root: Path,
verify: bool,
ctx: ToolContext,
extensions: set[str] | None = None,
) -> None:
if extensions is None:
extensions = _CLANG_FORMAT_EXTENSIONS
exclude_dirs = set(_ALWAYS_EXCLUDE)
build_root = ctx.tokens.get("build_root")
logs_root = ctx.tokens.get("logs_root")
if build_root:
exclude_dirs.add(Path(build_root).name)
if logs_root:
exclude_dirs.add(Path(logs_root).name)
clang_format_exe = require_executable("clang-format", feature="cpp")
clang_format_file = root / ".clang-format"
if not clang_format_file.exists():
logger.error(f".clang-format not found at {clang_format_file}")
sys.exit(1)
source_files = []
for path in root.rglob("*"):
if path.is_file() and path.suffix in extensions:
parts = path.parts
if not any(FormatTool._clang_format_verify method · python · L110-L159 (50 LOC)repo_tools/format.py
def _clang_format_verify(
self, exe: str, style_file: Path, files: list[Path],
) -> None:
logger.info("Running in verify mode (no files will be modified)")
failed_files = []
# Try --dry-run --Werror first (clang-format 10+)
test = subprocess.run(
[exe, "--dry-run", "--Werror", "--style=file", str(files[0])],
capture_output=True, text=True,
)
use_dry_run = test.returncode in (0, 1) # 0=ok, 1=diff found; not "unknown flag"
if use_dry_run:
for batch_start in range(0, len(files), _BATCH_SIZE):
batch = files[batch_start:batch_start + _BATCH_SIZE]
result = subprocess.run(
[exe, "--dry-run", "--Werror", f"--style=file:{style_file}"]
+ [str(f) for f in batch],
capture_output=True, text=True, encoding="utf-8", errors="replace",
)
if result.returncode != 0:
FormatTool._clang_format_inplace method · python · L161-L178 (18 LOC)repo_tools/format.py
def _clang_format_inplace(
self, exe: str, style_file: Path, files: list[Path],
) -> None:
logger.info("Formatting files...")
for batch_start in range(0, len(files), _BATCH_SIZE):
batch = files[batch_start:batch_start + _BATCH_SIZE]
try:
subprocess.run(
[exe, "-i", f"--style=file:{style_file}"]
+ [str(f) for f in batch],
check=True, capture_output=True,
text=True, encoding="utf-8", errors="replace",
)
except subprocess.CalledProcessError as e:
error_msg = e.stderr if e.stderr else str(e)
logger.error(f"Failed to format batch: {error_msg}")
sys.exit(1)
logger.info(f"Successfully formatted {len(files)} file(s)")FormatTool._run_python_formatter method · python · L180-L195 (16 LOC)repo_tools/format.py
def _run_python_formatter(self, root: Path, verify: bool, tool_name: str) -> None:
exe = require_executable(tool_name, feature="python")
if verify:
cmd = [exe, "format", "--check", str(root)]
else:
cmd = [exe, "format", str(root)]
try:
subprocess.run(cmd, check=True)
except subprocess.CalledProcessError:
if verify:
logger.error("Python files are not properly formatted")
else:
logger.error("Python formatting failed")
sys.exit(1)If a scraper extracted this row, it came from Repobility (https://repobility.com)
patch_gitignore function · python · L12-L53 (42 LOC)repo_tools/gitignore.py
def patch_gitignore(
path: Path,
entries: list[str] = ENTRIES,
marker: str = MARKER,
) -> None:
"""Ensure *entries* exist in the gitignore file under *marker*.
Creates the file if absent. Preserves original line endings (CRLF/LF).
Idempotent — does nothing when all entries are already present.
"""
raw = b""
if path.exists():
raw = path.read_bytes()
# Detect line ending style from existing content.
eol = "\r\n" if b"\r\n" in raw else "\n"
text = raw.decode()
existing_lines = {l.rstrip("\r\n") for l in text.splitlines()}
missing = [e for e in entries if e not in existing_lines]
if not missing:
return
parts: list[str] = []
# Ensure trailing newline on existing content.
if text and not text.endswith("\n"):
parts.append(eol)
# Blank separator + marker (only when file already has content and
# the marker isn't present yet).
if text and marker not in existing_lines:
part_is_local_venv function · python · L15-L25 (11 LOC)repo_tools/init.py
def _is_local_venv(workspace_root: Path) -> bool:
"""True when the running Python lives under workspace_root/_tools/venv/.
Avoids resolve() — venv Python is often a symlink to uv-managed Python
in _tools/python/, which would break the path check.
"""
try:
Path(sys.executable).relative_to(workspace_root / "_tools" / "venv")
return True
except ValueError:
return FalseInitTool.execute method · python · L38-L65 (28 LOC)repo_tools/init.py
def execute(self, ctx: ToolContext, args: dict[str, Any]) -> None:
if not _is_local_venv(ctx.workspace_root):
print(
"ERROR: init refused — the running Python is not in this "
"workspace's _tools/venv/. This usually means "
"--workspace-root points to a different project. "
"Bootstrap that project directly instead.",
file=sys.stderr,
)
raise SystemExit(1)
repo_cfg = ctx.config.get("repo", {})
if not isinstance(repo_cfg, dict):
repo_cfg = {}
if args.get("clean"):
self._clean(ctx.workspace_root)
extra_deps = repo_cfg.get("extra_deps", [])
tool_deps = registered_tool_deps()
all_deps = sorted(set(extra_deps + tool_deps))
_bootstrap.run(
framework_root=Path(ctx.tokens["framework_root"]),
workspace_root=ctx.workspace_root,
features=repo_cfg.get("feInitTool._clean method · python · L68-L74 (7 LOC)repo_tools/init.py
def _clean(workspace_root: Path) -> None:
pyproject = workspace_root / "tools" / "pyproject.toml"
lock = workspace_root / "tools" / "uv.lock"
for path in (pyproject, lock):
if path.is_file():
path.unlink()
print(f"Removed {path}")_expand_braces function · python · L27-L41 (15 LOC)repo_tools/package.py
def _expand_braces(pattern: str) -> list[str]:
"""Expand ``{a,b,c}`` brace groups into multiple glob patterns.
Only single-level braces are common in file-extension patterns
(e.g. ``*.{js,wasm}``). Nested braces are handled by recursion.
"""
match = _BRACE_RE.search(pattern)
if not match:
return [pattern]
prefix = pattern[: match.start()]
suffix = pattern[match.end() :]
results: list[str] = []
for alt in match.group(1).split(","):
results.extend(_expand_braces(prefix + alt.strip() + suffix))
return results_extract_glob_base function · python · L44-L66 (23 LOC)repo_tools/package.py
def _extract_glob_base(pattern: str) -> str:
"""Return the longest directory prefix containing no glob metacharacters.
>>> _extract_glob_base("/a/b/c/**/*.exe")
'/a/b/c'
>>> _extract_glob_base("/a/b/*.dll")
'/a/b'
>>> _extract_glob_base("**/*.exe")
'.'
"""
parts = pattern.replace("\\", "/").split("/")
base_parts: list[str] = []
for part in parts:
if any(c in part for c in _GLOB_META):
break
base_parts.append(part)
if not base_parts:
return "."
base = "/".join(base_parts)
# If the entire pattern had no globs, return the parent directory.
if base == pattern.replace("\\", "/"):
return str(Path(base).parent)
return basePackageTool.setup method · python · L73-L92 (20 LOC)repo_tools/package.py
def setup(self, cmd: click.Command) -> click.Command:
cmd = click.option(
"--dry-run",
is_flag=True,
default=None,
help="Show what would be copied without copying",
)(cmd)
cmd = click.option(
"--no-clean",
is_flag=True,
default=None,
help="Do not remove the output directory before packaging",
)(cmd)
cmd = click.option(
"--output-dir",
type=click.Path(),
default=None,
help="Override the output directory",
)(cmd)
return cmdPackageTool.default_args method · python · L94-L100 (7 LOC)repo_tools/package.py
def default_args(self, tokens: dict[str, str]) -> dict[str, Any]:
return {
"dry_run": False,
"no_clean": False,
"output_dir": None,
"mappings": [],
}Citation: Repobility (2026). State of AI-Generated Code. https://repobility.com/research/
PackageTool.execute method · python · L102-L189 (88 LOC)repo_tools/package.py
def execute(self, ctx: ToolContext, args: dict[str, Any]) -> None:
formatter = TokenFormatter(ctx.tokens)
# Resolve output directory: CLI > config > default
output_dir_raw = args.get("output_dir")
if not output_dir_raw:
output_dir_raw = "{workspace_root}/_package/{platform}"
output_dir = Path(formatter.resolve(str(output_dir_raw)))
if not output_dir.is_absolute():
output_dir = ctx.workspace_root / output_dir
dry_run = bool(args.get("dry_run"))
no_clean = bool(args.get("no_clean"))
mappings = args.get("mappings")
if not mappings or not isinstance(mappings, list):
logger.error("No 'mappings' configured in the package section of config.yaml")
sys.exit(1)
# Clean output directory
if not no_clean and output_dir.exists():
if dry_run:
logger.info(f"Would clean: {output_dir}")
else:
logger_git function · python · L31-L39 (9 LOC)test_driver/tools/repo_tools/publish.py
def _git(*args: str, capture: bool = False, cwd: str | Path | None = None) -> str:
result = subprocess.run(
["git", *args],
check=True,
text=True,
capture_output=capture,
cwd=cwd,
)
return result.stdout.strip() if capture else ""PublishTool.setup method · python · L46-L57 (12 LOC)test_driver/tools/repo_tools/publish.py
def setup(self, cmd: click.Command) -> click.Command:
cmd = click.option(
"--dry-run",
default=None,
is_flag=False,
flag_value=".",
help="Preview without changes. Optionally pass a directory to populate with the release tree.",
)(cmd)
cmd = click.option(
"--push", is_flag=True, help="Push release branch and tag to origin"
)(cmd)
return cmdPublishTool.execute method · python · L62-L213 (152 LOC)test_driver/tools/repo_tools/publish.py
def execute(self, ctx: ToolContext, args: dict[str, Any]) -> None:
dry_run = args.get("dry_run")
push = args.get("push", False)
# All git operations must run from the repo root, not the workspace
# root (which may be a subdirectory like test_driver/).
git_root = Path(_git("rev-parse", "--show-toplevel", capture=True))
git = partial(_git, cwd=git_root)
# ── Read version from pyproject.toml ──────────────────────
pyproject_path = git_root / "pyproject.toml"
if not pyproject_path.exists():
logger.error("pyproject.toml not found at git root.")
raise SystemExit(1)
pyproject = tomllib.loads(pyproject_path.read_text(encoding="utf-8"))
version = pyproject.get("project", {}).get("version", "")
if not version:
logger.error("No version found in pyproject.toml [project].version.")
raise SystemExit(1)
if not SEMVER_RE.match(version):
‹ prevpage 3 / 3