"""Owned subset for YAML/.env routing; not the Hermes CLI."""
import copy,json,re
from pathlib import Path
from tempfile import TemporaryDirectory
import sys
sys.path.insert(0,str(Path(__file__).resolve().parent/"vendor"))
from dotenv import dotenv_values,set_key
import yaml
class ConfigFiles:
def __init__(self,root):
self.root=Path(root);self.root.mkdir(parents=True,exist_ok=True)
self.config=self.root/"config.yaml";self.env=self.root/".env"
def document(self):return yaml.safe_load(self.config.read_text(encoding="utf8")) if self.config.exists() else {}
def values(self):return dict(dotenv_values(self.env,interpolate=False))
def set(self,key,value):
if key in {"PATH","HERMES_YOLO_MODE"}:raise ValueError("protected environment name")
if re.fullmatch(r"[A-Z][A-Z0-9_]*",key):
set_key(str(self.env),key,str(value),quote_mode="always");return ".env"
if key not in {"model.default","terminal.backend","model.api_key","display.token_count"}:raise ValueError("not an allowed owned dotted setting")
data=self.document();section,leaf=key.split(".")
if key=="model.api_key":
set_key(str(self.env),"MBSKY_FAKE_MODEL_API_KEY",str(value),quote_mode="always")
value="${MBSKY_FAKE_MODEL_API_KEY}"
data.setdefault(section,{})[leaf]=value
self.config.write_text(yaml.safe_dump(data,allow_unicode=True,sort_keys=True),encoding="utf8")
return "config.yaml"
def display(self):
result=copy.deepcopy(self.document())
if "api_key" in result.get("model",{}):result["model"]["api_key"]="[redacted]"
return result
def exercise(root):
files=ConfigFiles(Path(root)/"review");rows=[]
def check(name,inputs,operation,expected,actual):
assert expected==actual,(name,expected,actual)
rows.append(dict(name=name,input=inputs,operation=operation,expected=expected,actual=actual))
destination=files.set("model.default","mbsky-owned")
check("ordinary_dotted","model.default","write and parse actual YAML",["config.yaml","mbsky-owned"],[destination,files.document()["model"]["default"]])
destination=files.set("HERMES_TIMEZONE","UTC")
check("nonsecret_environment","HERMES_TIMEZONE","write ordinary uppercase value to .env and parse it",
[".env","UTC",False],[destination,files.values()["HERMES_TIMEZONE"],"HERMES_TIMEZONE" in files.document()])
fake="MBSKY-FAKE-ONLY";files.set("model.api_key",fake)
check("secret_reference","synthetic model key","store fake value in .env and only its reference in YAML",
[True,"${MBSKY_FAKE_MODEL_API_KEY}",False],[files.values()["MBSKY_FAKE_MODEL_API_KEY"]==fake,files.document()["model"]["api_key"],fake in files.config.read_text(encoding="utf8")])
awkward="MBSKY-FAKE-'quote'\nsecond ${UNRELATED_VARIABLE}";files.set("MBSKY_FAKE_QUOTING",awkward)
check("dotenv_roundtrip","quote/newline/literal placeholder","round-trip with python-dotenv interpolation disabled",True,files.values()["MBSKY_FAKE_QUOTING"]==awkward)
before=[files.config.read_bytes(),files.env.read_bytes()];refused=[]
for key in ("PATH","HERMES_YOLO_MODE","model..default","BAD\nKEY"):
try:files.set(key,"owned")
except ValueError:refused.append(key)
check("invalid_keys",["PATH","HERMES_YOLO_MODE","model..default","BAD\\nKEY"],"reject four owned-policy invalid keys and retain prior bytes",
[4,True],[len(refused),before==[files.config.read_bytes(),files.env.read_bytes()]])
files.set("display.token_count",7)
check("display","synthetic key and ordinary counter","mask the owned credential field; retain numeric counter",
[True,7],[fake not in json.dumps(files.display()),files.display()["display"]["token_count"]])
reopened=ConfigFiles(files.root);other=ConfigFiles(Path(root)/"research")
check("reopen_and_separate","existing and empty owned directories","read actual files through a new object and verify the other directory is empty",
[True,True,{},{}],[reopened.document()==files.document(),reopened.values()==files.values(),other.document(),other.values()])
return dict(cases=rows,scope="Owned restricted policy, not Hermes CLI/schema/redactor or authentication",
yaml_module=yaml.__file__,dotenv_module=__import__("dotenv").__file__)
if __name__=="__main__":
with TemporaryDirectory(prefix="mbsky-hermes-config-split-") as root:result=exercise(root)
print(json.dumps(result,ensure_ascii=False))
本例需在 Windows、CPython3.12.14、PyYAML6.0.3和python-dotenv1.2.4;本站机制实验,完整Hermes未安装。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、CPython3.12.14、PyYAML6.0.3和python-dotenv1.2.4;本站机制实验,完整Hermes未安装。
入口文件:projects/hermes-config/config_split.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
config_split.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、CPython3.12.14、PyYAML6.0.3和python-dotenv1.2.4;本站机制实验,完整Hermes未安装。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联20章) · 含当前章节或实例 · mbskycom202612a184.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a187.zip