(oldRootHTML string, rootHTMLPath string, alreadyRewritten bool, pathToReplace, newPath, subpath string)
| 96 | } |
| 97 | |
| 98 | func updateRootFile(oldRootHTML string, rootHTMLPath string, alreadyRewritten bool, pathToReplace, newPath, subpath string) error { |
| 99 | newRootHTML := oldRootHTML |
| 100 | |
| 101 | reCSP := regexp.MustCompile(`<meta http-equiv="Content-Security-Policy" content="script-src 'self'([^"]*)">`) |
| 102 | if results := reCSP.FindAllString(newRootHTML, -1); len(results) == 0 { |
| 103 | return fmt.Errorf("failed to find 'Content-Security-Policy' meta tag to rewrite") |
| 104 | } |
| 105 | |
| 106 | newRootHTML = reCSP.ReplaceAllLiteralString(newRootHTML, fmt.Sprintf( |
| 107 | `<meta http-equiv="Content-Security-Policy" content="script-src 'self'%s">`, |
| 108 | GetSubpathScriptHash(subpath), |
| 109 | )) |
| 110 | |
| 111 | // Rewrite the root.html references to `/static/*` to include the given subpath. |
| 112 | // This potentially includes a previously injected inline script that needs to |
| 113 | // be updated (and isn't covered by the cases above). |
| 114 | newRootHTML = strings.Replace(newRootHTML, pathToReplace, newPath, -1) |
| 115 | |
| 116 | publicPathInWindowsScriptRegex := regexp.MustCompile(`(?s)<script id="publicPathInWindowScript">(.*?)</script>`) |
| 117 | |
| 118 | if alreadyRewritten && subpath == "/" { |
| 119 | // Remove window global publicPath definition if subpath is root |
| 120 | newRootHTML = publicPathInWindowsScriptRegex.ReplaceAllLiteralString(newRootHTML, "<script id=\"publicPathInWindowScript\"></script>") |
| 121 | } else if !alreadyRewritten && subpath != "/" { |
| 122 | // Inject the script to define `window.publicPath` for the specified subpath |
| 123 | subpathScript := getSubpathScript(subpath) |
| 124 | newRootHTML = publicPathInWindowsScriptRegex.ReplaceAllLiteralString(newRootHTML, fmt.Sprintf("<script id=\"publicPathInWindowScript\">%s</script>", subpathScript)) |
| 125 | } |
| 126 | |
| 127 | if newRootHTML == oldRootHTML { |
| 128 | mlog.Debug("No need to rewrite unmodified root.html", mlog.String("from_subpath", pathToReplace), mlog.String("to_subpath", newPath)) |
| 129 | return nil |
| 130 | } |
| 131 | |
| 132 | mlog.Debug("Rewriting root.html", mlog.String("from_subpath", pathToReplace), mlog.String("to_subpath", newPath)) |
| 133 | // Write out the updated root.html. |
| 134 | if err := os.WriteFile(rootHTMLPath, []byte(newRootHTML), 0); err != nil { |
| 135 | return errors.Wrapf(err, "failed to update root.html with subpath %s", subpath) |
| 136 | } |
| 137 | |
| 138 | return nil |
| 139 | } |
| 140 | |
| 141 | func updateManifestAndCSSFiles(staticDir, pathToReplace, newPath, subpath string) error { |
| 142 | if pathToReplace == newPath { |
no test coverage detected
searching dependent graphs…