Skip to content

Commit 89ae32a

Browse files
authored
Add GitHub trigger script and update documentation (#41)
A new script, `github-trigger.py`, automates the triggering of the `run-struct` workflow for private repositories in a GitHub organization based on specific criteria. Documentation has been updated to include instructions for using the script and its features.
1 parent b13add8 commit 89ae32a

5 files changed

Lines changed: 198 additions & 4 deletions

File tree

.github/copilot-instructions.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Copilot Instructions
2+
3+
## Pull Request Template
4+
5+
- Use the provided pull request template to ensure all necessary information is included.
6+
- Fill in the sections with relevant details about the changes made, including a description of the issue being addressed and any additional context.
7+
- Use the checklist to confirm that you have followed the contributing guidelines and completed all necessary steps.

README.es.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,58 @@ Para asegurar que tus archivos de configuración YAML cumplan con la estructura
296296

297297
Esta configuración asociará el esquema JSON con todos los archivos .struct.yaml en tu espacio de trabajo, proporcionando validación y autocompletado.
298298

299+
## 🔄 Script de Disparador de GitHub
300+
301+
El script `github-trigger.py` es una utilidad diseñada para activar el flujo de trabajo `run-struct` en todos los repositorios privados de una organización de GitHub que cumplan con ciertos criterios. Este script es especialmente útil para automatizar tareas en múltiples repositorios.
302+
303+
### 📋 Características
304+
305+
- Filtra repositorios por un tema específico (por ejemplo, `struct-enabled`).
306+
- Verifica la existencia de un archivo `.struct.yaml` en la rama predeterminada del repositorio.
307+
- Comprueba la presencia del archivo de flujo de trabajo `run-struct` en `.github/workflows/`.
308+
- Activa el evento de despacho del flujo de trabajo en los repositorios elegibles.
309+
310+
### 🚀 Uso
311+
312+
Para usar el script, asegúrate de cumplir con los siguientes requisitos:
313+
314+
1. Un token de acceso personal de GitHub válido con los permisos necesarios (configurado como la variable de entorno `GITHUB_TOKEN`).
315+
2. La biblioteca `PyGithub` instalada (`pip install PyGithub`).
316+
317+
Ejecuta el script con el siguiente comando:
318+
319+
```sh
320+
python3 scripts/github-trigger.py <organización> <tema>
321+
```
322+
323+
#### Argumentos
324+
325+
- `<organización>`: El nombre de la organización de GitHub.
326+
- `<tema>`: El tema para filtrar los repositorios (por ejemplo, `struct-enabled`).
327+
328+
#### Ejemplo
329+
330+
```sh
331+
export GITHUB_TOKEN=tu_token_de_acceso_personal
332+
python3 scripts/github-trigger.py mi-org struct-enabled
333+
```
334+
335+
### 🛠️ Cómo Funciona
336+
337+
1. El script se conecta a la API de GitHub utilizando el token proporcionado.
338+
2. Itera a través de todos los repositorios privados de la organización especificada.
339+
3. Para cada repositorio:
340+
- Verifica si el repositorio tiene el tema especificado.
341+
- Comprueba la existencia de un archivo `.struct.yaml` en la rama predeterminada.
342+
- Confirma la presencia del archivo de flujo de trabajo `run-struct`.
343+
- Activa el evento de despacho del flujo de trabajo si se cumplen todas las condiciones.
344+
345+
### ⚠️ Notas
346+
347+
- Asegúrate de configurar la variable de entorno `GITHUB_TOKEN` antes de ejecutar el script.
348+
- El token debe tener permisos suficientes para acceder a repositorios privados y activar flujos de trabajo.
349+
- Los errores durante la ejecución (por ejemplo, archivos faltantes o permisos insuficientes) se registrarán en la consola.
350+
299351
## 👩‍💻 Desarrollo
300352

301353
Para comenzar con el desarrollo, sigue estos pasos:

README.md

Lines changed: 53 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,11 @@
99
- [Introduction](#-introduction)
1010
- [Features](#-features)
1111
- [Installation](#installation)
12-
- [Using pip](#using-pip)
13-
- [From Source](#from-source)
14-
- [Using Docker](#using-docker)
1512
- [Quick Start](#-quick-start)
1613
- [Usage](#-usage)
1714
- [YAML Configuration](#-yaml-configuration)
1815
- [YAML Schema](#-yaml-schema)
16+
- [GitHub Trigger Script](#-github-trigger-script)
1917
- [Development](#-development)
2018
- [License](#-license)
2119
- [Funding](#-funding)
@@ -307,6 +305,58 @@ To ensure your YAML configuration files adhere to the expected structure, you ca
307305

308306
This configuration will associate the JSON schema with all .struct.yaml files in your workspace, providing validation and autocompletion.
309307

308+
## 🔄 GitHub Trigger Script
309+
310+
The `github-trigger.py` script is a utility designed to trigger the `run-struct` workflow for all private repositories in a GitHub organization that meet specific criteria. This script is particularly useful for automating tasks across multiple repositories.
311+
312+
### Features
313+
314+
- Filters repositories by a specific topic (e.g., `struct-enabled`).
315+
- Checks for the existence of a `.struct.yaml` file in the repository's default branch.
316+
- Verifies the presence of the `run-struct` workflow file in `.github/workflows/`.
317+
- Triggers the workflow dispatch event for eligible repositories.
318+
319+
### Usage
320+
321+
To use the script, ensure you have the following prerequisites:
322+
323+
1. A valid GitHub Personal Access Token with the necessary permissions (set as the `GITHUB_TOKEN` environment variable).
324+
2. The `PyGithub` library installed (`pip install PyGithub`).
325+
326+
Run the script with the following command:
327+
328+
```sh
329+
python3 scripts/github-trigger.py <organization> <topic>
330+
```
331+
332+
#### Arguments
333+
334+
- `<organization>`: The name of the GitHub organization.
335+
- `<topic>`: The topic to filter repositories by (e.g., `struct-enabled`).
336+
337+
#### Example
338+
339+
```sh
340+
export GITHUB_TOKEN=your_personal_access_token
341+
python3 scripts/github-trigger.py my-org struct-enabled
342+
```
343+
344+
### How It Works
345+
346+
1. The script connects to the GitHub API using the provided token.
347+
2. It iterates through all private repositories in the specified organization.
348+
3. For each repository:
349+
- Checks if the repository has the specified topic.
350+
- Verifies the existence of a `.struct.yaml` file in the default branch.
351+
- Confirms the presence of the `run-struct` workflow file.
352+
- Triggers the workflow dispatch event if all conditions are met.
353+
354+
### Notes
355+
356+
- Ensure the `GITHUB_TOKEN` environment variable is set before running the script.
357+
- The token must have sufficient permissions to access private repositories and trigger workflows.
358+
- Errors during execution (e.g., missing files or insufficient permissions) will be logged to the console.
359+
310360
## 👩‍💻 Development
311361

312362
To get started with development, follow these steps:

scripts/github-trigger.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#!/usr/bin/env python3
2+
import os
3+
import sys
4+
import argparse
5+
from github import Github, GithubException
6+
7+
def main():
8+
parser = argparse.ArgumentParser(
9+
description="Trigger the 'run-struct' workflow for all private repos in an organization that have a .struct.yaml file and the specified topic."
10+
)
11+
parser.add_argument("org", help="Name of the GitHub organization")
12+
parser.add_argument("topic", help="Repository topic to filter by (e.g., 'struct-enabled')")
13+
args = parser.parse_args()
14+
15+
# Ensure that the GitHub token is set in the environment
16+
token = os.environ.get("GITHUB_TOKEN")
17+
if not token:
18+
sys.exit("Error: Please set the GITHUB_TOKEN environment variable.")
19+
20+
# Connect to GitHub
21+
g = Github(token)
22+
23+
try:
24+
org = g.get_organization(args.org)
25+
except GithubException as e:
26+
sys.exit(f"Error getting organization '{args.org}': {e}")
27+
28+
# Iterate over all repositories in the organization
29+
for repo in org.get_repos():
30+
# Filter for private repositories only
31+
if not repo.private:
32+
continue
33+
34+
# Check if the repository has the specified topic
35+
try:
36+
topics = repo.get_topics()
37+
except GithubException as e:
38+
print(f"Could not retrieve topics for repo {repo.full_name}: {e}")
39+
continue
40+
41+
if args.topic not in topics:
42+
continue
43+
44+
print(f"\nProcessing repository: {repo.full_name}")
45+
46+
# Check for the existence of .struct.yaml file (in the repo's default branch)
47+
try:
48+
_ = repo.get_contents(".struct.yaml", ref=repo.default_branch)
49+
except GithubException as e:
50+
if e.status == 404:
51+
print(" .struct.yaml file not found. Skipping.")
52+
else:
53+
print(f" Error retrieving .struct.yaml: {e}")
54+
continue
55+
56+
print(" Found .struct.yaml file.")
57+
58+
# Check if the workflow file exists at .github/workflows/run-struct.yaml
59+
try:
60+
_ = repo.get_contents(".github/workflows/run-struct.yaml", ref=repo.default_branch)
61+
except GithubException as e:
62+
if e.status == 404:
63+
print(" Workflow file .github/workflows/run-struct.yaml not found. Skipping workflow trigger.")
64+
else:
65+
print(f" Error retrieving workflow file: {e}")
66+
continue
67+
68+
print(" Found workflow file .github/workflows/run-struct.yaml.")
69+
70+
# Retrieve the workflow object (using the file name as identifier)
71+
try:
72+
workflow = repo.get_workflow("run-struct.yaml")
73+
except GithubException as e:
74+
print(f" Error retrieving workflow object: {e}")
75+
continue
76+
77+
# Trigger a workflow dispatch event on the default branch
78+
try:
79+
workflow.create_dispatch(ref=repo.default_branch)
80+
print(" Triggered run-struct workflow successfully.")
81+
except GithubException as e:
82+
print(f" Error triggering workflow: {e}")
83+
84+
if __name__ == "__main__":
85+
main()

struct_module/contribs/configs/devcontainer.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
folders:
1+
structure:
22
- .devcontainer/devcontainer.json:
33
content: |
44
// For format details, see https://aka.ms/devcontainer.json. For config options, see the

0 commit comments

Comments
 (0)