|
| 1 | +// Copyright 2022 The Gitea Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a MIT-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +//go:build !bindata |
| 6 | +// +build !bindata |
| 7 | + |
| 8 | +package public |
| 9 | + |
| 10 | +import ( |
| 11 | + "io" |
| 12 | + "io/fs" |
| 13 | + "net/http" |
| 14 | + "sync" |
| 15 | + "time" |
| 16 | + |
| 17 | + "code.gitea.io/gitea/modules/json" |
| 18 | + "code.gitea.io/gitea/modules/log" |
| 19 | + "code.gitea.io/gitea/modules/setting" |
| 20 | +) |
| 21 | + |
| 22 | +var ( |
| 23 | + manifest map[string]string |
| 24 | + manifestName = "assets-manifest.json" |
| 25 | + manifestMutex = &sync.Mutex{} |
| 26 | + manifestModified time.Time |
| 27 | +) |
| 28 | + |
| 29 | +func readManifestFile(fs http.FileSystem) (http.File, fs.FileInfo, error) { |
| 30 | + f, err := fs.Open(manifestName) |
| 31 | + if err != nil { |
| 32 | + return nil, nil, err |
| 33 | + } |
| 34 | + |
| 35 | + fi, err := f.Stat() |
| 36 | + if err != nil { |
| 37 | + return nil, nil, err |
| 38 | + } |
| 39 | + |
| 40 | + return f, fi, nil |
| 41 | +} |
| 42 | + |
| 43 | +func readManifest(fs http.FileSystem) map[string]string { |
| 44 | + manifestMutex.Lock() |
| 45 | + var assetMap map[string]string |
| 46 | + |
| 47 | + f, fi, err := readManifestFile(fs) |
| 48 | + if err != nil { |
| 49 | + log.Error("[Static] Failed to open %q: %v", manifestName, err) |
| 50 | + return assetMap |
| 51 | + } |
| 52 | + defer f.Close() |
| 53 | + |
| 54 | + bytes, err := io.ReadAll(f) |
| 55 | + if err != nil { |
| 56 | + log.Error("[Static] Failed to read %q: %v", manifestName, err) |
| 57 | + return assetMap |
| 58 | + } |
| 59 | + |
| 60 | + err = json.Unmarshal(bytes, &assetMap) |
| 61 | + if err != nil { |
| 62 | + log.Error("[Static] Failed to parse %q: %v", manifestName, err) |
| 63 | + return assetMap |
| 64 | + } |
| 65 | + |
| 66 | + manifestModified = fi.ModTime() |
| 67 | + manifestMutex.Unlock() |
| 68 | + return assetMap |
| 69 | +} |
| 70 | + |
| 71 | +// ResolveWithManifest turns /js/index.js into /js/index.5ed90373e37c.js using assets-manifest.json |
| 72 | +func ResolveWithManifest(fs http.FileSystem, file string) string { |
| 73 | + if len(manifest) == 0 { |
| 74 | + manifest = readManifest(fs) |
| 75 | + } |
| 76 | + |
| 77 | + // in development, the manifest can frequently change, check and reload if necessary |
| 78 | + if !setting.IsProd { |
| 79 | + f, fi, err := readManifestFile(fs) |
| 80 | + if err != nil { |
| 81 | + log.Error("[Static] Failed to open %q: %v", manifestName, err) |
| 82 | + } else { |
| 83 | + defer f.Close() |
| 84 | + } |
| 85 | + |
| 86 | + if fi.ModTime().After(manifestModified) { |
| 87 | + manifest = readManifest(fs) |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + if mappedFile, ok := manifest[file]; ok { |
| 92 | + return mappedFile |
| 93 | + } |
| 94 | + return file |
| 95 | +} |
0 commit comments