Skip to content
This repository has been archived by the owner on Jun 30, 2021. It is now read-only.

Commit

Permalink
Run and enforces mix format (#159)
Browse files Browse the repository at this point in the history
* Add `mix format` config
* Run `mix format` on entire repo
* Fix credo error for triple quotes instead of sigils
* Upgrade credo to latest version and update credo config
* Update Jenkinsfile to do format check
  • Loading branch information
unnawut authored Apr 24, 2018
1 parent 7e89da9 commit f95ce2f
Show file tree
Hide file tree
Showing 300 changed files with 8,099 additions and 6,221 deletions.
40 changes: 27 additions & 13 deletions .credo.exs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@
#
# You can give explicit globs or simply directories.
# In the latter case `**/*.{ex,exs}` will be used.
#
included: ["lib/", "src/", "web/", "apps/"],
#
included: ["lib/", "src/", "test/", "web/", "apps/"],
excluded: [~r"/_build/", ~r"/deps/"]
},
#
Expand All @@ -48,33 +48,40 @@
# {Credo.Check.Design.DuplicatedCode, false}
#
checks: [
#
## Consistency Checks
#
{Credo.Check.Consistency.ExceptionNames},
{Credo.Check.Consistency.LineEndings},
{Credo.Check.Consistency.ParameterPatternMatching},
{Credo.Check.Consistency.SpaceAroundOperators},
{Credo.Check.Consistency.SpaceInParentheses},
{Credo.Check.Consistency.TabsOrSpaces},

# For some checks, like AliasUsage, you can only customize the priority
#
## Design Checks
#
# You can customize the priority of any check
# Priority values are: `low, normal, high, higher`
#
{Credo.Check.Design.AliasUsage, priority: :low},

# For others you can set parameters

# For some checks, you can also set other parameters
#
# If you don't want the `setup` and `test` macro calls in ExUnit tests
# or the `schema` macro in Ecto schemas to trigger DuplicatedCode, just
# set the `excluded_macros` parameter to `[:schema, :setup, :test]`.
#
{Credo.Check.Design.DuplicatedCode, excluded_macros: []},

# You can also customize the exit_status of each check.
# If you don't want TODO comments to cause `mix credo` to fail, just
# set this value to 0 (zero).
#
{Credo.Check.Design.TagTODO, exit_status: 2},
{Credo.Check.Design.TagFIXME},

#
## Readability Checks
#
{Credo.Check.Readability.FunctionNames},
{Credo.Check.Readability.LargeNumbers},
{Credo.Check.Readability.MaxLineLength, priority: :low, max_length: 100},
Expand All @@ -93,6 +100,9 @@
{Credo.Check.Readability.Semicolons},
{Credo.Check.Readability.SpaceAfterCommas},

#
## Refactoring Opportunities
#
{Credo.Check.Refactor.DoubleBooleanNegation},
{Credo.Check.Refactor.CondStatements},
{Credo.Check.Refactor.CyclomaticComplexity},
Expand All @@ -102,10 +112,15 @@
{Credo.Check.Refactor.NegatedConditionsInUnless},
{Credo.Check.Refactor.NegatedConditionsWithElse},
{Credo.Check.Refactor.Nesting},
{Credo.Check.Refactor.PipeChainStart},
{Credo.Check.Refactor.PipeChainStart,
excluded_argument_types: [:atom, :binary, :fn, :keyword], excluded_functions: []},
{Credo.Check.Refactor.UnlessWithElse},

#
## Warnings
#
{Credo.Check.Warning.BoolOperationOnSameValues},
{Credo.Check.Warning.ExpensiveEmptyEnumCheck},
{Credo.Check.Warning.IExPry},
{Credo.Check.Warning.IoInspect},
{Credo.Check.Warning.LazyLogging},
Expand All @@ -121,6 +136,7 @@
{Credo.Check.Warning.UnusedTupleOperation},
{Credo.Check.Warning.RaiseInsideRescue},

#
# Controversial and experimental checks (opt-in, just remove `, false`)
#
{Credo.Check.Refactor.ABCSize, false},
Expand All @@ -129,14 +145,12 @@
{Credo.Check.Warning.MapGetUnsafePass, false},
{Credo.Check.Consistency.MultiAliasImportRequireUse, false},

#
# Deprecated checks (these will be deleted after a grace period)
#
{Credo.Check.Readability.Specs, false},
{Credo.Check.Warning.NameRedeclarationByAssignment, false},
{Credo.Check.Warning.NameRedeclarationByCase, false},
{Credo.Check.Warning.NameRedeclarationByDef, false},
{Credo.Check.Warning.NameRedeclarationByFn, false},
{Credo.Check.Readability.Specs, false}

#
# Custom checks can be created using `mix credo.gen.check`.
#
]
Expand Down
7 changes: 7 additions & 0 deletions .formatter.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[
inputs: [
"mix.exs",
"{config,lib,test}/**/*.{ex,exs}",
"apps/*/{config,lib,test}/**/*.{ex,exs}"
]
]
2 changes: 1 addition & 1 deletion Jenkinsfile
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ podTemplate(
s6-env HOME=/tmp/ewallet \
s6-env MIX_ENV=test \
cd /app \
mix do credo, ecto.create, ecto.migrate, test \
mix do format --check-formatted, credo, ecto.create, ecto.migrate, test \
" \
""".stripIndent()
)
Expand Down
60 changes: 37 additions & 23 deletions apps/admin_api/config/config.exs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ config :admin_api,
enable_client_auth: System.get_env("ENABLE_ADMIN_CLIENT_AUTH") == "true"

# Configs for the endpoint
config :admin_api,
AdminAPI.Endpoint,
config :admin_api, AdminAPI.Endpoint,
secret_key_base: System.get_env("SECRET_KEY_BASE"),
error_handler: AdminAPI.V1.ErrorHandler,
render_errors: [
Expand All @@ -24,12 +23,10 @@ config :admin_api,
]

# Config for Phoenix's generators
config :admin_api, :generators,
context_app: false
config :admin_api, :generators, context_app: false

# Configs for Bamboo emailing library
config :admin_api, AdminAPI.Mailer,
adapter: Bamboo.LocalAdapter
config :admin_api, AdminAPI.Mailer, adapter: Bamboo.LocalAdapter

# Config for CORSPlug
#
Expand All @@ -41,18 +38,35 @@ config :admin_api, AdminAPI.Mailer,
# Because of this the anonymous function is invoked right away through
# `(fn -> ... end).()` in order for :origin to be assigned at compile time.
config :cors_plug,
max_age: System.get_env("CORS_MAX_AGE") || 600, # Lowest common value of all browsers
headers: ["Authorization", "Content-Type", "Accept", "Origin",
"User-Agent", "DNT", "Cache-Control", "X-Mx-ReqToken",
"Keep-Alive", "X-Requested-With", "If-Modified-Since",
"X-CSRF-Token", "OMGAdmin-Account-ID"],
# Lowest common value of all browsers
max_age: System.get_env("CORS_MAX_AGE") || 600,
headers: [
"Authorization",
"Content-Type",
"Accept",
"Origin",
"User-Agent",
"DNT",
"Cache-Control",
"X-Mx-ReqToken",
"Keep-Alive",
"X-Requested-With",
"If-Modified-Since",
"X-CSRF-Token",
"OMGAdmin-Account-ID"
],
methods: ["POST"],
origin: (fn ->
case System.get_env("CORS_ORIGINS") do
nil -> [] # Disallow all origins if CORS_ORIGINS is not set
origins -> origins |> String.trim() |> String.split(~r{\s*,\s*})
end
end).()
origin:
(fn ->
case System.get_env("CORS_ORIGINS") do
# Disallow all origins if CORS_ORIGINS is not set
nil ->
[]

origins ->
origins |> String.trim() |> String.split(~r{\s*,\s*})
end
end).()

# Two configs need to be added to have a new EWallet Admin version:
#
Expand All @@ -76,16 +90,16 @@ config :mime, :types, %{
# Configs for Sentry exception reporting
config :sentry,
dsn: System.get_env("SENTRY_DSN"),
environment_name: Mix.env,
environment_name: Mix.env(),
enable_source_code_context: true,
root_source_code_path: File.cwd!,
root_source_code_path: File.cwd!(),
tags: %{
env: Mix.env,
application: Mix.Project.config[:app]
env: Mix.env(),
application: Mix.Project.config()[:app]
},
server_name: elem(:inet.gethostname, 1),
server_name: elem(:inet.gethostname(), 1),
included_environments: [:prod]

# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env}.exs"
import_config "#{Mix.env()}.exs"
6 changes: 2 additions & 4 deletions apps/admin_api/config/test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ config :admin_api, AdminAPI.Endpoint,
secret_key_base: "G1DLBdjjJSoSiQRa5Gf8YrWUx5yrX+JFmZx+UBk829W1+e0oJ9TYrW/GkIgrAdfm",
server: false

config :admin_api,
enable_client_auth: "true"
config :admin_api, enable_client_auth: "true"

# Configs for Bamboo emailing library
config :admin_api, AdminAPI.Mailer,
adapter: Bamboo.TestAdapter
config :admin_api, AdminAPI.Mailer, adapter: Bamboo.TestAdapter
5 changes: 3 additions & 2 deletions apps/admin_api/lib/admin_api.ex
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,9 @@ defmodule AdminAPI do

def view do
quote do
use Phoenix.View, root: "lib/admin_api/templates",
namespace: AdminAPI
use Phoenix.View,
root: "lib/admin_api/templates",
namespace: AdminAPI

# Import convenience functions from controllers
import Phoenix.Controller, only: [get_flash: 2, view_module: 1]
Expand Down
2 changes: 1 addition & 1 deletion apps/admin_api/lib/admin_api/application.ex
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ defmodule AdminAPI.Application do
# Define workers and child supervisors to be supervised
children = [
# Start the endpoint when the application starts
supervisor(AdminAPI.Endpoint, []),
supervisor(AdminAPI.Endpoint, [])
]

# See https://hexdocs.pm/elixir/Supervisor.html
Expand Down
3 changes: 2 additions & 1 deletion apps/admin_api/lib/admin_api/emails/forget_password_email.ex
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ defmodule AdminAPI.ForgetPasswordEmail do

def create(request, redirect_url) do
sender = Application.get_env(:admin_api, :sender_email)
link =

link =
redirect_url
|> String.replace("{email}", request.user.email)
|> String.replace("{token}", request.token)
Expand Down
26 changes: 15 additions & 11 deletions apps/admin_api/lib/admin_api/endpoint.ex
Original file line number Diff line number Diff line change
@@ -1,30 +1,34 @@
defmodule AdminAPI.Endpoint do
use Phoenix.Endpoint, otp_app: :admin_api

plug Plug.Static,
plug(
Plug.Static,
at: "/public/",
from: Path.join(File.cwd!, "../../public/"),
from: Path.join(File.cwd!(), "../../public/"),
only: ~w(uploads)
)

plug AdminAPI.AssetNotFoundPlug
plug(AdminAPI.AssetNotFoundPlug)

# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
plug Phoenix.CodeReloader
plug(Phoenix.CodeReloader)
end

plug Plug.RequestId
plug Plug.Logger
plug(Plug.RequestId)
plug(Plug.Logger)

plug Plug.Parsers,
plug(
Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Poison
)

plug Plug.MethodOverride
plug Plug.Head
plug CORSPlug
plug(Plug.MethodOverride)
plug(Plug.Head)
plug(CORSPlug)

plug AdminAPI.Router
plug(AdminAPI.Router)
end
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ defmodule AdminAPI.StatusController do
use AdminAPI, :controller

def status(conn, _attrs) do
json conn, %{success: true}
json(conn, %{success: true})
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@ defmodule AdminAPI.AssetNotFoundPlug do
|> send_resp(404, "")
|> halt()
end

defp check_asset(conn, _), do: conn
end
3 changes: 2 additions & 1 deletion apps/admin_api/lib/admin_api/invites/invite_email.ex
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ defmodule AdminAPI.InviteEmail do

def create(invite, redirect_url) do
sender = Application.get_env(:admin_api, :sender_email)
link =

link =
redirect_url
|> String.replace("{email}", invite.user.email)
|> String.replace("{token}", invite.token)
Expand Down
15 changes: 9 additions & 6 deletions apps/admin_api/lib/admin_api/invites/inviter.ex
Original file line number Diff line number Diff line change
Expand Up @@ -26,25 +26,28 @@ defmodule AdminAPI.Inviter do
end

defp validate_email(email) do
if EmailValidator.valid?(email), do: email, else: throw :invalid_email
if EmailValidator.valid?(email), do: email, else: throw(:invalid_email)
end

defp get_or_create_user(email) do
case User.get_by_email(email) do
%User{} = user ->
check_active(user)

nil ->
{:ok, user} = User.insert(%{
email: email,
password: Crypto.generate_key(32)
})
{:ok, user} =
User.insert(%{
email: email,
password: Crypto.generate_key(32)
})

user
end
end

defp check_active(user) do
case User.get_status(user) do
:active -> throw :user_already_active
:active -> throw(:user_already_active)
_ -> user
end
end
Expand Down
4 changes: 2 additions & 2 deletions apps/admin_api/lib/admin_api/router.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ defmodule AdminAPI.Router do
alias AdminAPI.{StatusController, VersionedRouter}

scope "/admin/api" do
get "/", StatusController, :status
forward "/", VersionedRouter
get("/", StatusController, :status)
forward("/", VersionedRouter)
end
end
Loading

0 comments on commit f95ce2f

Please sign in to comment.