Skip to content

Commit

Permalink
save relative paths to config file, if possible
Browse files Browse the repository at this point in the history
Although using paths that are *not* relative to the current working directory (cwd) is discouraged,
this *should* still be possible. So, if the path is not relative to cwd, we just save the absolute path.
  • Loading branch information
dennisvang committed Sep 5, 2023
1 parent 1b5db9d commit a101ece
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
23 changes: 19 additions & 4 deletions src/tufup/repo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -567,15 +567,30 @@ def app_version(self) -> str:

@classmethod
def get_config_file_path(cls) -> pathlib.Path:
# config must be stored in current working directory
return pathlib.Path.cwd() / cls.config_filename

def save_config(self):
"""Save current configuration."""
# todo: write directories relative to config file dir?
file_path = self.get_config_file_path()
file_path.write_text(
config_file_path = self.get_config_file_path()
# make paths relative to current working directory (cwd),
# if possible, otherwise keep absolute paths (note, to avoid
# confusion, using paths other than cwd is discouraged)
temp_config_dict = self.config_dict # note self.config_dict is a property
for key in ['repo_dir', 'keys_dir']:
try:
temp_config_dict[key] = temp_config_dict[key].relative_to(
pathlib.Path.cwd()
)
except ValueError:
logger.warning(
f'Saving *absolute* path in config, because the path is'
f' not relative to cwd: {temp_config_dict[key]}'
)
# write file
config_file_path.write_text(
data=json.dumps(
self.config_dict, default=str, sort_keys=True, indent=4
temp_config_dict, default=str, sort_keys=True, indent=4
),
encoding='utf-8',
)
Expand Down
4 changes: 2 additions & 2 deletions tests/test_repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -529,8 +529,8 @@ def test_save_config(self):
self.assertTrue(repo.get_config_file_path().exists())
config_file_text = repo.get_config_file_path().read_text()
print(config_file_text) # for convenience
# paths saved to config file must be relative (note that we should
# still be able to *read* absolute paths from the config file)
# paths saved to config file are relative to current working
# directory (cwd) if possible (otherwise absolute paths are saved)
config_dict = json.loads(config_file_text)
for key in ['repo_dir', 'keys_dir']:
with self.subTest(msg=key):
Expand Down

0 comments on commit a101ece

Please sign in to comment.