Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 {
appendFileSync,
existsSync,
mkdirSync,
readdirSync,
readFileSync,
renameSync,
rmSync,
} from "node:fs";
import { dirname, join } from "node:path";
import process from "node:process";
import { at } from "../../shared/adapters/git.ts";
import { usageBufferPath } from "../../shared/adapters/usage.ts";
const LOG_ROOT = "data/telemetry";
const FLUSHING = /\.(\d+)\.flushing$/;
/** `kill(pid, 0)` sends nothing; it throws `ESRCH` only when no such process exists. */
const isAlive = (pid: number): boolean => {
try {
process.kill(pid, 0);
return true;
} catch (error) {
return (error as NodeJS.ErrnoException).code !== "ESRCH";
}
};
/**
* The buffer is renamed before it is read, so a script that finishes mid-flush appends to a fresh
* file instead of one about to be deleted. A `.flushing` is adopted only once its flush has died,
* since another worktree's commit may be flushing it right now.
*/
export const takeBuffer = (log: string): { text: string; discard: () => void } => {
const buffer = usageBufferPath(log);
const directory = dirname(buffer);
const taken = `${buffer}.${process.pid}.flushing`;
const files = existsSync(directory)
? readdirSync(directory)
.filter((name) => {
const pid = FLUSHING.exec(name)?.[1];
return pid !== undefined && !isAlive(Number(pid));
})
.map((name) => join(directory, name))
: [];
try {
renameSync(buffer, taken);
files.push(taken);
} catch {
// No buffer, or a concurrent flush renamed it first: nothing of ours to take.
}
return {
text: files.map((file) => readFileSync(file, "utf8")).join(""),
discard: () => files.forEach((file) => rmSync(file, { force: true })),
};
};
/** Returns the repo-relative path written to. */
export const appendToLog = (
log: string,
file: string,
columns: readonly string[],
lines: string[],
): string => {
const path = `${LOG_ROOT}/${log}/${file}`;
const absolute = at(path);
mkdirSync(dirname(absolute), { recursive: true });
const header = existsSync(absolute) ? "" : `${columns.join(",")}\n`;
appendFileSync(absolute, `${header}${lines.join("\n")}\n`);
return path;
};
|