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