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
3 changes: 2 additions & 1 deletion code/+nansen/+internal/+setup/Contents.m
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
% userpath, missing jars on the Java class path, a too-old Widgets Toolbox.
%
% Functions
% resolveEmptyUserpath - Set userpath if it is empty (Linux)
% resolveEmptyUserpath - Ask for a folder and make it MATLAB's userpath
% setUserpathFromFolder - Set MATLAB's userpath from a folder given by the user
% addYamlJarToJavaClassPath - Add the YAML-Matlab jar to the Java class path
% addUiwidgetsJarToJavaClassPath - Add the Widgets Toolbox jar to the Java class path
% isUiwidgetsOnJavapath - True if the Widgets Toolbox jar is on the Java class path
Expand Down
66 changes: 36 additions & 30 deletions code/+nansen/+internal/+setup/resolveEmptyUserpath.m
Original file line number Diff line number Diff line change
@@ -1,37 +1,43 @@
function resolveEmptyUserpath()
function resolveEmptyUserpath(options)
%resolveEmptyUserpath - Ask for a folder and make it MATLAB's userpath
% resolveEmptyUserpath() asks in the Command Window for a folder for
% user data and passes the answer to
% nansen.internal.setup.setUserpathFromFolder.
%
% MATLAB can not read input in batch mode, so there this function throws
% the error NANSEN:Setup:EmptyUserpathInBatchMode, which says what to run.
%
% resolveEmptyUserpath(IsBatchMode=TF) uses TF instead of asking MATLAB
% whether it runs in batch mode.
%
% See also nansen.internal.setup.setUserpathFromFolder

prompt = [ 'Please enter the path name of a directory which NANSEN ', ...
'can use for saving userdata \nand dependencies like addons and ', ...
'toolboxes. Note: MATLAB/Nansen will be appended to \nthe path ', ...
'you enter.\nEnter path name: '];
arguments
options.IsBatchMode (1,1) logical = batchStartupOptionUsed()
end

answer = input(prompt, 's');
if isempty(answer)
error('NANSEN:SetUserpathAborted', 'Please enter a directory for userdata')
if options.IsBatchMode
error('NANSEN:Setup:EmptyUserpathInBatchMode', ...
['MATLAB''s userpath is empty and MATLAB can not ask for a folder in batch mode. ', ...
'Run userpath("<full path of an existing folder>"), then run nansen_install again.'])
end

enteredPath = answer;
userPathDirectory = fullfile(enteredPath, 'MATLAB');
directoryPath = fullfile(userPathDirectory, 'Nansen');
prompt = [ 'MATLAB''s userpath is empty. Please enter the full path of a ', ...
'directory which NANSEN \ncan use for saving userdata and ', ...
'dependencies like addons and toolboxes. \nNote: MATLAB/Nansen will ', ...
'be appended to the path you enter, and the MATLAB \nsubfolder ', ...
'becomes MATLAB''s userpath, also in later sessions.\nEnter path name: '];

if ~isfolder(directoryPath)
% Ask user if they want to create the directory
prompt = sprintf([ '\nThe directory "%s" does not exist.\n', ...
'Do you want to create it?\n', ...
'Enter "y" for yes or "n" for no: '], directoryPath);
answer = input(prompt, 's');
if isempty(answer)
error('NANSEN:SetUserpathAborted', 'Please enter "y" or "n"')
end
if strcmpi(answer, 'y')
mkdir(directoryPath)
else
error('NANSEN:SetUserpathAborted', 'A directory for userdata is required')
end
end
answer = input(prompt, 's');
nansen.internal.setup.setUserpathFromFolder(answer, @askToCreateFolder)
end

function isConfirmed = askToCreateFolder(folder)
%askToCreateFolder - Ask the user whether a missing folder may be created

% Add the directory to the userpath
%userpath(userPathDirectory)
fprintf('Updated MATLAB''s userpath to: "%s"\n', userPathDirectory)
fprintf(newline)
% The folder is printed separately because input interprets a
% backslash in its prompt as an escape sequence
fprintf('\nThe directory "%s" does not exist.\n', folder)
answer = input('Do you want to create it?\nEnter "y" for yes or "n" for no: ', 's');
isConfirmed = strcmpi(strip(answer), 'y');
end
64 changes: 64 additions & 0 deletions code/+nansen/+internal/+setup/setUserpathFromFolder.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
function setUserpathFromFolder(enteredFolder, confirmCreateFolder)
%setUserpathFromFolder - Set MATLAB's userpath from a folder given by the user
% setUserpathFromFolder(enteredFolder, confirmCreateFolder) sets MATLAB's
% userpath to <enteredFolder>/MATLAB and creates the folder
% <enteredFolder>/MATLAB/Nansen if it does not exist. enteredFolder must
% be an absolute path. MATLAB adds the new userpath to the search path
% and keeps it as a saved setting for later sessions.
%
% confirmCreateFolder is a function handle that takes the path of the
% missing folder and returns true if the folder may be created. It is
% not called when the folder exists.
%
% Call this function only when userpath is empty: it detects a userpath
% that MATLAB did not accept by reading back an empty value.
%
% See also nansen.internal.setup.resolveEmptyUserpath, userpath

arguments
enteredFolder (1,1) string
confirmCreateFolder (1,1) function_handle
end

enteredFolder = strip(enteredFolder);
if strlength(enteredFolder) == 0
error('NANSEN:SetUserpathAborted', 'Please enter a directory for userdata.')
end
if ~isAbsolutePath(enteredFolder)
error('NANSEN:Setup:UserpathFolderNotAbsolute', ...
'"%s" is not an absolute path. Enter the full path of a folder.', enteredFolder)
end

userpathFolder = fullfile(enteredFolder, "MATLAB");
nansenFolder = fullfile(userpathFolder, "Nansen");

if ~isfolder(nansenFolder)
if ~confirmCreateFolder(nansenFolder)
error('NANSEN:SetUserpathAborted', 'A directory for userdata is required.')
end
mkdir(nansenFolder)
end

userpath(userpathFolder)

% MATLAB leaves the userpath unchanged, with only a warning, if it can
% not add the folder to the search path
newUserpath = userpath();
if isempty(newUserpath)
error('NANSEN:Setup:UserpathNotSet', ...
['MATLAB did not accept "%s" as userpath. Check that the folder ', ...
'can be added to the search path, then run nansen_install again.'], userpathFolder)
end

fprintf('Set MATLAB''s userpath to: "%s"\n\n', newUserpath)
end

function isAbsolute = isAbsolutePath(folder)
%isAbsolutePath - True for a full path, on the current platform
if ispc
driveRoot = lettersPattern(1) + ":" + characterListPattern("\/");
isAbsolute = startsWith(folder, driveRoot) || startsWith(folder, ["\\", "//"]);
else
isAbsolute = startsWith(folder, "/");
end
end
6 changes: 4 additions & 2 deletions nansen_install.m
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,10 @@ function nansen_install(dependencyIds, options)
%
% nansen_install(...,AddonFolder=FOLDER) installs the toolboxes in
% FOLDER instead of the default add-on folder of NANSEN. When the
% default folder is used and userpath is empty, nansen_install sets
% userpath first.
% default folder is used and userpath is empty, nansen_install asks for
% a folder and sets userpath to its MATLAB subfolder, which MATLAB keeps
% for later sessions. In batch mode, where MATLAB can not ask,
% nansen_install throws an error that says what to run.
%
% Example: Install a toolbox that an error message says is missing
% nansen_install("flowreg")
Expand Down
143 changes: 143 additions & 0 deletions tests/+nansen/+unittest/+setup/EmptyUserpathTest.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
classdef EmptyUserpathTest < matlab.unittest.TestCase
%EmptyUserpathTest Handling of an empty userpath by nansen_install
%
% Calling the real userpath with an argument changes a setting that MATLAB
% saves between sessions, so a stub replaces it. The stub keeps userpath's
% documented behaviour: the folder must exist when it is set, and an
% empty userpath is returned as empty char.
%
% Run tests:
% runtests('nansen.unittest.setup.EmptyUserpathTest')

properties (Constant, Access = private)
UserpathKey = 'EmptyUserpathTestValue'
IgnoreSetKey = 'EmptyUserpathTestIgnoreSet'
end

properties (Access = private)
Folder (1,1) string = missing
end

methods (TestClassSetup)
function stubMatlabFunctions(testCase)
%stubMatlabFunctions Shadow userpath
import matlab.unittest.fixtures.PathFixture
import matlab.unittest.fixtures.TemporaryFolderFixture

stubFolder = string(testCase.applyFixture(TemporaryFolderFixture).Folder);
writelines([ ...
"function value = userpath(newValue)"; ...
" if nargin == 0"; ...
" value = getappdata(groot, '" + testCase.UserpathKey + "');"; ...
" return"; ...
" end"; ...
" assert(isfolder(newValue), 'MATLAB:userpath:invalidInput', 'Folder must exist.')"; ...
" if ~getappdata(groot, '" + testCase.IgnoreSetKey + "')"; ...
" setappdata(groot, '" + testCase.UserpathKey + "', char(newValue))"; ...
" end"; ...
"end"], fullfile(stubFolder, "userpath.m"))
testCase.applyFixture(PathFixture(stubFolder))

testCase.addTeardown(@rmappdata, groot, testCase.UserpathKey)
testCase.addTeardown(@rmappdata, groot, testCase.IgnoreSetKey)
end
end

methods (TestMethodSetup)
function resetState(testCase)
setappdata(groot, testCase.UserpathKey, '')
setappdata(groot, testCase.IgnoreSetKey, false)

testCase.assertFalse(startsWith(which("userpath"), matlabroot), ...
"The tests must not reach MATLAB's userpath function.")

testCase.Folder = string( ...
testCase.applyFixture(matlab.unittest.fixtures.TemporaryFolderFixture).Folder);
end
end

methods (Test)
function setsUserpathAndCreatesFolders(testCase)
output = testCase.applyFolder(testCase.Folder, @(~) true);

expectedUserpath = fullfile(testCase.Folder, "MATLAB");
testCase.verifyEqual(string(userpath()), expectedUserpath)
testCase.verifyTrue(isfolder(fullfile(expectedUserpath, "Nansen")))
testCase.verifySubstring(output, char(expectedUserpath))
end

function defaultAddonFolderIsUsableAfterwards(testCase)
testCase.applyFolder(testCase.Folder, @(~) true);

testCase.verifyEqual(string(nansen.config.addons.getDefaultAddonFolder()), ...
fullfile(testCase.Folder, "MATLAB", "Nansen", "Add-Ons"))
end

function existingFolderIsNotConfirmed(testCase)
mkdir(fullfile(testCase.Folder, "MATLAB", "Nansen"))

testCase.applyFolder(testCase.Folder, @failIfCalled);

testCase.verifyEqual(string(userpath()), fullfile(testCase.Folder, "MATLAB"))
end

function surroundingSpaceIsIgnored(testCase)
testCase.applyFolder(" " + testCase.Folder + " ", @(~) true);

testCase.verifyEqual(string(userpath()), fullfile(testCase.Folder, "MATLAB"))
end

function decliningLeavesUserpathEmpty(testCase)
testCase.verifyError(@() testCase.applyFolder(testCase.Folder, @(~) false), ...
'NANSEN:SetUserpathAborted')

testCase.verifyEmpty(userpath())
testCase.verifyFalse(isfolder(fullfile(testCase.Folder, "MATLAB")))
end

function emptyAnswerAborts(testCase)
testCase.verifyError(@() testCase.applyFolder(" ", @failIfCalled), ...
'NANSEN:SetUserpathAborted')

testCase.verifyEmpty(userpath())
end

function relativeFolderIsRejectedBeforeCreatingAnything(testCase)
testCase.applyFixture(matlab.unittest.fixtures.CurrentFolderFixture(testCase.Folder))

testCase.verifyError(@() testCase.applyFolder("relative/folder", @failIfCalled), ...
'NANSEN:Setup:UserpathFolderNotAbsolute')

testCase.verifyEmpty(userpath())
testCase.verifyFalse(isfolder(fullfile(testCase.Folder, "relative")))
end

function reportsUserpathThatDidNotTakeEffect(testCase)
setappdata(groot, testCase.IgnoreSetKey, true)

testCase.verifyError(@() testCase.applyFolder(testCase.Folder, @(~) true), ...
'NANSEN:Setup:UserpathNotSet')
end

function batchModeStopsWithInstruction(testCase)
try
nansen.internal.setup.resolveEmptyUserpath(IsBatchMode=true)
testCase.verifyFail("Expected an error in batch mode.")
catch exception
testCase.verifyEqual(exception.identifier, 'NANSEN:Setup:EmptyUserpathInBatchMode')
testCase.verifySubstring(exception.message, 'userpath("')
end
end
end

methods (Access = private)
function output = applyFolder(~, folder, confirmCreateFolder) %#ok<INUSD>
%applyFolder Set the userpath and return the printed message
output = evalc("nansen.internal.setup.setUserpathFromFolder(folder, confirmCreateFolder)");
end
end
end

function isConfirmed = failIfCalled(folder) %#ok<STOUT>
error('EmptyUserpathTest:UnexpectedConfirmation', 'Did not expect to confirm "%s".', folder)
end
Loading