Skip to content

Commit

Permalink
refactor: add input to pass job-name manually
Browse files Browse the repository at this point in the history
  • Loading branch information
qoomon committed Sep 30, 2024
1 parent b2617f8 commit 3d4b5f5
Show file tree
Hide file tree
Showing 6 changed files with 39 additions and 94 deletions.
6 changes: 2 additions & 4 deletions .github/workflows/example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,6 @@ on:
push:
branches: ['main']

permissions:
contents: read
id-token: write

jobs:
build:
name: build name
Expand All @@ -18,6 +14,8 @@ jobs:
- uses: actions/checkout@v4

- uses: ./
with:
job-name: build name

- run: |
echo github.job: ${{ github.job }}
Expand Down
12 changes: 7 additions & 5 deletions action.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ inputs:
required: true
default: '${{ github.token }}'

workflow-context:
description: |
Workflow context e.g. '"<REUSABLE_WORKFLOW_JOB_NAME>", $ {{ toJSON(matrix) }}'
'#matrix':
description: 'DO NOT SET MANUALLY - Current matrix properties'
# --- Workarounds for missing GitHub Actions context variables ---
job-name:
default: '${{ github.job }}'
'#job-matrix':
description: 'DO NOT SET MANUALLY'
default: '${{ toJSON(matrix) }}'
workflow-context:
description: '<REUSABLE_WORKFLOW_JOB_NAME>, $ {{ toJSON(matrix) }}'

outputs:
job:
Expand Down
52 changes: 14 additions & 38 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -43633,7 +43633,16 @@ var dist = __nccwpck_require__(4083);
const LiteralSchema = z.union([z.string(), z.number(), z.boolean(), z["null"]()]);
const JsonSchema = z.lazy(() => z.union([LiteralSchema, JsonObjectSchema, z.array(JsonSchema)]));
const JsonObjectSchema = z.record(JsonSchema);
const YamlTransformer = z.string().transform((str, ctx) => {
const YamlParser = z.string().transform((str, ctx) => {
try {
return dist.parse(str);
}
catch (error) {
ctx.addIssue({ code: 'custom', message: error.message });
return z.NEVER;
}
});
const JsonParser = z.string().transform((str, ctx) => {
try {
return dist.parse(str);
}
Expand Down Expand Up @@ -43711,7 +43720,6 @@ function getWorkflowRunHtmlUrl(context) {




const context = enhancedContext();
/**
* GitHub Actions bot user
Expand Down Expand Up @@ -43817,13 +43825,13 @@ function getAbsoluteJobName({ job, matrix, workflowContextChain }) {
});
return actualJobName;
}
const JobMatrixParser = YamlTransformer.pipe(JsonObjectSchema.nullable());
const JobMatrixParser = JsonParser.pipe(JsonObjectSchema.nullable());
const WorkflowContextSchema = z.object({
job: z.string(),
matrix: JsonObjectSchema.nullable(),
}).strict();
const WorkflowContextParser = z.string()
.transform((str, ctx) => YamlTransformer.parse(`[${str}]`, ctx))
.transform((str, ctx) => YamlParser.parse(`[${str}]`, ctx))
.pipe(z.array(z.union([z.string(), JsonObjectSchema]).nullable()))
.transform((contextChainArray, ctx) => {
const contextChain = [];
Expand Down Expand Up @@ -43854,8 +43862,8 @@ async function getJobObject(octokit) {
if (_jobObject)
return _jobObject;
const absoluteJobName = getAbsoluteJobName({
job: await getJobName(),
matrix: getInput('#matrix', JobMatrixParser),
job: getInput('job-name', { required: true }),
matrix: getInput('#job-matrix', JobMatrixParser),
workflowContextChain: getInput('workflow-context', WorkflowContextParser),
});
const workflowRunJobs = await octokit.paginate(octokit.rest.actions.listJobsForWorkflowRunAttempt, {
Expand All @@ -43868,11 +43876,6 @@ async function getJobObject(octokit) {
}
throw error;
});
console.log('context.job:', context.job);
console.log('absoluteJobName:', absoluteJobName);
console.log('workflowRunJobs:', workflowRunJobs.map((job) => ({
name: job.name,
})));
const currentJob = workflowRunJobs.find((job) => job.name === absoluteJobName);
if (!currentJob) {
throw new Error(`Current job '${absoluteJobName}' could not be found in workflow run.\n` +
Expand All @@ -43883,32 +43886,6 @@ async function getJobObject(octokit) {
}
const jobObject = { ...currentJob, };
return _jobObject = jobObject;
async function getJobName() {
// try to get job name from job workflow definition
const idToken = await core.getIDToken().catch((error) => {
core.debug(`Failed to get job workflow definition: ${error.message}`);
});
if (idToken) {
const tokenPayload = JSON.parse(Buffer.from(idToken.split('.')[1], 'base64').toString());
const jobWorkflowFilePath = tokenPayload.job_workflow_ref.replace(/[^/]+\/[^/]+\//, '').replace(/@[^@]+$/, '');
const jobWorkflowDefinition = await octokit.rest.repos.getContent({
...context.repo,
path: jobWorkflowFilePath,
ref: tokenPayload.job_workflow_sha,
}).then(({ data }) => {
if (!('content' in data)) {
throw new Error('Unexpected response from GitHub API: missing content');
}
const content = Buffer.from(data.content, 'base64').toString('utf-8');
return dist.parse(content);
});
const jobName = jobWorkflowDefinition?.jobs?.[context.job]?.name;
if (jobName) {
return jobName;
}
}
return context.job;
}
}
let _deploymentObject;
/**
Expand Down Expand Up @@ -44006,7 +43983,6 @@ function throwPermissionError(permission, options) {
// eslint-disable-next-line max-len
'https://docs.github.com/en/actions/security-guides/automatic-token-authentication#modifying-the-permissions-for-the-github_token', options);
}
// TODO function to store and read job state

// EXTERNAL MODULE: external "url"
var external_url_ = __nccwpck_require__(7310);
Expand Down
2 changes: 1 addition & 1 deletion dist/index.js.map

Large diffs are not rendered by default.

50 changes: 5 additions & 45 deletions lib/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@ import {InputOptions} from '@actions/core'
import {z, ZodSchema} from 'zod'
import {Context} from '@actions/github/lib/context';
import process from 'node:process';
import {_throw, getFlatValues, JsonObject, JsonObjectSchema, YamlTransformer} from './common.js';
import {_throw, getFlatValues, JsonObject, JsonObjectSchema, JsonParser, YamlParser} from './common.js';
import * as github from '@actions/github';
import {Deployment} from '@octokit/graphql-schema';
import {GitHub} from "@actions/github/lib/utils";
import {getWorkflowRunHtmlUrl} from "./github.js";
import YAML from 'yaml'

export const context = enhancedContext()

Expand Down Expand Up @@ -198,7 +197,7 @@ function getAbsoluteJobName({job, matrix, workflowContextChain}: {
return actualJobName
}

const JobMatrixParser = YamlTransformer.pipe(JsonObjectSchema.nullable())
const JobMatrixParser = JsonParser.pipe(JsonObjectSchema.nullable())

const WorkflowContextSchema = z.object({
job: z.string(),
Expand All @@ -208,7 +207,7 @@ const WorkflowContextSchema = z.object({
type WorkflowContext = z.infer<typeof WorkflowContextSchema>

const WorkflowContextParser = z.string()
.transform((str, ctx) => YamlTransformer.parse(`[${str}]`, ctx))
.transform((str, ctx) => YamlParser.parse(`[${str}]`, ctx))
.pipe(z.array(z.union([z.string(), JsonObjectSchema]).nullable()))
.transform((contextChainArray, ctx) => {
const contextChain: unknown[] = []
Expand Down Expand Up @@ -242,8 +241,8 @@ export async function getJobObject(octokit: InstanceType<typeof GitHub>): Promis
if (_jobObject) return _jobObject

const absoluteJobName = getAbsoluteJobName({
job: await getJobName(),
matrix: getInput('#matrix', JobMatrixParser),
job: getInput('job-name', {required: true}),
matrix: getInput('#job-matrix', JobMatrixParser),
workflowContextChain: getInput('workflow-context', WorkflowContextParser),
})

Expand All @@ -258,12 +257,6 @@ export async function getJobObject(octokit: InstanceType<typeof GitHub>): Promis
throw error
})

console.log('context.job:', context.job)
console.log('absoluteJobName:', absoluteJobName)
console.log('workflowRunJobs:', workflowRunJobs.map((job) => ({
name: job.name,
})))

const currentJob = workflowRunJobs.find((job) => job.name === absoluteJobName)
if (!currentJob) {
throw new Error(`Current job '${absoluteJobName}' could not be found in workflow run.\n` +
Expand All @@ -276,36 +269,6 @@ export async function getJobObject(octokit: InstanceType<typeof GitHub>): Promis

const jobObject = {...currentJob,}
return _jobObject = jobObject;

async function getJobName() {
// try to get job name from job workflow definition
const idToken = await core.getIDToken().catch((error) => {
core.debug(`Failed to get job workflow definition: ${error.message}`)
})
if(idToken) {
const tokenPayload = JSON.parse(Buffer.from(idToken.split('.')[1], 'base64').toString())

const jobWorkflowFilePath = tokenPayload.job_workflow_ref.replace(/[^/]+\/[^/]+\//, '').replace(/@[^@]+$/, '')
const jobWorkflowDefinition = await octokit.rest.repos.getContent({
...context.repo,
path: jobWorkflowFilePath,
ref: tokenPayload.job_workflow_sha,
}).then(({data}) => {
if (!('content' in data)) {
throw new Error('Unexpected response from GitHub API: missing content')
}
const content = Buffer.from(data.content, 'base64').toString('utf-8')
return YAML.parse(content)
})

const jobName = jobWorkflowDefinition?.jobs?.[context.job]?.name
if(jobName) {
return jobName
}
}

return context.job
}
}

let _deploymentObject: Awaited<ReturnType<typeof getDeploymentObject>>
Expand Down Expand Up @@ -418,6 +381,3 @@ export function throwPermissionError(permission: { scope: string; permission: st
'https://docs.github.com/en/actions/security-guides/automatic-token-authentication#modifying-the-permissions-for-the-github_token',
options)
}


// TODO function to store and read job state
11 changes: 10 additions & 1 deletion lib/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,16 @@ export const LiteralSchema: z.ZodType<JsonLiteral> = z.union([z.string(), z.numb
export const JsonSchema: z.ZodType<Json> = z.lazy(() => z.union([LiteralSchema, JsonObjectSchema, z.array(JsonSchema)]))
export const JsonObjectSchema: z.ZodType<JsonObject> = z.record(JsonSchema)

export const YamlTransformer = z.string().transform((str, ctx) => {
export const YamlParser = z.string().transform((str, ctx) => {
try {
return YAML.parse(str) as Json
} catch (error: unknown) {
ctx.addIssue({code: 'custom', message: (error as { message?: string }).message})
return z.NEVER
}
})

export const JsonParser = z.string().transform((str, ctx) => {
try {
return YAML.parse(str) as Json
} catch (error: unknown) {
Expand Down

0 comments on commit 3d4b5f5

Please sign in to comment.