OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 // Md5sum implementation for Android. This version handles files as well as |
| 6 // directories. Its output is sorted by file path. |
| 7 |
| 8 #include <fstream> |
| 9 #include <iostream> |
| 10 #include <set> |
| 11 #include <string> |
| 12 |
| 13 #include "base/file_path.h" |
| 14 #include "base/file_util.h" |
| 15 #include "base/logging.h" |
| 16 #include "base/md5.h" |
| 17 |
| 18 namespace { |
| 19 |
| 20 const int kBufferSize = 1024; |
| 21 |
| 22 // Returns whether |path|'s MD5 was successfully written to |digest_string|. |
| 23 bool MD5Sum(const char* path, std::string* digest_string) { |
| 24 std::ifstream stream(path); |
| 25 if (!stream.good()) { |
| 26 LOG(ERROR) << "Could not open file " << path; |
| 27 return false; |
| 28 } |
| 29 base::MD5Context ctx; |
| 30 base::MD5Init(&ctx); |
| 31 char buf[kBufferSize]; |
| 32 while (stream.good()) { |
| 33 std::streamsize bytes_read = stream.readsome(buf, sizeof(buf)); |
| 34 if (bytes_read == 0) |
| 35 break; |
| 36 base::MD5Update(&ctx, base::StringPiece(buf, bytes_read)); |
| 37 } |
| 38 if (stream.fail()) { |
| 39 LOG(ERROR) << "Error reading file " << path; |
| 40 return false; |
| 41 } |
| 42 base::MD5Digest digest; |
| 43 base::MD5Final(&digest, &ctx); |
| 44 *digest_string = base::MD5DigestToBase16(digest); |
| 45 return true; |
| 46 } |
| 47 |
| 48 // Returns the set of all files contained in |files|. This handles directories |
| 49 // by walking them recursively. |
| 50 std::set<std::string> MakeFileSet(const char** files) { |
| 51 std::set<std::string> file_set; |
| 52 for (const char** file = files; *file; ++file) { |
| 53 FilePath file_path(*file); |
| 54 if (file_util::DirectoryExists(file_path)) { |
| 55 file_util::FileEnumerator file_enumerator( |
| 56 file_path, true /* recurse */, file_util::FileEnumerator::FILES); |
| 57 for (FilePath child, empty; (child = file_enumerator.Next()) != empty; ) { |
| 58 file_util::AbsolutePath(&child); |
| 59 file_set.insert(child.value()); |
| 60 } |
| 61 } else { |
| 62 file_set.insert(*file); |
| 63 } |
| 64 } |
| 65 return file_set; |
| 66 } |
| 67 |
| 68 } // namespace |
| 69 |
| 70 int main(int argc, const char* argv[]) { |
| 71 if (argc < 2) { |
| 72 LOG(ERROR) << "Usage: md5sum <path/to/file_or_dir>..."; |
| 73 return 1; |
| 74 } |
| 75 const std::set<std::string> files = MakeFileSet(argv + 1); |
| 76 bool failed = false; |
| 77 std::string digest; |
| 78 for (std::set<std::string>::const_iterator it = files.begin(); |
| 79 it != files.end(); ++it) { |
| 80 if (!MD5Sum(it->c_str(), &digest)) |
| 81 failed = true; |
| 82 FilePath file_path(*it); |
| 83 file_util::AbsolutePath(&file_path); |
| 84 std::cout << digest << " " << file_path.value() << std::endl; |
| 85 } |
| 86 return failed; |
| 87 } |
OLD | NEW |