qpi-cli 0.2.0__py3-none-any.whl

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.
qpi_cli/core.py ADDED
@@ -0,0 +1,405 @@
1
+ # -*- coding: utf-8 -*-
2
+ """qpi-cli 核心: 输出辅助 / SDK 根定位 / 配置读写 / SDK 环境内执行。"""
3
+
4
+ import fnmatch
5
+ import json
6
+ import os
7
+ import re
8
+ import shlex
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+
13
+ # ---- SDK 内部相对路径 (全部相对 SDK 根目录) --------------------------------
14
+ BUILD_SH = "quectel_build/compile/build.sh"
15
+ GEN_HEADER = "quectel_build/compile/quectel-features-config/quectel-buildconfig-gen.h"
16
+ FLASH_SH = "quectel_build/tools/flash.sh"
17
+ VERSION_TXT = "tools/VERSION.txt"
18
+ INSTALL_ENV_SH = "install_build_env.sh"
19
+ BUILD_DIR = "build-qcom-wayland"
20
+
21
+ # 固件版本目录的"打包指纹": buildpackage 会往版本目录里放这些 (支持通配)
22
+ FW_MARKER_PATTERNS = (
23
+ "rawprogram*.xml",
24
+ "prog_firehose*.elf",
25
+ "partition*.xml",
26
+ "contents.xml",
27
+ )
28
+
29
+ # quectel_build/ 下的基础设施目录, 一律不计入"固件版本目录"
30
+ INFRA_DIRS = {
31
+ "compile",
32
+ "tools",
33
+ "output",
34
+ "downloads",
35
+ "sstate-cache",
36
+ "BP",
37
+ "build-qcom-wayland",
38
+ "conf",
39
+ "sources",
40
+ "tmp",
41
+ "logs",
42
+ }
43
+
44
+ DEFAULT_REV = "SG565DWFPARL1A01_BL01BP01K0M01_QDP_LP6.6.0XX.01.00X_V0X"
45
+
46
+
47
+ def has_fw_fingerprint(path):
48
+ """目录 (仅顶层) 是否含任一打包指纹文件。"""
49
+ try:
50
+ names = os.listdir(path)
51
+ except OSError:
52
+ return False
53
+ for name in names:
54
+ for pat in FW_MARKER_PATTERNS:
55
+ if fnmatch.fnmatch(name, pat):
56
+ return True
57
+ return False
58
+
59
+
60
+ # ---------------------------------------------------------------- 输出辅助 ---
61
+ def _color(code, text):
62
+ if sys.stdout.isatty() and os.environ.get("NO_COLOR") is None:
63
+ return "\033[%sm%s\033[0m" % (code, text)
64
+ return text
65
+
66
+
67
+ def info(msg):
68
+ print("%s %s" % (_color("32;1", "[INFO]"), msg), flush=True)
69
+
70
+
71
+ def warn(msg):
72
+ print(
73
+ "%s %s" % (_color("33;1", "[WARN]"), msg), file=sys.stderr, flush=True
74
+ )
75
+
76
+
77
+ def error(msg):
78
+ print(
79
+ "%s %s" % (_color("31;1", "[ERROR]"), msg), file=sys.stderr, flush=True
80
+ )
81
+
82
+
83
+ def banner(title):
84
+ print(_color("36;1", "=== %s ===" % title), flush=True)
85
+
86
+
87
+ _VERDICT_COLOR = {"PASS": "32;1", "WARN": "33;1", "FAIL": "31;1"}
88
+
89
+
90
+ def verdict(state, label, msg):
91
+ print(
92
+ " %s %-32s %s"
93
+ % (_color(_VERDICT_COLOR[state], "[%s]" % state), label, msg)
94
+ )
95
+
96
+
97
+ # ------------------------------------------------------------ SDK 根定位 ---
98
+ def _is_sdk_root(path):
99
+ """硬条件: 目录下存在 quectel_build/compile/build.sh。
100
+
101
+ tools/VERSION.txt 降级为可选 (仅作为辅助信息, 不作必要条件)。
102
+ """
103
+ return os.path.isfile(os.path.join(path, BUILD_SH))
104
+
105
+
106
+ def find_sdk_root(start=None):
107
+ """定位 SDK 根目录。
108
+
109
+ 候选顺序: $QPI_SDK_ROOT -> --sdk/start -> 当前目录及其各级父目录。
110
+ 判定硬条件是存在 build.sh; 额外优先接受同时存在 install_build_env.sh 的
111
+ 目录 (对外仓库的首次环境安装入口, 可提高判定置信度)。
112
+ """
113
+ cand = []
114
+ if os.environ.get("QPI_SDK_ROOT"):
115
+ cand.append(os.environ["QPI_SDK_ROOT"])
116
+ if start:
117
+ cand.append(start)
118
+ cur = os.getcwd()
119
+ for _ in range(6):
120
+ cand.append(cur)
121
+ parent = os.path.dirname(cur)
122
+ if parent == cur:
123
+ break
124
+ cur = parent
125
+
126
+ best = None
127
+ for c in cand:
128
+ if not c or not os.path.isdir(c):
129
+ continue
130
+ if _is_sdk_root(c):
131
+ # 同时具备 install_build_env.sh 视为强信号, 直接采用
132
+ if os.path.isfile(os.path.join(c, INSTALL_ENV_SH)):
133
+ return os.path.abspath(c)
134
+ if best is None:
135
+ best = os.path.abspath(c)
136
+ return best
137
+
138
+
139
+ # --------------------------------------------------------------- 配置读写 ---
140
+ def user_config_path():
141
+ """用户级配置路径 (默认落盘位置, 不写入用户 clone 的 SDK)。"""
142
+ return os.path.join(
143
+ os.path.expanduser("~"), ".config", "qpi-cli", "config.json"
144
+ )
145
+
146
+
147
+ def resolve_config_path(root):
148
+ """解析配置路径, 返回 (path, read_only)。
149
+
150
+ 优先级: $QPI_CONFIG > SDK 根下 .qpi_config.json (只读覆盖) > 用户级路径。
151
+ """
152
+ env = os.environ.get("QPI_CONFIG")
153
+ if env:
154
+ return os.path.abspath(os.path.expanduser(env)), False
155
+ sdk_override = os.path.join(root, ".qpi_config.json")
156
+ if os.path.isfile(sdk_override):
157
+ return sdk_override, True
158
+ return user_config_path(), False
159
+
160
+
161
+ def default_config():
162
+ return {
163
+ "schema": 1,
164
+ "sdk": {"name": "yocto-h1", "type": "yocto"},
165
+ "build": {
166
+ "project": "QSM565DWF",
167
+ "rev": DEFAULT_REV,
168
+ "os": "LINUX",
169
+ "version": "STD",
170
+ },
171
+ }
172
+
173
+
174
+ def dget(d, path, default=None):
175
+ cur = d
176
+ for k in path.split("."):
177
+ if not isinstance(cur, dict) or k not in cur:
178
+ return default
179
+ cur = cur[k]
180
+ return cur
181
+
182
+
183
+ def dset(d, path, value):
184
+ keys = path.split(".")
185
+ cur = d
186
+ for k in keys[:-1]:
187
+ cur = cur.setdefault(k, {})
188
+ cur[keys[-1]] = value
189
+
190
+
191
+ class Ctx:
192
+ def __init__(self, root):
193
+ self.root = root
194
+ self.config_path, self.read_only = resolve_config_path(root)
195
+ self.config = self._load_config()
196
+
197
+ def _load_config(self):
198
+ if os.path.isfile(self.config_path):
199
+ try:
200
+ with open(self.config_path, "r") as fh:
201
+ cfg = json.load(fh)
202
+ base = default_config()
203
+ # 浅合并, 缺字段时回落到默认值
204
+ for k, v in base.items():
205
+ cfg.setdefault(k, v)
206
+ return cfg
207
+ except (ValueError, OSError) as exc:
208
+ warn(
209
+ "读取 %s 失败 (%s), 回落到默认配置"
210
+ % (self.config_path, exc)
211
+ )
212
+ return default_config()
213
+
214
+ def save_config(self):
215
+ path = self.config_path
216
+ if self.read_only:
217
+ # SDK 根下的 .qpi_config.json 仅作为只读覆盖, 改写落到用户级
218
+ path = user_config_path()
219
+ warn(
220
+ "%s 是 SDK 根下只读覆盖配置, 改写用户级配置: %s"
221
+ % (self.config_path, path)
222
+ )
223
+ parent = os.path.dirname(path)
224
+ if parent:
225
+ os.makedirs(parent, exist_ok=True)
226
+ with open(path, "w") as fh:
227
+ json.dump(self.config, fh, indent=2, ensure_ascii=False)
228
+ fh.write("\n")
229
+
230
+ def p(self, *parts):
231
+ return os.path.join(self.root, *parts)
232
+
233
+ # ---- SDK 元信息 ----
234
+ def sdk_meta(self):
235
+ """解析 tools/VERSION.txt。缺文件/缺键都不报错, 缺失键由调用方降级。"""
236
+ meta = {}
237
+ path = self.p(VERSION_TXT)
238
+ if not os.path.isfile(path):
239
+ return meta
240
+ try:
241
+ with open(path, "r") as fh:
242
+ for line in fh:
243
+ line = line.strip()
244
+ if not line or line.startswith("#") or "=" not in line:
245
+ continue
246
+ k, v = line.split("=", 1)
247
+ meta[k.strip()] = v.strip()
248
+ except OSError:
249
+ return {}
250
+ return meta
251
+
252
+ def current_header(self):
253
+ """解析 quectel-buildconfig-gen.h, 得到当前 buildconfig 的落盘值。
254
+
255
+ 文件缺失或键缺失都安全降级, 不会抛异常。
256
+ """
257
+ out = {}
258
+ path = self.p(GEN_HEADER)
259
+ if not os.path.isfile(path):
260
+ return out
261
+ pat = re.compile(r'^#define\s+(QUECTEL_\w+)\s+"([^"]*)"')
262
+ try:
263
+ with open(path, "r") as fh:
264
+ for line in fh:
265
+ m = pat.match(line.strip())
266
+ if m:
267
+ out[m.group(1)] = m.group(2)
268
+ except OSError:
269
+ return {}
270
+ return out
271
+
272
+ def current_rev(self):
273
+ hdr = self.current_header()
274
+ return hdr.get("QUECTEL_PROJECT_REV") or dget(
275
+ self.config, "build.rev", DEFAULT_REV
276
+ )
277
+
278
+ def current_custom(self):
279
+ hdr = self.current_header()
280
+ return hdr.get("QUECTEL_CUSTOM_NAME") or dget(
281
+ self.config, "build.version", "STD"
282
+ )
283
+
284
+ # ---- 固件版本目录 (三态) ----
285
+ def rev_candidate_names(self):
286
+ """当前 buildconfig 对应的候选版本目录名 (rev 与 rev_DBG)。"""
287
+ rev = self.current_rev()
288
+ return {rev, rev + "_DBG"}
289
+
290
+ def rev_dirs(self):
291
+ """枚举 quectel_build/ 下的固件版本目录及其状态。
292
+
293
+ 候选判定 (满足任一即为版本目录, 其余目录一律排除):
294
+ 1) 目录内 (顶层) 存在任一打包指纹文件 -> "已打包(可烧录)";
295
+ 2) 目录名等于当前 buildconfig 的 rev 或 rev_DBG (目录存在即算),
296
+ 有指纹即"已打包(可烧录)", 无指纹即"已构建未打包"。
297
+
298
+ 返回 [(name, path, state)]; 全新 clone (目录不存在/为空) 返回空列表, 不报错。
299
+ """
300
+ base = self.p("quectel_build")
301
+ found = []
302
+ if not os.path.isdir(base):
303
+ return found
304
+ rev_names = self.rev_candidate_names()
305
+ try:
306
+ entries = sorted(os.listdir(base))
307
+ except OSError:
308
+ return found
309
+ for name in entries:
310
+ path = os.path.join(base, name)
311
+ if not os.path.isdir(path):
312
+ continue
313
+ if name.startswith(".") or name in INFRA_DIRS:
314
+ continue
315
+ packaged = has_fw_fingerprint(path)
316
+ if not packaged and name not in rev_names:
317
+ continue
318
+ state = "已打包(可烧录)" if packaged else "已构建未打包"
319
+ found.append((name, path, state))
320
+ return found
321
+
322
+ def rev_state(self, name):
323
+ """按目录名判定单个版本的三态 (供 '未构建' 场景使用)。"""
324
+ path = self.p("quectel_build", name)
325
+ if not os.path.isdir(path):
326
+ return "未构建"
327
+ if has_fw_fingerprint(path):
328
+ return "已打包(可烧录)"
329
+ return "已构建未打包"
330
+
331
+ def firmware_dirs(self):
332
+ """仅返回已打包 (含指纹文件) 的版本目录, 供 clean 使用。"""
333
+ return [
334
+ (name, path)
335
+ for name, path, state in self.rev_dirs()
336
+ if state == "已打包(可烧录)"
337
+ ]
338
+
339
+
340
+ # ------------------------------------------------------- SDK 环境内执行 -----
341
+ def run_sdk(cmd_body, sdk_root, verbose=False, dry_run=False):
342
+ """在 source 过 build.sh 的 bash 环境里执行 cmd_body。
343
+
344
+ build.sh 是 source 型脚本: 它会设置 TOPDIR/BUILDDIR 等变量、定义
345
+ buildconfig/buildall/buildpackage/flash 等函数。所以这里生成一段临时
346
+ bash, 先 source 再把调用体接在后面。
347
+ """
348
+ lines = [
349
+ "#!/bin/bash",
350
+ "cd %s || exit 1" % shlex.quote(sdk_root),
351
+ "source %s %s || { echo '[qpi-cli] ERROR: source build.sh failed' >&2; exit 1; }"
352
+ % (shlex.quote(BUILD_SH), ">/dev/null" if not verbose else ""),
353
+ "set -e",
354
+ cmd_body,
355
+ ]
356
+ script = "\n".join(lines) + "\n"
357
+
358
+ if dry_run:
359
+ banner("dry-run: 将要执行的 SDK 环境脚本")
360
+ print(script, flush=True)
361
+ return 0
362
+
363
+ if verbose:
364
+ banner("SDK environment script")
365
+ sys.stdout.flush()
366
+ sys.stderr.flush()
367
+
368
+ fd, tmp = tempfile.mkstemp(prefix="qpi-cli-", suffix=".sh", text=True)
369
+ try:
370
+ with os.fdopen(fd, "w") as fh:
371
+ fh.write(script)
372
+ proc = subprocess.run(["bash", tmp], cwd=sdk_root)
373
+ return proc.returncode
374
+ finally:
375
+ try:
376
+ os.remove(tmp)
377
+ except OSError:
378
+ pass
379
+
380
+
381
+ # ------------------------------------------------------------- flash 探测 ---
382
+ def configured_flash_entry(ctx):
383
+ """tools/VERSION.txt 中配置的 FLASH_ENTRY (原始值, 可能不存在/为空)。"""
384
+ return (ctx.sdk_meta().get("FLASH_ENTRY") or "").strip()
385
+
386
+
387
+ def resolve_flash_entry(ctx):
388
+ """按配置探测烧录入口 (相对 SDK 根的路径)。
389
+
390
+ 读 tools/VERSION.txt 的 FLASH_ENTRY; 若该键缺失或其指向的文件不存在,
391
+ 回落到 quectel_build/tools/flash.sh。
392
+ """
393
+ entry = configured_flash_entry(ctx)
394
+ if entry and os.path.isfile(ctx.p(entry)):
395
+ return entry
396
+ return FLASH_SH
397
+
398
+
399
+ def flash_entry_error(entry):
400
+ """校验配置的烧录入口是否可用于本 (Linux 宿主) 版本; 返回错误信息或 None。"""
401
+ if sys.platform.startswith("win"):
402
+ return "当前版本仅支持 Linux 宿主 (检测到 Windows 平台)"
403
+ if entry and entry.lower().endswith(".bat"):
404
+ return "当前版本仅支持 Linux 宿主, 不支持 .bat 烧录入口: %s" % entry
405
+ return None
qpi_cli/templates.py ADDED
@@ -0,0 +1,41 @@
1
+ # -*- coding: utf-8 -*-
2
+ """qpi-cli new 子命令生成应用工程时使用的文件模板。"""
3
+
4
+ MAIN_C_TMPL = """#include <stdio.h>
5
+
6
+ int main(void)
7
+ {
8
+ printf("Hello from %s on QuecPi QCS6490!\\n");
9
+ return 0;
10
+ }
11
+ """
12
+
13
+ MAKEFILE_TMPL = """# %(app)s — QuecPi QCS6490 application
14
+ # The cross toolchain comes from the SDK (eSDK); without it CC falls back to
15
+ # the host gcc and is only good for a syntax check.
16
+ CC ?= aarch64-poky-linux-gcc
17
+ CFLAGS ?= -O2 -Wall
18
+ TARGET = %(app)s
19
+
20
+ all: $(TARGET)
21
+
22
+ $(TARGET): main.c
23
+ \t$(CC) $(CFLAGS) -o $@ $<
24
+
25
+ clean:
26
+ \trm -f $(TARGET)
27
+
28
+ .PHONY: all clean
29
+ """
30
+
31
+ CODE_WORKSPACE_TMPL = """{
32
+ "folders": [
33
+ { "name": "%(app)s", "path": "." },
34
+ { "name": "sdk:quectel_build", "path": "../../quectel_build" },
35
+ { "name": "sdk:layers", "path": "../../layers" }
36
+ ],
37
+ "settings": {
38
+ "files.exclude": { "**/.git": true }
39
+ }
40
+ }
41
+ """
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Quectel Pi
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.