Skip to content
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
0f3293f
move examples under pdf dir
cadenmyers13 Sep 23, 2025
c5c9f84
edit cli to reflect new path change
cadenmyers13 Sep 23, 2025
1092dcb
news
cadenmyers13 Sep 23, 2025
14102ad
fix typo
cadenmyers13 Sep 23, 2025
d423377
Revise examples in news/ex-path.rst for clarity
sbillinge Sep 24, 2025
683b4c3
rm type hint
cadenmyers13 Sep 25, 2025
71f9de4
merge to local: move news from added to changed
cadenmyers13 Sep 25, 2025
3a1ee8b
change list_examples to map_pack_to_examples which returns a dict
cadenmyers13 Sep 25, 2025
d3b531c
change variable name to reflect action properly
cadenmyers13 Sep 25, 2025
73d083e
change function name
cadenmyers13 Sep 25, 2025
61a9bd6
update docstring
cadenmyers13 Sep 25, 2025
012a45e
Merge branch 'main' of github.com:diffpy/diffpy.cmi into ex-path
cadenmyers13 Sep 25, 2025
d90a271
tests for help command, listing examples, and copying examples
cadenmyers13 Sep 25, 2025
c12f6b5
fix monkeypatch debugging code
cadenmyers13 Sep 25, 2025
c0bead8
update function names to be more readable
cadenmyers13 Sep 26, 2025
63ac630
test map pack to examples function
cadenmyers13 Sep 26, 2025
e0a2c75
add no packs, no examples case
cadenmyers13 Sep 26, 2025
81fa5cf
make sure directory was created
cadenmyers13 Sep 26, 2025
10771b1
add tests for copy_example
cadenmyers13 Sep 26, 2025
4ee36af
Add Error if pack or example doesnt exist
cadenmyers13 Sep 26, 2025
4019e36
Merge branch 'main' ex-path to see core example
cadenmyers13 Sep 26, 2025
65fd2c7
map packs function test, simplified
cadenmyers13 Sep 29, 2025
74e992b
add condition that catches extra slashes
cadenmyers13 Sep 29, 2025
d53fab8
test copy behavior
cadenmyers13 Sep 29, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions news/ex-path.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
**Added:**

* <news item>

**Changed:**

* change examples directory structure to insert the name of the ``pack" that the examples exemplify.

**Deprecated:**

* <news item>

**Removed:**

* <news item>

**Fixed:**

* <news item>

**Security:**

* <news item>
44 changes: 29 additions & 15 deletions src/diffpy/cmi/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,27 +52,33 @@ def _installed_examples_dir() -> Path:
)


def list_examples() -> List[str]:
"""List installed example names.
def get_examples_by_pack() -> dict[str, List[str]]:
"""Return a dictionary mapping pack name -> list of example
subdirectories.

Returns
-------
list of str
Installed example directory names.
dict:
pack name -> list of example subdirectory names
"""
root = _installed_examples_dir()
if not root.exists():
return []
return sorted([p.name for p in root.iterdir() if p.is_dir()])
return {}
examples_by_pack = {}
for pack_dir in sorted(root.iterdir()):
if pack_dir.is_dir():
exdirs = sorted(p.name for p in pack_dir.iterdir() if p.is_dir())
examples_by_pack[pack_dir.name] = exdirs
return examples_by_pack
Copy link
Contributor Author

@cadenmyers13 cadenmyers13 Sep 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

returns a dict, mapping pack name (str) to its corresponding list of examples (list of strs). This replaces previous format were all the examples are stored in one list.



def copy_example(example: str) -> Path:
def copy_example(pack_example: str) -> Path:
"""Copy an example into the current working directory.

Parameters
----------
example : str
Example directory name under the installed examples root.
Pack and example name in the form ``<pack>/<exdir>``.

Returns
-------
Expand All @@ -81,15 +87,20 @@ def copy_example(example: str) -> Path:

Raises
------
ValueError
If the format is invalid.
FileNotFoundError
If the example directory does not exist.
FileExistsError
If the destination directory already exists.
"""
src = _installed_examples_dir() / example
if "/" not in pack_example:
raise ValueError("Example must be specified as <pack>/<exdir>")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Enforces new format of copying examples. This format is cmi example copy <pack>/<exdir>

pack, exdir = pack_example.split("/", 1)
src = _installed_examples_dir() / pack / exdir
if not src.exists() or not src.is_dir():
raise FileNotFoundError(f"Example not found: {example}")
dest = Path.cwd() / example
raise FileNotFoundError(f"Example not found: {pack_example}")
dest = Path.cwd() / exdir
if dest.exists():
raise FileExistsError(f"Destination {dest} already exists")
copytree(src, dest)
Expand Down Expand Up @@ -163,7 +174,9 @@ def _build_parser() -> argparse.ArgumentParser:
_parser=p_example
)
p_example_copy = sub_ex.add_parser("copy", help="Copy an example to CWD")
p_example_copy.add_argument("name", metavar="EXAMPLE", help="Example name")
p_example_copy.add_argument(
"name", metavar="EXAMPLE", help="Example name <pack>/<exdir>"
)
p_example_copy.set_defaults(_parser=p_example)
p_example.set_defaults(example_cmd=None)

Expand Down Expand Up @@ -339,10 +352,11 @@ def _cmd_example(ns: argparse.Namespace) -> int:
print(f"Example copied to: {out}")
return 0
if ns.example_cmd == "list":
for g in list_examples():
print(g)
for pack, examples in get_examples_by_pack().items():
print(f"{pack}:")
for ex in examples:
print(f" - {ex}")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

prints examples in the format of

$ cmi example list
pack1:
 - exampleA
 - exampleB
pack2:
 - exampleC
 - exampleD

instead of

$ cmi example list
 exampleA
 exampleB
 exampleC
 exampleD

return 0

plog.error("Unknown example subcommand.")
ns._parser.print_help()
return 2
Expand Down
39 changes: 39 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import pytest

from diffpy.cmi.cli import main


def test_cli_help(capsys):
"""Test that the CLI help message is displayed correctly."""
with pytest.raises(SystemExit) as exc:
main(["--help", "-h"])
assert exc.value.code == 0
out, _ = capsys.readouterr()
assert "Welcome to diffpy.cmi" in out


def test_example_list(capsys):
"""Test that the example listing works."""
rc = main(["example", "list"])
assert rc == 0
out, _ = capsys.readouterr()
# test specific known pack and example
assert "ch03NiModelling" in out
assert "pdf" in out


def test_example_copy(monkeypatch, tmp_path):
"""Test that an example can be copied to the current directory."""
# create a fake example
fake_examples = tmp_path / "docs" / "examples"
src = fake_examples / "pack1" / "ex1"
src.mkdir(parents=True)
monkeypatch.setattr(
"diffpy.cmi.cli._installed_examples_dir",
lambda: fake_examples,
)
cwd = tmp_path
monkeypatch.chdir(cwd)
rc = main(["example", "copy", "pack1/ex1"])
assert rc == 0
assert (cwd / "ex1").exists()
Loading