Created
September 4, 2021 21:15
-
-
Save me2beats/8257bea22ded1866bd88fa6b98b7bfc7 to your computer and use it in GitHub Desktop.
file utils
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
static func get_files_by_ext(dir:String, extension:String, recursive=false)->Array: | |
var files = get_files(dir, recursive) | |
var res = [] | |
for i in files: | |
if i.get_extension() == extension: | |
res.push_back(i) | |
return res | |
const ERROR_MSG = "An error occurred when trying to access the path." | |
# push_warning vs push_error ? | |
# https://godotengine.org/qa/5175/how-to-get-all-the-files-inside-a-folder | |
static func get_dir_contents(rootPath: String) -> Array: | |
rootPath = rootPath.trim_suffix("/") | |
var files = [] | |
var directories = [] | |
var dir = Directory.new() | |
if dir.open(rootPath) == OK: | |
dir.list_dir_begin(true, false) | |
_add_dir_contents(dir, files, directories) | |
else: | |
push_warning(ERROR_MSG) | |
return [files, directories] | |
static func _add_dir_contents(dir: Directory, files: Array, directories: Array): | |
var file_name = dir.get_next() | |
while file_name != "": | |
var path = dir.get_current_dir() + "/" + file_name | |
if dir.current_is_dir(): | |
var subDir = Directory.new() | |
subDir.open(path) | |
subDir.list_dir_begin(true, false) | |
directories.append(path) | |
_add_dir_contents(subDir, files, directories) | |
else: | |
files.append(path) | |
file_name = dir.get_next() | |
dir.list_dir_end() | |
# get files non recursively | |
static func get_files(path:String, recursive=false)->Array: | |
if recursive: | |
return get_dir_contents(path)[0] | |
path = path.trim_suffix("/") | |
var dir = Directory.new() | |
var res = [] | |
if dir.open(path) == OK: | |
dir.list_dir_begin() | |
var file_name = dir.get_next() | |
while file_name != "": | |
if !dir.current_is_dir(): | |
res.push_back(path+"/"+file_name) | |
file_name = dir.get_next() | |
else: | |
push_warning(ERROR_MSG) | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment