1
Fork 0
mirror of https://gitea.com/actions/checkout.git synced 2024-11-22 16:45:56 +01:00

use token for workflow repo

This commit is contained in:
eric sciple 2020-03-18 23:33:26 -04:00
parent 9a3a9ade82
commit 85a425b582
8 changed files with 210 additions and 47 deletions

View file

@ -725,6 +725,7 @@ async function setup(testName: string): Promise<void> {
setEnvironmentVariable: jest.fn((name: string, value: string) => { setEnvironmentVariable: jest.fn((name: string, value: string) => {
git.env[name] = value git.env[name] = value
}), }),
setRemoteUrl: jest.fn(),
submoduleForeach: jest.fn(async () => { submoduleForeach: jest.fn(async () => {
return '' return ''
}), }),
@ -748,7 +749,7 @@ async function setup(testName: string): Promise<void> {
} }
), ),
tryDisableAutomaticGarbageCollection: jest.fn(), tryDisableAutomaticGarbageCollection: jest.fn(),
tryGetFetchUrl: jest.fn(), tryGetRemoteUrl: jest.fn(),
tryReset: jest.fn() tryReset: jest.fn()
} }
@ -757,6 +758,7 @@ async function setup(testName: string): Promise<void> {
clean: true, clean: true,
commit: '', commit: '',
fetchDepth: 1, fetchDepth: 1,
isWorkflowRepository: true,
lfs: false, lfs: false,
submodules: false, submodules: false,
nestedSubmodules: false, nestedSubmodules: false,

View file

@ -7,7 +7,8 @@ import {IGitCommandManager} from '../lib/git-command-manager'
const testWorkspace = path.join(__dirname, '_temp', 'git-directory-helper') const testWorkspace = path.join(__dirname, '_temp', 'git-directory-helper')
let repositoryPath: string let repositoryPath: string
let repositoryUrl: string let httpsUrl: string
let sshUrl: string
let clean: boolean let clean: boolean
let git: IGitCommandManager let git: IGitCommandManager
@ -40,7 +41,8 @@ describe('git-directory-helper tests', () => {
await gitDirectoryHelper.prepareExistingDirectory( await gitDirectoryHelper.prepareExistingDirectory(
git, git,
repositoryPath, repositoryPath,
repositoryUrl, httpsUrl,
[httpsUrl, sshUrl],
clean clean
) )
@ -62,7 +64,8 @@ describe('git-directory-helper tests', () => {
await gitDirectoryHelper.prepareExistingDirectory( await gitDirectoryHelper.prepareExistingDirectory(
git, git,
repositoryPath, repositoryPath,
repositoryUrl, httpsUrl,
[httpsUrl, sshUrl],
clean clean
) )
@ -87,7 +90,8 @@ describe('git-directory-helper tests', () => {
await gitDirectoryHelper.prepareExistingDirectory( await gitDirectoryHelper.prepareExistingDirectory(
git, git,
repositoryPath, repositoryPath,
repositoryUrl, httpsUrl,
[httpsUrl, sshUrl],
clean clean
) )
@ -108,7 +112,8 @@ describe('git-directory-helper tests', () => {
await gitDirectoryHelper.prepareExistingDirectory( await gitDirectoryHelper.prepareExistingDirectory(
git, git,
repositoryPath, repositoryPath,
repositoryUrl, httpsUrl,
[httpsUrl, sshUrl],
clean clean
) )
@ -136,7 +141,8 @@ describe('git-directory-helper tests', () => {
await gitDirectoryHelper.prepareExistingDirectory( await gitDirectoryHelper.prepareExistingDirectory(
git, git,
repositoryPath, repositoryPath,
repositoryUrl, httpsUrl,
[httpsUrl, sshUrl],
clean clean
) )
@ -155,14 +161,15 @@ describe('git-directory-helper tests', () => {
await setup(removesContentsWhenDifferentRepositoryUrl) await setup(removesContentsWhenDifferentRepositoryUrl)
clean = false clean = false
await fs.promises.writeFile(path.join(repositoryPath, 'my-file'), '') await fs.promises.writeFile(path.join(repositoryPath, 'my-file'), '')
const differentRepositoryUrl = const differentRemoteUrl =
'https://github.com/my-different-org/my-different-repo' 'https://github.com/my-different-org/my-different-repo'
// Act // Act
await gitDirectoryHelper.prepareExistingDirectory( await gitDirectoryHelper.prepareExistingDirectory(
git, git,
repositoryPath, repositoryPath,
differentRepositoryUrl, differentRemoteUrl,
[differentRemoteUrl],
clean clean
) )
@ -186,7 +193,8 @@ describe('git-directory-helper tests', () => {
await gitDirectoryHelper.prepareExistingDirectory( await gitDirectoryHelper.prepareExistingDirectory(
git, git,
repositoryPath, repositoryPath,
repositoryUrl, httpsUrl,
[httpsUrl, sshUrl],
clean clean
) )
@ -211,7 +219,8 @@ describe('git-directory-helper tests', () => {
await gitDirectoryHelper.prepareExistingDirectory( await gitDirectoryHelper.prepareExistingDirectory(
git, git,
repositoryPath, repositoryPath,
repositoryUrl, httpsUrl,
[httpsUrl, sshUrl],
clean clean
) )
@ -235,7 +244,8 @@ describe('git-directory-helper tests', () => {
await gitDirectoryHelper.prepareExistingDirectory( await gitDirectoryHelper.prepareExistingDirectory(
undefined, undefined,
repositoryPath, repositoryPath,
repositoryUrl, httpsUrl,
[httpsUrl, sshUrl],
clean clean
) )
@ -259,7 +269,8 @@ describe('git-directory-helper tests', () => {
await gitDirectoryHelper.prepareExistingDirectory( await gitDirectoryHelper.prepareExistingDirectory(
git, git,
repositoryPath, repositoryPath,
repositoryUrl, httpsUrl,
[httpsUrl, sshUrl],
clean clean
) )
@ -289,7 +300,8 @@ describe('git-directory-helper tests', () => {
await gitDirectoryHelper.prepareExistingDirectory( await gitDirectoryHelper.prepareExistingDirectory(
git, git,
repositoryPath, repositoryPath,
repositoryUrl, httpsUrl,
[httpsUrl, sshUrl],
clean clean
) )
@ -319,7 +331,8 @@ describe('git-directory-helper tests', () => {
await gitDirectoryHelper.prepareExistingDirectory( await gitDirectoryHelper.prepareExistingDirectory(
git, git,
repositoryPath, repositoryPath,
repositoryUrl, httpsUrl,
[httpsUrl, sshUrl],
clean clean
) )
@ -329,6 +342,30 @@ describe('git-directory-helper tests', () => {
expect(git.branchDelete).toHaveBeenCalledWith(true, 'remote-branch-1') expect(git.branchDelete).toHaveBeenCalledWith(true, 'remote-branch-1')
expect(git.branchDelete).toHaveBeenCalledWith(true, 'remote-branch-2') expect(git.branchDelete).toHaveBeenCalledWith(true, 'remote-branch-2')
}) })
const updatesRemoteUrl = 'updates remote URL'
it(updatesRemoteUrl, async () => {
// Arrange
await setup(updatesRemoteUrl)
await fs.promises.writeFile(path.join(repositoryPath, 'my-file'), '')
// Act
await gitDirectoryHelper.prepareExistingDirectory(
git,
repositoryPath,
sshUrl,
[sshUrl, httpsUrl],
clean
)
// Assert
const files = await fs.promises.readdir(repositoryPath)
expect(files.sort()).toEqual(['.git', 'my-file'])
expect(git.isDetached).toHaveBeenCalled()
expect(git.branchList).toHaveBeenCalled()
expect(core.warning).not.toHaveBeenCalled()
expect(git.setRemoteUrl).toHaveBeenCalledWith(sshUrl)
})
}) })
async function setup(testName: string): Promise<void> { async function setup(testName: string): Promise<void> {
@ -338,8 +375,9 @@ async function setup(testName: string): Promise<void> {
repositoryPath = path.join(testWorkspace, testName) repositoryPath = path.join(testWorkspace, testName)
await fs.promises.mkdir(path.join(repositoryPath, '.git'), {recursive: true}) await fs.promises.mkdir(path.join(repositoryPath, '.git'), {recursive: true})
// Repository URL // Remote URLs
repositoryUrl = 'https://github.com/my-org/my-repo' httpsUrl = 'https://github.com/my-org/my-repo'
sshUrl = 'git@github.com:my-org/my-repo'
// Clean // Clean
clean = true clean = true
@ -365,6 +403,7 @@ async function setup(testName: string): Promise<void> {
remoteAdd: jest.fn(), remoteAdd: jest.fn(),
removeEnvironmentVariable: jest.fn(), removeEnvironmentVariable: jest.fn(),
setEnvironmentVariable: jest.fn(), setEnvironmentVariable: jest.fn(),
setRemoteUrl: jest.fn(),
submoduleForeach: jest.fn(), submoduleForeach: jest.fn(),
submoduleSync: jest.fn(), submoduleSync: jest.fn(),
submoduleUpdate: jest.fn(), submoduleUpdate: jest.fn(),
@ -374,10 +413,10 @@ async function setup(testName: string): Promise<void> {
}), }),
tryConfigUnset: jest.fn(), tryConfigUnset: jest.fn(),
tryDisableAutomaticGarbageCollection: jest.fn(), tryDisableAutomaticGarbageCollection: jest.fn(),
tryGetFetchUrl: jest.fn(async () => { tryGetRemoteUrl: jest.fn(async () => {
// Sanity check - this function shouldn't be called when the .git directory doesn't exist // Sanity check - this function shouldn't be called when the .git directory doesn't exist
await fs.promises.stat(path.join(repositoryPath, '.git')) await fs.promises.stat(path.join(repositoryPath, '.git'))
return repositoryUrl return httpsUrl
}), }),
tryReset: jest.fn(async () => { tryReset: jest.fn(async () => {
return true return true

48
dist/index.js vendored
View file

@ -5581,6 +5581,11 @@ class GitCommandManager {
setEnvironmentVariable(name, value) { setEnvironmentVariable(name, value) {
this.gitEnv[name] = value; this.gitEnv[name] = value;
} }
setRemoteUrl(value) {
return __awaiter(this, void 0, void 0, function* () {
yield this.config('git.remote.url', value);
});
}
submoduleForeach(command, recursive) { submoduleForeach(command, recursive) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const args = ['submodule', 'foreach']; const args = ['submodule', 'foreach'];
@ -5643,7 +5648,7 @@ class GitCommandManager {
return output.exitCode === 0; return output.exitCode === 0;
}); });
} }
tryGetFetchUrl() { tryGetRemoteUrl() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const output = yield this.execGit(['config', '--local', '--get', 'remote.origin.url'], true); const output = yield this.execGit(['config', '--local', '--get', 'remote.origin.url'], true);
if (output.exitCode !== 0) { if (output.exitCode !== 0) {
@ -5800,11 +5805,12 @@ const stateHelper = __importStar(__webpack_require__(153));
const hostname = 'github.com'; const hostname = 'github.com';
function getSource(settings) { function getSource(settings) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
// Repository URL
core.info(`Syncing repository: ${settings.repositoryOwner}/${settings.repositoryName}`); core.info(`Syncing repository: ${settings.repositoryOwner}/${settings.repositoryName}`);
const repositoryUrl = settings.sshKey // Remote URL
? `git@${hostname}:${encodeURIComponent(settings.repositoryOwner)}/${encodeURIComponent(settings.repositoryName)}.git` const httpsUrl = `https://${hostname}/${encodeURIComponent(settings.repositoryOwner)}/${encodeURIComponent(settings.repositoryName)}`;
: `https://${hostname}/${encodeURIComponent(settings.repositoryOwner)}/${encodeURIComponent(settings.repositoryName)}`; const sshUrl = `git@${hostname}:${encodeURIComponent(settings.repositoryOwner)}/${encodeURIComponent(settings.repositoryName)}.git`;
// Always fetch the workflow repository using the token, not the SSH key
const initialRemoteUrl = !settings.sshKey || settings.isWorkflowRepository ? httpsUrl : sshUrl;
// Remove conflicting file path // Remove conflicting file path
if (fsHelper.fileExistsSync(settings.repositoryPath)) { if (fsHelper.fileExistsSync(settings.repositoryPath)) {
yield io.rmRF(settings.repositoryPath); yield io.rmRF(settings.repositoryPath);
@ -5819,7 +5825,7 @@ function getSource(settings) {
const git = yield getGitCommandManager(settings); const git = yield getGitCommandManager(settings);
// Prepare existing directory, otherwise recreate // Prepare existing directory, otherwise recreate
if (isExisting) { if (isExisting) {
yield gitDirectoryHelper.prepareExistingDirectory(git, settings.repositoryPath, repositoryUrl, settings.clean); yield gitDirectoryHelper.prepareExistingDirectory(git, settings.repositoryPath, initialRemoteUrl, [httpsUrl, sshUrl], settings.clean);
} }
if (!git) { if (!git) {
// Downloading using REST API // Downloading using REST API
@ -5839,7 +5845,7 @@ function getSource(settings) {
// Initialize the repository // Initialize the repository
if (!fsHelper.directoryExistsSync(path.join(settings.repositoryPath, '.git'))) { if (!fsHelper.directoryExistsSync(path.join(settings.repositoryPath, '.git'))) {
yield git.init(); yield git.init();
yield git.remoteAdd('origin', repositoryUrl); yield git.remoteAdd('origin', initialRemoteUrl);
} }
// Disable automatic garbage collection // Disable automatic garbage collection
if (!(yield git.tryDisableAutomaticGarbageCollection())) { if (!(yield git.tryDisableAutomaticGarbageCollection())) {
@ -5864,6 +5870,10 @@ function getSource(settings) {
if (settings.lfs) { if (settings.lfs) {
yield git.lfsFetch(checkoutInfo.startPoint || checkoutInfo.ref); yield git.lfsFetch(checkoutInfo.startPoint || checkoutInfo.ref);
} }
// Fix URL when using SSH
if (settings.sshKey && initialRemoteUrl != sshUrl) {
yield git.setRemoteUrl(sshUrl);
}
// Checkout // Checkout
yield git.checkout(checkoutInfo.ref, checkoutInfo.startPoint); yield git.checkout(checkoutInfo.ref, checkoutInfo.startPoint);
// Submodules // Submodules
@ -7191,21 +7201,29 @@ var __importStar = (this && this.__importStar) || function (mod) {
return result; return result;
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const assert = __importStar(__webpack_require__(357));
const core = __importStar(__webpack_require__(470)); const core = __importStar(__webpack_require__(470));
const fs = __importStar(__webpack_require__(747)); const fs = __importStar(__webpack_require__(747));
const fsHelper = __importStar(__webpack_require__(618)); const fsHelper = __importStar(__webpack_require__(618));
const io = __importStar(__webpack_require__(1)); const io = __importStar(__webpack_require__(1));
const path = __importStar(__webpack_require__(622)); const path = __importStar(__webpack_require__(622));
function prepareExistingDirectory(git, repositoryPath, repositoryUrl, clean) { function prepareExistingDirectory(git, repositoryPath, initialRemoteUrl, allowedRemoteUrls, clean) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
assert.ok(repositoryPath, 'Expected repositoryPath to be defined');
assert.ok(allowedRemoteUrls, 'Expected allowedRemoteUrls to be defined');
assert.ok(allowedRemoteUrls.length, 'Expected allowedRemoteUrls to have at least one value');
assert.ok(initialRemoteUrl, 'Expected initialRemoteUrl to be defined');
// Indicates whether to delete the directory contents
let remove = false; let remove = false;
// The remote URL
let remoteUrl;
// Check whether using git or REST API // Check whether using git or REST API
if (!git) { if (!git) {
remove = true; remove = true;
} }
// Fetch URL does not match // Fetch URL does not match
else if (!fsHelper.directoryExistsSync(path.join(repositoryPath, '.git')) || else if (!fsHelper.directoryExistsSync(path.join(repositoryPath, '.git')) ||
repositoryUrl !== (yield git.tryGetFetchUrl())) { allowedRemoteUrls.indexOf((remoteUrl = yield git.tryGetRemoteUrl())) < 0) {
remove = true; remove = true;
} }
else { else {
@ -7250,6 +7268,10 @@ function prepareExistingDirectory(git, repositoryPath, repositoryUrl, clean) {
core.warning(`Unable to clean or reset the repository. The repository will be recreated instead.`); core.warning(`Unable to clean or reset the repository. The repository will be recreated instead.`);
} }
} }
// Always fetch the workflow repository using HTTPS
if (remoteUrl !== initialRemoteUrl) {
yield git.setRemoteUrl(initialRemoteUrl);
}
} }
catch (error) { catch (error) {
core.warning(`Unable to prepare the existing repository. The repository will be recreated instead.`); core.warning(`Unable to prepare the existing repository. The repository will be recreated instead.`);
@ -13989,6 +14011,7 @@ const core = __importStar(__webpack_require__(470));
const fsHelper = __importStar(__webpack_require__(618)); const fsHelper = __importStar(__webpack_require__(618));
const github = __importStar(__webpack_require__(469)); const github = __importStar(__webpack_require__(469));
const path = __importStar(__webpack_require__(622)); const path = __importStar(__webpack_require__(622));
const hostname = 'github.com';
function getInputs() { function getInputs() {
const result = {}; const result = {};
// GitHub workspace // GitHub workspace
@ -14018,12 +14041,13 @@ function getInputs() {
throw new Error(`Repository path '${result.repositoryPath}' is not under '${githubWorkspacePath}'`); throw new Error(`Repository path '${result.repositoryPath}' is not under '${githubWorkspacePath}'`);
} }
// Workflow repository? // Workflow repository?
const isWorkflowRepository = qualifiedRepository.toUpperCase() === result.isWorkflowRepository =
`${github.context.repo.owner}/${github.context.repo.repo}`.toUpperCase(); qualifiedRepository.toUpperCase() ===
`${github.context.repo.owner}/${github.context.repo.repo}`.toUpperCase();
// Source branch, source version // Source branch, source version
result.ref = core.getInput('ref'); result.ref = core.getInput('ref');
if (!result.ref) { if (!result.ref) {
if (isWorkflowRepository) { if (result.isWorkflowRepository) {
result.ref = github.context.ref; result.ref = github.context.ref;
result.commit = github.context.sha; result.commit = github.context.sha;
// Some events have an unqualifed ref. For example when a PR is merged (pull_request closed event), // Some events have an unqualifed ref. For example when a PR is merged (pull_request closed event),

View file

@ -33,6 +33,7 @@ export interface IGitCommandManager {
remoteAdd(remoteName: string, remoteUrl: string): Promise<void> remoteAdd(remoteName: string, remoteUrl: string): Promise<void>
removeEnvironmentVariable(name: string): void removeEnvironmentVariable(name: string): void
setEnvironmentVariable(name: string, value: string): void setEnvironmentVariable(name: string, value: string): void
setRemoteUrl(url: string): Promise<void>
submoduleForeach(command: string, recursive: boolean): Promise<string> submoduleForeach(command: string, recursive: boolean): Promise<string>
submoduleSync(recursive: boolean): Promise<void> submoduleSync(recursive: boolean): Promise<void>
submoduleUpdate(fetchDepth: number, recursive: boolean): Promise<void> submoduleUpdate(fetchDepth: number, recursive: boolean): Promise<void>
@ -40,7 +41,7 @@ export interface IGitCommandManager {
tryClean(): Promise<boolean> tryClean(): Promise<boolean>
tryConfigUnset(configKey: string, globalConfig?: boolean): Promise<boolean> tryConfigUnset(configKey: string, globalConfig?: boolean): Promise<boolean>
tryDisableAutomaticGarbageCollection(): Promise<boolean> tryDisableAutomaticGarbageCollection(): Promise<boolean>
tryGetFetchUrl(): Promise<string> tryGetRemoteUrl(): Promise<string>
tryReset(): Promise<boolean> tryReset(): Promise<boolean>
} }
@ -241,6 +242,10 @@ class GitCommandManager {
this.gitEnv[name] = value this.gitEnv[name] = value
} }
async setRemoteUrl(value: string): Promise<void> {
await this.config('git.remote.url', value)
}
async submoduleForeach(command: string, recursive: boolean): Promise<string> { async submoduleForeach(command: string, recursive: boolean): Promise<string> {
const args = ['submodule', 'foreach'] const args = ['submodule', 'foreach']
if (recursive) { if (recursive) {
@ -309,7 +314,7 @@ class GitCommandManager {
return output.exitCode === 0 return output.exitCode === 0
} }
async tryGetFetchUrl(): Promise<string> { async tryGetRemoteUrl(): Promise<string> {
const output = await this.execGit( const output = await this.execGit(
['config', '--local', '--get', 'remote.origin.url'], ['config', '--local', '--get', 'remote.origin.url'],
true true

View file

@ -1,18 +1,30 @@
import * as assert from 'assert'
import * as core from '@actions/core' import * as core from '@actions/core'
import * as fs from 'fs' import * as fs from 'fs'
import * as fsHelper from './fs-helper' import * as fsHelper from './fs-helper'
import * as io from '@actions/io' import * as io from '@actions/io'
import * as path from 'path' import * as path from 'path'
import {IGitCommandManager} from './git-command-manager' import {IGitCommandManager} from './git-command-manager'
import {IGitSourceSettings} from './git-source-settings'
export async function prepareExistingDirectory( export async function prepareExistingDirectory(
git: IGitCommandManager | undefined, git: IGitCommandManager | undefined,
repositoryPath: string, repositoryPath: string,
repositoryUrl: string, preferredRemoteUrl: string,
allowedRemoteUrls: string[],
clean: boolean clean: boolean
): Promise<void> { ): Promise<void> {
assert.ok(repositoryPath, 'Expected repositoryPath to be defined')
assert.ok(preferredRemoteUrl, 'Expected preferredRemoteUrl to be defined')
assert.ok(allowedRemoteUrls, 'Expected allowedRemoteUrls to be defined')
assert.ok(allowedRemoteUrls.length, 'Expected allowedRemoteUrls to have at least one value')
// Indicates whether to delete the directory contents
let remove = false let remove = false
// The remote URL
let remoteUrl: string
// Check whether using git or REST API // Check whether using git or REST API
if (!git) { if (!git) {
remove = true remove = true
@ -20,7 +32,7 @@ export async function prepareExistingDirectory(
// Fetch URL does not match // Fetch URL does not match
else if ( else if (
!fsHelper.directoryExistsSync(path.join(repositoryPath, '.git')) || !fsHelper.directoryExistsSync(path.join(repositoryPath, '.git')) ||
repositoryUrl !== (await git.tryGetFetchUrl()) allowedRemoteUrls.indexOf((remoteUrl = await git.tryGetRemoteUrl())) < 0
) { ) {
remove = true remove = true
} else { } else {
@ -72,6 +84,11 @@ export async function prepareExistingDirectory(
) )
} }
} }
// Update to the preferred remote URL
if (remoteUrl !== preferredRemoteUrl) {
await git.setRemoteUrl(preferredRemoteUrl)
}
} catch (error) { } catch (error) {
core.warning( core.warning(
`Unable to prepare the existing repository. The repository will be recreated instead.` `Unable to prepare the existing repository. The repository will be recreated instead.`

View file

@ -14,17 +14,21 @@ import {IGitSourceSettings} from './git-source-settings'
const hostname = 'github.com' const hostname = 'github.com'
export async function getSource(settings: IGitSourceSettings): Promise<void> { export async function getSource(settings: IGitSourceSettings): Promise<void> {
// Repository URL
core.info( core.info(
`Syncing repository: ${settings.repositoryOwner}/${settings.repositoryName}` `Syncing repository: ${settings.repositoryOwner}/${settings.repositoryName}`
) )
const repositoryUrl = settings.sshKey
? `git@${hostname}:${encodeURIComponent( // Remote URL
settings.repositoryOwner const httpsUrl = `https://${hostname}/${encodeURIComponent(
)}/${encodeURIComponent(settings.repositoryName)}.git` settings.repositoryOwner
: `https://${hostname}/${encodeURIComponent( )}/${encodeURIComponent(settings.repositoryName)}`
settings.repositoryOwner const sshUrl = `git@${hostname}:${encodeURIComponent(
)}/${encodeURIComponent(settings.repositoryName)}` settings.repositoryOwner
)}/${encodeURIComponent(settings.repositoryName)}.git`
// Always fetch the workflow repository using the token, not the SSH key
const initialRemoteUrl =
!settings.sshKey || settings.isWorkflowRepository ? httpsUrl : sshUrl
// Remove conflicting file path // Remove conflicting file path
if (fsHelper.fileExistsSync(settings.repositoryPath)) { if (fsHelper.fileExistsSync(settings.repositoryPath)) {
@ -46,7 +50,8 @@ export async function getSource(settings: IGitSourceSettings): Promise<void> {
await gitDirectoryHelper.prepareExistingDirectory( await gitDirectoryHelper.prepareExistingDirectory(
git, git,
settings.repositoryPath, settings.repositoryPath,
repositoryUrl, initialRemoteUrl,
[httpsUrl, sshUrl],
settings.clean settings.clean
) )
} }
@ -86,7 +91,7 @@ export async function getSource(settings: IGitSourceSettings): Promise<void> {
!fsHelper.directoryExistsSync(path.join(settings.repositoryPath, '.git')) !fsHelper.directoryExistsSync(path.join(settings.repositoryPath, '.git'))
) { ) {
await git.init() await git.init()
await git.remoteAdd('origin', repositoryUrl) await git.remoteAdd('origin', initialRemoteUrl)
} }
// Disable automatic garbage collection // Disable automatic garbage collection
@ -124,6 +129,11 @@ export async function getSource(settings: IGitSourceSettings): Promise<void> {
await git.lfsFetch(checkoutInfo.startPoint || checkoutInfo.ref) await git.lfsFetch(checkoutInfo.startPoint || checkoutInfo.ref)
} }
// Fix URL when using SSH
if (settings.sshKey && initialRemoteUrl != sshUrl) {
await git.setRemoteUrl(sshUrl)
}
// Checkout // Checkout
await git.checkout(checkoutInfo.ref, checkoutInfo.startPoint) await git.checkout(checkoutInfo.ref, checkoutInfo.startPoint)

View file

@ -1,17 +1,81 @@
export interface IGitSourceSettings { export interface IGitSourceSettings {
/**
* The location on disk where the repository will be placed
*/
repositoryPath: string repositoryPath: string
/**
* The repository owner
*/
repositoryOwner: string repositoryOwner: string
/**
* The repository name
*/
repositoryName: string repositoryName: string
/**
* Indicates whether the repository is main workflow repository
*/
isWorkflowRepository: boolean
/**
* The ref to fetch
*/
ref: string ref: string
/**
* The commit to checkout
*/
commit: string commit: string
/**
* Indicates whether to clean the repository
*/
clean: boolean clean: boolean
/**
* The depth when fetching
*/
fetchDepth: number fetchDepth: number
/**
* Indicates whether to fetch LFS objects
*/
lfs: boolean lfs: boolean
/**
* Indicates whether to checkout submodules
*/
submodules: boolean submodules: boolean
/**
* Indicates whether to recursively checkout submodules
*/
nestedSubmodules: boolean nestedSubmodules: boolean
/**
* The auth token to use when fetching the repository
*/
authToken: string authToken: string
/**
* The SSH key to configure
*/
sshKey: string sshKey: string
/**
* Additional SSH known hosts
*/
sshKnownHosts: string sshKnownHosts: string
/**
* Indicates whether the server must be a known host
*/
sshStrict: boolean sshStrict: boolean
/**
* Indicates whether to persist the credentials on disk to enable scripting authenticated git commands
*/
persistCredentials: boolean persistCredentials: boolean
} }

View file

@ -4,6 +4,8 @@ import * as github from '@actions/github'
import * as path from 'path' import * as path from 'path'
import {IGitSourceSettings} from './git-source-settings' import {IGitSourceSettings} from './git-source-settings'
const hostname = 'github.com'
export function getInputs(): IGitSourceSettings { export function getInputs(): IGitSourceSettings {
const result = ({} as unknown) as IGitSourceSettings const result = ({} as unknown) as IGitSourceSettings
@ -51,14 +53,14 @@ export function getInputs(): IGitSourceSettings {
} }
// Workflow repository? // Workflow repository?
const isWorkflowRepository = result.isWorkflowRepository =
qualifiedRepository.toUpperCase() === qualifiedRepository.toUpperCase() ===
`${github.context.repo.owner}/${github.context.repo.repo}`.toUpperCase() `${github.context.repo.owner}/${github.context.repo.repo}`.toUpperCase()
// Source branch, source version // Source branch, source version
result.ref = core.getInput('ref') result.ref = core.getInput('ref')
if (!result.ref) { if (!result.ref) {
if (isWorkflowRepository) { if (result.isWorkflowRepository) {
result.ref = github.context.ref result.ref = github.context.ref
result.commit = github.context.sha result.commit = github.context.sha