// // Copyright 2021 DXOS.org // const chalk = require('chalk'); import fs from 'fs'; import path from 'path'; import { Argv, CommandModule } from 'yargs'; import { getRepos } from '../helpers'; const createLink = (name: string, link: string) => `[${name}](./${link})`; /** * Hints commands. */ export const wikiModule: CommandModule = { command: 'wiki', describe: 'Github wiki tools.', handler: (argv: any) => {}, builder: (yargs: Argv) => yargs .demandCommand() .option('repo', { default: 'eng.wiki' }) // TODO(burdon): Config. // TODO(burdon): Commit and push. .option('ignore', { default: '^[_\.].+' }) .option('sort', { default: ['Home', 'Getting-Started'] }) .option('out', { default: '_Sidebar.md' }) .option('delimitor', { default: '-~-' }) .command({ command: 'update', describe: 'Update sidebar', builder: (yargs: Argv) => yargs, // TODO(burdon): Command (checkout, update, fixlinks, etc.) handler: async ({ projects, repo, ignore, delimitor, out, verbose, sort }: any) => { const repos = await getRepos(projects); const match = repos.filter(({ origin }) => origin.indexOf(repo) !== -1); if (!match.length) { console.log(chalk.red(`Repo not found: ${repo}`)); return; } const { dir } = match[0]; // Create sidebar. const sidebar: { [section: string]: any[] } = {}; // Read files. const ignoreRegexp = new RegExp(ignore); const files = await fs.readdirSync(dir); files.forEach(file => { if (file.match(ignoreRegexp)) { return; } const match = file.match(/(.+)\.md/); if (!match) { return; } const [section, part] = match[1].split(delimitor); let parts = sidebar[section]; if (!parts) { parts = []; sidebar[section] = parts; } parts.push({ part, file }); }); // Sort. const keys = [...sort, ...Object.keys(sidebar).filter(k => !sort.find((s: string) => s === k))]; const url = (key: string, part: string) => key + delimitor + part; // Create list. const lines: string[] = []; keys.forEach(key => { const value = sidebar[key]; if (!value) { return; } const name = key.replace(/-/g, ' '); const root = value.find(f => f.part === undefined); // Header. const header = `## ${createLink(name, root ? key : url(key, sidebar[key][0].part))}`; lines.push(header); // Sub-items. value.forEach(({ part }) => { if (part) { const name = part.replace(/-/g, ' '); const sub = `- ${createLink(name, url(key, part))}`; lines.push(sub); } }); lines.push(''); }); const content = lines.join('\n'); if (verbose) { console.log(chalk.yellow(content)); } // Write output. try { const outfile = path.join(dir, out); fs.writeFileSync(outfile, content); console.log(chalk.green('Updated: ' + outfile)); } catch (err) { console.log(chalk.red(err)); } } }) };