cp: improve status message when omitting directories
[coreutils.git] / src / mv.c
blob04d2be3ecc551df8a73d0413cceb55b235a4838b
1 /* mv -- move or rename files
2 Copyright (C) 1986-2016 Free Software Foundation, Inc.
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 3 of the License, or
7 (at your option) any later version.
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.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Written by Mike Parker, David MacKenzie, and Jim Meyering */
19 #include <config.h>
20 #include <stdio.h>
21 #include <getopt.h>
22 #include <sys/types.h>
23 #include <assert.h>
24 #include <selinux/selinux.h>
26 #include "system.h"
27 #include "backupfile.h"
28 #include "copy.h"
29 #include "cp-hash.h"
30 #include "die.h"
31 #include "error.h"
32 #include "filenamecat.h"
33 #include "remove.h"
34 #include "root-dev-ino.h"
35 #include "priv-set.h"
37 /* The official name of this program (e.g., no 'g' prefix). */
38 #define PROGRAM_NAME "mv"
40 #define AUTHORS \
41 proper_name ("Mike Parker"), \
42 proper_name ("David MacKenzie"), \
43 proper_name ("Jim Meyering")
45 /* For long options that have no equivalent short option, use a
46 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
47 enum
49 STRIP_TRAILING_SLASHES_OPTION = CHAR_MAX + 1
52 /* Remove any trailing slashes from each SOURCE argument. */
53 static bool remove_trailing_slashes;
55 static struct option const long_options[] =
57 {"backup", optional_argument, NULL, 'b'},
58 {"context", no_argument, NULL, 'Z'},
59 {"force", no_argument, NULL, 'f'},
60 {"interactive", no_argument, NULL, 'i'},
61 {"no-clobber", no_argument, NULL, 'n'},
62 {"no-target-directory", no_argument, NULL, 'T'},
63 {"strip-trailing-slashes", no_argument, NULL, STRIP_TRAILING_SLASHES_OPTION},
64 {"suffix", required_argument, NULL, 'S'},
65 {"target-directory", required_argument, NULL, 't'},
66 {"update", no_argument, NULL, 'u'},
67 {"verbose", no_argument, NULL, 'v'},
68 {GETOPT_HELP_OPTION_DECL},
69 {GETOPT_VERSION_OPTION_DECL},
70 {NULL, 0, NULL, 0}
73 static void
74 rm_option_init (struct rm_options *x)
76 x->ignore_missing_files = false;
77 x->remove_empty_directories = true;
78 x->recursive = true;
79 x->one_file_system = false;
81 /* Should we prompt for removal, too? No. Prompting for the 'move'
82 part is enough. It implies removal. */
83 x->interactive = RMI_NEVER;
84 x->stdin_tty = false;
86 x->verbose = false;
88 /* Since this program may well have to process additional command
89 line arguments after any call to 'rm', that function must preserve
90 the initial working directory, in case one of those is a
91 '.'-relative name. */
92 x->require_restore_cwd = true;
95 static struct dev_ino dev_ino_buf;
96 x->root_dev_ino = get_root_dev_ino (&dev_ino_buf);
97 if (x->root_dev_ino == NULL)
98 die (EXIT_FAILURE, errno, _("failed to get attributes of %s"),
99 quoteaf ("/"));
103 static void
104 cp_option_init (struct cp_options *x)
106 bool selinux_enabled = (0 < is_selinux_enabled ());
108 cp_options_default (x);
109 x->copy_as_regular = false; /* FIXME: maybe make this an option */
110 x->reflink_mode = REFLINK_AUTO;
111 x->dereference = DEREF_NEVER;
112 x->unlink_dest_before_opening = false;
113 x->unlink_dest_after_failed_open = false;
114 x->hard_link = false;
115 x->interactive = I_UNSPECIFIED;
116 x->move_mode = true;
117 x->install_mode = false;
118 x->one_file_system = false;
119 x->preserve_ownership = true;
120 x->preserve_links = true;
121 x->preserve_mode = true;
122 x->preserve_timestamps = true;
123 x->explicit_no_preserve_mode= false;
124 x->preserve_security_context = selinux_enabled;
125 x->set_security_context = false;
126 x->reduce_diagnostics = false;
127 x->data_copy_required = true;
128 x->require_preserve = false; /* FIXME: maybe make this an option */
129 x->require_preserve_context = false;
130 x->preserve_xattr = true;
131 x->require_preserve_xattr = false;
132 x->recursive = true;
133 x->sparse_mode = SPARSE_AUTO; /* FIXME: maybe make this an option */
134 x->symbolic_link = false;
135 x->set_mode = false;
136 x->mode = 0;
137 x->stdin_tty = isatty (STDIN_FILENO);
139 x->open_dangling_dest_symlink = false;
140 x->update = false;
141 x->verbose = false;
142 x->dest_info = NULL;
143 x->src_info = NULL;
146 /* FILE is the last operand of this command. Return true if FILE is a
147 directory. But report an error if there is a problem accessing FILE, other
148 than nonexistence (errno == ENOENT). */
150 static bool
151 target_directory_operand (char const *file)
153 struct stat st;
154 int err = (stat (file, &st) == 0 ? 0 : errno);
155 bool is_a_dir = !err && S_ISDIR (st.st_mode);
156 if (err && err != ENOENT)
157 die (EXIT_FAILURE, err, _("failed to access %s"), quoteaf (file));
158 return is_a_dir;
161 /* Move SOURCE onto DEST. Handles cross-file-system moves.
162 If SOURCE is a directory, DEST must not exist.
163 Return true if successful. */
165 static bool
166 do_move (const char *source, const char *dest, const struct cp_options *x)
168 bool copy_into_self;
169 bool rename_succeeded;
170 bool ok = copy (source, dest, false, x, &copy_into_self, &rename_succeeded);
172 if (ok)
174 char const *dir_to_remove;
175 if (copy_into_self)
177 /* In general, when copy returns with copy_into_self set, SOURCE is
178 the same as, or a parent of DEST. In this case we know it's a
179 parent. It doesn't make sense to move a directory into itself, and
180 besides in some situations doing so would give highly nonintuitive
181 results. Run this 'mkdir b; touch a c; mv * b' in an empty
182 directory. Here's the result of running echo $(find b -print):
183 b b/a b/b b/b/a b/c. Notice that only file 'a' was copied
184 into b/b. Handle this by giving a diagnostic, removing the
185 copied-into-self directory, DEST ('b/b' in the example),
186 and failing. */
188 dir_to_remove = NULL;
189 ok = false;
191 else if (rename_succeeded)
193 /* No need to remove anything. SOURCE was successfully
194 renamed to DEST. Or the user declined to rename a file. */
195 dir_to_remove = NULL;
197 else
199 /* This may mean SOURCE and DEST referred to different devices.
200 It may also conceivably mean that even though they referred
201 to the same device, rename wasn't implemented for that device.
203 E.g., (from Joel N. Weber),
204 [...] there might someday be cases where you can't rename
205 but you can copy where the device name is the same, especially
206 on Hurd. Consider an ftpfs with a primitive ftp server that
207 supports uploading, downloading and deleting, but not renaming.
209 Also, note that comparing device numbers is not a reliable
210 check for 'can-rename'. Some systems can be set up so that
211 files from many different physical devices all have the same
212 st_dev field. This is a feature of some NFS mounting
213 configurations.
215 We reach this point if SOURCE has been successfully copied
216 to DEST. Now we have to remove SOURCE.
218 This function used to resort to copying only when rename
219 failed and set errno to EXDEV. */
221 dir_to_remove = source;
224 if (dir_to_remove != NULL)
226 struct rm_options rm_options;
227 enum RM_status status;
228 char const *dir[2];
230 rm_option_init (&rm_options);
231 rm_options.verbose = x->verbose;
232 dir[0] = dir_to_remove;
233 dir[1] = NULL;
235 status = rm ((void*) dir, &rm_options);
236 assert (VALID_STATUS (status));
237 if (status == RM_ERROR)
238 ok = false;
242 return ok;
245 /* Move file SOURCE onto DEST. Handles the case when DEST is a directory.
246 Treat DEST as a directory if DEST_IS_DIR.
247 Return true if successful. */
249 static bool
250 movefile (char *source, char *dest, bool dest_is_dir,
251 const struct cp_options *x)
253 bool ok;
255 /* This code was introduced to handle the ambiguity in the semantics
256 of mv that is induced by the varying semantics of the rename function.
257 Some systems (e.g., GNU/Linux) have a rename function that honors a
258 trailing slash, while others (like Solaris 5,6,7) have a rename
259 function that ignores a trailing slash. I believe the GNU/Linux
260 rename semantics are POSIX and susv2 compliant. */
262 if (remove_trailing_slashes)
263 strip_trailing_slashes (source);
265 if (dest_is_dir)
267 /* Treat DEST as a directory; build the full filename. */
268 char const *src_basename = last_component (source);
269 char *new_dest = file_name_concat (dest, src_basename, NULL);
270 strip_trailing_slashes (new_dest);
271 ok = do_move (source, new_dest, x);
272 free (new_dest);
274 else
276 ok = do_move (source, dest, x);
279 return ok;
282 void
283 usage (int status)
285 if (status != EXIT_SUCCESS)
286 emit_try_help ();
287 else
289 printf (_("\
290 Usage: %s [OPTION]... [-T] SOURCE DEST\n\
291 or: %s [OPTION]... SOURCE... DIRECTORY\n\
292 or: %s [OPTION]... -t DIRECTORY SOURCE...\n\
294 program_name, program_name, program_name);
295 fputs (_("\
296 Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.\n\
297 "), stdout);
299 emit_mandatory_arg_note ();
301 fputs (_("\
302 --backup[=CONTROL] make a backup of each existing destination file\
304 -b like --backup but does not accept an argument\n\
305 -f, --force do not prompt before overwriting\n\
306 -i, --interactive prompt before overwrite\n\
307 -n, --no-clobber do not overwrite an existing file\n\
308 If you specify more than one of -i, -f, -n, only the final one takes effect.\n\
309 "), stdout);
310 fputs (_("\
311 --strip-trailing-slashes remove any trailing slashes from each SOURCE\n\
312 argument\n\
313 -S, --suffix=SUFFIX override the usual backup suffix\n\
314 "), stdout);
315 fputs (_("\
316 -t, --target-directory=DIRECTORY move all SOURCE arguments into DIRECTORY\n\
317 -T, --no-target-directory treat DEST as a normal file\n\
318 -u, --update move only when the SOURCE file is newer\n\
319 than the destination file or when the\n\
320 destination file is missing\n\
321 -v, --verbose explain what is being done\n\
322 -Z, --context set SELinux security context of destination\n\
323 file to default type\n\
324 "), stdout);
325 fputs (HELP_OPTION_DESCRIPTION, stdout);
326 fputs (VERSION_OPTION_DESCRIPTION, stdout);
327 emit_backup_suffix_note ();
328 emit_ancillary_info (PROGRAM_NAME);
330 exit (status);
334 main (int argc, char **argv)
336 int c;
337 bool ok;
338 bool make_backups = false;
339 char *version_control_string = NULL;
340 struct cp_options x;
341 char *target_directory = NULL;
342 bool no_target_directory = false;
343 int n_files;
344 char **file;
345 bool selinux_enabled = (0 < is_selinux_enabled ());
347 initialize_main (&argc, &argv);
348 set_program_name (argv[0]);
349 setlocale (LC_ALL, "");
350 bindtextdomain (PACKAGE, LOCALEDIR);
351 textdomain (PACKAGE);
353 atexit (close_stdin);
355 cp_option_init (&x);
357 /* Try to disable the ability to unlink a directory. */
358 priv_set_remove_linkdir ();
360 while ((c = getopt_long (argc, argv, "bfint:uvS:TZ", long_options, NULL))
361 != -1)
363 switch (c)
365 case 'b':
366 make_backups = true;
367 if (optarg)
368 version_control_string = optarg;
369 break;
370 case 'f':
371 x.interactive = I_ALWAYS_YES;
372 break;
373 case 'i':
374 x.interactive = I_ASK_USER;
375 break;
376 case 'n':
377 x.interactive = I_ALWAYS_NO;
378 break;
379 case STRIP_TRAILING_SLASHES_OPTION:
380 remove_trailing_slashes = true;
381 break;
382 case 't':
383 if (target_directory)
384 die (EXIT_FAILURE, 0, _("multiple target directories specified"));
385 else
387 struct stat st;
388 if (stat (optarg, &st) != 0)
389 die (EXIT_FAILURE, errno, _("failed to access %s"),
390 quoteaf (optarg));
391 if (! S_ISDIR (st.st_mode))
392 die (EXIT_FAILURE, 0, _("target %s is not a directory"),
393 quoteaf (optarg));
395 target_directory = optarg;
396 break;
397 case 'T':
398 no_target_directory = true;
399 break;
400 case 'u':
401 x.update = true;
402 break;
403 case 'v':
404 x.verbose = true;
405 break;
406 case 'S':
407 make_backups = true;
408 simple_backup_suffix = optarg;
409 break;
410 case 'Z':
411 /* As a performance enhancement, don't even bother trying
412 to "restorecon" when not on an selinux-enabled kernel. */
413 if (selinux_enabled)
415 x.preserve_security_context = false;
416 x.set_security_context = true;
418 break;
419 case_GETOPT_HELP_CHAR;
420 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
421 default:
422 usage (EXIT_FAILURE);
426 n_files = argc - optind;
427 file = argv + optind;
429 if (n_files <= !target_directory)
431 if (n_files <= 0)
432 error (0, 0, _("missing file operand"));
433 else
434 error (0, 0, _("missing destination file operand after %s"),
435 quoteaf (file[0]));
436 usage (EXIT_FAILURE);
439 if (no_target_directory)
441 if (target_directory)
442 die (EXIT_FAILURE, 0,
443 _("cannot combine --target-directory (-t) "
444 "and --no-target-directory (-T)"));
445 if (2 < n_files)
447 error (0, 0, _("extra operand %s"), quoteaf (file[2]));
448 usage (EXIT_FAILURE);
451 else if (!target_directory)
453 assert (2 <= n_files);
454 if (target_directory_operand (file[n_files - 1]))
455 target_directory = file[--n_files];
456 else if (2 < n_files)
457 die (EXIT_FAILURE, 0, _("target %s is not a directory"),
458 quoteaf (file[n_files - 1]));
461 if (make_backups && x.interactive == I_ALWAYS_NO)
463 error (0, 0,
464 _("options --backup and --no-clobber are mutually exclusive"));
465 usage (EXIT_FAILURE);
468 x.backup_type = (make_backups
469 ? xget_version (_("backup type"),
470 version_control_string)
471 : no_backups);
473 hash_init ();
475 if (target_directory)
477 int i;
479 /* Initialize the hash table only if we'll need it.
480 The problem it is used to detect can arise only if there are
481 two or more files to move. */
482 if (2 <= n_files)
483 dest_info_init (&x);
485 ok = true;
486 for (i = 0; i < n_files; ++i)
487 ok &= movefile (file[i], target_directory, true, &x);
489 else
490 ok = movefile (file[0], file[1], false, &x);
492 return ok ? EXIT_SUCCESS : EXIT_FAILURE;