Skip to content

Commit

Permalink
Update __main__.py
Browse files Browse the repository at this point in the history
  • Loading branch information
ZeroIntensity authored Dec 7, 2023
1 parent f511b23 commit 1d41724
Showing 1 changed file with 111 additions and 99 deletions.
210 changes: 111 additions & 99 deletions src/view/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@

import getpass
import os
import random
import re
import subprocess
import venv as _venv
from pathlib import Path

import click

from ._logging import VIEW_TEXT
from .exceptions import AppNotFoundError

B_OPEN = "{"
Expand Down Expand Up @@ -53,26 +57,32 @@ def _get_email():


def success(msg: str) -> None:
click.secho(msg, fg="green", bold=True)
click.secho(f" - {msg}", fg="green", bold=True)


def warn(msg: str) -> None:
click.secho(msg, fg="yellow", bold=True)
click.secho(f" ! {msg}", fg="yellow", bold=True)


def error(msg: str) -> None:
click.secho(msg, fg="red", bold=True)
click.secho(f" ! {msg}", fg="red", bold=True)
exit(1)


def should_continue(msg: str):
if not click.confirm(
click.style(
msg,
fg="yellow",
)
):
exit(2)
def info(msg: str) -> None:
click.secho(f" * {msg}", fg="bright_magenta", bold=True)


def welcome() -> None:
click.secho(random.choice(VIEW_TEXT) + "\n", fg="blue", bold=True)
click.echo("Docs: ", nl=False)
click.secho("https://view.zintensity.dev", fg="blue", bold=True)
click.echo("GitHub: ", nl=False)
click.secho(
"https://github.com/ZeroIntensity/view.py",
fg="blue",
bold=True,
)


@click.group(invoke_without_command=True)
Expand All @@ -84,15 +94,7 @@ def main(ctx: click.Context, debug: bool) -> None:

enable_debug()
elif not ctx.invoked_subcommand:
click.secho("Welcome to view.py!", fg="green", bold=True)
click.echo("Docs: ", nl=False)
click.secho("https://view.zintensity.dev", fg="blue", bold=True)
click.echo("GitHub: ", nl=False)
click.secho(
"https://github.com/ZeroIntensity/view.py",
fg="blue",
bold=True,
)
welcome()


@main.group()
Expand Down Expand Up @@ -195,6 +197,37 @@ def deploy(target: str):


@main.command()
@click.option(
"--name",
"-n",
help="Project name.",
type=str,
default="my_app",
prompt="Project name",
)
@click.option(
"--load",
"-l",
help="Preset for route loading.",
default="simple",
type=click.Choice(("manual", "filesystem", "simple")),
prompt="Loader strategy",
)
@click.option(
"--repo",
"-r",
help="Whether a Git repository should be created.",
default=True,
is_flag=True,
prompt="Create repository?",
)
@click.option(
"--venv",
help="Whether a virtual environment should be created.",
default=True,
is_flag=True,
prompt="Create virtual environment?",
)
@click.option(
"--path",
"-p",
Expand All @@ -205,66 +238,72 @@ def deploy(target: str):
path_type=Path,
writable=True,
),
default="./",
prompt="Target path",
default=None,
)
@click.option(
"--type",
"-t",
help="Configuration type to initalize.",
default="toml",
type=click.Choice(("toml", "json", "ini", "py")),
)
@click.option(
"--load",
"-l",
help="Preset for route loading.",
default="filesystem",
type=click.Choice(("manual", "filesystem", "simple")),
prompt="Loader strategy",
type=click.Choice(("toml", "json", "ini", "yml", "py")),
)
@click.option(
"--no-project",
help="Disable creation of a pyproject.toml file.",
is_flag=True,
)
@click.option(
"--name",
"-n",
help="Project name to be used in configuration.",
type=str,
default="my_app",
prompt="Project name",
)
def init(path: Path, type: str, load: str, no_project: bool, name: str):
def init(
name: str,
repo: bool,
venv: bool,
path: Path | None,
type: str,
load: str,
no_project: bool,
):
from .config import make_preset

path = path or Path(f"./{name}")

fname = f"view.{type}"
if not path.exists():
success(f"Created `{path.relative_to('.')}`")
path.mkdir()

conf_path = path / fname
if conf_path.exists():
should_continue(f"`{conf_path}` already exists, overwrite?")
if repo:
info("Initializing repository...")
res = subprocess.call(["git", "init", str(path)])
if res != 0:
warn("failed to initalize git repository")

if venv:
info("Creating venv...")
venv_path = path / ".venv"
_venv.create(venv_path, with_pip=True)
success(f"Created virtual environment in {venv_path}")
info("Installing view.py...")
res = subprocess.call(
[(venv_path / "bin" / "pip").absolute(), "install", "view.py"]
)

if res != 0:
error("failed to install view.py")

conf_path = path / fname
with open(conf_path, "w") as f:
f.write(make_preset(type, load))

click.echo(f"Created `{fname}`")
success(f"Created `{fname}`")

app_path = path / "app.py"

if app_path.exists():
should_continue(f"`{app_path}` already exists, overwrite?")

from .__about__ import __version__

with open(app_path, "w") as f:
if load in {"filesystem", "simple"}:
f.write(
f"# view.py {__version__}"
"""
import view
"""import view
app = view.new_app()
app.run()
Expand All @@ -274,77 +313,50 @@ def init(path: Path, type: str, load: str, no_project: bool, name: str):
if load == "manual":
f.write(
f"# view.py {__version__}"
"""
import view
from routes.index import index
"""import view
app = view.new_app()
app.load([index])
@app.get("/")
async def index():
return "Hello, view.py!"
app.run()
"""
)

click.echo("Created `app.py`")
success("Created `app.py`")

if not no_project:
pyproject = path / "pyproject.toml"

if pyproject.exists():
should_continue("`pyproject.toml` already exists, overwrite?")

with pyproject.open("w", encoding="utf-8") as f:
f.write(PYPROJECT_BASE(name))

click.echo("Created `pyproject.toml`")

scripts = path / "utils"

if scripts.exists():
should_continue("`utils` already exists, overwrite?")

scripts.mkdir()
click.echo("Created `utils`")
success("Created `pyproject.toml`")

routes = path / "routes"
if routes.exists():
should_continue("`routes` already exists, overwrite?")
if load != "manual":
routes = path / "routes"
routes.mkdir()
success("Created `routes`")

routes.mkdir()
click.echo("Created `routes`")
index = routes / "index.py"

setup = path / "setup.py"

if setup.exists():
should_continue("`setup.py` already exists, overwrite?")

with open(setup, "w") as f:
f.write(
f"""from setuptools import setup
if __name__ == '__main__':
setup()"""
)

index = routes / "index.py"
pathstr = "" if load == "filesystem" else "'/'"
with open(index, "w") as f:
f.write(
f"""from view.routing import get
if index.exists():
should_continue(
f"`{index.relative_to('.')}` already exists, overwrite?"
)
pathstr = "" if load == "filesystem" else "'/'"
with open(index, "w") as f:
f.write(
f"""from view import get
@get({pathstr})
async def index():
return 'Hello, view.py!'
"""
)
@get({pathstr})
async def index():
return 'Hello, view.py!'
"""
)

click.echo("Created `routes/index.py`")
success("Created `routes/index.py`")

welcome()
success(f"Successfully initalized app in `{path}`")
return

Expand Down

0 comments on commit 1d41724

Please sign in to comment.