Skip to content

Add temp utilities (alias OS::get_temp_dir(), FileAccess::create_temp(), and DirAccess::create_temp()) - #98397

Merged
Repiteo merged 1 commit into
godotengine:masterfrom
adamscott:add-tmp-support
Dec 3, 2024
Merged

Repiteo merged 1 commit into
godotengine:masterfrom
adamscott:add-tmp-support

Conversation

@adamscott

@adamscott adamscott commented Oct 21, 2024

Copy link
Copy Markdown
Member

This PR adds OS::get_temp_dir(), FileAccess::create_temp(), and DirAccess::create_temp() functions (the PR originally spelled tmp instead of temp), for all the supported platforms.

The concept of temporary files and directories

 There's already OS.get_cache_dir(), why do we need temporary files?

Temporary files and cache files are really similar, but they are distinct.

Cache files Temporary files
Can be deleted at any time by the user
Can be deleted at any time by the OS
Purpose Persistent temporary files, usually can be expected to be there the next time, useful after creation.  Volatile temporary files, usually not needed after use.
Example  Generated thumbnail icons. One-time write to a file to get the binary data of it.

So this is why Godot should support and provide an API for this special kind of files.

Methods

OS.get_temp_dir()

This function returns the global OS temporary dir for the application. It may be the root /tmp directory for most of the Unix/Linux systems, but for other platforms, it is the temporary dir given by the OS.

If no such thing as a temporary directory exist for the OS (ie. the Android platform), a directory inside the cache directory is chosen.

FileAccess.create_temp(int mode_flags, String prefix = "", String extension = "", bool keep = false)

This static function returns a FileAccess object with a temporary file open.

For sorting purposes, you can set prefix to the name of your project, just to be able to quickly debug temporary files if needed.

As ResourceLoaders usually detect the type of the file with the extension, you can pass a custom extension to add to the file name.

And if you set keep to true, the file will not get cleaned up when the FileAccess instance will be freed.

DirAccess.create_temp(String prefix = "", bool keep = false)

This static function returns a DirAccess object with a temporary directory open. Useful if you need temporary named files and directories.

prefix and keep exist such as in FileAccess.create_temp().

If keep is false, it will recursively delete the contents of the temporary directory when the DirAccess instance will be freed.