injectBuildIdMeta function
Inserts the build-ID meta tag just before </head>, removing any previous
one first.
Throws a FormatException when html has no </head>.
Implementation
String injectBuildIdMeta(String html, String buildId) {
final String clean = removeBuildIdMeta(html);
final Match? head = _headClose.firstMatch(clean);
if (head == null) {
throw const FormatException('index.html has no </head> tag');
}
final String tag =
'<meta name="$buildIdMetaName" content="${_escapeAttr(buildId)}">';
final int lineStart = head.start == 0
? 0
: clean.lastIndexOf('\n', head.start - 1) + 1;
final String before = clean.substring(lineStart, head.start);
if (before.trim().isEmpty) {
// `</head>` starts its own line: add the tag as a line of its own.
final String newline = clean.contains('\r\n') ? '\r\n' : '\n';
return '${clean.substring(0, lineStart)}$before $tag$newline'
'${clean.substring(lineStart)}';
}
return '${clean.substring(0, head.start)}$tag${clean.substring(head.start)}';
}