codecraftai-extension 1.3.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,204 @@
1
+ # Code Craft AI - Source Available License
2
+ Version 1.0, October 2026
3
+
4
+ Copyright (C) 2026, Code Craft AI LLC
5
+
6
+ Everyone is permitted to copy and distribute verbatim copies of *This License* document, but changing it is not allowed.
7
+
8
+ *This License* covers the Python Automation Kit, the full suite of software published by *Licensor* that consists of every `codecraftai-*` package, every `pychestrate` package, and the `pychestrate` server.
9
+
10
+ *The Software* is source available. Its source code is published so that anyone can read it, learn from it, and use it, but *This License* is not an open source license. *The Software* is free to use for *Non-Commercial Use*. *Commercial Use* is permitted in exchange for a *Usage Fee* that is based on a reasonable estimation of the income derived from *The Software*, as described in section 5. When a company migrates a product or service to *The Software* from another code base, the *Profit* from that product or service is not counted toward the *Usage Fee* for two years, as described in section 5.4. For assurance of costs, a company can disclose its usage and estimated returns to *Licensor* and negotiate a fixed license cost, as described in section 5.10.
11
+
12
+ ## 1. Definitions
13
+
14
+ ### 1.1 *This License* or *The License*
15
+ **This License** or **The License** refers to version 1.0 of the Code Craft AI - Source Available License.
16
+
17
+ ### 1.2 Licensor
18
+ **Licensor** refers to Code Craft AI LLC.
19
+
20
+ ### 1.3 The Software
21
+ **The Software** refers to the Python Automation Kit, the full suite of software that *Licensor* publishes under *This License*. The Python Automation Kit consists of the following components (each, a **Component**), together with their source code, documentation, and other materials:
22
+
23
+ 1. Every Python package published by *Licensor* whose name begins with `codecraftai-`
24
+ 2. Every Python package published by *Licensor* whose name begins with `pychestrate`
25
+ 3. The `pychestrate` server
26
+
27
+ ### 1.4 You
28
+ **You** refers to the individual or legal entity that exercises rights under *This License*. When an individual exercises rights under *This License* on behalf of a company, organization, or other legal entity, **You** refers to that entity.
29
+
30
+ ### 1.5 Use
31
+ **Use** means to install, execute, load, access, operate, display, copy, modify, configure, customize, and otherwise use.
32
+
33
+ ### 1.6 Non-Commercial Use
34
+ **Non-Commercial Use** means any *Use* of *The Software* that is not *Commercial Use*. Examples of *Non-Commercial Use* include personal use, hobby projects, study, teaching, academic research, evaluation, and use by a non-profit organization for its non-profit purposes.
35
+
36
+ ### 1.7 Commercial Use
37
+ **Commercial Use** means any *Use* of *The Software* by or on behalf of a for-profit entity, and any *Use* of *The Software* in connection with a product, service, or activity that generates revenue. *Commercial Use* includes, without limitation, *Use* of *The Software* to develop, build, test, validate, deploy, operate, or support commercial products and services, and *Use* of *The Software* to provide services to others.
38
+
39
+ ### 1.8 Commercial Activity
40
+ **Commercial Activity** means the products, services, and business operations in connection with which *You* make *Commercial Use* of *The Software*.
41
+
42
+ ### 1.9 Fiscal Year
43
+ **Fiscal Year** means the annual accounting period that *You* use for financial reporting.
44
+
45
+ ### 1.10 Profit
46
+ **Profit** means the net profit that *You* earn from the *Commercial Activity* during a *Fiscal Year*, determined under the accounting principles that *You* regularly use for financial reporting.
47
+
48
+ ### 1.11 Contribution Estimate
49
+ **Contribution Estimate** means *Your* reasonable, good faith estimate of the portion of the *Profit* that *The Software* contributed to, expressed as a number from 0 to 1.
50
+
51
+ ### 1.12 Derived Income
52
+ **Derived Income** means the portion of the *Profit* for a *Fiscal Year* that is derived from *The Software*, calculated as described in section 5.2.
53
+
54
+ ### 1.13 Usage Fee
55
+ **Usage Fee** means the yearly fee for *Commercial Use* that is set by the table in section 5.3.
56
+
57
+ ### 1.14 Migration
58
+ **Migration** means moving the work for one of *Your* products or services from a code base other than *The Software*, such as another framework, another library, or *Your* own code, to *The Software*.
59
+
60
+ ### 1.15 Migration Period
61
+ **Migration Period** means the two (2) year period, described in section 5.4, during which the *Profit* from a product or service that *You* are migrating to *The Software* is not counted.
62
+
63
+ ## 2. License Grant
64
+
65
+ Subject to the terms and conditions of *This License*, *Licensor* hereby grants to *You* a non-exclusive, worldwide, non-transferable license to *Use*, copy, modify, create derivative works of, and distribute *The Software*.
66
+
67
+ *Licensor* also grants to *You* a license under any patents that *Licensor* can license, and that are necessarily infringed by *The Software*, for the same purposes and subject to the same conditions as the license granted above.
68
+
69
+ *This License* covers the Python Automation Kit as a whole. *Use* of one, some, or all of the *Components* is *Use* of *The Software*.
70
+
71
+ The licenses granted by *This License* are free of charge for *Non-Commercial Use*. The licenses granted by *This License* for *Commercial Use* are conditioned on the payment of the *Usage Fee* described in section 5.
72
+
73
+ ## 3. Conditions
74
+
75
+ ### 3.1 License Notice
76
+ Every copy of *The Software* that *You* distribute, in original or modified form, must include a complete copy of *This License* and must keep all copyright, patent, trademark, and attribution notices that appear in *The Software*.
77
+
78
+ ### 3.2 Recipients
79
+ Anyone who receives *The Software* from *You* receives it under the terms of *This License*. *You* may not impose terms on a recipient that conflict with *This License*, and *You* may not grant a recipient rights that *This License* does not grant to *You*.
80
+
81
+ ### 3.3 Modified Versions
82
+ *You* must clearly mark any modified version of *The Software* as modified. *The Software* is published by *Licensor* under a specific identity, such as a package name. *You* may not publish a modified version of *The Software* under the identity that *Licensor* originally published it under. Every copy of *The Software* that *You* redistribute under its original identity must be an exact copy of *The Software* as *Licensor* published it.
83
+
84
+ ### 3.4 Trademarks
85
+ *This License* does not grant any rights to use the names, logos, or trademarks of *Licensor*, except as required to comply with section 3.1 and to describe the origin of *The Software*.
86
+
87
+ ## 4. Non-Commercial Use
88
+
89
+ *Non-Commercial Use* of *The Software* is free. No *Usage Fee*, registration, or report is required for *Non-Commercial Use*.
90
+
91
+ ## 5. Commercial Use
92
+
93
+ ### 5.1 Usage Fee Obligation
94
+ For each *Fiscal Year* in which *You* make *Commercial Use* of *The Software*, *You* must pay *Licensor* a *Usage Fee*. A single *Usage Fee* covers all of *Your* *Commercial Use* of the *Components*. *Usage Fees* are not owed separately for each *Component*.
95
+
96
+ ### 5.2 Derived Income
97
+ The *Derived Income* for a *Fiscal Year* is calculated as follows:
98
+
99
+ (Contribution Estimate) * (Profit) = (Derived Income)
100
+
101
+ If *You* make *Commercial Use* of *The Software* for more than one product or service, calculate the *Derived Income* for each product or service using its own *Contribution Estimate* and *Profit*, and add the results together. The *Profit* from a product or service that is in its *Migration Period* is not counted, as described in section 5.4.
102
+
103
+ If the *Profit* from a product or service for a *Fiscal Year* is zero or less, then the *Derived Income* from that product or service for that *Fiscal Year* is zero.
104
+
105
+ ### 5.3 Usage Fee
106
+ The *Usage Fee* for a *Fiscal Year* is set by the *Derived Income* for that *Fiscal Year*, as shown in the following table.
107
+
108
+ | Derived Income for the Fiscal Year | Usage Fee per Fiscal Year |
109
+ |------------------------------------|---------------------------|
110
+ | 1,000,000 or less | Free |
111
+ | More than 1,000,000, up to and including 10,000,000 | 50,000 |
112
+ | More than 10,000,000, up to and including 100,000,000 | 100,000 |
113
+ | More than 100,000,000, up to and including 1,000,000,000 | 250,000 |
114
+ | More than 1,000,000,000 | 500,000 |
115
+
116
+ All amounts in this section 5 are in United States dollars. If *You* report *Profit* in a different currency, convert the *Derived Income* to United States dollars using the average exchange rate for the *Fiscal Year*.
117
+
118
+ ### 5.4 Migration Allowance
119
+ When *You* migrate a product or service to *The Software*, the *Profit* from that product or service is not counted when calculating the *Derived Income* during its *Migration Period* (the **Migration Allowance**).
120
+
121
+ The *Migration Period* for a product or service begins on the date that *You* first make *Commercial Use* of *The Software* for that product or service as part of its *Migration*, and ends two (2) years after that date.
122
+
123
+ The *Migration Allowance* applies to each product or service separately, and *You* may use it for every product or service that *You* migrate. Each product or service has only one *Migration Period*.
124
+
125
+ If a *Fiscal Year* is only partly within the *Migration Period* of a product or service, the *Profit* from that product or service for that *Fiscal Year* is reduced in proportion to the number of days of that *Fiscal Year* that fall within its *Migration Period*.
126
+
127
+ For example, a company tests product A with *The Software* and pays a *Usage Fee* based on the *Profit* from product A. On March 1, 2027, the company begins moving the testing of product B from a different test framework to *The Software*. The company does not count the *Profit* from product B in its *Derived Income* from March 1, 2027 until March 1, 2029. Starting March 1, 2029, the *Profit* from product B is counted. If the company later migrates product C, the *Profit* from product C is not counted for two years from the start of its own *Migration*.
128
+
129
+ ### 5.5 Contribution Estimate
130
+ *You* are responsible for making the *Contribution Estimate*. A *Contribution Estimate* must be reasonable and made in good faith. The *Contribution Estimate* for a product or service covers all of the *Components* that *You* *Use* for that product or service. When making the *Contribution Estimate*, *You* should consider how important *The Software* is to the *Commercial Activity*, how much of the *Commercial Activity* depends on *The Software*, and the effort and cost that *You* would otherwise need to spend to accomplish what *The Software* accomplishes for *You*.
131
+
132
+ The following table is a guide for making the *Contribution Estimate*. When *Your* *Commercial Use* of *The Software* matches an entry in the table, the *Contribution Estimate* in that entry is a reasonable *Contribution Estimate*. When *Your* *Commercial Use* does not match an entry in the table, make the *Contribution Estimate* by comparing *Your* *Commercial Use* with the entries in the table. When more than one entry matches the same *Commercial Activity*, use the entry with the highest *Contribution Estimate*.
133
+
134
+ | Commercial Use of *The Software* | Contribution Estimate |
135
+ |----------------------------------|-----------------------|
136
+ | Quality Assurance (QA) and Continuous Integration (CI): *The Software* is used to test or validate the products or services of the *Commercial Activity*, or to run their build and test pipelines | 0.3 |
137
+ | Products Completely Based on *The Software*: the products or services of the *Commercial Activity* are built completely on *The Software* | 0.5 |
138
+
139
+ ### 5.6 Examples
140
+ A company earns 1,000,000,000 in *Profit* from a product line during a *Fiscal Year*. The company uses *The Software* for the QA and CI of that product line, so the *Contribution Estimate* is 0.3.
141
+
142
+ 0.3 * 1,000,000,000 = 300,000,000
143
+
144
+ The *Derived Income* of 300,000,000 is more than 100,000,000 and not more than 1,000,000,000, so the *Usage Fee* for that *Fiscal Year* is 250,000.
145
+
146
+ A company earns 4,000,000 in *Profit* from a product during a *Fiscal Year*. The product is built completely on *The Software*, so the *Contribution Estimate* is 0.5.
147
+
148
+ 0.5 * 4,000,000 = 2,000,000
149
+
150
+ The *Derived Income* of 2,000,000 is more than 1,000,000 and not more than 10,000,000, so the *Usage Fee* for that *Fiscal Year* is 50,000.
151
+
152
+ A company earns 3,000,000 in *Profit* from a product line during a *Fiscal Year*. The company uses *The Software* for the QA and CI of that product line, so the *Contribution Estimate* is 0.3.
153
+
154
+ 0.3 * 3,000,000 = 900,000
155
+
156
+ The *Derived Income* of 900,000 is 1,000,000 or less, so there is no *Usage Fee* for that *Fiscal Year*.
157
+
158
+ ### 5.7 Reporting and Payment
159
+ Within one hundred twenty (120) days after the end of each *Fiscal Year* for which a *Usage Fee* is owed, *You* must pay the *Usage Fee* to *Licensor* and provide *Licensor* with a written statement that shows the *Profit*, the *Contribution Estimate*, the reasoning used to make the *Contribution Estimate*, the *Derived Income*, and the *Usage Fee*. *Usage Fees* are payable in United States dollars. If any *Profit* is not counted under section 5.4, the statement must also identify each product or service that is in a *Migration Period* and show the dates of its *Migration Period*. No statement is required for a *Fiscal Year* in which no *Usage Fee* is owed.
160
+
161
+ ### 5.8 Records and Review
162
+ *You* must keep records that reasonably support each *Contribution Estimate*, each *Profit* figure, and the dates of any *Migration Period* for at least three (3) years after the end of the *Fiscal Year* that they apply to. No more than once in any twelve (12) month period, *Licensor* may ask in writing for the records that support a statement, and *You* must provide them within sixty (60) days of the request. *Licensor* will treat those records as confidential.
163
+
164
+ ### 5.9 Disputes About the Usage Fee
165
+ If *Licensor* believes that a *Contribution Estimate*, a *Profit* figure, or the dates of a *Migration Period* are not reasonable, *Licensor* will notify *You* in writing and explain why. *You* and *Licensor* will then negotiate in good faith for at least sixty (60) days to agree on a reasonable *Usage Fee*. If *You* and *Licensor* cannot agree, either party may resolve the dispute as described in section 8.
166
+
167
+ ### 5.10 Fixed License Cost
168
+ For assurance of costs, *You* may disclose to *Licensor* how *You* *Use* *The Software* and the returns that *You* estimate *You* will derive from it, and negotiate a fixed license cost with *Licensor*. A fixed license cost, and any other terms that *You* and *Licensor* agree to, must be set out in a writing signed by both *You* and *Licensor* (a **Fixed License Agreement**).
169
+
170
+ While a *Fixed License Agreement* is in effect, the fixed license cost replaces the *Usage Fee* for the *Commercial Use* that the *Fixed License Agreement* covers, and sections 5.7 through 5.9 apply to that *Commercial Use* only as the *Fixed License Agreement* provides. To the extent that a *Fixed License Agreement* conflicts with this section 5, the *Fixed License Agreement* controls.
171
+
172
+ *Licensor* will treat the information that *You* disclose under this section 5.10 as confidential.
173
+
174
+ ## 6. Termination
175
+
176
+ If *You* violate *This License*, the licenses granted to *You* by *This License* end. If *Licensor* notifies *You* in writing of the violation and *You* correct the violation within thirty (30) days of receiving the notice, including by paying any *Usage Fee* that is owed, then the licenses granted to *You* are reinstated. This reinstatement is available to *You* only once. Termination does not release *You* from any *Usage Fee* that is owed for *Commercial Use* that took place before the termination.
177
+
178
+ ## 7. No Warranty and Limitation of Liability
179
+
180
+ ### 7.1 No Warranty
181
+ *THE SOFTWARE* IS PROVIDED "AS IS", WITHOUT ANY WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
182
+
183
+ ### 7.2 Limitation of Liability
184
+ TO THE EXTENT PERMITTED BY LAW, IN NO EVENT WILL *LICENSOR* BE LIABLE TO *YOU* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR EXEMPLARY DAMAGES OF ANY KIND ARISING OUT OF OR RELATED TO *THIS LICENSE* OR THE *USE* OF *THE SOFTWARE*, EVEN IF *LICENSOR* HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
185
+
186
+ ### 7.3 Support
187
+ *This License* does not entitle *You* to support, maintenance, or other services. Support and services are available only under a separate written agreement with *Licensor*.
188
+
189
+ ## 8. Governing Law and Jurisdiction
190
+
191
+ *This License* is governed by the laws of the State of Washington and the United States as though fully performed in Washington, without regard to provisions relating to conflicts of laws. The UN Convention for the International Sale of Goods and the Uniform Computer Information Transactions Act (UCITA) will not apply. The state and federal courts located in King County, Washington will have exclusive jurisdiction to adjudicate any disputes arising under *This License*, and *You* and *Licensor* agree to submit to the jurisdiction of those courts.
192
+
193
+ ## 9. General
194
+
195
+ ### 9.1 Severability
196
+ If any provision of *This License* is held to be unenforceable, that provision will be enforced to the maximum extent permitted, and the remaining provisions of *This License* will remain in effect.
197
+
198
+ ### 9.2 Interpretation
199
+ The section headings in *This License* are for reference purposes only and do not modify or restrict any term of *This License*. *This License* is written in the English language, and the English text prevails over any translation.
200
+
201
+ ### 9.3 Contact
202
+ Questions about *This License*, *Usage Fee* statements, payments, and requests to negotiate a *Fixed License Agreement* may be sent to *Licensor* using the contact information published at:
203
+
204
+ https://code-craft.ai
@@ -0,0 +1,85 @@
1
+ Metadata-Version: 2.4
2
+ Name: codecraftai-extension
3
+ Version: 1.3.0
4
+ Summary: Code Craft AI - Extension Package
5
+ License-Expression: LicenseRef-CodeCraftAI-Source-Available
6
+ License-File: LICENSE.md
7
+ Keywords: python
8
+ Author: Myron Walker
9
+ Author-email: myron.walker@gmail.com
10
+ Requires-Python: >=3.10,<4.0
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: POSIX
13
+ Project-URL: Issues, https://github.com/code-craft-ai-company/codecraftai-extension/issues
14
+ Project-URL: Repository, https://github.com/code-craft-ai-company/codecraftai-extension
15
+ Description-Content-Type: text/x-rst
16
+
17
+ ==========================
18
+ Code Craft AI Extension
19
+ ==========================
20
+
21
+ The ``codecraftai-extension`` package provides the lightweight extension and factory machinery that other ccai packages use to allow third-party code to plug in new resource types, coordinators, and protocol handlers without modifying the host package. Extensions are discovered by scanning the ``ccai.factories`` namespace on ``sys.path`` (and via explicit module registration through ``SuperFactory.add_factory_module``), and are picked up by extension-aware packages such as ``codecraftai-landscaping``, ``codecraftai-interop``, and the ``codecraftai-interop-ext-*`` packages.
22
+
23
+ Highlights
24
+ ==========
25
+
26
+ - ``FactoryExtension`` plus ``FactoryProtocolBase`` and ``SuperFactory`` for pluggable object construction.
27
+ - ``ResourceExtension`` for resources that must be discovered and registered at runtime.
28
+ - ``ccai.factories`` namespace scanning (plus explicit module registration) so third-party packages can contribute without modifying host code.
29
+ - Used as the substrate for the composable ``codecraftai-interop-ext-*`` ecosystem of device types, protocols, and services.
30
+
31
+ Repository Structure
32
+ ====================
33
+
34
+ - ``development/`` - Runtime environment scripts.
35
+ - ``repository-setup/`` - Repository homing and setup scripts.
36
+ - ``source/packages/`` - Package source code.
37
+ - ``source/tests/`` - ``unittest``-based tests.
38
+ - ``specs/`` - Requirements, design, and task documentation.
39
+ - ``userguide/`` - Standards, conventions, and documentation.
40
+
41
+ Environment Setup
42
+ =================
43
+
44
+ When working in a Codex container:
45
+
46
+ .. code-block:: bash
47
+
48
+ ./development/setup-agent-container
49
+
50
+ For local development:
51
+
52
+ .. code-block:: bash
53
+
54
+ ./repository-setup/rehome-repository
55
+ ./development/setup-environment
56
+
57
+ Running Tests
58
+ =============
59
+
60
+ Activate the virtual environment:
61
+
62
+ .. code-block:: bash
63
+
64
+ source .venv/bin/activate
65
+
66
+ Run ``unittest`` tests:
67
+
68
+ .. code-block:: bash
69
+
70
+ python -m unittest discover -s source/tests -p "test_*.py"
71
+
72
+ Standards and Conventions
73
+ =========================
74
+
75
+ - Naming conventions: ``userguide/10-02-naming-conventions.rst``
76
+ - Code organization: ``userguide/10-01-code-organization.rst``
77
+ - Coding standards: ``userguide/10-00-coding-standards.rst``
78
+
79
+ Additional Resources
80
+ ====================
81
+
82
+ - User guide entry point: ``userguide/userguide.rst``
83
+ - Design documentation: ``specs/design.md``
84
+ - Requirements: ``specs/requirements.md``
85
+
@@ -0,0 +1,68 @@
1
+ ==========================
2
+ Code Craft AI Extension
3
+ ==========================
4
+
5
+ The ``codecraftai-extension`` package provides the lightweight extension and factory machinery that other ccai packages use to allow third-party code to plug in new resource types, coordinators, and protocol handlers without modifying the host package. Extensions are discovered by scanning the ``ccai.factories`` namespace on ``sys.path`` (and via explicit module registration through ``SuperFactory.add_factory_module``), and are picked up by extension-aware packages such as ``codecraftai-landscaping``, ``codecraftai-interop``, and the ``codecraftai-interop-ext-*`` packages.
6
+
7
+ Highlights
8
+ ==========
9
+
10
+ - ``FactoryExtension`` plus ``FactoryProtocolBase`` and ``SuperFactory`` for pluggable object construction.
11
+ - ``ResourceExtension`` for resources that must be discovered and registered at runtime.
12
+ - ``ccai.factories`` namespace scanning (plus explicit module registration) so third-party packages can contribute without modifying host code.
13
+ - Used as the substrate for the composable ``codecraftai-interop-ext-*`` ecosystem of device types, protocols, and services.
14
+
15
+ Repository Structure
16
+ ====================
17
+
18
+ - ``development/`` - Runtime environment scripts.
19
+ - ``repository-setup/`` - Repository homing and setup scripts.
20
+ - ``source/packages/`` - Package source code.
21
+ - ``source/tests/`` - ``unittest``-based tests.
22
+ - ``specs/`` - Requirements, design, and task documentation.
23
+ - ``userguide/`` - Standards, conventions, and documentation.
24
+
25
+ Environment Setup
26
+ =================
27
+
28
+ When working in a Codex container:
29
+
30
+ .. code-block:: bash
31
+
32
+ ./development/setup-agent-container
33
+
34
+ For local development:
35
+
36
+ .. code-block:: bash
37
+
38
+ ./repository-setup/rehome-repository
39
+ ./development/setup-environment
40
+
41
+ Running Tests
42
+ =============
43
+
44
+ Activate the virtual environment:
45
+
46
+ .. code-block:: bash
47
+
48
+ source .venv/bin/activate
49
+
50
+ Run ``unittest`` tests:
51
+
52
+ .. code-block:: bash
53
+
54
+ python -m unittest discover -s source/tests -p "test_*.py"
55
+
56
+ Standards and Conventions
57
+ =========================
58
+
59
+ - Naming conventions: ``userguide/10-02-naming-conventions.rst``
60
+ - Code organization: ``userguide/10-01-code-organization.rst``
61
+ - Coding standards: ``userguide/10-00-coding-standards.rst``
62
+
63
+ Additional Resources
64
+ ====================
65
+
66
+ - User guide entry point: ``userguide/userguide.rst``
67
+ - Design documentation: ``specs/design.md``
68
+ - Requirements: ``specs/requirements.md``
@@ -0,0 +1,55 @@
1
+ [project]
2
+ name = "codecraftai-extension"
3
+ version = "1.3.0"
4
+ description = "Code Craft AI - Extension Package"
5
+ readme = "README.rst"
6
+ license = "LicenseRef-CodeCraftAI-Source-Available"
7
+ authors = [{name = "Myron Walker", email = "myron.walker@gmail.com"}]
8
+ keywords = [
9
+ "python"
10
+ ]
11
+ classifiers = [
12
+ "Programming Language :: Python :: 3",
13
+ "Operating System :: POSIX",
14
+ ]
15
+ requires-python = ">=3.10,<4.0"
16
+ dependencies = []
17
+
18
+ [project.urls]
19
+ Repository = "https://github.com/code-craft-ai-company/codecraftai-extension"
20
+ Issues = "https://github.com/code-craft-ai-company/codecraftai-extension/issues"
21
+
22
+ [dependency-groups]
23
+ dev = []
24
+
25
+ [tool.poetry]
26
+ packages = [{include="ccai", from="source/packages"}]
27
+ # The README only marks the shared 'ccai' namespace directory in the source tree. It stays out of the
28
+ # wheel because several codecraftai packages install into that directory and a file there collides.
29
+ exclude = ["source/packages/ccai/README.md"]
30
+
31
+ [[tool.poetry.source]]
32
+ name = "codecraftai"
33
+ url = "https://code-craft.ai/licensed-repository/simple/"
34
+ priority = "supplemental"
35
+
36
+ [[tool.uv.index]]
37
+ # Same licensed index as [[tool.poetry.source]]. Listed before PyPI so that
38
+ # codecraftai-* packages (direct and transitive) resolve from it; everything
39
+ # else falls through to PyPI. Credentials: UV_INDEX_CODECRAFTAI_USERNAME /
40
+ # UV_INDEX_CODECRAFTAI_PASSWORD, or `uv auth login`.
41
+ name = "codecraftai"
42
+ url = "https://code-craft.ai/licensed-repository/simple/"
43
+
44
+ [tool.ruff.lint]
45
+ # Deliberately narrow. This gate exists for one reason: a bare `except:`
46
+ # swallows ConfigurationError and SemanticError, which derive from
47
+ # BaseException precisely so that they pass through ordinary handlers and end
48
+ # the run. Catching them hides the original cause behind whatever error
49
+ # happens next. See userguide/10-00-coding-standards.rst, exception-handling
50
+ # rules 5-7. Use `except Exception:` when you mean "any ordinary failure".
51
+ select = ["E722"]
52
+
53
+ [build-system]
54
+ requires = ["poetry-core"]
55
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,13 @@
1
+ """
2
+ .. module:: constants
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Module that contains extensibility constants.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+ __author__ = "Myron Walker"
10
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
+ __credits__ = []
12
+
13
+ EXT_MOD_SEP = ","
@@ -0,0 +1,23 @@
1
+ """
2
+ .. module:: factoryextension
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Module that contains the FactoryExtension base type.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+ __author__ = "Myron Walker"
10
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
+ __credits__ = []
12
+
13
+
14
+ class FactoryExtension:
15
+ """
16
+ The :class:`FactoryExtension` serves as the base class for factory extensions or objects that implement
17
+ a specific factory protocol oriented towards the creation of instances of specific objects. Factory extension
18
+ classes inherit from this type in order to be identified as a participant in the factory extension discovery
19
+ process.
20
+ """
21
+
22
+ PRECEDENCE = 0
23
+
@@ -0,0 +1,38 @@
1
+ """
2
+ .. module:: factoryprotocolbase
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Module that contains the FactoryProtocolBase base type.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+ __author__ = "Myron Walker"
10
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
+ __credits__ = []
12
+
13
+
14
+ from typing import Protocol
15
+
16
+ class FactoryProtocolBase(Protocol):
17
+ """
18
+ The :class:`FactoryProtocolBase` serves as the base type for objects that declare a factory protocol that should be followed
19
+ in order to override or replace functionality of a software component. :class:`FactoryProtocolBase` provides the base functionality
20
+ for all factory protocols to inherit from. It defines the contract that all factory protocols must adhere to in order to be
21
+ recognized as a specific and unique factory protocol.
22
+
23
+ Subclasses must set ``factory_protocol_name`` to provide a unique identifier for any factory that implements a specific
24
+ factory protocol.
25
+ """
26
+
27
+ factory_protocol_name = None
28
+
29
+ def __init_subclass__(cls, *args, **kwargs):
30
+ """
31
+ Validates that derived classes specify ``factory_protocol_name``.
32
+ """
33
+ if cls.factory_protocol_name is None:
34
+ errmsg = (
35
+ "The 'factory_protocol_name' class level field must be set on derived protocol types."
36
+ )
37
+ raise RuntimeError(errmsg)
38
+ return super().__init_subclass__(*args, **kwargs)
@@ -0,0 +1,321 @@
1
+ """
2
+ .. module:: extensionsuperfactory
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Module that contains the `ExtensionSuperFactory` object which is used to
5
+ create a singleton instance for dynamically loading type extensions.
6
+
7
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
8
+ """
9
+
10
+ __author__ = "Myron Walker"
11
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
12
+ __credits__ = []
13
+
14
+
15
+ import inspect
16
+ import logging
17
+ import os
18
+ import sys
19
+
20
+
21
+ from operator import attrgetter
22
+ from typing import Callable, Generator, List, Tuple, Type, Union
23
+
24
+ from ccai.extension.utilities import import_by_name
25
+
26
+ from ccai.extension.factory.factoryextension import FactoryExtension
27
+ from ccai.extension.factory.factoryprotocolbase import FactoryProtocolBase
28
+
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ def is_subclass_of_factory_extension(cand_type):
34
+ """
35
+ Returns a boolean value indicating if the candidate type is a subclass of :class:`FactoryExtension`.
36
+ """
37
+ is_scoep = False
38
+ if inspect.isclass(cand_type):
39
+ if cand_type != FactoryExtension and issubclass(cand_type, FactoryExtension):
40
+ is_scoep = True
41
+
42
+ return is_scoep
43
+
44
+
45
+ def load_and_set_factoryextension_types(module_name: str) -> List[FactoryExtension]:
46
+ """
47
+ Scans the module provided for :class:`FactoryExtension` derived classes.
48
+ """
49
+ factory_types = []
50
+
51
+ fe_module = import_by_name(module_name)
52
+ class_items = inspect.getmembers(fe_module, is_subclass_of_factory_extension)
53
+
54
+ factory_types = []
55
+ for _, cls_type in class_items:
56
+ type_module_name = cls_type.__module__
57
+ if type_module_name == fe_module.__name__:
58
+ factory_types.append(cls_type)
59
+ else:
60
+ # The class is a FactoryExtension subclass that was re-exported
61
+ # (imported) into this module but defined elsewhere. We register
62
+ # it only under its defining module to avoid duplicate registration,
63
+ # so we skip it here. This is expected, not an error.
64
+ dmsg = f"Skipping factory class '{cls_type.__name__}' re-exported into module={fe_module.__name__}; it is registered under its defining module '{type_module_name}'."
65
+ logger.debug(dmsg)
66
+
67
+ return factory_types
68
+
69
+
70
+ def scan_ccai_factories_namespace() -> List[str]:
71
+
72
+ search_paths = set([p for p in sys.path])
73
+
74
+ # __file__ == .../source/packages/ccai/extension/factory/superfactory.py.
75
+ # Four dirname() calls climb to the packages root (.../source/packages), which
76
+ # is the directory that *contains* the 'ccai' package — the correct base for
77
+ # the 'ccai/factories' join below. (The prior three-call version yielded
78
+ # .../source/packages/ccai and produced a never-existing 'ccai/ccai/factories'.)
79
+ packages_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
80
+ search_paths.add(packages_root)
81
+
82
+ modules_found = []
83
+
84
+ for dir_path in search_paths:
85
+ check_dir = os.path.join(dir_path, "ccai", "factories")
86
+ if os.path.exists(check_dir) and os.path.isdir(check_dir):
87
+ check_dir_modules = scan_for_descendant_modules(check_dir)
88
+ modules_found.extend(check_dir_modules)
89
+
90
+ return modules_found
91
+
92
+
93
+ def scan_for_descendant_modules(scan_dir: str, module_prefix: str="ccai.factories") -> List[str]:
94
+
95
+ modules_found = []
96
+
97
+ for dirpath, dirnames, filenames in os.walk(scan_dir):
98
+ leafpath = dirpath[len(scan_dir):].strip(os.sep)
99
+ leafpath_parts = []
100
+ if len(leafpath) > 0:
101
+ leafpath_parts = leafpath.split(os.sep)
102
+
103
+ mod_parts_comp = ""
104
+ if len(leafpath_parts) > 0:
105
+ mod_parts_comp = "." + ".".join(leafpath_parts)
106
+
107
+ for fname in filenames:
108
+ if not fname.endswith(".py"):
109
+ continue
110
+
111
+ if fname == "__init__.py":
112
+ # Emit the package's own importable name rather than a
113
+ # '<pkg>.__init__' alias. Importing the alias would re-execute
114
+ # the package as a second, distinct module object, registering
115
+ # any factory classes defined in __init__.py as duplicates.
116
+ mod_name = f"{module_prefix}{mod_parts_comp}"
117
+ else:
118
+ fcomp = fname[:-3]
119
+ mod_name = f"{module_prefix}{mod_parts_comp}.{fcomp}"
120
+
121
+ if mod_name not in modules_found:
122
+ modules_found.append(mod_name)
123
+
124
+ return modules_found
125
+
126
+
127
+ def resolve_protocol_dispatch(factory_method: Callable) -> Tuple[str, str]:
128
+ """
129
+ Resolves the dispatch keys for a protocol factory method.
130
+
131
+ :param factory_method: A method of a protocol type used to locate an
132
+ extension factory that implements that protocol.
133
+
134
+ :returns: A tuple of (factory_protocol_name, method_name).
135
+ :raises: RuntimeError when the protocol class cannot be resolved from
136
+ the method's module globals (e.g. a nested or mixin-inherited
137
+ method whose owning protocol is not a top-level module name).
138
+ """
139
+ method_qualname = factory_method.__qualname__
140
+ proto_type_name = method_qualname.split('.')[0]
141
+ method_globals = factory_method.__globals__
142
+
143
+ if proto_type_name not in method_globals:
144
+ errmsg_lines = [
145
+ f"SuperFactory could not resolve the protocol class '{proto_type_name}' that defines factory method '{method_qualname}'.",
146
+ "The protocol class must be a top-level name in the module where the method is defined (not nested or mixin-inherited).",
147
+ f"METHOD MODULE: {getattr(factory_method, '__module__', '<unknown>')}"
148
+ ]
149
+ errmsg = os.linesep.join(errmsg_lines)
150
+ raise RuntimeError(errmsg)
151
+
152
+ proto_type: FactoryProtocolBase = method_globals[proto_type_name]
153
+ proto_name = proto_type.factory_protocol_name
154
+ method_name = factory_method.__name__
155
+
156
+ rtnval = (proto_name, method_name)
157
+ return rtnval
158
+
159
+
160
+ class SuperFactory:
161
+ """
162
+ A :class:`SuperFactory` object is used to maintain a chain of factory types that
163
+ can be traversed in order to locate a factory that implements a specific protocol
164
+ in order to enable various types of overload or overinstance states.
165
+ """
166
+
167
+ def __init__(self, factory_modules: List[str]):
168
+ """
169
+ Constructs the super factory and loads factory modules.
170
+
171
+ :param factory_modules: Additional factory module paths to load.
172
+ """
173
+
174
+ self._factory_modules = scan_ccai_factories_namespace()
175
+ if len(factory_modules) > 0:
176
+ self._factory_modules.extend(factory_modules)
177
+
178
+ self._protocol_factories: List[Union[FactoryExtension, FactoryProtocolBase]] = []
179
+
180
+ for smod in self._factory_modules:
181
+ factory_types = load_and_set_factoryextension_types(smod)
182
+ for ftype in factory_types:
183
+ self._protocol_factories.append(ftype)
184
+
185
+ self._protocol_factories.sort(key=attrgetter('PRECEDENCE'))
186
+
187
+ return
188
+
189
+ @property
190
+ def extension_factories(self):
191
+ """
192
+ List of loaded extension factory types.
193
+ """
194
+ item_list = [item for item in self._protocol_factories]
195
+ return item_list
196
+
197
+ @property
198
+ def factory_modules(self):
199
+ """
200
+ List of module names searched for factories.
201
+ """
202
+ item_list = [item for item in self._factory_modules]
203
+ return item_list
204
+
205
+ def add_factory_module(self, factory_module: str):
206
+ """
207
+ Can be used by super factory consumers to app the path of a wellknown factory module.
208
+ """
209
+ if factory_module not in self._factory_modules:
210
+ self._factory_modules.append(factory_module)
211
+
212
+ factory_types = load_and_set_factoryextension_types(factory_module)
213
+ for ftype in factory_types:
214
+ self._protocol_factories.append(ftype)
215
+
216
+ self._protocol_factories.sort(key=attrgetter('PRECEDENCE'))
217
+
218
+ return
219
+
220
+ def create_instance_by_order(self, factory_method: Callable, *args, **kwargs) -> Union[object, None]:
221
+ """
222
+ Create an instance using the highest-precedence factory that supports the protocol.
223
+
224
+ Factories are consulted in ascending PRECEDENCE order and the last (highest
225
+ PRECEDENCE) match wins, so a higher-precedence factory overrides lower ones.
226
+
227
+ :param factory_method: A callable that is a method of the protocol type that we are going to use
228
+ in order to find an extension factory that implements the protocol.
229
+ :param args: Positional arguments to pass to the factory method.
230
+ :param kwargs: Keyword arguments to pass to the factory method.
231
+
232
+ :returns: An instance of an object type created by the highest-precedence factory that
233
+ supports the protocol factory method provided, or ``None`` if no factory matches.
234
+ """
235
+
236
+ instance = None
237
+
238
+ proto_name, factory_method = resolve_protocol_dispatch(factory_method)
239
+
240
+ create_instance: Callable = None
241
+
242
+ for factory_type in self._protocol_factories:
243
+ if hasattr(factory_type, factory_method):
244
+ factory_proto_name = factory_type.factory_protocol_name
245
+ if factory_proto_name == proto_name:
246
+ create_instance = getattr(factory_type, factory_method)
247
+
248
+ if create_instance is not None:
249
+ instance = create_instance(*args, **kwargs)
250
+
251
+ return instance
252
+
253
+ def create_instance_for_each(self, factory_method: Callable, *args, **kwargs) -> List[object]:
254
+ """
255
+ Create an instance using each factory that supports the protocol.
256
+ """
257
+
258
+ list_of_instances = []
259
+
260
+ proto_name, factory_method = resolve_protocol_dispatch(factory_method)
261
+
262
+ for factory_type in self._protocol_factories:
263
+ if hasattr(factory_type, factory_method):
264
+ factory_proto_name = factory_type.factory_protocol_name
265
+ if factory_proto_name == proto_name:
266
+ create_instance = getattr(factory_type, factory_method)
267
+ instance = create_instance(*args, **kwargs)
268
+ list_of_instances.append(instance)
269
+
270
+ return list_of_instances
271
+
272
+ def get_override_types_by_order(self, get_type_method: Callable) -> Union[Type, List[Type], None]:
273
+ """
274
+ Return the override type from the highest-precedence factory that supplies it.
275
+
276
+ Factories are consulted in ascending PRECEDENCE order and the last (highest
277
+ PRECEDENCE) match wins.
278
+ """
279
+
280
+ found_type = None
281
+
282
+ get_type_with = None
283
+
284
+ proto_name, get_type_method = resolve_protocol_dispatch(get_type_method)
285
+
286
+ for factory_type in self._protocol_factories:
287
+ if hasattr(factory_type, get_type_method):
288
+ factory_proto_name = factory_type.factory_protocol_name
289
+ if factory_proto_name == proto_name:
290
+ get_type_with = getattr(factory_type, get_type_method)
291
+
292
+ if get_type_with is not None:
293
+ found_type = get_type_with()
294
+
295
+ return found_type
296
+
297
+ def iterate_override_types_for_each(self, get_type_method: Callable, iterate_type_lists: bool = True) -> Generator[Union[Type, List[Type], None], None, None]:
298
+ """
299
+ Yield override types from each factory in order.
300
+ """
301
+
302
+ found_type = None
303
+
304
+ get_type_with = None
305
+
306
+ proto_name, get_type_method = resolve_protocol_dispatch(get_type_method)
307
+
308
+ for factory_type in self._protocol_factories:
309
+ if hasattr(factory_type, get_type_method):
310
+ factory_proto_name = factory_type.factory_protocol_name
311
+ if factory_proto_name == proto_name:
312
+ get_type_with = getattr(factory_type, get_type_method)
313
+
314
+ found_type = get_type_with()
315
+
316
+ if iterate_type_lists and type(found_type) is list:
317
+ for ftitem in found_type:
318
+ yield ftitem
319
+ else:
320
+ yield found_type
321
+
@@ -0,0 +1,160 @@
1
+ """
2
+ .. module:: resourceextension
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Module containing functions and classes that help create and work with
5
+ dynamically generated and discoverable resource extension objects.
6
+
7
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
8
+ """
9
+
10
+ __author__ = "Myron Walker"
11
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
12
+ __credits__ = []
13
+
14
+
15
+
16
+ from typing import List, Type
17
+ from types import ModuleType
18
+
19
+
20
+ import inspect
21
+ import os
22
+
23
+
24
+ from ccai.extension.utilities import get_directory_for_code_container, import_by_name, import_file
25
+
26
+
27
+ NoneType = type(None)
28
+
29
+
30
+ class ResourceExtension: # pylint: disable=too-few-public-methods
31
+ """
32
+ Marks a class as an extension for collection purposes so we can distinguish extension
33
+ classes from base classes
34
+ """
35
+
36
+
37
+ def collect_resource_extensions_under_code_container(container: ModuleType,
38
+ ext_base_type: Type[ResourceExtension]) -> List[Type[ResourceExtension]]:
39
+ """
40
+ Scans the code `container` provide and all descendant containers for classes
41
+ that inherit from the type passed as `ext_base_type`
42
+
43
+ :param container: A python package or module to scan for extension types.
44
+ :param ext_base_type: A python class type that serves as a base class to identify other
45
+ types that are a type of extension.
46
+
47
+ :returns: A list of types found that inherit from `ext_base_type`
48
+ """
49
+ ext_collection = []
50
+
51
+ # This is declare here so it can be used as a closure
52
+ nxtmod = None
53
+
54
+ def is_extension_class(obj):
55
+ result = False
56
+
57
+ if inspect.isclass(obj):
58
+ obj_container = obj.__module__
59
+ if obj_container == nxtmod.__name__ and ext_base_type in obj.__bases__:
60
+ result = issubclass(obj, ext_base_type) and obj is not ext_base_type
61
+ return result
62
+
63
+ container_name = container.__name__
64
+ container_dir = get_directory_for_code_container(container)
65
+ container_parts = container_name.split(".")
66
+ container_root = os.sep.join(container_dir.split(os.sep)[:-len(container_parts)])
67
+ rootlen = len(container_root)
68
+
69
+ for dirpath, _, filenames in os.walk(container_dir):
70
+ leafdir = dirpath[rootlen:].lstrip(os.sep)
71
+ leafcontainer = leafdir.replace(os.sep, ".")
72
+ for nxtfile in filenames:
73
+ nfbase, nfext = os.path.splitext(nxtfile)
74
+ if nfext != ".py":
75
+ continue
76
+
77
+ if nfbase == "__init__":
78
+ nxtmodname = "%s" % (leafcontainer)
79
+ else:
80
+ nxtmodname = "%s.%s" % (leafcontainer, nfbase)
81
+
82
+ nxtmod = import_by_name(nxtmodname)
83
+ if nxtmod is None:
84
+ continue
85
+
86
+ ext_collection.extend(inspect.getmembers(nxtmod, predicate=is_extension_class))
87
+
88
+ return ext_collection
89
+
90
+
91
+ def collect_resource_extensions_under_folder(extension_folder: str, ext_base_type: Type[ResourceExtension],
92
+ module_base: str="ccai.ext.generated") -> List[type]:
93
+ """
94
+ Scans the folder provided and all descendant folders for classes that are
95
+ direct subclasses of the type passed as `ext_base_type`.
96
+
97
+ :param extension_folder: A filesystem folder to scan for extension modules.
98
+ :param ext_base_type: A python class type that serves as a base class to identify other
99
+ types that are a direct subclass of an extension.
100
+ :param module_base: The dotted module-name prefix under which the discovered
101
+ modules are registered (e.g. ``ccai.ext.generated``).
102
+
103
+ :returns: A list of types found that are direct subclasses of `ext_base_type`
104
+ """
105
+ ext_collection = []
106
+
107
+ # This is declare here so it can be used as a closure
108
+ nxtmod = None
109
+
110
+ def is_extension_class(obj):
111
+ result = False
112
+
113
+ if inspect.isclass(obj):
114
+ obj_container = obj.__module__
115
+ if obj_container == nxtmod.__name__ and ext_base_type in obj.__bases__:
116
+ result = issubclass(obj, ext_base_type) and obj is not ext_base_type
117
+ return result
118
+
119
+ rootlen = len(extension_folder)
120
+
121
+ for dirpath, _, filenames in os.walk(extension_folder):
122
+ leafdir = dirpath[rootlen:].lstrip(os.sep)
123
+ leafcontainer = leafdir.replace(os.sep, ".")
124
+ for nxtfile in filenames:
125
+ filefull = os.path.join(dirpath, nxtfile)
126
+ nfbase, nfext = os.path.splitext(nxtfile)
127
+ if nfext != ".py":
128
+ continue
129
+
130
+ if nfbase == "__init__":
131
+ continue
132
+
133
+ # Root-level files have an empty leafcontainer; omit it so we don't
134
+ # build a malformed double-dot module name (e.g. "ccai.ext.generated..good").
135
+ if len(leafcontainer) > 0:
136
+ nxtmodname = "%s.%s.%s" % (module_base, leafcontainer, nfbase)
137
+ else:
138
+ nxtmodname = "%s.%s" % (module_base, nfbase)
139
+
140
+ nxtmod = import_file(nxtmodname, filefull, by_file_only=True)
141
+ if nxtmod is None:
142
+ continue
143
+
144
+ ext_collection.extend(inspect.getmembers(nxtmod, predicate=is_extension_class))
145
+
146
+ return ext_collection
147
+
148
+
149
+ def generate_extension_key(*parts: str) -> str:
150
+ """
151
+ Generates a unique key that identifies an extension type based on where
152
+ it was found in a hiearchy of code containers.
153
+
154
+ :params parts: List of names of the path to the extension type
155
+
156
+ :returns: A unique path based identifier for a type.
157
+ """
158
+ extkey = "/".join(parts)
159
+ return extkey
160
+
@@ -0,0 +1,104 @@
1
+ """
2
+ .. module:: utilities
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Module that contains utility functions used to scan for factory protocol modules
5
+ and factory types.
6
+
7
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
8
+ """
9
+
10
+ __author__ = "Myron Walker"
11
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
12
+ __credits__ = []
13
+
14
+
15
+ import importlib
16
+ import importlib.util
17
+ import os
18
+ import sys
19
+
20
+
21
+ from types import ModuleType
22
+
23
+
24
+ is_python3 = sys.version_info[0] == 3
25
+ is_python_pre_3_5 = (is_python3 and sys.version_info[1] < 5)
26
+
27
+
28
+ def get_directory_for_code_container(container: ModuleType) -> str:
29
+ """
30
+ Returns the directory associated with a code container (module or package).
31
+
32
+ :param container: The module or package object you want to get a directory for.
33
+
34
+ :returns: The package directory for a package, or the directory containing the
35
+ module file for a module.
36
+ """
37
+ if hasattr(container, '__path__'):
38
+ container_dir = str(container.__path__[0]).rstrip(os.sep)
39
+ elif hasattr(container, '__file__'):
40
+ container_dir = os.path.dirname(container.__file__).rstrip(os.sep)
41
+ else:
42
+ raise RuntimeError("Unable to get parent dir for module") from None
43
+
44
+ return container_dir
45
+
46
+
47
+ def import_by_name(modulename: str) -> ModuleType:
48
+ """
49
+ Imports a module by name.
50
+ """
51
+
52
+ mod = None
53
+ if modulename in sys.modules:
54
+ mod = sys.modules[modulename]
55
+ else:
56
+ mod = importlib.import_module(modulename)
57
+
58
+ return mod
59
+
60
+
61
+ def import_file(name: str, loc: str, by_file_only: bool=False) -> ModuleType:
62
+ """
63
+ Import a module from a specific file path.
64
+
65
+ :param name: Name assigned to the loaded module.
66
+ :param loc: Filesystem path to the module file.
67
+ :param by_file_only: Only attempt loading from ``loc`` if ``True``.
68
+
69
+ :returns: The imported module.
70
+ :raises: ImportError if the module cannot be loaded by name or from ``loc``.
71
+ """
72
+ mod = None
73
+ if name in sys.modules:
74
+ mod = sys.modules[name]
75
+
76
+ if mod is None:
77
+ by_name_error = None
78
+
79
+ if not by_file_only:
80
+ # First try to import the module by name only. If that fails, keep
81
+ # the error so we can surface it as context if the file load also
82
+ # fails (rather than silently discarding it).
83
+ try:
84
+ mod = importlib.import_module(name)
85
+ except ImportError as imp_err:
86
+ by_name_error = imp_err
87
+
88
+ if mod is None:
89
+ spec = importlib.util.spec_from_file_location(name, str(loc))
90
+ if spec is None or spec.loader is None:
91
+ errmsg_lines = [
92
+ f"Unable to import module name='{name}' from location='{loc}'.",
93
+ "No import spec/loader could be created for the given location (the path may not exist or may not be a valid Python module)."
94
+ ]
95
+ if by_name_error is not None:
96
+ errmsg_lines.append(f"BY-NAME IMPORT ERROR: {by_name_error}")
97
+ errmsg = os.linesep.join(errmsg_lines)
98
+ raise ImportError(errmsg) from by_name_error
99
+
100
+ mod = importlib.util.module_from_spec(spec)
101
+ spec.loader.exec_module(mod)
102
+ sys.modules[name] = mod
103
+
104
+ return mod