Skip to content

Instantly share code, notes, and snippets.

@szkrd
Last active April 11, 2019 13:48
Show Gist options
  • Save szkrd/1e61fc05fb5c5dda371969024bffa3d9 to your computer and use it in GitHub Desktop.
Save szkrd/1e61fc05fb5c5dda371969024bffa3d9 to your computer and use it in GitHub Desktop.
prettify changed ts(x) files
const fs = require('fs')
const path = require('path')
const shell = require('shelljs')
const prettier = require('prettier')
const args = process.argv
const doGitAdd = args.includes('--git-add') || args.includes('-ga')
const FILTER_PATTERN = /\.tsx?$/
shell.config.silent = true
const changedFiles = shell.exec('git status --porcelain=v1 -z')
// get filenames (except for deleted items)
const lines = changedFiles.split('\0')
const filenames = []
for (let i = 0; i < lines.length; i++) {
const line = lines[i]
const flags = line.substr(0, 2)
const filename = line.substr(3)
if (!flags.includes('D') && FILTER_PATTERN.test(filename)) {
filenames.push(path.resolve(__dirname + `/../../${filename}`))
}
if (flags.includes('R')) {
i++
}
}
// run prettier if needed
filenames.forEach(fn => {
fs.readFile(fn, 'utf-8', (error, text) => {
if (error) {
console.error('File read error', error)
return
}
prettier.resolveConfig(fn).then(options => {
options = Object.assign(options, { parser: 'typescript' })
const shortFn = path.basename(fn)
if (prettier.check(text, options)) {
console.log(`${shortFn} - already formatted`)
} else {
console.log(`${shortFn} - reformatting`)
fs.writeFile(fn, prettier.format(text, options), (error) => {
if (error) {
console.error('File write error', error)
return
}
if (doGitAdd) {
shell.exec(`git add "${fn}"`)
}
})
}
}).catch(error => {
console.error('Prettier config resolver error', error)
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment