Skip to content

Instantly share code, notes, and snippets.

@jolle-c
Created November 10, 2017 09:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jolle-c/154d87324d40cd1c45f32a635a3c9350 to your computer and use it in GitHub Desktop.
Save jolle-c/154d87324d40cd1c45f32a635a3c9350 to your computer and use it in GitHub Desktop.
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