Newer
Older
dub_jkp / source / dub / internal / temp_files.d
  1. /**
  2. Provides methods to generate temporary file names and folders and
  3. automatically clean them up on program exit.
  4.  
  5. Copyright: © 2012 Matthias Dondorff, © 2012-2023 Sönke Ludwig
  6. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
  7. Authors: Matthias Dondorff, Sönke Ludwig, Jan Jurzitza
  8. */
  9. module dub.internal.temp_files;
  10.  
  11. import std.file;
  12.  
  13. import dub.internal.vibecompat.core.file;
  14.  
  15. NativePath getTempDir()
  16. {
  17. return NativePath(std.file.tempDir());
  18. }
  19.  
  20. NativePath getTempFile(string prefix, string extension = null)
  21. {
  22. import std.uuid : randomUUID;
  23. import std.array: replace;
  24.  
  25. string fileName = prefix ~ "-" ~ randomUUID.toString() ~ extension;
  26.  
  27. if (extension !is null && extension == ".d")
  28. fileName = fileName.replace("-", "_");
  29.  
  30. auto path = getTempDir() ~ fileName;
  31. temporary_files ~= path;
  32. return path;
  33. }
  34.  
  35. private NativePath[] temporary_files;
  36.  
  37. static ~this()
  38. {
  39. foreach (path; temporary_files)
  40. {
  41. auto spath = path.toNativeString();
  42. if (spath.exists)
  43. std.file.remove(spath);
  44. }
  45. }