Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use git command to commit and push version file updates. #16

Merged
merged 4 commits into from
Aug 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ For more information, reference the GitHub Help Documentation for [Creating a wo
### Inputs

- `version`: The version number to use.
- `token`: The GitHub token to use for the commit.
- `path`: The path to the file within the repository.
- `user-email`: The email of the user that commits the version file.
- `user-name`: The name of the user that commits the version file.

For information on how GitHub actions tokens work, read more [here](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/authenticating-with-the-github_token#about-the-github_token-secret).

Expand All @@ -48,8 +49,9 @@ jobs:
uses: dolittle/write-version-to-file-action@v2
with:
version: ${{ steps.context.outputs.current-version }}
token: ${{ secrets.GITHUB_TOKEN }}
path: ./Source/version.json
user-email: [email protected]
user-name: dolittle-build
```

## Contributing
Expand Down
154 changes: 49 additions & 105 deletions Source/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,125 +2,36 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

import * as core from '@actions/core';
import { Logger } from '@dolittle/github-actions.shared.logging';
import * as github from '@actions/github';

import { exec } from '@actions/exec';
import path from 'path';
import editJsonFile from 'edit-json-file';
import { Octokit } from '@octokit/core';

import * as fs from 'fs';
import { Logger } from '@dolittle/github-actions.shared.logging';

const logger = new Logger();

async function getCurrentCommit(
octo: Octokit,
owner: string,
repo: string,
ref: string) {

const { data: refData } = await octo.git.getRef({
owner,
repo,
ref,
});

const commitSha = refData.object.sha;
const { data: commitData } = await octo.git.getCommit({
owner: owner,
repo,
commit_sha: commitSha,
});

return {
commitSha,
treeSha: commitData.tree.sha,
};
}

async function createNewTree(
octo: Octokit,
owner: string,
repo: string,
blobs: any[],
paths: string[],
parentTreeSha: string) {

// My custom config. Could be taken as parameters
const tree = blobs.map(({ sha }, index) => ({
path: paths[index],
mode: '100644',
type: 'blob',
sha,
}));

const { data } = await octo.git.createTree({
owner,
repo,
tree,
base_tree: parentTreeSha,
});

return data;
}

const getFileAsUTF8 = (filePath: string) => fs.promises.readFile(filePath, 'utf8');

async function createBlobForFile(octo: Octokit, org: string, repo: string, filePath: string) {
const content = await getFileAsUTF8(filePath);
const blobData = await octo.git.createBlob({
owner: org,
repo,
content,
encoding: 'utf-8',
});

return blobData.data;
}

run();
export async function run() {
try {
const path = core.getInput('path', { required: true });
const version = core.getInput('version', { required: true });
const token = core.getInput('token', { required: true });

logger.info(`Path : ${path}`);
logger.info(`Version: ${version}`);

const octokit = github.getOctokit(token);

const currentRepo = github.context.repo;
const currentRef = github.context.ref.replace('refs/', '');

logger.info(`Current repo ${currentRepo.owner} - ${currentRepo.repo}`);
const path = core.getInput('path', { required: true });

const file = editJsonFile(path);
file.set('version', version);
file.set('commit', github.context.sha);
file.set('built', new Date().toISOString());
file.save();
const userEmail = core.getInput('user-email', { required: false }) || '[email protected]';
const userName = core.getInput('user-name', { required: false }) || 'dolittle-build';

const currentCommit = await getCurrentCommit(octokit, currentRepo.owner, currentRepo.repo, currentRef);
const commitSHA = github.context.sha;
const buildDate = new Date().toISOString();

const blob = await createBlobForFile(octokit, currentRepo.owner, currentRepo.repo, path);
logger.info('Writing build version information to file');
logger.info(`\tPath : ${path}`);
logger.info(`\tVersion: ${version}`);
logger.info(`\tCommit: ${commitSHA}`);
logger.info(`\tBuilt: ${buildDate}`);

const tree = await createNewTree(octokit, currentRepo.owner, currentRepo.repo, [blob], [path], currentCommit.treeSha);
const newCommit = await octokit.git.createCommit({
owner: currentRepo.owner,
repo: currentRepo.repo,
message: 'Updating version information',
tree: tree.sha,
parents: [currentCommit.commitSha]
});
updateVersionFile(path, version, commitSHA, buildDate);
await commitVersionFile(path, version, userEmail, userName);
await pushChanges();

await octokit.git.updateRef({
owner: currentRepo.owner,
repo: currentRepo.repo,
ref: currentRef,
sha: newCommit.data.sha
});

logger.info('Version updated, written and committed');
} catch (error) {
logger.info(`Error : ${error}`);
fail(error);
Expand All @@ -131,3 +42,36 @@ function fail(error: Error) {
logger.error(error.message);
core.setFailed(error.message);
}

function updateVersionFile(filePath: string, version: string, commitSHA: string, buildDate: string) {
logger.info(`Updating version file ${filePath}`);
const file = editJsonFile(filePath);
file.set('version', version);
file.set('commit', commitSHA);
file.set('built', buildDate);
file.save();
}

async function commitVersionFile(filePath: string, version: string, userEmail: string, userName: string) {
logger.info(`Adding and committing ${filePath}`);
await exec('git add', [filePath]);
await exec(
'git commit',
[
`-m "Update to ${version} in version file"`
],
{
env: {
GIT_AUTHOR_NAME: userName,
GIT_AUTHOR_EMAIL: userEmail,
GIT_COMMITTER_NAME: userName,
GIT_COMMITTER_EMAIL: userEmail,
},
});
}

async function pushChanges() {
const branchName = path.basename(github.context.ref);
logger.info(`Pushing changelog to origin ${branchName}`);
await exec('git push origin', [branchName]);
}
15 changes: 10 additions & 5 deletions action.yml
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
name: 'Write Version To File'
description: 'Writes version information to a structured JSON file and commits the file'
inputs:
token:
description: The GitHub api token used to commit the file
version:
description: The version number to use
required: true
path:
description: The path to the version file to output
required: true
version:
description: The version number to use
required: true
user-email:
description: The email of the user that commits the version file
required: false
default: '[email protected]'
user-name:
description: The name of the user that commits the version file
required: false
default: 'dolittle-build'

runs:
using: 'node12'
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
},
"dependencies": {
"@actions/core": "^1.2.4",
"@actions/exec": "1.0.4",
"@actions/github": "4.0.0",
"@dolittle/github-actions.shared.logging": "^1.1.1",
"@dolittle/github-actions.shared.rudiments": "^1.1.1",
Expand Down