Skip to content

Commit

Permalink
Fix links that are relative to the site root
Browse files Browse the repository at this point in the history
Imported links like `/public/foo.json` currently get converted to
https://docs.publishing.service.gov.uk/public/foo.json.
These links obviously 404.

Whilst technically they should be converted to
https://www.github.com/public/foo.json (if we were to take them
at face value), those links would also 404. What the developer
intends, and what GitHub obliges to do, is to convert them
relative to the repository, i.e.
https://github.com/alphagov/lipsum/blob/master/public/foo.json.
We must do the same.

This commit should fix a live issue I'm seeing on this page:
https://docs.publishing.service.gov.uk/apps/hmrc-manuals-api/extended_documentation.html#example-json
  • Loading branch information
ChrisBAshton committed Jan 20, 2021
1 parent b5f0424 commit 2f80db1
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 8 deletions.
14 changes: 6 additions & 8 deletions app/external_doc.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,17 +59,15 @@ def call

href = element["href"].strip
uri = URI.parse(href)
path = uri.path

next if uri.scheme || href.start_with?("#")

base = if path.start_with? "/"
base_url
else
context[:subpage_url]
end

element["href"] = URI.join(base, href).to_s
if href.start_with?("/") && context[:subpage_url].to_s.start_with?("https://github.com")
# remove preceding "/" to make links relative to the repository
# rather than to github.com. This is what GitHub does too.
href = href[1..-1]
end
element["href"] = URI.join(context[:subpage_url], href).to_s
end

doc
Expand Down
4 changes: 4 additions & 0 deletions spec/app/external_doc_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@
expect(html).to have_link("Subfolder", href: "https://github.com/alphagov/lipsum/blob/master/docs/some-subfolder/foo.md")
end

it "converts links relative to the 'root' to absolute GitHub URLs" do
expect(html).to have_link("Link relative to root", href: "https://github.com/alphagov/lipsum/blob/master/public/json_examples/requests/foo.json")
end

context "the document we are parsing is in the `docs` folder" do
let(:path) { "docs/some-document.md" }

Expand Down
2 changes: 2 additions & 0 deletions spec/fixtures/markdown.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ neque consequat porta, [Suspendisse iaculis](#suspendisse-iaculis). Sed et

[Relative docs link without period](docs/no-prefix.md)

[Link relative to root](/public/json_examples/requests/foo.json)

[Subfolder](docs/some-subfolder/foo.md)

## Suspendisse iaculis
Expand Down

0 comments on commit 2f80db1

Please sign in to comment.