repoverse 0.1.6

Multi-repo workspace tool: keep many git repos in sync and roll changes up across dependency boundaries
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
//! `.repoverse.yaml` — intent (committed, hand-edited).

use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

pub const CONFIG_FILE: &str = ".repoverse.yaml";

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Config {
    pub version: u32,
    #[serde(default)]
    pub defaults: Defaults,
    #[serde(default)]
    pub remotes: BTreeMap<String, Remote>,
    /// Optional root-repo task overrides. These apply to workspace path `.`
    /// even when the root repo is not listed as a project.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub setup: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lint: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub test: Option<String>,
    #[serde(default)]
    pub projects: Vec<Project>,
    /// Repos this workspace materializes once and lends to consumers
    /// (explicit, not inferred — predictable under nested worktrees).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub provides: Vec<String>,
    /// Central shared-link table: every place a provided repo is symlinked.
    /// Source of truth; a `.repoverse.yaml` in a sub-repo overrides its
    /// subtree (nearest-config-wins).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub links: Vec<Link>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Link {
    /// `owner/repo` of the provided/shared repo.
    pub repo: String,
    /// Workspace-relative path where it is symlinked.
    pub at: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub branch: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Defaults {
    #[serde(default = "default_remote")]
    pub remote: String,
    /// Stable branch used as the PR base/mainline when a project does not
    /// override it. Falls back to `revision` for older configs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub main_branch: Option<String>,
    #[serde(default = "default_revision")]
    pub revision: String,
    #[serde(default)]
    pub scheme: Scheme,
}

impl Default for Defaults {
    fn default() -> Self {
        Defaults {
            remote: default_remote(),
            main_branch: None,
            revision: default_revision(),
            scheme: Scheme::default(),
        }
    }
}

fn default_remote() -> String {
    "github".to_string()
}
fn default_revision() -> String {
    "main".to_string()
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum Scheme {
    #[default]
    Ssh,
    Https,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Remote {
    /// Scheme-agnostic host, e.g. `github.com`.
    pub host: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum Submodules {
    #[default]
    None,
    Shallow,
    Recursive,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Project {
    /// `owner/repo`
    pub name: String,
    /// Workspace-relative path; `.` is the root/parent repo.
    pub path: String,
    /// Stable branch used as the PR base/mainline for this repo. This is
    /// distinct from `revision`, which is what the workspace checks out/uses.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub main_branch: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revision: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub remote: Option<String>,
    /// Optional source repo/remote used only for fetching upstream updates.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub upstream: Option<Upstream>,
    #[serde(default, skip_serializing_if = "is_default_submodules")]
    pub submodules: Submodules,
    /// Repos whose merged commits this project consumes (rollup graph).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub consumes: Vec<String>,
    /// CI mapping: which workflow/jobs map to local tasks.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ci: Option<CiMap>,
    /// Explicit task overrides (escape hatch).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub setup: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lint: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub test: Option<String>,
    /// Transitive deps lifted to one shared copy (fan-in >= 2).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub shared: Vec<SharedDep>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Upstream {
    /// `owner/repo` to fetch updates from. Defaults to the project `name`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Key in `remotes`; defaults to `upstream` when present, else defaults.remote.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub remote: Option<String>,
    /// Branch/revision to fetch. Defaults to project revision/default revision.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revision: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SharedDep {
    /// `owner/repo` — matched to a provider by normalized URL.
    pub name: String,
    /// Local path the consumer's build expects it at (the submodule path).
    pub path: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revision: Option<String>,
}

fn is_default_submodules(s: &Submodules) -> bool {
    *s == Submodules::None
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CiMap {
    pub workflow: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub setup_job: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lint_job: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub test_job: Option<String>,
}

impl Config {
    pub fn load(path: &Path) -> Result<Config> {
        let text =
            std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
        let cfg: Config =
            serde_yaml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?;
        cfg.validate()?;
        Ok(cfg)
    }

    /// Find `.repoverse.yaml` from `start` upward.
    pub fn discover(start: &Path) -> Option<PathBuf> {
        let mut dir = Some(start);
        while let Some(d) = dir {
            let c = d.join(CONFIG_FILE);
            if c.is_file() {
                return Some(c);
            }
            dir = d.parent();
        }
        None
    }

    pub fn validate(&self) -> Result<()> {
        if self.version != 1 {
            bail!("unsupported config version {} (expected 1)", self.version);
        }
        if !self.remotes.contains_key(&self.defaults.remote) {
            bail!(
                "defaults.remote `{}` is not defined in remotes",
                self.defaults.remote
            );
        }
        let mut seen_paths = std::collections::HashSet::new();
        for p in &self.projects {
            if p.name.is_empty() {
                bail!("project with empty name");
            }
            if !seen_paths.insert(&p.path) {
                bail!("duplicate project path `{}`", p.path);
            }
            if let Some(r) = &p.remote {
                if !self.remotes.contains_key(r) {
                    bail!("project `{}` references unknown remote `{}`", p.name, r);
                }
            }
            if let Some(upstream) = &p.upstream {
                if let Some(r) = upstream.remote.as_deref() {
                    if !self.remotes.contains_key(r) {
                        bail!(
                            "project `{}` references unknown upstream remote `{}`",
                            p.name,
                            r
                        );
                    }
                }
            }
        }
        for p in &self.projects {
            for c in &p.consumes {
                if !self.projects.iter().any(|x| &x.path == c || &x.name == c) {
                    bail!(
                        "project `{}` consumes `{}` which is not a known project",
                        p.name,
                        c
                    );
                }
            }
        }
        Ok(())
    }

    pub fn project_revision<'a>(&'a self, p: &'a Project) -> &'a str {
        p.revision.as_deref().unwrap_or(&self.defaults.revision)
    }

    pub fn project_main_branch<'a>(&'a self, p: &'a Project) -> &'a str {
        p.main_branch
            .as_deref()
            .or(self.defaults.main_branch.as_deref())
            .unwrap_or_else(|| self.project_revision(p))
    }

    pub fn project_remote<'a>(&'a self, p: &'a Project) -> Option<&'a Remote> {
        let key = p.remote.as_deref().unwrap_or(&self.defaults.remote);
        self.remotes.get(key)
    }
}

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

    fn sample() -> &'static str {
        r#"
version: 1
defaults:
  remote: github
  revision: main
  scheme: ssh
remotes:
  github:
    host: github.com
projects:
  - name: acme/lib
    path: lib
  - name: acme/app
    path: .
    consumes: [lib]
"#
    }

    #[test]
    fn parses_and_validates() {
        let cfg: Config = serde_yaml::from_str(sample()).unwrap();
        cfg.validate().unwrap();
        assert_eq!(cfg.projects.len(), 2);
        assert_eq!(cfg.project_revision(&cfg.projects[0]), "main");
        assert_eq!(cfg.project_main_branch(&cfg.projects[0]), "main");
    }

    #[test]
    fn main_branch_is_separate_from_revision() {
        let cfg: Config = serde_yaml::from_str(
            r#"
version: 1
defaults:
  main_branch: main
  revision: develop
remotes:
  github: { host: github.com }
projects:
  - name: acme/lib
    path: lib
  - name: acme/app
    path: app
    main_branch: stable
    revision: feature/app
"#,
        )
        .unwrap();
        cfg.validate().unwrap();
        assert_eq!(cfg.project_revision(&cfg.projects[0]), "develop");
        assert_eq!(cfg.project_main_branch(&cfg.projects[0]), "main");
        assert_eq!(cfg.project_revision(&cfg.projects[1]), "feature/app");
        assert_eq!(cfg.project_main_branch(&cfg.projects[1]), "stable");
    }

    #[test]
    fn rejects_bad_version() {
        let mut cfg: Config = serde_yaml::from_str(sample()).unwrap();
        cfg.version = 2;
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn rejects_unknown_consumes() {
        let cfg: Config = serde_yaml::from_str(
            r#"
version: 1
remotes:
  github: { host: github.com }
projects:
  - name: acme/app
    path: .
    consumes: [ghost]
"#,
        )
        .unwrap();
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn rejects_duplicate_paths() {
        let cfg: Config = serde_yaml::from_str(
            r#"
version: 1
remotes: { github: { host: github.com } }
projects:
  - name: acme/a
    path: x
  - name: acme/b
    path: x
"#,
        )
        .unwrap();
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn parses_project_upstream() {
        let cfg: Config = serde_yaml::from_str(
            r#"
version: 1
remotes:
  github: { host: github.com }
  upstream: { host: github.com }
projects:
  - name: fork/lib
    path: lib
    upstream:
      name: source/lib
      remote: upstream
      revision: stable
"#,
        )
        .unwrap();
        cfg.validate().unwrap();
        let upstream = cfg.projects[0].upstream.as_ref().unwrap();
        assert_eq!(upstream.name.as_deref(), Some("source/lib"));
        assert_eq!(upstream.remote.as_deref(), Some("upstream"));
        assert_eq!(upstream.revision.as_deref(), Some("stable"));
    }

    #[test]
    fn rejects_unknown_upstream_remote() {
        let cfg: Config = serde_yaml::from_str(
            r#"
version: 1
remotes:
  github: { host: github.com }
projects:
  - name: fork/lib
    path: lib
    upstream:
      remote: missing
"#,
        )
        .unwrap();
        assert!(cfg.validate().is_err());
    }
}