ファイルパスの先頭のチルダを展開する。
たまーにプログラムを書こうとすると、こういうことで引っ掛かるのだった。
参考:http://pleac.sourceforge.net/pleac_ocaml/fileaccess.html
こちらはStrモジュール無しで書いてみる。
let expand_path path =
let homedir () =
try Unix.getenv "HOME" with Not_found ->
(Unix.getpwuid (Unix.getuid ())).Unix.pw_dir
in
let userdir u = (Unix.getpwnam u).Unix.pw_dir in
let rec find_slash_or_term p len s =
if p >= len then len
else if s.[p] = '/' then p
else find_slash_or_term (p + 1) len s
in
let find_slash_or_term s = find_slash_or_term 0 (String.length s) s in
let lchop s n = String.sub s n (String.length s - n) in
if path = "" || path.[0] <> '~' then path
else if path = "~" then homedir ()
else if path.[1] = '/' then (homedir ()) ^ (lchop path 1)
else
let p = find_slash_or_term path in
let u = String.sub path 1 (p - 1) in
(userdir u) ^ (lchop path p)