Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
safe_filename will take a string as input and return a string safe to use as a file name
define safe_filename(
filename::string,
-replacechar::string = '-',
-clearemoji::boolean = false,
-noleadingperiod::boolean = false,
-allowed_length::integer = 255
) => {
local(_filename = string(#filename))
// spaces at start and end not allowed
#_filename->trim
// periods at end of filename not allowed
#_filename->removetrailing('.')
// period at start of filename is allowed but makes the file invisible on some OS
#noleadingperiod ? #_filename->removeleading('.')
// emojis can cause issues when communicating with Mysql
#clearemoji ? #_filename->replace(regexp(`[\x{10000}-\x{10ffff}]`, #replacechar))
// illegal chars in some or all file systems
#_filename->replace(regexp(`[\\/:]`, #replacechar))
while (#_filename->length > #allowed_length) => {
local(
nameparts = #_filename->split('.'),
suffix = #nameparts->last
)
#suffix->length > #allowed_length ? #suffix = #suffix->substring(1, #allowed_length)
#nameparts->remove // gets rid of the suffix
#_filename = #nameparts->join('.')->substring(1, max(1, #allowed_length - (#suffix->length + 1)))
#_filename->length > 0 ? #_filename->append('.')
#_filename->append(#suffix)
}
return #_filename
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.