Skip to content

Commit

Permalink
add: tests for cjs
Browse files Browse the repository at this point in the history
  • Loading branch information
TOsmanov committed Dec 4, 2024
1 parent d71093f commit 189ed37
Show file tree
Hide file tree
Showing 7 changed files with 577 additions and 98 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ node_modules/
package-lock.json
*.log
.markdownlint-cli2.jsonc
.markdownlint-cli2.cjs
.idea
.DS_store
/alt-src
Expand Down
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ Run _foliant-md-linter_ from the project root with following commands and option

- `--includes-map` – set the path to the includes map (default: false)
- `--foliant-config` – set the configuration file is a foliant from which chapters (default: `./foliant.yml`)
- `--format` – set the format of the markdownlint-cli2 config file (default: `jsonc`, incompatible with `--project`, `--node-modules`, `--working-dir`)

- `markdown` – check md files for errors with markdownlint
- `-v`, `-s`, `-c`, `-d`, `-a`, `-l`, `-f`, `-m`, `--includes-map`, `--foliant-config`
Expand All @@ -123,6 +124,19 @@ Run _foliant-md-linter_ from the project root with following commands and option

`.markdownlintignore` – an exception file, each line of which can contain a glob.

### Format `cjs`

Using the `--format` argument on the CLI, you can set the configuration file format for `markdownlint-cli2`.
If you select the `cjs` format, you will get a more automated version of the configuration file.
You will not need to manually specify the parameters `working_dir`, `node_modules` and `project`.
These arguments will be make automatically using the `path` and `git-repo-name` extensions.

The configuration file will list all the files specified in the `chapters` and `includes_map` sections for use as "globs".

To use the `lint all markdown files` function with the markdownlint extension for VS Code, a file will be added to the project folder `.vscode/settings.json`.
Checking of all files will be disabled in this file, but the list of files that need to be checked will remain in the `cjs` file.
So you can use the `lint all markdown files` function in vs code, but it will check only those files that will be contained in chapters, and in includes_map.json

### Examples

The simplest case
Expand Down
81 changes: 43 additions & 38 deletions generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const {

function createConfig (mode = 'full', source = '', project = '', configPath = '',
includesMap = '', nodeModulePath = '', workingDir = '', foliantConfig = '',
vscode = false, debug = false, format = '') {
debug = false, format = '') {
let existIncludesMap = false
let listOfFiles = []

Expand Down Expand Up @@ -245,19 +245,24 @@ function createConfig (mode = 'full', source = '', project = '', configPath = ''
const json = { customRules, config }
let configExist = false
if (format === 'cjs') {
validateIntLinksConf.includesMap = undefined
validateIntLinksConf.project = undefined
validateIntLinksConf.workingDir = undefined
const includesMapPath = path.relative('./', includesMap)
const content = []
json.globs = listOfFiles
content.push('// @ts-check\n\n"use strict";\n\n')
content.push("const path = require('path')")
content.push("const repoName = require('git-repo-name')")
if (json.config.validateIntLinksConf) {
content.push("const path = require('path')")
content.push("const repoName = require('git-repo-name')")
}

content.push(`const json = ${JSON.stringify(json, null, 4)}`)
content.push('json.config[\'validate-internal-links\'].project = repoName.sync({cwd: __dirname})')
content.push('json.config[\'validate-internal-links\'].workingDir = __dirname')
content.push(`json.config['validate-internal-links'].includesMap = "./${includesMapPath}"`)

if (json.config.validateIntLinksConf) {
content.push('json.config[\'validate-internal-links\'].project = repoName.sync({cwd: __dirname})')
content.push('json.config[\'validate-internal-links\'].workingDir = __dirname')
}
if (includesMap) {
const includesMapPath = path.relative('./', includesMap)
content.push(`json.config['validate-internal-links'].includesMap = "./${includesMapPath}"`)
}

content.push('\n\nmodule.exports = json')

Expand All @@ -269,26 +274,40 @@ function createConfig (mode = 'full', source = '', project = '', configPath = ''
}
console.log(`${mode} markdownlint config '.markdownlint-cli2.cjs' created successfully!`)

if (vscode) {
// disabling globs used by the markdownlint extension
configExist = initVSCodeSettings([])
}
// disabling globs used by the markdownlint extension
configExist = initVSCodeSettings([])

// write package.json
const packageJSONforCJS = {
dependencies: {
'markdownlint-rules-foliant': 'latest',
'git-repo-name': '^1.0.1'
const existPackageJSON = fs.existsSync('package.json')
if (existPackageJSON) {
const data = JSON.parse(fs.readFileSync('package.json'))
data.dependencies['git-repo-name'] = '^1.0.1'
data.dependencies['markdownlint-rules-foliant'] = 'latest'
fs.writeFileSync('package.json', JSON.stringify(data, null, 2))
} else {
// write package.json
const packageJSONforCJS = {
dependencies: {
'markdownlint-rules-foliant': 'latest',
'git-repo-name': '^1.0.1'
}
}
fs.writeFileSync(path.resolve(cwd, 'package.json'), JSON.stringify(packageJSONforCJS, null, 2), { mode: 0o777 })
}
fs.writeFileSync(path.resolve(cwd, 'package.json'), JSON.stringify(packageJSONforCJS, null, 4), { mode: 0o777 })

// install dependencies
childProcess.execSync('npm i .', { stdio: [0, 1, 2] })

// remove package.json
fs.rmSync(path.resolve(cwd, 'package.json'))
fs.rmSync(path.resolve(cwd, 'package-lock.json'))
if (!existPackageJSON) {
// remove package.json
fs.rmSync(path.resolve(cwd, 'package.json'))
fs.rmSync(path.resolve(cwd, 'package-lock.json'))
}

if (configExist) {
console.log(`${vscodeSettings} config updated successfully!`)
} else {
console.log(`${vscodeSettings} config created successfully!`)
}
} else {
const content = JSON.stringify({ customRules, config }, null, 4)

Expand All @@ -299,17 +318,6 @@ function createConfig (mode = 'full', source = '', project = '', configPath = ''
process.exit(1)
}
console.log(`${mode} markdownlint config '.markdownlint-cli2.jsonc' created successfully!`)

if (vscode) {
configExist = initVSCodeSettings(listOfFiles)
}
}
if (vscode) {
if (configExist) {
console.log(`${vscodeSettings} config updated successfully!`)
} else {
console.log(`${vscodeSettings} config created successfully!`)
}
}
}

Expand All @@ -322,7 +330,6 @@ function initVSCodeSettings (listOfFiles = []) {
if (configExist) {
const originalData = JSON.parse(fs.readFileSync(vscodeSettings))
data = Object.assign({}, originalData, data)
console.log(data)
} else {
fs.mkdirSync(path.dirname(vscodeSettings), { recursive: true })
}
Expand Down Expand Up @@ -350,8 +357,6 @@ program
.option('-w, --working-dir <working-dir>', 'working dir', '')
.option('--foliant-config <config-path>',
'the configuration file is a foliant from which chapters', 'foliant.yml')
.option('--vs-code',
'generate settings.json for vs code', false)
.option('--format <format>',
'config for markdownlint-cli2 (default"jsonc") or "cjs" format with automatic parameter detection',
'jsonc')
Expand All @@ -362,4 +367,4 @@ program.parse()
const options = program.opts()
createConfig(options.mode, options.source, options.project, options.configPath,
options.includesMap, options.nodeModules, options.workingDir,
options.foliantConfig, options.vsCode, options.debug, options.format)
options.foliantConfig, options.debug, options.format)
63 changes: 19 additions & 44 deletions linter.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,11 @@ const markdownLinkCheckLog = '.markdownlinkcheck.log'
const genIncludesMapLog = '.gen_includes_map.log'

// Default paths
const defaultConfig = path.resolve(cwd, '.markdownlint-cli2.jsonc')
const defaultConfig = path.resolve(cwd, '.markdownlint-cli2')
const defaultSrc = 'src'
const defaultFoliantConfig = path.resolve(cwd, 'foliant.yml')
const defaultIncludesMap = 'includes_map.json'
const usedFoliantConfig = path.resolve(cwd, 'only_includes_map.yml')
const vscodeSettings = '.vscode/settings.json'

// Options
const verboseOption = new Option('-v, --verbose',
Expand Down Expand Up @@ -75,11 +74,9 @@ const nodeModulesOption = new Option('--node-modules <node-modules-path>',
const workingDirOption = new Option('-w --working-dir <working-dir>',
'working directory (required when using the extension for vs code)')
.default('')
const vsCodeOption = new Option('--vs-code',
'generate settings.json for vs code').default(false)
const formatOptions = new Option('--format <format>',
'format of the config file')
.default('jsonc')
.default('jsonc').conflicts(['project', 'working-dir', 'node-modules'])

// The path to execution
let execPath = path.resolve(__dirname, '../.bin/')
Expand Down Expand Up @@ -194,7 +191,7 @@ function writeLog (logFile) {

const commandsGen = function (src = defaultSrc, configPath = '', project = '',
markdownlintMode = 'slim', foliantConfig = defaultFoliantConfig,
nodeModules = '', workinDir = '', isFix = false, debug = false, vsCode = false, format = '') {
nodeModules = '', workinDir = '', isFix = false, debug = false, format = '') {
const commands = {}
const fix = (isFix === true) ? '-fix' : ''
const args = []
Expand All @@ -217,19 +214,14 @@ const commandsGen = function (src = defaultSrc, configPath = '', project = '',
`nodeModules: ${nodeModules}`,
`workinDir: ${workinDir}`,
`isFix: ${isFix}`,
`debug: ${debug}`,
`vsCode: ${vsCode}`
`debug: ${debug}`
)
}

if (nodeModules) {
args.push(`--node-modules ${nodeModules}`)
}

if (vsCode) {
args.push('--vs-code')
}

// Working directory and node_modules
if (workinDir) {
args.push(`--working-dir ${workinDir}`)
Expand Down Expand Up @@ -261,10 +253,6 @@ const commandsGen = function (src = defaultSrc, configPath = '', project = '',
args.push('-d')
}

if (vsCode) {
initVSCodeSettings(listOfFiles)
}

if (listOfFiles.length > 0 && !isWin) {
filesArgMdLint = ''
listOfFiles.forEach((file) => {
Expand Down Expand Up @@ -309,12 +297,12 @@ function generateIncludesMap (foliantConfig) {
})
}

function clearConfigFile (clearConfig) {
function clearConfigFile (clearConfig, format) {
if (clearConfig === true) {
console.log(`removing ${defaultConfig} ...`)
unlink(defaultConfig, (err) => {
console.log(`removing ${defaultConfig}.${format} ...`)
unlink(`${defaultConfig}.${format}`, (err) => {
if (err && err.syscall === 'unlink') {
console.log(`${defaultConfig} is absent`)
console.log(`${defaultConfig}.${format} is absent`)
}
})
}
Expand All @@ -326,29 +314,16 @@ function checkExitCode (allowfailure) {
}
}

function afterLint (verbose = false, clearConfig = false, allowFailure = false, debug = false) {
function afterLint (verbose = false, clearConfig = false, allowFailure = false, debug = false, format = '') {
printLintResults(verbose)
clearConfigFile(clearConfig)
clearConfigFile(clearConfig, format)
if (!debug) {
rmIncludesMap(clearConfig)
}
checkExitCode(allowFailure)
}

function initVSCodeSettings (listOfFiles = []) {
let data = {
'markdownlint.lintWorkspaceGlobs': listOfFiles
}
if (fs.existsSync(vscodeSettings)) {
const originalData = JSON.parse(fs.readFileSync(vscodeSettings))
data = Object.assign({}, originalData, data)
} else {
fs.mkdirSync(path.dirname(vscodeSettings), { recursive: true })
}
fs.writeFileSync(vscodeSettings, JSON.stringify(data))
}

function execute (command, verbose = false, debug = false, allowFailure = false, clearConfig = false) {
function execute (command, verbose = false, debug = false, allowFailure = false, clearConfig = false, format = '') {
if (debug) {
console.log('executed command: ')
console.log(command)
Expand All @@ -357,13 +332,14 @@ function execute (command, verbose = false, debug = false, allowFailure = false,
`verbose: ${verbose}`,
`debug: ${debug}`,
`allowFailure: ${allowFailure}`,
`clearConfig: ${clearConfig}`
`clearConfig: ${clearConfig}`,
`format: ${format}`
)
}
if (verbose === false) {
exec(command, { shell: shell }, (err, stdout, stderror) => {
if (err || stderror || stdout) {
afterLint(verbose, clearConfig, allowFailure, debug)
afterLint(verbose, clearConfig, allowFailure, debug, format)
} else {
console.log('Command completed with no errors!')
}
Expand All @@ -382,7 +358,7 @@ function execute (command, verbose = false, debug = false, allowFailure = false,
spawnCommand.on('close', (code) => {
console.log(`child process exited with code ${code}`)
console.log(`\n${'='.repeat(80)}\n\n${' '.repeat(37)}RESULTS\n\n${'='.repeat(80)}\n`)
afterLint(verbose, clearConfig, allowFailure, debug)
afterLint(verbose, clearConfig, allowFailure, debug, format)
})
}
}
Expand Down Expand Up @@ -451,7 +427,7 @@ program.command('full-check')
execute(commandsGen(options.source, options.config, options.project,
options.markdownlintmode, options.foliantConfig, options.nodeModules,
options.workingDir, options.fix, options.debug, options.format).commands.lintSrcFull,
options.verbose, options.debug, options.allowFailure, options.clearConfig)
options.verbose, options.debug, options.allowFailure, options.clearConfig, options.format)
})

program.command('markdown')
Expand All @@ -473,7 +449,7 @@ program.command('markdown')
execute(commandsGen(options.source, options.config, options.project,
options.markdownlintMode, options.foliantConfig, options.nodeModules,
options.workingDir, options.fix, options.debug, options.format).commands.markdownlint,
options.verbose, options.debug, options.allowFailure, options.clearConfig)
options.verbose, options.debug, options.allowFailure, options.clearConfig, options.format)
})

program.command('urls')
Expand All @@ -488,7 +464,7 @@ program.command('urls')
.action((options) => {
execute(commandsGen(options.source, options.config, options.nodeModules,
options.workingDir, options.debug, options.format).commands.markdownlinkcheck,
options.verbose, options.debug, options.allowFailure, options.clearConfig)
options.verbose, options.debug, options.allowFailure, options.clearConfig, options.format)
})

program.command('print')
Expand All @@ -508,12 +484,11 @@ program.command('create-config')
.addOption(foliantConfigOption)
.addOption(nodeModulesOption)
.addOption(workingDirOption)
.addOption(vsCodeOption)
.addOption(formatOptions)
.action((options) => {
execute(commandsGen(options.source, options.config, options.project,
options.markdownlintMode, options.foliantConfig, options.nodeModules,
options.workingDir, options.fix, options.debug, options.vsCode, options.format).commands.createMarkdownlintConfig,
options.workingDir, options.fix, options.debug, options.format).commands.createMarkdownlintConfig,
options.verbose, options.debug)
})

Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
"markdown-link-check": "~3.10.3",
"markdownlint-cli2": "^0.6.0",
"markdownlint-rules-foliant": "latest",
"uuid": "^11.0.1"
"uuid": "^11.0.1",
"git-repo-name": "^1.0.1"
},
"devDependencies": {
"eslint": "^7.32.0",
Expand All @@ -34,4 +35,4 @@
"husky": "^7.0.4",
"jest": "^27.5.1"
}
}
}
Loading

0 comments on commit 189ed37

Please sign in to comment.