Skip to content

Commit 0d9b23c

Browse files
committed
Read env vars from _index.md
1 parent 977dbae commit 0d9b23c

File tree

3 files changed

+58
-4
lines changed

3 files changed

+58
-4
lines changed

.github/workflows/run-code-blocks.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,5 +35,5 @@ jobs:
3535
ALL_CHANGED_FILES: ${{ steps.changed-files.outputs.all_changed_files }}
3636
run: |
3737
for file in ${ALL_CHANGED_FILES}; do
38-
python -u scripts/md-k6.py --duration 2s "$file"
38+
python -u scripts/md-k6.py --duration 2s "$file" --index-file docs/sources/k6/_index.md
3939
done

docs/sources/k6/next/javascript-api/jslib/http-instrumentation-pyroscope/_index.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ This module, by default, adds three key-value pairs:
3434

3535
## Example
3636

37-
This example demonstrates how to use the this library to instrument every HTTP request made in a script with the `baggage` header.
37+
This example demonstrates how to use the this library to instrument every HTTP request made in a script with the `baggage` header TEST.
3838

3939
{{< code >}}
4040

scripts/md-k6.py

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import argparse
1212
import subprocess
1313
import tempfile
14+
from typing import TextIO
1415
from unittest import TestCase
1516
from collections import namedtuple
1617

@@ -120,7 +121,11 @@ def run_k6(script: Script, duration: str | None, verbose: bool) -> None:
120121
print(line)
121122

122123

123-
def extract_scripts(text: str, lang: str = JS) -> list[Script]:
124+
def extract_scripts(
125+
text: str, lang: str = JS, index_env: dict[str, str] | None = None
126+
) -> list[Script]:
127+
index_env = index_env or {}
128+
124129
# A somewhat complicated regex in order to make parsing of the code block
125130
# easier. Essentially, takes this:
126131
#
@@ -185,6 +190,13 @@ def extract_scripts(text: str, lang: str = JS) -> list[Script]:
185190
args.append(opt.removeprefix(ARG))
186191

187192
script_text = "\n".join(lines[1:])
193+
for key, value in index_env.items():
194+
# Replace instances of '{{< param "FOO_BAR" >}}' with '1234', assuming
195+
# the env value of FOO_BAR=1234.
196+
script_text = re.sub(
197+
r"{{ *< *param *\"" + key + '" *> *}}', value, script_text
198+
)
199+
188200
scripts.append(
189201
Script(
190202
text=script_text,
@@ -198,6 +210,26 @@ def extract_scripts(text: str, lang: str = JS) -> list[Script]:
198210
return scripts
199211

200212

213+
def read_front_matter_env(f: TextIO) -> dict[str, str]:
214+
# Read a Front Matter .md file with environment variables.
215+
# The variables are actually in a YAML dictionary, but since
216+
# I want to avoid 3rd party library, I will just try to parse
217+
# them line-by-line.
218+
result = {}
219+
for line in f.readlines():
220+
if ":" not in line:
221+
continue
222+
223+
parts = line.strip().split(":")
224+
key, value = parts[0].strip(), parts[1].strip()
225+
226+
# Look for YAML keys with ALL_CAPS_NAMES
227+
if re.match(r"[A-Z0-9_]", key) and value:
228+
result[key] = value
229+
230+
return result
231+
232+
201233
def main() -> None:
202234
parser = argparse.ArgumentParser(
203235
description="Run k6 scripts within Markdown files."
@@ -215,6 +247,12 @@ def main() -> None:
215247
default=None,
216248
help="Override script(s) duration. Is not applied to browser tests.",
217249
)
250+
parser.add_argument(
251+
"--index-file",
252+
type=argparse.FileType(),
253+
default=None,
254+
help="Path to Front Matter _index.md file containing environment variables.",
255+
)
218256
parser.add_argument(
219257
"--verbose",
220258
"-v",
@@ -223,8 +261,13 @@ def main() -> None:
223261
action="store_true",
224262
)
225263
args = parser.parse_args()
264+
index_env = read_front_matter_env(args.index_file)
226265

227266
print("Starting md-k6 script.")
267+
print("Front Matter variables:")
268+
for key, value in index_env.items():
269+
print(f" {key}={value}")
270+
228271
print("Reading from file:", args.file.name)
229272

230273
lang = args.lang
@@ -234,7 +277,7 @@ def main() -> None:
234277
print(f"Skipping entire file ({SKIP_ALL}).")
235278
return
236279

237-
scripts = extract_scripts(text, lang)
280+
scripts = extract_scripts(text, lang, index_env)
238281

239282
if ":" in args.blocks:
240283
range_parts = args.blocks.split(":")
@@ -290,6 +333,17 @@ def testExtractScriptSimple(self):
290333
self.assertEqual(len(scripts), 1)
291334
self.assertEqual(scripts[0].text, "hello, world!")
292335

336+
def testExtractScriptIndexEnv(self):
337+
text = """
338+
```javascript
339+
{{< param "FOO_BAR" >}} {{ < param "FOO_BAR" > }}
340+
```
341+
"""
342+
scripts = extract_scripts(text, JS, {"FOO_BAR": "testing"})
343+
344+
self.assertEqual(len(scripts), 1)
345+
self.assertEqual(scripts[0].text, "testing testing")
346+
293347
def testExtractScriptOptions(self):
294348
text = """
295349
<!-- md-k6:nofail,env.A=B,env.C=X- -->

0 commit comments

Comments
 (0)