From 9b498182b169b2edf7eb1106d7347c5dd15e698a Mon Sep 17 00:00:00 2001 From: ehennestad Date: Wed, 4 Nov 2026 11:31:56 +0100 Subject: [PATCH 1/2] feat: prepare the staged README for the packaged toolbox A README copied from the project root through RootFilesToPackage is the package readme on R2026b, and File Exchange shows it. Its badges and relative links only work on GitHub. packageToolbox now rewrites the staged copy named by Readme, once the version is known, with matbox.toolbox.internal.prepareReadme: - Lines made only of Markdown images are removed from the leading block, before the first line of prose. Image lines further down, such as figures, and HTML lines are kept. - Relative destinations of Markdown links and images, reference definitions and the HTML attributes href, src and srcset become absolute URLs at the tag v..: blob for a file, tree for a folder, the raw URL for an image. Fenced code blocks are not changed. The repository URL comes from GITHUB_SERVER_URL and GITHUB_REPOSITORY on GitHub Actions, else from the origin remote. Without either, the links stay relative and MatBox:Package:RepositoryUrlNotFound is issued. A readme committed in the source folder is not processed. stageRootFilesForPackaging returns the paths of the staged copies, so packageToolbox can tell a staged copy from a committed file. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 + code/+matbox/+tasks/packageToolbox.m | 30 ++- .../+toolbox/+internal/getRepositoryUrl.m | 50 ++++ .../+toolbox/+internal/prepareReadme.m | 238 +++++++++++++++++ .../+toolbox/+internal/prepareReadmeFile.m | 39 +++ .../+internal/stageRootFilesForPackaging.m | 8 +- docs/ci.md | 4 +- .../+unittest/PrepareReadmeTest.m | 243 ++++++++++++++++++ .../tests/+matboxtools/+unittest/TasksTest.m | 54 +++- 9 files changed, 656 insertions(+), 16 deletions(-) create mode 100644 code/+matbox/+toolbox/+internal/getRepositoryUrl.m create mode 100644 code/+matbox/+toolbox/+internal/prepareReadme.m create mode 100644 code/+matbox/+toolbox/+internal/prepareReadmeFile.m create mode 100644 tools/tests/+matboxtools/+unittest/PrepareReadmeTest.m 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([ ... + "

" + "" + "# Toolbox" + "" + "[![tests](.github/badges/tests.svg)](https://example.com/actions)" + "![version](https://img.shields.io/badge/v-1-blue) ![b](https://example.com/b.svg)" + "" + "" + "Intro text."]); + + expected = joinLines([ ... + "

" + "" + "# Toolbox" + "" + "Intro text."]); + testCase.verifyEqual(testCase.prepare(text), expected) + end + + function testImageLinesAfterProseAreKept(testCase) + text = joinLines(["# Toolbox", "Intro text.", "", "![Plot](docs/plot.png)"]); + + expected = joinLines(["# Toolbox", "Intro text.", "", ... + "![Plot](" + testCase.RawURL + "docs/plot.png)"]); + testCase.verifyEqual(testCase.prepare(text), expected) + end + + function testLineWithTextAndImageEndsLeadingBlock(testCase) + text = joinLines(["# Toolbox", "![icon](https://example.com/i.svg) Intro text.", ... + "[![b](https://example.com/b.svg)](https://example.com)"]); + + testCase.verifyEqual(testCase.prepare(text), text) + end + + function testHtmlImageLinesAreKept(testCase) + text = joinLines([ ... + "" + " " + " " + " " + " " + "" + "# Toolbox"]); + + expected = joinLines([ ... + "" + " " + " " + " " + " " + "" + "# Toolbox"]); + testCase.verifyEqual(testCase.prepare(text), expected) + end + + function testLinksToFileFolderAndImage(testCase) + mkdir(fullfile(pwd, "docs")) + text = "Text [file](LICENSE), [folder](docs), [slash](src/) and ![image](img/a.png)."; + + expected = "Text [file](" + testCase.BlobURL + "LICENSE), " ... + + "[folder](" + testCase.TreeURL + "docs), " ... + + "[slash](" + testCase.TreeURL + "src) and " ... + + "![image](" + testCase.RawURL + "img/a.png)."; + testCase.verifyEqual(testCase.prepare(text, pwd), expected) + end + + function testLinkedImageGetsRawImageAndBlobLink(testCase) + text = "Text [![logo](img/a.png)](img/a.png)."; + + expected = "Text [![logo](" + testCase.RawURL + "img/a.png)](" ... + + testCase.BlobURL + "img/a.png)."; + testCase.verifyEqual(testCase.prepare(text), expected) + end + + function testFragmentQueryAndDotSlashAreHandled(testCase) + text = "See [install](./docs/guide.md#install) and [raw](/img/a.png?raw=true)."; + + expected = "See [install](" + testCase.BlobURL + "docs/guide.md#install) and " ... + + "[raw](" + testCase.BlobURL + "img/a.png?raw=true)."; + testCase.verifyEqual(testCase.prepare(text), expected) + end + + function testAngleBracketDestinationIsRewritten(testCase) + text = "See [guide]()."; + + expected = "See [guide](<" + testCase.BlobURL + "docs/my guide.md>)."; + testCase.verifyEqual(testCase.prepare(text), expected) + end + + function testAbsoluteAndLocalDestinationsAreUnchanged(testCase) + text = joinLines([ ... + "[web](https://example.com/a.md) [mail](mailto:a@example.com)" + "[anchor](#usage) [cdn](//cdn.example.com/a.js) [parent](../other/a.md)" + "x empty"]); + + testCase.verifyEqual(testCase.prepare(text), text) + end + + function testFencedCodeIsUnchanged(testCase) + text = joinLines([ ... + "```markdown" + "[![b](b.svg)](c)" + "" + "" + "[file](LICENSE)" + "```" + "~~~~" + "```" + "[file](LICENSE)" + "~~~~" + "[file](LICENSE)"]); + + lines = splitlines(text); + expected = joinLines([lines(1:end-1); "[file](" + testCase.BlobURL + "LICENSE)"]); + testCase.verifyEqual(testCase.prepare(text), expected) + end + + function testReferenceDefinitionsAreRewritten(testCase) + text = joinLines(["Read the [guide] and see ![logo].", "", ... + "[guide]: docs/guide.md ""Guide""", " [logo]: "]); + + expected = joinLines(["Read the [guide] and see ![logo].", "", ... + "[guide]: " + testCase.BlobURL + "docs/guide.md ""Guide""", ... + " [logo]: <" + testCase.RawURL + "img/logo.svg>"]); + testCase.verifyEqual(testCase.prepare(text), expected) + end + + function testRepositoryOutsideGithubUsesRawPath(testCase) + text = "Text ![image](img/a.png) and [file](LICENSE)."; + + actual = matbox.toolbox.internal.prepareReadme(text, ... + "RepositoryURL", "https://gitlab.com/owner/repo", "Ref", testCase.Ref); + testCase.verifyEqual(actual, "Text ![image](https://gitlab.com/owner/repo/raw/v1.2.3/img/a.png) " ... + + "and [file](https://gitlab.com/owner/repo/blob/v1.2.3/LICENSE).") + end + + function testWithoutRepositoryUrlOnlyBadgesAreRemoved(testCase) + text = joinLines(["# Toolbox", "[![b](b.svg)](c)", "", "See [file](LICENSE)."]); + + actual = matbox.toolbox.internal.prepareReadme(text); + testCase.verifyEqual(actual, joinLines(["# Toolbox", "", "See [file](LICENSE)."])) + end + + function testFinalNewlineIsKept(testCase) + testCase.verifyEqual(testCase.prepare("Text." + newline), "Text." + newline) + testCase.verifyEqual(testCase.prepare("Text."), "Text.") + end + + function testRepositoryUrlFromGithubActions(testCase) + testCase.applyFixture(matlab.unittest.fixtures.EnvironmentVariableFixture( ... + "GITHUB_SERVER_URL", "https://github.com")); + testCase.applyFixture(matlab.unittest.fixtures.EnvironmentVariableFixture( ... + "GITHUB_REPOSITORY", "owner/repo")); + + testCase.verifyEqual(matbox.toolbox.internal.getRepositoryUrl(pwd), ... + "https://github.com/owner/repo") + end + + function testRepositoryUrlFromOriginRemote(testCase) + testCase.clearGithubActionsEnvironment() + testCase.initializeGitRepository() + + remoteUrls = [ ... + "git@github.com:owner/repo.git" + "ssh://git@example.com:2222/owner/repo.git" + "https://user:token@github.com/owner/repo.git" + "https://github.com/owner/repo/"]; + expectedUrls = [ ... + "https://github.com/owner/repo" + "https://example.com/owner/repo" + "https://github.com/owner/repo" + "https://github.com/owner/repo"]; + for iUrl = 1:numel(remoteUrls) + testCase.setOriginRemote(remoteUrls(iUrl)) + testCase.verifyEqual(matbox.toolbox.internal.getRepositoryUrl(pwd), ... + expectedUrls(iUrl), "Remote URL: " + remoteUrls(iUrl)) + end + end + + function testRepositoryUrlIsEmptyWithoutOrigin(testCase) + testCase.clearGithubActionsEnvironment() + testCase.initializeGitRepository() + + testCase.verifyEqual(matbox.toolbox.internal.getRepositoryUrl(pwd), "") + end + end + + methods (Access = private) + function text = prepare(testCase, text, projectRoot) + arguments + testCase + text (1,1) string + projectRoot (1,1) string = "" + end + text = matbox.toolbox.internal.prepareReadme(text, ... + "RepositoryURL", testCase.RepositoryURL, ... + "Ref", testCase.Ref, ... + "ProjectRoot", projectRoot); + end + + function clearGithubActionsEnvironment(testCase) + testCase.applyFixture(matlab.unittest.fixtures.EnvironmentVariableFixture( ... + "GITHUB_SERVER_URL", "")); + testCase.applyFixture(matlab.unittest.fixtures.EnvironmentVariableFixture( ... + "GITHUB_REPOSITORY", "")); + end + + function initializeGitRepository(testCase) + [status, output] = system(sprintf('git -C "%s" init', pwd)); + testCase.assertEqual(status, 0, output) + end + + function setOriginRemote(testCase, remoteUrl) + [~, ~] = system(sprintf('git -C "%s" remote remove origin', pwd)); % Fails when there is no origin yet + [status, output] = system(sprintf('git -C "%s" remote add origin %s', pwd, remoteUrl)); + testCase.assertEqual(status, 0, output) + end + end +end + +function text = joinLines(lines) + text = join(lines(:), newline); +end diff --git a/tools/tests/+matboxtools/+unittest/TasksTest.m b/tools/tests/+matboxtools/+unittest/TasksTest.m index 449f1a5..9133253 100644 --- a/tools/tests/+matboxtools/+unittest/TasksTest.m +++ b/tools/tests/+matboxtools/+unittest/TasksTest.m @@ -175,20 +175,48 @@ function testMltbxFileNameWithFolderErrors(testCase) function testPackageToolboxWithReadmeAndPackageName(testCase) % Releases before R2026b have neither property, and must still % package the readme as an ordinary file. - archiveFolder = packageWithReadmeAndPackageName(); - + [archiveFolder, newVersion] = packageWithReadmeAndPackageName(testCase); + + % The staged copy of the project README is packaged after + % processing, with links to the tag of the new version. + versionParts = split(newVersion, "."); + expectedText = matbox.toolbox.internal.prepareReadme( ... + string(fileread(fullfile(pwd, "README.md"), "Encoding", "UTF-8")), ... + "RepositoryURL", "https://github.com/owner/repo", ... + "Ref", "v" + join(versionParts(1:3), "."), ... + "ProjectRoot", pwd); packagedReadmeFile = fullfile(archiveFolder, "fsroot", "README.md"); - testCase.verifyTrue(isfile(packagedReadmeFile)) - testCase.verifyEqual(fileread(packagedReadmeFile), ... - fileread(fullfile(pwd, "README.md"))) + testCase.assertTrue(isfile(packagedReadmeFile)) + packagedText = string(fileread(packagedReadmeFile, "Encoding", "UTF-8")); + testCase.verifyEqual(packagedText, expectedText) + testCase.verifyFalse(contains(packagedText, "](.github/badges/tests.svg)")) + testCase.verifySubstring(packagedText, "https://github.com/owner/repo/blob/v") + testCase.verifyFalse(isfile(fullfile(pwd, "code", "README.md"))) end + function testPackageToolboxLeavesCommittedReadmeUnchanged(testCase) + copyfile(matboxtools.projectdir(), pwd); + + % A readme committed in the source folder is not a staged copy + readmeText = "[![b](.github/badges/tests.svg)](https://example.com)" + newline ... + + "See [file](LICENSE)." + newline; + matbox.utility.filewrite(fullfile(pwd, "code", "README.md"), readmeText); + setToolboxInfoFields(pwd, struct("Readme", "README.md")) + + [~, toolboxFile] = matbox.tasks.packageToolbox(pwd, "build", "", "SourceFolderName", "code"); + + archiveFolder = fullfile(pwd, "toolbox-archive"); + unzip(toolboxFile, archiveFolder) + testCase.verifyEqual(string(fileread(fullfile(archiveFolder, "fsroot", "README.md"))), readmeText) + testCase.verifyEqual(string(fileread(fullfile(pwd, "code", "README.md"))), readmeText) + end + function testPackageToolboxWritesReadmeAndPackageNameToMpackage(testCase) testCase.assumeFalse(isMATLABReleaseOlderThan("R2026b"), ... "ToolboxOptions has Readme and PackageName only from R2026b.") - archiveFolder = packageWithReadmeAndPackageName(); + archiveFolder = packageWithReadmeAndPackageName(testCase); mpackage = jsondecode(fileread( ... fullfile(archiveFolder, "fsroot", "resources", "mpackage.json"))); @@ -307,17 +335,23 @@ function writeTestResultsReport(projectRootDirectory, releaseName, options) badgeInfo = jsondecode(fileread(badgeFile)); end -function archiveFolder = packageWithReadmeAndPackageName() +function [archiveFolder, newVersion] = packageWithReadmeAndPackageName(testCase) % packageWithReadmeAndPackageName - Package a copy of MatBox that sets Readme and PackageName % -% The project README.md is staged through RootFilesToPackage. Returns the -% folder the packaged toolbox is unzipped to. +% The project README.md is staged through RootFilesToPackage, and the +% repository URL is https://github.com/owner/repo. Returns the folder the +% packaged toolbox is unzipped to, and the packaged version. + + testCase.applyFixture(matlab.unittest.fixtures.EnvironmentVariableFixture( ... + "GITHUB_SERVER_URL", "https://github.com")); + testCase.applyFixture(matlab.unittest.fixtures.EnvironmentVariableFixture( ... + "GITHUB_REPOSITORY", "owner/repo")); copyfile(matboxtools.projectdir(), pwd); setToolboxInfoFields(pwd, struct("Readme", "README.md", "PackageName", "MatBoxTest"), ... {'LICENSE'; 'README.md'}) - [~, toolboxFile] = matbox.tasks.packageToolbox(pwd, "build", "", "SourceFolderName", "code"); + [newVersion, toolboxFile] = matbox.tasks.packageToolbox(pwd, "build", "", "SourceFolderName", "code"); archiveFolder = fullfile(pwd, "toolbox-archive"); unzip(toolboxFile, archiveFolder) end From a80d1e4a4243ff571c2df152a8256f8b640d7261 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 10:36:15 +0000 Subject: [PATCH 2/2] Update GitHub badges [skip ci] --- .github/badges/tests.svg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 @@ -tests: 114 passedtests114 passed +tests: 132 passedtests132 passed