inqaba 0.1.0__py3-none-any.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.
- inqaba/__init__.py +20 -0
- inqaba/config.py +169 -0
- inqaba/entry.py +109 -0
- inqaba/files.py +31 -0
- inqaba/json5.py +213 -0
- inqaba/path.py +113 -0
- inqaba-0.1.0.dist-info/METADATA +45 -0
- inqaba-0.1.0.dist-info/RECORD +9 -0
- inqaba-0.1.0.dist-info/WHEEL +4 -0
inqaba/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Shared Python framework boundaries for RAIkeep."""
|
|
2
|
+
|
|
3
|
+
from .files import InqFile, InqJsonFile, InqTextFile
|
|
4
|
+
from .entry import InqEntry
|
|
5
|
+
from .config import DEFAULT_CONFIG_FILE_LOCATION, InqConfig
|
|
6
|
+
from .path import InqPath, InqPathError, InqRelPath
|
|
7
|
+
|
|
8
|
+
__version__ = "0.1.0"
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"InqEntry",
|
|
12
|
+
"InqFile",
|
|
13
|
+
"InqConfig",
|
|
14
|
+
"InqJsonFile",
|
|
15
|
+
"InqPath",
|
|
16
|
+
"InqPathError",
|
|
17
|
+
"InqRelPath",
|
|
18
|
+
"InqTextFile",
|
|
19
|
+
"DEFAULT_CONFIG_FILE_LOCATION",
|
|
20
|
+
]
|
inqaba/config.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Shared configuration discovery and cloud roots for RAIkeep."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import os
|
|
4
|
+
from typing import Any
|
|
5
|
+
from .entry import InqEntry
|
|
6
|
+
from .path import InqPath
|
|
7
|
+
from .json5 import loads_json5
|
|
8
|
+
|
|
9
|
+
DEFAULT_CONFIG_FILE_LOCATION: str = "~/.config/RAIkeep.json5"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def missing_configuration_diagnostic() -> str:
|
|
13
|
+
"""
|
|
14
|
+
CR044 §7.4: Standardized diagnostic when RAIkeep configuration is not found.
|
|
15
|
+
Directs the operator to 'amafu init'.
|
|
16
|
+
"""
|
|
17
|
+
return (
|
|
18
|
+
f"RAIkeep configuration was not found at '{DEFAULT_CONFIG_FILE_LOCATION}'. "
|
|
19
|
+
"Run 'amafu init' to detect cloud providers and create it."
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class InqConfig:
|
|
24
|
+
"""
|
|
25
|
+
System configuration derived from ~/.config/RAIkeep.json5 or fallback files.
|
|
26
|
+
Provides authoritative cloud drive paths, temporary directories, and backup paths.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
_instance: InqConfig | None = None
|
|
30
|
+
|
|
31
|
+
def __init__(self, config_dict: dict[str, Any] | None = None, config_path: InqEntry | None = None) -> None:
|
|
32
|
+
self._config_path = config_path
|
|
33
|
+
raw = config_dict or {}
|
|
34
|
+
|
|
35
|
+
# TempDir
|
|
36
|
+
raw_temp = raw.get("TempDir", "~/temp/")
|
|
37
|
+
self.temp_dir: InqEntry = self._normalize_path(raw_temp)
|
|
38
|
+
|
|
39
|
+
# LocalBackupDir
|
|
40
|
+
raw_backup = raw.get("LocalBackupDir")
|
|
41
|
+
self.local_backup_dir: InqEntry | None = self._normalize_path(raw_backup) if raw_backup else None
|
|
42
|
+
|
|
43
|
+
# SyncPropagationDelayMs
|
|
44
|
+
self.sync_propagation_delay_ms: int = int(raw.get("SyncPropagationDelayMs", 10000))
|
|
45
|
+
|
|
46
|
+
# DefaultCloudOrder
|
|
47
|
+
self.default_cloud_order: list[str] = list(
|
|
48
|
+
raw.get("DefaultCloudOrder", ["OneDrive", "Dropbox", "GoogleDrive", "ICloudDrive"])
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
# Cloud roots
|
|
52
|
+
self.clouds: dict[str, InqEntry] = {}
|
|
53
|
+
raw_cloud = raw.get("Cloud", {})
|
|
54
|
+
if isinstance(raw_cloud, dict):
|
|
55
|
+
for name, path_str in raw_cloud.items():
|
|
56
|
+
if path_str:
|
|
57
|
+
self.clouds[name] = self._normalize_path(str(path_str))
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def is_config_loaded(self) -> bool:
|
|
61
|
+
"""Returns True if configuration was loaded from a file or explicit dictionary."""
|
|
62
|
+
return self._config_path is not None or bool(self.clouds)
|
|
63
|
+
|
|
64
|
+
@classmethod
|
|
65
|
+
def reset(cls) -> None:
|
|
66
|
+
"""Resets the singleton instance (used in tests)."""
|
|
67
|
+
cls._instance = None
|
|
68
|
+
|
|
69
|
+
@staticmethod
|
|
70
|
+
def _normalize_path(p: str) -> InqEntry:
|
|
71
|
+
expanded = os.path.expanduser(p.strip())
|
|
72
|
+
return InqPath.from_directory(expanded)
|
|
73
|
+
|
|
74
|
+
@staticmethod
|
|
75
|
+
def find_config_file() -> InqEntry | None:
|
|
76
|
+
"""Locates the active configuration file according to ecosystem precedence."""
|
|
77
|
+
# 1. Environment variable override
|
|
78
|
+
for env_var in ("JSONPIT_CONFIG", "RAIKEEP_CONFIG"):
|
|
79
|
+
val = os.getenv(env_var)
|
|
80
|
+
if val:
|
|
81
|
+
p = InqEntry(os.path.expanduser(val))
|
|
82
|
+
if p.is_file():
|
|
83
|
+
return p
|
|
84
|
+
|
|
85
|
+
# 2. Shared ecosystem ground truth: ~/.config/RAIkeep.json5
|
|
86
|
+
raikeep = InqEntry(os.path.expanduser("~/.config/RAIkeep.json5"))
|
|
87
|
+
if raikeep.is_file():
|
|
88
|
+
return raikeep
|
|
89
|
+
|
|
90
|
+
# 3. Python-specific fallback: ~/.config/umgodi.json5
|
|
91
|
+
umgodi_conf = InqEntry(os.path.expanduser("~/.config/umgodi.json5"))
|
|
92
|
+
if umgodi_conf.is_file():
|
|
93
|
+
return umgodi_conf
|
|
94
|
+
|
|
95
|
+
# 4. XDG fallback: $XDG_CONFIG_HOME/umgodi/config.json5
|
|
96
|
+
xdg_config = os.getenv("XDG_CONFIG_HOME")
|
|
97
|
+
if xdg_config:
|
|
98
|
+
xdg_path = InqEntry(os.path.expanduser(xdg_config)) / "umgodi" / "config.json5"
|
|
99
|
+
if xdg_path.is_file():
|
|
100
|
+
return xdg_path
|
|
101
|
+
|
|
102
|
+
return None
|
|
103
|
+
|
|
104
|
+
@classmethod
|
|
105
|
+
def load(cls, config_path: InqEntry | str | None = None) -> InqConfig:
|
|
106
|
+
"""Loads InqConfig from file or singleton instance."""
|
|
107
|
+
if config_path is not None:
|
|
108
|
+
p = InqEntry(os.path.expanduser(str(config_path)))
|
|
109
|
+
if p.is_file():
|
|
110
|
+
data = loads_json5(p.read_text(encoding="utf-8"))
|
|
111
|
+
return cls(data, config_path=p)
|
|
112
|
+
raise FileNotFoundError(f"Configuration file not found: {p}")
|
|
113
|
+
|
|
114
|
+
if cls._instance is not None:
|
|
115
|
+
return cls._instance
|
|
116
|
+
|
|
117
|
+
resolved_file = cls.find_config_file()
|
|
118
|
+
if resolved_file and resolved_file.is_file():
|
|
119
|
+
try:
|
|
120
|
+
data = loads_json5(resolved_file.read_text(encoding="utf-8"))
|
|
121
|
+
cls._instance = cls(data, config_path=resolved_file)
|
|
122
|
+
return cls._instance
|
|
123
|
+
except Exception:
|
|
124
|
+
pass
|
|
125
|
+
|
|
126
|
+
# Fallback default configuration
|
|
127
|
+
cls._instance = cls({}, config_path=None)
|
|
128
|
+
return cls._instance
|
|
129
|
+
|
|
130
|
+
def get_cloud_root(self, cloud_name: str | None = None) -> InqEntry | None:
|
|
131
|
+
"""Returns the InqEntry to the requested cloud drive root, or default."""
|
|
132
|
+
if cloud_name:
|
|
133
|
+
# Check case-insensitive match
|
|
134
|
+
for k, v in self.clouds.items():
|
|
135
|
+
if k.lower() == cloud_name.lower():
|
|
136
|
+
return v
|
|
137
|
+
return None
|
|
138
|
+
# Use default cloud order
|
|
139
|
+
for cloud in self.default_cloud_order:
|
|
140
|
+
root = self.get_cloud_root(cloud)
|
|
141
|
+
if root and root.exists():
|
|
142
|
+
return root
|
|
143
|
+
return None
|
|
144
|
+
|
|
145
|
+
def is_cloud_path(self, path: InqEntry | str) -> bool:
|
|
146
|
+
"""
|
|
147
|
+
Returns True if the target path is inside any known cloud drive root.
|
|
148
|
+
Resolves symbolic shortcuts and existing ancestors matching CR051.
|
|
149
|
+
"""
|
|
150
|
+
target = InqEntry(os.path.abspath(os.path.expanduser(str(path))))
|
|
151
|
+
try:
|
|
152
|
+
target_resolved = target.resolve()
|
|
153
|
+
except Exception:
|
|
154
|
+
target_resolved = target
|
|
155
|
+
|
|
156
|
+
for root in self.clouds.values():
|
|
157
|
+
try:
|
|
158
|
+
root_resolved = root.resolve()
|
|
159
|
+
except Exception:
|
|
160
|
+
root_resolved = root
|
|
161
|
+
|
|
162
|
+
for cand in (target, target_resolved):
|
|
163
|
+
for r in (root, root_resolved):
|
|
164
|
+
try:
|
|
165
|
+
cand.relative_to(r)
|
|
166
|
+
return True
|
|
167
|
+
except ValueError:
|
|
168
|
+
continue
|
|
169
|
+
return False
|
inqaba/entry.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""PathLike interoperability for inputs whose file/directory kind is not yet known.
|
|
2
|
+
|
|
3
|
+
InqEntry deliberately exposes an explicit, bounded API rather than forwarding
|
|
4
|
+
arbitrary pathlib attributes. Domain code uses InqPath and InqFile once known.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
import shutil
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class InqEntry(os.PathLike[str]):
|
|
14
|
+
def __init__(self, value="."):
|
|
15
|
+
self._native = Path(value)
|
|
16
|
+
|
|
17
|
+
def as_path(self):
|
|
18
|
+
return self._native
|
|
19
|
+
|
|
20
|
+
def as_posix(self):
|
|
21
|
+
return self._native.as_posix()
|
|
22
|
+
|
|
23
|
+
def __fspath__(self):
|
|
24
|
+
return str(self._native)
|
|
25
|
+
|
|
26
|
+
def __str__(self):
|
|
27
|
+
return str(self._native)
|
|
28
|
+
|
|
29
|
+
def __hash__(self):
|
|
30
|
+
return hash(self._native)
|
|
31
|
+
|
|
32
|
+
def __eq__(self, other):
|
|
33
|
+
if not isinstance(other, os.PathLike):
|
|
34
|
+
return NotImplemented
|
|
35
|
+
return self._native == Path(other)
|
|
36
|
+
|
|
37
|
+
def __lt__(self, other):
|
|
38
|
+
return self._native < Path(other)
|
|
39
|
+
|
|
40
|
+
@classmethod
|
|
41
|
+
def cwd(cls):
|
|
42
|
+
from .path import InqPath
|
|
43
|
+
return InqPath.from_directory(Path.cwd())
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def parent(self):
|
|
47
|
+
from .path import InqPath
|
|
48
|
+
return InqPath.from_directory(self._native.parent)
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def parents(self):
|
|
52
|
+
from .path import InqPath
|
|
53
|
+
return tuple(InqPath.from_directory(p) for p in self._native.parents)
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def name(self): return self._native.name
|
|
57
|
+
@property
|
|
58
|
+
def stem(self): return self._native.stem
|
|
59
|
+
@property
|
|
60
|
+
def suffix(self): return self._native.suffix
|
|
61
|
+
@property
|
|
62
|
+
def parts(self): return self._native.parts
|
|
63
|
+
|
|
64
|
+
def __truediv__(self, other):
|
|
65
|
+
return InqEntry(self._native / os.fspath(other))
|
|
66
|
+
|
|
67
|
+
def expanduser(self): return type(self)(self._native.expanduser())
|
|
68
|
+
def absolute(self): return type(self)(self._native.absolute())
|
|
69
|
+
def resolve(self, strict=False): return type(self)(self._native.resolve(strict=strict))
|
|
70
|
+
def is_absolute(self): return self._native.is_absolute()
|
|
71
|
+
def relative_to(self, other): return InqEntry(self._native.relative_to(other))
|
|
72
|
+
def with_suffix(self, suffix):
|
|
73
|
+
from .files import InqFile
|
|
74
|
+
return InqFile(self._native.with_suffix(suffix))
|
|
75
|
+
def exists(self): return self._native.exists()
|
|
76
|
+
def is_file(self): return self._native.is_file()
|
|
77
|
+
def is_dir(self): return self._native.is_dir()
|
|
78
|
+
def stat(self): return self._native.stat()
|
|
79
|
+
def mkdir(self, mode=0o777, parents=False, exist_ok=False):
|
|
80
|
+
self._native.mkdir(mode=mode, parents=parents, exist_ok=exist_ok)
|
|
81
|
+
def unlink(self, missing_ok=False): self._native.unlink(missing_ok=missing_ok)
|
|
82
|
+
def rename(self, target): return InqEntry(self._native.rename(target))
|
|
83
|
+
def replace(self, target): return InqEntry(self._native.replace(target))
|
|
84
|
+
def open(self, *args, **kwargs): return self._native.open(*args, **kwargs)
|
|
85
|
+
def read_text(self, encoding="utf-8", **kwargs): return self._native.read_text(encoding=encoding, **kwargs)
|
|
86
|
+
def write_text(self, content, encoding="utf-8", **kwargs): return self._native.write_text(content, encoding=encoding, **kwargs)
|
|
87
|
+
def read_bytes(self): return self._native.read_bytes()
|
|
88
|
+
def write_bytes(self, content): return self._native.write_bytes(content)
|
|
89
|
+
|
|
90
|
+
@staticmethod
|
|
91
|
+
def _typed(path):
|
|
92
|
+
from .path import InqPath
|
|
93
|
+
from .files import InqFile
|
|
94
|
+
return InqPath.from_directory(path) if path.is_dir() else InqFile(path)
|
|
95
|
+
|
|
96
|
+
def iterdir(self):
|
|
97
|
+
return (self._typed(p) for p in self._native.iterdir())
|
|
98
|
+
|
|
99
|
+
def glob(self, pattern):
|
|
100
|
+
return (self._typed(p) for p in self._native.glob(pattern))
|
|
101
|
+
|
|
102
|
+
def copy_to(self, target):
|
|
103
|
+
return InqEntry(shutil.copy2(self._native, target))
|
|
104
|
+
|
|
105
|
+
def write_durable(self, content):
|
|
106
|
+
with self.open("w", encoding="utf-8", newline="") as stream:
|
|
107
|
+
stream.write(content)
|
|
108
|
+
stream.flush()
|
|
109
|
+
os.fsync(stream.fileno())
|
inqaba/files.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""File objects keep filesystem access inside Inqaba."""
|
|
2
|
+
import json
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from .entry import InqEntry
|
|
5
|
+
from .path import InqPathError
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class InqFile(InqEntry):
|
|
9
|
+
def __init__(self, parent, name=None):
|
|
10
|
+
if name is None:
|
|
11
|
+
super().__init__(parent)
|
|
12
|
+
else:
|
|
13
|
+
if not name or name in (".", "..") or "/" in name or "\\" in name or Path(name).is_absolute():
|
|
14
|
+
raise InqPathError("a file name must be a single terminal name")
|
|
15
|
+
super().__init__(Path(parent) / name)
|
|
16
|
+
|
|
17
|
+
@property
|
|
18
|
+
def full_name(self): return str(self)
|
|
19
|
+
def delete(self): self.unlink(missing_ok=True)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class InqTextFile(InqFile):
|
|
23
|
+
"""UTF-8 text file; durable writes preserve the existing inode."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class InqJsonFile(InqTextFile):
|
|
27
|
+
def read_json(self, encoding="utf-8"):
|
|
28
|
+
return json.loads(self.read_text(encoding=encoding))
|
|
29
|
+
|
|
30
|
+
def write_json(self, value, encoding="utf-8"):
|
|
31
|
+
self.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding=encoding)
|
inqaba/json5.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""JSON5 subset parser shared by configuration and ingestion."""
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
def loads_json5(text: str) -> Any:
|
|
5
|
+
"""
|
|
6
|
+
Parses a JSON5 string into Python dictionaries, lists, strings, numbers, booleans, or None.
|
|
7
|
+
Supports unquoted keys, single and double quotes, trailing commas, line comments (//),
|
|
8
|
+
and block comments (/* ... */) without third-party dependencies.
|
|
9
|
+
"""
|
|
10
|
+
# Step 1: Strip comments while respecting strings
|
|
11
|
+
chars = list(text)
|
|
12
|
+
n = len(chars)
|
|
13
|
+
i = 0
|
|
14
|
+
cleaned: list[str] = []
|
|
15
|
+
in_string: str | None = None
|
|
16
|
+
escape = False
|
|
17
|
+
|
|
18
|
+
while i < n:
|
|
19
|
+
c = chars[i]
|
|
20
|
+
if in_string:
|
|
21
|
+
cleaned.append(c)
|
|
22
|
+
if escape:
|
|
23
|
+
escape = False
|
|
24
|
+
elif c == "\\":
|
|
25
|
+
escape = True
|
|
26
|
+
elif c == in_string:
|
|
27
|
+
in_string = None
|
|
28
|
+
i += 1
|
|
29
|
+
else:
|
|
30
|
+
if c in ('"', "'"):
|
|
31
|
+
in_string = c
|
|
32
|
+
cleaned.append(c)
|
|
33
|
+
i += 1
|
|
34
|
+
elif c == "/" and i + 1 < n and chars[i + 1] == "/":
|
|
35
|
+
# Line comment
|
|
36
|
+
i += 2
|
|
37
|
+
while i < n and chars[i] not in ("\r", "\n"):
|
|
38
|
+
i += 1
|
|
39
|
+
elif c == "/" and i + 1 < n and chars[i + 1] == "*":
|
|
40
|
+
# Block comment
|
|
41
|
+
i += 2
|
|
42
|
+
while i + 1 < n and not (chars[i] == "*" and chars[i + 1] == "/"):
|
|
43
|
+
i += 1
|
|
44
|
+
i += 2
|
|
45
|
+
else:
|
|
46
|
+
cleaned.append(c)
|
|
47
|
+
i += 1
|
|
48
|
+
|
|
49
|
+
cleaned_str = "".join(cleaned)
|
|
50
|
+
pos = 0
|
|
51
|
+
length = len(cleaned_str)
|
|
52
|
+
|
|
53
|
+
def skip_ws() -> None:
|
|
54
|
+
nonlocal pos
|
|
55
|
+
while pos < length and cleaned_str[pos].isspace():
|
|
56
|
+
pos += 1
|
|
57
|
+
|
|
58
|
+
def parse_value() -> Any:
|
|
59
|
+
skip_ws()
|
|
60
|
+
if pos >= length:
|
|
61
|
+
raise ValueError("Unexpected end of JSON5 input")
|
|
62
|
+
ch = cleaned_str[pos]
|
|
63
|
+
if ch == "{":
|
|
64
|
+
return parse_object()
|
|
65
|
+
elif ch == "[":
|
|
66
|
+
return parse_array()
|
|
67
|
+
elif ch in ('"', "'"):
|
|
68
|
+
return parse_string()
|
|
69
|
+
elif ch in ("t", "f"):
|
|
70
|
+
return parse_bool()
|
|
71
|
+
elif ch == "n":
|
|
72
|
+
return parse_null()
|
|
73
|
+
else:
|
|
74
|
+
return parse_number_or_ident()
|
|
75
|
+
|
|
76
|
+
def parse_string() -> str:
|
|
77
|
+
nonlocal pos
|
|
78
|
+
quote = cleaned_str[pos]
|
|
79
|
+
pos += 1
|
|
80
|
+
res: list[str] = []
|
|
81
|
+
while pos < length:
|
|
82
|
+
c = cleaned_str[pos]
|
|
83
|
+
if c == "\\":
|
|
84
|
+
pos += 1
|
|
85
|
+
if pos >= length:
|
|
86
|
+
raise ValueError("Unterminated escape sequence")
|
|
87
|
+
esc = cleaned_str[pos]
|
|
88
|
+
if esc == "n":
|
|
89
|
+
res.append("\n")
|
|
90
|
+
elif esc == "r":
|
|
91
|
+
res.append("\r")
|
|
92
|
+
elif esc == "t":
|
|
93
|
+
res.append("\t")
|
|
94
|
+
elif esc == "\\":
|
|
95
|
+
res.append("\\")
|
|
96
|
+
elif esc == quote:
|
|
97
|
+
res.append(quote)
|
|
98
|
+
elif esc == "/":
|
|
99
|
+
res.append("/")
|
|
100
|
+
else:
|
|
101
|
+
res.append(esc)
|
|
102
|
+
pos += 1
|
|
103
|
+
elif c == quote:
|
|
104
|
+
pos += 1
|
|
105
|
+
return "".join(res)
|
|
106
|
+
else:
|
|
107
|
+
res.append(c)
|
|
108
|
+
pos += 1
|
|
109
|
+
raise ValueError("Unterminated string literal")
|
|
110
|
+
|
|
111
|
+
def parse_object() -> dict[str, Any]:
|
|
112
|
+
nonlocal pos
|
|
113
|
+
pos += 1 # skip {
|
|
114
|
+
obj: dict[str, Any] = {}
|
|
115
|
+
while True:
|
|
116
|
+
skip_ws()
|
|
117
|
+
if pos >= length:
|
|
118
|
+
raise ValueError("Unterminated JSON5 object")
|
|
119
|
+
if cleaned_str[pos] == "}":
|
|
120
|
+
pos += 1
|
|
121
|
+
return obj
|
|
122
|
+
# Key: either quoted string or bare identifier
|
|
123
|
+
if cleaned_str[pos] in ('"', "'"):
|
|
124
|
+
key = parse_string()
|
|
125
|
+
else:
|
|
126
|
+
k_start = pos
|
|
127
|
+
while pos < length and (
|
|
128
|
+
cleaned_str[pos].isalnum() or cleaned_str[pos] in ("_", "$", "-")
|
|
129
|
+
):
|
|
130
|
+
pos += 1
|
|
131
|
+
key = cleaned_str[k_start:pos]
|
|
132
|
+
if not key:
|
|
133
|
+
raise ValueError(f"Invalid key at position {pos}")
|
|
134
|
+
skip_ws()
|
|
135
|
+
if pos >= length or cleaned_str[pos] != ":":
|
|
136
|
+
raise ValueError(f"Expected ':' at position {pos}")
|
|
137
|
+
pos += 1 # skip :
|
|
138
|
+
val = parse_value()
|
|
139
|
+
obj[key] = val
|
|
140
|
+
skip_ws()
|
|
141
|
+
if pos < length and cleaned_str[pos] == ",":
|
|
142
|
+
pos += 1
|
|
143
|
+
skip_ws()
|
|
144
|
+
elif pos < length and cleaned_str[pos] == "}":
|
|
145
|
+
pass
|
|
146
|
+
else:
|
|
147
|
+
raise ValueError(f"Expected ',' or '}}' at position {pos}")
|
|
148
|
+
|
|
149
|
+
def parse_array() -> list[Any]:
|
|
150
|
+
nonlocal pos
|
|
151
|
+
pos += 1 # skip [
|
|
152
|
+
arr: list[Any] = []
|
|
153
|
+
while True:
|
|
154
|
+
skip_ws()
|
|
155
|
+
if pos >= length:
|
|
156
|
+
raise ValueError("Unterminated JSON5 array")
|
|
157
|
+
if cleaned_str[pos] == "]":
|
|
158
|
+
pos += 1
|
|
159
|
+
return arr
|
|
160
|
+
val = parse_value()
|
|
161
|
+
arr.append(val)
|
|
162
|
+
skip_ws()
|
|
163
|
+
if pos < length and cleaned_str[pos] == ",":
|
|
164
|
+
pos += 1
|
|
165
|
+
skip_ws()
|
|
166
|
+
elif pos < length and cleaned_str[pos] == "]":
|
|
167
|
+
pass
|
|
168
|
+
else:
|
|
169
|
+
raise ValueError(f"Expected ',' or ']' at position {pos}")
|
|
170
|
+
|
|
171
|
+
def parse_bool() -> bool:
|
|
172
|
+
nonlocal pos
|
|
173
|
+
if cleaned_str.startswith("true", pos):
|
|
174
|
+
pos += 4
|
|
175
|
+
return True
|
|
176
|
+
if cleaned_str.startswith("false", pos):
|
|
177
|
+
pos += 5
|
|
178
|
+
return False
|
|
179
|
+
raise ValueError(f"Unknown literal at position {pos}")
|
|
180
|
+
|
|
181
|
+
def parse_null() -> None:
|
|
182
|
+
nonlocal pos
|
|
183
|
+
if cleaned_str.startswith("null", pos):
|
|
184
|
+
pos += 4
|
|
185
|
+
return None
|
|
186
|
+
raise ValueError(f"Unknown literal at position {pos}")
|
|
187
|
+
|
|
188
|
+
def parse_number_or_ident() -> Any:
|
|
189
|
+
nonlocal pos
|
|
190
|
+
start = pos
|
|
191
|
+
if cleaned_str[pos] in ("-", "+"):
|
|
192
|
+
pos += 1
|
|
193
|
+
while pos < length and (
|
|
194
|
+
cleaned_str[pos].isalnum() or cleaned_str[pos] in (".", "-", "+")
|
|
195
|
+
):
|
|
196
|
+
pos += 1
|
|
197
|
+
raw = cleaned_str[start:pos]
|
|
198
|
+
if not raw:
|
|
199
|
+
raise ValueError(f"Invalid value at position {pos}")
|
|
200
|
+
try:
|
|
201
|
+
if "." in raw or "e" in raw or "E" in raw:
|
|
202
|
+
return float(raw)
|
|
203
|
+
if raw.startswith(("0x", "0X")):
|
|
204
|
+
return int(raw, 16)
|
|
205
|
+
return int(raw)
|
|
206
|
+
except ValueError:
|
|
207
|
+
return raw
|
|
208
|
+
|
|
209
|
+
result = parse_value()
|
|
210
|
+
skip_ws()
|
|
211
|
+
if pos != length:
|
|
212
|
+
raise ValueError(f"Unexpected trailing content at position {pos}")
|
|
213
|
+
return result
|
inqaba/path.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Typed absolute and relative directory paths for the RAIkeep Python stack."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from .entry import InqEntry
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class InqPathError(ValueError):
|
|
11
|
+
"""Raised when a path violates the Inqaba path contract."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _text(value: str | os.PathLike[str]) -> str:
|
|
15
|
+
value = os.fspath(value)
|
|
16
|
+
if not isinstance(value, str):
|
|
17
|
+
raise TypeError("path values must be text")
|
|
18
|
+
return value.strip()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True, slots=True)
|
|
22
|
+
class InqRelPath(os.PathLike[str]):
|
|
23
|
+
"""Relative directory path; filenames are intentionally not represented here."""
|
|
24
|
+
|
|
25
|
+
value: str = ""
|
|
26
|
+
|
|
27
|
+
def __post_init__(self) -> None:
|
|
28
|
+
raw = _text(self.value).replace("\\", os.sep)
|
|
29
|
+
if raw in ("", "."):
|
|
30
|
+
object.__setattr__(self, "value", "")
|
|
31
|
+
return
|
|
32
|
+
if os.path.isabs(raw) or raw == "~" or raw.startswith("~/") or (len(raw) > 1 and raw[1] == ":"):
|
|
33
|
+
raise InqPathError("InqRelPath requires a relative path")
|
|
34
|
+
explicit_directory = raw.endswith(os.sep)
|
|
35
|
+
if explicit_directory:
|
|
36
|
+
raw = raw.rstrip(os.sep)
|
|
37
|
+
# A terminal filename is not a relative directory path. Match the
|
|
38
|
+
# OsLib split convention: constructing a relative path from a bare
|
|
39
|
+
# filename yields the empty path (displayed as '.').
|
|
40
|
+
if not explicit_directory and os.sep not in raw and Path(raw).suffix:
|
|
41
|
+
object.__setattr__(self, "value", "")
|
|
42
|
+
return
|
|
43
|
+
parts = [part for part in raw.split(os.sep) if part not in ("", ".")]
|
|
44
|
+
if any(part == ".." for part in parts):
|
|
45
|
+
raise InqPathError("InqRelPath cannot escape its anchor")
|
|
46
|
+
object.__setattr__(self, "value", os.sep.join(parts))
|
|
47
|
+
|
|
48
|
+
def __fspath__(self) -> str:
|
|
49
|
+
return self.value
|
|
50
|
+
|
|
51
|
+
def __str__(self) -> str:
|
|
52
|
+
return self.value or "."
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def segments(self) -> tuple[str, ...]:
|
|
56
|
+
return tuple(self.value.split(os.sep)) if self.value else ()
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def depth(self) -> int:
|
|
60
|
+
return len(self.segments)
|
|
61
|
+
|
|
62
|
+
def __truediv__(self, other: str | "InqRelPath") -> "InqRelPath":
|
|
63
|
+
if isinstance(other, InqRelPath):
|
|
64
|
+
part = other.value
|
|
65
|
+
else:
|
|
66
|
+
part = _text(other)
|
|
67
|
+
if os.path.basename(part) != part or part.endswith((".pit", ".json", ".txt")):
|
|
68
|
+
raise InqPathError("filenames belong at an anchored path, not InqRelPath")
|
|
69
|
+
return InqRelPath(os.path.join(self.value, part))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class InqPath(InqEntry):
|
|
73
|
+
"""Absolute directory path with safe relative composition."""
|
|
74
|
+
|
|
75
|
+
def __init__(self, value=".") -> None:
|
|
76
|
+
path = Path(value).expanduser()
|
|
77
|
+
if not path.is_absolute():
|
|
78
|
+
path = Path.cwd() / path
|
|
79
|
+
self._native = Path(os.path.abspath(path))
|
|
80
|
+
|
|
81
|
+
@classmethod
|
|
82
|
+
def from_directory(cls, value: str | os.PathLike[str] | Path) -> "InqPath":
|
|
83
|
+
return cls(Path(_text(value)))
|
|
84
|
+
|
|
85
|
+
@classmethod
|
|
86
|
+
def from_path(cls, value: str | os.PathLike[str] | Path) -> "InqPath":
|
|
87
|
+
return cls(Path(_text(value)))
|
|
88
|
+
|
|
89
|
+
def __fspath__(self) -> str:
|
|
90
|
+
return str(self._native)
|
|
91
|
+
|
|
92
|
+
def __str__(self) -> str:
|
|
93
|
+
return str(self._native)
|
|
94
|
+
|
|
95
|
+
def as_path(self) -> Path:
|
|
96
|
+
return self._native
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def segments(self) -> tuple[str, ...]:
|
|
100
|
+
return self._native.parts
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def depth(self) -> int:
|
|
104
|
+
return len(self.segments)
|
|
105
|
+
|
|
106
|
+
def __truediv__(self, other: str | InqRelPath):
|
|
107
|
+
if isinstance(other, InqRelPath):
|
|
108
|
+
return InqPath(self._native / other.value)
|
|
109
|
+
name = _text(other)
|
|
110
|
+
if not name or os.path.basename(name) != name:
|
|
111
|
+
raise InqPathError("path composition accepts one relative segment or filename")
|
|
112
|
+
from .files import InqFile
|
|
113
|
+
return InqFile(self, name)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: inqaba
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Shared Python filesystem, configuration, command, and media boundaries for RAIkeep.
|
|
5
|
+
Project-URL: Repository, https://github.com/Burkhardt/inqaba
|
|
6
|
+
Project-URL: ReleaseNotes, https://github.com/Burkhardt/RAIkeep/blob/main/doc/releases/v4.x/inqaba_RELEASE_NOTES_4.x.md
|
|
7
|
+
Author: Dr. Rainer Burkhardt
|
|
8
|
+
License: Apache-2.0
|
|
9
|
+
Requires-Python: >=3.12
|
|
10
|
+
Provides-Extra: dev
|
|
11
|
+
Requires-Dist: build; extra == 'dev'
|
|
12
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
13
|
+
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
|
|
14
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
15
|
+
Requires-Dist: ruff>=0.5; extra == 'dev'
|
|
16
|
+
Requires-Dist: twine; extra == 'dev'
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
<p align="center">
|
|
20
|
+
<img src="https://raw.githubusercontent.com/Burkhardt/inqaba/main/assets/inqaba-soweto-twins.svg" width="180" height="180" alt="Inqaba Soweto Twins Logo" />
|
|
21
|
+
</p>
|
|
22
|
+
|
|
23
|
+
# inqaba
|
|
24
|
+
|
|
25
|
+
Install the `inqaba` distribution with `python -m pip install inqaba`.
|
|
26
|
+
|
|
27
|
+
Shared Python framework boundaries for RAIkeep. The public API begins with
|
|
28
|
+
`Inq*` names and currently provides typed path, file, and configuration
|
|
29
|
+
objects for the active Python projects. Command and media APIs remain planned.
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from inqaba import InqPath, InqRelPath
|
|
33
|
+
|
|
34
|
+
root = InqPath.from_directory("/srv/jsonpit/")
|
|
35
|
+
people = root / InqRelPath("People")
|
|
36
|
+
person_file = people / "Person.pit"
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`InqRelPath` represents directory segments. A terminal filename is supplied as
|
|
40
|
+
a string and is not itself a relative directory path.
|
|
41
|
+
|
|
42
|
+
See the [rendered class diagram](https://github.com/Burkhardt/inqaba/blob/main/doc/inqaba-class-diagram.svg), its
|
|
43
|
+
[PlantUML source](https://github.com/Burkhardt/inqaba/blob/main/doc/inqaba-class-diagram.puml), and the
|
|
44
|
+
[migration contract](https://github.com/Burkhardt/inqaba/blob/main/doc/MIGRATION.md). For release verification, use the
|
|
45
|
+
paired Umgodi `scripts/preflight.py` with both repositories checked out.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
inqaba/__init__.py,sha256=X761eLcweJKPov5N4gySWAjSzsyTPjwmjEPEg0nriqM,434
|
|
2
|
+
inqaba/config.py,sha256=wqHl4ysXlNvPyvdk-UqdpboP6SH6E8Zd3pLmFqlXxZY,5225
|
|
3
|
+
inqaba/entry.py,sha256=KGaAoj8UHPOjcha0pNkkeES3ruivO9bLxRYozrXlJIs,3565
|
|
4
|
+
inqaba/files.py,sha256=X78vf0iaoQZZhuHir1UnzeeySNuQ7VRfkRLMfxz7CGY,951
|
|
5
|
+
inqaba/json5.py,sha256=4ZSWEvRGMianNXiL7e2zNiah-NWyEiyh5zcg0_lkS5w,5103
|
|
6
|
+
inqaba/path.py,sha256=DgpsRNnRs_rkJKRlw7JqpHZ8HCVxRMgqkMEDLmbcWx8,3440
|
|
7
|
+
inqaba-0.1.0.dist-info/METADATA,sha256=bwTKwgh9hN_XMmBJfu1k1e-8OjDTOJtwjN3KM4m3FZ0,1918
|
|
8
|
+
inqaba-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
inqaba-0.1.0.dist-info/RECORD,,
|