Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add basic project scaffolding functionality via CLI #78

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,4 @@ dependencies = [
tealish = "tealish.cli:cli"

[tool.setuptools.package-data]
tealish = ["langspec.json", "tealish_expressions.tx"]
tealish = ["langspec.json", "tealish_expressions.tx", "scaffold/**"]
91 changes: 76 additions & 15 deletions tealish/cli.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
import json
import pathlib
from os import getcwd
from shutil import copytree
from typing import IO, List, Optional, Tuple

import click
from typing import List, Optional, Tuple, IO
from tealish import compile_program, reformat_program

from tealish import compile_program, config, reformat_program
from tealish.build import assemble_with_algod, assemble_with_goal
from tealish.errors import CompileError, ParseError
from tealish.langspec import (
fetch_langspec,
get_active_langspec,
packaged_lang_spec,
local_lang_spec,
packaged_lang_spec,
)
from tealish.build import assemble_with_goal, assemble_with_algod
from tealish.utils import TealishMap

# TODO: consider using config to modify project structure
# TODO: make recursive building a flag?


def _build(
path: pathlib.Path,
Expand All @@ -21,28 +28,43 @@ def _build(
quiet: bool = False,
) -> None:
paths: List[pathlib.Path]

if path.is_dir():
paths = list(path.glob("*.tl"))
paths = [file.resolve().as_posix() for file in path.rglob("*.tl")]
if len(paths) == 0:
raise click.ClickException(
f"{path.name} and all of its subdirectories do not contain any Tealish files - aborting."
)
else:
if not path.name.endswith(".tl"):
raise click.ClickException(f"{path.name} is not a Tealish file - aborting.")
paths = [path.resolve().as_posix()]
path = path.parent

if not config.is_using_config:
_build_path = path / "build"
_contracts_path = path
else:
paths = [path]
_build_path = config.build_path
_contracts_path = config.contracts_path

for path in paths:
output_path = pathlib.Path(path).parent / "build"
output_path.mkdir(exist_ok=True)
filename = pathlib.Path(path).name
for p in paths:
filename = str(p).replace(f"{str(_contracts_path)}", f"{str(_build_path)}")
base_filename = filename.replace(".tl", "")

# Teal
teal_filename = output_path / f"{base_filename}.teal"
teal_filename = pathlib.Path(f"{base_filename}.teal")
if not quiet:
click.echo(f"Compiling {path} to {teal_filename}")
teal, tealish_map = _compile_program(open(path).read())
# TODO: change relative to build/contracts directories to avoid long prints
click.echo(f"Compiling {p} to {teal_filename}")
teal, tealish_map = _compile_program(open(p).read())
teal_string = "\n".join(teal + [""])
teal_filename.parent.mkdir(parents=True, exist_ok=True)
with open(teal_filename, "w") as f:
f.write("\n".join(teal + [""]))

if assembler:
tok_filename = output_path / f"{base_filename}.teal.tok"
tok_filename = f"{base_filename}.teal.tok"
if assembler == "goal":
if not quiet:
click.echo(
Expand Down Expand Up @@ -74,13 +96,42 @@ def _build(
f.write(bytecode)
# Source Map
tealish_map.update_from_teal_sourcemap(sourcemap)
map_filename = output_path / f"{base_filename}.map.json"
map_filename = f"{base_filename}.map.json"
if not quiet:
click.echo(f"Writing source map to {map_filename}")
with open(map_filename, "w") as f:
f.write(json.dumps(tealish_map.as_dict()).replace("],", "],\n"))


def _create_project(
project_name: str,
template: str,
quiet: bool = False,
) -> None:
project_path = pathlib.Path(getcwd()) / project_name

if not quiet:
click.echo(
f'Starting a new Tealish project named "{project_name}" with {template} template...'
)

# Only pure algosdk implementation for now.
# Can have other templates in the future like Algojig, Beaker, etc.
if template == "algosdk" or template is None:
# Relies on the template project being in Tealish package.
# Not ideal as they would all be downloaded when Tealish is downloaded.
# Templates should rather be in their own repositories and separately maintained.
# TODO: change to pulling from GitHub.
copytree(
pathlib.Path(__file__).parent / "scaffold",
project_path,
ignore=lambda x, y: ["__pycache__"],
)

if not quiet:
click.echo(f'Done - project "{project_name}" is ready for take off!')


def _compile_program(source: str) -> Tuple[List[str], TealishMap]:
try:
teal, map = compile_program(source)
Expand All @@ -100,6 +151,15 @@ def cli(ctx: click.Context, quiet: bool) -> None:
ctx.obj["quiet"] = quiet


@click.command()
@click.argument("project_name", type=str)
@click.option("--template", type=click.Choice(["algosdk"], case_sensitive=False))
@click.pass_context
def start(ctx: click.Context, project_name: str, template: str):
"""Start a new Tealish project"""
_create_project(project_name, template, quiet=ctx.obj["quiet"])


@click.command()
@click.argument("path", type=click.Path(exists=True, path_type=pathlib.Path))
@click.pass_context
Expand Down Expand Up @@ -218,6 +278,7 @@ def langspec_diff(url: str) -> None:
langspec.add_command(langspec_fetch, "fetch")
langspec.add_command(langspec_diff, "diff")

cli.add_command(start)
cli.add_command(compile)
cli.add_command(build)
cli.add_command(format)
Expand Down
33 changes: 33 additions & 0 deletions tealish/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import json
from os import getcwd
from pathlib import Path

CONFIG_FILE_NAME = "tealish.json"

is_using_config = False

project_root_path = Path(getcwd())

# Check if config file is present - if found then we assume the directory
# it's in must be the project root.
while True:
if (project_root_path / CONFIG_FILE_NAME).is_file():
is_using_config = True
break
if len(project_root_path.parts) == 1:
break
project_root_path = project_root_path.parent

if is_using_config:
with open(project_root_path / CONFIG_FILE_NAME) as f:
config = json.load(f)
try:
build_dir_name: str = config["directories"]["build"]
build_path = project_root_path / build_dir_name
except KeyError:
build_path = project_root_path / "build" # default
try:
contracts_dir_name: str = config["directories"]["contracts"]
contracts_path = project_root_path / contracts_dir_name
except KeyError:
contracts_path = project_root_path / "contracts" # default
133 changes: 133 additions & 0 deletions tealish/scaffold/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
# build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

.DS_Store
.idea
.vscode/
69 changes: 69 additions & 0 deletions tealish/scaffold/contracts/example/approval.tl
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#pragma version 8

if Txn.ApplicationID == 0:
# Handle Create App
exit(1)
end

switch Txn.OnCompletion:
NoOp: main
OptIn: opt_in
CloseOut: close_out
UpdateApplication: update_app
DeleteApplication: delete_app
end

block opt_in:
# Handle Opt In
# some statements here
# exit(1)

# OR
# Disallow Opt In
exit(0)
end

block close_out:
# Handle Close Out
# some statements here
# exit(1)

# OR
# Disallow Closing Out
exit(0)
end

block update_app:
# Handle Update App
# Example: Only allow the Creator to update the app
# exit(Txn.Sender == Global.CreatorAddress)
# exit(1)

# OR
# Disallow Update App
exit(0)
end

block delete_app:
# Handle Delete App
# Example: Only allow the Creator to update the app
# exit(Txn.Sender == Global.CreatorAddress)
# exit(1)

# OR
# Disallow Delete App
exit(0)
end

block main:
switch Txn.ApplicationArgs[0]:
"hello": hello
end

block hello:
log("Hello, world!")
exit(1)
end

exit(1)
end
Loading