A python client for the GitHub API
—
GitHub Actions integration module providing support for workflows, contexts, events, and automation including workflow creation and event handling within GitHub Actions environments.
Functions for creating and managing GitHub Actions workflows.
def user_repo():
"""
Get user and repository from GITHUB_REPOSITORY environment variable.
Returns:
list: [user, repo] from env_github.repository
"""
def create_workflow_files():
"""
Create GitHub Actions workflow files.
"""
def fill_workflow_templates():
"""
Fill GitHub Actions workflow templates with data.
"""
def create_workflow():
"""
Create a complete GitHub Actions workflow.
"""
def gh_create_workflow():
"""
CLI command for creating GitHub Actions workflows.
"""
def env_contexts(contexts):
"""
Create suitable env: line for workflow to make contexts available.
Parameters:
- contexts: list, context names to make available
Returns:
str: Environment configuration string
"""GitHub Actions specific logging and output functions.
def actions_output():
"""
Set GitHub Actions output variable.
"""
def actions_debug():
"""
Write debug message to GitHub Actions log.
"""
def actions_warn():
"""
Write warning message to GitHub Actions log.
"""
def actions_error():
"""
Write error message to GitHub Actions log.
"""
def actions_group():
"""
Create collapsible log group in GitHub Actions.
"""
def actions_mask():
"""
Mask sensitive data in GitHub Actions logs.
"""Helper functions for configuring Git in GitHub Actions environments.
def set_git_user():
"""
Set Git user configuration for GitHub Actions.
"""GitHub webhook event types and handling.
Event = str_enum('Event', [
'page_build', # Page build event
'content_reference', # Content reference event
'repository_import', # Repository import event
'create', # Create event (branch/tag)
'workflow_run', # Workflow run event
'delete', # Delete event (branch/tag)
'organization', # Organization event
'sponsorship', # Sponsorship event
'project_column', # Project column event
'push', # Push event
'context', # Context event
'milestone', # Milestone event
'project_card', # Project card event
'project', # Project event
'package', # Package event
'pull_request', # Pull request event
'repository_dispatch', # Repository dispatch event
'team_add', # Team add event
'workflow_dispatch', # Workflow dispatch event
'member', # Member event
'meta', # Meta event
'code_scanning_alert', # Code scanning alert event
'public', # Public event
'needs', # Needs event
'check_run', # Check run event
'security_advisory', # Security advisory event
'pull_request_review_comment', # PR review comment event
'org_block', # Organization block event
'commit_comment', # Commit comment event
'watch', # Watch event (star)
'marketplace_purchase', # Marketplace purchase event
'star', # Star event
'installation_repositories', # Installation repositories event
'check_suite', # Check suite event
'github_app_authorization', # GitHub App authorization event
'team', # Team event
'status', # Status event
'repository_vulnerability_alert', # Repository vulnerability alert
'pull_request_review', # Pull request review event
'label', # Label event
'installation', # Installation event
'release', # Release event
'issues', # Issues event
'repository', # Repository event
'gollum', # Gollum (wiki) event
'membership', # Membership event
'deployment', # Deployment event
'deploy_key', # Deploy key event
'issue_comment', # Issue comment event
'ping', # Ping event
'deployment_status', # Deployment status event
'fork', # Fork event
'schedule' # Schedule event
])GitHub Actions context objects providing access to workflow runtime information.
context_github: dict # GitHub context (github.*)
context_env: dict # Environment variables context (env.*)
context_job: dict # Job context (job.*)
context_steps: dict # Steps context (steps.*)
context_runner: dict # Runner context (runner.*)
context_secrets: dict # Secrets context (secrets.*)
context_strategy: dict # Strategy context (strategy.*)
context_matrix: dict # Matrix context (matrix.*)
context_needs: dict # Needs context (needs.*)
# Environment context object
env_github: dict # GitHub environment variables (GITHUB_*)
# Context names tuple
contexts: tuple = ('github', 'env', 'job', 'steps', 'runner', 'secrets', 'strategy', 'matrix', 'needs')
# Default pip install command for workflows
def_pipinst: str = 'pip install -Uq ghapi'Functions for accessing GitHub Actions data.
def example_payload():
"""
Get example webhook payload for testing.
Returns:
dict: Example webhook payload
"""
def github_token():
"""
Get GitHub token from environment.
Returns:
str: GitHub token
"""from ghapi.all import context_github, context_env, env_github
# Access GitHub context information
print(f"Repository: {context_github.repository}")
print(f"Event name: {context_github.event_name}")
print(f"Actor: {context_github.actor}")
print(f"SHA: {context_github.sha}")
print(f"Ref: {context_github.ref}")
# Access environment variables
print(f"Workflow: {env_github.workflow}")
print(f"Action: {env_github.action}")
print(f"Run ID: {env_github.run_id}")
# Get user and repo
user, repo = user_repo()
print(f"Working with {user}/{repo}")from ghapi.all import actions_debug, actions_warn, actions_error, actions_group, actions_mask
# Debug logging
actions_debug("This is a debug message")
# Warning message
actions_warn("This is a warning message")
# Error message
actions_error("This is an error message")
# Create log group
with actions_group("Building application"):
print("Step 1: Installing dependencies")
print("Step 2: Running build")
print("Step 3: Running tests")
# Mask sensitive data
actions_mask("secret_value_to_hide")
print("The secret_value_to_hide will be masked in logs")from ghapi.all import Event, context_github
# Check event type
current_event = context_github.event_name
if current_event == Event.push:
print("This is a push event")
elif current_event == Event.pull_request:
print("This is a pull request event")
elif current_event == Event.workflow_dispatch:
print("This is a manual workflow dispatch")
elif current_event in [Event.issues, Event.issue_comment]:
print("This is an issue-related event")
# Event type validation
valid_events = [Event.push, Event.pull_request, Event.release]
if current_event in valid_events:
print(f"Processing {current_event} event")from ghapi.all import create_workflow, gh_create_workflow
# Create workflow programmatically
workflow_data = {
'name': 'CI/CD Pipeline',
'on': ['push', 'pull_request'],
'jobs': {
'build': {
'runs-on': 'ubuntu-latest',
'steps': [
{'uses': 'actions/checkout@v2'},
{'name': 'Setup Python', 'uses': 'actions/setup-python@v2'},
{'name': 'Install dependencies', 'run': 'pip install -r requirements.txt'},
{'name': 'Run tests', 'run': 'pytest'}
]
}
}
}
create_workflow(workflow_data)from ghapi.all import set_git_user
# Configure git for commits in Actions
set_git_user()
# Now git commands will work with proper attribution
import subprocess
subprocess.run(['git', 'add', '.'])
subprocess.run(['git', 'commit', '-m', 'Automated commit from Actions'])
subprocess.run(['git', 'push'])from ghapi.all import context_secrets, context_env, github_token
import os
# Access secrets (only available in Actions environment)
if 'GITHUB_ACTIONS' in os.environ:
# Get GitHub token
token = github_token()
# Access other secrets through environment
api_key = os.environ.get('API_KEY')
database_url = os.environ.get('DATABASE_URL')
print("Running in GitHub Actions environment")
else:
print("Not running in GitHub Actions")
# Check runner information
from ghapi.all import context_runner
if context_runner:
print(f"Runner OS: {context_runner.get('os')}")
print(f"Runner Architecture: {context_runner.get('arch')}")from ghapi.all import context_matrix, context_strategy
# Work with matrix builds
if context_matrix:
python_version = context_matrix.get('python-version')
os_version = context_matrix.get('os')
print(f"Running on Python {python_version} with OS {os_version}")
# Conditional logic based on matrix
if python_version == '3.9':
print("Running Python 3.9 specific steps")
elif os_version == 'windows-latest':
print("Running Windows specific steps")
# Strategy information
if context_strategy:
print(f"Strategy: {context_strategy}")from ghapi.all import context_needs
# Access outputs from previous jobs
if context_needs:
# Access outputs from job named 'build'
build_outputs = context_needs.get('build', {}).get('outputs', {})
artifact_path = build_outputs.get('artifact-path')
if artifact_path:
print(f"Using artifact from: {artifact_path}")
# Check if prerequisite jobs completed successfully
if context_needs.get('test', {}).get('result') == 'success':
print("Tests passed, proceeding with deployment")Install with Tessl CLI
npx tessl i tessl/pypi-ghapi