🐛 Fix format #8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name: Minify JS/CSS on Change | |
on: | |
workflow_dispatch: | |
push: | |
branches: | |
- main | |
paths: | |
- 'static/js/**' | |
- 'static/css/**' | |
jobs: | |
minify: | |
runs-on: ubuntu-latest | |
steps: | |
- name: Checkout code | |
uses: actions/checkout@v3 | |
with: | |
fetch-depth: 0 # 获取完整历史记录 | |
# 使用actions/cache来保存和读取上次成功运行时的commit SHA | |
- name: Get previous commit SHA | |
id: previous-sha | |
uses: actions/cache@v3 | |
with: | |
path: /tmp/previous-sha | |
key: previous-sha-${{ github.ref }} | |
restore-keys: | | |
previous-sha-${{ github.ref }} | |
- name: Set current commit SHA | |
run: | | |
if [ -f /tmp/previous-sha ]; then | |
PREV_SHA=$(cat /tmp/previous-sha) | |
else | |
# 首次运行时使用初始提交作为比较基准 | |
PREV_SHA=$(git rev-list --max-parents=0 HEAD) # 首次运行时使用初始提交 | |
fi | |
echo "PREV_SHA=$PREV_SHA" >> $GITHUB_ENV | |
echo "${{ github.sha }}" > /tmp/previous-sha | |
- name: Set up Node.js | |
uses: actions/setup-node@v3 | |
with: | |
node-version: 18 | |
- name: Install dependencies | |
run: npm install terser clean-css-cli -g | |
# 使用git diff $PREV_SHA $CURRENT_SHA来获取两个提交之间的所有变更 | |
- name: Get changed files | |
id: changed-files | |
run: | | |
echo "CHANGED_FILES=$(git diff --name-only $PREV_SHA ${{ github.sha }} | grep -E 'static/(js|css)/.*\.(js|css)$' | tr '\n' ' ')" >> $GITHUB_OUTPUT | |
- name: Minify files | |
if: steps.changed-files.outputs.CHANGED_FILES != '' | |
run: | | |
export PREFIX=static/production | |
for file in ${{ steps.changed-files.outputs.CHANGED_FILES }}; do | |
[ ! -f $file ] && echo Skipped $file as it does not exist && continue | |
echo Processing $file... | |
if [[ $file == *.js ]]; then | |
output_file="$PREFIX/${file#static/}" | |
[ ! -d $(dirname $output_file) ] && mkdir -p $(dirname $output_file) | |
terser $file -o $output_file --compress --mangle | |
elif [[ $file == *.css ]]; then | |
output_file="$PREFIX/${file#static/}" | |
[ ! -d $(dirname $output_file) ] && mkdir -p $(dirname $output_file) | |
cleancss -o $output_file $file | |
fi | |
done | |
- name: Commit and push changes | |
if: steps.changed-files.outputs.CHANGED_FILES != '' | |
run: | | |
git config --global user.name "GitHub Actions" | |
git config --global user.email "actions@github.com" | |
git add . | |
git commit -m "Auto minify changed files [skip ci]" | |
git push | |
# 在每次成功运行后保存当前的commit SHA | |
- name: Save current SHA | |
uses: actions/cache@v3 | |
with: | |
path: /tmp/previous-sha | |
key: previous-sha-${{ github.ref }} |