(usage): Include one- or two-line synopsis in --help output.
[platform/upstream/coreutils.git] / src / ln.c
1 /* `ln' program to create links between files.
2    Copyright (C) 1986, 1989, 1990, 1991, 1995 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software
16    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
17 \f
18 /* Written by Mike Parker and David MacKenzie. */
19
20 #ifdef _AIX
21  #pragma alloca
22 #endif
23
24 #include <config.h>
25 #include <stdio.h>
26 #include <sys/types.h>
27 #include <getopt.h>
28
29 #include "system.h"
30 #include "backupfile.h"
31 #include "version.h"
32 #include "error.h"
33
34 int link ();                    /* Some systems don't declare this anywhere. */
35
36 #ifdef S_ISLNK
37 int symlink ();
38 #endif
39
40 /* Construct a string NEW_DEST by concatenating DEST, a slash, and
41    basename(SOURCE) in alloca'd memory.  Don't modify DEST or SOURCE.  */
42
43 #define PATH_BASENAME_CONCAT(new_dest, dest, source)                    \
44     do                                                                  \
45       {                                                                 \
46         char *source_base;                                              \
47         char *tmp_source;                                               \
48                                                                         \
49         tmp_source = (char *) alloca (strlen ((source)) + 1);           \
50         strcpy (tmp_source, (source));                                  \
51         strip_trailing_slashes (tmp_source);                            \
52         source_base = basename (tmp_source);                            \
53                                                                         \
54         (new_dest) = (char *) alloca (strlen ((dest)) + 1               \
55                                       + strlen (source_base) + 1);      \
56         stpcpy (stpcpy (stpcpy ((new_dest), (dest)), "/"), source_base);\
57       }                                                                 \
58     while (0)
59
60 char *basename ();
61 enum backup_type get_version ();
62 int isdir ();
63 int yesno ();
64 void strip_trailing_slashes ();
65 char *stpcpy ();
66
67 static void usage ();
68 static int do_link ();
69
70 /* The name by which the program was run, for error messages.  */
71 char *program_name;
72
73 /* A pointer to the function used to make links.  This will point to either
74    `link' or `symlink'. */
75 static int (*linkfunc) ();
76
77 /* If nonzero, make symbolic links; otherwise, make hard links.  */
78 static int symbolic_link;
79
80 /* If nonzero, ask the user before removing existing files.  */
81 static int interactive;
82
83 /* If nonzero, remove existing files unconditionally.  */
84 static int remove_existing_files;
85
86 /* If nonzero, list each file as it is moved. */
87 static int verbose;
88
89 /* If nonzero, allow the superuser to make hard links to directories. */
90 static int hard_dir_link;
91
92 /* If nonzero, and the specified destination is a symbolic link to a
93    directory, treat it just as if it were a directory.  Otherwise, the
94    command `ln --force --no-dereference file symlink-to-dir' deletes
95    symlink-to-dir before creating the new link.  */
96 static int dereference_dest_dir_symlinks = 1;
97
98 /* If non-zero, display usage information and exit.  */
99 static int show_help;
100
101 /* If non-zero, print the version on standard output and exit.  */
102 static int show_version;
103
104 static struct option const long_options[] =
105 {
106   {"backup", no_argument, NULL, 'b'},
107   {"directory", no_argument, &hard_dir_link, 1},
108   {"no-dereference", no_argument, NULL, 'n'},
109   {"force", no_argument, NULL, 'f'},
110   {"interactive", no_argument, NULL, 'i'},
111   {"suffix", required_argument, NULL, 'S'},
112   {"symbolic", no_argument, &symbolic_link, 1},
113   {"verbose", no_argument, &verbose, 1},
114   {"version-control", required_argument, NULL, 'V'},
115   {"help", no_argument, &show_help, 1},
116   {"version", no_argument, &show_version, 1},
117   {NULL, 0, NULL, 0}
118 };
119
120 void
121 main (argc, argv)
122      int argc;
123      char **argv;
124 {
125   int c;
126   int errors;
127   int make_backups = 0;
128   char *version;
129
130   version = getenv ("SIMPLE_BACKUP_SUFFIX");
131   if (version)
132     simple_backup_suffix = version;
133   version = getenv ("VERSION_CONTROL");
134   program_name = argv[0];
135   linkfunc = link;
136   symbolic_link = remove_existing_files = interactive = verbose
137     = hard_dir_link = 0;
138   errors = 0;
139
140   while ((c = getopt_long (argc, argv, "bdfinsvFS:V:", long_options, (int *) 0))
141          != EOF)
142     {
143       switch (c)
144         {
145         case 0:                 /* Long-named option. */
146           break;
147         case 'b':
148           make_backups = 1;
149           break;
150         case 'd':
151         case 'F':
152           hard_dir_link = 1;
153           break;
154         case 'f':
155           remove_existing_files = 1;
156           interactive = 0;
157           break;
158         case 'i':
159           remove_existing_files = 0;
160           interactive = 1;
161           break;
162         case 'n':
163           dereference_dest_dir_symlinks = 0;
164           break;
165         case 's':
166 #ifdef S_ISLNK
167           symbolic_link = 1;
168 #else
169           error (1, 0, "symbolic links are not supported on this system");
170 #endif
171           break;
172         case 'v':
173           verbose = 1;
174           break;
175         case 'S':
176           simple_backup_suffix = optarg;
177           break;
178         case 'V':
179           version = optarg;
180           break;
181         default:
182           usage (1);
183           break;
184         }
185     }
186
187   if (show_version)
188     {
189       printf ("%s\n", version_string);
190       exit (0);
191     }
192
193   if (show_help)
194     usage (0);
195
196   if (optind == argc)
197     {
198       error (0, 0, "missing file argument");
199       usage (1);
200     }
201
202   if (make_backups)
203     backup_type = get_version (version);
204
205 #ifdef S_ISLNK
206   if (symbolic_link)
207     linkfunc = symlink;
208 #endif
209
210   if (optind == argc - 1)
211     errors = do_link (argv[optind], ".");
212   else if (optind == argc - 2)
213     {
214       struct stat source_stats;
215       char *source;
216       char *dest;
217       char *new_dest;
218
219       source = argv[optind];
220       dest = argv[optind + 1];
221
222       /* When the destination is specified with a trailing slash and the
223          source exists but is not a directory, convert the user's command
224          `ln source dest/' to `ln source dest/basename(source)'.  */
225
226       if (dest[strlen (dest) - 1] == '/'
227           && lstat (source, &source_stats) == 0
228           && !S_ISDIR (source_stats.st_mode))
229         {
230           PATH_BASENAME_CONCAT (new_dest, dest, source);
231         }
232       else
233         {
234           new_dest = dest;
235         }
236
237       errors = do_link (source, new_dest);
238     }
239   else
240     {
241       char *to;
242
243       to = argv[argc - 1];
244       if (!isdir (to))
245         error (1, 0, "when making multiple links, last argument must be a directory");
246       for (; optind < argc - 1; ++optind)
247         errors += do_link (argv[optind], to);
248     }
249
250   exit (errors != 0);
251 }
252
253 /* Make a link DEST to the (usually) existing file SOURCE.
254    Symbolic links to nonexistent files are allowed.
255    If DEST is a directory, put the link to SOURCE in that directory.
256    Return 1 if there is an error, otherwise 0.  */
257
258 static int
259 do_link (source, dest)
260      char *source;
261      char *dest;
262 {
263   struct stat dest_stats;
264   char *dest_backup = NULL;
265   int lstat_status;
266
267   /* Use stat here instead of lstat.
268      On SVR4, link does not follow symlinks, so this check disallows
269      making hard links to symlinks that point to directories.  Big deal.
270      On other systems, link follows symlinks, so this check is right.  */
271   if (!symbolic_link)
272     {
273       struct stat source_stats;
274
275       if (stat (source, &source_stats) != 0)
276         {
277           error (0, errno, "%s", source);
278           return 1;
279         }
280       if (!hard_dir_link && S_ISDIR (source_stats.st_mode))
281         {
282           error (0, 0, "%s: hard link not allowed for directory", source);
283           return 1;
284         }
285     }
286
287   if (lstat (dest, &dest_stats) != 0 && errno != ENOENT)
288     {
289       error (0, errno, "%s", dest);
290       return 1;
291     }
292
293   /* If the destination is a directory or (it is a symlink to a directory
294      and the user has not specified --no-dereference), then form the
295      actual destination name by appending basename (source) to the
296      specified destination directory.  */
297   lstat_status = lstat (dest, &dest_stats);
298
299   if (lstat_status != 0 && errno != ENOENT)
300     {
301       error (0, errno, "%s", dest);
302       return 1;
303     }
304
305   if ((lstat_status == 0
306        && S_ISDIR (dest_stats.st_mode))
307 #ifdef S_ISLNK
308       || (dereference_dest_dir_symlinks
309           && (S_ISLNK (dest_stats.st_mode)
310           && isdir (dest)))
311 #endif
312      )
313     {
314       /* Target is a directory; build the full filename. */
315       char *new_dest;
316       PATH_BASENAME_CONCAT (new_dest, dest, source);
317       dest = new_dest;
318       /* Set this to non-zero to force another call to lstat
319          with the new destination.  */
320       lstat_status = 1;
321     }
322
323   if (lstat_status == 0 || lstat (dest, &dest_stats) == 0)
324     {
325       if (S_ISDIR (dest_stats.st_mode))
326         {
327           error (0, 0, "%s: cannot overwrite directory", dest);
328           return 1;
329         }
330       if (interactive)
331         {
332           fprintf (stderr, "%s: replace `%s'? ", program_name, dest);
333           if (!yesno ())
334             return 0;
335         }
336       else if (!remove_existing_files)
337         {
338           error (0, 0, "%s: File exists", dest);
339           return 1;
340         }
341
342       if (backup_type != none)
343         {
344           char *tmp_backup = find_backup_file_name (dest);
345           if (tmp_backup == NULL)
346             error (1, 0, "virtual memory exhausted");
347           dest_backup = (char *) alloca (strlen (tmp_backup) + 1);
348           strcpy (dest_backup, tmp_backup);
349           free (tmp_backup);
350           if (rename (dest, dest_backup))
351             {
352               if (errno != ENOENT)
353                 {
354                   error (0, errno, "cannot backup `%s'", dest);
355                   return 1;
356                 }
357               else
358                 dest_backup = NULL;
359             }
360         }
361       else if (unlink (dest) && errno != ENOENT)
362         {
363           error (0, errno, "cannot remove `%s'", dest);
364           return 1;
365         }
366     }
367   else if (errno != ENOENT)
368     {
369       error (0, errno, "%s", dest);
370       return 1;
371     }
372
373   if (verbose)
374     printf ("%s -> %s\n", source, dest);
375
376   if ((*linkfunc) (source, dest) == 0)
377     {
378       return 0;
379     }
380
381   error (0, errno, "cannot %slink `%s' to `%s'",
382 #ifdef S_ISLNK
383          symbolic_link ? "symbolic " : "",
384 #else
385          "",
386 #endif
387          source, dest);
388
389   if (dest_backup)
390     {
391       if (rename (dest_backup, dest))
392         error (0, errno, "cannot un-backup `%s'", dest);
393     }
394   return 1;
395 }
396
397 static void
398 usage (status)
399      int status;
400 {
401   if (status != 0)
402     fprintf (stderr, "Try `%s --help' for more information.\n",
403              program_name);
404   else
405     {
406       printf ("\
407 Usage: %s [OPTION]... SOURCE [DEST]\n\
408   or:  %s [OPTION]... SOURCE... DIRECTORY\n\
409 ",
410               program_name, program_name);
411       printf ("\
412 \n\
413   -b, --backup                 make backups for removed files\n\
414   -d, -F, --directory          hard link directories (super-user only)\n\
415   -f, --force                  remove existing destinations\n\
416   -n, --no-dereference         with --force, remove destination that is a\n\
417                                  symlink to a directory\n\
418   -i, --interactive            prompt whether to remove destinations\n\
419   -s, --symbolic               make symbolic links, instead of hard links\n\
420   -v, --verbose                print name of each file before linking\n\
421   -S, --suffix=SUFFIX          override the usual backup suffix\n\
422   -V, --version-control=WORD   override the usual version control\n\
423       --help                   display this help and exit\n\
424       --version                output version information and exit\n\
425 \n\
426 The backup suffix is ~, unless set with SIMPLE_BACKUP_SUFFIX.  The\n\
427 version control may be set with VERSION_CONTROL, values are:\n\
428 \n\
429   t, numbered     make numbered backups\n\
430   nil, existing   numbered if numbered backups exist, simple otherwise\n\
431   never, simple   always make simple backups\n");
432     }
433   exit (status);
434 }