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
mod library;
pub mod err;

use std::collections::BinaryHeap;
use std::path::{Path, PathBuf};
use std::ffi::OsStr;
use std::ops::BitAnd;
use std::usize;
use std::env;
use std::process;
use std::fs;

use self::library::Library;
pub use self::err::{CompositerError, Result};

use ::git2::Repository;

/// The default capacity of heap.
const SPEC_CAPACITY: usize = 10;
/// The default priority of call.
const SPEC_PRIORITY: usize = usize::MAX / 2;

/// The struct `Compositer` is a heap of a double tuple
/// of a dynamic libraries and a priority order.
#[derive(Debug)]
pub struct Compositer(BinaryHeap<Library>);

impl Compositer {

    /// The accessor method `source` returns the source directory where
    /// found the `git` and `lib` sub-directories.
    pub fn source(&self) -> PathBuf {
      env::home_dir()
          .unwrap_or(PathBuf::new())
          .join(".neko")
    }

    /// The method `mount` adds a new library to the heap's compositer.
    #[cfg(any(target_os = "linux", target_os = "android"))]
    pub fn mount<S: AsRef<OsStr> >(&mut self,
                 libraryname: S,
                 priority: Option<usize>)
                 -> Result<()> {
        let mut path: PathBuf = self.source().join("lib")
                                             .join(libraryname.as_ref());
        if path.set_extension("so").bitand(path.exists()) {
            match Library::new(&path, priority.unwrap_or(SPEC_PRIORITY)) {
                Err(why) => Err(CompositerError::BadMount(why)),
                Ok(lib) => {
                    lib.start();
                    Ok(self.0.push(lib))
                },
            }
        } else {
            Err(CompositerError::BadPath)
        }
    }

    /// The method `mount` adds a new library to the heap's compositer.
    #[cfg(any(target_os = "bitrig", target_os = "dragonfly",
              target_os = "freebsd", target_os = "ios", target_os = "macos",
              target_os = "netbsd", target_os = "openbsd"))]
    pub fn mount<S: AsRef<OsStr> >(&mut self,
                 libraryname: S,
                 priority: Option<usize>)
                 -> Result<()> {
        let path: PathBuf = self.source().join("lib")
                                         .join(libraryname.as_ref());
        if path.set_extension("dylib").bitand(path.exists()) {
            match Library::new(&path, priority.unwrap_or(SPEC_PRIORITY)) {
                Err(why) => Err(CompositerError::BadMount(why)),
                Ok(lib) => Ok(self.0.push(lib)),
            }
        } else {
            Err(CompositerError::BadPath)
        }
    }

    /// The method `build` runs a Makefile from a directory.
    fn build(&self, directory: &Path, source: &Path) -> Result<()> {
        if directory.join("Makefile").exists() {
            match process::Command::new("make")
                          .env("SOURCE", source)
                          .current_dir(directory)
                          .status() {
                Ok(status) if status.success() => Ok(()),
                Ok(status) => Err(CompositerError::BadReturnCommand(
                    status.code().unwrap_or_default()
                )),
                Err(why) => Err(CompositerError::BadCommand(why)),
            }
        }
        else {
          Err(CompositerError::NotMakeFound)
        }
    }

    /// The method `mount_from_dir` adds a new library to the heap's compositer
    /// from a directory.
    pub fn mount_from_dir(&mut self,
                          directory: &str,
                          priority: Option<usize>)
                          -> Result<()> {
      let source: &Path = &self.source();
      let path: &Path = Path::new(directory);

      self.build(path, &source).and(
          self.mount(path.iter().last().unwrap_or_default(), priority)
      )
    }

    /// The method `mount_from_git` adds a new library to the heap's compositer
    /// from a git repository.
    pub fn mount_from_git(&mut self,
                          repository: &str,
                          priority: Option<usize>)
                          -> Result<()> {
        let source: &Path = &self.source();
        let path: PathBuf = source.join("git")
            .join(repository.chars()
                .skip(repository.rfind('/')
                    .unwrap_or_default())
                .skip(1)
                .take_while(|g| g.is_alphanumeric())
                .collect::<String>());

        match Repository::clone(repository, &path) {
            Err(why) => Err(CompositerError::BadGitClone(why)),
            Ok(_) => {
                self.build(&path, source).and(
                    self.mount(path.iter().last().unwrap_or_default(), priority)
                )
            },
        }
    }

    pub fn start(&self) {
        self.0.iter().all(|lib| {
            lib.start();
            true
        });
    }
}

/// A trait for giving a type a useful default value.
impl Default for Compositer {

    /// The constructor `default` returns a Compositer prepared with
    /// the libraries from the source directory.
    fn default() -> Compositer {
        let mut compositer: Compositer = Compositer(
            BinaryHeap::with_capacity(SPEC_CAPACITY)
        );

        if let Some(mut paths) = fs::read_dir(compositer.source().join("lib"))
                                                                 .ok() {
          paths.all(|path| {
            if let Some(entry) = path.ok() {
              if let Some(path) = entry.path().file_stem() {
                compositer.mount(path, None).is_ok()
              } else { true }
            } else { true }
          });
        }
        compositer
    }
}