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
use std::{
    self,
    ffi::{OsStr, OsString},
    io::Write,
    path::{Path, PathBuf},
    process::{Command, Stdio},
};

use std::borrow::Cow;
use std::fs::{read_to_string, File};
use std::io::Read;
use std::sync::Arc;
use toml_edit::{Array, Document, Item, Table};

#[derive(Clone)]
pub enum Channel {
    Stable,
    Beta,
    Nightly,
    Custom(String),
}

pub static CHANNEL_DEFAULT: Channel = Channel::Stable;
pub static ENV_CHANNEL: &'static str = "RSTEST_TEST_CHANNEL";

impl From<String> for Channel {
    fn from(value: String) -> Self {
        let s = value.to_string();
        match s.to_lowercase().as_str() {
            "stable" => Channel::Stable,
            "beta" => Channel::Beta,
            "nightly" => Channel::Nightly,
            _ => Channel::Custom(s),
        }
    }
}

impl Default for Channel {
    fn default() -> Self {
        std::env::var(ENV_CHANNEL)
            .ok()
            .map(Channel::from)
            .unwrap_or(CHANNEL_DEFAULT.clone())
    }
}

pub struct Project {
    pub name: OsString,
    root: PathBuf,
    channel: Channel,
    ws: Arc<std::sync::RwLock<()>>,
}

impl Project {
    const GLOBAL_TEST_ATTR: &'static str = "#![cfg(test)]";

    pub fn new<P: AsRef<Path>>(root: P) -> Self {
        Self {
            root: root.as_ref().to_owned(),
            name: "project".into(),
            channel: Default::default(),
            ws: Arc::new(std::sync::RwLock::new(())),
        }
        .create()
    }

    pub fn get_name(&self) -> Cow<str> {
        self.name.to_string_lossy()
    }

    pub fn subproject<O: AsRef<OsStr>>(&self, name: O) -> Self {
        let _guard = self.ws.write().expect("Cannot lock workspace resource");
        self.workspace_add(name.as_ref().to_str().unwrap());
        Self {
            root: self.path(),
            name: name.as_ref().to_owned(),
            channel: self.channel.clone(),
            ws: self.ws.clone(),
        }
        .create()
    }

    pub fn name<O: AsRef<OsStr>>(mut self, name: O) -> Self {
        self.name = name.as_ref().to_owned();
        self
    }

    pub fn path(&self) -> PathBuf {
        self.root.join(&self.name)
    }

    pub fn run_tests(&self) -> Result<std::process::Output, std::io::Error> {
        let _guard = self.ws.read().expect("Cannot lock workspace resource");
        if !self.has_test_global_attribute(self.code_path()) {
            self.add_test_global_attribute(self.code_path())
        }
        Command::new("cargo")
            .current_dir(&self.path())
            .arg(&self.cargo_channel_arg())
            .arg("test")
            .output()
    }

    pub fn compile(&self) -> Result<std::process::Output, std::io::Error> {
        let _guard = self.ws.read().expect("Cannot lock workspace resource");
        Command::new("cargo")
            .current_dir(&self.path())
            .arg("build")
            .output()
    }

    fn create(self) -> Self {
        match Command::new("cargo")
            .current_dir(&self.root)
            .arg("init")
            .arg(&self.name)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .unwrap()
            .wait()
            .unwrap()
            .code()
            .unwrap()
        {
            0 => {
                std::fs::File::create(self.code_path()).unwrap();
                self
            }

            code => panic!("cargo init return an error code: {}", code),
        }
    }

    fn has_test_global_attribute(&self, path: impl AsRef<Path>) -> bool {
        return read_to_string(&path)
            .unwrap()
            .starts_with(Self::GLOBAL_TEST_ATTR);
    }

    fn add_test_global_attribute(&self, path: impl AsRef<Path>) {
        let body = read_to_string(&path).unwrap();
        let mut out = std::fs::File::create(&path).unwrap();

        write!(out, "{}", Self::GLOBAL_TEST_ATTR).unwrap();
        write!(out, "{}", body).unwrap();
    }

    pub fn set_code_file<P: AsRef<Path>>(self, src: P) -> Self {
        std::fs::copy(src, self.code_path()).unwrap();
        self
    }

    pub fn append_code<S: AsRef<str>>(&self, code: S) {
        std::fs::OpenOptions::new()
            .append(true)
            .open(self.code_path())
            .unwrap()
            .write_all(code.as_ref().as_ref())
            .unwrap()
    }

    pub fn add_dependency(&self, crate_name: &str, attrs: &str) {
        let mut doc = self.read_cargo_toml();

        doc["dependencies"].or_insert(Item::Table(Table::new()))[crate_name]
            .or_insert(Item::Value(attrs.parse().unwrap()));

        self.save_cargo_toml(&doc);
    }

    pub fn add_local_dependency(&self, name: &str) {
        self.add_dependency(
            name,
            format!(r#"{{path="{}"}}"#, self.current_dir_str()).as_str(),
        );
    }

    fn workspace_add(&self, prj: &str) {
        let mut doc = self.read_cargo_toml();

        let members: Array = Array::default();

        doc["workspace"].or_insert(Item::Table(Table::new()))["members"]
            .or_insert(Item::Value(members.into()))
            .as_array_mut()
            .map(|members| members.push(prj));

        self.save_cargo_toml(&doc);
    }

    fn code_path(&self) -> PathBuf {
        self.path().join("src").join("lib.rs")
    }

    fn cargo_toml_path(&self) -> PathBuf {
        let mut path = self.path().clone();
        path.push("Cargo.toml");
        path
    }

    fn read_cargo_toml(&self) -> Document {
        let mut orig = String::new();
        File::open(self.cargo_toml_path())
            .expect("cannot open Cargo.toml")
            .read_to_string(&mut orig)
            .expect("cannot read Cargo.toml");

        orig.parse::<Document>().expect("invalid Cargo.toml")
    }

    fn save_cargo_toml(&self, doc: &Document) {
        File::create(self.cargo_toml_path())
            .expect("cannot update Cargo.toml")
            .write(doc.to_string().as_bytes())
            .expect("cannot write Cargo.toml");
    }

    fn current_dir_str(&self) -> String {
        std::env::current_dir()
            .unwrap()
            .as_os_str()
            .to_str()
            .unwrap()
            .to_owned()
    }

    fn cargo_channel_arg(&self) -> String {
        match &self.channel {
            Channel::Stable => "+stable".into(),
            Channel::Beta => "+beta".into(),
            Channel::Nightly => "+nightly".into(),
            Channel::Custom(name) => format!("+{}", name),
        }
    }
}