From a5c5d339a56dc356e9e86b59df0cf627954e02f4 Mon Sep 17 00:00:00 2001 From: Steven Zeck Date: Tue, 21 Nov 2017 21:08:06 -0600 Subject: [PATCH] Refactor handleSaveEvent to use onWillSave async (#1924) * Update handleSaveEvent to use onWillSave and refactor * Remove old handleSaveEvent function * Specify minimum version of Atom of 1.21.0 --- package.json | 2 +- src/beautify.coffee | 29 +++++++---------------------- 2 files changed, 8 insertions(+), 23 deletions(-) diff --git a/package.json b/package.json index 394f8ce..7ea09f2 100644 --- a/package.json +++ b/package.json @@ -153,7 +153,7 @@ } ], "engines": { - "atom": ">=1.6.0 <2.0.0" + "atom": ">=1.21.0 <2.0.0" }, "dependencies": { "align-yaml": "^0.1.8", diff --git a/src/beautify.coffee b/src/beautify.coffee index 3a850a4..9b9aba9 100644 --- a/src/beautify.coffee +++ b/src/beautify.coffee @@ -506,20 +506,17 @@ debug = () -> handleSaveEvent = -> atom.workspace.observeTextEditors (editor) -> - pendingPaths = {} beautifyOnSaveHandler = ({path: filePath}) -> - logger.verbose('Should beautify on this save?') - if pendingPaths[filePath] - logger.verbose("Editor with file path #{filePath} already beautified!") - return - buffer = editor.getBuffer() path ?= require('path') - # Get Grammar - grammar = editor.getGrammar().name # Get file extension fileExtension = path.extname(filePath) # Remove prefix "." (period) in fileExtension fileExtension = fileExtension.substr(1) + # Set path of buffer for unsaved files + if editor.getPath() is undefined + editor.getBuffer().setPath(filePath) + # Get Grammar from the editor + grammar = editor.getGrammar().name # Get language languages = beautifier.languages.getLanguages({grammar, extension: fileExtension}) if languages.length < 1 @@ -535,23 +532,11 @@ handleSaveEvent = -> beautify({editor, onSave: true}) .then(() -> logger.verbose('Done beautifying file', filePath) - if editor.isAlive() is true - logger.verbose('Saving TextEditor...') - # Store the filePath to prevent infinite looping - # When Whitespace package has option "Ensure Single Trailing Newline" enabled - # It will add a newline and keep the file from converging on a beautified form - # and saving without emitting onDidSave event, because there were no changes. - pendingPaths[filePath] = true - Promise.resolve(editor.save()).then(() -> - delete pendingPaths[filePath] - logger.verbose('Saved TextEditor.') - ) ) .catch((error) -> return showError(error) ) - disposable = editor.onDidSave(({path : filePath}) -> - # TODO: Implement debouncing + disposable = editor.getBuffer().onWillSave(({path: filePath}) -> beautifyOnSaveHandler({path: filePath}) ) plugin.subscriptions.add disposable @@ -632,4 +617,4 @@ plugin.activate = -> @addLanguageCommands() plugin.deactivate = -> - @subscriptions.dispose() + @subscriptions.dispose() \ No newline at end of file