ruby_workspace_manager 0.6.3 → 0.6.4

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: abb2b2c2c95382842ff412711726e5180b6b044b09278f74fd41bce2d29ae7e0
4
- data.tar.gz: 2370c792ceb61d94619822c8b7a6f63277284f178e72d6a3539f782496d64ba1
3
+ metadata.gz: 38623d16221111f5899c657ecd424a14397cb4b33223ee7d8f95ebd766c61777
4
+ data.tar.gz: 99992c68cb96d2ce4a7414e2ec5ee0fe5aed244c5fbcf9e3d70887090c1c155b
5
5
  SHA512:
6
- metadata.gz: a6746e8ced0a14de677e83de564c7477e89b0f2519a37447dc1a94dbe28acc3cef2b848c1b3bb2604afe24cd399050d677eceb2dbea194a87163c564df1cada4
7
- data.tar.gz: 076e897c277f1074f5c4eef7ee834e5c1920050569783e2a84bac836aa9bb4c82aef182390294663068a24fd6690c172e6946b38ea2e29f0bc9289803ac47283
6
+ metadata.gz: 5f1651f55f29fe8cff0bbe731941e52baf5d173139cd62cd1c75ad80d99ae8008a2caf4ef3bea261a27fb8642d74006599eaa30919d1d16349678e4b1a08a927
7
+ data.tar.gz: f663aebaa0ddaabb9032a6809105eab4df406170eda4f1ed2b540340cebdb16150e9fed5f4df745ca711330b0cc431b156623d9d61e0bb9cb1a4b7ddd34150e4
data/README.md CHANGED
@@ -9,102 +9,32 @@ A monorepo tool for Ruby, inspired by [Nx](https://nx.dev). Convention-over-conf
9
9
 
10
10
  RWM discovers packages in your repository, builds a dependency graph from Gemfiles, runs tasks in parallel respecting dependency order, detects which packages are affected by a change, and caches results so unchanged work is never repeated.
11
11
 
12
- ## Table of Contents
12
+ ## Is this for me?
13
13
 
14
- - [Getting started](#getting-started)
15
- - [Core concepts](#core-concepts)
16
- - [Workspace layout](#workspace-layout)
17
- - [Managing packages](#managing-packages)
18
- - [Dependencies between packages](#dependencies-between-packages)
19
- - [The dependency graph](#the-dependency-graph)
20
- - [Running tasks](#running-tasks)
21
- - [Task caching](#task-caching)
22
- - [Affected detection](#affected-detection)
23
- - [Bootstrap and daily workflow](#bootstrap-and-daily-workflow)
24
- - [Git hooks](#git-hooks)
25
- - [Convention enforcement](#convention-enforcement)
26
- - [Rails and Zeitwerk](#rails-and-zeitwerk)
27
- - [VSCode integration](#vscode-integration)
28
- - [Shell completions](#shell-completions)
29
- - [Command reference](#command-reference)
30
- - [Design philosophy](#design-philosophy)
31
- - [Resources](#resources)
14
+ RWM is useful whenever you have **multiple Ruby packages in one repository** and want structure around them. Common scenarios:
32
15
 
33
- ---
16
+ - **Multiple apps sharing internal libraries** (auth, billing, notifications) — you want clear dependency boundaries, parallel test runs, and CI that only tests what changed.
17
+ - **Outgrowing a single Rails app** — you're extracting shared code into libraries that multiple apps consume, and you want to manage the dependencies between them without setting up a private gem server.
18
+ - **Several Rails apps that share domain logic** — you want one `git clone`, one `bootstrap` command, and a dependency graph that keeps everything honest.
34
19
 
35
- ## Getting started
20
+ RWM orchestrates Rake tasks. If you can express it as a Rake task, RWM can run it across your packages — tests, linting, builds, deploys, gem publishing, whatever your workflow needs.
36
21
 
37
- ### New workspace
22
+ ## Quick start
38
23
 
39
24
  ```sh
40
25
  gem install ruby_workspace_manager
41
26
 
42
27
  mkdir my-project && cd my-project
43
28
  git init
44
- rwm init
45
- ```
46
-
47
- `rwm init` creates the full workspace structure — `libs/`, `apps/`, a root Gemfile (with `rake` and `ruby_workspace_manager`), a root Rakefile, and adds `.rwm/` to `.gitignore`. It then runs `rwm bootstrap` automatically. The command is idempotent.
48
-
49
- ### Existing project
50
-
51
- If you already have a git repo with a Gemfile, add RWM to it and initialize:
52
-
53
- ```sh
54
- bundle add ruby_workspace_manager
55
- rwm init
56
- ```
57
-
58
- `rwm init` won't overwrite your existing Gemfile or Rakefile — it only creates files that are missing.
29
+ rwm init # creates workspace structure, bootstraps everything
59
30
 
60
- ### Creating packages
61
-
62
- ```sh
63
- rwm new lib auth
31
+ rwm new lib auth # scaffold a library
64
32
  rwm new lib billing
65
- rwm new app api
66
- ```
67
-
68
- Each command scaffolds a complete gem structure: Gemfile, gemspec, Rakefile, module stub, and test helper (unless `--test=none`).
69
-
70
- ### Declaring dependencies
71
-
72
- Edit the consuming package's Gemfile:
73
-
74
- ```ruby
75
- # apps/api/Gemfile
76
- require "rwm/gemfile"
33
+ rwm new app api # scaffold an application
77
34
 
78
- rwm_lib "auth"
79
- rwm_lib "billing"
80
- ```
81
-
82
- Then bootstrap to install deps and rebuild the graph:
83
-
84
- ```sh
85
- rwm bootstrap
86
- ```
87
-
88
- ### Running tasks
89
-
90
- ```sh
91
- rwm spec # runs `rake spec` in every package that defines it
92
- rwm lint # any unrecognized command is a task shortcut
93
- rwm lint auth # run a task in a single package
94
- ```
95
-
96
- Tasks run in parallel, respecting dependency order. Packages that don't define the requested task are silently skipped.
97
-
98
- ```
99
- $ rwm spec
100
- Running `rake spec` across 4 package(s)...
101
-
102
- [auth] 12 examples, 0 failures
103
- [billing] 8 examples, 0 failures
104
- [notifications] 5 examples, 0 failures
105
- [api] 21 examples, 0 failures
106
-
107
- 4 package(s): 4 passed.
35
+ rwm spec # runs `rake spec` in every package, in parallel
36
+ rwm spec --affected # only packages changed on this branch
37
+ rwm spec auth billing # only specific packages
108
38
  ```
109
39
 
110
40
  ## Core concepts
@@ -150,676 +80,17 @@ A directory is recognized as a package if it lives directly inside `libs/` or `a
150
80
 
151
81
  The `.rwm/` directory is created automatically and gitignored by `rwm init`. It stores the dependency graph cache and task cache state.
152
82
 
153
- ## Managing packages
154
-
155
- ### Scaffolding
156
-
157
- ```sh
158
- rwm new lib <name>
159
- rwm new app <name>
160
- rwm new lib <name> --test=minitest
161
- rwm new app <name> --test=none
162
- ```
163
-
164
- Package names must match `/\A[a-z][a-z0-9_]*\z/` (lowercase, letters/digits/underscores, starts with a letter).
165
-
166
- The `--test` flag controls which test framework is scaffolded. Values: `rspec` (default), `minitest`, `none`.
167
-
168
- The scaffold includes:
169
-
170
- - **Gemfile** — Sources rubygems.org, loads the gemspec, includes development dependencies (`rake`, the chosen test gem, `ruby_workspace_manager`), and requires `rwm/gemfile` for the `rwm_lib` helper.
171
- - **Gemspec** — Minimal spec. Libraries use `require_paths = ["lib"]` and declare `spec.files`; applications use `require_paths = ["app"]` and omit `spec.files`.
172
- - **Rakefile** — A `cacheable_task` for the test framework (`:spec` for rspec, `:test` for minitest) plus an empty `:bootstrap` task. With `--test=none`, only the bootstrap task is generated.
173
- - **Source file** — `lib/<name>.rb` for libraries, `app/<name>.rb` for applications. Module stub.
174
- - **Test helper** — `spec/spec_helper.rb` for rspec, `test/test_helper.rb` for minitest. Omitted with `--test=none`.
175
-
176
- ### Inspecting and listing
177
-
178
- ```sh
179
- rwm info auth # type, path, dependencies, direct/transitive dependents
180
- rwm list # formatted table of all packages
181
- ```
182
-
183
- ## Dependencies between packages
184
-
185
- ### How dependency detection works
186
-
187
- RWM reads each package's Gemfile using Bundler's DSL parser and extracts gems declared with a `path:` option pointing into the workspace. It does not scan source code for `require` statements. This means Bundler's Gemfile is the single source of truth for both runtime resolution and RWM's dependency graph.
188
-
189
- ### The `rwm_lib` helper
190
-
191
- Scaffolded packages include `require "rwm/gemfile"` in their Gemfile, which adds the `rwm_lib` method to Bundler's DSL:
192
-
193
- ```ruby
194
- # libs/billing/Gemfile
195
- require "rwm/gemfile"
196
-
197
- rwm_lib "auth"
198
- ```
199
-
200
- This expands to:
201
-
202
- ```ruby
203
- gem "auth", path: "/absolute/path/to/libs/auth"
204
- ```
205
-
206
- The workspace root is resolved via `git rev-parse --show-toplevel`, so it works regardless of where you run the command. You can pass any extra options that `gem` accepts:
207
-
208
- ```ruby
209
- rwm_lib "auth", require: false
210
- ```
211
-
212
- There is no `rwm_app` helper. Applications are leaf nodes — nothing should depend on them.
213
-
214
- `rwm_lib` validates that the library directory exists. If you reference a library that hasn't been created yet, you'll get a clear error:
215
-
216
- ```
217
- rwm_lib 'payments': no library found at libs/payments.
218
- Libraries must live in libs/. Create one with: rwm new lib payments
219
- ```
220
-
221
- You can also use raw `gem ... path:` syntax directly. Both work identically for dependency detection.
222
-
223
- ### Transitive resolution
224
-
225
- When you call `rwm_lib "auth"`, RWM automatically resolves auth's own workspace dependencies. If auth's Gemfile declares `rwm_lib "core"`, then `core` is added to your bundle automatically.
226
-
227
- This works recursively. Diamond dependencies and cycles are handled safely (each lib is resolved at most once).
228
-
229
- ```ruby
230
- # apps/web/Gemfile — only the direct dep is needed
231
- require "rwm/gemfile"
232
-
233
- rwm_lib "auth" # core (auth's dep) is added automatically
234
- ```
235
-
236
- Transitive resolution uses `Bundler::Dsl.eval_gemfile` — the same mechanism Bundler uses internally. Options passed to the direct `rwm_lib` call (like `group:` or `require:`) are not forwarded to transitive deps.
237
-
238
- ## The dependency graph
239
-
240
- ### Building
241
-
242
- ```sh
243
- rwm graph
244
- ```
245
-
246
- Parses every package's Gemfile, constructs a DAG using Ruby's `TSort` module (Tarjan's algorithm), writes it to `.rwm/graph.json`, and prints a summary.
247
-
248
- ### Caching and staleness
249
-
250
- Most commands (`run`, `list`, `check`, `affected`, `info`) load the graph from `.rwm/graph.json` rather than re-parsing Gemfiles. If any package's Gemfile has a modification time newer than the cache file, the graph is silently rebuilt. You rarely need to run `rwm graph` manually.
251
-
252
- Concurrent `rwm` processes are safe — graph reads use shared file locks and writes use exclusive file locks.
253
-
254
- ### Visualization
255
-
256
- ```sh
257
- rwm graph --dot # Graphviz DOT format
258
- rwm graph --mermaid # Mermaid flowchart format
259
- ```
260
-
261
- Pipe DOT output to Graphviz to render an image:
262
-
263
- ```sh
264
- rwm graph --dot | dot -Tpng -o graph.png
265
- ```
266
-
267
- Or paste Mermaid output into any Mermaid-compatible renderer (GitHub markdown, Mermaid Live Editor, etc.).
268
-
269
- ## Running tasks
270
-
271
- ### Basic usage
272
-
273
- ```sh
274
- rwm run <task> # run in all packages
275
- rwm run <task> <package> # run in one package
276
- rwm spec # shortcut for `rwm run spec`
277
- rwm lint auth # shortcut for `rwm run lint auth`
278
- ```
279
-
280
- Any command that isn't a built-in subcommand is treated as a task name and forwarded to `rwm run`.
281
-
282
- RWM runs `bundle exec rake <task>` in each package directory that has a Rakefile. Packages that don't define the requested task are automatically detected and silently skipped.
283
-
284
- ### Parallel execution
285
-
286
- RWM uses a DAG scheduler with a thread pool. Each package starts executing the instant all of its dependencies have completed. If A and B are independent, they run simultaneously. If C depends on A, C starts as soon as A finishes — it does not wait for B.
287
-
288
- The default concurrency is `Etc.nprocessors` (number of CPU cores). Override with:
289
-
290
- ```sh
291
- rwm run spec --concurrency 4
292
- ```
293
-
294
- ### Output modes
295
-
296
- **Streaming (default)** — Output is printed as it happens, prefixed with the package name:
297
-
298
- ```
299
- [auth] 5 examples, 0 failures
300
- [billing] 3 examples, 0 failures
301
- ```
302
-
303
- **Buffered** — Each package's output is collected and printed as a complete block when it finishes. Failed packages have their output sent to stderr:
304
-
305
- ```sh
306
- rwm run spec --buffered
307
- ```
308
-
309
- ### Failure handling
310
-
311
- When a package fails, its transitive dependents are immediately skipped. Unrelated packages continue running. The exit code is 0 if all packages pass, 1 if any fail.
312
-
313
- The summary distinguishes between skip reasons:
314
-
315
- ```
316
- 5 package(s): 2 passed, 1 failed, 1 skipped (dep failed), 1 skipped (no task).
317
- ```
318
-
319
- - **skipped (dep failed)** — a dependency failed, so this package was not attempted
320
- - **skipped (no task)** — the package's Rakefile doesn't define the requested task
321
-
322
- ## Task caching
323
-
324
- ### Why caching matters
325
-
326
- In a monorepo with many packages, most runs touch only a few. Without caching, `rwm spec` re-runs everything even if nothing changed. Task caching skips packages whose inputs are unchanged.
327
-
328
- ### Content-hash caching
329
-
330
- RWM's cache is inspired by [DJB's redo](https://cr.yp.to/redo.html). The core insight: **use content hashes, not timestamps, to decide what needs rebuilding.** Timestamps are fragile — `git checkout` changes them, rebasing rewrites them. Content hashes are deterministic: if the bytes haven't changed, the result is still valid.
331
-
332
- For each (package, task) pair, RWM:
333
-
334
- 1. **Computes a content hash** — SHA256 of all source files in the package (sorted by path), plus the content hashes of all dependency packages.
335
- 2. **Compares with stored hash** — If the hash matches the last successful run and declared outputs exist, the task is skipped.
336
- 3. **Stores on success** — After a successful run, the hash is saved to `.rwm/cache/<package>-<task>`.
337
-
338
- Source files are discovered via `git ls-files` (tracked + untracked-but-not-ignored), so anything in `.gitignore` is excluded from the hash.
339
-
340
- ### Transitive invalidation
341
-
342
- A package's content hash includes the content hashes of its dependencies, recursively:
343
-
344
- ```
345
- hash(auth) = SHA256(auth's files)
346
- hash(billing) = SHA256(billing's files + hash(auth))
347
- hash(api) = SHA256(api's files + hash(billing) + hash(auth))
348
- ```
349
-
350
- Change a single file in `auth` and the hashes of `billing` and `api` change automatically. No explicit invalidation logic needed.
351
-
352
- ### Where the cache is coarser than redo
353
-
354
- True redo tracks exactly which files a build step read during execution. RWM hashes every git-tracked file in the package directory. This means editing a README invalidates the spec cache even though RSpec never reads it.
355
-
356
- This is a deliberate tradeoff. File-level read tracking would require filesystem interception (`strace`, `dtrace`, FUSE), which contradicts the zero-dependency philosophy. Package-level hashing may give false invalidations (unnecessary re-runs) but never false cache hits (skipping when it shouldn't).
357
-
358
- ### Declaring cacheable tasks
359
-
360
- Tasks are only cached if declared with `cacheable_task` in the Rakefile:
361
-
362
- ```ruby
363
- # libs/auth/Rakefile
364
- require "rwm/rake"
365
-
366
- cacheable_task :spec do
367
- sh "bundle exec rspec"
368
- end
369
-
370
- cacheable_task :build, output: "pkg/*.gem" do
371
- sh "gem build *.gemspec"
372
- end
373
- ```
374
-
375
- `cacheable_task` creates a normal Rake task — it works like `task` when run directly. The caching metadata is only used when RWM orchestrates the run.
376
-
377
- The optional `output:` parameter declares a glob for expected output files. If declared outputs don't exist, the cache is invalid even if the input hash matches.
378
-
379
- Tasks declared with plain `task` always run unconditionally.
380
-
381
- ### Bypassing the cache
382
-
383
- ```sh
384
- rwm run spec --no-cache
385
- ```
386
-
387
- ### Sharing the cache
388
-
389
- The `.rwm/` directory is gitignored by design — committing it would create constant merge conflicts as the cache and graph change with every task run. Instead, treat your main branch CI as the single source of truth and distribute the cache from there.
390
-
391
- Cache entries are content hashes with no absolute paths or machine-specific data. They're fully portable across machines. Restoring a stale cache is always safe — stale entries won't match and the task simply re-runs.
392
-
393
- **The pattern:**
394
-
395
- 1. Main branch CI runs the full test suite, producing a complete `.rwm/` cache.
396
- 2. Feature branch CI restores main's cache, then runs only `--affected` packages.
397
- 3. Developer machines download the cache during `rwm bootstrap`, so new branches start pre-warmed.
398
-
399
- The result: feature branch CI and local development only run what actually changed.
400
-
401
- #### GitHub Actions
402
-
403
- ```yaml
404
- name: CI
405
-
406
- on:
407
- push:
408
- branches: [main]
409
- pull_request:
410
-
411
- jobs:
412
- test:
413
- runs-on: ubuntu-latest
414
- steps:
415
- - uses: actions/checkout@v4
416
-
417
- - name: Fetch base branch for affected detection
418
- if: github.ref != 'refs/heads/main'
419
- run: git fetch origin main --depth=1
420
-
421
- - name: Set up Ruby
422
- uses: ruby/setup-ruby@v1
423
- with:
424
- ruby-version: "3.4"
425
- bundler-cache: true
426
-
427
- - name: Restore RWM cache
428
- uses: actions/cache@v4
429
- with:
430
- path: .rwm
431
- key: rwm-${{ runner.os }}-${{ github.sha }}
432
- restore-keys: rwm-${{ runner.os }}-
433
-
434
- - name: Bootstrap
435
- run: bundle exec rwm bootstrap
436
-
437
- - name: Run specs
438
- run: |
439
- if [ "${{ github.ref }}" = "refs/heads/main" ]; then
440
- bundle exec rwm run spec
441
- else
442
- bundle exec rwm run spec --affected
443
- fi
444
-
445
- # Make cache available for local dev bootstrap
446
- - name: Upload RWM cache
447
- if: github.ref == 'refs/heads/main'
448
- uses: actions/upload-artifact@v4
449
- with:
450
- name: rwm-cache
451
- path: .rwm/
452
- retention-days: 30
453
- ```
454
-
455
- Key points:
456
-
457
- - **Fetch base branch** — Affected detection runs `git diff main...HEAD`, which needs the base branch ref. A shallow fetch of `main` is enough — no need for `fetch-depth: 0` or a full clone.
458
- - **`actions/cache`** — Caches created on the default branch are accessible to all feature branches. The `restore-keys` prefix picks up the most recent main cache automatically.
459
- - **Main runs everything**, populating a complete cache. Feature branches run only `--affected` and skip anything already cached from main.
460
- - **`upload-artifact`** on main makes the cache downloadable for local dev bootstrap (see below).
461
-
462
- #### Local developer cache (optional)
463
-
464
- Add a cache download step to your root Rakefile so `rwm bootstrap` warms the local cache automatically:
465
-
466
- ```ruby
467
- # Rakefile
468
- task :bootstrap do
469
- restore_rwm_cache
470
- end
471
-
472
- def restore_rwm_cache
473
- return if File.directory?(".rwm/cache")
474
- return unless system("which gh > /dev/null 2>&1")
475
-
476
- puts "Downloading RWM cache from CI..."
477
- run_id = `gh run list --branch main --status success --workflow ci.yml --limit 1 --json databaseId --jq '.[0].databaseId'`.strip
478
- if run_id.empty?
479
- puts "No CI cache found. Skipping."
480
- return
481
- end
482
-
483
- system("gh", "run", "download", run_id, "--name", "rwm-cache", "--dir", ".rwm")
484
- puts File.directory?(".rwm/cache") ? "Cache restored." : "Cache download failed. Continuing without cache."
485
- end
486
- ```
487
-
488
- The example above uses the [GitHub CLI](https://cli.github.com/) (`gh`) to download artifacts — your setup may look different depending on your CI provider or storage backend (S3, GCS, etc.). The idea is the same: download the `.rwm/` directory from a known location during bootstrap.
489
-
490
- After cloning and running `rwm bootstrap`, developers have a warm cache. Creating a feature branch from main and running `rwm run spec --affected` skips unchanged packages immediately.
491
-
492
- ## Affected detection
493
-
494
- ### What "affected" means
495
-
496
- When you change code on a feature branch, the affected packages are those you directly changed plus every package that depends on them, transitively. If you change `libs/auth/` and `libs/billing/` depends on `auth` and `apps/api/` depends on `billing`, all three are affected.
497
-
498
- ### Viewing affected packages
499
-
500
- ```sh
501
- rwm affected
502
- ```
503
-
504
- ### Running tasks on affected packages
505
-
506
- ```sh
507
- rwm run spec --affected
508
- ```
509
-
510
- This is the most useful command for feature branch CI. It combines affected detection with task execution — only affected packages are tested, in correct dependency order with full parallelism.
511
-
512
- ### How change detection works
513
-
514
- RWM detects changes from three sources:
515
-
516
- 1. **Committed changes** — `git diff --name-only <base>...HEAD`
517
- 2. **Staged changes** — `git diff --name-only --cached`
518
- 3. **Unstaged changes** — `git diff --name-only`
519
-
520
- Changed files are mapped to packages by path prefix. Use `--committed` to only consider committed changes (ignoring staged and unstaged):
521
-
522
- ```sh
523
- rwm run spec --affected --committed
524
- ```
525
-
526
- ### Root-level changes
527
-
528
- Files outside any package directory (like the root `Gemfile` or `Rakefile`) cause all packages to be marked as affected. This is a conservative default — root-level changes can affect the entire workspace.
529
-
530
- However, inert files are automatically excluded from triggering a full run. The following patterns are ignored by default:
531
-
532
- - `*.md`, `LICENSE*`, `CHANGELOG*`
533
- - `.github/**`, `.vscode/**`, `.idea/**`
534
- - `docs/**`, `.rwm/**`
535
-
536
- You can add custom patterns in `.rwm/affected_ignore` (one glob per line, `#` for comments).
537
-
538
- ### Base branch auto-detection
539
-
540
- RWM detects the base branch by reading `git symbolic-ref refs/remotes/origin/HEAD`, falling back to checking for `main` or `master` locally. Override with:
541
-
542
- ```sh
543
- rwm affected --base develop
544
- rwm run spec --affected --base develop
545
- ```
546
-
547
- If the provided `--base` ref doesn't exist, RWM errors immediately instead of silently returning no affected packages.
548
-
549
- ## Bootstrap and daily workflow
550
-
551
- ### What bootstrap does
552
-
553
- `rwm bootstrap` gets a workspace into a working state:
554
-
555
- 1. Runs `bundle install` in the workspace root.
556
- 2. Runs `rake bootstrap` in the root (if defined — for binstubs, shared tooling, etc.).
557
- 3. Installs git hooks (pre-push runs `rwm check`, post-commit rebuilds the graph on Gemfile changes).
558
- 4. Runs `bundle install` in every package (in parallel).
559
- 5. Runs `rake bootstrap` in packages that define it (in parallel).
560
- 6. Builds and validates the dependency graph.
561
- 7. Updates the `.code-workspace` file (if it exists).
562
-
563
- Both `rwm init` and `rwm bootstrap` are idempotent.
564
-
565
- **Note on parallel installs:** Step 4 runs `bundle install` concurrently across packages. If your packages share a gem installation directory (the default), you may see Bundler log `Waiting for another process to let go of lock`. This is normal — Bundler serializes writes to the shared directory automatically. On large monorepos with many packages, this can slow down bootstrap. If this becomes a bottleneck, consider using `BUNDLE_PATH` per-package or running bootstrap sequentially.
566
-
567
- ### The bootstrap rake task
568
-
569
- Every scaffolded package includes an empty `bootstrap` task. This is where package-specific setup belongs:
570
-
571
- ```ruby
572
- # libs/auth/Rakefile
573
- task :bootstrap do
574
- sh "bin/rails db:setup" if File.exist?("bin/rails")
575
- sh "cp config/credentials.example.yml config/credentials.yml" unless File.exist?("config/credentials.yml")
576
- end
577
- ```
578
-
579
- Common uses: database setup, copying example config files, generating local certificates, compiling native extensions.
580
-
581
- The key property: `rwm bootstrap` runs every package's bootstrap task automatically. Developers don't need to know which packages have special setup — they run one command and everything is handled.
582
-
583
- ### After cloning
584
-
585
- ```sh
586
- git clone <repo>
587
- cd <repo>
588
- rwm bootstrap
589
- ```
590
-
591
- Every package is installed, the graph is built, hooks are active, and the workspace is ready.
592
-
593
- ### Daily workflow
594
-
595
- ```sh
596
- git pull --rebase
597
- rwm bootstrap # picks up any new packages or dependency changes
598
- git checkout -b my-feature
599
- # ... make changes ...
600
- rwm spec # run all specs
601
- rwm spec --affected # or just the affected ones
602
- ```
603
-
604
- The pre-push hook runs `rwm check` automatically. The post-commit hook rebuilds the graph when Gemfiles change.
605
-
606
- ## Git hooks
607
-
608
- RWM installs two hooks during `rwm bootstrap`:
609
-
610
- - **pre-push** — Runs `rwm check` to validate conventions before pushing. Blocks the push on failure.
611
- - **post-commit** — Runs `rwm graph` if any Gemfile was changed in the commit. Keeps the cached graph in sync.
612
-
613
- ### Overcommit integration
614
-
615
- If `.overcommit.yml` exists, RWM integrates with [Overcommit](https://github.com/sds/overcommit) — it merges hook configuration into the YAML file and creates executable hook scripts. Without Overcommit, RWM writes directly to `.git/hooks/`, appending to existing hooks rather than overwriting.
616
-
617
- ## Convention enforcement
618
-
619
- ```sh
620
- rwm check
621
- ```
622
-
623
- Three rules:
624
-
625
- 1. **No library depending on an application.** Libraries are shared building blocks and must not be coupled to deployment targets.
626
- 2. **No application depending on another application.** Applications are independent deployment units. Shared code should be extracted into a library.
627
- 3. **No circular dependencies.** Cycles make build ordering impossible and indicate tangled responsibilities.
628
-
629
- Exits 0 on pass, 1 on violation. The pre-push hook runs this automatically.
630
-
631
- ## Rails and Zeitwerk
632
-
633
- ### How workspace libs work in Rails
634
-
635
- Workspace libs declared via `rwm_lib` are path gems. The standard Rails boot sequence handles them automatically:
636
-
637
- 1. `config/boot.rb` calls `Bundler.setup` — adds all gem `lib/` directories to `$LOAD_PATH`
638
- 2. `config/application.rb` calls `Bundler.require(*Rails.groups)` — auto-requires every gem, including workspace libs and their transitive deps
639
- 3. `config/environment.rb` calls `Rails.application.initialize!` — Zeitwerk activates for the app's own code
640
-
641
- By the time Zeitwerk starts in step 3, workspace libs are already loaded as plain Ruby modules. Zeitwerk never touches them — it only manages directories in `config.autoload_paths`.
642
-
643
- **No special setup is needed in `application.rb`.** A standard Rails template works:
644
-
645
- ```ruby
646
- # apps/web/Gemfile
647
- require "rwm/gemfile"
648
-
649
- source "https://rubygems.org"
650
- gemspec
651
-
652
- rwm_lib "auth" # transitive deps resolved automatically
653
- ```
654
-
655
- ```ruby
656
- # apps/web/config/application.rb
657
- require_relative "boot"
658
- require "rails/all"
659
- Bundler.require(*Rails.groups)
660
-
661
- module Web
662
- class Application < Rails::Application
663
- config.load_defaults 8.0
664
- end
665
- end
666
- ```
667
-
668
- That's it. `Bundler.require` loads `auth` and all of its transitive workspace dependencies. No manual `Rwm.require_libs`, no ordering tricks.
669
-
670
- ### A note on Zeitwerk
671
-
672
- > [!IMPORTANT]
673
- > **Correction (v0.6.2):** Documentation in v0.6.1 and earlier incorrectly stated that Zeitwerk overrides `Kernel#require`. This was wrong. Zeitwerk uses `Module#autoload` and `const_missing` to lazily load files from `config.autoload_paths`. A plain `require "auth"` (from `Bundler.require` or anywhere else) works normally at any point during the boot sequence — Zeitwerk does not intercept it.
674
-
675
- ### The practical lib workflow
676
-
677
- **Develop inside your Rails app first.** While a feature is in active development, keep the code in your Rails app's `app/` directory where Zeitwerk gives you hot reloading for free. Change a file, refresh the page, see the result.
678
-
679
- **Extract when stable.** When the code has solidified — the interface is settled, multiple apps could use it, you're not changing it every day — extract it into a workspace lib. This is the natural monorepo rhythm: apps are where you experiment, libs are where you consolidate.
680
-
681
- At extraction time, choose how the lib is structured.
682
-
683
- ### Traditional structure (the default)
684
-
685
- This is what `rwm new lib` scaffolds. The lib's entry point loads all sub-files eagerly with `require_relative`:
686
-
687
- ```ruby
688
- # libs/auth/lib/auth.rb
689
- require_relative "auth/token"
690
- require_relative "auth/user"
691
-
692
- module Auth
693
- VERSION = "0.1.0"
694
- end
695
- ```
696
-
697
- **Pros:** Works everywhere — Rails, non-Rails, any Ruby app. Simple. Standard gem structure.
698
-
699
- **Cons:** No hot reloading in Rails development. After changing a lib file, you restart the server. This is fine for stable extracted code — you're not changing it often.
700
-
701
- This is the right choice for most workspace libs.
702
-
703
- ### Zeitwerk-compatible structure (opt-in)
704
-
705
- Choose this when you're still actively iterating on a lib **and** multiple Rails apps consume it. The lib follows Zeitwerk naming conventions — one constant per file, no `require_relative`:
706
-
707
- ```ruby
708
- # libs/auth/lib/auth.rb
709
- module Auth
710
- end
711
-
712
- # libs/auth/lib/auth/token.rb — defines Auth::Token
713
- # libs/auth/lib/auth/user.rb — defines Auth::User
714
- # Zeitwerk auto-discovers these. No require lines needed.
715
- ```
716
-
717
- Each consuming Rails app opts in by adding the lib to its autoload paths and telling Bundler not to auto-require it:
718
-
719
- ```ruby
720
- # apps/web/Gemfile
721
- rwm_lib "auth", require: false # Bundler won't auto-require
722
- ```
723
-
724
- ```ruby
725
- # apps/web/config/application.rb
726
- module Web
727
- class Application < Rails::Application
728
- config.autoload_paths << Rwm.lib_path("auth")
729
- config.eager_load_paths << Rwm.lib_path("auth")
730
- end
731
- end
732
- ```
733
-
734
- Now Zeitwerk manages `auth` — lazy loading in development (with hot reloading), eager loading in production. Changes to lib files are picked up on the next request without restarting the server.
735
-
736
- **Trade-offs:**
737
-
738
- - All consumer apps must add the lib to their autoload paths — this is a per-app decision
739
- - The lib cannot use `require_relative` for its own files (Zeitwerk must control loading)
740
- - Non-Rails consumers need a different loading strategy (e.g., `Zeitwerk::Loader.for_gem` or a `Dir.glob` require)
741
-
742
- ### What doesn't work
743
-
744
- **Mixing `Bundler.require` and `autoload_paths` for the same lib.** If `Bundler.require` loads a lib (the default) and you also add it to `config.autoload_paths`, the lib's constants are loaded twice — once eagerly by Bundler, once lazily by Zeitwerk. Reloading breaks because Zeitwerk didn't control the initial load. Pick one or the other per lib.
745
-
746
- **Using `require_relative` inside a Zeitwerk-managed lib.** Initial loading works fine — Zeitwerk tolerates other loading mechanisms. But after a Zeitwerk reload cycle (in development), files loaded by `require_relative` are still in `$LOADED_FEATURES`. Ruby's `require_relative` sees them as already loaded and skips them. The constants were removed by Zeitwerk's reload but never re-defined. Result: `NameError`.
747
-
748
- ### `Rwm.require_libs` — when you need it
749
-
750
- For standard Rails apps, `Bundler.require` handles everything. `Rwm.require_libs` exists for edge cases:
751
-
752
- - Non-standard Rails setups that don't call `Bundler.require`
753
- - Non-Rails apps that want to load all workspace libs in one call
754
- - Explicit control over when workspace libs are loaded
755
-
756
- ```ruby
757
- require "rwm/rails"
758
- Rwm.require_libs # requires all libs resolved by rwm_lib, idempotent
759
- ```
760
-
761
- Non-Rails apps don't need any of this — `require` workspace libs from your Gemfile anywhere in your code, as with any gem.
762
-
763
- ## VSCode integration
764
-
765
- ```sh
766
- rwm init --vscode
767
- ```
768
-
769
- Generates a `.code-workspace` file that configures VSCode's multi-root workspace feature. Each package becomes a separate root folder in the sidebar. After initial creation, `rwm bootstrap` and `rwm new` keep the folder list updated automatically. Existing `settings`, `extensions`, `launch`, and `tasks` keys are preserved.
770
-
771
- ## Shell completions
772
-
773
- RWM ships with completion scripts for Bash and Zsh that provide command, flag, and package name completion.
774
-
775
- ### Bash
776
-
777
- Add to `.bashrc` or `.bash_profile`:
778
-
779
- ```bash
780
- source "$(gem contents ruby_workspace_manager | grep rwm.bash)"
781
- ```
782
-
783
- ### Zsh
784
-
785
- Add to `.zshrc` (before `compinit`):
786
-
787
- ```zsh
788
- fpath=($(gem contents ruby_workspace_manager | grep completions/rwm.zsh | xargs dirname) $fpath)
789
- autoload -Uz compinit && compinit
790
- ```
791
-
792
- Both scripts dynamically discover package names by scanning `libs/` and `apps/`, so tab completion always reflects your current workspace.
793
-
794
- ## Command reference
795
-
796
- | Command | Description |
797
- |---------|-------------|
798
- | `rwm init [--vscode]` | Initialize a workspace. Creates dirs, Gemfile, Rakefile, .gitignore. Runs bootstrap. Idempotent. |
799
- | `rwm bootstrap` | Install deps, build graph, install hooks, run bootstrap tasks. Idempotent. |
800
- | `rwm new <app\|lib> <name> [--test=FW]` | Scaffold a new package. `--test`: `rspec` (default), `minitest`, `none`. |
801
- | `rwm info <name>` | Show package details: type, path, deps, dependents. |
802
- | `rwm graph [--dot\|--mermaid]` | Rebuild dependency graph. Optionally output DOT or Mermaid. |
803
- | `rwm check` | Validate conventions. Exit 0 on pass, 1 on failure. |
804
- | `rwm list` | List all packages. |
805
- | `rwm run <task> [pkg]` | Run a Rake task across packages. |
806
- | `rwm <task> [pkg]` | Task shortcut: `rwm spec` = `rwm run spec`. |
807
- | `rwm affected [--committed] [--base REF]` | Show affected packages. |
808
- | `rwm cache clean [pkg]` | Clear cached task results. |
809
- | `rwm help` | Show available commands. |
810
- | `rwm version` | Show version. |
811
-
812
- ### `rwm run` flags
813
-
814
- | Flag | Description |
815
- |------|-------------|
816
- | `--affected` | Only run on packages affected by current changes. |
817
- | `--committed` | With `--affected`, only consider committed changes. |
818
- | `--base REF` | With `--affected`, compare against REF instead of auto-detected base. |
819
- | `--dry-run` | Show what would run without executing. |
820
- | `--no-cache` | Bypass task caching. Force all tasks to run. |
821
- | `--buffered` | Buffer output per-package and print on completion. |
822
- | `--concurrency N` | Limit parallel workers. Default: number of CPU cores. |
83
+ ## Documentation
84
+
85
+ | Guide | Description |
86
+ |-------|-------------|
87
+ | [Getting Started](docs/getting-started.md) | Install, create packages, declare dependencies, build the graph |
88
+ | [Running Tasks](docs/running-tasks.md) | Parallel execution, output modes, failure handling, task caching |
89
+ | [Affected Detection](docs/affected-detection.md) | Change detection, root-level changes, base branch configuration |
90
+ | [Bootstrap](docs/bootstrap.md) | Workspace setup, the bootstrap rake task, daily workflow |
91
+ | [Conventions and Hooks](docs/conventions-and-hooks.md) | The three rules, git hooks, Overcommit integration |
92
+ | [Rails Integration](docs/rails-integration.md) | Zeitwerk, traditional vs compatible structure, `Rwm.require_libs` |
93
+ | [Command Reference](docs/command-reference.md) | All commands, flags, shell completions, VSCode integration |
823
94
 
824
95
  ## Design philosophy
825
96
 
data/lib/rwm/cli.rb CHANGED
@@ -88,14 +88,14 @@ module Rwm
88
88
 
89
89
  Commands:
90
90
  init [--vscode] Initialize a new rwm workspace
91
- bootstrap Install deps and run bootstrap tasks in all packages
91
+ bootstrap [pkg...] Install deps and run bootstrap (all if none given)
92
92
  new <type> <name> Scaffold a new app or lib
93
93
  info <name> Show details about a package
94
94
  graph Build and save the dependency graph
95
95
  --dot Output in Graphviz DOT format
96
96
  --mermaid Output in Mermaid format
97
97
  check Validate dependency graph and conventions
98
- run <task> [pkg] Run a rake task across all (or one) package(s)
98
+ run <task> [pkg...] Run a rake task across packages (all if none given)
99
99
  affected Show packages affected by current changes
100
100
  --base REF Compare against REF instead of auto-detected base
101
101
  --committed Only consider committed changes
@@ -105,8 +105,8 @@ module Rwm
105
105
  version Show version
106
106
 
107
107
  Any unrecognized command is treated as a task name:
108
- rwm test → rwm run test
109
- rwm lint → rwm run lint
108
+ rwm test → rwm run test
109
+ rwm test auth billing → rwm run test auth billing
110
110
 
111
111
  Run options (for `rwm run` and task shortcuts):
112
112
  --affected Only run on affected packages
@@ -5,6 +5,7 @@ module Rwm
5
5
  class Bootstrap
6
6
  def initialize(argv)
7
7
  @argv = argv
8
+ @package_names = argv.dup.uniq
8
9
  end
9
10
 
10
11
  def run
@@ -56,14 +57,31 @@ module Rwm
56
57
  end
57
58
 
58
59
  def bootstrap_packages(workspace, graph)
59
- packages = workspace.packages
60
+ packages = if @package_names.any?
61
+ # Validate all names, then expand to include transitive deps
62
+ @package_names.each { |name| workspace.find_package(name) }
63
+ all_names = Set.new(@package_names)
64
+ @package_names.each do |name|
65
+ graph.transitive_dependencies(name).each { |dep| all_names << dep }
66
+ end
67
+ all_names.map { |name| workspace.find_package(name) }
68
+ else
69
+ workspace.packages
70
+ end
71
+
60
72
  if packages.empty?
61
73
  puts "==> No packages found. Skipping package bootstrap."
62
74
  return
63
75
  end
64
76
 
65
77
  # Step 1: bundle install in all packages (parallel by execution level)
66
- puts "==> Installing gems in #{packages.size} package(s)..."
78
+ dep_count = packages.size - (@package_names.any? ? @package_names.uniq.size : 0)
79
+ label = if @package_names.any? && dep_count > 0
80
+ "==> Installing gems in #{packages.size} package(s) (#{@package_names.join(", ")} + #{dep_count} dependencies)..."
81
+ else
82
+ "==> Installing gems in #{packages.size} package(s)..."
83
+ end
84
+ puts label
67
85
  install_runner = TaskRunner.new(graph, packages: packages)
68
86
  install_runner.run_command do |pkg|
69
87
  ["bundle", "install"]
@@ -29,7 +29,7 @@ module Rwm
29
29
  graph.packages.each_value do |pkg|
30
30
  deps = graph.edges[pkg.name] || []
31
31
  dep_str = deps.empty? ? "" : " → #{deps.join(", ")}"
32
- puts " #{pkg.type == "lib" ? "lib" : "app"}/#{pkg.name}#{dep_str}"
32
+ puts " #{pkg.lib? ? "lib" : "app"}/#{pkg.name}#{dep_str}"
33
33
  end
34
34
  end
35
35
  end
@@ -21,17 +21,23 @@ module Rwm
21
21
  task = @argv.shift
22
22
 
23
23
  unless task
24
- $stderr.puts "Usage: rwm run <task> [<package>] [--affected] [--base REF] [--dry-run] [--no-cache] [--buffered] [--concurrency N]"
24
+ $stderr.puts "Usage: rwm run <task> [<package>...] [--affected] [--base REF] [--dry-run] [--no-cache] [--buffered] [--concurrency N]"
25
25
  return 1
26
26
  end
27
27
 
28
- package_name = @argv.shift
28
+ package_names = @argv.dup.uniq
29
+ @argv.clear
30
+
31
+ if package_names.any? && @affected_only
32
+ $stderr.puts "Error: --affected and explicit package names are mutually exclusive."
33
+ return 1
34
+ end
29
35
 
30
36
  workspace = Workspace.find
31
37
  graph = DependencyGraph.load(workspace)
32
38
 
33
- packages = if package_name
34
- [workspace.find_package(package_name)]
39
+ packages = if package_names.any?
40
+ package_names.map { |name| workspace.find_package(name) }
35
41
  elsif @affected_only
36
42
  detector = AffectedDetector.new(workspace, graph, committed_only: @committed_only, base_branch: @base_branch)
37
43
  affected = detector.affected_packages
@@ -57,6 +57,24 @@ module Rwm
57
57
  visited.to_a
58
58
  end
59
59
 
60
+ # Walk the graph to find all transitive dependencies (what a package transitively depends on)
61
+ def transitive_dependencies(name)
62
+ visited = Set.new
63
+ queue = [name]
64
+
65
+ until queue.empty?
66
+ current = queue.shift
67
+ dependencies(current).each do |dep|
68
+ next if visited.include?(dep)
69
+
70
+ visited << dep
71
+ queue << dep
72
+ end
73
+ end
74
+
75
+ visited.to_a
76
+ end
77
+
60
78
  # Topological sort (dependencies before dependents)
61
79
  def topological_order
62
80
  tsort
data/lib/rwm/rake.rb CHANGED
@@ -45,7 +45,19 @@ module Rwm
45
45
  end
46
46
 
47
47
  # Top-level DSL method available in Rakefiles
48
- def cacheable_task(name, output: nil, &block)
49
- Rwm::RakeCache.register(name, output: output)
50
- Rake::Task.define_task(name, &block)
48
+ def cacheable_task(*args, **opts, &block)
49
+ output = opts.delete(:output)
50
+
51
+ # Remaining keyword opts are Rake dependency syntax (e.g. seed: :environment)
52
+ args << opts unless opts.empty?
53
+
54
+ # Resolve the task name using Rake's own parser (dup because resolve_args mutates)
55
+ task_name, = Rake.application.resolve_args(args.dup)
56
+
57
+ Rwm::RakeCache.register(task_name, output: output)
58
+
59
+ # Clear existing actions so we replace rather than stack (e.g. rspec-rails :spec)
60
+ Rake::Task[task_name].clear_actions if Rake::Task.task_defined?(task_name)
61
+
62
+ Rake::Task.define_task(*args, &block)
51
63
  end
@@ -132,7 +132,7 @@ module Rwm
132
132
  end
133
133
 
134
134
  Rwm.debug("cache declarations: discovering for #{package.name}")
135
- output, _, status = Open3.capture3("bundle", "exec", "rake", "rwm:cache_config", chdir: package.path)
135
+ output, _, status = Open3.capture3(Rwm.bundle_env(package.path), "bundle", "exec", "rake", "rwm:cache_config", chdir: package.path)
136
136
  result = if status.success? && !output.strip.empty?
137
137
  JSON.parse(output.strip)
138
138
  else
@@ -154,7 +154,7 @@ module Rwm
154
154
  prefix = "[#{pkg.name}]"
155
155
  Rwm.debug("running: #{cmd.join(' ')} in #{pkg.path}")
156
156
 
157
- stdout, stderr, status = Open3.capture3(*cmd, chdir: pkg.path)
157
+ stdout, stderr, status = Open3.capture3(Rwm.bundle_env(pkg.path), *cmd, chdir: pkg.path)
158
158
  output = format_output(prefix, stdout, stderr)
159
159
 
160
160
  # Detect "task not found" and treat as skipped, not failed
data/lib/rwm/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Rwm
4
- VERSION = "0.6.3"
4
+ VERSION = "0.6.4"
5
5
  end
data/lib/rwm.rb CHANGED
@@ -18,6 +18,14 @@ module Rwm
18
18
  $stderr.puts "[rwm debug] #{msg}" if @verbose
19
19
  end
20
20
 
21
+ # Environment hash that points BUNDLE_GEMFILE at a specific directory's Gemfile.
22
+ # Pass as the first argument to Open3.capture3 or system() when spawning
23
+ # bundle commands in package directories, so the child process resolves
24
+ # against the package's Gemfile instead of inheriting the root's.
25
+ def self.bundle_env(dir)
26
+ { "BUNDLE_GEMFILE" => File.join(dir, "Gemfile") }
27
+ end
28
+
21
29
  autoload :Workspace, "rwm/workspace"
22
30
  autoload :Package, "rwm/package"
23
31
  autoload :GemfileParser, "rwm/gemfile_parser"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ruby_workspace_manager
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.6.3
4
+ version: 0.6.4
5
5
  platform: ruby
6
6
  authors:
7
7
  - Siddharth Bhatt