cwl2click 0.2.0__tar.gz

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,43 @@
1
+ # Copyright 2025 Terradue
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ name: docs
16
+ on:
17
+ push:
18
+ branches:
19
+ - docs
20
+ - develop
21
+ - main
22
+ paths:
23
+ # Only rebuild website when docs have changed
24
+ - 'README.md'
25
+ - 'docs/**'
26
+ - 'mkdocs.yaml'
27
+ - .github/**
28
+
29
+ jobs:
30
+ deploy:
31
+ runs-on: ubuntu-latest
32
+ steps:
33
+ - name: Checkout master
34
+ uses: actions/checkout@v4
35
+
36
+ - name: Set up Python 3.x
37
+ uses: actions/setup-python@v5
38
+ with:
39
+ python-version: 3.x
40
+ - run: pip install mkdocs-material mkdocs-mermaid2-plugin mkdocs-jupyter legacy-cgi pdocs
41
+ # - run: pip install .
42
+ # - run: pdocs as_markdown --output_dir ./docs/api/latest --exclude_source --overwrite transpiler_mate
43
+ - run: mkdocs gh-deploy --force
@@ -0,0 +1,70 @@
1
+ # Copyright 2025 Terradue
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ name: publish-to-pypi
16
+
17
+ on:
18
+ push:
19
+ branches: [develop, main]
20
+ paths:
21
+ - 'src/**'
22
+ - '.github/workflows/package.yaml'
23
+ - 'tests/**'
24
+
25
+ release:
26
+ types: [published]
27
+ pull_request:
28
+ branches: [develop, main]
29
+ paths:
30
+ - 'src/**'
31
+
32
+ permissions:
33
+ contents: read
34
+ packages: write
35
+
36
+ jobs:
37
+
38
+ deploy:
39
+ runs-on: ubuntu-latest
40
+ environment: release
41
+ permissions:
42
+ id-token: write # IMPORTANT: this permission is mandatory for trusted publishing
43
+
44
+ steps:
45
+ - uses: actions/checkout@v4
46
+ - name: Set up Python
47
+ uses: actions/setup-python@v5
48
+ with:
49
+ python-version: '3.10'
50
+ cache: 'pip'
51
+ - name: Install dependencies
52
+ run: |
53
+ # python -m pip install --upgrade pip
54
+ pip install hatch
55
+ - name: Build package
56
+ run: |
57
+ hatch build
58
+ - name: Test package
59
+ run: |
60
+ hatch test
61
+ - name: Publish package distributions to PyPI (main)
62
+ if: github.ref == 'refs/heads/main'
63
+ uses: pypa/gh-action-pypi-publish@release/v1
64
+ with:
65
+ repository-url: https://upload.pypi.org/legacy/
66
+ - name: Publish package distributions to PyPI (develop)
67
+ if: github.ref != 'refs/heads/main'
68
+ uses: pypa/gh-action-pypi-publish@release/v1
69
+ with:
70
+ repository-url: https://test.pypi.org/legacy/
@@ -0,0 +1,7 @@
1
+ .pydevproject
2
+ .project
3
+ __pycache__
4
+ /.pytest_cache/
5
+ .settings
6
+ .venv
7
+ docs/api
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
cwl2click-0.2.0/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ cwl2click
2
+ Copyright 2025 Terradue.
3
+
4
+ This product includes software developed at
5
+ The Apache Software Foundation (http://www.apache.org/).
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.4
2
+ Name: cwl2click
3
+ Version: 0.2.0
4
+ Project-URL: Documentation, https://github.com/Terradue/cwl2click#readme
5
+ Project-URL: Issues, https://github.com/Terradue/cwl2click/issues
6
+ Project-URL: Source, https://github.com/Terradue/cwl2click
7
+ Author-email: Simone Tripodi <simone.tripodi@terradue.com>, Fabrice Brito <fabrice.brito@terradue.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ License-File: NOTICE
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Programming Language :: Python :: 3.8
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: Implementation :: CPython
19
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
20
+ Requires-Python: >=3.8
21
+ Requires-Dist: click>=8.2.1
22
+ Requires-Dist: cwl-loader>=0.14.0
23
+ Requires-Dist: cwl-utils>=0.40
24
+ Requires-Dist: jinja2>=3.1.6
25
+ Requires-Dist: loguru
26
+ Description-Content-Type: text/markdown
27
+
28
+ # cwl2click
29
+
30
+ Boostrap a Python CLI using `click` from a CWL `CommandLineTool`(s).
31
+
32
+ [![PyPI - Version](https://img.shields.io/pypi/v/cwl2click.svg)](https://pypi.org/project/cwl2click)
33
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/cwl2click.svg)](https://pypi.org/project/cwl2click)
34
+
35
+ -----
36
+
37
+ ## Table of Contents
38
+
39
+ - [Installation](#installation)
40
+ - [License](#license)
41
+
42
+ ## Installation
43
+
44
+ ```console
45
+ pip install cwl2click
46
+ ```
47
+
48
+ ## License
49
+
50
+ `cwl2click` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
@@ -0,0 +1,23 @@
1
+ # cwl2click
2
+
3
+ Boostrap a Python CLI using `click` from a CWL `CommandLineTool`(s).
4
+
5
+ [![PyPI - Version](https://img.shields.io/pypi/v/cwl2click.svg)](https://pypi.org/project/cwl2click)
6
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/cwl2click.svg)](https://pypi.org/project/cwl2click)
7
+
8
+ -----
9
+
10
+ ## Table of Contents
11
+
12
+ - [Installation](#installation)
13
+ - [License](#license)
14
+
15
+ ## Installation
16
+
17
+ ```console
18
+ pip install cwl2click
19
+ ```
20
+
21
+ ## License
22
+
23
+ `cwl2click` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
@@ -0,0 +1,76 @@
1
+ # Adopters recommendations
2
+
3
+ ## On CWL
4
+
5
+ When submitting CWL document(s) to `cwl2click`, please mind the following constraints:
6
+
7
+ - `CommandLineTool`s only will be taken in consideration;
8
+ - The `click.Command` name is derived from `baseCommand` and `arguments` declarations, accepting the patterns below:
9
+
10
+ both `baseCommand` and `arguments` are declared
11
+
12
+ ```yaml
13
+ baseCommand: runner
14
+ arguments:
15
+ - crop-cli
16
+ ```
17
+
18
+ ```yaml
19
+ baseCommand:
20
+ - runner
21
+ arguments:
22
+ - crop-cli
23
+ ```
24
+
25
+ `baseCommand` only is declared:
26
+
27
+ ```
28
+ baseCommand:
29
+ - runner
30
+ - crop-cli
31
+ arguments: []
32
+ ```
33
+
34
+ In all the cases above, the resulting `click.Command` will result being `crop-cli`
35
+ Any other case will force `cwl2click` not able to detect the command name, then an exception will be thrown.
36
+
37
+ - `click.Option` parameter declaration is derived from `inputs[].inputBinding.prefix`, i.e.
38
+
39
+ ```yaml
40
+ - class: CommandLineTool
41
+ id: crop
42
+ baseCommand:
43
+ - runner
44
+ arguments:
45
+ - crop-cli
46
+ inputs:
47
+ item:
48
+ type: Directory
49
+ inputBinding:
50
+ prefix: --input-item
51
+ ...
52
+ ```
53
+
54
+ will result to
55
+
56
+ ```python
57
+ cli.add_command(
58
+ click.Command(
59
+ name="crop-cli",
60
+ callback=crop_command,
61
+ params=[
62
+ click.Option(
63
+ ["--input-item"],
64
+ "item",
65
+ type=click.Path(path_type=Path, exists=True, readable=True, resolve_path=True, file_okay=False, dir_okay=True),
66
+ multiple=False,
67
+ required=True,
68
+ is_flag=False,
69
+
70
+ ),
71
+ ...
72
+ ```
73
+
74
+ If `inputs[].inputBinding.prefix` is not found, it will follow up on `--{{inputs[].id}}`
75
+
76
+ - Users have in charge to implement all the callback functions - `click2cwl` generates the interface only, concrete implementations must be provided by implementors!
@@ -0,0 +1,16 @@
1
+ # Crosswalk
2
+
3
+ | CWL Type | Click Type |
4
+ |-----------------------------------------------------------------------------------|---------------------------------------------------|
5
+ | `int` | `click.INT` |
6
+ | `long` | `click.INT` |
7
+ | `double` | `click.FLOAT` |
8
+ | `float` | `click.FLOAT` |
9
+ | `boolean` | `click.BOOL` |
10
+ | `string` | `click.STRING` |
11
+ | `Directory` | `click.Path(file_okay=False, dir_okay=True)` |
12
+ | `File` | `click.Path(file_okay=True, dir_okay=False)` |
13
+ | `https://raw.githubusercontent.com/eoap/schemas/main/string_format.yaml#DateTime` | `click.DateTime(formats=['%Y-%m- %d T%H:%M:%S'])` |
14
+ | `https://raw.githubusercontent.com/eoap/schemas/main/string_format.yaml#UUID` | `click.UUID` |
15
+
16
+ Any other unsupported type is threated like a `click.STRING`.
@@ -0,0 +1,162 @@
1
+ # Execution
2
+
3
+ Based on a KISS approach:
4
+
5
+ ```
6
+ $ cwl2click --help
7
+ Usage: cwl2click [OPTIONS] WORKFLOW
8
+
9
+ Options:
10
+ --workflow-id TEXT ID(s) of the CommandLineTools
11
+ --output PATH Output directory path [required]
12
+ --help Show this message and exit.
13
+ ```
14
+
15
+ Users can generate `Click` code by executing:
16
+
17
+ ```
18
+ cwl2click \
19
+ --output /path/to/your-project/src/your-module \
20
+ https://raw.githubusercontent.com/eoap/application-package-patterns/refs/heads/main/cwl-workflow/pattern-12.cwl
21
+ ```
22
+
23
+ and monitor the execution:
24
+
25
+ ```
26
+ 2025-12-24 10:55:57.416 | DEBUG | cwl_loader:load_cwl_from_location:228 - Loading CWL document from https://raw.githubusercontent.com/eoap/application-package-patterns/refs/heads/main/cwl-workflow/pattern-12.cwl...
27
+ 2025-12-24 10:55:57.664 | DEBUG | cwl_loader:_load_cwl_from_stream:231 - Reading stream from https://raw.githubusercontent.com/eoap/application-package-patterns/refs/heads/main/cwl-workflow/pattern-12.cwl...
28
+ 2025-12-24 10:55:57.689 | DEBUG | cwl_loader:load_cwl_from_stream:203 - CWL data of type <class 'ruamel.yaml.comments.CommentedMap'> successfully loaded from stream
29
+ 2025-12-24 10:55:57.689 | DEBUG | cwl_loader:load_cwl_from_yaml:143 - No needs to update the Raw CWL document since it targets already the v1.2
30
+ 2025-12-24 10:55:57.689 | DEBUG | cwl_loader:load_cwl_from_yaml:145 - Parsing the raw CWL document to the CWL Utils DOM...
31
+ 2025-12-24 10:56:04.305 | DEBUG | cwl_loader:load_cwl_from_yaml:158 - Raw CWL document successfully parsed to the CWL Utils DOM!
32
+ 2025-12-24 10:56:04.305 | DEBUG | cwl_loader:load_cwl_from_yaml:160 - Dereferencing the steps[].run...
33
+ 2025-12-24 10:56:04.305 | DEBUG | cwl_loader:_on_process:78 - Checking if https://raw.githubusercontent.com/eoap/application-package-patterns/refs/heads/main/cwl-workflow/pattern-12.cwl#crop must be externally imported...
34
+ 2025-12-24 10:56:04.305 | DEBUG | cwl_loader:_on_process:82 - run_url: https://raw.githubusercontent.com/eoap/application-package-patterns/refs/heads/main/cwl-workflow/pattern-12.cwl - uri: https://raw.githubusercontent.com/eoap/application-package-patterns/refs/heads/main/cwl-workflow/pattern-12.cwl
35
+ 2025-12-24 10:56:04.305 | DEBUG | cwl_loader:_on_process:78 - Checking if https://raw.githubusercontent.com/eoap/application-package-patterns/refs/heads/main/cwl-workflow/pattern-12.cwl#norm_diff must be externally imported...
36
+ 2025-12-24 10:56:04.305 | DEBUG | cwl_loader:_on_process:82 - run_url: https://raw.githubusercontent.com/eoap/application-package-patterns/refs/heads/main/cwl-workflow/pattern-12.cwl - uri: https://raw.githubusercontent.com/eoap/application-package-patterns/refs/heads/main/cwl-workflow/pattern-12.cwl
37
+ 2025-12-24 10:56:04.305 | DEBUG | cwl_loader:_on_process:78 - Checking if https://raw.githubusercontent.com/eoap/application-package-patterns/refs/heads/main/cwl-workflow/pattern-12.cwl#otsu must be externally imported...
38
+ 2025-12-24 10:56:04.305 | DEBUG | cwl_loader:_on_process:82 - run_url: https://raw.githubusercontent.com/eoap/application-package-patterns/refs/heads/main/cwl-workflow/pattern-12.cwl - uri: https://raw.githubusercontent.com/eoap/application-package-patterns/refs/heads/main/cwl-workflow/pattern-12.cwl
39
+ 2025-12-24 10:56:04.305 | DEBUG | cwl_loader:load_cwl_from_yaml:167 - steps[].run successfully dereferenced! Dereferencing the FQNs...
40
+ 2025-12-24 10:56:04.305 | DEBUG | cwl_loader:load_cwl_from_yaml:171 - CWL document successfully dereferenced! Now verifying steps[].run integrity...
41
+ 2025-12-24 10:56:04.305 | DEBUG | cwl_loader:load_cwl_from_yaml:175 - All steps[].run link are resolvable!
42
+ 2025-12-24 10:56:04.305 | DEBUG | cwl_loader:load_cwl_from_yaml:178 - Sorting Process instances by dependencies....
43
+ 2025-12-24 10:56:04.305 | DEBUG | cwl_loader:load_cwl_from_yaml:180 - Sorting process is over.
44
+ 2025-12-24 10:56:04.305 | DEBUG | cwl_loader:_load_cwl_from_stream:240 - Stream from https://raw.githubusercontent.com/eoap/application-package-patterns/refs/heads/main/cwl-workflow/pattern-12.cwl successfully load!
45
+ 2025-12-24 10:56:04.305 | DEBUG | cwl2click.cli:main:89 - Input CWL Document from https://raw.githubusercontent.com/eoap/application-package-patterns/refs/heads/main/cwl-workflow/pattern-12.cwl is a $graph:
46
+ 2025-12-24 10:56:04.305 | DEBUG | cwl2click.cli:_add_if_eligible:72 - * Checking 'norm_diff'...
47
+ 2025-12-24 10:56:04.305 | DEBUG | cwl2click.cli:_add_if_eligible:74 - 'norm_diff' is a CommandLineTool instance
48
+ 2025-12-24 10:56:04.305 | DEBUG | cwl2click.cli:_add_if_eligible:83 - Include list not defined, processing 'norm_diff'
49
+ 2025-12-24 10:56:04.305 | DEBUG | cwl2click.cli:_add_if_eligible:72 - * Checking 'otsu'...
50
+ 2025-12-24 10:56:04.305 | DEBUG | cwl2click.cli:_add_if_eligible:74 - 'otsu' is a CommandLineTool instance
51
+ 2025-12-24 10:56:04.305 | DEBUG | cwl2click.cli:_add_if_eligible:83 - Include list not defined, processing 'otsu'
52
+ 2025-12-24 10:56:04.305 | DEBUG | cwl2click.cli:_add_if_eligible:72 - * Checking 'crop'...
53
+ 2025-12-24 10:56:04.305 | DEBUG | cwl2click.cli:_add_if_eligible:74 - 'crop' is a CommandLineTool instance
54
+ 2025-12-24 10:56:04.305 | DEBUG | cwl2click.cli:_add_if_eligible:83 - Include list not defined, processing 'crop'
55
+ 2025-12-24 10:56:04.306 | DEBUG | cwl2click.cli:_add_if_eligible:72 - * Checking 'pattern-12'...
56
+ 2025-12-24 10:56:04.306 | WARNING | cwl2click.cli:_add_if_eligible:86 - 'pattern-12' is not a CommandLineTool instance, discarding
57
+ 2025-12-24 10:56:04.306 | INFO | cwl2click.cli:main:101 - ------------------------------------------------------------------------
58
+ 2025-12-24 10:56:04.306 | DEBUG | cwl2click.cli:main:102 - Processing CommadLineTools ['norm_diff', 'otsu', 'crop']
59
+ 2025-12-24 10:56:04.306 | DEBUG | cwl2click.cli:main:110 - https://raw.githubusercontent.com/eoap/application-package-patterns/refs/heads/main/cwl-workflow/pattern-12.cwl was parsed from a URL, normalizing...
60
+ 2025-12-24 10:56:04.309 | DEBUG | cwl2click:to_click_type:94 - Converting <cwl_utils.parser.cwl_v1_2.CommandInputArraySchema object at 0x7ce30a43bf40> CWL type to the related Click type...
61
+ 2025-12-24 10:56:04.309 | DEBUG | cwl2click:to_click_type:94 - Converting Directory CWL type to the related Click type...
62
+ 2025-12-24 10:56:04.309 | DEBUG | cwl2click:to_click_type:94 - Converting https://raw.githubusercontent.com/eoap/schemas/main/string_format.yaml#URI CWL type to the related Click type...
63
+ 2025-12-24 10:56:04.309 | DEBUG | cwl2click:to_click_type:94 - Converting Directory CWL type to the related Click type...
64
+ 2025-12-24 10:56:04.309 | DEBUG | cwl2click:to_click_type:94 - Converting Directory CWL type to the related Click type...
65
+ 2025-12-24 10:56:04.309 | DEBUG | cwl2click:to_click_type:94 - Converting https://raw.githubusercontent.com/eoap/schemas/main/string_format.yaml#URI CWL type to the related Click type...
66
+ 2025-12-24 10:56:04.309 | DEBUG | cwl2click:to_click_type:94 - Converting Directory CWL type to the related Click type...
67
+ 2025-12-24 10:56:04.309 | DEBUG | cwl2click:to_click_type:94 - Converting https://raw.githubusercontent.com/eoap/schemas/main/ogc.yaml#BBox CWL type to the related Click type...
68
+ 2025-12-24 10:56:04.309 | DEBUG | cwl2click:to_click_type:94 - Converting https://raw.githubusercontent.com/eoap/schemas/main/ogc.yaml#BBox CWL type to the related Click type...
69
+ 2025-12-24 10:56:04.309 | DEBUG | cwl2click:to_click_type:94 - Converting string CWL type to the related Click type...
70
+ 2025-12-24 10:56:04.309 | DEBUG | cwl2click:to_click_type:94 - Converting https://raw.githubusercontent.com/eoap/schemas/main/string_format.yaml#URI CWL type to the related Click type...
71
+ 2025-12-24 10:56:04.310 | SUCCESS | cwl2click.cli:main:128 - 'https://raw.githubusercontent.com/eoap/application-package-patterns/refs/heads/main/cwl-workflow/pattern-12.cwl' successfully converted to Click Python application in '/path/to/your-project/src/your-module/pattern-12.py'.
72
+ 2025-12-24 10:56:04.310 | INFO | cwl2click.cli:main:130 - ------------------------------------------------------------------------
73
+ 2025-12-24 10:56:04.310 | SUCCESS | cwl2click.cli:main:131 - BUILD SUCCESS
74
+ 2025-12-24 10:56:04.310 | INFO | cwl2click.cli:main:139 - ------------------------------------------------------------------------
75
+ 2025-12-24 10:56:04.310 | INFO | cwl2click.cli:main:140 - Total time: 6.8937 seconds
76
+ 2025-12-24 10:56:04.310 | INFO | cwl2click.cli:main:141 - Finished at: 2025-12-24T10:56:04.310
77
+ ```
78
+
79
+ As reported in the `SUCCESS` logging message, the `Click` application is serialized to the `/path/to/your-project/src/your-module/pattern-12.py` file:
80
+
81
+ ```pyton
82
+ # File generated by cwl2click v0.30.0
83
+ # timestamp: 2025-12-24T10:56:04.309
84
+
85
+ from norm_diff_impl import execute as norm_diff_command
86
+ from otsu_impl import execute as otsu_command
87
+ from crop_impl import execute as crop_command
88
+
89
+ from pathlib import Path
90
+
91
+ import click
92
+
93
+ @click.group()
94
+ def cli() -> None:
95
+ pass
96
+
97
+ cli.add_command(
98
+ click.Command(
99
+ name="ndi-cli",
100
+ callback=norm_diff_command,
101
+ # CODE OMITTED FOR SIMPLICITY
102
+ )
103
+ )
104
+
105
+ cli.add_command(
106
+ click.Command(
107
+ name="otsu-cli",
108
+ callback=otsu_command,
109
+ params=[
110
+ click.Option(
111
+ ["--input-ndi"],
112
+ "raster",
113
+ type=click.Path(path_type=Path, exists=True, readable=True, resolve_path=True, file_okay=False, dir_okay=True),
114
+ multiple=False,
115
+ required=True,
116
+ is_flag=False,
117
+
118
+ ),
119
+ click.Option(
120
+ ["--item"],
121
+ "item",
122
+ type=click.Path(path_type=Path, exists=True, readable=True, resolve_path=True, file_okay=False, dir_okay=True),
123
+ multiple=False,
124
+ required=True,
125
+ is_flag=False,
126
+
127
+ ),
128
+ click.Option(
129
+ ["None"],
130
+ "collection",
131
+ type=click.STRING,
132
+ multiple=False,
133
+ required=True,
134
+ is_flag=False,
135
+
136
+ ),
137
+ ]
138
+ )
139
+ )
140
+
141
+ cli.add_command(
142
+ click.Command(
143
+ name="crop-cli",
144
+ callback=crop_command,
145
+ # CODE OMITTED FOR SIMPLICITY
146
+ )
147
+ )
148
+ ```
149
+
150
+ #### Include list
151
+
152
+ By default, `cwl2click` will transpile _all_ the `CommandLineTool` found instances inside the CWL, in case users are interested in just one sub-set, can use the `--workflow-id` option:
153
+
154
+ ```
155
+ cwl2click \
156
+ --output /path/to/your-project/src/your-module \
157
+ --workflow-id crop \
158
+ --workflow-id otsu \
159
+ https://raw.githubusercontent.com/eoap/application-package-patterns/refs/heads/main/cwl-workflow/pattern-12.cwl
160
+ ```
161
+
162
+ By executing this example, `ndi-cli` won't be generated.
@@ -0,0 +1,17 @@
1
+ # Introduction
2
+
3
+ ## Rationale
4
+
5
+ Taking inspiration from the [Contract-First Development](https://openpracticelibrary.com/practice/contract-first-development/) approach, this small tool aims to simplify the development of Python CLI with [Click](https://click.palletsprojects.com/en/stable/) to be integrated in [CWL Command Line Tool](https://www.commonwl.org/user_guide/topics/command-line-tool.html).
6
+
7
+ Defining the Interface(s) first in the CWL not only speeds up the development, it also alleviates developers to manually write the boilerplate code to implement the CLIs.
8
+
9
+ ## Usage
10
+
11
+ ### Installation
12
+
13
+ `cwl2click` is published on [Pypi](https://pypi.org/project/cwl2click/), users just have to execute
14
+
15
+ ```
16
+ pip install cwl2click
17
+ ```
@@ -0,0 +1,83 @@
1
+ # Copyright 2025 Terradue
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ site_name: CWL2Click
16
+ site_url: https://eoepca.github.io/cwl2ckick/
17
+ site_author: Fabrice Brito, Simone Tripodi
18
+ repo_url: https://github.com/Terradue/cwl2ckick/
19
+ repo_name: Terradue/cwl2ckick
20
+
21
+ theme:
22
+ logo: imgs/icon-eoap.png
23
+ name: material
24
+
25
+ palette:
26
+ - media: "(prefers-color-scheme: light)"
27
+ scheme: default
28
+ toggle:
29
+ icon: material/toggle-switch-off-outline
30
+ name: Switch to dark mode
31
+ - media: "(prefers-color-scheme: dark)"
32
+ scheme: slate
33
+ toggle:
34
+ icon: material/toggle-switch
35
+ name: Switch to light mode
36
+
37
+ plugins:
38
+ - search
39
+ - mermaid2:
40
+ version: 11.4.1
41
+ - mkdocs-jupyter:
42
+ execute: true
43
+ show_input: True
44
+ no_input: False
45
+
46
+ markdown_extensions:
47
+ - pymdownx.details
48
+ - abbr
49
+ - admonition
50
+ - footnotes
51
+ - pymdownx.caret
52
+ - pymdownx.mark
53
+ - pymdownx.tilde
54
+ - pymdownx.arithmatex:
55
+ generic: true
56
+ - pymdownx.superfences
57
+ - pymdownx.tabbed
58
+ - pymdownx.superfences:
59
+ custom_fences:
60
+ - name: mermaid
61
+ class: mermaid
62
+ format: !!python/name:pymdownx.superfences.fence_div_format
63
+ - attr_list
64
+ - pymdownx.snippets:
65
+ base_path: './'
66
+ - pymdownx.highlight:
67
+ line_spans: __span
68
+
69
+ extra_css:
70
+ - styles/css/app.css
71
+
72
+ extra_javascript:
73
+ - javascripts/config.js
74
+ - https://polyfill.io/v3/polyfill.min.js?features=es6
75
+ - https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js
76
+
77
+ nav:
78
+ - index.md
79
+ - execution.md
80
+ - adopters.md
81
+ - crosswalk.md
82
+
83
+ copyright: <a href="https://www.apache.org/licenses/LICENSE-2.0"><img src="https://img.shields.io/badge/license-Apache%20License%202.0-blue"" alt="Apache License, Version 2.0" /></a>
@@ -0,0 +1,71 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "cwl2click"
7
+ dynamic = ["version"]
8
+ description = ''
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = "MIT"
12
+ keywords = []
13
+ authors = [
14
+ { name = "Simone Tripodi", email = "simone.tripodi@terradue.com" },
15
+ { name = "Fabrice Brito", email = "fabrice.brito@terradue.com" }
16
+ ]
17
+ classifiers = [
18
+ "Development Status :: 4 - Beta",
19
+ "Programming Language :: Python",
20
+ "Programming Language :: Python :: 3.8",
21
+ "Programming Language :: Python :: 3.9",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: Implementation :: CPython",
26
+ "Programming Language :: Python :: Implementation :: PyPy",
27
+ ]
28
+ dependencies = [
29
+ "cwl-loader>=0.14.0",
30
+ "cwl-utils>=0.40",
31
+ "click>=8.2.1",
32
+ "Jinja2>=3.1.6",
33
+ "loguru"
34
+ ]
35
+
36
+ [project.scripts]
37
+ cwl2click = "cwl2click.cli:main"
38
+
39
+ [project.urls]
40
+ Documentation = "https://github.com/Terradue/cwl2click#readme"
41
+ Issues = "https://github.com/Terradue/cwl2click/issues"
42
+ Source = "https://github.com/Terradue/cwl2click"
43
+
44
+ [tool.hatch.version]
45
+ path = "src/cwl2click/__about__.py"
46
+
47
+ [tool.hatch.envs.types]
48
+ extra-dependencies = [
49
+ "mypy>=1.0.0",
50
+ ]
51
+ [tool.hatch.envs.types.scripts]
52
+ check = "mypy --install-types --non-interactive {args:src/cwl2click tests}"
53
+
54
+ [tool.coverage.run]
55
+ source_pkgs = ["cwl2click", "tests"]
56
+ branch = true
57
+ parallel = true
58
+ omit = [
59
+ "src/cwl2click/__about__.py",
60
+ ]
61
+
62
+ [tool.coverage.paths]
63
+ cwl2click = ["src/cwl2click", "*/cwl2click/src/cwl2click"]
64
+ tests = ["tests", "*/cwl2click/tests"]
65
+
66
+ [tool.coverage.report]
67
+ exclude_lines = [
68
+ "no cov",
69
+ "if __name__ == .__main__.:",
70
+ "if TYPE_CHECKING:",
71
+ ]
@@ -0,0 +1,15 @@
1
+ # Copyright 2025 Terradue
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ __version__ = "0.2.0"
@@ -0,0 +1,201 @@
1
+ # Copyright 2025 Terradue
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from cwl_loader.utils import (
16
+ contains_process,
17
+ search_process
18
+ )
19
+ from cwl_utils.parser import CommandLineTool
20
+ from datetime import datetime
21
+ from jinja2 import (
22
+ Environment,
23
+ PackageLoader
24
+ )
25
+ from loguru import logger
26
+ from importlib.metadata import (
27
+ version,
28
+ PackageNotFoundError
29
+ )
30
+ from typing import (
31
+ Any,
32
+ List,
33
+ Mapping,
34
+ TextIO
35
+ )
36
+
37
+ import re
38
+ import time
39
+
40
+ pattern = re.compile(r'(?<!^)(?=[A-Z])')
41
+
42
+ def to_snake_case(name: str) -> str:
43
+ return pattern.sub('_', name.replace('-', '_')).lower()
44
+
45
+ def is_nullable(
46
+ type_: Any
47
+ ) -> bool:
48
+ return isinstance(type_, list) and "null" in type_
49
+
50
+ def is_required(
51
+ type_: Any
52
+ ) -> bool:
53
+ return not is_nullable(type_)
54
+
55
+ def is_flag(
56
+ type_: Any
57
+ ) -> bool:
58
+ return isinstance(type_, list) and "boolean" in type_ or "boolean" == type_
59
+
60
+ def get_command_name(
61
+ clt: CommandLineTool
62
+ ) -> str:
63
+ if clt.baseCommand:
64
+ if isinstance(clt.baseCommand, list):
65
+ if len(clt.baseCommand) > 1:
66
+ return clt.baseCommand[1]
67
+
68
+ if clt.arguments:
69
+ if isinstance(clt.arguments, list):
70
+ return clt.arguments[0]
71
+ return str(clt.arguments)
72
+
73
+ raise Exception(f"Impossible to extract the sub-command from CommandLineTool '{clt.id}':\n- `clt.baseCommand` contains the tool only or is empty;\n-no `clt.arguments` provided.")
74
+ raise Exception(f"CommandLineTool '{clt.id}' does not define a 'baseCommand' property, impossible to map it to a `click.Command`")
75
+
76
+ _STRING_FORMAT_SCHEMA_: str = "https://raw.githubusercontent.com/eoap/schemas/main/string_format.yaml"
77
+
78
+ _CWL_CLICK_MAP_: Mapping[Any, str] = {
79
+ "int": "INT",
80
+ "long": "INT",
81
+ "double": "FLOAT",
82
+ "float": "FLOAT",
83
+ "boolean": "BOOL",
84
+ "string": "STRING",
85
+ "Directory": "Path(path_type=Path, exists=True, readable=True, resolve_path=True, file_okay=False, dir_okay=True)",
86
+ "File": "Path(path_type=Path, exists=True, readable=True, resolve_path=True, file_okay=True, dir_okay=False)",
87
+ f"{_STRING_FORMAT_SCHEMA_}#DateTime": "DateTime(formats=['%Y-%m-%dT%H:%M:%S'])",
88
+ f"{_STRING_FORMAT_SCHEMA_}#UUID": "UUID"
89
+ }
90
+
91
+ def to_click_type(
92
+ type_: Any
93
+ ) -> str:
94
+ logger.debug(f"Converting {type_} CWL type to the related Click type...")
95
+
96
+ key = None
97
+
98
+ if isinstance(type_, str):
99
+ key = type_
100
+ elif isinstance(type_, list):
101
+ key = [item_type for item_type in type_ if "null" != item_type][0]
102
+ elif hasattr(type_, "class_"):
103
+ key = type_.class_ # type: ignore
104
+ elif hasattr(type_, "symbols"):
105
+ return f"Choice({list(map(lambda symbol : symbol.split('/')[-1], type_.symbols))})"
106
+
107
+ if key and not isinstance(key, str) and hasattr(key, "symbols"):
108
+ return f"Choice({list(map(lambda symbol : symbol.split('/')[-1], key.symbols))})"
109
+
110
+ return _CWL_CLICK_MAP_.get(key, "STRING")
111
+
112
+ _CWL_PYTHON_MAP_: Mapping[Any, str] = {
113
+ "int": "int",
114
+ "long": "int",
115
+ "double": "float",
116
+ "float": "float",
117
+ "boolean": "bool",
118
+ "string": "str",
119
+ "Directory": "str",
120
+ "File": "str"
121
+ }
122
+
123
+ def to_python_type(
124
+ type_
125
+ ) -> str:
126
+ logger.debug(f"Converting {type_} CWL type to the related Python type...")
127
+
128
+ key: str
129
+ if isinstance(type_, str):
130
+ key = type_
131
+ elif isinstance(type_, list):
132
+ key = [item_type for item_type in type_ if "null" != item_type][0]
133
+ else:
134
+ key = type_.class_ # type: ignore
135
+
136
+ if "enum" == key:
137
+ key = "string"
138
+
139
+ return _CWL_PYTHON_MAP_.get(key, str(type_))
140
+
141
+ def _to_mapping(
142
+ functions: List[Any]
143
+ ) -> Mapping[str, Any]:
144
+ mapping: Mapping[str, Any] = {}
145
+
146
+ for function in functions:
147
+ mapping[function.__name__] = function
148
+
149
+ return mapping
150
+
151
+ def is_array(
152
+ type_
153
+ ) -> bool:
154
+ return isinstance(type, list) or hasattr(type_, "class_") and "array" == type_.class_
155
+
156
+ def _get_version() -> str:
157
+ try:
158
+ return version("cwl2puml")
159
+ except PackageNotFoundError:
160
+ return 'N/A'
161
+
162
+ _jinja_environment = Environment(
163
+ loader=PackageLoader(
164
+ package_name='cwl2click'
165
+ )
166
+ )
167
+ _jinja_environment.filters.update(
168
+ _to_mapping(
169
+ [
170
+ get_command_name,
171
+ is_array,
172
+ is_flag,
173
+ is_required,
174
+ is_nullable,
175
+ to_click_type,
176
+ to_python_type,
177
+ to_snake_case,
178
+ ]
179
+ )
180
+ )
181
+ _jinja_environment.tests.update(
182
+ _to_mapping(
183
+ [ is_array ]
184
+ )
185
+ )
186
+
187
+ def to_click(
188
+ command_line_tools: List[CommandLineTool],
189
+ module_name: str,
190
+ output_stream: TextIO
191
+ ):
192
+ template = _jinja_environment.get_template(f"command_line_tools.py")
193
+
194
+ output_stream.write(
195
+ template.render(
196
+ version=_get_version(),
197
+ timestamp=datetime.fromtimestamp(time.time()).isoformat(timespec='milliseconds'),
198
+ module_name=module_name,
199
+ command_line_tools=command_line_tools
200
+ )
201
+ )
@@ -0,0 +1,143 @@
1
+ # Copyright 2025 Terradue
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from . import (
16
+ to_click,
17
+ to_snake_case
18
+ )
19
+ from cwl_loader import load_cwl_from_location
20
+ from cwl_utils.parser import (
21
+ Process,
22
+ CommandLineTool
23
+ )
24
+ from datetime import datetime
25
+ from loguru import logger
26
+ from pathlib import Path
27
+ from os.path import (
28
+ basename,
29
+ splitext
30
+ )
31
+ from typing import List
32
+ from urllib.parse import urlparse
33
+
34
+ import click
35
+ import time
36
+
37
+ @click.command()
38
+ @click.argument(
39
+ 'workflow',
40
+ required=True
41
+ )
42
+ @click.option(
43
+ '--workflow-id',
44
+ required=False,
45
+ type=click.STRING,
46
+ multiple=True,
47
+ help="ID(s) of the CommandLineTools"
48
+ )
49
+ @click.option(
50
+ '--output',
51
+ type=click.Path(
52
+ path_type=Path
53
+ ),
54
+ required=True,
55
+ default=Path("."),
56
+ help="Output directory path"
57
+ )
58
+ def main(
59
+ workflow: str,
60
+ workflow_id: List[str],
61
+ output: Path
62
+ ):
63
+ start_time = time.time()
64
+
65
+ click.STRING
66
+
67
+ cwl_document: Process | List[Process] = load_cwl_from_location(path=workflow)
68
+
69
+ clts: List[CommandLineTool] = []
70
+
71
+ def _add_if_eligible(process: Process):
72
+ logger.debug(f"* Checking '{process.id}'...")
73
+ if isinstance(process, CommandLineTool):
74
+ logger.debug(f" '{process.id}' is a CommandLineTool instance")
75
+ if workflow_id:
76
+ logger.debug(f" Checking if '{process.id}' is in the include list {workflow_id}...")
77
+ if process.id in workflow_id:
78
+ logger.debug(f" '{process.id}' is in the include list {workflow_id}, processing")
79
+ clts.append(process)
80
+ else:
81
+ logger.warning(f" '{process.id}' not in the include list, discarding")
82
+ else:
83
+ logger.debug(f" Include list not defined, processing '{process.id}'")
84
+ clts.append(process)
85
+ else:
86
+ logger.warning(f" '{process.id}' is not a CommandLineTool instance, discarding")
87
+
88
+ if isinstance(cwl_document, list):
89
+ logger.debug(f"Input CWL Document from {workflow} is a $graph:")
90
+ for process in cwl_document:
91
+ _add_if_eligible(process)
92
+ else:
93
+ _add_if_eligible(cwl_document)
94
+
95
+ if not clts:
96
+ if workflow_id:
97
+ logger.error(f"{workflow_id} not found on in input CWL document, only {list(map(lambda p: p.id, cwl_document)) if isinstance(cwl_document, list) else [cwl_document.id]} available.")
98
+ else:
99
+ logger.error("No CommandLineTool(s) found in input CWL document")
100
+ else:
101
+ logger.info('------------------------------------------------------------------------')
102
+ logger.debug(f"Processing CommadLineTools {[clt.id for clt in clts]}")
103
+
104
+ output.mkdir(parents=True, exist_ok=True)
105
+
106
+ file_name = basename(workflow)
107
+ try:
108
+ result = urlparse(workflow)
109
+ if result.scheme in ('http', 'https') and result.netloc:
110
+ logger.debug(f"{workflow} was parsed from a URL, normalizing...")
111
+ file_name = basename(result.path)
112
+ else:
113
+ logger.debug(f"{workflow} was not parsed from a URL")
114
+ except Exception:
115
+ logger.debug(f"{workflow} was not parsed from a URL")
116
+
117
+ file_name, _ = splitext(file_name)
118
+
119
+ target: Path = Path(output, f"{to_snake_case(file_name)}.py")
120
+ module_name = basename(target.parent.absolute().as_posix())
121
+
122
+ try:
123
+ with target.open('w') as stream:
124
+ to_click(
125
+ command_line_tools=clts,
126
+ module_name=module_name,
127
+ output_stream=stream
128
+ )
129
+
130
+ logger.success(f"'{workflow}' successfully converted to Click Python application in '{target.absolute()}'.")
131
+
132
+ logger.info('------------------------------------------------------------------------')
133
+ logger.success('BUILD SUCCESS')
134
+ except Exception as e:
135
+ logger.info('------------------------------------------------------------------------')
136
+ logger.error('BUILD FAILED')
137
+ logger.error(f"An unexpected error occurred while generating {target}: {e}")
138
+
139
+ end_time = time.time()
140
+
141
+ logger.info('------------------------------------------------------------------------')
142
+ logger.info(f"Total time: {end_time - start_time:.4f} seconds")
143
+ logger.info(f"Finished at: {datetime.fromtimestamp(end_time).isoformat(timespec='milliseconds')}")
@@ -0,0 +1,31 @@
1
+ # File generated by cwl2click v{{ version }}
2
+ # timestamp: {{ timestamp }}
3
+
4
+ {% for clt in command_line_tools %}from {{module_name}}.{{clt.id | to_snake_case}}_impl import execute as {{clt.id | to_snake_case}}_command
5
+ {% endfor %}
6
+ from pathlib import Path
7
+
8
+ import click
9
+
10
+ @click.group()
11
+ def cli() -> None:
12
+ pass
13
+ {% for clt in command_line_tools %}
14
+ cli.add_command(
15
+ click.Command(
16
+ name="{{clt | get_command_name}}",
17
+ callback={{clt.id | to_snake_case}}_command,
18
+ params=[
19
+ {% for input in clt.inputs %} click.Option(
20
+ ["{% if input.inputBinding.prefix %}{{input.inputBinding.prefix}}{% else %}--{{input.id}}{% endif %}"],
21
+ "{{input.id}}",
22
+ type=click.{{input.type_ | to_click_type}},
23
+ multiple={{input.type_ | is_array}},
24
+ required={{input.type_ | is_required}},
25
+ is_flag={{input.type_ | is_flag}},{% if input.doc %}
26
+ help="{{input.doc}}",{% endif %}
27
+ ),
28
+ {% endfor %} ]
29
+ )
30
+ )
31
+ {% endfor %}
@@ -0,0 +1,3 @@
1
+ # SPDX-FileCopyrightText: 2025-present stripodi <simone.tripodi@terradue.com>
2
+ #
3
+ # SPDX-License-Identifier: MIT
@@ -0,0 +1,10 @@
1
+ from unittest import TestCase
2
+
3
+ class Testloading(TestCase):
4
+
5
+ def setUp(self):
6
+ pass
7
+
8
+ def test_void(self):
9
+ """ Test with no content."""
10
+ pass