Skip to content

Commit 64289c1

Browse files
committed
Make the reading and writing of files less ugly
1 parent 7e20f91 commit 64289c1

File tree

1 file changed

+23
-14
lines changed

1 file changed

+23
-14
lines changed

src/commands/tests.sidebar.ts

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -60,14 +60,23 @@ export function registerRunAll(testsDataProvider: TestsDataProvider) {
6060
"state.json",
6161
);
6262

63-
function warningWasShown(path: string): boolean {
63+
function readJSON(path: string) {
6464
try {
6565
const file = nova.fs.open(path) as FileTextMode;
66-
const data = JSON.parse(file.readlines().join("\n"));
66+
const content = JSON.parse(file.readlines().join("\n"));
6767
file.close();
68-
return data.warningWasShown;
68+
return content;
69+
} catch {
70+
return "";
71+
}
72+
}
73+
74+
function warningWasShown(path: string): boolean {
75+
let content = readJSON(path);
76+
let file;
77+
try {
78+
file = nova.fs.open(path, "w") as FileTextMode;
6979
} catch {
70-
// I hope it's OK to create so many `File` objects.
7180
try {
7281
nova.fs.mkdir(nova.extension.workspaceStoragePath);
7382
} catch (e) {
@@ -76,12 +85,16 @@ export function registerRunAll(testsDataProvider: TestsDataProvider) {
7685
{ cause: e },
7786
);
7887
}
79-
nova.fs.open(path, "x").close();
80-
const file = nova.fs.open(path, "w");
88+
file = nova.fs.open(path, "w") as FileTextMode;
89+
}
90+
91+
if (!content.length) {
8192
file.write(JSON.stringify({ warningWasShown: false }));
82-
file.close();
83-
return warningWasShown(path);
93+
content = readJSON(path);
8494
}
95+
96+
const { warningWasShown } = content;
97+
return !!warningWasShown;
8598
}
8699

87100
if (!warningWasShown(hiddenWorkspaceDataPath)) {
@@ -101,12 +114,8 @@ export function registerRunAll(testsDataProvider: TestsDataProvider) {
101114
return;
102115
}
103116

104-
const oldFile = nova.fs.open(hiddenWorkspaceDataPath) as FileTextMode;
105-
const data = JSON.parse(oldFile.readlines().join("\n"));
106-
oldFile.close();
107-
nova.fs.remove(hiddenWorkspaceDataPath);
108-
nova.fs.open(hiddenWorkspaceDataPath, "x").close();
109-
const file = nova.fs.open(hiddenWorkspaceDataPath, "w");
117+
const file = nova.fs.open(hiddenWorkspaceDataPath, "rw") as FileTextMode;
118+
const data = JSON.parse(file.readlines().join("\n"));
110119
data.warningWasShown = true;
111120
file.write(JSON.stringify(data));
112121
file.close();

0 commit comments

Comments
 (0)