2 * Copyright 2014, Ingo Weinhold, ingo_weinhold@gmx.de.
3 * Distributed under the terms of the MIT License.
20 #include <package/hpkg/HPKGDefs.h>
21 #include <package/hpkg/PackageWriter.h>
23 #include <DataPositionIOWrapper.h>
28 #include "PackageWriterListener.h"
31 using BPackageKit::BHPKG::BPackageWriter
;
32 using BPackageKit::BHPKG::BPackageWriterListener
;
33 using BPackageKit::BHPKG::BPackageWriterParameters
;
36 struct ChecksumIO
: BDataIO
{
42 virtual ssize_t
Write(const void* buffer
, size_t size
)
45 fChecksummer
.Update(buffer
, size
);
51 const uint8
* digest
= fChecksummer
.Digest();
53 size_t length
= fChecksummer
.DigestLength();
54 char* buffer
= hex
.LockBuffer(length
* 2);
57 throw std::bad_alloc();
60 for (size_t i
= 0; i
< length
; i
++)
61 snprintf(buffer
+ 2 * i
, 3, "%02x", digest
[i
]);
73 create_stdio(bool isInput
)
75 BFdIO
* dataIO
= new BFdIO(isInput
? 0 : 1, false);
76 return new BDataPositionIOWrapper(dataIO
);
81 command_checksum(int argc
, const char* const* argv
)
87 static struct option sLongOptions
[] = {
88 { "help", no_argument
, 0, 'h' },
89 { "quiet", no_argument
, 0, 'q' },
90 { "verbose", no_argument
, 0, 'v' },
94 opterr
= 0; // don't print errors
95 int c
= getopt_long(argc
, (char**)argv
, "+hqv",
102 print_usage_and_exit(false);
114 print_usage_and_exit(true);
119 // The optional remaining argument is the package file.
120 if (argc
- optind
> 1)
121 print_usage_and_exit(true);
123 const char* packageFileName
= optind
< argc
? argv
[optind
++] : NULL
;
125 // open the input package
126 status_t error
= B_OK
;
127 BPositionIO
* inputFile
;
128 if (packageFileName
== NULL
|| strcmp(packageFileName
, "-") == 0) {
129 inputFile
= create_stdio(true);
131 BFile
* inputFileFile
= new BFile
;
132 error
= inputFileFile
->SetTo(packageFileName
, O_RDONLY
);
134 fprintf(stderr
, "Error: Failed to open input file \"%s\": %s\n",
135 packageFileName
, strerror(error
));
138 inputFile
= inputFileFile
;
141 // write the output package to a BDataIO that computes the checksum
142 BPackageWriterParameters writerParameters
;
143 writerParameters
.SetCompressionLevel(0);
144 writerParameters
.SetCompression(
145 BPackageKit::BHPKG::B_HPKG_COMPRESSION_NONE
);
147 PackageWriterListener
listener(verbose
, quiet
);
148 BPackageWriter
packageWriter(&listener
);
149 ChecksumIO outputFile
;
150 error
= packageWriter
.Init(new BDataPositionIOWrapper(&outputFile
), true,
155 error
= packageWriter
.Recompress(inputFile
);
159 printf("%s\n", outputFile
.Digest().String());