Skip to main content

A simple utility to pretty-print a directory tree, suitable for use in pytest test cases.

Project description

yaml_to_disk

PyPI - Version python codecov tests code-quality license PRs contributors

A simple tool to let you define a directory structure in yaml form, then populate it on disk in a single command. Highly useful for simplifying test case setup, espically in doctest settings where readability is critical.

1. Installation

pip install yaml_to_disk

2. Usage

To use, you simply define a yaml representation of the files you want to populate, then call the function. E.g.,

>>> from yaml_to_disk import yaml_disk
>>> target_contents = '''
... dir1:
...   sub1:
...     file1.txt: "Hello, World!"
...   sub2:
...     cfg.yaml: {"foo": "bar"}
...     data.csv: |-2
...       a,b,c
...       1,2,3
... a.json:
...   - key1: value1
...     key2: value2
...   - str_element
... '''
>>> with yaml_disk(target_contents) as root_path:
...     print_directory(root_path)
...     print("---------------------")
...     print(f"file1.txt contents: {(root_path / 'dir1' / 'sub1' / 'file1.txt').read_text()}")
...     print(f"a.json contents: {(root_path / 'a.json').read_text()}")
...     print("cfg.yaml contents:")
...     print((root_path / 'dir1' / 'sub2' / 'cfg.yaml').read_text().strip())
...     print("data.csv contents:")
...     print((root_path / 'dir1' / 'sub2' / 'data.csv').read_text().strip())
├── a.json
└── dir1
    ├── sub1
       └── file1.txt
    └── sub2
        ├── cfg.yaml
        └── data.csv
---------------------
file1.txt contents: Hello, World!
a.json contents: [{"key1": "value1", "key2": "value2"}, "str_element"]
cfg.yaml contents:
foo: bar
data.csv contents:
a,b,c
1,2,3

You can also pass a filepath that contains the target yaml on disk, or a parsed view of the yaml contents (e.g., as a dictionary or a list):

>>> with tempfile.TemporaryDirectory() as temp_dir:
...     yaml_path = Path(temp_dir) / "target.yaml"
...     _ = yaml_path.write_text(target_contents)
...     with yaml_disk(yaml_path) as root_path:
...         print_directory(root_path)
├── a.json
└── dir1
    ├── sub1
       └── file1.txt
    └── sub2
        ├── cfg.yaml
        └── data.csv
>>> as_list = ["foo.png"] # Note that this will only make an empty file with this name
>>> with yaml_disk(as_list) as root_path:
...     print_directory(root_path)
└── foo.png
>>> as_dict = {"foo.pkl": {"bar": "baz"}}
>>> import pickle
>>> with yaml_disk(as_dict) as root_path:
...     print_directory(root_path)
...     print("----------------------")
...     with open(root_path / "foo.pkl", "rb") as f:
...         print(f"foo.pkl contents: {pickle.load(f)}")
└── foo.pkl
----------------------
foo.pkl contents: {'bar': 'baz'}

YAML Syntax

The YAML syntax specifies a list or ordered dictionaries of nested files and directories. In list form, a plain string list entry is either a file name (if it does not end in /) or a directory name (if it does end in /), and the file (or directory) will be created at the requisite location. If the entry is a dictionary, it must have a single key, which is the file (or directory) name, and the value is either the file contents (in various representations) or the nested directory contents. In this syntax, directories are not required to end in /, as file contents can only be added to files with extensions so that the package knows how to format them.

DIR_NAME:
  SUB_DIR_NAME:
    - FILE_NAME.EXT: FILE_CONTENT
    - FILE_NAME.EXT # No contents, just an empty file
    - SUB_DIR_NAME/ # No contents, just an empty directory
  SUB_DIR_NAME:
    FILE_NAME.EXT: FILE_CONTENT # Can also use a dictionary representation rather than a list if suitable

Supported Extensions:

Extension Description Accepts? Write Method
txt Plain text file Plain strings Written as is
json JSON file Any JSON compatible object Written via json.dump
yaml,yml YAML file Any YAML compatible object Written via yaml.dump
pkl Pickle file Any pickle serializable Written via pickle.dump
csv CSV file CSV data in either string, column-map, or a list of rows format See CSVFile for details

Other extensions can be used, but only in the empty files mode.

Adding new extensions:

You can easily add your own file extensions to be supported in your custom python packages by simply subclassing the FileType abstract base class and implementing the necessary methods and class variables. Then, you can register it as a supported extension by adding an entry point to your pyproject.toml file, like this:

[project.entry-points."yaml_to_disk.file_types"]
txt = "yaml_to_disk.file_types.txt:TextFile"
json = "yaml_to_disk.file_types.json:JSONFile"
pkl = "yaml_to_disk.file_types.pkl:PickleFile"
yaml = "yaml_to_disk.file_types.yaml:YAMLFile"
csv = "yaml_to_disk.file_types.csv:CSVFile"

Then, the system will automatically know how to match and use your new file type. Note that you cannot overwrite existing file extensions in this way; instead, if an overwrite is attempted, upon the load of all registered file types, an error will be raised.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

yaml_to_disk-0.0.1.tar.gz (18.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

yaml_to_disk-0.0.1-py3-none-any.whl (15.3 kB view details)

Uploaded Python 3

File details

Details for the file yaml_to_disk-0.0.1.tar.gz.

File metadata

  • Download URL: yaml_to_disk-0.0.1.tar.gz
  • Upload date:
  • Size: 18.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for yaml_to_disk-0.0.1.tar.gz
Algorithm Hash digest
SHA256 8ddbdf92d65141fc37c116d1e10b874fc2dec400e732a9fade0361160a12a624
MD5 d5e1a1f54032325850eeb05c8b25e4fd
BLAKE2b-256 b47536631d748885812100dd7f33f4a505a1f216a0f6653ebd0934460eda65fa

See more details on using hashes here.

Provenance

The following attestation bundles were made for yaml_to_disk-0.0.1.tar.gz:

Publisher: python-build.yaml on mmcdermott/yaml_to_disk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file yaml_to_disk-0.0.1-py3-none-any.whl.

File metadata

  • Download URL: yaml_to_disk-0.0.1-py3-none-any.whl
  • Upload date:
  • Size: 15.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for yaml_to_disk-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 30538b6bd882b3b8ec92f83479c4f64151686d8c835a6855182446ba61d44e21
MD5 17681f78469b978f3b4c690acb85a183
BLAKE2b-256 9bcb46b71517fb89fc585f68b51ecca1a267e818c7804ea1bbfbcf106ca6725c

See more details on using hashes here.

Provenance

The following attestation bundles were made for yaml_to_disk-0.0.1-py3-none-any.whl:

Publisher: python-build.yaml on mmcdermott/yaml_to_disk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page