diff --git a/.github/badges/tests.svg b/.github/badges/tests.svg
index ee73004..f00481a 100644
--- a/.github/badges/tests.svg
+++ b/.github/badges/tests.svg
@@ -1 +1 @@
-
+
diff --git a/README.md b/README.md
index 5541a9c..389139e 100644
--- a/README.md
+++ b/README.md
@@ -206,6 +206,12 @@ From R2026b, an `.mltbx` file is a package file with a readme and a package name
- `PackageName` must be a valid MATLAB identifier. It names the installation folder and identifies the package in `mpmlist` and to packages that depend on it. Without it, R2026b derives the name from `ToolboxName`, dropping spaces and writing a hyphen as `0x2D`.
- Releases before R2026b package the readme as an ordinary file and have no package name. MatBox checks both fields on every release.
+A readme copied from the project root is changed in the package, so that it reads correctly outside GitHub, for example on File Exchange. The project file is not changed, and neither is a readme committed in the source folder:
+
+- Lines made only of Markdown images, such as badges, are removed from the top of the file, before the first line of text.
+- Relative links and image paths become absolute URLs at the tag `v..` of the packaged version: `/blob//` for a file, `/tree//` for a folder, and the raw file URL for an image. This covers Markdown links and images, reference definitions, and the HTML attributes `href`, `src` and `srcset`. Fenced code blocks are left as they are.
+- The repository is `GITHUB_SERVER_URL/GITHUB_REPOSITORY` on GitHub Actions, and the `origin` remote elsewhere. Without either, links stay relative and MatBox warns `MatBox:Package:RepositoryUrlNotFound`.
+
The packaged toolbox is saved as `releases/_v.mltbx`, for example `MatBox_v1_2_3.mltbx`. To use the same file name for every release, add a top-level `MltbxFileName` to `MLToolboxInfo.json`. `.mltbx` is appended if it is missing, and the name must not contain folders:
```json
diff --git a/code/+matbox/+tasks/packageToolbox.m b/code/+matbox/+tasks/packageToolbox.m
index a839268..e7406ca 100644
--- a/code/+matbox/+tasks/packageToolbox.m
+++ b/code/+matbox/+tasks/packageToolbox.m
@@ -24,6 +24,11 @@
% package the readme as an ordinary file and have no package name. Both
% fields are checked on every release.
%
+% A readme copied from the project root is processed before packaging, on
+% every release: badge lines at the top are removed and relative links
+% point to the tag v.. of the new version (see
+% matbox.toolbox.internal.prepareReadme).
+%
% The MLTBX file is named _v.mltbx. To use a fixed
% file name for every release, specify a top-level "MltbxFileName" in
% MLToolboxInfo.json, e.g. "MltbxFileName": "MatBox".
@@ -52,8 +57,8 @@
% Temporarily copy project root files (e.g. LICENSE) into the source
% folder so they are included in the packaged toolbox.
- stagedFilesCleanupObj = matbox.toolbox.internal.stageRootFilesForPackaging(...
- projectRootDirectory, sourceFolderPath); %#ok
+ [stagedFilesCleanupObj, stagedFiles] = matbox.toolbox.internal.stageRootFilesForPackaging(...
+ projectRootDirectory, sourceFolderPath); %#ok
try
previousVersion = matbox.utility.getVersionFromContents(sourceFolderPath);
@@ -63,6 +68,8 @@
newVersion = matbox.utility.updateVersionNumber(previousVersion, releaseType, ...
versionString, "IncludeBuildNumber", includeBuildNumer);
+ prepareStagedReadme(projectRootDirectory, sourceFolderPath, stagedFiles, newVersion)
+
% Create/retrieve options for packaging toolbox
nvPairs = namedargs2cell(options);
toolboxOptions = matbox.toolbox.createToolboxOptions(projectRootDirectory, newVersion, nvPairs{:});
@@ -122,3 +129,22 @@
clear newVersion
end
end
+
+function prepareStagedReadme(projectRootDirectory, sourceFolderPath, stagedFiles, versionNumber)
+% prepareStagedReadme - Prepare the readme for the package if it is a staged copy
+%
+% The readme named by "Readme" in MLToolboxInfo.json is processed with
+% matbox.toolbox.internal.prepareReadmeFile only when it was copied from
+% the project root for packaging. A readme committed in the source folder
+% is left as it is.
+
+ toolboxInfo = matbox.toolbox.readToolboxInfo(projectRootDirectory);
+ if ~isfield(toolboxInfo, "Readme") || isempty(toolboxInfo.Readme)
+ return
+ end
+
+ readmeFile = fullfile(sourceFolderPath, string(toolboxInfo.Readme));
+ if ismember(readmeFile, stagedFiles)
+ matbox.toolbox.internal.prepareReadmeFile(readmeFile, projectRootDirectory, versionNumber)
+ end
+end
diff --git a/code/+matbox/+toolbox/+internal/getRepositoryUrl.m b/code/+matbox/+toolbox/+internal/getRepositoryUrl.m
new file mode 100644
index 0000000..76d2d0d
--- /dev/null
+++ b/code/+matbox/+toolbox/+internal/getRepositoryUrl.m
@@ -0,0 +1,50 @@
+function repositoryUrl = getRepositoryUrl(projectRootDirectory)
+% getRepositoryUrl - Get the web URL of a project's git repository
+%
+% repositoryUrl = matbox.toolbox.internal.getRepositoryUrl(projectRootDirectory)
+% returns the URL in the form https:////.
+%
+% On GitHub Actions the URL is GITHUB_SERVER_URL/GITHUB_REPOSITORY.
+% Elsewhere it is the URL of the "origin" remote of the repository in
+% projectRootDirectory, with credentials and a trailing ".git" removed,
+% and an SSH address (git@:/ or ssh://...) written as
+% https:////. The result is "" when there is no such
+% remote or its URL is not a web or SSH address.
+
+ arguments
+ projectRootDirectory (1,1) string {mustBeFolder}
+ end
+
+ serverUrl = string(getenv("GITHUB_SERVER_URL"));
+ repository = string(getenv("GITHUB_REPOSITORY"));
+ if serverUrl ~= "" && repository ~= ""
+ repositoryUrl = serverUrl + "/" + repository;
+ return
+ end
+
+ [status, commandOutput] = system(sprintf('git -C "%s" remote get-url origin', projectRootDirectory));
+ outputLines = splitlines(strip(string(commandOutput)));
+ if status ~= 0 || outputLines(end) == ""
+ repositoryUrl = "";
+ return
+ end
+ repositoryUrl = remoteUrlToWebUrl(outputLines(end));
+end
+
+function webUrl = remoteUrlToWebUrl(remoteUrl)
+% remoteUrlToWebUrl - Write a git remote URL as the web URL of the repository
+
+ remoteUrl = regexprep(remoteUrl, '(\.git)?/?$', '');
+
+ scpAddress = regexp(remoteUrl, '^[^@/:]+@(?[^:/]+):(?.+)$', 'names', 'once');
+ sshUrl = regexp(remoteUrl, '^ssh://(?:[^@/]+@)?(?[^/:]+)(?::\d+)?/(?.+)$', 'names', 'once');
+ if ~isempty(scpAddress)
+ webUrl = "https://" + scpAddress.host + "/" + scpAddress.path;
+ elseif ~isempty(sshUrl)
+ webUrl = "https://" + sshUrl.host + "/" + sshUrl.path;
+ elseif startsWith(remoteUrl, ["https://", "http://"])
+ webUrl = regexprep(remoteUrl, '^(https?://)[^@/]+@', '$1');
+ else
+ webUrl = "";
+ end
+end
diff --git a/code/+matbox/+toolbox/+internal/prepareReadme.m b/code/+matbox/+toolbox/+internal/prepareReadme.m
new file mode 100644
index 0000000..fd460e7
--- /dev/null
+++ b/code/+matbox/+toolbox/+internal/prepareReadme.m
@@ -0,0 +1,238 @@
+function text = prepareReadme(text, options)
+% prepareReadme - Prepare Markdown README text for display outside the repository
+%
+% text = matbox.toolbox.internal.prepareReadme(text, Name=Value) returns
+% the README text with two changes, both made outside fenced code blocks:
+%
+% - Badge lines are removed. A badge line is a line made only of Markdown
+% images, linked or not, in the leading block of the README: the lines
+% before the first line of prose. Blank lines, headings and lines of
+% HTML tags do not end the leading block. Runs of blank lines are then
+% collapsed to one, and leading blank lines are removed.
+%
+% - Relative destinations become absolute URLs in the repository at Ref.
+% This applies to inline links and images, reference definitions, and
+% the HTML attributes href, src and srcset:
+% image https://raw.githubusercontent.com////
+% for a repository on github.com, else
+% /raw//
+% folder /tree//
+% file /blob//
+% An image is the destination of a Markdown image, of src or srcset, or
+% of a reference definition that names an image file. A folder is a
+% path that ends with "/" or is a folder under ProjectRoot. A leading
+% "./" or "/" is removed, and a query or fragment is kept. Destinations
+% that are empty, have a scheme (https:, mailto:), or start with "#",
+% "//" or "../" are left unchanged.
+%
+% Name-Value Arguments:
+% RepositoryURL - Web URL of the repository, e.g.
+% "https://github.com//". Without it,
+% links are left unchanged.
+% Ref - Branch, tag or commit the links point to, e.g.
+% "v1.2.3". Without it, links are left unchanged.
+% ProjectRoot - Folder of the repository on disk, used to tell
+% folders from files.
+
+ arguments
+ text (1,1) string
+ options.RepositoryURL (1,1) string = ""
+ options.Ref (1,1) string = ""
+ options.ProjectRoot (1,1) string = ""
+ end
+
+ hasFinalNewline = endsWith(text, newline);
+ lines = splitlines(text);
+ if hasFinalNewline
+ lines(end) = [];
+ end
+
+ isCode = findCodeBlockLines(lines);
+ isBadge = findBadgeLines(lines, isCode);
+
+ if options.RepositoryURL ~= "" && options.Ref ~= ""
+ for iLine = find(~isCode & ~isBadge)'
+ lines(iLine) = makeDestinationsAbsolute(lines(iLine), options);
+ end
+ end
+
+ lines(isBadge) = [];
+ isCode(isBadge) = [];
+ lines = collapseBlankLines(lines, isCode);
+ if isempty(lines)
+ text = "";
+ return
+ end
+
+ text = join(lines, newline);
+ if hasFinalNewline
+ text = text + newline;
+ end
+end
+
+function isCode = findCodeBlockLines(lines)
+% findCodeBlockLines - Find the lines of fenced code blocks, fences included
+%
+% A fence is three or more backticks or tildes, indented by at most three
+% spaces. A block is closed by a fence of the same character that is at
+% least as long as the opening fence.
+
+ isCode = false(size(lines));
+ openingFence = "";
+ for iLine = 1:numel(lines)
+ if openingFence == ""
+ fence = regexp(lines(iLine), '^ {0,3}(?`{3,}|~{3,})', 'names', 'once');
+ if ~isempty(fence)
+ openingFence = fence.fence;
+ isCode(iLine) = true;
+ end
+ else
+ isCode(iLine) = true;
+ fenceCharacter = regexptranslate("escape", extractBefore(openingFence, 2));
+ closingPattern = "^ {0,3}" + fenceCharacter + "{" + strlength(openingFence) + ",}\s*$";
+ if ~isempty(regexp(lines(iLine), closingPattern, 'once'))
+ openingFence = "";
+ end
+ end
+ end
+end
+
+function isBadge = findBadgeLines(lines, isCode)
+% findBadgeLines - Find the image-only lines of the leading block
+
+ markdownImage = '\[!\[[^\]]*\]\([^)]*\)\]\([^)]*\)|!\[[^\]]*\]\([^)]*\)';
+ heading = '^ {0,3}#{1,6}(\s|$)';
+ htmlTags = '^\s*<.*>\s*$';
+
+ isBadge = false(size(lines));
+ for iLine = 1:numel(lines)
+ line = lines(iLine);
+ isImageOnly = strip(line) ~= "" && strip(regexprep(line, markdownImage, "")) == "";
+ isLeadingBlockLine = strip(line) == "" || isImageOnly ...
+ || ~isempty(regexp(line, heading, 'once')) ...
+ || ~isempty(regexp(line, htmlTags, 'once'));
+ if isCode(iLine) || ~isLeadingBlockLine
+ break
+ end
+ isBadge(iLine) = isImageOnly;
+ end
+end
+
+function lines = collapseBlankLines(lines, isCode)
+% collapseBlankLines - Keep at most one blank line in a row outside code blocks
+
+ isBlank = strip(lines) == "" & ~isCode;
+ isRepeatedBlank = isBlank & [true; isBlank(1:end-1)];
+ lines(isRepeatedBlank) = [];
+end
+
+function line = makeDestinationsAbsolute(line, options)
+% makeDestinationsAbsolute - Make the relative destinations of one line absolute
+
+ % Markdown images come first. The link pattern also matches the "](" of
+ % an image, and finds its destination already absolute.
+ line = replaceDestinations(line, '!\[[^\]]*\]\(\s*(<[^>]*>|[^)\s]+)', "image", options);
+ line = replaceDestinations(line, '\]\(\s*(<[^>]*>|[^)\s]+)', "link", options);
+ line = replaceDestinations(line, '^ {0,3}\[[^\]]+\]:\s*(<[^>]*>|\S+)', "reference", options);
+ line = replaceDestinations(line, '\shref\s*=\s*"([^"]*)"', "link", options);
+ line = replaceDestinations(line, "\shref\s*=\s*'([^']*)'", "link", options);
+ line = replaceDestinations(line, '\ssrc\s*=\s*"([^"]*)"', "image", options);
+ line = replaceDestinations(line, "\ssrc\s*=\s*'([^']*)'", "image", options);
+ line = replaceDestinations(line, '\ssrcset\s*=\s*"([^"]*)"', "srcset", options);
+ line = replaceDestinations(line, "\ssrcset\s*=\s*'([^']*)'", "srcset", options);
+end
+
+function line = replaceDestinations(line, pattern, kind, options)
+% replaceDestinations - Replace the destination captured by the single token of pattern
+
+ tokenExtents = regexp(line, pattern, 'tokenExtents');
+
+ % Replace from the end of the line, so the extents of earlier matches
+ % stay valid.
+ for iMatch = numel(tokenExtents):-1:1
+ extent = tokenExtents{iMatch};
+ if extent(2) < extent(1)
+ continue % Empty destination
+ end
+ destination = extractBetween(line, extent(1), extent(2));
+ if kind == "srcset"
+ newDestination = absoluteSrcset(destination, options);
+ else
+ newDestination = absoluteDestination(destination, kind, options);
+ end
+ if newDestination ~= destination
+ line = replaceBetween(line, extent(1), extent(2), newDestination);
+ end
+ end
+end
+
+function srcset = absoluteSrcset(srcset, options)
+% absoluteSrcset - Make each image candidate of a srcset value absolute
+%
+% A candidate is a URL, optionally followed by a width or density
+% descriptor, and candidates are separated by commas.
+
+ candidates = strip(split(srcset, ","));
+ for iCandidate = 1:numel(candidates)
+ parts = split(candidates(iCandidate));
+ parts(1) = absoluteDestination(parts(1), "image", options);
+ candidates(iCandidate) = join(parts, " ");
+ end
+ srcset = join(candidates, ", ");
+end
+
+function destination = absoluteDestination(destination, kind, options)
+% absoluteDestination - Make one link or image destination absolute
+
+ if startsWith(destination, "<") && endsWith(destination, ">")
+ innerDestination = extractBetween(destination, 2, strlength(destination) - 1);
+ destination = "<" + absoluteDestination(innerDestination, kind, options) + ">";
+ return
+ end
+
+ hasScheme = ~isempty(regexp(destination, '^[A-Za-z][A-Za-z0-9+.\-]*:', 'once'));
+ if destination == "" || hasScheme || startsWith(destination, ["#", "//", "../"])
+ return
+ end
+
+ % Keep a query or fragment as it is
+ suffixStart = regexp(destination, '[?#]', 'once');
+ if isempty(suffixStart)
+ repositoryPath = destination;
+ suffix = "";
+ else
+ repositoryPath = extractBefore(destination, suffixStart);
+ suffix = extractAfter(destination, suffixStart - 1);
+ end
+ repositoryPath = regexprep(repositoryPath, '^(\./)+', '');
+ repositoryPath = regexprep(repositoryPath, '^/', '');
+ if repositoryPath == ""
+ return
+ end
+
+ if kind == "reference"
+ imageExtensions = [".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp"];
+ if endsWith(lower(repositoryPath), imageExtensions)
+ kind = "image";
+ else
+ kind = "link";
+ end
+ end
+
+ repositoryUrl = options.RepositoryURL;
+ if kind == "image"
+ githubPrefix = "https://github.com/";
+ if startsWith(repositoryUrl, githubPrefix)
+ url = "https://raw.githubusercontent.com/" + extractAfter(repositoryUrl, githubPrefix) ...
+ + "/" + options.Ref + "/" + repositoryPath;
+ else
+ url = repositoryUrl + "/raw/" + options.Ref + "/" + repositoryPath;
+ end
+ elseif endsWith(repositoryPath, "/") ...
+ || (options.ProjectRoot ~= "" && isfolder(fullfile(options.ProjectRoot, repositoryPath)))
+ url = repositoryUrl + "/tree/" + options.Ref + "/" + regexprep(repositoryPath, '/+$', '');
+ else
+ url = repositoryUrl + "/blob/" + options.Ref + "/" + repositoryPath;
+ end
+ destination = url + suffix;
+end
diff --git a/code/+matbox/+toolbox/+internal/prepareReadmeFile.m b/code/+matbox/+toolbox/+internal/prepareReadmeFile.m
new file mode 100644
index 0000000..cae142b
--- /dev/null
+++ b/code/+matbox/+toolbox/+internal/prepareReadmeFile.m
@@ -0,0 +1,39 @@
+function prepareReadmeFile(readmeFile, projectRootDirectory, versionNumber)
+% prepareReadmeFile - Prepare a README file for display outside the repository
+%
+% matbox.toolbox.internal.prepareReadmeFile(readmeFile, projectRootDirectory, versionNumber)
+% rewrites readmeFile with matbox.toolbox.internal.prepareReadme. Relative
+% links point to the tag v.. of versionNumber in the
+% repository given by matbox.toolbox.internal.getRepositoryUrl. When that
+% URL is not available, badge lines are still removed, relative links are
+% left unchanged, and a warning is issued.
+%
+% The file is read and written as UTF-8.
+
+ arguments
+ readmeFile (1,1) string {mustBeFile}
+ projectRootDirectory (1,1) string {mustBeFolder}
+ versionNumber (1,1) string
+ end
+
+ versionParts = split(versionNumber, ".");
+ tagName = "v" + join(versionParts(1:min(3, end)), ".");
+
+ repositoryUrl = matbox.toolbox.internal.getRepositoryUrl(projectRootDirectory);
+ if repositoryUrl == ""
+ warning("MatBox:Package:RepositoryUrlNotFound", ...
+ ['The repository URL of "%s" could not be found, so relative links ', ...
+ 'in "%s" are left unchanged. Add a git remote named "origin".'], ...
+ projectRootDirectory, readmeFile)
+ end
+
+ text = string(fileread(readmeFile, "Encoding", "UTF-8"));
+ text = matbox.toolbox.internal.prepareReadme(text, ...
+ "RepositoryURL", repositoryUrl, ...
+ "Ref", tagName, ...
+ "ProjectRoot", projectRootDirectory);
+
+ fileId = fopen(readmeFile, "w", "n", "UTF-8");
+ fileCleanup = onCleanup(@() fclose(fileId));
+ fprintf(fileId, "%s", text);
+end
diff --git a/code/+matbox/+toolbox/+internal/stageRootFilesForPackaging.m b/code/+matbox/+toolbox/+internal/stageRootFilesForPackaging.m
index c58a3fd..96d0f36 100644
--- a/code/+matbox/+toolbox/+internal/stageRootFilesForPackaging.m
+++ b/code/+matbox/+toolbox/+internal/stageRootFilesForPackaging.m
@@ -1,13 +1,15 @@
-function cleanupObj = stageRootFilesForPackaging(projectRootDirectory, sourceFolderPath)
+function [cleanupObj, stagedFiles] = stageRootFilesForPackaging(projectRootDirectory, sourceFolderPath)
% stageRootFilesForPackaging - Temporarily copy project root files into the source folder
%
-% cleanupObj = stageRootFilesForPackaging(projectRootDirectory, sourceFolderPath)
+% [cleanupObj, stagedFiles] = stageRootFilesForPackaging(projectRootDirectory, sourceFolderPath)
% copies selected files from the project root directory into the toolbox
% source folder so that they are included in the packaged toolbox.
% ToolboxOptions only packages files located below the source folder, so
% files like LICENSE that conventionally live in the project root must be
% staged before packaging. The returned onCleanup object deletes the
-% staged copies when it goes out of scope.
+% staged copies when it goes out of scope. stagedFiles holds the full
+% paths of the copies; a file the source folder already had is not one
+% of them.
%
% The files to stage are read from the top-level "RootFilesToPackage"
% field of MLToolboxInfo.json. If the field is not present, the default
diff --git a/docs/ci.md b/docs/ci.md
index a328612..6611d75 100644
--- a/docs/ci.md
+++ b/docs/ci.md
@@ -217,7 +217,9 @@ The reusable workflow chains these jobs:
Project root files declared in the top-level `RootFilesToPackage`
list in `MLToolboxInfo.json` (by default `LICENSE`) are included in
the packaged toolbox. On R2026b, `Readme` and `PackageName` in its
- `ToolboxOptions` set the package readme and package name. The `.mltbx`
+ `ToolboxOptions` set the package readme and package name. A readme
+ copied from the project root loses its leading badge lines, and its
+ relative links point to the release tag. The `.mltbx`
file is named `_v.mltbx`, or by the top-level
`MltbxFileName` in `MLToolboxInfo.json` when that field is set
5. **Verify installation** — installs the packaged toolbox and confirms it
diff --git a/tools/tests/+matboxtools/+unittest/PrepareReadmeTest.m b/tools/tests/+matboxtools/+unittest/PrepareReadmeTest.m
new file mode 100644
index 0000000..ee77491
--- /dev/null
+++ b/tools/tests/+matboxtools/+unittest/PrepareReadmeTest.m
@@ -0,0 +1,243 @@
+classdef PrepareReadmeTest < matlab.unittest.TestCase
+% PrepareReadmeTest - Tests for preparing a README for the packaged toolbox
+
+ properties (Constant)
+ RepositoryURL = "https://github.com/owner/repo"
+ Ref = "v1.2.3"
+ BlobURL = "https://github.com/owner/repo/blob/v1.2.3/"
+ TreeURL = "https://github.com/owner/repo/tree/v1.2.3/"
+ RawURL = "https://raw.githubusercontent.com/owner/repo/v1.2.3/"
+ end
+
+ methods (TestMethodSetup)
+ function setupMethod(testCase)
+ testCase.applyFixture(matlab.unittest.fixtures.WorkingFolderFixture);
+ end
+ end
+
+ methods (Test)
+ function testBadgeLinesInLeadingBlockAreRemoved(testCase)
+ text = joinLines([ ...
+ "