Advertisement
Guest User

Untitled

a guest
Aug 25th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. defmodule Ldif do
  2.  
  3. import NimbleParsec
  4.  
  5. name= ascii_string([?a..?z, ?A..?Z, ?0..?9], min: 1)
  6. eol = ascii_char([?\n]) |> ignore()
  7.  
  8. assigment =
  9. choice([
  10. string("::") |> replace(:base64),
  11. string(":") |> replace(:string)
  12. ])
  13.  
  14. rest_value = ignore(string(" ")) |> ascii_string([32..255], min: 1) |> concat(eol)
  15. value = ascii_string([32..255], min: 1) |> concat(eol) |> repeat(rest_value)
  16. attribute = name |> concat(assigment) |> ignore(string(" ")) |> concat(value) |> tag(:attribute)
  17. attributes = repeat(lookahead_not(eol) |> concat(attribute)) |> concat(eol)
  18.  
  19. defparsec :parseLdif,
  20. ignore(string("dn")) |> ignore(string(": ")) |> concat(value) |> tag(:dn)
  21. |> concat(attributes)
  22.  
  23. def ldif(src) do
  24. Enum.reverse(parse_ldif(src, []))
  25. end
  26.  
  27. defp parse_ldif("", xs), do: xs
  28. defp parse_ldif(src, xs) do
  29. with {:ok, result, rest, %{}, _, _} <- parseLdif(src) do
  30.  
  31. record = Enum.reduce(result, %{}, fn
  32. {:dn, [dn]}, m -> Map.put(m, "dn", dn)
  33. {:attribute, attr}, m -> process_attribute(m, attr)
  34. end)
  35. parse_ldif(rest, [record | xs])
  36. end
  37. end
  38.  
  39. defp update_map(map, key, value) do
  40. case Map.get(map, key, nil) do
  41. nil -> Map.put(map, key, value)
  42. xs when is_list(xs) -> Map.put(map, key, [value | xs])
  43. other -> Map.put(map, key, [value, other] )
  44. end
  45. end
  46. defp process_attribute(result, [key, :string, value]) do
  47. update_map(result, key, value)
  48. end
  49.  
  50. defp process_attribute(result, [key, :base64, value]) do
  51. update_map(result, key, Base.decode64!(value) )
  52. end
  53.  
  54. defp process_attribute(result, [key | [:base64 | xs]]) do
  55. update_map(result, key, Base.decode64!(Enum.join(xs, "")))
  56. end
  57.  
  58. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement