Skip to content

Commit

Permalink
format: add styler
Browse files Browse the repository at this point in the history
  • Loading branch information
cschmatzler committed Sep 4, 2023
1 parent 4ae5f6b commit 80ced66
Show file tree
Hide file tree
Showing 23 changed files with 508 additions and 152 deletions.
26 changes: 13 additions & 13 deletions .credo.exs
Original file line number Diff line number Diff line change
Expand Up @@ -14,39 +14,30 @@
enabled: [
{Credo.Check.Consistency.ExceptionNames, []},
{Credo.Check.Consistency.LineEndings, []},
{Credo.Check.Consistency.ParameterPatternMatching, []},
{Credo.Check.Consistency.SpaceAroundOperators, []},
{Credo.Check.Consistency.SpaceInParentheses, []},
{Credo.Check.Consistency.TabsOrSpaces, []},
{Credo.Check.Design.TagFIXME, []},
{Credo.Check.Design.TagTODO, [exit_status: 2]},
{Credo.Check.Readability.AliasOrder, []},
{Credo.Check.Readability.FunctionNames, []},
{Credo.Check.Readability.LargeNumbers, []},
{Credo.Check.Readability.ModuleAttributeNames, []},
{Credo.Check.Readability.ModuleDoc, []},
{Credo.Check.Readability.ModuleNames, []},
{Credo.Check.Readability.ParenthesesInCondition, []},
{Credo.Check.Readability.PipeIntoAnonymousFunctions, []},
{Credo.Check.Readability.PredicateFunctionNames, []},
{Credo.Check.Readability.PreferImplicitTry, []},
{Credo.Check.Readability.RedundantBlankLines, []},
{Credo.Check.Readability.Semicolons, []},
{Credo.Check.Readability.SpaceAfterCommas, []},
{Credo.Check.Readability.StringSigils, []},
{Credo.Check.Readability.TrailingBlankLine, []},
{Credo.Check.Readability.TrailingWhiteSpace, []},
{Credo.Check.Readability.UnnecessaryAliasExpansion, []},
{Credo.Check.Readability.VariableNames, []},
{Credo.Check.Readability.WithSingleClause, []},
{Credo.Check.Refactor.Apply, []},
{Credo.Check.Refactor.CondStatements, []},
{Credo.Check.Refactor.CyclomaticComplexity, []},
{Credo.Check.Refactor.FilterCount, []},
{Credo.Check.Refactor.FilterFilter, []},
{Credo.Check.Refactor.FunctionArity, []},
{Credo.Check.Refactor.LongQuoteBlocks, []},
{Credo.Check.Refactor.MapJoin, []},
{Credo.Check.Refactor.MatchInCondition, []},
{Credo.Check.Refactor.NegatedConditionsInUnless, []},
{Credo.Check.Refactor.NegatedConditionsWithElse, []},
Expand Down Expand Up @@ -77,17 +68,13 @@
{Credo.Check.Warning.UnusedTupleOperation, []},
{Credo.Check.Warning.WrongTestFileExtension, []},
# ---
{Credo.Check.Consistency.MultiAliasImportRequireUse, []},
{Credo.Check.Design.DuplicatedCode, []},
{Credo.Check.Design.SkipTestWithoutComment, []},
{Credo.Check.Readability.AliasAs, []},
{Credo.Check.Readability.ImplTrue, []},
{Credo.Check.Readability.MultiAlias, []},
{Credo.Check.Readability.NestedFunctionCalls, []},
{Credo.Check.Readability.OneArityFunctionInPipe, []},
{Credo.Check.Readability.SeparateAliasRequire, []},
{Credo.Check.Readability.SingleFunctionToBlockPipe, []},
{Credo.Check.Readability.StrictModuleLayout, []},
{Credo.Check.Readability.WithCustomTaggedTuple, []},
{Credo.Check.Refactor.DoubleBooleanNegation, []},
{Credo.Check.Refactor.FilterReject, []},
Expand All @@ -102,16 +89,29 @@
{Credo.Check.Warning.MixEnv, []},
],
disabled: [
{Credo.Check.Consistency.MultiAliasImportRequireUse, []},
{Credo.Check.Consistency.ParameterPatternMatching, []},
{Credo.Check.Consistency.UnusedVariableNames, []},
{Credo.Check.Design.AliasUsage, []},
{Credo.Check.Readability.AliasOrder, []},
{Credo.Check.Readability.BlockPipe, []},
{Credo.Check.Readability.LargeNumbers, []},
{Credo.Check.Readability.MaxLineLength, [priority: :low, max_length: 120]},
{Credo.Check.Readability.ModuleDoc, []},
{Credo.Check.Readability.MultiAlias, []},
{Credo.Check.Readability.OneArityFunctionInPipe, []},
{Credo.Check.Readability.OnePipePerLine, []},
{Credo.Check.Readability.ParenthesesOnZeroArityDefs, []},
{Credo.Check.Readability.PipeIntoAnonymousFunctions, []},
{Credo.Check.Readability.PreferImplicitTry, []},
{Credo.Check.Readability.SinglePipe, []},
{Credo.Check.Readability.Specs, []},
{Credo.Check.Readability.StrictModuleLayout, []},
{Credo.Check.Readability.UnnecessaryAliasExpansion, []},
{Credo.Check.Refactor.ABCSize, []},
{Credo.Check.Refactor.AppendSingleItem, []},
{Credo.Check.Refactor.FilterCount, []},
{Credo.Check.Refactor.MapJoin, []},
{Credo.Check.Refactor.ModuleDependencies, []},
{Credo.Check.Refactor.PipeChainStart, []},
{Credo.Check.Warning.LazyLogging, []},
Expand Down
4 changes: 2 additions & 2 deletions .formatter.exs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"],
line_length: 160,
locals_without_parens: [plug: 1, plug: 2, adapter: 1, adapter: 2]
plugins: [Styler],
line_length: 88
]
24 changes: 17 additions & 7 deletions lib/idiom.ex
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ defmodule Idiom do
|> Enum.fetch!(1)

import Idiom.Interpolation

alias Idiom.Cache
alias Idiom.Locales
alias Idiom.Plural

require Logger

@doc false
Expand Down Expand Up @@ -66,7 +68,8 @@ defmodule Idiom do
run_t(locale, namespace, key_or_keys, bindings, opts)
end

defp run_t(locale, namespace, key_or_keys, _binding, _opts) when is_nil(locale) or is_nil(namespace) do
defp run_t(locale, namespace, key_or_keys, _binding, _opts)
when is_nil(locale) or is_nil(namespace) do
Logger.warning("""
Idiom: Called `t/3` without a locale or namespace set. You can configure a default locale and namespace by adding
Expand All @@ -82,7 +85,9 @@ defmodule Idiom do
end

defp run_t(locale, namespace, key_or_keys, bindings, opts) do
fallback = Keyword.get(opts, :fallback) || Application.get_env(:idiom, :default_fallback)
fallback =
Keyword.get(opts, :fallback) || Application.get_env(:idiom, :default_fallback)

count = Keyword.get(opts, :count)
bindings = Map.put_new(bindings, :count, count)

Expand All @@ -94,15 +99,20 @@ defmodule Idiom do
lookup_keys =
Enum.reduce(locale_resolve_hierarchy, [], fn locale, acc ->
acc ++
(List.wrap(key_or_keys)
(key_or_keys
|> List.wrap()
|> Enum.flat_map(fn key ->
[{locale, namespace, key}, {locale, namespace, "#{key}_#{Plural.get_suffix(locale, count)}"}]
[
{locale, namespace, key},
{locale, namespace, "#{key}_#{Plural.get_suffix(locale, count)}"}
]
end))
end)

cache_table_name = Keyword.get(opts, :cache_table_name, Cache.cache_table_name())

Enum.find_value(lookup_keys, fallback_message(key_or_keys), fn {locale, namespace, key} ->
lookup_keys
|> Enum.find_value(fallback_message(key_or_keys), fn {locale, namespace, key} ->
Cache.get_translation(locale, namespace, key, cache_table_name)
end)
|> interpolate(bindings)
Expand All @@ -119,7 +129,7 @@ defmodule Idiom do
```
"""
@spec get_locale() :: String.t()
def get_locale() do
def get_locale do
Process.get(:idiom_locale) || Application.get_env(:idiom, :default_locale)
end

Expand Down Expand Up @@ -151,7 +161,7 @@ defmodule Idiom do
```
"""
@spec get_namespace() :: String.t()
def get_namespace() do
def get_namespace do
Process.get(:idiom_namespace) || Application.get_env(:idiom, :default_namespace)
end

Expand Down
47 changes: 36 additions & 11 deletions lib/idiom/backend/phrase.ex
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ defmodule Idiom.Backend.Phrase do
"""

use GenServer

alias Idiom.Cache

require Logger

@opts_schema [
Expand Down Expand Up @@ -89,13 +91,19 @@ defmodule Idiom.Backend.Phrase do
end

@impl GenServer
def handle_info(:fetch_data, %{current_version: current_version, last_update: last_update, opts: opts} = state) do
def handle_info(
:fetch_data,
%{current_version: current_version, last_update: last_update, opts: opts} =
state
) do
current_version = fetch_data(current_version, last_update, opts)

Keyword.get(opts, :fetch_interval)
opts
|> Keyword.get(:fetch_interval)
|> schedule_refresh()

{:noreply, %{state | current_version: current_version, last_update: last_update_now()}}
{:noreply,
%{state | current_version: current_version, last_update: last_update_now()}}
end

defp schedule_refresh(interval) do
Expand All @@ -105,12 +113,19 @@ defmodule Idiom.Backend.Phrase do
defp fetch_data(current_version, last_update, opts) do
locales = Keyword.get(opts, :locales)

Enum.map(locales, &fetch_locale(&1, current_version, last_update, opts))
locales
|> Enum.map(&fetch_locale(&1, current_version, last_update, opts))
|> Enum.min()
end

defp fetch_locale(locale, current_version, last_update, opts) do
%{datacenter: datacenter, distribution_id: distribution_id, distribution_secret: distribution_secret, namespace: namespace, app_version: app_version} =
%{
datacenter: datacenter,
distribution_id: distribution_id,
distribution_secret: distribution_secret,
namespace: namespace,
app_version: app_version
} =
Map.new(opts)

params = [
Expand All @@ -120,14 +135,22 @@ defmodule Idiom.Backend.Phrase do
last_update: last_update
]

case Req.new(url: "#{distribution_id}/#{distribution_secret}/#{locale}/i18next_4", base_url: base_url(datacenter), params: params)
|> Req.Request.append_response_steps(add_version_to_response: &add_version_to_response/1)
case [
url: "#{distribution_id}/#{distribution_secret}/#{locale}/i18next_4",
base_url: base_url(datacenter),
params: params
]
|> Req.new()
|> Req.Request.append_response_steps(
add_version_to_response: &add_version_to_response/1
)
|> Req.get() do
{:ok, %Req.Response{status: 304}} ->
current_version

{:ok, %Req.Response{body: body} = response} ->
Map.new([{locale, %{namespace => body}}])
[{locale, %{namespace => body}}]
|> Map.new()
|> Cache.insert_keys()

Req.Response.get_private(response, :version)
Expand All @@ -140,7 +163,7 @@ defmodule Idiom.Backend.Phrase do
defp maybe_add_app_version_to_opts(opts, nil), do: opts

defp maybe_add_app_version_to_opts(opts, otp_app) do
app_version = Application.spec(otp_app, :vsn) |> to_string()
app_version = otp_app |> Application.spec(:vsn) |> to_string()

Keyword.put(opts, :app_version, app_version)
end
Expand All @@ -159,7 +182,7 @@ defmodule Idiom.Backend.Phrase do
{request, Req.Response.put_private(response, :version, version)}
end

defp last_update_now(), do: DateTime.utc_now() |> DateTime.to_unix()
defp last_update_now, do: DateTime.to_unix(DateTime.utc_now())

defp base_url(datacenter) do
case datacenter do
Expand All @@ -170,7 +193,9 @@ defmodule Idiom.Backend.Phrase do
"https://ota.eu.phrase.com"

_ ->
Logger.error("#{datacenter} is not a valid Phrase datacenter. Falling back to `eu`.")
Logger.error(
"#{datacenter} is not a valid Phrase datacenter. Falling back to `eu`."
)

"https://ota.eu.phrase.com"
end
Expand Down
16 changes: 12 additions & 4 deletions lib/idiom/cache.ex
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,16 @@ defmodule Idiom.Cache do
```
"""
@spec init(map(), atom()) :: :ok
def init(initial_state \\ %{}, table_name \\ @cache_table_name) when is_map(initial_state) do
:ets.new(table_name, [:set, :public, :named_table, read_concurrency: true, decentralized_counters: true])
def init(initial_state \\ %{}, table_name \\ @cache_table_name)
when is_map(initial_state) do
:ets.new(table_name, [
:set,
:public,
:named_table,
read_concurrency: true,
decentralized_counters: true
])

insert_keys(initial_state, table_name)
end

Expand Down Expand Up @@ -87,9 +95,9 @@ defmodule Idiom.Cache do
end

defp map_to_cache_data(value, keys) when is_binary(value) do
locale = Enum.at(keys, 0) |> Locales.format_locale()
locale = keys |> Enum.at(0) |> Locales.format_locale()
namespace = Enum.at(keys, 1)
key = Enum.slice(keys, 2..-1) |> Enum.join(".")
key = keys |> Enum.slice(2..-1) |> Enum.join(".")

[{{locale, namespace, key}, value}]
end
Expand Down
6 changes: 4 additions & 2 deletions lib/idiom/interpolation.ex
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,14 @@ defmodule Idiom.Interpolation do
end

defp interpolate([], parts, _bindings) do
Enum.reverse(parts)
parts
|> Enum.reverse()
|> Enum.join("")
end

defp parse(message) when is_binary(message) do
parse(message, "", [])
message
|> parse("", [])
|> Enum.reject(fn part -> is_binary(part) and String.equivalent?(part, "") end)
|> Enum.reverse()
end
Expand Down
10 changes: 6 additions & 4 deletions lib/idiom/local.ex
Original file line number Diff line number Diff line change
Expand Up @@ -59,19 +59,21 @@ defmodule Idiom.Local do
Application.get_env(:idiom, :data_dir) ||
"priv/idiom"

Path.join(data_dir, "*/*.json")
data_dir
|> Path.join("*/*.json")
|> Path.wildcard()
|> Enum.map(&parse_file/1)
|> Enum.reject(&is_nil/1)
|> Enum.reduce(%{}, fn keys, acc -> Map.merge(acc, keys, fn _k, v1, v2 -> Map.merge(v1, v2) end) end)
|> Enum.reduce(%{}, fn keys, acc ->
Map.merge(acc, keys, fn _k, v1, v2 -> Map.merge(v1, v2) end)
end)
end

defp parse_file(path) do
with {:ok, contents} <- File.read(path),
{:ok, map} <- Jason.decode(contents),
{locale, domain} <- extract_locale_and_domain(path) do
[{locale, Map.new([{domain, map}])}]
|> Map.new()
Map.new([{locale, Map.new([{domain, map}])}])
else
{:error, _error} ->
Logger.warning("Could not parse file #{path}")
Expand Down
2 changes: 1 addition & 1 deletion lib/idiom/locales.ex
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ defmodule Idiom.Locales do
|> String.split("-")
|> case do
parts when length(parts) <= 2 -> nil
parts -> Enum.take(parts, 2) |> Enum.join("-")
parts -> parts |> Enum.take(2) |> Enum.join("-")
end
end

Expand Down
Loading

0 comments on commit 80ced66

Please sign in to comment.