Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 7 additions & 27 deletions code/+nansen/+config/+dloc/@DataLocationModel/DataLocationModel.m
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -92,15 +90,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
Expand All @@ -110,7 +111,6 @@ function tempDevFix(obj)

if any(strcmp(rootPath, ''))
rootPath(strcmp(rootPath, '')) = [];
dirty = true;
end

obj.Data(i).RootPath = rootPath;
Expand All @@ -119,7 +119,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
Expand All @@ -130,27 +129,23 @@ 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

% Add a fourth variable (DiskType) to root path cell array.
if ~isempty(obj.Data)
if ~isfield( obj.Data(1).RootPath, 'DiskType' )
obj.addDiskTypeToAllRootPaths()
dirty = true;
end
end

Expand All @@ -159,31 +154,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

Expand Down Expand Up @@ -973,7 +959,6 @@ function updateMetadataExtractorFunctionNames(obj)
obj.Data(i).MetaDataDef(j).FunctionName = functionName;
end
end
obj.save()
end

function initializeLocalRootPathManager(obj)
Expand Down Expand Up @@ -1028,24 +1013,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
Expand Down
47 changes: 41 additions & 6 deletions code/general/+utility/+data/StorableCatalog.m
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand Down
112 changes: 112 additions & 0 deletions tests/+nansen/+unittest/+config/DataLocationModelPersistenceTest.m
Original file line number Diff line number Diff line change
@@ -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
Loading