Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: refactor commands #10

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 41 additions & 11 deletions generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const fs = require('fs')
const program = new Command()
const cwd = process.cwd().toString()

function createConfig (mode = 'full', source = '', project = '') {
function createConfig (mode = 'full', source = '', project = '', configpath = '') {
let customRules
if (fs.existsSync(path.join(__dirname, '/node_modules/markdownlint-rules-foliant/package.json'))) {
customRules = [
Expand Down Expand Up @@ -180,33 +180,63 @@ function createConfig (mode = 'full', source = '', project = '') {
}

let config
if (mode === 'slim') {
config = configSlim
} else if (mode === 'default') {
return null
} else if (mode === 'typograph') {
config = configTypograph
if (configpath === '') {
if (mode === 'slim') {
config = configSlim
} else if (mode === 'default') {
return null
} else if (mode === 'typograph') {
config = configTypograph
} else {
config = configFull
}
} else {
config = configFull
mode = 'custom'
console.log('loading config...')
try {
const sharedConfig = require(path.resolve(cwd, configpath))
if (sharedConfig && sharedConfig.hasOwnProperty('markdownlintConfig')) {
console.log(sharedConfig.markdownlintConfig)
config = sharedConfig.markdownlintConfig
} else {
console.log('markdownlintConfig not found in JSON file')
mode = 'slim'
config = configSlim
}
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
console.error('File not found')
} else if (err instanceof SyntaxError) {
console.error('Invalid JSON format')
} else {
console.error(err)
}
mode = 'slim'
config = configSlim
}

console.log(config)
}

const obj = {
customRules,
config
}
const json = JSON.stringify(obj, null, 4)
fs.writeFileSync(path.resolve(cwd, '.markdownlint-cli2.jsonc'), json, 'utf8')
console.log(`${mode} markdownlint config created succesfully!`)
console.log(`${mode} markdownlint config created successfully!`)
}

program
.name('create-markdownlint-config')
.description('script for generating .markdownlint-cli2.jsonc in foliant-project root')
.version('0.0.1')
.option('-m, --mode <mode>', 'full, slim, typograph or default config', 'full')
.option('-m, --mode <mode>', 'full, slim, typograph or default config', 'slim')
.option('-s, --source <source>', 'relative path to source directory', '')
.option('-p, --project <project>', 'project name', '')
.option('-c, --configpath <path-to-config>', 'path to custom config', '')

program.parse()

const options = program.opts()
createConfig(options.mode, options.source, options.project)
createConfig(options.mode, options.source, options.project, options.configpath)
146 changes: 34 additions & 112 deletions linter.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,9 @@ const cwd = process.cwd().toString()
const isWin = process.platform === 'win32'
const shell = (isWin === true) ? 'cmd.exe' : '/bin/bash'

const markdownLintSlimLog = '.markdownlint_slim.log'
const markdownLintFullLog = '.markdownlint_full.log'
const markdownLintLog = '.markdownlint.log'
const markdownLinkCheckLog = '.markdownlinkcheck.log'
const defaultConfig = path.resolve(cwd, '.markdownlint-cli2.jsonc')
const markdownLintLogs = /\.markdownlint_.*\.log/
const defaultSrc = 'src'

let execPath = path.resolve(__dirname, '../.bin/')
Expand All @@ -33,7 +31,7 @@ function printErrors (logFile) {
let file
let fileTmp
let fileLink
if (logFile.match(markdownLintLogs)) {
if (logFile.match(markdownLintLog)) {
regex = /^(?!Finding: |Linting: |Summary: |markdownlint-cli2| ).+/gm
} else {
regex = /^\s*\[✖].* Status:/gm
Expand All @@ -47,10 +45,10 @@ function printErrors (logFile) {
}
if (line.match(regex)) {
file = line.split(':')[0]
if (fileTmp !== file && logFile.match(markdownLintLogs)) {
if (fileTmp !== file && logFile.match(markdownLintLog)) {
fileTmp = file
console.log(`\n${'-'.repeat(80)}\n\nFILE: ${fileTmp}\n`)
} else if (!logFile.match(markdownLintLogs)) {
} else if (!logFile.match(markdownLintLog)) {
console.log(`\n${'-'.repeat(80)}\n\n${fileLink}\n`)
}
console.log(line)
Expand Down Expand Up @@ -87,32 +85,24 @@ function numberFromLog (logFile, regex, counterror = true) {
}

const printLintResults = function (verbose = false) {
const markdownlintSlim = path.resolve(cwd, markdownLintSlimLog)
const markdownlintLogPath = path.resolve(cwd, markdownLintLog)
const markdownFiles = /Linting: (\d+) file/g
const files = fs.readdirSync(__dirname).filter(fn => fn.match(markdownLintLogs))
const files = fs.readdirSync(__dirname).filter(fn => fn.match(markdownLintLog))
const markdownFilesCount = numberFromLog(files[0], markdownFiles, false)

if (markdownFilesCount !== null && markdownFilesCount !== undefined) {
console.log(`Checked ${markdownFilesCount} files`)
}

const markdownLintErrors = /Summary: (\d+) error/g
let markdownLintErrorsCount = numberFromLog(markdownlintSlim, markdownLintErrors)
const markdownLintErrorsCount = numberFromLog(markdownlintLogPath, markdownLintErrors)

if (markdownLintErrorsCount !== null && markdownLintErrorsCount !== undefined) {
console.log(`Found ${markdownLintErrorsCount} critical formatting errors`)
console.log(`Found ${markdownLintErrorsCount} formatting errors`)
if (verbose) {
printErrors(markdownlintSlim)
printErrors(markdownlintLogPath)
}
console.log(`Full markdownlint log see in ${markdownlintSlim}\n`)
}

const markdownlintFull = path.resolve(cwd, markdownLintFullLog)
markdownLintErrorsCount = numberFromLog(markdownlintFull, markdownLintErrors)

if (markdownLintErrorsCount !== null && markdownLintErrorsCount !== undefined) {
console.log(`Found ${markdownLintErrorsCount} styleguide and formatting errors`)
console.log(`Full markdownlint log see in ${markdownlintFull}\n`)
console.log(`Full markdownlint log see in ${markdownlintLogPath}\n`)
}

const markdownLinkCheckErrors = /ERROR: (\d+) dead links found!/g
Expand All @@ -132,21 +122,15 @@ function writeLog (logFile) {
return (isWin === true) ? `>> ${logFile} 2>&1` : `2>&1 | tee ${logFile}`
}

const commandsGen = function (src = defaultSrc, customConfig = false, project = '') {
const commandsGen = function (src = defaultSrc, configPath = '', project = '', markdownlintmode, isFix) {
const commands = {}
const and = (isWin === true) ? '&' : ';'
commands.createFullMarkdownlintConfig = (customConfig === false) ? `node ${path.join(__dirname, '/generate.js')} -m full -s ${src} -p "${project}"` : 'echo "using custom config"'
commands.createSlimMarkdownlintConfig = (customConfig === false) ? `node ${path.join(__dirname, '/generate.js')} -m slim -s ${src} -p "${project}"` : 'echo "using custom config"'
commands.createTypographMarkdownlintConfig = (customConfig === false) ? `node ${path.join(__dirname, '/generate.js')} -m typograph -s ${src} -p "${project}"` : 'echo "using custom config"'
commands.markdownlintSrcSlim = `${commands.createSlimMarkdownlintConfig} && ${execPath}/markdownlint-cli2 "${src}/**/*.md" ${writeLog(markdownLintSlimLog)}`
commands.markdownlintSrcFull = `${commands.markdownlintSrcSlim} ${and} ${commands.createFullMarkdownlintConfig} && ${execPath}/markdownlint-cli2 "${src}/**/*.md" ${writeLog(markdownLintFullLog)}`
commands.markdownlintSrcFix = `${commands.markdownlintSrcSlim} ${and} ${commands.createFullMarkdownlintConfig} && ${execPath}/markdownlint-cli2-fix "${src}/**/*.md" ${writeLog(markdownLintFullLog)}`
commands.markdownlintSrcTypograph = `${commands.createTypographMarkdownlintConfig} && ${execPath}/markdownlint-cli2-fix "${src}/**/*.md" ${writeLog(markdownLintFullLog)}`
const fix = (isFix === true) ? '-fix' : ''
commands.createMarkdownlintConfig = (markdownlintmode !== 'mdlint-default') ? `node ${path.join(__dirname, '/generate.js')} -m ${markdownlintmode} -s ${src} -p "${project}" -c "${configPath}"` : 'echo "using default markdownlint config"'
commands.markdownlint = `${commands.createMarkdownlintConfig} && ${execPath}/markdownlint-cli2${fix} "${src}/**/*.md" ${writeLog(markdownLintLog)}`
commands.markdownlinkcheckSrcUnix = `find ${src}/ -type f -name '*.md' -print0 | xargs -0 -n1 ${execPath}/markdown-link-check -p -c ${path.join(__dirname, '/configs/mdLinkCheckConfig.json')} ${writeLog(path.join(cwd, markdownLinkCheckLog))}`
commands.markdownlinkcheckSrcWin = `del ${path.join(cwd, markdownLinkCheckLog)} & forfiles /P ${src} /S /M *.md /C "cmd /c npx markdown-link-check @file -p -c ${path.join(__dirname, '/configs/mdLinkCheckConfig.json')} ${writeLog(path.join(cwd, markdownLinkCheckLog))}"`
commands.markdownlinkcheckSrc = (isWin === true) ? commands.markdownlinkcheckSrcWin : commands.markdownlinkcheckSrcUnix
commands.lintSrcEssential = `${commands.markdownlintSrcSlim} & ${commands.markdownlinkcheckSrc}`
commands.lintSrcFull = `${commands.markdownlintSrcFull} & ${commands.markdownlinkcheckSrc}`
commands.markdownlinkcheck = (isWin === true) ? commands.markdownlinkcheckSrcWin : commands.markdownlinkcheckSrcUnix
commands.lintSrcFull = `${commands.markdownlint} & ${commands.markdownlinkcheck}`
return {
commands
}
Expand Down Expand Up @@ -209,11 +193,13 @@ function execute (command, verbose = false, debug = false, allowfailure = false,

const verboseOption = new Option('-v, --verbose', 'Print full linting results').default(false)
const sourceOption = new Option('-s, --source <path-to-sources>', 'source directory').default(defaultSrc)
const configOption = new Option('-c, --config', 'use custom markdownlint config').default(false)
const configOption = new Option('-c, --config <path-to-config>', 'path to custom config').default('')
const projectOption = new Option('-p, --project <project-name>', 'project name').default('')
const debugOption = new Option('-d, --debug', 'print executing command').default(false)
const allowfailureOption = new Option('-f, --allowfailure', 'allow exit with failure if errors').default(false)
const allowfailureOption = new Option('-a, --allowfailure', 'allow exit with failure if errors').default(false)
const clearconfigOption = new Option('-l, --clearconfig', 'remove markdownlint config after execution').default(false)
const fixOption = new Option('-f, --fix', 'fix errors with markdownlint').default(false)
const markdownlintmodeOption = new Option('-m, --markdownlintmode <mode-name>', 'set mode for markdownlint').choices(['full', 'slim', 'typograph', 'mdlint-default']).default('slim')

program
.name('foliant-md-linter')
Expand All @@ -229,21 +215,25 @@ program.command('full-check')
.addOption(debugOption)
.addOption(allowfailureOption)
.addOption(clearconfigOption)
.addOption(fixOption)
.addOption(markdownlintmodeOption)
.action((options) => {
execute(commandsGen(options.source, options.config, options.project).commands.lintSrcFull, options.verbose, options.debug, options.allowfailure, options.clearconfig)
execute(commandsGen(options.source, options.config, options.project, options.markdownlintmode, options.fix).commands.lintSrcFull, options.verbose, options.debug, options.allowfailure, options.clearconfig)
})

program.command('essential')
.description('Check md files for critical formatting errors with markdownlint and validate external links ith markdown-link-check')
program.command('markdown')
.description('Check md files for errors with markdownlint')
.addOption(verboseOption)
.addOption(sourceOption)
.addOption(configOption)
.addOption(projectOption)
.addOption(debugOption)
.addOption(allowfailureOption)
.addOption(clearconfigOption)
.addOption(fixOption)
.addOption(markdownlintmodeOption)
.action((options) => {
execute(commandsGen(options.source, options.config, options.project).commands.lintSrcEssential, options.verbose, options.debug, options.allowfailure, options.clearconfig)
execute(commandsGen(options.source, options.config, options.project, options.markdownlintmode, options.fix).commands.markdownlint, options.verbose, options.debug, options.allowfailure, options.clearconfig)
})

program.command('urls')
Expand All @@ -254,59 +244,7 @@ program.command('urls')
.addOption(allowfailureOption)
.addOption(clearconfigOption)
.action((options) => {
execute(commandsGen(options.source, options.config).commands.markdownlinkcheckSrc, options.verbose, options.debug, options.allowfailure, options.clearconfig)
})

program.command('styleguide')
.description('Check for styleguide adherence with markdownlint')
.addOption(verboseOption)
.addOption(sourceOption)
.addOption(configOption)
.addOption(projectOption)
.addOption(debugOption)
.addOption(allowfailureOption)
.addOption(clearconfigOption)
.action((options) => {
execute(commandsGen(options.source, options.config, options.project).commands.markdownlintSrcFull, options.verbose, options.debug, options.allowfailure, options.clearconfig)
})

program.command('slim')
.description('Check for critical errors with markdownlint')
.addOption(verboseOption)
.addOption(sourceOption)
.addOption(configOption)
.addOption(projectOption)
.addOption(debugOption)
.addOption(allowfailureOption)
.addOption(clearconfigOption)
.action((options) => {
execute(commandsGen(options.source, options.config, options.project).commands.markdownlintSrcSlim, options.verbose, options.debug, options.allowfailure, options.clearconfig)
})

program.command('fix')
.description('Fix formatting errors with markdownlint')
.addOption(verboseOption)
.addOption(sourceOption)
.addOption(configOption)
.addOption(projectOption)
.addOption(debugOption)
.addOption(allowfailureOption)
.addOption(clearconfigOption)
.action((options) => {
execute(commandsGen(options.source, options.config, options.project).commands.markdownlintSrcFix, options.verbose, options.debug, options.allowfailure, options.clearconfig)
})

program.command('typograph')
.description('Fix typographic errors with markdownlint')
.addOption(verboseOption)
.addOption(sourceOption)
.addOption(configOption)
.addOption(projectOption)
.addOption(debugOption)
.addOption(allowfailureOption)
.addOption(clearconfigOption)
.action((options) => {
execute(commandsGen(options.source, options.config, options.project).commands.markdownlintSrcTypograph, options.verbose, options.debug, options.allowfailure, options.clearconfig)
execute(commandsGen(options.source, options.config).commands.markdownlinkcheck, options.verbose, options.debug, options.allowfailure, options.clearconfig)
})

program.command('print')
Expand All @@ -316,31 +254,15 @@ program.command('print')
printLintResults(options.verbose)
})

program.command('create-full-config')
.description('Create full markdownlint config')
.addOption(sourceOption)
.addOption(projectOption)
.addOption(debugOption)
.action((options) => {
execute(commandsGen(options.source, options.config, options.project).commands.createFullMarkdownlintConfig, options.verbose, options.debug)
})

program.command('create-slim-config')
.description('Create slim markdownlint config')
.addOption(sourceOption)
.addOption(projectOption)
.addOption(debugOption)
.action((options) => {
execute(commandsGen(options.source, options.config, options.project).commands.createSlimMarkdownlintConfig, options.verbose, options.debug)
})

program.command('create-typograph-config')
.description('Create typograph markdownlint config')
program.command('create-config')
.description('Create markdownlint config')
.addOption(verboseOption)
.addOption(sourceOption)
.addOption(projectOption)
.addOption(markdownlintmodeOption)
.addOption(debugOption)
.action((options) => {
execute(commandsGen(options.source, options.config, options.project).commands.createTypographMarkdownlintConfig, options.verbose, options.debug)
execute(commandsGen(options.source, options.config, options.project, options.markdownlintmode).commands.createMarkdownlintConfig, options.verbose, options.debug)
})

program.parse()
Loading