import os
from subprocess import call, PIPE

from django.conf import settings
from django.core.management.base import BaseCommand, CommandError

import git


path = lambda *a: os.path.join(settings.MEDIA_ROOT, *a)


class Command(BaseCommand):  #pragma: no cover
    help = ("Compresses css and js assets defined in settings.MINIFY_BUNDLES")

    requires_model_validation = False

    def handle(self, **options):
        jar_path = (os.path.dirname(__file__), '..', '..', 'bin',
                'yuicompressor-2.4.4.jar')
        path_to_jar = os.path.realpath(os.path.join(*jar_path))

        v = ''
        if 'verbosity' in options and options['verbosity'] == '2':
            v = '-v'

        for ftype, bundle in settings.MINIFY_BUNDLES.iteritems():
            for name, files in bundle.iteritems():
                # Compile LESS files
                files_all = []
                for fn in files:
                    if fn.endswith('.less'):
                        fp = path(fn.lstrip('/'))
                        call('%s %s %s.css' % (settings.LESS_BIN, fp, fp),
                             shell=True)
                        # Outputs a *.less.css file.
                        files_all.append('%s.css' % fn)
                    else:
                        files_all.append(fn)

                concatted_file = path(ftype, '%s-all.%s' % (name, ftype,))
                compressed_file = path(ftype, '%s-min.%s' % (name, ftype,))
                real_files = [path(f.lstrip('/')) for f in files_all]

                # Concats the files.
                call("cat %s > %s" % (' '.join(real_files), concatted_file),
                     shell=True)

                # Compresses the concatenation.
                call("%s -jar %s %s %s -o %s" % (settings.JAVA_BIN, path_to_jar,
                     v, concatted_file, compressed_file), shell=True, stdout=PIPE)

        build_id_file = os.path.realpath(os.path.join(
            settings.ROOT, 'build.py'))

        gitid = lambda path: git.repo.Repo(os.path.join(settings.ROOT,
                path)).log('-1')[0].id_abbrev

        with open(build_id_file, 'w') as f:
            f.write('BUILD_ID_CSS = "%s"' % gitid('media/css'))
            f.write("\n")
            f.write('BUILD_ID_JS = "%s"' % gitid('media/js'))
            f.write("\n")
            f.write('BUILD_ID_IMG = "%s"' % gitid('media/img'))
            f.write("\n")

@@ -1,13 +1,58 @@
-import os
+from optparse import make_option%0Aimport os%0Aimport time
 %0Afro
@@ -171,22 +171,8 @@
 mand
-, CommandError
 %0A%0Aim
@@ -270,16 +270,17 @@
 and):  #
+ 
 pragma: 
@@ -371,80 +371,1211 @@
 S%22)%0A
-%0A    requires_model_validation = False%0A%0A    def handle(self, **options):
+    option_list = BaseCommand.option_list + (%0A        make_option('-u', '--update-only', action='store_true',%0A                    dest='do_update_only', help='Updates the hash only'),%0A    )%0A    requires_model_validation = False%0A    do_update_only = False%0A%0A    def update_hashes(self, update=False):%0A        def gitid(path):%0A            id = (git.repo.Repo(os.path.join(settings.ROOT, path))%0A                     .log('-1')%5B0%5D.id_abbrev)%0A            if update:%0A                # Adds a time based hash on to the build id.%0A                return '%25s-%25s' %25 (id, hex(int(time.time()))%5B2:%5D)%0A            return id%0A%0A        build_id_file = os.path.realpath(os.path.join(settings.ROOT,%0A                                                      'build.py'))%0A        with open(build_id_file, 'w') as f:%0A            f.write('BUILD_ID_CSS = %22%25s%22' %25 gitid('media/css'))%0A            f.write(%22%5Cn%22)%0A            f.write('BUILD_ID_JS = %22%25s%22' %25 gitid('media/js'))%0A            f.write(%22%5Cn%22)%0A            f.write('BUILD_ID_IMG = %22%25s%22' %25 gitid('media/img'))%0A            f.write(%22%5Cn%22)%0A%0A    def handle(self, **options):%0A        if options.get('do_update_only', False):%0A            self.update_hashes(update=True)%0A            return%0A
 %0A   
@@ -2948,21 +2948,8 @@
 BIN,
- path_to_jar,
 %0A   
@@ -2965,16 +2965,29 @@
         
+ path_to_jar,
  v, conc
@@ -3019,557 +3019,81 @@
 le),
- shell=True, stdout=PIPE)%0A%0A        build_id_file = os.path.realpath(os.path.join(%0A            settings.ROOT, 'build.py'))%0A%0A        gitid = lambda path: git.repo.Repo(os.path.join(settings.ROOT,%0A                path)).log('-1')%5B0%5D.id_abbrev%0A%0A        with open(build_id_file, 'w') as f:%0A            f.write('BUILD_ID_CSS = %22%25s%22' %25 gitid('media/css'))%0A            f.write(%22%5Cn%22)%0A            f.write('BUILD_ID_JS = %22%25s%22' %25 gitid('media/js'))%0A            f.write(%22%5Cn%22)%0A            f.write('BUILD_ID_IMG = %22%25s%22' %25 gitid('media/img'))%0A            f.write(%22%5Cn%22
+%0A                     shell=True, stdout=PIPE)%0A%0A        self.update_hashes(
 )%0A

add in -u or --update-only to append a hash to the build id (bug 660094)