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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
#[macro_use]
extern crate handlebars;
extern crate hex;
extern crate itertools;
extern crate petgraph;
extern crate semver;
extern crate serde;
extern crate sha2;
extern crate toml;
extern crate toml_edit;
extern crate vfs;

use std::collections::HashMap;
use std::io;

use semver::{BuildMetadata, Prerelease, Version};
use serde::Deserialize;
use toml_edit::{value, Document};
use vfs::VfsPath;

pub mod brew;
pub mod cargo;
pub mod git;
pub mod hash;
mod pkg;
mod resource;
pub mod scoop;
mod version_iter;
pub mod workflow;

#[cfg(test)] // <-- not needed in integration tests
extern crate spectral;

#[cfg(test)] // <-- not needed in integration tests
#[macro_use]
extern crate mockall;

#[cfg(test)] // <-- not needed in integration tests
extern crate rstest;

#[cfg(test)]
use mockall::{automock, predicate::*};

pub type AnyError = Box<dyn std::error::Error>;
pub type Result<T> = core::result::Result<T, AnyError>;

const CARGO_CONFIG: &str = "Cargo.toml";
const VERSION: &str = "version";
const PACK: &str = "package";
const DEPS: &str = "dependencies";

#[derive(Default, Eq, PartialEq, Debug)]
pub struct PublishOptions<'a> {
    pub crate_to_publish: Option<&'a str>,
    pub all_features: bool,
}

#[cfg_attr(test, automock)]
pub trait Publisher {
    fn publish<'a>(&'a self, path: &'a str, options: PublishOptions<'a>) -> io::Result<()>;
}

#[cfg_attr(test, automock)]
pub trait Vcs {
    fn commit(&self, path: &str, message: &str) -> io::Result<()>;
    fn create_tag(&self, path: &str, tag: &str) -> io::Result<()>;
    fn push_tag(&self, path: &str, tag: &str) -> io::Result<()>;
}

pub fn update_configs<I>(path: &VfsPath, iter: &mut I, incr: Increment) -> Result<Version>
where
    I: Iterator<Item = CrateVersion>,
{
    let result = Version::parse("0.0.0")?;

    let result = iter
        .by_ref()
        .map(|config| update_config(path, &config, incr))
        .filter(|v| v.is_ok())
        .map(|r| r.unwrap())
        .fold(result, |r, v| r.max(v));

    Ok(result)
}

pub fn update_config(path: &VfsPath, version: &CrateVersion, incr: Increment) -> Result<Version> {
    let working_config_path: &VfsPath;
    let member_config_path: VfsPath;
    if version.path.is_empty() {
        working_config_path = path;
    } else {
        let parent = path.parent().unwrap();
        member_config_path = parent.join(&version.path)?.join(CARGO_CONFIG)?;
        working_config_path = &member_config_path;
    }

    let mut file = working_config_path.open_file()?;
    let mut content = String::new();
    file.read_to_string(&mut content)?;

    let mut doc = content.parse::<Document>()?;

    let mut result = Version::parse("0.0.0")?;

    for place in &version.places {
        match place {
            Place::Package(ver) => {
                let v = increment(ver, incr)?;
                result = result.max(v);
                doc[PACK][VERSION] = value(result.to_string());
            }
            Place::Dependency(n, ver) => {
                let v = increment(ver, incr)?;
                result = result.max(v);
                doc[DEPS][n][VERSION] = value(result.to_string());
            }
        }
    }

    let mut f = working_config_path.create_file()?;
    let changed = doc.to_string();
    f.write_all(changed.as_bytes())?;
    Ok(result)
}

fn increment(v: &str, i: Increment) -> Result<Version> {
    let mut v = Version::parse(v)?;
    match i {
        Increment::Major => increment_major(&mut v),
        Increment::Minor => increment_minor(&mut v),
        Increment::Patch => increment_patch(&mut v),
    }
    Ok(v)
}

fn new_cargo_config_path(root: &VfsPath) -> Option<VfsPath> {
    join(root, CARGO_CONFIG)
}

fn join(p: &VfsPath, other: &str) -> Option<VfsPath> {
    match p.join(other) {
        Ok(r) => Some(r),
        Err(_) => None,
    }
}

fn increment_patch(v: &mut Version) {
    v.patch += 1;
    v.pre = Prerelease::EMPTY;
    v.build = BuildMetadata::EMPTY;
}

fn increment_minor(v: &mut Version) {
    v.minor += 1;
    v.patch = 0;
    v.pre = Prerelease::EMPTY;
    v.build = BuildMetadata::EMPTY;
}

fn increment_major(v: &mut Version) {
    v.major += 1;
    v.minor = 0;
    v.patch = 0;
    v.pre = Prerelease::EMPTY;
    v.build = BuildMetadata::EMPTY;
}

#[derive(Deserialize)]
struct WorkspaceConfig {
    workspace: Workspace,
}

#[derive(Deserialize)]
struct Workspace {
    members: Vec<String>,
}

#[derive(Deserialize, Default)]
struct CrateConfig {
    package: Package,
    dependencies: Option<HashMap<String, Dependency>>,
}

impl CrateConfig {
    pub fn open(path: &VfsPath) -> Result<Self> {
        let mut file = path.open_file()?;
        let mut content = String::new();
        file.read_to_string(&mut content)?;
        let conf: CrateConfig = toml::from_str(&content)?;
        Ok(conf)
    }

    pub fn new_version(&self, path: String) -> CrateVersion {
        let places = vec![Place::Package(self.package.version.clone())];

        CrateVersion { places, path }
    }
}

#[derive(Deserialize, Default)]
struct Package {
    name: String,
    version: String,
    description: Option<String>,
    license: Option<String>,
    homepage: Option<String>,
}

#[derive(Deserialize, Debug)]
#[serde(untagged)]
enum Dependency {
    Plain(String),
    Optional(bool),
    Object(HashMap<String, Dependency>),
    List(Vec<Dependency>),
}

#[derive(Debug, Default)]
pub struct CrateVersion {
    path: String,
    places: Vec<Place>,
}

/// Place defines where to find version
#[derive(Debug)]
pub enum Place {
    /// Find version in package metadata (i.e. `package` section)
    Package(String),
    /// Find version in dependencies (i.e. `dependencies` section)
    Dependency(String, String),
}

#[derive(Copy, Clone, Debug)]
pub enum Increment {
    Major,
    Minor,
    Patch,
}

#[cfg(test)]
mod tests {
    use super::*;
    use rstest::*;
    use spectral::prelude::*;

    #[rstest]
    #[case::patch(Increment::Patch, "0.1.2")]
    #[case::minor(Increment::Minor, "0.2.0")]
    #[case::major(Increment::Major, "1.0.0")]
    #[trace]
    fn increment_tests(#[case] incr: Increment, #[case] expected: &str) {
        // Arrange
        let v = "0.1.1";

        // Act
        let actual = increment(v, incr).unwrap();

        // Assert
        assert_that!(actual).is_equal_to(Version::parse(expected).unwrap());
    }

    #[test]
    fn toml_parse_workspace() {
        // Arrange

        // Act
        let cfg: WorkspaceConfig = toml::from_str(WKS).unwrap();

        // Assert
        assert_eq!(2, cfg.workspace.members.len());
    }

    #[test]
    fn toml_parse_crate() {
        // Arrange

        // Act
        let cfg: CrateConfig = toml::from_str(SOLV).unwrap();

        // Assert
        let deps = cfg.dependencies.unwrap();
        assert_eq!("solv", cfg.package.name);
        assert_eq!("0.1.13", cfg.package.version);
        assert_eq!(6, deps.len());
        let solp = &deps["solp"];
        if let Dependency::Object(o) = solp {
            assert_eq!(2, o.len());
            assert!(o.contains_key(VERSION));
            assert!(o.contains_key("path"));
        }
    }

    #[test]
    fn toml_parse_crate_with_optional_deps() {
        // Arrange
        let conf = r#"[package]
name = "editorconfiger"
version = "0.1.9"
description = "Plain tool to validate and compare .editorconfig files"
authors = ["egoroff <egoroff@gmail.com>"]
keywords = ["editorconfig"]
homepage = "https://github.com/aegoroff/editorconfiger"
edition = "2021"
license = "MIT"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[build-dependencies] # <-- We added this and everything after!
lalrpop = "0.19"

[dependencies]
lalrpop-util  = { version = "0.19", features = ["lexer"] }
regex = "1"
jwalk = "0.6"
aho-corasick = "0.7"
nom = "7"
num_cpus = "1.13.0"

ansi_term = { version = "0.12", optional = true }
prettytable-rs = { version = "^0.8", optional = true }
clap = { version = "2", optional = true }

[dev-dependencies]
table-test = "0.2.1"
spectral = "0.6.0"
rstest = "0.12.0"

[features]
build-binary = ["clap", "ansi_term", "prettytable-rs"]

[[bin]]
name = "editorconfiger"
required-features = ["build-binary"]

[profile.release]
lto = true"#;

        // Act
        let cfg: CrateConfig = toml::from_str(conf).unwrap();

        // Assert
        let deps = cfg.dependencies.unwrap();
        assert_eq!("editorconfiger", cfg.package.name);
        assert_eq!("0.1.9", cfg.package.version);
        assert_eq!(9, deps.len());
        let ansi_term = &deps["ansi_term"];
        if let Dependency::Object(o) = ansi_term {
            assert_eq!(2, o.len());
            assert!(o.contains_key(VERSION));
            assert!(o.contains_key("optional"));
        }
    }

    const WKS: &str = r#"
[workspace]

members = [
    "solv",
    "solp",
]
        "#;

    const SOLV: &str = r#"
[package]
name = "solv"
description = "Microsoft Visual Studio solution validator"
repository = "https://github.com/aegoroff/solv"
version = "0.1.13"
authors = ["egoroff <egoroff@gmail.com>"]
edition = "2018"
license = "MIT"
workspace = ".."

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
prettytable-rs = "^0.8"
ansi_term = "0.12"
humantime = "2.1"
clap = "2"
fnv = "1"
solp = { path = "../solp/", version = "0.1.13" }

        "#;
}