123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172openCoreopenPolyletextra_path=ref["/bin";"/usr/bin";"/usr/local/bin"]letget_path?(use_extra_path=true)()=letenv_path=Sys.getenv"PATH"|>Option.map~f:(String.split~on:':')|>Option.value~default:[]|>List.filter~f:((<>)"")inletpath=ifuse_extra_paththenenv_path@!extra_pathelseenv_pathinList.stable_deduppathletis_executablepath=tryletstat=Unix.statpathinstat.Unix.st_kind=Unix.S_REG(* Is file *)&&(stat.Unix.st_permland0o111>0)(* Is executable*)with|Unix.Unix_error((ENOENT|ENOTDIR),_,_)->false(* File not found *)letpath_lookup?use_extra_pathbin=letrecloop=function|[]->None|h::t->letfile=h^/binintryifis_executablefilethenSomefileelseraiseExitwith(Unix.Unix_error_)|Exit->looptinloop(get_path?use_extra_path())letwhich?use_extra_pathbin=ifnot(String.containsbin'/')thenpath_lookup?use_extra_pathbinelsebeginifnot(is_executablebin)thenNoneelseSomebinendletpath_expand?use_extra_pathprog=ifnot(String.containsprog'/')thenmatchpath_lookup?use_extra_pathprogwith|None->failwithf"executable %s not found in $PATH (%s)"prog(String.concat~sep:":"(get_path()))()|Somev->velseifFilename.is_relativeprogthenSys.getcwd()^/progelseprog(* "real" switches between real and effective uids. sudo sets both real and
effective uids, so this will not work, though you should be able to use
$SUDO_UID *)letwhoami?(real=false)()=letuid=ifrealthenUnix.getuid()elseUnix.geteuid()inmatchUnix.Passwd.getbyuiduidwith|Someuser->user.Unix.Passwd.name|None->failwith"unable to determine username"