aboutsummaryrefslogtreecommitdiff
path: root/packages/server/src/git/tree_entry.ts
blob: 3bcf10e0d31b2a4cc64da53591e7a9d5718b861b (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
import { Blob } from "./blob";
import { Commit } from "./commit";
import { TreeEntry as NodeGitTreeEntry } from "nodegit";
import { Repository } from "./repository";
import { Tree } from "./tree";
import { dirname } from "path";
import { findAsync } from "./misc";

export class TreeEntry {
	private _ng_tree_entry: NodeGitTreeEntry;
	private _owner: Repository;

	public path: string;
	public type: "blob" | "tree";

	constructor(owner: Repository, entry: NodeGitTreeEntry) {
		this._ng_tree_entry = entry;
		this._owner = owner;

		this.path = entry.path();
		this.type = entry.isBlob() ? "blob" : "tree";
	}

	async latestCommit(): Promise<Commit> {
		const commits = await this._owner.commits();

		return findAsync(commits, async commit => {
			const diff = await commit.diff();
			const patches = await diff.getPatches();

			return Boolean(this.type === "blob"
				? patches.find(patch => patch.to === this.path)
				: patches.find(patch => dirname(patch.to).startsWith(this.path)));
		});
	}

	async peel(): Promise<Blob | Tree> {
		return this.type === "blob" ? new Blob(this._ng_tree_entry) : new Tree(this._owner, await this._ng_tree_entry.getTree());
	}
}