18
18
#include <stdlib.h>
20
20
#include <getopt.h>
22
#include <sys/types.h>
23
26
#include "xalloc.h"
28
#include "closestream.h"
26
static int do_rename(char *from, char *to, char *s, int verbose)
30
static int do_rename(char *from, char *to, char *s, int verbose, int symtarget)
28
char *newname, *where, *p, *q;
32
char *newname, *where, *p, *q, *target = NULL;
29
33
int flen, tlen, slen;
31
where = strstr(s, from);
37
if (lstat(s, &sb) == -1)
38
err(EXIT_FAILURE, _("%s: lstat failed"), s);
40
if (!S_ISLNK(sb.st_mode))
41
errx(EXIT_FAILURE, _("%s: not a symbolic link"), s);
43
target = xmalloc(sb.st_size + 1);
44
if (readlink(s, target, sb.st_size + 1) < 0)
45
err(EXIT_FAILURE, _("%s: readlink failed"), s);
47
target[sb.st_size] = '\0';
48
where = strstr(target, from);
50
where = strstr(s, from);
35
57
flen = strlen(from);
60
slen = strlen(target);
38
66
newname = xmalloc(tlen + slen + 1);
52
if (rename(s, newname) != 0)
53
err(EXIT_FAILURE, _("renaming %s to %s failed"),
56
printf("`%s' -> `%s'\n", s, newname);
81
err(EXIT_FAILURE, _("%s: unlink failed"), s);
82
if (symlink(newname, s) != 0)
83
err(EXIT_FAILURE, _("%s: symlinking to %s failed"), s, newname);
85
printf("%s: `%s' -> `%s'\n", s, target, newname);
87
if (rename(s, newname) != 0)
88
err(EXIT_FAILURE, _("%s: rename to %s failed"), s, newname);
90
printf("`%s' -> `%s'\n", s, newname);
62
98
static void __attribute__ ((__noreturn__)) usage(FILE * out)
64
fputs(_("\nUsage:\n"), out);
100
fputs(USAGE_HEADER, out);
66
102
_(" %s [options] expression replacement file...\n"),
67
103
program_invocation_short_name);
69
fputs(_("\nOptions:\n"), out);
70
fputs(_(" -v, --verbose explain what is being done\n"
71
" -V, --version output version information and exit\n"
72
" -h, --help display this help and exit\n\n"), out);
104
fputs(USAGE_OPTIONS, out);
105
fputs(_(" -v, --verbose explain what is being done\n"), out);
106
fputs(_(" -s, --symlink act on symlink target\n"), out);
107
fputs(USAGE_SEPARATOR, out);
108
fputs(USAGE_HELP, out);
109
fputs(USAGE_VERSION, out);
110
fprintf(out, USAGE_MAN_TAIL("rename(1)"));
74
111
exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
77
114
int main(int argc, char **argv)
80
int i, c, verbose = 0;
117
int i, c, symtarget=0, verbose = 0;
82
119
static const struct option longopts[] = {
83
120
{"verbose", no_argument, NULL, 'v'},
84
121
{"version", no_argument, NULL, 'V'},
85
122
{"help", no_argument, NULL, 'h'},
123
{"symlink", no_argument, NULL, 's'},
86
124
{NULL, 0, NULL, 0}
89
127
setlocale(LC_ALL, "");
90
128
bindtextdomain(PACKAGE, LOCALEDIR);
91
129
textdomain(PACKAGE);
130
atexit(close_stdout);
93
while ((c = getopt_long(argc, argv, "vVh", longopts, NULL)) != -1)
132
while ((c = getopt_long(argc, argv, "vsVh", longopts, NULL)) != -1)
99
printf(_("%s from %s\n"),
100
program_invocation_short_name,
141
printf(UTIL_LINUX_VERSION);
102
142
return EXIT_SUCCESS;