command_utils.py 1.69 KB
Newer Older
1 2 3 4 5 6 7 8 9
"""
Useful utilities for management commands.
"""

from django.core.management.base import CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey


10
def get_mutually_exclusive_required_option(options, *selections):
11 12 13 14 15
    """
    Validates that exactly one of the 2 given options is specified.
    Returns the name of the found option.
    """

16 17 18
    selected = [sel for sel in selections if options.get(sel)]
    if len(selected) != 1:
        selection_string = u', '.join('--{}'.format(selection) for selection in selections)
19

20 21
        raise CommandError(u'Must specify exactly one of {}'.format(selection_string))
    return selected[0]
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48


def validate_mutually_exclusive_option(options, option_1, option_2):
    """
    Validates that both of the 2 given options are not specified.
    """
    if options.get(option_1) and options.get(option_2):
        raise CommandError('Both --{} and --{} cannot be specified.'.format(option_1, option_2))


def validate_dependent_option(options, dependent_option, depending_on_option):
    """
    Validates that option_1 is specified if dependent_option is specified.
    """
    if options.get(dependent_option) and not options.get(depending_on_option):
        raise CommandError('Option --{} requires option --{}.'.format(dependent_option, depending_on_option))


def parse_course_keys(course_key_strings):
    """
    Parses and returns a list of CourseKey objects from the given
    list of course key strings.
    """
    try:
        return [CourseKey.from_string(course_key_string) for course_key_string in course_key_strings]
    except InvalidKeyError as error:
        raise CommandError('Invalid key specified: {}'.format(error.message))