2 * This file is part of DisOrder.
3 * Copyright (C) 2006, 2007, 2008 Richard Kettlewell
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
39 /* Arguments etc ----------------------------------------------------------- */
41 typedef int copyfn(const char *from
, const char *to
);
42 typedef int mkdirfn(const char *dir
, mode_t mode
);
44 /* Input and output directories */
45 static const char *source
, *destination
;
47 /* Function used to copy or link a file */
48 static copyfn
*copier
= link
;
50 /* Function used to make a directory */
51 static mkdirfn
*dirmaker
= mkdir
;
53 /* Various encodings */
54 static const char *fromencoding
, *toencoding
, *tagencoding
;
56 /* Directory for untagged files */
57 static const char *untagged
;
59 /* Extract tag information? */
60 static int extracttags
;
62 /* Windows-friendly filenames? */
63 static int windowsfriendly
;
65 /* Native character encoding (i.e. from LC_CTYPE) */
66 static const char *nativeencoding
;
71 /* Included/excluded filename patterns */
72 static struct pattern
{
76 } *patterns
, **patterns_end
= &patterns
;
78 static int default_inclusion
= 1;
80 static const struct option options
[] = {
81 { "help", no_argument
, 0, 'h' },
82 { "version", no_argument
, 0, 'V' },
83 { "debug", no_argument
, 0, 'd' },
84 { "from", required_argument
, 0, 'f' },
85 { "to", required_argument
, 0, 't' },
86 { "include", required_argument
, 0, 'i' },
87 { "exclude", required_argument
, 0, 'e' },
88 { "extract-tags", no_argument
, 0, 'E' },
89 { "tag-encoding", required_argument
, 0, 'T' },
90 { "untagged", required_argument
, 0, 'u' },
91 { "windows-friendly", no_argument
, 0, 'w' },
92 { "link", no_argument
, 0, 'l' },
93 { "symlink", no_argument
, 0, 's' },
94 { "copy", no_argument
, 0, 'c' },
95 { "no-action", no_argument
, 0, 'n' },
99 /* display usage message and terminate */
100 static void help(void) {
102 " disorderfm [OPTIONS] SOURCE DESTINATION\n"
104 " --from, -f ENCODING Source encoding\n"
105 " --to, -t ENCODING Destination encoding\n"
106 "If neither --from nor --to are specified then no encoding translation is\n"
107 "performed. If only one is specified then the other defaults to the current\n"
108 "locale's encoding.\n"
109 " --windows-friendly, -w Replace illegal characters with '_'\n"
110 " --include, -i PATTERN Include files matching a glob pattern\n"
111 " --exclude, -e PATTERN Include files matching a glob pattern\n"
112 "--include and --exclude may be used multiple times. They are checked in\n"
113 "order and the first match wins. If --include is ever used then nonmatching\n"
114 "files are excluded, otherwise they are included.\n"
115 " --link, -l Link files from source to destination (default)\n"
116 " --symlink, -s Symlink files from source to destination\n"
117 " --copy, -c Copy files from source to destination\n"
118 " --no-action, -n Just report what would be done\n"
119 " --debug, -d Debug mode\n"
120 " --help, -h Display usage message\n"
121 " --version, -V Display version number\n");
122 /* TODO: tag extraction stuff when implemented */
127 /* Utilities --------------------------------------------------------------- */
129 /* Copy FROM to TO. Has the same signature as link/symlink. */
130 static int copy(const char *from
, const char *to
) {
135 if((fdin
= open(from
, O_RDONLY
)) < 0)
136 fatal(errno
, "error opening %s", from
);
137 if((fdout
= open(to
, O_WRONLY
|O_CREAT
|O_TRUNC
, 0666)) < 0)
138 fatal(errno
, "error opening %s", to
);
139 while((n
= read(fdin
, buffer
, sizeof buffer
)) > 0) {
140 if(write(fdout
, buffer
, n
) < 0)
141 fatal(errno
, "error writing to %s", to
);
143 if(n
< 0) fatal(errno
, "error reading %s", from
);
144 if(close(fdout
) < 0) fatal(errno
, "error closing %s", to
);
149 static int nocopy(const char *from
, const char *to
) {
150 xprintf("%s -> %s\n",
151 any2mb(fromencoding
, from
),
152 any2mb(toencoding
, to
));
156 static int nomkdir(const char *dir
, mode_t
attribute((unused
)) mode
) {
157 xprintf("mkdir %s\n", any2mb(toencoding
, dir
));
161 /* Name translation -------------------------------------------------------- */
163 static int bad_windows_char(int c
) {
167 /* Documented as bad by MS */
174 /* Not documented as bad by MS but Samba mangles anyway? */
180 /* Return the translated form of PATH */
181 static char *nametrans(const char *path
) {
182 char *t
= any2any(fromencoding
, toencoding
, path
);
184 if(windowsfriendly
) {
186 * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/naming_a_file.asp?frame=true&hidetoc=true */
187 /* List of forbidden names */
188 static const char *const devicenames
[] = {
189 "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5",
190 "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5",
191 "LPT6", "LPT7", "LPT8", "LPT9", "CLOCK$"
193 #define NDEVICENAMES (sizeof devicenames / sizeof *devicenames)
197 /* Certain characters are just not allowed. We replace them with
200 if(bad_windows_char((unsigned char)*s
))
202 /* Trailing spaces and dots are not allowed. We just strip them. */
203 while(s
> t
&& (s
[-1] == ' ' || s
[-1] == '.'))
206 /* Reject device names */
207 if((s
= strchr(t
, '.'))) l
= s
- t
;
209 for(n
= 0; n
< NDEVICENAMES
; ++n
)
210 if(l
== strlen(devicenames
[n
]) && !strncasecmp(devicenames
[n
], t
, l
))
213 byte_xasprintf(&t
, "_%s", t
);
218 /* The file walker --------------------------------------------------------- */
220 /* Visit file or directory PATH relative to SOURCE. SOURCE is a null pointer
223 * PATH is something we extracted from the filesystem so by assumption is in
224 * the FROM encoding, which might _not_ be the same as the current locale's
227 * For most errors we carry on as best we can.
229 static void visit(const char *path
, const char *destpath
) {
230 const struct pattern
*p
;
232 /* fullsourcepath is the full source pathname for PATH */
233 char *fullsourcepath
;
234 /* fulldestpath will be the full destination pathname */
236 /* String to use in error messags. We convert to the current locale; this
237 * may be somewhat misleading but is necessary to avoid getting EILSEQ in
239 char *errsourcepath
, *errdestpath
;
241 D(("visit %s", path ? path
: "NULL"));
243 /* Set up all the various path names */
245 byte_xasprintf(&fullsourcepath
, "%s/%s",
247 byte_xasprintf(&fulldestpath
, "%s/%s",
248 destination
, destpath
);
249 byte_xasprintf(&errsourcepath
, "%s/%s",
250 source
, any2mb(fromencoding
, path
));
251 byte_xasprintf(&errdestpath
, "%s/%s",
252 destination
, any2mb(toencoding
, destpath
));
253 for(p
= patterns
; p
; p
= p
->next
)
254 if(fnmatch(p
->pattern
, path
, FNM_PATHNAME
) == 0)
257 /* We found a matching pattern */
259 D(("%s matches %s therefore excluding",
264 /* We did not find a matching pattern */
265 if(!default_inclusion
) {
266 D(("%s matches nothing and not including by default", path
));
271 fullsourcepath
= errsourcepath
= (char *)source
;
272 fulldestpath
= errdestpath
= (char *)destination
;
275 /* The destination directory might be a subdirectory of the source
276 * directory. In that case we'd better not descend into it when we encounter
277 * it in the source. */
278 if(!strcmp(fullsourcepath
, destination
)) {
279 info("%s matches destination directory, not recursing", errsourcepath
);
283 /* Find out what kind of file we're dealing with */
284 if(stat(fullsourcepath
, &sb
) < 0) {
285 error(errno
, "cannot stat %s", errsourcepath
);
289 if(S_ISREG(sb
.st_mode
)) {
291 if(unlink(fulldestpath
) < 0 && errno
!= ENOENT
) {
292 error(errno
, "cannot remove %s", errdestpath
);
296 if(copier(fullsourcepath
, fulldestpath
) < 0) {
297 error(errno
, "cannot link %s to %s", errsourcepath
, errdestpath
);
301 } else if(S_ISDIR(sb
.st_mode
)) {
304 char *childpath
, *childdestpath
;
306 /* We create the directory on the destination side. If it already exists,
308 if(dirmaker(fulldestpath
, 0777) < 0 && errno
!= EEXIST
) {
309 error(errno
, "cannot mkdir %s", errdestpath
);
313 /* We read the directory and visit all the files in it in any old order. */
314 if(!(dp
= opendir(fullsourcepath
))) {
315 error(errno
, "cannot open directory %s", errsourcepath
);
319 while(((errno
= 0), (de
= readdir(dp
)))) {
320 if(!strcmp(de
->d_name
, ".")
321 || !strcmp(de
->d_name
, "..")) continue;
323 byte_xasprintf(&childpath
, "%s/%s", path
, de
->d_name
);
324 byte_xasprintf(&childdestpath
, "%s/%s",
325 destpath
, nametrans(de
->d_name
));
327 childpath
= de
->d_name
;
328 childdestpath
= nametrans(de
->d_name
);
330 visit(childpath
, childdestpath
);
332 if(errno
) fatal(errno
, "error reading directory %s", errsourcepath
);
335 /* We don't handle special files, but we'd better warn the user. */
336 info("ignoring %s", errsourcepath
);
340 int main(int argc
, char **argv
) {
345 if(!setlocale(LC_CTYPE
, "")) fatal(errno
, "error calling setlocale");
346 while((n
= getopt_long(argc
, argv
, "hVdf:t:i:e:ET:u:wlscn", options
, 0)) >= 0) {
349 case 'V': version("disorderfm");
350 case 'd': debugging
= 1; break;
351 case 'f': fromencoding
= optarg
; break;
352 case 't': toencoding
= optarg
; break;
355 p
= xmalloc(sizeof *p
);
360 patterns_end
= &p
->next
;
361 if(n
== 'i') default_inclusion
= 0;
363 case 'E': extracttags
= 1; break;
364 case 'T': tagencoding
= optarg
; break;
365 case 'u': untagged
= optarg
; break;
366 case 'w': windowsfriendly
= 1; break;
367 case 'l': copier
= link
; break;
368 case 's': copier
= symlink
; break;
369 case 'c': copier
= copy
; break;
370 case 'n': copier
= nocopy
; dirmaker
= nomkdir
; break;
371 default: fatal(0, "invalid option");
374 if(optind
== argc
) fatal(0, "missing SOURCE and DESTINATION arguments");
375 else if(optind
+ 1 == argc
) fatal(0, "missing DESTINATION argument");
376 else if(optind
+ 2 != argc
) fatal(0, "redundant extra arguments");
377 if(extracttags
) fatal(0, "--extract-tags is not implemented yet"); /* TODO */
378 if(tagencoding
&& !extracttags
)
379 fatal(0, "--tag-encoding without --extra-tags does not make sense");
380 if(untagged
&& !extracttags
)
381 fatal(0, "--untagged without --extra-tags does not make sense");
382 source
= argv
[optind
];
383 destination
= argv
[optind
+ 1];
384 nativeencoding
= nl_langinfo(CODESET
);
385 if(fromencoding
|| toencoding
) {
386 if(!fromencoding
) fromencoding
= nativeencoding
;
387 if(!toencoding
) toencoding
= nativeencoding
;
389 if(!tagencoding
) tagencoding
= nativeencoding
;
392 if(errors
) fprintf(stderr
, "%ld errors\n", errors
);