zt-apollo-cli 0.2.3__tar.gz → 0.4.0__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zt-apollo-cli
3
- Version: 0.2.3
3
+ Version: 0.4.0
4
4
  Summary: Apollo configuration management CLI
5
5
  Requires-Python: >=3.10
6
6
  Description-Content-Type: text/markdown
@@ -32,19 +32,18 @@ pip install -e .
32
32
 
33
33
  ```bash
34
34
  uv build
35
- uv public --token <your_token>
35
+ uv publish --token <your_token>
36
36
  ```
37
37
 
38
38
  ## 快速开始
39
39
 
40
- ### 1) 登录并缓存 Cookie(已登录可跳过)
40
+ ### 1) 登录并缓存 Cookie
41
41
 
42
- 首次运行会打开浏览器,请完成登录。成功后会缓存 Cookie 到本地。
43
- 再次执行 `login` 时,如果检测到本地已有有效登录态会自动跳过;如需强制刷新可加 `--force`。
42
+ 首次或需要刷新登录态时执行,会打开浏览器完成登录并缓存 Cookie 到本地。
43
+ 其他命令遇到认证失效时会自动重新登录。
44
44
 
45
45
  ```bash
46
46
  zt-apollo-cli login
47
- zt-apollo-cli login --force
48
47
  ```
49
48
 
50
49
  ### 2) 查看部门列表
@@ -105,6 +104,56 @@ zt-apollo-cli app del-namespace-release-publisher -a your_app_id -n application
105
104
  zt-apollo-cli app update -a your_app_id --file ./app-update.json
106
105
  ```
107
106
 
107
+ ### 11) 修改 Namespace 配置
108
+
109
+ 适用于 yml/json 等文本类 Namespace。`namespaceId` 与 `format` 默认从 `list-namespace` 自动解析。
110
+
111
+ ```bash
112
+ # 从文件更新
113
+ zt-apollo-cli app update-namespace -a your_app_id -n application.yml --file ./application.yml --env DEV --cluster default
114
+
115
+ # 直接传入配置文本
116
+ zt-apollo-cli app update-namespace -a your_app_id -n application.yml --text "# config"
117
+ ```
118
+
119
+ ### 12) 发布 Namespace 配置
120
+
121
+ 将未发布的 Namespace 变更发布到指定环境。`--title` 未指定时自动生成(如 `20260613144414-release`)。
122
+
123
+ ```bash
124
+ zt-apollo-cli app release-namespace -a your_app_id -n application.yml --env DEV --cluster default --comment "发布说明"
125
+
126
+ # 指定发布标题
127
+ zt-apollo-cli app release-namespace -a your_app_id -n application.yml --title "20260613144414-release" --comment "s"
128
+ ```
129
+
130
+ ### 13) 创建 Namespace
131
+
132
+ 在应用下新建 Namespace。默认追加 appId 前缀(`appendNamespacePrefix=true`)。
133
+
134
+ ```bash
135
+ zt-apollo-cli app create-namespace -a your_app_id -n test --format properties --comment ""
136
+
137
+ # 不追加前缀
138
+ zt-apollo-cli app create-namespace -a your_app_id -n application.yml --format yml --no-append-prefix
139
+ ```
140
+
141
+ ### 14) 删除 Namespace(指定环境)
142
+
143
+ 删除指定 env/cluster 下的 Namespace。
144
+
145
+ ```bash
146
+ zt-apollo-cli app delete-namespace -a your_app_id -n test --env DEV --cluster default
147
+ ```
148
+
149
+ ### 15) 删除应用 Namespace(所有环境)
150
+
151
+ 删除应用下的 Namespace 定义及所有环境的配置。
152
+
153
+ ```bash
154
+ zt-apollo-cli app delete-app-namespace -a your_app_id -n test
155
+ ```
156
+
108
157
  ## 全局参数
109
158
  - `-o, --output`:输出格式,支持:
110
159
  - `json`(默认)
@@ -19,19 +19,18 @@ pip install -e .
19
19
 
20
20
  ```bash
21
21
  uv build
22
- uv public --token <your_token>
22
+ uv publish --token <your_token>
23
23
  ```
24
24
 
25
25
  ## 快速开始
26
26
 
27
- ### 1) 登录并缓存 Cookie(已登录可跳过)
27
+ ### 1) 登录并缓存 Cookie
28
28
 
29
- 首次运行会打开浏览器,请完成登录。成功后会缓存 Cookie 到本地。
30
- 再次执行 `login` 时,如果检测到本地已有有效登录态会自动跳过;如需强制刷新可加 `--force`。
29
+ 首次或需要刷新登录态时执行,会打开浏览器完成登录并缓存 Cookie 到本地。
30
+ 其他命令遇到认证失效时会自动重新登录。
31
31
 
32
32
  ```bash
33
33
  zt-apollo-cli login
34
- zt-apollo-cli login --force
35
34
  ```
36
35
 
37
36
  ### 2) 查看部门列表
@@ -92,6 +91,56 @@ zt-apollo-cli app del-namespace-release-publisher -a your_app_id -n application
92
91
  zt-apollo-cli app update -a your_app_id --file ./app-update.json
93
92
  ```
94
93
 
94
+ ### 11) 修改 Namespace 配置
95
+
96
+ 适用于 yml/json 等文本类 Namespace。`namespaceId` 与 `format` 默认从 `list-namespace` 自动解析。
97
+
98
+ ```bash
99
+ # 从文件更新
100
+ zt-apollo-cli app update-namespace -a your_app_id -n application.yml --file ./application.yml --env DEV --cluster default
101
+
102
+ # 直接传入配置文本
103
+ zt-apollo-cli app update-namespace -a your_app_id -n application.yml --text "# config"
104
+ ```
105
+
106
+ ### 12) 发布 Namespace 配置
107
+
108
+ 将未发布的 Namespace 变更发布到指定环境。`--title` 未指定时自动生成(如 `20260613144414-release`)。
109
+
110
+ ```bash
111
+ zt-apollo-cli app release-namespace -a your_app_id -n application.yml --env DEV --cluster default --comment "发布说明"
112
+
113
+ # 指定发布标题
114
+ zt-apollo-cli app release-namespace -a your_app_id -n application.yml --title "20260613144414-release" --comment "s"
115
+ ```
116
+
117
+ ### 13) 创建 Namespace
118
+
119
+ 在应用下新建 Namespace。默认追加 appId 前缀(`appendNamespacePrefix=true`)。
120
+
121
+ ```bash
122
+ zt-apollo-cli app create-namespace -a your_app_id -n test --format properties --comment ""
123
+
124
+ # 不追加前缀
125
+ zt-apollo-cli app create-namespace -a your_app_id -n application.yml --format yml --no-append-prefix
126
+ ```
127
+
128
+ ### 14) 删除 Namespace(指定环境)
129
+
130
+ 删除指定 env/cluster 下的 Namespace。
131
+
132
+ ```bash
133
+ zt-apollo-cli app delete-namespace -a your_app_id -n test --env DEV --cluster default
134
+ ```
135
+
136
+ ### 15) 删除应用 Namespace(所有环境)
137
+
138
+ 删除应用下的 Namespace 定义及所有环境的配置。
139
+
140
+ ```bash
141
+ zt-apollo-cli app delete-app-namespace -a your_app_id -n test
142
+ ```
143
+
95
144
  ## 全局参数
96
145
  - `-o, --output`:输出格式,支持:
97
146
  - `json`(默认)
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "zt-apollo-cli"
7
- version = "0.2.3"
7
+ version = "0.4.0"
8
8
  description = "Apollo configuration management CLI"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -0,0 +1,304 @@
1
+ """Apollo API 请求封装"""
2
+ import requests
3
+
4
+ from .auth import get_auth_cookies, get_auth_headers, is_auth_error, login
5
+ from .config import config
6
+
7
+
8
+ class ApolloApi:
9
+ """Apollo API 客户端"""
10
+
11
+ def __init__(self):
12
+ self.base_url = config.base_url
13
+
14
+ def _request(self, method: str, path: str, _retried: bool = False, **kwargs):
15
+ """发送 API 请求;认证失效时自动重新登录并重试一次"""
16
+ cookies = get_auth_cookies()
17
+ headers = get_auth_headers(cookies)
18
+ extra_headers = kwargs.pop("headers", None)
19
+ if extra_headers:
20
+ headers.update(extra_headers)
21
+ url = f"{self.base_url}/{path.lstrip('/')}"
22
+
23
+ response = requests.request(
24
+ method=method,
25
+ url=url,
26
+ headers=headers,
27
+ cookies=cookies,
28
+ **kwargs
29
+ )
30
+
31
+ if is_auth_error(response):
32
+ if _retried:
33
+ raise Exception(
34
+ f"Apollo API 认证失败(已尝试重新登录): "
35
+ f"{response.status_code} {response.text[:500]}"
36
+ )
37
+ print("检测到认证失效,正在自动重新登录...")
38
+ login()
39
+ return self._request(method, path, _retried=True, **kwargs)
40
+
41
+ if response.status_code >= 400:
42
+ raise Exception(f"Apollo API 错误: {response.status_code} {response.text}")
43
+
44
+ try:
45
+ return response.json()
46
+ except ValueError:
47
+ return response.text
48
+
49
+ def list_organizations(self):
50
+ """列出部门"""
51
+ return self._request("GET", "/organizations")
52
+
53
+ def search_apps(self, query: str, page: int = 0, size: int = 20):
54
+ """按 appId 或名称搜索应用"""
55
+ return self._request(
56
+ "GET",
57
+ "/apps/search/by-appid-or-name",
58
+ params={
59
+ "query": query,
60
+ "page": page,
61
+ "size": size,
62
+ },
63
+ )
64
+
65
+ def get_app(self, app_id: str):
66
+ """获取应用基本信息"""
67
+ return self._request("GET", f"/apps/{app_id}")
68
+
69
+ def get_app_role_users(self, app_id: str):
70
+ """获取应用管理员"""
71
+ return self._request("GET", f"/apps/{app_id}/role_users")
72
+
73
+ def list_namespaces(self, app_id: str, env: str = "DEV", cluster: str = "default"):
74
+ """获取应用 Namespace 列表"""
75
+ return self._request(
76
+ "GET",
77
+ f"/apps/{app_id}/envs/{env}/clusters/{cluster}/namespaces",
78
+ )
79
+
80
+ def create_app_namespace(
81
+ self,
82
+ app_id: str,
83
+ name: str,
84
+ comment: str = "",
85
+ is_public: bool = False,
86
+ config_format: str = "properties",
87
+ append_namespace_prefix: bool = True,
88
+ ):
89
+ """创建应用 Namespace"""
90
+ payload = {
91
+ "appId": app_id,
92
+ "name": name,
93
+ "comment": comment,
94
+ "isPublic": is_public,
95
+ "format": config_format,
96
+ }
97
+ headers = {
98
+ "Content-Type": "application/json;charset=UTF-8"
99
+ }
100
+ return self._request(
101
+ "POST",
102
+ f"/apps/{app_id}/appnamespaces",
103
+ params={"appendNamespacePrefix": str(append_namespace_prefix).lower()},
104
+ json=payload,
105
+ headers=headers,
106
+ )
107
+
108
+ def clean_namespace(
109
+ self,
110
+ app_id: str,
111
+ namespace: str
112
+ ):
113
+ """删除应用 Namespace(该应用下所有环境)"""
114
+ headers = {
115
+ }
116
+ return self._request(
117
+ "DELETE",
118
+ f"/apps/{app_id}/appnamespaces/{namespace}",
119
+ headers=headers,
120
+ )
121
+
122
+ def delete_namespace(
123
+ self,
124
+ app_id: str,
125
+ namespace: str,
126
+ env: str = "DEV",
127
+ cluster: str = "default"
128
+ ):
129
+ """删除指定环境下的 Namespace"""
130
+ headers = {
131
+ }
132
+ return self._request(
133
+ "DELETE",
134
+ f"/apps/{app_id}/envs/{env}/clusters/{cluster}/namespaces/{namespace}",
135
+ headers=headers,
136
+ )
137
+
138
+ def get_namespace_active_release(
139
+ self,
140
+ app_id: str,
141
+ namespace: str,
142
+ env: str = "DEV",
143
+ cluster: str = "default",
144
+ page: int = 0,
145
+ size: int = 1,
146
+ ):
147
+ """获取 Namespace 当前生效发布"""
148
+ return self._request(
149
+ "GET",
150
+ f"/apps/{app_id}/envs/{env}/clusters/{cluster}/namespaces/{namespace}/releases/active",
151
+ params={"page": page, "size": size},
152
+ )
153
+
154
+ def update_app(self, app_id: str, payload: dict):
155
+ """更新应用配置"""
156
+ return self._request(
157
+ "PUT",
158
+ f"/apps/{app_id}",
159
+ json=payload,
160
+ )
161
+
162
+ def add_app_admin(self, app_id: str, user_code: str, role: str = "Master"):
163
+ """添加应用管理员"""
164
+ return self._request(
165
+ "POST",
166
+ f"/apps/{app_id}/roles/{role}",
167
+ data=user_code,
168
+ headers={"Content-Type": "text/plain;charset=UTF-8"},
169
+ )
170
+
171
+ def remove_app_admin(self, app_id: str, user_code: str, role: str = "Master"):
172
+ """移除应用管理员"""
173
+ return self._request(
174
+ "DELETE",
175
+ f"/apps/{app_id}/roles/{role}",
176
+ params={"user": user_code},
177
+ )
178
+
179
+ def add_namespace_modify_role(self, app_id: str, namespace: str, user_code: str):
180
+ """分配 Namespace 发布权限(ModifyNamespace)"""
181
+ return self._request(
182
+ "POST",
183
+ f"/apps/{app_id}/namespaces/{namespace}/roles/ModifyNamespace",
184
+ data=user_code,
185
+ headers={"Content-Type": "text/plain;charset=UTF-8"},
186
+ )
187
+
188
+ def remove_namespace_modify_role(self, app_id: str, namespace: str, user_code: str):
189
+ """移除 Namespace 发布权限(ModifyNamespace)"""
190
+ return self._request(
191
+ "DELETE",
192
+ f"/apps/{app_id}/namespaces/{namespace}/roles/ModifyNamespace",
193
+ params={"user": user_code},
194
+ )
195
+
196
+ def remove_namespace_release_role(self, app_id: str, namespace: str, user_code: str):
197
+ """移除 Namespace 发布权限(ReleaseNamespace)"""
198
+ return self._request(
199
+ "DELETE",
200
+ f"/apps/{app_id}/namespaces/{namespace}/roles/ReleaseNamespace",
201
+ params={"user": user_code},
202
+ )
203
+
204
+ def add_namespace_release_role(self, app_id: str, namespace: str, user_code: str):
205
+ """分配 Namespace 发布权限(ReleaseNamespace)"""
206
+ return self._request(
207
+ "POST",
208
+ f"/apps/{app_id}/namespaces/{namespace}/roles/ReleaseNamespace",
209
+ data=user_code,
210
+ headers={"Content-Type": "text/plain;charset=UTF-8"},
211
+ )
212
+
213
+ def find_namespace(
214
+ self,
215
+ app_id: str,
216
+ namespace: str,
217
+ env: str = "DEV",
218
+ cluster: str = "default",
219
+ ) -> dict:
220
+ """按名称查找 Namespace,返回 namespaceId 与 format"""
221
+ namespaces = self.list_namespaces(app_id=app_id, env=env, cluster=cluster)
222
+ if not isinstance(namespaces, list):
223
+ raise Exception(f"无法解析 Namespace 列表: {namespaces}")
224
+
225
+ for item in namespaces:
226
+ base_info = item.get("baseInfo") or {}
227
+ if base_info.get("namespaceName") == namespace:
228
+ namespace_id = base_info.get("id")
229
+ if namespace_id is None:
230
+ raise Exception(f"Namespace {namespace!r} 缺少 id")
231
+ return {
232
+ "namespaceId": namespace_id,
233
+ "format": item.get("format"),
234
+ }
235
+
236
+ raise Exception(
237
+ f"未找到 Namespace: {namespace!r} "
238
+ f"(appId={app_id}, env={env}, cluster={cluster})"
239
+ )
240
+
241
+ def update_namespace_config(
242
+ self,
243
+ app_id: str,
244
+ namespace: str,
245
+ config_text: str,
246
+ env: str = "DEV",
247
+ cluster: str = "default",
248
+ namespace_id: int | None = None,
249
+ config_format: str | None = None
250
+ ):
251
+ """更新 Namespace 配置(文本类 format,如 yml/json)"""
252
+ if namespace_id is None or config_format is None:
253
+ info = self.find_namespace(
254
+ app_id=app_id,
255
+ namespace=namespace,
256
+ env=env,
257
+ cluster=cluster,
258
+ )
259
+ namespace_id = namespace_id or info["namespaceId"]
260
+ config_format = config_format or info["format"]
261
+
262
+ if not config_format:
263
+ raise Exception(f"无法确定 Namespace {namespace!r} 的 format")
264
+
265
+ payload = {
266
+ "configText": config_text,
267
+ "namespaceId": namespace_id,
268
+ "format": config_format,
269
+ }
270
+ headers = {
271
+ "Content-Type": "application/json;charset=UTF-8",
272
+ }
273
+ return self._request(
274
+ "PUT",
275
+ f"/apps/{app_id}/envs/{env}/clusters/{cluster}/namespaces/{namespace}/items",
276
+ json=payload,
277
+ headers=headers,
278
+ )
279
+
280
+ def release_namespace(
281
+ self,
282
+ app_id: str,
283
+ namespace: str,
284
+ release_title: str,
285
+ release_comment: str = "",
286
+ is_emergency_publish: bool = False,
287
+ env: str = "DEV",
288
+ cluster: str = "default"
289
+ ):
290
+ """发布 Namespace 配置"""
291
+ payload = {
292
+ "releaseTitle": release_title,
293
+ "releaseComment": release_comment,
294
+ "isEmergencyPublish": is_emergency_publish,
295
+ }
296
+ headers = {
297
+ "Content-Type": "application/json;charset=UTF-8",
298
+ }
299
+ return self._request(
300
+ "POST",
301
+ f"/apps/{app_id}/envs/{env}/clusters/{cluster}/namespaces/{namespace}/releases",
302
+ json=payload,
303
+ headers=headers,
304
+ )
@@ -2,6 +2,7 @@
2
2
  import json
3
3
  import os
4
4
 
5
+ import requests
5
6
  from playwright.sync_api import sync_playwright
6
7
 
7
8
  from .config import config
@@ -9,6 +10,16 @@ from .config import config
9
10
 
10
11
  APOLLO_DOMAIN = ".eminxing.com"
11
12
  REQUIRED_COOKIES = ["SESSION"]
13
+ _LOGIN_PATH_KEYWORDS = ("login", "sso", "auth", "signin", "cas", "oauth")
14
+ _LOGIN_PAGE_HINTS = (
15
+ 'id="username"',
16
+ 'name="username"',
17
+ 'type="password"',
18
+ "login_in",
19
+ "btn-login",
20
+ "请登录",
21
+ "未登录",
22
+ )
12
23
 
13
24
  def save_cookies(cookies: dict):
14
25
  """保存 cookie 到缓存文件"""
@@ -23,6 +34,25 @@ def load_cookies() -> dict:
23
34
  return json.load(f)
24
35
  return {}
25
36
 
37
+ def is_auth_error(response: requests.Response) -> bool:
38
+ """判断 HTTP 响应是否为认证失效(需重新登录)"""
39
+ if response.status_code == 401:
40
+ return True
41
+
42
+ if response.status_code in (301, 302, 303, 307, 308):
43
+ location = response.headers.get("Location", "").lower()
44
+ if any(keyword in location for keyword in _LOGIN_PATH_KEYWORDS):
45
+ return True
46
+
47
+ content_type = response.headers.get("Content-Type", "").lower()
48
+ if "text/html" in content_type:
49
+ body = response.text
50
+ if any(hint in body for hint in _LOGIN_PAGE_HINTS):
51
+ return True
52
+
53
+ return False
54
+
55
+
26
56
  def get_auth_headers(cookies: dict) -> dict:
27
57
  """从 cookie 构建认证请求头"""
28
58
  session_cookie = "; ".join(f"{k}={v}" for k, v in cookies.items())
@@ -124,17 +154,12 @@ def get_cookies_from_browser(headless: bool = True) -> dict:
124
154
 
125
155
  return cookie_dict
126
156
 
127
- def login(headless: bool = True, force: bool = False) -> dict:
128
- """登录并缓存 cookie;已有有效登录态时默认跳过"""
129
- cached = load_cookies()
130
- if not force and all(cached.get(k) for k in REQUIRED_COOKIES):
131
- print("检测到已登录,跳过重新登录。如需刷新请使用 --force。")
132
- return cached
133
-
157
+ def login(headless: bool = True) -> dict:
158
+ """登录并缓存 cookie"""
134
159
  if headless:
135
- print("正在启动浏览器(无头模式),请重新登录...")
160
+ print("正在启动浏览器(无头模式),请登录...")
136
161
  else:
137
- print("正在打开浏览器,请重新登录...")
162
+ print("正在打开浏览器,请登录...")
138
163
  cookies = get_cookies_from_browser(headless=headless)
139
164
  save_cookies(cookies)
140
165
  print("登录成功,Apollo cookie 已缓存!")
@@ -2,6 +2,7 @@
2
2
  import click
3
3
  import json
4
4
  import shutil
5
+ from datetime import datetime
5
6
  from .api import ApolloApi
6
7
  from .auth import login
7
8
  from .config import config
@@ -110,14 +111,9 @@ def cli(ctx, output_format, base_url):
110
111
  is_flag=True,
111
112
  help="显示浏览器窗口,用于无环境变量时的手动登录",
112
113
  )
113
- @click.option(
114
- "--force",
115
- is_flag=True,
116
- help="强制重新登录并刷新本地 cookie",
117
- )
118
- def cmd_login(headed, force):
119
- """登录 - 已登录则跳过,传 --force 可强制重新登录"""
120
- login(headless=not headed, force=force)
114
+ def cmd_login(headed):
115
+ """登录并缓存 Cookie"""
116
+ login(headless=not headed)
121
117
 
122
118
 
123
119
  @cli.group()
@@ -321,6 +317,90 @@ def list_namespaces(ctx, app_id, env, cluster):
321
317
  result = api.list_namespaces(app_id=app_id, env=env, cluster=cluster)
322
318
  _print_result(ctx, result, preferred_headers=["name", "appId", "clusterName", "dataChangeLastModifiedTime"])
323
319
 
320
+
321
+ @app.command("create-namespace")
322
+ @click.option("--app-id", "-a", required=True, help="应用 appId")
323
+ @click.option("--name", "-n", required=True, help="Namespace 名称(不含 appId 前缀)")
324
+ @click.option("--comment", default="", show_default=True, help="备注")
325
+ @click.option("--public", is_flag=True, help="是否为公共 Namespace")
326
+ @click.option(
327
+ "--format",
328
+ "config_format",
329
+ type=click.Choice(["properties", "xml", "json", "yaml", "yml"], case_sensitive=False),
330
+ default="properties",
331
+ show_default=True,
332
+ help="配置格式",
333
+ )
334
+ @click.option(
335
+ "--append-prefix/--no-append-prefix",
336
+ default=True,
337
+ show_default=True,
338
+ help="是否追加 Namespace 前缀(appendNamespacePrefix)",
339
+ )
340
+ @click.pass_context
341
+ def create_namespace(ctx, app_id, name, comment, public, config_format, append_prefix):
342
+ """创建应用 Namespace"""
343
+ api = ApolloApi()
344
+ result = api.create_app_namespace(
345
+ app_id=app_id,
346
+ name=name,
347
+ comment=comment,
348
+ is_public=public,
349
+ config_format=config_format.lower(),
350
+ append_namespace_prefix=append_prefix,
351
+ )
352
+
353
+ if ctx.obj["output_format"] == "json":
354
+ click.echo(json.dumps(result, ensure_ascii=False, indent=2))
355
+ else:
356
+ click.echo(f"Namespace 已创建: {name} (appId={app_id}, format={config_format})")
357
+
358
+
359
+ @app.command("delete-namespace")
360
+ @click.option("--app-id", "-a", required=True, help="应用 appId")
361
+ @click.option("--namespace", "-n", required=True, help="Namespace 名称(如 test)")
362
+ @click.option("--env", default="DEV", show_default=True, help="环境")
363
+ @click.option("--cluster", default="default", show_default=True, help="集群")
364
+ @click.pass_context
365
+ def delete_namespace(ctx, app_id, namespace, env, cluster):
366
+ """删除指定环境下的 Namespace"""
367
+ api = ApolloApi()
368
+ result = api.delete_namespace(
369
+ app_id=app_id,
370
+ namespace=namespace,
371
+ env=env,
372
+ cluster=cluster,
373
+ )
374
+
375
+ if ctx.obj["output_format"] == "json":
376
+ click.echo(json.dumps(result, ensure_ascii=False, indent=2))
377
+ else:
378
+ click.echo(
379
+ f"Namespace 已删除: {namespace} "
380
+ f"(appId={app_id}, env={env}, cluster={cluster})"
381
+ )
382
+
383
+
384
+ @app.command("clean-namespace")
385
+ @click.option("--app-id", "-a", required=True, help="应用 appId")
386
+ @click.option("--namespace", "-n", required=True, help="Namespace 名称(如 test)")
387
+ @click.pass_context
388
+ def clean_namespace(ctx, app_id, namespace):
389
+ """删除应用 Namespace(删除该应用下所有环境的配置)"""
390
+ api = ApolloApi()
391
+ result = api.clean_namespace(
392
+ app_id=app_id,
393
+ namespace=namespace,
394
+ )
395
+
396
+ if ctx.obj["output_format"] == "json":
397
+ click.echo(json.dumps(result, ensure_ascii=False, indent=2))
398
+ else:
399
+ click.echo(
400
+ f"应用 Namespace 已删除: {namespace} "
401
+ f"(appId={app_id}, 所有环境)"
402
+ )
403
+
324
404
  @app.command("show-namespace-release")
325
405
  @click.option("--app-id", "-a", required=True, help="应用 appId")
326
406
  @click.option("--namespace", "-n", required=True, help="Namespace 名称")
@@ -359,6 +439,88 @@ def update_app(ctx, app_id, payload_file):
359
439
  else:
360
440
  click.echo("应用配置更新成功")
361
441
 
442
+
443
+ @app.command("update-namespace")
444
+ @click.option("--app-id", "-a", required=True, help="应用 appId")
445
+ @click.option("--namespace", "-n", required=True, help="Namespace 名称(如 application.yml)")
446
+ @click.option("--env", default="DEV", show_default=True, help="环境")
447
+ @click.option("--cluster", default="default", show_default=True, help="集群")
448
+ @click.option(
449
+ "--file",
450
+ "config_file",
451
+ type=click.Path(exists=True, dir_okay=False),
452
+ help="配置文件内容(与 --text 二选一)",
453
+ )
454
+ @click.option("--text", help="配置文本内容(与 --file 二选一)")
455
+ @click.option("--namespace-id", type=int, help="Namespace ID(默认从 list-namespace 自动解析)")
456
+ @click.option("--format", "config_format", help="配置 format(默认从 list-namespace 自动解析,如 yml)")
457
+ @click.pass_context
458
+ def update_namespace(ctx, app_id, namespace, env, cluster, config_file, text, namespace_id, config_format):
459
+ """修改 Namespace 配置(文本类 format,如 yml/json)"""
460
+ if bool(config_file) == bool(text):
461
+ raise click.UsageError("请指定 --file 或 --text 之一")
462
+
463
+ if config_file:
464
+ with open(config_file, encoding="utf-8") as f:
465
+ config_text = f.read()
466
+ else:
467
+ config_text = text
468
+
469
+ api = ApolloApi()
470
+ result = api.update_namespace_config(
471
+ app_id=app_id,
472
+ namespace=namespace,
473
+ config_text=config_text,
474
+ env=env,
475
+ cluster=cluster,
476
+ namespace_id=namespace_id,
477
+ config_format=config_format,
478
+ )
479
+
480
+ if ctx.obj["output_format"] == "json":
481
+ click.echo(json.dumps(result, ensure_ascii=False, indent=2))
482
+ else:
483
+ click.echo(
484
+ f"Namespace 配置已更新: {namespace} "
485
+ f"(appId={app_id}, env={env}, cluster={cluster})"
486
+ )
487
+
488
+
489
+ @app.command("release-namespace")
490
+ @click.option("--app-id", "-a", required=True, help="应用 appId")
491
+ @click.option("--namespace", "-n", required=True, help="Namespace 名称(如 application.yml)")
492
+ @click.option("--env", default="DEV", show_default=True, help="环境")
493
+ @click.option("--cluster", default="default", show_default=True, help="集群")
494
+ @click.option(
495
+ "--title",
496
+ help="发布标题(默认自动生成,如 20260613144414-release)",
497
+ )
498
+ @click.option("--comment", default="", show_default=True, help="发布备注")
499
+ @click.option("--emergency", is_flag=True, help="是否紧急发布")
500
+ @click.pass_context
501
+ def release_namespace(ctx, app_id, namespace, env, cluster, title, comment, emergency):
502
+ """发布 Namespace 配置"""
503
+ release_title = title or f"{datetime.now():%Y%m%d%H%M%S}-release"
504
+
505
+ api = ApolloApi()
506
+ result = api.release_namespace(
507
+ app_id=app_id,
508
+ namespace=namespace,
509
+ release_title=release_title,
510
+ release_comment=comment,
511
+ is_emergency_publish=emergency,
512
+ env=env,
513
+ cluster=cluster,
514
+ )
515
+
516
+ if ctx.obj["output_format"] == "json":
517
+ click.echo(json.dumps(result, ensure_ascii=False, indent=2))
518
+ else:
519
+ click.echo(
520
+ f"Namespace 配置已发布: {namespace} "
521
+ f"(title={release_title}, appId={app_id}, env={env}, cluster={cluster})"
522
+ )
523
+
362
524
  def main():
363
525
  cli()
364
526
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zt-apollo-cli
3
- Version: 0.2.3
3
+ Version: 0.4.0
4
4
  Summary: Apollo configuration management CLI
5
5
  Requires-Python: >=3.10
6
6
  Description-Content-Type: text/markdown
@@ -32,19 +32,18 @@ pip install -e .
32
32
 
33
33
  ```bash
34
34
  uv build
35
- uv public --token <your_token>
35
+ uv publish --token <your_token>
36
36
  ```
37
37
 
38
38
  ## 快速开始
39
39
 
40
- ### 1) 登录并缓存 Cookie(已登录可跳过)
40
+ ### 1) 登录并缓存 Cookie
41
41
 
42
- 首次运行会打开浏览器,请完成登录。成功后会缓存 Cookie 到本地。
43
- 再次执行 `login` 时,如果检测到本地已有有效登录态会自动跳过;如需强制刷新可加 `--force`。
42
+ 首次或需要刷新登录态时执行,会打开浏览器完成登录并缓存 Cookie 到本地。
43
+ 其他命令遇到认证失效时会自动重新登录。
44
44
 
45
45
  ```bash
46
46
  zt-apollo-cli login
47
- zt-apollo-cli login --force
48
47
  ```
49
48
 
50
49
  ### 2) 查看部门列表
@@ -105,6 +104,56 @@ zt-apollo-cli app del-namespace-release-publisher -a your_app_id -n application
105
104
  zt-apollo-cli app update -a your_app_id --file ./app-update.json
106
105
  ```
107
106
 
107
+ ### 11) 修改 Namespace 配置
108
+
109
+ 适用于 yml/json 等文本类 Namespace。`namespaceId` 与 `format` 默认从 `list-namespace` 自动解析。
110
+
111
+ ```bash
112
+ # 从文件更新
113
+ zt-apollo-cli app update-namespace -a your_app_id -n application.yml --file ./application.yml --env DEV --cluster default
114
+
115
+ # 直接传入配置文本
116
+ zt-apollo-cli app update-namespace -a your_app_id -n application.yml --text "# config"
117
+ ```
118
+
119
+ ### 12) 发布 Namespace 配置
120
+
121
+ 将未发布的 Namespace 变更发布到指定环境。`--title` 未指定时自动生成(如 `20260613144414-release`)。
122
+
123
+ ```bash
124
+ zt-apollo-cli app release-namespace -a your_app_id -n application.yml --env DEV --cluster default --comment "发布说明"
125
+
126
+ # 指定发布标题
127
+ zt-apollo-cli app release-namespace -a your_app_id -n application.yml --title "20260613144414-release" --comment "s"
128
+ ```
129
+
130
+ ### 13) 创建 Namespace
131
+
132
+ 在应用下新建 Namespace。默认追加 appId 前缀(`appendNamespacePrefix=true`)。
133
+
134
+ ```bash
135
+ zt-apollo-cli app create-namespace -a your_app_id -n test --format properties --comment ""
136
+
137
+ # 不追加前缀
138
+ zt-apollo-cli app create-namespace -a your_app_id -n application.yml --format yml --no-append-prefix
139
+ ```
140
+
141
+ ### 14) 删除 Namespace(指定环境)
142
+
143
+ 删除指定 env/cluster 下的 Namespace。
144
+
145
+ ```bash
146
+ zt-apollo-cli app delete-namespace -a your_app_id -n test --env DEV --cluster default
147
+ ```
148
+
149
+ ### 15) 删除应用 Namespace(所有环境)
150
+
151
+ 删除应用下的 Namespace 定义及所有环境的配置。
152
+
153
+ ```bash
154
+ zt-apollo-cli app delete-app-namespace -a your_app_id -n test
155
+ ```
156
+
108
157
  ## 全局参数
109
158
  - `-o, --output`:输出格式,支持:
110
159
  - `json`(默认)
@@ -1,143 +0,0 @@
1
- """Apollo API 请求封装"""
2
- import requests
3
-
4
- from .auth import get_auth_cookies, get_auth_headers
5
- from .config import config
6
-
7
-
8
- class ApolloApi:
9
- """Apollo API 客户端"""
10
-
11
- def __init__(self):
12
- self.base_url = config.base_url
13
-
14
- def _request(self, method: str, path: str, **kwargs):
15
- """发送 API 请求"""
16
- cookies = get_auth_cookies()
17
- headers = get_auth_headers(cookies)
18
- extra_headers = kwargs.pop("headers", None)
19
- if extra_headers:
20
- headers.update(extra_headers)
21
- url = f"{self.base_url}/{path.lstrip('/')}"
22
-
23
- response = requests.request(
24
- method=method,
25
- url=url,
26
- headers=headers,
27
- cookies=cookies,
28
- **kwargs
29
- )
30
-
31
- if response.status_code >= 400:
32
- raise Exception(f"Apollo API 错误: {response.status_code} {response.text}")
33
-
34
- try:
35
- return response.json()
36
- except ValueError:
37
- return response.text
38
-
39
- def list_organizations(self):
40
- """列出部门"""
41
- return self._request("GET", "/organizations")
42
-
43
- def search_apps(self, query: str, page: int = 0, size: int = 20):
44
- """按 appId 或名称搜索应用"""
45
- return self._request(
46
- "GET",
47
- "/apps/search/by-appid-or-name",
48
- params={
49
- "query": query,
50
- "page": page,
51
- "size": size,
52
- },
53
- )
54
-
55
- def get_app(self, app_id: str):
56
- """获取应用基本信息"""
57
- return self._request("GET", f"/apps/{app_id}")
58
-
59
- def get_app_role_users(self, app_id: str):
60
- """获取应用管理员"""
61
- return self._request("GET", f"/apps/{app_id}/role_users")
62
-
63
- def list_namespaces(self, app_id: str, env: str = "DEV", cluster: str = "default"):
64
- """获取应用 Namespace 列表"""
65
- return self._request(
66
- "GET",
67
- f"/apps/{app_id}/envs/{env}/clusters/{cluster}/namespaces",
68
- )
69
-
70
- def get_namespace_active_release(
71
- self,
72
- app_id: str,
73
- namespace: str,
74
- env: str = "DEV",
75
- cluster: str = "default",
76
- page: int = 0,
77
- size: int = 1,
78
- ):
79
- """获取 Namespace 当前生效发布"""
80
- return self._request(
81
- "GET",
82
- f"/apps/{app_id}/envs/{env}/clusters/{cluster}/namespaces/{namespace}/releases/active",
83
- params={"page": page, "size": size},
84
- )
85
-
86
- def update_app(self, app_id: str, payload: dict):
87
- """更新应用配置"""
88
- return self._request(
89
- "PUT",
90
- f"/apps/{app_id}",
91
- json=payload,
92
- )
93
-
94
- def add_app_admin(self, app_id: str, user_code: str, role: str = "Master"):
95
- """添加应用管理员"""
96
- return self._request(
97
- "POST",
98
- f"/apps/{app_id}/roles/{role}",
99
- data=user_code,
100
- headers={"Content-Type": "text/plain;charset=UTF-8"},
101
- )
102
-
103
- def remove_app_admin(self, app_id: str, user_code: str, role: str = "Master"):
104
- """移除应用管理员"""
105
- return self._request(
106
- "DELETE",
107
- f"/apps/{app_id}/roles/{role}",
108
- params={"user": user_code},
109
- )
110
-
111
- def add_namespace_modify_role(self, app_id: str, namespace: str, user_code: str):
112
- """分配 Namespace 发布权限(ModifyNamespace)"""
113
- return self._request(
114
- "POST",
115
- f"/apps/{app_id}/namespaces/{namespace}/roles/ModifyNamespace",
116
- data=user_code,
117
- headers={"Content-Type": "text/plain;charset=UTF-8"},
118
- )
119
-
120
- def remove_namespace_modify_role(self, app_id: str, namespace: str, user_code: str):
121
- """移除 Namespace 发布权限(ModifyNamespace)"""
122
- return self._request(
123
- "DELETE",
124
- f"/apps/{app_id}/namespaces/{namespace}/roles/ModifyNamespace",
125
- params={"user": user_code},
126
- )
127
-
128
- def remove_namespace_release_role(self, app_id: str, namespace: str, user_code: str):
129
- """移除 Namespace 发布权限(ReleaseNamespace)"""
130
- return self._request(
131
- "DELETE",
132
- f"/apps/{app_id}/namespaces/{namespace}/roles/ReleaseNamespace",
133
- params={"user": user_code},
134
- )
135
-
136
- def add_namespace_release_role(self, app_id: str, namespace: str, user_code: str):
137
- """分配 Namespace 发布权限(ReleaseNamespace)"""
138
- return self._request(
139
- "POST",
140
- f"/apps/{app_id}/namespaces/{namespace}/roles/ReleaseNamespace",
141
- data=user_code,
142
- headers={"Content-Type": "text/plain;charset=UTF-8"},
143
- )
File without changes