-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
256 lines (238 loc) · 8.61 KB
/
client.js
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
const socketIOClient = require("socket.io-client");
const os = require("os");
// const shell = require("shelljs");
const { findYmlFiles } = require("./index.js");
const { Act } = require("./kie-act-js/build/src/index.js");
const { v4: uuidv4 } = require("uuid");
const fs = require("fs");
const path = require("path");
const yaml = require("yaml");
const act = new Act();
const pidFilePath = path.join(__dirname, "pid.json");
function startClient() {
// const socket = socketIOClient("https://services.onetab.ai/");
// const socket = socketIOClient("http://localhost:3008/");
// const socket = socketIOClient("https://stg-services.onetab.ai/");
// const dockerCommandQueue = [];
// let isExecutingDockerCommand = false;
const socket = socketIOClient("https://stg-services.onetab.ai/", {
query: {
repoFullname: extractRepoFullNameFromYaml(),
},
maxHttpBufferSize: 10 * 1024 * 1024,
});
async function executeDockerCommands(uuid) {
try {
// const platform = os.platform();
// const dockerCommand =
// platform === "win32"
// ? "start Docker.exe"
// : platform === "darwin"
// ? "open -a Docker"
// : "docker";
await datafetch(uuid);
// await new Promise((resolve, reject) => {
// // shell.exec(dockerCommand, { async: true }, (code, stdout, stderr) => {
// // if (code === 0) {
// // console.log("Docker command executed successfully");
// datafetch(uuid).then(resolve).catch(reject);
// // } else {
// // console.error("Error executing Docker command:", stderr);
// // reject(new Error(stderr));
// // }
// // });
// });
// eslint-disable-next-line no-unused-vars
} catch (error) {
console.error("A Pipeline has been Terminated");
}
}
socket.on("sendDataToPackage", async(payload) => {
console.log(`Client: Received payload from backend: ${payload}`);
const jsonPayload = JSON.stringify(payload.gitPayload);
console.log(`Client: Received json payload from backend: ${jsonPayload}`);
if (payload) {
const fileContent = fs.existsSync(pidFilePath)
? fs.readFileSync(pidFilePath, "utf-8")
: "[]";
const currentDir = process.cwd();
const lastWord = currentDir.substring(currentDir.lastIndexOf('/') + 1);
const filecheck= JSON.parse(fileContent);
const ymlFiles = findYmlFiles(jsonPayload);
// console.log(ymlFiles, '-----------------------------------------------------------------');
if(filecheck.find(project => project.pathKey === currentDir && project.runStatus === true)|| filecheck.every(project => project.runStatus === false))
{if (ymlFiles?.length) {
filecheck.forEach(project => {
if (project.pathKey === currentDir) {
project.runStatus = true;
}
});
fs.writeFileSync(pidFilePath, JSON.stringify(filecheck, null, 2), 'utf-8');
executeDockerCommands(payload.uuid);
} else {
console.log(
"sorry we can't push an event because either you stopped your application or branch mismatch",
);
}
}
else {
filecheck.forEach(project => {
if (project.projectName === lastWord) {
project.Queue = true;
}
});
const data = await act.list();
const queuedLogsData = {
jsonPayload,
conclusion: "queued",
workflowName: data[1]?.workflowName,
};
socket.emit("queuedLogsData", queuedLogsData);
const indpid=filecheck.findIndex(project => project.projectName === lastWord)
fs.writeFileSync(pidFilePath, JSON.stringify(filecheck, null, 2), 'utf-8');
const intervalId = setInterval(() => {
const fileContents = fs.existsSync(pidFilePath)
? fs.readFileSync(pidFilePath, "utf-8")
: "[]";
const filechecks= JSON.parse(fileContents);
if (filechecks.every(project => project.runStatus === false) && filechecks.slice(0, indpid).every(project => project.Queue === false) ) {
clearInterval(intervalId);
filechecks.forEach(project => {
if (project.projectName === lastWord) {
project.Queue = false;
}
});
fs.writeFileSync(pidFilePath, JSON.stringify(filechecks, null, 2), 'utf-8');
if (ymlFiles?.length) {
filechecks.forEach(project => {
if (project.projectName === lastWord) {
project.runStatus = true;
}
});
fs.writeFileSync(pidFilePath, JSON.stringify(filechecks, null, 2), 'utf-8');
executeDockerCommands(payload.uuid);
} else {
console.log(
"sorry we can't push an event because either you stopped your application or branch mismatch",
);
}
}
}, 1000);
}
}
});
const workStep = async (uuid) => {
try {
const currentDir = process.cwd();
const ymlFiles = [];
function traverseDir(currentDir) {
const files = fs.readdirSync(currentDir);
for (const file of files) {
const filePath = path.join(currentDir, file);
if (fs.statSync(filePath).isDirectory()) {
if (
path.basename(filePath) !== "node_modules" &&
path.basename(filePath) !== "ios" &&
path.basename(filePath) !== "android"
) {
traverseDir(filePath);
}
} else if (file.endsWith("onetab-pipeline.yml")) {
ymlFiles.push(filePath);
}
}
}
traverseDir(currentDir);
console.log("YML files:", ymlFiles[0]);
const fileContents = fs.readFileSync(ymlFiles[0], "utf8");
const yamlObject = yaml.parse(fileContents);
if (yamlObject) {
const firstJobInWorkflow = yamlObject.jobs;
const data = firstJobInWorkflow[Object.keys(firstJobInWorkflow)].steps;
const steps = [];
data.forEach(function (obj, index) {
const res = obj?.name ?? obj?.uses ?? obj?.run;
steps.push({ step: res.trim(), uuid, index: index + 1 });
});
console.log(steps);
steps.length > 0 && socket.emit("steps", steps);
} else {
console.error(
'Invalid YAML file format. Ensure it contains "workflows" property.',
);
}
} catch (error) {
console.log(error);
}
};
const datafetch = async (uuid) => {
let uniqueId = uuid;
if (uuid === null) {
uniqueId = uuidv4();
}
const data = await act.list();
console.log("workflow list-->", data);
await workStep(uniqueId);
const currentDir = process.cwd();
const homedir = os.homedir();
const relativePath = path.relative(homedir, currentDir);
const result = await act
.setEnv("relativePath", relativePath)
.setEnv("workDir", currentDir)
.runEvent("push", { verbose: true, uuid: uniqueId });
for (let i = 0; i < result.result.length; i++) {
result.result[i].output = null;
}
const fileContent = fs.existsSync(pidFilePath)
? fs.readFileSync(pidFilePath, "utf-8")
: "[]";
const lastWord = currentDir.substring(currentDir.lastIndexOf('/') + 1);
const filecheck= JSON.parse(fileContent);
filecheck.forEach(project => {
if (project.projectName === lastWord) {
project.runStatus = false;
}
});
fs.writeFileSync(pidFilePath, JSON.stringify(filecheck, null, 2), 'utf-8');
socket.emit("workflowResult", result);
};
}
function extractRepoFullNameFromYaml(searchPath = process.cwd()) {
try {
let yamlFilePath = null;
function traverseDir(currentDir) {
const files = fs.readdirSync(currentDir);
for (const file of files) {
const filePath = path.join(currentDir, file);
if (fs.statSync(filePath).isDirectory()) {
if (
path.basename(filePath) !== "node_modules" &&
path.basename(filePath) !== "ios" &&
path.basename(filePath) !== "android"
) {
traverseDir(filePath);
}
} else if (file.endsWith("onetab-pipeline.yml")) {
yamlFilePath = filePath;
break; // Stop traversal once the file is found
}
}
}
traverseDir(searchPath);
if (!yamlFilePath) {
console.log("Failed to locate onetab-pipeline yml file.");
return null;
}
const fileContent = fs.readFileSync(yamlFilePath, "utf8");
const yamlData = yaml.parse(fileContent);
const repoFullName = yamlData?.repoFullName;
return repoFullName;
} catch (error) {
console.error(
"Error extracting repository full name from onetab-pipeline.yml:",
error.message,
);
return null;
}
}
startClient();