Skip to content

Add --resume, --update, and BIDS entity filters to dataset download - #370

Merged
neuromechanist merged 11 commits into
devfrom
feature/issue-347-348-365-download-ux
Apr 27, 2026
Merged

neuromechanist merged 11 commits into
devfrom
feature/issue-347-348-365-download-ux

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Summary

Three downloads UX improvements bundled in one feature branch as discussed:

Closes #347
Closes #348
Closes #365

Design choices

  • Filter pass-through to git-annex. Instead of writing a JS BIDS parser, each flag becomes a small list of --include/--exclude globs joined with -( … --or … -) group operators. ~50 LOC instead of ~250, and git-annex does what it was built for.
  • Entity normalization. Accept 01 and sub-01 interchangeably; bare values get auto-prefixed.
  • Run zero-padding. --runs 1 matches both run-1 and run-01 (expanded into both globs).
  • --no-data × filters is an error. Filters imply data download — combining them is a contradiction.
  • --prune semantics. After git merge --ff-only removes upstream-deleted files, their annex keys become orphans. --prune runs git annex unused + git annex dropunused all to reclaim space.
  • Essential BIDS root files (dataset_description.json, participants.tsv, README, etc.) are already excluded from the annex by the project's largefiles config and land via plain git clone. No special-casing needed.

Files

File Purpose
src/commands/dataset.ts wire flags into the download action; mutex checks; resume/update branches
src/lib/git-annex.ts new helpers: readLocalDatasetVersion, readRemoteHeadDatasetVersion, isWorkingTreeDirty, gitFetchOrigin, gitMergeFastForward, dropUnusedAnnexObjects, resolveUpstreamRef; getDatasetData accepts extraArgs
src/lib/manifest-diff.ts new pure helper: diff two VersionManifests into added/changed/removed
src/lib/bids-filter.ts new pure helper: translate flag values into git-annex matching args
test/bids-filter.test.ts 18 unit tests (no mocks)
test/manifest-diff.test.ts 6 unit tests (no mocks)
docs/guides/downloading.md + scripts/generate-docs.ts user-facing docs for the new flags

Notable upstream-ref fallback

--update's merge step uses resolveUpstreamRef which prefers the current branch's configured upstream and falls back to origin/HEAD → origin/main → origin/master, so older datasets that still use master (e.g. nm000109 per CLAUDE.md) keep working. --update also refuses git-annex adjusted branches and points to git annex sync instead, since a plain merge would corrupt the adjusted view.

Testing

Unit tests (no mocks per project policy):

  • bun test test/bids-filter.test.ts test/manifest-diff.test.ts — 24/24 pass
  • bun run typecheck — clean
  • bun run build — succeeds

Integration tests against nm099999:

  • --subjects sub-01 cloned full repo + fetched only the matching annex file
  • --resume against the resulting clone validated target, refreshed credentials, ran git annex get (0 files since complete)
  • --update resolved origin/main via the new resolver and fast-forwarded successfully
  • Wrong dataset id and non-git-annex dir error paths fire correctly

git-annex argv smoke test:

  • Built a temp annex with sub-01/sub-02/sub-03/derivatives, ran git annex find -( --include='sub-01/**' --or --include='sub-02/**' -) and confirmed it matches only sub-01 + sub-02. This validates that Bun's spawn correctly passes -( -) as separate argv items.

Test plan

  • Pull a known multi-version dataset and run --update to exercise the manifest-diff path with non-empty added/changed sets
  • Run --update --prune on a dataset with upstream-removed files; verify dropunused count
  • Try --exclude 'derivatives/**' against a dataset with derivatives to confirm exclusion
  • Smoke-test the help text formatting in your terminal

Resume mode reuses an existing partial clone instead of refusing to
proceed when the output directory exists. Validates the directory is a
git-annex repo for the requested dataset, refuses on dirty trees, and
refuses when local DatasetVersion has fallen behind remote HEAD
(directing the user to --update).

Adds helpers in lib/git-annex.ts: readLocalDatasetVersion,
readRemoteHeadDatasetVersion, isWorkingTreeDirty, gitFetchOrigin,
gitMergeFastForward, dropUnusedAnnexObjects (last three used by
--update / --prune in subsequent commits).

getDatasetData gains an extraArgs option for callers that need to
inject git-annex matching flags (used by BIDS filters).
--update reuses an existing clone, fast-forwards to origin/HEAD, and
runs git-annex get only on the annex keys that changed between local
and remote DatasetVersion. For a 5 GB dataset with a 20 MB metadata
bump, this pulls ~20 MB instead of 5 GB.

Behavior:
  - Validates the target as in --resume (git-annex repo, correct id,
    clean tree).
  - Fetches origin, reads local + remote DatasetVersion. Equal versions
    exit with 'already up to date'.
  - Pulls both manifests via getManifest and computes added / changed /
    removed paths. Falls back to a full git annex get if either manifest
    is missing (older datasets).
  - git merge --ff-only origin/HEAD; refuses non-fast-forward merges
    and points the user at 'nemar dataset update' (PR workflow).
  - --prune drops orphan annex objects via 'git annex unused' +
    'git annex dropunused' after the merge has unreferenced them.

--resume and --update are mutually exclusive; --prune requires --update.

Adds src/lib/manifest-diff.ts with the pure diffManifests helper.
New flags on `nemar dataset download` translate BIDS entities into
git-annex --include / --exclude / --or / -( -) so the clone stays a
structurally valid BIDS dataset (full git-annex tree, all symlinks
present) but only matching files have content locally.

Flags (all comma-separated):
  --subjects sub-01,02         (auto-prefix; "01" -> "sub-01")
  --sessions ses-pre,post
  --tasks rest,nback
  --runs 1,2                   (unpadded 1-9 expand to padded + unpadded)
  --datatypes eeg,emg
  --include 'sub-01/eeg/*.edf' (raw glob pass-through)
  --exclude 'derivatives/**'   (raw glob pass-through)

Each entity group is OR'd internally; distinct groups AND together via
git-annex's default combining. Filters compose with --update (only the
changed files within the filter scope) and --resume.

--no-data + filters is rejected as a contradiction. Essential BIDS root
files (dataset_description.json, README, participants.tsv, etc.) are
already excluded from the annex by the project largefiles config and
land via plain git clone, so no special-casing is needed.

Tests: pure unit coverage for the flag-to-glob translator and the
manifest diff helper (24 + 6 cases, no mocks).
Adds the new download flags (and their semantics) to the user-facing
downloading guide. Updates scripts/generate-docs.ts so future
`bun run docs:generate` runs preserve these sections.
The previous version of --update merged 'origin/HEAD' unconditionally.
That symbolic ref can be absent in some clones and would have failed on
older nemarDatasets repos that still use 'master' as the default
branch (per CLAUDE.md, nm000109 has master; nm000110-114 use
adjusted/master(unlocked)).

resolveUpstreamRef now prefers the configured upstream of the current
branch (`git rev-parse --abbrev-ref @{upstream}`) and falls back to
origin/HEAD, origin/main, origin/master in turn. --update also refuses
to run on git-annex adjusted branches and points the user at
'git annex sync' instead, since a plain merge would corrupt the
adjusted view.

Verified end-to-end against nm099999: --subjects filters at fetch
time, --resume reuses an existing clone, --update fast-forwards via
the resolver.
Previously the helper returned false on any non-zero exit from
'git status --porcelain', so a corrupt index, missing repo, or
.git/index.lock contention silently masqueraded as a clean tree
and let --resume / --update proceed.

Switch to {dirty, error?} so callers can distinguish 'definitely
clean' from 'could not determine'. The download action now exits
non-zero with the underlying stderr in the latter case.

Addresses PR #370 review (silent-failure-hunter, finding #1).
readLocalDatasetVersion now returns {version, error?} and
readRemoteHeadDatasetVersion returns {version, warnings[]}, so
malformed dataset_description.json files and unexpected git
failures are no longer silently treated as 'no version
configured'.

The download action prints any errors / warnings as yellow
chalk lines before falling through, keeping the existing
'unknown -> HEAD' behavior for legitimately missing fields.
The remote reader still treats 'unknown revision' / 'bad
revision' messages as expected (the fallback chain is meant to
probe missing refs); only unexpected stderr is reported.

Also distinguishes auth (401/403) and 404 from generic 5xx in
the manifest-diff fallback so users get an actionable hint
instead of a vague 'falling back to full get'.

Addresses PR #370 review (silent-failure-hunter, findings #2 #3 #4).
git annex unused walks reachability from all refs, so stale
local tags pointing at removed dataset versions kept their
annex keys 'reachable' and survived the prune. The user-visible
effect was --prune dropping fewer (or zero) objects despite
ostensibly cleaning up after a version bump.

Run 'git fetch --prune --prune-tags origin' inside
dropUnusedAnnexObjects (only on the prune path), so --resume
and the ordinary --update fetch are unaffected.

Addresses PR #370 review (code-reviewer, finding #2).
If the user had an interrupted v1.0.0 clone (where only some
annex content landed) and then runs --update to v1.1.0, the
diff-only get pulls just the changes between versions and
silently leaves the original gaps in place. The completion
message now points at --resume to fill those gaps.

Cheaper than detecting pre-existing missing content (which
would mean running 'git annex find --not --in=here' twice and
diffing).

Addresses PR #370 review (code-reviewer, finding #1).
…tVersion against real git

Each test creates a fresh temp git repo with mkdtempSync and
shells out to git for real (no mocks per project policy).

isWorkingTreeDirty: clean repo, modified-tracked, untracked,
non-repo (error case).

resolveUpstreamRef: cloned repo with configured upstream
(origin/HEAD or origin/main), repo with no remote (returns null
+ error).

readLocalDatasetVersion: missing file, malformed JSON, missing
DatasetVersion field, valid version.

10/10 pass. Addresses PR #370 review (pr-test-analyzer, gaps
#1, #2, #4).
Per project policy (default to no comments unless WHY is
non-obvious): trim JSDoc that just restated function names or
referenced calling flows.

- manifest-diff.ts module header: violated 'no PR-flow refs'
  rule and restated the type. Kept the WHY note about
  content-addressed keys on diffManifests.
- ManifestDiff field comments: tautological with the names.
- gitFetchOrigin / gitMergeFastForward / dropUnusedAnnexObjects
  JSDoc: pure restatement of the bodies.
- 'Mutex / dependency checks for the new download flags' inline
  comment: 'for the new flags' is exactly the banned 'added for
  X' phrasing.

Kept all WHY-bearing comments: adjusted-branch corruption note,
fallback-chain rationale on resolveUpstreamRef,
dataset_description.json lookup contract on
readLocalDatasetVersion, etc.

Addresses PR #370 review (comment-analyzer, items #4 #5 #7 #8 #9 #19).
@github-actions

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR370

Version: 0.8.2-PR370.6aff939
Commit: 6aff939


🤖 Updated on each push.

@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review response

Ran /review-pr with all five subagents in parallel (code, tests, comments, errors, types). Aggregated findings + advisor synthesis below. 6 follow-up commits pushed.

Addressed (commits c4dcb8b → 6aff939)

Finding Severity Source Commit
isWorkingTreeDirty returns false on git failure critical (per reviewer) silent-failure c4dcb8b
readLocalDatasetVersion empty catch important silent-failure 8bbe5d0
readRemoteHeadDatasetVersion empty catch + git-failure conflated with ref-missing important silent-failure 8bbe5d0
Manifest-diff fallback masks 401/403/5xx important silent-failure 8bbe5d0
--prune undermined by stale local tags important code 0c3615a
--update after partial v1.0.0 leaves gaps important code 70abfb1 (completion-message hint, not detection)
Missing tests for isWorkingTreeDirty / resolveUpstreamRef / readLocalDatasetVersion important tests 44d5806 (10 new tests, real-git tmpdirs, no mocks)
Redundant JSDoc on new helpers suggestion comments 6aff939 (5 trims, kept the WHY ones)

Skipped with rationale

Verification

  • bun test test/manifest-diff.test.ts test/bids-filter.test.ts test/git-helpers.test.ts — 34/34 pass
  • bun run typecheck — clean
  • bun run build — succeeds
  • Mutex error paths (--resume --update, --prune without --update, --no-data + filter) still fire correctly

Commit list

6aff939 style: drop redundant JSDoc on new helpers
44d5806 test: cover isWorkingTreeDirty / resolveUpstreamRef / readLocalDatasetVersion
70abfb1 docs: hint at --resume after --update for partial prior downloads
0c3615a fix: prune stale tags before --update --prune walk
8bbe5d0 fix: surface JSON parse + git errors in version readers
c4dcb8b fix: surface git status errors in isWorkingTreeDirty

@neuromechanist
neuromechanist merged commit cf3853f into dev Apr 27, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-347-348-365-download-ux branch April 27, 2026 22:14

This branch was previously deployed

1 inactive deployment
npm — 6aff939c Deployed Apr 27, 2026 by neuromechanist via publish #649
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant