workflowforge 1.0.0__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.
@@ -0,0 +1,139 @@
1
+ """GitHub Actions workflow trigger definitions."""
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import Any
5
+
6
+ from pydantic import BaseModel, Field
7
+
8
+
9
+ class Trigger(BaseModel, ABC):
10
+ """Abstract base class for triggers."""
11
+
12
+ @abstractmethod
13
+ def to_dict(self) -> str | dict[str, Any]:
14
+ """Convert trigger to YAML format."""
15
+
16
+
17
+ class PushTrigger(Trigger):
18
+ """Trigger for push events."""
19
+
20
+ branches: list[str] | None = Field(None, description="Branches that trigger")
21
+ branches_ignore: list[str] | None = Field(None, description="Branches to ignore")
22
+ tags: list[str] | None = Field(None, description="Tags that trigger")
23
+ tags_ignore: list[str] | None = Field(None, description="Tags to ignore")
24
+ paths: list[str] | None = Field(None, description="Paths that trigger")
25
+ paths_ignore: list[str] | None = Field(None, description="Paths to ignore")
26
+
27
+ def to_dict(self) -> str | dict[str, Any]:
28
+ """Convert to dictionary."""
29
+ result = {}
30
+ if self.branches:
31
+ result["branches"] = self.branches
32
+ if self.branches_ignore:
33
+ result["branches-ignore"] = self.branches_ignore
34
+ if self.tags:
35
+ result["tags"] = self.tags
36
+ if self.tags_ignore:
37
+ result["tags-ignore"] = self.tags_ignore
38
+ if self.paths:
39
+ result["paths"] = self.paths
40
+ if self.paths_ignore:
41
+ result["paths-ignore"] = self.paths_ignore
42
+
43
+ return {"push": result} if result else "push"
44
+
45
+
46
+ class PullRequestTrigger(Trigger):
47
+ """Trigger for pull request events."""
48
+
49
+ types: list[str] | None = Field(None, description="PR event types")
50
+ branches: list[str] | None = Field(None, description="Target branches")
51
+ branches_ignore: list[str] | None = Field(None, description="Branches to ignore")
52
+ paths: list[str] | None = Field(None, description="Paths that trigger")
53
+ paths_ignore: list[str] | None = Field(None, description="Paths to ignore")
54
+
55
+ def to_dict(self) -> str | dict[str, Any]:
56
+ """Convert to dictionary."""
57
+ result = {}
58
+ if self.types:
59
+ result["types"] = self.types
60
+ if self.branches:
61
+ result["branches"] = self.branches
62
+ if self.branches_ignore:
63
+ result["branches-ignore"] = self.branches_ignore
64
+ if self.paths:
65
+ result["paths"] = self.paths
66
+ if self.paths_ignore:
67
+ result["paths-ignore"] = self.paths_ignore
68
+
69
+ return {"pull_request": result} if result else "pull_request"
70
+
71
+
72
+ class ScheduleTrigger(Trigger):
73
+ """Trigger for scheduled events (cron)."""
74
+
75
+ cron: str = Field(..., description="Cron expression")
76
+
77
+ def to_dict(self) -> str | dict[str, Any]:
78
+ """Convert to dictionary."""
79
+ return {"schedule": [{"cron": self.cron}]}
80
+
81
+
82
+ class WorkflowDispatchTrigger(Trigger):
83
+ """Trigger for manual execution."""
84
+
85
+ inputs: dict[str, dict[str, Any]] | None = Field(
86
+ None, description="Workflow inputs"
87
+ )
88
+
89
+ def to_dict(self) -> str | dict[str, Any]:
90
+ """Convert to dictionary."""
91
+ result = {}
92
+ if self.inputs:
93
+ result["inputs"] = self.inputs
94
+ return {"workflow_dispatch": result} if result else "workflow_dispatch"
95
+
96
+
97
+ class ReleaseTrigger(Trigger):
98
+ """Trigger for release events."""
99
+
100
+ types: list[str] | None = Field(None, description="Release event types")
101
+
102
+ def to_dict(self) -> str | dict[str, Any]:
103
+ """Convert to dictionary."""
104
+ result = {}
105
+ if self.types:
106
+ result["types"] = self.types
107
+ return {"release": result} if result else "release"
108
+
109
+
110
+ # Factory functions for convenient trigger creation
111
+ def on_push(
112
+ branches: list[str] | None = None, paths: list[str] | None = None
113
+ ) -> PushTrigger:
114
+ """Create a PushTrigger conveniently."""
115
+ return PushTrigger(branches=branches, paths=paths)
116
+
117
+
118
+ def on_pull_request(
119
+ branches: list[str] | None = None, types: list[str] | None = None
120
+ ) -> PullRequestTrigger:
121
+ """Create a PullRequestTrigger conveniently."""
122
+ return PullRequestTrigger(branches=branches, types=types)
123
+
124
+
125
+ def on_schedule(cron: str) -> ScheduleTrigger:
126
+ """Create a ScheduleTrigger conveniently."""
127
+ return ScheduleTrigger(cron=cron)
128
+
129
+
130
+ def on_workflow_dispatch(
131
+ inputs: dict[str, dict[str, Any]] | None = None,
132
+ ) -> WorkflowDispatchTrigger:
133
+ """Create a WorkflowDispatchTrigger conveniently."""
134
+ return WorkflowDispatchTrigger(inputs=inputs)
135
+
136
+
137
+ def on_release(types: list[str] | None = None) -> ReleaseTrigger:
138
+ """Create a ReleaseTrigger conveniently."""
139
+ return ReleaseTrigger(types=types)
@@ -0,0 +1,75 @@
1
+ """Validation utilities for WorkflowForge."""
2
+
3
+ import re
4
+ from typing import Any
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 = (
42
+ r"^[a-z0-9]+(?:[._-][a-z0-9]+)*"
43
+ r"(?:/[a-z0-9]+(?:[._-][a-z0-9]+)*)*"
44
+ r"(?::[a-zA-Z0-9._-]+)?$"
45
+ )
46
+ return bool(re.match(pattern, image))
47
+
48
+
49
+ class ValidationError(Exception):
50
+ """Raised when validation fails."""
51
+
52
+
53
+ def validate_workflow_structure(workflow_dict: dict[str, Any]) -> list[str]:
54
+ """Validate workflow structure and return list of errors."""
55
+ errors = []
56
+
57
+ # Required fields
58
+ if "name" not in workflow_dict:
59
+ errors.append("Workflow must have a 'name' field")
60
+
61
+ if "on" not in workflow_dict:
62
+ errors.append("Workflow must have an 'on' field")
63
+
64
+ if "jobs" not in workflow_dict:
65
+ errors.append("Workflow must have a 'jobs' field")
66
+ elif not workflow_dict["jobs"]:
67
+ errors.append("Workflow must have at least one job")
68
+
69
+ # Validate job names
70
+ if "jobs" in workflow_dict:
71
+ for job_name in workflow_dict["jobs"]:
72
+ if not validate_job_name(job_name):
73
+ errors.append(f"Invalid job name: '{job_name}'")
74
+
75
+ return errors
@@ -0,0 +1,204 @@
1
+ """Pipeline visualization for WorkflowForge using Graphviz."""
2
+
3
+ import os
4
+ import tempfile
5
+ from typing import Any
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: Any) -> 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: Any) -> 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: Any) -> 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: Any) -> 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}", '
44
+ "shape=ellipse, color=green];"
45
+ )
46
+
47
+ # Jobs
48
+ for job_name, job in workflow.jobs.items():
49
+ steps_count = len(job.steps) if hasattr(job, "steps") else 0
50
+ runs_on = getattr(job, "runs_on", "ubuntu-latest")
51
+
52
+ label = f"{job_name}\\nRuns on: {runs_on}\\nSteps: {steps_count}"
53
+ dot.append(f' {job_name} [label="{label}"];')
54
+
55
+ # Connect trigger to job
56
+ dot.append(f" trigger -> {job_name};")
57
+
58
+ # Job dependencies
59
+ if hasattr(job, "needs") and job.needs:
60
+ needs = job.needs if isinstance(job.needs, list) else [job.needs]
61
+ for need in needs:
62
+ dot.append(f" {need} -> {job_name};")
63
+
64
+ dot.append("}")
65
+ return "\n".join(dot)
66
+
67
+ def _create_jenkins_dot(self, pipeline: Any) -> str:
68
+ """Create Graphviz DOT content for Jenkins pipeline."""
69
+ dot = ["digraph JenkinsPipeline {"]
70
+ dot.append(" rankdir=TB;")
71
+ dot.append(" node [shape=box, style=rounded];")
72
+ dot.append(" edge [color=orange];")
73
+
74
+ # Agent
75
+ agent_info = self._format_jenkins_agent(pipeline.agent)
76
+ dot.append(
77
+ f' agent [label="Agent\\n{agent_info}", ' "shape=ellipse, color=blue];"
78
+ )
79
+
80
+ # Stages
81
+ prev_stage = "agent"
82
+ for i, stage in enumerate(pipeline.stages):
83
+ stage_name = stage.name.replace(" ", "_").replace("-", "_")
84
+ steps_count = len(stage.steps)
85
+
86
+ label = f"{stage.name}\\nSteps: {steps_count}"
87
+ dot.append(f' {stage_name} [label="{label}"];')
88
+ dot.append(f" {prev_stage} -> {stage_name};")
89
+ prev_stage = stage_name
90
+
91
+ dot.append("}")
92
+ return "\n".join(dot)
93
+
94
+ def _create_codebuild_dot(self, buildspec: Any) -> str:
95
+ """Create Graphviz DOT content for CodeBuild spec."""
96
+ dot = ["digraph CodeBuildSpec {"]
97
+ dot.append(" rankdir=TB;")
98
+ dot.append(" node [shape=box, style=rounded];")
99
+ dot.append(" edge [color=purple];")
100
+
101
+ # Environment
102
+ if buildspec.env:
103
+ vars_count = len(buildspec.env.variables) if buildspec.env.variables else 0
104
+ dot.append(
105
+ f' env [label="Environment\\nVariables: {vars_count}", '
106
+ "shape=ellipse, color=green];"
107
+ )
108
+ prev_node = "env"
109
+ else:
110
+ prev_node = None
111
+
112
+ # Phases
113
+ phases = [
114
+ ("install", buildspec.install),
115
+ ("pre_build", buildspec.pre_build),
116
+ ("build", buildspec.build),
117
+ ("post_build", buildspec.post_build),
118
+ ]
119
+
120
+ for phase_name, phase in phases:
121
+ if phase:
122
+ commands_count = len(phase.commands) if phase.commands else 0
123
+ phase_display = phase_name.replace("_", " ").title()
124
+ label = f"{phase_display}\\nCommands: {commands_count}"
125
+ dot.append(f' {phase_name} [label="{label}"];')
126
+
127
+ if prev_node:
128
+ dot.append(f" {prev_node} -> {phase_name};")
129
+ prev_node = phase_name
130
+
131
+ # Artifacts
132
+ if buildspec.artifacts:
133
+ files_count = len(buildspec.artifacts.files)
134
+ dot.append(
135
+ f' artifacts [label="Artifacts\\nFiles: {files_count}", '
136
+ "shape=ellipse, color=red];"
137
+ )
138
+ if prev_node:
139
+ dot.append(f" {prev_node} -> artifacts;")
140
+
141
+ dot.append("}")
142
+ return "\n".join(dot)
143
+
144
+ def _format_triggers(self, triggers: Any) -> str:
145
+ """Format workflow triggers for display."""
146
+ if isinstance(triggers, list):
147
+ return "\\n".join([str(t) for t in triggers])
148
+ return str(triggers)
149
+
150
+ def _format_jenkins_agent(self, agent: Any) -> str:
151
+ """Format Jenkins agent for display."""
152
+ if hasattr(agent, "docker") and agent.docker:
153
+ return f"Docker: {agent.docker}"
154
+ elif hasattr(agent, "label") and agent.label:
155
+ return f"Label: {agent.label}"
156
+ return "Any"
157
+
158
+ def _render_diagram(self, dot_content: str, filename: str) -> str:
159
+ """Render DOT content to image file."""
160
+ try:
161
+ # Try using graphviz command
162
+ import subprocess # nosec B404
163
+
164
+ # Create temp file for DOT content
165
+ with tempfile.NamedTemporaryFile(
166
+ mode="w", suffix=".dot", delete=False
167
+ ) as f:
168
+ f.write(dot_content)
169
+ dot_file = f.name
170
+
171
+ # Output file
172
+ output_file = f"{filename}.{self.output_format}"
173
+
174
+ # Render with graphviz
175
+ result = subprocess.run( # nosec B603 B607
176
+ ["dot", f"-T{self.output_format}", dot_file, "-o", output_file],
177
+ capture_output=True,
178
+ text=True,
179
+ )
180
+
181
+ # Cleanup
182
+ os.unlink(dot_file)
183
+
184
+ if result.returncode == 0:
185
+ return output_file
186
+ else:
187
+ # Fallback: save DOT file
188
+ fallback_file = f"{filename}.dot"
189
+ with open(fallback_file, "w") as f:
190
+ f.write(dot_content)
191
+ return fallback_file
192
+
193
+ except (ImportError, FileNotFoundError):
194
+ # Fallback: save DOT file
195
+ fallback_file = f"{filename}.dot"
196
+ with open(fallback_file, "w") as f:
197
+ f.write(dot_content)
198
+ return fallback_file
199
+
200
+
201
+ # Factory function
202
+ def visualizer(output_format: str = "png") -> PipelineVisualizer:
203
+ """Create a pipeline visualizer."""
204
+ return PipelineVisualizer(output_format=output_format)
@@ -0,0 +1,161 @@
1
+ """Clase principal para definir workflows de GitHub Actions."""
2
+
3
+ from typing import Any
4
+
5
+ from pydantic import BaseModel, Field
6
+ from ruamel.yaml import YAML
7
+
8
+ from .job import Job
9
+ from .triggers import Trigger
10
+
11
+
12
+ class Workflow(BaseModel):
13
+ """Represents a complete GitHub Actions workflow."""
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
+ """Add a job to the workflow."""
35
+ self.jobs[job_id] = job
36
+ return self
37
+
38
+ def set_env(self, key: str, value: str) -> "Workflow":
39
+ """Set a global environment variable."""
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
+ """Convert workflow to YAML format."""
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 = YAML()
66
+ yaml.default_flow_style = False
67
+ yaml.indent(mapping=2, sequence=4, offset=2)
68
+ yaml.width = 120
69
+ yaml.preserve_quotes = True
70
+
71
+ from io import StringIO
72
+
73
+ stream = StringIO()
74
+ yaml.dump(workflow_dict, stream)
75
+ yaml_content = stream.getvalue()
76
+
77
+ return f"# Do not modify - Generated with WorkflowForge\n{yaml_content}"
78
+
79
+ def generate_readme(self, use_ai: bool = True, ai_model: str = "llama3.2") -> str:
80
+ """Generate README documentation for this workflow.
81
+
82
+ Args:
83
+ use_ai: Whether to use AI generation (requires Ollama)
84
+ ai_model: AI model to use for generation
85
+
86
+ Returns:
87
+ Generated README content
88
+ """
89
+ from .ai_documentation import generate_workflow_readme
90
+
91
+ return generate_workflow_readme(self.to_yaml(), "github", use_ai)
92
+
93
+ def generate_diagram(self, output_format: str = "png") -> str:
94
+ """Generate visual diagram of this workflow.
95
+
96
+ Args:
97
+ output_format: Output format (png, svg, pdf, dot)
98
+
99
+ Returns:
100
+ Path to generated diagram file
101
+ """
102
+ from .visualization import visualizer
103
+
104
+ viz = visualizer(output_format=output_format)
105
+ return viz.generate_github_diagram(self)
106
+
107
+ def save(
108
+ self,
109
+ filepath: str | None = None,
110
+ generate_readme: bool = False,
111
+ use_ai: bool = True,
112
+ generate_diagram: bool = True,
113
+ ) -> None:
114
+ """Save workflow to YAML file.
115
+
116
+ Args:
117
+ filepath: Path to save the workflow YAML (default: workflow name + .yml)
118
+ generate_readme: Whether to also generate a README file
119
+ use_ai: Whether to use AI for README generation
120
+ generate_diagram: Whether to generate visual diagram
121
+ """
122
+ if filepath is None:
123
+ # Generate filename from workflow name
124
+ safe_name = self.name.lower().replace(" ", "-").replace("_", "-")
125
+ filepath = f"{safe_name}.yml"
126
+
127
+ with open(filepath, "w", encoding="utf-8") as f:
128
+ f.write(self.to_yaml())
129
+
130
+ if generate_readme:
131
+ readme_path = filepath.replace(".yml", "_README.md").replace(
132
+ ".yaml", "_README.md"
133
+ )
134
+ with open(readme_path, "w", encoding="utf-8") as f:
135
+ f.write(self.generate_readme(use_ai=use_ai))
136
+
137
+ if generate_diagram:
138
+ diagram_path = self.generate_diagram()
139
+ print(f"📊 Workflow diagram saved: {diagram_path}")
140
+
141
+ def _serialize_triggers(self) -> str | list[str] | dict[str, Any]:
142
+ """Serialize triggers for YAML output."""
143
+ if isinstance(self.on, list):
144
+ # Combinar mĂșltiples triggers en un solo diccionario
145
+ result: dict[str, Any] = {}
146
+ for trigger in self.on:
147
+ if hasattr(trigger, "to_dict"):
148
+ trigger_dict = trigger.to_dict()
149
+ if isinstance(trigger_dict, dict):
150
+ # Merge each trigger's dictionary
151
+ for key, value in trigger_dict.items():
152
+ if value is None or (isinstance(value, dict) and not value):
153
+ result[key] = None
154
+ else:
155
+ result[key] = value
156
+ elif isinstance(trigger, str):
157
+ result[trigger] = None
158
+ return result
159
+ elif hasattr(self.on, "to_dict"):
160
+ return self.on.to_dict()
161
+ return self.on