Skip to content

Commit eea678c

Browse files
committed
Make the reading and writing of files less ugly
1 parent d3aec98 commit eea678c

File tree

1 file changed

+18
-19
lines changed

1 file changed

+18
-19
lines changed

src/commands/tests.sidebar.ts

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

63-
function warningWasShown(path: string): boolean {
63+
function readState(path: string): Record<string, unknown> {
6464
try {
6565
const file = nova.fs.open(path) as FileTextMode;
66-
const data = JSON.parse(file.readlines().join("\n"));
66+
const content = file.readlines().join("\n");
6767
file.close();
68-
return data.warningWasShown;
68+
69+
return JSON.parse(content);
70+
} catch {
71+
return {};
72+
}
73+
}
74+
function writeState(path: string, content: Record<string, unknown>) {
75+
let file;
76+
try {
77+
file = nova.fs.open(path, "w") as FileTextMode;
6978
} catch {
70-
// I hope it's OK to create so many `File` objects.
7179
try {
7280
nova.fs.mkdir(nova.extension.workspaceStoragePath);
7381
} catch (e) {
@@ -76,15 +84,13 @@ export function registerRunAll(testsDataProvider: TestsDataProvider) {
7684
{ cause: e },
7785
);
7886
}
79-
nova.fs.open(path, "x").close();
80-
const file = nova.fs.open(path, "w");
81-
file.write(JSON.stringify({ warningWasShown: false }));
82-
file.close();
83-
return warningWasShown(path);
87+
file = nova.fs.open(path, "w") as FileTextMode;
8488
}
89+
file.write(JSON.stringify(content));
8590
}
8691

87-
if (!warningWasShown(hiddenWorkspaceDataPath)) {
92+
const state = readState(hiddenWorkspaceDataPath);
93+
if (!state.warningWasShown) {
8894
const permissionsNotificationRequest = new NotificationRequest(
8995
"co.gwil.deno.notifications.findSymbolUnavailable",
9096
);
@@ -101,15 +107,8 @@ export function registerRunAll(testsDataProvider: TestsDataProvider) {
101107
return;
102108
}
103109

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");
110-
data.warningWasShown = true;
111-
file.write(JSON.stringify(data));
112-
file.close();
110+
state.warningWasShown = true;
111+
writeState(hiddenWorkspaceDataPath, state);
113112
}
114113

115114
const timeoutID = setTimeout(() => {

0 commit comments

Comments
 (0)