shania 6.8 KB
Newer Older
J
James Troup 已提交
1 2 3
#!/usr/bin/env python

# Clean incoming of old unused files
J
James Troup 已提交
4
# Copyright (C) 2000, 2001, 2002  James Troup <james@nocrew.org>
J
sync  
James Troup 已提交
5
# $Id: shania,v 1.16 2002-05-23 09:54:23 troup Exp $
J
James Troup 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

################################################################################

J
James Troup 已提交
23 24
import os, stat, sys, time;
import utils;
J
James Troup 已提交
25 26 27
import apt_pkg;

################################################################################
J
James Troup 已提交
28

J
rewrite  
James Troup 已提交
29 30 31
Cnf = None;
Options = None;
del_dir = None;
J
James Troup 已提交
32
delete_date = None;
J
James Troup 已提交
33 34 35

################################################################################

J
James Troup 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49
def usage (exit_code=0):
    print """Usage: shania [OPTIONS]
Clean out incoming directories.

  -d, --days=DAYS            remove anything older than DAYS old
  -i, --incoming=INCOMING    the incoming directory to clean
  -n, --no-action            don't do anything
  -v, --verbose              explain what is being done
  -h, --help                 show this help and exit"""

    sys.exit(exit_code)

################################################################################

J
rewrite  
James Troup 已提交
50 51
def init ():
    global delete_date, del_dir;
J
James Troup 已提交
52

J
rewrite  
James Troup 已提交
53 54 55 56 57 58 59 60 61 62 63 64 65
    delete_date = int(time.time())-(int(Options["Days"])*84600);

    # Ensure a directory exists to remove files to
    if not Options["No-Action"]:
        date = time.strftime("%Y-%m-%d", time.localtime(time.time()));
        del_dir = Cnf["Dir::Morgue"] + '/' + Cnf["Shania::MorgueSubDir"] + '/' + date;
        if not os.path.exists(del_dir):
            os.makedirs(del_dir, 02775);
        if not os.path.isdir(del_dir):
            utils.fubar("%s must be a directory." % (del_dir));

    # Move to the directory to clean
    incoming = Options["Incoming"];
J
James Troup 已提交
66
    if incoming == "":
J
James Troup 已提交
67
        incoming = Cnf["Dir::Queue::Unchecked"];
J
James Troup 已提交
68 69
    os.chdir(incoming);

J
rewrite  
James Troup 已提交
70 71 72 73 74 75 76
# Remove a file to the morgue
def remove (file):
    if os.access(file, os.R_OK):
        dest_filename = del_dir + '/' + os.path.basename(file);
        # If the destination file exists; try to find another filename to use
        if os.path.exists(dest_filename):
            dest_filename = utils.find_next_free(dest_filename, 10);
77
        utils.move(file, dest_filename, 0660);
J
rewrite  
James Troup 已提交
78 79
    else:
        utils.warn("skipping '%s', permission denied." % (os.path.basename(file)));
J
James Troup 已提交
80

J
rewrite  
James Troup 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
# Removes any old files.
# [Used for Incoming/REJECT]
#
def flush_old ():
    for file in os.listdir('.'):
        if os.path.isfile(file):
            if os.stat(file)[stat.ST_MTIME] < delete_date:
                if Options["No-Action"]:
                    print "I: Would delete '%s'." % (os.path.basename(file));
                else:
                    if Options["Verbose"]:
                        print "Removing '%s' (to '%s')."  % (os.path.basename(file), del_dir);
                    remove(file);
            else:
                if Options["Verbose"]:
                    print "Skipping, too new, '%s'." % (os.path.basename(file));

# Removes any files which are old orphans (not associated with a valid .changes file).
# [Used for Incoming]
#
def flush_orphans ():
    all_files = {};
    changes_files = [];
J
James Troup 已提交
104

J
James Troup 已提交
105 106 107 108
    # Build up the list of all files in the directory
    for i in os.listdir('.'):
        if os.path.isfile(i):
            all_files[i] = 1;
J
rewrite  
James Troup 已提交
109
            if i[-8:] == ".changes":
J
James Troup 已提交
110 111 112 113 114
                changes_files.append(i);

    # Proces all .changes and .dsc files.
    for changes_filename in changes_files:
        try:
115 116
            changes = utils.parse_changes(changes_filename);
            files = utils.build_file_list(changes);
J
James Troup 已提交
117
        except:
118
            utils.warn("error processing '%s'; skipping it. [Got %s]" % (changes_filename, sys.exc_type));
J
James Troup 已提交
119 120 121 122
            continue;

        dsc_files = {};
        for file in files.keys():
J
rewrite  
James Troup 已提交
123
            if file[-4:] == ".dsc":
J
James Troup 已提交
124
                try:
125 126
                    dsc = utils.parse_changes(file);
                    dsc_files = utils.build_file_list(dsc, is_a_dsc=1);
J
James Troup 已提交
127
                except:
J
rewrite  
James Troup 已提交
128
                    utils.warn("error processing '%s'; skipping it. [Got %s]" % (file, sys.exc_type));
J
James Troup 已提交
129 130
                    continue;

J
rewrite  
James Troup 已提交
131 132 133 134 135 136 137 138 139
        # Ensure all the files we've seen aren't deleted
        keys = [];
        for i in (files.keys(), dsc_files.keys(), [changes_filename]):
            keys.extend(i);
        for key in keys:
            if all_files.has_key(key):
                if Options["Verbose"]:
                    print "Skipping, has parents, '%s'." % (key);
                del all_files[key];
J
James Troup 已提交
140

J
rewrite  
James Troup 已提交
141 142
    # Anthing left at this stage is not referenced by a .changes (or
    # a .dsc) and should be deleted if old enough.
J
James Troup 已提交
143 144
    for file in all_files.keys():
        if os.stat(file)[stat.ST_MTIME] < delete_date:
J
rewrite  
James Troup 已提交
145 146
            if Options["No-Action"]:
                print "I: Would delete '%s'." % (os.path.basename(file));
J
James Troup 已提交
147
            else:
J
rewrite  
James Troup 已提交
148
                if Options["Verbose"]:
J
James Troup 已提交
149
                    print "Removing '%s' (to '%s')."  % (os.path.basename(file), del_dir);
J
rewrite  
James Troup 已提交
150
                remove(file);
J
James Troup 已提交
151
        else:
J
rewrite  
James Troup 已提交
152
            if Options["Verbose"]:
J
James Troup 已提交
153
                print "Skipping, too new, '%s'." % (os.path.basename(file));
J
James Troup 已提交
154 155 156

################################################################################

J
rewrite  
James Troup 已提交
157 158
def main ():
    global Cnf, Options;
J
James Troup 已提交
159

160
    Cnf = utils.get_conf()
R
Ryan Murray 已提交
161 162

    for i in ["Help", "Incoming", "No-Action", "Verbose" ]:
163 164 165 166
	if not Cnf.has_key("Shania::Options::%s" % (i)):
	    Cnf["Shania::Options::%s" % (i)] = "";
    if not Cnf.has_key("Shania::Options::Days"):
	Cnf["Shania::Options::Days"] = "14";
R
Ryan Murray 已提交
167

J
James Troup 已提交
168
    Arguments = [('h',"help","Shania::Options::Help"),
169
                 ('d',"days","Shania::Options::Days", "IntLevel"),
J
rewrite  
James Troup 已提交
170 171 172 173 174 175 176
                 ('i',"incoming","Shania::Options::Incoming", "HasArg"),
                 ('n',"no-action","Shania::Options::No-Action"),
                 ('v',"verbose","Shania::Options::Verbose")];

    apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv);
    Options = Cnf.SubTree("Shania::Options")

J
James Troup 已提交
177 178 179
    if Options["Help"]:
	usage();

J
sync  
James Troup 已提交
180
    init();
J
rewrite  
James Troup 已提交
181 182 183 184 185 186 187 188 189 190

    if Options["Verbose"]:
        print "Processing incoming..."
    flush_orphans();

    if os.path.exists("REJECT") and os.path.isdir("REJECT"):
        if Options["Verbose"]:
            print "Processing incoming/REJECT..."
        os.chdir("REJECT");
        flush_old();
J
James Troup 已提交
191 192 193 194

#######################################################################################

if __name__ == '__main__':
J
sync  
James Troup 已提交
195
    main();