UpdateAssetsSubpathInDir rewrites assets in the given directory to assume the application is hosted at the given subpath instead of at the root. No changes are written unless necessary.
(subpath, directory string)
| 47 | // UpdateAssetsSubpathInDir rewrites assets in the given directory to assume the application is |
| 48 | // hosted at the given subpath instead of at the root. No changes are written unless necessary. |
| 49 | func UpdateAssetsSubpathInDir(subpath, directory string) error { |
| 50 | if subpath == "" { |
| 51 | subpath = "/" |
| 52 | } |
| 53 | |
| 54 | // Resolve the static directory |
| 55 | staticDir, found := fileutils.FindDir(directory) |
| 56 | if !found { |
| 57 | return errors.New("failed to find client dir") |
| 58 | } |
| 59 | staticDir, err := filepath.EvalSymlinks(staticDir) |
| 60 | if err != nil { |
| 61 | return errors.Wrapf(err, "failed to resolve symlinks to %s", staticDir) |
| 62 | } |
| 63 | |
| 64 | // Read the old root.html file |
| 65 | rootHTMLPath := filepath.Join(staticDir, "root.html") |
| 66 | oldRootHTML, err := os.ReadFile(rootHTMLPath) |
| 67 | if err != nil { |
| 68 | return errors.Wrap(err, "failed to open root.html") |
| 69 | } |
| 70 | |
| 71 | oldSubpath := "/" |
| 72 | |
| 73 | // Determine if a previous subpath had already been rewritten into the assets. |
| 74 | reWebpackPublicPathScript := regexp.MustCompile("window.publicPath='([^']+/)static/'") |
| 75 | alreadyRewritten := false |
| 76 | if matches := reWebpackPublicPathScript.FindStringSubmatch(string(oldRootHTML)); matches != nil { |
| 77 | oldSubpath = matches[1] |
| 78 | alreadyRewritten = true |
| 79 | } |
| 80 | |
| 81 | // Determine the old and new paths |
| 82 | pathToReplace := path.Join(oldSubpath, "static") + "/" |
| 83 | newPath := path.Join(subpath, "static") + "/" |
| 84 | |
| 85 | // Update the root.html file |
| 86 | if err := updateRootFile(string(oldRootHTML), rootHTMLPath, alreadyRewritten, pathToReplace, newPath, subpath); err != nil { |
| 87 | return fmt.Errorf("failed to update root.html: %w", err) |
| 88 | } |
| 89 | |
| 90 | // Update the manifest.json and *.css files |
| 91 | if err := updateManifestAndCSSFiles(staticDir, pathToReplace, newPath, subpath); err != nil { |
| 92 | return fmt.Errorf("failed to update manifest.json and *.css files: %w", err) |
| 93 | } |
| 94 | |
| 95 | return nil |
| 96 | } |
| 97 | |
| 98 | func updateRootFile(oldRootHTML string, rootHTMLPath string, alreadyRewritten bool, pathToReplace, newPath, subpath string) error { |
| 99 | newRootHTML := oldRootHTML |
no test coverage detected
searching dependent graphs…