Skip to content

Commit

Permalink
Merge branch 'Anduin2017:master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
it985 authored Jun 17, 2024
2 parents a2928bf + 38c14ee commit 6661bb0
Show file tree
Hide file tree
Showing 18 changed files with 823 additions and 930 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
3 changes: 0 additions & 3 deletions .github/templates/mkdocs_template.yml
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,7 @@ plugins:
copyright: The Unlicense
cover_title: How To Cook
cover_subtitle: 程序员做饭指南
back_cover: true
output_path: document.pdf
show_anchors: true
toc_level: 4
- minify:
minify_html: true

Expand Down
15 changes: 13 additions & 2 deletions .github/templates/readme_template.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,25 @@
[![GitHub contributors](https://img.shields.io/github/contributors/Anduin2017/HowToCook)](https://github.com/Anduin2017/HowToCook/graphs/contributors)
[![npm](https://img.shields.io/npm/v/how-to-cook)](https://www.npmjs.com/package/how-to-cook)
![Man hours](https://manhours.aiursoft.cn/r/github.com/anduin2017/howtocook.svg)
[![Docker](https://img.shields.io/badge/docker-latest-blue?logo=docker)](https://hub.docker.com/r/anduin2019/howtocook)
[![Docker](https://img.shields.io/badge/docker-latest-blue?logo=docker)](https://github.com/Anduin2017/HowToCook/pkgs/container/how-to-cook)

最近在家隔离,出不了门。只能宅在家做饭了。作为程序员,我偶尔在网上找找菜谱和做法。但是这些菜谱往往写法千奇百怪,经常中间莫名出来一些材料。对于习惯了形式语言的程序员来说极其不友好。

所以,我计划自己搜寻菜谱并结合实际做菜的经验,准备用更清晰精准的描述来整理常见菜的做法,以方便程序员在家做饭。

同样,我希望它是一个由社区驱动和维护的开源项目,使更多人能够一起做一个有趣的仓库。所以非常欢迎大家贡献它~

## 本地部署

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

```bash
docker pull ghcr.io/anduin2017/how-to-cook:latest
docker run -d -p 5000:5000 ghcr.io/anduin2017/how-to-cook:latest
```

如需下载 PDF 版本,可以在浏览器中访问 [/document.pdf](https://cook.aiursoft.cn/document.pdf)

## 如何贡献

针对发现的问题,直接修改并提交 Pull request 即可。
Expand All @@ -25,7 +36,7 @@

## 菜谱

### 家常菜
{{index_stars}}

{{main}}

Expand Down
28 changes: 10 additions & 18 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
name: build
name: Continuous Deployment

on:
push:
branches: [ master ]
workflow_dispatch:

jobs:
Rebuild-everything:
build-readme-file:
runs-on: ubuntu-latest
steps:
# Checkout, install tools..
Expand All @@ -17,10 +16,8 @@ jobs:
with:
node-version: '16'
cache: 'npm'
# Generate Readme, mkdocs.
- run: node ./.github/readme-generate.js
# Lint issues first. (Without node_modules)
- run: npm install
- run: npm run build
- run: npm run lint
# Save files.
- uses: stefanzweifel/git-auto-commit-action@v4
Expand All @@ -31,18 +28,13 @@ jobs:
commit_user_name: github-actions[bot]
commit_user_email: github-actions[bot]@users.noreply.github.com
commit_author: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
# Build docs

# Deprecated. Now use docker.
# - run: echo cook.aiurs.co > CNAME
# - run: mkdir docs && echo cook.aiurs.co > docs/CNAME
# - uses: mhausenblas/mkdocs-deploy-gh-pages@master
# env:
# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# CUSTOM_DOMAIN: cook.aiurs.co
# CONFIG_FILE: mkdocs.yml
# REQUIREMENTS: requirements.txt

build-docker-image:
needs: build-readme-file
runs-on: ubuntu-latest
steps:
# Checkout, install tools..
- uses: actions/checkout@v2
# Use docker to build current directory ./Dockfile
- name: Login to GitHub Container Registry
uses: docker/login-action@v1
Expand All @@ -51,7 +43,7 @@ jobs:
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

- name: Build the hello-world Docker image
- name: Build and push the Docker image
run: |
docker build . --tag ghcr.io/anduin2017/how-to-cook:latest
docker push ghcr.io/anduin2017/how-to-cook:latest
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ node_modules/
site/

.idea
*.iml
*.iml
mkdocs.yml
Loading

0 comments on commit 6661bb0

Please sign in to comment.