All files / src/Site template.ts

24.7% Statements 21/85
13.33% Branches 2/15
13.04% Functions 3/23
24.69% Lines 20/81

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224                        1x 1x   1x   1x 1x 1x   1x 1x 1x 1x                     1x       1x 1x       1x 2x 2x   2x 1x                                           1x 1x                                                                                                                                                                                                                                                                                                              
import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';
import walkSync from 'walk-sync';
import * as fsUtil from '../utils/fsUtil.js';
import { INDEX_MARKDOWN_FILE, SITE_CONFIG_NAME, _ } from './constants.js';
import { SiteConfig, SiteConfigPage } from './SiteConfig.js';
import { VariableRenderer } from '../variables/VariableRenderer.js';
import * as logger from '../utils/logger.js';
 
import { LAYOUT_DEFAULT_NAME, LAYOUT_FOLDER_PATH } from '../Layout/index.js';
 
const __filepath = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filepath);
 
const requiredFiles = ['index.md', 'site.json', '_markbind/'];
 
const PATH_TO_TEMPLATE = '../../template';
const ABOUT_MARKDOWN_FILE = 'about.md';
const ABOUT_MARKDOWN_DEFAULT = '# About\n'
  + 'Welcome to your **About Us** page.\n';
const CONFIG_FOLDER_NAME = '_markbind';
const SITE_FOLDER_NAME = '_site';
const WIKI_SITE_NAV_PATH = '_Sidebar.md';
const WIKI_FOOTER_PATH = '_Footer.md';
 
type NaviagablePage = {
  src: string,
  title?: string,
};
 
export class Template {
  rootPath: string;
  templatePath: string;
  siteConfig!: SiteConfig;
  siteConfigPath: string = SITE_CONFIG_NAME;
  navigablePages!: NaviagablePage[];
 
  constructor(rootPath: string, templatePath: string) {
    this.rootPath = rootPath;
    this.templatePath = path.join(__dirname, PATH_TO_TEMPLATE, templatePath);
  }
 
  validateTemplateFromPath() {
    for (let i = 0; i < requiredFiles.length; i += 1) {
      const requiredFile = requiredFiles[i];
      const requiredFilePath = path.join(this.templatePath, requiredFile);
 
      if (!fs.existsSync(requiredFilePath)) {
        return false;
      }
    }
 
    return true;
  }
 
  generateSiteWithTemplate() {
    return new Promise((resolve, reject) => {
      fs.access(this.rootPath)
        .catch(() => fs.mkdirSync(this.rootPath))
        .then(() => fsUtil.copySyncWithOptions(this.templatePath, this.rootPath, { overwrite: false }))
        .then(resolve)
        .catch(reject);
    });
  }
 
  /**
   * A method for initializing a markbind site according to the given template.
   * Generate the site.json and an index.md file.
   */
  async init() {
    if (!this.validateTemplateFromPath()) {
      throw new Error('Template validation failed. Required files does not exist.');
    }
 
    return new Promise((resolve, reject) => {
      this.generateSiteWithTemplate()
        .then(resolve)
        .catch(reject);
    });
  }
 
  /**
   * Converts an existing GitHub wiki or docs folder to a MarkBind website.
   */
  async convert() {
    this.siteConfig = await SiteConfig.readSiteConfig(this.rootPath, this.siteConfigPath);
    this.collectNavigablePages();
    await this.addIndexPage();
    await this.addAboutPage();
    this.addDefaultLayoutFiles();
    await this.addDefaultLayoutToSiteConfig();
  }
 
  getPageGlobPaths(page: SiteConfigPage, pagesExclude: string[]) {
    const pageGlobs = page.glob ?? [];
    return walkSync(this.rootPath, {
      directories: false,
      globs: Array.isArray(pageGlobs) ? pageGlobs : [pageGlobs],
      ignore: [
        CONFIG_FOLDER_NAME,
        SITE_FOLDER_NAME,
        ...pagesExclude.concat(page.globExclude || []),
      ],
    });
  }
 
  /**
   * Collects the paths to be traversed as navigable pages
   */
  collectNavigablePages() {
    const { pages, pagesExclude } = this.siteConfig;
    const pagesFromGlobs = _.flatMap(pages.filter(page => page.glob),
                                     page => this.getPageGlobPaths(page, pagesExclude)
                                       .map(filePath => ({
                                         src: filePath,
                                         title: page.title,
                                       }))) as NaviagablePage[];
 
    this.navigablePages = pagesFromGlobs;
  }
 
  /**
   * Copies over README.md or Home.md to default index.md if present.
   */
  async addIndexPage() {
    const indexPagePath = path.join(this.rootPath, INDEX_MARKDOWN_FILE);
    const fileNames = ['README.md', 'Home.md'];
    const filePath = fileNames.find(fileName => fs.existsSync(path.join(this.rootPath, fileName)));
    // if none of the files exist, do nothing
    Iif (_.isUndefined(filePath)) return;
    try {
      await fs.copy(path.join(this.rootPath, filePath), indexPagePath);
    } catch (error) {
      throw new Error(`Failed to copy over ${filePath}`);
    }
  }
 
  /**
   * Adds an about page to site if not present.
   */
  async addAboutPage() {
    const aboutPath = path.join(this.rootPath, ABOUT_MARKDOWN_FILE);
    try {
      await fs.access(aboutPath);
    } catch (error) {
      Iif (fs.existsSync(aboutPath)) {
        return;
      }
      await fs.outputFile(aboutPath, ABOUT_MARKDOWN_DEFAULT);
    }
  }
 
  /**
   * Adds a footer to default layout of site.
   */
  addDefaultLayoutFiles() {
    const wikiFooterPath = path.join(this.rootPath, WIKI_FOOTER_PATH);
    let footer;
    Iif (fs.existsSync(wikiFooterPath)) {
      logger.info(`Copied over the existing ${WIKI_FOOTER_PATH} file to the converted layout`);
      footer = `\n${fs.readFileSync(wikiFooterPath, 'utf8')}`;
    }
 
    const wikiSiteNavPath = path.join(this.rootPath, WIKI_SITE_NAV_PATH);
    let siteNav;
    if (fs.existsSync(wikiSiteNavPath)) {
      logger.info(`Copied over the existing ${WIKI_SITE_NAV_PATH} file to the converted layout\n`
        + 'Check https://markbind.org/userGuide/tweakingThePageStructure.html#site-navigation-menus\n'
        + 'for information on site navigation menus.');
      siteNav = fs.readFileSync(wikiSiteNavPath, 'utf8');
    } else {
      siteNav = this.buildSiteNav();
    }
 
    const convertedLayoutTemplate = VariableRenderer.compile(
      fs.readFileSync(path.join(__dirname, 'siteConvertLayout.njk'), 'utf8'));
    const renderedLayout = convertedLayoutTemplate.render({
      footer,
      siteNav,
    });
    const layoutOutputPath = path.join(this.rootPath, LAYOUT_FOLDER_PATH, LAYOUT_DEFAULT_NAME);
 
    fs.writeFileSync(layoutOutputPath, renderedLayout, 'utf-8');
  }
 
  /**
   * Builds a site navigation file from the directory structure of the site.
   */
  buildSiteNav() {
    let siteNavContent = '';
    this.navigablePages
      .filter(navigablePage => !navigablePage.src.startsWith('_'))
      .forEach((page) => {
        const navigablePagePath = path.join(this.rootPath, page.src);
        const relativePagePathWithoutExt = fsUtil.removeExtensionPosix(
          path.relative(this.rootPath, navigablePagePath));
        const pageName = _.startCase(fsUtil.removeExtension(path.basename(navigablePagePath)));
        const pageUrl = `{{ baseUrl }}/${relativePagePathWithoutExt}.html`;
        siteNavContent += `* [${pageName}](${pageUrl})\n`;
      });
 
    return siteNavContent.trimEnd();
  }
 
  /**
   * Applies the default layout to all addressable pages by modifying the site config file.
   */
  async addDefaultLayoutToSiteConfig() {
    const configPath = path.join(this.rootPath, SITE_CONFIG_NAME);
    const config = await fs.readJson(configPath);
    await Template.writeToSiteConfig(config, configPath);
  }
 
  /**
   * Helper function for addDefaultLayoutToSiteConfig().
   */
  static async writeToSiteConfig(config: SiteConfig, configPath: string) {
    const layoutObj: SiteConfigPage = { glob: '**/*.md', layout: LAYOUT_DEFAULT_NAME };
    config.pages.push(layoutObj);
    await fs.outputJson(configPath, config);
  }
}