|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# |
| 4 | +# This custom plugin dynamically sets the 'versions' parameter |
| 5 | +# for a page at any '/guides/v<...>/' directory. |
| 6 | +# The pararmeter is available as a liquid expression {{ page.versions }}. |
| 7 | +# It stores an array of hashes like [ { 'name' => '2.1', 'url' = guides/v2.1/index.html }, { 'name' => '2.2', 'url' = guides/v2.2/index.html }, etc ]. |
| 8 | +# The parameter contains all available versions of the topic. |
| 9 | +# |
| 10 | +Jekyll::Hooks.register :pages, :pre_render do |page, config| |
| 11 | + # Process only files with 'md' and 'html' extensions |
| 12 | + next unless File.extname(page.path).match?(/md|html/) |
| 13 | + |
| 14 | + # Do nothing for redirects |
| 15 | + next if page.name == 'redirect.html' |
| 16 | + |
| 17 | + # Process only pages that have URL starting with '/guides/v' |
| 18 | + filtering_pattern = '/guides/v' |
| 19 | + next unless page.url.start_with? filtering_pattern |
| 20 | + |
| 21 | + # Get all page objects at the site |
| 22 | + pages = page.site.pages |
| 23 | + |
| 24 | + # Select pages that do not have name 'redirect.html' and their URL |
| 25 | + # starts with '/guides/v'. Get 'url' of each page and store them as an array. |
| 26 | + urls_filtered_by_pattern = |
| 27 | + pages.filter do |site_page| |
| 28 | + next if site_page.name == 'redirect.html' |
| 29 | + site_page.url.start_with? filtering_pattern |
| 30 | + end.map(&:url) |
| 31 | + |
| 32 | + url = page.url |
| 33 | + |
| 34 | + # Get the nonversion path from URL removing prefix 'guides/v<...>/'. |
| 35 | + versioned_prefix_pattern = %r{\A#{filtering_pattern}[^/]+} |
| 36 | + non_version_path = url.sub(versioned_prefix_pattern, '') |
| 37 | + |
| 38 | + # Define a regular expression to match all versions of a topic |
| 39 | + full_path_pattern = /#{versioned_prefix_pattern}#{non_version_path}\Z/ |
| 40 | + |
| 41 | + # Get URLs for all versions of the topic |
| 42 | + versioned_urls = |
| 43 | + urls_filtered_by_pattern.filter { |path| path.match full_path_pattern } |
| 44 | + |
| 45 | + # Define a regular expression to get a version number from URL |
| 46 | + # to the 'version_from_path' variable |
| 47 | + version_pattern = %r{\A#{filtering_pattern}(?<version_from_path>[^/]+)} |
| 48 | + |
| 49 | + # Get all versioned URLs of the topic into array of key-value pairs |
| 50 | + # like { 'name' => '2.0', 'url' => '/guides/v2.3/index.html' } |
| 51 | + versions = |
| 52 | + versioned_urls.map do |v_url| |
| 53 | + version_pattern.match(v_url) |
| 54 | + version = Regexp.last_match(:version_from_path) |
| 55 | + { |
| 56 | + 'name' => version, |
| 57 | + 'url' => v_url |
| 58 | + } |
| 59 | + end |
| 60 | + |
| 61 | + # Set the page.versions parameter to sorted array of key-value pairs |
| 62 | + # from 'versions' |
| 63 | + config['page']['versions'] = versions.sort_by { |version| version['name'] } |
| 64 | +end |
0 commit comments