Skip to content

Generate File Checksums #1

Generate File Checksums

Generate File Checksums #1

# نام ورک‌فلو که در صفحه Actions گیت‌هاب نمایش داده می‌شود
name: Generate File Checksums
# تعریف تریگرها (triggers) برای اجرای ورک‌فلو
on:
# اجرا در زمان push به شاخه main، فقط اگر فایل‌ها در مسیر مشخص شده تغییر کنند
push:
branches:
- main
paths:
- 'main/files/**'
- '!.github/**' # از اجرای ورک‌فلو به خاطر تغییرات خودش جلوگیری می‌کند
# اجازه می‌دهد که ورک‌فلو را به صورت دستی از تب Actions اجرا کنید
workflow_dispatch:
jobs:
generate-checksums:
# استفاده از آخرین نسخه اوبونتو برای اجرای جاب
runs-on: ubuntu-latest
# تعریف مراحل اجرای جاب
steps:
# مرحله ۱: دریافت کد ریپازیتوری
- name: Checkout repository
uses: actions/checkout@v4
# مرحله ۲: اجرای اسکریپت پایتون برای تولید Checksums
- name: Generate and Save Checksums
id: generate_checksums
run: |
# مسیر پوشه‌ای که فایل‌های شما در آن قرار دارد
TARGET_DIR="main/files"
# نام فایل خروجی
OUTPUT_FILE="checksums.sha256"
# استفاده از Heredoc برای نوشتن اسکریپت پایتون در یک فایل موقت
cat << 'EOF' > generate_checksums.py
import os
import hashlib
import sys
def create_checksums(root_dir, output_filename):
checksums = {}
output_filepath = os.path.join(root_dir, output_filename)
for dirpath, _, filenames in os.walk(root_dir):
for filename in filenames:
file_path = os.path.join(dirpath, filename)
# از پردازش خود فایل checksum و فایل‌های گیت جلوگیری شود
if file_path == output_filepath or ".git" in file_path:
continue
sha256_hash = hashlib.sha256()
with open(file_path, "rb") as f:
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
relative_path = os.path.relpath(file_path, root_dir)
checksums[relative_path] = sha256_hash.hexdigest()
# نوشتن نتایج در فایل خروجی
with open(output_filepath, "w", encoding="utf-8") as f:
for path, digest in sorted(checksums.items()):
# استفاده از * برای سازگاری با ابزار sha256sum
f.write(f"{digest} *{path.replace(os.sep, '/')}\n")
print(f"Checksums saved to {output_filepath}")
if __name__ == "__main__":
target_directory = sys.argv[1]
output_file_name = sys.argv[2]
if os.path.isdir(target_directory):
create_checksums(target_directory, output_file_name)
else:
print(f"Error: Directory '{target_directory}' not found.")
sys.exit(1)
EOF
# اجرای اسکریپت پایتون
python generate_checksums.py $TARGET_DIR $OUTPUT_FILE
# مرحله ۳: کامیت و پوش کردن فایل checksums.sha256 در صورت تغییر
- name: Commit and push if changed
uses: stefanzweifel/git-auto-commit-action@v5
with:
# پیام کامیت
commit_message: "ci: Update file checksums"
# فایل‌هایی که باید کامیت شوند
file_pattern: main/files/checksums.sha256
# اطلاعات نویسنده کامیت
commit_user_name: "GitHub Actions Bot"
commit_user_email: "github-actions[bot]@users.noreply.github.com"