cognihub-pygotemplate 0.0.2__cp310-cp310-macosx_12_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ from .engine import GoTemplateEngine
2
+
3
+ __all__ = ["GoTemplateEngine"]
@@ -0,0 +1,77 @@
1
+ """go包的包装器."""
2
+ import ctypes
3
+ import json
4
+ import os
5
+ import platform
6
+ import asyncio
7
+ from typing import Dict, Any
8
+
9
+
10
+ class GoTemplateEngine:
11
+ """
12
+ A Python interface to Go's text/template engine.
13
+ It relies on a pre-compiled shared library managed by the package installation process.
14
+ """
15
+ _go_lib = None
16
+ _free_func = None
17
+
18
+ def __init__(self, template_content: str):
19
+ self._load_library()
20
+ self.template_content = template_content
21
+
22
+ @classmethod
23
+ def _load_library(cls) -> None:
24
+ """Loads the pre-compiled Go shared library."""
25
+ if cls._go_lib:
26
+ return
27
+
28
+ lib_name = "librenderer.so"
29
+ if platform.system() == "Windows":
30
+ lib_name = "renderer.dll"
31
+ elif platform.system() == "Darwin":
32
+ lib_name = "librenderer.dylib"
33
+
34
+ # 库文件应该和这个Python文件在同一个目录下
35
+ lib_path = os.path.join(os.path.dirname(__file__), lib_name)
36
+
37
+ if not os.path.exists(lib_path):
38
+ raise FileNotFoundError(
39
+ f"Shared library not found at {lib_path}. "
40
+ "The package may not have been installed correctly. "
41
+ "Try reinstalling with 'pip install .'"
42
+ )
43
+
44
+ cls._go_lib = ctypes.CDLL(lib_path)
45
+
46
+ cls._go_lib.RenderTemplate.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
47
+ cls._go_lib.RenderTemplate.restype = ctypes.c_char_p
48
+
49
+ cls._go_lib.FreeString.argtypes = [ctypes.c_char_p]
50
+ cls._go_lib.FreeString.restype = None
51
+
52
+ cls._free_func = cls._go_lib.FreeString
53
+
54
+ def render(self, data: Dict[str, Any]) -> str:
55
+ """Renders the template with the given data."""
56
+ if not self._go_lib:
57
+ raise RuntimeError("Go renderer library is not loaded.")
58
+
59
+ template_bytes = self.template_content.encode('utf-8')
60
+ json_data_bytes = json.dumps(data).encode('utf-8')
61
+
62
+ result_ptr = self._go_lib.RenderTemplate(template_bytes, json_data_bytes)
63
+
64
+ try:
65
+ rendered_string = ctypes.string_at(result_ptr).decode('utf-8')
66
+ finally:
67
+ if self._free_func and result_ptr:
68
+ self._free_func(result_ptr)
69
+
70
+ if rendered_string.startswith(("JSON_ERROR:", "TEMPLATE_PARSE_ERROR:", "TEMPLATE_EXECUTE_ERROR:")):
71
+ raise ValueError(f"Error from Go renderer: {rendered_string}")
72
+
73
+ return rendered_string
74
+
75
+ async def render_async(self, data: Dict[str, Any]) -> str:
76
+ """Asynchronously renders the template with the given data."""
77
+ return await asyncio.to_thread(self.render, data)
@@ -0,0 +1,82 @@
1
+ /* Code generated by cmd/cgo; DO NOT EDIT. */
2
+
3
+ /* package command-line-arguments */
4
+
5
+
6
+ #line 1 "cgo-builtin-export-prolog"
7
+
8
+ #include <stddef.h>
9
+
10
+ #ifndef GO_CGO_EXPORT_PROLOGUE_H
11
+ #define GO_CGO_EXPORT_PROLOGUE_H
12
+
13
+ #ifndef GO_CGO_GOSTRING_TYPEDEF
14
+ typedef struct { const char *p; ptrdiff_t n; } _GoString_;
15
+ #endif
16
+
17
+ #endif
18
+
19
+ /* Start of preamble from import "C" comments. */
20
+
21
+
22
+
23
+
24
+ /* End of preamble from import "C" comments. */
25
+
26
+
27
+ /* Start of boilerplate cgo prologue. */
28
+ #line 1 "cgo-gcc-export-header-prolog"
29
+
30
+ #ifndef GO_CGO_PROLOGUE_H
31
+ #define GO_CGO_PROLOGUE_H
32
+
33
+ typedef signed char GoInt8;
34
+ typedef unsigned char GoUint8;
35
+ typedef short GoInt16;
36
+ typedef unsigned short GoUint16;
37
+ typedef int GoInt32;
38
+ typedef unsigned int GoUint32;
39
+ typedef long long GoInt64;
40
+ typedef unsigned long long GoUint64;
41
+ typedef GoInt64 GoInt;
42
+ typedef GoUint64 GoUint;
43
+ typedef size_t GoUintptr;
44
+ typedef float GoFloat32;
45
+ typedef double GoFloat64;
46
+ #ifdef _MSC_VER
47
+ #include <complex.h>
48
+ typedef _Fcomplex GoComplex64;
49
+ typedef _Dcomplex GoComplex128;
50
+ #else
51
+ typedef float _Complex GoComplex64;
52
+ typedef double _Complex GoComplex128;
53
+ #endif
54
+
55
+ /*
56
+ static assertion to make sure the file is being used on architecture
57
+ at least with matching size of GoInt.
58
+ */
59
+ typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1];
60
+
61
+ #ifndef GO_CGO_GOSTRING_TYPEDEF
62
+ typedef _GoString_ GoString;
63
+ #endif
64
+ typedef void *GoMap;
65
+ typedef void *GoChan;
66
+ typedef struct { void *t; void *v; } GoInterface;
67
+ typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;
68
+
69
+ #endif
70
+
71
+ /* End of boilerplate cgo prologue. */
72
+
73
+ #ifdef __cplusplus
74
+ extern "C" {
75
+ #endif
76
+
77
+ extern char* RenderTemplate(char* templateStr, char* jsonData);
78
+ extern void FreeString(char* str);
79
+
80
+ #ifdef __cplusplus
81
+ }
82
+ #endif
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 HUANG SIZHE
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,165 @@
1
+ Metadata-Version: 2.1
2
+ Name: cognihub-pygotemplate
3
+ Version: 0.0.2
4
+ Summary: A Python wrapper for Go's text/template engine via CGo
5
+ Author-email: hsz <hsz1273327@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/HszGitea/CogniHub/cognihub_pygotemplate
8
+ Project-URL: Repository, https://github.com/HszGitea/CogniHub/cognihub_pygotemplate
9
+ Project-URL: Issues, https://github.com/HszGitea/CogniHub/cognihub_pygotemplate/issues
10
+ Keywords: template,go,cgo,text-template,golang
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
14
+ Classifier: Topic :: Text Processing :: General
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Go
20
+ Classifier: License :: OSI Approved :: MIT License
21
+ Classifier: Operating System :: OS Independent
22
+ Classifier: Operating System :: POSIX :: Linux
23
+ Classifier: Operating System :: MacOS
24
+ Classifier: Operating System :: Microsoft :: Windows
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Provides-Extra: dev
29
+ Requires-Dist: coverage>=7.0; extra == "dev"
30
+ Requires-Dist: wheel>=0.40; extra == "dev"
31
+ Requires-Dist: mypy>=1.0; extra == "dev"
32
+
33
+ # cognihub_pygotemplate
34
+
35
+ A simple, high-performance Python wrapper for Go's native `text/template` engine.
36
+
37
+ *[中文文档](README_CN.md)*
38
+
39
+ This library allows you to use Go templates (like those from Ollama) directly in your Python projects with 100% compatibility, by calling a compiled Go shared library via CGo and Python's `ctypes`.
40
+
41
+ ## Prerequisites
42
+
43
+ - Python 3.10+
44
+ - Go compiler (1.21+ recommended) installed and available in your system's PATH
45
+
46
+ ## Installation
47
+
48
+ ### From PyPI (Recommended)
49
+
50
+ ```bash
51
+ pip install cognihub_pygotemplate
52
+ ```
53
+
54
+ ### From Source
55
+
56
+ ```bash
57
+ # Clone the repository
58
+ git clone https://github.com/hsz1273327/cognihub_pygotemplate.git
59
+ cd cognihub_pygotemplate
60
+
61
+ # Install the package
62
+ pip install .
63
+ ```
64
+
65
+ The library will automatically compile the Go source code during installation.
66
+
67
+ ## Usage
68
+
69
+ ```python
70
+ from cognihub_pygotemplate import GoTemplateEngine
71
+
72
+ # Your Go template string
73
+ template_str = """
74
+ Hello, {{.Name}}!
75
+ {{if .Items}}You have {{len .Items}} items:
76
+ {{range .Items}}- {{.}}
77
+ {{end}}{{else}}You have no items.{{end}}
78
+ """
79
+
80
+ # Data to render
81
+ data = {
82
+ "Name": "World",
83
+ "Items": ["apple", "banana", "cherry"]
84
+ }
85
+
86
+ try:
87
+ # Create an engine instance
88
+ engine = GoTemplateEngine(template_str)
89
+
90
+ # Render the template
91
+ output = engine.render(data)
92
+
93
+ print(output)
94
+
95
+ except (RuntimeError, ValueError) as e:
96
+ print(f"An error occurred: {e}")
97
+
98
+ ```
99
+
100
+ ## Development Workflow
101
+
102
+ Full development cycle: Clean -> Build -> Type Check -> Test. Iterate until requirements are met, then package.
103
+
104
+ ### Clean
105
+
106
+ ```bash
107
+ python setup.py clean
108
+ ```
109
+
110
+ ### Build
111
+
112
+ ```bash
113
+ python setup.py build_py
114
+ ```
115
+
116
+ ### Type Check
117
+
118
+ ```bash
119
+ # Use mypy for type checking
120
+ python setup.py type_check [--strict]
121
+ ```
122
+
123
+ ### Test
124
+
125
+ ```bash
126
+ # 运行所有测试
127
+ python setup.py test
128
+
129
+ # 或者执行单条测试
130
+ python -m unittest tests.test_engine.TestGoTemplateEngine.test_render
131
+ # 或者使用自定义测试运行器
132
+ ```
133
+
134
+ ### Build Wheels
135
+
136
+ ```bash
137
+ # For current platform
138
+ python setup.py bdist_wheel
139
+ ```
140
+
141
+ ## Features
142
+
143
+ - **100% Go Template Compatibility**: Uses Go's native `text/template` engine
144
+ - **High Performance**: Direct CGo bindings with minimal overhead
145
+ - **Cross-Platform**: Supports Windows, macOS (Intel & ARM64), and Linux
146
+ - **Memory Safe**: Proper memory management to prevent leaks
147
+ - **Easy Integration**: Simple Python API that feels native
148
+
149
+ ## Error Handling
150
+
151
+ The library provides clear error messages for common issues:
152
+
153
+ - `JSON_ERROR`: Invalid data format
154
+ - `TEMPLATE_PARSE_ERROR`: Template syntax errors
155
+ - `TEMPLATE_EXECUTE_ERROR`: Runtime template execution errors
156
+
157
+ ## License
158
+
159
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
160
+
161
+ ## Contributing
162
+
163
+ Contributions are welcome! Please feel free to submit a Pull Request.
164
+
165
+
@@ -0,0 +1,9 @@
1
+ cognihub_pygotemplate-0.0.2.data/purelib/cognihub_pygotemplate/__init__.py,sha256=m7jMRYxrh0lXrkjTDzymWvHEHyOaMty9MW1CJK8MPxU,68
2
+ cognihub_pygotemplate-0.0.2.data/purelib/cognihub_pygotemplate/engine.py,sha256=0mpSivMXp6D7RTqoZLdM7gN6hydp58UGMjgzHQP9gI8,2612
3
+ cognihub_pygotemplate-0.0.2.data/purelib/cognihub_pygotemplate/librenderer.dylib,sha256=4lUqF8VRKT66Avm2GwL12tHeXOCQlu2MEd5k-Vq5AUE,3044338
4
+ cognihub_pygotemplate-0.0.2.data/purelib/cognihub_pygotemplate/librenderer.h,sha256=qzF3oEGwKbkvXpAnRSHcIclMelEj6owWU6ryyoaP5tQ,1745
5
+ cognihub_pygotemplate-0.0.2.dist-info/LICENSE,sha256=3XBD597f722-JFXQre9mI-le0_Ct3-Jcf6d70THzErM,1068
6
+ cognihub_pygotemplate-0.0.2.dist-info/METADATA,sha256=Xn8deOVB3GRhQhCu4E56eAg-70uyVynp6_JFBjAfvls,4186
7
+ cognihub_pygotemplate-0.0.2.dist-info/WHEEL,sha256=q0TPgUxajuMfSTFwO3317FclNU7HRupUtKlJk4ZUMOs,110
8
+ cognihub_pygotemplate-0.0.2.dist-info/top_level.txt,sha256=JQidWgxvFtP5hdUE_k1A6f-P9ySD1LcxcsFCm5Zo-s4,22
9
+ cognihub_pygotemplate-0.0.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.45.1)
3
+ Root-Is-Purelib: false
4
+ Tag: cp310-cp310-macosx_12_0_arm64
5
+
@@ -0,0 +1 @@
1
+ cognihub_pygotemplate