Skip to content

Commit

Permalink
Refactored command-line interface; Added unit testing
Browse files Browse the repository at this point in the history
  • Loading branch information
ThisIsManta committed Apr 30, 2017
1 parent b870755 commit d6f1d3c
Show file tree
Hide file tree
Showing 6 changed files with 176 additions and 38 deletions.
7 changes: 7 additions & 0 deletions edge/commandLineInterface.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#!/usr/bin/env node

const ps = require('process')

const process = require('commandLineProcessor')

process(ps.argv[2], ps.argv.slice(3))
37 changes: 13 additions & 24 deletions edge/command.js → edge/commandLineProcessor.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
#!/usr/bin/env node

const ps = require('process')
const fs = require('fs')
const pt = require('path')
const glob = require('glob')
Expand All @@ -10,9 +7,9 @@ const format = require('./format')
const createFormattingOptions = require('./createFormattingOptions')
const createFormattingOptionsFromStylint = require('./createFormattingOptionsFromStylint')

function process(command, params) {
function process(command, params = [], Console = console) {
if (command === '--version' || command === '-v') {
console.log('v' + require('../package.json').version)
Console.log('v' + require('../package.json').version)

} else if (command === 'format') {
const optionFilePathParams = getParam(params, ['--options', '-p'], 1)
Expand All @@ -27,7 +24,7 @@ function process(command, params) {
.flatten()
.value()
if (inputFiles.length === 0) {
console.log('No input files found.')
Console.log('No input files found.')
}

let formattingOptions = {}
Expand All @@ -45,14 +42,14 @@ function process(command, params) {
}

if (debuggingParams.length > 0) {
console.log(JSON.stringify(formattingOptions, null, ' '))
Console.log(JSON.stringify(formattingOptions, null, ' '))
}

const errorCount = _.chain(inputFiles)
const errors = _.chain(inputFiles)
.map(path => {
if (inputFiles.length > 1) {
console.log()
console.log('»', path)
Console.log()
Console.log('»', path)
}

try {
Expand All @@ -75,26 +72,18 @@ function process(command, params) {
}

} else {
console.log(outputContent)
Console.log(outputContent)
}
return 0

} catch (error) {
if (error.stack) {
console.log(error.stack)
} else {
console.log(error.name + ': ' + error.message)
}
return 1
Console.error(error)
}
})
.sum()
.compact()
.value()

if (errorCount > 0) {
console.log()
console.log(`Done with ${errorCount} error${errorCount === 1 ? '' : 's'}.`)
ps.exit(1)
if (errors.length > 0) {
throw new Error(`Done with ${errors.length} error${errors.length === 1 ? '' : 's'}.`)
}

} else {
Expand All @@ -112,4 +101,4 @@ function getParam(paramArray, names, nextValueCount = 0) {
return []
}

process(ps.argv[2], ps.argv.slice(3))
module.exports = process
16 changes: 16 additions & 0 deletions edge/getCodeForFormatting.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const _ = require('lodash')

function getCodeForFormatting(code) {
let lines = code.split(/\r?\n/)

while (lines[0].trim() === '') {
lines.shift()
}

const indent = _.get(lines[0].match(/(\s|\t)+/g), '0', '')
lines = lines.map(line => line.substring(indent.length))

return lines.join('\n')
}

module.exports = getCodeForFormatting
14 changes: 1 addition & 13 deletions edge/reviseDocumentation.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const createFormattingOptions = require('./createFormattingOptions')
const createFormattingOptionsFromStylint = require('./createFormattingOptionsFromStylint')
const format = require('./format')
const stylintOptions = require('stylint/src/core/config')
const getCodeForFormatting = require('./getCodeForFormatting')

let document = fs.readFileSync('docs/index.html', 'utf-8')
document = updateDocument(document, '<!-- formatting toggler placeholder -->', createFormattingTogglersForDemo)
Expand Down Expand Up @@ -150,19 +151,6 @@ function getNonBreakableForFirstWord(prefix, text) {
return '<span class="nobr">' + prefix + text.substring(0, pivot) + '</span>' + text.substring(pivot)
}

function getCodeForFormatting(code) {
let lines = code.split(/\r?\n/)

while (lines[0].trim() === '') {
lines.shift()
}

const indent = _.get(lines[0].match(/(\s|\t)+/g), '0', '')
lines = lines.map(line => line.substring(indent.length))

return lines.join('\n')
}

function getCodeForHTML(code) {
return code
.split(/\r?\n/)
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"beautify"
],
"bugs": "https://github.com/ThisIsManta/stylus-supremacy/issues",
"bin": "./edge/command.js",
"bin": "./edge/commandLineInterface.js",
"main": "./edge/index.js",
"scripts": {
"test": "node ./test/runner.js",
Expand Down
138 changes: 138 additions & 0 deletions spec/commandLineProcessor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
const fs = require('fs')

const process = require('../edge/commandLineProcessor')
const getCodeForFormatting = require('../edge/getCodeForFormatting')

const inputTempFile = 'commandLineProcessorInput.styl'
const optionTempFile = 'formattingOptions.json'
const outputTempFile = 'commandLineProcessorOutput.styl'

describe('commandLineProcessor', () => {
let Console

beforeEach(() => {
Console = {
_log: [],
log(...data) {
this._log.push(data)
},
_error: [],
error(...data) {
this._error.push(data)
},
}
})

afterEach(() => {
if (fs.existsSync(inputTempFile)) {
fs.unlinkSync(inputTempFile)
}

if (fs.existsSync(optionTempFile)) {
fs.unlinkSync(optionTempFile)
}

if (fs.existsSync(outputTempFile)) {
fs.unlinkSync(outputTempFile)
}
})

;['--version'].forEach(param => {
it('prints the current version number', () => {
process(param, [], Console)
expect(Console._log[0]).toEqual([jasmine.stringMatching(/v\d+\.\d+\.\d+/)]);
})
})

it('prints the formatted content given no formatting options', () => {
const inputContent = getCodeForFormatting(`
body
display none
`)

const expectContent = getCodeForFormatting(`
body {
display: none;
}
`)

fs.writeFileSync(inputTempFile, inputContent)
process('format', [inputTempFile], Console)
const outputContent = Console._log[0][0]

expect(outputContent).toBe(expectContent)
})

;['--options', '-p'].forEach(param => {
it('prints the formatted content given the formatting options', () => {
const inputContent = getCodeForFormatting(`
body
display none
`)

const formattingOptions = {
insertColons: false,
}

const expectContent = getCodeForFormatting(`
body {
display none;
}
`)

fs.writeFileSync(inputTempFile, inputContent)
fs.writeFileSync(optionTempFile, JSON.stringify(formattingOptions, null, '\t'))
process('format', [inputTempFile, param, optionTempFile], Console)
const outputContent = Console._log[0][0]

expect(outputContent).toBe(expectContent)
})
})

;['--outDir', '-o'].forEach(param => {
it('writes the formatted content into the given output directory', () => {
const inputContent = getCodeForFormatting(`
body
display none
`)

const expectContent = getCodeForFormatting(`
body {
display: none;
}
`)

fs.writeFileSync(inputTempFile, inputContent)
process('format', [inputTempFile, param, 'temp'], Console)
const outputContent = fs.readFileSync('temp/' + inputTempFile, 'utf-8')
fs.unlinkSync('temp/' + inputTempFile)

expect(outputContent).toBe(expectContent)
})
})

;['--replace', '-r'].forEach(param => {
it('writes the formatted content into the given output directory', () => {
const inputContent = getCodeForFormatting(`
body
display none
`)

const expectContent = getCodeForFormatting(`
body {
display: none;
}
`)

fs.writeFileSync(inputTempFile, inputContent)
process('format', [inputTempFile, param], Console)
const outputContent = fs.readFileSync(inputTempFile, 'utf-8')

expect(outputContent).toBe(expectContent)
})
})

it('throws an error given an unknown command', () => {
expect(() => { process('unknown', [], Console) }).toThrow()
})
})

0 comments on commit d6f1d3c

Please sign in to comment.