Skip to content

Commit

Permalink
Update command func to return Error, added tests. (#14)
Browse files Browse the repository at this point in the history
* test scaffolding

* add github workflow

* match_all not working for now

* more scaffolding

* more tests

* add gitignore

* fix test

* update readme
  • Loading branch information
thatstoasty authored Apr 20, 2024
1 parent 2ed174a commit 70f24b6
Show file tree
Hide file tree
Showing 19 changed files with 608 additions and 174 deletions.
23 changes: 23 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Run Tests

on: ["push"]

jobs:
test:
runs-on: ubuntu-latest
environment: basic
steps:
- name: Check out repository code
uses: actions/checkout@v2
- name: Install dependencies
run: |
curl https://get.modular.com | MODULAR_AUTH=${{ secrets.MODULAR_AUTH }} sh -
modular auth ${{ secrets.MODULAR_AUTH }}
modular install nightly/mojo
pip install pytest
pip install git+https://github.com/guidorice/mojo-pytest.git
- name: Unit Tests
run: |
export MODULAR_HOME="/home/runner/.modular"
export PATH="/home/runner/.modular/pkg/packages.modular.com_nightly_mojo/bin:$PATH"
pytest
160 changes: 160 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
# 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/
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/
cover/

# 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
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .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

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__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/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
80 changes: 49 additions & 31 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,55 +19,68 @@ from prism import Flag, Command, CommandArc
from python import Python, PythonObject
fn base(command: CommandArc, args: List[String]) raises -> None:
fn base(command: CommandArc, args: List[String]) -> Error:
print("This is the base command!")
return Error()
fn print_information(command: CommandArc, args: List[String]) raises -> None:
fn print_information(command: CommandArc, args: List[String]) -> Error:
print("Pass cat or dog as a subcommand, and see what you get!")
return Error()
fn get_cat_fact(command: CommandArc, args: List[String]) raises -> None:
fn get_cat_fact(command: CommandArc, args: List[String]) -> Error:
var flags = command[].get_all_flags()[]
var lover = flags.get_as_bool("lover")
if lover and lover.value():
print("Hello fellow cat lover!")
var requests = Python.import_module("requests")
# URL you want to send a GET request to
var url = "https://cat-fact.herokuapp.com/facts/"
try:
var requests = Python.import_module("requests")
# Send the GET request
var response = requests.get(url)
# URL you want to send a GET request to
var url = "https://cat-fact.herokuapp.com/facts/"
# Check if the request was successful (status code 200)
if response.status_code == 200:
var count = flags.get_as_int("count")
if not count:
raise Error("Count flag was not found.")
var body = response.json()
for i in range(count.value()):
print(body[i]["text"])
else:
raise Error("Request failed!")
# Send the GET request
var response = requests.get(url)
# Check if the request was successful (status code 200)
if response.status_code == 200:
var count = flags.get_as_int("count")
if not count:
return Error("Count flag was not found.")
var body = response.json()
for i in range(count.value()):
print(body[i]["text"])
else:
return Error("Request failed!")
except e:
return e
fn get_dog_breeds(command: CommandArc, args: List[String]) raises -> None:
var requests = Python.import_module("requests")
# URL you want to send a GET request to
var url = "https://dog.ceo/api/breeds/list/all"
return Error()
# Send the GET request
var response = requests.get(url)
# Check if the request was successful (status code 200)
if response.status_code == 200:
print(response.json()["message"])
else:
raise Error("Request failed!")
fn get_dog_breeds(command: CommandArc, args: List[String]) -> Error:
try:
var requests = Python.import_module("requests")
# URL you want to send a GET request to
var url = "https://dog.ceo/api/breeds/list/all"
# Send the GET request
var response = requests.get(url)
fn init() raises -> None:
# Check if the request was successful (status code 200)
if response.status_code == 200:
print(response.json()["message"])
else:
return Error("Request failed!")
except e:
return e
return Error()
fn init() -> None:
var root_command = Command(name="nested", description="Base command.", run=base)
var get_command = Command(
Expand Down Expand Up @@ -96,8 +109,9 @@ fn init() raises -> None:
root_command.execute()
fn main() raises -> None:
fn main() -> None:
init()
```

Start by navigating to the `nested` example directory.
Expand Down Expand Up @@ -168,6 +182,8 @@ Usage information will be printed the console by passing the `--help` flag.

- Flags can have values passed by using the `=` operator. Like `--count=5` OR like `--count 5`.
- Commands can be created via a typical `Command()` constructor to use runtime values, or you can use `Command.new()` method to create a new `Command` using compile time `Parameters` instead (when possible).
- This library leans towards Errors as values over raising Exceptions.
- `Optional[Error]` would be much cleaner for Command run functions. For now return `Error()` if there's no `Error` to return.

## TODO

Expand All @@ -183,6 +199,8 @@ Usage information will be printed the console by passing the `--help` flag.
- Map `--help` flag to configurable help function.
- Add find suggestion logic to `Command` struct.
- Enable required flags.
- Replace print usage with writers to enable stdout/stderr/file writing.
- Split `Run` and `RunE` fields so that the primary run function `Run` can return no errors while `RunE` can return errors.

### Improvements

Expand Down
5 changes: 3 additions & 2 deletions examples/hello_world/printer.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ from prism import Flag, Command
from prism.command import CommandArc


fn printer(command: CommandArc, args: List[String]) raises -> None:
fn printer(command: CommandArc, args: List[String]) -> Error:
if len(args) == 0:
print("No args provided.")
return None
return Error()

print(args[0])
return Error()


fn build_printer_command() -> Command:
Expand Down
8 changes: 5 additions & 3 deletions examples/hello_world/root.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ from memory._arc import Arc


# TODO: Using CommandArc instead of Arc[Command] works. But using Arc[Command] causes a recursive relationship error?
fn test(command: CommandArc, args: List[String]) raises -> None:
fn test(command: CommandArc, args: List[String]) -> Error:
for item in command[].get_all_flags()[].flags:
print(item[].name, item[].value.value())

return Error()

fn init() raises -> None:

fn init() -> None:
var root_command = Command(
name="tones",
description="This is a dummy command!",
Expand All @@ -38,5 +40,5 @@ fn init() raises -> None:
root_command.execute()


fn main() raises -> None:
fn main() -> None:
init()
9 changes: 6 additions & 3 deletions examples/hello_world/say.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,19 @@ from prism import Flag, Command
from prism.command import CommandArc


fn say(command: CommandArc, args: List[String]) raises -> None:
fn say(command: CommandArc, args: List[String]) -> Error:
print("Shouldn't be here!")
return Error()


fn say_hello(command: CommandArc, args: List[String]) raises -> None:
fn say_hello(command: CommandArc, args: List[String]) -> Error:
print("Hello World!")
return Error()


fn say_goodbye(command: CommandArc, args: List[String]) raises -> None:
fn say_goodbye(command: CommandArc, args: List[String]) -> Error:
print("Goodbye World!")
return Error()


# for some reason returning the command object without setting it to variable breaks the compiler
Expand Down
Loading

0 comments on commit 70f24b6

Please sign in to comment.