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,35 @@
1
+ #!/usr/bin/env python3
2
+ # File: /home/ywatanabe/proj/scitex-code/src/scitex/git/__init__.py
3
+
4
+ """scitex-git — git operations and utilities (extracted from SciTeX)."""
5
+
6
+ __version__ = "0.1.0"
7
+
8
+ from ._branch import git_branch_rename, git_checkout_new_branch
9
+ from ._clone import clone_repo, git_init
10
+ from ._commit import git_add_all, git_commit
11
+ from ._init import create_child_git, find_parent_git, init_git_repo, remove_child_git
12
+ from ._remote import get_head_hash, get_remote_url, is_cloned_from, ls_remote
13
+ from ._retry import git_retry
14
+ from ._workflow import setup_branches
15
+
16
+ __all__ = [
17
+ "init_git_repo",
18
+ "find_parent_git",
19
+ "create_child_git",
20
+ "remove_child_git",
21
+ "clone_repo",
22
+ "git_init",
23
+ "git_add_all",
24
+ "git_commit",
25
+ "git_branch_rename",
26
+ "git_checkout_new_branch",
27
+ "get_remote_url",
28
+ "is_cloned_from",
29
+ "ls_remote",
30
+ "get_head_hash",
31
+ "setup_branches",
32
+ "git_retry",
33
+ ]
34
+
35
+ # EOF
scitex_git/_branch.py ADDED
@@ -0,0 +1,187 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # File: /home/ywatanabe/proj/scitex-code/src/scitex/git/branch.py
4
+
5
+ """
6
+ Git branch operations.
7
+
8
+ Examples
9
+ --------
10
+ >>> from pathlib import Path
11
+ >>> from scitex.git import git_branch_rename, git_checkout_new_branch
12
+ >>> repo = Path("/path/to/repo")
13
+ >>> git_branch_rename(repo, "main")
14
+ >>> git_checkout_new_branch(repo, "feature/new-feature")
15
+ """
16
+
17
+ from pathlib import Path
18
+
19
+ from logging import getLogger
20
+ from ._vendor_sh import sh
21
+
22
+ from ._constants import EXIT_FAILURE, EXIT_SUCCESS
23
+ from ._utils import _in_directory
24
+ from ._validation import validate_branch_name, validate_path
25
+
26
+ logger = getLogger(__name__)
27
+
28
+
29
+ def git_branch_rename(repo_path: Path, new_name: str, verbose: bool = True) -> bool:
30
+ """
31
+ Rename current branch.
32
+
33
+ Parameters
34
+ ----------
35
+ repo_path : Path
36
+ Git repository path
37
+ new_name : str
38
+ New branch name
39
+ verbose : bool
40
+ Enable verbose output
41
+
42
+ Returns
43
+ -------
44
+ bool
45
+ True if successful, False if:
46
+ - repo_path is not a git repository
47
+ - new_name is invalid
48
+ - git branch command fails
49
+
50
+ Examples
51
+ --------
52
+ >>> git_branch_rename(Path("/my/repo"), "main")
53
+ True
54
+ """
55
+ valid, error = validate_path(repo_path, must_exist=True)
56
+ if not valid:
57
+ logger.error(error)
58
+ return False
59
+
60
+ if not (repo_path / ".git").exists():
61
+ logger.error(f"Not a git repository: {repo_path}")
62
+ return False
63
+
64
+ valid, error = validate_branch_name(new_name)
65
+ if not valid:
66
+ logger.error(error)
67
+ return False
68
+
69
+ with _in_directory(repo_path):
70
+ result = sh(
71
+ ["git", "branch", "-M", new_name], verbose=verbose, return_as="dict"
72
+ )
73
+
74
+ if not result["success"]:
75
+ error_msg = (
76
+ result["stderr"].strip() if result["stderr"] else "Unknown error"
77
+ )
78
+ logger.error(f"Failed to rename branch in {repo_path}: {error_msg}")
79
+ return False
80
+
81
+ if verbose:
82
+ logger.info(f"Branch renamed to {new_name}")
83
+ return True
84
+
85
+
86
+ def git_checkout_new_branch(
87
+ repo_path: Path, branch_name: str, verbose: bool = True
88
+ ) -> bool:
89
+ """
90
+ Create and checkout a new branch.
91
+
92
+ Parameters
93
+ ----------
94
+ repo_path : Path
95
+ Git repository path
96
+ branch_name : str
97
+ New branch name
98
+ verbose : bool
99
+ Enable verbose output
100
+
101
+ Returns
102
+ -------
103
+ bool
104
+ True if successful, False if:
105
+ - repo_path is not a git repository
106
+ - branch_name is invalid
107
+ - git checkout command fails
108
+
109
+ Examples
110
+ --------
111
+ >>> git_checkout_new_branch(Path("/my/repo"), "feature/auth")
112
+ True
113
+ """
114
+ valid, error = validate_path(repo_path, must_exist=True)
115
+ if not valid:
116
+ logger.error(error)
117
+ return False
118
+
119
+ if not (repo_path / ".git").exists():
120
+ logger.error(f"Not a git repository: {repo_path}")
121
+ return False
122
+
123
+ valid, error = validate_branch_name(branch_name)
124
+ if not valid:
125
+ logger.error(error)
126
+ return False
127
+
128
+ with _in_directory(repo_path):
129
+ result = sh(
130
+ ["git", "checkout", "-b", branch_name], verbose=verbose, return_as="dict"
131
+ )
132
+
133
+ if not result["success"]:
134
+ error_msg = (
135
+ result["stderr"].strip() if result["stderr"] else "Unknown error"
136
+ )
137
+ logger.error(
138
+ f"Failed to create branch {branch_name} in {repo_path}: {error_msg}"
139
+ )
140
+ return False
141
+
142
+ if verbose:
143
+ logger.info(f"Switched to new branch: {branch_name}")
144
+ return True
145
+
146
+
147
+ def main(args):
148
+ if args.action == "rename":
149
+ success = git_branch_rename(args.repo_path, args.branch_name, args.verbose)
150
+ elif args.action == "checkout":
151
+ success = git_checkout_new_branch(
152
+ args.repo_path, args.branch_name, args.verbose
153
+ )
154
+ else:
155
+ return EXIT_FAILURE
156
+ return EXIT_SUCCESS if success else EXIT_FAILURE
157
+
158
+
159
+ def parse_args():
160
+ """Parse command line arguments."""
161
+ import argparse
162
+
163
+ parser = argparse.ArgumentParser()
164
+ parser.add_argument("--repo-path", type=Path, required=True)
165
+ parser.add_argument("--action", choices=["rename", "checkout"], required=True)
166
+ parser.add_argument("--branch-name", required=True)
167
+ parser.add_argument("--verbose", action="store_true")
168
+ return parser.parse_args()
169
+
170
+
171
+ def run_session():
172
+ """Initialize scitex framework, run main function, and cleanup."""
173
+ from ._session import run_with_session
174
+
175
+ run_with_session(parse_args, main)
176
+
177
+
178
+ __all__ = [
179
+ "git_branch_rename",
180
+ "git_checkout_new_branch",
181
+ ]
182
+
183
+
184
+ if __name__ == "__main__":
185
+ run_session()
186
+
187
+ # EOF
scitex_git/_clone.py ADDED
@@ -0,0 +1,169 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # File: /home/ywatanabe/proj/scitex-code/src/scitex/git/clone.py
4
+
5
+ """
6
+ Git clone operations.
7
+ """
8
+
9
+ from pathlib import Path
10
+
11
+ from logging import getLogger
12
+ from ._vendor_sh import sh
13
+
14
+ from ._constants import EXIT_FAILURE, EXIT_SUCCESS
15
+
16
+ logger = getLogger(__name__)
17
+
18
+
19
+ def clone_repo(
20
+ url: str,
21
+ target_path: Path,
22
+ branch: str = None,
23
+ tag: str = None,
24
+ verbose: bool = True,
25
+ ) -> bool:
26
+ """
27
+ Safely clone a git repository.
28
+
29
+ Parameters
30
+ ----------
31
+ url : str
32
+ Git repository URL
33
+ target_path : Path
34
+ Destination path for cloning
35
+ branch : str, optional
36
+ Specific branch to clone. If None, clones the default branch.
37
+ Mutually exclusive with tag parameter.
38
+ tag : str, optional
39
+ Specific tag/release to clone. If None, clones the default branch.
40
+ Mutually exclusive with branch parameter.
41
+ verbose : bool
42
+ Enable verbose output
43
+
44
+ Returns
45
+ -------
46
+ bool
47
+ True if successful, False otherwise
48
+
49
+ Raises
50
+ ------
51
+ ValueError
52
+ If both branch and tag are specified
53
+ """
54
+ from ._remote import _validate_git_url
55
+
56
+ # Validate mutual exclusivity
57
+ if branch and tag:
58
+ raise ValueError(
59
+ "Cannot specify both 'branch' and 'tag' parameters. They are mutually exclusive."
60
+ )
61
+
62
+ if not _validate_git_url(url):
63
+ logger.error(f"Invalid git URL: {url}")
64
+ return False
65
+
66
+ cmd = ["git", "clone"]
67
+ ref_info = ""
68
+ if branch:
69
+ cmd.extend(["--branch", branch])
70
+ ref_info = f" (branch: {branch})"
71
+ elif tag:
72
+ cmd.extend(["--branch", tag])
73
+ ref_info = f" (tag: {tag})"
74
+ cmd.extend([url, str(target_path)])
75
+
76
+ result = sh(cmd, verbose=verbose, return_as="dict")
77
+
78
+ if not result["success"]:
79
+ logger.error(f"Failed to clone repository: {result['stderr']}")
80
+ return False
81
+
82
+ if verbose:
83
+ logger.info(f"Repository cloned successfully{ref_info}")
84
+ return True
85
+
86
+
87
+ def git_init(repo_path: Path, verbose: bool = True) -> bool:
88
+ """
89
+ Initialize a new git repository.
90
+
91
+ Parameters
92
+ ----------
93
+ repo_path : Path
94
+ Path to initialize as git repository
95
+ verbose : bool
96
+ Enable verbose output
97
+
98
+ Returns
99
+ -------
100
+ bool
101
+ True if successful, False otherwise
102
+ """
103
+ from ._utils import _in_directory
104
+
105
+ if (repo_path / ".git").exists():
106
+ logger.warning("Git repository already initialized")
107
+ return False
108
+
109
+ with _in_directory(repo_path):
110
+ result = sh(["git", "init", "-b", "main"], verbose=verbose, return_as="dict")
111
+
112
+ if not result["success"]:
113
+ logger.warning(f"Failed to initialize git repository: {result['stderr']}")
114
+ return False
115
+
116
+ if verbose:
117
+ logger.info("Git repository initialized")
118
+ return True
119
+
120
+
121
+ def main(args):
122
+ if args.action == "clone":
123
+ if not args.url:
124
+ logger.error("URL required for clone action")
125
+ return EXIT_FAILURE
126
+ success = clone_repo(
127
+ args.url, args.path, branch=args.branch, tag=args.tag, verbose=args.verbose
128
+ )
129
+ return EXIT_SUCCESS if success else EXIT_FAILURE
130
+ elif args.action == "init":
131
+ success = git_init(args.path, args.verbose)
132
+ return EXIT_SUCCESS if success else EXIT_FAILURE
133
+
134
+
135
+ def parse_args():
136
+ """Parse command line arguments."""
137
+ import argparse
138
+
139
+ parser = argparse.ArgumentParser()
140
+ parser.add_argument("--action", choices=["clone", "init"], required=True)
141
+ parser.add_argument("--url", help="Repository URL for cloning")
142
+ parser.add_argument("--path", type=Path, required=True)
143
+ parser.add_argument(
144
+ "--branch", help="Branch to clone (mutually exclusive with --tag)"
145
+ )
146
+ parser.add_argument(
147
+ "--tag", help="Tag/release to clone (mutually exclusive with --branch)"
148
+ )
149
+ parser.add_argument("--verbose", action="store_true")
150
+ return parser.parse_args()
151
+
152
+
153
+ def run_session():
154
+ """Initialize scitex framework, run main function, and cleanup."""
155
+ from ._session import run_with_session
156
+
157
+ run_with_session(parse_args, main)
158
+
159
+
160
+ __all__ = [
161
+ "clone_repo",
162
+ "git_init",
163
+ ]
164
+
165
+
166
+ if __name__ == "__main__":
167
+ run_session()
168
+
169
+ # EOF
scitex_git/_commit.py ADDED
@@ -0,0 +1,172 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # File: /home/ywatanabe/proj/scitex-code/src/scitex/git/commit.py
4
+
5
+ """
6
+ Git commit operations.
7
+
8
+ Examples
9
+ --------
10
+ >>> from pathlib import Path
11
+ >>> from scitex.git import git_commit, git_add_all
12
+ >>> repo = Path("/path/to/repo")
13
+ >>> result = git_add_all(repo)
14
+ >>> if result:
15
+ ... git_commit(repo, "Initial commit")
16
+ """
17
+
18
+ from pathlib import Path
19
+
20
+ from logging import getLogger
21
+ from ._vendor_sh import sh
22
+
23
+ from ._constants import EXIT_FAILURE, EXIT_SUCCESS
24
+ from ._utils import _in_directory
25
+ from ._validation import validate_commit_message, validate_path
26
+
27
+ logger = getLogger(__name__)
28
+
29
+
30
+ def git_add_all(repo_path: Path, verbose: bool = True) -> bool:
31
+ """
32
+ Add all files to git staging.
33
+
34
+ Parameters
35
+ ----------
36
+ repo_path : Path
37
+ Git repository path
38
+ verbose : bool
39
+ Enable verbose output
40
+
41
+ Returns
42
+ -------
43
+ bool
44
+ True if successful, False if:
45
+ - repo_path is not a git repository
46
+ - git add command fails
47
+ - path is invalid
48
+
49
+ Examples
50
+ --------
51
+ >>> git_add_all(Path("/my/repo"))
52
+ True
53
+ """
54
+ valid, error = validate_path(repo_path, must_exist=True)
55
+ if not valid:
56
+ logger.error(error)
57
+ return False
58
+
59
+ if not (repo_path / ".git").exists():
60
+ logger.error(f"Not a git repository: {repo_path}")
61
+ return False
62
+
63
+ with _in_directory(repo_path):
64
+ result = sh(["git", "add", "."], verbose=verbose, return_as="dict")
65
+
66
+ if not result["success"]:
67
+ error_msg = (
68
+ result["stderr"].strip() if result["stderr"] else "Unknown error"
69
+ )
70
+ logger.error(f"Failed to add files to {repo_path}: {error_msg}")
71
+ return False
72
+
73
+ return True
74
+
75
+
76
+ def git_commit(repo_path: Path, message: str, verbose: bool = True) -> bool:
77
+ """
78
+ Create a git commit.
79
+
80
+ Parameters
81
+ ----------
82
+ repo_path : Path
83
+ Git repository path
84
+ message : str
85
+ Commit message
86
+ verbose : bool
87
+ Enable verbose output
88
+
89
+ Returns
90
+ -------
91
+ bool
92
+ True if successful, False if:
93
+ - repo_path is not a git repository
94
+ - message is empty
95
+ - git commit command fails
96
+ - no changes to commit
97
+
98
+ Examples
99
+ --------
100
+ >>> git_commit(Path("/my/repo"), "Fix bug in parser")
101
+ True
102
+ """
103
+ valid, error = validate_path(repo_path, must_exist=True)
104
+ if not valid:
105
+ logger.error(error)
106
+ return False
107
+
108
+ if not (repo_path / ".git").exists():
109
+ logger.error(f"Not a git repository: {repo_path}")
110
+ return False
111
+
112
+ valid, error = validate_commit_message(message)
113
+ if not valid:
114
+ logger.error(error)
115
+ return False
116
+
117
+ with _in_directory(repo_path):
118
+ result = sh(["git", "commit", "-m", message], verbose=verbose, return_as="dict")
119
+
120
+ if not result["success"]:
121
+ error_msg = (
122
+ result["stderr"].strip() if result["stderr"] else "Unknown error"
123
+ )
124
+ logger.error(f"Failed to commit in {repo_path}: {error_msg}")
125
+ return False
126
+
127
+ if verbose:
128
+ logger.info("Commit created successfully")
129
+ return True
130
+
131
+
132
+ def main(args):
133
+ if args.action == "add":
134
+ success = git_add_all(args.repo_path, args.verbose)
135
+ return EXIT_SUCCESS if success else EXIT_FAILURE
136
+ elif args.action == "commit":
137
+ if not args.message:
138
+ logger.error("Message required for commit action")
139
+ return EXIT_FAILURE
140
+ success = git_commit(args.repo_path, args.message, args.verbose)
141
+ return EXIT_SUCCESS if success else EXIT_FAILURE
142
+
143
+
144
+ def parse_args():
145
+ """Parse command line arguments."""
146
+ import argparse
147
+
148
+ parser = argparse.ArgumentParser()
149
+ parser.add_argument("--repo-path", type=Path, required=True)
150
+ parser.add_argument("--action", choices=["add", "commit"], required=True)
151
+ parser.add_argument("--message", help="Commit message")
152
+ parser.add_argument("--verbose", action="store_true")
153
+ return parser.parse_args()
154
+
155
+
156
+ def run_session():
157
+ """Initialize scitex framework, run main function, and cleanup."""
158
+ from ._session import run_with_session
159
+
160
+ run_with_session(parse_args, main)
161
+
162
+
163
+ __all__ = [
164
+ "git_add_all",
165
+ "git_commit",
166
+ ]
167
+
168
+
169
+ if __name__ == "__main__":
170
+ run_session()
171
+
172
+ # EOF
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # File: /home/ywatanabe/proj/scitex-code/src/scitex/git/constants.py
4
+
5
+ """
6
+ Constants for git module.
7
+ """
8
+
9
+ EXIT_SUCCESS = 0
10
+ EXIT_FAILURE = 1
11
+
12
+ __all__ = [
13
+ "EXIT_SUCCESS",
14
+ "EXIT_FAILURE",
15
+ ]
16
+
17
+ # EOF