ubuntu-service 0.0.0-stage β†’ 1.0.0

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 ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 KeshavSoft
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,117 @@
1
- # Temporary Holding Version
1
+ # ubuntu-service
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://img.shields.io/badge/npm-v1.0.0-blue.svg)](https://www.npmjs.com/package/ubuntu-service)
4
+ [![License: ISC](https://img.shields.io/badge/License-ISC-green.svg)](https://opensource.org/licenses/ISC)
5
+ [![Organization](https://img.shields.io/badge/org-KeshavSoft-purple.svg)](https://github.com/keshavsoft)
6
+ [![Node](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen.svg)](https://nodejs.org)
7
+ [![Zero Dependencies](https://img.shields.io/badge/dependencies-0-success.svg)](https://github.com/keshavsoft/ubuntu-service)
8
+
9
+ > **Context-aware single service manager for Ubuntu VPS.**
10
+ > Automatically identifies the systemd service associated with your current working directory (`process.cwd()`), inspects its status, restarts it, and displays its logs. Zero memory neededβ€”run right after `git pull`.
11
+
12
+ ---
13
+
14
+ ## 🎯 The Philosophy: Singular vs. Plural
15
+
16
+ | Repository | Focus | Scope | Question Answered |
17
+ | :--- | :--- | :--- | :--- |
18
+ | **`ubuntu-services`** *(Plural)* | Fleet / Inventory | All services on the OS | *"What is everything running on my Ubuntu VPS? Are there broken folders?"* |
19
+ | **`ubuntu-service`** *(Singular)* | Atomic / Current App | Single service for current directory | *"What service runs THIS folder, and let me restart only this service right now."* |
20
+
21
+ ---
22
+
23
+ ## πŸ’‘ The Everyday VPS Problem
24
+
25
+ When deploying code on an Ubuntu server:
26
+ ```bash
27
+ root@server6358:~/KeshavSoft/appointment-notifier# git pull
28
+ Updating cced23f..34bc3e5
29
+ Fast-forward
30
+ ...
31
+ ```
32
+
33
+ Now you need to restart the application. But:
34
+ * *What is the exact systemd unit name for this directory?*
35
+ * Is it `appointment.service`? `appointment-notifier.service`? `appointment.keshavsoft.com.service`?
36
+ * Instead of grepping `/etc/systemd/system/` or rebooting the server:
37
+
38
+ Simply run:
39
+ ```bash
40
+ us restart
41
+ ```
42
+
43
+ ---
44
+
45
+ ## ⚑ Quick Start
46
+
47
+ Run directly with zero installation via `npx`:
48
+
49
+ ```bash
50
+ # Stand in any project directory on your Ubuntu VPS
51
+ cd /root/KeshavSoft/appointment-notifier
52
+
53
+ # 1. Inspect the service running this directory
54
+ npx ubuntu-service
55
+ # Or with short alias:
56
+ us
57
+
58
+ # 2. Restart ONLY this service
59
+ us restart
60
+
61
+ # 3. View live systemd logs
62
+ us logs -n 50
63
+
64
+ # 4. Output only the unit name (e.g. for scripts or CI)
65
+ us name
66
+ ```
67
+
68
+ ---
69
+
70
+ ## πŸ“– CLI Commands
71
+
72
+ | Command | Description |
73
+ | :--- | :--- |
74
+ | `us` / `npx ubuntu-service` | Shows service card: unit name, state, PID, memory, port, working directory |
75
+ | `us restart` | Restarts only the service attached to the current directory and verifies status |
76
+ | `us status` | Detailed status inspection for the current service |
77
+ | `us logs [-n <count>]` | Fetches live `journalctl` logs for this specific service |
78
+ | `us name` | Prints only the unit name (e.g. `appointment.keshavsoft.com.service`) |
79
+ | `us port` | Prints only the detected port (e.g. `3000`) |
80
+
81
+ ### Flags & Options
82
+
83
+ * `--dir <path>`: Target a specific folder instead of `process.cwd()`
84
+ * `--systemd-dir <path>`: Custom systemd directory (useful for testing)
85
+ * `-n, --lines <count>`: Number of log lines to retrieve (default: 25)
86
+ * `--json`: Output machine-readable JSON
87
+ * `-h, --help`: Display help screen
88
+
89
+ ---
90
+
91
+ ## πŸ—οΈ Architecture
92
+
93
+ ```text
94
+ ubuntu-service/
95
+ β”œβ”€β”€ bin/
96
+ β”‚ └── index.js # Executable entrypoint (`ubuntu-service`, `us`)
97
+ β”œβ”€β”€ src/
98
+ β”‚ β”œβ”€β”€ index.js # Orchestrator (delegates to latest v1)
99
+ β”‚ β”œβ”€β”€ cli.js # CLI Orchestrator
100
+ β”‚ └── v1/
101
+ β”‚ β”œβ”€β”€ index.js # Public API exports
102
+ β”‚ β”œβ”€β”€ detector.js # Context detection (CWD to systemd unit mapping)
103
+ β”‚ β”œβ”€β”€ parser.js # Systemd .service INI & port parser
104
+ β”‚ β”œβ”€β”€ systemctl.js # Native systemctl & journalctl execution
105
+ β”‚ β”œβ”€β”€ actions.js # Business actions (inspect, restart, logs)
106
+ β”‚ └── cli.js # Terminal UI & formatting
107
+ β”œβ”€β”€ test/ # Automated test suite (node --test)
108
+ β”œβ”€β”€ docs/ # GitHub Pages portal & live terminal simulator
109
+ β”œβ”€β”€ package.json # Whitelisted files: ["bin", "src"], zero dependencies
110
+ └── LICENSE # ISC License
111
+ ```
112
+
113
+ ---
114
+
115
+ ## πŸ›‘οΈ License
116
+
117
+ ISC License β€” [KeshavSoft](https://github.com/keshavsoft)
package/bin/index.js ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { runCli } from "../src/cli.js";
4
+
5
+ const exitCode = runCli(process.argv.slice(2));
6
+ if (typeof exitCode === "number") {
7
+ process.exitCode = exitCode;
8
+ }
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "ubuntu-service",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Context-aware CLI to identify, inspect, restart, and view logs of the single systemd service running in the current directory on an Ubuntu VPS.",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "exports": {
8
+ ".": "./src/index.js",
9
+ "./v1": "./src/v1/index.js"
10
+ },
11
+ "bin": {
12
+ "ubuntu-service": "bin/index.js",
13
+ "us": "bin/index.js"
14
+ },
15
+ "files": [
16
+ "bin",
17
+ "src"
18
+ ],
19
+ "scripts": {
20
+ "start": "node bin/index.js",
21
+ "cli": "node bin/index.js",
22
+ "test": "node --test"
23
+ },
24
+ "keywords": [
25
+ "ubuntu",
26
+ "systemd",
27
+ "service",
28
+ "vps",
29
+ "process",
30
+ "restart",
31
+ "cwd",
32
+ "caddy"
33
+ ],
34
+ "author": "KeshavSoft",
35
+ "license": "ISC",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/keshavsoft/ubuntu-service.git"
39
+ },
40
+ "bugs": {
41
+ "url": "https://github.com/keshavsoft/ubuntu-service/issues"
42
+ },
43
+ "homepage": "https://keshavsoft.github.io/ubuntu-service/",
44
+ "engines": {
45
+ "node": ">=18.0.0"
46
+ }
47
+ }
package/src/cli.js ADDED
@@ -0,0 +1,2 @@
1
+ // Orchestrator: delegates CLI execution directly to latest version (v1)
2
+ export { runCli, printHelp } from "./v1/cli.js";
package/src/index.js ADDED
@@ -0,0 +1,3 @@
1
+ // Orchestrator: delegates directly to latest version (v1)
2
+ export * from "./v1/index.js";
3
+ export { default } from "./v1/index.js";
@@ -0,0 +1,58 @@
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 ADDED
@@ -0,0 +1,245 @@
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
+ }
@@ -0,0 +1,194 @@
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
+ }
@@ -0,0 +1,55 @@
1
+ import { parseServiceFile, detectPort } from "./parser.js";
2
+ import {
3
+ findServiceForDirectory,
4
+ normalizePath,
5
+ inspectDirectoryMetadata,
6
+ DEFAULT_SYSTEMD_DIRS
7
+ } from "./detector.js";
8
+ import {
9
+ isSystemctlAvailable,
10
+ getServiceLiveStatus,
11
+ restartService,
12
+ getServiceLogs
13
+ } from "./systemctl.js";
14
+ import {
15
+ inspectCurrentService,
16
+ restartCurrentService,
17
+ getCurrentServiceLogs
18
+ } from "./actions.js";
19
+ import { runCli, printHelp } from "./cli.js";
20
+
21
+ export {
22
+ parseServiceFile,
23
+ detectPort,
24
+ findServiceForDirectory,
25
+ normalizePath,
26
+ inspectDirectoryMetadata,
27
+ DEFAULT_SYSTEMD_DIRS,
28
+ isSystemctlAvailable,
29
+ getServiceLiveStatus,
30
+ restartService,
31
+ getServiceLogs,
32
+ inspectCurrentService,
33
+ restartCurrentService,
34
+ getCurrentServiceLogs,
35
+ runCli,
36
+ printHelp
37
+ };
38
+
39
+ export default {
40
+ parseServiceFile,
41
+ detectPort,
42
+ findServiceForDirectory,
43
+ normalizePath,
44
+ inspectDirectoryMetadata,
45
+ DEFAULT_SYSTEMD_DIRS,
46
+ isSystemctlAvailable,
47
+ getServiceLiveStatus,
48
+ restartService,
49
+ getServiceLogs,
50
+ inspectCurrentService,
51
+ restartCurrentService,
52
+ getCurrentServiceLogs,
53
+ runCli,
54
+ printHelp
55
+ };
@@ -0,0 +1,113 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ /**
5
+ * Parses a systemd .service INI file into structured sections.
6
+ * @param {string} filePath - Absolute path to .service file
7
+ * @returns {object} Parsed service configuration
8
+ */
9
+ export function parseServiceFile(filePath) {
10
+ if (!fs.existsSync(filePath)) {
11
+ return null;
12
+ }
13
+
14
+ const content = fs.readFileSync(filePath, "utf-8");
15
+ const lines = content.split(/\r?\n/);
16
+ const result = {
17
+ Unit: {},
18
+ Service: {},
19
+ Install: {},
20
+ raw: content
21
+ };
22
+
23
+ let currentSection = null;
24
+
25
+ for (const rawLine of lines) {
26
+ const line = rawLine.trim();
27
+ if (!line || line.startsWith("#") || line.startsWith(";")) {
28
+ continue;
29
+ }
30
+
31
+ const sectionMatch = line.match(/^\[(.*?)\]$/);
32
+ if (sectionMatch) {
33
+ currentSection = sectionMatch[1];
34
+ if (!result[currentSection]) {
35
+ result[currentSection] = {};
36
+ }
37
+ continue;
38
+ }
39
+
40
+ const eqIdx = line.indexOf("=");
41
+ if (eqIdx !== -1 && currentSection) {
42
+ const key = line.slice(0, eqIdx).trim();
43
+ let value = line.slice(eqIdx + 1).trim();
44
+
45
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
46
+ value = value.slice(1, -1);
47
+ }
48
+
49
+ if (result[currentSection][key] !== undefined) {
50
+ if (Array.isArray(result[currentSection][key])) {
51
+ result[currentSection][key].push(value);
52
+ } else {
53
+ result[currentSection][key] = [result[currentSection][key], value];
54
+ }
55
+ } else {
56
+ result[currentSection][key] = value;
57
+ }
58
+ }
59
+ }
60
+
61
+ return result;
62
+ }
63
+
64
+ /**
65
+ * Extracts port numbers from Environment strings, ExecStart args, or .env files.
66
+ * @param {object} parsedConfig - Output from parseServiceFile
67
+ * @param {string} [workingDir] - Service working directory
68
+ * @returns {number|null} Detected port or null
69
+ */
70
+ export function detectPort(parsedConfig, workingDir) {
71
+ if (!parsedConfig) return null;
72
+ const service = parsedConfig.Service || {};
73
+
74
+ // 1. Check Environment key(s)
75
+ const envs = service.Environment;
76
+ if (envs) {
77
+ const envList = Array.isArray(envs) ? envs : [envs];
78
+ for (const e of envList) {
79
+ const portMatch = e.match(/(?:PORT|LISTEN_PORT|APP_PORT)\s*=\s*(\d{2,5})/i);
80
+ if (portMatch) {
81
+ return parseInt(portMatch[1], 10);
82
+ }
83
+ }
84
+ }
85
+
86
+ // 2. Check ExecStart for --port 3000, -p 3000, or port number
87
+ const execStart = service.ExecStart;
88
+ if (execStart) {
89
+ const execMatch = execStart.match(/(?:--port|-p)\s+([0-9]{2,5})/i);
90
+ if (execMatch) {
91
+ return parseInt(execMatch[1], 10);
92
+ }
93
+ }
94
+
95
+ // 3. Check .env file in WorkingDirectory if it exists
96
+ const dir = workingDir || service.WorkingDirectory;
97
+ if (dir && fs.existsSync(dir)) {
98
+ const envFilePath = path.join(dir, ".env");
99
+ if (fs.existsSync(envFilePath)) {
100
+ try {
101
+ const envContent = fs.readFileSync(envFilePath, "utf-8");
102
+ const m = envContent.match(/(?:PORT|APP_PORT|SERVER_PORT)\s*=\s*(\d{2,5})/i);
103
+ if (m) {
104
+ return parseInt(m[1], 10);
105
+ }
106
+ } catch {
107
+ // ignore unreadable .env
108
+ }
109
+ }
110
+ }
111
+
112
+ return null;
113
+ }
@@ -0,0 +1,147 @@
1
+ import { execSync } from "node:child_process";
2
+
3
+ /**
4
+ * Checks if systemctl command is available in the environment.
5
+ */
6
+ export function isSystemctlAvailable() {
7
+ try {
8
+ execSync("which systemctl", { stdio: "pipe" });
9
+ return true;
10
+ } catch {
11
+ return false;
12
+ }
13
+ }
14
+
15
+ /**
16
+ * Queries systemctl for the live status of a service.
17
+ * @param {string} unitName - Name of the service unit (e.g. appointment.keshavsoft.com.service)
18
+ * @returns {object} Status details
19
+ */
20
+ export function getServiceLiveStatus(unitName) {
21
+ if (!isSystemctlAvailable()) {
22
+ return {
23
+ available: false,
24
+ activeState: "unknown",
25
+ subState: "unknown",
26
+ pid: null,
27
+ memory: null,
28
+ uptime: null,
29
+ raw: "systemctl not available on this platform"
30
+ };
31
+ }
32
+
33
+ try {
34
+ const showOutput = execSync(
35
+ `systemctl show ${unitName} --property=ActiveState,SubState,MainPID,ExecMainStartTimestamp,MemoryCurrent`,
36
+ { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }
37
+ );
38
+
39
+ const props = {};
40
+ for (const line of showOutput.split(/\r?\n/)) {
41
+ const eq = line.indexOf("=");
42
+ if (eq !== -1) {
43
+ props[line.slice(0, eq).trim()] = line.slice(eq + 1).trim();
44
+ }
45
+ }
46
+
47
+ const activeState = props.ActiveState || "unknown";
48
+ const subState = props.SubState || "unknown";
49
+ const mainPid = props.MainPID ? parseInt(props.MainPID, 10) : 0;
50
+ const startTime = props.ExecMainStartTimestamp || null;
51
+
52
+ let memoryFormatted = null;
53
+ if (props.MemoryCurrent && props.MemoryCurrent !== "[not set]") {
54
+ const bytes = parseInt(props.MemoryCurrent, 10);
55
+ if (!isNaN(bytes) && bytes > 0) {
56
+ memoryFormatted = (bytes / (1024 * 1024)).toFixed(1) + " MB";
57
+ }
58
+ }
59
+
60
+ return {
61
+ available: true,
62
+ activeState,
63
+ subState,
64
+ isActive: activeState === "active",
65
+ pid: mainPid > 0 ? mainPid : null,
66
+ memory: memoryFormatted,
67
+ startTime,
68
+ raw: showOutput
69
+ };
70
+ } catch (err) {
71
+ return {
72
+ available: true,
73
+ activeState: "failed_to_query",
74
+ subState: "error",
75
+ isActive: false,
76
+ pid: null,
77
+ memory: null,
78
+ error: err.message
79
+ };
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Restarts a systemd service unit via systemctl restart.
85
+ * @param {string} unitName - Service unit name
86
+ * @returns {object} Execution result
87
+ */
88
+ export function restartService(unitName) {
89
+ if (!isSystemctlAvailable()) {
90
+ return {
91
+ success: false,
92
+ error: "systemctl is not available in this environment (must run on Ubuntu Linux with systemd)"
93
+ };
94
+ }
95
+
96
+ try {
97
+ execSync(`systemctl restart ${unitName}`, {
98
+ encoding: "utf-8",
99
+ stdio: ["pipe", "pipe", "pipe"]
100
+ });
101
+ const freshStatus = getServiceLiveStatus(unitName);
102
+ return {
103
+ success: true,
104
+ unitName,
105
+ status: freshStatus
106
+ };
107
+ } catch (err) {
108
+ const msg = err.stderr ? err.stderr.toString() : err.message;
109
+ let hint = null;
110
+ if (msg.includes("Access denied") || msg.includes("interactive authentication")) {
111
+ hint = "Permission denied: try running with sudo (e.g., sudo npx ubuntu-service restart)";
112
+ }
113
+ return {
114
+ success: false,
115
+ unitName,
116
+ error: msg.trim(),
117
+ hint
118
+ };
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Fetches recent systemd journal logs for a service.
124
+ * @param {string} unitName - Service unit name
125
+ * @param {number} [lines=25] - Number of lines to retrieve
126
+ * @returns {object} Logs result
127
+ */
128
+ export function getServiceLogs(unitName, lines = 25) {
129
+ try {
130
+ const output = execSync(`journalctl -u ${unitName} -n ${lines} --no-pager`, {
131
+ encoding: "utf-8",
132
+ stdio: ["pipe", "pipe", "pipe"]
133
+ });
134
+ return {
135
+ success: true,
136
+ unitName,
137
+ lines,
138
+ output: output.trim()
139
+ };
140
+ } catch (err) {
141
+ return {
142
+ success: false,
143
+ unitName,
144
+ error: err.stderr ? err.stderr.toString().trim() : err.message
145
+ };
146
+ }
147
+ }