-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathshared.ts
More file actions
370 lines (328 loc) · 9.75 KB
/
shared.ts
File metadata and controls
370 lines (328 loc) · 9.75 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
/**
* Shared utilities for dotfiles installation scripts
*/
export type PackageManager = "zypper" | "dnf" | "apt" | "winget" | "homebrew"
export type LogLevel = "INFO" | "WARN" | "ERROR" | "SUCCESS"
export interface CommandResult {
success: boolean
stdout: string
stderr: string
code: number
}
// ===== LOGGING UTILITIES =====
let logPath: string | null = null
/**
* Initialize logging for a script
*/
export async function initializeLogging(scriptName: string, logDir = "./logs"): Promise<string> {
const timestamp = new Date().toISOString().replace(/[:.]/g, "-")
const logFileName = `${scriptName}_${timestamp}.log`
logPath = `${logDir}/${logFileName}`
try {
await Deno.mkdir(logDir, { recursive: true })
} catch (error) {
console.error(`⚠️ Failed to create log directory: ${error}`)
}
return logPath
}
/**
* Log a message with optional level and emoji
*/
export async function log(message: string, level: LogLevel = "INFO"): Promise<void> {
const timestamp = new Date().toISOString()
const logEntry = `[${timestamp}] [${level}] ${message}\n`
// Console output with colors and emojis
const styles = {
INFO: { color: "\x1b[36m", emoji: "" }, // Cyan
WARN: { color: "\x1b[33m", emoji: "⚠️" }, // Yellow
ERROR: { color: "\x1b[31m", emoji: "❌" }, // Red
SUCCESS: { color: "\x1b[32m", emoji: "✅" }, // Green
RESET: "\x1b[0m",
}
const style = styles[level]
console.log(`${style.color}${style.emoji} ${message}${styles.RESET}`)
// File logging
if (logPath) {
try {
await Deno.writeTextFile(logPath, logEntry, { append: true })
} catch (error) {
console.error(`⚠️ Failed to write to log file: ${error}`)
}
}
}
// ===== UTILITY FUNCTIONS =====
/**
* Format bytes to human-readable string
*/
export function formatBytes(bytes: number): string {
const units = ["B", "KB", "MB", "GB", "TB", "PB"]
let value = bytes
let unitIndex = 0
while (value >= 1024 && unitIndex < units.length - 1) {
value /= 1024
unitIndex++
}
return `${value.toFixed(1)}${units[unitIndex]}`
}
/**
* Get system memory size in bytes
*/
export async function getSystemMemoryBytes(): Promise<number> {
const result = await runShellCommand("free -b | grep '^Mem:' | awk '{print $2}'")
if (!result.success) {
throw new Error(`Failed to get system memory: ${result.stderr}`)
}
const memBytes = parseInt(result.stdout.trim())
if (isNaN(memBytes)) {
throw new Error("Could not parse memory size")
}
return memBytes
}
/**
* Get disk usage information for a path
*/
export async function getDiskUsage(
path: string,
): Promise<{ total: number; used: number; available: number }> {
const result = await runShellCommand(
`df -B1 "${path}" | tail -1 | awk '{print $2 " " $3 " " $4}'`,
)
if (!result.success) {
throw new Error(`Failed to get disk usage for ${path}: ${result.stderr}`)
}
const [total, used, available] = result.stdout.trim().split(" ").map((s) => parseInt(s))
if (total === undefined || used === undefined || available === undefined) {
throw new Error("Could not parse disk usage information")
}
return { total, used, available }
}
/**
* Run a command and return the result
*/
export async function runCommand(command: string[]): Promise<CommandResult> {
try {
const cmd = new Deno.Command(command[0], {
args: command.slice(1),
stdout: "piped",
stderr: "piped",
})
const { success, code, stdout, stderr } = await cmd.output()
return {
success,
code,
stdout: new TextDecoder().decode(stdout),
stderr: new TextDecoder().decode(stderr),
}
} catch (error) {
return {
success: false,
code: -1,
stdout: "",
stderr: error instanceof Error ? error.message : String(error),
}
}
}
/**
* Run a shell command (bash -c "command")
*/
export async function runShellCommand(command: string): Promise<CommandResult> {
return runCommand(["bash", "-c", command])
}
/**
* Detect the package manager for the current OS
*/
export async function detectPackageManager(): Promise<PackageManager | null> {
const os = Deno.build.os
if (os === "linux") {
// Try to detect package manager by existence in PATH
for (const mgr of ["zypper", "dnf", "apt"]) {
const result = await runCommand(["which", mgr])
if (result.success) {
return mgr as PackageManager
}
}
} else if (os === "windows") {
return "winget"
} else if (os === "darwin") {
return "homebrew"
}
return null
}
/**
* Check if a file exists
*/
export async function fileExists(path: string): Promise<boolean> {
try {
await Deno.stat(path)
return true
} catch {
return false
}
}
/**
* Check if a directory exists
*/
export async function directoryExists(path: string): Promise<boolean> {
try {
const stat = await Deno.stat(path)
return stat.isDirectory
} catch {
return false
}
}
/**
* Check if a command is available in PATH
*/
export async function commandExists(command: string): Promise<boolean> {
const result = await runCommand(["which", command])
return result.success
}
/**
* Install packages using the detected package manager
*/
export async function installPackages(
packageManager: PackageManager,
packages: string[],
): Promise<CommandResult & { alreadyInstalled?: string[]; newlyInstalled?: string[] }> {
if (packages.length === 0) {
return {
success: true,
code: 0,
stdout: "",
stderr: "",
alreadyInstalled: [],
newlyInstalled: [],
}
}
let command: string[]
switch (packageManager) {
case "zypper":
command = ["sudo", "zypper", "install", "-y", ...packages]
break
case "dnf":
command = ["sudo", "dnf", "install", "-y", ...packages]
break
case "apt":
command = ["sudo", "apt", "install", "-y", ...packages]
break
case "winget": {
// winget doesn't support batch installation, so install one by one
const newlyInstalled: string[] = []
const alreadyInstalled: string[] = []
for (const pkg of packages) {
const result = await runCommand(["winget", "install", "--silent", pkg])
if (result.success) {
if (
result.stdout.includes("already installed") ||
result.stdout.includes("No applicable update found")
) {
alreadyInstalled.push(pkg)
} else {
newlyInstalled.push(pkg)
}
} else {
return { ...result, alreadyInstalled, newlyInstalled }
}
}
return { success: true, code: 0, stdout: "", stderr: "", alreadyInstalled, newlyInstalled }
}
case "homebrew":
command = ["brew", "install", ...packages]
break
default:
return {
success: false,
code: -1,
stdout: "",
stderr: `Unsupported package manager: ${packageManager}`,
}
}
const result = await runCommand(command)
// Parse output to determine installation status
const alreadyInstalled: string[] = []
const newlyInstalled: string[] = []
if (result.success) {
if (packageManager === "dnf") {
// Parse DNF output for specific package status
for (const pkg of packages) {
if (
result.stdout.includes(`Installing : ${pkg}`) ||
result.stdout.includes(`Upgrading : ${pkg}`) ||
result.stdout.includes(`Installed:`) && result.stdout.includes(pkg)
) {
newlyInstalled.push(pkg)
} else if (
result.stdout.includes(`Package ${pkg}`) && result.stdout.includes("already installed") ||
result.stderr.includes(`Package ${pkg}`) && result.stderr.includes("already installed") ||
result.stdout.includes("Nothing to do") && packages.length === 1
) {
alreadyInstalled.push(pkg)
} else {
// Check if package is actually installed by querying DNF
const checkResult = await runCommand(["dnf", "list", "installed", pkg])
if (checkResult.success) {
alreadyInstalled.push(pkg)
} else {
newlyInstalled.push(pkg) // Default assumption if we can't determine status
}
}
}
} else if (packageManager === "apt") {
// APT shows specific messages for already installed packages
for (const pkg of packages) {
if (
result.stdout.includes(`${pkg} is already the newest version`) ||
result.stdout.includes(`${pkg} set to manually installed`)
) {
alreadyInstalled.push(pkg)
} else {
newlyInstalled.push(pkg)
}
}
} else if (packageManager === "homebrew") {
// Homebrew shows "already installed" message
for (const pkg of packages) {
if (result.stdout.includes(`${pkg}: already installed`)) {
alreadyInstalled.push(pkg)
} else {
newlyInstalled.push(pkg)
}
}
} else {
// Default for other package managers
newlyInstalled.push(...packages)
}
}
return { ...result, alreadyInstalled, newlyInstalled }
}
/**
* Update package manager repositories
*/
export async function updatePackageManager(packageManager: PackageManager): Promise<CommandResult> {
let command: string[]
switch (packageManager) {
case "zypper":
command = ["sudo", "zypper", "refresh"]
break
case "dnf":
command = ["sudo", "dnf", "check-update"]
break
case "apt":
command = ["sudo", "apt", "update"]
break
case "winget":
command = ["winget", "source", "update"]
break
case "homebrew":
command = ["brew", "update"]
break
default:
return {
success: false,
code: -1,
stdout: "",
stderr: `Unsupported package manager: ${packageManager}`,
}
}
return runCommand(command)
}