This source file includes following definitions.
- MD5Sum
- MakeFileSet
- main
#include <fstream>
#include <iostream>
#include <set>
#include <string>
#include "base/file_util.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/md5.h"
namespace {
const int kBufferSize = 1024;
bool MD5Sum(const char* path, std::string* digest_string) {
std::ifstream stream(path);
if (!stream.good()) {
LOG(ERROR) << "Could not open file " << path;
return false;
}
base::MD5Context ctx;
base::MD5Init(&ctx);
char buf[kBufferSize];
while (stream.good()) {
std::streamsize bytes_read = stream.readsome(buf, sizeof(buf));
if (bytes_read == 0)
break;
base::MD5Update(&ctx, base::StringPiece(buf, bytes_read));
}
if (stream.fail()) {
LOG(ERROR) << "Error reading file " << path;
return false;
}
base::MD5Digest digest;
base::MD5Final(&digest, &ctx);
*digest_string = base::MD5DigestToBase16(digest);
return true;
}
std::set<std::string> MakeFileSet(const char** files) {
const std::string svn_dir_component = FILE_PATH_LITERAL("/.svn/");
std::set<std::string> file_set;
for (const char** file = files; *file; ++file) {
base::FilePath file_path(*file);
if (base::DirectoryExists(file_path)) {
base::FileEnumerator file_enumerator(
file_path, true , base::FileEnumerator::FILES);
for (base::FilePath child, empty;
(child = file_enumerator.Next()) != empty; ) {
if (child.value().find(svn_dir_component) == std::string::npos) {
child = base::MakeAbsoluteFilePath(child);
file_set.insert(child.value());
}
}
} else {
file_set.insert(*file);
}
}
return file_set;
}
}
int main(int argc, const char* argv[]) {
if (argc < 2) {
LOG(ERROR) << "Usage: md5sum <path/to/file_or_dir>...";
return 1;
}
const std::set<std::string> files = MakeFileSet(argv + 1);
bool failed = false;
std::string digest;
for (std::set<std::string>::const_iterator it = files.begin();
it != files.end(); ++it) {
if (!MD5Sum(it->c_str(), &digest))
failed = true;
base::FilePath file_path(*it);
std::cout << digest << " "
<< base::MakeAbsoluteFilePath(file_path).value() << std::endl;
}
return failed;
}