Skip to content

Commit

Permalink
Amended "format" function so that it returns the formatted content an…
Browse files Browse the repository at this point in the history
…d throws when warnings
  • Loading branch information
Anantachai Saothong (Manta) committed Apr 27, 2017
1 parent ba8b689 commit c56d181
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 60 deletions.
63 changes: 30 additions & 33 deletions edge/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,52 +41,49 @@ if (printVersion) {
console.log('v' + require('../package.json').version)

} else if (inputFiles.length === 0) {
throw new Error('No files specified.')
throw new Error('No input files specified.')

} else {
let formattingOptions = null
if (optionFilePath) {
formattingOptions = JSON.parse(fs.readFileSync(optionFilePath, 'utf8'))
if (fs.existsSync(optionFilePath)) {
formattingOptions = JSON.parse(fs.readFileSync(optionFilePath, 'utf8'))
} else {
throw new Error('Option file could not be found.')
}
}

const outputFiles = _.chain(inputFiles)
_.chain(inputFiles)
.map(path => glob.sync(path))
.flatten()
.map(path => Object.assign({ path }, format(fs.readFileSync(path, 'utf8'), formattingOptions)))
.value()
.forEach(path => {
console.log('Processing ', path)

if (outputDirectory) {
if (fs.existsSync(pt.resolve(outputDirectory)) === false) {
fs.mkdirSync(pt.resolve(outputDirectory))
}
outputFiles.forEach(file => {
fs.writeFileSync(pt.resolve(outputDirectory, pt.basename(file.path)), file.text)
})
try {
const inputContent = fs.readFileSync(path, 'utf8')
const outputContent = format(inputContent, formattingOptions)

} else if (replaceOriginal) {
outputFiles.forEach(file => {
fs.writeFileSync(file.path, file.text)
})
if (outputDirectory) {
if (fs.existsSync(pt.resolve(outputDirectory)) === false) {
fs.mkdirSync(pt.resolve(outputDirectory))
}

} else {
outputFiles.forEach(file => {
console.log(file.text)
})
}
fs.writeFileSync(pt.resolve(outputDirectory, pt.basename(path)), outputContent)

} else if (replaceOriginal) {
if (inputContent !== outputContent) {
fs.writeFileSync(path, outputContent)
}

if (outputFiles.some(file => file.warnings.length > 0)) {
outputFiles.forEach(file => {
file.warnings.forEach(warn => {
console.log(`WARN: ${warn.message} in ${file.path}`)
if (warn.data !== undefined) {
console.log(JSON.stringify(warn.data, null, '\t'))
} else {
console.log(outputContent)
}
})

} catch (error) {
console.log(error)
}
})
const warningCount = _.sumBy(outputFiles, file => file.warnings.length)
console.log(`Done with ${warningCount} warning${warningCount === 1 ? '' : 's'}.`)
.value()

} else {
console.log('Done without warnings.')
}
console.log('Done.')
}
27 changes: 8 additions & 19 deletions edge/format.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,7 @@ const createFormattingOptionsFromStylintOptions = require('./createFormattingOpt
function format(content, options) {
// Stop processing if the input content is empty
if (content.trim().length === 0) {
return {
text: '',
tree: null,
warnings: [],
}
return ''
}

// Consolidate the formatting options
Expand All @@ -24,9 +20,6 @@ function format(content, options) {
const openParen = options.insertSpaceInsideParenthesis ? '( ' : '('
const closeParen = options.insertSpaceInsideParenthesis ? ' )' : ')'

// Store warning messages (if any)
const warnings = []

// Store the input content line-by-line
const originalLines = content.split(/\r?\n/)

Expand Down Expand Up @@ -312,7 +305,9 @@ function format(content, options) {
}

} else {
warnings.push({ message: 'Found unknown object', data: inputNode })
const error = new Error('Found unknown object')
error.data = inputNode
throw error
}

if (options.insertSemicolons) {
Expand Down Expand Up @@ -873,7 +868,9 @@ function format(content, options) {
}

} else {
warnings.push({ message: 'Found unknown object', data: inputNode })
const error = new Error('Found unknown object')
error.data = inputNode
throw error
}

// Insert sticky comment(s) on the right of the current node
Expand Down Expand Up @@ -1037,7 +1034,6 @@ function format(content, options) {

const outputText = travel(null, rootNode, 0)
let outputLines = outputText.split(new RegExp(_.escapeRegExp(options.newLineChar)))
let outputNode = rootNode

// Trim a beginning new-line character
if (_.first(outputLines).trim().length === 0) {
Expand All @@ -1050,9 +1046,6 @@ function format(content, options) {
}

if (options.wrapMode) {
// Trim the wrap node as it was a root node
outputNode = rootNode.nodes[0].block

// Remove the wrap node block
if (outputLines[0].startsWith('wrap')) {
outputLines.shift()
Expand Down Expand Up @@ -1085,11 +1078,7 @@ function format(content, options) {
outputLines.push('')
}

return {
tree: outputNode,
text: outputLines.join(options.newLineChar),
warnings,
}
return outputLines.join(options.newLineChar)
}

module.exports = format
22 changes: 14 additions & 8 deletions test/runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@ const ps = require('process')
const fs = require('fs')
const pt = require('path')
const _ = require('lodash')
const Stylus = require('stylus')
const format = require('../edge/format')

const filteredSpecName = _.chain(ps.argv).map((param, index, array) => (param === '--filter' || param === '-f') ? _.trim(array[index + 1], '"') : null).compact().first().value()

const filesAndDirectories = glob.sync('spec/' + (filteredSpecName || '*'))
const filesOnly = path => pt.extname(path) === '.js'
const directoriesOnly = path => pt.extname(path) === ''
const createComparableLines = text => text.replace(/\r/g, '¶').replace(/\t/g, '→').replace(/^\s+/gm, spaces => _.repeat('·', spaces.length)).split('\n')

filesAndDirectories.filter(directoriesOnly).forEach(directory => {
const inputFilePath = pt.join(directory, 'input.styl')
Expand All @@ -44,14 +46,20 @@ filesAndDirectories.filter(directoriesOnly).forEach(directory => {
if (fs.existsSync(actualFilePath)) fs.unlinkSync(actualFilePath)
if (fs.existsSync(debuggingFilePath)) fs.unlinkSync(debuggingFilePath)

const actual = format(inputContent, formattingOptions)
const actualContent = format(inputContent, formattingOptions)

if (actual.text === outputContent) { // In case of success
if (actualContent === outputContent) { // In case of success
expect(true).toBeTruthy()

} else { // In case of failure
fs.writeFileSync(actualFilePath, actual.text, 'utf8')
fs.writeFileSync(debuggingFilePath, JSON.stringify(actual.tree, null, '\t'), 'utf8')
fs.writeFileSync(actualFilePath, actualContent)

try {
const tree = new Stylus.Parser(modifiedContent).parse()
fs.writeFileSync(debuggingFilePath, JSON.stringify(tree, null, '\t'))
} catch (ex) {
// Do nothing
}

const stack = [
inputFilePath,
Expand All @@ -60,8 +68,8 @@ filesAndDirectories.filter(directoriesOnly).forEach(directory => {
debuggingFilePath
].map(path => pt.resolve(path)).join('\n')

const resultLines = actual.text.replace(/\t/gm, '··').replace(/\r/gm, '¶').split('\n')
const expectLines = outputContent.replace(/\t/gm, '··').replace(/\r/gm, '¶').split('\n')
const resultLines = createComparableLines(actualContent)
const expectLines = createComparableLines(outputContent)

let lineIndex = -1
const lineLimit = Math.min(resultLines.length, expectLines.length)
Expand Down Expand Up @@ -95,8 +103,6 @@ filesAndDirectories.filter(directoriesOnly).forEach(directory => {
stack
})
}

expect(actual.warnings.length).toBe(0)
})
})
})
Expand Down

0 comments on commit c56d181

Please sign in to comment.