Skip to content

Commit

Permalink
perf: hugo new script
Browse files Browse the repository at this point in the history
  • Loading branch information
eallion committed Aug 29, 2024
1 parent 0665ece commit c5bfd59
Show file tree
Hide file tree
Showing 6 changed files with 144 additions and 35 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
CAIYUN_TOKEN=your_token_here
1 change: 1 addition & 0 deletions .env.local
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
CAIYUN_TOKEN=bd3j83c221vr1i5401dj
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ ossconfig
oss.config
.oss.config

.env.local

node_modules

autocorrect
Expand Down
70 changes: 42 additions & 28 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,25 +87,25 @@ git submodule add https://github.com/eallion/blowfish.git themes/DoIt
```bash
git submodule update --init --recursive

# bun recursive
# pnpm run recursive
```

如果上游主题有更新,更新 [主题](https://github.com/eallion/blowfish.git)[mastodon-embed-timeline](https://github.com/eallion/mastodon-embed-timeline.git)

```diff
- git submodule update --remote --merge
+ bun theme
+ pnpm run theme
```

Blowfish 编译 TailwindCSS 的 main.css ,位于 [assets/css/compiled/main.css](https://github.com/eallion/eallion.com/blob/main/assets/css/compiled/main.css)

```bash
# cd theme/blowfish
# npm install
# ../..
# pnpm install
# cd ../..

# bun dev
bun run build
# pnpm run dev
pnpm run build
```

```bash
Expand Down Expand Up @@ -136,20 +136,20 @@ https://github.com/eallion/eallion.com/blob/main/layouts/_default/mastodon.html
https://github.com/eallion/eallion.com/blob/main/data/neodb/movie.json
```

### 🧑‍💻 bun 命令

- `bun dev` 启动 TailwindCSS 监听
- `bun hugo` 构建 Hugo,一般不用,都是交给 CI/CD 构建
- `bun new` 创建新文章,直接输入文章标题,生成到 example 目录
- `bun prepare` Git Commit Husky 勾子,目前用于提交时更新 Cloudflare Pages Wrangler 的 `HUGO_VERSION`
- `bun preview` 启动 Hugo 服务器,即预览线上生成环境,文档内容为 `content` 目录
- `bun recursive` 递归更新 Submodule 子项目,一般第一次克隆本项目时使用
- `bun run build` 构建 Blowfish 的 TailwindCSS `assets/css/compiled/main.css`
- `bun server` 启动 Hugo 服务器,文档内容为 `example` 目录
- `bun shiki` 生成 Shiki 语法高亮,目前已取消
- `bun theme` 更新 Submodule 子项目
- `bun vercel` 构建适用于 Vercel 平台的 Hugo,在 Vercel 平台使用
- `bun winnat` 谨慎使用,用于 Windows 重置 Winnat,解决绑定 1313 端口冲突
### 🧑‍💻 pnpm 命令

- `pnpm run dev` 启动 TailwindCSS 监听
- `pnpm run hugo` 构建 Hugo,一般不用,都是交给 CI/CD 构建
- `pnpm run new` 创建新文章,直接输入文章标题,生成到 example 目录
- `pnpm run prepare` Git Commit Husky 勾子,目前用于提交时更新 Cloudflare Pages Wrangler 的 `HUGO_VERSION`
- `pnpm run preview` 启动 Hugo 服务器,即预览线上生成环境,文档内容为 `content` 目录
- `pnpm run recursive` 递归更新 Submodule 子项目,一般第一次克隆本项目时使用
- `pnpm run build` 构建 Blowfish 的 TailwindCSS `assets/css/compiled/main.css`
- `pnpm run server` 启动 Hugo 服务器,文档内容为 `example` 目录
- `pnpm run shiki` 生成 Shiki 语法高亮,目前已取消
- `pnpm run theme` 更新 Submodule 子项目
- `pnpm run vercel` 构建适用于 Vercel 平台的 Hugo,在 Vercel 平台使用
- `pnpm run winnat` 谨慎使用,用于 Windows 重置 Winnat,解决绑定 1313 端口冲突

### 🔊 嘀咕页面

Expand All @@ -167,13 +167,27 @@ git submodule add https://github.com/eallion/mastodon-embed-timeline.git assets/
##### 1. **生成新文章**

通过 Hugo 命令 New 一篇新文章模板:
现改为 npm (bun) 命令:
现改为 pnpm 命令:

```diff
- hugo new posts/daily/new_title.md
+ bun new
+ pnpm run new

# node scripts/post_title_prompt.js && bash scripts/format_filename.sh
# node scripts/new_post.js
```

如果需要用上 [彩云小译](https://docs.caiyunapp.com/lingocloud-api/) 自动翻译标题为 slug,需要 Token。

1. 导入 Token

```bash
export CAIYUN_TOKEN=3975l6lr5pcbvidl6jl2
```

2. 复制 .env.example 为 .env.local

```txt
CAIYUN_TOKEN=3975l6lr5pcbvidl6jl2
```

##### 2. **缩略图**
Expand All @@ -190,8 +204,8 @@ Icon 可以从网上下载,放到 `assets/icons` 目录下,格式为 `.svg`

##### 5. **编辑文章**

通过 [Typora](https://typora.io/)[VSCode](https://code.visualstudio.com/) 编辑第一步 `bun new` 出来的文章。
这篇文章在 `example/blog/{title}` 目录下,文件名为:`{title}/index.md``{title}``bun new` 输入的文字。
通过 [Typora](https://typora.io/)[VSCode](https://code.visualstudio.com/) 编辑第一步 `pnpm run new` 出来的文章。
这篇文章在 `example/blog/{title}` 目录下,文件名为:`{title}/index.md``{title}``pnpm run new` 输入的文字。
编辑好之后需要把这个文件复制到 `content/blog` 相应的目录中,再 `git push`
缩略图(OG:Image)放在文章同目录下,命名为:`feature*.png`

Expand Down Expand Up @@ -247,10 +261,10 @@ git push

```diff
- ./server.sh
+ bun server
+ pnpm run server

# 查看博客实际效果 👇
# bun preview
# pnpm run preview

# git submodule update --remote --merge && \
# start http://192.168.0.5:1313 && \
Expand Down Expand Up @@ -298,7 +312,7 @@ git push

```diff
- hugo --cleanDestinationDir --forceSyncStatic --gc --ignoreCache --minify --enableGitInfo
+ bun hugo
+ pnpm run hugo
```

- `--cleanDestinationDir` 构建前先清理目标目录,即 public
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"@shikijs/rehype": "^1.13.0",
"@types/node": "^20.14.15",
"axios": "^1.7.4",
"dotenv": "^16.4.5",
"fs": "0.0.1-security",
"husky": "^9.1.4",
"rehype-cli": "^12.0.0",
Expand Down
104 changes: 97 additions & 7 deletions scripts/new_post.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,104 @@
const { spawn, execSync } = require('child_process');
const fs = require('fs');
var today = new Date().toJSON().slice(0,10);
const path = require('path');
const readline = require('readline');
const axios = require('axios');
require('dotenv').config({ path: '.env.local' });

const exec = commands => {
execSync(commands, { stdio: 'inherit', shell: true });
};

const spawnProcess = commands => {
spawn(commands, { stdio: 'inherit', shell: true });
};

const readline = require('readline');

const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});

rl.question('Input your post title (CJK Available): ', title => {
const filteredTitle = title.trim().replace(/ /g, '-');
console.log(`Your new draft is located in \"example/blog/${filteredTitle}\"`);
exec(`hugo new --kind post --contentDir example --quiet blog/${filteredTitle}/${filteredTitle}.md `);
rl.question('Input your post title (CJK Available): ', async title => {
const translateText = async (source, direction) => {
const url = "http://api.interpreter.caiyunai.com/v1/translator";
const token = process.env.CAIYUN_TOKEN;

if (!token) {
console.warn('No token provided for translation. Skipping translation.');
return { translated: false, text: source };
}

const payload = {
source: source,
trans_type: direction,
request_id: "demo",
detect: true,
};

const headers = {
"content-type": "application/json",
"x-authorization": "token " + token,
};

try {
const response = await axios.post(url, payload, { headers: headers });
return { translated: true, text: response.data.target };
} catch (error) {
console.error('Translation failed:', error.message);
return { translated: false, text: source };
}
};

const parseFrontMatter = (content) => {
const lines = content.split('\n');
const frontMatter = {};
let inFrontMatter = false;

lines.forEach(line => {
if (line.trim() === '---') {
inFrontMatter = !inFrontMatter;
} else if (inFrontMatter) {
const [key, value] = line.split(':').map(part => part.trim());
if (key && value) {
frontMatter[key] = value;
}
}
});

return frontMatter;
};

const getOldestPost = (dir, excludeDirs) => {
const directories = fs.readdirSync(dir, { withFileTypes: true })
.filter(dirent => dirent.isDirectory() && !excludeDirs.includes(dirent.name))
.map(dirent => dirent.name);

let oldestDate = new Date();
let oldestDir = null;

directories.forEach(directory => {
const filePath = path.join(dir, directory, 'index.md');
if (fs.existsSync(filePath)) {
const content = fs.readFileSync(filePath, 'utf8');
const frontMatter = parseFrontMatter(content);
if (frontMatter.date) {
const date = new Date(frontMatter.date);
if (date < oldestDate) {
oldestDate = date;
oldestDir = directory;
}
}
}
});

return oldestDir;
};

const translationResult = await translateText(title, "auto2en");
const translatedTitle = translationResult.text;
const filteredTitle = translationResult.translated ? translatedTitle.trim().replace(/[^a-zA-Z0-9]/g, '-').toLowerCase() : translatedTitle;
console.log(`Your new draft is located in "example/blog/${filteredTitle}"`);
exec(`hugo new --kind post --contentDir example --quiet blog/${filteredTitle}/${filteredTitle}.md`);

// 创建目录和文件
const targetDir = `example/blog/${filteredTitle}`;
Expand All @@ -36,5 +116,15 @@ rl.question('Input your post title (CJK Available): ', title => {
fs.renameSync(oldFile, newFile);
}

// 删除最老的一篇文章所在的目录
const blogDir = 'example/blog';
const excludeDirs = ['en', 'doudou', 'markdown-syntax']; // 添加更多要排除的目录
const oldestPostDir = getOldestPost(blogDir, excludeDirs);
if (oldestPostDir && !excludeDirs.includes(oldestPostDir)) {
const oldestDirPath = path.join(blogDir, oldestPostDir);
fs.rmSync(oldestDirPath, { recursive: true, force: true });
console.log(`Deleted oldest post directory: ${oldestDirPath}`);
}

rl.close();
});

0 comments on commit c5bfd59

Please sign in to comment.