1 defmodule Pleroma.Docs.Generator do
2 @callback process(keyword()) :: {:ok, String.t()}
4 @spec process(module(), keyword()) :: {:ok, String.t()}
5 def process(implementation, descriptions) do
6 implementation.process(descriptions)
9 @spec list_modules_in_dir(String.t(), String.t()) :: [module()]
10 def list_modules_in_dir(dir, start) do
11 with {:ok, files} <- File.ls(dir) do
13 |> Enum.filter(&String.ends_with?(&1, ".ex"))
14 |> Enum.map(fn filename ->
15 module = filename |> String.trim_trailing(".ex") |> Macro.camelize()
16 String.to_atom(start <> module)
23 - atoms to strings with leading `:`
24 - module names to strings, without leading `Elixir.`
25 - add humanized labels to `keys` if label is not defined, e.g. `:instance` -> `Instance`
27 @spec convert_to_strings([map()]) :: [map()]
28 def convert_to_strings(descriptions) do
29 Enum.map(descriptions, &format_entity(&1))
32 defp format_entity(entity) do
35 |> Map.put(:group, atom_to_string(entity[:group]))
39 defp format_key(%{key: key} = entity) do
41 |> Map.put(:key, atom_to_string(key))
42 |> Map.put(:label, entity[:label] || humanize(key))
45 defp format_key(%{group: group} = entity) do
46 Map.put(entity, :label, entity[:label] || humanize(group))
49 defp format_key(entity), do: entity
51 defp format_children(%{children: children} = entity) do
52 Map.put(entity, :children, Enum.map(children, &format_child(&1)))
55 defp format_children(entity), do: entity
57 defp format_child(%{suggestions: suggestions} = entity) do
59 |> Map.put(:suggestions, format_suggestions(suggestions))
65 defp format_child(entity) do
72 defp format_group(%{group: group} = entity) do
73 Map.put(entity, :group, format_suggestion(group))
76 defp format_group(entity), do: entity
78 defp atom_to_string(entity) when is_binary(entity), do: entity
80 defp atom_to_string(entity) when is_atom(entity), do: inspect(entity)
82 defp humanize(entity) do
83 string = inspect(entity)
85 if String.starts_with?(string, ":"),
86 do: Phoenix.Naming.humanize(entity),
90 defp format_suggestions([]), do: []
92 defp format_suggestions([suggestion | tail]) do
93 [format_suggestion(suggestion) | format_suggestions(tail)]
96 defp format_suggestion(entity) when is_atom(entity) do
97 atom_to_string(entity)
100 defp format_suggestion([head | tail] = entity) when is_list(entity) do
101 [format_suggestion(head) | format_suggestions(tail)]
104 defp format_suggestion(entity) when is_tuple(entity) do
105 format_suggestions(Tuple.to_list(entity)) |> List.to_tuple()
108 defp format_suggestion(entity), do: entity
111 defimpl Jason.Encoder, for: Tuple do
112 def encode(tuple, opts), do: Jason.Encode.list(Tuple.to_list(tuple), opts)
115 defimpl Jason.Encoder, for: [Regex, Function] do
116 def encode(term, opts), do: Jason.Encode.string(inspect(term), opts)
119 defimpl String.Chars, for: Regex do
120 def to_string(term), do: inspect(term)