Skip to content

Commit

Permalink
Merge pull request #8 from rupert648/rupert/symlink-pre-commit-fix
Browse files Browse the repository at this point in the history
added pre-commit hook to commit actual files instead of symlinks
  • Loading branch information
rupert648 authored Dec 20, 2024
2 parents 4032ca1 + 98ee809 commit 6a58b15
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 1 deletion.
27 changes: 27 additions & 0 deletions src/git_operations.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
use std::fs::{self, File};
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::Command;

pub fn init_git_repo(repo_path: &str) -> Result<(), std::io::Error> {
Expand All @@ -7,3 +11,26 @@ pub fn init_git_repo(repo_path: &str) -> Result<(), std::io::Error> {
.output()?;
Ok(())
}

pub fn add_pre_commit_hook(repo_path: &str) -> Result<(), std::io::Error> {
let hook_contents = fs::read_to_string("sym-link-pre-commit.sh")?;

let hook_path = Path::new(repo_path)
.join(".git")
.join("hooks")
.join("pre-commit");

if let Some(parent) = hook_path.parent() {
fs::create_dir_all(parent)?;
}

let mut file = File::create(&hook_path)?;
file.write_all(hook_contents.as_bytes())?;

// Make the file executable (rwxr-xr-x = 0o755)
let mut perms = file.metadata()?.permissions();
perms.set_mode(0o755);
fs::set_permissions(&hook_path, perms)?;

Ok(())
}
3 changes: 2 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use cli::Args;
use colored::*;
use config::Config;
use file_operations::{create_dotfiles_repo, find_dotfiles, print_file_tree};
use git_operations::init_git_repo;
use git_operations::{add_pre_commit_hook, init_git_repo};
use indicatif::{ProgressBar, ProgressStyle};
use std::fs;
use std::path::Path;
Expand Down Expand Up @@ -62,6 +62,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
spinner.enable_steady_tick(Duration::from_millis(100));

init_git_repo(&repo_path)?;
add_pre_commit_hook(&repo_path)?;
spinner.finish_and_clear();

println!("{}", "Dotfiles repo created successfully!".green().bold());
Expand Down
19 changes: 19 additions & 0 deletions sym-link-pre-commit.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#!/bin/bash
# Save as .git/hooks/pre-commit and make executable

# Find all symlinks that are tracked by git
git ls-files -s | grep ^120000 | cut -f2 | while read -r file; do
if [ -L "$file" ]; then
target=$(readlink -f "$file") # -f follows the link recursively
if [ -d "$target" ]; then
# Handle directory
rm "$file"
cp -rL "$target" "$file" # -r for recursive, -L to follow symlinks
else
# Handle regular file
rm "$file"
cp -L "$target" "$file"
fi
git add "$file"
fi
done

0 comments on commit 6a58b15

Please sign in to comment.