Skip to content

Commit f4b7f36

Browse files
committed
[RHTAP-4561] Makes pipelineRun checks search for exact commit
1 parent f1d1252 commit f4b7f36

14 files changed

+135
-130
lines changed

src/apis/kubernetes/kube.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ export class Kubernetes extends Utils {
144144
* @returns {Promise<PipelineRunKind | undefined>} A Promise resolving to the most recent PipelineRun associated with the repository, or undefined if no PipelineRun is found.
145145
* @throws This function may throw errors during API calls or retries.
146146
*/
147-
public async getPipelineRunByRepository(gitRepository: string, eventType: string): Promise<PipelineRunKind | undefined> {
147+
public async getPipelineRunByRepository(gitRepository: string, commitRevision: string, eventType: string): Promise<PipelineRunKind | undefined> {
148148
const customObjectsApi = this.kubeConfig.makeApiClient(CustomObjectsApi);
149149
const maxAttempts = 10;
150150
const retryInterval = 10 * 1000;
@@ -162,7 +162,7 @@ export class Kubernetes extends Utils {
162162
}
163163
const labels = metadata.labels;
164164

165-
return labels?.['pipelinesascode.tekton.dev/event-type'] === eventType;
165+
return labels?.['pipelinesascode.tekton.dev/event-type'] === eventType && labels?.['pipelinesascode.tekton.dev/sha'] === commitRevision;
166166
});
167167

168168
if (filteredPipelineRuns.length > 0) {
@@ -183,7 +183,7 @@ export class Kubernetes extends Utils {
183183
}
184184
}
185185

186-
throw new Error(`Max attempts reached. Unable to fetch pipeline runs for your component in cluster for ${gitRepository}. Check Openshift Pipelines resources...`);
186+
throw new Error(`Max attempts reached. Unable to fetch pipeline runs for your component in cluster for ${gitRepository} with commit ${commitRevision}. Check Openshift Pipelines resources...`);
187187
}
188188

189189
/**

src/apis/scm-providers/bitbucket.ts

+24-15
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ export class BitbucketProvider extends Utils {
9595
fileName: string,
9696
fileContent: string,
9797
message = "Automatic commit generated from tests"
98-
):Promise<boolean> {
98+
):Promise<string> {
9999
try {
100100

101101
const commitData = qs.stringify({
@@ -114,12 +114,17 @@ export class BitbucketProvider extends Utils {
114114
}
115115
);
116116

117-
console.log(`Changes in file ${fileName} successfully committed for branch ${repoBranch}`);
118-
return response.status === 201;
117+
// Extract the revision from the header
118+
const commitSha = response.headers.location.split('/').pop();
119+
120+
console.log(`Changes in file ${fileName} successfully committed in ${commitSha} for branch ${repoBranch}`);
121+
if (response.status != 201) {
122+
throw new Error(`Failed to create commit, request failed with ${response.status}`);
123+
}
119124

125+
return commitSha;
120126
} catch (error) {
121-
console.error('Error committing file:', error);
122-
return false;
127+
throw new Error(`Error committing file: ${error}`);
123128
}
124129
}
125130

@@ -157,7 +162,7 @@ export class BitbucketProvider extends Utils {
157162
* @param fileName file name in bitbucket repo to add/update in PR
158163
* @param fileContent file content to be committed in file
159164
*/
160-
public async createPullrequest(workspace: string, repoSlug: string, fileName: string, fileContent: string):Promise<number> {
165+
public async createPullrequest(workspace: string, repoSlug: string, fileName: string, fileContent: string):Promise<[number, string]> {
161166
const testBranch = `test-${generateRandomChars(4)}`;
162167

163168
// create new branch
@@ -173,7 +178,7 @@ export class BitbucketProvider extends Utils {
173178
);
174179

175180
// Make changes in new branch
176-
await this.createCommit(workspace, repoSlug, testBranch, fileName, fileContent);
181+
const commitSha = await this.createCommit(workspace, repoSlug, testBranch, fileName, fileContent);
177182

178183
// Open PR to merge new branch into main branch
179184
const prData = {
@@ -196,7 +201,7 @@ export class BitbucketProvider extends Utils {
196201
);
197202

198203
console.log(`Pull request ${prResponse.data.id} created in ${repoSlug} repository`);
199-
return prResponse.data.id;
204+
return [prResponse.data.id, commitSha];
200205

201206
} catch(error){
202207
console.log(error);
@@ -210,7 +215,7 @@ export class BitbucketProvider extends Utils {
210215
* @param repoSlug valid bitbucket repository where PR is open
211216
* @param pullRequestID valid ID of pull request to merge
212217
*/
213-
public async mergePullrequest(workspace: string, repoSlug: string, pullRequestID: number) {
218+
public async mergePullrequest(workspace: string, repoSlug: string, pullRequestID: number): Promise<string> {
214219
const mergeData = {
215220
"type": "commit",
216221
"message": "PR merge by automated tests",
@@ -219,14 +224,18 @@ export class BitbucketProvider extends Utils {
219224
};
220225

221226
try {
222-
await this.bitbucket.post(
227+
const response = await this.bitbucket.post(
223228
`repositories/${workspace}/${repoSlug}/pullrequests/${pullRequestID}/merge`,
224229
mergeData
225230
);
226231

227-
console.log(`Pull request "${pullRequestID}" merged successfully in ${repoSlug} repository`);
232+
const commitSha = response.data.merge_commit.hash;
233+
234+
console.log(`Pull request "${pullRequestID}" merged successfully in ${repoSlug} repository with merge commit ${commitSha}`);
235+
236+
return commitSha;
228237
} catch (error) {
229-
console.log("Error merging PR", error);
238+
throw new Error(`Error merging PR: ${error} `);
230239
}
231240
}
232241

@@ -237,7 +246,7 @@ export class BitbucketProvider extends Utils {
237246
* @param fromEnvironment valid environment name from which image will be promoted (dev, stage)
238247
* @param toEnvironment valid environment name to which image will be promoted (stage, prod)
239248
*/
240-
public async createPromotionPullrequest(workspace: string, componentName: string, fromEnvironment: string, toEnvironment: string):Promise<number> {
249+
public async createPromotionPullrequest(workspace: string, componentName: string, fromEnvironment: string, toEnvironment: string):Promise<[number, string]> {
241250
const pattern = /- image: (.*)/;
242251
let extractedImage;
243252

@@ -284,7 +293,7 @@ export class BitbucketProvider extends Utils {
284293
* @param workspace valid workspace in Bitbucket
285294
* @param repoSlug valid Bitbucket repository slug
286295
*/
287-
public async updateJenkinsfileForCI(workspace: string, repoSlug: string): Promise<boolean> {
296+
public async updateJenkinsfileForCI(workspace: string, repoSlug: string): Promise<string> {
288297
const filePath = 'Jenkinsfile';
289298
let currentContent = await this.getFileContent(workspace, repoSlug, 'main', filePath);
290299
const stringReplaceContent = [
@@ -328,7 +337,7 @@ export class BitbucketProvider extends Utils {
328337
roxCentralEndpoint:string,
329338
cosignPublicKey: string,
330339
imageRegistryUser: string
331-
): Promise<boolean> {
340+
): Promise<string> {
332341
const filePath = 'rhtap/env.sh';
333342
let fileContent = await this.getFileContent(workspace, repoSlug, 'main', filePath);
334343
console.log(`File before all changes: ${filePath}\n${fileContent}`);

src/apis/scm-providers/github.ts

+17-10
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ export class GitHubProvider extends Utils {
106106
* @returns {Promise<string | undefined>} A Promise resolving to the SHA of the commit if successful, otherwise undefined.
107107
* @throws Any error that occurs during the execution of the function.
108108
*/
109-
public async createEmptyCommit(gitOrg: string, gitRepository: string): Promise<string | undefined> {
109+
public async createEmptyCommit(gitOrg: string, gitRepository: string): Promise<string> {
110110
try {
111111
const baseBranchRef = await this.octokit.git.getRef({ owner: gitOrg, repo: gitRepository, ref: 'heads/main' });
112112

@@ -130,7 +130,7 @@ export class GitHubProvider extends Utils {
130130

131131
return newCommit.data.sha;
132132
} catch (error) {
133-
console.log(error);
133+
throw new Error(`Failed to create empty commit: ${error}`);
134134
}
135135
}
136136

@@ -279,7 +279,7 @@ export class GitHubProvider extends Utils {
279279
}
280280
}
281281

282-
public async createPullRequestFromMainBranch(owner: string, repo: string, filePath: string, content: string, fileSHA = ""): Promise<number> {
282+
public async createPullRequestFromMainBranch(owner: string, repo: string, filePath: string, content: string, fileSHA = ""): Promise<[number, string]> {
283283
const baseBranch = "main"; // Specify the base branch
284284
const newBranch = generateRandomChars(5); // Specify the new branch name
285285

@@ -298,7 +298,7 @@ export class GitHubProvider extends Utils {
298298
sha: latestCommit.commit.sha
299299
});
300300

301-
await this.octokit.repos.createOrUpdateFileContents({
301+
const response = await this.octokit.repos.createOrUpdateFileContents({
302302
owner,
303303
repo,
304304
path: filePath,
@@ -308,6 +308,12 @@ export class GitHubProvider extends Utils {
308308
sha: fileSHA
309309
});
310310

311+
const commitSha = response.data.commit.sha;
312+
313+
if (commitSha === undefined) {
314+
throw new Error("Failed to create commit");
315+
}
316+
311317
const { data: pullRequest } = await this.octokit.pulls.create({
312318
owner,
313319
repo,
@@ -317,11 +323,10 @@ export class GitHubProvider extends Utils {
317323
body: "RHTAP E2E: Automatic Pull Request"
318324
});
319325

320-
return pullRequest.number;
326+
return [pullRequest.number, commitSha];
321327

322328
} catch (error) {
323-
console.error("Error:", error);
324-
throw new Error(`Error: ${error}`);
329+
throw new Error(`Failed to create pull request from main branch: ${error}`);
325330
}
326331
}
327332

@@ -331,15 +336,17 @@ export class GitHubProvider extends Utils {
331336
* @param {string} repo - The name of the repository.
332337
* @param {string} pullRequest - PR number.
333338
*/
334-
public async mergePullRequest(owner: string, repo: string, pullRequest: number) {
339+
public async mergePullRequest(owner: string, repo: string, pullRequest: number): Promise<string> {
335340
try {
336-
await this.octokit.pulls.merge({
341+
const response = await this.octokit.pulls.merge({
337342
owner,
338343
repo,
339344
pull_number: pullRequest,
340345
commit_title: "RHTAP E2E: Automatic Pull Request merge",
341346
merge_method: "squash"
342347
});
348+
349+
return response.data.sha;
343350
} catch (error) {
344351
throw new Error(`Failed to merge Pull Request ${pullRequest}, owner: ${owner}, repo: ${repo}. Error: ${error}`);
345352
}
@@ -395,7 +402,7 @@ export class GitHubProvider extends Utils {
395402
* @param {string} environment - environment name(development, stage, prod).
396403
* @param {string} image - image name.
397404
*/
398-
public async promoteGitopsImageEnvironment(owner: string, repo: string, componentName: string, environment: string, image: string): Promise<number> {
405+
public async promoteGitopsImageEnvironment(owner: string, repo: string, componentName: string, environment: string, image: string): Promise<[number, string]> {
399406
try {
400407
const response = await this.octokit.repos.getContent({
401408
owner,

src/apis/scm-providers/gitlab.ts

+22-10
Original file line numberDiff line numberDiff line change
@@ -91,10 +91,10 @@ export class GitLabProvider extends Utils {
9191
/**
9292
* name
9393
*/
94-
public async createCommit(repositoryID: number, branchName: string) {
94+
public async createCommit(repositoryID: number, branchName: string): Promise<string> {
9595
try {
9696

97-
await this.gitlab.Commits.create(
97+
const commit = await this.gitlab.Commits.create(
9898
repositoryID,
9999
branchName,
100100
'Commit message',
@@ -107,6 +107,12 @@ export class GitLabProvider extends Utils {
107107
]
108108
);
109109

110+
if (!commit) {
111+
throw new Error("Commit SHA not found in the response");
112+
}
113+
114+
return commit.id;
115+
110116
} catch (error) {
111117
console.log(error);
112118
throw new Error("Failed to create commit in Gitlab. Check bellow error");
@@ -168,7 +174,7 @@ export class GitLabProvider extends Utils {
168174
}
169175

170176
public async createMergeRequestWithPromotionImage(repositoryID: number, targetBranch: string,
171-
componentName: string, fromEnvironment: string, toEnvironment: string): Promise<number> {
177+
componentName: string, fromEnvironment: string, toEnvironment: string): Promise<[number, string]> {
172178

173179
let extractedImage;
174180

@@ -191,7 +197,7 @@ export class GitLabProvider extends Utils {
191197
const pattern = /- image: (.*)/;
192198
const newContent = targetEnvironmentContentToString.replace(pattern, `- image: ${extractedImage}`);
193199

194-
await this.gitlab.Commits.create(
200+
const commit = await this.gitlab.Commits.create(
195201
repositoryID,
196202
targetBranch,
197203
`Promotion from ${fromEnvironment} to ${toEnvironment}`,
@@ -209,7 +215,7 @@ export class GitLabProvider extends Utils {
209215

210216
console.log(`Merge request created successfully. URL: ${mergeRequest.web_url}`);
211217

212-
return mergeRequest.iid;
218+
return [mergeRequest.iid, commit.id];
213219
} catch (error) {
214220
console.log(error);
215221
throw new Error("Failed to create merge request. Check bellow error");
@@ -242,13 +248,13 @@ export class GitLabProvider extends Utils {
242248
/**
243249
* createMergeRequest
244250
*/
245-
public async createMergeRequest(repositoryID: number, branchName: string, title: string): Promise<number> {
251+
public async createMergeRequest(repositoryID: number, branchName: string, title: string): Promise<[number, string]> {
246252
try {
247253
const mainBranch = await this.gitlab.Branches.show(repositoryID, 'main');
248254

249255
await this.gitlab.Branches.create(repositoryID, branchName, mainBranch.commit.id);
250256

251-
await this.gitlab.Commits.create(
257+
const commit = await this.gitlab.Commits.create(
252258
repositoryID,
253259
branchName,
254260
'Automatic commit generated from RHTAP E2E framework',
@@ -268,7 +274,7 @@ export class GitLabProvider extends Utils {
268274

269275
console.log(`Pull request "${title}" created successfully. URL: ${mergeRequest.web_url}`);
270276

271-
return mergeRequest.iid;
277+
return [mergeRequest.iid, commit.id];
272278
} catch (error) {
273279
console.log(error);
274280
throw new Error("Failed to create merge request. Check bellow error");
@@ -281,12 +287,18 @@ export class GitLabProvider extends Utils {
281287
* @param {number} projectId - The ID number of GitLab repo.
282288
* @param {number} mergeRequestId - The ID number of GitLab merge request.
283289
*/
284-
public async mergeMergeRequest(projectId: number, mergeRequestId: number) {
290+
public async mergeMergeRequest(projectId: number, mergeRequestId: number): Promise<string> {
285291
try {
286292
console.log(`Merging merge request "${mergeRequestId}"`);
287-
await this.gitlab.MergeRequests.accept(projectId, mergeRequestId);
293+
const response = await this.gitlab.MergeRequests.accept(projectId, mergeRequestId);
288294

289295
console.log(`Pull request "${mergeRequestId}" merged successfully.`);
296+
297+
if (!response.merge_commit_sha) {
298+
throw new Error(`Failed to get revision of merge request with id ${mergeRequestId}`);
299+
}
300+
301+
return response.merge_commit_sha;
290302
} catch (error) {
291303
console.log(error);
292304
throw new Error("Failed to merge Merge Request. Check bellow error");

src/utils/tekton.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,8 @@ export class Tekton {
100100
}
101101
}
102102

103-
public async verifyPipelineRunByRepository(repositoryName: string, namespace: string, eventType: string, expectedTasks: string[]) {
104-
const pipelineRun = await this.kubeClient.getPipelineRunByRepository(repositoryName, eventType);
103+
public async verifyPipelineRunByRepository(repositoryName: string, namespace: string, commitRevision: string, eventType: string, expectedTasks: string[]) {
104+
const pipelineRun = await this.kubeClient.getPipelineRunByRepository(repositoryName, commitRevision, eventType);
105105
if (pipelineRun === undefined) {
106106
throw new Error("Error to read pipelinerun from the cluster. Seems like pipelinerun was never created; verify PAC controller logs.");
107107
}

src/utils/test.utils.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -376,8 +376,8 @@ export async function waitForJenkinsJobToFinish(jenkinsClient: JenkinsCI, jobNam
376376
* @throws {Error} If the pipeline run cannot be found or if there is an error interacting with the Kubernetes API.
377377
*
378378
*/
379-
export async function checkIfAcsScanIsPass(kubeClient: Kubernetes, repositoryName: string, ciNamespace: string, eventType: string): Promise<boolean> {
380-
const pipelineRun = await kubeClient.getPipelineRunByRepository(repositoryName, eventType);
379+
export async function checkIfAcsScanIsPass(kubeClient: Kubernetes, repositoryName: string, ciNamespace: string, revision: string, eventType: string): Promise<boolean> {
380+
const pipelineRun = await kubeClient.getPipelineRunByRepository(repositoryName, revision, eventType);
381381
if (pipelineRun?.metadata?.name) {
382382
const podName: string = pipelineRun.metadata.name + '-acs-image-scan-pod';
383383
// Read the logs from the related container
@@ -437,8 +437,8 @@ export async function waitForGitLabCIPipelineToFinish(gitLabProvider: GitLabProv
437437
* @throws {Error} If the pipeline run cannot be found or if there is an error interacting with the Kubernetes API.
438438
*
439439
*/
440-
export async function verifySyftImagePath(kubeClient: Kubernetes, repositoryName: string, ciNamespace: string, eventType: string): Promise<boolean> {
441-
const pipelineRun = await kubeClient.getPipelineRunByRepository(repositoryName, eventType);
440+
export async function verifySyftImagePath(kubeClient: Kubernetes, repositoryName: string, ciNamespace: string, revision: string, eventType: string): Promise<boolean> {
441+
const pipelineRun = await kubeClient.getPipelineRunByRepository(repositoryName, revision, eventType);
442442
let result = true;
443443
if (pipelineRun?.metadata?.name) {
444444
// eslint-disable-next-line @typescript-eslint/no-explicit-any

0 commit comments

Comments
 (0)