-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnix-dev
More file actions
executable file
·223 lines (173 loc) · 5.66 KB
/
nix-dev
File metadata and controls
executable file
·223 lines (173 loc) · 5.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
#!/usr/bin/env python3
import argparse
import glob
import hashlib
import json
import os
import os.path
import subprocess
#
# General Helpers
#
def unlink_if_exists(path):
if os.path.lexists(path):
os.unlink(path)
def get_cache_directory():
xdg_cache_dir = os.getenv("XDG_CACHE_DIR")
if xdg_cache_dir:
return xdg_cache_dir
else:
home = os.getenv("HOME")
return f"{home}/.cache"
def get_my_cache_directory():
cache_directory = get_cache_directory()
return f"{cache_directory}/nix-dev"
#
# Config Related
#
def build_config(args):
return {
"attr": args.attr,
"shell_nix": os.path.abspath(args.shell_nix_file),
"shell_nix_hash": hash_of_file(args.shell_nix_file),
}
def hash_of_file(filename):
with open(filename, "rb", buffering=0) as f:
return hashlib.file_digest(f, "sha256").hexdigest()
def hash_of_config(config):
digest = hashlib.sha256()
digest.update(json.dumps(config, sort_keys=True).encode("utf8"))
return digest.hexdigest()
def dump_config(config, cfg_file):
with open(cfg_file, "wt") as f:
json.dump(config, f, indent=2, sort_keys=True)
f.write("\n")
#
# Development Environment Handling
#
def collect_garbage(cache_dir):
hashes = set()
for filename in glob.glob("*", root_dir=cache_dir):
path = os.path.join(cache_dir, filename)
is_garbage = (
len(filename) != 64 + 4
or filename[-4:] not in (".cfg", ".drv", ".out")
or not os.path.exists(path)
)
if is_garbage:
print(f"Removing broken {path}")
os.unlink(path)
else:
hashes.add(filename[:64])
for h in hashes:
cfg_file = os.path.join(cache_dir, f"{h}.cfg")
drv_link = os.path.join(cache_dir, f"{h}.drv")
out_link = os.path.join(cache_dir, f"{h}.out")
is_garbage = True
if os.path.exists(cfg_file):
with open(cfg_file, "rt") as f:
config = json.load(f)
if os.path.exists(config["shell_nix"]):
if hash_of_file(config["shell_nix"]) == config["shell_nix_hash"]:
is_garbage = False
if is_garbage:
for path in (cfg_file, drv_link, out_link):
print(f"Removing stale {path}")
unlink_if_exists(path)
def nix_instantiate(args, drv_link):
cmd = ["nix-instantiate"]
if args.attr:
cmd.extend(["--attr", args.attr])
cmd.extend(["--add-root", drv_link])
cmd.append(args.shell_nix_file)
print("nix-dev: Calling nix-instantiate...")
subprocess.check_call(cmd)
def nix_build(args, drv_link, out_link):
cmd = ["nix-build", "--out-link", out_link, drv_link]
print("nix-dev: Calling nix-build...")
subprocess.check_call(cmd)
def nix_shell(args, drv_link):
cmd = ["nix-shell"]
if args.command:
cmd.extend(["--command", args.command])
if args.keep:
cmd.extend(["--keep", args.keep])
if args.pure:
cmd.extend(["--pure"])
if args.run:
cmd.extend(["--run", args.run])
cmd.append(drv_link)
print("nix-dev: Calling nix-shell...")
os.execvp(cmd[0], cmd)
#
# Main Entry
#
def parse_args():
parser = argparse.ArgumentParser()
# nix-dev options
group = parser.add_argument_group("nix-dev")
group.add_argument(
"--break-cache",
action="store_true",
help="Ignore existing cache entry and force instantiation of environment.",
)
group.add_argument(
"--collect-garbage",
action="store_true",
help="Removes stale environments.",
)
group.add_argument(
"shell_nix_file",
nargs="?",
default="shell.nix",
help="If file is not given, defaults to shell.nix.",
)
# nix-instantiate options
group = parser.add_argument_group("nix-instantiate")
group.add_argument(
"--attr",
"-A",
help="Select an attribute from the top-level Nix expression being evaluated.",
)
# nix-shell options
group = parser.add_argument_group("nix-shell")
group.add_argument(
"--command",
help="In the environment of the derivation, run the shell command COMMAND.",
)
group.add_argument(
"--keep",
help="When a --pure shell is started, keep the listed environment variables.",
)
group.add_argument(
"--pure",
action="store_true",
help="If this flag is specified, the environment is almost entirely cleared before the interactive shell is started, so you get an environment that more closely corresponds to the “real” Nix build.",
)
group.add_argument(
"--run",
help="Like --command, but executes the command in a non-interactive shell.",
)
return parser.parse_args()
def main():
args = parse_args()
cache_dir = get_my_cache_directory()
if args.collect_garbage:
collect_garbage(cache_dir=cache_dir)
return
config = build_config(args=args)
filename = hash_of_config(config=config)
cfg_file = f"{cache_dir}/{filename}.cfg"
drv_link = f"{cache_dir}/{filename}.drv"
out_link = f"{cache_dir}/{filename}.out"
state_exists = all(os.path.exists(p) for p in (cfg_file, drv_link, out_link))
if not state_exists or args.break_cache:
os.makedirs(cache_dir, exist_ok=True)
unlink_if_exists(drv_link)
unlink_if_exists(out_link)
dump_config(config=config, cfg_file=cfg_file)
nix_instantiate(args=args, drv_link=drv_link)
nix_build(args=args, drv_link=drv_link, out_link=out_link)
nix_shell(args=args, drv_link=drv_link)
if __name__ == "__main__":
main()