ccgo 3.10.5

A high-performance C++ cross-platform build CLI
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
//! `ccgo yank` — flip a published version's `yanked` flag in a registry
//! index repo. Mirrors `cargo yank`.
//!
//! The default target is the package described by the local CCGO.toml in
//! the current directory; pass `--package` to operate on someone else's
//! package from any cwd. The version must already exist in the index;
//! re-yanking an already-yanked version is a clear error rather than a
//! silent no-op so a CI pipeline that loops on this command surfaces the
//! mistake.
//!
//! Yanking is purely a flag flip — the `VersionEntry` and its
//! `archive_url` / `checksum` are preserved, so consumers who already
//! locked this version in their `CCGO.lock` continue to fetch the same
//! bytes. New `ccgo fetch` runs (without `--locked`) skip yanked entries
//! during resolution (`resolve_dep`), so subsequent fresh resolutions
//! pick a different version.

use std::path::Path;

use anyhow::{bail, Context, Result};
use clap::Args;

use crate::config::CcgoConfig;
use crate::registry::{index_writer, PackageEntry, PackageIndex};

#[path = "yank_recovery.rs"]
mod recovery;

/// Yank (or unyank) a published package version in a registry index.
///
/// Mirrors `cargo yank --vers <V> [--undo] [<crate>]`. The package name
/// defaults to the current project's CCGO.toml `[project].name`; pass
/// `--package` to override.
#[derive(Args, Debug)]
pub struct YankCommand {
    /// Override the package name (default: read CCGO.toml in cwd).
    #[arg(long)]
    pub package: Option<String>,

    /// The version to yank or unyank. The flag is `--vers` (and the
    /// field name is `vers`) rather than `--version` to avoid colliding
    /// with clap's auto-generated `--version` flag — same reason
    /// `cargo yank --vers` does it.
    #[arg(long)]
    pub vers: String,

    /// Index repository URL or local path. Required.
    #[arg(long)]
    pub index_repo: Option<String>,

    /// Index registry name (used as the local clone subdir).
    #[arg(long)]
    pub index_name: Option<String>,

    /// Why this version is being yanked. Required when yanking; rejected
    /// when `--undo` is set.
    #[arg(long)]
    pub reason: Option<String>,

    /// Undo a previous yank — flip `yanked: false` and clear the reason.
    #[arg(long)]
    pub undo: bool,

    /// Override the auto-generated commit message.
    #[arg(long)]
    pub message: Option<String>,

    /// Push to remote after committing. Without this flag the commit is
    /// made in the local clone of the index repo; the operator can `cd`
    /// in and push manually.
    #[arg(long)]
    pub push: bool,
}

impl YankCommand {
    pub fn execute(self, verbose: bool) -> Result<()> {
        // 1. Resolve package name — explicit > CCGO.toml in cwd.
        let package_name = match &self.package {
            Some(name) => name.clone(),
            None => Self::read_package_name_from_cwd()?,
        };

        // 2. Validate flag combinations.
        let index_repo = self
            .index_repo
            .clone()
            .ok_or_else(|| anyhow::anyhow!("--index-repo is required"))?;
        let index_name = self
            .index_name
            .clone()
            .unwrap_or_else(|| "custom-index".to_string());

        self.validate_action()?;

        let action = if self.undo { "Unyanking" } else { "Yanking" };
        println!(
            "🔖 {} {} {} (registry: {})",
            action, package_name, self.vers, index_name
        );

        // 3. Clone/pull the index repo, locate the package's JSON entry.
        let _write_lock = index_writer::lock_index(&index_writer::publish_work_dir(&index_name))?;
        if index_writer::publish_work_dir(&index_name)
            .join(".git/ccgo-publication.json")
            .exists()
        {
            bail!(
                "An interrupted publication is pending; retry that publish command before yanking"
            );
        }
        let pending = recovery::PendingYank::resume(
            &index_writer::publish_work_dir(&index_name),
            &self,
            &package_name,
            verbose,
        )?;
        let index_path = index_writer::prepare_index_repo(&index_repo, &index_name, verbose)?;
        if let Some(pending) = pending {
            pending.verify_target(&index_path)?;
            if self.push {
                index_writer::push_changes_retry(&index_path, &index_name, verbose)?;
            }
            pending.finish(&index_path)?;
            println!("✅ Interrupted yank operation completed");
            return Ok(());
        }
        self.commit_yank(
            &index_path,
            &index_repo,
            &index_name,
            &package_name,
            verbose,
        )
    }

    fn validate_action(&self) -> Result<()> {
        if self.undo && self.reason.is_some() {
            bail!("--reason is not accepted with --undo (unyank clears the reason)");
        }
        if !self.undo && self.reason.is_none() {
            bail!(
                "--reason is required when yanking. Pass --reason \"<why>\" to leave \
                 an audit trail; or pass --undo to unyank."
            );
        }

        Ok(())
    }

    fn apply_action(&self, v: &mut crate::registry::VersionEntry) -> Result<()> {
        if self.undo {
            if !v.yanked {
                bail!(
                    "version '{}' is not currently yanked; nothing to undo",
                    self.vers
                );
            }
            v.yanked = false;
            v.yanked_reason = None;
            println!("   ✓ Cleared yanked flag");
        } else {
            if v.yanked {
                bail!(
                    "version '{}' is already yanked (reason: {}). Pass --undo to unyank \
                     first if you want to re-yank with a different reason.",
                    self.vers,
                    v.yanked_reason.as_deref().unwrap_or("<unset>")
                );
            }
            v.yanked = true;
            v.yanked_reason = self.reason.clone();
            println!(
                "   ✓ Yanked (reason: {})",
                self.reason.as_deref().unwrap_or("")
            );
        }

        Ok(())
    }

    fn commit_yank(
        &self,
        index_path: &Path,
        index_repo: &str,
        index_name: &str,
        package_name: &str,
        verbose: bool,
    ) -> Result<()> {
        let package_file = Self::existing_package_file(index_path, package_name)?;

        // 4. Mutate the matching VersionEntry.
        let json = std::fs::read_to_string(&package_file)
            .with_context(|| format!("failed to read {}", package_file.display()))?;
        let mut entry: PackageEntry = serde_json::from_str(&json)
            .with_context(|| format!("failed to parse {}", package_file.display()))?;

        // Snapshot the available versions BEFORE the mutable lookup so
        // the not-found error message can include them without borrowing
        // `entry.versions` twice.
        let available: Vec<String> = entry
            .versions
            .iter()
            .take(5)
            .map(|v| v.version.clone())
            .collect();

        let v = entry
            .versions
            .iter_mut()
            .find(|v| v.version == self.vers)
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "version '{}' is not in the index entry for '{}'. \
                     Available: {}",
                    self.vers,
                    package_name,
                    available.join(", ")
                )
            })?;

        self.apply_action(v)?;

        // 5. Write back, refresh metadata, commit, optionally push.
        let desired = v.clone();
        let json = serde_json::to_string_pretty(&entry)
            .context("failed to serialize updated package entry")?;
        let before = std::fs::read(&package_file)?;
        let pending = recovery::PendingYank::start(
            index_path,
            index_repo,
            package_name,
            desired,
            &before,
            json.as_bytes(),
            self.push,
        )?;
        recovery::write_atomic(&package_file, json.as_bytes())
            .with_context(|| format!("failed to write {}", package_file.display()))?;

        index_writer::update_index_metadata(index_path, index_name)?;

        let commit_message = self.commit_message(package_name);

        index_writer::commit_changes(index_path, &commit_message, verbose)?;

        if self.push {
            println!("\n📤 Pushing to remote...");
            index_writer::push_changes_retry(index_path, index_name, verbose)?;
            println!("✅ Pushed successfully!");
        } else {
            println!("\n💡 Changes committed locally. Use --push to push to remote.");
        }

        pending.finish(index_path)
    }

    fn existing_package_file(index_path: &Path, package_name: &str) -> Result<std::path::PathBuf> {
        let package_rel_path = PackageIndex::package_index_path(package_name);
        let package_file = index_path.join(&package_rel_path);

        if !package_file.exists() {
            bail!(
                "package '{}' is not in the index ({} does not exist). \
                 Did you mean to publish it first?",
                package_name,
                package_file.display()
            );
        }

        Ok(package_file)
    }

    fn commit_message(&self, package_name: &str) -> String {
        self.message.clone().unwrap_or_else(|| {
            if self.undo {
                format!("unyank: {} {}", package_name, self.vers)
            } else {
                let reason = self.reason.as_deref().unwrap_or("");
                format!("yank: {} {}\n\nreason: {}", package_name, self.vers, reason)
            }
        })
    }

    fn read_package_name_from_cwd() -> Result<String> {
        let cwd = std::env::current_dir().context("failed to read current directory")?;
        let toml_path = Self::find_ccgo_toml(&cwd)?;
        let config = CcgoConfig::load_from_path(&toml_path).with_context(|| {
            format!(
                "failed to load CCGO.toml at {} (use --package to skip CCGO.toml lookup)",
                toml_path.display()
            )
        })?;
        let package = config.package.ok_or_else(|| {
            anyhow::anyhow!(
                "no [package] section in CCGO.toml at {}; pass --package <name> explicitly",
                toml_path.display()
            )
        })?;
        Ok(package.name)
    }

    fn find_ccgo_toml(start: &Path) -> Result<std::path::PathBuf> {
        let direct = start.join("CCGO.toml");
        if direct.is_file() {
            return Ok(direct);
        }
        // Look one level down (mirrors the existing pattern in publish.rs).
        if let Ok(entries) = std::fs::read_dir(start) {
            for entry in entries.flatten() {
                if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
                    let candidate = entry.path().join("CCGO.toml");
                    if candidate.is_file() {
                        return Ok(candidate);
                    }
                }
            }
        }
        bail!(
            "no CCGO.toml found in {} or its immediate subdirectories. \
             Run `ccgo yank` from the project root, or pass --package <name>.",
            start.display()
        );
    }
}

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

    fn entry_with_versions(versions: Vec<VersionEntry>) -> PackageEntry {
        PackageEntry {
            name: "leaf".into(),
            description: "x".into(),
            repository: "x".into(),
            homepage: None,
            license: None,
            keywords: Vec::new(),
            platforms: Vec::new(),
            versions,
        }
    }

    fn version(v: &str, tag: &str, yanked: bool) -> VersionEntry {
        VersionEntry {
            version: v.into(),
            tag: tag.into(),
            checksum: None,
            archive_url: None,
            archive_format: None,
            released_at: None,
            yanked,
            yanked_reason: None,
        }
    }

    /// Run a single yank/unyank pass against an in-memory PackageEntry,
    /// returning the resulting (yanked, reason) so tests can pin the
    /// state machine without spawning git or touching disk.
    fn apply_yank_in_memory(
        mut entry: PackageEntry,
        target_version: &str,
        undo: bool,
        reason: Option<&str>,
    ) -> Result<(bool, Option<String>)> {
        let v = entry
            .versions
            .iter_mut()
            .find(|v| v.version == target_version)
            .ok_or_else(|| anyhow::anyhow!("version '{}' not found", target_version))?;

        if undo {
            if !v.yanked {
                bail!("not currently yanked");
            }
            v.yanked = false;
            v.yanked_reason = None;
        } else {
            if v.yanked {
                bail!("already yanked");
            }
            v.yanked = true;
            v.yanked_reason = reason.map(str::to_string);
        }
        Ok((v.yanked, v.yanked_reason.clone()))
    }

    #[test]
    fn yank_flips_flag_and_records_reason() {
        let entry = entry_with_versions(vec![version("1.0.0", "v1.0.0", false)]);
        let (yanked, reason) =
            apply_yank_in_memory(entry, "1.0.0", false, Some("broken bytes")).unwrap();
        assert!(yanked);
        assert_eq!(reason.as_deref(), Some("broken bytes"));
    }

    #[test]
    fn yank_rejects_already_yanked() {
        let entry = entry_with_versions(vec![version("1.0.0", "v1.0.0", true)]);
        let err = apply_yank_in_memory(entry, "1.0.0", false, Some("oops")).unwrap_err();
        assert!(err.to_string().contains("already yanked"), "got: {err}");
    }

    #[test]
    fn unyank_clears_flag_and_reason() {
        let mut entry = entry_with_versions(vec![version("1.0.0", "v1.0.0", true)]);
        entry.versions[0].yanked_reason = Some("broken".into());
        let (yanked, reason) = apply_yank_in_memory(entry, "1.0.0", true, None).unwrap();
        assert!(!yanked);
        assert!(reason.is_none());
    }

    #[test]
    fn unyank_rejects_when_not_yanked() {
        let entry = entry_with_versions(vec![version("1.0.0", "v1.0.0", false)]);
        let err = apply_yank_in_memory(entry, "1.0.0", true, None).unwrap_err();
        assert!(
            err.to_string().contains("not currently yanked"),
            "got: {err}"
        );
    }

    #[test]
    fn yank_unknown_version_errors() {
        let entry = entry_with_versions(vec![version("1.0.0", "v1.0.0", false)]);
        let err = apply_yank_in_memory(entry, "9.9.9", false, Some("x")).unwrap_err();
        assert!(err.to_string().contains("not found"), "got: {err}");
    }
}