darwin-shell 0.1.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 (46) hide show
  1. darwin_shell-0.1.0/LICENSE +21 -0
  2. darwin_shell-0.1.0/PKG-INFO +208 -0
  3. darwin_shell-0.1.0/README.md +195 -0
  4. darwin_shell-0.1.0/pyproject.toml +32 -0
  5. darwin_shell-0.1.0/setup.cfg +4 -0
  6. darwin_shell-0.1.0/src/darwin_shell/__init__.py +34 -0
  7. darwin_shell-0.1.0/src/darwin_shell/cli.py +140 -0
  8. darwin_shell-0.1.0/src/darwin_shell/share/bootstrap.sh +74 -0
  9. darwin_shell-0.1.0/src/darwin_shell/share/checkpoint.sh +437 -0
  10. darwin_shell-0.1.0/src/darwin_shell/share/cli.sh +555 -0
  11. darwin_shell-0.1.0/src/darwin_shell/share/core.sh +214 -0
  12. darwin_shell-0.1.0/src/darwin_shell/share/datetime.sh +367 -0
  13. darwin_shell-0.1.0/src/darwin_shell/share/env.sh +322 -0
  14. darwin_shell-0.1.0/src/darwin_shell/share/file.sh +303 -0
  15. darwin_shell-0.1.0/src/darwin_shell/share/i18n.sh +181 -0
  16. darwin_shell-0.1.0/src/darwin_shell/share/json.sh +258 -0
  17. darwin_shell-0.1.0/src/darwin_shell/share/locale/zh_CN.sh +456 -0
  18. darwin_shell-0.1.0/src/darwin_shell/share/lock.sh +414 -0
  19. darwin_shell-0.1.0/src/darwin_shell/share/log.sh +317 -0
  20. darwin_shell-0.1.0/src/darwin_shell/share/notify.sh +576 -0
  21. darwin_shell-0.1.0/src/darwin_shell/share/process.sh +394 -0
  22. darwin_shell-0.1.0/src/darwin_shell/share/sched.sh +360 -0
  23. darwin_shell-0.1.0/src/darwin_shell/share/stats.sh +540 -0
  24. darwin_shell-0.1.0/src/darwin_shell/share/terminal.sh +226 -0
  25. darwin_shell-0.1.0/src/darwin_shell.egg-info/PKG-INFO +208 -0
  26. darwin_shell-0.1.0/src/darwin_shell.egg-info/SOURCES.txt +44 -0
  27. darwin_shell-0.1.0/src/darwin_shell.egg-info/dependency_links.txt +1 -0
  28. darwin_shell-0.1.0/src/darwin_shell.egg-info/entry_points.txt +2 -0
  29. darwin_shell-0.1.0/src/darwin_shell.egg-info/requires.txt +3 -0
  30. darwin_shell-0.1.0/src/darwin_shell.egg-info/top_level.txt +1 -0
  31. darwin_shell-0.1.0/tests/test_checkpoint.py +225 -0
  32. darwin_shell-0.1.0/tests/test_cli.py +250 -0
  33. darwin_shell-0.1.0/tests/test_core.py +191 -0
  34. darwin_shell-0.1.0/tests/test_datetime.py +209 -0
  35. darwin_shell-0.1.0/tests/test_env.py +219 -0
  36. darwin_shell-0.1.0/tests/test_file.py +256 -0
  37. darwin_shell-0.1.0/tests/test_framework.py +141 -0
  38. darwin_shell-0.1.0/tests/test_i18n.py +253 -0
  39. darwin_shell-0.1.0/tests/test_json.py +294 -0
  40. darwin_shell-0.1.0/tests/test_lock.py +359 -0
  41. darwin_shell-0.1.0/tests/test_log.py +228 -0
  42. darwin_shell-0.1.0/tests/test_notify.py +267 -0
  43. darwin_shell-0.1.0/tests/test_process.py +277 -0
  44. darwin_shell-0.1.0/tests/test_sched.py +341 -0
  45. darwin_shell-0.1.0/tests/test_stats.py +234 -0
  46. darwin_shell-0.1.0/tests/test_terminal.py +173 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 darwinalpha
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.
@@ -0,0 +1,208 @@
1
+ Metadata-Version: 2.4
2
+ Name: darwin-shell
3
+ Version: 0.1.0
4
+ Summary: Reusable Bash mechanics: logging, locking, scheduling, checkpoints and notification plumbing
5
+ License: MIT
6
+ Project-URL: Chinese Documentation, https://github.com/darwinalpha/darwin-shell/blob/main/README.cn.md
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Provides-Extra: test
11
+ Requires-Dist: pytest>=8; extra == "test"
12
+ Dynamic: license-file
13
+
14
+ # darwin-shell
15
+
16
+ English · [简体中文](README.cn.md)
17
+
18
+ **Status: all 15 modules shipped, 177 contract tests passing.**
19
+
20
+ A reusable Bash 4+ function library extracted from the shell orchestration
21
+ layer of `darwin-fetch`. It owns mechanics — loading, errors, i18n, logging,
22
+ CLI parsing, files, JSON, dates, locks, processes, scheduling, checkpoints,
23
+ statistics and notifications — and deliberately knows nothing about business
24
+ domains such as data sources, instruments or trading calendars.
25
+
26
+ ## Why this exists
27
+
28
+ `darwin-fetch` accumulated 11,681 lines of shell across 35 files. Three
29
+ schedulers implemented similar limit/failure semantics with different flag
30
+ names; three modules fought over the EXIT trap; a library sourced `set -e` and
31
+ `set -u` into every caller; commands were assembled as strings and executed
32
+ with `eval`. The extraction is worthwhile only if those problems are solved
33
+ rather than relocated.
34
+
35
+ The resulting rules are strict:
36
+
37
+ - the library never calls `exit`, installs a trap, or changes shell options;
38
+ - callers may use `set -euo pipefail` safely;
39
+ - public functions live in `dsh::<module>::<verb>`, private helpers in
40
+ `_dsh_private_<module>_<name>`, configuration in `DARWIN_SH_*`;
41
+ - messages are English msgids rendered through `i18n.sh`, with an optional
42
+ Chinese table and runtime language switching;
43
+ - external tools are resolved at call time and can be injected for tests.
44
+
45
+ ## Installation
46
+
47
+ ### From a wheel or a source checkout
48
+
49
+ ```bash
50
+ uv build
51
+ pip install dist/darwin_shell-0.1.0-py3-none-any.whl
52
+ darwin-sh doctor
53
+ ```
54
+
55
+ ### Bootstrap in a shell script
56
+
57
+ `darwin-sh init` prints a sourceable snippet; it does not modify rc files:
58
+
59
+ ```bash
60
+ eval "$(darwin-sh init)"
61
+ dsh::use i18n core log cli
62
+ ```
63
+
64
+ To copy the modules into a stable directory outside the Python environment:
65
+
66
+ ```bash
67
+ eval "$(darwin-sh install --dir ~/.local/share/darwin-shell)"
68
+ ```
69
+
70
+ `darwin-sh lib [module]` prints the library directory or one module path.
71
+ `darwin-sh version` prints the version. `darwin-sh doctor` checks bash, module
72
+ files and the locale table.
73
+
74
+ A repository checkout works without installation:
75
+
76
+ ```bash
77
+ export DARWIN_SH_LIB_DIR="$PWD/src/darwin_shell/share"
78
+ source "$DARWIN_SH_LIB_DIR/bootstrap.sh"
79
+ dsh::use core log
80
+ ```
81
+
82
+ ## Quick start
83
+
84
+ ```bash
85
+ #!/usr/bin/env bash
86
+ set -euo pipefail
87
+ eval "$(darwin-sh init)"
88
+
89
+ dsh::use i18n core log cli
90
+ dsh::log::configure --name demo --stderr-only --level INFO
91
+ dsh::core::require_cmd bash
92
+ dsh::log::info 'darwin-shell is ready'
93
+
94
+ dsh::cli::spec demo
95
+ dsh::cli::value demo target --into TARGET --required --help 'Target path'
96
+ dsh::cli::run demo --target ./data
97
+ printf 'target=%s\n' "$TARGET"
98
+ ```
99
+
100
+ `dsh::use` is idempotent and whitelist-based. Modules are never loaded by
101
+ implicit side effects, and sourcing them does not create files, directories,
102
+ traps or global counters.
103
+
104
+ ## Module reference
105
+
106
+ | Module | Responsibility | Representative APIs |
107
+ |---|---|---|
108
+ | `bootstrap.sh` | locate the library and load modules | `dsh::use` |
109
+ | `i18n.sh` | msgid rendering, language detection, locale table | `t`, `set_lang`, `lang` |
110
+ | `core.sh` | exit codes, dependency checks, tool resolution, dry run | `fail`, `have_cmd`, `require_cmd`, `tool`, `warn_once`, `dry_run` |
111
+ | `env.sh` | dotenv parsing and export policy | `parse`, `load`, `get`, `has`, `require` |
112
+ | `terminal.sh` | colour policy and ANSI output | `enabled`, `code`, `line`, `info`, `warn`, `error` |
113
+ | `log.sh` | levels, formatted stderr and deferred file sink | `configure`, `level`, `file`, `debug`, `info`, `warn`, `error` |
114
+ | `cli.sh` | declarative option specs and parser | `spec`, `flag`, `value`, `optional_value`, `mutex`, `help`, `run`, `remaining_append` |
115
+ | `file.sh` | size, count, atomic write, temp dirs, stale cleanup | `size`, `count`, `is_empty`, `atomic_write`, `temp_dir`, `prune_stale` |
116
+ | `json.sh` | jq-backed reads, writes and atomic updates | `jq`, `valid`, `exists`, `get`, `get_raw`, `set` |
117
+ | `datetime.sh` | calendar validation, formatting, arithmetic, month range | `now`, `today`, `valid`, `compare`, `add`, `month_range` |
118
+ | `lock.sh` | inode locks with explicit fd lifecycle | `acquire`, `release`, `with_lock`, `prune_stale` |
119
+ | `process.sh` | timeout, bounded parallel tasks, process lifecycle | `parallel`, `run_timeout`, `spawn`, `alive`, `stop` |
120
+ | `sched.sh` | flat, grouped and nested scheduling | `run --mode ...` |
121
+ | `checkpoint.sh` | four-state markers with configurable layout | `configure`, `path`, `state`, `mark`, `read`, `clear` |
122
+ | `stats.sh` | counters, lists, messages, cross-process merge, JSON export | `init`, `record`, `result`, `flush`, `merge`, `dump_json` |
123
+ | `notify.sh` | data-driven rendering and pluggable transports | `configure`, `render`, `send`, `from_result`, `transport::register` |
124
+
125
+ Full function signatures are available with `dsh::<module>::<verb> --help`.
126
+
127
+ ## Key contracts
128
+
129
+ ### Errors and exit codes
130
+
131
+ `dsh::core::fail <code> <msgid> [args...]` writes to stderr and returns the
132
+ code without exiting. The shared table is:
133
+
134
+ | Code | Constant | Meaning |
135
+ |---|---|---|
136
+ | 0 | `DSH_RC_OK` | success |
137
+ | 1 | `DSH_RC_FAILURE` | generic failure |
138
+ | 2 | `DSH_RC_USAGE` | usage or validation error |
139
+ | 3 | `DSH_RC_TRANSIENT` | required tool unavailable |
140
+ | 4 | `DSH_RC_AUTH` | reserved |
141
+ | 5 | `DSH_RC_SKIP` | skipped work item |
142
+ | 6 | `DSH_RC_EXISTS` | target already exists |
143
+ | 7 | `DSH_RC_LOCK_BUSY` | lock held by another process |
144
+ | 124 | `DSH_RC_TIMEOUT` | timeout expired |
145
+ | 130 | `DSH_RC_INTERRUPT` | interrupted |
146
+
147
+ ### Dependency injection
148
+
149
+ Logical tool names are resolved through `dsh::core::tool`. Override them with
150
+ `DARWIN_SH_TOOL_JQ`, `DARWIN_SH_TOOL_FLOCK`, `DARWIN_SH_TOOL_TIMEOUT`, etc.
151
+ Missing tools are explicit failures, never silent degradation.
152
+
153
+ Time and environment are injectable too: `DARWIN_SH_NOW` freezes the clock,
154
+ `DARWIN_SH_TZ` scopes a timezone to one child process, `DARWIN_SH_TMPDIR`
155
+ selects the temp root, and `DARWIN_SH_LANG` selects the language.
156
+
157
+ ### State ownership
158
+
159
+ Modules keep state in private associative arrays. `stats::init` and
160
+ `checkpoint::configure` must be called explicitly; nothing is initialised at
161
+ source time. Results are handed back via `--into VAR` namerefs instead of global
162
+ counters or stdout side effects.
163
+
164
+ ### Boundaries deliberately kept out
165
+
166
+ - business rc-to-status mapping, `retry_count`, trading calendars;
167
+ - grouped/nested business orchestration beyond `sched.sh`'s generic modes;
168
+ - hard-coded webhook clients — callers register transports in `notify.sh`;
169
+ - a compatibility shim for the original `darwin-fetch` function names;
170
+ - `set -euo pipefail`, traps and `exit` inside library files.
171
+
172
+ ## Examples
173
+
174
+ See [examples/README.md](examples/README.md) for seven independent runnable
175
+ scripts, expected output, prerequisites and troubleshooting. They cover
176
+ bootstrap, dotenv + CLI, files + JSON, dates + locks, scheduling, checkpoints +
177
+ stats, and a webhook-shaped notification transport with no network access.
178
+
179
+ ## Tests and verification
180
+
181
+ ```bash
182
+ uv run pytest -q # 177 contract tests
183
+ uv run darwin-sh doctor
184
+ for f in examples/*.sh; do bash "$f" || exit 1; done
185
+ uv build
186
+ ```
187
+
188
+ Tests are fast and independent. Where a host lacks jq or flock, shell stubs
189
+ verify the library's calling contract (argv, exit codes, data flow) rather than
190
+ the external binary itself. BSD `date` branches and a real WeCom webhook are
191
+ best covered in CI on the respective platforms.
192
+
193
+ All shipped text files are UTF-8 with LF line endings; `.gitattributes` and
194
+ `.editorconfig` enforce this, and the test suite checks for CRLF regressions.
195
+
196
+ ## Documents
197
+
198
+ - [Design](docs/design.md) — boundaries, API decisions, packaging and migration.
199
+ - [Shell code walkthrough](docs/shell-code-walkthrough.md) — evidence from the
200
+ original code and the twelve issues that must not be copied.
201
+ - [Examples](examples/README.md) — runnable usage guide.
202
+
203
+ Both design and walkthrough documents have Chinese counterparts linked from
204
+ their first line.
205
+
206
+ ## License
207
+
208
+ MIT.
@@ -0,0 +1,195 @@
1
+ # darwin-shell
2
+
3
+ English · [简体中文](README.cn.md)
4
+
5
+ **Status: all 15 modules shipped, 177 contract tests passing.**
6
+
7
+ A reusable Bash 4+ function library extracted from the shell orchestration
8
+ layer of `darwin-fetch`. It owns mechanics — loading, errors, i18n, logging,
9
+ CLI parsing, files, JSON, dates, locks, processes, scheduling, checkpoints,
10
+ statistics and notifications — and deliberately knows nothing about business
11
+ domains such as data sources, instruments or trading calendars.
12
+
13
+ ## Why this exists
14
+
15
+ `darwin-fetch` accumulated 11,681 lines of shell across 35 files. Three
16
+ schedulers implemented similar limit/failure semantics with different flag
17
+ names; three modules fought over the EXIT trap; a library sourced `set -e` and
18
+ `set -u` into every caller; commands were assembled as strings and executed
19
+ with `eval`. The extraction is worthwhile only if those problems are solved
20
+ rather than relocated.
21
+
22
+ The resulting rules are strict:
23
+
24
+ - the library never calls `exit`, installs a trap, or changes shell options;
25
+ - callers may use `set -euo pipefail` safely;
26
+ - public functions live in `dsh::<module>::<verb>`, private helpers in
27
+ `_dsh_private_<module>_<name>`, configuration in `DARWIN_SH_*`;
28
+ - messages are English msgids rendered through `i18n.sh`, with an optional
29
+ Chinese table and runtime language switching;
30
+ - external tools are resolved at call time and can be injected for tests.
31
+
32
+ ## Installation
33
+
34
+ ### From a wheel or a source checkout
35
+
36
+ ```bash
37
+ uv build
38
+ pip install dist/darwin_shell-0.1.0-py3-none-any.whl
39
+ darwin-sh doctor
40
+ ```
41
+
42
+ ### Bootstrap in a shell script
43
+
44
+ `darwin-sh init` prints a sourceable snippet; it does not modify rc files:
45
+
46
+ ```bash
47
+ eval "$(darwin-sh init)"
48
+ dsh::use i18n core log cli
49
+ ```
50
+
51
+ To copy the modules into a stable directory outside the Python environment:
52
+
53
+ ```bash
54
+ eval "$(darwin-sh install --dir ~/.local/share/darwin-shell)"
55
+ ```
56
+
57
+ `darwin-sh lib [module]` prints the library directory or one module path.
58
+ `darwin-sh version` prints the version. `darwin-sh doctor` checks bash, module
59
+ files and the locale table.
60
+
61
+ A repository checkout works without installation:
62
+
63
+ ```bash
64
+ export DARWIN_SH_LIB_DIR="$PWD/src/darwin_shell/share"
65
+ source "$DARWIN_SH_LIB_DIR/bootstrap.sh"
66
+ dsh::use core log
67
+ ```
68
+
69
+ ## Quick start
70
+
71
+ ```bash
72
+ #!/usr/bin/env bash
73
+ set -euo pipefail
74
+ eval "$(darwin-sh init)"
75
+
76
+ dsh::use i18n core log cli
77
+ dsh::log::configure --name demo --stderr-only --level INFO
78
+ dsh::core::require_cmd bash
79
+ dsh::log::info 'darwin-shell is ready'
80
+
81
+ dsh::cli::spec demo
82
+ dsh::cli::value demo target --into TARGET --required --help 'Target path'
83
+ dsh::cli::run demo --target ./data
84
+ printf 'target=%s\n' "$TARGET"
85
+ ```
86
+
87
+ `dsh::use` is idempotent and whitelist-based. Modules are never loaded by
88
+ implicit side effects, and sourcing them does not create files, directories,
89
+ traps or global counters.
90
+
91
+ ## Module reference
92
+
93
+ | Module | Responsibility | Representative APIs |
94
+ |---|---|---|
95
+ | `bootstrap.sh` | locate the library and load modules | `dsh::use` |
96
+ | `i18n.sh` | msgid rendering, language detection, locale table | `t`, `set_lang`, `lang` |
97
+ | `core.sh` | exit codes, dependency checks, tool resolution, dry run | `fail`, `have_cmd`, `require_cmd`, `tool`, `warn_once`, `dry_run` |
98
+ | `env.sh` | dotenv parsing and export policy | `parse`, `load`, `get`, `has`, `require` |
99
+ | `terminal.sh` | colour policy and ANSI output | `enabled`, `code`, `line`, `info`, `warn`, `error` |
100
+ | `log.sh` | levels, formatted stderr and deferred file sink | `configure`, `level`, `file`, `debug`, `info`, `warn`, `error` |
101
+ | `cli.sh` | declarative option specs and parser | `spec`, `flag`, `value`, `optional_value`, `mutex`, `help`, `run`, `remaining_append` |
102
+ | `file.sh` | size, count, atomic write, temp dirs, stale cleanup | `size`, `count`, `is_empty`, `atomic_write`, `temp_dir`, `prune_stale` |
103
+ | `json.sh` | jq-backed reads, writes and atomic updates | `jq`, `valid`, `exists`, `get`, `get_raw`, `set` |
104
+ | `datetime.sh` | calendar validation, formatting, arithmetic, month range | `now`, `today`, `valid`, `compare`, `add`, `month_range` |
105
+ | `lock.sh` | inode locks with explicit fd lifecycle | `acquire`, `release`, `with_lock`, `prune_stale` |
106
+ | `process.sh` | timeout, bounded parallel tasks, process lifecycle | `parallel`, `run_timeout`, `spawn`, `alive`, `stop` |
107
+ | `sched.sh` | flat, grouped and nested scheduling | `run --mode ...` |
108
+ | `checkpoint.sh` | four-state markers with configurable layout | `configure`, `path`, `state`, `mark`, `read`, `clear` |
109
+ | `stats.sh` | counters, lists, messages, cross-process merge, JSON export | `init`, `record`, `result`, `flush`, `merge`, `dump_json` |
110
+ | `notify.sh` | data-driven rendering and pluggable transports | `configure`, `render`, `send`, `from_result`, `transport::register` |
111
+
112
+ Full function signatures are available with `dsh::<module>::<verb> --help`.
113
+
114
+ ## Key contracts
115
+
116
+ ### Errors and exit codes
117
+
118
+ `dsh::core::fail <code> <msgid> [args...]` writes to stderr and returns the
119
+ code without exiting. The shared table is:
120
+
121
+ | Code | Constant | Meaning |
122
+ |---|---|---|
123
+ | 0 | `DSH_RC_OK` | success |
124
+ | 1 | `DSH_RC_FAILURE` | generic failure |
125
+ | 2 | `DSH_RC_USAGE` | usage or validation error |
126
+ | 3 | `DSH_RC_TRANSIENT` | required tool unavailable |
127
+ | 4 | `DSH_RC_AUTH` | reserved |
128
+ | 5 | `DSH_RC_SKIP` | skipped work item |
129
+ | 6 | `DSH_RC_EXISTS` | target already exists |
130
+ | 7 | `DSH_RC_LOCK_BUSY` | lock held by another process |
131
+ | 124 | `DSH_RC_TIMEOUT` | timeout expired |
132
+ | 130 | `DSH_RC_INTERRUPT` | interrupted |
133
+
134
+ ### Dependency injection
135
+
136
+ Logical tool names are resolved through `dsh::core::tool`. Override them with
137
+ `DARWIN_SH_TOOL_JQ`, `DARWIN_SH_TOOL_FLOCK`, `DARWIN_SH_TOOL_TIMEOUT`, etc.
138
+ Missing tools are explicit failures, never silent degradation.
139
+
140
+ Time and environment are injectable too: `DARWIN_SH_NOW` freezes the clock,
141
+ `DARWIN_SH_TZ` scopes a timezone to one child process, `DARWIN_SH_TMPDIR`
142
+ selects the temp root, and `DARWIN_SH_LANG` selects the language.
143
+
144
+ ### State ownership
145
+
146
+ Modules keep state in private associative arrays. `stats::init` and
147
+ `checkpoint::configure` must be called explicitly; nothing is initialised at
148
+ source time. Results are handed back via `--into VAR` namerefs instead of global
149
+ counters or stdout side effects.
150
+
151
+ ### Boundaries deliberately kept out
152
+
153
+ - business rc-to-status mapping, `retry_count`, trading calendars;
154
+ - grouped/nested business orchestration beyond `sched.sh`'s generic modes;
155
+ - hard-coded webhook clients — callers register transports in `notify.sh`;
156
+ - a compatibility shim for the original `darwin-fetch` function names;
157
+ - `set -euo pipefail`, traps and `exit` inside library files.
158
+
159
+ ## Examples
160
+
161
+ See [examples/README.md](examples/README.md) for seven independent runnable
162
+ scripts, expected output, prerequisites and troubleshooting. They cover
163
+ bootstrap, dotenv + CLI, files + JSON, dates + locks, scheduling, checkpoints +
164
+ stats, and a webhook-shaped notification transport with no network access.
165
+
166
+ ## Tests and verification
167
+
168
+ ```bash
169
+ uv run pytest -q # 177 contract tests
170
+ uv run darwin-sh doctor
171
+ for f in examples/*.sh; do bash "$f" || exit 1; done
172
+ uv build
173
+ ```
174
+
175
+ Tests are fast and independent. Where a host lacks jq or flock, shell stubs
176
+ verify the library's calling contract (argv, exit codes, data flow) rather than
177
+ the external binary itself. BSD `date` branches and a real WeCom webhook are
178
+ best covered in CI on the respective platforms.
179
+
180
+ All shipped text files are UTF-8 with LF line endings; `.gitattributes` and
181
+ `.editorconfig` enforce this, and the test suite checks for CRLF regressions.
182
+
183
+ ## Documents
184
+
185
+ - [Design](docs/design.md) — boundaries, API decisions, packaging and migration.
186
+ - [Shell code walkthrough](docs/shell-code-walkthrough.md) — evidence from the
187
+ original code and the twelve issues that must not be copied.
188
+ - [Examples](examples/README.md) — runnable usage guide.
189
+
190
+ Both design and walkthrough documents have Chinese counterparts linked from
191
+ their first line.
192
+
193
+ ## License
194
+
195
+ MIT.
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "darwin-shell"
7
+ version = "0.1.0"
8
+ description = "Reusable Bash mechanics: logging, locking, scheduling, checkpoints and notification plumbing"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.10"
12
+ dependencies = []
13
+
14
+ [project.urls]
15
+ "Chinese Documentation" = "https://github.com/darwinalpha/darwin-shell/blob/main/README.cn.md"
16
+
17
+ [project.optional-dependencies]
18
+ test = ["pytest>=8"]
19
+
20
+ [project.scripts]
21
+ darwin-sh = "darwin_shell.cli:main"
22
+
23
+ [tool.setuptools.packages.find]
24
+ where = ["src"]
25
+
26
+ [tool.setuptools.package-data]
27
+ darwin_shell = ["share/*.sh", "share/locale/*.sh"]
28
+
29
+ [tool.pytest.ini_options]
30
+ testpaths = ["tests"]
31
+ pythonpath = ["src"]
32
+ addopts = "-q"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,34 @@
1
+ """Package metadata and path resolution for darwin-shell.
2
+
3
+ Python is used only to locate, verify and export the shell modules. The
4
+ modules themselves have no Python runtime dependency.
5
+ """
6
+
7
+ from pathlib import Path
8
+
9
+ __version__ = "0.1.0"
10
+
11
+ SHARE_DIR = Path(__file__).resolve().parent / "share"
12
+
13
+ MODULES = (
14
+ "i18n",
15
+ "core",
16
+ "env",
17
+ "terminal",
18
+ "log",
19
+ "cli",
20
+ "file",
21
+ "json",
22
+ "datetime",
23
+ "lock",
24
+ "process",
25
+ "sched",
26
+ "checkpoint",
27
+ "stats",
28
+ "notify",
29
+ )
30
+
31
+
32
+ def lib_dir() -> Path:
33
+ """Return the absolute directory that contains the shipped shell modules."""
34
+ return SHARE_DIR
@@ -0,0 +1,140 @@
1
+ """darwin-sh: locate, verify and export darwin-shell modules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import shlex
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ from . import MODULES, __version__, lib_dir
13
+
14
+
15
+ def _cmd_version(_args: argparse.Namespace) -> int:
16
+ """Print the installed version."""
17
+ print(__version__)
18
+ return 0
19
+
20
+
21
+ def _cmd_lib(args: argparse.Namespace) -> int:
22
+ """Print the library directory, or the path of one named module."""
23
+ root = lib_dir()
24
+ if args.module is None:
25
+ print(root)
26
+ return 0
27
+ if args.module not in MODULES:
28
+ print(f"darwin-sh: unknown module: {args.module}", file=sys.stderr)
29
+ return 2
30
+ print(root / f"{args.module}.sh")
31
+ return 0
32
+
33
+
34
+ def _cmd_init(_args: argparse.Namespace) -> int:
35
+ """Print a sourceable snippet that bootstraps the library."""
36
+ root = lib_dir()
37
+ print(f"DARWIN_SH_LIB_DIR={shlex.quote(str(root))}; export DARWIN_SH_LIB_DIR")
38
+ print(f"source {shlex.quote(str(root / 'bootstrap.sh'))}")
39
+ return 0
40
+
41
+
42
+ def _cmd_install(args: argparse.Namespace) -> int:
43
+ """Copy the shipped modules to a stable directory outside the Python env."""
44
+ target = Path(args.dir).expanduser()
45
+ target.mkdir(parents=True, exist_ok=True)
46
+ source = lib_dir()
47
+ for name in ("bootstrap.sh", *(f"{m}.sh" for m in MODULES)):
48
+ path = source / name
49
+ if path.is_file():
50
+ shutil.copy2(path, target / name)
51
+
52
+ locale_source = source / "locale"
53
+ if locale_source.is_dir():
54
+ locale_target = target / "locale"
55
+ locale_target.mkdir(parents=True, exist_ok=True)
56
+ for path in sorted(locale_source.glob("*.sh")):
57
+ shutil.copy2(path, locale_target / path.name)
58
+
59
+ print(f"DARWIN_SH_LIB_DIR={shlex.quote(str(target))}; export DARWIN_SH_LIB_DIR")
60
+ print(f"source {shlex.quote(str(target / 'bootstrap.sh'))}")
61
+ return 0
62
+
63
+
64
+ def _cmd_doctor(_args: argparse.Namespace) -> int:
65
+ """Report bootstrap prerequisites; exit non-zero only when loading is impossible."""
66
+ root = lib_dir()
67
+ bash = shutil.which("bash")
68
+ if bash is None:
69
+ # uv/isolated environments on Windows can drop bash from PATH; probe directly.
70
+ for candidate in ("/usr/bin/bash", "/bin/bash", "C:/Program Files/Git/usr/bin/bash.exe"):
71
+ if Path(candidate).is_file():
72
+ bash = candidate
73
+ break
74
+ if bash is None:
75
+ print("FAIL: bash not found on PATH", file=sys.stderr)
76
+ return 1
77
+ result = subprocess.run(
78
+ [bash, "-c", 'printf "%s" "${BASH_VERSINFO[0]}"'],
79
+ capture_output=True,
80
+ text=True,
81
+ check=False,
82
+ )
83
+ major = result.stdout.strip().splitlines()[0].strip() if result.stdout.strip() else ""
84
+ if not major.isdigit() or int(major) < 4:
85
+ print("FAIL: bash >= 4.0 is required", file=sys.stderr)
86
+ return 1
87
+ print(f"OK: darwin-shell {__version__}")
88
+ print(f"OK: bash {major}")
89
+ print(f"OK: lib dir {root}")
90
+ if not (root / "bootstrap.sh").is_file():
91
+ print("FAIL: bootstrap.sh is missing", file=sys.stderr)
92
+ return 1
93
+ missing = [m for m in MODULES if not (root / f"{m}.sh").is_file()]
94
+ if missing:
95
+ print("WARN: modules not yet shipped: " + ", ".join(missing))
96
+ if not (root / "locale" / "zh_CN.sh").is_file():
97
+ print("WARN: zh_CN locale table is missing")
98
+ for tool in ("shellcheck", "bats"):
99
+ state = "ok" if shutil.which(tool) else "absent (optional)"
100
+ print(f"INFO: {tool} {state}")
101
+ return 0
102
+
103
+
104
+ def main(argv: list[str] | None = None) -> int:
105
+ """Entry point for the ``darwin-sh`` console script."""
106
+ parser = argparse.ArgumentParser(
107
+ prog="darwin-sh",
108
+ description="Locate, verify and export darwin-shell modules.",
109
+ )
110
+ parser.add_argument(
111
+ "--version", action="version", version=f"%(prog)s {__version__}"
112
+ )
113
+ commands = parser.add_subparsers(dest="command", required=True)
114
+
115
+ commands.add_parser("version", help="print the installed version").set_defaults(
116
+ func=_cmd_version
117
+ )
118
+
119
+ lib_parser = commands.add_parser("lib", help="print a module path")
120
+ lib_parser.add_argument("module", nargs="?", help="module name, e.g. sched")
121
+ lib_parser.set_defaults(func=_cmd_lib)
122
+
123
+ commands.add_parser("init", help="print a sourceable bootstrap snippet").set_defaults(
124
+ func=_cmd_init
125
+ )
126
+ install_parser = commands.add_parser(
127
+ "install", help="copy modules to a stable directory"
128
+ )
129
+ install_parser.add_argument("--dir", required=True, dest="dir")
130
+ install_parser.set_defaults(func=_cmd_install)
131
+ commands.add_parser("doctor", help="check bootstrap prerequisites").set_defaults(
132
+ func=_cmd_doctor
133
+ )
134
+
135
+ args = parser.parse_args(argv)
136
+ return int(args.func(args))
137
+
138
+
139
+ if __name__ == "__main__":
140
+ sys.exit(main())