Last active
November 28, 2022 05:58
-
-
Save selvinortiz/ca18f9a5476f9c6cc33e42bad643a339 to your computer and use it in GitHub Desktop.
Read PNG files as variants into a trait and add those traits to the collection to prepare layers for the next step in generating NFTs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::convert::AsRef; | |
use std::io::Result; | |
use std::path::{Path, PathBuf}; | |
#[derive(Debug)] | |
struct Trait { | |
name: String, | |
variants: Vec<String>, | |
} | |
#[derive(Debug)] | |
struct Collection { | |
name: String, | |
traits: Vec<Trait>, | |
} | |
impl Collection { | |
fn new(name: &str) -> Self { | |
Self { | |
name: name.to_string(), | |
traits: Vec::new(), | |
} | |
} | |
} | |
/// Reads files in a directory and returns a collection of PNG file paths | |
fn read_files_in_dir(dir: impl AsRef<Path>) -> Result<Vec<PathBuf>> { | |
Ok(std::fs::read_dir(dir)? | |
// We leverage that From knows how to turn an | |
// Iterator<Item = Result<T, E>> into a Result<Iterator<Item = T>, E> | |
.collect::<Result<Vec<_>>>()? | |
.into_iter() | |
.map(|entry| entry.path()) | |
.filter(|path| path.is_file() && path.extension().unwrap_or_default() == "png") | |
.collect()) | |
} | |
/// Reads direcotries in a directory and returns a collection of directory paths | |
fn read_dirs_in_dir(dir: impl AsRef<Path>) -> Result<Vec<PathBuf>> { | |
Ok(std::fs::read_dir(dir)? | |
// We leverage that From knows how to turn an | |
// Iterator<Item = Result<T, K>> into a Result<Iterator<Item = T>, K> | |
.collect::<Result<Vec<_>>>()? | |
.into_iter() | |
.map(|entry| entry.path()) | |
.filter(|path| path.is_dir()) | |
.collect()) | |
} | |
fn run() -> Result<Box<Collection>> { | |
let mut col = Collection::new("My Collection"); | |
let dirs = read_dirs_in_dir("/path/to/layers/directory")?; | |
// Read files in each directory and add them to the collection as a trait variants | |
for dir in dirs { | |
let files = read_files_in_dir(dir.clone())?; | |
let trait_name = dir.file_name().unwrap().to_str().unwrap().to_string(); | |
let variants = files | |
.into_iter() | |
.map(|path| path.to_string_lossy().to_string()) | |
.collect(); | |
col.traits.push(Trait { | |
name: trait_name, | |
variants, | |
}); | |
} | |
Ok(Box::new(col)) | |
} | |
fn main() { | |
let collection = run().expect("Failed to run"); | |
println!("\n🔥{}", collection.name); | |
collection.traits.into_iter().for_each(|trait_| { | |
println!("\n📁 {}", trait_.name); | |
trait_.variants.into_iter().for_each(|variant| { | |
println!("\t{:#?}", variant); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment