Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
quarto-dev
GitHub Repository: quarto-dev/quarto-cli
Path: blob/main/src/core/file.ts
3562 views
1
/*
2
* file.ts
3
*
4
* Copyright (C) 2020-2022 Posit Software, PBC
5
*/
6
7
import { existsSync } from "../deno_ral/fs.ts";
8
import { isWindows } from "../deno_ral/platform.ts";
9
import { execProcess } from "./process.ts";
10
import { TextLineStream } from "streams/text-line-stream";
11
12
export function existsSync1(s: string | URL) {
13
// eat all but the first param to work in map, filter, find, etc.
14
return existsSync(s);
15
}
16
17
export async function visitLines(
18
path: string,
19
visitor: (line: string | null, count: number) => boolean,
20
) {
21
if (existsSync(path)) {
22
const file = await Deno.open(path, { read: true });
23
try {
24
const stream = file.readable
25
.pipeThrough(new TextDecoderStream())
26
.pipeThrough(new TextLineStream());
27
28
let count = 0;
29
for await (const line of stream) {
30
if (line !== null) {
31
if (!visitor(line, count)) {
32
break;
33
}
34
} else {
35
break;
36
}
37
count += 1;
38
}
39
} finally {
40
try {
41
file.close();
42
} catch {
43
// Swallow error see https://github.com/denoland/deno/issues/15442
44
}
45
}
46
}
47
}
48
49
export async function appendTextFile(
50
path: string,
51
text: string,
52
) {
53
const file = await Deno.open(path, { append: true });
54
try {
55
const encoder = new TextEncoder();
56
file.writeSync(encoder.encode(text));
57
} finally {
58
file.close();
59
}
60
}
61
62
export async function touch(path: string) {
63
if (isWindows) {
64
// TODO is there a better way to do this that doesn't rewrite the file?
65
// Touch the file be rewriting it
66
const contents = await Deno.readFileSync(path);
67
await Deno.writeFileSync(path, contents);
68
} else {
69
await execProcess({
70
cmd: "touch",
71
args: [path],
72
});
73
}
74
}
75
76