github.com/Jeffail/benthos/v3@v3.65.0/website/src/plugins/cookbooks/cookbookUtils.js (about) 1 /** 2 * Copyright (c) 2017-present, Facebook, Inc. 3 * 4 * This source code is licensed under the MIT license found in the 5 * LICENSE file in the root directory of this source tree. 6 */ 7 8 const fs = require('fs-extra'); 9 const globby = require('globby'); 10 const path = require('path'); 11 const {parseMarkdownString, normalizeUrl, aliasedSitePath} = require('@docusaurus/utils'); 12 13 module.exports = { 14 truncate: truncate, 15 generateCookbookPosts: generateCookbookPosts, 16 }; 17 18 function truncate(fileString, truncateMarker) { 19 return fileString.split(truncateMarker, 1).shift() || ''; 20 } 21 22 // YYYY-MM-DD-{name}.mdx? 23 // prefer named capture, but old Node version does not support. 24 const FILENAME_PATTERN = /^(\d{4}-\d{1,2}-\d{1,2})-?(.*?).mdx?$/; 25 26 async function generateCookbookPosts( 27 guideDir, 28 {siteConfig, siteDir}, 29 options, 30 ) { 31 const {include, routeBasePath} = options; 32 33 if (!fs.existsSync(guideDir)) { 34 return null; 35 } 36 37 const {baseUrl = ''} = siteConfig; 38 const guideFiles = await globby(include, { 39 cwd: guideDir, 40 }); 41 42 const guidePosts = []; 43 44 await Promise.all( 45 guideFiles.map(async (relativeSource) => { 46 const source = path.join(guideDir, relativeSource); 47 const aliasedSource = aliasedSitePath(source, siteDir); 48 const guideFileName = path.basename(relativeSource); 49 50 const fileString = await fs.readFile(source, 'utf-8'); 51 const {frontMatter, excerpt} = parseMarkdownString(fileString); 52 53 let date; 54 // Extract date and title from filename. 55 const match = guideFileName.match(FILENAME_PATTERN); 56 let linkName = guideFileName.replace(/\.mdx?$/, ''); 57 if (match) { 58 const [, dateString, name] = match; 59 date = new Date(dateString); 60 linkName = name; 61 } 62 // Prefer user-defined date. 63 if (frontMatter.date) { 64 date = new Date(frontMatter.date); 65 } 66 // Use file create time for guide. 67 date = date || (await fs.stat(source)).birthtime; 68 frontMatter.title = frontMatter.title || linkName; 69 70 guidePosts.push({ 71 id: frontMatter.id || frontMatter.title, 72 metadata: { 73 permalink: normalizeUrl([ 74 baseUrl, 75 routeBasePath, 76 frontMatter.id || linkName, 77 ]), 78 source: aliasedSource, 79 description: frontMatter.description || excerpt, 80 date, 81 featured: frontMatter.featured || false, 82 keywords: frontMatter.keywords, 83 title: frontMatter.title, 84 }, 85 }); 86 }), 87 ); 88 89 guidePosts.sort( 90 (a, b) => b.metadata.date.getTime() - a.metadata.date.getTime(), 91 ); 92 93 return guidePosts; 94 }