diff --git a/code/+nansen/+config/+project/@ProjectManager/ProjectManager.m b/code/+nansen/+config/+project/@ProjectManager/ProjectManager.m index cd59a6c1..31855043 100644 --- a/code/+nansen/+config/+project/@ProjectManager/ProjectManager.m +++ b/code/+nansen/+config/+project/@ProjectManager/ProjectManager.m @@ -704,7 +704,7 @@ function saveCatalog(obj) save(obj.CatalogPath, 'projectCatalog') elseif obj.CatalogSaveFormat == "json" jsonStr = jsonencode(projectCatalog, 'PrettyPrint', true); - jsonPath = replace(obj.CatalogPath, '.mat', '.json'); + jsonPath = nansen.util.path.changeFilenameExtension(obj.CatalogPath, '.json'); fid = fopen(jsonPath, 'w'); fwrite(fid, jsonStr); fclose(fid); diff --git a/code/+nansen/+dataio/FileAdapter.m b/code/+nansen/+dataio/FileAdapter.m index d0ed22ce..1f8cc2fb 100644 --- a/code/+nansen/+dataio/FileAdapter.m +++ b/code/+nansen/+dataio/FileAdapter.m @@ -536,7 +536,7 @@ function initializeMetadata(obj) if isTemporary filepathMat = [tempname, '.mat']; else - filepathMat = strrep(filepathNpy, '.npy', '.mat'); + filepathMat = nansen.util.path.changeFilenameExtension(filepathNpy, '.mat'); end if ispc diff --git a/code/+nansen/+processing/@MotionCorrection/MotionCorrection.m b/code/+nansen/+processing/@MotionCorrection/MotionCorrection.m index 4ab7e687..fe6290a6 100644 --- a/code/+nansen/+processing/@MotionCorrection/MotionCorrection.m +++ b/code/+nansen/+processing/@MotionCorrection/MotionCorrection.m @@ -441,7 +441,10 @@ function openTargetStack(obj, stackSize, dataType, ~) if ~isfolder(folderPath); mkdir(folderPath); end % Force file to be saved as .tif if extension was set to .mat - filePath = strrep(filePath, '.mat', '.tif'); + [~, ~, extension] = fileparts(filePath); + if strcmp(extension, '.mat') + filePath = nansen.util.path.changeFilenameExtension(filePath, '.tif'); + end % Call method of ImageStackProcessor openTargetStack@nansen.stack.ImageStackProcessor(obj, filePath, ... @@ -811,7 +814,7 @@ function resaveRGBProjectionImages(obj, projectionType) rgbArray = imArray; rgbArray(:, :, 3, :) = 0; - newFilepath = strrep(filepath, '.tif', '_rgb.tif'); + newFilepath = nansen.util.path.appendToFilename(filepath, '_rgb'); nansen.stack.utility.mat2tiffstack( rgbArray, newFilepath, true ) % true to save as rgb. end diff --git a/code/+nansen/+util/+path/appendToFilename.m b/code/+nansen/+util/+path/appendToFilename.m new file mode 100644 index 00000000..cc373e39 --- /dev/null +++ b/code/+nansen/+util/+path/appendToFilename.m @@ -0,0 +1,23 @@ +function newFilename = appendToFilename(filename, suffix) +%appendToFilename Add text to the end of a file name, before its extension +% +% newFilename = appendToFilename(filename, suffix) returns filename with +% suffix inserted between the file name and its extension. +% +% Only the name of the file is changed. Folder names are left untouched, +% including when they contain the extension of the file. +% +% Example: +% nansen.util.path.appendToFilename('/data/my.mat.bak/x.mat', '_clean') +% % Returns '/data/my.mat.bak/x_clean.mat' +% +% See also nansen.util.path.changeFilenameExtension, fileparts, fullfile + + arguments + filename (1,:) char {mustBeNonempty} + suffix (1,:) char {mustBeNonempty} + end + + [folderPath, fileName, extension] = fileparts(filename); + newFilename = fullfile(folderPath, [fileName, suffix, extension]); +end diff --git a/code/apps/+mclassifier/manualClassifier.m b/code/apps/+mclassifier/manualClassifier.m index 166c0273..3062ebee 100644 --- a/code/apps/+mclassifier/manualClassifier.m +++ b/code/apps/+mclassifier/manualClassifier.m @@ -1408,7 +1408,7 @@ function saveClassification(obj, ~, ~, varargin) S.(varNames{i}) = S.(varNames{i})(keep); end - savePath = strrep(savePath, '.mat', '_clean.mat'); + savePath = appendToFilename(savePath, '_clean'); save(savePath, '-struct', 'S') fprintf('Saved classification results to %s\n', savePath) @@ -1433,7 +1433,7 @@ function saveClassification(obj, ~, ~, varargin) case 'append _classified' pickFile = false; - savePath = strrep(obj.dataFilePath, '.mat', '_classified.mat'); + savePath = appendToFilename(obj.dataFilePath, '_classified'); otherwise return @@ -1677,6 +1677,21 @@ function removeFocusFromControl(h) end end +function newFilename = appendToFilename(filename, suffix) +%appendToFilename Add text to the end of a file name, before its extension +% +% This package does not depend on the nansen namespace, so it keeps its +% own copy of nansen.util.path.appendToFilename. + + arguments + filename (1,:) char {mustBeNonempty} + suffix (1,:) char {mustBeNonempty} + end + + [folderPath, fileName, extension] = fileparts(filename); + newFilename = fullfile(folderPath, [fileName, suffix, extension]); +end + function str = pval2str(pval, numSignificantValues) %pval2str Format a pvalue as a string diff --git a/code/apps/+nansen/@TaskProcessor/TaskProcessor.m b/code/apps/+nansen/@TaskProcessor/TaskProcessor.m index df808508..93fb794f 100644 --- a/code/apps/+nansen/@TaskProcessor/TaskProcessor.m +++ b/code/apps/+nansen/@TaskProcessor/TaskProcessor.m @@ -376,7 +376,7 @@ function loadTaskLists(obj, filePath) catch ME % Back up file dateStr = char(datetime('now'), 'yyyyMMdd_HH_mm_ss'); - filePathBackup = strrep(filePath, '.mat', sprintf('corrupted_%s.mat', dateStr)); + filePathBackup = nansen.util.path.appendToFilename(filePath, sprintf('corrupted_%s', dateStr)); movefile(filePath, filePathBackup); warning('Could not load the task list. This might be due to the file being corrupt. The file is backed up, and the task list is reset. If you see this warning several times, please report!') diff --git a/code/apps/+roiclassifier/@App/App.m b/code/apps/+roiclassifier/@App/App.m index 2e8c4307..f0836f19 100644 --- a/code/apps/+roiclassifier/@App/App.m +++ b/code/apps/+roiclassifier/@App/App.m @@ -955,7 +955,7 @@ function saveClassification(obj, ~, ~, varargin) roiGroupStruct(i).roiClassification = tempRoiGroup(i).roiClassification(keep); end - savePath = strrep(savePath, '.mat', '_clean.mat'); + savePath = nansen.util.path.appendToFilename(savePath, '_clean'); % Save roigroup using roigroup fileadapter fileObj = nansen.dataio.fileadapter.roi.RoiGroup(savePath, '-w'); diff --git a/code/datatypes/+nansen/+stack/+virtual/SciScanRaw.m b/code/datatypes/+nansen/+stack/+virtual/SciScanRaw.m index e65d78bd..1c9e4477 100644 --- a/code/datatypes/+nansen/+stack/+virtual/SciScanRaw.m +++ b/code/datatypes/+nansen/+stack/+virtual/SciScanRaw.m @@ -225,7 +225,7 @@ function updateDataSize(obj) function metadata = getSciScanRecordingInfo(obj) %getSciScanRecordingInfo Get recording info from the sciscan ini file - inifilepath = strrep(obj.FilePath, '.raw', '.ini'); + inifilepath = nansen.util.path.changeFilenameExtension(obj.FilePath, '.ini'); inistring = fileread(inifilepath); metadata = struct(); @@ -408,7 +408,7 @@ function getChannelColors(obj) isValid = false; return; else rawFilePath = fullfile(L.folder, L.name); - iniFilePath = strrep(rawFilePath, '.raw', '.ini'); + iniFilePath = nansen.util.path.changeFilenameExtension(rawFilePath, '.ini'); end elseif isfile(pathStr) diff --git a/code/general/+utility/+data/StorableCatalog.m b/code/general/+utility/+data/StorableCatalog.m index 848455eb..fe243bc4 100644 --- a/code/general/+utility/+data/StorableCatalog.m +++ b/code/general/+utility/+data/StorableCatalog.m @@ -729,7 +729,7 @@ function parseVarargin(obj, varargin) function saveToFolder(obj, S) %saveToFolder Save catalog to a folder with one file per item % Make folder if it does not exist. - folderPath = strrep(obj.FilePath, '.mat', ''); + folderPath = obj.getItemFolderPath(); if ~isfolder(folderPath); mkdir(folderPath); end % Create and save a master list @@ -759,7 +759,7 @@ function saveToFolder(obj, S) % Note: will be slower than loading from single file, but is more % modular, in that its easier to add and remove items. - folderPath = strrep(obj.FilePath, '.mat', ''); + folderPath = obj.getItemFolderPath(); L = dir(fullfile(folderPath, '*.mat')); @@ -780,6 +780,14 @@ function saveToFolder(obj, S) S.Data = cat(2, itemArray{:}); end + + function folderPath = getItemFolderPath(obj) + %getItemFolderPath Folder of a one-file-per-item catalog + % + % The folder is named after the catalog file and sits beside it. + [parentFolder, catalogName] = fileparts(obj.FilePath); + folderPath = fullfile(parentFolder, catalogName); + end end methods (Static) diff --git a/code/tools/+roimanager/resources/icons/saveIcon.m b/code/tools/+roimanager/resources/icons/saveIcon.m index 8a49b20f..58997ff9 100644 --- a/code/tools/+roimanager/resources/icons/saveIcon.m +++ b/code/tools/+roimanager/resources/icons/saveIcon.m @@ -33,7 +33,7 @@ function saveIcon(iconName) hV.Height = hV.Height/hV.Height; S.imageVector = hV.getVectorStruct; - savePath = strrep(loadPath, '.png', '.mat'); + savePath = nansen.util.path.changeFilenameExtension(loadPath, '.mat'); save(savePath, '-struct', 'S') end diff --git a/tests/+nansen/+unittest/+util/PathUtilTest.m b/tests/+nansen/+unittest/+util/PathUtilTest.m index 6cb30f68..1e2fcc55 100644 --- a/tests/+nansen/+unittest/+util/PathUtilTest.m +++ b/tests/+nansen/+unittest/+util/PathUtilTest.m @@ -1,14 +1,67 @@ classdef PathUtilTest < matlab.unittest.TestCase %PathUtilTest Unit tests for nansen.util.path utilities. % - % Covers changeFilenameExtension, which must replace only the - % extension of the file name and never alter folder names. + % Covers changeFilenameExtension and appendToFilename, which must + % change only the name of the file and never alter folder names. % % Run tests: % runtests('nansen.unittest.util.PathUtilTest') methods (Test) + % ---------------------------------------------------------------- + % appendToFilename + % ---------------------------------------------------------------- + + function testSuffixGoesBeforeTheExtension(testCase) + inputPath = fullfile('/data', 'rois.mat'); + expected = fullfile('/data', 'rois_clean.mat'); + + actual = nansen.util.path.appendToFilename(inputPath, '_clean'); + + testCase.verifyEqual(actual, expected); + end + + function testSuffixIsAddedForAnyExtension(testCase) + % A path without the expected extension must still change, so + % that a derived file can not overwrite the one it came from. + actual = nansen.util.path.appendToFilename('rois.h5', '_clean'); + + testCase.verifyEqual(actual, 'rois_clean.h5'); + end + + function testSuffixLeavesFoldersContainingTheExtensionAlone(testCase) + inputPath = fullfile('/home', '.matlab', 'archive.mat.bak', 'rois.mat'); + expected = fullfile('/home', '.matlab', 'archive.mat.bak', 'rois_clean.mat'); + + actual = nansen.util.path.appendToFilename(inputPath, '_clean'); + + testCase.verifyEqual(actual, expected); + end + + function testSuffixGoesBeforeTheFinalExtensionOnly(testCase) + actual = nansen.util.path.appendToFilename('rois.mat.mat', '_clean'); + + testCase.verifyEqual(actual, 'rois.mat_clean.mat'); + end + + function testSuffixIsAddedToANameWithoutExtension(testCase) + actual = nansen.util.path.appendToFilename('rois', '_clean'); + + testCase.verifyEqual(actual, 'rois_clean'); + end + + function testAppendAcceptsStringAndReturnsChar(testCase) + actual = nansen.util.path.appendToFilename("rois.mat", "_clean"); + + testCase.verifyEqual(actual, 'rois_clean.mat'); + end + + function testAppendRejectsEmptyInput(testCase) + testCase.verifyError(@() nansen.util.path.appendToFilename('', '_clean'), ... + 'MATLAB:validators:mustBeNonempty'); + end + % ---------------------------------------------------------------- % changeFilenameExtension - ordinary use % ----------------------------------------------------------------