rocky-workbench 0.3.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.
@@ -0,0 +1,253 @@
1
+ Metadata-Version: 2.5
2
+ Name: rocky-workbench
3
+ Version: 0.3.0
4
+ Summary: Local repo workbench that switches to target branches and fast-forwards only
5
+ Project-URL: Homepage, https://github.com/linyu19872008/rocky-workbench
6
+ Project-URL: Changelog, https://github.com/linyu19872008/rocky-workbench/blob/main/CHANGELOG.md
7
+ Author: linyu19872008
8
+ License: MIT License
9
+
10
+ Copyright (c) 2026 linyu19872008
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all
20
+ copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE.
29
+ License-File: LICENSE
30
+ Keywords: cli,git,local,repo,workbench
31
+ Classifier: Environment :: Console
32
+ Classifier: License :: OSI Approved :: MIT License
33
+ Classifier: Operating System :: MacOS
34
+ Classifier: Operating System :: POSIX :: Linux
35
+ Classifier: Programming Language :: Python :: 3 :: Only
36
+ Classifier: Programming Language :: Python :: 3.11
37
+ Classifier: Programming Language :: Python :: 3.12
38
+ Classifier: Programming Language :: Python :: 3.13
39
+ Classifier: Programming Language :: Python :: 3.14
40
+ Classifier: Topic :: Software Development :: Version Control :: Git
41
+ Requires-Python: >=3.11
42
+ Description-Content-Type: text/markdown
43
+
44
+ <div align="center">
45
+ <img src="workbench/web/icon.png" alt="Rocky Workbench" width="120">
46
+ <h1>Rocky Workbench</h1>
47
+ <p>
48
+ <a href="https://github.com/linyu19872008/rocky-workbench/actions/workflows/ci.yml"><img src="https://github.com/linyu19872008/rocky-workbench/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
49
+ <a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License: MIT"></a>
50
+ </p>
51
+ <p><strong>English</strong> | <a href="README.zh-CN.md">简体中文</a></p>
52
+ </div>
53
+
54
+ ## What it is
55
+
56
+ A local workbench that checks out each enabled repo to its target branch and **fast-forwards only**. The UI and CLI share one SQLite catalog.
57
+
58
+ - **Does:** manage repos by directory, check whether they are behind, fast-forward sync, pause or remove catalog rows (never deletes on-disk repos)
59
+ - **Does not:** force-push, auto-merge diverged histories, touch repos outside the catalog, overwrite dirty worktrees
60
+ - The server listens on localhost only (`127.0.0.1` / `localhost` / `::1`)
61
+ - Repository name: `rocky-workbench`. Python package entrypoint: `python3 -m workbench …`
62
+ - **UI** supports English and Simplified Chinese (browser default, then your choice). **CLI, API responses, and server logs are English-only.**
63
+
64
+ ## Quick start
65
+
66
+ **Requirements**
67
+
68
+ - Python 3.11+, standard library only
69
+ - `git` installed locally; remote name `origin`
70
+ - **Choose folder…** uses macOS `osascript` (you can also type a path)
71
+
72
+ Install from PyPI:
73
+
74
+ ```bash
75
+ pipx install rocky-workbench
76
+ rocky-workbench serve
77
+ ```
78
+
79
+ Or run from a checkout without installing:
80
+
81
+ ```bash
82
+ python3 -m workbench serve
83
+ ```
84
+
85
+ Open http://127.0.0.1:8765/ (the terminal prints the real URL). Another port: `python3 -m workbench serve --port 8766`. Stop with Ctrl+C.
86
+
87
+ On first launch the catalog is empty:
88
+
89
+ 1. Click **Add** and pick a code directory (system folder dialog or typed path).
90
+ 2. Select repos, set the target branch (**Keep current** or **Specific branch**), choose enabled or not, then **Add repos**.
91
+ 3. Click **Check for updates**. By default it only reads local `origin/*`. To talk to the remote, open the adjacent menu and choose **Also fetch remote**.
92
+
93
+ Target-branch suggestions come from local branches and existing `origin/*` (no network). You can type a name. **Keep current** stores the target as `stay`.
94
+
95
+ ## Using the UI
96
+
97
+ The sidebar currently has one item: **Repo sync**. Bottom-left: theme (system / light / dark), language (English / Simplified Chinese), and the data-file path.
98
+
99
+ **Model:** directory tabs at the top; only one directory is active. Check, sync, filters, and selection apply to the **current directory** only. Under the title: counts for repos, aligned, needs attention, and last check time.
100
+
101
+ | Action | Scope |
102
+ |---|---|
103
+ | **Check for updates** | Enabled repos in the current directory; local-only by default; menu can **Also fetch remote** |
104
+ | **Sync N** | Repos in the current directory that need work (failed / dirty / will switch / behind / unchecked) |
105
+ | **Sync selected N** | Checked rows |
106
+ | Row **Check / Sync / Retry** | That row |
107
+ | Search and status filters | Display and selection only; does not change check/sync scope |
108
+
109
+ **Rules**
110
+
111
+ - Groups: **Needs attention**, **Aligned**, **Disabled**. Needs attention first; aligned is collapsed by default.
112
+ - If a sync would switch branches, hit dirty trees, likely fail, or run before any check, the UI lists targets and reasons and asks to confirm. If never checked, it runs a local check first. Otherwise sync starts immediately.
113
+ - Afterward a summary card shows updated / up to date / skipped / failed; failures can be retried.
114
+ - Click the target branch to search or type a new name. Enter only fills the input; **Save** writes the catalog.
115
+ - Disabled repos skip check/sync but keep their target; re-enable under **Disabled**.
116
+ - **Remove from workbench** deletes the catalog row only, not the on-disk repo; disable first.
117
+ - Check, sync, and catalog edits run one at a time. Conflicting actions are disabled; scrolling, filtering, and copying paths still work.
118
+
119
+ ## CLI
120
+
121
+ Run from the project root with `python3 -m workbench`, or use the installed `rocky-workbench` entry point. Put `--db` before the subcommand; other flags after it.
122
+
123
+ | Command | Purpose |
124
+ |---|---|
125
+ | `python3 -m workbench status` | Status of enabled repos vs target (fetches by default) |
126
+ | `python3 -m workbench status --no-fetch` | No remote access; use local `origin` refs only |
127
+ | `python3 -m workbench sync` | Check out the target branch and fast-forward to `origin/<target>` |
128
+ | `python3 -m workbench serve` | Open the local UI |
129
+ | `python3 -m workbench --db /path/to/workbench.db status` | Use another catalog file |
130
+
131
+ ```bash
132
+ python3 -m workbench status api-mall-v2
133
+ python3 -m workbench status --jobs 3 # default concurrency is 6
134
+ python3 -m workbench sync api-mall-v2 vue-manage
135
+ ```
136
+
137
+ **CLI vs UI (easy to miss)**
138
+
139
+ - CLI with no repo names: **all enabled** repos in the catalog, **across directories**.
140
+ - UI check/sync: **current directory tab** only.
141
+ - Both only touch enabled rows. Add / change branch / enable / disable / remove are UI-only; the CLI has no matching subcommands.
142
+
143
+ From another directory:
144
+
145
+ ```bash
146
+ python3 /path/to/rocky-workbench/workbench/__main__.py status
147
+ ```
148
+
149
+ ## Sync rules & safety
150
+
151
+ Sync semantics live in `workbench/repos/git.py` and are shared by UI and CLI.
152
+
153
+ When it stops:
154
+
155
+ - Dirty worktree, or merge / rebase / cherry-pick / bisect in progress → **skipped**; branch and worktree unchanged
156
+ - Remote has no catalog branch → **missing branch**
157
+ - Current branch diverged from remote; fast-forward fails → stay on the old commit
158
+ - Local branch you would check out has diverged from remote → stay on the current branch
159
+ - Directory missing or no `.git` → **failed**
160
+
161
+ Other rules:
162
+
163
+ - `stay`: keep the current checkout; fast-forward only; detached HEAD fails
164
+ - After a successful fast-forward, if the local branch has no upstream, set it to `origin/<target>`
165
+ - A single `git` call timing out past 180s counts as failed; `GIT_TERMINAL_PROMPT=0` so credentials are never prompted interactively
166
+
167
+ `sync` summary buckets: up to date, updated, switched, skipped, missing branch, failed.
168
+
169
+ ## Catalog & data
170
+
171
+ The default catalog depends on how the app runs:
172
+
173
+ - source checkout: `data/workbench.db` (gitignored, including `-wal` / `-shm`)
174
+ - installed package: the platform user data directory
175
+ (`~/Library/Application Support/rocky-workbench/` on macOS,
176
+ `$XDG_DATA_HOME/rocky-workbench/` or `~/.local/share/rocky-workbench/` on Linux,
177
+ `%APPDATA%\rocky-workbench\` on Windows)
178
+
179
+ Override it with `--db` or `ROCKY_WORKBENCH_DB`. The directory is created as needed. On every open, pending schema migrations under `workbench/migrations/` are applied automatically (forward-only; there is no separate `migrate` command).
180
+
181
+ If a legacy `workbench.db` still sits at the repo root and `data/` has none, startup moves it (never overwrites an existing `data/` file). An explicit `--db` path is never moved.
182
+
183
+ | Table | Contents |
184
+ |---|---|
185
+ | `directories` | Code roots; path unique |
186
+ | `repos` | Directory, repo name, target branch, enabled, order; repo name unique per directory |
187
+ | `schema_migrations` | Applied migration versions (managed by the migrator) |
188
+
189
+ Schema changes belong in new numbered files such as `workbench/migrations/002_….sql`. Do not edit migration files that have already shipped.
190
+
191
+ Repo path is `directory / name`. On add, that path must exist and contain `.git`.
192
+
193
+ If the same repo name is enabled in more than one directory, CLI name selection and UI check/sync stop with an error. Branch / enable / disable / remove use row ids and can be handled separately.
194
+
195
+ ## Exit codes
196
+
197
+ Primarily for `sync` (`status` returns 0 when the catalog is valid; a temporarily unreachable remote is noted on that repo’s line).
198
+
199
+ | Code | Meaning |
200
+ |---|---|
201
+ | 0 | Finished. Skipping dirty repos still counts as success |
202
+ | 1 | At least one repo failed, or the remote lacks the target branch |
203
+ | 2 | Bad catalog, or a named repo is not in the catalog; `--jobs` &lt; 1 is also 2 |
204
+
205
+ ## Development
206
+
207
+ Pushes and PRs to `main` run the suite on Python 3.11–3.14 (Ubuntu) and 3.13 (macOS), plus lint, repository checks, and a wheel install smoke test via GitHub Actions.
208
+
209
+ ```bash
210
+ python3 -m unittest discover -s tests
211
+ python3 -m pip install -r requirements-dev.txt
212
+ python3 -m build
213
+ ```
214
+
215
+ **Where to change what**
216
+
217
+ | Change | Location |
218
+ |---|---|
219
+ | Skip / checkout / fast-forward semantics | `workbench/repos/git.py`, plus `tests/test_git_safety.py` |
220
+ | HTTP routes, static files, event streams | `workbench/server.py` |
221
+ | Selection, concurrency, UI payloads, folder picker | `workbench/repos/service.py` |
222
+ | SQLite read/write | `workbench/repos/store.py` |
223
+ | Schema migrations | `workbench/migrations/*.sql`, runner `workbench/repos/migrate.py` |
224
+ | Validation, `stay`, default db / legacy move | `workbench/repos/config_file.py` |
225
+ | CLI args, terminal output, exit codes | `workbench/cli.py` |
226
+ | Sidebar menus | `workbench/registry.py` |
227
+ | Shell (menus, theme, language, page loading) | `workbench/web/shell.js` |
228
+ | UI i18n | `workbench/web/i18n/` |
229
+ | UI primitives (modals, popovers, …) | `workbench/web/ui.js` |
230
+ | Repo sync page | `workbench/web/pages/repos.js` |
231
+ | Styles | `workbench/web/tokens.css`, `base.css`, `components.css` |
232
+
233
+ Entrypoint: `workbench/__main__.py` → `workbench.cli`. UI and CLI must keep the same sync outcomes.
234
+
235
+ **Add a sidebar feature**
236
+
237
+ 1. Add an item to `MENUS` in `workbench/registry.py`: `id`, `label`, `href` (`#/` + same id).
238
+ 2. Add `workbench/web/pages/<id>.js` exporting `window.workbenchPages.<id> = { mount, unmount }`.
239
+ 3. Add routes in `workbench/server.py` if needed; keep non-repo logic out of `workbench/repos/`.
240
+
241
+ `docs/ux-overhaul-plan.md` is a historical UX write-up, not the current spec.
242
+
243
+ When you change behavior described here, update **both** `README.md` and `README.zh-CN.md`. See also [CONTRIBUTING.md](CONTRIBUTING.md), [docs/release.md](docs/release.md), and [SECURITY.md](SECURITY.md).
244
+
245
+ ## Language
246
+
247
+ - Web UI: `en` and `zh-CN`. Default follows `navigator.language` / `navigator.languages` (`zh*` → Chinese, otherwise English). Choosing a language stores `workbench-locale` in `localStorage`.
248
+ - Use the globe control next to the theme button to switch.
249
+ - CLI, HTTP JSON/SSE payloads, and server logs stay English. The UI maps stable `kind` / `detail_code` values to the active locale.
250
+
251
+ ## License
252
+
253
+ This project is licensed under the MIT License. See [LICENSE](LICENSE).
@@ -0,0 +1,27 @@
1
+ workbench/__init__.py,sha256=FkbqO6e5_QITae01QyDJ2LFloXyZ3jCxSfCsrxTm2LE,83
2
+ workbench/__main__.py,sha256=yGhhe7qKVKMTK33HcFSsubhAyUvUmyZ7Z9OknlH1ENI,142
3
+ workbench/cli.py,sha256=krApvcLptRU-zfJOILMtxrz5QznfA3tuSK41a2hYvnc,6890
4
+ workbench/registry.py,sha256=cDicr4nK4-yUUQYIgOckfUr-8HWryhiuGZN5oIVggc4,213
5
+ workbench/server.py,sha256=5Y1nG-4-0DH6HTEEDRxCPQBhRstJk5v_OHe89Wb6rXk,14535
6
+ workbench/migrations/001_baseline.sql,sha256=frIo1vTfrF-D9QbPZFq_KYa2hV7-XF1VzyWV7pDT0Nc,524
7
+ workbench/repos/__init__.py,sha256=veU9khkULaNBqUBoJG1AfJaaaTLhIEsALyz_eswhq_Q,76
8
+ workbench/repos/config_file.py,sha256=gqmaiyhD8djB5LFFOzEOz1qtNpKLRErSs27GFo7gdT4,3533
9
+ workbench/repos/git.py,sha256=MtDf3PQHC52s6HFgfClPtCEAZ5ST3DL98cCk-VNK3lA,15983
10
+ workbench/repos/migrate.py,sha256=hb5LrD2OgYXXHZkzXelTBsVLMT_G2cQuku-00USHARI,3050
11
+ workbench/repos/service.py,sha256=RHoRAeR3FcVenQaUp37KbufgDtVYPu6H2I-TBMkj5Ic,10562
12
+ workbench/repos/store.py,sha256=e-WIe8iw3YcUrJsXbsZHo3PI-tpTKlAzk_RNTOiuE-s,6602
13
+ workbench/web/base.css,sha256=2hRfJFREwdB4wcolyvr8c8OU4eY3b6E-dRV0cvOm4UY,4271
14
+ workbench/web/components.css,sha256=fe5db-crlYGGzmBexSr8XnmeRlzE7qZsPFnTYc2XytU,33524
15
+ workbench/web/icon.png,sha256=LPh2ET2AWWG-lJunDSG7O-e3fj4PhA_OA5ruGnCewtI,187931
16
+ workbench/web/index.html,sha256=6mroXT5qgymdJKrHl_qooueaBdLx9A7il5npPvHWxEc,8526
17
+ workbench/web/shell.js,sha256=OElKqLl36KKfOp6zg2HZ674GVDLLJ7uLKGe2b5N5MF8,10955
18
+ workbench/web/tokens.css,sha256=bpEkZndcnOubM6p75TBuq7AtkIy-CvUWR8C_u0GiRUs,3121
19
+ workbench/web/ui.js,sha256=g6GIW4DQmoNKnxoTM44g-StFLUdcekctfsw3xEbYCKk,14174
20
+ workbench/web/i18n/i18n.js,sha256=uBgPvUz45BRuACxl6V-TiFe004bJVHLjk-6Dbk_jFUE,2659
21
+ workbench/web/i18n/locales.js,sha256=TdVEeM-f74LbqjDEUMXGSI-gkBddMx0WfBSdhjZqkoA,21998
22
+ workbench/web/pages/repos.js,sha256=YI65Xwe71kAdDPSnpnAWDmgBR5Uzd5XgCrDOYsK0HsE,87317
23
+ rocky_workbench-0.3.0.dist-info/METADATA,sha256=ySkb7QP_mmuYs_0SZ14XEebca9zEP-zlTK5fIVGr8eg,12711
24
+ rocky_workbench-0.3.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
25
+ rocky_workbench-0.3.0.dist-info/entry_points.txt,sha256=qA3aw-OV77Cp3qTZf4mOOv9TZ5sOEy831ncSztIcvLs,55
26
+ rocky_workbench-0.3.0.dist-info/licenses/LICENSE,sha256=jPklXwmzr1T0emdpqi21gPf7XfBLJEAe2iPDf-q6rJk,1070
27
+ rocky_workbench-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ rocky-workbench = workbench.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 linyu19872008
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
workbench/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Rocky Workbench. CLI and web share modules from here."""
2
+
3
+ __version__ = "0.3.0"
workbench/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Rocky Workbench commands. Run python3 -m workbench from the project directory."""
2
+
3
+ from workbench.cli import main
4
+
5
+ raise SystemExit(main())
workbench/cli.py ADDED
@@ -0,0 +1,166 @@
1
+ """CLI entry point. python3 -m workbench delegates here."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from workbench import __version__
10
+ from workbench.repos.config_file import ConfigError, adopt_legacy_db, default_db_path
11
+ from workbench.repos.git import Outcome, status_one, sync_one
12
+ from workbench.repos.service import DEFAULT_JOBS, KINDS, run_all, select_specs
13
+ from workbench.repos.store import ensure_ready, list_repos
14
+
15
+
16
+ def die(message: str, code: int = 2) -> None:
17
+ print(message, file=sys.stderr)
18
+ raise SystemExit(code)
19
+
20
+
21
+ def display_width(text: str) -> int:
22
+ width = 0
23
+ for char in text:
24
+ width += 2 if ord(char) > 0x2E80 else 1
25
+ return width
26
+
27
+
28
+ def pad(text: str, width: int) -> str:
29
+ gap = width - display_width(text)
30
+ if gap < 1:
31
+ return text + " "
32
+ return text + (" " * gap)
33
+
34
+
35
+ def print_status(results: list[Outcome]) -> None:
36
+ ordered = sorted(results, key=lambda outcome: outcome.spec.order)
37
+ index = 0
38
+ while index < len(ordered):
39
+ target = ordered[index].target or "unknown target"
40
+ run: list[Outcome] = []
41
+ while index < len(ordered) and (ordered[index].target or "unknown target") == target:
42
+ run.append(ordered[index])
43
+ index += 1
44
+ print(f"\n{target} {len(run)} repo(s)")
45
+ print(f" {pad('Repository', 26)}{pad('Current', 24)}Details")
46
+ for outcome in run:
47
+ print(f" {pad(outcome.spec.name, 26)}{pad(outcome.current, 24)}{outcome.detail}")
48
+ switch = sum(1 for outcome in results if outcome.will_switch)
49
+ skip = sum(1 for outcome in results if outcome.will_skip)
50
+ failed = sum(1 for outcome in results if outcome.kind == "failed")
51
+ print(
52
+ f"\n{len(results)} repo(s): {switch} will switch, "
53
+ f"{skip} sync skipped, {failed} inaccessible or misconfigured"
54
+ )
55
+
56
+
57
+ def print_sync_summary(results: list[Outcome]) -> None:
58
+ print()
59
+ counts: list[str] = []
60
+ for kind, label in KINDS:
61
+ items = sorted((outcome for outcome in results if outcome.kind == kind), key=lambda outcome: outcome.spec.name)
62
+ counts.append(f"{label} {len(items)}")
63
+ if not items:
64
+ continue
65
+ print(f"{label} ({len(items)})")
66
+ for outcome in items:
67
+ extra = f" {outcome.detail}" if outcome.detail else ""
68
+ print(f" {outcome.spec.name}{extra}")
69
+ print()
70
+ print(", ".join(counts))
71
+
72
+
73
+ def parse_args(argv: list[str]) -> argparse.Namespace:
74
+ parser = argparse.ArgumentParser(
75
+ prog="rocky-workbench",
76
+ description="Rocky Workbench: switch repos to target branches and fast-forward pull only.",
77
+ formatter_class=argparse.RawDescriptionHelpFormatter,
78
+ epilog=(
79
+ "Examples:\n"
80
+ " python3 -m workbench status\n"
81
+ " python3 -m workbench status api-mall-v2\n"
82
+ " python3 -m workbench status --no-fetch\n"
83
+ " python3 -m workbench sync\n"
84
+ " python3 -m workbench sync api-mall-v2 vue-manage\n"
85
+ " python3 -m workbench serve\n"
86
+ "\n"
87
+ "The Python package is still named workbench, so use python3 -m workbench.\n"
88
+ "Catalog defaults to data/workbench.db in a checkout, or the user data directory when installed.\n"
89
+ "Each row has its own target branch.\n"
90
+ "Set branch to stay to remain on the current branch and only fast-forward.\n"
91
+ "Repos with local changes or in-progress merge/rebase are skipped.\n"
92
+ "Diverged local and remote histories stop sync — no auto-merge or worktree overwrite."
93
+ ),
94
+ )
95
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
96
+ parser.add_argument(
97
+ "--db",
98
+ type=Path,
99
+ default=default_db_path(),
100
+ help="Catalog database (default: data/workbench.db in a checkout, user data dir when installed)",
101
+ )
102
+ sub = parser.add_subparsers(dest="command", required=True)
103
+
104
+ status = sub.add_parser("status", help="Show current and target branches without switching or merging")
105
+ status.add_argument("names", nargs="*", help="Repository names; omit for all enabled repos")
106
+ status.add_argument("--jobs", type=int, default=DEFAULT_JOBS, help=f"Parallel remote fetches (default {DEFAULT_JOBS})")
107
+ status.add_argument("--no-fetch", action="store_true", help="Skip remote; use local origin refs only")
108
+
109
+ sync = sub.add_parser("sync", help="Switch to target branch and fast-forward update")
110
+ sync.add_argument("names", nargs="*", help="Repository names; omit for all enabled repos")
111
+ sync.add_argument("--jobs", type=int, default=DEFAULT_JOBS, help=f"Parallel repos to process (default {DEFAULT_JOBS})")
112
+
113
+ serve = sub.add_parser("serve", help="Start local Rocky Workbench web UI")
114
+ serve.add_argument("--host", default="127.0.0.1", help="Bind address (localhost only by default)")
115
+ serve.add_argument("--port", type=int, default=8765, help="Port (default 8765)")
116
+ return parser.parse_args(argv)
117
+
118
+
119
+ def main(argv: list[str] | None = None) -> int:
120
+ args = parse_args(sys.argv[1:] if argv is None else argv)
121
+ adopt_legacy_db(args.db)
122
+ if getattr(args, "jobs", 1) < 1:
123
+ die("--jobs must be at least 1")
124
+ if args.command == "serve":
125
+ from workbench.server import serve
126
+
127
+ serve(args.host, args.port, args.db)
128
+ return 0
129
+
130
+ try:
131
+ ensure_ready(args.db)
132
+ specs = select_specs(list_repos(args.db, enabled_only=True), args.names)
133
+ except ConfigError as exc:
134
+ die(str(exc))
135
+
136
+ if args.command == "status":
137
+ scope = " (no fetch)" if args.no_fetch else ""
138
+ print(f"Checking {len(specs)} repo(s){scope}", flush=True)
139
+ progress = "quiet" if args.no_fetch else "status"
140
+ results = _run_cli(specs, args.jobs, lambda spec: status_one(spec, fetch=not args.no_fetch), progress)
141
+ print_status(results)
142
+ return 0
143
+
144
+ print(f"Syncing {len(specs)} repo(s), up to {args.jobs} in parallel", flush=True)
145
+ results = _run_cli(specs, args.jobs, sync_one, "sync")
146
+ print_sync_summary(results)
147
+ if any(outcome.kind in {"missing", "failed"} for outcome in results):
148
+ return 1
149
+ return 0
150
+
151
+
152
+ def _run_cli(specs, jobs: int, worker, progress: str) -> list[Outcome]:
153
+ total = len(specs)
154
+ done = 0
155
+
156
+ def on_result(outcome: Outcome) -> None:
157
+ nonlocal done
158
+ done += 1
159
+ if progress == "sync":
160
+ label = dict(KINDS).get(outcome.kind, "Failed")
161
+ suffix = f" {outcome.detail}" if outcome.detail else ""
162
+ print(f"{pad(label, 8)}{pad(outcome.spec.name, 26)}{suffix}", flush=True)
163
+ elif progress == "status":
164
+ print(f"[{done}/{total}] {outcome.spec.name}", flush=True)
165
+
166
+ return run_all(specs, jobs, worker, on_result if progress != "quiet" else None)
@@ -0,0 +1,18 @@
1
+ -- Baseline schema for Rocky Workbench catalog (version 1).
2
+ -- Safe on existing databases that already have these tables.
3
+
4
+ CREATE TABLE IF NOT EXISTS directories (
5
+ id INTEGER PRIMARY KEY,
6
+ path TEXT NOT NULL UNIQUE
7
+ );
8
+
9
+ CREATE TABLE IF NOT EXISTS repos (
10
+ id INTEGER PRIMARY KEY,
11
+ directory_id INTEGER NOT NULL REFERENCES directories(id),
12
+ name TEXT NOT NULL,
13
+ branch TEXT NOT NULL,
14
+ enabled INTEGER NOT NULL CHECK (enabled IN (0, 1)),
15
+ position INTEGER NOT NULL,
16
+ UNIQUE (directory_id, name)
17
+ );
18
+
workbench/registry.py ADDED
@@ -0,0 +1,11 @@
1
+ """Sidebar menus. Register new features here with their page script."""
2
+
3
+ from __future__ import annotations
4
+
5
+ MENUS = (
6
+ {
7
+ "id": "repos",
8
+ "label": "Repo sync",
9
+ "href": "#/repos",
10
+ },
11
+ )
@@ -0,0 +1 @@
1
+ """Repository sync: read catalog, inspect worktrees, fast-forward update."""
@@ -0,0 +1,124 @@
1
+ """Repository records. Target branch is stored on each row."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ STAY = "stay"
11
+ APP_DIR = "rocky-workbench"
12
+ DB_ENV = "ROCKY_WORKBENCH_DB"
13
+
14
+
15
+ class ConfigError(Exception):
16
+ pass
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class RepoSpec:
21
+ name: str
22
+ root: str
23
+ branch: str
24
+ enabled: bool
25
+ order: int
26
+ id: int = 0
27
+ directory_id: int = 0
28
+
29
+ @property
30
+ def path(self) -> str:
31
+ return os.path.join(self.root, self.name)
32
+
33
+ @property
34
+ def keeps_current(self) -> bool:
35
+ return self.branch == STAY
36
+
37
+ @property
38
+ def configured_target(self) -> str:
39
+ return self.branch
40
+
41
+
42
+ def project_root() -> Path:
43
+ return Path(__file__).resolve().parents[2]
44
+
45
+
46
+ def source_checkout() -> Path | None:
47
+ """Return the checkout root when running from a source tree, otherwise None."""
48
+ root = project_root()
49
+ if (root / "pyproject.toml").is_file() and (root / "workbench").is_dir():
50
+ return root
51
+ return None
52
+
53
+
54
+ def user_data_dir() -> Path:
55
+ if sys.platform == "darwin":
56
+ base = Path.home() / "Library" / "Application Support"
57
+ elif os.name == "nt":
58
+ base = Path(os.environ.get("APPDATA", str(Path.home())))
59
+ else:
60
+ base = Path(os.environ.get("XDG_DATA_HOME", str(Path.home() / ".local" / "share")))
61
+ return base / APP_DIR
62
+
63
+
64
+ def default_db_path() -> Path:
65
+ override = os.environ.get(DB_ENV)
66
+ if override:
67
+ return Path(override).expanduser()
68
+ checkout = source_checkout()
69
+ if checkout is not None:
70
+ return checkout / "data" / "workbench.db"
71
+ return user_data_dir() / "workbench.db"
72
+
73
+
74
+ def adopt_legacy_db(db_path: Path, *, root: Path | None = None) -> None:
75
+ """Move a catalog from the pre-data/ layout into the default location without overwriting."""
76
+ if root is None:
77
+ default = default_db_path()
78
+ legacy_root = project_root()
79
+ else:
80
+ default = root / "data" / "workbench.db"
81
+ legacy_root = root
82
+ try:
83
+ chosen = db_path.expanduser().resolve()
84
+ target = default.resolve()
85
+ except OSError:
86
+ return
87
+ if chosen != target:
88
+ return
89
+ legacy = legacy_root / "workbench.db"
90
+ if default.exists() or not legacy.is_file():
91
+ return
92
+ default.parent.mkdir(parents=True, exist_ok=True)
93
+ for name in ("workbench.db", "workbench.db-wal", "workbench.db-shm"):
94
+ source = legacy_root / name
95
+ if source.exists():
96
+ source.rename(default.parent / name)
97
+
98
+
99
+ def check_repo_name(name: str) -> str:
100
+ cleaned = name.strip()
101
+ if (
102
+ not cleaned
103
+ or cleaned in {".", ".."}
104
+ or cleaned.startswith("#")
105
+ or "/" in cleaned
106
+ or "\\" in cleaned
107
+ or ":" in cleaned
108
+ or any(char.isspace() for char in cleaned)
109
+ ):
110
+ raise ConfigError(f"Invalid repository name: {name}")
111
+ return cleaned
112
+
113
+
114
+ def check_branch_name(branch: str) -> str:
115
+ if not isinstance(branch, str):
116
+ raise ConfigError("Target branch cannot be empty")
117
+ cleaned = branch.strip()
118
+ if not cleaned:
119
+ raise ConfigError("Target branch cannot be empty")
120
+ if cleaned != STAY and (":" in cleaned or any(char.isspace() for char in cleaned)):
121
+ raise ConfigError("Branch name cannot contain spaces or colons")
122
+ if cleaned in {".", ".."} or cleaned.startswith("/") or "\\" in cleaned or cleaned.startswith("-"):
123
+ raise ConfigError(f"Invalid branch name: {cleaned}")
124
+ return cleaned