-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig_loader.py
More file actions
145 lines (118 loc) · 5.57 KB
/
config_loader.py
File metadata and controls
145 lines (118 loc) · 5.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#!/usr/bin/env python3
import os
import json
import sys
from typing import Dict, Any, Optional
class ConfigLoader:
"""Загрузчик конфигурации для DevOps инструментов."""
# Путь к конфигурационному файлу
CONFIG_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")
# Кэш конфигурации
_config = None
@classmethod
def load_config(cls) -> Dict[str, Any]:
"""Загружает конфигурацию из файла."""
if cls._config is not None:
return cls._config
try:
if not os.path.exists(cls.CONFIG_PATH):
print(f"Ошибка: Конфигурационный файл не найден: {cls.CONFIG_PATH}")
print("Создайте файл config.json на основе config.example.json")
return {}
with open(cls.CONFIG_PATH, "r", encoding="utf-8") as f:
cls._config = json.load(f)
return cls._config
except Exception as e:
print(f"Ошибка загрузки конфигурации: {str(e)}")
return {}
@classmethod
def get_gitlab_config(cls) -> Dict[str, Any]:
"""Возвращает конфигурацию GitLab."""
config = cls.load_config()
return config.get("gitlab", {})
@classmethod
def get_vercel_config(cls) -> Dict[str, Any]:
"""Возвращает конфигурацию Vercel."""
config = cls.load_config()
return config.get("vercel", {})
@classmethod
def get_project_paths(cls) -> Dict[str, str]:
"""Возвращает пути к файлам проекта."""
config = cls.load_config()
return config.get("paths", {})
@classmethod
def get_required_dirs(cls) -> list:
"""Возвращает список необходимых директорий."""
config = cls.load_config()
return config.get("required_dirs", [])
@classmethod
def get_required_files(cls) -> list:
"""Возвращает список необходимых файлов."""
config = cls.load_config()
return config.get("required_files", [])
@classmethod
def get_endpoints(cls) -> list:
"""Возвращает список эндпоинтов для проверки."""
config = cls.load_config()
return config.get("endpoints", [])
@classmethod
def get_project_name(cls) -> str:
"""Возвращает имя проекта."""
config = cls.load_config()
return config.get("project", {}).get("name", "example-project")
@classmethod
def get_gitlab_project_id(cls) -> str:
"""Возвращает ID проекта в GitLab."""
# Приоритет: переменная окружения, потом конфиг
project_id = os.environ.get("GITLAB_PROJECT_ID")
if project_id:
return project_id
return cls.get_gitlab_config().get("project_id", "YOUR_GITLAB_PROJECT_ID")
@classmethod
def get_gitlab_token(cls) -> str:
"""Возвращает токен GitLab."""
# Приоритет: переменная окружения, потом файл, потом конфиг
token = os.environ.get("GITLAB_TOKEN")
if token:
return token
# Проверяем наличие файла с токеном
token_file = os.path.expanduser("~/.gitlab_token")
if os.path.exists(token_file):
try:
with open(token_file, "r", encoding="utf-8") as f:
return f.read().strip()
except:
pass
return cls.get_gitlab_config().get("token", "")
@classmethod
def get_vercel_team_id(cls) -> str:
"""Возвращает ID команды в Vercel."""
# Приоритет: переменная окружения, потом конфиг
team_id = os.environ.get("VERCEL_ID")
if team_id:
return team_id
return cls.get_vercel_config().get("team_id", "YOUR_VERCEL_TEAM_ID")
@classmethod
def get_vercel_project_id(cls) -> str:
"""Возвращает ID проекта в Vercel."""
# Приоритет: переменная окружения, потом конфиг
project_id = os.environ.get("VERCEL_PROJECT_ID")
if project_id:
return project_id
return cls.get_vercel_config().get("project_id", "YOUR_VERCEL_PROJECT_ID")
@classmethod
def get_vercel_token(cls) -> str:
"""Возвращает токен Vercel."""
# Приоритет: переменная окружения, потом конфиг
token = os.environ.get("VERCEL_TOKEN")
if token:
return token
return cls.get_vercel_config().get("token", "YOUR_VERCEL_TOKEN")
@classmethod
def get_project_url(cls) -> str:
"""Возвращает URL проекта."""
return cls.get_vercel_config().get("project_url", "https://www.example.com")
# Для использования в качестве модуля
if __name__ == "__main__":
# При запуске скрипта напрямую выводим текущую конфигурацию
print(json.dumps(ConfigLoader.load_config(), indent=2, ensure_ascii=False))