aboutsummaryrefslogtreecommitdiff
path: root/packages/server/src/git/misc.ts
blob: 43c7a70476e60c46123ed044e12f04ba19413d15 (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
import { readFile, readdir } from "fs";
import { createError, ErrorWhere, FailedError } from "./error";

/**
 * Asynchronously find an item in an array that matches the requirements set by the callback
 *
 * @param arr - The array to look in
 * @param callback - A callback that knowns what you're looking for
 * @returns The item in the array you wanted to find
 */
export async function findAsync<T>(arr: T[], callback: (t: T) => Promise<boolean>): Promise<T> {
	const results = await Promise.all(arr.map(callback));
	const index = results.findIndex(result => result);
	return arr[index];
}

/**
 * Returns the content of a file inside a repository
 *
 * @param git_dir - The directory which the repository is in
 * @param repository - The directory of a bare repository
 * @param file - The path of a file
 */
export function getFile(git_dir: string, repository: string, file: string): Promise<string> {
	return new Promise((resolve, reject) => {
		readFile(`${git_dir}/${repository}/${file}`, (err, content) => {
			if(err) {
				reject(createError(ErrorWhere.Misc, FailedError, `open repository file '${file}'`));
				return;
			}

			resolve(content.toString().replace(/\n/gu, ""));
		});
	});
}

/**
 * Returns all of the files & folders inside of a directory
 *
 * @param directory - The directory to look in
 * @returns An array of directory content
 */
export function getDirectory(directory: string): Promise<string[]> {
	return new Promise<string[]>((resolve, reject) => {
		readdir(directory, (err, dir_content) => {
			if(err) {
				reject(createError(ErrorWhere.Misc, FailedError, `open directory '${directory}'`));
				return;
			}

			resolve(dir_content);
		});
	});
}