chatglance 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ChatArch
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,123 @@
1
+ Metadata-Version: 2.4
2
+ Name: chatglance
3
+ Version: 0.0.1
4
+ Summary: ChatArch Glance dashboard generation CLI.
5
+ Author-email: ChatArch <1073853456@qq.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/ChatArch/chatglance
8
+ Project-URL: Repository, https://github.com/ChatArch/chatglance
9
+ Keywords: chatglance,chatarch,cli
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: click>=8.0
16
+ Requires-Dist: PyYAML<7.0,>=6.0
17
+ Provides-Extra: dev
18
+ Requires-Dist: build; extra == "dev"
19
+ Requires-Dist: pytest; extra == "dev"
20
+ Requires-Dist: twine; extra == "dev"
21
+ Dynamic: license-file
22
+
23
+ <div align="center">
24
+ <a href="https://pypi.python.org/pypi/chatglance">
25
+ <img src="https://img.shields.io/pypi/v/chatglance.svg" alt="PyPI version" />
26
+ </a>
27
+ <a href="https://github.com/ChatArch/chatglance/actions/workflows/ci.yml">
28
+ <img src="https://github.com/ChatArch/chatglance/actions/workflows/ci.yml/badge.svg" alt="Tests" />
29
+ </a>
30
+ </div>
31
+
32
+ <div align="center">
33
+
34
+ [English](README.en.md) | [简体中文](README.md)
35
+ </div>
36
+
37
+ # chatglance
38
+
39
+ `chatglance` 是 ChatArch/WZHECNU Glance dashboard 的 Python 生成与运维 CLI。
40
+
41
+ 它不是 NPM 项目,也不是重新实现 Glance 后端:上游 Glance 仍然是 Go 单二进制 dashboard server;`chatglance` 负责把 ChatArch 项目清单、Glance YAML 页面、inline HTML 表格和安全运维补丁组织成可复用的 Python 包/CLI。
42
+
43
+ ## 当前能力
44
+
45
+ - 从 repository inventory JSON 生成 Glance `项目` page。
46
+ - 当前 page tabs 固定为:`最近提交`、`待处理 PR / Issue`、`分类`、`一览表`。
47
+ - `待处理 PR / Issue` 只显示 PR/Issue 非 0 的仓库,并按 `(PR, Issue, 最近提交)` 降序。
48
+ - 生成 config 副本时清理 legacy generated pages:`Projects`、`ChatArch Projects`、`ChatArch Projects List`。
49
+ - 为 Glance `server-stats` 写入 root-only Disk 配置:`hide-mountpoints-by-default: true` + `mountpoints: /`,避免 snap/loop mount 出现在 Disk popover。
50
+ - 维护 durable runtime:一次性 `runtime maintain` 可原子更新 live config、备份、校验,并在内容变化时可选重启 systemd user service。
51
+ - 渲染 systemd user units:主服务仍直接启动 upstream Glance Go binary;维护任务是独立 oneshot/timer,不是 Python wrapper。
52
+
53
+ ## 快速开始
54
+
55
+ ```bash
56
+ pip install -e ".[dev]"
57
+ chatglance --help
58
+ chatglance --tree
59
+ chatglance --version
60
+ python -m pytest -q
61
+ python -m build
62
+ ```
63
+
64
+ ## CLI 示例
65
+
66
+ 只生成 `项目` page YAML:
67
+
68
+ ```bash
69
+ chatglance projects render-page \
70
+ --data /path/to/chatarch-projects.json \
71
+ --output playground/projects-page.yml
72
+ ```
73
+
74
+ 把生成页写入一个 Glance config 副本:
75
+
76
+ ```bash
77
+ chatglance projects update-config \
78
+ --data /path/to/chatarch-projects.json \
79
+ --config /path/to/glance.yml \
80
+ --output playground/glance.with-projects.yml
81
+ ```
82
+
83
+ 把 `server-stats` Disk 改成只显示 root 分区,写入 config 副本:
84
+
85
+ ```bash
86
+ chatglance disks root-only \
87
+ --config /path/to/glance.yml \
88
+ --output playground/glance.root-disk.yml
89
+ ```
90
+
91
+ 维护一个 durable Glance runtime(默认 `~/.chatarch/glance`):
92
+
93
+ ```bash
94
+ chatglance runtime maintain \
95
+ --runtime-home ~/.chatarch/glance \
96
+ --restart-service chatarch-glance.service
97
+ ```
98
+
99
+ 生成推荐 systemd user units:
100
+
101
+ ```bash
102
+ chatglance runtime render-systemd \
103
+ --runtime-home ~/.chatarch/glance \
104
+ --chatglance-bin ~/.chatarch/venv/bin/chatglance \
105
+ --output-dir playground/systemd
106
+ ```
107
+
108
+ ## 运行态边界
109
+
110
+ 推荐拓扑是 **systemd 直接运行 Glance,chatglance 只做维护**:
111
+
112
+ - 主服务:`chatarch-glance.service` 直接执行 `~/.chatarch/glance/bin/glance -config ~/.chatarch/glance/config/glance.yml`。
113
+ - 内容数据:repository inventory JSON、缓存和生成快照放在 `~/.chatarch/glance/data/` 或 `~/.chatarch/glance/cache/`。
114
+ - live config:`~/.chatarch/glance/config/glance.yml`;更新前写备份到 `~/.chatarch/glance/config/backups/`。
115
+ - 维护:`chatglance runtime maintain` 是 oneshot,可由 `chatarch-glance-maintenance.timer` 周期触发。
116
+ - 不建议加 Python 长驻 wrapper:wrapper 会把 server 生命周期和内容生成耦合,反而不利于 systemd 重启、日志、健康检查和回滚。
117
+
118
+ ## 安全边界
119
+
120
+ - CLI 默认写 output file,不默认覆盖 live `glance.yml`。
121
+ - 不保存或输出 Glance auth、password hash、GitHub token、proxy credential。
122
+ - live runtime、logs、backups、全量实时 JSON 快照默认不进源码仓库。
123
+ - 后续如需动态表格、搜索、中英文切换,再考虑增加小型静态前端层;当前 Python CLI 是基础层。
@@ -0,0 +1,101 @@
1
+ <div align="center">
2
+ <a href="https://pypi.python.org/pypi/chatglance">
3
+ <img src="https://img.shields.io/pypi/v/chatglance.svg" alt="PyPI version" />
4
+ </a>
5
+ <a href="https://github.com/ChatArch/chatglance/actions/workflows/ci.yml">
6
+ <img src="https://github.com/ChatArch/chatglance/actions/workflows/ci.yml/badge.svg" alt="Tests" />
7
+ </a>
8
+ </div>
9
+
10
+ <div align="center">
11
+
12
+ [English](README.en.md) | [简体中文](README.md)
13
+ </div>
14
+
15
+ # chatglance
16
+
17
+ `chatglance` 是 ChatArch/WZHECNU Glance dashboard 的 Python 生成与运维 CLI。
18
+
19
+ 它不是 NPM 项目,也不是重新实现 Glance 后端:上游 Glance 仍然是 Go 单二进制 dashboard server;`chatglance` 负责把 ChatArch 项目清单、Glance YAML 页面、inline HTML 表格和安全运维补丁组织成可复用的 Python 包/CLI。
20
+
21
+ ## 当前能力
22
+
23
+ - 从 repository inventory JSON 生成 Glance `项目` page。
24
+ - 当前 page tabs 固定为:`最近提交`、`待处理 PR / Issue`、`分类`、`一览表`。
25
+ - `待处理 PR / Issue` 只显示 PR/Issue 非 0 的仓库,并按 `(PR, Issue, 最近提交)` 降序。
26
+ - 生成 config 副本时清理 legacy generated pages:`Projects`、`ChatArch Projects`、`ChatArch Projects List`。
27
+ - 为 Glance `server-stats` 写入 root-only Disk 配置:`hide-mountpoints-by-default: true` + `mountpoints: /`,避免 snap/loop mount 出现在 Disk popover。
28
+ - 维护 durable runtime:一次性 `runtime maintain` 可原子更新 live config、备份、校验,并在内容变化时可选重启 systemd user service。
29
+ - 渲染 systemd user units:主服务仍直接启动 upstream Glance Go binary;维护任务是独立 oneshot/timer,不是 Python wrapper。
30
+
31
+ ## 快速开始
32
+
33
+ ```bash
34
+ pip install -e ".[dev]"
35
+ chatglance --help
36
+ chatglance --tree
37
+ chatglance --version
38
+ python -m pytest -q
39
+ python -m build
40
+ ```
41
+
42
+ ## CLI 示例
43
+
44
+ 只生成 `项目` page YAML:
45
+
46
+ ```bash
47
+ chatglance projects render-page \
48
+ --data /path/to/chatarch-projects.json \
49
+ --output playground/projects-page.yml
50
+ ```
51
+
52
+ 把生成页写入一个 Glance config 副本:
53
+
54
+ ```bash
55
+ chatglance projects update-config \
56
+ --data /path/to/chatarch-projects.json \
57
+ --config /path/to/glance.yml \
58
+ --output playground/glance.with-projects.yml
59
+ ```
60
+
61
+ 把 `server-stats` Disk 改成只显示 root 分区,写入 config 副本:
62
+
63
+ ```bash
64
+ chatglance disks root-only \
65
+ --config /path/to/glance.yml \
66
+ --output playground/glance.root-disk.yml
67
+ ```
68
+
69
+ 维护一个 durable Glance runtime(默认 `~/.chatarch/glance`):
70
+
71
+ ```bash
72
+ chatglance runtime maintain \
73
+ --runtime-home ~/.chatarch/glance \
74
+ --restart-service chatarch-glance.service
75
+ ```
76
+
77
+ 生成推荐 systemd user units:
78
+
79
+ ```bash
80
+ chatglance runtime render-systemd \
81
+ --runtime-home ~/.chatarch/glance \
82
+ --chatglance-bin ~/.chatarch/venv/bin/chatglance \
83
+ --output-dir playground/systemd
84
+ ```
85
+
86
+ ## 运行态边界
87
+
88
+ 推荐拓扑是 **systemd 直接运行 Glance,chatglance 只做维护**:
89
+
90
+ - 主服务:`chatarch-glance.service` 直接执行 `~/.chatarch/glance/bin/glance -config ~/.chatarch/glance/config/glance.yml`。
91
+ - 内容数据:repository inventory JSON、缓存和生成快照放在 `~/.chatarch/glance/data/` 或 `~/.chatarch/glance/cache/`。
92
+ - live config:`~/.chatarch/glance/config/glance.yml`;更新前写备份到 `~/.chatarch/glance/config/backups/`。
93
+ - 维护:`chatglance runtime maintain` 是 oneshot,可由 `chatarch-glance-maintenance.timer` 周期触发。
94
+ - 不建议加 Python 长驻 wrapper:wrapper 会把 server 生命周期和内容生成耦合,反而不利于 systemd 重启、日志、健康检查和回滚。
95
+
96
+ ## 安全边界
97
+
98
+ - CLI 默认写 output file,不默认覆盖 live `glance.yml`。
99
+ - 不保存或输出 Glance auth、password hash、GitHub token、proxy credential。
100
+ - live runtime、logs、backups、全量实时 JSON 快照默认不进源码仓库。
101
+ - 后续如需动态表格、搜索、中英文切换,再考虑增加小型静态前端层;当前 Python CLI 是基础层。
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "chatglance"
7
+ dynamic = ["version"]
8
+ description = "ChatArch Glance dashboard generation CLI."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ dependencies = ["click>=8.0", "PyYAML>=6.0,<7.0"]
13
+ authors = [{name = "ChatArch", email = "1073853456@qq.com"}]
14
+ keywords = ["chatglance", "chatarch", "cli"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Operating System :: OS Independent",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://github.com/ChatArch/chatglance"
22
+ Repository = "https://github.com/ChatArch/chatglance"
23
+
24
+ [project.scripts]
25
+ chatglance = "chatglance.cli:main"
26
+
27
+ [project.optional-dependencies]
28
+ dev = ["build", "pytest", "twine"]
29
+
30
+ [tool.setuptools.dynamic]
31
+ version = {attr = "chatglance.__version__"}
32
+
33
+ [tool.setuptools.packages.find]
34
+ where = ["src"]
35
+
36
+ [tool.setuptools]
37
+ include-package-data = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,5 @@
1
+ """chatglance package."""
2
+
3
+ __all__ = ["__version__"]
4
+
5
+ __version__ = "0.0.1"
@@ -0,0 +1,221 @@
1
+ """CLI entrypoint for chatglance."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ from pathlib import Path
7
+
8
+ import click
9
+
10
+ from chatglance import __version__
11
+ from chatglance.glance_config import patch_disks_from_files, update_projects_page_from_files
12
+ from chatglance.projects import PAGE_NAME, build_projects_page, dump_yaml, load_inventory
13
+ from chatglance.runtime import maintain_config, runtime_path
14
+ from chatglance.systemd import render_all_units, write_units
15
+
16
+
17
+ def _purpose(command: click.Command) -> str:
18
+ text = command.short_help or inspect.getdoc(command.callback) or ""
19
+ return " ".join(text.strip().split()).rstrip(".")
20
+
21
+
22
+ def _parameter_piece(parameter: click.Parameter) -> str | None:
23
+ if getattr(parameter, "hidden", False) or parameter.name == "help":
24
+ return None
25
+ if isinstance(parameter, click.Argument):
26
+ piece = parameter.name.upper().replace("_", "-")
27
+ if not parameter.required:
28
+ piece = f"[{piece}]"
29
+ if parameter.nargs == -1:
30
+ piece = f"{piece}..."
31
+ return piece
32
+ if not isinstance(parameter, click.Option):
33
+ return None
34
+ option_names = [name for name in (*parameter.opts, *parameter.secondary_opts) if name.startswith("--")]
35
+ if not option_names:
36
+ option_names = [name for name in (*parameter.opts, *parameter.secondary_opts) if name.startswith("-")]
37
+ if not option_names:
38
+ return None
39
+ if parameter.is_flag or parameter.flag_value is not None:
40
+ piece = "/".join(option_names)
41
+ else:
42
+ metavar = parameter.metavar or parameter.name.upper().replace("_", "-")
43
+ piece = f"{'/'.join(option_names)} {metavar}"
44
+ if not parameter.required:
45
+ piece = f"[{piece}]"
46
+ return piece
47
+
48
+
49
+ def _command_signature(name: str, command: click.Command) -> str:
50
+ pieces = [piece for piece in (_parameter_piece(parameter) for parameter in command.params) if piece]
51
+ return " ".join([name, *pieces])
52
+
53
+
54
+ def _render_command_tree(command: click.Command, name: str, prefix: str, is_last: bool, lines: list[str]) -> None:
55
+ connector = "└── " if is_last else "├── "
56
+ line = f"{prefix}{connector}{_command_signature(name, command)}"
57
+ purpose = _purpose(command)
58
+ if purpose:
59
+ line = f"{line} # {purpose}"
60
+ lines.append(line)
61
+ if not isinstance(command, click.Group):
62
+ return
63
+ children = [(child_name, child) for child_name, child in command.commands.items() if not child.hidden]
64
+ child_prefix = prefix + (" " if is_last else "│ ")
65
+ for index, (child_name, child) in enumerate(children):
66
+ _render_command_tree(child, child_name, child_prefix, index == len(children) - 1, lines)
67
+
68
+
69
+ def _render_cli_tree(root: click.Group) -> str:
70
+ children = [(name, command) for name, command in root.commands.items() if not command.hidden]
71
+ lines = [f"chatglance # {_purpose(root)}"]
72
+ root_options = [
73
+ ("--help", "Show help for the current command."),
74
+ ("--version", "Show package version."),
75
+ ("--tree", "Print the registered CLI tree."),
76
+ ]
77
+ for index, (option, purpose) in enumerate(root_options):
78
+ is_last = not children and index == len(root_options) - 1
79
+ lines.append(f"{'└──' if is_last else '├──'} {option} # {purpose}")
80
+ for index, (child_name, child) in enumerate(children):
81
+ _render_command_tree(child, child_name, "", index == len(children) - 1, lines)
82
+ return "\n".join(lines)
83
+
84
+
85
+ @click.group(invoke_without_command=True, no_args_is_help=True)
86
+ @click.version_option(__version__, prog_name="chatglance")
87
+ @click.option("--tree", "show_tree", is_flag=True, is_eager=True, help="Print the registered CLI tree.")
88
+ @click.pass_context
89
+ def main(ctx: click.Context, show_tree: bool) -> None:
90
+ """Generate and maintain ChatArch Glance dashboard config."""
91
+
92
+ if show_tree:
93
+ click.echo(_render_cli_tree(ctx.command))
94
+ ctx.exit()
95
+
96
+
97
+ @main.group()
98
+ def projects() -> None:
99
+ """Generate Glance project dashboard pages."""
100
+
101
+
102
+ @projects.command("render-page")
103
+ @click.option("--data", "data_path", type=click.Path(path_type=Path, dir_okay=False, exists=True), required=True, help="Inventory JSON generated from repository metadata.")
104
+ @click.option("--output", "output_path", type=click.Path(path_type=Path, dir_okay=False), required=True, help="YAML file to write the generated Glance page object to.")
105
+ @click.option("--page-name", default=PAGE_NAME, show_default=True, help="Generated Glance page name.")
106
+ def render_projects_page(data_path: Path, output_path: Path, page_name: str) -> None:
107
+ """Render the `项目` page YAML from inventory JSON."""
108
+
109
+ data = load_inventory(data_path)
110
+ page = build_projects_page(data, page_name=page_name)
111
+ output_path.parent.mkdir(parents=True, exist_ok=True)
112
+ output_path.write_text(dump_yaml(page), encoding="utf-8")
113
+ click.echo(f"wrote {output_path}")
114
+
115
+
116
+ @projects.command("update-config")
117
+ @click.option("--data", "data_path", type=click.Path(path_type=Path, dir_okay=False, exists=True), required=True, help="Inventory JSON generated from repository metadata.")
118
+ @click.option("--config", "config_path", type=click.Path(path_type=Path, dir_okay=False, exists=True), required=True, help="Existing Glance YAML config.")
119
+ @click.option("--output", "output_path", type=click.Path(path_type=Path, dir_okay=False), required=True, help="Output path for the updated Glance YAML config.")
120
+ @click.option("--page-name", default=PAGE_NAME, show_default=True, help="Generated Glance page name.")
121
+ def update_projects_config(data_path: Path, config_path: Path, output_path: Path, page_name: str) -> None:
122
+ """Write a config copy with the generated project page replaced."""
123
+
124
+ output_path.parent.mkdir(parents=True, exist_ok=True)
125
+ update_projects_page_from_files(config_path, data_path, output_path, page_name=page_name)
126
+ click.echo(f"wrote {output_path}")
127
+
128
+
129
+ @main.group()
130
+ def disks() -> None:
131
+ """Patch Glance server-stats disk display."""
132
+
133
+
134
+ @disks.command("root-only")
135
+ @click.option("--config", "config_path", type=click.Path(path_type=Path, dir_okay=False, exists=True), required=True, help="Existing Glance YAML config.")
136
+ @click.option("--output", "output_path", type=click.Path(path_type=Path, dir_okay=False), required=True, help="Output path for the patched Glance YAML config.")
137
+ @click.option("--mountpoint", default="/", show_default=True, help="Only mountpoint to display.")
138
+ @click.option("--name", "mount_name", default="根分区", show_default=True, help="Display name for the mountpoint.")
139
+ def root_only_disk(config_path: Path, output_path: Path, mountpoint: str, mount_name: str) -> None:
140
+ """Write a config copy that hides default snap/loop mountpoints."""
141
+
142
+ output_path.parent.mkdir(parents=True, exist_ok=True)
143
+ patch_disks_from_files(config_path, output_path, mountpoint=mountpoint, name=mount_name)
144
+ click.echo(f"wrote {output_path}")
145
+
146
+
147
+ @main.group()
148
+ def runtime() -> None:
149
+ """Maintain a durable Glance service runtime."""
150
+
151
+
152
+ @runtime.command("maintain")
153
+ @click.option("--runtime-home", type=click.Path(path_type=Path, file_okay=False), default=Path("~/.chatarch/glance"), show_default=True, help="Durable Glance service home.")
154
+ @click.option("--config", "config_path", type=click.Path(path_type=Path, dir_okay=False), default=Path("config/glance.yml"), show_default=True, help="Runtime-relative or absolute Glance YAML config.")
155
+ @click.option("--data", "data_path", type=click.Path(path_type=Path, dir_okay=False), default=Path("data/chatarch-projects.json"), show_default=True, help="Runtime-relative or absolute repository inventory JSON.")
156
+ @click.option("--backup-dir", type=click.Path(path_type=Path, file_okay=False), default=Path("config/backups"), show_default=True, help="Runtime-relative or absolute backup directory for in-place writes.")
157
+ @click.option("--page-name", default=PAGE_NAME, show_default=True, help="Generated Glance page name.")
158
+ @click.option("--validate/--no-validate", default=True, show_default=True, help="Validate the candidate config with the upstream Glance binary before replacing it.")
159
+ @click.option("--glance-bin", type=click.Path(path_type=Path, dir_okay=False), default=Path("bin/glance"), show_default=True, help="Runtime-relative or absolute Glance binary used for config validation.")
160
+ @click.option("--restart-service", default=None, help="systemd user service to restart only if the rendered config changed.")
161
+ def maintain_runtime(runtime_home: Path, config_path: Path, data_path: Path, backup_dir: Path, page_name: str, validate: bool, glance_bin: Path, restart_service: str | None) -> None:
162
+ """Apply generated project content and root-only Disk config once."""
163
+
164
+ runtime_home = runtime_home.expanduser()
165
+ config = runtime_path(runtime_home, config_path)
166
+ data = runtime_path(runtime_home, data_path)
167
+ backups = runtime_path(runtime_home, backup_dir) if backup_dir else None
168
+ binary = runtime_path(runtime_home, glance_bin) if validate else None
169
+ result = maintain_config(
170
+ config_path=config,
171
+ data_path=data,
172
+ output_path=config,
173
+ backup_dir=backups,
174
+ validate_bin=binary,
175
+ page_name=page_name,
176
+ restart_service=restart_service,
177
+ )
178
+ click.echo(
179
+ " ".join(
180
+ [
181
+ f"output={result.output_path}",
182
+ f"changed={str(result.changed).lower()}",
183
+ f"validated={str(result.validated).lower()}",
184
+ f"restarted={str(result.restarted).lower()}",
185
+ f"backup={result.backup_path or '-'}",
186
+ ]
187
+ )
188
+ )
189
+
190
+
191
+ @runtime.command("render-systemd")
192
+ @click.option("--runtime-home", type=click.Path(path_type=Path, file_okay=False), default=Path("~/.chatarch/glance"), show_default=True, help="Durable Glance service home.")
193
+ @click.option("--chatglance-bin", type=click.Path(path_type=Path, dir_okay=False), required=True, help="Absolute path to the chatglance executable used by the maintenance oneshot.")
194
+ @click.option("--service-name", default="chatarch-glance.service", show_default=True, help="Main Glance user service name.")
195
+ @click.option("--maintenance-service-name", default="chatarch-glance-maintenance.service", show_default=True, help="Generated oneshot maintenance service name.")
196
+ @click.option("--timer-name", default="chatarch-glance-maintenance.timer", show_default=True, help="Generated maintenance timer name.")
197
+ @click.option("--interval", default="30min", show_default=True, help="systemd OnUnitActiveSec interval for the maintenance timer.")
198
+ @click.option("--output-dir", type=click.Path(path_type=Path, file_okay=False), help="Directory to write unit files. Omit to print them.")
199
+ def render_systemd(runtime_home: Path, chatglance_bin: Path, service_name: str, maintenance_service_name: str, timer_name: str, interval: str, output_dir: Path | None) -> None:
200
+ """Render direct Glance service plus chatglance maintenance units."""
201
+
202
+ units = render_all_units(
203
+ runtime_home=runtime_home.expanduser(),
204
+ chatglance_bin=chatglance_bin.expanduser(),
205
+ service_name=service_name,
206
+ maintenance_service_name=maintenance_service_name,
207
+ timer_name=timer_name,
208
+ interval=interval,
209
+ )
210
+ if output_dir:
211
+ paths = write_units(output_dir.expanduser(), units)
212
+ for path in paths:
213
+ click.echo(f"wrote {path}")
214
+ return
215
+ click.echo(f"# {units.service_name}\n{units.service}")
216
+ click.echo(f"# {units.maintenance_service_name}\n{units.maintenance_service}")
217
+ click.echo(f"# {units.timer_name}\n{units.timer}")
218
+
219
+
220
+ if __name__ == "__main__":
221
+ main()
@@ -0,0 +1,104 @@
1
+ """Safe Glance YAML config transformations for chatglance."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from copy import deepcopy
6
+ from pathlib import Path
7
+ from typing import Any, Iterator
8
+
9
+ from .projects import LEGACY_PAGE_NAMES, PAGE_NAME, build_projects_page, dump_yaml, load_inventory
10
+
11
+
12
+ def load_yaml(path: str | Path) -> dict[str, Any]:
13
+ import yaml
14
+
15
+ data = yaml.safe_load(Path(path).read_text(encoding="utf-8"))
16
+ if not isinstance(data, dict):
17
+ raise ValueError("Glance config must be a YAML mapping")
18
+ return data
19
+
20
+
21
+ def write_yaml(path: str | Path, data: dict[str, Any]) -> None:
22
+ Path(path).write_text(dump_yaml(data), encoding="utf-8")
23
+
24
+
25
+ def replace_projects_page(config: dict[str, Any], inventory: dict[str, Any], *, page_name: str = PAGE_NAME) -> dict[str, Any]:
26
+ """Return a config copy where the generated projects page is replaced.
27
+
28
+ This function does not mutate the input mapping. It removes old generated page
29
+ names and then replaces/appends the current `page_name` page.
30
+ """
31
+
32
+ updated = deepcopy(config)
33
+ pages = updated.setdefault("pages", [])
34
+ if not isinstance(pages, list):
35
+ raise ValueError("Glance config `pages` must be a list")
36
+ legacy_names = set(LEGACY_PAGE_NAMES) | {page_name}
37
+ pages[:] = [page for page in pages if not (isinstance(page, dict) and page.get("name") in legacy_names)]
38
+ pages.append(build_projects_page(inventory, page_name=page_name))
39
+ return updated
40
+
41
+
42
+ def iter_widgets(value: Any) -> Iterator[dict[str, Any]]:
43
+ """Yield Glance widget mappings recursively from pages/columns/groups."""
44
+
45
+ if isinstance(value, dict):
46
+ if "type" in value:
47
+ yield value
48
+ for key in ("widgets", "columns"):
49
+ nested = value.get(key)
50
+ if isinstance(nested, list):
51
+ for item in nested:
52
+ yield from iter_widgets(item)
53
+ elif isinstance(value, list):
54
+ for item in value:
55
+ yield from iter_widgets(item)
56
+
57
+
58
+ def patch_server_stats_root_only(
59
+ config: dict[str, Any],
60
+ *,
61
+ mountpoint: str = "/",
62
+ name: str = "根分区",
63
+ hide_swap: bool = True,
64
+ ) -> dict[str, Any]:
65
+ """Return a config copy where all server-stats widgets show only one mountpoint.
66
+
67
+ Glance's `mountpoints` entries name configured mountpoints, but without
68
+ `hide-mountpoints-by-default: true` Glance can still render all default OS
69
+ mountpoints, including snap/loop mounts. This helper sets both fields.
70
+ """
71
+
72
+ updated = deepcopy(config)
73
+ for widget in iter_widgets(updated.get("pages", [])):
74
+ if widget.get("type") != "server-stats":
75
+ continue
76
+ widget["hide-mountpoints-by-default"] = True
77
+ servers = widget.get("servers")
78
+ if not isinstance(servers, list):
79
+ # A bare local server-stats widget can exist; keep it safe by adding
80
+ # a local server entry rather than leaving defaults visible.
81
+ servers = [{"type": "local", "name": "local"}]
82
+ widget["servers"] = servers
83
+ for server in servers:
84
+ if not isinstance(server, dict):
85
+ continue
86
+ server["hide-swap"] = bool(hide_swap)
87
+ server["hide-mountpoints-by-default"] = True
88
+ server["mountpoints"] = {mountpoint: {"name": name}}
89
+ return updated
90
+
91
+
92
+ def update_projects_page_from_files(config_path: str | Path, data_path: str | Path, output_path: str | Path, *, page_name: str = PAGE_NAME) -> Path:
93
+ config = load_yaml(config_path)
94
+ inventory = load_inventory(data_path)
95
+ updated = replace_projects_page(config, inventory, page_name=page_name)
96
+ write_yaml(output_path, updated)
97
+ return Path(output_path)
98
+
99
+
100
+ def patch_disks_from_files(config_path: str | Path, output_path: str | Path, *, mountpoint: str = "/", name: str = "根分区") -> Path:
101
+ config = load_yaml(config_path)
102
+ updated = patch_server_stats_root_only(config, mountpoint=mountpoint, name=name)
103
+ write_yaml(output_path, updated)
104
+ return Path(output_path)