Skip to content

Commit

Permalink
Merge pull request #27 from s0/feature/tags
Browse files Browse the repository at this point in the history
Implement Tags feature
  • Loading branch information
s0 authored Sep 19, 2020
2 parents 5111e9e + 0186901 commit ff973c4
Show file tree
Hide file tree
Showing 5 changed files with 168 additions and 15 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ All configuration options are passed in via `env`, as environment variables.
| `GITHUB_TOKEN` | Should always be equal to `${{ secrets.GITHUB_TOKEN }}` | When `REPO = self` |
| `SQUASH_HISTORY` | If set to `true`, all previous commits on the target branch will be discarded. For example, if you are deploying a static site with lots of binary artifacts, this can help the repository becoming overly bloated. | No |
| `MESSAGE` | A custom template to use as the commit message pushed to the target branch. See [custom commit messages](#custom-commit-messages). | No |
| `TAG` | A string following the [git-check-ref-format](https://git-scm.com/docs/git-check-ref-format) that tags the commit with a lightweight git-tag. | No |

## Custom commit messages

Expand Down
32 changes: 24 additions & 8 deletions action/dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8017,6 +8017,7 @@ var config = (function () {
var folder = ENV.FOLDER;
var squashHistory = ENV.SQUASH_HISTORY === 'true';
var message = ENV.MESSAGE || DEFAULT_MESSAGE;
var tag = ENV.TAG;
// Determine the type of URL
if (repo === REPO_SELF) {
if (!ENV.GITHUB_TOKEN)
Expand All @@ -8031,6 +8032,7 @@ var config = (function () {
squashHistory: squashHistory,
mode: 'self',
message: message,
tag: tag,
};
return config_1;
}
Expand All @@ -8048,6 +8050,7 @@ var config = (function () {
privateKey: ENV.SSH_PRIVATE_KEY,
knownHostsFile: ENV.KNOWN_HOSTS_FILE,
message: message,
tag: tag,
};
return config_2;
}
Expand Down Expand Up @@ -8082,7 +8085,7 @@ var writeToProcess = function (command, args, opts) { return new Promise(functio
});
}); };
(function () { return __awaiter(void 0, void 0, void 0, function () {
var TMP_PATH, REPO_TEMP, SSH_AUTH_SOCK, event, _a, _b, name, email, getGitInformation, gitInfo, env, known_hosts, sshAgentMatch, _c, _d, branchCheck, folder, message, forceArg, push;
var TMP_PATH, REPO_TEMP, SSH_AUTH_SOCK, event, _a, _b, name, email, tag, getGitInformation, gitInfo, env, known_hosts, sshAgentMatch, _c, _d, branchCheck, folder, message, forceArg, tagsArg, push;
var _e, _f;
return __generator(this, function (_g) {
switch (_g.label) {
Expand All @@ -8099,6 +8102,7 @@ var writeToProcess = function (command, args, opts) { return new Promise(functio
event = _b.apply(_a, [(_g.sent()).toString()]);
name = ((_e = event.pusher) === null || _e === void 0 ? void 0 : _e.name) || ENV.GITHUB_ACTOR || 'Git Publish Subdirectory';
email = ((_f = event.pusher) === null || _f === void 0 ? void 0 : _f.email) || (ENV.GITHUB_ACTOR ? ENV.GITHUB_ACTOR + "@users.noreply.github.com" : 'nobody@nowhere');
tag = ENV.TAG;
// Set Git Config
return [4 /*yield*/, exec("git config --global user.name \"" + name + "\"")];
case 3:
Expand Down Expand Up @@ -8294,24 +8298,36 @@ var writeToProcess = function (command, args, opts) { return new Promise(functio
fs: fs,
dir: REPO_TEMP,
message: message,
author: { email: email, name: name }
author: { email: email, name: name },
})];
case 28:
_g.sent();
if (!tag) return [3 /*break*/, 30];
console.log("##[info] Tagging commit with " + tag);
return [4 /*yield*/, isomorphic_git_1.default.tag({
fs: fs,
dir: REPO_TEMP,
ref: tag,
})];
case 29:
_g.sent();
_g.label = 30;
case 30:
console.log("##[info] Pushing");
forceArg = config.squashHistory ? '-f' : '';
return [4 /*yield*/, exec("git push " + forceArg + " origin \"" + config.branch + "\"", { env: env, cwd: REPO_TEMP })];
case 29:
tagsArg = tag ? '--tags' : '';
return [4 /*yield*/, exec("git push " + forceArg + " origin \"" + config.branch + "\" " + tagsArg, { env: env, cwd: REPO_TEMP })];
case 31:
push = _g.sent();
console.log(push.stdout);
console.log("##[info] Deployment Successful");
if (!(config.mode === 'ssh')) return [3 /*break*/, 31];
if (!(config.mode === 'ssh')) return [3 /*break*/, 33];
console.log("##[info] Killing ssh-agent");
return [4 /*yield*/, exec("ssh-agent -k", { env: env })];
case 30:
case 32:
_g.sent();
_g.label = 31;
case 31: return [2 /*return*/];
_g.label = 33;
case 33: return [2 /*return*/];
}
});
}); })().catch(function (err) {
Expand Down
32 changes: 25 additions & 7 deletions action/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ export interface EnvironmentVariables {
* * `{msg}` - the commit message for the HEAD of the current branch
*/
MESSAGE?: string;
/**
* An optional string in git-check-ref-format to use for tagging the commit
*/
TAG?: string;

// Implicit environment variables passed by GitHub

Expand All @@ -67,7 +71,7 @@ export interface EnvironmentVariables {

declare global {
namespace NodeJS {
interface ProcessEnv extends EnvironmentVariables {}
interface ProcessEnv extends EnvironmentVariables { }
}
}

Expand Down Expand Up @@ -116,6 +120,7 @@ interface BaseConfig {
repo: string;
squashHistory: boolean;
message: string;
tag?: string;
}

interface SshConfig extends BaseConfig {
Expand Down Expand Up @@ -154,6 +159,7 @@ const config: Config = (() => {
const folder = ENV.FOLDER;
const squashHistory = ENV.SQUASH_HISTORY === 'true';
const message = ENV.MESSAGE || DEFAULT_MESSAGE;
const tag = ENV.TAG;

// Determine the type of URL
if (repo === REPO_SELF) {
Expand All @@ -169,6 +175,7 @@ const config: Config = (() => {
squashHistory,
mode: 'self',
message,
tag,
};
return config;
}
Expand All @@ -187,13 +194,14 @@ const config: Config = (() => {
privateKey: ENV.SSH_PRIVATE_KEY,
knownHostsFile: ENV.KNOWN_HOSTS_FILE,
message,
tag,
};
return config;
}
throw new Error('Unsupported REPO URL');
})();

const writeToProcess = (command: string, args: string[], opts: {env: { [id: string]: string | undefined }; data: string;} ) => new Promise((resolve, reject) => {
const writeToProcess = (command: string, args: string[], opts: { env: { [id: string]: string | undefined }; data: string; }) => new Promise((resolve, reject) => {
const child = child_process.spawn(command, args, {
env: opts.env,
stdio: "pipe"
Expand Down Expand Up @@ -236,6 +244,7 @@ const writeToProcess = (command: string, args: string[], opts: {env: { [id: stri

const name = event.pusher?.name || ENV.GITHUB_ACTOR || 'Git Publish Subdirectory';
const email = event.pusher?.email || (ENV.GITHUB_ACTOR ? `${ENV.GITHUB_ACTOR}@users.noreply.github.com` : 'nobody@nowhere');
const tag = ENV.TAG

// Set Git Config
await exec(`git config --global user.name "${name}"`);
Expand Down Expand Up @@ -309,13 +318,13 @@ const writeToProcess = (command: string, args: string[], opts: {env: { [id: stri
if (!known_hosts) {
console.warn(KNOWN_HOSTS_WARNING);
} else {
await mkdir(SSH_FOLDER, {recursive: true});
await mkdir(SSH_FOLDER, { recursive: true });
await copyFile(known_hosts, KNOWN_HOSTS_TARGET);
}

// Setup ssh-agent with private key
console.log(`Setting up ssh-agent on ${SSH_AUTH_SOCK}`);
const sshAgentMatch = SSH_AGENT_PID_EXTRACT.exec((await exec(`ssh-agent -a ${SSH_AUTH_SOCK}`, {env})).stdout);
const sshAgentMatch = SSH_AGENT_PID_EXTRACT.exec((await exec(`ssh-agent -a ${SSH_AUTH_SOCK}`, { env })).stdout);
/* istanbul ignore if */
if (!sshAgentMatch)
throw new Error('Unexpected output from ssh-agent');
Expand Down Expand Up @@ -358,7 +367,7 @@ const writeToProcess = (command: string, args: string[], opts: {env: { [id: stri

// Check if branch already exists
console.log(`##[info] Checking if branch ${config.branch} exists already`);
const branchCheck = await exec(`git branch --list "${config.branch}"`, {env, cwd: REPO_TEMP });
const branchCheck = await exec(`git branch --list "${config.branch}"`, { env, cwd: REPO_TEMP });
if (branchCheck.stdout.trim() === '') {
// Branch does not exist yet, let's check it out as an orphan
console.log(`##[info] ${config.branch} does not exist, creating as orphan`);
Expand Down Expand Up @@ -396,11 +405,20 @@ const writeToProcess = (command: string, args: string[], opts: {env: { [id: stri
fs,
dir: REPO_TEMP,
message,
author: { email, name }
author: { email, name },
});
if (tag) {
console.log(`##[info] Tagging commit with ${tag}`)
await git.tag({
fs,
dir: REPO_TEMP,
ref: tag,
});
}
console.log(`##[info] Pushing`);
const forceArg = config.squashHistory ? '-f' : '';
const push = await exec(`git push ${forceArg} origin "${config.branch}"`, { env, cwd: REPO_TEMP });
const tagsArg = tag ? '--tags' : '';
const push = await exec(`git push ${forceArg} origin "${config.branch}" ${tagsArg}`, { env, cwd: REPO_TEMP });
console.log(push.stdout);
console.log(`##[info] Deployment Successful`);

Expand Down
23 changes: 23 additions & 0 deletions action/test/specs/__snapshots__/ssh-custom-tags.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Test custom tags 1`] = `
"msg:This is another commit follow up with no content changes
tree:8bf87c66655949e66937b11593cc4ae732d1f610
author:s0 <[email protected]>
msg:Update branch-a to output generated at <sha>
tree:8bf87c66655949e66937b11593cc4ae732d1f610
author:s0 <[email protected]>"
`;
exports[`Test custom tags 2`] = `
"msg:This is another commit follow up with no content changes
tree:8bf87c66655949e66937b11593cc4ae732d1f610
author:s0 <[email protected]>
msg:Update branch-a to output generated at <sha>
tree:8bf87c66655949e66937b11593cc4ae732d1f610
author:s0 <[email protected]>"
`;
95 changes: 95 additions & 0 deletions action/test/specs/ssh-custom-tags.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import * as fs from 'fs';
import * as path from 'path';
import git from 'isomorphic-git';

import * as util from '../util';

const REPO_DIR = path.join(util.REPOS_DIR, 'ssh-custom-tags.git');
const DATA_DIR = path.join(util.DATA_DIR, 'ssh-custom-tags');

it('Test custom tags', async () => {

// Create empty repo
await util.mkdir(REPO_DIR);
await util.execWithOutput('git init --bare', { cwd: REPO_DIR });

// Create dummy data
await util.mkdir(DATA_DIR);
await util.mkdir(path.join(DATA_DIR, 'dummy'));
await util.writeFile(path.join(DATA_DIR, 'dummy', 'baz'), 'foobar');
await util.writeFile(path.join(DATA_DIR, 'dummy', '.bat'), 'foobar');

// Run Action
await util.runWithGithubEnv(
path.basename(__filename),
{
REPO: 'ssh://git@git-ssh/git-server/repos/ssh-custom-tags.git',
BRANCH: 'branch-a',
FOLDER: DATA_DIR,
SSH_PRIVATE_KEY: (await util.readFile(util.SSH_PRIVATE_KEY)).toString(),
KNOWN_HOSTS_FILE: util.KNOWN_HOSTS,
},
's0/test',
{},
's0',
);
// Run the action again to make sure that a commit is added even when there are
// no content changes
await util.runWithGithubEnv(
path.basename(__filename),
{
REPO: 'ssh://git@git-ssh/git-server/repos/ssh-custom-tags.git',
BRANCH: 'branch-a',
FOLDER: DATA_DIR,
SSH_PRIVATE_KEY: (await util.readFile(util.SSH_PRIVATE_KEY)).toString(),
KNOWN_HOSTS_FILE: util.KNOWN_HOSTS,
MESSAGE: 'This is another commit follow up with no content changes',
TAG: 'foo-bar-tag-v0.1.2',
},
's0/test',
{},
's0',
);

{
// Check that the log of the branch is as expected
let log = (await util.exec(
'git log --pretty="format:msg:%B%ntree:%T%nauthor:%an <%ae>" branch-a',
{
cwd: REPO_DIR
}
)).stdout;
const fullSha = await util.getFullRepoSha();
const sha = fullSha.substr(0, 7);
const cleanedLog = log.replace(fullSha, '<long-sha>').replace(sha, '<sha>');
expect(cleanedLog).toMatchSnapshot();
}

{
// Check that the log got the tag is also as expected
let log = (await util.exec(
'git log --pretty="format:msg:%B%ntree:%T%nauthor:%an <%ae>" foo-bar-tag-v0.1.2',
{
cwd: REPO_DIR
}
)).stdout;
const fullSha = await util.getFullRepoSha();
const sha = fullSha.substr(0, 7);
const cleanedLog = log.replace(fullSha, '<long-sha>').replace(sha, '<sha>');
expect(cleanedLog).toMatchSnapshot();
}

// Ensure that commits for branch and tag are identical
const tagSha = await git.resolveRef({
fs,
gitdir: REPO_DIR,
ref: 'refs/tags/foo-bar-tag-v0.1.2',
});
const branchSha = await git.resolveRef({
fs,
gitdir: REPO_DIR,
ref: 'refs/heads/branch-a',
});
expect(tagSha).toEqual(branchSha);

});

0 comments on commit ff973c4

Please sign in to comment.