semver-sync 0.1.2

Keep one version across every crate in a cargo workspace; bumps are checked as docker tags before any manifest is written.
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Reading the settings a run works from, and writing the file `ss config`
//! makes.

use std::io::{ErrorKind, Write};
use std::path::{Path, PathBuf};

use serde::Deserialize;
use toml_edit::de;

use crate::Result;
use crate::workspace;

/// The names checked in every directory, plain before dotted.
const NAMES: [&str; 2] = ["semver-sync.toml", ".semver-sync.toml"];

/// The whole file `ss config` writes: every setting at the value a run reads
/// when no file is there at all, and the order the files are read in.
const SCAFFOLD: &str = "\
# semver-sync configuration.
#
# The first file that exists is the one read:
#   1. the repo root: semver-sync.toml, then .semver-sync.toml
#   2. $HOME: semver-sync.toml, then .semver-sync.toml
#   3. the user config dir ($XDG_CONFIG_HOME, else $HOME/.config): the same two
#      names
#
# So a repo can say something different from the machine it sits on.

# Tag the version as v<VERSION>, then push the commits and the tag with them.
# The tag lands on the commit you are standing on: commit what a bump wrote
# first when the tag has to carry it.
git-tag = false
";

/// The settings a run reads, from the one file that wins.
#[derive(Debug, Default)]
pub struct Config {
    /// Where they came from. Empty in the default, which is what a run reads
    /// when no file is there at all.
    pub path: PathBuf,
    /// Tag the version `v<VERSION>`, then push the commits and the tag.
    pub git_tag: bool,
}

/// The keys a config file may name. One it does not know is an error instead
/// of something to walk past: a setting the tool never read is the one kind of
/// wrong a user cannot see for themselves.
#[derive(Default, Deserialize)]
#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
struct Settings {
    git_tag: bool,
}

/// What a run of `ss config` did to a directory.
#[derive(Debug, PartialEq, Eq)]
pub enum Scaffold {
    Written { path: PathBuf },
    Existing { path: PathBuf },
}

impl Config {
    /// The candidate that wins: the repo's own file over the user's, so a
    /// checkout can say something different from the machine it sits on.
    ///
    /// A file that does not parse is an error, not a miss. Reading the one
    /// behind it would quietly drop the settings written in it.
    pub fn discover() -> Result<Option<Self>> {
        find(workspace::repo_root().ok().as_deref())
    }

    /// The same search for a run that already has a workspace, so it does not
    /// ask cargo where the repo root is a second time.
    pub fn from_repo(repo: &Path) -> Result<Option<Self>> {
        find(Some(repo))
    }
}

fn find(repo: Option<&Path>) -> Result<Option<Config>> {
    search(&candidates(
        repo,
        home().as_deref(),
        config_dir().as_deref(),
    ))
}

/// Write the config file next to the workspace root, or in the user config dir
/// for `--global`.
pub fn scaffold(global: bool) -> Result<Scaffold> {
    if global {
        let dir = config_dir().ok_or_else(|| {
            String::from("cannot find your config directory: set $XDG_CONFIG_HOME or $HOME")
        })?;

        return write_scaffold(&dir);
    }

    // Cargo decides the root, the same way every other command decides it.
    let root = workspace::repo_root().map_err(|err| {
        let way_out = "  run it inside a workspace, or pass --global for the user file";

        format!("cannot find the repo root: {err}\n{way_out}")
    })?;

    write_scaffold(&root)
}

/// Every file that could be read, the one that wins first.
fn candidates(repo: Option<&Path>, home: Option<&Path>, config_dir: Option<&Path>) -> Vec<PathBuf> {
    let mut paths = Vec::with_capacity(NAMES.len() * 3);

    for dir in [repo, home, config_dir] {
        let Some(dir) = dir else { continue };

        paths.extend(NAMES.iter().map(|name| dir.join(name)));
    }

    paths
}

/// The first candidate that is a real file. One that does not parse is the
/// error, not a reason to look further.
fn search(paths: &[PathBuf]) -> Result<Option<Config>> {
    for path in paths {
        let found = match std::fs::metadata(path) {
            Ok(found) => found,
            Err(err) if err.kind() == ErrorKind::NotFound => continue,
            Err(err) => return Err(format!("cannot read {}: {err}", path.display())),
        };

        if !found.is_file() {
            continue;
        }

        let text = std::fs::read_to_string(path)
            .map_err(|err| format!("cannot read {}: {err}", path.display()))?;
        let settings = de::from_str::<Settings>(&text)
            .map_err(|err| format!("cannot parse {}: {err}", path.display()))?;

        return Ok(Some(Config {
            path: path.clone(),
            git_tag: settings.git_tag,
        }));
    }

    Ok(None)
}

/// The file, written whole, in a directory holding no config file yet under
/// either of its names.
fn write_scaffold(dir: &Path) -> Result<Scaffold> {
    std::fs::create_dir_all(dir)
        .map_err(|err| format!("cannot create {}: {err}", dir.display()))?;

    // A dotted file already there is the config. A second name beside it would
    // only settle which of the two a run reads.
    for name in NAMES {
        let path = dir.join(name);

        if path.is_file() {
            return Ok(Scaffold::Existing { path });
        }
    }

    let path = dir.join(NAMES[0]);

    // `create_new` is the check as well as the write: an existing file is left
    // alone, including one that appeared a moment before.
    let mut file = match std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&path)
    {
        Ok(file) => file,
        Err(err) if err.kind() == ErrorKind::AlreadyExists => {
            return if path.is_file() {
                Ok(Scaffold::Existing { path })
            } else {
                Err(format!("{} is not a file", path.display()))
            };
        }
        Err(err) => return Err(format!("cannot write {}: {err}", path.display())),
    };

    file.write_all(SCAFFOLD.as_bytes())
        .map_err(|err| format!("cannot write {}: {err}", path.display()))?;

    Ok(Scaffold::Written { path })
}

fn home() -> Option<PathBuf> {
    absolute("HOME")
}

/// Where user configuration goes: `$XDG_CONFIG_HOME`, else `$HOME/.config`. A
/// relative one is not a config dir, so it does not hide the fallback.
fn config_dir() -> Option<PathBuf> {
    absolute("XDG_CONFIG_HOME").or_else(|| home().map(|home| home.join(".config")))
}

/// A directory from the environment, usable only if it is there and absolute.
fn absolute(var: &str) -> Option<PathBuf> {
    std::env::var_os(var)
        .map(PathBuf::from)
        .filter(|path| path.is_absolute())
}

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

    fn touch(path: &Path) {
        std::fs::write(path, "# nothing set\n").expect("write config");
    }

    #[test]
    fn the_repo_dir_is_searched_before_the_user_dirs() {
        let dirs = tempfile::tempdir().expect("temp dir");
        let repo = dirs.path().join("repo");
        let home = dirs.path().join("home");
        let config = dirs.path().join("config");

        let found = candidates(Some(&repo), Some(&home), Some(&config));

        assert_eq!(
            found,
            vec![
                repo.join("semver-sync.toml"),
                repo.join(".semver-sync.toml"),
                home.join("semver-sync.toml"),
                home.join(".semver-sync.toml"),
                config.join("semver-sync.toml"),
                config.join(".semver-sync.toml"),
            ]
        );
    }

    #[test]
    fn a_repo_with_no_config_file_falls_through_to_the_user_dir() {
        let dirs = tempfile::tempdir().expect("temp dir");
        let repo = dirs.path().join("repo");
        let home = dirs.path().join("home");
        std::fs::create_dir_all(&home).expect("create home");
        touch(&home.join(NAMES[1]));

        let found = search(&candidates(Some(&repo), Some(&home), None)).expect("search");

        // The repo holds neither name, so the dotted one in $HOME is the file.
        assert_eq!(found.map(|config| config.path), Some(home.join(NAMES[1])));
    }

    #[test]
    fn nothing_written_anywhere_is_no_configuration() {
        let dirs = tempfile::tempdir().expect("temp dir");

        let found = search(&candidates(
            Some(&dirs.path().join("repo")),
            Some(&dirs.path().join("home")),
            None,
        ))
        .expect("search");

        assert!(found.is_none());
    }

    #[test]
    fn a_file_that_is_not_toml_stops_the_search() {
        let dirs = tempfile::tempdir().expect("temp dir");
        let repo = dirs.path().join("repo");
        let home = dirs.path().join("home");
        std::fs::create_dir_all(&repo).expect("create repo");
        std::fs::create_dir_all(&home).expect("create home");
        std::fs::write(repo.join(NAMES[0]), "this is not toml = = 1\n").expect("write config");
        touch(&home.join(NAMES[0]));

        let err = search(&candidates(Some(&repo), Some(&home), None))
            .expect_err("a broken file is not skipped");

        assert!(
            err.contains(&repo.join(NAMES[0]).display().to_string()),
            "{err}"
        );
    }

    #[test]
    fn a_comment_only_file_is_configuration() {
        let dirs = tempfile::tempdir().expect("temp dir");
        let repo = dirs.path().join("repo");
        std::fs::create_dir_all(&repo).expect("create repo");
        std::fs::write(repo.join(NAMES[0]), "# only a note\n").expect("write config");

        let found = search(&candidates(Some(&repo), None, None))
            .expect("search")
            .expect("a file of comments is still the config file");

        // Nothing named in it is nothing set: these are the settings a run
        // reads when no file is there at all.
        assert_eq!(found.path, repo.join(NAMES[0]));
        assert!(!found.git_tag);
    }

    #[test]
    fn git_tag_comes_from_the_file_that_wins() {
        let dirs = tempfile::tempdir().expect("temp dir");
        let repo = dirs.path().join("repo");
        let home = dirs.path().join("home");
        std::fs::create_dir_all(&repo).expect("create repo");
        std::fs::create_dir_all(&home).expect("create home");
        std::fs::write(repo.join(NAMES[1]), "git-tag = true\n").expect("write repo config");
        std::fs::write(home.join(NAMES[0]), "git-tag = false\n").expect("write home config");

        let found = search(&candidates(Some(&repo), Some(&home), None))
            .expect("search")
            .expect("the repo has a config file");

        // The repo holds only the dotted name, and that file is the one read:
        // the plain one in $HOME behind it never is.
        assert_eq!(found.path, repo.join(NAMES[1]));
        assert!(found.git_tag);
    }

    #[test]
    fn a_setting_of_the_wrong_shape_is_an_error() {
        let dirs = tempfile::tempdir().expect("temp dir");
        let repo = dirs.path().join("repo");
        std::fs::create_dir_all(&repo).expect("create repo");
        std::fs::write(repo.join(NAMES[0]), "git-tag = \"yes\"\n").expect("write config");

        let err = search(&candidates(Some(&repo), None, None)).expect_err("a string is no boolean");

        assert!(err.contains("boolean"), "{err}");
    }

    #[test]
    fn a_key_that_names_no_setting_is_an_error() {
        let dirs = tempfile::tempdir().expect("temp dir");
        let repo = dirs.path().join("repo");
        std::fs::create_dir_all(&repo).expect("create repo");
        std::fs::write(repo.join(NAMES[0]), "git-taggable = true\n").expect("write config");

        let err = search(&candidates(Some(&repo), None, None))
            .expect_err("a misspelled key is not a key left out");

        // Walking past it would run the whole bump without the tag the user
        // thought they had asked for.
        assert!(err.contains("git-taggable"), "{err}");
    }

    #[test]
    fn scaffolding_writes_the_file_once() {
        let dirs = tempfile::tempdir().expect("temp dir");
        let repo = dirs.path().join("repo");

        let first = write_scaffold(&repo).expect("scaffold");
        let written = repo.join(NAMES[0]);
        let text = std::fs::read_to_string(&written).expect("read config");
        let second = write_scaffold(&repo).expect("scaffold again");

        assert_eq!(
            first,
            Scaffold::Written {
                path: written.clone()
            }
        );
        assert!(text.starts_with("# semver-sync configuration."));
        // A second run reports where the file is instead of filling in what
        // the user has since put in it.
        assert_eq!(
            second,
            Scaffold::Existing {
                path: written.clone()
            }
        );
        assert_eq!(
            std::fs::read_to_string(&written).expect("read config again"),
            text
        );

        // What the command writes is what a run then reads: the entry is there
        // to be edited, at the value a file not being there gives.
        let settings = search(&candidates(Some(&repo), None, None))
            .expect("search")
            .expect("the scaffold is a config file");
        assert!(!settings.git_tag);
    }

    #[test]
    fn a_dotted_file_there_already_is_the_config() {
        let dirs = tempfile::tempdir().expect("temp dir");
        let repo = dirs.path().join("repo");
        std::fs::create_dir_all(&repo).expect("create repo");
        touch(&repo.join(NAMES[1]));

        let outcome = write_scaffold(&repo).expect("scaffold");

        // A plain file beside it would only settle which of the two a run
        // reads, so what is there is what gets reported.
        assert_eq!(
            outcome,
            Scaffold::Existing {
                path: repo.join(NAMES[1])
            }
        );
        assert!(!repo.join(NAMES[0]).exists());
    }

    #[test]
    fn scaffolding_a_user_dir_creates_the_dir_too() {
        let dirs = tempfile::tempdir().expect("temp dir");
        let config = dirs.path().join(".config");

        let outcome = write_scaffold(&config.join("nested")).expect("scaffold");

        assert!(
            matches!(outcome, Scaffold::Written { .. }),
            "the config dir is usually not there yet"
        );
        assert!(config.join("nested").join(NAMES[0]).is_file());
    }

    #[test]
    fn a_directory_in_the_way_is_not_reported_as_the_file() {
        let dirs = tempfile::tempdir().expect("temp dir");
        let repo = dirs.path().join("repo");
        std::fs::create_dir_all(repo.join(NAMES[0])).expect("create dir in the way");

        let err = write_scaffold(&repo).expect_err("a dir is not a config file");

        assert!(err.contains("is not a file"), "{err}");
    }
}