UNPKG

2.58 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const fs = require("fs-extra");
4const gh = require('github-url-to-object');
5const spawn = require('child_process').spawn;
6const tmp = require('tmp');
7const NOT_A_GIT_REPOSITORY = 'not a git repository';
8const RUN_IN_A_GIT_REPOSITORY = 'Please run this command from the directory containing your project\'s git repo';
9const NOT_ON_A_BRANCH = 'not a symbolic ref';
10const CHECKOUT_A_BRANCH = 'Please checkout a branch before running this command';
11function runGit(...args) {
12 const git = spawn('git', args);
13 return new Promise((resolve, reject) => {
14 git.on('exit', (exitCode) => {
15 if (exitCode === 0) {
16 return;
17 }
18 const error = (git.stderr.read() || 'unknown error').toString().trim();
19 if (error.toLowerCase().includes(NOT_A_GIT_REPOSITORY)) {
20 reject(RUN_IN_A_GIT_REPOSITORY);
21 return;
22 }
23 if (error.includes(NOT_ON_A_BRANCH)) {
24 reject(CHECKOUT_A_BRANCH);
25 return;
26 }
27 reject(new Error(`Error while running 'git ${args.join(' ')}' (${error})`));
28 });
29 git.stdout.on('data', (data) => resolve(data.toString().trim()));
30 });
31}
32async function getRef(branch) {
33 return runGit('rev-parse', branch || 'HEAD');
34}
35async function getBranch(symbolicRef) {
36 return runGit('symbolic-ref', '--short', symbolicRef);
37}
38async function getCommitTitle(ref) {
39 return runGit('log', ref || '', '-1', '--pretty=format:%s');
40}
41async function createArchive(ref) {
42 const tar = spawn('git', ['archive', '--format', 'tar.gz', ref]);
43 const file = tmp.fileSync({ postfix: '.tar.gz' });
44 const write = tar.stdout.pipe(fs.createWriteStream(file.name));
45 return new Promise((resolve, reject) => {
46 write.on('close', () => resolve(file.name));
47 write.on('error', reject);
48 });
49}
50exports.createArchive = createArchive;
51async function githubRepository() {
52 const remote = await runGit('remote', 'get-url', 'origin');
53 const repository = gh(remote);
54 if (repository === null) {
55 throw new Error('Not a GitHub repository');
56 }
57 return repository;
58}
59exports.githubRepository = githubRepository;
60async function readCommit(commit) {
61 const branch = await getBranch('HEAD');
62 const ref = await getRef(commit);
63 const message = await getCommitTitle(ref);
64 return Promise.resolve({
65 branch,
66 ref,
67 message,
68 });
69}
70exports.readCommit = readCommit;