110 lines
3.4 KiB
Python
110 lines
3.4 KiB
Python
#!/usr/bin/env python3.9
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
JFinal ClassPathSource - Class Path Source
|
|
"""
|
|
|
|
import importlib.resources
|
|
import os
|
|
|
|
class ClassPathSource:
|
|
"""Class path source for template loading"""
|
|
|
|
def __init__(self, base_template_path: str, fileName: str, encoding: str):
|
|
"""
|
|
Initialize class path source
|
|
|
|
Args:
|
|
base_template_path: Base template path
|
|
fileName: File name
|
|
encoding: Encoding
|
|
"""
|
|
self._fileName = fileName
|
|
self._encoding = encoding
|
|
self._baseTemplatePath = base_template_path
|
|
|
|
# Build resource path
|
|
if base_template_path:
|
|
self._resourcePath = os.path.join(base_template_path, fileName).replace('\\', '/')
|
|
else:
|
|
self._resourcePath = fileName.replace('\\', '/')
|
|
|
|
def get_content(self) -> str:
|
|
"""
|
|
Get class path resource content
|
|
|
|
Returns:
|
|
Resource content as string
|
|
"""
|
|
try:
|
|
# Try to load from classpath
|
|
import importlib
|
|
import sys
|
|
|
|
# Try different approaches to load resource
|
|
try:
|
|
# Try direct resource loading
|
|
with open(self._resourcePath, 'r', encoding=self._encoding) as f:
|
|
return f.read()
|
|
except:
|
|
# Try as package resource
|
|
if '.' in self._resourcePath:
|
|
parts = self._resourcePath.split('/')
|
|
if len(parts) > 1:
|
|
package_name = '.'.join(parts[:-1])
|
|
resource_name = parts[-1]
|
|
try:
|
|
with importlib.resources.open_text(package_name, resource_name, encoding=self._encoding) as f:
|
|
return f.read()
|
|
except:
|
|
pass
|
|
|
|
# Fall back to file system
|
|
return self._try_file_system()
|
|
|
|
except Exception as e:
|
|
raise RuntimeError(f"Error reading classpath resource {self._resourcePath}: {e}")
|
|
|
|
def _try_file_system(self) -> str:
|
|
"""
|
|
Try to load from file system as fallback
|
|
|
|
Returns:
|
|
File content as string
|
|
"""
|
|
# Try current directory
|
|
try:
|
|
current_dir = os.getcwd()
|
|
file_path = os.path.join(current_dir, self._resourcePath)
|
|
if os.path.exists(file_path):
|
|
with open(file_path, 'r', encoding=self._encoding) as f:
|
|
return f.read()
|
|
except:
|
|
pass
|
|
|
|
# Try absolute path
|
|
if os.path.isabs(self._resourcePath):
|
|
try:
|
|
with open(self._resourcePath, 'r', encoding=self._encoding) as f:
|
|
return f.read()
|
|
except:
|
|
pass
|
|
|
|
raise RuntimeError(f"Resource not found: {self._resourcePath}")
|
|
|
|
def is_modified(self) -> bool:
|
|
"""
|
|
Check if resource has been modified
|
|
|
|
Returns:
|
|
False for classpath resources (not supported)
|
|
"""
|
|
return False
|
|
|
|
def get_file_name(self) -> str:
|
|
"""Get file name"""
|
|
return self._fileName
|
|
|
|
def __repr__(self) -> str:
|
|
return f"ClassPathSource({self._fileName})"
|