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
use checksum::Checksum;
use core::{Range, RelativePath, RpPackage, Version};
use core::errors::*;
use index::{Deployment, Index};
use objects::{FileObjects, Objects};
use serde_json;
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};

/// Default to objects relative to index repo.
const DEFAULT_OBJECTS: &'static str = "./objects";
/// Index configuration file.
const CONFIG_JSON: &'static str = "config.json";
/// Name of metadata file for each package.
const METADATA_JSON: &'static str = "metadata.json";

fn default_objects() -> String {
    DEFAULT_OBJECTS.to_owned()
}

#[derive(Deserialize, Serialize)]
pub struct Config {
    #[serde(default = "default_objects")]
    objects: String,
}

pub struct FileIndex {
    path: PathBuf,
    config: Config,
}

impl FileIndex {
    pub fn new<P: AsRef<Path> + ?Sized>(path: &P) -> Result<FileIndex> {
        let config = read_config(path)?;

        Ok(FileIndex {
            path: path.as_ref().to_owned(),
            config: config,
        })
    }

    /// Path to root of file index
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// # read package metadata
    ///
    /// returns a tuple where the first is all matching deployments, and the second is a boolean
    /// indicating if some deployments have been omitted or not.
    fn read_package<F>(&self, package: &RpPackage, filter: F) -> Result<(Vec<Deployment>, bool)>
    where
        F: Fn(&Deployment) -> bool,
    {
        let path = self.path_for(package).join(METADATA_JSON);

        if !path.is_file() {
            return Ok((vec![], false));
        }

        let f = File::open(&path)?;
        let reader = BufReader::new(f);
        let mut out = Vec::new();
        let mut non_match = false;

        for (i, line) in reader.lines().enumerate() {
            let line = line?;

            let deployment: Deployment = serde_json::from_str(&line).map_err(|e| {
                format!(
                    "{}: bad deployment on line #{}: {}",
                    path.display(),
                    i + 1,
                    e
                )
            })?;

            if filter(&deployment) {
                out.push(deployment);
            } else {
                non_match = true;
            }
        }

        Ok((out, non_match))
    }

    fn write_package<I>(&self, package: &RpPackage, deployments: I) -> Result<()>
    where
        I: IntoIterator<Item = Deployment>,
    {
        let target = self.path_for(package).join(METADATA_JSON);
        debug!("writing: {}", target.display());

        let mut tmp_target = target.clone();
        tmp_target.set_extension(".tmp");

        if let Some(parent) = tmp_target.parent() {
            if !parent.is_dir() {
                debug!("creating directory: {}", parent.display());
                fs::create_dir_all(parent)?;
            }
        }

        {
            let mut f = File::create(&tmp_target)?;
            let it = deployments.into_iter();

            for deployment in it {
                writeln!(f, "{}", serde_json::to_string(&deployment)?)?;
            }
        }

        fs::rename(&tmp_target, &target)?;
        Ok(())
    }

    fn path_for(&self, package: &RpPackage) -> PathBuf {
        package
            .parts
            .iter()
            .fold(self.path.clone(), |path, next| path.join(next))
    }
}

impl Index for FileIndex {
    fn resolve(&self, package: &RpPackage, range: &Range) -> Result<Vec<Deployment>> {
        self.read_package(package, |d| range.matches(&d.version))
            .map(|r| r.0)
    }

    fn all(&self, package: &RpPackage) -> Result<Vec<Deployment>> {
        self.read_package(package, |_| true)
            .map(|r| r.0)
            .map(|all| {
                // get the last deployment available
                all.into_iter().collect::<Vec<_>>()
            })
    }

    fn put_version(
        &self,
        checksum: &Checksum,
        package: &RpPackage,
        version: &Version,
        force: bool,
    ) -> Result<()> {
        let (mut deployments, other_match) = self.read_package(package, |d| d.version != *version)?;

        if other_match {
            if !force {
                return Err(format!("{}@{}: already published", package, version).into());
            }
        }

        deployments.push(Deployment::new(version.clone(), checksum.clone()));
        deployments.sort_by(|a, b| a.version.cmp(&b.version));
        self.write_package(package, deployments)?;
        Ok(())
    }

    fn get_deployments(&self, package: &RpPackage, version: &Version) -> Result<Vec<Deployment>> {
        self.read_package(package, |d| d.version == *version)
            .map(|r| r.0)
    }

    fn objects_from_index(&self, relative_path: &RelativePath) -> Result<Box<Objects>> {
        let path = relative_path.to_path(&self.path);
        Ok(Box::new(FileObjects::new(&path)))
    }

    fn objects_url(&self) -> Result<&str> {
        Ok(self.config.objects.as_str())
    }
}

pub fn init_file_index<P: AsRef<Path> + ?Sized>(path: &P) -> Result<()> {
    let path = path.as_ref();

    if !path.is_dir() {
        fs::create_dir_all(path)?;
    }

    let config_path = path.join(CONFIG_JSON);

    if !config_path.is_file() {
        let mut f = File::create(config_path)?;
        let config = Config {
            objects: DEFAULT_OBJECTS.to_owned(),
        };
        let config_content = serde_json::to_value(&config)?;
        writeln!(f, "{:#}", config_content)?;
    }

    Ok(())
}

/// Read the configuration from the given path.
fn read_config<P: AsRef<Path> + ?Sized>(path: &P) -> Result<Config> {
    let path = path.as_ref();

    if !path.is_dir() {
        return Err(format!("{}: not a directory", path.display()).into());
    }

    let config_path = path.join(CONFIG_JSON);

    if !config_path.is_file() {
        return Err(format!("{}: not an index, missing {}", path.display(), CONFIG_JSON).into());
    }

    let mut f = File::open(&config_path)
        .map_err(|e| format!("failed to open {}: {}", config_path.display(), e))?;

    let mut content = String::new();
    f.read_to_string(&mut content)?;

    let config: Config = serde_json::from_str(content.as_str())
        .map_err(|e| format!("{}: bad config file: {}", config_path.display(), e))?;

    Ok(config)
}