Skip to content

Instantly share code, notes, and snippets.

@dx3mod
Last active September 3, 2024 14:39
Show Gist options
  • Save dx3mod/6eec9dfe6df8eefbb8de5c8a36e5b4d9 to your computer and use it in GitHub Desktop.
Save dx3mod/6eec9dfe6df8eefbb8de5c8a36e5b4d9 to your computer and use it in GitHub Desktop.
Простой парсер /etc/passwd файла с помошью парсеров-комбинаторов
(* Простой парсер /etc/passwd файла с помошью парсеров-комбинаторов.
utop # Passwd.user_of_string "dx3mod:x:1000:1000:Михаил:/home/dx3mod:/usr/bin/fish";;
- : Passwd.user =
{Passwd.name = "dx3mod"; hash = Passwd.Hide; uid = 1000; gid = 1000;
description = "Михаил"; home = "/home/dx3mod"; shell = "/usr/bin/fish"}
utop # let passwd_contents = In_channel.(with_open_text "/etc/passwd" input_all);;
utop # Passwd.of_string passwd_contents;;
- : Passwd.user list =
[ ... ]
*)
type user = {
name : string;
hash : hash;
uid : int;
gid : int;
description : string;
home : string;
shell : string;
}
and hash = Hidden | Hash of string
module P = struct
open Angstrom
let id =
take_while1 (function '0' .. '9' -> true | _ -> false) >>| int_of_string
let user =
let field p = p <* char ':' in
let text = take_while (( <> ) ':') <|> return "" in
let+ name = field text
and+ hash = field text >>| function "x" -> Hidden | hash -> Hash hash
and+ uid = field id
and+ gid = field id
and+ description = field text
and+ home = field text
and+ shell = take_while (( <> ) '\n')
and+ _ = option () end_of_line in
{ name; hash; uid; gid; description; home; shell }
let file = many user
end
let user_of_string s =
Angstrom.(parse_string ~consume:Consume.All P.user s) |> Result.get_ok
let of_string s =
Angstrom.(parse_string ~consume:Consume.All P.file s) |> Result.get_ok
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment