byhash.cc 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. /* ######################################################################
  4. ByHash
  5. ByHash helper functions
  6. ##################################################################### */
  7. /*}}}*/
  8. // Include Files /*{{{*/
  9. #include <config.h>
  10. #include<algorithm>
  11. #include<string>
  12. #include <unistd.h>
  13. #include <sys/stat.h>
  14. #define st_mtim st_mtimespec
  15. #include <apt-pkg/fileutl.h>
  16. #include <apt-pkg/hashes.h>
  17. #include "byhash.h"
  18. // Delete all files in a directory except the most recent N ones
  19. void DeleteAllButMostRecent(std::string dir, int KeepFiles)
  20. {
  21. struct Cmp {
  22. bool operator() (const std::string& lhs, const std::string& rhs) {
  23. struct stat buf_l, buf_r;
  24. stat(lhs.c_str(), &buf_l);
  25. stat(rhs.c_str(), &buf_r);
  26. if (buf_l.st_mtim.tv_sec == buf_r.st_mtim.tv_sec)
  27. return buf_l.st_mtim.tv_nsec < buf_r.st_mtim.tv_nsec;
  28. return buf_l.st_mtim.tv_sec < buf_r.st_mtim.tv_sec;
  29. }
  30. };
  31. if (!DirectoryExists(dir))
  32. return;
  33. auto files = GetListOfFilesInDir(dir, false);
  34. std::sort(files.begin(), files.end(), Cmp());
  35. for (auto I=files.begin(); I<files.end()-KeepFiles; ++I)
  36. RemoveFile("DeleteAllButMostRecent", *I);
  37. }
  38. // Takes a input filename (e.g. binary-i386/Packages) and a hashstring
  39. // of the Input data and transforms it into a suitable by-hash filename
  40. std::string GenByHashFilename(std::string ByHashOutputFile, HashString const &h)
  41. {
  42. std::string const ByHash = "/by-hash/" + h.HashType() + "/" + h.HashValue();
  43. size_t trailing_slash = ByHashOutputFile.find_last_of("/");
  44. if (trailing_slash == std::string::npos)
  45. trailing_slash = 0;
  46. ByHashOutputFile = ByHashOutputFile.replace(
  47. trailing_slash,
  48. ByHashOutputFile.substr(trailing_slash+1).size()+1,
  49. ByHash);
  50. return ByHashOutputFile;
  51. }