canonicalize_filename.sh 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #!/bin/sh
  2. # Provide the canonicalize filename (physical filename with out any symlinks)
  3. # like the GNU version readlink with the -f option regardless of the version of
  4. # readlink (GNU or BSD).
  5. # This file is part of a set of unofficial pre-commit hooks available
  6. # at github.
  7. # Link: https://github.com/githubbrowser/Pre-commit-hooks
  8. # Contact: David Martin, david.martin.mailbox@googlemail.com
  9. ###########################################################
  10. # There should be no need to change anything below this line.
  11. # Canonicalize by recursively following every symlink in every component of the
  12. # specified filename. This should reproduce the results of the GNU version of
  13. # readlink with the -f option.
  14. #
  15. # Reference: http://stackoverflow.com/questions/1055671/how-can-i-get-the-behavior-of-gnus-readlink-f-on-a-mac
  16. canonicalize_filename () {
  17. local target_file="$1"
  18. local physical_directory=""
  19. local result=""
  20. # Need to restore the working directory after work.
  21. local working_dir="`pwd`"
  22. cd -- "$(dirname -- "$target_file")"
  23. target_file="$(basename -- "$target_file")"
  24. # Iterate down a (possible) chain of symlinks
  25. while [ -L "$target_file" ]
  26. do
  27. target_file="$(readlink -- "$target_file")"
  28. cd -- "$(dirname -- "$target_file")"
  29. target_file="$(basename -- "$target_file")"
  30. done
  31. # Compute the canonicalized name by finding the physical path
  32. # for the directory we're in and appending the target file.
  33. physical_directory="`pwd -P`"
  34. result="$physical_directory/$target_file"
  35. # restore the working directory after work.
  36. cd -- "$working_dir"
  37. echo "$result"
  38. }