-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.c
114 lines (87 loc) · 2.44 KB
/
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <getopt.h>
#include "src/mmv.h"
/**
* @brief Create struct of possible user flags
* @return Opt struct
*/
static struct Opts *make_opts(void)
{
struct Opts *opts = malloc(sizeof(struct Opts));
if (opts == NULL)
{
perror("mmv: failed to allocate memory for user flags\n");
return NULL;
}
opts->resolve_paths = false;
opts->verbose = false;
return opts;
}
/**
* @brief Print program usage information
*/
static void usage(void)
{
printf("Usage: %s [OPTION] SOURCES\n\n", PROG_NAME);
puts("Rename or move SOURCE(s) by editing them in $EDITOR.");
printf("For full documentation, see man %s\n", PROG_NAME);
}
int main(int argc, char *argv[])
{
int cur_flag;
char short_opts[] = "rhvV";
struct Opts *options = make_opts();
if (options == NULL)
return EXIT_FAILURE;
while ((cur_flag = getopt(argc, argv, short_opts)) != -1)
{
switch (cur_flag)
{
case 'r': options->resolve_paths = true; break;
case 'v': options->verbose = true; break;
case 'h':
free(options);
usage();
return EXIT_SUCCESS;
case 'V':
free(options);
puts(PROG_VERSION);
return EXIT_SUCCESS;
default:
free(options);
puts("Try 'mmv -h'for more information");
return EXIT_FAILURE;
}
}
argv += optind;
argc -= optind;
struct Set *src_set = init_src_set(argc, argv, options);
if (src_set == NULL)
goto free_opts_out;
char tmpfile[] = "/tmp/mmv_editbuf_XXXXXX";
if (write_strarr_to_tmpfile(src_set, tmpfile) != 0)
goto free_src_out;
if (edit_tmpfile(tmpfile) != 0)
goto rm_path_out;
struct Set *dest_set = init_dest_set(src_set->num_keys, tmpfile);
if (dest_set == NULL)
goto rm_path_out;
if (rm_unedited_pairs(src_set, dest_set, options) != 0)
goto free_dest_out;
if (argc > 1 && rm_cycles(src_set, dest_set, options) != 0)
goto free_dest_out;
rename_paths(src_set, dest_set, options);
set_destroy(dest_set);
remove(tmpfile);
set_destroy(src_set);
free(options);
return EXIT_SUCCESS;
free_dest_out:
set_destroy(dest_set);
rm_path_out:
remove(tmpfile);
free_src_out:
set_destroy(src_set);
free_opts_out:
free(options);
return EXIT_FAILURE;
}