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,323 @@
1
+ """Jenkins pipeline generation for WorkflowForge."""
2
+
3
+ from typing import Any
4
+
5
+ from pydantic import BaseModel, Field
6
+
7
+
8
+ class JenkinsStage(BaseModel):
9
+ """Represents a Jenkins pipeline stage."""
10
+
11
+ name: str = Field(..., description="Stage name")
12
+ steps: list[str] = Field(default_factory=list, description="Stage steps")
13
+ when: str | None = Field(None, description="When condition")
14
+ parallel: dict[str, "JenkinsStage"] | None = Field(
15
+ None, description="Parallel stages"
16
+ )
17
+
18
+ def add_step(self, step: str) -> "JenkinsStage":
19
+ """Add a step to the stage."""
20
+ self.steps.append(step)
21
+ return self
22
+
23
+ def set_when(self, condition: str) -> "JenkinsStage":
24
+ """Set when condition."""
25
+ self.when = condition
26
+ return self
27
+
28
+
29
+ class JenkinsAgent(BaseModel):
30
+ """Represents Jenkins agent configuration."""
31
+
32
+ label: str | None = Field(None, description="Agent label")
33
+ docker: str | None = Field(None, description="Docker image")
34
+ any: bool | None = Field(None, description="Any available agent")
35
+
36
+ def to_dict(self) -> str | dict[str, Any]:
37
+ """Convert to Jenkinsfile format."""
38
+ if self.any:
39
+ return "any"
40
+ if self.docker:
41
+ return {"docker": self.docker}
42
+ if self.label:
43
+ return {"label": self.label}
44
+ return "any"
45
+
46
+
47
+ class JenkinsPipeline(BaseModel):
48
+ """Represents a complete Jenkins pipeline."""
49
+
50
+ agent: JenkinsAgent = Field(
51
+ default_factory=lambda: JenkinsAgent(any=True), description="Pipeline agent"
52
+ )
53
+ stages: list[JenkinsStage] = Field(
54
+ default_factory=list, description="Pipeline stages"
55
+ )
56
+ environment: dict[str, str] | None = Field(
57
+ None, description="Environment variables"
58
+ )
59
+ tools: dict[str, str] | None = Field(None, description="Tools configuration")
60
+ options: list[str] | None = Field(None, description="Pipeline options")
61
+ triggers: list[str] | None = Field(None, description="Pipeline triggers")
62
+ post: dict[str, list[str]] | None = Field(None, description="Post actions")
63
+ libraries: list[str] | None = Field(None, description="Shared libraries")
64
+ parameters: list[dict[str, Any]] | None = Field(
65
+ None, description="Pipeline parameters"
66
+ )
67
+ description: str | None = Field(None, description="Pipeline description")
68
+
69
+ def add_stage(self, stage: JenkinsStage) -> "JenkinsPipeline":
70
+ """Add a stage to the pipeline."""
71
+ self.stages.append(stage)
72
+ return self
73
+
74
+ def set_agent(self, agent: JenkinsAgent) -> "JenkinsPipeline":
75
+ """Set pipeline agent."""
76
+ self.agent = agent
77
+ return self
78
+
79
+ def set_env(self, key: str, value: str) -> "JenkinsPipeline":
80
+ """Set environment variable."""
81
+ if self.environment is None:
82
+ self.environment = {}
83
+ self.environment[key] = value
84
+ return self
85
+
86
+ def add_tool(self, name: str, version: str) -> "JenkinsPipeline":
87
+ """Add tool configuration."""
88
+ if self.tools is None:
89
+ self.tools = {}
90
+ self.tools[name] = version
91
+ return self
92
+
93
+ def add_library(self, library: str) -> "JenkinsPipeline":
94
+ """Add shared library."""
95
+ if self.libraries is None:
96
+ self.libraries = []
97
+ self.libraries.append(library)
98
+ return self
99
+
100
+ def add_parameter(
101
+ self, param_type: str, name: str, **kwargs: Any
102
+ ) -> "JenkinsPipeline":
103
+ """Add pipeline parameter."""
104
+ if self.parameters is None:
105
+ self.parameters = []
106
+ param = {"type": param_type, "name": name, **kwargs}
107
+ self.parameters.append(param)
108
+ return self
109
+
110
+ def add_credential(self, id: str, description: str = "") -> "JenkinsPipeline":
111
+ """Add credential parameter."""
112
+ return self.add_parameter("credentials", id, description=description)
113
+
114
+ def set_description(self, description: str) -> "JenkinsPipeline":
115
+ """Set pipeline description."""
116
+ forge_note = "Generated with WorkflowForge"
117
+ if description:
118
+ self.description = f"{description} - {forge_note}"
119
+ else:
120
+ self.description = forge_note
121
+ return self
122
+
123
+ def to_jenkinsfile(self) -> str:
124
+ """Convert to Jenkinsfile format."""
125
+ lines = []
126
+
127
+ # WorkflowForge comment
128
+ lines.append("// Do not modify - Generated with WorkflowForge")
129
+ lines.append("")
130
+
131
+ # Libraries (before pipeline block)
132
+ if self.libraries:
133
+ for library in self.libraries:
134
+ lines.append(f"@Library('{library}') _")
135
+ lines.append("")
136
+
137
+ lines.append("pipeline {")
138
+
139
+ # Description (if set)
140
+ if self.description:
141
+ lines.append(f" description '{self.description}'")
142
+
143
+ # Agent
144
+ agent_config = self.agent.to_dict()
145
+ if isinstance(agent_config, str):
146
+ lines.append(f" agent {agent_config}")
147
+ else:
148
+ lines.append(" agent {")
149
+ for key, value in agent_config.items():
150
+ lines.append(f" {key} '{value}'")
151
+ lines.append(" }")
152
+
153
+ # Parameters
154
+ if self.parameters:
155
+ lines.append(" parameters {")
156
+ for param in self.parameters:
157
+ param_line = f" {param['type']}("
158
+ param_line += f"name: '{param['name']}'"
159
+ for key, value in param.items():
160
+ if key not in ["type", "name"]:
161
+ if isinstance(value, str):
162
+ param_line += f", {key}: '{value}'"
163
+ else:
164
+ param_line += f", {key}: {value}"
165
+ param_line += ")"
166
+ lines.append(param_line)
167
+ lines.append(" }")
168
+
169
+ # Environment
170
+ if self.environment:
171
+ lines.append(" environment {")
172
+ for key, value in self.environment.items():
173
+ lines.append(f" {key} = '{value}'")
174
+ lines.append(" }")
175
+
176
+ # Tools
177
+ if self.tools:
178
+ lines.append(" tools {")
179
+ for name, version in self.tools.items():
180
+ lines.append(f" {name} '{version}'")
181
+ lines.append(" }")
182
+
183
+ # Options
184
+ if self.options:
185
+ lines.append(" options {")
186
+ for option in self.options:
187
+ lines.append(f" {option}")
188
+ lines.append(" }")
189
+
190
+ # Triggers
191
+ if self.triggers:
192
+ lines.append(" triggers {")
193
+ for trigger in self.triggers:
194
+ lines.append(f" {trigger}")
195
+ lines.append(" }")
196
+
197
+ # Stages
198
+ lines.append(" stages {")
199
+ for stage in self.stages:
200
+ lines.extend(self._format_stage(stage, 2))
201
+ lines.append(" }")
202
+
203
+ # Post
204
+ if self.post:
205
+ lines.append(" post {")
206
+ for condition, actions in self.post.items():
207
+ lines.append(f" {condition} {{")
208
+ for action in actions:
209
+ lines.append(f" {action}")
210
+ lines.append(" }")
211
+ lines.append(" }")
212
+
213
+ lines.append("}")
214
+ return "\n".join(lines) + "\n"
215
+
216
+ def _format_stage(self, stage: JenkinsStage, indent: int) -> list[str]:
217
+ """Format a stage for Jenkinsfile."""
218
+ prefix = " " * indent
219
+ lines = [f"{prefix}stage('{stage.name}') {{"]
220
+
221
+ if stage.when:
222
+ lines.append(f"{prefix} when {{ {stage.when} }}")
223
+
224
+ if stage.parallel:
225
+ lines.append(f"{prefix} parallel {{")
226
+ for name, parallel_stage in stage.parallel.items():
227
+ lines.append(f"{prefix} '{name}': {{")
228
+ lines.append(f"{prefix} steps {{")
229
+ for step in parallel_stage.steps:
230
+ lines.append(f"{prefix} {step}")
231
+ lines.append(f"{prefix} }}")
232
+ lines.append(f"{prefix} }}")
233
+ lines.append(f"{prefix} }}")
234
+ else:
235
+ lines.append(f"{prefix} steps {{")
236
+ for step in stage.steps:
237
+ lines.append(f"{prefix} {step}")
238
+ lines.append(f"{prefix} }}")
239
+
240
+ lines.append(f"{prefix}}}")
241
+ return lines
242
+
243
+ def generate_readme(self, use_ai: bool = True, ai_model: str = "llama3.2") -> str:
244
+ """Generate README documentation for this pipeline.
245
+
246
+ Args:
247
+ use_ai: Whether to use AI generation (requires Ollama)
248
+ ai_model: AI model to use for generation
249
+
250
+ Returns:
251
+ Generated README content
252
+ """
253
+ from .ai_documentation import generate_workflow_readme
254
+
255
+ return generate_workflow_readme(self.to_jenkinsfile(), "jenkins", use_ai)
256
+
257
+ def generate_diagram(self, output_format: str = "png") -> str:
258
+ """Generate visual diagram of this pipeline.
259
+
260
+ Args:
261
+ output_format: Output format (png, svg, pdf, dot)
262
+
263
+ Returns:
264
+ Path to generated diagram file
265
+ """
266
+ from .visualization import visualizer
267
+
268
+ viz = visualizer(output_format=output_format)
269
+ return viz.generate_jenkins_diagram(self)
270
+
271
+ def save(
272
+ self,
273
+ filepath: str = "Jenkinsfile",
274
+ generate_readme: bool = False,
275
+ use_ai: bool = True,
276
+ generate_diagram: bool = True,
277
+ ) -> None:
278
+ """Save pipeline to Jenkinsfile.
279
+
280
+ Args:
281
+ filepath: Path to save the Jenkinsfile (default: Jenkinsfile)
282
+ Note: Jenkins typically expects 'Jenkinsfile' (no extension)
283
+ generate_readme: Whether to also generate a README file
284
+ use_ai: Whether to use AI for README generation
285
+ generate_diagram: Whether to generate visual diagram
286
+ """
287
+ with open(filepath, "w", encoding="utf-8") as f:
288
+ f.write(self.to_jenkinsfile())
289
+
290
+ if generate_readme:
291
+ readme_path = filepath.replace("Jenkinsfile", "Jenkinsfile_README.md")
292
+ with open(readme_path, "w", encoding="utf-8") as f:
293
+ f.write(self.generate_readme(use_ai=use_ai))
294
+
295
+ if generate_diagram:
296
+ diagram_path = self.generate_diagram()
297
+ print(f"📊 Pipeline diagram saved: {diagram_path}")
298
+
299
+
300
+ # Factory functions
301
+ def agent_any() -> JenkinsAgent:
302
+ """Create any agent."""
303
+ return JenkinsAgent(any=True)
304
+
305
+
306
+ def agent_docker(image: str) -> JenkinsAgent:
307
+ """Create docker agent."""
308
+ return JenkinsAgent(docker=image)
309
+
310
+
311
+ def agent_label(label: str) -> JenkinsAgent:
312
+ """Create label agent."""
313
+ return JenkinsAgent(label=label)
314
+
315
+
316
+ def stage(name: str) -> JenkinsStage:
317
+ """Create a stage."""
318
+ return JenkinsStage(name=name)
319
+
320
+
321
+ def pipeline() -> JenkinsPipeline:
322
+ """Create a pipeline."""
323
+ return JenkinsPipeline()
@@ -0,0 +1,172 @@
1
+ """Jenkins plugins and VCS support for WorkflowForge."""
2
+
3
+ from pydantic import BaseModel, Field
4
+
5
+
6
+ class GitCheckout(BaseModel):
7
+ """Git checkout configuration."""
8
+
9
+ url: str = Field(..., description="Git repository URL")
10
+ branch: str = Field(default="main", description="Branch to checkout")
11
+ credentials_id: str | None = Field(None, description="Jenkins credentials ID")
12
+ shallow: bool | None = Field(None, description="Shallow clone")
13
+ depth: int | None = Field(None, description="Clone depth")
14
+
15
+ def to_step(self) -> str:
16
+ """Convert to Jenkins step."""
17
+ step = "checkout scm: [$class: 'GitSCM', "
18
+ step += f"branches: [[name: '{self.branch}']], "
19
+ step += f"userRemoteConfigs: [[url: '{self.url}'"
20
+ if self.credentials_id:
21
+ step += f", credentialsId: '{self.credentials_id}'"
22
+ step += "]]"
23
+ if self.shallow:
24
+ step += (
25
+ f", extensions: [[$class: 'CloneOption', "
26
+ f"shallow: {str(self.shallow).lower()}"
27
+ )
28
+ if self.depth:
29
+ step += f", depth: {self.depth}"
30
+ step += "]]"
31
+ step += "]"
32
+ return step
33
+
34
+
35
+ class DockerPlugin(BaseModel):
36
+ """Docker plugin configuration."""
37
+
38
+ image: str = Field(..., description="Docker image")
39
+ args: str | None = Field(None, description="Docker run arguments")
40
+ registry_url: str | None = Field(None, description="Docker registry URL")
41
+ credentials_id: str | None = Field(None, description="Registry credentials")
42
+
43
+ def to_step(self, command: str) -> str:
44
+ """Convert to Docker step."""
45
+ step = f"docker.image('{self.image}')"
46
+ if self.registry_url or self.credentials_id:
47
+ step += ".withRegistry("
48
+ if self.registry_url:
49
+ step += f"'{self.registry_url}'"
50
+ if self.credentials_id:
51
+ if self.registry_url:
52
+ step += f", '{self.credentials_id}'"
53
+ else:
54
+ step += f"null, '{self.credentials_id}'"
55
+ step += ")"
56
+ step += f".inside('{self.args or ''}') {{ {command} }}"
57
+ return step
58
+
59
+
60
+ class SlackNotification(BaseModel):
61
+ """Slack notification plugin."""
62
+
63
+ channel: str = Field(..., description="Slack channel")
64
+ message: str = Field(..., description="Message to send")
65
+ color: str | None = Field(None, description="Message color")
66
+ token_credential_id: str | None = Field(
67
+ None, description="Slack token credential ID"
68
+ )
69
+
70
+ def to_step(self) -> str:
71
+ """Convert to Slack step."""
72
+ step = f"slackSend channel: '{self.channel}', message: '{self.message}'"
73
+ if self.color:
74
+ step += f", color: '{self.color}'"
75
+ if self.token_credential_id:
76
+ step += f", tokenCredentialId: '{self.token_credential_id}'"
77
+ return step
78
+
79
+
80
+ class EmailNotification(BaseModel):
81
+ """Email notification plugin."""
82
+
83
+ to: str = Field(..., description="Email recipients")
84
+ subject: str = Field(..., description="Email subject")
85
+ body: str = Field(..., description="Email body")
86
+ attach_log: bool | None = Field(None, description="Attach build log")
87
+
88
+ def to_step(self) -> str:
89
+ """Convert to email step."""
90
+ step = (
91
+ f"emailext to: '{self.to}', subject: '{self.subject}', body: '{self.body}'"
92
+ )
93
+ if self.attach_log:
94
+ step += f", attachLog: {str(self.attach_log).lower()}"
95
+ return step
96
+
97
+
98
+ class ArtifactArchiver(BaseModel):
99
+ """Artifact archiver plugin."""
100
+
101
+ artifacts: str = Field(..., description="Artifacts pattern")
102
+ allow_empty: bool | None = Field(None, description="Allow empty archive")
103
+ fingerprint: bool | None = Field(None, description="Fingerprint artifacts")
104
+ only_if_successful: bool | None = Field(
105
+ None, description="Only if build successful"
106
+ )
107
+
108
+ def to_step(self) -> str:
109
+ """Convert to archive step."""
110
+ step = f"archiveArtifacts artifacts: '{self.artifacts}'"
111
+ if self.allow_empty is not None:
112
+ step += f", allowEmptyArchive: {str(self.allow_empty).lower()}"
113
+ if self.fingerprint is not None:
114
+ step += f", fingerprint: {str(self.fingerprint).lower()}"
115
+ if self.only_if_successful is not None:
116
+ step += f", onlyIfSuccessful: {str(self.only_if_successful).lower()}"
117
+ return step
118
+
119
+
120
+ class JUnitPublisher(BaseModel):
121
+ """JUnit test results publisher."""
122
+
123
+ test_results: str = Field(..., description="Test results pattern")
124
+ allow_empty: bool | None = Field(None, description="Allow empty results")
125
+ keep_long_stdio: bool | None = Field(None, description="Keep long stdio")
126
+
127
+ def to_step(self) -> str:
128
+ """Convert to JUnit step."""
129
+ step = f"junit testResults: '{self.test_results}'"
130
+ if self.allow_empty is not None:
131
+ step += f", allowEmptyResults: {str(self.allow_empty).lower()}"
132
+ if self.keep_long_stdio is not None:
133
+ step += f", keepLongStdio: {str(self.keep_long_stdio).lower()}"
134
+ return step
135
+
136
+
137
+ # Factory functions for common plugins
138
+ def git_checkout(
139
+ url: str, branch: str = "main", credentials_id: str | None = None
140
+ ) -> GitCheckout:
141
+ """Create Git checkout configuration."""
142
+ return GitCheckout(url=url, branch=branch, credentials_id=credentials_id)
143
+
144
+
145
+ def docker_run(image: str, command: str, args: str | None = None) -> str:
146
+ """Create Docker run step."""
147
+ docker = DockerPlugin(image=image, args=args)
148
+ return docker.to_step(command)
149
+
150
+
151
+ def slack_notify(channel: str, message: str, color: str | None = None) -> str:
152
+ """Create Slack notification step."""
153
+ slack = SlackNotification(channel=channel, message=message, color=color)
154
+ return slack.to_step()
155
+
156
+
157
+ def email_notify(to: str, subject: str, body: str) -> str:
158
+ """Create email notification step."""
159
+ email = EmailNotification(to=to, subject=subject, body=body)
160
+ return email.to_step()
161
+
162
+
163
+ def archive_artifacts(artifacts: str, allow_empty: bool = False) -> str:
164
+ """Create artifact archiver step."""
165
+ archiver = ArtifactArchiver(artifacts=artifacts, allow_empty=allow_empty)
166
+ return archiver.to_step()
167
+
168
+
169
+ def publish_junit(test_results: str, allow_empty: bool = False) -> str:
170
+ """Create JUnit publisher step."""
171
+ junit = JUnitPublisher(test_results=test_results, allow_empty=allow_empty)
172
+ return junit.to_step()
workflowforge/job.py ADDED
@@ -0,0 +1,102 @@
1
+ """Definición de Jobs para workflows de GitHub Actions."""
2
+
3
+ from typing import Any
4
+
5
+ from pydantic import BaseModel, Field
6
+
7
+ from .environment import Environment
8
+ from .step import Step
9
+ from .strategy import Strategy
10
+
11
+
12
+ class Job(BaseModel):
13
+ """Represents a job in a GitHub Actions workflow."""
14
+
15
+ runs_on: str | list[str] = Field(..., description="Runner donde ejecutar el job")
16
+ steps: list[Step] = Field(default_factory=list, description="Pasos del job")
17
+ needs: str | list[str] | None = Field(None, description="Jobs de los que depende")
18
+ if_condition: str | None = Field(
19
+ None, alias="if", description="Condición para ejecutar el job"
20
+ )
21
+ strategy: Strategy | None = Field(None, description="Estrategia de matriz")
22
+ environment: str | Environment | None = Field(
23
+ None, description="Entorno de despliegue"
24
+ )
25
+ env: dict[str, str] | None = Field(None, description="Variables de entorno del job")
26
+ defaults: dict[str, Any] | None = Field(
27
+ None, description="Configuraciones por defecto"
28
+ )
29
+ timeout_minutes: int | None = Field(None, description="Timeout en minutos")
30
+ continue_on_error: bool | None = Field(None, description="Continuar si hay error")
31
+ container: str | dict[str, Any] | None = Field(
32
+ None, description="Contenedor para el job"
33
+ )
34
+ services: dict[str, Any] | None = Field(None, description="Servicios del job")
35
+ outputs: dict[str, str] | None = Field(None, description="Outputs del job")
36
+ permissions: dict[str, str] | None = Field(None, description="Permisos del job")
37
+
38
+ def add_step(self, step: Step) -> "Job":
39
+ """Add a step to the job."""
40
+ self.steps.append(step)
41
+ return self
42
+
43
+ def set_env(self, key: str, value: str) -> "Job":
44
+ """Set an environment variable."""
45
+ if self.env is None:
46
+ self.env = {}
47
+ self.env[key] = value
48
+ return self
49
+
50
+ def set_needs(self, *job_ids: str) -> "Job":
51
+ """Set job dependencies."""
52
+ if len(job_ids) == 1:
53
+ self.needs = job_ids[0]
54
+ else:
55
+ self.needs = list(job_ids)
56
+ return self
57
+
58
+ def set_condition(self, condition: str) -> "Job":
59
+ """Set condition for job execution."""
60
+ self.if_condition = condition
61
+ return self
62
+
63
+ def set_timeout(self, minutes: int) -> "Job":
64
+ """Set job timeout."""
65
+ self.timeout_minutes = minutes
66
+ return self
67
+
68
+ def set_output(self, key: str, value: str) -> "Job":
69
+ """Set job output."""
70
+ if self.outputs is None:
71
+ self.outputs = {}
72
+ self.outputs[key] = value
73
+ return self
74
+
75
+ def set_permissions(self, permissions: dict[str, str]) -> "Job":
76
+ """Set job permissions."""
77
+ self.permissions = permissions
78
+ return self
79
+
80
+ def model_dump(self, **kwargs: Any) -> dict[str, Any]:
81
+ """Serialize job to dictionary, converting steps correctly."""
82
+ data = super().model_dump(**kwargs)
83
+
84
+ # Convertir steps usando su método to_dict()
85
+ if "steps" in data and data["steps"]:
86
+ data["steps"] = [step.to_dict() for step in self.steps]
87
+
88
+ # Convertir environment si es un objeto Environment
89
+ if "environment" in data and hasattr(data["environment"], "model_dump"):
90
+ data["environment"] = data["environment"].model_dump()
91
+
92
+ # Convertir if_condition a if
93
+ if "if_condition" in data and data["if_condition"]:
94
+ data["if"] = data["if_condition"]
95
+ del data["if_condition"]
96
+
97
+ # Convertir runs_on a runs-on
98
+ if "runs_on" in data:
99
+ data["runs-on"] = data["runs_on"]
100
+ del data["runs_on"]
101
+
102
+ return data