~danyspin97/rinstall

ref: 2394e0aee48431682d51dd88394209ce645ebf56 rinstall/src/main.rs -rw-r--r-- 6.2 KiB
2394e0aeDanilo Spinella main: Update .packaging to .package 1 year, 3 months ago
                                                                                
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
mod config;
mod dirs;
mod install_entry;
mod install_target;
mod package;

use std::{env, fs, path::PathBuf};

use clap::Clap;
use color_eyre::eyre::{bail, ensure, Context, ContextCompat, Result};
use walkdir::WalkDir;
use xdg::BaseDirectories;

use config::Config;
use dirs::Dirs;
use install_target::InstallTarget;
use package::Package;

fn main() -> Result<()> {
    color_eyre::install()?;
    let opts = Config::parse();
    let dry_run = opts.dry_run;
    let root_install = !opts.user;
    let uid = unsafe { libc::getuid() };
    ensure!(
        dry_run || !root_install || uid == 0,
        "need either root privileges or --user flag"
    );

    let mut config = if root_install {
        Config::new_default_root()
    } else {
        Config::new_default_user()
    };

    let xdg = BaseDirectories::new().context("unable to initialize XDG Base Directories")?;

    let config_file = if let Some(config_file) = &opts.config {
        let config_file = PathBuf::from(config_file);
        ensure!(config_file.exists(), "config file does not exists");
        config_file
    } else if root_install {
        PathBuf::from("/etc/rinstall.yml")
    } else {
        xdg.place_config_file("rinstall.yml")?
    };
    if config_file.exists() {
        let config_from_file = serde_yaml::from_str(
            &fs::read_to_string(&config_file)
                .with_context(|| format!("unable to read file {:?}", config_file))?,
        )?;
        if root_install {
            config.merge_root_conf(config_from_file);
        } else {
            config.merge_user_conf(config_from_file);
        }
    }

    let package_dir = opts.package_dir.clone().map_or(
        env::current_dir().context("unable to get current directory")?,
        PathBuf::from,
    );
    let destdir = opts.destdir.clone();

    if root_install {
        config.merge_root_conf(opts);
        config.replace_root_placeholders();
    } else {
        config.merge_user_conf(opts);
        config
            .replace_user_placeholders(&xdg)
            .context("unable to sanitize user directories")?;
    }

    let dirs = Dirs::new(config).context("unable to create dirs")?;

    // Try root/install.yml and root/.package/install.yml files
    let install_spec = {
        let install_spec = package_dir.join("install.yml");
        if install_spec.exists() {
            install_spec
        } else {
            let install_spec = package_dir.join(".package").join("install.yml");
            if install_spec.exists() {
                install_spec
            } else {
                bail!("unable to find 'install.yml' file");
            }
        }
    };
    let program: Package = serde_yaml::from_str(
        &fs::read_to_string(&install_spec)
            .with_context(|| format!("unable to read file {:?}", install_spec))?,
    )?;

    program
        .targets(dirs)?
        .iter()
        .try_for_each(|install| -> Result<()> {
            let InstallTarget {
                source,
                destination,
            } = install;
            // handle destdir
            let destination = destdir.as_ref().map_or(destination.to_owned(), |destdir| {
                // join does not work when the argument (not the self) is an absolute path
                PathBuf::from({
                    let mut s = destdir.clone();
                    s.push_str(destination.as_os_str().to_str().unwrap());
                    s
                })
            });

            let source_path = package_dir.join(source);

            ensure!(source_path.exists(), "{:?} does not exists", source);

            if source_path.is_file() {
                let destination = if destination.as_os_str().to_str().unwrap().ends_with('/') {
                    destination.join(
                        source
                            .file_name()
                            .with_context(|| format!("unable to get filename for {:?}", source))?,
                    )
                } else {
                    destination.to_owned()
                };
                println!("Installing {:?} to {:?}", source, destination);
                if !dry_run {
                    fs::create_dir_all(&destination.parent().unwrap()).with_context(|| {
                        format!("unable to create directory {:?}", destination.parent())
                    })?;
                    fs::copy(source_path, &destination).with_context(|| {
                        format!("unable to copy file {:?} to {:?}", source, destination)
                    })?;
                }
            } else if source_path.is_dir() {
                WalkDir::new(&source_path)
                    .into_iter()
                    .try_for_each(|entry| -> Result<()> {
                        let entry = entry?;
                        if !entry.file_type().is_file() {
                            return Ok(());
                        }

                        let full_path = entry.path();
                        let relative_path =
                            full_path.strip_prefix(&source_path).with_context(|| {
                                format!(
                                    "unable to strip prefix {:?} from {:?}",
                                    source_path, full_path
                                )
                            })?;
                        let source = source.join(relative_path);
                        let destination = destination.join(relative_path);
                        println!("Installing {:?} to {:?}", source, destination);
                        if dry_run {
                            return Ok(());
                        }

                        fs::create_dir_all(destination.parent().unwrap()).with_context(|| {
                            format!("unable to create directory {:?}", destination.parent())
                        })?;
                        fs::copy(full_path, &destination).with_context(|| {
                            format!("unable to copy file {:?} to {:?}", full_path, destination)
                        })?;

                        Ok(())
                    })?;
            } else {
                bail!("{:?} is neither a file nor a directory", source);
            }

            Ok(())
        })?;

    Ok(())
}