My user-friendly symlinking tool `lns' is another thing that really
[sgt/utils] / lns / lns
CommitLineData
337ff285 1#!/usr/bin/env perl
2
3# lns -- create a symbolic link. Alternative to "ln -s".
4# This program works more like "cp", in that the source path name is not
5# taken literally.
6# ln -s filename /tmp
7# creates a link
8# /tmp/filename -> filename
9# whereas we would prefer
10# /tmp/filename -> /home/me/filename
11# or wherever the file *really* was.
12#
13# Usage: lns [-afF] file1 file2
14# or lns [-af] file1 [file2...] dir
15#
16# Where:
17# -a means absolute - "symlink /usr/bin/argh /usr/local/bin/argh" produces
18# a relative link "/usr/bin/argh -> ../local/bin/argh", but using the
19# -a option will give a real absolute link.
20# -f means forceful - overwrite the target filename if it exists *and* is
21# a link. You can't accidentally overwrite real files like this.
22# -q means quiet - don't complain if we fail to do the job.
23# -v means verbose - say what we're doing.
24# -F means FILE - forces interpretation to be the "file1 file2" syntax,
25# even if file2 is a link to a directory. This option implies -f.
26
27use Cwd;
28
29$usage =
30 "usage: lns [flags] srcfile destfile\n".
31 " or: lns [flags] srcfile [srcfile...] destdir\n".
32 "where: -a create symlinks with absolute path names\n".
33 " -f overwrite existing symlink at target location\n".
34 " -F like -f, but works even if target is link to dir\n".
35 " -v verbosely log activity (repeat for more verbosity)\n".
36 " -q suppress error messages on failure\n".
37 " also: lns --version report version number\n" .
38 " lns --help display this help text\n" .
39 " lns --licence display (MIT) licence text\n";
40
41$licence =
42 "lns is copyright 1999,2004 Simon Tatham.\n" .
43 "\n" .
44 "Permission is hereby granted, free of charge, to any person\n" .
45 "obtaining a copy of this software and associated documentation files\n" .
46 "(the \"Software\"), to deal in the Software without restriction,\n" .
47 "including without limitation the rights to use, copy, modify, merge,\n" .
48 "publish, distribute, sublicense, and/or sell copies of the Software,\n" .
49 "and to permit persons to whom the Software is furnished to do so,\n" .
50 "subject to the following conditions:\n" .
51 "\n" .
52 "The above copyright notice and this permission notice shall be\n" .
53 "included in all copies or substantial portions of the Software.\n" .
54 "\n" .
55 "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n" .
56 "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n" .
57 "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n" .
58 "NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n" .
59 "BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n" .
60 "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n" .
61 "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n" .
62 "SOFTWARE.\n";
63
64$abs=$force=$quiet=$verbose=$FILE=0;
65while ($_=shift @ARGV) {
66 last if /^--$/;
67 unshift (@ARGV, $_), last unless /^-(.*)/;
68 if ($1 eq "-help") {
69 print STDERR $usage;
70 exit 0;
71 } elsif ($1 eq "-version") {
72 if ('$Revision$' =~ /Revision:\s+(\d+)/) {
73 print "lns revision $1\n";
74 } else {
75 print "lns: unknown revision\n";
76 }
77 exit 0;
78 } elsif ($1 eq "-licence" or $1 eq "-license") {
79 print $licence;
80 exit 0;
81 } else {
82 foreach $opt (split //, $1) {
83 if ($opt eq "a") { $abs=1; }
84 elsif ($opt eq "f") { $force=1; }
85 elsif ($opt eq "q") { $quiet=1; }
86 elsif ($opt eq "v") { $verbose++; }
87 elsif ($opt eq "F") { $force=$FILE=1; }
88 else { die "$0: unrecognised option '-$1'\n"; }
89 }
90 }
91}
92
93die $usage if $#ARGV < 1;
94
95die "$0: multiple source files specified with -F option\n"
96 if $#ARGV > 1 && $FILE;
97die "$0: -q (quiet) and -v (verbose) options both specified\n"
98 if $quiet && $verbose;
99
100$target = pop @ARGV;
101die "$0: multiple source files specified, $target not a directory\n"
102 if $#ARGV > 0 && !-d $target;
103
104$multiple = (-d $target && !$FILE);
105$whereami = getcwd();
106
107$target =~ s/// if $target =~ /\/$/; # strip trailing slash if present
108
109if ($multiple) {
110 foreach $source (@ARGV) {
111 $source =~ /^(.*\/)?([^\/]*)$/; # find final file name component
112 &makelink($source, "$target/$2"); # actually make a link
113 }
114} else {
115 $source = $ARGV[0]; # only one source file
116 &makelink($source, $target); # make the link
117}
118
119sub makelink {
120 local ($source, $target) = @_;
121
122 # If the target exists...
123 if (-e $target || readlink $target) {
124 # If it's a symlink and we're in Force mode, remove it and carry on.
125 if ($force && readlink $target) {
126 unlink $target || die "$0: unable to remove link $target\n";
127 # Report that if in Verbose mode.
128 warn "$0: removing existing target link $target\n" if $verbose;
129 } else {
130 # Otherwise, fail. Report that fact if not in Quiet mode.
131 warn "$0: failed to link $source to $target: target exists\n"
132 if !$quiet;
133 return;
134 }
135 }
136
137 # OK, now we're ready to do the link. Calculate the absolute path names
138 # of both source and target.
139 $source = &absolute($source);
140 $target = &absolute($target);
141
142 # If we're in Relative mode (the default), calculate the relative path
143 # name we will reference the source by.
144 $sourcename = $abs ? $source : &relname($source, $target);
145
146 warn "$0: linking $source: $target -> $sourcename\n" if $verbose;
147
148 # Make the link
149 symlink($sourcename, $target) || die "$0: unable to make link to $target\n";
150}
151
152sub absolute {
153 local ($_) = @_;
154 $_ = "$whereami/$_" if !/^\//;
155 s//$whereami/ if /^\./;
156 1 while s/\/\.\//\//;
157 1 while s/\/\//\//;
158 1 while s/\/[^\/]+\/\.\.//;
159 1 while s/^\/\.\.\//\//;
160 $_;
161}
162
163sub relname {
164 local ($source, $target) = @_;
165 local $prefix;
166
167 # Strip the last word off the target (the actual file name) to
168 # obtain the target _directory_.
169 $target =~ s/\/[^\/]*$//;
170
171 # Our starting prefix is empty. We will add one "../" at a time
172 # until we find a match.
173
174 while (1) {
175
176 # If $target is a prefix of $source, we are done. (No matter what
177 # symlinks may exist on the shared common pathname, if we are
178 # linking `a/b/c/foo' to `foo' then a simple relative link will
179 # work.)
180 if (substr($source, 0, length $target) eq $target) {
181 return $prefix . substr($source, 1 + length $target); # skip the slash
182 }
183
184 # Otherwise, descend to "..".
185
186 $target = $target . "/..";
187
188 # Now normalise the path by removing all ".." segments. We want
189 # to do this while _as far as possible_ preserving symlinks. So
190 # the algorithm is:
191 #
192 # - Repeatedly search for the rightmost `directory/..'
193 # fragment.
194 # - When we find it, one of two cases apply.
195 # * If the directory before the .. is not a symlink, we can
196 # remove both it and the .. from the string.
197 # * If it _is_ a symlink, we substitute it for its link
198 # text, and loop round again.
199 while ($target =~
200 /^(.*)\/((\.|\.\.[^\/]+|\.?[^\/\.][^\/]*)\/\.\.)(\/.*)?$/)
201 {
202 my ($pre, $dir, $frag, $post) = ($1,$2,$3,$4);
203 my $log = "transforming $target -> ";
204 if (-l "$pre/$frag") {
205 my $linktext = readlink "$pre/$frag";
206 if ($linktext =~ /^\//) { # absolute link
207 $target = $linktext;
208 } else { # relative link
209 $target = "$pre/$linktext";
210 }
211 $target .= "/.." . $post;
212 } else {
213 $target = $pre . $post;
214 }
215 $target = "/" if $target eq ""; # special case
216 $log .= "$target";
217 warn "$0: $log\n" if $verbose > 1;
218 }
219
220 # Now we have replaced $target with a pathname equivalent to
221 # `$target/..'. So add a "../" to $prefix, and try matching
222 # again.
223 $prefix .= "../";
224 }
225}