├── .gitignore
├── CHANGELOG.md
├── Jenkinsfile
├── Jenkinsfile.yaml
├── LICENSE
├── README.md
├── images
└── branch-source.png
├── pom.xml
├── scripts
└── hello.sh
├── src
├── main
│ ├── java
│ │ └── io
│ │ │ └── jenkins
│ │ │ └── plugins
│ │ │ └── sprp
│ │ │ ├── YamlBranchProjectFactory.java
│ │ │ ├── YamlFlowDefinition.java
│ │ │ ├── YamlMultiBranchProjectFactory.java
│ │ │ ├── YamlToPipeline.java
│ │ │ ├── exception
│ │ │ └── ConversionException.java
│ │ │ ├── generators
│ │ │ ├── AgentGenerator.java
│ │ │ ├── ArchiveArtifactStageGenerator.java
│ │ │ ├── CustomSectionGenerator.java
│ │ │ ├── EnvironmentGenerator.java
│ │ │ ├── GitPushStageGenerator.java
│ │ │ ├── PipelineGenerator.java
│ │ │ ├── PostGenerator.java
│ │ │ ├── PublishReportsAndArtifactsStageGenerator.java
│ │ │ ├── StageGenerator.java
│ │ │ └── StepGenerator.java
│ │ │ ├── git
│ │ │ ├── GitConfig.java
│ │ │ ├── GitOperations.java
│ │ │ └── GitPushStep.java
│ │ │ └── models
│ │ │ ├── Agent.java
│ │ │ ├── ArtifactPublishingConfig.java
│ │ │ ├── Configuration.java
│ │ │ ├── Credential.java
│ │ │ ├── CustomPipelineSection.java
│ │ │ ├── Environment.java
│ │ │ ├── Post.java
│ │ │ ├── ReportsAndArtifactsInfo.java
│ │ │ ├── Stage.java
│ │ │ ├── Step.java
│ │ │ └── YamlPipeline.java
│ └── resources
│ │ ├── index.jelly
│ │ └── io
│ │ └── jenkins
│ │ └── plugins
│ │ └── sprp
│ │ └── Messages.properties
└── test
│ └── java
│ └── io
│ └── jenkins
│ └── plugins
│ └── sprp
│ ├── FullPipelineGenerationTest.java
│ ├── YamlToPipelineTest.java
│ └── generators
│ ├── AgentGeneratorTest.java
│ ├── ArchiveArtifactStageGeneratorTest.java
│ ├── CustomSectionGeneratorTest.java
│ ├── EnvironmentGeneratorTest.java
│ ├── GitPushStageGeneratorTest.java
│ ├── PostGeneratorTest.java
│ ├── PublishReportsAndArtifactsStageGenaratorTest.java
│ ├── StageGeneratorTest.java
│ └── StepGeneratorTest.java
└── yamlExamples
├── AgentExamples.md
├── ConfigurationExample.md
├── EnvironmentExample.md
├── Jenkinsfile.yaml
├── MultipleStagesExample.md
├── Readme.md
└── SimpleStageExample.md
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 | *.iml
3 | target/
4 | work/
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | Changelog
2 | ===
3 |
4 | # 1.0-alpha-1
5 |
6 | Release date: July 6, 2018
7 |
8 | Initial Release
9 |
--------------------------------------------------------------------------------
/Jenkinsfile:
--------------------------------------------------------------------------------
1 | buildPlugin()
--------------------------------------------------------------------------------
/Jenkinsfile.yaml:
--------------------------------------------------------------------------------
1 | agent:
2 | # Docket image agent example
3 | # label: my_label
4 | # customWorkspace: path_to_workspace
5 | # dockerImage: maven:3-alpine
6 | # args: -v /tmp:/tmp
7 |
8 | # tools needs to be defined in the tool configuration
9 | tools:
10 | maven : maven_3.0.1
11 | jdk : jdk8
12 |
13 | configuration:
14 | # Push PR changes to the target branch if the build will be success.
15 | # default value will be false
16 | pushPrOnSuccess: false
17 |
18 | prApprovers:
19 | - username1
20 | - username2
21 | - username3
22 |
23 | # Study about the reports type. Urgent
24 | reports:
25 | - location_of_report_1
26 | - location_of_report_2
27 |
28 | environment:
29 | variables:
30 | variable_1: value_1
31 | variable_2: value_2
32 |
33 | # Credentials contains only two fields. See pipeline file for how it will be used
34 | credentials:
35 | - credentialId : fileCredentialId
36 | variable : FILE
37 |
38 | # Username will be accessed by LOGIN_USR and Password will be accessed by LOGIN_PSW
39 | - credentialId : dummyGitRepo
40 | variable : LOGIN
41 |
42 | stages:
43 | - name: satge1
44 | agent: any
45 | steps:
46 | - sh:
47 | script: "scripts/hello"
48 | - sh: "scripts/hello"
49 | - sleep:
50 | time: 2
51 | # Configurator.lookup() in JCasc plugin returns null for java.util.concurrent.TimeUnit which is an Enum class
52 | # jira link: https://issues.jenkins-ci.org/browse/JENKINS-52443
53 | # unit: SECONDS
54 | - sleep: 2
55 | - junit:
56 | testResults: "target/**.xml"
57 | allowEmptyResults: true
58 | testDataPublishers:
59 | - AutomateTestDataPublisher
60 | - JunitResultPublisher:
61 | urlOverride: "urlOverride"
62 | # JCasc plugin having problem in configuring below class
63 | # jira link: https://issues.jenkins-ci.org/browse/JENKINS-52444
64 |
65 | - JiraTestDataPublisher:
66 | configs:
67 | - SelectableFields:
68 | fieldKey: "SelectableFields key"
69 | value: "SelectableFields value"
70 |
71 | projectKey: "project key"
72 | issueType: "issue type"
73 | autoRaiseIssue: true
74 |
75 |
76 | post:
77 | failure:
78 | - sh: "scripts/hello"
79 | post:
80 | always:
81 | - sh: "scripts/hello"
82 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Simple Pull Request job plugin for Jenkins
2 |
3 | [](https://gitter.im/jenkinsci/simple-pull-request-job-plugin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
4 |
5 | This project aims to develop a Job Plugin which can interact with Bitbucket Server, Bitbucket Cloud, and Github whenever a pull request is created or updated. Users should be able to configure job type using YAML file which will be placed in root directory of the Git repository being the subject of the PR.
6 |
7 | ### Overview
8 |
9 | This plugin take build.yaml file (which will be stored in root location of repository which has to be built of target branch)
10 | and converts it to Declarative pipeline code internally and build the repository. Yaml syntax is very similar to Declarative
11 | pipeline code and examples can be found [here](yamlExamples).
12 |
13 | ### How to run this plugin
14 |
15 | Till this point of time plugin is tested with GitHub plugin, ans it needs to be installed on the jenkins instance.
16 | 1. Create a multibranch project.
17 | 2. In Branch sources add GitHub (Needs to install Github Plugin)
18 | 3. Set required credentials, owner and repository.
19 | 4. Set behaviours as follows.
20 | 
21 |
22 | 5. Scroll down to Build Configuration and select "by Jenkinsfile.yaml".
23 | 6. Edit anyother configurations and hit save. Plugin will automatiacally
24 | discover all the branches and pull requests and start to build them
25 | according to "Jenkinsfile.yaml".
26 |
27 | To run the demo repository configure the GitHub branch source as shown in the above
28 | figure. Don't specify git credentials (As no one except @gautamabhishek have them)
29 | and the build will be successful except one git push step at the last. Everyone can
30 | also use "Scan Repository Now" and "Build Now" (for all branches and PRs).
31 |
32 | [Demo repository](https://github.com/gautamabhishek46/dummy)
33 |
34 | #### Jenkinsfile.yaml example
35 | ```yaml
36 | agent: any
37 |
38 | buildResultPaths:
39 | - path-1
40 | - path-2
41 |
42 | testResultPaths:
43 | - path-1
44 | - path-2
45 |
46 | stages:
47 | - name: First
48 | steps:
49 | - sh './scripts/hello'
50 | defaultParameter: ./scripts/hello
51 | - name: Build
52 | steps:
53 | - stepName: sh
54 | parameters:
55 | script: ./scripts/build
56 | - name: Tests
57 | steps:
58 | - stepName: sh
59 | defaultParameter: ./scripts/hello
60 |
61 | archiveArtifacts:
62 | - Jenkinsfile.yaml
63 | - scripts/hello.sh
64 |
65 | artifactPublishingConfig: # Details are not correct
66 | host: 192.32.52.12
67 | user: user53
68 | credentialId: dummyGitRepo
69 |
70 | publishArtifacts:
71 | - from: Jenkinsfile.yaml
72 | to: ~/archives
73 | - from: scripts/hello.sh
74 | to: ~/archives
75 |
76 | ```
77 |
78 | #### Simple agent example
79 | ```yaml
80 | agent:
81 | label: 'my-label'
82 | customWorkspace: 'path-to-workspace'
83 | ```
84 |
85 |
86 | #### Agent with docker image example
87 | ```yaml
88 | agent:
89 | label: 'my-label'
90 | customWorkspace: 'path-to-workspace'
91 | dockerImage: 'image-name'
92 | args: 'some argument' # optional
93 | ```
94 |
95 | #### Agent with dockerfile example
96 | ```yaml
97 | agent:
98 | label: 'my-label'
99 | customWorkspace: 'path-to-workspace'
100 | dockerfile: 'image-name'
101 | dir: 'path-to-directory'
102 | args: 'some argument' # optional
103 | ```
104 |
105 | Note:
106 | 1. Agent arguments are same as declarative pipeline agent arguments except "dockerImage".
107 | 2. Don't use dockerImage and dockerfile parameters simultaneously, else it will result in errors.
108 | 3. The build will be started for pull request and normal branches after branch indexing.
109 | 4. Sections such as tools, post, when, ect are not supported at this point in time.
110 |
111 | If there is a need to call a script then use "sh" step name and just give the relative path of
112 | the script without extension (.bat or .sh). plugin will detect the machine (linux or windows) and
113 | add the extension on its own.
114 |
115 | Users can declare any number of stages but stages named 'Build' and 'Tests' must be declared by the
116 | user. These two stages can contain simple echo steps also. It is needed because at this stage
117 | plugin generate post sections in these two stages to archive artifacts, publish reports and to
118 | push the changes to target branch.
119 |
120 | Only xml reports are supported at this point in time.
121 |
122 | ### Future tasks
123 |
124 | 1. Support the “when” Declarative Pipeline directive
125 | 2. Detect the presence of certain types of the report based on a conventional location, and automatically publish them. If the reports are not in a conventional location, users could specify the location using the YML file.
126 | 3. Support build from webhook of diffrent platforms (like GitHub, Bitbucket, etc).
--------------------------------------------------------------------------------
/images/branch-source.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jenkinsci/simple-pull-request-job-plugin/281a7b43ed86ef5815669e3480972f1d336dffba/images/branch-source.png
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 |
5 | org.jenkins-ci.plugins
6 | plugin
7 | 3.18
8 |
9 |
10 | io.jenkins.plugins
11 | simple-pull-request-job
12 | 1.0-alpha-4-SNAPSHOT
13 | hpi
14 |
15 |
16 | 2.138.1
17 | 8
18 | true
19 |
20 | Simple Pull Request Job Plugin
21 | Simple pull request job plugin. This plugin will use YAML to configure a job for pull request.
22 |
23 |
24 | MIT License
25 | https://opensource.org/licenses/MIT
26 |
27 |
28 |
29 |
30 | org.jenkins-ci.plugins
31 | structs
32 | 1.15
33 |
34 |
35 | org.jenkins-ci.plugins
36 | scm-api
37 | 2.2.8
38 |
39 |
40 | org.jenkins-ci.plugins
41 | script-security
42 | 1.46
43 |
44 |
45 | org.jenkins-ci.plugins
46 | cloudbees-folder
47 | 6.5.1
48 |
49 |
50 | org.jenkins-ci.plugins.workflow
51 | workflow-scm-step
52 | 2.7
53 |
54 |
55 | org.jenkins-ci.plugins.workflow
56 | workflow-multibranch
57 | 2.20
58 |
59 |
60 | org.jenkins-ci.plugins.workflow
61 | workflow-step-api
62 | 2.16
63 |
64 |
65 | org.jenkins-ci.plugins.workflow
66 | workflow-basic-steps
67 | 2.11
68 | test
69 |
70 |
71 | org.jenkins-ci.plugins.workflow
72 | workflow-durable-task-step
73 | 2.13
74 | test
75 |
76 |
77 | org.jenkins-ci.plugins.workflow
78 | workflow-support
79 | 2.20
80 | test
81 |
82 |
83 | org.jenkins-ci.plugins.workflow
84 | workflow-cps
85 | 2.57
86 | compile
87 |
88 |
89 | org.jenkins-ci.plugins.workflow
90 | workflow-api
91 | 2.29
92 | compile
93 |
94 |
95 | org.jenkins-ci.plugins.workflow
96 | workflow-job
97 | 2.25
98 | compile
99 |
100 |
101 | org.jenkins-ci.plugins
102 | git-client
103 | 2.7.3
104 | compile
105 |
106 |
107 | org.jenkins-ci.plugins
108 | git
109 | 3.9.1
110 |
111 |
112 | org.jenkins-ci.plugins
113 | jackson2-api
114 | 2.8.11.3
115 |
116 |
117 | org.jenkins-ci.plugins
118 | credentials
119 | 2.1.18
120 |
121 |
122 | org.jenkins-ci.plugins
123 | junit
124 | 1.26.1
125 |
126 |
127 | org.jenkins-ci
128 | annotation-indexer
129 | 1.12
130 |
131 |
132 | io.jenkins
133 | configuration-as-code
134 | 1.0
135 |
136 |
137 | org.yaml
138 | snakeyaml
139 | 1.23
140 |
141 |
142 | org.jenkinsci.plugins
143 | pipeline-model-api
144 | 1.3.2
145 |
146 |
147 |
148 |
149 |
150 |
151 | gautamabhishek46
152 | Abhishek Gautam
153 | gautam.abhishek46@gmail.com
154 |
155 |
156 |
157 |
158 | scm:git:git://github.com/jenkinsci/simple-pull-request-job-plugin.git
159 | scm:git:git@github.com:jenkinsci/simple-pull-request-job-plugin.git
160 | https://github.com/jenkinsci/simple-pull-request-job-plugin
161 | HEAD
162 |
163 |
164 |
165 |
166 | repo.jenkins-ci.org
167 | https://repo.jenkins-ci.org/public/
168 |
169 |
170 |
171 |
172 | repo.jenkins-ci.org
173 | https://repo.jenkins-ci.org/public/
174 |
175 |
176 |
177 |
178 |
--------------------------------------------------------------------------------
/scripts/hello.sh:
--------------------------------------------------------------------------------
1 | echo "Hello!! from pipeline generator"
--------------------------------------------------------------------------------
/src/main/java/io/jenkins/plugins/sprp/YamlBranchProjectFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright 2015-2018 CloudBees, Inc, Abhishek Gautam (@gautamabhishek46).
5 | *
6 | * Permission is hereby granted, free of charge, to any person obtaining a copy
7 | * of this software and associated documentation files (the "Software"), to deal
8 | * in the Software without restriction, including without limitation the rights
9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | * copies of the Software, and to permit persons to whom the Software is
11 | * furnished to do so, subject to the following conditions:
12 | *
13 | * The above copyright notice and this permission notice shall be included in
14 | * all copies or substantial portions of the Software.
15 | *
16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | * THE SOFTWARE.
23 | */
24 |
25 | package io.jenkins.plugins.sprp;
26 |
27 | import hudson.Extension;
28 | import hudson.model.TaskListener;
29 | import jenkins.scm.api.SCMProbeStat;
30 | import jenkins.scm.api.SCMSource;
31 | import jenkins.scm.api.SCMSourceCriteria;
32 | import org.apache.commons.lang.StringUtils;
33 | import org.jenkinsci.plugins.workflow.flow.FlowDefinition;
34 | import org.jenkinsci.plugins.workflow.multibranch.AbstractWorkflowBranchProjectFactory;
35 | import org.kohsuke.accmod.Restricted;
36 | import org.kohsuke.accmod.restrictions.NoExternalUse;
37 | import org.kohsuke.stapler.DataBoundConstructor;
38 | import org.kohsuke.stapler.DataBoundSetter;
39 |
40 | import java.io.IOException;
41 | import java.util.logging.Logger;
42 |
43 | /**
44 | * Recognizes and builds {@code Jenkinsfile.yaml}.
45 | * Original code: org.jenkinsci.plugins.workflow.multibranch.YamlBranchProjectFactory
46 | */
47 | public class YamlBranchProjectFactory extends AbstractWorkflowBranchProjectFactory {
48 | private static final Logger LOGGER = Logger.getLogger(YamlBranchProjectFactory.class.getName());
49 | static final String YAML_SCRIPT = "Jenkinsfile.yaml";
50 | static final String YML_SCRIPT = "Jenkinsfile.yml";
51 | private String scriptPath = YAML_SCRIPT;
52 |
53 | @DataBoundConstructor
54 | public YamlBranchProjectFactory() {
55 | }
56 |
57 | public Object readResolve() {
58 | if (this.scriptPath == null) {
59 | this.scriptPath = YAML_SCRIPT;
60 | }
61 | return this;
62 | }
63 |
64 | public String getScriptPath() {
65 | return scriptPath;
66 | }
67 |
68 | @DataBoundSetter
69 | public void setScriptPath(String scriptPath) {
70 | if (StringUtils.isEmpty(scriptPath)) {
71 | this.scriptPath = YAML_SCRIPT;
72 | } else {
73 | this.scriptPath = scriptPath;
74 | }
75 | }
76 |
77 | @Override
78 | protected FlowDefinition createDefinition() {
79 | return new YamlFlowDefinition(scriptPath);
80 | }
81 |
82 | @Override
83 | protected SCMSourceCriteria getSCMSourceCriteria(SCMSource source) {
84 | return new SCMSourceCriteria() {
85 | @Override
86 | public boolean isHead(SCMSourceCriteria.Probe probe, TaskListener listener) throws IOException {
87 | while (true) {
88 | SCMProbeStat stat = probe.stat(scriptPath);
89 | switch (stat.getType()) {
90 | case NONEXISTENT:
91 | // Handle default yml case.
92 | if (scriptPath.equals(YAML_SCRIPT)) {
93 | scriptPath = YML_SCRIPT;
94 | }
95 | if (stat.getAlternativePath() != null) {
96 | listener.getLogger().format("‘%s’ not found (but found ‘%s’, search is case sensitive)%n", scriptPath, stat.getAlternativePath());
97 | } else {
98 | listener.getLogger().format("‘%s’ not found%n", scriptPath);
99 | }
100 | return false;
101 | case DIRECTORY:
102 | listener.getLogger().format("‘%s’ found but is a directory not a file%n", scriptPath);
103 | return false;
104 | default:
105 | listener.getLogger().format("‘%s’ found%n", scriptPath);
106 | return isCorrectYAMLFile(scriptPath);
107 | }
108 | }
109 | }
110 |
111 | @Override
112 | public int hashCode() {
113 | return getClass().hashCode();
114 | }
115 |
116 | @Override
117 | public boolean equals(Object obj) {
118 | return getClass().isInstance(obj);
119 | }
120 | };
121 | }
122 |
123 | @Extension
124 | @Restricted(NoExternalUse.class)
125 | public static class DescriptorImpl extends AbstractWorkflowBranchProjectFactoryDescriptor {
126 | @Override
127 | public String getDisplayName() {
128 | return "by " + YAML_SCRIPT;
129 | }
130 | }
131 |
132 | private boolean isCorrectYAMLFile(String path) {
133 | String[] paths = path.split("/");
134 | String filename = paths[paths.length - 1];
135 | String[] exts = filename.split("\\.");
136 | String extension = exts[exts.length - 1];
137 | return extension.equals("yaml") || extension.equals("yml");
138 | }
139 | }
140 |
--------------------------------------------------------------------------------
/src/main/java/io/jenkins/plugins/sprp/YamlFlowDefinition.java:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright 2018 Abhishek Gautam (@gautamabhishek46).
5 | *
6 | * Permission is hereby granted, free of charge, to any person obtaining a copy
7 | * of this software and associated documentation files (the "Software"), to deal
8 | * in the Software without restriction, including without limitation the rights
9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | * copies of the Software, and to permit persons to whom the Software is
11 | * furnished to do so, subject to the following conditions:
12 | *
13 | * The above copyright notice and this permission notice shall be included in
14 | * all copies or substantial portions of the Software.
15 | *
16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | * THE SOFTWARE.
23 | */
24 |
25 | package io.jenkins.plugins.sprp;
26 |
27 | import hudson.Extension;
28 | import hudson.model.Action;
29 | import hudson.model.ItemGroup;
30 | import hudson.model.Queue;
31 | import hudson.model.TaskListener;
32 | import hudson.plugins.git.GitSCM;
33 | import io.jenkins.plugins.sprp.git.GitConfig;
34 | import jenkins.branch.Branch;
35 | import jenkins.scm.api.SCMFileSystem;
36 | import jenkins.scm.api.SCMHead;
37 | import jenkins.scm.api.SCMRevision;
38 | import jenkins.scm.api.SCMSource;
39 | import jenkins.scm.api.mixin.ChangeRequestSCMHead2;
40 | import org.jenkinsci.plugins.workflow.cps.CpsFlowExecution;
41 | import org.jenkinsci.plugins.workflow.flow.FlowDefinition;
42 | import org.jenkinsci.plugins.workflow.flow.FlowDefinitionDescriptor;
43 | import org.jenkinsci.plugins.workflow.flow.FlowExecution;
44 | import org.jenkinsci.plugins.workflow.flow.FlowExecutionOwner;
45 | import org.jenkinsci.plugins.workflow.job.WorkflowJob;
46 | import org.jenkinsci.plugins.workflow.job.WorkflowRun;
47 | import org.jenkinsci.plugins.workflow.multibranch.BranchJobProperty;
48 | import org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject;
49 | import org.kohsuke.accmod.Restricted;
50 | import org.kohsuke.accmod.restrictions.NoExternalUse;
51 |
52 | import javax.annotation.Nonnull;
53 | import java.io.IOException;
54 | import java.io.InputStream;
55 | import java.util.List;
56 |
57 | public class YamlFlowDefinition extends FlowDefinition {
58 | private String scriptPath;
59 |
60 | public YamlFlowDefinition(String scriptPath) {
61 | this.scriptPath = scriptPath;
62 | }
63 |
64 | public Object readResolve() {
65 | if (this.scriptPath == null) {
66 | this.scriptPath = "Jenkinsfile.yaml";
67 | }
68 | return this;
69 | }
70 |
71 | @Override
72 | public FlowExecution create(FlowExecutionOwner owner, TaskListener listener,
73 | List extends Action> actions) throws Exception {
74 | Queue.Executable exec = owner.getExecutable();
75 | if (!(exec instanceof WorkflowRun)) {
76 | throw new IllegalStateException("inappropriate context");
77 | }
78 |
79 | WorkflowRun build = (WorkflowRun) exec;
80 | WorkflowJob job = build.getParent();
81 | BranchJobProperty property = job.getProperty(BranchJobProperty.class);
82 |
83 | Branch branch = property.getBranch();
84 | ItemGroup> parent = job.getParent();
85 |
86 | if (!(parent instanceof WorkflowMultiBranchProject)) {
87 | throw new IllegalStateException("inappropriate context");
88 | }
89 |
90 | SCMSource scmSource = ((WorkflowMultiBranchProject) parent).getSCMSource(branch.getSourceId());
91 |
92 | if (scmSource == null) {
93 | throw new IllegalStateException(branch.getSourceId() + " not found");
94 | }
95 |
96 | GitConfig gitConfig = new GitConfig();
97 |
98 | SCMHead head = branch.getHead();
99 |
100 | if ("Pull Request".equals(head.getPronoun())) {
101 | ChangeRequestSCMHead2 changeRequestSCMHead2 = (ChangeRequestSCMHead2) branch.getHead();
102 | head = changeRequestSCMHead2.getTarget();
103 | }
104 |
105 | SCMRevision tip = scmSource.fetch(head, listener);
106 |
107 | if (tip == null) {
108 | throw new IllegalStateException("Cannot determine the revision.");
109 | }
110 |
111 | SCMRevision rev = scmSource.getTrustedRevision(tip, listener);
112 | GitSCM gitSCM = (GitSCM) scmSource.build(head, rev);
113 |
114 | gitConfig.setGitUrl(gitSCM.getUserRemoteConfigs().get(0).getUrl());
115 | gitConfig.setCredentialsId(gitSCM.getUserRemoteConfigs().get(0).getCredentialsId());
116 | gitConfig.setGitBranch(head.getName());
117 |
118 | String script;
119 | try (SCMFileSystem fs = SCMFileSystem.of(scmSource, head, rev)) {
120 | if (fs != null) {
121 | InputStream yamlInputStream = fs.child(scriptPath).content();
122 | listener.getLogger().println("Path of yaml/yml config file: " + fs.child(scriptPath).getPath());
123 | YamlToPipeline y = new YamlToPipeline();
124 | script = y.generatePipeline(yamlInputStream, gitConfig, listener);
125 | } else {
126 | throw new IOException("SCM not supported");
127 | // FIXME implement full checkout
128 | }
129 | }
130 |
131 | listener.getLogger().println(script);
132 | return new CpsFlowExecution(script, false, owner);
133 | }
134 |
135 | @Extension
136 | @Restricted(NoExternalUse.class)
137 | public static class DescriptorImpl extends FlowDefinitionDescriptor {
138 |
139 | @Nonnull
140 | @Override
141 | public String getDisplayName() {
142 | return Messages.YAML_FlowDefinition_DescriptorImpl_DisplayName();
143 | }
144 | }
145 | }
146 |
--------------------------------------------------------------------------------
/src/main/java/io/jenkins/plugins/sprp/YamlMultiBranchProjectFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License
3 | *
4 | * Copyright 2015-2018 CloudBees, Inc, Abhishek Gautam (@gautamabhishek46).
5 | *
6 | * Permission is hereby granted, free of charge, to any person obtaining a copy
7 | * of this software and associated documentation files (the "Software"), to deal
8 | * in the Software without restriction, including without limitation the rights
9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | * copies of the Software, and to permit persons to whom the Software is
11 | * furnished to do so, subject to the following conditions:
12 | *
13 | * The above copyright notice and this permission notice shall be included in
14 | * all copies or substantial portions of the Software.
15 | *
16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | * THE SOFTWARE.
23 | */
24 |
25 | package io.jenkins.plugins.sprp;
26 |
27 | import hudson.Extension;
28 | import jenkins.branch.MultiBranchProjectFactory;
29 | import jenkins.branch.MultiBranchProjectFactoryDescriptor;
30 | import jenkins.scm.api.SCMSource;
31 | import jenkins.scm.api.SCMSourceCriteria;
32 | import org.apache.commons.lang.StringUtils;
33 | import org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProjectFactory;
34 | import org.kohsuke.accmod.Restricted;
35 | import org.kohsuke.accmod.restrictions.NoExternalUse;
36 | import org.kohsuke.stapler.DataBoundConstructor;
37 | import org.kohsuke.stapler.DataBoundSetter;
38 |
39 | import java.io.IOException;
40 |
41 | /**
42 | * Defines organization folders by {@link YamlBranchProjectFactory}.
43 | * Original code: org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProjectFactory
44 | */
45 | public class YamlMultiBranchProjectFactory extends WorkflowMultiBranchProjectFactory {
46 | private String scriptPath = YamlBranchProjectFactory.YAML_SCRIPT;
47 |
48 | @DataBoundConstructor
49 | public YamlMultiBranchProjectFactory() {
50 | }
51 |
52 | public Object readResolve() {
53 | if (this.scriptPath == null) {
54 | this.scriptPath = YamlBranchProjectFactory.YAML_SCRIPT;
55 | }
56 |
57 | return this;
58 | }
59 |
60 | public String getScriptPath() {
61 | return scriptPath;
62 | }
63 |
64 | @DataBoundSetter
65 | public void setScriptPath(String scriptPath) {
66 | if (StringUtils.isEmpty(scriptPath)) {
67 | this.scriptPath = YamlBranchProjectFactory.YAML_SCRIPT;
68 | } else {
69 | this.scriptPath = scriptPath;
70 | }
71 | }
72 |
73 | @Override
74 | protected SCMSourceCriteria getSCMSourceCriteria(SCMSource source) {
75 | return newProjectFactorySCMSourceCriteria(source);
76 | }
77 |
78 | private org.jenkinsci.plugins.workflow.multibranch.AbstractWorkflowBranchProjectFactory newProjectFactory() {
79 | YamlBranchProjectFactory workflowBranchProjectFactory = new YamlBranchProjectFactory();
80 | workflowBranchProjectFactory.setScriptPath(scriptPath);
81 | return workflowBranchProjectFactory;
82 | }
83 |
84 | private SCMSourceCriteria newProjectFactorySCMSourceCriteria(SCMSource source) {
85 | YamlBranchProjectFactory workflowBranchProjectFactory = new YamlBranchProjectFactory();
86 | workflowBranchProjectFactory.setScriptPath(scriptPath);
87 | return workflowBranchProjectFactory.getSCMSourceCriteria(source);
88 | }
89 |
90 | @Override
91 | protected void customize(org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject project)
92 | throws IOException, InterruptedException {
93 | project.setProjectFactory(newProjectFactory());
94 | }
95 |
96 | @Extension
97 | @Restricted(NoExternalUse.class)
98 | public static class DescriptorImpl extends MultiBranchProjectFactoryDescriptor {
99 |
100 | @Override
101 | public MultiBranchProjectFactory newInstance() {
102 | return new org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProjectFactory();
103 | }
104 |
105 | @Override
106 | public String getDisplayName() {
107 | return "Pipeline " + YamlBranchProjectFactory.YAML_SCRIPT;
108 | }
109 |
110 | }
111 | }
112 |
--------------------------------------------------------------------------------
/src/main/java/io/jenkins/plugins/sprp/YamlToPipeline.java:
--------------------------------------------------------------------------------
1 | package io.jenkins.plugins.sprp;
2 |
3 | import hudson.model.TaskListener;
4 | import io.jenkins.plugins.sprp.exception.ConversionException;
5 | import io.jenkins.plugins.sprp.generators.PipelineGenerator;
6 | import io.jenkins.plugins.sprp.git.GitConfig;
7 | import io.jenkins.plugins.sprp.models.*;
8 | import org.yaml.snakeyaml.Yaml;
9 | import org.yaml.snakeyaml.constructor.CustomClassLoaderConstructor;
10 |
11 | import javax.annotation.CheckForNull;
12 | import javax.annotation.Nonnull;
13 | import java.io.InputStream;
14 | import java.util.ArrayList;
15 | import java.util.LinkedHashMap;
16 | import java.util.Map;
17 |
18 | public class YamlToPipeline {
19 | public String generatePipeline(@Nonnull InputStream yamlScriptInputStream,
20 | @CheckForNull GitConfig gitConfig,
21 | @Nonnull TaskListener listener)
22 | throws ConversionException {
23 | ArrayList scriptLines = new ArrayList<>();
24 |
25 | YamlPipeline yamlPipeline = loadYaml(yamlScriptInputStream, listener);
26 |
27 | scriptLines.add("pipeline {");
28 |
29 | // Adding outer agent and tools section
30 | scriptLines.addAll(PipelineGenerator.convert("agent", yamlPipeline.getAgent()));
31 |
32 | // Adding environment
33 | scriptLines.addAll(PipelineGenerator.convert("environment", yamlPipeline.getEnvironment()));
34 |
35 | // Stages begin
36 | scriptLines.add("stages {");
37 |
38 | if (yamlPipeline.getSteps() != null) {
39 | scriptLines.add("stage('Build') {");
40 | scriptLines.add("steps {");
41 |
42 | for (LinkedHashMap step : yamlPipeline.getSteps()) {
43 | for (Map.Entry entry : step.entrySet()) {
44 | scriptLines.addAll(PipelineGenerator.convert("step", entry.getValue()));
45 | }
46 | }
47 |
48 | scriptLines.add("}");
49 | scriptLines.add("}");
50 | }
51 |
52 | if (yamlPipeline.getStages() != null) {
53 | for (Stage stage : yamlPipeline.getStages()) {
54 | scriptLines.addAll(PipelineGenerator.convert("stage", stage));
55 | }
56 | }
57 |
58 | // Archive artifacts stage
59 | scriptLines.addAll(PipelineGenerator.convert("archiveArtifactStage", yamlPipeline.getArchiveArtifacts()));
60 |
61 | ReportsAndArtifactsInfo reportsAndArtifactsInfo = new ReportsAndArtifactsInfo();
62 | reportsAndArtifactsInfo.setArtifactPublishingConfig(yamlPipeline.getArtifactPublishingConfig());
63 | reportsAndArtifactsInfo.setReports(yamlPipeline.getReports());
64 | reportsAndArtifactsInfo.setPublishArtifacts(yamlPipeline.getPublishArtifacts());
65 |
66 | scriptLines.addAll(PipelineGenerator.convert("publishReportsAndArtifactsStage", reportsAndArtifactsInfo));
67 |
68 | // This stage will always be generated at last, because if anyone of the above stage fails then we
69 | // will not push the code to target branch
70 | if (yamlPipeline.getConfiguration() != null && yamlPipeline.getConfiguration().isPushPrOnSuccess()) {
71 | if (gitConfig == null) {
72 | throw new ConversionException("Git Configuration is not defined, but it is required for the Git Push");
73 | }
74 | scriptLines.addAll(PipelineGenerator.convert("gitPushStage", gitConfig));
75 | }
76 |
77 | scriptLines.add("}");
78 |
79 | scriptLines.addAll(PipelineGenerator.convert("post", yamlPipeline.getPost()));
80 |
81 | for (CustomPipelineSection section : yamlPipeline.getSections()) {
82 | scriptLines.addAll(PipelineGenerator.convert(section));
83 | }
84 |
85 | scriptLines.add("}");
86 | return PipelineGenerator.autoAddTabs(scriptLines);
87 | }
88 |
89 | public YamlPipeline loadYaml(InputStream yamlScriptInputStream, TaskListener listener) {
90 | CustomClassLoaderConstructor constructor = new CustomClassLoaderConstructor(this.getClass().getClassLoader());
91 | Yaml yaml = new Yaml(constructor);
92 | YamlPipeline yamlPipeline = yaml.loadAs(yamlScriptInputStream, YamlPipeline.class);
93 |
94 | if (yamlPipeline.getStages() != null && yamlPipeline.getSteps() != null) {
95 | throw new IllegalStateException("Only one of 'steps' or 'stages' must be present in the YAML file.");
96 | }
97 |
98 | return yamlPipeline;
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/src/main/java/io/jenkins/plugins/sprp/exception/ConversionException.java:
--------------------------------------------------------------------------------
1 | package io.jenkins.plugins.sprp.exception;
2 |
3 | public class ConversionException extends Exception {
4 |
5 | public ConversionException(String message) {
6 | super(message);
7 | }
8 |
9 | public ConversionException(String message, Throwable cause) {
10 | super(message, cause);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/io/jenkins/plugins/sprp/generators/AgentGenerator.java:
--------------------------------------------------------------------------------
1 | package io.jenkins.plugins.sprp.generators;
2 |
3 | import hudson.Extension;
4 | import io.jenkins.plugins.sprp.models.Agent;
5 | import org.jenkinsci.Symbol;
6 | import org.kohsuke.accmod.Restricted;
7 | import org.kohsuke.accmod.restrictions.NoExternalUse;
8 |
9 | import javax.annotation.Nonnull;
10 | import java.util.ArrayList;
11 | import java.util.LinkedHashMap;
12 | import java.util.List;
13 | import java.util.Map;
14 |
15 | @Extension
16 | @Symbol("agent")
17 | @Restricted(NoExternalUse.class)
18 | public class AgentGenerator extends PipelineGenerator {
19 |
20 | @Nonnull
21 | @Override
22 | public List toPipeline(Agent agent) {
23 | ArrayList agentLines = new ArrayList<>();
24 |
25 | if (agent == null) {
26 | agentLines.add("agent any");
27 | } else if (agent.getAnyOrNone() != null)
28 | agentLines.add("agent " + agent.getAnyOrNone());
29 | else if(agent.isNone()) {
30 | agentLines.add("agent none");
31 | }
32 | else {
33 |
34 | if (agent.getDockerImage() != null) {
35 | agentLines.add("agent {");
36 | agentLines.add("docker {");
37 | agentLines.add("image '" + agent.getDockerImage() + "'");
38 |
39 | if (agent.getArgs() != null) {
40 | agentLines.add("args '" + agent.getArgs() + "'");
41 | }
42 |
43 | agentLines.add("alwaysPull " + agent.getAlwaysPull() + "");
44 | agentLines.addAll(getCommonOptionsOfAgent(agent));
45 | agentLines.add("}");
46 | agentLines.add("}");
47 | } else if (agent.getDockerfile() != null) {
48 | agentLines.add("agent {");
49 | agentLines.add("dockerfile {");
50 | agentLines.add("filename '" + agent.getDockerfile() + "'");
51 |
52 | if (agent.getDir() != null) {
53 | agentLines.add("dir '" + agent.getDir() + "'");
54 | }
55 |
56 | if (agent.getArgs() != null) {
57 | agentLines.add("additionalBuildArgs '" + agent.getArgs() + "'");
58 | }
59 |
60 | agentLines.addAll(getCommonOptionsOfAgent(agent));
61 | agentLines.add("}");
62 | agentLines.add("}");
63 | } else if (agent.getLabel() != null || agent.getCustomWorkspace() != null) {
64 | agentLines.add("agent {");
65 | agentLines.add("node {");
66 | agentLines.addAll(getCommonOptionsOfAgent(agent));
67 | agentLines.add("}");
68 | agentLines.add("}");
69 | } else {
70 | agentLines.add("agent any");
71 | }
72 | }
73 |
74 | if (agent != null) {
75 | agentLines.addAll(getTools(agent.getTools()));
76 | }
77 |
78 | return agentLines;
79 | }
80 |
81 | @Override
82 | public boolean canConvert(@Nonnull Object object) {
83 | return object instanceof Agent;
84 | }
85 |
86 | private List getCommonOptionsOfAgent(Agent agent) {
87 | ArrayList snippetLines = new ArrayList<>();
88 |
89 | if (agent.getLabel() != null) {
90 | snippetLines.add("label '" + agent.getLabel() + "'");
91 | }
92 |
93 | if (agent.getCustomWorkspace() != null) {
94 | snippetLines.add("customWorkspace '" + agent.getCustomWorkspace() + "'");
95 | }
96 |
97 | if (agent.getDockerfile() != null || agent.getDockerImage() != null) {
98 | snippetLines.add("reuseNode " + agent.getReuseNode() + "");
99 | }
100 |
101 | return snippetLines;
102 | }
103 |
104 | private List getTools(LinkedHashMap tools) {
105 | ArrayList snippetLines = new ArrayList<>();
106 |
107 | if (tools == null) {
108 | return snippetLines;
109 | }
110 |
111 | snippetLines.add("tools {");
112 |
113 | for (Map.Entry entry : tools.entrySet()) {
114 | snippetLines.add(entry.getKey() + " '" + entry.getValue() + "'");
115 | }
116 |
117 | snippetLines.add("}");
118 |
119 | return snippetLines;
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/src/main/java/io/jenkins/plugins/sprp/generators/ArchiveArtifactStageGenerator.java:
--------------------------------------------------------------------------------
1 | package io.jenkins.plugins.sprp.generators;
2 |
3 | import hudson.Extension;
4 | import org.jenkinsci.Symbol;
5 | import org.kohsuke.accmod.Restricted;
6 | import org.kohsuke.accmod.restrictions.NoExternalUse;
7 |
8 | import javax.annotation.Nonnull;
9 | import java.util.ArrayList;
10 | import java.util.List;
11 |
12 | @Extension
13 | @Symbol("archiveArtifactStage")
14 | @Restricted(NoExternalUse.class)
15 | public class ArchiveArtifactStageGenerator extends PipelineGenerator> {
16 |
17 | @Nonnull
18 | @Override
19 | public List toPipeline(ArrayList paths) {
20 | ArrayList snippetLines = new ArrayList<>();
21 |
22 | if (paths == null) {
23 | return snippetLines;
24 | }
25 |
26 | snippetLines.add("stage('Archive artifacts') {");
27 | snippetLines.add("steps {");
28 |
29 | for (String p : paths) {
30 | snippetLines.add("archiveArtifacts artifacts: '" + p + "'");
31 | }
32 |
33 | snippetLines.add("}");
34 | snippetLines.add("}");
35 |
36 | return snippetLines;
37 | }
38 |
39 | @Override
40 | public boolean canConvert(@Nonnull Object object) {
41 | if(object instanceof ArrayList>){
42 | return ((ArrayList) object).get(0) instanceof String;
43 | }
44 |
45 | return false;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/io/jenkins/plugins/sprp/generators/CustomSectionGenerator.java:
--------------------------------------------------------------------------------
1 | package io.jenkins.plugins.sprp.generators;
2 |
3 | import hudson.Extension;
4 | import io.jenkins.plugins.sprp.exception.ConversionException;
5 | import io.jenkins.plugins.sprp.models.CustomPipelineSection;
6 | import org.jenkinsci.Symbol;
7 | import org.kohsuke.accmod.Restricted;
8 | import org.kohsuke.accmod.restrictions.NoExternalUse;
9 |
10 | import javax.annotation.CheckForNull;
11 | import javax.annotation.Nonnull;
12 | import java.util.Collections;
13 | import java.util.List;
14 |
15 | /**
16 | * Converter for {@link CustomPipelineSection}.
17 | * @author Oleg Nenashev
18 | */
19 | @Extension
20 | @Symbol("custom")
21 | @Restricted(NoExternalUse.class)
22 | public class CustomSectionGenerator extends PipelineGenerator {
23 |
24 | @Nonnull
25 | @Override
26 | public List toPipeline(@CheckForNull CustomPipelineSection section)
27 | throws ConversionException {
28 | if (section == null) {
29 | return Collections.emptyList();
30 | }
31 |
32 | PipelineGenerator gen = PipelineGenerator.lookupForName(section.getName());
33 | if (gen == null) {
34 | throw new ConversionException("No converter for Custom Pipeline Section: " + section.getName());
35 | }
36 | return gen.toPipeline(section.getData());
37 | }
38 |
39 | @Override
40 | public boolean canConvert(@Nonnull Object object) {
41 | return object instanceof CustomPipelineSection;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/io/jenkins/plugins/sprp/generators/EnvironmentGenerator.java:
--------------------------------------------------------------------------------
1 | package io.jenkins.plugins.sprp.generators;
2 |
3 | import hudson.Extension;
4 | import io.jenkins.plugins.sprp.models.Credential;
5 | import io.jenkins.plugins.sprp.models.Environment;
6 | import org.jenkinsci.Symbol;
7 | import org.kohsuke.accmod.Restricted;
8 | import org.kohsuke.accmod.restrictions.NoExternalUse;
9 |
10 | import javax.annotation.Nonnull;
11 | import java.util.ArrayList;
12 | import java.util.List;
13 | import java.util.Map;
14 |
15 | @Extension
16 | @Symbol("environment")
17 | @Restricted(NoExternalUse.class)
18 | public class EnvironmentGenerator extends PipelineGenerator {
19 |
20 | @Nonnull
21 | @Override
22 | public List toPipeline(Environment environment) {
23 | ArrayList snippetLines = new ArrayList<>();
24 |
25 | if (environment == null || (environment.getVariables() == null && environment.getCredentials() == null)) {
26 | return snippetLines;
27 | }
28 |
29 | snippetLines.add("environment {");
30 |
31 | for (Map.Entry entry : environment.getVariables().entrySet()) {
32 | snippetLines.add(entry.getKey() + " = '" + entry.getValue() + "'");
33 | }
34 |
35 | for (Credential credential : environment.getCredentials()) {
36 | snippetLines.add(credential.getVariable() + " = credentials('" + credential.getCredentialId() + "')");
37 | }
38 |
39 | snippetLines.add("}");
40 |
41 | return snippetLines;
42 | }
43 |
44 | @Override
45 | public boolean canConvert(@Nonnull Object object) {
46 | return object instanceof Environment;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/io/jenkins/plugins/sprp/generators/GitPushStageGenerator.java:
--------------------------------------------------------------------------------
1 | package io.jenkins.plugins.sprp.generators;
2 |
3 | import hudson.Extension;
4 | import io.jenkins.plugins.sprp.git.GitConfig;
5 | import org.jenkinsci.Symbol;
6 | import org.kohsuke.accmod.Restricted;
7 | import org.kohsuke.accmod.restrictions.NoExternalUse;
8 |
9 | import javax.annotation.Nonnull;
10 | import java.util.ArrayList;
11 | import java.util.List;
12 |
13 | @Extension
14 | @Symbol("gitPushStage")
15 | @Restricted(NoExternalUse.class)
16 | public class GitPushStageGenerator extends PipelineGenerator {
17 |
18 | @Nonnull
19 | @Override
20 | public List toPipeline(GitConfig gitConfig) {
21 | ArrayList snippetLines = new ArrayList<>();
22 |
23 | if(gitConfig == null){
24 | return snippetLines;
25 | }
26 |
27 | snippetLines.add("stage('Git Push') {");
28 | snippetLines.add("steps {");
29 | snippetLines.add("gitPush " +
30 | "credentialId: \"" + gitConfig.getCredentialsId() + "\"," +
31 | "url: \"" + gitConfig.getGitUrl() + "\"," +
32 | "branch: \"" + gitConfig.getGitBranch() + "\"");
33 |
34 | snippetLines.add("}");
35 | snippetLines.add("}");
36 | return snippetLines;
37 | }
38 |
39 | @Override
40 | public boolean canConvert(@Nonnull Object object) {
41 | return object instanceof GitConfig;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/io/jenkins/plugins/sprp/generators/PipelineGenerator.java:
--------------------------------------------------------------------------------
1 | package io.jenkins.plugins.sprp.generators;
2 |
3 | import hudson.ExtensionList;
4 | import hudson.ExtensionPoint;
5 | import io.jenkins.plugins.sprp.exception.ConversionException;
6 | import org.apache.commons.lang.StringUtils;
7 | import org.apache.log4j.Logger;
8 | import org.jenkinsci.plugins.structs.SymbolLookup;
9 |
10 | import javax.annotation.CheckForNull;
11 | import javax.annotation.Nonnull;
12 | import java.util.ArrayList;
13 | import java.util.List;
14 |
15 |
16 | public abstract class PipelineGenerator implements ExtensionPoint {
17 | static private Logger logger = Logger.getLogger(PipelineGenerator.class.getClass().getName());
18 |
19 | @Nonnull
20 | public abstract List toPipeline(@CheckForNull T object) throws ConversionException;
21 |
22 | public abstract boolean canConvert(@Nonnull Object object);
23 |
24 | public static ExtensionList all() {
25 | return ExtensionList.lookup(PipelineGenerator.class);
26 | }
27 |
28 | @CheckForNull
29 | public static PipelineGenerator lookupForName(@Nonnull String name) {
30 | return SymbolLookup.get().find(PipelineGenerator.class, name);
31 | }
32 |
33 | @CheckForNull
34 | public static T lookupConverter(Class clazz) {
35 | for (PipelineGenerator gen : all()) {
36 | if (clazz.equals(gen.getClass())) {
37 | return clazz.cast(gen);
38 | }
39 | }
40 | return null;
41 | }
42 |
43 | @Nonnull
44 | public static T lookupConverterOrFail(Class clazz)
45 | throws ConversionException {
46 | T converter = lookupConverter(clazz);
47 | if (converter == null) {
48 | throw new ConversionException("Failed to find converter: " + clazz);
49 | }
50 | return converter;
51 | }
52 |
53 | @CheckForNull
54 | public static PipelineGenerator lookup(@Nonnull Object object) {
55 | for (PipelineGenerator gen : all()) {
56 | if (gen.canConvert(object)) {
57 | return gen;
58 | }
59 | }
60 | return null;
61 | }
62 |
63 | @Nonnull
64 | public static List convert(@Nonnull Object object) throws ConversionException {
65 | PipelineGenerator gen = lookup(object);
66 | if (gen == null) {
67 | // TODO: add better diagnostics (field matching)
68 | throw new ConversionException("Cannot find converter for the object: " + object.getClass());
69 | }
70 | //TODO: handle raw type conversion risks
71 | return gen.toPipeline(object);
72 | }
73 |
74 | @Nonnull
75 | public static List convert(@Nonnull String converterName, @CheckForNull Object object) throws ConversionException {
76 | PipelineGenerator gen = lookupForName(converterName);
77 | if (gen == null) {
78 | // TODO: add better diagnostics (field matching)
79 | throw new ConversionException("Cannot find converter for the type: " + converterName);
80 | }
81 | //TODO: handle raw type conversion risks
82 | return gen.toPipeline(object);
83 | }
84 |
85 | public static String autoAddTabs(ArrayList snippetLines) {
86 | int numOfTabs = 0;
87 | StringBuilder snippet = new StringBuilder();
88 |
89 | for (String str : snippetLines) {
90 | if (str.startsWith("}")) {
91 | numOfTabs--;
92 | }
93 |
94 | if (numOfTabs != 0) {
95 | snippet.append(StringUtils.repeat("\t", numOfTabs));
96 | }
97 |
98 | snippet.append(str).append("\n");
99 |
100 | if (str.endsWith("{")) {
101 | numOfTabs++;
102 | }
103 | }
104 |
105 | return snippet.toString();
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/src/main/java/io/jenkins/plugins/sprp/generators/PostGenerator.java:
--------------------------------------------------------------------------------
1 | package io.jenkins.plugins.sprp.generators;
2 |
3 | import hudson.Extension;
4 | import io.jenkins.plugins.sprp.exception.ConversionException;
5 | import io.jenkins.plugins.sprp.models.Post;
6 | import io.jenkins.plugins.sprp.models.Step;
7 | import org.jenkinsci.Symbol;
8 | import org.kohsuke.accmod.Restricted;
9 | import org.kohsuke.accmod.restrictions.NoExternalUse;
10 |
11 | import javax.annotation.Nonnull;
12 | import java.util.ArrayList;
13 | import java.util.LinkedHashMap;
14 | import java.util.List;
15 | import java.util.Map;
16 |
17 | @Extension
18 | @Symbol("post")
19 | @Restricted(NoExternalUse.class)
20 | public class PostGenerator extends PipelineGenerator {
21 |
22 | @Nonnull
23 | @Override
24 | public List toPipeline(Post postSection) throws ConversionException {
25 | ArrayList snippetLines = new ArrayList<>();
26 |
27 | if (postSection == null) {
28 | return snippetLines;
29 | }
30 |
31 | snippetLines.add("post {");
32 |
33 | snippetLines.addAll(getPostConditionSnippetIfNonNull("always", postSection.getAlways()));
34 | snippetLines.addAll(getPostConditionSnippetIfNonNull("changed", postSection.getChanged()));
35 | snippetLines.addAll(getPostConditionSnippetIfNonNull("fixed", postSection.getFixed()));
36 | snippetLines.addAll(getPostConditionSnippetIfNonNull("regression", postSection.getRegression()));
37 | snippetLines.addAll(getPostConditionSnippetIfNonNull("aborted", postSection.getAborted()));
38 | snippetLines.addAll(getPostConditionSnippetIfNonNull("failure", postSection.getFailure()));
39 | snippetLines.addAll(getPostConditionSnippetIfNonNull("success", postSection.getSuccess()));
40 | snippetLines.addAll(getPostConditionSnippetIfNonNull("unstable", postSection.getUnstable()));
41 | snippetLines.addAll(getPostConditionSnippetIfNonNull("cleanup", postSection.getCleanup()));
42 |
43 | snippetLines.add("}");
44 |
45 | return snippetLines;
46 | }
47 |
48 | @Override
49 | public boolean canConvert(@Nonnull Object object) {
50 | return object instanceof Post;
51 | }
52 |
53 | private List getPostConditionSnippetIfNonNull(String postCondition, ArrayList> steps)
54 | throws ConversionException {
55 | ArrayList snippetLines = new ArrayList<>();
56 | if (steps != null) {
57 | snippetLines.add(postCondition + " {");
58 |
59 | for (LinkedHashMap step : steps) {
60 | for (Map.Entry entry : step.entrySet()) {
61 | snippetLines.addAll(PipelineGenerator.convert("step", entry.getValue()));
62 | }
63 | }
64 |
65 | snippetLines.add("}");
66 | }
67 |
68 | return snippetLines;
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/io/jenkins/plugins/sprp/generators/PublishReportsAndArtifactsStageGenerator.java:
--------------------------------------------------------------------------------
1 | package io.jenkins.plugins.sprp.generators;
2 |
3 | import hudson.Extension;
4 | import io.jenkins.plugins.sprp.models.ArtifactPublishingConfig;
5 | import io.jenkins.plugins.sprp.models.ReportsAndArtifactsInfo;
6 | import org.jenkinsci.Symbol;
7 | import org.kohsuke.accmod.Restricted;
8 | import org.kohsuke.accmod.restrictions.NoExternalUse;
9 |
10 | import javax.annotation.Nonnull;
11 | import java.util.ArrayList;
12 | import java.util.HashMap;
13 | import java.util.List;
14 |
15 | @Extension
16 | @Symbol("publishReportsAndArtifactsStage")
17 | @Restricted(NoExternalUse.class)
18 | public class PublishReportsAndArtifactsStageGenerator extends PipelineGenerator {
19 |
20 | @Nonnull
21 | @Override
22 | public List toPipeline(ReportsAndArtifactsInfo reportsAndArtifactsInfo) {
23 | ArrayList snippetLines = new ArrayList<>();
24 |
25 | if(reportsAndArtifactsInfo == null){
26 | return snippetLines;
27 | }
28 |
29 | ArrayList reports = reportsAndArtifactsInfo.getReports();
30 | ArtifactPublishingConfig config = reportsAndArtifactsInfo.getArtifactPublishingConfig();
31 | ArrayList> publishArtifacts = reportsAndArtifactsInfo.getPublishArtifacts();
32 |
33 |
34 |
35 | if (reports == null && config == null) {
36 | return snippetLines;
37 | }
38 |
39 | snippetLines.add("stage('Publish reports & artifacts') {");
40 | snippetLines.add("steps {");
41 |
42 | if (reports != null) {
43 | snippetLines.addAll(getPublishReportSnippet(reports));
44 | }
45 |
46 | if (config != null) {
47 | snippetLines.add("" + "withCredentials([file(credentialsId: '" + config.getCredentialId() + "', variable: 'FILE')]) {");
48 |
49 | for (HashMap artifact : publishArtifacts) {
50 | snippetLines.add("sh 'scp -i $FILE " + artifact.get("from") + " " + config.getUser() + "@" + config.getHost() + ":" + artifact.get("to") + "'");
51 | }
52 |
53 | snippetLines.add("}");
54 | }
55 |
56 | snippetLines.add("}");
57 | snippetLines.add("}");
58 |
59 | return snippetLines;
60 | }
61 |
62 | @Override
63 | public boolean canConvert(@Nonnull Object object) {
64 | return object instanceof PublishReportsAndArtifactsStageGenerator;
65 | }
66 |
67 | private List getPublishReportSnippet(ArrayList paths) {
68 | ArrayList snippetLines = new ArrayList<>();
69 |
70 | for (String p : paths) {
71 | snippetLines.add("junit '" + p + "'");
72 | }
73 |
74 | return snippetLines;
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/main/java/io/jenkins/plugins/sprp/generators/StageGenerator.java:
--------------------------------------------------------------------------------
1 | package io.jenkins.plugins.sprp.generators;
2 |
3 | import hudson.Extension;
4 | import io.jenkins.plugins.sprp.exception.ConversionException;
5 | import io.jenkins.plugins.sprp.models.Agent;
6 | import io.jenkins.plugins.sprp.models.Stage;
7 | import io.jenkins.plugins.sprp.models.Step;
8 | import org.jenkinsci.Symbol;
9 | import org.kohsuke.accmod.Restricted;
10 | import org.kohsuke.accmod.restrictions.NoExternalUse;
11 |
12 | import javax.annotation.Nonnull;
13 | import java.util.ArrayList;
14 | import java.util.LinkedHashMap;
15 | import java.util.List;
16 | import java.util.Map;
17 |
18 | @Extension
19 | @Symbol("stage")
20 | @Restricted(NoExternalUse.class)
21 | public class StageGenerator extends PipelineGenerator {
22 |
23 | @Nonnull
24 | @Override
25 | public List toPipeline(Stage stage) throws ConversionException {
26 | ArrayList snippetLines = new ArrayList<>();
27 |
28 | if(stage == null){
29 | return snippetLines;
30 | }
31 |
32 | String stageName = stage.getName();
33 |
34 | snippetLines.add("stage('" + stageName + "') {");
35 |
36 | final Agent agent = stage.getAgent();
37 | if (agent != null && !agent.getAnyOrNone().equals("any")) {
38 | AgentGenerator gen = lookupConverterOrFail(AgentGenerator.class);
39 | snippetLines.addAll(gen.toPipeline(agent));
40 | }
41 |
42 | snippetLines.add("steps {");
43 |
44 | for (LinkedHashMap step : stage.getSteps()) {
45 | for (Map.Entry entry : step.entrySet()) {
46 | snippetLines.addAll(PipelineGenerator.convert("step", entry.getValue()));
47 | }
48 | }
49 |
50 | snippetLines.add("}");
51 |
52 | snippetLines.addAll(PipelineGenerator.convert("post", stage.getPost()));
53 |
54 | snippetLines.add("}");
55 |
56 | return snippetLines;
57 | }
58 |
59 | @Override
60 | public boolean canConvert(@Nonnull Object object) {
61 | return object instanceof Stage;
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/main/java/io/jenkins/plugins/sprp/generators/StepGenerator.java:
--------------------------------------------------------------------------------
1 | package io.jenkins.plugins.sprp.generators;
2 |
3 | import hudson.Extension;
4 | import hudson.model.Descriptor;
5 | import io.jenkins.plugins.casc.ConfigurationContext;
6 | import io.jenkins.plugins.casc.Configurator;
7 | import io.jenkins.plugins.casc.ConfiguratorException;
8 | import io.jenkins.plugins.casc.ConfiguratorRegistry;
9 | import io.jenkins.plugins.casc.impl.configurators.DataBoundConfigurator;
10 | import io.jenkins.plugins.casc.model.Mapping;
11 | import io.jenkins.plugins.casc.model.Scalar;
12 | import io.jenkins.plugins.casc.model.Sequence;
13 | import io.jenkins.plugins.sprp.exception.ConversionException;
14 | import io.jenkins.plugins.sprp.models.Step;
15 | import org.jenkinsci.Symbol;
16 | import org.jenkinsci.plugins.workflow.cps.Snippetizer;
17 | import org.jenkinsci.plugins.workflow.steps.StepDescriptor;
18 | import org.kohsuke.accmod.Restricted;
19 | import org.kohsuke.accmod.restrictions.NoExternalUse;
20 |
21 | import javax.annotation.Nonnull;
22 | import java.lang.reflect.Constructor;
23 | import java.lang.reflect.InvocationTargetException;
24 | import java.util.ArrayList;
25 | import java.util.List;
26 | import java.util.Map;
27 |
28 | @Extension
29 | @Symbol("step")
30 | @Restricted(NoExternalUse.class)
31 | public class StepGenerator extends PipelineGenerator {
32 |
33 | @Nonnull
34 | @Override
35 | public List toPipeline(Step step) throws ConversionException {
36 | ArrayList pipelineStep = new ArrayList<>();
37 | pipelineStep.add(stepConfigurator(step));
38 | return pipelineStep;
39 | }
40 |
41 | @Override
42 | public boolean canConvert(@Nonnull Object object) {
43 | return object instanceof Step;
44 | }
45 |
46 | private String stepConfigurator(Step step) throws ConversionException {
47 | if (step == null)
48 | return "\n";
49 |
50 | String snippet;
51 | Object stepObject;
52 | Descriptor stepDescriptor = StepDescriptor.byFunctionName(step.getStepName());
53 |
54 | if (stepDescriptor == null) {
55 | throw new ConversionException("No step exist with the name " + step.getStepName());
56 | }
57 |
58 | Class clazz = stepDescriptor.clazz;
59 |
60 | if (step.getDefaultParameter() != null) {
61 |
62 | Constructor constructor = DataBoundConfigurator.getDataBoundConstructor(clazz);
63 |
64 | if (constructor != null && constructor.getParameterCount() == 1) {
65 | try {
66 | stepObject = constructor.newInstance(step.getDefaultParameter());
67 | } catch (InvocationTargetException e) {
68 | throw new ConversionException("Error while invoking constructor " + constructor.getName() +
69 | " with parameter type " + constructor.getParameters()[0].getType(), e);
70 | } catch (InstantiationException e) {
71 | throw new ConversionException("Error while instantiating" + step.getStepName() +
72 | " step object with constructor " + constructor.getName(), e);
73 | } catch (IllegalAccessException e) {
74 | throw new ConversionException("Unknown error while instantiating an object of step " +
75 | step.getStepName() + " with default parameter");
76 | }
77 | } else {
78 | throw new ConversionException("No suitable constructor found for default parameter of step "
79 | + step.getStepName());
80 | }
81 | } else {
82 | Mapping mapping = doMappingForMap(step.getParameters());
83 |
84 | ConfigurationContext context = new ConfigurationContext(ConfiguratorRegistry.get());
85 | Configurator configurator = ConfiguratorRegistry.get().lookup(clazz);
86 |
87 | if (configurator != null) {
88 | try {
89 | stepObject = configurator.configure(mapping, context);
90 | } catch (ConfiguratorException e) {
91 | throw new ConversionException("JCasC plugin is not able to configure the step + " + step.getStepName(), e);
92 | }
93 | } else {
94 | throw new ConversionException("No step with name '" + step.getStepName() +
95 | "' exist. Have you installed required plugin.");
96 | }
97 | }
98 |
99 | snippet = Snippetizer.object2Groovy(stepObject);
100 | return snippet;
101 | }
102 |
103 | private Mapping doMappingForMap(Map map) throws ConversionException {
104 | Mapping mapping = new Mapping();
105 |
106 | for (Map.Entry entry : map.entrySet()) {
107 | if (entry.getValue() instanceof Map) {
108 | mapping.put(entry.getKey(), doMappingForMap((Map) entry.getValue()));
109 | } else if (entry.getValue() instanceof List) {
110 | mapping.put(entry.getKey(), doMappingForSequence((List) entry.getValue()));
111 | } else {
112 | mapping.put(entry.getKey(), doMappingForScalar(entry.getValue()));
113 | }
114 | }
115 |
116 | return mapping;
117 | }
118 |
119 | private Scalar doMappingForScalar(Object object) throws ConversionException {
120 | Scalar scalar;
121 |
122 | if (object instanceof String) {
123 | scalar = new Scalar((String) object);
124 | } else if (object instanceof Number) {
125 | scalar = new Scalar((Number) object);
126 | } else if (object instanceof Enum) {
127 | scalar = new Scalar((Enum) object);
128 | } else if (object instanceof Boolean) {
129 | scalar = new Scalar((Boolean) object);
130 | } else {
131 | throw new ConversionException(object.getClass() + " is not supported.");
132 | }
133 |
134 | return scalar;
135 | }
136 |
137 | private Sequence doMappingForSequence(List