244 lines
8.2 KiB
Python
244 lines
8.2 KiB
Python
"""
|
|
Command-line interface for gallery generation.
|
|
|
|
Provides a CLI entry point for gallery generation and config management.
|
|
"""
|
|
|
|
import argparse
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
from gallery import generate
|
|
from gallery.config import ConfigManager, GalleryConfig, GallerySource, default_config_path
|
|
|
|
_WELCOME = """\
|
|
Gallery - Scientific Plot Gallery Generator
|
|
===========================================
|
|
|
|
Generates responsive static HTML galleries from collections of PDFs and HTMLs.
|
|
|
|
Getting started:
|
|
1. Set your web output directory:
|
|
gallery config set paths.web_folder /path/to/your/public_html
|
|
|
|
2. Add one or more plot sources:
|
|
gallery config add-source --name my_plots --path /path/to/plots
|
|
|
|
3. Generate your gallery:
|
|
gallery generate
|
|
|
|
Config commands:
|
|
gallery config list Show all settings
|
|
gallery config get <key> Get a single value (e.g. gallery.png_dpi)
|
|
gallery config set <key> <value> Update a setting (e.g. paths.web_folder /my/web)
|
|
gallery config add-source --name X --path P Add a plot source
|
|
gallery config remove-source <name> Remove a plot source
|
|
gallery config sources List configured sources
|
|
gallery config path Show config file location
|
|
|
|
Generate commands:
|
|
gallery generate Generate gallery from config
|
|
gallery generate --config myconfig.yaml Use a custom config file
|
|
gallery generate --clean Clean and regenerate everything
|
|
gallery generate --source /path/to/plots Regenerate one source only
|
|
gallery generate --verbose Print detailed output
|
|
|
|
Config file: {config_path}
|
|
"""
|
|
|
|
|
|
def _is_configured(config_path: Path) -> bool:
|
|
"""Return True if web_folder is set to a non-empty value."""
|
|
try:
|
|
mgr = ConfigManager(config_path)
|
|
web_folder = mgr.get("paths.web_folder")
|
|
return bool(web_folder and str(web_folder).strip())
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Config subcommand
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _cmd_config(argv: list) -> int:
|
|
parser = argparse.ArgumentParser(
|
|
prog="gallery config",
|
|
description="Read and write gallery configuration",
|
|
)
|
|
parser.add_argument(
|
|
"--config",
|
|
type=str,
|
|
default=None,
|
|
help="Path to config file (default: package config)",
|
|
)
|
|
sub = parser.add_subparsers(dest="action", metavar="ACTION")
|
|
|
|
sub.add_parser("list", help="Print all config values")
|
|
sub.add_parser("path", help="Print the resolved config file path")
|
|
|
|
p_get = sub.add_parser("get", help="Get a config value by key")
|
|
p_get.add_argument("key", help="Dot-separated key, e.g. gallery.png_dpi")
|
|
|
|
p_set = sub.add_parser("set", help="Set a config value")
|
|
p_set.add_argument("key", help="Dot-separated key, e.g. gallery.png_dpi")
|
|
p_set.add_argument("value", help="New value (YAML-parsed: use true/false for bools)")
|
|
|
|
p_add = sub.add_parser("add-source", help="Add a plot source")
|
|
p_add.add_argument("--name", default=None, help="Source name (default: bottom-level directory name)")
|
|
p_add.add_argument("--path", required=True, help="Path to source directory")
|
|
|
|
p_rm = sub.add_parser("remove-source", help="Remove a plot source by name")
|
|
p_rm.add_argument("name", help="Source name to remove")
|
|
|
|
sub.add_parser("sources", help="List all configured sources")
|
|
|
|
args = parser.parse_args(argv)
|
|
|
|
config_path = Path(args.config) if args.config else default_config_path()
|
|
mgr = ConfigManager(config_path)
|
|
|
|
if args.action == "path":
|
|
print(mgr.path)
|
|
|
|
elif args.action == "list":
|
|
import yaml
|
|
print(yaml.dump(mgr.list_all(), default_flow_style=False).rstrip())
|
|
|
|
elif args.action == "get":
|
|
try:
|
|
value = mgr.get(args.key)
|
|
print(value)
|
|
except KeyError as e:
|
|
print(f"Error: {e}", file=sys.stderr)
|
|
return 1
|
|
|
|
elif args.action == "set":
|
|
try:
|
|
mgr.set(args.key, args.value)
|
|
except Exception as e:
|
|
print(f"Error: {e}", file=sys.stderr)
|
|
return 1
|
|
|
|
elif args.action == "add-source":
|
|
try:
|
|
name = args.name or Path(args.path).resolve().name
|
|
mgr.add_source(name, args.path)
|
|
except ValueError as e:
|
|
print(f"Error: {e}", file=sys.stderr)
|
|
return 1
|
|
|
|
elif args.action == "remove-source":
|
|
try:
|
|
mgr.remove_source(args.name)
|
|
except KeyError as e:
|
|
print(f"Error: {e}", file=sys.stderr)
|
|
return 1
|
|
|
|
elif args.action == "sources":
|
|
sources = mgr.list_sources()
|
|
if not sources:
|
|
print("No sources configured.")
|
|
else:
|
|
for s in sources:
|
|
print(f" {s['name']}: {s['path']}")
|
|
|
|
else:
|
|
parser.print_help()
|
|
|
|
return 0
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Generate subcommand (existing behaviour)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _cmd_generate(argv: list) -> int:
|
|
parser = argparse.ArgumentParser(
|
|
prog="gallery generate",
|
|
description="Generate scientific gallery from plot collections",
|
|
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
epilog="""
|
|
Examples:
|
|
gallery generate # Generate using package config
|
|
gallery generate --config myconfig.yaml # Use custom config file
|
|
gallery generate --clean # Clean and regenerate
|
|
gallery generate --source /path/to/plots # Generate only specific source
|
|
""",
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--config",
|
|
type=str,
|
|
default=None,
|
|
help="Path to config.yaml (default: package bundled config)",
|
|
)
|
|
parser.add_argument("--clean", action="store_true", help="Clean gallery directory before generation")
|
|
parser.add_argument(
|
|
"--source",
|
|
type=str,
|
|
default=None,
|
|
help="Only recompute a specific source directory",
|
|
)
|
|
parser.add_argument("-v", "--verbose", action="store_true", help="Print verbose output")
|
|
|
|
args = parser.parse_args(argv)
|
|
|
|
config_path = Path(args.config) if args.config else default_config_path()
|
|
|
|
try:
|
|
config = GalleryConfig.from_yaml(config_path)
|
|
|
|
source_to_update = None
|
|
if args.source:
|
|
source_path = Path(args.source).resolve()
|
|
matching_source = None
|
|
for source in config.sources:
|
|
if Path(source.path).resolve() == source_path:
|
|
matching_source = source
|
|
break
|
|
if matching_source is None:
|
|
source_name = source_path.name
|
|
source_to_update = GallerySource(name=source_name, path=source_path)
|
|
config.sources.append(source_to_update)
|
|
if args.verbose:
|
|
print(f"Source {args.source} not in config. Adding temporarily as '{source_name}'")
|
|
else:
|
|
source_to_update = matching_source
|
|
|
|
success = generate(
|
|
config=config,
|
|
clean_first=args.clean,
|
|
verbose=args.verbose,
|
|
source_to_update=source_to_update,
|
|
)
|
|
return 0 if success else 1
|
|
|
|
except FileNotFoundError as e:
|
|
print(f"Error: {e}", file=sys.stderr)
|
|
return 1
|
|
except ValueError as e:
|
|
print(f"Error: {e}", file=sys.stderr)
|
|
return 1
|
|
except Exception as e:
|
|
print(f"Error: {e}", file=sys.stderr)
|
|
return 1
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Entry point
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def main():
|
|
if len(sys.argv) > 1 and sys.argv[1] == "config":
|
|
sys.exit(_cmd_config(sys.argv[2:]))
|
|
elif len(sys.argv) > 1 and sys.argv[1] == "generate":
|
|
sys.exit(_cmd_generate(sys.argv[2:]))
|
|
else:
|
|
print(_WELCOME.format(config_path=default_config_path()))
|
|
sys.exit(0)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|