2
0

mklink.pl 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. my $pwd;
  16. eval 'use Cwd;';
  17. if ($@)
  18. {
  19. $pwd = `pwd`;
  20. }
  21. else
  22. {
  23. $pwd = getcwd();
  24. }
  25. my $from = shift;
  26. my @files = @ARGV;
  27. my @from_path = split(/[\\\/]/, $from);
  28. chomp($pwd);
  29. my @pwd_path = split(/[\\\/]/, $pwd);
  30. my @to_path = ();
  31. my $dirname;
  32. foreach $dirname (@from_path) {
  33. # In this loop, @to_path always is a relative path from
  34. # @pwd_path (interpreted is an absolute path) to the original pwd.
  35. # At the end, @from_path (as a relative path from the original pwd)
  36. # designates the same directory as the absolute path @pwd_path,
  37. # which means that @to_path then is a path from there to the original pwd.
  38. next if ($dirname eq "" || $dirname eq ".");
  39. if ($dirname eq "..") {
  40. @to_path = (pop(@pwd_path), @to_path);
  41. } else {
  42. @to_path = ("..", @to_path);
  43. push(@pwd_path, $dirname);
  44. }
  45. }
  46. my $to = join('/', @to_path);
  47. my $file;
  48. $symlink_exists=eval {symlink("",""); 1};
  49. foreach $file (@files) {
  50. my $err = "";
  51. if ($symlink_exists) {
  52. unlink "$from/$file";
  53. symlink("$to/$file", "$from/$file") or $err = " [$!]";
  54. } else {
  55. unlink "$from/$file";
  56. open (OLD, "<$file") or die "Can't open $file: $!";
  57. open (NEW, ">$from/$file") or die "Can't open $from/$file: $!";
  58. binmode(OLD);
  59. binmode(NEW);
  60. while (<OLD>) {
  61. print NEW $_;
  62. }
  63. close (OLD) or die "Can't close $file: $!";
  64. close (NEW) or die "Can't close $from/$file: $!";
  65. }
  66. print $file . " => $from/$file$err\n";
  67. }