]> git.decadent.org.uk Git - dak.git/blob - shania
sync
[dak.git] / shania
1 #!/usr/bin/env python
2
3 # Clean incoming of old unused files
4 # Copyright (C) 2000, 2001, 2002  James Troup <james@nocrew.org>
5 # $Id: shania,v 1.16 2002-05-23 09:54:23 troup Exp $
6
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
11
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20
21 ################################################################################
22
23 import os, stat, sys, time;
24 import utils;
25 import apt_pkg;
26
27 ################################################################################
28
29 Cnf = None;
30 Options = None;
31 del_dir = None;
32 delete_date = None;
33
34 ################################################################################
35
36 def usage (exit_code=0):
37     print """Usage: shania [OPTIONS]
38 Clean out incoming directories.
39
40   -d, --days=DAYS            remove anything older than DAYS old
41   -i, --incoming=INCOMING    the incoming directory to clean
42   -n, --no-action            don't do anything
43   -v, --verbose              explain what is being done
44   -h, --help                 show this help and exit"""
45
46     sys.exit(exit_code)
47
48 ################################################################################
49
50 def init ():
51     global delete_date, del_dir;
52
53     delete_date = int(time.time())-(int(Options["Days"])*84600);
54
55     # Ensure a directory exists to remove files to
56     if not Options["No-Action"]:
57         date = time.strftime("%Y-%m-%d", time.localtime(time.time()));
58         del_dir = Cnf["Dir::Morgue"] + '/' + Cnf["Shania::MorgueSubDir"] + '/' + date;
59         if not os.path.exists(del_dir):
60             os.makedirs(del_dir, 02775);
61         if not os.path.isdir(del_dir):
62             utils.fubar("%s must be a directory." % (del_dir));
63
64     # Move to the directory to clean
65     incoming = Options["Incoming"];
66     if incoming == "":
67         incoming = Cnf["Dir::Queue::Unchecked"];
68     os.chdir(incoming);
69
70 # Remove a file to the morgue
71 def remove (file):
72     if os.access(file, os.R_OK):
73         dest_filename = del_dir + '/' + os.path.basename(file);
74         # If the destination file exists; try to find another filename to use
75         if os.path.exists(dest_filename):
76             dest_filename = utils.find_next_free(dest_filename, 10);
77         utils.move(file, dest_filename, 0660);
78     else:
79         utils.warn("skipping '%s', permission denied." % (os.path.basename(file)));
80
81 # Removes any old files.
82 # [Used for Incoming/REJECT]
83 #
84 def flush_old ():
85     for file in os.listdir('.'):
86         if os.path.isfile(file):
87             if os.stat(file)[stat.ST_MTIME] < delete_date:
88                 if Options["No-Action"]:
89                     print "I: Would delete '%s'." % (os.path.basename(file));
90                 else:
91                     if Options["Verbose"]:
92                         print "Removing '%s' (to '%s')."  % (os.path.basename(file), del_dir);
93                     remove(file);
94             else:
95                 if Options["Verbose"]:
96                     print "Skipping, too new, '%s'." % (os.path.basename(file));
97
98 # Removes any files which are old orphans (not associated with a valid .changes file).
99 # [Used for Incoming]
100 #
101 def flush_orphans ():
102     all_files = {};
103     changes_files = [];
104
105     # Build up the list of all files in the directory
106     for i in os.listdir('.'):
107         if os.path.isfile(i):
108             all_files[i] = 1;
109             if i[-8:] == ".changes":
110                 changes_files.append(i);
111
112     # Proces all .changes and .dsc files.
113     for changes_filename in changes_files:
114         try:
115             changes = utils.parse_changes(changes_filename);
116             files = utils.build_file_list(changes);
117         except:
118             utils.warn("error processing '%s'; skipping it. [Got %s]" % (changes_filename, sys.exc_type));
119             continue;
120
121         dsc_files = {};
122         for file in files.keys():
123             if file[-4:] == ".dsc":
124                 try:
125                     dsc = utils.parse_changes(file);
126                     dsc_files = utils.build_file_list(dsc, is_a_dsc=1);
127                 except:
128                     utils.warn("error processing '%s'; skipping it. [Got %s]" % (file, sys.exc_type));
129                     continue;
130
131         # Ensure all the files we've seen aren't deleted
132         keys = [];
133         for i in (files.keys(), dsc_files.keys(), [changes_filename]):
134             keys.extend(i);
135         for key in keys:
136             if all_files.has_key(key):
137                 if Options["Verbose"]:
138                     print "Skipping, has parents, '%s'." % (key);
139                 del all_files[key];
140
141     # Anthing left at this stage is not referenced by a .changes (or
142     # a .dsc) and should be deleted if old enough.
143     for file in all_files.keys():
144         if os.stat(file)[stat.ST_MTIME] < delete_date:
145             if Options["No-Action"]:
146                 print "I: Would delete '%s'." % (os.path.basename(file));
147             else:
148                 if Options["Verbose"]:
149                     print "Removing '%s' (to '%s')."  % (os.path.basename(file), del_dir);
150                 remove(file);
151         else:
152             if Options["Verbose"]:
153                 print "Skipping, too new, '%s'." % (os.path.basename(file));
154
155 ################################################################################
156
157 def main ():
158     global Cnf, Options;
159
160     Cnf = utils.get_conf()
161
162     for i in ["Help", "Incoming", "No-Action", "Verbose" ]:
163         if not Cnf.has_key("Shania::Options::%s" % (i)):
164             Cnf["Shania::Options::%s" % (i)] = "";
165     if not Cnf.has_key("Shania::Options::Days"):
166         Cnf["Shania::Options::Days"] = "14";
167
168     Arguments = [('h',"help","Shania::Options::Help"),
169                  ('d',"days","Shania::Options::Days", "IntLevel"),
170                  ('i',"incoming","Shania::Options::Incoming", "HasArg"),
171                  ('n',"no-action","Shania::Options::No-Action"),
172                  ('v',"verbose","Shania::Options::Verbose")];
173
174     apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv);
175     Options = Cnf.SubTree("Shania::Options")
176
177     if Options["Help"]:
178         usage();
179
180     init();
181
182     if Options["Verbose"]:
183         print "Processing incoming..."
184     flush_orphans();
185
186     if os.path.exists("REJECT") and os.path.isdir("REJECT"):
187         if Options["Verbose"]:
188             print "Processing incoming/REJECT..."
189         os.chdir("REJECT");
190         flush_old();
191
192 #######################################################################################
193
194 if __name__ == '__main__':
195     main();