Skip to main content

tree

Macro tree 

Source
macro_rules! tree {
    ($($all:tt)+) => { ... };
}
Expand description

Macro for creating a FsTree.

§Syntax:

§Base syntax:

  • name represents a regular file with the given name.
  • name: [ ... ] is a directory.
  • name -> name is a symlink.
  • Commas are not accepted.

Here is a simple example:

use fs_tree::{FsTree, tree, TrieMap};

let trie = tree! {
    file1
    outer_dir: [
        file2
        inner_dir: [
            file3
        ]
        link1 -> target1
        link2 -> target2
    ]
};

let expected = FsTree::Directory(TrieMap::from([
    ("file1".into(), FsTree::Regular),
    ("outer_dir".into(), FsTree::Directory(TrieMap::from([
        ("file2".into(), FsTree::Regular),
        ("inner_dir".into(), FsTree::Directory(TrieMap::from([
            ("file3".into(), FsTree::Regular),
        ]))),
        ("link1".into(), FsTree::Symlink("target1".into())),
        ("link2".into(), FsTree::Symlink("target2".into())),
    ]))),
]));

assert_eq!(trie, expected);

§Other symbols

If you need symbols like - or ., you must use "" (double quotes):

use fs_tree::tree;

let my_tree = tree! {
    ".gitignore"
    ".config": [
        folder1: [
            folder2: [
                "complex-!@#%&-filename"
            ]
        ]
    ]
};

If the path you want is stored in a variable, you can insert an expression by enclosing it in {} (curly braces). The expression must implement Into<PathBuf> (e.g., String, &str, PathBuf).

use fs_tree::tree;

use std::path::PathBuf;

let hi = "hello ".to_string();

let regular_example = tree! {
    hardcoded_file_name
    {hi + " world!"}
    {100.to_string()}
    {PathBuf::from("look im using PathBuf now")}
};

let link = Link { from: "from", to: "to" };

let symlink_example = tree! {
    {link.from} -> {link.to}
};

let dir_name = "also works with directories".to_string();
let directory_example = tree! {
    {dir_name.to_uppercase()}: [
        file1
        file2
        file3
        file4
    ]
};

§Return Value

This macro always returns an FsTree::Directory containing the declared entries.

§Note

If duplicate keys are declared, later entries overwrite earlier ones (standard BTreeMap behavior).

§Alternatives

This macro isn’t always the easiest way to create an FsTree. See also: