mklink.pl 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. unlink "$from/$file";
  46. symlink("$to/$file", "$from/$file") or $err = " [$!]";
  47. } else {
  48. unlink "$from/$file";
  49. open (OLD, "<$file") or die "Can't open $file: $!";
  50. open (NEW, ">$from/$file") or die "Can't open $from/$file: $!";
  51. binmode(OLD);
  52. binmode(NEW);
  53. while (<OLD>) {
  54. print NEW $_;
  55. }
  56. close (OLD) or die "Can't close $file: $!";
  57. close (NEW) or die "Can't close $from/$file: $!";
  58. }
  59. print $file . " => $from/$file$err\n";
  60. }