diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 68c7118..15996ee 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -72,6 +72,16 @@ jobs: shell: bash run: __test__/verify-side-by-side.sh + # Filter + - name: Fetch filter + uses: ./ + with: + filter: 'blob:none' + path: fetch-filter + + - name: Verify fetch filter + run: __test__/verify-fetch-filter.sh + # Sparse checkout - name: Sparse checkout uses: ./ diff --git a/CHANGELOG.md b/CHANGELOG.md index 072f267..f2458bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # Changelog +## v4.1.0 +- [Add support for partial checkout filters](https://github.com/actions/checkout/pull/1396) + ## v4.0.0 - [Support fetching without the --progress option](https://github.com/actions/checkout/pull/1067) - [Update to node20](https://github.com/actions/checkout/pull/1436) diff --git a/README.md b/README.md index af826ef..8f3a88a 100644 --- a/README.md +++ b/README.md @@ -75,8 +75,12 @@ When Git 2.18 or higher is not in your PATH, falls back to the REST API to downl # Default: true clean: '' + # Partially clone against a given filter. Overrides sparse-checkout if set. + # Default: null + filter: '' + # Do a sparse checkout on given patterns. Each pattern should be separated with - # new lines + # new lines. # Default: null sparse-checkout: '' diff --git a/__test__/git-auth-helper.test.ts b/__test__/git-auth-helper.test.ts index f28bff0..caabbdd 100644 --- a/__test__/git-auth-helper.test.ts +++ b/__test__/git-auth-helper.test.ts @@ -802,6 +802,7 @@ async function setup(testName: string): Promise { authToken: 'some auth token', clean: true, commit: '', + filter: undefined, sparseCheckout: [], sparseCheckoutConeMode: true, fetchDepth: 1, diff --git a/__test__/input-helper.test.ts b/__test__/input-helper.test.ts index f90eda9..5c79f7a 100644 --- a/__test__/input-helper.test.ts +++ b/__test__/input-helper.test.ts @@ -79,6 +79,7 @@ describe('input-helper tests', () => { expect(settings.clean).toBe(true) expect(settings.commit).toBeTruthy() expect(settings.commit).toBe('1234567890123456789012345678901234567890') + expect(settings.filter).toBe(undefined) expect(settings.sparseCheckout).toBe(undefined) expect(settings.sparseCheckoutConeMode).toBe(true) expect(settings.fetchDepth).toBe(1) diff --git a/__test__/verify-fetch-filter.sh b/__test__/verify-fetch-filter.sh new file mode 100755 index 0000000..4fc9d9e --- /dev/null +++ b/__test__/verify-fetch-filter.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +# Verify .git folder +if [ ! -d "./fetch-filter/.git" ]; then + echo "Expected ./fetch-filter/.git folder to exist" + exit 1 +fi + +# Verify .git/config contains partialclonefilter + +CLONE_FILTER=$(git -C fetch-filter config --local --get remote.origin.partialclonefilter) + +if [ "$CLONE_FILTER" != "blob:none" ]; then + echo "Expected ./fetch-filter/.git/config to have 'remote.origin.partialclonefilter' set to 'blob:none'" + exit 1 +fi diff --git a/action.yml b/action.yml index d4732ad..1e46e38 100644 --- a/action.yml +++ b/action.yml @@ -53,10 +53,15 @@ inputs: clean: description: 'Whether to execute `git clean -ffdx && git reset --hard HEAD` before fetching' default: true + filter: + description: > + Partially clone against a given filter. + Overrides sparse-checkout if set. + default: null sparse-checkout: description: > Do a sparse checkout on given patterns. - Each pattern should be separated with new lines + Each pattern should be separated with new lines. default: null sparse-checkout-cone-mode: description: > diff --git a/dist/index.js b/dist/index.js index cef2aea..14185f9 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,286 @@ 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.filter) { + fetchOptions.filter = settings.filter; + } + else 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 +1396,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 +1476,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 +1636,164 @@ 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 = {}; - // Working directory - let workingDirectory = core.getInput('working-directory') || 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)) { - throw new Error(`Repository path '${result.repositoryPath + path.sep}' 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; + +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('working-directory') || 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)) { + throw new Error(`Repository path '${result.repositoryPath + path.sep}' 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}`); + // Filter + const filter = core.getInput('filter'); + if (filter) { + result.filter = filter; + } + core.debug(`filter = ${result.filter}`); + // 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 +1802,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 +1886,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 +2157,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 +2174,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 +2266,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 +2350,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 +2416,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; /***/ }), @@ -14100,1303 +14110,1303 @@ exports.parseURL = __nccwpck_require__(33).parseURL; /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - -const punycode = __nccwpck_require__(5477); -const tr46 = __nccwpck_require__(2299); - -const specialSchemes = { - ftp: 21, - file: null, - gopher: 70, - http: 80, - https: 443, - ws: 80, - wss: 443 -}; - -const failure = Symbol("failure"); - -function countSymbols(str) { - return punycode.ucs2.decode(str).length; -} - -function at(input, idx) { - const c = input[idx]; - return isNaN(c) ? undefined : String.fromCodePoint(c); -} - -function isASCIIDigit(c) { - return c >= 0x30 && c <= 0x39; -} - -function isASCIIAlpha(c) { - return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); -} - -function isASCIIAlphanumeric(c) { - return isASCIIAlpha(c) || isASCIIDigit(c); -} - -function isASCIIHex(c) { - return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); -} - -function isSingleDot(buffer) { - return buffer === "." || buffer.toLowerCase() === "%2e"; -} - -function isDoubleDot(buffer) { - buffer = buffer.toLowerCase(); - return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; -} - -function isWindowsDriveLetterCodePoints(cp1, cp2) { - return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); -} - -function isWindowsDriveLetterString(string) { - return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); -} - -function isNormalizedWindowsDriveLetterString(string) { - return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; -} - -function containsForbiddenHostCodePoint(string) { - return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; -} - -function containsForbiddenHostCodePointExcludingPercent(string) { - return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; -} - -function isSpecialScheme(scheme) { - return specialSchemes[scheme] !== undefined; -} - -function isSpecial(url) { - return isSpecialScheme(url.scheme); -} - -function defaultPort(scheme) { - return specialSchemes[scheme]; -} - -function percentEncode(c) { - let hex = c.toString(16).toUpperCase(); - if (hex.length === 1) { - hex = "0" + hex; - } - - return "%" + hex; -} - -function utf8PercentEncode(c) { - const buf = new Buffer(c); - - let str = ""; - - for (let i = 0; i < buf.length; ++i) { - str += percentEncode(buf[i]); - } - - return str; -} - -function utf8PercentDecode(str) { - const input = new Buffer(str); - const output = []; - for (let i = 0; i < input.length; ++i) { - if (input[i] !== 37) { - output.push(input[i]); - } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { - output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); - i += 2; - } else { - output.push(input[i]); - } - } - return new Buffer(output).toString(); -} - -function isC0ControlPercentEncode(c) { - return c <= 0x1F || c > 0x7E; -} - -const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); -function isPathPercentEncode(c) { - return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); -} - -const extraUserinfoPercentEncodeSet = - new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); -function isUserinfoPercentEncode(c) { - return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); -} - -function percentEncodeChar(c, encodeSetPredicate) { - const cStr = String.fromCodePoint(c); - - if (encodeSetPredicate(c)) { - return utf8PercentEncode(cStr); - } - - return cStr; -} - -function parseIPv4Number(input) { - let R = 10; - - if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { - input = input.substring(2); - R = 16; - } else if (input.length >= 2 && input.charAt(0) === "0") { - input = input.substring(1); - R = 8; - } - - if (input === "") { - return 0; - } - - const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); - if (regex.test(input)) { - return failure; - } - - return parseInt(input, R); -} - -function parseIPv4(input) { - const parts = input.split("."); - if (parts[parts.length - 1] === "") { - if (parts.length > 1) { - parts.pop(); - } - } - - if (parts.length > 4) { - return input; - } - - const numbers = []; - for (const part of parts) { - if (part === "") { - return input; - } - const n = parseIPv4Number(part); - if (n === failure) { - return input; - } - - numbers.push(n); - } - - for (let i = 0; i < numbers.length - 1; ++i) { - if (numbers[i] > 255) { - return failure; - } - } - if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { - return failure; - } - - let ipv4 = numbers.pop(); - let counter = 0; - - for (const n of numbers) { - ipv4 += n * Math.pow(256, 3 - counter); - ++counter; - } - - return ipv4; -} - -function serializeIPv4(address) { - let output = ""; - let n = address; - - for (let i = 1; i <= 4; ++i) { - output = String(n % 256) + output; - if (i !== 4) { - output = "." + output; - } - n = Math.floor(n / 256); - } - - return output; -} - -function parseIPv6(input) { - const address = [0, 0, 0, 0, 0, 0, 0, 0]; - let pieceIndex = 0; - let compress = null; - let pointer = 0; - - input = punycode.ucs2.decode(input); - - if (input[pointer] === 58) { - if (input[pointer + 1] !== 58) { - return failure; - } - - pointer += 2; - ++pieceIndex; - compress = pieceIndex; - } - - while (pointer < input.length) { - if (pieceIndex === 8) { - return failure; - } - - if (input[pointer] === 58) { - if (compress !== null) { - return failure; - } - ++pointer; - ++pieceIndex; - compress = pieceIndex; - continue; - } - - let value = 0; - let length = 0; - - while (length < 4 && isASCIIHex(input[pointer])) { - value = value * 0x10 + parseInt(at(input, pointer), 16); - ++pointer; - ++length; - } - - if (input[pointer] === 46) { - if (length === 0) { - return failure; - } - - pointer -= length; - - if (pieceIndex > 6) { - return failure; - } - - let numbersSeen = 0; - - while (input[pointer] !== undefined) { - let ipv4Piece = null; - - if (numbersSeen > 0) { - if (input[pointer] === 46 && numbersSeen < 4) { - ++pointer; - } else { - return failure; - } - } - - if (!isASCIIDigit(input[pointer])) { - return failure; - } - - while (isASCIIDigit(input[pointer])) { - const number = parseInt(at(input, pointer)); - if (ipv4Piece === null) { - ipv4Piece = number; - } else if (ipv4Piece === 0) { - return failure; - } else { - ipv4Piece = ipv4Piece * 10 + number; - } - if (ipv4Piece > 255) { - return failure; - } - ++pointer; - } - - address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; - - ++numbersSeen; - - if (numbersSeen === 2 || numbersSeen === 4) { - ++pieceIndex; - } - } - - if (numbersSeen !== 4) { - return failure; - } - - break; - } else if (input[pointer] === 58) { - ++pointer; - if (input[pointer] === undefined) { - return failure; - } - } else if (input[pointer] !== undefined) { - return failure; - } - - address[pieceIndex] = value; - ++pieceIndex; - } - - if (compress !== null) { - let swaps = pieceIndex - compress; - pieceIndex = 7; - while (pieceIndex !== 0 && swaps > 0) { - const temp = address[compress + swaps - 1]; - address[compress + swaps - 1] = address[pieceIndex]; - address[pieceIndex] = temp; - --pieceIndex; - --swaps; - } - } else if (compress === null && pieceIndex !== 8) { - return failure; - } - - return address; -} - -function serializeIPv6(address) { - let output = ""; - const seqResult = findLongestZeroSequence(address); - const compress = seqResult.idx; - let ignore0 = false; - - for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { - if (ignore0 && address[pieceIndex] === 0) { - continue; - } else if (ignore0) { - ignore0 = false; - } - - if (compress === pieceIndex) { - const separator = pieceIndex === 0 ? "::" : ":"; - output += separator; - ignore0 = true; - continue; - } - - output += address[pieceIndex].toString(16); - - if (pieceIndex !== 7) { - output += ":"; - } - } - - return output; -} - -function parseHost(input, isSpecialArg) { - if (input[0] === "[") { - if (input[input.length - 1] !== "]") { - return failure; - } - - return parseIPv6(input.substring(1, input.length - 1)); - } - - if (!isSpecialArg) { - return parseOpaqueHost(input); - } - - const domain = utf8PercentDecode(input); - const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); - if (asciiDomain === null) { - return failure; - } - - if (containsForbiddenHostCodePoint(asciiDomain)) { - return failure; - } - - const ipv4Host = parseIPv4(asciiDomain); - if (typeof ipv4Host === "number" || ipv4Host === failure) { - return ipv4Host; - } - - return asciiDomain; -} - -function parseOpaqueHost(input) { - if (containsForbiddenHostCodePointExcludingPercent(input)) { - return failure; - } - - let output = ""; - const decoded = punycode.ucs2.decode(input); - for (let i = 0; i < decoded.length; ++i) { - output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); - } - return output; -} - -function findLongestZeroSequence(arr) { - let maxIdx = null; - let maxLen = 1; // only find elements > 1 - let currStart = null; - let currLen = 0; - - for (let i = 0; i < arr.length; ++i) { - if (arr[i] !== 0) { - if (currLen > maxLen) { - maxIdx = currStart; - maxLen = currLen; - } - - currStart = null; - currLen = 0; - } else { - if (currStart === null) { - currStart = i; - } - ++currLen; - } - } - - // if trailing zeros - if (currLen > maxLen) { - maxIdx = currStart; - maxLen = currLen; - } - - return { - idx: maxIdx, - len: maxLen - }; -} - -function serializeHost(host) { - if (typeof host === "number") { - return serializeIPv4(host); - } - - // IPv6 serializer - if (host instanceof Array) { - return "[" + serializeIPv6(host) + "]"; - } - - return host; -} - -function trimControlChars(url) { - return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); -} - -function trimTabAndNewline(url) { - return url.replace(/\u0009|\u000A|\u000D/g, ""); -} - -function shortenPath(url) { - const path = url.path; - if (path.length === 0) { - return; - } - if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { - return; - } - - path.pop(); -} - -function includesCredentials(url) { - return url.username !== "" || url.password !== ""; -} - -function cannotHaveAUsernamePasswordPort(url) { - return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; -} - -function isNormalizedWindowsDriveLetter(string) { - return /^[A-Za-z]:$/.test(string); -} - -function URLStateMachine(input, base, encodingOverride, url, stateOverride) { - this.pointer = 0; - this.input = input; - this.base = base || null; - this.encodingOverride = encodingOverride || "utf-8"; - this.stateOverride = stateOverride; - this.url = url; - this.failure = false; - this.parseError = false; - - if (!this.url) { - this.url = { - scheme: "", - username: "", - password: "", - host: null, - port: null, - path: [], - query: null, - fragment: null, - - cannotBeABaseURL: false - }; - - const res = trimControlChars(this.input); - if (res !== this.input) { - this.parseError = true; - } - this.input = res; - } - - const res = trimTabAndNewline(this.input); - if (res !== this.input) { - this.parseError = true; - } - this.input = res; - - this.state = stateOverride || "scheme start"; - - this.buffer = ""; - this.atFlag = false; - this.arrFlag = false; - this.passwordTokenSeenFlag = false; - - this.input = punycode.ucs2.decode(this.input); - - for (; this.pointer <= this.input.length; ++this.pointer) { - const c = this.input[this.pointer]; - const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); - - // exec state machine - const ret = this["parse " + this.state](c, cStr); - if (!ret) { - break; // terminate algorithm - } else if (ret === failure) { - this.failure = true; - break; - } - } -} - -URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { - if (isASCIIAlpha(c)) { - this.buffer += cStr.toLowerCase(); - this.state = "scheme"; - } else if (!this.stateOverride) { - this.state = "no scheme"; - --this.pointer; - } else { - this.parseError = true; - return failure; - } - - return true; -}; - -URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { - if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { - this.buffer += cStr.toLowerCase(); - } else if (c === 58) { - if (this.stateOverride) { - if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { - return false; - } - - if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { - return false; - } - - if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { - return false; - } - - if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { - return false; - } - } - this.url.scheme = this.buffer; - this.buffer = ""; - if (this.stateOverride) { - return false; - } - if (this.url.scheme === "file") { - if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { - this.parseError = true; - } - this.state = "file"; - } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { - this.state = "special relative or authority"; - } else if (isSpecial(this.url)) { - this.state = "special authority slashes"; - } else if (this.input[this.pointer + 1] === 47) { - this.state = "path or authority"; - ++this.pointer; - } else { - this.url.cannotBeABaseURL = true; - this.url.path.push(""); - this.state = "cannot-be-a-base-URL path"; - } - } else if (!this.stateOverride) { - this.buffer = ""; - this.state = "no scheme"; - this.pointer = -1; - } else { - this.parseError = true; - return failure; - } - - return true; -}; - -URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { - if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { - return failure; - } else if (this.base.cannotBeABaseURL && c === 35) { - this.url.scheme = this.base.scheme; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - this.url.fragment = ""; - this.url.cannotBeABaseURL = true; - this.state = "fragment"; - } else if (this.base.scheme === "file") { - this.state = "file"; - --this.pointer; - } else { - this.state = "relative"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { - if (c === 47 && this.input[this.pointer + 1] === 47) { - this.state = "special authority ignore slashes"; - ++this.pointer; - } else { - this.parseError = true; - this.state = "relative"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { - if (c === 47) { - this.state = "authority"; - } else { - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse relative"] = function parseRelative(c) { - this.url.scheme = this.base.scheme; - if (isNaN(c)) { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - } else if (c === 47) { - this.state = "relative slash"; - } else if (c === 63) { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(); - this.url.query = ""; - this.state = "query"; - } else if (c === 35) { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - this.url.fragment = ""; - this.state = "fragment"; - } else if (isSpecial(this.url) && c === 92) { - this.parseError = true; - this.state = "relative slash"; - } else { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(0, this.base.path.length - 1); - - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { - if (isSpecial(this.url) && (c === 47 || c === 92)) { - if (c === 92) { - this.parseError = true; - } - this.state = "special authority ignore slashes"; - } else if (c === 47) { - this.state = "authority"; - } else { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { - if (c === 47 && this.input[this.pointer + 1] === 47) { - this.state = "special authority ignore slashes"; - ++this.pointer; - } else { - this.parseError = true; - this.state = "special authority ignore slashes"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { - if (c !== 47 && c !== 92) { - this.state = "authority"; - --this.pointer; - } else { - this.parseError = true; - } - - return true; -}; - -URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { - if (c === 64) { - this.parseError = true; - if (this.atFlag) { - this.buffer = "%40" + this.buffer; - } - this.atFlag = true; - - // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars - const len = countSymbols(this.buffer); - for (let pointer = 0; pointer < len; ++pointer) { - const codePoint = this.buffer.codePointAt(pointer); - - if (codePoint === 58 && !this.passwordTokenSeenFlag) { - this.passwordTokenSeenFlag = true; - continue; - } - const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); - if (this.passwordTokenSeenFlag) { - this.url.password += encodedCodePoints; - } else { - this.url.username += encodedCodePoints; - } - } - this.buffer = ""; - } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || - (isSpecial(this.url) && c === 92)) { - if (this.atFlag && this.buffer === "") { - this.parseError = true; - return failure; - } - this.pointer -= countSymbols(this.buffer) + 1; - this.buffer = ""; - this.state = "host"; - } else { - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse hostname"] = -URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { - if (this.stateOverride && this.url.scheme === "file") { - --this.pointer; - this.state = "file host"; - } else if (c === 58 && !this.arrFlag) { - if (this.buffer === "") { - this.parseError = true; - return failure; - } - - const host = parseHost(this.buffer, isSpecial(this.url)); - if (host === failure) { - return failure; - } - - this.url.host = host; - this.buffer = ""; - this.state = "port"; - if (this.stateOverride === "hostname") { - return false; - } - } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || - (isSpecial(this.url) && c === 92)) { - --this.pointer; - if (isSpecial(this.url) && this.buffer === "") { - this.parseError = true; - return failure; - } else if (this.stateOverride && this.buffer === "" && - (includesCredentials(this.url) || this.url.port !== null)) { - this.parseError = true; - return false; - } - - const host = parseHost(this.buffer, isSpecial(this.url)); - if (host === failure) { - return failure; - } - - this.url.host = host; - this.buffer = ""; - this.state = "path start"; - if (this.stateOverride) { - return false; - } - } else { - if (c === 91) { - this.arrFlag = true; - } else if (c === 93) { - this.arrFlag = false; - } - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { - if (isASCIIDigit(c)) { - this.buffer += cStr; - } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || - (isSpecial(this.url) && c === 92) || - this.stateOverride) { - if (this.buffer !== "") { - const port = parseInt(this.buffer); - if (port > Math.pow(2, 16) - 1) { - this.parseError = true; - return failure; - } - this.url.port = port === defaultPort(this.url.scheme) ? null : port; - this.buffer = ""; - } - if (this.stateOverride) { - return false; - } - this.state = "path start"; - --this.pointer; - } else { - this.parseError = true; - return failure; - } - - return true; -}; - -const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); - -URLStateMachine.prototype["parse file"] = function parseFile(c) { - this.url.scheme = "file"; - - if (c === 47 || c === 92) { - if (c === 92) { - this.parseError = true; - } - this.state = "file slash"; - } else if (this.base !== null && this.base.scheme === "file") { - if (isNaN(c)) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - } else if (c === 63) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - this.url.query = ""; - this.state = "query"; - } else if (c === 35) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - this.url.fragment = ""; - this.state = "fragment"; - } else { - if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points - !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || - (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points - !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - shortenPath(this.url); - } else { - this.parseError = true; - } - - this.state = "path"; - --this.pointer; - } - } else { - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { - if (c === 47 || c === 92) { - if (c === 92) { - this.parseError = true; - } - this.state = "file host"; - } else { - if (this.base !== null && this.base.scheme === "file") { - if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { - this.url.path.push(this.base.path[0]); - } else { - this.url.host = this.base.host; - } - } - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { - if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { - --this.pointer; - if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { - this.parseError = true; - this.state = "path"; - } else if (this.buffer === "") { - this.url.host = ""; - if (this.stateOverride) { - return false; - } - this.state = "path start"; - } else { - let host = parseHost(this.buffer, isSpecial(this.url)); - if (host === failure) { - return failure; - } - if (host === "localhost") { - host = ""; - } - this.url.host = host; - - if (this.stateOverride) { - return false; - } - - this.buffer = ""; - this.state = "path start"; - } - } else { - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { - if (isSpecial(this.url)) { - if (c === 92) { - this.parseError = true; - } - this.state = "path"; - - if (c !== 47 && c !== 92) { - --this.pointer; - } - } else if (!this.stateOverride && c === 63) { - this.url.query = ""; - this.state = "query"; - } else if (!this.stateOverride && c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } else if (c !== undefined) { - this.state = "path"; - if (c !== 47) { - --this.pointer; - } - } - - return true; -}; - -URLStateMachine.prototype["parse path"] = function parsePath(c) { - if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || - (!this.stateOverride && (c === 63 || c === 35))) { - if (isSpecial(this.url) && c === 92) { - this.parseError = true; - } - - if (isDoubleDot(this.buffer)) { - shortenPath(this.url); - if (c !== 47 && !(isSpecial(this.url) && c === 92)) { - this.url.path.push(""); - } - } else if (isSingleDot(this.buffer) && c !== 47 && - !(isSpecial(this.url) && c === 92)) { - this.url.path.push(""); - } else if (!isSingleDot(this.buffer)) { - if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { - if (this.url.host !== "" && this.url.host !== null) { - this.parseError = true; - this.url.host = ""; - } - this.buffer = this.buffer[0] + ":"; - } - this.url.path.push(this.buffer); - } - this.buffer = ""; - if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { - while (this.url.path.length > 1 && this.url.path[0] === "") { - this.parseError = true; - this.url.path.shift(); - } - } - if (c === 63) { - this.url.query = ""; - this.state = "query"; - } - if (c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } - } else { - // TODO: If c is not a URL code point and not "%", parse error. - - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - this.buffer += percentEncodeChar(c, isPathPercentEncode); - } - - return true; -}; - -URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { - if (c === 63) { - this.url.query = ""; - this.state = "query"; - } else if (c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } else { - // TODO: Add: not a URL code point - if (!isNaN(c) && c !== 37) { - this.parseError = true; - } - - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - if (!isNaN(c)) { - this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); - } - } - - return true; -}; - -URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { - if (isNaN(c) || (!this.stateOverride && c === 35)) { - if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { - this.encodingOverride = "utf-8"; - } - - const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead - for (let i = 0; i < buffer.length; ++i) { - if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || - buffer[i] === 0x3C || buffer[i] === 0x3E) { - this.url.query += percentEncode(buffer[i]); - } else { - this.url.query += String.fromCodePoint(buffer[i]); - } - } - - this.buffer = ""; - if (c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } - } else { - // TODO: If c is not a URL code point and not "%", parse error. - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { - if (isNaN(c)) { // do nothing - } else if (c === 0x0) { - this.parseError = true; - } else { - // TODO: If c is not a URL code point and not "%", parse error. - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); - } - - return true; -}; - -function serializeURL(url, excludeFragment) { - let output = url.scheme + ":"; - if (url.host !== null) { - output += "//"; - - if (url.username !== "" || url.password !== "") { - output += url.username; - if (url.password !== "") { - output += ":" + url.password; - } - output += "@"; - } - - output += serializeHost(url.host); - - if (url.port !== null) { - output += ":" + url.port; - } - } else if (url.host === null && url.scheme === "file") { - output += "//"; - } - - if (url.cannotBeABaseURL) { - output += url.path[0]; - } else { - for (const string of url.path) { - output += "/" + string; - } - } - - if (url.query !== null) { - output += "?" + url.query; - } - - if (!excludeFragment && url.fragment !== null) { - output += "#" + url.fragment; - } - - return output; -} - -function serializeOrigin(tuple) { - let result = tuple.scheme + "://"; - result += serializeHost(tuple.host); - - if (tuple.port !== null) { - result += ":" + tuple.port; - } - - return result; -} - -module.exports.serializeURL = serializeURL; - -module.exports.serializeURLOrigin = function (url) { - // https://url.spec.whatwg.org/#concept-url-origin - switch (url.scheme) { - case "blob": - try { - return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); - } catch (e) { - // serializing an opaque origin returns "null" - return "null"; - } - case "ftp": - case "gopher": - case "http": - case "https": - case "ws": - case "wss": - return serializeOrigin({ - scheme: url.scheme, - host: url.host, - port: url.port - }); - case "file": - // spec says "exercise to the reader", chrome says "file://" - return "file://"; - default: - // serializing an opaque origin returns "null" - return "null"; - } -}; - -module.exports.basicURLParse = function (input, options) { - if (options === undefined) { - options = {}; - } - - const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); - if (usm.failure) { - return "failure"; - } - - return usm.url; -}; - -module.exports.setTheUsername = function (url, username) { - url.username = ""; - const decoded = punycode.ucs2.decode(username); - for (let i = 0; i < decoded.length; ++i) { - url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); - } -}; - -module.exports.setThePassword = function (url, password) { - url.password = ""; - const decoded = punycode.ucs2.decode(password); - for (let i = 0; i < decoded.length; ++i) { - url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); - } -}; - -module.exports.serializeHost = serializeHost; - -module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; - -module.exports.serializeInteger = function (integer) { - return String(integer); -}; - -module.exports.parseURL = function (input, options) { - if (options === undefined) { - options = {}; - } - - // We don't handle blobs, so this just delegates: - return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); -}; + +const punycode = __nccwpck_require__(5477); +const tr46 = __nccwpck_require__(2299); + +const specialSchemes = { + ftp: 21, + file: null, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443 +}; + +const failure = Symbol("failure"); + +function countSymbols(str) { + return punycode.ucs2.decode(str).length; +} + +function at(input, idx) { + const c = input[idx]; + return isNaN(c) ? undefined : String.fromCodePoint(c); +} + +function isASCIIDigit(c) { + return c >= 0x30 && c <= 0x39; +} + +function isASCIIAlpha(c) { + return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); +} + +function isASCIIAlphanumeric(c) { + return isASCIIAlpha(c) || isASCIIDigit(c); +} + +function isASCIIHex(c) { + return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); +} + +function isSingleDot(buffer) { + return buffer === "." || buffer.toLowerCase() === "%2e"; +} + +function isDoubleDot(buffer) { + buffer = buffer.toLowerCase(); + return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; +} + +function isWindowsDriveLetterCodePoints(cp1, cp2) { + return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); +} + +function isWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); +} + +function isNormalizedWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; +} + +function containsForbiddenHostCodePoint(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function containsForbiddenHostCodePointExcludingPercent(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function isSpecialScheme(scheme) { + return specialSchemes[scheme] !== undefined; +} + +function isSpecial(url) { + return isSpecialScheme(url.scheme); +} + +function defaultPort(scheme) { + return specialSchemes[scheme]; +} + +function percentEncode(c) { + let hex = c.toString(16).toUpperCase(); + if (hex.length === 1) { + hex = "0" + hex; + } + + return "%" + hex; +} + +function utf8PercentEncode(c) { + const buf = new Buffer(c); + + let str = ""; + + for (let i = 0; i < buf.length; ++i) { + str += percentEncode(buf[i]); + } + + return str; +} + +function utf8PercentDecode(str) { + const input = new Buffer(str); + const output = []; + for (let i = 0; i < input.length; ++i) { + if (input[i] !== 37) { + output.push(input[i]); + } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { + output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); + i += 2; + } else { + output.push(input[i]); + } + } + return new Buffer(output).toString(); +} + +function isC0ControlPercentEncode(c) { + return c <= 0x1F || c > 0x7E; +} + +const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); +function isPathPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); +} + +const extraUserinfoPercentEncodeSet = + new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); +function isUserinfoPercentEncode(c) { + return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); +} + +function percentEncodeChar(c, encodeSetPredicate) { + const cStr = String.fromCodePoint(c); + + if (encodeSetPredicate(c)) { + return utf8PercentEncode(cStr); + } + + return cStr; +} + +function parseIPv4Number(input) { + let R = 10; + + if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { + input = input.substring(2); + R = 16; + } else if (input.length >= 2 && input.charAt(0) === "0") { + input = input.substring(1); + R = 8; + } + + if (input === "") { + return 0; + } + + const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); + if (regex.test(input)) { + return failure; + } + + return parseInt(input, R); +} + +function parseIPv4(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length > 1) { + parts.pop(); + } + } + + if (parts.length > 4) { + return input; + } + + const numbers = []; + for (const part of parts) { + if (part === "") { + return input; + } + const n = parseIPv4Number(part); + if (n === failure) { + return input; + } + + numbers.push(n); + } + + for (let i = 0; i < numbers.length - 1; ++i) { + if (numbers[i] > 255) { + return failure; + } + } + if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { + return failure; + } + + let ipv4 = numbers.pop(); + let counter = 0; + + for (const n of numbers) { + ipv4 += n * Math.pow(256, 3 - counter); + ++counter; + } + + return ipv4; +} + +function serializeIPv4(address) { + let output = ""; + let n = address; + + for (let i = 1; i <= 4; ++i) { + output = String(n % 256) + output; + if (i !== 4) { + output = "." + output; + } + n = Math.floor(n / 256); + } + + return output; +} + +function parseIPv6(input) { + const address = [0, 0, 0, 0, 0, 0, 0, 0]; + let pieceIndex = 0; + let compress = null; + let pointer = 0; + + input = punycode.ucs2.decode(input); + + if (input[pointer] === 58) { + if (input[pointer + 1] !== 58) { + return failure; + } + + pointer += 2; + ++pieceIndex; + compress = pieceIndex; + } + + while (pointer < input.length) { + if (pieceIndex === 8) { + return failure; + } + + if (input[pointer] === 58) { + if (compress !== null) { + return failure; + } + ++pointer; + ++pieceIndex; + compress = pieceIndex; + continue; + } + + let value = 0; + let length = 0; + + while (length < 4 && isASCIIHex(input[pointer])) { + value = value * 0x10 + parseInt(at(input, pointer), 16); + ++pointer; + ++length; + } + + if (input[pointer] === 46) { + if (length === 0) { + return failure; + } + + pointer -= length; + + if (pieceIndex > 6) { + return failure; + } + + let numbersSeen = 0; + + while (input[pointer] !== undefined) { + let ipv4Piece = null; + + if (numbersSeen > 0) { + if (input[pointer] === 46 && numbersSeen < 4) { + ++pointer; + } else { + return failure; + } + } + + if (!isASCIIDigit(input[pointer])) { + return failure; + } + + while (isASCIIDigit(input[pointer])) { + const number = parseInt(at(input, pointer)); + if (ipv4Piece === null) { + ipv4Piece = number; + } else if (ipv4Piece === 0) { + return failure; + } else { + ipv4Piece = ipv4Piece * 10 + number; + } + if (ipv4Piece > 255) { + return failure; + } + ++pointer; + } + + address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; + + ++numbersSeen; + + if (numbersSeen === 2 || numbersSeen === 4) { + ++pieceIndex; + } + } + + if (numbersSeen !== 4) { + return failure; + } + + break; + } else if (input[pointer] === 58) { + ++pointer; + if (input[pointer] === undefined) { + return failure; + } + } else if (input[pointer] !== undefined) { + return failure; + } + + address[pieceIndex] = value; + ++pieceIndex; + } + + if (compress !== null) { + let swaps = pieceIndex - compress; + pieceIndex = 7; + while (pieceIndex !== 0 && swaps > 0) { + const temp = address[compress + swaps - 1]; + address[compress + swaps - 1] = address[pieceIndex]; + address[pieceIndex] = temp; + --pieceIndex; + --swaps; + } + } else if (compress === null && pieceIndex !== 8) { + return failure; + } + + return address; +} + +function serializeIPv6(address) { + let output = ""; + const seqResult = findLongestZeroSequence(address); + const compress = seqResult.idx; + let ignore0 = false; + + for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { + if (ignore0 && address[pieceIndex] === 0) { + continue; + } else if (ignore0) { + ignore0 = false; + } + + if (compress === pieceIndex) { + const separator = pieceIndex === 0 ? "::" : ":"; + output += separator; + ignore0 = true; + continue; + } + + output += address[pieceIndex].toString(16); + + if (pieceIndex !== 7) { + output += ":"; + } + } + + return output; +} + +function parseHost(input, isSpecialArg) { + if (input[0] === "[") { + if (input[input.length - 1] !== "]") { + return failure; + } + + return parseIPv6(input.substring(1, input.length - 1)); + } + + if (!isSpecialArg) { + return parseOpaqueHost(input); + } + + const domain = utf8PercentDecode(input); + const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); + if (asciiDomain === null) { + return failure; + } + + if (containsForbiddenHostCodePoint(asciiDomain)) { + return failure; + } + + const ipv4Host = parseIPv4(asciiDomain); + if (typeof ipv4Host === "number" || ipv4Host === failure) { + return ipv4Host; + } + + return asciiDomain; +} + +function parseOpaqueHost(input) { + if (containsForbiddenHostCodePointExcludingPercent(input)) { + return failure; + } + + let output = ""; + const decoded = punycode.ucs2.decode(input); + for (let i = 0; i < decoded.length; ++i) { + output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); + } + return output; +} + +function findLongestZeroSequence(arr) { + let maxIdx = null; + let maxLen = 1; // only find elements > 1 + let currStart = null; + let currLen = 0; + + for (let i = 0; i < arr.length; ++i) { + if (arr[i] !== 0) { + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + currStart = null; + currLen = 0; + } else { + if (currStart === null) { + currStart = i; + } + ++currLen; + } + } + + // if trailing zeros + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + return { + idx: maxIdx, + len: maxLen + }; +} + +function serializeHost(host) { + if (typeof host === "number") { + return serializeIPv4(host); + } + + // IPv6 serializer + if (host instanceof Array) { + return "[" + serializeIPv6(host) + "]"; + } + + return host; +} + +function trimControlChars(url) { + return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); +} + +function trimTabAndNewline(url) { + return url.replace(/\u0009|\u000A|\u000D/g, ""); +} + +function shortenPath(url) { + const path = url.path; + if (path.length === 0) { + return; + } + if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { + return; + } + + path.pop(); +} + +function includesCredentials(url) { + return url.username !== "" || url.password !== ""; +} + +function cannotHaveAUsernamePasswordPort(url) { + return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; +} + +function isNormalizedWindowsDriveLetter(string) { + return /^[A-Za-z]:$/.test(string); +} + +function URLStateMachine(input, base, encodingOverride, url, stateOverride) { + this.pointer = 0; + this.input = input; + this.base = base || null; + this.encodingOverride = encodingOverride || "utf-8"; + this.stateOverride = stateOverride; + this.url = url; + this.failure = false; + this.parseError = false; + + if (!this.url) { + this.url = { + scheme: "", + username: "", + password: "", + host: null, + port: null, + path: [], + query: null, + fragment: null, + + cannotBeABaseURL: false + }; + + const res = trimControlChars(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + } + + const res = trimTabAndNewline(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + + this.state = stateOverride || "scheme start"; + + this.buffer = ""; + this.atFlag = false; + this.arrFlag = false; + this.passwordTokenSeenFlag = false; + + this.input = punycode.ucs2.decode(this.input); + + for (; this.pointer <= this.input.length; ++this.pointer) { + const c = this.input[this.pointer]; + const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); + + // exec state machine + const ret = this["parse " + this.state](c, cStr); + if (!ret) { + break; // terminate algorithm + } else if (ret === failure) { + this.failure = true; + break; + } + } +} + +URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { + if (isASCIIAlpha(c)) { + this.buffer += cStr.toLowerCase(); + this.state = "scheme"; + } else if (!this.stateOverride) { + this.state = "no scheme"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { + if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { + this.buffer += cStr.toLowerCase(); + } else if (c === 58) { + if (this.stateOverride) { + if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { + return false; + } + + if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { + return false; + } + + if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { + return false; + } + + if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { + return false; + } + } + this.url.scheme = this.buffer; + this.buffer = ""; + if (this.stateOverride) { + return false; + } + if (this.url.scheme === "file") { + if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { + this.parseError = true; + } + this.state = "file"; + } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { + this.state = "special relative or authority"; + } else if (isSpecial(this.url)) { + this.state = "special authority slashes"; + } else if (this.input[this.pointer + 1] === 47) { + this.state = "path or authority"; + ++this.pointer; + } else { + this.url.cannotBeABaseURL = true; + this.url.path.push(""); + this.state = "cannot-be-a-base-URL path"; + } + } else if (!this.stateOverride) { + this.buffer = ""; + this.state = "no scheme"; + this.pointer = -1; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { + if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { + return failure; + } else if (this.base.cannotBeABaseURL && c === 35) { + this.url.scheme = this.base.scheme; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.url.cannotBeABaseURL = true; + this.state = "fragment"; + } else if (this.base.scheme === "file") { + this.state = "file"; + --this.pointer; + } else { + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { + if (c === 47) { + this.state = "authority"; + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative"] = function parseRelative(c) { + this.url.scheme = this.base.scheme; + if (isNaN(c)) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 47) { + this.state = "relative slash"; + } else if (c === 63) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else if (isSpecial(this.url) && c === 92) { + this.parseError = true; + this.state = "relative slash"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(0, this.base.path.length - 1); + + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { + if (isSpecial(this.url) && (c === 47 || c === 92)) { + if (c === 92) { + this.parseError = true; + } + this.state = "special authority ignore slashes"; + } else if (c === 47) { + this.state = "authority"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "special authority ignore slashes"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { + if (c !== 47 && c !== 92) { + this.state = "authority"; + --this.pointer; + } else { + this.parseError = true; + } + + return true; +}; + +URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { + if (c === 64) { + this.parseError = true; + if (this.atFlag) { + this.buffer = "%40" + this.buffer; + } + this.atFlag = true; + + // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars + const len = countSymbols(this.buffer); + for (let pointer = 0; pointer < len; ++pointer) { + const codePoint = this.buffer.codePointAt(pointer); + + if (codePoint === 58 && !this.passwordTokenSeenFlag) { + this.passwordTokenSeenFlag = true; + continue; + } + const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); + if (this.passwordTokenSeenFlag) { + this.url.password += encodedCodePoints; + } else { + this.url.username += encodedCodePoints; + } + } + this.buffer = ""; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + if (this.atFlag && this.buffer === "") { + this.parseError = true; + return failure; + } + this.pointer -= countSymbols(this.buffer) + 1; + this.buffer = ""; + this.state = "host"; + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse hostname"] = +URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { + if (this.stateOverride && this.url.scheme === "file") { + --this.pointer; + this.state = "file host"; + } else if (c === 58 && !this.arrFlag) { + if (this.buffer === "") { + this.parseError = true; + return failure; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "port"; + if (this.stateOverride === "hostname") { + return false; + } + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + --this.pointer; + if (isSpecial(this.url) && this.buffer === "") { + this.parseError = true; + return failure; + } else if (this.stateOverride && this.buffer === "" && + (includesCredentials(this.url) || this.url.port !== null)) { + this.parseError = true; + return false; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "path start"; + if (this.stateOverride) { + return false; + } + } else { + if (c === 91) { + this.arrFlag = true; + } else if (c === 93) { + this.arrFlag = false; + } + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { + if (isASCIIDigit(c)) { + this.buffer += cStr; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92) || + this.stateOverride) { + if (this.buffer !== "") { + const port = parseInt(this.buffer); + if (port > Math.pow(2, 16) - 1) { + this.parseError = true; + return failure; + } + this.url.port = port === defaultPort(this.url.scheme) ? null : port; + this.buffer = ""; + } + if (this.stateOverride) { + return false; + } + this.state = "path start"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); + +URLStateMachine.prototype["parse file"] = function parseFile(c) { + this.url.scheme = "file"; + + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file slash"; + } else if (this.base !== null && this.base.scheme === "file") { + if (isNaN(c)) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 63) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else { + if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points + !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || + (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points + !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + shortenPath(this.url); + } else { + this.parseError = true; + } + + this.state = "path"; + --this.pointer; + } + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file host"; + } else { + if (this.base !== null && this.base.scheme === "file") { + if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { + this.url.path.push(this.base.path[0]); + } else { + this.url.host = this.base.host; + } + } + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { + if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { + --this.pointer; + if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { + this.parseError = true; + this.state = "path"; + } else if (this.buffer === "") { + this.url.host = ""; + if (this.stateOverride) { + return false; + } + this.state = "path start"; + } else { + let host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + if (host === "localhost") { + host = ""; + } + this.url.host = host; + + if (this.stateOverride) { + return false; + } + + this.buffer = ""; + this.state = "path start"; + } + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { + if (isSpecial(this.url)) { + if (c === 92) { + this.parseError = true; + } + this.state = "path"; + + if (c !== 47 && c !== 92) { + --this.pointer; + } + } else if (!this.stateOverride && c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (!this.stateOverride && c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (c !== undefined) { + this.state = "path"; + if (c !== 47) { + --this.pointer; + } + } + + return true; +}; + +URLStateMachine.prototype["parse path"] = function parsePath(c) { + if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || + (!this.stateOverride && (c === 63 || c === 35))) { + if (isSpecial(this.url) && c === 92) { + this.parseError = true; + } + + if (isDoubleDot(this.buffer)) { + shortenPath(this.url); + if (c !== 47 && !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } + } else if (isSingleDot(this.buffer) && c !== 47 && + !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } else if (!isSingleDot(this.buffer)) { + if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { + if (this.url.host !== "" && this.url.host !== null) { + this.parseError = true; + this.url.host = ""; + } + this.buffer = this.buffer[0] + ":"; + } + this.url.path.push(this.buffer); + } + this.buffer = ""; + if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { + while (this.url.path.length > 1 && this.url.path[0] === "") { + this.parseError = true; + this.url.path.shift(); + } + } + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += percentEncodeChar(c, isPathPercentEncode); + } + + return true; +}; + +URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else { + // TODO: Add: not a URL code point + if (!isNaN(c) && c !== 37) { + this.parseError = true; + } + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + if (!isNaN(c)) { + this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); + } + } + + return true; +}; + +URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { + if (isNaN(c) || (!this.stateOverride && c === 35)) { + if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { + this.encodingOverride = "utf-8"; + } + + const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead + for (let i = 0; i < buffer.length; ++i) { + if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || + buffer[i] === 0x3C || buffer[i] === 0x3E) { + this.url.query += percentEncode(buffer[i]); + } else { + this.url.query += String.fromCodePoint(buffer[i]); + } + } + + this.buffer = ""; + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { + if (isNaN(c)) { // do nothing + } else if (c === 0x0) { + this.parseError = true; + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); + } + + return true; +}; + +function serializeURL(url, excludeFragment) { + let output = url.scheme + ":"; + if (url.host !== null) { + output += "//"; + + if (url.username !== "" || url.password !== "") { + output += url.username; + if (url.password !== "") { + output += ":" + url.password; + } + output += "@"; + } + + output += serializeHost(url.host); + + if (url.port !== null) { + output += ":" + url.port; + } + } else if (url.host === null && url.scheme === "file") { + output += "//"; + } + + if (url.cannotBeABaseURL) { + output += url.path[0]; + } else { + for (const string of url.path) { + output += "/" + string; + } + } + + if (url.query !== null) { + output += "?" + url.query; + } + + if (!excludeFragment && url.fragment !== null) { + output += "#" + url.fragment; + } + + return output; +} + +function serializeOrigin(tuple) { + let result = tuple.scheme + "://"; + result += serializeHost(tuple.host); + + if (tuple.port !== null) { + result += ":" + tuple.port; + } + + return result; +} + +module.exports.serializeURL = serializeURL; + +module.exports.serializeURLOrigin = function (url) { + // https://url.spec.whatwg.org/#concept-url-origin + switch (url.scheme) { + case "blob": + try { + return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); + } catch (e) { + // serializing an opaque origin returns "null" + return "null"; + } + case "ftp": + case "gopher": + case "http": + case "https": + case "ws": + case "wss": + return serializeOrigin({ + scheme: url.scheme, + host: url.host, + port: url.port + }); + case "file": + // spec says "exercise to the reader", chrome says "file://" + return "file://"; + default: + // serializing an opaque origin returns "null" + return "null"; + } +}; + +module.exports.basicURLParse = function (input, options) { + if (options === undefined) { + options = {}; + } + + const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); + if (usm.failure) { + return "failure"; + } + + return usm.url; +}; + +module.exports.setTheUsername = function (url, username) { + url.username = ""; + const decoded = punycode.ucs2.decode(username); + for (let i = 0; i < decoded.length; ++i) { + url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.setThePassword = function (url, password) { + url.password = ""; + const decoded = punycode.ucs2.decode(password); + for (let i = 0; i < decoded.length; ++i) { + url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.serializeHost = serializeHost; + +module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; + +module.exports.serializeInteger = function (integer) { + return String(integer); +}; + +module.exports.parseURL = function (input, options) { + if (options === undefined) { + options = {}; + } + + // We don't handle blobs, so this just delegates: + return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); +}; /***/ }), diff --git a/package-lock.json b/package-lock.json index 6b77be1..3a8851a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "checkout", - "version": "4.0.0", + "version": "4.1.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "checkout", - "version": "4.0.0", + "version": "4.1.0", "license": "MIT", "dependencies": { "@actions/core": "^1.10.0", diff --git a/package.json b/package.json index 84d6430..0fd7c5c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "checkout", - "version": "4.0.0", + "version": "4.1.0", "description": "checkout action", "main": "lib/main.js", "scripts": { diff --git a/src/git-source-provider.ts b/src/git-source-provider.ts index c1360b8..5c98e9f 100644 --- a/src/git-source-provider.ts +++ b/src/git-source-provider.ts @@ -159,7 +159,13 @@ export async function getSource(settings: IGitSourceSettings): Promise { fetchTags?: boolean showProgress?: boolean } = {} - if (settings.sparseCheckout) fetchOptions.filter = 'blob:none' + + if (settings.filter) { + fetchOptions.filter = settings.filter + } else if (settings.sparseCheckout) { + fetchOptions.filter = 'blob:none' + } + if (settings.fetchDepth <= 0) { // Fetch all branches and tags let refSpec = refHelper.getRefSpecForAllHistory( diff --git a/src/git-source-settings.ts b/src/git-source-settings.ts index 2f80b5e..629350b 100644 --- a/src/git-source-settings.ts +++ b/src/git-source-settings.ts @@ -29,6 +29,11 @@ export interface IGitSourceSettings { */ clean: boolean + /** + * The filter determining which objects to include + */ + filter: string | undefined + /** * The array of folders to make the sparse checkout */ diff --git a/src/input-helper.ts b/src/input-helper.ts index 48e1fae..3d2f2f1 100644 --- a/src/input-helper.ts +++ b/src/input-helper.ts @@ -82,6 +82,14 @@ export async function getInputs(): Promise { result.clean = (core.getInput('clean') || 'true').toUpperCase() === 'TRUE' core.debug(`clean = ${result.clean}`) + // Filter + const filter = core.getInput('filter') + if (filter) { + result.filter = filter + } + + core.debug(`filter = ${result.filter}`) + // Sparse checkout const sparseCheckout = core.getMultilineInput('sparse-checkout') if (sparseCheckout.length) {