Cleanup Old News Folders #36
This file contains 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: Cleanup Old News Folders | |
on: | |
schedule: | |
- cron: '0 0 * * *' | |
workflow_dispatch: | |
jobs: | |
cleanup: | |
runs-on: ubuntu-latest | |
steps: | |
- name: Set up Python | |
uses: actions/setup-python@v4 | |
with: | |
python-version: '3.x' | |
- name: Install PyGitHub | |
run: | | |
python -m pip install --upgrade pip | |
pip install PyGitHub | |
- name: Remove outdated folders via GitHub API | |
env: | |
GITHUB_TOKEN: ${{ secrets.GIT_TOKEN }} | |
run: | | |
python - <<EOF | |
import os | |
from datetime import datetime, timedelta, timezone | |
from github import Github | |
# Initialize GitHub client | |
token = os.getenv("GITHUB_TOKEN") | |
repo_name = "Damantha126/Helakuru-Esana-API" | |
g = Github(token) | |
repo = g.get_repo(repo_name) | |
# Define the cutoff time for outdated folders | |
cutoff_time = datetime.now(timezone.utc) - timedelta(days=7) # Use timezone-aware datetime | |
# List contents of the News directory | |
contents = repo.get_contents("News") | |
for content in contents: | |
if content.type == "dir": | |
# Get last commit date of the folder | |
commits = repo.get_commits(path=content.path) | |
if commits.totalCount > 0: | |
last_modified = commits[0].commit.author.date # This is already timezone-aware | |
# Check if folder is outdated | |
if last_modified < cutoff_time: | |
print(f"Deleting outdated folder: {content.path}") | |
# GitHub API requires a file to delete | |
files = repo.get_contents(content.path) | |
for file in files: | |
repo.delete_file(file.path, f"Delete outdated file {file.path}", file.sha) | |
print(f"Delete outdated file {file.path}") | |
print(f"Deleted folder: {content.path}") | |
EOF |