]> 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  James Troup <james@nocrew.org>
5 # $Id: shania,v 1.12 2002-02-12 22:14:38 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 # 23:12|<aj> I will not hush!
30 # 23:12|<elmo> :>
31 # 23:12|<aj> Where there is injustice in the world, I shall be there!
32 # 23:13|<aj> I shall not be silenced!
33 # 23:13|<aj> The world shall know!
34 # 23:13|<aj> The world *must* know!
35 # 23:13|<elmo> oh dear, he's gone back to powerpuff girls... ;-)
36 # 23:13|<aj> yay powerpuff girls!!
37 # 23:13|<aj> buttercup's my favourite, who's yours?
38 # 23:14|<aj> you're backing away from the keyboard right now aren't you?
39 # 23:14|<aj> *AREN'T YOU*?!
40 # 23:15|<aj> I will not be treated like this.
41 # 23:15|<aj> I shall have my revenge.
42 # 23:15|<aj> I SHALL!!!
43
44 ################################################################################
45
46 Cnf = None;
47 Options = None;
48 del_dir = None;
49 delete_date = None;
50
51 ################################################################################
52
53 def usage (exit_code=0):
54     print """Usage: shania [OPTIONS]
55 Clean out incoming directories.
56
57   -d, --days=DAYS            remove anything older than DAYS old
58   -i, --incoming=INCOMING    the incoming directory to clean
59   -n, --no-action            don't do anything
60   -v, --verbose              explain what is being done
61   -h, --help                 show this help and exit"""
62
63     sys.exit(exit_code)
64
65 ################################################################################
66
67 def init ():
68     global delete_date, del_dir;
69
70     delete_date = int(time.time())-(int(Options["Days"])*84600);
71
72     # Ensure a directory exists to remove files to
73     if not Options["No-Action"]:
74         date = time.strftime("%Y-%m-%d", time.localtime(time.time()));
75         del_dir = Cnf["Dir::Morgue"] + '/' + Cnf["Shania::MorgueSubDir"] + '/' + date;
76         if not os.path.exists(del_dir):
77             os.makedirs(del_dir, 02775);
78         if not os.path.isdir(del_dir):
79             utils.fubar("%s must be a directory." % (del_dir));
80
81     # Move to the directory to clean
82     incoming = Options["Incoming"];
83     if incoming == "":
84         incoming = Cnf["Dir::IncomingDir"];
85     os.chdir(incoming);
86
87 # Remove a file to the morgue
88 def remove (file):
89     if os.access(file, os.R_OK):
90         dest_filename = del_dir + '/' + os.path.basename(file);
91         # If the destination file exists; try to find another filename to use
92         if os.path.exists(dest_filename):
93             dest_filename = utils.find_next_free(dest_filename, 10);
94         utils.move(file, dest_filename);
95     else:
96         utils.warn("skipping '%s', permission denied." % (os.path.basename(file)));
97
98 # Removes any old files.
99 # [Used for Incoming/REJECT]
100 #
101 def flush_old ():
102     for file in os.listdir('.'):
103         if os.path.isfile(file):
104             if os.stat(file)[stat.ST_MTIME] < delete_date:
105                 if Options["No-Action"]:
106                     print "I: Would delete '%s'." % (os.path.basename(file));
107                 else:
108                     if Options["Verbose"]:
109                         print "Removing '%s' (to '%s')."  % (os.path.basename(file), del_dir);
110                     remove(file);
111             else:
112                 if Options["Verbose"]:
113                     print "Skipping, too new, '%s'." % (os.path.basename(file));
114
115 # Removes any files which are old orphans (not associated with a valid .changes file).
116 # [Used for Incoming]
117 #
118 def flush_orphans ():
119     all_files = {};
120     changes_files = [];
121
122     # Build up the list of all files in the directory
123     for i in os.listdir('.'):
124         if os.path.isfile(i):
125             all_files[i] = 1;
126             if i[-8:] == ".changes":
127                 changes_files.append(i);
128
129     # Proces all .changes and .dsc files.
130     for changes_filename in changes_files:
131         try:
132             changes = utils.parse_changes(changes_filename, 0)
133             files = utils.build_file_list(changes, "");
134         except:
135             utils.warn("error processing '%s'; skipping it. [Got %s]" % (changes_filename, sys.exc_type));
136             continue;
137
138         dsc_files = {};
139         for file in files.keys():
140             if file[-4:] == ".dsc":
141                 try:
142                     dsc = utils.parse_changes(file, 0)
143                     dsc_files = utils.build_file_list(dsc, 1)
144                 except:
145                     utils.warn("error processing '%s'; skipping it. [Got %s]" % (file, sys.exc_type));
146                     continue;
147
148         # Ensure all the files we've seen aren't deleted
149         keys = [];
150         for i in (files.keys(), dsc_files.keys(), [changes_filename]):
151             keys.extend(i);
152         for key in keys:
153             if all_files.has_key(key):
154                 if Options["Verbose"]:
155                     print "Skipping, has parents, '%s'." % (key);
156                 del all_files[key];
157
158     # Anthing left at this stage is not referenced by a .changes (or
159     # a .dsc) and should be deleted if old enough.
160     for file in all_files.keys():
161         if os.stat(file)[stat.ST_MTIME] < delete_date:
162             if Options["No-Action"]:
163                 print "I: Would delete '%s'." % (os.path.basename(file));
164             else:
165                 if Options["Verbose"]:
166                     print "Removing '%s' (to '%s')."  % (os.path.basename(file), del_dir);
167                 remove(file);
168         else:
169             if Options["Verbose"]:
170                 print "Skipping, too new, '%s'." % (os.path.basename(file));
171
172 ################################################################################
173
174 def main ():
175     global Cnf, Options;
176
177     Cnf = utils.get_conf()
178
179     for i in ["Help", "Incoming", "No-Action", "Verbose" ]:
180         if not Cnf.has_key("Shania::Options::%s" % (i)):
181             Cnf["Shania::Options::%s" % (i)] = "";
182     if not Cnf.has_key("Shania::Options::Days"):
183         Cnf["Shania::Options::Days"] = "14";
184
185     Arguments = [('h',"help","Shania::Options::Help"),
186                  ('d',"days","Shania::Options::Days", "IntLevel"),
187                  ('i',"incoming","Shania::Options::Incoming", "HasArg"),
188                  ('n',"no-action","Shania::Options::No-Action"),
189                  ('v',"verbose","Shania::Options::Verbose")];
190
191     apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv);
192     Options = Cnf.SubTree("Shania::Options")
193
194     if Options["Help"]:
195         usage();
196
197     init ();
198
199     if Options["Verbose"]:
200         print "Processing incoming..."
201     flush_orphans();
202
203     if os.path.exists("REJECT") and os.path.isdir("REJECT"):
204         if Options["Verbose"]:
205             print "Processing incoming/REJECT..."
206         os.chdir("REJECT");
207         flush_old();
208
209 #######################################################################################
210
211 if __name__ == '__main__':
212     main()