About a week ago, I implemented a simple solution to specify Hops paths relative to the current script: Relative Paths
Unfortunately, that solution blows up when changing the directory of a file that contains clusters: Hops is missing inside some clusters
As I really want to use clusters with Hops in them, I thought, OK, then back to absolute paths, as much as a mistake that is. To make that work when moving stuff around, I created a script to update them. It only works with GHX files:
2024-04-21_update_paths.gh (6.8 KB)
The embedded Python code:
# In all Hops paths, replaces Olddir with the current directory.
#
# Creates a backup file first.
#
# Only works for definitions in GHX format.
#
# Felix E. Klee <felix.klee@inka.de>
import os;
import re;
def get_current_dir():
doc = ghenv.Component.OnPingDocument()
# In case of cluster, possibly nested, find parent document:
while doc.Owner is not None:
doc = doc.Owner.OwnerDocument()
return os.path.dirname(doc.FilePath)
def create_backup(file_path):
backup_file_path = f"{file_path}bak"
i = 1
while os.path.exists(backup_file_path):
backup_file_path = f"{file_path}bak{i}"
i += 1
os.rename(file_path, backup_file_path)
def fix_hops_paths(content, old_dir, new_dir):
old_dir.rstrip("\\")
new_dir.rstrip("\\")
pattern = r'(<[^>]*"RemoteDefinitionLocation"[^>]*>)' + re.escape(old_dir) + r'\\'
replacement = r'\1' + re.escape(current_dir) + r'\\'
return re.sub(pattern, replacement, content)
old_dir = Olddir
current_dir = get_current_dir()
definition_path = os.path.join(current_dir, Definition) + ".ghx"
with open(definition_path, 'r', encoding = 'utf-8') as file:
content = file.read()
new_content = fix_hops_paths(content, old_dir, current_dir)
create_backup(definition_path)
with open(definition_path, 'w', encoding='utf-8') as file:
file.write(new_content)
A definition and Hops functions for testing:
2024-04-21_definition.ghx (35.3 KB)
2024-04-21_double.gh (3.9 KB)
2024-04-21_half.gh (4.9 KB)
Every time, 2024-04-21_update_paths.gh
runs, it creates a backup. That worked at least during my tests.