Repository navigation
Expand file tree
/
Copy pathubuntu
More file actions
executable file
·393 lines (330 loc) · 14.2 KB
/
Copy pathubuntu
File metadata and controls
executable file
·393 lines (330 loc) · 14.2 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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">= 3.14"
# dependencies = ["rich", "click"]
# ///
import getpass
import os
import shutil
import subprocess
import sys
import threading
import time
from pathlib import Path
from typing import Any
import click
from rich.console import Console
from rich.theme import Theme
custom_theme = Theme({
"info": "cyan",
"warning": "yellow",
"error": "red bold",
"success": "green",
"title": "bold magenta",
})
console = Console(theme=custom_theme)
IDE_COMMANDS = {
"vscode": "code",
"codium": "codium",
"trae": "trae",
"cursor": "cursor",
"antigravity": "antigravity",
}
EXTENSIONS = [
{"id": "ms-python.python", "details": "Python support"},
{"id": "ritwickdey.liveserver", "details": "Live Server"},
{"id": "visualstudioexptteam.vscodeintellicode", "details": "IntelliCode"},
{"id": "ms-azuretools.vscode-docker", "details": "Docker"},
{"id": "octref.vetur", "details": "Vue.js support"},
{"id": "pkief.material-icon-theme", "details": "Material Icons"},
{"id": "felixfbecker.php-intellisense", "details": "PHP IntelliSense"},
{"id": "redhat.vscode-yaml", "details": "YAML support"},
{"id": "xabikos.javascriptsnippets", "details": "JS Snippets"},
{"id": "formulahendry.auto-rename-tag", "details": "Auto Rename Tag"},
{"id": "golang.go", "details": "Go language"},
{"id": "christian-kohler.path-intellisense", "details": "Path IntelliSense"},
{"id": "formulahendry.auto-close-tag", "details": "Auto Close Tag"},
{"id": "zignd.html-css-class-completion", "details": "HTML CSS Completion"},
{"id": "naumovs.color-highlight", "details": "Color Highlight"},
{"id": "dsznajder.es7-react-js-snippets", "details": "React JS Snippets"},
{"id": "yzhang.markdown-all-in-one", "details": "Markdown All in One"},
{"id": "oderwat.indent-rainbow", "details": "Indent Rainbow"},
{"id": "mikestead.dotenv", "details": "dotenv support"},
{"id": "thekalinga.bootstrap4-vscode", "details": "Bootstrap 4"},
{"id": "onecentlin.laravel-blade", "details": "Laravel Blade"},
{"id": "mhutchie.git-graph", "details": "Git Graph"},
{"id": "mechatroner.rainbow-csv", "details": "Rainbow CSV"},
{"id": "gruntfuggly.todo-tree", "details": "TODO Tree"},
{"id": "onecentlin.laravel5-snippets", "details": "Laravel 5 Snippets"},
{"id": "orta.vscode-jest", "details": "Jest support"},
{"id": "pivotal.vscode-boot-dev-pack", "details": "Spring Boot"},
{"id": "njpwerner.autodocstring", "details": "Auto Docstring"},
{"id": "cjhowe7.laravel-blade", "details": "Laravel Blade Snippets"},
{"id": "ms-dotnettools.csharp", "details": "C# support"},
{"id": "mads-hartmann.bash-ide-vscode", "details": "Bash IDE"},
{"id": "tamasfe.even-better-toml", "details": "TOML support"},
]
results: dict[str, Any] = {}
def collect_system_info(res: dict[str, Any]) -> None:
start = time.perf_counter()
distro_text = Path("/etc/os-release").read_text()
for line in distro_text.splitlines():
if line.startswith("NAME="):
res["distro_name"] = line.split("=", 1)[1].strip().strip('"')
elif line.startswith("VERSION_ID="):
res["distro_version"] = line.split("=", 1)[1].strip().strip('"')
res["desktop_environment"] = os.environ.get("DESKTOP_SESSION")
try:
res["user"] = os.getlogin()
except OSError:
res["user"] = os.environ.get("USER", None)
res["host_name"] = os.uname().nodename
try:
res["swappiness"] = Path("/proc/sys/vm/swappiness").read_text().strip()
except FileNotFoundError:
res["swappiness"] = None
if shutil.which("nala"):
res["package_manager"] = "nala"
elif shutil.which("apt"):
res["package_manager"] = "apt"
else:
res["package_manager"] = None
res["available_ides"] = {}
for name, cmd in IDE_COMMANDS.items():
if shutil.which(cmd):
res["available_ides"][name] = cmd
commands = [
"stow", "git", "python3", "pip3", "php", "composer",
"node", "npm", "nvim", "docker", "flutter", "rustc", "cargo", "uv", "rustup"
]
res["versions"] = {}
for cmd in commands:
try:
output = subprocess.run(
[cmd, "--version"],
capture_output=True,
text=True,
timeout=5
)
version_output = output.stdout.strip() or output.stderr.strip()
res["versions"][cmd] = version_output if version_output else None
except (FileNotFoundError, subprocess.TimeoutExpired, Exception):
res["versions"][cmd] = None
res["duration"] = time.perf_counter() - start
def get_sudo_password() -> str | None:
console.print("[info]Sudo password options:[/info]")
console.print(" [info]1.[/info] Interactive input (secure)")
console.print(" [info]2.[/info] From SUDO_PASS env var")
console.print(" [info]3.[/info] Let sudo prompt naturally")
choice = click.prompt("Select option", type=int, default=3)
if choice == 1:
return getpass.getpass("sudo password: ")
elif choice == 2:
console.print("[warning]Warning: SUDO_PASS env var is visible in process list[/warning]")
return os.environ.get("SUDO_PASS")
else:
return None
def run_sudo(cmd: list[str], sudo_pass: str | None, timeout: int = 300) -> bool:
try:
if sudo_pass:
# -S reads the password from stdin; -p "" suppresses the prompt
result = subprocess.run(
["sudo", "-S", "-p", ""] + cmd,
input=f"{sudo_pass}\n",
text=True,
timeout=timeout
)
else:
result = subprocess.run(
["sudo"] + cmd,
timeout=timeout
)
if result.stdout:
console.print(result.stdout)
if result.stderr:
console.print(f"[warning]{result.stderr}[/warning]")
return result.returncode == 0
except subprocess.TimeoutExpired:
console.print(f"[error]Command timed out: {' '.join(cmd)}[/error]")
return False
except Exception as e:
console.print(f"[error]Error: {e}[/error]")
return False
def run_tool_update(name: str, cmd: list[str], sudo_pass: str | None = None, timeout: int = 120) -> None:
"""Run a single tool's update command, reporting failures without aborting."""
console.print(f"[info]Updating {name}...[/info]")
try:
if sudo_pass:
if not run_sudo(cmd, sudo_pass, timeout=timeout):
console.print(f"[warning]{name} update failed[/warning]")
return
result = subprocess.run(cmd, timeout=timeout, text=True)
if result.stdout:
console.print(result.stdout)
if result.stderr:
console.print(f"[warning]{result.stderr}[/warning]")
except Exception as e:
console.print(f"[error]{name} update failed: {e}[/error]")
@click.group()
def cli():
pass
@cli.command()
def update():
"""Update system packages, tools, and AI agents"""
sudo_pass = get_sudo_password()
pkg_mgr = results.get("package_manager", "apt")
console.print(f"[info]Using package manager: {pkg_mgr}[/info]")
console.print("[info]Cleaning...[/info]")
if pkg_mgr == "nala":
if not run_sudo(["nala", "clean"], sudo_pass):
console.print("[warning]Clean failed[/warning]")
else:
if not run_sudo(["apt", "clean"], sudo_pass):
console.print("[warning]Clean failed[/warning]")
console.print("[info]Updating packages...[/info]")
if pkg_mgr == "nala":
if not run_sudo(["nala", "update"], sudo_pass):
console.print("[warning]Update failed[/warning]")
if not run_sudo(["nala", "upgrade", "--full", "-y"], sudo_pass):
console.print("[warning]Upgrade failed[/warning]")
else:
if not run_sudo(["apt", "update", "-y"], sudo_pass):
console.print("[warning]Update failed[/warning]")
if not run_sudo(["apt", "upgrade", "-y"], sudo_pass):
console.print("[warning]Upgrade failed[/warning]")
if results.get("versions", {}).get("uv"):
console.print("[info]Updating uv...[/info]")
try:
result = subprocess.run(["uv", "self", "update"], timeout=60, text=True)
if result.stdout:
console.print(result.stdout)
except Exception as e:
console.print(f"[error]uv update failed: {e}[/error]")
if results.get("versions", {}).get("npm"):
console.print("[info]Updating npm packages...[/info]")
try:
result = subprocess.run(["npm", "update", "-g"], timeout=120, text=True)
if result.stdout:
console.print(result.stdout)
except Exception as e:
console.print(f"[error]npm update failed: {e}[/error]")
if results.get("versions", {}).get("rustup"):
console.print("[info]Updating Rust...[/info]")
try:
result = subprocess.run(["rustup", "update"], timeout=120, text=True)
if result.stdout:
console.print(result.stdout)
if result.stderr:
console.print(f"[warning]{result.stderr}[/warning]")
except Exception as e:
console.print(f"[error]rustup update failed: {e}[/error]")
if shutil.which("snap"):
console.print("[info]Updating snap packages...[/info]")
if not run_sudo(["snap", "refresh"], sudo_pass, timeout=300):
console.print("[warning]snap refresh failed[/warning]")
console.print("\n[title]=== Agents & AI ===[/title]")
if shutil.which("opencode"):
run_tool_update("opencode", ["opencode", "upgrade"])
if shutil.which("claude"):
run_tool_update("claude", ["claude", "update"])
if shutil.which("pi"):
run_tool_update("pi", ["pi", "update"], timeout=300)
if shutil.which("whisper"):
# Ubuntu 24.04+ marks the system python externally managed (PEP 668)
run_tool_update(
"whisper",
["pip3", "install", "--user", "-U", "--break-system-packages", "openai-whisper"],
timeout=600,
)
if shutil.which("laya"):
run_tool_update("laya", ["uv", "tool", "upgrade", "laya"], timeout=300)
if shutil.which("ollama"):
if subprocess.run(["dpkg", "-s", "ollama"], capture_output=True).returncode == 0:
console.print("[info]ollama is apt-managed, already covered by the package upgrade[/info]")
else:
# script installs have no self-update command; the official installer updates in place
run_tool_update(
"ollama",
["bash", "-c", "set -o pipefail; curl -fsSL https://ollama.com/install.sh | sh"],
sudo_pass,
timeout=600,
)
console.print("[success]Update complete![/success]")
@cli.command()
@click.option("--ide", "-i", multiple=True, help="IDE(s) to install on")
@click.option("--list", "list_extensions", is_flag=True, help="List available extensions")
def extensions(ide: tuple, list_extensions: bool):
"""Install extensions on selected IDEs"""
if list_extensions:
console.print("[title]Available Extensions:[/title]")
for ext in EXTENSIONS:
console.print(f" [info]{ext['id']}:[/info] {ext.get('details', '')}")
return
available = results.get("available_ides", {})
if not ide:
selected = list(available.keys())
if not selected:
console.print("[error]No IDEs detected. Use --ide to specify.[/error]")
return
else:
selected = []
for i in ide:
if i in available:
selected.append(i)
else:
console.print(f"[warning]Skipping {i}: not found[/warning]")
console.print(f"[info]Installing on: {', '.join(selected)}[/info]")
for ide_name in selected:
cmd = available[ide_name]
for ext in EXTENSIONS:
try:
subprocess.run(
[cmd, "--install-extension", ext["id"]],
timeout=30,
capture_output=True
)
console.print(f"[success]{ide_name}:[/success] {ext['id']}")
except Exception:
console.print(f"[error]Failed: {ext['id']}[/error]")
continue
def main() -> None:
global results
worker = threading.Thread(target=collect_system_info, args=(results,))
worker.start()
worker.join()
if len(sys.argv) > 1:
cli()
else:
print_results()
def print_results():
global results
console.print("[title]=== Environment Variables ===[/title]")
for key, value in results.items():
if key == "versions":
continue
if key == "duration":
continue
if key == "available_ides":
continue
console.print(f"[info]{key}:[/info] [success]{value if value is not None else 'N/A'}[/success]")
console.print("\n[title]=== Package Manager ===[/title]")
console.print(f"[info]pkg_mgr:[/info] [success]{results.get('package_manager', 'N/A')}[/success]")
console.print("\n[title]=== Available IDEs ===[/title]")
ides = results.get("available_ides", {})
if ides:
for name in ides:
console.print(f" [success]{name}[/success]")
else:
console.print(" [info]N/A[/info]")
console.print("\n[title]=== Versions ===[/title]")
for cmd, version in results.get("versions", {}).items():
console.print(f"[info]{cmd}:[/info] [success]{version if version is not None else 'N/A'}[/success]")
console.print(f"\n[title]=== Performance ===[/title]")
console.print(f"[success]Thread completed in {results.get('duration', 0):.2f} seconds[/success]")
console.print("\n[title]=== Commands ===[/title]")
console.print(" [info]uv run ./ubuntu update[/info] - Update system packages")
console.print(" [info]uv run ./ubuntu extensions[/info] - Install extensions on detected IDEs")
console.print(" [info]uv run ./ubuntu extensions --list[/info] - List available extensions")
console.print(" [info]uv run ./ubuntu extensions -i vscode -i trae[/info] - Install on specific IDEs")
if __name__ == "__main__":
main()