dotter 0.13.4

A dotfile manager and templater written in rust
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
use anyhow::{Context as AnyhowContext, Result};

use handlebars::{
    Context, Handlebars, Helper, HelperResult, Output, RenderContext, RenderErrorReason,
};
use toml::value::{Table, Value};

use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::process::{Command, Stdio};

#[cfg(feature = "scripting")]
use crate::config::Helpers;
use crate::config::{Configuration, Files, Variables};

pub fn create_new_handlebars<'b>(config: &mut Configuration) -> Result<Handlebars<'b>> {
    debug!("Creating Handlebars instance...");
    let mut handlebars = Handlebars::new();
    handlebars.register_escape_fn(str::to_string); // Disable html-escaping
    handlebars.set_strict_mode(true); // Report missing variables as errors
    register_rust_helpers(&mut handlebars);

    #[cfg(feature = "scripting")]
    register_script_helpers(&mut handlebars, &config.helpers);

    add_dotter_variable(&mut config.variables, &config.files, &config.packages);
    filter_files_condition(&handlebars, &config.variables, &mut config.files)
        .context("filter files based on `if` field")?;
    trace!("Handlebars instance: {:#?}", handlebars);
    Ok(handlebars)
}

fn filter_files_condition(
    handlebars: &Handlebars<'_>,
    variables: &Variables,
    files: &mut Files,
) -> Result<()> {
    let filtered = std::mem::take(files)
        .into_iter()
        .map(|(source, target)| -> Result<Option<_>> {
            let condition = target.condition();
            Ok(if let Some(condition) = condition {
                if eval_condition(handlebars, variables, condition).context("")? {
                    Some((source, target))
                } else {
                    None
                }
            } else {
                Some((source, target))
            })
        })
        .collect::<Result<BTreeSet<Option<(PathBuf, _)>>>>()?
        .into_iter()
        .flatten()
        .collect();
    *files = filtered;
    Ok(())
}

fn eval_condition(
    handlebars: &Handlebars<'_>,
    variables: &Variables,
    condition: &str,
) -> Result<bool> {
    // extra { for format!()
    let condition = format!("{{{{#if {condition} }}}}true{{{{/if}}}}");
    let rendered = handlebars
        .render_template(&condition, variables)
        .context("")?;
    Ok(rendered == "true")
}

fn math_helper(
    h: &Helper<'_>,
    _: &Handlebars<'_>,
    _: &Context,
    _: &mut RenderContext<'_, '_>,
    out: &mut dyn Output,
) -> HelperResult {
    let params = h
        .params()
        .iter()
        .map(|p| p.render())
        .collect::<Vec<String>>();
    let expression = params.join(" ");

    out.write(
        &evalexpr::eval(&expression)
            .map_err(|e| {
                RenderErrorReason::Other(format!(
                    "Cannot evaluate expression {expression} because {e}"
                ))
            })?
            .to_string(),
    )?;
    Ok(())
}

fn include_template_helper(
    h: &Helper<'_>,
    handlebars: &Handlebars<'_>,
    ctx: &Context,
    rc: &mut RenderContext<'_, '_>,
    out: &mut dyn Output,
) -> HelperResult {
    let mut params = h.params().iter();
    let path = params
        .next()
        .ok_or(RenderErrorReason::ParamNotFoundForIndex(
            "include_template",
            0,
        ))?
        .render();
    if params.next().is_some() {
        return Err(RenderErrorReason::Other(
            "include_template: More than one parameter given".to_owned(),
        )
        .into());
    }

    let included_file =
        std::fs::read_to_string(path).map_err(|e| RenderErrorReason::NestedError(Box::new(e)))?;
    let rendered_file = handlebars
        .render_template_with_context(&included_file, rc.context().as_deref().unwrap_or(ctx))
        .map_err(|e| RenderErrorReason::NestedError(Box::new(e)))?;

    out.write(&rendered_file)?;

    Ok(())
}

fn is_executable_helper(
    h: &Helper<'_>,
    _: &Handlebars<'_>,
    _: &Context,
    _: &mut RenderContext<'_, '_>,
    out: &mut dyn Output,
) -> HelperResult {
    let mut params = h.params().iter();
    let executable = params
        .next()
        .ok_or(RenderErrorReason::ParamNotFoundForIndex("is_executable", 0))?
        .render();
    if params.next().is_some() {
        return Err(RenderErrorReason::Other(
            "is_executable: More than one parameter given".to_owned(),
        )
        .into());
    }

    let status = is_executable(&executable)
        .map_err(|e| RenderErrorReason::Other(format!("failed to run is_executable: {e}")))?;
    if status {
        out.write("true")?;
    }
    // writing anything other than an empty string is considered truthy

    Ok(())
}

fn command_success_helper(
    h: &Helper<'_>,
    _: &Handlebars<'_>,
    _: &Context,
    _: &mut RenderContext<'_, '_>,
    out: &mut dyn Output,
) -> HelperResult {
    let mut params = h.params().iter();
    let command = params
        .next()
        .ok_or(RenderErrorReason::ParamNotFoundForIndex(
            "command_success",
            0,
        ))?
        .render();
    if params.next().is_some() {
        return Err(RenderErrorReason::Other(
            "command_success: More than one parameter given".to_owned(),
        )
        .into());
    }

    let status = os_shell()
        .arg(&command)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()?
        .success();
    if status {
        out.write("true")?;
    }
    // writing anything other than an empty string is considered truthy

    Ok(())
}

fn command_output_helper(
    h: &Helper<'_>,
    _: &Handlebars<'_>,
    _: &Context,
    _: &mut RenderContext<'_, '_>,
    out: &mut dyn Output,
) -> HelperResult {
    let mut params = h.params().iter();
    let command = params
        .next()
        .ok_or(RenderErrorReason::ParamNotFoundForIndex(
            "command_success",
            0,
        ))?
        .render();
    if params.next().is_some() {
        return Err(RenderErrorReason::Other(
            "command_success: More than one parameter given".to_owned(),
        )
        .into());
    }

    let output = os_shell()
        .arg(&command)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        // .stderr(Stdio::piped()) - probably not wanted
        .output()?;
    out.write(&String::from_utf8_lossy(&output.stdout))?;
    // writing anything other than an empty string is considered truthy

    Ok(())
}

#[cfg(windows)]
fn is_executable(name: &str) -> Result<bool> {
    let name = if name.ends_with(".exe") {
        name.to_string()
    } else {
        format!("{}.exe", name)
    };

    Command::new("where")
        .arg(name)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .context("run `where` command")
}

#[cfg(unix)]
fn is_executable(name: &str) -> Result<bool> {
    Command::new("which")
        .arg(name)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .context("run `which` command")
}

#[cfg(windows)]
fn os_shell() -> Command {
    let mut cmd = Command::new("cmd");
    cmd.arg("/C");
    cmd
}

#[cfg(unix)]
fn os_shell() -> Command {
    let mut cmd = Command::new("sh");
    cmd.arg("-c");
    cmd
}

fn register_rust_helpers(handlebars: &mut Handlebars<'_>) {
    handlebars_misc_helpers::register(handlebars);
    handlebars.register_helper("math", Box::new(math_helper));

    handlebars.register_helper("include_template", Box::new(include_template_helper));
    handlebars.register_helper("is_executable", Box::new(is_executable_helper));
    handlebars.register_helper("command_success", Box::new(command_success_helper));
    handlebars.register_helper("command_output", Box::new(command_output_helper));
}

#[cfg(feature = "scripting")]
fn register_script_helpers(handlebars: &mut Handlebars<'_>, helpers: &Helpers) {
    debug!("Registering script helpers...");
    for (helper_name, helper_path) in helpers {
        if let Err(e) = handlebars.register_script_helper_file(helper_name, helper_path) {
            warn!(
                "Coudln't register helper script {} at path {:?} because {}",
                helper_name, helper_path, e
            );
        }
    }
}

fn files_as_toml(files: &Files) -> Value {
    Value::Table(
        files
            .iter()
            .map(|(source, target)| {
                (
                    source.to_string_lossy().to_string(),
                    target.path().to_string_lossy().to_string().into(),
                )
            })
            .collect(),
    )
}

fn add_dotter_variable(
    variables: &mut Variables,
    files: &Files,
    packages: &BTreeMap<String, bool>,
) {
    let mut dotter = Table::new();
    dotter.insert(
        "packages".into(),
        Value::Table(
            packages
                .iter()
                .map(|(p, e)| (p.to_string(), Value::Boolean(*e)))
                .collect(),
        ),
    );
    dotter.insert("files".into(), files_as_toml(files));
    dotter.insert(
        "os".into(),
        (if cfg!(windows) { "windows" } else { "unix" }).into(),
    );

    // New better way
    dotter.insert("unix".into(), Value::Boolean(cfg!(unix)));
    dotter.insert(
        "windows".into(),
        Value::Boolean(cfg!(target_os = "windows")),
    );
    dotter.insert("linux".into(), Value::Boolean(cfg!(target_os = "linux")));
    dotter.insert("macos".into(), Value::Boolean(cfg!(target_os = "macos")));

    dotter.insert(
        "current_dir".into(),
        Value::String(
            std::env::current_dir()
                .expect("get current dir")
                .to_string_lossy()
                .into(),
        ),
    );
    if let Ok(hostname) = hostname::get() {
        dotter.insert(
            "hostname".into(),
            Value::String(hostname.to_string_lossy().into()),
        );
    } else {
        warn!("Failed to get hostname, skipping dotter.hostname variable");
    }

    variables.insert("dotter".into(), dotter.into());
}

#[cfg(test)]
mod test {
    use crate::config::Settings;

    use super::*;

    #[test]
    fn eval_condition_simple() {
        let mut config = Configuration {
            files: Files::new(),
            variables: maplit::btreemap! { "foo".into() => 2.into() },
            #[cfg(feature = "scripting")]
            helpers: Helpers::new(),
            packages: maplit::btreemap! { "default".into() => true, "disabled".into() => false },
            recurse: true,
            settings: Settings::default(),
        };
        let handlebars = create_new_handlebars(&mut config).unwrap();

        assert!(eval_condition(&handlebars, &config.variables, "foo").unwrap());
        assert!(!eval_condition(&handlebars, &config.variables, "bar").unwrap());
        assert!(eval_condition(&handlebars, &config.variables, "dotter.packages.default").unwrap());
        assert!(
            !eval_condition(&handlebars, &config.variables, "dotter.packages.nonexist").unwrap()
        );
        assert!(!eval_condition(
            &handlebars,
            &config.variables,
            "(and true dotter.packages.disabled)"
        )
        .unwrap());
    }

    #[test]
    fn eval_condition_helpers() {
        let mut config = Configuration {
            files: Files::new(),
            variables: Variables::new(),
            #[cfg(feature = "scripting")]
            helpers: Helpers::new(),
            packages: BTreeMap::new(),
            recurse: true,
            settings: Settings::default(),
        };
        let handlebars = create_new_handlebars(&mut config).unwrap();

        assert!(!eval_condition(
            &handlebars,
            &config.variables,
            "(is_executable \"no_such_executable_please\")"
        )
        .unwrap());
        assert!(
            eval_condition(&handlebars, &config.variables, "(eq (math \"5+5\") \"10\")").unwrap()
        );
    }
}