envoluntary 0.1.4

Automatic Nix development environments for your shell
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
use std::{env, fs, os::unix::fs::PermissionsExt, process};

use assert_cmd::{Command, cargo};
use env_hooks::{BashSource, EnvVars, get_env_vars_from_bash};
use predicates::prelude::*;
use sha1::{Digest, Sha1};

#[test]
fn shell_hook_bash_produces_evaluable_shell_syntax() {
    let mut cmd = Command::new(cargo::cargo_bin!());
    cmd.args(["shell", "hook", "bash"]);

    let export_output = cmd.output().unwrap();
    assert!(export_output.status.success());

    let bash_script = String::from_utf8_lossy(&export_output.stdout);

    assert!(!bash_script.contains("{{."));

    let bash_export = process::Command::new("bash")
        .arg("-c")
        .arg(bash_script.as_ref())
        .output()
        .unwrap();

    assert!(bash_export.status.success());
}

#[test]
fn shell_print_cache_path_outputs_valid_path() {
    let cache_dir = tempfile::tempdir().unwrap();

    let flake_reference = "github:owner/repo";

    let mut cmd = Command::new(cargo::cargo_bin!());
    cmd.args([
        "shell",
        "print-cache-path",
        "--flake-reference",
        flake_reference,
        "--cache-dir",
        &cache_dir.path().to_string_lossy(),
    ]);

    cmd.assert().success().stdout(predicate::eq(
        cache_dir
            .path()
            .join(format!("{:x}\n", Sha1::digest(flake_reference)))
            .to_string_lossy(),
    ));
}

#[test]
fn shell_export_with_empty_config_and_no_flake_references() {
    let work_dir = tempfile::tempdir().unwrap();
    let bin_dir = work_dir.path().join("bin");
    fs::create_dir(&bin_dir).unwrap();
    let nix_file = bin_dir.join("nix");

    let bash_path = env::var("NIX_BIN_BASH").unwrap_or_else(|_| String::from("/bin/bash"));
    let nix_file_content = format!(
        r#"#! {bash_path}

if [[ "$@" == "--extra-experimental-features nix-command flakes --version" ]]; then
  echo "nix (Nix) 2.30.0"
fi

exit 0
"#
    );
    fs::write(&nix_file, nix_file_content).unwrap();
    fs::set_permissions(&nix_file, fs::Permissions::from_mode(0o755)).unwrap();

    let original_path = env::var("PATH").unwrap_or_default();
    let new_path = format!("{}:{}", bin_dir.display(), original_path);

    let mut cmd = Command::new(cargo::cargo_bin!());
    cmd.args(["shell", "export", "bash"]).env("PATH", new_path);

    cmd.assert().success().stdout(predicate::eq(""));
}

#[test]
fn test_shell_export_state_init_update_and_reset() {
    let work_dir = tempfile::tempdir().unwrap();
    let cache_dir = tempfile::tempdir_in(work_dir.path()).unwrap();
    let config_file = work_dir.path().join("config.toml");
    fs::write(
        &config_file,
        toml::to_string_pretty(&toml::toml! {
            [[entries]]
            pattern = "^/some/dir(/.*)?"
            flake_reference = "github:owner/repo"

            [[entries]]
            pattern = "~/some/other/dir(/.*)?"
            flake_reference = "github:other_github_owner/repo"

            [[entries]]
            pattern = ".*"
            flake_reference = "github:owner/super_cool_tool"
            pattern_adjacent = ".*/\\.supercooltool"

            [[entries]]
            pattern = ".*"
            flake_reference = "github:owner/awesome_tool"
            pattern_adjacent = "~/\\.awesometool"
        })
        .unwrap(),
    )
    .unwrap();
    let bin_dir = work_dir.path().join("bin");
    fs::create_dir(&bin_dir).unwrap();
    let nix_file = bin_dir.join("nix");

    let bash_path = env::var("NIX_BIN_BASH").unwrap_or_else(|_| String::from("/bin/bash"));
    let profile_rc_content = "export FAKE_VAR=true;";
    let nix_file_content = format!(
        r#"#! {bash_path}

if [[ "$@" == "--extra-experimental-features nix-command flakes --version" ]]; then
    echo "nix (Nix) 2.30.0"
elif [[ "$@" == "--extra-experimental-features nix-command flakes print-dev-env --no-write-lock-file --profile "* ]]; then
rc="{profile_rc_content}"
for ((i=0; i<$#; i++)); do
    if [[ "${{@:$i:1}}" == "--profile" ]]; then
        profile_path="${{@:$((i+1)):1}}"
        echo "$rc" > "$profile_path"
        break
    fi
done
echo "$rc"
elif [[ "$@" == "--extra-experimental-features nix-command flakes build --out-link "* ]]; then
for ((i=0; i<$#; i++)); do
    if [[ "${{@:$i:1}}" == "--out-link" ]]; then
        link_path="${{@:$((i+1)):1}}"
        installable="${{@:$((i+2)):1}}"
        mkdir -p "$(dirname "$link_path")"
        ln -sf "$installable" "$link_path"
        break
    fi
done
elif [[ "$@" == "--extra-experimental-features nix-command flakes flake archive --json --no-write-lock-file "* ]]; then
echo '{{ "inputs": {{ "nixpkgs": {{ "inputs": {{}}, "path": "/nix/store/yfzmnk75f009yb7b542kf4r7qaqq9kid-source" }} }} }}'
fi

exit 0
"#
    );
    fs::write(&nix_file, nix_file_content).unwrap();
    fs::set_permissions(&nix_file, fs::Permissions::from_mode(0o755)).unwrap();

    let original_path = env::var("PATH").unwrap_or_default();
    let new_path = format!("{}:{}", bin_dir.display(), original_path);

    {
        let mut cmd = Command::new(cargo::cargo_bin!());
        cmd.args([
            "shell",
            "export",
            "bash",
            "--config-path",
            &config_file.to_string_lossy(),
            "--cache-dir",
            &cache_dir.path().to_string_lossy(),
            "--current-dir",
            "/no-match-path",
        ])
        .env("PATH", &new_path)
        .env("HOME", "/home");

        let no_match_output = cmd.output().unwrap();

        assert!(no_match_output.status.success());

        let no_match_shell_export = String::from_utf8_lossy(&no_match_output.stdout);

        assert_eq!(no_match_shell_export, "");
    }

    let initial_shell_export = {
        let mut cmd = Command::new(cargo::cargo_bin!());
        cmd.args([
            "shell",
            "export",
            "bash",
            "--config-path",
            &config_file.to_string_lossy(),
            "--cache-dir",
            &cache_dir.path().to_string_lossy(),
            "--current-dir",
            "/some/dir",
        ])
        .env("PATH", &new_path)
        .env("HOME", "/home");

        let initial_output = cmd.output().unwrap();

        assert!(initial_output.status.success());

        String::from(String::from_utf8_lossy(&initial_output.stdout))
    };

    assert_eq!(
        initial_shell_export
            .split('\n')
            .filter(|s| !s.is_empty())
            .collect::<Vec<_>>(),
        vec![
            "export FAKE_VAR=true;",
            "export ENVOLUNTARY_ENV_STATE=KLUv/QQ4dQMArAYAeyJmbGFrZV9yZWZlcmVuY2VzIjpbImdpdGh1Yjpvd25lci9yZXBvIl0sImVudl92YXJzX3Jlc2V0Ijp7IkZBS0VfVkFSIjpudWxsLCJFTlZPTFVOVEFSWV9FTlZfU1RBVEUiOm51bGx9fQCbvTM7;",
        ]
    );

    let update_shell_export = {
        let initial_env_vars = get_env_vars_from_bash(
            BashSource::Script(initial_shell_export.into()),
            Some(EnvVars::from_iter([("PATH".to_string(), new_path.clone())])),
        )
        .unwrap();
        let mut cmd = Command::new(cargo::cargo_bin!());
        cmd.args([
            "shell",
            "export",
            "bash",
            "--config-path",
            &config_file.to_string_lossy(),
            "--cache-dir",
            &cache_dir.path().to_string_lossy(),
            "--current-dir",
            "/home/some/other/dir",
        ])
        .env("PATH", &new_path)
        .env("HOME", "/home")
        .envs(initial_env_vars.iter());

        let update_output = cmd.output().unwrap();

        assert!(update_output.status.success());

        String::from(String::from_utf8_lossy(&update_output.stdout))
    };

    assert_eq!(
        update_shell_export
            .split('\n')
            .filter(|s| !s.is_empty())
            .collect::<Vec<_>>(),
        vec![
            "unset FAKE_VAR;",
            "unset ENVOLUNTARY_ENV_STATE;",
            "export FAKE_VAR=true;",
            "export ENVOLUNTARY_ENV_STATE=$'KLUv/QQ4HQQAHAcAeyJmbGFrZV9yZWZlcmVuY2VzIjpbImdpdGh1YjpvdGhlcl9fb3duZXIvcmVwbyJdLCJlbnZfdmFyc19yZXNldCI6eyJGQUtFX1ZBUiI6bnVsbCwiRU5WT0xVTlRBUllfRU5WX1NUQVRFIjpudWxsfX0BqBDj//0Qww8Qow+DMUZWbCwq';"
        ]
    );

    let update_env_vars = get_env_vars_from_bash(
        BashSource::Script(update_shell_export.into()),
        Some(EnvVars::from_iter([("PATH".to_string(), new_path.clone())])),
    )
    .unwrap();

    {
        let mut cmd = Command::new(cargo::cargo_bin!());
        cmd.args([
            "shell",
            "export",
            "bash",
            "--config-path",
            &config_file.to_string_lossy(),
            "--cache-dir",
            &cache_dir.path().to_string_lossy(),
            "--current-dir",
            "/home/some/other/dir",
        ])
        .env("PATH", &new_path)
        .env("HOME", "/home")
        .envs(update_env_vars.iter());

        let no_update_output = cmd.output().unwrap();

        assert!(no_update_output.status.success());

        let no_update_shell_export =
            String::from(String::from_utf8_lossy(&no_update_output.stdout));

        assert_eq!(no_update_shell_export, "");
    }

    let reset_shell_export = {
        let mut cmd = Command::new(cargo::cargo_bin!());
        cmd.args([
            "shell",
            "export",
            "bash",
            "--config-path",
            &config_file.to_string_lossy(),
            "--cache-dir",
            &cache_dir.path().to_string_lossy(),
            "--current-dir",
            "/",
        ])
        .env("PATH", &new_path)
        .env("HOME", "/home")
        .envs(update_env_vars.iter());

        let reset_output = cmd.output().unwrap();

        assert!(reset_output.status.success());

        String::from(String::from_utf8_lossy(&reset_output.stdout))
    };

    assert_eq!(
        reset_shell_export
            .split('\n')
            .filter(|s| !s.is_empty())
            .collect::<Vec<_>>(),
        vec!["unset FAKE_VAR;", "unset ENVOLUNTARY_ENV_STATE;"]
    );

    {
        let mut cmd = Command::new(cargo::cargo_bin!());
        cmd.args([
            "shell",
            "export",
            "bash",
            "--config-path",
            &config_file.to_string_lossy(),
            "--cache-dir",
            &cache_dir.path().to_string_lossy(),
            "--current-dir",
            &bin_dir.to_string_lossy(),
        ])
        .env("PATH", &new_path)
        .env("HOME", "/home");

        // nothing matching the pattern adjacent yet
        let pattern_adjacent_no_match_output =
            String::from(String::from_utf8_lossy(&cmd.output().unwrap().stdout));
        assert_eq!(pattern_adjacent_no_match_output, "");

        // create a file that matches the pattern adjacent, in the parent directory
        let supercooltool_file = work_dir.path().join(".supercooltool");
        fs::File::create_new(supercooltool_file).unwrap();

        let pattern_adjacent_output = cmd.output().unwrap();

        assert!(pattern_adjacent_output.status.success());

        let pattern_adjacent_export =
            String::from(String::from_utf8_lossy(&pattern_adjacent_output.stdout));

        assert_eq!(
            pattern_adjacent_export
                .split('\n')
                .filter(|s| !s.is_empty())
                .collect::<Vec<_>>(),
            vec![
                "export FAKE_VAR=true;",
                "export ENVOLUNTARY_ENV_STATE=$'KLUv/QQ4zQMAXAcAeyJmbGFrZV9yZWZlcmVuY2VzIjpbImdpdGh1Yjpvd25lci9zdXBlcl9jb29sX3Rvb2wiXSwiZW52X3ZhcnNfcmVzZXQiOnsiRkFLRV9WQVIiOm51bGwsIkVOVk9MVU5UQVJZX0VOVl9TVEFURSI6bnVsbH19ACCjTjk=';",
            ]
        );
    }

    {
        let home_dir = tempfile::tempdir().unwrap();
        let mut cmd = Command::new(cargo::cargo_bin!());
        cmd.args([
            "shell",
            "export",
            "bash",
            "--config-path",
            &config_file.to_string_lossy(),
            "--cache-dir",
            &cache_dir.path().to_string_lossy(),
            "--current-dir",
            &home_dir.path().to_string_lossy(),
        ])
        .env("PATH", &new_path)
        .env("HOME", home_dir.path());

        let awesometool_file = home_dir.path().join(".awesometool");
        fs::File::create_new(awesometool_file).unwrap();

        let pattern_adjacent_home_dir_output = cmd.output().unwrap();

        assert!(pattern_adjacent_home_dir_output.status.success());

        let pattern_adjacent_home_dir_export = String::from(String::from_utf8_lossy(
            &pattern_adjacent_home_dir_output.stdout,
        ));

        assert_eq!(
            pattern_adjacent_home_dir_export
                .split('\n')
                .filter(|s| !s.is_empty())
                .collect::<Vec<_>>(),
            vec![
                "export FAKE_VAR=true;",
                "export ENVOLUNTARY_ENV_STATE=$'KLUv/QQ4tQMALAcAeyJmbGFrZV9yZWZlcmVuY2VzIjpbImdpdGh1Yjpvd25lci9hd2Vzb21lX3Rvb2wiXSwiZW52X3ZhcnNfcmVzZXQiOnsiRkFLRV9WQVIiOm51bGwsIkVOVk9MVU5UQVJZX0VOVl9TVEFURSI6bnVsbH19AB6hxkc=';",
            ]
        );
    }
}