ubuntu-service 1.2.1 → 3.1.1
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.
- package/LICENSE +15 -15
- package/README.md +129 -117
- package/bin/index.js +8 -8
- package/package.json +50 -48
- package/src/cli.js +2 -2
- package/src/index.js +3 -3
- package/src/v2/actions.js +49 -58
- package/src/v2/cli.js +245 -245
- package/src/v2/detector.js +195 -195
- package/src/v2/index.js +11 -55
- package/src/v2/parser.js +113 -113
- package/src/v2/systemctl.js +147 -147
- package/src/v3/cli.js +126 -0
- package/src/v3/index.js +5 -0
- package/src/v3/service.js +175 -0
- package/src/v1/actions.js +0 -58
- package/src/v1/cli.js +0 -245
- package/src/v1/detector.js +0 -194
- package/src/v1/index.js +0 -55
- package/src/v1/parser.js +0 -113
- package/src/v1/systemctl.js +0 -147
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { parseServiceFile, detectPort } from "../v2/parser.js";
|
|
4
|
+
import { getServiceLiveStatus } from "../v1/systemctl.js";
|
|
5
|
+
|
|
6
|
+
export const DEFAULT_SYSTEMD_DIRS = [
|
|
7
|
+
"/etc/systemd/system",
|
|
8
|
+
"/run/systemd/system",
|
|
9
|
+
"/usr/lib/systemd/system",
|
|
10
|
+
"/lib/systemd/system"
|
|
11
|
+
];
|
|
12
|
+
|
|
13
|
+
function readPortFromEnvPath(envPath) {
|
|
14
|
+
if (!envPath || typeof envPath !== "string") return null;
|
|
15
|
+
const cleanPath = envPath.replace(/^-/, "").trim();
|
|
16
|
+
if (!cleanPath || !fs.existsSync(cleanPath)) return null;
|
|
17
|
+
try {
|
|
18
|
+
const content = fs.readFileSync(cleanPath, "utf-8");
|
|
19
|
+
const m = content.match(/^\s*(?:PORT|APP_PORT|SERVER_PORT|LISTEN_PORT)\s*=\s*['"]?(\d{2,5})['"]?/m);
|
|
20
|
+
return m ? parseInt(m[1], 10) : null;
|
|
21
|
+
} catch {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function resolvePortWithSource(parsedConfig, workingDir) {
|
|
27
|
+
const service = parsedConfig?.Service || {};
|
|
28
|
+
|
|
29
|
+
const envs = Array.isArray(service.Environment)
|
|
30
|
+
? service.Environment
|
|
31
|
+
: service.Environment ? [service.Environment] : [];
|
|
32
|
+
for (const entry of envs) {
|
|
33
|
+
const m = String(entry).match(/(?:PORT|LISTEN_PORT|APP_PORT)\s*=\s*(\d{2,5})/i);
|
|
34
|
+
if (m) {
|
|
35
|
+
return { port: parseInt(m[1], 10), portSource: "Environment directive" };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const execStart = Array.isArray(service.ExecStart)
|
|
40
|
+
? service.ExecStart.join(" ")
|
|
41
|
+
: String(service.ExecStart || "");
|
|
42
|
+
const execPort = execStart.match(/(?:PORT\s*=\s*|--port(?:=|\s+)|-p\s+)(\d{2,5})/i);
|
|
43
|
+
if (execPort) {
|
|
44
|
+
return { port: parseInt(execPort[1], 10), portSource: "ExecStart argument" };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const execEnvFile = execStart.match(/--env-file\s*=\s*([^\s"']+)|--env-file\s+([^\s"']+)/i);
|
|
48
|
+
if (execEnvFile) {
|
|
49
|
+
const envPath = execEnvFile[1] || execEnvFile[2];
|
|
50
|
+
const port = readPortFromEnvPath(envPath);
|
|
51
|
+
if (port) {
|
|
52
|
+
return { port, portSource: `ExecStart --env-file (${envPath})` };
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const envFiles = Array.isArray(service.EnvironmentFile)
|
|
57
|
+
? service.EnvironmentFile
|
|
58
|
+
: service.EnvironmentFile ? [service.EnvironmentFile] : [];
|
|
59
|
+
for (const rawFile of envFiles) {
|
|
60
|
+
const port = readPortFromEnvPath(rawFile);
|
|
61
|
+
if (port) {
|
|
62
|
+
return { port, portSource: `EnvironmentFile (${rawFile})` };
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const fallbackPort = detectPort(parsedConfig, workingDir);
|
|
67
|
+
if (fallbackPort) {
|
|
68
|
+
return { port: fallbackPort, portSource: "WorkingDirectory/.env" };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return { port: null, portSource: null };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function readPackageInfo(workingDir) {
|
|
75
|
+
if (!workingDir || !fs.existsSync(workingDir)) return null;
|
|
76
|
+
const pkgPath = path.join(workingDir, "package.json");
|
|
77
|
+
if (!fs.existsSync(pkgPath)) return null;
|
|
78
|
+
try {
|
|
79
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
|
80
|
+
return {
|
|
81
|
+
name: pkg.name || null,
|
|
82
|
+
version: pkg.version || null
|
|
83
|
+
};
|
|
84
|
+
} catch {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Inspects a single systemd service strictly by the supplied domain name.
|
|
91
|
+
* Performs no automatic directory/cwd detection.
|
|
92
|
+
*
|
|
93
|
+
* @param {string} domain - Domain or unit base name (e.g. "appointment.keshavsoft.com")
|
|
94
|
+
* @param {object} [options] - Optional { systemdDir }
|
|
95
|
+
* @returns {object} Domain service story
|
|
96
|
+
*/
|
|
97
|
+
export function inspectDomainService(domain, options = {}) {
|
|
98
|
+
const clean = String(domain || "").trim().toLowerCase().replace(/\.service$/i, "");
|
|
99
|
+
if (!clean) {
|
|
100
|
+
throw new Error("Boss, you need to supply a valid domain name.");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const dirsToScan = options.systemdDir
|
|
104
|
+
? [path.resolve(options.systemdDir)]
|
|
105
|
+
: DEFAULT_SYSTEMD_DIRS;
|
|
106
|
+
|
|
107
|
+
const candidateNames = clean.includes(".")
|
|
108
|
+
? [`${clean}.service`]
|
|
109
|
+
: [`${clean}.service`, `${clean}.keshavsoft.com.service`];
|
|
110
|
+
|
|
111
|
+
let matchedFile = null;
|
|
112
|
+
let matchedDir = null;
|
|
113
|
+
|
|
114
|
+
for (const dir of dirsToScan) {
|
|
115
|
+
if (!fs.existsSync(dir)) continue;
|
|
116
|
+
for (const candidate of candidateNames) {
|
|
117
|
+
const fullPath = path.join(dir, candidate);
|
|
118
|
+
if (fs.existsSync(fullPath)) {
|
|
119
|
+
matchedFile = fullPath;
|
|
120
|
+
matchedDir = dir;
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (matchedFile) break;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (!matchedFile) {
|
|
128
|
+
return {
|
|
129
|
+
found: false,
|
|
130
|
+
domain: clean,
|
|
131
|
+
candidateUnits: candidateNames,
|
|
132
|
+
searchedDirs: dirsToScan,
|
|
133
|
+
message: `No systemd service found for '${clean}' (checked: ${candidateNames.join(", ")})`
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const unitName = path.basename(matchedFile);
|
|
138
|
+
const parsed = parseServiceFile(matchedFile);
|
|
139
|
+
const unit = parsed?.Unit || {};
|
|
140
|
+
const service = parsed?.Service || {};
|
|
141
|
+
const workingDir = service.WorkingDirectory || null;
|
|
142
|
+
const workingDirectoryExists = workingDir ? fs.existsSync(workingDir) : false;
|
|
143
|
+
const { port, portSource } = resolvePortWithSource(parsed, workingDir);
|
|
144
|
+
const packageInfo = readPackageInfo(workingDir);
|
|
145
|
+
const liveStatus = getServiceLiveStatus(unitName);
|
|
146
|
+
|
|
147
|
+
return {
|
|
148
|
+
found: true,
|
|
149
|
+
domain: unitName.replace(/\.service$/i, ""),
|
|
150
|
+
unitName,
|
|
151
|
+
filePath: matchedFile,
|
|
152
|
+
systemdDir: matchedDir,
|
|
153
|
+
description: unit.Description || null,
|
|
154
|
+
after: unit.After || null,
|
|
155
|
+
user: service.User || "root",
|
|
156
|
+
type: service.Type || null,
|
|
157
|
+
restart: service.Restart || null,
|
|
158
|
+
restartSec: service.RestartSec || null,
|
|
159
|
+
workingDirectory: workingDir,
|
|
160
|
+
workingDirectoryExists,
|
|
161
|
+
execStart: service.ExecStart || null,
|
|
162
|
+
environment: service.Environment || null,
|
|
163
|
+
environmentFile: service.EnvironmentFile || null,
|
|
164
|
+
port,
|
|
165
|
+
portSource,
|
|
166
|
+
packageInfo,
|
|
167
|
+
liveStatus,
|
|
168
|
+
unitSections: {
|
|
169
|
+
Unit: unit,
|
|
170
|
+
Service: service,
|
|
171
|
+
Install: parsed?.Install || {}
|
|
172
|
+
},
|
|
173
|
+
rawContent: parsed?.raw || ""
|
|
174
|
+
};
|
|
175
|
+
}
|
package/src/v1/actions.js
DELETED
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
import { findServiceForDirectory } from "./detector.js";
|
|
2
|
-
import { getServiceLiveStatus, restartService, getServiceLogs } from "./systemctl.js";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* High-level action to inspect the service for the current or target directory.
|
|
6
|
-
*/
|
|
7
|
-
export function inspectCurrentService(targetDir = process.cwd(), options = {}) {
|
|
8
|
-
const detected = findServiceForDirectory(targetDir, options);
|
|
9
|
-
if (!detected.found) {
|
|
10
|
-
return detected;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
const liveStatus = getServiceLiveStatus(detected.unitName);
|
|
14
|
-
return {
|
|
15
|
-
...detected,
|
|
16
|
-
liveStatus
|
|
17
|
-
};
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* High-level action to restart the service associated with current or target directory.
|
|
22
|
-
*/
|
|
23
|
-
export function restartCurrentService(targetDir = process.cwd(), options = {}) {
|
|
24
|
-
const detected = findServiceForDirectory(targetDir, options);
|
|
25
|
-
if (!detected.found) {
|
|
26
|
-
return {
|
|
27
|
-
success: false,
|
|
28
|
-
error: detected.message,
|
|
29
|
-
targetDir
|
|
30
|
-
};
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
const restartResult = restartService(detected.unitName);
|
|
34
|
-
return {
|
|
35
|
-
...detected,
|
|
36
|
-
restartResult
|
|
37
|
-
};
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* High-level action to get logs of the service associated with current or target directory.
|
|
42
|
-
*/
|
|
43
|
-
export function getCurrentServiceLogs(targetDir = process.cwd(), lines = 25, options = {}) {
|
|
44
|
-
const detected = findServiceForDirectory(targetDir, options);
|
|
45
|
-
if (!detected.found) {
|
|
46
|
-
return {
|
|
47
|
-
success: false,
|
|
48
|
-
error: detected.message,
|
|
49
|
-
targetDir
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
const logsResult = getServiceLogs(detected.unitName, lines);
|
|
54
|
-
return {
|
|
55
|
-
...detected,
|
|
56
|
-
logsResult
|
|
57
|
-
};
|
|
58
|
-
}
|
package/src/v1/cli.js
DELETED
|
@@ -1,245 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
inspectCurrentService,
|
|
3
|
-
restartCurrentService,
|
|
4
|
-
getCurrentServiceLogs
|
|
5
|
-
} from "./actions.js";
|
|
6
|
-
import { findServiceForDirectory } from "./detector.js";
|
|
7
|
-
|
|
8
|
-
export function printHelp() {
|
|
9
|
-
console.log(`
|
|
10
|
-
ubuntu-service (v1) — Single service management for the current directory
|
|
11
|
-
|
|
12
|
-
Usage:
|
|
13
|
-
npx ubuntu-service [command] [options]
|
|
14
|
-
us [command] [options]
|
|
15
|
-
|
|
16
|
-
Commands:
|
|
17
|
-
(default) Inspect the systemd service running in the current directory
|
|
18
|
-
status Detailed status card for the current service
|
|
19
|
-
restart Restart only the service associated with the current directory
|
|
20
|
-
logs [-n <count>] View journalctl logs for the current service
|
|
21
|
-
name Output only the service unit name (e.g. appointment.keshavsoft.com.service)
|
|
22
|
-
port Output only the detected port (e.g. 3000)
|
|
23
|
-
|
|
24
|
-
Options:
|
|
25
|
-
--dir <path> Target a specific directory instead of process.cwd()
|
|
26
|
-
--systemd-dir <path> Custom systemd unit directory (defaults to /etc/systemd/system)
|
|
27
|
-
-n, --lines <count> Number of log lines to show (default: 25)
|
|
28
|
-
--json Output machine-readable JSON
|
|
29
|
-
-h, --help Show this help message
|
|
30
|
-
|
|
31
|
-
Aliases:
|
|
32
|
-
us Short alias for ubuntu-service
|
|
33
|
-
|
|
34
|
-
Examples:
|
|
35
|
-
# Stand in your project folder and run:
|
|
36
|
-
us
|
|
37
|
-
us restart
|
|
38
|
-
us logs -n 50
|
|
39
|
-
us name
|
|
40
|
-
`);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export function runCli(argv = process.argv.slice(2)) {
|
|
44
|
-
const isHelp = argv.includes("-h") || argv.includes("--help");
|
|
45
|
-
if (isHelp) {
|
|
46
|
-
printHelp();
|
|
47
|
-
return 0;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
const isJson = argv.includes("--json");
|
|
51
|
-
|
|
52
|
-
// Parse options
|
|
53
|
-
let targetDir = process.cwd();
|
|
54
|
-
const dirIdx = argv.indexOf("--dir");
|
|
55
|
-
if (dirIdx !== -1 && argv[dirIdx + 1]) {
|
|
56
|
-
targetDir = argv[dirIdx + 1];
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
let systemdDir = null;
|
|
60
|
-
const sysIdx = argv.indexOf("--systemd-dir");
|
|
61
|
-
if (sysIdx !== -1 && argv[sysIdx + 1]) {
|
|
62
|
-
systemdDir = argv[sysIdx + 1];
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
let logLines = 25;
|
|
66
|
-
const nIdx = argv.findIndex(a => a === "-n" || a === "--lines");
|
|
67
|
-
if (nIdx !== -1 && argv[nIdx + 1]) {
|
|
68
|
-
const parsedN = parseInt(argv[nIdx + 1], 10);
|
|
69
|
-
if (!isNaN(parsedN) && parsedN > 0) {
|
|
70
|
-
logLines = parsedN;
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
const options = { systemdDir };
|
|
75
|
-
|
|
76
|
-
// Determine subcommand
|
|
77
|
-
const positionalArgs = argv.filter((arg, i) => {
|
|
78
|
-
if (arg.startsWith("-")) return false;
|
|
79
|
-
if (i > 0 && (argv[i - 1] === "--dir" || argv[i - 1] === "--systemd-dir" || argv[i - 1] === "-n" || argv[i - 1] === "--lines")) {
|
|
80
|
-
return false;
|
|
81
|
-
}
|
|
82
|
-
return true;
|
|
83
|
-
});
|
|
84
|
-
|
|
85
|
-
const command = positionalArgs[0] || "status";
|
|
86
|
-
|
|
87
|
-
// Subcommand: name
|
|
88
|
-
if (command === "name") {
|
|
89
|
-
const detected = findServiceForDirectory(targetDir, options);
|
|
90
|
-
if (isJson) {
|
|
91
|
-
console.log(JSON.stringify(detected, null, 2));
|
|
92
|
-
} else if (detected.found) {
|
|
93
|
-
console.log(detected.unitName);
|
|
94
|
-
} else {
|
|
95
|
-
console.error(detected.message);
|
|
96
|
-
return 1;
|
|
97
|
-
}
|
|
98
|
-
return 0;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
// Subcommand: port
|
|
102
|
-
if (command === "port") {
|
|
103
|
-
const detected = findServiceForDirectory(targetDir, options);
|
|
104
|
-
if (isJson) {
|
|
105
|
-
console.log(JSON.stringify({ port: detected.port || null }, null, 2));
|
|
106
|
-
} else if (detected.found && detected.port) {
|
|
107
|
-
console.log(detected.port);
|
|
108
|
-
} else if (detected.found) {
|
|
109
|
-
console.log("No port configured or detected.");
|
|
110
|
-
} else {
|
|
111
|
-
console.error(detected.message);
|
|
112
|
-
return 1;
|
|
113
|
-
}
|
|
114
|
-
return 0;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
// Subcommand: restart
|
|
118
|
-
if (command === "restart") {
|
|
119
|
-
const res = restartCurrentService(targetDir, options);
|
|
120
|
-
if (isJson) {
|
|
121
|
-
console.log(JSON.stringify(res, null, 2));
|
|
122
|
-
return res.restartResult && res.restartResult.success ? 0 : 1;
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
if (!res.found) {
|
|
126
|
-
console.error(`\n❌ No systemd service found for directory:\n ${res.targetDir}`);
|
|
127
|
-
console.error(`\n💡 Tip: Verify that /etc/systemd/system/*.service contains WorkingDirectory=${res.targetDir}\n Or run 'npx ubuntu-services' to see all services.`);
|
|
128
|
-
return 1;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
console.log(`\n===============================================================`);
|
|
132
|
-
console.log(` 🔄 ubuntu-service restart`);
|
|
133
|
-
console.log(`===============================================================`);
|
|
134
|
-
console.log(` 📍 Directory: ${res.targetDir}`);
|
|
135
|
-
console.log(` 🎯 Service Unit: ${res.unitName}`);
|
|
136
|
-
console.log(`---------------------------------------------------------------`);
|
|
137
|
-
|
|
138
|
-
if (res.restartResult && res.restartResult.success) {
|
|
139
|
-
const st = res.restartResult.status || {};
|
|
140
|
-
const stateText = st.isActive ? "🟢 active (running)" : `🟡 ${st.activeState || "unknown"}`;
|
|
141
|
-
console.log(` ✅ Service successfully restarted!`);
|
|
142
|
-
console.log(` ⚡ Status: ${stateText}`);
|
|
143
|
-
if (st.pid) console.log(` 🆔 Main PID: ${st.pid}`);
|
|
144
|
-
if (st.memory) console.log(` 💾 Memory: ${st.memory}`);
|
|
145
|
-
if (res.port) console.log(` 🌐 Port: ${res.port}`);
|
|
146
|
-
console.log(`===============================================================\n`);
|
|
147
|
-
return 0;
|
|
148
|
-
} else {
|
|
149
|
-
console.error(` ❌ Restart failed!`);
|
|
150
|
-
if (res.restartResult && res.restartResult.error) {
|
|
151
|
-
console.error(` ⚠️ Error: ${res.restartResult.error}`);
|
|
152
|
-
}
|
|
153
|
-
if (res.restartResult && res.restartResult.hint) {
|
|
154
|
-
console.error(` 💡 Hint: ${res.restartResult.hint}`);
|
|
155
|
-
}
|
|
156
|
-
console.log(`===============================================================\n`);
|
|
157
|
-
return 1;
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
// Subcommand: logs
|
|
162
|
-
if (command === "logs" || command === "log") {
|
|
163
|
-
const res = getCurrentServiceLogs(targetDir, logLines, options);
|
|
164
|
-
if (isJson) {
|
|
165
|
-
console.log(JSON.stringify(res, null, 2));
|
|
166
|
-
return res.logsResult && res.logsResult.success ? 0 : 1;
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
if (!res.found) {
|
|
170
|
-
console.error(`\n❌ No systemd service found for directory:\n ${res.targetDir}`);
|
|
171
|
-
return 1;
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
console.log(`\n📜 Logs for ${res.unitName} (last ${logLines} lines):`);
|
|
175
|
-
console.log(`---------------------------------------------------------------`);
|
|
176
|
-
if (res.logsResult && res.logsResult.success) {
|
|
177
|
-
console.log(res.logsResult.output || "(No recent logs)");
|
|
178
|
-
} else {
|
|
179
|
-
console.error(res.logsResult?.error || "Failed to retrieve logs");
|
|
180
|
-
}
|
|
181
|
-
console.log(`---------------------------------------------------------------\n`);
|
|
182
|
-
return 0;
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
// Default / status command
|
|
186
|
-
const info = inspectCurrentService(targetDir, options);
|
|
187
|
-
|
|
188
|
-
if (isJson) {
|
|
189
|
-
console.log(JSON.stringify(info, null, 2));
|
|
190
|
-
return info.found ? 0 : 1;
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
if (!info.found) {
|
|
194
|
-
console.error(`\n===============================================================`);
|
|
195
|
-
console.error(` 🔍 ubuntu-service — No Service Match`);
|
|
196
|
-
console.error(`===============================================================`);
|
|
197
|
-
console.error(` 📍 Current Directory: ${info.targetDir}`);
|
|
198
|
-
console.error(` ❌ Status: No systemd service found for this folder.`);
|
|
199
|
-
console.error(`---------------------------------------------------------------`);
|
|
200
|
-
console.error(` 💡 Troubleshooting:`);
|
|
201
|
-
console.error(` 1. Ensure a service unit file in /etc/systemd/system/ has:`);
|
|
202
|
-
console.error(` WorkingDirectory=${info.targetDir}`);
|
|
203
|
-
console.error(` 2. Run 'npx ubuntu-services' to list all registered services.`);
|
|
204
|
-
console.error(` 3. If service uses a different path, test with:`);
|
|
205
|
-
console.error(` us --dir /path/to/folder`);
|
|
206
|
-
console.error(`===============================================================\n`);
|
|
207
|
-
return 1;
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
const live = info.liveStatus || {};
|
|
211
|
-
let statusBadge = "⚪ unknown";
|
|
212
|
-
if (live.available) {
|
|
213
|
-
if (live.isActive) {
|
|
214
|
-
statusBadge = `🟢 active (${live.subState || "running"})`;
|
|
215
|
-
} else if (live.activeState === "failed") {
|
|
216
|
-
statusBadge = `🔴 failed (${live.subState})`;
|
|
217
|
-
} else {
|
|
218
|
-
statusBadge = `🟡 ${live.activeState || "inactive"} (${live.subState || "dead"})`;
|
|
219
|
-
}
|
|
220
|
-
} else {
|
|
221
|
-
statusBadge = "⚪ unqueried (systemctl unavailable)";
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
console.log(`\n===============================================================`);
|
|
225
|
-
console.log(` 🎯 ubuntu-service — Single Service Card`);
|
|
226
|
-
console.log(`===============================================================`);
|
|
227
|
-
console.log(` 📍 Directory: ${info.targetDir}`);
|
|
228
|
-
console.log(` 🎯 Service Unit: ${info.unitName}`);
|
|
229
|
-
console.log(` ⚡ State: ${statusBadge}`);
|
|
230
|
-
if (live.pid) console.log(` 🆔 Main PID: ${live.pid}`);
|
|
231
|
-
if (live.memory) console.log(` 💾 Memory: ${live.memory}`);
|
|
232
|
-
if (info.port) console.log(` 🌐 Port: ${info.port}`);
|
|
233
|
-
console.log(` 📁 WorkingDir: ${info.workingDirectory || "-"} ${info.workingDirectoryExists ? "✅" : "❌ (missing)"}`);
|
|
234
|
-
console.log(` 🚀 ExecStart: ${info.execStart || "-"}`);
|
|
235
|
-
if (info.description) console.log(` 📝 Description: ${info.description}`);
|
|
236
|
-
console.log(` 🔍 Match Reason: ${info.matchType} (confidence: ${info.score}%)`);
|
|
237
|
-
console.log(`---------------------------------------------------------------`);
|
|
238
|
-
console.log(` 💡 Quick Actions:`);
|
|
239
|
-
console.log(` us restart Restart this single service`);
|
|
240
|
-
console.log(` us logs View recent journalctl logs`);
|
|
241
|
-
console.log(` us name Output unit name`);
|
|
242
|
-
console.log(`===============================================================\n`);
|
|
243
|
-
|
|
244
|
-
return 0;
|
|
245
|
-
}
|
package/src/v1/detector.js
DELETED
|
@@ -1,194 +0,0 @@
|
|
|
1
|
-
import fs from "node:fs";
|
|
2
|
-
import path from "node:path";
|
|
3
|
-
import { parseServiceFile, detectPort } from "./parser.js";
|
|
4
|
-
|
|
5
|
-
export const DEFAULT_SYSTEMD_DIRS = [
|
|
6
|
-
"/etc/systemd/system",
|
|
7
|
-
"/run/systemd/system",
|
|
8
|
-
"/usr/lib/systemd/system",
|
|
9
|
-
"/lib/systemd/system"
|
|
10
|
-
];
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Normalizes a directory path for reliable cross-platform comparison.
|
|
14
|
-
* Resolves symlinks if the path exists.
|
|
15
|
-
*/
|
|
16
|
-
export function normalizePath(p) {
|
|
17
|
-
if (!p) return "";
|
|
18
|
-
let resolved = path.resolve(p);
|
|
19
|
-
try {
|
|
20
|
-
if (fs.existsSync(resolved)) {
|
|
21
|
-
resolved = fs.realpathSync(resolved);
|
|
22
|
-
}
|
|
23
|
-
} catch {
|
|
24
|
-
// Fall back to resolved if realpath fails
|
|
25
|
-
}
|
|
26
|
-
// Normalize slashes to forward slashes for unified comparison
|
|
27
|
-
let normalized = resolved.replace(/\\/g, "/");
|
|
28
|
-
if (normalized.endsWith("/") && normalized.length > 1) {
|
|
29
|
-
normalized = normalized.slice(0, -1);
|
|
30
|
-
}
|
|
31
|
-
return normalized;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* Inspects a directory for package.json or git config metadata.
|
|
36
|
-
*/
|
|
37
|
-
export function inspectDirectoryMetadata(dirPath) {
|
|
38
|
-
const meta = {
|
|
39
|
-
name: null,
|
|
40
|
-
gitRemote: null
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
if (!dirPath || !fs.existsSync(dirPath)) {
|
|
44
|
-
return meta;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
// Check package.json
|
|
48
|
-
const pkgPath = path.join(dirPath, "package.json");
|
|
49
|
-
if (fs.existsSync(pkgPath)) {
|
|
50
|
-
try {
|
|
51
|
-
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
|
52
|
-
meta.name = pkg.name || null;
|
|
53
|
-
} catch {
|
|
54
|
-
// ignore malformed JSON
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// Check .git/config
|
|
59
|
-
const gitConfigPath = path.join(dirPath, ".git", "config");
|
|
60
|
-
if (fs.existsSync(gitConfigPath)) {
|
|
61
|
-
try {
|
|
62
|
-
const gitConfig = fs.readFileSync(gitConfigPath, "utf-8");
|
|
63
|
-
const m = gitConfig.match(/url\s*=\s*.*github\.com[/:]([^/\s]+\/[^\s.]+)/i);
|
|
64
|
-
if (m) {
|
|
65
|
-
meta.gitRemote = m[1];
|
|
66
|
-
}
|
|
67
|
-
} catch {
|
|
68
|
-
// ignore git config error
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
return meta;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
* Finds the single systemd service that owns or runs from the given directory.
|
|
77
|
-
* @param {string} [targetDir] - Directory to check (defaults to process.cwd())
|
|
78
|
-
* @param {object} [options] - Options ({ systemdDir })
|
|
79
|
-
* @returns {object} Result with matched service or not found status
|
|
80
|
-
*/
|
|
81
|
-
export function findServiceForDirectory(targetDir = process.cwd(), options = {}) {
|
|
82
|
-
const normTarget = normalizePath(targetDir);
|
|
83
|
-
const meta = inspectDirectoryMetadata(targetDir);
|
|
84
|
-
|
|
85
|
-
const dirsToScan = options.systemdDir
|
|
86
|
-
? [path.resolve(options.systemdDir)]
|
|
87
|
-
: DEFAULT_SYSTEMD_DIRS;
|
|
88
|
-
|
|
89
|
-
const matchedUnits = [];
|
|
90
|
-
|
|
91
|
-
for (const scanDir of dirsToScan) {
|
|
92
|
-
if (!fs.existsSync(scanDir)) continue;
|
|
93
|
-
|
|
94
|
-
let files = [];
|
|
95
|
-
try {
|
|
96
|
-
files = fs.readdirSync(scanDir).filter(f => f.endsWith(".service"));
|
|
97
|
-
} catch {
|
|
98
|
-
continue;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
for (const file of files) {
|
|
102
|
-
const filePath = path.join(scanDir, file);
|
|
103
|
-
const parsed = parseServiceFile(filePath);
|
|
104
|
-
if (!parsed) continue;
|
|
105
|
-
|
|
106
|
-
const serviceSection = parsed.Service || {};
|
|
107
|
-
const unitSection = parsed.Unit || {};
|
|
108
|
-
const workingDir = serviceSection.WorkingDirectory;
|
|
109
|
-
const execStart = serviceSection.ExecStart || "";
|
|
110
|
-
|
|
111
|
-
let matchType = null;
|
|
112
|
-
let score = 0;
|
|
113
|
-
|
|
114
|
-
if (workingDir) {
|
|
115
|
-
const normWorking = normalizePath(workingDir);
|
|
116
|
-
if (normWorking === normTarget) {
|
|
117
|
-
matchType = "exact_working_directory";
|
|
118
|
-
score = 100;
|
|
119
|
-
} else if (normTarget.startsWith(normWorking + "/") || normWorking.startsWith(normTarget + "/")) {
|
|
120
|
-
matchType = "subpath_working_directory";
|
|
121
|
-
score = 80;
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
if (!matchType && execStart) {
|
|
126
|
-
const normExec = execStart.replace(/\\/g, "/");
|
|
127
|
-
if (normExec.includes(normTarget)) {
|
|
128
|
-
matchType = "exec_start_path";
|
|
129
|
-
score = 70;
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
// Fallback: match by package name or directory basename against service name
|
|
134
|
-
if (!matchType) {
|
|
135
|
-
const baseName = path.basename(normTarget).toLowerCase();
|
|
136
|
-
const unitBase = file.replace(/\.service$/, "").toLowerCase();
|
|
137
|
-
|
|
138
|
-
if (meta.name && unitBase.includes(meta.name.toLowerCase())) {
|
|
139
|
-
matchType = "package_name_match";
|
|
140
|
-
score = 50;
|
|
141
|
-
} else if (unitBase.includes(baseName) || baseName.includes(unitBase)) {
|
|
142
|
-
matchType = "directory_name_match";
|
|
143
|
-
score = 40;
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
if (matchType) {
|
|
148
|
-
const port = detectPort(parsed, workingDir);
|
|
149
|
-
matchedUnits.push({
|
|
150
|
-
unitName: file,
|
|
151
|
-
filePath,
|
|
152
|
-
systemdDir: scanDir,
|
|
153
|
-
matchType,
|
|
154
|
-
score,
|
|
155
|
-
workingDirectory: workingDir || null,
|
|
156
|
-
workingDirectoryExists: workingDir ? fs.existsSync(workingDir) : false,
|
|
157
|
-
execStart,
|
|
158
|
-
description: unitSection.Description || null,
|
|
159
|
-
port,
|
|
160
|
-
serviceConfig: parsed
|
|
161
|
-
});
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
if (matchedUnits.length === 0) {
|
|
167
|
-
return {
|
|
168
|
-
found: false,
|
|
169
|
-
targetDir: normTarget,
|
|
170
|
-
message: `No systemd service unit found matching directory '${normTarget}'`
|
|
171
|
-
};
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
// Sort by best score
|
|
175
|
-
matchedUnits.sort((a, b) => b.score - a.score);
|
|
176
|
-
const primary = matchedUnits[0];
|
|
177
|
-
|
|
178
|
-
return {
|
|
179
|
-
found: true,
|
|
180
|
-
targetDir: normTarget,
|
|
181
|
-
unitName: primary.unitName,
|
|
182
|
-
filePath: primary.filePath,
|
|
183
|
-
systemdDir: primary.systemdDir,
|
|
184
|
-
matchType: primary.matchType,
|
|
185
|
-
score: primary.score,
|
|
186
|
-
workingDirectory: primary.workingDirectory,
|
|
187
|
-
workingDirectoryExists: primary.workingDirectoryExists,
|
|
188
|
-
execStart: primary.execStart,
|
|
189
|
-
description: primary.description,
|
|
190
|
-
port: primary.port,
|
|
191
|
-
allMatches: matchedUnits.length > 1 ? matchedUnits : undefined,
|
|
192
|
-
serviceConfig: primary.serviceConfig
|
|
193
|
-
};
|
|
194
|
-
}
|