From b20aad7fd4019c84ff18d7dd492afd71ac613a6d Mon Sep 17 00:00:00 2001 From: ehennestad Date: Sun, 8 Nov 2026 20:06:50 +0100 Subject: [PATCH 1/2] fix(dloc): write a data location model on load only when it changed Constructing a DataLocationModel saved it unconditionally at the end of updateMetadataExtractorFunctionNames, and tempDevFix saved it again whenever a stored root path list was empty, because an empty list never gains the DiskType field. Every load rewrote a file that is meant to be kept under version control. The saves cannot simply be removed. Loading also generates missing uuids and converts older root path formats, and those values are referred to from other files, so they have to be stored once. The constructor now compares the content it would write with the file and writes only on a difference. fixDefaultDataLocation no longer has to report whether it changed anything. Co-Authored-By: Claude Opus 5.5 --- .../@DataLocationModel/DataLocationModel.m | 32 ++--- code/general/+utility/+data/StorableCatalog.m | 47 +++++++- .../DataLocationModelPersistenceTest.m | 112 ++++++++++++++++++ 3 files changed, 160 insertions(+), 31 deletions(-) create mode 100644 tests/+nansen/+unittest/+config/DataLocationModelPersistenceTest.m diff --git a/code/+nansen/+config/+dloc/@DataLocationModel/DataLocationModel.m b/code/+nansen/+config/+dloc/@DataLocationModel/DataLocationModel.m index 53d020d7..b1b0ff8d 100644 --- a/code/+nansen/+config/+dloc/@DataLocationModel/DataLocationModel.m +++ b/code/+nansen/+config/+dloc/@DataLocationModel/DataLocationModel.m @@ -92,15 +92,18 @@ obj.updateMetadataExtractorFunctionNames() obj.tempDevFix() + + % Loading and the two steps above bring older data up to date. + % That has to be stored, because generated values such as uuids + % are referred to from other files. + obj.saveIfChanged() end function tempDevFix(obj) - dirty = false; - % Add default data location to preferences if ~isfield(obj.Preferences, 'DefaultDataLocation') - dirty = obj.fixDefaultDataLocation() || dirty; + obj.fixDefaultDataLocation() end % Rootpath field changed from cell array with 2 cells to root @@ -110,7 +113,6 @@ function tempDevFix(obj) if any(strcmp(rootPath, '')) rootPath(strcmp(rootPath, '')) = []; - dirty = true; end obj.Data(i).RootPath = rootPath; @@ -119,7 +121,6 @@ function tempDevFix(obj) % Add 'Type' as a table variable on the third column if ~isfield(obj.Data, 'Type') obj.addTypeAsTableVariable() - dirty = true; end % Reorder so that Type is the third table variable @@ -130,19 +131,16 @@ function tempDevFix(obj) obj.Data = orderfields(obj.Data, ... [fieldNamesNew(1:2); 'Type'; fieldNamesNew(3:end)]); - dirty = true; end if ~isfield(obj.Preferences, 'SourceID') obj.Preferences.SourceID = utility.system.getComputerName(true); - dirty = true; end % Add a third variable (DiskName) to root path cell array. if ~isempty(obj.Data) if ~isfield( obj.Data(1).RootPath, 'DiskName' ) obj.addDiskNameToAllRootPaths() - dirty = true; end end @@ -150,7 +148,6 @@ function tempDevFix(obj) if ~isempty(obj.Data) if ~isfield( obj.Data(1).RootPath, 'DiskType' ) obj.addDiskTypeToAllRootPaths() - dirty = true; end end @@ -159,31 +156,22 @@ function tempDevFix(obj) for j = 1:numel(obj.Data(i).SubfolderStructure) if strcmp( obj.Data(i).SubfolderStructure(j).Type, "Animal") obj.Data(i).SubfolderStructure(j).Type = 'Subject'; - dirty = true; elseif isstring(obj.Data(i).SubfolderStructure(j).Type) obj.Data(i).SubfolderStructure(j).Type = char(obj.Data(i).SubfolderStructure(j).Type); - dirty = true; end if ~isfield(obj.Data(i).SubfolderStructure, 'IsFolder') [obj.Data(i).SubfolderStructure(:).IsFolder] = deal(true); - dirty = true; end end % Rename Animal ID to Subject ID for j = 1:numel(obj.Data(i).MetaDataDef) if strcmp( obj.Data(i).MetaDataDef(j).VariableName, "Animal ID") obj.Data(i).MetaDataDef(j).VariableName = 'Subject ID'; - dirty = true; elseif isstring(obj.Data(i).MetaDataDef(j).VariableName) obj.Data(i).MetaDataDef(j).VariableName = char(obj.Data(i).MetaDataDef(j).VariableName); - dirty = true; end end end - - if dirty - obj.save() - end end end @@ -973,7 +961,6 @@ function updateMetadataExtractorFunctionNames(obj) obj.Data(i).MetaDataDef(j).FunctionName = functionName; end end - obj.save() end function initializeLocalRootPathManager(obj) @@ -1028,24 +1015,19 @@ function onProjectRenamed(obj, oldName, newName) methods (Access = private) - function wasSet = fixDefaultDataLocation(obj) + function fixDefaultDataLocation(obj) %fixDefaultDataLocation Pick a default for a model that has none % % Chooses the first data location whose type may be a default, % which excludes read only types such as recorded. When no data % location qualifies the preference is left unset, so that a % default is picked once a qualifying data location is added. - % The output says whether a default was set, so that the caller - % only marks the model dirty when there is something to save. % Todo: Add uuid, not name - wasSet = false; - for i = 1:obj.NumDataLocations if obj.Data(i).Type.AllowAsDefault obj.DefaultDataLocation = obj.Data(i).Name; - wasSet = true; return end end diff --git a/code/general/+utility/+data/StorableCatalog.m b/code/general/+utility/+data/StorableCatalog.m index 73d431a6..848455eb 100644 --- a/code/general/+utility/+data/StorableCatalog.m +++ b/code/general/+utility/+data/StorableCatalog.m @@ -286,16 +286,40 @@ function resolveFilePath(obj) obj.SaveFormat = obj.getFormatFromPath(obj.FilePath); end + function saveIfChanged(obj) + %saveIfChanged Save data unless the file already holds the same content + % + % For work that runs on every load, such as migrating older data. + % A migration that changes the data reaches the file, and a load + % that changes nothing leaves a file under version control alone. + S = obj.cleanStructOnSave(obj.toStruct()); + + if ~obj.isCatalogFileContent(S) + obj.save() + end + end + + function tf = isCatalogFileContent(obj, S) + %isCatalogFileContent Test if the catalog file holds a catalog struct + % + % Json is compared after decoding, so that formatting alone does + % not count as a difference. + filePath = nansen.util.path.changeFilenameExtension(obj.FilePath, obj.SaveFormat); + + if ~isfile(filePath) + tf = false; + elseif strcmp(obj.SaveFormat, 'json') + tf = isequaln(jsondecode(fileread(filePath)), jsondecode(obj.encodeAsJson(S))); + else + tf = isequaln(load(filePath, 'Data', 'Preferences'), S); + end + end + function writeCatalogFile(obj, S, filePath) %writeCatalogFile Write a catalog struct in the format its extension implies if strcmp(obj.getFormatFromPath(filePath), 'json') - % Encode the items, and every struct array nested in them, - % as json arrays even when they hold one element or none, - % so that a reader in another language does not have to - % guess whether a value is a list. - S.Data = utility.data.StorableCatalog.encodeStructArraysAsLists(S.Data); - utility.filewrite(filePath, jsonencode(S, 'PrettyPrint', true)) + utility.filewrite(filePath, obj.encodeAsJson(S)) else save(filePath, '-struct', 'S') end @@ -325,6 +349,17 @@ function writeCatalogFile(obj, S, filePath) methods (Static, Access = protected) + function text = encodeAsJson(S) + %encodeAsJson Encode a catalog struct as the text of a json catalog file + % + % The items, and every struct array nested in them, are written + % as json arrays even when they hold one element or none, so that + % a reader in another language does not have to guess whether a + % value is a list. + S.Data = utility.data.StorableCatalog.encodeStructArraysAsLists(S.Data); + text = jsonencode(S, 'PrettyPrint', true); + end + function format = getFormatFromPath(filePath) %getFormatFromPath Save format implied by a catalog file extension [~, ~, extension] = fileparts(filePath); diff --git a/tests/+nansen/+unittest/+config/DataLocationModelPersistenceTest.m b/tests/+nansen/+unittest/+config/DataLocationModelPersistenceTest.m new file mode 100644 index 00000000..289b6811 --- /dev/null +++ b/tests/+nansen/+unittest/+config/DataLocationModelPersistenceTest.m @@ -0,0 +1,112 @@ +classdef DataLocationModelPersistenceTest < matlab.unittest.TestCase + %DataLocationModelPersistenceTest What loading a data location model writes + % + % Loading applies migrations and refreshes derived values. The file + % is written when that changes its content and left alone otherwise. + % + % Run tests: + % runtests('nansen.unittest.config.DataLocationModelPersistenceTest') + + properties + FolderPath char + end + + methods (TestClassSetup) + function setupProject(testCase) + % The model constructor resolves the current project. + testCase.applyFixture(nansen.fixture.ProjectFixture) + end + end + + methods (TestMethodSetup) + function createFolder(testCase) + import matlab.unittest.fixtures.TemporaryFolderFixture + fixture = testCase.applyFixture(TemporaryFolderFixture); + testCase.FolderPath = fixture.Folder; + end + end + + methods (Access = private) + + function filePath = createSettledModel(testCase, extension) + %createSettledModel Write a model file that a load has nothing to add to + % + % The data location has no root paths, so its empty list carries + % none of the fields that a root path migration looks for. + filePath = fullfile(testCase.FolderPath, "datalocation_settings." + extension); + + model = nansen.config.dloc.DataLocationModel(char(filePath)); + item = model.getBlankItem(); + item.Name = 'Processed'; + item.Type = nansen.config.dloc.DataLocationType('processed'); + model.insertItem(item) + + nansen.config.dloc.DataLocationModel(char(filePath)); + end + + function modifyJsonFile(~, filePath, modifyFcn) + %modifyJsonFile Apply a function to the decoded content of a json file + S = jsondecode(fileread(filePath)); + S = modifyFcn(S); + utility.filewrite(filePath, jsonencode(S, 'PrettyPrint', true)) + end + end + + methods (Test) + + function testLoadingUnchangedJsonLeavesTheFileAlone(testCase) + % Whitespace does not change the content, so it survives only + % if the file is not written. + filePath = testCase.createSettledModel("json"); + paddedText = [fileread(filePath), newline, newline]; + utility.filewrite(filePath, paddedText) + + nansen.config.dloc.DataLocationModel(char(filePath)); + + testCase.verifyEqual(string(fileread(filePath)), string(paddedText), ... + 'Loading a model that has nothing to change must not write its file.') + end + + function testLoadingUnchangedMatLeavesTheFileAlone(testCase) + % Saving replaces the file with the catalog variables, so a + % variable the catalog does not know survives only if the file + % is not written. + filePath = testCase.createSettledModel("mat"); + Marker = true; + save(filePath, 'Marker', '-append') + + nansen.config.dloc.DataLocationModel(char(filePath)); + + testCase.verifyTrue(any(strcmp(who('-file', filePath), 'Marker')), ... + 'Loading a model that has nothing to change must not write its file.') + end + + function testGeneratedUuidsReachTheFile(testCase) + % A uuid generated on load has to be stored. A data location is + % referred to by its uuid, so it must be the same next time. + filePath = testCase.createSettledModel("json"); + testCase.modifyJsonFile(filePath, @(S) setfield(S, 'Data', rmfield(S.Data, 'Uuid'))) + + firstLoad = nansen.config.dloc.DataLocationModel(char(filePath)); + secondLoad = nansen.config.dloc.DataLocationModel(char(filePath)); + + testCase.verifyNotEmpty(firstLoad.Data(1).Uuid) + testCase.verifyEqual(secondLoad.Data(1).Uuid, firstLoad.Data(1).Uuid) + end + + function testRefreshedFunctionNamesReachTheFile(testCase) + filePath = testCase.createSettledModel("json"); + + function S = renameFirstFunction(S) + S.Data.MetaDataDef(1).FunctionName = 'otherProject.datalocation.getSubjectId'; + end + testCase.modifyJsonFile(filePath, @renameFirstFunction) + + nansen.config.dloc.DataLocationModel(char(filePath)); + + stored = jsondecode(fileread(filePath)); + expected = sprintf('%s.datalocation.getSubjectId', nansen.getCurrentProject().Name); + testCase.verifyEqual(stored.Data.MetaDataDef(1).FunctionName, expected) + end + end +end From 4e84326c7aaf3c3d1bd26ddc1464c4f6b95d212a Mon Sep 17 00:00:00 2001 From: ehennestad Date: Sun, 8 Nov 2026 20:07:42 +0100 Subject: [PATCH 2/2] refactor(dloc): remove the unusable IsDirty property of DataLocationModel IsDirty was declared Dependent without a get method, so reading it raises MATLAB:class:noGetMethod. Nothing reads it. DataBackup, the private property it was meant to compare against, is never assigned. Co-Authored-By: Claude Opus 5.5 --- .../+config/+dloc/@DataLocationModel/DataLocationModel.m | 2 -- 1 file changed, 2 deletions(-) diff --git a/code/+nansen/+config/+dloc/@DataLocationModel/DataLocationModel.m b/code/+nansen/+config/+dloc/@DataLocationModel/DataLocationModel.m index b1b0ff8d..48cafac8 100644 --- a/code/+nansen/+config/+dloc/@DataLocationModel/DataLocationModel.m +++ b/code/+nansen/+config/+dloc/@DataLocationModel/DataLocationModel.m @@ -15,12 +15,10 @@ end properties (Dependent) - IsDirty % Todo: Dependent on whether data backup is different than data DefaultDataLocation end properties (Access = private) - DataBackup % Todo: assign this on construction and when model is marked as clean(?) LocalRootPathManager nansen.config.dloc.LocalRootPathManager end