cargo-rail 0.31.1

Cargo-native Rust workspace engine for affected CI, Rust source-surface analysis, compiler reuse, dependency coherence, exact-SHA releases, and split/sync
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
//! Typed `rail.toml` configuration and discovery.

pub(crate) mod migration;
pub(crate) mod plan;
mod release;
pub(crate) mod schema;
mod split;
mod surface;
mod unify;

pub use plan::{
    CargoPrerequisiteConfig, CargoRootConfig, CargoTargetRootConfig, PlanConfig, PlanWorkConfig, PlanWorkScope,
};
pub use release::{
    ChangelogConfig, ChangelogFilters, ChangelogRelativeTo, ChangelogShape, CommitPolicy, CrateReleaseConfig,
    GroupSpec, Pre1BreakingBump, ReleaseArtifacts, ReleaseAsset, ReleaseConfig, ReleaseRegistryPublication,
    ReleaseRemoteEffects, ReleaseSource, RequireChangeFiles, SemverCheckPolicy,
};
pub use split::{CrateSplitConfig, SplitConfig, SplitMode, WorkspaceMode};
pub use surface::{
    SurfaceConfig, SurfaceConsumerScope, SurfaceCrateVisibility, SurfaceDoctest, SurfaceDoctestCoverage,
    SurfaceExclude, SurfaceExternal, SurfaceFeatureProfile, SurfaceLintDirective, SurfaceLintLevel, SurfaceOverride,
    SurfaceProduct, SurfaceTargetSelection,
};
pub use unify::{
    CompilerTargetSelection, ConsumerScope, ExactPinHandling, MajorVersionConflict, MsrvPolicy, MsrvSource,
    TransitiveFeatureHost, TransitivePinning, UnifyConfig,
};

use crate::error::{ConfigError, RailError, RailResult};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

/// Configuration for cargo-rail
/// Searched in order: rail.toml, .rail.toml, .cargo/rail.toml, .config/rail.toml
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RailConfig {
    /// Target triples for multi-platform validation (workspace-wide)
    /// Detected via `cargo rail init`, used by multiple commands
    #[serde(default)]
    pub targets: Vec<String>,
    /// Dependency unification settings
    #[serde(default)]
    pub unify: UnifyConfig,
    /// Release management settings
    #[serde(default)]
    pub release: ReleaseConfig,
    /// Rust source-surface analysis policy
    #[serde(default)]
    pub surface: SurfaceConfig,
    /// Input-only declarations for repository-owned planner work.
    #[serde(default)]
    pub plan: PlanConfig,
    /// Per-crate configuration (overrides workspace defaults)
    #[serde(default)]
    pub crates: BTreeMap<String, CrateConfig>,
}

/// Per-crate configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CrateConfig {
    /// Split/sync configuration for this crate
    pub split: Option<CrateSplitConfig>,
    /// Release configuration for this crate
    pub release: Option<CrateReleaseConfig>,
    /// Changelog configuration for this crate
    pub changelog: Option<ChangelogConfig>,
}

/// Result of attempting to load configuration
#[derive(Debug)]
pub enum ConfigLoadResult {
    /// Config loaded successfully
    Loaded(Box<RailConfig>),
    /// Config file found but failed to parse
    ParseError {
        /// Path to the config file that failed to parse
        path: PathBuf,
        /// Error message describing the parse failure
        message: String,
    },
    /// No config file found
    NotFound,
}

/// One parsed source and its effective policy. Source bytes remain owned by the caller.
#[derive(Debug)]
pub(crate) struct DecodedConfig {
    pub(crate) config: RailConfig,
    pub(crate) document: toml_edit::DocumentMut,
}

/// How decoding treats keys that an earlier release removed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RetiredKeys {
    /// Name the release and the action; consuming commands use this.
    Reject,
    /// Delete removable retired keys, which have no current meaning. Migration and
    /// historical planning use this; a key that needs a manual edit is still rejected.
    Strip,
}

/// Decode captured input using the current configuration contract.
pub(crate) fn decode(bytes: &[u8]) -> RailResult<DecodedConfig> {
    decode_with(bytes, RetiredKeys::Reject)
}

/// Decode captured input, treating retired keys as `retired` selects.
pub(crate) fn decode_with(bytes: &[u8], retired: RetiredKeys) -> RailResult<DecodedConfig> {
    decode_all(bytes, retired).map_err(|errors| match combine_errors(errors) {
        Err(error) => error,
        Ok(()) => RailError::message("configuration failed to decode"),
    })
}

/// Decode captured input and return every independent decode error, so validation can report each one.
pub(crate) fn decode_all(bytes: &[u8], retired: RetiredKeys) -> Result<DecodedConfig, Vec<RailError>> {
    let content = std::str::from_utf8(bytes)
        .map_err(|error| vec![RailError::message(format!("configuration is not valid UTF-8: {error}"))])?;
    let mut document: toml_edit::DocumentMut = content
        .parse()
        .map_err(|error: toml_edit::TomlError| vec![RailError::message(error.to_string())])?;
    if retired == RetiredKeys::Strip {
        migration::strip_retired(&mut document);
    }
    let config = RailConfig::from_document(document.clone())
        .map_err(|errors| errors.into_iter().map(RailError::message).collect::<Vec<_>>())?;
    Ok(DecodedConfig { config, document })
}

/// Decode a file while retaining its exact bytes for capture and drift validation.
pub(crate) fn load_decoded(path: &Path) -> RailResult<(DecodedConfig, Vec<u8>)> {
    load_decoded_with(path, RetiredKeys::Reject)
}

/// Decode a file with an explicit retired-key treatment, retaining its exact bytes.
pub(crate) fn load_decoded_with(path: &Path, retired: RetiredKeys) -> RailResult<(DecodedConfig, Vec<u8>)> {
    let bytes =
        fs::read(path).map_err(|error| RailError::message(format!("failed to read {}: {error}", path.display())))?;
    let decoded =
        decode_with(&bytes, retired).map_err(|error| error.context(format!("configuration {}", path.display())))?;
    Ok((decoded, bytes))
}

/// Report independent configuration errors together; a single error is returned unchanged.
pub(crate) fn combine_errors(mut errors: Vec<RailError>) -> RailResult<()> {
    match errors.len() {
        0 => Ok(()),
        1 => Err(errors.remove(0)),
        count => Err(RailError::message(format!(
            "{count} configuration errors:\n{}",
            errors
                .iter()
                .map(|error| format!("  - {error}"))
                .collect::<Vec<_>>()
                .join("\n")
        ))),
    }
}

pub(crate) fn workspace_context_required(field: &str) -> RailError {
    RailError::message(format!(
        "{field} requires Cargo workspace context; inspect a configuration file in its owning workspace"
    ))
}

impl RailConfig {
    fn from_document(doc: toml_edit::DocumentMut) -> Result<Self, Vec<String>> {
        // Report every unknown key at once; a key below a reported one adds nothing.
        let mut errors = Vec::new();
        let mut reported = Vec::<schema::ConfigPath>::new();
        for path in schema::document_paths(&doc) {
            if schema::is_known_config_path(&path)
                || reported
                    .iter()
                    .any(|parent| path.segments().starts_with(parent.segments()))
            {
                continue;
            }
            if let Some((retired, key)) = schema::retired_key(&path) {
                let action = if retired.removable {
                    "`cargo rail config migrate` previews its removal"
                } else {
                    "change it by hand"
                };
                errors.push(format!(
                    "configuration key '{key}' was removed in Cargo-Rail {}; {}; {action}",
                    retired.removed_in, retired.instead
                ));
                reported.push(key);
            } else {
                errors.push(format!(
                    "unknown configuration key '{path}'; run `cargo rail config explain --all` with supported configuration to inspect current fields"
                ));
                reported.push(path);
            }
        }
        if !errors.is_empty() {
            return Err(errors);
        }
        toml_edit::de::from_document(doc).map_err(|error| vec![error.to_string()])
    }

    /// Validate policy independently of any filesystem or workspace membership.
    ///
    /// Independent sections are all checked. One violation is returned unchanged; several are reported together.
    pub(crate) fn validate_policy(&self) -> RailResult<()> {
        combine_errors(self.policy_errors())
    }

    /// Every independent workspace-free policy violation: the first error of each section.
    pub(crate) fn policy_errors(&self) -> Vec<RailError> {
        let mut checks = vec![
            self.plan.validate().map_err(RailError::Config),
            self.surface
                .validate()
                .and_then(|()| self.surface.validate_workspace_targets(&self.targets))
                .map_err(RailError::Config),
            self.unify
                .validate_workspace_targets(&self.targets)
                .and_then(|()| self.unify.validate_policy())
                .map_err(RailError::Config),
            self.release.validate_policy().map_err(RailError::Config),
            crate::release::changelog::ChangelogSpec::resolve(&self.release.changelog, None).map(drop),
        ];
        checks.extend(self.build_split_configs().iter().map(SplitConfig::validate));
        checks.extend(
            self.crates
                .values()
                .filter_map(|config| config.changelog.as_ref())
                .map(|config| {
                    crate::release::changelog::ChangelogSpec::resolve(&self.release.changelog, Some(config)).map(drop)
                }),
        );
        for (name, config) in &self.crates {
            if config
                .release
                .as_ref()
                .and_then(|config| config.tag_format.as_deref())
                .is_some_and(|format| format.trim().is_empty())
            {
                checks.push(Err(RailError::Config(ConfigError::InvalidField {
                    field: format!("crates.{name}.release.tag_format"),
                    reason: "tag_format cannot be empty".into(),
                })));
            }
        }
        checks.into_iter().filter_map(Result::err).collect()
    }

    /// A standalone source cannot claim validation of repository-dependent policy.
    pub(crate) fn validate_without_workspace(&self) -> RailResult<()> {
        self.validate_policy()?;
        if self.unify.transitive_host_path().is_some() {
            return Err(workspace_context_required("unify.transitive_pinning.host"));
        }
        if self
            .crates
            .values()
            .any(|config| config.split.is_some() || config.release.is_some() || config.changelog.is_some())
            || !self.release.version_groups.is_empty()
            || matches!(&self.release.require_change_files, RequireChangeFiles::Crates(names) if !names.is_empty())
        {
            return Err(workspace_context_required("package selection"));
        }
        if !self.targets.is_empty() {
            crate::targets::validate_targets(&self.targets)?;
        }
        Ok(())
    }

    /// Validate every semantic configuration rule available at this boundary.
    pub(crate) fn validate(
        &self,
        workspace_root: &Path,
        workspace_members: Option<&[String]>,
    ) -> RailResult<Vec<String>> {
        self.validate_policy()?;
        self.validate_workspace(workspace_root, workspace_members)
    }

    pub(crate) fn release_warnings(&self, members: &[String]) -> RailResult<Vec<String>> {
        let mut warnings = self.release.validate(members).map_err(RailError::Config)?;
        let mut namespaces = std::collections::HashSet::new();
        let collision = members.iter().any(|name| {
            !namespaces.insert(
                self.release_tag_format_override(name)
                    .unwrap_or(&self.release.tag_format)
                    .replace("{crate}", name)
                    .replace("{prefix}", &self.release.tag_prefix)
                    .replace("{version}", "*"),
            )
        });
        if !collision {
            warnings.retain(|warning| !warning.starts_with("release.tag_format does not contain {crate}"));
        } else if self.release.tag_format.contains("{crate}") {
            warnings
                .push("crate release tag formats share a namespace; choose a distinct tag line for each crate".into());
        }
        for (name, config) in &self.crates {
            if let Some(format) = config.release.as_ref().and_then(|config| config.tag_format.as_ref())
                && !format.contains("{version}")
            {
                warnings.push(format!(
                    "crates.{name}.release.tag_format does not contain {{version}}; tags may not identify releases"
                ));
            }
        }
        Ok(warnings)
    }

    pub(crate) fn release_tag_format_override(&self, name: &str) -> Option<&str> {
        self.crates
            .get(name)
            .and_then(|config| config.release.as_ref())
            .and_then(|config| config.tag_format.as_deref())
    }

    /// Validate repository-bound rules for policy whose [`Self::validate_policy`] passed.
    pub(crate) fn validate_workspace(
        &self,
        workspace_root: &Path,
        workspace_members: Option<&[String]>,
    ) -> RailResult<Vec<String>> {
        self.unify.validate_host(workspace_root).map_err(RailError::Config)?;
        let Some(workspace_members) = workspace_members else {
            return Ok(Vec::new());
        };
        if !self.targets.is_empty() {
            crate::targets::validate_targets(&self.targets)?;
        }
        let warnings = self.release_warnings(workspace_members)?;
        for (crate_name, crate_config) in &self.crates {
            // A split table may name a combined-repository boundary rather
            // than one Cargo package. Per-package release/changelog tables
            // without that boundary must still resolve to a real member.
            if crate_config.split.is_none()
                && (crate_config.release.is_some() || crate_config.changelog.is_some())
                && !workspace_members.contains(crate_name)
            {
                return Err(RailError::Config(ConfigError::CrateNotFound {
                    name: crate_name.clone(),
                }));
            }
        }
        for split in self.build_split_configs() {
            if let Some(member) = split.members.iter().find(|member| !workspace_members.contains(*member)) {
                return Err(RailError::Config(ConfigError::CrateNotFound { name: member.clone() }));
            }
        }
        Ok(warnings)
    }

    /// Load policy without Cargo discovery, retaining the captured bytes.
    pub(crate) fn load_path_with_bytes(path: &Path) -> RailResult<(Self, Vec<u8>)> {
        let (decoded, bytes) = load_decoded(path)?;
        Ok((decoded.config, bytes))
    }

    /// Find config file in search order: rail.toml, .rail.toml, .cargo/rail.toml, .config/rail.toml
    ///
    /// On Windows, this handles path canonicalization issues (UNC paths, 8.3 short names)
    /// by checking both the original path and its parent's canonicalization.
    pub fn find_config_path(path: &Path) -> Option<PathBuf> {
        let candidates = [
            path.join("rail.toml"),
            path.join(".rail.toml"),
            path.join(".cargo").join("rail.toml"),
            path.join(".config").join("rail.toml"),
        ];

        // First, try the candidates as-is
        if let Some(found) = candidates.iter().find(|p| match p.symlink_metadata() {
            Ok(_) => true,
            Err(error) => error.kind() != std::io::ErrorKind::NotFound,
        }) {
            return Some(found.to_path_buf());
        }

        // Cargo and Win32 can expose one directory through long and 8.3 spellings.
        // Search the canonical spelling and enumerate entries before declaring the config absent.
        #[cfg(target_os = "windows")]
        {
            if let Ok(canonical) = path.canonicalize() {
                let canonical_candidates = [
                    canonical.join("rail.toml"),
                    canonical.join(".rail.toml"),
                    canonical.join(".cargo").join("rail.toml"),
                    canonical.join(".config").join("rail.toml"),
                ];
                if let Some(found) = canonical_candidates.iter().find(|p| match p.symlink_metadata() {
                    Ok(_) => true,
                    Err(error) => error.kind() != std::io::ErrorKind::NotFound,
                }) {
                    return Some(found.to_path_buf());
                }
            }

            if let Ok(entries) = std::fs::read_dir(path) {
                for entry in entries.flatten() {
                    let file_name = entry.file_name();
                    let file_name_str = file_name.to_string_lossy();

                    if file_name_str == "rail.toml" || file_name_str == ".rail.toml" {
                        return Some(entry.path());
                    }
                }
            }

            for subdir in &[".cargo", ".config"] {
                let subdir_path = path.join(subdir);
                if let Ok(entries) = std::fs::read_dir(&subdir_path) {
                    for entry in entries.flatten() {
                        let file_name = entry.file_name();
                        if file_name.to_string_lossy() == "rail.toml" {
                            return Some(entry.path());
                        }
                    }
                }
            }
        }

        None
    }

    /// Load config from rail.toml (searches multiple locations).
    ///
    /// Searches: `rail.toml`, `.rail.toml`, `.cargo/rail.toml`, `.config/rail.toml`
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError::NotFound`] if no config file exists.
    ///
    /// Returns [`ConfigError::ParseError`] if the config file cannot be read or parsed.
    pub fn load(path: &Path) -> RailResult<Self> {
        match Self::try_load(path) {
            ConfigLoadResult::Loaded(config) => Ok(*config),
            ConfigLoadResult::ParseError { path, message } => {
                Err(RailError::Config(ConfigError::ParseError { path, message }))
            }
            ConfigLoadResult::NotFound => Err(RailError::Config(ConfigError::NotFound {
                workspace_root: path.to_path_buf(),
            })),
        }
    }

    /// Try to load config, returning a result that distinguishes between
    /// "not found" and "parse error" without Cargo discovery.
    pub fn try_load(path: &Path) -> ConfigLoadResult {
        let config_path = match Self::find_config_path(path) {
            Some(p) => p,
            None => return ConfigLoadResult::NotFound,
        };

        match Self::load_path_with_bytes(&config_path) {
            Ok((config, _)) => ConfigLoadResult::Loaded(Box::new(config)),
            Err(error) => ConfigLoadResult::ParseError {
                path: config_path,
                message: error.to_string(),
            },
        }
    }

    /// Get all crates that have split configuration
    pub fn get_split_crates(&self) -> Vec<(&str, &CrateSplitConfig)> {
        self.crates
            .iter()
            .filter_map(|(name, config)| config.split.as_ref().map(|split| (name.as_str(), split)))
            .collect()
    }

    /// Build all SplitConfigs from unified crate config
    pub fn build_split_configs(&self) -> Vec<SplitConfig> {
        self.crates
            .iter()
            .filter_map(|(name, config)| {
                config.split.as_ref().map(|split_cfg| {
                    split::build_split_config(
                        name.clone(),
                        split_cfg,
                        config.release.as_ref().map(|r| r.publish),
                        config.changelog.as_ref(),
                    )
                })
            })
            .collect()
    }
}