aboutcode.pipeline 0.1.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,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.
@@ -0,0 +1,21 @@
1
+ SPDX-License-Identifier: Apache-2.0
2
+
3
+ http://nexb.com and https://github.com/nexB/scancode.io
4
+ The ScanCode.io software is licensed under the Apache License version 2.0.
5
+ Data generated with ScanCode.io is provided as-is without warranties.
6
+ ScanCode is a trademark of nexB Inc.
7
+
8
+ You may not use this software except in compliance with the License.
9
+ You may obtain a copy of the License at: http://apache.org/licenses/LICENSE-2.0
10
+ Unless required by applicable law or agreed to in writing, software distributed
11
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
12
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
13
+ specific language governing permissions and limitations under the License.
14
+
15
+ Data Generated with ScanCode.io is provided on an "AS IS" BASIS, WITHOUT WARRANTIES
16
+ OR CONDITIONS OF ANY KIND, either express or implied. No content created from
17
+ ScanCode.io should be considered or used as legal advice. Consult an Attorney
18
+ for any legal advice.
19
+
20
+ ScanCode.io is a free software code scanning tool from nexB Inc. and others.
21
+ Visit https://github.com/nexB/scancode.io for support and download.
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.1
2
+ Name: aboutcode.pipeline
3
+ Version: 0.1.0
4
+ Summary: AboutCode Pipeline library. Execute code in steps.
5
+ Keywords: open source,pipeline,scancode
6
+ Author-email: "nexB. Inc. and others" <info@aboutcode.org>
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Software Development
18
+ Classifier: Topic :: Utilities
19
+ Project-URL: Changelog, https://github.com/nexB/scancode.io/tree/main/aboutcode/pipeline/CHANGELOG.md
20
+ Project-URL: Documentation, https://scancodeio.readthedocs.io/
21
+ Project-URL: Homepage, https://github.com/nexB/scancode.io
22
+ Project-URL: Issues, https://github.com/nexB/scancode.io/issues
23
+ Project-URL: Repository, https://github.com/nexB/scancode.io/tree/main/aboutcode/pipeline
24
+
25
+ # `aboutcode.pipeline`
26
+
27
+ Define and run pipelines.
28
+
29
+ ### Install
30
+
31
+ ```bash
32
+ pip install aboutcode.pipeline
33
+ ```
34
+
35
+ ### Define and execute a pipeline
36
+
37
+ ```python
38
+ from aboutcode.pipeline import BasePipeline
39
+
40
+ class PrintMessages(BasePipeline):
41
+ @classmethod
42
+ def steps(cls):
43
+ return (cls.step1,)
44
+
45
+ def step1(self):
46
+ print("Message from step1")
47
+
48
+ PrintMessages().execute()
49
+ ```
50
+
51
+ ### Groups and steps selection
52
+
53
+ ```python
54
+ from aboutcode.pipeline import BasePipeline
55
+ from aboutcode.pipeline import group
56
+
57
+ class PrintMessages(BasePipeline):
58
+ @classmethod
59
+ def steps(cls):
60
+ return (cls.step1, cls.step2)
61
+
62
+ def step1(self):
63
+ print("Message from step1")
64
+
65
+ @group("foo")
66
+ def step2(self):
67
+ print("Message from step2")
68
+
69
+
70
+ # Execute pipeline with group selection
71
+ run = PrintMessages(selected_groups=["foo"])
72
+ exitcode, error = run.execute()
73
+
74
+ # Execute pipeline with steps selection
75
+ run = PrintMessages(selected_steps=["step1"])
76
+ exitcode, error = run.execute()
77
+ ```
78
+
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## Release 0.1.0 (August 9, 2023)
4
+
5
+ * Initial release of the `aboutcode.pipeline` library. [Issue #1351](https://github.com/nexB/scancode.io/issues/1351)
@@ -0,0 +1,53 @@
1
+ # `aboutcode.pipeline`
2
+
3
+ Define and run pipelines.
4
+
5
+ ### Install
6
+
7
+ ```bash
8
+ pip install aboutcode.pipeline
9
+ ```
10
+
11
+ ### Define and execute a pipeline
12
+
13
+ ```python
14
+ from aboutcode.pipeline import BasePipeline
15
+
16
+ class PrintMessages(BasePipeline):
17
+ @classmethod
18
+ def steps(cls):
19
+ return (cls.step1,)
20
+
21
+ def step1(self):
22
+ print("Message from step1")
23
+
24
+ PrintMessages().execute()
25
+ ```
26
+
27
+ ### Groups and steps selection
28
+
29
+ ```python
30
+ from aboutcode.pipeline import BasePipeline
31
+ from aboutcode.pipeline import group
32
+
33
+ class PrintMessages(BasePipeline):
34
+ @classmethod
35
+ def steps(cls):
36
+ return (cls.step1, cls.step2)
37
+
38
+ def step1(self):
39
+ print("Message from step1")
40
+
41
+ @group("foo")
42
+ def step2(self):
43
+ print("Message from step2")
44
+
45
+
46
+ # Execute pipeline with group selection
47
+ run = PrintMessages(selected_groups=["foo"])
48
+ exitcode, error = run.execute()
49
+
50
+ # Execute pipeline with steps selection
51
+ run = PrintMessages(selected_steps=["step1"])
52
+ exitcode, error = run.execute()
53
+ ```
@@ -0,0 +1,29 @@
1
+ # Release instructions for `aboutcode.pipeline`
2
+
3
+ ### Automated release workflow
4
+
5
+ - Create a new `aboutcode.pipeline-release-x.x.x` branch
6
+ - Update the version in:
7
+ - `pipeline-pyproject.toml`
8
+ - `aboutcode/pipeline/__init__.py`
9
+ - Commit and push this branch
10
+ - Create a PR and merge once approved
11
+ - Tag and push to trigger the `pypi-release-aboutcode-pipeline.yml` workflow that
12
+ takes care of building the distribution archives and upload those to pypi::
13
+ ```
14
+ VERSION=x.x.x # <- Set the new version here
15
+ TAG=aboutcode.pipeline/$VERSION
16
+ git tag -a $TAG -m ""
17
+ git push origin $TAG
18
+ ```
19
+
20
+ ### Manual build
21
+
22
+ ```
23
+ cd scancode.io
24
+ source .venv/bin/activate
25
+ pip install flot
26
+ flot --pyproject pipeline-pyproject.toml --sdist --wheel --output-dir dist/
27
+ ```
28
+
29
+ The distribution archives will be available in the local `dist/` directory.
@@ -0,0 +1,317 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ #
3
+ # http://nexb.com and https://github.com/nexB/scancode.io
4
+ # The ScanCode.io software is licensed under the Apache License version 2.0.
5
+ # Data generated with ScanCode.io is provided as-is without warranties.
6
+ # ScanCode is a trademark of nexB Inc.
7
+ #
8
+ # You may not use this software except in compliance with the License.
9
+ # You may obtain a copy of the License at: http://apache.org/licenses/LICENSE-2.0
10
+ # Unless required by applicable law or agreed to in writing, software distributed
11
+ # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
12
+ # CONDITIONS OF ANY KIND, either express or implied. See the License for the
13
+ # specific language governing permissions and limitations under the License.
14
+ #
15
+ # Data Generated with ScanCode.io is provided on an "AS IS" BASIS, WITHOUT WARRANTIES
16
+ # OR CONDITIONS OF ANY KIND, either express or implied. No content created from
17
+ # ScanCode.io should be considered or used as legal advice. Consult an Attorney
18
+ # for any legal advice.
19
+ #
20
+ # ScanCode.io is a free software code scanning tool from nexB Inc. and others.
21
+ # Visit https://github.com/nexB/scancode.io for support and download.
22
+
23
+ import logging
24
+ import traceback
25
+ from datetime import datetime
26
+ from datetime import timezone
27
+ from pydoc import getdoc
28
+ from pydoc import splitdoc
29
+ from timeit import default_timer as timer
30
+
31
+ module_logger = logging.getLogger(__name__)
32
+
33
+ __version__ = "0.1.0"
34
+
35
+
36
+ class PipelineDefinition:
37
+ """
38
+ Encapsulate the code related to a Pipeline definition:
39
+ - Steps
40
+ - Attributes
41
+ - Documentation
42
+ """
43
+
44
+ # Flag indicating if the Pipeline is an add-on, meaning it cannot be run first.
45
+ is_addon = False
46
+
47
+ @classmethod
48
+ def steps(cls):
49
+ raise NotImplementedError
50
+
51
+ @classmethod
52
+ def get_steps(cls, groups=None):
53
+ """
54
+ Return the list of steps defined in the ``steps`` class method.
55
+
56
+ If the optional ``groups`` parameter is provided, only include steps labeled
57
+ with groups that intersect with the provided list. If a step has no groups or
58
+ if ``groups`` is not specified, include the step in the result.
59
+ """
60
+ if not callable(cls.steps):
61
+ raise TypeError("Use a ``steps(cls)`` classmethod to declare the steps.")
62
+
63
+ steps = cls.steps()
64
+
65
+ if initial_steps := cls.get_initial_steps():
66
+ steps = (*initial_steps, *steps)
67
+
68
+ if groups is not None:
69
+ steps = tuple(
70
+ step
71
+ for step in steps
72
+ if not getattr(step, "groups", [])
73
+ or set(getattr(step, "groups")).intersection(groups)
74
+ )
75
+
76
+ return steps
77
+
78
+ @classmethod
79
+ def get_initial_steps(cls):
80
+ """
81
+ Return a tuple of extra initial steps to be run at the start of the pipeline
82
+ execution.
83
+ """
84
+ return
85
+
86
+ @classmethod
87
+ def get_doc(cls):
88
+ """Get the doc string of this pipeline."""
89
+ return getdoc(cls)
90
+
91
+ @classmethod
92
+ def get_graph(cls):
93
+ """Return a graph of steps."""
94
+ return [
95
+ {
96
+ "name": step.__name__,
97
+ "doc": getdoc(step),
98
+ "groups": getattr(step, "groups", []),
99
+ }
100
+ for step in cls.get_steps()
101
+ ]
102
+
103
+ @classmethod
104
+ def get_info(cls):
105
+ """Get a dictionary of combined information data about this pipeline."""
106
+ summary, description = splitdoc(cls.get_doc())
107
+ steps = cls.get_graph()
108
+
109
+ return {
110
+ "summary": summary,
111
+ "description": description,
112
+ "steps": steps,
113
+ "available_groups": cls.get_available_groups(),
114
+ }
115
+
116
+ @classmethod
117
+ def get_summary(cls):
118
+ """Get the doc string summary."""
119
+ return cls.get_info()["summary"]
120
+
121
+ @classmethod
122
+ def get_available_groups(cls):
123
+ return sorted(
124
+ set(
125
+ group_name
126
+ for step in cls.get_steps()
127
+ for group_name in getattr(step, "groups", [])
128
+ )
129
+ )
130
+
131
+
132
+ class PipelineRun:
133
+ """
134
+ Encapsulate the code related to a Pipeline run (execution):
135
+ - Execution context: groups, steps
136
+ - Execution logic
137
+ - Logging
138
+ - Results
139
+ """
140
+
141
+ def __init__(self, selected_groups=None, selected_steps=None):
142
+ """Load the Pipeline class."""
143
+ self.pipeline_class = self.__class__
144
+ self.pipeline_name = self.__class__.__name__
145
+
146
+ self.selected_groups = selected_groups
147
+ self.selected_steps = selected_steps or []
148
+
149
+ self.execution_log = []
150
+ self.current_step = ""
151
+
152
+ def append_to_log(self, message):
153
+ self.execution_log.append(message)
154
+
155
+ def set_current_step(self, message):
156
+ self.current_step = message
157
+
158
+ def log(self, message):
159
+ """Log the given `message` to the current module logger and execution_log."""
160
+ now_local = datetime.now(timezone.utc).astimezone()
161
+ timestamp = now_local.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
162
+ message = f"{timestamp} {message}"
163
+ module_logger.info(message)
164
+ self.append_to_log(message)
165
+
166
+ @staticmethod
167
+ def output_from_exception(exception):
168
+ """Return a formatted error message including the traceback."""
169
+ output = f"{exception}\n\n"
170
+
171
+ if exception.__cause__ and str(exception.__cause__) != str(exception):
172
+ output += f"Cause: {exception.__cause__}\n\n"
173
+
174
+ traceback_formatted = "".join(traceback.format_tb(exception.__traceback__))
175
+ output += f"Traceback:\n{traceback_formatted}"
176
+
177
+ return output
178
+
179
+ def execute(self):
180
+ """Execute each steps in the order defined on this pipeline class."""
181
+ self.log(f"Pipeline [{self.pipeline_name}] starting")
182
+
183
+ steps = self.pipeline_class.get_steps(groups=self.selected_groups)
184
+ steps_count = len(steps)
185
+ pipeline_start_time = timer()
186
+
187
+ for current_index, step in enumerate(steps, start=1):
188
+ step_name = step.__name__
189
+
190
+ if self.selected_steps and step_name not in self.selected_steps:
191
+ self.log(f"Step [{step_name}] skipped")
192
+ continue
193
+
194
+ self.set_current_step(f"{current_index}/{steps_count} {step_name}")
195
+ self.log(f"Step [{step_name}] starting")
196
+ step_start_time = timer()
197
+
198
+ try:
199
+ step(self)
200
+ except Exception as exception:
201
+ self.log("Pipeline failed")
202
+ return 1, self.output_from_exception(exception)
203
+
204
+ step_run_time = timer() - step_start_time
205
+ self.log(f"Step [{step_name}] completed in {humanize_time(step_run_time)}")
206
+
207
+ self.set_current_step("") # Reset the `current_step` field on completion
208
+ pipeline_run_time = timer() - pipeline_start_time
209
+ self.log(f"Pipeline completed in {humanize_time(pipeline_run_time)}")
210
+
211
+ return 0, ""
212
+
213
+
214
+ class BasePipeline(PipelineDefinition, PipelineRun):
215
+ """
216
+ Base class for all pipeline implementations.
217
+ It combines the pipeline definition and execution logics.
218
+ """
219
+
220
+
221
+ def group(*groups):
222
+ """Mark a function as part of a particular group."""
223
+
224
+ def decorator(obj):
225
+ if hasattr(obj, "groups"):
226
+ obj.groups = obj.groups.union(groups)
227
+ else:
228
+ setattr(obj, "groups", set(groups))
229
+ return obj
230
+
231
+ return decorator
232
+
233
+
234
+ def humanize_time(seconds):
235
+ """Convert the provided ``seconds`` number into human-readable time."""
236
+ message = f"{seconds:.0f} seconds"
237
+
238
+ if seconds > 86400:
239
+ message += f" ({seconds / 86400:.1f} days)"
240
+ if seconds > 3600:
241
+ message += f" ({seconds / 3600:.1f} hours)"
242
+ elif seconds > 60:
243
+ message += f" ({seconds / 60:.1f} minutes)"
244
+
245
+ return message
246
+
247
+
248
+ class LoopProgress:
249
+ """
250
+ A context manager for logging progress in loops.
251
+
252
+ Usage::
253
+ total_iterations = 100
254
+ logger = print # Replace with your actual logger function
255
+
256
+ progress = LoopProgress(total_iterations, logger, progress_step=10)
257
+ for item in progress.iter(iterator):
258
+ "Your processing logic here"
259
+
260
+ # As a context manager
261
+ with LoopProgress(total_iterations, logger, progress_step=10) as progress:
262
+ for item in progress.iter(iterator):
263
+ "Your processing logic here"
264
+ """
265
+
266
+ def __init__(self, total_iterations, logger, progress_step=10):
267
+ self.total_iterations = total_iterations
268
+ self.logger = logger
269
+ self.progress_step = progress_step
270
+ self.start_time = timer()
271
+ self.last_logged_progress = 0
272
+ self.current_iteration = 0
273
+
274
+ def get_eta(self, current_progress):
275
+ run_time = timer() - self.start_time
276
+ return round(run_time / current_progress * (100 - current_progress))
277
+
278
+ @property
279
+ def current_progress(self):
280
+ return int((self.current_iteration / self.total_iterations) * 100)
281
+
282
+ @property
283
+ def eta(self):
284
+ run_time = timer() - self.start_time
285
+ return round(run_time / self.current_progress * (100 - self.current_progress))
286
+
287
+ def log_progress(self):
288
+ reasons_to_skip = [
289
+ not self.logger,
290
+ not self.current_iteration > 0,
291
+ self.total_iterations <= self.progress_step,
292
+ ]
293
+ if any(reasons_to_skip):
294
+ return
295
+
296
+ if self.current_progress >= self.last_logged_progress + self.progress_step:
297
+ msg = (
298
+ f"Progress: {self.current_progress}% "
299
+ f"({self.current_iteration}/{self.total_iterations})"
300
+ )
301
+ if eta := self.eta:
302
+ msg += f" ETA: {humanize_time(eta)}"
303
+
304
+ self.logger(msg)
305
+ self.last_logged_progress = self.current_progress
306
+
307
+ def __enter__(self):
308
+ return self
309
+
310
+ def __exit__(self, exc_type, exc_value, traceback):
311
+ pass
312
+
313
+ def iter(self, iterator):
314
+ for item in iterator:
315
+ self.current_iteration += 1
316
+ self.log_progress()
317
+ yield item
@@ -0,0 +1,45 @@
1
+ [build-system]
2
+ requires = ["flot"]
3
+ build-backend = "flot.buildapi"
4
+
5
+ [project]
6
+ name = "aboutcode.pipeline"
7
+ version = "0.1.0"
8
+ description = "AboutCode Pipeline library. Execute code in steps."
9
+ license = { text = "Apache-2.0" }
10
+ readme = "aboutcode/pipeline/README.md"
11
+ requires-python = ">=3.9"
12
+ authors = [ { name = "nexB. Inc. and others", email = "info@aboutcode.org" } ]
13
+ keywords = [
14
+ "open source",
15
+ "pipeline",
16
+ "scancode",
17
+ ]
18
+ classifiers = [
19
+ "Development Status :: 4 - Beta",
20
+ "Intended Audience :: Developers",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3 :: Only",
23
+ "Programming Language :: Python :: 3.9",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Topic :: Software Development",
28
+ "Topic :: Utilities",
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://github.com/nexB/scancode.io"
33
+ Documentation = "https://scancodeio.readthedocs.io/"
34
+ Changelog = "https://github.com/nexB/scancode.io/tree/main/aboutcode/pipeline/CHANGELOG.md"
35
+ Repository = "https://github.com/nexB/scancode.io/tree/main/aboutcode/pipeline"
36
+ Issues = "https://github.com/nexB/scancode.io/issues"
37
+
38
+ [tool.flot]
39
+ includes = [
40
+ "aboutcode/pipeline/*",
41
+ ]
42
+ metadata_files = [
43
+ "LICENSE",
44
+ "NOTICE",
45
+ ]