예제 #1
0
def test_set_cfg():
    cfg = get_cfg()
    cfg['foo'] = 'bar'
    set_cfg(cfg)

    another_cfg = get_cfg()
    assert ('foo' in another_cfg)

    teardown_config()
예제 #2
0
def scaffold_model():
    cfg = get_cfg()
    # Add title
    title = string_input('What will you call your model? ').capitalize()
    cfg['current_scaffold']['model']['title'] = title
    cfg['current_scaffold']['model']['fields'] = []
    set_cfg(cfg)

    # Should never be necessary, but just in case.
    if 'models' not in cfg:
        cfg['models'] = []
        set_cfg(cfg)

    # Add owner field if necessary
    need_owner = False
    if cfg['need_users']:
        need_owner = boolean_input('Will users own instances of this model?')
    if need_owner:
        cfg['current_scaffold']['model']['fields'].append({
            'title': 'owner',
            'type': 'ForeignKey',
            'options': ['UserProfile', 'on_delete = models.CASCADE'],
            'string': f"owner = models.ForeignKey('UserProfile', on_delete = models.CASCADE)\n    "
        })

        cfg['current_scaffold']['need_owner'] = 'True'
    else:
        cfg['current_scaffold']['need_owner'] = 'False'
    set_cfg(cfg)

    # Add other fields
    print(' ')
    print('Let\'s create at least one model field now.')
    get_model_field()

    # Refresh config
    cfg = get_cfg()

    # Put the model in models.py
    f('$api/models.py', 'a', return_model())
    wl('Created the ' + title + ' model')

    # Put the model in config.json
    fields = cfg['current_scaffold']['model']['fields']
    title = cfg['current_scaffold']['model']['title']
    str_method = cfg['current_scaffold']['model']['__str__']
    cfg['models'].append({
        'title': title,
        'fields': fields,
        '__str__': str(str_method),
    })
    set_cfg(cfg)
예제 #3
0
def scaffold_details_page():
    cfg = get_cfg()
    title = cfg['current_scaffold']['model']['title']
    title_singular = title.lower()
    details_page = parse_content(f('$assets/pages/content_details.js', 'r'))
    f('$pages/' + title_singular + '.js', 'w', details_page)
    wl('Built the details page')
예제 #4
0
def scaffold_content_components():
    cfg = get_cfg()
    title = cfg['current_scaffold']['model']['title']
    need_owner = cfg['current_scaffold']['need_owner'] == 'True'
    content_plural = pluralize(title.lower())
    # Get the directory
    mkdir('$out/components/' + content_plural)
    comps = f('$out/components/' + content_plural, '$')

    # Make the files
    create_asset = parse_content(
        f('$assets/components/content_plural/Create.js', 'r'))
    f(comps + '/Create.js', 'w', create_asset)

    details_asset = parse_content(
        f('$assets/components/content_plural/Details.js', 'r'))
    f(comps + '/Details.js', 'w', details_asset)

    list_asset = parse_content(
        f('$assets/components/content_plural/List.js', 'r'))
    f(comps + '/List.js', 'w', list_asset)

    update_asset = parse_content(
        f('$assets/components/content_plural/Update.js', 'r'))
    f(comps + '/Update.js', 'w', update_asset)

    delete_asset = parse_content(
        f('$assets/components/content_plural/Delete.js', 'r'))
    f(comps + '/Delete.js', 'w', delete_asset)
예제 #5
0
def parse_shortcuts(path):
    cfg = get_cfg()
    output_name = cfg['backend_name']

    # Build all the paths
    su_path = cfg['paths']['super_root']
    prj_path = cfg['paths']['project_root']
    rc = os.path.join(su_path, 'reactjorc')
    ext = os.path.join(rc, 'extensions', RC_HOME)
    assets = os.path.join(ext, 'assets')
    out_path = os.path.join(prj_path, output_name)
    main_app = os.path.join(out_path, output_name)
    api = os.path.join(out_path, 'api')

    # Build the shortcuts
    shortcuts = {
        '$su': su_path,
        '$prj': prj_path,
        '$project': prj_path,
        '$rc': rc,
        '$ext': ext,
        '$extension': ext,
        '$assets': assets,
        '$out': out_path,
        '$output': out_path,
        '$main': main_app,
        '$api': api,
    }

    # Iterate over all shortcuts. If the path argument contains it, use it.
    parsed_string = path
    for key, value in shortcuts.items():
        parsed_string = os.path.join(parsed_string.replace(key, value))
    return parsed_string
예제 #6
0
def user_model_file():
    cfg = get_cfg()
    fields = cfg['current_scaffold']['model']['fields']

    # title_list = ["name", "email", "etc"]
    title_list = [field['title'] for field in fields]

    # quoted_list = ['"name"', '"email"', '"etc"']
    quoted_list = [quote(field['title']) for field in fields]

    # required_list = ['"email"', '"etc"']
    required_list = [field['title'] for field in fields]
    required_list.remove('name')
    required_list = [quote(field) for field in required_list]

    # assignment_list = ["email=email", "name=name"]
    assignment_list = [f'{title}={title}' for title in title_list]

    field_strings = [field['string'] for field in fields]
    model = f('$assets/models/UserProfile.py', 'r').replace(
        'title_list', ', '.join(title_list)).replace(
        'required_list', ', '.join(required_list)).replace(
        'field_strings', ''.join(field_strings)).replace(
        'assignment_list', ', '.join(assignment_list))

    f('$api/models.py', 'a', model)
    wl('Added UserProfile model')
예제 #7
0
def parse_shortcuts(path):
    cfg = get_cfg()
    OUTPUT_HOME = cfg['frontend_name']
    su_path = cfg['paths']['super_root']
    prj_path = cfg['paths']['project_root']
    out_path = os.path.join(prj_path, OUTPUT_HOME)

    shortcuts = {
        '$assets': os.path.join(su_path, 'reactjorc/extensions', RC_HOME,
                                'assets'),
        '$ext': os.path.join(su_path, 'reactjorc/extensions', RC_HOME),
        '$extension': os.path.join(su_path, 'reactjorc/extensions', RC_HOME),
        '$out': out_path,
        '$output': out_path,
        '$pages': os.path.join(out_path, 'pages'),
        '$project': prj_path,
        '$prj': prj_path,
        '$rc': os.path.join(su_path, 'reactjorc'),
        '$su': su_path,
    }
    if 'shortcuts' not in cfg['paths'].keys():
        cfg['paths']['shortcuts'] = shortcuts
    parsed_string = path
    for key, value in shortcuts.items():
        parsed_string = os.path.join(parsed_string.replace(key, value))
    return parsed_string
def test_mkdir():
    from helpers.config_manager import get_cfg
    mkdir('$su/tests/sandbox/path_manager', 'pm')
    assert (os.path.exists('tests/sandbox/path_manager'))
    assert ('pm' in get_cfg()['paths'].keys())

    # Teardown.
    os.rmdir(parse_shortcuts('$su/tests/sandbox/path_manager'))
    teardown_config()
예제 #9
0
def scaffold_config():
    cfg = get_cfg()
    cfg['current_scaffold'] = {}
    model = {
        "title": 'UserProfile',
        "fields": [
            {
                "title": "name",
                "type": "CharField",
                "options": [
                    "max_length = 255",
                    "unique = True"
                ],
                "string": "name = models.CharField(max_length=255, unique=True)\n    "
            },
            {
                "title": "email",
                "type": "EmailField",
                "options": [
                    "max_length = 255",
                    "unique = True"
                ],
                "string": "email = models.EmailField(max_length=255, unique=True)\n    "
            }
        ]
    }
    cfg['current_scaffold']['model'] = model
    cfg['current_scaffold']['need_owner'] = 'True'
    set_cfg(cfg)

    print(' ')
    print(' ')
    print(paint(return_model(), 'green'))
    print(' ')
    print(' ')
    if boolean_input('Add some fields to the user model?'):
        get_model_field()

    user_permission()

    # Push current_scaffold to models
    cfg = get_cfg()
    cfg['models'].append(cfg['current_scaffold']['model'])
    set_cfg(cfg)
예제 #10
0
def scaffold_view():
    cfg = get_cfg()

    new_view = f('$assets/views/new.py',
                 'r').format(title=cfg['current_scaffold']['model']['title'])
    f('$api/views.py', 'a', new_view)
    wl('Created a view')

    # Urls only make sense if there is a view. Putting it here.
    scaffold_url()
예제 #11
0
def mkdir(path, name=None):
    path = parse_shortcuts(path)
    # Create directory
    if not os.path.exists(path):
        os.mkdir(path)

    # Create path entry in config
    cfg = get_cfg()
    if not name in cfg['paths'].keys() and name is not None:
        cfg['paths'][name] = path
        set_cfg(cfg)
예제 #12
0
def new():
    backend_name = string_input('Name the Django backend app:', 'backend')
    need_users = True  # Kept for legacy
    cfg = get_cfg()
    cfg['need_users'] = str(need_users)
    cfg['backend_name'] = backend_name
    set_cfg(cfg)

    try:
        build_structure()
    except Exception as e:
        print(e)
예제 #13
0
def scaffold_url():
    cfg = get_cfg()
    title = cfg['current_scaffold']['model']['title']

    route = f('$assets/urls/new_api_url.py',
              'r').format(title=title, title_lower=title.lower())
    data = {
        'target': '# Register new routes below',
        'content': '# Register new routes below\n' + route
    }
    f('$api/urls.py', 'w', data)
    wl('Created url route')
예제 #14
0
def setup_config():
    src = file_read(config_asset_path)
    target = config_destination_path
    if not os.path.isdir(reactjorc_path):
        os.mkdir(reactjorc_path)
    file_write(target, src)
    cfg = get_cfg()
    super_root = os.getcwd()
    project_name = 'www'

    cfg['paths']['super_root'] = super_root
    cfg['paths']['project_root'] = os.path.join(super_root, project_name)

    set_cfg(cfg)
예제 #15
0
def scaffold_serializer():
    cfg = get_cfg()
    fields_arr = cfg['current_scaffold']['model']['fields']
    titles = [quote(field['title']) for field in fields_arr]
    if cfg['current_scaffold']['need_owner'] == 'True':
        titles.append(quote('owner_name'))

    fields_str = ', '.join(titles)
    fields_str = "'pk', " + fields_str

    new_serializer = f('$assets/serializers/new.py', 'r').format(
        title=cfg['current_scaffold']['model']['title'], fields=fields_str)

    f('$api/serializers.py', 'a', new_serializer)
    wl('Created new serializer')
예제 #16
0
def scaffold_menu_item():
    cfg = get_cfg()
    title = cfg['current_scaffold']['model']['title']
    title_plural = pluralize(title.capitalize())

    st = "import { list_type_permission } from '../services/permissions.js'\n"
    f('$out/components/Navbar.js', 'p', st.replace('type', title.lower()))

    st = "\n    {title: 'title_plural', permissions: list_type_permission},"
    st = st.replace('title_plural',
                    title_plural).replace('type', title.lower())
    data = {'target': ['const content_types'], 'content': st}
    f('$out/components/Navbar.js', 'a', data)

    wl(f'Added {title} menu item')
예제 #17
0
def scaffold_list_page():
    cfg = get_cfg()
    title = cfg['current_scaffold']['model']['title']
    title_plural = pluralize(title.lower())
    list_page = parse_content(f('$assets/pages/content_list.js', 'r'))
    f('$pages/' + title_plural + '.js', 'w', list_page)
    wl('Built the list page')

    # Add content type to server.js
    data = {
        'target': ['const content_types'],
        'content': quote(title.lower()) + ','
    }
    f('$out/server.js', 'a', data)
    wl('Add frontend CRUD routes')
예제 #18
0
def user_serializers():
    serializer = f('$assets/serializers/user_profile.py', 'r')
    cfg = get_cfg()
    fields = cfg['current_scaffold']['model']['fields']
    titles = [field['title'] for field in fields]
    fields_list = [',\n            ' + quote(t) for t in titles]

    # validated_list = [ name=validated_data['name'], etc ]
    validated_list = [
        f"\n            {t}=validated_data['{t}']," for t in titles
    ]
    serializer = serializer.replace(
        'fields_list', ''.join(fields_list)).replace(
        'validated_list', ''.join(validated_list))
    f('$api/serializers.py', 'a', serializer)
    wl('Added user serializer')
예제 #19
0
def content():
    cfg = get_cfg()
    cfg['current_scaffold'] = {'model': {}}
    set_cfg(cfg)

    scaffold_model()
    prev_path = os.getcwd()
    os.chdir(f('$out', '$'))
    subprocess.run([cfg['py_cmd'], 'manage.py', 'makemigrations'])
    subprocess.run([cfg['py_cmd'], 'manage.py', 'migrate'])
    os.chdir(prev_path)
    wl('Ran migrations')

    scaffold_permission()
    scaffold_view()
    scaffold_serializer()
    scaffold_admin()
예제 #20
0
def worklist(string, prev_path=None):
    # Solves issues with finding config.json after changing dirs
    if prev_path:
        next_path = os.getcwd()
        os.chdir(prev_path)

    cfg = get_cfg()

    # Create worklist if necessary. Should never be necessary.
    if not 'worklist' in cfg:
        cfg['worklist'] = []

    # Add worklist entry
    cfg['worklist'].append(string)
    set_cfg(cfg)

    if prev_path:
        os.chdir(next_path)
예제 #21
0
def new_permissionset():
    cfg = get_cfg()
    perm = cfg['current_scaffold']['permissions']
    title = cfg['current_scaffold']['model']['title']
    title = 'User' if title == 'UserProfile' else title

    new_permissions = f('$assets/services/new_permissionset.js', 'r').replace(
        'title', title.lower()).replace('upper', title).replace(
            'create_permission', perm['post'].lower() + '(user, obj)').replace(
                'list_permission',
                perm['list'].lower() + '(user, obj)').replace(
                    'details_permission',
                    perm['details'].lower() + '(user, obj)').replace(
                        'update_permission',
                        perm['update'].lower() + '(user, obj)').replace(
                            'delete_permission',
                            perm['delete'].lower() + '(user, obj)')
    f('$out/services/permissions.js', 'a', new_permissions)
예제 #22
0
def parse_content(string):
    cfg = get_cfg()
    title = cfg['current_scaffold']['model']['title']
    title_singular = title.capitalize()
    title_plural = pluralize(title.capitalize())
    if '__str__' in cfg['current_scaffold']['model']:
        string_method = cfg['current_scaffold']['model']['__str__']
    else:
        string_method = 'pk'

    all_fields = cfg['current_scaffold']['model']['fields']
    all_titles = [quote(field['title']) for field in all_fields]
    fields_string = ', '.join(all_titles)

    return string.replace('singular_lower', title_singular.lower()).replace(
        'plural_lower',
        title_plural.lower()).replace('plural_upper', title_plural).replace(
            'string_method',
            string_method).replace('singular_upper', title_singular).replace(
                'const fields = []', 'const fields = [' + fields_string + ']')
예제 #23
0
def return_model():
    cfg = get_cfg()
    fields = ''
    for field in cfg['current_scaffold']['model']['fields']:
        fields += field['string']

    new_model = f('$assets/models/new.py', 'r').format(
        title = cfg['current_scaffold']['model']['title'],
        fields = fields,
    )

    if '__str__' in cfg['current_scaffold']['model']:
        str_method = f('$assets/models/str_method.py', 'r').format(
            title = cfg['current_scaffold']['model']['__str__'],
        )
        new_model = new_model + str_method

    if cfg['current_scaffold']['need_owner'] == 'True':
        string = 'def owner_name(self):\n        return self.owner.name\n    '
        new_model = new_model + '\n    ' + string

    return new_model
def test_parse_shortcuts():
    setup_config()
    from helpers.config_manager import get_cfg
    cfg = get_cfg()

    actual = parse_shortcuts('$su')
    expected = os.getcwd()
    assert (actual == expected)

    actual = parse_shortcuts('$su/some/path')
    expected = os.path.join(os.getcwd(), 'some/path')
    assert (actual == expected)

    actual = parse_shortcuts('$rc')
    expected = os.path.join(cfg['paths']['super_root'], 'reactjorc')
    assert (actual == expected)

    actual = parse_shortcuts('$prj')
    expected = cfg['paths']['project_root']
    assert (actual == expected)

    actual = parse_shortcuts('$out')
    expected = os.path.join(cfg['paths']['project_root'], OUTPUT_HOME)
    assert (actual == expected)

    actual = parse_shortcuts('$ext')
    expected = os.path.join(cfg['paths']['super_root'], 'reactjorc/extensions',
                            RC_HOME)
    assert (actual == expected)

    actual = parse_shortcuts('$assets')
    expected = os.path.join(cfg['paths']['super_root'], 'reactjorc/extensions',
                            RC_HOME, 'assets')
    assert (actual == expected)

    actual = parse_shortcuts('$assets/test.txt')
    expected = os.path.join(cfg['paths']['super_root'], 'reactjorc/extensions',
                            RC_HOME, 'assets/test.txt')
    assert (actual == expected)
예제 #25
0
def build_settings(prev_path):
    os.chdir(prev_path)
    cfg = get_cfg()

    path_above_settings = f('$main', '$')
    settings_dir = os.path.join(path_above_settings, 'settings')

    # settings dir
    mkdir(settings_dir, 'settings_dir')

    # __init__ file
    init_asset = f('$assets/settings_init.py', 'r')
    init_output = f(os.path.join(settings_dir, '__init__.py'), '$')
    f(init_output, 'w', init_asset)

    # Settings variables
    old_settings_path = f(os.path.join(path_above_settings, 'settings.py'),
                          '$')
    base_settings_path = f(os.path.join(settings_dir, 'base.py'), '$')
    prod_settings_path = f(os.path.join(settings_dir, 'production.py'), '$')
    dev_settings_path = f(os.path.join(settings_dir, 'development.py'), '$')

    # Edit old settings file
    data = {
        'target': ['INSTALLED_APPS'],
        'content':
        "\n\t'api',\n\t'rest_framework',\n\t'rest_framework.authtoken',\n\t'corsheaders',"
    }
    f(old_settings_path, 'a', data)

    if cfg['need_users'] == 'True':
        f(old_settings_path, 'a', "\nAUTH_USER_MODEL = 'api.UserProfile'")

    drf_settings = dedent("""
    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.TokenAuthentication',
        ),
        'DEFAULT_PERMISSION_CLASSES': (
            'rest_framework.permissions.IsAuthenticatedOrReadOnly',
        )
    }
    """)

    if cfg['need_users'] == 'True':
        f(old_settings_path, 'a', drf_settings)

    data = {
        'target':
        "BASE_DIR =",
        'content':
        "BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))"
    }
    f(old_settings_path, 'w', data)

    # Add cors to middle of Middleware by replacing the whole list.
    old_file = f(old_settings_path, 'r')
    mid_i_begin = old_file.find('MIDDLEWARE = [')
    mid_i_end = old_file.find(']', mid_i_begin) + 1

    new_middle = dedent("""\
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'corsheaders.middleware.CorsMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]""")

    # Assemble the pieces.
    begin = old_file[:mid_i_begin]
    end = old_file[mid_i_end:]
    f(old_settings_path, 'w', begin + new_middle + end)

    # Copy settings files into dir, and remove original
    old_settings_file = f(old_settings_path, 'r')
    f(base_settings_path, 'w', old_settings_file)
    f(prod_settings_path, 'w', old_settings_file)
    f(dev_settings_path, 'w', old_settings_file)
    f(old_settings_path, 'd')

    # ENV specific configs
    data = {
        'target': "ALLOWED_HOSTS =",
        'content': "ALLOWED_HOSTS = ['localhost', '127.0.0.1']"
    }
    f(dev_settings_path, 'w', data)

    # PRODUCTION ONLY
    backend_name = cfg['backend_name']

    data = {'target': 'DEBUG = True', 'content': 'DEBUG = False'}
    f(prod_settings_path, 'w', data)

    data = {
        'target': 'ROOT_URLCONF = ',
        'content': "ROOT_URLCONF = '{}.urls'".format(backend_name)
    }
    f(prod_settings_path, 'w', data)

    data = {
        'target': "WSGI_APPLICATION = ",
        'content':
        "WSGI_APPLICATION = '{}.wsgi.application'".format(backend_name)
    }
    f(prod_settings_path, 'w', data)

    data = {'target': "STATIC_URL = '/static/'", 'content': ''}
    f(prod_settings_path, 'w', data)

    prod_drf_settings = """
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'utils.renderers.BrowsableAPIRendererWithoutForms',
    )"""
    data = {'target': ['REST_FRAMEWORK'], 'content': prod_drf_settings}
    f(prod_settings_path, 'a', data)

    db_settings = dedent("""\
    import dj_database_url
    db_from_env = dj_database_url.config(conn_max_age=500)
    DATABASES['default'].update(db_from_env)

    # CORS_ORIGIN_WHITELIST = ('your-frontend-app.herokuapp.com',)
    """)
    f(prod_settings_path, 'a', db_settings)

    cors = dedent("""\
    CORS_ORIGIN_WHITELIST = (
        'localhost:3000'
        '127.0.0.1:3000'
    )

    DEBUG_TOOLBAR_CONFIG = {
        'SHOW_TOOLBAR_CALLBACK': lambda x: True
    }
    """)
    f(dev_settings_path, 'a', cors)

    # Debug toolbar, dev only
    data = {'target': ['INSTALLED_APPS'], 'content': "\n\t'debug_toolbar',"}
    f(dev_settings_path, 'a', data)

    data = {
        'target': ['MIDDLEWARE'],
        'content': "\n\t'debug_toolbar.middleware.DebugToolbarMiddleware',"
    }
    f(dev_settings_path, 'a', data)
예제 #26
0
def test_get_cfg():
    setup_config()
    cfg = get_cfg()
    assert ('paths' in cfg)
예제 #27
0
def get_path(name):
    all_paths = get_cfg()['paths']
    path_names = all_paths.keys()
    ext_name = EXTENSION_NAME + "_" + name
    return ext_name if ext_name in all_paths else name
예제 #28
0
def ls():
    print(" ")
    for name, path in get_cfg()['paths'].items():
        print(path, "\t|\tp(" + name + ")")
    print(" ")
예제 #29
0
def scaffold_permission():
    cfg = get_cfg()
    # Get data
    title = cfg['current_scaffold']['model']['title']
    model = 'User' if title == 'UserProfile' else title
    all_types = [
        'Superuser', 'Staff', 'Authenticated', 'Anonymous', 'Active', 'Anyone',
        'Nobody', 'Owner'
    ]
    ownerless = all_types[:-1]
    custom = boolean_input('Customize permissions for ' + model + '?', 'y')
    auth = cfg['need_users'] == 'True'
    owner = cfg['current_scaffold']['need_owner'] == 'True'
    is_user = model == 'User'

    # Adjust data
    if not auth:
        all_types.remove('Authenticated')
        all_types.remove('Active')
    if not owner:
        all_types.remove('Owner')

    # Build the questions
    list_answer = 'Anyone'
    list_options = ownerless
    list_q = 'Who can view the list of all ' + pluralize(model.lower()) + '?'

    details_answer = 'Anyone'
    details_options = all_types
    details_q = 'Who can view the details of a ' + model.lower() + '?'

    post_answer = ''
    if is_user:
        post_answer = 'Anonymous'
    else:
        post_answer = 'Authenticated' if auth else 'Anyone'
    post_options = ownerless
    post_q = 'Who can create a ' + model.lower() + '?'

    update_answer = 'Owner' if owner else 'Staff'
    update_options = all_types
    update_q = 'Who can update an existing ' + model.lower() + '?'

    delete_answer = 'Owner' if owner else 'Staff'
    delete_options = all_types
    delete_q = 'Who can delete an existing ' + model.lower() + '?'

    # Ask questions if necessary
    if custom:
        list_answer = options_input(list_q, list_options, list_answer)
        details_answer = options_input(details_q, details_options,
                                       details_answer)
        post_answer = options_input(post_q, post_options, post_answer)
        update_answer = options_input(update_q, update_options, update_answer)
        delete_answer = options_input(delete_q, delete_options, delete_answer)

    # Update config
    cfg['current_scaffold']['permissions'] = {
        'list': list_answer,
        'details': details_answer,
        'post': post_answer,
        'update': update_answer,
        'delete': delete_answer,
    }
    set_cfg(cfg)

    # Build permisionset
    new_permission = f('$assets/permissions/new.py', 'r').format(
        Model=model,
        list_users=list_answer,
        details_users=details_answer,
        post_users=post_answer,
        update_users=update_answer,
        delete_users=delete_answer,
    )
    f('$api/permissions.py', 'a', new_permission)
    wl('Created permission')
예제 #30
0
def build_structure():
    prev_path = os.getcwd()
    cfg = get_cfg()

    frontend_name = string_input('Name the frontend Node.js app', 'frontend')
    cfg['frontend_name'] = frontend_name
    set_cfg(cfg)
    project_name = cfg['project_name']

    # directories
    mkdir('$out')
    mkdir('$out/__tests__')
    mkdir('$out/components')
    mkdir('$out/components/users')
    mkdir('$out/middleware')
    mkdir('$out/pages')
    mkdir('$out/redux')
    mkdir('$out/services')
    mkdir('$out/styles')
    mkdir('$out/styles/base')
    mkdir('$out/styles/hacks')
    mkdir('$out/styles/layout')
    mkdir('$out/styles/module')
    mkdir('$out/styles/state')
    mkdir('$out/styles/vendor')

    # Component assets
    f('$out/components/Head.js', 'w', '$assets/components/Head.js')
    f('$out/components/Navbar.js', 'w', '$assets/components/Navbar.js')

    # Middleware
    f('$out/middleware/set_uri.js', 'w', '$assets/middleware/set_uri.js')
    res_current_user = f('$assets/middleware/res_current_user.js',
                         'r').replace('reactjo', project_name)
    f('$out/middleware/res_current_user.js', 'w', res_current_user)

    # Misc assets
    f('$out/.env', 'w', '$assets/env.txt')
    f('$out/.babelrc', 'w', '$assets/babel.js')
    f('$out/.gitignore', 'w', '$assets/gitignore.txt')
    f('$out/.eslintrc.json', 'w', '$assets/eslint.js')
    f('$out/app.json', 'w', '$assets/app.js')
    f('$out/next.config.js', 'w', '$assets/next.config.js')
    f('$out/package.json', 'w', '$assets/package.js')
    f('$out/postcss.config.js', 'w', '$assets/postcss.config.js')
    f('$out/shim.js', 'w', '$assets/shim.js')

    # Redux
    f('$out/redux/store.js', 'w', '$assets/redux/store.js')
    f('$out/pages/redux_demo.js', 'w', '$assets/pages/redux_demo.js')
    f('$out/components/ReduxDemo.js', 'w', '$assets/components/ReduxDemo.js')

    server_string = f('$assets/server.js', 'r').replace(
        'random_string', id_generator()).replace('reactjo', project_name)

    f('$out/server.js', 'w', server_string)

    # Pages assets

    # Vars
    cfg = get_cfg()
    user_fields = cfg['current_scaffold']['model']['fields']
    user_titles = [field['title'] for field in user_fields]
    fields_arr = [quote(title) for title in user_titles]
    fields_arr.append(quote('password'))

    signup_page = f('$assets/pages/signup.js', 'r').replace(
        'const form_fields = []',
        'const form_fields = [' + ', '.join(fields_arr) + ']')

    user_page = f('$assets/pages/user.js', 'r').replace(
        'const fields = []', 'const fields = [' + ', '.join(fields_arr) + ']')

    # User Pages
    f('$out/pages/login.js', 'w', '$assets/pages/login.js')
    f('$out/pages/signup.js', 'w', signup_page)
    f('$out/pages/user.js', 'w', user_page)
    f('$out/pages/users.js', 'w', '$assets/pages/users.js')
    f('$out/pages/index.js', 'w', '$assets/pages/index.js')

    # User Components
    f('$out/components/users/Delete.js', 'w',
      '$assets/components/users/Delete.js')
    f('$out/components/users/Details.js', 'w',
      '$assets/components/users/Details.js')
    f('$out/components/users/List.js', 'w', '$assets/components/users/List.js')
    f('$out/components/users/Login.js', 'w',
      '$assets/components/users/Login.js')
    f('$out/components/users/Signup.js', 'w',
      '$assets/components/users/Signup.js')
    f('$out/components/users/Update.js', 'w',
      '$assets/components/users/Update.js')

    # Services assets
    f('$out/services/content_create.js', 'w',
      '$assets/services/content_create.js')
    f('$out/services/content_update.js', 'w',
      '$assets/services/content_update.js')
    f('$out/services/content_delete.js', 'w',
      '$assets/services/content_delete.js')
    f('$out/services/permissions.js', 'w', '$assets/services/permissions.js')
    f('$out/services/get_cookie.js', 'w', '$assets/services/get_cookie.js')
    f('$out/services/get_headers.js', 'w', '$assets/services/get_headers.js')
    f('$out/services/get_uri.js', 'w', '$assets/services/get_uri.js')

    # Vars
    cfg = get_cfg()
    user_fields = cfg['current_scaffold']['model']['fields']
    user_titles = [field['title'] for field in user_fields]
    quote_titles = [quote(title) for title in user_titles]
    set_cfg(cfg)

    # User Permissions
    new_permissionset()

    # Login
    login_service = f('$assets/services/login_service.js',
                      'r').replace('reactjo', project_name)
    f('$out/services/login_service.js', 'w', login_service)

    # Logout
    logout_service = f('$assets/services/logout_service.js',
                       'r').replace('reactjo', project_name)
    f('$out/services/logout_service.js', 'w', logout_service)

    # Signup
    signup_service = f('$assets/services/signup_service.js', 'r').replace(
        'let fields = []', 'let fields = [' + ', '.join(quote_titles) + ']')
    f('$out/services/signup_service.js', 'w', signup_service)

    # Check current_user
    current_user_service = f('$assets/services/current_user.js',
                             'r').replace('reactjo', project_name)
    f('$out/services/current_user.js', 'w', current_user_service)

    # Style assets
    f('$out/styles/index.scss', 'w', '$assets/styles/index.scss')
    f('$out/styles/base/_base.scss', 'w', '$assets/styles/base/_base.scss')
    f('$out/styles/base/_functions.scss', 'w',
      '$assets/styles/base/_functions.scss')
    f('$out/styles/base/_mixins.scss', 'w', '$assets/styles/base/_mixins.scss')
    f('$out/styles/base/_variables.scss', 'w',
      '$assets/styles/base/_variables.scss')
    f('$out/styles/hacks/_shame.scss', 'w', '$assets/styles/hacks/_shame.scss')
    f('$out/styles/layout/_body.scss', 'w', '$assets/styles/layout/_body.scss')
    f('$out/styles/layout/_header.scss', 'w',
      '$assets/styles/layout/_header.scss')
    f('$out/styles/layout/_grid.scss', 'w', '$assets/styles/layout/_grid.scss')
    f('$out/styles/module/_navigations.scss', 'w',
      '$assets/styles/module/_navigations.scss')
    f('$out/styles/module/_forms.scss', 'w',
      '$assets/styles/module/_forms.scss')
    f('$out/styles/module/_buttons.scss', 'w',
      '$assets/styles/module/_buttons.scss')
    f('$out/styles/state/_state.scss', 'w', '$assets/styles/state/_state.scss')
    wl('Build front end directories and files')

    # Tests
    mkdir('$out/__tests__/users')
    f('$out/__tests__/users/Delete.test.js', 'w',
      '$assets/tests/users/Delete.js')
    f('$out/__tests__/users/Details.test.js', 'w',
      '$assets/tests/users/Details.js')
    f('$out/__tests__/users/Update.test.js', 'w',
      '$assets/tests/users/Update.js')

    print('Installing node dependencies. This will take a while.')
    os.chdir(f('$out', '$'))

    if os.name == 'nt':
        subprocess.run('npm install', shell=True)
    else:
        subprocess.run(['npm', 'install'])

    os.chdir(prev_path)
    wl('Installed node dependencies')