VersionUpgrade44to45.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. # Copyright (c) 2022 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import configparser
  4. from typing import Tuple, List
  5. import fnmatch # To filter files that we need to delete.
  6. import io
  7. import os # To get the path to check for hidden stacks to delete.
  8. import urllib.parse # To get the container IDs from file names.
  9. import re # To filter directories to search for hidden stacks to delete.
  10. from UM.Logger import Logger
  11. from UM.Resources import Resources # To get the path to check for hidden stacks to delete.
  12. from UM.Version import Version # To sort folders by version number.
  13. from UM.VersionUpgrade import VersionUpgrade
  14. # Settings that were merged into one. Each one is a pair of settings. If both
  15. # are overwritten, the key wins. If only the key or the value is overwritten,
  16. # that value is used in the key.
  17. _merged_settings = {
  18. "machine_head_with_fans_polygon": "machine_head_polygon",
  19. "support_wall_count": "support_tree_wall_count"
  20. }
  21. _removed_settings = {
  22. "support_tree_wall_thickness"
  23. }
  24. class VersionUpgrade44to45(VersionUpgrade):
  25. def __init__(self) -> None:
  26. """
  27. Creates the version upgrade plug-in from 4.4 to 4.5.
  28. In this case the plug-in will also check for stacks that need to be
  29. deleted.
  30. """
  31. super().__init__()
  32. # Only delete hidden stacks when upgrading from version 4.4. Not 4.3 or 4.5, just when you're starting out from 4.4.
  33. # If you're starting from an earlier version, you can't have had the bug that produces too many hidden stacks (https://github.com/Ultimaker/Cura/issues/6731).
  34. # If you're starting from a later version, the bug was already fixed.
  35. data_storage_root = os.path.dirname(Resources.getDataStoragePath())
  36. if os.path.exists(data_storage_root):
  37. folders = set(os.listdir(data_storage_root)) # All version folders.
  38. folders = set(filter(lambda p: re.fullmatch(r"\d+\.\d+", p), folders)) # Only folders with a correct version number as name.
  39. folders.difference_update({os.path.basename(Resources.getDataStoragePath())}) # Remove current version from candidates (since the folder was just copied).
  40. if folders:
  41. latest_version = max(folders, key = Version) # Sort them by semantic version numbering.
  42. if latest_version == "4.4":
  43. self.removeHiddenStacks()
  44. def removeHiddenStacks(self) -> None:
  45. """
  46. If starting the upgrade from 4.4, this will remove any hidden printer
  47. stacks from the configuration folder as well as all of the user profiles
  48. and definition changes profiles.
  49. This will ONLY run when upgrading from 4.4, not when e.g. upgrading from
  50. 4.3 to 4.6 (through 4.4). This is because it's to fix a bug
  51. (https://github.com/Ultimaker/Cura/issues/6731) that occurred in 4.4
  52. only, so only there will it have hidden stacks that need to be deleted.
  53. If people upgrade from 4.3 they don't need to be deleted. If people
  54. upgrade from 4.5 they have already been deleted previously or never got
  55. the broken hidden stacks.
  56. """
  57. Logger.log("d", "Removing all hidden container stacks.")
  58. hidden_global_stacks = set() # Which global stacks have been found? We'll delete anything referred to by these. Set of stack IDs.
  59. hidden_extruder_stacks = set() # Which extruder stacks refer to the hidden global profiles?
  60. hidden_instance_containers = set() # Which instance containers are referred to by the hidden stacks?
  61. exclude_directories = {"plugins"}
  62. # First find all of the hidden container stacks.
  63. data_storage = Resources.getDataStoragePath()
  64. for root, dirs, files in os.walk(data_storage):
  65. dirs[:] = [dir for dir in dirs if dir not in exclude_directories]
  66. for filename in fnmatch.filter(files, "*.global.cfg"):
  67. parser = configparser.ConfigParser(interpolation = None)
  68. try:
  69. parser.read(os.path.join(root, filename))
  70. except OSError: # File not found or insufficient rights.
  71. continue
  72. except configparser.Error: # Invalid file format.
  73. continue
  74. if "metadata" in parser and "hidden" in parser["metadata"] and parser["metadata"]["hidden"] == "True":
  75. stack_id = urllib.parse.unquote_plus(os.path.basename(filename).split(".")[0])
  76. hidden_global_stacks.add(stack_id)
  77. # The user container and definition changes container are specific to this stack. We need to delete those too.
  78. if "containers" in parser:
  79. if "0" in parser["containers"]: # User container.
  80. hidden_instance_containers.add(parser["containers"]["0"])
  81. if "6" in parser["containers"]: # Definition changes container.
  82. hidden_instance_containers.add(parser["containers"]["6"])
  83. os.remove(os.path.join(root, filename))
  84. # Walk a second time to find all extruder stacks referring to these hidden container stacks.
  85. for root, dirs, files in os.walk(data_storage):
  86. dirs[:] = [dir for dir in dirs if dir not in exclude_directories]
  87. for filename in fnmatch.filter(files, "*.extruder.cfg"):
  88. parser = configparser.ConfigParser(interpolation = None)
  89. try:
  90. parser.read(os.path.join(root, filename))
  91. except OSError: # File not found or insufficient rights.
  92. continue
  93. except configparser.Error: # Invalid file format.
  94. continue
  95. if "metadata" in parser and "machine" in parser["metadata"] and parser["metadata"]["machine"] in hidden_global_stacks:
  96. stack_id = urllib.parse.unquote_plus(os.path.basename(filename).split(".")[0])
  97. hidden_extruder_stacks.add(stack_id)
  98. # The user container and definition changes container are specific to this stack. We need to delete those too.
  99. if "containers" in parser:
  100. if "0" in parser["containers"]: # User container.
  101. hidden_instance_containers.add(parser["containers"]["0"])
  102. if "6" in parser["containers"]: # Definition changes container.
  103. hidden_instance_containers.add(parser["containers"]["6"])
  104. os.remove(os.path.join(root, filename))
  105. # Walk a third time to remove all instance containers that are referred to by either of those.
  106. for root, dirs, files in os.walk(data_storage):
  107. dirs[:] = [dir for dir in dirs if dir not in exclude_directories]
  108. for filename in fnmatch.filter(files, "*.inst.cfg"):
  109. container_id = urllib.parse.unquote_plus(os.path.basename(filename).split(".")[0])
  110. if container_id in hidden_instance_containers:
  111. try:
  112. os.remove(os.path.join(root, filename))
  113. except OSError: # Is a directory, file not found, or insufficient rights.
  114. continue
  115. def upgradePreferences(self, serialized: str, filename: str) -> Tuple[List[str], List[str]]:
  116. """Upgrades Preferences to have the new version number.
  117. This renames the renamed settings in the list of visible settings.
  118. """
  119. parser = configparser.ConfigParser(interpolation = None)
  120. parser.read_string(serialized)
  121. # Update version number.
  122. parser["metadata"]["setting_version"] = "11"
  123. result = io.StringIO()
  124. parser.write(result)
  125. return [filename], [result.getvalue()]
  126. def upgradeInstanceContainer(self, serialized: str, filename: str) -> Tuple[List[str], List[str]]:
  127. """Upgrades instance containers to have the new version number.
  128. This renames the renamed settings in the containers.
  129. """
  130. parser = configparser.ConfigParser(interpolation = None, comment_prefixes = ())
  131. parser.read_string(serialized)
  132. # Update version number.
  133. parser["metadata"]["setting_version"] = "11"
  134. if "values" in parser:
  135. # Merged settings: When two settings are merged, one is preferred.
  136. # If the preferred one is available, that value is taken regardless
  137. # of the other one. If only the non-preferred one is available, that
  138. # value is moved to the preferred setting value.
  139. for preferred, removed in _merged_settings.items():
  140. if removed in parser["values"]:
  141. if preferred not in parser["values"]:
  142. parser["values"][preferred] = parser["values"][removed]
  143. del parser["values"][removed]
  144. for removed in _removed_settings:
  145. if removed in parser["values"]:
  146. del parser["values"][removed]
  147. result = io.StringIO()
  148. parser.write(result)
  149. return [filename], [result.getvalue()]
  150. def upgradeStack(self, serialized: str, filename: str) -> Tuple[List[str], List[str]]:
  151. """Upgrades stacks to have the new version number."""
  152. parser = configparser.ConfigParser(interpolation = None)
  153. parser.read_string(serialized)
  154. # Update version number.
  155. if "metadata" not in parser:
  156. parser["metadata"] = {}
  157. parser["metadata"]["setting_version"] = "11"
  158. result = io.StringIO()
  159. parser.write(result)
  160. return [filename], [result.getvalue()]