Beautify all src/ files to pass linting with Coffeelint

This commit is contained in:
Glavin Wiechert 2015-06-11 22:57:03 -03:00
parent 6b7b3d6401
commit c1f09e4f8b
15 changed files with 479 additions and 480 deletions

View File

@ -1,10 +1,13 @@
{ {
"indentation" : { "indentation": {
"level" : "error", "level": "error",
"value" : 2 "value": 2
}, },
"line_endings" : { "line_endings": {
"value" : "unix", "value": "unix",
"level" : "error" "level": "error"
},
"max_line_length": {
"value": false
} }
} }

View File

@ -5,7 +5,7 @@ Requires https://github.com/hhatto/autopep8
"use strict" "use strict"
Beautifier = require('./beautifier') Beautifier = require('./beautifier')
module.exports = class autopep8 extends Beautifier module.exports = class Autopep8 extends Beautifier
name: "autopep8" name: "autopep8"
@ -21,5 +21,5 @@ module.exports = class autopep8 extends Beautifier
["--indent-size","#{options.indent_size}"] if options.indent_size? ["--indent-size","#{options.indent_size}"] if options.indent_size?
["--ignore","#{options.ignore.join(',')}"] if options.ignore? ["--ignore","#{options.ignore.join(',')}"] if options.ignore?
], help: { ], help: {
link: "https://github.com/hhatto/autopep8" link: "https://github.com/hhatto/autopep8"
}) })

View File

@ -21,27 +21,27 @@ module.exports = class Beautifier
### ###
Supported Options Supported Options
Enable options for supported languages. Enable options for supported languages.
- <string:language>:<boolean:all_options_enabled> - <string:language>:<boolean:all_options_enabled>
- <string:language>:<string:option_key>:<boolean:enabled> - <string:language>:<string:option_key>:<boolean:enabled>
- <string:language>:<string:option_key>:<string:rename> - <string:language>:<string:option_key>:<string:rename>
- <string:language>:<string:option_key>:<function:transform> - <string:language>:<string:option_key>:<function:transform>
- <string:language>:<string:option_key>:<array:mapper> - <string:language>:<string:option_key>:<array:mapper>
### ###
options: {} options: {}
### ###
Supported languages by this Beautifier Supported languages by this Beautifier
Extracted from the keys of the `options` field. Extracted from the keys of the `options` field.
### ###
languages: null languages: null
### ###
Beautify text Beautify text
Override this method in subclasses Override this method in subclasses
### ###
beautify: null beautify: null
@ -61,9 +61,9 @@ module.exports = class Beautifier
temp.open(name, (err, info) => temp.open(name, (err, info) =>
@debug('tempFile', name, err, info) @debug('tempFile', name, err, info)
return reject(err) if err return reject(err) if err
fs.write(info.fd, contents, (err) => fs.write(info.fd, contents, (err) ->
return reject(err) if err return reject(err) if err
fs.close(info.fd, (err) => fs.close(info.fd, (err) ->
return reject(err) if err return reject(err) if err
resolve(info.path) resolve(info.path)
) )
@ -88,7 +88,7 @@ module.exports = class Beautifier
### ###
Get Shell Environment variables Get Shell Environment variables
Special thank you to @ioquatix Special thank you to @ioquatix
See https://github.com/ioquatix/script-runner/blob/v1.5.0/lib/script-runner.coffee#L45-L63 See https://github.com/ioquatix/script-runner/blob/v1.5.0/lib/script-runner.coffee#L45-L63
### ###
@ -140,7 +140,7 @@ module.exports = class Beautifier
### ###
Like the unix which utility. Like the unix which utility.
Finds the first instance of a specified executable in the PATH environment variable. Finds the first instance of a specified executable in the PATH environment variable.
Does not cache the results, Does not cache the results,
so hash -r is not needed when the PATH changes. so hash -r is not needed when the PATH changes.
@ -161,7 +161,7 @@ module.exports = class Beautifier
### ###
Add help to error.description Add help to error.description
Note: error.description is not officially used in JavaScript, Note: error.description is not officially used in JavaScript,
however it is used internally for Atom Beautify when displaying errors. however it is used internally for Atom Beautify when displaying errors.
### ###

View File

@ -5,7 +5,7 @@ Requires http://golang.org/cmd/gofmt/
"use strict" "use strict"
Beautifier = require('./beautifier') Beautifier = require('./beautifier')
module.exports = class gofmt extends Beautifier module.exports = class Gofmt extends Beautifier
name: "gofmt" name: "gofmt"
options: { options: {

View File

@ -29,7 +29,7 @@ Register all supported beautifiers
module.exports = class Beautifiers extends EventEmitter module.exports = class Beautifiers extends EventEmitter
### ###
List of beautifier names List of beautifier names
To register a beautifier add its name here To register a beautifier add its name here
### ###
beautifierNames : [ beautifierNames : [
@ -55,14 +55,14 @@ module.exports = class Beautifiers extends EventEmitter
### ###
List of loaded beautifiers List of loaded beautifiers
Autogenerated in `constructor` from `beautifierNames` Autogenerated in `constructor` from `beautifierNames`
### ###
beautifiers : null beautifiers : null
### ###
All beautifier options All beautifier options
Autogenerated in `constructor` Autogenerated in `constructor`
### ###
options : null options : null
@ -527,12 +527,12 @@ module.exports = class Beautifiers extends EventEmitter
Searches for a file with a specified name starting with Searches for a file with a specified name starting with
'dir' and going all the way up either until it finds the file 'dir' and going all the way up either until it finds the file
or hits the root. or hits the root.
@param {string} name filename to search for (e.g. .jshintrc) @param {string} name filename to search for (e.g. .jshintrc)
@param {string} dir directory to start search from (default: @param {string} dir directory to start search from (default:
current working directory) current working directory)
@param {boolean} upwards should recurse upwards on failure? (default: true) @param {boolean} upwards should recurse upwards on failure? (default: true)
@returns {string} normalized filename @returns {string} normalized filename
### ###
findFile : (name, dir, upwards = true) -> findFile : (name, dir, upwards = true) ->
@ -557,11 +557,11 @@ module.exports = class Beautifiers extends EventEmitter
Tries to find a configuration file in either project directory Tries to find a configuration file in either project directory
or in the home directory. Configuration files are named or in the home directory. Configuration files are named
'.jsbeautifyrc'. '.jsbeautifyrc'.
@param {string} config name of the configuration file @param {string} config name of the configuration file
@param {string} file path to the file to be linted @param {string} file path to the file to be linted
@param {boolean} upwards should recurse upwards on failure? (default: true) @param {boolean} upwards should recurse upwards on failure? (default: true)
@returns {string} a path to the config file @returns {string} a path to the config file
### ###
findConfig : (config, file, upwards = true) -> findConfig : (config, file, upwards = true) ->
@ -673,7 +673,7 @@ module.exports = class Beautifiers extends EventEmitter
# http://editorconfig.org/ # http://editorconfig.org/
editorconfig ?= require('editorconfig') editorconfig ?= require('editorconfig')
editorConfigOptions = editorconfig.parse(editedFilePath) editorConfigOptions = editorconfig.parse(editedFilePath)
.then((editorConfigOptions) => .then((editorConfigOptions) ->
logger.verbose('editorConfigOptions', editorConfigOptions) logger.verbose('editorConfigOptions', editorConfigOptions)
@ -788,9 +788,9 @@ module.exports = class Beautifiers extends EventEmitter
# where `selection` could be `html`, `js`, 'css', etc # where `selection` could be `html`, `js`, 'css', etc
for selection in selections for selection in selections
# Merge current options on top of fallback options # Merge current options on top of fallback options
logger.verbose('options', selection, currOptions[selection]); logger.verbose('options', selection, currOptions[selection])
_.merge collectedConfig, currOptions[selection] _.merge collectedConfig, currOptions[selection]
logger.verbose('options', selection, collectedConfig); logger.verbose('options', selection, collectedConfig)
extend result, collectedConfig extend result, collectedConfig
, {}) , {})

View File

@ -26,5 +26,5 @@ module.exports = class PerlTidy extends Beautifier
"--profile=#{options.perltidy_profile}" if options.perltidy_profile? "--profile=#{options.perltidy_profile}" if options.perltidy_profile?
@tempFile("input", text) @tempFile("input", text)
], help: { ], help: {
link: "http://perltidy.sourceforge.net/" link: "http://perltidy.sourceforge.net/"
}) })

View File

@ -20,5 +20,5 @@ module.exports = class RubyBeautify extends Beautifier
"--indent_count", options.indent_count "--indent_count", options.indent_count
@tempFile("input", text) @tempFile("input", text)
], help: { ], help: {
link: "https://github.com/erniebrodeur/ruby-beautify" link: "https://github.com/erniebrodeur/ruby-beautify"
}) })

View File

@ -5,7 +5,7 @@ Requires https://github.com/nrc/rustfmt
"use strict" "use strict"
Beautifier = require('./beautifier') Beautifier = require('./beautifier')
module.exports = class rustfmt extends Beautifier module.exports = class Rustfmt extends Beautifier
name: "rustfmt" name: "rustfmt"
@ -18,9 +18,9 @@ module.exports = class rustfmt extends Beautifier
@run(program, [ @run(program, [
tmpFile = @tempFile("tmp", text) tmpFile = @tempFile("tmp", text)
], help: { ], help: {
link: "https://github.com/nrc/rustfmt" link: "https://github.com/nrc/rustfmt"
program: "rustfmt" program: "rustfmt"
pathOption: "Rust - Rustfmt Path" pathOption: "Rust - Rustfmt Path"
}) })
.then(=> .then(=>
@readFile(tmpFile) @readFile(tmpFile)

View File

@ -5,7 +5,7 @@ Requires https://github.com/andialbrecht/sqlparse
"use strict" "use strict"
Beautifier = require('./beautifier') Beautifier = require('./beautifier')
module.exports = class sqlformat extends Beautifier module.exports = class Sqlformat extends Beautifier
name: "sqlformat" name: "sqlformat"
options: { options: {
@ -20,5 +20,5 @@ module.exports = class sqlformat extends Beautifier
"--keywords=#{options.keywords}" if options.keywords? "--keywords=#{options.keywords}" if options.keywords?
"--identifiers=#{options.identifiers}" if options.identifiers? "--identifiers=#{options.identifiers}" if options.identifiers?
], help: { ], help: {
link: "https://github.com/andialbrecht/sqlparse" link: "https://github.com/andialbrecht/sqlparse"
}) })

View File

@ -23,7 +23,7 @@ module.exports = class Uncrustify extends Beautifier
beautify: (text, language, options) -> beautify: (text, language, options) ->
# console.log('uncrustify.beautify', language, options) # console.log('uncrustify.beautify', language, options)
return new @Promise((resolve, reject) => return new @Promise((resolve, reject) ->
configPath = options.configPath configPath = options.configPath
unless configPath unless configPath
# No custom config path # No custom config path
@ -76,7 +76,7 @@ module.exports = class Uncrustify extends Beautifier
"-l" "-l"
lang lang
], help: { ], help: {
link: "http://sourceforge.net/projects/uncrustify/" link: "http://sourceforge.net/projects/uncrustify/"
}) })
.then(=> .then(=>
@readFile(outputFile) @readFile(outputFile)

View File

@ -27,417 +27,413 @@ $ = null
# return data; # return data;
# } # }
getCursors = (editor) -> getCursors = (editor) ->
cursors = editor.getCursors() cursors = editor.getCursors()
posArray = [] posArray = []
for cursor in cursors for cursor in cursors
bufferPosition = cursor.getBufferPosition() bufferPosition = cursor.getBufferPosition()
posArray.push [ posArray.push [
bufferPosition.row bufferPosition.row
bufferPosition.column bufferPosition.column
] ]
posArray posArray
setCursors = (editor, posArray) -> setCursors = (editor, posArray) ->
# console.log "setCursors: # console.log "setCursors:
for bufferPosition, i in posArray for bufferPosition, i in posArray
if i is 0 if i is 0
editor.setCursorBufferPosition bufferPosition editor.setCursorBufferPosition bufferPosition
continue continue
editor.addCursorAtBufferPosition bufferPosition editor.addCursorAtBufferPosition bufferPosition
return return
# Show beautification progress/loading view # Show beautification progress/loading view
beautifier.on('beautify::start', -> beautifier.on('beautify::start', ->
LoadingView ?= require "./views/loading-view" LoadingView ?= require "./views/loading-view"
loadingView ?= new LoadingView() loadingView ?= new LoadingView()
loadingView.show() loadingView.show()
) )
beautifier.on('beautify::end', -> beautifier.on('beautify::end', ->
loadingView?.hide() loadingView?.hide()
) )
# Show error # Show error
showError = (error) => showError = (error) ->
if not atom.config.get("atom-beautify.muteAllErrors") if not atom.config.get("atom-beautify.muteAllErrors")
# console.log(e)
# console.log(e) stack = error.stack
stack = error.stack detail = error.description or error.message
detail = error.description or error.message atom.notifications?.addError(error.message, {
atom.notifications?.addError(error.message, { stack, detail, dismissable : true})
stack, detail, dismissable : true})
beautify = ({onSave}) -> beautify = ({onSave}) ->
# Deprecation warning for beautify on save # Deprecation warning for beautify on save
if atom.config.get("atom-beautify.beautifyOnSave") is true if atom.config.get("atom-beautify.beautifyOnSave") is true
detail = """See issue https://github.com/Glavin001/atom-beautify/issues/308 detail = """See issue https://github.com/Glavin001/atom-beautify/issues/308
To stop seeing this message: To stop seeing this message:
- Uncheck (disable) the deprecated \"Beautify On Save\" option - Uncheck (disable) the deprecated \"Beautify On Save\" option
To enable Beautify on Save for a particular language: To enable Beautify on Save for a particular language:
- Go to Atom Beautify's package settings - Go to Atom Beautify's package settings
- Find option for \"Language Config - <Your Language> - Beautify On Save\" - Find option for \"Language Config - <Your Language> - Beautify On Save\"
- Check (enable) Beautify On Save option for that particular language - Check (enable) Beautify On Save option for that particular language
""" """
atom?.notifications.addWarning("The option \"atom-beautify.beautifyOnSave\" has been deprecated", {detail, dismissable : true}) atom?.notifications.addWarning("The option \"atom-beautify.beautifyOnSave\" has been deprecated", {detail, dismissable : true})
# Continue beautifying # Continue beautifying
path ?= require("path") path ?= require("path")
forceEntireFile = onSave and atom.config.get("atom-beautify.beautifyEntireFileOnSave") forceEntireFile = onSave and atom.config.get("atom-beautify.beautifyEntireFileOnSave")
# Get the path to the config file # Get the path to the config file
# All of the options # All of the options
# Listed in order from default (base) to the one with the highest priority # Listed in order from default (base) to the one with the highest priority
# Left = Default, Right = Will override the left. # Left = Default, Right = Will override the left.
# Atom Editor # Atom Editor
# #
# User's Home path # User's Home path
# Project path # Project path
# Asynchronously and callback-style # Asynchronously and callback-style
beautifyCompleted = (text)=> beautifyCompleted = (text) ->
# console.log 'beautifyCompleted' if not text?
if not text? # Do nothing, is undefined
# console.log 'beautifyCompleted'
else if text instanceof Error
showError(text)
else if typeof text is "string"
if oldText isnt text
# console.log "Replacing current editor's text with new text"
posArray = getCursors(editor)
# Do nothing, is undefined # console.log "posArray:
else if text instanceof Error origScrollTop = editor.getScrollTop()
showError(text)
else if typeof text is "string"
if oldText isnt text
# console.log "Replacing current editor's text with new text" # console.log "origScrollTop:
posArray = getCursors(editor) if not forceEntireFile and isSelection
selectedBufferRange = editor.getSelectedBufferRange()
# console.log "selectedBufferRange:
# console.log "posArray: editor.setTextInBufferRange selectedBufferRange, text
origScrollTop = editor.getScrollTop()
# console.log "origScrollTop:
if not forceEntireFile and isSelection
selectedBufferRange = editor.getSelectedBufferRange()
# console.log "selectedBufferRange:
editor.setTextInBufferRange selectedBufferRange, text
else
# console.log "setText"
editor.setText text
# console.log "setCursors"
setCursors editor, posArray
# console.log "Done setCursors"
# Let the scrollTop setting run after all the save related stuff is run,
# otherwise setScrollTop is not working, probably because the cursor
# addition happens asynchronously
setTimeout ( ->
# console.log "setScrollTop"
editor.setScrollTop origScrollTop
return
), 0
else else
showError( new Error("Unsupported beautification result '#{text}'."))
# else # console.log "setText"
# console.log "Already Beautiful!" editor.setText text
return
# console.log 'Beautify time!' # console.log "setCursors"
# setCursors editor, posArray
# Get current editor
editor = atom.workspace.getActiveTextEditor()
# console.log "Done setCursors"
# Let the scrollTop setting run after all the save related stuff is run,
# otherwise setScrollTop is not working, probably because the cursor
# addition happens asynchronously
setTimeout ( ->
# Check if there is an active editor # console.log "setScrollTop"
if not editor? editor.setScrollTop origScrollTop
return showError( new Error("Active Editor not found. " return
"Please select a Text Editor first to beautify.")) ), 0
isSelection = !!editor.getSelectedText()
# Get editor path and configurations for paths
editedFilePath = editor.getPath()
# Get all options
allOptions = beautifier.getOptionsForPath(editedFilePath, editor)
# Get current editor's text
text = undefined
if not forceEntireFile and isSelection
text = editor.getSelectedText()
else else
text = editor.getText() showError( new Error("Unsupported beautification result '#{text}'."))
oldText = text
# else
# Get Grammar # console.log "Already Beautiful!"
grammarName = editor.getGrammar().name
# Finally, beautify!
try
beautifier.beautify(text, allOptions, grammarName, editedFilePath, onSave : onSave)
.then(beautifyCompleted)
.catch(beautifyCompleted)
catch e
showError(e)
return return
# console.log 'Beautify time!'
#
# Get current editor
editor = atom.workspace.getActiveTextEditor()
# Check if there is an active editor
if not editor?
return showError( new Error("Active Editor not found. "
"Please select a Text Editor first to beautify."))
isSelection = !!editor.getSelectedText()
# Get editor path and configurations for paths
editedFilePath = editor.getPath()
# Get all options
allOptions = beautifier.getOptionsForPath(editedFilePath, editor)
# Get current editor's text
text = undefined
if not forceEntireFile and isSelection
text = editor.getSelectedText()
else
text = editor.getText()
oldText = text
# Get Grammar
grammarName = editor.getGrammar().name
# Finally, beautify!
try
beautifier.beautify(text, allOptions, grammarName, editedFilePath, onSave : onSave)
.then(beautifyCompleted)
.catch(beautifyCompleted)
catch e
showError(e)
return
beautifyFilePath = (filePath, callback) -> beautifyFilePath = (filePath, callback) ->
# Show in progress indicate on file's tree-view entry # Show in progress indicate on file's tree-view entry
$ ?= require("atom-space-pen-views").$ $ ?= require("atom-space-pen-views").$
$el = $(".icon-file-text[data-path=\"#{filePath}\"]")
$el.addClass('beautifying')
# Cleanup and return callback function
cb = (err, result) ->
$el = $(".icon-file-text[data-path=\"#{filePath}\"]") $el = $(".icon-file-text[data-path=\"#{filePath}\"]")
$el.addClass('beautifying') $el.removeClass('beautifying')
return callback(err, result)
# Cleanup and return callback function # Get contents of file
cb = (err, result) -> fs ?= require "fs"
$el = $(".icon-file-text[data-path=\"#{filePath}\"]") fs.readFile(filePath, (err, data) ->
$el.removeClass('beautifying') return cb(err) if err
return callback(err, result) input = data?.toString()
grammar = atom.grammars.selectGrammar(filePath, input)
grammarName = grammar.name
# Get contents of file # Get the options
fs ?= require "fs" allOptions = beautifier.getOptionsForPath(filePath)
fs.readFile(filePath, (err, data) ->
return cb(err) if err
input = data?.toString()
grammar = atom.grammars.selectGrammar(filePath, input)
grammarName = grammar.name
# Get the options # Beautify File
allOptions = beautifier.getOptionsForPath(filePath) completionFun = (output) ->
if output instanceof Error
# Beautify File return cb(output, null ) # output == Error
completionFun = (output) -> else if typeof output is "string"
if output instanceof Error # do not allow empty string
return cb(output, null ) # output == Error return cb(null, output) if output is ''
else if typeof output is "string" # save to file
# do not allow empty string fs.writeFile(filePath, output, (err) ->
return cb(null, output) if output is '' return cb(err) if err
# save to file return cb( null , output)
fs.writeFile(filePath, output, (err) ->
return cb(err) if err
return cb( null , output)
)
else
return cb( new Error("Unknown beautification result #{output}."), output)
try
beautifier.beautify(input, allOptions, grammarName, filePath)
.then(completionFun)
.catch(completionFun)
catch e
return cb(e)
) )
beautifyFile = ({target}) -> else
filePath = target.dataset.path return cb( new Error("Unknown beautification result #{output}."), output)
return unless filePath try
beautifyFilePath(filePath, (err, result) -> beautifier.beautify(input, allOptions, grammarName, filePath)
return showError(err) if err .then(completionFun)
# console.log("Beautify File .catch(completionFun)
catch e
return cb(e)
) )
return
beautifyDirectory = ({target}) ->
dirPath = target.dataset.path
return unless dirPath
return if atom?.confirm( beautifyFile = ({target}) ->
message: "This will beautify all of the files found \ filePath = target.dataset.path
return unless filePath
beautifyFilePath(filePath, (err, result) ->
return showError(err) if err
# console.log("Beautify File
)
return
beautifyDirectory = ({target}) ->
dirPath = target.dataset.path
return unless dirPath
return if atom?.confirm(
message: "This will beautify all of the files found \
recursively in this directory, '#{dirPath}'. \ recursively in this directory, '#{dirPath}'. \
Do you want to continue?", Do you want to continue?",
buttons: ['Yes, continue!','No, cancel!']) isnt 0 buttons: ['Yes, continue!','No, cancel!']) isnt 0
# Show in progress indicate on directory's tree-view entry # Show in progress indicate on directory's tree-view entry
$ ?= require("atom-space-pen-views").$ $ ?= require("atom-space-pen-views").$
$el = $(".icon-file-directory[data-path=\"#{dirPath}\"]") $el = $(".icon-file-directory[data-path=\"#{dirPath}\"]")
$el.addClass('beautifying') $el.addClass('beautifying')
# Process Directory # Process Directory
dir ?= require "node-dir" dir ?= require "node-dir"
async ?= require "async" async ?= require "async"
dir.files(dirPath, (err, files) -> dir.files(dirPath, (err, files) ->
return showError(err) if err return showError(err) if err
async.each(files, (filePath, callback) -> async.each(files, (filePath, callback) ->
# Ignore errors # Ignore errors
beautifyFilePath(filePath, -> callback()) beautifyFilePath(filePath, -> callback())
, (err) -> , (err) ->
$el = $(".icon-file-directory[data-path=\"#{dirPath}\"]") $el = $(".icon-file-directory[data-path=\"#{dirPath}\"]")
$el.removeClass('beautifying') $el.removeClass('beautifying')
# console.log('Completed beautifying directory!', dirPath) # console.log('Completed beautifying directory!', dirPath)
)
) )
return )
return
debug = () -> debug = () ->
# Get current editor # Get current editor
editor = atom.workspace.getActiveTextEditor() editor = atom.workspace.getActiveTextEditor()
# Check if there is an active editor
if not editor?
return confirm("Active Editor not found.\n" +
"Please select a Text Editor first to beautify.")
return unless confirm('Are you ready to debug Atom Beautify?\n\n' +
'Warning: This will change your current clipboard contents.')
debugInfo = ""
addInfo = (key, val) ->
debugInfo += "**#{key}**: #{val}\n\n"
addHeader = (level, title) ->
debugInfo += "#{Array(level+1).join('#')} #{title}\n\n"
addHeader(1, "Atom Beautify - Debugging information")
debugInfo += "The following debugging information was " +
"generated by `Atom Beautify` on `#{new Date()}`." +
"\n\n---\n\n"
# Platform
addInfo('Platform', process.platform)
addHeader(2, "Versions")
# Check if there is an active editor # Atom Version
if not editor? addInfo('Atom Version', atom.appVersion)
return confirm("Active Editor not found.\n" +
"Please select a Text Editor first to beautify.")
return unless confirm('Are you ready to debug Atom Beautify?\n\n' +
'Warning: This will change your current clipboard contents.')
debugInfo = ""
addInfo = (key, val) ->
debugInfo += "**#{key}**: #{val}\n\n"
addHeader = (level, title) ->
debugInfo += "#{Array(level+1).join('#')} #{title}\n\n"
addHeader(1, "Atom Beautify - Debugging information")
debugInfo += "The following debugging information was " +
"generated by `Atom Beautify` on `#{new Date()}`." +
"\n\n---\n\n"
# Platform
addInfo('Platform', process.platform)
addHeader(2, "Versions")
# Atom Version # Atom Beautify Version
addInfo('Atom Version', atom.appVersion) addInfo('Atom Beautify Version', pkg.version)
addHeader(2, "Original file to be beautified")
# Atom Beautify Version # Original file
addInfo('Atom Beautify Version', pkg.version) #
addHeader(2, "Original file to be beautified") # Get editor path and configurations for paths
filePath = editor.getPath()
# Original file # Path
# addInfo('Original File Path', "`#{filePath}`")
# Get editor path and configurations for paths
filePath = editor.getPath()
# Path # Get Grammar
addInfo('Original File Path', "`#{filePath}`") grammarName = editor.getGrammar().name
# Get Grammar # Grammar
grammarName = editor.getGrammar().name addInfo('Original File Grammar', grammarName)
# Grammar # Get current editor's text
addInfo('Original File Grammar', grammarName) text = editor.getText()
# Get current editor's text # Contents
text = editor.getText() codeBlockSyntax = grammarName.toLowerCase().split(' ')[0]
addInfo('Original File Contents', "\n```#{codeBlockSyntax}\n#{text}\n```")
addHeader(2, "Beautification options")
# Contents # Beautification Options
codeBlockSyntax = grammarName.toLowerCase().split(' ')[0] # Get all options
addInfo('Original File Contents', "\n```#{codeBlockSyntax}\n#{text}\n```") allOptions = beautifier.getOptionsForPath(filePath, editor)
addHeader(2, "Beautification options") # Resolve options with promises
Promise.all(allOptions)
.then((allOptions) ->
# Extract options
[
editorOptions
configOptions
homeOptions
editorConfigOptions
] = allOptions
projectOptions = allOptions[4..]
# Show options
# Beautification Options addInfo('Editor Options', "\n" +
# Get all options "Options from Atom Editor settings\n" +
allOptions = beautifier.getOptionsForPath(filePath, editor) "```json\n#{JSON.stringify(editorOptions, undefined, 4)}\n```")
# Resolve options with promises addInfo('Config Options', "\n" +
Promise.all(allOptions) "Options from Atom Beautify package settings\n" +
.then((allOptions) => "```json\n#{JSON.stringify(configOptions, undefined, 4)}\n```")
# Extract options addInfo('Home Options', "\n" +
[ "Options from `#{path.resolve(beautifier.getUserHome(), '.jsbeautifyrc')}`\n" +
editorOptions "```json\n#{JSON.stringify(homeOptions, undefined, 4)}\n```")
configOptions addInfo('EditorConfig Options', "\n" +
homeOptions "Options from [EditorConfig](http://editorconfig.org/) file\n" +
editorConfigOptions "```json\n#{JSON.stringify(editorConfigOptions, undefined, 4)}\n```")
] = allOptions addInfo('Project Options', "\n" +
projectOptions = allOptions[4..] "Options from `.jsbeautifyrc` files starting from directory `#{path.dirname(filePath)}` and going up to root\n" +
"```json\n#{JSON.stringify(projectOptions, undefined, 4)}\n```")
# Show options logs = ""
addInfo('Editor Options', "\n" + subscription = logger.onLogging((msg) ->
"Options from Atom Editor settings\n" + # console.log('logging', msg)
"```json\n#{JSON.stringify(editorOptions, undefined, 4)}\n```") logs += msg
addInfo('Config Options', "\n" +
"Options from Atom Beautify package settings\n" +
"```json\n#{JSON.stringify(configOptions, undefined, 4)}\n```")
addInfo('Home Options', "\n" +
"Options from `#{path.resolve(beautifier.getUserHome(), '.jsbeautifyrc')}`\n" +
"```json\n#{JSON.stringify(homeOptions, undefined, 4)}\n```")
addInfo('EditorConfig Options', "\n" +
"Options from [EditorConfig](http://editorconfig.org/) file\n" +
"```json\n#{JSON.stringify(editorConfigOptions, undefined, 4)}\n```")
addInfo('Project Options', "\n" +
"Options from `.jsbeautifyrc` files starting from directory `#{path.dirname(filePath)}` and going up to root\n" +
"```json\n#{JSON.stringify(projectOptions, undefined, 4)}\n```")
logs = ""
subscription = logger.onLogging((msg) ->
# console.log('logging', msg)
logs += msg
)
cb = (result) ->
subscription.dispose()
addHeader(2, "Results")
# Logs
addInfo('Beautified File Contents', "\n```#{codeBlockSyntax}\n#{result}\n```")
addInfo('Logs', "\n```\n#{logs}\n```")
# Save to clipboard
atom.clipboard.write(debugInfo)
confirm('Atom Beautify debugging information is now in your clipboard.\n' +
'You can now paste this into an Issue you are reporting here\n' +
'https://github.com/Glavin001/atom-beautify/issues/ \n\n' +
'Warning: Be sure to look over the debug info before you send it,
to ensure you are not sharing undesirable private information.'
)
try
beautifier.beautify(text, allOptions, grammarName, filePath)
.then(cb)
.catch(cb)
catch e
return cb(e)
) )
cb = (result) ->
subscription.dispose()
addHeader(2, "Results")
handleSaveEvent = => # Logs
atom.workspace.observeTextEditors (editor) => addInfo('Beautified File Contents', "\n```#{codeBlockSyntax}\n#{result}\n```")
buffer = editor.getBuffer() addInfo('Logs', "\n```\n#{logs}\n```")
disposable = buffer.onDidSave(({path : filePath}) =>
path ?= require('path') # Save to clipboard
# Get Grammar atom.clipboard.write(debugInfo)
grammar = editor.getGrammar().name confirm('Atom Beautify debugging information is now in your clipboard.\n' +
# Get file extension 'You can now paste this into an Issue you are reporting here\n' +
fileExtension = path.extname(filePath) 'https://github.com/Glavin001/atom-beautify/issues/ \n\n' +
# Remove prefix "." (period) in fileExtension 'Warning: Be sure to look over the debug info before you send it,
fileExtension = fileExtension.substr(1) to ensure you are not sharing undesirable private information.'
# Get language )
languages = beautifier.languages.getLanguages({grammar, extension: fileExtension}) try
if languages.length < 1 beautifier.beautify(text, allOptions, grammarName, filePath)
return .then(cb)
# TODO: select appropriate language .catch(cb)
language = languages[0] catch e
# Get language config return cb(e)
key = "atom-beautify.language_#{language.namespace}_beautify_on_save" )
beautifyOnSave = atom.config.get(key)
logger.verbose('save editor positions', key, beautifyOnSave) handleSaveEvent = ->
if beautifyOnSave atom.workspace.observeTextEditors (editor) ->
posArray = getCursors(editor) buffer = editor.getBuffer()
origScrollTop = editor.getScrollTop() disposable = buffer.onDidSave(({path : filePath}) ->
beautifyFilePath(filePath, -> path ?= require('path')
buffer.reload() # Get Grammar
logger.verbose('restore editor positions', posArray,origScrollTop) grammar = editor.getGrammar().name
setCursors(editor, posArray) # Get file extension
editor.setScrollTop(origScrollTop) fileExtension = path.extname(filePath)
) # Remove prefix "." (period) in fileExtension
) fileExtension = fileExtension.substr(1)
plugin.subscribe disposable # Get language
languages = beautifier.languages.getLanguages({grammar, extension: fileExtension})
if languages.length < 1
return
# TODO: select appropriate language
language = languages[0]
# Get language config
key = "atom-beautify.language_#{language.namespace}_beautify_on_save"
beautifyOnSave = atom.config.get(key)
logger.verbose('save editor positions', key, beautifyOnSave)
if beautifyOnSave
posArray = getCursors(editor)
origScrollTop = editor.getScrollTop()
beautifyFilePath(filePath, ->
buffer.reload()
logger.verbose('restore editor positions', posArray,origScrollTop)
setCursors(editor, posArray)
editor.setScrollTop(origScrollTop)
)
)
plugin.subscribe disposable
{Subscriber} = require path.join(atom.packages.resourcePath, 'node_modules', 'emissary') {Subscriber} = require path.join(atom.packages.resourcePath, 'node_modules', 'emissary')
Subscriber.extend plugin Subscriber.extend plugin
plugin.config = _.merge(require('./config.coffee'), defaultLanguageOptions) plugin.config = _.merge(require('./config.coffee'), defaultLanguageOptions)
plugin.activate = -> plugin.activate = ->
handleSaveEvent() handleSaveEvent()
plugin.subscribe atom.config.observe("atom-beautify.beautifyOnSave", handleSaveEvent) plugin.subscribe atom.config.observe("atom-beautify.beautifyOnSave", handleSaveEvent)
atom.commands.add "atom-workspace", "atom-beautify:beautify-editor", beautify atom.commands.add "atom-workspace", "atom-beautify:beautify-editor", beautify
atom.commands.add "atom-workspace", "atom-beautify:help-debug-editor", debug atom.commands.add "atom-workspace", "atom-beautify:help-debug-editor", debug
atom.commands.add ".tree-view .file .name", "atom-beautify:beautify-file", beautifyFile atom.commands.add ".tree-view .file .name", "atom-beautify:beautify-file", beautifyFile
atom.commands.add ".tree-view .directory .name", "atom-beautify:beautify-directory", beautifyDirectory atom.commands.add ".tree-view .directory .name", "atom-beautify:beautify-directory", beautifyDirectory

View File

@ -1,31 +1,31 @@
module.exports = { module.exports = {
analytics : analytics :
type : 'boolean' type : 'boolean'
default : true default : true
description : "There is [Segment.io](https://segment.io/) which forwards data to [Google description : "There is [Segment.io](https://segment.io/) which forwards data to [Google
Analytics](http://www.google.com/analytics/) to track what languages are being Analytics](http://www.google.com/analytics/) to track what languages are being
used the most, as well as other stats. Everything is anonymized and no personal used the most, as well as other stats. Everything is anonymized and no personal
information, such as source code, is sent. information, such as source code, is sent.
See https://github.com/Glavin001/atom-beautify/issues/47 for more details." See https://github.com/Glavin001/atom-beautify/issues/47 for more details."
_analyticsUserId : _analyticsUserId :
type : 'string' type : 'string'
default : "" default : ""
description : "Unique identifier for this user for tracking usage analytics" description : "Unique identifier for this user for tracking usage analytics"
_loggerLevel : _loggerLevel :
type : 'string' type : 'string'
default : 'warn' default : 'warn'
description : 'Set the level for the logger' description : 'Set the level for the logger'
enum : ['verbose', 'debug', 'info', 'warn', 'error'] enum : ['verbose', 'debug', 'info', 'warn', 'error']
beautifyEntireFileOnSave : beautifyEntireFileOnSave :
type : 'boolean' type : 'boolean'
default : true default : true
description : "When beautifying on save, use the entire file, even if there is selected text in the editor" description : "When beautifying on save, use the entire file, even if there is selected text in the editor"
muteUnsupportedLanguageErrors : muteUnsupportedLanguageErrors :
type : 'boolean' type : 'boolean'
default : false default : false
description : "Do not show \"Unsupported Language\" errors when they occur" description : "Do not show \"Unsupported Language\" errors when they occur"
muteAllErrors : muteAllErrors :
type : 'boolean' type : 'boolean'
default : false default : false
description : "Do not show any/all errors when they occur" description : "Do not show any/all errors when they occur"
} }

View File

@ -76,10 +76,10 @@ module.exports = class Languages
Get language for grammar and extension Get language for grammar and extension
### ###
getLanguages: ({name, namespace, grammar, extension}) -> getLanguages: ({name, namespace, grammar, extension}) ->
# console.log('getLanguages', name, namespace, grammar, extension, @languages) # console.log('getLanguages', name, namespace, grammar, extension, @languages)
_.union( _.union(
_.filter(@languages, (language) -> _.isEqual(language.name, name)) _.filter(@languages, (language) -> _.isEqual(language.name, name))
_.filter(@languages, (language) -> _.isEqual(language.namespace, namespace)) _.filter(@languages, (language) -> _.isEqual(language.namespace, namespace))
_.filter(@languages, (language) -> _.contains(language.grammars, grammar)) _.filter(@languages, (language) -> _.contains(language.grammars, grammar))
_.filter(@languages, (language) -> _.contains(language.extensions, extension)) _.filter(@languages, (language) -> _.contains(language.extensions, extension))
) )

View File

@ -2,73 +2,73 @@
Global Logger Global Logger
### ###
module.exports = do -> module.exports = do ->
# Create Event Emitter # Create Event Emitter
{Emitter} = require 'event-kit' {Emitter} = require 'event-kit'
emitter = new Emitter() emitter = new Emitter()
# Create Transport with Writable Stream # Create Transport with Writable Stream
# See http://stackoverflow.com/a/21583831/2578205 # See http://stackoverflow.com/a/21583831/2578205
winston = require('winston') winston = require('winston')
stream = require('stream') stream = require('stream')
writable = new stream.Writable() writable = new stream.Writable()
writable._write = (chunk, encoding, next) -> writable._write = (chunk, encoding, next) ->
msg = chunk.toString() msg = chunk.toString()
# console.log(msg) # console.log(msg)
emitter.emit('logging', msg) emitter.emit('logging', msg)
next() next()
levels = { levels = {
silly: 0, silly: 0,
input: 1, input: 1,
verbose: 2, verbose: 2,
prompt: 3, prompt: 3,
debug: 4, debug: 4,
info: 5, info: 5,
data: 6, data: 6,
help: 7, help: 7,
warn: 8, warn: 8,
error: 9 error: 9
} }
return (label) -> return (label) ->
transport = new (winston.transports.File)({ transport = new (winston.transports.File)({
label: label label: label
level: 'debug' level: 'debug'
timestamp: true timestamp: true
# prettyPrint: true # prettyPrint: true
# colorize: true # colorize: true
stream: writable stream: writable
json: false json: false
}) })
# Initialize logger # Initialize logger
wlogger = new (winston.Logger)({ wlogger = new (winston.Logger)({
# Configure transports # Configure transports
transports: [ transports: [
transport transport
] ]
}) })
wlogger.on('logging', (transport, level, msg, meta)-> wlogger.on('logging', (transport, level, msg, meta)->
loggerLevel = atom?.config.get(\ loggerLevel = atom?.config.get(\
'atom-beautify._loggerLevel') ? "warn" 'atom-beautify._loggerLevel') ? "warn"
# console.log('logging', loggerLevel, arguments) # console.log('logging', loggerLevel, arguments)
loggerLevelNum = levels[loggerLevel] loggerLevelNum = levels[loggerLevel]
levelNum = levels[level] levelNum = levels[level]
if loggerLevelNum <= levelNum if loggerLevelNum <= levelNum
path = require('path') path = require('path')
label = "#{path.dirname(transport.label)\ label = "#{path.dirname(transport.label)\
.split(path.sep).reverse()[0]}\ .split(path.sep).reverse()[0]}\
#{path.sep}#{path.basename(transport.label)}" #{path.sep}#{path.basename(transport.label)}"
console.log("#{label} [#{level}]: #{msg}", meta) console.log("#{label} [#{level}]: #{msg}", meta)
) )
# Export logger methods # Export logger methods
loggerMethods = ['silly','debug','verbose','info','warn','error'] loggerMethods = ['silly','debug','verbose','info','warn','error']
logger = {} logger = {}
for method in loggerMethods for method in loggerMethods
logger[method] = wlogger[method] logger[method] = wlogger[method]
# Add logger listener # Add logger listener
logger.onLogging = (handler) -> logger.onLogging = (handler) ->
# console.log('onLogging', handler) # console.log('onLogging', handler)
subscription = emitter.on('logging', handler) subscription = emitter.on('logging', handler)
# console.log('emitter', emitter.handlersByEventName, subscription) # console.log('emitter', emitter.handlersByEventName, subscription)
return subscription return subscription
# Return simplified logger # Return simplified logger
return logger return logger

View File

@ -59,7 +59,7 @@ class MessageView extends View
destroy: -> destroy: ->
addMessage: (message) => addMessage: (message) =>
@messages.push(message); @messages.push(message)
@refresh() @refresh()
clearMessages: => clearMessages: =>