Пример #1
0
def checkout(args):
    """
    This is our main entrypoint for the checkout command.
    """
    package_name_version = get_requirements()
    SOURCE_DIR = USERLAND_HERE.parent
    with SOURCE_DIR:
        ls_source = [str(f) for f in SOURCE_DIR.ls()]
        uncommitted = []

        for package_name, version in package_name_version.items():
            if package_name in ls_source:
                with SOURCE_DIR/package_name:
                    if check_for_uncommitted():
                        uncommitted.append(package_name)

        if len(uncommitted):
            write("We have uncommitted changes in {}".format(
                ", ".join(uncommitted)
            ))
            write('Abandonning attempt to check out to requirements.txt')
            return

        for package_name, version in package_name_version.items():
            if package_name in ls_source:
                with SOURCE_DIR/package_name:
                    write("checking out {0} to {1}".format(
                        package_name, version
                    ))
                    os.system("git checkout {}".format(version))
                    os.system("python setup.py develop")
            else:
                write('Unable to checkout versions from requirements')
                write('{0} is missing'.format(package_name))
                return
Пример #2
0
def checkout(args):
    """
    This is our main entrypoint for the checkout command.
    """
    package_name_version = get_requirements()
    SOURCE_DIR = USERLAND_HERE.parent
    with SOURCE_DIR:
        ls_source = [str(f) for f in SOURCE_DIR.ls()]
        uncommitted = []

        for package_name, version in package_name_version.items():
            if package_name in ls_source:
                with SOURCE_DIR/package_name:
                    if check_for_uncommitted():
                        uncommitted.append(package_name)

        if len(uncommitted):
            write("We have uncommitted changes in {}".format(
                ", ".join(uncommitted)
            ))
            write('Abandonning attempt to check out to requirements.txt')
            return

        for package_name, version in package_name_version.items():
            if package_name in ls_source:
                with SOURCE_DIR/package_name:
                    write("checking out {0} to {1}".format(
                        package_name, version
                    ))
                    os.system("git checkout {}".format(version))
                    os.system("python setup.py develop")
            else:
                write('Unable to checkout versions from requirements')
                write('{0} is missing'.format(package_name))
                return
Пример #3
0
    def delete(self):
        write('Deleting Synonyms')

        for item in Synonym.objects.all():
            item.delete()

        write('Deleting Lookuplists')
        for model in lookuplists.lookuplists():
            for item in model.objects.all():
                item.delete()
Пример #4
0
def call(cmd, **kwargs):
    """
    Call an external program in a subprocess
    """
    write("Calling: {}".format(' '.join(cmd)))
    try:
        subprocess.check_call(cmd, **kwargs)
    except subprocess.CalledProcessError:
        write("Failed to run: {}".format(' '.join(cmd)))
        sys.exit(1)
Пример #5
0
    def delete(self):
        write('Deleting Synonyms')

        for item in Synonym.objects.all():
            item.delete()

        write('Deleting Lookuplists')
        for model in LookupList.__subclasses__():
            for item in model.objects.all():
                item.delete()
Пример #6
0
def call(cmd, **kwargs):
    """
    Call an external program in a subprocess
    """
    write("Calling: {}".format(' '.join(cmd)))
    try:
        subprocess.check_call(cmd, **kwargs)
    except subprocess.CalledProcessError:
        write("Failed to run: {}".format(' '.join(cmd)))
        sys.exit(1)
Пример #7
0
def scaffold(args):
    """
    Create record boilierplates:

    1. Run a south auto migration
    2. Create display templates
    3. Create forms
    """
    app = args.app
    name = find_application_name()
    scaffold_utils._set_settings_module(name)
    sys.path.append(os.path.abspath('.'))

    # 1. Let's run a Django migration
    dry_run = ''
    if args.dry_run:
        dry_run = '--dry-run'

    if not args.nomigrations:
        makemigrations_cmd = "python manage.py makemigrations {app} " \
                             "--traceback {dry_run}"
        makemigrations_cmd = makemigrations_cmd.format(
            app=app, dry_run=dry_run)
        migrate_cmd = 'python manage.py migrate {app} --traceback'.format(
            app=app)

        os.system(makemigrations_cmd)
        if not args.dry_run:
            os.system(migrate_cmd)

    # 2. Let's create some display templates
    from opal.models import Subrecord, EpisodeSubrecord, PatientSubrecord

    models = stringport('{0}.models'.format(app))
    for i in dir(models):
        thing = getattr(models, i)
        if inspect.isclass(thing) and issubclass(thing, Subrecord):
            if thing in [Subrecord, EpisodeSubrecord, PatientSubrecord]:
                continue
            if not thing.get_display_template():
                if args.dry_run:
                    write('No Display template for {0}'.format(thing))
                else:
                    scaffold_utils.create_display_template_for(
                        thing, SCAFFOLDING_BASE
                    )
            if not thing.get_modal_template():
                if args.dry_run:
                    write('No Form template for {0}'.format(thing))
                else:
                    scaffold_utils.create_form_template_for(
                        thing, SCAFFOLDING_BASE
                    )
    return
Пример #8
0
def scaffold(args):
    """
    Create record boilierplates:

    1. Run a south auto migration
    2. Create display templates
    3. Create forms
    """
    app = args.app
    name = find_application_name()
    scaffold_utils._set_settings_module(name)
    sys.path.append(os.path.abspath('.'))

    # 1. Let's run a Django migration
    dry_run = ''
    if args.dry_run:
        dry_run = '--dry-run'

    if not args.nomigrations:
        makemigrations_cmd = "python manage.py makemigrations {app} " \
                             "--traceback {dry_run}"
        makemigrations_cmd = makemigrations_cmd.format(app=app,
                                                       dry_run=dry_run)
        migrate_cmd = 'python manage.py migrate {app} --traceback'.format(
            app=app)

        os.system(makemigrations_cmd)
        if not args.dry_run:
            os.system(migrate_cmd)

    # 2. Let's create some display templates
    from opal.models import Subrecord, EpisodeSubrecord, PatientSubrecord

    models = stringport('{0}.models'.format(app))
    for i in dir(models):
        thing = getattr(models, i)
        if inspect.isclass(thing) and issubclass(thing, Subrecord):
            if thing in [Subrecord, EpisodeSubrecord, PatientSubrecord]:
                continue
            if not thing.get_display_template():
                if args.dry_run:
                    write('No Display template for {0}'.format(thing))
                else:
                    scaffold_utils.create_display_template_for(
                        thing, SCAFFOLDING_BASE)
            if not thing.get_modal_template():
                if args.dry_run:
                    write('No Form template for {0}'.format(thing))
                else:
                    scaffold_utils.create_form_template_for(
                        thing, SCAFFOLDING_BASE)
    return
Пример #9
0
    def handle(self, *args, **options):
        # create 100 patients, give each between 1-5 episodes
        # over the past 3 years, at least 10 of which have an episode in the
        # last week
        if options['number']:
            number = int(options['number'])
        else:
            number = 100
        p = PatientGenerator()

        for i in range(number):
            msg = 'Generating Patient {0} / {1}'.format(i + 1, number)
            write(msg)
            p.make()
Пример #10
0
    def handle(self, *args, **options):
        # create 100 patients, give each between 1-5 episodes
        # over the past 3 years, at least 10 of which have an episode in the
        # last week
        if options['number']:
            number = int(options['number'])
        else:
            number = 100
        p = PatientGenerator()

        for i in range(number):
            msg = 'Generating Patient {0} / {1}'.format(i+1, number)
            write(msg)
            p.make()
Пример #11
0
def scaffold_subrecords(
    app, migrations=True, dry_run=False, dir=SCAFFOLDING_BASE
):
    """
    In which we scaffold an django app (opal plugin or application).

    1. Make migrations
    2. Migrate
    3. Create Form Templates of all subrecords in the models
    4. Create Record Templates of all subrecords in the models
    """
    if app not in apps.all_models:
        err = "Unable to find app {} in settings.INSTALLED_APPS"
        raise ValueError(
            err.format(app)
        )

    if migrations:
        if dry_run:
            management.call_command(
                'makemigrations', app, "--traceback", "--dry-run"
            )
        else:
            management.call_command(
                'makemigrations', app, "--traceback"
            )
            management.call_command('migrate', app, "--traceback")

    models = apps.all_models[app]
    all_subrecords = set(i for i in subrecords.subrecords())

    for model in models.values():
        if model in all_subrecords:
            if not model.get_display_template():
                if dry_run:
                    write('No Display template for {0}'.format(model))
                else:
                    create_display_template_for(
                        model, SCAFFOLDING_BASE
                    )
            if not model.get_form_template():
                if dry_run:
                    write('No Form template for {0}'.format(model))
                else:
                    create_form_template_for(
                        model, SCAFFOLDING_BASE
                    )
Пример #12
0
def start_plugin(name, USERLAND):
    name = name

    write('Bootstrapping "{0}" - your new Opal plugin...'.format(name))

    if 'opal' in name:
        reponame = name
        name = name.replace('opal-', '')
    else:
        reponame = 'opal-{0}'.format(name)

    root = USERLAND / reponame

    # 1. Copy across scaffold
    nix.cp_r(PLUGIN_SCAFFOLD, root)

    # 2n. Interpolate scaffold
    interpolate_dir(root, name=name, version=opal.__version__)

    # 3. Rename the code dir
    code_root = root / name
    nix.mv(root / 'app', code_root)

    # 4. Create some extra directories.
    create_lookuplists(code_root)
    templates = code_root / 'templates'
    templates.mkdir()
    static = code_root / 'static'
    static.mkdir()
    jsdir = static / 'js/{0}'.format(name)
    jsdir.mkdir()
    cssdir = static / 'css'
    cssdir.mkdir()
    controllers = jsdir / 'controllers'
    controllers.mkdir()
    services = jsdir / 'services'
    services.mkdir()
    # 5. Initialize git repo
    call_if_exists(
        ('git', 'init'),
        'Unable to locate git; Skipping git repository initialization.',
        cwd=root,
        stdout=subprocess.PIPE)

    write('Plugin complete at {0}'.format(reponame))
    return
Пример #13
0
def start_plugin(name, USERLAND):
    name = name

    write('Bootstrapping "{0}" - your new Opal plugin...'.format(name))

    if 'opal' in name:
        reponame = name
        name = name.replace('opal-', '')
    else:
        reponame = 'opal-{0}'.format(name)

    root = USERLAND/reponame

    # 1. Copy across scaffold
    nix.cp_r(PLUGIN_SCAFFOLD, root)

    # 2n. Interpolate scaffold
    interpolate_dir(root, name=name, version=opal.__version__)

    # 3. Rename the code dir
    code_root = root/name
    nix.mv(root/'app', code_root)

    # 4. Create some extra directories.
    create_lookuplists(code_root)
    templates = code_root/'templates'
    templates.mkdir()
    static = code_root/'static'
    static.mkdir()
    jsdir = static/'js/{0}'.format(name)
    jsdir.mkdir()
    cssdir = static/'css'
    cssdir.mkdir()
    controllers = jsdir/'controllers'
    controllers.mkdir()
    services = jsdir/'services'
    services.mkdir()
    # 5. Initialize git repo
    call_if_exists(
        ('git', 'init'),
        'Unable to locate git; Skipping git repository initialization.',
        cwd=root, stdout=subprocess.PIPE
    )

    write('Plugin complete at {0}'.format(reponame))
    return
Пример #14
0
def call_if_exists(cmd, failure_message, **kwargs):
    """
    Call an external program in a subprocess if it exists.

    Returns True.

    If it does not exist, write a failure message and return False
    without raising an exception
    """
    try:
        call(cmd, **kwargs)
        return True
    except OSError as e:
        if e.errno == errno.ENOENT:
            write(failure_message)
            return False
        else:
            raise
Пример #15
0
def call_if_exists(cmd, failure_message, **kwargs):
    """
    Call an external program in a subprocess if it exists.

    Returns True.

    If it does not exist, write a failure message and return False
    without raising an exception
    """
    try:
        call(cmd, **kwargs)
        return True
    except OSError as e:
        if e.errno == errno.ENOENT:
            write(failure_message)
            return False
        else:
            raise
Пример #16
0
def _run_py_tests(args):
    """
    Run our Python test suite
    """
    write("Running Python Unit Tests")
    test_args = None

    # We have a custom test runner - e.g. it's Opal itself or a plugin.
    if _has_file(args.userland_here, 'runtests.py'):
        test_args = ['python', 'runtests.py']

        if args.coverage:
            test_args = ['coverage', 'run', 'runtests.py']

        if args.test:
            test_args.append(args.test)

    # We have a manage.py script - assume that we're in an application
    elif _has_file(args.userland_here, 'manage.py'):
        test_args = ['python', 'manage.py', 'test']

        if args.coverage:
            test_args = [
                'coverage',
                'run',
                'manage.py',
                'test',
            ]

        if args.test:
            test_args.append(args.test)

    else:
        write("\n\nCripes!\n")
        write("We can't figure out how to run your tests :(\n")
        write("Are you in the root directory? \n\n")
        sys.exit(1)

    if args.failfast:
        test_args.append('--failfast')

    if test_args:
        try:
            subprocess.check_call(test_args)
        except subprocess.CalledProcessError:
            sys.exit(1)

        if args.coverage:
            try:
                subprocess.check_call(['coverage', 'html'])
            except subprocess.CalledProcessError:
                sys.exit(1)

    return
Пример #17
0
def start_plugin(name, USERLAND):
    name = name

    write('Bootstrapping "{0}" - your new Opal plugin...'.format(name))

    if 'opal' in name:
        reponame = name
        name = name.replace('opal-', '')
    else:
        reponame = 'opal-{0}'.format(name)

    root = USERLAND / reponame

    # 1. Copy across scaffold
    shutil.copytree(PLUGIN_SCAFFOLD, root)

    # 2n. Interpolate scaffold
    interpolate_dir(root, name=name, version=opal.__version__)

    # 3. Rename the code dir
    code_root = root / name
    nix.mv(root / 'app', code_root)

    # 4. Create some extra directories.
    create_lookuplists(code_root)
    templates = code_root / 'templates'
    templates.mkdir()
    static = code_root / 'static'
    static.mkdir()
    jsdir = static / 'js/{0}'.format(name)
    jsdir.mkdir()
    cssdir = static / 'css'
    cssdir.mkdir()
    controllers = jsdir / 'controllers'
    controllers.mkdir()
    services = jsdir / 'services'
    services.mkdir()
    # 5. Initialize git repo
    os.system('cd {0}; git init'.format(reponame))

    write('Plugin complete at {0}'.format(reponame))
    return
Пример #18
0
def start_plugin(name, USERLAND):
    name = name

    write('Bootstrapping "{0}" - your new Opal plugin...'.format(name))

    if 'opal' in name:
        reponame = name
        name = name.replace('opal-', '')
    else:
        reponame = 'opal-{0}'.format(name)

    root = USERLAND/reponame

    # 1. Copy across scaffold
    shutil.copytree(PLUGIN_SCAFFOLD, root)

    # 2n. Interpolate scaffold
    interpolate_dir(root, name=name, version=opal.__version__)

    # 3. Rename the code dir
    code_root = root/name
    nix.mv(root/'app', code_root)

    # 4. Create some extra directories.
    create_lookuplists(code_root)
    templates = code_root/'templates'
    templates.mkdir()
    static = code_root/'static'
    static.mkdir()
    jsdir = static/'js/{0}'.format(name)
    jsdir.mkdir()
    cssdir = static/'css'
    cssdir.mkdir()
    controllers = jsdir/'controllers'
    controllers.mkdir()
    services = jsdir/'services'
    services.mkdir()
    # 5. Initialize git repo
    os.system('cd {0}; git init'.format(reponame))

    write('Plugin complete at {0}'.format(reponame))
    return
Пример #19
0
def create_form_template_for(record, scaffold_base):
    """
    Create a form template for RECORD.
    """
    write('Creating form template for{0}'.format(record))
    name = record.get_api_name()

    templates = _get_template_dir_from_record(record)
    forms = templates/'forms'
    if not forms:
        forms.mkdir()

    form_template = scaffold_base/'record_templates/record_form.jinja2'
    template = forms/'{0}_form.html'.format(name)
    fields = _strip_non_user_fields(record.build_field_schema())
    contents = mold.cast(form_template, record=record, fields=fields)
    # We often get lots of lines containing just spaces as a Jinja2 artifact. Lose them.
    contents = "\n".join(l for l in contents.split("\n") if l.strip())
    template << contents
    return
Пример #20
0
def create_form_template_for(record, scaffold_base):
    """
    Create a form template for RECORD.
    """
    write('Creating form template for{0}'.format(record))
    name = record.get_api_name()

    templates = _get_template_dir_from_record(record)
    forms = templates/'forms'
    if not forms:
        forms.mkdir()

    form_template = scaffold_base/'record_templates/record_form.jinja2'
    template = forms/'{0}_form.html'.format(name)
    fields = _strip_non_user_fields(record.build_field_schema())
    contents = mold.cast(form_template, record=record, fields=fields)
    # We often get lots of lines containing just spaces as a Jinja2
    # artifact. Lose them.
    contents = "\n".join(l for l in contents.split("\n") if l.strip())
    template << contents
    return
Пример #21
0
def _get_template_dir_from_record(record):
    """
    Given a RECORD, return it's relative template dir
    """
    modelsfile = inspect.getfile(record)
    if modelsfile.endswith('.pyc'):
        modelsfile = modelsfile.replace('.pyc', '.py')

    appdir = None
    if modelsfile.endswith('models.py'):
        # We're assuming the app in question has models in
        # ./app/models.py
        appdir = ffs.Path(modelsfile)[:-1]
    else:
        if ffs.Path(modelsfile)[-2] == 'models':
            # We're assuming the app in question has models
            # in ./app/models/here.py
            appdir = ffs.Path(modelsfile)[:-2]

    if appdir is None:
        write("\n\nCripes!\n")
        write("We can't figure out what the correct directory to \n")
        write("put templates for {0} is :( \n\n".format(record))
        sys.exit(1)
    else:
        templates = appdir / 'templates'
        return templates
Пример #22
0
def _get_template_dir_from_record(record):
    """
    Given a RECORD, return it's relative template dir
    """
    modelsfile = inspect.getfile(record)
    if modelsfile.endswith('.pyc'):
        modelsfile = modelsfile.replace('.pyc', '.py')

    appdir = None
    if modelsfile.endswith('models.py'):
        # We're assuming the app in question has models in
        # ./app/models.py
        appdir = ffs.Path(modelsfile)[:-1]
    else:
        if ffs.Path(modelsfile)[-2] == 'models':
            # We're assuming the app in question has models
            # in ./app/models/here.py
            appdir = ffs.Path(modelsfile)[:-2]

    if appdir is None:
        write("\n\nCripes!\n")
        write("We can't figure out what the correct directory to \n")
        write("put templates for {0} is :( \n\n".format(record))
        sys.exit(1)
    else:
        templates = appdir/'templates'
        return templates
Пример #23
0
def create_display_template_for(record, scaffold_base):
    """
    Create a display template for RECORD.
    """
    write('Creating display template for {0}'.format(record))
    name = record.get_api_name()

    # 1. Locate the records template directory
    templates = _get_template_dir_from_record(record)
    records = templates / 'records'
    if not records:
        records.mkdir()

    display_template = scaffold_base / 'record_templates/record_display.jinja2'
    template = records / '{0}.html'.format(name)
    fields = _strip_non_user_fields(record.build_field_schema())
    contents = mold.cast(display_template, record=record, fields=fields)
    # We often get lots of lines containing just spaces as a Jinja2
    # artifact. Lose them.
    contents = "\n".join(l for l in contents.split("\n") if l.strip())
    template << contents
    return
Пример #24
0
def _run_py_tests(args):
    """
    Run our Python test suite
    """
    write("Running Python Unit Tests")
    test_args = None

    # We have a custom test runner - e.g. it's Opal itself or a plugin.
    if _has_file(args.userland_here, 'runtests.py'):
        test_args = ['python', 'runtests.py']

        if args.coverage:
            test_args = ['coverage', 'run', 'runtests.py']

        if args.test:
            test_args.append(args.test)

    # We have a manage.py script - assume that we're in an application
    elif _has_file(args.userland_here, 'manage.py'):
        test_args = ['python', 'manage.py', 'test']

        if args.coverage:
            test_args = ['coverage', 'run', 'manage.py', 'test', ]

        if args.test:
            test_args.append(args.test)

    else:
        write("\n\nCripes!\n")
        write("We can't figure out how to run your tests :(\n")
        write("Are you in the root directory? \n\n")
        sys.exit(1)

    if args.failfast:
        test_args.append('--failfast')

    if test_args:
        try:
            subprocess.check_call(test_args)
        except subprocess.CalledProcessError:
            sys.exit(1)

        if args.coverage:
            try:
                subprocess.check_call(['coverage', 'html'])
            except subprocess.CalledProcessError:
                sys.exit(1)

    return
Пример #25
0
def scaffold_subrecords(app,
                        migrations=True,
                        dry_run=False,
                        dir=SCAFFOLDING_BASE):
    """
    In which we scaffold an django app (opal plugin or application).

    1. Make migrations
    2. Migrate
    3. Create Form Templates of all subrecords in the models
    4. Create Record Templates of all subrecords in the models
    """
    if app not in apps.all_models:
        err = "Unable to find app {} in settings.INSTALLED_APPS"
        raise ValueError(err.format(app))

    if migrations:
        if dry_run:
            management.call_command('makemigrations', app, "--traceback",
                                    "--dry-run")
        else:
            management.call_command('makemigrations', app, "--traceback")
            management.call_command('migrate', app, "--traceback")

    models = apps.all_models[app]
    all_subrecords = set(i for i in subrecords.subrecords())

    for model in models.values():
        if model in all_subrecords:
            if not model.get_display_template():
                if dry_run:
                    write('No Display template for {0}'.format(model))
                else:
                    create_display_template_for(model, SCAFFOLDING_BASE)
            if not model.get_form_template():
                if dry_run:
                    write('No Form template for {0}'.format(model))
                else:
                    create_form_template_for(model, SCAFFOLDING_BASE)
Пример #26
0
def find_application_name():
    """
    Return the name of the current Opal application
    """
    for d in USERLAND_HERE.ls():
        if d.is_dir:
            if d/'settings.py':
                return d[-1]

    write("\n\nCripes!\n")
    write("We can't figure out what the name of your application is :(\n")
    write("Are you in the application root directory? \n\n")
    sys.exit(1)
Пример #27
0
def find_application_name():
    """
    Return the name of the current Opal application
    """
    for d in USERLAND_HERE.ls():
        if d.is_dir:
            if d/'settings.py':
                return d[-1]

    write("\n\nCripes!\n")
    write("We can't figure out what the name of your application is :(\n")
    write("Are you in the application root directory? \n\n")
    sys.exit(1)
Пример #28
0
 def test_write(self):
     with patch.object(utils, 'sys') as mocksys:
         mocksys.argv = ['not', 'te$targs']
         utils.write('this')
         mocksys.stdout.write.assert_called_with('this\n')
Пример #29
0
def start_project(name, USERLAND_HERE):
    """
    In which we perform the steps required to start a new Opal project.

    1. Run Django' Startproject
    2. Create a data/lookuplists dir
    3. Copy across the scaffolding directory
    4. Interpolate our project data into the templates.
    5. Swap our scaffold app with the Django created app
    6. Interpolate the code templates from our scaffold app
    7. Create extra directories we need
    8. Run Django's migrations
    9. Create a superuser
    10. Initialise our git repo
    11. Load referencedata shipped with Opal
    """

    project_dir = USERLAND_HERE/name
    if project_dir:
        write("\n\nDirectory {0} already exists !".format(project_dir))
        write("Please remove it or choose a new name.\n\n")
        sys.exit(1)

    write("Bootstrapping your Opal project...")

    # 1. Run Django Startproject
    write("Creating project dir at {0}".format(project_dir))
    project_dir.mkdir()
    management.call_command('startproject', name, project_dir)

    # 3. Copy across the scaffold
    with SCAFFOLD:
        for p in SCAFFOLD.ls():
            target = project_dir/p[-1]
            p.cp(target)

    # Dotfiles need their dot back
    gitignore = project_dir/'gitignore'
    gitignore.mv(project_dir/'.gitignore')

    # 4. Interpolate the project data
    interpolate_dir(project_dir, name=name, secret_key=get_random_secret_key(),
                    version=opal.__version__)

    app_dir = project_dir/name

    # 5. Django Startproject creates some things - let's kill them &
    # replace with our own things.
    nix.rm(app_dir, recursive=True, force=True)
    nix.mv(project_dir/'app', app_dir)

    #  7. Create extra directories we need
    js = app_dir/'static/js/{0}'.format(name)
    css = app_dir/'static/css'
    js.mkdir()
    css.mkdir()
    nix.mv(app_dir/'static/js/app/routes.js',
           app_dir/'static/js/{0}/routes.js'.format(name))

    templates = app_dir/'templates'/name
    templates.mkdir()

    assets = app_dir/'assets'
    assets.mkdir()
    assets_explainer = assets/'README.md'
    assets_explainer << """
    This placeholder file is here to ensure that there we still have our
    STATICFILES_DIRS target if we commit generated code to source control.

    This means that we can run collectstatic OK.
    """

    # 2. Create lookup lists
    create_lookuplists(app_dir)

    # We have this here because it uses name from above.
    def manage(command):
        args = ['python', os.path.join(name, 'manage.py')]
        args += command.split()
        args.append('--traceback')
        call(args)

    # 8. Run Django's migrations
    write('Creating Database')
    manage('makemigrations {0}'.format(name))
    manage('migrate')

    # 9. Create a superuser
    write('Creating superuser')
    manage('createopalsuperuser')

    # 10. Initialise git repo
    call_if_exists(
        ('git', 'init'),
        'Unable to locate git; Skipping git repository initialization.',
        cwd=project_dir, stdout=subprocess.PIPE
    )

    # 11. Load referencedata shipped with Opal
    manage('load_lookup_lists')
Пример #30
0
def _run_js_tests(args):
    """
    Run our Javascript test suite
    """
    write("Running Javascript Unit Tests")
    env = os.environ.copy()

    # used by the karma config file where to find the opal karma defaults
    # python3 breaks on ffs if we don't explicitly cast the location
    # to a string
    env["OPAL_LOCATION"] = str(args.opal_location)

    if TRAVIS:
        karma = './node_modules/karma/bin/karma'
    else:
        karma = 'karma'
        env['DISPLAY'] = ':10'

    sub_args = [
        karma,
        'start',
        'config/karma.conf.js',
        '--single-run',
    ]
    if args.failfast:
        sub_args.append('--failfast')

    try:
        subprocess.check_call(sub_args, env=env)
    except subprocess.CalledProcessError:
        sys.exit(1)
    except OSError as e:
        if e.errno == errno.ENOENT:
            write("\n\nCripes!\n")
            write("We can't find the karma executable\n")
            write("Please consult the Opal documentation about installing the")
            write("Javascript testing tools required to run Javascript tests:")
            write(
                "http://opal.openhealthcare.org.uk/docs/reference/"
                "testing/"
            )
            write("\nAlternatively run just the Python test suite with")
            write("opal test py")
        sys.exit(1)
    return
Пример #31
0
def _run_js_tests(args):
    """
    Run our Javascript test suite
    """
    write("Running Javascript Unit Tests")
    env = os.environ.copy()

    # used by the karma config file where to find the opal karma defaults
    # python3 breaks on ffs if we don't explicitly cast the location
    # to a string
    env["OPAL_LOCATION"] = str(args.opal_location)

    if TRAVIS:
        karma = './node_modules/karma/bin/karma'
    else:
        karma = 'karma'
        env['DISPLAY'] = ':10'

    sub_args = [
        karma,
        'start',
        'config/karma.conf.js',
        '--single-run',
    ]

    try:
        subprocess.check_call(sub_args, env=env)
    except subprocess.CalledProcessError:
        sys.exit(1)
    except OSError as e:
        if e.errno == errno.ENOENT:
            write("\n\nCripes!\n")
            write("We can't find the karma executable\n")
            write("Please consult the Opal documentation aobut installing the")
            write("Javascript testing tools requried to run Javascript tests:")
            write(
                "http://opal.openhealthcare.org.uk/docs/reference/"
                "testing/"
            )
            write("\nAlternatively run just the Python test sutite with")
            write("opal test py")
        sys.exit(1)
    return
Пример #32
0
 def test_write(self):
     with patch.object(utils, 'sys') as mocksys:
         mocksys.argv = ['not', 'te$targs']
         utils.write('this')
         mocksys.stdout.write.assert_called_with('this\n')
Пример #33
0
def start_project(name, USERLAND_HERE):
    """
    In which we perform the steps required to start a new Opal project.

    1. Run Django' Startproject
    2. Create a data/lookuplists dir
    3. Copy across the scaffolding directory
    4. Interpolate our project data into the templates.
    5. Swap our scaffold app with the Django created app
    6. Interpolate the code templates from our scaffold app
    7. Create extra directories we need
    8. Run Django's migrations
    9. Create a superuser
    10. Initialise our git repo
    """

    project_dir = USERLAND_HERE/name
    if project_dir:
        write("\n\nDirectory {0} already exists !".format(project_dir))
        write("Please remove it or choose a new name.\n\n")
        sys.exit(1)

    # 1. Run Django Startproject
    write("Creating project dir at {0}".format(project_dir))
    os.system('django-admin.py startproject {0}'.format(name))

    write("Bootstrapping your Opal project...")

    if not project_dir:
        project_dir.mkdir()

    # Copy across the scaffold
    with SCAFFOLD:
        for p in SCAFFOLD.ls():
            target = project_dir/p[-1]
            p.cp(target)

    # Dotfiles need their dot back
    gitignore = project_dir/'gitignore'
    gitignore.mv(project_dir/'.gitignore')


    # Interpolate the project data
    interpolate_dir(project_dir, name=name, secret_key=get_random_secret_key())

    app_dir = project_dir/name

    # Django Startproject creates some things - let's kill them &
    # replace with our own things.
    nix.rm(app_dir, recursive=True, force=True)
    nix.mv(project_dir/'app', app_dir)

    #  Create extra directories we need
    js = app_dir/'static/js/{0}'.format(name)
    css = app_dir/'static/css'
    js.mkdir()
    css.mkdir()
    nix.mv(app_dir/'static/js/app/routes.js', app_dir/'static/js/{0}/routes.js'.format(name))
    nix.mv(app_dir/'static/js/app/flow.js', app_dir/'static/js/{0}/flow.js'.format(name))

    templates = app_dir/'templates'/name
    templates.mkdir()

    assets = app_dir/'assets'
    assets.mkdir()
    assets_explainer = assets/'README.md'
    assets_explainer << """
    This placeholder file is here to ensure that there we still have our STATICFILES_DIRS target
    if we commit generated code to source control.

    This means that we can run collectstatic OK.
    """

    # Create lookup lists
    create_lookuplists(app_dir)

    # We have this here because it uses name from above.
    def manage(command):
        args = ['python', '{0}/manage.py'.format(name)]
        args += command.split()
        args.append('--traceback')

        try:
            subprocess.check_call(args)
        except subprocess.CalledProcessError:
            sys.exit(1)
        return

    # 8. Run Django's migrations
    write( 'Creating Database')
    manage('makemigrations {0}'.format(name))
    manage('migrate')

    # 9. Create a superuser
    sys.path.append(os.path.join(os.path.abspath('.'), name))
    _set_settings_module(name)

    from django.contrib.auth.models import User
    user = User(username='******')
    user.set_password('super1')
    user.is_superuser = True
    user.is_staff = True
    user.save()
    from opal.models import UserProfile
    profile, _ = UserProfile.objects.get_or_create(user=user)
    profile.force_password_change = False
    profile.save()

    # 11. Initialise git repo
    os.system('cd {0}; git init'.format(name))
Пример #34
0
def start_project(name, USERLAND_HERE):
    """
    In which we perform the steps required to start a new Opal project.

    1. Run Django' Startproject
    2. Create a data/lookuplists dir
    3. Copy across the scaffolding directory
    4. Interpolate our project data into the templates.
    5. Swap our scaffold app with the Django created app
    6. Interpolate the code templates from our scaffold app
    7. Create extra directories we need
    8. Run Django's migrations
    9. Create a superuser
    10. Initialise our git repo
    """

    project_dir = USERLAND_HERE/name
    if project_dir:
        write("\n\nDirectory {0} already exists !".format(project_dir))
        write("Please remove it or choose a new name.\n\n")
        sys.exit(1)

    # 1. Run Django Startproject
    write("Creating project dir at {0}".format(project_dir))
    os.system('django-admin.py startproject {0}'.format(name))

    write("Bootstrapping your Opal project...")

    if not project_dir:
        project_dir.mkdir()

    # Copy across the scaffold
    with SCAFFOLD:
        for p in SCAFFOLD.ls():
            target = project_dir/p[-1]
            p.cp(target)

    # Dotfiles need their dot back
    gitignore = project_dir/'gitignore'
    gitignore.mv(project_dir/'.gitignore')

    # Interpolate the project data
    interpolate_dir(project_dir, name=name, secret_key=get_random_secret_key(),
                    version=opal.__version__)

    app_dir = project_dir/name

    # Django Startproject creates some things - let's kill them &
    # replace with our own things.
    nix.rm(app_dir, recursive=True, force=True)
    nix.mv(project_dir/'app', app_dir)

    #  Create extra directories we need
    js = app_dir/'static/js/{0}'.format(name)
    css = app_dir/'static/css'
    js.mkdir()
    css.mkdir()
    nix.mv(app_dir/'static/js/app/routes.js',
           app_dir/'static/js/{0}/routes.js'.format(name))
    nix.mv(app_dir/'static/js/app/flow.js',
           app_dir/'static/js/{0}/flow.js'.format(name))

    templates = app_dir/'templates'/name
    templates.mkdir()

    assets = app_dir/'assets'
    assets.mkdir()
    assets_explainer = assets/'README.md'
    assets_explainer << """
    This placeholder file is here to ensure that there we still have our
    STATICFILES_DIRS target if we commit generated code to source control.

    This means that we can run collectstatic OK.
    """

    # Create lookup lists
    create_lookuplists(app_dir)

    # We have this here because it uses name from above.
    def manage(command):
        args = ['python', '{0}/manage.py'.format(name)]
        args += command.split()
        args.append('--traceback')

        try:
            subprocess.check_call(args)
        except subprocess.CalledProcessError:
            sys.exit(1)
        return

    # 8. Run Django's migrations
    write('Creating Database')
    manage('makemigrations {0}'.format(name))
    manage('migrate')

    # 9. Create a superuser
    sys.path.append(os.path.join(os.path.abspath('.'), name))
    _set_settings_module(name)

    from django.contrib.auth.models import User
    user = User(username='******')
    user.set_password('super1')
    user.is_superuser = True
    user.is_staff = True
    user.save()
    from opal.models import UserProfile
    profile, _ = UserProfile.objects.get_or_create(user=user)
    profile.force_password_change = False
    profile.save()

    # 11. Initialise git repo
    os.system('cd {0}; git init'.format(name))
Пример #35
0
def start_project(name, USERLAND_HERE):
    """
    In which we perform the steps required to start a new Opal project.

    1. Run Django' Startproject
    2. Create a data/lookuplists dir
    3. Copy across the scaffolding directory
    4. Interpolate our project data into the templates.
    5. Swap our scaffold app with the Django created app
    6. Interpolate the code templates from our scaffold app
    7. Create extra directories we need
    8. Run Django's migrations
    9. Create a superuser
    10. Initialise our git repo
    11. Load referencedata shipped with Opal
    """

    project_dir = USERLAND_HERE / name
    if project_dir:
        write("\n\nDirectory {0} already exists !".format(project_dir))
        write("Please remove it or choose a new name.\n\n")
        sys.exit(1)

    write("Bootstrapping your Opal project...")

    # 1. Run Django Startproject
    write("Creating project dir at {0}".format(project_dir))
    project_dir.mkdir()
    management.call_command('startproject', name, project_dir)

    # 3. Copy across the scaffold
    with SCAFFOLD:
        for p in SCAFFOLD.ls():
            target = project_dir / p[-1]
            p.cp(target)

    # Dotfiles need their dot back
    gitignore = project_dir / 'gitignore'
    gitignore.mv(project_dir / '.gitignore')

    # 4. Interpolate the project data
    interpolate_dir(project_dir,
                    name=name,
                    secret_key=get_random_secret_key(),
                    version=opal.__version__)

    app_dir = project_dir / name

    # 5. Django Startproject creates some things - let's kill them &
    # replace with our own things.
    nix.rm(app_dir, recursive=True, force=True)
    nix.mv(project_dir / 'app', app_dir)

    #  7. Create extra directories we need
    js = app_dir / 'static/js/{0}'.format(name)
    css = app_dir / 'static/css'
    js.mkdir()
    css.mkdir()
    nix.mv(app_dir / 'static/js/app/routes.js',
           app_dir / 'static/js/{0}/routes.js'.format(name))
    nix.mv(app_dir / 'static/js/app/flow.js',
           app_dir / 'static/js/{0}/flow.js'.format(name))

    templates = app_dir / 'templates' / name
    templates.mkdir()

    assets = app_dir / 'assets'
    assets.mkdir()
    assets_explainer = assets / 'README.md'
    assets_explainer << """
    This placeholder file is here to ensure that there we still have our
    STATICFILES_DIRS target if we commit generated code to source control.

    This means that we can run collectstatic OK.
    """

    # 2. Create lookup lists
    create_lookuplists(app_dir)

    # We have this here because it uses name from above.
    def manage(command):
        args = ['python', os.path.join(name, 'manage.py')]
        args += command.split()
        args.append('--traceback')
        call(args)

    # 8. Run Django's migrations
    write('Creating Database')
    manage('makemigrations {0}'.format(name))
    manage('migrate')

    # 9. Create a superuser
    write('Creating superuser')
    manage('createopalsuperuser')

    # 10. Initialise git repo
    call_if_exists(
        ('git', 'init'),
        'Unable to locate git; Skipping git repository initialization.',
        cwd=project_dir,
        stdout=subprocess.PIPE)

    # 11. Load referencedata shipped with Opal
    manage('load_lookup_lists')