import csv
import errno
from optparse import make_option

from django.contrib.redirects.models import Redirect
from django.contrib.sites.models import Site
from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import BaseCommand, CommandError


class Command(BaseCommand):
    help = "Import redirects from a CSV"
    args = "<file>"

    option_list = BaseCommand.option_list + (
        make_option('--site',
                    dest="site",
                    default=Site.objects.get_current(),
                    help=("The domain of the site to import redirects into. "
                          "(Defaults to current site.)")),
    )

    def execute(self, *args, **options):
        if len(args) != 1:
            raise CommandError("You must provide a file to import!")
        filepath = args[0]

        try:
            with open(filepath) as fp:
                reader = csv.reader(fp)
                header = reader.next()
                if sorted(header) != ["from", "to"]:
                    raise CommandError("File should have 'from' and 'to' "
                                       "columns!")

                dictreader = csv.DictReader(fp, header)

                site = options["site"]
                if not isinstance(site, Site):
                    try:
                        site = Site.objects.get(domain=options["site"])
                    except ObjectDoesNotExist:
                        raise CommandError("No site found for domain: %s"
                                           % options["site"])

                _create_redirects(site, dictreader)

        except IOError as e:
            if e.errno == errno.ENOENT:
                raise CommandError("The specified file does not exist!")
            else:
                raise


def _create_redirects(site, rows):
    for row in rows:
        old_path = row["from"]
        new_path = row["to"]
        redirect = Redirect(site=site, old_path=old_path, new_path=new_path)
        redirect.save()

@@ -49,16 +49,27 @@
 e_option
+%0Aimport sys
 %0A%0Afrom d
@@ -818,24 +818,25 @@
 port!%22)%0A
+%0A
         
 filepath
@@ -831,216 +831,205 @@
     
-filepath = args%5B0%5D%0A%0A
+self.site = options%5B%22site%22%5D%0A 
        
- try:%0A            with open(filepath) as fp:%0A                reader = csv.reader(fp)%0A                header = reader.next()%0A                if sorted(header) != %5B%22from%22, %22to%22%5D:%0A    
+if not isinstance(self.site, Site):%0A            try:%0A                self.site = Site.objects.get(domain=options%5B%22site%22%5D)%0A            except ObjectDoesNotExist:%0A
     
@@ -1064,41 +1064,36 @@
 or(%22
-File should have 'from' and 'to' 
+No site found for domain: %25s
 %22%0A  
@@ -1129,167 +1129,170 @@
     
-    %22columns!%22)%0A%0A                dictreader = csv.DictReader(fp, header)%0A%0A                site = options%5B%22site%22%5D%0A                if not isinstance(site, Site):
+%25 options%5B%22site%22%5D)%0A%0A        filepath = args%5B0%5D%0A%0A        if filepath == '-':%0A            rows = _get_rows(sys.stdin)%0A            _create_redirects(self.site, rows)
 %0A   
@@ -1288,32 +1288,38 @@
 , rows)%0A        
+else:%0A
             try:
@@ -1339,109 +1339,33 @@
     
-        site = Site.objects.get(domain=options%5B%22site%22%5D)%0A                    except ObjectDoesNotExist
+with open(filepath) as fp
 :%0A  
@@ -1386,125 +1386,33 @@
     
-    raise CommandError(%22No site found for domain: %25s%22%0A                                           %25 options%5B%22site%22%5D)%0A%0A
+rows = _get_rows(fp)%0A    
     
@@ -1446,23 +1446,22 @@
 ts(s
-ite, dictreader
+elf.site, rows
 )%0A%0A 
@@ -1463,24 +1463,28 @@
 s)%0A%0A        
+    
 except IOErr
@@ -1492,16 +1492,20 @@
 r as e:%0A
+    
         
@@ -1544,32 +1544,36 @@
                 
+    
 raise CommandErr
@@ -1617,32 +1617,36 @@
 !%22)%0A            
+    
 else:%0A          
@@ -1655,16 +1655,20 @@
     
+    
 raise%0A%0A%0A
 def 
@@ -1663,16 +1663,244 @@
 raise%0A%0A%0A
+def _get_rows(fp):%0A    reader = csv.reader(fp)%0A%0A    header = reader.next()%0A    if sorted(header) != %5B%22from%22, %22to%22%5D:%0A        raise CommandError(%22CSV should have 'from' and 'to' columns!%22)%0A%0A    return csv.DictReader(fp, header)%0A%0A%0A
 def _cre

Allow CSV importer to read from STDIN