aboutsummaryrefslogtreecommitdiff
path: root/packages/server/src/git/commit.ts
blob: 7062304ad93913d12877524a486cdb97246d6642 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import { Commit as NodeGitCommit, Oid as NodeGitOid, Revwalk as NodeGitRevwalk } from "nodegit";
import { Author } from "api";
import { Diff } from "./diff";
import { Repository } from "./repository";
import { Tree } from "./tree";
import { promisify } from "util";
import { exec, ExecException } from "child_process";
import { ErrorWhere, createError, CommitNotSignedError, FailedError, NotInKeyringError } from "./error";
import { createMessage, readKey, readSignature, verify } from "openpgp";

const pExec = promisify(exec);

export type CommitSummary = {
	id: string,
	message: string,
	date: number
}

type DiffStats = {
	insertions: number,
	deletions: number,
	files_changed: number
}

/**
 * A author of a commit
 */
export class CommitAuthor implements Author {
	private _commit;

	constructor(commit: Commit) {
		this._commit = commit;
	}

	public get name(): string {
		return this._commit.ng_commit.author().name();
	}

	public get email(): string {
		return this._commit.ng_commit.author().email();
	}

	/**
	 * Returns the public key fingerprint of the commit's signer.
	 */
	public async fingerprint(): Promise<string> {
		if(!await this._commit.isSigned()) {
			throw(createError(ErrorWhere.Commit, CommitNotSignedError));
		}

		const key = await pExec(`gpg --list-public-keys ${this.email}`).catch((err: ExecException) => {
			return {
				stdout: null,
				stderr: err.message.split("\n")[1]
			};
		});

		if(key.stderr || !key.stdout) {
			if(/^gpg: error reading key: No public key\n?/.test(key.stderr)) {
				throw(createError(ErrorWhere.Commit, NotInKeyringError, this.email));
			}

			throw(createError(ErrorWhere.Commit, FailedError, `receive pgp key for '${this.email}'`));
		}

		return key.stdout
			.split("\n")[1]
			.replace(/^\s*/, "");
	}
}

/**
 * A representation of a commit
 */
export class Commit {
	private _owner: Repository;

	public ng_commit: NodeGitCommit;

	public id: string;
	public date: number;
	public message: string;

	/**
	 * @param owner - The repository which the commit is in
	 * @param commit - An instance of a Nodegit commit
	 */
	constructor(owner: Repository, commit: NodeGitCommit) {
		this.ng_commit = commit;
		this._owner = owner;
		this.id = commit.sha();
		this.date = commit.time();
		this.message = commit.message();
	}

	/**
	 * Returns the commit's author
	 *
	 * @returns An instance of a commit author
	 */
	public author(): CommitAuthor {
		return new CommitAuthor(this);
	}

	/**
	 * Returns the commit's diff
	 *
	 * @returns An instance of a diff
	 */
	public async diff(): Promise<Diff> {
		return new Diff((await this.ng_commit.getDiff())[0]);
	}

	/**
	 * Returns the commit's stats
	 *
	 * @returns A diff stats instance
	 */
	public async stats(): Promise<DiffStats> {
		const stats = await (await this.ng_commit.getDiff())[0].getStats();

		return {
			insertions: <number>stats.insertions(),
			deletions: <number>stats.deletions(),
			files_changed: <number>stats.filesChanged()
		};
	}

	/**
	 * Returns the commit's tree
	 *
	 * @returns An instance of a tree
	 */
	public async tree(): Promise<Tree> {
		return new Tree(this._owner, await this.ng_commit.getTree());
	}

	/**
	 * Returns whether or not the commit is signed
	 */
	public isSigned(): Promise<boolean> {
		return this.ng_commit.getSignature()
			.then(() => true)
			.catch(() => false);
	}

	/**
	 * Verify the commit's pgp signature
	 *
	 * @returns Whether or not the signature is valid
	 */
	public async verifySignature(): Promise<boolean> {
		const fingerprint = await this.author().fingerprint();

		const pub_key = await pExec(`gpg --armor --export ${fingerprint}`).catch((err: ExecException) => {
			return {
				stdout: null,
				stderr: err.message
			};
		});

		if(pub_key.stderr || !pub_key.stdout) {
			throw(createError(ErrorWhere.Commit, FailedError, "export a public key from gpg!"));
		}

		const pgp_signature = await this.ng_commit.getSignature();

		return await verify({
			message: await createMessage({ text: pgp_signature.signedData }),
			verificationKeys: await readKey({ armoredKey: pub_key.stdout }),
			expectSigned: true,
			signature: await readSignature({ armoredSignature: pgp_signature.signature })
		})
			.then(result => result.signatures[0].verified)
			.catch(() => Promise.resolve(false));
	}

	/**
	 * Lookup a commit
	 *
	 * @param repository - The repository which the commit is in
	 * @param id - The SHA of a commit
	 * @returns An instance of a commit
	 */
	public static async lookup(repository: Repository, id: string | NodeGitOid): Promise<Commit> {
		const commit = await NodeGitCommit.lookup(repository.ng_repository, id instanceof NodeGitOid ? id : NodeGitOid.fromString(id));
		return new Commit(repository, commit);
	}

	/**
	 * Returns if an commit exists or not
	 *
	 * @param repository - The repository which the commit is in
	 * @param id - The sha of a commit
	 * @returns Whether or not the commit exists
	 */
	public static lookupExists(repository: Repository, id: string): Promise<boolean> {
		return NodeGitCommit.lookup(repository.ng_repository, NodeGitOid.fromString(id))
			.then(() => true)
			.catch(() => false);
	}

	/**
	 * Returns the most recent commit of the repository's branch
	 *
	 * @param owner - A repository
	 * @returns An instance of a commit
	 */
	public static async branchCommit(owner: Repository): Promise<Commit> {
		return new Commit(owner, await owner.ng_repository.getBranchCommit(owner.branch));
	}

	/**
	 * Returns a number of commits in a repository
	 *
	 * @param owner - The repository which the commits are in
	 * @param [amount=20] - The number of commits to get or whether or not to get all commits
	 * @returns An array of commit instances
	 */
	public static async getMultiple(owner: Repository, amount: number | boolean = 20): Promise<Commit[]> {
		const walker = NodeGitRevwalk.create(owner.ng_repository);

		walker.pushRef(`refs/heads/${owner.branch}`);

		if(typeof amount === "boolean") {
			return Promise.all((await (amount
				? walker.getCommitsUntil(() => true)
				: walker.getCommits(20)
			)).map(commit => new Commit(owner, commit)));
		}

		return Promise.all((await walker.getCommits(amount)).map(commit => new Commit(owner, commit)));
	}
}