function [filelist] = collectProjectFiles(projectDir, ignorePatterns)
%COLLECTPROJECTFILES create a filelist of a project ready for packaging
%
%Usage: filelist = collectProjectFiles(projectDir, ignorePatterns);
%
%filelist: list of files to be included in the package
%projectDir: the root directory of the project
%ignorePatterns: files and folders to ignore
%default value
filelist = [];
%do some basic checks
if exist(projectDir, 'dir') ~= 7
%folder does not exist
filelist = [];
return;
end
if nargin == 1
ignorePatterns.files = {'^\.', '~$'};
ignorePatterns.dirs = {'^\.'};
end
%collect all the files and folders in the projectDir
projectContent = dir(projectDir);
%get the relevant fields for processing
contentName = {projectContent.name};
dirFilter = [projectContent.isdir];
%remove the first 2 items ('.' and '..')
contentName(1:2) = [];
dirFilter(1:2) = [];
%remove unwanted folders
rmUnwantedDirs = cellfun(@(c) regexpi(c, ignorePatterns.dirs, 'once'), contentName, 'UniformOutput', false);
rmUnwantedDirs = cellfun(@(c) cellfun(@any, c), rmUnwantedDirs, 'UniformOutput', false);
rmUnwantedDirs = cellfun(@any, rmUnwantedDirs);
unwantedFilter = all([dirFilter; rmUnwantedDirs], 1);
%remove the undesired folders from the lists
contentName(unwantedFilter) = [];
dirFilter(unwantedFilter) = [];
%add the files in the projectDir
rootFiles = contentName(~dirFilter);
if isempty(rootFiles)
%no root files present
else
%remove unwanted files
rmUnwantedFiles = cellfun(@(c) regexpi(c, ignorePatterns.files, 'once'), rootFiles, 'UniformOutput', false);
rmUnwantedFiles = cellfun(@(c) cellfun(@any, c), rmUnwantedFiles, 'UniformOutput', false);
rmUnwantedFiles = cellfun(@any, rmUnwantedFiles);
rootFiles(rmUnwantedFiles) = [];
%create full path names
filelist = cellfun(@(c) fullfile(projectDir, c), rootFiles, 'UniformOutput', false);
end
if sum(dirFilter) > 0
%there are subfolders for packaging, get their names
subdirs = contentName(dirFilter);
%check the subfolders in a recursive manner
numSubDirs = numel(subdirs);
for sd = 1:numSubDirs
subdir = subdirs{sd};
subFilelist = collectProjectFiles(fullfile(projectDir,subdir), ignorePatterns);
if isempty(filelist)
filelist = subFilelist;
else
filelist = [filelist, subFilelist];
end
end
end
end