-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
155 lines (136 loc) · 4.36 KB
/
index.js
File metadata and controls
155 lines (136 loc) · 4.36 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
const fs = require("fs").promises;
const { spawn } = require("child_process");
const path = require("path");
class JSONScript {
constructor(jsonScript) {
this.jsonScript = jsonScript;
this.executionDescription = [];
this.executionPlan = [];
this.results = [];
this.error = null;
this.initialCwd = process.cwd();
this.cwd = this.initialCwd;
this.#validateJSONScript();
this.#createExecutionPlan();
}
async execute() {
for (const [index, step] of this.jsonScript.entries()) {
const success = await this.#executeSteps(step, index);
if (!success) {
return { results: this.results, error: this.error };
}
}
return { results: this.results, error: this.error };
}
#validateJSONScript() {
if (!Array.isArray(this.jsonScript)) {
throw new Error("JSONScript must be an array of objects.");
}
this.jsonScript.forEach((step, index) => {
if (typeof step !== "object" || step === null) {
throw new Error(`Step ${index + 1} is not a valid object.`);
}
});
}
#createExecutionPlan() {
this.jsonScript.forEach((step) => {
if (step.comment) {
this.executionDescription.push(`${step.comment}`);
}
if (step.cmd) {
this.executionPlan.push(`${step.cmd}`);
}
if (step.file) {
this.executionPlan.push(`Create file: ${step.file.name}`);
}
});
}
async #executeCommand(cmd) {
const cmdParts = this.#getCommandParts(cmd);
const options = this.#getCommandOptions(false);
const process = spawn(cmdParts.mainCmd, cmdParts.args, options);
return this.#handleProcess(process);
}
async #executeBackgroundCommand(cmd) {
const cmdParts = this.#getCommandParts(cmd.slice(0, -1).trim());
const options = this.#getCommandOptions(true);
const childProcess = spawn(cmdParts.mainCmd, cmdParts.args, options);
childProcess.unref();
console.log(`Backgrounded task: ${cmd} with PID: ${childProcess.pid}`); // Inform the user about background task
return `Backgrounded task: ${cmd}`;
}
#getCommandParts(cmd) {
const cmdParts = cmd.trim().split(" ");
return {
mainCmd: cmdParts.shift(),
args: cmdParts,
};
}
#getCommandOptions(isBackground) {
return {
cwd: this.cwd,
shell: true,
detached: isBackground,
stdio: isBackground ? "ignore" : ["pipe", "pipe", "pipe"], // Use 'pipe' to capture streams for foreground tasks
};
}
#handleProcess(childProcess) {
return new Promise((resolve, reject) => {
process.stdin.pipe(childProcess.stdin);
childProcess.stdout.pipe(process.stdout);
childProcess.stderr.pipe(process.stderr);
childProcess.on("close", (code) => {
if (code !== 0) {
resolve(`Command failed with exit code ${code}`);
} else {
resolve(`Command succeeded with exit code ${code}`);
}
});
});
}
async #changeDirectory(command) {
const newDir = command.slice(3).trim();
const newCwd = path.resolve(this.cwd, newDir);
if (newCwd !== this.cwd) {
this.cwd = newCwd;
return `Changed directory to ${this.cwd}`;
}
}
async #createFile(step) {
const filePath = path.resolve(this.initialCwd, step.file.name);
await fs.writeFile(filePath, step.file.data);
return `File ${filePath} created successfully.`;
}
async #processCommand(command, index) {
if (command.startsWith("cd ")) {
const result = await this.#changeDirectory(command);
if (result) {
this.results.push({ step: index + 1, type: "cmd", result });
}
} else {
const isBackground = command.endsWith("&");
const result = isBackground
? await this.#executeBackgroundCommand(command)
: await this.#executeCommand(command);
this.results.push({ step: index + 1, type: "cmd", result });
}
}
async #executeSteps(step, index) {
try {
if (step.cmd) {
const commands = step.cmd.split("&&").map((cmd) => cmd.trim());
for (let command of commands) {
await this.#processCommand(command, index);
}
} else if (step.file) {
const result = await this.#createFile(step);
this.results.push({ step: index + 1, type: "file", result });
}
} catch (error) {
this.error = error;
return false;
}
return true;
}
}
module.exports = JSONScript;