Пример #1
0
def test_search_fail(temp_builds_dir, datas):
    """
    Test discover search which should fails
    """
    tmp_dirname = 'discovery_search_{}'.format(datas['id'])
    test_basedir = temp_builds_dir.join(tmp_dirname).strpath
    os.makedirs(test_basedir)

    # Prepend path with created temporary base directory since it can not
    # exists yet in parameter values
    if datas['filepath'] and datas['filepath'].startswith("BASEDIR_PREPEND"):
        datas['filepath'] = datas['filepath'].replace("BASEDIR_PREPEND", test_basedir)
    if datas['basedir'] and datas['basedir'].startswith("BASEDIR_PREPEND"):
        datas['basedir'] = datas['basedir'].replace("BASEDIR_PREPEND", test_basedir)

    # Create a dummy settings file in temp base directory
    if datas['fake_filename']:
        settings_filepath = os.path.join(test_basedir, datas['fake_filename'])
        with io.open(settings_filepath, 'w', encoding='utf-8') as f:
            result = f.write(u"""Dummy""")

    # Makes search
    disco = Discover(backends=datas['backends'])
    with pytest.raises(datas['expected_exception']):
        discovered_filepath, discovered_engine = disco.search(filepath=datas['filepath'],
                                                            basedir=datas['basedir'],
                                                            kind=datas['kind'])
Пример #2
0
def test_search_fail(temp_builds_dir, datas):
    """
    Test discover search which should fails
    """
    tmp_dirname = 'discovery_search_{}'.format(datas['id'])
    test_basedir = temp_builds_dir.join(tmp_dirname).strpath
    os.makedirs(test_basedir)

    # Prepend path with created temporary base directory since it can not
    # exists yet in parameter values
    if datas['filepath'] and datas['filepath'].startswith("BASEDIR_PREPEND"):
        datas['filepath'] = datas['filepath'].replace("BASEDIR_PREPEND",
                                                      test_basedir)
    if datas['basedir'] and datas['basedir'].startswith("BASEDIR_PREPEND"):
        datas['basedir'] = datas['basedir'].replace("BASEDIR_PREPEND",
                                                    test_basedir)

    # Create a dummy settings file in temp base directory
    if datas['fake_filename']:
        settings_filepath = os.path.join(test_basedir, datas['fake_filename'])
        with io.open(settings_filepath, 'w', encoding='utf-8') as f:
            result = f.write(u"""Dummy""")

    # Makes search
    disco = Discover(backends=datas['backends'])
    with pytest.raises(datas['expected_exception']):
        discovered_filepath, discovered_engine = disco.search(
            filepath=datas['filepath'],
            basedir=datas['basedir'],
            kind=datas['kind'])
Пример #3
0
def test_get_backend_success(filepath, kind, name):
    """
    Discover backend from given filename and kind
    """
    disco = Discover([SettingsBackendJson, SettingsBackendYaml])
    backend = disco.get_engine(filepath, kind=kind)

    assert backend._kind_name == name
Пример #4
0
def test_search_empty():
    """
    Error if basedir and filepath are empty
    """
    disco = Discover()

    with pytest.raises(SettingsDiscoveryError):
        disco.search()
Пример #5
0
def test_get_backend_fail(filepath, kind):
    """
    Error on discovering backend from given filename
    """
    disco = Discover([SettingsBackendJson, SettingsBackendYaml])

    with pytest.raises(SettingsDiscoveryError):
        backend = disco.get_engine(filepath, kind=kind)
Пример #6
0
def test_get_backend_success(filepath, kind, name):
    """
    Discover backend from given filename and kind
    """
    disco = Discover([SettingsBackendJson, SettingsBackendYaml])
    backend = disco.get_engine(filepath, kind=kind)

    assert backend._kind_name == name
Пример #7
0
def test_search_empty():
    """
    Error if basedir and filepath are empty
    """
    disco = Discover()

    with pytest.raises(SettingsDiscoveryError):
        disco.search()
Пример #8
0
def test_get_backend_fail(filepath, kind):
    """
    Error on discovering backend from given filename
    """
    disco = Discover([SettingsBackendJson, SettingsBackendYaml])

    with pytest.raises(SettingsDiscoveryError):
        backend = disco.get_engine(filepath, kind=kind)
Пример #9
0
def compile_command(context, backend, config):
    """
    Compile Sass project sources to CSS
    """
    logger = logging.getLogger("boussole")
    logger.info(u"Building project")

    # Discover settings file
    try:
        discovering = Discover(
            backends=[SettingsBackendJson, SettingsBackendYaml])
        config_filepath, config_engine = discovering.search(
            filepath=config, basedir=os.getcwd(), kind=backend)

        project = ProjectBase(backend_name=config_engine._kind_name)
        settings = project.backend_engine.load(filepath=config_filepath)
    except BoussoleBaseException as e:
        logger.critical(six.text_type(e))
        raise click.Abort()

    logger.debug(u"Settings file: {} ({})".format(config_filepath,
                                                  config_engine._kind_name))
    logger.debug(u"Project sources directory: {}".format(
        settings.SOURCES_PATH))
    logger.debug(u"Project destination directory: {}".format(
        settings.TARGET_PATH))
    logger.debug(u"Exclude patterns: {}".format(settings.EXCLUDES))

    # Find all sources with their destination path
    try:
        compilable_files = ScssFinder().mirror_sources(
            settings.SOURCES_PATH,
            targetdir=settings.TARGET_PATH,
            excludes=settings.EXCLUDES)
    except BoussoleBaseException as e:
        logger.error(six.text_type(e))
        raise click.Abort()

    # Build all compilable stylesheets
    compiler = SassCompileHelper()
    errors = 0
    for src, dst in compilable_files:
        logger.debug(u"Compile: {}".format(src))

        output_opts = {}
        success, message = compiler.safe_compile(settings, src, dst)

        if success:
            logger.info(u"Output: {}".format(message), **output_opts)
        else:
            errors += 1
            logger.error(message)

    # Ensure correct exit code if error has occured
    if errors:
        raise click.Abort()
Пример #10
0
def test_discover_scan_backends(backends, expected_engines, expected_exts,
                                expected_filenames):
    """
    Discover init engines from default backends
    """
    disco = Discover()

    engines, filenames, extensions = disco.scan_backends(backends)

    assert engines == OrderedDict(expected_engines)
    assert filenames == OrderedDict(expected_exts)
    assert extensions == OrderedDict(expected_filenames)
Пример #11
0
def test_discover_scan_backends(backends, expected_engines, expected_exts,
                                expected_filenames):
    """
    Discover init engines from default backends
    """
    disco = Discover()

    engines, filenames, extensions = disco.scan_backends(backends)

    assert engines == OrderedDict(expected_engines)
    assert filenames == OrderedDict(expected_exts)
    assert extensions == OrderedDict(expected_filenames)
Пример #12
0
def watch_command(context, backend, config, poll):
    """
    Watch for change on your Sass project sources then compile them to CSS.

    Watched events are:

    \b
    * Create: when a new source file is created;
    * Change: when a source is changed;
    * Delete: when a source is deleted;
    * Move: When a source file is moved in watched dirs. Also occurs with
      editor transition file;

    Almost all errors occurring during compile won't break watcher, so you can
    resolve them and watcher will try again to compile once a new event
    occurs.

    You can stop watcher using key combo "CTRL+C" (or CMD+C on MacOSX).
    """
    logger = logging.getLogger("boussole")
    logger.info("Watching project")

    # Discover settings file
    try:
        discovering = Discover(backends=[SettingsBackendJson,
                                         SettingsBackendYaml])
        config_filepath, config_engine = discovering.search(
            filepath=config,
            basedir=os.getcwd(),
            kind=backend
        )

        project = ProjectBase(backend_name=config_engine._kind_name)
        settings = project.backend_engine.load(filepath=config_filepath)
    except BoussoleBaseException as e:
        logger.critical(six.text_type(e))
        raise click.Abort()

    logger.debug(u"Settings file: {} ({})".format(
                 config_filepath, config_engine._kind_name))
    logger.debug(u"Project sources directory: {}".format(
                settings.SOURCES_PATH))
    logger.debug(u"Project destination directory: {}".format(
                settings.TARGET_PATH))
    logger.debug(u"Exclude patterns: {}".format(
                settings.EXCLUDES))

    # Watcher settings
    watcher_templates_patterns = {
        'patterns': ['*.scss'],
        'ignore_patterns': ['*.part'],
        'ignore_directories': False,
        'case_sensitive': True,
    }

    # Init inspector instance shared through all handlers
    inspector = ScssInspector()

    if not poll:
        logger.debug(u"Using Watchdog native platform observer")
        observer = Observer()
    else:
        logger.debug(u"Using Watchdog polling observer")
        observer = PollingObserver()

    # Init event handlers
    project_handler = WatchdogProjectEventHandler(settings, inspector,
                                                  **watcher_templates_patterns)

    lib_handler = WatchdogLibraryEventHandler(settings, inspector,
                                              **watcher_templates_patterns)

    # Observe source directory
    observer.schedule(project_handler, settings.SOURCES_PATH, recursive=True)

    # Also observe libraries directories
    for libpath in settings.LIBRARY_PATHS:
        observer.schedule(lib_handler, libpath, recursive=True)

    # Start watching
    logger.warning(u"Launching the watcher, use CTRL+C to stop it")
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        logger.warning(u"CTRL+C used, stopping..")
        observer.stop()

    observer.join()
Пример #13
0
def watch_command(context, backend, config, poll):
    """
    Watch for change on your Sass project sources then compile them to CSS.

    Watched events are:

    \b
    * Create: when a new source file is created;
    * Change: when a source is changed;
    * Delete: when a source is deleted;
    * Move: When a source file is moved in watched dirs. Also occurs with
      editor transition file;

    Almost all errors occurring during compile won't break watcher, so you can
    resolve them and watcher will try again to compile once a new event
    occurs.

    You can stop watcher using key combo "CTRL+C" (or CMD+C on MacOSX).
    """
    logger = logging.getLogger("boussole")
    logger.info("Watching project")

    # Discover settings file
    try:
        discovering = Discover(
            backends=[SettingsBackendJson, SettingsBackendYaml])
        config_filepath, config_engine = discovering.search(
            filepath=config, basedir=os.getcwd(), kind=backend)

        project = ProjectBase(backend_name=config_engine._kind_name)
        settings = project.backend_engine.load(filepath=config_filepath)
    except BoussoleBaseException as e:
        logger.critical(six.text_type(e))
        raise click.Abort()

    logger.debug(u"Settings file: {} ({})".format(config_filepath,
                                                  config_engine._kind_name))
    logger.debug(u"Project sources directory: {}".format(
        settings.SOURCES_PATH))
    logger.debug(u"Project destination directory: {}".format(
        settings.TARGET_PATH))
    logger.debug(u"Exclude patterns: {}".format(settings.EXCLUDES))

    # Watcher settings
    watcher_templates_patterns = {
        'patterns': ['*.scss'],
        'ignore_patterns': ['*.part'],
        'ignore_directories': False,
        'case_sensitive': True,
    }

    # Init inspector instance shared through all handlers
    inspector = ScssInspector()

    if not poll:
        logger.debug(u"Using Watchdog native platform observer")
        observer = Observer()
    else:
        logger.debug(u"Using Watchdog polling observer")
        observer = PollingObserver()

    # Init event handlers
    project_handler = WatchdogProjectEventHandler(settings, inspector,
                                                  **watcher_templates_patterns)

    lib_handler = WatchdogLibraryEventHandler(settings, inspector,
                                              **watcher_templates_patterns)

    # Observe source directory
    observer.schedule(project_handler, settings.SOURCES_PATH, recursive=True)

    # Also observe libraries directories
    for libpath in settings.LIBRARY_PATHS:
        observer.schedule(lib_handler, libpath, recursive=True)

    # Start watching
    logger.warning(u"Launching the watcher, use CTRL+C to stop it")
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        logger.warning(u"CTRL+C used, stopping..")
        observer.stop()

    observer.join()
Пример #14
0
def compile_command(context, backend, config):
    """
    Compile Sass project sources to CSS
    """
    logger = logging.getLogger("boussole")
    logger.info(u"Building project")

    # Discover settings file
    try:
        discovering = Discover(backends=[SettingsBackendJson,
                                         SettingsBackendYaml])
        config_filepath, config_engine = discovering.search(
            filepath=config,
            basedir=os.getcwd(),
            kind=backend
        )

        project = ProjectBase(backend_name=config_engine._kind_name)
        settings = project.backend_engine.load(filepath=config_filepath)
    except BoussoleBaseException as e:
        logger.critical(six.text_type(e))
        raise click.Abort()

    logger.debug(u"Settings file: {} ({})".format(
                 config_filepath, config_engine._kind_name))
    logger.debug(u"Project sources directory: {}".format(
                 settings.SOURCES_PATH))
    logger.debug(u"Project destination directory: {}".format(
                 settings.TARGET_PATH))
    logger.debug(u"Exclude patterns: {}".format(
                 settings.EXCLUDES))

    # Find all sources with their destination path
    try:
        compilable_files = ScssFinder().mirror_sources(
            settings.SOURCES_PATH,
            targetdir=settings.TARGET_PATH,
            excludes=settings.EXCLUDES
        )
    except BoussoleBaseException as e:
        logger.error(six.text_type(e))
        raise click.Abort()

    # Build all compilable stylesheets
    compiler = SassCompileHelper()
    errors = 0
    for src, dst in compilable_files:
        logger.debug(u"Compile: {}".format(src))

        output_opts = {}
        success, message = compiler.safe_compile(settings, src, dst)

        if success:
            logger.info(u"Output: {}".format(message), **output_opts)
        else:
            errors += 1
            logger.error(message)

    # Ensure correct exit code if error has occured
    if errors:
        raise click.Abort()