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 // Returns whether |path|'s MD5 was successfully written to |digest_string|. |
| 21 bool MD5Sum(const char* path, std::string* digest_string) { |
| 22 std::ifstream stream(path); |
| 23 if (!stream.good()) { |
| 24 LOG(ERROR) << "Could not open file " << path; |
| 25 return false; |
| 26 } |
| 27 base::MD5Context ctx; |
| 28 base::MD5Init(&ctx); |
| 29 char buf[1024]; |
| 30 while (stream.good()) { |
| 31 std::streamsize bytes_read = stream.readsome(buf, sizeof(buf)); |
| 32 if (bytes_read == 0) |
| 33 break; |
| 34 base::MD5Update(&ctx, base::StringPiece(buf, bytes_read)); |
| 35 } |
| 36 if (stream.fail()) { |
| 37 LOG(ERROR) << "Error reading file " << path; |
| 38 return false; |
| 39 } |
| 40 base::MD5Digest digest; |
| 41 base::MD5Final(&digest, &ctx); |
| 42 *digest_string = base::MD5DigestToBase16(digest); |
| 43 return true; |
| 44 } |
| 45 |
| 46 // Returns the set of all files contained in |files|. This handles directories |
| 47 // by walking them recursively. |
| 48 std::set<std::string> MakeFileSet(const char** files) { |
| 49 std::set<std::string> file_set; |
| 50 for (const char** file = files; *file; ++file) { |
| 51 FilePath file_path(*file); |
| 52 if (file_util::DirectoryExists(file_path)) { |
| 53 file_util::FileEnumerator file_enumerator( |
| 54 file_path, true /* recurse */, file_util::FileEnumerator::FILES); |
| 55 for (FilePath child, empty; (child = file_enumerator.Next()) != empty; ) { |
| 56 file_util::AbsolutePath(&child); |
| 57 file_set.insert(child.value()); |
| 58 } |
| 59 } else { |
| 60 file_set.insert(*file); |
| 61 } |
| 62 } |
| 63 return file_set; |
| 64 } |
| 65 |
| 66 } // namespace |
| 67 |
| 68 int main(int argc, const char* argv[]) { |
| 69 if (argc < 2) { |
| 70 LOG(ERROR) << "Usage: md5sum <path/to/file_or_dir>..."; |
| 71 return 1; |
| 72 } |
| 73 const std::set<std::string> files = MakeFileSet(argv + 1); |
| 74 bool failed = false; |
| 75 std::string digest; |
| 76 for (std::set<std::string>::const_iterator it = files.begin(); |
| 77 it != files.end(); ++it) { |
| 78 if (!MD5Sum(it->c_str(), &digest)) |
| 79 failed = true; |
| 80 FilePath file_path(*it); |
| 81 file_util::AbsolutePath(&file_path); |
| 82 std::cout << digest << " " << file_path.value() << std::endl; |
| 83 } |
| 84 return failed; |
| 85 } |
OLD | NEW |