summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--ChangeLog25
-rw-r--r--INSTALL2
-rw-r--r--Makefile.in161
-rw-r--r--NEWS11
-rw-r--r--README20
-rw-r--r--arg_parser.cc20
-rw-r--r--arg_parser.h20
-rwxr-xr-xconfigure20
-rw-r--r--doc/zcat.167
-rw-r--r--doc/zcmp.167
-rw-r--r--doc/zdiff.1100
-rw-r--r--doc/zgrep.1120
-rw-r--r--doc/ztest.119
-rw-r--r--doc/zutils.infobin7255 -> 13902 bytes
-rw-r--r--doc/zutils.texinfo480
-rw-r--r--main.cc996
-rwxr-xr-xtestsuite/check.sh195
-rw-r--r--testsuite/test.txt676
-rw-r--r--zcat.cc213
-rw-r--r--zcat.in116
-rw-r--r--zcmp.cc502
-rw-r--r--zcmp.in3
-rw-r--r--zdiff.cc476
-rw-r--r--zdiff.in160
-rw-r--r--zegrep.in2
-rw-r--r--zfgrep.in2
-rw-r--r--zgrep.cc159
-rw-r--r--zgrep.in137
-rw-r--r--ztest.cc119
-rw-r--r--ztest.in103
-rw-r--r--zutils.cc301
-rw-r--r--zutils.h53
32 files changed, 3796 insertions, 1549 deletions
diff --git a/ChangeLog b/ChangeLog
index 85f7717..54282fe 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,6 +1,19 @@
-2009-12-01 Antonio Diaz Diaz <ant_diaz@teleline.es>
-
- * Version 0.8-rc1 released.
+2010-11-15 Antonio Diaz Diaz <ant_diaz@teleline.es>
+
+ * Version 0.8 released.
+ * main.cc: Added new options "--zcat", "--zgrep" and "--ztest".
+ * zcat.cc: New file implementing zcat+cat functionality in C++.
+ * zcmp.cc: New file implementing zcmp+cmp functionality in C++.
+ * doc/zcmp.1: New file.
+ * zcmp.in: Removed.
+ * zdiff.cc: New file implementing zdiff functionality in C++.
+ * zdiff.in: Removed.
+ * zgrep.cc: New file implementing zgrep functionality in C++.
+ * All mentions to zegrep and zfgrep have been removed from the
+ documentation because egrep and fgrep are deprecated.
+ * ztest.cc: New file implementing ztest functionality in C++.
+ * Makefile.in: Added quotes to directory names.
+ * testsuite/check.sh: Use "test.txt" instead of "COPYING" for testing.
* Removed environment safeguards from configure as requested by
Richard Stallman. Now environment variables affect configure.
@@ -46,8 +59,8 @@
* Version 0.1 released.
-Copyright (C) 2009 Antonio Diaz Diaz.
+Copyright (C) 2009, 2010 Antonio Diaz Diaz.
This file is a collection of facts, and thus it is not copyrightable,
-but just in case, I give you unlimited permission to copy, distribute
-and modify it.
+but just in case, you have unlimited permission to copy, distribute and
+modify it.
diff --git a/INSTALL b/INSTALL
index 1dadb5e..9c7b683 100644
--- a/INSTALL
+++ b/INSTALL
@@ -55,7 +55,7 @@ After running `configure', you can run `make' and `make install' as
explained above.
-Copyright (C) 2009 Antonio Diaz Diaz.
+Copyright (C) 2009, 2010 Antonio Diaz Diaz.
This file is free documentation: you have unlimited permission to copy,
distribute and modify it.
diff --git a/Makefile.in b/Makefile.in
index edaf42f..4a04228 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -1,5 +1,5 @@
-DISTNAME = $(progname)-$(progversion)
+DISTNAME = $(pkgname)-$(pkgversion)
INSTALL = install
INSTALL_PROGRAM = $(INSTALL) -p -m 755
INSTALL_SCRIPT = $(INSTALL) -p -m 755
@@ -7,33 +7,33 @@ INSTALL_DATA = $(INSTALL) -p -m 644
INSTALL_DIR = $(INSTALL) -d -m 755
SHELL = /bin/sh
-objs = arg_parser.o main.o
-scripts = zcat zcmp zdiff zegrep zfgrep zgrep ztest
+objs = arg_parser.o zutils.o main.o
+zcmp_objs = arg_parser.o zutils.o zcmp.o
+zdiff_objs = arg_parser.o zutils.o zdiff.o
+scripts = zcat zegrep zfgrep zgrep ztest
.PHONY : all install install-info install-man install-strip \
uninstall uninstall-info uninstall-man \
doc info man check dist clean distclean
-all : $(progname) $(scripts)
+all : $(progname) zcmp zdiff $(scripts)
$(progname) : $(objs)
- $(CXX) $(LDFLAGS) -o $(progname) $(objs)
+ $(CXX) $(LDFLAGS) -o $@ $(objs)
$(progname)_profiled : $(objs)
- $(CXX) $(LDFLAGS) -pg -o $(progname)_profiled $(objs)
+ $(CXX) $(LDFLAGS) -pg -o $@ $(objs)
zcat : zcat.in
- sed -e 's,VERSION,$(progversion),g' $(VPATH)/zcat.in > zcat
+ cat $(VPATH)/zcat.in > zcat
chmod a+x zcat
-zcmp : zcmp.in
- cat $(VPATH)/zcmp.in > zcmp
- chmod a+x zcmp
+zcmp : $(zcmp_objs)
+ $(CXX) $(LDFLAGS) -o $@ $(zcmp_objs)
-zdiff : zdiff.in
- sed -e 's,VERSION,$(progversion),g' $(VPATH)/zdiff.in > zdiff
- chmod a+x zdiff
+zdiff : $(zdiff_objs)
+ $(CXX) $(LDFLAGS) -o $@ $(zdiff_objs)
zegrep : zegrep.in
cat $(VPATH)/zegrep.in > zegrep
@@ -44,15 +44,15 @@ zfgrep : zfgrep.in
chmod a+x zfgrep
zgrep : zgrep.in
- sed -e 's,VERSION,$(progversion),g' $(VPATH)/zgrep.in > zgrep
+ cat $(VPATH)/zgrep.in > zgrep
chmod a+x zgrep
ztest : ztest.in
- sed -e 's,VERSION,$(progversion),g' $(VPATH)/ztest.in > ztest
+ cat $(VPATH)/ztest.in > ztest
chmod a+x ztest
-main.o : main.cc
- $(CXX) $(CPPFLAGS) $(CXXFLAGS) -DPROGVERSION=\"$(progversion)\" -c -o $@ $<
+zutils.o : zutils.cc
+ $(CXX) $(CPPFLAGS) $(CXXFLAGS) -DPROGVERSION=\"$(pkgversion)\" -c -o $@ $<
%.o : %.cc
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<
@@ -60,96 +60,100 @@ main.o : main.cc
$(objs) : Makefile
$(scripts) : Makefile
arg_parser.o : arg_parser.h
-main.o : arg_parser.h
+main.o : arg_parser.h zutils.h zcat.cc zgrep.cc ztest.cc
+zcmp.o : arg_parser.h zutils.h Makefile
+zdiff.o : arg_parser.h zutils.h Makefile
+zutils.o : zutils.h
doc : info man
-info : $(VPATH)/doc/$(progname).info
+info : $(VPATH)/doc/$(pkgname).info
-$(VPATH)/doc/$(progname).info : $(VPATH)/doc/$(progname).texinfo
- cd $(VPATH)/doc && makeinfo $(progname).texinfo
+$(VPATH)/doc/$(pkgname).info : $(VPATH)/doc/$(pkgname).texinfo
+ cd $(VPATH)/doc && makeinfo $(pkgname).texinfo
-man : $(VPATH)/doc/zcat.1 $(VPATH)/doc/zdiff.1 \
+man : $(VPATH)/doc/zcat.1 $(VPATH)/doc/zcmp.1 $(VPATH)/doc/zdiff.1 \
$(VPATH)/doc/zgrep.1 $(VPATH)/doc/ztest.1
-$(VPATH)/doc/zcat.1 : zcat
- help2man -n 'concatenate compressed files to stdout' \
- -o $(VPATH)/doc/zcat.1 --no-info ./zcat
+$(VPATH)/doc/zcat.1 : $(progname) zcat
+ help2man -n 'decompress and concatenate files to standard output' \
+ -o $@ --no-info ./zcat
+
+$(VPATH)/doc/zcmp.1 : zcmp
+ help2man -n 'decompress and compare two files byte by byte' \
+ -o $@ --no-info ./zcmp
$(VPATH)/doc/zdiff.1 : zdiff
- help2man -n 'compare compressed files' \
- -o $(VPATH)/doc/zdiff.1 --no-info ./zdiff
+ help2man -n 'decompress and compare two files line by line' \
+ -o $@ --no-info ./zdiff
-$(VPATH)/doc/zgrep.1 : zgrep
+$(VPATH)/doc/zgrep.1 : $(progname) zgrep
help2man -n 'search compressed files for a regular expression' \
- -o $(VPATH)/doc/zgrep.1 --no-info ./zgrep
+ -o $@ --no-info ./zgrep
-$(VPATH)/doc/ztest.1 : ztest
+$(VPATH)/doc/ztest.1 : $(progname) ztest
help2man -n 'verify integrity of compressed files' \
- -o $(VPATH)/doc/ztest.1 --no-info ./ztest
+ -o $@ --no-info ./ztest
Makefile : $(VPATH)/configure $(VPATH)/Makefile.in
./config.status
-check : all $(VPATH)/testsuite/check.sh
- @$(VPATH)/testsuite/check.sh $(VPATH)/testsuite
+check : all
+ @$(VPATH)/testsuite/check.sh $(VPATH)/testsuite $(pkgversion)
install : all install-info install-man
- if [ ! -d $(DESTDIR)$(bindir) ] ; then $(INSTALL_DIR) $(DESTDIR)$(bindir) ; fi
- $(INSTALL_PROGRAM) ./$(progname) $(DESTDIR)$(bindir)/$(progname)
- $(INSTALL_SCRIPT) zcat $(DESTDIR)$(bindir)/zcat
- $(INSTALL_SCRIPT) zcmp $(DESTDIR)$(bindir)/zcmp
- $(INSTALL_SCRIPT) zdiff $(DESTDIR)$(bindir)/zdiff
- $(INSTALL_SCRIPT) zegrep $(DESTDIR)$(bindir)/zegrep
- $(INSTALL_SCRIPT) zfgrep $(DESTDIR)$(bindir)/zfgrep
- $(INSTALL_SCRIPT) zgrep $(DESTDIR)$(bindir)/zgrep
- $(INSTALL_SCRIPT) ztest $(DESTDIR)$(bindir)/ztest
+ if [ ! -d "$(DESTDIR)$(bindir)" ] ; then $(INSTALL_DIR) "$(DESTDIR)$(bindir)" ; fi
+ $(INSTALL_PROGRAM) ./$(progname) "$(DESTDIR)$(bindir)/$(progname)"
+ $(INSTALL_SCRIPT) ./zcat "$(DESTDIR)$(bindir)/zcat"
+ $(INSTALL_PROGRAM) ./zcmp "$(DESTDIR)$(bindir)/zcmp"
+ $(INSTALL_PROGRAM) ./zdiff "$(DESTDIR)$(bindir)/zdiff"
+ $(INSTALL_SCRIPT) ./zegrep "$(DESTDIR)$(bindir)/zegrep"
+ $(INSTALL_SCRIPT) ./zfgrep "$(DESTDIR)$(bindir)/zfgrep"
+ $(INSTALL_SCRIPT) ./zgrep "$(DESTDIR)$(bindir)/zgrep"
+ $(INSTALL_SCRIPT) ./ztest "$(DESTDIR)$(bindir)/ztest"
install-info :
- if [ ! -d $(DESTDIR)$(infodir) ] ; then $(INSTALL_DIR) $(DESTDIR)$(infodir) ; fi
- $(INSTALL_DATA) $(VPATH)/doc/$(progname).info $(DESTDIR)$(infodir)/$(progname).info
- -install-info --info-dir=$(DESTDIR)$(infodir) $(DESTDIR)$(infodir)/$(progname).info
+ if [ ! -d "$(DESTDIR)$(infodir)" ] ; then $(INSTALL_DIR) "$(DESTDIR)$(infodir)" ; fi
+ $(INSTALL_DATA) $(VPATH)/doc/$(pkgname).info "$(DESTDIR)$(infodir)/$(pkgname).info"
+ -install-info --info-dir="$(DESTDIR)$(infodir)" $(DESTDIR)$(infodir)/$(pkgname).info
install-man :
- if [ ! -d $(DESTDIR)$(mandir)/man1 ] ; then $(INSTALL_DIR) $(DESTDIR)$(mandir)/man1 ; fi
- $(INSTALL_DATA) $(VPATH)/doc/zcat.1 $(DESTDIR)$(mandir)/man1/zcat.1
- -rm -f $(DESTDIR)$(mandir)/man1/zcmp.1
- cd $(DESTDIR)$(mandir)/man1 && ln -s zdiff.1 zcmp.1
- $(INSTALL_DATA) $(VPATH)/doc/zdiff.1 $(DESTDIR)$(mandir)/man1/zdiff.1
- $(INSTALL_DATA) $(VPATH)/doc/zgrep.1 $(DESTDIR)$(mandir)/man1/zgrep.1
- -rm -f $(DESTDIR)$(mandir)/man1/zegrep.1
- -rm -f $(DESTDIR)$(mandir)/man1/zfgrep.1
- cd $(DESTDIR)$(mandir)/man1 && ln -s zgrep.1 zegrep.1
- cd $(DESTDIR)$(mandir)/man1 && ln -s zgrep.1 zfgrep.1
- $(INSTALL_DATA) $(VPATH)/doc/ztest.1 $(DESTDIR)$(mandir)/man1/ztest.1
+ if [ ! -d "$(DESTDIR)$(mandir)/man1" ] ; then $(INSTALL_DIR) "$(DESTDIR)$(mandir)/man1" ; fi
+ $(INSTALL_DATA) $(VPATH)/doc/zcat.1 "$(DESTDIR)$(mandir)/man1/zcat.1"
+ $(INSTALL_DATA) $(VPATH)/doc/zcmp.1 "$(DESTDIR)$(mandir)/man1/zcmp.1"
+ $(INSTALL_DATA) $(VPATH)/doc/zdiff.1 "$(DESTDIR)$(mandir)/man1/zdiff.1"
+ $(INSTALL_DATA) $(VPATH)/doc/zgrep.1 "$(DESTDIR)$(mandir)/man1/zgrep.1"
+ -rm -f "$(DESTDIR)$(mandir)/man1/zegrep.1"
+ -rm -f "$(DESTDIR)$(mandir)/man1/zfgrep.1"
+ $(INSTALL_DATA) $(VPATH)/doc/ztest.1 "$(DESTDIR)$(mandir)/man1/ztest.1"
install-strip : all
$(MAKE) INSTALL_PROGRAM='$(INSTALL_PROGRAM) -s' install
uninstall : uninstall-info uninstall-man
- -rm -f $(DESTDIR)$(bindir)/$(progname)
- -rm -f $(DESTDIR)$(bindir)/zcat
- -rm -f $(DESTDIR)$(bindir)/zcmp
- -rm -f $(DESTDIR)$(bindir)/zdiff
- -rm -f $(DESTDIR)$(bindir)/zegrep
- -rm -f $(DESTDIR)$(bindir)/zfgrep
- -rm -f $(DESTDIR)$(bindir)/zgrep
- -rm -f $(DESTDIR)$(bindir)/ztest
+ -rm -f "$(DESTDIR)$(bindir)/$(progname)"
+ -rm -f "$(DESTDIR)$(bindir)/zcat"
+ -rm -f "$(DESTDIR)$(bindir)/zcmp"
+ -rm -f "$(DESTDIR)$(bindir)/zdiff"
+ -rm -f "$(DESTDIR)$(bindir)/zegrep"
+ -rm -f "$(DESTDIR)$(bindir)/zfgrep"
+ -rm -f "$(DESTDIR)$(bindir)/zgrep"
+ -rm -f "$(DESTDIR)$(bindir)/ztest"
uninstall-info :
- -install-info --info-dir=$(DESTDIR)$(infodir) --remove $(DESTDIR)$(infodir)/$(progname).info
- -rm -f $(DESTDIR)$(infodir)/$(progname).info
+ -install-info --info-dir="$(DESTDIR)$(infodir)" --remove "$(DESTDIR)$(infodir)/$(pkgname).info"
+ -rm -f "$(DESTDIR)$(infodir)/$(pkgname).info"
uninstall-man :
- -rm -f $(DESTDIR)$(mandir)/man1/zcat.1
- -rm -f $(DESTDIR)$(mandir)/man1/zcmp.1
- -rm -f $(DESTDIR)$(mandir)/man1/zdiff.1
- -rm -f $(DESTDIR)$(mandir)/man1/zegrep.1
- -rm -f $(DESTDIR)$(mandir)/man1/zfgrep.1
- -rm -f $(DESTDIR)$(mandir)/man1/zgrep.1
- -rm -f $(DESTDIR)$(mandir)/man1/ztest.1
-
-dist :
+ -rm -f "$(DESTDIR)$(mandir)/man1/zcat.1"
+ -rm -f "$(DESTDIR)$(mandir)/man1/zcmp.1"
+ -rm -f "$(DESTDIR)$(mandir)/man1/zdiff.1"
+ -rm -f "$(DESTDIR)$(mandir)/man1/zegrep.1"
+ -rm -f "$(DESTDIR)$(mandir)/man1/zfgrep.1"
+ -rm -f "$(DESTDIR)$(mandir)/man1/zgrep.1"
+ -rm -f "$(DESTDIR)$(mandir)/man1/ztest.1"
+
+dist : doc
ln -sf $(VPATH) $(DISTNAME)
tar -cvf $(DISTNAME).tar \
$(DISTNAME)/AUTHORS \
@@ -161,9 +165,10 @@ dist :
$(DISTNAME)/README \
$(DISTNAME)/configure \
$(DISTNAME)/doc/*.1 \
- $(DISTNAME)/doc/$(progname).info \
- $(DISTNAME)/doc/$(progname).texinfo \
+ $(DISTNAME)/doc/$(pkgname).info \
+ $(DISTNAME)/doc/$(pkgname).texinfo \
$(DISTNAME)/testsuite/check.sh \
+ $(DISTNAME)/testsuite/test.txt \
$(DISTNAME)/*.h \
$(DISTNAME)/*.cc \
$(DISTNAME)/z*.in
@@ -172,7 +177,7 @@ dist :
clean :
-rm -f $(progname) $(progname)_profiled $(objs)
- -rm -f $(scripts)
+ -rm -f zcmp zcmp.o zdiff zdiff.o $(scripts)
distclean : clean
-rm -f Makefile config.status *.tar *.tar.lz
diff --git a/NEWS b/NEWS
index 66001d3..cf6500b 100644
--- a/NEWS
+++ b/NEWS
@@ -1,4 +1,15 @@
Changes in version 0.8:
+The option "--recursive" has been added to zgrep.
+
+All the utilities have been rewritten in C++, making them safer and more
+efficient.
+
+Zcat and zcmp implement the functionality of cat and cmp respectively.
+Cat and cmp are not needed at runtime.
+
+All mentions to zegrep and zfgrep have been removed from the
+documentation because egrep and fgrep are deprecated.
+
Environment safeguards from configure have been removed. This allows
environment variables to affect configuration.
diff --git a/README b/README
index 2550b69..a94268b 100644
--- a/README
+++ b/README
@@ -1,18 +1,22 @@
Description
-Zutils is a collection of utilities for dealing with any combination of
-compressed and non-compressed files transparently. The supported
-compressors are bzip2, gzip, lzip and xz.
+Zutils is a collection of utilities able to deal with any combination of
+compressed and non-compressed files transparently. If any given file,
+including standard input, is compressed, its uncompressed content is
+used. Compressed files are decompressed on the fly; no temporary files
+are created. These utilities are not wrapper scripts but safer and more
+efficient C++ programs. In particular the "--recursive" option is very
+efficient in those utilities supporting it.
-The currently provided utilities are zcat, zcmp, zdiff, zegrep, zfgrep,
-zgrep and ztest.
+The provided utilities are zcat, zcmp, zdiff, zgrep and ztest.
+The supported compressors are bzip2, gzip, lzip and xz.
-Copyright (C) 2009 Antonio Diaz Diaz.
+Copyright (C) 2009, 2010 Antonio Diaz Diaz.
This file is free documentation: you have unlimited permission to copy,
distribute and modify it.
The file Makefile.in is a data file used by configure to produce the
-Makefile. It has the same copyright owner and permissions that this
-file.
+Makefile. It has the same copyright owner and permissions that configure
+itself.
diff --git a/arg_parser.cc b/arg_parser.cc
index b889e1a..cc9f87d 100644
--- a/arg_parser.cc
+++ b/arg_parser.cc
@@ -1,18 +1,28 @@
-/* Arg_parser - A POSIX/GNU command line argument parser.
- Copyright (C) 2006, 2007, 2008, 2009 Antonio Diaz Diaz.
+/* Arg_parser - A POSIX/GNU command line argument parser. (C++ version)
+ Copyright (C) 2006, 2007, 2008, 2009, 2010 Antonio Diaz Diaz.
- This program is free software: you can redistribute it and/or modify
+ This library is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
- This program is distributed in the hope that it will be useful,
+ This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
+ along with this library. If not, see <http://www.gnu.org/licenses/>.
+
+ As a special exception, you may use this file as part of a free
+ software library without restriction. Specifically, if other files
+ instantiate templates or use macros or inline functions from this
+ file, or you compile this file and link it with other files to
+ produce an executable, this file does not by itself cause the
+ resulting executable to be covered by the GNU General Public
+ License. This exception does not however invalidate any other
+ reasons why the executable file might be covered by the GNU General
+ Public License.
*/
#include <cstring>
diff --git a/arg_parser.h b/arg_parser.h
index fa6161b..da1cc94 100644
--- a/arg_parser.h
+++ b/arg_parser.h
@@ -1,18 +1,28 @@
-/* Arg_parser - A POSIX/GNU command line argument parser.
- Copyright (C) 2006, 2007, 2008, 2009 Antonio Diaz Diaz.
+/* Arg_parser - A POSIX/GNU command line argument parser. (C++ version)
+ Copyright (C) 2006, 2007, 2008, 2009, 2010 Antonio Diaz Diaz.
- This program is free software: you can redistribute it and/or modify
+ This library is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
- This program is distributed in the hope that it will be useful,
+ This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
+ along with this library. If not, see <http://www.gnu.org/licenses/>.
+
+ As a special exception, you may use this file as part of a free
+ software library without restriction. Specifically, if other files
+ instantiate templates or use macros or inline functions from this
+ file, or you compile this file and link it with other files to
+ produce an executable, this file does not by itself cause the
+ resulting executable to be covered by the GNU General Public
+ License. This exception does not however invalidate any other
+ reasons why the executable file might be covered by the GNU General
+ Public License.
*/
/* Arg_parser reads the arguments in `argv' and creates a number of
diff --git a/configure b/configure
index c94a506..2a45a9a 100755
--- a/configure
+++ b/configure
@@ -1,17 +1,18 @@
#! /bin/sh
# configure script for Zutils - Utilities dealing with compressed files
-# Copyright (C) 2009 Antonio Diaz Diaz.
+# Copyright (C) 2009, 2010 Antonio Diaz Diaz.
#
# This configure script is free software: you have unlimited permission
# to copy, distribute and modify it.
#
-# Date of this version: 2009-12-01
+# Date of this version: 2010-11-15
args=
no_create=
+pkgname=zutils
+pkgversion=0.8
progname=zutils
-progversion=0.8-rc1
-srctrigger=zdiff.in
+srctrigger=zutils.h
# clear some things potentially inherited from environment.
LC_ALL=C
@@ -69,7 +70,7 @@ while [ -n "$1" ] ; do
echo
exit 0 ;;
--version | --ve* | -V)
- echo "Configure script for ${progname} version ${progversion}"
+ echo "Configure script for ${pkgname} version ${pkgversion}"
exit 0 ;;
--srcdir* | --sr*)
srcdir=`echo ${optarg} | sed -e 's,/$,,'` ;;
@@ -81,7 +82,7 @@ while [ -n "$1" ] ; do
bindir=`echo ${optarg} | sed -e 's,/$,,'` ;;
--datadir* | --da*)
datadir=`echo ${optarg} | sed -e 's,/$,,'` ;;
- --infodir* | --in*)
+ --infodir* | --inf*)
infodir=`echo ${optarg} | sed -e 's,/$,,'` ;;
--mandir* | --ma*)
mandir=`echo ${optarg} | sed -e 's,/$,,'` ;;
@@ -136,7 +137,7 @@ if [ -z "${CXX}" ] ; then # Let the user override the test.
fi
echo
-if [ x${no_create} = x ] ; then
+if [ -z "${no_create}" ] ; then
echo "creating config.status"
rm -f config.status
cat > config.status << EOF
@@ -168,14 +169,15 @@ echo "LDFLAGS = ${LDFLAGS}"
rm -f Makefile
cat > Makefile << EOF
# Makefile for Zutils - Utilities dealing with compressed files
-# Copyright (C) 2009 Antonio Diaz Diaz.
+# Copyright (C) 2009, 2010 Antonio Diaz Diaz.
# This file was generated automatically by configure. Do not edit.
#
# This Makefile is free software: you have unlimited permission
# to copy, distribute and modify it.
+pkgname = ${pkgname}
+pkgversion = ${pkgversion}
progname = ${progname}
-progversion = ${progversion}
VPATH = ${srcdir}
prefix = ${prefix}
exec_prefix = ${exec_prefix}
diff --git a/doc/zcat.1 b/doc/zcat.1
index 407e270..244aaad 100644
--- a/doc/zcat.1
+++ b/doc/zcat.1
@@ -1,25 +1,22 @@
-.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.36.
-.TH ZCAT "1" "December 2009" "Zcat (zutils) 0.8-rc1" "User Commands"
+.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.37.1.
+.TH ZCAT "1" "November 2010" "Zcat (zutils) 0.8" "User Commands"
.SH NAME
-Zcat \- concatenate compressed files to stdout
+Zcat \- decompress and concatenate files to standard output
.SH SYNOPSIS
.B zcat
-[\fIOPTIONS\fR] [\fICAT_OPTIONS\fR] [\fIFILES\fR]
+[\fIoptions\fR] [\fIfiles\fR]
.SH DESCRIPTION
-Zcat \- Cat wrapper for compressed files.
-.PP
-Zcat is a wrapper script around the cat command that allows transparent
-concatenation of any combination of compressed and non\-compressed files.
-If any given file is compressed, its uncompressed content is used. If a
-given file does not exist, zcat tries the compressed file names
+Zcat copies each given file ("\-" means standard input), to standard
+output. If any given file is compressed, its uncompressed content is
+used. If a given file does not exist, and its name does not end with one
+of the known extensions, zcat tries the compressed file names
corresponding to the supported compressors. If no files are specified,
data is read from standard input, decompressed if needed, and sent to
-stdout. Data read from standard input must be of the same type; all
-uncompressed or all compressed with the same compressor.
+standard output. Data read from standard input must be of the same type;
+all uncompressed or all compressed with the same compressor.
The supported compressors are bzip2, gzip, lzip and xz.
.PP
-CAT_OPTIONS are passed directly to cat.
-The exit status from cat is preserved.
+Exit status is 0 if no errors occurred, 1 otherwise.
.SH OPTIONS
.TP
\fB\-h\fR, \fB\-\-help\fR
@@ -28,12 +25,48 @@ display this help and exit
\fB\-V\fR, \fB\-\-version\fR
output version information and exit
.TP
+\fB\-A\fR, \fB\-\-show\-all\fR
+equivalent to `\-vET'
+.TP
+\fB\-b\fR, \fB\-\-number\-nonblank\fR
+number nonblank output lines
+.TP
+\fB\-e\fR
+equivalent to `\-vE'
+.TP
+\fB\-E\fR, \fB\-\-show\-ends\fR
+display `$' at end of each line
+.TP
+\fB\-n\fR, \fB\-\-number\fR
+number all output lines
+.TP
+\fB\-q\fR, \fB\-\-quiet\fR
+suppress all messages
+.TP
\fB\-r\fR, \fB\-\-recursive\fR
operate recursively on directories
+.TP
+\fB\-s\fR, \fB\-\-squeeze\-blank\fR
+never more than one single blank line
+.TP
+\fB\-t\fR
+equivalent to `\-vT'
+.TP
+\fB\-T\fR, \fB\-\-show\-tabs\fR
+display TAB characters as `^I'
+.TP
+\fB\-v\fR, \fB\-\-show\-nonprinting\fR
+use `^' and `M\-' notation, except for LF and TAB
+.TP
+\fB\-\-verbose\fR
+verbose mode (show error messages)
.SH "REPORTING BUGS"
Report bugs to zutils\-bug@nongnu.org
+.br
Zutils home page: http://www.nongnu.org/zutils/zutils.html
.SH COPYRIGHT
-Copyright \(co 2009 Antonio Diaz Diaz.
-This script is free software: you have unlimited permission
-to copy, distribute and modify it.
+Copyright \(co 2010 Antonio Diaz Diaz.
+License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
+.br
+This is free software: you are free to change and redistribute it.
+There is NO WARRANTY, to the extent permitted by law.
diff --git a/doc/zcmp.1 b/doc/zcmp.1
new file mode 100644
index 0000000..ab3da39
--- /dev/null
+++ b/doc/zcmp.1
@@ -0,0 +1,67 @@
+.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.37.1.
+.TH ZCMP "1" "November 2010" "Zcmp (zutils) 0.8" "User Commands"
+.SH NAME
+Zcmp \- decompress and compare two files byte by byte
+.SH SYNOPSIS
+.B zcmp
+[\fIoptions\fR] \fIfile1 \fR[\fIfile2\fR]
+.SH DESCRIPTION
+Zcmp compares two files ("\-" means standard input), and if they
+differ, tells the first byte and line number where they differ. Bytes
+and lines are numbered starting with 1. If any given file is compressed,
+its uncompressed content is used. Compressed files are uncompressed on
+the fly; no temporary files are created.
+The supported compressors are bzip2, gzip, lzip and xz.
+.PP
+Compares <file1> to <file2>. If <file2> is omitted zcmp tries the
+following:
+If <file1> is compressed, compares <file1> to the file with the
+corresponding decompressed file name (removes the extension from
+<file1>).
+If <file1> is not compressed, compares <file1> to the uncompressed
+contents of <file1>.[bz2|gz|lz|xz] (the first one that is found).
+If no suitable file is found, compares <file1> to data read from
+standard input.
+.PP
+Exit status is 0 if inputs are identical, 1 if different, 2 if trouble.
+.SH OPTIONS
+.TP
+\fB\-h\fR, \fB\-\-help\fR
+display this help and exit
+.TP
+\fB\-V\fR, \fB\-\-version\fR
+output version information and exit
+.TP
+\fB\-b\fR, \fB\-\-print\-bytes\fR
+print differing bytes
+.TP
+\fB\-i\fR, \fB\-\-ignore\-initial=\fR<n>[,<n2>]
+ignore differences in the first <n> bytes
+.TP
+\fB\-l\fR, \fB\-\-list\fR
+list position, value of all differing bytes
+.TP
+\fB\-n\fR, \fB\-\-bytes=\fR<n>
+compare at most <n> bytes
+.TP
+\fB\-q\fR, \fB\-\-quiet\fR
+suppress all messages
+.TP
+\fB\-s\fR, \fB\-\-silent\fR
+(same as \fB\-\-quiet\fR)
+.TP
+\fB\-v\fR, \fB\-\-verbose\fR
+verbose mode (same as \fB\-\-list\fR)
+.PP
+Numbers may be followed by a multiplier: k = kB = 10^3 = 1000,
+Ki = KiB = 2^10 = 1024, M = 10^6, Mi = 2^20, G = 10^9, Gi = 2^30, etc...
+.SH "REPORTING BUGS"
+Report bugs to zutils\-bug@nongnu.org
+.br
+Zutils home page: http://www.nongnu.org/zutils/zutils.html
+.SH COPYRIGHT
+Copyright \(co 2010 Antonio Diaz Diaz.
+License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
+.br
+This is free software: you are free to change and redistribute it.
+There is NO WARRANTY, to the extent permitted by law.
diff --git a/doc/zdiff.1 b/doc/zdiff.1
index dc7abdb..f6417c2 100644
--- a/doc/zdiff.1
+++ b/doc/zdiff.1
@@ -1,27 +1,29 @@
-.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.36.
-.TH ZDIFF "1" "December 2009" "Zdiff (zutils) 0.8-rc1" "User Commands"
+.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.37.1.
+.TH ZDIFF "1" "November 2010" "Zdiff (zutils) 0.8" "User Commands"
.SH NAME
-Zdiff \- compare compressed files
+Zdiff \- decompress and compare two files line by line
.SH SYNOPSIS
.B zdiff
-[\fIOPTIONS\fR] [\fIDIFF_OPTIONS\fR] \fIFILE1 \fR[\fIFILE2\fR]
+[\fIoptions\fR] \fIfile1 \fR[\fIfile2\fR]
.SH DESCRIPTION
-Zdiff \- Diff/cmp wrapper for compressed files.
+Zdiff compares two files ("\-" means standard input), and if they
+differ, shows the differences line by line. If any given file is
+compressed, its uncompressed content is used. Zdiff is a front end to
+the diff program and has the limitation that messages from diff refer to
+temporary filenames instead of those specified.
+The supported compressors are bzip2, gzip, lzip and xz.
.PP
-Zdiff is a wrapper script around the diff and cmp commands that allows
-transparent comparison of any combination of compressed and
-non\-compressed files. If any given file is compressed, its uncompressed
-content is used. The supported compressors are bzip2, gzip, lzip and xz.
+Compares <file1> to <file2>. If <file2> is omitted zdiff tries the
+following:
+If <file1> is compressed, compares <file1> to the file with the
+corresponding decompressed file name (removes the extension from
+<file1>).
+If <file1> is not compressed, compares <file1> to the uncompressed
+contents of <file1>.[bz2|gz|lz|xz] (the first one that is found).
+If no suitable file is found, compares <file1> to data read from
+standard input.
.PP
-Zcmp is a shortcut for "zdiff \fB\-\-cmp\fR"
-.PP
-Compares FILE1 to FILE2. If FILE2 is omitted and FILE1 is compressed,
-compares FILE1 to the file with the corresponding decompressed file
-name (removes the extension from FILE1). If FILE2 is omitted and FILE1
-is not compressed, compares FILE1 to the uncompressed contents of
-FILE1.[bz2|gz|lz|xz] (the first one that is found).
-DIFF_OPTIONS are passed directly to diff or cmp.
-The exit status from diff or cmp is preserved.
+Exit status is 0 if inputs are identical, 1 if different, 2 if trouble.
.SH OPTIONS
.TP
\fB\-h\fR, \fB\-\-help\fR
@@ -30,15 +32,63 @@ display this help and exit
\fB\-V\fR, \fB\-\-version\fR
output version information and exit
.TP
-\fB\-\-diff\fR
-use diff to compare files (default)
+\fB\-a\fR, \fB\-\-text\fR
+treat all files as text
+.TP
+\fB\-b\fR, \fB\-\-ignore\-space\-change\fR
+ignore changes in the amount of white space
+.TP
+\fB\-B\fR, \fB\-\-ignore\-blank\-lines\fR
+ignore changes whose lines are all blank
+.TP
+\fB\-c\fR
+use the context output format
+.TP
+\fB\-C\fR, \fB\-\-context=\fR<n>
+same as \fB\-c\fR but use <n> lines of context
+.TP
+\fB\-d\fR, \fB\-\-minimal\fR
+try hard to find a smaller set of changes
+.TP
+\fB\-E\fR, \fB\-\-ignore\-tab\-expansion\fR
+ignore changes due to tab expansion
+.TP
+\fB\-i\fR, \fB\-\-ignore\-case\fR
+ignore case differences in file contents
.TP
-\fB\-\-cmp\fR
-use cmp to compare files
+\fB\-p\fR, \fB\-\-show\-c\-function\fR
+show which C function each change is in
+.TP
+\fB\-q\fR, \fB\-\-brief\fR
+output only whether files differ
+.TP
+\fB\-s\fR, \fB\-\-report\-identical\-files\fR
+report when two files are identical
+.TP
+\fB\-t\fR, \fB\-\-expand\-tabs\fR
+expand tabs to spaces in output
+.TP
+\fB\-T\fR, \fB\-\-initial\-tab\fR
+make tabs line up by prepending a tab
+.TP
+\fB\-u\fR
+use the unified output format
+.TP
+\fB\-U\fR, \fB\-\-unified=\fR<n>
+same as \fB\-u\fR but use <n> lines of context
+.TP
+\fB\-w\fR, \fB\-\-ignore\-all\-space\fR
+ignore all white space
+.PP
+Numbers may be followed by a multiplier: k = kB = 10^3 = 1000,
+Ki = KiB = 2^10 = 1024, M = 10^6, Mi = 2^20, G = 10^9, Gi = 2^30, etc...
.SH "REPORTING BUGS"
Report bugs to zutils\-bug@nongnu.org
+.br
Zutils home page: http://www.nongnu.org/zutils/zutils.html
.SH COPYRIGHT
-Copyright \(co 2009 Antonio Diaz Diaz.
-This script is free software: you have unlimited permission
-to copy, distribute and modify it.
+Copyright \(co 2010 Antonio Diaz Diaz.
+License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
+.br
+This is free software: you are free to change and redistribute it.
+There is NO WARRANTY, to the extent permitted by law.
diff --git a/doc/zgrep.1 b/doc/zgrep.1
index fee5e3d..aab13b2 100644
--- a/doc/zgrep.1
+++ b/doc/zgrep.1
@@ -1,39 +1,115 @@
-.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.36.
-.TH ZGREP "1" "December 2009" "Zgrep (zutils) 0.8-rc1" "User Commands"
+.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.37.1.
+.TH ZGREP "1" "November 2010" "Zgrep (zutils) 0.8" "User Commands"
.SH NAME
Zgrep \- search compressed files for a regular expression
.SH SYNOPSIS
.B zgrep
-[\fIOPTIONS\fR] [\fIGREP_OPTIONS\fR] \fIPATTERN \fR[\fIFILES\fR]
+[\fIoptions\fR] \fI<pattern> \fR[\fIfiles\fR]
.SH DESCRIPTION
-Zgrep \- Grep wrapper for compressed files.
-.PP
-Zgrep is a wrapper script around the grep command that allows
-transparent search on any combination of compressed and non\-compressed
-files. If any given file is compressed, its uncompressed content is
-used. If a given file does not exist, zgrep tries the compressed file
-names corresponding to the supported compressors. If no files are
-specified, data is read from standard input, decompressed if needed, and
-fed to grep. Data read from standard input must be of the same type; all
-uncompressed or all compressed with the same compressor.
+Zgrep is a front end to the grep program that allows transparent search
+on any combination of compressed and non\-compressed files. If any given
+file is compressed, its uncompressed content is used. If a given file
+does not exist, and its name does not end with one of the known
+extensions, zgrep tries the compressed file names corresponding to the
+supported compressors. If no files are specified, data is read from
+standard input, decompressed if needed, and fed to grep. Data read from
+standard input must be of the same type; all uncompressed or all
+compressed with the same compressor.
The supported compressors are bzip2, gzip, lzip and xz.
.PP
-Zegrep is a shortcut for "zgrep \fB\-E\fR"
-Zfgrep is a shortcut for "zgrep \fB\-F\fR"
-.PP
-GREP_OPTIONS are passed directly to grep.
-The exit status from grep is preserved.
+Exit status is 0 if match, 1 if no match, 2 if trouble.
.SH OPTIONS
.TP
-\fB\-h\fR, \fB\-\-help\fR
+\fB\-\-help\fR
display this help and exit
.TP
\fB\-V\fR, \fB\-\-version\fR
output version information and exit
+.TP
+\fB\-a\fR, \fB\-\-text\fR
+treat all files as text
+.TP
+\fB\-A\fR, \fB\-\-after\-context=\fR<n>
+print <n> lines of trailing context
+.TP
+\fB\-b\fR, \fB\-\-byte\-offset\fR
+print the byte offset of each line
+.TP
+\fB\-B\fR, \fB\-\-before\-context=\fR<n>
+print <n> lines of leading context
+.TP
+\fB\-c\fR, \fB\-\-count\fR
+only print a count of matching lines per file
+.TP
+\fB\-C\fR, \fB\-\-context=\fR<n>
+print <n> lines of output context
+.TP
+\fB\-e\fR, \fB\-\-regexp=\fR<pattern>
+use <pattern> as the pattern to match
+.TP
+\fB\-E\fR, \fB\-\-extended\-regexp\fR
+<pattern> is an extended regular expression
+.TP
+\fB\-f\fR, \fB\-\-file=\fR<file>
+obtain patterns from <file>
+.TP
+\fB\-F\fR, \fB\-\-fixed\-strings\fR
+<pattern> is a set of newline\-separated strings
+.TP
+\fB\-h\fR, \fB\-\-no\-filename\fR
+suppress the prefixing filename on output
+.TP
+\fB\-H\fR, \fB\-\-with\-filename\fR
+print the filename for each match
+.TP
+\fB\-i\fR, \fB\-\-ignore\-case\fR
+ignore case distinctions
+.TP
+\fB\-I\fR
+ignore binary files
+.TP
+\fB\-l\fR, \fB\-\-files\-with\-matches\fR
+only print names of files containing matches
+.TP
+\fB\-L\fR, \fB\-\-files\-without\-match\fR
+only print names of files containing no matches
+.TP
+\fB\-m\fR, \fB\-\-max\-count=\fR<n>
+stop after <n> matches
+.TP
+\fB\-n\fR, \fB\-\-line\-number\fR
+print the line number of each line
+.TP
+\fB\-o\fR, \fB\-\-only\-matching\fR
+show only the part of a line matching <pattern>
+.TP
+\fB\-q\fR, \fB\-\-quiet\fR
+suppress all messages
+.TP
+\fB\-r\fR, \fB\-\-recursive\fR
+operate recursively on directories
+.TP
+\fB\-s\fR, \fB\-\-no\-messages\fR
+suppress error messages
+.TP
+\fB\-v\fR, \fB\-\-invert\-match\fR
+select non\-matching lines
+.TP
+\fB\-\-verbose\fR
+verbose mode (show error messages)
+.TP
+\fB\-w\fR, \fB\-\-word\-regexp\fR
+match only whole words
+.TP
+\fB\-x\fR, \fB\-\-line\-regexp\fR
+match only whole lines
.SH "REPORTING BUGS"
Report bugs to zutils\-bug@nongnu.org
+.br
Zutils home page: http://www.nongnu.org/zutils/zutils.html
.SH COPYRIGHT
-Copyright \(co 2009 Antonio Diaz Diaz.
-This script is free software: you have unlimited permission
-to copy, distribute and modify it.
+Copyright \(co 2010 Antonio Diaz Diaz.
+License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
+.br
+This is free software: you are free to change and redistribute it.
+There is NO WARRANTY, to the extent permitted by law.
diff --git a/doc/ztest.1 b/doc/ztest.1
index 2c53401..9a36415 100644
--- a/doc/ztest.1
+++ b/doc/ztest.1
@@ -1,20 +1,18 @@
-.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.36.
-.TH ZTEST "1" "December 2009" "Ztest (zutils) 0.8-rc1" "User Commands"
+.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.37.1.
+.TH ZTEST "1" "November 2010" "Ztest (zutils) 0.8" "User Commands"
.SH NAME
Ztest \- verify integrity of compressed files
.SH SYNOPSIS
.B ztest
-[\fIOPTIONS\fR] [\fIFILES\fR]
+[\fIoptions\fR] [\fIfiles\fR]
.SH DESCRIPTION
-Ztest \- Test integrity of compressed files.
-.PP
Ztest verifies the integrity of the specified compressed files.
Non\-compressed files are ignored. If no files are specified, the
integrity of compressed data read from standard input is verified. Data
read from standard input must be all compressed with the same compressor.
The supported compressors are bzip2, gzip, lzip and xz.
.PP
-The exit status is 1 if any compressed file is corrupt, 0 otherwise.
+Exit status is 2 if any compressed file is corrupt, 0 otherwise.
.SH OPTIONS
.TP
\fB\-h\fR, \fB\-\-help\fR
@@ -33,8 +31,11 @@ operate recursively on directories
be verbose (a 2nd \fB\-v\fR gives more)
.SH "REPORTING BUGS"
Report bugs to zutils\-bug@nongnu.org
+.br
Zutils home page: http://www.nongnu.org/zutils/zutils.html
.SH COPYRIGHT
-Copyright \(co 2009 Antonio Diaz Diaz.
-This script is free software: you have unlimited permission
-to copy, distribute and modify it.
+Copyright \(co 2010 Antonio Diaz Diaz.
+License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
+.br
+This is free software: you are free to change and redistribute it.
+There is NO WARRANTY, to the extent permitted by law.
diff --git a/doc/zutils.info b/doc/zutils.info
index e9762b9..b7f1250 100644
--- a/doc/zutils.info
+++ b/doc/zutils.info
Binary files differ
diff --git a/doc/zutils.texinfo b/doc/zutils.texinfo
index 5442249..bb6eb6c 100644
--- a/doc/zutils.texinfo
+++ b/doc/zutils.texinfo
@@ -5,8 +5,8 @@
@finalout
@c %**end of header
-@set UPDATED 1 December 2009
-@set VERSION 0.8-rc1
+@set UPDATED 15 November 2010
+@set VERSION 0.8
@dircategory Data Compression
@direntry
@@ -24,7 +24,9 @@
@vskip 0pt plus 1filll
@end titlepage
+@ifnothtml
@contents
+@end ifnothtml
@node Top
@top
@@ -32,17 +34,18 @@
This manual is for Zutils (version @value{VERSION}, @value{UPDATED}).
@menu
-* Introduction:: Purpose and features of zutils
-* Zcat:: Concatenating compressed files
-* Zcmp/Zdiff:: Comparing compressed files
-* Zgrep:: Searching inside compressed files
-* Ztest:: Testing integrity of compressed files
-* Problems:: Reporting bugs
-* Concept Index:: Index of concepts
+* Introduction:: Purpose and features of zutils
+* Zcat:: Concatenating compressed files
+* Zcmp:: Comparing compressed files byte by byte
+* Zdiff:: Comparing compressed files line by line
+* Zgrep:: Searching inside compressed files
+* Ztest:: Testing integrity of compressed files
+* Problems:: Reporting bugs
+* Concept Index:: Index of concepts
@end menu
@sp 1
-Copyright @copyright{} 2008, 2009 Antonio Diaz Diaz.
+Copyright @copyright{} 2008, 2009, 2010 Antonio Diaz Diaz.
This manual is free documentation: you have unlimited permission
to copy, distribute and modify it.
@@ -52,148 +55,443 @@ to copy, distribute and modify it.
@chapter Introduction
@cindex introduction
-Zutils is a collection of utilities for dealing with any combination of
-compressed and non-compressed files transparently. The supported
-compressors are bzip2, gzip, lzip and xz.
+Zutils is a collection of utilities able to deal with any combination of
+compressed and non-compressed files transparently. If any given file,
+including standard input, is compressed, its uncompressed content is
+used. Compressed files are decompressed on the fly; no temporary files
+are created. These utilities are not wrapper scripts but safer and more
+efficient C++ programs. In particular the @samp{--recursive} option is
+very efficient in those utilities supporting it.
-The currently provided utilities are zcat, zcmp, zdiff, zegrep, zfgrep,
-zgrep and ztest.
+@noindent
+The provided utilities are zcat, zcmp, zdiff, zgrep and ztest.@*
+The supported compressors are bzip2, gzip, lzip and xz.
+
+@sp 1
+Numbers given as arguments to options (positions, sizes) may be followed
+by a multiplier and an optional @samp{B} for "byte".
+
+Table of SI and binary prefixes (unit multipliers):
+
+@multitable {Prefix} {kilobyte (10^3 = 1000)} {|} {Prefix} {kibibyte (2^10 = 1024)}
+@item Prefix @tab Value @tab | @tab Prefix @tab Value
+@item k @tab kilobyte (10^3 = 1000) @tab | @tab Ki @tab kibibyte (2^10 = 1024)
+@item M @tab megabyte (10^6) @tab | @tab Mi @tab mebibyte (2^20)
+@item G @tab gigabyte (10^9) @tab | @tab Gi @tab gibibyte (2^30)
+@item T @tab terabyte (10^12) @tab | @tab Ti @tab tebibyte (2^40)
+@item P @tab petabyte (10^15) @tab | @tab Pi @tab pebibyte (2^50)
+@item E @tab exabyte (10^18) @tab | @tab Ei @tab exbibyte (2^60)
+@item Z @tab zettabyte (10^21) @tab | @tab Zi @tab zebibyte (2^70)
+@item Y @tab yottabyte (10^24) @tab | @tab Yi @tab yobibyte (2^80)
+@end multitable
@node Zcat
@chapter Zcat
@cindex zcat
-Zcat is a wrapper script around the cat command that allows transparent
-concatenation of any combination of compressed and non-compressed files.
-If any given file is compressed, its uncompressed content is used. If a
-given file does not exist, zcat tries the compressed file names
+Zcat copies each given file (@samp{-} means standard input), to standard
+output. If any given file is compressed, its uncompressed content is
+used. If a given file does not exist, and its name does not end with one
+of the known extensions, zcat tries the compressed file names
corresponding to the supported compressors. If no files are specified,
data is read from standard input, decompressed if needed, and sent to
-stdout. Data read from standard input must be of the same type; all
-uncompressed or all compressed with the same compressor.
+standard output. Data read from standard input must be of the same type;
+all uncompressed or all compressed with the same compressor.
The format for running zcat is:
@example
-zcat [@var{options}] [@var{cat_options}] [@var{files}]
+zcat [@var{options}] [@var{files}]
@end example
@noindent
-@var{cat_options} are passed directly to cat. The exit status from cat
-is preserved.
+Exit status is 0 if no errors occurred, 1 otherwise.
Zcat supports the following options:
@table @samp
-@item --help
-@itemx -h
+@item -h
+@itemx --help
Print an informative help message describing the options and exit.
-@item --version
-@itemx -V
+@item -V
+@itemx --version
Print the version number of zcat on the standard output and exit.
-@item --recursive
-@itemx -r
+@item -A
+@itemx --show-all
+Equivalent to @samp{-vET}.
+
+@item -b
+@itemx --number-nonblank
+Number all nonblank output lines, starting with 1. The line count is
+unlimited.
+
+@item -e
+Equivalent to @samp{-vE}.
+
+@item -E
+@itemx --show-ends
+Print a @samp{$} after the end of each line.
+
+@item -n
+@itemx --number
+Number all output lines, starting with 1. The line count is unlimited.
+
+@item -q
+@itemx --quiet
+Quiet operation. Suppress all messages.
+
+@item -r
+@itemx --recursive
Operate recursively on directories.
+@item -s
+@itemx --squeeze-blank
+Replace multiple adjacent blank lines with a single blank line.
+
+@item -t
+Equivalent to @samp{-vT}.
+
+@item -T
+@itemx --show-tabs
+Print TAB characters as @samp{^I}.
+
+@item -v
+@itemx --show-nonprinting
+Print control characters except for LF (newline) and TAB using @samp{^}
+notation and precede characters larger than 127 with @samp{M-} (which
+stands for "meta").
+
+@item --verbose
+Verbose mode. Show error messages.
+
@end table
-@node Zcmp/Zdiff
-@chapter Zcmp/Zdiff
+@node Zcmp
+@chapter Zcmp
@cindex zcmp
-@cindex zdiff
-Zdiff is a wrapper script around the diff and cmp commands that allows
-transparent comparison of any combination of compressed and
-non-compressed files. If any given file is compressed, its uncompressed
-content is used.
+Zcmp compares two files (@samp{-} means standard input), and if they
+differ, tells the first byte and line number where they differ. Bytes
+and lines are numbered starting with 1. If any given file is compressed,
+its uncompressed content is used. Compressed files are decompressed on
+the fly; no temporary files are created.
+
+The format for running zcmp is:
+
+@example
+zcmp [@var{options}] @var{file1} [@var{file2}]
+@end example
+
+@noindent
+Compares @var{file1} to @var{file2}. If @var{file2} is omitted zcmp
+tries the following:@*
+If @var{file1} is compressed, compares @var{file1} to the file with the
+corresponding decompressed file name (removes the extension from
+@var{file1}).@*
+If @var{file1} is not compressed, compares @var{file1} to the
+uncompressed contents of @var{file1}.[bz2|gz|lz|xz] (the first one that
+is found).@*
+If no suitable file is found, compares @var{file1} to data read from
+standard input.
@noindent
-Zcmp is a shortcut for @samp{zdiff --cmp}
+An exit status of 0 means no differences were found, 1 means some
+differences were found, and 2 means trouble.
+
+Zcmp supports the following options:
+
+@table @samp
+@item -h
+@itemx --help
+Print an informative help message describing the options and exit.
+
+@item -V
+@itemx --version
+Print the version number of zcmp on the standard output and exit.
+
+@item -b
+@itemx --print-bytes
+Print the differing bytes. Print control bytes as a @samp{^} followed by
+a letter, and precede bytes larger than 127 with @samp{M-} (which stands
+for "meta").
+
+@item -i @var{size}
+@itemx --ignore-initial=@var{size}
+Ignore any differences in the first @var{size} bytes of the input files.
+Treat files with fewer than @var{size} bytes as if they were empty. If
+@var{size} is in the form @samp{@var{size1},@var{size2}}, ignore the
+first @var{size1} bytes of the first input file and the first
+@var{size2} bytes of the second input file.
+
+@item -l
+@itemx -v
+@itemx --list
+@itemx --verbose
+Print the byte numbers (in decimal) and values (in octal) of all
+differing bytes.
+
+@item -n @var{count}
+@itemx --bytes=@var{count}
+Compare at most @var{count} input bytes.
+
+@item -q
+@itemx -s
+@itemx --quiet
+@itemx --silent
+Do not print anything; only return an exit status indicating whether the
+files differ.
+
+@end table
+
+
+@node Zdiff
+@chapter Zdiff
+@cindex zdiff
+
+Zdiff compares two files (@samp{-} means standard input), and if they
+differ, shows the differences line by line. If any given file is
+compressed, its uncompressed content is used. Zdiff is a front end to
+the diff program and has the limitation that messages from diff refer to
+temporary filenames instead of those specified.
The format for running zdiff is:
@example
-zdiff [@var{options}] [@var{diff_options}] @var{file1} [@var{file2}]
+zdiff [@var{options}] @var{file1} [@var{file2}]
@end example
@noindent
-Compares @var{file1} to @var{file2}. If @var{file2} is omitted and
-@var{file1} is compressed, compares @var{file1} to the file with the
+Compares @var{file1} to @var{file2}. If @var{file2} is omitted zdiff
+tries the following:@*
+If @var{file1} is compressed, compares @var{file1} to the file with the
corresponding decompressed file name (removes the extension from
-@var{file1}). If @var{file2} is omitted and @var{file1} is not
-compressed, compares @var{file1} to the uncompressed contents of
-@var{file1}.[bz2|gz|lz|xz] (the first one that is found).
-@var{diff_options} are passed directly to diff or cmp. The exit status
-from diff or cmp is preserved.
+@var{file1}).@*
+If @var{file1} is not compressed, compares @var{file1} to the
+uncompressed contents of @var{file1}.[bz2|gz|lz|xz] (the first one that
+is found).@*
+If no suitable file is found, compares @var{file1} to data read from
+standard input.
+
+@noindent
+An exit status of 0 means no differences were found, 1 means some
+differences were found, and 2 means trouble.
Zdiff supports the following options:
@table @samp
-@item --help
-@itemx -h
+@item -h
+@itemx --help
Print an informative help message describing the options and exit.
-@item --version
-@itemx -V
+@item -V
+@itemx --version
Print the version number of zdiff on the standard output and exit.
-@item --diff
-Use diff to compare files (default).
+@item -a
+@itemx --text
+Treat all files as text.
-@item --cmp
-Use cmp to compare files.
+@item -b
+@itemx --ignore-space-change
+Ignore changes in the amount of white space.
-@end table
+@item -B
+@itemx --ignore-blank-lines
+Ignore changes whose lines are all blank.
+
+@itemx -c
+Use the context output format.
+
+@item -C @var{n}
+@itemx --context=@var{n}
+Same as -c but use @var{n} lines of context.
+
+@item -d
+@itemx --minimal
+Try hard to find a smaller set of changes.
-Zdiff has the limitation that messages from the diff or cmp programs
-refer to temporary filenames instead of those specified.
+@item -E
+@itemx --ignore-tab-expansion
+Ignore changes due to tab expansion.
+
+@item -i
+@itemx --ignore-case
+Ignore case differences in file contents.
+
+@item -p
+@itemx --show-c-function
+Show which C function each change is in.
+
+@item -q
+@itemx --brief
+Output only whether files differ.
+
+@item -s
+@itemx --report-identical-files
+Report when two files are identical.
+
+@item -t
+@itemx --expand-tabs
+Expand tabs to spaces in output.
+
+@item -T
+@itemx --initial-tab
+Make tabs line up by prepending a tab.
+
+@item -u
+Use the unified output format.
+
+@item -U @var{n}
+@itemx --unified=@var{n}
+Same as -u but use @var{n} lines of context.
+
+@item -w
+@itemx --ignore-all-space
+Ignore all white space.
+
+@end table
@node Zgrep
@chapter Zgrep
-@cindex zegrep
-@cindex zfgrep
@cindex zgrep
-Zgrep is a wrapper script around the grep command that allows
-transparent search on any combination of compressed and non-compressed
-files. If any given file is compressed, its uncompressed content is
-used. If a given file does not exist, zgrep tries the compressed file
-names corresponding to the supported compressors. If no files are
-specified, data is read from standard input, decompressed if needed, and
-fed to grep. Data read from standard input must be of the same type; all
-uncompressed or all compressed with the same compressor.
-
-@noindent
-Zegrep is a shortcut for @samp{zgrep -E}@*
-Zfgrep is a shortcut for @samp{zgrep -F}
-
+Zgrep is a front end to the grep program that allows transparent search
+on any combination of compressed and non-compressed files. If any given
+file is compressed, its uncompressed content is used. If a given file
+does not exist, and its name does not end with one of the known
+extensions, zgrep tries the compressed file names corresponding to the
+supported compressors. If no files are specified, data is read from
+standard input, decompressed if needed, and fed to grep. Data read from
+standard input must be of the same type; all uncompressed or all
+compressed with the same compressor.
The format for running zgrep is:
@example
-zgrep [@var{options}] [@var{grep_options}] @var{pattern} [@var{files}]
+zgrep [@var{options}] @var{pattern} [@var{files}]
@end example
@noindent
-@var{grep_options} are passed directly to grep. The exit status from
-grep is preserved.
+An exit status of 0 means at least one match was found, 1 means no
+matches were found, and 2 means trouble.
Zgrep supports the following options:
@table @samp
@item --help
-@itemx -h
Print an informative help message describing the options and exit.
-@item --version
-@itemx -V
+@item -V
+@itemx --version
Print the version number of zgrep on the standard output and exit.
+@item -a
+@itemx --text
+Treat all files as text.
+
+@item -A @var{n}
+@itemx --after-context=@var{n}
+Print @var{n} lines of trailing context.
+
+@item -b
+@itemx --byte-offset
+Print the byte offset of each line.
+
+@item -B @var{n}
+@itemx --before-context=@var{n}
+Print @var{n} lines of leading context.
+
+@item -c
+@itemx --count
+Only print a count of matching lines per file.
+
+@item -C @var{n}
+@itemx --context=@var{n}
+Print @var{n} lines of output context.
+
+@item -e @var{pattern}
+@itemx --regexp=@var{pattern}
+Use @var{pattern} as the pattern to match.
+
+@item -E
+@itemx --extended-regexp
+Treat @var{pattern} as an extended regular expression.
+
+@item -f @var{file}
+@itemx --file=@var{file}
+Obtain patterns from @var{file}, one per line.
+
+@item -F
+@itemx --fixed-strings
+Treat @var{pattern} as a set of newline-separated strings.
+
+@item -h
+@itemx --no-filename
+Suppress the prefixing filename on output.
+
+@item -H
+@itemx --with-filename
+Print the filename for each match.
+
+@item -i
+@itemx --ignore-case
+Ignore case distinctions.
+
+@item -I
+Ignore binary files.
+
+@item -l
+@itemx --files-with-matches
+Only print names of files containing at least one match.
+
+@item -L
+@itemx --files-without-match
+Only print names of files not containing any matches.
+
+@item -m @var{n}
+@itemx --max-count=@var{n}
+Stop after @var{n} matches.
+
+@item -n
+@itemx --line-number
+Prefix each matched line with its line number in the input file.
+
+@item -o
+@itemx --only-matching
+Show only the part of matching lines that actually matches @var{pattern}.
+
+@item -q
+@itemx --quiet
+Suppress all messages.
+
+@item -r
+@itemx --recursive
+Operate recursively on directories.
+
+@item -s
+@itemx --no-messages
+Suppress error messages.
+
+@item -v
+@itemx --invert-match
+Select non-matching lines.
+
+@item --verbose
+Verbose mode. Show error messages.
+
+@item -w
+@itemx --word-regexp
+Match only whole words.
+
+@item -x
+@itemx --line-regexp
+Match only whole lines.
+
@end table
@@ -213,29 +511,31 @@ ztest [@var{options}] [@var{files}]
@end example
@noindent
-The exit status is 0 if all files verify OK, 1 otherwise.
+The exit status is 0 if all files verify OK, 1 for environmental
+problems (file not found, invalid flags, I/O errors, etc), 2 to indicate
+a corrupt or invalid input file.
Ztest supports the following options:
@table @samp
-@item --help
-@itemx -h
+@item -h
+@itemx --help
Print an informative help message describing the options and exit.
-@item --version
-@itemx -V
+@item -V
+@itemx --version
Print the version number of ztest on the standard output and exit.
-@item --quiet
-@itemx -q
+@item -q
+@itemx --quiet
Quiet operation. Suppress all messages.
-@item --recursive
-@itemx -r
+@item -r
+@itemx --recursive
Operate recursively on directories.
-@item --verbose
-@itemx -v
+@item -v
+@itemx --verbose
Verbose mode. Show the verify status for each file processed.
Further -v's increase the verbosity level.
@@ -254,7 +554,7 @@ for all eternity, if not longer.
If you find a bug in zutils, please send electronic mail to
@email{zutils-bug@@nongnu.org}. Include the version number, which you can
-find by running @w{@samp{zdiff --version}}.
+find by running @w{@samp{zutils --version}}.
@node Concept Index
diff --git a/main.cc b/main.cc
index eba364b..bc7c5fb 100644
--- a/main.cc
+++ b/main.cc
@@ -1,5 +1,5 @@
-/* Zutils - A file format detector for compressed files
- Copyright (C) 2009 Antonio Diaz Diaz.
+/* Zutils - Utilities dealing with compressed files
+ Copyright (C) 2009, 2010 Antonio Diaz Diaz.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -14,257 +14,69 @@
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-/*
- Return values: 0 for a normal exit, 1 for environmental problems
- (file not found, invalid flags, I/O errors, etc), 2 to indicate a
- corrupt or invalid input file, 3 for an internal consistency error
- (eg, bug) which caused zutils to panic.
-*/
#define _FILE_OFFSET_BITS 64
-#include <algorithm>
#include <cerrno>
#include <climits>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
+#include <list>
#include <string>
#include <vector>
+#include <dirent.h>
#include <fcntl.h>
#include <stdint.h>
#include <unistd.h>
-#include <utime.h>
#include <sys/stat.h>
-#include <sys/time.h>
+#if defined(__MSVCRT__) || defined(__OS2__)
+#include <io.h>
+#endif
#include "arg_parser.h"
+#include "zutils.h"
-#ifndef LLONG_MAX
-#define LLONG_MAX 0x7FFFFFFFFFFFFFFFLL
-#endif
-#ifndef LLONG_MIN
-#define LLONG_MIN (-LLONG_MAX - 1LL)
-#endif
-#ifndef ULLONG_MAX
-#define ULLONG_MAX 0xFFFFFFFFFFFFFFFFULL
+#if CHAR_BIT != 8
+#error "Environments where CHAR_BIT != 8 are not supported."
#endif
namespace {
-const char * invocation_name = 0;
-const char * const Program_name = "Zutils";
-const char * const program_name = "zutils";
-const char * const program_year = "2009";
-
-struct { const char * from; const char * to; } const known_extensions[] = {
- { ".zf", "" },
- { 0, 0 } };
-
-enum Mode { m_compress = 0, m_decompress, m_test };
-
-std::string output_filename;
-int outhandle = -1;
-int verbosity = 0;
-bool delete_output_on_interrupt = false;
-
-
-class Pretty_print
- {
- const char * const stdin_name;
- const unsigned int stdin_name_len;
- unsigned int longest_name;
- std::string name_;
- mutable bool first_post;
-
-public:
- Pretty_print( const std::vector< std::string > & filenames )
- : stdin_name( "(stdin)" ), stdin_name_len( std::strlen( stdin_name ) ),
- longest_name( 0 ), first_post( false )
- {
- for( unsigned int i = 0; i < filenames.size(); ++i )
- {
- const std::string & s = filenames[i];
- const unsigned int len = ( ( s == "-" ) ? stdin_name_len : s.size() );
- if( len > longest_name ) longest_name = len;
- }
- if( longest_name == 0 ) longest_name = stdin_name_len;
- }
-
- void set_name( const std::string & filename )
- {
- if( filename.size() && filename != "-" ) name_ = filename;
- else name_ = stdin_name;
- first_post = true;
- }
-
- void reset() const throw() { if( name_.size() ) first_post = true; }
- const char * name() const throw() { return name_.c_str(); }
- void operator()( const char * const msg = 0 ) const throw();
- };
-
+#ifdef O_BINARY
+const int o_binary = O_BINARY;
+#else
+const int o_binary = 0;
+#endif
-void Pretty_print::operator()( const char * const msg ) const throw()
- {
- if( verbosity >= 0 )
- {
- if( first_post )
- {
- first_post = false;
- std::fprintf( stderr, " %s: ", name_.c_str() );
- for( unsigned int i = 0; i < longest_name - name_.size(); ++i )
- std::fprintf( stderr, " " );
- if( !msg ) std::fflush( stderr );
- }
- if( msg ) std::fprintf( stderr, "%s.\n", msg );
- }
- }
+enum Mode { m_none, m_zcat, m_zgrep, m_ztest };
void show_help() throw()
{
- std::printf( "%s - A file format detector for compressed files.\n", Program_name );
- std::printf( "\nUsage: %s [options] [files]\n", invocation_name );
- std::printf( "\nOptions:\n" );
+ std::printf( "Zutils is a collection of utilities able to deal with any combination of\n" );
+ std::printf( "compressed and non-compressed files transparently. If any given file,\n" );
+ std::printf( "including standard input, is compressed, its uncompressed content is used.\n" );
+ std::printf( "The supported compressors are bzip2, gzip, lzip and xz.\n" );
+ std::printf( "\nUsage: %s <operation> [options] [files]\n", invocation_name );
+ std::printf( "\nTry `%s <operation> --help' for more specific help.\n", invocation_name );
+ std::printf( "\nOperations:\n" );
std::printf( " -h, --help display this help and exit\n" );
std::printf( " -V, --version output version information and exit\n" );
-// std::printf( " -c, --stdout send output to standard output\n" );
-// std::printf( " -d, --decompress decompress\n" );
-// std::printf( " -f, --force overwrite existing output files\n" );
-// std::printf( " -k, --keep keep (don't delete) input files\n" );
- std::printf( " -m, --magic=<type> output magic bytes for given file type\n" );
-// std::printf( " -o, --output=<file> if reading stdin, place the output into <file>\n" );
- std::printf( " -q, --quiet suppress all messages\n" );
- std::printf( " -t, --test test compressed file type\n" );
- std::printf( " -v, --verbose be verbose (a 2nd -v gives more)\n" );
- std::printf( "\nReport bugs to zutils-bug@nongnu.org\n" );
- std::printf( "Zutils home page: http://www.nongnu.org/zutils/zutils.html\n" );
+ std::printf( " --zcat zcat operation\n" );
+ std::printf( " --zgrep zgrep operation\n" );
+ std::printf( " --ztest ztest operation\n" );
+ show_help_addr();
}
-void show_version() throw()
+int simple_extension_index( const std::string & name ) throw()
{
- std::printf( "%s %s\n", Program_name, PROGVERSION );
- std::printf( "Copyright (C) %s Antonio Diaz Diaz.\n", program_year );
- std::printf( "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n" );
- std::printf( "This is free software: you are free to change and redistribute it.\n" );
- std::printf( "There is NO WARRANTY, to the extent permitted by law.\n" );
- }
-
-
-void show_error( const char * msg, const int errcode = 0, const bool help = false ) throw()
- {
- if( verbosity >= 0 )
+ for( int i = 0; simple_extensions[i]; ++i )
{
- if( msg && msg[0] != 0 )
- {
- std::fprintf( stderr, "%s: %s", program_name, msg );
- if( errcode > 0 ) std::fprintf( stderr, ": %s", std::strerror( errcode ) );
- std::fprintf( stderr, "\n" );
- }
- if( help && invocation_name && invocation_name[0] != 0 )
- std::fprintf( stderr, "Try `%s --help' for more information.\n", invocation_name );
- }
- }
-
-
-void internal_error( const char * msg )
- {
- std::string s( "internal error: " ); s += msg;
- show_error( s.c_str() );
- std::exit( 3 );
- }
-
-
-const char * format_num( long long num, long long limit = 9999,
- const int set_prefix = 0 ) throw()
- {
- const char * const si_prefix[8] =
- { "k", "M", "G", "T", "P", "E", "Z", "Y" };
- const char * const binary_prefix[8] =
- { "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi" };
- static bool si = false;
- static char buf[16];
-
- if( set_prefix ) si = ( set_prefix > 0 );
- const int factor = ( si ) ? 1000 : 1024;
- const char * const *prefix = ( si ) ? si_prefix : binary_prefix;
- const char *p = "";
- limit = std::max( 999LL, std::min( 999999LL, limit ) );
-
- for( int i = 0; i < 8 && ( llabs( num ) > limit ||
- ( llabs( num ) >= factor && num % factor == 0 ) ); ++i )
- { num /= factor; p = prefix[i]; }
- snprintf( buf, sizeof buf, "%lld %s", num, p );
- return buf;
- }
-
-
-long long getnum( const char * ptr, const int bs,
- const long long llimit = LLONG_MIN + 1,
- const long long ulimit = LLONG_MAX ) throw()
- {
- errno = 0;
- char *tail;
- long long result = strtoll( ptr, &tail, 0 );
- if( tail == ptr )
- {
- show_error( "bad or missing numerical argument", 0, true );
- std::exit( 1 );
- }
-
- if( !errno && tail[0] )
- {
- int factor = ( tail[1] == 'i' ) ? 1024 : 1000;
- int exponent = 0;
- bool bad_multiplier = false;
- switch( tail[0] )
- {
- case ' ': break;
- case 'b': if( bs > 0 ) { factor = bs; exponent = 1; }
- else bad_multiplier = true;
- break;
- case 'Y': exponent = 8; break;
- case 'Z': exponent = 7; break;
- case 'E': exponent = 6; break;
- case 'P': exponent = 5; break;
- case 'T': exponent = 4; break;
- case 'G': exponent = 3; break;
- case 'M': exponent = 2; break;
- case 'K': if( factor == 1024 ) exponent = 1; else bad_multiplier = true;
- break;
- case 'k': if( factor == 1000 ) exponent = 1; else bad_multiplier = true;
- break;
- default: bad_multiplier = true;
- }
- if( bad_multiplier )
- {
- show_error( "bad multiplier in numerical argument", 0, true );
- std::exit( 1 );
- }
- for( int i = 0; i < exponent; ++i )
- {
- if( LLONG_MAX / factor >= llabs( result ) ) result *= factor;
- else { errno = ERANGE; break; }
- }
- }
- if( !errno && ( result < llimit || result > ulimit ) ) errno = ERANGE;
- if( errno )
- {
- show_error( "numerical argument out of limits" );
- std::exit( 1 );
- }
- return result;
- }
-
-
-int extension_index( const std::string & name ) throw()
- {
- for( int i = 0; known_extensions[i].from; ++i )
- {
- const std::string ext( known_extensions[i].from );
+ const std::string ext( simple_extensions[i] );
if( name.size() > ext.size() &&
name.compare( name.size() - ext.size(), ext.size(), ext ) == 0 )
return i;
@@ -273,449 +85,262 @@ int extension_index( const std::string & name ) throw()
}
-int open_instream( const std::string & name, struct stat * in_statsp,
- const Mode program_mode, const int eindex,
- const bool force, const bool to_stdout ) throw()
+int open_instream( std::string & input_filename, const Mode program_mode ) throw()
{
- int inhandle = -1;
- if( program_mode == m_compress && !force && eindex >= 0 )
- {
- if( verbosity >= 0 )
- std::fprintf( stderr, "%s: input file `%s' already has `%s' suffix.\n",
- program_name, name.c_str(),
- known_extensions[eindex].from );
- }
- else
+ int infd = open( input_filename.c_str(), O_RDONLY | o_binary );
+ if( infd < 0 )
{
- inhandle = open( name.c_str(), O_RDONLY );
- if( inhandle < 0 )
+ if( ( program_mode == m_zcat || program_mode == m_zgrep )
+ && simple_extension_index( input_filename ) < 0 )
{
- if( verbosity >= 0 )
- std::fprintf( stderr, "%s: Can't open input file `%s': %s.\n",
- program_name, name.c_str(), std::strerror( errno ) );
- }
- else
- {
- const int i = fstat( inhandle, in_statsp );
- const mode_t & mode = in_statsp->st_mode;
- if( i < 0 || !( S_ISREG( mode ) || ( to_stdout &&
- ( S_ISFIFO( mode ) || S_ISSOCK( mode ) ||
- S_ISBLK( mode ) || S_ISCHR( mode ) ) ) ) )
+ for( int i = 0; simple_extensions[i]; ++i )
{
- if( verbosity >= 0 )
- std::fprintf( stderr, "%s: input file `%s' is not a regular file%s.\n",
- program_name, name.c_str(),
- to_stdout ? "" : " and `--stdout' was not specified" );
- close( inhandle );
- inhandle = -1;
+ const std::string name( input_filename + simple_extensions[i] );
+ infd = open( name.c_str(), O_RDONLY | o_binary );
+ if( infd >= 0 ) { input_filename = name; break; }
}
}
+ if( infd < 0 && verbosity >= 0 )
+ std::fprintf( stderr, "%s: Can't open input file `%s': %s.\n",
+ util_name, input_filename.c_str(), std::strerror( errno ) );
}
- return inhandle;
- }
-
-
-void set_c_outname( const std::string & name ) throw()
- {
- output_filename = name;
- output_filename += known_extensions[0].from;
- }
-
-
-void set_d_outname( const std::string & name, const int i ) throw()
- {
- if( i >= 0 )
- {
- const std::string from( known_extensions[i].from );
- if( name.size() > from.size() )
- {
- output_filename.assign( name, 0, name.size() - from.size() );
- output_filename += known_extensions[i].to;
- return;
- }
- }
- output_filename = name; output_filename += ".out";
- if( verbosity >= 0 )
- std::fprintf( stderr, "%s: can't guess original name for `%s' -- using `%s'.\n",
- program_name, name.c_str(), output_filename.c_str() );
- }
-
-
-bool open_outstream( const bool /*force*/ ) throw()
- {
-/* if( force )
- outhandle = open( output_filename.c_str(), O_CREAT | O_TRUNC | O_WRONLY,
- S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH );
- else outhandle = open( output_filename.c_str(), O_CREAT | O_EXCL | O_WRONLY,
- S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH );
- if( outhandle < 0 )
- {
- if( errno == EEXIST ) outhandle = -2; else outhandle = -1;
- if( verbosity >= 0 )
- {
- if( outhandle == -2 )
- std::fprintf( stderr, "%s: Output file %s already exists, skipping.\n",
- program_name, output_filename.c_str() );
- else
- std::fprintf( stderr, "%s: Can't create output file `%s': %s.\n",
- program_name, output_filename.c_str(), std::strerror( errno ) );
- }
- }*/
- return ( outhandle >= 0 );
- }
-
-
-bool check_tty( const int inhandle, const Mode program_mode ) throw()
- {
- if( program_mode == m_compress && isatty( outhandle ) )
- {
- show_error( "I won't write compressed data to a terminal.", 0, true );
- return false;
- }
- if( ( program_mode == m_decompress || program_mode == m_test ) &&
- isatty( inhandle ) )
- {
- show_error( "I won't read compressed data from a terminal.", 0, true );
- return false;
- }
- return true;
+ return infd;
}
+#include "zcat.cc"
+#include "zgrep.cc"
+#include "ztest.cc"
-void cleanup_and_fail( const int retval ) throw()
- {
- if( delete_output_on_interrupt )
- {
- if( verbosity >= 0 )
- std::fprintf( stderr, "%s: Deleting output file `%s', if it exists.\n",
- program_name, output_filename.c_str() );
- if( outhandle >= 0 ) { close( outhandle ); outhandle = -1; }
- if( std::remove( output_filename.c_str() ) != 0 )
- show_error( "WARNING: deletion of output file (apparently) failed." );
- }
- std::exit( retval );
- }
-
-
- // Set permissions, owner and times.
-void close_and_set_permissions( const struct stat * in_statsp, int * retvalp )
- {
- int tmp = 0;
- if( in_statsp )
- {
- if( fchmod( outhandle, in_statsp->st_mode ) != 0 ) tmp = 1;
- if( !tmp ) (void)fchown( outhandle, in_statsp->st_uid, in_statsp->st_gid );
- // fchown will in many cases return with EPERM, which can be safely ignored.
- }
- if( close( outhandle ) == 0 ) outhandle = -1;
- else cleanup_and_fail( 1 );
- delete_output_on_interrupt = false;
- if( !in_statsp ) return;
- if( !tmp )
- {
- struct utimbuf t;
- t.actime = in_statsp->st_atime;
- t.modtime = in_statsp->st_mtime;
- tmp = utime( output_filename.c_str(), &t );
- }
- if( tmp )
- {
- if( tmp > *retvalp ) *retvalp = tmp;
- show_error( "I can't change output file attributes." );
- cleanup_and_fail( *retvalp );
- }
- }
+} // end namespace
-// Returns the number of bytes really read.
-// If (returned value < size) and (errno == 0), means EOF was reached.
-//
-int readblock( const int fd, char * buf, const int size ) throw()
+int main( const int argc, const char * const argv[] )
{
- int rest = size;
- errno = 0;
- while( rest > 0 )
- {
- errno = 0;
- const int n = read( fd, buf + size - rest, rest );
- if( n > 0 ) rest -= n;
- else if( n == 0 ) break;
- else if( errno != EINTR && errno != EAGAIN ) break;
- }
- return ( rest > 0 ) ? size - rest : size;
- }
-
+ enum { help_opt = 256, verbose_opt, zcat_opt, zgrep_opt, ztest_opt };
+ const Arg_parser::Option * options = 0;
+ int infd = -1;
+ Mode program_mode = m_none;
+ bool recursive = false;
+ std::string input_filename;
+ std::list< std::string > filenames;
+ Cat_options cat_options;
+ std::vector< const char * > grep_args; // args to grep, maybe empty
+ std::vector< const char * > ztest_args; // args to ztest, maybe empty
+ invocation_name = argv[0];
-// Returns the number of bytes really written.
-// If (returned value < size), it is always an error.
-//
-int writeblock( const int fd, const char * buf, const int size ) throw()
- {
- int rest = size;
- errno = 0;
- while( rest > 0 )
+ const Arg_parser::Option m_zcat_options[] =
{
- errno = 0;
- const int n = write( fd, buf + size - rest, rest );
- if( n > 0 ) rest -= n;
- else if( errno && errno != EINTR && errno != EAGAIN ) break;
- }
- return ( rest > 0 ) ? size - rest : size;
- }
-
-/*
-int compress( const int inhandle, const Pretty_print & pp,
- const struct stat * in_statsp, int * retvalp )
- {
- long long in_size = 0, out_size = 0;
- if( verbosity >= 1 )
+ { 'A', "show-all", Arg_parser::no }, // cat
+ { 'b', "number-nonblank", Arg_parser::no }, // cat
+ { 'c', "stdout", Arg_parser::no }, // gzip
+ { 'd', "decompress", Arg_parser::no }, // gzip
+ { 'e', 0, Arg_parser::no }, // cat
+ { 'E', "show-ends", Arg_parser::no }, // cat
+ { 'f', "force", Arg_parser::no }, // gzip
+ { 'h', "help", Arg_parser::no },
+ { 'l', "list", Arg_parser::no }, // gzip
+ { 'L', "license", Arg_parser::no }, // gzip
+ { 'n', "number", Arg_parser::no }, // cat
+ { 'q', "quiet", Arg_parser::no },
+ { 'r', "recursive", Arg_parser::no },
+ { 's', "squeeze-blank", Arg_parser::no }, // cat
+ { 't', 0, Arg_parser::no }, // cat
+ { 'T', "show-tabs", Arg_parser::no }, // cat
+ { 'v', "show-nonprinting", Arg_parser::no }, // cat
+ { 'V', "version", Arg_parser::no },
+ { verbose_opt, "verbose", Arg_parser::no },
+ { zcat_opt, "zcat", Arg_parser::no },
+ { 0 , 0, Arg_parser::no } };
+
+ const Arg_parser::Option m_zgrep_options[] =
{
- pp();
- if( in_size <= 0 || out_size <= 0 )
- std::fprintf( stderr, "no data compressed.\n" );
- else
- std::fprintf( stderr, "%6.3f:1, %6.3f bits/byte, "
- "%5.2f%% saved, %lld in, %lld out.\n",
- (double)in_size / out_size,
- ( 8.0 * out_size ) / in_size,
- 100.0 * ( 1.0 - ( (double)out_size / in_size ) ),
- in_size, out_size );
- }
- return 0;
- }
-
-
-int decompress( const int inhandle, const Pretty_print & pp )
- {
- if( verbosity >= 1 )
- std::fprintf( stderr, "done\n" );
- return 0;
- }
-*/
-
-unsigned char xdigit( const int value ) throw()
- {
- if( value >= 0 && value <= 9 ) return '0' + value;
- if( value >= 10 && value <= 15 ) return 'A' + value - 10;
- return 0;
- }
-
-
-int xtoi( const unsigned char ch ) throw()
- {
- switch( ch )
+ { 'a', "text", Arg_parser::no }, // grep GNU
+ { 'A', "after-context", Arg_parser::yes }, // grep GNU
+ { 'b', "byte-offset", Arg_parser::no }, // grep GNU
+ { 'B', "before-context", Arg_parser::yes }, // grep GNU
+ { 'c', "count", Arg_parser::no }, // grep
+ { 'C', "context", Arg_parser::yes }, // grep GNU
+ { 'e', "regexp", Arg_parser::yes }, // grep
+ { 'E', "extended-regexp", Arg_parser::no }, // grep
+ { 'f', "file ", Arg_parser::yes }, // grep
+ { 'F', "fixed-strings", Arg_parser::no }, // grep
+ { 'h', "no-filename", Arg_parser::no }, // grep GNU
+ { 'H', "with-filename", Arg_parser::no }, // grep GNU
+ { 'i', "ignore-case", Arg_parser::no }, // grep
+ { 'I', 0, Arg_parser::no }, // grep GNU
+ { 'l', "files-with-matches", Arg_parser::no }, // grep
+ { 'L', "files-without-match", Arg_parser::no }, // grep GNU
+ { 'm', "max-count", Arg_parser::yes }, // grep GNU
+ { 'n', "line-number", Arg_parser::no }, // grep
+ { 'o', "only-matching", Arg_parser::no }, // grep
+ { 'q', "quiet", Arg_parser::no },
+ { 'r', "recursive", Arg_parser::no },
+ { 's', "no-messages", Arg_parser::no }, // grep
+ { 'v', "invert-match", Arg_parser::no }, // grep
+ { 'V', "version", Arg_parser::no },
+ { 'w', "word-regexp", Arg_parser::no }, // grep GNU
+ { 'x', "line-regexp", Arg_parser::no }, // grep
+ { help_opt, "help", Arg_parser::no },
+ { verbose_opt, "verbose", Arg_parser::no },
+ { zgrep_opt, "zgrep", Arg_parser::no },
+ { 0 , 0, Arg_parser::no } };
+
+ const Arg_parser::Option m_ztest_options[] =
{
- case '0': return 0;
- case '1': return 1;
- case '2': return 2;
- case '3': return 3;
- case '4': return 4;
- case '5': return 5;
- case '6': return 6;
- case '7': return 7;
- case '8': return 8;
- case '9': return 9;
- case 'a':
- case 'A': return 0x0A;
- case 'b':
- case 'B': return 0x0B;
- case 'c':
- case 'C': return 0x0C;
- case 'd':
- case 'D': return 0x0D;
- case 'e':
- case 'E': return 0x0E;
- case 'f':
- case 'F': return 0x0F;
- default: return -1;
- }
- }
-
-
-bool hex_to_data( const std::string & hex, std::string & data )
- {
- data.clear();
- if( hex.size() == 0 || hex.size() % 2 != 0 ) return false;
- for( unsigned int i = 0; 2 * i + 1 < hex.size(); ++i )
+ { 'h', "help", Arg_parser::no },
+ { 'q', "quiet", Arg_parser::no },
+ { 'r', "recursive", Arg_parser::no },
+ { 'v', "verbose", Arg_parser::no },
+ { 'V', "version", Arg_parser::no },
+ { ztest_opt, "ztest", Arg_parser::no },
+ { 0 , 0, Arg_parser::no } };
+
+ { // parse operation
+ const Arg_parser::Option operations[] =
{
- int uch = xtoi( hex[2*i] );
- int lch = xtoi( hex[2*i+1] );
- if( uch < 0 || lch < 0 ) return false;
- data.push_back( ( uch << 4 ) | lch );
- }
- return true;
- }
-
-
-int print_magic_type( const std::string & magic_type )
- {
- std::string data;
-
- if( magic_type == "bzip2" ) std::printf( "BZh" );
- else if( magic_type == "gzip" ) std::printf( "\x1F\x8B" );
- else if( magic_type == "lzip" ) std::printf( "LZIP" );
- else if( magic_type == "xz" ) std::printf( "%c7zXZ", '\xFD' );
- else if( hex_to_data( magic_type, data ) ) std::printf( data.c_str() );
- else return 1;
- return 0;
- }
-
+ { 'h', "help", Arg_parser::no },
+ { 'V', "version", Arg_parser::no },
+ { zcat_opt, "zcat", Arg_parser::no },
+ { zgrep_opt, "zgrep", Arg_parser::no },
+ { ztest_opt, "ztest", Arg_parser::no },
+ { 0 , 0, Arg_parser::no } };
+
+ const Arg_parser parser( argv[1], ( argc > 2 ) ? argv[2] : 0, operations );
+ if( parser.error().size() ) // bad operation
+ { show_error( parser.error().c_str(), 0, true ); return 1; }
-int test_stdin_type( const int inhandle, const Pretty_print & pp )
- {
- unsigned char buf[5];
- const char * msg = 0;
- int i = 0;
- if( readblock( inhandle, (char *)buf, 1 ) == 1 )
+ if( parser.arguments() > 0 )
{
- if( buf[0] == 0x1F )
+ switch( parser.code( 0 ) )
{
- if( readblock( inhandle, (char *)&buf[++i], 1 ) == 1 && buf[i] == 0x8B )
- msg = "gzip";
- }
- else if( buf[0] == 'B' )
- {
- if( readblock( inhandle, (char *)&buf[++i], 1 ) == 1 && buf[i] == 'Z' &&
- readblock( inhandle, (char *)&buf[++i], 1 ) == 1 && buf[i] == 'h' )
- msg = "bzip2";
- }
- else if( buf[0] == 'L' )
- {
- if( readblock( inhandle, (char *)&buf[++i], 1 ) == 1 && buf[i] == 'Z' &&
- readblock( inhandle, (char *)&buf[++i], 1 ) == 1 && buf[i] == 'I' &&
- readblock( inhandle, (char *)&buf[++i], 1 ) == 1 && buf[i] == 'P' )
- msg = "lzip";
- }
- else if( buf[0] == 0xFD )
- {
- if( readblock( inhandle, (char *)&buf[++i], 1 ) == 1 && buf[i] == '7' &&
- readblock( inhandle, (char *)&buf[++i], 1 ) == 1 && buf[i] == 'z' &&
- readblock( inhandle, (char *)&buf[++i], 1 ) == 1 && buf[i] == 'X' &&
- readblock( inhandle, (char *)&buf[++i], 1 ) == 1 && buf[i] == 'Z' )
- msg = "xz";
- }
- }
- const int retval = ( msg ? 0 : 1 );
- if( verbosity >= 0 )
- {
- if( verbosity >= 1 ) pp();
- if( !msg )
- {
- char hexmsg[(2*sizeof buf)+1];
- for( int j = 0; j <= i; ++j )
- {
- hexmsg[2*j] = xdigit( buf[j] >> 4 );
- hexmsg[2*j+1] = xdigit( buf[j] & 0x0F );
- }
- hexmsg[2*i+2] = 0;
- msg = hexmsg;
+ case 0 : break;
+ case 'h': show_help(); return 0;
+ case 'V': show_version(); return 0;
+ case zcat_opt : program_mode = m_zcat; options = m_zcat_options;
+ util_name = "zcat"; break;
+ case zgrep_opt : program_mode = m_zgrep; options = m_zgrep_options;
+ util_name = "zgrep"; break;
+ case ztest_opt : program_mode = m_ztest; options = m_ztest_options;
+ util_name = "ztest"; break;
+ default : internal_error( "uncaught option" );
}
- std::printf( "%s\n", msg );
}
- return retval;
- }
+#if defined(__MSVCRT__) || defined(__OS2__)
+ _setmode( STDIN_FILENO, O_BINARY );
+ _setmode( STDOUT_FILENO, O_BINARY );
+#endif
-int test_type( const int inhandle, const Pretty_print & pp )
- {
- unsigned char buf[5];
- const char * msg = 0;
- const int size = readblock( inhandle, (char *)buf, sizeof buf );
- if( size == (int)sizeof buf )
- {
- if( buf[0] == 0x1F && buf[1] == 0x8B )
- msg = "gzip";
- else if( buf[0] == 'B' && buf[1] == 'Z' && buf[2] == 'h' )
- msg = "bzip2";
- else if( buf[0] == 'L' && buf[1] == 'Z' && buf[2] == 'I' && buf[3] == 'P' )
- msg = "lzip";
- else if( buf[0] == 0xFD && buf[1] == '7' && buf[2] == 'z' && buf[3] == 'X' && buf[4] == 'Z' )
- msg = "xz";
- }
- const int retval = ( msg ? 0 : 1 );
- if( verbosity >= 0 )
+ if( program_mode == m_none )
{
- if( verbosity >= 1 ) pp();
- if( !msg ) msg = "unknown";
- std::printf( "%s\n", msg );
+ show_error( "You must specify the operation to be performed.", 0, true );
+ return 1;
}
- return retval;
- }
-
-
-extern "C" void signal_handler( int ) throw()
- {
- show_error( "Control-C or similar caught, quitting." );
- cleanup_and_fail( 0 );
- }
-
+ } // end parse operation
-void set_signals() throw()
- {
- signal( SIGHUP, signal_handler );
- signal( SIGINT, signal_handler );
- signal( SIGTERM, signal_handler );
- }
-
-} // end namespace
-
-
-int main( const int argc, const char * argv[] )
- {
- int inhandle = -1;
- Mode program_mode = m_compress;
- bool force = false;
- bool keep_input_files = false;
- bool to_stdout = false;
- std::string input_filename;
- std::string default_output_filename;
- std::vector< std::string > filenames;
- std::string magic_type;
- invocation_name = argv[0];
-
- const Arg_parser::Option options[] =
- {
- { 'c', "stdout", Arg_parser::no },
- { 'd', "decompress", Arg_parser::no },
- { 'f', "force", Arg_parser::no },
- { 'h', "help", Arg_parser::no },
- { 'k', "keep", Arg_parser::no },
- { 'm', "magic", Arg_parser::yes },
- { 'o', "output", Arg_parser::yes },
- { 'q', "quiet", Arg_parser::no },
- { 't', "test", Arg_parser::no },
- { 'v', "verbose", Arg_parser::no },
- { 'V', "version", Arg_parser::no },
- { 0 , 0, Arg_parser::no } };
-
- Arg_parser parser( argc, argv, options );
+ const Arg_parser parser( argc, argv, options );
if( parser.error().size() ) // bad option
- { show_error( parser.error().c_str(), 0, true ); return 1; }
+ { show_error( parser.error().c_str(), 0, true );
+ return ( program_mode == m_zcat ) ? 1 : 2; }
int argind = 0;
+ bool grep_list = false;
+ bool grep_show_name = true;
+ bool grep_pattern_found = false;
for( ; argind < parser.arguments(); ++argind )
{
const int code = parser.code( argind );
- if( !code ) break; // no more options
- const std::string & arg = parser.argument( argind );
- switch( code )
+ const char * arg = parser.argument( argind ).c_str();
+ if( !code )
{
- case 'c': to_stdout = true; break;
- case 'd': program_mode = m_decompress; break;
- case 'f': force = true; break;
- case 'h': show_help(); return 0;
- case 'k': keep_input_files = true; break;
- case 'm': magic_type = arg; break;
- case 'o': default_output_filename = arg; break;
- case 'q': verbosity = -1; break;
- case 't': program_mode = m_test; break;
- case 'v': if( verbosity < 4 ) ++verbosity; break;
- case 'V': show_version(); return 0;
- default : internal_error( "uncaught option" );
+ if( program_mode == m_zgrep && !grep_pattern_found )
+ { grep_args.push_back( arg ); grep_pattern_found = true; continue; }
+ else break; // no more options
}
- }
+ switch( program_mode )
+ {
+ case m_none: internal_error( "invalid operation" );
+ case m_zcat:
+ switch( code )
+ {
+ case 'A': cat_options.show_ends = true;
+ cat_options.show_nonprinting = true;
+ cat_options.show_tabs = true; break;
+ case 'b': cat_options.number_lines = 1; break;
+ case 'c': break;
+ case 'd': break;
+ case 'e': cat_options.show_nonprinting = true; // fall through
+ case 'E': cat_options.show_ends = true; break;
+ case 'f': break;
+ case 'h': show_zcat_help(); return 0;
+ case 'l': break;
+ case 'L': break;
+ case 'n': if( cat_options.number_lines == 0 )
+ { cat_options.number_lines = 2; } break;
+ case 'q': verbosity = -1; break;
+ case 'r': recursive = true; break;
+ case 's': cat_options.squeeze_blank = true; break;
+ case 't': cat_options.show_nonprinting = true; // fall through
+ case 'T': cat_options.show_tabs = true; break;
+ case 'v': cat_options.show_nonprinting = true; break;
+ case 'V': show_version( "Zcat" ); return 0;
+ case verbose_opt : if( verbosity < 4 ) ++verbosity; break;
+ case zcat_opt : break;
+ default : internal_error( "uncaught option" );
+ } break;
+ case m_zgrep:
+ switch( code )
+ {
+ case 'a': grep_args.push_back( "-a" ); break;
+ case 'A': grep_args.push_back( "-A" ); grep_args.push_back( arg ); break;
+ case 'b': grep_args.push_back( "-b" ); break;
+ case 'B': grep_args.push_back( "-B" ); grep_args.push_back( arg ); break;
+ case 'c': grep_args.push_back( "-c" ); break;
+ case 'C': grep_args.push_back( "-C" ); grep_args.push_back( arg ); break;
+ case 'e': grep_args.push_back( "-e" ); grep_args.push_back( arg );
+ grep_pattern_found = true; break;
+ case 'E': grep_args.push_back( "-E" ); break;
+ case 'f': grep_args.push_back( "-f" ); grep_args.push_back( arg );
+ grep_pattern_found = true; break;
+ case 'F': grep_args.push_back( "-F" ); break;
+ case 'h': grep_show_name = false; break;
+ case 'H': grep_show_name = true; break;
+ case 'i': grep_args.push_back( "-i" ); break;
+ case 'I': grep_args.push_back( "-I" ); break;
+ case 'l': grep_args.push_back( "-l" ); grep_list = true; break;
+ case 'L': grep_args.push_back( "-L" ); grep_list = true; break;
+ case 'm': grep_args.push_back( "-m" ); grep_args.push_back( arg ); break;
+ case 'n': grep_args.push_back( "-n" ); break;
+ case 'o': grep_args.push_back( "-o" ); break;
+ case 'q': grep_args.push_back( "-q" ); verbosity = -1; break;
+ case 'r': recursive = true; break;
+ case 's': grep_args.push_back( "-s" ); verbosity = -1; break;
+ case 'v': grep_args.push_back( "-v" ); break;
+ case 'V': show_version( "Zgrep" ); return 0;
+ case 'w': grep_args.push_back( "-w" ); break;
+ case 'x': grep_args.push_back( "-x" ); break;
+ case help_opt : show_zgrep_help(); return 0;
+ case verbose_opt : if( verbosity < 4 ) ++verbosity; break;
+ case zgrep_opt : break;
+ default : internal_error( "uncaught option" );
+ } break;
+ case m_ztest:
+ switch( code )
+ {
+ case 'h': show_ztest_help(); return 0;
+ case 'q': verbosity = -1; ztest_args.push_back( "-q" ); break;
+ case 'r': recursive = true; break;
+ case 'v': if( verbosity < 4 ) ++verbosity;
+ ztest_args.push_back( "-v" ); break;
+ case 'V': show_version( "Ztest" ); return 0;
+ case ztest_opt : break;
+ default : internal_error( "uncaught option" );
+ } break;
+ }
+ } // end process options
- if( magic_type.size() ) return print_magic_type( magic_type );
+ if( program_mode == m_zgrep && !grep_pattern_found )
+ { show_error( "Pattern not found.", 0, true ); return 2; }
bool filenames_given = false;
for( ; argind < parser.arguments(); ++argind )
@@ -725,96 +350,87 @@ int main( const int argc, const char * argv[] )
}
if( filenames.empty() ) filenames.push_back("-");
- if( filenames_given ) set_signals();
- Pretty_print pp( filenames );
- if( program_mode == m_test )
- outhandle = -1;
-
- int retval = 0;
- for( unsigned int i = 0; i < filenames.size(); ++i )
+ int retval = ( ( program_mode == m_zgrep ) ? 1 : 0 );
+ while( !filenames.empty() )
{
- struct stat in_stats;
- output_filename.clear();
-
- if( !filenames[i].size() || filenames[i] == "-" )
+ input_filename = filenames.front();
+ filenames.pop_front();
+ if( !input_filename.size() || input_filename == "-" )
{
input_filename.clear();
- inhandle = STDIN_FILENO;
- if( program_mode != m_test )
- {
- if( to_stdout || !default_output_filename.size() )
- outhandle = STDOUT_FILENO;
- else
- {
- if( program_mode == m_compress )
- set_c_outname( default_output_filename );
- else output_filename = default_output_filename;
- if( !open_outstream( force ) )
- {
- if( outhandle == -1 && retval < 1 ) retval = 1;
- close( inhandle ); inhandle = -1;
- continue;
- }
- }
- }
+ infd = STDIN_FILENO;
}
else
{
- input_filename = filenames[i];
- const int eindex = extension_index( input_filename );
- inhandle = open_instream( input_filename, &in_stats, program_mode,
- eindex, force, to_stdout );
- if( inhandle < 0 ) { if( retval < 1 ) retval = 1; continue; }
- if( program_mode != m_test )
+ if( recursive )
{
- if( to_stdout ) outhandle = STDOUT_FILENO;
- else
+ struct stat st;
+ if( !stat( input_filename.c_str(), &st ) && S_ISDIR( st.st_mode ) )
{
- if( program_mode == m_compress )
- set_c_outname( input_filename );
- else set_d_outname( input_filename, eindex );
- if( !open_outstream( force ) )
+ DIR * const dirp = opendir( input_filename.c_str() );
+ if( !dirp )
{
- if( outhandle == -1 && retval < 1 ) retval = 1;
- close( inhandle ); inhandle = -1;
- continue;
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: Can't open directory `%s': %s.\n",
+ util_name, input_filename.c_str(), std::strerror( errno ) );
+ if( retval < 1 ) retval = 1; continue;
}
+ std::list< std::string > tmp_list;
+ while( true )
+ {
+ const struct dirent * const entryp = readdir( dirp );
+ if( !entryp ) { closedir( dirp ); break; }
+ std::string tmp_name( entryp->d_name );
+ if( tmp_name != "." && tmp_name != ".." )
+ tmp_list.push_back( input_filename + "/" + tmp_name );
+ }
+ filenames.splice( filenames.begin(), tmp_list );
+ continue;
}
}
+ infd = open_instream( input_filename, program_mode );
+ if( infd < 0 ) { if( retval < 1 ) retval = 1; continue; }
}
- if( !check_tty( inhandle, program_mode ) ) return 1;
-
- if( output_filename.size() && !to_stdout && program_mode != m_test )
- delete_output_on_interrupt = true;
-// const struct stat * in_statsp = input_filename.size() ? &in_stats : 0;
- pp.set_name( input_filename );
int tmp = 0;
switch( program_mode )
{
- case m_compress:
- /*tmp = compress( inhandle, pp, in_statsp, &retval );*/ break;
- case m_decompress:
- /*tmp = decompress( inhandle, pp );*/ break;
- case m_test:
- if( inhandle == STDIN_FILENO )
- tmp = test_stdin_type( inhandle, pp );
- else tmp = test_type( inhandle, pp );
+ case m_none:
+ break;
+ case m_zcat:
+ tmp = cat( infd, input_filename, cat_options );
+ break;
+ case m_zgrep:
+ if( infd == STDIN_FILENO )
+ tmp = zgrep_stdin( infd, grep_args );
+ else tmp = zgrep_file( infd, input_filename, grep_args,
+ grep_list, grep_show_name );
+ break;
+ case m_ztest:
+ if( infd == STDIN_FILENO )
+ tmp = ztest_stdin( infd, ztest_args );
+ else tmp = ztest_file( infd, input_filename, ztest_args );
break;
}
- if( tmp > retval ) retval = tmp;
- if( tmp && program_mode != m_test ) cleanup_and_fail( retval );
+ if( program_mode == m_zgrep )
+ { if( tmp == 0 || ( tmp == 2 && retval == 1 ) ) retval = tmp; }
+ else if( tmp > retval ) retval = tmp;
-// if( delete_output_on_interrupt )
-// close_and_set_permissions( in_statsp, &retval );
if( input_filename.size() )
+ { close( infd ); infd = -1; }
+ }
+
+ if( std::fclose( stdout ) != 0 )
+ {
+ show_error( "Can't close stdout", errno );
+ switch( program_mode )
{
- close( inhandle ); inhandle = -1;
- if( !keep_input_files && !to_stdout && program_mode != m_test )
- std::remove( input_filename.c_str() );
+ case m_none: break;
+ case m_zcat: retval = 1; break;
+ case m_zgrep: if( retval != 0 || verbosity >= 0 ) retval = 2; break;
+ case m_ztest: if( retval == 0 ) retval = 1; break;
}
}
- if( outhandle >= 0 ) close( outhandle );
return retval;
}
diff --git a/testsuite/check.sh b/testsuite/check.sh
index 94e9c71..073843e 100755
--- a/testsuite/check.sh
+++ b/testsuite/check.sh
@@ -1,6 +1,6 @@
#! /bin/sh
# check script for Zutils - Utilities dealing with compressed files
-# Copyright (C) 2009 Antonio Diaz Diaz.
+# Copyright (C) 2009, 2010 Antonio Diaz Diaz.
#
# This script is free software: you have unlimited permission
# to copy, distribute and modify it.
@@ -16,11 +16,10 @@ ZGREP="${objdir}"/zgrep
ZEGREP="${objdir}"/zegrep
ZFGREP="${objdir}"/zfgrep
ZTEST="${objdir}"/ztest
-ZUTILS="${objdir}"/zutils
compressors="bzip2 gzip lzip"
extensions="bz2 gz lz"
-framework_failure() { echo 'failure in testing framework'; exit 1; }
-compressor_needed() { echo "${compressors} are needed to run tests"; exit 1; }
+framework_failure() { echo "failure in testing framework" ; exit 1 ; }
+compressor_needed() { echo "${compressors} are needed to run tests" ; exit 1 ; }
if [ ! -x "${ZCAT}" ] ; then
echo "${ZCAT}: cannot execute"
@@ -32,123 +31,181 @@ mkdir tmp
cd "${objdir}"/tmp
for i in ${compressors}; do
- cat "${testdir}"/../COPYING > in || framework_failure
+ cat "${testdir}"/test.txt > in || framework_failure
$i in || compressor_needed
done
-echo -n "testing zutils..."
-cat "${testdir}"/../COPYING > in || framework_failure
+printf "testing zutils-%s..." "$2"
+cat "${testdir}"/test.txt > in || framework_failure
cat in > -in- || framework_failure
cat in.lz > -in-.lz || framework_failure
-cat in in in in in > in5 || framework_failure
+cat in.lz > lz_only.lz || framework_failure
+cat in in in in in in > in6 || framework_failure
fail=0
+printf "\ntesting zcat-%s..." "$2"
for i in ${extensions}; do
"${ZCAT}" in.$i > copy || fail=1
cmp in copy || fail=1
- echo -n .
+ printf .
done
"${ZCAT}" < in > copy || fail=1
cmp in copy || fail=1
-echo -n .
+printf .
"${ZCAT}" < in.gz > copy || fail=1
cmp in copy || fail=1
-echo -n .
+printf .
"${ZCAT}" < in.bz2 > copy || fail=1
cmp in copy || fail=1
-echo -n .
+printf .
"${ZCAT}" < in.lz > copy || fail=1
cmp in copy || fail=1
-echo -n .
+printf .
"${ZCAT}" in > copy || fail=1
cmp in copy || fail=1
-echo -n .
-"${ZCAT}" in in.gz in.bz2 in.lz -- -in- > copy5 || fail=1
-cmp in5 copy5 || fail=1
-echo -n .
+printf .
+"${ZCAT}" lz_only > copy || fail=1
+cmp in copy || fail=1
+printf .
+"${ZCAT}" in in.gz in.bz2 in.lz -- -in- -in-.lz > copy6 || fail=1
+cmp in6 copy6 || fail=1
+printf .
+printf "\ntesting zcmp-%s..." "$2"
for i in ${extensions}; do
"${ZCMP}" in.$i || fail=1
- echo -n .
+ printf .
"${ZCMP}" in in.$i || fail=1
- echo -n .
+ printf .
"${ZCMP}" in.$i in || fail=1
- echo -n .
+ printf .
done
-
+"${ZCMP}" - || fail=1
+printf .
+"${ZCMP}" in in || fail=1
+printf .
+"${ZCMP}" in || fail=1
+printf .
+"${ZCMP}" in.lz in.gz || fail=1
+printf .
+"${ZCMP}" in.gz -- -in-.lz || fail=1
+printf .
+"${ZCMP}" -- -in-.lz in.gz || fail=1
+printf .
+"${ZCMP}" in -- -in-.lz || fail=1
+printf .
+"${ZCMP}" -- -in- in.lz || fail=1
+printf .
+"${ZCMP}" in.lz -- -in- || fail=1
+printf .
+"${ZCMP}" -- -in-.lz in || fail=1
+printf .
+"${ZCMP}" -- -in- in || fail=1
+printf .
+"${ZCMP}" in -- -in- || fail=1
+printf .
+"${ZCMP}" lz_only.lz < in || fail=1
+printf .
+"${ZCMP}" in.lz - < in || fail=1
+printf .
+"${ZCMP}" - in.lz < in || fail=1
+printf .
+"${ZCMP}" in - < in.lz || fail=1
+printf .
+"${ZCMP}" - in < in.lz || fail=1
+printf .
+
+
+printf "\ntesting zdiff-%s..." "$2"
for i in ${extensions}; do
"${ZDIFF}" in.$i || fail=1
- echo -n .
+ printf .
"${ZDIFF}" in in.$i || fail=1
- echo -n .
+ printf .
"${ZDIFF}" in.$i in || fail=1
- echo -n .
+ printf .
done
+"${ZDIFF}" - || fail=1
+printf .
+"${ZDIFF}" in in || fail=1
+printf .
"${ZDIFF}" in || fail=1
-echo -n .
+printf .
"${ZDIFF}" in.lz in.gz || fail=1
-echo -n .
+printf .
"${ZDIFF}" in.gz -- -in-.lz || fail=1
-echo -n .
+printf .
"${ZDIFF}" -- -in-.lz in.gz || fail=1
-echo -n .
+printf .
"${ZDIFF}" in -- -in-.lz || fail=1
-echo -n .
+printf .
"${ZDIFF}" -- -in- in.lz || fail=1
-echo -n .
+printf .
"${ZDIFF}" in.lz -- -in- || fail=1
-echo -n .
+printf .
"${ZDIFF}" -- -in-.lz in || fail=1
-echo -n .
+printf .
"${ZDIFF}" -- -in- in || fail=1
-echo -n .
+printf .
"${ZDIFF}" in -- -in- || fail=1
-echo -n .
-
-
+printf .
+"${ZDIFF}" lz_only.lz < in || fail=1
+printf .
+"${ZDIFF}" in.lz - < in || fail=1
+printf .
+"${ZDIFF}" - in.lz < in || fail=1
+printf .
+"${ZDIFF}" in - < in.lz || fail=1
+printf .
+"${ZDIFF}" - in < in.lz || fail=1
+printf .
+
+
+printf "\ntesting zgrep-%s..." "$2"
for i in ${extensions}; do
- "${ZGREP}" License in.$i 2>&1 > /dev/null || fail=1
- echo -n .
+ "${ZGREP}" License in.$i > /dev/null || fail=1
+ "${ZGREP}" nx_pattern in.$i > /dev/null && fail=1
+ printf .
done
-"${ZGREP}" License < in 2>&1 > /dev/null || fail=1
-echo -n .
-"${ZGREP}" License < in.gz 2>&1 > /dev/null || fail=1
-echo -n .
-"${ZGREP}" License < in.bz2 2>&1 > /dev/null || fail=1
-echo -n .
-"${ZGREP}" License < in.lz 2>&1 > /dev/null || fail=1
-echo -n .
-"${ZGREP}" License in 2>&1 > /dev/null || fail=1
-echo -n .
-"${ZGREP}" License -- -in- 2>&1 > /dev/null || fail=1
-echo -n .
-"${ZGREP}" License -- -in-.lz 2>&1 > /dev/null || fail=1
-echo -n .
-"${ZGREP}" License in in.gz in.bz2 in.lz -- -in- 2>&1 > /dev/null || fail=1
-echo -n .
-"${ZEGREP}" License in 2>&1 > /dev/null || fail=1
-echo -n .
-"${ZFGREP}" License in 2>&1 > /dev/null || fail=1
-echo -n .
-
+"${ZGREP}" -r License . > /dev/null || fail=1
+printf .
+"${ZGREP}" nx_pattern -r . in > /dev/null && fail=1
+printf .
+"${ZGREP}" License < in > /dev/null || fail=1
+printf .
+"${ZGREP}" License < in.gz > /dev/null || fail=1
+printf .
+"${ZGREP}" License < in.bz2 > /dev/null || fail=1
+printf .
+"${ZGREP}" License < in.lz > /dev/null || fail=1
+printf .
+"${ZGREP}" License in > /dev/null || fail=1
+printf .
+"${ZGREP}" License -- -in- > /dev/null || fail=1
+printf .
+"${ZGREP}" License -- -in-.lz > /dev/null || fail=1
+printf .
+"${ZGREP}" License in in.gz in.bz2 in.lz -- -in- > /dev/null || fail=1
+printf .
+"${ZEGREP}" License in > /dev/null || fail=1
+printf .
+"${ZFGREP}" License in > /dev/null || fail=1
+printf .
+
+
+printf "\ntesting ztest-%s..." "$2"
"${ZTEST}" in in.gz in.bz2 in.lz -- -in- || fail=1
-echo -n .
+printf .
"${ZTEST}" -r . || fail=1
-echo -n .
-
-if [ "bzip2" != `"${ZUTILS}" -t in.bz2` ] ; then fail=1 ; fi
-echo -n .
-if [ "gzip" != `"${ZUTILS}" -t in.gz` ] ; then fail=1 ; fi
-echo -n .
-if [ "lzip" != `"${ZUTILS}" -t in.lz` ] ; then fail=1 ; fi
-echo -n .
-
+printf .
+printf "LZIPvs0000000000000000000000" | "${ZTEST}" 2>/dev/null && fail=1
+printf .
echo
if [ ${fail} = 0 ] ; then
diff --git a/testsuite/test.txt b/testsuite/test.txt
new file mode 100644
index 0000000..5b244d5
--- /dev/null
+++ b/testsuite/test.txt
@@ -0,0 +1,676 @@
+
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+
diff --git a/zcat.cc b/zcat.cc
new file mode 100644
index 0000000..f813bbe
--- /dev/null
+++ b/zcat.cc
@@ -0,0 +1,213 @@
+/* Zcat - decompress and concatenate files to standard output
+ Copyright (C) 2010 Antonio Diaz Diaz.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+struct Cat_options
+ {
+ int number_lines; // 0 = no, 1 = nonblank, 2 = all
+ bool show_ends;
+ bool show_nonprinting;
+ bool show_tabs;
+ bool squeeze_blank;
+
+ Cat_options() throw()
+ : number_lines( 0 ), show_ends( false ), show_nonprinting( false ),
+ show_tabs( false ), squeeze_blank( false ) {}
+ };
+
+
+class Line_number // unlimited size line counter
+ {
+ std::string str;
+ int first_digit_pos;
+
+public:
+ Line_number() : str( " 0\t" ), first_digit_pos( 5 ) {}
+
+ void next()
+ {
+ for( int i = str.size() - 2; i >= first_digit_pos; --i )
+ {
+ if( str[i] < '9' ) { ++str[i]; return; }
+ str[i] = '0';
+ }
+ if( first_digit_pos > 0 ) str[--first_digit_pos] = '1';
+ else str.insert( 0, 1, '1' );
+ }
+
+ int sprint( uint8_t * const buf )
+ {
+ std::memcpy( buf, str.c_str(), str.size() );
+ return str.size();
+ }
+ };
+
+Line_number line_number;
+
+
+void show_zcat_help() throw()
+ {
+ std::printf( "Zcat copies each given file (\"-\" means standard input), to standard\n" );
+ std::printf( "output. If any given file is compressed, its uncompressed content is\n" );
+ std::printf( "used. If a given file does not exist, and its name does not end with one\n" );
+ std::printf( "of the known extensions, zcat tries the compressed file names\n" );
+ std::printf( "corresponding to the supported compressors. If no files are specified,\n" );
+ std::printf( "data is read from standard input, decompressed if needed, and sent to\n" );
+ std::printf( "standard output. Data read from standard input must be of the same type;\n" );
+ std::printf( "all uncompressed or all compressed with the same compressor.\n" );
+ std::printf( "The supported compressors are bzip2, gzip, lzip and xz.\n" );
+ std::printf( "\nUsage: zcat [options] [files]\n" );
+ std::printf( "\nExit status is 0 if no errors occurred, 1 otherwise.\n" );
+ std::printf( "\nOptions:\n" );
+ std::printf( " -h, --help display this help and exit\n" );
+ std::printf( " -V, --version output version information and exit\n" );
+ std::printf( " -A, --show-all equivalent to `-vET'\n" );
+ std::printf( " -b, --number-nonblank number nonblank output lines\n" );
+ std::printf( " -e equivalent to `-vE'\n" );
+ std::printf( " -E, --show-ends display `$' at end of each line\n" );
+ std::printf( " -n, --number number all output lines\n" );
+ std::printf( " -q, --quiet suppress all messages\n" );
+ std::printf( " -r, --recursive operate recursively on directories\n" );
+ std::printf( " -s, --squeeze-blank never more than one single blank line\n" );
+ std::printf( " -t equivalent to `-vT'\n" );
+ std::printf( " -T, --show-tabs display TAB characters as `^I'\n" );
+ std::printf( " -v, --show-nonprinting use `^' and `M-' notation, except for LF and TAB\n" );
+ std::printf( " --verbose verbose mode (show error messages)\n" );
+ show_help_addr();
+ }
+
+
+int do_cat( const int infd, const int buffer_size,
+ uint8_t * const inbuf, uint8_t * const outbuf,
+ const std::string & input_filename,
+ const Cat_options & cat_options )
+ {
+ static int at_bol = 1; // at begin of line. 0 = false, 1 = true,
+ // 2 = at begin of second blank line.
+ int inpos = 0; // positions in buffers
+ int outpos = 0;
+ int rd = -1; // bytes read by the last readblock
+ unsigned char c;
+
+ while( true )
+ {
+ do {
+ if( outpos >= buffer_size )
+ {
+ if( writeblock( STDOUT_FILENO, outbuf, outpos ) != outpos )
+ { show_error( "Write error", errno ); return 1; }
+ outpos = 0;
+ }
+ if( inpos > rd ) // inbuf is empty
+ {
+ rd = readblock( infd, inbuf, buffer_size );
+ if( rd != buffer_size && errno )
+ {
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: Error reading file `%s': %s.\n",
+ util_name, input_filename.c_str(),
+ std::strerror( errno ) );
+ return 1;
+ }
+ if( rd == 0 )
+ {
+ if( writeblock( STDOUT_FILENO, outbuf, outpos ) != outpos )
+ { show_error( "Write error", errno ); return 1; }
+ outpos = 0;
+ return 0;
+ }
+ inpos = 0;
+ inbuf[rd] = '\n'; // sentinel newline
+ }
+ else // a real newline was found
+ {
+ if( at_bol > 1 )
+ {
+ if( cat_options.squeeze_blank ) { c = inbuf[inpos++]; continue; }
+ }
+ else ++at_bol;
+ if( at_bol > 1 && cat_options.number_lines == 2 )
+ {
+ line_number.next();
+ outpos += line_number.sprint( &outbuf[outpos] );
+ }
+ if( cat_options.show_ends ) outbuf[outpos++] = '$';
+ outbuf[outpos++] = '\n'; // output the newline
+ }
+ c = inbuf[inpos++];
+ }
+ while( c == '\n' );
+
+ if( at_bol > 0 && cat_options.number_lines )
+ {
+ line_number.next();
+ outpos += line_number.sprint( &outbuf[outpos] );
+ }
+ at_bol = 0;
+
+ // the loops below continue until a newline (real or sentinel) is found
+
+ if( cat_options.show_nonprinting )
+ while( true )
+ {
+ if( c < 32 || c >= 127 )
+ {
+ if( c == '\n' ) break;
+ if( c != '\t' || cat_options.show_tabs )
+ {
+ if( c >= 128 )
+ { c -= 128; outbuf[outpos++] = 'M'; outbuf[outpos++] = '-'; }
+ if( c < 32 ) { c += 64; outbuf[outpos++] = '^'; }
+ else if( c == 127 ) { c = '?'; outbuf[outpos++] = '^'; }
+ }
+ }
+ outbuf[outpos++] = c;
+ c = inbuf[inpos++];
+ }
+ else // not quoting
+ while( c != '\n' )
+ {
+ if( c == '\t' && cat_options.show_tabs )
+ { c += 64; outbuf[outpos++] = '^'; }
+ outbuf[outpos++] = c;
+ c = inbuf[inpos++];
+ }
+ }
+ }
+
+
+int cat( int infd, const std::string & input_filename,
+ const Cat_options & cat_options )
+ {
+ enum { buffer_size = 4096 };
+ // buffer with space for sentinel newline at the end
+ uint8_t * const inbuf = new uint8_t[buffer_size+1];
+ // buffer with space for character quoting and 255-digit line number
+ uint8_t * const outbuf = new uint8_t[(4*buffer_size)+256];
+ pid_t pid = 0;
+ int retval = 0;
+ if( !set_data_feeder( &infd, &pid ) ) retval = 1;
+ else
+ {
+ retval = do_cat( infd, buffer_size, inbuf, outbuf,
+ input_filename, cat_options );
+ if( pid && wait_for_child( pid, "data feeder" ) != 0 ) retval = 1;
+ if( close( infd ) != 0 )
+ { show_error( "Can't close output of data feeder", errno ); retval = 1; }
+ }
+ delete[] inbuf; delete[] outbuf;
+ return retval;
+ }
diff --git a/zcat.in b/zcat.in
index 2284c97..d88eef1 100644
--- a/zcat.in
+++ b/zcat.in
@@ -1,115 +1,3 @@
#! /bin/sh
-# Zcat - Cat wrapper for compressed files.
-# Copyright (C) 2009 Antonio Diaz Diaz.
-#
-# This script is free software: you have unlimited permission
-# to copy, distribute and modify it.
-
-LC_ALL=C
-export LC_ALL
-args=
-gz_args=
-xz_args=
-recursive=0
-two_hyphens=0
-
-# Loop over args until a filename is found
-while [ -n "$1" ] ; do
-
- case "$1" in
- --help | --he* | -h)
- echo "Zcat - Cat wrapper for compressed files."
- echo
- echo "Zcat is a wrapper script around the cat command that allows transparent"
- echo "concatenation of any combination of compressed and non-compressed files."
- echo "If any given file is compressed, its uncompressed content is used. If a"
- echo "given file does not exist, zcat tries the compressed file names"
- echo "corresponding to the supported compressors. If no files are specified,"
- echo "data is read from standard input, decompressed if needed, and sent to"
- echo "stdout. Data read from standard input must be of the same type; all"
- echo "uncompressed or all compressed with the same compressor."
- echo "The supported compressors are bzip2, gzip, lzip and xz."
- echo
- echo "Usage: $0 [OPTIONS] [CAT_OPTIONS] [FILES]"
- echo
- echo "CAT_OPTIONS are passed directly to cat."
- echo "The exit status from cat is preserved."
- echo
- echo "Options:"
- echo " -h, --help display this help and exit"
- echo " -V, --version output version information and exit"
- echo " -r, --recursive operate recursively on directories"
- echo
- echo "Report bugs to zutils-bug@nongnu.org"
- echo "Zutils home page: http://www.nongnu.org/zutils/zutils.html"
- exit 0 ;;
- --version | --ve* | -V)
- echo "Zcat (zutils) VERSION"
- echo "Copyright (C) 2009 Antonio Diaz Diaz."
- echo "This script is free software: you have unlimited permission"
- echo "to copy, distribute and modify it."
- exit 0 ;;
- - | -c | --st* | -d | --de* | -f | --fo* | -q | --qu* | -L | --lic* )
- ;;
- -l | --lis*)
- gz_args="${gz_args} $1"; xz_args="${xz_args} $1" ;;
- -r | --re*)
- recursive=1 ;;
- --)
- shift ; two_hyphens=1 ; break ;;
- -?*)
- args="${args} $1" ;;
- *)
- break ;;
- esac
- shift
-done
-
-if [ $# = 0 ] ; then
- bindir=`echo "$0" | sed -e 's,[^/]*$,,'`
- prog_name=`"${bindir}"zutils -t`
- case "${prog_name}" in
- bzip2) prog="bzip2 -cdfq" ;;
- gzip) prog="gzip -cdfq ${gz_args}" ;;
- lzip) prog="lzip -cdfq" ;;
- xz) prog="xz -cdfq ${xz_args}" ;;
- *) prog=cat ;;
- esac
- { "${bindir}"zutils -m ${prog_name} ; cat ; } | ${prog} | cat ${args}
- exit $?
-fi
-
-retval=0
-for i in "$@" ; do
- if [ "$i" = "--" ] && [ ${two_hyphens} = 0 ] ; then two_hyphens=1
- else
- if [ ! -f "$i" ] ; then
- if [ -f "$i.gz" ] ; then i="$i.gz"
- elif [ -f "$i.bz2" ] ; then i="$i.bz2"
- elif [ -f "$i.lz" ] ; then i="$i.lz"
- elif [ -f "$i.xz" ] ; then i="$i.xz"
- elif [ ${recursive} = 1 ] && [ -d "$i" ] ; then
- find "$i" -type f -exec "$0" '{}' ';'
- continue
- else
- echo "$0: File \"$i\" not found or not a regular file" 1>&2
- if [ ${retval} = 0 ] ; then retval=1 ; fi
- continue
- fi
- fi
- bindir=`echo "$0" | sed -e 's,[^/]*$,,'`
- prog_name=`"${bindir}"zutils -t -- "$i"`
- case "${prog_name}" in
- bzip2) prog="bzip2 -cdfq" ;;
- gzip) prog="gzip -cdfq ${gz_args}" ;;
- lzip) prog="lzip -cdfq" ;;
- xz) prog="xz -cdfq ${xz_args}" ;;
- *) prog=cat ;;
- esac
- ${prog} -- "$i" | cat ${args}
- r=$?
- if [ $r != 0 ] ; then retval=$r ; fi
- fi
-done
-
-exit ${retval}
+bindir=`echo "$0" | sed -e 's,[^/]*$,,'`
+exec "${bindir}"zutils --zcat "$@"
diff --git a/zcmp.cc b/zcmp.cc
new file mode 100644
index 0000000..caa7852
--- /dev/null
+++ b/zcmp.cc
@@ -0,0 +1,502 @@
+/* Zcmp - decompress and compare two files byte by byte
+ Copyright (C) 2010 Antonio Diaz Diaz.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#define _FILE_OFFSET_BITS 64
+
+#include <cctype>
+#include <cerrno>
+#include <climits>
+#include <csignal>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <string>
+#include <vector>
+#include <fcntl.h>
+#include <stdint.h>
+#include <unistd.h>
+#include <sys/stat.h>
+#if defined(__MSVCRT__) || defined(__OS2__)
+#include <io.h>
+#endif
+
+#include "arg_parser.h"
+#include "zutils.h"
+
+#if CHAR_BIT != 8
+#error "Environments where CHAR_BIT != 8 are not supported."
+#endif
+
+#ifndef LLONG_MAX
+#define LLONG_MAX 0x7FFFFFFFFFFFFFFFLL
+#endif
+#ifndef LLONG_MIN
+#define LLONG_MIN (-LLONG_MAX - 1LL)
+#endif
+#ifndef ULLONG_MAX
+#define ULLONG_MAX 0xFFFFFFFFFFFFFFFFULL
+#endif
+
+
+namespace {
+
+#ifdef O_BINARY
+const int o_binary = O_BINARY;
+#else
+const int o_binary = 0;
+#endif
+
+struct { const char * from; const char * to; } const known_extensions[] = {
+ { ".bz2", "" },
+ { ".tbz", ".tar" },
+ { ".tbz2", ".tar" },
+ { ".gz", "" },
+ { ".tgz", ".tar" },
+ { ".lz", "" },
+ { ".tlz", ".tar" },
+ { ".xz", "" },
+ { ".txz", ".tar" },
+ { 0, 0 } };
+
+
+void show_help() throw()
+ {
+ std::printf( "Zcmp compares two files (\"-\" means standard input), and if they\n" );
+ std::printf( "differ, tells the first byte and line number where they differ. Bytes\n" );
+ std::printf( "and lines are numbered starting with 1. If any given file is compressed,\n" );
+ std::printf( "its uncompressed content is used. Compressed files are uncompressed on\n" );
+ std::printf( "the fly; no temporary files are created.\n" );
+ std::printf( "The supported compressors are bzip2, gzip, lzip and xz.\n" );
+ std::printf( "\nUsage: zcmp [options] file1 [file2]\n" );
+ std::printf( "\nCompares <file1> to <file2>. If <file2> is omitted zcmp tries the\n" );
+ std::printf( "following:\n" );
+ std::printf( "If <file1> is compressed, compares <file1> to the file with the\n" );
+ std::printf( "corresponding decompressed file name (removes the extension from\n" );
+ std::printf( "<file1>).\n" );
+ std::printf( "If <file1> is not compressed, compares <file1> to the uncompressed\n" );
+ std::printf( "contents of <file1>.[bz2|gz|lz|xz] (the first one that is found).\n" );
+ std::printf( "If no suitable file is found, compares <file1> to data read from\n" );
+ std::printf( "standard input.\n" );
+ std::printf( "\nExit status is 0 if inputs are identical, 1 if different, 2 if trouble.\n" );
+ std::printf( "\nOptions:\n" );
+ std::printf( " -h, --help display this help and exit\n" );
+ std::printf( " -V, --version output version information and exit\n" );
+ std::printf( " -b, --print-bytes print differing bytes\n" );
+ std::printf( " -i, --ignore-initial=<n>[,<n2>] ignore differences in the first <n> bytes\n" );
+ std::printf( " -l, --list list position, value of all differing bytes\n" );
+ std::printf( " -n, --bytes=<n> compare at most <n> bytes\n" );
+ std::printf( " -q, --quiet suppress all messages\n" );
+ std::printf( " -s, --silent (same as --quiet)\n" );
+ std::printf( " -v, --verbose verbose mode (same as --list)\n" );
+ std::printf( "Numbers may be followed by a multiplier: k = kB = 10^3 = 1000,\n" );
+ std::printf( "Ki = KiB = 2^10 = 1024, M = 10^6, Mi = 2^20, G = 10^9, Gi = 2^30, etc...\n" );
+ show_help_addr();
+ }
+
+
+long long getnum( const char * const ptr, const char ** const tailp = 0,
+ const long long llimit = LLONG_MIN + 1,
+ const long long ulimit = LLONG_MAX ) throw()
+ {
+ errno = 0;
+ char * tail;
+ long long result = strtoll( ptr, &tail, 0 );
+ if( tail == ptr )
+ {
+ show_error( "Bad or missing numerical argument.", 0, true );
+ std::exit( 2 );
+ }
+
+ if( !errno && tail[0] && std::isalpha( tail[0] ) )
+ {
+ int factor = ( tail[1] == 'i' ) ? 1024 : 1000;
+ int exponent = 0;
+ bool bad_multiplier = false;
+ switch( tail[0] )
+ {
+ case 'Y': exponent = 8; break;
+ case 'Z': exponent = 7; break;
+ case 'E': exponent = 6; break;
+ case 'P': exponent = 5; break;
+ case 'T': exponent = 4; break;
+ case 'G': exponent = 3; break;
+ case 'M': exponent = 2; break;
+ case 'K': if( factor == 1024 ) exponent = 1; else bad_multiplier = true;
+ break;
+ case 'k': if( factor == 1000 ) exponent = 1; else bad_multiplier = true;
+ break;
+ default : bad_multiplier = true;
+ }
+ if( bad_multiplier )
+ {
+ show_error( "Bad multiplier in numerical argument.", 0, true );
+ std::exit( 2 );
+ }
+ for( int i = 0; i < exponent; ++i )
+ {
+ if( LLONG_MAX / factor >= llabs( result ) ) result *= factor;
+ else { errno = ERANGE; break; }
+ }
+ }
+ if( !errno && ( result < llimit || result > ulimit ) ) errno = ERANGE;
+ if( errno )
+ {
+ show_error( "Numerical argument out of limits." );
+ std::exit( 2 );
+ }
+ if( tailp ) *tailp = tail;
+ return result;
+ }
+
+
+int open_instream( const std::string & input_filename ) throw()
+ {
+ int infd = open( input_filename.c_str(), O_RDONLY | o_binary );
+ if( infd < 0 && verbosity >= 0 )
+ std::fprintf( stderr, "%s: Can't open input file `%s': %s.\n",
+ util_name, input_filename.c_str(), std::strerror( errno ) );
+ return infd;
+ }
+
+
+int open_other_instream( std::string & name ) throw()
+ {
+ for( int i = 0; known_extensions[i].from; ++i )
+ { // search uncompressed version
+ const std::string from( known_extensions[i].from );
+ if( name.size() > from.size() &&
+ name.compare( name.size() - from.size(), from.size(), from ) == 0 )
+ {
+ name.resize( name.size() - from.size() );
+ name += known_extensions[i].to;
+ return open( name.c_str(), O_RDONLY | o_binary );
+ }
+ }
+ for( int i = 0; simple_extensions[i]; ++i )
+ { // search compressed version
+ const std::string s( name + simple_extensions[i] );
+ const int infd = open( s.c_str(), O_RDONLY | o_binary );
+ if( infd >= 0 ) { name = s; return infd; }
+ }
+ return -1;
+ }
+
+
+bool check_identical( const char * const name1, const char * const name2 ) throw()
+ {
+ if( !std::strcmp( name1, name2 ) ) return true;
+ struct stat stat1, stat2;
+ if( stat( name1, &stat1 ) || stat( name2, &stat2 ) ) return false;
+ return ( stat1.st_ino == stat2.st_ino && stat1.st_dev == stat2.st_dev );
+ }
+
+
+void parse_ignore_initial( const char * const arg, long long ignore_initial[2] )
+ {
+ const char * tail;
+ ignore_initial[0] = getnum( arg, &tail, 0 );
+ if( *tail == ',' || *tail == ':' )
+ ignore_initial[1] = getnum( ++tail, 0, 0 );
+ else ignore_initial[1] = ignore_initial[0];
+ }
+
+
+bool skip_ignore_initial( const long long ignore_initial, const int infd )
+ {
+ if( ignore_initial > 0 )
+ {
+ enum { buffer_size = 4096 };
+ long long rest = ignore_initial;
+ uint8_t buffer[buffer_size];
+ while( rest > 0 )
+ {
+ const int size = std::min( rest, (long long)buffer_size );
+ const int rd = readblock( infd, buffer, size );
+ if( rd != size && errno ) return false;
+ if( rd < size ) break;
+ rest -= rd;
+ }
+ }
+ return true;
+ }
+
+
+// Put into buf the unsigned char c, making unprintable bytes
+// visible by quoting like cat -t does.
+void sprintc( char * const buf, unsigned char c )
+ {
+ int i = 0;
+
+ if( c < 32 || c >= 127 )
+ {
+ if( c >= 128 ) { c -= 128; buf[i++] = 'M'; buf[i++] = '-'; }
+ if( c < 32 ) { c += 64; buf[i++] = '^'; }
+ else if( c == 127 ) { c = '?'; buf[i++] = '^'; }
+ }
+ buf[i++] = c;
+ buf[i++] = 0;
+ }
+
+
+int block_compare( const uint8_t * const buffer0,
+ const uint8_t * const buffer1,
+ long long * line_numberp )
+ {
+ const uint8_t * p0 = buffer0;
+ const uint8_t * p1 = buffer1;
+ if( verbosity == 0 )
+ {
+ int nl_count = 0;
+ while( *p0 == *p1 )
+ { if( *p0 == '\n' ) { ++nl_count; } ++p0; ++p1; }
+ *line_numberp += nl_count;
+ }
+ else while( *p0 == *p1 ) { ++p0; ++p1; }
+ return p0 - buffer0;
+ }
+
+
+int cmp( const long long max_size, const int infd[2],
+ const std::string filenames[2], const bool print_bytes )
+ {
+ enum { buffer_size = 4096 };
+ long long byte_number = 1;
+ long long line_number = 1;
+ long long rest = max_size; // remaining number of bytes to compare
+ // buffers with space for sentinels at the end
+ uint8_t * const buffer0 = new uint8_t[2*(buffer_size+1)];
+ uint8_t * const buffer1 = buffer0 + buffer_size + 1;
+ uint8_t * buffer[2];
+ buffer[0] = buffer0; buffer[1] = buffer1;
+ int different = 0;
+
+ while( rest > 0 )
+ {
+ const int size = std::min( rest, (long long)buffer_size );
+ int rd[2]; // number of bytes read from each file
+ for( int i = 0; i < 2; ++i )
+ {
+ rd[i] = readblock( infd[i], buffer[i], size );
+ if( rd[i] != size && errno )
+ {
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: Error reading file `%s': %s.\n",
+ util_name, filenames[i].c_str(), std::strerror( errno ) );
+ return 2;
+ }
+ }
+ rest -= size;
+
+ buffer0[rd[0]] = ~buffer1[rd[0]]; // sentinels for the block compare
+ buffer1[rd[1]] = ~buffer0[rd[1]];
+
+ int first_diff = block_compare( buffer0, buffer1, &line_number );
+ byte_number += first_diff;
+ const int min_rd = std::min( rd[0], rd[1] );
+
+ if( first_diff < min_rd )
+ {
+ if( verbosity < 0 ) return 1; // return status only
+ if( verbosity == 0 ) // show first difference
+ {
+ if( !print_bytes )
+ std::printf( "%s %s differ: byte %lld, line %lld\n",
+ filenames[0].c_str(), filenames[1].c_str(),
+ byte_number, line_number );
+ else
+ {
+ const unsigned char c0 = buffer0[first_diff];
+ const unsigned char c1 = buffer1[first_diff];
+ char buf0[5], buf1[5];
+ sprintc( buf0, c0 ); sprintc( buf1, c1 );
+ std::printf( "%s %s differ: byte %lld, line %lld is %3o %s %3o %s\n",
+ filenames[0].c_str(), filenames[1].c_str(),
+ byte_number, line_number, c0, buf0, c1, buf1 );
+ }
+ return 1;
+ }
+ else // verbosity > 0 ; show all differences
+ {
+ different = 1;
+ for( ; first_diff < min_rd; ++byte_number, ++first_diff )
+ {
+ const unsigned char c0 = buffer0[first_diff];
+ const unsigned char c1 = buffer1[first_diff];
+ if( c0 != c1 )
+ {
+ if( !print_bytes )
+ std::printf( "%lld %3o %3o\n", byte_number, c0, c1 );
+ else
+ {
+ char buf0[5], buf1[5];
+ sprintc( buf0, c0 ); sprintc( buf1, c1 );
+ std::printf( "%lld %3o %-4s %3o %s\n",
+ byte_number, c0, buf0, c1, buf1 );
+ }
+ }
+ }
+ }
+ }
+
+ if( rd[0] != rd[1] )
+ {
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: EOF on %s\n",
+ util_name, filenames[rd[1]<rd[0]].c_str() );
+ return 1;
+ }
+ if( min_rd != buffer_size ) break;
+ }
+
+ delete[] buffer0;
+ return different;
+ }
+
+} // end namespace
+
+
+int main( const int argc, const char * const argv[] )
+ {
+ // number of initial bytes ignored for each file
+ long long ignore_initial[2] = { 0, 0 };
+ long long max_size = LLONG_MAX;
+ bool print_bytes = false;
+ invocation_name = argv[0];
+ util_name = "zcmp";
+
+ const Arg_parser::Option options[] =
+ {
+ { 'b', "print-bytes", Arg_parser::no },
+ { 'h', "help", Arg_parser::no },
+ { 'i', "ignore-initial", Arg_parser::yes },
+ { 'l', "list", Arg_parser::no },
+ { 'n', "bytes", Arg_parser::yes },
+ { 'q', "quiet", Arg_parser::no },
+ { 's', "silent", Arg_parser::no },
+ { 'v', "verbose", Arg_parser::no },
+ { 'V', "version", Arg_parser::no },
+ { 0 , 0, Arg_parser::no } };
+
+ const Arg_parser parser( argc, argv, options );
+ if( parser.error().size() ) // bad option
+ { show_error( parser.error().c_str(), 0, true ); return 2; }
+
+ int argind = 0;
+ for( ; argind < parser.arguments(); ++argind )
+ {
+ const int code = parser.code( argind );
+ if( !code ) break; // no more options
+ const char * const arg = parser.argument( argind ).c_str();
+ switch( code )
+ {
+ case 'b': print_bytes = true; break;
+ case 'h': show_help(); return 0;
+ case 'i': parse_ignore_initial( arg, ignore_initial ); break;
+ case 'l': verbosity = 1; break;
+ case 'n': max_size = getnum( arg, 0, 0 ); break;
+ case 'q':
+ case 's': verbosity = -1; break;
+ case 'v': verbosity = 1; break;
+ case 'V': show_version( "Zcmp" ); return 0;
+ default : internal_error( "uncaught option" );
+ }
+ } // end process options
+
+#if defined(__MSVCRT__) || defined(__OS2__)
+ _setmode( STDIN_FILENO, O_BINARY );
+ _setmode( STDOUT_FILENO, O_BINARY );
+#endif
+
+ if( argind >= parser.arguments() )
+ { show_error( "No files given.", 0, true ); return 2; }
+ if( argind + 2 < parser.arguments() )
+ { show_error( "Too many files.", 0, true ); return 2; }
+
+ const int files = parser.arguments() - argind;
+ std::string filenames[2]; // file names of the two input files
+ filenames[0] = parser.argument( argind );
+ if( files == 2 ) filenames[1] = parser.argument( argind + 1 );
+
+ int infd[2]; // file descriptors of the two files
+ infd[0] = ( filenames[0] == "-" ) ?
+ STDIN_FILENO : open_instream( filenames[0] );
+ if( infd[0] < 0 ) return 2;
+
+ if( ( files == 1 && filenames[0] == "-" ) ||
+ ( files == 2 && check_identical( filenames[0].c_str(),
+ filenames[1].c_str() ) ) )
+ {
+ if( ignore_initial[0] == ignore_initial[1] ) return 0;
+ else { show_error( "Can't compare parts of same file." ); return 2; }
+ }
+
+ if( files == 2 )
+ {
+ infd[1] = ( filenames[1] == "-" ) ?
+ STDIN_FILENO : open_instream( filenames[1] );
+ if( infd[1] < 0 ) return 2;
+ }
+ else
+ {
+ filenames[1] = filenames[0];
+ infd[1] = open_other_instream( filenames[1] );
+ if( infd[1] < 0 ) { infd[1] = STDIN_FILENO; filenames[1] = "-"; }
+ }
+
+ int old_infd[2]; // copy of file descriptors of the two files
+ old_infd[0] = infd[0]; old_infd[1] = infd[1];
+ pid_t pid[2];
+ if( !set_data_feeder( &infd[0], &pid[0] ) ||
+ !set_data_feeder( &infd[1], &pid[1] ) )
+ return 2;
+
+ for( int i = 0; i < 2; ++i )
+ if( !skip_ignore_initial( ignore_initial[i], infd[i] ) )
+ {
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: Can't skip initial bytes from file `%s': %s.\n",
+ util_name, filenames[i].c_str(), std::strerror( errno ) );
+ return 2;
+ }
+
+ int retval = cmp( max_size, infd, filenames, print_bytes );
+
+ if( ( ( pid[0] && wait_for_child( pid[0], "data feeder" ) != 0 ) ||
+ ( pid[1] && wait_for_child( pid[1], "data feeder" ) != 0 ) ) &&
+ retval == 0 )
+ retval = 2;
+
+ for( int i = 0; i < 2; ++i )
+ {
+ if( close( infd[i] ) != 0 )
+ { show_error( "Can't close output of data feeder", errno ); retval = 2; }
+ if( filenames[i] != "-" && close( old_infd[i] ) != 0 )
+ {
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: Can't close input file `%s': %s.\n",
+ util_name, filenames[i].c_str(), std::strerror( errno ) );
+ retval = 2;
+ }
+ }
+ if( std::fclose( stdout ) != 0 )
+ {
+ show_error( "Can't close stdout", errno );
+ retval = 2;
+ }
+
+ return retval;
+ }
diff --git a/zcmp.in b/zcmp.in
deleted file mode 100644
index d2ad056..0000000
--- a/zcmp.in
+++ /dev/null
@@ -1,3 +0,0 @@
-#! /bin/sh
-bindir=`echo "$0" | sed -e 's,[^/]*$,,'`
-exec "${bindir}"zdiff --cmp "$@"
diff --git a/zdiff.cc b/zdiff.cc
new file mode 100644
index 0000000..d01f492
--- /dev/null
+++ b/zdiff.cc
@@ -0,0 +1,476 @@
+/* Zdiff - decompress and compare two files line by line
+ Copyright (C) 2010 Antonio Diaz Diaz.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#define _FILE_OFFSET_BITS 64
+
+#include <cctype>
+#include <cerrno>
+#include <climits>
+#include <csignal>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <string>
+#include <vector>
+#include <fcntl.h>
+#include <stdint.h>
+#include <unistd.h>
+#include <sys/stat.h>
+#if defined(__MSVCRT__) || defined(__OS2__)
+#include <io.h>
+#endif
+
+#include "arg_parser.h"
+#include "zutils.h"
+
+#if CHAR_BIT != 8
+#error "Environments where CHAR_BIT != 8 are not supported."
+#endif
+
+#ifndef LLONG_MAX
+#define LLONG_MAX 0x7FFFFFFFFFFFFFFFLL
+#endif
+#ifndef LLONG_MIN
+#define LLONG_MIN (-LLONG_MAX - 1LL)
+#endif
+#ifndef ULLONG_MAX
+#define ULLONG_MAX 0xFFFFFFFFFFFFFFFFULL
+#endif
+
+
+namespace {
+
+std::string fifonames[2]; // names of the two fifos passed to diff
+
+#ifdef O_BINARY
+const int o_binary = O_BINARY;
+#else
+const int o_binary = 0;
+#endif
+
+struct { const char * from; const char * to; } const known_extensions[] = {
+ { ".bz2", "" },
+ { ".tbz", ".tar" },
+ { ".tbz2", ".tar" },
+ { ".gz", "" },
+ { ".tgz", ".tar" },
+ { ".lz", "" },
+ { ".tlz", ".tar" },
+ { ".xz", "" },
+ { ".txz", ".tar" },
+ { 0, 0 } };
+
+
+void show_help() throw()
+ {
+ std::printf( "Zdiff compares two files (\"-\" means standard input), and if they\n" );
+ std::printf( "differ, shows the differences line by line. If any given file is\n" );
+ std::printf( "compressed, its uncompressed content is used. Zdiff is a front end to\n" );
+ std::printf( "the diff program and has the limitation that messages from diff refer to\n" );
+ std::printf( "temporary filenames instead of those specified.\n" );
+ std::printf( "The supported compressors are bzip2, gzip, lzip and xz.\n" );
+ std::printf( "\nUsage: zdiff [options] file1 [file2]\n" );
+ std::printf( "\nCompares <file1> to <file2>. If <file2> is omitted zdiff tries the\n" );
+ std::printf( "following:\n" );
+ std::printf( "If <file1> is compressed, compares <file1> to the file with the\n" );
+ std::printf( "corresponding decompressed file name (removes the extension from\n" );
+ std::printf( "<file1>).\n" );
+ std::printf( "If <file1> is not compressed, compares <file1> to the uncompressed\n" );
+ std::printf( "contents of <file1>.[bz2|gz|lz|xz] (the first one that is found).\n" );
+ std::printf( "If no suitable file is found, compares <file1> to data read from\n" );
+ std::printf( "standard input.\n" );
+ std::printf( "\nExit status is 0 if inputs are identical, 1 if different, 2 if trouble.\n" );
+ std::printf( "\nOptions:\n" );
+ std::printf( " -h, --help display this help and exit\n" );
+ std::printf( " -V, --version output version information and exit\n" );
+ std::printf( " -a, --text treat all files as text\n" );
+ std::printf( " -b, --ignore-space-change ignore changes in the amount of white space\n" );
+ std::printf( " -B, --ignore-blank-lines ignore changes whose lines are all blank\n" );
+ std::printf( " -c use the context output format\n" );
+ std::printf( " -C, --context=<n> same as -c but use <n> lines of context\n" );
+ std::printf( " -d, --minimal try hard to find a smaller set of changes\n" );
+ std::printf( " -E, --ignore-tab-expansion ignore changes due to tab expansion\n" );
+ std::printf( " -i, --ignore-case ignore case differences in file contents\n" );
+ std::printf( " -p, --show-c-function show which C function each change is in\n" );
+ std::printf( " -q, --brief output only whether files differ\n" );
+ std::printf( " -s, --report-identical-files report when two files are identical\n" );
+ std::printf( " -t, --expand-tabs expand tabs to spaces in output\n" );
+ std::printf( " -T, --initial-tab make tabs line up by prepending a tab\n" );
+ std::printf( " -u use the unified output format\n" );
+ std::printf( " -U, --unified=<n> same as -u but use <n> lines of context\n" );
+ std::printf( " -w, --ignore-all-space ignore all white space\n" );
+ std::printf( "Numbers may be followed by a multiplier: k = kB = 10^3 = 1000,\n" );
+ std::printf( "Ki = KiB = 2^10 = 1024, M = 10^6, Mi = 2^20, G = 10^9, Gi = 2^30, etc...\n" );
+ show_help_addr();
+ }
+
+
+int open_instream( const std::string & input_filename ) throw()
+ {
+ int infd = open( input_filename.c_str(), O_RDONLY | o_binary );
+ if( infd < 0 && verbosity >= 0 )
+ std::fprintf( stderr, "%s: Can't open input file `%s': %s.\n",
+ util_name, input_filename.c_str(), std::strerror( errno ) );
+ return infd;
+ }
+
+
+int open_other_instream( std::string & name ) throw()
+ {
+ for( int i = 0; known_extensions[i].from; ++i )
+ { // search uncompressed version
+ const std::string from( known_extensions[i].from );
+ if( name.size() > from.size() &&
+ name.compare( name.size() - from.size(), from.size(), from ) == 0 )
+ {
+ name.resize( name.size() - from.size() );
+ name += known_extensions[i].to;
+ return open( name.c_str(), O_RDONLY | o_binary );
+ }
+ }
+ for( int i = 0; simple_extensions[i]; ++i )
+ { // search compressed version
+ const std::string s( name + simple_extensions[i] );
+ const int infd = open( s.c_str(), O_RDONLY | o_binary );
+ if( infd >= 0 ) { name = s; return infd; }
+ }
+ return -1;
+ }
+
+
+bool check_identical( const char * const name1, const char * const name2 ) throw()
+ {
+ if( !std::strcmp( name1, name2 ) ) return true;
+ struct stat stat1, stat2;
+ if( stat( name1, &stat1 ) || stat( name2, &stat2 ) ) return false;
+ return ( stat1.st_ino == stat2.st_ino && stat1.st_dev == stat2.st_dev );
+ }
+
+
+const char * my_basename( const char * filename ) throw()
+ {
+ const char * c = filename;
+ while( *c ) { if( *c == '/' ) { filename = c + 1; } ++c; }
+ return filename;
+ }
+
+
+void remove_fifos() throw()
+ {
+ if( fifonames[0].size() )
+ { std::remove( fifonames[0].c_str() ); fifonames[0].clear(); }
+ if( fifonames[1].size() )
+ { std::remove( fifonames[1].c_str() ); fifonames[1].clear(); }
+ }
+
+
+// Set fifonames[i] to "${TMPDIR}/<coded_pid><i>_<basename(filenames[i])>"
+// and create FIFOs.
+bool set_fifonames( const std::string filenames[2] )
+ {
+ enum { num_codes = 36 };
+ const char * const codes = "0123456789abcdefghijklmnopqrstuvwxyz";
+ const char * p = std::getenv( "TMPDIR" );
+ const int pid = getpid();
+
+ for( int i = 0; i < 2; ++i )
+ {
+ if( p ) fifonames[i] = p; else fifonames[i] = "/tmp";
+ fifonames[i] += '/';
+ int n = ( 2 * pid ) + i;
+ const unsigned int pos = fifonames[i].size();
+ do { fifonames[i].insert( pos, 1, codes[n % num_codes] );
+ n /= num_codes; }
+ while( n );
+ fifonames[i] += '_';
+ fifonames[i] += my_basename( filenames[i].c_str() );
+ }
+
+ for( int i = 0; i < 2; ++i )
+ if( mkfifo( fifonames[i].c_str(), S_IRUSR | S_IWUSR ) != 0 )
+ {
+ if( errno == EEXIST )
+ {
+ std::remove( fifonames[i].c_str() );
+ if( mkfifo( fifonames[i].c_str(), S_IRUSR | S_IWUSR ) == 0 )
+ continue;
+ }
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: Can't create FIFO `%s': %s.\n",
+ util_name, fifonames[i].c_str(), std::strerror( errno ) );
+ return false;
+ }
+ return true;
+ }
+
+
+bool set_data_feeder( const std::string & fifoname, const int infd,
+ pid_t * const pidp )
+ {
+ std::string file_type;
+ const uint8_t * magic_data;
+ int magic_size;
+ const bool compressed =
+ test_format( infd, file_type, &magic_data, &magic_size );
+
+ if( compressed ) // compressed with `file_type'
+ {
+ int fda[2]; // pipe from feeder to decompressor
+ if( pipe( fda ) < 0 )
+ { show_error( "Can't create pipe", errno ); return false; }
+ const pid_t pid = fork();
+ if( pid == 0 ) // child (decompressor feeder)
+ {
+ const pid_t pid2 = fork();
+ if( pid2 == 0 ) // grandchild (decompressor)
+ {
+ const int outfd = open( fifoname.c_str(), O_WRONLY | o_binary );
+ if( outfd < 0 )
+ {
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: Can't open FIFO `%s' for writing: %s.\n",
+ util_name, fifoname.c_str(), std::strerror( errno ) );
+ _exit( 2 );
+ }
+ if( dup2( fda[0], STDIN_FILENO ) >= 0 &&
+ dup2( outfd, STDOUT_FILENO ) >= 0 &&
+ close( fda[0] ) == 0 && close( fda[1] ) == 0 &&
+ close( outfd ) == 0 )
+ execlp( file_type.c_str(), file_type.c_str(), "-cdfq", (char *)0 );
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: Can't exec `%s': %s.\n",
+ util_name, file_type.c_str(), std::strerror( errno ) );
+ _exit( 2 );
+ }
+ if( pid2 < 0 )
+ {
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: Can't fork `%s': %s.\n",
+ util_name, file_type.c_str(), std::strerror( errno ) );
+ _exit( 2 );
+ }
+
+ if( close( fda[0] ) != 0 ||
+ !feed_data( infd, fda[1], magic_data, magic_size ) )
+ _exit( 2 );
+ if( close( fda[1] ) != 0 )
+ { show_error( "Can't close output of feeder", errno ); _exit( 2 ); }
+ _exit( wait_for_child( pid2, file_type.c_str() ) );
+ }
+ // parent
+ close( fda[0] ); close( fda[1] );
+ if( pid < 0 )
+ { show_error( "Can't fork decompressor feeder", errno ); return false; }
+ *pidp = pid;
+ }
+ else // not compressed
+ {
+ const pid_t pid = fork();
+ if( pid == 0 ) // child (feeder)
+ {
+ const int outfd = open( fifoname.c_str(), O_WRONLY | o_binary );
+ if( outfd < 0 )
+ {
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: Can't open FIFO `%s' for writing: %s.\n",
+ util_name, fifoname.c_str(), std::strerror( errno ) );
+ _exit( 2 );
+ }
+ if( !feed_data( infd, outfd, magic_data, magic_size ) )
+ _exit( 2 );
+ if( close( outfd ) != 0 )
+ { show_error( "Can't close output of feeder", errno ); _exit( 2 ); }
+ _exit( 0 );
+ }
+ // parent
+ if( pid < 0 )
+ { show_error( "Can't fork data feeder", errno ); return false; }
+ *pidp = pid;
+ }
+ return true;
+ }
+
+
+extern "C" void signal_handler( int sig ) throw()
+ {
+ remove_fifos();
+ std::signal( sig, SIG_DFL );
+ std::raise( sig );
+ }
+
+
+void set_signals() throw()
+ {
+ std::signal( SIGHUP, signal_handler );
+ std::signal( SIGINT, signal_handler );
+ std::signal( SIGTERM, signal_handler );
+ }
+
+} // end namespace
+
+
+int main( const int argc, const char * const argv[] )
+ {
+ std::vector< const char * > diff_args; // args to diff, maybe empty
+ invocation_name = argv[0];
+ util_name = "zdiff";
+
+ const Arg_parser::Option options[] =
+ {
+ { 'a', "text", Arg_parser::no },
+ { 'b', "ignore-space-change", Arg_parser::no },
+ { 'B', "ignore-blank-lines", Arg_parser::no },
+ { 'c', 0, Arg_parser::no },
+ { 'C', "context", Arg_parser::yes },
+ { 'd', "minimal", Arg_parser::no },
+ { 'E', "ignore-tab-expansion", Arg_parser::no },
+ { 'h', "help", Arg_parser::no },
+ { 'i', "ignore-case", Arg_parser::no },
+ { 'p', "show-c-function", Arg_parser::no },
+ { 'q', "brief", Arg_parser::no },
+ { 's', "report-identical-files", Arg_parser::no },
+ { 't', "expand-tabs", Arg_parser::no },
+ { 'T', "initial-tab", Arg_parser::no },
+ { 'u', 0, Arg_parser::no },
+ { 'U', "unified", Arg_parser::yes },
+ { 'V', "version", Arg_parser::no },
+ { 'w', "ignore-all-space", Arg_parser::no },
+ { 0 , 0, Arg_parser::no } };
+
+ const Arg_parser parser( argc, argv, options );
+ if( parser.error().size() ) // bad option
+ { show_error( parser.error().c_str(), 0, true ); return 2; }
+
+ int argind = 0;
+ for( ; argind < parser.arguments(); ++argind )
+ {
+ const int code = parser.code( argind );
+ if( !code ) break; // no more options
+ const char * const arg = parser.argument( argind ).c_str();
+ switch( code )
+ {
+ case 'a': diff_args.push_back( "-a" ); break;
+ case 'b': diff_args.push_back( "-b" ); break;
+ case 'B': diff_args.push_back( "-B" ); break;
+ case 'c': diff_args.push_back( "-c" ); break;
+ case 'C': diff_args.push_back( "-C" ); diff_args.push_back( arg ); break;
+ case 'd': diff_args.push_back( "-d" ); break;
+ case 'E': diff_args.push_back( "-E" ); break;
+ case 'h': show_help(); return 0;
+ case 'i': diff_args.push_back( "-i" ); break;
+ case 'p': diff_args.push_back( "-p" ); break;
+ case 'q': diff_args.push_back( "-q" ); break;
+ case 's': diff_args.push_back( "-s" ); break;
+ case 't': diff_args.push_back( "-t" ); break;
+ case 'T': diff_args.push_back( "-T" ); break;
+ case 'u': diff_args.push_back( "-u" ); break;
+ case 'U': diff_args.push_back( "-U" ); diff_args.push_back( arg ); break;
+ case 'V': show_version( "Zdiff" ); return 0;
+ case 'w': diff_args.push_back( "-w" ); break;
+ default : internal_error( "uncaught option" );
+ }
+ } // end process options
+
+#if defined(__MSVCRT__) || defined(__OS2__)
+ _setmode( STDIN_FILENO, O_BINARY );
+ _setmode( STDOUT_FILENO, O_BINARY );
+#endif
+
+ if( argind >= parser.arguments() )
+ { show_error( "No files given.", 0, true ); return 2; }
+ if( argind + 2 < parser.arguments() )
+ { show_error( "Too many files.", 0, true ); return 2; }
+
+ const int files = parser.arguments() - argind;
+ std::string filenames[2]; // file names of the two input files
+ filenames[0] = parser.argument( argind );
+ if( files == 2 ) filenames[1] = parser.argument( argind + 1 );
+
+ int infd[2]; // file descriptors of the two files
+ infd[0] = ( filenames[0] == "-" ) ?
+ STDIN_FILENO : open_instream( filenames[0] );
+ if( infd[0] < 0 ) return 2;
+
+ if( ( files == 1 && filenames[0] == "-" ) ||
+ ( files == 2 && check_identical( filenames[0].c_str(),
+ filenames[1].c_str() ) ) )
+ return 0;
+
+ if( files == 2 )
+ {
+ infd[1] = ( filenames[1] == "-" ) ?
+ STDIN_FILENO : open_instream( filenames[1] );
+ if( infd[1] < 0 ) return 2;
+ }
+ else
+ {
+ filenames[1] = filenames[0];
+ infd[1] = open_other_instream( filenames[1] );
+ if( infd[1] < 0 ) { infd[1] = STDIN_FILENO; filenames[1] = "-"; }
+ }
+
+ std::atexit( remove_fifos );
+ set_signals();
+ if( !set_fifonames( filenames ) ) return 2;
+
+ const pid_t diff_pid = fork();
+ if( diff_pid == 0 ) // child (diff)
+ {
+ const char ** const argv = new const char *[diff_args.size()+5];
+ argv[0] = "diff";
+ for( unsigned int i = 0; i < diff_args.size(); ++i )
+ argv[i+1] = diff_args[i];
+ argv[diff_args.size()+1] = "--";
+ argv[diff_args.size()+2] = fifonames[0].c_str();
+ argv[diff_args.size()+3] = fifonames[1].c_str();
+ argv[diff_args.size()+4] = 0;
+ execvp( argv[0], (char **)argv );
+ show_error( "Can't exec `diff'." );
+ _exit( 2 );
+ }
+ // parent
+ if( diff_pid < 0 )
+ { show_error( "Can't fork `diff'", errno ); return 2; }
+
+ pid_t pid[2];
+ if( !set_data_feeder( fifonames[0], infd[0], &pid[0] ) ||
+ !set_data_feeder( fifonames[1], infd[1], &pid[1] ) )
+ return 2;
+
+ int retval = wait_for_child( diff_pid, "diff" );
+
+ if( retval != 0 )
+ {
+ if( pid[0] ) kill( pid[0], SIGTERM );
+ if( pid[1] ) kill( pid[1], SIGTERM );
+ }
+ else
+ if( ( pid[0] && wait_for_child( pid[0], "data feeder" ) != 0 ) ||
+ ( pid[1] && wait_for_child( pid[1], "data feeder" ) != 0 ) )
+ retval = 2;
+
+ for( int i = 0; i < 2; ++i )
+ if( filenames[i] != "-" && close( infd[i] ) != 0 )
+ {
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: Can't close input file `%s': %s.\n",
+ util_name, filenames[i].c_str(), std::strerror( errno ) );
+ retval = 2;
+ }
+
+ return retval;
+ }
diff --git a/zdiff.in b/zdiff.in
deleted file mode 100644
index dde93ba..0000000
--- a/zdiff.in
+++ /dev/null
@@ -1,160 +0,0 @@
-#! /bin/sh
-# Zdiff - Diff/cmp wrapper for compressed files.
-# Copyright (C) 2008, 2009 Antonio Diaz Diaz.
-#
-# This script is free software: you have unlimited permission
-# to copy, distribute and modify it.
-
-LC_ALL=C
-export LC_ALL
-args=
-diff_prog=diff
-file1=
-file2=
-two_hyphens=0
-
-# Loop over args
-while [ -n "$1" ] ; do
-
- case "$1" in
- --help | --he* | -h)
- echo "Zdiff - Diff/cmp wrapper for compressed files."
- echo
- echo "Zdiff is a wrapper script around the diff and cmp commands that allows"
- echo "transparent comparison of any combination of compressed and"
- echo "non-compressed files. If any given file is compressed, its uncompressed"
- echo "content is used. The supported compressors are bzip2, gzip, lzip and xz."
- echo
- echo "Zcmp is a shortcut for \"zdiff --cmp\""
- echo
- echo "Usage: $0 [OPTIONS] [DIFF_OPTIONS] FILE1 [FILE2]"
- echo
- echo "Compares FILE1 to FILE2. If FILE2 is omitted and FILE1 is compressed,"
- echo "compares FILE1 to the file with the corresponding decompressed file"
- echo "name (removes the extension from FILE1). If FILE2 is omitted and FILE1"
- echo "is not compressed, compares FILE1 to the uncompressed contents of"
- echo "FILE1.[bz2|gz|lz|xz] (the first one that is found)."
- echo "DIFF_OPTIONS are passed directly to diff or cmp."
- echo "The exit status from diff or cmp is preserved."
- echo
- echo "Options:"
- echo " -h, --help display this help and exit"
- echo " -V, --version output version information and exit"
- echo " --diff use diff to compare files (default)"
- echo " --cmp use cmp to compare files"
- echo
- echo "Report bugs to zutils-bug@nongnu.org"
- echo "Zutils home page: http://www.nongnu.org/zutils/zutils.html"
- exit 0 ;;
- --version | --ve* | -V)
- echo "Zdiff (zutils) VERSION"
- echo "Copyright (C) 2009 Antonio Diaz Diaz."
- echo "This script is free software: you have unlimited permission"
- echo "to copy, distribute and modify it."
- exit 0 ;;
- --diff)
- diff_prog=diff ;;
- --cmp)
- diff_prog=cmp ;;
- -)
- echo "$0: reading from stdin not supported"
- exit 1 ;;
- --)
- shift; two_hyphens=1 ; break ;;
- -?*)
- args="${args} $1" ;;
- *)
- break ;;
- esac
- shift
-done
-
-# Loop over files
-for i in "$@" ; do
- if [ "$i" = "--" ] && [ ${two_hyphens} = 0 ] ; then two_hyphens=1
- else
- if [ -f "$i" ] ; then
- if [ -z "${file1}" ] ; then file1="$i"
- else
- if [ -z "${file2}" ] ; then file2="$i"
- else
- echo "$0: Too many files; use --help for usage." 1>&2
- fi
- fi
- else
- echo "$0: File \"$i\" not found or not a regular file" 1>&2
- exit 1
- fi
- fi
-done
-
-if [ -z "${file1}" ] ; then
- echo "$0: No files given; use --help for usage." 1>&2
- exit 1
-fi
-
-if [ -z "${file2}" ] ; then
- case "${file1}" in
- *.bz2) file2=`printf "%s" "${file1}" | sed -e 's,.bz2$,,'` ;;
- *.tbz) file2=`printf "%s" "${file1}" | sed -e 's,tbz$,tar,'` ;;
- *.tbz2) file2=`printf "%s" "${file1}" | sed -e 's,tbz2$,tar,'` ;;
- *.gz) file2=`printf "%s" "${file1}" | sed -e 's,.gz$,,'` ;;
- *.tgz) file2=`printf "%s" "${file1}" | sed -e 's,tgz$,tar,'` ;;
- *.lz) file2=`printf "%s" "${file1}" | sed -e 's,.lz$,,'` ;;
- *.tlz) file2=`printf "%s" "${file1}" | sed -e 's,tlz$,tar,'` ;;
- *.xz) file2=`printf "%s" "${file1}" | sed -e 's,.xz$,,'` ;;
- *.txz) file2=`printf "%s" "${file1}" | sed -e 's,txz$,tar,'` ;;
- *)
- if [ -f "${file1}.bz2" ] ; then file2="${file1}.bz2"
- elif [ -f "${file1}.gz" ] ; then file2="${file1}.gz"
- elif [ -f "${file1}.lz" ] ; then file2="${file1}.lz"
- elif [ -f "${file1}.xz" ] ; then file2="${file1}.xz"
- else
- echo "$0: Compressed version of ${file1} not found; use --help for usage." 1>&2
- exit 1
- fi ;;
- esac
-fi
-
-prog1=
-prog2=
-bindir=`echo "$0" | sed -e 's,[^/]*$,,'`
-if [ -f "${file1}" ] ; then
- prog_name=`"${bindir}"zutils -t -- "${file1}"`
- case "${prog_name}" in
- bzip2 | gzip | lzip | xz) prog1=${prog_name} ;;
- esac
-fi
-if [ -f "${file2}" ] ; then
- prog_name=`"${bindir}"zutils -t -- "${file2}"`
- case "${prog_name}" in
- bzip2 | gzip | lzip | xz) prog2=${prog_name} ;;
- esac
-fi
-
-retval=0
-if [ -n "${prog1}" ] ; then
- if [ -n "${prog2}" ] ; then
- tmp_file=`mktemp "${TMPDIR:-/tmp}"/zdiff.XXXXXXXXXX` || {
- echo 'cannot create a temporary file' 1>&2
- exit 1
- }
- ${prog2} -cdfq -- "${file2}" > "${tmp_file}" || exit 1
- ${prog1} -cdfq -- "${file1}" | ${diff_prog} ${args} - -- "${tmp_file}"
- retval=$?
- rm -f "${tmp_file}" || retval=$?
- else
- ${prog1} -cdfq -- "${file1}" | ${diff_prog} ${args} - -- "${file2}"
- retval=$?
- fi
-else
- if [ -n "${prog2}" ] ; then
- ${prog2} -cdfq -- "${file2}" | ${diff_prog} ${args} -- "${file1}" -
- retval=$?
- else
- ${diff_prog} ${args} -- "${file1}" "${file2}"
- retval=$?
- fi
-fi
-
-exit ${retval}
diff --git a/zegrep.in b/zegrep.in
index 0cac12e..e01f655 100644
--- a/zegrep.in
+++ b/zegrep.in
@@ -1,3 +1,3 @@
#! /bin/sh
bindir=`echo "$0" | sed -e 's,[^/]*$,,'`
-exec "${bindir}"zgrep -E "$@"
+exec "${bindir}"zutils --zgrep -E "$@"
diff --git a/zfgrep.in b/zfgrep.in
index c1a96d8..a3d54f3 100644
--- a/zfgrep.in
+++ b/zfgrep.in
@@ -1,3 +1,3 @@
#! /bin/sh
bindir=`echo "$0" | sed -e 's,[^/]*$,,'`
-exec "${bindir}"zgrep -F "$@"
+exec "${bindir}"zutils --zgrep -F "$@"
diff --git a/zgrep.cc b/zgrep.cc
new file mode 100644
index 0000000..b1c18b4
--- /dev/null
+++ b/zgrep.cc
@@ -0,0 +1,159 @@
+/* Zgrep - search compressed files for a regular expression
+ Copyright (C) 2010 Antonio Diaz Diaz.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+void show_zgrep_help() throw()
+ {
+ std::printf( "Zgrep is a front end to the grep program that allows transparent search\n" );
+ std::printf( "on any combination of compressed and non-compressed files. If any given\n" );
+ std::printf( "file is compressed, its uncompressed content is used. If a given file\n" );
+ std::printf( "does not exist, and its name does not end with one of the known\n" );
+ std::printf( "extensions, zgrep tries the compressed file names corresponding to the\n" );
+ std::printf( "supported compressors. If no files are specified, data is read from\n" );
+ std::printf( "standard input, decompressed if needed, and fed to grep. Data read from\n" );
+ std::printf( "standard input must be of the same type; all uncompressed or all\n" );
+ std::printf( "compressed with the same compressor.\n" );
+ std::printf( "The supported compressors are bzip2, gzip, lzip and xz.\n" );
+ std::printf( "\nUsage: zgrep [options] <pattern> [files]\n" );
+ std::printf( "\nExit status is 0 if match, 1 if no match, 2 if trouble.\n" );
+ std::printf( "\nOptions:\n" );
+ std::printf( " --help display this help and exit\n" );
+ std::printf( " -V, --version output version information and exit\n" );
+ std::printf( " -a, --text treat all files as text\n" );
+ std::printf( " -A, --after-context=<n> print <n> lines of trailing context\n" );
+ std::printf( " -b, --byte-offset print the byte offset of each line\n" );
+ std::printf( " -B, --before-context=<n> print <n> lines of leading context\n" );
+ std::printf( " -c, --count only print a count of matching lines per file\n" );
+ std::printf( " -C, --context=<n> print <n> lines of output context\n" );
+ std::printf( " -e, --regexp=<pattern> use <pattern> as the pattern to match\n" );
+ std::printf( " -E, --extended-regexp <pattern> is an extended regular expression\n" );
+ std::printf( " -f, --file=<file> obtain patterns from <file>\n" );
+ std::printf( " -F, --fixed-strings <pattern> is a set of newline-separated strings\n" );
+ std::printf( " -h, --no-filename suppress the prefixing filename on output\n" );
+ std::printf( " -H, --with-filename print the filename for each match\n" );
+ std::printf( " -i, --ignore-case ignore case distinctions\n" );
+ std::printf( " -I ignore binary files\n" );
+ std::printf( " -l, --files-with-matches only print names of files containing matches\n" );
+ std::printf( " -L, --files-without-match only print names of files containing no matches\n" );
+ std::printf( " -m, --max-count=<n> stop after <n> matches\n" );
+ std::printf( " -n, --line-number print the line number of each line\n" );
+ std::printf( " -o, --only-matching show only the part of a line matching <pattern>\n" );
+ std::printf( " -q, --quiet suppress all messages\n" );
+ std::printf( " -r, --recursive operate recursively on directories\n" );
+ std::printf( " -s, --no-messages suppress error messages\n" );
+ std::printf( " -v, --invert-match select non-matching lines\n" );
+ std::printf( " --verbose verbose mode (show error messages)\n" );
+ std::printf( " -w, --word-regexp match only whole words\n" );
+ std::printf( " -x, --line-regexp match only whole lines\n" );
+ show_help_addr();
+ }
+
+
+int zgrep_stdin( int infd, const std::vector< const char * > & grep_args )
+ {
+ pid_t pid;
+ if( !set_data_feeder( &infd, &pid ) ) return 2;
+ const pid_t grep_pid = fork();
+ if( grep_pid == 0 ) // child (grep)
+ {
+ if( dup2( infd, STDIN_FILENO ) >= 0 && close( infd ) == 0 )
+ {
+ const char ** const argv = new const char *[grep_args.size()+2];
+ argv[0] = "grep";
+ for( unsigned int i = 0; i < grep_args.size(); ++i )
+ argv[i+1] = grep_args[i];
+ argv[grep_args.size()+1] = 0;
+ execvp( argv[0], (char **)argv );
+ }
+ show_error( "Can't exec `grep'." );
+ _exit( 2 );
+ }
+ // parent
+ if( grep_pid < 0 )
+ { show_error( "Can't fork `grep'", errno ); return 2; }
+ int retval = 0;
+ if( pid && wait_for_child( pid, "data feeder" ) != 0 ) retval = 2;
+ if( wait_for_child( grep_pid, "grep" ) != 0 ) retval = 2;
+ if( close( infd ) != 0 )
+ { show_error( "Can't close output of data feeder", errno ); return 2; }
+ return retval;
+ }
+
+
+int zgrep_file( int infd, const std::string & input_filename,
+ const std::vector< const char * > & grep_args,
+ const bool grep_list, const bool grep_show_name )
+ {
+ pid_t pid;
+ if( !set_data_feeder( &infd, &pid ) ) return 2;
+ int fda[2]; // pipe from grep
+ if( pipe( fda ) < 0 )
+ { show_error( "Can't create pipe", errno ); return 2; }
+ const pid_t grep_pid = fork();
+ if( grep_pid == 0 ) // child (grep)
+ {
+ if( dup2( infd, STDIN_FILENO ) >= 0 &&
+ dup2( fda[1], STDOUT_FILENO ) >= 0 &&
+ close( infd ) == 0 && close( fda[0] ) == 0 && close( fda[1] ) == 0 )
+ {
+ const char ** const argv = new const char *[grep_args.size()+2];
+ argv[0] = "grep";
+ for( unsigned int i = 0; i < grep_args.size(); ++i )
+ argv[i+1] = grep_args[i];
+ argv[grep_args.size()+1] = 0;
+ execvp( argv[0], (char **)argv );
+ }
+ show_error( "Can't exec `grep'." );
+ _exit( 2 );
+ }
+ // parent
+ close( fda[1] );
+ if( grep_pid < 0 )
+ { show_error( "Can't fork `grep'", errno ); return 2; }
+ enum { buffer_size = 256 };
+ uint8_t buffer[buffer_size];
+ bool line_begin = true;
+ while( true )
+ {
+ const int size = readblock( fda[0], buffer, buffer_size );
+ if( size != buffer_size && errno )
+ { show_error( "Read error", errno ); return 2; }
+ if( size > 0 && !grep_list )
+ {
+ if( grep_show_name )
+ for( int i = 0; i < size; ++i )
+ {
+ if( line_begin )
+ { line_begin = false; std::printf( "%s:", input_filename.c_str() ); }
+ if( buffer[i] == '\n' ) line_begin = true;
+ putchar( buffer[i] );
+ }
+ else if( std::fwrite( buffer, 1, size, stdout ) != (unsigned int)size )
+ { show_error( "Write error", errno ); return 2; }
+ }
+ if( size < buffer_size ) break;
+ }
+ int retval = 0;
+ if( pid && wait_for_child( pid, "data feeder" ) != 0 ) retval = 2;
+ if( wait_for_child( grep_pid, "grep" ) != 0 ) retval = 2;
+ if( grep_list && retval == 0 )
+ std::printf( "%s\n", input_filename.c_str() );
+ if( close( infd ) != 0 )
+ { show_error( "Can't close output of data feeder", errno ); return 2; }
+ if( close( fda[0] ) != 0 )
+ { show_error( "Can't close output of grep", errno ); return 2; }
+ return retval;
+ }
diff --git a/zgrep.in b/zgrep.in
index dbcb58c..bfbc490 100644
--- a/zgrep.in
+++ b/zgrep.in
@@ -1,136 +1,3 @@
#! /bin/sh
-# Zgrep - Grep wrapper for compressed files.
-# Copyright (C) 2008, 2009 Antonio Diaz Diaz.
-#
-# This script is free software: you have unlimited permission
-# to copy, distribute and modify it.
-
-LC_ALL=C
-export LC_ALL
-args=
-have_pat=0
-list=0
-no_name=0
-two_hyphens=0
-
-# Loop over args until pattern is found
-while [ -n "$1" ] ; do
-
- case "$1" in
- --help | --he* | -h)
- echo "Zgrep - Grep wrapper for compressed files."
- echo
- echo "Zgrep is a wrapper script around the grep command that allows"
- echo "transparent search on any combination of compressed and non-compressed"
- echo "files. If any given file is compressed, its uncompressed content is"
- echo "used. If a given file does not exist, zgrep tries the compressed file"
- echo "names corresponding to the supported compressors. If no files are"
- echo "specified, data is read from standard input, decompressed if needed, and"
- echo "fed to grep. Data read from standard input must be of the same type; all"
- echo "uncompressed or all compressed with the same compressor."
- echo "The supported compressors are bzip2, gzip, lzip and xz."
- echo
- echo "Zegrep is a shortcut for \"zgrep -E\""
- echo "Zfgrep is a shortcut for \"zgrep -F\""
- echo
- echo "Usage: $0 [OPTIONS] [GREP_OPTIONS] PATTERN [FILES]"
- echo
- echo "GREP_OPTIONS are passed directly to grep."
- echo "The exit status from grep is preserved."
- echo
- echo "Options:"
- echo " -h, --help display this help and exit"
- echo " -V, --version output version information and exit"
- echo
- echo "Report bugs to zutils-bug@nongnu.org"
- echo "Zutils home page: http://www.nongnu.org/zutils/zutils.html"
- exit 0 ;;
- --version | --ve* | -V)
- echo "Zgrep (zutils) VERSION"
- echo "Copyright (C) 2009 Antonio Diaz Diaz."
- echo "This script is free software: you have unlimited permission"
- echo "to copy, distribute and modify it."
- exit 0 ;;
- -[drRzZ] | --di* | --exc* | --inc* | --nu* | --rec*)
- echo "$0: option $1 not supported"
- exit 1 ;;
- -e?* | -f?* | --file=* | --reg*=*)
- args="${args} $1"; have_pat=1 ;;
- -e | -f | --file | --reg*)
- args="${args} $1 $2"; shift; have_pat=1 ;;
- --*=*)
- args="${args} $1" ;;
- -[ABCDm] | --af* | --be* | --binary-* | --con* | --de* | --[lm]a*)
- args="${args} $1 $2"; shift ;;
- -l | --files-with-*)
- args="${args} $1"; list=1 ;;
- -h | --no-f*)
- args="${args} $1"; no_name=1 ;;
- --)
- shift ; two_hyphens=1 ; break ;;
- -?*)
- args="${args} $1" ;;
- *)
- if [ ${have_pat} = 0 ] ; then args="${args} $1"; have_pat=1
- else break
- fi ;;
- esac
- shift
-done
-
-if [ ${have_pat} = 0 ] ; then
- echo "$0: Pattern not found; use --help for usage." 1>&2
- exit 1
-fi
-
-if [ $# = 0 ] ; then
- bindir=`echo "$0" | sed -e 's,[^/]*$,,'`
- prog_name=`"${bindir}"zutils -t`
- case "${prog_name}" in
- bzip2 | gzip | lzip | xz) prog="${prog_name} -cdfq" ;;
- *) prog=cat ;;
- esac
- { "${bindir}"zutils -m ${prog_name} ; cat ; } | ${prog} | grep ${args}
- exit $?
-fi
-
-retval=0
-for i in "$@" ; do
- if [ "$i" = "--" ] && [ ${two_hyphens} = 0 ] ; then two_hyphens=1
- else
- if [ ! -f "$i" ] ; then
- if [ -f "$i.gz" ] ; then i="$i.gz"
- elif [ -f "$i.bz2" ] ; then i="$i.bz2"
- elif [ -f "$i.lz" ] ; then i="$i.lz"
- elif [ -f "$i.xz" ] ; then i="$i.xz"
- else
- echo "$0: File \"$i\" not found or not a regular file" 1>&2
- if [ ${retval} = 0 ] ; then retval=1 ; fi
- continue
- fi
- fi
- bindir=`echo "$0" | sed -e 's,[^/]*$,,'`
- prog_name=`"${bindir}"zutils -t -- "$i"`
- case "${prog_name}" in
- bzip2 | gzip | lzip | xz) prog="${prog_name} -cdfq" ;;
- *) prog=cat ;;
- esac
- if [ ${list} = 1 ] ; then
- ${prog} -- "$i" | grep ${args} 2>&1 > /dev/null && echo "$i"
- r=$?
- elif [ $# = 1 ] || [ ${no_name} = 1 ] ; then
- ${prog} -- "$i" | grep ${args}
- r=$?
- else
- j=`printf "%s" "$i" | sed -e 's,\\\\,\\\\\\\\,g'`
- j=`printf "%s" "$j" | sed -e 's,|,\\\\|,g'`
- j=`printf "%s" "$j" | sed -e 's,&,\\\\&,g'`
- j=`printf "%s" "$j" | tr '\n' ' '`
- ${prog} -- "$i" | grep ${args} | sed -e "s,^,${j}:,"
- r=$?
- fi
- [ $r != 0 ] && retval="$r"
- fi
-done
-
-exit ${retval}
+bindir=`echo "$0" | sed -e 's,[^/]*$,,'`
+exec "${bindir}"zutils --zgrep "$@"
diff --git a/ztest.cc b/ztest.cc
new file mode 100644
index 0000000..6a9b910
--- /dev/null
+++ b/ztest.cc
@@ -0,0 +1,119 @@
+/* Ztest - verify integrity of compressed files
+ Copyright (C) 2010 Antonio Diaz Diaz.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+void show_ztest_help() throw()
+ {
+ std::printf( "Ztest verifies the integrity of the specified compressed files.\n" );
+ std::printf( "Non-compressed files are ignored. If no files are specified, the\n" );
+ std::printf( "integrity of compressed data read from standard input is verified. Data\n" );
+ std::printf( "read from standard input must be all compressed with the same compressor.\n" );
+ std::printf( "The supported compressors are bzip2, gzip, lzip and xz.\n" );
+ std::printf( "\nUsage: ztest [options] [files]\n" );
+ std::printf( "\nExit status is 2 if any compressed file is corrupt, 0 otherwise.\n" );
+ std::printf( "\nOptions:\n" );
+ std::printf( " -h, --help display this help and exit\n" );
+ std::printf( " -V, --version output version information and exit\n" );
+ std::printf( " -q, --quiet suppress all messages\n" );
+ std::printf( " -r, --recursive operate recursively on directories\n" );
+ std::printf( " -v, --verbose be verbose (a 2nd -v gives more)\n" );
+ show_help_addr();
+ }
+
+
+int ztest_stdin( const int infd,
+ const std::vector< const char * > & ztest_args )
+ {
+ std::string file_type;
+ const uint8_t * magic_data;
+ int magic_size = 0;
+ if( !test_format( infd, file_type, &magic_data, &magic_size ) )
+ { show_error( "Unknown data format read from stdin." ); return 2; }
+ int fda[2];
+ if( pipe( fda ) < 0 )
+ { show_error( "Can't create pipe", errno ); return 1; }
+ const pid_t pid = fork();
+
+ if( pid == 0 ) // child (decompressor)
+ {
+ if( dup2( fda[0], STDIN_FILENO ) >= 0 &&
+ close( fda[0] ) == 0 && close( fda[1] ) == 0 )
+ {
+ const char ** const argv = new const char *[ztest_args.size()+3];
+ argv[0] = file_type.c_str();
+ for( unsigned int i = 0; i < ztest_args.size(); ++i )
+ argv[i+1] = ztest_args[i];
+ argv[ztest_args.size()+1] = "-t";
+ argv[ztest_args.size()+2] = 0;
+ execvp( argv[0], (char **)argv );
+ }
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: Can't exec `%s': %s.\n",
+ util_name, file_type.c_str(), std::strerror( errno ) );
+ _exit( 1 );
+ }
+ // parent
+ if( pid < 0 )
+ {
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: Can't fork `%s': %s.\n",
+ util_name, file_type.c_str(), std::strerror( errno ) );
+ return 1;
+ }
+ close( fda[0] );
+ if( !feed_data( infd, fda[1], magic_data, magic_size ) ) return 1;
+ if( close( fda[1] ) != 0 )
+ { show_error( "Can't close output of data feeder", errno ); return 1; }
+ return wait_for_child( pid, file_type.c_str() );
+ }
+
+
+int ztest_file( const int infd, const std::string & input_filename,
+ const std::vector< const char * > & ztest_args )
+ {
+ std::string file_type;
+ const uint8_t * magic_data;
+ int magic_size = 0;
+ if( !test_format( infd, file_type, &magic_data, &magic_size ) )
+ return 0; // ignored
+ const pid_t pid = fork();
+
+ if( pid == 0 ) // child (decompressor)
+ {
+ const char ** const argv = new const char *[ztest_args.size()+5];
+ argv[0] = file_type.c_str();
+ for( unsigned int i = 0; i < ztest_args.size(); ++i )
+ argv[i+1] = ztest_args[i];
+ argv[ztest_args.size()+1] = "-t";
+ argv[ztest_args.size()+2] = "--";
+ argv[ztest_args.size()+3] = input_filename.c_str();
+ argv[ztest_args.size()+4] = 0;
+ execvp( argv[0], (char **)argv );
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: Can't exec `%s': %s.\n",
+ util_name, argv[0], std::strerror( errno ) );
+ _exit( 1 );
+ }
+ // parent
+ if( pid < 0 )
+ {
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: Can't fork `%s': %s.\n",
+ util_name, file_type.c_str(), std::strerror( errno ) );
+ return 1;
+ }
+ return wait_for_child( pid, file_type.c_str() );
+ }
diff --git a/ztest.in b/ztest.in
index 98e93f6..cc7dc9b 100644
--- a/ztest.in
+++ b/ztest.in
@@ -1,102 +1,3 @@
#! /bin/sh
-# Ztest - Test integrity of compressed files.
-# Copyright (C) 2009 Antonio Diaz Diaz.
-#
-# This script is free software: you have unlimited permission
-# to copy, distribute and modify it.
-
-LC_ALL=C
-export LC_ALL
-args=
-recursive=0
-two_hyphens=0
-
-# Loop over args until a filename is found
-while [ -n "$1" ] ; do
-
- case "$1" in
- --help | --he* | -h)
- echo "Ztest - Test integrity of compressed files."
- echo
- echo "Ztest verifies the integrity of the specified compressed files."
- echo "Non-compressed files are ignored. If no files are specified, the"
- echo "integrity of compressed data read from standard input is verified. Data"
- echo "read from standard input must be all compressed with the same compressor."
- echo "The supported compressors are bzip2, gzip, lzip and xz."
- echo
- echo "Usage: $0 [OPTIONS] [FILES]"
- echo
- echo "The exit status is 1 if any compressed file is corrupt, 0 otherwise."
- echo
- echo "Options:"
- echo " -h, --help display this help and exit"
- echo " -V, --version output version information and exit"
- echo " -q, --quiet suppress all messages"
- echo " -r, --recursive operate recursively on directories"
- echo " -v, --verbose be verbose (a 2nd -v gives more)"
- echo
- echo "Report bugs to zutils-bug@nongnu.org"
- echo "Zutils home page: http://www.nongnu.org/zutils/zutils.html"
- exit 0 ;;
- --version | --ve* | -V)
- echo "Ztest (zutils) VERSION"
- echo "Copyright (C) 2009 Antonio Diaz Diaz."
- echo "This script is free software: you have unlimited permission"
- echo "to copy, distribute and modify it."
- exit 0 ;;
- -r | --re*)
- recursive=1 ;;
- -v | -vv | -vvv | --ve* | -q | --qu*)
- args="${args} $1" ;;
- --)
- shift ; two_hyphens=1 ; break ;;
- - | -?*)
- ;;
- *)
- break ;;
- esac
- shift
-done
-
-if [ $# = 0 ] ; then
- bindir=`echo "$0" | sed -e 's,[^/]*$,,'`
- prog=`"${bindir}"zutils -t`
- case "${prog}" in
- bzip2 | gzip | lzip | xz)
- ;;
- *) echo "$0: Unknown data format read from stdin" 1>&2
- exit 1 ;;
- esac
- { "${bindir}"zutils -m ${prog} ; cat ; } | ${prog} -t ${args}
- exit $?
-fi
-
-retval=0
-for i in "$@" ; do
- if [ "$i" = "--" ] && [ ${two_hyphens} = 0 ] ; then two_hyphens=1
- else
- if [ ! -f "$i" ] ; then
- if [ ${recursive} = 1 ] && [ -d "$i" ] ; then
- bad_files=`find "$i" -type f \( -exec "$0" ${args} '{}' ';' -o -print \)`
- if [ ${retval} = 0 ] && [ -n "${bad_files}" ] ; then retval=1 ; fi
- continue
- else
- echo "$0: File \"$i\" not found or not a regular file" 1>&2
- if [ ${retval} = 0 ] ; then retval=1 ; fi
- continue
- fi
- fi
- bindir=`echo "$0" | sed -e 's,[^/]*$,,'`
- prog=`"${bindir}"zutils -t -- "$i"`
- case "${prog}" in
- bzip2 | gzip | lzip | xz)
- ;;
- *) continue ;;
- esac
- ${prog} -t ${args} -- "$i"
- r=$?
- if [ $r != 0 ] ; then retval=$r ; fi
- fi
-done
-
-exit ${retval}
+bindir=`echo "$0" | sed -e 's,[^/]*$,,'`
+exec "${bindir}"zutils --ztest "$@"
diff --git a/zutils.cc b/zutils.cc
new file mode 100644
index 0000000..5451534
--- /dev/null
+++ b/zutils.cc
@@ -0,0 +1,301 @@
+/* Zutils - Utilities dealing with compressed files
+ Copyright (C) 2009, 2010 Antonio Diaz Diaz.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#define _FILE_OFFSET_BITS 64
+
+#include <cerrno>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <string>
+#include <stdint.h>
+#include <unistd.h>
+#include <sys/wait.h>
+
+#include "zutils.h"
+
+
+const char * invocation_name = 0;
+const char * util_name = program_name;
+
+int verbosity = 0;
+
+
+// Returns the number of bytes really read.
+// If (returned value < size) and (errno == 0), means EOF was reached.
+//
+int readblock( const int fd, uint8_t * const buf, const int size ) throw()
+ {
+ int rest = size;
+ errno = 0;
+ while( rest > 0 )
+ {
+ errno = 0;
+ const int n = read( fd, buf + size - rest, rest );
+ if( n > 0 ) rest -= n;
+ else if( n == 0 ) break;
+ else if( errno != EINTR && errno != EAGAIN ) break;
+ }
+ return ( rest > 0 ) ? size - rest : size;
+ }
+
+
+// Returns the number of bytes really written.
+// If (returned value < size), it is always an error.
+//
+int writeblock( const int fd, const uint8_t * const buf, const int size ) throw()
+ {
+ int rest = size;
+ errno = 0;
+ while( rest > 0 )
+ {
+ errno = 0;
+ const int n = write( fd, buf + size - rest, rest );
+ if( n > 0 ) rest -= n;
+ else if( errno && errno != EINTR && errno != EAGAIN ) break;
+ }
+ return ( rest > 0 ) ? size - rest : size;
+ }
+
+
+bool feed_data( const int infd, const int outfd,
+ const uint8_t * magic_data, const int magic_size )
+ {
+ if( writeblock( outfd, magic_data, magic_size ) != magic_size )
+ { show_error( "Write error", errno ); return false; }
+ enum { buffer_size = 4096 };
+ uint8_t buffer[buffer_size];
+ while( true )
+ {
+ const int size = readblock( infd, buffer, buffer_size );
+ if( size != buffer_size && errno )
+ { show_error( "Read error", errno ); return false; }
+ if( size > 0 && writeblock( outfd, buffer, size ) != size )
+ { show_error( "Write error", errno ); return false; }
+ if( size < buffer_size ) break;
+ }
+ return true;
+ }
+
+
+bool set_data_feeder( int * const infdp, pid_t * const pidp )
+ {
+ std::string file_type;
+ const uint8_t * magic_data;
+ int magic_size;
+ const bool compressed =
+ test_format( *infdp, file_type, &magic_data, &magic_size );
+
+ if( compressed ) // compressed with `file_type'
+ {
+ int fda[2]; // pipe from feeder
+ int fda2[2]; // pipe from decompressor
+ if( pipe( fda ) < 0 || pipe( fda2 ) < 0 )
+ { show_error( "Can't create pipe", errno ); return false; }
+ const int old_infd = *infdp;
+ *infdp = fda2[0];
+ const pid_t pid = fork();
+ if( pid == 0 ) // child (decompressor feeder)
+ {
+ const pid_t pid2 = fork();
+ if( pid2 == 0 ) // grandchild (decompressor)
+ {
+ if( dup2( fda[0], STDIN_FILENO ) >= 0 &&
+ dup2( fda2[1], STDOUT_FILENO ) >= 0 &&
+ close( fda[0] ) == 0 && close( fda[1] ) == 0 &&
+ close( fda2[0] ) == 0 && close( fda2[1] ) == 0 )
+ execlp( file_type.c_str(), file_type.c_str(), "-cdfq", (char *)0 );
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: Can't exec `%s': %s.\n",
+ util_name, file_type.c_str(), std::strerror( errno ) );
+ _exit( 2 );
+ }
+ if( pid2 < 0 )
+ {
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: Can't fork `%s': %s.\n",
+ util_name, file_type.c_str(), std::strerror( errno ) );
+ _exit( 2 );
+ }
+
+ if( close( fda[0] ) != 0 ||
+ close( fda2[0] ) != 0 || close( fda2[1] ) != 0 ||
+ !feed_data( old_infd, fda[1], magic_data, magic_size ) )
+ _exit( 2 );
+ if( close( fda[1] ) != 0 )
+ { show_error( "Can't close output of decompressor feeder", errno );
+ _exit( 2 ); }
+ _exit( wait_for_child( pid2, file_type.c_str() ) );
+ }
+ // parent
+ close( fda[0] ); close( fda[1] ); close( fda2[1] );
+ if( pid < 0 )
+ { show_error( "Can't fork decompressor feeder", errno ); return false; }
+ *pidp = pid;
+ }
+ else // not compressed
+ {
+ int fda[2]; // pipe from feeder
+ if( pipe( fda ) < 0 )
+ { show_error( "Can't create pipe", errno ); return false; }
+ const int old_infd = *infdp;
+ *infdp = fda[0];
+ const pid_t pid = fork();
+ if( pid == 0 ) // child (feeder)
+ {
+ if( close( fda[0] ) != 0 ||
+ !feed_data( old_infd, fda[1], magic_data, magic_size ) )
+ _exit( 2 );
+ if( close( fda[1] ) != 0 )
+ { show_error( "Can't close output of data feeder", errno );
+ _exit( 2 ); }
+ _exit( 0 );
+ }
+ // parent
+ close( fda[1] );
+ if( pid < 0 )
+ { show_error( "Can't fork data feeder", errno ); return false; }
+ *pidp = pid;
+ }
+ return true;
+ }
+
+
+void show_help_addr() throw()
+ {
+ std::printf( "\nReport bugs to zutils-bug@nongnu.org\n" );
+ std::printf( "Zutils home page: http://www.nongnu.org/zutils/zutils.html\n" );
+ }
+
+
+void show_version( const char * const Util_name ) throw()
+ {
+ if( !Util_name || !*Util_name )
+ std::printf( "%s %s\n", Program_name, PROGVERSION );
+ else
+ std::printf( "%s (%s) %s\n", Util_name, program_name, PROGVERSION );
+ std::printf( "Copyright (C) %s Antonio Diaz Diaz.\n", program_year );
+ std::printf( "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n" );
+ std::printf( "This is free software: you are free to change and redistribute it.\n" );
+ std::printf( "There is NO WARRANTY, to the extent permitted by law.\n" );
+ }
+
+
+void show_error( const char * const msg, const int errcode,
+ const bool help ) throw()
+ {
+ if( verbosity >= 0 )
+ {
+ if( msg && msg[0] )
+ {
+ std::fprintf( stderr, "%s: %s", util_name, msg );
+ if( errcode > 0 )
+ std::fprintf( stderr, ": %s", std::strerror( errcode ) );
+ std::fprintf( stderr, "\n" );
+ }
+ if( help && invocation_name && invocation_name[0] )
+ std::fprintf( stderr, "Try `%s --help' for more information.\n",
+ invocation_name );
+ }
+ }
+
+
+void internal_error( const char * const msg )
+ {
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: internal error: %s.\n", util_name, msg );
+ std::exit( 3 );
+ }
+
+
+unsigned char xdigit( const int value ) throw()
+ {
+ if( value >= 0 && value <= 9 ) return '0' + value;
+ if( value >= 10 && value <= 15 ) return 'A' + ( value - 10 );
+ return 0;
+ }
+
+
+bool test_format( const int infd, std::string & file_type,
+ const uint8_t ** const magic_datap, int * const magic_sizep )
+ {
+ enum { buf_size = 5 };
+ static uint8_t buf[buf_size];
+ int i = 0;
+ file_type.clear();
+ if( readblock( infd, buf, 1 ) == 1 )
+ {
+ ++i;
+ if( buf[0] == bzip2_magic[0] )
+ {
+ if( readblock( infd, &buf[i], 1 ) == 1 && buf[i++] == bzip2_magic[1] &&
+ readblock( infd, &buf[i], 1 ) == 1 && buf[i++] == bzip2_magic[2] )
+ { file_type = "bzip2";
+ *magic_datap = bzip2_magic; *magic_sizep = bzip2_magic_size; }
+ }
+ else if( buf[0] == gzip_magic[0] )
+ {
+ if( readblock( infd, &buf[i], 1 ) == 1 && buf[i++] == gzip_magic[1] )
+ { file_type = "gzip";
+ *magic_datap = gzip_magic; *magic_sizep = gzip_magic_size; }
+ }
+ else if( buf[0] == lzip_magic[0] )
+ {
+ if( readblock( infd, &buf[i], 1 ) == 1 && buf[i++] == lzip_magic[1] &&
+ readblock( infd, &buf[i], 1 ) == 1 && buf[i++] == lzip_magic[2] &&
+ readblock( infd, &buf[i], 1 ) == 1 && buf[i++] == lzip_magic[3] )
+ { file_type = "lzip";
+ *magic_datap = lzip_magic; *magic_sizep = lzip_magic_size; }
+ }
+ else if( buf[0] == xz_magic[0] )
+ {
+ if( readblock( infd, &buf[i], 1 ) == 1 && buf[i++] == xz_magic[1] &&
+ readblock( infd, &buf[i], 1 ) == 1 && buf[i++] == xz_magic[2] &&
+ readblock( infd, &buf[i], 1 ) == 1 && buf[i++] == xz_magic[3] &&
+ readblock( infd, &buf[i], 1 ) == 1 && buf[i++] == xz_magic[4] )
+ { file_type = "xz";
+ *magic_datap = xz_magic; *magic_sizep = xz_magic_size; }
+ }
+ }
+ if( file_type.size() ) return true;
+ for( int j = 0; j < i; ++j )
+ {
+ file_type += xdigit( buf[j] >> 4 );
+ file_type += xdigit( buf[j] & 0x0F );
+ }
+ *magic_datap = buf; *magic_sizep = i;
+ return false;
+ }
+
+
+int wait_for_child( const pid_t pid, const char * const name )
+ {
+ int status;
+ while( waitpid( pid, &status, 0 ) == -1 )
+ {
+ if( errno != EINTR )
+ {
+ if( verbosity >= 0 )
+ std::fprintf( stderr, "%s: Error waiting termination of `%s': %s.\n",
+ util_name, name, std::strerror( errno ) );
+ _exit( 1 );
+ }
+ }
+
+ if( WIFEXITED( status ) ) return WEXITSTATUS( status );
+ else return 1;
+ }
diff --git a/zutils.h b/zutils.h
new file mode 100644
index 0000000..296f3ac
--- /dev/null
+++ b/zutils.h
@@ -0,0 +1,53 @@
+/* Zutils - Utilities dealing with compressed files
+ Copyright (C) 2009, 2010 Antonio Diaz Diaz.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+const char * const Program_name = "Zutils";
+const char * const program_name = "zutils";
+const char * const program_year = "2010";
+extern const char * invocation_name;
+extern const char * util_name;
+
+extern int verbosity;
+
+const char * const simple_extensions[] = { ".gz", ".lz", ".bz2", ".xz", 0 };
+
+enum { bzip2_magic_size = 3 };
+enum { gzip_magic_size = 2 };
+enum { lzip_magic_size = 4 };
+enum { xz_magic_size = 5 };
+const uint8_t bzip2_magic[bzip2_magic_size] = { 'B', 'Z', 'h' };
+const uint8_t gzip_magic[ gzip_magic_size] = { '\x1F', '\x8B' };
+const uint8_t lzip_magic[ lzip_magic_size] = { 'L', 'Z', 'I', 'P' };
+const uint8_t xz_magic[ xz_magic_size] = { '\xFD', '7', 'z', 'X', 'Z' };
+
+
+int readblock( const int fd, uint8_t * const buf, const int size ) throw();
+int writeblock( const int fd, const uint8_t * const buf, const int size ) throw();
+bool feed_data( const int infd, const int outfd,
+ const uint8_t * magic_data, const int magic_size );
+bool set_data_feeder( int * const infdp, pid_t * const pidp );
+
+void show_help_addr() throw();
+void show_version( const char * const Util_name = 0 ) throw();
+void show_error( const char * const msg, const int errcode = 0,
+ const bool help = false ) throw();
+void internal_error( const char * const msg );
+
+bool test_format( const int infd, std::string & file_type,
+ const uint8_t ** magic_data, int * magic_sizep );
+
+int wait_for_child( const pid_t pid, const char * const name );