-
Notifications
You must be signed in to change notification settings - Fork 1
/
shim.rs
90 lines (72 loc) · 2.11 KB
/
shim.rs
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
use std::fs;
use std::fs::File;
use std::io;
use std::path::PathBuf;
use crate::utils::paths::*;
use crate::utils::script::*;
use super::shells::SupportedShell;
pub fn get_func_name(func: &str) -> Result<String, Box<dyn std::error::Error>> {
Ok(get_file_name(func)?)
}
pub fn get_shim_content(
current_shell: &SupportedShell,
func: &str,
bin_dir: &str,
env: Option<&str>,
) -> Result<String, Box<dyn std::error::Error>> {
match env {
None => get_basic_shim(current_shell, func, bin_dir),
Some("base") => get_basic_shim(current_shell, func, bin_dir),
Some(&_) => get_basic_shim(current_shell, func, bin_dir),
}
}
pub fn get_basic_shim(
current_shell: &SupportedShell,
func: &str,
bin_dir: &str,
) -> Result<String, Box<dyn std::error::Error>> {
let func_name = get_func_name(func)?;
let resolved_bin_path = resolve_single_path(bin_dir)?;
// set exec mode
run_cmd(
current_shell,
&format!("chmod +x {}", &resolved_bin_path.display().to_string()),
)?;
let bin_dir = get_dir(&resolved_bin_path)?.display().to_string();
Ok(format!(
r##"
#!/bin/sh
{internal_func}() {{
local bindir="{bin_dir}"
local PATH="$bindir":"$PATH"
"$bindir"/"{func}" "$@"
}}
{internal_func} "$@"
"##,
func = func_name,
internal_func = func_name.replace("-", "_"),
bin_dir = bin_dir
))
}
fn get_shim_path(cmd: &str) -> Result<PathBuf, Box<dyn std::error::Error>> {
Ok(get_bin_file_path(&get_func_name(&cmd)?)?)
}
pub fn create_shim(
current_shell: &SupportedShell,
cmd: &str,
shim_content: &str,
) -> Result<(), Box<dyn std::error::Error>> {
fs::create_dir_all(&get_bin_dir_path()?)?;
let shim_path = get_shim_path(&cmd)?;
let mut dest = File::create(&shim_path)?;
io::copy(&mut shim_content.as_bytes(), &mut dest)?;
// set shim mode
run_cmd(
current_shell,
&format!("chmod +x {}", &shim_path.display().to_string()),
)?;
Ok(())
}
pub fn remove_shim(cmd: &str) -> Result<(), Box<dyn std::error::Error>> {
Ok(fs::remove_file(get_shim_path(&cmd)?)?)
}