msvc 0.1.0

A tool to automate setup for MSVC projects with vc-ltl and thunk-rs.
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
use clap::Parser;
use std::fs;
use std::path::Path;
use std::process::Command;
use toml_edit::value;

/// Custom error type for msvc tool
///
/// This enum represents all possible errors that can occur during the execution
/// of the msvc tool, providing detailed error information for better debugging.
#[derive(Debug)]
enum MsvcError {
    /// File system or I/O related errors
    Io(std::io::Error),
    /// TOML parsing or serialization errors
    TomlParse(String),
    /// External command execution failures
    CommandFailed(String),
    /// Project configuration or validation errors
    InvalidProject(String),
}

impl std::fmt::Display for MsvcError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            MsvcError::Io(err) => write!(f, "IO error: {}", err),
            MsvcError::TomlParse(err) => write!(f, "TOML parse error: {}", err),
            MsvcError::CommandFailed(msg) => write!(f, "Command failed: {}", msg),
            MsvcError::InvalidProject(msg) => write!(f, "Invalid project: {}", msg),
        }
    }
}

impl std::error::Error for MsvcError {}

impl From<std::io::Error> for MsvcError {
    fn from(err: std::io::Error) -> Self {
        MsvcError::Io(err)
    }
}

type Result<T> = std::result::Result<T, MsvcError>;

/// Check if we're in a valid Cargo project directory
///
/// This function validates that the current directory contains a Cargo.toml file,
/// which is required for the msvc tool to operate correctly.
///
/// # Errors
/// Returns `MsvcError::InvalidProject` if no Cargo.toml file is found in the current directory.
fn validate_project() -> Result<()> {
    let cargo_file = Path::new("Cargo.toml");
    if !cargo_file.exists() {
        return Err(MsvcError::InvalidProject(
            "Not in a Cargo project directory. Please run this command from a directory containing Cargo.toml".to_string()
        ));
    }
    Ok(())
}

/// Load and parse Cargo.toml file
///
/// This function reads and parses the Cargo.toml file in the current directory,
/// returning a mutable document that can be used for further modifications.
///
/// # Errors
/// Returns `MsvcError::Io` if the file cannot be read.
/// Returns `MsvcError::TomlParse` if the file content is not valid TOML.
fn load_cargo_toml() -> Result<toml_edit::DocumentMut> {
    let cargo_file = Path::new("Cargo.toml");
    let content = fs::read_to_string(cargo_file)?;
    let doc = content.parse::<toml_edit::DocumentMut>()
        .map_err(|e| MsvcError::TomlParse(e.to_string()))?;
    Ok(doc)
}

/// Check if a dependency exists in the given section
///
/// This function checks if a specific dependency exists in a particular section
/// of the Cargo.toml file (e.g., "dependencies" or "build-dependencies").
///
/// # Arguments
/// * `doc` - The parsed Cargo.toml document
/// * `section` - The section to check (e.g., "dependencies", "build-dependencies")
/// * `dep_name` - The name of the dependency to look for
///
/// # Returns
/// Returns `true` if the dependency exists in the specified section, `false` otherwise.
fn has_dependency(doc: &toml_edit::DocumentMut, section: &str, dep_name: &str) -> bool {
    doc.get(section)
        .and_then(|item| item.as_table())
        .map(|table| table.contains_key(dep_name))
        .unwrap_or(false)
}

/// Execute a cargo command and return success status
///
/// This function runs a cargo command with the given arguments and returns whether
/// the command executed successfully.
///
/// # Arguments
/// * `args` - Array of command line arguments to pass to cargo
///
/// # Errors
/// Returns `MsvcError::CommandFailed` if the cargo command cannot be executed.
///
/// # Returns
/// Returns `true` if the command succeeded, `false` otherwise.
fn run_cargo_command(args: &[&str]) -> Result<bool> {
    let mut child = Command::new("cargo")
        .args(args)
        .stdout(std::process::Stdio::inherit())
        .stderr(std::process::Stdio::inherit())
        .spawn()
        .map_err(|e| MsvcError::CommandFailed(format!("Failed to execute cargo command: {}", e)))?;

    let status = child
        .wait()
        .map_err(|e| MsvcError::CommandFailed(format!("Failed to wait for cargo command: {}", e)))?;

    Ok(status.success())
}

#[derive(Parser, Debug)]
#[command(
    name = "msvc",
    author = "Baoge <baoge@live.cn>",
    version,
    about = "A tool to automate setup for MSVC projects with vc-ltl and thunk-rs",
    long_about = "msvc is a command-line tool that helps automate the setup of MSVC (Microsoft Visual C++) projects in Rust. It can manage vc-ltl dependencies, thunk-rs integration, and target configurations."
)]
struct Args {
    /// Set up or remove thunk-rs integration for MSVC builds
    #[arg(short, long)]
    thunk: bool,

    /// Configure or remove the default target to x86_64-pc-windows-msvc
    #[arg(short = 'x', long = "x86-64")]
    x86_64: bool,

    /// Add all MSVC configurations (vc-ltl, thunk-rs, and target configuration)
    #[arg(short = 'a', long = "add-all")]
    add_all: bool,

    /// Remove all MSVC configurations (vc-ltl, thunk-rs, and target configuration)
    #[arg(short = 'r', long = "remove-all")]
    remove_all: bool,

    /// Build the project (shorthand: 'b')
    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(clap::Subcommand, Debug)]
enum Commands {
    /// Build the project
    #[command(alias = "b")]
    Build {
        /// Build with release profile
        #[arg(short = 'r', long)]
        release: bool,
    },


}

fn main() -> Result<()> {
    let args = Args::parse();

    // Validate project directory
    validate_project()?;

    println!("Working on project directory: {:?}", std::env::current_dir()?);

    // 处理构建子命令
    if let Some(command) = args.command {
        match command {
            Commands::Build { release } => {
                let mut build_args = vec!["build", "--target", "x86_64-pc-windows-msvc"];
                if release {
                    build_args.push("--release");
                }
                if !run_cargo_command(&build_args)? {
                    return Err(MsvcError::CommandFailed("Build failed".to_string()));
                }
                println!("✓ Build completed successfully with MSVC target");
                return Ok(());
            }
        }
    }

    // 处理原有的配置命令
    if args.remove_all {
        remove_all()?;
        return Ok(());
    }
    if args.add_all {
        add_all()?;
        return Ok(());
    }

    // Load Cargo.toml once
    let doc = load_cargo_toml()?;
    let has_vc_ltl = has_dependency(&doc, "dependencies", "vc-ltl");
    let has_thunk = has_dependency(&doc, "build-dependencies", "thunk-rs");

    // Default behavior: toggle vc-ltl
    if !args.thunk && !args.x86_64 {
        if has_vc_ltl {
            remove_vc_ltl()?;
        } else {
            add_vc_ltl()?;
        }
    }

    if args.thunk {
        if has_thunk {
            remove_thunk_rs()?;
            remove_build_script()?;
        } else {
            add_thunk_rs()?;
            add_build_script()?;
        }
    }

    if args.x86_64 {
        toggle_target_config()?;
    }

    Ok(())
}

fn remove_vc_ltl() -> Result<()> {
    if run_cargo_command(&["remove", "vc-ltl"])? {
        println!("✓ Removed vc-ltl dependency");
    } else {
        println!("⚠ vc-ltl not found in dependencies");
    }
    Ok(())
}

/// Remove vc-ltl dependency from the project
///
/// This function attempts to remove the vc-ltl dependency using `cargo remove`.
/// It provides user feedback about the success or failure of the operation.
///
/// # Errors
/// Returns `MsvcError::CommandFailed` if the cargo command cannot be executed.

fn add_vc_ltl() -> Result<()> {
    if run_cargo_command(&["add", "vc-ltl"])? {
        println!("✓ Added vc-ltl dependency");
    } else {
        println!("✗ Failed to add vc-ltl dependency");
    }
    Ok(())
}

/// Add vc-ltl dependency to the project
///
/// This function attempts to add the vc-ltl dependency using `cargo add`.
/// It provides user feedback about the success or failure of the operation.
///
/// # Errors
/// Returns `MsvcError::CommandFailed` if the cargo command cannot be executed.

fn remove_thunk_rs() -> Result<()> {
    if run_cargo_command(&["remove", "--build", "thunk-rs"])? {
        println!("✓ Removed thunk-rs build dependency");
    } else {
        println!("⚠ thunk-rs not found in build dependencies");
    }
    Ok(())
}

fn add_thunk_rs() -> Result<()> {
    if run_cargo_command(&["add", "--build", "thunk-rs"])? {
        println!("✓ Added thunk-rs build dependency");
    } else {
        println!("✗ Failed to add thunk-rs build dependency");
    }
    Ok(())
}

fn add_all() -> Result<()> {
    add_vc_ltl()?;
    add_thunk_rs()?;
    add_target_config()?;
    add_build_script()?;
    println!("✓ Added all MSVC configurations");
    Ok(())
}

fn remove_all() -> Result<()> {
    remove_vc_ltl()?;
    remove_thunk_rs()?;
    remove_target_config()?;
    remove_build_script()?;
    println!("✓ Removed all MSVC configurations");
    Ok(())
}

fn add_build_script() -> Result<()> {
    let build_rs_path = Path::new("build.rs");
    const BUILD_RS_CONTENT: &str = r#"// This file is automatically generated/managed by cargo-msvc.
fn main() {
    if std::env::var("CARGO_CFG_TARGET_ENV").map_or(false, |env| env == "msvc") {
        thunk::thunk();
    }
}
"#;

    if !build_rs_path.exists() {
        fs::write(build_rs_path, BUILD_RS_CONTENT)?;
        println!("✓ Created build.rs file with thunk-rs integration");
        return Ok(());
    }

    let content = fs::read_to_string(&build_rs_path)?;
    if content.contains("thunk::thunk();") {
        println!("⚠ thunk-rs integration already exists in build.rs");
        return Ok(());
    }

    if content.contains("// This file is automatically generated/managed by cargo-msvc.") {
        // File is managed by us, but missing thunk call
        fs::write(build_rs_path, BUILD_RS_CONTENT)?;
    } else {
        // File exists but not managed by us, merge carefully
        if let Some(last_brace_pos) = content.rfind('}') {
            let new_content = format!(
                "{}    if std::env::var(\"CARGO_CFG_TARGET_ENV\").map_or(false, |env| env == \"msvc\") {{\n        thunk::thunk();\n    }}\n{}",
                &content[..last_brace_pos],
                &content[last_brace_pos..]
            );
            fs::write(build_rs_path, new_content)?;
        } else {
            println!("⚠ Could not find suitable location to add thunk-rs integration");
            return Ok(());
        }
    }
    println!("✓ Added thunk-rs integration to build.rs");
    Ok(())
}

fn remove_build_script() -> Result<()> {
    let build_rs_path = Path::new("build.rs");
    if !build_rs_path.exists() {
        println!("⚠ build.rs file not found");
        return Ok(());
    }

    let content = fs::read_to_string(&build_rs_path)?;
    if !content.contains("thunk::thunk();") {
        println!("⚠ No thunk-rs integration found in build.rs");
        return Ok(());
    }

    let new_content = if content.contains("// This file is automatically generated/managed by cargo-msvc.") {
        // If this is our managed file, replace it with a minimal version
        "fn main() {}\n".to_string()
    } else {
        // Otherwise just remove the thunk call and its conditional
        content.replace(
            "    if std::env::var(\"CARGO_CFG_TARGET_ENV\").map_or(false, |env| env == \"msvc\") {\n        thunk::thunk();\n    }\n",
            ""
        )
    };

    fs::write(build_rs_path, new_content)?;
    println!("✓ Removed thunk-rs integration from build.rs");
    Ok(())
}

fn add_target_config() -> Result<()> {
    let config_toml_path = Path::new(".cargo/config.toml");
    if let Some(parent) = config_toml_path.parent() {
        if !parent.exists() {
            fs::create_dir_all(parent)?;
        }
    }

    let mut doc = if config_toml_path.exists() {
        let content = fs::read_to_string(&config_toml_path)?;
        if content.trim().is_empty() {
            toml_edit::DocumentMut::new()
        } else {
            content.parse::<toml_edit::DocumentMut>()
                .map_err(|e| MsvcError::TomlParse(e.to_string()))?
        }
    } else {
        toml_edit::DocumentMut::new()
    };

    // 获取或创建 [build] 表
    let build_table = doc["build"].or_insert(toml_edit::table());
    if let Some(table) = build_table.as_table_mut() {
        table["target"] = value("x86_64-pc-windows-msvc");
    }

    fs::write(config_toml_path, doc.to_string())?;
    println!("✓ Added target configuration to .cargo/config.toml");
    Ok(())
}

fn toggle_target_config() -> Result<()> {
    let config_toml_path = Path::new(".cargo/config.toml");
    if config_toml_path.exists() {
        let content = fs::read_to_string(&config_toml_path)?;
        let doc = if content.trim().is_empty() {
            toml_edit::DocumentMut::new()
        } else {
            content.parse::<toml_edit::DocumentMut>()
                .map_err(|e| MsvcError::TomlParse(e.to_string()))?
        };

        // 检查是否存在 target 配置
        let has_target = doc
            .get("build")
            .and_then(|item| item.as_table())
            .and_then(|table| table.get("target"))
            .and_then(|target| target.as_str())
            .map(|target_str| target_str == "x86_64-pc-windows-msvc")
            .unwrap_or(false);

        if has_target {
            remove_target_config()?;
        } else {
            add_target_config()?;
        }
    } else {
        println!("⚠ Config file not found, creating one");
        add_target_config()?;
    }
    Ok(())
}

fn remove_target_config() -> Result<()> {
    let config_toml_path = Path::new(".cargo/config.toml");
    if !config_toml_path.exists() {
        return Ok(());
    }

    let content = fs::read_to_string(&config_toml_path)?;
    let mut doc = if content.trim().is_empty() {
        toml_edit::DocumentMut::new()
    } else {
        content.parse::<toml_edit::DocumentMut>()
            .map_err(|e| MsvcError::TomlParse(e.to_string()))?
    };

    // 检查并修改 [build] 表
    if let Some(build_table) = doc.get_mut("build").and_then(|item| item.as_table_mut()) {
        if build_table.contains_key("target") {
            build_table.remove("target");
            if build_table.is_empty() {
                doc.remove("build");
            }
        }
    }

    if doc.to_string().trim().is_empty() {
        fs::remove_file(config_toml_path)?;
        println!("✓ Removed .cargo/config.toml file");
    } else {
        fs::write(config_toml_path, doc.to_string())?;
        println!("✓ Removed target configuration from .cargo/config.toml");
    }
    Ok(())
}