diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..a13fdbe --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,70 @@ +--- +name: Bug report +about: Report incorrect behavior, regressions, or integration problems +title: "bug: " +labels: [bug] +assignees: [] +--- + +## Summary + +What happened? + +## Reproduction + +Provide the smallest reproduction you can. + +```nix +# Minimal flake/module/home-manager snippet if relevant +``` + +Steps: + +1. +2. +3. + +## Expected Behavior + +What should have happened? + +## Actual Behavior + +What happened instead? + +Include the exact error message if there is one. + +```text +paste error output here +``` + +## Configuration Context + +- Deferred Apps mode: `packages` / `apps` / `cliPackages` / `cliApps` / `extraApps` +- Target: `NixOS` / `Home Manager standalone` / `Home Manager on NixOS` +- Package or app name(s): +- `allowUnfree` used?: yes / no / not relevant +- `gcRoot` used?: yes / no +- Custom `flakeRef` used?: yes / no +- Custom `extraApps` overrides used?: yes / no + +## Environment + +- System: `x86_64-linux`, `aarch64-linux`, etc. +- Nix version: +- NixOS release (if applicable): +- Home Manager release (if applicable): +- Deferred Apps revision/commit: + +## Checks + +What did you already try? + +- [ ] `nix flake check` +- [ ] `nixos-rebuild build` or `home-manager build` +- [ ] reproduced with a minimal configuration +- [ ] checked whether the package works without Deferred Apps + +## Additional Context + +Anything else that would help diagnose the issue? diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..033f730 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Questions and design discussion + url: https://github.com/WitteShadovv/deferred-apps/discussions + about: Use Discussions for open-ended questions or early design exploration. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..8fa4a0b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,45 @@ +--- +name: Feature request +about: Propose a new capability or improvement +title: "feat: " +labels: [enhancement] +assignees: [] +--- + +## Summary + +What would you like to add or improve? + +## Problem + +What limitation or pain point does this solve? + +## Proposed Approach + +Describe the preferred behavior. + +If relevant, include example configuration: + +```nix +programs.deferredApps = { + enable = true; +}; +``` + +## Alternatives Considered + +What workarounds exist today? + +## Impact + +Please note any likely impact on: + +- module options +- wrapper behavior +- closure size +- documentation +- backward compatibility + +## Additional Context + +Links, prior art, or related issues. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..8c67993 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,22 @@ +## Summary + +- + +## Validation + +- [ ] `nix flake check` +- [ ] `statix check .` +- [ ] `deadnix --fail -L .` +- [ ] `nix fmt . -- --check` + +## Definition of Done + +- [ ] scope is focused and reviewable +- [ ] tests added or updated when behavior changed +- [ ] docs updated for any user-facing change +- [ ] examples and option names match the current implementation +- [ ] no accidental closure-size or dependency regression introduced + +## Notes for Reviewers + +- diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9141e84..56f8ebf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,28 +30,30 @@ jobs: permissions: pull-requests: read outputs: - nix: ${{ steps.filter.outputs.nix }} - docs: ${{ steps.filter.outputs.docs }} + quality: ${{ steps.filter.outputs.quality }} steps: - uses: actions/checkout@v4 - uses: dorny/paths-filter@v3 id: filter with: filters: | - nix: + quality: - '**/*.nix' - 'flake.lock' - docs: - '**/*.md' - 'LICENSE' + - '.github/ISSUE_TEMPLATE/**' + - '.github/workflows/**' + - 'scripts/**' + - '.pre-commit-config.yaml' # =========================================================================== - # Core Nix checks - runs flake check which includes module evaluation + # Canonical quality gates for local and CI validation # =========================================================================== - flake-check: - name: Flake check + quality-gates: + name: Quality gates needs: changes - if: ${{ needs.changes.outputs.nix == 'true' || github.event_name == 'workflow_dispatch' }} + if: ${{ needs.changes.outputs.quality == 'true' || github.event_name == 'workflow_dispatch' }} runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -68,187 +70,21 @@ jobs: with: fail-mode: true - - name: Run flake checks - run: nix flake check --print-build-logs - - # =========================================================================== - # Code formatting - ensures consistent style - # =========================================================================== - formatting: - name: Check formatting - needs: changes - if: ${{ needs.changes.outputs.nix == 'true' || github.event_name == 'workflow_dispatch' }} - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - name: Install Nix - uses: cachix/install-nix-action@v31 - with: - extra_nix_config: | - experimental-features = nix-command flakes - - - name: Check Nix formatting - run: | - echo "Checking Nix file formatting with nixfmt-rfc-style..." - # Find all .nix files and check formatting - find . -name '*.nix' -type f | xargs nix develop .#ci --command nixfmt --check - - # =========================================================================== - # Static analysis - linting and dead code detection - # =========================================================================== - lint: - name: Lint - needs: changes - if: ${{ needs.changes.outputs.nix == 'true' || github.event_name == 'workflow_dispatch' }} - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - name: Install Nix - uses: cachix/install-nix-action@v31 - with: - extra_nix_config: | - experimental-features = nix-command flakes - - - name: Run statix (Nix linter) - run: | - echo "Running statix for Nix lints and suggestions..." - nix develop .#ci --command statix check . - - - name: Run deadnix (unused code detector) - run: | - echo "Checking for unused Nix code with deadnix..." - # -L: Don't check lambda attrset pattern names (nixpkgs callPackage compatibility) - nix develop .#ci --command deadnix --fail -L . - - # =========================================================================== - # Test suite - comprehensive tests for library, module, and edge cases - # =========================================================================== - test-suite: - name: Test suite - needs: changes - if: ${{ needs.changes.outputs.nix == 'true' || github.event_name == 'workflow_dispatch' }} - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - name: Install Nix - uses: cachix/install-nix-action@v31 - with: - extra_nix_config: | - experimental-features = nix-command flakes - - - name: List all test cases - run: | - echo "Available test cases in tests/ directory:" - nix eval .#checks.x86_64-linux --apply 'checks: builtins.attrNames checks' --json | jq -r '.[]' | sort - - - name: Run internal function tests - run: | - echo "Running internal function tests..." - for check in $(nix eval .#checks.x86_64-linux --apply 'checks: builtins.attrNames checks' --json | jq -r '.[]' | grep '^internal-'); do - echo " Building: $check" - nix build ".#checks.x86_64-linux.$check" --print-build-logs - done - echo "✓ All internal function tests passed" - - - name: Run library tests - run: | - echo "Running library function tests..." - for check in $(nix eval .#checks.x86_64-linux --apply 'checks: builtins.attrNames checks' --json | jq -r '.[]' | grep '^lib-'); do - echo " Building: $check" - nix build ".#checks.x86_64-linux.$check" --print-build-logs - done - echo "✓ All library tests passed" - - - name: Run nested package tests - run: | - echo "Running nested package tests..." - for check in $(nix eval .#checks.x86_64-linux --apply 'checks: builtins.attrNames checks' --json | jq -r '.[]' | grep '^nested-'); do - echo " Building: $check" - nix build ".#checks.x86_64-linux.$check" --print-build-logs - done - echo "✓ All nested package tests passed" - - - name: Run collision detection tests - run: | - echo "Running collision detection tests..." - for check in $(nix eval .#checks.x86_64-linux --apply 'checks: builtins.attrNames checks' --json | jq -r '.[]' | grep '^collision-'); do - echo " Building: $check" - nix build ".#checks.x86_64-linux.$check" --print-build-logs - done - echo "✓ All collision detection tests passed" - - - name: Run module tests - run: | - echo "Running NixOS module tests..." - for check in $(nix eval .#checks.x86_64-linux --apply 'checks: builtins.attrNames checks' --json | jq -r '.[]' | grep '^module-'); do - echo " Building: $check" - nix build ".#checks.x86_64-linux.$check" --print-build-logs - done - echo "✓ All module tests passed" - - - name: Run Home Manager tests - run: | - echo "Running Home Manager module tests..." - for check in $(nix eval .#checks.x86_64-linux --apply 'checks: builtins.attrNames checks' --json | jq -r '.[]' | grep '^hm-'); do - echo " Building: $check" - nix build ".#checks.x86_64-linux.$check" --print-build-logs - done - echo "✓ All Home Manager tests passed" - - - name: Run error handling tests - run: | - echo "Running error handling tests..." - for check in $(nix eval .#checks.x86_64-linux --apply 'checks: builtins.attrNames checks' --json | jq -r '.[]' | grep '^error-'); do - echo " Building: $check" - nix build ".#checks.x86_64-linux.$check" --print-build-logs - done - echo "✓ All error handling tests passed" - - - name: Run compatibility tests - run: | - echo "Running compatibility tests..." - for check in $(nix eval .#checks.x86_64-linux --apply 'checks: builtins.attrNames checks' --json | jq -r '.[]' | grep '^compat-'); do - echo " Building: $check" - nix build ".#checks.x86_64-linux.$check" --print-build-logs - done - echo "✓ All compatibility tests passed" - - - name: Run meta and integration tests - run: | - echo "Running meta and integration tests..." - for check in $(nix eval .#checks.x86_64-linux --apply 'checks: builtins.attrNames checks' --json | jq -r '.[]' | grep -E '^(meta-|integration-)'); do - echo " Building: $check" - nix build ".#checks.x86_64-linux.$check" --print-build-logs - done - echo "✓ All meta and integration tests passed" - - - name: Run package mode tests - run: | - echo "Running package mode tests..." - for check in $(nix eval .#checks.x86_64-linux --apply 'checks: builtins.attrNames checks' --json | jq -r '.[]' | grep '^pkg-'); do - echo " Building: $check" - nix build ".#checks.x86_64-linux.$check" --print-build-logs - done - echo "✓ All package mode tests passed" + - name: Run canonical quality gates + run: ./scripts/quality-gates.sh # =========================================================================== # Summary job - provides clear status # =========================================================================== ci-success: name: CI Success - needs: [flake-check, formatting, lint, test-suite] + needs: [quality-gates] if: always() runs-on: ubuntu-latest steps: - name: Check all jobs passed run: | - if [[ "${{ needs.flake-check.result }}" == "failure" ]] || \ - [[ "${{ needs.formatting.result }}" == "failure" ]] || \ - [[ "${{ needs.lint.result }}" == "failure" ]] || \ - [[ "${{ needs.test-suite.result }}" == "failure" ]]; then + if [[ "${{ needs.quality-gates.result }}" == "failure" ]]; then echo "One or more CI jobs failed" exit 1 fi diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml new file mode 100644 index 0000000..0fdf0ad --- /dev/null +++ b/.github/workflows/prepare-release.yml @@ -0,0 +1,58 @@ +name: Prepare Release + +on: + workflow_dispatch: + inputs: + version: + description: Release version (for example 0.4.0 or v0.4.0) + required: true + type: string + ref: + description: Branch or commit to prepare from + required: false + default: main + type: string + +permissions: + contents: write + pull-requests: write + +jobs: + prepare: + name: Prepare release README update + runs-on: ubuntu-latest + steps: + - name: Checkout target ref + uses: actions/checkout@v4 + with: + ref: ${{ inputs.ref }} + fetch-depth: 0 + + - name: Install Nix + uses: cachix/install-nix-action@v31 + with: + extra_nix_config: | + accept-flake-config = true + experimental-features = nix-command flakes + + - name: Update README release snippets + run: ./scripts/prepare-release.sh --version "${{ inputs.version }}" + + - name: Run canonical quality gates + run: ./scripts/quality-gates.sh + + - name: Create release preparation pull request + uses: peter-evans/create-pull-request@v7 + with: + token: ${{ secrets.GITHUB_TOKEN }} + branch: release/prepare-${{ inputs.version }} + delete-branch: true + commit-message: "docs: prepare release ${{ inputs.version }}" + title: "docs: prepare release ${{ inputs.version }}" + body: | + ## Summary + - update README non-flake `fetchTarball` examples for `${{ inputs.version }}` + - pin the examples to the deterministic release source tarball asset and computed Nix hash + - validate the repository with the canonical quality gates + add-paths: | + README.md diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 72e13eb..b9bac1d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -35,27 +35,12 @@ jobs: accept-flake-config = true experimental-features = nix-command flakes - - name: Validate flake - run: nix flake check --print-build-logs + - name: Run canonical quality gates + run: ./scripts/quality-gates.sh - - name: Check formatting + - name: Verify release README metadata run: | - find . -name '*.nix' -type f | xargs nix develop .#ci --command nixfmt --check - - - name: Run linters - run: | - nix develop .#ci --command statix check . - nix develop .#ci --command deadnix --fail -L . - - - name: Build key checks - run: | - # Run a representative subset of checks to validate the release - # Full test suite runs via 'nix flake check' above - nix build .#checks.x86_64-linux.lib-basic - nix build .#checks.x86_64-linux.lib-mkDeferredApps - nix build .#checks.x86_64-linux.module-apps-only - nix build .#checks.x86_64-linux.nested-basic - nix build .#checks.x86_64-linux.integration-full-build + ./scripts/prepare-release.sh --version "${GITHUB_REF#refs/tags/}" --ref "$GITHUB_SHA" --check # =========================================================================== # Create GitHub release @@ -70,12 +55,19 @@ jobs: with: fetch-depth: 0 - - name: Extract version from tag - id: version + - name: Resolve release metadata + id: metadata + run: | + TAG=$(./scripts/release-metadata.sh --version "${GITHUB_REF#refs/tags/}" --field tag) + VERSION=$(./scripts/release-metadata.sh --version "$TAG" --field version) + ASSET_NAME=$(./scripts/release-metadata.sh --version "$TAG" --field asset-name) + echo "tag=$TAG" >> "$GITHUB_OUTPUT" + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + echo "asset_name=$ASSET_NAME" >> "$GITHUB_OUTPUT" + + - name: Create release source tarball run: | - VERSION=${GITHUB_REF#refs/tags/v} - echo "version=$VERSION" >> $GITHUB_OUTPUT - echo "tag=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT + ./scripts/create-release-source-tarball.sh --version "${{ steps.metadata.outputs.tag }}" --ref "$GITHUB_SHA" - name: Generate release notes id: notes @@ -94,29 +86,32 @@ jobs: # Write to file for multiline handling cat > release-notes.md << EOF ## Installation - + Add to your \`flake.nix\`: \`\`\`nix { - inputs.deferred-apps.url = "github:WitteShadovv/deferred-apps/${{ steps.version.outputs.tag }}"; + inputs.deferred-apps.url = "github:WitteShadovv/deferred-apps/${{ steps.metadata.outputs.tag }}"; } \`\`\` - + + For non-flake installs, use the release source tarball asset published with this release. + ## Changes $CHANGELOG ## Full Documentation - - See [README.md](https://github.com/WitteShadovv/deferred-apps/blob/${{ steps.version.outputs.tag }}/README.md) for complete usage instructions. + + See [README.md](https://github.com/WitteShadovv/deferred-apps/blob/${{ steps.metadata.outputs.tag }}/README.md) for complete usage instructions. EOF - name: Create GitHub Release uses: softprops/action-gh-release@v2 with: - name: "v${{ steps.version.outputs.version }}" + name: "v${{ steps.metadata.outputs.version }}" body_path: release-notes.md + files: dist/${{ steps.metadata.outputs.asset_name }} draft: false - prerelease: ${{ contains(steps.version.outputs.version, '-') }} + prerelease: ${{ contains(steps.metadata.outputs.version, '-') }} generate_release_notes: false diff --git a/.gitignore b/.gitignore index 32a3f28..00ff69b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ # Nix build outputs result result-* +dist/ # Editor files *.swp diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..ad9c84e --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,34 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v5.0.0 + hooks: + - id: check-added-large-files + - id: check-executables-have-shebangs + - id: check-merge-conflict + - id: check-shebang-scripts-are-executable + - id: check-yaml + - id: end-of-file-fixer + - id: mixed-line-ending + - id: trailing-whitespace + + - repo: local + hooks: + - id: bash-syntax + name: bash -n + entry: bash -n + language: system + files: ^scripts/.*\.sh$ + + - id: nix-format-check + name: nix fmt -- --check + entry: bash -c 'nix fmt . -- --check' + language: system + files: \.nix$ + pass_filenames: false + + - id: quality-gates + name: canonical quality gates + entry: ./scripts/quality-gates.sh + language: system + pass_filenames: false + stages: [manual] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..a1c54a5 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,150 @@ +# Contributing to Deferred Apps + +Thanks for contributing. + +Deferred Apps is a small project with a strict bar for correctness: wrappers must stay lightweight, documentation must match behavior, and contributor changes should be easy to review. + +## Before You Start + +- Read the [README](README.md) for user-facing behavior and examples. +- Read [TESTING.md](TESTING.md) before changing code or tests. +- If you are changing core behavior, skim `AGENTS.md` for architecture notes and common pitfalls. +- Keep changes focused. Small, reviewable patches are preferred. + +## Development Setup + +### Requirements + +- [Nix](https://nixos.org/) +- Flakes enabled +- A Linux environment for the full test and module workflow + +### Enter the development shell + +```bash +nix develop +``` + +This provides the tools used by local checks and CI. + +## Recommended Workflow + +1. Start from a clean branch. +2. Understand the requirement before editing code. +3. Add or update tests first when behavior changes. +4. Implement the smallest change that satisfies the requirement. +5. Update docs in the same patch when user-facing behavior or options change. +6. Run local quality gates before opening a PR. + +## Required Quality Gates + +Run these before submitting a pull request: + +```bash +nix flake check +statix check . +deadnix --fail -L . +nix fmt . -- --check +``` + +If any check fails, fix it before requesting review. + +## Testing Expectations + +### When tests are required + +Add or update tests for: + +- library behavior in `package.nix` +- module option behavior in `modules/shared.nix` +- regression fixes +- new configuration surface +- collision detection or closure-size-sensitive behavior + +Documentation-only changes usually do not need new tests, but they should still keep examples and option references accurate. + +### Pick the right test style + +- Use `mkCheck` for pure evaluation assertions. +- Use `mkBuildCheck` for wrapper output structure. +- Use `mkClosureCheck` for closure-size and dependency guarantees. +- Use `testShouldFail` / `testListShouldFail` for expected failures. + +See [TESTING.md](TESTING.md) for categories, commands, and manual checks. + +## Documentation Parity + +Documentation is part of the product. + +If your change affects user-visible behavior, also update the relevant docs in the same PR: + +- `README.md` for user-facing configuration and behavior +- `TESTING.md` for contributor-facing test guidance +- inline code comments where they explain non-obvious design constraints + +Examples in documentation should be realistic and consistent with the current module surface. + +## Commit Messages + +Use concise, descriptive commits: + +```text +: +``` + +Common types: + +- `feat` +- `fix` +- `docs` +- `test` +- `refactor` +- `chore` + +Examples: + +- `fix: prevent terminal command collisions in cli mode` +- `docs: document cliPackages and notification overrides` + +## Pull Requests + +PRs should explain both the change and the reason for it. + +Include: + +- a short summary +- relevant context or linked issue +- tests run locally +- screenshots or launcher behavior notes if desktop-facing behavior changed + +Before opening a PR, confirm: + +- the patch is scoped and reviewable +- tests and checks are green locally +- docs were updated for any user-facing change +- no unrelated cleanup was bundled in + +## Issue Reports and Feature Requests + +Please use the GitHub issue templates. + +For bugs, include: + +- Nix / NixOS / Home Manager context +- whether you used `packages`, `apps`, `cliPackages`, `cliApps`, or `extraApps` +- the exact error message +- a minimal reproducer when possible + +## Review Guidelines + +The fastest-reviewed contributions tend to: + +- preserve existing architecture +- avoid expanding closure size accidentally +- include regression coverage +- keep option docs synchronized with `modules/shared.nix` +- explain tradeoffs clearly when behavior changes + +## Need Help? + +If you are unsure whether a change belongs in this project, open an issue or draft PR with the proposed approach before doing a large implementation pass. diff --git a/README.md b/README.md index 82cba58..910c77d 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,8 @@ Deferred Apps creates wrapper scripts that look like installed applications but only download the actual package on first use. Perfect for apps you rarely use but want available. +**Contributing?** See [CONTRIBUTING.md](CONTRIBUTING.md) and [TESTING.md](TESTING.md). + ## Features - **Instant availability** — Apps appear in your launcher immediately @@ -52,7 +54,7 @@ Add to your `flake.nix`: } ``` -> **Note**: For unfree packages like `spotify` and `discord`, your nixpkgs must have `config.allowUnfree = true`. See [Unfree Packages](#unfree-packages). +> **Note**: For unfree packages like `spotify` and `discord` in `packages` mode, the nixpkgs instance that produced `pkgs` must have `config.allowUnfree = true`. See [Unfree Packages](#unfree-packages). Run `nixos-rebuild switch` and the apps appear in your launcher. @@ -125,13 +127,13 @@ Run `home-manager switch` (standalone) or `nixos-rebuild switch` (NixOS module) 2. **At first launch**: Downloads the package via `nix-store -r` (from binary cache) or builds it if needed. 3. **Subsequent launches**: Uses the Nix store cache (near-instant). -Packages are pinned to exact versions from your `flake.lock`, and custom overlays are respected since you're passing actual package references. +When you pass package derivations from your own flake inputs, those versions stay pinned by that flake's lock file, and custom overlays are preserved. > **Note**: By default, downloaded packages may be removed by `nix-collect-garbage`. Enable `gcRoot = true` to prevent this (see [Garbage Collection](#garbage-collection)). ## Unfree Packages -For unfree packages (spotify, discord, steam, etc.), your nixpkgs instance must have `config.allowUnfree = true`: +When you use package derivations for unfree packages (spotify, discord, steam, etc.), the nixpkgs instance producing those derivations must have `config.allowUnfree = true`: ```nix # In your flake.nix @@ -145,7 +147,7 @@ nixosConfigurations.myhost = nixpkgs.lib.nixosSystem { }; ``` -The license check happens at flake evaluation time. If you reference an unfree package without enabling `allowUnfree`, you'll get an error during `nix flake check` or `nixos-rebuild`, not at runtime. +That license check happens at evaluation time. If you reference an unfree package derivation without enabling `config.allowUnfree`, you'll get an error during `nix flake check` or `nixos-rebuild`, not at runtime. If you use `apps` instead, set `programs.deferredApps.allowUnfree = true` so the runtime `nix shell` invocation can opt in as well. ## Garbage Collection @@ -221,6 +223,9 @@ programs.deferredApps = { my-spotify = { package = pkgs.spotify; createTerminalCommand = false; # GUI only, no terminal command + showNotification = true; + notificationTitle = "Starting {app}..."; + notificationBody = "Downloading application (first run only)..."; }; # Override auto-detected values @@ -231,10 +236,31 @@ programs.deferredApps = { icon = "custom-icon"; categories = [ "Development" ]; }; + + # CLI-only wrapper via extraApps + ripgrep = { + package = pkgs.ripgrep; + cliOnly = true; + }; }; }; ``` +Notification placeholders support `{app}` and are resolved when the wrapper runs. Module users get `libnotify` automatically, and wrappers simply skip the notification step if `notify-send` is unavailable. + +### CLI-only tools + +Use `cliPackages` or `cliApps` for tools that should be available in the terminal but should not create desktop files or icons: + +```nix +programs.deferredApps = { + enable = true; + + cliPackages = with pkgs; [ ripgrep fd jq ]; + cliApps = [ "hello" "cowsay" ]; +}; +``` + ### Alternative: Package Names (apps option) For simpler setups, you can use package names instead of direct references: @@ -248,7 +274,7 @@ programs.deferredApps = { This uses `nix shell` at runtime to fetch packages from the flake registry. However, this approach: - Requires `allowUnfree = true` option for unfree packages (uses `--impure` mode) -- Uses flake registry versions instead of your `flake.lock` +- Uses flake registry versions instead of your package derivations - Doesn't support custom overlays **We recommend using `packages` instead** for better reproducibility and cleaner unfree handling. @@ -314,8 +340,11 @@ environment.systemPackages = ## Installation Without Flakes +The non-flake examples below are managed by the release process so the documented version and hash can be updated automatically for future releases. + ### NixOS + ```nix let deferred-apps = import (fetchTarball { @@ -328,9 +357,11 @@ in { programs.deferredApps.packages = with pkgs; [ hello ]; } ``` + ### Home Manager + ```nix let deferred-apps = import (fetchTarball { @@ -343,6 +374,7 @@ in { programs.deferredApps.packages = with pkgs; [ hello ]; } ``` + ## Module Options @@ -351,16 +383,29 @@ in { | `enable` | bool | `false` | Enable deferred apps | | `packages` | list of package | `[]` | Package derivations to defer (recommended) | | `apps` | list of str | `[]` | Package names to defer (uses `nix shell` at runtime) | +| `cliPackages` | list of package | `[]` | CLI-only package derivations; no desktop files or icons | +| `cliApps` | list of str | `[]` | CLI-only package names; no desktop files or icons | | `flakeRef` | str | `"nixpkgs"` | Flake reference for `apps` option | | `allowUnfree` | bool | `false` | Allow unfree packages in `apps` (uses `--impure`) | | `gcRoot` | bool | `false` | Create GC roots to prevent cleanup | -| `iconTheme.enable` | bool | `true` | Install Papirus icon theme | +| `iconTheme.enable` | bool | `true` | Install/configure the icon theme when desktop apps are generated | | `iconTheme.package` | package | `pkgs.papirus-icon-theme` | Icon theme package | | `iconTheme.name` | str | `"Papirus-Dark"` | Icon theme name | | `extraApps` | attrs | `{}` | Apps with custom configuration | | `extraApps..package` | package | `null` | Direct package reference | | `extraApps..exe` | str | `null` | Override executable name | +| `extraApps..desktopName` | str | `null` | Override launcher display name | +| `extraApps..description` | str | `null` | Override desktop entry description | +| `extraApps..icon` | str | `null` | Override icon name or absolute icon path | +| `extraApps..categories` | list of str | `[ "Application" ]` | Override desktop entry categories | | `extraApps..createTerminalCommand` | bool | `true` | Create terminal command symlink | +| `extraApps..flakeRef` | str | `null` | Per-app flake reference in pname mode | +| `extraApps..allowUnfree` | bool | `null` | Per-app unfree override in pname mode | +| `extraApps..gcRoot` | bool | `null` | Per-app GC root override | +| `extraApps..showNotification` | bool | `null` | Per-app download notification override | +| `extraApps..notificationTitle` | str | `null` | Custom notification title; supports `{app}` | +| `extraApps..notificationBody` | str | `null` | Custom notification body; supports `{app}` | +| `extraApps..cliOnly` | bool | `null` | Skip desktop file and icons for this app | ## Flake Outputs @@ -405,7 +450,7 @@ This is expected by default. Enable `gcRoot = true` to protect downloaded packag **Q: Should I use `packages` or `apps`?** **Use `packages`** (recommended) for: -- Exact version pinning from your `flake.lock` +- Versions pinned by the flake inputs that produced the package derivations - Packages from custom nixpkgs instances or overlays - Cleaner unfree handling (checked at eval time, not runtime) diff --git a/TESTING.md b/TESTING.md new file mode 100644 index 0000000..d5e0132 --- /dev/null +++ b/TESTING.md @@ -0,0 +1,195 @@ +# Testing + +This document explains how Deferred Apps is tested, which helpers to use, and which checks still require manual verification. + +## Quick Commands + +Run the full local test and quality suite: + +```bash +nix flake check +statix check . +deadnix --fail -L . +nix fmt . -- --check +``` + +Run a specific check: + +```bash +nix build .#checks.x86_64-linux. +``` + +Run a specific check with logs: + +```bash +nix build .#checks.x86_64-linux. -L +``` + +List available checks: + +```bash +nix flake show --json | jq '.checks["x86_64-linux"] | keys' +``` + +## Test Categories + +The test suite is organized in `tests/`. + +| File | Focus | +| --- | --- | +| `internal.nix` | internal helper behavior | +| `library.nix` | `mkDeferredApp` in pname mode | +| `package-mode.nix` | `mkDeferredApp` in package mode | +| `batch.nix` | batch helpers | +| `collision.nix` | terminal command collision detection | +| `module.nix` | NixOS module integration | +| `home-manager.nix` | Home Manager module integration | +| `nested.nix` | nested attribute paths like `python313Packages.numpy` | +| `error.nix` | expected failures and validation errors | +| `compat.nix` | `default.nix` compatibility checks | +| `cli-mode.nix` | CLI-only wrappers, `cliPackages`, and `cliApps` | + +## Test Helpers + +Shared helpers live in `tests/lib.nix`. + +### `mkCheck` + +Use for pure evaluation assertions that do not require building a derivation. + +```nix +mkCheck "name" (someCondition == true) +``` + +Best for: + +- option evaluation +- list lengths +- simple invariants + +### `mkBuildCheck` + +Use when you need to build a wrapper and inspect its output. + +```nix +mkBuildCheck "name" derivation '' + test -f "$drvPath/libexec/deferred-foo" || exit 1 +'' +``` + +Best for: + +- wrapper file layout +- desktop file presence or absence +- terminal command symlinks +- generated script content + +### `mkClosureCheck` + +Use to protect closure-size-sensitive behavior. + +```nix +mkClosureCheck "name" derivation { + maxPaths = 5; + forbiddenPatterns = [ "papirus" ".drv$" ]; +} +``` + +Best for: + +- preventing accidental theme/package references +- ensuring `.drv` files do not leak into closures +- keeping CLI-only outputs minimal + +### `testShouldFail` and `testListShouldFail` + +Use for validation behavior that should fail during evaluation. + +Best for: + +- invalid `pname` input +- missing attributes +- invalid combinations of options + +## Choosing the Right Coverage + +### If you change library behavior + +Usually update one or more of: + +- `library.nix` +- `package-mode.nix` +- `collision.nix` +- `error.nix` +- `cli-mode.nix` + +### If you change module options + +Usually update one or more of: + +- `module.nix` +- `home-manager.nix` +- docs in `README.md` + +### If you change closure-sensitive behavior + +Add or update `mkClosureCheck` coverage. + +This project is intentionally strict about: + +- not pulling large icon themes into runtime closures +- not dragging `.drv` files into system closures +- keeping CLI-only wrappers lightweight + +## Manual Checks Still Needed + +Some important behaviors are not fully covered by `nix flake check`. + +### Runtime wrapper behavior + +Manual verification may still be needed for: + +- first-launch download flow +- `notify-send` behavior +- GC root creation at runtime +- real launcher integration in a desktop environment + +### NixOS and Home Manager integration + +Automated tests cover evaluation and package generation, but not full activation behavior. + +Useful manual checks: + +```bash +# NixOS +nixos-rebuild build + +# Home Manager +home-manager build +``` + +Then verify desktop entries, icons, and launcher behavior in a real environment. + +### `default.nix` compatibility + +`default.nix` is a compatibility import path, so it is not fully exercised by standard flake checks. + +Example manual check: + +```bash +nix eval --impure --expr 'let deferredApps = import ./default.nix; in (deferredApps.mkDeferredApp { pname = "hello"; }).name' +``` + +## Common Debugging Commands + +```bash +nix eval .#checks.x86_64-linux. --show-trace +nix build .#checks.x86_64-linux. -L --keep-failed +nix path-info -rsSh .#checks.x86_64-linux. +``` + +## When in Doubt + +Prefer adding a focused regression test over relying on reviewer memory. + +If a behavior is difficult to test automatically, document the manual verification steps in the PR. diff --git a/flake.lock b/flake.lock index e5515b2..682004d 100644 --- a/flake.lock +++ b/flake.lock @@ -2,11 +2,11 @@ "nodes": { "nixpkgs": { "locked": { - "lastModified": 1766651565, - "narHash": "sha256-QEhk0eXgyIqTpJ/ehZKg9IKS7EtlWxF3N7DXy42zPfU=", + "lastModified": 1776169885, + "narHash": "sha256-l/iNYDZ4bGOAFQY2q8y5OAfBBtrDAaPuRQqWaFHVRXM=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "3e2499d5539c16d0d173ba53552a4ff8547f4539", + "rev": "4bd9165a9165d7b5e33ae57f3eecbcb28fb231c9", "type": "github" }, "original": { diff --git a/modules/shared.nix b/modules/shared.nix index 9212c91..f4648a9 100644 --- a/modules/shared.nix +++ b/modules/shared.nix @@ -34,6 +34,19 @@ assert builtins.elem target [ let cfg = config.programs.deferredApps; + # Whether at least one deferred app will produce desktop integration. + # CLI-only entries do not need an icon theme package or GTK icon theme hint. + hasDesktopApps = + cfg.apps != [ ] + || cfg.packages != [ ] + || lib.any ( + opts: + builtins.elem opts.cliOnly [ + null + false + ] + ) (lib.attrValues cfg.extraApps); + # Import the deferred apps library with icon theme configuration # Icon resolution happens at BUILD TIME (inside derivations) to: # 1. Avoid derivation references at evaluation time (CI/CD compatible) @@ -162,6 +175,56 @@ let Note: This is ignored when `package` is provided. ''; }; + + notificationTitle = lib.mkOption { + type = lib.types.nullOr lib.types.str; + default = null; + example = "Loading {app}"; + description = '' + Custom notification title. + + Use `{app}` as a placeholder for the application name. + Example: "Loading {app}" will show "Loading spotify" for Spotify. + ''; + }; + + notificationBody = lib.mkOption { + type = lib.types.nullOr lib.types.str; + default = null; + example = "Please wait while {app} downloads..."; + description = '' + Custom notification body text. + + Use `{app}` as a placeholder for the application name. + Example: "Downloading {app}" will show "Downloading spotify" for Spotify. + ''; + }; + + showNotification = lib.mkOption { + type = lib.types.nullOr lib.types.bool; + default = null; + description = '' + Whether to show download notifications for this specific app. + + If null (default), uses the global setting. + Set to `false` to disable notifications entirely for this app. + Set to `true` to force notifications even if globally disabled. + ''; + }; + + cliOnly = lib.mkOption { + type = lib.types.nullOr lib.types.bool; + default = null; + description = '' + Whether this is a CLI-only application (no desktop file or icons). + + If true, the deferred app will not create a desktop entry or icons, + which is useful for terminal tools like ripgrep, fd, jq, etc. + + If null (default), inherits from global setting based on which list the + app is in (cliPackages/cliApps vs packages/apps). + ''; + }; }; }; @@ -183,7 +246,7 @@ let extraAppsWithPname = lib.filterAttrs (_: opts: opts.package == null) cfg.extraApps; # Build config list for collision detection - # Includes: apps (pname), packages (direct), extraApps (both modes) + # Includes: apps (pname), packages (direct), cliPackages, cliApps, extraApps (both modes) allAppConfigs = # Standard apps (pname mode) (map (pname: { @@ -195,6 +258,18 @@ let inherit package; createTerminalCommand = true; }) cfg.packages) + # CLI packages (package mode) + ++ (map (package: { + inherit package; + createTerminalCommand = true; + cliOnly = true; + }) cfg.cliPackages) + # CLI apps (pname mode) + ++ (map (pname: { + inherit pname; + createTerminalCommand = true; + cliOnly = true; + }) cfg.cliApps) # extraApps with pname mode ++ (lib.mapAttrsToList (pname: opts: { inherit pname; @@ -227,6 +302,26 @@ let } ) cfg.packages; + # Build CLI packages (package mode, CLI-only) + cliPackageApps = map ( + package: + deferredAppsLib.mkDeferredApp { + inherit package; + inherit (cfg) gcRoot; + cliOnly = true; + } + ) cfg.cliPackages; + + # Build CLI apps (pname mode, CLI-only) + cliAppsList = map ( + pname: + deferredAppsLib.mkDeferredApp { + inherit pname; + inherit (cfg) flakeRef allowUnfree gcRoot; + cliOnly = true; + } + ) cfg.cliApps; + # Build extra apps with pname mode (manual configuration) extraAppsListPname = lib.mapAttrsToList ( pname: opts: @@ -239,7 +334,12 @@ let icon categories createTerminalCommand + cliOnly ; + # Only pass notification values if specified (null means use default) + notificationTitle = if opts.notificationTitle != null then opts.notificationTitle else null; + notificationBody = if opts.notificationBody != null then opts.notificationBody else null; + showNotification = if opts.showNotification != null then opts.showNotification else null; # Use per-app settings if specified, otherwise fall back to global flakeRef = if opts.flakeRef != null then opts.flakeRef else cfg.flakeRef; allowUnfree = if opts.allowUnfree != null then opts.allowUnfree else cfg.allowUnfree; @@ -250,8 +350,8 @@ let # Build extra apps with package mode (direct package reference) # Note: We pass the key name as pnameOverride so the desktop file uses # the user's chosen name (e.g., "spotify-unstable") instead of the - # package's pname (e.g., "spotify"). This prevents collisions when - # the same package is referenced with different keys. + # package's pname (e.g., "spotify"). This prevents collisions when the + # same package is referenced with different keys. extraAppsListPackage = lib.mapAttrsToList ( name: opts: deferredAppsLib.mkDeferredApp { @@ -263,7 +363,12 @@ let icon categories createTerminalCommand + cliOnly ; + # Only pass notification values if specified (null means use default) + notificationTitle = if opts.notificationTitle != null then opts.notificationTitle else null; + notificationBody = if opts.notificationBody != null then opts.notificationBody else null; + showNotification = if opts.showNotification != null then opts.showNotification else null; # Use the key name as pname for desktop file naming # This prevents collisions like apps=["spotify"] + extraApps.spotify-unstable.package pnameOverride = name; @@ -273,14 +378,16 @@ let } ) extraAppsWithPackage; - # Icon theme package (if enabled) - iconThemePackages = lib.optional cfg.iconTheme.enable cfg.iconTheme.package; + # Icon theme package (only when desktop apps are present) + iconThemePackages = lib.optional (cfg.iconTheme.enable && hasDesktopApps) cfg.iconTheme.package; + # Assert no terminal command collisions before building in - # Assert no terminal command collisions before building assert lib.assertMsg (collision == null) collision; standardApps ++ packageApps + ++ cliPackageApps + ++ cliAppsList ++ extraAppsListPname ++ extraAppsListPackage ++ iconThemePackages @@ -392,13 +499,8 @@ in ''; }; - package = lib.mkOption { - type = lib.types.package; - default = pkgs.papirus-icon-theme; - defaultText = lib.literalExpression "pkgs.papirus-icon-theme"; - description = '' - The icon theme package to install. - + package = lib.mkPackageOption pkgs "papirus-icon-theme" { + extraDescription = '' Must be a freedesktop.org-compliant icon theme that includes application icons in share/icons/*/apps/. ''; @@ -440,15 +542,63 @@ in - **Overlays**: Your custom overlays are respected since you're passing the actual package. - At system build time, only the store paths are captured - the package - outputs are NOT built. On first launch, `nix-store -r` fetches the - package from binary caches (or builds it if not available). + At system build time, only store paths are captured - the package + outputs are NOT built. On first launch, `nix-store -r` fetches + the package from binary caches (or builds it if not available). Note: `allowUnfree` is not needed for packages passed here, as the license check happens when you reference the package in your flake. ''; }; + cliPackages = lib.mkOption { + type = lib.types.listOf lib.types.package; + default = [ ]; + example = lib.literalExpression '' + [ + pkgs.ripgrep + pkgs.fd + pkgs.jq + ] + ''; + description = '' + List of CLI tools to create deferred launchers for. + + CLI-only apps do NOT create desktop files or icons, which is useful + for terminal tools like ripgrep, fd, jq, etc. This reduces build time + and closure size by skipping icon resolution. + + These are functionally equivalent to using `packages` with `cliOnly = true`, + but this option provides a more convenient interface for CLI tools. + ''; + }; + + cliApps = lib.mkOption { + type = lib.types.listOf lib.types.str; + default = [ ]; + example = [ + "hello" + "cowsay" + "tree" + ]; + description = '' + List of CLI tool names to create deferred launchers for. + + CLI-only apps do NOT create desktop files or icons, which is useful + for terminal tools like ripgrep, fd, jq, etc. This reduces build time + and closure size by skipping icon resolution. + + These are functionally equivalent to using `apps` with `cliOnly = true`, + but this option provides a more convenient interface for CLI tools. + + Supports nested packages with dot notation: + - `haskellPackages.pandoc` + - `nodePackages.typescript` + + Note: For unfree CLI tools, you must set `allowUnfree = true`. + ''; + }; + extraApps = lib.mkOption { type = lib.types.attrsOf extraAppModule; default = { }; @@ -523,7 +673,7 @@ in # Set the icon theme via environment variable as fallback # Desktop environments typically have their own settings, but this helps # applications that read XDG_CURRENT_DESKTOP or use gtk-icon-theme-name - variables = lib.mkIf cfg.iconTheme.enable { + variables = lib.mkIf (cfg.iconTheme.enable && hasDesktopApps) { # This is a hint for applications; DE settings take precedence GTK_ICON_THEME = lib.mkDefault cfg.iconTheme.name; }; @@ -541,7 +691,7 @@ in # Set GTK icon theme via session variable # Users may prefer to use gtk.iconTheme instead for better integration - home.sessionVariables = lib.mkIf cfg.iconTheme.enable { + home.sessionVariables = lib.mkIf (cfg.iconTheme.enable && hasDesktopApps) { GTK_ICON_THEME = lib.mkDefault cfg.iconTheme.name; }; } diff --git a/package.nix b/package.nix index a09398b..005acca 100644 --- a/package.nix +++ b/package.nix @@ -217,9 +217,9 @@ let || builtins.match "[0-9]+(rc|alpha|beta|pre|post)[0-9]*" p != null; nonVersionParts = takeWhile (p: !isVersionPart p) parts; result = lib.concatStringsSep "-" nonVersionParts; + # Fallback to full name if no non-version parts found + # This handles edge cases like a package named just "1.0" (unlikely but safe) in - # Fallback to full name if no non-version parts found - # This handles edge cases like a package named just "1.0" (unlikely but safe) if result == "" then name else result ); @@ -295,6 +295,7 @@ let # createTerminalCommand - create terminal command symlink (defaults to true) # allowUnfree - allow unfree packages (enables --impure for pname mode, defaults to false) # gcRoot - create GC root to prevent garbage collection (defaults to false) + # cliOnly - skip desktop file and icon generation (defaults to false) # # Icon Resolution: # Icons are resolved at BUILD TIME to absolute paths from the configured @@ -316,8 +317,14 @@ let createTerminalCommand ? true, allowUnfree ? false, gcRoot ? false, + notificationTitle ? null, + notificationBody ? null, + showNotification ? true, + cliOnly ? null, }: let + cliOnlyBool = if cliOnly == null then false else cliOnly; + showNotificationBool = if showNotification == null then true else showNotification; # =========================================================================== # Mode Detection and Validation # =========================================================================== @@ -423,61 +430,72 @@ let # Wrapper for PNAME mode (uses nix shell) wrapperScriptPname = writeText "deferred-${validatedPname}-wrapper-pname" '' - #!/usr/bin/env bash - set -euo pipefail + #!/usr/bin/env bash + set -euo pipefail - PNAME="@pname@" - FLAKE_REF="@flakeRef@" + PNAME="@pname@" + FLAKE_REF="@flakeRef@" EXE="@exe@" ICON="@icon@" NEEDS_IMPURE="@needsImpure@" GC_ROOT="@gcRoot@" + SHOW_NOTIFICATION="@showNotification@" + NOTIFICATION_TITLE="@notificationTitle@" + NOTIFICATION_BODY="@notificationBody@" # GC root directory for this user GC_ROOT_DIR="''${XDG_DATA_HOME:-$HOME/.local/share}/deferred-apps/gcroots" - # Show notification (only if not already cached) - maybe_notify() { - if [ "$GC_ROOT" = "1" ] && [ -L "$GC_ROOT_DIR/$PNAME" ]; then - return - fi - if command -v notify-send &>/dev/null; then - notify-send \ - --app-name="Deferred Apps" \ - --urgency=low \ - --icon="$ICON" \ - "Starting $PNAME..." \ - "Downloading application (first run only)..." & - fi - } + # Show notification (only if not already cached) + maybe_notify() { + if [ "$SHOW_NOTIFICATION" != "1" ]; then + return + fi + if [ "$GC_ROOT" = "1" ] && [ -L "$GC_ROOT_DIR/$PNAME" ]; then + return + fi + if command -v notify-send &>/dev/null; then + local title="$NOTIFICATION_TITLE" + local body="$NOTIFICATION_BODY" + # Substitute {app} with actual app name + title="''${title//\{app\}/$PNAME}" + body="''${body//\{app\}/$PNAME}" + notify-send \ + --app-name="Deferred Apps" \ + --urgency=low \ + --icon="$ICON" \ + "$title" \ + "$body" & + fi + } - # Ensure package is downloaded and create GC root - ensure_downloaded() { - local build_args=("$FLAKE_REF#$PNAME" "--no-link" "--print-out-paths") + # Ensure package is downloaded and create GC root + ensure_downloaded() { + local build_args=("$FLAKE_REF#$PNAME" "--no-link" "--print-out-paths") - if [ "$NEEDS_IMPURE" = "1" ]; then - export NIXPKGS_ALLOW_UNFREE=1 - build_args=("--impure" "''${build_args[@]}") - fi + if [ "$NEEDS_IMPURE" = "1" ]; then + export NIXPKGS_ALLOW_UNFREE=1 + build_args=("--impure" "''${build_args[@]}") + fi - local store_path - store_path=$(nix build "''${build_args[@]}" 2>/dev/null) || return 0 + local store_path + store_path=$(nix build "''${build_args[@]}" 2>/dev/null) || return 0 - if [ "$GC_ROOT" = "1" ] && [ -n "$store_path" ]; then - mkdir -p "$GC_ROOT_DIR" - nix-store --add-root "$GC_ROOT_DIR/$PNAME" --indirect -r "$store_path" &>/dev/null || true - fi - } + if [ "$GC_ROOT" = "1" ] && [ -n "$store_path" ]; then + mkdir -p "$GC_ROOT_DIR" + nix-store --add-root "$GC_ROOT_DIR/$PNAME" --indirect -r "$store_path" &>/dev/null || true + fi + } - maybe_notify - ensure_downloaded + maybe_notify + ensure_downloaded - if [ "$NEEDS_IMPURE" = "1" ]; then - export NIXPKGS_ALLOW_UNFREE=1 - exec nix shell --impure "$FLAKE_REF#$PNAME" --command "$EXE" "$@" - else - exec nix shell "$FLAKE_REF#$PNAME" --command "$EXE" "$@" - fi + if [ "$NEEDS_IMPURE" = "1" ]; then + export NIXPKGS_ALLOW_UNFREE=1 + exec nix shell --impure "$FLAKE_REF#$PNAME" --command "$EXE" "$@" + else + exec nix shell "$FLAKE_REF#$PNAME" --command "$EXE" "$@" + fi ''; # Wrapper for PACKAGE mode (uses nix-store -r with output path) @@ -495,8 +513,8 @@ let # where the binary is in a different output (rare), users can override with # the `exe` option providing a path relative to the package or use pname mode. wrapperScriptPackage = writeText "deferred-${validatedPname}-wrapper-package" '' - #!/usr/bin/env bash - set -euo pipefail + #!/usr/bin/env bash + set -euo pipefail PNAME="@pname@" DRV_PATH="@drvPath@" @@ -504,86 +522,97 @@ let EXE="@exe@" ICON="@icon@" GC_ROOT="@gcRoot@" + SHOW_NOTIFICATION="@showNotification@" + NOTIFICATION_TITLE="@notificationTitle@" + NOTIFICATION_BODY="@notificationBody@" # GC root directory for this user GC_ROOT_DIR="''${XDG_DATA_HOME:-$HOME/.local/share}/deferred-apps/gcroots" - # Check if package is already available (cached or realized) - is_available() { - # If GC root is enabled and exists, package is available - if [ "$GC_ROOT" = "1" ] && [ -L "$GC_ROOT_DIR/$PNAME" ]; then - return 0 - fi - # Otherwise check if output directory exists in store - [ -d "$OUT_PATH" ] - } - - # Show notification (only if not already available) - maybe_notify() { - if is_available; then - return - fi - if command -v notify-send &>/dev/null; then - notify-send \ - --app-name="Deferred Apps" \ - --urgency=low \ - --icon="$ICON" \ - "Starting $PNAME..." \ - "Downloading application (first run only)..." & - fi - } - - # Ensure package is realized - tries multiple strategies - ensure_realized() { - if [ -d "$OUT_PATH" ]; then - return 0 - fi - - # Strategy 1: Try to fetch output directly from binary cache - # This works for all packages in cache.nixos.org (most nixpkgs packages) - if nix-store -r "$OUT_PATH" >/dev/null 2>&1; then - return 0 - fi + # Check if package is already available (cached or realized) + is_available() { + # If GC root is enabled and exists, package is available + if [ "$GC_ROOT" = "1" ] && [ -L "$GC_ROOT_DIR/$PNAME" ]; then + return 0 + fi + # Otherwise check if output directory exists in store + [ -d "$OUT_PATH" ] + } + + # Show notification (only if not already available) + maybe_notify() { + if [ "$SHOW_NOTIFICATION" != "1" ]; then + return + fi + if is_available; then + return + fi + if command -v notify-send &>/dev/null; then + local title="$NOTIFICATION_TITLE" + local body="$NOTIFICATION_BODY" + # Substitute {app} with actual app name + title="''${title//\{app\}/$PNAME}" + body="''${body//\{app\}/$PNAME}" + notify-send \ + --app-name="Deferred Apps" \ + --urgency=low \ + --icon="$ICON" \ + "$title" \ + "$body" & + fi + } - # Strategy 2: If .drv exists locally (from evaluation), use it - # This works for packages built locally or with custom overlays - if [ -n "$DRV_PATH" ] && [ -f "$DRV_PATH" ]; then - if nix-store --realise "$DRV_PATH" >/dev/null; then + # Ensure package is realized - tries multiple strategies + ensure_realized() { + if [ -d "$OUT_PATH" ]; then return 0 fi - fi - # Both strategies failed - echo "deferred-apps: Failed to fetch $PNAME" >&2 - echo "" >&2 - echo "The package output ($OUT_PATH) is not available from binary caches," >&2 - echo "and the derivation file is not available locally." >&2 - echo "" >&2 - echo "This can happen with:" >&2 - echo " - Packages from custom overlays" >&2 - echo " - Packages modified locally" >&2 - echo " - Private packages not in public caches" >&2 - echo "" >&2 - echo "Solutions:" >&2 - echo " 1. Build the package once: nix build nixpkgs#$PNAME" >&2 - echo " 2. Use 'apps' option instead of 'packages' for this package" >&2 - echo " 3. Set up your own binary cache" >&2 - exit 1 - } + # Strategy 1: Try to fetch output directly from binary cache + # This works for all packages in cache.nixos.org (most nixpkgs packages) + if nix-store -r "$OUT_PATH" >/dev/null 2>&1; then + return 0 + fi - maybe_notify - ensure_realized + # Strategy 2: If .drv exists locally (from evaluation), use it + # This works for packages built locally or with custom overlays + if [ -n "$DRV_PATH" ] && [ -f "$DRV_PATH" ]; then + if nix-store --realise "$DRV_PATH" >/dev/null; then + return 0 + fi + fi - # Create GC root if enabled and not already present - if [ "$GC_ROOT" = "1" ] && [ ! -L "$GC_ROOT_DIR/$PNAME" ]; then - mkdir -p "$GC_ROOT_DIR" - nix-store --add-root "$GC_ROOT_DIR/$PNAME" --indirect -r "$OUT_PATH" &>/dev/null || true - fi + # Both strategies failed + echo "deferred-apps: Failed to fetch $PNAME" >&2 + echo "" >&2 + echo "The package output ($OUT_PATH) is not available from binary caches," >&2 + echo "and the derivation file is not available locally." >&2 + echo "" >&2 + echo "This can happen with:" >&2 + echo " - Packages from custom overlays" >&2 + echo " - Packages modified locally" >&2 + echo " - Private packages not in public caches" >&2 + echo "" >&2 + echo "Solutions:" >&2 + echo " 1. Build the package once: nix build nixpkgs#$PNAME" >&2 + echo " 2. Use 'apps' option instead of 'packages' for this package" >&2 + echo " 3. Set up your own binary cache" >&2 + exit 1 + } + + maybe_notify + ensure_realized + + # Create GC root if enabled and not already present + if [ "$GC_ROOT" = "1" ] && [ ! -L "$GC_ROOT_DIR/$PNAME" ]; then + mkdir -p "$GC_ROOT_DIR" + nix-store --add-root "$GC_ROOT_DIR/$PNAME" --indirect -r "$OUT_PATH" &>/dev/null || true + fi - # Run the application directly from the store path - # Note: Assumes binary is in $out/bin/. For multi-output packages where - # the binary is in a different output, use the exe option with a full path. - exec "$OUT_PATH/bin/$EXE" "$@" + # Run the application directly from the store path + # Note: Assumes binary is in $out/bin/. For multi-output packages where + # the binary is in a different output, use the exe option with a full path. + exec "$OUT_PATH/bin/$EXE" "$@" ''; # Select the right wrapper based on mode @@ -602,63 +631,80 @@ let startupWMClass = finalExe; }; + # Validation: unfree check for pname mode in - # Validation: unfree check for pname mode assert lib.assertMsg (hasPackage || !packageIsUnfree || allowUnfree) "deferred-apps: Package '${validatedPname}' is unfree. Set 'allowUnfree = true' to enable it (uses --impure)."; runCommand "deferred-${validatedPname}" - { - inherit - validatedPname - finalExe - wrapperScript - desktopItem - terminalCommand - mode # Force evaluation of mode (triggers validation assertions) - ; - # Mode-specific variables - isPackageMode = if hasPackage then "1" else ""; - flakeRef = if hasPackage then "" else flakeRef; - drvPath = pkgDrvPath; - outPath = pkgOutPath; - # Common variables - iconThemePath = "${iconThemePackage}/share/icons/${iconThemeName}"; - iconSizes = iconSizesList; - userIcon = if iconIsAbsolutePath then icon else ""; - createTerminal = if createTerminalCommand then "1" else ""; - needsImpureStr = if needsImpure then "1" else "0"; - gcRootStr = if gcRoot then "1" else "0"; - inherit iconName iconNameFallback; - } + ( + (lib.optionalAttrs (!cliOnlyBool) { inherit desktopItem; }) + // { + inherit + validatedPname + finalExe + wrapperScript + terminalCommand + mode # Force evaluation of mode (triggers validation assertions) + ; + # Mode-specific variables + isPackageMode = if hasPackage then "1" else ""; + flakeRef = if hasPackage then "" else flakeRef; + drvPath = pkgDrvPath; + outPath = pkgOutPath; + # Common variables + iconThemePath = if cliOnlyBool then "" else "${iconThemePackage}/share/icons/${iconThemeName}"; + iconSizes = iconSizesList; + userIcon = if iconIsAbsolutePath then icon else ""; + createTerminal = if createTerminalCommand then "1" else ""; + needsImpureStr = if needsImpure then "1" else "0"; + gcRootStr = if gcRoot then "1" else "0"; + inherit iconName iconNameFallback; + # Notification variables + showNotificationStr = if showNotificationBool then "1" else "0"; + notificationTitleValue = + if notificationTitle != null then notificationTitle else "Starting {app}..."; + notificationBodyValue = + if notificationBody != null then + notificationBody + else + "Downloading application (first run only)..."; + cliOnlyStr = if cliOnlyBool then "1" else ""; + } + ) '' - # =========================================================================== - # Build-time icon resolution - # =========================================================================== - # - # IMPORTANT: We COPY the icon into $out to avoid pulling in the entire icon - # theme (~1GB) as a runtime dependency. The desktop file then references - # our local copy instead of the theme package. - find_icon() { - local name="$1" - local theme_path="$iconThemePath" + local icon_name="$1" + local size ext icon_path found for size in $iconSizes; do - local icon_path="$theme_path/$size/apps/$name.svg" - if [ -e "$icon_path" ]; then - # Return the resolved path (follows symlinks) - readlink -f "$icon_path" - return 0 - fi + for ext in svg png; do + icon_path="$iconThemePath/$size/apps/$icon_name.$ext" + if [ -f "$icon_path" ]; then + printf '%s\n' "$icon_path" + return 0 + fi + done done + + found=$(find "$iconThemePath" \( -name "$icon_name.svg" -o -name "$icon_name.png" \) -print -quit 2>/dev/null) + if [ -n "$found" ]; then + printf '%s\n' "$found" + return 0 + fi + return 1 } - mkdir -p "$out/libexec" "$out/share/applications" "$out/share/icons" + mkdir -p "$out/libexec" + if [ -z "$cliOnlyStr" ]; then + mkdir -p "$out/share/applications" "$out/share/icons" + fi # Resolve and copy icon RESOLVED_ICON="" - if [ -n "$userIcon" ]; then + if [ -n "$cliOnlyStr" ]; then + : + elif [ -n "$userIcon" ]; then # User provided absolute path - use as-is (they control the dependency) RESOLVED_ICON="$userIcon" else @@ -693,7 +739,10 @@ let --replace-fail '@drvPath@' "$drvPath" \ --replace-fail '@outPath@' "$outPath" \ --replace-fail '@exe@' "$finalExe" \ - --replace-fail '@gcRoot@' "$gcRootStr" + --replace-fail '@gcRoot@' "$gcRootStr" \ + --replace-fail '@showNotification@' "$showNotificationStr" \ + --replace-fail '@notificationTitle@' "$notificationTitleValue" \ + --replace-fail '@notificationBody@' "$notificationBodyValue" else # Pname mode: substitute flake-specific variables substitute "$wrapperScript" "$out/libexec/deferred-$validatedPname" \ @@ -702,7 +751,10 @@ let --replace-fail '@flakeRef@' "$flakeRef" \ --replace-fail '@exe@' "$finalExe" \ --replace-fail '@needsImpure@' "$needsImpureStr" \ - --replace-fail '@gcRoot@' "$gcRootStr" + --replace-fail '@gcRoot@' "$gcRootStr" \ + --replace-fail '@showNotification@' "$showNotificationStr" \ + --replace-fail '@notificationTitle@' "$notificationTitleValue" \ + --replace-fail '@notificationBody@' "$notificationBodyValue" fi chmod +x "$out/libexec/deferred-$validatedPname" @@ -710,16 +762,18 @@ let # =========================================================================== # Create the .desktop file # =========================================================================== - cp "$desktopItem/share/applications/$validatedPname.desktop" \ - "$out/share/applications/$validatedPname.desktop" + if [ -z "$cliOnlyStr" ]; then + cp "$desktopItem/share/applications/$validatedPname.desktop" \ + "$out/share/applications/$validatedPname.desktop" - substitute "$out/share/applications/$validatedPname.desktop" \ - "$out/share/applications/$validatedPname.desktop.tmp" \ - --replace-fail '@out@' "$out" \ - --replace-fail '@icon@' "$RESOLVED_ICON" + substitute "$out/share/applications/$validatedPname.desktop" \ + "$out/share/applications/$validatedPname.desktop.tmp" \ + --replace-fail '@out@' "$out" \ + --replace-fail '@icon@' "$RESOLVED_ICON" - mv "$out/share/applications/$validatedPname.desktop.tmp" \ - "$out/share/applications/$validatedPname.desktop" + mv "$out/share/applications/$validatedPname.desktop.tmp" \ + "$out/share/applications/$validatedPname.desktop" + fi # =========================================================================== # Create terminal command symlink (optional) diff --git a/scripts/compute-release-nix-hash.sh b/scripts/compute-release-nix-hash.sh new file mode 100755 index 0000000..823f183 --- /dev/null +++ b/scripts/compute-release-nix-hash.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash + +set -euo pipefail + +usage() { + printf 'Usage: %s --tarball \n' "$0" >&2 +} + +tarball='' + +while [[ $# -gt 0 ]]; do + case "$1" in + --tarball) + [[ $# -ge 2 ]] || { + usage + exit 1 + } + tarball="$2" + shift 2 + ;; + -h | --help) + usage + exit 0 + ;; + *) + usage + exit 1 + ;; + esac +done + +[[ -n "$tarball" ]] || { + usage + exit 1 +} + +if [[ "$tarball" != /* ]]; then + tarball="$PWD/$tarball" +fi + +[[ -f "$tarball" ]] || { + printf 'Tarball not found: %s\n' "$tarball" >&2 + exit 1 +} + +tmpdir=$(mktemp -d) +cleanup() { + rm -rf "$tmpdir" +} +trap cleanup EXIT + +tar -xzf "$tarball" -C "$tmpdir" + +shopt -s nullglob +entries=("$tmpdir"/*) +shopt -u nullglob + +if [[ ${#entries[@]} -ne 1 || ! -d "${entries[0]}" ]]; then + printf 'Expected exactly one top-level directory in %s\n' "$tarball" >&2 + exit 1 +fi + +nix hash path --type sha256 --base32 "${entries[0]}" diff --git a/scripts/create-release-source-tarball.sh b/scripts/create-release-source-tarball.sh new file mode 100755 index 0000000..a1f8c8f --- /dev/null +++ b/scripts/create-release-source-tarball.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash + +set -euo pipefail + +script_dir=$(dirname "$(readlink -f "$0")") +# shellcheck source=./release-metadata.sh +source "$script_dir/release-metadata.sh" + +usage() { + printf 'Usage: %s --version [--ref ] [--output ]\n' "$0" >&2 +} + +version='' +ref='HEAD' +output='' + +while [[ $# -gt 0 ]]; do + case "$1" in + --version) + [[ $# -ge 2 ]] || { + usage + exit 1 + } + version="$2" + shift 2 + ;; + --ref) + [[ $# -ge 2 ]] || { + usage + exit 1 + } + ref="$2" + shift 2 + ;; + --output) + [[ $# -ge 2 ]] || { + usage + exit 1 + } + output="$2" + shift 2 + ;; + -h | --help) + usage + exit 0 + ;; + *) + usage + exit 1 + ;; + esac +done + +[[ -n "$version" ]] || { + usage + exit 1 +} + +tag=$(normalize_release_tag "$version") + +repo_root=$(git rev-parse --show-toplevel) +git -C "$repo_root" rev-parse --verify "${ref}^{commit}" >/dev/null + +if [[ -z "$output" ]]; then + output=$(release_output_path "$repo_root" "$tag") +elif [[ "$output" != /* ]]; then + output="$repo_root/$output" +fi + +mkdir -p "$(dirname "$output")" + +tmp_output="${output}.tmp" +prefix="deferred-apps-${tag}/" + +rm -f "$tmp_output" +git -C "$repo_root" archive --format=tar --prefix="$prefix" "$ref" | gzip -n > "$tmp_output" +mv "$tmp_output" "$output" + +printf '%s\n' "$output" diff --git a/scripts/prepare-release.sh b/scripts/prepare-release.sh new file mode 100755 index 0000000..8caaf8a --- /dev/null +++ b/scripts/prepare-release.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash + +set -euo pipefail + +script_dir=$(dirname "$(readlink -f "$0")") +# shellcheck source=./release-metadata.sh +source "$script_dir/release-metadata.sh" + +usage() { + printf 'Usage: %s --version [--ref ] [--output ] [--readme ] [--check]\n' "$0" >&2 +} + +version='' +ref='HEAD' +output='' +readme='' +check_only='0' + +while [[ $# -gt 0 ]]; do + case "$1" in + --version) + [[ $# -ge 2 ]] || { + usage + exit 1 + } + version="$2" + shift 2 + ;; + --ref) + [[ $# -ge 2 ]] || { + usage + exit 1 + } + ref="$2" + shift 2 + ;; + --output) + [[ $# -ge 2 ]] || { + usage + exit 1 + } + output="$2" + shift 2 + ;; + --readme) + [[ $# -ge 2 ]] || { + usage + exit 1 + } + readme="$2" + shift 2 + ;; + --check) + check_only='1' + shift + ;; + -h | --help) + usage + exit 0 + ;; + *) + usage + exit 1 + ;; + esac +done + +[[ -n "$version" ]] || { + usage + exit 1 +} + +repo_root=$(git rev-parse --show-toplevel) +scripts_dir="$repo_root/scripts" +tag=$(normalize_release_tag "$version") + +tarball_args=(--version "$version" --ref "$ref") +if [[ -n "$output" ]]; then + tarball_args+=(--output "$output") +fi + +tarball_path=$("$scripts_dir/create-release-source-tarball.sh" "${tarball_args[@]}") + +update_args=(--version "$version" --tarball "$tarball_path") +if [[ -n "$readme" ]]; then + update_args+=(--readme "$readme") +fi + +if [[ "$check_only" != '1' ]]; then + "$scripts_dir/update-readme-release-snippets.py" "${update_args[@]}" +fi +"$scripts_dir/update-readme-release-snippets.py" "${update_args[@]}" --check + +hash=$("$scripts_dir/compute-release-nix-hash.sh" --tarball "$tarball_path") +mode='Prepared' +if [[ "$check_only" == '1' ]]; then + mode='Verified' +fi +printf '%s release %s\nTarball: %s\nNix sha256: %s\n' "$mode" "$tag" "$tarball_path" "$hash" diff --git a/scripts/quality-gates.sh b/scripts/quality-gates.sh new file mode 100755 index 0000000..f0b0216 --- /dev/null +++ b/scripts/quality-gates.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + +set -euo pipefail + +repo_root=$(git rev-parse --show-toplevel) + +cd "$repo_root" + +printf '==> nix flake check\n' +nix flake check --print-build-logs + +printf '==> statix check .\n' +nix develop .#ci --command statix check . + +printf '==> deadnix --fail -L .\n' +nix develop .#ci --command deadnix --fail -L . + +printf '==> release tooling smoke test\n' +./scripts/smoke-test-release-tooling.sh + +printf '==> nix fmt . -- --check\n' +nix fmt . -- --check diff --git a/scripts/release-metadata.sh b/scripts/release-metadata.sh new file mode 100755 index 0000000..c0419d4 --- /dev/null +++ b/scripts/release-metadata.sh @@ -0,0 +1,125 @@ +#!/usr/bin/env bash + +set -euo pipefail + +normalize_release_tag() { + local version="$1" + + if [[ -z "$version" ]]; then + printf 'release version must not be empty\n' >&2 + return 1 + fi + + if [[ "$version" == v* ]]; then + printf '%s\n' "$version" + else + printf 'v%s\n' "$version" + fi +} + +release_version_from_tag() { + local tag="$1" + printf '%s\n' "${tag#v}" +} + +release_asset_name() { + local tag="$1" + printf 'deferred-apps-%s.tar.gz\n' "$tag" +} + +release_asset_url() { + local tag="$1" + local asset_name + + asset_name=$(release_asset_name "$tag") + printf 'https://github.com/WitteShadovv/deferred-apps/releases/download/%s/%s\n' "$tag" "$asset_name" +} + +release_output_path() { + local repo_root="$1" + local tag="$2" + local asset_name + + asset_name=$(release_asset_name "$tag") + printf '%s/dist/%s\n' "$repo_root" "$asset_name" +} + +usage() { + printf 'Usage: %s --version --field [--repo-root ]\n' "$0" >&2 +} + +if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then + version='' + field='' + repo_root='' + + while [[ $# -gt 0 ]]; do + case "$1" in + --version) + [[ $# -ge 2 ]] || { + usage + exit 1 + } + version="$2" + shift 2 + ;; + --field) + [[ $# -ge 2 ]] || { + usage + exit 1 + } + field="$2" + shift 2 + ;; + --repo-root) + [[ $# -ge 2 ]] || { + usage + exit 1 + } + repo_root="$2" + shift 2 + ;; + -h | --help) + usage + exit 0 + ;; + *) + usage + exit 1 + ;; + esac + done + + [[ -n "$version" && -n "$field" ]] || { + usage + exit 1 + } + + tag=$(normalize_release_tag "$version") + + case "$field" in + tag) + printf '%s\n' "$tag" + ;; + version) + release_version_from_tag "$tag" + ;; + asset-name) + release_asset_name "$tag" + ;; + asset-url) + release_asset_url "$tag" + ;; + output-path) + [[ -n "$repo_root" ]] || { + printf '--repo-root is required for output-path\n' >&2 + exit 1 + } + release_output_path "$repo_root" "$tag" + ;; + *) + usage + exit 1 + ;; + esac +fi diff --git a/scripts/smoke-test-release-tooling.sh b/scripts/smoke-test-release-tooling.sh new file mode 100755 index 0000000..bf41893 --- /dev/null +++ b/scripts/smoke-test-release-tooling.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash + +set -euo pipefail + +repo_root=$(git rev-parse --show-toplevel) +tmpdir=$(mktemp -d) + +cleanup() { + rm -rf "$tmpdir" +} + +trap cleanup EXIT + +version='v0.0.0-smoke' +readme_copy="$tmpdir/README.md" +tarball_path="$tmpdir/release.tar.gz" + +cp "$repo_root/README.md" "$readme_copy" + +"$repo_root/scripts/prepare-release.sh" \ + --version "$version" \ + --ref HEAD \ + --output "$tarball_path" \ + --readme "$readme_copy" + +"$repo_root/scripts/prepare-release.sh" \ + --version "$version" \ + --ref HEAD \ + --output "$tarball_path" \ + --readme "$readme_copy" \ + --check + +printf 'Release tooling smoke test passed for %s\n' "$version" diff --git a/scripts/update-readme-release-snippets.py b/scripts/update-readme-release-snippets.py new file mode 100755 index 0000000..1626a1b --- /dev/null +++ b/scripts/update-readme-release-snippets.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 + +from __future__ import annotations + +import argparse +import pathlib +import subprocess +import sys + + +START_MARKER_TEMPLATE = "" +END_MARKER_TEMPLATE = "" + + +def release_metadata(scripts_dir: pathlib.Path, version: str, field: str) -> str: + script_path = scripts_dir / "release-metadata.sh" + result = subprocess.run( + [str(script_path), "--version", version, "--field", field], + check=True, + capture_output=True, + text=True, + ) + return result.stdout.strip() + + +def normalize_tag(version: str) -> str: + return release_metadata(pathlib.Path(__file__).resolve().parent, version, "tag") + + +def compute_nix_hash(scripts_dir: pathlib.Path, tarball: pathlib.Path) -> str: + script_path = scripts_dir / "compute-release-nix-hash.sh" + result = subprocess.run( + [str(script_path), "--tarball", str(tarball)], + check=True, + capture_output=True, + text=True, + ) + return result.stdout.strip() + + +def build_expected_pair(tag: str, nix_hash: str) -> str: + scripts_dir = pathlib.Path(__file__).resolve().parent + asset_url = release_metadata(scripts_dir, tag, "asset-url") + return f' url = "{asset_url}";\n sha256 = "{nix_hash}";' + + +def build_example(import_path: str, replacement: str) -> str: + return "\n".join( + [ + "```nix", + "let", + " deferred-apps = import (fetchTarball {", + replacement, + " });", + "in {", + f" imports = [ deferred-apps.{import_path} ];", + " programs.deferredApps.enable = true;", + " programs.deferredApps.packages = with pkgs; [ hello ];", + "}", + "```", + ] + ) + + +def replace_managed_block(content: str, name: str, replacement: str) -> str: + start_marker = START_MARKER_TEMPLATE.format(name=name) + end_marker = END_MARKER_TEMPLATE.format(name=name) + + start_index = content.find(start_marker) + end_index = content.find(end_marker) + if start_index == -1 or end_index == -1: + raise ValueError(f"Missing managed README markers for {name}") + if end_index <= start_index: + raise ValueError(f"Invalid managed README marker order for {name}") + + block_start = start_index + len(start_marker) + updated_block = f"\n{replacement}\n" + return content[:block_start] + updated_block + content[end_index:] + + +def update_readme(content: str, replacement: str) -> str: + updated = replace_managed_block( + content, + "nixos", + build_example("nixosModules.default", replacement), + ) + return replace_managed_block( + updated, + "home-manager", + build_example("homeManagerModules.default", replacement), + ) + + +def main() -> int: + parser = argparse.ArgumentParser( + description="Update or verify README fetchTarball release snippets." + ) + parser.add_argument( + "--version", required=True, help="Release version, with or without v prefix" + ) + parser.add_argument( + "--tarball", required=True, help="Path to release source tarball" + ) + parser.add_argument("--readme", help="README path", default=None) + parser.add_argument( + "--check", + action="store_true", + help="Verify README already contains the expected release URL and hash", + ) + args = parser.parse_args() + + scripts_dir = pathlib.Path(__file__).resolve().parent + repo_root = scripts_dir.parent + readme_path = ( + pathlib.Path(args.readme).resolve() if args.readme else repo_root / "README.md" + ) + tarball_path = pathlib.Path(args.tarball).resolve() + + tag = normalize_tag(args.version) + nix_hash = compute_nix_hash(scripts_dir, tarball_path) + replacement = build_expected_pair(tag, nix_hash) + + content = readme_path.read_text(encoding="utf-8") + try: + updated_content = update_readme(content, replacement) + except ValueError as exc: + print(str(exc), file=sys.stderr) + return 1 + + if args.check: + if content != updated_content: + print( + f"README release snippets do not match {tag} / {nix_hash}", + file=sys.stderr, + ) + return 1 + + print(f"README release snippets already match {tag} / {nix_hash}") + return 0 + + if content != updated_content: + readme_path.write_text(updated_content, encoding="utf-8") + + print(f"Updated README release snippets to {tag} / {nix_hash}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/cli-mode.nix b/tests/cli-mode.nix new file mode 100644 index 0000000..1a6fc0c --- /dev/null +++ b/tests/cli-mode.nix @@ -0,0 +1,157 @@ +# CLI-Only Mode Tests +# +# Tests for cliOnly parameter which creates wrappers without desktop files +# or icons, perfect for CLI tools like ripgrep, fd, jq, etc. +# +{ helpers, pkgs }: + +let + inherit (helpers) + deferredAppsLib + mkBuildCheck + mkCheck + evalModule + mkClosureCheck + ; + +in +{ + # =========================================================================== + # Test 1: CLI-only has bin symlink (package mode) + # =========================================================================== + cli-mode-has-bin = + mkBuildCheck "cli-mode-has-bin" + (deferredAppsLib.mkDeferredApp { + package = pkgs.ripgrep; + cliOnly = true; + }) + '' + test -L "$drvPath/bin/rg" || { echo "FAIL: missing bin symlink"; exit 1; } + echo "PASS: bin symlink exists" + ''; + + # =========================================================================== + # Test 2: CLI-only has NO desktop file + # =========================================================================== + cli-mode-no-desktop = + mkBuildCheck "cli-mode-no-desktop" + (deferredAppsLib.mkDeferredApp { + package = pkgs.ripgrep; + cliOnly = true; + }) + '' + if [ -d "$drvPath/share/applications" ]; then + echo "FAIL: cli-only should not have share/applications" + exit 1 + fi + echo "PASS: no desktop directory" + ''; + + # =========================================================================== + # Test 3: CLI-only has NO icons + # =========================================================================== + cli-mode-no-icons = + mkBuildCheck "cli-mode-no-icons" + (deferredAppsLib.mkDeferredApp { + package = pkgs.ripgrep; + cliOnly = true; + }) + '' + if [ -d "$drvPath/share/icons" ]; then + echo "FAIL: cli-only should not have share/icons" + exit 1 + fi + echo "PASS: no icons directory" + ''; + + # =========================================================================== + # Test 4: CLI-only with pname mode + # =========================================================================== + cli-mode-pname = + mkBuildCheck "cli-mode-pname" + (deferredAppsLib.mkDeferredApp { + pname = "fd"; + cliOnly = true; + }) + '' + test -L "$drvPath/bin/fd" || { echo "FAIL: missing bin symlink"; exit 1; } + test ! -d "$drvPath/share/applications" || { echo "FAIL: has desktop dir"; exit 1; } + echo "PASS: pname cli-only works" + ''; + + # =========================================================================== + # Test 5: Default cliOnly is false (backward compatibility) + # =========================================================================== + cli-mode-default-false = + mkBuildCheck "cli-mode-default-false" (deferredAppsLib.mkDeferredApp { package = pkgs.hello; }) + '' + test -d "$drvPath/share/applications" || { echo "FAIL: default should have desktop"; exit 1; } + echo "PASS: default has desktop file" + ''; + + # =========================================================================== + # Test 6: CLI-only closure doesn't contain icon theme + # =========================================================================== + cli-mode-no-icon-theme-closure = + mkClosureCheck "cli-mode-no-icon-theme-closure" + (deferredAppsLib.mkDeferredApp { + package = pkgs.ripgrep; + cliOnly = true; + }) + { + forbiddenPatterns = [ "papirus" ]; + maxPaths = 3; # Just wrapper, symlink, and bash + }; + + # =========================================================================== + # Test 7: Module cliPackages option + # =========================================================================== + cli-mode-module-packages = + let + eval = evalModule { + programs.deferredApps = { + enable = true; + cliPackages = [ + pkgs.ripgrep + pkgs.fd + ]; + }; + }; + # Should have at least 2 CLI apps + libnotify + in + mkCheck "cli-mode-module-packages" (builtins.length eval.config.environment.systemPackages >= 3); + + # =========================================================================== + # Test 8: Module cliApps option + # =========================================================================== + cli-mode-module-apps = + let + eval = evalModule { + programs.deferredApps = { + enable = true; + cliApps = [ + "hello" + "cowsay" + ]; + }; + }; + # Should have at least 2 CLI apps + libnotify + in + mkCheck "cli-mode-module-apps" (builtins.length eval.config.environment.systemPackages >= 3); + + # =========================================================================== + # Test 9: CLI-only can be combined with cliPackages and packages + # =========================================================================== + cli-mode-mixed = + let + eval = evalModule { + programs.deferredApps = { + enable = true; + cliPackages = [ pkgs.ripgrep ]; # CLI-only + packages = [ pkgs.hello ]; # GUI app (default) + }; + }; + # Should have: ripgrep (cli), hello (gui), libnotify + in + mkCheck "cli-mode-mixed" (builtins.length eval.config.environment.systemPackages >= 3); +} diff --git a/tests/default.nix b/tests/default.nix index d8b2822..7481415 100644 --- a/tests/default.nix +++ b/tests/default.nix @@ -81,9 +81,10 @@ let nestedTests = import ./nested.nix { inherit pkgs lib helpers; }; errorTests = import ./error.nix { inherit helpers; }; compatTests = import ./compat.nix { inherit pkgs; }; + cliModeTests = import ./cli-mode.nix { inherit helpers pkgs; }; + # Meta test for infrastructure validation in -# Meta test for infrastructure validation { meta-test-infrastructure = helpers.mkCheckValidator "test-infrastructure"; } @@ -98,3 +99,4 @@ in // nestedTests // errorTests // compatTests +// cliModeTests diff --git a/tests/home-manager.nix b/tests/home-manager.nix index 6dcc0b9..3acc40e 100644 --- a/tests/home-manager.nix +++ b/tests/home-manager.nix @@ -10,11 +10,7 @@ }: let - inherit (helpers) - evalHomeModule - forceEvalHomePackages - mkCheck - ; + inherit (helpers) evalHomeModule forceEvalHomePackages mkCheck; in { # =========================================================================== @@ -193,6 +189,28 @@ in in mkCheck "hm-module-iconTheme-custom-name" (forceEvalHomePackages eval); + # Test: Custom iconTheme package in HM module + hm-module-iconTheme-custom-package = + let + eval = evalHomeModule { + programs.deferredApps = { + enable = true; + extraApps.hello.icon = "preferences-desktop-multitasking-symbolic"; + iconTheme = { + enable = true; + package = pkgs.adwaita-icon-theme; + name = "Adwaita"; + }; + }; + }; + packageNames = map (pkg: pkg.name or "") eval.config.home.packages; + hasAdwaita = lib.any (name: lib.hasInfix "adwaita-icon-theme" name) packageNames; + hasPapirus = lib.any (name: lib.hasInfix "papirus" name) packageNames; + in + mkCheck "hm-module-iconTheme-custom-package" ( + forceEvalHomePackages eval && hasAdwaita && !hasPapirus + ); + # =========================================================================== # SESSION VARIABLES TEST # =========================================================================== @@ -215,6 +233,40 @@ in in mkCheck "hm-module-session-variables" (hasIconThemeVar && iconThemeValue == "Papirus-Dark"); + # Test: Pure CLI-only HM config should not set GTK_ICON_THEME + hm-module-no-session-variables-for-cli-only = + let + eval = evalHomeModule { + programs.deferredApps = { + enable = true; + cliPackages = [ pkgs.ripgrep ]; + cliApps = [ "hello" ]; + extraApps.cowsay.cliOnly = true; + }; + }; + hasIconThemeVar = eval.config.home.sessionVariables ? GTK_ICON_THEME; + in + mkCheck "hm-module-no-session-variables-for-cli-only" (!hasIconThemeVar); + + # Test: Mixed GUI + CLI HM config should still set GTK_ICON_THEME + hm-module-session-variables-retained-for-mixed = + let + eval = evalHomeModule { + programs.deferredApps = { + enable = true; + packages = [ pkgs.hello ]; + cliPackages = [ pkgs.ripgrep ]; + extraApps.cowsay.cliOnly = true; + iconTheme.name = "Papirus-Dark"; + }; + }; + hasIconThemeVar = eval.config.home.sessionVariables ? GTK_ICON_THEME; + iconThemeValue = eval.config.home.sessionVariables.GTK_ICON_THEME or ""; + in + mkCheck "hm-module-session-variables-retained-for-mixed" ( + hasIconThemeVar && iconThemeValue == "Papirus-Dark" + ); + # Test: No GTK_ICON_THEME when iconTheme disabled hm-module-no-session-variables = let diff --git a/tests/lib.nix b/tests/lib.nix index 981500e..e6449e5 100644 --- a/tests/lib.nix +++ b/tests/lib.nix @@ -21,6 +21,7 @@ let minimalNixosConfig = { boot.loader.grub.enable = false; fileSystems."/".device = "none"; + fileSystems."/".fsType = "tmpfs"; system.stateVersion = "25.11"; }; diff --git a/tests/module.nix b/tests/module.nix index 000d2d6..fd8acd2 100644 --- a/tests/module.nix +++ b/tests/module.nix @@ -312,6 +312,40 @@ in in mkCheck "module-iconTheme-custom-package" (forceEvalPackages eval && hasAdwaita && !hasPapirus); + # Test: Pure CLI-only module config should not set GTK_ICON_THEME + module-no-environment-variables-for-cli-only = + let + eval = evalModule { + programs.deferredApps = { + enable = true; + cliPackages = [ pkgs.ripgrep ]; + cliApps = [ "hello" ]; + extraApps.cowsay.cliOnly = true; + }; + }; + hasIconThemeVar = eval.config.environment.variables ? GTK_ICON_THEME; + in + mkCheck "module-no-environment-variables-for-cli-only" (!hasIconThemeVar); + + # Test: Mixed GUI + CLI module config should still set GTK_ICON_THEME + module-environment-variables-retained-for-mixed = + let + eval = evalModule { + programs.deferredApps = { + enable = true; + packages = [ pkgs.hello ]; + cliPackages = [ pkgs.ripgrep ]; + extraApps.cowsay.cliOnly = true; + iconTheme.name = "Papirus-Dark"; + }; + }; + hasIconThemeVar = eval.config.environment.variables ? GTK_ICON_THEME; + iconThemeValue = eval.config.environment.variables.GTK_ICON_THEME or ""; + in + mkCheck "module-environment-variables-retained-for-mixed" ( + hasIconThemeVar && iconThemeValue == "Papirus-Dark" + ); + # =========================================================================== # MODULE ENABLE/DISABLE TESTS # =========================================================================== diff --git a/tests/nested.nix b/tests/nested.nix index bdeb140..c1ef9d9 100644 --- a/tests/nested.nix +++ b/tests/nested.nix @@ -311,12 +311,12 @@ in { echo "FAIL: PNAME should be full nested path"; exit 1; } ''; - # Test: Real-world nested package - nodePackages + # Test: Real-world nested package - php83Packages nested-node = - mkBuildCheck "nested-node" (deferredAppsLib.mkDeferredApp { pname = "nodePackages.typescript"; }) + mkBuildCheck "nested-node" (deferredAppsLib.mkDeferredApp { pname = "php83Packages.composer"; }) '' - test -x "$drvPath/libexec/deferred-nodePackages.typescript" || \ - { echo "FAIL: node package wrapper missing"; exit 1; } + test -x "$drvPath/libexec/deferred-php83Packages.composer" || \ + { echo "FAIL: nested php package wrapper missing"; exit 1; } ''; # Test: Real-world nested package - perlPackages @@ -353,11 +353,15 @@ in # Test: Nonexistent nested package throws error error-nested-nonexistent = testShouldFail "error-nested-nonexistent" ( - deferredAppsLib.mkDeferredApp { pname = "python313Packages.thisPackageDoesNotExist12345"; } + deferredAppsLib.mkDeferredApp { + pname = "python313Packages.thisPackageDoesNotExist12345"; + } ); # Test: Nonexistent parent in nested path error-nested-nonexistent-parent = testShouldFail "error-nested-nonexistent-parent" ( - deferredAppsLib.mkDeferredApp { pname = "nonExistentPackageSet12345.somePackage"; } + deferredAppsLib.mkDeferredApp { + pname = "nonExistentPackageSet12345.somePackage"; + } ); }