Skip to content

Commit

Permalink
Added "--compare"
Browse files Browse the repository at this point in the history
  • Loading branch information
ThisIsManta committed Oct 5, 2019
1 parent 35a8235 commit 2925e6b
Show file tree
Hide file tree
Showing 5 changed files with 117 additions and 52 deletions.
12 changes: 11 additions & 1 deletion docs/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,17 @@ <h1>Command-line usage</h1>
<p>Alternatively, you may overwrite the original files by specifying <mark>--replace</mark> or <mark>-r</mark> parameter.</p>
<code>stylus-supremacy format ./path/to/your/file.styl --replace</code>

<p>Note that <mark>--outDir</mark> and <mark>--replace</mark> do not work together. You have to choose just one.</p>
<p>In case you want to check whether your file is being formatted correctly, you may specify <mark>--compare</mark> or <mark>-c</mark>. If the input file does not comply with the given formatting options, the command will print out the difference and exit with a code of 1. This is useful when running in a CI environment.</p>
<code>
stylus-supremacy format ./path/to/your/file.styl --compare<br>
The first mismatched was at line 2.<br>
&nbsp;&nbsp;Actual: →display none<br>
&nbsp;&nbsp;Expect: →display: none;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;^^^^^^^<br>
Done with 1 error.
</code>

<p>Note that <mark>--outDir</mark>, <mark>--replace</mark>, and <mark>--compare</mark> do not work together. You have to choose just one.</p>
</article>
<article id="programming">
<h1>Programming usage</h1>
Expand Down
9 changes: 9 additions & 0 deletions edge/commandLineProcessor.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const format = require('./format')
const createFormattingOptions = require('./createFormattingOptions')
const createFormattingOptionsFromStylint = require('./createFormattingOptionsFromStylint')
const checkIfFilePathIsIgnored = require('./checkIfFilePathIsIgnored')
const compareContent = require('./compareContent')

function process(command, params = [], Console = console) {
if (command === '--version' || command === '-v') {
Expand All @@ -19,6 +20,7 @@ function process(command, params = [], Console = console) {
const optionFilePathParams = getParam(params, ['--options', '-p'], 1)
const outputDirectoryParams = getParam(params, ['--outDir', '-o'], 1)
const replaceOriginalParams = getParam(params, ['--replace', '-r'])
const compareOriginalParams = getParam(params, ['--compare', '-c'])
const dryRunParams = getParam(params, ['--dryRun'])
const debuggingParams = getParam(params, ['--debug', '-d'])

Expand Down Expand Up @@ -90,6 +92,13 @@ function process(command, params = [], Console = console) {
fs.writeFileSync(path, outputContent)
}

} else if (compareOriginalParams.length > 0) {
const error = compareContent(inputContent, outputContent)
if (error) {
Console.log(error)
return error
}

} else {
Console.log(outputContent)
}
Expand Down
43 changes: 43 additions & 0 deletions edge/compareContent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
const _ = require('lodash')

const createComparableLines = text => text
.replace(/\r/g, '¶')
.replace(/\t/g, '→')
.replace(/^\s+/gm, spaces => _.repeat('·', spaces.length))
.split('\n')

function compareContent(actualContent, expectContent) {
if (actualContent === expectContent) {
return
}

const resultLines = createComparableLines(actualContent)
const expectLines = createComparableLines(expectContent)

let lineIndex = -1
while (++lineIndex < Math.min(resultLines.length, expectLines.length)) {
if (resultLines[lineIndex] !== expectLines[lineIndex]) {
let markers = ''
let charIndex = -1
const charLimit = Math.max(resultLines[lineIndex].length, expectLines[lineIndex].length)
while (++charIndex < charLimit) {
if (resultLines[lineIndex][charIndex] !== expectLines[lineIndex][charIndex]) {
markers += '^'
} else {
markers += ' '
}
}

return [
'The first mismatched was at line ' + (lineIndex + 1) + '.',
' Actual: ' + resultLines[lineIndex],
' Expect: ' + expectLines[lineIndex],
' ' + markers
].join('\n')
}
}

return 'It was not clear to show the difference.'
}

module.exports = compareContent
39 changes: 36 additions & 3 deletions spec/commandLineProcessor.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ describe('commandLineProcessor', () => {
})
})

it('prints the formatted content given no formatting options', () => {
it('prints the formatted content, given no formatting options', () => {
const inputContent = createCodeForFormatting(`
body
display none
Expand All @@ -69,7 +69,7 @@ describe('commandLineProcessor', () => {
})

;['--options', '-p'].forEach(param => {
it('prints the formatted content given the formatting options in JSON', () => {
it('prints the formatted content, given the formatting options in JSON', () => {
const inputContent = createCodeForFormatting(`
body
display none
Expand All @@ -96,7 +96,7 @@ describe('commandLineProcessor', () => {
})

;['--options', '-p'].forEach(param => {
it('prints the formatted content given the formatting options in YAML', () => {
it('prints the formatted content, given the formatting options in YAML', () => {
const inputContent = createCodeForFormatting(`
body
display none
Expand Down Expand Up @@ -162,6 +162,39 @@ describe('commandLineProcessor', () => {
})
})

;['--compare', '-c'].forEach(param => {
it('prints no errors, given a well-formatted content', () => {
const inputContent = createCodeForFormatting(`
body {
display: none;
}
`)

fs.writeFileSync(inputTempFile, inputContent)
const errors = process('format', [inputTempFile, param], Console)

expect(errors.length).toBe(0)
})

it('prints the difference between the input and the formatted content', () => {
const inputContent = createCodeForFormatting(`
body {
display none
}
`)

fs.writeFileSync(inputTempFile, inputContent)
const errors = process('format', [inputTempFile, param], Console)

expect(errors[0]).toEqual([
'The first mismatched was at line 2.',
' Actual: →display none',
' Expect: →display: none;',
' ^^^^^^^',
].join('\n'))
})
})

it('throws an error given an unknown command', () => {
expect(() => { process('unknown', [], Console) }).toThrow()
})
Expand Down
66 changes: 18 additions & 48 deletions test/runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,47 +18,11 @@ const pt = require('path')
const _ = require('lodash')
const Stylus = require('stylus')
const format = require('../edge/format')
const compareContent = require('../edge/compareContent')

const filesAndDirectories = _.chain(ps.argv.length > 2 ? ps.argv.slice(2) : ['*']).map(para => glob.sync('spec/' + para)).flatten().value()
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')
const createComparisonTest = (actualContent, expectContent, stack) => {
const resultLines = createComparableLines(actualContent)
const expectLines = createComparableLines(expectContent)

let lineIndex = -1
const lineLimit = Math.min(resultLines.length, expectLines.length)
while (++lineIndex < Math.min(resultLines.length, expectLines.length)) {
if (resultLines[lineIndex] !== expectLines[lineIndex]) {
let diffs = ''
let charIndex = -1
const charLimit = Math.max(resultLines[lineIndex].length, expectLines[lineIndex].length)
while (++charIndex < charLimit) {
if (resultLines[lineIndex][charIndex] !== expectLines[lineIndex][charIndex]) {
diffs += '^'
} else {
diffs += ' '
}
}

return fail({
message: [
'The first mismatched was at line ' + (lineIndex + 1) + '.',
' Actual: ' + resultLines[lineIndex],
' Expect: ' + expectLines[lineIndex],
' ' + diffs
].join('\n'),
stack
})
}
}

return fail({
message: 'It was not clear to show the difference. Please check out the files below.',
stack
})
}

filesAndDirectories.filter(directoriesOnly).forEach(directory => {
const optionFilePath = pt.join(directory, 'formattingOptions.json')
Expand Down Expand Up @@ -91,10 +55,8 @@ filesAndDirectories.filter(directoriesOnly).forEach(directory => {

const actualContent = format(inputContent, formattingOptions)

if (actualContent === outputContent) {
expect(true).toBeTruthy()

} else {
const errorMessage = compareContent(actualContent, outputContent)
if (errorMessage) {
fs.writeFileSync(inputFormattedFilePath, actualContent)

const stack = [
Expand All @@ -104,7 +66,12 @@ filesAndDirectories.filter(directoriesOnly).forEach(directory => {
outputFilePath,
].map(path => pt.resolve(path)).join('\n')

createComparisonTest(actualContent, outputContent, stack)
fail({
message: errorMessage,
stack,
})
} else {
expect(true).toBeTruthy()
}
})

Expand All @@ -131,19 +98,22 @@ filesAndDirectories.filter(directoriesOnly).forEach(directory => {
// Do nothing
}

if (actualContent === outputContent) {
expect(true).toBeTruthy()

} else {
const errorMessage = compareContent(actualContent, outputContent)
if (errorMessage) {
fs.writeFileSync(outputFormattedFilePath, actualContent)

stack = [
const stack = [
outputFilePath,
outputFormattedFilePath,
outputDebuggingFilePath,
].map(path => pt.resolve(path)).join('\n')

createComparisonTest(actualContent, outputContent, stack)
fail({
message: errorMessage,
stack,
})
} else {
expect(true).toBeTruthy()
}
})
})
Expand Down

0 comments on commit 2925e6b

Please sign in to comment.