feat: add config module with INI-based configuration management
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
70
src/jianda_proxy/config.py
Normal file
70
src/jianda_proxy/config.py
Normal file
@@ -0,0 +1,70 @@
|
||||
import os
|
||||
import configparser
|
||||
from pathlib import Path
|
||||
|
||||
SECTION = "proxy"
|
||||
DEFAULTS = {
|
||||
"remote_domain": "git.zz.com",
|
||||
"upstream_host": "62.234.191.215",
|
||||
"upstream_port": "3000",
|
||||
"listen_port": "13000",
|
||||
"listen_host": "127.0.0.1",
|
||||
}
|
||||
|
||||
|
||||
def get_config_dir():
|
||||
if os.name == "nt":
|
||||
base = os.environ.get("APPDATA", os.path.expanduser("~"))
|
||||
else:
|
||||
base = os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config"))
|
||||
return os.path.join(base, "jianda-proxy")
|
||||
|
||||
|
||||
def _ensure_dir(path):
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
def get_config_path():
|
||||
return os.path.join(get_config_dir(), "config.ini")
|
||||
|
||||
|
||||
def get_pid_path():
|
||||
return os.path.join(get_config_dir(), "daemon.pid")
|
||||
|
||||
|
||||
def get_log_path():
|
||||
return os.path.join(get_config_dir(), "proxy.log")
|
||||
|
||||
|
||||
def load_config():
|
||||
path = get_config_path()
|
||||
_ensure_dir(get_config_dir())
|
||||
parser = configparser.ConfigParser()
|
||||
if not os.path.exists(path):
|
||||
parser[SECTION] = dict(DEFAULTS)
|
||||
with open(path, "w") as f:
|
||||
parser.write(f)
|
||||
else:
|
||||
parser.read(path)
|
||||
if SECTION not in parser:
|
||||
parser[SECTION] = dict(DEFAULTS)
|
||||
return parser
|
||||
|
||||
|
||||
def set_config_value(key, value):
|
||||
if key not in DEFAULTS:
|
||||
raise ValueError(f"Unknown config key: {key}. Valid keys: {', '.join(DEFAULTS)}")
|
||||
parser = load_config()
|
||||
parser[SECTION][key] = value
|
||||
with open(get_config_path(), "w") as f:
|
||||
parser.write(f)
|
||||
|
||||
|
||||
def get_config_value(key):
|
||||
parser = load_config()
|
||||
return parser.get(SECTION, key)
|
||||
|
||||
|
||||
def list_config():
|
||||
parser = load_config()
|
||||
return dict(parser[SECTION])
|
||||
Reference in New Issue
Block a user