refactor importlessons
authorJan Szejko <jan.szejko@gmail.com>
Wed, 13 Apr 2016 13:25:27 +0000 (15:25 +0200)
committerJan Szejko <jan.szejko@gmail.com>
Wed, 13 Apr 2016 13:25:27 +0000 (15:25 +0200)
catalogue/management/commands/importlessons.py

index e4c09e6..d179b16 100755 (executable)
@@ -7,14 +7,11 @@ import sys
 from optparse import make_option
 
 from django.core.management.base import BaseCommand
 from optparse import make_option
 
 from django.core.management.base import BaseCommand
-from django.core.management.color import color_style
 from django.db import transaction
 
 from catalogue.models import Lesson, Section
 from librarian import IOFile
 
 from django.db import transaction
 
 from catalogue.models import Lesson, Section
 from librarian import IOFile
 
-# from search import Index
-
 
 class Command(BaseCommand):
     option_list = BaseCommand.option_list + (
 
 class Command(BaseCommand):
     option_list = BaseCommand.option_list + (
@@ -28,11 +25,10 @@ class Command(BaseCommand):
     help = 'Imports lessons from the specified directories.'
     args = 'directory [directory ...]'
 
     help = 'Imports lessons from the specified directories.'
     args = 'directory [directory ...]'
 
-    def import_book(self, file_path, options, attachments, ignore_incomplete=False):
-        verbose = options.get('verbose')
-        iofile = IOFile.from_filename(os.path.join(self.curdir, file_path))
-        iofile.attachments = attachments
-        return Lesson.publish(iofile, ignore_incomplete)
+    def __init__(self):
+        super(Command, self).__init__()
+        self.options = None
+        self.levels = None
 
     @staticmethod
     def all_attachments(path):
 
     @staticmethod
     def all_attachments(path):
@@ -54,76 +50,26 @@ class Command(BaseCommand):
     @transaction.atomic
     def handle(self, *directories, **options):
 
     @transaction.atomic
     def handle(self, *directories, **options):
 
-        levels = set()
-        self.style = color_style()
-        
-        verbose = options.get('verbose')
-        self.curdir = os.path.abspath(os.curdir)
+        self.levels = set()
+
+        curdir = os.path.abspath(os.curdir)
+        self.options = options
 
         files_imported = 0
         files_skipped = 0
 
         for dir_name in directories:
 
         files_imported = 0
         files_skipped = 0
 
         for dir_name in directories:
-            abs_dir = os.path.join(self.curdir, dir_name)
+            abs_dir = os.path.join(curdir, dir_name)
             if not os.path.isdir(abs_dir):
                 print self.style.ERROR("%s: Not a directory. Skipping." % abs_dir)
             else:
             if not os.path.isdir(abs_dir):
                 print self.style.ERROR("%s: Not a directory. Skipping." % abs_dir)
             else:
-                att_dir = os.path.join(abs_dir, options['attachments'])
-                attachments = self.all_attachments(att_dir)
-
-                # files queue
-                files = sorted(os.listdir(abs_dir))
-                postponed = {}
-                ignore_incomplete = set()
-                while files:
-                    file_name = files.pop(0)
-                    file_path = os.path.join(abs_dir, file_name)
-                    file_base, ext = os.path.splitext(file_path)
-
-                    # Skip files that are not XML files
-                    if not ext == '.xml':
-                        continue
+                files_imported_dir, files_skipped_dir = self.import_from_dir(abs_dir)
+                files_imported += files_imported_dir
+                files_skipped += files_skipped_dir
 
 
-                    if verbose > 0:
-                        print "Parsing '%s'" % file_path
-                    else:
-                        sys.stdout.write('.')
-                        sys.stdout.flush()
-
-                    # Import book files
-                    try:
-                        lesson = self.import_book(
-                            file_path, options, attachments,
-                            ignore_incomplete=file_name in ignore_incomplete)
-                    except Section.IncompleteError, e:
-                        if file_name not in postponed or postponed[file_name] < files_imported:
-                            # Push it back into the queue, maybe the missing lessons will show up.
-                            if verbose > 0:
-                                print self.style.NOTICE('Waiting for missing lessons.')
-                            files.append(file_name)
-                            postponed[file_name] = files_imported
-                        elif options['ignore_incomplete'] and file_name not in ignore_incomplete:
-                            files.append(file_name)
-                            ignore_incomplete.add(file_name)
-                            postponed[file_name] = files_imported
-                        else:
-                            # We're in a loop, nothing's being imported - some lesson is really missing.
-                            raise e
-                    except BaseException:
-                        import traceback
-                        traceback.print_exc()
-                        files_skipped += 1
-                    else:
-                        files_imported += 1
-                        if hasattr(lesson, 'level'):
-                            levels.add(lesson.level)
-                    finally:
-                        if verbose > 0:
-                            print
-
-        if levels:
+        if self.levels:
             print "Rebuilding level packages:"
             print "Rebuilding level packages:"
-            for level in levels:
+            for level in self.levels:
                 print level.name
                 level.build_packages()
 
                 print level.name
                 level.build_packages()
 
@@ -132,3 +78,59 @@ class Command(BaseCommand):
         print "Results: %d files imported, %d skipped, %d total." % (
             files_imported, files_skipped, files_imported + files_skipped)
         print
         print "Results: %d files imported, %d skipped, %d total." % (
             files_imported, files_skipped, files_imported + files_skipped)
         print
+
+    def import_from_dir(self, abs_dir):
+        verbose = self.options.get('verbose')
+        files_imported = 0
+        files_skipped = 0
+        att_dir = os.path.join(abs_dir, self.options['attachments'])
+        attachments = self.all_attachments(att_dir)
+        # files queue
+        files = sorted(os.listdir(abs_dir))
+        postponed = {}
+        ignore_incomplete = set()
+        while files:
+            file_name = files.pop(0)
+            file_path = os.path.join(abs_dir, file_name)
+            file_base, ext = os.path.splitext(file_path)
+
+            # Skip files that are not XML files
+            if not ext == '.xml':
+                continue
+
+            if verbose > 0:
+                print "Parsing '%s'" % file_path
+            else:
+                sys.stdout.write('.')
+                sys.stdout.flush()
+
+            try:
+                iofile = IOFile.from_filename(file_path)
+                iofile.attachments = attachments
+                lesson = Lesson.publish(iofile, file_name in ignore_incomplete)
+            except Section.IncompleteError:
+                if file_name not in postponed or postponed[file_name] < files_imported:
+                    # Push it back into the queue, maybe the missing lessons will show up.
+                    if verbose > 0:
+                        print self.style.NOTICE('Waiting for missing lessons.')
+                    files.append(file_name)
+                    postponed[file_name] = files_imported
+                elif self.options['ignore_incomplete'] and file_name not in ignore_incomplete:
+                    files.append(file_name)
+                    ignore_incomplete.add(file_name)
+                    postponed[file_name] = files_imported
+                else:
+                    # We're in a loop, nothing's being imported - some lesson is really missing.
+                    raise
+            except BaseException:
+                import traceback
+                traceback.print_exc()
+                files_skipped += 1
+            else:
+                files_imported += 1
+                if hasattr(lesson, 'level'):
+                    self.levels.add(lesson.level)
+            finally:
+                if verbose > 0:
+                    print
+        return files_imported, files_skipped