From a66a86e6366140c66d4c57d21adf0b76c1f309ee Mon Sep 17 00:00:00 2001 From: Marco Accorinti Date: Sun, 17 Sep 2023 20:45:12 +0200 Subject: [PATCH 1/7] Add workingDirectory option Let user override $GITHUB_WORKSPACE as default working directory Defaults to undefined, the original behaviour is maintained --- __test__/git-auth-helper.test.ts | 3 +- dist/index.js | 4700 +++++++++++++++--------------- src/git-source-settings.ts | 5 + src/input-helper.ts | 20 +- 4 files changed, 2367 insertions(+), 2361 deletions(-) diff --git a/__test__/git-auth-helper.test.ts b/__test__/git-auth-helper.test.ts index a0cff63..603376e 100644 --- a/__test__/git-auth-helper.test.ts +++ b/__test__/git-auth-helper.test.ts @@ -820,7 +820,8 @@ async function setup(testName: string): Promise { sshStrict: true, workflowOrganizationId: 123456, setSafeDirectory: true, - githubServerUrl: githubServerUrl + githubServerUrl: githubServerUrl, + workingDirectory: undefined } } diff --git a/dist/index.js b/dist/index.js index 67752ae..76c1143 100644 --- a/dist/index.js +++ b/dist/index.js @@ -5,94 +5,94 @@ /***/ (function(__unused_webpack_module, exports, __nccwpck_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; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fileExistsSync = exports.existsSync = exports.directoryExistsSync = void 0; -const fs = __importStar(__nccwpck_require__(7147)); -function directoryExistsSync(path, required) { - var _a, _b, _c; - if (!path) { - throw new Error("Arg 'path' must not be empty"); - } - let stats; - try { - stats = fs.statSync(path); - } - catch (error) { - if (((_a = error) === null || _a === void 0 ? void 0 : _a.code) === 'ENOENT') { - if (!required) { - return false; - } - throw new Error(`Directory '${path}' does not exist`); - } - throw new Error(`Encountered an error when checking whether path '${path}' exists: ${(_c = (_b = error) === null || _b === void 0 ? void 0 : _b.message) !== null && _c !== void 0 ? _c : error}`); - } - if (stats.isDirectory()) { - return true; - } - else if (!required) { - return false; - } - throw new Error(`Directory '${path}' does not exist`); -} -exports.directoryExistsSync = directoryExistsSync; -function existsSync(path) { - var _a, _b, _c; - if (!path) { - throw new Error("Arg 'path' must not be empty"); - } - try { - fs.statSync(path); - } - catch (error) { - if (((_a = error) === null || _a === void 0 ? void 0 : _a.code) === 'ENOENT') { - return false; - } - throw new Error(`Encountered an error when checking whether path '${path}' exists: ${(_c = (_b = error) === null || _b === void 0 ? void 0 : _b.message) !== null && _c !== void 0 ? _c : error}`); - } - return true; -} -exports.existsSync = existsSync; -function fileExistsSync(path) { - var _a, _b, _c; - if (!path) { - throw new Error("Arg 'path' must not be empty"); - } - let stats; - try { - stats = fs.statSync(path); - } - catch (error) { - if (((_a = error) === null || _a === void 0 ? void 0 : _a.code) === 'ENOENT') { - return false; - } - throw new Error(`Encountered an error when checking whether path '${path}' exists: ${(_c = (_b = error) === null || _b === void 0 ? void 0 : _b.message) !== null && _c !== void 0 ? _c : error}`); - } - if (!stats.isDirectory()) { - return true; - } - return false; -} -exports.fileExistsSync = fileExistsSync; + +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; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fileExistsSync = exports.existsSync = exports.directoryExistsSync = void 0; +const fs = __importStar(__nccwpck_require__(7147)); +function directoryExistsSync(path, required) { + var _a, _b, _c; + if (!path) { + throw new Error("Arg 'path' must not be empty"); + } + let stats; + try { + stats = fs.statSync(path); + } + catch (error) { + if (((_a = error) === null || _a === void 0 ? void 0 : _a.code) === 'ENOENT') { + if (!required) { + return false; + } + throw new Error(`Directory '${path}' does not exist`); + } + throw new Error(`Encountered an error when checking whether path '${path}' exists: ${(_c = (_b = error) === null || _b === void 0 ? void 0 : _b.message) !== null && _c !== void 0 ? _c : error}`); + } + if (stats.isDirectory()) { + return true; + } + else if (!required) { + return false; + } + throw new Error(`Directory '${path}' does not exist`); +} +exports.directoryExistsSync = directoryExistsSync; +function existsSync(path) { + var _a, _b, _c; + if (!path) { + throw new Error("Arg 'path' must not be empty"); + } + try { + fs.statSync(path); + } + catch (error) { + if (((_a = error) === null || _a === void 0 ? void 0 : _a.code) === 'ENOENT') { + return false; + } + throw new Error(`Encountered an error when checking whether path '${path}' exists: ${(_c = (_b = error) === null || _b === void 0 ? void 0 : _b.message) !== null && _c !== void 0 ? _c : error}`); + } + return true; +} +exports.existsSync = existsSync; +function fileExistsSync(path) { + var _a, _b, _c; + if (!path) { + throw new Error("Arg 'path' must not be empty"); + } + let stats; + try { + stats = fs.statSync(path); + } + catch (error) { + if (((_a = error) === null || _a === void 0 ? void 0 : _a.code) === 'ENOENT') { + return false; + } + throw new Error(`Encountered an error when checking whether path '${path}' exists: ${(_c = (_b = error) === null || _b === void 0 ? void 0 : _b.message) !== null && _c !== void 0 ? _c : error}`); + } + if (!stats.isDirectory()) { + return true; + } + return false; +} +exports.fileExistsSync = fileExistsSync; /***/ }), @@ -101,334 +101,334 @@ exports.fileExistsSync = fileExistsSync; /***/ (function(__unused_webpack_module, exports, __nccwpck_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()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createAuthHelper = void 0; -const assert = __importStar(__nccwpck_require__(9491)); -const core = __importStar(__nccwpck_require__(2186)); -const exec = __importStar(__nccwpck_require__(1514)); -const fs = __importStar(__nccwpck_require__(7147)); -const io = __importStar(__nccwpck_require__(7436)); -const os = __importStar(__nccwpck_require__(2037)); -const path = __importStar(__nccwpck_require__(1017)); -const regexpHelper = __importStar(__nccwpck_require__(3120)); -const stateHelper = __importStar(__nccwpck_require__(8647)); -const urlHelper = __importStar(__nccwpck_require__(9437)); -const v4_1 = __importDefault(__nccwpck_require__(824)); -const IS_WINDOWS = process.platform === 'win32'; -const SSH_COMMAND_KEY = 'core.sshCommand'; -function createAuthHelper(git, settings) { - return new GitAuthHelper(git, settings); -} -exports.createAuthHelper = createAuthHelper; -class GitAuthHelper { - constructor(gitCommandManager, gitSourceSettings) { - this.insteadOfValues = []; - this.sshCommand = ''; - this.sshKeyPath = ''; - this.sshKnownHostsPath = ''; - this.temporaryHomePath = ''; - this.git = gitCommandManager; - this.settings = gitSourceSettings || {}; - // Token auth header - const serverUrl = urlHelper.getServerUrl(this.settings.githubServerUrl); - this.tokenConfigKey = `http.${serverUrl.origin}/.extraheader`; // "origin" is SCHEME://HOSTNAME[:PORT] - const basicCredential = Buffer.from(`x-access-token:${this.settings.authToken}`, 'utf8').toString('base64'); - core.setSecret(basicCredential); - this.tokenPlaceholderConfigValue = `AUTHORIZATION: basic ***`; - this.tokenConfigValue = `AUTHORIZATION: basic ${basicCredential}`; - // Instead of SSH URL - this.insteadOfKey = `url.${serverUrl.origin}/.insteadOf`; // "origin" is SCHEME://HOSTNAME[:PORT] - 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* () { - // Remove possible previous values - yield this.removeAuth(); - // Configure new values - yield this.configureSsh(); - yield this.configureToken(); - }); - } - configureTempGlobalConfig() { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - // Already setup global config - if (((_a = this.temporaryHomePath) === null || _a === void 0 ? void 0 : _a.length) > 0) { - return path.join(this.temporaryHomePath, '.gitconfig'); - } - // Create a temp home directory - const runnerTemp = process.env['RUNNER_TEMP'] || ''; - assert.ok(runnerTemp, 'RUNNER_TEMP is not defined'); - const uniqueId = (0, v4_1.default)(); - this.temporaryHomePath = path.join(runnerTemp, uniqueId); - yield fs.promises.mkdir(this.temporaryHomePath, { recursive: true }); - // Copy the global git config - const gitConfigPath = path.join(process.env['HOME'] || os.homedir(), '.gitconfig'); - const newGitConfigPath = path.join(this.temporaryHomePath, '.gitconfig'); - let configExists = false; - try { - yield fs.promises.stat(gitConfigPath); - configExists = true; - } - catch (err) { - if (((_b = err) === null || _b === void 0 ? void 0 : _b.code) !== 'ENOENT') { - throw err; - } - } - if (configExists) { - core.info(`Copying '${gitConfigPath}' to '${newGitConfigPath}'`); - yield io.cp(gitConfigPath, newGitConfigPath); - } - else { - yield fs.promises.writeFile(newGitConfigPath, ''); - } - // Override HOME - core.info(`Temporarily overriding HOME='${this.temporaryHomePath}' before making global git config changes`); - this.git.setEnvironmentVariable('HOME', this.temporaryHomePath); - return newGitConfigPath; - }); - } - configureGlobalAuth() { - return __awaiter(this, void 0, void 0, function* () { - // 'configureTempGlobalConfig' noops if already set, just returns the path - const newGitConfigPath = yield this.configureTempGlobalConfig(); - try { - // Configure the token - yield this.configureToken(newGitConfigPath, true); - // Configure HTTPS instead of SSH - yield this.git.tryConfigUnset(this.insteadOfKey, true); - if (!this.settings.sshKey) { - for (const insteadOfValue of this.insteadOfValues) { - yield this.git.config(this.insteadOfKey, insteadOfValue, true, true); - } - } - } - catch (err) { - // Unset in case somehow written to the real global config - core.info('Encountered an error when attempting to configure token. Attempting unconfigure.'); - yield this.git.tryConfigUnset(this.tokenConfigKey, true); - throw err; - } - }); - } - configureSubmoduleAuth() { - return __awaiter(this, void 0, void 0, function* () { - // Remove possible previous HTTPS instead of SSH - yield this.removeGitConfig(this.insteadOfKey, true); - if (this.settings.persistCredentials) { - // Configure a placeholder value. This approach avoids the credential being captured - // by process creation audit events, which are commonly logged. For more information, - // refer to https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/manage/component-updates/command-line-process-auditing - const output = yield this.git.submoduleForeach( - // wrap the pipeline in quotes to make sure it's handled properly by submoduleForeach, rather than just the first part of the pipeline - `sh -c "git config --local '${this.tokenConfigKey}' '${this.tokenPlaceholderConfigValue}' && git config --local --show-origin --name-only --get-regexp remote.origin.url"`, this.settings.nestedSubmodules); - // Replace the placeholder - const configPaths = output.match(/(?<=(^|\n)file:)[^\t]+(?=\tremote\.origin\.url)/g) || []; - for (const configPath of configPaths) { - core.debug(`Replacing token placeholder in '${configPath}'`); - yield this.replaceTokenPlaceholder(configPath); - } - if (this.settings.sshKey) { - // Configure core.sshCommand - yield this.git.submoduleForeach(`git config --local '${SSH_COMMAND_KEY}' '${this.sshCommand}'`, this.settings.nestedSubmodules); - } - else { - // Configure HTTPS instead of SSH - for (const insteadOfValue of this.insteadOfValues) { - yield this.git.submoduleForeach(`git config --local --add '${this.insteadOfKey}' '${insteadOfValue}'`, this.settings.nestedSubmodules); - } - } - } - }); - } - removeAuth() { - return __awaiter(this, void 0, void 0, function* () { - yield this.removeSsh(); - yield this.removeToken(); - }); - } - removeGlobalConfig() { - var _a; - return __awaiter(this, void 0, void 0, function* () { - if (((_a = this.temporaryHomePath) === null || _a === void 0 ? void 0 : _a.length) > 0) { - core.debug(`Unsetting HOME override`); - this.git.removeEnvironmentVariable('HOME'); - yield io.rmRF(this.temporaryHomePath); - } - }); - } - configureSsh() { - var _a; - return __awaiter(this, void 0, void 0, function* () { - if (!this.settings.sshKey) { - return; - } - // Write key - const runnerTemp = process.env['RUNNER_TEMP'] || ''; - assert.ok(runnerTemp, 'RUNNER_TEMP is not defined'); - const uniqueId = (0, v4_1.default)(); - this.sshKeyPath = path.join(runnerTemp, uniqueId); - stateHelper.setSshKeyPath(this.sshKeyPath); - yield fs.promises.mkdir(runnerTemp, { recursive: true }); - yield fs.promises.writeFile(this.sshKeyPath, this.settings.sshKey.trim() + '\n', { mode: 0o600 }); - // Remove inherited permissions on Windows - if (IS_WINDOWS) { - const icacls = yield io.which('icacls.exe'); - yield exec.exec(`"${icacls}" "${this.sshKeyPath}" /grant:r "${process.env['USERDOMAIN']}\\${process.env['USERNAME']}:F"`); - yield exec.exec(`"${icacls}" "${this.sshKeyPath}" /inheritance:r`); - } - // Write known hosts - const userKnownHostsPath = path.join(os.homedir(), '.ssh', 'known_hosts'); - let userKnownHosts = ''; - try { - userKnownHosts = (yield fs.promises.readFile(userKnownHostsPath)).toString(); - } - catch (err) { - if (((_a = err) === null || _a === void 0 ? void 0 : _a.code) !== 'ENOENT') { - throw err; - } - } - let knownHosts = ''; - if (userKnownHosts) { - knownHosts += `# Begin from ${userKnownHostsPath}\n${userKnownHosts}\n# End from ${userKnownHostsPath}\n`; - } - if (this.settings.sshKnownHosts) { - knownHosts += `# Begin from input known hosts\n${this.settings.sshKnownHosts}\n# end from input known hosts\n`; - } - knownHosts += `# Begin implicitly added github.com\ngithub.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCj7ndNxQowgcQnjshcLrqPEiiphnt+VTTvDP6mHBL9j1aNUkY4Ue1gvwnGLVlOhGeYrnZaMgRK6+PKCUXaDbC7qtbW8gIkhL7aGCsOr/C56SJMy/BCZfxd1nWzAOxSDPgVsmerOBYfNqltV9/hWCqBywINIR+5dIg6JTJ72pcEpEjcYgXkE2YEFXV1JHnsKgbLWNlhScqb2UmyRkQyytRLtL+38TGxkxCflmO+5Z8CSSNY7GidjMIZ7Q4zMjA2n1nGrlTDkzwDCsw+wqFPGQA179cnfGWOWRVruj16z6XyvxvjJwbz0wQZ75XK5tKSb7FNyeIEs4TT4jk+S4dhPeAUC5y+bDYirYgM4GC7uEnztnZyaVWQ7B381AK4Qdrwt51ZqExKbQpTUNn+EjqoTwvqNj4kqx5QUCI0ThS/YkOxJCXmPUWZbhjpCg56i+2aB6CmK2JGhn57K5mj0MNdBXA4/WnwH6XoPWJzK5Nyu2zB3nAZp+S5hpQs+p1vN1/wsjk=\n# End implicitly added github.com\n`; - this.sshKnownHostsPath = path.join(runnerTemp, `${uniqueId}_known_hosts`); - stateHelper.setSshKnownHostsPath(this.sshKnownHostsPath); - yield fs.promises.writeFile(this.sshKnownHostsPath, knownHosts); - // Configure GIT_SSH_COMMAND - const sshPath = yield io.which('ssh', true); - this.sshCommand = `"${sshPath}" -i "$RUNNER_TEMP/${path.basename(this.sshKeyPath)}"`; - if (this.settings.sshStrict) { - this.sshCommand += ' -o StrictHostKeyChecking=yes -o CheckHostIP=no'; - } - this.sshCommand += ` -o "UserKnownHostsFile=$RUNNER_TEMP/${path.basename(this.sshKnownHostsPath)}"`; - core.info(`Temporarily overriding GIT_SSH_COMMAND=${this.sshCommand}`); - this.git.setEnvironmentVariable('GIT_SSH_COMMAND', this.sshCommand); - // Configure core.sshCommand - if (this.settings.persistCredentials) { - yield this.git.config(SSH_COMMAND_KEY, this.sshCommand); - } - }); - } - configureToken(configPath, globalConfig) { - return __awaiter(this, void 0, void 0, function* () { - // Validate args - assert.ok((configPath && globalConfig) || (!configPath && !globalConfig), 'Unexpected configureToken parameter combinations'); - // Default config path - if (!configPath && !globalConfig) { - configPath = path.join(this.git.getWorkingDirectory(), '.git', 'config'); - } - // Configure a placeholder value. This approach avoids the credential being captured - // by process creation audit events, which are commonly logged. For more information, - // refer to https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/manage/component-updates/command-line-process-auditing - yield this.git.config(this.tokenConfigKey, this.tokenPlaceholderConfigValue, globalConfig); - // Replace the placeholder - yield this.replaceTokenPlaceholder(configPath || ''); - }); - } - replaceTokenPlaceholder(configPath) { - return __awaiter(this, void 0, void 0, function* () { - assert.ok(configPath, 'configPath is not defined'); - let content = (yield fs.promises.readFile(configPath)).toString(); - const placeholderIndex = content.indexOf(this.tokenPlaceholderConfigValue); - if (placeholderIndex < 0 || - placeholderIndex != content.lastIndexOf(this.tokenPlaceholderConfigValue)) { - throw new Error(`Unable to replace auth placeholder in ${configPath}`); - } - assert.ok(this.tokenConfigValue, 'tokenConfigValue is not defined'); - content = content.replace(this.tokenPlaceholderConfigValue, this.tokenConfigValue); - yield fs.promises.writeFile(configPath, content); - }); - } - removeSsh() { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - // SSH key - const keyPath = this.sshKeyPath || stateHelper.SshKeyPath; - if (keyPath) { - try { - yield io.rmRF(keyPath); - } - catch (err) { - core.debug(`${(_b = (_a = err) === null || _a === void 0 ? void 0 : _a.message) !== null && _b !== void 0 ? _b : err}`); - core.warning(`Failed to remove SSH key '${keyPath}'`); - } - } - // SSH known hosts - const knownHostsPath = this.sshKnownHostsPath || stateHelper.SshKnownHostsPath; - if (knownHostsPath) { - try { - yield io.rmRF(knownHostsPath); - } - catch (_c) { - // Intentionally empty - } - } - // SSH command - yield this.removeGitConfig(SSH_COMMAND_KEY); - }); - } - removeToken() { - return __awaiter(this, void 0, void 0, function* () { - // HTTP extra header - yield this.removeGitConfig(this.tokenConfigKey); - }); - } - removeGitConfig(configKey, submoduleOnly = false) { - return __awaiter(this, void 0, void 0, function* () { - if (!submoduleOnly) { - if ((yield this.git.configExists(configKey)) && - !(yield this.git.tryConfigUnset(configKey))) { - // Load the config contents - core.warning(`Failed to remove '${configKey}' from the git config`); - } - } - const pattern = regexpHelper.escape(configKey); - yield this.git.submoduleForeach( - // wrap the pipeline in quotes to make sure it's handled properly by submoduleForeach, rather than just the first part of the pipeline - `sh -c "git config --local --name-only --get-regexp '${pattern}' && git config --local --unset-all '${configKey}' || :"`, true); - }); - } -} + +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()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createAuthHelper = void 0; +const assert = __importStar(__nccwpck_require__(9491)); +const core = __importStar(__nccwpck_require__(2186)); +const exec = __importStar(__nccwpck_require__(1514)); +const fs = __importStar(__nccwpck_require__(7147)); +const io = __importStar(__nccwpck_require__(7436)); +const os = __importStar(__nccwpck_require__(2037)); +const path = __importStar(__nccwpck_require__(1017)); +const regexpHelper = __importStar(__nccwpck_require__(3120)); +const stateHelper = __importStar(__nccwpck_require__(8647)); +const urlHelper = __importStar(__nccwpck_require__(9437)); +const v4_1 = __importDefault(__nccwpck_require__(824)); +const IS_WINDOWS = process.platform === 'win32'; +const SSH_COMMAND_KEY = 'core.sshCommand'; +function createAuthHelper(git, settings) { + return new GitAuthHelper(git, settings); +} +exports.createAuthHelper = createAuthHelper; +class GitAuthHelper { + constructor(gitCommandManager, gitSourceSettings) { + this.insteadOfValues = []; + this.sshCommand = ''; + this.sshKeyPath = ''; + this.sshKnownHostsPath = ''; + this.temporaryHomePath = ''; + this.git = gitCommandManager; + this.settings = gitSourceSettings || {}; + // Token auth header + const serverUrl = urlHelper.getServerUrl(this.settings.githubServerUrl); + this.tokenConfigKey = `http.${serverUrl.origin}/.extraheader`; // "origin" is SCHEME://HOSTNAME[:PORT] + const basicCredential = Buffer.from(`x-access-token:${this.settings.authToken}`, 'utf8').toString('base64'); + core.setSecret(basicCredential); + this.tokenPlaceholderConfigValue = `AUTHORIZATION: basic ***`; + this.tokenConfigValue = `AUTHORIZATION: basic ${basicCredential}`; + // Instead of SSH URL + this.insteadOfKey = `url.${serverUrl.origin}/.insteadOf`; // "origin" is SCHEME://HOSTNAME[:PORT] + 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* () { + // Remove possible previous values + yield this.removeAuth(); + // Configure new values + yield this.configureSsh(); + yield this.configureToken(); + }); + } + configureTempGlobalConfig() { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + // Already setup global config + if (((_a = this.temporaryHomePath) === null || _a === void 0 ? void 0 : _a.length) > 0) { + return path.join(this.temporaryHomePath, '.gitconfig'); + } + // Create a temp home directory + const runnerTemp = process.env['RUNNER_TEMP'] || ''; + assert.ok(runnerTemp, 'RUNNER_TEMP is not defined'); + const uniqueId = (0, v4_1.default)(); + this.temporaryHomePath = path.join(runnerTemp, uniqueId); + yield fs.promises.mkdir(this.temporaryHomePath, { recursive: true }); + // Copy the global git config + const gitConfigPath = path.join(process.env['HOME'] || os.homedir(), '.gitconfig'); + const newGitConfigPath = path.join(this.temporaryHomePath, '.gitconfig'); + let configExists = false; + try { + yield fs.promises.stat(gitConfigPath); + configExists = true; + } + catch (err) { + if (((_b = err) === null || _b === void 0 ? void 0 : _b.code) !== 'ENOENT') { + throw err; + } + } + if (configExists) { + core.info(`Copying '${gitConfigPath}' to '${newGitConfigPath}'`); + yield io.cp(gitConfigPath, newGitConfigPath); + } + else { + yield fs.promises.writeFile(newGitConfigPath, ''); + } + // Override HOME + core.info(`Temporarily overriding HOME='${this.temporaryHomePath}' before making global git config changes`); + this.git.setEnvironmentVariable('HOME', this.temporaryHomePath); + return newGitConfigPath; + }); + } + configureGlobalAuth() { + return __awaiter(this, void 0, void 0, function* () { + // 'configureTempGlobalConfig' noops if already set, just returns the path + const newGitConfigPath = yield this.configureTempGlobalConfig(); + try { + // Configure the token + yield this.configureToken(newGitConfigPath, true); + // Configure HTTPS instead of SSH + yield this.git.tryConfigUnset(this.insteadOfKey, true); + if (!this.settings.sshKey) { + for (const insteadOfValue of this.insteadOfValues) { + yield this.git.config(this.insteadOfKey, insteadOfValue, true, true); + } + } + } + catch (err) { + // Unset in case somehow written to the real global config + core.info('Encountered an error when attempting to configure token. Attempting unconfigure.'); + yield this.git.tryConfigUnset(this.tokenConfigKey, true); + throw err; + } + }); + } + configureSubmoduleAuth() { + return __awaiter(this, void 0, void 0, function* () { + // Remove possible previous HTTPS instead of SSH + yield this.removeGitConfig(this.insteadOfKey, true); + if (this.settings.persistCredentials) { + // Configure a placeholder value. This approach avoids the credential being captured + // by process creation audit events, which are commonly logged. For more information, + // refer to https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/manage/component-updates/command-line-process-auditing + const output = yield this.git.submoduleForeach( + // wrap the pipeline in quotes to make sure it's handled properly by submoduleForeach, rather than just the first part of the pipeline + `sh -c "git config --local '${this.tokenConfigKey}' '${this.tokenPlaceholderConfigValue}' && git config --local --show-origin --name-only --get-regexp remote.origin.url"`, this.settings.nestedSubmodules); + // Replace the placeholder + const configPaths = output.match(/(?<=(^|\n)file:)[^\t]+(?=\tremote\.origin\.url)/g) || []; + for (const configPath of configPaths) { + core.debug(`Replacing token placeholder in '${configPath}'`); + yield this.replaceTokenPlaceholder(configPath); + } + if (this.settings.sshKey) { + // Configure core.sshCommand + yield this.git.submoduleForeach(`git config --local '${SSH_COMMAND_KEY}' '${this.sshCommand}'`, this.settings.nestedSubmodules); + } + else { + // Configure HTTPS instead of SSH + for (const insteadOfValue of this.insteadOfValues) { + yield this.git.submoduleForeach(`git config --local --add '${this.insteadOfKey}' '${insteadOfValue}'`, this.settings.nestedSubmodules); + } + } + } + }); + } + removeAuth() { + return __awaiter(this, void 0, void 0, function* () { + yield this.removeSsh(); + yield this.removeToken(); + }); + } + removeGlobalConfig() { + var _a; + return __awaiter(this, void 0, void 0, function* () { + if (((_a = this.temporaryHomePath) === null || _a === void 0 ? void 0 : _a.length) > 0) { + core.debug(`Unsetting HOME override`); + this.git.removeEnvironmentVariable('HOME'); + yield io.rmRF(this.temporaryHomePath); + } + }); + } + configureSsh() { + var _a; + return __awaiter(this, void 0, void 0, function* () { + if (!this.settings.sshKey) { + return; + } + // Write key + const runnerTemp = process.env['RUNNER_TEMP'] || ''; + assert.ok(runnerTemp, 'RUNNER_TEMP is not defined'); + const uniqueId = (0, v4_1.default)(); + this.sshKeyPath = path.join(runnerTemp, uniqueId); + stateHelper.setSshKeyPath(this.sshKeyPath); + yield fs.promises.mkdir(runnerTemp, { recursive: true }); + yield fs.promises.writeFile(this.sshKeyPath, this.settings.sshKey.trim() + '\n', { mode: 0o600 }); + // Remove inherited permissions on Windows + if (IS_WINDOWS) { + const icacls = yield io.which('icacls.exe'); + yield exec.exec(`"${icacls}" "${this.sshKeyPath}" /grant:r "${process.env['USERDOMAIN']}\\${process.env['USERNAME']}:F"`); + yield exec.exec(`"${icacls}" "${this.sshKeyPath}" /inheritance:r`); + } + // Write known hosts + const userKnownHostsPath = path.join(os.homedir(), '.ssh', 'known_hosts'); + let userKnownHosts = ''; + try { + userKnownHosts = (yield fs.promises.readFile(userKnownHostsPath)).toString(); + } + catch (err) { + if (((_a = err) === null || _a === void 0 ? void 0 : _a.code) !== 'ENOENT') { + throw err; + } + } + let knownHosts = ''; + if (userKnownHosts) { + knownHosts += `# Begin from ${userKnownHostsPath}\n${userKnownHosts}\n# End from ${userKnownHostsPath}\n`; + } + if (this.settings.sshKnownHosts) { + knownHosts += `# Begin from input known hosts\n${this.settings.sshKnownHosts}\n# end from input known hosts\n`; + } + knownHosts += `# Begin implicitly added github.com\ngithub.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCj7ndNxQowgcQnjshcLrqPEiiphnt+VTTvDP6mHBL9j1aNUkY4Ue1gvwnGLVlOhGeYrnZaMgRK6+PKCUXaDbC7qtbW8gIkhL7aGCsOr/C56SJMy/BCZfxd1nWzAOxSDPgVsmerOBYfNqltV9/hWCqBywINIR+5dIg6JTJ72pcEpEjcYgXkE2YEFXV1JHnsKgbLWNlhScqb2UmyRkQyytRLtL+38TGxkxCflmO+5Z8CSSNY7GidjMIZ7Q4zMjA2n1nGrlTDkzwDCsw+wqFPGQA179cnfGWOWRVruj16z6XyvxvjJwbz0wQZ75XK5tKSb7FNyeIEs4TT4jk+S4dhPeAUC5y+bDYirYgM4GC7uEnztnZyaVWQ7B381AK4Qdrwt51ZqExKbQpTUNn+EjqoTwvqNj4kqx5QUCI0ThS/YkOxJCXmPUWZbhjpCg56i+2aB6CmK2JGhn57K5mj0MNdBXA4/WnwH6XoPWJzK5Nyu2zB3nAZp+S5hpQs+p1vN1/wsjk=\n# End implicitly added github.com\n`; + this.sshKnownHostsPath = path.join(runnerTemp, `${uniqueId}_known_hosts`); + stateHelper.setSshKnownHostsPath(this.sshKnownHostsPath); + yield fs.promises.writeFile(this.sshKnownHostsPath, knownHosts); + // Configure GIT_SSH_COMMAND + const sshPath = yield io.which('ssh', true); + this.sshCommand = `"${sshPath}" -i "$RUNNER_TEMP/${path.basename(this.sshKeyPath)}"`; + if (this.settings.sshStrict) { + this.sshCommand += ' -o StrictHostKeyChecking=yes -o CheckHostIP=no'; + } + this.sshCommand += ` -o "UserKnownHostsFile=$RUNNER_TEMP/${path.basename(this.sshKnownHostsPath)}"`; + core.info(`Temporarily overriding GIT_SSH_COMMAND=${this.sshCommand}`); + this.git.setEnvironmentVariable('GIT_SSH_COMMAND', this.sshCommand); + // Configure core.sshCommand + if (this.settings.persistCredentials) { + yield this.git.config(SSH_COMMAND_KEY, this.sshCommand); + } + }); + } + configureToken(configPath, globalConfig) { + return __awaiter(this, void 0, void 0, function* () { + // Validate args + assert.ok((configPath && globalConfig) || (!configPath && !globalConfig), 'Unexpected configureToken parameter combinations'); + // Default config path + if (!configPath && !globalConfig) { + configPath = path.join(this.git.getWorkingDirectory(), '.git', 'config'); + } + // Configure a placeholder value. This approach avoids the credential being captured + // by process creation audit events, which are commonly logged. For more information, + // refer to https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/manage/component-updates/command-line-process-auditing + yield this.git.config(this.tokenConfigKey, this.tokenPlaceholderConfigValue, globalConfig); + // Replace the placeholder + yield this.replaceTokenPlaceholder(configPath || ''); + }); + } + replaceTokenPlaceholder(configPath) { + return __awaiter(this, void 0, void 0, function* () { + assert.ok(configPath, 'configPath is not defined'); + let content = (yield fs.promises.readFile(configPath)).toString(); + const placeholderIndex = content.indexOf(this.tokenPlaceholderConfigValue); + if (placeholderIndex < 0 || + placeholderIndex != content.lastIndexOf(this.tokenPlaceholderConfigValue)) { + throw new Error(`Unable to replace auth placeholder in ${configPath}`); + } + assert.ok(this.tokenConfigValue, 'tokenConfigValue is not defined'); + content = content.replace(this.tokenPlaceholderConfigValue, this.tokenConfigValue); + yield fs.promises.writeFile(configPath, content); + }); + } + removeSsh() { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + // SSH key + const keyPath = this.sshKeyPath || stateHelper.SshKeyPath; + if (keyPath) { + try { + yield io.rmRF(keyPath); + } + catch (err) { + core.debug(`${(_b = (_a = err) === null || _a === void 0 ? void 0 : _a.message) !== null && _b !== void 0 ? _b : err}`); + core.warning(`Failed to remove SSH key '${keyPath}'`); + } + } + // SSH known hosts + const knownHostsPath = this.sshKnownHostsPath || stateHelper.SshKnownHostsPath; + if (knownHostsPath) { + try { + yield io.rmRF(knownHostsPath); + } + catch (_c) { + // Intentionally empty + } + } + // SSH command + yield this.removeGitConfig(SSH_COMMAND_KEY); + }); + } + removeToken() { + return __awaiter(this, void 0, void 0, function* () { + // HTTP extra header + yield this.removeGitConfig(this.tokenConfigKey); + }); + } + removeGitConfig(configKey, submoduleOnly = false) { + return __awaiter(this, void 0, void 0, function* () { + if (!submoduleOnly) { + if ((yield this.git.configExists(configKey)) && + !(yield this.git.tryConfigUnset(configKey))) { + // Load the config contents + core.warning(`Failed to remove '${configKey}' from the git config`); + } + } + const pattern = regexpHelper.escape(configKey); + yield this.git.submoduleForeach( + // wrap the pipeline in quotes to make sure it's handled properly by submoduleForeach, rather than just the first part of the pipeline + `sh -c "git config --local --name-only --get-regexp '${pattern}' && git config --local --unset-all '${configKey}' || :"`, true); + }); + } +} /***/ }), @@ -437,526 +437,526 @@ class GitAuthHelper { /***/ (function(__unused_webpack_module, exports, __nccwpck_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.createCommandManager = exports.MinimumGitVersion = void 0; -const core = __importStar(__nccwpck_require__(2186)); -const exec = __importStar(__nccwpck_require__(1514)); -const fs = __importStar(__nccwpck_require__(7147)); -const fshelper = __importStar(__nccwpck_require__(7219)); -const io = __importStar(__nccwpck_require__(7436)); -const path = __importStar(__nccwpck_require__(1017)); -const refHelper = __importStar(__nccwpck_require__(8601)); -const regexpHelper = __importStar(__nccwpck_require__(3120)); -const retryHelper = __importStar(__nccwpck_require__(2155)); -const git_version_1 = __nccwpck_require__(3142); -// Auth header not supported before 2.9 -// Wire protocol v2 not supported before 2.18 -exports.MinimumGitVersion = new git_version_1.GitVersion('2.18'); -function createCommandManager(workingDirectory, lfs, doSparseCheckout) { - return __awaiter(this, void 0, void 0, function* () { - return yield GitCommandManager.createCommandManager(workingDirectory, lfs, doSparseCheckout); - }); -} -exports.createCommandManager = createCommandManager; -class GitCommandManager { - // Private constructor; use createCommandManager() - constructor() { - this.gitEnv = { - GIT_TERMINAL_PROMPT: '0', - GCM_INTERACTIVE: 'Never' // Disable prompting for git credential manager - }; - this.gitPath = ''; - this.lfs = false; - this.doSparseCheckout = false; - this.workingDirectory = ''; - } - branchDelete(remote, branch) { - return __awaiter(this, void 0, void 0, function* () { - const args = ['branch', '--delete', '--force']; - if (remote) { - args.push('--remote'); - } - args.push(branch); - yield this.execGit(args); - }); - } - branchExists(remote, pattern) { - return __awaiter(this, void 0, void 0, function* () { - const args = ['branch', '--list']; - if (remote) { - args.push('--remote'); - } - args.push(pattern); - const output = yield this.execGit(args); - return !!output.stdout.trim(); - }); - } - branchList(remote) { - return __awaiter(this, void 0, void 0, function* () { - const result = []; - // Note, this implementation uses "rev-parse --symbolic-full-name" because the output from - // "branch --list" is more difficult when in a detached HEAD state. - // TODO(https://github.com/actions/checkout/issues/786): this implementation uses - // "rev-parse --symbolic-full-name" because there is a bug - // in Git 2.18 that causes "rev-parse --symbolic" to output symbolic full names. When - // 2.18 is no longer supported, we can switch back to --symbolic. - const args = ['rev-parse', '--symbolic-full-name']; - if (remote) { - args.push('--remotes=origin'); - } - else { - args.push('--branches'); - } - const stderr = []; - const errline = []; - const stdout = []; - const stdline = []; - const listeners = { - stderr: (data) => { - stderr.push(data.toString()); - }, - errline: (data) => { - errline.push(data.toString()); - }, - stdout: (data) => { - stdout.push(data.toString()); - }, - stdline: (data) => { - stdline.push(data.toString()); - } - }; - // Suppress the output in order to avoid flooding annotations with innocuous errors. - yield this.execGit(args, false, true, listeners); - core.debug(`stderr callback is: ${stderr}`); - core.debug(`errline callback is: ${errline}`); - core.debug(`stdout callback is: ${stdout}`); - core.debug(`stdline callback is: ${stdline}`); - for (let branch of stdline) { - branch = branch.trim(); - if (!branch) { - continue; - } - if (branch.startsWith('refs/heads/')) { - branch = branch.substring('refs/heads/'.length); - } - else if (branch.startsWith('refs/remotes/')) { - branch = branch.substring('refs/remotes/'.length); - } - result.push(branch); - } - return result; - }); - } - sparseCheckout(sparseCheckout) { - return __awaiter(this, void 0, void 0, function* () { - yield this.execGit(['sparse-checkout', 'set', ...sparseCheckout]); - }); - } - sparseCheckoutNonConeMode(sparseCheckout) { - return __awaiter(this, void 0, void 0, function* () { - yield this.execGit(['config', 'core.sparseCheckout', 'true']); - const output = yield this.execGit([ - 'rev-parse', - '--git-path', - 'info/sparse-checkout' - ]); - const sparseCheckoutPath = path.join(this.workingDirectory, output.stdout.trimRight()); - yield fs.promises.appendFile(sparseCheckoutPath, `\n${sparseCheckout.join('\n')}\n`); - }); - } - checkout(ref, startPoint) { - return __awaiter(this, void 0, void 0, function* () { - const args = ['checkout', '--progress', '--force']; - if (startPoint) { - args.push('-B', ref, startPoint); - } - else { - args.push(ref); - } - yield this.execGit(args); - }); - } - checkoutDetach() { - return __awaiter(this, void 0, void 0, function* () { - const args = ['checkout', '--detach']; - yield this.execGit(args); - }); - } - config(configKey, configValue, globalConfig, add) { - return __awaiter(this, void 0, void 0, function* () { - const args = ['config', globalConfig ? '--global' : '--local']; - if (add) { - args.push('--add'); - } - args.push(...[configKey, configValue]); - yield this.execGit(args); - }); - } - configExists(configKey, globalConfig) { - return __awaiter(this, void 0, void 0, function* () { - const pattern = regexpHelper.escape(configKey); - const output = yield this.execGit([ - 'config', - globalConfig ? '--global' : '--local', - '--name-only', - '--get-regexp', - pattern - ], true); - return output.exitCode === 0; - }); - } - fetch(refSpec, options) { - return __awaiter(this, void 0, void 0, function* () { - const args = ['-c', 'protocol.version=2', 'fetch']; - if (!refSpec.some(x => x === refHelper.tagsRefSpec) && !options.fetchTags) { - args.push('--no-tags'); - } - args.push('--prune', '--no-recurse-submodules'); - if (options.showProgress) { - args.push('--progress'); - } - if (options.filter) { - args.push(`--filter=${options.filter}`); - } - if (options.fetchDepth && options.fetchDepth > 0) { - args.push(`--depth=${options.fetchDepth}`); - } - else if (fshelper.fileExistsSync(path.join(this.workingDirectory, '.git', 'shallow'))) { - args.push('--unshallow'); - } - args.push('origin'); - for (const arg of refSpec) { - args.push(arg); - } - const that = this; - yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () { - yield that.execGit(args); - })); - }); - } - getDefaultBranch(repositoryUrl) { - return __awaiter(this, void 0, void 0, function* () { - let output; - yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () { - output = yield this.execGit([ - 'ls-remote', - '--quiet', - '--exit-code', - '--symref', - repositoryUrl, - 'HEAD' - ]); - })); - if (output) { - // Satisfy compiler, will always be set - for (let line of output.stdout.trim().split('\n')) { - line = line.trim(); - if (line.startsWith('ref:') || line.endsWith('HEAD')) { - return line - .substr('ref:'.length, line.length - 'ref:'.length - 'HEAD'.length) - .trim(); - } - } - } - throw new Error('Unexpected output when retrieving default branch'); - }); - } - getWorkingDirectory() { - return this.workingDirectory; - } - init() { - return __awaiter(this, void 0, void 0, function* () { - yield this.execGit(['init', this.workingDirectory]); - }); - } - isDetached() { - return __awaiter(this, void 0, void 0, function* () { - // Note, "branch --show-current" would be simpler but isn't available until Git 2.22 - const output = yield this.execGit(['rev-parse', '--symbolic-full-name', '--verify', '--quiet', 'HEAD'], true); - return !output.stdout.trim().startsWith('refs/heads/'); - }); - } - lfsFetch(ref) { - return __awaiter(this, void 0, void 0, function* () { - const args = ['lfs', 'fetch', 'origin', ref]; - const that = this; - yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () { - yield that.execGit(args); - })); - }); - } - lfsInstall() { - return __awaiter(this, void 0, void 0, function* () { - yield this.execGit(['lfs', 'install', '--local']); - }); - } - log1(format) { - return __awaiter(this, void 0, void 0, function* () { - const args = format ? ['log', '-1', format] : ['log', '-1']; - const silent = format ? false : true; - const output = yield this.execGit(args, false, silent); - return output.stdout; - }); - } - remoteAdd(remoteName, remoteUrl) { - return __awaiter(this, void 0, void 0, function* () { - yield this.execGit(['remote', 'add', remoteName, remoteUrl]); - }); - } - removeEnvironmentVariable(name) { - delete this.gitEnv[name]; - } - /** - * Resolves a ref to a SHA. For a branch or lightweight tag, the commit SHA is returned. - * For an annotated tag, the tag SHA is returned. - * @param {string} ref For example: 'refs/heads/main' or '/refs/tags/v1' - * @returns {Promise} - */ - revParse(ref) { - return __awaiter(this, void 0, void 0, function* () { - const output = yield this.execGit(['rev-parse', ref]); - return output.stdout.trim(); - }); - } - setEnvironmentVariable(name, value) { - this.gitEnv[name] = value; - } - shaExists(sha) { - return __awaiter(this, void 0, void 0, function* () { - const args = ['rev-parse', '--verify', '--quiet', `${sha}^{object}`]; - const output = yield this.execGit(args, true); - return output.exitCode === 0; - }); - } - submoduleForeach(command, recursive) { - return __awaiter(this, void 0, void 0, function* () { - const args = ['submodule', 'foreach']; - if (recursive) { - args.push('--recursive'); - } - args.push(command); - const output = yield this.execGit(args); - return output.stdout; - }); - } - submoduleSync(recursive) { - return __awaiter(this, void 0, void 0, function* () { - const args = ['submodule', 'sync']; - if (recursive) { - args.push('--recursive'); - } - yield this.execGit(args); - }); - } - submoduleUpdate(fetchDepth, recursive) { - return __awaiter(this, void 0, void 0, function* () { - const args = ['-c', 'protocol.version=2']; - args.push('submodule', 'update', '--init', '--force'); - if (fetchDepth > 0) { - args.push(`--depth=${fetchDepth}`); - } - if (recursive) { - args.push('--recursive'); - } - yield this.execGit(args); - }); - } - submoduleStatus() { - return __awaiter(this, void 0, void 0, function* () { - const output = yield this.execGit(['submodule', 'status'], true); - core.debug(output.stdout); - return output.exitCode === 0; - }); - } - tagExists(pattern) { - return __awaiter(this, void 0, void 0, function* () { - const output = yield this.execGit(['tag', '--list', pattern]); - return !!output.stdout.trim(); - }); - } - tryClean() { - return __awaiter(this, void 0, void 0, function* () { - const output = yield this.execGit(['clean', '-ffdx'], true); - return output.exitCode === 0; - }); - } - tryConfigUnset(configKey, globalConfig) { - return __awaiter(this, void 0, void 0, function* () { - const output = yield this.execGit([ - 'config', - globalConfig ? '--global' : '--local', - '--unset-all', - configKey - ], true); - return output.exitCode === 0; - }); - } - tryDisableAutomaticGarbageCollection() { - return __awaiter(this, void 0, void 0, function* () { - const output = yield this.execGit(['config', '--local', 'gc.auto', '0'], true); - return output.exitCode === 0; - }); - } - tryGetFetchUrl() { - return __awaiter(this, void 0, void 0, function* () { - const output = yield this.execGit(['config', '--local', '--get', 'remote.origin.url'], true); - if (output.exitCode !== 0) { - return ''; - } - const stdout = output.stdout.trim(); - if (stdout.includes('\n')) { - return ''; - } - return stdout; - }); - } - tryReset() { - return __awaiter(this, void 0, void 0, function* () { - const output = yield this.execGit(['reset', '--hard', 'HEAD'], true); - return output.exitCode === 0; - }); - } - static createCommandManager(workingDirectory, lfs, doSparseCheckout) { - return __awaiter(this, void 0, void 0, function* () { - const result = new GitCommandManager(); - yield result.initializeCommandManager(workingDirectory, lfs, doSparseCheckout); - return result; - }); - } - execGit(args, allowAllExitCodes = false, silent = false, customListeners = {}) { - return __awaiter(this, void 0, void 0, function* () { - fshelper.directoryExistsSync(this.workingDirectory, true); - const result = new GitOutput(); - const env = {}; - for (const key of Object.keys(process.env)) { - env[key] = process.env[key]; - } - for (const key of Object.keys(this.gitEnv)) { - env[key] = this.gitEnv[key]; - } - const defaultListener = { - stdout: (data) => { - stdout.push(data.toString()); - } - }; - const mergedListeners = Object.assign(Object.assign({}, defaultListener), customListeners); - const stdout = []; - const options = { - cwd: this.workingDirectory, - env, - silent, - ignoreReturnCode: allowAllExitCodes, - listeners: mergedListeners - }; - result.exitCode = yield exec.exec(`"${this.gitPath}"`, args, options); - result.stdout = stdout.join(''); - core.debug(result.exitCode.toString()); - core.debug(result.stdout); - return result; - }); - } - initializeCommandManager(workingDirectory, lfs, doSparseCheckout) { - return __awaiter(this, void 0, void 0, function* () { - this.workingDirectory = workingDirectory; - // Git-lfs will try to pull down assets if any of the local/user/system setting exist. - // If the user didn't enable `LFS` in their pipeline definition, disable LFS fetch/checkout. - this.lfs = lfs; - if (!this.lfs) { - this.gitEnv['GIT_LFS_SKIP_SMUDGE'] = '1'; - } - this.gitPath = yield io.which('git', true); - // Git version - core.debug('Getting git version'); - let gitVersion = new git_version_1.GitVersion(); - let gitOutput = yield this.execGit(['version']); - let stdout = gitOutput.stdout.trim(); - if (!stdout.includes('\n')) { - const match = stdout.match(/\d+\.\d+(\.\d+)?/); - if (match) { - gitVersion = new git_version_1.GitVersion(match[0]); - } - } - if (!gitVersion.isValid()) { - throw new Error('Unable to determine git version'); - } - // Minimum git version - if (!gitVersion.checkMinimum(exports.MinimumGitVersion)) { - throw new Error(`Minimum required git version is ${exports.MinimumGitVersion}. Your git ('${this.gitPath}') is ${gitVersion}`); - } - if (this.lfs) { - // Git-lfs version - core.debug('Getting git-lfs version'); - let gitLfsVersion = new git_version_1.GitVersion(); - const gitLfsPath = yield io.which('git-lfs', true); - gitOutput = yield this.execGit(['lfs', 'version']); - stdout = gitOutput.stdout.trim(); - if (!stdout.includes('\n')) { - const match = stdout.match(/\d+\.\d+(\.\d+)?/); - if (match) { - gitLfsVersion = new git_version_1.GitVersion(match[0]); - } - } - if (!gitLfsVersion.isValid()) { - throw new Error('Unable to determine git-lfs version'); - } - // Minimum git-lfs version - // Note: - // - Auth header not supported before 2.1 - const minimumGitLfsVersion = new git_version_1.GitVersion('2.1'); - if (!gitLfsVersion.checkMinimum(minimumGitLfsVersion)) { - throw new Error(`Minimum required git-lfs version is ${minimumGitLfsVersion}. Your git-lfs ('${gitLfsPath}') is ${gitLfsVersion}`); - } - } - this.doSparseCheckout = doSparseCheckout; - if (this.doSparseCheckout) { - // The `git sparse-checkout` command was introduced in Git v2.25.0 - const minimumGitSparseCheckoutVersion = new git_version_1.GitVersion('2.25'); - if (!gitVersion.checkMinimum(minimumGitSparseCheckoutVersion)) { - throw new Error(`Minimum Git version required for sparse checkout is ${minimumGitSparseCheckoutVersion}. Your git ('${this.gitPath}') is ${gitVersion}`); - } - } - // Set the user agent - const gitHttpUserAgent = `git/${gitVersion} (github-actions-checkout)`; - core.debug(`Set git useragent to: ${gitHttpUserAgent}`); - this.gitEnv['GIT_HTTP_USER_AGENT'] = gitHttpUserAgent; - }); - } -} -class GitOutput { - constructor() { - this.stdout = ''; - this.exitCode = 0; - } -} + +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.createCommandManager = exports.MinimumGitVersion = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const exec = __importStar(__nccwpck_require__(1514)); +const fs = __importStar(__nccwpck_require__(7147)); +const fshelper = __importStar(__nccwpck_require__(7219)); +const io = __importStar(__nccwpck_require__(7436)); +const path = __importStar(__nccwpck_require__(1017)); +const refHelper = __importStar(__nccwpck_require__(8601)); +const regexpHelper = __importStar(__nccwpck_require__(3120)); +const retryHelper = __importStar(__nccwpck_require__(2155)); +const git_version_1 = __nccwpck_require__(3142); +// Auth header not supported before 2.9 +// Wire protocol v2 not supported before 2.18 +exports.MinimumGitVersion = new git_version_1.GitVersion('2.18'); +function createCommandManager(workingDirectory, lfs, doSparseCheckout) { + return __awaiter(this, void 0, void 0, function* () { + return yield GitCommandManager.createCommandManager(workingDirectory, lfs, doSparseCheckout); + }); +} +exports.createCommandManager = createCommandManager; +class GitCommandManager { + // Private constructor; use createCommandManager() + constructor() { + this.gitEnv = { + GIT_TERMINAL_PROMPT: '0', + GCM_INTERACTIVE: 'Never' // Disable prompting for git credential manager + }; + this.gitPath = ''; + this.lfs = false; + this.doSparseCheckout = false; + this.workingDirectory = ''; + } + branchDelete(remote, branch) { + return __awaiter(this, void 0, void 0, function* () { + const args = ['branch', '--delete', '--force']; + if (remote) { + args.push('--remote'); + } + args.push(branch); + yield this.execGit(args); + }); + } + branchExists(remote, pattern) { + return __awaiter(this, void 0, void 0, function* () { + const args = ['branch', '--list']; + if (remote) { + args.push('--remote'); + } + args.push(pattern); + const output = yield this.execGit(args); + return !!output.stdout.trim(); + }); + } + branchList(remote) { + return __awaiter(this, void 0, void 0, function* () { + const result = []; + // Note, this implementation uses "rev-parse --symbolic-full-name" because the output from + // "branch --list" is more difficult when in a detached HEAD state. + // TODO(https://github.com/actions/checkout/issues/786): this implementation uses + // "rev-parse --symbolic-full-name" because there is a bug + // in Git 2.18 that causes "rev-parse --symbolic" to output symbolic full names. When + // 2.18 is no longer supported, we can switch back to --symbolic. + const args = ['rev-parse', '--symbolic-full-name']; + if (remote) { + args.push('--remotes=origin'); + } + else { + args.push('--branches'); + } + const stderr = []; + const errline = []; + const stdout = []; + const stdline = []; + const listeners = { + stderr: (data) => { + stderr.push(data.toString()); + }, + errline: (data) => { + errline.push(data.toString()); + }, + stdout: (data) => { + stdout.push(data.toString()); + }, + stdline: (data) => { + stdline.push(data.toString()); + } + }; + // Suppress the output in order to avoid flooding annotations with innocuous errors. + yield this.execGit(args, false, true, listeners); + core.debug(`stderr callback is: ${stderr}`); + core.debug(`errline callback is: ${errline}`); + core.debug(`stdout callback is: ${stdout}`); + core.debug(`stdline callback is: ${stdline}`); + for (let branch of stdline) { + branch = branch.trim(); + if (!branch) { + continue; + } + if (branch.startsWith('refs/heads/')) { + branch = branch.substring('refs/heads/'.length); + } + else if (branch.startsWith('refs/remotes/')) { + branch = branch.substring('refs/remotes/'.length); + } + result.push(branch); + } + return result; + }); + } + sparseCheckout(sparseCheckout) { + return __awaiter(this, void 0, void 0, function* () { + yield this.execGit(['sparse-checkout', 'set', ...sparseCheckout]); + }); + } + sparseCheckoutNonConeMode(sparseCheckout) { + return __awaiter(this, void 0, void 0, function* () { + yield this.execGit(['config', 'core.sparseCheckout', 'true']); + const output = yield this.execGit([ + 'rev-parse', + '--git-path', + 'info/sparse-checkout' + ]); + const sparseCheckoutPath = path.join(this.workingDirectory, output.stdout.trimRight()); + yield fs.promises.appendFile(sparseCheckoutPath, `\n${sparseCheckout.join('\n')}\n`); + }); + } + checkout(ref, startPoint) { + return __awaiter(this, void 0, void 0, function* () { + const args = ['checkout', '--progress', '--force']; + if (startPoint) { + args.push('-B', ref, startPoint); + } + else { + args.push(ref); + } + yield this.execGit(args); + }); + } + checkoutDetach() { + return __awaiter(this, void 0, void 0, function* () { + const args = ['checkout', '--detach']; + yield this.execGit(args); + }); + } + config(configKey, configValue, globalConfig, add) { + return __awaiter(this, void 0, void 0, function* () { + const args = ['config', globalConfig ? '--global' : '--local']; + if (add) { + args.push('--add'); + } + args.push(...[configKey, configValue]); + yield this.execGit(args); + }); + } + configExists(configKey, globalConfig) { + return __awaiter(this, void 0, void 0, function* () { + const pattern = regexpHelper.escape(configKey); + const output = yield this.execGit([ + 'config', + globalConfig ? '--global' : '--local', + '--name-only', + '--get-regexp', + pattern + ], true); + return output.exitCode === 0; + }); + } + fetch(refSpec, options) { + return __awaiter(this, void 0, void 0, function* () { + const args = ['-c', 'protocol.version=2', 'fetch']; + if (!refSpec.some(x => x === refHelper.tagsRefSpec) && !options.fetchTags) { + args.push('--no-tags'); + } + args.push('--prune', '--no-recurse-submodules'); + if (options.showProgress) { + args.push('--progress'); + } + if (options.filter) { + args.push(`--filter=${options.filter}`); + } + if (options.fetchDepth && options.fetchDepth > 0) { + args.push(`--depth=${options.fetchDepth}`); + } + else if (fshelper.fileExistsSync(path.join(this.workingDirectory, '.git', 'shallow'))) { + args.push('--unshallow'); + } + args.push('origin'); + for (const arg of refSpec) { + args.push(arg); + } + const that = this; + yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () { + yield that.execGit(args); + })); + }); + } + getDefaultBranch(repositoryUrl) { + return __awaiter(this, void 0, void 0, function* () { + let output; + yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () { + output = yield this.execGit([ + 'ls-remote', + '--quiet', + '--exit-code', + '--symref', + repositoryUrl, + 'HEAD' + ]); + })); + if (output) { + // Satisfy compiler, will always be set + for (let line of output.stdout.trim().split('\n')) { + line = line.trim(); + if (line.startsWith('ref:') || line.endsWith('HEAD')) { + return line + .substr('ref:'.length, line.length - 'ref:'.length - 'HEAD'.length) + .trim(); + } + } + } + throw new Error('Unexpected output when retrieving default branch'); + }); + } + getWorkingDirectory() { + return this.workingDirectory; + } + init() { + return __awaiter(this, void 0, void 0, function* () { + yield this.execGit(['init', this.workingDirectory]); + }); + } + isDetached() { + return __awaiter(this, void 0, void 0, function* () { + // Note, "branch --show-current" would be simpler but isn't available until Git 2.22 + const output = yield this.execGit(['rev-parse', '--symbolic-full-name', '--verify', '--quiet', 'HEAD'], true); + return !output.stdout.trim().startsWith('refs/heads/'); + }); + } + lfsFetch(ref) { + return __awaiter(this, void 0, void 0, function* () { + const args = ['lfs', 'fetch', 'origin', ref]; + const that = this; + yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () { + yield that.execGit(args); + })); + }); + } + lfsInstall() { + return __awaiter(this, void 0, void 0, function* () { + yield this.execGit(['lfs', 'install', '--local']); + }); + } + log1(format) { + return __awaiter(this, void 0, void 0, function* () { + const args = format ? ['log', '-1', format] : ['log', '-1']; + const silent = format ? false : true; + const output = yield this.execGit(args, false, silent); + return output.stdout; + }); + } + remoteAdd(remoteName, remoteUrl) { + return __awaiter(this, void 0, void 0, function* () { + yield this.execGit(['remote', 'add', remoteName, remoteUrl]); + }); + } + removeEnvironmentVariable(name) { + delete this.gitEnv[name]; + } + /** + * Resolves a ref to a SHA. For a branch or lightweight tag, the commit SHA is returned. + * For an annotated tag, the tag SHA is returned. + * @param {string} ref For example: 'refs/heads/main' or '/refs/tags/v1' + * @returns {Promise} + */ + revParse(ref) { + return __awaiter(this, void 0, void 0, function* () { + const output = yield this.execGit(['rev-parse', ref]); + return output.stdout.trim(); + }); + } + setEnvironmentVariable(name, value) { + this.gitEnv[name] = value; + } + shaExists(sha) { + return __awaiter(this, void 0, void 0, function* () { + const args = ['rev-parse', '--verify', '--quiet', `${sha}^{object}`]; + const output = yield this.execGit(args, true); + return output.exitCode === 0; + }); + } + submoduleForeach(command, recursive) { + return __awaiter(this, void 0, void 0, function* () { + const args = ['submodule', 'foreach']; + if (recursive) { + args.push('--recursive'); + } + args.push(command); + const output = yield this.execGit(args); + return output.stdout; + }); + } + submoduleSync(recursive) { + return __awaiter(this, void 0, void 0, function* () { + const args = ['submodule', 'sync']; + if (recursive) { + args.push('--recursive'); + } + yield this.execGit(args); + }); + } + submoduleUpdate(fetchDepth, recursive) { + return __awaiter(this, void 0, void 0, function* () { + const args = ['-c', 'protocol.version=2']; + args.push('submodule', 'update', '--init', '--force'); + if (fetchDepth > 0) { + args.push(`--depth=${fetchDepth}`); + } + if (recursive) { + args.push('--recursive'); + } + yield this.execGit(args); + }); + } + submoduleStatus() { + return __awaiter(this, void 0, void 0, function* () { + const output = yield this.execGit(['submodule', 'status'], true); + core.debug(output.stdout); + return output.exitCode === 0; + }); + } + tagExists(pattern) { + return __awaiter(this, void 0, void 0, function* () { + const output = yield this.execGit(['tag', '--list', pattern]); + return !!output.stdout.trim(); + }); + } + tryClean() { + return __awaiter(this, void 0, void 0, function* () { + const output = yield this.execGit(['clean', '-ffdx'], true); + return output.exitCode === 0; + }); + } + tryConfigUnset(configKey, globalConfig) { + return __awaiter(this, void 0, void 0, function* () { + const output = yield this.execGit([ + 'config', + globalConfig ? '--global' : '--local', + '--unset-all', + configKey + ], true); + return output.exitCode === 0; + }); + } + tryDisableAutomaticGarbageCollection() { + return __awaiter(this, void 0, void 0, function* () { + const output = yield this.execGit(['config', '--local', 'gc.auto', '0'], true); + return output.exitCode === 0; + }); + } + tryGetFetchUrl() { + return __awaiter(this, void 0, void 0, function* () { + const output = yield this.execGit(['config', '--local', '--get', 'remote.origin.url'], true); + if (output.exitCode !== 0) { + return ''; + } + const stdout = output.stdout.trim(); + if (stdout.includes('\n')) { + return ''; + } + return stdout; + }); + } + tryReset() { + return __awaiter(this, void 0, void 0, function* () { + const output = yield this.execGit(['reset', '--hard', 'HEAD'], true); + return output.exitCode === 0; + }); + } + static createCommandManager(workingDirectory, lfs, doSparseCheckout) { + return __awaiter(this, void 0, void 0, function* () { + const result = new GitCommandManager(); + yield result.initializeCommandManager(workingDirectory, lfs, doSparseCheckout); + return result; + }); + } + execGit(args, allowAllExitCodes = false, silent = false, customListeners = {}) { + return __awaiter(this, void 0, void 0, function* () { + fshelper.directoryExistsSync(this.workingDirectory, true); + const result = new GitOutput(); + const env = {}; + for (const key of Object.keys(process.env)) { + env[key] = process.env[key]; + } + for (const key of Object.keys(this.gitEnv)) { + env[key] = this.gitEnv[key]; + } + const defaultListener = { + stdout: (data) => { + stdout.push(data.toString()); + } + }; + const mergedListeners = Object.assign(Object.assign({}, defaultListener), customListeners); + const stdout = []; + const options = { + cwd: this.workingDirectory, + env, + silent, + ignoreReturnCode: allowAllExitCodes, + listeners: mergedListeners + }; + result.exitCode = yield exec.exec(`"${this.gitPath}"`, args, options); + result.stdout = stdout.join(''); + core.debug(result.exitCode.toString()); + core.debug(result.stdout); + return result; + }); + } + initializeCommandManager(workingDirectory, lfs, doSparseCheckout) { + return __awaiter(this, void 0, void 0, function* () { + this.workingDirectory = workingDirectory; + // Git-lfs will try to pull down assets if any of the local/user/system setting exist. + // If the user didn't enable `LFS` in their pipeline definition, disable LFS fetch/checkout. + this.lfs = lfs; + if (!this.lfs) { + this.gitEnv['GIT_LFS_SKIP_SMUDGE'] = '1'; + } + this.gitPath = yield io.which('git', true); + // Git version + core.debug('Getting git version'); + let gitVersion = new git_version_1.GitVersion(); + let gitOutput = yield this.execGit(['version']); + let stdout = gitOutput.stdout.trim(); + if (!stdout.includes('\n')) { + const match = stdout.match(/\d+\.\d+(\.\d+)?/); + if (match) { + gitVersion = new git_version_1.GitVersion(match[0]); + } + } + if (!gitVersion.isValid()) { + throw new Error('Unable to determine git version'); + } + // Minimum git version + if (!gitVersion.checkMinimum(exports.MinimumGitVersion)) { + throw new Error(`Minimum required git version is ${exports.MinimumGitVersion}. Your git ('${this.gitPath}') is ${gitVersion}`); + } + if (this.lfs) { + // Git-lfs version + core.debug('Getting git-lfs version'); + let gitLfsVersion = new git_version_1.GitVersion(); + const gitLfsPath = yield io.which('git-lfs', true); + gitOutput = yield this.execGit(['lfs', 'version']); + stdout = gitOutput.stdout.trim(); + if (!stdout.includes('\n')) { + const match = stdout.match(/\d+\.\d+(\.\d+)?/); + if (match) { + gitLfsVersion = new git_version_1.GitVersion(match[0]); + } + } + if (!gitLfsVersion.isValid()) { + throw new Error('Unable to determine git-lfs version'); + } + // Minimum git-lfs version + // Note: + // - Auth header not supported before 2.1 + const minimumGitLfsVersion = new git_version_1.GitVersion('2.1'); + if (!gitLfsVersion.checkMinimum(minimumGitLfsVersion)) { + throw new Error(`Minimum required git-lfs version is ${minimumGitLfsVersion}. Your git-lfs ('${gitLfsPath}') is ${gitLfsVersion}`); + } + } + this.doSparseCheckout = doSparseCheckout; + if (this.doSparseCheckout) { + // The `git sparse-checkout` command was introduced in Git v2.25.0 + const minimumGitSparseCheckoutVersion = new git_version_1.GitVersion('2.25'); + if (!gitVersion.checkMinimum(minimumGitSparseCheckoutVersion)) { + throw new Error(`Minimum Git version required for sparse checkout is ${minimumGitSparseCheckoutVersion}. Your git ('${this.gitPath}') is ${gitVersion}`); + } + } + // Set the user agent + const gitHttpUserAgent = `git/${gitVersion} (github-actions-checkout)`; + core.debug(`Set git useragent to: ${gitHttpUserAgent}`); + this.gitEnv['GIT_HTTP_USER_AGENT'] = gitHttpUserAgent; + }); + } +} +class GitOutput { + constructor() { + this.stdout = ''; + this.exitCode = 0; + } +} /***/ }), @@ -965,141 +965,141 @@ class GitOutput { /***/ (function(__unused_webpack_module, exports, __nccwpck_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.prepareExistingDirectory = void 0; -const assert = __importStar(__nccwpck_require__(9491)); -const core = __importStar(__nccwpck_require__(2186)); -const fs = __importStar(__nccwpck_require__(7147)); -const fsHelper = __importStar(__nccwpck_require__(7219)); -const io = __importStar(__nccwpck_require__(7436)); -const path = __importStar(__nccwpck_require__(1017)); -function prepareExistingDirectory(git, repositoryPath, repositoryUrl, clean, ref) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - assert.ok(repositoryPath, 'Expected repositoryPath to be defined'); - assert.ok(repositoryUrl, 'Expected repositoryUrl to be defined'); - // Indicates whether to delete the directory contents - let remove = false; - // Check whether using git or REST API - if (!git) { - remove = true; - } - // Fetch URL does not match - else if (!fsHelper.directoryExistsSync(path.join(repositoryPath, '.git')) || - repositoryUrl !== (yield git.tryGetFetchUrl())) { - remove = true; - } - else { - // Delete any index.lock and shallow.lock left by a previously canceled run or crashed git process - const lockPaths = [ - path.join(repositoryPath, '.git', 'index.lock'), - path.join(repositoryPath, '.git', 'shallow.lock') - ]; - for (const lockPath of lockPaths) { - try { - yield io.rmRF(lockPath); - } - catch (error) { - core.debug(`Unable to delete '${lockPath}'. ${(_b = (_a = error) === null || _a === void 0 ? void 0 : _a.message) !== null && _b !== void 0 ? _b : error}`); - } - } - try { - core.startGroup('Removing previously created refs, to avoid conflicts'); - // Checkout detached HEAD - if (!(yield git.isDetached())) { - yield git.checkoutDetach(); - } - // Remove all refs/heads/* - let branches = yield git.branchList(false); - for (const branch of branches) { - yield git.branchDelete(false, branch); - } - // Remove any conflicting refs/remotes/origin/* - // Example 1: Consider ref is refs/heads/foo and previously fetched refs/remotes/origin/foo/bar - // Example 2: Consider ref is refs/heads/foo/bar and previously fetched refs/remotes/origin/foo - if (ref) { - ref = ref.startsWith('refs/') ? ref : `refs/heads/${ref}`; - if (ref.startsWith('refs/heads/')) { - const upperName1 = ref.toUpperCase().substr('REFS/HEADS/'.length); - const upperName1Slash = `${upperName1}/`; - branches = yield git.branchList(true); - for (const branch of branches) { - const upperName2 = branch.substr('origin/'.length).toUpperCase(); - const upperName2Slash = `${upperName2}/`; - if (upperName1.startsWith(upperName2Slash) || - upperName2.startsWith(upperName1Slash)) { - yield git.branchDelete(true, branch); - } - } - } - } - core.endGroup(); - // Check for submodules and delete any existing files if submodules are present - if (!(yield git.submoduleStatus())) { - remove = true; - core.info('Bad Submodules found, removing existing files'); - } - // Clean - if (clean) { - core.startGroup('Cleaning the repository'); - if (!(yield git.tryClean())) { - core.debug(`The clean command failed. This might be caused by: 1) path too long, 2) permission issue, or 3) file in use. For further investigation, manually run 'git clean -ffdx' on the directory '${repositoryPath}'.`); - remove = true; - } - else if (!(yield git.tryReset())) { - remove = true; - } - core.endGroup(); - if (remove) { - core.warning(`Unable to clean or reset the repository. The repository will be recreated instead.`); - } - } - } - catch (error) { - core.warning(`Unable to prepare the existing repository. The repository will be recreated instead.`); - remove = true; - } - } - if (remove) { - // Delete the contents of the directory. Don't delete the directory itself - // since it might be the current working directory. - core.info(`Deleting the contents of '${repositoryPath}'`); - for (const file of yield fs.promises.readdir(repositoryPath)) { - yield io.rmRF(path.join(repositoryPath, file)); - } - } - }); -} -exports.prepareExistingDirectory = prepareExistingDirectory; + +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.prepareExistingDirectory = void 0; +const assert = __importStar(__nccwpck_require__(9491)); +const core = __importStar(__nccwpck_require__(2186)); +const fs = __importStar(__nccwpck_require__(7147)); +const fsHelper = __importStar(__nccwpck_require__(7219)); +const io = __importStar(__nccwpck_require__(7436)); +const path = __importStar(__nccwpck_require__(1017)); +function prepareExistingDirectory(git, repositoryPath, repositoryUrl, clean, ref) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + assert.ok(repositoryPath, 'Expected repositoryPath to be defined'); + assert.ok(repositoryUrl, 'Expected repositoryUrl to be defined'); + // Indicates whether to delete the directory contents + let remove = false; + // Check whether using git or REST API + if (!git) { + remove = true; + } + // Fetch URL does not match + else if (!fsHelper.directoryExistsSync(path.join(repositoryPath, '.git')) || + repositoryUrl !== (yield git.tryGetFetchUrl())) { + remove = true; + } + else { + // Delete any index.lock and shallow.lock left by a previously canceled run or crashed git process + const lockPaths = [ + path.join(repositoryPath, '.git', 'index.lock'), + path.join(repositoryPath, '.git', 'shallow.lock') + ]; + for (const lockPath of lockPaths) { + try { + yield io.rmRF(lockPath); + } + catch (error) { + core.debug(`Unable to delete '${lockPath}'. ${(_b = (_a = error) === null || _a === void 0 ? void 0 : _a.message) !== null && _b !== void 0 ? _b : error}`); + } + } + try { + core.startGroup('Removing previously created refs, to avoid conflicts'); + // Checkout detached HEAD + if (!(yield git.isDetached())) { + yield git.checkoutDetach(); + } + // Remove all refs/heads/* + let branches = yield git.branchList(false); + for (const branch of branches) { + yield git.branchDelete(false, branch); + } + // Remove any conflicting refs/remotes/origin/* + // Example 1: Consider ref is refs/heads/foo and previously fetched refs/remotes/origin/foo/bar + // Example 2: Consider ref is refs/heads/foo/bar and previously fetched refs/remotes/origin/foo + if (ref) { + ref = ref.startsWith('refs/') ? ref : `refs/heads/${ref}`; + if (ref.startsWith('refs/heads/')) { + const upperName1 = ref.toUpperCase().substr('REFS/HEADS/'.length); + const upperName1Slash = `${upperName1}/`; + branches = yield git.branchList(true); + for (const branch of branches) { + const upperName2 = branch.substr('origin/'.length).toUpperCase(); + const upperName2Slash = `${upperName2}/`; + if (upperName1.startsWith(upperName2Slash) || + upperName2.startsWith(upperName1Slash)) { + yield git.branchDelete(true, branch); + } + } + } + } + core.endGroup(); + // Check for submodules and delete any existing files if submodules are present + if (!(yield git.submoduleStatus())) { + remove = true; + core.info('Bad Submodules found, removing existing files'); + } + // Clean + if (clean) { + core.startGroup('Cleaning the repository'); + if (!(yield git.tryClean())) { + core.debug(`The clean command failed. This might be caused by: 1) path too long, 2) permission issue, or 3) file in use. For further investigation, manually run 'git clean -ffdx' on the directory '${repositoryPath}'.`); + remove = true; + } + else if (!(yield git.tryReset())) { + remove = true; + } + core.endGroup(); + if (remove) { + core.warning(`Unable to clean or reset the repository. The repository will be recreated instead.`); + } + } + } + catch (error) { + core.warning(`Unable to prepare the existing repository. The repository will be recreated instead.`); + remove = true; + } + } + if (remove) { + // Delete the contents of the directory. Don't delete the directory itself + // since it might be the current working directory. + core.info(`Deleting the contents of '${repositoryPath}'`); + for (const file of yield fs.promises.readdir(repositoryPath)) { + yield io.rmRF(path.join(repositoryPath, file)); + } + } + }); +} +exports.prepareExistingDirectory = prepareExistingDirectory; /***/ }), @@ -1108,282 +1108,282 @@ exports.prepareExistingDirectory = prepareExistingDirectory; /***/ (function(__unused_webpack_module, exports, __nccwpck_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.cleanup = exports.getSource = void 0; -const core = __importStar(__nccwpck_require__(2186)); -const fsHelper = __importStar(__nccwpck_require__(7219)); -const gitAuthHelper = __importStar(__nccwpck_require__(2565)); -const gitCommandManager = __importStar(__nccwpck_require__(738)); -const gitDirectoryHelper = __importStar(__nccwpck_require__(8609)); -const githubApiHelper = __importStar(__nccwpck_require__(138)); -const io = __importStar(__nccwpck_require__(7436)); -const path = __importStar(__nccwpck_require__(1017)); -const refHelper = __importStar(__nccwpck_require__(8601)); -const stateHelper = __importStar(__nccwpck_require__(8647)); -const urlHelper = __importStar(__nccwpck_require__(9437)); -function getSource(settings) { - return __awaiter(this, void 0, void 0, function* () { - // Repository URL - core.info(`Syncing repository: ${settings.repositoryOwner}/${settings.repositoryName}`); - const repositoryUrl = urlHelper.getFetchUrl(settings); - // Remove conflicting file path - if (fsHelper.fileExistsSync(settings.repositoryPath)) { - yield io.rmRF(settings.repositoryPath); - } - // Create directory - let isExisting = true; - if (!fsHelper.directoryExistsSync(settings.repositoryPath)) { - isExisting = false; - yield io.mkdirP(settings.repositoryPath); - } - // Git command manager - core.startGroup('Getting Git version info'); - const git = yield getGitCommandManager(settings); - core.endGroup(); - let authHelper = null; - try { - if (git) { - authHelper = gitAuthHelper.createAuthHelper(git, settings); - if (settings.setSafeDirectory) { - // Setup the repository path as a safe directory, so if we pass this into a container job with a different user it doesn't fail - // Otherwise all git commands we run in a container fail - yield authHelper.configureTempGlobalConfig(); - core.info(`Adding repository directory to the temporary git global config as a safe directory`); - yield git - .config('safe.directory', settings.repositoryPath, true, true) - .catch(error => { - core.info(`Failed to initialize safe directory with error: ${error}`); - }); - stateHelper.setSafeDirectory(); - } - } - // Prepare existing directory, otherwise recreate - if (isExisting) { - yield gitDirectoryHelper.prepareExistingDirectory(git, settings.repositoryPath, repositoryUrl, settings.clean, settings.ref); - } - if (!git) { - // Downloading using REST API - core.info(`The repository will be downloaded using the GitHub REST API`); - core.info(`To create a local Git repository instead, add Git ${gitCommandManager.MinimumGitVersion} or higher to the PATH`); - if (settings.submodules) { - throw new Error(`Input 'submodules' not supported when falling back to download using the GitHub REST API. To create a local Git repository instead, add Git ${gitCommandManager.MinimumGitVersion} or higher to the PATH.`); - } - else if (settings.sshKey) { - throw new Error(`Input 'ssh-key' not supported when falling back to download using the GitHub REST API. To create a local Git repository instead, add Git ${gitCommandManager.MinimumGitVersion} or higher to the PATH.`); - } - yield githubApiHelper.downloadRepository(settings.authToken, settings.repositoryOwner, settings.repositoryName, settings.ref, settings.commit, settings.repositoryPath, settings.githubServerUrl); - return; - } - // Save state for POST action - stateHelper.setRepositoryPath(settings.repositoryPath); - // Initialize the repository - if (!fsHelper.directoryExistsSync(path.join(settings.repositoryPath, '.git'))) { - core.startGroup('Initializing the repository'); - yield git.init(); - yield git.remoteAdd('origin', repositoryUrl); - core.endGroup(); - } - // Disable automatic garbage collection - core.startGroup('Disabling automatic garbage collection'); - if (!(yield git.tryDisableAutomaticGarbageCollection())) { - core.warning(`Unable to turn off git automatic garbage collection. The git fetch operation may trigger garbage collection and cause a delay.`); - } - core.endGroup(); - // If we didn't initialize it above, do it now - if (!authHelper) { - authHelper = gitAuthHelper.createAuthHelper(git, settings); - } - // Configure auth - core.startGroup('Setting up auth'); - yield authHelper.configureAuth(); - core.endGroup(); - // Determine the default branch - if (!settings.ref && !settings.commit) { - core.startGroup('Determining the default branch'); - if (settings.sshKey) { - settings.ref = yield git.getDefaultBranch(repositoryUrl); - } - else { - settings.ref = yield githubApiHelper.getDefaultBranch(settings.authToken, settings.repositoryOwner, settings.repositoryName, settings.githubServerUrl); - } - core.endGroup(); - } - // LFS install - if (settings.lfs) { - yield git.lfsInstall(); - } - // Fetch - core.startGroup('Fetching the repository'); - const fetchOptions = {}; - if (settings.sparseCheckout) - fetchOptions.filter = 'blob:none'; - if (settings.fetchDepth <= 0) { - // Fetch all branches and tags - let refSpec = refHelper.getRefSpecForAllHistory(settings.ref, settings.commit); - yield git.fetch(refSpec, fetchOptions); - // When all history is fetched, the ref we're interested in may have moved to a different - // commit (push or force push). If so, fetch again with a targeted refspec. - if (!(yield refHelper.testRef(git, settings.ref, settings.commit))) { - refSpec = refHelper.getRefSpec(settings.ref, settings.commit); - yield git.fetch(refSpec, fetchOptions); - } - } - else { - fetchOptions.fetchDepth = settings.fetchDepth; - fetchOptions.fetchTags = settings.fetchTags; - const refSpec = refHelper.getRefSpec(settings.ref, settings.commit); - yield git.fetch(refSpec, fetchOptions); - } - core.endGroup(); - // Checkout info - core.startGroup('Determining the checkout info'); - const checkoutInfo = yield refHelper.getCheckoutInfo(git, settings.ref, settings.commit); - core.endGroup(); - // LFS fetch - // Explicit lfs-fetch to avoid slow checkout (fetches one lfs object at a time). - // Explicit lfs fetch will fetch lfs objects in parallel. - // For sparse checkouts, let `checkout` fetch the needed objects lazily. - if (settings.lfs && !settings.sparseCheckout) { - core.startGroup('Fetching LFS objects'); - yield git.lfsFetch(checkoutInfo.startPoint || checkoutInfo.ref); - core.endGroup(); - } - // Sparse checkout - if (settings.sparseCheckout) { - core.startGroup('Setting up sparse checkout'); - if (settings.sparseCheckoutConeMode) { - yield git.sparseCheckout(settings.sparseCheckout); - } - else { - yield git.sparseCheckoutNonConeMode(settings.sparseCheckout); - } - core.endGroup(); - } - // Checkout - core.startGroup('Checking out the ref'); - yield git.checkout(checkoutInfo.ref, checkoutInfo.startPoint); - core.endGroup(); - // Submodules - if (settings.submodules) { - // Temporarily override global config - core.startGroup('Setting up auth for fetching submodules'); - yield authHelper.configureGlobalAuth(); - core.endGroup(); - // Checkout submodules - core.startGroup('Fetching submodules'); - yield git.submoduleSync(settings.nestedSubmodules); - yield git.submoduleUpdate(settings.fetchDepth, settings.nestedSubmodules); - yield git.submoduleForeach('git config --local gc.auto 0', settings.nestedSubmodules); - core.endGroup(); - // Persist credentials - if (settings.persistCredentials) { - core.startGroup('Persisting credentials for submodules'); - yield authHelper.configureSubmoduleAuth(); - core.endGroup(); - } - } - // Get commit information - const commitInfo = yield git.log1(); - // Log commit sha - yield git.log1("--format='%H'"); - // Check for incorrect pull request merge commit - yield refHelper.checkCommitInfo(settings.authToken, commitInfo, settings.repositoryOwner, settings.repositoryName, settings.ref, settings.commit, settings.githubServerUrl); - } - finally { - // Remove auth - if (authHelper) { - if (!settings.persistCredentials) { - core.startGroup('Removing auth'); - yield authHelper.removeAuth(); - core.endGroup(); - } - authHelper.removeGlobalConfig(); - } - } - }); -} -exports.getSource = getSource; -function cleanup(repositoryPath) { - return __awaiter(this, void 0, void 0, function* () { - // Repo exists? - if (!repositoryPath || - !fsHelper.fileExistsSync(path.join(repositoryPath, '.git', 'config'))) { - return; - } - let git; - try { - git = yield gitCommandManager.createCommandManager(repositoryPath, false, false); - } - catch (_a) { - return; - } - // Remove auth - const authHelper = gitAuthHelper.createAuthHelper(git); - try { - if (stateHelper.PostSetSafeDirectory) { - // Setup the repository path as a safe directory, so if we pass this into a container job with a different user it doesn't fail - // Otherwise all git commands we run in a container fail - yield authHelper.configureTempGlobalConfig(); - core.info(`Adding repository directory to the temporary git global config as a safe directory`); - yield git - .config('safe.directory', repositoryPath, true, true) - .catch(error => { - core.info(`Failed to initialize safe directory with error: ${error}`); - }); - } - yield authHelper.removeAuth(); - } - finally { - yield authHelper.removeGlobalConfig(); - } - }); -} -exports.cleanup = cleanup; -function getGitCommandManager(settings) { - return __awaiter(this, void 0, void 0, function* () { - core.info(`Working directory is '${settings.repositoryPath}'`); - try { - return yield gitCommandManager.createCommandManager(settings.repositoryPath, settings.lfs, settings.sparseCheckout != null); - } - catch (err) { - // Git is required for LFS - if (settings.lfs) { - throw err; - } - // Otherwise fallback to REST API - return undefined; - } - }); -} + +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.cleanup = exports.getSource = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const fsHelper = __importStar(__nccwpck_require__(7219)); +const gitAuthHelper = __importStar(__nccwpck_require__(2565)); +const gitCommandManager = __importStar(__nccwpck_require__(738)); +const gitDirectoryHelper = __importStar(__nccwpck_require__(8609)); +const githubApiHelper = __importStar(__nccwpck_require__(138)); +const io = __importStar(__nccwpck_require__(7436)); +const path = __importStar(__nccwpck_require__(1017)); +const refHelper = __importStar(__nccwpck_require__(8601)); +const stateHelper = __importStar(__nccwpck_require__(8647)); +const urlHelper = __importStar(__nccwpck_require__(9437)); +function getSource(settings) { + return __awaiter(this, void 0, void 0, function* () { + // Repository URL + core.info(`Syncing repository: ${settings.repositoryOwner}/${settings.repositoryName}`); + const repositoryUrl = urlHelper.getFetchUrl(settings); + // Remove conflicting file path + if (fsHelper.fileExistsSync(settings.repositoryPath)) { + yield io.rmRF(settings.repositoryPath); + } + // Create directory + let isExisting = true; + if (!fsHelper.directoryExistsSync(settings.repositoryPath)) { + isExisting = false; + yield io.mkdirP(settings.repositoryPath); + } + // Git command manager + core.startGroup('Getting Git version info'); + const git = yield getGitCommandManager(settings); + core.endGroup(); + let authHelper = null; + try { + if (git) { + authHelper = gitAuthHelper.createAuthHelper(git, settings); + if (settings.setSafeDirectory) { + // Setup the repository path as a safe directory, so if we pass this into a container job with a different user it doesn't fail + // Otherwise all git commands we run in a container fail + yield authHelper.configureTempGlobalConfig(); + core.info(`Adding repository directory to the temporary git global config as a safe directory`); + yield git + .config('safe.directory', settings.repositoryPath, true, true) + .catch(error => { + core.info(`Failed to initialize safe directory with error: ${error}`); + }); + stateHelper.setSafeDirectory(); + } + } + // Prepare existing directory, otherwise recreate + if (isExisting) { + yield gitDirectoryHelper.prepareExistingDirectory(git, settings.repositoryPath, repositoryUrl, settings.clean, settings.ref); + } + if (!git) { + // Downloading using REST API + core.info(`The repository will be downloaded using the GitHub REST API`); + core.info(`To create a local Git repository instead, add Git ${gitCommandManager.MinimumGitVersion} or higher to the PATH`); + if (settings.submodules) { + throw new Error(`Input 'submodules' not supported when falling back to download using the GitHub REST API. To create a local Git repository instead, add Git ${gitCommandManager.MinimumGitVersion} or higher to the PATH.`); + } + else if (settings.sshKey) { + throw new Error(`Input 'ssh-key' not supported when falling back to download using the GitHub REST API. To create a local Git repository instead, add Git ${gitCommandManager.MinimumGitVersion} or higher to the PATH.`); + } + yield githubApiHelper.downloadRepository(settings.authToken, settings.repositoryOwner, settings.repositoryName, settings.ref, settings.commit, settings.repositoryPath, settings.githubServerUrl); + return; + } + // Save state for POST action + stateHelper.setRepositoryPath(settings.repositoryPath); + // Initialize the repository + if (!fsHelper.directoryExistsSync(path.join(settings.repositoryPath, '.git'))) { + core.startGroup('Initializing the repository'); + yield git.init(); + yield git.remoteAdd('origin', repositoryUrl); + core.endGroup(); + } + // Disable automatic garbage collection + core.startGroup('Disabling automatic garbage collection'); + if (!(yield git.tryDisableAutomaticGarbageCollection())) { + core.warning(`Unable to turn off git automatic garbage collection. The git fetch operation may trigger garbage collection and cause a delay.`); + } + core.endGroup(); + // If we didn't initialize it above, do it now + if (!authHelper) { + authHelper = gitAuthHelper.createAuthHelper(git, settings); + } + // Configure auth + core.startGroup('Setting up auth'); + yield authHelper.configureAuth(); + core.endGroup(); + // Determine the default branch + if (!settings.ref && !settings.commit) { + core.startGroup('Determining the default branch'); + if (settings.sshKey) { + settings.ref = yield git.getDefaultBranch(repositoryUrl); + } + else { + settings.ref = yield githubApiHelper.getDefaultBranch(settings.authToken, settings.repositoryOwner, settings.repositoryName, settings.githubServerUrl); + } + core.endGroup(); + } + // LFS install + if (settings.lfs) { + yield git.lfsInstall(); + } + // Fetch + core.startGroup('Fetching the repository'); + const fetchOptions = {}; + if (settings.sparseCheckout) + fetchOptions.filter = 'blob:none'; + if (settings.fetchDepth <= 0) { + // Fetch all branches and tags + let refSpec = refHelper.getRefSpecForAllHistory(settings.ref, settings.commit); + yield git.fetch(refSpec, fetchOptions); + // When all history is fetched, the ref we're interested in may have moved to a different + // commit (push or force push). If so, fetch again with a targeted refspec. + if (!(yield refHelper.testRef(git, settings.ref, settings.commit))) { + refSpec = refHelper.getRefSpec(settings.ref, settings.commit); + yield git.fetch(refSpec, fetchOptions); + } + } + else { + fetchOptions.fetchDepth = settings.fetchDepth; + fetchOptions.fetchTags = settings.fetchTags; + const refSpec = refHelper.getRefSpec(settings.ref, settings.commit); + yield git.fetch(refSpec, fetchOptions); + } + core.endGroup(); + // Checkout info + core.startGroup('Determining the checkout info'); + const checkoutInfo = yield refHelper.getCheckoutInfo(git, settings.ref, settings.commit); + core.endGroup(); + // LFS fetch + // Explicit lfs-fetch to avoid slow checkout (fetches one lfs object at a time). + // Explicit lfs fetch will fetch lfs objects in parallel. + // For sparse checkouts, let `checkout` fetch the needed objects lazily. + if (settings.lfs && !settings.sparseCheckout) { + core.startGroup('Fetching LFS objects'); + yield git.lfsFetch(checkoutInfo.startPoint || checkoutInfo.ref); + core.endGroup(); + } + // Sparse checkout + if (settings.sparseCheckout) { + core.startGroup('Setting up sparse checkout'); + if (settings.sparseCheckoutConeMode) { + yield git.sparseCheckout(settings.sparseCheckout); + } + else { + yield git.sparseCheckoutNonConeMode(settings.sparseCheckout); + } + core.endGroup(); + } + // Checkout + core.startGroup('Checking out the ref'); + yield git.checkout(checkoutInfo.ref, checkoutInfo.startPoint); + core.endGroup(); + // Submodules + if (settings.submodules) { + // Temporarily override global config + core.startGroup('Setting up auth for fetching submodules'); + yield authHelper.configureGlobalAuth(); + core.endGroup(); + // Checkout submodules + core.startGroup('Fetching submodules'); + yield git.submoduleSync(settings.nestedSubmodules); + yield git.submoduleUpdate(settings.fetchDepth, settings.nestedSubmodules); + yield git.submoduleForeach('git config --local gc.auto 0', settings.nestedSubmodules); + core.endGroup(); + // Persist credentials + if (settings.persistCredentials) { + core.startGroup('Persisting credentials for submodules'); + yield authHelper.configureSubmoduleAuth(); + core.endGroup(); + } + } + // Get commit information + const commitInfo = yield git.log1(); + // Log commit sha + yield git.log1("--format='%H'"); + // Check for incorrect pull request merge commit + yield refHelper.checkCommitInfo(settings.authToken, commitInfo, settings.repositoryOwner, settings.repositoryName, settings.ref, settings.commit, settings.githubServerUrl); + } + finally { + // Remove auth + if (authHelper) { + if (!settings.persistCredentials) { + core.startGroup('Removing auth'); + yield authHelper.removeAuth(); + core.endGroup(); + } + authHelper.removeGlobalConfig(); + } + } + }); +} +exports.getSource = getSource; +function cleanup(repositoryPath) { + return __awaiter(this, void 0, void 0, function* () { + // Repo exists? + if (!repositoryPath || + !fsHelper.fileExistsSync(path.join(repositoryPath, '.git', 'config'))) { + return; + } + let git; + try { + git = yield gitCommandManager.createCommandManager(repositoryPath, false, false); + } + catch (_a) { + return; + } + // Remove auth + const authHelper = gitAuthHelper.createAuthHelper(git); + try { + if (stateHelper.PostSetSafeDirectory) { + // Setup the repository path as a safe directory, so if we pass this into a container job with a different user it doesn't fail + // Otherwise all git commands we run in a container fail + yield authHelper.configureTempGlobalConfig(); + core.info(`Adding repository directory to the temporary git global config as a safe directory`); + yield git + .config('safe.directory', repositoryPath, true, true) + .catch(error => { + core.info(`Failed to initialize safe directory with error: ${error}`); + }); + } + yield authHelper.removeAuth(); + } + finally { + yield authHelper.removeGlobalConfig(); + } + }); +} +exports.cleanup = cleanup; +function getGitCommandManager(settings) { + return __awaiter(this, void 0, void 0, function* () { + core.info(`Working directory is '${settings.repositoryPath}'`); + try { + return yield gitCommandManager.createCommandManager(settings.repositoryPath, settings.lfs, settings.sparseCheckout != null); + } + catch (err) { + // Git is required for LFS + if (settings.lfs) { + throw err; + } + // Otherwise fallback to REST API + return undefined; + } + }); +} /***/ }), @@ -1392,78 +1392,78 @@ function getGitCommandManager(settings) { /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.GitVersion = void 0; -class GitVersion { - /** - * Used for comparing the version of git and git-lfs against the minimum required version - * @param version the version string, e.g. 1.2 or 1.2.3 - */ - constructor(version) { - this.major = NaN; - this.minor = NaN; - this.patch = NaN; - if (version) { - const match = version.match(/^(\d+)\.(\d+)(\.(\d+))?$/); - if (match) { - this.major = Number(match[1]); - this.minor = Number(match[2]); - if (match[4]) { - this.patch = Number(match[4]); - } - } - } - } - /** - * Compares the instance against a minimum required version - * @param minimum Minimum version - */ - checkMinimum(minimum) { - if (!minimum.isValid()) { - throw new Error('Arg minimum is not a valid version'); - } - // Major is insufficient - if (this.major < minimum.major) { - return false; - } - // Major is equal - if (this.major === minimum.major) { - // Minor is insufficient - if (this.minor < minimum.minor) { - return false; - } - // Minor is equal - if (this.minor === minimum.minor) { - // Patch is insufficient - if (this.patch && this.patch < (minimum.patch || 0)) { - return false; - } - } - } - return true; - } - /** - * Indicates whether the instance was constructed from a valid version string - */ - isValid() { - return !isNaN(this.major); - } - /** - * Returns the version as a string, e.g. 1.2 or 1.2.3 - */ - toString() { - let result = ''; - if (this.isValid()) { - result = `${this.major}.${this.minor}`; - if (!isNaN(this.patch)) { - result += `.${this.patch}`; - } - } - return result; - } -} -exports.GitVersion = GitVersion; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GitVersion = void 0; +class GitVersion { + /** + * Used for comparing the version of git and git-lfs against the minimum required version + * @param version the version string, e.g. 1.2 or 1.2.3 + */ + constructor(version) { + this.major = NaN; + this.minor = NaN; + this.patch = NaN; + if (version) { + const match = version.match(/^(\d+)\.(\d+)(\.(\d+))?$/); + if (match) { + this.major = Number(match[1]); + this.minor = Number(match[2]); + if (match[4]) { + this.patch = Number(match[4]); + } + } + } + } + /** + * Compares the instance against a minimum required version + * @param minimum Minimum version + */ + checkMinimum(minimum) { + if (!minimum.isValid()) { + throw new Error('Arg minimum is not a valid version'); + } + // Major is insufficient + if (this.major < minimum.major) { + return false; + } + // Major is equal + if (this.major === minimum.major) { + // Minor is insufficient + if (this.minor < minimum.minor) { + return false; + } + // Minor is equal + if (this.minor === minimum.minor) { + // Patch is insufficient + if (this.patch && this.patch < (minimum.patch || 0)) { + return false; + } + } + } + return true; + } + /** + * Indicates whether the instance was constructed from a valid version string + */ + isValid() { + return !isNaN(this.major); + } + /** + * Returns the version as a string, e.g. 1.2 or 1.2.3 + */ + toString() { + let result = ''; + if (this.isValid()) { + result = `${this.major}.${this.minor}`; + if (!isNaN(this.patch)) { + result += `.${this.patch}`; + } + } + return result; + } +} +exports.GitVersion = GitVersion; /***/ }), @@ -1472,158 +1472,158 @@ exports.GitVersion = GitVersion; /***/ (function(__unused_webpack_module, exports, __nccwpck_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()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getDefaultBranch = exports.downloadRepository = void 0; -const assert = __importStar(__nccwpck_require__(9491)); -const core = __importStar(__nccwpck_require__(2186)); -const fs = __importStar(__nccwpck_require__(7147)); -const github = __importStar(__nccwpck_require__(5438)); -const io = __importStar(__nccwpck_require__(7436)); -const path = __importStar(__nccwpck_require__(1017)); -const retryHelper = __importStar(__nccwpck_require__(2155)); -const toolCache = __importStar(__nccwpck_require__(7784)); -const v4_1 = __importDefault(__nccwpck_require__(824)); -const url_helper_1 = __nccwpck_require__(9437); -const IS_WINDOWS = process.platform === 'win32'; -function downloadRepository(authToken, owner, repo, ref, commit, repositoryPath, baseUrl) { - return __awaiter(this, void 0, void 0, function* () { - // Determine the default branch - if (!ref && !commit) { - core.info('Determining the default branch'); - ref = yield getDefaultBranch(authToken, owner, repo, baseUrl); - } - // Download the archive - let archiveData = yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () { - core.info('Downloading the archive'); - return yield downloadArchive(authToken, owner, repo, ref, commit, baseUrl); - })); - // Write archive to disk - core.info('Writing archive to disk'); - const uniqueId = (0, v4_1.default)(); - const archivePath = path.join(repositoryPath, `${uniqueId}.tar.gz`); - yield fs.promises.writeFile(archivePath, archiveData); - archiveData = Buffer.from(''); // Free memory - // Extract archive - core.info('Extracting the archive'); - const extractPath = path.join(repositoryPath, uniqueId); - yield io.mkdirP(extractPath); - if (IS_WINDOWS) { - yield toolCache.extractZip(archivePath, extractPath); - } - else { - yield toolCache.extractTar(archivePath, extractPath); - } - yield io.rmRF(archivePath); - // Determine the path of the repository content. The archive contains - // a top-level folder and the repository content is inside. - const archiveFileNames = yield fs.promises.readdir(extractPath); - assert.ok(archiveFileNames.length == 1, 'Expected exactly one directory inside archive'); - const archiveVersion = archiveFileNames[0]; // The top-level folder name includes the short SHA - core.info(`Resolved version ${archiveVersion}`); - const tempRepositoryPath = path.join(extractPath, archiveVersion); - // Move the files - for (const fileName of yield fs.promises.readdir(tempRepositoryPath)) { - const sourcePath = path.join(tempRepositoryPath, fileName); - const targetPath = path.join(repositoryPath, fileName); - if (IS_WINDOWS) { - yield io.cp(sourcePath, targetPath, { recursive: true }); // Copy on Windows (Windows Defender may have a lock) - } - else { - yield io.mv(sourcePath, targetPath); - } - } - yield io.rmRF(extractPath); - }); -} -exports.downloadRepository = downloadRepository; -/** - * Looks up the default branch name - */ -function getDefaultBranch(authToken, owner, repo, baseUrl) { - return __awaiter(this, void 0, void 0, function* () { - return yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () { - var _a; - core.info('Retrieving the default branch name'); - const octokit = github.getOctokit(authToken, { - baseUrl: (0, url_helper_1.getServerApiUrl)(baseUrl) - }); - let result; - try { - // Get the default branch from the repo info - const response = yield octokit.rest.repos.get({ owner, repo }); - result = response.data.default_branch; - assert.ok(result, 'default_branch cannot be empty'); - } - catch (err) { - // Handle .wiki repo - if (((_a = err) === null || _a === void 0 ? void 0 : _a.status) === 404 && - repo.toUpperCase().endsWith('.WIKI')) { - result = 'master'; - } - // Otherwise error - else { - throw err; - } - } - // Print the default branch - core.info(`Default branch '${result}'`); - // Prefix with 'refs/heads' - if (!result.startsWith('refs/')) { - result = `refs/heads/${result}`; - } - return result; - })); - }); -} -exports.getDefaultBranch = getDefaultBranch; -function downloadArchive(authToken, owner, repo, ref, commit, baseUrl) { - return __awaiter(this, void 0, void 0, function* () { - const octokit = github.getOctokit(authToken, { - baseUrl: (0, url_helper_1.getServerApiUrl)(baseUrl) - }); - const download = IS_WINDOWS - ? octokit.rest.repos.downloadZipballArchive - : octokit.rest.repos.downloadTarballArchive; - const response = yield download({ - owner: owner, - repo: repo, - ref: commit || ref - }); - return Buffer.from(response.data); // response.data is ArrayBuffer - }); -} + +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()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getDefaultBranch = exports.downloadRepository = void 0; +const assert = __importStar(__nccwpck_require__(9491)); +const core = __importStar(__nccwpck_require__(2186)); +const fs = __importStar(__nccwpck_require__(7147)); +const github = __importStar(__nccwpck_require__(5438)); +const io = __importStar(__nccwpck_require__(7436)); +const path = __importStar(__nccwpck_require__(1017)); +const retryHelper = __importStar(__nccwpck_require__(2155)); +const toolCache = __importStar(__nccwpck_require__(7784)); +const v4_1 = __importDefault(__nccwpck_require__(824)); +const url_helper_1 = __nccwpck_require__(9437); +const IS_WINDOWS = process.platform === 'win32'; +function downloadRepository(authToken, owner, repo, ref, commit, repositoryPath, baseUrl) { + return __awaiter(this, void 0, void 0, function* () { + // Determine the default branch + if (!ref && !commit) { + core.info('Determining the default branch'); + ref = yield getDefaultBranch(authToken, owner, repo, baseUrl); + } + // Download the archive + let archiveData = yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () { + core.info('Downloading the archive'); + return yield downloadArchive(authToken, owner, repo, ref, commit, baseUrl); + })); + // Write archive to disk + core.info('Writing archive to disk'); + const uniqueId = (0, v4_1.default)(); + const archivePath = path.join(repositoryPath, `${uniqueId}.tar.gz`); + yield fs.promises.writeFile(archivePath, archiveData); + archiveData = Buffer.from(''); // Free memory + // Extract archive + core.info('Extracting the archive'); + const extractPath = path.join(repositoryPath, uniqueId); + yield io.mkdirP(extractPath); + if (IS_WINDOWS) { + yield toolCache.extractZip(archivePath, extractPath); + } + else { + yield toolCache.extractTar(archivePath, extractPath); + } + yield io.rmRF(archivePath); + // Determine the path of the repository content. The archive contains + // a top-level folder and the repository content is inside. + const archiveFileNames = yield fs.promises.readdir(extractPath); + assert.ok(archiveFileNames.length == 1, 'Expected exactly one directory inside archive'); + const archiveVersion = archiveFileNames[0]; // The top-level folder name includes the short SHA + core.info(`Resolved version ${archiveVersion}`); + const tempRepositoryPath = path.join(extractPath, archiveVersion); + // Move the files + for (const fileName of yield fs.promises.readdir(tempRepositoryPath)) { + const sourcePath = path.join(tempRepositoryPath, fileName); + const targetPath = path.join(repositoryPath, fileName); + if (IS_WINDOWS) { + yield io.cp(sourcePath, targetPath, { recursive: true }); // Copy on Windows (Windows Defender may have a lock) + } + else { + yield io.mv(sourcePath, targetPath); + } + } + yield io.rmRF(extractPath); + }); +} +exports.downloadRepository = downloadRepository; +/** + * Looks up the default branch name + */ +function getDefaultBranch(authToken, owner, repo, baseUrl) { + return __awaiter(this, void 0, void 0, function* () { + return yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () { + var _a; + core.info('Retrieving the default branch name'); + const octokit = github.getOctokit(authToken, { + baseUrl: (0, url_helper_1.getServerApiUrl)(baseUrl) + }); + let result; + try { + // Get the default branch from the repo info + const response = yield octokit.rest.repos.get({ owner, repo }); + result = response.data.default_branch; + assert.ok(result, 'default_branch cannot be empty'); + } + catch (err) { + // Handle .wiki repo + if (((_a = err) === null || _a === void 0 ? void 0 : _a.status) === 404 && + repo.toUpperCase().endsWith('.WIKI')) { + result = 'master'; + } + // Otherwise error + else { + throw err; + } + } + // Print the default branch + core.info(`Default branch '${result}'`); + // Prefix with 'refs/heads' + if (!result.startsWith('refs/')) { + result = `refs/heads/${result}`; + } + return result; + })); + }); +} +exports.getDefaultBranch = getDefaultBranch; +function downloadArchive(authToken, owner, repo, ref, commit, baseUrl) { + return __awaiter(this, void 0, void 0, function* () { + const octokit = github.getOctokit(authToken, { + baseUrl: (0, url_helper_1.getServerApiUrl)(baseUrl) + }); + const download = IS_WINDOWS + ? octokit.rest.repos.downloadZipballArchive + : octokit.rest.repos.downloadTarballArchive; + const response = yield download({ + owner: owner, + repo: repo, + ref: commit || ref + }); + return Buffer.from(response.data); // response.data is ArrayBuffer + }); +} /***/ }), @@ -1632,158 +1632,158 @@ function downloadArchive(authToken, owner, repo, ref, commit, baseUrl) { /***/ (function(__unused_webpack_module, exports, __nccwpck_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.getInputs = void 0; -const core = __importStar(__nccwpck_require__(2186)); -const fsHelper = __importStar(__nccwpck_require__(7219)); -const github = __importStar(__nccwpck_require__(5438)); -const path = __importStar(__nccwpck_require__(1017)); -const workflowContextHelper = __importStar(__nccwpck_require__(9568)); -function getInputs() { - 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}`); - // Sparse checkout - const sparseCheckout = core.getMultilineInput('sparse-checkout'); - if (sparseCheckout.length) { - result.sparseCheckout = sparseCheckout; - core.debug(`sparse checkout = ${result.sparseCheckout}`); - } - result.sparseCheckoutConeMode = - (core.getInput('sparse-checkout-cone-mode') || 'true').toUpperCase() === - 'TRUE'; - // 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}`); - // Fetch tags - result.fetchTags = - (core.getInput('fetch-tags') || 'false').toUpperCase() === 'TRUE'; - core.debug(`fetch tags = ${result.fetchTags}`); - // Show fetch progress - result.showProgress = - (core.getInput('show-progress') || 'true').toUpperCase() === 'TRUE'; - core.debug(`show progress = ${result.showProgress}`); - // 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(); - // Set safe.directory in git global config. - result.setSafeDirectory = - (core.getInput('set-safe-directory') || 'true').toUpperCase() === 'TRUE'; - // Determine the GitHub URL that the repository is being hosted from - result.githubServerUrl = core.getInput('github-server-url'); - core.debug(`GitHub Host URL = ${result.githubServerUrl}`); - return result; - }); -} -exports.getInputs = getInputs; + +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.getInputs = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const fsHelper = __importStar(__nccwpck_require__(7219)); +const github = __importStar(__nccwpck_require__(5438)); +const path = __importStar(__nccwpck_require__(1017)); +const workflowContextHelper = __importStar(__nccwpck_require__(9568)); +function getInputs() { + return __awaiter(this, void 0, void 0, function* () { + const result = {}; + // Working directory + let workingDirectory = core.getInput('workingDirectory') || process.env['GITHUB_WORKSPACE']; + if (!workingDirectory) { + throw new Error('working dir not defined'); + } + workingDirectory = path.resolve(workingDirectory); + core.debug(`working directory = '${workingDirectory}'`); + fsHelper.directoryExistsSync(workingDirectory, 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(workingDirectory, result.repositoryPath); + if (!(result.repositoryPath + path.sep).startsWith(workingDirectory + path.sep)) { + throw new Error(`Repository path '${result.repositoryPath}' is not under '${workingDirectory}'`); + } + // 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}`); + // Sparse checkout + const sparseCheckout = core.getMultilineInput('sparse-checkout'); + if (sparseCheckout.length) { + result.sparseCheckout = sparseCheckout; + core.debug(`sparse checkout = ${result.sparseCheckout}`); + } + result.sparseCheckoutConeMode = + (core.getInput('sparse-checkout-cone-mode') || 'true').toUpperCase() === + 'TRUE'; + // 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}`); + // Fetch tags + result.fetchTags = + (core.getInput('fetch-tags') || 'false').toUpperCase() === 'TRUE'; + core.debug(`fetch tags = ${result.fetchTags}`); + // Show fetch progress + result.showProgress = + (core.getInput('show-progress') || 'true').toUpperCase() === 'TRUE'; + core.debug(`show progress = ${result.showProgress}`); + // 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(); + // Set safe.directory in git global config. + result.setSafeDirectory = + (core.getInput('set-safe-directory') || 'true').toUpperCase() === 'TRUE'; + // Determine the GitHub URL that the repository is being hosted from + result.githubServerUrl = core.getInput('github-server-url'); + core.debug(`GitHub Host URL = ${result.githubServerUrl}`); + return result; + }); +} +exports.getInputs = getInputs; /***/ }), @@ -1792,82 +1792,82 @@ exports.getInputs = getInputs; /***/ (function(__unused_webpack_module, exports, __nccwpck_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 })); -const core = __importStar(__nccwpck_require__(2186)); -const coreCommand = __importStar(__nccwpck_require__(7351)); -const gitSourceProvider = __importStar(__nccwpck_require__(9210)); -const inputHelper = __importStar(__nccwpck_require__(5480)); -const path = __importStar(__nccwpck_require__(1017)); -const stateHelper = __importStar(__nccwpck_require__(8647)); -function run() { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - try { - const sourceSettings = yield inputHelper.getInputs(); - try { - // Register problem matcher - coreCommand.issueCommand('add-matcher', {}, path.join(__dirname, 'problem-matcher.json')); - // Get sources - yield gitSourceProvider.getSource(sourceSettings); - } - finally { - // Unregister problem matcher - coreCommand.issueCommand('remove-matcher', { owner: 'checkout-git' }, ''); - } - } - catch (error) { - core.setFailed(`${(_b = (_a = error) === null || _a === void 0 ? void 0 : _a.message) !== null && _b !== void 0 ? _b : error}`); - } - }); -} -function cleanup() { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - try { - yield gitSourceProvider.cleanup(stateHelper.RepositoryPath); - } - catch (error) { - core.warning(`${(_b = (_a = error) === null || _a === void 0 ? void 0 : _a.message) !== null && _b !== void 0 ? _b : error}`); - } - }); -} -// Main -if (!stateHelper.IsPost) { - run(); -} -// Post -else { - cleanup(); -} + +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 })); +const core = __importStar(__nccwpck_require__(2186)); +const coreCommand = __importStar(__nccwpck_require__(7351)); +const gitSourceProvider = __importStar(__nccwpck_require__(9210)); +const inputHelper = __importStar(__nccwpck_require__(5480)); +const path = __importStar(__nccwpck_require__(1017)); +const stateHelper = __importStar(__nccwpck_require__(8647)); +function run() { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + try { + const sourceSettings = yield inputHelper.getInputs(); + try { + // Register problem matcher + coreCommand.issueCommand('add-matcher', {}, path.join(__dirname, 'problem-matcher.json')); + // Get sources + yield gitSourceProvider.getSource(sourceSettings); + } + finally { + // Unregister problem matcher + coreCommand.issueCommand('remove-matcher', { owner: 'checkout-git' }, ''); + } + } + catch (error) { + core.setFailed(`${(_b = (_a = error) === null || _a === void 0 ? void 0 : _a.message) !== null && _b !== void 0 ? _b : error}`); + } + }); +} +function cleanup() { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + try { + yield gitSourceProvider.cleanup(stateHelper.RepositoryPath); + } + catch (error) { + core.warning(`${(_b = (_a = error) === null || _a === void 0 ? void 0 : _a.message) !== null && _b !== void 0 ? _b : error}`); + } + }); +} +// Main +if (!stateHelper.IsPost) { + run(); +} +// Post +else { + cleanup(); +} /***/ }), @@ -1876,269 +1876,269 @@ else { /***/ (function(__unused_webpack_module, exports, __nccwpck_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.checkCommitInfo = exports.testRef = exports.getRefSpec = exports.getRefSpecForAllHistory = exports.getCheckoutInfo = exports.tagsRefSpec = void 0; -const core = __importStar(__nccwpck_require__(2186)); -const github = __importStar(__nccwpck_require__(5438)); -const url_helper_1 = __nccwpck_require__(9437); -exports.tagsRefSpec = '+refs/tags/*:refs/tags/*'; -function getCheckoutInfo(git, ref, commit) { - return __awaiter(this, void 0, void 0, function* () { - if (!git) { - throw new Error('Arg git cannot be empty'); - } - if (!ref && !commit) { - throw new Error('Args ref and commit cannot both be empty'); - } - const result = {}; - const upperRef = (ref || '').toUpperCase(); - // SHA only - if (!ref) { - result.ref = commit; - } - // refs/heads/ - else if (upperRef.startsWith('REFS/HEADS/')) { - const branch = ref.substring('refs/heads/'.length); - result.ref = branch; - result.startPoint = `refs/remotes/origin/${branch}`; - } - // refs/pull/ - else if (upperRef.startsWith('REFS/PULL/')) { - const branch = ref.substring('refs/pull/'.length); - result.ref = `refs/remotes/pull/${branch}`; - } - // refs/tags/ - else if (upperRef.startsWith('REFS/')) { - result.ref = ref; - } - // Unqualified ref, check for a matching branch or tag - else { - if (yield git.branchExists(true, `origin/${ref}`)) { - result.ref = ref; - result.startPoint = `refs/remotes/origin/${ref}`; - } - else if (yield git.tagExists(`${ref}`)) { - result.ref = `refs/tags/${ref}`; - } - else { - throw new Error(`A branch or tag with the name '${ref}' could not be found`); - } - } - return result; - }); -} -exports.getCheckoutInfo = getCheckoutInfo; -function getRefSpecForAllHistory(ref, commit) { - const result = ['+refs/heads/*:refs/remotes/origin/*', exports.tagsRefSpec]; - if (ref && ref.toUpperCase().startsWith('REFS/PULL/')) { - const branch = ref.substring('refs/pull/'.length); - result.push(`+${commit || ref}:refs/remotes/pull/${branch}`); - } - return result; -} -exports.getRefSpecForAllHistory = getRefSpecForAllHistory; -function getRefSpec(ref, commit) { - if (!ref && !commit) { - throw new Error('Args ref and commit cannot both be empty'); - } - const upperRef = (ref || '').toUpperCase(); - // SHA - if (commit) { - // refs/heads - if (upperRef.startsWith('REFS/HEADS/')) { - const branch = ref.substring('refs/heads/'.length); - return [`+${commit}:refs/remotes/origin/${branch}`]; - } - // refs/pull/ - else if (upperRef.startsWith('REFS/PULL/')) { - const branch = ref.substring('refs/pull/'.length); - return [`+${commit}:refs/remotes/pull/${branch}`]; - } - // refs/tags/ - else if (upperRef.startsWith('REFS/TAGS/')) { - return [`+${commit}:${ref}`]; - } - // Otherwise no destination ref - else { - return [commit]; - } - } - // Unqualified ref, check for a matching branch or tag - else if (!upperRef.startsWith('REFS/')) { - return [ - `+refs/heads/${ref}*:refs/remotes/origin/${ref}*`, - `+refs/tags/${ref}*:refs/tags/${ref}*` - ]; - } - // refs/heads/ - else if (upperRef.startsWith('REFS/HEADS/')) { - const branch = ref.substring('refs/heads/'.length); - return [`+${ref}:refs/remotes/origin/${branch}`]; - } - // refs/pull/ - else if (upperRef.startsWith('REFS/PULL/')) { - const branch = ref.substring('refs/pull/'.length); - return [`+${ref}:refs/remotes/pull/${branch}`]; - } - // refs/tags/ - else { - return [`+${ref}:${ref}`]; - } -} -exports.getRefSpec = getRefSpec; -/** - * Tests whether the initial fetch created the ref at the expected commit - */ -function testRef(git, ref, commit) { - return __awaiter(this, void 0, void 0, function* () { - if (!git) { - throw new Error('Arg git cannot be empty'); - } - if (!ref && !commit) { - throw new Error('Args ref and commit cannot both be empty'); - } - // No SHA? Nothing to test - if (!commit) { - return true; - } - // SHA only? - else if (!ref) { - return yield git.shaExists(commit); - } - const upperRef = ref.toUpperCase(); - // refs/heads/ - if (upperRef.startsWith('REFS/HEADS/')) { - const branch = ref.substring('refs/heads/'.length); - return ((yield git.branchExists(true, `origin/${branch}`)) && - commit === (yield git.revParse(`refs/remotes/origin/${branch}`))); - } - // refs/pull/ - else if (upperRef.startsWith('REFS/PULL/')) { - // Assume matches because fetched using the commit - return true; - } - // refs/tags/ - else if (upperRef.startsWith('REFS/TAGS/')) { - const tagName = ref.substring('refs/tags/'.length); - return ((yield git.tagExists(tagName)) && commit === (yield git.revParse(ref))); - } - // Unexpected - else { - core.debug(`Unexpected ref format '${ref}' when testing ref info`); - return true; - } - }); -} -exports.testRef = testRef; -function checkCommitInfo(token, commitInfo, repositoryOwner, repositoryName, ref, commit, baseUrl) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - try { - // GHES? - if ((0, url_helper_1.isGhes)(baseUrl)) { - return; - } - // Auth token? - if (!token) { - return; - } - // Public PR synchronize, for workflow repo? - if (fromPayload('repository.private') !== false || - github.context.eventName !== 'pull_request' || - fromPayload('action') !== 'synchronize' || - repositoryOwner !== github.context.repo.owner || - repositoryName !== github.context.repo.repo || - ref !== github.context.ref || - !ref.startsWith('refs/pull/') || - commit !== github.context.sha) { - return; - } - // Head SHA - const expectedHeadSha = fromPayload('after'); - if (!expectedHeadSha) { - core.debug('Unable to determine head sha'); - return; - } - // Base SHA - const expectedBaseSha = fromPayload('pull_request.base.sha'); - if (!expectedBaseSha) { - core.debug('Unable to determine base sha'); - return; - } - // Expected message? - const expectedMessage = `Merge ${expectedHeadSha} into ${expectedBaseSha}`; - if (commitInfo.indexOf(expectedMessage) >= 0) { - return; - } - // Extract details from message - const match = commitInfo.match(/Merge ([0-9a-f]{40}) into ([0-9a-f]{40})/); - if (!match) { - core.debug('Unexpected message format'); - return; - } - // Post telemetry - const actualHeadSha = match[1]; - if (actualHeadSha !== expectedHeadSha) { - core.debug(`Expected head sha ${expectedHeadSha}; actual head sha ${actualHeadSha}`); - const octokit = github.getOctokit(token, { - baseUrl: (0, url_helper_1.getServerApiUrl)(baseUrl), - userAgent: `actions-checkout-tracepoint/1.0 (code=STALE_MERGE;owner=${repositoryOwner};repo=${repositoryName};pr=${fromPayload('number')};run_id=${process.env['GITHUB_RUN_ID']};expected_head_sha=${expectedHeadSha};actual_head_sha=${actualHeadSha})` - }); - yield octokit.rest.repos.get({ - owner: repositoryOwner, - repo: repositoryName - }); - } - } - catch (err) { - core.debug(`Error when validating commit info: ${(_b = (_a = err) === null || _a === void 0 ? void 0 : _a.stack) !== null && _b !== void 0 ? _b : err}`); - } - }); -} -exports.checkCommitInfo = checkCommitInfo; -function fromPayload(path) { - return select(github.context.payload, path); -} -function select(obj, path) { - if (!obj) { - return undefined; - } - const i = path.indexOf('.'); - if (i < 0) { - return obj[path]; - } - const key = path.substr(0, i); - return select(obj[key], path.substr(i + 1)); -} + +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.checkCommitInfo = exports.testRef = exports.getRefSpec = exports.getRefSpecForAllHistory = exports.getCheckoutInfo = exports.tagsRefSpec = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const github = __importStar(__nccwpck_require__(5438)); +const url_helper_1 = __nccwpck_require__(9437); +exports.tagsRefSpec = '+refs/tags/*:refs/tags/*'; +function getCheckoutInfo(git, ref, commit) { + return __awaiter(this, void 0, void 0, function* () { + if (!git) { + throw new Error('Arg git cannot be empty'); + } + if (!ref && !commit) { + throw new Error('Args ref and commit cannot both be empty'); + } + const result = {}; + const upperRef = (ref || '').toUpperCase(); + // SHA only + if (!ref) { + result.ref = commit; + } + // refs/heads/ + else if (upperRef.startsWith('REFS/HEADS/')) { + const branch = ref.substring('refs/heads/'.length); + result.ref = branch; + result.startPoint = `refs/remotes/origin/${branch}`; + } + // refs/pull/ + else if (upperRef.startsWith('REFS/PULL/')) { + const branch = ref.substring('refs/pull/'.length); + result.ref = `refs/remotes/pull/${branch}`; + } + // refs/tags/ + else if (upperRef.startsWith('REFS/')) { + result.ref = ref; + } + // Unqualified ref, check for a matching branch or tag + else { + if (yield git.branchExists(true, `origin/${ref}`)) { + result.ref = ref; + result.startPoint = `refs/remotes/origin/${ref}`; + } + else if (yield git.tagExists(`${ref}`)) { + result.ref = `refs/tags/${ref}`; + } + else { + throw new Error(`A branch or tag with the name '${ref}' could not be found`); + } + } + return result; + }); +} +exports.getCheckoutInfo = getCheckoutInfo; +function getRefSpecForAllHistory(ref, commit) { + const result = ['+refs/heads/*:refs/remotes/origin/*', exports.tagsRefSpec]; + if (ref && ref.toUpperCase().startsWith('REFS/PULL/')) { + const branch = ref.substring('refs/pull/'.length); + result.push(`+${commit || ref}:refs/remotes/pull/${branch}`); + } + return result; +} +exports.getRefSpecForAllHistory = getRefSpecForAllHistory; +function getRefSpec(ref, commit) { + if (!ref && !commit) { + throw new Error('Args ref and commit cannot both be empty'); + } + const upperRef = (ref || '').toUpperCase(); + // SHA + if (commit) { + // refs/heads + if (upperRef.startsWith('REFS/HEADS/')) { + const branch = ref.substring('refs/heads/'.length); + return [`+${commit}:refs/remotes/origin/${branch}`]; + } + // refs/pull/ + else if (upperRef.startsWith('REFS/PULL/')) { + const branch = ref.substring('refs/pull/'.length); + return [`+${commit}:refs/remotes/pull/${branch}`]; + } + // refs/tags/ + else if (upperRef.startsWith('REFS/TAGS/')) { + return [`+${commit}:${ref}`]; + } + // Otherwise no destination ref + else { + return [commit]; + } + } + // Unqualified ref, check for a matching branch or tag + else if (!upperRef.startsWith('REFS/')) { + return [ + `+refs/heads/${ref}*:refs/remotes/origin/${ref}*`, + `+refs/tags/${ref}*:refs/tags/${ref}*` + ]; + } + // refs/heads/ + else if (upperRef.startsWith('REFS/HEADS/')) { + const branch = ref.substring('refs/heads/'.length); + return [`+${ref}:refs/remotes/origin/${branch}`]; + } + // refs/pull/ + else if (upperRef.startsWith('REFS/PULL/')) { + const branch = ref.substring('refs/pull/'.length); + return [`+${ref}:refs/remotes/pull/${branch}`]; + } + // refs/tags/ + else { + return [`+${ref}:${ref}`]; + } +} +exports.getRefSpec = getRefSpec; +/** + * Tests whether the initial fetch created the ref at the expected commit + */ +function testRef(git, ref, commit) { + return __awaiter(this, void 0, void 0, function* () { + if (!git) { + throw new Error('Arg git cannot be empty'); + } + if (!ref && !commit) { + throw new Error('Args ref and commit cannot both be empty'); + } + // No SHA? Nothing to test + if (!commit) { + return true; + } + // SHA only? + else if (!ref) { + return yield git.shaExists(commit); + } + const upperRef = ref.toUpperCase(); + // refs/heads/ + if (upperRef.startsWith('REFS/HEADS/')) { + const branch = ref.substring('refs/heads/'.length); + return ((yield git.branchExists(true, `origin/${branch}`)) && + commit === (yield git.revParse(`refs/remotes/origin/${branch}`))); + } + // refs/pull/ + else if (upperRef.startsWith('REFS/PULL/')) { + // Assume matches because fetched using the commit + return true; + } + // refs/tags/ + else if (upperRef.startsWith('REFS/TAGS/')) { + const tagName = ref.substring('refs/tags/'.length); + return ((yield git.tagExists(tagName)) && commit === (yield git.revParse(ref))); + } + // Unexpected + else { + core.debug(`Unexpected ref format '${ref}' when testing ref info`); + return true; + } + }); +} +exports.testRef = testRef; +function checkCommitInfo(token, commitInfo, repositoryOwner, repositoryName, ref, commit, baseUrl) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + try { + // GHES? + if ((0, url_helper_1.isGhes)(baseUrl)) { + return; + } + // Auth token? + if (!token) { + return; + } + // Public PR synchronize, for workflow repo? + if (fromPayload('repository.private') !== false || + github.context.eventName !== 'pull_request' || + fromPayload('action') !== 'synchronize' || + repositoryOwner !== github.context.repo.owner || + repositoryName !== github.context.repo.repo || + ref !== github.context.ref || + !ref.startsWith('refs/pull/') || + commit !== github.context.sha) { + return; + } + // Head SHA + const expectedHeadSha = fromPayload('after'); + if (!expectedHeadSha) { + core.debug('Unable to determine head sha'); + return; + } + // Base SHA + const expectedBaseSha = fromPayload('pull_request.base.sha'); + if (!expectedBaseSha) { + core.debug('Unable to determine base sha'); + return; + } + // Expected message? + const expectedMessage = `Merge ${expectedHeadSha} into ${expectedBaseSha}`; + if (commitInfo.indexOf(expectedMessage) >= 0) { + return; + } + // Extract details from message + const match = commitInfo.match(/Merge ([0-9a-f]{40}) into ([0-9a-f]{40})/); + if (!match) { + core.debug('Unexpected message format'); + return; + } + // Post telemetry + const actualHeadSha = match[1]; + if (actualHeadSha !== expectedHeadSha) { + core.debug(`Expected head sha ${expectedHeadSha}; actual head sha ${actualHeadSha}`); + const octokit = github.getOctokit(token, { + baseUrl: (0, url_helper_1.getServerApiUrl)(baseUrl), + userAgent: `actions-checkout-tracepoint/1.0 (code=STALE_MERGE;owner=${repositoryOwner};repo=${repositoryName};pr=${fromPayload('number')};run_id=${process.env['GITHUB_RUN_ID']};expected_head_sha=${expectedHeadSha};actual_head_sha=${actualHeadSha})` + }); + yield octokit.rest.repos.get({ + owner: repositoryOwner, + repo: repositoryName + }); + } + } + catch (err) { + core.debug(`Error when validating commit info: ${(_b = (_a = err) === null || _a === void 0 ? void 0 : _a.stack) !== null && _b !== void 0 ? _b : err}`); + } + }); +} +exports.checkCommitInfo = checkCommitInfo; +function fromPayload(path) { + return select(github.context.payload, path); +} +function select(obj, path) { + if (!obj) { + return undefined; + } + const i = path.indexOf('.'); + if (i < 0) { + return obj[path]; + } + const key = path.substr(0, i); + return select(obj[key], path.substr(i + 1)); +} /***/ }), @@ -2147,15 +2147,15 @@ function select(obj, path) { /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.escape = void 0; -function escape(value) { - return value.replace(/[^a-zA-Z0-9_]/g, x => { - return `\\${x}`; - }); -} -exports.escape = escape; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.escape = void 0; +function escape(value) { + return value.replace(/[^a-zA-Z0-9_]/g, x => { + return `\\${x}`; + }); +} +exports.escape = escape; /***/ }), @@ -2164,90 +2164,90 @@ exports.escape = escape; /***/ (function(__unused_webpack_module, exports, __nccwpck_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.execute = exports.RetryHelper = void 0; -const core = __importStar(__nccwpck_require__(2186)); -const defaultMaxAttempts = 3; -const defaultMinSeconds = 10; -const defaultMaxSeconds = 20; -class RetryHelper { - constructor(maxAttempts = defaultMaxAttempts, minSeconds = defaultMinSeconds, maxSeconds = defaultMaxSeconds) { - this.maxAttempts = maxAttempts; - this.minSeconds = Math.floor(minSeconds); - this.maxSeconds = Math.floor(maxSeconds); - if (this.minSeconds > this.maxSeconds) { - throw new Error('min seconds should be less than or equal to max seconds'); - } - } - execute(action) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - let attempt = 1; - while (attempt < this.maxAttempts) { - // Try - try { - return yield action(); - } - catch (err) { - core.info((_a = err) === null || _a === void 0 ? void 0 : _a.message); - } - // Sleep - const seconds = this.getSleepAmount(); - core.info(`Waiting ${seconds} seconds before trying again`); - yield this.sleep(seconds); - attempt++; - } - // Last attempt - return yield action(); - }); - } - getSleepAmount() { - return (Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + - this.minSeconds); - } - sleep(seconds) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise(resolve => setTimeout(resolve, seconds * 1000)); - }); - } -} -exports.RetryHelper = RetryHelper; -function execute(action) { - return __awaiter(this, void 0, void 0, function* () { - const retryHelper = new RetryHelper(); - return yield retryHelper.execute(action); - }); -} -exports.execute = execute; + +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.execute = exports.RetryHelper = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const defaultMaxAttempts = 3; +const defaultMinSeconds = 10; +const defaultMaxSeconds = 20; +class RetryHelper { + constructor(maxAttempts = defaultMaxAttempts, minSeconds = defaultMinSeconds, maxSeconds = defaultMaxSeconds) { + this.maxAttempts = maxAttempts; + this.minSeconds = Math.floor(minSeconds); + this.maxSeconds = Math.floor(maxSeconds); + if (this.minSeconds > this.maxSeconds) { + throw new Error('min seconds should be less than or equal to max seconds'); + } + } + execute(action) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + let attempt = 1; + while (attempt < this.maxAttempts) { + // Try + try { + return yield action(); + } + catch (err) { + core.info((_a = err) === null || _a === void 0 ? void 0 : _a.message); + } + // Sleep + const seconds = this.getSleepAmount(); + core.info(`Waiting ${seconds} seconds before trying again`); + yield this.sleep(seconds); + attempt++; + } + // Last attempt + return yield action(); + }); + } + getSleepAmount() { + return (Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + + this.minSeconds); + } + sleep(seconds) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise(resolve => setTimeout(resolve, seconds * 1000)); + }); + } +} +exports.RetryHelper = RetryHelper; +function execute(action) { + return __awaiter(this, void 0, void 0, function* () { + const retryHelper = new RetryHelper(); + return yield retryHelper.execute(action); + }); +} +exports.execute = execute; /***/ }), @@ -2256,82 +2256,82 @@ exports.execute = execute; /***/ (function(__unused_webpack_module, exports, __nccwpck_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; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.setSafeDirectory = exports.setSshKnownHostsPath = exports.setSshKeyPath = exports.setRepositoryPath = exports.SshKnownHostsPath = exports.SshKeyPath = exports.PostSetSafeDirectory = exports.RepositoryPath = exports.IsPost = void 0; -const core = __importStar(__nccwpck_require__(2186)); -/** - * Indicates whether the POST action is running - */ -exports.IsPost = !!core.getState('isPost'); -/** - * The repository path for the POST action. The value is empty during the MAIN action. - */ -exports.RepositoryPath = core.getState('repositoryPath'); -/** - * The set-safe-directory for the POST action. The value is set if input: 'safe-directory' is set during the MAIN action. - */ -exports.PostSetSafeDirectory = core.getState('setSafeDirectory') === 'true'; -/** - * The SSH key path for the POST action. The value is empty during the MAIN action. - */ -exports.SshKeyPath = core.getState('sshKeyPath'); -/** - * The SSH known hosts path for the POST action. The value is empty during the MAIN action. - */ -exports.SshKnownHostsPath = core.getState('sshKnownHostsPath'); -/** - * Save the repository path so the POST action can retrieve the value. - */ -function setRepositoryPath(repositoryPath) { - core.saveState('repositoryPath', repositoryPath); -} -exports.setRepositoryPath = setRepositoryPath; -/** - * Save the SSH key path so the POST action can retrieve the value. - */ -function setSshKeyPath(sshKeyPath) { - core.saveState('sshKeyPath', sshKeyPath); -} -exports.setSshKeyPath = setSshKeyPath; -/** - * Save the SSH known hosts path so the POST action can retrieve the value. - */ -function setSshKnownHostsPath(sshKnownHostsPath) { - core.saveState('sshKnownHostsPath', sshKnownHostsPath); -} -exports.setSshKnownHostsPath = setSshKnownHostsPath; -/** - * Save the set-safe-directory input so the POST action can retrieve the value. - */ -function setSafeDirectory() { - core.saveState('setSafeDirectory', 'true'); -} -exports.setSafeDirectory = setSafeDirectory; -// Publish a variable so that when the POST action runs, it can determine it should run the cleanup logic. -// This is necessary since we don't have a separate entry point. -if (!exports.IsPost) { - core.saveState('isPost', 'true'); -} + +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; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.setSafeDirectory = exports.setSshKnownHostsPath = exports.setSshKeyPath = exports.setRepositoryPath = exports.SshKnownHostsPath = exports.SshKeyPath = exports.PostSetSafeDirectory = exports.RepositoryPath = exports.IsPost = void 0; +const core = __importStar(__nccwpck_require__(2186)); +/** + * Indicates whether the POST action is running + */ +exports.IsPost = !!core.getState('isPost'); +/** + * The repository path for the POST action. The value is empty during the MAIN action. + */ +exports.RepositoryPath = core.getState('repositoryPath'); +/** + * The set-safe-directory for the POST action. The value is set if input: 'safe-directory' is set during the MAIN action. + */ +exports.PostSetSafeDirectory = core.getState('setSafeDirectory') === 'true'; +/** + * The SSH key path for the POST action. The value is empty during the MAIN action. + */ +exports.SshKeyPath = core.getState('sshKeyPath'); +/** + * The SSH known hosts path for the POST action. The value is empty during the MAIN action. + */ +exports.SshKnownHostsPath = core.getState('sshKnownHostsPath'); +/** + * Save the repository path so the POST action can retrieve the value. + */ +function setRepositoryPath(repositoryPath) { + core.saveState('repositoryPath', repositoryPath); +} +exports.setRepositoryPath = setRepositoryPath; +/** + * Save the SSH key path so the POST action can retrieve the value. + */ +function setSshKeyPath(sshKeyPath) { + core.saveState('sshKeyPath', sshKeyPath); +} +exports.setSshKeyPath = setSshKeyPath; +/** + * Save the SSH known hosts path so the POST action can retrieve the value. + */ +function setSshKnownHostsPath(sshKnownHostsPath) { + core.saveState('sshKnownHostsPath', sshKnownHostsPath); +} +exports.setSshKnownHostsPath = setSshKnownHostsPath; +/** + * Save the set-safe-directory input so the POST action can retrieve the value. + */ +function setSafeDirectory() { + core.saveState('setSafeDirectory', 'true'); +} +exports.setSafeDirectory = setSafeDirectory; +// Publish a variable so that when the POST action runs, it can determine it should run the cleanup logic. +// This is necessary since we don't have a separate entry point. +if (!exports.IsPost) { + core.saveState('isPost', 'true'); +} /***/ }), @@ -2340,64 +2340,64 @@ if (!exports.IsPost) { /***/ (function(__unused_webpack_module, exports, __nccwpck_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; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isGhes = exports.getServerApiUrl = exports.getServerUrl = exports.getFetchUrl = void 0; -const assert = __importStar(__nccwpck_require__(9491)); -const url_1 = __nccwpck_require__(7310); -function getFetchUrl(settings) { - assert.ok(settings.repositoryOwner, 'settings.repositoryOwner must be defined'); - assert.ok(settings.repositoryName, 'settings.repositoryName must be defined'); - const serviceUrl = getServerUrl(settings.githubServerUrl); - const encodedOwner = encodeURIComponent(settings.repositoryOwner); - const encodedName = encodeURIComponent(settings.repositoryName); - if (settings.sshKey) { - return `git@${serviceUrl.hostname}:${encodedOwner}/${encodedName}.git`; - } - // "origin" is SCHEME://HOSTNAME[:PORT] - return `${serviceUrl.origin}/${encodedOwner}/${encodedName}`; -} -exports.getFetchUrl = getFetchUrl; -function getServerUrl(url) { - let urlValue = url && url.trim().length > 0 - ? url - : process.env['GITHUB_SERVER_URL'] || 'https://github.com'; - return new url_1.URL(urlValue); -} -exports.getServerUrl = getServerUrl; -function getServerApiUrl(url) { - let apiUrl = 'https://api.github.com'; - if (isGhes(url)) { - const serverUrl = getServerUrl(url); - apiUrl = new url_1.URL(`${serverUrl.origin}/api/v3`).toString(); - } - return apiUrl; -} -exports.getServerApiUrl = getServerApiUrl; -function isGhes(url) { - const ghUrl = getServerUrl(url); - return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; -} -exports.isGhes = isGhes; + +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; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isGhes = exports.getServerApiUrl = exports.getServerUrl = exports.getFetchUrl = void 0; +const assert = __importStar(__nccwpck_require__(9491)); +const url_1 = __nccwpck_require__(7310); +function getFetchUrl(settings) { + assert.ok(settings.repositoryOwner, 'settings.repositoryOwner must be defined'); + assert.ok(settings.repositoryName, 'settings.repositoryName must be defined'); + const serviceUrl = getServerUrl(settings.githubServerUrl); + const encodedOwner = encodeURIComponent(settings.repositoryOwner); + const encodedName = encodeURIComponent(settings.repositoryName); + if (settings.sshKey) { + return `git@${serviceUrl.hostname}:${encodedOwner}/${encodedName}.git`; + } + // "origin" is SCHEME://HOSTNAME[:PORT] + return `${serviceUrl.origin}/${encodedOwner}/${encodedName}`; +} +exports.getFetchUrl = getFetchUrl; +function getServerUrl(url) { + let urlValue = url && url.trim().length > 0 + ? url + : process.env['GITHUB_SERVER_URL'] || 'https://github.com'; + return new url_1.URL(urlValue); +} +exports.getServerUrl = getServerUrl; +function getServerApiUrl(url) { + let apiUrl = 'https://api.github.com'; + if (isGhes(url)) { + const serverUrl = getServerUrl(url); + apiUrl = new url_1.URL(`${serverUrl.origin}/api/v3`).toString(); + } + return apiUrl; +} +exports.getServerApiUrl = getServerApiUrl; +function isGhes(url) { + const ghUrl = getServerUrl(url); + return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; +} +exports.isGhes = isGhes; /***/ }), @@ -2406,67 +2406,67 @@ exports.isGhes = isGhes; /***/ (function(__unused_webpack_module, exports, __nccwpck_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(__nccwpck_require__(2186)); -const fs = __importStar(__nccwpck_require__(7147)); -/** - * 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; + +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(__nccwpck_require__(2186)); +const fs = __importStar(__nccwpck_require__(7147)); +/** + * 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; /***/ }), diff --git a/src/git-source-settings.ts b/src/git-source-settings.ts index 2f80b5e..16d08b1 100644 --- a/src/git-source-settings.ts +++ b/src/git-source-settings.ts @@ -108,4 +108,9 @@ export interface IGitSourceSettings { * User override on the GitHub Server/Host URL that hosts the repository to be cloned */ githubServerUrl: string | undefined + + /** + * User override of the working directory (default is $GITHUB_WORKSPACE) + */ + workingDirectory: string | undefined } diff --git a/src/input-helper.ts b/src/input-helper.ts index be9cecd..bee5c12 100644 --- a/src/input-helper.ts +++ b/src/input-helper.ts @@ -8,14 +8,14 @@ import {IGitSourceSettings} from './git-source-settings' export async function getInputs(): Promise { const result = ({} as unknown) as IGitSourceSettings - // GitHub workspace - let githubWorkspacePath = process.env['GITHUB_WORKSPACE'] - if (!githubWorkspacePath) { - throw new Error('GITHUB_WORKSPACE not defined') + // Working directory + let workingDirectory = core.getInput('workingDirectory') || process.env['GITHUB_WORKSPACE'] + if (!workingDirectory) { + throw new Error('working dir not defined') } - githubWorkspacePath = path.resolve(githubWorkspacePath) - core.debug(`GITHUB_WORKSPACE = '${githubWorkspacePath}'`) - fsHelper.directoryExistsSync(githubWorkspacePath, true) + workingDirectory = path.resolve(workingDirectory) + core.debug(`working directory = '${workingDirectory}'`) + fsHelper.directoryExistsSync(workingDirectory, true) // Qualified repository const qualifiedRepository = @@ -38,16 +38,16 @@ export async function getInputs(): Promise { // Repository path result.repositoryPath = core.getInput('path') || '.' result.repositoryPath = path.resolve( - githubWorkspacePath, + workingDirectory, result.repositoryPath ) if ( !(result.repositoryPath + path.sep).startsWith( - githubWorkspacePath + path.sep + workingDirectory + path.sep ) ) { throw new Error( - `Repository path '${result.repositoryPath}' is not under '${githubWorkspacePath}'` + `Repository path '${result.repositoryPath}' is not under '${workingDirectory}'` ) } From c51e56cd7a9fe39fb46f9265b136653988650f0b Mon Sep 17 00:00:00 2001 From: Marco Accorinti Date: Tue, 19 Sep 2023 18:30:16 +0200 Subject: [PATCH 2/7] update: action.yml Add working-directory input parameter --- action.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/action.yml b/action.yml index 43d408d..2311f58 100644 --- a/action.yml +++ b/action.yml @@ -89,6 +89,9 @@ inputs: github-server-url: description: The base URL for the GitHub instance that you are trying to clone from, will use environment defaults to fetch from the same instance that the workflow is running from unless specified. Example URLs are https://github.com or https://my-ghes-server.example.com required: false + working-directory: + description: Provide the working directory for the git commands to execute into, defaults to $GITHUB_WORKSPACE + required: false runs: using: node20 main: dist/index.js From a0ec92ce0c9953c70e1e32ef57b5bda03098757d Mon Sep 17 00:00:00 2001 From: Marco Accorinti Date: Tue, 19 Sep 2023 18:35:24 +0200 Subject: [PATCH 3/7] fix input name (workingDirectory -> working-directory) --- src/input-helper.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/input-helper.ts b/src/input-helper.ts index bee5c12..4697f65 100644 --- a/src/input-helper.ts +++ b/src/input-helper.ts @@ -9,7 +9,7 @@ export async function getInputs(): Promise { const result = ({} as unknown) as IGitSourceSettings // Working directory - let workingDirectory = core.getInput('workingDirectory') || process.env['GITHUB_WORKSPACE'] + let workingDirectory = core.getInput('working-directory') || process.env['GITHUB_WORKSPACE'] if (!workingDirectory) { throw new Error('working dir not defined') } From ed925880d3a21d0d88fc7b7bd09055cc9d478f25 Mon Sep 17 00:00:00 2001 From: Marco Accorinti Date: Wed, 20 Sep 2023 20:59:18 +0200 Subject: [PATCH 4/7] fix(action.yml): path description Add working-directory --- action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/action.yml b/action.yml index 2311f58..d4732ad 100644 --- a/action.yml +++ b/action.yml @@ -49,7 +49,7 @@ inputs: description: 'Whether to configure the token or SSH key with the local git config' default: true path: - description: 'Relative path under $GITHUB_WORKSPACE to place the repository' + description: 'Relative path under $GITHUB_WORKSPACE/working-directory to place the repository' clean: description: 'Whether to execute `git clean -ffdx && git reset --hard HEAD` before fetching' default: true From b9dc833d4746ca2c6730b7c7663dcfe30e0f95e7 Mon Sep 17 00:00:00 2001 From: Marco Accorinti Date: Wed, 20 Sep 2023 21:00:03 +0200 Subject: [PATCH 5/7] remove(git-source-settings.ts): workingDirectory option Not needed (working-directory option is used internally) --- src/git-source-settings.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/git-source-settings.ts b/src/git-source-settings.ts index 16d08b1..2f80b5e 100644 --- a/src/git-source-settings.ts +++ b/src/git-source-settings.ts @@ -108,9 +108,4 @@ export interface IGitSourceSettings { * User override on the GitHub Server/Host URL that hosts the repository to be cloned */ githubServerUrl: string | undefined - - /** - * User override of the working directory (default is $GITHUB_WORKSPACE) - */ - workingDirectory: string | undefined } From faa95350fe5cd154655b19a752605fc5ca0fd709 Mon Sep 17 00:00:00 2001 From: Marco Accorinti Date: Wed, 20 Sep 2023 21:00:50 +0200 Subject: [PATCH 6/7] update: README.md with new options, descriptions --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7e76cde..af826ef 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ When Git 2.18 or higher is not in your PATH, falls back to the REST API to downl # Default: true persist-credentials: '' - # Relative path under $GITHUB_WORKSPACE to place the repository + # Relative path under $GITHUB_WORKSPACE/working-directory to place the repository path: '' # Whether to execute `git clean -ffdx && git reset --hard HEAD` before fetching @@ -119,6 +119,10 @@ When Git 2.18 or higher is not in your PATH, falls back to the REST API to downl # running from unless specified. Example URLs are https://github.com or # https://my-ghes-server.example.com github-server-url: '' + + # Provide the working directory for the git commands to execute into, defaults to + # $GITHUB_WORKSPACE + working-directory: '' ``` From 53a4183deab8281bfe5e005362c848799dd1fd58 Mon Sep 17 00:00:00 2001 From: Marco Accorinti Date: Wed, 20 Sep 2023 21:02:10 +0200 Subject: [PATCH 7/7] change: remove path.sep, add unit tests, dist Remove path.sep during comparison with repositoryPath (did not take in account root folders) Updated and added more unit tests Updated dist/index.js --- __test__/git-auth-helper.test.ts | 1 - __test__/input-helper.test.ts | 21 +++++++++++++++++++++ dist/index.js | 6 +++--- src/input-helper.ts | 4 ++-- 4 files changed, 26 insertions(+), 6 deletions(-) diff --git a/__test__/git-auth-helper.test.ts b/__test__/git-auth-helper.test.ts index 603376e..f28bff0 100644 --- a/__test__/git-auth-helper.test.ts +++ b/__test__/git-auth-helper.test.ts @@ -821,7 +821,6 @@ async function setup(testName: string): Promise { workflowOrganizationId: 123456, setSafeDirectory: true, githubServerUrl: githubServerUrl, - workingDirectory: undefined } } diff --git a/__test__/input-helper.test.ts b/__test__/input-helper.test.ts index 21932ca..f90eda9 100644 --- a/__test__/input-helper.test.ts +++ b/__test__/input-helper.test.ts @@ -143,4 +143,25 @@ describe('input-helper tests', () => { const settings: IGitSourceSettings = await inputHelper.getInputs() expect(settings.workflowOrganizationId).toBe(123456) }) + + it('sets a different working directory', async() => { + inputs['working-directory'] = '/home/user/test' + inputs['path'] = 'path/to/repo' + const settings: IGitSourceSettings = await inputHelper.getInputs() + expect(settings.repositoryPath).toBe(path.resolve('/home/user/test/path/to/repo')) + }) + + it('sets a working directory on root', async() => { + inputs['working-directory'] = '/' + inputs['path'] = 'path/to/repo' + const settings: IGitSourceSettings = await inputHelper.getInputs() + expect(settings.repositoryPath).toBe(path.resolve('/path/to/repo')) + }) + + it('sets a working directory on root and repository path is set to empty', async() => { + inputs['working-directory'] = '/' + inputs['path'] = '' + const settings: IGitSourceSettings = await inputHelper.getInputs() + expect(settings.repositoryPath).toBe(path.resolve('/')) + }) }) diff --git a/dist/index.js b/dist/index.js index 76c1143..cef2aea 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1672,7 +1672,7 @@ function getInputs() { return __awaiter(this, void 0, void 0, function* () { const result = {}; // Working directory - let workingDirectory = core.getInput('workingDirectory') || process.env['GITHUB_WORKSPACE']; + let workingDirectory = core.getInput('working-directory') || process.env['GITHUB_WORKSPACE']; if (!workingDirectory) { throw new Error('working dir not defined'); } @@ -1694,8 +1694,8 @@ function getInputs() { // Repository path result.repositoryPath = core.getInput('path') || '.'; result.repositoryPath = path.resolve(workingDirectory, result.repositoryPath); - if (!(result.repositoryPath + path.sep).startsWith(workingDirectory + path.sep)) { - throw new Error(`Repository path '${result.repositoryPath}' is not under '${workingDirectory}'`); + if (!(result.repositoryPath + path.sep).startsWith(workingDirectory)) { + throw new Error(`Repository path '${result.repositoryPath + path.sep}' is not under '${workingDirectory}'`); } // Workflow repository? const isWorkflowRepository = qualifiedRepository.toUpperCase() === diff --git a/src/input-helper.ts b/src/input-helper.ts index 4697f65..48e1fae 100644 --- a/src/input-helper.ts +++ b/src/input-helper.ts @@ -43,11 +43,11 @@ export async function getInputs(): Promise { ) if ( !(result.repositoryPath + path.sep).startsWith( - workingDirectory + path.sep + workingDirectory ) ) { throw new Error( - `Repository path '${result.repositoryPath}' is not under '${workingDirectory}'` + `Repository path '${result.repositoryPath + path.sep}' is not under '${workingDirectory}'` ) }