Debian Codegraph @

R/sanitize.R

raw
1 #' Sanitize a filename by removing directory paths and invalid characters
2 #'
3 #' `path_sanitize()` removes the following:
4 #' - [Control characters](https://en.wikipedia.org/wiki/C0_and_C1_control_codes)
5 #' - [Reserved characters](https://web.archive.org/web/20230126161942/https://kb.acronis.com/content/39790)
6 #' - Unix reserved filenames (`.` and `..`)
7 #' - Trailing periods and spaces (invalid on Windows)
8 #' - Windows reserved filenames (`CON`, `PRN`, `AUX`, `NUL`, `COM1`, `COM2`,
9 #' `COM3`, COM4, `COM5`, `COM6`, `COM7`, `COM8`, `COM9`, `LPT1`, `LPT2`,
10 #' `LPT3`, `LPT4`, `LPT5`, `LPT6`, LPT7, `LPT8`, and `LPT9`)
11 #' The resulting string is then truncated to [255 bytes in length](https://en.wikipedia.org/wiki/Comparison_of_file_systems#Limits)
12 #' @param filename A character vector to be sanitized.
13 #' @param replacement A character vector used to replace invalid characters.
14 #' @seealso <https://www.npmjs.com/package/sanitize-filename>, upon which this
15 #' function is based.
16 #' @export
17 #' @examples
18 #' # potentially unsafe string
19 #' str <- "~/.\u0001ssh/authorized_keys"
20 #' path_sanitize(str)
21 #'
22 #' path_sanitize("..")
23 path_sanitize <- function(filename, replacement = "") {
24 illegal <- "[/\\?<>\\:*|\":]"
25 control <- "[[:cntrl:]]"
26 reserved <- "^[.]+$"
27 windows_reserved <- "^(con|prn|aux|nul|com[0-9]|lpt[0-9])([.].*)?$"
28 windows_trailing <- "[. ]+$"
29
30 filename <- gsub(illegal, replacement, filename)
31 filename <- gsub(control, replacement, filename)
32 filename <- gsub(reserved, replacement, filename)
33 filename <- gsub(windows_reserved, replacement, filename, ignore.case = TRUE)
34 filename <- gsub(windows_trailing, replacement, filename)
35
36 # TODO: this substr should really be unicode aware, so it doesn't chop a
37 # multibyte code point in half.
38 filename <- substr(filename, 1, 255)
39 if (replacement == "") {
40 return(filename)
41 }
42 path_sanitize(filename, "")
43 }