|
| 1 | +import type { PluginHooks } from '../../lib/hooks/exported.js'; |
| 2 | + |
| 3 | +import { Args, Flags, type Hook } from '@oclif/core'; |
| 4 | +import chalk from 'chalk'; |
| 5 | +import ora from 'ora'; |
| 6 | +import { dir } from 'tmp-promise'; |
| 7 | + |
| 8 | +import BaseCommand from '../../lib/baseCommand.js'; |
| 9 | +import { fix, writeFixes } from '../../lib/frontmatter.js'; |
| 10 | +import isCI from '../../lib/isCI.js'; |
| 11 | +import { oraOptions } from '../../lib/logger.js'; |
| 12 | +import promptTerminal from '../../lib/promptWrapper.js'; |
| 13 | +import { fetchMappings, fetchSchema } from '../../lib/readmeAPIFetch.js'; |
| 14 | +import { findPages } from '../../lib/readPage.js'; |
| 15 | + |
| 16 | +const alphaNotice = 'This command is in an experimental alpha and is likely to change. Use at your own risk!'; |
| 17 | + |
| 18 | +export default class DocsMigrateCommand extends BaseCommand<typeof DocsMigrateCommand> { |
| 19 | + id = 'docs migrate' as const; |
| 20 | + |
| 21 | + route = 'guides' as const; |
| 22 | + |
| 23 | + static hidden = true; |
| 24 | + |
| 25 | + static summary = `Migrates a directory of pages to the ReadMe Guides format.\n\n${alphaNotice}`; |
| 26 | + |
| 27 | + static description = |
| 28 | + "The path can either be a directory or a single Markdown file. The command will transform the Markdown using plugins and validate the frontmatter to conform to ReadMe's standards."; |
| 29 | + |
| 30 | + static args = { |
| 31 | + path: Args.string({ description: 'Path to a local Markdown file or folder of Markdown files.', required: true }), |
| 32 | + }; |
| 33 | + |
| 34 | + static flags = { |
| 35 | + out: Flags.string({ |
| 36 | + summary: 'The directory to write the migration output to. Defaults to a temporary directory.', |
| 37 | + }), |
| 38 | + 'skip-validation': Flags.boolean({ |
| 39 | + description: |
| 40 | + 'Skips the validation of the Markdown files. Useful if this command is as part of a chain of commands that includes `docs upload`.', |
| 41 | + }), |
| 42 | + }; |
| 43 | + |
| 44 | + async run() { |
| 45 | + const { path: rawPathInput }: { path: string } = this.args; |
| 46 | + const { out: rawOutputDir, 'skip-validation': skipValidation } = this.flags; |
| 47 | + |
| 48 | + const outputDir = rawOutputDir || (await dir({ prefix: 'rdme-migration-output' })).path; |
| 49 | + |
| 50 | + let pathInput = rawPathInput; |
| 51 | + |
| 52 | + // todo: fix this type once https://github.com/oclif/core/pull/1359 is merged |
| 53 | + const fileScanHookResults: Hook.Result<PluginHooks['pre_markdown_file_scan']['return']> = await this.config.runHook( |
| 54 | + 'pre_markdown_file_scan', |
| 55 | + { pathInput }, |
| 56 | + ); |
| 57 | + |
| 58 | + fileScanHookResults.successes.forEach(success => { |
| 59 | + if (success.result) { |
| 60 | + pathInput = success.result; |
| 61 | + } |
| 62 | + }); |
| 63 | + |
| 64 | + fileScanHookResults.failures.forEach(fail => { |
| 65 | + if (fail.error && fail.error instanceof Error) { |
| 66 | + throw new Error(`Error executing the \`${fail.plugin.name}\` plugin: ${fail.error.message}`); |
| 67 | + } |
| 68 | + }); |
| 69 | + |
| 70 | + let unsortedFiles = await findPages.call(this, pathInput); |
| 71 | + |
| 72 | + let transformedByHooks = false; |
| 73 | + |
| 74 | + // todo: fix this type once https://github.com/oclif/core/pull/1359 is merged |
| 75 | + const validationHookResults: Hook.Result<PluginHooks['pre_markdown_validation']['return']> = |
| 76 | + await this.config.runHook('pre_markdown_validation', { pages: unsortedFiles }); |
| 77 | + |
| 78 | + if (!validationHookResults.successes.length && !validationHookResults.failures.length) { |
| 79 | + throw new Error('This command requires a valid migration plugin.'); |
| 80 | + } |
| 81 | + |
| 82 | + validationHookResults.successes.forEach(success => { |
| 83 | + if (success.result && success.result.length) { |
| 84 | + transformedByHooks = true; |
| 85 | + this.log(`🔌 ${success.result.length} Markdown files updated via the \`${success.plugin.name}\` plugin`); |
| 86 | + unsortedFiles = success.result; |
| 87 | + } |
| 88 | + }); |
| 89 | + |
| 90 | + validationHookResults.failures.forEach(fail => { |
| 91 | + if (fail.error && fail.error instanceof Error) { |
| 92 | + throw new Error(`Error executing the \`${fail.plugin.name}\` plugin: ${fail.error.message}`); |
| 93 | + } |
| 94 | + }); |
| 95 | + |
| 96 | + // todo: either DRY this validation logic up or remove it entirely |
| 97 | + if (!skipValidation) { |
| 98 | + const validationSpinner = ora({ ...oraOptions() }).start('🔬 Validating frontmatter data...'); |
| 99 | + |
| 100 | + const schema = await fetchSchema.call(this); |
| 101 | + const mappings = await fetchMappings.call(this); |
| 102 | + |
| 103 | + // validate the files, prompt user to fix if necessary |
| 104 | + const validationResults = unsortedFiles.map(file => { |
| 105 | + this.debug(`validating frontmatter for ${file.filePath}`); |
| 106 | + return fix.call(this, file.data, schema, mappings); |
| 107 | + }); |
| 108 | + |
| 109 | + const filesWithIssues = validationResults.filter(result => result.hasIssues); |
| 110 | + const filesWithFixableIssues = filesWithIssues.filter(result => result.changeCount); |
| 111 | + const filesWithUnfixableIssues = filesWithIssues.filter(result => result.unfixableErrors.length); |
| 112 | + |
| 113 | + if (filesWithIssues.length) { |
| 114 | + validationSpinner.warn(`${validationSpinner.text} issues found in ${filesWithIssues.length} file(s).`); |
| 115 | + if (filesWithFixableIssues.length) { |
| 116 | + if (isCI()) { |
| 117 | + throw new Error( |
| 118 | + `${filesWithIssues.length} file(s) have issues. Please run \`${this.config.bin} ${this.id} ${pathInput} --dry-run\` in a non-CI environment to fix them.`, |
| 119 | + ); |
| 120 | + } |
| 121 | + |
| 122 | + const { confirm } = await promptTerminal([ |
| 123 | + { |
| 124 | + type: 'confirm', |
| 125 | + name: 'confirm', |
| 126 | + message: `${filesWithFixableIssues.length} file(s) have issues that can be fixed automatically. Would you like to make these changes?`, |
| 127 | + }, |
| 128 | + ]); |
| 129 | + |
| 130 | + if (!confirm) { |
| 131 | + throw new Error('Aborting fixes due to user input.'); |
| 132 | + } |
| 133 | + |
| 134 | + const fileUpdateSpinner = ora({ ...oraOptions() }).start( |
| 135 | + `📝 Writing file changes to the following directory: ${chalk.underline(outputDir)}...`, |
| 136 | + ); |
| 137 | + |
| 138 | + const updatedFiles = unsortedFiles.map((file, index) => { |
| 139 | + return writeFixes.call(this, file, validationResults[index].updatedData, outputDir); |
| 140 | + }); |
| 141 | + |
| 142 | + fileUpdateSpinner.succeed(`${fileUpdateSpinner.text} ${updatedFiles.length} file(s) updated!`); |
| 143 | + |
| 144 | + unsortedFiles = updatedFiles; |
| 145 | + } |
| 146 | + |
| 147 | + // also inform the user if there are files with issues that can't be fixed |
| 148 | + if (filesWithUnfixableIssues.length) { |
| 149 | + this.warn( |
| 150 | + `${filesWithUnfixableIssues.length} file(s) have issues that cannot be fixed automatically. Please get in touch with us at support@readme.io if you need a hand.`, |
| 151 | + ); |
| 152 | + } |
| 153 | + } else if (transformedByHooks) { |
| 154 | + validationSpinner.succeed(`${validationSpinner.text} no issues found!`); |
| 155 | + |
| 156 | + const fileUpdateSpinner = ora({ ...oraOptions() }).start( |
| 157 | + `📝 Writing the updated files to the following directory: ${chalk.underline(outputDir)}...`, |
| 158 | + ); |
| 159 | + |
| 160 | + const updatedFiles = unsortedFiles.map((file, index) => { |
| 161 | + return writeFixes.call(this, file, validationResults[index].updatedData, outputDir); |
| 162 | + }); |
| 163 | + |
| 164 | + fileUpdateSpinner.succeed(`${fileUpdateSpinner.text} done!`); |
| 165 | + |
| 166 | + unsortedFiles = updatedFiles; |
| 167 | + } else { |
| 168 | + validationSpinner.succeed(`${validationSpinner.text} no issues found!`); |
| 169 | + } |
| 170 | + } else { |
| 171 | + this.debug('skipping validation'); |
| 172 | + if (transformedByHooks) { |
| 173 | + const fileUpdateSpinner = ora({ ...oraOptions() }).start( |
| 174 | + `📝 Writing the updated files to the following directory: ${chalk.underline(outputDir)}...`, |
| 175 | + ); |
| 176 | + |
| 177 | + const updatedFiles = unsortedFiles.map(file => { |
| 178 | + return writeFixes.call(this, file, file.data, outputDir); |
| 179 | + }); |
| 180 | + |
| 181 | + fileUpdateSpinner.succeed(`${fileUpdateSpinner.text} done!`); |
| 182 | + |
| 183 | + unsortedFiles = updatedFiles; |
| 184 | + } |
| 185 | + } |
| 186 | + |
| 187 | + return { outputDir }; |
| 188 | + } |
| 189 | +} |
0 commit comments