1
- use std:: path:: { Path , PathBuf } ;
1
+ use std:: {
2
+ io:: { Error , ErrorKind } ,
3
+ path:: { Path , PathBuf } ,
4
+ } ;
2
5
3
6
use bevy_ecs:: { system:: Resource , world:: World } ;
4
7
5
8
use crate :: io:: AssetSourceBuilder ;
6
9
10
+ /// Private resource to store the temporary directory used by `temp://`.
11
+ /// Kept private as it should only be removed on application exit.
7
12
#[ derive( Resource ) ]
8
- struct TempAssetDirectory {
9
- folder : TempDirectory ,
10
- }
11
-
12
- impl TempAssetDirectory {
13
- fn path ( & self ) -> & Path {
14
- self . folder . path ( )
15
- }
16
- }
17
-
18
13
enum TempDirectory {
14
+ /// Uses [`TempDir`](tempfile::TempDir)'s drop behaviour to delete the directory.
15
+ /// Note that this is not _guaranteed_ to succeed, so it is possible to leak files from this
16
+ /// option until the underlying OS cleans temporary directories. For secure files, consider using
17
+ /// [`tempfile`](tempfile::tempfile) directly.
19
18
Delete ( tempfile:: TempDir ) ,
19
+ /// Will not delete the temporary directory on exit, leaving cleanup the responsibility of
20
+ /// the user or their system.
20
21
Persist ( PathBuf ) ,
21
22
}
22
23
@@ -32,17 +33,24 @@ impl TempDirectory {
32
33
pub ( crate ) fn get_temp_source (
33
34
world : & mut World ,
34
35
temporary_file_path : Option < String > ,
35
- ) -> AssetSourceBuilder {
36
- let temp_dir = world. get_resource_or_insert_with :: < TempAssetDirectory > ( || {
37
- let folder = match temporary_file_path {
36
+ ) -> std:: io:: Result < AssetSourceBuilder > {
37
+ let temp_dir = match world. remove_resource :: < TempDirectory > ( ) {
38
+ Some ( resource) => resource,
39
+ None => match temporary_file_path {
38
40
Some ( path) => TempDirectory :: Persist ( path. into ( ) ) ,
39
- None => TempDirectory :: Delete ( tempfile:: tempdir ( ) . expect ( "todo" ) ) ,
40
- } ;
41
+ None => TempDirectory :: Delete ( tempfile:: tempdir ( ) ?) ,
42
+ } ,
43
+ } ;
44
+
45
+ let path = temp_dir
46
+ . path ( )
47
+ . as_os_str ( )
48
+ . try_into ( )
49
+ . map_err ( |error| Error :: new ( ErrorKind :: InvalidData , error) ) ?;
41
50
42
- TempAssetDirectory { folder }
43
- } ) ;
51
+ let source = AssetSourceBuilder :: platform_default ( path, None ) ;
44
52
45
- let path = temp_dir . path ( ) . to_str ( ) . expect ( "todo" ) ;
53
+ world . insert_resource ( temp_dir ) ;
46
54
47
- AssetSourceBuilder :: platform_default ( path , None )
55
+ Ok ( source )
48
56
}
0 commit comments