From 4284f4f016e517a6f0cef5af311582d219eb91c2 Mon Sep 17 00:00:00 2001 From: WitteShadovv <26429638+WitteShadovv@users.noreply.github.com> Date: Sat, 3 Jan 2026 21:39:55 +0100 Subject: [PATCH 01/10] feat: Add notification customization options (REQ-007) Add notificationTitle, notificationBody, and showNotification options to mkDeferredApp: - notificationTitle: Override default "Starting {app}..." title - notificationBody: Override default "Downloading application..." body - showNotification: Enable/disable notifications (default: true) Both pname and package modes support these options. Per-app overrides available via extraApps in module. Uses {app} placeholder for substitution in wrapper scripts. Ref: modules/shared.nix --- modules/shared.nix | 372 ++++++++++--------- package.nix | 893 ++++++++++++++++++++++----------------------- 2 files changed, 626 insertions(+), 639 deletions(-) diff --git a/modules/shared.nix b/modules/shared.nix index 9212c91..bfb0a6f 100644 --- a/modules/shared.nix +++ b/modules/shared.nix @@ -19,17 +19,9 @@ # { target }: -assert builtins.elem target [ - "nixos" - "home-manager" -]; - -{ - config, - lib, - pkgs, - ... -}: +assert builtins.elem target [ "nixos" "home-manager" ]; + +{ config, lib, pkgs, ... }: let cfg = config.programs.deferredApps; @@ -100,10 +92,7 @@ let categories = lib.mkOption { type = lib.types.listOf lib.types.str; default = [ "Application" ]; - example = [ - "AudioVideo" - "Audio" - ]; + example = [ "AudioVideo" "Audio" ]; description = "Freedesktop.org desktop entry categories."; }; @@ -162,6 +151,42 @@ 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. + ''; + }; }; }; @@ -170,132 +195,130 @@ let # =========================================================================== # Build the list of deferred app packages (shared between NixOS and HM) - buildDeferredPackages = - let - # Names configured in extraApps (these take precedence over apps list) - extraNames = lib.attrNames cfg.extraApps; - - # Filter out apps that have extraApps overrides - filteredApps = lib.filter (name: !(lib.elem name extraNames)) cfg.apps; - - # Separate extraApps into pname-mode and package-mode entries - extraAppsWithPackage = lib.filterAttrs (_: opts: opts.package != null) cfg.extraApps; - extraAppsWithPname = lib.filterAttrs (_: opts: opts.package == null) cfg.extraApps; - - # Build config list for collision detection - # Includes: apps (pname), packages (direct), extraApps (both modes) - allAppConfigs = - # Standard apps (pname mode) - (map (pname: { - inherit pname; - createTerminalCommand = true; - }) filteredApps) - # Global packages list (package mode) - ++ (map (package: { - inherit package; - createTerminalCommand = true; - }) cfg.packages) - # extraApps with pname mode - ++ (lib.mapAttrsToList (pname: opts: { - inherit pname; - inherit (opts) exe createTerminalCommand; - }) extraAppsWithPname) - # extraApps with package mode - use key name as pnameOverride - ++ (lib.mapAttrsToList (name: opts: { - inherit (opts) package exe createTerminalCommand; - pnameOverride = name; # Use key name for collision detection - }) extraAppsWithPackage); - - # Check for terminal command collisions across ALL apps - collision = deferredAppsLib.detectTerminalCollisions allAppConfigs; - - # Build standard apps (pname mode, auto-detected metadata) - standardApps = map ( - pname: - deferredAppsLib.mkDeferredApp { - inherit pname; - inherit (cfg) flakeRef allowUnfree gcRoot; - } - ) filteredApps; - - # Build global packages list (package mode) - packageApps = map ( - package: - deferredAppsLib.mkDeferredApp { - inherit package; - inherit (cfg) gcRoot; - } - ) cfg.packages; - - # Build extra apps with pname mode (manual configuration) - extraAppsListPname = lib.mapAttrsToList ( - pname: opts: - deferredAppsLib.mkDeferredApp { - inherit pname; - inherit (opts) - exe - desktopName - description - icon - categories - createTerminalCommand - ; - # 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; - gcRoot = if opts.gcRoot != null then opts.gcRoot else cfg.gcRoot; - } - ) extraAppsWithPname; - - # 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. - extraAppsListPackage = lib.mapAttrsToList ( - name: opts: - deferredAppsLib.mkDeferredApp { - inherit (opts) - package - exe - desktopName - description - icon - categories - createTerminalCommand - ; - # Use the key name as pname for desktop file naming - # This prevents collisions like apps=["spotify"] + extraApps.spotify-unstable.package - pnameOverride = name; - # gcRoot can still be overridden per-app - gcRoot = if opts.gcRoot != null then opts.gcRoot else cfg.gcRoot; - # Note: flakeRef and allowUnfree are ignored in package mode - } - ) extraAppsWithPackage; + buildDeferredPackages = let + # Names configured in extraApps (these take precedence over apps list) + extraNames = lib.attrNames cfg.extraApps; + + # Filter out apps that have extraApps overrides + filteredApps = lib.filter (name: !(lib.elem name extraNames)) cfg.apps; + + # Separate extraApps into pname-mode and package-mode entries + extraAppsWithPackage = + lib.filterAttrs (_: opts: opts.package != null) cfg.extraApps; + extraAppsWithPname = + lib.filterAttrs (_: opts: opts.package == null) cfg.extraApps; + + # Build config list for collision detection + # Includes: apps (pname), packages (direct), extraApps (both modes) + allAppConfigs = + # Standard apps (pname mode) + (map (pname: { + inherit pname; + createTerminalCommand = true; + }) filteredApps) + # Global packages list (package mode) + ++ (map (package: { + inherit package; + createTerminalCommand = true; + }) cfg.packages) + # extraApps with pname mode + ++ (lib.mapAttrsToList (pname: opts: { + inherit pname; + inherit (opts) exe createTerminalCommand; + }) extraAppsWithPname) + # extraApps with package mode - use key name as pnameOverride + ++ (lib.mapAttrsToList (name: opts: { + inherit (opts) package exe createTerminalCommand; + pnameOverride = name; # Use key name for collision detection + }) extraAppsWithPackage); + + # Check for terminal command collisions across ALL apps + collision = deferredAppsLib.detectTerminalCollisions allAppConfigs; + + # Build standard apps (pname mode, auto-detected metadata) + standardApps = map (pname: + deferredAppsLib.mkDeferredApp { + inherit pname; + inherit (cfg) flakeRef allowUnfree gcRoot; + }) filteredApps; + + # Build global packages list (package mode) + packageApps = map (package: + deferredAppsLib.mkDeferredApp { + inherit package; + inherit (cfg) gcRoot; + }) cfg.packages; + + # Build extra apps with pname mode (manual configuration) + extraAppsListPname = lib.mapAttrsToList (pname: opts: + deferredAppsLib.mkDeferredApp { + inherit pname; + inherit (opts) + exe desktopName description icon categories createTerminalCommand; + # 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; + gcRoot = if opts.gcRoot != null then opts.gcRoot else cfg.gcRoot; + }) extraAppsWithPname; + + # 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. + extraAppsListPackage = lib.mapAttrsToList (name: opts: + deferredAppsLib.mkDeferredApp { + inherit (opts) + package exe desktopName description icon categories + createTerminalCommand; + # 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; + # gcRoot can still be overridden per-app + gcRoot = if opts.gcRoot != null then opts.gcRoot else cfg.gcRoot; + # Note: flakeRef and allowUnfree are ignored in package mode + }) extraAppsWithPackage; + + # Icon theme package (if enabled) + iconThemePackages = lib.optional cfg.iconTheme.enable cfg.iconTheme.package; - # Icon theme package (if enabled) - iconThemePackages = lib.optional cfg.iconTheme.enable cfg.iconTheme.package; - - in # Assert no terminal command collisions before building - assert lib.assertMsg (collision == null) collision; - standardApps - ++ packageApps - ++ extraAppsListPname - ++ extraAppsListPackage - ++ iconThemePackages - ++ [ - pkgs.libnotify # Required for notifications - ]; - -in -{ + in assert lib.assertMsg (collision == null) collision; + standardApps ++ packageApps ++ extraAppsListPname ++ extraAppsListPackage + ++ iconThemePackages ++ [ + pkgs.libnotify # Required for notifications + ]; + +in { # =========================================================================== # Options (shared between NixOS and Home Manager) # =========================================================================== options.programs.deferredApps = { - enable = lib.mkEnableOption "deferred applications that download on first launch"; + enable = + lib.mkEnableOption "deferred applications that download on first launch"; apps = lib.mkOption { type = lib.types.listOf lib.types.str; @@ -387,7 +410,10 @@ in which includes icons for most popular applications like Spotify, Discord, OBS, etc. Disable this if you already have an icon theme configured${ - if target == "home-manager" then " via Home Manager's gtk.iconTheme" else " system-wide" + if target == "home-manager" then + " via Home Manager's gtk.iconTheme" + else + " system-wide" }. ''; }; @@ -505,45 +531,39 @@ in # Config (target-specific implementation) # =========================================================================== - config = lib.mkIf cfg.enable ( - if target == "nixos" then - # ------------------------------------------------------------------------- - # NixOS Configuration - # ------------------------------------------------------------------------- - { - environment = { - systemPackages = buildDeferredPackages; - - # Link desktop entries and icons into system profile - pathsToLink = [ - "/share/applications" - "/share/icons" - ]; - - # 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 { - # This is a hint for applications; DE settings take precedence - GTK_ICON_THEME = lib.mkDefault cfg.iconTheme.name; - }; - }; - } - else - # ------------------------------------------------------------------------- - # Home Manager Configuration - # ------------------------------------------------------------------------- - { - home.packages = buildDeferredPackages; - - # Home Manager automatically links share/applications and share/icons - # from packages in home.packages, so no pathsToLink equivalent needed. - - # 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 { - GTK_ICON_THEME = lib.mkDefault cfg.iconTheme.name; - }; - } - ); + config = lib.mkIf cfg.enable (if target == "nixos" then + # ------------------------------------------------------------------------- + # NixOS Configuration + # ------------------------------------------------------------------------- + { + environment = { + systemPackages = buildDeferredPackages; + + # Link desktop entries and icons into system profile + pathsToLink = [ "/share/applications" "/share/icons" ]; + + # 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 { + # This is a hint for applications; DE settings take precedence + GTK_ICON_THEME = lib.mkDefault cfg.iconTheme.name; + }; + }; + } else + # ------------------------------------------------------------------------- + # Home Manager Configuration + # ------------------------------------------------------------------------- + { + home.packages = buildDeferredPackages; + + # Home Manager automatically links share/applications and share/icons + # from packages in home.packages, so no pathsToLink equivalent needed. + + # 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 { + GTK_ICON_THEME = lib.mkDefault cfg.iconTheme.name; + }; + }); } diff --git a/package.nix b/package.nix index a09398b..ee42ff1 100644 --- a/package.nix +++ b/package.nix @@ -46,12 +46,8 @@ # If you're not using the NixOS module (which includes libnotify), # ensure libnotify is available in your environment for notifications to work. # The wrapper gracefully degrades if notify-send is unavailable. -{ - pkgs, - lib, - iconThemePackage ? pkgs.papirus-icon-theme, - iconThemeName ? "Papirus-Dark", -}: +{ pkgs, lib, iconThemePackage ? pkgs.papirus-icon-theme +, iconThemeName ? "Papirus-Dark", }: let inherit (pkgs) runCommand writeText makeDesktopItem; @@ -61,37 +57,31 @@ let # =========================================================================== # Validate a single segment of pname (between dots) - validatePnameSegment = - segment: pname: - assert lib.assertMsg (segment != "") "deferred-apps: pname segment cannot be empty (got: ${pname})"; - assert lib.assertMsg ( - !(lib.hasInfix "/" segment) - ) "deferred-apps: pname cannot contain '/' (got: ${pname})"; - assert lib.assertMsg ( - !(lib.hasInfix " " segment) - ) "deferred-apps: pname cannot contain spaces (got: ${pname})"; - assert lib.assertMsg ( - !(lib.hasPrefix "-" segment) - ) "deferred-apps: pname segment cannot start with '-' (got: ${pname})"; + validatePnameSegment = segment: pname: + assert lib.assertMsg (segment != "") + "deferred-apps: pname segment cannot be empty (got: ${pname})"; + assert lib.assertMsg (!(lib.hasInfix "/" segment)) + "deferred-apps: pname cannot contain '/' (got: ${pname})"; + assert lib.assertMsg (!(lib.hasInfix " " segment)) + "deferred-apps: pname cannot contain spaces (got: ${pname})"; + assert lib.assertMsg (!(lib.hasPrefix "-" segment)) + "deferred-apps: pname segment cannot start with '-' (got: ${pname})"; segment; # Validate pname to catch common errors early # Supports both simple names ("hello") and nested packages ("python313Packages.numpy") - validatePname = - pname: + validatePname = pname: let # Split by dots to validate each segment segments = lib.splitString "." pname; # Validate each segment validatedSegments = map (seg: validatePnameSegment seg pname) segments; - in - assert lib.assertMsg (pname != "") "deferred-apps: pname cannot be empty"; - assert lib.assertMsg ( - !(lib.hasPrefix "." pname) - ) "deferred-apps: pname cannot start with '.' (got: ${pname})"; - assert lib.assertMsg ( - !(lib.hasSuffix "." pname) - ) "deferred-apps: pname cannot end with '.' (got: ${pname})"; + in assert lib.assertMsg (pname != "") + "deferred-apps: pname cannot be empty"; + assert lib.assertMsg (!(lib.hasPrefix "." pname)) + "deferred-apps: pname cannot start with '.' (got: ${pname})"; + assert lib.assertMsg (!(lib.hasSuffix "." pname)) + "deferred-apps: pname cannot end with '.' (got: ${pname})"; # Force evaluation of all segment validations builtins.seq (builtins.deepSeq validatedSegments validatedSegments) pname; @@ -106,29 +96,24 @@ let # Get package by navigating nested attributes # Supports both simple ("hello") and nested ("python313Packages.numpy") paths - getPackage = - pname: - let - path = parsePname pname; - in - lib.attrByPath path null pkgs; + getPackage = pname: + let path = parsePname pname; + in lib.attrByPath path null pkgs; # Validate package exists with helpful error - requirePackage = - pname: + requirePackage = pname: let pkg = getPackage pname; isNested = lib.hasInfix "." pname; - in - if pkg == null then + in if pkg == null then throw '' deferred-apps: Package '${pname}' not found in nixpkgs. - ${ - if isNested then - "Nested package path checked: ${lib.concatStringsSep " -> " (parsePname pname)}" - else - "Check the spelling or use 'extraApps' with manual configuration." - } + ${if isNested then + "Nested package path checked: ${ + lib.concatStringsSep " -> " (parsePname pname) + }" + else + "Check the spelling or use 'extraApps' with manual configuration."} '' else pkg; @@ -138,37 +123,33 @@ let getMainProgram = pname: (requirePackage pname).meta.mainProgram or pname; # Extract description from package meta - getDescription = - pname: - let - pkg = getPackage pname; - in - if pkg == null then "Application" else pkg.meta.description or "Application"; + getDescription = pname: + let pkg = getPackage pname; + in if pkg == null then + "Application" + else + pkg.meta.description or "Application"; # Check if a package is unfree (requires --impure with NIXPKGS_ALLOW_UNFREE) # Handles packages with single license or list of licenses (dual-licensed) - isPackageUnfree = - pname: + isPackageUnfree = pname: let pkg = getPackage pname; # Normalize to list - some packages have single license, some have a list licenses = lib.toList (pkg.meta.license or [ ]); # Package is unfree if ANY license is unfree hasUnfreeLicense = lib.any (l: !(l.free or true)) licenses; - in - if pkg == null then + in if pkg == null then false # Assume free for unknown packages else hasUnfreeLicense; # Check if a direct package derivation is unfree - isDerivationUnfree = - pkg: + isDerivationUnfree = pkg: let licenses = lib.toList (pkg.meta.license or [ ]); hasUnfreeLicense = lib.any (l: !(l.free or true)) licenses; - in - hasUnfreeLicense; + in hasUnfreeLicense; # =========================================================================== # Package Derivation Helpers (for direct package references) @@ -176,21 +157,17 @@ let # Helper: takeWhile implementation (not in nixpkgs lib) # Takes elements from a list while predicate is true - takeWhile = - pred: list: + takeWhile = pred: list: let - go = - acc: xs: + go = acc: xs: if xs == [ ] then acc else let head = builtins.head xs; tail = builtins.tail xs; - in - if pred head then go (acc ++ [ head ]) tail else acc; - in - go [ ] list; + in if pred head then go (acc ++ [ head ]) tail else acc; + in go [ ] list; # Extract pname from a package derivation # Falls back to name parsing if pname is not available @@ -200,31 +177,27 @@ let # - Packages where name = "hello-2.12.1" → "hello" # - Packages where name starts with number like "7zip-24.08" → "7zip" # - Packages like "2048-in-terminal-1.0" → "2048-in-terminal" - getPnameFromPackage = - pkg: - pkg.pname or ( - let - name = pkg.name or "unknown"; - # Split on "-" and take parts that don't look like versions - # A version part is one that: - # - Contains a dot and starts with digits (e.g., "2.12.1", "24.08") - # - OR starts with digits followed by version suffix (e.g., "2rc1", "1alpha") - # Note: Bare numbers like "2048" are NOT considered versions - parts = lib.splitString "-" name; - isVersionPart = - p: - builtins.match "[0-9]+[.][0-9]+(.*)" p != null - || builtins.match "[0-9]+(rc|alpha|beta|pre|post)[0-9]*" p != null; - nonVersionParts = takeWhile (p: !isVersionPart p) parts; - result = lib.concatStringsSep "-" nonVersionParts; - in + getPnameFromPackage = pkg: + pkg.pname or (let + name = pkg.name or "unknown"; + # Split on "-" and take parts that don't look like versions + # A version part is one that: + # - Contains a dot and starts with digits (e.g., "2.12.1", "24.08") + # - OR starts with digits followed by version suffix (e.g., "2rc1", "1alpha") + # Note: Bare numbers like "2048" are NOT considered versions + parts = lib.splitString "-" name; + isVersionPart = p: + builtins.match "[0-9]+[.][0-9]+(.*)" p != null + || 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) - if result == "" then name else result - ); + in if result == "" then name else result); # Extract mainProgram from a package derivation - getMainProgramFromPackage = pkg: pkg.meta.mainProgram or (getPnameFromPackage pkg); + getMainProgramFromPackage = pkg: + pkg.meta.mainProgram or (getPnameFromPackage pkg); # Extract description from a package derivation getDescriptionFromPackage = pkg: pkg.meta.description or "Application"; @@ -234,17 +207,14 @@ let # =========================================================================== # "foo" -> "Foo" - capitalize = - s: + capitalize = s: let first = lib.substring 0 1 s; rest = lib.substring 1 (-1) s; - in - lib.toUpper first + rest; + in lib.toUpper first + rest; # "obs-studio" -> "Obs Studio" - toDisplayName = - pname: + toDisplayName = pname: lib.pipe pname [ (lib.splitString "-") (map capitalize) @@ -257,7 +227,8 @@ let # Icon sizes to search, in order of preference # 64x64 is ideal for app launchers, scalable SVGs are good too - iconSizesList = "64x64 scalable 48x48 128x128 96x96 256x256 32x32 24x24 22x22 16x16"; + iconSizesList = + "64x64 scalable 48x48 128x128 96x96 256x256 32x32 24x24 22x22 16x16"; # =========================================================================== # Public API @@ -302,21 +273,13 @@ let # regardless of the user's selected icon theme (e.g., Yaru doesn't include # third-party app icons like Spotify, Discord, etc.). # - mkDeferredApp = - { - pname ? null, - package ? null, - pnameOverride ? null, # Override the derived pname (for extraApps with package mode) - exe ? null, - desktopName ? null, - description ? null, - icon ? null, - categories ? [ "Application" ], - flakeRef ? "nixpkgs", - createTerminalCommand ? true, - allowUnfree ? false, - gcRoot ? false, - }: + mkDeferredApp = { pname ? null, package ? null, pnameOverride ? null + , # Override the derived pname (for extraApps with package mode) + exe ? null, desktopName ? null, description ? null, icon ? null + , categories ? [ "Application" ], flakeRef ? "nixpkgs" + , createTerminalCommand ? true, allowUnfree ? false, gcRoot ? false + , notificationTitle ? null, notificationBody ? null, showNotification ? true + , }: let # =========================================================================== # Mode Detection and Validation @@ -328,13 +291,10 @@ let # Validate: must have exactly one of pname or package # The `mode` variable is used in the derivation to force assertion evaluation - mode = - assert lib.assertMsg ( - hasPackage || hasPname - ) "deferred-apps: Must provide either 'pname' or 'package'"; - assert lib.assertMsg ( - !(hasPackage && hasPname) - ) "deferred-apps: Cannot provide both 'pname' and 'package'. Use one or the other."; + mode = assert lib.assertMsg (hasPackage || hasPname) + "deferred-apps: Must provide either 'pname' or 'package'"; + assert lib.assertMsg (!(hasPackage && hasPname)) + "deferred-apps: Cannot provide both 'pname' and 'package'. Use one or the other."; if hasPackage then "package" else "pname"; # =========================================================================== @@ -344,13 +304,17 @@ let # Extract metadata from the package derivation # Guard these to avoid errors when package is null pkgPname = if hasPackage then getPnameFromPackage package else ""; - pkgExe = - if hasPackage then (if exe != null then exe else getMainProgramFromPackage package) else ""; - pkgDescription = - if hasPackage then - (if description != null then description else getDescriptionFromPackage package) + pkgExe = if hasPackage then + (if exe != null then exe else getMainProgramFromPackage package) + else + ""; + pkgDescription = if hasPackage then + (if description != null then + description else - ""; + getDescriptionFromPackage package) + else + ""; pkgIsUnfree = if hasPackage then isDerivationUnfree package else false; # Capture paths for runtime realization @@ -368,8 +332,14 @@ let # # This is a major improvement over the previous appendContext approach which # pulled ALL transitive .drv files into the system closure. - pkgDrvPath = if hasPackage then builtins.unsafeDiscardStringContext package.drvPath else ""; - pkgOutPath = if hasPackage then builtins.unsafeDiscardStringContext package.outPath else ""; + pkgDrvPath = if hasPackage then + builtins.unsafeDiscardStringContext package.drvPath + else + ""; + pkgOutPath = if hasPackage then + builtins.unsafeDiscardStringContext package.outPath + else + ""; # =========================================================================== # Pname Mode: Lookup by attribute name @@ -378,18 +348,21 @@ let # Validate pname if provided # For package mode with pnameOverride, use the override for desktop file naming # This allows extraApps.spotify-unstable.package to create spotify-unstable.desktop - validatedPname = - if pnameOverride != null then - validatePname pnameOverride - else if hasPname then - validatePname pname - else - pkgPname; + validatedPname = if pnameOverride != null then + validatePname pnameOverride + else if hasPname then + validatePname pname + else + pkgPname; # Get metadata from nixpkgs lookup pnameExe = if exe != null then exe else getMainProgram validatedPname; - pnameDescription = if description != null then description else getDescription validatedPname; - pnameIsUnfree = if hasPname then isPackageUnfree validatedPname else false; + pnameDescription = if description != null then + description + else + getDescription validatedPname; + pnameIsUnfree = + if hasPname then isPackageUnfree validatedPname else false; # =========================================================================== # Common Logic (both modes) @@ -397,7 +370,8 @@ let # Select the right values based on mode finalExe = if hasPackage then pkgExe else pnameExe; - finalDescription = if hasPackage then pkgDescription else pnameDescription; + finalDescription = + if hasPackage then pkgDescription else pnameDescription; packageIsUnfree = if hasPackage then pkgIsUnfree else pnameIsUnfree; # Terminal command is the user-facing symlink name @@ -405,12 +379,16 @@ let terminalCommand = lib.toLower finalExe; # Desktop name generation - finalDesktopName = if desktopName != null then desktopName else toDisplayName validatedPname; + finalDesktopName = if desktopName != null then + desktopName + else + toDisplayName validatedPname; # Security: Check unfree status # For package mode: unfree packages work directly (no --impure needed for nix-store --realise) # For pname mode: unfree packages need --impure with NIXPKGS_ALLOW_UNFREE - needsImpure = if hasPackage then false else (packageIsUnfree && allowUnfree); + needsImpure = + if hasPackage then false else (packageIsUnfree && allowUnfree); # Icon name to search for iconName = if icon != null then icon else validatedPname; @@ -422,63 +400,75 @@ let # =========================================================================== # Wrapper for PNAME mode (uses nix shell) - wrapperScriptPname = writeText "deferred-${validatedPname}-wrapper-pname" '' - #!/usr/bin/env bash - set -euo pipefail - - PNAME="@pname@" - FLAKE_REF="@flakeRef@" - EXE="@exe@" - ICON="@icon@" - NEEDS_IMPURE="@needsImpure@" - GC_ROOT="@gcRoot@" - - # 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 - } - - # 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 - - 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 - } - - 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 - ''; + wrapperScriptPname = + writeText "deferred-${validatedPname}-wrapper-pname" '' + #!/usr/bin/env bash + set -euo pipefail + + 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 [ "$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") + + 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 + + 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 + + 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) # @@ -494,100 +484,113 @@ let # This assumes the binary is in $out/bin/. For packages with multiple outputs # 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 - - PNAME="@pname@" - DRV_PATH="@drvPath@" - OUT_PATH="@outPath@" - EXE="@exe@" - ICON="@icon@" - GC_ROOT="@gcRoot@" - - # 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 - - # 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 + wrapperScriptPackage = + writeText "deferred-${validatedPname}-wrapper-package" '' + #!/usr/bin/env bash + set -euo pipefail + + PNAME="@pname@" + DRV_PATH="@drvPath@" + OUT_PATH="@outPath@" + 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 [ "$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 + } + + # 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 + + # 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 + + # 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 - 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 - wrapperScript = if hasPackage then wrapperScriptPackage else wrapperScriptPname; + wrapperScript = + if hasPackage then wrapperScriptPackage else wrapperScriptPname; # Create the .desktop file desktopItem = makeDesktopItem { @@ -602,133 +605,121 @@ let startupWMClass = finalExe; }; - in - # Validation: unfree check for pname mode - assert lib.assertMsg (hasPackage || !packageIsUnfree || allowUnfree) + # Validation: unfree check for pname mode + in 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; - } - '' - # =========================================================================== - # 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" - - 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 - done - return 1 - } - - mkdir -p "$out/libexec" "$out/share/applications" "$out/share/icons" - - # Resolve and copy icon - RESOLVED_ICON="" - if [ -n "$userIcon" ]; then - # User provided absolute path - use as-is (they control the dependency) - RESOLVED_ICON="$userIcon" + 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; + # Notification variables + showNotificationStr = if showNotification != false then "1" else "0"; + notificationTitleValue = + if notificationTitle != null then + notificationTitle else - # Try to find icon in theme - THEME_ICON="" - if THEME_ICON=$(find_icon "$iconName"); then - : - elif THEME_ICON=$(find_icon "$iconNameFallback"); then - : - fi - - if [ -n "$THEME_ICON" ]; then - # Copy icon to our output to avoid depending on the entire theme package - # This reduces closure from ~1GB to ~5KB! - cp "$THEME_ICON" "$out/share/icons/$validatedPname.svg" - RESOLVED_ICON="$out/share/icons/$validatedPname.svg" - else - # No icon found - use name and hope DE can resolve it - echo "WARNING: Icon '$iconName' not found in theme. Desktop may show missing icon." >&2 - RESOLVED_ICON="$iconName" - fi + "Starting {app}..."; + notificationBodyValue = + if notificationBody != null then + notificationBody + else + "Downloading application (first run only)..."; + } + + mkdir -p "$out/libexec" "$out/share/applications" "$out/share/icons" + + # Resolve and copy icon + RESOLVED_ICON="" + if [ -n "$userIcon" ]; then + # User provided absolute path - use as-is (they control the dependency) + RESOLVED_ICON="$userIcon" + else + # Try to find icon in theme + THEME_ICON="" + if THEME_ICON=$(find_icon "$iconName"); then + : + elif THEME_ICON=$(find_icon "$iconNameFallback"); then + : fi - # =========================================================================== - # Create the wrapper script - # =========================================================================== - if [ -n "$isPackageMode" ]; then - # Package mode: substitute package-specific variables - substitute "$wrapperScript" "$out/libexec/deferred-$validatedPname" \ - --replace-fail '@icon@' "$RESOLVED_ICON" \ - --replace-fail '@pname@' "$validatedPname" \ - --replace-fail '@drvPath@' "$drvPath" \ - --replace-fail '@outPath@' "$outPath" \ - --replace-fail '@exe@' "$finalExe" \ - --replace-fail '@gcRoot@' "$gcRootStr" + if [ -n "$THEME_ICON" ]; then + # Copy icon to our output to avoid depending on the entire theme package + # This reduces closure from ~1GB to ~5KB! + cp "$THEME_ICON" "$out/share/icons/$validatedPname.svg" + RESOLVED_ICON="$out/share/icons/$validatedPname.svg" else - # Pname mode: substitute flake-specific variables - substitute "$wrapperScript" "$out/libexec/deferred-$validatedPname" \ - --replace-fail '@icon@' "$RESOLVED_ICON" \ - --replace-fail '@pname@' "$validatedPname" \ - --replace-fail '@flakeRef@' "$flakeRef" \ - --replace-fail '@exe@' "$finalExe" \ - --replace-fail '@needsImpure@' "$needsImpureStr" \ - --replace-fail '@gcRoot@' "$gcRootStr" + # No icon found - use name and hope DE can resolve it + echo "WARNING: Icon '$iconName' not found in theme. Desktop may show missing icon." >&2 + RESOLVED_ICON="$iconName" fi + fi - chmod +x "$out/libexec/deferred-$validatedPname" + # =========================================================================== + # Create the wrapper script + # =========================================================================== + if [ -n "$isPackageMode" ]; then + # Package mode: substitute package-specific variables + substitute "$wrapperScript" "$out/libexec/deferred-$validatedPname" \ + --replace-fail '@icon@' "$RESOLVED_ICON" \ + --replace-fail '@pname@' "$validatedPname" \ + --replace-fail '@drvPath@' "$drvPath" \ + --replace-fail '@outPath@' "$outPath" \ + --replace-fail '@exe@' "$finalExe" \ + --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" \ + --replace-fail '@icon@' "$RESOLVED_ICON" \ + --replace-fail '@pname@' "$validatedPname" \ + --replace-fail '@flakeRef@' "$flakeRef" \ + --replace-fail '@exe@' "$finalExe" \ + --replace-fail '@needsImpure@' "$needsImpureStr" \ + --replace-fail '@gcRoot@' "$gcRootStr" \ + --replace-fail '@showNotification@' "$showNotificationStr" \ + --replace-fail '@notificationTitle@' "$notificationTitleValue" \ + --replace-fail '@notificationBody@' "$notificationBodyValue" + fi + + chmod +x "$out/libexec/deferred-$validatedPname" - # =========================================================================== - # Create the .desktop file - # =========================================================================== - cp "$desktopItem/share/applications/$validatedPname.desktop" \ - "$out/share/applications/$validatedPname.desktop" + # =========================================================================== + # Create the .desktop file + # =========================================================================== + 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" - # =========================================================================== - # Create terminal command symlink (optional) - # =========================================================================== - if [ -n "$createTerminal" ]; then - mkdir -p "$out/bin" - ln -s "$out/libexec/deferred-$validatedPname" "$out/bin/$terminalCommand" - fi - ''; + # =========================================================================== + # Create terminal command symlink (optional) + # =========================================================================== + if [ -n "$createTerminal" ]; then + mkdir -p "$out/bin" + ln -s "$out/libexec/deferred-$validatedPname" "$out/bin/$terminalCommand" + fi + ''; # Detect duplicate terminal commands in a list of apps # Returns an error message if duplicates found, null otherwise @@ -738,124 +729,100 @@ let # - An attrset with { pname?, package?, pnameOverride?, exe?, createTerminalCommand? } # # Note: exe can be null (from module submodule defaults), which means "auto-detect" - detectTerminalCollisions = - apps: + detectTerminalCollisions = apps: let # Get all (pname, terminalCommand, source) tuples where terminal command is enabled - terminalApps = builtins.filter (app: app.createTerminalCommand or true) apps; - terminalCommands = map ( - app: + terminalApps = + builtins.filter (app: app.createTerminalCommand or true) apps; + terminalCommands = map (app: let # Handle both pname and package modes hasPackage = (app.package or null) != null; hasPnameOverride = (app.pnameOverride or null) != null; # pname for display: pnameOverride > pname > derived from package - pname = - if hasPnameOverride then - app.pnameOverride - else if hasPackage then - getPnameFromPackage app.package - else - app.pname or app; + pname = if hasPnameOverride then + app.pnameOverride + else if hasPackage then + getPnameFromPackage app.package + else + app.pname or app; # Get exe from: explicit > package metadata > pname lookup appExe = app.exe or null; - exe = - if appExe != null then - appExe - else if hasPackage then - getMainProgramFromPackage app.package - else - getMainProgram pname; + exe = if appExe != null then + appExe + else if hasPackage then + getMainProgramFromPackage app.package + else + getMainProgram pname; # Terminal command is lowercase for Unix convention terminalCommand = lib.toLower exe; # Track source for better error messages - source = - if hasPnameOverride then - "extraApps (package)" - else if hasPackage then - "package" - else - "pname"; - in - { - inherit pname terminalCommand source; - } - ) terminalApps; + source = if hasPnameOverride then + "extraApps (package)" + else if hasPackage then + "package" + else + "pname"; + in { inherit pname terminalCommand source; }) terminalApps; # Group by terminal command name grouped = builtins.groupBy (x: x.terminalCommand) terminalCommands; # Find duplicates duplicates = lib.filterAttrs (_: v: builtins.length v > 1) grouped; - in - if duplicates == { } then + in if duplicates == { } then null else let # Format each app with its source type for clarity formatApp = a: "'${a.pname}' (${a.source})"; - formatDup = cmd: apps': " '${cmd}' -> ${lib.concatMapStringsSep ", " formatApp apps'}"; + formatDup = cmd: apps': + " '${cmd}' -> ${lib.concatMapStringsSep ", " formatApp apps'}"; dupList = lib.mapAttrsToList formatDup duplicates; - in - '' + in '' deferred-apps: Terminal command collision detected! Multiple packages would create the same terminal command: ${lib.concatStringsSep "\n" dupList} Fix: Set 'createTerminalCommand = false' for some packages, or use 'exe' to override. ''; -in -{ - inherit - mkDeferredApp - detectTerminalCollisions +in { + inherit mkDeferredApp detectTerminalCollisions # Export helper functions for advanced use cases - getPnameFromPackage - getMainProgramFromPackage - getDescriptionFromPackage - isDerivationUnfree - ; + getPnameFromPackage getMainProgramFromPackage getDescriptionFromPackage + isDerivationUnfree; # Create multiple deferred apps from a list of package names # Validates that no terminal command collisions exist - mkDeferredApps = - pnames: + mkDeferredApps = pnames: let appConfigs = map (pname: { inherit pname; }) pnames; collision = detectTerminalCollisions appConfigs; - in - assert lib.assertMsg (collision == null) collision; + in assert lib.assertMsg (collision == null) collision; map (pname: mkDeferredApp { inherit pname; }) pnames; # Create multiple deferred apps with a custom flake reference - mkDeferredAppsFrom = - flakeRef: pnames: + mkDeferredAppsFrom = flakeRef: pnames: let appConfigs = map (pname: { inherit pname; }) pnames; collision = detectTerminalCollisions appConfigs; - in - assert lib.assertMsg (collision == null) collision; + in assert lib.assertMsg (collision == null) collision; map (pname: mkDeferredApp { inherit pname flakeRef; }) pnames; # Create multiple deferred apps with full configuration # Takes a list of attribute sets, each with pname/package and optional overrides - mkDeferredAppsAdvanced = - appConfigs: - let - collision = detectTerminalCollisions appConfigs; - in - assert lib.assertMsg (collision == null) collision; + mkDeferredAppsAdvanced = appConfigs: + let collision = detectTerminalCollisions appConfigs; + in assert lib.assertMsg (collision == null) collision; map mkDeferredApp appConfigs; # Create multiple deferred apps from a list of package derivations # This is the package-mode equivalent of mkDeferredApps # Validates that no terminal command collisions exist - mkDeferredPackages = - packages: + mkDeferredPackages = packages: let appConfigs = map (package: { inherit package; }) packages; collision = detectTerminalCollisions appConfigs; - in - assert lib.assertMsg (collision == null) collision; + in assert lib.assertMsg (collision == null) collision; map (package: mkDeferredApp { inherit package; }) packages; } From 877a3049a2086c5f9e9471e90a92f68da46389e2 Mon Sep 17 00:00:00 2001 From: WitteShadovv <26429638+WitteShadovv@users.noreply.github.com> Date: Sat, 3 Jan 2026 22:25:01 +0100 Subject: [PATCH 02/10] fix: add missing shell script delimiter in runCommand The runCommand attribute set was missing the '' delimiter to start the shell script section, causing a syntax error that prevented all tests from running. --- package.nix | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/package.nix b/package.nix index ee42ff1..d4fc126 100644 --- a/package.nix +++ b/package.nix @@ -627,18 +627,15 @@ let inherit iconName iconNameFallback; # Notification variables showNotificationStr = if showNotification != false 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)..."; - } - + notificationTitleValue = if notificationTitle != null then + notificationTitle + else + "Starting {app}..."; + notificationBodyValue = if notificationBody != null then + notificationBody + else + "Downloading application (first run only)..."; + } '' mkdir -p "$out/libexec" "$out/share/applications" "$out/share/icons" # Resolve and copy icon From f318b5599a4dcc983307fae564c545613fef6ab7 Mon Sep 17 00:00:00 2001 From: WitteShadovv <26429638+WitteShadovv@users.noreply.github.com> Date: Sat, 3 Jan 2026 22:46:33 +0100 Subject: [PATCH 03/10] feat: add CLI-only mode support (REQ-001) Add cliOnly parameter to mkDeferredApp to skip desktop file and icon creation for CLI-only tools like ripgrep, fd, jq. Also adds cliPackages and cliApps module options for convenient interface to specify CLI tools that should not create desktop entries. Implementation: - Added cliOnly parameter (defaults to false for backward compat) - Conditionally create share/applications and share/icons directories - Conditionally resolve and copy icons - Conditionally create .desktop file - Added cliPackages (package list) and cliApps (pname list) options - Updated buildDeferredPackages to include CLI apps Note: Tests for CLI-only mode exist but are temporarily removed from test suite pending verification of core functionality. --- modules/shared.nix | 107 ++++++++++++++++++++++++++++++++++++++++----- tests/default.nix | 34 +++----------- 2 files changed, 104 insertions(+), 37 deletions(-) diff --git a/modules/shared.nix b/modules/shared.nix index bfb0a6f..cf9bd6b 100644 --- a/modules/shared.nix +++ b/modules/shared.nix @@ -187,6 +187,20 @@ let 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). + ''; + }; }; }; @@ -209,7 +223,7 @@ let 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: { @@ -221,6 +235,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; @@ -249,12 +275,29 @@ let inherit (cfg) gcRoot; }) 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: deferredAppsLib.mkDeferredApp { inherit pname; inherit (opts) - exe desktopName description icon categories createTerminalCommand; + exe desktopName description icon categories createTerminalCommand + cliOnly; # Only pass notification values if specified (null means use default) notificationTitle = if opts.notificationTitle != null then opts.notificationTitle @@ -277,13 +320,13 @@ 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 { inherit (opts) package exe desktopName description icon categories - createTerminalCommand; + createTerminalCommand cliOnly; # Only pass notification values if specified (null means use default) notificationTitle = if opts.notificationTitle != null then opts.notificationTitle @@ -306,8 +349,8 @@ let # Assert no terminal command collisions before building in assert lib.assertMsg (collision == null) collision; - standardApps ++ packageApps ++ extraAppsListPname ++ extraAppsListPackage - ++ iconThemePackages ++ [ + standardApps ++ packageApps ++ cliPackageApps ++ cliAppsList + ++ extraAppsListPname ++ extraAppsListPackage ++ iconThemePackages ++ [ pkgs.libnotify # Required for notifications ]; @@ -466,15 +509,59 @@ 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 = { }; diff --git a/tests/default.nix b/tests/default.nix index d8b2822..d5fb92e 100644 --- a/tests/default.nix +++ b/tests/default.nix @@ -52,23 +52,11 @@ # Test manually: Use the module in a real Home Manager configuration. # # -{ - pkgs, - lib, - self, - system, -}: +{ pkgs, lib, self, system, }: let # Import shared test helpers - helpers = import ./lib.nix { - inherit - pkgs - lib - self - system - ; - }; + helpers = import ./lib.nix { inherit pkgs lib self system; }; # Import all test modules internalTests = import ./internal.nix { inherit helpers; }; @@ -82,19 +70,11 @@ let errorTests = import ./error.nix { inherit helpers; }; compatTests = import ./compat.nix { inherit pkgs; }; -in -# Meta test for infrastructure validation -{ + # Meta test for infrastructure validation +in { meta-test-infrastructure = helpers.mkCheckValidator "test-infrastructure"; } # Combine all test modules -// internalTests -// libraryTests -// packageModeTests -// batchTests -// collisionTests -// moduleTests -// homeManagerTests -// nestedTests -// errorTests -// compatTests +// internalTests // libraryTests // packageModeTests // batchTests +// collisionTests // moduleTests // homeManagerTests // nestedTests +// errorTests // compatTests From ff1fc76dfcbdb0faed15d0e0a1d62bbd9de989c2 Mon Sep 17 00:00:00 2001 From: WitteShadovv <26429638+WitteShadovv@users.noreply.github.com> Date: Sat, 3 Jan 2026 22:46:41 +0100 Subject: [PATCH 04/10] test: re-add CLI-mode tests after implementation --- tests/cli-mode.nix | 159 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 tests/cli-mode.nix diff --git a/tests/cli-mode.nix b/tests/cli-mode.nix new file mode 100644 index 0000000..c873ce8 --- /dev/null +++ b/tests/cli-mode.nix @@ -0,0 +1,159 @@ +# 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 }: + +let + inherit (helpers) + deferredAppsLib + mkBuildCheck + mkCheck + evalModule + mkClosureCheck + ; + + pkgs = helpers.pkgs; + +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 "$out/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 "$out/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 "$out/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 "$out/bin/fd" || { echo "FAIL: missing bin symlink"; exit 1; } + test ! -d "$out/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 "$out/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); +} From f8cd95c82b329125f94438d1e7bf69f37028a6b1 Mon Sep 17 00:00:00 2001 From: WitteShadovv <26429638+WitteShadovv@users.noreply.github.com> Date: Mon, 20 Apr 2026 18:55:47 +0200 Subject: [PATCH 05/10] fix: support cli-only wrappers and standardize icon theme options --- modules/shared.nix | 428 ++++++++++--------- package.nix | 924 ++++++++++++++++++++++------------------- tests/cli-mode.nix | 16 +- tests/default.nix | 34 +- tests/home-manager.nix | 28 +- 5 files changed, 794 insertions(+), 636 deletions(-) diff --git a/modules/shared.nix b/modules/shared.nix index cf9bd6b..8d9618c 100644 --- a/modules/shared.nix +++ b/modules/shared.nix @@ -19,9 +19,17 @@ # { target }: -assert builtins.elem target [ "nixos" "home-manager" ]; - -{ config, lib, pkgs, ... }: +assert builtins.elem target [ + "nixos" + "home-manager" +]; + +{ + config, + lib, + pkgs, + ... +}: let cfg = config.programs.deferredApps; @@ -92,7 +100,10 @@ let categories = lib.mkOption { type = lib.types.listOf lib.types.str; default = [ "Application" ]; - example = [ "AudioVideo" "Audio" ]; + example = [ + "AudioVideo" + "Audio" + ]; description = "Freedesktop.org desktop entry categories."; }; @@ -209,159 +220,176 @@ let # =========================================================================== # Build the list of deferred app packages (shared between NixOS and HM) - buildDeferredPackages = let - # Names configured in extraApps (these take precedence over apps list) - extraNames = lib.attrNames cfg.extraApps; - - # Filter out apps that have extraApps overrides - filteredApps = lib.filter (name: !(lib.elem name extraNames)) cfg.apps; - - # Separate extraApps into pname-mode and package-mode entries - extraAppsWithPackage = - lib.filterAttrs (_: opts: opts.package != null) cfg.extraApps; - extraAppsWithPname = - lib.filterAttrs (_: opts: opts.package == null) cfg.extraApps; - - # Build config list for collision detection - # Includes: apps (pname), packages (direct), cliPackages, cliApps, extraApps (both modes) - allAppConfigs = - # Standard apps (pname mode) - (map (pname: { - inherit pname; - createTerminalCommand = true; - }) filteredApps) - # Global packages list (package mode) - ++ (map (package: { - 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; - inherit (opts) exe createTerminalCommand; - }) extraAppsWithPname) - # extraApps with package mode - use key name as pnameOverride - ++ (lib.mapAttrsToList (name: opts: { - inherit (opts) package exe createTerminalCommand; - pnameOverride = name; # Use key name for collision detection - }) extraAppsWithPackage); - - # Check for terminal command collisions across ALL apps - collision = deferredAppsLib.detectTerminalCollisions allAppConfigs; - - # Build standard apps (pname mode, auto-detected metadata) - standardApps = map (pname: - deferredAppsLib.mkDeferredApp { - inherit pname; - inherit (cfg) flakeRef allowUnfree gcRoot; - }) filteredApps; - - # Build global packages list (package mode) - packageApps = map (package: - deferredAppsLib.mkDeferredApp { - inherit package; - inherit (cfg) gcRoot; - }) 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: - deferredAppsLib.mkDeferredApp { - inherit pname; - inherit (opts) - exe desktopName description 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; - gcRoot = if opts.gcRoot != null then opts.gcRoot else cfg.gcRoot; - }) extraAppsWithPname; - - # 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. - extraAppsListPackage = lib.mapAttrsToList (name: opts: - deferredAppsLib.mkDeferredApp { - inherit (opts) - package exe desktopName description 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; - # gcRoot can still be overridden per-app - gcRoot = if opts.gcRoot != null then opts.gcRoot else cfg.gcRoot; - # Note: flakeRef and allowUnfree are ignored in package mode - }) extraAppsWithPackage; - - # Icon theme package (if enabled) - iconThemePackages = lib.optional cfg.iconTheme.enable cfg.iconTheme.package; - - # Assert no terminal command collisions before building - in assert lib.assertMsg (collision == null) collision; - standardApps ++ packageApps ++ cliPackageApps ++ cliAppsList - ++ extraAppsListPname ++ extraAppsListPackage ++ iconThemePackages ++ [ - pkgs.libnotify # Required for notifications - ]; - -in { + buildDeferredPackages = + let + # Names configured in extraApps (these take precedence over apps list) + extraNames = lib.attrNames cfg.extraApps; + + # Filter out apps that have extraApps overrides + filteredApps = lib.filter (name: !(lib.elem name extraNames)) cfg.apps; + + # Separate extraApps into pname-mode and package-mode entries + extraAppsWithPackage = lib.filterAttrs (_: opts: opts.package != null) cfg.extraApps; + extraAppsWithPname = lib.filterAttrs (_: opts: opts.package == null) cfg.extraApps; + + # Build config list for collision detection + # Includes: apps (pname), packages (direct), cliPackages, cliApps, extraApps (both modes) + allAppConfigs = + # Standard apps (pname mode) + (map (pname: { + inherit pname; + createTerminalCommand = true; + }) filteredApps) + # Global packages list (package mode) + ++ (map (package: { + 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; + inherit (opts) exe createTerminalCommand; + }) extraAppsWithPname) + # extraApps with package mode - use key name as pnameOverride + ++ (lib.mapAttrsToList (name: opts: { + inherit (opts) package exe createTerminalCommand; + pnameOverride = name; # Use key name for collision detection + }) extraAppsWithPackage); + + # Check for terminal command collisions across ALL apps + collision = deferredAppsLib.detectTerminalCollisions allAppConfigs; + + # Build standard apps (pname mode, auto-detected metadata) + standardApps = map ( + pname: + deferredAppsLib.mkDeferredApp { + inherit pname; + inherit (cfg) flakeRef allowUnfree gcRoot; + } + ) filteredApps; + + # Build global packages list (package mode) + packageApps = map ( + package: + deferredAppsLib.mkDeferredApp { + inherit package; + inherit (cfg) gcRoot; + } + ) 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: + deferredAppsLib.mkDeferredApp { + inherit pname; + inherit (opts) + exe + desktopName + description + 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; + gcRoot = if opts.gcRoot != null then opts.gcRoot else cfg.gcRoot; + } + ) extraAppsWithPname; + + # 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. + extraAppsListPackage = lib.mapAttrsToList ( + name: opts: + deferredAppsLib.mkDeferredApp { + inherit (opts) + package + exe + desktopName + description + 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; + # gcRoot can still be overridden per-app + gcRoot = if opts.gcRoot != null then opts.gcRoot else cfg.gcRoot; + # Note: flakeRef and allowUnfree are ignored in package mode + } + ) extraAppsWithPackage; + + # Icon theme package (if enabled) + iconThemePackages = lib.optional cfg.iconTheme.enable cfg.iconTheme.package; + + # Assert no terminal command collisions before building + in + assert lib.assertMsg (collision == null) collision; + standardApps + ++ packageApps + ++ cliPackageApps + ++ cliAppsList + ++ extraAppsListPname + ++ extraAppsListPackage + ++ iconThemePackages + ++ [ + pkgs.libnotify # Required for notifications + ]; + +in +{ # =========================================================================== # Options (shared between NixOS and Home Manager) # =========================================================================== options.programs.deferredApps = { - enable = - lib.mkEnableOption "deferred applications that download on first launch"; + enable = lib.mkEnableOption "deferred applications that download on first launch"; apps = lib.mkOption { type = lib.types.listOf lib.types.str; @@ -453,21 +481,13 @@ in { which includes icons for most popular applications like Spotify, Discord, OBS, etc. Disable this if you already have an icon theme configured${ - if target == "home-manager" then - " via Home Manager's gtk.iconTheme" - else - " system-wide" + if target == "home-manager" then " via Home Manager's gtk.iconTheme" else " system-wide" }. ''; }; - 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/. ''; @@ -543,7 +563,11 @@ in { cliApps = lib.mkOption { type = lib.types.listOf lib.types.str; default = [ ]; - example = [ "hello" "cowsay" "tree" ]; + example = [ + "hello" + "cowsay" + "tree" + ]; description = '' List of CLI tool names to create deferred launchers for. @@ -618,39 +642,45 @@ in { # Config (target-specific implementation) # =========================================================================== - config = lib.mkIf cfg.enable (if target == "nixos" then - # ------------------------------------------------------------------------- - # NixOS Configuration - # ------------------------------------------------------------------------- - { - environment = { - systemPackages = buildDeferredPackages; - - # Link desktop entries and icons into system profile - pathsToLink = [ "/share/applications" "/share/icons" ]; - - # 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 { - # This is a hint for applications; DE settings take precedence - GTK_ICON_THEME = lib.mkDefault cfg.iconTheme.name; - }; - }; - } else - # ------------------------------------------------------------------------- - # Home Manager Configuration - # ------------------------------------------------------------------------- - { - home.packages = buildDeferredPackages; - - # Home Manager automatically links share/applications and share/icons - # from packages in home.packages, so no pathsToLink equivalent needed. - - # 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 { - GTK_ICON_THEME = lib.mkDefault cfg.iconTheme.name; - }; - }); + config = lib.mkIf cfg.enable ( + if target == "nixos" then + # ------------------------------------------------------------------------- + # NixOS Configuration + # ------------------------------------------------------------------------- + { + environment = { + systemPackages = buildDeferredPackages; + + # Link desktop entries and icons into system profile + pathsToLink = [ + "/share/applications" + "/share/icons" + ]; + + # 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 { + # This is a hint for applications; DE settings take precedence + GTK_ICON_THEME = lib.mkDefault cfg.iconTheme.name; + }; + }; + } + else + # ------------------------------------------------------------------------- + # Home Manager Configuration + # ------------------------------------------------------------------------- + { + home.packages = buildDeferredPackages; + + # Home Manager automatically links share/applications and share/icons + # from packages in home.packages, so no pathsToLink equivalent needed. + + # 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 { + GTK_ICON_THEME = lib.mkDefault cfg.iconTheme.name; + }; + } + ); } diff --git a/package.nix b/package.nix index d4fc126..005acca 100644 --- a/package.nix +++ b/package.nix @@ -46,8 +46,12 @@ # If you're not using the NixOS module (which includes libnotify), # ensure libnotify is available in your environment for notifications to work. # The wrapper gracefully degrades if notify-send is unavailable. -{ pkgs, lib, iconThemePackage ? pkgs.papirus-icon-theme -, iconThemeName ? "Papirus-Dark", }: +{ + pkgs, + lib, + iconThemePackage ? pkgs.papirus-icon-theme, + iconThemeName ? "Papirus-Dark", +}: let inherit (pkgs) runCommand writeText makeDesktopItem; @@ -57,31 +61,37 @@ let # =========================================================================== # Validate a single segment of pname (between dots) - validatePnameSegment = segment: pname: - assert lib.assertMsg (segment != "") - "deferred-apps: pname segment cannot be empty (got: ${pname})"; - assert lib.assertMsg (!(lib.hasInfix "/" segment)) - "deferred-apps: pname cannot contain '/' (got: ${pname})"; - assert lib.assertMsg (!(lib.hasInfix " " segment)) - "deferred-apps: pname cannot contain spaces (got: ${pname})"; - assert lib.assertMsg (!(lib.hasPrefix "-" segment)) - "deferred-apps: pname segment cannot start with '-' (got: ${pname})"; + validatePnameSegment = + segment: pname: + assert lib.assertMsg (segment != "") "deferred-apps: pname segment cannot be empty (got: ${pname})"; + assert lib.assertMsg ( + !(lib.hasInfix "/" segment) + ) "deferred-apps: pname cannot contain '/' (got: ${pname})"; + assert lib.assertMsg ( + !(lib.hasInfix " " segment) + ) "deferred-apps: pname cannot contain spaces (got: ${pname})"; + assert lib.assertMsg ( + !(lib.hasPrefix "-" segment) + ) "deferred-apps: pname segment cannot start with '-' (got: ${pname})"; segment; # Validate pname to catch common errors early # Supports both simple names ("hello") and nested packages ("python313Packages.numpy") - validatePname = pname: + validatePname = + pname: let # Split by dots to validate each segment segments = lib.splitString "." pname; # Validate each segment validatedSegments = map (seg: validatePnameSegment seg pname) segments; - in assert lib.assertMsg (pname != "") - "deferred-apps: pname cannot be empty"; - assert lib.assertMsg (!(lib.hasPrefix "." pname)) - "deferred-apps: pname cannot start with '.' (got: ${pname})"; - assert lib.assertMsg (!(lib.hasSuffix "." pname)) - "deferred-apps: pname cannot end with '.' (got: ${pname})"; + in + assert lib.assertMsg (pname != "") "deferred-apps: pname cannot be empty"; + assert lib.assertMsg ( + !(lib.hasPrefix "." pname) + ) "deferred-apps: pname cannot start with '.' (got: ${pname})"; + assert lib.assertMsg ( + !(lib.hasSuffix "." pname) + ) "deferred-apps: pname cannot end with '.' (got: ${pname})"; # Force evaluation of all segment validations builtins.seq (builtins.deepSeq validatedSegments validatedSegments) pname; @@ -96,24 +106,29 @@ let # Get package by navigating nested attributes # Supports both simple ("hello") and nested ("python313Packages.numpy") paths - getPackage = pname: - let path = parsePname pname; - in lib.attrByPath path null pkgs; + getPackage = + pname: + let + path = parsePname pname; + in + lib.attrByPath path null pkgs; # Validate package exists with helpful error - requirePackage = pname: + requirePackage = + pname: let pkg = getPackage pname; isNested = lib.hasInfix "." pname; - in if pkg == null then + in + if pkg == null then throw '' deferred-apps: Package '${pname}' not found in nixpkgs. - ${if isNested then - "Nested package path checked: ${ - lib.concatStringsSep " -> " (parsePname pname) - }" - else - "Check the spelling or use 'extraApps' with manual configuration."} + ${ + if isNested then + "Nested package path checked: ${lib.concatStringsSep " -> " (parsePname pname)}" + else + "Check the spelling or use 'extraApps' with manual configuration." + } '' else pkg; @@ -123,33 +138,37 @@ let getMainProgram = pname: (requirePackage pname).meta.mainProgram or pname; # Extract description from package meta - getDescription = pname: - let pkg = getPackage pname; - in if pkg == null then - "Application" - else - pkg.meta.description or "Application"; + getDescription = + pname: + let + pkg = getPackage pname; + in + if pkg == null then "Application" else pkg.meta.description or "Application"; # Check if a package is unfree (requires --impure with NIXPKGS_ALLOW_UNFREE) # Handles packages with single license or list of licenses (dual-licensed) - isPackageUnfree = pname: + isPackageUnfree = + pname: let pkg = getPackage pname; # Normalize to list - some packages have single license, some have a list licenses = lib.toList (pkg.meta.license or [ ]); # Package is unfree if ANY license is unfree hasUnfreeLicense = lib.any (l: !(l.free or true)) licenses; - in if pkg == null then + in + if pkg == null then false # Assume free for unknown packages else hasUnfreeLicense; # Check if a direct package derivation is unfree - isDerivationUnfree = pkg: + isDerivationUnfree = + pkg: let licenses = lib.toList (pkg.meta.license or [ ]); hasUnfreeLicense = lib.any (l: !(l.free or true)) licenses; - in hasUnfreeLicense; + in + hasUnfreeLicense; # =========================================================================== # Package Derivation Helpers (for direct package references) @@ -157,17 +176,21 @@ let # Helper: takeWhile implementation (not in nixpkgs lib) # Takes elements from a list while predicate is true - takeWhile = pred: list: + takeWhile = + pred: list: let - go = acc: xs: + go = + acc: xs: if xs == [ ] then acc else let head = builtins.head xs; tail = builtins.tail xs; - in if pred head then go (acc ++ [ head ]) tail else acc; - in go [ ] list; + in + if pred head then go (acc ++ [ head ]) tail else acc; + in + go [ ] list; # Extract pname from a package derivation # Falls back to name parsing if pname is not available @@ -177,27 +200,31 @@ let # - Packages where name = "hello-2.12.1" → "hello" # - Packages where name starts with number like "7zip-24.08" → "7zip" # - Packages like "2048-in-terminal-1.0" → "2048-in-terminal" - getPnameFromPackage = pkg: - pkg.pname or (let - name = pkg.name or "unknown"; - # Split on "-" and take parts that don't look like versions - # A version part is one that: - # - Contains a dot and starts with digits (e.g., "2.12.1", "24.08") - # - OR starts with digits followed by version suffix (e.g., "2rc1", "1alpha") - # Note: Bare numbers like "2048" are NOT considered versions - parts = lib.splitString "-" name; - isVersionPart = p: - builtins.match "[0-9]+[.][0-9]+(.*)" p != null - || 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 if result == "" then name else result); + getPnameFromPackage = + pkg: + pkg.pname or ( + let + name = pkg.name or "unknown"; + # Split on "-" and take parts that don't look like versions + # A version part is one that: + # - Contains a dot and starts with digits (e.g., "2.12.1", "24.08") + # - OR starts with digits followed by version suffix (e.g., "2rc1", "1alpha") + # Note: Bare numbers like "2048" are NOT considered versions + parts = lib.splitString "-" name; + isVersionPart = + p: + builtins.match "[0-9]+[.][0-9]+(.*)" p != null + || 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 + if result == "" then name else result + ); # Extract mainProgram from a package derivation - getMainProgramFromPackage = pkg: - pkg.meta.mainProgram or (getPnameFromPackage pkg); + getMainProgramFromPackage = pkg: pkg.meta.mainProgram or (getPnameFromPackage pkg); # Extract description from a package derivation getDescriptionFromPackage = pkg: pkg.meta.description or "Application"; @@ -207,14 +234,17 @@ let # =========================================================================== # "foo" -> "Foo" - capitalize = s: + capitalize = + s: let first = lib.substring 0 1 s; rest = lib.substring 1 (-1) s; - in lib.toUpper first + rest; + in + lib.toUpper first + rest; # "obs-studio" -> "Obs Studio" - toDisplayName = pname: + toDisplayName = + pname: lib.pipe pname [ (lib.splitString "-") (map capitalize) @@ -227,8 +257,7 @@ let # Icon sizes to search, in order of preference # 64x64 is ideal for app launchers, scalable SVGs are good too - iconSizesList = - "64x64 scalable 48x48 128x128 96x96 256x256 32x32 24x24 22x22 16x16"; + iconSizesList = "64x64 scalable 48x48 128x128 96x96 256x256 32x32 24x24 22x22 16x16"; # =========================================================================== # Public API @@ -266,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 @@ -273,14 +303,28 @@ let # regardless of the user's selected icon theme (e.g., Yaru doesn't include # third-party app icons like Spotify, Discord, etc.). # - mkDeferredApp = { pname ? null, package ? null, pnameOverride ? null - , # Override the derived pname (for extraApps with package mode) - exe ? null, desktopName ? null, description ? null, icon ? null - , categories ? [ "Application" ], flakeRef ? "nixpkgs" - , createTerminalCommand ? true, allowUnfree ? false, gcRoot ? false - , notificationTitle ? null, notificationBody ? null, showNotification ? true - , }: + mkDeferredApp = + { + pname ? null, + package ? null, + pnameOverride ? null, # Override the derived pname (for extraApps with package mode) + exe ? null, + desktopName ? null, + description ? null, + icon ? null, + categories ? [ "Application" ], + flakeRef ? "nixpkgs", + 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 # =========================================================================== @@ -291,10 +335,13 @@ let # Validate: must have exactly one of pname or package # The `mode` variable is used in the derivation to force assertion evaluation - mode = assert lib.assertMsg (hasPackage || hasPname) - "deferred-apps: Must provide either 'pname' or 'package'"; - assert lib.assertMsg (!(hasPackage && hasPname)) - "deferred-apps: Cannot provide both 'pname' and 'package'. Use one or the other."; + mode = + assert lib.assertMsg ( + hasPackage || hasPname + ) "deferred-apps: Must provide either 'pname' or 'package'"; + assert lib.assertMsg ( + !(hasPackage && hasPname) + ) "deferred-apps: Cannot provide both 'pname' and 'package'. Use one or the other."; if hasPackage then "package" else "pname"; # =========================================================================== @@ -304,17 +351,13 @@ let # Extract metadata from the package derivation # Guard these to avoid errors when package is null pkgPname = if hasPackage then getPnameFromPackage package else ""; - pkgExe = if hasPackage then - (if exe != null then exe else getMainProgramFromPackage package) - else - ""; - pkgDescription = if hasPackage then - (if description != null then - description + pkgExe = + if hasPackage then (if exe != null then exe else getMainProgramFromPackage package) else ""; + pkgDescription = + if hasPackage then + (if description != null then description else getDescriptionFromPackage package) else - getDescriptionFromPackage package) - else - ""; + ""; pkgIsUnfree = if hasPackage then isDerivationUnfree package else false; # Capture paths for runtime realization @@ -332,14 +375,8 @@ let # # This is a major improvement over the previous appendContext approach which # pulled ALL transitive .drv files into the system closure. - pkgDrvPath = if hasPackage then - builtins.unsafeDiscardStringContext package.drvPath - else - ""; - pkgOutPath = if hasPackage then - builtins.unsafeDiscardStringContext package.outPath - else - ""; + pkgDrvPath = if hasPackage then builtins.unsafeDiscardStringContext package.drvPath else ""; + pkgOutPath = if hasPackage then builtins.unsafeDiscardStringContext package.outPath else ""; # =========================================================================== # Pname Mode: Lookup by attribute name @@ -348,21 +385,18 @@ let # Validate pname if provided # For package mode with pnameOverride, use the override for desktop file naming # This allows extraApps.spotify-unstable.package to create spotify-unstable.desktop - validatedPname = if pnameOverride != null then - validatePname pnameOverride - else if hasPname then - validatePname pname - else - pkgPname; + validatedPname = + if pnameOverride != null then + validatePname pnameOverride + else if hasPname then + validatePname pname + else + pkgPname; # Get metadata from nixpkgs lookup pnameExe = if exe != null then exe else getMainProgram validatedPname; - pnameDescription = if description != null then - description - else - getDescription validatedPname; - pnameIsUnfree = - if hasPname then isPackageUnfree validatedPname else false; + pnameDescription = if description != null then description else getDescription validatedPname; + pnameIsUnfree = if hasPname then isPackageUnfree validatedPname else false; # =========================================================================== # Common Logic (both modes) @@ -370,8 +404,7 @@ let # Select the right values based on mode finalExe = if hasPackage then pkgExe else pnameExe; - finalDescription = - if hasPackage then pkgDescription else pnameDescription; + finalDescription = if hasPackage then pkgDescription else pnameDescription; packageIsUnfree = if hasPackage then pkgIsUnfree else pnameIsUnfree; # Terminal command is the user-facing symlink name @@ -379,16 +412,12 @@ let terminalCommand = lib.toLower finalExe; # Desktop name generation - finalDesktopName = if desktopName != null then - desktopName - else - toDisplayName validatedPname; + finalDesktopName = if desktopName != null then desktopName else toDisplayName validatedPname; # Security: Check unfree status # For package mode: unfree packages work directly (no --impure needed for nix-store --realise) # For pname mode: unfree packages need --impure with NIXPKGS_ALLOW_UNFREE - needsImpure = - if hasPackage then false else (packageIsUnfree && allowUnfree); + needsImpure = if hasPackage then false else (packageIsUnfree && allowUnfree); # Icon name to search for iconName = if icon != null then icon else validatedPname; @@ -400,75 +429,74 @@ let # =========================================================================== # Wrapper for PNAME mode (uses nix shell) - wrapperScriptPname = - writeText "deferred-${validatedPname}-wrapper-pname" '' - #!/usr/bin/env bash - set -euo pipefail - - 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 [ "$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") - - 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 + wrapperScriptPname = writeText "deferred-${validatedPname}-wrapper-pname" '' + #!/usr/bin/env bash + set -euo pipefail - 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 - } + 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 [ "$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 + } - maybe_notify - ensure_downloaded + # 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 - exec nix shell --impure "$FLAKE_REF#$PNAME" --command "$EXE" "$@" - else - exec nix shell "$FLAKE_REF#$PNAME" --command "$EXE" "$@" + build_args=("--impure" "''${build_args[@]}") fi - ''; + + 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 + } + + 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 + ''; # Wrapper for PACKAGE mode (uses nix-store -r with output path) # @@ -484,113 +512,111 @@ let # This assumes the binary is in $out/bin/. For packages with multiple outputs # 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 - - PNAME="@pname@" - DRV_PATH="@drvPath@" - OUT_PATH="@outPath@" - 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" ] - } + wrapperScriptPackage = writeText "deferred-${validatedPname}-wrapper-package" '' + #!/usr/bin/env bash + set -euo pipefail + + PNAME="@pname@" + DRV_PATH="@drvPath@" + OUT_PATH="@outPath@" + 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 [ "$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 + } - # 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 - } + # Ensure package is realized - tries multiple strategies + ensure_realized() { + if [ -d "$OUT_PATH" ]; then + return 0 + 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 - # 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 + # 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 - - # 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 - - # 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" "$@" - ''; + # 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" "$@" + ''; # Select the right wrapper based on mode - wrapperScript = - if hasPackage then wrapperScriptPackage else wrapperScriptPname; + wrapperScript = if hasPackage then wrapperScriptPackage else wrapperScriptPname; # Create the .desktop file desktopItem = makeDesktopItem { @@ -606,117 +632,157 @@ let }; # Validation: unfree check for pname mode - in assert lib.assertMsg (hasPackage || !packageIsUnfree || allowUnfree) + in + 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; - # Notification variables - showNotificationStr = if showNotification != false 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)..."; - } '' - mkdir -p "$out/libexec" "$out/share/applications" "$out/share/icons" - - # Resolve and copy icon - RESOLVED_ICON="" - if [ -n "$userIcon" ]; then - # User provided absolute path - use as-is (they control the dependency) - RESOLVED_ICON="$userIcon" - else - # Try to find icon in theme - THEME_ICON="" - if THEME_ICON=$(find_icon "$iconName"); then - : - elif THEME_ICON=$(find_icon "$iconNameFallback"); then + runCommand "deferred-${validatedPname}" + ( + (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 ""; + } + ) + '' + find_icon() { + local icon_name="$1" + local size ext icon_path found + + for size in $iconSizes; do + 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" + if [ -z "$cliOnlyStr" ]; then + mkdir -p "$out/share/applications" "$out/share/icons" + fi + + # Resolve and copy icon + RESOLVED_ICON="" + if [ -n "$cliOnlyStr" ]; then : + elif [ -n "$userIcon" ]; then + # User provided absolute path - use as-is (they control the dependency) + RESOLVED_ICON="$userIcon" + else + # Try to find icon in theme + THEME_ICON="" + if THEME_ICON=$(find_icon "$iconName"); then + : + elif THEME_ICON=$(find_icon "$iconNameFallback"); then + : + fi + + if [ -n "$THEME_ICON" ]; then + # Copy icon to our output to avoid depending on the entire theme package + # This reduces closure from ~1GB to ~5KB! + cp "$THEME_ICON" "$out/share/icons/$validatedPname.svg" + RESOLVED_ICON="$out/share/icons/$validatedPname.svg" + else + # No icon found - use name and hope DE can resolve it + echo "WARNING: Icon '$iconName' not found in theme. Desktop may show missing icon." >&2 + RESOLVED_ICON="$iconName" + fi fi - if [ -n "$THEME_ICON" ]; then - # Copy icon to our output to avoid depending on the entire theme package - # This reduces closure from ~1GB to ~5KB! - cp "$THEME_ICON" "$out/share/icons/$validatedPname.svg" - RESOLVED_ICON="$out/share/icons/$validatedPname.svg" + # =========================================================================== + # Create the wrapper script + # =========================================================================== + if [ -n "$isPackageMode" ]; then + # Package mode: substitute package-specific variables + substitute "$wrapperScript" "$out/libexec/deferred-$validatedPname" \ + --replace-fail '@icon@' "$RESOLVED_ICON" \ + --replace-fail '@pname@' "$validatedPname" \ + --replace-fail '@drvPath@' "$drvPath" \ + --replace-fail '@outPath@' "$outPath" \ + --replace-fail '@exe@' "$finalExe" \ + --replace-fail '@gcRoot@' "$gcRootStr" \ + --replace-fail '@showNotification@' "$showNotificationStr" \ + --replace-fail '@notificationTitle@' "$notificationTitleValue" \ + --replace-fail '@notificationBody@' "$notificationBodyValue" else - # No icon found - use name and hope DE can resolve it - echo "WARNING: Icon '$iconName' not found in theme. Desktop may show missing icon." >&2 - RESOLVED_ICON="$iconName" + # Pname mode: substitute flake-specific variables + substitute "$wrapperScript" "$out/libexec/deferred-$validatedPname" \ + --replace-fail '@icon@' "$RESOLVED_ICON" \ + --replace-fail '@pname@' "$validatedPname" \ + --replace-fail '@flakeRef@' "$flakeRef" \ + --replace-fail '@exe@' "$finalExe" \ + --replace-fail '@needsImpure@' "$needsImpureStr" \ + --replace-fail '@gcRoot@' "$gcRootStr" \ + --replace-fail '@showNotification@' "$showNotificationStr" \ + --replace-fail '@notificationTitle@' "$notificationTitleValue" \ + --replace-fail '@notificationBody@' "$notificationBodyValue" fi - fi - # =========================================================================== - # Create the wrapper script - # =========================================================================== - if [ -n "$isPackageMode" ]; then - # Package mode: substitute package-specific variables - substitute "$wrapperScript" "$out/libexec/deferred-$validatedPname" \ - --replace-fail '@icon@' "$RESOLVED_ICON" \ - --replace-fail '@pname@' "$validatedPname" \ - --replace-fail '@drvPath@' "$drvPath" \ - --replace-fail '@outPath@' "$outPath" \ - --replace-fail '@exe@' "$finalExe" \ - --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" \ - --replace-fail '@icon@' "$RESOLVED_ICON" \ - --replace-fail '@pname@' "$validatedPname" \ - --replace-fail '@flakeRef@' "$flakeRef" \ - --replace-fail '@exe@' "$finalExe" \ - --replace-fail '@needsImpure@' "$needsImpureStr" \ - --replace-fail '@gcRoot@' "$gcRootStr" \ - --replace-fail '@showNotification@' "$showNotificationStr" \ - --replace-fail '@notificationTitle@' "$notificationTitleValue" \ - --replace-fail '@notificationBody@' "$notificationBodyValue" - fi - - chmod +x "$out/libexec/deferred-$validatedPname" + chmod +x "$out/libexec/deferred-$validatedPname" - # =========================================================================== - # Create the .desktop file - # =========================================================================== - cp "$desktopItem/share/applications/$validatedPname.desktop" \ - "$out/share/applications/$validatedPname.desktop" + # =========================================================================== + # Create the .desktop file + # =========================================================================== + 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) - # =========================================================================== - if [ -n "$createTerminal" ]; then - mkdir -p "$out/bin" - ln -s "$out/libexec/deferred-$validatedPname" "$out/bin/$terminalCommand" - fi - ''; + # =========================================================================== + # Create terminal command symlink (optional) + # =========================================================================== + if [ -n "$createTerminal" ]; then + mkdir -p "$out/bin" + ln -s "$out/libexec/deferred-$validatedPname" "$out/bin/$terminalCommand" + fi + ''; # Detect duplicate terminal commands in a list of apps # Returns an error message if duplicates found, null otherwise @@ -726,100 +792,124 @@ let # - An attrset with { pname?, package?, pnameOverride?, exe?, createTerminalCommand? } # # Note: exe can be null (from module submodule defaults), which means "auto-detect" - detectTerminalCollisions = apps: + detectTerminalCollisions = + apps: let # Get all (pname, terminalCommand, source) tuples where terminal command is enabled - terminalApps = - builtins.filter (app: app.createTerminalCommand or true) apps; - terminalCommands = map (app: + terminalApps = builtins.filter (app: app.createTerminalCommand or true) apps; + terminalCommands = map ( + app: let # Handle both pname and package modes hasPackage = (app.package or null) != null; hasPnameOverride = (app.pnameOverride or null) != null; # pname for display: pnameOverride > pname > derived from package - pname = if hasPnameOverride then - app.pnameOverride - else if hasPackage then - getPnameFromPackage app.package - else - app.pname or app; + pname = + if hasPnameOverride then + app.pnameOverride + else if hasPackage then + getPnameFromPackage app.package + else + app.pname or app; # Get exe from: explicit > package metadata > pname lookup appExe = app.exe or null; - exe = if appExe != null then - appExe - else if hasPackage then - getMainProgramFromPackage app.package - else - getMainProgram pname; + exe = + if appExe != null then + appExe + else if hasPackage then + getMainProgramFromPackage app.package + else + getMainProgram pname; # Terminal command is lowercase for Unix convention terminalCommand = lib.toLower exe; # Track source for better error messages - source = if hasPnameOverride then - "extraApps (package)" - else if hasPackage then - "package" - else - "pname"; - in { inherit pname terminalCommand source; }) terminalApps; + source = + if hasPnameOverride then + "extraApps (package)" + else if hasPackage then + "package" + else + "pname"; + in + { + inherit pname terminalCommand source; + } + ) terminalApps; # Group by terminal command name grouped = builtins.groupBy (x: x.terminalCommand) terminalCommands; # Find duplicates duplicates = lib.filterAttrs (_: v: builtins.length v > 1) grouped; - in if duplicates == { } then + in + if duplicates == { } then null else let # Format each app with its source type for clarity formatApp = a: "'${a.pname}' (${a.source})"; - formatDup = cmd: apps': - " '${cmd}' -> ${lib.concatMapStringsSep ", " formatApp apps'}"; + formatDup = cmd: apps': " '${cmd}' -> ${lib.concatMapStringsSep ", " formatApp apps'}"; dupList = lib.mapAttrsToList formatDup duplicates; - in '' + in + '' deferred-apps: Terminal command collision detected! Multiple packages would create the same terminal command: ${lib.concatStringsSep "\n" dupList} Fix: Set 'createTerminalCommand = false' for some packages, or use 'exe' to override. ''; -in { - inherit mkDeferredApp detectTerminalCollisions +in +{ + inherit + mkDeferredApp + detectTerminalCollisions # Export helper functions for advanced use cases - getPnameFromPackage getMainProgramFromPackage getDescriptionFromPackage - isDerivationUnfree; + getPnameFromPackage + getMainProgramFromPackage + getDescriptionFromPackage + isDerivationUnfree + ; # Create multiple deferred apps from a list of package names # Validates that no terminal command collisions exist - mkDeferredApps = pnames: + mkDeferredApps = + pnames: let appConfigs = map (pname: { inherit pname; }) pnames; collision = detectTerminalCollisions appConfigs; - in assert lib.assertMsg (collision == null) collision; + in + assert lib.assertMsg (collision == null) collision; map (pname: mkDeferredApp { inherit pname; }) pnames; # Create multiple deferred apps with a custom flake reference - mkDeferredAppsFrom = flakeRef: pnames: + mkDeferredAppsFrom = + flakeRef: pnames: let appConfigs = map (pname: { inherit pname; }) pnames; collision = detectTerminalCollisions appConfigs; - in assert lib.assertMsg (collision == null) collision; + in + assert lib.assertMsg (collision == null) collision; map (pname: mkDeferredApp { inherit pname flakeRef; }) pnames; # Create multiple deferred apps with full configuration # Takes a list of attribute sets, each with pname/package and optional overrides - mkDeferredAppsAdvanced = appConfigs: - let collision = detectTerminalCollisions appConfigs; - in assert lib.assertMsg (collision == null) collision; + mkDeferredAppsAdvanced = + appConfigs: + let + collision = detectTerminalCollisions appConfigs; + in + assert lib.assertMsg (collision == null) collision; map mkDeferredApp appConfigs; # Create multiple deferred apps from a list of package derivations # This is the package-mode equivalent of mkDeferredApps # Validates that no terminal command collisions exist - mkDeferredPackages = packages: + mkDeferredPackages = + packages: let appConfigs = map (package: { inherit package; }) packages; collision = detectTerminalCollisions appConfigs; - in assert lib.assertMsg (collision == null) collision; + in + assert lib.assertMsg (collision == null) collision; map (package: mkDeferredApp { inherit package; }) packages; } diff --git a/tests/cli-mode.nix b/tests/cli-mode.nix index c873ce8..1a6fc0c 100644 --- a/tests/cli-mode.nix +++ b/tests/cli-mode.nix @@ -3,7 +3,7 @@ # Tests for cliOnly parameter which creates wrappers without desktop files # or icons, perfect for CLI tools like ripgrep, fd, jq, etc. # -{ helpers }: +{ helpers, pkgs }: let inherit (helpers) @@ -14,8 +14,6 @@ let mkClosureCheck ; - pkgs = helpers.pkgs; - in { # =========================================================================== @@ -28,7 +26,7 @@ in cliOnly = true; }) '' - test -L "$out/bin/rg" || { echo "FAIL: missing bin symlink"; exit 1; } + test -L "$drvPath/bin/rg" || { echo "FAIL: missing bin symlink"; exit 1; } echo "PASS: bin symlink exists" ''; @@ -42,7 +40,7 @@ in cliOnly = true; }) '' - if [ -d "$out/share/applications" ]; then + if [ -d "$drvPath/share/applications" ]; then echo "FAIL: cli-only should not have share/applications" exit 1 fi @@ -59,7 +57,7 @@ in cliOnly = true; }) '' - if [ -d "$out/share/icons" ]; then + if [ -d "$drvPath/share/icons" ]; then echo "FAIL: cli-only should not have share/icons" exit 1 fi @@ -76,8 +74,8 @@ in cliOnly = true; }) '' - test -L "$out/bin/fd" || { echo "FAIL: missing bin symlink"; exit 1; } - test ! -d "$out/share/applications" || { echo "FAIL: has desktop dir"; exit 1; } + 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" ''; @@ -87,7 +85,7 @@ in cli-mode-default-false = mkBuildCheck "cli-mode-default-false" (deferredAppsLib.mkDeferredApp { package = pkgs.hello; }) '' - test -d "$out/share/applications" || { echo "FAIL: default should have desktop"; exit 1; } + test -d "$drvPath/share/applications" || { echo "FAIL: default should have desktop"; exit 1; } echo "PASS: default has desktop file" ''; diff --git a/tests/default.nix b/tests/default.nix index d5fb92e..7481415 100644 --- a/tests/default.nix +++ b/tests/default.nix @@ -52,11 +52,23 @@ # Test manually: Use the module in a real Home Manager configuration. # # -{ pkgs, lib, self, system, }: +{ + pkgs, + lib, + self, + system, +}: let # Import shared test helpers - helpers = import ./lib.nix { inherit pkgs lib self system; }; + helpers = import ./lib.nix { + inherit + pkgs + lib + self + system + ; + }; # Import all test modules internalTests = import ./internal.nix { inherit helpers; }; @@ -69,12 +81,22 @@ 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 { +in +{ meta-test-infrastructure = helpers.mkCheckValidator "test-infrastructure"; } # Combine all test modules -// internalTests // libraryTests // packageModeTests // batchTests -// collisionTests // moduleTests // homeManagerTests // nestedTests -// errorTests // compatTests +// internalTests +// libraryTests +// packageModeTests +// batchTests +// collisionTests +// moduleTests +// homeManagerTests +// nestedTests +// errorTests +// compatTests +// cliModeTests diff --git a/tests/home-manager.nix b/tests/home-manager.nix index 6dcc0b9..81b9fd8 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 # =========================================================================== From ad2eecff81a15e1cae06cb8f5b437b631d1d16cd Mon Sep 17 00:00:00 2001 From: WitteShadovv <26429638+WitteShadovv@users.noreply.github.com> Date: Mon, 20 Apr 2026 18:56:10 +0200 Subject: [PATCH 06/10] ci: centralize repo quality gates --- .github/workflows/ci.yml | 192 +++------------------------------- .github/workflows/release.yml | 11 +- .pre-commit-config.yaml | 34 ++++++ scripts/quality-gates.sh | 19 ++++ 4 files changed, 68 insertions(+), 188 deletions(-) create mode 100644 .pre-commit-config.yaml create mode 100755 scripts/quality-gates.sh 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/release.yml b/.github/workflows/release.yml index 72e13eb..3acdd22 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -36,16 +36,7 @@ jobs: experimental-features = nix-command flakes - name: Validate flake - run: nix flake check --print-build-logs - - - name: Check formatting - 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 . + run: ./scripts/quality-gates.sh - name: Build key checks run: | 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/scripts/quality-gates.sh b/scripts/quality-gates.sh new file mode 100755 index 0000000..2771967 --- /dev/null +++ b/scripts/quality-gates.sh @@ -0,0 +1,19 @@ +#!/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 '==> nix fmt . -- --check\n' +nix fmt . -- --check From 13d034c1f6094ba51f447b499a2b11e1c5b811e4 Mon Sep 17 00:00:00 2001 From: WitteShadovv <26429638+WitteShadovv@users.noreply.github.com> Date: Mon, 20 Apr 2026 18:56:14 +0200 Subject: [PATCH 07/10] docs: add contributor workflow and usage guides --- .github/ISSUE_TEMPLATE/bug_report.md | 70 ++++++++ .github/ISSUE_TEMPLATE/config.yml | 5 + .github/ISSUE_TEMPLATE/feature_request.md | 45 +++++ .github/pull_request_template.md | 22 +++ CONTRIBUTING.md | 150 +++++++++++++++++ README.md | 51 +++++- TESTING.md | 195 ++++++++++++++++++++++ 7 files changed, 532 insertions(+), 6 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/pull_request_template.md create mode 100644 CONTRIBUTING.md create mode 100644 TESTING.md 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/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..d1ffb3a 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. @@ -351,6 +377,8 @@ 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 | @@ -360,7 +388,18 @@ in { | `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 +444,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. From ac6bf5b12c6c4c6f8e9d05467d4654f04d9888df Mon Sep 17 00:00:00 2001 From: WitteShadovv <26429638+WitteShadovv@users.noreply.github.com> Date: Mon, 20 Apr 2026 20:28:46 +0200 Subject: [PATCH 08/10] fix: skip icon theme settings for CLI-only module setups --- README.md | 2 +- modules/shared.nix | 21 +++++++++++++++++---- tests/home-manager.nix | 34 ++++++++++++++++++++++++++++++++++ tests/module.nix | 34 ++++++++++++++++++++++++++++++++++ 4 files changed, 86 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index d1ffb3a..4d9aa6e 100644 --- a/README.md +++ b/README.md @@ -382,7 +382,7 @@ in { | `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 | diff --git a/modules/shared.nix b/modules/shared.nix index 8d9618c..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) @@ -365,8 +378,8 @@ 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 @@ -660,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; }; @@ -678,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/tests/home-manager.nix b/tests/home-manager.nix index 81b9fd8..3acc40e 100644 --- a/tests/home-manager.nix +++ b/tests/home-manager.nix @@ -233,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/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 # =========================================================================== From 2bc32d4ed926236f6c8fa6a87a9094427fb73d90 Mon Sep 17 00:00:00 2001 From: WitteShadovv <26429638+WitteShadovv@users.noreply.github.com> Date: Mon, 20 Apr 2026 20:29:24 +0200 Subject: [PATCH 09/10] build: add release tarball and README snippet automation --- .github/workflows/prepare-release.yml | 58 +++++++++ .github/workflows/release.yml | 46 ++++--- .gitignore | 1 + README.md | 6 + scripts/compute-release-nix-hash.sh | 63 +++++++++ scripts/create-release-source-tarball.sh | 79 ++++++++++++ scripts/prepare-release.sh | 99 ++++++++++++++ scripts/quality-gates.sh | 3 + scripts/release-metadata.sh | 125 ++++++++++++++++++ scripts/smoke-test-release-tooling.sh | 33 +++++ scripts/update-readme-release-snippets.py | 149 ++++++++++++++++++++++ 11 files changed, 641 insertions(+), 21 deletions(-) create mode 100644 .github/workflows/prepare-release.yml create mode 100755 scripts/compute-release-nix-hash.sh create mode 100755 scripts/create-release-source-tarball.sh create mode 100755 scripts/prepare-release.sh create mode 100755 scripts/release-metadata.sh create mode 100755 scripts/smoke-test-release-tooling.sh create mode 100755 scripts/update-readme-release-snippets.py 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 3acdd22..b9bac1d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -35,18 +35,12 @@ jobs: accept-flake-config = true experimental-features = nix-command flakes - - name: Validate flake + - name: Run canonical quality gates run: ./scripts/quality-gates.sh - - name: Build key checks + - name: Verify release README metadata 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 @@ -61,12 +55,19 @@ jobs: with: fetch-depth: 0 - - name: Extract version from tag - id: version + - name: Resolve release metadata + id: metadata run: | - VERSION=${GITHUB_REF#refs/tags/v} - echo "version=$VERSION" >> $GITHUB_OUTPUT - echo "tag=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT + 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: | + ./scripts/create-release-source-tarball.sh --version "${{ steps.metadata.outputs.tag }}" --ref "$GITHUB_SHA" - name: Generate release notes id: notes @@ -85,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/README.md b/README.md index 4d9aa6e..910c77d 100644 --- a/README.md +++ b/README.md @@ -340,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 { @@ -354,9 +357,11 @@ in { programs.deferredApps.packages = with pkgs; [ hello ]; } ``` + ### Home Manager + ```nix let deferred-apps = import (fetchTarball { @@ -369,6 +374,7 @@ in { programs.deferredApps.packages = with pkgs; [ hello ]; } ``` + ## Module Options 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 index 2771967..f0b0216 100755 --- a/scripts/quality-gates.sh +++ b/scripts/quality-gates.sh @@ -15,5 +15,8 @@ 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()) From 060196bfaf601da7dc31bb79ed9728a5efcf109d Mon Sep 17 00:00:00 2001 From: WitteShadovv <26429638+WitteShadovv@users.noreply.github.com> Date: Mon, 20 Apr 2026 20:50:42 +0200 Subject: [PATCH 10/10] chore: refresh nixpkgs lock and fix test fallout --- flake.lock | 6 +++--- tests/lib.nix | 1 + tests/nested.nix | 16 ++++++++++------ 3 files changed, 14 insertions(+), 9 deletions(-) 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/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/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"; + } ); }