Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added init, create and switch command. #13

Merged
merged 17 commits into from
Dec 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
/target
.vault
.vaultignore
/vault-test
/vault-test
/tmp
*tmp.rs
42 changes: 42 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
chrono = "0.4.31"
whoami = "1.4.1"
sha256 = "1.4.0"
sha256 = "1.4.0"
serde_yaml = "0.9.27"
123 changes: 80 additions & 43 deletions src/commands/commit.rs
Original file line number Diff line number Diff line change
@@ -1,63 +1,100 @@
use crate::compress_zlib::compress_zlib;
use crate::core::blob::Blob;
//VAULT COMMIT
// Loop around the directory and make the commit
// No add . apparently : )
use crate::core::tree::TreeEntry;
use crate::core::types::GitObject;
use crate::hash::hash_in_sha256;
use crate::utils::get_current_branch::get_current_branch;
use crate::utils::read_files::read_string;
use flate2::Compression;
use std::collections::HashMap;
use std::fs;
use std::io;
use std::path::Path;
use std::fs::File;
use std::io::{self, Write};
use std::path::{Path, PathBuf};

pub fn commit(dir_path: &Path) -> io::Result<()> {
fn handle_commit(dir_path: &Path) -> io::Result<Vec<TreeEntry>> {
let mut entries: Vec<TreeEntry> = Vec::new();
if let Ok(entries_result) = fs::read_dir(dir_path) {
for entry_result in entries_result {
if let Ok(entry) = entry_result {
if entry
.file_type()
.map_or(false, |ft: fs::FileType| ft.is_dir())
{
let subdirectory_entries: Result<(), io::Error> = commit(&entry.path());
// let sub_dir_tree: crate::core::tree::Tree = make_tree(subdirectory_entries);
//Push entry of type GitObject::Tree
entries.push(
// TreeEntry{
// name: "".to_string(),
// object: GitObject::Tree(sub_dir_tree)
// }
todo!(),
);
} else {
// Read file content and create a blob object
if let Ok(content) = fs::read(entry.path()) {
//Using Read string as I don't down if I can read binary from a text file
let file_contents: String = read_string(entry.path()).unwrap();
let file_blob: Result<Blob, std::io::Error> = Blob::new_blob(file_contents);
match file_blob {
Ok(file_blob) => {
let string_to_be_hashed: &String =
&file_blob.clone().get_content_of_blob();
let hashed_blob_string: String =
hash_in_sha256(&string_to_be_hashed);
entries.push(TreeEntry {
// Enter file Name here
name: "".to_string(),
object: GitObject::Blob(file_blob),
hashedPath: hashed_blob_string,
});
let current_branch: Result<String, io::Error> = get_current_branch();
match current_branch {
Ok(current_branch) => {
let path: &Path = Path::new(".vault");
let branch_path: PathBuf = path.join(current_branch);
let vault_path: PathBuf = branch_path.join("objects");
if let Ok(entries_result) = fs::read_dir(dir_path) {
for entry_result in entries_result {
if let Ok(entry) = entry_result {
if entry
.file_type()
.map_or(false, |ft: fs::FileType| ft.is_dir())
{
let subdirectory_entries: Result<Vec<TreeEntry>, io::Error> =
handle_commit(&entry.path());
// let sub_dir_tree: crate::core::tree::Tree = make_tree(subdirectory_entries);
//Push entry of type GitObject::Tree
entries.push(
// TreeEntry{
// name: "".to_string(),
// object: GitObject::Tree(sub_dir_tree)
// }
todo!(),
);
} else {
// Read file content and create a blob object
if let Ok(content) = fs::read(entry.path()) {
//Using Read string as I don't down if I can read binary from a text file
let file_contents: String = read_string(entry.path()).unwrap();
let file_blob: Result<Blob, std::io::Error> =
Blob::new_blob(file_contents);
match file_blob {
Ok(file_blob) => {
let string_to_be_hashed: &String =
&file_blob.clone().get_content_of_blob();
let serialized_content: String = format!(
"blob {}\0{}",
string_to_be_hashed.len(),
string_to_be_hashed
);
let compressed_content: Vec<u8> =
compress_zlib(&serialized_content)?;
let hashed_blob_string: String =
hash_in_sha256(&string_to_be_hashed);
// Make a directory with the 1st two letters of the hash
let dir_name: &str = &hashed_blob_string[0..2];
let dir_path: std::path::PathBuf =
vault_path.join(dir_name);
let file_name: &str = &hashed_blob_string[2..];
let file_path: std::path::PathBuf =
dir_path.join(file_name);
fs::create_dir(dir_path).expect("Some error occurred");
let mut file: File = File::create(file_path)?;
let _ = file.write_all(&compressed_content);
entries.push(TreeEntry {
// Enter file Name here
name: "".to_string(),
object: GitObject::Blob(file_blob),
hashedPath: hashed_blob_string,
});
}
//Think what could be the error actually shown to the user?
Err(_e) => panic!("Some Error Occurred"),
}
}
//Think what could be the error actually shown to the user?
Err(e) => panic!("Some Error Occurred"),
}
}
}
}
}
Err(e) => panic!("Failed to read YAML"),
}

Ok(())
Ok(entries)
}

pub fn commit(dir_path: &Path) -> io::Result<()> {
let commit = handle_commit(dir_path);
match commit {
Ok(_) => Ok(()),
Err(e) => panic!("Failed to Commit: {e}"),
}
}
29 changes: 29 additions & 0 deletions src/commands/create.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
use crate::utils::yaml_layouts::{ConfigLayout, InitLayout};
use std::fs;
use std::path::{Path, PathBuf};

pub fn create(branch_name: &String) {
let vault_folder: &Path = Path::new(".vault");
let init_file: PathBuf = vault_folder.join("init.yaml");
let content_bytes: Vec<u8> = fs::read(&init_file).unwrap();
let content: std::borrow::Cow<'_, str> = String::from_utf8_lossy(&content_bytes);
let mut init_content: InitLayout = serde_yaml::from_str(&content).unwrap();

init_content.branches.push(branch_name.clone());
let branch_folder: PathBuf = vault_folder.join(branch_name.clone());
let branch_object_folder: PathBuf = branch_folder.join("objects");
// @TODO Handle Error here with match statements
fs::create_dir(&branch_folder).unwrap();
fs::create_dir(branch_object_folder).unwrap();
create_config_yaml(&branch_folder);
println!("content of init.yaml file \n{:?}", init_content);
let yaml_string: String = serde_yaml::to_string(&init_content).unwrap();
fs::write(init_file, yaml_string).unwrap();
}

fn create_config_yaml(folder_path: &PathBuf) {
let config_path: PathBuf = folder_path.join("config.yaml");
let yaml_struct: ConfigLayout = ConfigLayout::default();
let yaml_string: String = serde_yaml::to_string(&yaml_struct).unwrap();
fs::write(config_path, yaml_string).unwrap();
}
56 changes: 28 additions & 28 deletions src/commands/init.rs
Original file line number Diff line number Diff line change
@@ -1,36 +1,36 @@
//This will have an init function which will currently create a .vault folder in the current directory
// VAULT INIT
use std::fs::File;
use crate::commands::{create, switch};
use crate::utils::yaml_layouts::InitLayout;
use std::fs::{self, create_dir};
use std::path::Path;
use std::{fs, io};

//@TODO - make a utils module with reusable function like create file and create dir...

pub fn init() -> io::Result<()> {
pub fn init() {
let vault_folder: &Path = Path::new(".vault");
let current_dir: std::path::PathBuf =
std::env::current_dir().expect("Unable to get current directory");
let current_dir_str: String = current_dir.to_string_lossy().into_owned();
let path: &Path = Path::new(".vault");
let file_path: std::path::PathBuf = path.join("CurrentDir");
let objects: std::path::PathBuf = path.join("objects");
let logs: std::path::PathBuf = path.join("logs");
let log_head: std::path::PathBuf = logs.join("HEAD");
let ignore_file_path: &Path = Path::new(".vaultignore");
if path.exists() {
panic!("This directory already is a in a vault. Cannot init!");
} else {
//@TODO - Think of better error messages
//@TODO - If any step fails, reverse all the previous steps...,
// We can do this by making a temp directory and only copy the temp dir if all the steps pass
fs::create_dir(path).expect("Unable to create .vault folder");
fs::create_dir(objects).expect("Unable to create a vault! \n Some error occured");
fs::create_dir(logs).expect("Unable to create a vault! \n Some error occured");
fs::File::create(file_path.clone())
.expect("Unable to create a vault! \n Some error occured");
fs::File::create(log_head).expect("Unable to create a vault! \n Some error occured");
let _ = fs::write(file_path, current_dir_str);
let _ = File::create(ignore_file_path);
println!("Vault created successfully");
Ok(())
let ignore_file_path: std::path::PathBuf = current_dir.join(".vaultignore");
match create_dir(vault_folder) {
Ok(_) => {
let init_file: std::path::PathBuf = vault_folder.join("init.yaml");
let content: String = get_init_data();
fs::File::create(ignore_file_path).unwrap();
fs::write(init_file, content).unwrap();
// @TODO: Add call to branch function with default(master) parameter.
create(&"master".to_string());
// @TODO: Add call to switch function with default(master) parameter.
switch(&"master".to_string());
}
Err(_) => println!("Vault already initialized"),
}
}

fn get_init_data() -> String {
let yaml_struct: InitLayout = InitLayout {
current_branch: String::new(),
branches: Vec::new(),
};

let yaml_string: String = serde_yaml::to_string(&yaml_struct).unwrap();
return yaml_string;
}
8 changes: 7 additions & 1 deletion src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,8 @@
pub mod commit;
pub mod create;
pub mod init;
pub mod commit;
pub mod switch;

pub use commit::commit;
pub use create::create;
pub use switch::switch;
22 changes: 22 additions & 0 deletions src/commands/switch.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use crate::utils::yaml_layouts::InitLayout;
use std::fs;
use std::path::Path;

pub fn switch(branch_name: &String) {
let vault_folder: &Path = Path::new(".vault");
let init_file: std::path::PathBuf = vault_folder.join("init.yaml");
let content_bytes: Vec<u8> = fs::read(&init_file).unwrap();
let content: std::borrow::Cow<'_, str> = String::from_utf8_lossy(&content_bytes);
let mut init_content: InitLayout = serde_yaml::from_str(&content).unwrap();
if init_content.branches.contains(branch_name) {
init_content.current_branch = branch_name.to_string();
println!("Branch switched to: {}", branch_name);
let yaml_string = serde_yaml::to_string(&init_content).unwrap();
fs::write(init_file, yaml_string).unwrap();
} else {
println!(
"Invalid branch name: {} Please check for spell error",
branch_name
);
};
}
10 changes: 10 additions & 0 deletions src/compress_zlib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use std::io::Write;

use flate2::{write::ZlibEncoder, Compression};


pub fn compress_zlib(data: &str) -> std::io::Result<Vec<u8>> {
let mut encoder: ZlibEncoder<Vec<u8>> = ZlibEncoder::new(Vec::new(), Compression::default());
encoder.write_all(data.as_bytes())?;
encoder.finish()
}
Loading