Skip to content

Commit a0ad4f5

Browse files
subsume wrap under create (#118)
* subsume wrap under create * typecase Path to str * improve README * improvements * suggested improvements * fix types * fix mypy * fix mypy issues * more mypy improvements * suggested changes
1 parent 403a5fc commit a0ad4f5

File tree

9 files changed

+195
-369
lines changed

9 files changed

+195
-369
lines changed

README.md

Lines changed: 49 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -28,44 +28,6 @@ $ pip install pyscript
2828

2929
## Usage
3030

31-
### wrap
32-
33-
#### Embed a Python script into a PyScript HTML file
34-
35-
```shell
36-
$ pyscript wrap <filename.py>
37-
```
38-
39-
This will generate a file called `<filename.html>` by default.
40-
This can be overwritten with the `-o` or `--output` option:
41-
42-
```shell
43-
$ pyscript wrap <filename.py> -o <another_filename.html>
44-
```
45-
46-
#### Open the script inside the browser using the `--show` option
47-
48-
```shell
49-
$ pyscript wrap <filename.py> --show
50-
```
51-
52-
#### Set a title for the browser tab
53-
54-
You can set the title of the browser tab with the `--title` option:
55-
56-
```shell
57-
$ pyscript wrap <filename.py> --title "My cool app!"
58-
```
59-
60-
#### Very simple command examples with `--command` option
61-
62-
The `-c` or `--command` option can be used to demo very simple cases.
63-
In this case, if the `--show` option is used and no `--output` file is used, a temporary file will be generated.
64-
65-
```shell
66-
$ pyscript wrap -c 'print("Hello World!")' --show
67-
```
68-
6931
### run
7032

7133
#### Spin up a local server to run on the path and specified port
@@ -109,3 +71,52 @@ The following files will be created:
10971
- `index.html`: start page for the project
11072
- `pyscript.toml`: project metadata and config file
11173
- `main.py`: a "Hello world" python starter module
74+
75+
#### Use --wrap to embed a python file OR a command string
76+
77+
- ##### Embed a Python script into a PyScript HTML file
78+
79+
```shell
80+
$ pyscript create --wrap <filename.py>
81+
```
82+
83+
This will generate a project i.e. a new directory named `filename` under the current directory.
84+
85+
Similar to the above, interactive prompts will further ask for metadata information.
86+
87+
The following files will be created:
88+
89+
- `index.html`: start page for the project
90+
- `pyscript.toml`: project metadata and config file
91+
- `main.py`: contains code of `filename.py`
92+
93+
This can be overridden with the `-o` or `--output` option:
94+
95+
```shell
96+
$ pyscript create --wrap <filename.py> -o <another_filename.html>
97+
```
98+
99+
i.e. the HTML file created in the above directory will now be named `another_filename.html`
100+
101+
- ##### Very simple command examples with `--command` option
102+
103+
The `-c` or `--command` option can be used to demo very simple cases.
104+
105+
By default, the name of the project folder created will be `pyscript-command-app` with the HTML file named `index.html`.
106+
107+
`-o/--output` option can be used with the `-c/--command` option to configure name of the project folder as well
108+
as the name of the resulting HTML file.
109+
110+
```shell
111+
$ pyscript create --wrap -c 'print("Hello World!")' -o <output_filename.html>
112+
```
113+
114+
This will generate a project i.e. a new directory named `output_filename` under the current directory.
115+
116+
Similar to the above, interactive prompts will further ask for metadata information.
117+
118+
The following files will be created:
119+
120+
- `output_filename.html`: start page for the project
121+
- `pyscript.toml`: project metadata and config file
122+
- `main.py`: contains code of the command string passed via `-c/--command`

src/pyscript/_generator.py

Lines changed: 36 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -68,55 +68,16 @@ def save_config_file(config_file: Path, configuration: dict):
6868
toml.dump(configuration, fp)
6969

7070

71-
def string_to_html(
72-
code: str,
73-
title: str,
74-
output_path: Path,
75-
template_name: str = "wrap.html",
76-
pyscript_version: str = LATEST_PYSCRIPT_VERSION,
77-
) -> None:
78-
"""Write a Python script string to an HTML file template.
79-
80-
Params:
81-
82-
- code(str): string containing the application code to be written to the
83-
PyScript app template
84-
- title(str): application title, that will be placed as title of the html
85-
app template
86-
- output_path(Path): path where to write the new html file
87-
- template_name(str): name of the template to be used
88-
- pyscript_version(str): version of pyscript to be used
89-
90-
Output:
91-
(None)
92-
"""
93-
template = _env.get_template(template_name)
94-
with output_path.open("w") as fp:
95-
fp.write(
96-
template.render(code=code, title=title, pyscript_version=pyscript_version)
97-
)
98-
99-
100-
def file_to_html(
101-
input_path: Path,
102-
title: str,
103-
output_path: Optional[Path],
104-
template_name: str = "wrap.html",
105-
pyscript_version: str = LATEST_PYSCRIPT_VERSION,
106-
) -> None:
107-
"""Write a Python script string to an HTML file template."""
108-
output_path = output_path or input_path.with_suffix(".html")
109-
with input_path.open("r") as fp:
110-
string_to_html(fp.read(), title, output_path, template_name, pyscript_version)
111-
112-
11371
def create_project(
114-
app_name: str,
72+
app_or_file_name: Optional[str],
11573
app_description: str,
11674
author_name: str,
11775
author_email: str,
11876
pyscript_version: str = LATEST_PYSCRIPT_VERSION,
11977
project_type: str = "app",
78+
wrap: bool = False,
79+
command: Optional[str] = None,
80+
output: Optional[str] = None,
12081
) -> None:
12182
"""
12283
New files created:
@@ -126,40 +87,63 @@ def create_project(
12687
index.html - start page for the project
12788
"""
12889
date_stamp = datetime.date.today()
90+
91+
if wrap:
92+
if command:
93+
# app_or_file_name is None in this case
94+
assert app_or_file_name is None
95+
if output:
96+
app_name = output.removesuffix(".html")
97+
else:
98+
app_name = "pyscript-command-app"
99+
else:
100+
assert app_or_file_name is not None
101+
app_name = app_or_file_name.removesuffix(".py")
102+
else:
103+
assert app_or_file_name is not None
104+
app_name = app_or_file_name
105+
129106
context = {
130107
"name": app_name,
131108
"description": app_description,
132109
"type": "app",
133110
"author_name": author_name,
134111
"author_email": author_email,
135-
"version": f"{date_stamp.year}.{date_stamp.month}.1",
112+
"version": f"{date_stamp.year}.{'{:02d}'.format(date_stamp.month)}.1",
136113
}
137114
app_dir = Path(".") / app_name
138115
app_dir.mkdir()
139116
manifest_file = app_dir / config["project_config_filename"]
140117

141118
save_config_file(manifest_file, context)
119+
output_path = app_dir / "index.html" if output is None else app_dir / output
142120

143-
index_file = app_dir / "index.html"
144121
if project_type == "app":
145122
template = "basic.html"
146-
elif project_type == "plugin":
147-
template = "plugin.html"
148123
else:
149124
raise ValueError(
150-
f"Unknown project type: {project_type}. Valid values are: 'app' and 'plugin'"
125+
f"Unknown project type: {project_type}. Valid values are: 'app'"
151126
)
152127

153-
# Save the new python file
154128
python_filepath = app_dir / "main.py"
155-
with python_filepath.open("w", encoding="utf-8") as fp:
156-
fp.write(TEMPLATE_PYTHON_CODE)
129+
130+
if not wrap:
131+
# Save the new python file
132+
with python_filepath.open("w", encoding="utf-8") as fp:
133+
fp.write(TEMPLATE_PYTHON_CODE)
134+
else:
135+
if command:
136+
with python_filepath.open("w", encoding="utf-8") as fp:
137+
fp.write(command)
138+
else:
139+
assert app_or_file_name is not None
140+
python_filepath.write_bytes(Path(app_or_file_name).read_bytes())
157141

158142
create_project_html(
159143
app_name,
160144
config["project_main_filename"],
161145
config["project_config_filename"],
162-
index_file,
146+
output_path,
163147
pyscript_version=pyscript_version,
164148
template=template,
165149
)

src/pyscript/cli.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from pyscript import __version__, app, console, plugins, typer
88
from pyscript.plugins import hookspecs
99

10-
DEFAULT_PLUGINS = ["create", "wrap", "run"]
10+
DEFAULT_PLUGINS = ["create", "run"]
1111

1212

1313
def ok(msg: str = ""):

src/pyscript/plugins/create.py

Lines changed: 55 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from typing import Optional
2+
13
import typer
24

35
from pyscript import LATEST_PYSCRIPT_VERSION, app, cli, plugins
@@ -6,10 +8,12 @@
68

79
@app.command()
810
def create(
9-
app_name: str = typer.Argument(..., help="The name of your new app."),
10-
app_description: str = typer.Option(..., prompt=True),
11-
author_name: str = typer.Option(..., prompt=True),
12-
author_email: str = typer.Option(..., prompt=True),
11+
app_or_file_name: Optional[str] = typer.Argument(
12+
None, help="The name of your new app or path to an input .py script"
13+
),
14+
app_description: str = typer.Option(None, help="App description"),
15+
author_name: str = typer.Option(None, help="Name of the author"),
16+
author_email: str = typer.Option(None, help="Email of the author"),
1317
pyscript_version: str = typer.Option(
1418
LATEST_PYSCRIPT_VERSION,
1519
"--pyscript-version",
@@ -18,25 +22,68 @@ def create(
1822
project_type: str = typer.Option(
1923
"app",
2024
"--project-type",
21-
help="Type of project that is being created. Supported types are: 'app' or 'plugin'",
25+
help="Type of project that is being created. Supported types are: 'app'",
26+
),
27+
wrap: bool = typer.Option(
28+
False,
29+
"-w",
30+
"--wrap",
31+
help="Use wrap mode i.e. embed a python script into an HTML file",
32+
),
33+
command: Optional[str] = typer.Option(
34+
None,
35+
"-c",
36+
"--command",
37+
help="If provided, embed a single command string. Meant to be used with `--wrap`",
38+
),
39+
output: Optional[str] = typer.Option(
40+
None,
41+
"-o",
42+
"--output",
43+
help="""Name of the resulting HTML output file. Meant to be used with `-w/--wrap`""",
2244
),
2345
):
2446
"""
2547
Create a new pyscript project with the passed in name, creating a new
26-
directory in the current directory.
48+
directory in the current directory. Alternatively, use `--wrap` so as to embed
49+
a python file instead.
2750
"""
51+
if not app_or_file_name and not command:
52+
raise cli.Abort(
53+
"Must provide either an input '.py' file or a command with the '-c' option."
54+
)
55+
56+
if app_or_file_name and command:
57+
raise cli.Abort("Cannot provide both an input '.py' file and '-c' option.")
58+
59+
if (output or command) and (not wrap):
60+
raise cli.Abort(
61+
"""`--output/-o`, and `--command/-c`
62+
are meant to be used with `--wrap/-w`"""
63+
)
64+
65+
if not app_description:
66+
app_description = typer.prompt("App description")
67+
if not author_name:
68+
author_name = typer.prompt("Author name")
69+
if not author_email:
70+
author_email = typer.prompt("Author email")
71+
2872
try:
2973
create_project(
30-
app_name,
74+
app_or_file_name,
3175
app_description,
3276
author_name,
3377
author_email,
3478
pyscript_version,
3579
project_type,
80+
wrap,
81+
command,
82+
output,
3683
)
3784
except FileExistsError:
3885
raise cli.Abort(
39-
f"A directory called {app_name} already exists in this location."
86+
f"A directory called {app_or_file_name} already exists in this location."
4087
)
4188

4289

0 commit comments

Comments
 (0)