workflowforge 1.0b1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of workflowforge might be problematic. Click here for more details.
- workflowforge/__init__.py +195 -0
- workflowforge/ai_documentation.py +137 -0
- workflowforge/codebuild.py +337 -0
- workflowforge/environment.py +25 -0
- workflowforge/jenkins.py +321 -0
- workflowforge/jenkins_plugins.py +171 -0
- workflowforge/job.py +102 -0
- workflowforge/schema_validation.py +137 -0
- workflowforge/secrets.py +153 -0
- workflowforge/step.py +106 -0
- workflowforge/strategy.py +59 -0
- workflowforge/templates.py +177 -0
- workflowforge/triggers.py +142 -0
- workflowforge/validation.py +73 -0
- workflowforge/visualization.py +200 -0
- workflowforge/workflow.py +152 -0
- workflowforge-1.0b1.dist-info/METADATA +336 -0
- workflowforge-1.0b1.dist-info/RECORD +22 -0
- workflowforge-1.0b1.dist-info/WHEEL +5 -0
- workflowforge-1.0b1.dist-info/licenses/AUTHORS.md +18 -0
- workflowforge-1.0b1.dist-info/licenses/LICENSE +21 -0
- workflowforge-1.0b1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Definición de triggers para workflows de GitHub Actions."""
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from typing import Any, Dict, List, Optional, Union
|
|
5
|
+
|
|
6
|
+
from pydantic import BaseModel, Field
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Trigger(BaseModel, ABC):
|
|
10
|
+
"""Clase base abstracta para triggers."""
|
|
11
|
+
|
|
12
|
+
@abstractmethod
|
|
13
|
+
def to_dict(self) -> str | dict[str, Any]:
|
|
14
|
+
"""Convierte el trigger a formato para YAML."""
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class PushTrigger(Trigger):
|
|
19
|
+
"""Trigger para eventos push."""
|
|
20
|
+
|
|
21
|
+
branches: list[str] | None = Field(
|
|
22
|
+
None, description="Ramas que disparan el trigger"
|
|
23
|
+
)
|
|
24
|
+
branches_ignore: list[str] | None = Field(None, description="Ramas a ignorar")
|
|
25
|
+
tags: list[str] | None = Field(None, description="Tags que disparan el trigger")
|
|
26
|
+
tags_ignore: list[str] | None = Field(None, description="Tags a ignorar")
|
|
27
|
+
paths: list[str] | None = Field(None, description="Rutas que disparan el trigger")
|
|
28
|
+
paths_ignore: list[str] | None = Field(None, description="Rutas a ignorar")
|
|
29
|
+
|
|
30
|
+
def to_dict(self) -> dict[str, Any]:
|
|
31
|
+
"""Convierte a diccionario."""
|
|
32
|
+
result = {}
|
|
33
|
+
if self.branches:
|
|
34
|
+
result["branches"] = self.branches
|
|
35
|
+
if self.branches_ignore:
|
|
36
|
+
result["branches-ignore"] = self.branches_ignore
|
|
37
|
+
if self.tags:
|
|
38
|
+
result["tags"] = self.tags
|
|
39
|
+
if self.tags_ignore:
|
|
40
|
+
result["tags-ignore"] = self.tags_ignore
|
|
41
|
+
if self.paths:
|
|
42
|
+
result["paths"] = self.paths
|
|
43
|
+
if self.paths_ignore:
|
|
44
|
+
result["paths-ignore"] = self.paths_ignore
|
|
45
|
+
|
|
46
|
+
return {"push": result} if result else "push"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class PullRequestTrigger(Trigger):
|
|
50
|
+
"""Trigger para eventos pull request."""
|
|
51
|
+
|
|
52
|
+
types: list[str] | None = Field(None, description="Tipos de eventos PR")
|
|
53
|
+
branches: list[str] | None = Field(None, description="Ramas objetivo")
|
|
54
|
+
branches_ignore: list[str] | None = Field(None, description="Ramas a ignorar")
|
|
55
|
+
paths: list[str] | None = Field(None, description="Rutas que disparan el trigger")
|
|
56
|
+
paths_ignore: list[str] | None = Field(None, description="Rutas a ignorar")
|
|
57
|
+
|
|
58
|
+
def to_dict(self) -> dict[str, Any]:
|
|
59
|
+
"""Convierte a diccionario."""
|
|
60
|
+
result = {}
|
|
61
|
+
if self.types:
|
|
62
|
+
result["types"] = self.types
|
|
63
|
+
if self.branches:
|
|
64
|
+
result["branches"] = self.branches
|
|
65
|
+
if self.branches_ignore:
|
|
66
|
+
result["branches-ignore"] = self.branches_ignore
|
|
67
|
+
if self.paths:
|
|
68
|
+
result["paths"] = self.paths
|
|
69
|
+
if self.paths_ignore:
|
|
70
|
+
result["paths-ignore"] = self.paths_ignore
|
|
71
|
+
|
|
72
|
+
return {"pull_request": result} if result else "pull_request"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class ScheduleTrigger(Trigger):
|
|
76
|
+
"""Trigger para eventos programados (cron)."""
|
|
77
|
+
|
|
78
|
+
cron: str = Field(..., description="Expresión cron")
|
|
79
|
+
|
|
80
|
+
def to_dict(self) -> dict[str, Any]:
|
|
81
|
+
"""Convierte a diccionario."""
|
|
82
|
+
return {"schedule": [{"cron": self.cron}]}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class WorkflowDispatchTrigger(Trigger):
|
|
86
|
+
"""Trigger para ejecución manual."""
|
|
87
|
+
|
|
88
|
+
inputs: dict[str, dict[str, Any]] | None = Field(
|
|
89
|
+
None, description="Inputs del workflow"
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
def to_dict(self) -> dict[str, Any]:
|
|
93
|
+
"""Convierte a diccionario."""
|
|
94
|
+
result = {}
|
|
95
|
+
if self.inputs:
|
|
96
|
+
result["inputs"] = self.inputs
|
|
97
|
+
return {"workflow_dispatch": result} if result else "workflow_dispatch"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class ReleaseTrigger(Trigger):
|
|
101
|
+
"""Trigger para eventos de release."""
|
|
102
|
+
|
|
103
|
+
types: list[str] | None = Field(None, description="Tipos de eventos de release")
|
|
104
|
+
|
|
105
|
+
def to_dict(self) -> dict[str, Any]:
|
|
106
|
+
"""Convierte a diccionario."""
|
|
107
|
+
result = {}
|
|
108
|
+
if self.types:
|
|
109
|
+
result["types"] = self.types
|
|
110
|
+
return {"release": result} if result else "release"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
# Factory functions para crear triggers fácilmente
|
|
114
|
+
def on_push(
|
|
115
|
+
branches: list[str] | None = None, paths: list[str] | None = None
|
|
116
|
+
) -> PushTrigger:
|
|
117
|
+
"""Crea un PushTrigger de manera conveniente."""
|
|
118
|
+
return PushTrigger(branches=branches, paths=paths)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def on_pull_request(
|
|
122
|
+
branches: list[str] | None = None, types: list[str] | None = None
|
|
123
|
+
) -> PullRequestTrigger:
|
|
124
|
+
"""Crea un PullRequestTrigger de manera conveniente."""
|
|
125
|
+
return PullRequestTrigger(branches=branches, types=types)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def on_schedule(cron: str) -> ScheduleTrigger:
|
|
129
|
+
"""Crea un ScheduleTrigger de manera conveniente."""
|
|
130
|
+
return ScheduleTrigger(cron=cron)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def on_workflow_dispatch(
|
|
134
|
+
inputs: dict[str, dict[str, Any]] | None = None,
|
|
135
|
+
) -> WorkflowDispatchTrigger:
|
|
136
|
+
"""Crea un WorkflowDispatchTrigger de manera conveniente."""
|
|
137
|
+
return WorkflowDispatchTrigger(inputs=inputs)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def on_release(types: list[str] | None = None) -> ReleaseTrigger:
|
|
141
|
+
"""Crea un ReleaseTrigger de manera conveniente."""
|
|
142
|
+
return ReleaseTrigger(types=types)
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Validation utilities for WorkflowForge."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from typing import Any, Dict, List
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def validate_job_name(name: str) -> bool:
|
|
8
|
+
"""Validate GitHub Actions job name."""
|
|
9
|
+
return bool(re.match(r"^[a-zA-Z_][a-zA-Z0-9_-]*$", name))
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def validate_step_name(name: str) -> bool:
|
|
13
|
+
"""Validate GitHub Actions step name."""
|
|
14
|
+
return len(name) > 0 and len(name) <= 255
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def validate_environment_name(name: str) -> bool:
|
|
18
|
+
"""Validate GitHub Actions environment name."""
|
|
19
|
+
return bool(re.match(r"^[a-zA-Z0-9_-]+$", name))
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def validate_secret_name(name: str) -> bool:
|
|
23
|
+
"""Validate GitHub Actions secret name."""
|
|
24
|
+
return bool(re.match(r"^[A-Z][A-Z0-9_]*$", name))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def validate_cron_expression(cron: str) -> bool:
|
|
28
|
+
"""Basic validation for cron expressions."""
|
|
29
|
+
parts = cron.split()
|
|
30
|
+
if len(parts) != 5:
|
|
31
|
+
return False
|
|
32
|
+
|
|
33
|
+
# Basic pattern check (not comprehensive)
|
|
34
|
+
cron_pattern = r"^[0-9*,-/]+\s+[0-9*,-/]+\s+[0-9*,-/]+\s+[0-9*,-/]+\s+[0-9*,-/]+$"
|
|
35
|
+
return bool(re.match(cron_pattern, cron))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def validate_docker_image(image: str) -> bool:
|
|
39
|
+
"""Validate Docker image name format."""
|
|
40
|
+
# Basic validation for Docker image names
|
|
41
|
+
pattern = r"^[a-z0-9]+(?:[._-][a-z0-9]+)*(?:/[a-z0-9]+(?:[._-][a-z0-9]+)*)*(?::[a-zA-Z0-9._-]+)?$"
|
|
42
|
+
return bool(re.match(pattern, image))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ValidationError(Exception):
|
|
46
|
+
"""Raised when validation fails."""
|
|
47
|
+
|
|
48
|
+
pass
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def validate_workflow_structure(workflow_dict: dict[str, Any]) -> list[str]:
|
|
52
|
+
"""Validate workflow structure and return list of errors."""
|
|
53
|
+
errors = []
|
|
54
|
+
|
|
55
|
+
# Required fields
|
|
56
|
+
if "name" not in workflow_dict:
|
|
57
|
+
errors.append("Workflow must have a 'name' field")
|
|
58
|
+
|
|
59
|
+
if "on" not in workflow_dict:
|
|
60
|
+
errors.append("Workflow must have an 'on' field")
|
|
61
|
+
|
|
62
|
+
if "jobs" not in workflow_dict:
|
|
63
|
+
errors.append("Workflow must have a 'jobs' field")
|
|
64
|
+
elif not workflow_dict["jobs"]:
|
|
65
|
+
errors.append("Workflow must have at least one job")
|
|
66
|
+
|
|
67
|
+
# Validate job names
|
|
68
|
+
if "jobs" in workflow_dict:
|
|
69
|
+
for job_name in workflow_dict["jobs"]:
|
|
70
|
+
if not validate_job_name(job_name):
|
|
71
|
+
errors.append(f"Invalid job name: '{job_name}'")
|
|
72
|
+
|
|
73
|
+
return errors
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"""Pipeline visualization for WorkflowForge using Graphviz."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import tempfile
|
|
5
|
+
from typing import Any, Dict, List, Optional
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel, Field
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class PipelineVisualizer(BaseModel):
|
|
11
|
+
"""Generates visual diagrams of CI/CD pipelines."""
|
|
12
|
+
|
|
13
|
+
output_format: str = Field(
|
|
14
|
+
default="png", description="Output format (png, svg, pdf)"
|
|
15
|
+
)
|
|
16
|
+
theme: str = Field(default="default", description="Visual theme")
|
|
17
|
+
|
|
18
|
+
def generate_github_diagram(self, workflow) -> str:
|
|
19
|
+
"""Generate diagram for GitHub Actions workflow."""
|
|
20
|
+
dot_content = self._create_github_dot(workflow)
|
|
21
|
+
return self._render_diagram(dot_content, f"{workflow.name}_workflow")
|
|
22
|
+
|
|
23
|
+
def generate_jenkins_diagram(self, pipeline) -> str:
|
|
24
|
+
"""Generate diagram for Jenkins pipeline."""
|
|
25
|
+
dot_content = self._create_jenkins_dot(pipeline)
|
|
26
|
+
return self._render_diagram(dot_content, "jenkins_pipeline")
|
|
27
|
+
|
|
28
|
+
def generate_codebuild_diagram(self, buildspec) -> str:
|
|
29
|
+
"""Generate diagram for CodeBuild spec."""
|
|
30
|
+
dot_content = self._create_codebuild_dot(buildspec)
|
|
31
|
+
return self._render_diagram(dot_content, "codebuild_spec")
|
|
32
|
+
|
|
33
|
+
def _create_github_dot(self, workflow) -> str:
|
|
34
|
+
"""Create Graphviz DOT content for GitHub workflow."""
|
|
35
|
+
dot = ["digraph GitHubWorkflow {"]
|
|
36
|
+
dot.append(" rankdir=TB;")
|
|
37
|
+
dot.append(" node [shape=box, style=rounded];")
|
|
38
|
+
dot.append(" edge [color=blue];")
|
|
39
|
+
|
|
40
|
+
# Triggers
|
|
41
|
+
triggers = self._format_triggers(workflow.on)
|
|
42
|
+
dot.append(
|
|
43
|
+
f' trigger [label="Triggers\\n{triggers}", shape=ellipse, color=green];'
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
# Jobs
|
|
47
|
+
for job_name, job in workflow.jobs.items():
|
|
48
|
+
steps_count = len(job.steps) if hasattr(job, "steps") else 0
|
|
49
|
+
runs_on = getattr(job, "runs_on", "ubuntu-latest")
|
|
50
|
+
|
|
51
|
+
label = f"{job_name}\\nRuns on: {runs_on}\\nSteps: {steps_count}"
|
|
52
|
+
dot.append(f' {job_name} [label="{label}"];')
|
|
53
|
+
|
|
54
|
+
# Connect trigger to job
|
|
55
|
+
dot.append(f" trigger -> {job_name};")
|
|
56
|
+
|
|
57
|
+
# Job dependencies
|
|
58
|
+
if hasattr(job, "needs") and job.needs:
|
|
59
|
+
needs = job.needs if isinstance(job.needs, list) else [job.needs]
|
|
60
|
+
for need in needs:
|
|
61
|
+
dot.append(f" {need} -> {job_name};")
|
|
62
|
+
|
|
63
|
+
dot.append("}")
|
|
64
|
+
return "\n".join(dot)
|
|
65
|
+
|
|
66
|
+
def _create_jenkins_dot(self, pipeline) -> str:
|
|
67
|
+
"""Create Graphviz DOT content for Jenkins pipeline."""
|
|
68
|
+
dot = ["digraph JenkinsPipeline {"]
|
|
69
|
+
dot.append(" rankdir=TB;")
|
|
70
|
+
dot.append(" node [shape=box, style=rounded];")
|
|
71
|
+
dot.append(" edge [color=orange];")
|
|
72
|
+
|
|
73
|
+
# Agent
|
|
74
|
+
agent_info = self._format_jenkins_agent(pipeline.agent)
|
|
75
|
+
dot.append(
|
|
76
|
+
f' agent [label="Agent\\n{agent_info}", shape=ellipse, color=blue];'
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
# Stages
|
|
80
|
+
prev_stage = "agent"
|
|
81
|
+
for i, stage in enumerate(pipeline.stages):
|
|
82
|
+
stage_name = stage.name.replace(" ", "_").replace("-", "_")
|
|
83
|
+
steps_count = len(stage.steps)
|
|
84
|
+
|
|
85
|
+
label = f"{stage.name}\\nSteps: {steps_count}"
|
|
86
|
+
dot.append(f' {stage_name} [label="{label}"];')
|
|
87
|
+
dot.append(f" {prev_stage} -> {stage_name};")
|
|
88
|
+
prev_stage = stage_name
|
|
89
|
+
|
|
90
|
+
dot.append("}")
|
|
91
|
+
return "\n".join(dot)
|
|
92
|
+
|
|
93
|
+
def _create_codebuild_dot(self, buildspec) -> str:
|
|
94
|
+
"""Create Graphviz DOT content for CodeBuild spec."""
|
|
95
|
+
dot = ["digraph CodeBuildSpec {"]
|
|
96
|
+
dot.append(" rankdir=TB;")
|
|
97
|
+
dot.append(" node [shape=box, style=rounded];")
|
|
98
|
+
dot.append(" edge [color=purple];")
|
|
99
|
+
|
|
100
|
+
# Environment
|
|
101
|
+
if buildspec.env:
|
|
102
|
+
vars_count = len(buildspec.env.variables) if buildspec.env.variables else 0
|
|
103
|
+
dot.append(
|
|
104
|
+
f' env [label="Environment\\nVariables: {vars_count}", shape=ellipse, color=green];'
|
|
105
|
+
)
|
|
106
|
+
prev_node = "env"
|
|
107
|
+
else:
|
|
108
|
+
prev_node = None
|
|
109
|
+
|
|
110
|
+
# Phases
|
|
111
|
+
phases = [
|
|
112
|
+
("install", buildspec.install),
|
|
113
|
+
("pre_build", buildspec.pre_build),
|
|
114
|
+
("build", buildspec.build),
|
|
115
|
+
("post_build", buildspec.post_build),
|
|
116
|
+
]
|
|
117
|
+
|
|
118
|
+
for phase_name, phase in phases:
|
|
119
|
+
if phase:
|
|
120
|
+
commands_count = len(phase.commands) if phase.commands else 0
|
|
121
|
+
label = f"{phase_name.replace('_', ' ').title()}\\nCommands: {commands_count}"
|
|
122
|
+
dot.append(f' {phase_name} [label="{label}"];')
|
|
123
|
+
|
|
124
|
+
if prev_node:
|
|
125
|
+
dot.append(f" {prev_node} -> {phase_name};")
|
|
126
|
+
prev_node = phase_name
|
|
127
|
+
|
|
128
|
+
# Artifacts
|
|
129
|
+
if buildspec.artifacts:
|
|
130
|
+
files_count = len(buildspec.artifacts.files)
|
|
131
|
+
dot.append(
|
|
132
|
+
f' artifacts [label="Artifacts\\nFiles: {files_count}", shape=ellipse, color=red];'
|
|
133
|
+
)
|
|
134
|
+
if prev_node:
|
|
135
|
+
dot.append(f" {prev_node} -> artifacts;")
|
|
136
|
+
|
|
137
|
+
dot.append("}")
|
|
138
|
+
return "\n".join(dot)
|
|
139
|
+
|
|
140
|
+
def _format_triggers(self, triggers) -> str:
|
|
141
|
+
"""Format workflow triggers for display."""
|
|
142
|
+
if isinstance(triggers, list):
|
|
143
|
+
return "\\n".join([str(t) for t in triggers])
|
|
144
|
+
return str(triggers)
|
|
145
|
+
|
|
146
|
+
def _format_jenkins_agent(self, agent) -> str:
|
|
147
|
+
"""Format Jenkins agent for display."""
|
|
148
|
+
if hasattr(agent, "docker") and agent.docker:
|
|
149
|
+
return f"Docker: {agent.docker}"
|
|
150
|
+
elif hasattr(agent, "label") and agent.label:
|
|
151
|
+
return f"Label: {agent.label}"
|
|
152
|
+
return "Any"
|
|
153
|
+
|
|
154
|
+
def _render_diagram(self, dot_content: str, filename: str) -> str:
|
|
155
|
+
"""Render DOT content to image file."""
|
|
156
|
+
try:
|
|
157
|
+
# Try using graphviz command
|
|
158
|
+
import subprocess # nosec B404
|
|
159
|
+
|
|
160
|
+
# Create temp file for DOT content
|
|
161
|
+
with tempfile.NamedTemporaryFile(
|
|
162
|
+
mode="w", suffix=".dot", delete=False
|
|
163
|
+
) as f:
|
|
164
|
+
f.write(dot_content)
|
|
165
|
+
dot_file = f.name
|
|
166
|
+
|
|
167
|
+
# Output file
|
|
168
|
+
output_file = f"{filename}.{self.output_format}"
|
|
169
|
+
|
|
170
|
+
# Render with graphviz
|
|
171
|
+
result = subprocess.run( # nosec B603 B607
|
|
172
|
+
["dot", f"-T{self.output_format}", dot_file, "-o", output_file],
|
|
173
|
+
capture_output=True,
|
|
174
|
+
text=True,
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
# Cleanup
|
|
178
|
+
os.unlink(dot_file)
|
|
179
|
+
|
|
180
|
+
if result.returncode == 0:
|
|
181
|
+
return output_file
|
|
182
|
+
else:
|
|
183
|
+
# Fallback: save DOT file
|
|
184
|
+
fallback_file = f"{filename}.dot"
|
|
185
|
+
with open(fallback_file, "w") as f:
|
|
186
|
+
f.write(dot_content)
|
|
187
|
+
return fallback_file
|
|
188
|
+
|
|
189
|
+
except (ImportError, FileNotFoundError):
|
|
190
|
+
# Fallback: save DOT file
|
|
191
|
+
fallback_file = f"{filename}.dot"
|
|
192
|
+
with open(fallback_file, "w") as f:
|
|
193
|
+
f.write(dot_content)
|
|
194
|
+
return fallback_file
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
# Factory function
|
|
198
|
+
def visualizer(output_format: str = "png") -> PipelineVisualizer:
|
|
199
|
+
"""Create a pipeline visualizer."""
|
|
200
|
+
return PipelineVisualizer(output_format=output_format)
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Clase principal para definir workflows de GitHub Actions."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Dict, List, Optional, Union
|
|
4
|
+
|
|
5
|
+
import yaml
|
|
6
|
+
from pydantic import BaseModel, Field
|
|
7
|
+
|
|
8
|
+
from .job import Job
|
|
9
|
+
from .triggers import Trigger
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Workflow(BaseModel):
|
|
13
|
+
"""Representa un workflow completo de GitHub Actions."""
|
|
14
|
+
|
|
15
|
+
name: str = Field(..., description="Nombre del workflow")
|
|
16
|
+
on: Trigger | list[Trigger] | dict[str, Any] = Field(
|
|
17
|
+
..., description="Eventos que disparan el workflow"
|
|
18
|
+
)
|
|
19
|
+
jobs: dict[str, Job] = Field(default_factory=dict, description="Jobs del workflow")
|
|
20
|
+
env: dict[str, str] | None = Field(
|
|
21
|
+
None, description="Variables de entorno globales"
|
|
22
|
+
)
|
|
23
|
+
defaults: dict[str, Any] | None = Field(
|
|
24
|
+
None, description="Configuraciones por defecto"
|
|
25
|
+
)
|
|
26
|
+
concurrency: str | dict[str, Any] | None = Field(
|
|
27
|
+
None, description="Control de concurrencia"
|
|
28
|
+
)
|
|
29
|
+
permissions: dict[str, str] | None = Field(
|
|
30
|
+
None, description="Permisos del workflow"
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
def add_job(self, job_id: str, job: Job) -> "Workflow":
|
|
34
|
+
"""Añade un job al workflow."""
|
|
35
|
+
self.jobs[job_id] = job
|
|
36
|
+
return self
|
|
37
|
+
|
|
38
|
+
def set_env(self, key: str, value: str) -> "Workflow":
|
|
39
|
+
"""Establece una variable de entorno global."""
|
|
40
|
+
if self.env is None:
|
|
41
|
+
self.env = {}
|
|
42
|
+
self.env[key] = value
|
|
43
|
+
return self
|
|
44
|
+
|
|
45
|
+
def to_yaml(self) -> str:
|
|
46
|
+
"""Convierte el workflow a formato YAML."""
|
|
47
|
+
workflow_dict = {
|
|
48
|
+
"name": self.name,
|
|
49
|
+
"on": self._serialize_triggers(),
|
|
50
|
+
"jobs": {
|
|
51
|
+
job_id: job.model_dump(exclude_none=True)
|
|
52
|
+
for job_id, job in self.jobs.items()
|
|
53
|
+
},
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if self.env:
|
|
57
|
+
workflow_dict["env"] = self.env
|
|
58
|
+
if self.defaults:
|
|
59
|
+
workflow_dict["defaults"] = self.defaults
|
|
60
|
+
if self.concurrency:
|
|
61
|
+
workflow_dict["concurrency"] = self.concurrency
|
|
62
|
+
if self.permissions:
|
|
63
|
+
workflow_dict["permissions"] = self.permissions
|
|
64
|
+
|
|
65
|
+
yaml_content = yaml.dump(
|
|
66
|
+
workflow_dict, default_flow_style=False, sort_keys=False
|
|
67
|
+
)
|
|
68
|
+
return f"# Do not modify - Generated with WorkflowForge\n{yaml_content}"
|
|
69
|
+
|
|
70
|
+
def generate_readme(self, use_ai: bool = True, ai_model: str = "llama3.2") -> str:
|
|
71
|
+
"""Generate README documentation for this workflow.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
use_ai: Whether to use AI generation (requires Ollama)
|
|
75
|
+
ai_model: AI model to use for generation
|
|
76
|
+
|
|
77
|
+
Returns:
|
|
78
|
+
Generated README content
|
|
79
|
+
"""
|
|
80
|
+
from .ai_documentation import generate_workflow_readme
|
|
81
|
+
|
|
82
|
+
return generate_workflow_readme(self.to_yaml(), "github", use_ai)
|
|
83
|
+
|
|
84
|
+
def generate_diagram(self, output_format: str = "png") -> str:
|
|
85
|
+
"""Generate visual diagram of this workflow.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
output_format: Output format (png, svg, pdf, dot)
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
Path to generated diagram file
|
|
92
|
+
"""
|
|
93
|
+
from .visualization import visualizer
|
|
94
|
+
|
|
95
|
+
viz = visualizer(output_format=output_format)
|
|
96
|
+
return viz.generate_github_diagram(self)
|
|
97
|
+
|
|
98
|
+
def save(
|
|
99
|
+
self,
|
|
100
|
+
filepath: str = None,
|
|
101
|
+
generate_readme: bool = False,
|
|
102
|
+
use_ai: bool = True,
|
|
103
|
+
generate_diagram: bool = True,
|
|
104
|
+
) -> None:
|
|
105
|
+
"""Save workflow to YAML file.
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
filepath: Path to save the workflow YAML (default: workflow name + .yml)
|
|
109
|
+
generate_readme: Whether to also generate a README file
|
|
110
|
+
use_ai: Whether to use AI for README generation
|
|
111
|
+
generate_diagram: Whether to generate visual diagram
|
|
112
|
+
"""
|
|
113
|
+
if filepath is None:
|
|
114
|
+
# Generate filename from workflow name
|
|
115
|
+
safe_name = self.name.lower().replace(" ", "-").replace("_", "-")
|
|
116
|
+
filepath = f"{safe_name}.yml"
|
|
117
|
+
|
|
118
|
+
with open(filepath, "w", encoding="utf-8") as f:
|
|
119
|
+
f.write(self.to_yaml())
|
|
120
|
+
|
|
121
|
+
if generate_readme:
|
|
122
|
+
readme_path = filepath.replace(".yml", "_README.md").replace(
|
|
123
|
+
".yaml", "_README.md"
|
|
124
|
+
)
|
|
125
|
+
with open(readme_path, "w", encoding="utf-8") as f:
|
|
126
|
+
f.write(self.generate_readme(use_ai=use_ai))
|
|
127
|
+
|
|
128
|
+
if generate_diagram:
|
|
129
|
+
diagram_path = self.generate_diagram()
|
|
130
|
+
print(f"📊 Workflow diagram saved: {diagram_path}")
|
|
131
|
+
|
|
132
|
+
def _serialize_triggers(self) -> str | list[str] | dict[str, Any]:
|
|
133
|
+
"""Serializa los triggers para el YAML."""
|
|
134
|
+
if isinstance(self.on, list):
|
|
135
|
+
# Combinar múltiples triggers en un solo diccionario
|
|
136
|
+
result = {}
|
|
137
|
+
for trigger in self.on:
|
|
138
|
+
if hasattr(trigger, "to_dict"):
|
|
139
|
+
trigger_dict = trigger.to_dict()
|
|
140
|
+
if isinstance(trigger_dict, dict):
|
|
141
|
+
# Merge each trigger's dictionary
|
|
142
|
+
for key, value in trigger_dict.items():
|
|
143
|
+
if value is None or (isinstance(value, dict) and not value):
|
|
144
|
+
result[key] = None
|
|
145
|
+
else:
|
|
146
|
+
result[key] = value
|
|
147
|
+
elif isinstance(trigger, str):
|
|
148
|
+
result[trigger] = None
|
|
149
|
+
return result
|
|
150
|
+
elif hasattr(self.on, "to_dict"):
|
|
151
|
+
return self.on.to_dict()
|
|
152
|
+
return self.on
|