From 83052a1e9ff8df76d87f3780e4c3bd34603708e6 Mon Sep 17 00:00:00 2001 From: Alex Miller Date: Wed, 16 Oct 2024 22:07:32 +1300 Subject: [PATCH] fix: when workflow name is the substring of another workflow name --- src/api.spec.ts | 40 ++++++++++++++++++++++++++++++++++++++++ src/api.ts | 10 +++++----- 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/src/api.spec.ts b/src/api.spec.ts index 0d6cd58..25c4b35 100644 --- a/src/api.spec.ts +++ b/src/api.spec.ts @@ -281,6 +281,46 @@ describe("API", () => { `"fetchWorkflowId: An unexpected error has occurred: Unable to find ID for Workflow: slice"`, ); }); + + it("should return the workflow ID when the name is a substring of another workflow name", async () => { + const mockData = [ + { + id: 0, + path: ".github/workflows/small-cake.yml", + }, + { + id: 1, + path: ".github/workflows/big-cake.yml", + }, + { + id: 2, + path: ".github/workflows/cake.yml", + }, + ]; + vi.spyOn(mockOctokit.rest.actions, "listRepoWorkflows").mockReturnValue( + Promise.resolve({ + data: mockData, + status: 200, + }), + ); + + // Behaviour + expect(await fetchWorkflowId("cake.yml")).toStrictEqual(mockData[2]!.id); + + // Logging + assertOnlyCalled(coreInfoLogMock); + expect(coreInfoLogMock).toHaveBeenCalledOnce(); + expect(coreInfoLogMock.mock.calls[0]?.[0]).toMatchInlineSnapshot( + ` + "Fetched Workflow ID: + Repository: owner/repo + Workflow ID: '2' + Input Filename: 'cake.yml' + Sanitised Filename: 'cake\\.yml' + URL: undefined" + `, + ); + }); }); describe("fetchWorkflowRunIds", () => { diff --git a/src/api.ts b/src/api.ts index 4fe0025..b74faa7 100644 --- a/src/api.ts +++ b/src/api.ts @@ -61,10 +61,10 @@ export async function fetchWorkflowId( workflowFilename: string, ): Promise { try { - const sanitisedFilename = workflowFilename.replace( - /[.*+?^${}()|[\]\\]/g, - "\\$&", - ); + const sanitisedFilename = workflowFilename + .replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + .trim(); + const filenameRegex = new RegExp(`/${sanitisedFilename}`); // https://docs.github.com/en/rest/actions/workflows#list-repository-workflows const workflowIterator = octokit.paginate.iterator( @@ -85,7 +85,7 @@ export async function fetchWorkflowId( } const workflowData = response.data.find((workflow) => - new RegExp(sanitisedFilename).test(workflow.path), + filenameRegex.test(workflow.path), ); workflowId = workflowData?.id;