Refactor: reorganize configuration management and add default config file
This commit is contained in:
+184
-62
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
Command-line interface for gallery generation.
|
||||
|
||||
Provides a CLI entry point for gallery generation when using git clone setup.
|
||||
Provides a CLI entry point for gallery generation and config management.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
@@ -9,113 +9,235 @@ import sys
|
||||
from pathlib import Path
|
||||
|
||||
from gallery import generate
|
||||
from gallery.config import GalleryConfig
|
||||
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 main():
|
||||
"""
|
||||
Main CLI entry point for gallery generation.
|
||||
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
|
||||
|
||||
Supports:
|
||||
- Loading config from YAML file (default: config.yaml)
|
||||
- Clean gallery directory before generation
|
||||
- Override to process only a specific source directory
|
||||
"""
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Config subcommand
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _cmd_config(argv: list) -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Generate scientific gallery from plot collections',
|
||||
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 from config.yaml
|
||||
gallery --config myconfig.yaml # Use custom config file
|
||||
gallery --clean # Clean and regenerate
|
||||
gallery --source /path/to/plots # Generate only specific source
|
||||
"""
|
||||
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='config.yaml',
|
||||
help='Path to config.yaml file (default: config.yaml)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--clean',
|
||||
action='store_true',
|
||||
help='Clean gallery directory before generation'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--source',
|
||||
"--config",
|
||||
type=str,
|
||||
default=None,
|
||||
help='Override to only recompute a specific source directory. '
|
||||
'If the directory is not in config, it will be added '
|
||||
'temporarily.'
|
||||
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(
|
||||
'-v', '--verbose',
|
||||
action='store_true',
|
||||
help='Print verbose output'
|
||||
"--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()
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
config_path = Path(args.config) if args.config else default_config_path()
|
||||
|
||||
try:
|
||||
# Load config from file
|
||||
config = GalleryConfig.from_yaml(args.config)
|
||||
config = GalleryConfig.from_yaml(config_path)
|
||||
|
||||
# Handle source override
|
||||
source_to_update = None
|
||||
if args.source:
|
||||
from gallery.config import GallerySource
|
||||
source_path = Path(args.source).resolve()
|
||||
|
||||
# Check if source is in config
|
||||
matching_source = None
|
||||
for source in config.sources:
|
||||
if Path(source.path).resolve() == source_path:
|
||||
matching_source = source
|
||||
break
|
||||
|
||||
# If not in config, create a temporary source entry
|
||||
if matching_source is None:
|
||||
source_name = source_path.name
|
||||
source_to_update = GallerySource(
|
||||
name=source_name,
|
||||
path=source_path
|
||||
)
|
||||
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. "
|
||||
f"Adding temporarily as '{source_name}'"
|
||||
)
|
||||
print(f"Source {args.source} not in config. Adding temporarily as '{source_name}'")
|
||||
else:
|
||||
source_to_update = matching_source
|
||||
|
||||
# Generate gallery
|
||||
success = generate(
|
||||
config=config,
|
||||
clean_first=args.clean,
|
||||
verbose=args.verbose,
|
||||
source_to_update=source_to_update
|
||||
source_to_update=source_to_update,
|
||||
)
|
||||
|
||||
sys.exit(0 if success else 1)
|
||||
return 0 if success else 1
|
||||
|
||||
except FileNotFoundError as e:
|
||||
print(f"Error: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
return 1
|
||||
except ValueError as e:
|
||||
print(f"Error: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
return 1
|
||||
except Exception as e:
|
||||
print(f"Error: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# ---------------------------------------------------------------------------
|
||||
# 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()
|
||||
|
||||
Reference in New Issue
Block a user