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/_init.py ADDED
@@ -0,0 +1,183 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # File: /home/ywatanabe/proj/scitex-code/src/scitex/git/init.py
4
+
5
+ """
6
+ Git initialization utilities.
7
+
8
+ Provides functions to initialize, find, and manage git repositories
9
+ with different strategies (child, parent, origin).
10
+ """
11
+
12
+ from pathlib import Path
13
+ from typing import Optional
14
+
15
+ from git import InvalidGitRepositoryError, Repo
16
+
17
+ from logging import getLogger
18
+
19
+ logger = getLogger(__name__)
20
+
21
+
22
+ def find_parent_git(project_dir: Path) -> Optional[Path]:
23
+ """
24
+ Find parent git repository by walking up directory tree.
25
+
26
+ Args:
27
+ project_dir: Starting directory to search from
28
+
29
+ Returns:
30
+ Path to parent git root, or None if not found
31
+ """
32
+ try:
33
+ repo_parent = Repo(project_dir.parent, search_parent_directories=True)
34
+ return Path(repo_parent.git_dir).parent
35
+ except InvalidGitRepositoryError:
36
+ return None
37
+
38
+
39
+ def remove_child_git(project_dir: Path) -> bool:
40
+ """
41
+ Remove project's local .git folder.
42
+
43
+ When parent git is found, the project's own .git/ is redundant and
44
+ should be removed to avoid nested git repository issues.
45
+
46
+ Args:
47
+ project_dir: Project directory containing .git to remove
48
+
49
+ Returns:
50
+ True if removed successfully or doesn't exist, False on error
51
+ """
52
+ child_git = project_dir / ".git"
53
+
54
+ if not child_git.exists():
55
+ logger.info(f"No child .git found at {project_dir}")
56
+ return True
57
+
58
+ try:
59
+ import shutil
60
+
61
+ logger.info(f"Removing child .git to use parent repository...")
62
+ shutil.rmtree(child_git)
63
+ logger.info(f"Removed child .git from {project_dir}")
64
+ return True
65
+ except PermissionError as e:
66
+ logger.error(f"Permission denied removing .git from {project_dir}: {e}")
67
+ return False
68
+ except Exception as e:
69
+ logger.error(f"Failed to remove child .git from {project_dir}: {e}")
70
+ return False
71
+
72
+
73
+ def create_child_git(project_dir: Path) -> Optional[Path]:
74
+ """
75
+ Create isolated git repository in project directory.
76
+
77
+ Uses GitPython to initialize and make initial commit.
78
+
79
+ Args:
80
+ project_dir: Directory to initialize as git repo
81
+
82
+ Returns:
83
+ Path to git root (project_dir), or None on failure
84
+ """
85
+ try:
86
+ try:
87
+ repo = Repo(project_dir)
88
+ logger.info(f"Project is already a git repository at {project_dir}")
89
+ # Optional structure validation: only runs if scitex-writer is installed.
90
+ try:
91
+ from scitex.writer._verify_tree_structure import verify_tree_structure
92
+
93
+ verify_tree_structure(project_dir)
94
+ except ImportError:
95
+ pass
96
+ return project_dir
97
+ except InvalidGitRepositoryError:
98
+ logger.info(f"Initializing new git repository at {project_dir}")
99
+ repo = Repo.init(project_dir)
100
+
101
+ repo.index.add(["."])
102
+ repo.index.commit("Initial commit from scitex template")
103
+
104
+ logger.info(f"Git repository initialized at {project_dir}")
105
+ return project_dir
106
+ except PermissionError as e:
107
+ logger.error(f"Permission denied creating git repository at {project_dir}: {e}")
108
+ return None
109
+ except OSError as e:
110
+ logger.error(f"IO error creating git repository at {project_dir}: {e}")
111
+ return None
112
+ except Exception as e:
113
+ logger.error(f"Failed to create child git repository at {project_dir}: {e}")
114
+ return None
115
+
116
+
117
+ def init_git_repo(
118
+ project_dir: Path, git_strategy: Optional[str] = "child"
119
+ ) -> Optional[Path]:
120
+ """
121
+ Initialize or detect git repository based on git_strategy.
122
+
123
+ Args:
124
+ project_dir: Project directory
125
+ git_strategy: Git initialization strategy
126
+ - None: Git disabled, returns None
127
+ - 'child': Creates isolated git repo in project directory
128
+ - 'parent': Tries to use parent git, degrades to 'child' if not found
129
+ - 'origin': Preserves template's original git history (handled by clone)
130
+
131
+ Returns:
132
+ Path to git repository root, or None if disabled
133
+ """
134
+ if git_strategy is None:
135
+ logger.info("Git initialization disabled (git_strategy=None)")
136
+ return None
137
+
138
+ if git_strategy == "parent":
139
+ logger.info("Using 'parent' git strategy, searching for parent repository...")
140
+ parent_git = find_parent_git(project_dir)
141
+
142
+ if parent_git:
143
+ logger.info(f"Found parent git repository: {parent_git}")
144
+ remove_child_git(project_dir)
145
+ return parent_git
146
+
147
+ logger.warning(
148
+ f"No parent git repository found for {project_dir}. "
149
+ f"Degrading to 'child' strategy (isolated git repo)."
150
+ )
151
+ return create_child_git(project_dir)
152
+
153
+ if git_strategy == "child":
154
+ logger.info("Using 'child' git strategy, creating isolated repository...")
155
+ return create_child_git(project_dir)
156
+
157
+ if git_strategy == "origin":
158
+ logger.info("Using 'origin' git strategy, template git history preserved...")
159
+ try:
160
+ repo = Repo(project_dir)
161
+ logger.info(f"Found git repository at {project_dir}")
162
+ return project_dir
163
+ except InvalidGitRepositoryError:
164
+ logger.warning(
165
+ f"No git repository found at {project_dir}. "
166
+ f"Degrading to 'child' strategy."
167
+ )
168
+ return create_child_git(project_dir)
169
+
170
+ raise ValueError(
171
+ f"Unknown git_strategy: {git_strategy}. "
172
+ f"Expected 'parent', 'child', 'origin', or None"
173
+ )
174
+
175
+
176
+ __all__ = [
177
+ "find_parent_git",
178
+ "remove_child_git",
179
+ "create_child_git",
180
+ "init_git_repo",
181
+ ]
182
+
183
+ # EOF
scitex_git/_remote.py ADDED
@@ -0,0 +1,283 @@
1
+ #!/usr/bin/env python3
2
+ # File: /home/ywatanabe/proj/scitex-code/src/scitex/git/remote.py
3
+
4
+ """
5
+ Git remote operations.
6
+ """
7
+
8
+ from pathlib import Path
9
+ from typing import Optional
10
+
11
+ from logging import getLogger
12
+ from ._vendor_sh import sh
13
+
14
+ from ._constants import EXIT_FAILURE, EXIT_SUCCESS
15
+ from ._utils import _in_directory
16
+
17
+ logger = getLogger(__name__)
18
+
19
+
20
+ def get_remote_url(
21
+ repo_path: Path, remote_name: str = "origin", verbose: bool = False
22
+ ) -> Optional[str]:
23
+ """
24
+ Get remote URL for a git repository.
25
+
26
+ Parameters
27
+ ----------
28
+ repo_path : Path
29
+ Git repository path
30
+ remote_name : str
31
+ Remote name (default: origin)
32
+ verbose : bool
33
+ Enable verbose output
34
+
35
+ Returns
36
+ -------
37
+ Optional[str]
38
+ Remote URL if found, None otherwise
39
+
40
+ Notes
41
+ -----
42
+ Returns None if remote doesn't exist or repo is not a git repository.
43
+ Check stderr via sh() directly if detailed error info is needed.
44
+ """
45
+ if not (repo_path / ".git").exists():
46
+ logger.warning(f"Not a git repository: {repo_path}")
47
+ return None
48
+
49
+ with _in_directory(repo_path):
50
+ result = sh(
51
+ ["git", "config", "--get", f"remote.{remote_name}.url"],
52
+ verbose=verbose,
53
+ return_as="dict",
54
+ )
55
+ if result["success"]:
56
+ return result["stdout"].strip()
57
+
58
+ logger.debug(f"Remote '{remote_name}' not found in {repo_path}")
59
+ return None
60
+
61
+
62
+ def _validate_git_url(url: str) -> bool:
63
+ """
64
+ Validate git URL format.
65
+
66
+ Parameters
67
+ ----------
68
+ url : str
69
+ Git URL to validate
70
+
71
+ Returns
72
+ -------
73
+ bool
74
+ True if valid, False otherwise
75
+ """
76
+ valid_hosts = ("github.com", "gitlab.com", "bitbucket.org")
77
+
78
+ if url.startswith("https://"):
79
+ for host in valid_hosts:
80
+ if f"https://{host}/" in url:
81
+ return True
82
+
83
+ elif url.startswith("git@"):
84
+ for host in valid_hosts:
85
+ if url.startswith(f"git@{host}:"):
86
+ return True
87
+
88
+ return False
89
+
90
+
91
+ def _normalize_git_url(url: str) -> str:
92
+ """
93
+ Normalize git URL for comparison.
94
+ Handles HTTPS and SSH formats for GitHub, GitLab, Bitbucket.
95
+
96
+ Parameters
97
+ ----------
98
+ url : str
99
+ Git URL to normalize
100
+
101
+ Returns
102
+ -------
103
+ str
104
+ Normalized URL
105
+ """
106
+ url = url.rstrip("/")
107
+
108
+ if url.startswith("git@"):
109
+ url = url.replace(":", "/", 1).replace("git@", "https://")
110
+
111
+ if url.endswith(".git"):
112
+ url = url[:-4]
113
+
114
+ return url
115
+
116
+
117
+ def is_cloned_from(
118
+ repo_path: Path, expected_url: str, remote_name: str = "origin"
119
+ ) -> bool:
120
+ """
121
+ Check if directory is a git repository cloned from specific URL.
122
+ Handles both HTTPS and SSH URL formats.
123
+
124
+ Parameters
125
+ ----------
126
+ repo_path : Path
127
+ Directory to check
128
+ expected_url : str
129
+ Expected remote URL
130
+ remote_name : str
131
+ Remote name to check (default: origin)
132
+
133
+ Returns
134
+ -------
135
+ bool
136
+ True if directory is cloned from expected URL, False otherwise
137
+ """
138
+ if not (repo_path / ".git").exists():
139
+ return False
140
+ actual_url = get_remote_url(repo_path, remote_name)
141
+ if actual_url is None:
142
+ return False
143
+ return _normalize_git_url(actual_url) == _normalize_git_url(expected_url)
144
+
145
+
146
+ def ls_remote(
147
+ url: str,
148
+ ref: Optional[str] = None,
149
+ verbose: bool = False,
150
+ ) -> Optional[str]:
151
+ """
152
+ Get commit hash of a remote ref via ``git ls-remote``.
153
+
154
+ Parameters
155
+ ----------
156
+ url : str
157
+ Git repository URL.
158
+ ref : str, optional
159
+ Branch name, tag, or ref pattern. If None, returns HEAD.
160
+ verbose : bool
161
+ Enable verbose output.
162
+
163
+ Returns
164
+ -------
165
+ Optional[str]
166
+ Commit SHA-1 hash (40 hex chars), or None on failure.
167
+
168
+ Examples
169
+ --------
170
+ >>> ls_remote("https://github.com/user/repo.git")
171
+ 'abc123...'
172
+ >>> ls_remote("https://github.com/user/repo.git", ref="main")
173
+ 'abc123...'
174
+ >>> ls_remote("https://github.com/user/repo.git", ref="v1.0.0")
175
+ 'def456...'
176
+ """
177
+ cmd = ["git", "ls-remote"]
178
+ if ref is None:
179
+ cmd.append("--symref")
180
+ cmd.append(url)
181
+ if ref is not None:
182
+ cmd.append(ref)
183
+
184
+ result = sh(cmd, verbose=verbose, return_as="dict")
185
+ if not result["success"]:
186
+ logger.debug(f"ls-remote failed for {url}: {result.get('stderr', '')}")
187
+ return None
188
+
189
+ stdout = result["stdout"].strip()
190
+ if not stdout:
191
+ return None
192
+
193
+ # Parse first line: "<hash>\t<ref>"
194
+ for line in stdout.splitlines():
195
+ parts = line.split("\t", 1)
196
+ if len(parts) == 2 and len(parts[0]) == 40:
197
+ return parts[0]
198
+
199
+ return None
200
+
201
+
202
+ def get_head_hash(
203
+ repo_path: Path,
204
+ verbose: bool = False,
205
+ ) -> Optional[str]:
206
+ """
207
+ Get HEAD commit hash of a local git repository.
208
+
209
+ Parameters
210
+ ----------
211
+ repo_path : Path
212
+ Git repository path (must contain .git/).
213
+ verbose : bool
214
+ Enable verbose output.
215
+
216
+ Returns
217
+ -------
218
+ Optional[str]
219
+ Commit SHA-1 hash, or None if not a git repo.
220
+ """
221
+ if not (repo_path / ".git").exists():
222
+ return None
223
+
224
+ with _in_directory(repo_path):
225
+ result = sh(
226
+ ["git", "rev-parse", "HEAD"],
227
+ verbose=verbose,
228
+ return_as="dict",
229
+ )
230
+ if result["success"]:
231
+ return result["stdout"].strip()
232
+ return None
233
+
234
+
235
+ def main(args):
236
+ if args.action == "get-url":
237
+ url = get_remote_url(args.repo_path, args.remote_name, args.verbose)
238
+ if url:
239
+ print(url)
240
+ return EXIT_SUCCESS
241
+ return EXIT_FAILURE
242
+ elif args.action == "check-origin":
243
+ if not args.expected_url:
244
+ logger.error("Expected URL required for check-origin action")
245
+ return EXIT_FAILURE
246
+ result = is_cloned_from(args.repo_path, args.expected_url, args.remote_name)
247
+ print(result)
248
+ return EXIT_SUCCESS if result else EXIT_FAILURE
249
+
250
+
251
+ def parse_args():
252
+ """Parse command line arguments."""
253
+ import argparse
254
+
255
+ parser = argparse.ArgumentParser()
256
+ parser.add_argument("--action", choices=["get-url", "check-origin"], required=True)
257
+ parser.add_argument("--repo-path", type=Path, required=True)
258
+ parser.add_argument("--expected-url", help="Expected URL for check-origin action")
259
+ parser.add_argument("--remote-name", default="origin")
260
+ parser.add_argument("--verbose", action="store_true")
261
+ return parser.parse_args()
262
+
263
+
264
+ def run_session():
265
+ """Initialize scitex framework, run main function, and cleanup."""
266
+ from ._session import run_with_session
267
+
268
+ run_with_session(parse_args, main)
269
+
270
+
271
+ __all__ = [
272
+ "get_remote_url",
273
+ "is_cloned_from",
274
+ "ls_remote",
275
+ "get_head_hash",
276
+ "_validate_git_url",
277
+ ]
278
+
279
+
280
+ if __name__ == "__main__":
281
+ run_session()
282
+
283
+ # EOF
scitex_git/_result.py ADDED
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # File: /home/ywatanabe/proj/scitex-code/src/scitex/git/result.py
4
+
5
+ """
6
+ Result dataclasses for git operations.
7
+ """
8
+
9
+ from dataclasses import dataclass
10
+ from typing import Optional
11
+
12
+
13
+ @dataclass
14
+ class GitResult:
15
+ """
16
+ Result of a git operation.
17
+
18
+ Attributes
19
+ ----------
20
+ success : bool
21
+ Whether operation succeeded
22
+ error : Optional[str]
23
+ Error message if operation failed
24
+ stdout : Optional[str]
25
+ Standard output from git command
26
+ stderr : Optional[str]
27
+ Standard error from git command
28
+ """
29
+
30
+ success: bool
31
+ error: Optional[str] = None
32
+ stdout: Optional[str] = None
33
+ stderr: Optional[str] = None
34
+
35
+
36
+ @dataclass
37
+ class CommitResult(GitResult):
38
+ """
39
+ Result of a git commit operation.
40
+
41
+ Attributes
42
+ ----------
43
+ commit_hash : Optional[str]
44
+ Hash of created commit if successful
45
+ """
46
+
47
+ commit_hash: Optional[str] = None
48
+
49
+
50
+ @dataclass
51
+ class BranchResult(GitResult):
52
+ """
53
+ Result of a git branch operation.
54
+
55
+ Attributes
56
+ ----------
57
+ branch_name : Optional[str]
58
+ Name of created or renamed branch if successful
59
+ """
60
+
61
+ branch_name: Optional[str] = None
62
+
63
+
64
+ __all__ = [
65
+ "GitResult",
66
+ "CommitResult",
67
+ "BranchResult",
68
+ ]
69
+
70
+ # EOF
scitex_git/_retry.py ADDED
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # Timestamp: "2025-10-29 (ywatanabe)"
4
+ # File: /home/ywatanabe/proj/scitex-code/src/scitex/git/retry.py
5
+ # ----------------------------------------
6
+ from __future__ import annotations
7
+
8
+ import os
9
+
10
+ __FILE__ = "./src/scitex/git/retry.py"
11
+ __DIR__ = os.path.dirname(__FILE__)
12
+ # ----------------------------------------
13
+
14
+ """
15
+ Git retry logic with exponential backoff.
16
+
17
+ Handles git index.lock conflicts when multiple processes access git.
18
+ Shared across all scitex modules.
19
+ """
20
+
21
+ import subprocess
22
+ import time
23
+ from typing import Callable, TypeVar
24
+
25
+ from logging import getLogger
26
+
27
+ logger = getLogger(__name__)
28
+
29
+ T = TypeVar("T")
30
+
31
+
32
+ def git_retry(
33
+ operation: Callable[[], T],
34
+ max_retries: int = 5,
35
+ initial_delay: float = 0.1,
36
+ max_delay: float = 2.0,
37
+ backoff_factor: float = 2.0,
38
+ ) -> T:
39
+ """
40
+ Retry git operations with exponential backoff.
41
+
42
+ Handles git index.lock conflicts when multiple processes access git.
43
+
44
+ Parameters
45
+ ----------
46
+ operation : Callable
47
+ Function to retry
48
+ max_retries : int
49
+ Maximum number of retry attempts
50
+ initial_delay : float
51
+ Initial delay in seconds
52
+ max_delay : float
53
+ Maximum delay between retries
54
+ backoff_factor : float
55
+ Exponential backoff multiplier
56
+
57
+ Returns
58
+ -------
59
+ T
60
+ Result of operation
61
+
62
+ Raises
63
+ ------
64
+ TimeoutError
65
+ If all retries exhausted due to lock
66
+ Exception
67
+ Original exception if not a lock error
68
+
69
+ Examples
70
+ --------
71
+ >>> def commit_file():
72
+ ... subprocess.run(["git", "commit", "-m", "msg"], check=True)
73
+ >>> git_retry(commit_file)
74
+ """
75
+ delay = initial_delay
76
+ last_exception = None
77
+
78
+ for attempt in range(max_retries):
79
+ try:
80
+ return operation()
81
+ except subprocess.CalledProcessError as e:
82
+ # Check if it's a lock error
83
+ stderr = (
84
+ e.stderr
85
+ if isinstance(e.stderr, str)
86
+ else (e.stderr.decode("utf-8", errors="ignore") if e.stderr else "")
87
+ )
88
+
89
+ if "index.lock" in stderr and attempt < max_retries - 1:
90
+ logger.debug(
91
+ f"Git lock detected, retrying in {delay:.2f}s "
92
+ f"(attempt {attempt + 1}/{max_retries})"
93
+ )
94
+ time.sleep(delay)
95
+ delay = min(delay * backoff_factor, max_delay)
96
+ last_exception = e
97
+ continue
98
+
99
+ # Not a lock error, or retries exhausted
100
+ raise
101
+ except Exception:
102
+ # Non-git errors: don't retry
103
+ raise
104
+
105
+ # All retries exhausted
106
+ if last_exception:
107
+ raise TimeoutError(
108
+ f"Could not acquire git lock after {max_retries} attempts"
109
+ ) from last_exception
110
+
111
+
112
+ __all__ = ["git_retry"]
113
+
114
+ # EOF