easy-devops 0.2.4 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,7 @@
4
4
  * Nginx Manager — full control over nginx from the CLI.
5
5
  *
6
6
  * Exported functions:
7
- * - showNginxManager() — interactive menu for managing nginx
7
+ * - showNginxManager() — interactive menu for managing nginx
8
8
  *
9
9
  * All shell calls go through core/shell.js (run / runLive).
10
10
  * Platform differences (Windows/Linux) are handled via isWindows guards.
@@ -14,8 +14,9 @@ import chalk from 'chalk';
14
14
  import inquirer from 'inquirer';
15
15
  import ora from 'ora';
16
16
  import { run, runLive } from '../../core/shell.js';
17
- import { loadConfig } from '../../core/config.js';
17
+ import { loadConfig, saveConfig } from '../../core/config.js';
18
18
  import { ensureNginxInclude } from '../../core/nginx-conf-generator.js';
19
+ import { runDetection } from '../../core/detector.js';
19
20
 
20
21
  const isWindows = process.platform === 'win32';
21
22
 
@@ -136,7 +137,7 @@ async function viewErrorLog(logPath) {
136
137
  if (result.success && result.stdout) {
137
138
  console.log('\n' + result.stdout);
138
139
  } else {
139
- console.log(chalk.yellow('\n No errors logged yet (log file not found or empty)\n'));
140
+ console.log(chalk.yellow('\n No errors logged yet (log file not found or empty)\n'));
140
141
  }
141
142
  }
142
143
 
@@ -196,11 +197,11 @@ async function startNginx(nginxExe, nginxDir) {
196
197
  : `tail -n 20 "${logPath}" 2>/dev/null`;
197
198
  const logResult = await run(logCmd);
198
199
 
199
- console.log(chalk.yellow('\n Recent error log:'));
200
+ console.log(chalk.yellow('\n Recent error log:'));
200
201
  if (logResult.success && logResult.stdout) {
201
202
  console.log(chalk.red(logResult.stdout));
202
203
  } else {
203
- console.log(chalk.gray(' (error log not found or empty)'));
204
+ console.log(chalk.gray(' (error log not found or empty)'));
204
205
  }
205
206
 
206
207
  return { success: false };
@@ -233,7 +234,7 @@ async function installNginx() {
233
234
  }
234
235
  spinner.fail('Installation failed');
235
236
  console.log(chalk.red(result.stderr || result.stdout));
236
- console.log(chalk.gray('\n Manual instructions: https://nginx.org/en/docs/install.html\n'));
237
+ console.log(chalk.gray('\n Manual instructions: https://nginx.org/en/docs/install.html\n'));
237
238
  return { success: false, message: 'Installation failed', output: result.stderr || result.stdout };
238
239
  }
239
240
 
@@ -250,13 +251,50 @@ async function installNginx() {
250
251
  'winget install -e --id nginxinc.nginx --accept-package-agreements --accept-source-agreements',
251
252
  { timeout: 120000 },
252
253
  );
253
- if (result.success) {
254
- spinner.succeed('nginx installed successfully');
254
+
255
+ // Check if nginx was installed OR already installed
256
+ const output = (result.stdout || '') + (result.stderr || '');
257
+ const alreadyInstalled = output.includes('already installed') || output.includes('No newer package') || output.includes('No available upgrade');
258
+ const installed = result.success || alreadyInstalled;
259
+
260
+ if (installed) {
261
+ // Try to detect where nginx was installed and update config
262
+ const commonPaths = [
263
+ 'C:\\nginx',
264
+ `${process.env.ProgramFiles}\\nginx`,
265
+ `${process.env.LOCALAPPDATA}\\Programs\\nginx`,
266
+ `${process.env.ProgramW6432}\\nginx`,
267
+ ];
268
+
269
+ let foundPath = null;
270
+ for (const p of commonPaths) {
271
+ if (!p) continue;
272
+ const check = await run(`Test-Path "${p}\\nginx.exe"`);
273
+ if (check.stdout.trim().toLowerCase() === 'true') {
274
+ foundPath = p;
275
+ break;
276
+ }
277
+ }
278
+
279
+ if (foundPath) {
280
+ // Update config if different from current
281
+ const currentConfig = loadConfig();
282
+ if (currentConfig.nginxDir !== foundPath) {
283
+ currentConfig.nginxDir = foundPath;
284
+ saveConfig(currentConfig);
285
+ }
286
+ spinner.succeed(`nginx installed at ${foundPath}`);
287
+ } else {
288
+ spinner.succeed('nginx installed successfully');
289
+ }
290
+
291
+ // Re-run detection to update the stored info
292
+ await runDetection();
255
293
  return { success: true, message: 'nginx installed successfully', output: result.stdout };
256
294
  }
257
295
  spinner.fail('winget install failed');
258
296
  console.log(chalk.red(result.stderr || result.stdout));
259
- console.log(chalk.gray('\n Manual instructions: https://nginx.org/en/docs/install.html\n'));
297
+ console.log(chalk.gray('\n Manual instructions: https://nginx.org/en/docs/install.html\n'));
260
298
  return { success: false, message: 'Installation failed', output: result.stderr || result.stdout };
261
299
  }
262
300
 
@@ -274,7 +312,7 @@ async function installNginx() {
274
312
  const fetched = (fetchVersionResult.stdout || '').trim();
275
313
  if (/^\d+\.\d+\.\d+$/.test(fetched)) nginxVersion = fetched;
276
314
 
277
- const { nginxDir } = loadConfig();
315
+ let { nginxDir } = loadConfig();
278
316
  const zipUrl = `https://nginx.org/download/nginx-${nginxVersion}.zip`;
279
317
  const zipDest = `$env:TEMP\\nginx-${nginxVersion}.zip`;
280
318
 
@@ -302,7 +340,7 @@ async function installNginx() {
302
340
  if (!downloadOk) {
303
341
  spinner.fail('Download failed');
304
342
  console.log(chalk.red(downloadResult.stderr || downloadResult.stdout));
305
- console.log(chalk.gray(`\n Download nginx manually from: https://nginx.org/en/download.html\n`));
343
+ console.log(chalk.gray(`\n Download nginx manually from: https://nginx.org/en/download.html\n`));
306
344
  return { success: false, message: 'Download failed', output: downloadResult.stderr || downloadResult.stdout };
307
345
  }
308
346
 
@@ -326,6 +364,9 @@ async function installNginx() {
326
364
  return { success: false, message: 'nginx.exe not found after extraction' };
327
365
  }
328
366
 
367
+ // Re-run detection
368
+ await runDetection();
369
+
329
370
  spinner.succeed(`nginx ${nginxVersion} installed to ${nginxDir}`);
330
371
  return { success: true, message: `nginx ${nginxVersion} installed successfully`, output: '' };
331
372
  }
@@ -337,14 +378,14 @@ export async function showNginxManager() {
337
378
  const { nginxDir } = loadConfig();
338
379
  const status = await getNginxStatus(nginxDir);
339
380
 
340
- console.log(chalk.bold('\n Nginx Manager'));
341
- console.log(chalk.gray(' ' + '─'.repeat(40)));
381
+ console.log(chalk.bold('\n Nginx Manager'));
382
+ console.log(chalk.gray(' ' + '─'.repeat(40)));
342
383
 
343
384
  if (status.version) {
344
385
  const statusIcon = status.running ? chalk.green('✅ Running') : chalk.red('❌ Stopped');
345
- console.log(` ${statusIcon} | v${status.version} | ${status.nginxDir}`);
386
+ console.log(` ${statusIcon} | v${status.version} | ${status.nginxDir}`);
346
387
  } else {
347
- console.log(` ${chalk.yellow('⚠ Not installed')}`);
388
+ console.log(` ${chalk.yellow('⚠ Not installed')}`);
348
389
  }
349
390
  console.log();
350
391
 
@@ -394,7 +435,7 @@ export async function showNginxManager() {
394
435
  case 'Test config': {
395
436
  const result = await testConfig(status.nginxExe, status.nginxDir);
396
437
  console.log(
397
- '\n Config test: ' +
438
+ '\n Config test: ' +
398
439
  (result.success ? chalk.green('✓ OK') : chalk.red('✗ Failed')) +
399
440
  '\n',
400
441
  );
@@ -4,37 +4,31 @@
4
4
  * Check for updates and upgrade easy-devops in place.
5
5
  *
6
6
  * Flow:
7
- * 1. Fetch latest version from npm registry
8
- * 2. If an update is available, offer to install it
9
- * 3. Before installing: record dashboard running state in DB
10
- * (key: 'update-pre-dashboard') so it survives a crash mid-update
11
- * 4. Stop dashboard if it was running
12
- * 5. Close database connection
13
- * 6. Spawn an external update script that runs npm install
14
- * after this process exits (to avoid EBUSY on Windows)
15
- * 7. This process exits; update script runs
16
- * 8. On next launch, recoverIfNeeded restarts dashboard if needed
7
+ * 1. Fetch latest version from npm registry
8
+ * 2. If an update is available, offer to install it
9
+ * 3. Before installing: record dashboard running state in DB
10
+ * (key: 'update-pre-dashboard') so it survives a crash mid-update
11
+ * 4. Stop dashboard if it was running
12
+ * 5. Run: npm install -g easy-devops@<latest>
13
+ * 6. Re-start dashboard if it was running before
14
+ * 7. Clear the saved state key
17
15
  */
18
16
 
19
17
  import chalk from 'chalk';
20
18
  import inquirer from 'inquirer';
21
19
  import ora from 'ora';
22
20
  import path from 'path';
23
- import fs from 'fs';
24
21
  import { fileURLToPath } from 'url';
25
22
  import { createRequire } from 'module';
26
- import { spawn } from 'child_process';
27
23
  import { run } from '../../core/shell.js';
28
- import { dbGet, dbSet, closeDb } from '../../core/db.js';
24
+ import { dbGet, dbSet, closeDb, initDb } from '../../core/db.js';
29
25
  import { loadConfig } from '../../core/config.js';
30
- import { getDashboardStatus, stopDashboard } from './dashboard.js';
26
+ import { getDashboardStatus, startDashboard, stopDashboard } from './dashboard.js';
31
27
 
32
28
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
33
- const require = createRequire(import.meta.url);
29
+ const require = createRequire(import.meta.url);
34
30
  const { version: currentVersion } = require('../../package.json');
35
31
 
36
- const isWindows = process.platform === 'win32';
37
-
38
32
  // ─── Version helpers ──────────────────────────────────────────────────────────
39
33
 
40
34
  async function fetchLatestVersion() {
@@ -60,20 +54,18 @@ async function recoverIfNeeded() {
60
54
  const saved = dbGet('update-pre-dashboard');
61
55
  if (!saved?.wasRunning) return;
62
56
 
63
- console.log(chalk.yellow('\n A previous update left the dashboard stopped.'));
57
+ console.log(chalk.yellow('\n A previous update left the dashboard stopped.'));
64
58
  const { restart } = await inquirer.prompt([{
65
- type: 'confirm',
66
- name: 'restart',
59
+ type: 'confirm',
60
+ name: 'restart',
67
61
  message: 'Restart the dashboard now?',
68
62
  default: true,
69
63
  }]);
70
64
 
71
65
  if (restart) {
72
- // Dynamic import to avoid circular dependency and ensure fresh state
73
- const { startDashboard } = await import('./dashboard.js');
74
66
  const port = saved.port || loadConfig().dashboardPort;
75
- const sp = ora(`Starting dashboard on port ${port}...`).start();
76
- const res = await startDashboard(port);
67
+ const sp = ora(`Starting dashboard on port ${port}...`).start();
68
+ const res = await startDashboard(port);
77
69
  res.success
78
70
  ? sp.succeed(`Dashboard restarted on port ${port}`)
79
71
  : sp.fail('Could not restart dashboard — use the Dashboard menu');
@@ -84,141 +76,54 @@ async function recoverIfNeeded() {
84
76
 
85
77
  // ─── Perform update ───────────────────────────────────────────────────────────
86
78
 
87
- /**
88
- * Creates and spawns an external update script that runs after this process exits.
89
- * This is necessary on Windows because better-sqlite3's native module stays locked
90
- * as long as any Node.js process has the database open.
91
- */
92
79
  async function performUpdate(latestVersion) {
93
80
  // Step 1 — snapshot dashboard state and persist it
94
81
  const status = await getDashboardStatus();
95
82
  dbSet('update-pre-dashboard', {
96
83
  wasRunning: status.running,
97
- pid: status.pid,
98
- port: status.port,
84
+ pid: status.pid,
85
+ port: status.port,
99
86
  });
100
87
 
101
- // Step 2 — stop dashboard if running (it has its own DB connection)
88
+ // Step 2 — stop dashboard if running
102
89
  if (status.running) {
103
90
  const sp = ora('Stopping dashboard...').start();
104
91
  await stopDashboard(status.pid);
105
92
  sp.succeed('Dashboard stopped');
106
- // Give the dashboard process a moment to fully terminate
107
- await new Promise(r => setTimeout(r, 2000));
108
93
  }
109
94
 
110
- // Step 3 — close this process's database connection
95
+ // Step 3 — close the SQLite connection so npm can rename the db file (EBUSY on Windows)
111
96
  closeDb();
112
97
 
113
- // Step 4 — create an external update script and spawn it
114
- // The script will run npm install after this process exits
115
- const updateScriptPS = `
116
- $ProgressPreference = 'SilentlyContinue'
117
- Write-Host ""
118
- Write-Host "Installing easy-devops@${latestVersion}..." -ForegroundColor Cyan
119
- Write-Host ""
120
- npm install -g easy-devops@${latestVersion}
121
- if ($LASTEXITCODE -eq 0) {
122
- Write-Host ""
123
- Write-Host "Successfully updated to v${latestVersion}" -ForegroundColor Green
124
- Write-Host "Run 'easy-devops' to start the new version." -ForegroundColor Gray
125
- } else {
126
- Write-Host ""
127
- Write-Host "Update failed. Please try again or update manually:" -ForegroundColor Red
128
- Write-Host " npm install -g easy-devops@${latestVersion}" -ForegroundColor Yellow
129
- }
130
- Write-Host ""
131
- Write-Host "Press any key to close this window..." -ForegroundColor Gray
132
- $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
133
- `;
134
-
135
- const updateScriptBash = `#!/bin/bash
136
- echo ""
137
- echo -e "\\033[36mInstalling easy-devops@${latestVersion}...\\033[0m"
138
- echo ""
139
- npm install -g easy-devops@${latestVersion}
140
- if [ $? -eq 0 ]; then
141
- echo ""
142
- echo -e "\\033[32mSuccessfully updated to v${latestVersion}\\033[0m"
143
- echo -e "\\033[90mRun 'easy-devops' to start the new version.\\033[0m"
144
- else
145
- echo ""
146
- echo -e "\\033[31mUpdate failed. Please try again or update manually:\\033[0m"
147
- echo -e "\\033[33m npm install -g easy-devops@${latestVersion}\\033[0m"
148
- fi
149
- echo ""
150
- read -p "Press Enter to close this window..."
151
- `;
98
+ // Step 4 — install new version
99
+ const sp = ora(`Installing easy-devops@${latestVersion}...`).start();
100
+ const result = await run(`npm install -g easy-devops@${latestVersion}`, { timeout: 120000 });
152
101
 
153
- console.log(chalk.cyan('\n Starting external update process...'));
154
- console.log(chalk.gray(' A new window will open to complete the update.'));
155
- console.log(chalk.gray(' This window will close after the update starts.\n'));
156
-
157
- if (isWindows) {
158
- // Write script to temp file and run in new PowerShell window
159
- const tempDir = process.env.TEMP || 'C:\\Windows\\Temp';
160
- const tempScript = path.join(tempDir, 'easy-devops-update.ps1');
161
- fs.writeFileSync(tempScript, updateScriptPS, 'utf8');
162
-
163
- // Run in a new window, this process will exit
164
- spawn('powershell.exe', [
165
- '-NoExit',
166
- '-ExecutionPolicy', 'Bypass',
167
- '-File', tempScript
168
- ], {
169
- detached: true,
170
- stdio: 'ignore',
171
- windowsHide: false
172
- }).unref();
102
+ if (!result.success) {
103
+ sp.fail('Update failed');
104
+ console.log(chalk.red('\n' + (result.stderr || result.stdout) + '\n'));
105
+ // Leave 'update-pre-dashboard' in DB so recovery runs on next launch
106
+ return false;
107
+ }
173
108
 
174
- // Clean up hint
175
- console.log(chalk.gray(` Update script: ${tempScript}`));
176
- } else {
177
- // On Linux/Mac, run in a new terminal window if possible
178
- const tempScript = '/tmp/easy-devops-update.sh';
179
- fs.writeFileSync(tempScript, updateScriptBash, 'utf8');
180
- fs.chmodSync(tempScript, '755');
109
+ sp.succeed(`Updated to v${latestVersion}`);
181
110
 
182
- // Try common terminal emulators
183
- const terminals = [
184
- ['gnome-terminal', '--', 'bash', '-c', updateScriptBash],
185
- ['xterm', '-e', 'bash', '-c', updateScriptBash],
186
- ['konsole', '-e', 'bash', '-c', updateScriptBash],
187
- ];
188
- let launched = false;
111
+ // Re-initialize the database connection after npm replaced the module
112
+ initDb();
189
113
 
190
- for (const [cmd, ...args] of terminals) {
191
- try {
192
- spawn(cmd, args, {
193
- detached: true,
194
- stdio: 'ignore'
195
- }).unref();
196
- launched = true;
197
- break;
198
- } catch { /* try next */ }
199
- }
114
+ // Step 5 — restart dashboard if it was running before
115
+ const saved = dbGet('update-pre-dashboard');
116
+ dbSet('update-pre-dashboard', null);
200
117
 
201
- if (!launched) {
202
- // Fallback: just run npm directly in this terminal
203
- console.log(chalk.yellow('\nRunning update in this window...'));
204
- const result = await run(`npm install -g easy-devops@${latestVersion}`, { timeout: 120000 });
205
- if (result.success) {
206
- console.log(chalk.green(`\n Successfully updated to v${latestVersion}`));
207
- } else {
208
- console.log(chalk.red('\n Update failed:'));
209
- console.log(result.stderr || result.stdout);
210
- }
211
- return result.success;
212
- }
118
+ if (saved?.wasRunning) {
119
+ const port = saved.port || loadConfig().dashboardPort;
120
+ const restSp = ora(`Restarting dashboard on port ${port}...`).start();
121
+ const res = await startDashboard(port);
122
+ res.success
123
+ ? restSp.succeed(`Dashboard restarted on port ${port}`)
124
+ : restSp.fail('Could not restart dashboard — use the Dashboard menu');
213
125
  }
214
126
 
215
- // Give a moment for the external process to start
216
- await new Promise(r => setTimeout(r, 1000));
217
-
218
- console.log(chalk.green('\n Update process launched.'));
219
- console.log(chalk.gray(' Complete the update in the new window, then run: easy-devops'));
220
- console.log(chalk.gray(' If the dashboard was running, it will be restarted on next launch.\n'));
221
-
222
127
  return true;
223
128
  }
224
129
 
@@ -232,12 +137,12 @@ export default async function updateMenu() {
232
137
  const latestVersion = await fetchLatestVersion();
233
138
  spinner.stop();
234
139
 
235
- console.log(chalk.bold('\n Check for Updates'));
236
- console.log(chalk.gray(' ' + '─'.repeat(40)));
237
- console.log(` Current version : ${chalk.cyan('v' + currentVersion)}`);
140
+ console.log(chalk.bold('\n Check for Updates'));
141
+ console.log(chalk.gray(' ' + '─'.repeat(40)));
142
+ console.log(` Current version : ${chalk.cyan('v' + currentVersion)}`);
238
143
 
239
144
  if (!latestVersion) {
240
- console.log(chalk.yellow(' Could not reach npm registry. Check your internet connection.\n'));
145
+ console.log(chalk.yellow(' Could not reach npm registry. Check your internet connection.\n'));
241
146
  await inquirer.prompt([{ type: 'input', name: '_', message: 'Press Enter to go back...' }]);
242
147
  return;
243
148
  }
@@ -245,9 +150,9 @@ export default async function updateMenu() {
245
150
  const updateAvailable = isNewer(latestVersion, currentVersion);
246
151
 
247
152
  if (updateAvailable) {
248
- console.log(` Latest version : ${chalk.green('v' + latestVersion)} ${chalk.yellow('← update available')}\n`);
153
+ console.log(` Latest version : ${chalk.green('v' + latestVersion)} ${chalk.yellow('← update available')}\n`);
249
154
  } else {
250
- console.log(` Latest version : ${chalk.green('v' + latestVersion)} ${chalk.gray('✓ up to date')}\n`);
155
+ console.log(` Latest version : ${chalk.green('v' + latestVersion)} ${chalk.gray('✓ up to date')}\n`);
251
156
  }
252
157
 
253
158
  const choices = updateAvailable
@@ -257,8 +162,8 @@ export default async function updateMenu() {
257
162
  let choice;
258
163
  try {
259
164
  ({ choice } = await inquirer.prompt([{
260
- type: 'list',
261
- name: 'choice',
165
+ type: 'list',
166
+ name: 'choice',
262
167
  message: 'Select an option:',
263
168
  choices,
264
169
  }]));
@@ -268,9 +173,12 @@ export default async function updateMenu() {
268
173
  }
269
174
 
270
175
  if (choice === `Update to v${latestVersion}`) {
271
- await performUpdate(latestVersion);
176
+ const success = await performUpdate(latestVersion);
177
+ if (success) {
178
+ console.log(chalk.gray('\n Restart easy-devops to use the new version.\n'));
179
+ }
272
180
  try {
273
- await inquirer.prompt([{ type: 'input', name: '_', message: 'Press Enter to exit...' }]);
181
+ await inquirer.prompt([{ type: 'input', name: '_', message: 'Press Enter to continue...' }]);
274
182
  } catch { /* ExitPromptError */ }
275
183
  }
276
184
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "easy-devops",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
4
4
  "description": "A unified DevOps management tool with CLI and web dashboard for managing Nginx, SSL certificates, and Node.js on Linux and Windows servers.",
5
5
  "keywords": [
6
6
  "devops",