aboutsummaryrefslogtreecommitdiff
path: root/packages/server/src/git/commit.ts
blob: 4b3e44b5b50c1c9ceccf61b7a8869d68170238d8 (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
import { Commit as NodeGitCommit, Oid as NodeGitOid } from "nodegit";
import { Author } from "./misc";
import { Diff } from "./diff";
import { Repository } from "./repository";
import { Tree } from "./tree";

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

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

export class Commit {
	private _ng_commit: NodeGitCommit;
	private _owner: Repository;

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

	constructor(owner: Repository, commit: NodeGitCommit) {
		this._ng_commit = commit;
		this._owner = owner;

		this.id = commit.sha();
		this.author = {
			name: commit.author().name(),
			email: commit.author().email()
		};
		this.date = commit.time();
		this.message = commit.message();
	}

	public async diff(): Promise<Diff> {
		return new Diff((await this._ng_commit.getDiff())[0]);
	}

	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()
		};
	}

	public async tree(): Promise<Tree> {
		return new Tree(this._owner, await this._ng_commit.getTree());
	}

	public static async lookup(repository: Repository, id: string | NodeGitOid): Promise<Commit> {
		const commit = await NodeGitCommit.lookup(repository.nodegitRepository, id instanceof NodeGitOid ? id : NodeGitOid.fromString(id));
		return new Commit(repository, commit);
	}

	public static lookupExists(repository: Repository, id: string): Promise<boolean> {
		return NodeGitCommit.lookup(repository.nodegitRepository, NodeGitOid.fromString(id))
			.then(() => true)
			.catch(() => false);
	}
}