pacops 0.0.2

PKGBUILD maintainer Swiss Army knife
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
extern crate shellexpand;

use crate::chroot;
use crate::settings::{Build, Settings};
use crate::source::{Origin, Source};
use crate::update::Update;

use std::cell::RefCell;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::rc::{Rc, Weak};
use std::str;

use blake2::{Blake2b, Blake2s, Digest};
use md5::{Digest as md5digest, Md5};
use regex::Regex;
use sha1::{Digest as sha1digest, Sha1};
use sha2::{Digest as sha2digest, Sha224, Sha256, Sha384, Sha512};
use version_compare::{CompOp, VersionCompare};

pub struct Pkgbuild {
    raw: String,
    pkgname: String,
    version: Option<String>,
    sources: Vec<Source>,
    hashsums: HashSums,
    path: Option<PathBuf>,
}

pub struct HashSums {
    hashes: Vec<String>,
    alg: HashAlg,
}

#[derive(Clone, Copy)]
pub enum HashAlg {
    B2,
    SHA1,
    SHA224,
    SHA256,
    SHA384,
    SHA512,
    MD5,
}

impl HashSums {
    fn new(line_prefix: String, hashes: Vec<String>) -> Option<HashSums> {
        match line_prefix.as_str() {
            "md5" => Some(HashSums {
                hashes,
                alg: HashAlg::MD5,
            }),
            "b2" => Some(HashSums {
                hashes,
                alg: HashAlg::B2,
            }),
            "sha1" => Some(HashSums {
                hashes,
                alg: HashAlg::SHA1,
            }),
            "sha224" => Some(HashSums {
                hashes,
                alg: HashAlg::SHA224,
            }),
            "sha256" => Some(HashSums {
                hashes,
                alg: HashAlg::SHA256,
            }),
            "sha384" => Some(HashSums {
                hashes,
                alg: HashAlg::SHA384,
            }),
            "sha512" => Some(HashSums {
                hashes,
                alg: HashAlg::SHA512,
            }),
            _ => None,
        }
    }
}

impl Pkgbuild {
    fn new(raw: String, path: Option<PathBuf>) -> Result<Rc<RefCell<Pkgbuild>>, Box<dyn Error>> {
        let sources: Vec<Source> = Vec::new();
        let raw_double = raw.clone();
        let version = Pkgbuild::parse_version(&raw);
        let pkgname = Pkgbuild::parse_pkgname(&raw).unwrap();
        let hashsums = Pkgbuild::parse_hashsums(&raw).unwrap();
        let pkgb = Rc::new(RefCell::new(Pkgbuild {
            raw,
            version,
            pkgname,
            sources,
            hashsums,
            path,
        }));
        let tmp_value = pkgb.clone();
        pkgb.borrow_mut()
            .set_sources(Pkgbuild::parse_sources(raw_double, tmp_value));
        Ok(pkgb)
    }

    pub fn from_file(path: &str) -> Result<Rc<RefCell<Pkgbuild>>, Box<dyn Error>> {
        let path = Path::new(path);
        let display = path.display();

        let mut file = match File::open(&path) {
            Err(why) => panic!("couldn't open {}: {}", display, why),
            Ok(file) => file,
        };

        let mut s = String::new();
        match file.read_to_string(&mut s) {
            Err(why) => Err(Box::new(why)),
            Ok(_) => Ok(Pkgbuild::new(s, Some(path.to_path_buf()))?),
        }
    }

    pub fn hash_alg(&self) -> HashAlg {
        self.hashsums.alg
    }

    pub fn set_version(&mut self, new_version: String) {
        self.raw = self
            .raw
            .replace(self.version.as_ref().unwrap(), &new_version);
        self.version = Some(new_version);
    }

    pub fn version(&self) -> &Option<String> {
        &self.version
    }

    pub fn path(&self) -> &Option<PathBuf> {
        &self.path
    }

    pub fn pkgname(&self) -> &String {
        &self.pkgname
    }

    pub fn set_hash(&mut self, index: usize, new_hash: String) -> Result<(), Box<dyn Error>> {
        let current_hash = &self.hashsums.hashes[index];
        self.raw = self.raw.replace(current_hash, &new_hash);
        self.hashsums.hashes[index] = new_hash;
        Ok(())
    }

    fn parse_hashsums(pkg: &str) -> Option<HashSums> {
        let hash_types = ["md5", "b2", "sha1", "sha224", "sha256", "sha348", "sha512"];
        for hash_type in hash_types.iter() {
            let line_prefix = hash_line_prefix(hash_type.to_string());
            if pkg.contains(&line_prefix) {
                return Pkgbuild::parse_typed_hashes(pkg.to_string(), hash_type.to_string());
            }
        }
        None
    }

    fn parse_typed_hashes(pkg_string: String, hash_type: String) -> Option<HashSums> {
        let mut hashes: Vec<String> = Vec::new();
        let mut in_hashes = false;
        let line_prefix = hash_line_prefix(hash_type.clone());
        let lines = pkg_string.split('\n');
        for line in lines {
            if line.starts_with(&line_prefix) {
                in_hashes = true;
                let tokens = line.split('=');
                if tokens.clone().count() == 2 {
                    let hashes_right = tokens.last().unwrap().to_string();
                    Pkgbuild::parse_hash(hashes_right, &mut hashes);
                }
            } else if in_hashes {
                Pkgbuild::parse_hash(line.to_string(), &mut hashes);
            }
            if line.contains(')') {
                in_hashes = false;
            }
        }
        HashSums::new(hash_type, hashes)
    }

    fn parse_hash(string: String, result: &mut Vec<String>) {
        let hashes_dirty = string.split('\'');
        for candidate in hashes_dirty {
            let candidate_trimmed = candidate.trim(); // TODO: also trim tabulation
            if candidate_trimmed.len() > 1 {
                // this check just happens to work
                // gets rid of braces '(' & ')'
                result.push(candidate_trimmed.to_string());
            }
        }
    }

    // TODO: wrap in result
    // TODO: come up with Enum for type of version
    fn parse_version(pkg: &str) -> Option<String> {
        let lines = pkg.split('\n');
        for line in lines {
            if line.starts_with("pkgver=") {
                let tokens = line.split('=');
                if tokens.clone().count() == 2 {
                    let pkgver = tokens.last().unwrap();
                    return Some(pkgver.to_string());
                }
            }
        }
        None
    }

    fn parse_pkgname(pkg: &str) -> Option<String> {
        let lines = pkg.split('\n');
        for line in lines {
            if line.starts_with("pkgname=") {
                let tokens = line.split('=');
                if tokens.clone().count() == 2 {
                    let pkgver = tokens.last().unwrap();
                    return Some(pkgver.to_string());
                }
            }
        }
        None
    }

    pub fn to_file(&self, path: &str) -> Result<(), Box<dyn Error>> {
        let path = Path::new(path);
        let display = path.display();

        let mut file = match File::create(&path) {
            Err(why) => panic!("couldn't open {}: {}", display, why),
            Ok(file) => file,
        };

        match file.write_all(&self.raw.as_bytes()) {
            Err(why) => Err(Box::new(why)),
            Ok(_) => Ok(()),
        }
    }

    // Gets a value of a variable
    pub fn render(&self, variable: String) -> Option<String> {
        let lines = self.raw.split('\n');
        for line in lines {
            let mut var_with_eq_sign = variable.clone();
            var_with_eq_sign.push('=');
            if line.starts_with(&var_with_eq_sign) {
                let tokens = line.split('=');
                if tokens.clone().count() == 2 {
                    let render = tokens.last().unwrap();
                    return Some(render.to_string());
                }
            }
        }
        None
    }

    pub fn sources(&self) -> &Vec<Source> {
        &self.sources
    }

    fn set_sources(&mut self, sources: Vec<Source>) {
        self.sources = sources;
    }

    fn parse_sources(raw: String, pkgb: Rc<RefCell<Pkgbuild>>) -> Vec<Source> {
        let mut sources = Vec::new();
        let lines = raw.split('\n');
        let mut in_sources = false;
        for line in lines {
            if line.starts_with("source") {
                in_sources = true;
                let tokens = line.split('=');
                if tokens.clone().count() == 2 {
                    let sources_right = tokens.last().unwrap();
                    Pkgbuild::parse_source(
                        sources_right,
                        &mut sources,
                        Rc::downgrade(&pkgb.clone()),
                    );
                }
            } else if in_sources {
                Pkgbuild::parse_source(line, &mut sources, Rc::downgrade(&pkgb.clone()));
            }
            if line.contains(')') {
                in_sources = false;
            }
        }
        sources
    }

    fn parse_source(source: &str, result: &mut Vec<Source>, pkgb: Weak<RefCell<Pkgbuild>>) {
        let sources_dirty = source.split('"');
        for candidate in sources_dirty {
            let candidate_trimmed = candidate.trim(); // TODO: also trim tabulation
            if candidate_trimmed.len() > 1 {
                // this check just happens to work
                // gets rid of braces '(' & ')'
                let source_type = Origin::guess(candidate_trimmed.to_string());
                result.push(Source::new(
                    candidate_trimmed.to_string(),
                    source_type,
                    pkgb.clone(),
                    result.len(),
                ));
            }
        }
    }

    // Returns update if it's newer than current version
    pub fn check_for_updates(&self) -> Result<Vec<Update>, Box<dyn Error>> {
        let mut updates: Vec<Update> = Vec::new();
        for source in &self.sources {
            if let Some(update) = source.update_available()? {
                updates.push(update)
            }
        }
        Ok(updates)
    }
}

fn hash_line_prefix(hash_type: String) -> String {
    format!("{}sums=", hash_type)
}

pub fn dir(path_str: &str) -> &Path {
    let path = Path::new(path_str);
    if path.is_file() {
        return path.parent().unwrap();
    }
    path
}

pub fn build(pkgbuild_dir: &Path, settings: &Settings) {
    match settings.build_type() {
        Build::Chroot => {
            match settings.chroot() {
                Some(chroot_path) => {
                    println!(
                        "Starting build for \"{}\" in \"{}\"",
                        &pkgbuild_dir.display(),
                        &chroot_path.display()
                    );
                    // change string into a path & check it
                    let mut chroot_path = chroot_path.to_str().unwrap().to_string();
                    if chroot_path.contains('~') {
                        chroot_path = shellexpand::tilde(&chroot_path).into_owned();
                    }
                    //makechrootpkg -c -r ~/hobby/chroot -n -C -T
                    let mkchrtpkg = Command::new("makechrootpkg")
                        .current_dir(pkgbuild_dir.to_str().unwrap())
                        .arg("-c") // Clean the chroot before building
                        .arg("-r") // The chroot dir to use
                        .arg(chroot_path)
                        //.arg(-n) // Run namcap on the package
                        //.arg(-C) // Run checkpkg on the package
                        .arg("-T") // Build in a temporary directory
                        .stdout(Stdio::inherit())
                        .output()
                        .expect("failed to execute process");
                    println!("{}", str::from_utf8(&mkchrtpkg.stdout).unwrap());
                    println!("{}", str::from_utf8(&mkchrtpkg.stderr).unwrap());
                }
                None => {
                    println!("No chroot path");
                }
            }
        }
        Build::Local => {
            let mkpkg = Command::new("makepkg")
                .current_dir(pkgbuild_dir.to_str().unwrap())
                .arg("--syncdeps") // install dependencies
                .arg("--cleanbuild") // remove `srcdir` dir before the build
                .arg("--clean") // clean up after the build
                .arg("--force") // allows to build package even with existing one in PKGDEST
                .arg("--needed") // pass to pacman
                .arg("--noconfirm") // pass to pacman
                .output()
                .expect("failed to execute process");
            println!("{}", str::from_utf8(&mkpkg.stdout).unwrap());
            println!("{}", str::from_utf8(&mkpkg.stderr).unwrap());
        }
        _ => println!("We don't support this build method, yet. Sorry!"),
    }
}

pub fn update_build_env(settings: Settings) -> Result<(), Box<dyn Error>> {
    match settings.build_type() {
        Build::Chroot => match settings.chroot() {
            Some(chroot_path) => chroot::update(chroot_path),
            None => {
                let error: Box<dyn std::error::Error> =
                    String::from("The chroot path is not specified").into();
                Err(error)
            }
        },
        Build::Local => {
            let mkpkg = Command::new("sudo")
                .arg("pacman")
                .arg("-Syu")
                .arg("--noprogressbar")
                .arg("--noconfirm")
                .output()
                .expect("failed to execute process");
            println!("{}", str::from_utf8(&mkpkg.stdout).unwrap());
            println!("{}", str::from_utf8(&mkpkg.stderr).unwrap());
            Ok(())
        }
        _ => {
            let error: Box<dyn std::error::Error> = String::from("Unsupported build method").into();
            Err(error)
        }
    }
}

// take PKGBUILD path and writes
pub fn srcinfo(pkgbuild_path: &Path) -> Result<(), Box<dyn Error>> {
    let pkgbuild_dir = pkgbuild_path.parent().unwrap();
    let mkpkg = Command::new("makepkg")
        .current_dir(pkgbuild_dir.to_str().unwrap())
        .arg("--printsrcinfo")
        .output()
        .expect("failed to start `makepkg` process for .SRCINFO generation");
    if mkpkg.status.success() {
        let stdout = &mkpkg.stdout;
        //let data = format!("{}", str::from_utf8(&mkpkg.stdout).unwrap());

        let file_path = pkgbuild_dir.join(".SRCINFO");
        let mut file = File::create(file_path)?;
        //println!("{}", &data);
        file.write_all(stdout)?;
        return Ok(());
    }

    let error: Box<dyn std::error::Error> = format!(
        "Unable to generate .SRCINFO:\n {}",
        str::from_utf8(&mkpkg.stderr).unwrap()
    )
    .into();
    Err(error)
}

pub fn srcinfo_path(pkgbuild_path: &Path) -> Result<PathBuf, Box<dyn Error>> {
    let pkgbuild_dir = pkgbuild_path.parent().unwrap();
    Ok(pkgbuild_dir.join(".SRCINFO"))
}

pub fn find_variables(string: String) -> Vec<String> {
    let re = Regex::new(r"\$\{.*?\}").unwrap();
    re.captures_iter(&string)
        .map(|var_capture| {
            var_capture
                .get(0)
                .unwrap()
                .as_str()
                .to_string()
                .replace("${", "")
                .replace("}", "")
        })
        .collect()
}