package shell

  1. Overview
  2. Docs

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
71
72
73
open Core
open Poly
module Unix = Core_unix

let extra_path = ref ["/bin";"/usr/bin";"/usr/local/bin"]

let get_path ?(use_extra_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
  String.Set.stable_dedup_list path

let is_executable path =
  try
    let stat = Unix.stat path in
    stat.Unix.st_kind = Unix.S_REG (* Is file *)
    && (stat.Unix.st_perm land 0o111 > 0) (* Is executable*)
  with
  | Unix.Unix_error ((ENOENT | ENOTDIR), _, _) -> false (* File not found *)

let path_lookup ?use_extra_path 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 ?use_extra_path bin =
  if not (String.contains bin '/') then
    path_lookup ?use_extra_path bin
  else begin
    if not (is_executable bin) then
      None
    else
      Some bin
  end

let path_expand ?use_extra_path 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

(* "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 *)
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"
OCaml

Innovation. Community. Security.