Created
August 16, 2021 22:18
-
-
Save greggirwin/17509acc596a0a77b630fa660ac7537a to your computer and use it in GitHub Desktop.
safe-filename.red
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; This was developed for Windows only, as far as specific names | |
; the OS uses. For cross-platform use we need to add lists of | |
; reserved names, and maybe more complex rule checks. It also | |
; takes a "lowest common denomitator" approach, in that it doesn't | |
; express illegal chars by OS, the idea being that a good goal is | |
; to create portable filenames. | |
safe-filename: function [ | |
"Changes invalid characters to underscores, limits length; reserved OS names return none." | |
file [any-string!] "Unqualified filenames." | |
/local mark | |
][ | |
if any [empty? file #"." = first file #"." = last file] [ | |
;throw make error! join [script invalid-arg] file | |
return none | |
] | |
; The following are illegal in Windows: | |
illegal-windows: [ | |
%CON %PRN %AUX %NUL | |
%COM1 %COM2 %COM3 %COM4 %COM5 %COM6 %COM7 %COM8 %COM9 | |
%LPT1 %LPT2 %LPT3 %LPT4 %LPT5 %LPT6 %LPT7 %LPT8 %LPT9 | |
] | |
if find illegal-windows to file! file [ | |
;throw make error! join [script invalid-arg] file | |
return none | |
] | |
; The following are used internally by NTFS | |
illegal-NTFS: [ | |
%$Mft %$MftMirr %$LogFile %$Volume %$AttrDef %$Bitmap %$Boot %$BadClus | |
%$Secure %$Upcase %$Extend %$Quota %$ObjId %$Reparse | |
] | |
if find illegal-NTFS to file! file [ | |
;throw make error! join [script invalid-arg] file | |
return none | |
] | |
bad-char: union charset [#"^(0)" - #"^(1F)"] charset {<>:"/\|?*} | |
; " commented single quote to reset syntax highlighting. | |
file: copy file | |
parse file [any [mark: bad-char (change mark #"_") | skip]] | |
head clear at file 255 | |
] | |
; A few tests | |
[ | |
foreach file compose [ | |
%CON %con %LPT9 %lpt9 | |
%$Mft %$MFT | |
(to file! {^(0)^(1F)<>:^"/\|?*}) | |
][ | |
print [mold file tab mold safe-filename file] | |
] | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment