Skip to content

Commit 71c673d

Browse files
authored
Merge pull request #545 from dhalbert/fix-save-as-corruption
Fix Save As silently corrupting the file on BLE
2 parents e50f39f + 47553c2 commit 71c673d

1 file changed

Lines changed: 15 additions & 1 deletion

File tree

‎js/script.js‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,11 @@ workflows[CONNTYPE.Usb] = new USBWorkflow();
3737
workflows[CONNTYPE.Web] = new WebWorkflow();
3838

3939
let workflow = null;
40+
// Length of the leading run of bytes known to match what is on the device, used
41+
// as the offset for partial writes. It is only meaningful for one particular
42+
// file, so `unchangedPath` records which -- see saveFileContents().
4043
let unchanged = 0;
44+
let unchangedPath = null;
4145
let connectionPromise = null;
4246
let debugMessageAnsi = null;
4347

@@ -600,6 +604,7 @@ function loadEditorContents(content, path = null) {
600604
// can correctly skip a no-op reconfigure.
601605
editorLanguagePath = path;
602606
unchanged = editor.state.doc.length;
607+
unchangedPath = path;
603608
//console.log("doc length", unchanged);
604609
}
605610

@@ -706,7 +711,14 @@ async function saveFileContents(path) {
706711
// If this is a different file, we write everything. The language
707712
// plugin is refreshed by setFilename below (it routes through
708713
// setEditorLanguageForPath), so no extra dispatch is needed here.
709-
if (path !== workflow.currentFilename) {
714+
//
715+
// Compare against unchangedPath, not workflow.currentFilename:
716+
// saveFileAs() assigns currentFilename *before* calling us, so by this
717+
// point the two always match and the reset never fired. `unchanged`
718+
// then still described the previously open file, and Save As did a
719+
// partial write at that file's offset into a brand-new one, leaving
720+
// everything before the offset as whatever the fresh cluster held.
721+
if (path !== unchangedPath) {
710722
unchanged = 0;
711723
}
712724
let doc = editor.state.doc;
@@ -724,7 +736,9 @@ async function saveFileContents(path) {
724736
}
725737
// Optimistically mark the bytes-being-sent as unchanged. If the
726738
// write throws we'll roll back to baseUnchanged for the next try.
739+
// Either way the offset now describes `path`, so record that.
727740
unchanged = docLengthAtStart;
741+
unchangedPath = path;
728742
try {
729743
if (await workflow.writeFile(path, contents, offset)) {
730744
setFilename(workflow.currentFilename);

0 commit comments

Comments
 (0)