VersionUpgrade44to45.py 9.5 KB

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