-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathopen-file.ts
More file actions
59 lines (48 loc) · 1.36 KB
/
open-file.ts
File metadata and controls
59 lines (48 loc) · 1.36 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
import childProcess from "child_process";
import { promisify } from "util";
import os from "os";
import fs from "fs/promises";
import path from "path";
import logger from "@captain/logger";
const promisifiedExecFile = promisify(childProcess.execFile);
const getCommand = () => {
const plat = os
.platform()
.toLowerCase()
.replace(/[0-9]/g, ``)
.replace(`darwin`, `macos`);
if (plat === "win") return "start";
if (plat === "linux") return "xdg-open";
if (plat === "macos") return "open";
throw new Error("Idk what os this is");
};
const pathExists = async (path: string) => {
try {
await fs.access(path);
return true;
} catch {
return false;
}
};
const writeFile = async (filePath: string, data: string) => {
try {
const dirname = path.dirname(filePath);
const exist = await pathExists(dirname);
if (!exist) {
await fs.mkdir(dirname, { recursive: true });
}
await fs.writeFile(filePath, data, "utf8");
} catch (err) {
throw err;
}
};
export async function openFile(path: string) {
const exists = await pathExists(path);
const maybeFileName = path.split("/").pop();
// create file if it doesn't exist
if (!exists) {
logger.warn(`${maybeFileName ?? "file"} does not exist, creating it now!`);
await writeFile(path, "{}");
}
return await promisifiedExecFile(getCommand(), [path]);
}