-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcancelOldPipeline.js
More file actions
60 lines (47 loc) · 2.13 KB
/
cancelOldPipeline.js
File metadata and controls
60 lines (47 loc) · 2.13 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
const { fetchAllPipelines, getPipelineVariables, cancelPipeline } = require("./utility/service");
const hostName = process.env.CI_SERVER_HOST;
const projectId = process.env.CI_PROJECT_ID;
const pipelineName = process.env.PIPELINE_NAME;
const sourceBranch = process.env.SOURCE_BRANCH;
const currentPipelineId = process.env.CI_PIPELINE_ID;
const currentPipelineCreatedAt = process.env.CI_PIPELINE_CREATED_AT;
async function cancelOldPipeline() {
try {
console.log(`Using pipeline name: ${pipelineName}`);
console.log(`Current branch: ${sourceBranch}`);
// Fetch running pipelines
const pipelines = await fetchAllPipelines(hostName, projectId, pipelineName);
if (!pipelines || pipelines.length === 0) {
console.log("No running pipelines found. Nothing to cancel.");
return;
}
for (const pipeline of pipelines) {
const pipelineId = pipeline.id;
// Skip current pipeline itself
if (pipelineId === Number(currentPipelineId)) {
console.log(`Skipping current pipeline ${pipelineId}`);
continue;
}
// Convert current pipeline creation time to epoch milliseconds
const currentEpoch = new Date(currentPipelineCreatedAt).getTime();
const createdEpoch = new Date(pipeline.created_at).getTime();
// Skip newer pipelines
if (createdEpoch > currentEpoch) {
console.log(`Skipping newer pipeline ${pipelineId} created at ${pipeline.created_at}`);
continue;
}
// Get pipeline variables
const vars = await getPipelineVariables(hostName, projectId, pipelineId)
const pipelineBranch = vars.find(v => v.key === "SOURCE_BRANCH")?.value;
if (pipelineBranch === sourceBranch) {
console.log(`Cancelling older pipeline ${pipelineId} created at ${pipeline.created_at}`);
await cancelPipeline(hostName, projectId, pipelineId)
} else {
console.log(`Pipeline ${pipelineId} branch ${pipelineBranch} does not match current branch ${sourceBranch}, skipping`);
}
}
} catch (error) {
console.log("Error cancelling pipelines:", error.response?.data || error.message);
}
}
cancelOldPipeline();