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
use std::fmt::Debug;
use std::fs::{self, File, OpenOptions};
use std::io::prelude::*;
use std::io::{Error as IoError, ErrorKind, SeekFrom};
use std::ops::Deref;
use std::path::{Path, PathBuf};

use crate::options::FileExistsBehaviour;
use crate::options::Options;
use crate::toml_editor;
use crate::toml_file::TomlFile;

#[derive(Debug)]
pub enum Error {
    FileAlreadyExists,
    GenericCreationError(IoError),
    ReadError(IoError),
    ParseError,
    WriteError(IoError),
}

pub struct Workspace {
    toml: TomlFile,
    options: Options,
}

impl Workspace {
    pub fn new(options: Options) -> Workspace {
        let path = &options.path;
        let toml = TomlFile::new(path.join(Path::new("Cargo.toml")));

        Workspace { toml, options }
    }

    pub fn toml(&self) -> &TomlFile {
        &self.toml
    }

    pub fn update_toml(&self) -> Result<TomlFile, Error> {
        self.create_path()
            .map_err(|err| Error::GenericCreationError(err))?;

        let mut sub_crates = self
            .find_sub_crates()
            .map_err(|err| Error::GenericCreationError(err))?;

        sub_crates.sort();

        let mut file = self.open_file()?;

        self.write_toml_to_file(&mut file, &sub_crates)
            .map(|_| self.toml.clone())
    }

    fn path(&self) -> &PathBuf {
        &self.options.path
    }

    fn create_path(&self) -> Result<(), IoError> {
        fs::create_dir_all(self.path())
    }

    fn find_sub_crates(&self) -> Result<Vec<String>, IoError> {
        let root = &self.options.path;
        let sub_toml_files = Workspace::search_for_cargo_files(root, 0)?;

        Ok(sub_toml_files
            .iter()
            .map(|p| {
                p.parent()
                    .unwrap()
                    .strip_prefix(root)
                    .unwrap()
                    .to_str()
                    .unwrap()
                    .to_string()
            })
            .collect())
    }

    fn search_for_cargo_files(dir: &PathBuf, depth: i32) -> Result<Vec<PathBuf>, IoError> {
        let mut results: Vec<PathBuf> = vec![];

        // do not look in the workspace root
        if depth > 0 {
            for path in fs::read_dir(dir)? {
                let path = path.unwrap().path();

                if path.is_file() {
                    match path.file_name() {
                        Some(p) if p == "Cargo.toml" => {
                            results.push(path);
                            break;
                        }
                        _ => (),
                    }
                }
            }
        }

        // do not look in sub directories after found a Cargo.toml
        if results.is_empty() {
            for path in fs::read_dir(dir)? {
                let path = path.unwrap().path();

                if path.is_dir() {
                    match path.file_name() {
                        Some(p) if p != "target" => {
                            results.extend(Workspace::search_for_cargo_files(&path, depth + 1)?);
                        }
                        _ => (),
                    }
                }
            }
        }

        Ok(results)
    }

    fn open_file(&self) -> Result<File, Error> {
        OpenOptions::new()
            .write(true)
            .read(self.options.existing_file_behaviour == FileExistsBehaviour::Update)
            .create_new(self.options.existing_file_behaviour.create_new())
            .create(self.options.existing_file_behaviour != FileExistsBehaviour::Update)
            .open(self.toml.deref())
            .map_err(|err| match err.kind() {
                ErrorKind::AlreadyExists => Error::FileAlreadyExists,
                _ => Error::GenericCreationError(err),
            })
    }

    fn write_toml_to_file(&self, file: &mut File, sub_crates: &[String]) -> Result<(), Error> {
        let toml_content = match self.options.existing_file_behaviour {
            FileExistsBehaviour::Update => {
                Workspace::read_toml(file).map_err(|err| Error::ReadError(err))?
            }
            _ => "".to_string(),
        };

        let new_file_content = toml_editor::toml_update(toml_content.as_str(), &sub_crates[..])
            .map_err(|_| Error::ParseError)?;

        Workspace::write_toml(file, new_file_content).map_err(|err| Error::WriteError(err))
    }

    fn write_toml(file: &mut File, toml: String) -> Result<(), IoError> {
        file.set_len(0)?; // in lieu of OpenOptions::truncate which would prevent reading
        file.seek(SeekFrom::Start(0))?;
        file.write_all(toml.as_bytes())
    }

    fn read_toml(file: &mut File) -> Result<String, IoError> {
        let mut toml = String::new();
        file.read_to_string(&mut toml)?;
        Ok(toml)
    }
}