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
use std::rc::Rc;
use std::result::Result as StdResult;

use itertools::{Itertools, process_results};
use pkg_utils::{Alpm, Provide};
use solvent::{DepGraph, SolventError};
use version_compare::Version;

use config::Config;
use util::{InstallReason, MissingPackage, Result};

use dependency::ActionType::*;
use self::package::Package;

pub(crate) mod package;

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum ActionType {
    Fetch,
    Build,
    // Install from the built cache
    Install(InstallReason),
    // Install a package from the binary repos
    InstallBin,
    // Apply action to each foreign package
    Update(Box<ActionType>)
}

impl ActionType {
    pub fn is_update(&self) -> bool {
        match self {
            Update(_) => true,
            _ => false
        }
    }
    
    pub fn is_install_bin(&self) -> bool {
        match self {
            InstallBin => true,
            _ => false
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct PkgAction {
    pub action: ActionType,
    pub package: Package,
}

impl PkgAction {
    pub fn new(action: ActionType, package: Package) -> PkgAction {
        PkgAction { action, package }
    }
    
    // Same package, new action type
    fn clone_as(&self, a_type: ActionType) -> PkgAction {
        PkgAction {
            package: self.package.clone(),
            action: a_type
        }
    }
    
    // Return a list of the direct dependencies of this action
    fn dependencies(&self, config: &Config, dbs: Rc<Alpm>) -> Result<Vec<PkgAction>> {
        let mut deps = Vec::new();
        
        // Unresolved depends and makedepends are run through this function
        //   before being added to the dependency tree.
        let pkgname_as_pkg_action = |mut pkgname: String| -> Option<Result<PkgAction>> {
            // IDK what all the allowed symbols are in dependency lists;
            //   this is what I've seen.
            if pkgname.contains(|c| "=<>".contains(c) ) {
                // ^ Then this isn't a pkgname, it contains one.
                
                //TODO: Stop ignoring the version requirement of a provide
                pkgname = Provide::parse(pkgname)?.name;
            }
            
            match Package::new(pkgname, dbs.clone(), &config) {
                // pkg is always a dependency when being processed here, and is therefore
                //   required to be installed + Dependency as the reason.
                Ok(pkg) => match pkg {
                    Package::Alpm(_) => Some(Ok(
                        PkgAction::new(InstallBin, pkg)
                    )),
                    Package::Aur(_) => Some(Ok(
                        PkgAction::new(Install(InstallReason::Dependency), pkg)
                    )),
                },
                Err(e) => Some(Err(e))
            }
        };
        
        match &self.action {
            Fetch => {
                // Dep resolution has side-effects
                // - maybe it shouldn't
                config.cache.get(self.package.name().to_string())?;
            },
            Build => {
                // Assume that if an action is Build, the pkg is from the AUR
                deps.push(self.clone_as(Fetch));
                
                let makedepends = self.package.unresolved_makedepends(dbs.clone())
                    .filter_map(pkgname_as_pkg_action);
                let mut makedepends = process_results(makedepends, |iter| iter.collect_vec() )?;
                
                deps.append(&mut makedepends);
            },
            Install(_) => {
                let name = self.package.name();
                if !config.is_pkg_up_to_date(name.to_string())? {
                    deps.push(self.clone_as(Build));
                } else {
                    warn!("{} is up to date, skipping build", name);
                    // No dependencies if we skip the build
                    return Ok(deps);
                }
                
                let depends = self.package.unresolved_depends(dbs.clone())
                    .filter_map(pkgname_as_pkg_action);
                let mut depends = process_results(depends, |iter| iter.collect_vec() )?;
                
                deps.append(&mut depends);
            },
            // Pacman takes care of dependencies here
            InstallBin => {},
            Update(ref a_type) => {
                let mut foreign = dbs.foreign_pkgs()
                    .collect_vec();
                
                let foreign_names = foreign.iter()
                    .map(|pkg| pkg.name.clone() )
                    .collect_vec();
                
                config.cache.add(&foreign_names)?;
                let mut actions = Vec::with_capacity(foreign_names.len());
                
                for local_pkg in foreign.drain(..) {
                    let aur_pkg = match config.cache.get(&local_pkg.name) {
                        Ok(pkg) => pkg,
                        Err(e) => {
                            warn!("{} not found in AUR; skipping", e.downcast::<MissingPackage>()?.pkgname);
                            continue;
                        }
                    };
                    
                    if Version::from(&aur_pkg.version) > local_pkg.version() {
                        actions.push(PkgAction {
                            package: Package::Aur(aur_pkg),
                            action: (**a_type).clone()
                        });
                    }
                }
                
                deps.append(&mut actions);
            }
        }
        Ok(deps)
    }
}

impl Eq for PkgAction {}

/// This function takes a list of direct dependencies, then resolves the
/// dependencies recursively based on the results of PkgAction::dependencies
// There is a lot of cloning around to avoid borrow rules. Improve if you can
fn populate_tree(
    tree: &mut DepGraph<PkgAction>,
    deps: &[PkgAction],
    parent: Option<PkgAction>,
    config: &Config,
    dbs: Rc<Alpm>
) -> Result<()> {
    // I can't imagine that Clone reduces performance by enough to matter
    if let Some(parent) = parent {
        tree.register_dependencies(parent, deps.to_vec());
    } else {
        tree.register_nodes(deps.to_vec());
    }
    
    let mut deps_duped = deps.to_vec();
    for action in deps_duped.drain(..) {
        let deps = action.dependencies(config, dbs.clone())?;
        trace!("dependencies of {:?}->{}: {:?}", action.action, action.package.name(), deps);
        populate_tree(tree, &deps, Some(action), config, dbs.clone())?;
    }
    Ok(())
}

/// Main interface for depedency resolution. Call this function with a bunch of unresolved
/// dependencies and it spits out a Vec of all resolved dependencies in an order
/// that satisfies the dependency tree (see solvent docs).
//TODO: Take pkg_utils::Db instances so that the caller is responsible for figuring out
//  where the dbs actually are, and so they only get parsed once
pub(crate) fn resolve_dependencies(
    deps: &[PkgAction],
    config: &Config,
    dbs: Rc<Alpm>
) -> Result<Vec<StdResult<PkgAction, SolventError>>> {
    let mut tree = DepGraph::new();
    populate_tree(&mut tree, deps, None, config, dbs)?;
    
    let mut resolved = Vec::new();
    
    for dep in deps.iter() {
        let mut dep_resolved = tree
            // Should only error if a node (dep) doesn't exist
            .dependencies_of(&dep)?
            // Don't really want to do this...
            .map(|result| result.map(|action| action.clone() ) )
            .collect();
        resolved.append(&mut dep_resolved);
    }
    Ok(resolved)
}