Rust 操作 shell 进行 路径切换 , git 操作

302 阅读3分钟

Rust 操作 shell 进行 git 操作

完整代码如下:

use std::{
    io::stdin,
    process::{exit, Command},
};

fn main() {
    // 获取 commit 的内容
    let mut m = String::new();
    stdin().read_line(&mut m).expect("无法读取输入");

    // 进入目标目录
    if let Err(err) = std::env::set_current_dir(">>输入你的目标目录<< ") {
        eprintln!("目录更改失败: {}", err);
        exit(1);
    }

    // 添加所有修改
    let output = Command::new("git")
        .arg("add")
        .arg(".")
        .output()
        .expect("添加修改的进程执行失败");

    // 检查是否成功执行git操作
    if !output.status.success() {
        eprintln!(" git 进程失败 (add)");
        exit(1);
    }
    // commit
    let output = Command::new("git")
        .arg("commit")
        .arg("-m")
        .arg(&m)
        .output()
        .expect("commit 进程执行失败");

    // 检查是否成功执行git操作
    if !output.status.success() {
        eprintln!("git 进程失败 (commit)");
        exit(1);
    }
    
    // 提交
    let output = Command::new("git")
        .arg("push")
        .arg("origin")
        .arg("master")
        .output()
        .expect(" 提交进程失败");

    // 检查是否成功执行git操作
    if !output.status.success() {
        eprintln!("git 进程失败 (push)");
        exit(1);
    }

    // 查看提交结果
    let output = Command::new("git")
        .arg("status")
        .output()
        .expect("状态查看进程失败");

    // 检查是否成功执行git操作
    if !output.status.success() {
        eprintln!("进程失败 (status)");
        exit(1);
    }

    // 输出git命令的输出结果
    let result = String::from_utf8_lossy(&output.stdout);
    println!("Git command output: {:?}", result);
}

缘起

笔记都是通过 git 进行备份的 , 之前是通过 Mac 中的快捷指令执行的 shell 脚本 , 最近发现一直报错 , 还找不到错误原因 , 正好最近在学习 Rust , 就使用 Rust 制作了一个很简易的 git 同步脚本

记录

安装

linux , mac os , window wsl 都可以在终端直接执行下面的指令进行安装 , 按照提示下一步就好

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

初始化

在目标路径下执行 cargo new auto_push 会创建一个新的项目 , 里面包含src/main.rs 这里就是我们写程序的地方

操作shell

Rust 使用std::process::Command; 操作终端 , 使用 Command::new("git") 执行指定的指令 , 例如:

use std::process::{exit , Command};

fn main(){
	let output = Command::new("ls")
		.arg("-l")
		.arg("-a")
		.expect("无法执行 ls -l -a 指令")

    if !output.status.success() {
        eprintln!("ls 执行失败");
        exit(1);
    }
}
  • 这其中 .arg() 可以给要执行的 shell 指令添加参数 , 这里是给ls 添加了-l-la 两个参数
  • ::new() 返回的也是一个 Result , 可以通过expect 简单的处理Err 变体
  • 如果Result 是成功变体会返回一个 Output 结构体的实例
  • output.status.success() 可以获得实例中的指令执行状态

路径修改

使用Command::new("cd")来执行cd命令是无效的。cd命令是一个shell内建命令,无法直接通过Command模块执行。需要使用其他方法来改变当前工作目录。

所以改用了std::env::set_current_dir函数来改变当前工作目录,

	if let Err(err) = std::env::set_current_dir("=目标路径=") {
	eprintln!("目录更改失败: {}", err);
	exit(1);
}

完成

在终端执行 cargo run 执行程序 , 如果程序没有问题可以右键target/debug/auto_push 可执行文件 , 制作替身 , 将替身移动到桌面 , 这样就可以在桌面双击运行了 , 代码中的stdin().read_line(&mut m).expect("无法读取输入"); 会获取输入的commit 信息来执行 commit -m 指令

补充

在没有任何修改的时候执行程序是无效的 , 会终止于commit 这一步 , 因为没有修改的时候commit -m "" 是不会执行的