-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsyd.py
More file actions
executable file
·346 lines (277 loc) · 10.3 KB
/
syd.py
File metadata and controls
executable file
·346 lines (277 loc) · 10.3 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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
#!/usr/bin/env python3
# syd
# Copyright (c) 2025 Sidharth Sharma.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import os
import re
import sys
import subprocess
from pathlib import Path
from colorama import Fore, Style, init
init(autoreset=True)
# ------------------------------------------------------------
# COLORS AND CONSTANTS
# ------------------------------------------------------------
INFO = f"{Fore.BLUE}syd:{Style.RESET_ALL}"
SUCCESS = f"{Fore.GREEN}SUCCESS:{Style.RESET_ALL}"
ERROR = f"{Fore.RED}ERROR:{Style.RESET_ALL}"
sudo_user = os.environ.get("SUDO_USER")
if sudo_user and sudo_user != "root":
real_home = Path(f"/home/{sudo_user}")
else:
real_home = Path.home()
config_base = os.getenv("XDG_CONFIG_HOME", real_home / ".config")
CONFIG_DIR = Path(config_base) / "syd"
CONFIG_FILE = CONFIG_DIR / "config"
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
# ------------------------------------------------------------
# FUNCTIONS
# ------------------------------------------------------------
def help():
print(f"{INFO} a lightweight declarative package manager for NixOS\n")
print(f"{Fore.GREEN}USAGE:{Style.RESET_ALL}")
print(" sudo syd install <package> [more packages]")
print(" sudo syd remove <package> [more packages]")
print(" syd search <package> [more packages]")
print(" syd has <package> [more packages]")
print(" syd list")
print(" syd --reset")
print(" syd --help\n")
print(f"{Fore.GREEN}COMMANDS:{Style.RESET_ALL}")
print(" install Add one or more packages to your nix packages file")
print(" remove Remove one or more packages from your nix packages file")
print(" comment Comment one or more packages from your nix packages file")
print(" list Show all packages currently listed in your nix file")
print(" search Search for packages in nixpkgs")
print(" has Check if package is listed in your nix file")
print(" --reset Reset stored packages file path and rebuild command")
print(" --help Show this help message and exit\n")
print(f"{Fore.GREEN}EXAMPLES:{Style.RESET_ALL}")
print(" sudo syd install vim htop curl")
print(" sudo syd remove neovim htop curl")
print(" syd search discord")
print(" syd search htop neovim curl\n")
print(f"{INFO} Current config file: {CONFIG_FILE}")
def check_pkg_exists(pkg: str) -> bool:
result = subprocess.run(
[
"/run/current-system/sw/bin/nix",
"--extra-experimental-features", "nix-command",
"--extra-experimental-features", "flakes",
"eval",
f"nixpkgs#{pkg}.meta.name"
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
return result.returncode == 0
def reset_config():
if CONFIG_FILE.exists():
CONFIG_FILE.unlink()
print(f"{INFO} Config reset. Next run will ask for path and rebuild command again.")
else:
print(f"{ERROR} No config file found at {CONFIG_FILE}")
def setup_config():
PACKAGES = None
REBUILD = None
if CONFIG_FILE.exists():
with open(CONFIG_FILE, "r") as f:
for line in f:
if line.startswith("packages_file="):
PACKAGES = Path(line.split("=", 1)[1].strip())
elif line.startswith("rebuild_cmd="):
REBUILD = line.split("=", 1)[1].strip()
else:
PACKAGES = Path(input(f"{INFO} Enter path to your nix packages file: ").strip())
if not PACKAGES.exists():
print(f"{ERROR} File not found: {PACKAGES}")
sys.exit(1)
REBUILD = input(f"{INFO} Enter your rebuild command (e.g. sudo nixos-rebuild switch): ").strip()
if not REBUILD:
print(f"{ERROR} No rebuild command entered.")
sys.exit(1)
with open(CONFIG_FILE, "w") as f:
f.write(f"packages_file={PACKAGES}\n")
f.write(f"rebuild_cmd={REBUILD}\n")
print(f"{SUCCESS} Saved config to {CONFIG_FILE}")
return PACKAGES, REBUILD
def rebuild_prompt():
read = input(f"{INFO} Rebuild NixOS? [y/N]: ").strip().lower()
if read != "y":
print(f"{INFO} Skipping rebuild.")
return
cmd = REBUILD.strip()
if os.geteuid() == 0 and cmd.startswith("sudo "):
cmd = cmd.replace("sudo ", "", 1)
print(f"{INFO} Running (sudo stripped): {cmd}")
env = os.environ.copy()
env["PATH"] = "/run/wrappers/bin:/usr/local/bin:/usr/bin:/bin:/run/current-system/sw/bin"
print(f"{INFO} Running: {cmd}")
result = subprocess.run(cmd, shell=True, env=env)
if result.returncode != 0:
print(f"{ERROR} Rebuild command failed.")
sys.exit(1)
def install_pkgs(*pkgs):
for pkg in pkgs:
with open(PACKAGES, "r") as f:
lines = f.readlines()
if any(pkg in line for line in lines):
print(f"{INFO} {ERROR} {pkg} already listed.")
continue
if check_pkg_exists(pkg):
insert_index = len(lines)
for i, line in enumerate(lines):
if "]" in line:
insert_index = i
break
lines.insert(insert_index, f" {pkg}\n")
with open(PACKAGES, "w") as f:
f.writelines(lines)
print(f"{SUCCESS} Added '{pkg}' to {PACKAGES}")
else:
print(f"{ERROR} Package '{pkg}' not found in nixpkgs.")
rebuild_prompt()
def remove_pkgs(*pkgs):
for pkg in pkgs:
with open(PACKAGES, "r") as f:
lines = f.readlines()
new_lines = [line for line in lines if pkg not in line.strip()]
if len(new_lines) == len(lines):
print(f"{ERROR} Package '{pkg}' not found in config.")
continue
with open(PACKAGES, "w") as f:
f.writelines(new_lines)
print(f"{SUCCESS} Removed {pkg}")
rebuild_prompt()
def comment_pkgs(*pkgs):
for pkg in pkgs:
with open(PACKAGES, "r") as f:
lines = f.read()
pattern = rf"\b{re.escape(pkg)}\b"
new_lines = re.sub(pattern, f"# {pkg}", lines)
if len(new_lines) == len(lines):
print(f"{ERROR} Package '{pkg}' not found in config.")
continue
with open(PACKAGES, "w") as f:
f.write(new_lines)
print(f"{SUCCESS} Commented out {pkg}")
rebuild_prompt()
def list_pkgs():
print(f"{INFO} Packages listed in {PACKAGES}:")
with open(PACKAGES, "r") as f:
lines = f.readlines()
pkgs = [
line.strip()
for line in lines
if line.strip()
and not line.strip().startswith("#")
and "[" not in line and "]" not in line
]
if not pkgs:
print(f"{INFO} No packages found.")
else:
for pkg in pkgs:
print(f" {pkg}")
print(f"\n{INFO} Total packages: {len(pkgs)}")
def search_pkgs(*pkgs):
for pkg in pkgs:
if check_pkg_exists(pkg):
print(f"{INFO} '{pkg}' exists in nixpkgs.")
else:
print(f"{ERROR} '{pkg}' not found in nixpkgs.")
def is_installed(*pkgs):
with open(PACKAGES, "r") as f:
lines = f.readlines()
for pkg in pkgs:
if any(re.search(rf"\b{pkg}\b", line) for line in lines):
print(f"{SUCCESS} Yes. '{pkg}' exists in {PACKAGES}")
else:
print(f"{ERROR} Could not find '{pkg}' in {PACKAGES}")
# ------------------------------------------------------------
# MAIN
# ------------------------------------------------------------
def main():
if len(sys.argv) < 2:
help()
sys.exit(0)
subcommand = sys.argv[1]
args = sys.argv[2:]
global PACKAGES, REBUILD
PACKAGES, REBUILD = setup_config()
# check for sudo in certain functions since they need elevated perms
if subcommand in ["install", "remove", "comment"]:
if os.geteuid() != 0:
print(f"{ERROR} Root permissions required to modify {PACKAGES}")
print(f"{INFO} Try: sudo syd {subcommand} <package>")
sys.exit(1)
# syd install
if subcommand == "install":
PACKAGES, REBUILD = setup_config()
if len(args) == 0:
print(f"{INFO} Usage: syd install <package>")
sys.exit(1)
install_pkgs(*args)
# syd remove
elif subcommand == "remove":
PACKAGES, REBUILD = setup_config()
if len(args) == 0:
print(f"{INFO} Usage: syd remove <package>")
sys.exit(1)
remove_pkgs(*args)
# syd comment
elif subcommand == "comment":
PACKAGES, REBUILD = setup_config()
if len(args) == 0:
print(f"{INFO} Usage: syd comment <package>")
sys.exit(1)
comment_pkgs(*args)
# syd search
elif subcommand == "search":
PACKAGES, REBUILD = setup_config()
if len(args) == 0:
print(f"{INFO} Usage: syd search <package>")
sys.exit(1)
search_pkgs(*args)
# syd has
elif subcommand == "has":
if len(args) == 0:
print(f"{ERROR} Usage: syd has <package>")
sys.exit(1)
is_installed(*args)
# syd list
elif subcommand == "list":
if len(args) != 0:
print(f"{INFO} Usage: syd list")
sys.exit(1)
PACKAGES, REBUILD = setup_config()
list_pkgs()
# syd --reset
elif subcommand == "--reset":
if len(args) != 0:
print(f"{INFO} Usage: syd --reset")
sys.exit(1)
reset_config()
# syd --help
elif subcommand in ["--help", "-h", ""]:
if len(args) != 0:
print(f"{INFO} Usage: syd --help")
sys.exit(1)
help()
else:
print(f"{INFO} Unknown command: {subcommand}")
print("Run 'syd --help' for usage.")
sys.exit(1)
if __name__ == "__main__":
main() # call the main function