1{ config, pkgs, lib, ... }:
2
3let
4 cfg = config.programs.ccache;
5in {
6 options.programs.ccache = {
7 # host configuration
8 enable = lib.mkEnableOption "CCache, a compiler cache for fast recompilation of C/C++ code";
9 cacheDir = lib.mkOption {
10 type = lib.types.path;
11 description = "CCache directory";
12 default = "/var/cache/ccache";
13 };
14 # target configuration
15 packageNames = lib.mkOption {
16 type = lib.types.listOf lib.types.str;
17 description = "Nix top-level packages to be compiled using CCache";
18 default = [];
19 example = [ "wxGTK32" "ffmpeg" "libav_all" ];
20 };
21 owner = lib.mkOption {
22 type = lib.types.str;
23 default = "root";
24 description = "Owner of CCache directory";
25 };
26 group = lib.mkOption {
27 type = lib.types.str;
28 default = "nixbld";
29 description = "Group owner of CCache directory";
30 };
31 };
32
33 config = lib.mkMerge [
34 # host configuration
35 (lib.mkIf cfg.enable {
36 systemd.tmpfiles.rules = [ "d ${cfg.cacheDir} 0770 ${cfg.owner} ${cfg.group} -" ];
37
38 # "nix-ccache --show-stats" and "nix-ccache --clear"
39 security.wrappers.nix-ccache = {
40 inherit (cfg) owner group;
41 setuid = false;
42 setgid = true;
43 source = pkgs.writeScript "nix-ccache.pl" ''
44 #!${pkgs.perl}/bin/perl
45
46 %ENV=( CCACHE_DIR => '${cfg.cacheDir}' );
47 sub untaint {
48 my $v = shift;
49 return '-C' if $v eq '-C' || $v eq '--clear';
50 return '-V' if $v eq '-V' || $v eq '--version';
51 return '-s' if $v eq '-s' || $v eq '--show-stats';
52 return '-z' if $v eq '-z' || $v eq '--zero-stats';
53 exec('${pkgs.ccache}/bin/ccache', '-h');
54 }
55 exec('${pkgs.ccache}/bin/ccache', map { untaint $_ } @ARGV);
56 '';
57 };
58 })
59
60 # target configuration
61 (lib.mkIf (cfg.packageNames != []) {
62 nixpkgs.overlays = [
63 (self: super: lib.genAttrs cfg.packageNames (pn: super.${pn}.override { stdenv = builtins.trace "with ccache: ${pn}" self.ccacheStdenv; }))
64
65 (self: super: {
66 ccacheWrapper = super.ccacheWrapper.override {
67 extraConfig = ''
68 export CCACHE_COMPRESS=1
69 export CCACHE_DIR="${cfg.cacheDir}"
70 export CCACHE_UMASK=007
71 if [ ! -d "$CCACHE_DIR" ]; then
72 echo "====="
73 echo "Directory '$CCACHE_DIR' does not exist"
74 echo "Please create it with:"
75 echo " sudo mkdir -m0770 '$CCACHE_DIR'"
76 echo " sudo chown ${cfg.owner}:${cfg.group} '$CCACHE_DIR'"
77 echo "====="
78 exit 1
79 fi
80 if [ ! -w "$CCACHE_DIR" ]; then
81 echo "====="
82 echo "Directory '$CCACHE_DIR' is not accessible for user $(whoami)"
83 echo "Please verify its access permissions"
84 echo "====="
85 exit 1
86 fi
87 '';
88 };
89 })
90 ];
91 })
92 ];
93}