Skip to content
Draft
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
61 changes: 61 additions & 0 deletions +matnwb/+internal/+typecache/generateNamespaces.m
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ function generateNamespaces(namespaceInfoList, saveDir)

% Cache keys of the namespaces handled so far, used for their dependents.
cacheKeys = containers.Map();
replacedLoadedVersions = strings(1, 0);

for iNamespace = 1:numel(namespaceInfoList)
namespaceInfo = namespaceInfoList(iNamespace);
Expand All @@ -56,6 +57,9 @@ function generateNamespaces(namespaceInfoList, saveDir)
cacheKey = composeCacheKey(specHash, generatorHash, dependencyKeys);
cacheKeys(name) = cacheKey;

replacedLoadedVersions(end+1) = describeLoadedVersionReplacement( ...
name, namespaceInfo.version, saveDir); %#ok<AGROW>

versionFolder = fullfile(cacheFolder, "resources", name, namespaceInfo.version);
entryFolder = fullfile(versionFolder, extractBefore(cacheKey, entryKeyLength + 1));
if readCacheKey(entryFolder) == cacheKey
Expand All @@ -77,6 +81,17 @@ function generateNamespaces(namespaceInfoList, saveDir)
end
matnwb.internal.typecache.writeFunctionSignatures(saveDir)
rehash()

replacedLoadedVersions(replacedLoadedVersions == "") = [];
if ~isempty(replacedLoadedVersions)
% MATLAB redefines the loaded classes without a warning of its own.
warning("NWB:TypeCache:LoadedClassesReplaced", ...
"Classes that were loaded in this MATLAB session were replaced with another version:\n%s\n" + ...
"Objects created before this point now use the classes of the new version, and lose the " + ...
"values of properties that version does not define. Save or export the objects you need " + ...
"before switching to another schema version.", ...
strjoin(" " + replacedLoadedVersions, newline))
end
end

function namespaceInfoList = sortByDependency(namespaceInfoList)
Expand Down Expand Up @@ -151,6 +166,52 @@ function generateNamespaces(namespaceInfoList, saveDir)
cacheKey = matnwb.internal.typecache.computeSha256(strjoin(lines, newline));
end

function description = describeLoadedVersionReplacement(name, newVersion, saveDir)
% describeLoadedVersionReplacement - Describe a version switch of classes that are in use.
%
% Returns "<name> <previous version> -> <new version>" when MATLAB has
% loaded classes of the namespace from saveDir and saveDir holds another
% version than newVersion, and "" otherwise. Replacing the classes then
% changes objects created earlier: they take the class definitions of the
% new version, and lose the values of properties it does not define.

description = "";
previousVersion = readGeneratedVersion(name, saveDir);
if previousVersion == "" || previousVersion == newVersion
return
end

[~, ~, loadedClassNames] = inmem();
classPrefix = "types." + misc.str2validName(char(name)) + ".";
loadedClassNames = string(loadedClassNames(startsWith(loadedClassNames, classPrefix)));
if isempty(loadedClassNames)
return
end

% Classes of the same name may be loaded from another folder on the path.
loadedClassFolder = fileparts(which(loadedClassNames(1)));
if ~strcmp(getCanonicalPath(loadedClassFolder), getCanonicalPath(getTypesFolder(saveDir, name)))
return
end

description = sprintf("%s %s -> %s", name, previousVersion, newVersion);
end

function version = readGeneratedVersion(name, saveDir)
% readGeneratedVersion - Read the version of a namespace in saveDir, or "" if there is none.
cachePath = fullfile(saveDir, "namespaces", name + ".mat");
if isfile(cachePath)
cache = load(cachePath, "version");
version = string(cache.version);
else
version = "";
end
end

function canonicalPath = getCanonicalPath(folderPath)
canonicalPath = string(java.io.File(folderPath).getCanonicalPath());
end

function cacheKey = readCacheKey(entryFolder)
% readCacheKey - Read the cache key of a cache entry, or "" if there is none.
%
Expand Down
37 changes: 37 additions & 0 deletions +tests/+unit/TypeCacheTest.m
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,30 @@ function testClearingTypesRemovesSignatures(testCase)
testCase.verifyFalse(contains(testCase.readSignaturesFile(), "types.test_cache.CacheParent"))
end

function testSwitchingVersionWithLoadedClassesWarns(testCase)
testCase.generate(testCase.parseParentNamespace("0.1.0", "Parent doc."))
testCase.loadParentClass()

testCase.verifyWarning( ...
@() testCase.generate(testCase.parseParentNamespace("0.2.0", "Parent doc.")), ...
"NWB:TypeCache:LoadedClassesReplaced")
end

function testRegeneratingSameVersionWithLoadedClassesDoesNotWarn(testCase)
testCase.generate(testCase.parseParentNamespace("0.1.0", "Parent doc."))
testCase.loadParentClass()

testCase.verifyWarningFree( ...
@() testCase.generate(testCase.parseParentNamespace("0.1.0", "Changed parent doc.")))
end

function testSwitchingVersionWithoutLoadedClassesDoesNotWarn(testCase)
testCase.generate(testCase.parseParentNamespace("0.1.0", "Parent doc."))

testCase.verifyWarningFree( ...
@() testCase.generate(testCase.parseParentNamespace("0.2.0", "Parent doc.")))
end

function testSpecHashIsIndependentOfSourceFormat(testCase)
yamlInfo = testCase.parseParentNamespace("0.1.0", "Parent doc.");

Expand Down Expand Up @@ -363,6 +387,14 @@ function addMarkerToCacheEntry(testCase, namespaceName, version, className)
writeText(classPath, newline + testCase.Marker + newline, "a")
end

function loadParentClass(testCase)
% loadParentClass - Load the generated CacheParent class into memory.
testCase.applyFixture(matlab.unittest.fixtures.PathFixture(testCase.SaveFolder))
createParentObject()
% Remove the class definition before its folder is deleted.
testCase.addTeardown(@() clear("types.test_cache.CacheParent"))
end

function signatureText = readSignaturesFile(testCase)
signatureText = string(fileread( ...
fullfile(testCase.SaveFolder, "resources", "functionSignatures.json")));
Expand All @@ -386,3 +418,8 @@ function writeText(filePath, text, permission)
fileCleanup = onCleanup(@() fclose(fileId));
fwrite(fileId, char(text), "char");
end

function createParentObject()
% createParentObject - Create an object so MATLAB loads its class, then discard it.
types.test_cache.CacheParent();
end
Loading