Exemple #1
0
def copy_folder(fr, to, force=False):
    """Attempt (and optionally force) the copy of a folder.

    Parameters
    ----------
    fr : str
        From. Path of the folder to be copied.

    to : str
        To. Path of the to be created.

    force : bool
        Will remove an existing directory with the same name of ``to``, if it exists.
    """
    echo(f"\n> Copying `{to}` from `{fr}`:")

    exists = check_existence(to)

    if exists and force:
        try_remove(to)

    try:
        shutil.copytree(fr, to)
    except FileExistsError:
        error(f"Failure. It already exists.")
    else:
        success(f"Success.")
Exemple #2
0
def create_file(file, content):
    """Attempt the creation of a new file with custom content.

    Parameters
    ----------
    file : str
        Name of the file to be created (path must be included).

    content : str
        Content to write into the file.
    """
    echo(f"> Creating `{file}`:")
    try:
        config = open(file, "r")
    except:
        try:
            config = open(file, "w+")
        except:
            error("Failure.")
        else:
            config.write(content)
            config.close()
            success("Success.")
    else:
        config.close()
        error("Failure. It already exists.")
Exemple #3
0
def try_remove(path):
    """Attempt the removal of a path, either if it is a file or a directory.

    Parameters
    ----------
    path : str
        Must be an existing path.

    Notes
    -----
    To check for the existence of the path, previous to calling ``try_remove``, use
    `check_existence`_.
    """
    print(path)
    if os.path.isdir(path):
        echo(f"> `{path}` already exists. Attemping removal:")
        try:
            shutil.rmtree(path)
        except:
            error("Failure. Restart or delete manually.")
        else:
            success("Success.")
    elif os.path.isfile(path):
        echo(f"> `{path}` already exists. Attemping removal:")
        try:
            os.remove(path)
        except:
            error(f"Failure. Restart or delete manually.")
        else:
            success(f"Success.")
    else:
        echo(f"> `{path}` doesn't exist.")
        info("Skipping.")
Exemple #4
0
def build(path):
    """Main function of the module. This is what `ginpar build` calls.

    Parameters
    ----------
    build_path : str
        Path of the build.
    """

    _SITE_FILE = "config.yaml"
    _SITE = read_config(_SITE_FILE)

    _THEME = _SITE["theme"].split("/")[1]
    _THEME_PATH = os.path.join("themes", _THEME)

    _TEMPLATES_PATH = os.path.join(_THEME_PATH, "templates")
    _SKETCHES_PATH = _SITE["content_path"]

    _jinja_env = Environment(loader=FileSystemLoader(_TEMPLATES_PATH), trim_blocks=True)

    _jinja_env.filters["unkebab"] = unkebab
    _jinja_env.filters["getattrs"] = dict_to_attrs

    if not os.path.isdir(_THEME_PATH):
        clone_repo(_SITE["theme"], _THEME_PATH)
        delete_git_files(_THEME_PATH)

    input_templates = list(
        map(
            lambda t: _jinja_env.get_template(t),
            filter(
                lambda t: t.startswith(os.path.join("form", "inputs")),
                _jinja_env.list_templates(),
            ),
        )
    )

    create_publishing_directory(path)
    echo(f"Building in `{os.path.abspath(path)}`")

    copy_theme(path, _THEME)
    echo(f"Building using theme `{_THEME}`")

    ## Create the sketches list
    sketches = list(get_sketches(_SKETCHES_PATH))
    echo(f"Found {len(sketches)} sketch(es)")
    sketches.sort(key=lambda a: a["data"]["date"], reverse=True)

    render_index(path, sketches, _SITE, _jinja_env.get_template("index.html"))
    echo("Building main page")

    echo("Building sketches:")
    for sketch in sketches:
        echo(f"  Building {sketch['name']}")
        render_sketch_page(
            path, sketch, _SITE, _jinja_env.get_template("sketch.html"), input_templates
        )

    success("Success.")
Exemple #5
0
def create_folder(folder, force=False):
    """Attempt (and optionally force) the creation of a new folder.

    Parameters
    ----------
    folder : str
        Name of the folder to be created (path must be included).

    force : bool
        Will remove an existing directory with the same name, if it exists.
    """
    echo(f"> Creating `{folder}`:")
    try:
        os.makedirs(folder)
    except FileExistsError:
        error("Failure. It already exists.")
    except:
        error("Failure.")
    else:
        success("Sucess")
Exemple #6
0
def init(force, quick):
    """Main function of the module. This is what `ginpar init` calls.

    Parameters
    ----------
    force : bool
        Remove conflicting files when true.
    
    quick : bool
        Skip prompts when true.
    """

    if force:
        alert("You're forcing the initialization.")
        alert("This will replace any existent file relevant to the project.")
        click.confirm("Do you want to proceed?", abort=True)

    site = prompt_site_config(quick)
    path = space_to_kebab(site["sitename"]).lower()

    content_path = os.path.join(path, site["content_path"])
    config_yaml = os.path.join(path, "config.yaml")

    echo("\n---\n")

    if force:
        echo("\n---\n")
        try_remove(path)
        echo("\n---\n")

    create_folder(content_path)
    with open(config_yaml, "w") as file:
        yaml.dump(site, file)
        file.write(
            "scripts:\n  p5:\n    https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.min.js"
        )

    echo("\n---\n")
    success(
        "Done!\nRun `ginpar serve` or `ginpar build` and see your new site in action!\n"
    )
Exemple #7
0
def delete_git_files(path):
    """Delete the git files to only keep the relevant files

    Parameters
    ----------
    path : str
        Path to look for git files
    """

    echo("> Deleting .git files")
    try:
        print(os.path.join(path, ".git"))
        try_remove(os.path.join(path, ".git"))
        success("Successfully deleted .git files")
    except:
        error(
            f"Couldn't delete files. Delete all .git files manually in `{path}`"
        )
        return 1

    return 0
Exemple #8
0
def clone_repo(repo, path):
    """Clone the contents of a repository in a custom path

    Parameters
    ----------
    repo : str
        GitHub repository as in "{USER}/{REPO}"
    path : str
        Path to clone the repository to
    """

    repo_url = f"https://github.com/{repo}.git"

    echo(f"> Cloning {repo} in `{path}`")
    try:
        subprocess.call(["git", "clone", repo_url, path, "--quiet"])
    except OSError:
        error("You don't have git installed in your machine.")
        echo("Please install git and rerun or download the files manually:")
        echo(f"\t{repo_url}")
        return 1

    success(f"Successfully cloned {repo}.\n")
    return 0