assets.py 26.3 KB
Newer Older
Will Daly committed
1 2 3
"""
Asset compilation and collection.
"""
David Baumgold committed
4

5
from __future__ import print_function
6
from datetime import datetime
Omar Khan committed
7 8
from functools import wraps
from threading import Timer
Will Daly committed
9
import argparse
David Baumgold committed
10 11 12
import glob
import traceback

13
from paver import tasks
14
from paver.easy import sh, path, task, cmdopts, needs, consume_args, call_task, no_help
Omar Khan committed
15
from watchdog.observers.polling import PollingObserver
16
from watchdog.events import PatternMatchingEventHandler
David Baumgold committed
17

Will Daly committed
18 19
from .utils.envs import Env
from .utils.cmd import cmd, django_cmd
20
from .utils.timer import timed
Will Daly committed
21

22 23
from openedx.core.djangoapps.theming.paver_helpers import get_theme_paths

24 25
# setup baseline paths

26
ALL_SYSTEMS = ['lms', 'studio']
Will Daly committed
27
COFFEE_DIRS = ['lms', 'cms', 'common']
28 29 30 31 32 33 34 35 36 37 38 39 40

LMS = 'lms'
CMS = 'cms'

SYSTEMS = {
    'lms': LMS,
    'cms': CMS,
    'studio': CMS
}

# Common lookup paths that are added to the lookup paths for all sass compilations
COMMON_LOOKUP_PATHS = [
    path("common/static"),
41
    path("common/static/sass"),
42 43
    path('node_modules'),
    path('node_modules/edx-pattern-library/node_modules'),
44
]
45

46 47 48
# A list of NPM installed libraries that should be copied into the common
# static directory.
NPM_INSTALLED_LIBRARIES = [
49 50
    'jquery/dist/jquery.js',
    'jquery-migrate/dist/jquery-migrate.js',
51
    'jquery.scrollto/jquery.scrollTo.js',
52
    'underscore/underscore.js',
53
    'underscore.string/dist/underscore.string.js',
54
    'picturefill/dist/picturefill.js',
55
    'backbone/backbone.js',
56
    'edx-ui-toolkit/node_modules/backbone.paginator/lib/backbone.paginator.js',
57
    'backbone-validation/dist/backbone-validation-min.js',
58 59 60 61 62
]

# Directory to install static vendor files
NPM_VENDOR_DIRECTORY = path("common/static/common/js/vendor")

63 64 65 66
# system specific lookup path additions, add sass dirs if one system depends on the sass files for other systems
SASS_LOOKUP_DEPENDENCIES = {
    'cms': [path('lms') / 'static' / 'sass' / 'partials', ],
}
67

68 69 70
# Collectstatic log directory setting
COLLECTSTATIC_LOG_DIR_ARG = "collect_log_dir"

71

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
def get_sass_directories(system, theme_dir=None):
    """
    Determine the set of SASS directories to be compiled for the specified list of system and theme
    and return a list of those directories.

    Each item in the list is dict object containing the following key-value pairs.
    {
        "sass_source_dir": "",  # directory where source sass files are present
        "css_destination_dir": "",  # destination where css files would be placed
        "lookup_paths": [],  # list of directories to be passed as lookup paths for @import resolution.
    }

    if theme_dir is empty or None then return sass directories for the given system only. (i.e. lms or cms)

    :param system: name if the system for which to compile sass e.g. 'lms', 'cms'
    :param theme_dir: absolute path of theme for which to compile sass files.
    """
    if system not in SYSTEMS:
        raise ValueError("'system' must be one of ({allowed_values})".format(allowed_values=', '.join(SYSTEMS.keys())))
    system = SYSTEMS[system]

    applicable_directories = list()

    if theme_dir:
        # Add theme sass directories
        applicable_directories.extend(
            get_theme_sass_dirs(system, theme_dir)
        )
    else:
        # add system sass directories
        applicable_directories.extend(
            get_system_sass_dirs(system)
        )

    return applicable_directories


def get_common_sass_directories():
    """
    Determine the set of common SASS directories to be compiled for all the systems and themes.

    Each item in the returned list is dict object containing the following key-value pairs.
    {
        "sass_source_dir": "",  # directory where source sass files are present
        "css_destination_dir": "",  # destination where css files would be placed
        "lookup_paths": [],  # list of directories to be passed as lookup paths for @import resolution.
    }
    """
    applicable_directories = list()

    # add common sass directories
    applicable_directories.append({
        "sass_source_dir": path("common/static/sass"),
        "css_destination_dir": path("common/static/css"),
        "lookup_paths": COMMON_LOOKUP_PATHS,
    })
128

129
    return applicable_directories
130 131


132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
def get_theme_sass_dirs(system, theme_dir):
    """
    Return list of sass dirs that need to be compiled for the given theme.

    :param system: name if the system for which to compile sass e.g. 'lms', 'cms'
    :param theme_dir: absolute path of theme for which to compile sass files.
    """
    if system not in ('lms', 'cms'):
        raise ValueError('"system" must either be "lms" or "cms"')

    dirs = []

    system_sass_dir = path(system) / "static" / "sass"
    sass_dir = theme_dir / system / "static" / "sass"
    css_dir = theme_dir / system / "static" / "css"

    dependencies = SASS_LOOKUP_DEPENDENCIES.get(system, [])
    if sass_dir.isdir():
        css_dir.mkdir_p()

        # first compile lms sass files and place css in theme dir
        dirs.append({
            "sass_source_dir": system_sass_dir,
            "css_destination_dir": css_dir,
            "lookup_paths": dependencies + [
                sass_dir / "partials",
                system_sass_dir / "partials",
                system_sass_dir,
            ],
        })

        # now compile theme sass files and override css files generated from lms
        dirs.append({
            "sass_source_dir": sass_dir,
            "css_destination_dir": css_dir,
            "lookup_paths": dependencies + [
                sass_dir / "partials",
                system_sass_dir / "partials",
                system_sass_dir,
            ],
        })

    return dirs


def get_system_sass_dirs(system):
    """
    Return list of sass dirs that need to be compiled for the given system.

    :param system: name if the system for which to compile sass e.g. 'lms', 'cms'
    """
    if system not in ('lms', 'cms'):
        raise ValueError('"system" must either be "lms" or "cms"')

    dirs = []
    sass_dir = path(system) / "static" / "sass"
    css_dir = path(system) / "static" / "css"

    dependencies = SASS_LOOKUP_DEPENDENCIES.get(system, [])
    dirs.append({
        "sass_source_dir": sass_dir,
        "css_destination_dir": css_dir,
        "lookup_paths": dependencies + [
            sass_dir / "partials",
            sass_dir,
        ],
    })

    if system == 'lms':
        dirs.append({
            "sass_source_dir": path(system) / "static" / "certificates" / "sass",
            "css_destination_dir": path(system) / "static" / "certificates" / "css",
            "lookup_paths": [
                sass_dir / "partials",
                sass_dir
            ],
        })

    return dirs


def get_watcher_dirs(theme_dirs=None, themes=None):
    """
    Return sass directories that need to be added to sass watcher.

    Example:
        >> get_watcher_dirs('/edx/app/edx-platform/themes', ['red-theme'])
        [
            'common/static',
            'common/static/sass',
            'lms/static/sass',
            'lms/static/sass/partials',
            '/edx/app/edxapp/edx-platform/themes/red-theme/lms/static/sass',
            '/edx/app/edxapp/edx-platform/themes/red-theme/lms/static/sass/partials',
            'cms/static/sass',
            'cms/static/sass/partials',
            '/edx/app/edxapp/edx-platform/themes/red-theme/cms/static/sass/partials',
        ]

    Parameters:
        theme_dirs (list): list of theme base directories.
        themes (list): list containing names of themes
    Returns:
        (list): dirs that need to be added to sass watchers.
    """
    dirs = []
    dirs.extend(COMMON_LOOKUP_PATHS)
    if theme_dirs and themes:
        # Register sass watchers for all the given themes
        themes = get_theme_paths(themes=themes, theme_dirs=theme_dirs)
        for theme in themes:
            for _dir in get_sass_directories('lms', theme) + get_sass_directories('cms', theme):
                dirs.append(_dir['sass_source_dir'])
                dirs.extend(_dir['lookup_paths'])

    # Register sass watchers for lms and cms
    for _dir in get_sass_directories('lms') + get_sass_directories('cms') + get_common_sass_directories():
        dirs.append(_dir['sass_source_dir'])
        dirs.extend(_dir['lookup_paths'])

    # remove duplicates
    dirs = list(set(dirs))
    return dirs


Omar Khan committed
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
def debounce(seconds=1):
    """
    Prevents the decorated function from being called more than every `seconds`
    seconds. Waits until calls stop coming in before calling the decorated
    function.
    """
    def decorator(func):  # pylint: disable=missing-docstring
        func.timer = None

        @wraps(func)
        def wrapper(*args, **kwargs):  # pylint: disable=missing-docstring
            def call():  # pylint: disable=missing-docstring
                func(*args, **kwargs)
                func.timer = None
            if func.timer:
                func.timer.cancel()
            func.timer = Timer(seconds, call)
            func.timer.start()

        return wrapper
    return decorator


280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
class CoffeeScriptWatcher(PatternMatchingEventHandler):
    """
    Watches for coffeescript changes
    """
    ignore_directories = True
    patterns = ['*.coffee']

    def register(self, observer):
        """
        register files with observer
        """
        dirnames = set()
        for filename in sh(coffeescript_files(), capture=True).splitlines():
            dirnames.add(path(filename).dirname())
        for dirname in dirnames:
            observer.schedule(self, dirname)

Omar Khan committed
297 298
    @debounce()
    def on_any_event(self, event):
299 300 301
        print('\tCHANGED:', event.src_path)
        try:
            compile_coffeescript(event.src_path)
302
        except Exception:  # pylint: disable=broad-except
303 304 305 306 307 308 309 310 311 312 313
            traceback.print_exc()


class SassWatcher(PatternMatchingEventHandler):
    """
    Watches for sass file changes
    """
    ignore_directories = True
    patterns = ['*.scss']
    ignore_patterns = ['common/static/xmodule/*']

314
    def register(self, observer, directories):
315 316
        """
        register files with observer
317 318 319 320

        Arguments:
            observer (watchdog.observers.Observer): sass file observer
            directories (list): list of directories to be register for sass watcher.
321
        """
322
        for dirname in directories:
323 324 325 326 327 328 329 330
            paths = []
            if '*' in dirname:
                paths.extend(glob.glob(dirname))
            else:
                paths.append(dirname)
            for dirname in paths:
                observer.schedule(self, dirname, recursive=True)

Omar Khan committed
331 332
    @debounce()
    def on_any_event(self, event):
333 334
        print('\tCHANGED:', event.src_path)
        try:
335 336
            compile_sass()      # pylint: disable=no-value-for-parameter
        except Exception:       # pylint: disable=broad-except
337 338 339 340 341 342 343 344 345 346
            traceback.print_exc()


class XModuleSassWatcher(SassWatcher):
    """
    Watches for sass file changes
    """
    ignore_directories = True
    ignore_patterns = []

Omar Khan committed
347 348
    @debounce()
    def on_any_event(self, event):
349 350 351
        print('\tCHANGED:', event.src_path)
        try:
            process_xmodule_assets()
352
        except Exception:  # pylint: disable=broad-except
353 354 355
            traceback.print_exc()


356 357 358 359 360 361 362 363 364 365 366 367 368
class XModuleAssetsWatcher(PatternMatchingEventHandler):
    """
    Watches for css and js file changes
    """
    ignore_directories = True
    patterns = ['*.css', '*.js']

    def register(self, observer):
        """
        Register files with observer
        """
        observer.schedule(self, 'common/lib/xmodule/', recursive=True)

Omar Khan committed
369 370
    @debounce()
    def on_any_event(self, event):
371 372 373 374 375 376 377 378 379 380
        print('\tCHANGED:', event.src_path)
        try:
            process_xmodule_assets()
        except Exception:  # pylint: disable=broad-except
            traceback.print_exc()

        # To refresh the hash values of static xmodule content
        restart_django_servers()


381
def coffeescript_files():
Will Daly committed
382
    """
383
    return find command for paths containing coffee files
Will Daly committed
384
    """
David Baumgold committed
385
    dirs = " ".join(Env.REPO_ROOT / coffee_dir for coffee_dir in COFFEE_DIRS)
386 387 388
    return cmd('find', dirs, '-type f', '-name \"*.coffee\"')


389 390
@task
@no_help
391
@timed
392 393 394 395 396 397
def compile_coffeescript(*files):
    """
    Compile CoffeeScript to JavaScript.
    """
    if not files:
        files = ["`{}`".format(coffeescript_files())]
Will Daly committed
398
    sh(cmd(
399
        "node_modules/.bin/coffee", "--compile", *files
Will Daly committed
400 401 402
    ))


403 404
@task
@no_help
405
@cmdopts([
406
    ('system=', 's', 'The system to compile sass for (defaults to all)'),
407 408
    ('theme-dirs=', '-td', 'Theme dirs containing all themes (defaults to None)'),
    ('themes=', '-t', 'The theme to compile sass for (defaults to None)'),
409 410 411
    ('debug', 'd', 'Debug mode'),
    ('force', '', 'Force full compilation'),
])
412
@timed
413
def compile_sass(options):
Will Daly committed
414
    """
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    Compile Sass to CSS. If command is called without any arguments, it will
    only compile lms, cms sass for the open source theme. And none of the comprehensive theme's sass would be compiled.

    If you want to compile sass for all comprehensive themes you will have to run compile_sass
    specifying all the themes that need to be compiled..

    The following is a list of some possible ways to use this command.

    Command:
        paver compile_sass
    Description:
        compile sass files for both lms and cms. If command is called like above (i.e. without any arguments) it will
        only compile lms, cms sass for the open source theme. None of the theme's sass will be compiled.

    Command:
        paver compile_sass --theme-dirs /edx/app/edxapp/edx-platform/themes --themes=red-theme
    Description:
        compile sass files for both lms and cms for 'red-theme' present in '/edx/app/edxapp/edx-platform/themes'

    Command:
        paver compile_sass --theme-dirs=/edx/app/edxapp/edx-platform/themes --themes red-theme stanford-style
    Description:
        compile sass files for both lms and cms for 'red-theme' and 'stanford-style' present in
        '/edx/app/edxapp/edx-platform/themes'.

    Command:
        paver compile_sass --system=cms
            --theme-dirs /edx/app/edxapp/edx-platform/themes /edx/app/edxapp/edx-platform/common/test/
            --themes red-theme stanford-style test-theme
    Description:
        compile sass files for cms only for 'red-theme', 'stanford-style' and 'test-theme' present in
        '/edx/app/edxapp/edx-platform/themes' and '/edx/app/edxapp/edx-platform/common/test/'.

    """
    debug = options.get('debug')
    force = options.get('force')
    systems = getattr(options, 'system', ALL_SYSTEMS)
    themes = getattr(options, 'themes', [])
    theme_dirs = getattr(options, 'theme-dirs', [])

    if not theme_dirs and themes:
        # We can not compile a theme sass without knowing the directory that contains the theme.
        raise ValueError('theme-dirs must be provided for compiling theme sass.')

    if isinstance(systems, basestring):
        systems = systems.split(',')
    else:
        systems = systems if isinstance(systems, list) else [systems]

    if isinstance(themes, basestring):
        themes = themes.split(',')
    else:
        themes = themes if isinstance(themes, list) else [themes]

    if isinstance(theme_dirs, basestring):
        theme_dirs = theme_dirs.split(',')
    else:
        theme_dirs = theme_dirs if isinstance(theme_dirs, list) else [theme_dirs]

    if themes and theme_dirs:
        themes = get_theme_paths(themes=themes, theme_dirs=theme_dirs)

    # Compile sass for OpenEdx theme after comprehensive themes
    if None not in themes:
        themes.append(None)

    timing_info = []
    dry_run = tasks.environment.dry_run
    compilation_results = {'success': [], 'failure': []}

    print("\t\tStarted compiling Sass:")

    # compile common sass files
    is_successful = _compile_sass('common', None, debug, force, timing_info)
    if is_successful:
        print("Finished compiling 'common' sass.")
    compilation_results['success' if is_successful else 'failure'].append('"common" sass files.')

    for system in systems:
        for theme in themes:
            print("Started compiling '{system}' Sass for '{theme}'.".format(system=system, theme=theme or 'system'))

            # Compile sass files
            is_successful = _compile_sass(
                system=system,
                theme=path(theme) if theme else None,
                debug=debug,
                force=force,
                timing_info=timing_info
            )

            if is_successful:
                print("Finished compiling '{system}' Sass for '{theme}'.".format(
                    system=system, theme=theme or 'system'
                ))

            compilation_results['success' if is_successful else 'failure'].append('{system} sass for {theme}.'.format(
                system=system, theme=theme or 'system',
            ))

    print("\t\tFinished compiling Sass:")
    if not dry_run:
        for sass_dir, css_dir, duration in timing_info:
            print(">> {} -> {} in {}s".format(sass_dir, css_dir, duration))

    if compilation_results['success']:
        print("\033[92m\nSuccessful compilations:\n--- " + "\n--- ".join(compilation_results['success']) + "\n\033[00m")
    if compilation_results['failure']:
        print("\033[91m\nFailed compilations:\n--- " + "\n--- ".join(compilation_results['failure']) + "\n\033[00m")


def _compile_sass(system, theme, debug, force, timing_info):
    """
    Compile sass files for the given system and theme.

    :param system: system to compile sass for e.g. 'lms', 'cms', 'common'
    :param theme: absolute path of the theme to compile sass for.
    :param debug: boolean showing whether to display source comments in resulted css
    :param force: boolean showing whether to remove existing css files before generating new files
    :param timing_info: list variable to keep track of timing for sass compilation
Will Daly committed
535
    """
536

537 538 539 540 541
    # Note: import sass only when it is needed and not at the top of the file.
    # This allows other paver commands to operate even without libsass being
    # installed. In particular, this allows the install_prereqs command to be
    # used to install the dependency.
    import sass
542 543 544 545
    if system == "common":
        sass_dirs = get_common_sass_directories()
    else:
        sass_dirs = get_sass_directories(system, theme)
546

547 548 549
    dry_run = tasks.environment.dry_run

    # determine css out put style and source comments enabling
550
    if debug:
551 552
        source_comments = True
        output_style = 'nested'
553
    else:
554 555 556
        source_comments = False
        output_style = 'compressed'

557
    for dirs in sass_dirs:
558
        start = datetime.now()
559 560 561 562 563 564 565 566 567 568
        css_dir = dirs['css_destination_dir']
        sass_source_dir = dirs['sass_source_dir']
        lookup_paths = dirs['lookup_paths']

        if not sass_source_dir.isdir():
            print("\033[91m Sass dir '{dir}' does not exists, skipping sass compilation for '{theme}' \033[00m".format(
                dir=sass_dirs, theme=theme or system,
            ))
            # theme doesn't override sass directory, so skip it
            continue
569 570 571 572 573 574 575 576 577 578 579

        if force:
            if dry_run:
                tasks.environment.info("rm -rf {css_dir}/*.css".format(
                    css_dir=css_dir,
                ))
            else:
                sh("rm -rf {css_dir}/*.css".format(css_dir=css_dir))

        if dry_run:
            tasks.environment.info("libsass {sass_dir}".format(
580
                sass_dir=sass_source_dir,
581 582 583
            ))
        else:
            sass.compile(
584 585
                dirname=(sass_source_dir, css_dir),
                include_paths=COMMON_LOOKUP_PATHS + lookup_paths,
586 587 588 589
                source_comments=source_comments,
                output_style=output_style,
            )
            duration = datetime.now() - start
590 591
            timing_info.append((sass_source_dir, css_dir, duration))
    return True
592

Will Daly committed
593

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
def process_npm_assets():
    """
    Process vendor libraries installed via NPM.
    """
    # Skip processing of the libraries if this is just a dry run
    if tasks.environment.dry_run:
        tasks.environment.info("install npm_assets")
        return

    # Ensure that the vendor directory exists
    NPM_VENDOR_DIRECTORY.mkdir_p()

    # Copy each file to the vendor directory, overwriting any existing file.
    for library in NPM_INSTALLED_LIBRARIES:
        sh('/bin/cp -rf node_modules/{library} {vendor_dir}'.format(
            library=library,
            vendor_dir=NPM_VENDOR_DIRECTORY,
        ))


Will Daly committed
614 615 616 617 618
def process_xmodule_assets():
    """
    Process XModule static assets.
    """
    sh('xmodule_assets common/static/xmodule')
619
    print("\t\tFinished processing xmodule assets.")
Will Daly committed
620 621


622 623 624 625 626 627 628 629 630 631 632
def restart_django_servers():
    """
    Restart the django server.

    `$ touch` makes the Django file watcher thinks that something has changed, therefore
    it restarts the server.
    """
    sh(cmd(
        "touch", 'lms/urls.py', 'cms/urls.py',
    ))

633

634
def collect_assets(systems, settings, **kwargs):
Will Daly committed
635 636 637 638
    """
    Collect static assets, including Django pipeline processing.
    `systems` is a list of systems (e.g. 'lms' or 'studio' or both)
    `settings` is the Django settings module to use.
639
    `**kwargs` include arguments for using a log directory for collectstatic output. Defaults to /dev/null.
Will Daly committed
640
    """
641

Will Daly committed
642
    for sys in systems:
643 644 645 646
        collectstatic_stdout_str = _collect_assets_cmd(sys, **kwargs)
        sh(django_cmd(sys, settings, "collectstatic --noinput {logfile_str}".format(
            logfile_str=collectstatic_stdout_str
        )))
647
        print("\t\tFinished collecting {} assets.".format(sys))
Will Daly committed
648 649


650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
def _collect_assets_cmd(system, **kwargs):
    """
    Returns the collecstatic command to be used for the given system

    Unless specified, collectstatic (which can be verbose) pipes to /dev/null
    """
    try:
        if kwargs[COLLECTSTATIC_LOG_DIR_ARG] is None:
            collectstatic_stdout_str = ""
        else:
            collectstatic_stdout_str = "> {output_dir}/{sys}-collectstatic.log".format(
                output_dir=kwargs[COLLECTSTATIC_LOG_DIR_ARG],
                sys=system
            )
    except KeyError:
        collectstatic_stdout_str = "> /dev/null"

    return collectstatic_stdout_str


670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
def execute_compile_sass(args):
    """
    Construct django management command compile_sass (defined in theming app) and execute it.
    Args:
        args: command line argument passed via update_assets command
    """
    for sys in args.system:
        options = ""
        options += " --theme-dirs " + " ".join(args.theme_dirs) if args.theme_dirs else ""
        options += " --themes " + " ".join(args.themes) if args.themes else ""
        options += " --debug" if args.debug else ""

        sh(
            django_cmd(
                sys,
                args.settings,
                "compile_sass {system} {options}".format(
                    system='cms' if sys == 'studio' else sys,
                    options=options,
                ),
            ),
        )


Will Daly committed
694
@task
695 696 697 698 699
@cmdopts([
    ('background', 'b', 'Background mode'),
    ('theme-dirs=', '-td', 'The themes dir containing all themes (defaults to None)'),
    ('themes=', '-t', 'The themes to add sass watchers for (defaults to None)'),
])
700
@timed
701 702 703 704
def watch_assets(options):
    """
    Watch for changes to asset files, and regenerate js/css
    """
705 706 707 708
    # Don't watch assets when performing a dry run
    if tasks.environment.dry_run:
        return

709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
    themes = getattr(options, 'themes', None)
    theme_dirs = getattr(options, 'theme-dirs', [])

    if not theme_dirs and themes:
        # We can not add theme sass watchers without knowing the directory that contains the themes.
        raise ValueError('theme-dirs must be provided for watching theme sass.')
    else:
        theme_dirs = [path(_dir) for _dir in theme_dirs]

    if isinstance(themes, basestring):
        themes = themes.split(',')
    else:
        themes = themes if isinstance(themes, list) else [themes]

    sass_directories = get_watcher_dirs(theme_dirs, themes)
Omar Khan committed
724
    observer = PollingObserver()
725 726

    CoffeeScriptWatcher().register(observer)
727 728
    SassWatcher().register(observer, sass_directories)
    XModuleSassWatcher().register(observer, ['common/lib/xmodule/'])
729
    XModuleAssetsWatcher().register(observer)
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744

    print("Starting asset watcher...")
    observer.start()
    if not getattr(options, 'background', False):
        # when running as a separate process, the main thread needs to loop
        # in order to allow for shutdown by contrl-c
        try:
            while True:
                observer.join(2)
        except KeyboardInterrupt:
            observer.stop()
        print("\nStopped asset watcher.")


@task
745 746 747
@needs(
    'pavelib.prereqs.install_node_prereqs',
)
Will Daly committed
748
@consume_args
749
@timed
Will Daly committed
750 751 752 753 754
def update_assets(args):
    """
    Compile CoffeeScript and Sass, then collect static assets.
    """
    parser = argparse.ArgumentParser(prog='paver update_assets')
755
    parser.add_argument(
756
        'system', type=str, nargs='*', default=ALL_SYSTEMS,
757 758 759
        help="lms or studio",
    )
    parser.add_argument(
760
        '--settings', type=str, default="devstack",
761 762 763 764 765 766 767 768 769 770
        help="Django settings module",
    )
    parser.add_argument(
        '--debug', action='store_true', default=False,
        help="Disable Sass compression",
    )
    parser.add_argument(
        '--skip-collect', dest='collect', action='store_false', default=True,
        help="Skip collection of static assets",
    )
771 772 773 774
    parser.add_argument(
        '--watch', action='store_true', default=False,
        help="Watch files for changes",
    )
775 776 777 778 779 780 781 782
    parser.add_argument(
        '--theme-dirs', dest='theme_dirs', type=str, nargs='+', default=None,
        help="base directories where themes are placed",
    )
    parser.add_argument(
        '--themes', type=str, nargs='+', default=None,
        help="list of themes to compile sass for",
    )
783 784 785 786
    parser.add_argument(
        '--collect-log', dest=COLLECTSTATIC_LOG_DIR_ARG, default=None,
        help="When running collectstatic, direct output to specified log directory",
    )
Will Daly committed
787
    args = parser.parse_args(args)
788
    collect_log_args = {}
Will Daly committed
789 790

    process_xmodule_assets()
791
    process_npm_assets()
Will Daly committed
792
    compile_coffeescript()
793 794 795

    # Compile sass for themes and system
    execute_compile_sass(args)
Will Daly committed
796

797
    if args.collect:
798 799 800 801 802 803 804
        if args.debug:
            collect_log_args.update({COLLECTSTATIC_LOG_DIR_ARG: None})

        if args.collect_log_dir:
            collect_log_args.update({COLLECTSTATIC_LOG_DIR_ARG: args.collect_log_dir})

        collect_assets(args.system, args.settings, **collect_log_args)
805 806

    if args.watch:
807 808 809 810
        call_task(
            'pavelib.assets.watch_assets',
            options={'background': not args.debug, 'theme-dirs': args.theme_dirs, 'themes': args.themes},
        )