1
0
mirror of https://github.com/kamranahmedse/developer-roadmap.git synced 2025-08-21 00:21:35 +02:00

Rearrange scripts

This commit is contained in:
Kamran Ahmed
2023-05-08 22:16:27 +01:00
parent 6fcb153244
commit 0ba1a8a1d1
13 changed files with 10 additions and 615 deletions

View File

@@ -0,0 +1,173 @@
const fs = require('fs');
const path = require('path');
const OPEN_AI_API_KEY = process.env.OPEN_AI_API_KEY;
const ALL_BEST_PRACTICES_DIR = path.join(
__dirname,
'../src/data/best-practices'
);
const BEST_PRACTICE_JSON_DIR = path.join(
__dirname,
'../public/jsons/best-practices'
);
const bestPracticeId = process.argv[2];
const bestPracticeTitle = bestPracticeId.replace(/-/g, ' ');
const allowedBestPracticeIds = fs.readdirSync(ALL_BEST_PRACTICES_DIR);
if (!bestPracticeId) {
console.error('bestPracticeId is required');
process.exit(1);
}
if (!allowedBestPracticeIds.includes(bestPracticeId)) {
console.error(`Invalid bestPractice key ${bestPracticeId}`);
console.error(`Allowed keys are ${allowedBestPracticeIds.join(', ')}`);
process.exit(1);
}
const BEST_PRACTICE_CONTENT_DIR = path.join(
ALL_BEST_PRACTICES_DIR,
bestPracticeId,
'content'
);
const { Configuration, OpenAIApi } = require('openai');
const configuration = new Configuration({
apiKey: OPEN_AI_API_KEY,
});
const openai = new OpenAIApi(configuration);
function getFilesInFolder(folderPath, fileList = {}) {
const files = fs.readdirSync(folderPath);
files.forEach((file) => {
const filePath = path.join(folderPath, file);
const stats = fs.statSync(filePath);
if (stats.isDirectory()) {
getFilesInFolder(filePath, fileList);
} else if (stats.isFile()) {
const fileUrl = filePath
.replace(BEST_PRACTICE_CONTENT_DIR, '') // Remove the content folder
.replace(/\/\d+-/g, '/') // Remove ordering info `/101-ecosystem`
.replace(/\/index\.md$/, '') // Make the `/index.md` to become the parent folder only
.replace(/\.md$/, ''); // Remove `.md` from the end of file
fileList[fileUrl] = filePath;
}
});
return fileList;
}
function writeTopicContent(topicTitle) {
let prompt = `I am reading a guide that has best practices about "${bestPracticeTitle}". I want to know more about "${topicTitle}". Write me a brief introductory paragraph about this and some tips on how I make sure of this? Behave as if you are the author of the guide.`;
console.log(`Generating '${topicTitle}'...`);
return new Promise((resolve, reject) => {
openai
.createChatCompletion({
model: 'gpt-4',
messages: [
{
role: 'user',
content: prompt,
},
],
})
.then((response) => {
const article = response.data.choices[0].message.content;
resolve(article);
})
.catch((err) => {
reject(err);
});
});
}
async function writeFileForGroup(group, topicUrlToPathMapping) {
const topicId = group?.properties?.controlName;
const topicTitle = group?.children?.controls?.control?.find(
(control) => control?.typeID === 'Label'
)?.properties?.text;
const currTopicUrl = `/${topicId}`;
if (currTopicUrl.startsWith('/check:')) {
return;
}
const contentFilePath = topicUrlToPathMapping[currTopicUrl];
if (!contentFilePath) {
console.log(`Missing file for: ${currTopicUrl}`);
process.exit(0);
return;
}
const currentFileContent = fs.readFileSync(contentFilePath, 'utf8');
const isFileEmpty = currentFileContent.replace(/^#.+/, ``).trim() === '';
if (!isFileEmpty) {
console.log(`Ignoring ${topicId}. Not empty.`);
return;
}
let newFileContent = `# ${topicTitle}`;
if (!OPEN_AI_API_KEY) {
console.log(`Writing ${topicId}..`);
fs.writeFileSync(contentFilePath, newFileContent, 'utf8');
return;
}
const topicContent = await writeTopicContent(topicTitle);
newFileContent += `\n\n${topicContent}`;
console.log(`Writing ${topicId}..`);
fs.writeFileSync(contentFilePath, newFileContent, 'utf8');
// console.log(currentFileContent);
// console.log(currTopicUrl);
// console.log(topicTitle);
// console.log(topicUrlToPathMapping[currTopicUrl]);
}
async function run() {
const topicUrlToPathMapping = getFilesInFolder(BEST_PRACTICE_CONTENT_DIR);
const bestPracticeJson = require(path.join(
BEST_PRACTICE_JSON_DIR,
`${bestPracticeId}.json`
));
const groups = bestPracticeJson?.mockup?.controls?.control?.filter(
(control) =>
control.typeID === '__group__' &&
!control.properties?.controlName?.startsWith('ext_link')
);
if (!OPEN_AI_API_KEY) {
console.log('----------------------------------------');
console.log('OPEN_AI_API_KEY not found. Skipping openai api calls...');
console.log('----------------------------------------');
}
const writePromises = [];
for (let group of groups) {
writePromises.push(writeFileForGroup(group, topicUrlToPathMapping));
}
console.log('Waiting for all files to be written...');
await Promise.all(writePromises);
}
run()
.then(() => {
console.log('Done');
})
.catch((err) => {
console.error(err);
process.exit(1);
});

View File

@@ -0,0 +1,155 @@
const fs = require('fs');
const path = require('path');
const CONTENT_DIR = path.join(__dirname, '../content');
// Directory containing the best-practices
const BEST_PRACTICE_CONTENT_DIR = path.join(
__dirname,
'../src/data/best-practices'
);
const bestPracticeId = process.argv[2];
const allowedBestPracticeId = fs.readdirSync(BEST_PRACTICE_CONTENT_DIR);
if (!bestPracticeId) {
console.error('bestPractice is required');
process.exit(1);
}
if (!allowedBestPracticeId.includes(bestPracticeId)) {
console.error(`Invalid best practice key ${bestPracticeId}`);
console.error(`Allowed keys are ${allowedBestPracticeId.join(', ')}`);
process.exit(1);
}
// Directory holding the best parctice content files
const bestPracticeDirName = fs
.readdirSync(BEST_PRACTICE_CONTENT_DIR)
.find((dirName) => dirName.replace(/\d+-/, '') === bestPracticeId);
if (!bestPracticeDirName) {
console.error('Best practice directory not found');
process.exit(1);
}
const bestPracticeDirPath = path.join(
BEST_PRACTICE_CONTENT_DIR,
bestPracticeDirName
);
const bestPracticeContentDirPath = path.join(
BEST_PRACTICE_CONTENT_DIR,
bestPracticeDirName,
'content'
);
// If best practice content already exists do not proceed as it would override the files
if (fs.existsSync(bestPracticeContentDirPath)) {
console.error(
`Best Practice content already exists @ ${bestPracticeContentDirPath}`
);
process.exit(1);
}
function prepareDirTree(control, dirTree) {
// Directories are only created for groups
if (control.typeID !== '__group__') {
return;
}
// e.g. 104-testing-your-apps:other-options
const controlName = control?.properties?.controlName || '';
// No directory for a group without control name
if (
!controlName ||
controlName.startsWith('check:') ||
controlName.startsWith('ext_link:')
) {
return;
}
// e.g. ['testing-your-apps', 'other-options']
const dirParts = controlName.split(':');
// Nest the dir path in the dirTree
let currDirTree = dirTree;
dirParts.forEach((dirPart) => {
currDirTree[dirPart] = currDirTree[dirPart] || {};
currDirTree = currDirTree[dirPart];
});
const childrenControls = control.children.controls.control;
// No more children
if (childrenControls.length) {
childrenControls.forEach((childControl) => {
prepareDirTree(childControl, dirTree);
});
}
return { dirTree };
}
const bestPractice = require(path.join(
__dirname,
`../public/jsons/best-practices/${bestPracticeId}`
));
const controls = bestPractice.mockup.controls.control;
// Prepare the dir tree that we will be creating
const dirTree = {};
controls.forEach((control) => {
prepareDirTree(control, dirTree);
});
/**
* @param parentDir Parent directory in which directory is to be created
* @param dirTree Nested dir tree to be created
* @param filePaths The mapping from groupName to file path
*/
function createDirTree(parentDir, dirTree, filePaths = {}) {
const childrenDirNames = Object.keys(dirTree);
const hasChildren = childrenDirNames.length !== 0;
// @todo write test for this, yolo for now
const groupName = parentDir
.replace(bestPracticeContentDirPath, '') // Remove base dir path
.replace(/(^\/)|(\/$)/g, '') // Remove trailing slashes
.replaceAll('/', ':') // Replace slashes with `:`
.replace(/:\d+-/, ':');
const humanizedGroupName = groupName
.split(':')
.pop()
?.replaceAll('-', ' ')
.replace(/^\w/, ($0) => $0.toUpperCase());
// If no children, create a file for this under the parent directory
if (!hasChildren) {
let fileName = `${parentDir}.md`;
fs.writeFileSync(fileName, `# ${humanizedGroupName}`);
filePaths[groupName || 'home'] = fileName.replace(CONTENT_DIR, '');
return filePaths;
}
// There *are* children, so create the parent as a directory
// and create `index.md` as the content file for this
fs.mkdirSync(parentDir);
let readmeFilePath = path.join(parentDir, 'index.md');
fs.writeFileSync(readmeFilePath, `# ${humanizedGroupName}`);
filePaths[groupName || 'home'] = readmeFilePath.replace(CONTENT_DIR, '');
// For each of the directory names, create a
// directory inside the given directory
childrenDirNames.forEach((dirName) => {
createDirTree(path.join(parentDir, dirName), dirTree[dirName], filePaths);
});
return filePaths;
}
// Create directories and get back the paths for created directories
createDirTree(bestPracticeContentDirPath, dirTree);
console.log('Created best practice content directory structure');

View File

@@ -0,0 +1,19 @@
const fs = require('node:fs');
const path = require('node:path');
const jsonsDir = path.join(process.cwd(), 'public/jsons');
const childJsonDirs = fs.readdirSync(jsonsDir);
childJsonDirs.forEach((childJsonDir) => {
const fullChildJsonDirPath = path.join(jsonsDir, childJsonDir);
const jsonFiles = fs.readdirSync(fullChildJsonDirPath);
jsonFiles.forEach((jsonFileName) => {
console.log(`Compressing ${jsonFileName}...`);
const jsonFilePath = path.join(fullChildJsonDirPath, jsonFileName);
const json = require(jsonFilePath);
fs.writeFileSync(jsonFilePath, JSON.stringify(json));
});
});

129
scripts/page-data-agg.cjs Normal file
View File

@@ -0,0 +1,129 @@
const csv = require('csv-parser');
const fs = require('fs');
const path = require('path');
const csvFilePath = path.join(__dirname, '../data.csv');
const results = {};
const pageSummary = {};
fs.createReadStream(csvFilePath)
.pipe(
csv({
separator: ',',
mapHeaders: ({ header, index }) =>
header.toLowerCase().replace(/ /g, '_'),
mapValues: ({ header, index, value }) => {
if (header === 'page') {
return (
value
.replace(/"/g, '')
.replace(/'/g, '')
.replace(/`/g, '')
.replace(/\?r=/g, '#r#')
.replace(/\?.+?$/g, '')
.replace(/#r#/g, '?r=')
.replace(/\/$/g, '') || '/'
);
}
if (header !== 'month_of_year') {
return parseInt(value, 10);
}
return value;
},
})
)
.on('data', (data) => {
const { page, month_of_year, unique_pageviews, users } = data;
const pageData = results[page] || {};
const existingPageMonthData = pageData[month_of_year] || {};
const existingViews = existingPageMonthData.views || 0;
const existingUsers = existingPageMonthData.users || 0;
const newViews = existingViews + unique_pageviews;
const newUsers = existingUsers + users;
pageData[month_of_year] = {
views: newViews,
users: newUsers,
};
results[page] = pageData;
pageSummary[page] = pageSummary[page] || { views: 0, users: 0 };
pageSummary[page].views += unique_pageviews;
pageSummary[page].users += users;
})
.on('end', () => {
const csvHeader = [
'Page',
'Jan 2022',
'Feb 2022',
'Mar 2022',
'Apr 2022',
'May 2022',
'Jun 2022',
'Jul 2022',
'Aug 2022',
'Sep 2022',
'Oct 2022',
'Nov 2022',
'Dec 2022',
'Jan 2023',
'Feb 2023',
'Mar 2023',
'Apr 2023',
'May 2023',
'Jun 2023',
'Jul 2023',
'Aug 2023',
'Sep 2023',
'Oct 2023',
'Nov 2023',
'Dec 2023',
];
const csvRows = Object.keys(pageSummary)
.filter(pageUrl => pageSummary[pageUrl].views > 10)
.filter(pageUrl => !['/upcoming', '/pdfs', '/signup', '/login', '/@'].includes(pageUrl))
.sort((pageA, pageB) => {
const aViews = pageSummary[pageA].views;
const bViews = pageSummary[pageB].views;
return bViews - aViews;
})
.map((pageUrl) => {
const rawPageResult = results[pageUrl];
const pageResultCsvRow = [];
csvHeader.forEach((csvHeaderItem) => {
if (csvHeaderItem === 'Page') {
pageResultCsvRow.push(pageUrl);
return;
}
const csvHeaderItemAlt = csvHeaderItem
.replace(/ /g, '_')
.toLowerCase();
const result = rawPageResult[csvHeaderItem || csvHeaderItemAlt] || {};
const views = result.views || 0;
const users = result.users || 0;
pageResultCsvRow.push(users);
});
return pageResultCsvRow;
});
const finalCsvRows = [csvHeader, ...csvRows];
const csvRowStrings = finalCsvRows.map((row) => {
return row.join(',');
});
const csvString = csvRowStrings.join('\n');
fs.writeFileSync(path.join(__dirname, '../data-agg.csv'), csvString);
});

37
scripts/readme.md Normal file
View File

@@ -0,0 +1,37 @@
## CLI Tools
> A bunch of CLI scripts to make the development easier
## `roadmap-links.cjs`
Generates a list of all the resources links in any roadmap file.
## `compress-jsons.cjs`
Compresses all the JSON files in the `public/jsons` folder
## `update-sponsors.cjs`
Updates the sponsor ads on each roadmap page with the latest sponsor information in the Excel sheet.
## `roadmap-content.cjs`
Currently, for any new roadmaps that we add, we do create the interactive roadmap but we end up leaving the content empty in the roadmap till we get time to fill it up manually.
This script populates all the content files with some minimal content from OpenAI so that the users visiting the website have something to read in the interactive roadmap till we get time to fill it up manually.
## `roadmap-dirs.cjs`
This command is used to create the content folders and files for the interactivity of the roadmap. You can use the below command to generate the roadmap skeletons inside a roadmap directory:
```bash
npm run roadmap-dirs [frontend|backend|devops|...]
```
For the content skeleton to be generated, we should have proper grouping, and the group names in the project files. You can follow the steps listed below in order to add the meta information to the roadmap.
- Remove all the groups from the roadmaps through the project editor. Select all and press `cmd+shift+g`
- Identify the boxes that should be clickable and group them together with `cmd+shift+g`
- Assign the name to the groups.
- Group names have the format of `[sort]-[slug]` e.g. `100-internet`. Each group name should start with a number starting from 100 which helps with sorting of the directories and the files. Groups at the same level have the sequential sorting information.
- Each groups children have a separate group and have the name similar to `[sort]-[parent-slug]:[child-slug]` where sort refers to the sorting of the `child-slug` and not the parent. Also parent-slug does not need to have the sorting information as a part of slug e.g. if parent was `100-internet` the children would be `100-internet:how-does-the-internet-work`, `101-internet:what-is-http`, `102-internet:browsers`.

171
scripts/roadmap-content.cjs Normal file
View File

@@ -0,0 +1,171 @@
const fs = require('fs');
const path = require('path');
const OPEN_AI_API_KEY = process.env.OPEN_AI_API_KEY;
const ALL_ROADMAPS_DIR = path.join(__dirname, '../src/data/roadmaps');
const ROADMAP_JSON_DIR = path.join(__dirname, '../public/jsons/roadmaps');
const roadmapId = process.argv[2];
const allowedRoadmapIds = fs.readdirSync(ALL_ROADMAPS_DIR);
if (!roadmapId) {
console.error('roadmapId is required');
process.exit(1);
}
if (!allowedRoadmapIds.includes(roadmapId)) {
console.error(`Invalid roadmap key ${roadmapId}`);
console.error(`Allowed keys are ${allowedRoadmapIds.join(', ')}`);
process.exit(1);
}
const ROADMAP_CONTENT_DIR = path.join(ALL_ROADMAPS_DIR, roadmapId, 'content');
const { Configuration, OpenAIApi } = require('openai');
const configuration = new Configuration({
apiKey: OPEN_AI_API_KEY,
});
const openai = new OpenAIApi(configuration);
function getFilesInFolder(folderPath, fileList = {}) {
const files = fs.readdirSync(folderPath);
files.forEach((file) => {
const filePath = path.join(folderPath, file);
const stats = fs.statSync(filePath);
if (stats.isDirectory()) {
getFilesInFolder(filePath, fileList);
} else if (stats.isFile()) {
const fileUrl = filePath
.replace(ROADMAP_CONTENT_DIR, '') // Remove the content folder
.replace(/\/\d+-/g, '/') // Remove ordering info `/101-ecosystem`
.replace(/\/index\.md$/, '') // Make the `/index.md` to become the parent folder only
.replace(/\.md$/, ''); // Remove `.md` from the end of file
fileList[fileUrl] = filePath;
}
});
return fileList;
}
function writeTopicContent(currTopicUrl) {
const [parentTopic, childTopic] = currTopicUrl
.replace(/^\d+-/g, '/')
.replace(/:/g, '/')
.replace(/^\//, '')
.split('/')
.slice(-2)
.map((topic) => topic.replace(/-/g, ' '));
const roadmapTitle = roadmapId.replace(/-/g, ' ');
let prompt = `I am reading a guide about "${roadmapTitle}". I am on the topic "${parentTopic}". I want to know more about "${childTopic}". Write me a brief summary for that topic. Content should be in markdown. Behave as if you are the author of the guide.`;
if (!childTopic) {
prompt = `I am reading a guide about "${roadmapTitle}". I am on the topic "${parentTopic}". I want to know more about "${parentTopic}". Write me a brief summary for that topic. Content should be in markdown. Behave as if you are the author of the guide.`;
}
console.log(`Generating '${childTopic || parentTopic}'...`);
return new Promise((resolve, reject) => {
openai
.createChatCompletion({
model: 'gpt-4',
messages: [
{
role: 'user',
content: prompt,
},
],
})
.then((response) => {
const article = response.data.choices[0].message.content;
resolve(article);
})
.catch((err) => {
reject(err);
});
});
}
async function writeFileForGroup(group, topicUrlToPathMapping) {
const topicId = group?.properties?.controlName;
const topicTitle = group?.children?.controls?.control?.find(
(control) => control?.typeID === 'Label'
)?.properties?.text;
const currTopicUrl = topicId?.replace(/^\d+-/g, '/')?.replace(/:/g, '/');
if (!currTopicUrl) {
return;
}
const contentFilePath = topicUrlToPathMapping[currTopicUrl];
if (!contentFilePath) {
console.log(`Missing file for: ${currTopicUrl}`);
return;
}
const currentFileContent = fs.readFileSync(contentFilePath, 'utf8');
const isFileEmpty = currentFileContent.replace(/^#.+/, ``).trim() === '';
if (!isFileEmpty) {
console.log(`Ignoring ${topicId}. Not empty.`);
return;
}
let newFileContent = `# ${topicTitle}`;
if (!OPEN_AI_API_KEY) {
console.log(`Writing ${topicId}..`);
fs.writeFileSync(contentFilePath, newFileContent, 'utf8');
return;
}
const topicContent = await writeTopicContent(currTopicUrl);
newFileContent += `\n\n${topicContent}`;
console.log(`Writing ${topicId}..`);
fs.writeFileSync(contentFilePath, newFileContent, 'utf8');
// console.log(currentFileContent);
// console.log(currTopicUrl);
// console.log(topicTitle);
// console.log(topicUrlToPathMapping[currTopicUrl]);
}
async function run() {
const topicUrlToPathMapping = getFilesInFolder(ROADMAP_CONTENT_DIR);
const roadmapJson = require(path.join(ROADMAP_JSON_DIR, `${roadmapId}.json`));
const groups = roadmapJson?.mockup?.controls?.control?.filter(
(control) =>
control.typeID === '__group__' &&
!control.properties?.controlName?.startsWith('ext_link')
);
if (!OPEN_AI_API_KEY) {
console.log('----------------------------------------');
console.log('OPEN_AI_API_KEY not found. Skipping openai api calls...');
console.log('----------------------------------------');
}
const writePromises = [];
for (let group of groups) {
writePromises.push(writeFileForGroup(group, topicUrlToPathMapping));
}
console.log('Waiting for all files to be written...');
await Promise.all(writePromises);
}
run()
.then(() => {
console.log('Done');
})
.catch((err) => {
console.error(err);
process.exit(1);
});

166
scripts/roadmap-dirs.cjs Normal file
View File

@@ -0,0 +1,166 @@
const fs = require('fs');
const path = require('path');
const CONTENT_DIR = path.join(__dirname, '../content');
// Directory containing the roadmaps
const ROADMAP_CONTENT_DIR = path.join(__dirname, '../src/data/roadmaps');
const roadmapId = process.argv[2];
const allowedRoadmapIds = fs.readdirSync(ROADMAP_CONTENT_DIR);
if (!roadmapId) {
console.error('roadmapId is required');
process.exit(1);
}
if (!allowedRoadmapIds.includes(roadmapId)) {
console.error(`Invalid roadmap key ${roadmapId}`);
console.error(`Allowed keys are ${allowedRoadmapIds.join(', ')}`);
process.exit(1);
}
// Directory holding the roadmap content files
const roadmapDirName = fs
.readdirSync(ROADMAP_CONTENT_DIR)
.find((dirName) => dirName.replace(/\d+-/, '') === roadmapId);
if (!roadmapDirName) {
console.error('Roadmap directory not found');
process.exit(1);
}
const roadmapDirPath = path.join(ROADMAP_CONTENT_DIR, roadmapDirName);
const roadmapContentDirPath = path.join(
ROADMAP_CONTENT_DIR,
roadmapDirName,
'content'
);
// If roadmap content already exists do not proceed as it would override the files
if (fs.existsSync(roadmapContentDirPath)) {
console.error(`Roadmap content already exists @ ${roadmapContentDirPath}`);
process.exit(1);
}
function prepareDirTree(control, dirTree, dirSortOrders) {
// Directories are only created for groups
if (control.typeID !== '__group__') {
return;
}
// e.g. 104-testing-your-apps:other-options
const controlName = control?.properties?.controlName || '';
// e.g. 104
const sortOrder = controlName.match(/^\d+/)?.[0];
// No directory for a group without control name
if (!controlName || !sortOrder) {
return;
}
// e.g. testing-your-apps:other-options
const controlNameWithoutSortOrder = controlName.replace(/^\d+-/, '');
// e.g. ['testing-your-apps', 'other-options']
const dirParts = controlNameWithoutSortOrder.split(':');
// Nest the dir path in the dirTree
let currDirTree = dirTree;
dirParts.forEach((dirPart) => {
currDirTree[dirPart] = currDirTree[dirPart] || {};
currDirTree = currDirTree[dirPart];
});
dirSortOrders[controlNameWithoutSortOrder] = Number(sortOrder);
const childrenControls = control.children.controls.control;
// No more children
if (childrenControls.length) {
childrenControls.forEach((childControl) => {
prepareDirTree(childControl, dirTree, dirSortOrders);
});
}
return { dirTree, dirSortOrders };
}
const roadmap = require(path.join(
__dirname,
`../public/jsons/roadmaps/${roadmapId}`
));
const controls = roadmap.mockup.controls.control;
// Prepare the dir tree that we will be creating and also calculate the sort orders
const dirTree = {};
const dirSortOrders = {};
controls.forEach((control) => {
prepareDirTree(control, dirTree, dirSortOrders);
});
/**
* @param parentDir Parent directory in which directory is to be created
* @param dirTree Nested dir tree to be created
* @param sortOrders Mapping from groupName to sort order
* @param filePaths The mapping from groupName to file path
*/
function createDirTree(parentDir, dirTree, sortOrders, filePaths = {}) {
const childrenDirNames = Object.keys(dirTree);
const hasChildren = childrenDirNames.length !== 0;
// @todo write test for this, yolo for now
const groupName = parentDir
.replace(roadmapContentDirPath, '') // Remove base dir path
.replace(/(^\/)|(\/$)/g, '') // Remove trailing slashes
.replace(/(^\d+?-)/g, '') // Remove sorting information
.replaceAll('/', ':') // Replace slashes with `:`
.replace(/:\d+-/, ':');
const humanizedGroupName = groupName
.split(':')
.pop()
?.replaceAll('-', ' ')
.replace(/^\w/, ($0) => $0.toUpperCase());
const sortOrder = sortOrders[groupName] || '';
// Attach sorting information to dirname
// e.g. /roadmaps/100-frontend/content/internet
// ———> /roadmaps/100-frontend/content/103-internet
if (sortOrder) {
parentDir = parentDir.replace(/(.+?)([^\/]+)?$/, `$1${sortOrder}-$2`);
}
// If no children, create a file for this under the parent directory
if (!hasChildren) {
let fileName = `${parentDir}.md`;
fs.writeFileSync(fileName, `# ${humanizedGroupName}`);
filePaths[groupName || 'home'] = fileName.replace(CONTENT_DIR, '');
return filePaths;
}
// There *are* children, so create the parent as a directory
// and create `index.md` as the content file for this
fs.mkdirSync(parentDir);
let readmeFilePath = path.join(parentDir, 'index.md');
fs.writeFileSync(readmeFilePath, `# ${humanizedGroupName}`);
filePaths[groupName || 'home'] = readmeFilePath.replace(CONTENT_DIR, '');
// For each of the directory names, create a
// directory inside the given directory
childrenDirNames.forEach((dirName) => {
createDirTree(
path.join(parentDir, dirName),
dirTree[dirName],
dirSortOrders,
filePaths
);
});
return filePaths;
}
// Create directories and get back the paths for created directories
createDirTree(roadmapContentDirPath, dirTree, dirSortOrders);
console.log('Created roadmap content directory structure');

44
scripts/roadmap-links.cjs Normal file
View File

@@ -0,0 +1,44 @@
const fs = require('fs');
const path = require('path');
const roadmapId = process.argv[2];
if (!roadmapId) {
console.error('Error: roadmapId is required');
}
const fullPath = path.join(__dirname, `../src/data/roadmaps/${roadmapId}`);
if (!fs.existsSync(fullPath)) {
console.error(`Error: path not found: ${fullPath}!`);
process.exit(1);
}
function readFiles(folderPath) {
const stats = fs.lstatSync(folderPath);
if (stats.isFile()) {
return [folderPath];
}
const folderContent = fs.readdirSync(folderPath);
let files = [];
for (const file of folderContent) {
const filePath = path.join(folderPath, file);
files = [...files, ...readFiles(filePath)];
}
return files;
}
const files = readFiles(fullPath);
let allLinks = [];
files.forEach((file) => {
const fileContent = fs.readFileSync(file, 'utf-8');
const matches = [...fileContent.matchAll(/\[[^\]]+]\((https?:\/\/[^)]+)\)/g)];
allLinks = [...allLinks, ...matches.map((match) => match[1])];
});
allLinks.map((link) => console.log(link));

167
scripts/update-sponsors.cjs Normal file
View File

@@ -0,0 +1,167 @@
const path = require('path');
const fs = require('fs');
const yaml = require('js-yaml');
const apiKey = process.env.SPONSOR_SHEET_API_KEY;
const sheetId = process.env.SPONSOR_SHEET_ID;
if (!apiKey || !sheetId) {
console.error('Missing API key or sheet ID');
process.exit(1);
}
const sheetRange = 'A3:I1001';
const sheetUrl = `https://sheets.googleapis.com/v4/spreadsheets/${sheetId}/values/${sheetRange}?key=${apiKey}`;
function removeAllSponsors(baseContentDir) {
console.log('------------------------');
console.log('Removing sponsors from: ', baseContentDir);
console.log('------------------------');
const dataDirPath = path.join(__dirname, '../src/data');
const contentDirPath = path.join(dataDirPath, baseContentDir);
const contentDir = fs.readdirSync(contentDirPath);
contentDir.forEach((content) => {
console.log('Removing sponsors from: ', content);
const pageFilePath = path.join(contentDirPath, content, `${content}.md`);
const pageFileContent = fs.readFileSync(pageFilePath, 'utf8');
const frontMatterRegex = /---\n([\s\S]*?)\n---/;
const existingFrontmatter = pageFileContent.match(frontMatterRegex)[1];
const contentWithoutFrontmatter = pageFileContent
.replace(frontMatterRegex, ``)
.trim();
let frontmatterObj = yaml.load(existingFrontmatter);
delete frontmatterObj.sponsors;
const newFrontmatter = yaml.dump(frontmatterObj, {
lineWidth: 10000,
forceQuotes: true,
quotingType: "'",
});
const newContent = `---\n${newFrontmatter}---\n${contentWithoutFrontmatter}`;
fs.writeFileSync(pageFilePath, newContent, 'utf8');
});
}
function addPageSponsor({
pageUrl,
company,
redirectUrl,
imageUrl,
adTitle,
adDescription,
}) {
const urlPart = pageUrl
.replace('https://roadmap.sh/', '')
.replace(/\?.+?$/, '');
const parentDir = urlPart.startsWith('best-practices/')
? 'best-practices'
: 'roadmaps';
const pageId = urlPart.replace(`${parentDir}/`, '');
const pageFilePath = path.join(
__dirname,
`../src/data/${parentDir}`,
`${pageId}/${pageId}.md`
);
if (!fs.existsSync(pageFilePath)) {
console.error(`Page file not found: ${pageFilePath}`);
process.exit(1);
}
console.log(`Updating page: ${urlPart}`);
const pageFileContent = fs.readFileSync(pageFilePath, 'utf8');
const frontMatterRegex = /---\n([\s\S]*?)\n---/;
const existingFrontmatter = pageFileContent.match(frontMatterRegex)[1];
const contentWithoutFrontmatter = pageFileContent
.replace(frontMatterRegex, ``)
.trim();
let frontmatterObj = yaml.load(existingFrontmatter);
const sponsors = frontmatterObj.sponsors || [];
const frontmatterValues = Object.entries(frontmatterObj);
const roadmapLabel = frontmatterObj.briefTitle;
sponsors.push({
url: redirectUrl,
title: adTitle,
imageUrl,
description: adDescription,
page: roadmapLabel,
company,
});
// Insert sponsor data at 10 index i.e. after
// roadmap dimensions in the frontmatter
frontmatterValues.splice(10, 0, ['sponsors', sponsors]);
frontmatterObj = Object.fromEntries(frontmatterValues);
const newFrontmatter = yaml.dump(frontmatterObj, {
lineWidth: 10000,
forceQuotes: true,
quotingType: "'",
});
const newContent = `---\n${newFrontmatter}---\n\n${contentWithoutFrontmatter}`;
fs.writeFileSync(pageFilePath, newContent, 'utf8');
}
// Remove sponsors from all roadmaps
removeAllSponsors('roadmaps');
removeAllSponsors('best-practices');
console.log('------------------------');
console.log('Adding sponsors');
console.log('------------------------');
fetch(sheetUrl)
.then((res) => res.json())
.then((rawData) => {
const rows = rawData.values;
rows.map((row) => {
// prettier-ignore
const [
pageUrl,
company,
redirectUrl,
imageUrl,
adTitle,
adDescription,
startDate,
endDate,
isActive,
] = row;
const isConfiguredActive = isActive?.toLowerCase() === 'yes';
const currentDate = new Date();
const isDateInRange =
currentDate >= new Date(startDate) && currentDate <= new Date(endDate);
if (!isConfiguredActive || !isDateInRange) {
return;
}
addPageSponsor({
pageUrl,
company,
redirectUrl,
imageUrl,
adTitle,
adDescription,
startDate,
endDate,
isActive,
});
});
});