Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Moved functionality over from `manim new` to `manim init` and added deprecation warning for `manim new` (#2842)

Joshua Mankelow9b731037d9f2
diff --git a/manim/cli/init/commands.py b/manim/cli/init/commands.py
index 410d7a9f0..28766f821 100644
--- a/manim/cli/init/commands.py
+++ b/manim/cli/init/commands.py
@@ -7,28 +7,192 @@ group.
"""
from __future__ import annotations
+import configparser
from pathlib import Path
+import click
import cloup
-from ...constants import CONTEXT_SETTINGS, EPILOG
-from ...utils.file_ops import copy_template_files
+from ... import console
+from ...constants import CONTEXT_SETTINGS, EPILOG, QUALITIES
+from ...utils.file_ops import (
+ add_import_statement,
+ copy_template_files,
+ get_template_names,
+ get_template_path,
+)
+
+CFG_DEFAULTS = {
+ "frame_rate": 30,
+ "background_color": "BLACK",
+ "background_opacity": 1,
+ "scene_names": "Default",
+ "resolution": (854, 480),
+}
+
+
+def select_resolution():
+ """Prompts input of type click.Choice from user. Presents options from QUALITIES constant.
+
+ Returns
+ -------
+ :class:`tuple`
+ Tuple containing height and width.
+ """
+ resolution_options = []
+ for quality in QUALITIES.items():
+ resolution_options.append(
+ (quality[1]["pixel_height"], quality[1]["pixel_width"]),
+ )
+ resolution_options.pop()
+ choice = click.prompt(
+ "\nSelect resolution:\n",
+ type=click.Choice([f"{i[0]}p" for i in resolution_options]),
+ show_default=False,
+ default="480p",
+ )
+ return [res for res in resolution_options if f"{res[0]}p" == choice][0]
+
+
+def update_cfg(cfg_dict, project_cfg_path):
+ """Updates the manim.cfg file after reading it from the project_cfg_path.
+
+ Parameters
+ ----------
+ cfg : :class:`dict`
+ values used to update manim.cfg found project_cfg_path.
+ project_cfg_path : :class:`Path`
+ Path of manim.cfg file.
+ """
+ config = configparser.ConfigParser()
+ config.read(project_cfg_path)
+ cli_config = config["CLI"]
+ for key, value in cfg_dict.items():
+ if key == "resolution":
+ cli_config["pixel_height"] = str(value[0])
+ cli_config["pixel_width"] = str(value[1])
+ else:
+ cli_config[key] = str(value)
+
+ with open(project_cfg_path, "w") as conf:
+ config.write(conf)
+
+
+ context_settings=CONTEXT_SETTINGS,
+ epilog=EPILOG,
+)
[email protected]("project_name", type=Path, required=False)
+ "-d",
+ "--default",
+ "default_settings",
+ is_flag=True,
+ help="Default settings for project creation.",
+ nargs=1,
+)
+def project(default_settings, **args):
+ """Creates a new project.
+
+ PROJECT_NAME is the name of the folder in which the new project will be initialized.
+ """
+ if args["project_name"]:
+ project_name = args["project_name"]
+ else:
+ project_name = click.prompt("Project Name", type=Path)
+
+ # in the future when implementing a full template system. Choices are going to be saved in some sort of config file for templates
+ template_name = click.prompt(
+ "Template",
+ type=click.Choice(get_template_names(), False),
+ default="Default",
+ )
+
+ if project_name.is_dir():
+ console.print(
+ f"\nFolder [red]{project_name}[/red] exists. Please type another name\n",
+ )
+ else:
+ project_name.mkdir()
+ new_cfg = {}
+ new_cfg_path = Path.resolve(project_name / "manim.cfg")
+
+ if not default_settings:
+ for key, value in CFG_DEFAULTS.items():
+ if key == "scene_names":
+ new_cfg[key] = template_name + "Template"
+ elif key == "resolution":
+ new_cfg[key] = select_resolution()
+ else:
+ new_cfg[key] = click.prompt(f"\n{key}", default=value)
+
+ console.print("\n", new_cfg)
+ if click.confirm("Do you want to continue?", default=True, abort=True):
+ copy_template_files(project_name, template_name)
+ update_cfg(new_cfg, new_cfg_path)
+ else:
+ copy_template_files(project_name, template_name)
+ update_cfg(CFG_DEFAULTS, new_cfg_path)
@cloup.command(
context_settings=CONTEXT_SETTINGS,
+ no_args_is_help=True,
epilog=EPILOG,
- short_help="""Sets up a new project in current working directory with default settings.\n
-It copies files from templates directory and pastes them in the current working dir.
-""",
)
-def init():
- """Sets up a new project in current working directory with default settings.
[email protected]("scene_name", type=str, required=True)
[email protected]("file_name", type=str, required=False)
+def scene(**args):
+ """Inserts a SCENE to an existing FILE or creates a new FILE.
+
+ SCENE is the name of the scene that will be inserted.
- It copies files from templates directory and pastes them in the current working dir.
+ FILE is the name of file in which the SCENE will be inserted.
"""
- cfg = Path("manim.cfg")
- if cfg.exists():
- raise FileExistsError(f"\t{cfg} exists\n")
+ if not Path("main.py").exists():
+ raise FileNotFoundError(f"{Path('main.py')} : Not a valid project directory.")
+
+ template_name = click.prompt(
+ "template",
+ type=click.Choice(get_template_names(), False),
+ default="Default",
+ )
+ scene = ""
+ with open(Path.resolve(get_template_path() / f"{template_name}.mtp")) as f:
+ scene = f.read()
+ scene = scene.replace(template_name + "Template", args["scene_name"], 1)
+
+ if args["file_name"]:
+ file_name = Path(args["file_name"] + ".py")
+
+ if file_name.is_file():
+ # file exists so we are going to append new scene to that file
+ with open(file_name, "a") as f:
+ f.write("\n\n\n" + scene)
+ else:
+ # file does not exist so we create a new file, append the scene and prepend the import statement
+ with open(file_name, "w") as f:
+ f.write("\n\n\n" + scene)
+
+ add_import_statement(file_name)
else:
- copy_template_files()
+ # file name is not provided so we assume it is main.py
+ # if main.py does not exist we do not continue
+ with open(Path("main.py"), "a") as f:
+ f.write("\n\n\n" + scene)
+
+
+ context_settings=CONTEXT_SETTINGS,
+ invoke_without_command=True,
+ no_args_is_help=True,
+ epilog=EPILOG,
+ help="Create a new project or insert a new scene.",
+)
+def init(ctx):
+ pass
+
+
+init.add_command(project)
+init.add_command(scene)
diff --git a/manim/cli/new/group.py b/manim/cli/new/group.py
index b9ee9ccfe..32fde0dfe 100644
--- a/manim/cli/new/group.py
+++ b/manim/cli/new/group.py
@@ -181,6 +181,7 @@ def scene(**args):
no_args_is_help=True,
epilog=EPILOG,
help="Create a new project or insert a new scene.",
+ deprecated=True,
)
@cloup.pass_context
def new(ctx):
diff --git a/tests/interface/test_commands.py b/tests/interface/test_commands.py
index aed2bf179..5ab293964 100644
--- a/tests/interface/test_commands.py
+++ b/tests/interface/test_commands.py
@@ -65,42 +65,32 @@ Made with <3 by Manim Community developers.
def test_manim_init_subcommand():
command = ["init"]
runner = CliRunner()
- runner.invoke(main, command, prog_name="manim")
-
- expected_manim_cfg = ""
- expected_main_py = ""
+ result = runner.invoke(main, command, prog_name="manim")
+ expected_output = """\
+Usage: manim init [OPTIONS] COMMAND [ARGS]...
- with open(
- Path.resolve(
- Path(__file__).parent.parent.parent / "manim/templates/template.cfg"
- ),
- ) as f:
- expected_manim_cfg = f.read()
+ Create a new project or insert a new scene.
- with open(
- Path.resolve(
- Path(__file__).parent.parent.parent / "manim/templates/Default.mtp"
- ),
- ) as f:
- expected_main_py = f.read()
+Options:
+ --help Show this message and exit.
- manim_cfg_path = Path("manim.cfg")
- manim_cfg_content = ""
- main_py_path = Path("main.py")
- main_py_content = ""
- with open(manim_cfg_path) as f:
- manim_cfg_content = f.read()
+Commands:
+ project Creates a new project.
+ scene Inserts a SCENE to an existing FILE or creates a new FILE.
- with open(main_py_path) as f:
- main_py_content = f.read()
+Made with <3 by Manim Community developers.
+"""
+ assert dedent(expected_output) == result.output
- manim_cfg_path.unlink()
- main_py_path.unlink()
- assert (
- dedent(expected_manim_cfg + "from manim import *\n" + expected_main_py)
- == manim_cfg_content + main_py_content
- )
+def test_manim_init_project(tmp_path):
+ command = ["init", "project", "--default", "testproject"]
+ runner = CliRunner()
+ with runner.isolated_filesystem(temp_dir=tmp_path) as tmp_dir:
+ result = runner.invoke(main, command, prog_name="manim", input="Default\n")
+ assert not result.exception
+ assert (Path(tmp_dir) / "testproject/main.py").exists()
+ assert (Path(tmp_dir) / "testproject/manim.cfg").exists()
def test_manim_new_command():
@@ -110,7 +100,7 @@ def test_manim_new_command():
expected_output = """\
Usage: manim new [OPTIONS] COMMAND [ARGS]...
- Create a new project or insert a new scene.
+ (DEPRECATED) Create a new project or insert a new scene.
Options:
--help Show this message and exit.