Newer
Older
dub_jkp / source / dub / installation.d
  1. /**
  2. Stuff related to installation.
  3.  
  4. Copyright: © 2012 Matthias Dondorff
  5. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
  6. Authors: Matthias Dondorff
  7. */
  8. module dub.installation;
  9.  
  10. import dub.internal.vibecompat.core.log;
  11. import dub.internal.vibecompat.core.file;
  12. import dub.internal.vibecompat.data.json;
  13. import dub.internal.vibecompat.inet.url;
  14. import dub.utils;
  15.  
  16. import std.array;
  17. import std.exception;
  18. import std.conv;
  19.  
  20.  
  21. const bool PRETTY_JOURNAL = true;
  22.  
  23.  
  24. /// Installation journal for later uninstallation, saved alongside the installation.
  25. /// Example Json:
  26. /// {
  27. /// "version": 1,
  28. /// "files": {
  29. /// "file1": "typeoffile1",
  30. /// ...
  31. /// }
  32. /// }
  33. class Journal {
  34. private const int Version = 1;
  35. enum Type {
  36. RegularFile,
  37. Directory,
  38. Alien
  39. }
  40. struct Entry {
  41. this( Type t, Path f ) { type = t; relFilename = f; }
  42. Type type;
  43. Path relFilename;
  44. }
  45. @property const(Entry[]) entries() const { return m_entries; }
  46. this() { }
  47. /// Initializes a Journal from a previous installation.
  48. this(Path journalFile) {
  49. auto jsonJournal = jsonFromFile(journalFile);
  50. enforce(cast(int)jsonJournal["Version"] == Version, "Mismatched version: "~to!string(cast(int)jsonJournal["Version"]) ~ "vs. " ~to!string(Version));
  51. foreach(string file, type; jsonJournal["Files"])
  52. m_entries ~= Entry(to!Type(cast(string)type), Path(file));
  53. }
  54. void add(Entry e) {
  55. foreach(Entry ent; entries) {
  56. if( e.relFilename == ent.relFilename ) {
  57. enforce(e.type == ent.type, "Duplicate('"~to!string(e.relFilename)~"'), different types: "~to!string(e.type)~" vs. "~to!string(ent.type));
  58. return;
  59. }
  60. }
  61. m_entries ~= e;
  62. }
  63. void save(Path p) {
  64. Json jsonJournal = serialize();
  65. auto fileJournal = openFile(p, FileMode.CreateTrunc);
  66. scope(exit) fileJournal.close();
  67. if(PRETTY_JOURNAL) fileJournal.writePrettyJsonString(jsonJournal);
  68. else fileJournal.writeJsonString(jsonJournal);
  69. }
  70. private Json serialize() const {
  71. Json[string] files;
  72. foreach(Entry e; m_entries)
  73. files[to!string(e.relFilename)] = to!string(e.type);
  74. Json[string] json;
  75. json["Version"] = Version;
  76. json["Files"] = files;
  77. return Json(json);
  78. }
  79. private {
  80. Entry[] m_entries;
  81. }
  82. }