aboutsummaryrefslogtreecommitdiffstats
path: root/src/util.rs
blob: 7950d2a02393bd042572a1c7572bd61a9f8c5b8c (plain) (blame)
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
use git2::{Buf, Cred, FetchOptions, Oid, RemoteCallbacks, Repository, build::CheckoutBuilder};
use std::env;
use std::fs;
use std::io;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;

pub const BASE_REPO_PATH: &str = "/var/db/forge";
pub const BASE_CONFIG_PATH: &str = "/etc/forge/packages";
pub type PackageList = Vec<(String, PathBuf, PathBuf)>;

pub fn collect_packages() -> Result<PackageList, String> {
    let pkgs: PackageList = fs::read_dir(BASE_CONFIG_PATH)
        .map_err(|e| format!("failed to iterate package directory: {}", e))?
        .map(|p| {
            let entry = p.map_err(|e| e.to_string())?;
            let path = entry.path();

            let pkgname = path
                .file_stem()
                .ok_or_else(|| format!("invalid filename: {:?}", path))?
                .to_string_lossy()
                .into_owned();

            let path = PathBuf::from(BASE_REPO_PATH).join(&pkgname);
            let cfg_path = PathBuf::from(BASE_CONFIG_PATH).join(format!("{}.toml", &pkgname));

            if !path.exists() || !cfg_path.exists() {
                Err(format!("no installed package: {}", pkgname))
            } else {
                Ok((pkgname, path, cfg_path))
            }
        })
        .collect::<Result<_, _>>()?;

    Ok(pkgs)
}

pub fn collect_named_packages(packages: Vec<String>) -> Result<PackageList, String> {
    let pkgs: PackageList = packages
        .into_iter()
        .map(|p| {
            let path = PathBuf::from(BASE_REPO_PATH).join(&p);
            let cfg_path = PathBuf::from(BASE_CONFIG_PATH).join(format!("{}.toml", p));
            if !path.exists() || !cfg_path.exists() {
                Err(format!("no installed package: {}", p))
            } else {
                Ok((p, path, cfg_path))
            }
        })
        .collect::<Result<_, _>>()?;

    Ok(pkgs)
}

pub fn dir_size(path: &Path) -> std::io::Result<u64> {
    let mut size = 0;
    if path.is_dir() {
        for entry in fs::read_dir(path)? {
            let entry = entry?;
            let metadata = entry.metadata()?;
            if metadata.is_file() {
                size += metadata.len();
            } else if metadata.is_dir() {
                size += dir_size(&entry.path())?;
            }
        }
    }
    Ok(size)
}

pub fn get_commit_hash_full(path: &Path) -> Result<Oid, git2::Error> {
    let repo = Repository::open(path)?;
    let head = repo.head()?;

    let commit = head.peel_to_commit()?;
    Ok(commit.id())
}

pub fn get_commit_hash_short(path: &Path) -> Result<Buf, git2::Error> {
    let repo = Repository::open(path)?;
    let head = repo.head()?;

    let commit = head.peel_to_commit()?;
    Ok(repo.find_object(commit.id(), None)?.short_id()?)
}

pub fn get_editor() -> String {
    env::var("VISUAL")
        .or_else(|_| env::var("EDITOR"))
        .unwrap_or_else(|_| "nano".to_string())
}

pub fn get_remote_url(path: &Path) -> Result<String, git2::Error> {
    let repo = Repository::open(path)?;

    let remote = repo.find_remote("origin")?;

    if let Some(url) = remote.url() {
        Ok(url.to_string())
    } else {
        Err(git2::Error::from_str("Remote 'origin' has no URL"))
    }
}

pub fn open_in_editor(editor: &str, file: &str) -> Result<(), String> {
    let status = Command::new(editor)
        .arg(file)
        .status()
        .map_err(|e| format!("failed to execute editor: {}", e))?;

    if !status.success() {
        return Err(format!("editor exited with non-zero status: {}", status));
    }

    Ok(())
}

pub fn print_collected_packages(packages: &PackageList, message: &str) {
    println!(
        "{message} ({}): {}\n",
        packages.len(),
        packages
            .iter()
            .map(|(p, _, _)| p.as_str())
            .collect::<Vec<_>>()
            .join(", ")
    );
}

pub fn pull_latest_tag(path: &Path) -> Result<(), git2::Error> {
    let repo = Repository::open(path)?;

    let mut callbacks = RemoteCallbacks::new();
    callbacks.credentials(|_url, username_from_url, _allowed| {
        Cred::ssh_key_from_agent(username_from_url.unwrap())
    });

    let mut fetch_options = FetchOptions::new();
    fetch_options.remote_callbacks(callbacks);

    let mut remote = repo.find_remote("origin")?;
    remote.fetch(&["refs/tags/*:refs/tags/*"], Some(&mut fetch_options), None)?;

    let tag_names = repo.tag_names(None)?;
    let mut latest_commit = None;
    let mut latest_time = 0;

    for name in tag_names.iter().flatten() {
        let obj = repo.revparse_single(&format!("refs/tags/{}", name))?;
        let commit = obj.peel_to_commit()?;
        let time = commit.time().seconds();

        if time > latest_time {
            latest_time = time;
            latest_commit = Some(commit);
        }
    }

    let latest_commit = latest_commit.ok_or_else(|| git2::Error::from_str("No tags found"))?;

    let current_commit = repo.head()?.peel_to_commit()?;

    if current_commit.id() == latest_commit.id() {
        return Ok(());
    }

    repo.set_head_detached(latest_commit.id())?;
    repo.checkout_head(Some(CheckoutBuilder::default().force()))?;

    Ok(())
}

pub fn pull_repo(path: &Path) -> Result<(), git2::Error> {
    let repo = Repository::open(path)?;

    let head = repo.head()?;
    let branch = head
        .shorthand()
        .ok_or_else(|| git2::Error::from_str("Could not determine current branch"))?;

    let mut callbacks = RemoteCallbacks::new();
    callbacks.credentials(|_url, username_from_url, _allowed| {
        Cred::ssh_key_from_agent(username_from_url.unwrap())
    });

    let mut fetch_options = FetchOptions::new();
    fetch_options.remote_callbacks(callbacks);

    let mut remote = repo.find_remote("origin")?;
    remote.fetch(&[branch], Some(&mut fetch_options), None)?;

    let fetch_head = repo.find_reference("FETCH_HEAD")?;
    let fetch_commit = repo.reference_to_annotated_commit(&fetch_head)?;

    let (analysis, _pref) = repo.merge_analysis(&[&fetch_commit])?;

    if analysis.is_fast_forward() {
        let refname = format!("refs/heads/{}", branch);
        let mut reference = repo.find_reference(&refname)?;
        reference.set_target(fetch_commit.id(), "Fast-Forward")?;
        repo.set_head(&refname)?;
        repo.checkout_head(Some(CheckoutBuilder::default().force()))?;
    } else if !analysis.is_up_to_date() {
        println!("Non fast-forward merge required (manual merge needed).");
    }
    Ok(())
}

pub fn yn_prompt(prompt: &str) -> bool {
    print!("{} [y/n]: ", prompt);
    io::stdout().flush().unwrap();

    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();

    let input = input.trim().to_lowercase();

    match input.as_str() {
        "y" | "yes" | "" => true,
        _ => false,
    }
}