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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
#[cfg(test)]
mod tests {
    use crate::*;

    #[test]
    fn test_brew_install_test() {
        assert!(matches!(test_brew_installed(), Ok(())));
    }

    #[test]
    fn get_info() {
        let exa = Package::new("exa").unwrap();
        assert_eq!(exa.name, "exa");
        assert_eq!(exa.desc.unwrap(), "Modern replacement for 'ls'");
        assert!(
            exa.versions.stable.parse().unwrap() >= version_rs::Version::from((0 as u32, 9 as u32))
        );
    }

    #[test]
    fn look_at_everything() {
        all_installed().unwrap();
        all_packages().unwrap();
    }
}

use command_builder::{Command, Single};
use serde::{Deserialize, Serialize};
use serde_json;
use std::collections::HashMap;
use std::str::FromStr;
use version_rs;

fn brew_return(command: command_builder::Output, name: &str) -> Result<Package> {
    if command.success() {
        Ok(Package::new(name)?)
    } else {
        test_brew_installed()?;
        Err(Error::UnknownError(command.stderr().to_owned()))
    }
}

/// Represents a string which might be a version number for homebrew.
/// Homebrew has requirments for version strings, so it is not possable
/// to definitivly parse it.
#[derive(Serialize, Deserialize, Clone)]
#[serde(transparent)]
pub struct Version {
    original: String,
}

impl Version {
    /// Attempts to return a version of the form "N.N.N".
    pub fn parse(&self) -> Option<version_rs::Version> {
        version_rs::Version::from_str(&self.original).ok()
    }

    /// Returns the original version string.
    pub fn original(&self) -> &str {
        &self.original
    }
}

/// Represents a homebrew package, which may or may not be installed.
#[derive(Deserialize, Serialize, Clone)]
pub struct Package {
    pub name: String,
    pub full_name: String,
    pub aliases: Vec<String>,
    pub oldname: Option<String>,
    pub desc: Option<String>,
    pub homepage: Option<String>,
    pub versions: Versions,
    pub urls: HashMap<String, Url>,
    pub revision: usize,
    pub version_scheme: usize,
    pub bottle: HashMap<String, Bottle>,
    pub keg_only: bool,
    pub bottle_disabled: bool,
    pub options: Vec<BrewOption>,
    pub build_dependencies: Vec<String>,
    pub dependencies: Vec<String>,
    pub recommended_dependencies: Vec<String>,
    pub optional_dependencies: Vec<String>,
    pub uses_from_macos: Vec<MapOrString>,
    pub requirements: Vec<Requirment>,
    pub conflicts_with: Vec<String>,
    pub caveats: Option<String>,
    pub installed: Vec<Installed>,
    pub linked_keg: Option<String>,
    pub pinned: bool,
    pub outdated: bool,
    pub analytics: Option<Analytics>,
}

#[derive(Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum MapOrString {
    MapStringString(HashMap<String, String>),
    String(String),
    MapStringVecString(HashMap<String, Vec<String>>),
}

#[derive(Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum NumOrString {
    Num(u32),
    String(String),
}

#[derive(Deserialize, Serialize, Clone)]
pub struct Requirment {
    name: String,
    cask: Option<String>,
    download: Option<String>,
    version: Option<VersionResult>,
    contexts: Vec<String>,
}

#[derive(Deserialize, Serialize, Clone)]
pub struct BrewOption {
    option: String,
    description: String,
}

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug)]
pub enum Error {
    NotInstalled,
    PackageNotFound,
    IOError(std::io::Error),
    ParseError(serde_json::Error),
    InstallFailed(String),
    UnknownError(String),
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Error::IOError(e)
    }
}

impl From<serde_json::Error> for Error {
    fn from(e: serde_json::Error) -> Self {
        Error::ParseError(e)
    }
}

fn contains<I, J, E>(iter1: I, iter2: J) -> bool
where
    I: IntoIterator<Item = E>,
    J: IntoIterator<Item = E>,
    E: std::cmp::Eq + std::hash::Hash,
{
    let hash: std::collections::HashSet<E> = iter1.into_iter().collect();
    for item in iter2.into_iter() {
        if !hash.contains(&item) {
            return false;
        }
    }
    return true;
}

impl Package {
    /// Creates package, filling out struct from the command line toole.
    pub fn new(name: &str) -> Result<Package> {
        let output = Single::new("/usr/local/bin/brew")
            .arg("info")
            .arg(name)
            .arg("--json=v1")
            .arg("--analytics")
            .env("HOMEBREW_NO_AUTO_UPDATE", "1")
            .run()?;
        if output.success() {
            let packages: Vec<Package> = serde_json::from_str(output.stdout())?;
            packages
                .into_iter()
                .next()
                .map(|p| Ok(p))
                .unwrap_or(Err(Error::PackageNotFound))
        } else {
            test_brew_installed()?;
            Err(Error::PackageNotFound)
        }
    }

    /// Attempts to install a package, reinstalling a package if it is already installed.
    pub fn install(&self, options: &Options) -> Result<Package> {
        let command = Single::new("brew")
            .arg(if self.is_installed() && options.force {
                "reinstall"
            } else if self.is_installed() {
                let opts = self.install_options().unwrap();
                if contains(opts, options.package_options()) {
                    return Self::new(&self.name);
                } else {
                    "reinstall"
                }
            } else {
                "install"
            })
            .args(options.brew_options().as_slice())
            .arg(&self.name)
            .args(
                &options
                    .package_options()
                    .into_iter()
                    .map(|f| f.as_str())
                    .collect::<Vec<_>>(),
            )
            .env("HOMEBREW_NO_AUTO_UPDATE", "1")
            .run()?;
        if command.success() {
            let new = Self::new(&self.name)?;
            if new.is_installed() {
                Ok(new)
            } else {
                Err(Error::InstallFailed(
                    "Could not detect new install".to_owned(),
                ))
            }
        } else {
            test_brew_installed()?;
            Err(Error::InstallFailed(command.stderr().to_owned()))
        }
    }

    /// Check if a package is installed.
    pub fn is_installed(&self) -> bool {
        self.installed.len() != 0
    }

    /// The package options that the package was installed with.
    pub fn install_options(&self) -> Option<&[String]> {
        self.installed
            .first()
            .map(|i: &Installed| i.used_options.as_slice())
    }

    /// Uninstalls the package.
    pub fn uninstall(&self, force: bool, ignore_dependencies: bool) -> Result<Package> {
        let mut args = vec!["uninstall", &self.name];
        if force {
            args.push("--force");
        }
        if ignore_dependencies {
            args.push("--ignore-dependencies");
        }
        let command = Single::new("brew")
            .args(args)
            .env("HOMEBREW_NO_AUTO_UPDATE", "1")
            .run()?;
        brew_return(command, &self.name)
    }

    /// Pin forumla to prevent automatic updates/upgrades.
    pub fn pin(&self) -> Result<Package> {
        if !self.pinned {
            let command = Single::new("brew")
                .arg("pin")
                .arg(&self.name)
                .env("HOMEBREW_NO_AUTO_UPDATE", "1")
                .run()?;
            brew_return(command, &self.name)
        } else {
            Ok(self.clone())
        }
    }

    /// Unpin formula to allow automatic updates/upgrades.
    pub fn unpin(&self) -> Result<Package> {
        if self.pinned {
            let command = Single::new("brew")
                .arg("unpin")
                .arg(&self.name)
                .env("HOMEBREW_NO_AUTO_UPDATE", "1")
                .run()?;
            brew_return(command, &self.name)
        } else {
            Ok(self.clone())
        }
    }

    /// Upgrade formula.
    pub fn upgrade(&self) -> Result<Package> {
        if self.is_installed() {
            let command = Single::new("brew")
                .arg("upgrade")
                .arg(&self.name)
                .env("HOMEBREW_NO_AUTO_UPDATE", "1")
                .run()?;
            brew_return(command, &self.name)
        } else {
            Err(Error::NotInstalled)
        }
    }
}

/// Update homebrew, synchronizing the homebrew-core and package list.
pub fn update() -> Result<()> {
    let command = Single::new("brew").arg("update").run()?;
    if command.success() {
        Ok(())
    } else {
        test_brew_installed()?;
        Err(Error::UnknownError(command.stderr().to_owned()))
    }
}

/// Return a map of all installed packages.
pub fn all_installed() -> Result<HashMap<String, Package>> {
    packages("--installed")
}

/// For internal use, wrapper to get package info.
fn packages(arg: &str) -> Result<HashMap<String, Package>> {
    let output = Single::new("brew")
        .arg("info")
        .arg("--json=v1")
        .arg(arg)
        .arg("--analytics")
        .env("HOMEBREW_NO_AUTO_UPDATE", "1")
        .run()?;
    if output.success() {
        let v: Vec<Package> = serde_json::from_str(output.stdout())?;
        Ok(v.into_iter().map(|p| (p.name.clone(), p)).collect())
    } else {
        test_brew_installed()?;
        Err(Error::UnknownError(output.stdout().to_string()))
    }
}

/// Returns a map of all packages in the downloaded homebrew repository.
pub fn all_packages() -> Result<HashMap<String, Package>> {
    packages("--all")
}

#[derive(Deserialize, Serialize, Clone)]
pub struct Analytics {
    pub install: Analytic,
    pub install_on_request: Analytic,
    pub build_error: Analytic,
}

#[derive(Deserialize, Serialize, Clone)]
pub struct Analytic {
    #[serde(rename = "30d")]
    d30: Option<HashMap<String, usize>>,
    #[serde(rename = "90d")]
    d90: Option<HashMap<String, usize>>,
    #[serde(rename = "d365")]
    d365: Option<HashMap<String, usize>>,
}

#[derive(Deserialize, Serialize, Clone)]
pub struct Versions {
    pub stable: VersionResult,
    pub devel: Option<VersionResult>,
    pub head: Option<String>,
    pub bottle: bool,
}

#[derive(Deserialize, Serialize, Clone)]
pub struct Bottle {
    pub rebuild: usize,
    pub cellar: String,
    pub prefix: String,
    pub root_url: String,
    pub files: HashMap<String, File>,
}

#[derive(Deserialize, Serialize, Clone)]
pub struct File {
    pub url: String,
    pub sha256: String,
}

#[derive(Deserialize, Serialize, Clone)]
pub struct Url {
    pub url: String,
    pub tag: Option<String>,
    pub revision: Option<NumOrString>,
}

#[derive(Deserialize, Serialize, Clone)]
pub struct Installed {
    pub version: VersionResult,
    pub used_options: Vec<String>,
    pub built_as_bottle: bool,
    pub poured_from_bottle: bool,
    pub runtime_dependencies: Vec<Dependency>,
    pub installed_as_dependency: bool,
    pub installed_on_request: bool,
}

#[derive(Deserialize, Serialize, Clone)]
pub struct Dependency {
    pub full_name: String,
    pub version: VersionResult,
}

type VersionResult = Version;

/// Tests weither homebrew is installed by seeing if "brew --version" returns
/// successfully.
pub fn test_brew_installed() -> Result<()> {
    if Single::new("brew")
        .arg("--version")
        .env("HOMEBREW_NO_AUTO_UPDATE", "1")
        .run()
        .map(|o| o.success())
        .unwrap_or(false)
    {
        Ok(())
    } else {
        Err(Error::NotInstalled)
    }
}

/// WARNING: untested
/// installs the homebrew cli in "usr/local" which is it's recomended install location.
#[allow(dead_code)]
fn install_homebrew() -> Result<()> {
    install_homebrew_at("/usr/local")
}

/// WARNING: untested
/// TODO: Test this function
/// installs the homebrew cli in `dir`.
#[allow(dead_code)]
fn install_homebrew_at(dir: &str) -> Result<()> {
    Single::new("mkdir")
        .arg("homebrew")
        .and(
            Single::new("curl")
                .arg("-L")
                .arg("https://github.com/Homebrew/brew/tarball/master"),
        )
        .pipe(
            Single::new("tar")
                .arg("xz")
                .arg("--strip")
                .arg("1")
                .arg("-C")
                .arg("homebrew"),
        )
        .with_dir(dir)
        .run()?;
    test_brew_installed()?;
    Ok(())
}

/// Represents command line options with which to install a package.
#[derive(Clone)]
pub struct Options {
    env: BuildEnv,
    ignore_dependencies: bool,
    only_dependencies: bool,
    build_from_source: bool,
    include_test: bool,
    force_bottle: bool,
    devel: bool,
    head: bool,
    keep_tmp: bool,
    build_bottle: bool,
    bottle_arch: bool,
    force: bool,
    git: bool,
    package_options: Vec<String>,
}

impl Options {
    /// Represents no options added.
    pub fn new() -> Self {
        Self {
            env: BuildEnv::None,
            ignore_dependencies: false,
            only_dependencies: false,
            build_from_source: false,
            include_test: false,
            force_bottle: false,
            devel: false,
            head: false,
            keep_tmp: false,
            build_bottle: false,
            bottle_arch: false,
            force: false,
            git: false,
            package_options: Vec::new(),
        }
    }

    /// Adds the `--env=std` option.
    pub fn env_std(mut self) -> Self {
        self.env = BuildEnv::Std;
        self
    }

    /// Adds the `env=super` option.
    pub fn env_super(mut self) -> Self {
        self.env = BuildEnv::Super;
        self
    }

    /// Adds the `--ignore-dependencies` flag.
    pub fn ignore_dependencies(mut self) -> Self {
        self.ignore_dependencies = true;
        self
    }

    /// Adds the `--build-from-source` flag.
    pub fn build_from_source(mut self) -> Self {
        self.build_from_source = true;
        self
    }

    /// Adds the `--include-test` flag.
    pub fn include_test(mut self) -> Self {
        self.include_test = true;
        self
    }

    /// Adds the `--force-bottle` flag.
    pub fn force_bottle(mut self) -> Self {
        self.force_bottle = true;
        self
    }

    /// Adds the `--devel` flag.
    pub fn devel(mut self) -> Self {
        self.devel = true;
        self
    }

    /// Adds the `--HEAD` flag.
    pub fn head(mut self) -> Self {
        self.head = true;
        self
    }

    /// Adds the `--keep-tmp` flag.
    pub fn keep_tmp(mut self) -> Self {
        self.keep_tmp = true;
        self
    }

    /// Adds the `--build-bottle` flag.
    pub fn build_bottle(mut self) -> Self {
        self.build_bottle = true;
        self
    }

    /// Adds the `--bottle-arch` flag.
    pub fn bottle_arch(mut self) -> Self {
        self.bottle_arch = true;
        self
    }

    /// Adds the `--force` flag.
    pub fn force(mut self) -> Self {
        self.force = true;
        self
    }

    /// Adds the `--git` flag.
    pub fn git(mut self) -> Self {
        self.git = true;
        self
    }

    /// Adds a flag for the package to use directly.
    pub fn option(mut self, opt: &str) -> Self {
        self.package_options.push(opt.to_string());
        self
    }

    /// Adds an multiple flags for the package to use directly.
    pub fn options<I, S>(mut self, opts: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.package_options
            .extend(opts.into_iter().map(|s| s.as_ref().to_string()));
        self
    }

    fn package_options(&self) -> &Vec<String> {
        &self.package_options
    }

    fn brew_options(&self) -> Vec<&str> {
        let mut out = Vec::new();
        match self.env {
            BuildEnv::Std => out.push("--env=std"),
            BuildEnv::Super => out.push("--env=super"),
            BuildEnv::None => {}
        }
        if self.ignore_dependencies {
            out.push("--ignore-dependencies")
        }
        if self.build_from_source {
            out.push("--build-from-source")
        }
        if self.include_test {
            out.push("--include-test")
        }
        if self.force_bottle {
            out.push("--force-bottle")
        }
        if self.devel {
            out.push("--devel")
        }
        if self.head {
            out.push("--HEAD")
        }
        if self.keep_tmp {
            out.push("--keep-tmp")
        }
        if self.build_bottle {
            out.push("--build-bottle")
        }
        if self.bottle_arch {
            out.push("--bottle-arch")
        }
        if self.force {
            out.push("--force")
        }
        if self.git {
            out.push("--git")
        }
        out
    }
}

#[derive(Clone, Copy)]
pub enum BuildEnv {
    Std,
    Super,
    None,
}