(usage): Include one- or two-line synopsis in --help output.
[platform/upstream/coreutils.git] / src / mv.c
1 /* mv -- move or rename 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
18 /* Options:
19    -f, --force          Assume a 'y' answer to all questions it would
20                         normally ask, and not ask the questions.
21
22    -i, --interactive    Require confirmation from the user before
23                         performing any move that would destroy an
24                         existing file.
25
26    -u, --update         Do not move a nondirectory that has an
27                         existing destination with the same or newer
28                         modification time.
29
30    -v, --verbose                List the name of each file as it is moved, and
31                         the name it is moved to.
32
33    -b, --backup
34    -S, --suffix
35    -V, --version-control
36                         Backup file creation.
37
38    Written by Mike Parker and David MacKenzie */
39
40 #ifdef _AIX
41  #pragma alloca
42 #endif
43
44 #include <config.h>
45 #include <stdio.h>
46 #include <getopt.h>
47 #include <sys/types.h>
48
49 #include "system.h"
50 #include "backupfile.h"
51 #include "version.h"
52 #include "error.h"
53
54 #ifndef _POSIX_VERSION
55 uid_t geteuid ();
56 #endif
57
58 char *basename ();
59 enum backup_type get_version ();
60 int isdir ();
61 int yesno ();
62 int safe_read ();
63 int full_write ();
64 void strip_trailing_slashes ();
65 int eaccess_stat ();
66 char *stpcpy ();
67
68 static int copy_reg ();
69 static int do_move ();
70 static int movefile ();
71 static void usage ();
72
73 /* The name this program was run with. */
74 char *program_name;
75
76 /* If nonzero, query the user before overwriting files. */
77 static int interactive;
78
79 /* If nonzero, do not query the user before overwriting unwritable
80    files. */
81 static int override_mode;
82
83 /* If nonzero, do not move a nondirectory that has an existing destination
84    with the same or newer modification time. */
85 static int update = 0;
86
87 /* If nonzero, list each file as it is moved. */
88 static int verbose;
89
90 /* If nonzero, stdin is a tty. */
91 static int stdin_tty;
92
93 /* This process's effective user ID.  */
94 static uid_t myeuid;
95
96 /* If non-zero, display usage information and exit.  */
97 static int show_help;
98
99 /* If non-zero, print the version on standard output and exit.  */
100 static int show_version;
101
102 static struct option const long_options[] =
103 {
104   {"backup", no_argument, NULL, 'b'},
105   {"force", no_argument, NULL, 'f'},
106   {"interactive", no_argument, NULL, 'i'},
107   {"suffix", required_argument, NULL, 'S'},
108   {"update", no_argument, &update, 1},
109   {"verbose", no_argument, &verbose, 1},
110   {"version-control", required_argument, NULL, 'V'},
111   {"help", no_argument, &show_help, 1},
112   {"version", no_argument, &show_version, 1},
113   {NULL, 0, NULL, 0}
114 };
115
116 void
117 main (argc, argv)
118      int argc;
119      char **argv;
120 {
121   int c;
122   int errors;
123   int make_backups = 0;
124   char *version;
125
126   version = getenv ("SIMPLE_BACKUP_SUFFIX");
127   if (version)
128     simple_backup_suffix = version;
129   version = getenv ("VERSION_CONTROL");
130   program_name = argv[0];
131   myeuid = geteuid ();
132   interactive = override_mode = verbose = update = 0;
133   errors = 0;
134
135   while ((c = getopt_long (argc, argv, "bfiuvS:V:", long_options, (int *) 0))
136          != EOF)
137     {
138       switch (c)
139         {
140         case 0:
141           break;
142         case 'b':
143           make_backups = 1;
144           break;
145         case 'f':
146           interactive = 0;
147           override_mode = 1;
148           break;
149         case 'i':
150           interactive = 1;
151           override_mode = 0;
152           break;
153         case 'u':
154           update = 1;
155           break;
156         case 'v':
157           verbose = 1;
158           break;
159         case 'S':
160           simple_backup_suffix = optarg;
161           break;
162         case 'V':
163           version = optarg;
164           break;
165         default:
166           usage (1);
167         }
168     }
169
170   if (show_version)
171     {
172       printf ("%s\n", version_string);
173       exit (0);
174     }
175
176   if (show_help)
177     usage (0);
178
179   if (argc < optind + 2)
180     {
181       error (0, 0, "missing file argument%s", argc == optind ? "s" : "");
182       usage (1);
183     }
184
185   if (make_backups)
186     backup_type = get_version (version);
187
188   stdin_tty = isatty (STDIN_FILENO);
189
190   if (argc > optind + 2 && !isdir (argv[argc - 1]))
191     error (1, 0, "when moving multiple files, last argument must be a directory");
192
193   /* Move each arg but the last onto the last. */
194   for (; optind < argc - 1; ++optind)
195     errors |= movefile (argv[optind], argv[argc - 1]);
196
197   exit (errors);
198 }
199
200 /* If PATH is an existing directory, return nonzero, else 0.  */
201
202 static int
203 is_real_dir (path)
204      char *path;
205 {
206   struct stat stats;
207
208   return lstat (path, &stats) == 0 && S_ISDIR (stats.st_mode);
209 }
210
211 /* Move file SOURCE onto DEST.  Handles the case when DEST is a directory.
212    Return 0 if successful, 1 if an error occurred.  */
213
214 static int
215 movefile (source, dest)
216      char *source;
217      char *dest;
218 {
219   strip_trailing_slashes (source);
220
221   if ((dest[strlen (dest) - 1] == '/' && !is_real_dir (source))
222       || isdir (dest))
223     {
224       /* Target is a directory; build full target filename. */
225       char *base;
226       char *new_dest;
227
228       base = basename (source);
229       /* Remove a (single) trailing slash if there is at least one.  */
230       if (dest[strlen (dest) - 1] == '/')
231         dest[strlen (dest) - 1] = '\0';
232       new_dest = (char *) alloca (strlen (dest) + 1 + strlen (base) + 1);
233       stpcpy (stpcpy (stpcpy (new_dest, dest), "/"), base);
234       return do_move (source, new_dest);
235     }
236   else
237     return do_move (source, dest);
238 }
239
240 static struct stat dest_stats, source_stats;
241
242 /* Move SOURCE onto DEST.  Handles cross-filesystem moves.
243    If DEST is a directory, SOURCE must be also.
244    Return 0 if successful, 1 if an error occurred.  */
245
246 static int
247 do_move (source, dest)
248      char *source;
249      char *dest;
250 {
251   char *dest_backup = NULL;
252
253   if (lstat (source, &source_stats) != 0)
254     {
255       error (0, errno, "%s", source);
256       return 1;
257     }
258
259   if (lstat (dest, &dest_stats) == 0)
260     {
261       if (source_stats.st_dev == dest_stats.st_dev
262           && source_stats.st_ino == dest_stats.st_ino)
263         {
264           error (0, 0, "`%s' and `%s' are the same file", source, dest);
265           return 1;
266         }
267
268       if (S_ISDIR (dest_stats.st_mode))
269         {
270           error (0, 0, "%s: cannot overwrite directory", dest);
271           return 1;
272         }
273
274       if (!S_ISDIR (source_stats.st_mode) && update
275           && source_stats.st_mtime <= dest_stats.st_mtime)
276         return 0;
277
278       if (!override_mode && (interactive || stdin_tty)
279           && eaccess_stat (&dest_stats, W_OK, dest))
280         {
281           fprintf (stderr, "%s: replace `%s', overriding mode %04o? ",
282                    program_name, dest,
283                    (unsigned int) (dest_stats.st_mode & 07777));
284           if (!yesno ())
285             return 0;
286         }
287       else if (interactive)
288         {
289           fprintf (stderr, "%s: replace `%s'? ", program_name, dest);
290           if (!yesno ())
291             return 0;
292         }
293
294       if (backup_type != none)
295         {
296           char *tmp_backup = find_backup_file_name (dest);
297           if (tmp_backup == NULL)
298             error (1, 0, "virtual memory exhausted");
299           dest_backup = (char *) alloca (strlen (tmp_backup) + 1);
300           strcpy (dest_backup, tmp_backup);
301           free (tmp_backup);
302           if (rename (dest, dest_backup))
303             {
304               if (errno != ENOENT)
305                 {
306                   error (0, errno, "cannot backup `%s'", dest);
307                   return 1;
308                 }
309               else
310                 dest_backup = NULL;
311             }
312         }
313     }
314   else if (errno != ENOENT)
315     {
316       error (0, errno, "%s", dest);
317       return 1;
318     }
319
320   if (verbose)
321     printf ("%s -> %s\n", source, dest);
322
323   if (rename (source, dest) == 0)
324     {
325       return 0;
326     }
327
328   if (errno != EXDEV)
329     {
330       error (0, errno, "cannot move `%s' to `%s'", source, dest);
331       goto un_backup;
332     }
333
334   /* rename failed on cross-filesystem link.  Copy the file instead. */
335
336   if (copy_reg (source, dest))
337     goto un_backup;
338
339   if (unlink (source))
340     {
341       error (0, errno, "cannot remove `%s'", source);
342       return 1;
343     }
344
345   return 0;
346
347  un_backup:
348   if (dest_backup)
349     {
350       if (rename (dest_backup, dest))
351         error (0, errno, "cannot un-backup `%s'", dest);
352     }
353   return 1;
354 }
355
356 /* Copy regular file SOURCE onto file DEST.
357    Return 1 if an error occurred, 0 if successful. */
358
359 static int
360 copy_reg (source, dest)
361      char *source, *dest;
362 {
363   int ifd;
364   int ofd;
365   char buf[1024 * 8];
366   int len;                      /* Number of bytes read into `buf'. */
367
368   if (!S_ISREG (source_stats.st_mode))
369     {
370       error (0, 0, "cannot move `%s' across filesystems: Not a regular file",
371              source);
372       return 1;
373     }
374
375   if (unlink (dest) && errno != ENOENT)
376     {
377       error (0, errno, "cannot remove `%s'", dest);
378       return 1;
379     }
380
381   ifd = open (source, O_RDONLY, 0);
382   if (ifd < 0)
383     {
384       error (0, errno, "%s", source);
385       return 1;
386     }
387   ofd = open (dest, O_WRONLY | O_CREAT | O_TRUNC, 0600);
388   if (ofd < 0)
389     {
390       error (0, errno, "%s", dest);
391       close (ifd);
392       return 1;
393     }
394
395   while ((len = safe_read (ifd, buf, sizeof (buf))) > 0)
396     {
397       if (full_write (ofd, buf, len) < 0)
398         {
399           error (0, errno, "%s", dest);
400           close (ifd);
401           close (ofd);
402           unlink (dest);
403           return 1;
404         }
405     }
406   if (len < 0)
407     {
408       error (0, errno, "%s", source);
409       close (ifd);
410       close (ofd);
411       unlink (dest);
412       return 1;
413     }
414
415   if (close (ifd) < 0)
416     {
417       error (0, errno, "%s", source);
418       close (ofd);
419       return 1;
420     }
421   if (close (ofd) < 0)
422     {
423       error (0, errno, "%s", dest);
424       return 1;
425     }
426
427   /* chown turns off set[ug]id bits for non-root,
428      so do the chmod last.  */
429
430   /* Try to copy the old file's modtime and access time.  */
431   {
432     struct utimbuf tv;
433
434     tv.actime = source_stats.st_atime;
435     tv.modtime = source_stats.st_mtime;
436     if (utime (dest, &tv))
437       {
438         error (0, errno, "%s", dest);
439         return 1;
440       }
441   }
442
443   /* Try to preserve ownership.  For non-root it might fail, but that's ok.
444      But root probably wants to know, e.g. if NFS disallows it.  */
445   if (chown (dest, source_stats.st_uid, source_stats.st_gid)
446       && (errno != EPERM || myeuid == 0))
447     {
448       error (0, errno, "%s", dest);
449       return 1;
450     }
451
452   if (chmod (dest, source_stats.st_mode & 07777))
453     {
454       error (0, errno, "%s", dest);
455       return 1;
456     }
457
458   return 0;
459 }
460
461 static void
462 usage (status)
463      int status;
464 {
465   if (status != 0)
466     fprintf (stderr, "Try `%s --help' for more information.\n",
467              program_name);
468   else
469     {
470       printf ("\
471 Usage: %s [OPTION]... SOURCE DEST\n\
472   or:  %s [OPTION]... SOURCE... DIRECTORY\n\
473 ",
474               program_name, program_name);
475       printf ("\
476 \n\
477   -b, --backup                 make backup before removal\n\
478   -f, --force                  remove existing destinations, never prompt\n\
479   -i, --interactive            prompt before overwrite\n\
480   -u, --update                 move only older or brand new files\n\
481   -v, --verbose                explain what is being done\n\
482   -S, --suffix=SUFFIX          override the usual backup suffix\n\
483   -V, --version-control=WORD   override the usual version control\n\
484       --help                   display this help and exit\n\
485       --version                output version information and exit\n\
486 \n\
487 The backup suffix is ~, unless set with SIMPLE_BACKUP_SUFFIX.  The\n\
488 version control may be set with VERSION_CONTROL, values are:\n\
489 \n\
490   t, numbered     make numbered backups\n\
491   nil, existing   numbered if numbered backups exist, simple otherwise\n\
492   never, simple   always make simple backups  \n");
493     }
494   exit (status);
495 }