蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

检查全局、项目、子目录和临时内联配置

PYTHONWindows、OpenCode 1.19.5 与 2.2.6、Git 和 CPython 3.12。config_sources.py
config_sources.py62 行
"""Compare V1 effective configuration with V2 configuration-source lists."""
from pathlib import Path
from tempfile import TemporaryDirectory
from hashlib import sha256
import json
import os
import subprocess


def observe(v1, v2):
    results={}
    for label,exe in [('v1',v1),('v2',v2)]:
     with TemporaryDirectory(prefix='mbsky-opencode-config-') as work:
      root=Path(work).resolve()
      project=root/'repository'
      child=project/'docs'
      env={k:os.environ[k] for k in ('SystemRoot','WINDIR','PATH','TEMP','TMP','COMSPEC','USERPROFILE') if k in os.environ}
      for key in ('CONFIG','DATA','CACHE','STATE'):env[f'XDG_{key}_HOME']=str(root/key.lower())
      env.update(OPENCODE_DISABLE_AUTOUPDATE='1',OPENCODE_DISABLE_MODELS_FETCH='1',OPENCODE_DISABLE_DEFAULT_PLUGINS='1',
       HTTPS_PROXY='http://127.0.0.1:1',HTTP_PROXY='http://127.0.0.1:1',NO_PROXY='127.0.0.1,localhost',NO_COLOR='1')
      documents={}
      def save(f,data):
       f.parent.mkdir(parents=True,exist_ok=True)
       raw=json.dumps(data).encode();f.write_bytes(raw);documents[f.relative_to(root).as_posix()]=sha256(raw).hexdigest()
      save(root/'config/opencode/opencode.json',dict(model='fixture/global',username='training-global',autoupdate=False))
      save(project/'opencode.json',dict(model='fixture/repository'))
      save(child/'opencode.json',dict(model='fixture/docs'))
      save(root/'custom.json',dict(model='fixture/custom',snapshot=False))
      command=['debug','config'] + (['--standalone'] if label=='v2' else [])
      subprocess.run(['git','init','-q'],cwd=project,env=env,capture_output=True,timeout=8,check=True)
      result=[]
      for folder,name in [(root,'global'),(project,'repository'),(child,'docs')]:
       out=subprocess.run([str(exe),*command],cwd=folder,env=env,capture_output=True,encoding='utf8',errors='replace',timeout=12,check=True)
       raw=json.loads(out.stdout)
       summary=raw
       if isinstance(raw,list):
        summary=[dict(type=x.get('type'),path=Path(x['path']).relative_to(root).as_posix()
                      if x.get('path') and Path(x['path']).is_relative_to(root) else x.get('path'),
                      model=x.get('info',{}).get('model'),
                      update=x.get('info',{}).get('update')) for x in raw if isinstance(x,dict)]
       elif isinstance(raw,dict):
        summary={k:raw[k] for k in ('model','username','autoupdate') if k in raw}
       result.append(dict(cwd=name,decoded=summary,returncode=out.returncode))
      if label=='v1':
       trial_env=dict(env,OPENCODE_CONFIG=str(root/'custom.json'),OPENCODE_CONFIG_CONTENT=json.dumps(dict(model='fixture/inline')))
       out=subprocess.run([str(exe),*command],cwd=project,env=trial_env,capture_output=True,encoding='utf8',errors='replace',
         timeout=12,check=True)
       raw=json.loads(out.stdout)
       result.append(dict(cwd='repository_with_custom_and_inline',decoded={k:raw[k] for k in ('model','username','autoupdate','snapshot') if k in raw}))
      results[label]=dict(command=command,documents=documents,observations=result)

    return results


if __name__ == "__main__":
    import argparse
    parser=argparse.ArgumentParser()
    parser.add_argument("v1",type=lambda path:Path(path).resolve())
    parser.add_argument("v2",type=lambda path:Path(path).resolve())
    args=parser.parse_args()
    print(json.dumps(observe(args.v1,args.v2),ensure_ascii=False,indent=2))
本例需在 Windows、OpenCode 1.19.5 与 2.2.6、Git 和 CPython 3.12。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、OpenCode 1.19.5 与 2.2.6、Git 和 CPython 3.12。

入口文件:projects/opencode-config-sources/config_sources.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 config_sources.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、OpenCode 1.19.5 与 2.2.6、Git 和 CPython 3.12。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:OpenCode

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a238.zip

下载课程关联工程包:OpenCode

课程关联工程包(登记关联28章) · 含当前章节或实例 · mbskycom202612a236.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习