ccgo 3.4.1

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
430
431
432
//! Tag command implementation - Pure Rust version
//!
//! Creates and manages Git tags for versioning.
//! Supports auto-versioning from CCGO.toml, custom messages, and remote operations.

use std::process::Command;

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

use crate::config::CcgoConfig;

/// Create version tag from CCGO.toml
#[derive(Args, Debug)]
pub struct TagCommand {
    /// Tag version (e.g., v1.0.0). If not provided, auto-generated from CCGO.toml
    pub version: Option<String>,

    /// Custom tag message (default: auto-generated with version info)
    #[arg(short, long)]
    pub message: Option<String>,

    /// Create lightweight tag instead of annotated tag
    #[arg(long)]
    pub lightweight: bool,

    /// Push tag to remote after creation (default: no push)
    #[arg(long)]
    pub push: bool,

    /// Force create tag (replace if exists)
    #[arg(short, long)]
    pub force: bool,

    /// Delete specified tag (local and remote)
    #[arg(short, long)]
    pub delete: bool,

    /// When deleting, only delete local tag (used with --delete)
    #[arg(long)]
    pub local_only: bool,

    /// List all tags
    #[arg(short, long)]
    pub list: bool,

    /// When listing, show remote tags (used with --list)
    #[arg(long)]
    pub remote: bool,
}

impl TagCommand {
    /// Execute the tag command
    pub fn execute(self, _verbose: bool) -> Result<()> {
        // Handle list operation
        if self.list {
            return self.list_tags();
        }

        // Handle delete operation
        if self.delete {
            if self.version.is_none() {
                eprintln!("{}", "Version required for delete operation");
                eprintln!("Usage: ccgo tag --delete v1.0.0");
                std::process::exit(1);
            }
            return self.delete_tag();
        }

        // Handle create operation
        self.create_tag()
    }

    /// Create a Git tag
    fn create_tag(self) -> Result<()> {
        eprintln!("=== {} ===", "Creating Git tag");

        // Load project configuration
        let config = CcgoConfig::load()
            .context("Failed to load CCGO.toml. Please run from project root directory")?;

        let project_dir = std::env::current_dir().context("Failed to get current directory")?;

        // Get package info (required for tag command)
        let package = config.require_package()?;

        // Determine tag version
        let tag_version = if let Some(v) = self.version {
            v
        } else {
            // Auto-generate from CCGO.toml
            let config_version = &package.version;
            if config_version.starts_with('v') {
                config_version.clone()
            } else {
                format!("v{}", config_version)
            }
        };

        eprintln!("{}", &format!("Tag version: {}", tag_version));

        // Get git information
        let git_info = get_git_info(&project_dir)?;

        // Generate tag message
        let tag_message = if let Some(msg) = self.message {
            msg
        } else {
            generate_tag_message(&tag_version, &package.name, &git_info)
        };

        if !self.lightweight {
            println!("\nTag message:");
            println!("{}", "-".repeat(60));
            println!("{}", tag_message);
            println!("{}\n", "-".repeat(60));
        }

        // Check if tag already exists
        if tag_exists(&project_dir, &tag_version)? {
            if !self.force {
                eprintln!("{}", &format!("Tag '{}' already exists", tag_version));
                eprintln!("Use --force to replace it");
                std::process::exit(1);
            } else {
                eprintln!("{}", &format!(
                    "Tag '{}' already exists, will be replaced (--force)",
                    tag_version
                ));
                // Delete existing tag
                let _ = Command::new("git")
                    .args(&["tag", "-d", &tag_version])
                    .current_dir(&project_dir)
                    .output();
            }
        }

        // Create tag
        let result = if self.lightweight {
            // Lightweight tag
            let mut cmd = Command::new("git");
            cmd.args(&["tag", &tag_version]);
            if self.force {
                cmd.arg("-f");
            }
            cmd.current_dir(&project_dir)
                .status()
                .context("Failed to create lightweight tag")?
        } else {
            // Annotated tag
            let mut cmd = Command::new("git");
            cmd.args(&["tag", "-a", &tag_version, "-m", &tag_message]);
            if self.force {
                cmd.arg("-f");
            }
            cmd.current_dir(&project_dir)
                .status()
                .context("Failed to create annotated tag")?
        };

        if !result.success() {
            bail!("Failed to create tag");
        }

        eprintln!("{}", &format!(
            "Created {} tag: {}",
            if self.lightweight {
                "lightweight"
            } else {
                "annotated"
            },
            tag_version
        ));

        // Show tag info
        let output = Command::new("git")
            .args(&["show", &tag_version, "--no-patch"])
            .current_dir(&project_dir)
            .output()
            .context("Failed to show tag info")?;

        if output.status.success() {
            println!("\nTag info:");
            println!("{}", String::from_utf8_lossy(&output.stdout));
        }

        // Push to remote
        if self.push {
            eprintln!("{}", "Pushing tag to remote...");
            let mut push_cmd = Command::new("git");
            push_cmd.args(&["push", "origin", &tag_version]);
            if self.force {
                push_cmd.arg("-f");
            }

            let result = push_cmd.current_dir(&project_dir).status();

            match result {
                Ok(status) if status.success() => {
                    eprintln!("{}", &format!("Pushed tag to origin/{}", tag_version));
                }
                _ => {
                    eprintln!("{}", "Failed to push tag to remote");
                    println!("Tag created locally. You can push it manually:");
                    println!("  git push origin {}", tag_version);
                }
            }
        } else {
            println!("\n📝 Tag created locally");
            println!("To push it to remote, run:");
            println!("  git push origin {}", tag_version);
        }

        println!("\n{}", "=".repeat(60));
        eprintln!("{}", "Tag operation completed successfully!");
        println!("{}\n", "=".repeat(60));

        Ok(())
    }

    /// Delete a Git tag
    fn delete_tag(self) -> Result<()> {
        let tag_version = self.version.as_ref().unwrap();

        eprintln!("=== {} ===", &format!("Deleting tag: {}", tag_version));

        let project_dir = std::env::current_dir().context("Failed to get current directory")?;

        // Delete local tag
        let result = Command::new("git")
            .args(&["tag", "-d", tag_version])
            .current_dir(&project_dir)
            .status();

        match result {
            Ok(status) if status.success() => {
                eprintln!("{}", &format!("Deleted local tag: {}", tag_version));
            }
            _ => {
                eprintln!("{}", &format!(
                    "Local tag '{}' not found or already deleted",
                    tag_version
                ));
            }
        }

        // Delete remote tag
        if !self.local_only {
            let result = Command::new("git")
                .args(&["push", "origin", "--delete", tag_version])
                .current_dir(&project_dir)
                .status();

            match result {
                Ok(status) if status.success() => {
                    eprintln!("{}", &format!("Deleted remote tag: origin/{}", tag_version));
                }
                _ => {
                    eprintln!("{}", "Failed to delete remote tag (may not exist)");
                }
            }
        }

        eprintln!("{}", "Tag deletion completed");

        Ok(())
    }

    /// List Git tags
    fn list_tags(&self) -> Result<()> {
        let project_dir = std::env::current_dir().context("Failed to get current directory")?;

        if self.remote {
            eprintln!("=== {} ===", "Remote tags");

            let output = Command::new("git")
                .args(&["ls-remote", "--tags", "origin"])
                .current_dir(&project_dir)
                .output()
                .context("Failed to list remote tags")?;

            if !output.status.success() {
                bail!("Failed to list remote tags");
            }

            let stdout = String::from_utf8_lossy(&output.stdout);
            if stdout.trim().is_empty() {
                println!("  No remote tags found");
            } else {
                for line in stdout.lines() {
                    let parts: Vec<&str> = line.split('\t').collect();
                    if parts.len() >= 2 {
                        let tag = parts[1].replace("refs/tags/", "");
                        // Skip dereferenced tags (ending with ^{})
                        if !tag.ends_with("^{}") {
                            println!("  {}", tag);
                        }
                    }
                }
            }
        } else {
            eprintln!("=== {} ===", "Local tags");

            let output = Command::new("git")
                .args(&["tag", "-l"])
                .current_dir(&project_dir)
                .output()
                .context("Failed to list tags")?;

            if !output.status.success() {
                bail!("Failed to list tags");
            }

            let stdout = String::from_utf8_lossy(&output.stdout);
            if stdout.trim().is_empty() {
                println!("  No local tags found");
            } else {
                let mut tags: Vec<&str> = stdout.lines().filter(|s| !s.is_empty()).collect();
                tags.sort();
                for tag in tags {
                    println!("  {}", tag);
                }
            }
        }

        println!();

        Ok(())
    }
}

/// Git information for tag message
#[derive(Debug)]
struct GitInfo {
    branch: String,
    version_code: String,
    revision: String,
    datetime: String,
}

/// Get git information
fn get_git_info(project_dir: &std::path::Path) -> Result<GitInfo> {
    // Get branch name
    let branch = Command::new("git")
        .args(&["symbolic-ref", "--short", "-q", "HEAD"])
        .current_dir(project_dir)
        .output()
        .ok()
        .and_then(|out| {
            if out.status.success() {
                Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
            } else {
                None
            }
        })
        .unwrap_or_else(|| "unknown".to_string());

    // Get version code (commit count)
    let version_code = Command::new("git")
        .args(&["rev-list", "HEAD", "--count"])
        .current_dir(project_dir)
        .output()
        .ok()
        .and_then(|out| {
            if out.status.success() {
                Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
            } else {
                None
            }
        })
        .unwrap_or_else(|| "0".to_string());

    // Get revision (short commit hash)
    let revision = Command::new("git")
        .args(&["rev-parse", "--short", "HEAD"])
        .current_dir(project_dir)
        .output()
        .ok()
        .and_then(|out| {
            if out.status.success() {
                Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
            } else {
                None
            }
        })
        .unwrap_or_else(|| "unknown".to_string());

    // Get datetime from last commit
    let datetime = Command::new("git")
        .args(&["log", "-n1", "--format=%at"])
        .current_dir(project_dir)
        .output()
        .ok()
        .and_then(|out| {
            if out.status.success() {
                let timestamp = String::from_utf8_lossy(&out.stdout).trim().to_string();
                timestamp.parse::<i64>().ok().and_then(|ts| {
                    chrono::DateTime::from_timestamp(ts, 0)
                        .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string())
                })
            } else {
                None
            }
        })
        .unwrap_or_else(|| chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string());

    Ok(GitInfo {
        branch,
        version_code,
        revision,
        datetime,
    })
}

/// Generate default tag message
fn generate_tag_message(version: &str, project_name: &str, info: &GitInfo) -> String {
    format!(
        "{}\n\nPROJECT: {}\nVERSION: {}\nVERSION_CODE: {}\nREVISION: {}\nBRANCH: {}\nDATETIME: {}",
        version, project_name, version, info.version_code, info.revision, info.branch, info.datetime
    )
}

/// Check if a tag exists
fn tag_exists(project_dir: &std::path::Path, tag: &str) -> Result<bool> {
    let output = Command::new("git")
        .args(&["rev-parse", tag])
        .current_dir(project_dir)
        .output()
        .context("Failed to check tag existence")?;

    Ok(output.status.success())
}