crate-cli 10.1.7

A command-line tool for managing Cargo package lifecycles: version bump, workspace dependency sync, members-ordered publish and code formatting.
Documentation
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
use super::*;

/// Discover all packages in the workspace: every `[workspace.members]`
/// entry in declaration order, with the root package (when the workspace
/// root manifest also declares `[package]`) appended last.
///
/// # Arguments
///
/// - `&Path`: Path to workspace root Cargo.toml
///
/// # Returns
///
/// - `Result<(Vec<Package>, bool), PublishError>`: Packages and whether a
///   root package was appended
async fn discover_packages(
    workspace_manifest: &Path,
) -> Result<(Vec<Package>, bool), PublishError> {
    let content: String = read_to_string(workspace_manifest).await?;
    let doc: Value = toml::from_str(&content).map_err(|_| PublishError::ManifestParseError)?;
    let workspace_version: Option<String> = doc
        .get("workspace")
        .and_then(|workspace: &Value| workspace.get("package"))
        .and_then(|package: &Value| package.get("version"))
        .and_then(|version: &Value| version.as_str())
        .map(|version: &str| version.to_string());
    let mut packages: Vec<Package> = Vec::new();
    if let Some(workspace) = doc.get("workspace")
        && let Some(members) = workspace
            .get("members")
            .and_then(|members_value: &Value| members_value.as_array())
    {
        for member in members {
            if let Some(pattern) = member.as_str() {
                let base_path: &Path = workspace_manifest.parent().unwrap_or(workspace_manifest);
                expand_pattern(
                    base_path,
                    pattern,
                    &mut packages,
                    workspace_version.as_deref(),
                )
                .await?;
            }
        }
    }
    let has_root_package: bool = doc.get("package").is_some();
    if has_root_package {
        let root_package: Package =
            read_package_manifest(workspace_manifest, workspace_version.as_deref()).await?;
        packages.push(root_package);
    }
    Ok((packages, has_root_package))
}

/// Expand glob pattern to find package directories
///
/// # Arguments
///
/// - `&Path`: Base path for expansion
/// - `&str`: Glob pattern
/// - `&mut Vec<Package>`: Output vector for found packages
/// - `Option<&str>`: Workspace root version for `version.workspace = true`
///
/// # Returns
///
/// - `Result<(), PublishError>`: Success or error
async fn expand_pattern(
    base_path: &Path,
    pattern: &str,
    packages: &mut Vec<Package>,
    workspace_version: Option<&str>,
) -> Result<(), PublishError> {
    if pattern.contains('*') {
        let parent: &Path = Path::new(pattern).parent().unwrap_or(Path::new("."));
        let full_parent: PathBuf = base_path.join(parent);
        if full_parent.is_dir() {
            let mut entries: ReadDir = read_dir(&full_parent).await?;
            while let Some(entry) = entries.next_entry().await? {
                let path: PathBuf = entry.path();
                if path.is_dir() {
                    let cargo_toml: PathBuf = path.join("Cargo.toml");
                    if cargo_toml.exists() {
                        let package: Package =
                            read_package_manifest(&cargo_toml, workspace_version).await?;
                        packages.push(package);
                    }
                }
            }
        }
    } else {
        let cargo_toml: PathBuf = base_path.join(pattern).join("Cargo.toml");
        if cargo_toml.exists() {
            let package: Package = read_package_manifest(&cargo_toml, workspace_version).await?;
            packages.push(package);
        }
    }
    Ok(())
}

/// Read package manifest and extract information
///
/// `version.workspace = true` resolves to the workspace root version
/// passed in `workspace_version`.
///
/// # Arguments
///
/// - `&Path`: Path to package Cargo.toml
/// - `Option<&str>`: Workspace root `[workspace.package].version`, if any
///
/// # Returns
///
/// - `Result<Package, PublishError>`: Package info or error
async fn read_package_manifest(
    manifest_path: &Path,
    workspace_version: Option<&str>,
) -> Result<Package, PublishError> {
    let content: String = read_to_string(manifest_path).await?;
    let doc: Value = toml::from_str(&content).map_err(|_| PublishError::ManifestParseError)?;
    let package_table: &Value = doc.get("package").ok_or(PublishError::ManifestParseError)?;
    let name: String = package_table
        .get("name")
        .and_then(|n: &Value| n.as_str())
        .ok_or(PublishError::ManifestParseError)?
        .to_string();
    let version: String = match package_table.get("version") {
        Some(version_value) => {
            if let Some(version_str) = version_value.as_str() {
                version_str.to_string()
            } else if version_value
                .get("workspace")
                .and_then(|workspace_value: &Value| workspace_value.as_bool())
                .unwrap_or(false)
            {
                workspace_version
                    .ok_or(PublishError::ManifestParseError)?
                    .to_string()
            } else {
                return Err(PublishError::ManifestParseError);
            }
        }
        None => workspace_version
            .ok_or(PublishError::ManifestParseError)?
            .to_string(),
    };
    let publish: bool = package_table
        .get("publish")
        .and_then(|publish_value: &Value| publish_value.as_bool())
        .unwrap_or(true);
    let path: PathBuf = manifest_path
        .parent()
        .filter(|p: &&Path| !p.as_os_str().is_empty())
        .map_or_else(|| PathBuf::from("."), |p: &Path| p.to_path_buf());
    let local_dependencies: Vec<String> = extract_local_dependencies(&doc, manifest_path)?;
    Ok(Package {
        name,
        version,
        path,
        local_dependencies,
        publish,
    })
}

/// Extract local workspace dependencies that constrain publish order
///
/// `[dependencies]` and `[build-dependencies]` entries with `path` or
/// `workspace = true` always constrain. `[dev-dependencies]` are stripped
/// from the published manifest, so they constrain only when they carry a
/// `version` field (cargo publish registry-checks versioned dev-deps);
/// path-only dev-deps skip the registry and impose no order constraint.
///
/// # Arguments
///
/// - `&Value`: Parsed manifest
/// - `&Path`: Path to manifest for resolving relative paths
///
/// # Returns
///
/// - `Result<Vec<String>, PublishError>`: List of local dependency names
fn extract_local_dependencies(
    doc: &Value,
    _manifest_path: &Path,
) -> Result<Vec<String>, PublishError> {
    let mut deps: Vec<String> = Vec::new();
    let dep_sections: [&str; 3] = ["dependencies", "build-dependencies", "dev-dependencies"];
    for section in &dep_sections {
        if let Some(table) = doc
            .get(section)
            .and_then(|section_value: &Value| section_value.as_table())
        {
            for (dep_name, dep_value) in table {
                let is_local: bool = match dep_value {
                    Value::Table(t) => {
                        let has_path_or_workspace: bool = t.get("path").is_some()
                            || t.get("workspace")
                                .and_then(|workspace_value: &Value| workspace_value.as_bool())
                                .unwrap_or(false);
                        let versioned: bool = t.get("version").is_some();
                        has_path_or_workspace && (*section != "dev-dependencies" || versioned)
                    }
                    _ => false,
                };
                if is_local {
                    deps.push(dep_name.clone());
                }
            }
        }
    }
    Ok(deps)
}

/// Validate that the publish order satisfies every package's local
/// dependency constraints: a package must never appear before a
/// workspace-local dependency of its own.
///
/// # Arguments
///
/// - `&[Package]`: Packages in intended publish order
///
/// # Returns
///
/// - `Result<(), PublishError>`: `InvalidPublishOrder` naming the first
///   offending pair when the order violates a local dependency.
fn validate_publish_order(packages: &[Package]) -> Result<(), PublishError> {
    let position: HashMap<String, usize> = packages
        .iter()
        .enumerate()
        .map(|(index, package): (usize, &Package)| (package.name.clone(), index))
        .collect();
    for package in packages {
        let Some(package_position) = position.get(&package.name) else {
            continue;
        };
        for dep in &package.local_dependencies {
            if let Some(dep_position) = position.get(dep)
                && dep_position > package_position
            {
                return Err(PublishError::InvalidPublishOrder(format!(
                    "{} depends on {} but is listed before it in [workspace.members]",
                    package.name, dep
                )));
            }
        }
    }
    Ok(())
}

/// Move the root package (appended last by `discover_packages`) to its
/// topological position when workspace members depend on it
///
/// When no member depends on the root package the root stays last (the
/// conventional facade-last layout). When members do depend on the root
/// (e.g. `ui` / `engine` crates depending on a root facade crate), the
/// root is inserted right before the earliest such member, provided all
/// of the root's own local dependencies appear earlier in the members
/// order; otherwise the members order cannot satisfy both constraints
/// and `InvalidPublishOrder` is returned.
///
/// # Arguments
///
/// - `&mut Vec<Package>`: Packages with the root package as last element
///
/// # Returns
///
/// - `Result<(), PublishError>`: Success or `InvalidPublishOrder`
fn position_root_package(packages: &mut Vec<Package>) -> Result<(), PublishError> {
    let Some(root) = packages.pop() else {
        return Ok(());
    };
    let earliest_dependent: Option<usize> = packages
        .iter()
        .enumerate()
        .filter(|(_, package)| package.local_dependencies.contains(&root.name))
        .map(|(index, _)| index)
        .min();
    let Some(earliest) = earliest_dependent else {
        packages.push(root);
        return Ok(());
    };
    let member_positions: HashMap<&str, usize> = packages
        .iter()
        .enumerate()
        .map(|(index, package)| (package.name.as_str(), index))
        .collect();
    if let Some(max_dep) = root
        .local_dependencies
        .iter()
        .filter_map(|dep| member_positions.get(dep.as_str()))
        .max()
        && max_dep >= &earliest
    {
        return Err(PublishError::InvalidPublishOrder(format!(
            "{} must publish after its dependency at members position {} but before dependent at position {}; reorder [workspace.members]",
            root.name, max_dep, earliest
        )));
    }
    packages.insert(earliest, root);
    Ok(())
}

/// Resolve the publish order for a workspace: `[workspace.members]`
/// declaration order, with the root package (if any) placed at its
/// topological position, validated against local dependency constraints.
///
/// # Arguments
///
/// - `&str`: Path to the workspace root Cargo.toml
///
/// # Returns
///
/// - `Result<Vec<Package>, PublishError>`: Ordered packages, or an
///   error when the members order violates a local dependency.
pub async fn resolve_publish_order(manifest_path: &str) -> Result<Vec<Package>, PublishError> {
    let workspace_manifest: &Path = Path::new(manifest_path);
    let (mut packages, has_root_package) = discover_packages(workspace_manifest).await?;
    if has_root_package {
        position_root_package(&mut packages)?;
    }
    validate_publish_order(&packages)?;
    Ok(packages)
}

/// Check whether `cargo publish` stderr indicates the package version is
/// already present on the registry (a success case for idempotent
/// re-runs).
///
/// # Arguments
///
/// - `&str`: cargo publish stderr output
///
/// # Returns
///
/// - `bool`: True when the output means "already published"
pub fn is_already_published(stderr: &str) -> bool {
    stderr.contains("already been uploaded")
        || stderr.contains("is already published")
        || stderr.contains("already exists on crates.io index")
}

/// Publish a single package with retry logic
///
/// # Arguments
///
/// - `&Package`: Package to publish
/// - `u32`: Maximum retry attempts
///
/// # Returns
///
/// - `PublishResult`: Result with success status and retry count
async fn publish_package_with_retry(package: &Package, max_retries: u32) -> PublishResult {
    let mut attempt: u32 = 0;
    let mut last_error: Option<String> = None;
    while attempt <= max_retries {
        match publish_single_package(package).await {
            Ok(()) => {
                return PublishResult {
                    package_name: package.name.clone(),
                    success: true,
                    error: None,
                    retries: attempt,
                };
            }
            Err(error) => {
                last_error = Some(error.to_string());
                attempt += 1;
                if attempt <= max_retries {
                    sleep(Duration::from_secs(2_u64.pow(attempt))).await;
                }
            }
        }
    }
    PublishResult {
        package_name: package.name.clone(),
        success: false,
        error: last_error,
        retries: attempt - 1,
    }
}

/// Execute cargo publish command for a single package
///
/// # Arguments
///
/// - `&Package`: Package to publish
///
/// # Returns
///
/// - `Result<(), Box<dyn std::error::Error>>`: Success or error
async fn publish_single_package(package: &Package) -> Result<(), Box<dyn std::error::Error>> {
    let output: std::process::Output = Command::new("cargo")
        .arg("publish")
        .arg("--allow-dirty")
        .arg("--no-verify")
        .current_dir(&package.path)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .await?;
    if output.status.success() {
        return Ok(());
    }
    let stderr: String = String::from_utf8_lossy(&output.stderr).to_string();
    if is_already_published(&stderr) {
        log::info!("{} is already published, treating as success", package.name);
        return Ok(());
    }
    Err(stderr.into())
}

/// Execute publish command for all packages in workspace
///
/// Publishes in `[workspace.members]` declaration order with the root
/// package (if any) last, after validating the order against local
/// dependency constraints.
///
/// # Arguments
///
/// - `&str`: Path to workspace Cargo.toml
/// - `u32`: Maximum retry attempts per package
///
/// # Returns
///
/// - `Result<Vec<PublishResult>, PublishError>`: Results for all packages
pub async fn execute_publish(
    manifest_path: &str,
    max_retries: u32,
) -> Result<Vec<PublishResult>, PublishError> {
    let path: &Path = Path::new(manifest_path);
    let path: &Path = match path.parent() {
        Some(parent) if !parent.as_os_str().is_empty() => parent,
        _ => Path::new("."),
    };
    let workspace_manifest: PathBuf = path.join("Cargo.toml");
    let sync_report: SyncReport =
        match execute_sync(workspace_manifest.to_str().unwrap_or("Cargo.toml")).await {
            Ok(report) => report,
            Err(error) => return Err(PublishError::SyncFailed(error)),
        };
    if sync_report.file_changed {
        log::info!(
            "publish: synced workspace dependencies ({} renamed, {} versioned) to v{}",
            sync_report.renamed_entries.len(),
            sync_report.versioned_entries.len(),
            sync_report.workspace_version,
        );
    }
    let ordered_packages: Vec<Package> =
        resolve_publish_order(workspace_manifest.to_str().unwrap_or("Cargo.toml")).await?;
    if ordered_packages.is_empty() {
        return Ok(Vec::new());
    }
    let mut results: Vec<PublishResult> = Vec::new();
    for package in ordered_packages {
        if !package.publish {
            log::info!("Skipping {} (publish = false)", package.name);
            continue;
        }
        log::info!("Publishing {} v{}...", package.name, package.version);
        let result: PublishResult = publish_package_with_retry(&package, max_retries).await;
        if result.success {
            if result.retries == 0 {
                log::info!("Successfully published {}", result.package_name,);
            } else {
                log::info!(
                    "Successfully published {} (retried {} times)",
                    result.package_name,
                    result.retries
                );
            }
        } else if let Some(error) = &result.error {
            log::error!("Failed to publish {}: {error}", result.package_name);
        } else {
            log::error!("Failed to publish {}", result.package_name);
        }
        results.push(result);
    }
    Ok(results)
}