-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathfs.ts
More file actions
513 lines (469 loc) · 13.9 KB
/
fs.ts
File metadata and controls
513 lines (469 loc) · 13.9 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
/**
* (c) 2021-2022, Micro:bit Educational Foundation and contributors
*
* SPDX-License-Identifier: MIT
*/
import {
getIntelHexAppendedScript,
MicropythonFsHex,
} from "@microbit/microbit-fs";
import { fromByteArray, toByteArray } from "base64-js";
import EventEmitter from "events";
import sortBy from "lodash.sortby";
import { lineNumFromUint8Array } from "../common/text-util";
import { BoardId } from "../device/board-id";
import { FlashDataSource, HexGenerationError } from "../device/device";
import { Logging } from "../logging/logging";
import { MicroPythonSource } from "../micropython/micropython";
import { asciiToBytes, extractModuleData, generateId } from "./fs-util";
import { Host } from "./host";
import { PythonProject } from "./initial-project";
import { FSStorage } from "./storage";
const commonFsSize = 20 * 1024;
export interface FileVersion {
name: string;
version: number;
}
export interface VersionedData {
version: number;
data: Uint8Array;
}
export enum VersionAction {
/**
* Don't bump the version number.
*/
MAINTAIN,
/**
* Increment the version number.
*/
INCREMENT,
}
export interface Statistics {
/**
* The number of lines in main.py.
*
* Undefined when it is unchanged from the default program.
*/
lines: number | undefined;
/**
* File count.
*/
files: number;
/**
* HEX storage used.
*/
storageUsed: number;
/**
* Number of files tagged with "# microbit-module:".
*/
magicModules: number;
}
/**
* All size-related stats will be -1 until the file system
* has fully initialized.
*/
export interface Project {
/**
* An ID for the project.
*/
id: string;
/**
* A user-defined name for the project.
* Undefined if not set by the user.
*/
name: string | undefined;
/**
* The files in the project.
*/
files: FileVersion[];
}
interface FileChange {
name: string;
type: "create" | "delete" | "edit";
}
const byName = (files: FileVersion[]): Record<string, FileVersion> => {
const result = Object.create(null);
files.forEach((f) => {
result[f.name] = f;
});
return result;
};
export const diff = (before: Project, after: Project): FileChange[] => {
const result: FileChange[] = [];
const beforeFiles = byName(before.files);
const afterFiles = byName(after.files);
for (const beforeVersion of before.files) {
const afterVersion = afterFiles[beforeVersion.name];
if (beforeVersion && !afterVersion) {
result.push({
name: beforeVersion.name,
type: "delete",
});
} else if (
beforeVersion &&
afterVersion &&
beforeVersion.version !== afterVersion.version
) {
result.push({
name: afterVersion.name,
type: "edit",
});
}
}
for (const afterVersion of after.files) {
const beforeVersion = beforeFiles[afterVersion.name];
if (afterVersion && !beforeVersion) {
result.push({
name: afterVersion.name,
type: "create",
});
}
}
return result;
};
export const EVENT_PROJECT_UPDATED = "project_updated";
export const EVENT_TEXT_EDIT = "file_text_updated";
export const MAIN_FILE = "main.py";
export const isNameLengthValid = (filename: string): boolean =>
// This length is enforced by the underlying FS so we check it in the UI ahead of time.
new TextEncoder().encode(filename).length <= 120;
/**
* The MicroPython file system adapted for convienient use from the UI.
*
* For now we store contents backed by session storage so they're only
* persistent over a browser refresh or Chrome tab restore.
*
* We version files in a way that's designed to make UI updates simple.
* If a UI action updates a file (e.g. load from disk) then we bump its version.
* If the file is simply edited in the tool then we do not change its version
* or fire any events. This plays well with uncontrolled embeddings of
* third-party text editors.
*/
export class FileSystem extends EventEmitter implements FlashDataSource {
private initializing: Promise<void> | undefined;
private storage: FSStorage;
private fileVersions: Map<string, number> = new Map();
private fs: undefined | MicropythonFsHex;
private _dirty: boolean = false;
project: Project;
constructor(
private logging: Logging,
private host: Host,
private microPythonSource: MicroPythonSource
) {
super();
this.storage = host.createStorage(logging);
this.project = {
files: [],
id: generateId(),
name: undefined,
};
}
/**
* Determines if the file system has changed since the last hex load.
*
* Changes are edits to existing files (not version updates) and
* changes to the project name.
*/
get dirty() {
return this._dirty;
}
/**
* Run an initialization asynchronously.
*
* If it fails, we'll handle the error and attempt reinitialization on demand.
*/
async initializeInBackground() {
// It's been observed that this can be slow after the fetch on low-end devices,
// so it might be good to move the FS work to a worker if we can't make it fast.
this.initialize().catch((e) => {
this.initializing = undefined;
});
}
/**
* We remember this so we can tell whether the user has edited
* the project since for stats generation.
*/
private cachedInitialProject: PythonProject | undefined;
async initialize(): Promise<MicropythonFsHex> {
if (this.fs) {
return this.fs;
}
if (!this.initializing) {
this.initializing = (async () => {
this._dirty = await this.storage.isDirty();
if (await this.host.shouldReinitializeProject(this.storage)) {
// Do this ASAP to unblock the editor.
this.cachedInitialProject = await this.host.createInitialProject();
if (this.cachedInitialProject.projectName) {
await this.setProjectName(this.cachedInitialProject.projectName);
}
for (const key in this.cachedInitialProject.files) {
const content = toByteArray(this.cachedInitialProject.files[key]);
await this.write(key, content, VersionAction.INCREMENT);
}
this.host.notifyReady(this);
} else {
await this.notify();
}
const fs = await this.createInternalFileSystem();
await this.initializeFsFromStorage(fs);
this.fs = fs;
this.initializing = undefined;
this.logging.log("Initialized file system");
await this.notify();
})();
}
await this.initializing;
return this.fs!;
}
/**
* Update the project name.
*
* @param projectName New project name.
*/
async setProjectName(projectName: string) {
await this.storage.setProjectName(projectName);
await this.markDirty();
return this.notify();
}
private async markDirty(): Promise<void> {
this._dirty = true;
return this.storage.markDirty();
}
/**
* Read data from a file.
*
* @param filename The filename.
* @returns The data. See class comment for detail on the versioning.
* @throws If the file does not exist.
*/
async read(filename: string): Promise<VersionedData> {
return {
data: await this.storage.read(filename),
version: this.fileVersion(filename),
};
}
/**
* Check if a file exists.
*
* @param filename The filename.
* @returns The promise of existence.
*/
async exists(filename: string): Promise<boolean> {
return this.storage.exists(filename);
}
/**
* Writes the file to storage.
*
* Editors perform in-place writes that maintain the file version.
* Other UI actions increment the file version so that editors can be updated as required.
*
* @param filename The file to write to.
* @param content The file content. Text will be serialized as UTF-8.
* @param versionAction The file version update required.
*/
async write(
filename: string,
content: Uint8Array | string,
versionAction: VersionAction
) {
if (typeof content === "string") {
content = new TextEncoder().encode(content);
}
await this.storage.write(filename, content);
if (this.fs) {
this.fs.write(filename, content);
}
if (versionAction === VersionAction.INCREMENT) {
this.incrementFileVersion(filename);
return this.notify();
} else {
this.emit(EVENT_TEXT_EDIT);
// Nothing can have changed, don't needlessly change the identity of our file objects.
return this.markDirty();
}
}
private fileVersion(filename: string): number {
const version = this.fileVersions.get(filename);
if (version === undefined) {
this.incrementFileVersion(filename);
return this.fileVersion(filename);
}
return version;
}
private incrementFileVersion(filename: string): void {
const current = this.fileVersions.get(filename);
this.fileVersions.set(filename, current === undefined ? 1 : current + 1);
}
async getPythonProject(): Promise<PythonProject> {
const projectName = await this.storage.projectName();
const project: PythonProject = {
files: {},
projectName,
};
for (const file of await this.storage.ls()) {
const data = await this.storage.read(file);
const contentAsBase64 = fromByteArray(data);
project.files[file] = contentAsBase64;
}
return project;
}
async replaceWithMultipleFiles(project: PythonProject): Promise<void> {
const fs = await this.initialize();
fs.ls().forEach((f) => fs.remove(f));
for (const key in project.files) {
const content = toByteArray(project.files[key]);
fs.write(key, content);
}
await this.replaceCommon(project.projectName);
}
async replaceWithHexContents(
projectName: string,
hex: string
): Promise<void> {
const fs = await this.initialize();
try {
fs.importFilesFromHex(hex, {
overwrite: true,
formatFirst: true,
});
} catch (e) {
const code = getIntelHexAppendedScript(hex);
if (!code) {
throw new Error("No appended code found in the hex file");
}
fs.ls().forEach((f) => fs.remove(f));
fs.write(MAIN_FILE, code);
}
await this.replaceCommon(projectName);
}
async replaceCommon(projectName?: string): Promise<void> {
this.project = {
...this.project,
id: generateId(),
};
await this.storage.setProjectName(projectName);
await this.overwriteStorageWithFs();
await this.clearDirty();
return this.notify();
}
async remove(filename: string): Promise<void> {
await this.storage.remove(filename);
if (this.fs) {
this.fs.remove(filename);
}
return this.notify();
}
async statistics(): Promise<Statistics> {
const fs = await this.initialize();
const currentMainFile = fs.readBytes(MAIN_FILE);
const files = fs.ls();
let numMagicModules = 0;
for (const file of files) {
const text = fs.read(file);
if (extractModuleData(text)) {
numMagicModules++;
}
}
return {
files: files.length,
storageUsed: fs.getStorageUsed(),
lines:
this.cachedInitialProject &&
this.cachedInitialProject.files[MAIN_FILE] ===
fromByteArray(currentMainFile)
? undefined
: lineNumFromUint8Array(currentMainFile),
magicModules: numMagicModules,
};
}
private async notify() {
const fileNames = await this.storage.ls();
const projectFiles = fileNames.map((name) => ({
name,
version: this.fileVersion(name),
}));
const filesSorted = sortBy(
projectFiles,
(f) => f.name !== MAIN_FILE,
(f) => f.name
);
this.project = {
...this.project,
name: await this.storage.projectName(),
files: filesSorted,
};
this.emit(EVENT_PROJECT_UPDATED, this.project);
}
async toHexForSave(): Promise<string> {
const fs = await this.initialize();
return fs.getUniversalHex();
}
async toHexURI(): Promise<string> {
const fs = await this.initialize();
const universalHex = fs.getUniversalHex();
const b64EncodedHex = btoa(universalHex);
return `microbithex://?data:microbit-${this.project.name}.hex;base64,${b64EncodedHex}`;
}
async clearDirty(): Promise<void> {
this._dirty = false;
return this.storage.clearDirty();
}
async fullFlashData(boardId: BoardId): Promise<Uint8Array> {
try {
const fs = await this.initialize();
return asciiToBytes(fs.getIntelHex(boardId.normalize().id));
} catch (e: any) {
throw new HexGenerationError(e.message);
}
}
async partialFlashData(boardId: BoardId): Promise<Uint8Array> {
try {
const fs = await this.initialize();
return fs.getIntelHexBytes(boardId.normalize().id);
} catch (e: any) {
throw new HexGenerationError(e.message);
}
}
async files(): Promise<Record<string, Uint8Array>> {
const names = await this.storage.ls();
return Object.fromEntries(
await Promise.all(
names.map(async (name) => [name, (await this.read(name)).data])
)
);
}
private assertInitialized(): MicropythonFsHex {
if (!this.fs) {
throw new Error("Must be initialized");
}
return this.fs;
}
private async initializeFsFromStorage(fs: MicropythonFsHex) {
fs.ls().forEach(fs.remove.bind(fs));
for (const file of await this.storage.ls()) {
const data = await this.storage.read(file);
fs.write(file, data);
}
}
private async overwriteStorageWithFs() {
const fs = this.assertInitialized();
const keep = new Set(fs.ls());
await Promise.all(
(await this.storage.ls())
.filter((f) => !keep.has(f))
.map((f) => this.storage.remove(f))
);
for (const filename of Array.from(keep)) {
await this.storage.write(filename, fs.readBytes(filename));
this.incrementFileVersion(filename);
}
}
private createInternalFileSystem = async () => {
const microPython = await this.microPythonSource();
return new MicropythonFsHex(microPython, {
maxFsSize: commonFsSize,
});
};
}