2
0

mklink.pl 1.9 KB

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