设计一个Python脚本,用于自动生成环境变量文档,要求支持从代码注释或配置文件提取变量描述和默认值。
import os
import re
import argparse
from typing import Dict, List, Optional
import json
def extract_env_vars_from_comments(file_path: str) -> Dict[str, Dict[str, str]]:
"""
从 Python 文件中提取环境变量注释信息。
格式要求:注释以 # ENV_VAR: 开头,后接变量名和描述。
例如:
# ENV_VAR: API_KEY The API key for the service.
# ENV_VAR: DEBUG Enable debug mode (default: False).
:param file_path: Python 文件路径
:return: 字典,键为环境变量名,值为包含描述和默认值的字典
"""
env_vars = {}
pattern = re.compile(r"# ENV_VAR: (\w+)\s(.+?)\s*(?:\s\(default:\s(.+?)\))?\s*$")
with open(file_path, "r") as file:
for line in file:
match = pattern.match(line)
if match:
var_name, description, default_value = match.groups()
env_vars[var_name] = {
"description": description,
"default_value": default_value if default_value else ""
}
return env_vars
def extract_env_vars_from_config(config_file_path: str) -> Dict[str, Dict[str, str]]:
"""
从配置文件中提取环境变量信息。支持的格式为 JSON 或 YAML。
例如 JSON 格式:
{
"API_KEY": {
"description": "The API key for the service.",
"default_value": ""
},
"DEBUG": {
"description": "Enable debug mode.",
"default_value": "False"
}
}
:param config_file_path: 配置文件路径
:return: 字典,键为环境变量名,值为包含描述和默认值的字典
"""
env_vars = {}
if config_file_path.endswith(".json"):
with open(config_file_path, "r") as file:
env_vars = json.load(file)
elif config_file_path.endswith(".yaml") or config_file_path.endswith(".yml"):
import yaml
with open(config_file_path, "r") as file:
env_vars = yaml.safe_load(file)
return env_vars
def generate_markdown_documentation(env_vars: Dict[str, Dict[str, str]], output_file: str) -> None:
"""
生成 Markdown 格式的环境变量文档。
:param env_vars: 环境变量字典
:param output_file: 输出文件路径
"""
with open(output_file, "w") as file:
file.write("# Environment Variables Documentation\n\n")
file.write("| Variable Name | Description | Default Value |\n")
file.write("|--------------|-------------|--------------|\n")
for var_name, var_info in env_vars.items():
file.write(f"| {var_name} | {var_info['description']} | {var_info['default_value']} |\n")
def main() -> None:
"""
主函数,解析命令行参数并调用相应的函数。
"""
parser = argparse.ArgumentParser(description="Generate environment variables documentation from code comments or configuration files.")
parser.add_argument("--comments", type=str, help="Path to the Python file containing environment variable comments.")
parser.add_argument("--config", type=str, help="Path to the JSON or YAML configuration file.")
parser.add_argument("--output", type=str, required=True, help="Output file path for the generated documentation.")
args = parser.parse_args()
env_vars = {}
if args.comments:
env_vars.update(extract_env_vars_from_comments(args.comments))
if args.config:
env_vars.update(extract_env_vars_from_config(args.config))
if not env_vars:
print("No environment variables found. Please check your input files.")
return
generate_markdown_documentation(env_vars, args.output)
print(f"Documentation generated successfully at {args.output}.")
if __name__ == "__main__":
main()
示例说明
-
从代码注释中提取环境变量 假设有一个 Python 文件
app.py,内容如下:# ENV_VAR: API_KEY The API key for the service. # ENV_VAR: DEBUG Enable debug mode (default: False).运行脚本:
python script.py --comments app.py --output env_docs.md生成的
env_docs.md文件内容如下:# Environment Variables Documentation | Variable Name | Description | Default Value | |--------------|-------------|--------------| | API_KEY | The API key for the service. | | | DEBUG | Enable debug mode. | False | -
从配置文件中提取环境变量 假设有一个 JSON 配置文件
config.json,内容如下:{ "DB_HOST": { "description": "Database host address.", "default_value": "localhost" }, "DB_PORT": { "description": "Database port number.", "default_value": "5432" } }运行脚本:
python script.py --config config.json --output env_docs.md生成的
env_docs.md文件内容如下:# Environment Variables Documentation | Variable Name | Description | Default Value | |--------------|-------------|--------------| | DB_HOST | Database host address. | localhost | | DB_PORT | Database port number. | 5432 | -
结合注释和配置文件 如果同时提供
--comments和--config参数,脚本会将两者的结果合并。例如:python script.py --comments app.py --config config.json --output env_docs.md生成的文档会包含来自
app.py和config.json的所有环境变量信息。