Gitlab CSE Unil

adim_cleanup.py 2.57 KB
Newer Older
M. Chardon's avatar
M. Chardon committed
1
from django.core.management.base import CommandError, BaseCommand
2
3
4
5
6
7
8
from django.conf import settings
from adim.models import AnObj
import os
import sys
from optparse import make_option


M. Chardon's avatar
M. Chardon committed
9
class Command(BaseCommand):
10
    help = 'Remove image files not used by an Annotable Object'
M. Chardon's avatar
M. Chardon committed
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

    def add_arguments(self, parser):
        parser.add_argument(
            '--noinput',
            action='store_false',
            dest='interactive',
            default=True,
            help="Do NOT prompt the user for input of any kind."
        )
        parser.add_argument(
            '-n',
            '--dry-run',
            action='store_true',
            dest='dry_run',
            default=False,
            help="Do everything except modify the filesystem."
        )
28
29

    def __init__(self, *args, **kwargs):
M. Chardon's avatar
M. Chardon committed
30
        super(Command, self).__init__(*args, **kwargs)
31
32
33
34
35
36
37
38
39
40
41
42
        self.dry_run = False
        self.interactive = True
        self.verbosity = 1

    def set_options(self, **options):
        """
        Set instance variables based on an options dict
        """
        self.interactive = options['interactive']
        self.dry_run = options['dry_run']
        self.verbosity = int(options['verbosity']) if self.interactive else 0

M. Chardon's avatar
M. Chardon committed
43
    def handle(self, *args, **options):
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
        self.set_options(**options)

        anobj_uuid_list = AnObj.objects.all().values_list('uuid', flat=True)
        images_path = os.path.join(settings.MEDIA_ROOT, 'ao_images')
        files_to_remove = []
        for root, dirs, files in os.walk(unicode(images_path)):
            files_to_remove.extend(os.path.join(root, f) for f in files if f[:32] not in anobj_uuid_list)

        if len(files_to_remove) == 0:
            if self.verbosity >= 1:
                print "No files to remove."
            sys.exit(0)

        if self.verbosity >= 1:
            print "List of files to be deleted: "
            print "---------------------------"
            print "\n".join(f.replace(settings.MEDIA_ROOT, '    .') for f in files_to_remove)
            print "\n"

        message = "Continue and delete {} files ? [yes/NO] ".format(len(files_to_remove))
        if self.interactive and raw_input(message) != 'yes':
            raise CommandError("Removing unused files cancelled.")

        if not self.dry_run:
            for f in files_to_remove:
                try:
                    os.unlink(f)
                except OSError:
                    if self.verbosity >= 1:
                        print "# Unable to delete file {}\n  -> {}".format(f, sys.exc_info()[1][1])

        if self.verbosity >= 1:
            print "Done."