homebrew-fonts/remove-font.py
Matt Troutman 49fca2b3b9
no message
2025-04-05 17:40:26 -05:00

173 lines
No EOL
6.4 KiB
Python
Executable file

#!/usr/bin/env python3
import os
import sys
import json
import subprocess
import requests
import re
from pathlib import Path
from dotenv import load_dotenv
from urllib.parse import urlparse
# Load environment variables from .env file
load_dotenv()
def get_gitea_credentials():
"""Get Gitea credentials from environment variables."""
gitea_url = os.getenv("GITEA_URL")
gitea_username = os.getenv("GITEA_USERNAME")
gitea_token = os.getenv("GITEA_API_TOKEN")
if not all([gitea_url, gitea_username, gitea_token]):
print("Error: Missing Gitea credentials in .env file.")
print("Please make sure GITEA_URL, GITEA_USERNAME, and GITEA_API_TOKEN are set.")
sys.exit(1)
return gitea_url, gitea_username, gitea_token
def get_available_fonts():
"""Get a list of available fonts from the index.json file."""
index_path = Path("fonts/index.json")
if not index_path.exists():
print("Error: fonts/index.json not found.")
sys.exit(1)
with open(index_path, "r") as f:
index = json.load(f)
return [font["name"] for font in index.get("fonts", [])]
def get_repo_name_from_submodule(font_name):
"""Get the repository name from the submodule URL."""
submodule_path = f"fonts/{font_name}"
if not os.path.exists(submodule_path):
return None
# Get the submodule URL from .gitmodules
try:
result = subprocess.run(
["git", "config", "-f", ".gitmodules", f"submodule.{submodule_path}.url"],
capture_output=True, text=True, check=True
)
url = result.stdout.strip()
# Handle both HTTP and SSH URLs
if url.startswith('http://') or url.startswith('https://'):
# HTTP URL format: http://clancy.genet-godzilla.ts.net:3002/fishy/homebrew-font-test
match = re.search(r'/([^/]+)/([^/]+)$', url)
if match:
return match.group(2) # Return the repository name
elif url.startswith('git@') or ':' in url:
# SSH URL format: git@clancy.genet-godzilla.ts.net:fishy/homebrew-font-test
# or with custom port: ssh://git@clancy.genet-godzilla.ts.net:2222/fishy/homebrew-font-test
parts = url.split(':')
if len(parts) >= 2:
# Get the last part which should be username/repo
last_part = parts[-1]
if '/' in last_part:
return last_part.split('/')[-1]
print(f"Warning: Could not extract repository name from URL: {url}")
return None
except subprocess.CalledProcessError:
return None
def delete_gitea_repo(gitea_url, gitea_username, gitea_token, repo_name):
"""Delete a repository from Gitea using the API."""
api_url = f"{gitea_url}/api/v1/repos/{gitea_username}/{repo_name}"
headers = {
"Authorization": f"token {gitea_token}",
"Content-Type": "application/json"
}
print(f"Deleting repository {repo_name} from Gitea...")
response = requests.delete(api_url, headers=headers)
if response.status_code == 204:
print(f"Repository {repo_name} deleted successfully.")
return True
else:
print(f"Error deleting repository: {response.status_code} - {response.text}")
return False
def remove_font(font_name):
"""Remove a font from the Homebrew tap and delete its repository from Gitea."""
# Get Gitea credentials
gitea_url, gitea_username, gitea_token = get_gitea_credentials()
# Check if the font exists
available_fonts = get_available_fonts()
if font_name not in available_fonts:
print(f"Error: Font '{font_name}' not found in the available fonts.")
print(f"Available fonts: {', '.join(available_fonts)}")
sys.exit(1)
# Confirm deletion
print(f"\nWARNING: You are about to remove the font '{font_name}' and delete its repository from Gitea.")
print("This action cannot be undone.")
confirmation = input("Are you sure you want to proceed? (yes/no): ").lower()
if confirmation != "yes":
print("Operation cancelled.")
sys.exit(0)
# Get the repository name from the submodule
repo_name = get_repo_name_from_submodule(font_name)
if not repo_name:
print(f"Warning: Could not determine the repository name for font '{font_name}'.")
print("The repository will not be deleted from Gitea.")
repo_name = None
# Remove the submodule
submodule_path = f"fonts/{font_name}"
if os.path.exists(submodule_path):
print(f"Removing submodule {submodule_path}...")
subprocess.run(["git", "submodule", "deinit", "-f", submodule_path], check=True)
subprocess.run(["git", "rm", "-f", submodule_path], check=True)
subprocess.run(["rm", "-rf", f".git/modules/{submodule_path}"], check=True)
# Remove the formula
formula_path = f"Formula/font-{font_name}.rb"
if os.path.exists(formula_path):
print(f"Removing formula {formula_path}...")
subprocess.run(["git", "rm", "-f", formula_path], check=True)
# Update the index.json file
index_path = Path("fonts/index.json")
with open(index_path, "r") as f:
index = json.load(f)
# Remove the font from the index
index["fonts"] = [font for font in index.get("fonts", []) if font["name"] != font_name]
# Write the updated index back to the file
with open(index_path, "w") as f:
json.dump(index, f, indent=2)
# Delete the repository from Gitea if we found the name
if repo_name:
delete_gitea_repo(gitea_url, gitea_username, gitea_token, repo_name)
else:
print("Skipping repository deletion as the repository name could not be determined.")
# Commit the changes
subprocess.run(["git", "add", "fonts/index.json"], check=True)
subprocess.run(["git", "commit", "-m", f"Remove {font_name} font"], check=True)
print(f"\nFont '{font_name}' has been removed successfully.")
print("Remember to push your changes to Gitea manually.")
def main():
if len(sys.argv) != 2:
print("Usage: python3 remove-font.py <font-name>")
print("\nAvailable fonts:")
available_fonts = get_available_fonts()
for font in available_fonts:
print(f" - {font}")
sys.exit(1)
font_name = sys.argv[1]
remove_font(font_name)
if __name__ == "__main__":
main()