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" : {
"level" : "error",
"value" : 2
"indentation": {
"level": "error",
"value": 2
},
"line_endings" : {
"value" : "unix",
"level" : "error"
"line_endings": {
"value": "unix",
"level": "error"
},
"max_line_length": {
"value": false
}
}

View File

@ -5,7 +5,7 @@ Requires https://github.com/hhatto/autopep8
"use strict"
Beautifier = require('./beautifier')
module.exports = class autopep8 extends Beautifier
module.exports = class Autopep8 extends Beautifier
name: "autopep8"
@ -21,5 +21,5 @@ module.exports = class autopep8 extends Beautifier
["--indent-size","#{options.indent_size}"] if options.indent_size?
["--ignore","#{options.ignore.join(',')}"] if options.ignore?
], 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
Enable options for supported languages.
- <string:language>:<boolean:all_options_enabled>
- <string:language>:<string:option_key>:<boolean:enabled>
- <string:language>:<string:option_key>:<string:rename>
- <string:language>:<string:option_key>:<function:transform>
- <string:language>:<string:option_key>:<array:mapper>
###
options: {}
###
Supported languages by this Beautifier
Extracted from the keys of the `options` field.
###
languages: null
###
Beautify text
Override this method in subclasses
###
beautify: null
@ -61,9 +61,9 @@ module.exports = class Beautifier
temp.open(name, (err, info) =>
@debug('tempFile', name, err, info)
return reject(err) if err
fs.write(info.fd, contents, (err) =>
fs.write(info.fd, contents, (err) ->
return reject(err) if err
fs.close(info.fd, (err) =>
fs.close(info.fd, (err) ->
return reject(err) if err
resolve(info.path)
)
@ -88,7 +88,7 @@ module.exports = class Beautifier
###
Get Shell Environment variables
Special thank you to @ioquatix
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.
Finds the first instance of a specified executable in the PATH environment variable.
Does not cache the results,
so hash -r is not needed when the PATH changes.
@ -161,7 +161,7 @@ module.exports = class Beautifier
###
Add help to error.description
Note: error.description is not officially used in JavaScript,
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"
Beautifier = require('./beautifier')
module.exports = class gofmt extends Beautifier
module.exports = class Gofmt extends Beautifier
name: "gofmt"
options: {

View File

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

View File

@ -26,5 +26,5 @@ module.exports = class PerlTidy extends Beautifier
"--profile=#{options.perltidy_profile}" if options.perltidy_profile?
@tempFile("input", text)
], 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
@tempFile("input", text)
], 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"
Beautifier = require('./beautifier')
module.exports = class rustfmt extends Beautifier
module.exports = class Rustfmt extends Beautifier
name: "rustfmt"
@ -18,9 +18,9 @@ module.exports = class rustfmt extends Beautifier
@run(program, [
tmpFile = @tempFile("tmp", text)
], help: {
link: "https://github.com/nrc/rustfmt"
program: "rustfmt"
pathOption: "Rust - Rustfmt Path"
link: "https://github.com/nrc/rustfmt"
program: "rustfmt"
pathOption: "Rust - Rustfmt Path"
})
.then(=>
@readFile(tmpFile)

View File

@ -5,7 +5,7 @@ Requires https://github.com/andialbrecht/sqlparse
"use strict"
Beautifier = require('./beautifier')
module.exports = class sqlformat extends Beautifier
module.exports = class Sqlformat extends Beautifier
name: "sqlformat"
options: {
@ -20,5 +20,5 @@ module.exports = class sqlformat extends Beautifier
"--keywords=#{options.keywords}" if options.keywords?
"--identifiers=#{options.identifiers}" if options.identifiers?
], 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) ->
# console.log('uncrustify.beautify', language, options)
return new @Promise((resolve, reject) =>
return new @Promise((resolve, reject) ->
configPath = options.configPath
unless configPath
# No custom config path
@ -76,7 +76,7 @@ module.exports = class Uncrustify extends Beautifier
"-l"
lang
], help: {
link: "http://sourceforge.net/projects/uncrustify/"
link: "http://sourceforge.net/projects/uncrustify/"
})
.then(=>
@readFile(outputFile)

View File

@ -27,417 +27,413 @@ $ = null
# return data;
# }
getCursors = (editor) ->
cursors = editor.getCursors()
posArray = []
for cursor in cursors
bufferPosition = cursor.getBufferPosition()
posArray.push [
bufferPosition.row
bufferPosition.column
]
posArray
cursors = editor.getCursors()
posArray = []
for cursor in cursors
bufferPosition = cursor.getBufferPosition()
posArray.push [
bufferPosition.row
bufferPosition.column
]
posArray
setCursors = (editor, posArray) ->
# console.log "setCursors:
for bufferPosition, i in posArray
if i is 0
editor.setCursorBufferPosition bufferPosition
continue
editor.addCursorAtBufferPosition bufferPosition
return
# console.log "setCursors:
for bufferPosition, i in posArray
if i is 0
editor.setCursorBufferPosition bufferPosition
continue
editor.addCursorAtBufferPosition bufferPosition
return
# Show beautification progress/loading view
beautifier.on('beautify::start', ->
LoadingView ?= require "./views/loading-view"
loadingView ?= new LoadingView()
loadingView.show()
LoadingView ?= require "./views/loading-view"
loadingView ?= new LoadingView()
loadingView.show()
)
beautifier.on('beautify::end', ->
loadingView?.hide()
loadingView?.hide()
)
# Show error
showError = (error) =>
if not atom.config.get("atom-beautify.muteAllErrors")
# console.log(e)
stack = error.stack
detail = error.description or error.message
atom.notifications?.addError(error.message, {
stack, detail, dismissable : true})
showError = (error) ->
if not atom.config.get("atom-beautify.muteAllErrors")
# console.log(e)
stack = error.stack
detail = error.description or error.message
atom.notifications?.addError(error.message, {
stack, detail, dismissable : true})
beautify = ({onSave}) ->
# Deprecation warning for beautify on save
if atom.config.get("atom-beautify.beautifyOnSave") is true
detail = """See issue https://github.com/Glavin001/atom-beautify/issues/308
# Deprecation warning for beautify on save
if atom.config.get("atom-beautify.beautifyOnSave") is true
detail = """See issue https://github.com/Glavin001/atom-beautify/issues/308
To stop seeing this message:
- Uncheck (disable) the deprecated \"Beautify On Save\" option
To stop seeing this message:
- Uncheck (disable) the deprecated \"Beautify On Save\" option
To enable Beautify on Save for a particular language:
- Go to Atom Beautify's package settings
- Find option for \"Language Config - <Your Language> - Beautify On Save\"
- Check (enable) Beautify On Save option for that particular language
To enable Beautify on Save for a particular language:
- Go to Atom Beautify's package settings
- Find option for \"Language Config - <Your Language> - Beautify On Save\"
- 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
path ?= require("path")
forceEntireFile = onSave and atom.config.get("atom-beautify.beautifyEntireFileOnSave")
# Continue beautifying
path ?= require("path")
forceEntireFile = onSave and atom.config.get("atom-beautify.beautifyEntireFileOnSave")
# Get the path to the config file
# All of the options
# Listed in order from default (base) to the one with the highest priority
# Left = Default, Right = Will override the left.
# Atom Editor
#
# User's Home path
# Project path
# Asynchronously and callback-style
beautifyCompleted = (text)=>
# Get the path to the config file
# All of the options
# Listed in order from default (base) to the one with the highest priority
# Left = Default, Right = Will override the left.
# Atom Editor
#
# User's Home path
# Project path
# Asynchronously and callback-style
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
else if text instanceof Error
showError(text)
else if typeof text is "string"
if oldText isnt text
# console.log "posArray:
origScrollTop = editor.getScrollTop()
# console.log "Replacing current editor's text with new text"
posArray = getCursors(editor)
# console.log "origScrollTop:
if not forceEntireFile and isSelection
selectedBufferRange = editor.getSelectedBufferRange()
# console.log "posArray:
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
# console.log "selectedBufferRange:
editor.setTextInBufferRange selectedBufferRange, text
else
showError( new Error("Unsupported beautification result '#{text}'."))
# else
# console.log "Already Beautiful!"
return
# console.log "setText"
editor.setText text
# console.log 'Beautify time!'
#
# Get current editor
editor = atom.workspace.getActiveTextEditor()
# 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 ( ->
# 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()
# console.log "setScrollTop"
editor.setScrollTop origScrollTop
return
), 0
else
text = editor.getText()
oldText = text
showError( new Error("Unsupported beautification result '#{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)
# else
# console.log "Already Beautiful!"
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) ->
# Show in progress indicate on file's tree-view entry
$ ?= require("atom-space-pen-views").$
# Show in progress indicate on file's tree-view entry
$ ?= 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.addClass('beautifying')
$el.removeClass('beautifying')
return callback(err, result)
# Cleanup and return callback function
cb = (err, result) ->
$el = $(".icon-file-text[data-path=\"#{filePath}\"]")
$el.removeClass('beautifying')
return callback(err, result)
# Get contents of file
fs ?= require "fs"
fs.readFile(filePath, (err, data) ->
return cb(err) if err
input = data?.toString()
grammar = atom.grammars.selectGrammar(filePath, input)
grammarName = grammar.name
# Get contents of file
fs ?= require "fs"
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
allOptions = beautifier.getOptionsForPath(filePath)
# Get the options
allOptions = beautifier.getOptionsForPath(filePath)
# Beautify File
completionFun = (output) ->
if output instanceof Error
return cb(output, null ) # output == Error
else if typeof output is "string"
# do not allow empty string
return cb(null, output) if output is ''
# save to file
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)
# Beautify File
completionFun = (output) ->
if output instanceof Error
return cb(output, null ) # output == Error
else if typeof output is "string"
# do not allow empty string
return cb(null, output) if output is ''
# save to file
fs.writeFile(filePath, output, (err) ->
return cb(err) if err
return cb( null , output)
)
beautifyFile = ({target}) ->
filePath = target.dataset.path
return unless filePath
beautifyFilePath(filePath, (err, result) ->
return showError(err) if err
# console.log("Beautify File
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)
)
return
beautifyDirectory = ({target}) ->
dirPath = target.dataset.path
return unless dirPath
return if atom?.confirm(
message: "This will beautify all of the files found \
beautifyFile = ({target}) ->
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}'. \
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
$ ?= require("atom-space-pen-views").$
$el = $(".icon-file-directory[data-path=\"#{dirPath}\"]")
$el.addClass('beautifying')
# Show in progress indicate on directory's tree-view entry
$ ?= require("atom-space-pen-views").$
$el = $(".icon-file-directory[data-path=\"#{dirPath}\"]")
$el.addClass('beautifying')
# Process Directory
dir ?= require "node-dir"
async ?= require "async"
dir.files(dirPath, (err, files) ->
return showError(err) if err
# Process Directory
dir ?= require "node-dir"
async ?= require "async"
dir.files(dirPath, (err, files) ->
return showError(err) if err
async.each(files, (filePath, callback) ->
# Ignore errors
beautifyFilePath(filePath, -> callback())
, (err) ->
$el = $(".icon-file-directory[data-path=\"#{dirPath}\"]")
$el.removeClass('beautifying')
# console.log('Completed beautifying directory!', dirPath)
)
async.each(files, (filePath, callback) ->
# Ignore errors
beautifyFilePath(filePath, -> callback())
, (err) ->
$el = $(".icon-file-directory[data-path=\"#{dirPath}\"]")
$el.removeClass('beautifying')
# console.log('Completed beautifying directory!', dirPath)
)
return
)
return
debug = () ->
# Get current editor
editor = atom.workspace.getActiveTextEditor()
# Get current editor
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
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")
# Atom Version
addInfo('Atom Version', atom.appVersion)
# Atom Version
addInfo('Atom Version', atom.appVersion)
# Atom Beautify Version
addInfo('Atom Beautify Version', pkg.version)
addHeader(2, "Original file to be beautified")
# Atom Beautify Version
addInfo('Atom Beautify Version', pkg.version)
addHeader(2, "Original file to be beautified")
# Original file
#
# Get editor path and configurations for paths
filePath = editor.getPath()
# Original file
#
# Get editor path and configurations for paths
filePath = editor.getPath()
# Path
addInfo('Original File Path', "`#{filePath}`")
# Path
addInfo('Original File Path', "`#{filePath}`")
# Get Grammar
grammarName = editor.getGrammar().name
# Get Grammar
grammarName = editor.getGrammar().name
# Grammar
addInfo('Original File Grammar', grammarName)
# Grammar
addInfo('Original File Grammar', grammarName)
# Get current editor's text
text = editor.getText()
# Get current editor's text
text = editor.getText()
# Contents
codeBlockSyntax = grammarName.toLowerCase().split(' ')[0]
addInfo('Original File Contents', "\n```#{codeBlockSyntax}\n#{text}\n```")
addHeader(2, "Beautification options")
# Contents
codeBlockSyntax = grammarName.toLowerCase().split(' ')[0]
addInfo('Original File Contents', "\n```#{codeBlockSyntax}\n#{text}\n```")
addHeader(2, "Beautification options")
# Beautification Options
# Get all options
allOptions = beautifier.getOptionsForPath(filePath, editor)
# Resolve options with promises
Promise.all(allOptions)
.then((allOptions) ->
# Extract options
[
editorOptions
configOptions
homeOptions
editorConfigOptions
] = allOptions
projectOptions = allOptions[4..]
# Beautification Options
# Get all options
allOptions = beautifier.getOptionsForPath(filePath, editor)
# Resolve options with promises
Promise.all(allOptions)
.then((allOptions) =>
# Extract options
[
editorOptions
configOptions
homeOptions
editorConfigOptions
] = allOptions
projectOptions = allOptions[4..]
# Show options
addInfo('Editor Options', "\n" +
"Options from Atom Editor settings\n" +
"```json\n#{JSON.stringify(editorOptions, undefined, 4)}\n```")
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)
# Show options
addInfo('Editor Options', "\n" +
"Options from Atom Editor settings\n" +
"```json\n#{JSON.stringify(editorOptions, undefined, 4)}\n```")
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")
handleSaveEvent = =>
atom.workspace.observeTextEditors (editor) =>
buffer = editor.getBuffer()
disposable = buffer.onDidSave(({path : filePath}) =>
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)
# 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
# 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)
)
handleSaveEvent = ->
atom.workspace.observeTextEditors (editor) ->
buffer = editor.getBuffer()
disposable = buffer.onDidSave(({path : filePath}) ->
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)
# 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.extend plugin
plugin.config = _.merge(require('./config.coffee'), defaultLanguageOptions)
plugin.activate = ->
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:help-debug-editor", debug
atom.commands.add ".tree-view .file .name", "atom-beautify:beautify-file", beautifyFile
atom.commands.add ".tree-view .directory .name", "atom-beautify:beautify-directory", beautifyDirectory
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:help-debug-editor", debug
atom.commands.add ".tree-view .file .name", "atom-beautify:beautify-file", beautifyFile
atom.commands.add ".tree-view .directory .name", "atom-beautify:beautify-directory", beautifyDirectory

View File

@ -1,31 +1,31 @@
module.exports = {
analytics :
type : 'boolean'
default : true
description : "There is [Segment.io](https://segment.io/) which forwards data to [Google
analytics :
type : 'boolean'
default : true
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
used the most, as well as other stats. Everything is anonymized and no personal
information, such as source code, is sent.
See https://github.com/Glavin001/atom-beautify/issues/47 for more details."
_analyticsUserId :
type : 'string'
default : ""
description : "Unique identifier for this user for tracking usage analytics"
_loggerLevel :
type : 'string'
default : 'warn'
description : 'Set the level for the logger'
enum : ['verbose', 'debug', 'info', 'warn', 'error']
beautifyEntireFileOnSave :
type : 'boolean'
default : true
description : "When beautifying on save, use the entire file, even if there is selected text in the editor"
muteUnsupportedLanguageErrors :
type : 'boolean'
default : false
description : "Do not show \"Unsupported Language\" errors when they occur"
muteAllErrors :
type : 'boolean'
default : false
description : "Do not show any/all errors when they occur"
}
_analyticsUserId :
type : 'string'
default : ""
description : "Unique identifier for this user for tracking usage analytics"
_loggerLevel :
type : 'string'
default : 'warn'
description : 'Set the level for the logger'
enum : ['verbose', 'debug', 'info', 'warn', 'error']
beautifyEntireFileOnSave :
type : 'boolean'
default : true
description : "When beautifying on save, use the entire file, even if there is selected text in the editor"
muteUnsupportedLanguageErrors :
type : 'boolean'
default : false
description : "Do not show \"Unsupported Language\" errors when they occur"
muteAllErrors :
type : 'boolean'
default : false
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
###
getLanguages: ({name, namespace, grammar, extension}) ->
# console.log('getLanguages', name, namespace, grammar, extension, @languages)
_.union(
_.filter(@languages, (language) -> _.isEqual(language.name, name))
_.filter(@languages, (language) -> _.isEqual(language.namespace, namespace))
_.filter(@languages, (language) -> _.contains(language.grammars, grammar))
_.filter(@languages, (language) -> _.contains(language.extensions, extension))
)
# console.log('getLanguages', name, namespace, grammar, extension, @languages)
_.union(
_.filter(@languages, (language) -> _.isEqual(language.name, name))
_.filter(@languages, (language) -> _.isEqual(language.namespace, namespace))
_.filter(@languages, (language) -> _.contains(language.grammars, grammar))
_.filter(@languages, (language) -> _.contains(language.extensions, extension))
)

View File

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

View File

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