diff options
Diffstat (limited to 'toys')
-rw-r--r-- | toys/pending/gzip.c | 57 |
1 files changed, 25 insertions, 32 deletions
diff --git a/toys/pending/gzip.c b/toys/pending/gzip.c index bc059dd6..56d1e46a 100644 --- a/toys/pending/gzip.c +++ b/toys/pending/gzip.c @@ -64,7 +64,7 @@ GLOBALS( #if CFG_TOYBOX_LIBZ #include <zlib.h> -// Read fron in_fd, write to out_fd, decompress if dd else compress +// Read from in_fd, write to out_fd, decompress if dd else compress static int do_deflate(int in_fd, int out_fd, int dd, int level) { int len, err = 0; @@ -110,48 +110,41 @@ static int do_deflate(int in_fd, int out_fd, int dd, int level) #endif -static void do_gzip(int in_fd, char *arg) +static void do_gzip(int ifd, char *in) { struct stat sb; - int len, out_fd = 0; - char *out_name = 0; + char *out = 0; + int ofd = 0; // Are we writing to stdout? - if (!in_fd || (toys.optflags&FLAG_c)) out_fd = 1; - if (isatty(in_fd)) { - if (!(toys.optflags&FLAG_f)) - return error_msg("%s:need -f to read TTY"+3*!!in_fd, arg); - else out_fd = 1; + if (!ifd || FLAG(c)) ofd = 1; + if (isatty(ifd)) { + if (!FLAG(f)) return error_msg("%s:need -f to read TTY"+3*!!ifd, in); + else ofd = 1; } // Are we reading file.gz to write to file? - if (!out_fd) { - if (fstat(in_fd, &sb)) return perror_msg("%s", arg); - - if (!(toys.optflags&FLAG_d)) out_name = xmprintf("%s%s", arg, ".gz"); - else { - // "gunzip x.gz" will decompress "x.gz" to "x". - if ((len = strlen(arg))<4 || strcmp(arg+len-3, ".gz")) - return error_msg("no .gz: %s", arg); - out_name = xstrdup(arg); - out_name[len-3] = 0; - } - - out_fd = xcreate(out_name, - O_CREAT|O_WRONLY|WARN_ONLY|(O_EXCL*!(toys.optflags&FLAG_f)), sb.st_mode); - if (out_fd == -1) return; + if (!ofd) { + if (fstat(ifd, &sb)) return perror_msg("%s", in); + + // Add or remove .gz suffix as necessary + if (!FLAG(d)) out = xmprintf("%s%s", in, ".gz"); + else if ((out = strend(out, ".gz"))>in) out = xstrndup(out, out-in); + else return error_msg("no .gz: %s", in); + + ofd = xcreate(out, O_CREAT|O_WRONLY|WARN_ONLY|(O_EXCL*!FLAG(f)),sb.st_mode); + if (ofd == -1) return; } - if (do_deflate(in_fd, out_fd, toys.optflags&FLAG_d, TT.level) && out_name) - arg = out_name; - if (out_fd != 1) close(out_fd); + if (do_deflate(ifd, ofd, FLAG(d), TT.level)) in = out; - if (out_name) { - struct timespec times[] = { sb.st_atim, sb.st_mtim }; + if (out) { + struct timespec times[] = {sb.st_atim, sb.st_mtim}; - if (utimensat(AT_FDCWD, out_name, times, 0)) perror_exit("utimensat"); - if (!(toys.optflags&FLAG_k)) if (unlink(arg)) perror_msg("unlink %s", arg); - free(out_name); + if (futimens(ofd, times)) perror_exit("utimensat"); + close(ofd); + if (!FLAG(k) && in && unlink(in)) perror_msg("unlink %s", in); + free(out); } } |