"""Добавляет Gitea-сенсоры через REST.""" import re CFG = "/opt/smart-lxc/homeassistant/config/configuration.yaml" SEC = "/opt/smart-lxc/homeassistant/config/secrets.yaml" GT = open("/tmp/gitea-token", encoding="utf-8").read().strip() sec = open(SEC, encoding="utf-8").read() if "gitea_token" not in sec: with open(SEC, "a", encoding="utf-8") as f: f.write(f'\ngitea_token: "token {GT}"\n') print(" секрет Gitea добавлен") block = ''' - resource: http://192.168.1.140:3000/api/v1/repos/search?limit=50 headers: Authorization: !secret gitea_token scan_interval: 600 sensor: - name: "Gitea репозиториев" unique_id: gitea_repos_count value_template: "{{ (value_json.data or []) | count }}" - resource: http://192.168.1.140:3000/api/v1/user headers: Authorization: !secret gitea_token scan_interval: 600 sensor: - name: "Gitea пользователь" unique_id: gitea_user value_template: "{{ value_json.login }}" ''' s = open(CFG, encoding="utf-8").read() if "gitea_user" in s: print(" сенсоры уже есть") else: lines = s.split("\n") start = next((i for i, l in enumerate(lines) if re.match(r"^rest:\s*$", l)), None) if start is None: s = s.rstrip() + "\n\nrest:\n" + block else: end = len(lines) for j in range(start + 1, len(lines)): if lines[j] and not lines[j].startswith((" ", "\t")) and not lines[j].startswith("#"): end = j break lines[end:end] = block.split("\n") s = "\n".join(lines) open(CFG, "w", encoding="utf-8").write(s) print(" сенсоры добавлены")