Add new GitHub Action for optimizing image sizes (#77)

Co-authored-by: github-actions <41898282+github-actions[bot]@users.noreply.github.com>
This commit is contained in:
Jonah Lawrence 2022-10-07 17:49:58 -06:00 committed by GitHub
parent 960814ee23
commit abce5a353c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 107 additions and 0 deletions

56
.github/scripts/tinify_images.py vendored Normal file
View File

@ -0,0 +1,56 @@
import os
from argparse import ArgumentParser
from typing import List
import tinify
from dotenv import load_dotenv
from tqdm import tqdm
def filter_files(files: List[str], extensions: List[str]):
"""Filters files by extension"""
return [f for f in files if f.split(".")[-1] in extensions]
def tinify_files(dirpath: str, files: List[str]):
"""Tinifies files in the a given directory"""
for filename in tqdm(files):
with open(f"{dirpath}/{filename}", "rb") as source:
tinify.from_buffer(source.read()).to_file(f"{dirpath}/{filename}")
if __name__ == "__main__":
load_dotenv()
parser = ArgumentParser(description="Use TinyPNG to optimize file sizes.")
parser.add_argument(
"--dir",
"-d",
type=str,
default=".",
help="Directory to optimize wallpapers in. Defaults to current directory.",
)
parser.add_argument(
"--files",
"-ff",
type=str,
default="",
help="Comma-separated list of files to optimize. Defaults to all files in the directory.",
)
parser.add_argument(
"--key",
"-k",
type=str,
default=os.getenv("TINIFY_API_KEY"),
help="TinyPNG API key. Defaults to the TINYPNG_KEY environment variable.",
)
args = parser.parse_args()
dirpath = os.path.abspath(args.dir)
files = (
[os.path.basename(f) for f in args.files.split(",")] if args.files else os.listdir(args.dir)
)
tinify.key = args.key
files = filter_files(files, ["png", "jpg", "jpeg"])
tinify_files(dirpath, files)

50
.github/workflows/tinify-images.yml vendored Normal file
View File

@ -0,0 +1,50 @@
name: "Optimize images with TinyPNG"
on:
pull_request:
branches:
- main
paths:
- "**.jpg"
- "**.jpeg"
- "**.png"
- "**.webp"
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10"]
steps:
- uses: actions/checkout@v3
with:
repository: ${{ github.event.pull_request.head.repo.full_name }}
ref: ${{ github.event.pull_request.head.ref }}
- id: changed
uses: jitterbit/get-changed-files@v1
with:
format: "csv"
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: pip install tinify tqdm python-dotenv
- name: Tinify Images
run: |
python .github/scripts/tinify_images.py \
-d images \
-ff ${{ steps.changed.outputs.added_modified }} \
-k ${{ secrets.TINIFY_API_KEY }} \
|| exit 1
- name: Commit changes
uses: EndBug/add-and-commit@v9
with:
default_author: github_actions
message: "Optimize images with TinyPNG"

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
.vscode
.vercel
.env