]> git.ipfire.org Git - pakfire.git/blame - pakfire/repository/cache.py
Add "clean all" command to pakfire and pakfire-builder.
[pakfire.git] / pakfire / repository / cache.py
CommitLineData
a2d1644c
MT
1#!/usr/bin/python
2
3import os
4import stat
5import time
6
a2d1644c
MT
7import pakfire.util as util
8from pakfire.constants import *
9
10class RepositoryCache(object):
11 """
12 An object that is able to cache all data that is loaded from a
13 remote repository.
14 """
15
16 def __init__(self, pakfire, repo):
17 self.pakfire = pakfire
18 self.repo = repo
19
c605d735 20 self.__created = None
a2d1644c
MT
21
22 @property
c605d735
MT
23 def created(self):
24 """
25 Tells us, if the cache was already created.
26 """
27 if self.__created is None:
28 self.__created = os.path.exists(self.path)
29
30 return self.__created
a2d1644c
MT
31
32 @property
33 def path(self):
34 return os.path.join(REPO_CACHE_DIR, self.pakfire.distro.release, \
35 self.repo.name, self.repo.arch)
36
c605d735
MT
37 def abspath(self, path, create=True):
38 if create:
39 self.create()
40
a2d1644c
MT
41 return os.path.join(self.path, path)
42
43 def create(self):
44 """
45 Create all necessary directories.
46 """
c605d735
MT
47 # Do nothing, if the cache has already been created.
48 if self.created:
49 return
50
a2d1644c 51 for path in ("mirrors", "packages", "repodata"):
c605d735 52 path = self.abspath(path, create=False)
a2d1644c
MT
53
54 if not os.path.exists(path):
55 os.makedirs(path)
56
c605d735
MT
57 self.__created = True
58
a2d1644c
MT
59 def exists(self, filename):
60 """
61 Returns True if a file exists and False if it doesn't.
62 """
63 return os.path.exists(self.abspath(filename))
64
65 def age(self, filename):
66 """
67 Returns the age of a downloaded file in minutes.
68 i.e. the time from download until now.
69 """
70 if not self.exists(filename):
71 return None
72
73 filename = self.abspath(filename)
74
75 # Creation time of the file
76 ctime = os.stat(filename)[stat.ST_CTIME]
77
78 return (time.time() - ctime) / 60
79
80 def open(self, filename, *args, **kwargs):
81 filename = self.abspath(filename)
82
83 return open(filename, *args, **kwargs)
84
85 def verify(self, filename, hash1):
86 """
87 Return a bool that indicates if a file matches the given hash.
88 """
89 return util.calc_hash1(self.abspath(filename)) == hash1
90
91 def remove(self, filename):
92 """
93 Remove a file from cache.
94 """
95 if not self.exists(filename):
96 return
97
98 filename = self.abspath(filename)
99 os.unlink(filename)
100
31267a64
MT
101 def destroy(self):
102 """
103 Remove all files from this cache.
104 """
105 if self.created:
106 util.rm(self.path)