From 37d379085cb9954ea54df510595c49f73abe849f Mon Sep 17 00:00:00 2001 From: AdonZ <56778024+adonzone@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:08:16 -0500 Subject: [PATCH 1/3] made the framework --- .github/workflows/ci.yml | 36 ++ .github/workflows/release.yml | 71 ++ .gitignore | 8 + README.md | 71 +- bin/sgit | 17 + packaging/choco/simplegit.nuspec | 21 + packaging/choco/tools/chocolateyinstall.ps1 | 13 + packaging/choco/tools/chocolateyuninstall.ps1 | 7 + packaging/homebrew/simplegit.rb | 22 + packaging/npm/bin/sgit.js | 45 ++ packaging/npm/package.json | 30 + packaging/npm/scripts/postinstall.js | 78 +++ packaging/scoop/simplegit.json | 22 + .../winget/AdonaiAfewerki.SimpleGit.yaml | 21 + pyproject.toml | 36 ++ roadmap.md | 69 ++ scripts/build_zipapp.py | 39 ++ simplegit/__init__.py | 6 + simplegit/__main__.py | 8 + simplegit/cli.py | 53 ++ simplegit/commands/__init__.py | 3 + simplegit/commands/auth.py | 115 ++++ simplegit/commands/branches.py | 82 +++ simplegit/commands/extras.py | 258 ++++++++ simplegit/commands/save.py | 82 +++ simplegit/commands/status_diff.py | 69 ++ simplegit/commands/sync.py | 91 +++ simplegit/commands/undo.py | 52 ++ simplegit/commands/viewer.py | 45 ++ simplegit/core/__init__.py | 3 + simplegit/core/auth.py | 191 ++++++ simplegit/core/extras.py | 319 +++++++++ simplegit/core/models.py | 177 +++++ simplegit/core/native_git.py | 191 ++++++ simplegit/core/operations.py | 606 ++++++++++++++++++ simplegit/core/runner.py | 102 +++ simplegit/errors.py | 179 ++++++ simplegit/ui/__init__.py | 3 + simplegit/ui/render.py | 341 ++++++++++ simplegit/ui/terminal.py | 198 ++++++ simplegit/ui/theme.py | 102 +++ tests/__init__.py | 1 + tests/helpers.py | 66 ++ tests/test_branches_undo.py | 84 +++ tests/test_cli_interactive.py | 75 +++ tests/test_extras_auth.py | 153 +++++ tests/test_native_git.py | 92 +++ tests/test_runner_errors.py | 67 ++ tests/test_save.py | 65 ++ tests/test_sync_init.py | 100 +++ 50 files changed, 4583 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/release.yml create mode 100644 .gitignore create mode 100755 bin/sgit create mode 100644 packaging/choco/simplegit.nuspec create mode 100644 packaging/choco/tools/chocolateyinstall.ps1 create mode 100644 packaging/choco/tools/chocolateyuninstall.ps1 create mode 100644 packaging/homebrew/simplegit.rb create mode 100644 packaging/npm/bin/sgit.js create mode 100644 packaging/npm/package.json create mode 100644 packaging/npm/scripts/postinstall.js create mode 100644 packaging/scoop/simplegit.json create mode 100644 packaging/winget/AdonaiAfewerki.SimpleGit.yaml create mode 100644 pyproject.toml create mode 100644 roadmap.md create mode 100644 scripts/build_zipapp.py create mode 100644 simplegit/__init__.py create mode 100644 simplegit/__main__.py create mode 100644 simplegit/cli.py create mode 100644 simplegit/commands/__init__.py create mode 100644 simplegit/commands/auth.py create mode 100644 simplegit/commands/branches.py create mode 100644 simplegit/commands/extras.py create mode 100644 simplegit/commands/save.py create mode 100644 simplegit/commands/status_diff.py create mode 100644 simplegit/commands/sync.py create mode 100644 simplegit/commands/undo.py create mode 100644 simplegit/commands/viewer.py create mode 100644 simplegit/core/__init__.py create mode 100644 simplegit/core/auth.py create mode 100644 simplegit/core/extras.py create mode 100644 simplegit/core/models.py create mode 100644 simplegit/core/native_git.py create mode 100644 simplegit/core/operations.py create mode 100644 simplegit/core/runner.py create mode 100644 simplegit/errors.py create mode 100644 simplegit/ui/__init__.py create mode 100644 simplegit/ui/render.py create mode 100644 simplegit/ui/terminal.py create mode 100644 simplegit/ui/theme.py create mode 100644 tests/__init__.py create mode 100644 tests/helpers.py create mode 100644 tests/test_branches_undo.py create mode 100644 tests/test_cli_interactive.py create mode 100644 tests/test_extras_auth.py create mode 100644 tests/test_native_git.py create mode 100644 tests/test_runner_errors.py create mode 100644 tests/test_save.py create mode 100644 tests/test_sync_init.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..2fa103b --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,36 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + test: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + python-version: ["3.10", "3.12"] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - uses: actions/setup-node@v4 + with: + node-version: "20" + - name: Run unit and integration tests + run: python -m unittest discover -s tests -v + - name: Build portable zipapp + run: | + python scripts/build_zipapp.py + python dist/sgit.pyz --version + - name: Validate npm package and Python fallback + env: + SGIT_USE_PYTHON: "1" + run: | + node packaging/npm/bin/sgit.js --version + npm pack --dry-run ./packaging/npm diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..01bed82 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,71 @@ +name: Release + +on: + push: + tags: + - "v*" + +permissions: + contents: write + +jobs: + build-binaries: + strategy: + matrix: + include: + - os: macos-latest + asset: sgit-darwin-arm64 + ext: "" + - os: macos-13 + asset: sgit-darwin-x64 + ext: "" + - os: ubuntu-latest + asset: sgit-linux-x64 + ext: "" + - os: windows-latest + asset: sgit-win32-x64.exe + ext: ".exe" + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Install PyInstaller + run: pip install ".[build]" + - name: Build single-file executable + run: | + pyinstaller --onefile --name sgit simplegit/__main__.py + mkdir -p release-assets + cp "dist/sgit${{ matrix.ext }}" "release-assets/${{ matrix.asset }}" + - uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.asset }} + path: release-assets/${{ matrix.asset }} + + publish: + needs: build-binaries + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Download binaries + uses: actions/download-artifact@v4 + with: + path: release-assets + merge-multiple: true + - name: Build Python sdist/wheel and zipapp + run: | + pip install build + python -m build --outdir release-assets + python scripts/build_zipapp.py + cp dist/sgit.pyz release-assets/sgit.pyz + - name: Generate SHA256SUMS.txt + working-directory: release-assets + run: sha256sum * > SHA256SUMS.txt + - name: Create GitHub Release + uses: softprops/action-gh-release@v2 + with: + files: release-assets/* diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ac0e4ec --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +__pycache__/ +*.py[cod] +*.egg-info/ +build/ +dist/ +packaging/npm/vendor/ +.pytest_cache/ +.venv/ diff --git a/README.md b/README.md index 907fb6e..f9e015d 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,69 @@ -# SimpleGit -A simplified Git +# SimpleGit (`sgit`) + +A simplified, cross-platform Git CLI that combines a **native `.git` inspector** (pure Python stdlib) with **system `git` execution**, one-shot workflows, high-visibility colored error diagnostics, and a rich interactive terminal mode (`sgit cli`). + +## Features + +- **One-shot `sgit save "message"`**: Automatically discovers changed files from `git diff` (plus new untracked files unless `--tracked` is passed), stages them, and commits in a single command. Add `--push` (`-p`) to push right away, or `--dry-run` (`-n`) to preview. +- **Rich Interactive Mode (`sgit cli`)**: Keyboard-driven terminal dashboard for reviewing status/diffs, toggling files to save, switching/creating/merging branches, browsing commit history, undoing mistakes, and syncing. +- **Native `.git` Inspection (`sgit inspect`)**: Reads `.git/HEAD`, refs, `packed-refs`, operation sentinels (`MERGE_HEAD`, `REBASE_MERGE`, etc.), and loose `zlib` objects directly via Python stdlib (with `git cat-file` fallback for packfiles). +- **Clear Colored Error Banners**: Translates cryptic Git errors (conflicts, dirty worktrees, non-fast-forward rejections, missing upstream) into readable red `[ERROR]` banners with affected files and copy-pasteable `sgit` recovery hints. +- **Zero Third-Party Runtime Dependencies**: Requires only `git` (>= 2.23) and Python 3.10+ (or prebuilt release binaries). + +## Installation + +### From Source (Development) + +```bash +pip install -e . +# or run directly without installing: +./bin/sgit --help +``` + +### Portable Single-File Executable (`sgit.pyz`) + +```bash +python3 scripts/build_zipapp.py +python3 dist/sgit.pyz --help +``` + +### Package Manager Manifests (in `packaging/`) + +- **Homebrew**: `packaging/homebrew/simplegit.rb` +- **npm (`sgit-cli`)**: `packaging/npm/` (installs `sgit` globally with SHA-256 verified release binary or Python fallback) +- **Chocolatey**: `packaging/choco/` (`simplegit.nuspec`) +- **Scoop / Winget**: `packaging/scoop/simplegit.json`, `packaging/winget/AdonaiAfewerki.SimpleGit.yaml` + +## Quickstart + +```bash +sgit status # Grouped colored status + next-step tip +sgit save "Add login validation" # Diff-discover + stage + commit in one command +sgit save -t "Tracked only" # Stage only tracked files found in git diff +sgit save -p "Update docs" # Save and push immediately +sgit switch -c feat/auth # Create and switch to a new branch +sgit clone -gh AdonZ/SimpleGit # Clone from GitHub (or -gl for GitLab) +sgit clone /path/to/repo.git # Or clone any .git URL / local .git directory +sgit sync # Pull (--rebase) and push (auto-sets upstream) +sgit undo commit # Safely undo last commit, keeping edits staged +sgit undo stage # Unstage files without losing edits +sgit inspect HEAD # Inspect commit object directly from .git/objects +sgit savepoint "wip login" # Temporary savepoint (includes untracked files) +sgit remote add origin -gh u/repo # Link remote using -gh / -gl shorthand +sgit auth login -gh # Authenticate with GitHub (or -gl for GitLab) +sgit conflicts # Inspect & resolve merge conflicts (--ours/--theirs) +sgit ignore --template python # Add starter .gitignore patterns cleanly +sgit tag v0.1.0 --push # Create and push a release tag +sgit doctor # Check Git, identity, auth, and repo health +sgit viewer --files # Visual graph of branches, commits, and files +``` + +## Running Tests + +```bash +python3 -m unittest discover -s tests -v +``` + +## License + +Copyright (c) 2026 Adonai Afewerki. Licensed under the [GNU GPLv3](LICENSE). diff --git a/bin/sgit b/bin/sgit new file mode 100755 index 0000000..cdf64ee --- /dev/null +++ b/bin/sgit @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +"""POSIX launcher for running SimpleGit directly from a source checkout.""" + +from __future__ import annotations + +import os +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from simplegit.cli import main # noqa: E402 + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packaging/choco/simplegit.nuspec b/packaging/choco/simplegit.nuspec new file mode 100644 index 0000000..e34f788 --- /dev/null +++ b/packaging/choco/simplegit.nuspec @@ -0,0 +1,21 @@ + + + + simplegit + 0.1.0 + SimpleGit (sgit) + Adonai Afewerki + https://github.com/AdonZ/SimpleGit + https://github.com/AdonZ/SimpleGit/blob/main/LICENSE + false + A simplified, cross-platform Git CLI with native .git inspection, one-shot workflows, colored error diagnostics, and an interactive terminal UI. + Simplified Git CLI (`sgit`) + git cli vcs simplegit sgit + + + + + + + + diff --git a/packaging/choco/tools/chocolateyinstall.ps1 b/packaging/choco/tools/chocolateyinstall.ps1 new file mode 100644 index 0000000..f7f13b0 --- /dev/null +++ b/packaging/choco/tools/chocolateyinstall.ps1 @@ -0,0 +1,13 @@ +$ErrorActionPreference = 'Stop' + +$toolsDir = Split-Path -Parent $MyInvocation.MyCommand.Definition +$url64 = 'https://github.com/AdonZ/SimpleGit/releases/download/v0.1.0/sgit-win32-x64.exe' +$checksum64 = 'REPLACE_WITH_WIN32_X64_SHA256' +$targetExe = Join-Path $toolsDir 'sgit.exe' + +Get-ChocolateyWebFile ` + -PackageName 'simplegit' ` + -FileFullPath $targetExe ` + -Url64bit $url64 ` + -Checksum64 $checksum64 ` + -ChecksumType64 'sha256' diff --git a/packaging/choco/tools/chocolateyuninstall.ps1 b/packaging/choco/tools/chocolateyuninstall.ps1 new file mode 100644 index 0000000..a5e80a9 --- /dev/null +++ b/packaging/choco/tools/chocolateyuninstall.ps1 @@ -0,0 +1,7 @@ +$ErrorActionPreference = 'Stop' + +$toolsDir = Split-Path -Parent $MyInvocation.MyCommand.Definition +$targetExe = Join-Path $toolsDir 'sgit.exe' +if (Test-Path $targetExe) { + Remove-Item $targetExe -Force +} diff --git a/packaging/homebrew/simplegit.rb b/packaging/homebrew/simplegit.rb new file mode 100644 index 0000000..fbdcdf9 --- /dev/null +++ b/packaging/homebrew/simplegit.rb @@ -0,0 +1,22 @@ +class Simplegit < Formula + include Language::Python::Virtualenv + + desc "Simplified Git CLI with native .git inspection and interactive terminal UI" + homepage "https://github.com/AdonZ/SimpleGit" + url "https://github.com/AdonZ/SimpleGit/archive/refs/tags/v0.1.0.tar.gz" + sha256 "REPLACE_WITH_RELEASE_TARBALL_SHA256" + license "GPL-3.0-or-later" + + depends_on "git" + depends_on "python@3.12" + + def install + virtualenv_install_with_resources + end + + test do + assert_match "SimpleGit", shell_output("#{bin}/sgit --version") + system "#{bin}/sgit", "init", testpath/"repo" + assert_predicate testpath/"repo/.git/HEAD", :exist? + end +end diff --git a/packaging/npm/bin/sgit.js b/packaging/npm/bin/sgit.js new file mode 100644 index 0000000..818bae4 --- /dev/null +++ b/packaging/npm/bin/sgit.js @@ -0,0 +1,45 @@ +#!/usr/bin/env node +"use strict"; + +const { spawnSync } = require("node:child_process"); +const fs = require("node:fs"); +const path = require("node:path"); + +const vendorExe = path.join( + __dirname, + "..", + "vendor", + process.platform === "win32" ? "sgit.exe" : "sgit" +); +const repoRoot = path.resolve(__dirname, "..", "..", ".."); +const hasLocalPkg = fs.existsSync(path.join(repoRoot, "simplegit", "__main__.py")); +const usePython = process.env.SGIT_USE_PYTHON === "1" || !fs.existsSync(vendorExe); + +if (!usePython && fs.existsSync(vendorExe)) { + const res = spawnSync(vendorExe, process.argv.slice(2), { stdio: "inherit" }); + process.exit(res.status === null ? 1 : res.status); +} + +const pythonCandidates = + process.platform === "win32" ? [["py", ["-3"]], ["python", []]] : [["python3", []], ["python", []]]; + +const env = { ...process.env }; +if (hasLocalPkg) { + env.PYTHONPATH = env.PYTHONPATH ? `${repoRoot}${path.delimiter}${env.PYTHONPATH}` : repoRoot; +} + +for (const [cmd, prefixArgs] of pythonCandidates) { + const res = spawnSync(cmd, [...prefixArgs, "-m", "simplegit", ...process.argv.slice(2)], { + stdio: "inherit", + env, + }); + if (!res.error) { + process.exit(res.status === null ? 1 : res.status); + } +} + +console.error( + "sgit-cli error: neither the prebuilt sgit binary nor Python 3.10+ was found.\n" + + "Reinstall sgit-cli or install Python 3.10+ and Git." +); +process.exit(1); diff --git a/packaging/npm/package.json b/packaging/npm/package.json new file mode 100644 index 0000000..9cf3e6f --- /dev/null +++ b/packaging/npm/package.json @@ -0,0 +1,30 @@ +{ + "name": "sgit-cli", + "version": "0.1.0", + "description": "SimpleGit (sgit): simplified Git workflows, native .git inspection, and interactive CLI", + "license": "GPL-3.0-or-later", + "repository": { + "type": "git", + "url": "https://github.com/AdonZ/SimpleGit.git" + }, + "bin": { + "sgit": "./bin/sgit.js" + }, + "scripts": { + "postinstall": "node ./scripts/postinstall.js" + }, + "files": [ + "bin/", + "scripts/" + ], + "keywords": [ + "git", + "cli", + "simplegit", + "sgit", + "vcs" + ], + "engines": { + "node": ">=18" + } +} diff --git a/packaging/npm/scripts/postinstall.js b/packaging/npm/scripts/postinstall.js new file mode 100644 index 0000000..f5800d2 --- /dev/null +++ b/packaging/npm/scripts/postinstall.js @@ -0,0 +1,78 @@ +"use strict"; + +const crypto = require("node:crypto"); +const fs = require("node:fs"); +const https = require("node:https"); +const path = require("node:path"); +const pkg = require("../package.json"); + +if (process.env.SGIT_SKIP_DOWNLOAD === "1") { + process.exit(0); +} + +const TARGETS = { + "darwin-arm64": "sgit-darwin-arm64", + "darwin-x64": "sgit-darwin-x64", + "linux-x64": "sgit-linux-x64", + "linux-arm64": "sgit-linux-arm64", + "win32-x64": "sgit-win32-x64.exe", +}; + +const key = `${process.platform}-${process.arch}`; +const asset = TARGETS[key]; +if (!asset) { + console.warn(`[sgit-cli] No prebuilt binary for ${key}; will fall back to python3 -m simplegit.`); + process.exit(0); +} + +const repo = process.env.SGIT_RELEASE_REPO || "AdonZ/SimpleGit"; +const baseUrl = `https://github.com/${repo}/releases/download/v${pkg.version}`; +const vendorDir = path.join(__dirname, "..", "vendor"); +const destFile = path.join(vendorDir, process.platform === "win32" ? "sgit.exe" : "sgit"); + +function fetchBuffer(url, redirects = 0) { + return new Promise((resolve, reject) => { + if (redirects > 5) return reject(new Error("Too many redirects")); + https + .get(url, (res) => { + if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { + return resolve(fetchBuffer(res.headers.location, redirects + 1)); + } + if (res.statusCode !== 200) { + return reject(new Error(`HTTP ${res.statusCode} fetching ${url}`)); + } + const chunks = []; + res.on("data", (c) => chunks.push(c)); + res.on("end", () => resolve(Buffer.concat(chunks))); + }) + .on("error", reject); + }); +} + +(async () => { + try { + const [sumsBuf, binBuf] = await Promise.all([ + fetchBuffer(`${baseUrl}/SHA256SUMS.txt`), + fetchBuffer(`${baseUrl}/${asset}`), + ]); + const expectedLine = sumsBuf + .toString("utf8") + .split(/\r?\n/) + .find((ln) => ln.trim().endsWith(asset)); + if (!expectedLine) { + throw new Error(`Checksum entry for ${asset} missing in SHA256SUMS.txt`); + } + const expectedSha = expectedLine.trim().split(/\s+/)[0].toLowerCase(); + const actualSha = crypto.createHash("sha256").update(binBuf).digest("hex").toLowerCase(); + if (expectedSha !== actualSha) { + throw new Error(`SHA-256 mismatch for ${asset}: expected ${expectedSha}, got ${actualSha}`); + } + fs.mkdirSync(vendorDir, { recursive: true }); + fs.writeFileSync(destFile, binBuf); + if (process.platform !== "win32") { + fs.chmodSync(destFile, 0o755); + } + } catch (err) { + console.warn(`[sgit-cli] Binary download skipped (${err.message}); Python fallback will be used.`); + } +})(); diff --git a/packaging/scoop/simplegit.json b/packaging/scoop/simplegit.json new file mode 100644 index 0000000..b625434 --- /dev/null +++ b/packaging/scoop/simplegit.json @@ -0,0 +1,22 @@ +{ + "version": "0.1.0", + "description": "Simplified Git CLI with native .git inspection and interactive terminal UI", + "homepage": "https://github.com/AdonZ/SimpleGit", + "license": "GPL-3.0-or-later", + "depends": "git", + "architecture": { + "64bit": { + "url": "https://github.com/AdonZ/SimpleGit/releases/download/v0.1.0/sgit-win32-x64.exe#/sgit.exe", + "hash": "REPLACE_WITH_WIN32_X64_SHA256" + } + }, + "bin": "sgit.exe", + "checkver": "github", + "autoupdate": { + "architecture": { + "64bit": { + "url": "https://github.com/AdonZ/SimpleGit/releases/download/v$version/sgit-win32-x64.exe#/sgit.exe" + } + } + } +} diff --git a/packaging/winget/AdonaiAfewerki.SimpleGit.yaml b/packaging/winget/AdonaiAfewerki.SimpleGit.yaml new file mode 100644 index 0000000..4f8d80a --- /dev/null +++ b/packaging/winget/AdonaiAfewerki.SimpleGit.yaml @@ -0,0 +1,21 @@ +PackageIdentifier: AdonaiAfewerki.SimpleGit +PackageVersion: 0.1.0 +PackageLocale: en-US +Publisher: Adonai Afewerki +PackageName: SimpleGit +License: GPL-3.0-or-later +ShortDescription: Simplified Git CLI (`sgit`) with one-shot workflows and interactive terminal UI +Moniker: sgit +Commands: + - sgit +Dependencies: + PackageDependencies: + - PackageIdentifier: Git.Git +Installers: + - Architecture: x64 + InstallerType: portable + NestedInstallerType: portable + InstallerUrl: https://github.com/AdonZ/SimpleGit/releases/download/v0.1.0/sgit-win32-x64.exe + InstallerSha256: REPLACE_WITH_WIN32_X64_SHA256 +ManifestType: singleton +ManifestVersion: 1.6.0 diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..71164ca --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,36 @@ +[build-system] +requires = ["setuptools>=68"] +build-backend = "setuptools.build_meta" + +[project] +name = "simplegit" +version = "0.1.0" +description = "A simplified, cross-platform Git CLI with native .git inspection and interactive mode" +readme = "README.md" +requires-python = ">=3.10" +license = { text = "GPL-3.0-or-later" } +authors = [{ name = "Adonai Afewerki" }] +keywords = ["git", "cli", "vcs", "developer-tools", "terminal"] +classifiers = [ + "Development Status :: 4 - Beta", + "Environment :: Console", + "Intended Audience :: Developers", + "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Topic :: Software Development :: Version Control :: Git", +] +dependencies = [] + +[project.optional-dependencies] +build = ["pyinstaller>=6.0"] + +[project.scripts] +sgit = "simplegit.cli:main" + +[tool.setuptools.packages.find] +include = ["simplegit*"] diff --git a/roadmap.md b/roadmap.md new file mode 100644 index 0000000..fa6e86d --- /dev/null +++ b/roadmap.md @@ -0,0 +1,69 @@ +# SimpleGit (`sgit`) Roadmap + +A cross-platform, simplified Git CLI licensed under GNU GPLv3 (see [LICENSE](LICENSE)) that combines a native `.git` inspector with safe `git` subprocess execution, one-shot workflows, high-visibility colored error diagnostics, and a rich interactive terminal mode (`sgit cli`). + +--- + +## Architecture Overview + +- **Hybrid `.git` Engine**: + - **Native `.git` Inspector (`simplegit/core/native_git.py`)**: pure Python 3.10+ standard library (`pathlib`, `zlib`, `hashlib`) for repository/worktree discovery, `HEAD`/refs/`packed-refs` resolution, in-progress operation detection (`MERGE_HEAD`, `REBASE_*`, `CHERRY_PICK_HEAD`, `REVERT_HEAD`), and loose `.git/objects` decompression and SHA-1 verification. + - **System `git` Runner (`simplegit/core/runner.py`)**: safe `subprocess` execution with NUL-delimited (`-z`) porcelain parsing for index mutations, diffs, merges, hooks, signing, and remote transport (`clone`, `fetch`, `pull`, `push`). +- **Zero Third-Party Runtime Dependencies**: + - Only Python 3.10+ stdlib and the system `git` binary (>= 2.23) are required at runtime. +- **Multi-Package-Manager Distribution**: + - PyPI / `pipx` / `uv` (`pyproject.toml`), portable `sgit.pyz` zipapp, Homebrew (`simplegit.rb`), npm (`sgit-cli`), Chocolatey (`simplegit.nuspec`), Scoop, Winget, and GitHub Actions standalone binaries. + +--- + +## Phase 1: Foundation, UI & Error Diagnostics + +- [x] Set up `pyproject.toml` (`sgit` console entrypoint, GPL-3.0-or-later, zero runtime dependencies) and `bin/sgit` launcher +- [x] Implement `simplegit/errors.py` (`SimpleGitError` hierarchy and `translate_git_error()` stderr-to-hint translator) +- [x] Implement `simplegit/ui/theme.py` (cross-platform ANSI colors, `NO_COLOR`/`FORCE_COLOR`, Windows VT100 enabling) +- [x] Implement `simplegit/ui/render.py` (bold red `✗ ERROR:` banners, grouped status, colored diffs, commit logs, object views) +- [x] Implement `simplegit/ui/terminal.py` (POSIX `termios`/`tty` and Windows `msvcrt` raw key reader with non-TTY fallback) + +--- + +## Phase 2: Hybrid `.git` Core Engine + +- [x] Implement `simplegit/core/models.py` (`RepoLocation`, `FileChange`, `RepoState`, `BranchInfo`, `CommitInfo`, `GitObject`, `SavePlan`) +- [x] Implement `simplegit/core/native_git.py` (`.git` discovery, `HEAD`/`packed-refs`, merge/rebase state detection, `zlib` loose object reader, commit/tree parsers) +- [x] Implement `simplegit/core/runner.py` (`git` binary/version probe, `-z` NUL-delimited porcelain parser, error translation) +- [x] Implement `simplegit/core/operations.py` (composed workflows for status, diff-based save staging, branches, merge, undo, sync, and native object inspection) + +--- + +## Phase 3: One-Shot CLI Commands & Rich Interactive Mode + +- [x] Implement `simplegit/cli.py` and `simplegit/__main__.py` (`argparse` dispatcher, `--version`, `--no-color`, unified error handler) +- [x] `sgit save "msg" [files...]` — instant `git diff` + untracked discovery, staging, commit, `--tracked`/`-t`, `--push`/`-p`, `--amend`, `--dry-run` +- [x] `sgit status` (`st`), `sgit diff`, `sgit log`, `sgit inspect ` +- [x] `sgit branch` (`br`), `sgit switch` (`sw`, `-c/--create`), `sgit merge` (`--abort`, `--continue`) +- [x] `sgit undo` — `commit` (soft reset), `stage` (unstage), `changes` (restore with confirmation or `-y/--yes`) +- [x] `sgit init`, `sgit clone`, `sgit sync` (`pull --rebase` default + `--merge` + `--autostash` + auto `-u` push), `sgit pull`, `sgit push` +- [x] `sgit cli` — interactive terminal dashboard with live repo header, file multi-select for save, inline diff viewer, branch switcher, commit/object browser, undo wizard, and sync + +--- + +## Phase 4: Cross-Platform Packaging & CI/CD + +- [x] `scripts/build_zipapp.py` — single-file portable `dist/sgit.pyz` builder +- [x] `packaging/homebrew/simplegit.rb` — Homebrew formula (`depends_on "git"`, `depends_on "python@3.12"`) +- [x] `packaging/npm/` (`sgit-cli`) — `package.json`, `bin/sgit.js`, `scripts/postinstall.js` (checksum-verified binary download + Python fallback) +- [x] `packaging/choco/` — `simplegit.nuspec`, `chocolateyinstall.ps1`, `chocolateyuninstall.ps1` +- [x] `packaging/scoop/simplegit.json` and `packaging/winget/AdonaiAfewerki.SimpleGit.yaml` +- [x] `.github/workflows/ci.yml` — cross-platform `unittest` matrix (`ubuntu-latest`, `macos-latest`, `windows-latest`) +- [x] `.github/workflows/release.yml` — tagged release builds (PyInstaller standalone binaries, `SHA256SUMS.txt`, wheels/sdist, `.nupkg`) +- [x] Update `README.md` with installation and usage documentation + +--- + +## Phase 5: Verification + +- [x] Unit tests for native `.git` discovery, refs, and loose `zlib` object parsing (`tests/test_native_git.py`) +- [x] Error translation tests (`tests/test_runner_errors.py`) +- [x] Integration tests for `save`, `branch`/`switch`/`merge`/`undo`, and `init`/`clone`/`sync` (`tests/test_save.py`, `tests/test_branches_undo.py`, `tests/test_sync_init.py`) +- [x] CLI & interactive non-TTY fallback tests plus npm launcher validation (`tests/test_cli_interactive.py`) +- [x] Local end-to-end verification (`unittest`, `sgit.pyz`, `npm pack --dry-run`) diff --git a/scripts/build_zipapp.py b/scripts/build_zipapp.py new file mode 100644 index 0000000..6072b25 --- /dev/null +++ b/scripts/build_zipapp.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""Build a single-file portable `dist/sgit.pyz` zipapp using Python stdlib.""" + +from __future__ import annotations + +import shutil +import tempfile +import zipapp +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SRC_PKG = ROOT / "simplegit" +DIST_DIR = ROOT / "dist" +OUT_FILE = DIST_DIR / "sgit.pyz" + + +def main() -> int: + DIST_DIR.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory() as tmpdir: + stage = Path(tmpdir) / "app" + stage.mkdir(parents=True, exist_ok=True) + shutil.copytree( + SRC_PKG, + stage / "simplegit", + ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "*.pyo"), + ) + zipapp.create_archive( + stage, + target=OUT_FILE, + interpreter="/usr/bin/env python3", + main="simplegit.cli:main", + compressed=True, + ) + print(f"Built portable zipapp: {OUT_FILE}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/simplegit/__init__.py b/simplegit/__init__.py new file mode 100644 index 0000000..123dc9c --- /dev/null +++ b/simplegit/__init__.py @@ -0,0 +1,6 @@ +"""SimpleGit (`sgit`): A simplified, cross-platform Git CLI.""" + +from __future__ import annotations + +__version__ = "0.1.0" +__all__ = ["__version__"] diff --git a/simplegit/__main__.py b/simplegit/__main__.py new file mode 100644 index 0000000..cb90382 --- /dev/null +++ b/simplegit/__main__.py @@ -0,0 +1,8 @@ +"""Allow running SimpleGit via `python3 -m simplegit`.""" + +from __future__ import annotations + +from simplegit.cli import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/simplegit/cli.py b/simplegit/cli.py new file mode 100644 index 0000000..8dc356a --- /dev/null +++ b/simplegit/cli.py @@ -0,0 +1,53 @@ +"""Top-level CLI parser, subcommand dispatcher, and unified error handler.""" + +from __future__ import annotations + +import argparse +import sys + +from simplegit import __version__ +from simplegit.commands import auth, branches, extras, save, status_diff, sync, undo, viewer +from simplegit.errors import SimpleGitError +from simplegit.ui.render import render_error +from simplegit.ui.theme import THEME + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="sgit", + description="SimpleGit — simplified Git workflows, native .git inspection, and interactive CLI.", + ) + parser.add_argument("-V", "--version", action="version", version=f"SimpleGit {__version__}") + parser.add_argument("--no-color", action="store_true", help="Disable colored terminal output") + + subparsers = parser.add_subparsers(dest="command", metavar="") + save.register(subparsers) + status_diff.register(subparsers) + branches.register(subparsers) + undo.register(subparsers) + sync.register(subparsers) + extras.register(subparsers) + auth.register(subparsers) + viewer.register(subparsers) + return parser + + +def main(argv: list[str] | None = None) -> int: + parser = build_parser() + args = parser.parse_args(argv) + + if args.no_color: + THEME._force_no_color = True + + if not getattr(args, "handler", None): + parser.print_help() + return 0 + + try: + return int(args.handler(args)) + except SimpleGitError as exc: + render_error(exc) + return exc.exit_code + except KeyboardInterrupt: + print("\n" + THEME.muted("Interrupted."), file=sys.stderr) + return 130 diff --git a/simplegit/commands/__init__.py b/simplegit/commands/__init__.py new file mode 100644 index 0000000..a8ae1ab --- /dev/null +++ b/simplegit/commands/__init__.py @@ -0,0 +1,3 @@ +"""CLI subcommand handlers for SimpleGit.""" + +from __future__ import annotations diff --git a/simplegit/commands/auth.py b/simplegit/commands/auth.py new file mode 100644 index 0000000..bf368d0 --- /dev/null +++ b/simplegit/commands/auth.py @@ -0,0 +1,115 @@ +"""Handlers for `sgit auth` (GitHub & GitLab HTTPS token and SSH authentication).""" + +from __future__ import annotations + +import argparse +import getpass + +from simplegit.core.auth import ( + clear_https_credentials, + find_ssh_public_keys, + generate_ssh_key, + get_auth_status, + host_for_provider, + store_https_credentials, + verify_provider_token, +) +from simplegit.core.runner import run_git +from simplegit.errors import SimpleGitError +from simplegit.ui.terminal import confirm, prompt_line +from simplegit.ui.theme import THEME + + +def register(subparsers: argparse._SubParsersAction) -> None: + auth = subparsers.add_parser("auth", help="Authenticate with GitHub or GitLab (HTTPS token or SSH)") + auth_sub = auth.add_subparsers(dest="auth_action", metavar="") + + login = auth_sub.add_parser("login", help="Log in to GitHub or GitLab") + _add_provider_flags(login) + login.add_argument("--token", help="Personal Access Token (if omitted, prompts securely)") + login.add_argument("-u", "--username", help="Username (used with `--skip-verify`)") + login.add_argument("--skip-verify", action="store_true", help="Store token without calling the provider API") + login.add_argument("--ssh", action="store_true", help="Set up / display SSH public key instead of HTTPS token") + login.set_defaults(handler=run_login) + + status = auth_sub.add_parser("status", help="Show GitHub and GitLab authentication status") + status.set_defaults(handler=run_status) + + logout = auth_sub.add_parser("logout", help="Remove stored HTTPS credentials for a provider") + _add_provider_flags(logout) + logout.set_defaults(handler=run_logout) + + auth.set_defaults(handler=run_status) + + +def _add_provider_flags(parser: argparse.ArgumentParser) -> None: + group = parser.add_mutually_exclusive_group() + group.add_argument("-gh", "--github", action="store_true", help="Target GitHub (github.com)") + group.add_argument("-gl", "--gitlab", action="store_true", help="Target GitLab (gitlab.com)") + parser.add_argument("--host", help="Custom GitHub Enterprise / self-hosted GitLab domain") + + +def run_login(args: argparse.Namespace) -> int: + host = host_for_provider(github=bool(args.github), gitlab=bool(args.gitlab), custom_host=args.host) + is_gitlab = bool(args.gitlab) or ("gitlab" in host.lower()) + + if args.ssh: + return _handle_ssh_setup(host, is_gitlab) + + token = args.token or getpass.getpass(f"Paste Personal Access Token for {host} (input hidden): ").strip() + if not token: + raise SimpleGitError("No token provided.", hint="Create a Personal Access Token and pass it or paste at the prompt.") + + if args.skip_verify: + username = args.username or prompt_line(f"Username for {host}", "git") + else: + print(THEME.muted(f"Verifying token with {host}...")) + username = verify_provider_token(host, token, is_gitlab=is_gitlab) + + helper = store_https_credentials(host, username, token) + print(THEME.success(f"✓ Authenticated as @{username} on {host}") + THEME.muted(f" (stored via `{helper}`)")) + return 0 + + +def _handle_ssh_setup(host: str, is_gitlab: bool) -> int: + keys = find_ssh_public_keys() + if not keys: + if not confirm("No SSH public keys found in ~/.ssh. Generate an ed25519 key now?", default=True): + return 0 + default_email = run_git(["config", "--get", "user.email"], check=False).stdout.strip() + email = prompt_line("Email for SSH key", default_email or "user@example.com") + pub_path = generate_ssh_key(email) + keys = [pub_path] + print(THEME.success(f"✓ Generated SSH key: {pub_path}")) + + pub_key = keys[0] + settings_url = ( + f"https://{host}/-/user_settings/ssh_keys" + if is_gitlab + else f"https://{host}/settings/keys" + ) + print(f"\n{THEME.bold('Public key')} ({pub_key}):") + print(THEME.info(pub_key.read_text(encoding="utf-8", errors="replace").strip())) + print(f"\n{THEME.muted('Add this key at:')} {settings_url}") + print(THEME.muted(f"Test with: `ssh -T git@{host}`")) + return 0 + + +def run_status(_args: argparse.Namespace) -> int: + statuses = get_auth_status() + print(THEME.bold("Authentication Status")) + for item in statuses: + if item.https_user: + https_str = THEME.success(f"✓ HTTPS (@{item.https_user})") + else: + https_str = THEME.muted("not logged in via HTTPS") + ssh_str = THEME.info(f"SSH keys: {', '.join(item.ssh_keys)}") if item.ssh_keys else THEME.muted("no SSH keys") + print(f" {THEME.bold(item.host)}: {https_str} | {ssh_str}") + return 0 + + +def run_logout(args: argparse.Namespace) -> int: + host = host_for_provider(github=bool(args.github), gitlab=bool(args.gitlab), custom_host=args.host) + clear_https_credentials(host) + print(THEME.success(f"✓ Removed stored HTTPS credentials for {host}.")) + return 0 diff --git a/simplegit/commands/branches.py b/simplegit/commands/branches.py new file mode 100644 index 0000000..b5d1478 --- /dev/null +++ b/simplegit/commands/branches.py @@ -0,0 +1,82 @@ +"""Handlers for `sgit branch`, `sgit switch`, and `sgit merge`.""" + +from __future__ import annotations + +import argparse + +from simplegit.core.native_git import discover_repo +from simplegit.core.operations import ( + create_branch, + delete_branch, + list_branches, + merge_branch, + switch_branch, +) +from simplegit.ui.render import render_branches +from simplegit.ui.theme import THEME + + +def register(subparsers: argparse._SubParsersAction) -> None: + br = subparsers.add_parser("branch", aliases=["br"], help="List, create, or delete branches") + br.add_argument("name", nargs="?", help="Branch name to create or delete") + br.add_argument("-a", "--all", action="store_true", help="Include remote-tracking branches") + br.add_argument("-d", "--delete", action="store_true", help="Delete the named branch") + br.add_argument("-f", "--force", action="store_true", help="Force delete even if unmerged") + br.set_defaults(handler=run_branch) + + sw = subparsers.add_parser("switch", aliases=["sw"], help="Switch to a branch (or create with -c)") + sw.add_argument("name", help="Target branch name") + sw.add_argument("-c", "--create", action="store_true", help="Create the branch and switch to it") + sw.set_defaults(handler=run_switch) + + mg = subparsers.add_parser("merge", help="Merge another branch into the current branch") + mg.add_argument("branch", nargs="?", help="Branch to merge") + mg.add_argument("--abort", action="store_true", help="Abort an in-progress conflicted merge") + mg.add_argument("--continue", dest="continue_merge", action="store_true", help="Finish merge after resolving conflicts") + mg.set_defaults(handler=run_merge) + + +def run_branch(args: argparse.Namespace) -> int: + location = discover_repo() + if args.delete: + if not args.name: + raise SystemExit("Specify a branch name to delete.") + delete_branch(location.root, args.name, force=bool(args.force)) + print(THEME.success(f"✓ Deleted branch '{args.name}'.")) + return 0 + + if args.name: + create_branch(location.root, args.name) + print(THEME.success(f"✓ Created branch '{args.name}'.") + THEME.muted(f" (Run `sgit switch {args.name}` to switch)")) + return 0 + + branches = list_branches(location.root, include_remote=bool(args.all)) + render_branches(branches) + return 0 + + +def run_switch(args: argparse.Namespace) -> int: + location = discover_repo() + switch_branch(location.root, args.name, create=bool(args.create)) + verb = "Created and switched to" if args.create else "Switched to" + print(THEME.success(f"✓ {verb} branch '{args.name}'.")) + return 0 + + +def run_merge(args: argparse.Namespace) -> int: + location = discover_repo() + out = merge_branch( + location.root, + branch=args.branch, + abort=bool(args.abort), + continue_merge=bool(args.continue_merge), + ) + if out.strip(): + print(out.strip()) + if args.abort: + print(THEME.warn("Merge aborted.")) + elif args.continue_merge: + print(THEME.success("✓ Merge completed.")) + else: + print(THEME.success(f"✓ Merged '{args.branch}'.")) + return 0 diff --git a/simplegit/commands/extras.py b/simplegit/commands/extras.py new file mode 100644 index 0000000..8e30463 --- /dev/null +++ b/simplegit/commands/extras.py @@ -0,0 +1,258 @@ +"""Handlers for `savepoint`, `remote`, `conflicts`, `ignore`, `tag`, and `doctor`.""" + +from __future__ import annotations + +import argparse + +from simplegit.core.extras import ( + add_ignore_patterns, + add_remote, + create_tag, + delete_tag, + inspect_conflicts, + list_ignore_patterns, + list_remotes, + list_tags, + remove_remote, + resolve_conflicts, + run_doctor, + savepoint_drop, + savepoint_list, + savepoint_pop, + savepoint_push, + set_remote_url, +) +from simplegit.core.native_git import discover_repo +from simplegit.ui.theme import THEME + + +def register(subparsers: argparse._SubParsersAction) -> None: + sp = subparsers.add_parser( + "savepoint", + aliases=["sp"], + help="Manage temporary savepoints (clearer alternative to `git stash`)", + ) + sp.add_argument( + "action", + nargs="?", + default="list", + help="Message to save, or sub-action: `list`, `pop`, `apply`, `drop`", + ) + sp.add_argument("target", nargs="?", help="Message (with `push`) or numeric index (with `pop`/`apply`/`drop`)") + sp.set_defaults(handler=run_savepoint) + + rem = subparsers.add_parser("remote", help="List, add, or update remotes (supports -gh / -gl)") + rem_sub = rem.add_subparsers(dest="remote_action", metavar="") + + rem_add = rem_sub.add_parser("add", help="Add a remote") + rem_add.add_argument("name", help="Remote name (e.g. origin)") + rem_add.add_argument("url", help="Repository shorthand (with -gh/-gl), URL, or `.git` path") + _add_host_flags(rem_add) + rem_add.set_defaults(handler=run_remote_add) + + rem_set = rem_sub.add_parser("set-url", help="Update a remote URL") + rem_set.add_argument("name", help="Remote name") + rem_set.add_argument("url", help="New URL or shorthand") + _add_host_flags(rem_set) + rem_set.set_defaults(handler=run_remote_set_url) + + rem_rm = rem_sub.add_parser("remove", aliases=["rm"], help="Remove a remote") + rem_rm.add_argument("name", help="Remote name") + rem_rm.set_defaults(handler=run_remote_remove) + + rem.set_defaults(handler=run_remote_list) + + conf = subparsers.add_parser("conflicts", help="Inspect or resolve merge conflicts") + side = conf.add_mutually_exclusive_group() + side.add_argument("--ours", action="store_true", help="Keep our branch's version for given files") + side.add_argument("--theirs", action="store_true", help="Keep incoming branch's version for given files") + conf.add_argument("files", nargs="*", help="Files to resolve when using --ours or --theirs") + conf.set_defaults(handler=run_conflicts) + + ign = subparsers.add_parser("ignore", help="Add patterns or starter templates to .gitignore") + ign.add_argument("patterns", nargs="*", help="Patterns to add (e.g. '*.log' .env)") + ign.add_argument("-t", "--template", help="Starter template: python, node, macos, general") + ign.add_argument("-l", "--list", action="store_true", help="List current .gitignore patterns") + ign.set_defaults(handler=run_ignore) + + tg = subparsers.add_parser("tag", help="List, create (+ optionally push), or delete tags") + tg.add_argument("name", nargs="?", help="Tag name (omit to list tags)") + tg.add_argument("-m", "--message", help="Annotated tag message") + tg.add_argument("-p", "--push", action="store_true", help="Push tag to origin after creating") + tg.add_argument("-d", "--delete", action="store_true", help="Delete the named tag") + tg.add_argument("--remote", action="store_true", help="Also delete tag on origin when using -d") + tg.set_defaults(handler=run_tag) + + doc = subparsers.add_parser("doctor", help="Check Git, identity, auth, and repository health") + doc.set_defaults(handler=run_doctor_cmd) + + +def _add_host_flags(parser: argparse.ArgumentParser) -> None: + group = parser.add_mutually_exclusive_group() + group.add_argument("-gh", "--github", action="store_true", help="Expand `owner/repo` as GitHub") + group.add_argument("-gl", "--gitlab", action="store_true", help="Expand `group/repo` as GitLab") + parser.add_argument("--ssh", action="store_true", help="Use SSH (`git@host:...`) instead of HTTPS") + + +def run_savepoint(args: argparse.Namespace) -> int: + location = discover_repo() + action = args.action + if action == "list": + items = savepoint_list(location.root) + if not items: + print(THEME.muted("No savepoints found.")) + return 0 + for item in items: + print(f" {THEME.info('•')} {item}") + return 0 + + if action in ("pop", "apply"): + idx = int(args.target) if args.target else 0 + out = savepoint_pop(location.root, index=idx, keep=(action == "apply")) + if out: + print(out) + print(THEME.success(f"✓ Restored savepoint @{{{idx}}}.")) + return 0 + + if action == "drop": + idx = int(args.target) if args.target else 0 + savepoint_drop(location.root, index=idx) + print(THEME.warn(f"✓ Dropped savepoint @{{{idx}}}.")) + return 0 + + message = args.target if action == "push" else action + out = savepoint_push(location.root, message=message) + print(THEME.success("✓ Created savepoint.") + (f" ({out})" if out else "")) + return 0 + + +def run_remote_list(_args: argparse.Namespace) -> int: + location = discover_repo() + remotes = list_remotes(location.root) + if not remotes: + print(THEME.muted("No remotes configured.")) + return 0 + for name, url in remotes: + print(f" {THEME.accent(name)} -> {url}") + return 0 + + +def run_remote_add(args: argparse.Namespace) -> int: + location = discover_repo() + url = add_remote( + location.root, + args.name, + args.url, + github=bool(args.github), + gitlab=bool(args.gitlab), + ssh=bool(args.ssh), + ) + print(THEME.success(f"✓ Added remote '{args.name}' -> {url}")) + return 0 + + +def run_remote_set_url(args: argparse.Namespace) -> int: + location = discover_repo() + url = set_remote_url( + location.root, + args.name, + args.url, + github=bool(args.github), + gitlab=bool(args.gitlab), + ssh=bool(args.ssh), + ) + print(THEME.success(f"✓ Updated remote '{args.name}' -> {url}")) + return 0 + + +def run_remote_remove(args: argparse.Namespace) -> int: + location = discover_repo() + remove_remote(location.root, args.name) + print(THEME.warn(f"✓ Removed remote '{args.name}'.")) + return 0 + + +def run_conflicts(args: argparse.Namespace) -> int: + location = discover_repo() + if args.ours or args.theirs: + side = "ours" if args.ours else "theirs" + resolve_conflicts(location.root, side, args.files) + print(THEME.success(f"✓ Resolved {', '.join(args.files)} using `{side}` and staged.")) + print(THEME.muted('Next: run `sgit merge --continue` or `sgit save "resolve conflicts"`.')) + return 0 + + details = inspect_conflicts(location.root) + if not details: + print(THEME.success("✓ No merge conflicts in working tree.")) + return 0 + + print(THEME.error(f"Found {len(details)} conflicted file(s):")) + for item in details: + lines_str = ( + f"markers at line(s) {', '.join(map(str, item.marker_lines))}" + if item.marker_lines + else "binary/tree conflict" + ) + print(f" {THEME.error('!')} {THEME.bold(item.path)} ({THEME.muted(lines_str)})") + print(THEME.info('\nTip: edit files or run `sgit conflicts --ours ` / `--theirs `.')) + return 0 + + +def run_ignore(args: argparse.Namespace) -> int: + location = discover_repo() + if args.list: + patterns = list_ignore_patterns(location.root) + if not patterns: + print(THEME.muted(".gitignore has no patterns yet.")) + return 0 + for pat in patterns: + print(f" {pat}") + return 0 + + added = add_ignore_patterns(location.root, args.patterns, template=args.template) + if not added: + print(THEME.muted("All specified patterns are already in .gitignore.")) + return 0 + print(THEME.success(f"✓ Added {len(added)} pattern(s) to .gitignore:")) + for pat in added: + print(f" {THEME.info('+')} {pat}") + return 0 + + +def run_tag(args: argparse.Namespace) -> int: + location = discover_repo() + if not args.name: + tags = list_tags(location.root) + if not tags: + print(THEME.muted("No tags found.")) + return 0 + for tag in tags: + print(f" {THEME.accent(tag)}") + return 0 + + if args.delete: + delete_tag(location.root, args.name, remote=bool(args.remote)) + print(THEME.warn(f"✓ Deleted tag '{args.name}'" + (" (local + remote)." if args.remote else "."))) + return 0 + + create_tag(location.root, args.name, message=args.message, push=bool(args.push)) + print(THEME.success(f"✓ Created tag '{args.name}'" + (" and pushed to origin." if args.push else "."))) + return 0 + + +def run_doctor_cmd(_args: argparse.Namespace) -> int: + checks = run_doctor() + print(THEME.bold("SimpleGit Doctor")) + has_fail = False + for chk in checks: + if chk.status == "ok": + icon = THEME.success("✓") + elif chk.status == "warn": + icon = THEME.warn("!") + else: + icon = THEME.error("✗") + has_fail = True + print(f" {icon} {THEME.bold(chk.name)}: {chk.detail}") + if chk.fix_hint: + print(f" {THEME.info('Fix:')} {chk.fix_hint}") + return 1 if has_fail else 0 diff --git a/simplegit/commands/save.py b/simplegit/commands/save.py new file mode 100644 index 0000000..9443c5c --- /dev/null +++ b/simplegit/commands/save.py @@ -0,0 +1,82 @@ +"""Handler for `sgit save` — one-shot diff discovery, staging, and commit.""" + +from __future__ import annotations + +import argparse + +from simplegit.core.native_git import discover_repo +from simplegit.core.operations import collect_save_candidates, execute_save +from simplegit.errors import SimpleGitError +from simplegit.ui.theme import THEME + + +def register(subparsers: argparse._SubParsersAction) -> None: + parser = subparsers.add_parser( + "save", + help="Discover changed files from git diff, stage them, and commit in one step", + ) + parser.add_argument("message_pos", nargs="?", help="Commit message") + parser.add_argument("files", nargs="*", help="Optional specific files/paths to save") + parser.add_argument("-m", "--message", dest="message_flag", help="Commit message") + mode = parser.add_mutually_exclusive_group() + mode.add_argument( + "-t", + "--tracked", + action="store_true", + help="Only stage tracked files found in `git diff` (skip untracked files)", + ) + mode.add_argument( + "-a", + "--all", + action="store_true", + help="Include both tracked diff changes and untracked files (default)", + ) + parser.add_argument("-p", "--push", action="store_true", help="Push immediately after committing") + parser.add_argument("--amend", action="store_true", help="Amend the previous commit") + parser.add_argument("-n", "--dry-run", action="store_true", help="Preview files without committing") + parser.set_defaults(handler=run) + + +def run(args: argparse.Namespace) -> int: + files = list(args.files) + if args.message_flag is not None: + message = args.message_flag + if args.message_pos is not None: + files.insert(0, args.message_pos) + else: + message = args.message_pos + + if not message or not message.strip(): + raise SimpleGitError( + "Commit message is required.", + hint='Usage: `sgit save "your commit message"` (or `sgit save -m "msg" [files...]`).', + ) + + location = discover_repo() + plan = collect_save_candidates( + location.root, + tracked_only=bool(args.tracked), + paths=files or None, + ) + + sha, committed_files = execute_save( + plan, + message=message.strip(), + amend=bool(args.amend), + push=bool(args.push), + dry_run=bool(args.dry_run), + ) + + if args.dry_run: + print(THEME.warn("Dry run — no changes committed.")) + for path in committed_files: + print(f" {THEME.info('+')} {path}") + print(THEME.muted(f'Would commit with message: "{message.strip()}"')) + return 0 + + print(THEME.success(f"✓ Saved {sha}:") + f" {message.strip()}") + for path in committed_files: + print(f" {THEME.muted('•')} {path}") + if args.push: + print(THEME.success("✓ Pushed to remote.")) + return 0 diff --git a/simplegit/commands/status_diff.py b/simplegit/commands/status_diff.py new file mode 100644 index 0000000..b5a4b28 --- /dev/null +++ b/simplegit/commands/status_diff.py @@ -0,0 +1,69 @@ +"""Handlers for `sgit status`, `sgit diff`, `sgit log`, and `sgit inspect`.""" + +from __future__ import annotations + +import argparse + +from simplegit.core.native_git import discover_repo +from simplegit.core.operations import get_diff, get_log, get_repo_state, inspect_object +from simplegit.ui.render import render_diff, render_git_object, render_log, render_status + + +def register(subparsers: argparse._SubParsersAction) -> None: + st = subparsers.add_parser("status", aliases=["st"], help="Show grouped repository status") + st.add_argument("-s", "--short", action="store_true", help="Compact output") + st.set_defaults(handler=run_status) + + df = subparsers.add_parser("diff", help="Show colorized file differences") + df.add_argument("--staged", action="store_true", help="Show staged changes") + df.add_argument("--stat", action="store_true", help="Show diff summary statistics") + df.add_argument("--name-only", action="store_true", help="Show changed filenames only") + df.add_argument("paths", nargs="*", help="Optional paths to filter") + df.set_defaults(handler=run_diff) + + lg = subparsers.add_parser("log", help="Show concise commit history") + lg.add_argument("-n", "--limit", type=int, default=15, help="Max commits to show (default: 15)") + lg.set_defaults(handler=run_log) + + ins = subparsers.add_parser( + "inspect", + help="Inspect a Git object directly via `.git/objects` (with packfile fallback)", + ) + ins.add_argument("target", nargs="?", default="HEAD", help="Commit/tree/blob SHA or ref (default: HEAD)") + ins.set_defaults(handler=run_inspect) + + +def run_status(args: argparse.Namespace) -> int: + state = get_repo_state() + render_status(state, short=bool(args.short)) + return 0 + + +def run_diff(args: argparse.Namespace) -> int: + location = discover_repo() + output = get_diff( + location.root, + staged=bool(args.staged), + stat=bool(args.stat), + name_only=bool(args.name_only), + paths=args.paths or None, + ) + if args.stat or args.name_only: + print(output, end="" if output.endswith("\n") or not output else "\n") + else: + render_diff(output) + return 0 + + +def run_log(args: argparse.Namespace) -> int: + location = discover_repo() + commits = get_log(location.root, limit=max(1, args.limit)) + render_log(commits) + return 0 + + +def run_inspect(args: argparse.Namespace) -> int: + location = discover_repo() + obj = inspect_object(location, args.target) + render_git_object(obj) + return 0 diff --git a/simplegit/commands/sync.py b/simplegit/commands/sync.py new file mode 100644 index 0000000..2fcd637 --- /dev/null +++ b/simplegit/commands/sync.py @@ -0,0 +1,91 @@ +"""Handlers for `sgit init`, `sgit clone`, `sgit sync`, `sgit pull`, and `sgit push`.""" + +from __future__ import annotations + +import argparse +from pathlib import Path + +from simplegit.core.native_git import discover_repo +from simplegit.core.operations import clone_repo, init_repo, pull_repo, push_repo, sync_repo +from simplegit.ui.theme import THEME + + +def register(subparsers: argparse._SubParsersAction) -> None: + ini = subparsers.add_parser("init", help="Initialize a new Git repository") + ini.add_argument("path", nargs="?", help="Directory to initialize (default: current directory)") + ini.add_argument("--bare", action="store_true", help="Create a bare repository") + ini.set_defaults(handler=run_init) + + cln = subparsers.add_parser("clone", help="Clone a Git repository (supports -gh, -gl, or .git URL/dir)") + cln.add_argument("url", help="Repository shorthand (with -gh/-gl), `.git` URL, or local `.git` directory") + cln.add_argument("directory", nargs="?", help="Target folder name") + cln.add_argument("-b", "--branch", help="Branch to check out") + host_group = cln.add_mutually_exclusive_group() + host_group.add_argument("-gh", "--github", action="store_true", help="Expand `owner/repo` as GitHub") + host_group.add_argument("-gl", "--gitlab", action="store_true", help="Expand `group/repo` as GitLab") + cln.add_argument("--ssh", action="store_true", help="Use SSH (`git@host:...`) instead of HTTPS") + cln.set_defaults(handler=run_clone) + + snc = subparsers.add_parser("sync", help="Pull upstream changes and push local commits") + snc.add_argument("--merge", action="store_true", help="Use merge pull instead of `pull --rebase`") + snc.add_argument("--autostash", action="store_true", help="Automatically stash/unstash dirty files during rebase") + snc.add_argument("-n", "--dry-run", action="store_true", help="Show planned sync steps without running them") + snc.set_defaults(handler=run_sync) + + pul = subparsers.add_parser("pull", help="Pull updates from remote") + pul.add_argument("--merge", action="store_true", help="Use merge pull instead of `pull --rebase`") + pul.add_argument("--autostash", action="store_true", help="Auto-stash local changes before rebase") + pul.set_defaults(handler=run_pull) + + psh = subparsers.add_parser("push", help="Push local commits (auto-sets upstream on new branches)") + psh.set_defaults(handler=run_push) + + +def run_init(args: argparse.Namespace) -> int: + target = init_repo(Path(args.path) if args.path else None, bare=bool(args.bare)) + print(THEME.success(f"✓ Initialized Git repository in {target}")) + return 0 + + +def run_clone(args: argparse.Namespace) -> int: + resolved = clone_repo( + args.url, + directory=args.directory, + branch=args.branch, + github=bool(args.github), + gitlab=bool(args.gitlab), + ssh=bool(args.ssh), + ) + print(THEME.success(f"✓ Cloned {resolved}")) + return 0 + + +def run_sync(args: argparse.Namespace) -> int: + location = discover_repo() + actions = sync_repo( + location.root, + use_merge=bool(args.merge), + autostash=bool(args.autostash), + dry_run=bool(args.dry_run), + ) + if args.dry_run: + print(THEME.warn("Dry run — planned sync steps:")) + for step in actions: + print(f" {THEME.info('•')} {step}") + return 0 + print(THEME.success("✓ Sync complete.")) + return 0 + + +def run_pull(args: argparse.Namespace) -> int: + location = discover_repo() + pull_repo(location.root, use_merge=bool(args.merge), autostash=bool(args.autostash)) + print(THEME.success("✓ Pull complete.")) + return 0 + + +def run_push(args: argparse.Namespace) -> int: + location = discover_repo() + push_repo(location.root) + print(THEME.success("✓ Push complete.")) + return 0 diff --git a/simplegit/commands/undo.py b/simplegit/commands/undo.py new file mode 100644 index 0000000..272228d --- /dev/null +++ b/simplegit/commands/undo.py @@ -0,0 +1,52 @@ +"""Handler for `sgit undo` — safe recovery for commits, staging, and working files.""" + +from __future__ import annotations + +import argparse + +from simplegit.core.native_git import discover_repo +from simplegit.core.operations import undo_changes, undo_commit, undo_stage +from simplegit.errors import SimpleGitError +from simplegit.ui.terminal import confirm +from simplegit.ui.theme import THEME + + +def register(subparsers: argparse._SubParsersAction) -> None: + parser = subparsers.add_parser( + "undo", + help="Safely undo last commit, unstage files, or discard working changes", + ) + parser.add_argument( + "target", + choices=["commit", "stage", "changes"], + help="What to undo: `commit` (soft reset), `stage` (unstage), or `changes` (discard edits)", + ) + parser.add_argument("paths", nargs="*", help="Optional files for `stage` or `changes`") + parser.add_argument("-y", "--yes", action="store_true", help="Skip confirmation for `undo changes`") + parser.set_defaults(handler=run) + + +def run(args: argparse.Namespace) -> int: + location = discover_repo() + if args.target == "commit": + msg = undo_commit(location.root) + print(THEME.success(f"✓ {msg}")) + return 0 + + if args.target == "stage": + undo_stage(location.root, args.paths or None) + scope = ", ".join(args.paths) if args.paths else "all staged files" + print(THEME.success(f"✓ Unstaged {scope} (working edits preserved).")) + return 0 + + scope = ", ".join(args.paths) if args.paths else "ALL unstaged tracked changes" + if not args.yes: + if not confirm(f"Discard {scope}? This cannot be undone.", default=False): + print(THEME.muted("Cancelled.")) + return 0 + try: + undo_changes(location.root, args.paths or None) + except SimpleGitError: + raise + print(THEME.warn(f"✓ Discarded {scope}.")) + return 0 diff --git a/simplegit/commands/viewer.py b/simplegit/commands/viewer.py new file mode 100644 index 0000000..f511ab2 --- /dev/null +++ b/simplegit/commands/viewer.py @@ -0,0 +1,45 @@ +"""Handler for `sgit viewer` — GitHub Insights/Network-style graph (Local & Hosted).""" + +from __future__ import annotations + +import argparse + +from simplegit.core.operations import get_network_graph, get_repo_state, list_tracked_files +from simplegit.ui.render import render_viewer + + +def register(subparsers: argparse._SubParsersAction) -> None: + parser = subparsers.add_parser( + "viewer", + aliases=["view", "network"], + help="Show a GitHub Insights/Network-style graph (X=Time, Y=Branches) across Local & Hosted", + ) + parser.add_argument( + "-n", + "--limit", + type=int, + default=14, + help="Max commits to plot along the timeline (default: 14)", + ) + parser.add_argument("--all-commits", action="store_true", help="Plot all commits without a limit") + scope = parser.add_mutually_exclusive_group() + scope.add_argument("--local", action="store_true", help="Show Local branches only") + scope.add_argument("--hosted", action="store_true", help="Show Hosted remote branches only") + parser.add_argument("--fetch", action="store_true", help="Fetch remote refs before rendering") + parser.add_argument("--files", action="store_true", help="Also display the repository file tree") + parser.set_defaults(handler=run) + + +def run(args: argparse.Namespace) -> int: + state = get_repo_state() + limit = 0 if args.all_commits else max(1, args.limit) + graph = get_network_graph( + state.location.root, + limit=limit, + include_local=not bool(args.hosted), + include_hosted=not bool(args.local), + fetch_remote=bool(args.fetch), + ) + tracked_files = list_tracked_files(state.location.root) if args.files else None + render_viewer(state, graph, tracked_files=tracked_files) + return 0 diff --git a/simplegit/core/__init__.py b/simplegit/core/__init__.py new file mode 100644 index 0000000..54a64c9 --- /dev/null +++ b/simplegit/core/__init__.py @@ -0,0 +1,3 @@ +"""Pure-Python core package for hybrid `.git` inspection and Git execution.""" + +from __future__ import annotations diff --git a/simplegit/core/auth.py b/simplegit/core/auth.py new file mode 100644 index 0000000..6ae0247 --- /dev/null +++ b/simplegit/core/auth.py @@ -0,0 +1,191 @@ +"""GitHub and GitLab authentication via Git credential helpers and SSH.""" + +from __future__ import annotations + +import json +import os +import platform +import shutil +import subprocess +import urllib.error +import urllib.request +from dataclasses import dataclass +from pathlib import Path + +from simplegit.core.runner import find_git_binary, run_git +from simplegit.errors import SimpleGitError + + +@dataclass(frozen=True) +class AuthStatus: + """Summary of stored HTTPS credential or SSH readiness for a Git host.""" + + host: str + https_user: str | None + ssh_keys: tuple[str, ...] + + +def host_for_provider(github: bool = False, gitlab: bool = False, custom_host: str | None = None) -> str: + """Resolve hostname for GitHub, GitLab, or custom instance.""" + if github and gitlab: + raise SimpleGitError("Choose either `-gh` (GitHub) or `-gl` (GitLab), not both.") + if custom_host: + return custom_host.strip().removeprefix("https://").removeprefix("http://").strip("/") + if github: + return "github.com" + if gitlab: + return "gitlab.com" + raise SimpleGitError( + "Specify a provider (`-gh` for GitHub or `-gl` for GitLab).", + hint="Example: `sgit auth login -gh` or `sgit auth login -gl`", + ) + + +def ensure_credential_helper() -> str: + """Ensure a global `credential.helper` is configured and return its name.""" + res = run_git(["config", "--global", "--get", "credential.helper"], check=False) + existing = res.stdout.strip() + if existing: + return existing + + system = platform.system() + if system == "Darwin": + helper = "osxkeychain" + elif system == "Windows": + helper = "manager" + else: + helper = "store" + + run_git(["config", "--global", "credential.helper", helper]) + return helper + + +def verify_provider_token(host: str, token: str, is_gitlab: bool = False) -> str: + """Verify a PAT against GitHub or GitLab API and return the account username.""" + if is_gitlab or "gitlab" in host.lower(): + url = f"https://{host}/api/v4/user" + headers = {"PRIVATE-TOKEN": token, "User-Agent": "SimpleGit/0.1"} + else: + api_base = "https://api.github.com" if host == "github.com" else f"https://{host}/api/v3" + url = f"{api_base}/user" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "User-Agent": "SimpleGit/0.1", + } + + req = urllib.request.Request(url, headers=headers, method="GET") + try: + with urllib.request.urlopen(req, timeout=10) as resp: + payload = json.loads(resp.read().decode("utf-8", errors="replace")) + except urllib.error.HTTPError as exc: + if exc.code in (401, 403): + raise SimpleGitError( + f"Authentication rejected by {host} (HTTP {exc.code}).", + hint="Check that your Personal Access Token is valid and has `repo` / `write_repository` scope.", + ) from exc + raise SimpleGitError(f"Failed to verify token with {host}: HTTP {exc.code}") from exc + except urllib.error.URLError as exc: + raise SimpleGitError( + f"Could not reach {host}: {exc.reason}", + hint="Check your internet connection, or pass `--skip-verify` to store the token offline.", + ) from exc + + username = payload.get("login") or payload.get("username") + if not username: + raise SimpleGitError(f"Unexpected API response from {host}: missing username.") + return str(username) + + +def _run_git_credential(action: str, payload: str) -> subprocess.CompletedProcess[str]: + git_bin = find_git_binary() + env = os.environ.copy() + env["GIT_TERMINAL_PROMPT"] = "0" + return subprocess.run( + [git_bin, "credential", action], + input=payload, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + ) + + +def store_https_credentials(host: str, username: str, token: str) -> str: + """Store HTTPS credentials in Git's configured credential helper.""" + helper = ensure_credential_helper() + payload = f"protocol=https\nhost={host}\nusername={username}\npassword={token}\n\n" + proc = _run_git_credential("approve", payload) + if proc.returncode != 0: + raise SimpleGitError( + f"Failed to store credentials using `{helper}`.", + details=proc.stderr.strip(), + ) + return helper + + +def clear_https_credentials(host: str) -> None: + """Remove stored HTTPS credentials for `host` from Git's credential helper.""" + payload = f"protocol=https\nhost={host}\n\n" + proc = _run_git_credential("reject", payload) + if proc.returncode != 0: + raise SimpleGitError( + f"Failed to remove credentials for {host}.", + details=proc.stderr.strip(), + ) + + +def get_stored_username(host: str) -> str | None: + """Query Git's credential helper for a stored username on `host` without prompting.""" + payload = f"protocol=https\nhost={host}\n\n" + proc = _run_git_credential("fill", payload) + if proc.returncode != 0: + return None + for line in proc.stdout.splitlines(): + if line.startswith("username="): + return line.split("=", 1)[1].strip() or None + return None + + +def find_ssh_public_keys(ssh_dir: Path | None = None) -> list[Path]: + """Return existing SSH public key files in `~/.ssh`.""" + base = ssh_dir or (Path.home() / ".ssh") + if not base.is_dir(): + return [] + return sorted(p for p in base.glob("*.pub") if p.is_file()) + + +def generate_ssh_key(email: str, ssh_dir: Path | None = None) -> Path: + """Generate an ed25519 SSH keypair using `ssh-keygen` if none exists.""" + ssh_keygen = shutil.which("ssh-keygen") + if not ssh_keygen: + raise SimpleGitError("`ssh-keygen` was not found on your PATH.") + base = ssh_dir or (Path.home() / ".ssh") + base.mkdir(parents=True, exist_ok=True) + key_path = base / "id_ed25519" + if key_path.exists(): + raise SimpleGitError( + f"SSH key already exists at {key_path}.", + hint=f"Copy `{key_path}.pub` to your GitHub/GitLab SSH key settings.", + ) + subprocess.run( + [ssh_keygen, "-t", "ed25519", "-C", email, "-f", str(key_path), "-N", ""], + check=True, + capture_output=True, + text=True, + ) + return Path(f"{key_path}.pub") + + +def get_auth_status(hosts: tuple[str, ...] = ("github.com", "gitlab.com")) -> list[AuthStatus]: + """Return credential and SSH key status for GitHub and GitLab.""" + ssh_keys = tuple(p.name for p in find_ssh_public_keys()) + return [ + AuthStatus( + host=host, + https_user=get_stored_username(host), + ssh_keys=ssh_keys, + ) + for host in hosts + ] diff --git a/simplegit/core/extras.py b/simplegit/core/extras.py new file mode 100644 index 0000000..2fb3e19 --- /dev/null +++ b/simplegit/core/extras.py @@ -0,0 +1,319 @@ +"""Core implementations for savepoints, remotes, conflicts, ignore, tags, and doctor.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +from simplegit.core.auth import AuthStatus, get_auth_status +from simplegit.core.operations import get_repo_state, resolve_clone_url +from simplegit.core.runner import find_git_binary, get_git_version, run_git +from simplegit.errors import NotARepoError, SimpleGitError + +_IGNORE_TEMPLATES: dict[str, tuple[str, ...]] = { + "python": ( + "__pycache__/", + "*.py[cod]", + ".venv/", + "venv/", + "*.egg-info/", + "dist/", + "build/", + ".pytest_cache/", + ), + "node": ( + "node_modules/", + "dist/", + "build/", + ".env", + "*.log", + "npm-debug.log*", + ), + "macos": ( + ".DS_Store", + ".AppleDouble", + ".LSOverride", + "._*", + ), + "general": ( + ".env", + ".env.local", + "*.log", + "*.tmp", + ".DS_Store", + ), +} + + +@dataclass(frozen=True) +class ConflictDetail: + """Conflicted file and line numbers of `<<<<<<<` markers.""" + + path: str + marker_lines: tuple[int, ...] + + +@dataclass(frozen=True) +class DoctorCheck: + """Single health check result for `sgit doctor`.""" + + name: str + status: str # "ok", "warn", "fail" + detail: str + fix_hint: str | None = None + + +def savepoint_push(repo_root: Path, message: str | None = None) -> str: + """Create a stash savepoint including untracked files.""" + args = ["stash", "push", "-u"] + if message: + args.extend(["-m", message]) + res = run_git(args, cwd=repo_root) + return res.stdout.strip() + + +def savepoint_list(repo_root: Path) -> list[str]: + """List existing stash savepoints.""" + res = run_git(["stash", "list"], cwd=repo_root) + return [line for line in res.stdout.splitlines() if line.strip()] + + +def savepoint_pop(repo_root: Path, index: int = 0, keep: bool = False) -> str: + """Apply (and optionally drop) a stash savepoint by index.""" + sub = "apply" if keep else "pop" + res = run_git(["stash", sub, f"stash@{{{index}}}"], cwd=repo_root) + return res.stdout.strip() + + +def savepoint_drop(repo_root: Path, index: int = 0) -> None: + """Delete a stash savepoint by index.""" + run_git(["stash", "drop", f"stash@{{{index}}}"], cwd=repo_root) + + +def list_remotes(repo_root: Path) -> list[tuple[str, str]]: + """Return unique `(name, url)` pairs from `git remote -v`.""" + res = run_git(["remote", "-v"], cwd=repo_root) + seen: set[tuple[str, str]] = set() + remotes: list[tuple[str, str]] = [] + for line in res.stdout.splitlines(): + parts = line.split() + if len(parts) >= 2: + pair = (parts[0], parts[1]) + if pair not in seen: + seen.add(pair) + remotes.append(pair) + return remotes + + +def add_remote( + repo_root: Path, + name: str, + target: str, + github: bool = False, + gitlab: bool = False, + ssh: bool = False, +) -> str: + """Add a remote using `-gh`/`-gl` shorthand or full URL/path.""" + url = resolve_clone_url(target, github=github, gitlab=gitlab, ssh=ssh) + run_git(["remote", "add", name, url], cwd=repo_root) + return url + + +def set_remote_url( + repo_root: Path, + name: str, + target: str, + github: bool = False, + gitlab: bool = False, + ssh: bool = False, +) -> str: + """Update an existing remote URL.""" + url = resolve_clone_url(target, github=github, gitlab=gitlab, ssh=ssh) + run_git(["remote", "set-url", name, url], cwd=repo_root) + return url + + +def remove_remote(repo_root: Path, name: str) -> None: + run_git(["remote", "remove", name], cwd=repo_root) + + +def inspect_conflicts(repo_root: Path) -> list[ConflictDetail]: + """Return conflicted files and line numbers containing `<<<<<<<` markers.""" + state = get_repo_state(repo_root) + details: list[ConflictDetail] = [] + for item in state.conflicted_files: + full_path = repo_root / item.path + markers: list[int] = [] + if full_path.is_file(): + text = full_path.read_text(encoding="utf-8", errors="replace") + for idx, line in enumerate(text.splitlines(), start=1): + if line.startswith("<<<<<<<"): + markers.append(idx) + details.append(ConflictDetail(path=item.path, marker_lines=tuple(markers))) + return details + + +def resolve_conflicts(repo_root: Path, side: str, paths: list[str]) -> None: + """Resolve conflicted files using `--ours` or `--theirs` and stage them.""" + if side not in ("ours", "theirs"): + raise SimpleGitError("Side must be `ours` or `theirs`.") + if not paths: + raise SimpleGitError("Specify at least one conflicted file path.") + run_git(["checkout", f"--{side}", "--", *paths], cwd=repo_root) + run_git(["add", "--", *paths], cwd=repo_root) + + +def add_ignore_patterns( + repo_root: Path, + patterns: list[str], + template: str | None = None, +) -> list[str]: + """Append unique patterns (and/or template patterns) to `.gitignore`.""" + to_add: list[str] = list(patterns) + if template: + key = template.lower() + if key not in _IGNORE_TEMPLATES: + valid = ", ".join(sorted(_IGNORE_TEMPLATES)) + raise SimpleGitError(f"Unknown template '{template}'.", hint=f"Available templates: {valid}") + to_add.extend(_IGNORE_TEMPLATES[key]) + + if not to_add: + raise SimpleGitError("Provide patterns or `--template `.", hint="Example: `sgit ignore '*.log' .env`") + + gitignore = repo_root / ".gitignore" + existing_lines: list[str] = [] + if gitignore.is_file(): + existing_lines = gitignore.read_text(encoding="utf-8", errors="replace").splitlines() + existing_set = {ln.strip() for ln in existing_lines} + + added: list[str] = [] + for pat in to_add: + cleaned = pat.strip() + if cleaned and cleaned not in existing_set: + existing_set.add(cleaned) + existing_lines.append(cleaned) + added.append(cleaned) + + if added: + content = "\n".join(existing_lines) + "\n" + gitignore.write_text(content, encoding="utf-8") + return added + + +def list_ignore_patterns(repo_root: Path) -> list[str]: + gitignore = repo_root / ".gitignore" + if not gitignore.is_file(): + return [] + return [ln for ln in gitignore.read_text(encoding="utf-8", errors="replace").splitlines() if ln.strip()] + + +def list_tags(repo_root: Path) -> list[str]: + res = run_git(["tag", "-l", "--sort=-v:refname"], cwd=repo_root) + return [ln for ln in res.stdout.splitlines() if ln.strip()] + + +def create_tag(repo_root: Path, name: str, message: str | None = None, push: bool = False) -> None: + args = ["tag"] + if message: + args.extend(["-a", name, "-m", message]) + else: + args.append(name) + run_git(args, cwd=repo_root) + if push: + run_git(["push", "origin", name], cwd=repo_root, interactive=True, stream_output=True) + + +def delete_tag(repo_root: Path, name: str, remote: bool = False) -> None: + run_git(["tag", "-d", name], cwd=repo_root) + if remote: + run_git(["push", "origin", "--delete", name], cwd=repo_root, interactive=True, stream_output=True) + + +def run_doctor(start: Path | None = None) -> list[DoctorCheck]: + """Run environment, identity, auth, and repository health checks.""" + checks: list[DoctorCheck] = [] + + try: + git_bin = find_git_binary() + ver = get_git_version() + ver_str = ".".join(map(str, ver)) + if ver >= (2, 23, 0): + checks.append(DoctorCheck("Git binary", "ok", f"{git_bin} (v{ver_str})")) + else: + checks.append( + DoctorCheck( + "Git binary", + "warn", + f"{git_bin} (v{ver_str} — recommend >= 2.23)", + "Upgrade Git for full `switch`/`restore` support.", + ) + ) + except SimpleGitError as exc: + checks.append(DoctorCheck("Git binary", "fail", exc.message, exc.hint)) + return checks + + user_name = run_git(["config", "--get", "user.name"], check=False).stdout.strip() + user_email = run_git(["config", "--get", "user.email"], check=False).stdout.strip() + if user_name and user_email: + checks.append(DoctorCheck("Git identity", "ok", f"{user_name} <{user_email}>")) + else: + checks.append( + DoctorCheck( + "Git identity", + "warn", + "user.name or user.email is not set", + 'Run `git config --global user.name "Your Name"` and `git config --global user.email "you@example.com"`', + ) + ) + + helper = run_git(["config", "--get", "credential.helper"], check=False).stdout.strip() + if helper: + checks.append(DoctorCheck("Credential helper", "ok", helper)) + else: + checks.append( + DoctorCheck( + "Credential helper", + "warn", + "No credential.helper configured", + "Run `sgit auth login -gh` or `sgit auth login -gl` to configure HTTPS credentials.", + ) + ) + + auth_list: list[AuthStatus] = get_auth_status() + authed_hosts = [a.host for a in auth_list if a.https_user] + ssh_keys = auth_list[0].ssh_keys if auth_list else () + if authed_hosts or ssh_keys: + parts = [] + if authed_hosts: + parts.append("HTTPS: " + ", ".join(authed_hosts)) + if ssh_keys: + parts.append("SSH: " + ", ".join(ssh_keys)) + checks.append(DoctorCheck("GitHub / GitLab auth", "ok", " | ".join(parts))) + else: + checks.append( + DoctorCheck( + "GitHub / GitLab auth", + "warn", + "No stored GitHub/GitLab tokens or SSH keys found", + "Run `sgit auth login -gh` or `sgit auth login -gl`.", + ) + ) + + try: + state = get_repo_state(start) + status_note = f"branch '{state.branch}'" + if state.active_op: + checks.append( + DoctorCheck( + "Repository state", + "warn", + f"{status_note} ({state.active_op} in progress)", + "Resolve or abort the in-progress operation.", + ) + ) + else: + checks.append(DoctorCheck("Repository state", "ok", status_note)) + except NotARepoError: + checks.append(DoctorCheck("Repository state", "warn", "Current directory is not a Git repository")) + + return checks diff --git a/simplegit/core/models.py b/simplegit/core/models.py new file mode 100644 index 0000000..af3d57e --- /dev/null +++ b/simplegit/core/models.py @@ -0,0 +1,177 @@ +"""Typed domain models for SimpleGit's hybrid `.git` engine.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from pathlib import Path + + +@dataclass(frozen=True) +class RepoLocation: + """Resolved filesystem paths for a Git repository.""" + + root: Path + git_dir: Path + common_dir: Path + is_bare: bool = False + + +@dataclass(frozen=True) +class FileChange: + """Normalized file status entry from `git status --porcelain=v2`.""" + + path: str + status_x: str + status_y: str + orig_path: str | None = None + unmerged: bool = False + untracked: bool = False + + @property + def is_conflicted(self) -> bool: + return self.unmerged + + @property + def is_staged(self) -> bool: + return not self.untracked and not self.unmerged and self.status_x not in (".", " ", "?") + + @property + def is_unstaged(self) -> bool: + return not self.untracked and not self.unmerged and self.status_y not in (".", " ", "?") + + @property + def display_path(self) -> str: + if self.orig_path: + return f"{self.orig_path} -> {self.path}" + return self.path + + +@dataclass(frozen=True) +class RepoState: + """Combined snapshot of repository branch, tracking, operation state, and changes.""" + + location: RepoLocation + branch: str + head_sha: str | None + detached: bool + upstream: str | None = None + ahead: int = 0 + behind: int = 0 + active_op: str | None = None + changes: tuple[FileChange, ...] = () + + @property + def staged_files(self) -> list[FileChange]: + return [c for c in self.changes if c.is_staged] + + @property + def unstaged_files(self) -> list[FileChange]: + return [c for c in self.changes if c.is_unstaged] + + @property + def untracked_files(self) -> list[FileChange]: + return [c for c in self.changes if c.untracked] + + @property + def conflicted_files(self) -> list[FileChange]: + return [c for c in self.changes if c.is_conflicted] + + @property + def is_clean(self) -> bool: + return len(self.changes) == 0 + + +@dataclass(frozen=True) +class BranchInfo: + """Local or remote branch metadata.""" + + name: str + sha: str + is_current: bool = False + is_remote: bool = False + upstream: str | None = None + + +@dataclass(frozen=True) +class CommitInfo: + """Commit summary entry for `sgit log` and interactive history.""" + + sha: str + short_sha: str + author: str + date: str + subject: str + parents: tuple[str, ...] = () + + +@dataclass(frozen=True) +class NetworkLane: + """A branch swimlane on the Network graph Y-axis.""" + + name: str + scope: str # "local" or "hosted" + tip_sha: str + is_current: bool = False + + +@dataclass(frozen=True) +class NetworkCommit: + """Chronological commit node on the Network graph.""" + + sha: str + short_sha: str + date_label: str + author: str + subject: str + lane_index: int + parents: tuple[str, ...] = () + file_changes: tuple[tuple[str, str], ...] = () + + +@dataclass(frozen=True) +class NetworkGraph: + """Complete X=Time, Y=Branch/Remote Network graph.""" + + lanes: tuple[NetworkLane, ...] + commits: tuple[NetworkCommit, ...] + + +@dataclass(frozen=True) +class GitObject: + """Decoded `.git` object (`blob`, `tree`, `commit`, or `tag`).""" + + kind: str + size: int + sha: str + content: bytes + source: str # "loose" or "packed" + + +@dataclass(frozen=True) +class SavePlan: + """Resolved file targets for `sgit save`.""" + + repo_root: Path + tracked_diff_files: tuple[str, ...] = field(default_factory=tuple) + untracked_files: tuple[str, ...] = field(default_factory=tuple) + already_staged_files: tuple[str, ...] = field(default_factory=tuple) + + @property + def files_to_stage(self) -> list[str]: + seen: set[str] = set() + ordered: list[str] = [] + for path in (*self.tracked_diff_files, *self.untracked_files): + if path not in seen: + seen.add(path) + ordered.append(path) + return ordered + + @property + def all_commit_files(self) -> list[str]: + seen: set[str] = set() + ordered: list[str] = [] + for path in (*self.already_staged_files, *self.files_to_stage): + if path not in seen: + seen.add(path) + ordered.append(path) + return ordered diff --git a/simplegit/core/native_git.py b/simplegit/core/native_git.py new file mode 100644 index 0000000..0f80d85 --- /dev/null +++ b/simplegit/core/native_git.py @@ -0,0 +1,191 @@ +"""Direct `.git` inspection & plumbing implemented in pure Python stdlib.""" + +from __future__ import annotations + +import hashlib +import zlib +from pathlib import Path + +from simplegit.core.models import GitObject, RepoLocation +from simplegit.errors import NotARepoError + +_OP_SENTINELS: tuple[tuple[str, str], ...] = ( + ("MERGE_HEAD", "MERGING"), + ("REBASE_MERGE", "REBASING"), + ("REBASE_APPLY", "REBASING"), + ("CHERRY_PICK_HEAD", "CHERRY-PICKING"), + ("REVERT_HEAD", "REVERTING"), + ("BISECT_LOG", "BISECTING"), +) + + +def discover_repo(start: Path | None = None) -> RepoLocation: + """Locate `.git` directory (or worktree pointer / bare repo) walking upward from `start`.""" + current = (start or Path.cwd()).resolve() + for candidate in (current, *current.parents): + dot_git = candidate / ".git" + if dot_git.is_dir(): + common_dir = _resolve_common_dir(dot_git) + return RepoLocation(root=candidate, git_dir=dot_git, common_dir=common_dir, is_bare=False) + if dot_git.is_file(): + git_dir = _read_gitdir_pointer(dot_git) + common_dir = _resolve_common_dir(git_dir) + return RepoLocation(root=candidate, git_dir=git_dir, common_dir=common_dir, is_bare=False) + if _looks_like_bare_repo(candidate): + return RepoLocation(root=candidate, git_dir=candidate, common_dir=candidate, is_bare=True) + + raise NotARepoError( + message="This folder is not inside a Git repository.", + hint="Run `sgit init` to start a new repository here, or `cd` into an existing one.", + ) + + +def _looks_like_bare_repo(path: Path) -> bool: + return (path / "HEAD").is_file() and (path / "objects").is_dir() and (path / "refs").is_dir() + + +def _read_gitdir_pointer(dot_git_file: Path) -> Path: + text = dot_git_file.read_text(encoding="utf-8", errors="replace").strip() + if not text.startswith("gitdir:"): + raise NotARepoError(f"Invalid .git pointer file: {dot_git_file}") + raw_target = text.split(":", 1)[1].strip() + target = Path(raw_target) + if not target.is_absolute(): + target = (dot_git_file.parent / target).resolve() + return target + + +def _resolve_common_dir(git_dir: Path) -> Path: + commondir_file = git_dir / "commondir" + if not commondir_file.is_file(): + return git_dir + rel = commondir_file.read_text(encoding="utf-8", errors="replace").strip() + target = Path(rel) + return target if target.is_absolute() else (git_dir / target).resolve() + + +def detect_active_operation(git_dir: Path) -> str | None: + """Detect in-progress merge/rebase/cherry-pick/revert/bisect from `.git` files.""" + for name, label in _OP_SENTINELS: + if (git_dir / name).exists(): + return label + return None + + +def resolve_ref(location: RepoLocation, ref_name: str) -> str | None: + """Resolve a ref (e.g. `refs/heads/main`) across loose refs and `packed-refs`.""" + for base in (location.git_dir, location.common_dir): + loose = base / ref_name + if loose.is_file(): + return loose.read_text(encoding="utf-8", errors="replace").strip() + + packed = location.common_dir / "packed-refs" + if packed.is_file(): + for line in packed.read_text(encoding="utf-8", errors="replace").splitlines(): + if not line or line.startswith(("#", "^")): + continue + parts = line.split(" ", 1) + if len(parts) == 2 and parts[1] == ref_name: + return parts[0] + return None + + +def read_head(location: RepoLocation) -> tuple[str, str | None, bool]: + """Return `(branch_or_short_sha, head_sha_or_None, is_detached)` from `.git/HEAD`.""" + head_file = location.git_dir / "HEAD" + if not head_file.is_file(): + return ("HEAD", None, False) + raw = head_file.read_text(encoding="utf-8", errors="replace").strip() + if raw.startswith("ref:"): + ref_name = raw.split(":", 1)[1].strip() + short_name = ref_name[len("refs/heads/") :] if ref_name.startswith("refs/heads/") else ref_name + sha = resolve_ref(location, ref_name) + return (short_name, sha, False) + return (raw[:7], raw, True) + + +def compute_object_hash(kind: str, data: bytes) -> str: + """Compute Git's SHA-1 object ID for `(kind, data)`.""" + header = f"{kind} {len(data)}\0".encode("utf-8") + return hashlib.sha1(header + data).hexdigest() + + +def read_loose_object(common_dir: Path, sha_prefix: str) -> GitObject | None: + """Read and decompress a loose object from `.git/objects/xx/yyyy...` if present.""" + cleaned = sha_prefix.strip().lower() + if len(cleaned) < 4 or not all(c in "0123456789abcdef" for c in cleaned): + return None + + obj_dir = common_dir / "objects" / cleaned[:2] + if not obj_dir.is_dir(): + return None + + rest = cleaned[2:] + matches = [p for p in obj_dir.iterdir() if p.is_file() and p.name.startswith(rest)] + if len(matches) != 1: + return None + + obj_path = matches[0] + full_sha = cleaned[:2] + obj_path.name + raw = zlib.decompress(obj_path.read_bytes()) + nul_idx = raw.find(b"\0") + if nul_idx == -1: + return None + + header = raw[:nul_idx].decode("utf-8", errors="replace") + body = raw[nul_idx + 1 :] + kind, size_str = header.split(" ", 1) + size = int(size_str) + if len(body) != size: + raise ValueError(f"Corrupt Git object {full_sha}: expected {size} bytes, got {len(body)}") + + return GitObject(kind=kind, size=size, sha=full_sha, content=body, source="loose") + + +def parse_commit_object(data: bytes) -> dict: + """Parse raw Git commit object bytes into headers and commit message.""" + text = data.decode("utf-8", errors="replace") + if "\n\n" in text: + header_block, message = text.split("\n\n", 1) + else: + header_block, message = text, "" + + parents: list[str] = [] + tree = "" + author = "" + committer = "" + for line in header_block.splitlines(): + if line.startswith("tree "): + tree = line[5:] + elif line.startswith("parent "): + parents.append(line[7:]) + elif line.startswith("author "): + author = line[7:] + elif line.startswith("committer "): + committer = line[10:] + + return { + "tree": tree, + "parents": tuple(parents), + "author": author, + "committer": committer, + "message": message, + } + + +def parse_tree_object(data: bytes) -> list[tuple[str, str, str]]: + """Parse binary Git tree entries into `(mode, name, sha_hex)` tuples.""" + entries: list[tuple[str, str, str]] = [] + pos = 0 + total = len(data) + while pos < total: + space_idx = data.find(b" ", pos) + nul_idx = data.find(b"\0", space_idx + 1) + if space_idx == -1 or nul_idx == -1 or nul_idx + 21 > total: + break + mode = data[pos:space_idx].decode("ascii", errors="replace") + name = data[space_idx + 1 : nul_idx].decode("utf-8", errors="replace") + sha_hex = data[nul_idx + 1 : nul_idx + 21].hex() + entries.append((mode, name, sha_hex)) + pos = nul_idx + 21 + return entries diff --git a/simplegit/core/operations.py b/simplegit/core/operations.py new file mode 100644 index 0000000..c05cb8b --- /dev/null +++ b/simplegit/core/operations.py @@ -0,0 +1,606 @@ +"""High-level Git workflows composing native `.git` inspection and `git` runner.""" + +from __future__ import annotations + +from pathlib import Path + +from simplegit.core.models import ( + BranchInfo, + CommitInfo, + FileChange, + GitObject, + NetworkCommit, + NetworkGraph, + NetworkLane, + RepoLocation, + RepoState, + SavePlan, +) +from simplegit.core.native_git import ( + detect_active_operation, + discover_repo, + read_head, + read_loose_object, +) +from simplegit.core.runner import run_git, run_git_bytes, split_nul_lines +from simplegit.errors import NothingToCommitError, SimpleGitError + + +def get_repo_state(start: Path | None = None) -> RepoState: + """Return full `RepoState` combining native `.git` state with `git status --porcelain=v2`.""" + location = discover_repo(start) + branch, head_sha, detached = read_head(location) + active_op = detect_active_operation(location.git_dir) + + res = run_git(["status", "--porcelain=v2", "--branch", "-z"], cwd=location.root) + parsed_branch, upstream, ahead, behind, changes = _parse_porcelain_v2(res.stdout) + + if parsed_branch and parsed_branch != "(detached)": + branch = parsed_branch + + return RepoState( + location=location, + branch=branch, + head_sha=head_sha, + detached=detached, + upstream=upstream, + ahead=ahead, + behind=behind, + active_op=active_op, + changes=tuple(changes), + ) + + +def _parse_porcelain_v2( + output: str, +) -> tuple[str | None, str | None, int, int, list[FileChange]]: + branch: str | None = None + upstream: str | None = None + ahead = 0 + behind = 0 + changes: list[FileChange] = [] + + tokens = output.split("\0") + i = 0 + while i < len(tokens): + entry = tokens[i] + i += 1 + if not entry: + continue + + if entry.startswith("# "): + if entry.startswith("# branch.head "): + branch = entry[len("# branch.head ") :] + elif entry.startswith("# branch.upstream "): + upstream = entry[len("# branch.upstream ") :] + elif entry.startswith("# branch.ab "): + for part in entry[len("# branch.ab ") :].split(): + if part.startswith("+"): + ahead = int(part[1:]) + elif part.startswith("-"): + behind = int(part[1:]) + elif entry.startswith("1 "): + parts = entry.split(" ", 8) + xy = parts[1] + changes.append(FileChange(path=parts[8], status_x=xy[0], status_y=xy[1])) + elif entry.startswith("2 "): + parts = entry.split(" ", 9) + xy = parts[1] + orig_path = tokens[i] if i < len(tokens) else None + i += 1 + changes.append( + FileChange(path=parts[9], status_x=xy[0], status_y=xy[1], orig_path=orig_path) + ) + elif entry.startswith("u "): + parts = entry.split(" ", 10) + xy = parts[1] + changes.append( + FileChange(path=parts[10], status_x=xy[0], status_y=xy[1], unmerged=True) + ) + elif entry.startswith("? "): + changes.append( + FileChange(path=entry[2:], status_x="?", status_y="?", untracked=True) + ) + + return branch, upstream, ahead, behind, changes + + +def collect_save_candidates( + repo_root: Path, + tracked_only: bool = False, + paths: list[str] | None = None, +) -> SavePlan: + """Discover files to stage via `git diff` (and untracked files unless `tracked_only`).""" + path_args = ["--", *paths] if paths else [] + + diff_res = run_git(["diff", "--name-only", "-z", *path_args], cwd=repo_root) + tracked_diff = tuple(split_nul_lines(diff_res.stdout)) + + staged_res = run_git(["diff", "--cached", "--name-only", "-z", *path_args], cwd=repo_root) + already_staged = tuple(split_nul_lines(staged_res.stdout)) + + untracked: tuple[str, ...] = () + if not tracked_only: + untracked_res = run_git( + ["ls-files", "--others", "--exclude-standard", "-z", *path_args], + cwd=repo_root, + ) + untracked = tuple(split_nul_lines(untracked_res.stdout)) + + return SavePlan( + repo_root=repo_root, + tracked_diff_files=tracked_diff, + untracked_files=untracked, + already_staged_files=already_staged, + ) + + +def execute_save( + plan: SavePlan, + message: str, + amend: bool = False, + push: bool = False, + dry_run: bool = False, +) -> tuple[str, list[str]]: + """Stage discovered files, commit with `message`, and optionally push.""" + if not plan.all_commit_files and not amend: + raise NothingToCommitError( + message="Nothing to save — no modified or untracked files found.", + hint="Edit or create a file first, or check `sgit status`.", + ) + + staged_now = plan.files_to_stage + if dry_run: + return ("dry-run", plan.all_commit_files) + + if staged_now: + run_git(["add", "-A", "--", *staged_now], cwd=plan.repo_root) + + commit_args = ["commit", "-m", message] + if amend: + commit_args.append("--amend") + run_git(commit_args, cwd=plan.repo_root) + + sha_res = run_git(["rev-parse", "--short", "HEAD"], cwd=plan.repo_root) + short_sha = sha_res.stdout.strip() + + if push: + push_repo(plan.repo_root) + + return (short_sha, plan.all_commit_files) + + +def get_diff( + repo_root: Path, + staged: bool = False, + stat: bool = False, + name_only: bool = False, + paths: list[str] | None = None, +) -> str: + """Return unified diff, diffstat, or changed filenames.""" + args = ["diff"] + if staged: + args.append("--cached") + if stat: + args.append("--stat") + elif name_only: + args.append("--name-only") + if paths: + args.extend(["--", *paths]) + return run_git(args, cwd=repo_root).stdout + + +def get_log(repo_root: Path, limit: int = 15) -> list[CommitInfo]: + """Return recent commits for the current HEAD.""" + check_head = run_git(["rev-parse", "--verify", "--quiet", "HEAD"], cwd=repo_root, check=False) + if check_head.returncode != 0: + return [] + + fmt = "%H%x1f%h%x1f%an%x1f%ar%x1f%s%x1f%P%x1e" + res = run_git(["log", f"-n{limit}", f"--format={fmt}"], cwd=repo_root) + commits: list[CommitInfo] = [] + for record in res.stdout.split("\x1e"): + record = record.strip("\n") + if not record: + continue + fields = record.split("\x1f") + if len(fields) < 6: + continue + parents = tuple(p for p in fields[5].split() if p) + commits.append( + CommitInfo( + sha=fields[0], + short_sha=fields[1], + author=fields[2], + date=fields[3], + subject=fields[4], + parents=parents, + ) + ) + return commits + + +def get_network_graph( + repo_root: Path, + limit: int = 14, + include_local: bool = True, + include_hosted: bool = True, + fetch_remote: bool = False, +) -> NetworkGraph: + """Build an X=Time, Y=Branch Network graph across Local and Hosted viewpoints.""" + if fetch_remote: + run_git(["fetch", "--prune"], cwd=repo_root, check=False) + + check_head = run_git(["rev-parse", "--verify", "--quiet", "HEAD"], cwd=repo_root, check=False) + if check_head.returncode != 0: + return NetworkGraph(lanes=(), commits=()) + + branches = list_branches(repo_root, include_remote=include_hosted) + raw_lanes = _build_network_lanes(branches, include_local=include_local, include_hosted=include_hosted) + if not raw_lanes: + return NetworkGraph(lanes=(), commits=()) + + sha_to_lane: dict[str, int] = {} + for lane_idx, lane in enumerate(raw_lanes): + rev_res = run_git( + ["rev-list", "--first-parent", "-n", "200", lane.name], + cwd=repo_root, + check=False, + ) + if rev_res.returncode != 0: + continue + for sha in rev_res.stdout.splitlines(): + sha = sha.strip() + if sha and sha not in sha_to_lane: + sha_to_lane[sha] = lane_idx + + scope_args = ["--all"] if (include_local and include_hosted) else (["--branches"] if include_local else ["--remotes"]) + args = [ + "log", + *scope_args, + "--no-renames", + "--name-status", + "--topo-order", + "--date=format:%m-%d %H:%M", + "--format=__NET__%x09%H%x09%h%x09%cd%x09%an%x09%P%x09%s", + ] + if limit > 0: + args.append(f"-n{limit}") + + res = run_git(args, cwd=repo_root, check=False) + if res.returncode != 0: + return NetworkGraph(lanes=(), commits=()) + + parsed = _parse_network_log(res.stdout, sha_to_lane) + parsed.reverse() # Oldest -> newest left-to-right along X-axis + + visible_shas = {c.sha for c in parsed} + used_indices = {c.lane_index for c in parsed} | { + idx for idx, ln in enumerate(raw_lanes) if ln.tip_sha in visible_shas + } + remap = {old_idx: new_idx for new_idx, old_idx in enumerate(sorted(used_indices))} + final_lanes = tuple(raw_lanes[old_idx] for old_idx in sorted(used_indices)) + final_commits = tuple( + NetworkCommit( + sha=c.sha, + short_sha=c.short_sha, + date_label=c.date_label, + author=c.author, + subject=c.subject, + lane_index=remap.get(c.lane_index, 0), + parents=c.parents, + file_changes=c.file_changes, + ) + for c in parsed + ) + return NetworkGraph(lanes=final_lanes, commits=final_commits) + + +def _build_network_lanes( + branches: list[BranchInfo], + include_local: bool, + include_hosted: bool, +) -> list[NetworkLane]: + def _sort_key(br: BranchInfo) -> tuple[int, int, str]: + remote_rank = 1 if br.is_remote else 0 + primary_rank = 0 if br.name in ("main", "master", "origin/main", "origin/master") else (1 if br.is_current else 2) + return (remote_rank, primary_rank, br.name) + + lanes: list[NetworkLane] = [] + for br in sorted(branches, key=_sort_key): + if br.is_remote: + if not include_hosted or br.name.endswith("/HEAD"): + continue + lanes.append(NetworkLane(name=br.name, scope="hosted", tip_sha=br.sha, is_current=False)) + else: + if not include_local: + continue + lanes.append(NetworkLane(name=br.name, scope="local", tip_sha=br.sha, is_current=br.is_current)) + return lanes + + +def _parse_network_log(output: str, sha_to_lane: dict[str, int]) -> list[NetworkCommit]: + commits: list[NetworkCommit] = [] + current_fields: list[str] | None = None + current_files: list[tuple[str, str]] = [] + + def _flush() -> None: + if current_fields is None: + return + sha, short_sha, date_lbl, author, parents_str, subject = current_fields + commits.append( + NetworkCommit( + sha=sha, + short_sha=short_sha, + date_label=date_lbl, + author=author, + subject=subject, + lane_index=sha_to_lane.get(sha, 0), + parents=tuple(p for p in parents_str.split() if p), + file_changes=tuple(current_files), + ) + ) + + for line in output.splitlines(): + if line.startswith("__NET__\t"): + _flush() + parts = line.split("\t", 6) + current_fields = parts[1:] if len(parts) >= 7 else None + current_files = [] + elif line.strip() and current_fields is not None and "\t" in line: + status, path = line.split("\t", 1) + current_files.append((status[:1], path.strip())) + _flush() + return commits + + +def list_tracked_files(repo_root: Path) -> list[str]: + """Return tracked file paths in the repository.""" + res = run_git(["ls-files", "-z"], cwd=repo_root) + return sorted(split_nul_lines(res.stdout)) + + +def inspect_object(location: RepoLocation, rev_or_sha: str) -> GitObject: + """Inspect a Git object using native loose `.git/objects` first, falling back to `git cat-file`.""" + rev_res = run_git(["rev-parse", "--verify", rev_or_sha], cwd=location.root) + sha = rev_res.stdout.strip() + + loose = read_loose_object(location.common_dir, sha) + if loose is not None: + return loose + + kind = run_git(["cat-file", "-t", sha], cwd=location.root).stdout.strip() + size = int(run_git(["cat-file", "-s", sha], cwd=location.root).stdout.strip()) + content = run_git_bytes(["cat-file", kind, sha], cwd=location.root) + return GitObject(kind=kind, size=size, sha=sha, content=content, source="packed") + + +def list_branches(repo_root: Path, include_remote: bool = False) -> list[BranchInfo]: + """Return local (and optionally remote) branches.""" + args = [ + "for-each-ref", + "--format=%(HEAD)%09%(refname:short)%09%(objectname)%09%(upstream:short)%09%(refname)", + "refs/heads", + ] + if include_remote: + args.append("refs/remotes") + res = run_git(args, cwd=repo_root) + branches: list[BranchInfo] = [] + for line in res.stdout.splitlines(): + if not line.strip(): + continue + head_mark, name, sha, upstream, full_ref = line.split("\t") + branches.append( + BranchInfo( + name=name, + sha=sha, + is_current=(head_mark.strip() == "*"), + is_remote=full_ref.startswith("refs/remotes/"), + upstream=upstream or None, + ) + ) + return branches + + +def create_branch(repo_root: Path, name: str) -> None: + run_git(["branch", name], cwd=repo_root) + + +def delete_branch(repo_root: Path, name: str, force: bool = False) -> None: + flag = "-D" if force else "-d" + run_git(["branch", flag, name], cwd=repo_root) + + +def switch_branch(repo_root: Path, name: str, create: bool = False) -> None: + args = ["switch"] + if create: + args.append("-c") + args.append(name) + run_git(args, cwd=repo_root) + + +def merge_branch( + repo_root: Path, + branch: str | None = None, + abort: bool = False, + continue_merge: bool = False, +) -> str: + if abort: + return run_git(["merge", "--abort"], cwd=repo_root).stdout + if continue_merge: + return run_git(["merge", "--continue", "--no-edit"], cwd=repo_root).stdout + if not branch: + raise SimpleGitError("Specify a branch name to merge.", hint="Usage: `sgit merge `") + return run_git(["merge", branch], cwd=repo_root).stdout + + +def undo_commit(repo_root: Path) -> str: + """Undo the most recent commit while preserving all edits in the index/worktree.""" + has_head = run_git(["rev-parse", "--verify", "--quiet", "HEAD"], cwd=repo_root, check=False) + if has_head.returncode != 0: + raise SimpleGitError("There are no commits to undo yet.") + + has_parent = run_git(["rev-parse", "--verify", "--quiet", "HEAD~1"], cwd=repo_root, check=False) + if has_parent.returncode == 0: + run_git(["reset", "--soft", "HEAD~1"], cwd=repo_root) + return "Undid last commit (changes remain staged)." + + # Root commit has no parent; delete HEAD ref while keeping staged files intact. + run_git(["update-ref", "-d", "HEAD"], cwd=repo_root) + return "Undid initial commit (changes remain staged)." + + +def undo_stage(repo_root: Path, paths: list[str] | None = None) -> None: + """Unstage files without modifying working tree contents.""" + has_head = run_git(["rev-parse", "--verify", "--quiet", "HEAD"], cwd=repo_root, check=False) + if has_head.returncode == 0: + args = ["reset", "-q", "HEAD"] + if paths: + args.extend(["--", *paths]) + run_git(args, cwd=repo_root) + else: + targets = paths if paths else ["."] + run_git(["rm", "-r", "--cached", "-q", "--", *targets], cwd=repo_root) + + +def undo_changes(repo_root: Path, paths: list[str] | None = None) -> None: + """Discard unstaged working tree modifications.""" + targets = paths if paths else ["."] + run_git(["restore", "--worktree", "--", *targets], cwd=repo_root) + + +def init_repo(path: Path | None = None, bare: bool = False) -> Path: + """Initialize a new Git repository defaulting to `main`.""" + target = (path or Path.cwd()).resolve() + target.mkdir(parents=True, exist_ok=True) + args = ["init", "-b", "main"] + if bare: + args.append("--bare") + res = run_git(args, cwd=target, check=False) + if res.returncode != 0: + # Fallback for Git versions prior to `-b` on init + fallback = ["init"] + (["--bare"] if bare else []) + run_git(fallback, cwd=target) + return target + + +def resolve_clone_url( + target: str, + github: bool = False, + gitlab: bool = False, + ssh: bool = False, +) -> str: + """Resolve a clone target from `-gh`/`-gl` shorthand, hosted `.git` URL, or local path.""" + if github and gitlab: + raise SimpleGitError( + "Choose either `-gh` (GitHub) or `-gl` (GitLab), not both.", + ) + + cleaned = target.strip() + if not cleaned: + raise SimpleGitError("Repository URL or path is required.") + + if github or gitlab: + if "://" in cleaned or cleaned.startswith("git@"): + return cleaned + host = "github.com" if github else "gitlab.com" + slug = cleaned.strip("/") + if slug.endswith(".git"): + slug = slug[:-4] + if "/" not in slug: + flag = "-gh" if github else "-gl" + raise SimpleGitError( + f"Invalid repository shorthand '{target}'.", + hint=f"Expected `owner/repo`, e.g. `sgit clone {flag} owner/repo`.", + ) + return f"git@{host}:{slug}.git" if ssh else f"https://{host}/{slug}.git" + + if "://" in cleaned or cleaned.startswith("git@") or Path(cleaned).expanduser().exists(): + return cleaned + + first_part, _, rest = cleaned.partition("/") + if "." in first_part and rest: + slug = cleaned.rstrip("/") + if not slug.endswith(".git"): + slug = f"{slug}.git" + if ssh: + path_part = slug.split("/", 1)[1] + return f"git@{first_part}:{path_part}" + return f"https://{slug}" + + raise SimpleGitError( + f"Cannot determine repository host for '{target}'.", + hint="Use `-gh` for GitHub, `-gl` for GitLab, or pass a full `.git` URL / local `.git` directory.", + ) + + +def clone_repo( + url: str, + directory: str | None = None, + branch: str | None = None, + github: bool = False, + gitlab: bool = False, + ssh: bool = False, +) -> str: + """Clone a remote or local `.git` repository and return the resolved URL.""" + resolved = resolve_clone_url(url, github=github, gitlab=gitlab, ssh=ssh) + args = ["clone"] + if branch: + args.extend(["-b", branch]) + args.append(resolved) + if directory: + args.append(directory) + run_git(args, interactive=True, stream_output=True) + return resolved + + +def pull_repo(repo_root: Path, use_merge: bool = False, autostash: bool = False) -> None: + args = ["pull"] + if not use_merge: + args.append("--rebase") + if autostash: + args.append("--autostash") + run_git(args, cwd=repo_root, interactive=True, stream_output=True) + + +def push_repo(repo_root: Path) -> None: + state = get_repo_state(repo_root) + if state.detached: + raise SimpleGitError( + "Cannot push while in detached HEAD state.", + hint="Switch to a branch first with `sgit switch `.", + ) + if state.upstream: + run_git(["push"], cwd=repo_root, interactive=True, stream_output=True) + else: + run_git(["push", "-u", "origin", state.branch], cwd=repo_root, interactive=True, stream_output=True) + + +def sync_repo( + repo_root: Path, + use_merge: bool = False, + autostash: bool = False, + dry_run: bool = False, +) -> list[str]: + """Fetch, pull (if upstream exists), and push current branch.""" + state = get_repo_state(repo_root) + if state.detached: + raise SimpleGitError( + "Cannot sync while in detached HEAD state.", + hint="Switch to a branch first with `sgit switch `.", + ) + + actions: list[str] = [] + if state.upstream: + actions.append(f"pull ({'merge' if use_merge else 'rebase'}) from {state.upstream}") + else: + actions.append(f"publish new branch '{state.branch}' to origin") + actions.append(f"push '{state.branch}'") + + if dry_run: + return actions + + if state.upstream: + pull_repo(repo_root, use_merge=use_merge, autostash=autostash) + push_repo(repo_root) + return actions diff --git a/simplegit/core/runner.py b/simplegit/core/runner.py new file mode 100644 index 0000000..3291448 --- /dev/null +++ b/simplegit/core/runner.py @@ -0,0 +1,102 @@ +"""Safe subprocess runner around the system `git` binary.""" + +from __future__ import annotations + +import os +import re +import shutil +import subprocess +from dataclasses import dataclass +from pathlib import Path + +from simplegit.errors import GitNotFoundError, translate_git_error + +_VERSION_RE = re.compile(r"(\d+)\.(\d+)\.(\d+)") + + +@dataclass(frozen=True) +class GitResult: + """Captured output of a `git` invocation.""" + + args: list[str] + returncode: int + stdout: str + stderr: str + + +def find_git_binary() -> str: + """Return path to `git` executable or raise `GitNotFoundError`.""" + git_path = shutil.which("git") + if not git_path: + raise GitNotFoundError( + message="`git` was not found on your PATH.", + hint="Install Git (e.g., `brew install git`, `choco install git`, or https://git-scm.com) and try again.", + ) + return git_path + + +def get_git_version() -> tuple[int, int, int]: + """Return installed Git `(major, minor, patch)` version tuple.""" + res = run_git(["--version"], check=True) + match = _VERSION_RE.search(res.stdout) + if not match: + return (0, 0, 0) + return (int(match.group(1)), int(match.group(2)), int(match.group(3))) + + +def run_git( + args: list[str], + cwd: Path | None = None, + check: bool = True, + interactive: bool = False, + stream_output: bool = False, +) -> GitResult: + """Run `git` with explicit arg array (never shell=True) and translated errors.""" + git_bin = find_git_binary() + full_cmd = [git_bin, *args] + + env = os.environ.copy() + if not interactive: + env.setdefault("GIT_TERMINAL_PROMPT", "0") + + if stream_output: + proc = subprocess.run(full_cmd, cwd=cwd, env=env, text=True) + res = GitResult(args=args, returncode=proc.returncode, stdout="", stderr="") + else: + proc = subprocess.run( + full_cmd, + cwd=cwd, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + ) + res = GitResult( + args=args, + returncode=proc.returncode, + stdout=proc.stdout, + stderr=proc.stderr, + ) + + if check and res.returncode != 0: + raise translate_git_error(args, res.returncode, res.stderr, res.stdout) + return res + + +def run_git_bytes(args: list[str], cwd: Path | None = None) -> bytes: + """Run `git` and return raw stdout bytes (used for binary object fallback).""" + git_bin = find_git_binary() + env = os.environ.copy() + env.setdefault("GIT_TERMINAL_PROMPT", "0") + proc = subprocess.run([git_bin, *args], cwd=cwd, env=env, capture_output=True) + if proc.returncode != 0: + stderr = proc.stderr.decode("utf-8", errors="replace") + stdout = proc.stdout.decode("utf-8", errors="replace") + raise translate_git_error(args, proc.returncode, stderr, stdout) + return proc.stdout + + +def split_nul_lines(output: str) -> list[str]: + """Split NUL-delimited (`-z`) Git output into non-empty strings.""" + return [entry for entry in output.split("\0") if entry] diff --git a/simplegit/errors.py b/simplegit/errors.py new file mode 100644 index 0000000..33f7fc1 --- /dev/null +++ b/simplegit/errors.py @@ -0,0 +1,179 @@ +"""Structured error hierarchy and Git stderr-to-hint translation.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field + + +@dataclass +class SimpleGitError(Exception): + """Base error with user-facing message, optional recovery hint, and context.""" + + message: str + hint: str | None = None + command: str | None = None + details: str | None = None + affected_files: list[str] = field(default_factory=list) + exit_code: int = 1 + + def __str__(self) -> str: + return self.message + + +class GitNotFoundError(SimpleGitError): + """Raised when the `git` binary cannot be located on PATH.""" + + +class NotARepoError(SimpleGitError): + """Raised when an operation is invoked outside a Git repository.""" + + +class NothingToCommitError(SimpleGitError): + """Raised when `sgit save` finds no staged or unstaged changes to commit.""" + + +class MergeConflictError(SimpleGitError): + """Raised when a merge, pull, or rebase hits unresolved conflicts.""" + + +class DirtyWorktreeError(SimpleGitError): + """Raised when uncommitted changes block a branch switch, merge, or sync.""" + + +class UpstreamMissingError(SimpleGitError): + """Raised when a branch has no configured upstream tracking branch.""" + + +class PushRejectedError(SimpleGitError): + """Raised when remote rejects a non-fast-forward push.""" + + +class InvalidRefError(SimpleGitError): + """Raised when a branch, tag, commit, or pathspec does not exist.""" + + +class CommandFailedError(SimpleGitError): + """Fallback error for uncategorized `git` subprocess failures.""" + + +_CONFLICT_RE = re.compile(r"CONFLICT \([^)]+\): Merge conflict in (.+)") +_OVERWRITE_LINE_RE = re.compile(r"^\t(.+)$", re.MULTILINE) + + +def _extract_overwritten_files(stderr: str) -> list[str]: + """Extract indented filenames from Git's 'would be overwritten' messages.""" + lines: list[str] = [] + capture = False + for raw in stderr.splitlines(): + if "would be overwritten" in raw: + capture = True + continue + if capture: + if raw.startswith("\t"): + lines.append(raw.strip()) + elif raw.strip(): + break + return lines + + +def translate_git_error( + args: list[str], + returncode: int, + stderr: str, + stdout: str = "", +) -> SimpleGitError: + """Translate a failed `git` invocation into a friendly `SimpleGitError`.""" + cmd_str = "git " + " ".join(args) + combined = "\n".join(part for part in (stderr.strip(), stdout.strip()) if part) + lower = combined.lower() + + if "not a git repository" in lower: + return NotARepoError( + message="This folder is not inside a Git repository.", + hint="Run `sgit init` to start a new repository here, or `cd` into an existing one.", + command=cmd_str, + details=combined, + exit_code=returncode or 1, + ) + + conflicts = _CONFLICT_RE.findall(combined) + if conflicts or "fix conflicts and then commit" in lower or "unmerged files" in lower: + return MergeConflictError( + message="Merge conflict detected.", + hint="Resolve the conflicted files below, then run `sgit save \"resolve conflicts\"` (or `sgit merge --abort` to cancel).", + command=cmd_str, + details=combined, + affected_files=conflicts, + exit_code=returncode or 1, + ) + + if "would be overwritten" in lower or "local changes to the following files" in lower: + files = _extract_overwritten_files(combined) + return DirtyWorktreeError( + message="Local uncommitted changes would be overwritten by this action.", + hint="Run `sgit save \"wip\"` to commit your changes first, or `sgit undo changes` to discard them.", + command=cmd_str, + details=combined, + affected_files=files, + exit_code=returncode or 1, + ) + + if "nothing to commit" in lower or "no changes added to commit" in lower: + return NothingToCommitError( + message="Nothing to commit — your working tree has no changes.", + hint="Edit or create a file first, then run `sgit save \"your message\"`.", + command=cmd_str, + details=combined, + exit_code=returncode or 1, + ) + + if "has no upstream branch" in lower: + return UpstreamMissingError( + message="Current branch does not track a remote branch yet.", + hint="Run `sgit push` or `sgit sync` to publish and link it automatically.", + command=cmd_str, + details=combined, + exit_code=returncode or 1, + ) + + if "non-fast-forward" in lower or "fetch first" in lower or "[rejected]" in lower: + return PushRejectedError( + message="Push was rejected because the remote has newer commits.", + hint="Run `sgit sync` to pull remote changes and push safely.", + command=cmd_str, + details=combined, + exit_code=returncode or 1, + ) + + if ( + "did not match any file(s) known to git" in lower + or "invalid reference" in lower + or "not a valid object name" in lower + or "unknown revision" in lower + ): + return InvalidRefError( + message="The specified branch, commit, or file path was not found.", + hint="Check `sgit branch` or `sgit log` for valid names and commit hashes.", + command=cmd_str, + details=combined, + exit_code=returncode or 1, + ) + + if "please tell me who you are" in lower or "author identity unknown" in lower: + return CommandFailedError( + message="Git author name/email is not configured.", + hint='Set your identity with:\n git config --global user.name "Your Name"\n git config --global user.email "you@example.com"', + command=cmd_str, + details=combined, + exit_code=returncode or 1, + ) + + first_line = next((ln.strip() for ln in combined.splitlines() if ln.strip()), "Git command failed.") + return CommandFailedError( + message=first_line, + hint="Run `sgit status` to inspect your repository state.", + command=cmd_str, + details=combined, + exit_code=returncode or 1, + ) diff --git a/simplegit/ui/__init__.py b/simplegit/ui/__init__.py new file mode 100644 index 0000000..89b2cc4 --- /dev/null +++ b/simplegit/ui/__init__.py @@ -0,0 +1,3 @@ +"""Cross-platform terminal UI, ANSI theme, and rendering helpers.""" + +from __future__ import annotations diff --git a/simplegit/ui/render.py b/simplegit/ui/render.py new file mode 100644 index 0000000..a57ee54 --- /dev/null +++ b/simplegit/ui/render.py @@ -0,0 +1,341 @@ +"""Terminal renderers for errors, status, diffs, logs, and `.git` objects.""" + +from __future__ import annotations + +import sys + +from simplegit.core.models import ( + BranchInfo, + CommitInfo, + FileChange, + GitObject, + NetworkCommit, + NetworkGraph, + RepoState, +) +from simplegit.core.native_git import parse_commit_object, parse_tree_object +from simplegit.errors import SimpleGitError +from simplegit.ui.theme import THEME + + +def render_error(err: SimpleGitError) -> None: + """Print a high-contrast error block to stderr so failures are easy to spot.""" + stream = sys.stderr + badge = THEME.badge("ERROR", "bg_red", stream=stream) + print(f"\n{badge} {THEME.error(err.message, stream=stream)}", file=stream) + + if err.affected_files: + print(THEME.warn(" Affected files:", stream=stream), file=stream) + for path in err.affected_files[:15]: + print(f" {THEME.error('•', stream=stream)} {path}", file=stream) + if len(err.affected_files) > 15: + remaining = len(err.affected_files) - 15 + print(THEME.muted(f" ... and {remaining} more", stream=stream), file=stream) + + if err.command: + print(f" {THEME.muted('Command:')} {err.command}", file=stream) + + if err.details: + first_lines = [ln for ln in err.details.splitlines() if ln.strip()][:4] + if first_lines: + print(f" {THEME.muted('Git output:')}", file=stream) + for ln in first_lines: + print(f" {THEME.style(ln, 'red', stream=stream)}", file=stream) + + if err.hint: + print(f" {THEME.info('Hint:')} {err.hint}", file=stream) + print(file=stream) + + +def render_status(state: RepoState, short: bool = False) -> None: + """Render grouped repository status and actionable next-step guidance.""" + branch_label = ( + THEME.warn(f"detached @ {state.branch}") + if state.detached + else THEME.accent(state.branch) + ) + tracking = "" + if state.upstream: + parts: list[str] = [] + if state.ahead: + parts.append(THEME.success(f"↑{state.ahead}")) + if state.behind: + parts.append(THEME.warn(f"↓{state.behind}")) + delta = " ".join(parts) if parts else THEME.muted("up to date") + tracking = f" {THEME.muted('->')} {THEME.info(state.upstream)} ({delta})" + + print(f"{THEME.bold('On branch')} {branch_label}{tracking}") + if state.active_op: + print(f"{THEME.badge(state.active_op, 'bg_yellow')} {THEME.warn('Operation in progress')}") + + if state.is_clean: + print(THEME.success("✓ Working tree clean — nothing to commit.")) + return + + if short: + for change in state.changes: + code = "??" if change.untracked else f"{change.status_x}{change.status_y}" + print(f" {THEME.warn(code)} {change.display_path}") + return + + _print_change_group("Conflicts (resolve before committing)", state.conflicted_files, "bright_red", "!") + _print_change_group("Staged (ready to commit)", state.staged_files, "green", "+") + _print_change_group("Modified (unstaged changes)", state.unstaged_files, "yellow", "~") + _print_change_group("Untracked (new files)", state.untracked_files, "cyan", "?") + + print() + if state.conflicted_files: + print(THEME.info('Next: resolve conflicts, then run `sgit save "resolve conflicts"`')) + else: + print(THEME.muted('Tip: run `sgit save "your message"` to stage & commit in one step.')) + + +def _print_change_group(title: str, items: list[FileChange], color: str, marker: str) -> None: + if not items: + return + print() + print(THEME.style(f"{title} ({len(items)}):", "bold", color)) + for item in items: + print(f" {THEME.style(marker, 'bold', color)} {item.display_path}") + + +def render_diff(diff_text: str) -> None: + """Colorize unified diff output cleanly.""" + if not diff_text.strip(): + print(THEME.muted("No differences to display.")) + return + for line in diff_text.splitlines(): + if line.startswith(("diff --git", "index ", "--- ", "+++ ")): + print(THEME.bold(line)) + elif line.startswith("@@"): + print(THEME.info(line)) + elif line.startswith("+"): + print(THEME.style(line, "green")) + elif line.startswith("-"): + print(THEME.style(line, "red")) + else: + print(line) + + +def render_log(commits: list[CommitInfo]) -> None: + """Render concise commit history.""" + if not commits: + print(THEME.muted("No commits yet.")) + return + for commit in commits: + sha = THEME.warn(commit.short_sha) + date = THEME.muted(commit.date) + author = THEME.info(commit.author) + print(f"{sha} {commit.subject} {THEME.muted('(')}{date} · {author}{THEME.muted(')')}") + + +def render_branches(branches: list[BranchInfo]) -> None: + """Render local and remote branches.""" + if not branches: + print(THEME.muted("No branches found.")) + return + for br in branches: + marker = THEME.success("* ") if br.is_current else " " + name = THEME.success(br.name) if br.is_current else (THEME.muted(br.name) if br.is_remote else br.name) + sha = THEME.muted(br.sha[:7]) + upstream = f" -> {THEME.info(br.upstream)}" if br.upstream else "" + print(f"{marker}{name} {sha}{upstream}") + + +def render_git_object(obj: GitObject) -> None: + """Render a decoded `.git` object (`commit`, `tree`, `blob`, or `tag`).""" + print(f"{THEME.bold('Object:')} {THEME.warn(obj.sha)} ({THEME.info(obj.kind)}, {obj.size} bytes, {obj.source})") + if obj.kind == "commit": + parsed = parse_commit_object(obj.content) + print(f" {THEME.muted('tree:')} {parsed['tree']}") + for parent in parsed["parents"]: + print(f" {THEME.muted('parent:')} {parent}") + if parsed["author"]: + print(f" {THEME.muted('author:')} {parsed['author']}") + if parsed["committer"]: + print(f" {THEME.muted('committer:')} {parsed['committer']}") + print() + for line in parsed["message"].splitlines(): + print(f" {line}") + elif obj.kind == "tree": + for mode, name, sha in parse_tree_object(obj.content): + print(f" {THEME.muted(mode.zfill(6))} {THEME.warn(sha[:7])} {name}") + else: + text = obj.content.decode("utf-8", errors="replace") + print(text, end="" if text.endswith("\n") else "\n") + + +_LANE_COLORS = ("cyan", "green", "magenta", "yellow", "blue", "bright_cyan") + + +def render_viewer( + state: RepoState, + graph: NetworkGraph, + tracked_files: list[str] | None = None, +) -> None: + """Render a GitHub Insights/Network-style X=Time, Y=Branches graph.""" + branch_label = THEME.warn(f"detached@{state.branch}") if state.detached else THEME.accent(state.branch) + print(THEME.bold(f"Network Graph (X: Time →, Y: Branches ↕) — {state.location.root.name}") + f" [{branch_label}]") + if state.active_op: + print(f" {THEME.badge(state.active_op, 'bg_yellow')} {THEME.warn('Operation in progress')}") + + if not graph.commits or not graph.lanes: + print(THEME.muted("\n No commits yet.")) + return + + lanes = graph.lanes + commits = graph.commits + col_w = 7 + sha_to_col = {c.sha: i for i, c in enumerate(commits)} + sha_to_commit = {c.sha: c for c in commits} + + grid_rows = len(lanes) * 2 - 1 + grid_cols = len(commits) * col_w + canvas: list[list[str]] = [[" " for _ in range(grid_cols)] for _ in range(grid_rows)] + cell_color: list[list[str | None]] = [[None for _ in range(grid_cols)] for _ in range(grid_rows)] + + def _put(r: int, x: int, ch: str, color: str | None = None) -> None: + if 0 <= r < grid_rows and 0 <= x < grid_cols: + canvas[r][x] = ch + if color: + cell_color[r][x] = color + + # Draw horizontal & fork/merge edges first, then commit nodes on top. + for col_idx, commit in enumerate(commits): + lane_c = commit.lane_index + row_c = lane_c * 2 + x_c = col_idx * col_w + color_c = _LANE_COLORS[lane_c % len(_LANE_COLORS)] + + for parent_sha in commit.parents: + if parent_sha not in sha_to_col: + continue + col_p = sha_to_col[parent_sha] + lane_p = sha_to_commit[parent_sha].lane_index + x_p = col_p * col_w + + if lane_p == lane_c: + for x in range(x_p + 1, x_c): + _put(row_c, x, "─", color_c) + elif lane_p < lane_c: + # Fork downward from parent lane to child lane. + row_p = lane_p * 2 + for r in range(row_p + 1, row_c): + _put(r, x_p, "│", color_c) + _put(row_c, x_p, "╰", color_c) + for x in range(x_p + 1, x_c): + _put(row_c, x, "─", color_c) + else: + # Merge upward from parent lane into child lane. + row_p = lane_p * 2 + color_p = _LANE_COLORS[lane_p % len(_LANE_COLORS)] + for x in range(x_p + 1, x_c): + _put(row_p, x, "─", color_p) + _put(row_p, x_c, "╯", color_p) + for r in range(row_c + 1, row_p): + _put(r, x_c, "│", color_p) + + for col_idx, commit in enumerate(commits): + row = commit.lane_index * 2 + x = col_idx * col_w + color = _LANE_COLORS[commit.lane_index % len(_LANE_COLORS)] + node = "◆" if len(commit.parents) > 1 else "●" + label = f"{node}[{col_idx + 1}]" + for offset, ch in enumerate(label): + _put(row, x + offset, ch, color) + + # Mark hosted/local branch tips that sit on another lane's commit. + for lane_idx, lane in enumerate(lanes): + if lane.tip_sha in sha_to_col: + tip_col = sha_to_col[lane.tip_sha] + if sha_to_commit[lane.tip_sha].lane_index != lane_idx: + _put(lane_idx * 2, tip_col * col_w, "◎", _LANE_COLORS[lane_idx % len(_LANE_COLORS)]) + + scope_tags = ["[Hosted]" if ln.scope == "hosted" else "[Local] " for ln in lanes] + name_w = max(len(ln.name) for ln in lanes) + 3 + prefix_w = len(scope_tags[0]) + 1 + name_w + + print() + for r in range(grid_rows): + if r % 2 == 0: + lane_idx = r // 2 + lane = lanes[lane_idx] + color = _LANE_COLORS[lane_idx % len(_LANE_COLORS)] + scope_styled = ( + THEME.info("[Hosted]") if lane.scope == "hosted" else THEME.success("[Local] ") + ) + marker = "* " if lane.is_current else " " + name_str = f"{marker}{lane.name}".ljust(name_w) + name_styled = THEME.style(name_str, "bold", color) if lane.is_current else THEME.style(name_str, color) + left = f" {scope_styled} {name_styled}{THEME.muted('│')} " + else: + left = f" {' ' * prefix_w}{THEME.muted('│')} " + + row_chars = _render_colored_row(canvas[r], cell_color[r]) + print(f"{left}{row_chars.rstrip()}") + + axis_len = max(grid_cols + 2, 20) + axis_pad = " " * (prefix_w + 2) + print(f"{axis_pad}{THEME.muted('└' + '─' * axis_len + '▶ Time')}") + first_dt = commits[0].date_label + last_dt = commits[-1].date_label + if len(commits) == 1: + print(f"{axis_pad} {THEME.muted(first_dt)}") + else: + gap = max(2, axis_len - len(first_dt) - len(last_dt)) + print(f"{axis_pad} {THEME.muted(first_dt + ' ' * gap + last_dt)}") + + print(THEME.bold("\nChanges Made & When:")) + for idx, commit in enumerate(commits, start=1): + lane = lanes[commit.lane_index] + color = _LANE_COLORS[commit.lane_index % len(_LANE_COLORS)] + tag = THEME.style(f"[{idx}]", "bold", color) + when = THEME.muted(commit.date_label) + br = THEME.style(lane.name, color) + sha = THEME.warn(commit.short_sha) + files_str = _format_commit_files(commit.file_changes) + print(f" {tag} {when} {br} {sha} {commit.subject}{files_str}") + + if tracked_files is not None: + print(THEME.bold(f"\nRepository Files ({len(tracked_files)}):")) + _render_file_tree(tracked_files) + + +def _render_colored_row(chars: list[str], colors: list[str | None]) -> str: + out: list[str] = [] + for ch, color in zip(chars, colors): + out.append(THEME.style(ch, color) if color and ch != " " else ch) + return "".join(out) + + +def _format_commit_files(file_changes: tuple[tuple[str, str], ...]) -> str: + if not file_changes: + return "" + markers = {"A": "+", "M": "~", "D": "-"} + shown = [f"{markers.get(st, st)}{path}" for st, path in file_changes[:4]] + extra = f", +{len(file_changes) - 4} more" if len(file_changes) > 4 else "" + return " " + THEME.muted("(" + ", ".join(shown) + extra + ")") + + +def _render_file_tree(paths: list[str]) -> None: + if not paths: + print(THEME.muted(" (no tracked files)")) + return + tree: dict = {} + for path in paths: + node = tree + for part in path.split("/"): + node = node.setdefault(part, {}) + _print_tree_node(tree, prefix=" ") + + +def _print_tree_node(node: dict, prefix: str) -> None: + items = sorted(node.items(), key=lambda kv: (len(kv[1]) == 0, kv[0])) + for i, (name, children) in enumerate(items): + is_last = i == len(items) - 1 + branch_ch = "└── " if is_last else "├── " + label = THEME.accent(name + "/") if children else name + print(f"{prefix}{THEME.muted(branch_ch)}{label}") + if children: + ext = " " if is_last else "│ " + _print_tree_node(children, prefix + THEME.muted(ext)) diff --git a/simplegit/ui/terminal.py b/simplegit/ui/terminal.py new file mode 100644 index 0000000..f236fb4 --- /dev/null +++ b/simplegit/ui/terminal.py @@ -0,0 +1,198 @@ +"""Cross-platform interactive terminal key reader and selection widgets.""" + +from __future__ import annotations + +import os +import sys +from typing import Sequence + +from simplegit.ui.theme import THEME + + +def is_interactive_tty() -> bool: + """Return True when both stdin and stdout are attached to an interactive TTY.""" + return bool(sys.stdin.isatty() and sys.stdout.isatty()) + + +def clear_screen() -> None: + """Clear terminal screen if running interactively.""" + if sys.stdout.isatty(): + sys.stdout.write("\033[2J\033[H") + sys.stdout.flush() + + +def read_key() -> str: + """Read a single normalized keypress ('UP', 'DOWN', 'ENTER', 'SPACE', 'ESC', or char).""" + if not sys.stdin.isatty(): + line = sys.stdin.readline() + if not line: + return "EOF" + return line.strip()[:1] or "ENTER" + + if os.name == "nt": + import msvcrt + + ch = msvcrt.getwch() + if ch in ("\x00", "\xe0"): + ext = msvcrt.getwch() + return {"H": "UP", "P": "DOWN", "K": "LEFT", "M": "RIGHT"}.get(ext, "") + if ch in ("\r", "\n"): + return "ENTER" + if ch == " ": + return "SPACE" + if ch == "\x1b": + return "ESC" + if ch == "\x03": + raise KeyboardInterrupt + return ch + + import termios + import tty + + fd = sys.stdin.fileno() + old_settings = termios.tcgetattr(fd) + try: + tty.setraw(fd) + ch = sys.stdin.read(1) + if ch == "\x03": + raise KeyboardInterrupt + if ch in ("\r", "\n"): + return "ENTER" + if ch == " ": + return "SPACE" + if ch == "\x1b": + next1 = sys.stdin.read(1) if _posix_has_data(fd) else "" + if next1 == "[": + next2 = sys.stdin.read(1) if _posix_has_data(fd) else "" + return {"A": "UP", "B": "DOWN", "C": "RIGHT", "D": "LEFT"}.get(next2, "ESC") + return "ESC" + return ch + finally: + termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) + + +def _posix_has_data(fd: int) -> bool: + import select + + ready, _, _ = select.select([fd], [], [], 0.05) + return bool(ready) + + +def confirm(prompt: str, default: bool = False) -> bool: + """Ask a yes/no question cleanly, respecting default on Enter or EOF.""" + suffix = "[Y/n]" if default else "[y/N]" + sys.stdout.write(f"{THEME.warn('?')} {prompt} {THEME.muted(suffix)} ") + sys.stdout.flush() + try: + answer = sys.stdin.readline() + except EOFError: + return default + if not answer: + return default + cleaned = answer.strip().lower() + if not cleaned: + return default + return cleaned in ("y", "yes") + + +def prompt_line(label: str, default: str = "") -> str: + """Prompt for a single line of text input.""" + hint = f" [{default}]" if default else "" + sys.stdout.write(f"{THEME.info('>')} {label}{THEME.muted(hint)}: ") + sys.stdout.flush() + line = sys.stdin.readline() + if not line: + return default + value = line.rstrip("\r\n") + return value if value else default + + +def select_one(title: str, items: Sequence[str], allow_cancel: bool = True) -> int | None: + """Let the user choose one item index (arrow keys on TTY, numbered menu fallback).""" + if not items: + return None + if not is_interactive_tty(): + return _numbered_select_one(title, items, allow_cancel) + + idx = 0 + while True: + clear_screen() + print(THEME.bold(title)) + print(THEME.muted("Use ↑/↓ (or j/k) + Enter to select" + (", q to cancel" if allow_cancel else ""))) + print() + for i, item in enumerate(items): + cursor = THEME.accent("❯ ") if i == idx else " " + label = THEME.accent(item) if i == idx else item + print(f"{cursor}{label}") + + key = read_key() + if key in ("UP", "k"): + idx = (idx - 1) % len(items) + elif key in ("DOWN", "j"): + idx = (idx + 1) % len(items) + elif key == "ENTER": + return idx + elif allow_cancel and key in ("q", "ESC", "EOF"): + return None + + +def _numbered_select_one(title: str, items: Sequence[str], allow_cancel: bool) -> int | None: + print(THEME.bold(title)) + for i, item in enumerate(items, start=1): + print(f" {i}. {item}") + prompt = "Enter number" + (" (or 0 to cancel)" if allow_cancel else "") + raw = prompt_line(prompt) + if not raw or (allow_cancel and raw == "0"): + return None + try: + choice = int(raw) + except ValueError: + return None + if 1 <= choice <= len(items): + return choice - 1 + return None + + +def multi_select( + title: str, + items: Sequence[str], + preselected: set[int] | None = None, +) -> list[int] | None: + """Let the user toggle multiple items; returns selected indices or None on cancel.""" + if not items: + return [] + selected = set(preselected) if preselected is not None else set(range(len(items))) + if not is_interactive_tty(): + return sorted(selected) + + idx = 0 + while True: + clear_screen() + print(THEME.bold(title)) + print(THEME.muted("Space: toggle | a: all/none | Enter: confirm | q: cancel")) + print() + for i, item in enumerate(items): + cursor = THEME.accent("❯") if i == idx else " " + mark = THEME.success("[x]") if i in selected else THEME.muted("[ ]") + label = THEME.bold(item) if i == idx else item + print(f"{cursor} {mark} {label}") + + key = read_key() + if key in ("UP", "k"): + idx = (idx - 1) % len(items) + elif key in ("DOWN", "j"): + idx = (idx + 1) % len(items) + elif key == "SPACE": + if idx in selected: + selected.remove(idx) + else: + selected.add(idx) + elif key == "a": + if len(selected) == len(items): + selected.clear() + else: + selected = set(range(len(items))) + elif key == "ENTER": + return sorted(selected) + elif key in ("q", "ESC", "EOF"): + return None diff --git a/simplegit/ui/theme.py b/simplegit/ui/theme.py new file mode 100644 index 0000000..bff4bb4 --- /dev/null +++ b/simplegit/ui/theme.py @@ -0,0 +1,102 @@ +"""Cross-platform ANSI styling respecting NO_COLOR, FORCE_COLOR, and Windows VT100.""" + +from __future__ import annotations + +import os +import sys +from typing import TextIO + +_RESET = "\033[0m" +_CODES = { + "bold": "\033[1m", + "dim": "\033[2m", + "red": "\033[31m", + "green": "\033[32m", + "yellow": "\033[33m", + "blue": "\033[34m", + "magenta": "\033[35m", + "cyan": "\033[36m", + "white": "\033[37m", + "bright_red": "\033[91m", + "bright_green": "\033[92m", + "bright_yellow": "\033[93m", + "bright_cyan": "\033[96m", + "bg_red": "\033[41m", + "bg_green": "\033[42m", + "bg_yellow": "\033[43m", + "bg_blue": "\033[44m", +} + + +class Theme: + """Semantic ANSI color formatter with graceful fallback when color is disabled.""" + + def __init__(self, force_no_color: bool = False) -> None: + self._force_no_color = force_no_color + self._vt_initialized = False + + def _enable_windows_vt(self) -> None: + if self._vt_initialized or os.name != "nt": + return + self._vt_initialized = True + try: + import ctypes + + kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined] + for handle_id in (-11, -12): # STD_OUTPUT_HANDLE, STD_ERROR_HANDLE + handle = kernel32.GetStdHandle(handle_id) + mode = ctypes.c_uint32() + if kernel32.GetConsoleMode(handle, ctypes.byref(mode)): + kernel32.SetConsoleMode(handle, mode.value | 0x0004) + except Exception: + pass + + def enabled_for(self, stream: TextIO | None = None) -> bool: + """Return True if ANSI colors should be emitted to `stream`.""" + if self._force_no_color or os.environ.get("NO_COLOR") is not None: + return False + if os.environ.get("FORCE_COLOR"): + self._enable_windows_vt() + return True + target = stream or sys.stdout + term = os.environ.get("TERM", "") + if term.lower() == "dumb": + return False + is_tty = bool(getattr(target, "isatty", lambda: False)()) + if is_tty: + self._enable_windows_vt() + return is_tty + + def style(self, text: str, *names: str, stream: TextIO | None = None) -> str: + """Wrap `text` with ANSI codes if color is enabled for `stream`.""" + if not names or not self.enabled_for(stream): + return text + prefix = "".join(_CODES[n] for n in names if n in _CODES) + return f"{prefix}{text}{_RESET}" if prefix else text + + def error(self, text: str, stream: TextIO | None = None) -> str: + return self.style(text, "bold", "bright_red", stream=stream or sys.stderr) + + def warn(self, text: str, stream: TextIO | None = None) -> str: + return self.style(text, "bold", "yellow", stream=stream) + + def success(self, text: str, stream: TextIO | None = None) -> str: + return self.style(text, "bold", "green", stream=stream) + + def info(self, text: str, stream: TextIO | None = None) -> str: + return self.style(text, "cyan", stream=stream) + + def accent(self, text: str, stream: TextIO | None = None) -> str: + return self.style(text, "bold", "bright_cyan", stream=stream) + + def muted(self, text: str, stream: TextIO | None = None) -> str: + return self.style(text, "dim", stream=stream) + + def bold(self, text: str, stream: TextIO | None = None) -> str: + return self.style(text, "bold", stream=stream) + + def badge(self, label: str, bg: str = "bg_red", stream: TextIO | None = None) -> str: + return self.style(f" {label} ", "bold", "white", bg, stream=stream) + + +THEME = Theme() diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..fb5061d --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +"""SimpleGit test suite.""" diff --git a/tests/helpers.py b/tests/helpers.py new file mode 100644 index 0000000..6e253c2 --- /dev/null +++ b/tests/helpers.py @@ -0,0 +1,66 @@ +"""Isolated temporary Git repository helpers for SimpleGit tests.""" + +from __future__ import annotations + +import os +import subprocess +import tempfile +import unittest +from contextlib import contextmanager +from pathlib import Path +from typing import Iterator + + +class RepoTestCase(unittest.TestCase): + """Base TestCase providing isolated temp Git repositories and working directory management.""" + + def setUp(self) -> None: + self._tmpdir = tempfile.TemporaryDirectory() + self.tmp_path = Path(self._tmpdir.name).resolve() + + def tearDown(self) -> None: + self._tmpdir.cleanup() + + def run_raw_git(self, args: list[str], cwd: Path) -> subprocess.CompletedProcess[str]: + env = os.environ.copy() + env["GIT_TERMINAL_PROMPT"] = "0" + return subprocess.run( + ["git", *args], + cwd=cwd, + env=env, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + check=True, + ) + + def make_repo(self, name: str = "repo", initial_commit: bool = True) -> Path: + repo = self.tmp_path / name + repo.mkdir(parents=True, exist_ok=True) + res = subprocess.run(["git", "init", "-b", "main"], cwd=repo, capture_output=True, text=True) + if res.returncode != 0: + self.run_raw_git(["init"], cwd=repo) + self.run_raw_git(["config", "user.name", "SimpleGit Test"], cwd=repo) + self.run_raw_git(["config", "user.email", "test@simplegit.local"], cwd=repo) + if initial_commit: + (repo / "README.md").write_text("hello\n", encoding="utf-8") + self.run_raw_git(["add", "README.md"], cwd=repo) + self.run_raw_git(["commit", "-m", "Initial commit"], cwd=repo) + return repo + + def make_bare_remote(self, name: str = "remote.git") -> Path: + remote = self.tmp_path / name + remote.mkdir(parents=True, exist_ok=True) + res = subprocess.run(["git", "init", "--bare", "-b", "main"], cwd=remote, capture_output=True, text=True) + if res.returncode != 0: + self.run_raw_git(["init", "--bare"], cwd=remote) + return remote + + @contextmanager + def chdir(self, path: Path) -> Iterator[None]: + prev = Path.cwd() + os.chdir(path) + try: + yield + finally: + os.chdir(prev) diff --git a/tests/test_branches_undo.py b/tests/test_branches_undo.py new file mode 100644 index 0000000..4fcaf3a --- /dev/null +++ b/tests/test_branches_undo.py @@ -0,0 +1,84 @@ +"""Integration tests for branch, switch, merge, conflicts, and undo workflows.""" + +from __future__ import annotations + +from simplegit.cli import main +from simplegit.core.operations import ( + get_log, + get_repo_state, + list_branches, + merge_branch, + switch_branch, + undo_changes, + undo_commit, + undo_stage, +) +from simplegit.errors import MergeConflictError +from tests.helpers import RepoTestCase + + +class TestBranchesAndUndo(RepoTestCase): + def test_switch_create_and_merge(self) -> None: + repo = self.make_repo() + switch_branch(repo, "feat/demo", create=True) + (repo / "feature.txt").write_text("feat\n", encoding="utf-8") + with self.chdir(repo): + self.assertEqual(main(["save", "Add feature"]), 0) + + switch_branch(repo, "main") + merge_branch(repo, "feat/demo") + self.assertTrue((repo / "feature.txt").exists()) + names = [b.name for b in list_branches(repo)] + self.assertIn("feat/demo", names) + + def test_merge_conflict_raises_structured_error_and_aborts(self) -> None: + repo = self.make_repo() + switch_branch(repo, "branch-a", create=True) + (repo / "README.md").write_text("from A\n", encoding="utf-8") + with self.chdir(repo): + main(["save", "Edit on A"]) + + switch_branch(repo, "main") + (repo / "README.md").write_text("from main\n", encoding="utf-8") + with self.chdir(repo): + main(["save", "Edit on main"]) + + with self.assertRaises(MergeConflictError) as ctx: + merge_branch(repo, "branch-a") + self.assertIn("README.md", ctx.exception.affected_files) + self.assertEqual(get_repo_state(repo).active_op, "MERGING") + + merge_branch(repo, abort=True) + self.assertIsNone(get_repo_state(repo).active_op) + + def test_undo_commit_stage_and_changes(self) -> None: + repo = self.make_repo() + (repo / "README.md").write_text("v2\n", encoding="utf-8") + with self.chdir(repo): + main(["save", "Second commit"]) + self.assertEqual(len(get_log(repo, limit=10)), 2) + + undo_commit(repo) + self.assertEqual(len(get_log(repo, limit=10)), 1) + self.assertEqual(len(get_repo_state(repo).staged_files), 1) + + undo_stage(repo) + state = get_repo_state(repo) + self.assertEqual(len(state.staged_files), 0) + self.assertEqual(len(state.unstaged_files), 1) + + undo_changes(repo) + self.assertTrue(get_repo_state(repo).is_clean) + self.assertEqual((repo / "README.md").read_text(encoding="utf-8"), "hello\n") + + def test_undo_root_commit_edge_case(self) -> None: + repo = self.make_repo(initial_commit=False) + (repo / "init.txt").write_text("root\n", encoding="utf-8") + with self.chdir(repo): + main(["save", "Root commit"]) + self.assertEqual(len(get_log(repo, limit=10)), 1) + + msg = undo_commit(repo) + self.assertIn("initial commit", msg.lower()) + self.assertEqual(len(get_log(repo, limit=10)), 0) + self.assertEqual(len(get_repo_state(repo).staged_files), 1) diff --git a/tests/test_cli_interactive.py b/tests/test_cli_interactive.py new file mode 100644 index 0000000..d06af2c --- /dev/null +++ b/tests/test_cli_interactive.py @@ -0,0 +1,75 @@ +"""Tests for CLI dispatch, colored error rendering, `sgit cli` fallback, and npm shim.""" + +from __future__ import annotations + +import io +import os +import shutil +import subprocess +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from unittest.mock import patch + +from simplegit.cli import main +from tests.helpers import RepoTestCase + + +class TestCliAndInteractive(RepoTestCase): + def test_no_color_error_rendering(self) -> None: + outside = self.tmp_path / "not_a_repo" + outside.mkdir() + stderr = io.StringIO() + with self.chdir(outside), redirect_stderr(stderr): + rc = main(["--no-color", "status"]) + self.assertEqual(rc, 1) + out = stderr.getvalue() + self.assertIn("ERROR", out) + self.assertIn("sgit init", out) + self.assertNotIn("\033[", out) + + def test_inspect_command_uses_native_loose_object(self) -> None: + repo = self.make_repo() + stdout = io.StringIO() + with self.chdir(repo), redirect_stdout(stdout): + rc = main(["--no-color", "inspect", "HEAD"]) + self.assertEqual(rc, 0) + out = stdout.getvalue() + self.assertIn("loose", out) + self.assertIn("Initial commit", out) + + def test_viewer_renders_branches_graph_and_files(self) -> None: + repo = self.make_repo() + with self.chdir(repo): + main(["switch", "-c", "feat/ui"]) + (repo / "src").mkdir() + (repo / "src" / "app.py").write_text("print('hi')\n", encoding="utf-8") + main(["save", "Add app"]) + main(["switch", "main"]) + + stdout = io.StringIO() + with self.chdir(repo), redirect_stdout(stdout): + rc = main(["--no-color", "viewer", "--files"]) + self.assertEqual(rc, 0) + out = stdout.getvalue() + self.assertIn("Network Graph", out) + self.assertIn("[Local]", out) + self.assertIn("feat/ui", out) + self.assertIn("+src/app.py", out) + self.assertIn("README.md", out) + + def test_npm_shim_python_fallback(self) -> None: + node = shutil.which("node") + if not node: + self.skipTest("node not installed") + repo_root = Path(__file__).resolve().parent.parent + shim = repo_root / "packaging" / "npm" / "bin" / "sgit.js" + env = os.environ.copy() + env["SGIT_USE_PYTHON"] = "1" + proc = subprocess.run( + [node, str(shim), "--version"], + env=env, + capture_output=True, + text=True, + check=True, + ) + self.assertIn("SimpleGit", proc.stdout) diff --git a/tests/test_extras_auth.py b/tests/test_extras_auth.py new file mode 100644 index 0000000..e949ead --- /dev/null +++ b/tests/test_extras_auth.py @@ -0,0 +1,153 @@ +"""Tests for savepoints, remotes, conflicts, ignore, tags, doctor, and auth.""" + +from __future__ import annotations + +import io +import subprocess +from contextlib import redirect_stdout +from unittest.mock import patch + +from simplegit.cli import main +from simplegit.core.auth import host_for_provider, verify_provider_token +from simplegit.core.extras import ( + add_ignore_patterns, + add_remote, + create_tag, + delete_tag, + inspect_conflicts, + list_ignore_patterns, + list_remotes, + list_tags, + resolve_conflicts, + run_doctor, + savepoint_drop, + savepoint_list, + savepoint_pop, + savepoint_push, +) +from simplegit.core.operations import get_repo_state, merge_branch, switch_branch +from simplegit.errors import MergeConflictError, SimpleGitError +from tests.helpers import RepoTestCase + + +class TestExtrasAndAuth(RepoTestCase): + def test_savepoint_lifecycle_with_untracked(self) -> None: + repo = self.make_repo() + (repo / "README.md").write_text("wip edit\n", encoding="utf-8") + (repo / "temp.txt").write_text("untracked wip\n", encoding="utf-8") + + savepoint_push(repo, "wip feature") + self.assertTrue(get_repo_state(repo).is_clean) + items = savepoint_list(repo) + self.assertEqual(len(items), 1) + self.assertIn("wip feature", items[0]) + + savepoint_pop(repo, index=0) + self.assertFalse(get_repo_state(repo).is_clean) + self.assertTrue((repo / "temp.txt").exists()) + self.assertEqual(savepoint_list(repo), []) + + savepoint_push(repo, "drop me") + savepoint_drop(repo, index=0) + self.assertEqual(savepoint_list(repo), []) + + def test_remote_add_with_gh_and_gl(self) -> None: + repo = self.make_repo() + url_gh = add_remote(repo, "origin", "AdonZ/SimpleGit", github=True) + url_gl = add_remote(repo, "mirror", "org/proj", gitlab=True, ssh=True) + self.assertEqual(url_gh, "https://github.com/AdonZ/SimpleGit.git") + self.assertEqual(url_gl, "git@gitlab.com:org/proj.git") + self.assertEqual( + dict(list_remotes(repo)), + { + "origin": "https://github.com/AdonZ/SimpleGit.git", + "mirror": "git@gitlab.com:org/proj.git", + }, + ) + + def test_conflicts_inspect_and_resolve_ours(self) -> None: + repo = self.make_repo() + switch_branch(repo, "feat", create=True) + (repo / "README.md").write_text("feat line\n", encoding="utf-8") + with self.chdir(repo): + main(["save", "feat change"]) + + switch_branch(repo, "main") + (repo / "README.md").write_text("main line\n", encoding="utf-8") + with self.chdir(repo): + main(["save", "main change"]) + + with self.assertRaises(MergeConflictError): + merge_branch(repo, "feat") + + details = inspect_conflicts(repo) + self.assertEqual(len(details), 1) + self.assertEqual(details[0].path, "README.md") + self.assertTrue(len(details[0].marker_lines) >= 1) + + resolve_conflicts(repo, "ours", ["README.md"]) + self.assertEqual((repo / "README.md").read_text(encoding="utf-8"), "main line\n") + self.assertEqual(inspect_conflicts(repo), []) + + def test_ignore_patterns_and_template_dedup(self) -> None: + repo = self.make_repo() + added1 = add_ignore_patterns(repo, ["*.log", ".env"], template="python") + self.assertIn("*.log", added1) + self.assertIn("__pycache__/", added1) + + added2 = add_ignore_patterns(repo, ["*.log", "dist/"]) + self.assertEqual(added2, []) + self.assertIn(".env", list_ignore_patterns(repo)) + + def test_tag_create_list_delete(self) -> None: + repo = self.make_repo() + create_tag(repo, "v0.1.0", message="First release") + self.assertEqual(list_tags(repo), ["v0.1.0"]) + delete_tag(repo, "v0.1.0") + self.assertEqual(list_tags(repo), []) + + def test_doctor_runs_cleanly(self) -> None: + repo = self.make_repo() + checks = run_doctor(repo) + names = {c.name for c in checks} + self.assertIn("Git binary", names) + self.assertIn("Repository state", names) + + def test_auth_host_and_mocked_login_logout(self) -> None: + self.assertEqual(host_for_provider(github=True), "github.com") + self.assertEqual(host_for_provider(gitlab=True), "gitlab.com") + with self.assertRaises(SimpleGitError): + host_for_provider(github=True, gitlab=True) + + class _FakeResp: + def __init__(self, body: bytes) -> None: + self._body = body + + def read(self) -> bytes: + return self._body + + def __enter__(self) -> "_FakeResp": + return self + + def __exit__(self, *_args: object) -> None: + return None + + with patch("urllib.request.urlopen", return_value=_FakeResp(b'{"login": "adonz"}')): + self.assertEqual(verify_provider_token("github.com", "tok123"), "adonz") + + ok_proc = subprocess.CompletedProcess(args=[], returncode=0, stdout="username=adonz\n", stderr="") + stdout = io.StringIO() + with ( + patch("simplegit.core.auth.ensure_credential_helper", return_value="osxkeychain"), + patch("simplegit.core.auth._run_git_credential", return_value=ok_proc) as mock_cred, + redirect_stdout(stdout), + ): + rc = main(["auth", "login", "-gh", "--token", "tok", "-u", "adonz", "--skip-verify"]) + self.assertEqual(rc, 0) + self.assertIn("@adonz", stdout.getvalue()) + mock_cred.assert_called_once() + self.assertEqual(mock_cred.call_args[0][0], "approve") + + rc2 = main(["auth", "logout", "-gh"]) + self.assertEqual(rc2, 0) + self.assertEqual(mock_cred.call_args[0][0], "reject") diff --git a/tests/test_native_git.py b/tests/test_native_git.py new file mode 100644 index 0000000..1fba6b1 --- /dev/null +++ b/tests/test_native_git.py @@ -0,0 +1,92 @@ +"""Unit tests for pure-Python `.git` inspection in `simplegit.core.native_git`.""" + +from __future__ import annotations + +from simplegit.core.native_git import ( + compute_object_hash, + detect_active_operation, + discover_repo, + parse_commit_object, + parse_tree_object, + read_head, + read_loose_object, +) +from simplegit.errors import NotARepoError +from tests.helpers import RepoTestCase + + +class TestNativeGit(RepoTestCase): + def test_discover_repo_from_subdirectory(self) -> None: + repo = self.make_repo() + nested = repo / "src" / "pkg" + nested.mkdir(parents=True) + + loc = discover_repo(nested) + self.assertEqual(loc.root, repo) + self.assertEqual(loc.git_dir, repo / ".git") + self.assertFalse(loc.is_bare) + + def test_discover_repo_outside_git_raises(self) -> None: + outside = self.tmp_path / "plain_dir" + outside.mkdir() + with self.assertRaises(NotARepoError): + discover_repo(outside) + + def test_read_head_and_packed_refs(self) -> None: + repo = self.make_repo() + loc = discover_repo(repo) + branch, sha, detached = read_head(loc) + self.assertEqual(branch, "main") + self.assertIsNotNone(sha) + self.assertFalse(detached) + + # Pack refs and verify packed-refs resolution still finds HEAD SHA. + self.run_raw_git(["pack-refs", "--all"], cwd=repo) + branch2, sha2, detached2 = read_head(loc) + self.assertEqual(branch2, "main") + self.assertEqual(sha2, sha) + self.assertFalse(detached2) + + def test_detect_active_operation_sentinels(self) -> None: + repo = self.make_repo() + git_dir = repo / ".git" + self.assertIsNone(detect_active_operation(git_dir)) + (git_dir / "MERGE_HEAD").write_text("deadbeef\n", encoding="utf-8") + self.assertEqual(detect_active_operation(git_dir), "MERGING") + + def test_compute_hash_and_read_loose_commit_and_tree(self) -> None: + repo = self.make_repo() + loc = discover_repo(repo) + _, head_sha, _ = read_head(loc) + assert head_sha is not None + + # Verify SHA-1 helper matches `git hash-object`. + import subprocess + + blob_bytes = b"hello world\n" + proc = subprocess.run( + ["git", "hash-object", "--stdin"], + input=blob_bytes, + capture_output=True, + check=True, + ) + self.assertEqual( + compute_object_hash("blob", blob_bytes), + proc.stdout.decode().strip(), + ) + + commit_obj = read_loose_object(loc.common_dir, head_sha[:10]) + self.assertIsNotNone(commit_obj) + assert commit_obj is not None + self.assertEqual(commit_obj.kind, "commit") + self.assertEqual(commit_obj.source, "loose") + + parsed_commit = parse_commit_object(commit_obj.content) + self.assertIn("Initial commit", parsed_commit["message"]) + + tree_obj = read_loose_object(loc.common_dir, parsed_commit["tree"]) + self.assertIsNotNone(tree_obj) + assert tree_obj is not None + entries = parse_tree_object(tree_obj.content) + self.assertEqual(len(entries), 1) + self.assertEqual(entries[0][1], "README.md") diff --git a/tests/test_runner_errors.py b/tests/test_runner_errors.py new file mode 100644 index 0000000..2a9209e --- /dev/null +++ b/tests/test_runner_errors.py @@ -0,0 +1,67 @@ +"""Tests for Git stderr-to-friendly-error translation.""" + +from __future__ import annotations + +import unittest + +from simplegit.errors import ( + CommandFailedError, + DirtyWorktreeError, + InvalidRefError, + MergeConflictError, + NotARepoError, + NothingToCommitError, + PushRejectedError, + UpstreamMissingError, + translate_git_error, +) + + +class TestRunnerErrors(unittest.TestCase): + def test_not_a_repo(self) -> None: + err = translate_git_error(["status"], 128, "fatal: not a git repository (or any of the parent directories): .git") + self.assertIsInstance(err, NotARepoError) + self.assertIn("sgit init", err.hint or "") + + def test_merge_conflict_extracts_files(self) -> None: + stderr = ( + "Auto-merging app.py\n" + "CONFLICT (content): Merge conflict in app.py\n" + "CONFLICT (content): Merge conflict in README.md\n" + "Automatic merge failed; fix conflicts and then commit the result.\n" + ) + err = translate_git_error(["merge", "feat"], 1, stderr) + self.assertIsInstance(err, MergeConflictError) + self.assertEqual(err.affected_files, ["app.py", "README.md"]) + + def test_dirty_worktree_extracts_overwritten_files(self) -> None: + stderr = ( + "error: Your local changes to the following files would be overwritten by checkout:\n" + "\tsrc/main.py\n" + "\tREADME.md\n" + "Please commit your changes or stash them before you switch branches.\n" + ) + err = translate_git_error(["switch", "other"], 1, stderr) + self.assertIsInstance(err, DirtyWorktreeError) + self.assertEqual(err.affected_files, ["src/main.py", "README.md"]) + + def test_nothing_to_commit(self) -> None: + err = translate_git_error(["commit", "-m", "x"], 1, "", "nothing to commit, working tree clean") + self.assertIsInstance(err, NothingToCommitError) + + def test_upstream_missing(self) -> None: + err = translate_git_error(["push"], 128, "fatal: The current branch feat has no upstream branch.") + self.assertIsInstance(err, UpstreamMissingError) + + def test_push_rejected(self) -> None: + err = translate_git_error(["push"], 1, "! [rejected] main -> main (non-fast-forward)") + self.assertIsInstance(err, PushRejectedError) + + def test_invalid_ref(self) -> None: + err = translate_git_error(["switch", "nope"], 128, "fatal: invalid reference: nope") + self.assertIsInstance(err, InvalidRefError) + + def test_unknown_error_fallback(self) -> None: + err = translate_git_error(["weird"], 2, "fatal: unexpected failure") + self.assertIsInstance(err, CommandFailedError) + self.assertEqual(err.message, "fatal: unexpected failure") diff --git a/tests/test_save.py b/tests/test_save.py new file mode 100644 index 0000000..46f4cf1 --- /dev/null +++ b/tests/test_save.py @@ -0,0 +1,65 @@ +"""Integration tests for `sgit save` diff-based staging and commit workflows.""" + +from __future__ import annotations + +from simplegit.cli import main +from simplegit.core.operations import collect_save_candidates, execute_save, get_log, get_repo_state +from simplegit.errors import NothingToCommitError +from tests.helpers import RepoTestCase + + +class TestSave(RepoTestCase): + def test_save_discovers_diff_and_untracked_files(self) -> None: + repo = self.make_repo() + (repo / "README.md").write_text("updated\n", encoding="utf-8") + (repo / "my notes.txt").write_text("new file with spaces\n", encoding="utf-8") + + plan = collect_save_candidates(repo, tracked_only=False) + self.assertIn("README.md", plan.tracked_diff_files) + self.assertIn("my notes.txt", plan.untracked_files) + + sha, committed = execute_save(plan, message="Save both") + self.assertNotEqual(sha, "dry-run") + self.assertEqual(set(committed), {"README.md", "my notes.txt"}) + self.assertTrue(get_repo_state(repo).is_clean) + + def test_save_tracked_only_skips_untracked(self) -> None: + repo = self.make_repo() + (repo / "README.md").write_text("updated\n", encoding="utf-8") + (repo / "scratch.txt").write_text("untracked\n", encoding="utf-8") + + with self.chdir(repo): + rc = main(["save", "-t", "Only tracked"]) + self.assertEqual(rc, 0) + + state = get_repo_state(repo) + self.assertEqual([f.path for f in state.untracked_files], ["scratch.txt"]) + self.assertEqual(get_log(repo, limit=1)[0].subject, "Only tracked") + + def test_save_dry_run_does_not_commit(self) -> None: + repo = self.make_repo() + (repo / "README.md").write_text("edited\n", encoding="utf-8") + + with self.chdir(repo): + rc = main(["save", "--dry-run", "Preview commit"]) + self.assertEqual(rc, 0) + self.assertEqual(len(get_log(repo, limit=10)), 1) + self.assertFalse(get_repo_state(repo).is_clean) + + def test_save_with_m_flag_and_file_scope(self) -> None: + repo = self.make_repo() + (repo / "a.txt").write_text("A\n", encoding="utf-8") + (repo / "b.txt").write_text("B\n", encoding="utf-8") + + with self.chdir(repo): + rc = main(["save", "-m", "Only A", "a.txt"]) + self.assertEqual(rc, 0) + + state = get_repo_state(repo) + self.assertEqual([f.path for f in state.untracked_files], ["b.txt"]) + + def test_save_clean_tree_raises_nothing_to_commit(self) -> None: + repo = self.make_repo() + plan = collect_save_candidates(repo) + with self.assertRaises(NothingToCommitError): + execute_save(plan, message="Empty") diff --git a/tests/test_sync_init.py b/tests/test_sync_init.py new file mode 100644 index 0000000..4ea29cd --- /dev/null +++ b/tests/test_sync_init.py @@ -0,0 +1,100 @@ +"""Integration tests for `init`, `clone`, and `sync` against a local bare remote.""" + +from __future__ import annotations + +from unittest.mock import patch + +from simplegit.cli import main +from simplegit.core.operations import get_log, get_repo_state, resolve_clone_url, sync_repo +from simplegit.errors import SimpleGitError +from tests.helpers import RepoTestCase + + +class TestSyncAndInit(RepoTestCase): + def test_init_creates_repo_on_main(self) -> None: + target = self.tmp_path / "fresh" + rc = main(["init", str(target)]) + self.assertEqual(rc, 0) + self.assertTrue((target / ".git" / "HEAD").is_file()) + + def test_sync_sets_upstream_and_pulls_remote_changes(self) -> None: + remote = self.make_bare_remote() + repo_a = self.make_repo("repo_a") + self.run_raw_git(["remote", "add", "origin", str(remote)], cwd=repo_a) + + # First sync publishes branch and sets upstream automatically. + sync_repo(repo_a) + state_a = get_repo_state(repo_a) + self.assertEqual(state_a.upstream, "origin/main") + + # Clone into repo_b using `sgit clone` + repo_b = self.tmp_path / "repo_b" + self.assertEqual(main(["clone", str(remote), str(repo_b)]), 0) + self.run_raw_git(["config", "user.name", "Peer"], cwd=repo_b) + self.run_raw_git(["config", "user.email", "peer@simplegit.local"], cwd=repo_b) + + (repo_b / "peer.txt").write_text("from peer\n", encoding="utf-8") + with self.chdir(repo_b): + self.assertEqual(main(["save", "--push", "Peer commit"]), 0) + + # Now repo_a creates a local commit and runs `sgit sync` (rebases over peer commit + pushes). + (repo_a / "local.txt").write_text("from local\n", encoding="utf-8") + with self.chdir(repo_a): + self.assertEqual(main(["save", "Local commit"]), 0) + self.assertEqual(main(["sync"]), 0) + + subjects = [c.subject for c in get_log(repo_a, limit=10)] + self.assertIn("Peer commit", subjects) + self.assertIn("Local commit", subjects) + + def test_resolve_clone_url_variants(self) -> None: + self.assertEqual( + resolve_clone_url("AdonZ/SimpleGit", github=True), + "https://github.com/AdonZ/SimpleGit.git", + ) + self.assertEqual( + resolve_clone_url("AdonZ/SimpleGit.git", github=True, ssh=True), + "git@github.com:AdonZ/SimpleGit.git", + ) + self.assertEqual( + resolve_clone_url("group/sub/app", gitlab=True), + "https://gitlab.com/group/sub/app.git", + ) + self.assertEqual( + resolve_clone_url("git.example.com/team/repo"), + "https://git.example.com/team/repo.git", + ) + self.assertEqual( + resolve_clone_url("https://git.example.com/team/repo.git"), + "https://git.example.com/team/repo.git", + ) + bare = self.make_bare_remote("hosted.git") + self.assertEqual(resolve_clone_url(str(bare)), str(bare)) + + with self.assertRaises(SimpleGitError): + resolve_clone_url("owner/repo") + + def test_cli_clone_gh_and_gl_flags(self) -> None: + with patch("simplegit.commands.sync.clone_repo", return_value="https://github.com/AdonZ/SimpleGit.git") as mock_clone: + rc = main(["clone", "-gh", "AdonZ/SimpleGit", "my-dir"]) + self.assertEqual(rc, 0) + mock_clone.assert_called_once_with( + "AdonZ/SimpleGit", + directory="my-dir", + branch=None, + github=True, + gitlab=False, + ssh=False, + ) + + with patch("simplegit.commands.sync.clone_repo", return_value="https://gitlab.com/org/proj.git") as mock_clone: + rc = main(["clone", "-gl", "--ssh", "org/proj"]) + self.assertEqual(rc, 0) + mock_clone.assert_called_once_with( + "org/proj", + directory=None, + branch=None, + github=False, + gitlab=True, + ssh=True, + ) From 1520511014bb2bca08252ba77a570b62b0419bb1 Mon Sep 17 00:00:00 2001 From: AdonZ <56778024+adonzone@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:35:01 -0500 Subject: [PATCH 2/3] Add workflows, Git check, error handling, and automated GitHub Actions publishing --- .github/workflows/publish-on-main.yml | 235 ++++++++++++++++++ README.md | 5 +- packaging/choco/simplegit.nuspec | 4 +- packaging/choco/tools/chocolateyinstall.ps1 | 2 +- packaging/homebrew/simplegit.rb | 4 +- packaging/npm/package.json | 2 +- packaging/npm/scripts/postinstall.js | 2 +- packaging/scoop/simplegit.json | 6 +- .../winget/AdonaiAfewerki.SimpleGit.yaml | 2 +- simplegit/cli.py | 38 ++- simplegit/commands/branches.py | 6 +- simplegit/commands/extras.py | 20 +- simplegit/commands/workflow.py | 186 ++++++++++++++ simplegit/core/auth.py | 16 +- simplegit/core/native_git.py | 31 ++- simplegit/core/runner.py | 10 +- simplegit/core/workflows.py | 100 ++++++++ tests/test_cli_interactive.py | 25 ++ tests/test_workflow.py | 69 +++++ 19 files changed, 724 insertions(+), 39 deletions(-) create mode 100644 .github/workflows/publish-on-main.yml create mode 100644 simplegit/commands/workflow.py create mode 100644 simplegit/core/workflows.py create mode 100644 tests/test_workflow.py diff --git a/.github/workflows/publish-on-main.yml b/.github/workflows/publish-on-main.yml new file mode 100644 index 0000000..a82e333 --- /dev/null +++ b/.github/workflows/publish-on-main.yml @@ -0,0 +1,235 @@ +name: Publish Package Managers on Main + +on: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: write + +jobs: + check-version: + runs-on: ubuntu-latest + outputs: + version: ${{ steps.ver.outputs.version }} + tag: ${{ steps.ver.outputs.tag }} + should_release: ${{ steps.ver.outputs.should_release }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Read version from pyproject.toml + id: ver + run: | + VERSION=$(python3 -c ' + import tomllib + with open("pyproject.toml", "rb") as f: + print(tomllib.load(f)["project"]["version"]) + ') + TAG="v${VERSION}" + echo "version=${VERSION}" >> "$GITHUB_OUTPUT" + echo "tag=${TAG}" >> "$GITHUB_OUTPUT" + if git rev-parse "$TAG" >/dev/null 2>&1; then + echo "Tag $TAG already exists; skipping release." + echo "should_release=false" >> "$GITHUB_OUTPUT" + else + echo "should_release=true" >> "$GITHUB_OUTPUT" + fi + + build-binaries: + needs: check-version + if: needs.check-version.outputs.should_release == 'true' + strategy: + fail-fast: false + matrix: + include: + - os: macos-latest + asset: sgit-darwin-arm64 + ext: "" + - os: macos-13 + asset: sgit-darwin-x64 + ext: "" + - os: ubuntu-latest + asset: sgit-linux-x64 + ext: "" + - os: windows-latest + asset: sgit-win32-x64.exe + ext: ".exe" + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Install PyInstaller + run: pip install ".[build]" + - name: Build standalone binary + run: | + pyinstaller --onefile --name sgit simplegit/__main__.py + mkdir -p release-assets + cp "dist/sgit${{ matrix.ext }}" "release-assets/${{ matrix.asset }}" + - uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.asset }} + path: release-assets/${{ matrix.asset }} + + github-release: + needs: [check-version, build-binaries] + runs-on: ubuntu-latest + outputs: + win32_sha256: ${{ steps.hashes.outputs.win32_sha256 }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Download binaries + uses: actions/download-artifact@v4 + with: + path: release-assets + merge-multiple: true + + - name: Build Python sdist/wheel and zipapp + run: | + pip install build + python -m build --outdir release-assets + python scripts/build_zipapp.py + cp dist/sgit.pyz release-assets/sgit.pyz + + - name: Generate SHA256SUMS.txt + id: hashes + working-directory: release-assets + run: | + sha256sum * > SHA256SUMS.txt + WIN_SHA=$(sha256sum sgit-win32-x64.exe | awk '{print $1}') + echo "win32_sha256=${WIN_SHA}" >> "$GITHUB_OUTPUT" + + - name: Create Git tag and GitHub Release + uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ needs.check-version.outputs.tag }} + name: ${{ needs.check-version.outputs.tag }} + generate_release_notes: true + files: release-assets/* + + - uses: actions/upload-artifact@v4 + with: + name: python-dist + path: | + release-assets/*.whl + release-assets/*.tar.gz + + publish-npm: + needs: [check-version, github-release] + if: ${{ vars.ENABLE_NPM == 'true' }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "20" + registry-url: "https://registry.npmjs.org" + - name: Publish sgit-cli to npm + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + run: npm publish --access public ./packaging/npm + + publish-pypi: + needs: [check-version, github-release] + if: ${{ vars.ENABLE_PYPI == 'true' }} + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@v4 + with: + name: python-dist + path: dist + - uses: pypa/gh-action-pypi-publish@release/v1 + with: + password: ${{ secrets.PYPI_API_TOKEN }} + + publish-chocolatey: + needs: [check-version, github-release] + if: ${{ vars.ENABLE_CHOCO == 'true' }} + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - name: Update checksum and push to Chocolatey + shell: pwsh + env: + CHOCO_API_KEY: ${{ secrets.CHOCO_API_KEY }} + WIN_SHA: ${{ needs.github-release.outputs.win32_sha256 }} + VERSION: ${{ needs.check-version.outputs.version }} + run: | + $ps1 = "packaging/choco/tools/chocolateyinstall.ps1" + (Get-Content $ps1) -replace 'REPLACE_WITH_WIN32_X64_SHA256', $env:WIN_SHA | Set-Content $ps1 + choco pack packaging/choco/simplegit.nuspec --version $env:VERSION --outputdirectory packaging/choco + choco push "packaging/choco/simplegit.$($env:VERSION).nupkg" --source https://push.chocolatey.org/ --api-key $env:CHOCO_API_KEY + + publish-homebrew: + needs: [check-version, github-release] + if: ${{ vars.ENABLE_HOMEBREW == 'true' }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + path: source + - uses: actions/checkout@v4 + with: + repository: ${{ github.repository_owner }}/homebrew-tap + token: ${{ secrets.HOMEBREW_TAP_TOKEN }} + path: tap + - name: Update Homebrew formula + env: + TAG: ${{ needs.check-version.outputs.tag }} + run: | + TAR_SHA=$(curl -fsSL "https://github.com/${{ github.repository }}/archive/refs/tags/${TAG}.tar.gz" | sha256sum | awk '{print $1}') + mkdir -p tap/Formula + sed "s/REPLACE_WITH_RELEASE_TARBALL_SHA256/${TAR_SHA}/g" source/packaging/homebrew/simplegit.rb > tap/Formula/simplegit.rb + cd tap + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git add Formula/simplegit.rb + git commit -m "simplegit ${TAG}" + git push + + publish-scoop: + needs: [check-version, github-release] + if: ${{ vars.ENABLE_SCOOP == 'true' }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + path: source + - uses: actions/checkout@v4 + with: + repository: ${{ github.repository_owner }}/scoop-bucket + token: ${{ secrets.SCOOP_BUCKET_TOKEN }} + path: bucket + - name: Update Scoop manifest + env: + TAG: ${{ needs.check-version.outputs.tag }} + WIN_SHA: ${{ needs.github-release.outputs.win32_sha256 }} + run: | + mkdir -p bucket/bucket + sed "s/REPLACE_WITH_WIN32_X64_SHA256/${WIN_SHA}/g" source/packaging/scoop/simplegit.json > bucket/bucket/simplegit.json + cd bucket + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git add bucket/simplegit.json + git commit -m "simplegit ${TAG}" + git push + + publish-winget: + needs: [check-version, github-release] + if: ${{ vars.ENABLE_WINGET == 'true' }} + runs-on: windows-latest + steps: + - uses: vedantmgoyal9/winget-releaser@v2 + with: + identifier: AdonaiAfewerki.SimpleGit + version: ${{ needs.check-version.outputs.version }} + installers-regex: 'sgit-win32-x64\.exe$' + token: ${{ secrets.WINGET_TOKEN }} diff --git a/README.md b/README.md index f9e015d..8a0ae69 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ sgit save "Add login validation" # Diff-discover + stage + commit in one comman sgit save -t "Tracked only" # Stage only tracked files found in git diff sgit save -p "Update docs" # Save and push immediately sgit switch -c feat/auth # Create and switch to a new branch -sgit clone -gh AdonZ/SimpleGit # Clone from GitHub (or -gl for GitLab) +sgit clone -gh adonzone/SimpleGit # Clone from GitHub (or -gl for GitLab) sgit clone /path/to/repo.git # Or clone any .git URL / local .git directory sgit sync # Pull (--rebase) and push (auto-sets upstream) sgit undo commit # Safely undo last commit, keeping edits staged @@ -55,7 +55,8 @@ sgit conflicts # Inspect & resolve merge conflicts (--ours/-- sgit ignore --template python # Add starter .gitignore patterns cleanly sgit tag v0.1.0 --push # Create and push a release tag sgit doctor # Check Git, identity, auth, and repo health -sgit viewer --files # Visual graph of branches, commits, and files +sgit viewer --files # Visual Network graph (X=Time, Y=Branches) +sgit workflow "daily-sync" # Create, edit (-e), or run custom workflows ``` ## Running Tests diff --git a/packaging/choco/simplegit.nuspec b/packaging/choco/simplegit.nuspec index e34f788..3d97e2e 100644 --- a/packaging/choco/simplegit.nuspec +++ b/packaging/choco/simplegit.nuspec @@ -5,8 +5,8 @@ 0.1.0 SimpleGit (sgit) Adonai Afewerki - https://github.com/AdonZ/SimpleGit - https://github.com/AdonZ/SimpleGit/blob/main/LICENSE + https://github.com/adonzone/SimpleGit + https://github.com/adonzone/SimpleGit/blob/main/LICENSE false A simplified, cross-platform Git CLI with native .git inspection, one-shot workflows, colored error diagnostics, and an interactive terminal UI. Simplified Git CLI (`sgit`) diff --git a/packaging/choco/tools/chocolateyinstall.ps1 b/packaging/choco/tools/chocolateyinstall.ps1 index f7f13b0..b90daa2 100644 --- a/packaging/choco/tools/chocolateyinstall.ps1 +++ b/packaging/choco/tools/chocolateyinstall.ps1 @@ -1,7 +1,7 @@ $ErrorActionPreference = 'Stop' $toolsDir = Split-Path -Parent $MyInvocation.MyCommand.Definition -$url64 = 'https://github.com/AdonZ/SimpleGit/releases/download/v0.1.0/sgit-win32-x64.exe' +$url64 = 'https://github.com/adonzone/SimpleGit/releases/download/v0.1.0/sgit-win32-x64.exe' $checksum64 = 'REPLACE_WITH_WIN32_X64_SHA256' $targetExe = Join-Path $toolsDir 'sgit.exe' diff --git a/packaging/homebrew/simplegit.rb b/packaging/homebrew/simplegit.rb index fbdcdf9..6b1879e 100644 --- a/packaging/homebrew/simplegit.rb +++ b/packaging/homebrew/simplegit.rb @@ -2,8 +2,8 @@ class Simplegit < Formula include Language::Python::Virtualenv desc "Simplified Git CLI with native .git inspection and interactive terminal UI" - homepage "https://github.com/AdonZ/SimpleGit" - url "https://github.com/AdonZ/SimpleGit/archive/refs/tags/v0.1.0.tar.gz" + homepage "https://github.com/adonzone/SimpleGit" + url "https://github.com/adonzone/SimpleGit/archive/refs/tags/v0.1.0.tar.gz" sha256 "REPLACE_WITH_RELEASE_TARBALL_SHA256" license "GPL-3.0-or-later" diff --git a/packaging/npm/package.json b/packaging/npm/package.json index 9cf3e6f..02de7b2 100644 --- a/packaging/npm/package.json +++ b/packaging/npm/package.json @@ -5,7 +5,7 @@ "license": "GPL-3.0-or-later", "repository": { "type": "git", - "url": "https://github.com/AdonZ/SimpleGit.git" + "url": "https://github.com/adonzone/SimpleGit.git" }, "bin": { "sgit": "./bin/sgit.js" diff --git a/packaging/npm/scripts/postinstall.js b/packaging/npm/scripts/postinstall.js index f5800d2..7651d3f 100644 --- a/packaging/npm/scripts/postinstall.js +++ b/packaging/npm/scripts/postinstall.js @@ -25,7 +25,7 @@ if (!asset) { process.exit(0); } -const repo = process.env.SGIT_RELEASE_REPO || "AdonZ/SimpleGit"; +const repo = process.env.SGIT_RELEASE_REPO || "adonzone/SimpleGit"; const baseUrl = `https://github.com/${repo}/releases/download/v${pkg.version}`; const vendorDir = path.join(__dirname, "..", "vendor"); const destFile = path.join(vendorDir, process.platform === "win32" ? "sgit.exe" : "sgit"); diff --git a/packaging/scoop/simplegit.json b/packaging/scoop/simplegit.json index b625434..e8d02ae 100644 --- a/packaging/scoop/simplegit.json +++ b/packaging/scoop/simplegit.json @@ -1,12 +1,12 @@ { "version": "0.1.0", "description": "Simplified Git CLI with native .git inspection and interactive terminal UI", - "homepage": "https://github.com/AdonZ/SimpleGit", + "homepage": "https://github.com/adonzone/SimpleGit", "license": "GPL-3.0-or-later", "depends": "git", "architecture": { "64bit": { - "url": "https://github.com/AdonZ/SimpleGit/releases/download/v0.1.0/sgit-win32-x64.exe#/sgit.exe", + "url": "https://github.com/adonzone/SimpleGit/releases/download/v0.1.0/sgit-win32-x64.exe#/sgit.exe", "hash": "REPLACE_WITH_WIN32_X64_SHA256" } }, @@ -15,7 +15,7 @@ "autoupdate": { "architecture": { "64bit": { - "url": "https://github.com/AdonZ/SimpleGit/releases/download/v$version/sgit-win32-x64.exe#/sgit.exe" + "url": "https://github.com/adonzone/SimpleGit/releases/download/v$version/sgit-win32-x64.exe#/sgit.exe" } } } diff --git a/packaging/winget/AdonaiAfewerki.SimpleGit.yaml b/packaging/winget/AdonaiAfewerki.SimpleGit.yaml index 4f8d80a..f297c27 100644 --- a/packaging/winget/AdonaiAfewerki.SimpleGit.yaml +++ b/packaging/winget/AdonaiAfewerki.SimpleGit.yaml @@ -15,7 +15,7 @@ Installers: - Architecture: x64 InstallerType: portable NestedInstallerType: portable - InstallerUrl: https://github.com/AdonZ/SimpleGit/releases/download/v0.1.0/sgit-win32-x64.exe + InstallerUrl: https://github.com/adonzone/SimpleGit/releases/download/v0.1.0/sgit-win32-x64.exe InstallerSha256: REPLACE_WITH_WIN32_X64_SHA256 ManifestType: singleton ManifestVersion: 1.6.0 diff --git a/simplegit/cli.py b/simplegit/cli.py index 8dc356a..9177b92 100644 --- a/simplegit/cli.py +++ b/simplegit/cli.py @@ -4,23 +4,41 @@ import argparse import sys +import traceback +from typing import NoReturn from simplegit import __version__ -from simplegit.commands import auth, branches, extras, save, status_diff, sync, undo, viewer +from simplegit.commands import auth, branches, extras, save, status_diff, sync, undo, viewer, workflow +from simplegit.core.runner import find_git_binary from simplegit.errors import SimpleGitError from simplegit.ui.render import render_error from simplegit.ui.theme import THEME +class _SimpleGitArgumentParser(argparse.ArgumentParser): + """ArgumentParser that formats CLI syntax errors using SimpleGit's error banner.""" + + def error(self, message: str) -> NoReturn: + render_error( + SimpleGitError( + message=f"Invalid command usage: {message}", + hint=f"Run `{self.prog} --help` for usage.", + exit_code=2, + ) + ) + raise SystemExit(2) + + def build_parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser( + parser = _SimpleGitArgumentParser( prog="sgit", - description="SimpleGit — simplified Git workflows, native .git inspection, and interactive CLI.", + description="SimpleGit — simplified Git workflows, native .git inspection, and viewer.", ) parser.add_argument("-V", "--version", action="version", version=f"SimpleGit {__version__}") parser.add_argument("--no-color", action="store_true", help="Disable colored terminal output") + parser.add_argument("--debug", action="store_true", help="Print full traceback on unexpected errors") - subparsers = parser.add_subparsers(dest="command", metavar="") + subparsers = parser.add_subparsers(dest="command", metavar="", parser_class=_SimpleGitArgumentParser) save.register(subparsers) status_diff.register(subparsers) branches.register(subparsers) @@ -29,6 +47,7 @@ def build_parser() -> argparse.ArgumentParser: extras.register(subparsers) auth.register(subparsers) viewer.register(subparsers) + workflow.register(subparsers) return parser @@ -44,6 +63,7 @@ def main(argv: list[str] | None = None) -> int: return 0 try: + find_git_binary() return int(args.handler(args)) except SimpleGitError as exc: render_error(exc) @@ -51,3 +71,13 @@ def main(argv: list[str] | None = None) -> int: except KeyboardInterrupt: print("\n" + THEME.muted("Interrupted."), file=sys.stderr) return 130 + except Exception as exc: + if getattr(args, "debug", False): + traceback.print_exc() + render_error( + SimpleGitError( + message=f"Unexpected error: {exc}", + hint="Re-run with `--debug` to see the full traceback.", + ) + ) + return 1 diff --git a/simplegit/commands/branches.py b/simplegit/commands/branches.py index b5d1478..163e732 100644 --- a/simplegit/commands/branches.py +++ b/simplegit/commands/branches.py @@ -12,6 +12,7 @@ merge_branch, switch_branch, ) +from simplegit.errors import SimpleGitError from simplegit.ui.render import render_branches from simplegit.ui.theme import THEME @@ -40,7 +41,10 @@ def run_branch(args: argparse.Namespace) -> int: location = discover_repo() if args.delete: if not args.name: - raise SystemExit("Specify a branch name to delete.") + raise SimpleGitError( + "Specify a branch name to delete.", + hint="Usage: `sgit branch -d `", + ) delete_branch(location.root, args.name, force=bool(args.force)) print(THEME.success(f"✓ Deleted branch '{args.name}'.")) return 0 diff --git a/simplegit/commands/extras.py b/simplegit/commands/extras.py index 8e30463..998f9b0 100644 --- a/simplegit/commands/extras.py +++ b/simplegit/commands/extras.py @@ -23,6 +23,7 @@ set_remote_url, ) from simplegit.core.native_git import discover_repo +from simplegit.errors import SimpleGitError from simplegit.ui.theme import THEME @@ -94,6 +95,21 @@ def _add_host_flags(parser: argparse.ArgumentParser) -> None: parser.add_argument("--ssh", action="store_true", help="Use SSH (`git@host:...`) instead of HTTPS") +def _parse_savepoint_index(raw: str | None) -> int: + if not raw: + return 0 + try: + idx = int(raw) + except ValueError as exc: + raise SimpleGitError( + f"Invalid savepoint index '{raw}'.", + hint="Use a non-negative number from `sgit savepoint list` (e.g. `sgit savepoint pop 0`).", + ) from exc + if idx < 0: + raise SimpleGitError("Savepoint index cannot be negative.") + return idx + + def run_savepoint(args: argparse.Namespace) -> int: location = discover_repo() action = args.action @@ -107,7 +123,7 @@ def run_savepoint(args: argparse.Namespace) -> int: return 0 if action in ("pop", "apply"): - idx = int(args.target) if args.target else 0 + idx = _parse_savepoint_index(args.target) out = savepoint_pop(location.root, index=idx, keep=(action == "apply")) if out: print(out) @@ -115,7 +131,7 @@ def run_savepoint(args: argparse.Namespace) -> int: return 0 if action == "drop": - idx = int(args.target) if args.target else 0 + idx = _parse_savepoint_index(args.target) savepoint_drop(location.root, index=idx) print(THEME.warn(f"✓ Dropped savepoint @{{{idx}}}.")) return 0 diff --git a/simplegit/commands/workflow.py b/simplegit/commands/workflow.py new file mode 100644 index 0000000..86e2737 --- /dev/null +++ b/simplegit/commands/workflow.py @@ -0,0 +1,186 @@ +"""Handler for `sgit workflow` — create, edit, list, delete, and run custom workflows.""" + +from __future__ import annotations + +import argparse +import os +import sys +from pathlib import Path + +from simplegit.core.workflows import ( + delete_workflow, + execute_workflow_step, + load_workflows, + save_workflow, +) +from simplegit.errors import SimpleGitError +from simplegit.ui.theme import THEME + + +def register(subparsers: argparse._SubParsersAction) -> None: + parser = subparsers.add_parser( + "workflow", + aliases=["wf"], + help="Create, edit, or run custom saved Git/SimpleGit command workflows", + ) + parser.add_argument("name", nargs="?", help="Workflow name to run or create") + parser.add_argument("-e", "--edit", action="store_true", help="Create or edit the named workflow") + parser.add_argument("-l", "--list", action="store_true", help="List all saved workflows") + parser.add_argument("-d", "--delete", action="store_true", help="Delete the named workflow") + parser.set_defaults(handler=run) + + +def run(args: argparse.Namespace) -> int: + if args.list or not args.name: + return _list_workflows() + + name = args.name.strip() + if args.delete: + if not delete_workflow(name): + raise SimpleGitError(f"Workflow '{name}' does not exist.", hint="Run `sgit workflow --list` to see saved workflows.") + print(THEME.warn(f"✓ Deleted workflow '{name}'.")) + return 0 + + workflows = load_workflows() + if args.edit or name not in workflows: + return _edit_workflow(name, existing=workflows.get(name)) + + return _run_workflow(name, workflows[name]) + + +def _list_workflows() -> int: + workflows = load_workflows() + if not workflows: + print(THEME.muted("No workflows configured yet.")) + print(THEME.info('Create one with: `sgit workflow "my-flow"`')) + return 0 + print(THEME.bold("Saved Workflows:")) + for wf_name, steps in workflows.items(): + print(f" {THEME.accent(wf_name)} ({len(steps)} step(s)):") + for idx, step in enumerate(steps, start=1): + print(f" {THEME.muted(f'{idx}.')} {step}") + return 0 + + +def _edit_workflow(name: str, existing: list[str] | None = None) -> int: + print(THEME.bold(f"Editing workflow '{name}'")) + if existing: + print(THEME.muted("Current steps:")) + for idx, step in enumerate(existing, start=1): + print(f" {THEME.muted(f'{idx}.')} {step}") + print() + + commands: list[str] = [] + while True: + label = "First Git command" if not commands else "Next Git command" + prompt = f"{THEME.info('>')} {label} or put {THEME.bold('.')} to finish. {THEME.muted('(esc to exit)')} " + line = _read_editor_line(prompt) + if line is None: + print(THEME.warn("\nExited without saving.")) + return 0 + stripped = line.strip() + if stripped == ".": + break + if not stripped: + continue + commands.append(stripped) + + if not commands: + print(THEME.warn("No commands entered — workflow not saved.")) + return 0 + + path = save_workflow(name, commands) + print(THEME.success(f"✓ Saved workflow '{name}' ({len(commands)} command(s))") + THEME.muted(f" -> {path}")) + return 0 + + +def _run_workflow(name: str, steps: list[str]) -> int: + print(THEME.bold(f"Running workflow '{name}' ({len(steps)} step(s))...")) + cwd = Path.cwd() + for idx, step in enumerate(steps, start=1): + print(f"{THEME.info(f'[{idx}/{len(steps)}]')} {THEME.muted(step)}") + try: + rc = execute_workflow_step(step, cwd=cwd) + except SimpleGitError as exc: + exc.message = f"Workflow '{name}' failed at step {idx}/{len(steps)} (`{step}`): {exc.message}" + raise + if rc != 0: + raise SimpleGitError( + f"Workflow '{name}' stopped at step {idx}/{len(steps)}: `{step}`", + exit_code=rc, + ) + print(THEME.success(f"✓ Workflow '{name}' completed.")) + return 0 + + +def _read_editor_line(prompt: str) -> str | None: + """Read a command line while supporting `Esc` to cancel immediately.""" + sys.stdout.write(prompt) + sys.stdout.flush() + + if not sys.stdin.isatty(): + raw = sys.stdin.readline() + if not raw or raw.startswith("\x1b"): + return None + return raw.rstrip("\r\n") + + if os.name == "nt": + import msvcrt + + buf: list[str] = [] + while True: + ch = msvcrt.getwch() + if ch == "\x1b": + return None + if ch == "\x03": + raise KeyboardInterrupt + if ch in ("\r", "\n"): + sys.stdout.write("\n") + sys.stdout.flush() + return "".join(buf) + if ch in ("\x08", "\x7f"): + if buf: + buf.pop() + sys.stdout.write("\b \b") + sys.stdout.flush() + elif ch >= " ": + buf.append(ch) + sys.stdout.write(ch) + sys.stdout.flush() + + import termios + import tty + + try: + fd = sys.stdin.fileno() + old_settings = termios.tcgetattr(fd) + except (termios.error, OSError, ValueError): + raw = sys.stdin.readline() + if not raw or raw.startswith("\x1b"): + return None + return raw.rstrip("\r\n") + + buf = [] + try: + tty.setraw(fd) + while True: + ch = sys.stdin.read(1) + if ch == "\x1b": + return None + if ch == "\x03": + raise KeyboardInterrupt + if ch in ("\r", "\n"): + sys.stdout.write("\r\n") + sys.stdout.flush() + return "".join(buf) + if ch in ("\x7f", "\x08"): + if buf: + buf.pop() + sys.stdout.write("\b \b") + sys.stdout.flush() + elif ch >= " ": + buf.append(ch) + sys.stdout.write(ch) + sys.stdout.flush() + finally: + termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) diff --git a/simplegit/core/auth.py b/simplegit/core/auth.py index 6ae0247..3931de4 100644 --- a/simplegit/core/auth.py +++ b/simplegit/core/auth.py @@ -169,12 +169,16 @@ def generate_ssh_key(email: str, ssh_dir: Path | None = None) -> Path: f"SSH key already exists at {key_path}.", hint=f"Copy `{key_path}.pub` to your GitHub/GitLab SSH key settings.", ) - subprocess.run( - [ssh_keygen, "-t", "ed25519", "-C", email, "-f", str(key_path), "-N", ""], - check=True, - capture_output=True, - text=True, - ) + try: + subprocess.run( + [ssh_keygen, "-t", "ed25519", "-C", email, "-f", str(key_path), "-N", ""], + check=True, + capture_output=True, + text=True, + ) + except (subprocess.CalledProcessError, OSError) as exc: + err_detail = getattr(exc, "stderr", None) or str(exc) + raise SimpleGitError("Failed to generate ed25519 SSH key.", details=err_detail) from exc return Path(f"{key_path}.pub") diff --git a/simplegit/core/native_git.py b/simplegit/core/native_git.py index 0f80d85..3226c7d 100644 --- a/simplegit/core/native_git.py +++ b/simplegit/core/native_git.py @@ -7,7 +7,7 @@ from pathlib import Path from simplegit.core.models import GitObject, RepoLocation -from simplegit.errors import NotARepoError +from simplegit.errors import NotARepoError, SimpleGitError _OP_SENTINELS: tuple[tuple[str, str], ...] = ( ("MERGE_HEAD", "MERGING"), @@ -127,17 +127,26 @@ def read_loose_object(common_dir: Path, sha_prefix: str) -> GitObject | None: obj_path = matches[0] full_sha = cleaned[:2] + obj_path.name - raw = zlib.decompress(obj_path.read_bytes()) - nul_idx = raw.find(b"\0") - if nul_idx == -1: - return None - - header = raw[:nul_idx].decode("utf-8", errors="replace") - body = raw[nul_idx + 1 :] - kind, size_str = header.split(" ", 1) - size = int(size_str) + try: + raw = zlib.decompress(obj_path.read_bytes()) + nul_idx = raw.find(b"\0") + if nul_idx == -1: + raise ValueError("Missing NUL header separator") + header = raw[:nul_idx].decode("utf-8", errors="replace") + body = raw[nul_idx + 1 :] + kind, size_str = header.split(" ", 1) + size = int(size_str) + except (zlib.error, ValueError, OSError) as exc: + raise SimpleGitError( + f"Corrupt or unreadable Git object `{full_sha}`.", + hint="Run `git fsck` to check repository integrity.", + details=str(exc), + ) from exc if len(body) != size: - raise ValueError(f"Corrupt Git object {full_sha}: expected {size} bytes, got {len(body)}") + raise SimpleGitError( + f"Corrupt Git object `{full_sha}`: expected {size} bytes, got {len(body)}.", + hint="Run `git fsck` to check repository integrity.", + ) return GitObject(kind=kind, size=size, sha=full_sha, content=body, source="loose") diff --git a/simplegit/core/runner.py b/simplegit/core/runner.py index 3291448..259620c 100644 --- a/simplegit/core/runner.py +++ b/simplegit/core/runner.py @@ -29,8 +29,14 @@ def find_git_binary() -> str: git_path = shutil.which("git") if not git_path: raise GitNotFoundError( - message="`git` was not found on your PATH.", - hint="Install Git (e.g., `brew install git`, `choco install git`, or https://git-scm.com) and try again.", + message="`git` is not installed or was not found on your PATH.", + hint=( + "Install Git first:\n" + " • macOS: brew install git (or `xcode-select --install`)\n" + " • Windows: winget install Git.Git (or `choco install git`)\n" + " • Linux: sudo apt install git (or `sudo dnf install git`)\n" + " • Docs: https://git-scm.com/downloads | https://git-scm.com/doc" + ), ) return git_path diff --git a/simplegit/core/workflows.py b/simplegit/core/workflows.py new file mode 100644 index 0000000..e930d98 --- /dev/null +++ b/simplegit/core/workflows.py @@ -0,0 +1,100 @@ +"""Persistent custom user workflows (`sgit workflow`).""" + +from __future__ import annotations + +import json +import os +import shlex +from pathlib import Path + +from simplegit.core.runner import run_git +from simplegit.errors import SimpleGitError + + +def get_workflows_path() -> Path: + """Return path to the user's `workflows.json` file.""" + cfg_dir = os.environ.get("SGIT_CONFIG_DIR") + base = Path(cfg_dir) if cfg_dir else (Path.home() / ".config" / "simplegit") + return base / "workflows.json" + + +def load_workflows() -> dict[str, list[str]]: + """Load saved workflows from disk.""" + path = get_workflows_path() + if not path.is_file(): + return {} + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise SimpleGitError(f"Failed to read workflows file: {path}", details=str(exc)) from exc + if not isinstance(data, dict): + return {} + return {str(k): [str(cmd) for cmd in v] for k, v in data.items() if isinstance(v, list)} + + +def save_workflow(name: str, commands: list[str]) -> Path: + """Persist a named workflow's command list.""" + cleaned_name = name.strip() + if not cleaned_name: + raise SimpleGitError("Workflow name cannot be empty.") + if not commands: + raise SimpleGitError("Cannot save an empty workflow.", hint="Add at least one Git or sgit command.") + + workflows = load_workflows() + workflows[cleaned_name] = commands + path = get_workflows_path() + try: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(workflows, indent=2) + "\n", encoding="utf-8") + except OSError as exc: + raise SimpleGitError(f"Could not save workflows file: {path}", details=str(exc)) from exc + return path + + +def delete_workflow(name: str) -> bool: + """Delete a saved workflow by name; returns True if it existed.""" + workflows = load_workflows() + if name not in workflows: + return False + del workflows[name] + path = get_workflows_path() + try: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(workflows, indent=2) + "\n", encoding="utf-8") + except OSError as exc: + raise SimpleGitError(f"Could not update workflows file: {path}", details=str(exc)) from exc + return True + + +def execute_workflow_step(step: str, cwd: Path | None = None) -> int: + """Execute a single workflow step (`sgit ...`, `git ...`, or bare Git args).""" + try: + tokens = shlex.split(step) + except ValueError as exc: + raise SimpleGitError( + f"Invalid command syntax in workflow step: `{step}`", + hint="Check for unclosed quotes in your workflow command.", + details=str(exc), + ) from exc + if not tokens: + return 0 + + head = tokens[0].lower() + if head == "sgit": + if len(tokens) == 1: + raise SimpleGitError( + f"Incomplete workflow step: `{step}`", + hint="Specify a SimpleGit subcommand, e.g. `sgit status` or `sgit save \"wip\"`.", + ) + from simplegit.cli import main + + return main(tokens[1:]) + + git_args = tokens[1:] if head == "git" else tokens + if not git_args: + raise SimpleGitError( + f"Incomplete workflow step: `{step}`", + hint="Specify a Git subcommand, e.g. `git status`.", + ) + run_git(git_args, cwd=cwd, interactive=True, stream_output=True) + return 0 diff --git a/tests/test_cli_interactive.py b/tests/test_cli_interactive.py index d06af2c..4e4665b 100644 --- a/tests/test_cli_interactive.py +++ b/tests/test_cli_interactive.py @@ -27,6 +27,31 @@ def test_no_color_error_rendering(self) -> None: self.assertIn("sgit init", out) self.assertNotIn("\033[", out) + def test_missing_git_binary_shows_install_docs(self) -> None: + stderr = io.StringIO() + with patch("shutil.which", return_value=None), redirect_stderr(stderr): + rc = main(["--no-color", "status"]) + self.assertEqual(rc, 1) + out = stderr.getvalue() + self.assertIn("not installed", out) + self.assertIn("https://git-scm.com/downloads", out) + self.assertIn("https://git-scm.com/doc", out) + + def test_invalid_cli_usage_uses_styled_error_banner(self) -> None: + stderr = io.StringIO() + with redirect_stderr(stderr), self.assertRaises(SystemExit) as ctx: + main(["--no-color", "--unknown-flag"]) + self.assertEqual(ctx.exception.code, 2) + self.assertIn("Invalid command usage", stderr.getvalue()) + + def test_invalid_savepoint_index_raises_friendly_error(self) -> None: + repo = self.make_repo() + stderr = io.StringIO() + with self.chdir(repo), redirect_stderr(stderr): + rc = main(["--no-color", "savepoint", "pop", "not-a-number"]) + self.assertEqual(rc, 1) + self.assertIn("Invalid savepoint index", stderr.getvalue()) + def test_inspect_command_uses_native_loose_object(self) -> None: repo = self.make_repo() stdout = io.StringIO() diff --git a/tests/test_workflow.py b/tests/test_workflow.py new file mode 100644 index 0000000..861e568 --- /dev/null +++ b/tests/test_workflow.py @@ -0,0 +1,69 @@ +"""Tests for custom user workflows (`sgit workflow`).""" + +from __future__ import annotations + +import io +import os +from contextlib import redirect_stdout +from unittest.mock import patch + +from simplegit.cli import main +from simplegit.core.operations import get_log, get_repo_state +from simplegit.core.workflows import load_workflows +from tests.helpers import RepoTestCase + + +class TestWorkflow(RepoTestCase): + def test_create_and_run_workflow_and_esc_cancel(self) -> None: + repo = self.make_repo() + cfg_dir = self.tmp_path / "sgit_cfg" + + with patch.dict(os.environ, {"SGIT_CONFIG_DIR": str(cfg_dir)}): + # 1. Create workflow interactively using `.` to finish + fake_create = io.StringIO("git add -A\ngit commit -m \"From workflow\"\n.\n") + stdout = io.StringIO() + with patch("sys.stdin", fake_create), redirect_stdout(stdout): + rc = main(["--no-color", "workflow", "quick-commit"]) + self.assertEqual(rc, 0) + self.assertIn("First Git command or put . to finish. (esc to exit)", stdout.getvalue()) + self.assertEqual( + load_workflows()["quick-commit"], + ["git add -A", 'git commit -m "From workflow"'], + ) + + # 2. Run the saved workflow against a modified repo + (repo / "README.md").write_text("workflow edit\n", encoding="utf-8") + with self.chdir(repo): + rc_run = main(["--no-color", "workflow", "quick-commit"]) + self.assertEqual(rc_run, 0) + self.assertTrue(get_repo_state(repo).is_clean) + self.assertEqual(get_log(repo, limit=1)[0].subject, "From workflow") + + # 3. Edit with `-e` and cancel with Esc (`\x1b`) — existing workflow stays intact + fake_esc = io.StringIO("\x1b\n") + stdout_esc = io.StringIO() + with patch("sys.stdin", fake_esc), redirect_stdout(stdout_esc): + rc_esc = main(["--no-color", "workflow", "-e", "quick-commit"]) + self.assertEqual(rc_esc, 0) + self.assertIn("Exited without saving", stdout_esc.getvalue()) + self.assertEqual(len(load_workflows()["quick-commit"]), 2) + + # 4. Delete workflow + rc_del = main(["--no-color", "workflow", "-d", "quick-commit"]) + self.assertEqual(rc_del, 0) + self.assertEqual(load_workflows(), {}) + + def test_workflow_unclosed_quote_shows_friendly_error(self) -> None: + cfg_dir = self.tmp_path / "sgit_cfg_bad" + with patch.dict(os.environ, {"SGIT_CONFIG_DIR": str(cfg_dir)}): + from simplegit.core.workflows import save_workflow + + save_workflow("broken", ['git commit -m "unclosed']) + import io + from contextlib import redirect_stderr + + stderr = io.StringIO() + with redirect_stderr(stderr): + rc = main(["--no-color", "workflow", "broken"]) + self.assertEqual(rc, 1) + self.assertIn("Invalid command syntax", stderr.getvalue()) From 1e9824311612e744c63b9752cec4fdafed4c3082 Mon Sep 17 00:00:00 2001 From: AdonZ <56778024+adonzone@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:49:55 -0500 Subject: [PATCH 3/3] Force UTF-8 stdout/stderr encoding for Windows consoles --- simplegit/cli.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/simplegit/cli.py b/simplegit/cli.py index 9177b92..61f2ac0 100644 --- a/simplegit/cli.py +++ b/simplegit/cli.py @@ -51,7 +51,19 @@ def build_parser() -> argparse.ArgumentParser: return parser +def _ensure_utf8_streams() -> None: + """Ensure stdout/stderr can encode Unicode symbols on Windows cp1252 consoles.""" + for stream in (sys.stdout, sys.stderr): + reconfigure = getattr(stream, "reconfigure", None) + if callable(reconfigure): + try: + reconfigure(encoding="utf-8", errors="replace") + except (OSError, ValueError): + pass + + def main(argv: list[str] | None = None) -> int: + _ensure_utf8_streams() parser = build_parser() args = parser.parse_args(argv)