Beispiel #1
0
def new(sketch):
    """Main function of the module. This is what `ginpar new` calls.

    Parameters
    ----------
    sketch : str
        Name of the sketch to create
    """

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

    path = os.path.join(site["content_path"], sketch)

    _TEMPLATES_DIR = os.path.join(
        os.path.dirname(os.path.abspath(__file__)), "templates", "sketch"
    )
    _jinja_env = Environment(loader=FileSystemLoader(_TEMPLATES_DIR), trim_blocks=True)

    if os.path.isdir(path):
        error(f"Failure.")
        echo(f"{path} already exists.")
        raise click.Abort()

    create_folder(path)

    sketch_template = _jinja_env.get_template("sketch.js")
    data_template = _jinja_env.get_template("data.yaml")
    create_file(os.path.join(path, "sketch.js"), sketch_template.render())
    create_file(
        os.path.join(path, "data.yaml"),
        data_template.render(today=date.today().strftime("%Y-%m-%d")),
    )

    echo(f"\nYour new sketch {path} is ready.\n")
Beispiel #2
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.")
Beispiel #3
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.")
Beispiel #4
0
def quickstart(force):
    """Main function of the module. This is what `ginpar quickstart` calls.

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

    repo = "davidomarf/ginpar-quickstart"
    path = os.path.abspath("quickstart")

    if force:
        alert(
            "Forcing quickstart. This will replace existent directories and files.\n"
        )
        try_remove("quickstart")
        echo("")

    if os.path.isdir(path):
        error(f"`{path}` already exists.")
        echo("Delete it manually or run `ginpar quickstart -f` to force")
        raise click.Abort()

    if clone_repo(repo, path) == 0:
        if delete_git_files(path) == 0:
            echo(f"\nThe Ginpar sample site is ready.\n")
            echo("Run `cd quickstart` to move to the project directory.")
            echo(
                "Then run `ginpar build` or `ginpar serve` to see it working.")
    else:
        raise click.Abort()
Beispiel #5
0
def prompt_site_config(quick):
    """Echo the prompts and create the configuration dict.

    Echo the instructions and configuration fields, store each input,
    and create a dictionary containing those values.

    Parameters
    ----------
    quick : bool
        Returns the default values immediatle if True.

    Returns
    -------
    dict
        Used to generate the site configuration file.
    """
    site = {
        "author": "David Omar",
        "sitename": "My site",
        "description": "This is a Ginpar project",
        "url": "/",
        "theme": "davidomarf/gart",
        "content_path": "sketches",
        "build_path": "public",
    }

    if quick:
        return site

    info(
        "Welcome to ginpar! We'll ask for some values to initialize your project."
    )
    echo("")
    site["sitename"] = click.prompt("Site name", default=site["sitename"])
    site["description"] = click.prompt("Description",
                                       default=site["description"])
    site["author"] = click.prompt("Author", default=site["author"])
    site["url"] = click.prompt("url", default=site["url"])
    info("\nIf you're unsure about the next prompts, accept the defaults")
    echo("")
    site["theme"] = click.prompt("Theme", default=site["theme"])
    site["content_path"] = click.prompt("Sketches path",
                                        default=site["content_path"])
    site["build_path"] = click.prompt("Build path", default=site["build_path"])

    return site
Beispiel #6
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")
Beispiel #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
Beispiel #8
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.")
Beispiel #9
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"
    )
Beispiel #10
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
Beispiel #11
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.")