From d517b22cf0712b4e4f736b9b5f54c9092efc1582 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Mon, 5 Feb 2024 08:41:15 -0500 Subject: [PATCH] Allow code annotations to have hashbangs (#48995) --- src/content-render/tests/annotate.js | 25 +++++++++++++ src/content-render/unified/annotate.js | 9 ++++- .../foo/code-snippet-with-hashbang.md | 36 +++++++++++++++++++ .../fixtures/content/get-started/foo/index.md | 1 + src/fixtures/tests/annotations.js | 34 ++++++++++++++++++ 5 files changed, 104 insertions(+), 1 deletion(-) create mode 100644 src/fixtures/fixtures/content/get-started/foo/code-snippet-with-hashbang.md create mode 100644 src/fixtures/tests/annotations.js diff --git a/src/content-render/tests/annotate.js b/src/content-render/tests/annotate.js index ffd1ab310d..37a2b318cd 100644 --- a/src/content-render/tests/annotate.js +++ b/src/content-render/tests/annotate.js @@ -1,3 +1,4 @@ +import cheerio from 'cheerio' import { renderContent } from '#src/content-render/index.js' const example = ` @@ -22,4 +23,28 @@ describe('annotate', () => { // If it is indeed correct, run `jest --updateSnapshot` to update it. expect(await renderContent(example)).toMatchSnapshot() }) + + test('renders bash with hash bang annotations', async () => { + const example = ` +\`\`\`bash annotate +# The next line is the hash bang +#!/usr/bin/env bash + +# Sample comment +echo "Hello, world!" +\`\`\` +`.trim() + const res = await renderContent(example) + const $ = cheerio.load(res) + + const headerCode = $('header pre').text() + expect(headerCode).toMatch(example.split('\n').slice(1, -1).join('\n')) + const rows = $('.annotate-row') + const notes = $('.annotate-note p', rows) + const noteTexts = notes.map((i, el) => $(el).text()).get() + expect(noteTexts).toEqual(['The next line is the hash bang', 'Sample comment']) + const codes = $('.annotate-code pre', rows) + const codeTexts = codes.map((i, el) => $(el).text()).get() + expect(codeTexts).toEqual(['#!/usr/bin/env bash', 'echo "Hello, world!"']) + }) }) diff --git a/src/content-render/unified/annotate.js b/src/content-render/unified/annotate.js index 086ec39b38..ef7e04b7c1 100644 --- a/src/content-render/unified/annotate.js +++ b/src/content-render/unified/annotate.js @@ -40,7 +40,7 @@ import { header } from './code-header.js' const languages = yaml.load(fs.readFileSync('./data/code-languages.yml', 'utf8')) const commentRegexes = { - number: /^\s*#\s*/, // also known has hash or sharp; but the unicode name is "number sign" + number: /^\s*#[^!]\s*/, // also known has hash or sharp; but the unicode name is "number sign" slash: /^\s*\/\/\s*/, xml: /^\s*