From 974151e5ad1007bd963a454a4cd04ab418e020c5 Mon Sep 17 00:00:00 2001 From: Kenneth Belitzky Date: Mon, 7 Apr 2025 14:44:12 +0000 Subject: [PATCH] Add GitHub trigger script and update documentation --- .github/copilot-instructions.md | 7 ++ README.es.md | 52 ++++++++++++ README.md | 56 +++++++++++- scripts/github-trigger.py | 85 +++++++++++++++++++ .../contribs/configs/devcontainer.yaml | 2 +- 5 files changed, 198 insertions(+), 4 deletions(-) create mode 100644 .github/copilot-instructions.md create mode 100644 scripts/github-trigger.py diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..216db4e --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,7 @@ +# Copilot Instructions + +## Pull Request Template + +- Use the provided pull request template to ensure all necessary information is included. +- Fill in the sections with relevant details about the changes made, including a description of the issue being addressed and any additional context. +- Use the checklist to confirm that you have followed the contributing guidelines and completed all necessary steps. diff --git a/README.es.md b/README.es.md index d5595be..2837bd3 100644 --- a/README.es.md +++ b/README.es.md @@ -296,6 +296,58 @@ Para asegurar que tus archivos de configuración YAML cumplan con la estructura Esta configuración asociará el esquema JSON con todos los archivos .struct.yaml en tu espacio de trabajo, proporcionando validación y autocompletado. +## 🔄 Script de Disparador de GitHub + +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. + +### 📋 Características + +- Filtra repositorios por un tema específico (por ejemplo, `struct-enabled`). +- Verifica la existencia de un archivo `.struct.yaml` en la rama predeterminada del repositorio. +- Comprueba la presencia del archivo de flujo de trabajo `run-struct` en `.github/workflows/`. +- Activa el evento de despacho del flujo de trabajo en los repositorios elegibles. + +### 🚀 Uso + +Para usar el script, asegúrate de cumplir con los siguientes requisitos: + +1. Un token de acceso personal de GitHub válido con los permisos necesarios (configurado como la variable de entorno `GITHUB_TOKEN`). +2. La biblioteca `PyGithub` instalada (`pip install PyGithub`). + +Ejecuta el script con el siguiente comando: + +```sh +python3 scripts/github-trigger.py +``` + +#### Argumentos + +- ``: El nombre de la organización de GitHub. +- ``: El tema para filtrar los repositorios (por ejemplo, `struct-enabled`). + +#### Ejemplo + +```sh +export GITHUB_TOKEN=tu_token_de_acceso_personal +python3 scripts/github-trigger.py mi-org struct-enabled +``` + +### 🛠️ Cómo Funciona + +1. El script se conecta a la API de GitHub utilizando el token proporcionado. +2. Itera a través de todos los repositorios privados de la organización especificada. +3. Para cada repositorio: + - Verifica si el repositorio tiene el tema especificado. + - Comprueba la existencia de un archivo `.struct.yaml` en la rama predeterminada. + - Confirma la presencia del archivo de flujo de trabajo `run-struct`. + - Activa el evento de despacho del flujo de trabajo si se cumplen todas las condiciones. + +### ⚠️ Notas + +- Asegúrate de configurar la variable de entorno `GITHUB_TOKEN` antes de ejecutar el script. +- El token debe tener permisos suficientes para acceder a repositorios privados y activar flujos de trabajo. +- Los errores durante la ejecución (por ejemplo, archivos faltantes o permisos insuficientes) se registrarán en la consola. + ## 👩‍💻 Desarrollo Para comenzar con el desarrollo, sigue estos pasos: diff --git a/README.md b/README.md index 08338cb..b19ec25 100644 --- a/README.md +++ b/README.md @@ -9,13 +9,11 @@ - [Introduction](#-introduction) - [Features](#-features) - [Installation](#installation) - - [Using pip](#using-pip) - - [From Source](#from-source) - - [Using Docker](#using-docker) - [Quick Start](#-quick-start) - [Usage](#-usage) - [YAML Configuration](#-yaml-configuration) - [YAML Schema](#-yaml-schema) +- [GitHub Trigger Script](#-github-trigger-script) - [Development](#-development) - [License](#-license) - [Funding](#-funding) @@ -307,6 +305,58 @@ To ensure your YAML configuration files adhere to the expected structure, you ca This configuration will associate the JSON schema with all .struct.yaml files in your workspace, providing validation and autocompletion. +## 🔄 GitHub Trigger Script + +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. + +### Features + +- Filters repositories by a specific topic (e.g., `struct-enabled`). +- Checks for the existence of a `.struct.yaml` file in the repository's default branch. +- Verifies the presence of the `run-struct` workflow file in `.github/workflows/`. +- Triggers the workflow dispatch event for eligible repositories. + +### Usage + +To use the script, ensure you have the following prerequisites: + +1. A valid GitHub Personal Access Token with the necessary permissions (set as the `GITHUB_TOKEN` environment variable). +2. The `PyGithub` library installed (`pip install PyGithub`). + +Run the script with the following command: + +```sh +python3 scripts/github-trigger.py +``` + +#### Arguments + +- ``: The name of the GitHub organization. +- ``: The topic to filter repositories by (e.g., `struct-enabled`). + +#### Example + +```sh +export GITHUB_TOKEN=your_personal_access_token +python3 scripts/github-trigger.py my-org struct-enabled +``` + +### How It Works + +1. The script connects to the GitHub API using the provided token. +2. It iterates through all private repositories in the specified organization. +3. For each repository: + - Checks if the repository has the specified topic. + - Verifies the existence of a `.struct.yaml` file in the default branch. + - Confirms the presence of the `run-struct` workflow file. + - Triggers the workflow dispatch event if all conditions are met. + +### Notes + +- Ensure the `GITHUB_TOKEN` environment variable is set before running the script. +- The token must have sufficient permissions to access private repositories and trigger workflows. +- Errors during execution (e.g., missing files or insufficient permissions) will be logged to the console. + ## 👩‍💻 Development To get started with development, follow these steps: diff --git a/scripts/github-trigger.py b/scripts/github-trigger.py new file mode 100644 index 0000000..60ba8db --- /dev/null +++ b/scripts/github-trigger.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +import os +import sys +import argparse +from github import Github, GithubException + +def main(): + parser = argparse.ArgumentParser( + description="Trigger the 'run-struct' workflow for all private repos in an organization that have a .struct.yaml file and the specified topic." + ) + parser.add_argument("org", help="Name of the GitHub organization") + parser.add_argument("topic", help="Repository topic to filter by (e.g., 'struct-enabled')") + args = parser.parse_args() + + # Ensure that the GitHub token is set in the environment + token = os.environ.get("GITHUB_TOKEN") + if not token: + sys.exit("Error: Please set the GITHUB_TOKEN environment variable.") + + # Connect to GitHub + g = Github(token) + + try: + org = g.get_organization(args.org) + except GithubException as e: + sys.exit(f"Error getting organization '{args.org}': {e}") + + # Iterate over all repositories in the organization + for repo in org.get_repos(): + # Filter for private repositories only + if not repo.private: + continue + + # Check if the repository has the specified topic + try: + topics = repo.get_topics() + except GithubException as e: + print(f"Could not retrieve topics for repo {repo.full_name}: {e}") + continue + + if args.topic not in topics: + continue + + print(f"\nProcessing repository: {repo.full_name}") + + # Check for the existence of .struct.yaml file (in the repo's default branch) + try: + _ = repo.get_contents(".struct.yaml", ref=repo.default_branch) + except GithubException as e: + if e.status == 404: + print(" .struct.yaml file not found. Skipping.") + else: + print(f" Error retrieving .struct.yaml: {e}") + continue + + print(" Found .struct.yaml file.") + + # Check if the workflow file exists at .github/workflows/run-struct.yaml + try: + _ = repo.get_contents(".github/workflows/run-struct.yaml", ref=repo.default_branch) + except GithubException as e: + if e.status == 404: + print(" Workflow file .github/workflows/run-struct.yaml not found. Skipping workflow trigger.") + else: + print(f" Error retrieving workflow file: {e}") + continue + + print(" Found workflow file .github/workflows/run-struct.yaml.") + + # Retrieve the workflow object (using the file name as identifier) + try: + workflow = repo.get_workflow("run-struct.yaml") + except GithubException as e: + print(f" Error retrieving workflow object: {e}") + continue + + # Trigger a workflow dispatch event on the default branch + try: + workflow.create_dispatch(ref=repo.default_branch) + print(" Triggered run-struct workflow successfully.") + except GithubException as e: + print(f" Error triggering workflow: {e}") + +if __name__ == "__main__": + main() diff --git a/struct_module/contribs/configs/devcontainer.yaml b/struct_module/contribs/configs/devcontainer.yaml index a95aa1d..c76dd6f 100644 --- a/struct_module/contribs/configs/devcontainer.yaml +++ b/struct_module/contribs/configs/devcontainer.yaml @@ -1,4 +1,4 @@ -folders: +structure: - .devcontainer/devcontainer.json: content: | // For format details, see https://aka.ms/devcontainer.json. For config options, see the