Error Handling in Rust

Better Error Handling in Rust If you have written any Rust, you may have noted how the above code uses Result<T> instead of Result<T, E>. This is because we have used a crate called anyhow.rs. Consider this function: pub fn write_blob(self) { let blob_path = self.get_path(); create_dir_all(blob_path.parent().unwrap()).unwrap(); let mut file = File::create(blob_path).unwrap(); file.write_all(&self.content).unwrap(); file.flush().unwrap(); } There are a number of ways this can fail. However, we don’t care a lot about the exact type of each error....

1 min · Me

Git CLI in Rust

CLI Definition in Rust Writing CLIs in Rust is an absolute pleasure. Using a crate like structopt, you can define the structure of your CLI and it handles cleaning the input and converting it to an appropriate type. #[derive(Debug, StructOpt)] #[structopt(name = "TGit", about = "HedonHermDev's implementation of Git")] pub enum CLI { #[structopt( name = "init", about = "Initialize an empty git repository")] Init { git_dir: Option<PathBuf> }, #[structopt(name = "cat-file", about = "Cat the contents of a git object")] CatFile { #[structopt( name = "pretty_print", short = "p", about = "Pretty print the contents")] pretty_print: bool, #[structopt(name = "OBJECT SHA")] object_sha: String, }, // -- snip -- } impl CLI { pub async fn run() -> Result<()> { let args: Self = Self::from_args(); match args { CLI::Init { git_dir } => commands::init(git_dir)....

2 min · Me

Git Implementation in Rust

Git Implementation in Rust Since all three types of objects have some common behaviour that only differs in its implementation, we can easily define a trait Object that defines each of these methods. #[async_trait] pub trait Object { async fn from_object_sha(object_sha: String) -> Result<Self> where Self: Sized; fn sha1_hash(&self) -> [u8; 20]; fn write_data(&self) -> &Vec<u8>; async fn write(&self) -> Result<PathBuf> { let mut path = PathBuf::from(".git/objects"); let blob_hex = hex::encode(self....

2 min · Me

Internals of Git Object Storage

Internals of Git Object Storage To understand the implementation further, you will need a rough idea of how Git stores its data. Here’s a brief introduction to the same. Everything about Git is stored inside a directory called the gitdir aka .git. Example contents of the .git directory Think of Git like a database. Git stores its data in the form of Objects. There are three types of Git objects: Blob, Tree, and Commit....

1 min · Me

Writing Git in Rust

Writing Git in Rust Notes around the implementation of a small part of Git in Rust. Full implementation in this repository. Note that most of the implementation’s details will be snipped. If you want to see the full implementation and try it out on your machine, check out the repository. Structuring the Project The challenge proceeded in steps and each step was about implementing what they call “plumbing commands” of Git....

2 min · Me