Source file shell_internal.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
open Core
open Poly
module Unix = Core_unix
let = ref [ "/bin"; "/usr/bin"; "/usr/local/bin" ]
let get_path ?( = true) () =
let env_path =
Sys.getenv "PATH"
|> Option.map ~f:(String.split ~on:':')
|> Option.value ~default:[]
|> List.filter ~f:(( <> ) "")
in
let path = if use_extra_path then env_path @ !extra_path else env_path in
List.stable_dedup ~compare:String.compare path
;;
let is_executable path =
try
let stat = Unix.stat path in
stat.Unix.st_kind = Unix.S_REG && stat.Unix.st_perm land 0o111 > 0
with
| Unix.Unix_error ((ENOENT | ENOTDIR), _, _) -> false
;;
let path_lookup ? bin =
let rec loop = function
| [] -> None
| h :: t ->
let file = h ^/ bin in
(try if is_executable file then Some file else raise Exit with
| Unix.Unix_error _ | Exit -> loop t)
in
loop (get_path ?use_extra_path ())
;;
let which ? bin =
if not (String.contains bin '/')
then path_lookup ?use_extra_path bin
else if not (is_executable bin)
then None
else Some bin
;;
let path_expand ? prog =
if not (String.contains prog '/')
then (
match path_lookup ?use_extra_path prog with
| None ->
failwithf
"executable %s not found in $PATH (%s)"
prog
(String.concat ~sep:":" (get_path ()))
()
| Some v -> v)
else if Filename.is_relative prog
then Sys_unix.getcwd () ^/ prog
else prog
;;
let whoami ?(real = false) () =
let uid = if real then Unix.getuid () else Unix.geteuid () in
match Unix.Passwd.getbyuid uid with
| Some user -> user.Unix.Passwd.name
| None -> failwith "unable to determine username"
;;