-
-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathutil.ts
More file actions
76 lines (59 loc) · 2.26 KB
/
util.ts
File metadata and controls
76 lines (59 loc) · 2.26 KB
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
import { BenchmarkFunction } from "./benchmark_types";
export function toFixed(num: number, decimalPlaces = 0): string {
return string.format(`%.${decimalPlaces}f`, num);
}
export function calculatePercentageChange(oldValue: number, newValue: number): number {
return (newValue / oldValue) * 100 - 100;
}
// @ts-ignore
export const isWindows = package.config.startsWith("\\");
export const json: {
decode: (this: void, str: string) => Record<string, unknown> | unknown[];
encode: (this: void, val: any) => string;
} = require("json");
export function readFile(path: string): string {
const [fileHandle] = io.open(path, "rb");
if (!fileHandle) {
throw Error(`Can't open file ${path}`);
}
const fileContent = readAll(fileHandle);
fileHandle.close();
return fileContent;
}
export function readAll(file: LuaFile): string {
const content = file.read(_VERSION === "Lua 5.3" ? "a" : ("*a" as any));
if (content) {
return content as string;
}
throw Error(`Can't readAll for file ${file}`);
}
export function readDir(dir: string): string[] {
const [findHandle] = io.popen(isWindows ? `dir /A-D /B ${dir}` : `find '${dir}' -maxdepth 1 -type f`);
if (!findHandle) {
throw new Error(`Failed to read dir ${dir}`);
}
const findResult = readAll(findHandle);
if (!findHandle.close()) {
throw Error(`readDir popen failed for dir ${dir} see stdout for more information.`);
}
let files = findResult.split("\n");
if (isWindows) {
// on windows we need to append the directory path
// on unix this is done by find automatically
files = files.map(f => `${dir}/${f}`);
} else {
// strip leading "./" on unix
files = files.map(f => (f.startsWith(".") && f[1] === "/" ? f.substr(2) : f));
}
return files.filter(p => p !== "");
}
export function loadBenchmarksFromDirectory(benchmarkDir: string): BenchmarkFunction[] {
const benchmarkFiles = readDir(benchmarkDir);
return benchmarkFiles.map(f => {
// replace slashes with dots
let dotPath = string.gsub(f, "%/", ".")[0];
// remove extension
dotPath = string.gsub(dotPath, ".lua", "")[0];
return require(dotPath).default as BenchmarkFunction;
});
}