pkq 0.2.7

Unified package query CLI for DEB/RPM Linux distros (dpkg/apt, rpm/dnf)
Documentation
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};

use crate::error::{PkgError, Result};
use crate::model::PkgMetadata;

const CACHE_VERSION: u32 = 6;

#[derive(Serialize, Deserialize)]
pub struct PkgIndexCache {
    pub version: u32,
    pub packages: Vec<PkgMetadata>,
}

fn cache_dir() -> PathBuf {
    let dir = dirs::cache_dir()
        .unwrap_or_else(|| PathBuf::from("/tmp"))
        .join("pkq");
    if let Err(e) = std::fs::create_dir_all(&dir) {
        tracing::warn!("Failed to create cache dir {:?}: {}", dir, e);
    }
    dir
}

/// 缓存占用清单(相对路径, 字节数),按大小降序
pub fn cache_status() -> Vec<(String, u64)> {
    let base = cache_dir();
    let mut items: Vec<(String, u64)> = Vec::new();
    fn dir_size(dir: &Path) -> u64 {
        let mut total = 0;
        if let Ok(entries) = std::fs::read_dir(dir) {
            for e in entries.flatten() {
                let p = e.path();
                if p.is_dir() {
                    total += dir_size(&p);
                } else if let Ok(m) = e.metadata() {
                    total += m.len();
                }
            }
        }
        total
    }
    if let Ok(entries) = std::fs::read_dir(&base) {
        for e in entries.flatten() {
            let p = e.path();
            let size = if p.is_dir() {
                dir_size(&p)
            } else {
                e.metadata().map(|m| m.len()).unwrap_or(0)
            };
            if size > 0 {
                let rel = p
                    .strip_prefix(&base)
                    .unwrap_or(&p)
                    .to_string_lossy()
                    .to_string();
                items.push((rel, size));
            }
        }
    }
    items.sort_by_key(|(_, size)| std::cmp::Reverse(*size));
    items
}

/// pkq 缓存目录树中的最大 mtime(即最近一次元数据下载/落盘时间)。
/// 用于「上次元数据过期检查」Banner 的真实时间源——优先于发行版原生缓存目录。
pub fn cache_dir_mtime() -> u64 {
    fn walk(dir: &Path) -> u64 {
        let mut max = 0u64;
        if let Ok(entries) = std::fs::read_dir(dir) {
            for e in entries.flatten() {
                let p = e.path();
                if p.is_dir() {
                    max = max.max(walk(&p));
                } else if let Ok(m) = e.metadata() {
                    if let Ok(t) = m.modified() {
                        let s = t
                            .duration_since(UNIX_EPOCH)
                            .map(|d| d.as_secs())
                            .unwrap_or(0);
                        if s > max {
                            max = s;
                        }
                    }
                }
            }
        }
        max
    }
    walk(&cache_dir())
}

/// 按清理目标计算当前占用字节数(用于 clean 前的确认提示)。
/// target: all | index | repos | contents
pub fn cache_target_size(target: &str) -> u64 {
    let base = cache_dir();
    fn dir_size(dir: &Path) -> u64 {
        let mut total = 0;
        if let Ok(entries) = std::fs::read_dir(dir) {
            for e in entries.flatten() {
                let p = e.path();
                if p.is_dir() {
                    total += dir_size(&p);
                } else if let Ok(m) = e.metadata() {
                    total += m.len();
                }
            }
        }
        total
    }
    match target {
        "all" => dir_size(&base),
        "index" => dir_size(&base.join("index")),
        "repos" => dir_size(&base.join("repos")),
        "contents" => [deb_contents_raw_cache_path(), deb_contents_raw_meta_path()]
            .iter()
            .map(|p| std::fs::metadata(p).map(|m| m.len()).unwrap_or(0))
            .sum(),
        _ => 0,
    }
}

/// 清理缓存,返回释放的字节数。target: all | index | repos | contents
pub fn cache_clean(target: &str) -> Result<u64> {
    let base = cache_dir();
    let before = cache_target_size(target);
    let remove = |p: &Path| -> Result<()> {
        if p.is_dir() {
            std::fs::remove_dir_all(p)
        } else if p.exists() {
            std::fs::remove_file(p)
        } else {
            Ok(())
        }
        .map_err(|e| PkgError::IoError(format!("清理失败 {:?}: {}", p, e)))
    };
    match target {
        "all" => remove(&base)?,
        "index" => remove(&base.join("index"))?,
        "repos" => remove(&base.join("repos"))?,
        "contents" => {
            remove(&deb_contents_raw_cache_path())?;
            remove(&deb_contents_raw_meta_path())?;
        }
        other => {
            return Err(PkgError::InvalidArgument(format!(
                "未知清理目标: {}(可选 all|index|repos|contents)",
                other
            )))
        }
    }
    let after: u64 = cache_status().iter().map(|(_, s)| *s).sum();
    Ok(before.saturating_sub(after))
}

/// 原子落盘前确保目标父目录存在(改名迁移回归修复:
/// cache_dir 不再预建 index 子目录,save 必须自建,否则静默失败)。
fn ensure_parent_dir(path: &Path) -> Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| {
            PkgError::IoError(format!("Failed to create cache dir {:?}: {}", parent, e))
        })?;
    }
    Ok(())
}

/// 缓存文件魔数:与历史 bincode 1.x 格式强制隔离。
/// 历史事故:bincode 1 数据被 postcard varint 误读为「0 个包的合法缓存」
/// (version 字段恰好通过校验),导致本地库静默失效。魔数使异构格式
/// 在解析前即被拒绝。
const CACHE_MAGIC: &[u8; 4] = b"PKQ1";

fn encode_cache<T: serde::Serialize>(value: &T) -> Result<Vec<u8>> {
    let body = postcard::to_allocvec(value)
        .map_err(|e| PkgError::IoError(format!("Failed to serialize cache: {}", e)))?;
    let mut buf = Vec::with_capacity(body.len() + CACHE_MAGIC.len());
    buf.extend_from_slice(CACHE_MAGIC);
    buf.extend_from_slice(&body);
    Ok(buf)
}

fn decode_cache<T: serde::de::DeserializeOwned>(data: &[u8]) -> Option<T> {
    let body = data.get(CACHE_MAGIC.len()..)?;
    if &data[..CACHE_MAGIC.len()] != CACHE_MAGIC {
        return None; // 异构/损坏格式:拒绝解析
    }
    postcard::from_bytes(body).ok()
}

fn file_mtime(path: &Path) -> u64 {
    std::fs::metadata(path)
        .and_then(|m| m.modified())
        .map(|t| {
            t.duration_since(UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0)
        })
        .unwrap_or(0)
}

/// 补全用的本地包名+摘要缓存:TAB 补全每次按键都会拉起本进程,
/// 必须避免全量解析 dpkg status / rpmdb(实测占补全延迟 96%)。
/// 失效键 = 本地数据库文件 mtime。
#[derive(Serialize, Deserialize)]
pub struct CompletionNamesCache {
    pub source_mtime: u64,
    pub packages: Vec<(String, String)>,
}

impl CompletionNamesCache {
    pub fn load(path: &Path, source_mtime: u64) -> Option<Self> {
        if source_mtime == 0 {
            return None;
        }
        let data = std::fs::read(path).ok()?;
        let cache: Self = decode_cache(&data)?;
        if cache.source_mtime != source_mtime {
            return None;
        }
        // 空包列表 = 损坏缓存(与 PkgIndexCache 同款防御)
        if cache.packages.is_empty() {
            return None;
        }
        Some(cache)
    }

    pub fn save(path: &Path, source_mtime: u64, packages: Vec<(String, String)>) -> Result<()> {
        let cache = Self {
            source_mtime,
            packages,
        };
        let data = encode_cache(&cache)?;
        let tmp = path.with_extension("tmp");
        ensure_parent_dir(path)?;
        std::fs::write(&tmp, &data)?;
        std::fs::rename(&tmp, path)?;
        Ok(())
    }
}

/// 补全包名缓存路径(位于 index/ 下,自动纳入 cache status/clean)
pub fn completion_names_cache_path() -> PathBuf {
    cache_dir().join("index").join("completion_names.bin")
}

fn max_source_mtime(paths: &[PathBuf]) -> u64 {
    paths
        .iter()
        .filter_map(|p| {
            let m = file_mtime(p);
            if m > 0 {
                Some(m)
            } else {
                None
            }
        })
        .max()
        .unwrap_or(0)
}

impl PkgIndexCache {
    pub fn load(path: &Path, ttl: u64, force: bool, source_files: &[PathBuf]) -> Option<Self> {
        if force {
            return None;
        }
        let cache_mtime = file_mtime(path);
        if cache_mtime == 0 {
            return None;
        }
        let src_max = max_source_mtime(source_files);
        if cache_mtime < src_max {
            return None;
        }
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        if ttl > 0 && now > cache_mtime && now - cache_mtime > ttl {
            return None;
        }
        let data = std::fs::read(path).ok()?;
        let cache: PkgIndexCache = decode_cache(&data)?;
        if cache.version != CACHE_VERSION {
            return None;
        }
        // 空包列表 = 损坏缓存(历史事故:异构格式被误读为 0 个包)
        if cache.packages.is_empty() {
            return None;
        }
        Some(cache)
    }

    pub fn save(path: &Path, packages: Vec<PkgMetadata>) -> Result<()> {
        let cache = PkgIndexCache {
            version: CACHE_VERSION,
            packages,
        };
        let data = encode_cache(&cache)?;
        let tmp = path.with_extension("tmp");
        ensure_parent_dir(path)?;
        std::fs::write(&tmp, &data)?;
        std::fs::rename(&tmp, path)?;
        Ok(())
    }
}

#[derive(Serialize, Deserialize)]
pub struct ContentsMeta {
    version: u32,
}

impl ContentsMeta {
    pub fn check_valid(meta_path: &Path, ttl: u64, force: bool, source_files: &[PathBuf]) -> bool {
        if force {
            return false;
        }
        let meta_mtime = file_mtime(meta_path);
        if meta_mtime == 0 {
            return false;
        }
        let src_max = max_source_mtime(source_files);
        if meta_mtime < src_max {
            return false;
        }
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        if ttl > 0 && now > meta_mtime && now - meta_mtime > ttl {
            return false;
        }
        let data = match std::fs::read(meta_path) {
            Ok(d) => d,
            Err(_) => return false,
        };
        let meta: ContentsMeta = match decode_cache(&data) {
            Some(m) => m,
            None => return false,
        };
        meta.version == CACHE_VERSION
    }

    pub fn save_meta(path: &Path) -> Result<()> {
        let meta = ContentsMeta {
            version: CACHE_VERSION,
        };
        let data = encode_cache(&meta)?;
        let tmp = path.with_extension("tmp");
        ensure_parent_dir(path)?;
        std::fs::write(&tmp, &data)?;
        std::fs::rename(&tmp, path)?;
        Ok(())
    }
}

pub fn deb_cache_path() -> PathBuf {
    cache_dir().join("index").join("deb_packages.bin")
}

/// RPM 本地 rpmdb 解析结果缓存(P1-1)
pub fn rpm_local_cache_path() -> PathBuf {
    cache_dir().join("index").join("rpm_local.bin")
}

/// RPM 仓库 primary 解析结果缓存(P1-1),按 repo_id + baseurl 区分
pub fn rpm_repo_cache_path(repo_id: &str, baseurl: &str) -> PathBuf {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};
    let mut hasher = DefaultHasher::new();
    baseurl.hash(&mut hasher);
    let safe_id: String = repo_id
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect();
    cache_dir()
        .join("index")
        .join(format!("rpm_repo_{}_{:016x}.bin", safe_id, hasher.finish()))
}

/// RPM 仓库 primary 解析缓存:以 repomd 中 primary 数据项的 timestamp 为失效键
#[derive(Serialize, Deserialize)]
pub struct RpmRepoCache {
    pub primary_ts: i64,
    pub packages: Vec<PkgMetadata>,
}

impl RpmRepoCache {
    pub fn load(path: &Path, expected_ts: i64) -> Option<Self> {
        if expected_ts <= 0 {
            return None;
        }
        let data = std::fs::read(path).ok()?;
        let cache: RpmRepoCache = decode_cache(&data)?;
        if cache.primary_ts != expected_ts {
            return None;
        }
        // 空包列表 = 损坏缓存
        if cache.packages.is_empty() {
            return None;
        }
        Some(cache)
    }

    /// repomd 不可用时的最后降级:忽略时间戳校验直接加载解析缓存,
    /// 数据可能过期但保证仓库查询在离线/源故障场景下仍可用
    pub fn load_any(path: &Path) -> Option<Self> {
        let data = std::fs::read(path).ok()?;
        let cache: RpmRepoCache = decode_cache(&data)?;
        // 空包列表 = 损坏缓存
        if cache.packages.is_empty() {
            return None;
        }
        Some(cache)
    }

    pub fn save(path: &Path, primary_ts: i64, packages: Vec<PkgMetadata>) -> Result<()> {
        let cache = RpmRepoCache {
            primary_ts,
            packages,
        };
        let data = encode_cache(&cache)?;
        let tmp = path.with_extension("tmp");
        ensure_parent_dir(path)?;
        std::fs::write(&tmp, &data)?;
        std::fs::rename(&tmp, path)?;
        Ok(())
    }
}

pub fn deb_contents_raw_cache_path() -> PathBuf {
    cache_dir().join("index").join("deb_contents_raw.txt")
}

pub fn deb_contents_raw_meta_path() -> PathBuf {
    cache_dir().join("index").join("deb_contents_raw.meta")
}

/// RPM filelists 扁平索引(`file_path\tpkg_name\n`),落盘后 mmap 检索(对齐 DEB Contents)。
pub fn rpm_filelists_cache_path() -> PathBuf {
    cache_dir().join("index").join("rpm_filelists.txt")
}

/// RPM filelists 扁平索引的失效键元数据。
pub fn rpm_filelists_meta_path() -> PathBuf {
    cache_dir().join("index").join("rpm_filelists.meta")
}

/// RPM filelists 索引的失效键(各源 filelists 数据项时间戳,按仓库顺序拼接)。
#[derive(Serialize, Deserialize)]
pub struct RpmFilelistsMeta {
    pub key: String,
}

impl RpmFilelistsMeta {
    pub fn load(path: &Path) -> Option<Self> {
        let data = std::fs::read(path).ok()?;
        decode_cache(&data)
    }

    pub fn save(path: &Path, key: String) -> Result<()> {
        let data = encode_cache(&RpmFilelistsMeta { key })?;
        let tmp = path.with_extension("tmp");
        ensure_parent_dir(path)?;
        std::fs::write(&tmp, &data)?;
        std::fs::rename(&tmp, path)?;
        Ok(())
    }
}

pub fn deb_apt_sources() -> Vec<PathBuf> {
    let mut paths = vec![PathBuf::from("/etc/apt/sources.list")];
    let sources_d = PathBuf::from("/etc/apt/sources.list.d");
    if let Ok(entries) = std::fs::read_dir(&sources_d) {
        for entry in entries.flatten() {
            let p = entry.path();
            let ext = p.extension().and_then(|e| e.to_str());
            // .list(one-line)与 .sources(deb822)均为有效源定义
            if ext == Some("list") || ext == Some("sources") {
                paths.push(p);
            }
        }
    }
    paths
}

pub fn deb_apt_lists_packages() -> Vec<PathBuf> {
    let mut paths = Vec::new();
    let lists_dir = PathBuf::from("/var/lib/apt/lists");
    if let Ok(entries) = std::fs::read_dir(&lists_dir) {
        for entry in entries.flatten() {
            let p = entry.path();
            if p.to_string_lossy().ends_with("_Packages") {
                paths.push(p);
            }
        }
    }
    paths
}

pub fn deb_apt_lists_contents() -> Vec<PathBuf> {
    let mut paths = Vec::new();
    let lists_dir = PathBuf::from("/var/lib/apt/lists");
    if let Ok(entries) = std::fs::read_dir(&lists_dir) {
        for entry in entries.flatten() {
            let p = entry.path();
            let name = p.to_string_lossy();
            if name.contains("Contents-") && name.ends_with(".lz4") {
                paths.push(p);
            }
        }
    }
    paths
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_completion_names_cache_roundtrip_and_invalidation() {
        let path = std::env::temp_dir().join(format!(
            "pkq_completion_cache_test_{}.bin",
            std::process::id()
        ));
        let _ = std::fs::remove_file(&path);
        let pkgs = vec![("bash".to_string(), "GNU Bourne Again SHell".to_string())];

        CompletionNamesCache::save(&path, 1234, pkgs.clone()).unwrap();
        // mtime 一致:命中
        let loaded = CompletionNamesCache::load(&path, 1234).unwrap();
        assert_eq!(loaded.packages, pkgs);
        // mtime 变化(数据库更新):失效重建
        assert!(CompletionNamesCache::load(&path, 5678).is_none());
        // 无效 mtime:不信任
        assert!(CompletionNamesCache::load(&path, 0).is_none());

        std::fs::remove_file(&path).ok();
    }
}