MCPcopy
hub / github.com/pocketbase/pocketbase / normalizeName

Function normalizeName

tools/filesystem/file.go:195–236  ·  view source on GitHub ↗
(fr FileReader, name string)

Source from the content-addressed store, hash-verified

193const randomAlphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
194
195func normalizeName(fr FileReader, name string) string {
196 // cut the name even if it is not multibyte safe to avoid operating on too large strings
197 // ---
198 originalLength := len(name)
199 if originalLength > 300 {
200 name = name[originalLength-300:]
201 }
202
203 // extension
204 // ---
205 originalExt := extractExtension(name)
206 cleanExt := "." + strings.Trim(extInvalidCharsRegex.ReplaceAllString(originalExt, ""), ".")
207 if cleanExt == "." {
208 // try to detect the extension from the file content
209 cleanExt, _ = detectExtension(fr)
210 }
211 if extLength := len(cleanExt); extLength > 20 {
212 // keep only the last 20 characters (it is multibyte safe after the regex replace)
213 cleanExt = "." + strings.Trim(cleanExt[extLength-20:], ".")
214 }
215
216 // name
217 //
218 // note: leading dot is trimmed to prevent various subtle issues with files
219 // sync programs as they sometimes have special handling for "invisible" files
220 // ---
221 cleanName := inflector.Snakecase(strings.Trim(strings.TrimSuffix(name, originalExt), "."))
222 if length := len(cleanName); length < 3 {
223 // the name is too short so we concatenate an additional random part
224 cleanName += security.RandomStringWithAlphabet(10, randomAlphabet)
225 } else if length > 100 {
226 // keep only the first 100 characters (it is multibyte safe after Snakecase)
227 cleanName = cleanName[:100]
228 }
229
230 return fmt.Sprintf(
231 "%s_%s%s",
232 cleanName,
233 security.RandomStringWithAlphabet(10, randomAlphabet), // ensure that there is always a random part
234 cleanExt,
235 )
236}
237
238// extractExtension extracts the extension (with leading dot) from name.
239//

Callers 4

GetReuploadableFileMethod · 0.85
NewFileFromPathFunction · 0.85
NewFileFromBytesFunction · 0.85
NewFileFromMultipartFunction · 0.85

Calls 4

SnakecaseFunction · 0.92
RandomStringWithAlphabetFunction · 0.92
extractExtensionFunction · 0.85
detectExtensionFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…