sennit 0.9.0

A dotfiles manager that keeps symlink semantics, and adds templating and drift detection
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
use anyhow::{bail, Context, Result};
use std::collections::BTreeMap;

/// テンプレートから見える値をまとめる。
///
/// データファイル(既定は theme.toml)に加えて、その場でしか分からない値も
/// 入れる。ホスト名やプロファイルは配色と違ってファイルに書けないが、
/// マシンごとに変える設定では最も必要になる。
pub fn load_vars(paths: &[std::path::PathBuf]) -> Result<BTreeMap<String, String>> {
    let mut vars = BTreeMap::new();

    for path in paths {
        // 宣言されたデータファイルが無いのは設定漏れなので黙って進まない
        let text = std::fs::read_to_string(path)
            .with_context(|| format!("failed to read {}", path.display()))?;
        let value: toml::Value =
            toml::from_str(&text).with_context(|| format!("failed to parse {}", path.display()))?;
        flatten(&value, String::new(), &mut vars);
    }

    vars.insert("sennit.os".into(), crate::packages::current_os().into());
    vars.insert("sennit.hostname".into(), hostname());
    vars.insert(
        "sennit.profile".into(),
        crate::packages::current_profiles().join(","),
    );
    for (k, v) in std::env::vars() {
        vars.insert(format!("env.{k}"), v);
    }
    Ok(vars)
}

fn hostname() -> String {
    std::process::Command::new("hostname")
        .arg("-s")
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "unknown".into())
}

fn flatten(value: &toml::Value, prefix: String, out: &mut BTreeMap<String, String>) {
    match value {
        toml::Value::Table(t) => {
            for (k, v) in t {
                let key = if prefix.is_empty() {
                    k.clone()
                } else {
                    format!("{prefix}.{k}")
                };
                flatten(v, key, out);
            }
        }
        toml::Value::String(s) => {
            out.insert(prefix, s.clone());
        }
        other => {
            out.insert(prefix, other.to_string());
        }
    }
}

/// `scheme://rest` の形なら分解する。テンプレート変数は `ui.bg` のような
/// ドット記法なので、`://` の有無で区別できる。
pub fn split_reference(key: &str) -> Option<(&str, &str)> {
    let (scheme, rest) = key.split_once("://")?;
    if scheme.is_empty() || rest.is_empty() || scheme.contains(char::is_whitespace) {
        return None;
    }
    Some((scheme, rest))
}

/// このテンプレートが秘密を参照しているか。
///
/// 宣言させるのではなく中身から判定する。書き忘れると初回セットアップが
/// 落ちる種類の宣言は、そもそも人間に書かせない方がよい。
pub fn needs_secrets(template: &str) -> bool {
    let mut rest = template;
    while let Some(i) = rest.find("{{") {
        let after = &rest[i + 2..];
        let Some(end) = after.find("}}") else {
            return false;
        };
        if split_reference(after[..end].trim()).is_some() {
            return true;
        }
        rest = &after[end..];
    }
    false
}

/// `{{ key }}` を差し替えるだけの最小のテンプレート展開。
///
/// 汎用テンプレートエンジンを入れないのは、条件分岐やループを持ち込むと
/// 生成元が「設定ファイルとして読めるもの」でなくなるため。置換だけに
/// 限れば *.tmpl は元の設定とほぼ同じ見た目のまま保てる。
/// 秘密の取り出し方。
///
/// 主要なプロバイダはどれも「コマンドを実行して標準出力を受け取る」形なので、
/// プロバイダごとに実装を書かない。scheme とコマンドの対応を宣言してもらう。
/// こうすると sennit が知らないプロバイダでも動く。
#[derive(Debug, Clone, serde::Deserialize)]
pub struct Provider {
    /// `{}` が参照文字列に置き換わる。`op read --no-newline {}` のように書く。
    pub command: String,
    /// 末尾の改行を落とす。多くの CLI は改行を付けて返す。
    #[serde(default = "yes")]
    pub trim: bool,
}

fn yes() -> bool {
    true
}

/// scheme -> 取り出し方
pub type Providers = BTreeMap<String, Provider>;

/// 宣言が無いときの既定。1Password だけを知っている。
pub fn default_providers() -> Providers {
    let mut m = BTreeMap::new();
    m.insert(
        "op".to_string(),
        Provider {
            command: "op read --no-newline {}".into(),
            trim: true,
        },
    );
    m
}

/// 1 回の render で同じ参照を何度も引かないよう覚えておく。
#[derive(Default)]
pub struct SecretCache {
    seen: BTreeMap<String, String>,
    providers: Providers,
}

impl SecretCache {
    pub fn with(providers: Providers) -> Self {
        Self {
            seen: BTreeMap::new(),
            providers,
        }
    }

    fn read(&mut self, scheme: &str, reference: &str) -> Result<String> {
        let key = format!("{scheme}://{reference}");
        if let Some(v) = self.seen.get(&key) {
            return Ok(v.clone());
        }
        let Some(provider) = self.providers.get(scheme) else {
            let known: Vec<&str> = self.providers.keys().map(String::as_str).collect();
            bail!(
                "no provider declared for `{scheme}://`. Known: {}",
                if known.is_empty() {
                    "(none)".to_string()
                } else {
                    known.join(", ")
                }
            );
        };

        // 参照は引数として渡す。シェルを経由しないので、参照に空白や記号が
        // あってもそのまま届き、注入の余地も無い。
        let mut parts = shell_words(&provider.command);
        if parts.is_empty() {
            bail!("provider `{scheme}` has an empty command");
        }
        for part in parts.iter_mut() {
            *part = part.replace("{}", reference);
        }
        let bin = parts.remove(0);

        let out = std::process::Command::new(&bin)
            .args(&parts)
            .output()
            .with_context(|| format!("failed to run `{bin}` for {scheme}://; is it installed?"))?;
        if !out.status.success() {
            bail!(
                "`{} {}` failed: {}",
                bin,
                parts.join(" "),
                String::from_utf8_lossy(&out.stderr).trim()
            );
        }
        let mut value =
            String::from_utf8(out.stdout).with_context(|| format!("{key} is not valid UTF-8"))?;
        if provider.trim {
            while value.ends_with('\n') || value.ends_with('\r') {
                value.pop();
            }
        }
        self.seen.insert(key, value.clone());
        Ok(value)
    }
}

/// 引用符を尊重した最小の分割。見るのはコマンド定義側の引用だけ。
fn shell_words(s: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut cur = String::new();
    let mut quote: Option<char> = None;
    let mut had_quote = false;
    for c in s.chars() {
        match (quote, c) {
            (Some(q), ch) if ch == q => quote = None,
            (Some(_), ch) => cur.push(ch),
            (None, '\'') | (None, '"') => {
                quote = Some(c);
                had_quote = true;
            }
            (None, ch) if ch.is_whitespace() => {
                if !cur.is_empty() || had_quote {
                    out.push(std::mem::take(&mut cur));
                    had_quote = false;
                }
            }
            (None, ch) => cur.push(ch),
        }
    }
    if !cur.is_empty() || had_quote {
        out.push(cur);
    }
    out
}

/// 条件ブロックを先に処理して、残らない側を落とす。
///
/// ループも関数も入れない。入れた瞬間にテンプレートが「生成先の設定ファイル
/// として読めるもの」でなくなる。ブロック単位の分岐だけなら、消える行が
/// 見えるだけで元の形は保たれる。
///
///     {{ if sennit.os == "darwin" }}
///     macos-option-as-alt = true
///     {{ end }}
///
/// 比較は == と != のみ。左辺は変数、右辺は変数か引用符付きの文字列。
/// `{{ if var }}` は「空でなければ真」。
fn strip_conditionals(
    template: &str,
    vars: &BTreeMap<String, String>,
    source: &str,
) -> Result<String> {
    let mut out = String::with_capacity(template.len());
    let mut rest = template;
    // 真の側を出力しているか。ネストのために積む
    let mut stack: Vec<bool> = Vec::new();

    while let Some(i) = rest.find("{{") {
        let Some(end_rel) = rest[i + 2..].find("}}") else {
            break;
        };
        let directive = rest[i + 2..i + 2 + end_rel].trim();
        let before = &rest[..i];
        let after = &rest[i + 2 + end_rel + 2..];

        let keeping = stack.iter().all(|k| *k);
        if keeping {
            out.push_str(before);
        }

        if let Some(cond) = directive.strip_prefix("if ") {
            stack.push(evaluate(cond.trim(), vars, source)?);
            trim_line(&out, after, &mut rest);
            continue;
        }
        if directive == "else" {
            let Some(top) = stack.pop() else {
                bail!("{source}: `else` without `if`");
            };
            stack.push(!top);
            trim_line(&out, after, &mut rest);
            continue;
        }
        if directive == "end" {
            if stack.pop().is_none() {
                bail!("{source}: `end` without `if`");
            }
            trim_line(&out, after, &mut rest);
            continue;
        }

        // 条件でないものはそのまま残す。値の置換は次の段でやる
        if keeping {
            out.push_str(&rest[i..i + 2 + end_rel + 2]);
        }
        rest = after;
    }

    if !stack.is_empty() {
        bail!("{source}: unterminated `if`");
    }
    if stack.iter().all(|k| *k) {
        out.push_str(rest);
    }
    Ok(out)
}

/// ディレクティブだけの行は行ごと消す。残すと空行が増える。
fn trim_line<'a>(out: &str, after: &'a str, rest: &mut &'a str) {
    if out.ends_with('\n') || out.is_empty() {
        *rest = after.strip_prefix('\n').unwrap_or(after);
    } else {
        *rest = after;
    }
}

fn evaluate(cond: &str, vars: &BTreeMap<String, String>, source: &str) -> Result<bool> {
    for (op, negate) in [("==", false), ("!=", true)] {
        if let Some((l, r)) = cond.split_once(op) {
            let l = resolve(l.trim(), vars, source)?;
            let r = resolve(r.trim(), vars, source)?;
            return Ok((l == r) != negate);
        }
    }
    // 単体なら「空でなければ真」
    Ok(!resolve(cond, vars, source)?.is_empty())
}

fn resolve(token: &str, vars: &BTreeMap<String, String>, source: &str) -> Result<String> {
    if (token.starts_with('"') && token.ends_with('"') && token.len() >= 2)
        || (token.starts_with('\'') && token.ends_with('\'') && token.len() >= 2)
    {
        return Ok(token[1..token.len() - 1].to_string());
    }
    match vars.get(token) {
        Some(v) => Ok(v.clone()),
        None => bail!("{source}: unknown variable `{token}` in a condition"),
    }
}

pub fn expand_with(
    template: &str,
    vars: &BTreeMap<String, String>,
    source: &str,
    secrets: &mut SecretCache,
) -> Result<String> {
    let template = strip_conditionals(template, vars, source)?;
    let template = template.as_str();

    let mut out = String::with_capacity(template.len());
    let mut rest = template;

    while let Some(start) = rest.find("{{") {
        out.push_str(&rest[..start]);
        let after = &rest[start + 2..];
        let Some(end) = after.find("}}") else {
            bail!("{source}: unterminated `{{{{`");
        };
        let key = after[..end].trim();
        if let Some((scheme, reference)) = split_reference(key) {
            out.push_str(&secrets.read(scheme, reference)?);
        } else {
            match vars.get(key) {
                Some(v) => out.push_str(v),
                None => bail!("{source}: unknown template variable `{key}`"),
            }
        }
        rest = &after[end + 2..];
    }
    out.push_str(rest);
    Ok(out)
}

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

    /// 秘密を使わないテンプレートの展開。テストは 1Password を叩かない。
    fn expand_with_test(
        template: &str,
        vars: &BTreeMap<String, String>,
        source: &str,
    ) -> Result<String> {
        expand_with(template, vars, source, &mut SecretCache::default())
    }

    fn vars() -> BTreeMap<String, String> {
        let mut v = BTreeMap::new();
        v.insert("ui.bg".into(), "#1a1b26".into());
        v.insert("normal.red".into(), "#f7768e".into());
        v
    }

    #[test]
    fn expands_known_variables() {
        let out = expand_with_test("bg = \"{{ ui.bg }}\"", &vars(), "t").unwrap();
        assert_eq!(out, "bg = \"#1a1b26\"");
    }

    #[test]
    fn expands_multiple_occurrences() {
        let out =
            expand_with_test("{{ ui.bg }}/{{ normal.red }}/{{ ui.bg }}", &vars(), "t").unwrap();
        assert_eq!(out, "#1a1b26/#f7768e/#1a1b26");
    }

    #[test]
    fn leaves_text_without_placeholders_untouched() {
        let src = "no placeholders here";
        assert_eq!(expand_with_test(src, &vars(), "t").unwrap(), src);
    }

    #[test]
    fn tolerates_whitespace_in_placeholder() {
        assert_eq!(
            expand_with_test("{{ui.bg}}", &vars(), "t").unwrap(),
            "#1a1b26"
        );
        assert_eq!(
            expand_with_test("{{   ui.bg   }}", &vars(), "t").unwrap(),
            "#1a1b26"
        );
    }

    /// 未知の変数は黙って空文字にせず落とす。設定が壊れたまま配置されるのを防ぐ。
    #[test]
    fn unknown_variable_is_an_error() {
        let err = expand_with_test("{{ nope }}", &vars(), "t.tmpl").unwrap_err();
        assert!(err.to_string().contains("unknown template variable"));
        assert!(err.to_string().contains("t.tmpl"));
    }

    #[test]
    fn unterminated_placeholder_is_an_error() {
        assert!(expand_with_test("{{ ui.bg", &vars(), "t").is_err());
    }

    fn cond(t: &str) -> Result<String> {
        let mut v = vars();
        v.insert("sennit.os".into(), "darwin".into());
        v.insert("sennit.profile".into(), String::new());
        strip_conditionals(t, &v, "t")
    }

    #[test]
    fn keeps_the_true_branch() {
        let out = cond("{{ if sennit.os == \"darwin\" }}\nmac\n{{ end }}\n").unwrap();
        assert_eq!(out, "mac\n");
    }

    #[test]
    fn drops_the_false_branch() {
        let out = cond("{{ if sennit.os == \"linux\" }}\nlinux\n{{ end }}\n").unwrap();
        assert_eq!(out, "");
    }

    #[test]
    fn handles_else() {
        let out = cond("{{ if sennit.os == \"linux\" }}\na\n{{ else }}\nb\n{{ end }}\n").unwrap();
        assert_eq!(out, "b\n");
    }

    #[test]
    fn not_equal_works() {
        let out = cond("{{ if sennit.os != \"linux\" }}\nmac\n{{ end }}\n").unwrap();
        assert_eq!(out, "mac\n");
    }

    /// 単体の変数は「空でなければ真」。profile 未設定を素直に書けるように。
    #[test]
    fn a_bare_variable_is_true_when_not_empty() {
        assert_eq!(cond("{{ if sennit.os }}\nx\n{{ end }}\n").unwrap(), "x\n");
        assert_eq!(cond("{{ if sennit.profile }}\nx\n{{ end }}\n").unwrap(), "");
    }

    /// 設定ファイル側に [end] のようなリテラルがあっても壊さない。
    /// 見るのは {{ }} の中だけ。
    #[test]
    fn literal_text_resembling_directives_is_untouched() {
        let out = cond("[end]\nname = 1\n").unwrap();
        assert_eq!(out, "[end]\nname = 1\n");
    }

    #[test]
    fn nesting_works() {
        let out =
            cond("{{ if sennit.os == \"darwin\" }}\n{{ if sennit.os }}\ny\n{{ end }}\n{{ end }}\n")
                .unwrap();
        assert_eq!(out, "y\n");
    }

    #[test]
    fn unbalanced_blocks_are_errors() {
        assert!(cond("{{ if sennit.os }}\nx\n").is_err());
        assert!(cond("x\n{{ end }}\n").is_err());
        assert!(cond("{{ else }}\n").is_err());
    }

    /// 条件に出てくる未知の変数も黙って偽にしない。
    #[test]
    fn unknown_variable_in_a_condition_is_an_error() {
        assert!(cond("{{ if nope == \"x\" }}\ny\n{{ end }}\n").is_err());
    }

    /// op:// を含むかどうかで、初回セットアップで展開するかが変わる。
    #[test]
    fn detects_secret_references() {
        assert!(needs_secrets("token = {{ op://Vault/Item/field }}"));
        assert!(!needs_secrets("bg = {{ ui.bg }}"));
        assert!(!needs_secrets("no placeholders"));
    }

    /// 閉じていない {{ を秘密ありと誤判定しない。
    #[test]
    fn unterminated_placeholder_is_not_a_secret() {
        assert!(!needs_secrets("{{ op://Vault"));
    }

    #[test]
    fn flattens_nested_tables() {
        let toml_src = "[ui]\nbg = \"#111\"\n\n[normal]\nred = \"#f00\"\n";
        let value: toml::Value = toml::from_str(toml_src).unwrap();
        let mut out = BTreeMap::new();
        flatten(&value, String::new(), &mut out);
        assert_eq!(out.get("ui.bg").unwrap(), "#111");
        assert_eq!(out.get("normal.red").unwrap(), "#f00");
    }
}