Skip to content

Instantly share code, notes, and snippets.

@pawamoy
Created April 3, 2024 09:59
Show Gist options
  • Save pawamoy/ade3a2f0189c8469b52726943424a236 to your computer and use it in GitHub Desktop.
Save pawamoy/ade3a2f0189c8469b52726943424a236 to your computer and use it in GitHub Desktop.
funding urls for installed python packages, from FUNDING.yml source
import os
from importlib.metadata import distributions
import httpx
import yaml
def fetch_funding(httpx_client, owner, repo):
query = """
query($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
object(expression: "HEAD:.github/FUNDING.yml") {
... on Blob {
text
}
}
}
}
"""
variables = {
"owner": owner,
"repo": repo,
}
response = httpx_client.post('https://api.github.com/graphql', json={"query": query, "variables": variables})
data = response.json()
return yaml.safe_load(data['data']['repository']['object']['text'])
def owner_repo(metadata):
for project_url in metadata.get_all("Project-URL", []):
url = project_url.split(", ", 1)[1].strip().rstrip("/")
if url.startswith("https://github.com/") and url.count("/") == 4:
return url.split("/")[-2:]
raise ValueError("No source URL")
def platform_funding_urls(platform: str, accounts: str | list[str]) -> list[str]:
if accounts is None:
return []
if isinstance(accounts, str):
accounts = [accounts]
if platform == "github":
return [f"https://github.com/sponsors/{account}" for account in accounts]
if platform == "ko_fi":
return [f"https://ko-fi.com/{account}" for account in accounts]
if platform == "tidelift":
return [f"https://tidelift.com/subscription/pkg/{account.replace('/', '-')}" for account in accounts]
if platform == "open_collective":
return [f"https://opencollective.com/{account}" for account in accounts]
if platform == "polar":
return [f"https://polar.sh/{account}" for account in accounts]
if platform == "patreon":
return [f"https://www.patreon.com/{account}" for account in accounts]
if platform == "liberapay":
return [f"https://liberapay.com/{account}" for account in accounts]
if platform == "custom":
return accounts
raise ValueError(f"Unknown platform {platform}")
def main():
with httpx.Client(headers={"Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}"}) as httpx_client:
for package in distributions():
try:
owner, repo = owner_repo(package.metadata)
funding_data = fetch_funding(httpx_client, owner, repo)
except Exception:
continue
funding_urls = [
url
for platform, accounts in funding_data.items()
for url in platform_funding_urls(platform, accounts)
]
print(f"{package.name}: {', '.join(funding_urls)}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment