mklink.pl 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/local/bin/perl
  2. # mklink.pl
  3. # The first command line argument is a non-empty relative path
  4. # specifying the "from" directory.
  5. # Each other argument is a file name not containing / and
  6. # names a file in the current directory.
  7. #
  8. # For each of these files, we create in the "from" directory a link
  9. # of the same name pointing to the local file.
  10. #
  11. # We assume that the directory structure is a tree, i.e. that it does
  12. # not contain symbolic links and that the parent of / is never referenced.
  13. # Apart from this, this script should be able to handle even the most
  14. # pathological cases.
  15. use Cwd;
  16. my $from = shift;
  17. my @files = @ARGV;
  18. my @from_path = split(/[\\\/]/, $from);
  19. my $pwd = getcwd();
  20. chomp($pwd);
  21. my @pwd_path = split(/[\\\/]/, $pwd);
  22. my @to_path = ();
  23. my $dirname;
  24. foreach $dirname (@from_path) {
  25. # In this loop, @to_path always is a relative path from
  26. # @pwd_path (interpreted is an absolute path) to the original pwd.
  27. # At the end, @from_path (as a relative path from the original pwd)
  28. # designates the same directory as the absolute path @pwd_path,
  29. # which means that @to_path then is a path from there to the original pwd.
  30. next if ($dirname eq "" || $dirname eq ".");
  31. if ($dirname eq "..") {
  32. @to_path = (pop(@pwd_path), @to_path);
  33. } else {
  34. @to_path = ("..", @to_path);
  35. push(@pwd_path, $dirname);
  36. }
  37. }
  38. my $to = join('/', @to_path);
  39. my $file;
  40. $symlink_exists=eval {symlink("",""); 1};
  41. if ($^O eq "msys") { $symlink_exists=0 };
  42. foreach $file (@files) {
  43. my $err = "";
  44. if ($symlink_exists) {
  45. if (!-l "$from/$file") {
  46. unlink "$from/$file";
  47. symlink("$to/$file", "$from/$file") or $err = " [$!]";
  48. }
  49. } elsif (-d "$from" && (!-f "$from/$file" || ((stat("$file"))[9] > (stat("$from/$file"))[9]))) {
  50. unlink "$from/$file";
  51. open (OLD, "<$file") or die "Can't open $file: $!";
  52. open (NEW, ">$from/$file") or die "Can't open $from/$file: $!";
  53. binmode(OLD);
  54. binmode(NEW);
  55. while (<OLD>) {
  56. print NEW $_;
  57. }
  58. close (OLD) or die "Can't close $file: $!";
  59. close (NEW) or die "Can't close $from/$file: $!";
  60. }
  61. print $file . " => $from/$file$err\n";
  62. }