summaryrefslogtreecommitdiff
path: root/src/pkgtoolkit/install.rs
blob: 65476d95647fa54fe61df10f12cbf6a521c15f7c (plain)
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
use crate::cfg::config::Config;
use std::{
    fs::{self, Permissions, create_dir_all, set_permissions},
    os::unix::fs::PermissionsExt,
    path::{Path, StripPrefixError},
    process::Command,
};

use toml;

use super::archive::ArchiveOperations;
use super::build::BuildOperations;
use super::types::{Package, PackageManifest};

pub trait InstallOperations {
    fn collect_files_from_dir(root: &Path, base: &Path) -> Result<Vec<String>, std::io::Error>;
    fn install(&mut self) -> Result<bool, std::io::Error>;
    fn uninstall(&self) -> Result<bool, std::io::Error>;
    fn load_manifest(&self) -> Result<PackageManifest, std::io::Error>;
    fn list_installed_packages() -> Result<Vec<PackageManifest>, std::io::Error>;
    fn is_installed(&self) -> Result<bool, std::io::Error>;
}

impl InstallOperations for Package {
    /// Recursively collects all files from a directory and its subdirectories
    /// and returns them as a vector of strings.
    ///
    /// # Arguments
    ///
    /// * `root`: The root directory from which to collect files.
    /// * `base`: The base directory from which to strip the prefix from the file paths.
    ///
    /// # Returns
    ///
    /// A vector of strings containing the file paths relative to the `base` directory.
    fn collect_files_from_dir(root: &Path, base: &Path) -> Result<Vec<String>, std::io::Error> {
        let mut files = Vec::new();
        for entry in fs::read_dir(root)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                files.extend(Self::collect_files_from_dir(&path, base)?);
            } else {
                let rel_path = path
                    .strip_prefix(base)
                    .map_err(|e: StripPrefixError| {
                        std::io::Error::new(std::io::ErrorKind::InvalidData, e)
                    })?
                    .to_string_lossy()
                    .to_string();
                files.push(rel_path);
            }
        }
        Ok(files)
    }

    /// Installs the package according to the INSTALL file in the archive.
    ///
    /// There are two strategies for installing the package. If the BUILD file is empty, the package is assumed to be a binary package and the default install hook is skipped. If the BUILD file is not empty, the package is assumed to be a source package and the default build hook is skipped.
    ///
    /// If the BUILD file is empty and the INSTALL file contains a custom script, the custom script is run instead of the default install hook.
    /// If the BUILD file is not empty and the INSTALL file contains a custom script, the custom script is ignored.
    ///
    /// # Errors
    ///
    /// Returns an error if the BUILD file is invalid or if the build or install hook fails.
    fn install(&mut self) -> Result<bool, std::io::Error> {
        let config = Config::parse().map_err(|e| std::io::Error::other(e.to_string()))?;
        let (install_meta, _setts_meta, build_meta) = Self::loadmeta(self)?;

        let installed_db = Path::new(&config.paths.installed_db);
        create_dir_all(installed_db)?;

        let mut all_files: Vec<String> = Vec::new();

        let is_build_present_and_not_empty = build_meta.is_some();

        if is_build_present_and_not_empty {
            log::info!(
                "Found BUILD file, preparing to build and install package: {}",
                self.name
            );
            let build_meta_ref = build_meta.as_ref().unwrap();
            if let Err(e) = self.execute_build(build_meta_ref) {
                return Err(std::io::Error::other(format!(
                    "Build failed during installation: {}",
                    e
                )));
            }

            let staging_dir = Path::new(&config.paths.cache_dir).join("staging");
            create_dir_all(&staging_dir)?;
            all_files = Self::collect_files_from_dir(&staging_dir, &staging_dir)?
                .iter()
                .map(|rel| format!("/{}", rel)) // Преобразуйте в абсолютные пути (предполагаем root=/)
                .collect();

            for file in &all_files {
                let src = staging_dir.join(file.trim_start_matches('/'));
                let dest = Path::new(file);

                // Check if source file exists
                if !src.exists() {
                    log::warn!("Source file not found: {:?}, skipping", src);
                    continue;
                }

                if let Some(parent) = dest.parent() {
                    create_dir_all(parent)?;
                }

                fs::copy(&src, dest).map_err(|e| {
                    std::io::Error::other(format!(
                        "Failed to copy {} to {}: {}",
                        src.display(),
                        dest.display(),
                        e
                    ))
                })?;
                // TODO: Set proper permissions
            }

            fs::remove_dir_all(&staging_dir)?;
        } else {
            log::info!(
                "No BUILD file or it's empty. Treating as binary package. Installing via INSTALL config or custom script."
            );

            // Validate custom script before execution
            if let Some(ref script) = install_meta.install.custom_script {
                Self::validate_custom_script(script)?;
            }

            if let Some(ref script) = install_meta.install.custom_script {
                log::info!(
                    "Executing custom install script for {}",
                    install_meta.package.name
                );
                let status = if script.starts_with("./") || script.contains('/') {
                    Command::new("/bin/sh").arg("-c").arg(script).status()
                } else {
                    Command::new(script).status()
                }
                .map_err(|e| {
                    std::io::Error::other(format!("Failed to run custom script: {}", e))
                })?;

                if !status.success() {
                    return Err(std::io::Error::other("Custom install script failed"));
                }

                log::warn!(
                    "Custom script used; file list may be incomplete. Add manual tracking if needed."
                );
            } else {
                log::info!(
                    "No custom script. Running default install hook for {}",
                    install_meta.package.name
                );
                let source_file_name = &self.name;
                let build_dir = Path::new(&config.paths.cache_dir)
                    .join(format!("{}-{}", self.name, self.version));
                let src_path = build_dir.join(source_file_name);
                let dest_path = Path::new(&install_meta.install.path);

                // Check if source file exists
                if !src_path.exists() {
                    return Err(std::io::Error::other(format!(
                        "Source binary file not found: {}",
                        src_path.display()
                    )));
                }

                if let Some(parent) = dest_path.parent() {
                    create_dir_all(parent).map_err(|e| {
                        std::io::Error::other(format!("Failed to create parent dir: {}", e))
                    })?;
                }

                fs::copy(&src_path, dest_path)
                    .map_err(|e| std::io::Error::other(format!("Failed to copy file: {}", e)))?;

                let mode = u32::from_str_radix(&install_meta.install.mode, 8).map_err(|_| {
                    std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "Invalid mode string in INSTALL",
                    )
                })?;
                let perms = Permissions::from_mode(mode);
                set_permissions(dest_path, perms).map_err(|e| {
                    std::io::Error::other(format!("Failed to set permissions: {}", e))
                })?;

                let output = Command::new("chown")
                    .arg(format!(
                        "{}:{}",
                        install_meta.install.user, install_meta.install.group
                    ))
                    .arg(dest_path)
                    .output()
                    .map_err(|e| std::io::Error::other(format!("'chown' command failed: {}", e)))?;

                if !output.status.success() {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    log::warn!(
                        "Warning: 'chown' command failed (requires root?):\n{}",
                        stderr
                    );
                }

                all_files = install_meta.files;
            }
        }

        let manifest = PackageManifest {
            name: self.name.clone(),
            version: self.version.clone(),
            all_files,
        };
        let manifest_path = installed_db.join(format!("{}-{}.toml", self.name, self.version));
        let manifest_toml =
            toml::to_string_pretty(&manifest).map_err(|e| std::io::Error::other(e.to_string()))?;
        fs::write(&manifest_path, manifest_toml)?;

        log::info!(
            "Package {} installed successfully. Manifest generated at {:?} with {} files tracked",
            self.name,
            manifest_path,
            manifest.all_files.len()
        );
        Ok(true)
    }

    /// Loads the package manifest from the installed database
    fn load_manifest(&self) -> Result<PackageManifest, std::io::Error> {
        let config = Config::parse().map_err(|e| std::io::Error::other(e.to_string()))?;
        let installed_db = Path::new(&config.paths.installed_db);
        let manifest_path = installed_db.join(format!("{}-{}.toml", self.name, self.version));

        if !manifest_path.exists() {
            return Err(std::io::Error::other(format!(
                "Package manifest not found: {:?}",
                manifest_path
            )));
        }

        let manifest_content = fs::read_to_string(&manifest_path)?;
        let manifest: PackageManifest = toml::from_str(&manifest_content)
            .map_err(|e| std::io::Error::other(format!("Failed to parse manifest: {}", e)))?;

        Ok(manifest)
    }

    /// Uninstalls the package by removing all files listed in the manifest
    /// and then removing the manifest file itself
    fn uninstall(&self) -> Result<bool, std::io::Error> {
        let manifest = self.load_manifest()?;

        log::info!(
            "Uninstalling package {}-{}",
            manifest.name,
            manifest.version
        );

        let mut removed_files = 0;
        let mut failed_removals = 0;

        for file_path in &manifest.all_files {
            let path = Path::new(file_path);

            if path.exists() {
                match fs::remove_file(path) {
                    Ok(()) => {
                        removed_files += 1;
                        log::debug!("Removed file: {:?}", path);
                    }
                    Err(e) => {
                        failed_removals += 1;
                        log::warn!("Failed to remove file {:?}: {}", path, e);
                    }
                }
            } else {
                log::debug!("File not found, skipping: {:?}", path);
            }
        }

        // Remove the manifest file
        let config = Config::parse().map_err(|e| std::io::Error::other(e.to_string()))?;
        let installed_db = Path::new(&config.paths.installed_db);
        let manifest_path = installed_db.join(format!("{}-{}.toml", self.name, self.version));

        if manifest_path.exists() {
            fs::remove_file(&manifest_path)?;
            log::info!("Removed manifest file: {:?}", manifest_path);
        }

        log::info!(
            "Package {}-{} uninstalled successfully. Removed {} files, {} failures",
            manifest.name,
            manifest.version,
            removed_files,
            failed_removals
        );

        Ok(failed_removals == 0)
    }

    /// Lists all installed packages by reading manifest files from the installed database
    fn list_installed_packages() -> Result<Vec<PackageManifest>, std::io::Error> {
        let config = Config::parse().map_err(|e| std::io::Error::other(e.to_string()))?;
        let installed_db = Path::new(&config.paths.installed_db);

        if !installed_db.exists() {
            return Ok(Vec::new());
        }

        let mut packages = Vec::new();

        for entry in fs::read_dir(installed_db)? {
            let entry = entry?;
            let path = entry.path();

            if path.extension().and_then(|s| s.to_str()) == Some("toml") {
                let manifest_content = fs::read_to_string(&path)?;
                let manifest: PackageManifest = toml::from_str(&manifest_content).map_err(|e| {
                    std::io::Error::other(format!("Failed to parse manifest {:?}: {}", path, e))
                })?;
                packages.push(manifest);
            }
        }

        Ok(packages)
    }

    /// Checks if the package is currently installed by looking for its manifest
    fn is_installed(&self) -> Result<bool, std::io::Error> {
        let config = Config::parse().map_err(|e| std::io::Error::other(e.to_string()))?;
        let installed_db = Path::new(&config.paths.installed_db);
        let manifest_path = installed_db.join(format!("{}-{}.toml", self.name, self.version));

        Ok(manifest_path.exists())
    }
}