0
# GitHub Actions
1
2
GitHub Actions integration module providing support for workflows, contexts, events, and automation including workflow creation and event handling within GitHub Actions environments.
3
4
## Capabilities
5
6
### Workflow Management
7
8
Functions for creating and managing GitHub Actions workflows.
9
10
```python { .api }
11
def user_repo():
12
"""
13
Get user and repository from GITHUB_REPOSITORY environment variable.
14
15
Returns:
16
list: [user, repo] from env_github.repository
17
"""
18
19
def create_workflow_files():
20
"""
21
Create GitHub Actions workflow files.
22
"""
23
24
def fill_workflow_templates():
25
"""
26
Fill GitHub Actions workflow templates with data.
27
"""
28
29
def create_workflow():
30
"""
31
Create a complete GitHub Actions workflow.
32
"""
33
34
def gh_create_workflow():
35
"""
36
CLI command for creating GitHub Actions workflows.
37
"""
38
39
def env_contexts(contexts):
40
"""
41
Create suitable env: line for workflow to make contexts available.
42
43
Parameters:
44
- contexts: list, context names to make available
45
46
Returns:
47
str: Environment configuration string
48
"""
49
```
50
51
### Actions Logging
52
53
GitHub Actions specific logging and output functions.
54
55
```python { .api }
56
def actions_output():
57
"""
58
Set GitHub Actions output variable.
59
"""
60
61
def actions_debug():
62
"""
63
Write debug message to GitHub Actions log.
64
"""
65
66
def actions_warn():
67
"""
68
Write warning message to GitHub Actions log.
69
"""
70
71
def actions_error():
72
"""
73
Write error message to GitHub Actions log.
74
"""
75
76
def actions_group():
77
"""
78
Create collapsible log group in GitHub Actions.
79
"""
80
81
def actions_mask():
82
"""
83
Mask sensitive data in GitHub Actions logs.
84
"""
85
```
86
87
### Git Configuration
88
89
Helper functions for configuring Git in GitHub Actions environments.
90
91
```python { .api }
92
def set_git_user():
93
"""
94
Set Git user configuration for GitHub Actions.
95
"""
96
```
97
98
### Event System
99
100
GitHub webhook event types and handling.
101
102
```python { .api }
103
Event = str_enum('Event', [
104
'page_build', # Page build event
105
'content_reference', # Content reference event
106
'repository_import', # Repository import event
107
'create', # Create event (branch/tag)
108
'workflow_run', # Workflow run event
109
'delete', # Delete event (branch/tag)
110
'organization', # Organization event
111
'sponsorship', # Sponsorship event
112
'project_column', # Project column event
113
'push', # Push event
114
'context', # Context event
115
'milestone', # Milestone event
116
'project_card', # Project card event
117
'project', # Project event
118
'package', # Package event
119
'pull_request', # Pull request event
120
'repository_dispatch', # Repository dispatch event
121
'team_add', # Team add event
122
'workflow_dispatch', # Workflow dispatch event
123
'member', # Member event
124
'meta', # Meta event
125
'code_scanning_alert', # Code scanning alert event
126
'public', # Public event
127
'needs', # Needs event
128
'check_run', # Check run event
129
'security_advisory', # Security advisory event
130
'pull_request_review_comment', # PR review comment event
131
'org_block', # Organization block event
132
'commit_comment', # Commit comment event
133
'watch', # Watch event (star)
134
'marketplace_purchase', # Marketplace purchase event
135
'star', # Star event
136
'installation_repositories', # Installation repositories event
137
'check_suite', # Check suite event
138
'github_app_authorization', # GitHub App authorization event
139
'team', # Team event
140
'status', # Status event
141
'repository_vulnerability_alert', # Repository vulnerability alert
142
'pull_request_review', # Pull request review event
143
'label', # Label event
144
'installation', # Installation event
145
'release', # Release event
146
'issues', # Issues event
147
'repository', # Repository event
148
'gollum', # Gollum (wiki) event
149
'membership', # Membership event
150
'deployment', # Deployment event
151
'deploy_key', # Deploy key event
152
'issue_comment', # Issue comment event
153
'ping', # Ping event
154
'deployment_status', # Deployment status event
155
'fork', # Fork event
156
'schedule' # Schedule event
157
])
158
```
159
160
### Context Objects
161
162
GitHub Actions context objects providing access to workflow runtime information.
163
164
```python { .api }
165
context_github: dict # GitHub context (github.*)
166
context_env: dict # Environment variables context (env.*)
167
context_job: dict # Job context (job.*)
168
context_steps: dict # Steps context (steps.*)
169
context_runner: dict # Runner context (runner.*)
170
context_secrets: dict # Secrets context (secrets.*)
171
context_strategy: dict # Strategy context (strategy.*)
172
context_matrix: dict # Matrix context (matrix.*)
173
context_needs: dict # Needs context (needs.*)
174
175
# Environment context object
176
env_github: dict # GitHub environment variables (GITHUB_*)
177
178
# Context names tuple
179
contexts: tuple = ('github', 'env', 'job', 'steps', 'runner', 'secrets', 'strategy', 'matrix', 'needs')
180
181
# Default pip install command for workflows
182
def_pipinst: str = 'pip install -Uq ghapi'
183
```
184
185
### Payload and Token Access
186
187
Functions for accessing GitHub Actions data.
188
189
```python { .api }
190
def example_payload():
191
"""
192
Get example webhook payload for testing.
193
194
Returns:
195
dict: Example webhook payload
196
"""
197
198
def github_token():
199
"""
200
Get GitHub token from environment.
201
202
Returns:
203
str: GitHub token
204
"""
205
```
206
207
## Usage Examples
208
209
### Working with GitHub Actions Context
210
211
```python
212
from ghapi.all import context_github, context_env, env_github
213
214
# Access GitHub context information
215
print(f"Repository: {context_github.repository}")
216
print(f"Event name: {context_github.event_name}")
217
print(f"Actor: {context_github.actor}")
218
print(f"SHA: {context_github.sha}")
219
print(f"Ref: {context_github.ref}")
220
221
# Access environment variables
222
print(f"Workflow: {env_github.workflow}")
223
print(f"Action: {env_github.action}")
224
print(f"Run ID: {env_github.run_id}")
225
226
# Get user and repo
227
user, repo = user_repo()
228
print(f"Working with {user}/{repo}")
229
```
230
231
### GitHub Actions Logging
232
233
```python
234
from ghapi.all import actions_debug, actions_warn, actions_error, actions_group, actions_mask
235
236
# Debug logging
237
actions_debug("This is a debug message")
238
239
# Warning message
240
actions_warn("This is a warning message")
241
242
# Error message
243
actions_error("This is an error message")
244
245
# Create log group
246
with actions_group("Building application"):
247
print("Step 1: Installing dependencies")
248
print("Step 2: Running build")
249
print("Step 3: Running tests")
250
251
# Mask sensitive data
252
actions_mask("secret_value_to_hide")
253
print("The secret_value_to_hide will be masked in logs")
254
```
255
256
### Event Type Checking
257
258
```python
259
from ghapi.all import Event, context_github
260
261
# Check event type
262
current_event = context_github.event_name
263
264
if current_event == Event.push:
265
print("This is a push event")
266
elif current_event == Event.pull_request:
267
print("This is a pull request event")
268
elif current_event == Event.workflow_dispatch:
269
print("This is a manual workflow dispatch")
270
elif current_event in [Event.issues, Event.issue_comment]:
271
print("This is an issue-related event")
272
273
# Event type validation
274
valid_events = [Event.push, Event.pull_request, Event.release]
275
if current_event in valid_events:
276
print(f"Processing {current_event} event")
277
```
278
279
### Workflow Creation
280
281
```python
282
from ghapi.all import create_workflow, gh_create_workflow
283
284
# Create workflow programmatically
285
workflow_data = {
286
'name': 'CI/CD Pipeline',
287
'on': ['push', 'pull_request'],
288
'jobs': {
289
'build': {
290
'runs-on': 'ubuntu-latest',
291
'steps': [
292
{'uses': 'actions/checkout@v2'},
293
{'name': 'Setup Python', 'uses': 'actions/setup-python@v2'},
294
{'name': 'Install dependencies', 'run': 'pip install -r requirements.txt'},
295
{'name': 'Run tests', 'run': 'pytest'}
296
]
297
}
298
}
299
}
300
301
create_workflow(workflow_data)
302
```
303
304
### Git Configuration in Actions
305
306
```python
307
from ghapi.all import set_git_user
308
309
# Configure git for commits in Actions
310
set_git_user()
311
312
# Now git commands will work with proper attribution
313
import subprocess
314
subprocess.run(['git', 'add', '.'])
315
subprocess.run(['git', 'commit', '-m', 'Automated commit from Actions'])
316
subprocess.run(['git', 'push'])
317
```
318
319
### Accessing Secrets and Environment
320
321
```python
322
from ghapi.all import context_secrets, context_env, github_token
323
import os
324
325
# Access secrets (only available in Actions environment)
326
if 'GITHUB_ACTIONS' in os.environ:
327
# Get GitHub token
328
token = github_token()
329
330
# Access other secrets through environment
331
api_key = os.environ.get('API_KEY')
332
database_url = os.environ.get('DATABASE_URL')
333
334
print("Running in GitHub Actions environment")
335
else:
336
print("Not running in GitHub Actions")
337
338
# Check runner information
339
from ghapi.all import context_runner
340
if context_runner:
341
print(f"Runner OS: {context_runner.get('os')}")
342
print(f"Runner Architecture: {context_runner.get('arch')}")
343
```
344
345
### Matrix Strategy Handling
346
347
```python
348
from ghapi.all import context_matrix, context_strategy
349
350
# Work with matrix builds
351
if context_matrix:
352
python_version = context_matrix.get('python-version')
353
os_version = context_matrix.get('os')
354
355
print(f"Running on Python {python_version} with OS {os_version}")
356
357
# Conditional logic based on matrix
358
if python_version == '3.9':
359
print("Running Python 3.9 specific steps")
360
elif os_version == 'windows-latest':
361
print("Running Windows specific steps")
362
363
# Strategy information
364
if context_strategy:
365
print(f"Strategy: {context_strategy}")
366
```
367
368
### Job Dependencies
369
370
```python
371
from ghapi.all import context_needs
372
373
# Access outputs from previous jobs
374
if context_needs:
375
# Access outputs from job named 'build'
376
build_outputs = context_needs.get('build', {}).get('outputs', {})
377
artifact_path = build_outputs.get('artifact-path')
378
379
if artifact_path:
380
print(f"Using artifact from: {artifact_path}")
381
382
# Check if prerequisite jobs completed successfully
383
if context_needs.get('test', {}).get('result') == 'success':
384
print("Tests passed, proceeding with deployment")
385
```