mirror of
https://github.com/MrBeanCpp/MIT.git
synced 2026-02-09 13:15:00 +08:00
实现:init命令
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
use clap::{Parser, Subcommand};
|
||||
use mit::commands::init::init;
|
||||
|
||||
/// Rust实现的简易版本的Git,用于学习Rust语言
|
||||
#[derive(Parser)]
|
||||
@@ -42,7 +43,7 @@ pub fn handle_command() {
|
||||
let cli = Cli::parse();
|
||||
match cli.command {
|
||||
Command::Init => {
|
||||
println!("init");
|
||||
let _ = init();
|
||||
}
|
||||
Command::Add { files , all } => {
|
||||
if files.contains(&".".to_string()) || all {
|
||||
|
||||
45
src/commands/init.rs
Normal file
45
src/commands/init.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
use std::{env, fs, io};
|
||||
|
||||
/**
|
||||
初始化mit仓库 创建.mit/objects .mit/refs/heads .mit/HEAD
|
||||
并设置 .mit 为隐藏文件夹
|
||||
无法重复初始化
|
||||
*/
|
||||
pub fn init() -> io::Result<()> {
|
||||
let dir = env::current_dir()?;
|
||||
let mit_dir = dir.join(".mit");
|
||||
if mit_dir.exists() {
|
||||
println!("!Already a mit repo - [{}]", dir.display());
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let dirs = [
|
||||
mit_dir.join("objects"),
|
||||
mit_dir.join("refs/heads"),
|
||||
];
|
||||
// 创建 .git 目录和子目录
|
||||
for dir in &dirs {
|
||||
fs::create_dir_all(dir)?;
|
||||
}
|
||||
fs::write(mit_dir.join("HEAD"), "ref: refs/heads/master\n")?;
|
||||
|
||||
set_dir_hidden(&mit_dir.to_str().unwrap())?; // 设置目录隐藏 (跨平台)
|
||||
println!("Initialized empty mit repository in {}", dir.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn set_dir_hidden(dir: &str) -> io::Result<()> {
|
||||
use std::process::Command;
|
||||
Command::new("attrib")
|
||||
.arg("+H")
|
||||
.arg(dir)
|
||||
.spawn()?
|
||||
.wait()?; // 等待命令执行完成
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn set_dir_hidden(dir: &str) -> io::Result<()> { //linux下以'.'开头就已经是隐藏文件(夹)了
|
||||
Ok(())
|
||||
}
|
||||
1
src/commands/mod.rs
Normal file
1
src/commands/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub mod init;
|
||||
@@ -1,3 +1,4 @@
|
||||
// 不使用lib.rs的话,就无法在tests里引用到src中的模块
|
||||
pub mod objects;
|
||||
pub mod utils;
|
||||
pub mod utils;
|
||||
pub mod commands;
|
||||
Reference in New Issue
Block a user