From ec3a7ce113134d7a93b817d10a8272cb61118579 Mon Sep 17 00:00:00 2001 From: eric sciple Date: Mon, 1 Nov 2021 11:43:18 -0500 Subject: [PATCH] set insteadOf url for org-id (#621) --- __test__/git-auth-helper.test.ts | 12 +- __test__/input-helper.test.ts | 45 +++-- dist/index.js | 281 ++++++++++++++++++++----------- src/git-auth-helper.ts | 25 ++- src/git-command-manager.ts | 18 +- src/git-source-settings.ts | 5 + src/input-helper.ts | 6 +- src/main.ts | 2 +- src/workflow-context-helper.ts | 30 ++++ 9 files changed, 293 insertions(+), 131 deletions(-) create mode 100644 src/workflow-context-helper.ts diff --git a/__test__/git-auth-helper.test.ts b/__test__/git-auth-helper.test.ts index b39d35211..e14e948fb 100644 --- a/__test__/git-auth-helper.test.ts +++ b/__test__/git-auth-helper.test.ts @@ -518,12 +518,17 @@ describe('git-auth-helper tests', () => { await authHelper.configureSubmoduleAuth() // Assert - expect(mockSubmoduleForeach).toHaveBeenCalledTimes(3) + expect(mockSubmoduleForeach).toHaveBeenCalledTimes(4) expect(mockSubmoduleForeach.mock.calls[0][0]).toMatch( /unset-all.*insteadOf/ ) expect(mockSubmoduleForeach.mock.calls[1][0]).toMatch(/http.*extraheader/) - expect(mockSubmoduleForeach.mock.calls[2][0]).toMatch(/url.*insteadOf/) + expect(mockSubmoduleForeach.mock.calls[2][0]).toMatch( + /url.*insteadOf.*git@github.com:/ + ) + expect(mockSubmoduleForeach.mock.calls[3][0]).toMatch( + /url.*insteadOf.*org-123456@github.com:/ + ) } ) @@ -770,7 +775,8 @@ async function setup(testName: string): Promise { repositoryPath: '', sshKey: sshPath ? 'some ssh private key' : '', sshKnownHosts: '', - sshStrict: true + sshStrict: true, + workflowOrganizationId: 123456 } } diff --git a/__test__/input-helper.test.ts b/__test__/input-helper.test.ts index 920bc8e13..a31b11cfa 100644 --- a/__test__/input-helper.test.ts +++ b/__test__/input-helper.test.ts @@ -1,9 +1,9 @@ -import * as assert from 'assert' import * as core from '@actions/core' import * as fsHelper from '../lib/fs-helper' import * as github from '@actions/github' import * as inputHelper from '../lib/input-helper' import * as path from 'path' +import * as workflowContextHelper from '../lib/workflow-context-helper' import {IGitSourceSettings} from '../lib/git-source-settings' const originalGitHubWorkspace = process.env['GITHUB_WORKSPACE'] @@ -43,6 +43,11 @@ describe('input-helper tests', () => { .spyOn(fsHelper, 'directoryExistsSync') .mockImplementation((path: string) => path == gitHubWorkspace) + // Mock ./workflowContextHelper getOrganizationId() + jest + .spyOn(workflowContextHelper, 'getOrganizationId') + .mockImplementation(() => Promise.resolve(123456)) + // GitHub workspace process.env['GITHUB_WORKSPACE'] = gitHubWorkspace }) @@ -67,8 +72,8 @@ describe('input-helper tests', () => { jest.restoreAllMocks() }) - it('sets defaults', () => { - const settings: IGitSourceSettings = inputHelper.getInputs() + it('sets defaults', async () => { + const settings: IGitSourceSettings = await inputHelper.getInputs() expect(settings).toBeTruthy() expect(settings.authToken).toBeFalsy() expect(settings.clean).toBe(true) @@ -82,11 +87,11 @@ describe('input-helper tests', () => { expect(settings.repositoryPath).toBe(gitHubWorkspace) }) - it('qualifies ref', () => { + it('qualifies ref', async () => { let originalRef = github.context.ref try { github.context.ref = 'some-unqualified-ref' - const settings: IGitSourceSettings = inputHelper.getInputs() + const settings: IGitSourceSettings = await inputHelper.getInputs() expect(settings).toBeTruthy() expect(settings.commit).toBe('1234567890123456789012345678901234567890') expect(settings.ref).toBe('refs/heads/some-unqualified-ref') @@ -95,32 +100,42 @@ describe('input-helper tests', () => { } }) - it('requires qualified repo', () => { + it('requires qualified repo', async () => { inputs.repository = 'some-unqualified-repo' - assert.throws(() => { - inputHelper.getInputs() - }, /Invalid repository 'some-unqualified-repo'/) + try { + await inputHelper.getInputs() + throw 'should not reach here' + } catch (err) { + expect(`(${(err as any).message}`).toMatch( + "Invalid repository 'some-unqualified-repo'" + ) + } }) - it('roots path', () => { + it('roots path', async () => { inputs.path = 'some-directory/some-subdirectory' - const settings: IGitSourceSettings = inputHelper.getInputs() + const settings: IGitSourceSettings = await inputHelper.getInputs() expect(settings.repositoryPath).toBe( path.join(gitHubWorkspace, 'some-directory', 'some-subdirectory') ) }) - it('sets ref to empty when explicit sha', () => { + it('sets ref to empty when explicit sha', async () => { inputs.ref = '1111111111222222222233333333334444444444' - const settings: IGitSourceSettings = inputHelper.getInputs() + const settings: IGitSourceSettings = await inputHelper.getInputs() expect(settings.ref).toBeFalsy() expect(settings.commit).toBe('1111111111222222222233333333334444444444') }) - it('sets sha to empty when explicit ref', () => { + it('sets sha to empty when explicit ref', async () => { inputs.ref = 'refs/heads/some-other-ref' - const settings: IGitSourceSettings = inputHelper.getInputs() + const settings: IGitSourceSettings = await inputHelper.getInputs() expect(settings.ref).toBe('refs/heads/some-other-ref') expect(settings.commit).toBeFalsy() }) + + it('sets workflow organization ID', async () => { + const settings: IGitSourceSettings = await inputHelper.getInputs() + expect(settings.workflowOrganizationId).toBe(123456) + }) }) diff --git a/dist/index.js b/dist/index.js index 7155f1c32..8542f7dfc 100644 --- a/dist/index.js +++ b/dist/index.js @@ -4149,7 +4149,7 @@ function run() { var _a, _b; return __awaiter(this, void 0, void 0, function* () { try { - const sourceSettings = inputHelper.getInputs(); + const sourceSettings = yield inputHelper.getInputs(); try { // Register problem matcher coreCommand.issueCommand('add-matcher', {}, path.join(__dirname, 'problem-matcher.json')); @@ -6542,6 +6542,7 @@ function createAuthHelper(git, settings) { exports.createAuthHelper = createAuthHelper; class GitAuthHelper { constructor(gitCommandManager, gitSourceSettings) { + this.insteadOfValues = []; this.sshCommand = ''; this.sshKeyPath = ''; this.sshKnownHostsPath = ''; @@ -6557,7 +6558,10 @@ class GitAuthHelper { this.tokenConfigValue = `AUTHORIZATION: basic ${basicCredential}`; // Instead of SSH URL this.insteadOfKey = `url.${serverUrl.origin}/.insteadOf`; // "origin" is SCHEME://HOSTNAME[:PORT] - this.insteadOfValue = `git@${serverUrl.hostname}:`; + this.insteadOfValues.push(`git@${serverUrl.hostname}:`); + if (this.settings.workflowOrganizationId) { + this.insteadOfValues.push(`org-${this.settings.workflowOrganizationId}@github.com:`); + } } configureAuth() { return __awaiter(this, void 0, void 0, function* () { @@ -6606,7 +6610,9 @@ class GitAuthHelper { // Configure HTTPS instead of SSH yield this.git.tryConfigUnset(this.insteadOfKey, true); if (!this.settings.sshKey) { - yield this.git.config(this.insteadOfKey, this.insteadOfValue, true); + for (const insteadOfValue of this.insteadOfValues) { + yield this.git.config(this.insteadOfKey, insteadOfValue, true, true); + } } } catch (err) { @@ -6638,7 +6644,9 @@ class GitAuthHelper { } else { // Configure HTTPS instead of SSH - yield this.git.submoduleForeach(`git config --local '${this.insteadOfKey}' '${this.insteadOfValue}'`, this.settings.nestedSubmodules); + for (const insteadOfValue of this.insteadOfValues) { + yield this.git.submoduleForeach(`git config --local --add '${this.insteadOfKey}' '${insteadOfValue}'`, this.settings.nestedSubmodules); + } } } }); @@ -6928,14 +6936,14 @@ class GitCommandManager { yield this.execGit(args); }); } - config(configKey, configValue, globalConfig) { + config(configKey, configValue, globalConfig, add) { return __awaiter(this, void 0, void 0, function* () { - yield this.execGit([ - 'config', - globalConfig ? '--global' : '--local', - configKey, - configValue - ]); + const args = ['config', globalConfig ? '--global' : '--local']; + if (add) { + args.push('--add'); + } + args.push(...[configKey, configValue]); + yield this.execGit(args); }); } configExists(configKey, globalConfig) { @@ -13522,6 +13530,75 @@ module.exports = function callBoundIntrinsic(name, allowMissing) { module.exports = require("net"); +/***/ }), + +/***/ 642: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getOrganizationId = void 0; +const core = __importStar(__webpack_require__(470)); +const fs = __importStar(__webpack_require__(747)); +/** + * Gets the organization ID of the running workflow or undefined if the value cannot be loaded from the GITHUB_EVENT_PATH + */ +function getOrganizationId() { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + try { + const eventPath = process.env.GITHUB_EVENT_PATH; + if (!eventPath) { + core.debug(`GITHUB_EVENT_PATH is not defined`); + return; + } + const content = yield fs.promises.readFile(eventPath, { encoding: 'utf8' }); + const event = JSON.parse(content); + const id = (_b = (_a = event === null || event === void 0 ? void 0 : event.repository) === null || _a === void 0 ? void 0 : _a.owner) === null || _b === void 0 ? void 0 : _b.id; + if (typeof id !== 'number') { + core.debug('Repository owner ID not found within GITHUB event info'); + return; + } + return id; + } + catch (err) { + core.debug(`Unable to load organization ID from GITHUB_EVENT_PATH: ${err + .message || err}`); + } + }); +} +exports.getOrganizationId = getOrganizationId; + + /***/ }), /***/ 649: @@ -17062,99 +17139,113 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); exports.getInputs = void 0; const core = __importStar(__webpack_require__(470)); const fsHelper = __importStar(__webpack_require__(618)); const github = __importStar(__webpack_require__(469)); const path = __importStar(__webpack_require__(622)); +const workflowContextHelper = __importStar(__webpack_require__(642)); function getInputs() { - const result = {}; - // GitHub workspace - let githubWorkspacePath = process.env['GITHUB_WORKSPACE']; - if (!githubWorkspacePath) { - throw new Error('GITHUB_WORKSPACE not defined'); - } - githubWorkspacePath = path.resolve(githubWorkspacePath); - core.debug(`GITHUB_WORKSPACE = '${githubWorkspacePath}'`); - fsHelper.directoryExistsSync(githubWorkspacePath, true); - // Qualified repository - const qualifiedRepository = core.getInput('repository') || - `${github.context.repo.owner}/${github.context.repo.repo}`; - core.debug(`qualified repository = '${qualifiedRepository}'`); - const splitRepository = qualifiedRepository.split('/'); - if (splitRepository.length !== 2 || - !splitRepository[0] || - !splitRepository[1]) { - throw new Error(`Invalid repository '${qualifiedRepository}'. Expected format {owner}/{repo}.`); - } - result.repositoryOwner = splitRepository[0]; - result.repositoryName = splitRepository[1]; - // Repository path - result.repositoryPath = core.getInput('path') || '.'; - result.repositoryPath = path.resolve(githubWorkspacePath, result.repositoryPath); - if (!(result.repositoryPath + path.sep).startsWith(githubWorkspacePath + path.sep)) { - throw new Error(`Repository path '${result.repositoryPath}' is not under '${githubWorkspacePath}'`); - } - // Workflow repository? - const isWorkflowRepository = qualifiedRepository.toUpperCase() === - `${github.context.repo.owner}/${github.context.repo.repo}`.toUpperCase(); - // Source branch, source version - result.ref = core.getInput('ref'); - if (!result.ref) { - if (isWorkflowRepository) { - result.ref = github.context.ref; - result.commit = github.context.sha; - // Some events have an unqualifed ref. For example when a PR is merged (pull_request closed event), - // the ref is unqualifed like "main" instead of "refs/heads/main". - if (result.commit && result.ref && !result.ref.startsWith('refs/')) { - result.ref = `refs/heads/${result.ref}`; + return __awaiter(this, void 0, void 0, function* () { + const result = {}; + // GitHub workspace + let githubWorkspacePath = process.env['GITHUB_WORKSPACE']; + if (!githubWorkspacePath) { + throw new Error('GITHUB_WORKSPACE not defined'); + } + githubWorkspacePath = path.resolve(githubWorkspacePath); + core.debug(`GITHUB_WORKSPACE = '${githubWorkspacePath}'`); + fsHelper.directoryExistsSync(githubWorkspacePath, true); + // Qualified repository + const qualifiedRepository = core.getInput('repository') || + `${github.context.repo.owner}/${github.context.repo.repo}`; + core.debug(`qualified repository = '${qualifiedRepository}'`); + const splitRepository = qualifiedRepository.split('/'); + if (splitRepository.length !== 2 || + !splitRepository[0] || + !splitRepository[1]) { + throw new Error(`Invalid repository '${qualifiedRepository}'. Expected format {owner}/{repo}.`); + } + result.repositoryOwner = splitRepository[0]; + result.repositoryName = splitRepository[1]; + // Repository path + result.repositoryPath = core.getInput('path') || '.'; + result.repositoryPath = path.resolve(githubWorkspacePath, result.repositoryPath); + if (!(result.repositoryPath + path.sep).startsWith(githubWorkspacePath + path.sep)) { + throw new Error(`Repository path '${result.repositoryPath}' is not under '${githubWorkspacePath}'`); + } + // Workflow repository? + const isWorkflowRepository = qualifiedRepository.toUpperCase() === + `${github.context.repo.owner}/${github.context.repo.repo}`.toUpperCase(); + // Source branch, source version + result.ref = core.getInput('ref'); + if (!result.ref) { + if (isWorkflowRepository) { + result.ref = github.context.ref; + result.commit = github.context.sha; + // Some events have an unqualifed ref. For example when a PR is merged (pull_request closed event), + // the ref is unqualifed like "main" instead of "refs/heads/main". + if (result.commit && result.ref && !result.ref.startsWith('refs/')) { + result.ref = `refs/heads/${result.ref}`; + } } } - } - // SHA? - else if (result.ref.match(/^[0-9a-fA-F]{40}$/)) { - result.commit = result.ref; - result.ref = ''; - } - core.debug(`ref = '${result.ref}'`); - core.debug(`commit = '${result.commit}'`); - // Clean - result.clean = (core.getInput('clean') || 'true').toUpperCase() === 'TRUE'; - core.debug(`clean = ${result.clean}`); - // Fetch depth - result.fetchDepth = Math.floor(Number(core.getInput('fetch-depth') || '1')); - if (isNaN(result.fetchDepth) || result.fetchDepth < 0) { - result.fetchDepth = 0; - } - core.debug(`fetch depth = ${result.fetchDepth}`); - // LFS - result.lfs = (core.getInput('lfs') || 'false').toUpperCase() === 'TRUE'; - core.debug(`lfs = ${result.lfs}`); - // Submodules - result.submodules = false; - result.nestedSubmodules = false; - const submodulesString = (core.getInput('submodules') || '').toUpperCase(); - if (submodulesString == 'RECURSIVE') { - result.submodules = true; - result.nestedSubmodules = true; - } - else if (submodulesString == 'TRUE') { - result.submodules = true; - } - core.debug(`submodules = ${result.submodules}`); - core.debug(`recursive submodules = ${result.nestedSubmodules}`); - // Auth token - result.authToken = core.getInput('token', { required: true }); - // SSH - result.sshKey = core.getInput('ssh-key'); - result.sshKnownHosts = core.getInput('ssh-known-hosts'); - result.sshStrict = - (core.getInput('ssh-strict') || 'true').toUpperCase() === 'TRUE'; - // Persist credentials - result.persistCredentials = - (core.getInput('persist-credentials') || 'false').toUpperCase() === 'TRUE'; - return result; + // SHA? + else if (result.ref.match(/^[0-9a-fA-F]{40}$/)) { + result.commit = result.ref; + result.ref = ''; + } + core.debug(`ref = '${result.ref}'`); + core.debug(`commit = '${result.commit}'`); + // Clean + result.clean = (core.getInput('clean') || 'true').toUpperCase() === 'TRUE'; + core.debug(`clean = ${result.clean}`); + // Fetch depth + result.fetchDepth = Math.floor(Number(core.getInput('fetch-depth') || '1')); + if (isNaN(result.fetchDepth) || result.fetchDepth < 0) { + result.fetchDepth = 0; + } + core.debug(`fetch depth = ${result.fetchDepth}`); + // LFS + result.lfs = (core.getInput('lfs') || 'false').toUpperCase() === 'TRUE'; + core.debug(`lfs = ${result.lfs}`); + // Submodules + result.submodules = false; + result.nestedSubmodules = false; + const submodulesString = (core.getInput('submodules') || '').toUpperCase(); + if (submodulesString == 'RECURSIVE') { + result.submodules = true; + result.nestedSubmodules = true; + } + else if (submodulesString == 'TRUE') { + result.submodules = true; + } + core.debug(`submodules = ${result.submodules}`); + core.debug(`recursive submodules = ${result.nestedSubmodules}`); + // Auth token + result.authToken = core.getInput('token', { required: true }); + // SSH + result.sshKey = core.getInput('ssh-key'); + result.sshKnownHosts = core.getInput('ssh-known-hosts'); + result.sshStrict = + (core.getInput('ssh-strict') || 'true').toUpperCase() === 'TRUE'; + // Persist credentials + result.persistCredentials = + (core.getInput('persist-credentials') || 'false').toUpperCase() === 'TRUE'; + // Workflow organization ID + result.workflowOrganizationId = yield workflowContextHelper.getOrganizationId(); + return result; + }); } exports.getInputs = getInputs; diff --git a/src/git-auth-helper.ts b/src/git-auth-helper.ts index af400abd3..233b3e66a 100644 --- a/src/git-auth-helper.ts +++ b/src/git-auth-helper.ts @@ -37,7 +37,7 @@ class GitAuthHelper { private readonly tokenConfigValue: string private readonly tokenPlaceholderConfigValue: string private readonly insteadOfKey: string - private readonly insteadOfValue: string + private readonly insteadOfValues: string[] = [] private sshCommand = '' private sshKeyPath = '' private sshKnownHostsPath = '' @@ -45,7 +45,7 @@ class GitAuthHelper { constructor( gitCommandManager: IGitCommandManager, - gitSourceSettings?: IGitSourceSettings + gitSourceSettings: IGitSourceSettings | undefined ) { this.git = gitCommandManager this.settings = gitSourceSettings || (({} as unknown) as IGitSourceSettings) @@ -63,7 +63,12 @@ class GitAuthHelper { // Instead of SSH URL this.insteadOfKey = `url.${serverUrl.origin}/.insteadOf` // "origin" is SCHEME://HOSTNAME[:PORT] - this.insteadOfValue = `git@${serverUrl.hostname}:` + this.insteadOfValues.push(`git@${serverUrl.hostname}:`) + if (this.settings.workflowOrganizationId) { + this.insteadOfValues.push( + `org-${this.settings.workflowOrganizationId}@github.com:` + ) + } } async configureAuth(): Promise { @@ -118,7 +123,9 @@ class GitAuthHelper { // Configure HTTPS instead of SSH await this.git.tryConfigUnset(this.insteadOfKey, true) if (!this.settings.sshKey) { - await this.git.config(this.insteadOfKey, this.insteadOfValue, true) + for (const insteadOfValue of this.insteadOfValues) { + await this.git.config(this.insteadOfKey, insteadOfValue, true, true) + } } } catch (err) { // Unset in case somehow written to the real global config @@ -159,10 +166,12 @@ class GitAuthHelper { ) } else { // Configure HTTPS instead of SSH - await this.git.submoduleForeach( - `git config --local '${this.insteadOfKey}' '${this.insteadOfValue}'`, - this.settings.nestedSubmodules - ) + for (const insteadOfValue of this.insteadOfValues) { + await this.git.submoduleForeach( + `git config --local --add '${this.insteadOfKey}' '${insteadOfValue}'`, + this.settings.nestedSubmodules + ) + } } } } diff --git a/src/git-command-manager.ts b/src/git-command-manager.ts index 409a16191..699a963de 100644 --- a/src/git-command-manager.ts +++ b/src/git-command-manager.ts @@ -21,7 +21,8 @@ export interface IGitCommandManager { config( configKey: string, configValue: string, - globalConfig?: boolean + globalConfig?: boolean, + add?: boolean ): Promise configExists(configKey: string, globalConfig?: boolean): Promise fetch(refSpec: string[], fetchDepth?: number): Promise @@ -140,14 +141,15 @@ class GitCommandManager { async config( configKey: string, configValue: string, - globalConfig?: boolean + globalConfig?: boolean, + add?: boolean ): Promise { - await this.execGit([ - 'config', - globalConfig ? '--global' : '--local', - configKey, - configValue - ]) + const args: string[] = ['config', globalConfig ? '--global' : '--local'] + if (add) { + args.push('--add') + } + args.push(...[configKey, configValue]) + await this.execGit(args) } async configExists( diff --git a/src/git-source-settings.ts b/src/git-source-settings.ts index 278622231..19f46513d 100644 --- a/src/git-source-settings.ts +++ b/src/git-source-settings.ts @@ -73,4 +73,9 @@ export interface IGitSourceSettings { * Indicates whether to persist the credentials on disk to enable scripting authenticated git commands */ persistCredentials: boolean + + /** + * Organization ID for the currently running workflow (used for auth settings) + */ + workflowOrganizationId: number | undefined } diff --git a/src/input-helper.ts b/src/input-helper.ts index 4c05d6e32..40e6de44e 100644 --- a/src/input-helper.ts +++ b/src/input-helper.ts @@ -2,9 +2,10 @@ import * as core from '@actions/core' import * as fsHelper from './fs-helper' import * as github from '@actions/github' import * as path from 'path' +import * as workflowContextHelper from './workflow-context-helper' import {IGitSourceSettings} from './git-source-settings' -export function getInputs(): IGitSourceSettings { +export async function getInputs(): Promise { const result = ({} as unknown) as IGitSourceSettings // GitHub workspace @@ -118,5 +119,8 @@ export function getInputs(): IGitSourceSettings { result.persistCredentials = (core.getInput('persist-credentials') || 'false').toUpperCase() === 'TRUE' + // Workflow organization ID + result.workflowOrganizationId = await workflowContextHelper.getOrganizationId() + return result } diff --git a/src/main.ts b/src/main.ts index 07a7ce30b..97a27af0a 100644 --- a/src/main.ts +++ b/src/main.ts @@ -7,7 +7,7 @@ import * as stateHelper from './state-helper' async function run(): Promise { try { - const sourceSettings = inputHelper.getInputs() + const sourceSettings = await inputHelper.getInputs() try { // Register problem matcher diff --git a/src/workflow-context-helper.ts b/src/workflow-context-helper.ts new file mode 100644 index 000000000..c7d7918f9 --- /dev/null +++ b/src/workflow-context-helper.ts @@ -0,0 +1,30 @@ +import * as core from '@actions/core' +import * as fs from 'fs' + +/** + * Gets the organization ID of the running workflow or undefined if the value cannot be loaded from the GITHUB_EVENT_PATH + */ +export async function getOrganizationId(): Promise { + try { + const eventPath = process.env.GITHUB_EVENT_PATH + if (!eventPath) { + core.debug(`GITHUB_EVENT_PATH is not defined`) + return + } + + const content = await fs.promises.readFile(eventPath, {encoding: 'utf8'}) + const event = JSON.parse(content) + const id = event?.repository?.owner?.id + if (typeof id !== 'number') { + core.debug('Repository owner ID not found within GITHUB event info') + return + } + + return id as number + } catch (err) { + core.debug( + `Unable to load organization ID from GITHUB_EVENT_PATH: ${(err as any) + .message || err}` + ) + } +}