Serenity Operating System
1/*
2 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice, this
9 * list of conditions and the following disclaimer.
10 *
11 * 2. Redistributions in binary form must reproduce the above copyright notice,
12 * this list of conditions and the following disclaimer in the documentation
13 * and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
22 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
23 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#include <AK/FileSystemPath.h>
28#include <AK/String.h>
29#include <LibCore/ArgsParser.h>
30#include <stdio.h>
31#include <sys/stat.h>
32#include <unistd.h>
33
34int main(int argc, char** argv)
35{
36 if (pledge("stdio rpath wpath cpath fattr", nullptr) < 0) {
37 perror("pledge");
38 return 1;
39 }
40
41 const char* old_path = nullptr;
42 const char* new_path = nullptr;
43
44 Core::ArgsParser args_parser;
45 args_parser.add_positional_argument(old_path, "The file or directory being moved", "source");
46 args_parser.add_positional_argument(new_path, "destination of the move operation", "destination");
47 args_parser.parse(argc, argv);
48
49 struct stat st;
50
51 int rc = lstat(new_path, &st);
52 if (rc != 0 && errno != ENOENT) {
53 perror("lstat");
54 return 1;
55 }
56
57 String combined_new_path;
58 if (rc == 0 && S_ISDIR(st.st_mode)) {
59 auto old_basename = FileSystemPath(old_path).basename();
60 combined_new_path = String::format("%s/%s", new_path, old_basename.characters());
61 new_path = combined_new_path.characters();
62 }
63
64 rc = rename(old_path, new_path);
65 if (rc < 0) {
66 perror("rename");
67 return 1;
68 }
69 return 0;
70}