scitex-git 0.1.2__tar.gz → 0.2.0__tar.gz

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.
Files changed (35) hide show
  1. scitex_git-0.2.0/PKG-INFO +198 -0
  2. scitex_git-0.2.0/README.md +160 -0
  3. {scitex_git-0.1.2 → scitex_git-0.2.0}/pyproject.toml +3 -2
  4. {scitex_git-0.1.2 → scitex_git-0.2.0}/src/scitex_git/__init__.py +27 -1
  5. scitex_git-0.2.0/src/scitex_git/_gh_secrets.py +215 -0
  6. {scitex_git-0.1.2 → scitex_git-0.2.0}/src/scitex_git/_init.py +16 -7
  7. scitex_git-0.2.0/src/scitex_git/_skills/scitex-git/01_installation.md +46 -0
  8. scitex_git-0.2.0/src/scitex_git/_skills/scitex-git/02_quick-start.md +58 -0
  9. scitex_git-0.2.0/src/scitex_git/_skills/scitex-git/03_python-api.md +78 -0
  10. scitex_git-0.2.0/src/scitex_git/_skills/scitex-git/SKILL.md +30 -0
  11. scitex_git-0.2.0/src/scitex_git.egg-info/PKG-INFO +198 -0
  12. {scitex_git-0.1.2 → scitex_git-0.2.0}/src/scitex_git.egg-info/SOURCES.txt +5 -2
  13. {scitex_git-0.1.2 → scitex_git-0.2.0}/src/scitex_git.egg-info/requires.txt +1 -0
  14. scitex_git-0.1.2/PKG-INFO +0 -108
  15. scitex_git-0.1.2/README.md +0 -71
  16. scitex_git-0.1.2/src/scitex_git/_skills/scitex-git/SKILL.md +0 -27
  17. scitex_git-0.1.2/src/scitex_git.egg-info/PKG-INFO +0 -108
  18. scitex_git-0.1.2/tests/test_examples.py +0 -20
  19. {scitex_git-0.1.2 → scitex_git-0.2.0}/LICENSE +0 -0
  20. {scitex_git-0.1.2 → scitex_git-0.2.0}/setup.cfg +0 -0
  21. {scitex_git-0.1.2 → scitex_git-0.2.0}/src/scitex_git/_branch.py +0 -0
  22. {scitex_git-0.1.2 → scitex_git-0.2.0}/src/scitex_git/_clone.py +0 -0
  23. {scitex_git-0.1.2 → scitex_git-0.2.0}/src/scitex_git/_commit.py +0 -0
  24. {scitex_git-0.1.2 → scitex_git-0.2.0}/src/scitex_git/_constants.py +0 -0
  25. {scitex_git-0.1.2 → scitex_git-0.2.0}/src/scitex_git/_remote.py +0 -0
  26. {scitex_git-0.1.2 → scitex_git-0.2.0}/src/scitex_git/_result.py +0 -0
  27. {scitex_git-0.1.2 → scitex_git-0.2.0}/src/scitex_git/_retry.py +0 -0
  28. {scitex_git-0.1.2 → scitex_git-0.2.0}/src/scitex_git/_types.py +0 -0
  29. {scitex_git-0.1.2 → scitex_git-0.2.0}/src/scitex_git/_utils.py +0 -0
  30. {scitex_git-0.1.2 → scitex_git-0.2.0}/src/scitex_git/_validation.py +0 -0
  31. {scitex_git-0.1.2 → scitex_git-0.2.0}/src/scitex_git/_vendor_sh.py +0 -0
  32. {scitex_git-0.1.2 → scitex_git-0.2.0}/src/scitex_git/_workflow.py +0 -0
  33. {scitex_git-0.1.2 → scitex_git-0.2.0}/src/scitex_git.egg-info/dependency_links.txt +0 -0
  34. {scitex_git-0.1.2 → scitex_git-0.2.0}/src/scitex_git.egg-info/entry_points.txt +0 -0
  35. {scitex_git-0.1.2 → scitex_git-0.2.0}/src/scitex_git.egg-info/top_level.txt +0 -0
@@ -0,0 +1,198 @@
1
+ Metadata-Version: 2.4
2
+ Name: scitex-git
3
+ Version: 0.2.0
4
+ Summary: Git + GitHub Actions utilities (clone, branch, commit, retry, remote helpers, gh secrets/variables with SHA256 sidecar) — 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
+ Requires-Dist: scitex-dev>=0.11.5; extra == "dev"
29
+ Provides-Extra: docs
30
+ Requires-Dist: sphinx>=7.0; extra == "docs"
31
+ Requires-Dist: sphinx-rtd-theme>=2.0; extra == "docs"
32
+ Requires-Dist: myst-parser>=2.0; extra == "docs"
33
+ Requires-Dist: sphinx-copybutton>=0.5; extra == "docs"
34
+ Requires-Dist: sphinx-autodoc-typehints>=1.25; extra == "docs"
35
+ Provides-Extra: all
36
+ Requires-Dist: scitex-git[dev,docs]; extra == "all"
37
+ Dynamic: license-file
38
+
39
+ # scitex-git
40
+
41
+ <p align="center">
42
+ <a href="https://scitex.ai">
43
+ <img src="docs/scitex-logo-blue-cropped.png" alt="SciTeX" width="400">
44
+ </a>
45
+ </p>
46
+
47
+ <p align="center"><b>Git operations and utilities — clone, init, branch, remote, retry decorator.</b></p>
48
+
49
+ <p align="center">
50
+ <a href="https://scitex-git.readthedocs.io/">Full Documentation</a> · <code>pip install scitex-git</code>
51
+ </p>
52
+
53
+ <!-- scitex-badges:start -->
54
+ <p align="center">
55
+ <a href="https://pypi.org/project/scitex-git/"><img src="https://img.shields.io/pypi/v/scitex-git.svg" alt="PyPI"></a>
56
+ <a href="https://pypi.org/project/scitex-git/"><img src="https://img.shields.io/pypi/pyversions/scitex-git.svg" alt="Python"></a>
57
+ <a href="https://github.com/ywatanabe1989/scitex-git/actions/workflows/test.yml"><img src="https://github.com/ywatanabe1989/scitex-git/actions/workflows/test.yml/badge.svg" alt="Tests"></a>
58
+ <a href="https://github.com/ywatanabe1989/scitex-git/actions/workflows/install-test.yml"><img src="https://github.com/ywatanabe1989/scitex-git/actions/workflows/install-test.yml/badge.svg" alt="Install Test"></a>
59
+ <a href="https://codecov.io/gh/ywatanabe1989/scitex-git"><img src="https://codecov.io/gh/ywatanabe1989/scitex-git/graph/badge.svg" alt="Coverage"></a>
60
+ <a href="https://scitex-git.readthedocs.io/en/latest/"><img src="https://readthedocs.org/projects/scitex-git/badge/?version=latest" alt="Docs"></a>
61
+ <a href="https://www.gnu.org/licenses/agpl-3.0"><img src="https://img.shields.io/badge/license-AGPL_v3-blue.svg" alt="License: AGPL v3"></a>
62
+ </p>
63
+ <!-- scitex-badges:end -->
64
+
65
+ ---
66
+
67
+ ## Installation
68
+
69
+ ```bash
70
+ pip install scitex-git
71
+ ```
72
+
73
+ ## Architecture
74
+
75
+ ```
76
+ scitex_git/
77
+ ├── _clone.py ← clone_repo, ls_remote, get_remote_url
78
+ ├── _init.py ← git_init, init_git_repo, find_parent_git
79
+ ├── _commit.py ← git_add_all, git_commit
80
+ ├── _branch.py ← checkout_new_branch, branch_rename, setup_branches
81
+ ├── _remote.py ← remote-URL helpers, head-hash queries
82
+ ├── _retry.py ← @git_retry decorator (transient-error backoff)
83
+ ├── _validation.py ← repo-state guards
84
+ ├── _workflow.py ← high-level multi-step flows
85
+ ├── _vendor_sh.py ← ~70-LOC subprocess wrapper (replaces scitex.sh)
86
+ └── _skills/ ← agent-facing skill pages
87
+ ```
88
+
89
+ Pure-stdlib core. `_vendor_sh.py` is intentionally tiny so the package
90
+ has no `scitex.*` runtime dependency. The umbrella `scitex.git` import
91
+ resolves through a `sys.modules` bridge.
92
+
93
+ ## 1 Interfaces
94
+
95
+ <details open>
96
+ <summary><strong>Python API</strong></summary>
97
+
98
+ <br>
99
+
100
+ ```python
101
+ import scitex_git as sxg
102
+
103
+ # Clone / init
104
+ sxg.clone_repo(url, dest_dir)
105
+ sxg.git_init(repo_path)
106
+
107
+ # Add / commit
108
+ sxg.git_add_all(repo_path)
109
+ sxg.git_commit(repo_path, message="…")
110
+
111
+ # Branch
112
+ sxg.git_checkout_new_branch(repo_path, branch_name)
113
+ sxg.git_branch_rename(repo_path, old, new)
114
+ sxg.setup_branches(repo_path, template_name)
115
+
116
+ # Repo init / discovery
117
+ sxg.init_git_repo(project_dir, git_strategy="parent")
118
+ sxg.find_parent_git(project_dir)
119
+ sxg.create_child_git(project_dir)
120
+ sxg.remove_child_git(project_dir)
121
+
122
+ # Remote
123
+ sxg.get_remote_url(repo_path)
124
+ sxg.is_cloned_from(repo_path, url)
125
+ sxg.ls_remote(url)
126
+ sxg.get_head_hash(repo_path)
127
+
128
+ # Retry decorator
129
+ @sxg.git_retry(max_attempts=3)
130
+ def maybe_flaky_operation(): ...
131
+ ```
132
+
133
+ </details>
134
+
135
+ ## Demo
136
+
137
+ ```mermaid
138
+ flowchart LR
139
+ A["scitex_git.clone_repo<br/>(url, dest)"] --> B["@git_retry<br/>(transient errors)"]
140
+ B --> C["repo on disk"]
141
+ C --> D["git_add_all + git_commit"]
142
+ D --> E["checkout_new_branch<br/>+ branch_rename"]
143
+ E --> F["get_remote_url /<br/>get_head_hash"]
144
+ ```
145
+
146
+ ```python
147
+ >>> import scitex_git as sxg
148
+ >>> sxg.clone_repo("https://github.com/foo/bar", "./bar")
149
+ >>> sxg.git_add_all("./bar")
150
+ >>> sxg.git_commit("./bar", message="initial")
151
+ ```
152
+
153
+ ## Quick Start
154
+
155
+ ```python
156
+ import scitex_git as sxg
157
+
158
+ sxg.clone_repo("https://github.com/foo/bar", "./bar")
159
+ sxg.git_add_all("./bar")
160
+ sxg.git_commit("./bar", message="initial")
161
+ ```
162
+
163
+ ## Status
164
+
165
+ Standalone fork of `scitex.git`. `scitex.logging.getLogger` is replaced by stdlib
166
+ `logging.getLogger`; the `scitex.sh.sh` shell wrapper is replaced by a tiny
167
+ ~70-LOC `_vendor_sh.py` that supports just the call-shape used here. The
168
+ optional `scitex.writer.verify_tree_structure` validation step in
169
+ `create_child_git` is gated behind a `try/except` so it only runs when
170
+ `scitex-writer` is installed.
171
+
172
+ The umbrella package's `scitex.git` import path is preserved via a
173
+ `sys.modules`-alias bridge so existing code continues to work.
174
+
175
+ ## Part of SciTeX
176
+
177
+ `scitex-git` is part of [**SciTeX**](https://scitex.ai). Install via
178
+ the umbrella with `pip install scitex[git]` to use as
179
+ `scitex.git` (Python) or `scitex git ...` (CLI).
180
+
181
+ >Four Freedoms for Research
182
+ >
183
+ >0. The freedom to **run** your research anywhere — your machine, your terms.
184
+ >1. The freedom to **study** how every step works — from raw data to final manuscript.
185
+ >2. The freedom to **redistribute** your workflows, not just your papers.
186
+ >3. The freedom to **modify** any module and share improvements with the community.
187
+ >
188
+ >AGPL-3.0 — because we believe research infrastructure deserves the same freedoms as the software it runs on.
189
+
190
+ ## License
191
+
192
+ AGPL-3.0-only (see [LICENSE](./LICENSE)).
193
+
194
+ ---
195
+
196
+ <p align="center">
197
+ <a href="https://scitex.ai" target="_blank"><img src="docs/scitex-icon-navy-inverted.png" alt="SciTeX" width="40"/></a>
198
+ </p>
@@ -0,0 +1,160 @@
1
+ # scitex-git
2
+
3
+ <p align="center">
4
+ <a href="https://scitex.ai">
5
+ <img src="docs/scitex-logo-blue-cropped.png" alt="SciTeX" width="400">
6
+ </a>
7
+ </p>
8
+
9
+ <p align="center"><b>Git operations and utilities — clone, init, branch, remote, retry decorator.</b></p>
10
+
11
+ <p align="center">
12
+ <a href="https://scitex-git.readthedocs.io/">Full Documentation</a> · <code>pip install scitex-git</code>
13
+ </p>
14
+
15
+ <!-- scitex-badges:start -->
16
+ <p align="center">
17
+ <a href="https://pypi.org/project/scitex-git/"><img src="https://img.shields.io/pypi/v/scitex-git.svg" alt="PyPI"></a>
18
+ <a href="https://pypi.org/project/scitex-git/"><img src="https://img.shields.io/pypi/pyversions/scitex-git.svg" alt="Python"></a>
19
+ <a href="https://github.com/ywatanabe1989/scitex-git/actions/workflows/test.yml"><img src="https://github.com/ywatanabe1989/scitex-git/actions/workflows/test.yml/badge.svg" alt="Tests"></a>
20
+ <a href="https://github.com/ywatanabe1989/scitex-git/actions/workflows/install-test.yml"><img src="https://github.com/ywatanabe1989/scitex-git/actions/workflows/install-test.yml/badge.svg" alt="Install Test"></a>
21
+ <a href="https://codecov.io/gh/ywatanabe1989/scitex-git"><img src="https://codecov.io/gh/ywatanabe1989/scitex-git/graph/badge.svg" alt="Coverage"></a>
22
+ <a href="https://scitex-git.readthedocs.io/en/latest/"><img src="https://readthedocs.org/projects/scitex-git/badge/?version=latest" alt="Docs"></a>
23
+ <a href="https://www.gnu.org/licenses/agpl-3.0"><img src="https://img.shields.io/badge/license-AGPL_v3-blue.svg" alt="License: AGPL v3"></a>
24
+ </p>
25
+ <!-- scitex-badges:end -->
26
+
27
+ ---
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ pip install scitex-git
33
+ ```
34
+
35
+ ## Architecture
36
+
37
+ ```
38
+ scitex_git/
39
+ ├── _clone.py ← clone_repo, ls_remote, get_remote_url
40
+ ├── _init.py ← git_init, init_git_repo, find_parent_git
41
+ ├── _commit.py ← git_add_all, git_commit
42
+ ├── _branch.py ← checkout_new_branch, branch_rename, setup_branches
43
+ ├── _remote.py ← remote-URL helpers, head-hash queries
44
+ ├── _retry.py ← @git_retry decorator (transient-error backoff)
45
+ ├── _validation.py ← repo-state guards
46
+ ├── _workflow.py ← high-level multi-step flows
47
+ ├── _vendor_sh.py ← ~70-LOC subprocess wrapper (replaces scitex.sh)
48
+ └── _skills/ ← agent-facing skill pages
49
+ ```
50
+
51
+ Pure-stdlib core. `_vendor_sh.py` is intentionally tiny so the package
52
+ has no `scitex.*` runtime dependency. The umbrella `scitex.git` import
53
+ resolves through a `sys.modules` bridge.
54
+
55
+ ## 1 Interfaces
56
+
57
+ <details open>
58
+ <summary><strong>Python API</strong></summary>
59
+
60
+ <br>
61
+
62
+ ```python
63
+ import scitex_git as sxg
64
+
65
+ # Clone / init
66
+ sxg.clone_repo(url, dest_dir)
67
+ sxg.git_init(repo_path)
68
+
69
+ # Add / commit
70
+ sxg.git_add_all(repo_path)
71
+ sxg.git_commit(repo_path, message="…")
72
+
73
+ # Branch
74
+ sxg.git_checkout_new_branch(repo_path, branch_name)
75
+ sxg.git_branch_rename(repo_path, old, new)
76
+ sxg.setup_branches(repo_path, template_name)
77
+
78
+ # Repo init / discovery
79
+ sxg.init_git_repo(project_dir, git_strategy="parent")
80
+ sxg.find_parent_git(project_dir)
81
+ sxg.create_child_git(project_dir)
82
+ sxg.remove_child_git(project_dir)
83
+
84
+ # Remote
85
+ sxg.get_remote_url(repo_path)
86
+ sxg.is_cloned_from(repo_path, url)
87
+ sxg.ls_remote(url)
88
+ sxg.get_head_hash(repo_path)
89
+
90
+ # Retry decorator
91
+ @sxg.git_retry(max_attempts=3)
92
+ def maybe_flaky_operation(): ...
93
+ ```
94
+
95
+ </details>
96
+
97
+ ## Demo
98
+
99
+ ```mermaid
100
+ flowchart LR
101
+ A["scitex_git.clone_repo<br/>(url, dest)"] --> B["@git_retry<br/>(transient errors)"]
102
+ B --> C["repo on disk"]
103
+ C --> D["git_add_all + git_commit"]
104
+ D --> E["checkout_new_branch<br/>+ branch_rename"]
105
+ E --> F["get_remote_url /<br/>get_head_hash"]
106
+ ```
107
+
108
+ ```python
109
+ >>> import scitex_git as sxg
110
+ >>> sxg.clone_repo("https://github.com/foo/bar", "./bar")
111
+ >>> sxg.git_add_all("./bar")
112
+ >>> sxg.git_commit("./bar", message="initial")
113
+ ```
114
+
115
+ ## Quick Start
116
+
117
+ ```python
118
+ import scitex_git as sxg
119
+
120
+ sxg.clone_repo("https://github.com/foo/bar", "./bar")
121
+ sxg.git_add_all("./bar")
122
+ sxg.git_commit("./bar", message="initial")
123
+ ```
124
+
125
+ ## Status
126
+
127
+ Standalone fork of `scitex.git`. `scitex.logging.getLogger` is replaced by stdlib
128
+ `logging.getLogger`; the `scitex.sh.sh` shell wrapper is replaced by a tiny
129
+ ~70-LOC `_vendor_sh.py` that supports just the call-shape used here. The
130
+ optional `scitex.writer.verify_tree_structure` validation step in
131
+ `create_child_git` is gated behind a `try/except` so it only runs when
132
+ `scitex-writer` is installed.
133
+
134
+ The umbrella package's `scitex.git` import path is preserved via a
135
+ `sys.modules`-alias bridge so existing code continues to work.
136
+
137
+ ## Part of SciTeX
138
+
139
+ `scitex-git` is part of [**SciTeX**](https://scitex.ai). Install via
140
+ the umbrella with `pip install scitex[git]` to use as
141
+ `scitex.git` (Python) or `scitex git ...` (CLI).
142
+
143
+ >Four Freedoms for Research
144
+ >
145
+ >0. The freedom to **run** your research anywhere — your machine, your terms.
146
+ >1. The freedom to **study** how every step works — from raw data to final manuscript.
147
+ >2. The freedom to **redistribute** your workflows, not just your papers.
148
+ >3. The freedom to **modify** any module and share improvements with the community.
149
+ >
150
+ >AGPL-3.0 — because we believe research infrastructure deserves the same freedoms as the software it runs on.
151
+
152
+ ## License
153
+
154
+ AGPL-3.0-only (see [LICENSE](./LICENSE)).
155
+
156
+ ---
157
+
158
+ <p align="center">
159
+ <a href="https://scitex.ai" target="_blank"><img src="docs/scitex-icon-navy-inverted.png" alt="SciTeX" width="40"/></a>
160
+ </p>
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "scitex-git"
7
- version = "0.1.2"
8
- description = "Git operations and utilities (clone, branch, commit, retry, remote helpers) — standalone module from the SciTeX ecosystem"
7
+ version = "0.2.0"
8
+ description = "Git + GitHub Actions utilities (clone, branch, commit, retry, remote helpers, gh secrets/variables with SHA256 sidecar) — standalone module from the SciTeX ecosystem"
9
9
  readme = "README.md"
10
10
  license = "AGPL-3.0-only"
11
11
  requires-python = ">=3.9"
@@ -31,6 +31,7 @@ dev = [
31
31
  "pytest",
32
32
  "pytest-cov",
33
33
  "ruff",
34
+ "scitex-dev>=0.11.5",
34
35
  ]
35
36
  docs = [
36
37
  "sphinx>=7.0",
@@ -3,8 +3,12 @@
3
3
 
4
4
  """scitex-git — git operations and utilities (extracted from SciTeX)."""
5
5
 
6
+ from __future__ import annotations
7
+
6
8
  try:
7
- from importlib.metadata import version as _v, PackageNotFoundError
9
+ from importlib.metadata import PackageNotFoundError
10
+ from importlib.metadata import version as _v
11
+
8
12
  try:
9
13
  __version__ = _v("scitex-git")
10
14
  except PackageNotFoundError:
@@ -15,12 +19,24 @@ except ImportError: # pragma: no cover — only on ancient Pythons
15
19
  from ._branch import git_branch_rename, git_checkout_new_branch
16
20
  from ._clone import clone_repo, git_init
17
21
  from ._commit import git_add_all, git_commit
22
+ from ._gh_secrets import (
23
+ GhSecretError,
24
+ format_age,
25
+ get_secret_metadata,
26
+ get_variable,
27
+ list_secrets,
28
+ set_secret,
29
+ set_secret_with_sha_sidecar,
30
+ set_variable,
31
+ sha256_hex,
32
+ )
18
33
  from ._init import create_child_git, find_parent_git, init_git_repo, remove_child_git
19
34
  from ._remote import get_head_hash, get_remote_url, is_cloned_from, ls_remote
20
35
  from ._retry import git_retry
21
36
  from ._workflow import setup_branches
22
37
 
23
38
  __all__ = [
39
+ "__version__",
24
40
  "init_git_repo",
25
41
  "find_parent_git",
26
42
  "create_child_git",
@@ -37,6 +53,16 @@ __all__ = [
37
53
  "get_head_hash",
38
54
  "setup_branches",
39
55
  "git_retry",
56
+ # GitHub Actions secrets / variables
57
+ "GhSecretError",
58
+ "set_secret",
59
+ "list_secrets",
60
+ "get_secret_metadata",
61
+ "set_variable",
62
+ "get_variable",
63
+ "set_secret_with_sha_sidecar",
64
+ "sha256_hex",
65
+ "format_age",
40
66
  ]
41
67
 
42
68
  # EOF
@@ -0,0 +1,215 @@
1
+ #!/usr/bin/env python3
2
+ # File: /home/ywatanabe/proj/scitex-git/src/scitex_git/_gh_secrets.py
3
+
4
+ """GitHub Actions secrets / variables — thin wrappers around ``gh`` CLI.
5
+
6
+ The GitHub Actions REST API (and ``gh secret``) is **write-only** for
7
+ secret values: you can list names + ``updated_at``, but never read a
8
+ value back. This module bundles the everyday read/write primitives any
9
+ "rotate the CI key" workflow needs, plus a SHA256 sidecar pattern to
10
+ detect drift between local and remote without exposing the secret:
11
+
12
+ * :func:`set_secret` / :func:`list_secrets` /
13
+ :func:`get_secret_metadata` — direct ``gh secret`` wrappers.
14
+ * :func:`set_variable` / :func:`get_variable` — ``gh variable``
15
+ wrappers (variables are world-readable; suitable for non-sensitive
16
+ fingerprints, never for token material).
17
+ * :func:`set_secret_with_sha_sidecar` — pushes the secret AND a
18
+ SHA256 fingerprint to a same-name ``…_SHA256`` repo variable so a
19
+ later ``get_variable`` call lets the operator tell whether the
20
+ GitHub-side secret matches the local one. Hash is irreversible.
21
+ * :func:`format_age` — render an ISO-8601 ``updated_at`` as a
22
+ human-readable single-unit age (``15min`` / ``2.4d``) for CLI
23
+ reports.
24
+ * :func:`sha256_hex` — same hashing function the sidecar uses, so
25
+ callers can compute a local fingerprint to compare against
26
+ :func:`get_variable`.
27
+
28
+ The ``gh`` CLI must be authenticated. Each helper raises
29
+ :class:`GhSecretError` on subprocess failure with the underlying stderr
30
+ attached, so callers can surface a clean message rather than a stack
31
+ trace.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import hashlib
37
+ import json
38
+ import subprocess
39
+ from datetime import datetime, timezone
40
+ from logging import getLogger
41
+
42
+ logger = getLogger(__name__)
43
+
44
+ __all__ = [
45
+ "GhSecretError",
46
+ "set_secret",
47
+ "list_secrets",
48
+ "get_secret_metadata",
49
+ "set_variable",
50
+ "get_variable",
51
+ "set_secret_with_sha_sidecar",
52
+ "format_age",
53
+ "sha256_hex",
54
+ ]
55
+
56
+
57
+ class GhSecretError(RuntimeError):
58
+ """Raised when a ``gh`` subprocess returns non-zero."""
59
+
60
+
61
+ def _run(argv: list[str], *, stdin: str | None = None) -> str:
62
+ """Run ``argv`` and return stdout. Raise :class:`GhSecretError` on failure."""
63
+ proc = subprocess.run(
64
+ argv,
65
+ input=stdin,
66
+ text=True,
67
+ capture_output=True,
68
+ )
69
+ if proc.returncode != 0:
70
+ msg = proc.stderr.strip() or proc.stdout.strip() or "unknown error"
71
+ raise GhSecretError(f"{' '.join(argv[:3])}…: {msg}")
72
+ return proc.stdout
73
+
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Secrets
77
+ # ---------------------------------------------------------------------------
78
+
79
+
80
+ def set_secret(repo: str, name: str, value: str) -> None:
81
+ """Push ``value`` into the Actions secret ``name`` for ``repo``.
82
+
83
+ ``repo`` follows the ``owner/repo`` form. Idempotent — creates if
84
+ missing, updates otherwise.
85
+ """
86
+ _run(["gh", "secret", "set", name, "-R", repo, "--body", "-"], stdin=value)
87
+
88
+
89
+ def list_secrets(repo: str) -> dict[str, str]:
90
+ """Return ``{secret_name: updated_at_iso}`` for the repo.
91
+
92
+ Pagination is honoured (``--paginate``) so this scales beyond
93
+ GitHub's 100-secret default page size.
94
+ """
95
+ raw = _run(["gh", "api", f"repos/{repo}/actions/secrets", "--paginate"])
96
+ payload = json.loads(raw)
97
+ return {s["name"]: s["updated_at"] for s in payload.get("secrets", [])}
98
+
99
+
100
+ def get_secret_metadata(repo: str, name: str) -> dict | None:
101
+ """Return the secret's metadata dict (name / created_at / updated_at), or None.
102
+
103
+ GitHub never exposes the value itself — that's the whole point of
104
+ Actions secrets. Use :func:`get_variable` against a SHA sidecar
105
+ (see :func:`set_secret_with_sha_sidecar`) if you need to detect
106
+ value drift.
107
+ """
108
+ proc = subprocess.run(
109
+ ["gh", "api", f"repos/{repo}/actions/secrets/{name}"],
110
+ text=True,
111
+ capture_output=True,
112
+ )
113
+ if proc.returncode != 0:
114
+ return None
115
+ try:
116
+ return json.loads(proc.stdout)
117
+ except json.JSONDecodeError:
118
+ return None
119
+
120
+
121
+ # ---------------------------------------------------------------------------
122
+ # Variables (world-readable)
123
+ # ---------------------------------------------------------------------------
124
+
125
+
126
+ def set_variable(repo: str, name: str, value: str) -> None:
127
+ """Create-or-update an Actions variable. Idempotent.
128
+
129
+ Variables are visible to anyone with repo read access. Use this
130
+ for non-sensitive metadata (e.g. SHA256 fingerprints of secrets,
131
+ feature flags). NEVER store token material here.
132
+ """
133
+ _run(["gh", "variable", "set", name, "-R", repo, "--body", value])
134
+
135
+
136
+ def get_variable(repo: str, name: str) -> str | None:
137
+ """Return the variable's value, or None if absent."""
138
+ proc = subprocess.run(
139
+ ["gh", "api", f"repos/{repo}/actions/variables/{name}"],
140
+ text=True,
141
+ capture_output=True,
142
+ )
143
+ if proc.returncode != 0:
144
+ return None
145
+ try:
146
+ return json.loads(proc.stdout).get("value")
147
+ except json.JSONDecodeError:
148
+ return None
149
+
150
+
151
+ # ---------------------------------------------------------------------------
152
+ # SHA256 sidecar — secret-drift detection without exposing the value
153
+ # ---------------------------------------------------------------------------
154
+
155
+
156
+ def sha256_hex(value: str) -> str:
157
+ """Return the SHA256 hex digest of ``value`` (UTF-8)."""
158
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()
159
+
160
+
161
+ def set_secret_with_sha_sidecar(
162
+ repo: str, name: str, value: str, *, sidecar_suffix: str = "_SHA256"
163
+ ) -> str:
164
+ """Push the secret AND its SHA256 fingerprint as a public variable.
165
+
166
+ Returns the SHA256 hex digest so the caller can show it in CLI
167
+ output. The sidecar variable is named ``{name}{sidecar_suffix}`` and
168
+ holds the irreversible hash; later
169
+ ``get_variable(repo, f"{name}{sidecar_suffix}")`` lets you tell
170
+ whether the GitHub-side secret matches a local value (compare with
171
+ ``sha256_hex(local_value)``).
172
+
173
+ The hash itself is not sensitive — it cannot be reversed to the
174
+ original token without a brute-force search of the OAuth/api-key
175
+ namespace, which is computationally infeasible. It IS visible to
176
+ repo readers, so don't use the sidecar for tokens whose mere
177
+ existence is sensitive (the hash leaks "this token was rotated at
178
+ {time} to a value with hash {h}" but never the value).
179
+ """
180
+ digest = sha256_hex(value)
181
+ set_secret(repo, name, value)
182
+ set_variable(repo, f"{name}{sidecar_suffix}", digest)
183
+ return digest
184
+
185
+
186
+ # ---------------------------------------------------------------------------
187
+ # Display helpers
188
+ # ---------------------------------------------------------------------------
189
+
190
+
191
+ def format_age(updated_iso: str | None) -> str:
192
+ """Render an ISO-8601 timestamp as a single-unit human age.
193
+
194
+ Picks the largest unit that gives a readable number: seconds for
195
+ very fresh rotations, then minutes, hours, days. Mirrors the
196
+ ``git relative_date`` style — a single value + unit, no compound
197
+ "1d 4h" form. Returns ``"?"`` for ``None`` input.
198
+
199
+ >>> format_age(None)
200
+ '?'
201
+ """
202
+ if not updated_iso:
203
+ return "?"
204
+ dt = datetime.fromisoformat(updated_iso.replace("Z", "+00:00"))
205
+ seconds = (datetime.now(timezone.utc) - dt).total_seconds()
206
+ if seconds < 60:
207
+ return f"{int(seconds)}s"
208
+ if seconds < 3600:
209
+ return f"{int(seconds / 60)}min"
210
+ if seconds < 86400:
211
+ return f"{seconds / 3600:.1f}h"
212
+ return f"{seconds / 86400:.1f}d"
213
+
214
+
215
+ # EOF