Skip to content

Commit

Permalink
[bot] AutoMerging: merge all upstream's changes:
Browse files Browse the repository at this point in the history
* https://github.com/Anduin2017/HowToCook:
  [ci skip] Automatic file changes/fix
  Update dish difficulty titles to use Chinese characters
  [ci skip] Automatic file changes/fix
  Update readme-generate.js (Anduin2017#1329)
  • Loading branch information
github-actions[bot] committed Jun 6, 2024
2 parents 6914073 + cd7259e commit 116339b
Show file tree
Hide file tree
Showing 8 changed files with 683 additions and 310 deletions.
116 changes: 99 additions & 17 deletions .github/readme-generate.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
const { readdir, writeFile, stat } = require('fs/promises');
const fs = require('fs').promises;
const path = require('path');

const README_PATH = './README.md';

const MKDOCS_PATH = 'mkdocs.yml';
const dishesFolder = 'dishes';
const starsystemFolder = 'starsystem';

const ignorePaths = ['.git', 'README.md', 'node_modules', 'CONTRIBUTING.md', '.github'];

Expand Down Expand Up @@ -60,12 +62,77 @@ const categories = {
},
};

async function countStars(filename) {
const data = await fs.readFile(filename, 'utf-8');
let stars = 0;
const lines = data.split('\n');
lines.forEach(line => {
stars += (line.match(//g) || []).length;
});
return stars;
}

async function organizeByStars(dishesFolder, starsystemFolder) {
const dishes = {};

async function processFolder(folderPath) {
const files = await readdir(folderPath);
for (const filename of files) {
const filepath = path.join(folderPath, filename);
const fileStat = await stat(filepath);
if (fileStat.isFile() && filename.endsWith('.md')) {
const stars = await countStars(filepath);
dishes[filepath] = stars;
} else if (fileStat.isDirectory()) {
await processFolder(filepath);
}
}
}

const dishesFolderAbs = path.resolve(dishesFolder);
const starsystemFolderAbs = path.resolve(starsystemFolder);

if (!await fs.access(starsystemFolderAbs).then(() => true).catch(() => false)) {
await fs.mkdir(starsystemFolderAbs, { recursive: true });
}

if (!await fs.access(dishesFolderAbs).then(() => true).catch(() => false)) {
console.log(`Directory not found: ${dishesFolderAbs}, creating directory...`);
await fs.mkdir(dishesFolderAbs, { recursive: true });
}

await processFolder(dishesFolderAbs);

const starRatings = Array.from(new Set(Object.values(dishes))).sort((a, b) => a - b);
const navigationLinks = [];

for (const stars of starRatings) {
const starsFile = path.join(starsystemFolderAbs, `${stars}Star.md`);
const content = [`# ${stars} 星难度菜品`, ''];
for (const [filepath, starCount] of Object.entries(dishes)) {
if (starCount === stars) {
const relativePath = path.relative(starsystemFolderAbs, filepath).replace(/\\/g, '/');
content.push(`* [${path.basename(filepath, '.md')}](./${relativePath})`);
}
}
await writeFile(starsFile, content.join('\n'), 'utf-8');
navigationLinks.push(`- [${stars} 星难度](${path.relative(path.dirname(README_PATH), starsFile).replace(/\\/g, '/')})`);
}

return navigationLinks;
}

async function main() {
try {
let README_BEFORE = (README_MAIN = README_AFTER = '');
let MKDOCS_BEFORE = (MKDOCS_MAIN = MKDOCS_AFTER = '');
let README_BEFORE = '', README_MAIN = '', README_AFTER = '';
let MKDOCS_BEFORE = '', MKDOCS_MAIN = '', MKDOCS_AFTER = '';
const markdownObj = await getAllMarkdown('.');

// Debug logging to understand the structure of markdownObj
console.log("Markdown Object Structure:", JSON.stringify(markdownObj, null, 2));

for (const markdown of markdownObj) {
console.log("Processing markdown:", markdown);
if (markdown.path.includes('tips/advanced')) {
README_AFTER += inlineReadmeTemplate(markdown.file, markdown.path);
MKDOCS_AFTER += inlineMkdocsTemplate(markdown.file, markdown.path);
Expand Down Expand Up @@ -94,48 +161,63 @@ async function main() {
MKDOCS_MAIN += categoryMkdocsTemplate(category.title, category.mkdocs);
}

const MKDOCS_TEMPLATE = await fs.readFile("./.github/templates/mkdocs_template.yml", "utf-8");
const README_TEMPLATE = await fs.readFile("./.github/templates/readme_template.md", "utf-8");
let MKDOCS_TEMPLATE;
let README_TEMPLATE;

try {
MKDOCS_TEMPLATE = await fs.readFile("./.github/templates/mkdocs_template.yml", "utf-8");
} catch (error) {
MKDOCS_TEMPLATE = `site_name: My Docs\nnav:\n {{main}}\n`;
console.warn("mkdocs_template.yml not found, using default template");
}

try {
README_TEMPLATE = await fs.readFile("./.github/templates/readme_template.md", "utf-8");
} catch (error) {
README_TEMPLATE = `# My Project\n\n{{before}}\n\n{{main}}\n\n{{after}}`;
console.warn("readme_template.md not found, using default template");
}

const navigationLinks = await organizeByStars(dishesFolder, starsystemFolder);
// Debug logging to ensure navigationLinks is defined and contains data
console.log("难度索引", navigationLinks);
const navigationSection = `\n### 按难度索引\n\n${navigationLinks.join('\n')}`;

await writeFile(
README_PATH,
README_TEMPLATE
.replace('{{before}}', README_BEFORE.trim())
.replace('{{index_stars}}', navigationSection.trim())
.replace('{{main}}', README_MAIN.trim())
.replace('{{after}}', README_AFTER.trim()),
);


await writeFile(
MKDOCS_PATH,
MKDOCS_TEMPLATE
.replace('{{before}}', MKDOCS_BEFORE)
.replace('{{main}}', MKDOCS_MAIN)
.replace('{{after}}', MKDOCS_AFTER),
);

// Organize files by star rating
//await organizeByStars(dishesFolder, starsystemFolder);
} catch (error) {
console.error(error);
}
}

async function getAllMarkdown(path) {
async function getAllMarkdown(dir) {
const paths = [];
const files = await readdir(path);
// chinese alphabetic order
const files = await readdir(dir);
files.sort((a, b) => a.localeCompare(b, 'zh-CN'));

// mtime order
// files.sort(async (a, b) => {
// const aStat = await stat(`${path}/${a}`);
// const bStat = await stat(`${path}/${b}`);
// return aStat.mtime - bStat.mtime;
// });
for (const file of files) {
const filePath = `${path}/${file}`;
const filePath = path.join(dir, file);
if (ignorePaths.includes(file)) continue;
const fileStat = await stat(filePath);
if (fileStat.isFile() && file.endsWith('.md')) {
paths.push({ path, file });
paths.push({ path: dir, file });
} else if (fileStat.isDirectory()) {
const subFiles = await getAllMarkdown(filePath);
paths.push(...subFiles);
Expand Down
4 changes: 2 additions & 2 deletions .github/templates/readme_template.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

## 本地部署

如果需要在本地部署菜谱 Web 服务,可以在安装 Docker 后运行下面命令:
如果需要在本地部署菜谱 Web 服务,可以在安装 Docker 后运行下面命令:

```bash
docker pull ghcr.io/anduin2017/how-to-cook:latest
Expand All @@ -36,7 +36,7 @@ docker run -d -p 5000:5000 ghcr.io/anduin2017/how-to-cook:latest

## 菜谱

### 家常菜
{{index_stars}}

{{main}}

Expand Down
Loading

0 comments on commit 116339b

Please sign in to comment.