Files
embedfs/embedfs.v
T
2026-05-05 23:02:06 +03:00

63 lines
1.9 KiB
V

module embedfs
import os
@[params]
pub struct EmbedFsParams {
pub:
module_name string = 'main' // name of the generated V module.
const_name string = 'embed_files' // name of the constant that will store the embedded data.
const_public bool // if true make the const public.
key_path_prefix string // path prefix for all embedded files, will be added to data map key.
file_path_prefix string // path prefix for files used in $embed_file() call in generated file.
compression bool // add zlib compression flag to $embed_file() call in generated file.
notice string = 'This file is generated by embedfs module, DO NOT EDIT!'
}
@[params]
pub struct GenerateParams {
EmbedFsParams
pub:
ignore []string // glob expressions for files that should not be embedded.
}
// generate generates the V code that embeds the contents of directory `dir`.
pub fn generate(dir string, params GenerateParams) !string {
files := collect_files(dir, params.ignore)
return generate_with(files, params.EmbedFsParams)!
}
// generate_with generates the V code that embeds the files listed in `paths`.
pub fn generate_with(paths []string, params EmbedFsParams) !string {
module_name := params.module_name
const_name := params.const_name
const_public := params.const_public
compression := params.compression
notice := params.notice
skip_notice := params.notice == ''
mut files := map[string]string{}
for file in paths {
file_path := if params.file_path_prefix == '' {
file
} else {
os.join_path_single(params.file_path_prefix, file)
}
files[os.join_path_single(params.key_path_prefix, file)] = file_path
}
result := $tmpl('embedfs.template')
return result
}
fn collect_files(path string, ignore []string) []string {
mut file_list := &[]string{}
os.walk(path, fn [mut file_list, ignore] (file string) {
for globexpr in ignore {
if file.match_glob(globexpr) {
return
}
}
file_list << file
})
return *file_list
}