scitex-git 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
scitex_git/_types.py ADDED
@@ -0,0 +1,136 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # File: /home/ywatanabe/proj/scitex-code/src/scitex/git/types.py
4
+
5
+ """
6
+ Git operation result types.
7
+
8
+ This module provides dataclasses for rich error handling and result tracking
9
+ in git operations, addressing the "boolean blindness" issue identified in EVAL.md.
10
+ """
11
+
12
+ from dataclasses import dataclass
13
+ from typing import Optional
14
+
15
+
16
+ @dataclass
17
+ class GitResult:
18
+ """
19
+ Result of a git operation.
20
+
21
+ Attributes
22
+ ----------
23
+ success : bool
24
+ Whether the operation succeeded
25
+ message : Optional[str]
26
+ Human-readable message about the operation
27
+ stdout : Optional[str]
28
+ Standard output from git command
29
+ stderr : Optional[str]
30
+ Standard error from git command
31
+ exit_code : Optional[int]
32
+ Exit code from git command
33
+
34
+ Examples
35
+ --------
36
+ >>> result = GitResult(success=True, message="Commit created")
37
+ >>> if result.success:
38
+ ... print(f"Success: {result.message}")
39
+
40
+ >>> result = GitResult(
41
+ ... success=False,
42
+ ... message="Not a git repository",
43
+ ... stderr="fatal: not a git repository"
44
+ ... )
45
+ >>> if not result.success:
46
+ ... print(f"Error: {result.message}")
47
+ ... print(f"Details: {result.stderr}")
48
+ """
49
+
50
+ success: bool
51
+ message: Optional[str] = None
52
+ stdout: Optional[str] = None
53
+ stderr: Optional[str] = None
54
+ exit_code: Optional[int] = None
55
+
56
+
57
+ @dataclass
58
+ class CommitResult(GitResult):
59
+ """
60
+ Result of a git commit operation.
61
+
62
+ Attributes
63
+ ----------
64
+ commit_hash : Optional[str]
65
+ SHA hash of the created commit
66
+
67
+ Examples
68
+ --------
69
+ >>> result = CommitResult(
70
+ ... success=True,
71
+ ... message="Commit created",
72
+ ... commit_hash="abc123def456"
73
+ ... )
74
+ >>> if result.success:
75
+ ... print(f"Created commit {result.commit_hash}")
76
+ """
77
+
78
+ commit_hash: Optional[str] = None
79
+
80
+
81
+ @dataclass
82
+ class CloneResult(GitResult):
83
+ """
84
+ Result of a git clone operation.
85
+
86
+ Attributes
87
+ ----------
88
+ repo_path : Optional[str]
89
+ Path to the cloned repository
90
+
91
+ Examples
92
+ --------
93
+ >>> result = CloneResult(
94
+ ... success=True,
95
+ ... message="Repository cloned",
96
+ ... repo_path="/path/to/repo"
97
+ ... )
98
+ >>> if result.success:
99
+ ... print(f"Cloned to {result.repo_path}")
100
+ """
101
+
102
+ repo_path: Optional[str] = None
103
+
104
+
105
+ @dataclass
106
+ class BranchResult(GitResult):
107
+ """
108
+ Result of a git branch operation.
109
+
110
+ Attributes
111
+ ----------
112
+ branch_name : Optional[str]
113
+ Name of the branch created or modified
114
+
115
+ Examples
116
+ --------
117
+ >>> result = BranchResult(
118
+ ... success=True,
119
+ ... message="Branch created",
120
+ ... branch_name="feature/new-feature"
121
+ ... )
122
+ >>> if result.success:
123
+ ... print(f"Branch: {result.branch_name}")
124
+ """
125
+
126
+ branch_name: Optional[str] = None
127
+
128
+
129
+ __all__ = [
130
+ "GitResult",
131
+ "CommitResult",
132
+ "CloneResult",
133
+ "BranchResult",
134
+ ]
135
+
136
+ # EOF
scitex_git/_utils.py ADDED
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # File: /home/ywatanabe/proj/scitex-code/src/scitex/git/ops.py
4
+
5
+ """
6
+ Git operations utilities.
7
+ """
8
+
9
+ import os
10
+ from contextlib import contextmanager
11
+ from pathlib import Path
12
+
13
+
14
+ @contextmanager
15
+ def _in_directory(path: Path):
16
+ cwd_original = Path.cwd()
17
+ try:
18
+ os.chdir(path)
19
+ yield
20
+ finally:
21
+ os.chdir(cwd_original)
22
+
23
+
24
+ __all__ = [
25
+ "_in_directory",
26
+ ]
27
+
28
+ # EOF
@@ -0,0 +1,117 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # File: /home/ywatanabe/proj/scitex-code/src/scitex/git/validation.py
4
+
5
+ """
6
+ Input validation utilities for git operations.
7
+ """
8
+
9
+ import re
10
+ from pathlib import Path
11
+ from typing import Tuple
12
+
13
+
14
+ def validate_branch_name(name: str) -> Tuple[bool, str]:
15
+ """
16
+ Validate git branch name according to git naming rules.
17
+
18
+ Parameters
19
+ ----------
20
+ name : str
21
+ Branch name to validate
22
+
23
+ Returns
24
+ -------
25
+ Tuple[bool, str]
26
+ (is_valid, error_message)
27
+ """
28
+ if not name or not name.strip():
29
+ return False, "Branch name cannot be empty"
30
+
31
+ name = name.strip()
32
+
33
+ if name.startswith("-"):
34
+ return False, "Branch name cannot start with '-'"
35
+
36
+ if name.endswith(".lock"):
37
+ return False, "Branch name cannot end with '.lock'"
38
+
39
+ if ".." in name:
40
+ return False, "Branch name cannot contain '..'"
41
+
42
+ invalid_chars = ["~", "^", ":", "?", "*", "[", "\\", " ", "\t"]
43
+ for char in invalid_chars:
44
+ if char in name:
45
+ return False, f"Branch name cannot contain '{char}'"
46
+
47
+ if name.endswith("/"):
48
+ return False, "Branch name cannot end with '/'"
49
+
50
+ if name.startswith("/"):
51
+ return False, "Branch name cannot start with '/'"
52
+
53
+ if "//" in name:
54
+ return False, "Branch name cannot contain consecutive slashes"
55
+
56
+ return True, ""
57
+
58
+
59
+ def validate_commit_message(message: str) -> Tuple[bool, str]:
60
+ """
61
+ Validate git commit message.
62
+
63
+ Parameters
64
+ ----------
65
+ message : str
66
+ Commit message to validate
67
+
68
+ Returns
69
+ -------
70
+ Tuple[bool, str]
71
+ (is_valid, error_message)
72
+ """
73
+ if not message or not message.strip():
74
+ return False, "Commit message cannot be empty"
75
+
76
+ return True, ""
77
+
78
+
79
+ def validate_path(path: Path, must_exist: bool = False) -> Tuple[bool, str]:
80
+ """
81
+ Validate path for git operations.
82
+
83
+ Parameters
84
+ ----------
85
+ path : Path
86
+ Path to validate
87
+ must_exist : bool
88
+ Whether path must exist
89
+
90
+ Returns
91
+ -------
92
+ Tuple[bool, str]
93
+ (is_valid, error_message)
94
+ """
95
+ try:
96
+ resolved = path.resolve()
97
+
98
+ if must_exist and not resolved.exists():
99
+ return False, f"Path does not exist: {path}"
100
+
101
+ path_str = str(resolved)
102
+ if ".." in path.parts:
103
+ return False, "Path contains parent directory references"
104
+
105
+ return True, ""
106
+
107
+ except (OSError, RuntimeError) as e:
108
+ return False, f"Invalid path: {e}"
109
+
110
+
111
+ __all__ = [
112
+ "validate_branch_name",
113
+ "validate_commit_message",
114
+ "validate_path",
115
+ ]
116
+
117
+ # EOF
@@ -0,0 +1,83 @@
1
+ """Minimal vendored shell wrapper — replaces ``scitex.sh.sh`` for scitex-git.
2
+
3
+ Only the call-shape used by scitex-git is supported:
4
+
5
+ sh(cmd_list, verbose=False, return_as="dict") -> dict with
6
+ {"success": bool, "stdout": str, "stderr": str, "returncode": int, "cmd": str}
7
+
8
+ Refuses string commands (list-only) to match the upstream contract that
9
+ prevents shell injection. When scitex-sh is later split out as its own
10
+ package, replace this module with a direct dependency.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import shlex
16
+ import subprocess
17
+ from typing import Any, Dict, List, Sequence, Union
18
+
19
+ CommandInput = Union[Sequence[str], List[str]]
20
+
21
+
22
+ def sh(
23
+ command_str_or_list: CommandInput,
24
+ verbose: bool = False,
25
+ return_as: str = "dict",
26
+ timeout: int | None = None,
27
+ stream_output: bool = False,
28
+ ) -> Any:
29
+ if isinstance(command_str_or_list, str):
30
+ raise ValueError(
31
+ "sh() requires list/sequence input (e.g. ['git', 'status']) — "
32
+ "string commands are refused to prevent shell injection."
33
+ )
34
+
35
+ cmd_list = [str(x) for x in command_str_or_list]
36
+ pretty = " ".join(shlex.quote(p) for p in cmd_list)
37
+
38
+ if verbose:
39
+ print(f"$ {pretty}")
40
+
41
+ try:
42
+ proc = subprocess.run(
43
+ cmd_list,
44
+ capture_output=True,
45
+ text=True,
46
+ timeout=timeout,
47
+ check=False,
48
+ )
49
+ result: Dict[str, Any] = {
50
+ "success": proc.returncode == 0,
51
+ "stdout": proc.stdout,
52
+ "stderr": proc.stderr,
53
+ "returncode": proc.returncode,
54
+ "cmd": pretty,
55
+ }
56
+ except FileNotFoundError as e:
57
+ result = {
58
+ "success": False,
59
+ "stdout": "",
60
+ "stderr": str(e),
61
+ "returncode": 127,
62
+ "cmd": pretty,
63
+ }
64
+ except subprocess.TimeoutExpired as e:
65
+ out = e.stdout if isinstance(e.stdout, str) else ""
66
+ err = e.stderr if isinstance(e.stderr, str) else ""
67
+ result = {
68
+ "success": False,
69
+ "stdout": out,
70
+ "stderr": err + f"\nTIMEOUT after {timeout}s",
71
+ "returncode": 124,
72
+ "cmd": pretty,
73
+ }
74
+
75
+ if verbose:
76
+ if result["stdout"]:
77
+ print(result["stdout"], end="" if result["stdout"].endswith("\n") else "\n")
78
+ if result["stderr"]:
79
+ print(result["stderr"], end="" if result["stderr"].endswith("\n") else "\n")
80
+
81
+ if return_as == "dict":
82
+ return result
83
+ return result["stdout"] if result["success"] else result["stderr"]
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # File: /home/ywatanabe/proj/scitex-code/src/scitex/git/workflow.py
4
+
5
+ """
6
+ Git workflow operations combining multiple git commands.
7
+ """
8
+
9
+ from pathlib import Path
10
+
11
+ from ._branch import git_branch_rename, git_checkout_new_branch
12
+ from ._commit import git_add_all, git_commit
13
+
14
+
15
+ def setup_branches(repo_path: Path, template_name: str, verbose: bool = True) -> bool:
16
+ """
17
+ Setup standard git branches (main and develop).
18
+
19
+ Parameters
20
+ ----------
21
+ repo_path : Path
22
+ Git repository path
23
+ template_name : str
24
+ Template name for initial commit message
25
+ verbose : bool
26
+ Enable verbose output
27
+
28
+ Returns
29
+ -------
30
+ bool
31
+ True if successful, False otherwise
32
+
33
+ Notes
34
+ -----
35
+ This function attempts to rollback changes if branch operations fail.
36
+ If add or commit fail, no rollback is needed as the repo state is unchanged.
37
+ """
38
+ if not git_add_all(repo_path, verbose=verbose):
39
+ return False
40
+
41
+ if not git_commit(
42
+ repo_path, f"Initial commit from {template_name}", verbose=verbose
43
+ ):
44
+ return False
45
+
46
+ if not git_branch_rename(repo_path, "main", verbose=verbose):
47
+ _rollback_commit(repo_path, verbose=verbose)
48
+ return False
49
+
50
+ if not git_checkout_new_branch(repo_path, "develop", verbose=verbose):
51
+ _rollback_commit(repo_path, verbose=verbose)
52
+ return False
53
+
54
+ return True
55
+
56
+
57
+ def _rollback_commit(repo_path: Path, verbose: bool = True) -> None:
58
+ """
59
+ Rollback the last commit to restore clean state.
60
+
61
+ Parameters
62
+ ----------
63
+ repo_path : Path
64
+ Git repository path
65
+ verbose : bool
66
+ Enable verbose output
67
+ """
68
+ from logging import getLogger
69
+ from ._vendor_sh import sh
70
+
71
+ from ._utils import _in_directory
72
+
73
+ logger = getLogger(__name__)
74
+
75
+ with _in_directory(repo_path):
76
+ result = sh(
77
+ ["git", "reset", "--soft", "HEAD~1"], verbose=verbose, return_as="dict"
78
+ )
79
+ if result["success"]:
80
+ logger.info("Rolled back commit due to workflow failure")
81
+ else:
82
+ logger.warning(f"Failed to rollback commit: {result['stderr']}")
83
+
84
+
85
+ __all__ = [
86
+ "setup_branches",
87
+ ]
88
+
89
+ # EOF
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: scitex-git
3
+ Version: 0.1.0
4
+ Summary: Git operations and utilities (clone, branch, commit, retry, remote helpers) — standalone module from the SciTeX ecosystem
5
+ Author-email: Yusuke Watanabe <ywatanabe@scitex.ai>
6
+ License-Expression: AGPL-3.0-only
7
+ Project-URL: Homepage, https://github.com/ywatanabe1989/scitex-git
8
+ Project-URL: Repository, https://github.com/ywatanabe1989/scitex-git
9
+ Project-URL: Documentation, https://scitex-git.readthedocs.io
10
+ Keywords: scitex,git,gitpython,version-control,clone,commit
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Software Development :: Version Control :: Git
20
+ Requires-Python: >=3.9
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: GitPython>=3.1
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest; extra == "dev"
26
+ Requires-Dist: pytest-cov; extra == "dev"
27
+ Requires-Dist: ruff; extra == "dev"
28
+ Provides-Extra: docs
29
+ Requires-Dist: sphinx>=7.0; extra == "docs"
30
+ Requires-Dist: sphinx-rtd-theme>=2.0; extra == "docs"
31
+ Requires-Dist: myst-parser>=2.0; extra == "docs"
32
+ Requires-Dist: sphinx-copybutton>=0.5; extra == "docs"
33
+ Requires-Dist: sphinx-autodoc-typehints>=1.25; extra == "docs"
34
+ Provides-Extra: all
35
+ Requires-Dist: scitex-git[dev]; extra == "all"
36
+ Requires-Dist: scitex-git[docs]; extra == "all"
37
+ Dynamic: license-file
38
+
39
+ # scitex-git
40
+
41
+ Git operations and utilities extracted from the [SciTeX](https://github.com/ywatanabe1989/scitex-python) ecosystem as a standalone package.
42
+
43
+ ## Install
44
+
45
+ ```bash
46
+ pip install scitex-git
47
+ ```
48
+
49
+ ## API
50
+
51
+ ```python
52
+ import scitex_git as sxg
53
+
54
+ # Clone / init
55
+ sxg.clone_repo(url, dest_dir)
56
+ sxg.git_init(repo_path)
57
+
58
+ # Add / commit
59
+ sxg.git_add_all(repo_path)
60
+ sxg.git_commit(repo_path, message="…")
61
+
62
+ # Branch
63
+ sxg.git_checkout_new_branch(repo_path, branch_name)
64
+ sxg.git_branch_rename(repo_path, old, new)
65
+ sxg.setup_branches(repo_path, template_name)
66
+
67
+ # Repo init / discovery
68
+ sxg.init_git_repo(project_dir, git_strategy="parent")
69
+ sxg.find_parent_git(project_dir)
70
+ sxg.create_child_git(project_dir)
71
+ sxg.remove_child_git(project_dir)
72
+
73
+ # Remote
74
+ sxg.get_remote_url(repo_path)
75
+ sxg.is_cloned_from(repo_path, url)
76
+ sxg.ls_remote(url)
77
+ sxg.get_head_hash(repo_path)
78
+
79
+ # Retry decorator
80
+ @sxg.git_retry(max_attempts=3)
81
+ def maybe_flaky_operation(): ...
82
+ ```
83
+
84
+ ## Status
85
+
86
+ Standalone fork of `scitex.git`. `scitex.logging.getLogger` is replaced by stdlib
87
+ `logging.getLogger`; the `scitex.sh.sh` shell wrapper is replaced by a tiny
88
+ ~70-LOC `_vendor_sh.py` that supports just the call-shape used here. The
89
+ optional `scitex.writer.verify_tree_structure` validation step in
90
+ `create_child_git` is gated behind a `try/except ImportError` so it only runs
91
+ when `scitex-writer` is installed.
92
+
93
+ The umbrella package's `scitex.git` import path is preserved via a
94
+ `sys.modules`-alias bridge so existing code continues to work.
95
+
96
+ ## License
97
+
98
+ AGPL-3.0-only (see [LICENSE](./LICENSE)).
@@ -0,0 +1,19 @@
1
+ scitex_git/__init__.py,sha256=4nPLvlxLqwguXzDKqgul0yLrjaOtqWr1PHzeIhvi-Gs,935
2
+ scitex_git/_branch.py,sha256=AJG1OQkrYtRS57HsaRFlb7T3PsF23WJsQTpojV10SyE,4744
3
+ scitex_git/_clone.py,sha256=djinc-5WcPmH2eTV1czeyTQdLw8XGkqFNIO3RNOfW2k,4283
4
+ scitex_git/_commit.py,sha256=oS7pg8HoCCZNFnRxdPESe5ADzFPJfBC-0cw-cAD41RU,4353
5
+ scitex_git/_constants.py,sha256=d_t9PqjJTgNUB5GyEt6jWPGco_Lot-2Fes2iWLTlcaQ,248
6
+ scitex_git/_init.py,sha256=tyBjrddkulx5VDGFsfMsMTgDp_iK5SlAplfSilz7b2w,5711
7
+ scitex_git/_remote.py,sha256=l0qzgxgj3IebodC2eVxAU0S3uIA7X-4cquKStgSHPco,6858
8
+ scitex_git/_result.py,sha256=v687ocW-2VCJVGj7cz0XFB0IwSU3y5Qol0BMkSnuXms,1288
9
+ scitex_git/_retry.py,sha256=MAKz2vSoR8qP58ejLqXSX_PFZeiSBy348NIAPL0MqZ4,2864
10
+ scitex_git/_types.py,sha256=_bp8AV9Au47B6F8UJDK5u6Te9raO-roySbgQKGH6y6c,3005
11
+ scitex_git/_utils.py,sha256=cBf3rKwI5_l-h2UCrZEaFf0Grur7FfwPLGjxcrAeYwo,432
12
+ scitex_git/_validation.py,sha256=Hobe4BGXRpvHIk_E71O_KtbZyVnqgSy7ow5fEAvcW_E,2609
13
+ scitex_git/_vendor_sh.py,sha256=u_jq_urbmz2nkvlwv1rYETemkJyi3zaRSl4nVqVv4BA,2583
14
+ scitex_git/_workflow.py,sha256=OKGBufbLNRhHKIgdrhGfU2iUpbPoKwLz2i8526Tavsw,2232
15
+ scitex_git-0.1.0.dist-info/licenses/LICENSE,sha256=DZak_2itbUtvHzD3E7GNUYSRK6jdOJ-GqncQ2weavLA,34523
16
+ scitex_git-0.1.0.dist-info/METADATA,sha256=ztzmDHAfzDvWH72d6h68JP70yds5y0Y73Jl2asurYRU,3208
17
+ scitex_git-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
18
+ scitex_git-0.1.0.dist-info/top_level.txt,sha256=XKLrJtAXr4rm5K2GlNhDs6IndxY4R_x_tS2t0U9732Q,11
19
+ scitex_git-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+