{"commit":"9bb7fd4a733a053b048af19fe7896e304220e1b4","subject":"Remove mention to dict in ExUnit.Callbacks example","message":"Remove mention to dict in ExUnit.Callbacks example\n","repos":"pedrosnk\/elixir,kelvinst\/elixir,ggcampinho\/elixir,gfvcastro\/elixir,beedub\/elixir,kimshrier\/elixir,pedrosnk\/elixir,antipax\/elixir,kimshrier\/elixir,ggcampinho\/elixir,beedub\/elixir,elixir-lang\/elixir,lexmag\/elixir,gfvcastro\/elixir,lexmag\/elixir,joshprice\/elixir,kelvinst\/elixir,antipax\/elixir,michalmuskala\/elixir","old_file":"lib\/ex_unit\/lib\/ex_unit\/callbacks.ex","new_file":"lib\/ex_unit\/lib\/ex_unit\/callbacks.ex","new_contents":"defmodule ExUnit.Callbacks do\n @moduledoc ~S\"\"\"\n Defines ExUnit Callbacks.\n\n This module defines both `setup_all` and `setup` callbacks, as well as\n the `on_exit` facility.\n\n The setup callbacks are defined via macros and each one can optionally\n receive a map with metadata, usually referred to as `context`. The\n callback may optionally put extra data into `context` to be used in\n the tests.\n\n The `setup_all` callbacks are invoked once to setup the test case before any\n test is run and all `setup` callbacks are run before each test. No callback\n runs if the test case has no tests or all tests were filtered out.\n\n `on_exit` callbacks are registered on demand, usually to undo an action\n performed by a setup callback. `on_exit` may also take a reference,\n allowing callback to be overridden in the future. A registered `on_exit`\n callback always runs, while failures in `setup` and `setup_all` will stop\n all remaining setup callbacks from executing.\n\n Finally, `setup_all` callbacks run in the test case process, while all\n `setup` callbacks run in the same process as the test itself. `on_exit`\n callbacks always run in a separate process than the test case or the\n test itself. Since the test process exits with reason `:shutdown`, most\n of times `on_exit\/1` can be avoided as processes are going to clean\n up on their own.\n\n ## Context\n\n If you return `{:ok, keywords}` from `setup_all`, the keyword\n will be merged into the current context and be available in all\n subsequent `setup_all`, `setup` and the test itself.\n\n Similarly, returning `{:ok, keywords}` from `setup`, the keyword\n returned will be merged into the current context and be available\n in all subsequent `setup` and the `test` itself.\n\n Returning `:ok` leaves the context unchanged in both cases.\n\n Returning anything else from `setup_all` will force all tests to fail,\n while a bad response from `setup` causes the current test to fail.\n\n ## Examples\n\n defmodule AssertionTest do\n use ExUnit.Case, async: true\n\n # \"setup_all\" is called once to setup the case before any test is run\n setup_all do\n IO.puts \"Starting AssertionTest\"\n\n # No metadata\n :ok\n end\n\n # \"setup\" is called before each test is run\n setup do\n IO.puts \"This is a setup callback\"\n\n on_exit fn ->\n IO.puts \"This is invoked once the test is done\"\n end\n\n # Returns extra metadata to be merged into context\n {:ok, hello: \"world\"}\n end\n\n # Same as \"setup\", but receives the context\n # for the current test\n setup context do\n IO.puts \"Setting up: #{context[:test]}\"\n :ok\n end\n\n test \"always pass\" do\n assert true\n end\n\n test \"another one\", context do\n assert context[:hello] == \"world\"\n end\n end\n\n \"\"\"\n\n @doc false\n defmacro __using__(_) do\n quote do\n @ex_unit_setup []\n @ex_unit_setup_all []\n\n @before_compile unquote(__MODULE__)\n import unquote(__MODULE__)\n end\n end\n\n @doc false\n defmacro __before_compile__(env) do\n [compile_callbacks(env, :setup),\n compile_callbacks(env, :setup_all)]\n end\n\n @doc \"\"\"\n Defines a callback to be run before each test in a case.\n \"\"\"\n defmacro setup(var \\\\ quote(do: _), block) do\n quote bind_quoted: [var: escape(var), block: escape(block)] do\n name = :\"__ex_unit_setup_#{length(@ex_unit_setup)}\"\n defp unquote(name)(unquote(var)), unquote(block)\n @ex_unit_setup [name|@ex_unit_setup]\n end\n end\n\n @doc \"\"\"\n Defines a callback to be run before all tests in a case.\n \"\"\"\n defmacro setup_all(var \\\\ quote(do: _), block) do\n quote bind_quoted: [var: escape(var), block: escape(block)] do\n name = :\"__ex_unit_setup_all_#{length(@ex_unit_setup_all)}\"\n defp unquote(name)(unquote(var)), unquote(block)\n @ex_unit_setup_all [name|@ex_unit_setup_all]\n end\n end\n\n @doc \"\"\"\n Defines a callback that runs on the test (or test case) exit.\n\n An `on_exit` callback is a function that receives no arguments and\n runs in a separate process than the caller.\n\n `on_exit\/2` is usually called from `setup` and `setup_all` callbacks,\n often to undo the action performed during `setup`. However, `on_exit`\n may also be called dynamically, where a reference can be used to\n guarantee the callback will be invoked only once.\n \"\"\"\n @spec on_exit(term, (() -> term)) :: :ok\n def on_exit(ref \\\\ make_ref, callback) do\n case ExUnit.OnExitHandler.add(self, ref, callback) do\n :ok -> :ok\n :error ->\n raise ArgumentError, \"on_exit\/1 callback can only be invoked from the test process\"\n end\n end\n\n ## Helpers\n\n @reserved ~w(case test line file registered)a\n\n @doc false\n def __merge__(_mod, context, :ok) do\n {:ok, context}\n end\n\n def __merge__(mod, context, {:ok, data}) do\n {:ok, context_merge(mod, context, data)}\n end\n\n def __merge__(mod, _, data) do\n raise_merge_failed!(mod, data)\n end\n\n defp context_merge(mod, _context, %{__struct__: _} = data) do\n raise_merge_failed!(mod, data)\n end\n\n defp context_merge(mod, context, %{} = data) do\n Map.merge(context, data, fn\n k, v1, v2 when k in @reserved ->\n if v1 == v2, do: v1, else: raise_merge_reserved!(mod, k, v1)\n _, _, v ->\n v\n end)\n end\n\n defp context_merge(mod, context, data) when is_list(data) do\n context_merge(mod, context, Map.new(data))\n end\n\n defp context_merge(mod, _context, data) do\n raise_merge_failed!(mod, data)\n end\n\n defp raise_merge_failed!(mod, data) do\n raise \"expected ExUnit callback in #{inspect mod} to return :ok \" <>\n \"or {:ok, keywords | map}, got #{inspect data} instead\"\n end\n\n defp raise_merge_reserved!(mod, key, value) do\n raise \"ExUnit callback in #{inspect mod} is trying to set \" <>\n \"reserved field #{inspect key} to #{inspect value}\"\n end\n\n defp escape(contents) do\n Macro.escape(contents, unquote: true)\n end\n\n defp compile_callbacks(env, kind) do\n callbacks = Module.get_attribute(env.module, :\"ex_unit_#{kind}\") |> Enum.reverse\n\n acc =\n case callbacks do\n [] ->\n quote do: {:ok, context}\n [h|t] ->\n Enum.reduce t, compile_merge(h), fn(callback, acc) ->\n quote do\n {:ok, context} = unquote(acc)\n unquote(compile_merge(callback))\n end\n end\n end\n\n quote do\n def __ex_unit__(unquote(kind), context), do: unquote(acc)\n end\n end\n\n defp compile_merge(callback) do\n quote do\n unquote(__MODULE__).__merge__(__MODULE__, context, unquote(callback)(context))\n end\n end\nend\n","old_contents":"defmodule ExUnit.Callbacks do\n @moduledoc ~S\"\"\"\n Defines ExUnit Callbacks.\n\n This module defines both `setup_all` and `setup` callbacks, as well as\n the `on_exit` facility.\n\n The setup callbacks are defined via macros and each one can optionally\n receive a map with metadata, usually referred to as `context`. The\n callback may optionally put extra data into `context` to be used in\n the tests.\n\n The `setup_all` callbacks are invoked once to setup the test case before any\n test is run and all `setup` callbacks are run before each test. No callback\n runs if the test case has no tests or all tests were filtered out.\n\n `on_exit` callbacks are registered on demand, usually to undo an action\n performed by a setup callback. `on_exit` may also take a reference,\n allowing callback to be overridden in the future. A registered `on_exit`\n callback always runs, while failures in `setup` and `setup_all` will stop\n all remaining setup callbacks from executing.\n\n Finally, `setup_all` callbacks run in the test case process, while all\n `setup` callbacks run in the same process as the test itself. `on_exit`\n callbacks always run in a separate process than the test case or the\n test itself. Since the test process exits with reason `:shutdown`, most\n of times `on_exit\/1` can be avoided as processes are going to clean\n up on their own.\n\n ## Context\n\n If you return `{:ok, keywords}` from `setup_all`, the keyword\n will be merged into the current context and be available in all\n subsequent `setup_all`, `setup` and the test itself.\n\n Similarly, returning `{:ok, keywords}` from `setup`, the keyword\n returned will be merged into the current context and be available\n in all subsequent `setup` and the `test` itself.\n\n Returning `:ok` leaves the context unchanged in both cases.\n\n Returning anything else from `setup_all` will force all tests to fail,\n while a bad response from `setup` causes the current test to fail.\n\n ## Examples\n\n defmodule AssertionTest do\n use ExUnit.Case, async: true\n\n # \"setup_all\" is called once to setup the case before any test is run\n setup_all do\n IO.puts \"Starting AssertionTest\"\n\n # No metadata\n :ok\n end\n\n # \"setup\" is called before each test is run\n setup do\n IO.puts \"This is a setup callback\"\n\n on_exit fn ->\n IO.puts \"This is invoked once the test is done\"\n end\n\n # Returns extra metadata, it must be a dict\n {:ok, hello: \"world\"}\n end\n\n # Same as \"setup\", but receives the context\n # for the current test\n setup context do\n IO.puts \"Setting up: #{context[:test]}\"\n :ok\n end\n\n test \"always pass\" do\n assert true\n end\n\n test \"another one\", context do\n assert context[:hello] == \"world\"\n end\n end\n\n \"\"\"\n\n @doc false\n defmacro __using__(_) do\n quote do\n @ex_unit_setup []\n @ex_unit_setup_all []\n\n @before_compile unquote(__MODULE__)\n import unquote(__MODULE__)\n end\n end\n\n @doc false\n defmacro __before_compile__(env) do\n [compile_callbacks(env, :setup),\n compile_callbacks(env, :setup_all)]\n end\n\n @doc \"\"\"\n Defines a callback to be run before each test in a case.\n \"\"\"\n defmacro setup(var \\\\ quote(do: _), block) do\n quote bind_quoted: [var: escape(var), block: escape(block)] do\n name = :\"__ex_unit_setup_#{length(@ex_unit_setup)}\"\n defp unquote(name)(unquote(var)), unquote(block)\n @ex_unit_setup [name|@ex_unit_setup]\n end\n end\n\n @doc \"\"\"\n Defines a callback to be run before all tests in a case.\n \"\"\"\n defmacro setup_all(var \\\\ quote(do: _), block) do\n quote bind_quoted: [var: escape(var), block: escape(block)] do\n name = :\"__ex_unit_setup_all_#{length(@ex_unit_setup_all)}\"\n defp unquote(name)(unquote(var)), unquote(block)\n @ex_unit_setup_all [name|@ex_unit_setup_all]\n end\n end\n\n @doc \"\"\"\n Defines a callback that runs on the test (or test case) exit.\n\n An `on_exit` callback is a function that receives no arguments and\n runs in a separate process than the caller.\n\n `on_exit\/2` is usually called from `setup` and `setup_all` callbacks,\n often to undo the action performed during `setup`. However, `on_exit`\n may also be called dynamically, where a reference can be used to\n guarantee the callback will be invoked only once.\n \"\"\"\n @spec on_exit(term, (() -> term)) :: :ok\n def on_exit(ref \\\\ make_ref, callback) do\n case ExUnit.OnExitHandler.add(self, ref, callback) do\n :ok -> :ok\n :error ->\n raise ArgumentError, \"on_exit\/1 callback can only be invoked from the test process\"\n end\n end\n\n ## Helpers\n\n @reserved ~w(case test line file registered)a\n\n @doc false\n def __merge__(_mod, context, :ok) do\n {:ok, context}\n end\n\n def __merge__(mod, context, {:ok, data}) do\n {:ok, context_merge(mod, context, data)}\n end\n\n def __merge__(mod, _, data) do\n raise_merge_failed!(mod, data)\n end\n\n defp context_merge(mod, _context, %{__struct__: _} = data) do\n raise_merge_failed!(mod, data)\n end\n\n defp context_merge(mod, context, %{} = data) do\n Map.merge(context, data, fn\n k, v1, v2 when k in @reserved ->\n if v1 == v2, do: v1, else: raise_merge_reserved!(mod, k, v1)\n _, _, v ->\n v\n end)\n end\n\n defp context_merge(mod, context, data) when is_list(data) do\n context_merge(mod, context, Map.new(data))\n end\n\n defp context_merge(mod, _context, data) do\n raise_merge_failed!(mod, data)\n end\n\n defp raise_merge_failed!(mod, data) do\n raise \"expected ExUnit callback in #{inspect mod} to return :ok \" <>\n \"or {:ok, keywords | map}, got #{inspect data} instead\"\n end\n\n defp raise_merge_reserved!(mod, key, value) do\n raise \"ExUnit callback in #{inspect mod} is trying to set \" <>\n \"reserved field #{inspect key} to #{inspect value}\"\n end\n\n defp escape(contents) do\n Macro.escape(contents, unquote: true)\n end\n\n defp compile_callbacks(env, kind) do\n callbacks = Module.get_attribute(env.module, :\"ex_unit_#{kind}\") |> Enum.reverse\n\n acc =\n case callbacks do\n [] ->\n quote do: {:ok, context}\n [h|t] ->\n Enum.reduce t, compile_merge(h), fn(callback, acc) ->\n quote do\n {:ok, context} = unquote(acc)\n unquote(compile_merge(callback))\n end\n end\n end\n\n quote do\n def __ex_unit__(unquote(kind), context), do: unquote(acc)\n end\n end\n\n defp compile_merge(callback) do\n quote do\n unquote(__MODULE__).__merge__(__MODULE__, context, unquote(callback)(context))\n end\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"e180879f5ca28a8ca5fb774134129d77b89375b9","subject":"Match errors from gen_smtp_client","message":"Match errors from gen_smtp_client\n","repos":"kamilc\/mailman","old_file":"lib\/mailman\/external_smtp_adapter.ex","new_file":"lib\/mailman\/external_smtp_adapter.ex","new_contents":"defmodule Mailman.ExternalSmtpAdapter do\n @moduledoc \"Adapter for sending email via external SMTP server\"\n\n @doc \"Delivers an email based on specified config\"\n def deliver(config, email, message) do\n relay_config = [\n relay: config.relay,\n username: config.username,\n password: config.password,\n port: config.port,\n ssl: config.ssl,\n tls: config.tls,\n auth: config.auth\n ]\n ret = :gen_smtp_client.send_blocking {\n email.from,\n email.to,\n message\n }, relay_config\n case ret do\n { :error, _, _ } -> ret\n _ -> { :ok, message }\n end\n end\n\nend\n\n","old_contents":"defmodule Mailman.ExternalSmtpAdapter do\n @moduledoc \"Adapter for sending email via external SMTP server\"\n\n @doc \"Delivers an email based on specified config\"\n def deliver(config, email, message) do\n relay_config = [\n relay: config.relay,\n username: config.username,\n password: config.password,\n port: config.port,\n ssl: config.ssl,\n tls: config.tls,\n auth: config.auth\n ]\n ret = :gen_smtp_client.send_blocking {\n email.from,\n email.to,\n message\n }, relay_config\n case ret do\n { :error, _ } -> ret\n _ -> { :ok, message }\n end\n end\n\nend\n\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"0499de6bdce0bb9a1b1712de302e3cdebfa60326","subject":"version push","message":"version push\n","repos":"ckruse\/wwwtech.de,ckruse\/wwwtech.de,ckruse\/wwwtech.de","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Wwwtech.Mixfile do\n use Mix.Project\n\n def project do\n [\n app: :wwwtech,\n version: \"0.2.7\",\n elixir: \"~> 1.5\",\n elixirc_paths: elixirc_paths(Mix.env()),\n compilers: [:phoenix, :gettext] ++ Mix.compilers(),\n build_embedded: Mix.env() == :prod,\n start_permanent: Mix.env() == :prod,\n aliases: aliases(),\n deps: deps()\n ]\n end\n\n # Configuration for the OTP application.\n #\n # Type `mix help compile.app` for more information.\n def application do\n [\n mod: {Wwwtech, []},\n applications: [\n :phoenix,\n :phoenix_html,\n :cowboy,\n :logger,\n :gettext,\n :phoenix_ecto,\n :postgrex,\n :tzdata,\n :httpotion,\n :bamboo,\n :bamboo_smtp,\n :cmark,\n :comeonin,\n :bcrypt_elixir,\n :elixir_exif,\n :floki,\n :microformats2,\n :mogrify,\n :phoenix_pubsub,\n :timex,\n :timex_ecto,\n :webmentions,\n :edeliver\n ]\n ]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\"]\n\n # Specifies your project dependencies.\n #\n # Type `mix help deps` for examples and options.\n defp deps do\n [\n {:phoenix, \"~> 1.3.0\"},\n {:phoenix_pubsub, \"~> 1.0\"},\n {:phoenix_ecto, \"~> 3.2\"},\n {:postgrex, \">= 0.0.0\"},\n {:phoenix_html, \"~> 2.6\"},\n {:phoenix_live_reload, \"~> 1.0\", only: :dev},\n {:gettext, \"~> 0.11\"},\n {:comeonin, \"~> 4.0\"},\n {:bcrypt_elixir, \"~> 1.0\"},\n {:cmark, \"~> 0.5\"},\n {:mogrify, github: \"route\/mogrify\"},\n {:timex, \"~> 3.1\"},\n {:timex_ecto, github: \"bitwalker\/timex_ecto\", tag: \"3.2.0\"},\n {:httpotion, \"~> 3.0\"},\n {:floki, \"~> 0.15\"},\n {:plug_cowboy, \"~> 1.0\"},\n {:elixir_exif, github: \"sschneider1207\/ElixirExif\"},\n {:microformats2, \"~> 0.1.0\"},\n {:webmentions, \"~> 0.3\"},\n {:bamboo, \"~> 0.8\"},\n {:bamboo_smtp, \"~> 1.3\"},\n {:distillery, \"~> 1.4\"},\n {:edeliver, \"~> 1.4\"},\n {:ex_machina, \"~> 2.1\", only: :test}\n ]\n end\n\n # Aliases are shortcut or tasks specific to the current project.\n # For example, to create, migrate and run the seeds file at once:\n #\n # $ mix ecto.setup\n #\n # See the documentation for `Mix` for more info on aliases.\n defp aliases do\n [\n \"ecto.setup\": [\"ecto.create\", \"ecto.migrate\", \"run priv\/repo\/seeds.exs\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"]\n ]\n end\nend\n","old_contents":"defmodule Wwwtech.Mixfile do\n use Mix.Project\n\n def project do\n [\n app: :wwwtech,\n version: \"0.2.6\",\n elixir: \"~> 1.5\",\n elixirc_paths: elixirc_paths(Mix.env()),\n compilers: [:phoenix, :gettext] ++ Mix.compilers(),\n build_embedded: Mix.env() == :prod,\n start_permanent: Mix.env() == :prod,\n aliases: aliases(),\n deps: deps()\n ]\n end\n\n # Configuration for the OTP application.\n #\n # Type `mix help compile.app` for more information.\n def application do\n [\n mod: {Wwwtech, []},\n applications: [\n :phoenix,\n :phoenix_html,\n :cowboy,\n :logger,\n :gettext,\n :phoenix_ecto,\n :postgrex,\n :tzdata,\n :httpotion,\n :bamboo,\n :bamboo_smtp,\n :cmark,\n :comeonin,\n :bcrypt_elixir,\n :elixir_exif,\n :floki,\n :microformats2,\n :mogrify,\n :phoenix_pubsub,\n :timex,\n :timex_ecto,\n :webmentions,\n :edeliver\n ]\n ]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\"]\n\n # Specifies your project dependencies.\n #\n # Type `mix help deps` for examples and options.\n defp deps do\n [\n {:phoenix, \"~> 1.3.0\"},\n {:phoenix_pubsub, \"~> 1.0\"},\n {:phoenix_ecto, \"~> 3.2\"},\n {:postgrex, \">= 0.0.0\"},\n {:phoenix_html, \"~> 2.6\"},\n {:phoenix_live_reload, \"~> 1.0\", only: :dev},\n {:gettext, \"~> 0.11\"},\n {:comeonin, \"~> 4.0\"},\n {:bcrypt_elixir, \"~> 1.0\"},\n {:cmark, \"~> 0.5\"},\n {:mogrify, github: \"route\/mogrify\"},\n {:timex, \"~> 3.1\"},\n {:timex_ecto, github: \"bitwalker\/timex_ecto\", tag: \"3.2.0\"},\n {:httpotion, \"~> 3.0\"},\n {:floki, \"~> 0.15\"},\n {:plug_cowboy, \"~> 1.0\"},\n {:elixir_exif, github: \"sschneider1207\/ElixirExif\"},\n {:microformats2, \"~> 0.1.0\"},\n {:webmentions, \"~> 0.3\"},\n {:bamboo, \"~> 0.8\"},\n {:bamboo_smtp, \"~> 1.3\"},\n {:distillery, \"~> 1.4\"},\n {:edeliver, \"~> 1.4\"},\n {:ex_machina, \"~> 2.1\", only: :test}\n ]\n end\n\n # Aliases are shortcut or tasks specific to the current project.\n # For example, to create, migrate and run the seeds file at once:\n #\n # $ mix ecto.setup\n #\n # See the documentation for `Mix` for more info on aliases.\n defp aliases do\n [\n \"ecto.setup\": [\"ecto.create\", \"ecto.migrate\", \"run priv\/repo\/seeds.exs\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"]\n ]\n end\nend\n","returncode":0,"stderr":"","license":"agpl-3.0","lang":"Elixir"} {"commit":"5a8cf48387dd7c4a22651262bcf2ca6a6906ccd5","subject":"Bump version","message":"Bump version\n","repos":"walkr\/exns","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Exns.Mixfile do\n use Mix.Project\n\n def project do\n [app: :exns,\n version: \"0.3.0-beta\",\n elixir: \"~> 1.0\",\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n deps: deps,\n description: description,\n package: package]\n end\n\n # Configuration for the OTP application\n #\n # Type `mix help compile.app` for more information\n def application do\n [mod: {Exns, []},\n applications: [:logger, :enm, :msgpax, :poolboy]]\n end\n\n defp description do\n \"A library for writing clients to communicate with \" <>\n \"Python nanoservices via nanomsg.\"\n end\n\n defp package do\n [files: [\"lib\", \"mix.exs\", \"README.md\", \"LICENSE\"],\n contributors: [\"Tony Walker\"],\n licenses: [\"MIT\"],\n links: %{\"GitHub\" => \"https:\/\/github.com\/walkr\/exns\"}]\n end\n\n # Dependencies can be Hex packages:\n #\n # {:mydep, \"~> 0.3.0\"}\n #\n # Or git\/path repositories:\n #\n # {:mydep, git: \"https:\/\/github.com\/elixir-lang\/mydep.git\", tag: \"0.1.0\"}\n #\n # Type `mix help deps` for more examples and options\n\n defp deps do\n [{:enm, git: \"https:\/\/github.com\/walkr\/enm\"},\n {:poison, \"~> 1.5\"},\n {:msgpax, \"~> 0.8.1\"},\n {:uuid, \"~> 1.0.0\"},\n {:poolboy, \"~>1.5.1\"}]\n end\nend\n","old_contents":"defmodule Exns.Mixfile do\n use Mix.Project\n\n def project do\n [app: :exns,\n version: \"0.2.0-beta\",\n elixir: \"~> 1.0\",\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n deps: deps,\n description: description,\n package: package]\n end\n\n # Configuration for the OTP application\n #\n # Type `mix help compile.app` for more information\n def application do\n [mod: {Exns, []},\n applications: [:logger, :enm, :msgpax, :poolboy]]\n end\n\n defp description do\n \"A library for writing clients to communicate with \" <>\n \"Python nanoservices via nanomsg.\"\n end\n\n defp package do\n [files: [\"lib\", \"mix.exs\", \"README.md\", \"LICENSE\"],\n contributors: [\"Tony Walker\"],\n licenses: [\"MIT\"],\n links: %{\"GitHub\" => \"https:\/\/github.com\/walkr\/exns\"}]\n end\n\n # Dependencies can be Hex packages:\n #\n # {:mydep, \"~> 0.3.0\"}\n #\n # Or git\/path repositories:\n #\n # {:mydep, git: \"https:\/\/github.com\/elixir-lang\/mydep.git\", tag: \"0.1.0\"}\n #\n # Type `mix help deps` for more examples and options\n\n defp deps do\n [{:enm, git: \"https:\/\/github.com\/walkr\/enm\"},\n {:poison, \"~> 1.5\"},\n {:msgpax, \"~> 0.8.1\"},\n {:uuid, \"~> 1.0.0\"},\n {:poolboy, \"~>1.5.1\"}]\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"9dab351df1eac3f7d7c9613db80a3cae2d79eaf9","subject":"version bump","message":"version bump\n","repos":"rozap\/exsoda","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Exsoda.Mixfile do\n use Mix.Project\n\n def project do\n [app: :exsoda,\n version: \"1.2.11\",\n elixir: \"~> 1.3\",\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n deps: deps,\n package: package(),\n description: \"\"\"\n A Socrata Soda2 API wrapper\n \"\"\"\n ]\n end\n\n defp package do\n [\n licenses: [\"MIT\"],\n maintainers: [\"Chris Duranti\"],\n links: %{github: \"https:\/\/github.com\/rozap\/exsoda\"}\n ]\n end\n\n # Configuration for the OTP application\n #\n # Type `mix help compile.app` for more information\n def application do\n [applications: [:logger, :httpoison, :poison]]\n end\n\n # Dependencies can be Hex packages:\n #\n # {:mydep, \"~> 0.3.0\"}\n #\n # Or git\/path repositories:\n #\n # {:mydep, git: \"https:\/\/github.com\/elixir-lang\/mydep.git\", tag: \"0.1.0\"}\n #\n # Type `mix help deps` for more examples and options\n defp deps do\n [\n {:httpoison, \"~> 0.11.0\"},\n {:poison, \"~> 2.2.0\"},\n {:nimble_csv, \"~> 0.1.0\"},\n {:ex_doc, \">= 0.0.0\", only: :dev},\n {:uuid, \"~> 1.1\"}\n ]\n end\nend\n","old_contents":"defmodule Exsoda.Mixfile do\n use Mix.Project\n\n def project do\n [app: :exsoda,\n version: \"1.2.10\",\n elixir: \"~> 1.3\",\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n deps: deps,\n package: package(),\n description: \"\"\"\n A Socrata Soda2 API wrapper\n \"\"\"\n ]\n end\n\n defp package do\n [\n licenses: [\"MIT\"],\n maintainers: [\"Chris Duranti\"],\n links: %{github: \"https:\/\/github.com\/rozap\/exsoda\"}\n ]\n end\n\n # Configuration for the OTP application\n #\n # Type `mix help compile.app` for more information\n def application do\n [applications: [:logger, :httpoison, :poison]]\n end\n\n # Dependencies can be Hex packages:\n #\n # {:mydep, \"~> 0.3.0\"}\n #\n # Or git\/path repositories:\n #\n # {:mydep, git: \"https:\/\/github.com\/elixir-lang\/mydep.git\", tag: \"0.1.0\"}\n #\n # Type `mix help deps` for more examples and options\n defp deps do\n [\n {:httpoison, \"~> 0.11.0\"},\n {:poison, \"~> 2.2.0\"},\n {:nimble_csv, \"~> 0.1.0\"},\n {:ex_doc, \">= 0.0.0\", only: :dev},\n {:uuid, \"~> 1.1\"}\n ]\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"683d4fbdc5ebe730a1e6d68ba99f57f9c79f2d13","subject":"Bump version to 2.2.1 for release. (#30)","message":"Bump version to 2.2.1 for release. (#30)\n\n","repos":"JustMikey\/recaptcha,samueljseay\/recaptcha","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Recaptcha.Mixfile do\n use Mix.Project\n\n def project do\n [\n app: :recaptcha,\n version: \"2.2.1\",\n elixir: \"~> 1.2\",\n description: description(),\n deps: deps(),\n package: package(),\n\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n\n # Test coverage:\n test_coverage: [tool: ExCoveralls],\n preferred_cli_env: [\n \"coveralls\": :test,\n \"coveralls.detail\": :test,\n \"coveralls.post\": :test,\n \"coveralls.html\": :test,\n ],\n\n # Dialyzer:\n dialyzer: [\n plt_add_deps: :apps_direct,\n plt_add_apps: [:poison]\n ]\n ]\n end\n\n def application do\n [applications: [:logger, :httpoison, :eex]]\n end\n\n defp description do\n \"\"\"\n A simple reCaptcha package for Elixir applications, provides verification\n and templates for rendering forms with the reCaptcha widget\n \"\"\"\n end\n\n defp deps do\n [\n {:httpoison, \"~> 0.12.0\"},\n {:poison, \"~> 3.1.0 or ~> 2.2.0 or ~> 1.5.2\"},\n {:credo, \"~> 0.8.4\", only: [:dev, :test]},\n {:ex_doc, \">= 0.0.0\", only: :dev},\n {:dialyxir, \"~> 0.5\", only: [:dev]},\n {:excoveralls, \"~> 0.7.1\", only: :test},\n ]\n end\n\n defp package do\n [files: [\"lib\", \"mix.exs\", \"README.md\", \"LICENSE\"],\n maintainers: [\"Samuel Seay\", \"Nikita Sobolev\", \"Michael JustMikey\"],\n licenses: [\"MIT\"],\n links: %{\"GitHub\" => \"https:\/\/github.com\/samueljseay\/recaptcha\"}]\n end\nend\n","old_contents":"defmodule Recaptcha.Mixfile do\n use Mix.Project\n\n def project do\n [\n app: :recaptcha,\n version: \"2.1.1\",\n elixir: \"~> 1.2\",\n description: description(),\n deps: deps(),\n package: package(),\n\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n\n # Test coverage:\n test_coverage: [tool: ExCoveralls],\n preferred_cli_env: [\n \"coveralls\": :test,\n \"coveralls.detail\": :test,\n \"coveralls.post\": :test,\n \"coveralls.html\": :test,\n ],\n\n # Dialyzer:\n dialyzer: [\n plt_add_deps: :apps_direct,\n plt_add_apps: [:poison]\n ]\n ]\n end\n\n def application do\n [applications: [:logger, :httpoison, :eex]]\n end\n\n defp description do\n \"\"\"\n A simple reCaptcha package for Elixir applications, provides verification\n and templates for rendering forms with the reCaptcha widget\n \"\"\"\n end\n\n defp deps do\n [\n {:httpoison, \"~> 0.12.0\"},\n {:poison, \"~> 3.1.0 or ~> 2.2.0 or ~> 1.5.2\"},\n {:credo, \"~> 0.8.4\", only: [:dev, :test]},\n {:ex_doc, \">= 0.0.0\", only: :dev},\n {:dialyxir, \"~> 0.5\", only: [:dev]},\n {:excoveralls, \"~> 0.7.1\", only: :test},\n ]\n end\n\n defp package do\n [files: [\"lib\", \"mix.exs\", \"README.md\", \"LICENSE\"],\n maintainers: [\"Samuel Seay\", \"Nikita Sobolev\", \"Michael JustMikey\"],\n licenses: [\"MIT\"],\n links: %{\"GitHub\" => \"https:\/\/github.com\/samueljseay\/recaptcha\"}]\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"75ae647023cd4846c7e7c2ace84b973390496950","subject":"version 0.6.0","message":"version 0.6.0\n","repos":"ckruse\/wwwtech.de,ckruse\/wwwtech.de,ckruse\/wwwtech.de","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Wwwtech.MixProject do\n use Mix.Project\n\n def project do\n [\n app: :wwwtech,\n version: \"0.6.0\",\n elixir: \"~> 1.5\",\n elixirc_paths: elixirc_paths(Mix.env()),\n compilers: [:phoenix, :gettext] ++ Mix.compilers(),\n start_permanent: Mix.env() == :prod,\n aliases: aliases(),\n deps: deps()\n ]\n end\n\n # Configuration for the OTP application.\n #\n # Type `mix help compile.app` for more information.\n def application do\n [\n mod: {Wwwtech.Application, []},\n extra_applications: [:logger, :runtime_tools]\n ]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\"]\n\n # Specifies your project dependencies.\n #\n # Type `mix help deps` for examples and options.\n defp deps do\n [\n {:phoenix, \"~> 1.4.10\"},\n {:phoenix_pubsub, \"~> 1.1\"},\n {:phoenix_ecto, \"~> 4.0\"},\n {:ecto_sql, \"~> 3.1\"},\n {:postgrex, \">= 0.0.0\"},\n {:phoenix_html, \"~> 2.11\"},\n {:phoenix_live_reload, \"~> 1.2\", only: :dev},\n {:gettext, \"~> 0.11\"},\n {:jason, \"~> 1.0\"},\n {:plug_cowboy, \"~> 2.0\"},\n {:argon2_elixir, \"~> 2.0\"},\n {:timex, \"~> 3.5\"},\n {:earmark, \"~> 1.4.0\"},\n {:xml_builder, \"~> 2.1\"},\n {:exexif, \"~> 0.0.5\"},\n {:mogrify, \"~> 0.7.3\"},\n {:microformats2, \"~> 0.1\"},\n {:webmentions, \"~> 0.3\"},\n {:floki, \"~> 0.23\"},\n {:bamboo, \"~> 1.2\"},\n {:bamboo_smtp, \"~> 1.5\"},\n {:appsignal, \"~> 1.0\"},\n {:httpotion, \"~> 3.1.2\"}\n ]\n end\n\n # Aliases are shortcuts or tasks specific to the current project.\n # For example, to create, migrate and run the seeds file at once:\n #\n # $ mix ecto.setup\n #\n # See the documentation for `Mix` for more info on aliases.\n defp aliases do\n [\n \"ecto.setup\": [\"ecto.create\", \"ecto.migrate\", \"run priv\/repo\/seeds.exs\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"],\n test: [\"ecto.create --quiet\", \"ecto.migrate\", \"test\"],\n build: \"cmd .\/.build\/build\",\n deploy: \"cmd .\/.build\/deploy\"\n ]\n end\nend\n","old_contents":"defmodule Wwwtech.MixProject do\n use Mix.Project\n\n def project do\n [\n app: :wwwtech,\n version: \"0.5.7\",\n elixir: \"~> 1.5\",\n elixirc_paths: elixirc_paths(Mix.env()),\n compilers: [:phoenix, :gettext] ++ Mix.compilers(),\n start_permanent: Mix.env() == :prod,\n aliases: aliases(),\n deps: deps()\n ]\n end\n\n # Configuration for the OTP application.\n #\n # Type `mix help compile.app` for more information.\n def application do\n [\n mod: {Wwwtech.Application, []},\n extra_applications: [:logger, :runtime_tools]\n ]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\"]\n\n # Specifies your project dependencies.\n #\n # Type `mix help deps` for examples and options.\n defp deps do\n [\n {:phoenix, \"~> 1.4.10\"},\n {:phoenix_pubsub, \"~> 1.1\"},\n {:phoenix_ecto, \"~> 4.0\"},\n {:ecto_sql, \"~> 3.1\"},\n {:postgrex, \">= 0.0.0\"},\n {:phoenix_html, \"~> 2.11\"},\n {:phoenix_live_reload, \"~> 1.2\", only: :dev},\n {:gettext, \"~> 0.11\"},\n {:jason, \"~> 1.0\"},\n {:plug_cowboy, \"~> 2.0\"},\n {:argon2_elixir, \"~> 2.0\"},\n {:timex, \"~> 3.5\"},\n {:earmark, \"~> 1.4.0\"},\n {:xml_builder, \"~> 2.1\"},\n {:exexif, \"~> 0.0.5\"},\n {:mogrify, \"~> 0.7.3\"},\n {:microformats2, \"~> 0.1\"},\n {:webmentions, \"~> 0.3\"},\n {:floki, \"~> 0.23\"},\n {:bamboo, \"~> 1.2\"},\n {:bamboo_smtp, \"~> 1.5\"},\n {:appsignal, \"~> 1.0\"},\n {:httpotion, \"~> 3.1.2\"}\n ]\n end\n\n # Aliases are shortcuts or tasks specific to the current project.\n # For example, to create, migrate and run the seeds file at once:\n #\n # $ mix ecto.setup\n #\n # See the documentation for `Mix` for more info on aliases.\n defp aliases do\n [\n \"ecto.setup\": [\"ecto.create\", \"ecto.migrate\", \"run priv\/repo\/seeds.exs\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"],\n test: [\"ecto.create --quiet\", \"ecto.migrate\", \"test\"],\n build: \"cmd .\/.build\/build\",\n deploy: \"cmd .\/.build\/deploy\"\n ]\n end\nend\n","returncode":0,"stderr":"","license":"agpl-3.0","lang":"Elixir"} {"commit":"66207c4f6eaa7c95ee3dce206cf5502d1e44b1ba","subject":"Use local guides directory","message":"Use local guides directory\n\nThe guides have been moved from a mix dependency to inline. All file\nreferences have been updated to use the local guides directory.\n","repos":"bsmr-erlang\/phoenix,keathley\/phoenix,optikfluffel\/phoenix,0x00evil\/phoenix,stevedomin\/phoenix,keathley\/phoenix,michalmuskala\/phoenix,eksperimental\/phoenix,rafbgarcia\/phoenix,Gazler\/phoenix,dmarkow\/phoenix,nshafer\/phoenix,optikfluffel\/phoenix,mitchellhenke\/phoenix,Gazler\/phoenix,0x00evil\/phoenix,rafbgarcia\/phoenix,mitchellhenke\/phoenix,phoenixframework\/phoenix,trarbr\/phoenix,korobkov\/phoenix,pap\/phoenix,rafbgarcia\/phoenix,nshafer\/phoenix,0x00evil\/phoenix,gjaldon\/phoenix,gjaldon\/phoenix,Kosmas\/phoenix,evax\/phoenix,Joe-noh\/phoenix,dmarkow\/phoenix,mobileoverlord\/phoenix,michalmuskala\/phoenix,evax\/phoenix,Kosmas\/phoenix,phoenixframework\/phoenix,mobileoverlord\/phoenix,phoenixframework\/phoenix,optikfluffel\/phoenix,Joe-noh\/phoenix,mschae\/phoenix,eksperimental\/phoenix,mschae\/phoenix,korobkov\/phoenix,jwarwick\/phoenix,bsmr-erlang\/phoenix,trarbr\/phoenix,stevedomin\/phoenix,jwarwick\/phoenix,nshafer\/phoenix,pap\/phoenix","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Phoenix.Mixfile do\n use Mix.Project\n\n @version \"1.4.0-dev\"\n\n def project do\n [\n app: :phoenix,\n version: @version,\n elixir: \"~> 1.4\",\n deps: deps(),\n package: package(),\n preferred_cli_env: [docs: :docs],\n\n # Because we define protocols on the fly to test\n # Phoenix.Param, we need to disable consolidation\n # for the test environment for Elixir v1.2 onward.\n consolidate_protocols: Mix.env != :test,\n xref: [exclude: [Ecto.Type]],\n\n name: \"Phoenix\",\n docs: [\n source_ref: \"v#{@version}\",\n main: \"overview\",\n logo: \"logo.png\",\n extra_section: \"GUIDES\",\n assets: \"guides\/docs\/assets\",\n extras: extras()\n ],\n aliases: aliases(),\n source_url: \"https:\/\/github.com\/phoenixframework\/phoenix\",\n homepage_url: \"http:\/\/www.phoenixframework.org\",\n description: \"\"\"\n Productive. Reliable. Fast. A productive web framework that\n does not compromise speed and maintainability.\n \"\"\"\n ]\n end\n\n def application do\n [\n mod: {Phoenix, []},\n extra_applications: [:logger, :eex, :crypto],\n env: [\n stacktrace_depth: nil,\n template_engines: [],\n format_encoders: [],\n filter_parameters: [\"password\"],\n serve_endpoints: false,\n gzippable_exts: ~w(.js .css .txt .text .html .json .svg)\n ]\n ]\n end\n\n defp deps do\n [\n {:cowboy, \"~> 1.0\", optional: true},\n {:plug, \"~> 1.3.3 or ~> 1.4\"},\n {:phoenix_pubsub, \"~> 1.0\"},\n {:poison, \"~> 2.2 or ~> 3.0\"},\n {:gettext, \"~> 0.8\", only: :test},\n\n # Docs dependencies\n {:ex_doc, \"~> 0.16\", only: :docs},\n {:inch_ex, \"~> 0.2\", only: :docs},\n\n # Test dependencies\n {:phoenix_html, \"~> 2.10\", only: :test},\n {:websocket_client, git: \"https:\/\/github.com\/jeremyong\/websocket_client.git\", only: :test}\n ]\n end\n\n defp package do\n [\n maintainers: [\n \"Chris McCord\", \"Jos\u00e9 Valim\", \"Lance Halvorsen\", \"Gary Rennie\",\n \"Jason Stiebs\", \"Eric Meadows-J\u00f6nsson\", \"Sonny Scroggin\"\n ],\n licenses: [\"MIT\"],\n links: %{github: \"https:\/\/github.com\/phoenixframework\/phoenix\"},\n files: ~w(assets lib priv) ++\n ~w(brunch-config.js CHANGELOG.md LICENSE.md mix.exs package.json README.md)\n ]\n end\n\n defp extras do\n [\n \"introduction\/overview.md\": [group: \"Introduction\"],\n \"introduction\/installation.md\": [group: \"Introduction\"],\n \"introduction\/learning.md\": [group: \"Introduction\"],\n \"introduction\/community.md\": [group: \"Introduction\"],\n\n \"up_and_running.md\": [group: \"Guides\"],\n \"adding_pages.md\": [group: \"Guides\"],\n \"routing.md\": [group: \"Guides\"],\n \"plug.md\": [group: \"Guides\"],\n \"endpoint.md\": [group: \"Guides\"],\n \"controllers.md\": [group: \"Guides\"],\n \"views.md\": [group: \"Guides\"],\n \"templates.md\": [group: \"Guides\"],\n \"channels.md\": [group: \"Guides\"],\n \"ecto.md\": [group: \"Guides\"],\n \"contexts.md\": [group: \"Guides\"],\n \"phoenix_mix_tasks.md\": [group: \"Guides\"],\n \"errors.md\": [group: \"Guides\"],\n\n \"testing\/testing.md\": [group: \"Testing\"],\n \"testing\/testing_models.md\": [group: \"Testing\"],\n \"testing\/testing_controllers.md\": [group: \"Testing\"],\n \"testing\/testing_channels.md\": [group: \"Testing\"],\n\n \"deployment\/deployment.md\": [group: \"Deployment\"],\n \"deployment\/heroku.md\": [group: \"Deployment\"]\n ]\n |> Enum.map(fn {file, opts} -> {:\"guides\/docs\/#{file}\", opts} end)\n end\n\n defp aliases do\n [\n \"docs\": [\"docs\", &generate_js_docs\/1]\n ]\n end\n\n def generate_js_docs(_) do\n Mix.Task.run \"app.start\"\n System.cmd(\"npm\", [\"run\", \"docs\"])\n end\nend\n","old_contents":"defmodule Phoenix.Mixfile do\n use Mix.Project\n\n @version \"1.4.0-dev\"\n\n def project do\n [\n app: :phoenix,\n version: @version,\n elixir: \"~> 1.4\",\n deps: deps(),\n package: package(),\n preferred_cli_env: [docs: :docs],\n\n # Because we define protocols on the fly to test\n # Phoenix.Param, we need to disable consolidation\n # for the test environment for Elixir v1.2 onward.\n consolidate_protocols: Mix.env != :test,\n xref: [exclude: [Ecto.Type]],\n\n name: \"Phoenix\",\n docs: [\n source_ref: \"v#{@version}\",\n main: \"overview\",\n logo: \"logo.png\",\n extra_section: \"GUIDES\",\n assets: \"deps\/phoenix_guides\/docs\/assets\",\n extras: extras()\n ],\n aliases: aliases(),\n source_url: \"https:\/\/github.com\/phoenixframework\/phoenix\",\n homepage_url: \"http:\/\/www.phoenixframework.org\",\n description: \"\"\"\n Productive. Reliable. Fast. A productive web framework that\n does not compromise speed and maintainability.\n \"\"\"\n ]\n end\n\n def application do\n [\n mod: {Phoenix, []},\n extra_applications: [:logger, :eex, :crypto],\n env: [\n stacktrace_depth: nil,\n template_engines: [],\n format_encoders: [],\n filter_parameters: [\"password\"],\n serve_endpoints: false,\n gzippable_exts: ~w(.js .css .txt .text .html .json .svg)\n ]\n ]\n end\n\n defp deps do\n [\n {:cowboy, \"~> 1.0\", optional: true},\n {:plug, \"~> 1.3.3 or ~> 1.4\"},\n {:phoenix_pubsub, \"~> 1.0\"},\n {:poison, \"~> 2.2 or ~> 3.0\"},\n {:gettext, \"~> 0.8\", only: :test},\n\n # Docs dependencies\n {:ex_doc, \"~> 0.16\", only: :docs},\n {:inch_ex, \"~> 0.2\", only: :docs},\n {:phoenix_guides, git: \"https:\/\/github.com\/phoenixframework\/phoenix_guides.git\", compile: false, app: false, only: :docs},\n\n # Test dependencies\n {:phoenix_html, \"~> 2.10\", only: :test},\n {:websocket_client, git: \"https:\/\/github.com\/jeremyong\/websocket_client.git\", only: :test}\n ]\n end\n\n defp package do\n [\n maintainers: [\n \"Chris McCord\", \"Jos\u00e9 Valim\", \"Lance Halvorsen\", \"Gary Rennie\",\n \"Jason Stiebs\", \"Eric Meadows-J\u00f6nsson\", \"Sonny Scroggin\"\n ],\n licenses: [\"MIT\"],\n links: %{github: \"https:\/\/github.com\/phoenixframework\/phoenix\"},\n files: ~w(assets lib priv) ++\n ~w(brunch-config.js CHANGELOG.md LICENSE.md mix.exs package.json README.md)\n ]\n end\n\n defp extras do\n [\n \"introduction\/overview.md\": [group: \"Introduction\"],\n \"introduction\/installation.md\": [group: \"Introduction\"],\n \"introduction\/learning.md\": [group: \"Introduction\"],\n \"introduction\/community.md\": [group: \"Introduction\"],\n\n \"up_and_running.md\": [group: \"Guides\"],\n \"adding_pages.md\": [group: \"Guides\"],\n \"routing.md\": [group: \"Guides\"],\n \"plug.md\": [group: \"Guides\"],\n \"endpoint.md\": [group: \"Guides\"],\n \"controllers.md\": [group: \"Guides\"],\n \"views.md\": [group: \"Guides\"],\n \"templates.md\": [group: \"Guides\"],\n \"channels.md\": [group: \"Guides\"],\n \"ecto.md\": [group: \"Guides\"],\n \"contexts.md\": [group: \"Guides\"],\n\n \"testing\/testing.md\": [group: \"Testing\"],\n \"testing\/testing_models.md\": [group: \"Testing\"],\n \"testing\/testing_controllers.md\": [group: \"Testing\"],\n \"testing\/testing_channels.md\": [group: \"Testing\"],\n\n \"deployment\/deployment.md\": [group: \"Deployment\"],\n \"deployment\/heroku.md\": [group: \"Deployment\"],\n\n \"bonus_guides\/upgrading_phoenix.md\": [group: \"Bonus Guides\"],\n \"bonus_guides\/custom_primary_key.md\": [group: \"Bonus Guides\"],\n \"bonus_guides\/using_mysql.md\": [group: \"Bonus Guides\"],\n \"bonus_guides\/static_assets.md\": [group: \"Bonus Guides\"],\n \"bonus_guides\/mix_tasks.md\": [group: \"Bonus Guides\"],\n \"bonus_guides\/task_supervisor.md\": [group: \"Bonus Guides\"],\n \"bonus_guides\/file_uploads.md\": [group: \"Bonus Guides\"],\n \"bonus_guides\/sending_email_with_mailgun.md\": [group: \"Bonus Guides\"],\n \"bonus_guides\/sending_email_with_smtp.md\": [group: \"Bonus Guides\"],\n \"bonus_guides\/sessions.md\": [group: \"Bonus Guides\"],\n \"bonus_guides\/custom_errors.md\": [group: \"Bonus Guides\"],\n \"bonus_guides\/using_ssl.md\": [group: \"Bonus Guides\"],\n \"bonus_guides\/phoenix_behind_proxy.md\": [group: \"Bonus Guides\"],\n \"bonus_guides\/config.md\": [group: \"Bonus Guides\"],\n \"bonus_guides\/learning_elixir.md\": [group: \"Bonus Guides\"],\n \"bonus_guides\/seeding_data.md\": [group: \"Bonus Guides\"]\n ]\n |> Enum.map(fn {file, opts} -> {:\"deps\/phoenix_guides\/docs\/#{file}\", opts} end)\n end\n\n defp aliases do\n [\n \"docs\": [\"docs\", &generate_js_docs\/1]\n ]\n end\n\n def generate_js_docs(_) do\n Mix.Task.run \"app.start\"\n System.cmd(\"npm\", [\"run\", \"docs\"])\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"6986656c91c4a15d37cf3a6d441506a61d7d4a0c","subject":"Allow any 1.x minor version to run koans","message":"Allow any 1.x minor version to run koans\n\nSee #167\n","repos":"samstarling\/elixir-koans,elixirkoans\/elixir-koans","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Koans.Mixfile do\n use Mix.Project\n\n def project do\n [app: :elixir_koans,\n version: \"0.0.1\",\n elixir: \">= 1.2.1 and ~> 1.4\",\n elixirc_paths: elixirc_path(Mix.env),\n deps: deps()]\n end\n\n def application do\n [applications: [:exfswatch, :logger]]\n end\n\n defp deps do\n [{:exfswatch, \"~> 0.3\"}]\n end\n\n defp elixirc_path(:test), do: [\"lib\/\", \"test\/support\"]\n defp elixirc_path(_), do: [\"lib\/\"]\nend\n","old_contents":"defmodule Koans.Mixfile do\n use Mix.Project\n\n def project do\n [app: :elixir_koans,\n version: \"0.0.1\",\n elixir: \">= 1.2.1 and <= 1.4.1\",\n elixirc_paths: elixirc_path(Mix.env),\n deps: deps()]\n end\n\n def application do\n [applications: [:exfswatch, :logger]]\n end\n\n defp deps do\n [{:exfswatch, \"~> 0.3\"}]\n end\n\n defp elixirc_path(:test), do: [\"lib\/\", \"test\/support\"]\n defp elixirc_path(_), do: [\"lib\/\"]\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"940e6926119b34d8bef495c74ff299d1242160f2","subject":"Bump version to v0.6.8","message":"Bump version to v0.6.8","repos":"asaaki\/cmark.ex,asaaki\/cmark.ex","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Cmark.Mixfile do\n use Mix.Project\n\n @version \"0.6.8\"\n\n def project do\n [\n app: :cmark,\n version: @version,\n elixir: \"~> 1.0\",\n compilers: [:cmark, :elixir, :app],\n deps: deps,\n package: package,\n description: description,\n name: \"cmark\",\n source_url: \"https:\/\/github.com\/asaaki\/cmark.ex\",\n homepage_url: \"http:\/\/hexdocs.pm\/cmark\",\n docs: &docs\/0,\n test_coverage: [tool: ExCoveralls]\n ]\n end\n\n def application, do: []\n\n defp description do\n \"\"\"\n Elixir NIF for cmark (C), a parser library following the CommonMark spec,\n a compatible implementation of Markdown.\n \"\"\"\n end\n\n defp package do\n [\n maintainers: [\"Christoph Grabo\"],\n licenses: [\"MIT\"],\n links: %{\n \"GitHub\" => \"https:\/\/github.com\/asaaki\/cmark.ex\",\n \"Issues\" => \"https:\/\/github.com\/asaaki\/cmark.ex\/issues\",\n \"Docs\" => \"http:\/\/hexdocs.pm\/cmark\/#{@version}\/\"\n },\n files: [\n \"c_src\/*.h\",\n \"c_src\/*.c\",\n \"c_src\/*.inc\",\n \"c_src\/COPYING\",\n \"lib\",\n \"LICENSE\",\n \"Makefile\",\n \"mix.exs\",\n \"README.md\",\n \"src\"\n ]\n ]\n end\n\n defp docs do\n [\n extras: [\"README.md\"],\n main: \"readme\",\n source_ref: \"v#{@version}\",\n source_url: \"https:\/\/github.com\/asaaki\/cmark.ex\"\n ]\n end\n\n defp deps do\n [\n {:credo, \"~> 0.3.0-dev\", only: [:lint, :ci]},\n {:dogma, \"~> 0.0\", only: [:lint, :ci]},\n {:ex_doc, \"~> 0.11\", only: [:docs, :ci]},\n {:excoveralls, \"~> 0.4\", only: :ci},\n {:inch_ex, \"~> 0.5\", only: [:docs, :ci]},\n {:poison, \"~> 2.0\", only: [:dev, :test, :docs, :lint, :ci], override: true},\n {:dialyxir, \"~> 0.3\", only: [:dev]},\n ]\n end\nend\n\ndefmodule Mix.Tasks.Compile.Cmark do\n use Mix.Task\n @shortdoc \"Compiles cmark library\"\n def run(_) do\n if Mix.env != :test, do: File.rm_rf(\"priv\")\n File.mkdir(\"priv\")\n\n {result, error_code} = System.cmd(\"make\", [], stderr_to_stdout: true)\n IO.binwrite(result)\n\n if error_code != 0 do\n raise Mix.Error, message: \"\"\"\n Could not run `make`.\n Please check if `make` and either `clang` or `gcc` are installed\n \"\"\"\n end\n\n Mix.Project.build_structure\n :ok\n end\nend\n\ndefmodule Mix.Tasks.Spec do\n use Mix.Task\n @shortdoc \"Runs spec test\"\n def run(_) do\n Mix.shell.cmd(\"make spec\")\n end\nend\n","old_contents":"defmodule Cmark.Mixfile do\n use Mix.Project\n\n @version \"0.6.7\"\n\n def project do\n [\n app: :cmark,\n version: @version,\n elixir: \"~> 1.0\",\n compilers: [:cmark, :elixir, :app],\n deps: deps,\n package: package,\n description: description,\n name: \"cmark\",\n source_url: \"https:\/\/github.com\/asaaki\/cmark.ex\",\n homepage_url: \"http:\/\/hexdocs.pm\/cmark\",\n docs: &docs\/0,\n test_coverage: [tool: ExCoveralls]\n ]\n end\n\n def application, do: []\n\n defp description do\n \"\"\"\n Elixir NIF for cmark (C), a parser library following the CommonMark spec,\n a compatible implementation of Markdown.\n \"\"\"\n end\n\n defp package do\n [\n maintainers: [\"Christoph Grabo\"],\n licenses: [\"MIT\"],\n links: %{\n \"GitHub\" => \"https:\/\/github.com\/asaaki\/cmark.ex\",\n \"Issues\" => \"https:\/\/github.com\/asaaki\/cmark.ex\/issues\",\n \"Docs\" => \"http:\/\/hexdocs.pm\/cmark\/#{@version}\/\"\n },\n files: [\n \"c_src\/*.h\",\n \"c_src\/*.c\",\n \"c_src\/*.inc\",\n \"c_src\/COPYING\",\n \"lib\",\n \"LICENSE\",\n \"Makefile\",\n \"mix.exs\",\n \"README.md\",\n \"src\"\n ]\n ]\n end\n\n defp docs do\n [\n extras: [\"README.md\"],\n main: \"readme\",\n source_ref: \"v#{@version}\",\n source_url: \"https:\/\/github.com\/asaaki\/cmark.ex\"\n ]\n end\n\n defp deps do\n [\n {:credo, \"~> 0.3.0-dev\", only: [:lint, :ci]},\n {:dogma, \"~> 0.0\", only: [:lint, :ci]},\n {:ex_doc, \"~> 0.11\", only: [:docs, :ci]},\n {:excoveralls, \"~> 0.4\", only: :ci},\n {:inch_ex, \"~> 0.5\", only: [:docs, :ci]},\n {:poison, \"~> 2.0\", only: [:dev, :test, :docs, :lint, :ci], override: true},\n {:dialyxir, \"~> 0.3\", only: [:dev]},\n ]\n end\nend\n\ndefmodule Mix.Tasks.Compile.Cmark do\n use Mix.Task\n @shortdoc \"Compiles cmark library\"\n def run(_) do\n if Mix.env != :test, do: File.rm_rf(\"priv\")\n File.mkdir(\"priv\")\n\n {result, error_code} = System.cmd(\"make\", [], stderr_to_stdout: true)\n IO.binwrite(result)\n\n if error_code != 0 do\n raise Mix.Error, message: \"\"\"\n Could not run `make`.\n Please check if `make` and either `clang` or `gcc` are installed\n \"\"\"\n end\n\n Mix.Project.build_structure\n :ok\n end\nend\n\ndefmodule Mix.Tasks.Spec do\n use Mix.Task\n @shortdoc \"Runs spec test\"\n def run(_) do\n Mix.shell.cmd(\"make spec\")\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"9a94c933598696ecb0c2e9dca7bf2b04dc6651d9","subject":"fix travis","message":"fix travis\n","repos":"scrogson\/romeo","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Romeo.Mixfile do\n use Mix.Project\n\n @version \"0.7.0\"\n\n def project do\n [app: :romeo,\n name: \"Romeo\",\n version: @version,\n elixir: \"~> 1.1\",\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n description: description(),\n deps: deps(),\n docs: docs(),\n package: package(),\n test_coverage: [tool: ExCoveralls]]\n end\n\n def application do\n [applications: [:logger, :connection, :fast_xml],\n mod: {Romeo, []}]\n end\n\n defp description do\n \"An XMPP Client for Elixir\"\n end\n\n defp deps do\n [{:connection, \"~> 1.0\"},\n {:fast_xml, \"~> 1.1\"},\n\n # Docs deps\n {:ex_doc, \"~> 0.18\", only: :dev},\n\n # Test deps\n {:ejabberd, github: \"scrogson\/ejabberd\", branch: \"fix_mix_compile\", only: :test},\n {:excoveralls, \"~> 0.8\", only: :test}]\n end\n\n defp docs do\n [extras: docs_extras(),\n main: \"readme\"]\n end\n\n defp docs_extras do\n [\"README.md\"]\n end\n\n defp package do\n [files: [\"lib\", \"mix.exs\", \"README.md\", \"LICENSE\"],\n maintainers: [\"Sonny Scroggin\"],\n licenses: [\"MIT\"],\n links: %{\"GitHub\" => \"https:\/\/github.com\/scrogson\/romeo\"}]\n end\nend\n","old_contents":"defmodule Romeo.Mixfile do\n use Mix.Project\n\n @version \"0.7.0\"\n\n def project do\n [app: :romeo,\n name: \"Romeo\",\n version: @version,\n elixir: \"~> 1.1\",\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n description: description(),\n deps: deps(),\n docs: docs(),\n package: package(),\n test_coverage: [tool: ExCoveralls]]\n end\n\n def application do\n [applications: [:logger, :connection, :fast_xml],\n mod: {Romeo, []}]\n end\n\n defp description do\n \"An XMPP Client for Elixir\"\n end\n\n defp deps do\n [{:connection, \"~> 1.0\"},\n {:fast_xml, \"~> 1.1\"},\n\n # Docs deps\n {:ex_doc, \"~> 0.18\", only: :dev},\n\n # Test deps\n {:ejabberd, \"~> 18.1\", only: :test},\n {:excoveralls, \"~> 0.8\", only: :test}]\n end\n\n defp docs do\n [extras: docs_extras(),\n main: \"readme\"]\n end\n\n defp docs_extras do\n [\"README.md\"]\n end\n\n defp package do\n [files: [\"lib\", \"mix.exs\", \"README.md\", \"LICENSE\"],\n maintainers: [\"Sonny Scroggin\"],\n licenses: [\"MIT\"],\n links: %{\"GitHub\" => \"https:\/\/github.com\/scrogson\/romeo\"}]\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"702108fd02e4a8763ff68b21cb8d6df387772b38","subject":"0.4.2","message":"0.4.2\n","repos":"cgrates-web\/cgrates_web_jsonapi","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule CgratesWebJsonapi.Mixfile do\n use Mix.Project\n\n def project do\n [\n app: :cgrates_web_jsonapi,\n version: \"0.4.2\",\n elixir: \"~> 1.10\",\n elixirc_paths: elixirc_paths(Mix.env()),\n compilers: [:phoenix, :gettext] ++ Mix.compilers() ++ [:phoenix_swagger],\n build_embedded: Mix.env() == :prod,\n start_permanent: Mix.env() == :prod,\n aliases: aliases(),\n test_coverage: [tool: Coverex.Task, coveralls: true],\n deps: deps()\n ]\n end\n\n # Configuration for the OTP application.\n #\n # Type `mix help compile.app` for more information.\n def application do\n [\n mod: {CgratesWebJsonapi.Application, []},\n extra_applications: [:logger, :runtime_tools]\n ]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"web\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\", \"web\"]\n\n # Specifies your project dependencies.\n #\n # Type `mix help deps` for examples and options.\n defp deps do\n [\n {:phoenix, \"~> 1.5.3\"},\n {:phoenix_pubsub, \"~> 2.0\"},\n {:phoenix_ecto, \"~> 4.1\"},\n {:phoenix_live_dashboard, \"~> 0.2.0\"},\n {:phoenix_swagger, \"~> 0.8\"},\n {:ex_json_schema, \"~> 0.7.4\"},\n {:gettext, \"~> 0.11\"},\n {:plug_cowboy, \"~> 2.0\"},\n {:plug, \"~> 1.7\"},\n {:telemetry_metrics, \"~> 0.4\"},\n {:telemetry_poller, \"~> 0.4\"},\n {:jason, \"~> 1.0\"},\n {:bureaucrat, github: \"api-hogs\/bureaucrat\", only: :test},\n {:comeonin, \"~> 2.0\"},\n {:cors_plug, \"~> 1.2\"},\n {:coverex, \"~> 1.4.10\", only: :test},\n {:credo, \"~> 0.9.0-rc1\", only: [:dev, :test], runtime: false},\n {:csv, \"~> 2.0.0\"},\n {:distillery, \"~> 2.1\", runtime: false},\n {:ecto_conditionals, \"~> 0.1.0\"},\n {:ecto_sql, \"~> 3.4\"},\n {:ex_machina, \"~> 2.4\", only: :test},\n {:faker, \"~> 0.8\", only: :test},\n {:guardian, \"~> 2.0\"},\n {:httpoison, \"~> 1.8.0\"},\n {:ja_resource, github: \"vt-elixir\/ja_resource\"},\n {:ja_serializer, \"~> 0.16.0\"},\n {:mapail, \"~> 1.0\"},\n {:mock, \"~> 0.3.6\", only: :test},\n {:parallel_stream, \"~> 1.0.5\"},\n {:postgrex, \"~> 0.15.7\"},\n {:proper_case, github: \"max-konin\/proper_case\", branch: \"upper-case\"},\n {:scrivener_ecto, \"~> 2.0\"},\n {:uuid, \"~> 1.1\"},\n {:husky, \"~> 1.0\", only: :dev, runtime: false},\n {:dialyxir, \"~> 1.0\", only: [:dev], runtime: false},\n {:typed_struct, \"~> 0.2.1\"},\n {:poison, \"~> 3.1\"}\n ]\n end\n\n # Aliases are shortcuts or tasks specific to the current project.\n # For example, to create, migrate and run the seeds file at once:\n #\n # $ mix ecto.setup\n #\n # See the documentation for `Mix` for more info on aliases.\n defp aliases do\n [\n \"ecto.setup\": [\"ecto.create\", \"ecto.load\", \"ecto.migrate\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"],\n test: [\"ecto.drop\", \"ecto.create --quiet\", \"ecto.load\", \"ecto.migrate\", \"test\"]\n ]\n end\nend\n","old_contents":"defmodule CgratesWebJsonapi.Mixfile do\n use Mix.Project\n\n def project do\n [\n app: :cgrates_web_jsonapi,\n version: \"0.4.1\",\n elixir: \"~> 1.10\",\n elixirc_paths: elixirc_paths(Mix.env()),\n compilers: [:phoenix, :gettext] ++ Mix.compilers() ++ [:phoenix_swagger],\n build_embedded: Mix.env() == :prod,\n start_permanent: Mix.env() == :prod,\n aliases: aliases(),\n test_coverage: [tool: Coverex.Task, coveralls: true],\n deps: deps()\n ]\n end\n\n # Configuration for the OTP application.\n #\n # Type `mix help compile.app` for more information.\n def application do\n [\n mod: {CgratesWebJsonapi.Application, []},\n extra_applications: [:logger, :runtime_tools]\n ]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"web\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\", \"web\"]\n\n # Specifies your project dependencies.\n #\n # Type `mix help deps` for examples and options.\n defp deps do\n [\n {:phoenix, \"~> 1.5.3\"},\n {:phoenix_pubsub, \"~> 2.0\"},\n {:phoenix_ecto, \"~> 4.1\"},\n {:phoenix_live_dashboard, \"~> 0.2.0\"},\n {:phoenix_swagger, \"~> 0.8\"},\n {:ex_json_schema, \"~> 0.7.4\"},\n {:gettext, \"~> 0.11\"},\n {:plug_cowboy, \"~> 2.0\"},\n {:plug, \"~> 1.7\"},\n {:telemetry_metrics, \"~> 0.4\"},\n {:telemetry_poller, \"~> 0.4\"},\n {:jason, \"~> 1.0\"},\n {:bureaucrat, github: \"api-hogs\/bureaucrat\", only: :test},\n {:comeonin, \"~> 2.0\"},\n {:cors_plug, \"~> 1.2\"},\n {:coverex, \"~> 1.4.10\", only: :test},\n {:credo, \"~> 0.9.0-rc1\", only: [:dev, :test], runtime: false},\n {:csv, \"~> 2.0.0\"},\n {:distillery, \"~> 2.1\", runtime: false},\n {:ecto_conditionals, \"~> 0.1.0\"},\n {:ecto_sql, \"~> 3.4\"},\n {:ex_machina, \"~> 2.4\", only: :test},\n {:faker, \"~> 0.8\", only: :test},\n {:guardian, \"~> 2.0\"},\n {:httpoison, \"~> 1.8.0\"},\n {:ja_resource, github: \"vt-elixir\/ja_resource\"},\n {:ja_serializer, \"~> 0.16.0\"},\n {:mapail, \"~> 1.0\"},\n {:mock, \"~> 0.3.6\", only: :test},\n {:parallel_stream, \"~> 1.0.5\"},\n {:postgrex, \"~> 0.15.7\"},\n {:proper_case, github: \"max-konin\/proper_case\", branch: \"upper-case\"},\n {:scrivener_ecto, \"~> 2.0\"},\n {:uuid, \"~> 1.1\"},\n {:husky, \"~> 1.0\", only: :dev, runtime: false},\n {:dialyxir, \"~> 1.0\", only: [:dev], runtime: false},\n {:typed_struct, \"~> 0.2.1\"},\n {:poison, \"~> 3.1\"}\n ]\n end\n\n # Aliases are shortcuts or tasks specific to the current project.\n # For example, to create, migrate and run the seeds file at once:\n #\n # $ mix ecto.setup\n #\n # See the documentation for `Mix` for more info on aliases.\n defp aliases do\n [\n \"ecto.setup\": [\"ecto.create\", \"ecto.load\", \"ecto.migrate\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"],\n test: [\"ecto.drop\", \"ecto.create --quiet\", \"ecto.load\", \"ecto.migrate\", \"test\"]\n ]\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"996be0e5601897d78a496301de18d2a486b115a4","subject":"Fix version requirement for inch_ex","message":"Fix version requirement for inch_ex\n","repos":"rrrene\/html_sanitize_ex","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule HtmlSanitizeEx.Mixfile do\n use Mix.Project\n\n def project do\n [\n app: :html_sanitize_ex,\n version: \"0.3.0\",\n elixir: \"~> 1.0\",\n description: \"HTML sanitizer for Elixir\",\n source_url: \"https:\/\/github.com\/rrrene\/html_sanitize_ex\",\n package: [\n contributors: [\"Ren\u00e9 F\u00f6hring\"],\n licenses: [\"MIT\"],\n links: %{\n \"GitHub\" => \"https:\/\/github.com\/rrrene\/html_sanitize_ex\",\n }\n ],\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n deps: deps\n ]\n end\n\n # Configuration for the OTP application\n #\n # Type `mix help compile.app` for more information\n def application do\n [applications: [:logger, :mochiweb]]\n end\n\n # Dependencies can be Hex packages:\n #\n # {:mydep, \"~> 0.3.0\"}\n #\n # Or git\/path repositories:\n #\n # {:mydep, git: \"https:\/\/github.com\/elixir-lang\/mydep.git\", tag: \"0.1.0\"}\n #\n # Type `mix help deps` for more examples and options\n defp deps do\n [\n {:mochiweb, \"~> 2.12.2\"},\n {:inch_ex, \">= 0.0.0\", only: :docs}\n ]\n end\nend\n","old_contents":"defmodule HtmlSanitizeEx.Mixfile do\n use Mix.Project\n\n def project do\n [\n app: :html_sanitize_ex,\n version: \"0.3.0\",\n elixir: \"~> 1.0\",\n description: \"HTML sanitizer for Elixir\",\n source_url: \"https:\/\/github.com\/rrrene\/html_sanitize_ex\",\n package: [\n contributors: [\"Ren\u00e9 F\u00f6hring\"],\n licenses: [\"MIT\"],\n links: %{\n \"GitHub\" => \"https:\/\/github.com\/rrrene\/html_sanitize_ex\",\n }\n ],\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n deps: deps\n ]\n end\n\n # Configuration for the OTP application\n #\n # Type `mix help compile.app` for more information\n def application do\n [applications: [:logger, :mochiweb]]\n end\n\n # Dependencies can be Hex packages:\n #\n # {:mydep, \"~> 0.3.0\"}\n #\n # Or git\/path repositories:\n #\n # {:mydep, git: \"https:\/\/github.com\/elixir-lang\/mydep.git\", tag: \"0.1.0\"}\n #\n # Type `mix help deps` for more examples and options\n defp deps do\n [\n {:mochiweb, \"~> 2.12.2\"},\n {:inch_ex, only: :docs}\n ]\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"59015d2cd3c20167873410b318b0b7c022e378de","subject":"version 0.12.9","message":"version 0.12.9\n","repos":"ckruse\/wwwtech.de,ckruse\/wwwtech.de,ckruse\/wwwtech.de","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Wwwtech.MixProject do\n use Mix.Project\n\n def project do\n [\n app: :wwwtech,\n version: \"0.12.9\",\n elixir: \"~> 1.7\",\n elixirc_paths: elixirc_paths(Mix.env()),\n compilers: [:gettext] ++ Mix.compilers(),\n start_permanent: Mix.env() == :prod,\n aliases: aliases(),\n deps: deps()\n ]\n end\n\n # Configuration for the OTP application.\n #\n # Type `mix help compile.app` for more information.\n def application do\n [\n mod: {Wwwtech.Application, []},\n extra_applications: [:logger, :runtime_tools, :os_mon]\n ]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\"]\n\n # Specifies your project dependencies.\n #\n # Type `mix help deps` for examples and options.\n defp deps do\n [\n {:phoenix, \"~> 1.6.0\"},\n {:phoenix_pubsub, \"~> 2.0\"},\n {:phoenix_ecto, \"~> 4.0\"},\n {:ecto_sql, \"~> 3.1\"},\n {:postgrex, \">= 0.0.0\"},\n {:phoenix_html, \"~> 3.0\"},\n {:phoenix_live_reload, \"~> 1.2\", only: :dev},\n {:gettext, \"~> 0.18\"},\n {:jason, \"~> 1.0\"},\n {:plug_cowboy, \"~> 2.1\"},\n {:argon2_elixir, \"~> 2.0\"},\n {:timex, \"~> 3.5\"},\n {:earmark, \"~> 1.4\"},\n {:xml_builder, \"~> 2.1\"},\n {:exexif, \"~> 0.0.5\"},\n {:mogrify, \"~> 0.9.1\"},\n {:microformats2, \"~> 0.1\"},\n {:webmentions, \"~> 1.0\"},\n {:floki, \"~> 0.23\"},\n {:swoosh, \"~> 1.3\"},\n {:gen_smtp, \"~> 1.1\"},\n {:phoenix_swoosh, \"~> 1.0\"},\n {:appsignal_phoenix, \"~> 2.0.0\"},\n {:tesla, \"~> 1.3\"},\n {:hackney, \"~> 1.15\"},\n {:gh_webhook_plug, \"~> 0.0.5\"}\n ]\n end\n\n # Aliases are shortcuts or tasks specific to the current project.\n # For example, to create, migrate and run the seeds file at once:\n #\n # $ mix ecto.setup\n #\n # See the documentation for `Mix` for more info on aliases.\n defp aliases do\n [\n \"ecto.setup\": [\"ecto.create\", \"ecto.migrate\", \"run priv\/repo\/seeds.exs\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"],\n test: [\"ecto.create --quiet\", \"ecto.migrate\", \"test\"],\n build: \"cmd .\/.build\/build\",\n deploy: \"cmd .\/.build\/deploy\"\n ]\n end\nend\n","old_contents":"defmodule Wwwtech.MixProject do\n use Mix.Project\n\n def project do\n [\n app: :wwwtech,\n version: \"0.12.8\",\n elixir: \"~> 1.7\",\n elixirc_paths: elixirc_paths(Mix.env()),\n compilers: [:gettext] ++ Mix.compilers(),\n start_permanent: Mix.env() == :prod,\n aliases: aliases(),\n deps: deps()\n ]\n end\n\n # Configuration for the OTP application.\n #\n # Type `mix help compile.app` for more information.\n def application do\n [\n mod: {Wwwtech.Application, []},\n extra_applications: [:logger, :runtime_tools, :os_mon]\n ]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\"]\n\n # Specifies your project dependencies.\n #\n # Type `mix help deps` for examples and options.\n defp deps do\n [\n {:phoenix, \"~> 1.6.0\"},\n {:phoenix_pubsub, \"~> 2.0\"},\n {:phoenix_ecto, \"~> 4.0\"},\n {:ecto_sql, \"~> 3.1\"},\n {:postgrex, \">= 0.0.0\"},\n {:phoenix_html, \"~> 3.0\"},\n {:phoenix_live_reload, \"~> 1.2\", only: :dev},\n {:gettext, \"~> 0.18\"},\n {:jason, \"~> 1.0\"},\n {:plug_cowboy, \"~> 2.1\"},\n {:argon2_elixir, \"~> 2.0\"},\n {:timex, \"~> 3.5\"},\n {:earmark, \"~> 1.4\"},\n {:xml_builder, \"~> 2.1\"},\n {:exexif, \"~> 0.0.5\"},\n {:mogrify, \"~> 0.9.1\"},\n {:microformats2, \"~> 0.1\"},\n {:webmentions, \"~> 1.0\"},\n {:floki, \"~> 0.23\"},\n {:swoosh, \"~> 1.3\"},\n {:gen_smtp, \"~> 1.1\"},\n {:phoenix_swoosh, \"~> 1.0\"},\n {:appsignal_phoenix, \"~> 2.0.0\"},\n {:tesla, \"~> 1.3\"},\n {:hackney, \"~> 1.15\"},\n {:gh_webhook_plug, \"~> 0.0.5\"}\n ]\n end\n\n # Aliases are shortcuts or tasks specific to the current project.\n # For example, to create, migrate and run the seeds file at once:\n #\n # $ mix ecto.setup\n #\n # See the documentation for `Mix` for more info on aliases.\n defp aliases do\n [\n \"ecto.setup\": [\"ecto.create\", \"ecto.migrate\", \"run priv\/repo\/seeds.exs\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"],\n test: [\"ecto.create --quiet\", \"ecto.migrate\", \"test\"],\n build: \"cmd .\/.build\/build\",\n deploy: \"cmd .\/.build\/deploy\"\n ]\n end\nend\n","returncode":0,"stderr":"","license":"agpl-3.0","lang":"Elixir"} {"commit":"959a0c17214c0c9c1fb91e4e5c146e8670fe0835","subject":"Add comeonin dependency","message":"Add comeonin dependency\n","repos":"viatsko\/lyn,viatsko\/lyn,viatsko\/lyn","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Lyn.Mixfile do\n use Mix.Project\n\n def project do\n [app: :lyn,\n version: \"0.0.1\",\n elixir: \"~> 1.0\",\n elixirc_paths: elixirc_paths(Mix.env),\n compilers: [:phoenix, :gettext] ++ Mix.compilers,\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n aliases: aliases,\n description: description,\n package: package,\n deps: deps]\n end\n\n # Configuration for the OTP application.\n #\n # Type `mix help compile.app` for more information.\n def application do\n [mod: {Lyn, []},\n applications: [:phoenix, :phoenix_html, :cowboy, :logger, :gettext,\n :phoenix_ecto, :postgrex]]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"web\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\", \"web\"]\n\n # Specifies your project dependencies.\n #\n # Type `mix help deps` for examples and options.\n defp deps do\n [{:comeonin, \"~> 2.1\"},\n {:ex_machina, \"~> 0.6.1\", only: :test},\n {:phoenix, \"~> 1.1.4\"},\n {:postgrex, \">= 0.0.0\"},\n {:phoenix_ecto, \"~> 2.0\"},\n {:phoenix_html, \"~> 2.4\"},\n {:phoenix_live_reload, \"~> 1.0\", only: :dev},\n {:gettext, \"~> 0.9\"},\n {:cowboy, \"~> 1.0\"}]\n end\n\n # Aliases are shortcut or tasks specific to the current project.\n # For example, to create, migrate and run the seeds file at once:\n #\n # $ mix ecto.setup\n #\n # See the documentation for `Mix` for more info on aliases.\n defp aliases do\n [\"ecto.setup\": [\"ecto.create\", \"ecto.migrate\", \"run priv\/repo\/seeds.exs\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"]]\n end\n\n defp description do\n \"\"\"\n Elixir CMS\n \"\"\"\n end\n\n defp package do\n [# These are the default files included in the package\n files: [\"config\", \"lib\", \"priv\", \"test\", \"web\", \"mix.exs\", \"README*\", \"readme*\", \"LICENSE*\", \"license*\"],\n maintainers: [\"Valerii Iatsko\"],\n licenses: [\"MIT\"],\n links: %{\"GitHub\" => \"https:\/\/github.com\/viatsko\/lyn\",\n \"Docs\" => \"http:\/\/viatsko.github.io\/lyn\/\"}]\n end\nend\n","old_contents":"defmodule Lyn.Mixfile do\n use Mix.Project\n\n def project do\n [app: :lyn,\n version: \"0.0.1\",\n elixir: \"~> 1.0\",\n elixirc_paths: elixirc_paths(Mix.env),\n compilers: [:phoenix, :gettext] ++ Mix.compilers,\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n aliases: aliases,\n description: description,\n package: package,\n deps: deps]\n end\n\n # Configuration for the OTP application.\n #\n # Type `mix help compile.app` for more information.\n def application do\n [mod: {Lyn, []},\n applications: [:phoenix, :phoenix_html, :cowboy, :logger, :gettext,\n :phoenix_ecto, :postgrex]]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"web\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\", \"web\"]\n\n # Specifies your project dependencies.\n #\n # Type `mix help deps` for examples and options.\n defp deps do\n [{:ex_machina, \"~> 0.6.1\", only: :test},\n {:phoenix, \"~> 1.1.4\"},\n {:postgrex, \">= 0.0.0\"},\n {:phoenix_ecto, \"~> 2.0\"},\n {:phoenix_html, \"~> 2.4\"},\n {:phoenix_live_reload, \"~> 1.0\", only: :dev},\n {:gettext, \"~> 0.9\"},\n {:cowboy, \"~> 1.0\"}]\n end\n\n # Aliases are shortcut or tasks specific to the current project.\n # For example, to create, migrate and run the seeds file at once:\n #\n # $ mix ecto.setup\n #\n # See the documentation for `Mix` for more info on aliases.\n defp aliases do\n [\"ecto.setup\": [\"ecto.create\", \"ecto.migrate\", \"run priv\/repo\/seeds.exs\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"]]\n end\n\n defp description do\n \"\"\"\n Elixir CMS\n \"\"\"\n end\n\n defp package do\n [# These are the default files included in the package\n files: [\"config\", \"lib\", \"priv\", \"test\", \"web\", \"mix.exs\", \"README*\", \"readme*\", \"LICENSE*\", \"license*\"],\n maintainers: [\"Valerii Iatsko\"],\n licenses: [\"MIT\"],\n links: %{\"GitHub\" => \"https:\/\/github.com\/viatsko\/lyn\",\n \"Docs\" => \"http:\/\/viatsko.github.io\/lyn\/\"}]\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"cc23206d3f8197acd5af3f01ad46127ba94f899e","subject":"Bump version number","message":"Bump version number\n","repos":"vutuv\/vutuv,vutuv\/vutuv","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Vutuv.Mixfile do\n use Mix.Project\n\n def project do\n [app: :vutuv,\n version: \"1.3.3\",\n elixir: \"~> 1.4.0\",\n elixirc_paths: elixirc_paths(Mix.env),\n compilers: [:phoenix, :gettext] ++ Mix.compilers,\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n aliases: aliases(),\n deps: deps()]\n end\n\n # Configuration for the OTP application.\n #\n # Type `mix help compile.app` for more information.\n def application do\n [mod: {Vutuv, []},\n applications: [:phoenix,\n :phoenix_pubsub,\n :phoenix_html,\n :cowboy,\n :logger,\n :gettext,\n :phoenix_ecto,\n :ex_machina,\n :phoenix_html_simplified_helpers,\n :bamboo,\n :bamboo_smtp,\n :mariaex,\n :httpoison,\n :slugger,\n :timex_ecto,\n :word_smith,\n :arc,\n :arc_ecto,\n :quantum]]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"web\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\", \"web\"]\n\n # Specifies your project dependencies.\n #\n # Type `mix help deps` for examples and options.\n defp deps do\n [{:ecto, \"~> 2.0.1\", override: true},\n {:bamboo, \"~> 0.6\"},\n {:bamboo_smtp, \"~> 1.1.0\"},\n {:phoenix, \"~> 1.2.0\"},\n {:phoenix_ecto, \"~> 3.0.0-rc\"},\n {:phoenix_html, \"~> 2.8\"},\n {:phoenix_live_reload, \"~> 1.0\", only: :dev},\n {:gettext, \"~> 0.12.1\"},\n {:cowboy, \"~> 1.0\"},\n {:arc, \"~> 0.5.3\"},\n {:arc_ecto, \"~> 0.4.2\"},\n {:ex_machina, \"~> 1.0\"},\n {:phoenix_html_simplified_helpers, \"~> 0.6.0\"},\n {:mariaex, \">= 0.0.0\"},\n {:word_smith, \"~> 0.1.0\"},\n {:slugger, \"~> 0.1.0\"},\n {:httpoison, \"~> 0.9.0\"},\n {:distillery, \"~> 1.1.0\"},\n {:quantum, \">= 1.8.1\"}]\n end\n\n # Aliases are shortcut or tasks specific to the current project.\n # For example, to create, migrate and run the seeds file at once:\n #\n # $ mix ecto.setup\n #\n # See the documentation for `Mix` for more info on aliases.\n defp aliases do\n [\"ecto.setup\": [\"ecto.create\", \"ecto.migrate\", \"run priv\/repo\/seeds.exs\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"],\n \"test\": [\"ecto.create --quiet\", \"ecto.migrate\", \"test\"]]\n end\nend\n","old_contents":"defmodule Vutuv.Mixfile do\n use Mix.Project\n\n def project do\n [app: :vutuv,\n version: \"1.3.2\",\n elixir: \"~> 1.4.0\",\n elixirc_paths: elixirc_paths(Mix.env),\n compilers: [:phoenix, :gettext] ++ Mix.compilers,\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n aliases: aliases(),\n deps: deps()]\n end\n\n # Configuration for the OTP application.\n #\n # Type `mix help compile.app` for more information.\n def application do\n [mod: {Vutuv, []},\n applications: [:phoenix,\n :phoenix_pubsub,\n :phoenix_html,\n :cowboy,\n :logger,\n :gettext,\n :phoenix_ecto,\n :ex_machina,\n :phoenix_html_simplified_helpers,\n :bamboo,\n :bamboo_smtp,\n :mariaex,\n :httpoison,\n :slugger,\n :timex_ecto,\n :word_smith,\n :arc,\n :arc_ecto,\n :quantum]]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"web\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\", \"web\"]\n\n # Specifies your project dependencies.\n #\n # Type `mix help deps` for examples and options.\n defp deps do\n [{:ecto, \"~> 2.0.1\", override: true},\n {:bamboo, \"~> 0.6\"},\n {:bamboo_smtp, \"~> 1.1.0\"},\n {:phoenix, \"~> 1.2.0\"},\n {:phoenix_ecto, \"~> 3.0.0-rc\"},\n {:phoenix_html, \"~> 2.8\"},\n {:phoenix_live_reload, \"~> 1.0\", only: :dev},\n {:gettext, \"~> 0.12.1\"},\n {:cowboy, \"~> 1.0\"},\n {:arc, \"~> 0.5.3\"},\n {:arc_ecto, \"~> 0.4.2\"},\n {:ex_machina, \"~> 1.0\"},\n {:phoenix_html_simplified_helpers, \"~> 0.6.0\"},\n {:mariaex, \">= 0.0.0\"},\n {:word_smith, \"~> 0.1.0\"},\n {:slugger, \"~> 0.1.0\"},\n {:httpoison, \"~> 0.9.0\"},\n {:distillery, \"~> 1.1.0\"},\n {:quantum, \">= 1.8.1\"}]\n end\n\n # Aliases are shortcut or tasks specific to the current project.\n # For example, to create, migrate and run the seeds file at once:\n #\n # $ mix ecto.setup\n #\n # See the documentation for `Mix` for more info on aliases.\n defp aliases do\n [\"ecto.setup\": [\"ecto.create\", \"ecto.migrate\", \"run priv\/repo\/seeds.exs\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"],\n \"test\": [\"ecto.create --quiet\", \"ecto.migrate\", \"test\"]]\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"99d3d6eb1d071b57fa05c137bd552a81cf77dbc5","subject":"version 0.8.14","message":"version 0.8.14\n","repos":"ckruse\/wwwtech.de,ckruse\/wwwtech.de,ckruse\/wwwtech.de","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Wwwtech.MixProject do\n use Mix.Project\n\n def project do\n [\n app: :wwwtech,\n version: \"0.8.14\",\n elixir: \"~> 1.5\",\n elixirc_paths: elixirc_paths(Mix.env()),\n compilers: [:phoenix, :gettext] ++ Mix.compilers(),\n start_permanent: Mix.env() == :prod,\n aliases: aliases(),\n deps: deps()\n ]\n end\n\n # Configuration for the OTP application.\n #\n # Type `mix help compile.app` for more information.\n def application do\n [\n mod: {Wwwtech.Application, []},\n extra_applications: [:logger, :runtime_tools, :os_mon]\n ]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\"]\n\n # Specifies your project dependencies.\n #\n # Type `mix help deps` for examples and options.\n defp deps do\n [\n {:phoenix, \"~> 1.5.0\"},\n {:phoenix_pubsub, \"~> 2.0\"},\n {:phoenix_ecto, \"~> 4.0\"},\n {:ecto_sql, \"~> 3.1\"},\n {:postgrex, \">= 0.0.0\"},\n {:phoenix_html, \"~> 2.11\"},\n {:phoenix_live_reload, \"~> 1.2\", only: :dev},\n {:gettext, \"~> 0.11\"},\n {:jason, \"~> 1.0\"},\n {:plug_cowboy, \"~> 2.1\"},\n {:argon2_elixir, \"~> 2.0\"},\n {:timex, \"~> 3.5\"},\n {:earmark, \"~> 1.4\"},\n {:xml_builder, \"~> 2.1\"},\n {:exexif, \"~> 0.0.5\"},\n {:mogrify, \"~> 0.7.3\"},\n {:microformats2, \"~> 0.1\"},\n {:webmentions, \"~> 0.3\"},\n {:floki, \"~> 0.23\"},\n {:swoosh, \"~> 0.25\"},\n {:gen_smtp, \"~> 0.15\"},\n {:phoenix_swoosh, \"~> 0.2\"},\n {:appsignal, \"~> 1.0\"},\n {:tesla, \"~> 1.3\"},\n {:hackney, \"~> 1.15\"},\n {:phoenix_live_dashboard, \"~> 0.1\"},\n {:telemetry_poller, \"~> 0.4\"},\n {:telemetry_metrics, \"~> 0.4\"}\n ]\n end\n\n # Aliases are shortcuts or tasks specific to the current project.\n # For example, to create, migrate and run the seeds file at once:\n #\n # $ mix ecto.setup\n #\n # See the documentation for `Mix` for more info on aliases.\n defp aliases do\n [\n \"ecto.setup\": [\"ecto.create\", \"ecto.migrate\", \"run priv\/repo\/seeds.exs\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"],\n test: [\"ecto.create --quiet\", \"ecto.migrate\", \"test\"],\n build: \"cmd .\/.build\/build\",\n deploy: \"cmd .\/.build\/deploy\"\n ]\n end\nend\n","old_contents":"defmodule Wwwtech.MixProject do\n use Mix.Project\n\n def project do\n [\n app: :wwwtech,\n version: \"0.8.13\",\n elixir: \"~> 1.5\",\n elixirc_paths: elixirc_paths(Mix.env()),\n compilers: [:phoenix, :gettext] ++ Mix.compilers(),\n start_permanent: Mix.env() == :prod,\n aliases: aliases(),\n deps: deps()\n ]\n end\n\n # Configuration for the OTP application.\n #\n # Type `mix help compile.app` for more information.\n def application do\n [\n mod: {Wwwtech.Application, []},\n extra_applications: [:logger, :runtime_tools, :os_mon]\n ]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\"]\n\n # Specifies your project dependencies.\n #\n # Type `mix help deps` for examples and options.\n defp deps do\n [\n {:phoenix, \"~> 1.5.0\"},\n {:phoenix_pubsub, \"~> 2.0\"},\n {:phoenix_ecto, \"~> 4.0\"},\n {:ecto_sql, \"~> 3.1\"},\n {:postgrex, \">= 0.0.0\"},\n {:phoenix_html, \"~> 2.11\"},\n {:phoenix_live_reload, \"~> 1.2\", only: :dev},\n {:gettext, \"~> 0.11\"},\n {:jason, \"~> 1.0\"},\n {:plug_cowboy, \"~> 2.1\"},\n {:argon2_elixir, \"~> 2.0\"},\n {:timex, \"~> 3.5\"},\n {:earmark, \"~> 1.4\"},\n {:xml_builder, \"~> 2.1\"},\n {:exexif, \"~> 0.0.5\"},\n {:mogrify, \"~> 0.7.3\"},\n {:microformats2, \"~> 0.1\"},\n {:webmentions, \"~> 0.3\"},\n {:floki, \"~> 0.23\"},\n {:swoosh, \"~> 0.25\"},\n {:gen_smtp, \"~> 0.15\"},\n {:phoenix_swoosh, \"~> 0.2\"},\n {:appsignal, \"~> 1.0\"},\n {:tesla, \"~> 1.3\"},\n {:hackney, \"~> 1.15\"},\n {:phoenix_live_dashboard, \"~> 0.1\"},\n {:telemetry_poller, \"~> 0.4\"},\n {:telemetry_metrics, \"~> 0.4\"}\n ]\n end\n\n # Aliases are shortcuts or tasks specific to the current project.\n # For example, to create, migrate and run the seeds file at once:\n #\n # $ mix ecto.setup\n #\n # See the documentation for `Mix` for more info on aliases.\n defp aliases do\n [\n \"ecto.setup\": [\"ecto.create\", \"ecto.migrate\", \"run priv\/repo\/seeds.exs\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"],\n test: [\"ecto.create --quiet\", \"ecto.migrate\", \"test\"],\n build: \"cmd .\/.build\/build\",\n deploy: \"cmd .\/.build\/deploy\"\n ]\n end\nend\n","returncode":0,"stderr":"","license":"agpl-3.0","lang":"Elixir"} {"commit":"a9057bd7c6e8ed5104d36eec531d9582b12e2cd0","subject":"update exrm version to 0.6.12","message":"update exrm version to 0.6.12\n","repos":"liveforeverx\/exrm-rpm,smpallen99\/exrm-rpm","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule ExrmRpm.Mixfile do\n use Mix.Project\n\n def project do\n [app: :exrm_rpm,\n version: \"0.0.2\",\n elixir: \"~> 0.13.2\",\n deps: deps]\n end\n\n def application do\n [applications: []]\n end\n\n defp deps do\n [\n {:exrm, \"~>0.6.12\"}\n ]\n end\nend\n","old_contents":"defmodule ExrmRpm.Mixfile do\n use Mix.Project\n\n def project do\n [app: :exrm_rpm,\n version: \"0.0.2\",\n elixir: \"~> 0.13.2\",\n deps: deps]\n end\n\n def application do\n [applications: []]\n end\n\n defp deps do\n [\n {:exrm, \"~>0.6.11\"}\n ]\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"761075dca501745d82c978cb7ebc7e21db72aa79","subject":"Version upgrade","message":"Version upgrade\n","repos":"18Months\/distillery_packager,18Months\/distillery_packager","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule DistilleryPackager.Mixfile do\n use Mix.Project\n\n def project do\n [app: :distillery_packager,\n version: \"0.4.3\",\n elixir: \"~> 1.4\",\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n description: description(),\n test_coverage: [tool: ExCoveralls],\n preferred_cli_env: [\n \"coveralls\": :test,\n \"coveralls.detail\": :test,\n \"coveralls.post\": :test],\n package: package(),\n deps: deps()]\n end\n\n # Configuration for the OTP application\n #\n # Type \"mix help compile.app\" for more information\n def application do\n # Specify extra applications you'll use from Erlang\/Elixir\n [extra_applications: [:logger]]\n end\n\n # Dependencies can be Hex packages:\n #\n # {:my_dep, \"~> 0.3.0\"}\n #\n # Or git\/path repositories:\n #\n # {:my_dep, git: \"https:\/\/github.com\/elixir-lang\/my_dep.git\", tag: \"0.1.0\"}\n #\n # Type \"mix help deps\" for more examples and options\n defp deps do\n [\n {:distillery, \"~> 1.2\"},\n {:vex, \"~> 0.5\"},\n {:timex, \"~> 3.0\"},\n {:ex_doc, \">= 0.0.0\", only: :dev},\n {:credo, \"~> 0.6\", only: [:dev, :test], runtime: false},\n {:dogma, \"~> 0.1\", only: [:dev, :test], runtime: false},\n {:faker, \"~> 0.6\", only: :test},\n {:excoveralls, \"~> 0.4\", only: :test},\n ]\n end\n\n defp description do\n \"\"\"\n Elixir lib for creating Debian and RPM packages with Distillery.\n \"\"\"\n end\n\n defp package do\n [name: :distillery_packager,\n files: [\"lib\", \"mix.exs\", \"README*\", \"LICENSE*\", \"templates\"],\n maintainers: [\"18Months Dev Team \"],\n licenses: [\"MIT\"],\n links: %{\"GitHub\" => \"https:\/\/github.com\/18Months\/distillery_packager\",\n \"Docs\" => \"https:\/\/hexdocs.pm\/distillery_packager\"}]\n end\nend\n","old_contents":"defmodule DistilleryPackager.Mixfile do\n use Mix.Project\n\n def project do\n [app: :distillery_packager,\n version: \"0.4.2\",\n elixir: \"~> 1.4\",\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n description: description(),\n test_coverage: [tool: ExCoveralls],\n preferred_cli_env: [\n \"coveralls\": :test,\n \"coveralls.detail\": :test,\n \"coveralls.post\": :test],\n package: package(),\n deps: deps()]\n end\n\n # Configuration for the OTP application\n #\n # Type \"mix help compile.app\" for more information\n def application do\n # Specify extra applications you'll use from Erlang\/Elixir\n [extra_applications: [:logger]]\n end\n\n # Dependencies can be Hex packages:\n #\n # {:my_dep, \"~> 0.3.0\"}\n #\n # Or git\/path repositories:\n #\n # {:my_dep, git: \"https:\/\/github.com\/elixir-lang\/my_dep.git\", tag: \"0.1.0\"}\n #\n # Type \"mix help deps\" for more examples and options\n defp deps do\n [\n {:distillery, \"~> 1.2\"},\n {:vex, \"~> 0.5\"},\n {:timex, \"~> 3.0\"},\n {:ex_doc, \">= 0.0.0\", only: :dev},\n {:credo, \"~> 0.6\", only: [:dev, :test], runtime: false},\n {:dogma, \"~> 0.1\", only: [:dev, :test], runtime: false},\n {:faker, \"~> 0.6\", only: :test},\n {:excoveralls, \"~> 0.4\", only: :test},\n ]\n end\n\n defp description do\n \"\"\"\n Elixir lib for creating Debian and RPM packages with Distillery.\n \"\"\"\n end\n\n defp package do\n [name: :distillery_packager,\n files: [\"lib\", \"mix.exs\", \"README*\", \"LICENSE*\", \"templates\"],\n maintainers: [\"18Months Dev Team \"],\n licenses: [\"MIT\"],\n links: %{\"GitHub\" => \"https:\/\/github.com\/18Months\/distillery_packager\",\n \"Docs\" => \"https:\/\/hexdocs.pm\/distillery_packager\"}]\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"69e7104225f787f6158f57033fc586ec42712a55","subject":"[PERF] Update 4.1.3","message":"[PERF] Update 4.1.3\n\n * Keep track of queue size instead of constantly querying the\n queue length\n","repos":"hazardfn\/riemannx","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Riemannx.Mixfile do\n use Mix.Project\n\n @version \"4.1.3\"\n\n def project do\n [\n app: :riemannx,\n version: @version,\n elixir: \"~> 1.7\",\n package: package(),\n description: \"A riemann client for elixir with UDP\/TCP\/TLS support.\",\n deps: deps(),\n test_coverage: [tool: ExCoveralls],\n preferred_cli_env: [\n coveralls: :test,\n \"coveralls.detail\": :test,\n \"coveralls.post\": :test,\n \"coveralls.html\": :test\n ],\n elixirc_paths: elixirc_paths(Mix.env()),\n aliases: [test: \"test --no-start\"],\n dialyzer:\n [\n ignore_warnings: \".\/dialyzer.ignore-warnings\",\n plt_add_apps: [:ssl, :stdlib, :public_key, :qex]\n ] ++ dialyzer(),\n docs: [\n main: \"Riemannx\",\n source_ref: \"v#{@version}\",\n source_url: \"https:\/\/github.com\/hazardfn\/riemannx\",\n extras: [\"README.md\"]\n ]\n ]\n end\n\n # Run \"mix help compile.app\" to learn about applications.\n def application do\n [\n included_applications: [:qex],\n applications: applications(Mix.env()),\n mod: {Riemannx.Application, []}\n ]\n end\n\n defp elixirc_paths(:test), do: [\"lib\", \"test\/servers\", \"test\/\"]\n defp elixirc_paths(_), do: [\"lib\"]\n\n defp applications(:test) do\n applications(:others) ++ [:propcheck]\n end\n\n defp applications(_) do\n [:poolboy, :logger, :exprotobuf]\n end\n\n defp deps do\n [\n {:exprotobuf, \"~> 1.2.17\"},\n {:poolboy, \"~> 1.5\"},\n {:excoveralls, \"~> 0.11\", only: [:test]},\n {:ex_doc, \"~> 0.21\", only: [:dev], runtime: false},\n {:propcheck, \"~> 1.1.5\", only: :test},\n {:dialyxir, \"~> 1.0.0-rc.6\", only: [:dev, :test], runtime: false},\n {:credo, \"~> 1.1.2\", only: [:dev, :test], runtime: false},\n {:qex, \"~> 0.5.0\"}\n ]\n end\n\n defp package do\n %{\n licenses: [\"MIT\"],\n maintainers: [\"Howard Beard-Marlowe\"],\n links: %{\"GitHub\" => \"https:\/\/github.com\/hazardfn\/riemannx\"}\n }\n end\n\n defp dialyzer do\n if travis?(),\n do: [plt_file: {:no_warn, System.get_env(\"PLT_LOCATION\")}],\n else: []\n end\n\n defp travis? do\n if System.get_env(\"TRAVIS\"), do: true, else: false\n end\nend\n","old_contents":"defmodule Riemannx.Mixfile do\n use Mix.Project\n\n @version \"4.1.2\"\n\n def project do\n [\n app: :riemannx,\n version: @version,\n elixir: \"~> 1.7\",\n package: package(),\n description: \"A riemann client for elixir with UDP\/TCP\/TLS support.\",\n deps: deps(),\n test_coverage: [tool: ExCoveralls],\n preferred_cli_env: [\n coveralls: :test,\n \"coveralls.detail\": :test,\n \"coveralls.post\": :test,\n \"coveralls.html\": :test\n ],\n elixirc_paths: elixirc_paths(Mix.env()),\n aliases: [test: \"test --no-start\"],\n dialyzer:\n [\n ignore_warnings: \".\/dialyzer.ignore-warnings\",\n plt_add_apps: [:ssl, :stdlib, :public_key, :qex]\n ] ++ dialyzer(),\n docs: [\n main: \"Riemannx\",\n source_ref: \"v#{@version}\",\n source_url: \"https:\/\/github.com\/hazardfn\/riemannx\",\n extras: [\"README.md\"]\n ]\n ]\n end\n\n # Run \"mix help compile.app\" to learn about applications.\n def application do\n [\n included_applications: [:qex],\n applications: applications(Mix.env()),\n mod: {Riemannx.Application, []}\n ]\n end\n\n defp elixirc_paths(:test), do: [\"lib\", \"test\/servers\", \"test\/\"]\n defp elixirc_paths(_), do: [\"lib\"]\n\n defp applications(:test) do\n applications(:others) ++ [:propcheck]\n end\n\n defp applications(_) do\n [:poolboy, :logger, :exprotobuf]\n end\n\n defp deps do\n [\n {:exprotobuf, \"~> 1.2.17\"},\n {:poolboy, \"~> 1.5\"},\n {:excoveralls, \"~> 0.11\", only: [:test]},\n {:ex_doc, \"~> 0.21\", only: [:dev], runtime: false},\n {:propcheck, \"~> 1.1.5\", only: :test},\n {:dialyxir, \"~> 1.0.0-rc.6\", only: [:dev, :test], runtime: false},\n {:credo, \"~> 1.1.2\", only: [:dev, :test], runtime: false},\n {:qex, \"~> 0.5.0\"}\n ]\n end\n\n defp package do\n %{\n licenses: [\"MIT\"],\n maintainers: [\"Howard Beard-Marlowe\"],\n links: %{\"GitHub\" => \"https:\/\/github.com\/hazardfn\/riemannx\"}\n }\n end\n\n defp dialyzer do\n if travis?(),\n do: [plt_file: {:no_warn, System.get_env(\"PLT_LOCATION\")}],\n else: []\n end\n\n defp travis? do\n if System.get_env(\"TRAVIS\"), do: true, else: false\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"883f1f85b1fcfef9f31c890ba33211d983117b07","subject":"Remove redundant applications list","message":"Remove redundant applications list\n","repos":"ellsclytn\/home-control,ellsclytn\/home-control","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Thermio.Mixfile do\n use Mix.Project\n\n def project do\n [app: :thermio,\n version: \"0.0.1\",\n elixir: \"~> 1.2\",\n elixirc_paths: elixirc_paths(Mix.env),\n compilers: [:phoenix, :gettext] ++ Mix.compilers,\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n aliases: aliases(),\n deps: deps()]\n end\n\n # Configuration for the OTP application.\n #\n # Type `mix help compile.app` for more information.\n def application do\n [mod: {Thermio, []},\n extra_applications: [:logger]]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"web\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\", \"web\"]\n\n # Specifies your project dependencies.\n #\n # Type `mix help deps` for examples and options.\n defp deps do\n [{:phoenix, \"~> 1.2.1\"},\n {:phoenix_pubsub, \"~> 1.0\"},\n {:phoenix_ecto, \"~> 3.0\"},\n {:postgrex, \">= 0.0.0\"},\n {:phoenix_html, \"~> 2.6\"},\n {:phoenix_live_reload, \"~> 1.0\", only: :dev},\n {:gettext, \"~> 0.11\"},\n {:cowboy, \"~> 1.0\"},\n {:joken, \"~> 1.1\"},\n {:hulaaki, \"~> 0.0.4\"},\n {:proper_case, \"~> 1.0.1\"},\n {:timex, \"~> 3.1\"},\n {:timex_ecto, \"~> 3.1\"},\n {:httpoison, \"~> 0.13\"}]\n end\n\n # Aliases are shortcuts or tasks specific to the current project.\n # For example, to create, migrate and run the seeds file at once:\n #\n # $ mix ecto.setup\n #\n # See the documentation for `Mix` for more info on aliases.\n defp aliases do\n [\"ecto.setup\": [\"ecto.create\", \"ecto.migrate\", \"run priv\/repo\/seeds.exs\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"],\n \"test\": [\"ecto.create --quiet\", \"ecto.migrate\", \"test\"]]\n end\nend\n","old_contents":"defmodule Thermio.Mixfile do\n use Mix.Project\n\n def project do\n [app: :thermio,\n version: \"0.0.1\",\n elixir: \"~> 1.2\",\n elixirc_paths: elixirc_paths(Mix.env),\n compilers: [:phoenix, :gettext] ++ Mix.compilers,\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n aliases: aliases(),\n deps: deps()]\n end\n\n # Configuration for the OTP application.\n #\n # Type `mix help compile.app` for more information.\n def application do\n [mod: {Thermio, []},\n applications: [:phoenix, :phoenix_pubsub, :phoenix_html, :cowboy, :logger, :gettext,\n :phoenix_ecto, :postgrex, :timex, :httpoison]]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"web\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\", \"web\"]\n\n # Specifies your project dependencies.\n #\n # Type `mix help deps` for examples and options.\n defp deps do\n [{:phoenix, \"~> 1.2.1\"},\n {:phoenix_pubsub, \"~> 1.0\"},\n {:phoenix_ecto, \"~> 3.0\"},\n {:postgrex, \">= 0.0.0\"},\n {:phoenix_html, \"~> 2.6\"},\n {:phoenix_live_reload, \"~> 1.0\", only: :dev},\n {:gettext, \"~> 0.11\"},\n {:cowboy, \"~> 1.0\"},\n {:joken, \"~> 1.1\"},\n {:hulaaki, \"~> 0.0.4\"},\n {:proper_case, \"~> 1.0.1\"},\n {:timex, \"~> 3.1\"},\n {:timex_ecto, \"~> 3.1\"},\n {:httpoison, \"~> 0.13\"}]\n end\n\n # Aliases are shortcuts or tasks specific to the current project.\n # For example, to create, migrate and run the seeds file at once:\n #\n # $ mix ecto.setup\n #\n # See the documentation for `Mix` for more info on aliases.\n defp aliases do\n [\"ecto.setup\": [\"ecto.create\", \"ecto.migrate\", \"run priv\/repo\/seeds.exs\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"],\n \"test\": [\"ecto.create --quiet\", \"ecto.migrate\", \"test\"]]\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"3d0da7467cd84b8fbc6e20bec8e4afe9c752157f","subject":"Version 0.1.0","message":"Version 0.1.0\n","repos":"bitwalker\/conform","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Conform.Mixfile do\n use Mix.Project\n\n def project do\n [app: :conform,\n version: \"0.1.0\",\n elixir: \"~> 0.13.2-dev\",\n escript_main_module: Conform,\n description: description,\n package: package,\n deps: deps]\n end\n\n def application do\n [applications: []]\n end\n defp deps, do: []\n defp description, do: \"Easy release configuration for Elixir apps.\"\n defp package do\n [ files: [\"lib\", \"priv\", \"mix.exs\", \"README.md\", \"LICENSE\"],\n contributors: [\"Paul Schoenfelder\"],\n licenses: [\"MIT\"],\n links: [ { \"GitHub\", \"https:\/\/github.com\/bitwalker\/conform\" } ] ]\n end\nend\n","old_contents":"defmodule Conform.Mixfile do\n use Mix.Project\n\n def project do\n [app: :conform,\n version: \"0.0.1\",\n elixir: \"~> 0.13.2-dev\",\n escript_main_module: Conform,\n description: description,\n package: package,\n deps: deps]\n end\n\n def application do\n [applications: []]\n end\n defp deps, do: []\n defp description, do: \"Easy release configuration for Elixir apps.\"\n defp package do\n [ files: [\"lib\", \"priv\", \"mix.exs\", \"README.md\", \"LICENSE\"],\n contributors: [\"Paul Schoenfelder\"],\n licenses: [\"MIT\"],\n links: [ { \"GitHub\", \"https:\/\/github.com\/bitwalker\/conform\" } ] ]\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"25090f077f1c23ccaa28144b0ec5e8ff0a12a4c3","subject":"Fix up typo in docs.","message":"Fix up typo in docs.\n","repos":"messagerocket\/pixie,messagerocket\/pixie","old_file":"lib\/pixie\/monitor.ex","new_file":"lib\/pixie\/monitor.ex","new_contents":"defmodule Pixie.Monitor do\n use Timex\n use Behaviour\n\n @moduledoc \"\"\"\n Allows you to monitor various events within Pixie.\n\n Internally Pixie.Monitor is implemented using GenEvent, so you're free to\n bypass using the Pixie.Monitor behaviour and use your own GenEvent if the\n need arises.\n\n Usage example:\n ```elixir\n defmodule MyMonitor do\n use Pixie.Monitor\n\n def created_channel channel_name, at do\n Logger.info \"Channel \\#\\{channel_name} created at \\#\\{format at}\"\n end\n\n def destroyed_channel channel_name, at do\n Logger.info \"Channel \\#\\{channel_name} destroyed at \\#\\{format at}\"\n end\n\n defp format timestamp do\n timestamp\n |> Date.from(:timestamp)\n |> DateFormat.format!(\"{UNIX}\")\n end\n end\n ```\n \"\"\"\n\n defmacro __using__(_opts) do\n quote do\n use GenEvent\n use Timex\n\n def handle_event({fun, args}, state) when is_atom(fun) and is_list(args) do\n apply __MODULE__, fun, args\n {:ok, state}\n end\n\n def created_client(_client_id, _at), do: :ok\n def destroyed_client(_client_id, _at), do: :ok\n def created_channel(_channel_name, _at), do: :ok\n def destroyed_channel(_channel_name, _at), do: :ok\n def client_subscribed(_client_id, _channel_name, _at), do: :ok\n def client_unsubscribed(_client_id, _channel_name, _at), do: :ok\n def received_message(_client_id, _message_id, _at), do: :ok\n def delivered_message(_client_id, _message_id, _at), do: :ok\n\n defoverridable [\n created_client: 2,\n destroyed_client: 2,\n created_channel: 2,\n destroyed_channel: 2,\n client_subscribed: 3,\n client_unsubscribed: 3,\n received_message: 3,\n delivered_message: 3\n ]\n end\n end\n\n @doc \"\"\"\n Called when a new client is created during protocol handshake.\n \"\"\"\n defcallback created_client(client_id :: binary, at :: {megasecs :: integer, seconds :: integer, microsecs :: integer}) :: atom\n\n @doc \"\"\"\n Called when a client is destroyed - either by an explicit disconnect request\n from the client, or by a system generated timeout.\n \"\"\"\n defcallback destroyed_client(client_id :: binary, at :: {megasecs :: integer, seconds :: integer, microsecs :: integer}) :: atom\n\n @doc \"\"\"\n Called when a new channel is created - this happens when a client subscribes\n to it for the first time.\n \"\"\"\n defcallback created_channel(channel_name :: binary, at :: {megasecs :: integer, seconds :: integer, microsecs :: integer}) :: atom\n\n @doc \"\"\"\n Called when a channel is destroyed - this happens when the last client\n unsubscribes from it.\n \"\"\"\n defcallback destroyed_channel(channel_name :: binary, at :: {megasecs :: integer, seconds :: integer, microsecs :: integer}) :: atom\n\n @doc \"\"\"\n Called when a client subscribes to a channel.\n \"\"\"\n defcallback client_subscribed(client_id :: binary, channel_name :: binary, at :: {megasecs :: integer, seconds :: integer, microsecs :: integer}) :: atom\n\n @doc \"\"\"\n Called when a client unsubscribes from a channel.\n \"\"\"\n defcallback client_unsubscribed(client_id :: binary, channel_name :: binary, at :: {megasecs :: integer, seconds :: integer, microsecs :: integer}) :: atom\n\n @doc \"\"\"\n Called when a message is received with the ID of the message.\n\n Some caveats:\n\n - This function is only called when a publish message is received, not when\n any protocol messages, such as connect or subscribe are received.\n - Message IDs are only unique per client, not globally.\n - If the message was generated on the server (ie via `Pixie.publish\/2`) then\n the Client ID is likely to be `nil`.\n \"\"\"\n defcallback received_message(client_id :: binary, message_id :: binary, at :: {megasecs :: integer, seconds :: integer, microsecs :: integer}) :: atom\n\n @doc \"\"\"\n Called when a message is delivered to a client.\n\n Some caveats:\n\n - This function is only called when a publish message is delivered, not when\n any protocol messages, such as connect or subscribe are.\n - Message IDs are only unique per client, not globally.\n - The Client ID is that of the *sender*, not the receiver.\n - If the message was generated on the server (ie via `Pixie.publish\/2`) then\n the Client ID is likely to be `nil`.\n - You will likely receive a lot of delivered calls for each received call\n as one message published to a channel may be relayed to thousands of\n receivers.\n \"\"\"\n defcallback delivered_message(client_id :: binary, message_id :: binary, at :: {megasecs :: integer, seconds :: integer, microsecs :: integer}) :: atom\n\n def start_link handlers do\n {:ok, pid} = GenEvent.start_link name: __MODULE__\n Enum.each handlers, fn\n {handler, args} ->\n add_handler handler, args\n handler ->\n add_handler handler, []\n end\n {:ok, pid}\n end\n\n @doc \"\"\"\n Allows you to add a `Pixie.Monitor` or any other `GenEvent` handler to the\n event stream. Expects the name of your handler module and any args which\n you wish to be provided to your module's `init\/1` callback.\n \"\"\"\n def add_handler handler, args \\\\ [] do\n GenEvent.add_handler __MODULE__, handler, args\n end\n\n @doc \"\"\"\n Called by the backend when a new client is created either by protocol\n handshake, or via `Pixie.subscribe\/2`\n \"\"\"\n def created_client client_id do\n GenEvent.notify __MODULE__, {:created_client, [client_id, Time.now]}\n end\n\n @doc \"\"\"\n Called by the backend when a client is destroyed, either by an expicit\n protocol disconnect or for a system generated reason, such as a timeout.\n \"\"\"\n def destroyed_client client_id do\n GenEvent.notify __MODULE__, {:destroyed_client, [client_id, Time.now]}\n end\n\n @doc \"\"\"\n Called by the backend when a new channel is created.\n New channels are created when the first client subscribes to them.\n \"\"\"\n def created_channel channel_name do\n GenEvent.notify __MODULE__, {:created_channel, [channel_name, Time.now]}\n end\n\n @doc \"\"\"\n Called by the backend when a channel is destroyed.\n Channels are destroyed when the last client unsubscribes from them.\n \"\"\"\n def destroyed_channel channel_name do\n GenEvent.notify __MODULE__, {:destroyed_channel, [channel_name, Time.now]}\n end\n\n @doc \"\"\"\n Called by the backend when a client subscribes to a channel.\n \"\"\"\n def client_subscribed client_id, channel_name do\n GenEvent.notify __MODULE__, {:client_subscribed, [client_id, channel_name, Time.now]}\n end\n\n @doc \"\"\"\n Called by the backend when a client unsubscribes from a channel.\n \"\"\"\n def client_unsubscribed client_id, channel_name do\n GenEvent.notify __MODULE__, {:client_unsubscribed, [client_id, channel_name, Time.now]}\n end\n\n @doc \"\"\"\n Called whenever a new message is received for publication.\n This includes server-generated messages using `Pixie.publish\/2`\n \"\"\"\n def received_message %Pixie.Message.Publish{client_id: client_id, id: message_id} do\n GenEvent.notify __MODULE__, {:received_message, [client_id, message_id, Time.now]}\n end\n def received_message(_), do: :ok\n\n @doc \"\"\"\n Called by adapters when a message is finally delivered to a client.\n \"\"\"\n def delivered_message %Pixie.Message.Publish{client_id: client_id, id: message_id} do\n GenEvent.notify __MODULE__, {:delivered_message, [client_id, message_id, Time.now]}\n end\n def delivered_message(_), do: :ok\n\nend\n","old_contents":"defmodule Pixie.Monitor do\n use Timex\n use Behaviour\n\n @moduledoc \"\"\"\n Allows you to monitor various events within Pixie.\n\n Internally Pixie.Monitor is implemented using GenEvent, so you're free to\n bypass using the Pixie.Monitor behaviour and use your own GenEvent if the\n need arises.\n\n Usage example:\n ```elixir\n defmodule MyMonitor do\n use Pixie.Monitor\n\n def created_channel channel_name, at do\n Logger.info \"Channel \\#\\{channel_name} created at \\#\\{format at}\")}\"\n end\n\n def destroyed_channel channel_name, at do\n Logger.info \"Channel \\#\\{channel_name} destroyed at \\#\\{format at}\")}\"\n end\n\n defp format timestamp do\n timestamp\n |> Date.from(:timestamp)\n |> DateFormat.format!(\"{UNIX}\")\n end\n end\n ```\n \"\"\"\n\n defmacro __using__(_opts) do\n quote do\n use GenEvent\n use Timex\n\n def handle_event({fun, args}, state) when is_atom(fun) and is_list(args) do\n apply __MODULE__, fun, args\n {:ok, state}\n end\n\n def created_client(_client_id, _at), do: :ok\n def destroyed_client(_client_id, _at), do: :ok\n def created_channel(_channel_name, _at), do: :ok\n def destroyed_channel(_channel_name, _at), do: :ok\n def client_subscribed(_client_id, _channel_name, _at), do: :ok\n def client_unsubscribed(_client_id, _channel_name, _at), do: :ok\n def received_message(_client_id, _message_id, _at), do: :ok\n def delivered_message(_client_id, _message_id, _at), do: :ok\n\n defoverridable [\n created_client: 2,\n destroyed_client: 2,\n created_channel: 2,\n destroyed_channel: 2,\n client_subscribed: 3,\n client_unsubscribed: 3,\n received_message: 3,\n delivered_message: 3\n ]\n end\n end\n\n @doc \"\"\"\n Called when a new client is created during protocol handshake.\n \"\"\"\n defcallback created_client(client_id :: binary, at :: {megasecs :: integer, seconds :: integer, microsecs :: integer}) :: atom\n\n @doc \"\"\"\n Called when a client is destroyed - either by an explicit disconnect request\n from the client, or by a system generated timeout.\n \"\"\"\n defcallback destroyed_client(client_id :: binary, at :: {megasecs :: integer, seconds :: integer, microsecs :: integer}) :: atom\n\n @doc \"\"\"\n Called when a new channel is created - this happens when a client subscribes\n to it for the first time.\n \"\"\"\n defcallback created_channel(channel_name :: binary, at :: {megasecs :: integer, seconds :: integer, microsecs :: integer}) :: atom\n\n @doc \"\"\"\n Called when a channel is destroyed - this happens when the last client\n unsubscribes from it.\n \"\"\"\n defcallback destroyed_channel(channel_name :: binary, at :: {megasecs :: integer, seconds :: integer, microsecs :: integer}) :: atom\n\n @doc \"\"\"\n Called when a client subscribes to a channel.\n \"\"\"\n defcallback client_subscribed(client_id :: binary, channel_name :: binary, at :: {megasecs :: integer, seconds :: integer, microsecs :: integer}) :: atom\n\n @doc \"\"\"\n Called when a client unsubscribes from a channel.\n \"\"\"\n defcallback client_unsubscribed(client_id :: binary, channel_name :: binary, at :: {megasecs :: integer, seconds :: integer, microsecs :: integer}) :: atom\n\n @doc \"\"\"\n Called when a message is received with the ID of the message.\n\n Some caveats:\n\n - This function is only called when a publish message is received, not when\n any protocol messages, such as connect or subscribe are received.\n - Message IDs are only unique per client, not globally.\n - If the message was generated on the server (ie via `Pixie.publish\/2`) then\n the Client ID is likely to be `nil`.\n \"\"\"\n defcallback received_message(client_id :: binary, message_id :: binary, at :: {megasecs :: integer, seconds :: integer, microsecs :: integer}) :: atom\n\n @doc \"\"\"\n Called when a message is delivered to a client.\n\n Some caveats:\n\n - This function is only called when a publish message is delivered, not when\n any protocol messages, such as connect or subscribe are.\n - Message IDs are only unique per client, not globally.\n - The Client ID is that of the *sender*, not the receiver.\n - If the message was generated on the server (ie via `Pixie.publish\/2`) then\n the Client ID is likely to be `nil`.\n - You will likely receive a lot of delivered calls for each received call\n as one message published to a channel may be relayed to thousands of\n receivers.\n \"\"\"\n defcallback delivered_message(client_id :: binary, message_id :: binary, at :: {megasecs :: integer, seconds :: integer, microsecs :: integer}) :: atom\n\n def start_link handlers do\n {:ok, pid} = GenEvent.start_link name: __MODULE__\n Enum.each handlers, fn\n {handler, args} ->\n add_handler handler, args\n handler ->\n add_handler handler, []\n end\n {:ok, pid}\n end\n\n @doc \"\"\"\n Allows you to add a `Pixie.Monitor` or any other `GenEvent` handler to the\n event stream. Expects the name of your handler module and any args which\n you wish to be provided to your module's `init\/1` callback.\n \"\"\"\n def add_handler handler, args \\\\ [] do\n GenEvent.add_handler __MODULE__, handler, args\n end\n\n @doc \"\"\"\n Called by the backend when a new client is created either by protocol\n handshake, or via `Pixie.subscribe\/2`\n \"\"\"\n def created_client client_id do\n GenEvent.notify __MODULE__, {:created_client, [client_id, Time.now]}\n end\n\n @doc \"\"\"\n Called by the backend when a client is destroyed, either by an expicit\n protocol disconnect or for a system generated reason, such as a timeout.\n \"\"\"\n def destroyed_client client_id do\n GenEvent.notify __MODULE__, {:destroyed_client, [client_id, Time.now]}\n end\n\n @doc \"\"\"\n Called by the backend when a new channel is created.\n New channels are created when the first client subscribes to them.\n \"\"\"\n def created_channel channel_name do\n GenEvent.notify __MODULE__, {:created_channel, [channel_name, Time.now]}\n end\n\n @doc \"\"\"\n Called by the backend when a channel is destroyed.\n Channels are destroyed when the last client unsubscribes from them.\n \"\"\"\n def destroyed_channel channel_name do\n GenEvent.notify __MODULE__, {:destroyed_channel, [channel_name, Time.now]}\n end\n\n @doc \"\"\"\n Called by the backend when a client subscribes to a channel.\n \"\"\"\n def client_subscribed client_id, channel_name do\n GenEvent.notify __MODULE__, {:client_subscribed, [client_id, channel_name, Time.now]}\n end\n\n @doc \"\"\"\n Called by the backend when a client unsubscribes from a channel.\n \"\"\"\n def client_unsubscribed client_id, channel_name do\n GenEvent.notify __MODULE__, {:client_unsubscribed, [client_id, channel_name, Time.now]}\n end\n\n @doc \"\"\"\n Called whenever a new message is received for publication.\n This includes server-generated messages using `Pixie.publish\/2`\n \"\"\"\n def received_message %Pixie.Message.Publish{client_id: client_id, id: message_id} do\n GenEvent.notify __MODULE__, {:received_message, [client_id, message_id, Time.now]}\n end\n def received_message(_), do: :ok\n\n @doc \"\"\"\n Called by adapters when a message is finally delivered to a client.\n \"\"\"\n def delivered_message %Pixie.Message.Publish{client_id: client_id, id: message_id} do\n GenEvent.notify __MODULE__, {:delivered_message, [client_id, message_id, Time.now]}\n end\n def delivered_message(_), do: :ok\n\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"8cbd37eee8b04a1d94c1dd5985920f4e4a2e386a","subject":"Fixing small bug with users that have not seen any resources","message":"Fixing small bug with users that have not seen any resources\n","repos":"houshuang\/survey,houshuang\/survey","old_file":"web\/models\/resources.ex","new_file":"web\/models\/resources.ex","new_contents":"defmodule Survey.Resource do\n use Survey.Web, :model\n alias Survey.Repo\n import Ecto.Query\n require Ecto.Query\n alias Ecto.Adapters.SQL\n\n schema \"resources\" do\n field :name, :string\n field :url, :string\n field :tags, {:array, :string}\n field :description, :string\n field :generic, :boolean\n field :comments, {:array, Survey.JSON}\n field :old_desc, {:array, Survey.JSON}\n field :old_tags, {:array, Survey.JSON}\n field :score, :float\n field :old_score, {:array, Survey.JSON}\n belongs_to :sig, Survey.SIG\n belongs_to :user, Survey.User\n timestamps\n end\n\n # returns ID of an entry with a given URL, or nil if it doesn't exist\n def find_url(url, sig \\\\ nil) do\n req = from t in Survey.Resource,\n where: t.url == ^url,\n select: t.id,\n limit: 1\n if sig do\n req = from t in req, where: t.sig_id == ^sig\n end\n req |> Repo.one\n end\n\n def get_resource(id) do\n (from t in Survey.Resource,\n where: t.id == ^id,\n join: u in assoc(t, :user),\n preload: [user: u])\n |> Repo.one\n end\n\n # how many resources submitted by user\n def user_submitted_no(userid) do\n req = from t in Survey.Resource,\n where: t.user_id == ^userid,\n select: count(t.id)\n req |> Repo.one\n end\n\n # how many resources reviewed by user\n def user_reviewed_no(userid) do\n req = from t in Survey.User,\n where: t.id == ^userid,\n select: fragment(\"cardinality(?)\", [t.resources_seen])\n req |> Repo.one\n end\n\n def get_all_by_sigs do\n (from t in Survey.Resource,\n join: s in assoc(t, :sig),\n join: u in assoc(t, :user),\n preload: [sig: s, user: u])\n |> Repo.all\n |> Enum.group_by(fn x -> x.sig.name end)\n end\n\n def update_seen(user, id) do\n seen = user.resources_seen\n if !seen, do: seen = []\n if not id in seen do\n %{ user | resources_seen: [ id | seen ]} |> Repo.update!\n end\n end\n\n def tag_freq(sig) do\n sigsearch = if sig do\n \"where sig_id = #{sig}\"\n else\n \"\"\n end\n runq(\"\n WITH tags AS (SELECT unnest(tags) AS tag FROM resources\n #{sigsearch}) SELECT tag, \n count(tag) AS COUNT FROM tags GROUP BY tag;\")\n |> Enum.map(fn {tag, count} -> \n %{text: tag, weight: count, link: \"#\"} end)\n |> Poison.encode!\n end\n\n def resource_list(sig, tag \\\\ nil) do \n query = from t in Survey.Resource,\n order_by: [fragment(\"coalesce(?, -999)\", t.score), asc: t.score, asc: t.name]\n\n if sig do\n query = from t in query, where: (t.sig_id == ^sig) or (t.generic == true)\n end\n\n if tag do\n query = query |> and_and(:tags, [tag])\n end\n\n query \n |> Repo.all\n |> Enum.group_by(fn x -> x.sig_id == sig end)\n end\n\n def user_seen?(user, resourceid) do\n user[:resources_seen] && Enum.member?(user.resources_seen, resourceid)\n end\n\n defp and_and(query, col, val) when is_list(val) and is_atom(col) do\n from p in query, where: fragment(\"? && ?\", ^val, field(p, ^col))\n end\n\n # returns the id of a random resource fit for a given user, and adds it\n # to that users \"has seen\" list\n def get_random(user) do\n :random.seed(:os.timestamp)\n\n seen = user.resources_seen || []\n\n available_ids = \n (from f in Survey.Resource,\n where: not (f.id in ^seen),\n where: not (f.user_id == ^user.id),\n where: (f.sig_id == ^user.sig_id) or \n (f.generic == true),\n select: f.id)\n |> Repo.all\n\n if length(available_ids) == 0 do\n nil\n else\n selected = :random.uniform(length(available_ids)) - 1\n s_id = Enum.at(available_ids, selected)\n update_seen(user, s_id)\n\n s_id\n end\n end\n\n def runq(query, opts \\\\ []) do\n result = SQL.query(Survey.Repo, query, [])\n result.rows\n end\n\nend\n","old_contents":"defmodule Survey.Resource do\n use Survey.Web, :model\n alias Survey.Repo\n import Ecto.Query\n require Ecto.Query\n alias Ecto.Adapters.SQL\n\n schema \"resources\" do\n field :name, :string\n field :url, :string\n field :tags, {:array, :string}\n field :description, :string\n field :generic, :boolean\n field :comments, {:array, Survey.JSON}\n field :old_desc, {:array, Survey.JSON}\n field :old_tags, {:array, Survey.JSON}\n field :score, :float\n field :old_score, {:array, Survey.JSON}\n belongs_to :sig, Survey.SIG\n belongs_to :user, Survey.User\n timestamps\n end\n\n # returns ID of an entry with a given URL, or nil if it doesn't exist\n def find_url(url, sig \\\\ nil) do\n req = from t in Survey.Resource,\n where: t.url == ^url,\n select: t.id,\n limit: 1\n if sig do\n req = from t in req, where: t.sig_id == ^sig\n end\n req |> Repo.one\n end\n\n def get_resource(id) do\n (from t in Survey.Resource,\n where: t.id == ^id,\n join: u in assoc(t, :user),\n preload: [user: u])\n |> Repo.one\n end\n\n # how many resources submitted by user\n def user_submitted_no(userid) do\n req = from t in Survey.Resource,\n where: t.user_id == ^userid,\n select: count(t.id)\n req |> Repo.one\n end\n\n # how many resources reviewed by user\n def user_reviewed_no(userid) do\n req = from t in Survey.User,\n where: t.id == ^userid,\n select: fragment(\"cardinality(?)\", [t.resources_seen])\n req |> Repo.one\n end\n\n def get_all_by_sigs do\n (from t in Survey.Resource,\n join: s in assoc(t, :sig),\n join: u in assoc(t, :user),\n preload: [sig: s, user: u])\n |> Repo.all\n |> Enum.group_by(fn x -> x.sig.name end)\n end\n\n def update_seen(user, id) do\n seen = user.resources_seen\n if !seen, do: seen = []\n if not id in seen do\n %{ user | resources_seen: [ id | seen ]} |> Repo.update!\n end\n end\n\n def tag_freq(sig) do\n sigsearch = if sig do\n \"where sig_id = #{sig}\"\n else\n \"\"\n end\n runq(\"\n WITH tags AS (SELECT unnest(tags) AS tag FROM resources\n #{sigsearch}) SELECT tag, \n count(tag) AS COUNT FROM tags GROUP BY tag;\")\n |> Enum.map(fn {tag, count} -> \n %{text: tag, weight: count, link: \"#\"} end)\n |> Poison.encode!\n end\n\n def resource_list(sig, tag \\\\ nil) do \n query = from t in Survey.Resource,\n order_by: [fragment(\"coalesce(?, -999)\", t.score), asc: t.score, asc: t.name]\n\n if sig do\n query = from t in query, where: (t.sig_id == ^sig) or (t.generic == true)\n end\n\n if tag do\n query = query |> and_and(:tags, [tag])\n end\n\n query \n |> Repo.all\n |> Enum.group_by(fn x -> x.sig_id == sig end)\n end\n\n def user_seen?(user, resourceid) do\n IO.inspect(user)\n Enum.member?(user.resources_seen, resourceid)\n end\n\n defp and_and(query, col, val) when is_list(val) and is_atom(col) do\n from p in query, where: fragment(\"? && ?\", ^val, field(p, ^col))\n end\n\n # returns the id of a random resource fit for a given user, and adds it\n # to that users \"has seen\" list\n def get_random(user) do\n :random.seed(:os.timestamp)\n\n seen = user.resources_seen || []\n\n available_ids = \n (from f in Survey.Resource,\n where: not (f.id in ^seen),\n where: not (f.user_id == ^user.id),\n where: (f.sig_id == ^user.sig_id) or \n (f.generic == true),\n select: f.id)\n |> Repo.all\n\n if length(available_ids) == 0 do\n nil\n else\n selected = :random.uniform(length(available_ids)) - 1\n s_id = Enum.at(available_ids, selected)\n update_seen(user, s_id)\n\n s_id\n end\n end\n\n def runq(query, opts \\\\ []) do\n result = SQL.query(Survey.Repo, query, [])\n result.rows\n end\n\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"6533eaa9848e55cf4ce92702d8509e6e434746b2","subject":"fix error view","message":"fix error view\n","repos":"OpenAperture\/manager,OpenAperture\/manager","old_file":"web\/views\/error_view.ex","new_file":"web\/views\/error_view.ex","new_contents":"require Logger\ndefmodule OpenAperture.ErrorView do\n use OpenAperture.Manager.Web, :view\n\n def render(\"404.html\", assigns) do\n log_error(\"[Manager][ErrorView][404]\", assigns)\n \"Page not found - 404\"\n end\n\n def render(\"500.html\", assigns) do\n log_error(\"[Manager][ErrorView][500]\", assigns)\n \"Server internal error - 500\"\n end\n\n # In case no render clause matches or no\n # template is found, let's render it as 500\n def template_not_found(status, assigns) do\n log_error(\"[Manager][ErrorView][#{inspect status}]\", assigns)\n render \"500.html\", assigns\n end\n\n defp log_error(prefix, assigns) do\n try do\n error_map = Map.from_struct(assigns[:reason])\n if error_map[:message] != nil do\n Logger.error(\"#{prefix} #{assigns[:reason].message}\")\n else\n Logger.error(\"#{prefix} #{inspect assigns[:reason]}\")\n end\n catch\n :exit, code -> Logger.error(\"#{prefix} Exited with code #{inspect code}\")\n :throw, value -> Logger.error(\"#{prefix} Throw called with #{inspect value}\")\n what, value -> Logger.error(\"#{prefix} Caught #{inspect what} with #{inspect value}\")\n end \n end\nend\n","old_contents":"defmodule OpenAperture.Manager.ErrorView do\n use OpenAperture.Manager.Web, :view\n\n def render(\"404.html\", _assigns) do\n \"Page not found - 404\"\n end\n\n def render(\"500.html\", _assigns) do\n \"Server internal error - 500\"\n end\n\n # In case no render clause matches or no\n # template is found, let's render it as 500\n def template_not_found(_, assigns) do\n render \"500.html\", assigns\n end\nend\n","returncode":0,"stderr":"","license":"mpl-2.0","lang":"Elixir"} {"commit":"d9417df9e86691d7143ff0e5f59637eb722de304","subject":"build warning (#549)","message":"build warning (#549)\n\nwarning: variable \"err\" is unused\r\n lib\/mix\/lib\/releases\/runtime\/pidfile.ex:50","repos":"bitwalker\/distillery,bitwalker\/distillery","old_file":"lib\/mix\/lib\/releases\/runtime\/pidfile.ex","new_file":"lib\/mix\/lib\/releases\/runtime\/pidfile.ex","new_contents":"defmodule Mix.Releases.Runtime.Pidfile do\n @moduledoc \"\"\"\n This is a kernel process which will maintain a pidfile for the running node\n \"\"\"\n\n @doc false\n # Will be called by `:init`\n def start() do\n # We don't need to link to `:init`, it will take care\n # of linking to us, since we're being started as a kernel process\n pid = spawn(__MODULE__, :init, [self(), Process.whereis(:init)])\n\n receive do\n {:ok, ^pid} = ok ->\n ok\n\n {:ignore, ^pid} ->\n :ignore\n\n {:error, ^pid, reason} ->\n {:error, reason}\n end\n end\n\n @doc false\n def init(starter, parent) do\n me = self()\n\n case Application.get_env(:kernel, :pidfile, System.get_env(\"PIDFILE\")) do\n nil ->\n # No config, so no need for this process\n send(starter, {:ignore, me})\n\n path when is_binary(path) ->\n pid = :os.getpid()\n case :prim_file.write_file(path, List.to_string(pid)) do\n :ok ->\n # We've written the pid, so proceed\n Process.flag(:trap_exit, true)\n\n # Register\n Process.register(me, __MODULE__)\n\n # We're started!\n send(starter, {:ok, me})\n \n # Enter receive loop\n loop(%{pidfile: path}, starter, parent)\n\n {:error, reason} ->\n send(starter, {:error, me, {:invalid_pidfile, path, reason}})\n end\n\n path ->\n send(starter, {:error, me, {:invalid_pidfile_config, path}})\n end\n end\n\n defp loop(%{pidfile: path} = state, starter, parent) do\n receive do\n {:EXIT, pid, reason} when pid in [starter, parent] ->\n # Cleanup pidfile\n _ = :prim_file.delete(path)\n exit(reason)\n\n _ ->\n loop(state, starter, parent)\n after\n 5_000 ->\n if exists?(path) do\n loop(state, starter, parent)\n else\n :init.stop()\n end\n end\n end\n \n defp exists?(path) do\n case :prim_file.read_file_info(path) do\n {:error, _} ->\n false\n {:ok, _info} ->\n true\n end\n end\nend\n","old_contents":"defmodule Mix.Releases.Runtime.Pidfile do\n @moduledoc \"\"\"\n This is a kernel process which will maintain a pidfile for the running node\n \"\"\"\n\n @doc false\n # Will be called by `:init`\n def start() do\n # We don't need to link to `:init`, it will take care\n # of linking to us, since we're being started as a kernel process\n pid = spawn(__MODULE__, :init, [self(), Process.whereis(:init)])\n\n receive do\n {:ok, ^pid} = ok ->\n ok\n\n {:ignore, ^pid} ->\n :ignore\n\n {:error, ^pid, reason} ->\n {:error, reason}\n end\n end\n\n @doc false\n def init(starter, parent) do\n me = self()\n\n case Application.get_env(:kernel, :pidfile, System.get_env(\"PIDFILE\")) do\n nil ->\n # No config, so no need for this process\n send(starter, {:ignore, me})\n\n path when is_binary(path) ->\n pid = :os.getpid()\n case :prim_file.write_file(path, List.to_string(pid)) do\n :ok ->\n # We've written the pid, so proceed\n Process.flag(:trap_exit, true)\n\n # Register\n Process.register(me, __MODULE__)\n\n # We're started!\n send(starter, {:ok, me})\n \n # Enter receive loop\n loop(%{pidfile: path}, starter, parent)\n\n {:error, reason} = err ->\n send(starter, {:error, me, {:invalid_pidfile, path, reason}})\n end\n\n path ->\n send(starter, {:error, me, {:invalid_pidfile_config, path}})\n end\n end\n\n defp loop(%{pidfile: path} = state, starter, parent) do\n receive do\n {:EXIT, pid, reason} when pid in [starter, parent] ->\n # Cleanup pidfile\n _ = :prim_file.delete(path)\n exit(reason)\n\n _ ->\n loop(state, starter, parent)\n after\n 5_000 ->\n if exists?(path) do\n loop(state, starter, parent)\n else\n :init.stop()\n end\n end\n end\n \n defp exists?(path) do\n case :prim_file.read_file_info(path) do\n {:error, _} ->\n false\n {:ok, _info} ->\n true\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"471cf0a37a10d39c1697a4a84c95bf47ce097495","subject":"Remove IO.puts\/1 from test","message":"Remove IO.puts\/1 from test\n","repos":"rrrene\/credo,rrrene\/credo","old_file":"test\/credo\/code\/strings_test.exs","new_file":"test\/credo\/code\/strings_test.exs","new_contents":"defmodule Credo.Code.StringsTest do\n use Credo.Test.Case\n\n alias Credo.Code.Strings\n\n test \"it should return the source without string literals 2\" do\n source = \"\"\"\n @moduledoc \\\"\\\"\\\"\n this is an example # TODO: and this is no actual comment\n \\\"\\\"\\\"\n\n x = ~s{also: # TODO: no comment here}\n ?\" # TODO: this is the third\n # \"\n\n \"also: # TODO: no comment here as well\"\n \"\"\"\n\n expected =\n \"\"\"\n @moduledoc \\\"\\\"\\\"\n @@EMPTY_STRING@@\n \\\"\\\"\\\"\n\n x = ~s{ }\n ?\" # TODO: this is the third\n # \"\n\n \" \"\n \"\"\"\n |> String.replace(\n \"@@EMPTY_STRING@@\",\n \" \"\n )\n\n assert expected == source |> Strings.replace_with_spaces()\n end\n\n test \"it should return the source without string sigils 2\" do\n source = \"\"\"\n should \"not error for a quote in a heredoc\" do\n errors = ~s(\n \\\"\\\"\\\"\n this is an example \" TODO: and this is no actual comment\n \\\"\\\"\\\") |> lint\n assert [] == errors\n end\n \"\"\"\n\n result = source |> Strings.replace_with_spaces()\n assert source != result\n assert String.length(source) == String.length(result)\n refute String.contains?(result, \"example\")\n refute String.contains?(result, \"TODO:\")\n end\n\n test \"it should return the source without string sigils 3\" do\n source = ~S\"\"\"\n def gen_name(name) when is_binary(name),\n do: \"#{String.replace_suffix(name, \"-test\", \"\")}_name\"\n \"\"\"\n\n expected = ~S\"\"\"\n def gen_name(name) when is_binary(name),\n do: \" \"\n \"\"\"\n\n assert expected == Strings.replace_with_spaces(source)\n end\n\n test \"it should work with custom sigils\" do\n source = ~S[\n defmodule Foo do\n custom =\n ~X\"\"\"\n \"\"\"\n\n literal = \"anything\"\n end\n ]\n\n expected = ~S[\n defmodule Foo do\n custom =\n ~X\"\"\"\n \"\"\"\n\n literal = \" \"\n end\n ]\n\n assert expected == Strings.replace_with_spaces(source)\n end\n\n test \"it should return the source without string literals 3\" do\n source = \"\"\"\n x = \"\u2191 \u2197 \u2192\"\n x = ~s|text|\n x = ~s\"text\"\n x = ~s'text'\n x = ~s(text)\n x = ~s[text]\n x = ~s{text}\n x = ~s\n x = ~S|text|\n x = ~S\"text\"\n x = ~S'text'\n x = ~S(text)\n x = ~S[text]\n x = ~S{text}\n x = ~S\n x = to_string('text') <> \"text\"\n ?\" # <-- this is not a string\n \"\"\"\n\n expected = \"\"\"\n x = \" \"\n x = ~s| |\n x = ~s\" \"\n x = ~s' '\n x = ~s( )\n x = ~s[ ]\n x = ~s{ }\n x = ~s< >\n x = ~S| |\n x = ~S\" \"\n x = ~S' '\n x = ~S( )\n x = ~S[ ]\n x = ~S{ }\n x = ~S< >\n x = to_string('text') <> \" \"\n ?\" # <-- this is not a string\n \"\"\"\n\n assert expected == source |> Strings.replace_with_spaces()\n end\n\n test \"it should return the source without string sigils and replace the contents\" do\n source = \"\"\"\n t = ~s({\n })\n \"\"\"\n\n expected = \"\"\"\n t = ~s(.\n .)\n \"\"\"\n\n result = source |> Strings.replace_with_spaces(\".\")\n assert expected == result\n end\n\n test \"it should not modify commented out code\" do\n source = \"\"\"\n defmodule Foo do\n defmodule Bar do\n # @doc \\\"\\\"\\\"\n # Reassign a student to a discussion group.\n # This will un-assign student from the current discussion group\n # \\\"\\\"\\\"\n # def assign_group(leader = %User{}, student = %User{}) do\n # cond do\n # leader.role == :student ->\n # {:error, :invalid}\n #\n # student.role != :student ->\n # {:error, :invalid}\n #\n # true ->\n # Repo.transaction(fn ->\n # {:ok, _} = unassign_group(student)\n #\n # %Group{}\n # |> Group.changeset(%{})\n # |> put_assoc(:leader, leader)\n # |> put_assoc(:student, student)\n # |> Repo.insert!()\n # end)\n # end\n # end\n def baz, do: 123\n end\n end\n \"\"\"\n\n expected = source\n\n assert expected == source |> Strings.replace_with_spaces(\".\")\n end\n\n test \"it should NOT report expected code 2\" do\n input = ~S\"\"\"\n escape_charlist('\"\\\\' ++ r)\n \"\"\"\n\n assert input == Strings.replace_with_spaces(input)\n end\n\n test \"it should replace interpolations\" do\n input = ~S\"\"\"\n x = \"#{~s(Hello, #{name})}\"\n \"\"\"\n\n expected = ~S\"\"\"\n x = \" \"\n \"\"\"\n\n assert expected == Strings.replace_with_spaces(input)\n end\n\n @example_code File.read!(\"test\/fixtures\/example_code\/nested_escaped_heredocs.ex\")\n test \"it should produce valid code \/2\" do\n result = Strings.replace_with_spaces(@example_code)\n result2 = Strings.replace_with_spaces(result)\n\n assert result == result2\n assert match?({:ok, _}, Code.string_to_quoted(result))\n end\n\n @tag slow: :disk_io\n @example_code2 File.read!(\"test\/fixtures\/example_code\/large_heredoc.ex\")\n test \"it should produce valid code \/3\" do\n result = Strings.replace_with_spaces(@example_code2)\n result2 = Strings.replace_with_spaces(result)\n\n assert result == result2\n assert match?({:ok, _}, Code.string_to_quoted(result))\n end\n\n @tag slow: :disk_io\n test \"it should produce valid code \/5\" do\n example_code = File.read!(\"test\/fixtures\/example_code\/browser.ex\")\n\n result =\n example_code\n |> to_source_file()\n |> Strings.replace_with_spaces(\".\", \".\")\n\n result2 =\n result\n |> Strings.replace_with_spaces(\".\", \".\")\n\n assert match?({:ok, _}, Code.string_to_quoted(result))\n\n assert result == result2, \"Strings.replace_with_spaces\/2 should be idempotent\"\n end\n\n @tag slow: :disk_io\n test \"it should produce valid code with empty string as replacement \/5\" do\n example_code = File.read!(\"test\/fixtures\/example_code\/browser.ex\")\n\n result =\n example_code\n |> to_source_file()\n |> Strings.replace_with_spaces(\"\", \"\")\n\n result2 =\n result\n |> Strings.replace_with_spaces(\"\", \"\")\n\n assert match?({:ok, _}, Code.string_to_quoted(result))\n\n assert result == result2, \"Strings.replace_with_spaces\/2 should be idempotent\"\n end\nend\n","old_contents":"defmodule Credo.Code.StringsTest do\n use Credo.Test.Case\n\n alias Credo.Code.Strings\n\n test \"it should return the source without string literals 2\" do\n source = \"\"\"\n @moduledoc \\\"\\\"\\\"\n this is an example # TODO: and this is no actual comment\n \\\"\\\"\\\"\n\n x = ~s{also: # TODO: no comment here}\n ?\" # TODO: this is the third\n # \"\n\n \"also: # TODO: no comment here as well\"\n \"\"\"\n\n expected =\n \"\"\"\n @moduledoc \\\"\\\"\\\"\n @@EMPTY_STRING@@\n \\\"\\\"\\\"\n\n x = ~s{ }\n ?\" # TODO: this is the third\n # \"\n\n \" \"\n \"\"\"\n |> String.replace(\n \"@@EMPTY_STRING@@\",\n \" \"\n )\n\n assert expected == source |> Strings.replace_with_spaces()\n end\n\n test \"it should return the source without string sigils 2\" do\n source = \"\"\"\n should \"not error for a quote in a heredoc\" do\n errors = ~s(\n \\\"\\\"\\\"\n this is an example \" TODO: and this is no actual comment\n \\\"\\\"\\\") |> lint\n assert [] == errors\n end\n \"\"\"\n\n result = source |> Strings.replace_with_spaces()\n assert source != result\n assert String.length(source) == String.length(result)\n refute String.contains?(result, \"example\")\n refute String.contains?(result, \"TODO:\")\n end\n\n test \"it should return the source without string sigils 3\" do\n source = ~S\"\"\"\n def gen_name(name) when is_binary(name),\n do: \"#{String.replace_suffix(name, \"-test\", \"\")}_name\"\n \"\"\"\n\n expected = ~S\"\"\"\n def gen_name(name) when is_binary(name),\n do: \" \"\n \"\"\"\n\n assert expected == Strings.replace_with_spaces(source)\n end\n\n test \"it should work with custom sigils\" do\n source = ~S[\n defmodule Foo do\n custom =\n ~X\"\"\"\n \"\"\"\n\n literal = \"anything\"\n end\n ]\n\n expected = ~S[\n defmodule Foo do\n custom =\n ~X\"\"\"\n \"\"\"\n\n literal = \" \"\n end\n ]\n\n assert expected == Strings.replace_with_spaces(source)\n end\n\n test \"it should return the source without string literals 3\" do\n source = \"\"\"\n x = \"\u2191 \u2197 \u2192\"\n x = ~s|text|\n x = ~s\"text\"\n x = ~s'text'\n x = ~s(text)\n x = ~s[text]\n x = ~s{text}\n x = ~s\n x = ~S|text|\n x = ~S\"text\"\n x = ~S'text'\n x = ~S(text)\n x = ~S[text]\n x = ~S{text}\n x = ~S\n x = to_string('text') <> \"text\"\n ?\" # <-- this is not a string\n \"\"\"\n\n expected = \"\"\"\n x = \" \"\n x = ~s| |\n x = ~s\" \"\n x = ~s' '\n x = ~s( )\n x = ~s[ ]\n x = ~s{ }\n x = ~s< >\n x = ~S| |\n x = ~S\" \"\n x = ~S' '\n x = ~S( )\n x = ~S[ ]\n x = ~S{ }\n x = ~S< >\n x = to_string('text') <> \" \"\n ?\" # <-- this is not a string\n \"\"\"\n\n assert expected == source |> Strings.replace_with_spaces()\n end\n\n test \"it should return the source without string sigils and replace the contents\" do\n source = \"\"\"\n t = ~s({\n })\n \"\"\"\n\n expected = \"\"\"\n t = ~s(.\n .)\n \"\"\"\n\n result = source |> Strings.replace_with_spaces(\".\")\n assert expected == result\n end\n\n test \"it should not modify commented out code\" do\n source = \"\"\"\n defmodule Foo do\n defmodule Bar do\n # @doc \\\"\\\"\\\"\n # Reassign a student to a discussion group.\n # This will un-assign student from the current discussion group\n # \\\"\\\"\\\"\n # def assign_group(leader = %User{}, student = %User{}) do\n # cond do\n # leader.role == :student ->\n # {:error, :invalid}\n #\n # student.role != :student ->\n # {:error, :invalid}\n #\n # true ->\n # Repo.transaction(fn ->\n # {:ok, _} = unassign_group(student)\n #\n # %Group{}\n # |> Group.changeset(%{})\n # |> put_assoc(:leader, leader)\n # |> put_assoc(:student, student)\n # |> Repo.insert!()\n # end)\n # end\n # end\n def baz, do: 123\n end\n end\n \"\"\"\n\n expected = source\n\n assert expected == source |> Strings.replace_with_spaces(\".\")\n end\n\n test \"it should NOT report expected code 2\" do\n input = ~S\"\"\"\n escape_charlist('\"\\\\' ++ r)\n \"\"\"\n\n assert input == Strings.replace_with_spaces(input)\n end\n\n test \"it should replace interpolations\" do\n input = ~S\"\"\"\n x = \"#{~s(Hello, #{name})}\"\n \"\"\"\n\n expected = ~S\"\"\"\n x = \" \"\n \"\"\"\n\n assert expected == Strings.replace_with_spaces(input)\n end\n\n @example_code File.read!(\"test\/fixtures\/example_code\/nested_escaped_heredocs.ex\")\n test \"it should produce valid code \/2\" do\n result = Strings.replace_with_spaces(@example_code)\n result2 = Strings.replace_with_spaces(result)\n\n assert result == result2\n assert match?({:ok, _}, Code.string_to_quoted(result))\n end\n\n @tag slow: :disk_io\n @example_code2 File.read!(\"test\/fixtures\/example_code\/large_heredoc.ex\")\n test \"it should produce valid code \/3\" do\n result = Strings.replace_with_spaces(@example_code2)\n result2 = Strings.replace_with_spaces(result)\n\n assert result == result2\n assert match?({:ok, _}, Code.string_to_quoted(result))\n end\n\n @tag slow: :disk_io\n test \"it should produce valid code \/5\" do\n example_code = File.read!(\"test\/fixtures\/example_code\/browser.ex\")\n\n result =\n example_code\n |> to_source_file()\n |> Strings.replace_with_spaces(\".\", \".\")\n\n result2 =\n result\n |> Strings.replace_with_spaces(\".\", \".\")\n\n assert match?({:ok, _}, Code.string_to_quoted(result))\n\n assert result == result2, \"Strings.replace_with_spaces\/2 should be idempotent\"\n end\n\n @tag slow: :disk_io\n test \"it should produce valid code with empty string as replacement \/5\" do\n example_code = File.read!(\"test\/fixtures\/example_code\/browser.ex\")\n\n result =\n example_code\n |> to_source_file()\n |> Strings.replace_with_spaces(\"\", \"\")\n\n result2 =\n result\n |> Strings.replace_with_spaces(\"\", \"\")\n\n IO.puts(result)\n assert match?({:ok, _}, Code.string_to_quoted(result))\n\n assert result == result2, \"Strings.replace_with_spaces\/2 should be idempotent\"\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"1ffe4ce359cf74ff591ec1dc8b19123a69d400fe","subject":"Remove newlines before comparison","message":"Remove newlines before comparison\n","repos":"hashrocket\/tilex,hashrocket\/tilex,hashrocket\/tilex","old_file":"test\/features\/visitor_views_stats_test.exs","new_file":"test\/features\/visitor_views_stats_test.exs","new_contents":"defmodule Features.VisitorViewsStatsTest do\n use Tilex.IntegrationCase, async: true\n\n def text_without_newlines(element) do\n String.replace(Wallaby.Element.text(element), \"\\n\", \" \")\n end\n\n test \"sees total number of posts by channel\", %{session: session} do\n\n target_channel = Factory.insert!(:channel, name: \"phoenix\")\n other_channel = Factory.insert!(:channel, name: \"other\")\n\n Factory.insert!(:post, title: \"functional programming rocks\", channel: target_channel)\n\n Enum.each([\"i'm fine\", \"all these people out here\", \"what?\"], fn(title) ->\n Factory.insert!(:post, title: title, channel: other_channel)\n end)\n\n visit(session, \"\/statistics\")\n channels = find(session, Query.css(\".stats_column ul#channels\"))\n\n query = Query.css(\".stats_column header\", text: \"5 posts in 2 channels\")\n channels_header = find(session, query)\n assert(channels_header)\n\n [ other_channel, phoenix_channel ] = all(channels, Query.css(\"li\"))\n\n assert text_without_newlines(other_channel) =~ \"#other 3 posts\"\n assert text_without_newlines(phoenix_channel) =~ \"#phoenix 1 post\"\n end\n\n test \"sees most liked tils\", %{session: session} do\n posts = [\n \"Controllers\",\n \"Views\",\n \"Templates\",\n ]\n\n Factory.insert!(:channel, name: \"phoenix\")\n\n posts\n |> Enum.with_index\n |> Enum.each(fn({title, likes}) ->\n Factory.insert!(:post, title: title, likes: likes + 1)\n end)\n\n visit(session, \"\/statistics\")\n\n most_liked_posts = find(session, Query.css(\"article.most_liked_posts\"))\n channels_header = find(most_liked_posts, Query.css(\"header\"))\n\n assert Wallaby.Element.text(channels_header) =~ \"Most liked TILs\"\n\n [ fast_tests, slow_tests, insert_mode ] = all(most_liked_posts, Query.css(\"li\"))\n\n assert text_without_newlines(fast_tests) =~ \"Templates #phoenix \u2022 3 likes\"\n assert text_without_newlines(slow_tests) =~ \"Views #phoenix \u2022 2 likes\"\n assert text_without_newlines(insert_mode) =~ \"Controllers #phoenix \u2022 1 like\"\n end\n\n test \"sees til activity\", %{session: session} do\n dt = fn ({_y, _m, _d} = date) ->\n Ecto.DateTime.cast!({date, {12, 0, 0}})\n end\n\n today = Timex.today\n day_of_the_week = :calendar.day_of_the_week(Date.to_erl(Timex.today))\n\n duration = Timex.Duration.from_days((day_of_the_week - 1) + 7)\n previous_monday = Timex.subtract(today, duration)\n\n previous_tuesday = Timex.add(previous_monday, Timex.Duration.from_days(1))\n previous_wednesday = Timex.add(previous_monday, Timex.Duration.from_days(2))\n\n Factory.insert!(:post, title: \"Vim rules\", inserted_at: dt.(Date.to_erl(previous_monday)))\n Factory.insert!(:post, title: \"Vim rules\", inserted_at: dt.(Date.to_erl(previous_tuesday)))\n Factory.insert!(:post, title: \"Vim rules\", inserted_at: dt.(Date.to_erl(previous_tuesday)))\n Factory.insert!(:post, title: \"Vim rules\", inserted_at: dt.(Date.to_erl(previous_wednesday)))\n Factory.insert!(:post, title: \"Vim rules\", inserted_at: dt.(Date.to_erl(previous_wednesday)))\n Factory.insert!(:post, title: \"Vim rules\", inserted_at: dt.(Date.to_erl(previous_wednesday)))\n\n visit(session, \"\/statistics\")\n activity_tag = find(session, Query.css(\"ul#activity\"))\n\n find(activity_tag,\n Query.css(\"li[data-amount='1'][data-date='Mon, #{Timex.format!(previous_monday, \"%b %e\", :strftime)}']\")\n )\n find(activity_tag,\n Query.css(\"li[data-amount='2'][data-date='Tue, #{Timex.format!(previous_tuesday, \"%b %e\", :strftime)}']\")\n )\n find(activity_tag,\n Query.css(\"li[data-amount='3'][data-date='Wed, #{Timex.format!(previous_wednesday, \"%b %-e\", :strftime)}']\")\n )\n end\nend\n","old_contents":"defmodule Features.VisitorViewsStatsTest do\n use Tilex.IntegrationCase, async: true\n\n test \"sees total number of posts by channel\", %{session: session} do\n\n target_channel = Factory.insert!(:channel, name: \"phoenix\")\n other_channel = Factory.insert!(:channel, name: \"other\")\n\n Factory.insert!(:post, title: \"functional programming rocks\", channel: target_channel)\n\n Enum.each([\"i'm fine\", \"all these people out here\", \"what?\"], fn(title) ->\n Factory.insert!(:post, title: title, channel: other_channel)\n end)\n\n visit(session, \"\/statistics\")\n channels = find(session, Query.css(\".stats_column ul#channels\"))\n\n query = Query.css(\".stats_column header\", text: \"5 posts in 2 channels\")\n channels_header = find(session, query)\n assert(channels_header)\n\n [ other_channel, phoenix_channel ] = all(channels, Query.css(\"li\"))\n\n assert Wallaby.Element.text(other_channel) =~ \"#other\\n3 posts\"\n assert Wallaby.Element.text(phoenix_channel) =~ \"#phoenix\\n1 post\"\n end\n\n test \"sees most liked tils\", %{session: session} do\n posts = [\n \"Controllers\",\n \"Views\",\n \"Templates\",\n ]\n\n Factory.insert!(:channel, name: \"phoenix\")\n\n posts\n |> Enum.with_index\n |> Enum.each(fn({title, likes}) ->\n Factory.insert!(:post, title: title, likes: likes + 1)\n end)\n\n visit(session, \"\/statistics\")\n\n most_liked_posts = find(session, Query.css(\"article.most_liked_posts\"))\n channels_header = find(most_liked_posts, Query.css(\"header\"))\n\n assert Wallaby.Element.text(channels_header) =~ \"Most liked TILs\"\n\n [ fast_tests, slow_tests, insert_mode ] = all(most_liked_posts, Query.css(\"li\"))\n\n assert Wallaby.Element.text(fast_tests) =~ \"Templates\\n#phoenix \u2022 3 likes\"\n assert Wallaby.Element.text(slow_tests) =~ \"Views\\n#phoenix \u2022 2 likes\"\n assert Wallaby.Element.text(insert_mode) =~ \"Controllers\\n#phoenix \u2022 1 like\"\n end\n\n test \"sees til activity\", %{session: session} do\n dt = fn ({_y, _m, _d} = date) ->\n Ecto.DateTime.cast!({date, {12, 0, 0}})\n end\n\n today = Timex.today\n day_of_the_week = :calendar.day_of_the_week(Date.to_erl(Timex.today))\n\n duration = Timex.Duration.from_days((day_of_the_week - 1) + 7)\n previous_monday = Timex.subtract(today, duration)\n\n previous_tuesday = Timex.add(previous_monday, Timex.Duration.from_days(1))\n previous_wednesday = Timex.add(previous_monday, Timex.Duration.from_days(2))\n\n Factory.insert!(:post, title: \"Vim rules\", inserted_at: dt.(Date.to_erl(previous_monday)))\n Factory.insert!(:post, title: \"Vim rules\", inserted_at: dt.(Date.to_erl(previous_tuesday)))\n Factory.insert!(:post, title: \"Vim rules\", inserted_at: dt.(Date.to_erl(previous_tuesday)))\n Factory.insert!(:post, title: \"Vim rules\", inserted_at: dt.(Date.to_erl(previous_wednesday)))\n Factory.insert!(:post, title: \"Vim rules\", inserted_at: dt.(Date.to_erl(previous_wednesday)))\n Factory.insert!(:post, title: \"Vim rules\", inserted_at: dt.(Date.to_erl(previous_wednesday)))\n\n visit(session, \"\/statistics\")\n activity_tag = find(session, Query.css(\"ul#activity\"))\n\n find(activity_tag,\n Query.css(\"li[data-amount='1'][data-date='Mon, #{Timex.format!(previous_monday, \"%b %e\", :strftime)}']\")\n )\n find(activity_tag,\n Query.css(\"li[data-amount='2'][data-date='Tue, #{Timex.format!(previous_tuesday, \"%b %e\", :strftime)}']\")\n )\n find(activity_tag,\n Query.css(\"li[data-amount='3'][data-date='Wed, #{Timex.format!(previous_wednesday, \"%b %-e\", :strftime)}']\")\n )\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"1b91b8836437d617651a207fc2aa6f3b836707af","subject":"Update static manifest location","message":"Update static manifest location\n\nhttps:\/\/gist.github.com\/chrismccord\/71ab10d433c98b714b75c886eff17357\n","repos":"hashrocket\/tilex,hashrocket\/tilex,hashrocket\/tilex","old_file":"config\/prod.exs","new_file":"config\/prod.exs","new_contents":"use Mix.Config\n\n# For production, we configure the host to read the PORT\n# from the system environment. Therefore, you will need\n# to set PORT=80 before running your server.\n#\n# You should also configure the url host to something\n# meaningful, we use this information when generating URLs.\n#\n# Finally, we also include the path to a manifest\n# containing the digested version of static files. This\n# manifest is generated by the mix phoenix.digest task\n# which you typically run after static files are built.\nconfig :tilex, TilexWeb.Endpoint,\n http: [port: {:system, \"PORT\"}],\n url: [host: System.get_env(\"HOST\"), port: 80],\n cache_static_manifest: \"priv\/static\/cache_manifest.json\",\n secret_key_base: System.get_env(\"SECRET_KEY_BASE\")\n\n# Do not print debug messages in production\nconfig :logger, level: :info\n\nconfig :tilex, Tilex.Repo,\n adapter: Ecto.Adapters.Postgres,\n url: System.get_env(\"DATABASE_URL\"),\n pool_size: String.to_integer(System.get_env(\"POOL_SIZE\") || \"10\"),\n ssl: true\n\n# ## SSL Support\n#\n# To get SSL working, you will need to add the `https` key\n# to the previous section and set your `:url` port to 443:\n#\n# config :tilex, TilexWeb.Endpoint,\n# ...\n# url: [host: \"example.com\", port: 443],\n# https: [port: 443,\n# keyfile: System.get_env(\"SOME_APP_SSL_KEY_PATH\"),\n# certfile: System.get_env(\"SOME_APP_SSL_CERT_PATH\")]\n#\n# Where those two env variables return an absolute path to\n# the key and cert in disk or a relative path inside priv,\n# for example \"priv\/ssl\/server.key\".\n#\n# We also recommend setting `force_ssl`, ensuring no data is\n# ever sent via http, always redirecting to https:\nconfig :tilex, TilexWeb.Endpoint, force_ssl: [rewrite_on: [:x_forwarded_proto]]\n\n# Check `Plug.SSL` for all available options in `force_ssl`.\n\n# ## Using releases\n#\n# If you are doing OTP releases, you need to instruct Phoenix\n# to start the server for all endpoints:\n#\n# config :phoenix, :serve_endpoints, true\n#\n# Alternatively, you can configure exactly which server to\n# start per endpoint:\n#\n# config :tilex, TilexWeb.Endpoint, server: true\n#\n\n# Finally import the config\/prod.secret.exs\n# which should be versioned separately.\n\nif System.get_env(\"ENABLE_BASIC_AUTH\") do\n config :tilex, :basic_auth,\n realm: \"tilex\",\n username: System.get_env(\"BASIC_AUTH_USERNAME\"),\n password: System.get_env(\"BASIC_AUTH_PASSWORD\")\nend\n\nconfig :tilex, :page_size, 50\nconfig :tilex, :ga_identifier, System.get_env(\"GA_IDENTIFIER\")\n\nconfig :appsignal, :config, active: true\n\nconfig :tilex, :page_size, 50\n","old_contents":"use Mix.Config\n\n# For production, we configure the host to read the PORT\n# from the system environment. Therefore, you will need\n# to set PORT=80 before running your server.\n#\n# You should also configure the url host to something\n# meaningful, we use this information when generating URLs.\n#\n# Finally, we also include the path to a manifest\n# containing the digested version of static files. This\n# manifest is generated by the mix phoenix.digest task\n# which you typically run after static files are built.\nconfig :tilex, TilexWeb.Endpoint,\n http: [port: {:system, \"PORT\"}],\n url: [host: System.get_env(\"HOST\"), port: 80],\n cache_static_manifest: \"priv\/static\/manifest.json\",\n secret_key_base: System.get_env(\"SECRET_KEY_BASE\")\n\n# Do not print debug messages in production\nconfig :logger, level: :info\n\nconfig :tilex, Tilex.Repo,\n adapter: Ecto.Adapters.Postgres,\n url: System.get_env(\"DATABASE_URL\"),\n pool_size: String.to_integer(System.get_env(\"POOL_SIZE\") || \"10\"),\n ssl: true\n\n# ## SSL Support\n#\n# To get SSL working, you will need to add the `https` key\n# to the previous section and set your `:url` port to 443:\n#\n# config :tilex, TilexWeb.Endpoint,\n# ...\n# url: [host: \"example.com\", port: 443],\n# https: [port: 443,\n# keyfile: System.get_env(\"SOME_APP_SSL_KEY_PATH\"),\n# certfile: System.get_env(\"SOME_APP_SSL_CERT_PATH\")]\n#\n# Where those two env variables return an absolute path to\n# the key and cert in disk or a relative path inside priv,\n# for example \"priv\/ssl\/server.key\".\n#\n# We also recommend setting `force_ssl`, ensuring no data is\n# ever sent via http, always redirecting to https:\nconfig :tilex, TilexWeb.Endpoint, force_ssl: [rewrite_on: [:x_forwarded_proto]]\n\n# Check `Plug.SSL` for all available options in `force_ssl`.\n\n# ## Using releases\n#\n# If you are doing OTP releases, you need to instruct Phoenix\n# to start the server for all endpoints:\n#\n# config :phoenix, :serve_endpoints, true\n#\n# Alternatively, you can configure exactly which server to\n# start per endpoint:\n#\n# config :tilex, TilexWeb.Endpoint, server: true\n#\n\n# Finally import the config\/prod.secret.exs\n# which should be versioned separately.\n\nif System.get_env(\"ENABLE_BASIC_AUTH\") do\n config :tilex, :basic_auth,\n realm: \"tilex\",\n username: System.get_env(\"BASIC_AUTH_USERNAME\"),\n password: System.get_env(\"BASIC_AUTH_PASSWORD\")\nend\n\nconfig :tilex, :page_size, 50\nconfig :tilex, :ga_identifier, System.get_env(\"GA_IDENTIFIER\")\n\nconfig :appsignal, :config, active: true\n\nconfig :tilex, :page_size, 50\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"4de448d68dea9f7da46d20230886f684704e3535","subject":"Prepare for Heroku deployment","message":"Prepare for Heroku deployment\n","repos":"wojtekmach\/mr-rebase,wojtekmach\/mr-rebase","old_file":"config\/prod.exs","new_file":"config\/prod.exs","new_contents":"use Mix.Config\n\n# For production, we configure the host to read the PORT\n# from the system environment. Therefore, you will need\n# to set PORT=80 before running your server.\n#\n# You should also configure the url host to something\n# meaningful, we use this information when generating URLs.\n#\n# Finally, we also include the path to a manifest\n# containing the digested version of static files. This\n# manifest is generated by the mix phoenix.digest task\n# which you typically run after static files are built.\nconfig :mr_rebase, MrRebase.Endpoint,\n http: [port: {:system, \"PORT\"}],\n url: [scheme: \"https\", host: \"mr-rebase.herokuapp.com\", port: 443],\n force_ssl: [rewrite_on: [:x_forwarded_proto]],\n cache_static_manifest: \"priv\/static\/manifest.json\",\n secret_key_base: System.get_env(\"SECRET_KEY_BASE\")\n\nconfig :mr_rebase, MrRebase.Repo,\n adapter: Ecto.Adapters.Postgres,\n url: System.get_env(\"DATABASE_URL\"),\n pool_size: 20\n\n# Do not print debug messages in production\nconfig :logger, level: :info\n\n# ## SSL Support\n#\n# To get SSL working, you will need to add the `https` key\n# to the previous section and set your `:url` port to 443:\n#\n# config :mr_rebase, MrRebase.Endpoint,\n# ...\n# url: [host: \"example.com\", port: 443],\n# https: [port: 443,\n# keyfile: System.get_env(\"SOME_APP_SSL_KEY_PATH\"),\n# certfile: System.get_env(\"SOME_APP_SSL_CERT_PATH\")]\n#\n# Where those two env variables return an absolute path to\n# the key and cert in disk or a relative path inside priv,\n# for example \"priv\/ssl\/server.key\".\n#\n# We also recommend setting `force_ssl`, ensuring no data is\n# ever sent via http, always redirecting to https:\n#\n# config :mr_rebase, MrRebase.Endpoint,\n# force_ssl: [hsts: true]\n#\n# Check `Plug.SSL` for all available options in `force_ssl`.\n\n# ## Using releases\n#\n# If you are doing OTP releases, you need to instruct Phoenix\n# to start the server for all endpoints:\n#\n# config :phoenix, :serve_endpoints, true\n#\n# Alternatively, you can configure exactly which server to\n# start per endpoint:\n#\n# config :mr_rebase, MrRebase.Endpoint, server: true\n#\n# You will also need to set the application root to `.` in order\n# for the new static assets to be served after a hot upgrade:\n#\n# config :mr_rebase, MrRebase.Endpoint, root: \".\"\n\n# Finally import the config\/prod.secret.exs\n# which should be versioned separately.\n","old_contents":"use Mix.Config\n\n# For production, we configure the host to read the PORT\n# from the system environment. Therefore, you will need\n# to set PORT=80 before running your server.\n#\n# You should also configure the url host to something\n# meaningful, we use this information when generating URLs.\n#\n# Finally, we also include the path to a manifest\n# containing the digested version of static files. This\n# manifest is generated by the mix phoenix.digest task\n# which you typically run after static files are built.\nconfig :mr_rebase, MrRebase.Endpoint,\n http: [port: {:system, \"PORT\"}],\n url: [host: \"example.com\", port: 80],\n cache_static_manifest: \"priv\/static\/manifest.json\"\n\n# Do not print debug messages in production\nconfig :logger, level: :info\n\n# ## SSL Support\n#\n# To get SSL working, you will need to add the `https` key\n# to the previous section and set your `:url` port to 443:\n#\n# config :mr_rebase, MrRebase.Endpoint,\n# ...\n# url: [host: \"example.com\", port: 443],\n# https: [port: 443,\n# keyfile: System.get_env(\"SOME_APP_SSL_KEY_PATH\"),\n# certfile: System.get_env(\"SOME_APP_SSL_CERT_PATH\")]\n#\n# Where those two env variables return an absolute path to\n# the key and cert in disk or a relative path inside priv,\n# for example \"priv\/ssl\/server.key\".\n#\n# We also recommend setting `force_ssl`, ensuring no data is\n# ever sent via http, always redirecting to https:\n#\n# config :mr_rebase, MrRebase.Endpoint,\n# force_ssl: [hsts: true]\n#\n# Check `Plug.SSL` for all available options in `force_ssl`.\n\n# ## Using releases\n#\n# If you are doing OTP releases, you need to instruct Phoenix\n# to start the server for all endpoints:\n#\n# config :phoenix, :serve_endpoints, true\n#\n# Alternatively, you can configure exactly which server to\n# start per endpoint:\n#\n# config :mr_rebase, MrRebase.Endpoint, server: true\n#\n# You will also need to set the application root to `.` in order\n# for the new static assets to be served after a hot upgrade:\n#\n# config :mr_rebase, MrRebase.Endpoint, root: \".\"\n\n# Finally import the config\/prod.secret.exs\n# which should be versioned separately.\nimport_config \"prod.secret.exs\"\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"cc7dc8b11a5437dd2c0fe13bb5ce7a2b90177ccc","subject":"switch to selenium server","message":"switch to selenium server","repos":"cincinnati-elixir\/todos_phoenix_ember_example,cincinnati-elixir\/todos_phoenix_ember_example,cincinnati-elixir\/todos_phoenix_ember_example","old_file":"config\/test.exs","new_file":"config\/test.exs","new_contents":"use Mix.Config\n\n# We don't run a server during test. If one is required,\n# you can enable the server option below.\nconfig :todo_channels, TodoChannels.Endpoint,\n http: [port: 4001],\n server: true\n\n# Print only warnings and errors during test\nconfig :logger, level: :warn\n\nconfig :hound, driver: \"selenium\"\n\n# Configure your database\nconfig :todo_channels, TodoChannels.Repo,\n adapter: Ecto.Adapters.Postgres,\n database: \"todo_channels_test\",\n size: 1 # Use a single connection for transactional tests\n","old_contents":"use Mix.Config\n\n# We don't run a server during test. If one is required,\n# you can enable the server option below.\nconfig :todo_channels, TodoChannels.Endpoint,\n http: [port: 4001],\n server: true\n\n# Print only warnings and errors during test\nconfig :logger, level: :warn\n\nconfig :hound, driver: \"chrome_driver\"\n\n# Configure your database\nconfig :todo_channels, TodoChannels.Repo,\n adapter: Ecto.Adapters.Postgres,\n database: \"todo_channels_test\",\n size: 1 # Use a single connection for transactional tests\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"25100e2e079fde56810d21c5a07bdc7d4193a2de","subject":"update :ip","message":"update :ip\n","repos":"zzats\/processmon,zzats\/processmon","old_file":"lib\/Processmon\/HTTP\/HTTP.ex","new_file":"lib\/Processmon\/HTTP\/HTTP.ex","new_contents":"defmodule Processmon.HTTP do\n \n use GenServer\n\n def start_link(name) do\n GenServer.start_link(__MODULE__, :ok, [name: name])\n end\n\n @doc \"\"\"\n Standard init\n \"\"\"\n\n def init(:ok) do\n IO.puts(\"Starting the HTTP server process in port 8080\")\n start_server()\n end\n\n def start_server do\n dispatch = :cowboy_router.compile([\n {:_, [\n {\"\/\", :cowboy_static, {:priv_file, :processmon, \"index.html\"}},\n {\"\/static\/[...]\", :cowboy_static, {:priv_dir, :processmon, \"static\"}},\n {\"\/websocket\", WebsocketHandler, []}\n ]}\n ])\n {:ok, res} = :cowboy.start_http(:http_listener, 100, [{:ip, {127,0,0,1}}, port: 8080], [env: [dispatch: dispatch]])\n end\n\n ### Callbacks\n\n def handle_cast(_, state) do\n {:noreply, nil, state}\n end\n\n def handle_call(_, _from, state) do\n {:noreply, nil, state}\n end\n\nend","old_contents":"defmodule Processmon.HTTP do\n \n use GenServer\n\n def start_link(name) do\n GenServer.start_link(__MODULE__, :ok, [name: name])\n end\n\n @doc \"\"\"\n Standard init\n \"\"\"\n\n def init(:ok) do\n IO.puts(\"Starting the HTTP server process in port 8080\")\n start_server()\n end\n\n def start_server do\n dispatch = :cowboy_router.compile([\n {:_, [\n {\"\/\", :cowboy_static, {:priv_file, :processmon, \"index.html\"}},\n {\"\/static\/[...]\", :cowboy_static, {:priv_dir, :processmon, \"static\"}},\n {\"\/websocket\", WebsocketHandler, []}\n ]}\n ])\n {:ok, res} = :cowboy.start_http(:http_listener, 100, [{ip, {127,0,0,1}}, port: 8080], [env: [dispatch: dispatch]])\n end\n\n ### Callbacks\n\n def handle_cast(_, state) do\n {:noreply, nil, state}\n end\n\n def handle_call(_, _from, state) do\n {:noreply, nil, state}\n end\n\nend","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"1881652eef17ae96614cf089b7b439bce3700fd2","subject":"Commented debugs on method caller.","message":"Commented debugs on method caller.\n","repos":"serverboards\/serverboards,serverboards\/serverboards,serverboards\/serverboards,serverboards\/serverboards,serverboards\/serverboards","old_file":"backend\/apps\/mom\/lib\/MOM\/RPC\/method_caller.ex","new_file":"backend\/apps\/mom\/lib\/MOM\/RPC\/method_caller.ex","new_contents":"require Logger\n\ndefmodule Serverboards.MOM.RPC.MethodCaller do\n @moduledoc ~S\"\"\"\n This module stores methods to be called later.\n\n They are stored in an execute efficient way, and allow to have a list\n of methods to allow introspection (`dir` method).\n\n Can be connected with a RPC gateway with `add_method_caller`\n\n ## Example\n\n iex> alias Serverboards.MOM.RPC.MethodCaller\n iex> {:ok, mc} = MethodCaller.start_link\n iex> MethodCaller.add_method mc, \"ping\", fn _ -> \"pong\" end, async: false\n iex> MethodCaller.call mc, \"ping\", [], nil\n {:ok, \"pong\"}\n iex> MethodCaller.call mc, \"dir\", [], nil\n {:ok, [\"dir\", \"ping\"]}\n\n \"\"\"\n\n alias Serverboards.MOM.RPC\n\n def start_link(options \\\\ []) do\n {:ok, pid} = Agent.start_link fn -> %{ methods: %{}, mc: [], guards: [] } end, options\n\n add_method pid, \"dir\", fn _, context ->\n __dir(pid, context)\n end, [async: false, context: true]\n\n {:ok, pid}\n end\n\n def stop(pid) do\n Agent.stop pid\n end\n\n def debug(false) do\n false\n end\n\n def debug(pid) do\n st = Agent.get pid, &(&1)\n %{\n methods: (Map.keys st.methods),\n mc: Enum.map(st.mc, fn\n {mc, options} when is_function(mc) ->\n name = Keyword.get options, :name, (inspect mc)\n \"fn #{name}\"\n {pid, _options} when is_pid(pid) -> debug(pid)\n _ -> \"??\"\n end)\n }\n end\n\n def __dir(pid, context) when is_pid(pid) do\n st = Agent.get pid, &(&1)\n local = st.methods\n |> Enum.flat_map(fn {name, {_, options}} ->\n if check_guards(%Serverboards.MOM.RPC.Message{ method: name, context: context}, options, st.guards) do\n [name]\n else\n []\n end\n end)\n other = Enum.flat_map( st.mc, fn {smc, options} ->\n if check_guards(%Serverboards.MOM.RPC.Message{ method: \"dir\", context: context}, options, st.guards) do\n __dir(smc, context)\n else\n []\n end\n end)\n Enum.uniq Enum.sort( local ++ other )\n end\n\n def __dir(f, context) when is_function(f) do\n try do\n case f.(%RPC.Message{method: \"dir\", context: context}) do\n {:ok, l} when is_list(l) -> l\n _o ->\n Logger.error(\"dir dir not return list at #{inspect f}. Please fix.\")\n []\n end\n rescue\n e ->\n Logger.error(\"dir not implemented at #{inspect f}. Please fix.\\n#{inspect e}\\n#{ Exception.format_stacktrace System.stacktrace }\")\n []\n end\n end\n\n @doc ~S\"\"\"\n Adds a method to be called later.\n\n Method function must returns:\n\n * {:ok, v} -- Ok value\n * {:error, v} -- Error to return to client\n * v -- Ok value\n\n Options may be:\n\n * `async`, default true. Execute in another task, returns a promise.\n * `context`, the called function will be called with the client context. It is a Serverboards.MOM.RPC.Context\n\n ## Example\n\n iex> alias Serverboards.MOM.RPC.MethodCaller\n iex> {:ok, mc} = MethodCaller.start_link\n iex> MethodCaller.add_method mc, \"test_ok\", fn _ -> {:ok, :response_ok} end\n iex> MethodCaller.add_method mc, \"test_error\", fn _ -> {:error, :response_error} end\n iex> MethodCaller.add_method mc, \"test_plain\", fn _ -> :response_plain_ok end\n iex> MethodCaller.call mc, \"test_ok\", [], nil\n {:ok, :response_ok}\n iex> MethodCaller.call mc, \"test_error\", [], nil\n {:error, :response_error}\n iex> MethodCaller.call mc, \"test_plain\", [], nil\n {:ok, :response_plain_ok}\n\n \"\"\"\n def add_method(pid, name, f, options \\\\ []) do\n Agent.update pid, fn st ->\n %{ st | methods: Map.put(st.methods, name, {f, options})}\n end\n :ok\n end\n\n @doc ~S\"\"\"\n Method callers can be chained, so that if current does not resolve, try on another\n\n This another caller can be even shared between several method callers.\n\n Method callers are optimized callers, but a single function can be passed and\n it will be called with an %RPC.Message. If it returns {:ok, res} or\n {:error, error} its processed, :empty or :nok tries next callers.\n\n ## Example:\n\n I will create three method callers, so that a calls, and b too. Method can\n be shadowed at parent too.\n\n iex> alias Serverboards.MOM.RPC.{MethodCaller, Context}\n iex> {:ok, a} = MethodCaller.start_link\n iex> {:ok, b} = MethodCaller.start_link\n iex> {:ok, c} = MethodCaller.start_link\n iex> MethodCaller.add_method a, \"a\", fn _ -> :a end\n iex> MethodCaller.add_method b, \"b\", fn _ -> :b end\n iex> MethodCaller.add_method c, \"c\", fn _ -> :c end\n iex> MethodCaller.add_method c, \"c_\", fn _, context -> {:c, Context.get(context, :user, nil)} end, context: true\n iex> MethodCaller.add_method_caller a, c\n iex> MethodCaller.add_method_caller b, c\n iex> {:ok, context} = Context.start_link\n iex> Context.set context, :user, :me\n iex> MethodCaller.call a, \"c\", [], context\n {:ok, :c}\n iex> MethodCaller.call a, \"c_\", [], context\n {:ok, {:c, :me}}\n iex> MethodCaller.call b, \"c\", [], context\n {:ok, :c}\n iex> MethodCaller.call b, \"c_\", [], context\n {:ok, {:c, :me}}\n iex> MethodCaller.add_method a, \"c\", fn _ -> :shadow end\n iex> MethodCaller.call a, \"c\", [], context\n {:ok, :shadow}\n iex> MethodCaller.call b, \"c\", [], context\n {:ok, :c}\n iex> MethodCaller.call b, \"d\", [], context\n {:error, :unknown_method}\n\n Custom method caller that calls a function\n\n iex> alias Serverboards.MOM.RPC.MethodCaller\n iex> {:ok, mc} = MethodCaller.start_link\n iex> MethodCaller.add_method_caller(mc, fn msg ->\n ...> case msg.method do\n ...> \"hello.\"<>ret -> {:ok, ret}\n ...> _ -> :nok\n ...> end\n ...> end)\n iex> MethodCaller.call mc, \"hello.world\", [], nil\n {:ok, \"world\"}\n iex> MethodCaller.call mc, \"world.hello\", [], nil\n {:error, :unknown_method}\n\n \"\"\"\n def add_method_caller(pid, pid, _) do\n raise Exception, \"Cant add a method caller to itself.\"\n end\n def add_method_caller(pid, nmc, options) when is_pid(pid) do\n #Logger.debug(\"Add caller #{inspect nmc} to #{inspect pid}\")\n Agent.update pid, fn st ->\n %{ st | mc: st.mc ++ [{nmc, options}] }\n end\n :ok\n end\n def add_method_caller(pid, nmc), do: add_method_caller(pid, nmc, [])\n\n\n @doc ~S\"\"\"\n Adds a guard to the method caller\n\n This guards are used to ensure that a called method is allowed.\n\n If the mehtod is not allowed, it will be skipped as if never added, and\n `dir` will not return it neither.\n\n Guards are functions that receive the RPC message and the options of the\n method, and return true or false as they allow or not that method.\n This way generic guards can be created.\n\n name is a debug name used to log what guard failed. Any error\/exception on\n guards are interpreted as denial. Clause errors are not logged. Other errors\n are reraised.\n\n The very same \"dir\" that would be called with a method aller can have guards\n that prevent its call, but the dir implementation has to make sure to return\n only the approved methods.\n\n ## Example\n\n It creates a classic method and a function method caller. Both do the same.\n\n iex> require Logger\n iex> {:ok, mc} = start_link\n iex> add_method mc, \"echo\", &(&1), require_perm: \"echo\"\n iex> add_method_caller mc, fn\n ...> %{ method: \"dir\" } -> {:ok, [\"echo_fn\"]}\n ...> %{ method: \"echo_fn\", params: params } -> {:ok, params}\n ...> _ -> {:error, :unknown_method }\n ...> end, require_perm: \"echo\"\n iex> add_guard mc, \"perms\", fn %{ context: context }, options ->\n ...> case Keyword.get(options, :require_perm) do\n ...> nil -> true # no require perms, ok\n ...> required_perm ->\n ...> Enum.member? Map.get(context, :perms, []), required_perm\n ...> end\n ...> end\n iex> call mc, \"echo\", [1,2,3], %{ } # no context\n {:error, :unknown_method}\n iex> call mc, \"echo\", [1,2,3], %{ perms: [] } # no perms\n {:error, :unknown_method}\n iex> call mc, \"echo\", [1,2,3], %{ perms: [\"echo\"] } # no perms\n {:ok, [1,2,3]}\n iex> call mc, \"echo_fn\", [1,2,3], %{ } # no context\n {:error, :unknown_method}\n iex> call mc, \"echo_fn\", [1,2,3], %{ perms: [] } # no perms\n {:error, :unknown_method}\n iex> call mc, \"echo_fn\", [1,2,3], %{ perms: [\"echo\"] } # no perms\n {:ok, [1,2,3]}\n iex> call mc, \"dir\", [], %{}\n {:ok, [\"dir\"]}\n iex> call mc, \"dir\", [], %{ perms: [\"echo\"] }\n {:ok, [\"dir\", \"echo\", \"echo_fn\"]}\n\n In this example a map is used as context. Normally it would be a RPC.Context.\n \"\"\"\n def add_guard(pid, name, guard_f) when is_pid(pid) and is_function(guard_f) do\n Agent.update pid, fn st ->\n %{ st | guards: st.guards ++ [{name, guard_f}] }\n end\n end\n\n # Checks all the guards, return false if any fails.\n defp check_guards(%Serverboards.MOM.RPC.Message{}, _, []), do: true\n defp check_guards(%Serverboards.MOM.RPC.Message{} = msg, options, [{gname, gf} | rest]) do\n try do\n if gf.(msg, options) do\n #Logger.debug(\"Guard #{inspect msg} #{inspect gname} allowed pass\")\n check_guards(msg, options, rest)\n else\n #Logger.debug(\"Guard #{inspect msg} #{inspect gname} STOPPED pass\")\n false\n end\n rescue\n FunctionClauseError ->\n #Logger.debug(\"Guard #{inspect msg} #{inspect gname} STOPPED pass (Function Clause Error)\")\n false\n e ->\n Logger.error(\"Error checking method caller guard #{gname}: #{inspect e}\\n#{Exception.format_stacktrace}\")\n false\n end\n end\n\n @doc ~S\"\"\"\n Calls a method by name.\n\n Waits for execution always. Independent of async.\n\n Returns one of:\n\n * {:ok, v}\n * {:error, e}\n\n \"\"\"\n def call(pid, method, params, context) do\n #__call(pid, %RPC.Message{ method: method, params: params, context: context})\n async = Task.async(fn ->\n async = self()\n cast(pid, method, params, context, fn res ->\n send async, res\n end)\n receive do\n res -> res\n end\n end)\n Task.await async\n end\n\n @doc ~S\"\"\"\n Calls the method and calls the callback continuation with the result.\n\n If the method was async, it will be run in another task, if it was sync,\n its run right now.\n\n If the method does not exists, returns :nok, if it does, returns :ok.\n\n Callback is a function that can receive {:ok, value} or {:error, %Exception{...}}\n\n Alternatively mc can be a function that receies a %RPC.Message and returns any of:\n\n * {:ok, ret}\n * {:error, error}\n * :nok\n * :empty\n\n Possible errors:\n * :unknown_method\n * :bad_arity\n\n ## Examples\n\n iex> alias Serverboards.MOM.RPC.{Context, MethodCaller}\n iex> {:ok, mc} = MethodCaller.start_link\n iex> MethodCaller.add_method mc, \"echo\", fn [what], context -> \"#{what}#{Context.get(context, :test, :fail)}\" end, context: true\n iex> {:ok, context} = Context.start_link\n iex> Context.set context, :test, \"ok\"\n iex> MethodCaller.call mc, \"echo\", [\"test_\"], context\n {:ok, \"test_ok\"}\n\n iex> alias Serverboards.MOM.RPC.{Context, MethodCaller}\n iex> MethodCaller.cast(fn _ -> {:ok, :ok} end, \"any\", [], nil, fn\n ...> {:ok, _v} -> :ok\n ...> {:error, e} -> {:error, e}\n ...> end)\n :ok\n\n \"\"\"\n def cast(f, method, params, context, cb) when is_function(f) do\n ret = try do\n f.(%RPC.Message{ method: method, params: params, context: context})\n rescue\n FunctionClauseError ->\n Logger.warn(\"Function method caller did not accept input. May be too strict.\\n #{Exception.format_stacktrace}\")\n {:error, :unknown_method}\n other ->\n Logger.error(\"#{Exception.format :error, other}\")\n {:error, other}\n end\n #Logger.debug(\"Method #{method} caller function #{inspect f} -> #{inspect ret}.\")\n\n cb_params = case ret do\n {:ok, ret} -> {:ok, ret}\n {:error, :unknown_method} -> {:error, :unknown_method}\n {:error, other} -> {:error, other}\n :nok -> {:error, :unknown_method}\n :empty -> {:error, :unknown_method}\n end\n\n cb.(cb_params)\n end\n\n def cast(pid, method, params, context, cb) when is_pid(pid) do\n st = Agent.get pid, &(&1)\n #Logger.debug(\"Method #{method} caller pid #{inspect pid}, in #{inspect (Map.keys st.methods)} #{inspect Enum.map(st.mc, fn {f, options} -> Keyword.get options, :name, (inspect f) end) }\")\n case Map.get st.methods, method do\n {f, options} ->\n # Calls the function and the callback with the result, used in async and sync.\n call_f = fn ->\n if check_guards(%RPC.Message{ method: method, params: params, context: context}, options, st.guards) do\n try do\n v = if Keyword.get(options, :context, false) do\n #Logger.debug(\"Calling with context #{inspect f} #{inspect options}\")\n f.(params, context)\n else\n #Logger.debug(\"Calling without context #{inspect f}\")\n f.(params)\n end\n #Logger.debug(\"Method #{method} caller function #{inspect f} -> #{inspect v}.\")\n case v do\n {:error, e} ->\n cb.({:error, e })\n {:ok, v} ->\n cb.({:ok, v })\n v ->\n cb.({:ok, v })\n end\n rescue\n Serverboards.MOM.RPC.UnknownMethod ->\n Logger.error(\"Unknown method #{method}\\n#{Exception.format_stacktrace System.stacktrace}\")\n cb.({:error, :unknown_method})\n CaseClauseError ->\n Logger.error(\"Case clause error method #{method}\\n#{Exception.format_stacktrace System.stacktrace}\")\n cb.({:error, :bad_arity})\n BadArityError ->\n Logger.error(\"Bad arity error #{method}\\n#{Exception.format_stacktrace System.stacktrace}\")\n cb.({:error, :bad_arity})\n e ->\n Logger.error(\"Error on method #{method}\\n#{inspect e}\\n#{Exception.format_stacktrace System.stacktrace}\")\n cb.({:error, e})\n end\n else\n cb.({:error, :unknown_method })\n end\n end\n\n # sync or async\n if Keyword.get(options, :async, true) do\n Task.async fn -> call_f.() end\n else\n call_f.()\n end\n\n # found.\n :ok\n nil ->\n # Look for it at method callers\n #Logger.debug(\"Call cast from #{inspect pid} to #{inspect st.mc}\")\n ret = cast_mc(st.mc, method, params, context, st.guards, cb)\n #Logger.debug(\"#{inspect ret} at #{inspect pid}\")\n ret\n end\n end\n\n defp cast_mc([], _, _, _, _, cb) do # end of search, :unknown_method\n #Logger.debug(\"No more Method Callers to call\")\n cb.({:error, :unknown_method})\n :nok\n end\n\n ~S\"\"\"\n Casts a method caller from a list, and if any is ok, calls the callback\n with the data, or error.\n\n It must return :ok|:nok depending on if it was performed or not, and that makes\n things more difficult.\n\n To check each method caller, we have to cast into it in turns, and it signals\n if it worked using the continuation function, whtat will be called with the\n result ({:ok, v}, {:error, e}).\n\n If the error is :unknown_method, we can asume this method caller did not\n succed, so we can call the tail of the list t. If succeed, we call our\n own continuation cb. And then using a process signal we give the\n result to the original cast_mc.\n \"\"\"\n defp cast_mc([{h, options} | t], method, params, context, guards, cb) do\n #Logger.debug(\"Cast mc #{Keyword.get options, :name, (inspect h)}\")\n if check_guards(\n %RPC.Message{ method: method, params: params, context: context},\n options, guards) do\n task = Task.async fn ->\n task = self()\n cast(h, method, params, context, fn\n # Keep searching for it\n {:error, :unknown_method} ->\n #Logger.debug(\"Keep looking MC\")\n ok = cast_mc(t, method, params, context, guards, cb)\n # signal that it did it.\n send task, ok\n other ->\n #Logger.debug(\"Done #{inspect other}\")\n send task, :ok # done! Dont make it wait more.\n cb.(other)\n end)\n receive do\n a -> a\n end\n end\n\n Task.await(task)\n else\n # skip, guards not passed\n cast_mc(t, method, params, context, guards, cb)\n end\n end\n\nend\n","old_contents":"require Logger\n\ndefmodule Serverboards.MOM.RPC.MethodCaller do\n @moduledoc ~S\"\"\"\n This module stores methods to be called later.\n\n They are stored in an execute efficient way, and allow to have a list\n of methods to allow introspection (`dir` method).\n\n Can be connected with a RPC gateway with `add_method_caller`\n\n ## Example\n\n iex> alias Serverboards.MOM.RPC.MethodCaller\n iex> {:ok, mc} = MethodCaller.start_link\n iex> MethodCaller.add_method mc, \"ping\", fn _ -> \"pong\" end, async: false\n iex> MethodCaller.call mc, \"ping\", [], nil\n {:ok, \"pong\"}\n iex> MethodCaller.call mc, \"dir\", [], nil\n {:ok, [\"dir\", \"ping\"]}\n\n \"\"\"\n\n alias Serverboards.MOM.RPC\n\n def start_link(options \\\\ []) do\n {:ok, pid} = Agent.start_link fn -> %{ methods: %{}, mc: [], guards: [] } end, options\n\n add_method pid, \"dir\", fn _, context ->\n __dir(pid, context)\n end, [async: false, context: true]\n\n {:ok, pid}\n end\n\n def stop(pid) do\n Agent.stop pid\n end\n\n def debug(false) do\n false\n end\n\n def debug(pid) do\n st = Agent.get pid, &(&1)\n %{\n methods: (Map.keys st.methods),\n mc: Enum.map(st.mc, fn\n {mc, options} when is_function(mc) ->\n name = Keyword.get options, :name, (inspect mc)\n \"fn #{name}\"\n {pid, _options} when is_pid(pid) -> debug(pid)\n _ -> \"??\"\n end)\n }\n end\n\n def __dir(pid, context) when is_pid(pid) do\n st = Agent.get pid, &(&1)\n local = st.methods\n |> Enum.flat_map(fn {name, {_, options}} ->\n if check_guards(%Serverboards.MOM.RPC.Message{ method: name, context: context}, options, st.guards) do\n [name]\n else\n []\n end\n end)\n other = Enum.flat_map( st.mc, fn {smc, options} ->\n if check_guards(%Serverboards.MOM.RPC.Message{ method: \"dir\", context: context}, options, st.guards) do\n __dir(smc, context)\n else\n []\n end\n end)\n Enum.uniq Enum.sort( local ++ other )\n end\n\n def __dir(f, context) when is_function(f) do\n try do\n case f.(%RPC.Message{method: \"dir\", context: context}) do\n {:ok, l} when is_list(l) -> l\n _o ->\n Logger.error(\"dir dir not return list at #{inspect f}. Please fix.\")\n []\n end\n rescue\n e ->\n Logger.error(\"dir not implemented at #{inspect f}. Please fix.\\n#{inspect e}\\n#{ Exception.format_stacktrace System.stacktrace }\")\n []\n end\n end\n\n @doc ~S\"\"\"\n Adds a method to be called later.\n\n Method function must returns:\n\n * {:ok, v} -- Ok value\n * {:error, v} -- Error to return to client\n * v -- Ok value\n\n Options may be:\n\n * `async`, default true. Execute in another task, returns a promise.\n * `context`, the called function will be called with the client context. It is a Serverboards.MOM.RPC.Context\n\n ## Example\n\n iex> alias Serverboards.MOM.RPC.MethodCaller\n iex> {:ok, mc} = MethodCaller.start_link\n iex> MethodCaller.add_method mc, \"test_ok\", fn _ -> {:ok, :response_ok} end\n iex> MethodCaller.add_method mc, \"test_error\", fn _ -> {:error, :response_error} end\n iex> MethodCaller.add_method mc, \"test_plain\", fn _ -> :response_plain_ok end\n iex> MethodCaller.call mc, \"test_ok\", [], nil\n {:ok, :response_ok}\n iex> MethodCaller.call mc, \"test_error\", [], nil\n {:error, :response_error}\n iex> MethodCaller.call mc, \"test_plain\", [], nil\n {:ok, :response_plain_ok}\n\n \"\"\"\n def add_method(pid, name, f, options \\\\ []) do\n Agent.update pid, fn st ->\n %{ st | methods: Map.put(st.methods, name, {f, options})}\n end\n :ok\n end\n\n @doc ~S\"\"\"\n Method callers can be chained, so that if current does not resolve, try on another\n\n This another caller can be even shared between several method callers.\n\n Method callers are optimized callers, but a single function can be passed and\n it will be called with an %RPC.Message. If it returns {:ok, res} or\n {:error, error} its processed, :empty or :nok tries next callers.\n\n ## Example:\n\n I will create three method callers, so that a calls, and b too. Method can\n be shadowed at parent too.\n\n iex> alias Serverboards.MOM.RPC.{MethodCaller, Context}\n iex> {:ok, a} = MethodCaller.start_link\n iex> {:ok, b} = MethodCaller.start_link\n iex> {:ok, c} = MethodCaller.start_link\n iex> MethodCaller.add_method a, \"a\", fn _ -> :a end\n iex> MethodCaller.add_method b, \"b\", fn _ -> :b end\n iex> MethodCaller.add_method c, \"c\", fn _ -> :c end\n iex> MethodCaller.add_method c, \"c_\", fn _, context -> {:c, Context.get(context, :user, nil)} end, context: true\n iex> MethodCaller.add_method_caller a, c\n iex> MethodCaller.add_method_caller b, c\n iex> {:ok, context} = Context.start_link\n iex> Context.set context, :user, :me\n iex> MethodCaller.call a, \"c\", [], context\n {:ok, :c}\n iex> MethodCaller.call a, \"c_\", [], context\n {:ok, {:c, :me}}\n iex> MethodCaller.call b, \"c\", [], context\n {:ok, :c}\n iex> MethodCaller.call b, \"c_\", [], context\n {:ok, {:c, :me}}\n iex> MethodCaller.add_method a, \"c\", fn _ -> :shadow end\n iex> MethodCaller.call a, \"c\", [], context\n {:ok, :shadow}\n iex> MethodCaller.call b, \"c\", [], context\n {:ok, :c}\n iex> MethodCaller.call b, \"d\", [], context\n {:error, :unknown_method}\n\n Custom method caller that calls a function\n\n iex> alias Serverboards.MOM.RPC.MethodCaller\n iex> {:ok, mc} = MethodCaller.start_link\n iex> MethodCaller.add_method_caller(mc, fn msg ->\n ...> case msg.method do\n ...> \"hello.\"<>ret -> {:ok, ret}\n ...> _ -> :nok\n ...> end\n ...> end)\n iex> MethodCaller.call mc, \"hello.world\", [], nil\n {:ok, \"world\"}\n iex> MethodCaller.call mc, \"world.hello\", [], nil\n {:error, :unknown_method}\n\n \"\"\"\n def add_method_caller(pid, pid, _) do\n raise Exception, \"Cant add a method caller to itself.\"\n end\n def add_method_caller(pid, nmc, options) when is_pid(pid) do\n #Logger.debug(\"Add caller #{inspect nmc} to #{inspect pid}\")\n Agent.update pid, fn st ->\n %{ st | mc: st.mc ++ [{nmc, options}] }\n end\n :ok\n end\n def add_method_caller(pid, nmc), do: add_method_caller(pid, nmc, [])\n\n\n @doc ~S\"\"\"\n Adds a guard to the method caller\n\n This guards are used to ensure that a called method is allowed.\n\n If the mehtod is not allowed, it will be skipped as if never added, and\n `dir` will not return it neither.\n\n Guards are functions that receive the RPC message and the options of the\n method, and return true or false as they allow or not that method.\n This way generic guards can be created.\n\n name is a debug name used to log what guard failed. Any error\/exception on\n guards are interpreted as denial. Clause errors are not logged. Other errors\n are reraised.\n\n The very same \"dir\" that would be called with a method aller can have guards\n that prevent its call, but the dir implementation has to make sure to return\n only the approved methods.\n\n ## Example\n\n It creates a classic method and a function method caller. Both do the same.\n\n iex> require Logger\n iex> {:ok, mc} = start_link\n iex> add_method mc, \"echo\", &(&1), require_perm: \"echo\"\n iex> add_method_caller mc, fn\n ...> %{ method: \"dir\" } -> {:ok, [\"echo_fn\"]}\n ...> %{ method: \"echo_fn\", params: params } -> {:ok, params}\n ...> _ -> {:error, :unknown_method }\n ...> end, require_perm: \"echo\"\n iex> add_guard mc, \"perms\", fn %{ context: context }, options ->\n ...> case Keyword.get(options, :require_perm) do\n ...> nil -> true # no require perms, ok\n ...> required_perm ->\n ...> Enum.member? Map.get(context, :perms, []), required_perm\n ...> end\n ...> end\n iex> call mc, \"echo\", [1,2,3], %{ } # no context\n {:error, :unknown_method}\n iex> call mc, \"echo\", [1,2,3], %{ perms: [] } # no perms\n {:error, :unknown_method}\n iex> call mc, \"echo\", [1,2,3], %{ perms: [\"echo\"] } # no perms\n {:ok, [1,2,3]}\n iex> call mc, \"echo_fn\", [1,2,3], %{ } # no context\n {:error, :unknown_method}\n iex> call mc, \"echo_fn\", [1,2,3], %{ perms: [] } # no perms\n {:error, :unknown_method}\n iex> call mc, \"echo_fn\", [1,2,3], %{ perms: [\"echo\"] } # no perms\n {:ok, [1,2,3]}\n iex> call mc, \"dir\", [], %{}\n {:ok, [\"dir\"]}\n iex> call mc, \"dir\", [], %{ perms: [\"echo\"] }\n {:ok, [\"dir\", \"echo\", \"echo_fn\"]}\n\n In this example a map is used as context. Normally it would be a RPC.Context.\n \"\"\"\n def add_guard(pid, name, guard_f) when is_pid(pid) and is_function(guard_f) do\n Agent.update pid, fn st ->\n %{ st | guards: st.guards ++ [{name, guard_f}] }\n end\n end\n\n # Checks all the guards, return false if any fails.\n defp check_guards(%Serverboards.MOM.RPC.Message{}, _, []), do: true\n defp check_guards(%Serverboards.MOM.RPC.Message{} = msg, options, [{gname, gf} | rest]) do\n try do\n if gf.(msg, options) do\n #Logger.debug(\"Guard #{inspect msg} #{inspect gname} allowed pass\")\n check_guards(msg, options, rest)\n else\n #Logger.debug(\"Guard #{inspect msg} #{inspect gname} STOPPED pass\")\n false\n end\n rescue\n FunctionClauseError ->\n #Logger.debug(\"Guard #{inspect msg} #{inspect gname} STOPPED pass (Function Clause Error)\")\n false\n e ->\n Logger.error(\"Error checking method caller guard #{gname}: #{inspect e}\\n#{Exception.format_stacktrace}\")\n false\n end\n end\n\n @doc ~S\"\"\"\n Calls a method by name.\n\n Waits for execution always. Independent of async.\n\n Returns one of:\n\n * {:ok, v}\n * {:error, e}\n\n \"\"\"\n def call(pid, method, params, context) do\n #__call(pid, %RPC.Message{ method: method, params: params, context: context})\n async = Task.async(fn ->\n async = self()\n cast(pid, method, params, context, fn res ->\n send async, res\n end)\n receive do\n res -> res\n end\n end)\n Task.await async\n end\n\n @doc ~S\"\"\"\n Calls the method and calls the callback continuation with the result.\n\n If the method was async, it will be run in another task, if it was sync,\n its run right now.\n\n If the method does not exists, returns :nok, if it does, returns :ok.\n\n Callback is a function that can receive {:ok, value} or {:error, %Exception{...}}\n\n Alternatively mc can be a function that receies a %RPC.Message and returns any of:\n\n * {:ok, ret}\n * {:error, error}\n * :nok\n * :empty\n\n Possible errors:\n * :unknown_method\n * :bad_arity\n\n ## Examples\n\n iex> alias Serverboards.MOM.RPC.{Context, MethodCaller}\n iex> {:ok, mc} = MethodCaller.start_link\n iex> MethodCaller.add_method mc, \"echo\", fn [what], context -> \"#{what}#{Context.get(context, :test, :fail)}\" end, context: true\n iex> {:ok, context} = Context.start_link\n iex> Context.set context, :test, \"ok\"\n iex> MethodCaller.call mc, \"echo\", [\"test_\"], context\n {:ok, \"test_ok\"}\n\n iex> alias Serverboards.MOM.RPC.{Context, MethodCaller}\n iex> MethodCaller.cast(fn _ -> {:ok, :ok} end, \"any\", [], nil, fn\n ...> {:ok, _v} -> :ok\n ...> {:error, e} -> {:error, e}\n ...> end)\n :ok\n\n \"\"\"\n def cast(f, method, params, context, cb) when is_function(f) do\n ret = try do\n f.(%RPC.Message{ method: method, params: params, context: context})\n rescue\n FunctionClauseError ->\n Logger.warn(\"Function method caller did not accept input. May be too strict.\\n #{Exception.format_stacktrace}\")\n {:error, :unknown_method}\n other ->\n Logger.error(\"#{Exception.format :error, other}\")\n {:error, other}\n end\n Logger.debug(\"Method #{method} caller function #{inspect f} -> #{inspect ret}.\")\n\n cb_params = case ret do\n {:ok, ret} -> {:ok, ret}\n {:error, :unknown_method} -> {:error, :unknown_method}\n {:error, other} -> {:error, other}\n :nok -> {:error, :unknown_method}\n :empty -> {:error, :unknown_method}\n end\n\n cb.(cb_params)\n end\n\n def cast(pid, method, params, context, cb) when is_pid(pid) do\n st = Agent.get pid, &(&1)\n Logger.debug(\"Method #{method} caller pid #{inspect pid}, in #{inspect (Map.keys st.methods)} #{inspect Enum.map(st.mc, fn {f, options} -> Keyword.get options, :name, (inspect f) end) }\")\n case Map.get st.methods, method do\n {f, options} ->\n # Calls the function and the callback with the result, used in async and sync.\n call_f = fn ->\n if check_guards(%RPC.Message{ method: method, params: params, context: context}, options, st.guards) do\n try do\n v = if Keyword.get(options, :context, false) do\n #Logger.debug(\"Calling with context #{inspect f} #{inspect options}\")\n f.(params, context)\n else\n #Logger.debug(\"Calling without context #{inspect f}\")\n f.(params)\n end\n Logger.debug(\"Method #{method} caller function #{inspect f} -> #{inspect v}.\")\n case v do\n {:error, e} ->\n cb.({:error, e })\n {:ok, v} ->\n cb.({:ok, v })\n v ->\n cb.({:ok, v })\n end\n rescue\n Serverboards.MOM.RPC.UnknownMethod ->\n Logger.error(\"Unknown method #{method}\\n#{Exception.format_stacktrace System.stacktrace}\")\n cb.({:error, :unknown_method})\n CaseClauseError ->\n Logger.error(\"Case clause error method #{method}\\n#{Exception.format_stacktrace System.stacktrace}\")\n cb.({:error, :bad_arity})\n BadArityError ->\n Logger.error(\"Bad arity error #{method}\\n#{Exception.format_stacktrace System.stacktrace}\")\n cb.({:error, :bad_arity})\n e ->\n Logger.error(\"Error on method #{method}\\n#{inspect e}\\n#{Exception.format_stacktrace System.stacktrace}\")\n cb.({:error, e})\n end\n else\n cb.({:error, :unknown_method })\n end\n end\n\n # sync or async\n if Keyword.get(options, :async, true) do\n Task.async fn -> call_f.() end\n else\n call_f.()\n end\n\n # found.\n :ok\n nil ->\n # Look for it at method callers\n Logger.debug(\"Call cast from #{inspect pid} to #{inspect st.mc}\")\n ret = cast_mc(st.mc, method, params, context, st.guards, cb)\n Logger.debug(\"#{inspect ret} at #{inspect pid}\")\n ret\n end\n end\n\n defp cast_mc([], _, _, _, _, cb) do # end of search, :unknown_method\n #Logger.debug(\"No more Method Callers to call\")\n cb.({:error, :unknown_method})\n :nok\n end\n\n ~S\"\"\"\n Casts a method caller from a list, and if any is ok, calls the callback\n with the data, or error.\n\n It must return :ok|:nok depending on if it was performed or not, and that makes\n things more difficult.\n\n To check each method caller, we have to cast into it in turns, and it signals\n if it worked using the continuation function, whtat will be called with the\n result ({:ok, v}, {:error, e}).\n\n If the error is :unknown_method, we can asume this method caller did not\n succed, so we can call the tail of the list t. If succeed, we call our\n own continuation cb. And then using a process signal we give the\n result to the original cast_mc.\n \"\"\"\n defp cast_mc([{h, options} | t], method, params, context, guards, cb) do\n Logger.debug(\"Cast mc #{Keyword.get options, :name, (inspect h)}\")\n if check_guards(\n %RPC.Message{ method: method, params: params, context: context},\n options, guards) do\n task = Task.async fn ->\n task = self()\n cast(h, method, params, context, fn\n # Keep searching for it\n {:error, :unknown_method} ->\n #Logger.debug(\"Keep looking MC\")\n ok = cast_mc(t, method, params, context, guards, cb)\n # signal that it did it.\n send task, ok\n other ->\n #Logger.debug(\"Done #{inspect other}\")\n send task, :ok # done! Dont make it wait more.\n cb.(other)\n end)\n receive do\n a -> a\n end\n end\n\n Task.await(task)\n else\n # skip, guards not passed\n cast_mc(t, method, params, context, guards, cb)\n end\n end\n\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"36c8bad9bae995ea7ae64ddee853aba05f38a1c3","subject":"reorder error and ok cases","message":"reorder error and ok cases\n\n","repos":"digitalnatives\/course_planner,digitalnatives\/course_planner,digitalnatives\/course_planner","old_file":"web\/controllers\/setting_controller.ex","new_file":"web\/controllers\/setting_controller.ex","new_contents":"defmodule CoursePlanner.SettingController do\n @moduledoc false\n use CoursePlanner.Web, :controller\n\n alias CoursePlanner.{Settings, SystemVariable}\n\n import Canary.Plugs\n plug :authorize_controller\n\n def show(%{assigns: %{current_user: %{role: \"Coordinator\"}}} = conn, _param) do\n visible_system_variables = Settings.get_visible_systemvariables()\n program_system_variables =\n Settings.filter_program_systemvariables(visible_system_variables)\n non_program_system_variables =\n Settings.filter_non_program_systemvariables(visible_system_variables)\n\n render(conn, \"show.html\", program_system_variables: program_system_variables,\n non_program_system_variables: non_program_system_variables)\n end\n\n def edit(%{assigns: %{current_user: %{role: \"Coordinator\"}}} = conn,\n %{\"setting_type\" => setting_type}) do\n editable_system_variables = Settings.get_editable_systemvariables()\n\n case Settings.filter_system_variables(editable_system_variables, setting_type) do\n {:ok, filtered_system_variables} ->\n changeset =\n filtered_system_variables\n |> Enum.map(&SystemVariable.changeset\/1)\n |> Settings.wrap()\n\n render(conn, \"edit.html\", changeset: changeset)\n {:error, _} ->\n conn\n |> put_status(404)\n |> render(CoursePlanner.ErrorView, \"404.html\")\n end\n end\n\n def update(\n %{assigns: %{current_user: %{role: \"Coordinator\"}}} = conn,\n %{\"settings\" => %{\"system_variables\" => variables}}) do\n changesets = Settings.get_changesets_for_update(variables)\n\n case Settings.update(changesets) do\n {:ok, _setting} ->\n conn\n |> put_flash(:info, \"Setting updated successfully.\")\n |> redirect(to: setting_path(conn, :show))\n {:error, :non_existing_resource, _failed_value, _changes_so_far} ->\n conn\n |> put_status(404)\n |> render(CoursePlanner.ErrorView, \"404.html\")\n {:error, :uneditable_resource, _failed_value, _changes_so_far} ->\n conn\n |> put_status(403)\n |> render(CoursePlanner.ErrorView, \"403.html\")\n {:error, _failed_operation, _failed_value, _changes_so_far} ->\n changeset =\n changesets\n |> Settings.wrap()\n |> Map.put(:action, :update)\n render(conn, \"edit.html\", changeset: changeset)\n end\n end\nend\n","old_contents":"defmodule CoursePlanner.SettingController do\n @moduledoc false\n use CoursePlanner.Web, :controller\n\n alias CoursePlanner.{Settings, SystemVariable}\n\n import Canary.Plugs\n plug :authorize_controller\n\n def show(%{assigns: %{current_user: %{role: \"Coordinator\"}}} = conn, _param) do\n visible_system_variables = Settings.get_visible_systemvariables()\n program_system_variables =\n Settings.filter_program_systemvariables(visible_system_variables)\n non_program_system_variables =\n Settings.filter_non_program_systemvariables(visible_system_variables)\n\n render(conn, \"show.html\", program_system_variables: program_system_variables,\n non_program_system_variables: non_program_system_variables)\n end\n\n def edit(%{assigns: %{current_user: %{role: \"Coordinator\"}}} = conn,\n %{\"setting_type\" => setting_type}) do\n editable_system_variables = Settings.get_editable_systemvariables()\n\n case Settings.filter_system_variables(editable_system_variables, setting_type) do\n {:error, _} ->\n conn\n |> put_status(404)\n |> render(CoursePlanner.ErrorView, \"404.html\")\n {:ok, filtered_system_variables} ->\n changeset =\n filtered_system_variables\n |> Enum.map(&SystemVariable.changeset\/1)\n |> Settings.wrap()\n\n render(conn, \"edit.html\", changeset: changeset)\n end\n end\n\n def update(\n %{assigns: %{current_user: %{role: \"Coordinator\"}}} = conn,\n %{\"settings\" => %{\"system_variables\" => variables}}) do\n changesets = Settings.get_changesets_for_update(variables)\n\n case Settings.update(changesets) do\n {:ok, _setting} ->\n conn\n |> put_flash(:info, \"Setting updated successfully.\")\n |> redirect(to: setting_path(conn, :show))\n {:error, :non_existing_resource, _failed_value, _changes_so_far} ->\n conn\n |> put_status(404)\n |> render(CoursePlanner.ErrorView, \"404.html\")\n {:error, :uneditable_resource, _failed_value, _changes_so_far} ->\n conn\n |> put_status(403)\n |> render(CoursePlanner.ErrorView, \"403.html\")\n {:error, _failed_operation, _failed_value, _changes_so_far} ->\n changeset =\n changesets\n |> Settings.wrap()\n |> Map.put(:action, :update)\n render(conn, \"edit.html\", changeset: changeset)\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"cec3a0ea0a36372da3b11dac24f0364aa90667ff","subject":"Implement the response to webhooks","message":"Implement the response to webhooks\n","repos":"bors-ng\/bors-ng,bors-ng\/bors-ng,bors-ng\/bors-ng","old_file":"web\/controllers\/webhook_controller.ex","new_file":"web\/controllers\/webhook_controller.ex","new_contents":"defmodule Aelita2.WebhookController do\n use Aelita2.Web, :controller\n\n alias Aelita2.Installation\n alias Aelita2.Project\n\n @doc \"\"\"\n This action is reached via `\/webhook\/:provider`\n \"\"\"\n def webhook(conn, %{\"provider\" => \"github\"}) do\n do_webhook conn, \"github\", conn.req_headers[\"X-GitHub-Event\"]\n conn\n |> send_resp(200, \"\")\n end\n\n def do_webhook(conn, \"github\", \"ping\") do\n :ok\n end\n\n def do_webhook(conn, \"github\", \"integration_installation\") do\n payload = Poison.decode!(conn.body)\n installation_id = payload[\"installation\"][\"id\"]\n case payload[\"action\"] do\n \"deleted\" -> Repo.delete_all(from(\n i in Installation,\n where: i.installation_id == ^installation_id\n ))\n \"created\" -> Repo.insert!(%Installation{\n installation_id: installation_id\n })\n end\n :ok\n end\n\n def do_webhook(conn, \"github\", \"integration_installation_repositories\") do\n payload = Poison.decode!(conn.body)\n installation_id = payload[\"installation\"][\"id\"]\n installation = Repo.get_by!(Installation, installation_id: installation_id)\n :ok = case payload[\"action\"] do\n \"removed\" -> :ok\n \"added\" -> :ok\n end\n Enum.each(\n payload[\"repositories_removed\"],\n fn(r) -> Repo.delete_all(from(\n p in Project,\n where: p.repo_id == ^r[\"id\"])) end)\n Enum.each(\n payload[\"repositories_added\"],\n fn(r) -> Repo.insert! %Project{\n repo_id: r[\"id\"], name: r[\"full_name\"], installation: installation} end)\n :ok\n end\nend","old_contents":"defmodule Aelita2.WebhookController do\n use Aelita2.Web, :controller\n\n alias Aelita2.Installation\n alias Aelita2.Project\n\n @doc \"\"\"\n This action is reached via `\/webhook\/:provider`\n \"\"\"\n def webhook(conn, %{\"provider\" => \"github\"}) do\n do_webhook conn, \"github\", conn.req_headers[\"X-GitHub-Event\"]\n end\n\n def do_webhook(conn, \"github\", \"integration_installation\") do\n payload = Poison.decode!(conn.body)\n installation_id = payload[\"installation\"][\"id\"]\n case payload[\"action\"] do\n \"deleted\" -> Repo.delete_all(from(\n i in Installation,\n where: i.installation_id == ^installation_id\n ))\n \"created\" -> Repo.insert!(%Installation{\n installation_id: installation_id\n })\n end\n end\n\n def do_webhook(conn, \"github\", \"integration_installation_repositories\") do\n payload = Poison.decode!(conn.body)\n installation_id = payload[\"installation\"][\"id\"]\n installation = Repo.get_by!(Installation, installation_id: installation_id)\n :ok = case payload[\"action\"] do\n \"removed\" -> :ok\n \"added\" -> :ok\n end\n Enum.each(\n payload[\"repositories_removed\"],\n fn(r) -> Repo.delete_all(from(\n p in Project,\n where: p.repo_id == ^r[\"id\"])) end)\n Enum.each(\n payload[\"repositories_added\"],\n fn(r) -> Repo.insert! %Project{\n repo_id: r[\"id\"], name: r[\"full_name\"], installation: installation} end)\n end\nend","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"3e453df186f474a3a74223ebba972d2006f34fc4","subject":"Fix docs example in ExUnit.Case (#10754)","message":"Fix docs example in ExUnit.Case (#10754)\n\n","repos":"ggcampinho\/elixir,elixir-lang\/elixir,kimshrier\/elixir,pedrosnk\/elixir,ggcampinho\/elixir,pedrosnk\/elixir,joshprice\/elixir,kimshrier\/elixir,michalmuskala\/elixir,kelvinst\/elixir,kelvinst\/elixir","old_file":"lib\/ex_unit\/lib\/ex_unit\/case.ex","new_file":"lib\/ex_unit\/lib\/ex_unit\/case.ex","new_contents":"defmodule ExUnit.DuplicateTestError do\n defexception [:message]\nend\n\ndefmodule ExUnit.DuplicateDescribeError do\n defexception [:message]\nend\n\ndefmodule ExUnit.Case do\n @moduledoc \"\"\"\n Helpers for defining test cases.\n\n This module must be used in other modules as a way to configure\n and prepare them for testing.\n\n When used, it accepts the following options:\n\n * `:async` - configures tests in this module to run concurrently with\n tests in other modules. Tests in the same module never run concurrently.\n It should be enabled only if tests do not change any global state.\n Defaults to `false`.\n\n This module automatically includes all callbacks defined in\n `ExUnit.Callbacks`. See that module for more information on `setup`,\n `start_supervised`, `on_exit` and the test process life cycle.\n\n For grouping tests together, see `describe\/2` in this module.\n\n ## Examples\n\n defmodule AssertionTest do\n # Use the module\n use ExUnit.Case, async: true\n\n # The \"test\" macro is imported by ExUnit.Case\n test \"always pass\" do\n assert true\n end\n end\n\n ## Context\n\n All tests receive a context as an argument. The context is particularly\n useful for sharing information between callbacks and tests:\n\n defmodule KVTest do\n use ExUnit.Case\n\n setup do\n {:ok, pid} = KV.start_link()\n {:ok, pid: pid}\n end\n\n test \"stores key-value pairs\", context do\n assert KV.put(context[:pid], :hello, :world) == :ok\n assert KV.get(context[:pid], :hello) == :world\n end\n end\n\n As the context is a map, it can be pattern matched on to extract\n information:\n\n test \"stores key-value pairs\", %{pid: pid} = _context do\n assert KV.put(pid, :hello, :world) == :ok\n assert KV.get(pid, :hello) == :world\n end\n\n ## Tags\n\n The context is used to pass information from the callbacks to\n the test. In order to pass information from the test to the\n callback, ExUnit provides tags.\n\n By tagging a test, the tag value can be accessed in the context,\n allowing the developer to customize the test. Let's see an\n example:\n\n defmodule FileTest do\n # Changing directory cannot be async\n use ExUnit.Case, async: false\n\n setup context do\n # Read the :cd tag value\n if cd = context[:cd] do\n prev_cd = File.cwd!()\n File.cd!(cd)\n on_exit(fn -> File.cd!(prev_cd) end)\n end\n\n :ok\n end\n\n @tag cd: \"fixtures\"\n test \"reads UTF-8 fixtures\" do\n File.read(\"README.md\")\n end\n end\n\n In the example above, we have defined a tag called `:cd` that is\n read in the setup callback to configure the working directory the\n test is going to run on.\n\n Tags are also very effective when used with case templates\n (`ExUnit.CaseTemplate`) allowing callbacks in the case template\n to customize the test behaviour.\n\n Note a tag can be set in two different ways:\n\n @tag key: value\n @tag :key # equivalent to setting @tag key: true\n\n If a tag is given more than once, the last value wins.\n\n ### Module and describe tags\n\n A tag can be set for all tests in a module or describe block by\n setting `@moduletag` or `@describetag` inside each context\n respectively:\n\n defmodule ApiTest do\n use ExUnit.Case\n @moduletag :external\n\n describe \"makes calls to the right endpoint\" do\n @describetag :endpoint\n\n # ...\n end\n end\n\n If you are setting a `@moduletag` or `@describetag` attribute, you must\n set them after your call to `use ExUnit.Case` otherwise you will see\n compilation errors.\n\n If the same key is set via `@tag`, the `@tag` value has higher\n precedence.\n\n ### Known tags\n\n The following tags are set automatically by ExUnit and are\n therefore reserved:\n\n * `:module` - the module on which the test was defined\n\n * `:file` - the file on which the test was defined\n\n * `:line` - the line on which the test was defined\n\n * `:test` - the test name\n\n * `:async` - if the test case is in async mode\n\n * `:registered` - used for `ExUnit.Case.register_attribute\/3` values\n\n * `:describe` - the describe block the test belongs to\n\n The following tags customize how tests behave:\n\n * `:capture_log` - see the \"Log Capture\" section below\n\n * `:skip` - skips the test with the given reason\n\n * `:timeout` - customizes the test timeout in milliseconds (defaults to 60000).\n Accepts `:infinity` as a timeout value.\n\n * `:tmp_dir` - (since v1.11.0) see the \"Tmp Dir\" section below\n\n The `:test_type` tag is automatically set by ExUnit, but is **not** reserved.\n This tag is available for users to customize if they desire.\n\n ## Filters\n\n Tags can also be used to identify specific tests, which can then\n be included or excluded using filters. The most common functionality\n is to exclude some particular tests from running, which can be done\n via `ExUnit.configure\/1`:\n\n # Exclude all external tests from running\n ExUnit.configure(exclude: [external: true])\n\n From now on, ExUnit will not run any test that has the `:external` option\n set to `true`. This behaviour can be reversed with the `:include` option\n which is usually passed through the command line:\n\n mix test --include external:true\n\n Run `mix help test` for more information on how to run filters via Mix.\n\n Another use case for tags and filters is to exclude all tests that have\n a particular tag by default, regardless of its value, and include only\n a certain subset:\n\n ExUnit.configure(exclude: :os, include: [os: :unix])\n\n A given include\/exclude filter can be given more than once:\n\n ExUnit.configure(exclude: [os: :unix, os: :windows])\n\n Keep in mind that all tests are included by default, so unless they are\n excluded first, the `include` option has no effect.\n\n ## Log Capture\n\n ExUnit can optionally suppress printing of log messages that are generated\n during a test. Log messages generated while running a test are captured and\n only if the test fails are they printed to aid with debugging.\n\n You can opt into this behaviour for individual tests by tagging them with\n `:capture_log` or enable log capture for all tests in the ExUnit configuration:\n\n ExUnit.start(capture_log: true)\n\n This default can be overridden by `@tag capture_log: false` or\n `@moduletag capture_log: false`.\n\n Since `setup_all` blocks don't belong to a specific test, log messages generated\n in them (or between tests) are never captured. If you want to suppress these\n messages as well, remove the console backend globally by setting:\n\n config :logger, backends: []\n\n ## Tmp Dir\n\n ExUnit automatically creates a temporary directory for tests tagged with\n `:tmp_dir` and puts the path to that directory into the test context.\n The directory is removed before being created to ensure we start with a blank\n slate.\n\n The temporary directory path is unique (includes the test module and test name)\n and thus appropriate for running tests concurrently. You can customize the path\n further by setting the tag to a string, e.g.: `tmp_dir: \"my_path\"`, which would\n make the final path to be: `tmp\/\/\/my_path`.\n\n Example:\n\n defmodule MyTest do\n use ExUnit.Case, async: true\n\n @tag :tmp_dir\n test \"with tmp_dir\", %{tmp_dir: tmp_dir} do\n assert tmp_dir =~ \"with tmp_dir\"\n assert File.dir?(tmp_dir)\n end\n end\n\n As with other tags, `:tmp_dir` can also be set as `@moduletag` and\n `@describetag`.\n \"\"\"\n\n @type env :: module() | Macro.Env.t()\n\n @reserved [:module, :file, :line, :test, :async, :registered, :describe]\n\n @doc false\n defmacro __using__(opts) do\n unless Process.whereis(ExUnit.Server) do\n raise \"cannot use ExUnit.Case without starting the ExUnit application, \" <>\n \"please call ExUnit.start() or explicitly start the :ex_unit app\"\n end\n\n quote do\n unless ExUnit.Case.__register__(__MODULE__, unquote(opts)) do\n use ExUnit.Callbacks\n end\n\n import ExUnit.Callbacks\n import ExUnit.Assertions\n import ExUnit.Case, only: [describe: 2, test: 1, test: 2, test: 3]\n import ExUnit.DocTest\n end\n end\n\n @doc false\n def __register__(module, opts) do\n registered? = Module.has_attribute?(module, :ex_unit_tests)\n\n unless registered? do\n tag_check = Enum.any?([:moduletag, :describetag, :tag], &Module.has_attribute?(module, &1))\n\n if tag_check do\n raise \"you must set @tag, @describetag, and @moduletag after the call to \\\"use ExUnit.Case\\\"\"\n end\n\n attributes = [\n :ex_unit_tests,\n :tag,\n :describetag,\n :moduletag,\n :ex_unit_registered_test_attributes,\n :ex_unit_registered_describe_attributes,\n :ex_unit_registered_module_attributes,\n :ex_unit_used_describes\n ]\n\n Enum.each(attributes, &Module.register_attribute(module, &1, accumulate: true))\n\n attributes = [\n before_compile: ExUnit.Case,\n after_compile: ExUnit.Case,\n ex_unit_async: false,\n ex_unit_describe: nil\n ]\n\n Enum.each(attributes, fn {k, v} -> Module.put_attribute(module, k, v) end)\n end\n\n async? = opts[:async]\n\n if is_boolean(async?) do\n Module.put_attribute(module, :ex_unit_async, async?)\n end\n\n registered?\n end\n\n @doc \"\"\"\n Defines a test with `message`.\n\n The test may also define a pattern, which will be matched\n against the test context. For more information on contexts, see\n `ExUnit.Callbacks`.\n\n ## Examples\n\n test \"true is equal to true\" do\n assert true == true\n end\n\n \"\"\"\n defmacro test(message, var \\\\ quote(do: _), contents) do\n unless is_tuple(var) do\n IO.warn(\n \"test context is always a map. The pattern \" <>\n \"#{inspect(Macro.to_string(var))} will never match\",\n Macro.Env.stacktrace(__CALLER__)\n )\n end\n\n contents =\n case contents do\n [do: block] ->\n quote do\n unquote(block)\n :ok\n end\n\n _ ->\n quote do\n try(unquote(contents))\n :ok\n end\n end\n\n var = Macro.escape(var)\n contents = Macro.escape(contents, unquote: true)\n %{module: mod, file: file, line: line} = __CALLER__\n\n quote bind_quoted: [\n var: var,\n contents: contents,\n message: message,\n mod: mod,\n file: file,\n line: line\n ] do\n name = ExUnit.Case.register_test(mod, file, line, :test, message, [])\n def unquote(name)(unquote(var)), do: unquote(contents)\n end\n end\n\n @doc \"\"\"\n Defines a not implemented test with a string.\n\n Provides a convenient macro that allows a test to be defined\n with a string, but not yet implemented. The resulting test will\n always fail and print a \"Not implemented\" error message. The\n resulting test case is also tagged with `:not_implemented`.\n\n ## Examples\n\n test \"this will be a test in future\"\n\n \"\"\"\n defmacro test(message) do\n %{module: mod, file: file, line: line} = __CALLER__\n\n quote bind_quoted: binding() do\n name = ExUnit.Case.register_test(mod, file, line, :test, message, [:not_implemented])\n def unquote(name)(_), do: flunk(\"Not implemented\")\n end\n end\n\n @doc \"\"\"\n Describes tests together.\n\n Every describe block receives a name which is used as prefix for\n upcoming tests. Inside a block, `ExUnit.Callbacks.setup\/1` may be\n invoked and it will define a setup callback to run only for the\n current block. The describe name is also added as a tag, allowing\n developers to run tests for specific blocks.\n\n ## Examples\n\n defmodule StringTest do\n use ExUnit.Case, async: true\n\n describe \"String.capitalize\/1\" do\n test \"first grapheme is in uppercase\" do\n assert String.capitalize(\"hello\") == \"Hello\"\n end\n\n test \"converts remaining graphemes to lowercase\" do\n assert String.capitalize(\"HELLO\") == \"Hello\"\n end\n end\n end\n\n When using Mix, you can run all tests in a describe block by name:\n\n mix test --only describe:\"String.capitalize\/1\"\n\n or by passing the exact line the describe block starts on:\n\n mix test path\/to\/file:123\n\n Note describe blocks cannot be nested. Instead of relying on hierarchy\n for composition, developers should build on top of named setups. For\n example:\n\n defmodule UserManagementTest do\n use ExUnit.Case, async: true\n\n describe \"when user is logged in and is an admin\" do\n setup [:log_user_in, :set_type_to_admin]\n\n test ...\n end\n\n describe \"when user is logged in and is a manager\" do\n setup [:log_user_in, :set_type_to_manager]\n\n test ...\n end\n\n defp log_user_in(context) do\n # ...\n end\n end\n\n By forbidding hierarchies in favor of named setups, it is straightforward\n for the developer to glance at each describe block and know exactly the\n setup steps involved.\n \"\"\"\n defmacro describe(message, do: block) do\n quote do\n ExUnit.Case.__describe__(__MODULE__, __ENV__.line, unquote(message), fn ->\n unquote(block)\n end)\n end\n end\n\n @doc false\n def __describe__(module, line, message, fun) do\n if Module.get_attribute(module, :ex_unit_describe) do\n raise \"cannot call \\\"describe\\\" inside another \\\"describe\\\". See the documentation \" <>\n \"for ExUnit.Case.describe\/2 on named setups and how to handle hierarchies\"\n end\n\n cond do\n not is_binary(message) ->\n raise ArgumentError, \"describe name must be a string, got: #{inspect(message)}\"\n\n message in Module.get_attribute(module, :ex_unit_used_describes) ->\n raise ExUnit.DuplicateDescribeError,\n \"describe #{inspect(message)} is already defined in #{inspect(module)}\"\n\n true ->\n :ok\n end\n\n if Module.get_attribute(module, :describetag) != [] do\n raise \"@describetag must be set inside describe\/2 blocks\"\n end\n\n Module.put_attribute(module, :ex_unit_describe, {line, message})\n Module.put_attribute(module, :ex_unit_used_describes, message)\n\n try do\n fun.()\n after\n Module.put_attribute(module, :ex_unit_describe, nil)\n Module.delete_attribute(module, :describetag)\n\n for attribute <- Module.get_attribute(module, :ex_unit_registered_describe_attributes) do\n Module.delete_attribute(module, attribute)\n end\n end\n end\n\n @doc false\n defmacro __before_compile__(_) do\n quote do\n def __ex_unit__ do\n %ExUnit.TestModule{file: __ENV__.file, name: __MODULE__, tests: @ex_unit_tests}\n end\n end\n end\n\n @doc false\n def __after_compile__(%{module: module}, _) do\n if Module.get_attribute(module, :ex_unit_async) do\n ExUnit.Server.add_async_module(module)\n else\n ExUnit.Server.add_sync_module(module)\n end\n end\n\n @doc \"\"\"\n Registers a function to run as part of this case.\n\n This is used by third-party projects, like QuickCheck, to\n implement macros like `property\/3` that works like `test`\n but instead defines a property. See `test\/3` implementation\n for an example of invoking this function.\n\n The test type will be converted to a string and pluralized for\n display. You can use `ExUnit.plural_rule\/2` to set a custom\n pluralization.\n \"\"\"\n def register_test(mod, file, line, test_type, name, tags) do\n unless Module.has_attribute?(mod, :ex_unit_tests) do\n raise \"cannot define #{test_type}. Please make sure you have invoked \" <>\n \"\\\"use ExUnit.Case\\\" in the current module\"\n end\n\n registered_attribute_keys = [\n :ex_unit_registered_module_attributes,\n :ex_unit_registered_describe_attributes,\n :ex_unit_registered_test_attributes\n ]\n\n registered =\n for key <- registered_attribute_keys,\n attribute <- Module.get_attribute(mod, key),\n into: %{} do\n {attribute, Module.get_attribute(mod, attribute)}\n end\n\n moduletag = Module.get_attribute(mod, :moduletag)\n tag = Module.delete_attribute(mod, :tag)\n async = Module.get_attribute(mod, :ex_unit_async)\n\n {name, describe, describe_line, describetag} =\n case Module.get_attribute(mod, :ex_unit_describe) do\n {line, describe} ->\n description = :\"#{test_type} #{describe} #{name}\"\n {description, describe, line, Module.get_attribute(mod, :describetag)}\n\n _ ->\n {:\"#{test_type} #{name}\", nil, nil, []}\n end\n\n if Module.defines?(mod, {name, 1}) do\n raise ExUnit.DuplicateTestError, ~s(\"#{name}\" is already defined in #{inspect(mod)})\n end\n\n tags =\n (tags ++ tag ++ describetag ++ moduletag)\n |> normalize_tags\n |> validate_tags\n |> Map.merge(%{\n line: line,\n file: file,\n registered: registered,\n async: async,\n describe: describe,\n describe_line: describe_line,\n test_type: test_type\n })\n\n test = %ExUnit.Test{name: name, case: mod, tags: tags, module: mod}\n Module.put_attribute(mod, :ex_unit_tests, test)\n\n for attribute <- Module.get_attribute(mod, :ex_unit_registered_test_attributes) do\n Module.delete_attribute(mod, attribute)\n end\n\n name\n end\n\n @doc \"\"\"\n Registers a test with the given environment.\n\n This function is deprecated in favor of `register_test\/6` which performs\n better under tight loops by avoiding `__ENV__`.\n \"\"\"\n @doc deprecated: \"Use register_test\/6 instead\"\n def register_test(%{module: mod, file: file, line: line}, test_type, name, tags) do\n register_test(mod, file, line, test_type, name, tags)\n end\n\n @doc \"\"\"\n Registers a new attribute to be used during `ExUnit.Case` tests.\n\n The attribute values will be available through `context.registered`.\n Registered values are cleared after each `test\/3` similar\n to `@tag`.\n\n This function takes the same options as `Module.register_attribute\/3`.\n\n ## Examples\n\n defmodule MyTest do\n use ExUnit.Case\n\n ExUnit.Case.register_attribute(__MODULE__, :fixtures, accumulate: true)\n\n @fixtures :user\n @fixtures {:post, insert: false}\n test \"using custom attribute\", context do\n assert context.registered.fixtures == [{:post, insert: false}, :user]\n end\n\n test \"custom attributes are cleared per test\", context do\n assert context.registered.fixtures == []\n end\n end\n\n \"\"\"\n @spec register_attribute(env, atom, keyword) :: :ok\n def register_attribute(env, name, opts \\\\ [])\n def register_attribute(%{module: mod}, name, opts), do: register_attribute(mod, name, opts)\n\n def register_attribute(mod, name, opts) when is_atom(mod) and is_atom(name) and is_list(opts) do\n register_attribute(:ex_unit_registered_test_attributes, mod, name, opts)\n end\n\n @doc \"\"\"\n Registers a new describe attribute to be used during `ExUnit.Case` tests.\n\n The attribute values will be available through `context.registered`.\n Registered values are cleared after each `describe\/2` similar\n to `@describetag`.\n\n This function takes the same options as `Module.register_attribute\/3`.\n\n ## Examples\n\n defmodule MyTest do\n use ExUnit.Case\n\n ExUnit.Case.register_describe_attribute(__MODULE__, :describe_fixtures, accumulate: true)\n\n describe \"using custom attribute\" do\n @describe_fixtures :user\n @describe_fixtures {:post, insert: false}\n\n test \"has attribute\", context do\n assert context.registered.describe_fixtures == [{:post, insert: false}, :user]\n end\n end\n\n describe \"custom attributes are cleared per describe\" do\n test \"doesn't have attributes\", context do\n assert context.registered.describe_fixtures == []\n end\n end\n end\n\n \"\"\"\n @doc since: \"1.10.0\"\n @spec register_describe_attribute(env, atom, keyword) :: :ok\n def register_describe_attribute(env, name, opts \\\\ [])\n\n def register_describe_attribute(%{module: mod}, name, opts) do\n register_describe_attribute(mod, name, opts)\n end\n\n def register_describe_attribute(mod, name, opts)\n when is_atom(mod) and is_atom(name) and is_list(opts) do\n register_attribute(:ex_unit_registered_describe_attributes, mod, name, opts)\n end\n\n @doc \"\"\"\n Registers a new module attribute to be used during `ExUnit.Case` tests.\n\n The attribute values will be available through `context.registered`.\n\n This function takes the same options as `Module.register_attribute\/3`.\n\n ## Examples\n\n defmodule MyTest do\n use ExUnit.Case\n\n ExUnit.Case.register_module_attribute(__MODULE__, :module_fixtures, accumulate: true)\n\n @module_fixtures :user\n @module_fixtures {:post, insert: false}\n\n test \"using custom attribute\", context do\n assert context.registered.module_fixtures == [{:post, insert: false}, :user]\n end\n\n test \"still using custom attribute\", context do\n assert context.registered.module_fixtures == [{:post, insert: false}, :user]\n end\n end\n\n \"\"\"\n @doc since: \"1.10.0\"\n @spec register_module_attribute(env, atom, keyword) :: :ok\n def register_module_attribute(env, name, opts \\\\ [])\n\n def register_module_attribute(%{module: mod}, name, opts) do\n register_module_attribute(mod, name, opts)\n end\n\n def register_module_attribute(mod, name, opts)\n when is_atom(mod) and is_atom(name) and is_list(opts) do\n register_attribute(:ex_unit_registered_module_attributes, mod, name, opts)\n end\n\n defp register_attribute(type, mod, name, opts) do\n validate_registered_attribute!(type, mod, name)\n Module.register_attribute(mod, name, opts)\n Module.put_attribute(mod, type, name)\n end\n\n defp validate_registered_attribute!(type, mod, name) do\n registered_attribute_keys = [\n :ex_unit_registered_module_attributes,\n :ex_unit_registered_describe_attributes,\n :ex_unit_registered_test_attributes\n ]\n\n for key <- registered_attribute_keys,\n type != key and name in Module.get_attribute(mod, key) do\n raise ArgumentError, \"cannot register attribute #{inspect(name)} multiple times\"\n end\n\n if Module.has_attribute?(mod, name) do\n raise \"you must set @#{name} after it has been registered\"\n end\n end\n\n defp validate_tags(tags) do\n for tag <- @reserved, Map.has_key?(tags, tag) do\n raise \"cannot set tag #{inspect(tag)} because it is reserved by ExUnit\"\n end\n\n unless is_atom(tags[:test_type]) do\n raise(\"value for tag \\\":test_type\\\" must be an atom\")\n end\n\n tags\n end\n\n defp normalize_tags(tags) do\n Enum.reduce(Enum.reverse(tags), %{}, fn\n tag, acc when is_atom(tag) -> Map.put(acc, tag, true)\n tag, acc when is_list(tag) -> tag |> Enum.into(acc)\n end)\n end\nend\n","old_contents":"defmodule ExUnit.DuplicateTestError do\n defexception [:message]\nend\n\ndefmodule ExUnit.DuplicateDescribeError do\n defexception [:message]\nend\n\ndefmodule ExUnit.Case do\n @moduledoc \"\"\"\n Helpers for defining test cases.\n\n This module must be used in other modules as a way to configure\n and prepare them for testing.\n\n When used, it accepts the following options:\n\n * `:async` - configures tests in this module to run concurrently with\n tests in other modules. Tests in the same module never run concurrently.\n It should be enabled only if tests do not change any global state.\n Defaults to `false`.\n\n This module automatically includes all callbacks defined in\n `ExUnit.Callbacks`. See that module for more information on `setup`,\n `start_supervised`, `on_exit` and the test process life cycle.\n\n For grouping tests together, see `describe\/2` in this module.\n\n ## Examples\n\n defmodule AssertionTest do\n # Use the module\n use ExUnit.Case, async: true\n\n # The \"test\" macro is imported by ExUnit.Case\n test \"always pass\" do\n assert true\n end\n end\n\n ## Context\n\n All tests receive a context as an argument. The context is particularly\n useful for sharing information between callbacks and tests:\n\n defmodule KVTest do\n use ExUnit.Case\n\n setup do\n {:ok, pid} = KV.start_link()\n {:ok, pid: pid}\n end\n\n test \"stores key-value pairs\", context do\n assert KV.put(context[:pid], :hello, :world) == :ok\n assert KV.get(context[:pid], :hello) == :world\n end\n end\n\n As the context is a map, it can be pattern matched on to extract\n information:\n\n test \"stores key-value pairs\", %{pid: pid} = _context do\n assert KV.put(pid, :hello, :world) == :ok\n assert KV.get(pid, :hello) == :world\n end\n\n ## Tags\n\n The context is used to pass information from the callbacks to\n the test. In order to pass information from the test to the\n callback, ExUnit provides tags.\n\n By tagging a test, the tag value can be accessed in the context,\n allowing the developer to customize the test. Let's see an\n example:\n\n defmodule FileTest do\n # Changing directory cannot be async\n use ExUnit.Case, async: false\n\n setup context do\n # Read the :cd tag value\n if cd = context[:cd] do\n prev_cd = File.cwd!()\n File.cd!(cd)\n on_exit(fn -> File.cd!(prev_cd) end)\n end\n\n :ok\n end\n\n @tag cd: \"fixtures\"\n test \"reads UTF-8 fixtures\" do\n File.read(\"README.md\")\n end\n end\n\n In the example above, we have defined a tag called `:cd` that is\n read in the setup callback to configure the working directory the\n test is going to run on.\n\n Tags are also very effective when used with case templates\n (`ExUnit.CaseTemplate`) allowing callbacks in the case template\n to customize the test behaviour.\n\n Note a tag can be set in two different ways:\n\n @tag key: value\n @tag :key # equivalent to setting @tag key: true\n\n If a tag is given more than once, the last value wins.\n\n ### Module and describe tags\n\n A tag can be set for all tests in a module or describe block by\n setting `@moduletag` or `@describetag` inside each context\n respectively:\n\n defmodule ApiTest do\n use ExUnit.Case\n @moduletag :external\n\n describe \"makes calls to the right endpoint\" do\n @describetag :endpoint\n\n # ...\n end\n end\n\n If you are setting a `@moduletag` or `@describetag` attribute, you must\n set them after your call to `use ExUnit.Case` otherwise you will see\n compilation errors.\n\n If the same key is set via `@tag`, the `@tag` value has higher\n precedence.\n\n ### Known tags\n\n The following tags are set automatically by ExUnit and are\n therefore reserved:\n\n * `:module` - the module on which the test was defined\n\n * `:file` - the file on which the test was defined\n\n * `:line` - the line on which the test was defined\n\n * `:test` - the test name\n\n * `:async` - if the test case is in async mode\n\n * `:registered` - used for `ExUnit.Case.register_attribute\/3` values\n\n * `:describe` - the describe block the test belongs to\n\n The following tags customize how tests behave:\n\n * `:capture_log` - see the \"Log Capture\" section below\n\n * `:skip` - skips the test with the given reason\n\n * `:timeout` - customizes the test timeout in milliseconds (defaults to 60000).\n Accepts `:infinity` as a timeout value.\n\n * `:tmp_dir` - (since v1.11.0) see the \"Tmp Dir\" section below\n\n The `:test_type` tag is automatically set by ExUnit, but is **not** reserved.\n This tag is available for users to customize if they desire.\n\n ## Filters\n\n Tags can also be used to identify specific tests, which can then\n be included or excluded using filters. The most common functionality\n is to exclude some particular tests from running, which can be done\n via `ExUnit.configure\/1`:\n\n # Exclude all external tests from running\n ExUnit.configure(exclude: [external: true])\n\n From now on, ExUnit will not run any test that has the `:external` option\n set to `true`. This behaviour can be reversed with the `:include` option\n which is usually passed through the command line:\n\n mix test --include external:true\n\n Run `mix help test` for more information on how to run filters via Mix.\n\n Another use case for tags and filters is to exclude all tests that have\n a particular tag by default, regardless of its value, and include only\n a certain subset:\n\n ExUnit.configure(exclude: :os, include: [os: :unix])\n\n A given include\/exclude filter can be given more than once:\n\n ExUnit.configure(exclude: [os: :unix, os: :windows])\n\n Keep in mind that all tests are included by default, so unless they are\n excluded first, the `include` option has no effect.\n\n ## Log Capture\n\n ExUnit can optionally suppress printing of log messages that are generated\n during a test. Log messages generated while running a test are captured and\n only if the test fails are they printed to aid with debugging.\n\n You can opt into this behaviour for individual tests by tagging them with\n `:capture_log` or enable log capture for all tests in the ExUnit configuration:\n\n ExUnit.start(capture_log: true)\n\n This default can be overridden by `@tag capture_log: false` or\n `@moduletag capture_log: false`.\n\n Since `setup_all` blocks don't belong to a specific test, log messages generated\n in them (or between tests) are never captured. If you want to suppress these\n messages as well, remove the console backend globally by setting:\n\n config :logger, backends: []\n\n ## Tmp Dir\n\n ExUnit automatically creates a temporary directory for tests tagged with\n `:tmp_dir` and puts the path to that directory into the test context.\n The directory is removed before being created to ensure we start with a blank\n slate.\n\n The temporary directory path is unique (includes the test module and test name)\n and thus appropriate for running tests concurrently. You can customize the path\n further by setting the tag to a string, e.g.: `tmp_dir: \"my_path\"`, which would\n make the final path to be: `tmp\/\/\/my_path`.\n\n Example:\n\n defmodule MyTest do\n use ExUnit.Case, async: true\n\n @tag :tmp_dir\n test \"with tmp_dir\", %{tmp_dir: tmp_dir} do\n assert tmp_dir =~ \"with tmp_dir\"\n assert File.dir?(tmp_dir)\n end\n end\n\n As with other tags, `:tmp_dir` can also be set as `@moduletag` and\n `@describetag`.\n \"\"\"\n\n @type env :: module() | Macro.Env.t()\n\n @reserved [:module, :file, :line, :test, :async, :registered, :describe]\n\n @doc false\n defmacro __using__(opts) do\n unless Process.whereis(ExUnit.Server) do\n raise \"cannot use ExUnit.Case without starting the ExUnit application, \" <>\n \"please call ExUnit.start() or explicitly start the :ex_unit app\"\n end\n\n quote do\n unless ExUnit.Case.__register__(__MODULE__, unquote(opts)) do\n use ExUnit.Callbacks\n end\n\n import ExUnit.Callbacks\n import ExUnit.Assertions\n import ExUnit.Case, only: [describe: 2, test: 1, test: 2, test: 3]\n import ExUnit.DocTest\n end\n end\n\n @doc false\n def __register__(module, opts) do\n registered? = Module.has_attribute?(module, :ex_unit_tests)\n\n unless registered? do\n tag_check = Enum.any?([:moduletag, :describetag, :tag], &Module.has_attribute?(module, &1))\n\n if tag_check do\n raise \"you must set @tag, @describetag, and @moduletag after the call to \\\"use ExUnit.Case\\\"\"\n end\n\n attributes = [\n :ex_unit_tests,\n :tag,\n :describetag,\n :moduletag,\n :ex_unit_registered_test_attributes,\n :ex_unit_registered_describe_attributes,\n :ex_unit_registered_module_attributes,\n :ex_unit_used_describes\n ]\n\n Enum.each(attributes, &Module.register_attribute(module, &1, accumulate: true))\n\n attributes = [\n before_compile: ExUnit.Case,\n after_compile: ExUnit.Case,\n ex_unit_async: false,\n ex_unit_describe: nil\n ]\n\n Enum.each(attributes, fn {k, v} -> Module.put_attribute(module, k, v) end)\n end\n\n async? = opts[:async]\n\n if is_boolean(async?) do\n Module.put_attribute(module, :ex_unit_async, async?)\n end\n\n registered?\n end\n\n @doc \"\"\"\n Defines a test with `message`.\n\n The test may also define a pattern, which will be matched\n against the test context. For more information on contexts, see\n `ExUnit.Callbacks`.\n\n ## Examples\n\n test \"true is equal to true\" do\n assert true == true\n end\n\n \"\"\"\n defmacro test(message, var \\\\ quote(do: _), contents) do\n unless is_tuple(var) do\n IO.warn(\n \"test context is always a map. The pattern \" <>\n \"#{inspect(Macro.to_string(var))} will never match\",\n Macro.Env.stacktrace(__CALLER__)\n )\n end\n\n contents =\n case contents do\n [do: block] ->\n quote do\n unquote(block)\n :ok\n end\n\n _ ->\n quote do\n try(unquote(contents))\n :ok\n end\n end\n\n var = Macro.escape(var)\n contents = Macro.escape(contents, unquote: true)\n %{module: mod, file: file, line: line} = __CALLER__\n\n quote bind_quoted: [\n var: var,\n contents: contents,\n message: message,\n mod: mod,\n file: file,\n line: line\n ] do\n name = ExUnit.Case.register_test(mod, file, line, :test, message, [])\n def unquote(name)(unquote(var)), do: unquote(contents)\n end\n end\n\n @doc \"\"\"\n Defines a not implemented test with a string.\n\n Provides a convenient macro that allows a test to be defined\n with a string, but not yet implemented. The resulting test will\n always fail and print a \"Not implemented\" error message. The\n resulting test case is also tagged with `:not_implemented`.\n\n ## Examples\n\n test \"this will be a test in future\"\n\n \"\"\"\n defmacro test(message) do\n %{module: mod, file: file, line: line} = __CALLER__\n\n quote bind_quoted: binding() do\n name = ExUnit.Case.register_test(mod, file, line, :test, message, [:not_implemented])\n def unquote(name)(_), do: flunk(\"Not implemented\")\n end\n end\n\n @doc \"\"\"\n Describes tests together.\n\n Every describe block receives a name which is used as prefix for\n upcoming tests. Inside a block, `ExUnit.Callbacks.setup\/1` may be\n invoked and it will define a setup callback to run only for the\n current block. The describe name is also added as a tag, allowing\n developers to run tests for specific blocks.\n\n ## Examples\n\n defmodule StringTest do\n use ExUnit.Case, async: true\n\n describe \"String.capitalize\/1\" do\n test \"first grapheme is in uppercase\" do\n assert String.capitalize(\"hello\") == \"Hello\"\n end\n\n test \"converts remaining graphemes to lowercase\" do\n assert String.capitalize(\"HELLO\") == \"Hello\"\n end\n end\n end\n\n When using Mix, you can run all tests in a describe block by name:\n\n mix test --only describe:\"String.capitalize\/1\"\n\n or by passing the exact line the describe block starts on:\n\n mix test path\/to\/file:123\n\n Note describe blocks cannot be nested. Instead of relying on hierarchy\n for composition, developers should build on top of named setups. For\n example:\n\n defmodule UserManagementTest do\n use ExUnit.Case, async: true\n\n describe \"when user is logged in and is an admin\" do\n setup [:log_user_in, :set_type_to_admin]\n\n test ...\n end\n\n describe \"when user is logged in and is a manager\" do\n setup [:log_user_in, :set_type_to_manager]\n\n test ...\n end\n\n defp log_user_in(context) do\n # ...\n end\n end\n\n By forbidding hierarchies in favor of named setups, it is straightforward\n for the developer to glance at each describe block and know exactly the\n setup steps involved.\n \"\"\"\n defmacro describe(message, do: block) do\n quote do\n ExUnit.Case.__describe__(__MODULE__, __ENV__.line, unquote(message), fn ->\n unquote(block)\n end)\n end\n end\n\n @doc false\n def __describe__(module, line, message, fun) do\n if Module.get_attribute(module, :ex_unit_describe) do\n raise \"cannot call \\\"describe\\\" inside another \\\"describe\\\". See the documentation \" <>\n \"for ExUnit.Case.describe\/2 on named setups and how to handle hierarchies\"\n end\n\n cond do\n not is_binary(message) ->\n raise ArgumentError, \"describe name must be a string, got: #{inspect(message)}\"\n\n message in Module.get_attribute(module, :ex_unit_used_describes) ->\n raise ExUnit.DuplicateDescribeError,\n \"describe #{inspect(message)} is already defined in #{inspect(module)}\"\n\n true ->\n :ok\n end\n\n if Module.get_attribute(module, :describetag) != [] do\n raise \"@describetag must be set inside describe\/2 blocks\"\n end\n\n Module.put_attribute(module, :ex_unit_describe, {line, message})\n Module.put_attribute(module, :ex_unit_used_describes, message)\n\n try do\n fun.()\n after\n Module.put_attribute(module, :ex_unit_describe, nil)\n Module.delete_attribute(module, :describetag)\n\n for attribute <- Module.get_attribute(module, :ex_unit_registered_describe_attributes) do\n Module.delete_attribute(module, attribute)\n end\n end\n end\n\n @doc false\n defmacro __before_compile__(_) do\n quote do\n def __ex_unit__ do\n %ExUnit.TestModule{file: __ENV__.file, name: __MODULE__, tests: @ex_unit_tests}\n end\n end\n end\n\n @doc false\n def __after_compile__(%{module: module}, _) do\n if Module.get_attribute(module, :ex_unit_async) do\n ExUnit.Server.add_async_module(module)\n else\n ExUnit.Server.add_sync_module(module)\n end\n end\n\n @doc \"\"\"\n Registers a function to run as part of this case.\n\n This is used by third-party projects, like QuickCheck, to\n implement macros like `property\/3` that works like `test`\n but instead defines a property. See `test\/3` implementation\n for an example of invoking this function.\n\n The test type will be converted to a string and pluralized for\n display. You can use `ExUnit.plural_rule\/2` to set a custom\n pluralization.\n \"\"\"\n def register_test(mod, file, line, test_type, name, tags) do\n unless Module.has_attribute?(mod, :ex_unit_tests) do\n raise \"cannot define #{test_type}. Please make sure you have invoked \" <>\n \"\\\"use ExUnit.Case\\\" in the current module\"\n end\n\n registered_attribute_keys = [\n :ex_unit_registered_module_attributes,\n :ex_unit_registered_describe_attributes,\n :ex_unit_registered_test_attributes\n ]\n\n registered =\n for key <- registered_attribute_keys,\n attribute <- Module.get_attribute(mod, key),\n into: %{} do\n {attribute, Module.get_attribute(mod, attribute)}\n end\n\n moduletag = Module.get_attribute(mod, :moduletag)\n tag = Module.delete_attribute(mod, :tag)\n async = Module.get_attribute(mod, :ex_unit_async)\n\n {name, describe, describe_line, describetag} =\n case Module.get_attribute(mod, :ex_unit_describe) do\n {line, describe} ->\n description = :\"#{test_type} #{describe} #{name}\"\n {description, describe, line, Module.get_attribute(mod, :describetag)}\n\n _ ->\n {:\"#{test_type} #{name}\", nil, nil, []}\n end\n\n if Module.defines?(mod, {name, 1}) do\n raise ExUnit.DuplicateTestError, ~s(\"#{name}\" is already defined in #{inspect(mod)})\n end\n\n tags =\n (tags ++ tag ++ describetag ++ moduletag)\n |> normalize_tags\n |> validate_tags\n |> Map.merge(%{\n line: line,\n file: file,\n registered: registered,\n async: async,\n describe: describe,\n describe_line: describe_line,\n test_type: test_type\n })\n\n test = %ExUnit.Test{name: name, case: mod, tags: tags, module: mod}\n Module.put_attribute(mod, :ex_unit_tests, test)\n\n for attribute <- Module.get_attribute(mod, :ex_unit_registered_test_attributes) do\n Module.delete_attribute(mod, attribute)\n end\n\n name\n end\n\n @doc \"\"\"\n Registers a test with the given environment.\n\n This function is deprecated in favor of `register_test\/6` which performs\n better under tight loops by avoiding `__ENV__`.\n \"\"\"\n @doc deprecated: \"Use register_test\/6 instead\"\n def register_test(%{module: mod, file: file, line: line}, test_type, name, tags) do\n register_test(mod, file, line, test_type, name, tags)\n end\n\n @doc \"\"\"\n Registers a new attribute to be used during `ExUnit.Case` tests.\n\n The attribute values will be available through `context.registered`.\n Registered values are cleared after each `test\/3` similar\n to `@tag`.\n\n This function takes the same options as `Module.register_attribute\/3`.\n\n ## Examples\n\n defmodule MyTest do\n use ExUnit.Case\n\n ExUnit.Case.register_attribute(__MODULE__, :fixtures, accumulate: true)\n\n @fixtures :user\n @fixtures {:post, insert: false}\n test \"using custom attribute\", context do\n assert context.registered.fixtures == [{:post, insert: false}, :user]\n end\n\n test \"custom attributes are cleared per test\", context do\n assert context.registered.fixtures == []\n end\n end\n\n \"\"\"\n @spec register_attribute(env, atom, keyword) :: :ok\n def register_attribute(env, name, opts \\\\ [])\n def register_attribute(%{module: mod}, name, opts), do: register_attribute(mod, name, opts)\n\n def register_attribute(mod, name, opts) when is_atom(mod) and is_atom(name) and is_list(opts) do\n register_attribute(:ex_unit_registered_test_attributes, mod, name, opts)\n end\n\n @doc \"\"\"\n Registers a new describe attribute to be used during `ExUnit.Case` tests.\n\n The attribute values will be available through `context.registered`.\n Registered values are cleared after each `describe\/2` similar\n to `@describetag`.\n\n This function takes the same options as `Module.register_attribute\/3`.\n\n ## Examples\n\n defmodule MyTest do\n use ExUnit.Case\n\n ExUnit.Case.register_describe_attribute(__MODULE__, :describe_fixtures, accumulate: true)\n\n describe \"using custom attribute\" do\n @describe_fixtures :user\n @describe_fixtures {:post, insert: false}\n\n test \"has attribute\", context do\n assert context.registered.describe_fixtures == [{:post, insert: false}, :user]\n end\n end\n\n describe \"custom attributes are cleared per describe\" do\n test \"doesn't have attributes\", context do\n assert context.registered.describe_fixtures == []\n end\n end\n end\n\n \"\"\"\n @doc since: \"1.10.0\"\n @spec register_describe_attribute(env, atom, keyword) :: :ok\n def register_describe_attribute(env, name, opts \\\\ [])\n\n def register_describe_attribute(%{module: mod}, name, opts) do\n register_describe_attribute(mod, name, opts)\n end\n\n def register_describe_attribute(mod, name, opts)\n when is_atom(mod) and is_atom(name) and is_list(opts) do\n register_attribute(:ex_unit_registered_describe_attributes, mod, name, opts)\n end\n\n @doc \"\"\"\n Registers a new module attribute to be used during `ExUnit.Case` tests.\n\n The attribute values will be available through `context.registered`.\n\n This function takes the same options as `Module.register_attribute\/3`.\n\n ## Examples\n\n defmodule MyTest do\n use ExUnit.Case\n\n ExUnit.Case.register_module_attribute(__MODULE__, :module_fixtures, accumulate: true)\n\n @module_fixtures :user\n @module_fixtures {:post, insert: false}\n\n test \"using custom attribute\", context do\n assert context.registered.fixtures == [{:post, insert: false}, :user]\n end\n\n test \"still using custom attribute\", context do\n assert context.registered.fixtures == [{:post, insert: false}, :user]\n end\n end\n\n \"\"\"\n @doc since: \"1.10.0\"\n @spec register_module_attribute(env, atom, keyword) :: :ok\n def register_module_attribute(env, name, opts \\\\ [])\n\n def register_module_attribute(%{module: mod}, name, opts) do\n register_module_attribute(mod, name, opts)\n end\n\n def register_module_attribute(mod, name, opts)\n when is_atom(mod) and is_atom(name) and is_list(opts) do\n register_attribute(:ex_unit_registered_module_attributes, mod, name, opts)\n end\n\n defp register_attribute(type, mod, name, opts) do\n validate_registered_attribute!(type, mod, name)\n Module.register_attribute(mod, name, opts)\n Module.put_attribute(mod, type, name)\n end\n\n defp validate_registered_attribute!(type, mod, name) do\n registered_attribute_keys = [\n :ex_unit_registered_module_attributes,\n :ex_unit_registered_describe_attributes,\n :ex_unit_registered_test_attributes\n ]\n\n for key <- registered_attribute_keys,\n type != key and name in Module.get_attribute(mod, key) do\n raise ArgumentError, \"cannot register attribute #{inspect(name)} multiple times\"\n end\n\n if Module.has_attribute?(mod, name) do\n raise \"you must set @#{name} after it has been registered\"\n end\n end\n\n defp validate_tags(tags) do\n for tag <- @reserved, Map.has_key?(tags, tag) do\n raise \"cannot set tag #{inspect(tag)} because it is reserved by ExUnit\"\n end\n\n unless is_atom(tags[:test_type]) do\n raise(\"value for tag \\\":test_type\\\" must be an atom\")\n end\n\n tags\n end\n\n defp normalize_tags(tags) do\n Enum.reduce(Enum.reverse(tags), %{}, fn\n tag, acc when is_atom(tag) -> Map.put(acc, tag, true)\n tag, acc when is_list(tag) -> tag |> Enum.into(acc)\n end)\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"61b662a29c66493074665f39632cb176d8bc09d6","subject":"Run the code formatter on Mix.DepTest (#6731)","message":"Run the code formatter on Mix.DepTest (#6731)\n\n","repos":"ggcampinho\/elixir,beedub\/elixir,kelvinst\/elixir,pedrosnk\/elixir,elixir-lang\/elixir,michalmuskala\/elixir,joshprice\/elixir,antipax\/elixir,lexmag\/elixir,kelvinst\/elixir,kimshrier\/elixir,gfvcastro\/elixir,beedub\/elixir,antipax\/elixir,gfvcastro\/elixir,kimshrier\/elixir,pedrosnk\/elixir,lexmag\/elixir,ggcampinho\/elixir","old_file":"lib\/mix\/test\/mix\/dep_test.exs","new_file":"lib\/mix\/test\/mix\/dep_test.exs","new_contents":"Code.require_file(\"..\/test_helper.exs\", __DIR__)\n\ndefmodule Mix.DepTest do\n use MixTest.Case\n\n defmodule DepsApp do\n def project do\n [\n deps: [\n {:ok, \"0.1.0\", path: \"deps\/ok\"},\n {:invalidvsn, \"0.2.0\", path: \"deps\/invalidvsn\"},\n {:invalidapp, \"0.1.0\", path: \"deps\/invalidapp\"},\n {:noappfile, \"0.1.0\", path: \"deps\/noappfile\"},\n {:uncloned, git: \"https:\/\/github.com\/elixir-lang\/uncloned.git\"},\n {:optional, git: \"https:\/\/github.com\/elixir-lang\/optional.git\", optional: true}\n ]\n ]\n end\n end\n\n defmodule ProcessDepsApp do\n def project do\n [app: :process_deps_app, deps: Process.get(:mix_deps)]\n end\n end\n\n defp with_deps(deps, fun) do\n Process.put(:mix_deps, deps)\n Mix.Project.push(ProcessDepsApp)\n fun.()\n after\n Mix.Project.pop()\n end\n\n defp assert_wrong_dependency(deps) do\n with_deps(deps, fn ->\n assert_raise Mix.Error, ~r\"Dependency specified in the wrong format\", fn ->\n Mix.Dep.loaded([])\n end\n end)\n end\n\n test \"respects the MIX_NO_DEPS flag\" do\n Mix.Project.push(DepsApp)\n\n in_fixture \"deps_status\", fn ->\n deps = Mix.Dep.cached()\n assert length(deps) == 6\n\n System.put_env(\"MIX_NO_DEPS\", \"1\")\n deps = Mix.Dep.cached()\n assert length(deps) == 0\n end\n after\n System.delete_env(\"MIX_NO_DEPS\")\n end\n\n test \"extracts all dependencies from the given project\" do\n Mix.Project.push(DepsApp)\n\n in_fixture \"deps_status\", fn ->\n deps = Mix.Dep.loaded([])\n assert length(deps) == 6\n assert Enum.find(deps, &match?(%Mix.Dep{app: :ok, status: {:ok, _}}, &1))\n assert Enum.find(deps, &match?(%Mix.Dep{app: :invalidvsn, status: {:invalidvsn, :ok}}, &1))\n assert Enum.find(deps, &match?(%Mix.Dep{app: :invalidapp, status: {:invalidapp, _}}, &1))\n assert Enum.find(deps, &match?(%Mix.Dep{app: :noappfile, status: {:noappfile, _}}, &1))\n assert Enum.find(deps, &match?(%Mix.Dep{app: :uncloned, status: {:unavailable, _}}, &1))\n assert Enum.find(deps, &match?(%Mix.Dep{app: :optional, status: {:unavailable, _}}, &1))\n end\n end\n\n test \"extracts all dependencies paths from the given project\" do\n Mix.Project.push(DepsApp)\n\n in_fixture \"deps_status\", fn ->\n paths = Mix.Project.deps_paths()\n assert map_size(paths) == 6\n assert paths[:ok] =~ \"deps\/ok\"\n assert paths[:uncloned] =~ \"deps\/uncloned\"\n end\n end\n\n test \"fails on invalid dependencies\" do\n assert_wrong_dependency([{:ok}])\n assert_wrong_dependency([{:ok, nil}])\n assert_wrong_dependency([{:ok, nil, []}])\n end\n\n test \"use requirements for dependencies\" do\n with_deps([{:ok, \"~> 0.1\", path: \"deps\/ok\"}], fn ->\n in_fixture \"deps_status\", fn ->\n deps = Mix.Dep.loaded([])\n assert Enum.find(deps, &match?(%Mix.Dep{app: :ok, status: {:ok, _}}, &1))\n end\n end)\n end\n\n test \"raises when no SCM is specified\" do\n with_deps([{:ok, \"~> 0.1\", not_really: :ok}], fn ->\n in_fixture \"deps_status\", fn ->\n send(self(), {:mix_shell_input, :yes?, false})\n msg = \"Could not find an SCM for dependency :ok from Mix.DepTest.ProcessDepsApp\"\n assert_raise Mix.Error, msg, fn -> Mix.Dep.loaded([]) end\n end\n end)\n end\n\n test \"does not set the manager before the dependency was loaded\" do\n # It is important to not eagerly set the manager because the dependency\n # needs to be loaded (i.e. available in the filesystem) in order to get\n # the proper manager.\n Mix.Project.push(DepsApp)\n\n {_, true, _} =\n Mix.Dep.Converger.converge(false, [], nil, fn dep, acc, lock ->\n assert is_nil(dep.manager)\n {dep, acc or true, lock}\n end)\n end\n\n test \"raises on invalid deps req\" do\n with_deps([{:ok, \"+- 0.1.0\", path: \"deps\/ok\"}], fn ->\n in_fixture \"deps_status\", fn ->\n assert_raise Mix.Error, ~r\"Invalid requirement\", fn ->\n Mix.Dep.loaded([])\n end\n end\n end)\n end\n\n test \"nested deps come first\" do\n with_deps([{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"}], fn ->\n in_fixture \"deps_status\", fn ->\n assert Enum.map(Mix.Dep.loaded([]), & &1.app) == [:git_repo, :deps_repo]\n end\n end)\n end\n\n test \"nested optional deps are never added\" do\n with_deps([{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"}], fn ->\n in_fixture \"deps_status\", fn ->\n File.write!(\"custom\/deps_repo\/mix.exs\", \"\"\"\n defmodule DepsRepo do\n use Mix.Project\n\n def project do\n [app: :deps_repo,\n version: \"0.1.0\",\n deps: [{:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\"), optional: true}]]\n end\n end\n \"\"\")\n\n assert Enum.map(Mix.Dep.loaded([]), & &1.app) == [:deps_repo]\n end\n end)\n end\n\n test \"nested deps with convergence\" do\n deps = [\n {:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\")}\n ]\n\n with_deps(deps, fn ->\n in_fixture \"deps_status\", fn ->\n assert Enum.map(Mix.Dep.loaded([]), & &1.app) == [:git_repo, :deps_repo]\n end\n end)\n end\n\n test \"nested deps with convergence and managers\" do\n Process.put(:custom_deps_git_repo_opts, manager: :make)\n\n deps = [\n {:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\", manager: :rebar},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\")}\n ]\n\n with_deps(deps, fn ->\n in_fixture \"deps_status\", fn ->\n [dep1, dep2] = Mix.Dep.loaded([])\n assert dep1.manager == nil\n assert dep2.manager == :rebar\n end\n end)\n end\n\n test \"nested deps with convergence and optional dependencies\" do\n deps = [\n {:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\")}\n ]\n\n with_deps(deps, fn ->\n in_fixture \"deps_status\", fn ->\n File.write!(\"custom\/deps_repo\/mix.exs\", \"\"\"\n defmodule DepsRepo do\n use Mix.Project\n\n def project do\n [app: :deps_repo,\n version: \"0.1.0\",\n deps: [{:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\"), optional: true}]]\n end\n end\n \"\"\")\n\n assert Enum.map(Mix.Dep.loaded([]), & &1.app) == [:git_repo, :deps_repo]\n end\n end)\n end\n\n test \"nested deps with optional dependencies and cousin conflict\" do\n with_deps(\n [\n {:deps_repo1, \"0.1.0\", path: \"custom\/deps_repo1\"},\n {:deps_repo2, \"0.1.0\", path: \"custom\/deps_repo2\"}\n ],\n fn ->\n in_fixture \"deps_status\", fn ->\n File.mkdir_p!(\"custom\/deps_repo1\")\n\n File.write!(\"custom\/deps_repo1\/mix.exs\", \"\"\"\n defmodule DepsRepo1 do\n use Mix.Project\n\n def project do\n [app: :deps_repo1,\n version: \"0.1.0\",\n deps: [{:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\"), optional: true}]]\n end\n end\n \"\"\")\n\n File.mkdir_p!(\"custom\/deps_repo2\")\n\n File.write!(\"custom\/deps_repo2\/mix.exs\", \"\"\"\n defmodule DepsRepo2 do\n use Mix.Project\n\n def project do\n [app: :deps_repo2,\n version: \"0.1.0\",\n deps: [{:git_repo, \"0.2.0\", path: \"somewhere\"}]]\n end\n end\n \"\"\")\n\n Mix.Tasks.Deps.run([])\n assert_received {:mix_shell, :info, [\"* git_repo\" <> _]}\n assert_received {:mix_shell, :info, [msg]}\n assert msg =~ \"different specs were given for the git_repo\"\n end\n end\n )\n end\n\n ## Remove converger\n\n defmodule IdentityRemoteConverger do\n @behaviour Mix.RemoteConverger\n\n def remote?(%Mix.Dep{app: :deps_repo}), do: false\n def remote?(%Mix.Dep{}), do: true\n def deps(_dep, _lock), do: []\n def post_converge, do: :ok\n\n def converge(deps, lock) do\n Process.put(:remote_converger, deps)\n lock\n end\n end\n\n test \"remote converger\" do\n deps = [\n {:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\")}\n ]\n\n with_deps(deps, fn ->\n Mix.RemoteConverger.register(IdentityRemoteConverger)\n\n in_fixture \"deps_status\", fn ->\n Mix.Tasks.Deps.Get.run([])\n\n message = \"* Getting git_repo (#{fixture_path(\"git_repo\")})\"\n assert_received {:mix_shell, :info, [^message]}\n\n assert Process.get(:remote_converger)\n end\n end)\n after\n Mix.RemoteConverger.register(nil)\n end\n\n test \"pass dependencies to remote converger in defined order\" do\n deps = [\n {:ok, \"0.1.0\", path: \"deps\/ok\"},\n {:invalidvsn, \"0.2.0\", path: \"deps\/invalidvsn\"},\n {:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"},\n {:invalidapp, \"0.1.0\", path: \"deps\/invalidapp\"},\n {:noappfile, \"0.1.0\", path: \"deps\/noappfile\"}\n ]\n\n with_deps(deps, fn ->\n Mix.RemoteConverger.register(IdentityRemoteConverger)\n\n in_fixture \"deps_status\", fn ->\n Mix.Tasks.Deps.Get.run([])\n\n deps = Process.get(:remote_converger) |> Enum.map(& &1.app)\n assert deps == [:ok, :invalidvsn, :deps_repo, :invalidapp, :noappfile, :git_repo]\n end\n end)\n after\n Mix.RemoteConverger.register(nil)\n end\n\n defmodule RaiseRemoteConverger do\n @behaviour Mix.RemoteConverger\n\n def remote?(_app), do: false\n def deps(_dep, _lock), do: :ok\n def post_converge, do: :ok\n\n def converge(_deps, lock) do\n Process.put(:remote_converger, true)\n lock\n end\n end\n\n test \"remote converger is not invoked if deps diverge\" do\n deps = [\n {:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\"), only: :test}\n ]\n\n with_deps(deps, fn ->\n Mix.RemoteConverger.register(RaiseRemoteConverger)\n\n in_fixture \"deps_status\", fn ->\n assert_raise Mix.Error, fn ->\n Mix.Tasks.Deps.Get.run([])\n end\n\n assert_received {:mix_shell, :error, [\"Dependencies have diverged:\"]}\n refute Process.get(:remote_converger)\n end\n end)\n after\n Mix.RemoteConverger.register(nil)\n end\n\n test \"remote converger is not invoked if deps graph has cycles\" do\n deps = [{:app1, \"0.1.0\", path: \"app1\"}, {:app2, \"0.1.0\", path: \"app2\"}]\n\n with_deps(deps, fn ->\n Mix.RemoteConverger.register(RaiseRemoteConverger)\n\n in_fixture \"deps_cycle\", fn ->\n assert_raise Mix.Error, ~r\/cycles in the dependency graph\/, fn ->\n Mix.Tasks.Deps.Get.run([])\n end\n\n refute Process.get(:remote_converger)\n end\n end)\n after\n Mix.RemoteConverger.register(nil)\n end\n\n ## Only handling\n\n test \"only extracts deps matching environment\" do\n with_deps(\n [{:foo, github: \"elixir-lang\/foo\"}, {:bar, github: \"elixir-lang\/bar\", only: :other_env}],\n fn ->\n in_fixture \"deps_status\", fn ->\n deps = Mix.Dep.loaded(env: :other_env)\n assert length(deps) == 2\n\n deps = Mix.Dep.loaded([])\n assert length(deps) == 2\n\n assert [dep] = Mix.Dep.loaded(env: :prod)\n assert dep.app == :foo\n end\n end\n )\n end\n\n test \"only fetches parent deps matching specified env\" do\n with_deps([{:only, github: \"elixir-lang\/only\", only: [:dev]}], fn ->\n in_fixture \"deps_status\", fn ->\n Mix.Tasks.Deps.Get.run([\"--only\", \"prod\"])\n refute_received {:mix_shell, :info, [\"* Getting\" <> _]}\n\n assert_raise Mix.Error, \"Can't continue due to errors on dependencies\", fn ->\n Mix.Tasks.Deps.Loadpaths.run([])\n end\n\n Mix.ProjectStack.clear_cache()\n Mix.env(:prod)\n Mix.Tasks.Deps.Loadpaths.run([])\n end\n end)\n end\n\n test \"nested deps selects only prod dependencies\" do\n Process.put(:custom_deps_git_repo_opts, only: :test)\n deps = [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"}]\n\n with_deps(deps, fn ->\n in_fixture \"deps_status\", fn ->\n loaded = Mix.Dep.loaded([])\n assert [:deps_repo] = Enum.map(loaded, & &1.app)\n\n loaded = Mix.Dep.loaded(env: :test)\n assert [:deps_repo] = Enum.map(loaded, & &1.app)\n end\n end)\n end\n\n test \"nested deps on only matching\" do\n # deps_repo wants git_repo for test, git_repo is restricted to only test\n # We assert the dependencies match as expected, happens in umbrella apps\n Process.put(:custom_deps_git_repo_opts, only: :test)\n\n # We need to pass env: :test so the child dependency is loaded\n # in the first place (otherwise only :prod deps are loaded)\n deps = [\n {:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\", env: :test},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\"), only: :test}\n ]\n\n with_deps(deps, fn ->\n in_fixture \"deps_status\", fn ->\n loaded = Mix.Dep.loaded([])\n assert [:git_repo, :deps_repo] = Enum.map(loaded, & &1.app)\n assert [unavailable: _, noappfile: _] = Enum.map(loaded, & &1.status)\n\n loaded = Mix.Dep.loaded(env: :dev)\n assert [:deps_repo] = Enum.map(loaded, & &1.app)\n assert [noappfile: _] = Enum.map(loaded, & &1.status)\n\n loaded = Mix.Dep.loaded(env: :test)\n assert [:git_repo, :deps_repo] = Enum.map(loaded, & &1.app)\n assert [unavailable: _, noappfile: _] = Enum.map(loaded, & &1.status)\n end\n end)\n end\n\n test \"nested deps on only conflict\" do\n # deps_repo wants all git_repo, git_repo is restricted to only test\n deps = [\n {:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\"), only: :test}\n ]\n\n with_deps(deps, fn ->\n in_fixture \"deps_status\", fn ->\n loaded = Mix.Dep.loaded([])\n assert [:git_repo, :deps_repo] = Enum.map(loaded, & &1.app)\n assert [divergedonly: _, noappfile: _] = Enum.map(loaded, & &1.status)\n\n loaded = Mix.Dep.loaded(env: :dev)\n assert [:git_repo, :deps_repo] = Enum.map(loaded, & &1.app)\n assert [divergedonly: _, noappfile: _] = Enum.map(loaded, & &1.status)\n\n loaded = Mix.Dep.loaded(env: :test)\n assert [:git_repo, :deps_repo] = Enum.map(loaded, & &1.app)\n assert [divergedonly: _, noappfile: _] = Enum.map(loaded, & &1.status)\n\n Mix.Tasks.Deps.run([])\n assert_received {:mix_shell, :info, [\"* git_repo\" <> _]}\n assert_received {:mix_shell, :info, [msg]}\n assert msg =~ \"Remove the :only restriction from your dep\"\n end\n end)\n end\n\n test \"nested deps on only conflict does not happen with optional deps\" do\n Process.put(:custom_deps_git_repo_opts, optional: true)\n\n # deps_repo wants all git_repo, git_repo is restricted to only test\n deps = [\n {:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\"), only: :test}\n ]\n\n with_deps(deps, fn ->\n in_fixture \"deps_status\", fn ->\n loaded = Mix.Dep.loaded([])\n assert [:git_repo, :deps_repo] = Enum.map(loaded, & &1.app)\n assert [unavailable: _, noappfile: _] = Enum.map(loaded, & &1.status)\n\n loaded = Mix.Dep.loaded(env: :dev)\n assert [:deps_repo] = Enum.map(loaded, & &1.app)\n assert [noappfile: _] = Enum.map(loaded, & &1.status)\n\n loaded = Mix.Dep.loaded(env: :test)\n assert [:git_repo, :deps_repo] = Enum.map(loaded, & &1.app)\n assert [unavailable: _, noappfile: _] = Enum.map(loaded, & &1.status)\n end\n end)\n end\n\n test \"nested deps with valid only subset\" do\n # deps_repo wants git_repo for prod, git_repo is restricted to only prod and test\n deps = [\n {:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\", only: :prod},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\"), only: [:prod, :test]}\n ]\n\n with_deps(deps, fn ->\n in_fixture \"deps_status\", fn ->\n loaded = Mix.Dep.loaded([])\n assert [:git_repo, :deps_repo] = Enum.map(loaded, & &1.app)\n assert [unavailable: _, noappfile: _] = Enum.map(loaded, & &1.status)\n\n loaded = Mix.Dep.loaded(env: :dev)\n assert [] = Enum.map(loaded, & &1.app)\n\n loaded = Mix.Dep.loaded(env: :test)\n assert [:git_repo] = Enum.map(loaded, & &1.app)\n assert [unavailable: _] = Enum.map(loaded, & &1.status)\n\n loaded = Mix.Dep.loaded(env: :prod)\n assert [:git_repo, :deps_repo] = Enum.map(loaded, & &1.app)\n assert [unavailable: _, noappfile: _] = Enum.map(loaded, & &1.status)\n end\n end)\n end\n\n test \"nested deps with invalid only subset\" do\n # deps_repo wants git_repo for dev, git_repo is restricted to only test\n deps = [\n {:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\", only: :dev},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\"), only: [:test]}\n ]\n\n with_deps(deps, fn ->\n in_fixture \"deps_status\", fn ->\n loaded = Mix.Dep.loaded([])\n assert [:git_repo, :deps_repo] = Enum.map(loaded, & &1.app)\n assert [divergedonly: _, noappfile: _] = Enum.map(loaded, & &1.status)\n\n loaded = Mix.Dep.loaded(env: :dev)\n assert [:git_repo, :deps_repo] = Enum.map(loaded, & &1.app)\n assert [divergedonly: _, noappfile: _] = Enum.map(loaded, & &1.status)\n\n loaded = Mix.Dep.loaded(env: :test)\n assert [:git_repo] = Enum.map(loaded, & &1.app)\n assert [unavailable: _] = Enum.map(loaded, & &1.status)\n\n Mix.Tasks.Deps.run([])\n assert_received {:mix_shell, :info, [\"* git_repo\" <> _]}\n assert_received {:mix_shell, :info, [msg]}\n assert msg =~ \"Ensure you specify at least the same environments in :only in your dep\"\n end\n end)\n end\n\n test \"nested deps with valid only in both parent and child\" do\n Process.put(:custom_deps_git_repo_opts, only: :test)\n\n # deps_repo has environment set to test so it loads the deps_git_repo set to test too\n deps = [\n {:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\", env: :test, only: [:dev, :test]},\n {:git_repo, \"0.1.0\", git: MixTest.Case.fixture_path(\"git_repo\"), only: :test}\n ]\n\n with_deps(deps, fn ->\n in_fixture \"deps_status\", fn ->\n loaded = Mix.Dep.loaded([])\n assert [:git_repo, :deps_repo] = Enum.map(loaded, & &1.app)\n assert [unavailable: _, noappfile: _] = Enum.map(loaded, & &1.status)\n\n loaded = Mix.Dep.loaded(env: :dev)\n assert [:deps_repo] = Enum.map(loaded, & &1.app)\n assert [noappfile: _] = Enum.map(loaded, & &1.status)\n\n loaded = Mix.Dep.loaded(env: :test)\n assert [:git_repo, :deps_repo] = Enum.map(loaded, & &1.app)\n assert [unavailable: _, noappfile: _] = Enum.map(loaded, & &1.status)\n\n loaded = Mix.Dep.loaded(env: :prod)\n assert [] = Enum.map(loaded, & &1.app)\n end\n end)\n end\n\n test \"nested deps converge and diverge when only is not in_upper\" do\n loaded_only = fn deps ->\n with_deps(deps, fn ->\n in_fixture \"deps_status\", fn ->\n File.mkdir_p!(\"custom\/other_repo\")\n\n File.write!(\"custom\/other_repo\/mix.exs\", \"\"\"\n defmodule OtherRepo do\n use Mix.Project\n\n def project do\n [app: :deps_repo,\n version: \"0.1.0\",\n deps: [{:git_repo, \"0.1.0\", git: MixTest.Case.fixture_path(\"git_repo\")}]]\n end\n end\n \"\"\")\n\n Mix.ProjectStack.clear_cache()\n loaded = Mix.Dep.loaded([])\n assert [:git_repo, _, _] = Enum.map(loaded, & &1.app)\n hd(loaded).opts[:only]\n end\n end)\n end\n\n deps = [\n {:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\", only: :prod},\n {:other_repo, \"0.1.0\", path: \"custom\/other_repo\", only: :test}\n ]\n\n assert loaded_only.(deps) == [:test, :prod]\n\n deps = [\n {:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"},\n {:other_repo, \"0.1.0\", path: \"custom\/other_repo\", only: :test}\n ]\n\n refute loaded_only.(deps)\n\n deps = [\n {:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\", only: :prod},\n {:other_repo, \"0.1.0\", path: \"custom\/other_repo\"}\n ]\n\n refute loaded_only.(deps)\n\n deps = [\n {:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"},\n {:other_repo, \"0.1.0\", path: \"custom\/other_repo\"}\n ]\n\n refute loaded_only.(deps)\n\n Process.put(:custom_deps_git_repo_opts, optional: true)\n\n deps = [\n {:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\", only: :prod},\n {:other_repo, \"0.1.0\", path: \"custom\/other_repo\", only: :test}\n ]\n\n assert loaded_only.(deps) == :test\n end\nend\n","old_contents":"Code.require_file \"..\/test_helper.exs\", __DIR__\n\ndefmodule Mix.DepTest do\n use MixTest.Case\n\n defmodule DepsApp do\n def project do\n [deps: [\n {:ok, \"0.1.0\", path: \"deps\/ok\"},\n {:invalidvsn, \"0.2.0\", path: \"deps\/invalidvsn\"},\n {:invalidapp, \"0.1.0\", path: \"deps\/invalidapp\"},\n {:noappfile, \"0.1.0\", path: \"deps\/noappfile\"},\n {:uncloned, git: \"https:\/\/github.com\/elixir-lang\/uncloned.git\"},\n {:optional, git: \"https:\/\/github.com\/elixir-lang\/optional.git\", optional: true}\n ]]\n end\n end\n\n defmodule ProcessDepsApp do\n def project do\n [app: :process_deps_app, deps: Process.get(:mix_deps)]\n end\n end\n\n defp with_deps(deps, fun) do\n Process.put(:mix_deps, deps)\n Mix.Project.push ProcessDepsApp\n fun.()\n after\n Mix.Project.pop\n end\n\n defp assert_wrong_dependency(deps) do\n with_deps deps, fn ->\n assert_raise Mix.Error, ~r\"Dependency specified in the wrong format\", fn ->\n Mix.Dep.loaded([])\n end\n end\n end\n\n test \"respects the MIX_NO_DEPS flag\" do\n Mix.Project.push DepsApp\n\n in_fixture \"deps_status\", fn ->\n deps = Mix.Dep.cached()\n assert length(deps) == 6\n\n System.put_env(\"MIX_NO_DEPS\", \"1\")\n deps = Mix.Dep.cached()\n assert length(deps) == 0\n end\n after\n System.delete_env(\"MIX_NO_DEPS\")\n end\n\n test \"extracts all dependencies from the given project\" do\n Mix.Project.push DepsApp\n\n in_fixture \"deps_status\", fn ->\n deps = Mix.Dep.loaded([])\n assert length(deps) == 6\n assert Enum.find deps, &match?(%Mix.Dep{app: :ok, status: {:ok, _}}, &1)\n assert Enum.find deps, &match?(%Mix.Dep{app: :invalidvsn, status: {:invalidvsn, :ok}}, &1)\n assert Enum.find deps, &match?(%Mix.Dep{app: :invalidapp, status: {:invalidapp, _}}, &1)\n assert Enum.find deps, &match?(%Mix.Dep{app: :noappfile, status: {:noappfile, _}}, &1)\n assert Enum.find deps, &match?(%Mix.Dep{app: :uncloned, status: {:unavailable, _}}, &1)\n assert Enum.find deps, &match?(%Mix.Dep{app: :optional, status: {:unavailable, _}}, &1)\n end\n end\n\n test \"extracts all dependencies paths from the given project\" do\n Mix.Project.push DepsApp\n\n in_fixture \"deps_status\", fn ->\n paths = Mix.Project.deps_paths\n assert map_size(paths) == 6\n assert paths[:ok] =~ \"deps\/ok\"\n assert paths[:uncloned] =~ \"deps\/uncloned\"\n end\n end\n\n test \"fails on invalid dependencies\" do\n assert_wrong_dependency [{:ok}]\n assert_wrong_dependency [{:ok, nil}]\n assert_wrong_dependency [{:ok, nil, []}]\n end\n\n test \"use requirements for dependencies\" do\n with_deps [{:ok, \"~> 0.1\", path: \"deps\/ok\"}], fn ->\n in_fixture \"deps_status\", fn ->\n deps = Mix.Dep.loaded([])\n assert Enum.find deps, &match?(%Mix.Dep{app: :ok, status: {:ok, _}}, &1)\n end\n end\n end\n\n test \"raises when no SCM is specified\" do\n with_deps [{:ok, \"~> 0.1\", not_really: :ok}], fn ->\n in_fixture \"deps_status\", fn ->\n send self(), {:mix_shell_input, :yes?, false}\n msg = \"Could not find an SCM for dependency :ok from Mix.DepTest.ProcessDepsApp\"\n assert_raise Mix.Error, msg, fn -> Mix.Dep.loaded([]) end\n end\n end\n end\n\n test \"does not set the manager before the dependency was loaded\" do\n # It is important to not eagerly set the manager because the dependency\n # needs to be loaded (i.e. available in the filesystem) in order to get\n # the proper manager.\n Mix.Project.push DepsApp\n\n {_, true, _} =\n Mix.Dep.Converger.converge(false, [], nil, fn dep, acc, lock ->\n assert is_nil(dep.manager)\n {dep, acc or true, lock}\n end)\n end\n\n test \"raises on invalid deps req\" do\n with_deps [{:ok, \"+- 0.1.0\", path: \"deps\/ok\"}], fn ->\n in_fixture \"deps_status\", fn ->\n assert_raise Mix.Error, ~r\"Invalid requirement\", fn ->\n Mix.Dep.loaded([])\n end\n end\n end\n end\n\n test \"nested deps come first\" do\n with_deps [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"}], fn ->\n in_fixture \"deps_status\", fn ->\n assert Enum.map(Mix.Dep.loaded([]), &(&1.app)) == [:git_repo, :deps_repo]\n end\n end\n end\n\n test \"nested optional deps are never added\" do\n with_deps [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"}], fn ->\n in_fixture \"deps_status\", fn ->\n File.write! \"custom\/deps_repo\/mix.exs\", \"\"\"\n defmodule DepsRepo do\n use Mix.Project\n\n def project do\n [app: :deps_repo,\n version: \"0.1.0\",\n deps: [{:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\"), optional: true}]]\n end\n end\n \"\"\"\n\n assert Enum.map(Mix.Dep.loaded([]), &(&1.app)) == [:deps_repo]\n end\n end\n end\n\n test \"nested deps with convergence\" do\n deps = [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\")}]\n\n with_deps deps, fn ->\n in_fixture \"deps_status\", fn ->\n assert Enum.map(Mix.Dep.loaded([]), &(&1.app)) == [:git_repo, :deps_repo]\n end\n end\n end\n\n test \"nested deps with convergence and managers\" do\n Process.put(:custom_deps_git_repo_opts, [manager: :make])\n\n deps = [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\", manager: :rebar},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\")}]\n\n with_deps deps, fn ->\n in_fixture \"deps_status\", fn ->\n [dep1, dep2] = Mix.Dep.loaded([])\n assert dep1.manager == nil\n assert dep2.manager == :rebar\n end\n end\n end\n\n test \"nested deps with convergence and optional dependencies\" do\n deps = [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\")}]\n\n with_deps deps, fn ->\n in_fixture \"deps_status\", fn ->\n File.write! \"custom\/deps_repo\/mix.exs\", \"\"\"\n defmodule DepsRepo do\n use Mix.Project\n\n def project do\n [app: :deps_repo,\n version: \"0.1.0\",\n deps: [{:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\"), optional: true}]]\n end\n end\n \"\"\"\n\n assert Enum.map(Mix.Dep.loaded([]), &(&1.app)) == [:git_repo, :deps_repo]\n end\n end\n end\n\n test \"nested deps with optional dependencies and cousin conflict\" do\n with_deps [{:deps_repo1, \"0.1.0\", path: \"custom\/deps_repo1\"},\n {:deps_repo2, \"0.1.0\", path: \"custom\/deps_repo2\"}], fn ->\n in_fixture \"deps_status\", fn ->\n File.mkdir_p!(\"custom\/deps_repo1\")\n File.write! \"custom\/deps_repo1\/mix.exs\", \"\"\"\n defmodule DepsRepo1 do\n use Mix.Project\n\n def project do\n [app: :deps_repo1,\n version: \"0.1.0\",\n deps: [{:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\"), optional: true}]]\n end\n end\n \"\"\"\n\n File.mkdir_p!(\"custom\/deps_repo2\")\n File.write! \"custom\/deps_repo2\/mix.exs\", \"\"\"\n defmodule DepsRepo2 do\n use Mix.Project\n\n def project do\n [app: :deps_repo2,\n version: \"0.1.0\",\n deps: [{:git_repo, \"0.2.0\", path: \"somewhere\"}]]\n end\n end\n \"\"\"\n\n Mix.Tasks.Deps.run([])\n assert_received {:mix_shell, :info, [\"* git_repo\" <> _]}\n assert_received {:mix_shell, :info, [msg]}\n assert msg =~ \"different specs were given for the git_repo\"\n end\n end\n end\n\n ## Remove converger\n\n defmodule IdentityRemoteConverger do\n @behaviour Mix.RemoteConverger\n\n def remote?(%Mix.Dep{app: :deps_repo}), do: false\n def remote?(%Mix.Dep{}), do: true\n def deps(_dep, _lock), do: []\n def post_converge, do: :ok\n\n def converge(deps, lock) do\n Process.put(:remote_converger, deps)\n lock\n end\n\n end\n\n test \"remote converger\" do\n deps = [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\")}]\n\n with_deps deps, fn ->\n Mix.RemoteConverger.register(IdentityRemoteConverger)\n\n in_fixture \"deps_status\", fn ->\n Mix.Tasks.Deps.Get.run([])\n\n message = \"* Getting git_repo (#{fixture_path(\"git_repo\")})\"\n assert_received {:mix_shell, :info, [^message]}\n\n assert Process.get(:remote_converger)\n end\n end\n after\n Mix.RemoteConverger.register(nil)\n end\n\n test \"pass dependencies to remote converger in defined order\" do\n deps = [\n {:ok, \"0.1.0\", path: \"deps\/ok\"},\n {:invalidvsn, \"0.2.0\", path: \"deps\/invalidvsn\"},\n {:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"},\n {:invalidapp, \"0.1.0\", path: \"deps\/invalidapp\"},\n {:noappfile, \"0.1.0\", path: \"deps\/noappfile\"}\n ]\n\n with_deps deps, fn ->\n Mix.RemoteConverger.register(IdentityRemoteConverger)\n\n in_fixture \"deps_status\", fn ->\n Mix.Tasks.Deps.Get.run([])\n\n deps = Process.get(:remote_converger) |> Enum.map(& &1.app)\n assert deps == [:ok, :invalidvsn, :deps_repo, :invalidapp, :noappfile, :git_repo]\n end\n end\n after\n Mix.RemoteConverger.register(nil)\n end\n\n defmodule RaiseRemoteConverger do\n @behaviour Mix.RemoteConverger\n\n def remote?(_app), do: false\n def deps(_dep, _lock), do: :ok\n def post_converge, do: :ok\n\n def converge(_deps, lock) do\n Process.put(:remote_converger, true)\n lock\n end\n end\n\n test \"remote converger is not invoked if deps diverge\" do\n deps = [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\"), only: :test}]\n\n with_deps deps, fn ->\n Mix.RemoteConverger.register(RaiseRemoteConverger)\n\n in_fixture \"deps_status\", fn ->\n assert_raise Mix.Error, fn ->\n Mix.Tasks.Deps.Get.run([])\n end\n\n assert_received {:mix_shell, :error, [\"Dependencies have diverged:\"]}\n refute Process.get(:remote_converger)\n end\n end\n after\n Mix.RemoteConverger.register(nil)\n end\n\n test \"remote converger is not invoked if deps graph has cycles\" do\n deps = [{:app1, \"0.1.0\", path: \"app1\"},\n {:app2, \"0.1.0\", path: \"app2\"}]\n\n with_deps deps, fn ->\n Mix.RemoteConverger.register(RaiseRemoteConverger)\n\n in_fixture \"deps_cycle\", fn ->\n assert_raise Mix.Error, ~r\/cycles in the dependency graph\/, fn ->\n Mix.Tasks.Deps.Get.run([])\n end\n\n refute Process.get(:remote_converger)\n end\n end\n after\n Mix.RemoteConverger.register(nil)\n end\n\n ## Only handling\n\n test \"only extracts deps matching environment\" do\n with_deps [{:foo, github: \"elixir-lang\/foo\"},\n {:bar, github: \"elixir-lang\/bar\", only: :other_env}], fn ->\n in_fixture \"deps_status\", fn ->\n deps = Mix.Dep.loaded([env: :other_env])\n assert length(deps) == 2\n\n deps = Mix.Dep.loaded([])\n assert length(deps) == 2\n\n assert [dep] = Mix.Dep.loaded([env: :prod])\n assert dep.app == :foo\n end\n end\n end\n\n test \"only fetches parent deps matching specified env\" do\n with_deps [{:only, github: \"elixir-lang\/only\", only: [:dev]}], fn ->\n in_fixture \"deps_status\", fn ->\n Mix.Tasks.Deps.Get.run([\"--only\", \"prod\"])\n refute_received {:mix_shell, :info, [\"* Getting\" <> _]}\n\n assert_raise Mix.Error, \"Can't continue due to errors on dependencies\", fn ->\n Mix.Tasks.Deps.Loadpaths.run([])\n end\n\n Mix.ProjectStack.clear_cache()\n Mix.env(:prod)\n Mix.Tasks.Deps.Loadpaths.run([])\n end\n end\n end\n\n test \"nested deps selects only prod dependencies\" do\n Process.put(:custom_deps_git_repo_opts, [only: :test])\n deps = [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"}]\n\n with_deps deps, fn ->\n in_fixture \"deps_status\", fn ->\n loaded = Mix.Dep.loaded([])\n assert [:deps_repo] = Enum.map(loaded, &(&1.app))\n\n loaded = Mix.Dep.loaded([env: :test])\n assert [:deps_repo] = Enum.map(loaded, &(&1.app))\n end\n end\n end\n\n test \"nested deps on only matching\" do\n # deps_repo wants git_repo for test, git_repo is restricted to only test\n # We assert the dependencies match as expected, happens in umbrella apps\n Process.put(:custom_deps_git_repo_opts, [only: :test])\n\n # We need to pass env: :test so the child dependency is loaded\n # in the first place (otherwise only :prod deps are loaded)\n deps = [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\", env: :test},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\"), only: :test}]\n\n with_deps deps, fn ->\n in_fixture \"deps_status\", fn ->\n loaded = Mix.Dep.loaded([])\n assert [:git_repo, :deps_repo] = Enum.map(loaded, &(&1.app))\n assert [unavailable: _, noappfile: _] = Enum.map(loaded, &(&1.status))\n\n loaded = Mix.Dep.loaded([env: :dev])\n assert [:deps_repo] = Enum.map(loaded, &(&1.app))\n assert [noappfile: _] = Enum.map(loaded, &(&1.status))\n\n loaded = Mix.Dep.loaded([env: :test])\n assert [:git_repo, :deps_repo] = Enum.map(loaded, &(&1.app))\n assert [unavailable: _, noappfile: _] = Enum.map(loaded, &(&1.status))\n end\n end\n end\n\n test \"nested deps on only conflict\" do\n # deps_repo wants all git_repo, git_repo is restricted to only test\n deps = [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\"), only: :test}]\n\n with_deps deps, fn ->\n in_fixture \"deps_status\", fn ->\n loaded = Mix.Dep.loaded([])\n assert [:git_repo, :deps_repo] = Enum.map(loaded, &(&1.app))\n assert [divergedonly: _, noappfile: _] = Enum.map(loaded, &(&1.status))\n\n loaded = Mix.Dep.loaded([env: :dev])\n assert [:git_repo, :deps_repo] = Enum.map(loaded, &(&1.app))\n assert [divergedonly: _, noappfile: _] = Enum.map(loaded, &(&1.status))\n\n loaded = Mix.Dep.loaded([env: :test])\n assert [:git_repo, :deps_repo] = Enum.map(loaded, &(&1.app))\n assert [divergedonly: _, noappfile: _] = Enum.map(loaded, &(&1.status))\n\n Mix.Tasks.Deps.run([])\n assert_received {:mix_shell, :info, [\"* git_repo\" <> _]}\n assert_received {:mix_shell, :info, [msg]}\n assert msg =~ \"Remove the :only restriction from your dep\"\n end\n end\n end\n\n test \"nested deps on only conflict does not happen with optional deps\" do\n Process.put(:custom_deps_git_repo_opts, [optional: true])\n\n # deps_repo wants all git_repo, git_repo is restricted to only test\n deps = [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\"), only: :test}]\n\n with_deps deps, fn ->\n in_fixture \"deps_status\", fn ->\n loaded = Mix.Dep.loaded([])\n assert [:git_repo, :deps_repo] = Enum.map(loaded, &(&1.app))\n assert [unavailable: _, noappfile: _] = Enum.map(loaded, &(&1.status))\n\n loaded = Mix.Dep.loaded([env: :dev])\n assert [:deps_repo] = Enum.map(loaded, &(&1.app))\n assert [noappfile: _] = Enum.map(loaded, &(&1.status))\n\n loaded = Mix.Dep.loaded([env: :test])\n assert [:git_repo, :deps_repo] = Enum.map(loaded, &(&1.app))\n assert [unavailable: _, noappfile: _] = Enum.map(loaded, &(&1.status))\n end\n end\n end\n\n test \"nested deps with valid only subset\" do\n # deps_repo wants git_repo for prod, git_repo is restricted to only prod and test\n deps = [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\", only: :prod},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\"), only: [:prod, :test]}]\n\n with_deps deps, fn ->\n in_fixture \"deps_status\", fn ->\n loaded = Mix.Dep.loaded([])\n assert [:git_repo, :deps_repo] = Enum.map(loaded, &(&1.app))\n assert [unavailable: _, noappfile: _] = Enum.map(loaded, &(&1.status))\n\n loaded = Mix.Dep.loaded([env: :dev])\n assert [] = Enum.map(loaded, &(&1.app))\n\n loaded = Mix.Dep.loaded([env: :test])\n assert [:git_repo] = Enum.map(loaded, &(&1.app))\n assert [unavailable: _] = Enum.map(loaded, &(&1.status))\n\n loaded = Mix.Dep.loaded([env: :prod])\n assert [:git_repo, :deps_repo] = Enum.map(loaded, &(&1.app))\n assert [unavailable: _, noappfile: _] = Enum.map(loaded, &(&1.status))\n end\n end\n end\n\n test \"nested deps with invalid only subset\" do\n # deps_repo wants git_repo for dev, git_repo is restricted to only test\n deps = [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\", only: :dev},\n {:git_repo, \"0.2.0\", git: MixTest.Case.fixture_path(\"git_repo\"), only: [:test]}]\n\n with_deps deps, fn ->\n in_fixture \"deps_status\", fn ->\n loaded = Mix.Dep.loaded([])\n assert [:git_repo, :deps_repo] = Enum.map(loaded, &(&1.app))\n assert [divergedonly: _, noappfile: _] = Enum.map(loaded, &(&1.status))\n\n loaded = Mix.Dep.loaded([env: :dev])\n assert [:git_repo, :deps_repo] = Enum.map(loaded, &(&1.app))\n assert [divergedonly: _, noappfile: _] = Enum.map(loaded, &(&1.status))\n\n loaded = Mix.Dep.loaded([env: :test])\n assert [:git_repo] = Enum.map(loaded, &(&1.app))\n assert [unavailable: _] = Enum.map(loaded, &(&1.status))\n\n Mix.Tasks.Deps.run([])\n assert_received {:mix_shell, :info, [\"* git_repo\" <> _]}\n assert_received {:mix_shell, :info, [msg]}\n assert msg =~ \"Ensure you specify at least the same environments in :only in your dep\"\n end\n end\n end\n\n test \"nested deps with valid only in both parent and child\" do\n Process.put(:custom_deps_git_repo_opts, [only: :test])\n\n # deps_repo has environment set to test so it loads the deps_git_repo set to test too\n deps = [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\", env: :test, only: [:dev, :test]},\n {:git_repo, \"0.1.0\", git: MixTest.Case.fixture_path(\"git_repo\"), only: :test}]\n\n with_deps deps, fn ->\n in_fixture \"deps_status\", fn ->\n loaded = Mix.Dep.loaded([])\n assert [:git_repo, :deps_repo] = Enum.map(loaded, &(&1.app))\n assert [unavailable: _, noappfile: _] = Enum.map(loaded, &(&1.status))\n\n loaded = Mix.Dep.loaded([env: :dev])\n assert [:deps_repo] = Enum.map(loaded, &(&1.app))\n assert [noappfile: _] = Enum.map(loaded, &(&1.status))\n\n loaded = Mix.Dep.loaded([env: :test])\n assert [:git_repo, :deps_repo] = Enum.map(loaded, &(&1.app))\n assert [unavailable: _, noappfile: _] = Enum.map(loaded, &(&1.status))\n\n loaded = Mix.Dep.loaded([env: :prod])\n assert [] = Enum.map(loaded, &(&1.app))\n end\n end\n end\n\n test \"nested deps converge and diverge when only is not in_upper\" do\n loaded_only = fn deps ->\n with_deps deps, fn ->\n in_fixture \"deps_status\", fn ->\n File.mkdir_p! \"custom\/other_repo\"\n File.write! \"custom\/other_repo\/mix.exs\", \"\"\"\n defmodule OtherRepo do\n use Mix.Project\n\n def project do\n [app: :deps_repo,\n version: \"0.1.0\",\n deps: [{:git_repo, \"0.1.0\", git: MixTest.Case.fixture_path(\"git_repo\")}]]\n end\n end\n \"\"\"\n\n Mix.ProjectStack.clear_cache\n loaded = Mix.Dep.loaded([])\n assert [:git_repo, _, _] = Enum.map(loaded, &(&1.app))\n hd(loaded).opts[:only]\n end\n end\n end\n\n deps = [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\", only: :prod},\n {:other_repo, \"0.1.0\", path: \"custom\/other_repo\", only: :test}]\n assert loaded_only.(deps) == [:test, :prod]\n\n deps = [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"},\n {:other_repo, \"0.1.0\", path: \"custom\/other_repo\", only: :test}]\n refute loaded_only.(deps)\n\n deps = [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\", only: :prod},\n {:other_repo, \"0.1.0\", path: \"custom\/other_repo\"}]\n refute loaded_only.(deps)\n\n deps = [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\"},\n {:other_repo, \"0.1.0\", path: \"custom\/other_repo\"}]\n refute loaded_only.(deps)\n\n Process.put(:custom_deps_git_repo_opts, [optional: true])\n deps = [{:deps_repo, \"0.1.0\", path: \"custom\/deps_repo\", only: :prod},\n {:other_repo, \"0.1.0\", path: \"custom\/other_repo\", only: :test}]\n assert loaded_only.(deps) == :test\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"306263b7678e777d309fbfe585545fbddefc0577","subject":"Fix #295 - Missing function clause when rejecting low priority checks","message":"Fix #295 - Missing function clause when rejecting low priority checks\n","repos":"rrrene\/credo,rrrene\/credo","old_file":"lib\/credo\/check\/runner.ex","new_file":"lib\/credo\/check\/runner.ex","new_contents":"defmodule Credo.Check.Runner do\n alias Credo.CLI.Output.UI\n alias Credo.Config\n alias Credo.SourceFile\n alias Credo.Service.SourceFileIssues\n\n @doc false\n def run(source_files, config) when is_list(source_files) do\n {_time_run_on_all, source_files_after_run_on_all} =\n :timer.tc fn ->\n run_checks_that_run_on_all(source_files, config)\n end\n\n {_time_run, source_files} =\n :timer.tc fn ->\n source_files_after_run_on_all\n |> Enum.map(&Task.async(fn -> run(&1, config) end))\n |> Enum.map(&Task.await(&1, :infinity))\n end\n\n {source_files, config}\n end\n def run(%SourceFile{} = source_file, config) do\n checks =\n config\n |> Config.checks\n |> Enum.reject(&run_on_all_check?\/1)\n\n issues = run_checks(source_file, checks, config)\n\n %SourceFile{source_file | issues: source_file.issues ++ issues}\n end\n\n @doc \"\"\"\n Prepares the Config struct based on a given list of `source_files`.\n \"\"\"\n def prepare_config(source_files, config) do\n config\n |> set_lint_attributes(source_files)\n |> exclude_low_priority_checks(config.min_priority - 9)\n |> exclude_checks_based_on_elixir_version\n end\n\n defp set_lint_attributes(config, source_files) do\n lint_attribute_map =\n source_files\n |> run_linter_attribute_reader(config)\n |> Enum.reduce(%{}, fn(source_file, memo) ->\n # TODO: we should modify the config \"directly\" instead of going\n # through the SourceFile\n Map.put(memo, source_file.filename, source_file.lint_attributes)\n end)\n\n %Config{config | lint_attribute_map: lint_attribute_map}\n end\n\n defp run_linter_attribute_reader(source_files, config) do\n checks = [{Credo.Check.FindLintAttributes}]\n\n Enum.reduce(checks, source_files, fn(check_tuple, source_files) ->\n run_check(check_tuple, source_files, config)\n end)\n end\n\n defp exclude_low_priority_checks(config, below_priority) do\n checks =\n Enum.reject(config.checks, fn\n ({check}) -> check.base_priority < below_priority\n ({check, false}) -> true\n ({check, opts}) ->\n (opts[:priority] || check.base_priority) < below_priority\n end)\n\n %Config{config | checks: checks}\n end\n\n defp exclude_checks_based_on_elixir_version(config) do\n version = System.version()\n skipped_checks = Enum.reject(config.checks, &matches_requirement?(&1, version))\n checks = Enum.filter(config.checks, &matches_requirement?(&1, version))\n\n %Config{config | checks: checks, skipped_checks: skipped_checks}\n end\n\n defp matches_requirement?({check, _}, version) do\n matches_requirement?({check}, version)\n end\n defp matches_requirement?({check}, version) do\n Version.match?(version, check.elixir_version)\n end\n\n defp run_checks_that_run_on_all(source_files, config) do\n checks =\n config\n |> Config.checks\n |> Enum.filter(&run_on_all_check?\/1)\n\n checks\n |> Enum.map(&Task.async(fn ->\n run_check(&1, source_files, config)\n end))\n |> Enum.each(&Task.await(&1, :infinity))\n\n SourceFileIssues.update_in_source_files(source_files)\n end\n\n defp run_checks(%SourceFile{} = source_file, checks, config) when is_list(checks) do\n Enum.flat_map(checks, &run_check(&1, source_file, config))\n end\n\n defp run_check({_check, false}, source_files, _config) when is_list(source_files) do\n source_files\n end\n defp run_check({_check, false}, _source_file, _config) do\n []\n end\n defp run_check({check}, source_file, config) do\n run_check({check, []}, source_file, config)\n end\n defp run_check({check, params}, source_file, config) do\n try do\n check.run(source_file, params)\n rescue\n error ->\n warn_about_failed_run(check, source_file)\n if config.crash_on_error do\n reraise error, System.stacktrace()\n else\n []\n end\n end\n end\n\n defp warn_about_failed_run(check, %SourceFile{} = source_file) do\n UI.warn(\"Error while running #{check} on #{source_file.filename}\")\n end\n defp warn_about_failed_run(check, _) do\n UI.warn(\"Error while running #{check}\")\n end\n\n defp run_on_all_check?({check}), do: check.run_on_all?\n defp run_on_all_check?({check, _params}), do: check.run_on_all?\nend\n","old_contents":"defmodule Credo.Check.Runner do\n alias Credo.CLI.Output.UI\n alias Credo.Config\n alias Credo.SourceFile\n alias Credo.Service.SourceFileIssues\n\n @doc false\n def run(source_files, config) when is_list(source_files) do\n {_time_run_on_all, source_files_after_run_on_all} =\n :timer.tc fn ->\n run_checks_that_run_on_all(source_files, config)\n end\n\n {_time_run, source_files} =\n :timer.tc fn ->\n source_files_after_run_on_all\n |> Enum.map(&Task.async(fn -> run(&1, config) end))\n |> Enum.map(&Task.await(&1, :infinity))\n end\n\n {source_files, config}\n end\n def run(%SourceFile{} = source_file, config) do\n checks =\n config\n |> Config.checks\n |> Enum.reject(&run_on_all_check?\/1)\n\n issues = run_checks(source_file, checks, config)\n\n %SourceFile{source_file | issues: source_file.issues ++ issues}\n end\n\n @doc \"\"\"\n Prepares the Config struct based on a given list of `source_files`.\n \"\"\"\n def prepare_config(source_files, config) do\n config\n |> set_lint_attributes(source_files)\n |> exclude_low_priority_checks(config.min_priority - 9)\n |> exclude_checks_based_on_elixir_version\n end\n\n defp set_lint_attributes(config, source_files) do\n lint_attribute_map =\n source_files\n |> run_linter_attribute_reader(config)\n |> Enum.reduce(%{}, fn(source_file, memo) ->\n # TODO: we should modify the config \"directly\" instead of going\n # through the SourceFile\n Map.put(memo, source_file.filename, source_file.lint_attributes)\n end)\n\n %Config{config | lint_attribute_map: lint_attribute_map}\n end\n\n defp run_linter_attribute_reader(source_files, config) do\n checks = [{Credo.Check.FindLintAttributes}]\n\n Enum.reduce(checks, source_files, fn(check_tuple, source_files) ->\n run_check(check_tuple, source_files, config)\n end)\n end\n\n defp exclude_low_priority_checks(config, below_priority) do\n checks =\n Enum.reject(config.checks, fn\n ({check}) -> check.base_priority < below_priority\n ({check, opts}) ->\n (opts[:priority] || check.base_priority) < below_priority\n end)\n\n %Config{config | checks: checks}\n end\n\n defp exclude_checks_based_on_elixir_version(config) do\n version = System.version()\n skipped_checks = Enum.reject(config.checks, &matches_requirement?(&1, version))\n checks = Enum.filter(config.checks, &matches_requirement?(&1, version))\n\n %Config{config | checks: checks, skipped_checks: skipped_checks}\n end\n\n defp matches_requirement?({check, _}, version) do\n matches_requirement?({check}, version)\n end\n defp matches_requirement?({check}, version) do\n Version.match?(version, check.elixir_version)\n end\n\n defp run_checks_that_run_on_all(source_files, config) do\n checks =\n config\n |> Config.checks\n |> Enum.filter(&run_on_all_check?\/1)\n\n checks\n |> Enum.map(&Task.async(fn ->\n run_check(&1, source_files, config)\n end))\n |> Enum.each(&Task.await(&1, :infinity))\n\n SourceFileIssues.update_in_source_files(source_files)\n end\n\n defp run_checks(%SourceFile{} = source_file, checks, config) when is_list(checks) do\n Enum.flat_map(checks, &run_check(&1, source_file, config))\n end\n\n defp run_check({_check, false}, source_files, _config) when is_list(source_files) do\n source_files\n end\n defp run_check({_check, false}, _source_file, _config) do\n []\n end\n defp run_check({check}, source_file, config) do\n run_check({check, []}, source_file, config)\n end\n defp run_check({check, params}, source_file, config) do\n try do\n check.run(source_file, params)\n rescue\n error ->\n warn_about_failed_run(check, source_file)\n if config.crash_on_error do\n reraise error, System.stacktrace()\n else\n []\n end\n end\n end\n\n defp warn_about_failed_run(check, %SourceFile{} = source_file) do\n UI.warn(\"Error while running #{check} on #{source_file.filename}\")\n end\n defp warn_about_failed_run(check, _) do\n UI.warn(\"Error while running #{check}\")\n end\n\n defp run_on_all_check?({check}), do: check.run_on_all?\n defp run_on_all_check?({check, _params}), do: check.run_on_all?\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"967fba4f79024e8b59432fa6f2cd973e03550e0a","subject":"Fix wrong arity in Integer docs (#8181)","message":"Fix wrong arity in Integer docs (#8181)\n\nCloses #8180","repos":"kimshrier\/elixir,michalmuskala\/elixir,lexmag\/elixir,kelvinst\/elixir,lexmag\/elixir,kimshrier\/elixir,elixir-lang\/elixir,pedrosnk\/elixir,kelvinst\/elixir,ggcampinho\/elixir,joshprice\/elixir,pedrosnk\/elixir,ggcampinho\/elixir","old_file":"lib\/elixir\/lib\/integer.ex","new_file":"lib\/elixir\/lib\/integer.ex","new_contents":"defmodule Integer do\n @moduledoc \"\"\"\n Functions for working with integers.\n\n Some functions that work on integers are found in `Kernel`:\n\n * `abs\/1`\n * `div\/2`\n * `max\/2`\n * `min\/2`\n * `rem\/2`\n\n \"\"\"\n\n import Bitwise\n\n @doc \"\"\"\n Determines if `integer` is odd.\n\n Returns `true` if the given `integer` is an odd number,\n otherwise it returns `false`.\n\n Allowed in guard clauses.\n\n ## Examples\n\n iex> Integer.is_odd(5)\n true\n\n iex> Integer.is_odd(6)\n false\n\n iex> Integer.is_odd(-5)\n true\n\n iex> Integer.is_odd(0)\n false\n\n \"\"\"\n defguard is_odd(integer) when is_integer(integer) and (integer &&& 1) == 1\n\n @doc \"\"\"\n Determines if an `integer` is even.\n\n Returns `true` if the given `integer` is an even number,\n otherwise it returns `false`.\n\n Allowed in guard clauses.\n\n ## Examples\n\n iex> Integer.is_even(10)\n true\n\n iex> Integer.is_even(5)\n false\n\n iex> Integer.is_even(-10)\n true\n\n iex> Integer.is_even(0)\n true\n\n \"\"\"\n defguard is_even(integer) when is_integer(integer) and (integer &&& 1) == 0\n\n @doc \"\"\"\n Computes the modulo remainder of an integer division.\n\n `Integer.mod\/2` uses floored division, which means that\n the result will always have the sign of the `divisor`.\n\n Raises an `ArithmeticError` exception if one of the arguments is not an\n integer, or when the `divisor` is `0`.\n\n ## Examples\n\n iex> Integer.mod(5, 2)\n 1\n iex> Integer.mod(6, -4)\n -2\n\n \"\"\"\n @doc since: \"1.4.0\"\n @spec mod(integer, neg_integer | pos_integer) :: integer\n def mod(dividend, divisor) do\n remainder = rem(dividend, divisor)\n\n if remainder * divisor < 0 do\n remainder + divisor\n else\n remainder\n end\n end\n\n @doc \"\"\"\n Performs a floored integer division.\n\n Raises an `ArithmeticError` exception if one of the arguments is not an\n integer, or when the `divisor` is `0`.\n\n `Integer.floor_div\/2` performs *floored* integer division. This means that\n the result is always rounded towards negative infinity.\n\n If you want to perform truncated integer division (rounding towards zero),\n use `Kernel.div\/2` instead.\n\n ## Examples\n\n iex> Integer.floor_div(5, 2)\n 2\n iex> Integer.floor_div(6, -4)\n -2\n iex> Integer.floor_div(-99, 2)\n -50\n\n \"\"\"\n @doc since: \"1.4.0\"\n @spec floor_div(integer, neg_integer | pos_integer) :: integer\n def floor_div(dividend, divisor) do\n if dividend * divisor < 0 and rem(dividend, divisor) != 0 do\n div(dividend, divisor) - 1\n else\n div(dividend, divisor)\n end\n end\n\n @doc \"\"\"\n Returns the ordered digits for the given `integer`.\n\n An optional `base` value may be provided representing the radix for the returned\n digits. This one must be an integer >= 2.\n\n ## Examples\n\n iex> Integer.digits(123)\n [1, 2, 3]\n\n iex> Integer.digits(170, 2)\n [1, 0, 1, 0, 1, 0, 1, 0]\n\n iex> Integer.digits(-170, 2)\n [-1, 0, -1, 0, -1, 0, -1, 0]\n\n \"\"\"\n @spec digits(integer, pos_integer) :: [integer, ...]\n def digits(integer, base \\\\ 10)\n when is_integer(integer) and is_integer(base) and base >= 2 do\n do_digits(integer, base, [])\n end\n\n defp do_digits(integer, base, acc) when abs(integer) < base, do: [integer | acc]\n\n defp do_digits(integer, base, acc),\n do: do_digits(div(integer, base), base, [rem(integer, base) | acc])\n\n @doc \"\"\"\n Returns the integer represented by the ordered `digits`.\n\n An optional `base` value may be provided representing the radix for the `digits`.\n Base has to be an integer greater or equal than `2`.\n\n ## Examples\n\n iex> Integer.undigits([1, 2, 3])\n 123\n\n iex> Integer.undigits([1, 4], 16)\n 20\n\n iex> Integer.undigits([])\n 0\n\n \"\"\"\n @spec undigits([integer], pos_integer) :: integer\n def undigits(digits, base \\\\ 10) when is_list(digits) and is_integer(base) and base >= 2 do\n do_undigits(digits, base, 0)\n end\n\n defp do_undigits([], _base, acc), do: acc\n\n defp do_undigits([digit | _], base, _) when is_integer(digit) and digit >= base,\n do: raise(ArgumentError, \"invalid digit #{digit} in base #{base}\")\n\n defp do_undigits([digit | tail], base, acc) when is_integer(digit),\n do: do_undigits(tail, base, acc * base + digit)\n\n @doc \"\"\"\n Parses a text representation of an integer.\n\n An optional `base` to the corresponding integer can be provided.\n If `base` is not given, 10 will be used.\n\n If successful, returns a tuple in the form of `{integer, remainder_of_binary}`.\n Otherwise `:error`.\n\n Raises an error if `base` is less than 2 or more than 36.\n\n If you want to convert a string-formatted integer directly to an integer,\n `String.to_integer\/1` or `String.to_integer\/2` can be used instead.\n\n ## Examples\n\n iex> Integer.parse(\"34\")\n {34, \"\"}\n\n iex> Integer.parse(\"34.5\")\n {34, \".5\"}\n\n iex> Integer.parse(\"three\")\n :error\n\n iex> Integer.parse(\"34\", 10)\n {34, \"\"}\n\n iex> Integer.parse(\"f4\", 16)\n {244, \"\"}\n\n iex> Integer.parse(\"Awww++\", 36)\n {509216, \"++\"}\n\n iex> Integer.parse(\"fab\", 10)\n :error\n\n iex> Integer.parse(\"a2\", 38)\n ** (ArgumentError) invalid base 38\n\n \"\"\"\n @spec parse(binary, 2..36) :: {integer, binary} | :error\n def parse(binary, base \\\\ 10)\n\n def parse(_binary, base) when base not in 2..36 do\n raise ArgumentError, \"invalid base #{inspect(base)}\"\n end\n\n def parse(binary, base) do\n case count_digits(binary, base) do\n 0 ->\n :error\n\n count ->\n {digits, rem} = :erlang.split_binary(binary, count)\n {:erlang.binary_to_integer(digits, base), rem}\n end\n end\n\n defp count_digits(<>, base) when sign in '+-' do\n case count_digits_nosign(rest, base, 1) do\n 1 -> 0\n count -> count\n end\n end\n\n defp count_digits(<>, base) do\n count_digits_nosign(rest, base, 0)\n end\n\n digits = [{?0..?9, -?0}, {?A..?Z, 10 - ?A}, {?a..?z, 10 - ?a}]\n\n for {chars, diff} <- digits,\n char <- chars do\n digit = char + diff\n\n defp count_digits_nosign(<>, base, count)\n when base > unquote(digit) do\n count_digits_nosign(rest, base, count + 1)\n end\n end\n\n defp count_digits_nosign(<<_::binary>>, _, count), do: count\n\n @doc \"\"\"\n Returns a binary which corresponds to the text representation\n of `integer`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Integer.to_string(123)\n \"123\"\n\n iex> Integer.to_string(+456)\n \"456\"\n\n iex> Integer.to_string(-789)\n \"-789\"\n\n iex> Integer.to_string(0123)\n \"123\"\n\n \"\"\"\n @spec to_string(integer) :: String.t()\n def to_string(integer) do\n :erlang.integer_to_binary(integer)\n end\n\n @doc \"\"\"\n Returns a binary which corresponds to the text representation\n of `integer` in the given `base`.\n\n `base` can be an integer between 2 and 36.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Integer.to_string(100, 16)\n \"64\"\n\n iex> Integer.to_string(-100, 16)\n \"-64\"\n\n iex> Integer.to_string(882_681_651, 36)\n \"ELIXIR\"\n\n \"\"\"\n @spec to_string(integer, 2..36) :: String.t()\n def to_string(integer, base) do\n :erlang.integer_to_binary(integer, base)\n end\n\n @doc \"\"\"\n Returns a charlist which corresponds to the text representation of the given `integer`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Integer.to_charlist(123)\n '123'\n\n iex> Integer.to_charlist(+456)\n '456'\n\n iex> Integer.to_charlist(-789)\n '-789'\n\n iex> Integer.to_charlist(0123)\n '123'\n\n \"\"\"\n @spec to_charlist(integer) :: charlist\n def to_charlist(integer) do\n :erlang.integer_to_list(integer)\n end\n\n @doc \"\"\"\n Returns a charlist which corresponds to the text representation of `integer` in the given `base`.\n\n `base` can be an integer between 2 and 36.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Integer.to_charlist(100, 16)\n '64'\n\n iex> Integer.to_charlist(-100, 16)\n '-64'\n\n iex> Integer.to_charlist(882_681_651, 36)\n 'ELIXIR'\n\n \"\"\"\n @spec to_charlist(integer, 2..36) :: charlist\n def to_charlist(integer, base) do\n :erlang.integer_to_list(integer, base)\n end\n\n @doc \"\"\"\n Returns the greatest common divisor of the two given integers.\n\n The greatest common divisor (GCD) of `integer1` and `integer2` is the largest positive\n integer that divides both `integer1` and `integer2` without leaving a remainder.\n\n By convention, `gcd(0, 0)` returns `0`.\n\n ## Examples\n\n iex> Integer.gcd(2, 3)\n 1\n\n iex> Integer.gcd(8, 12)\n 4\n\n iex> Integer.gcd(8, -12)\n 4\n\n iex> Integer.gcd(10, 0)\n 10\n\n iex> Integer.gcd(7, 7)\n 7\n\n iex> Integer.gcd(0, 0)\n 0\n\n \"\"\"\n @doc since: \"1.5.0\"\n @spec gcd(0, 0) :: 0\n @spec gcd(integer, integer) :: pos_integer\n def gcd(integer1, integer2) when is_integer(integer1) and is_integer(integer2) do\n gcd_positive(abs(integer1), abs(integer2))\n end\n\n defp gcd_positive(0, integer2), do: integer2\n defp gcd_positive(integer1, 0), do: integer1\n defp gcd_positive(integer1, integer2), do: gcd_positive(integer2, rem(integer1, integer2))\n\n # TODO: Remove by 2.0\n @doc false\n @deprecated \"Use Integer.to_charlist\/1 instead\"\n def to_char_list(integer), do: Integer.to_charlist(integer)\n\n # TODO: Remove by 2.0\n @doc false\n @deprecated \"Use Integer.to_charlist\/2 instead\"\n def to_char_list(integer, base), do: Integer.to_charlist(integer, base)\nend\n","old_contents":"defmodule Integer do\n @moduledoc \"\"\"\n Functions for working with integers.\n\n Some functions that work on integers are found in `Kernel`:\n\n * `abs\/2`\n * `div\/2`\n * `max\/2`\n * `min\/2`\n * `rem\/2`\n\n \"\"\"\n\n import Bitwise\n\n @doc \"\"\"\n Determines if `integer` is odd.\n\n Returns `true` if the given `integer` is an odd number,\n otherwise it returns `false`.\n\n Allowed in guard clauses.\n\n ## Examples\n\n iex> Integer.is_odd(5)\n true\n\n iex> Integer.is_odd(6)\n false\n\n iex> Integer.is_odd(-5)\n true\n\n iex> Integer.is_odd(0)\n false\n\n \"\"\"\n defguard is_odd(integer) when is_integer(integer) and (integer &&& 1) == 1\n\n @doc \"\"\"\n Determines if an `integer` is even.\n\n Returns `true` if the given `integer` is an even number,\n otherwise it returns `false`.\n\n Allowed in guard clauses.\n\n ## Examples\n\n iex> Integer.is_even(10)\n true\n\n iex> Integer.is_even(5)\n false\n\n iex> Integer.is_even(-10)\n true\n\n iex> Integer.is_even(0)\n true\n\n \"\"\"\n defguard is_even(integer) when is_integer(integer) and (integer &&& 1) == 0\n\n @doc \"\"\"\n Computes the modulo remainder of an integer division.\n\n `Integer.mod\/2` uses floored division, which means that\n the result will always have the sign of the `divisor`.\n\n Raises an `ArithmeticError` exception if one of the arguments is not an\n integer, or when the `divisor` is `0`.\n\n ## Examples\n\n iex> Integer.mod(5, 2)\n 1\n iex> Integer.mod(6, -4)\n -2\n\n \"\"\"\n @doc since: \"1.4.0\"\n @spec mod(integer, neg_integer | pos_integer) :: integer\n def mod(dividend, divisor) do\n remainder = rem(dividend, divisor)\n\n if remainder * divisor < 0 do\n remainder + divisor\n else\n remainder\n end\n end\n\n @doc \"\"\"\n Performs a floored integer division.\n\n Raises an `ArithmeticError` exception if one of the arguments is not an\n integer, or when the `divisor` is `0`.\n\n `Integer.floor_div\/2` performs *floored* integer division. This means that\n the result is always rounded towards negative infinity.\n\n If you want to perform truncated integer division (rounding towards zero),\n use `Kernel.div\/2` instead.\n\n ## Examples\n\n iex> Integer.floor_div(5, 2)\n 2\n iex> Integer.floor_div(6, -4)\n -2\n iex> Integer.floor_div(-99, 2)\n -50\n\n \"\"\"\n @doc since: \"1.4.0\"\n @spec floor_div(integer, neg_integer | pos_integer) :: integer\n def floor_div(dividend, divisor) do\n if dividend * divisor < 0 and rem(dividend, divisor) != 0 do\n div(dividend, divisor) - 1\n else\n div(dividend, divisor)\n end\n end\n\n @doc \"\"\"\n Returns the ordered digits for the given `integer`.\n\n An optional `base` value may be provided representing the radix for the returned\n digits. This one must be an integer >= 2.\n\n ## Examples\n\n iex> Integer.digits(123)\n [1, 2, 3]\n\n iex> Integer.digits(170, 2)\n [1, 0, 1, 0, 1, 0, 1, 0]\n\n iex> Integer.digits(-170, 2)\n [-1, 0, -1, 0, -1, 0, -1, 0]\n\n \"\"\"\n @spec digits(integer, pos_integer) :: [integer, ...]\n def digits(integer, base \\\\ 10)\n when is_integer(integer) and is_integer(base) and base >= 2 do\n do_digits(integer, base, [])\n end\n\n defp do_digits(integer, base, acc) when abs(integer) < base, do: [integer | acc]\n\n defp do_digits(integer, base, acc),\n do: do_digits(div(integer, base), base, [rem(integer, base) | acc])\n\n @doc \"\"\"\n Returns the integer represented by the ordered `digits`.\n\n An optional `base` value may be provided representing the radix for the `digits`.\n Base has to be an integer greater or equal than `2`.\n\n ## Examples\n\n iex> Integer.undigits([1, 2, 3])\n 123\n\n iex> Integer.undigits([1, 4], 16)\n 20\n\n iex> Integer.undigits([])\n 0\n\n \"\"\"\n @spec undigits([integer], pos_integer) :: integer\n def undigits(digits, base \\\\ 10) when is_list(digits) and is_integer(base) and base >= 2 do\n do_undigits(digits, base, 0)\n end\n\n defp do_undigits([], _base, acc), do: acc\n\n defp do_undigits([digit | _], base, _) when is_integer(digit) and digit >= base,\n do: raise(ArgumentError, \"invalid digit #{digit} in base #{base}\")\n\n defp do_undigits([digit | tail], base, acc) when is_integer(digit),\n do: do_undigits(tail, base, acc * base + digit)\n\n @doc \"\"\"\n Parses a text representation of an integer.\n\n An optional `base` to the corresponding integer can be provided.\n If `base` is not given, 10 will be used.\n\n If successful, returns a tuple in the form of `{integer, remainder_of_binary}`.\n Otherwise `:error`.\n\n Raises an error if `base` is less than 2 or more than 36.\n\n If you want to convert a string-formatted integer directly to an integer,\n `String.to_integer\/1` or `String.to_integer\/2` can be used instead.\n\n ## Examples\n\n iex> Integer.parse(\"34\")\n {34, \"\"}\n\n iex> Integer.parse(\"34.5\")\n {34, \".5\"}\n\n iex> Integer.parse(\"three\")\n :error\n\n iex> Integer.parse(\"34\", 10)\n {34, \"\"}\n\n iex> Integer.parse(\"f4\", 16)\n {244, \"\"}\n\n iex> Integer.parse(\"Awww++\", 36)\n {509216, \"++\"}\n\n iex> Integer.parse(\"fab\", 10)\n :error\n\n iex> Integer.parse(\"a2\", 38)\n ** (ArgumentError) invalid base 38\n\n \"\"\"\n @spec parse(binary, 2..36) :: {integer, binary} | :error\n def parse(binary, base \\\\ 10)\n\n def parse(_binary, base) when base not in 2..36 do\n raise ArgumentError, \"invalid base #{inspect(base)}\"\n end\n\n def parse(binary, base) do\n case count_digits(binary, base) do\n 0 ->\n :error\n\n count ->\n {digits, rem} = :erlang.split_binary(binary, count)\n {:erlang.binary_to_integer(digits, base), rem}\n end\n end\n\n defp count_digits(<>, base) when sign in '+-' do\n case count_digits_nosign(rest, base, 1) do\n 1 -> 0\n count -> count\n end\n end\n\n defp count_digits(<>, base) do\n count_digits_nosign(rest, base, 0)\n end\n\n digits = [{?0..?9, -?0}, {?A..?Z, 10 - ?A}, {?a..?z, 10 - ?a}]\n\n for {chars, diff} <- digits,\n char <- chars do\n digit = char + diff\n\n defp count_digits_nosign(<>, base, count)\n when base > unquote(digit) do\n count_digits_nosign(rest, base, count + 1)\n end\n end\n\n defp count_digits_nosign(<<_::binary>>, _, count), do: count\n\n @doc \"\"\"\n Returns a binary which corresponds to the text representation\n of `integer`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Integer.to_string(123)\n \"123\"\n\n iex> Integer.to_string(+456)\n \"456\"\n\n iex> Integer.to_string(-789)\n \"-789\"\n\n iex> Integer.to_string(0123)\n \"123\"\n\n \"\"\"\n @spec to_string(integer) :: String.t()\n def to_string(integer) do\n :erlang.integer_to_binary(integer)\n end\n\n @doc \"\"\"\n Returns a binary which corresponds to the text representation\n of `integer` in the given `base`.\n\n `base` can be an integer between 2 and 36.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Integer.to_string(100, 16)\n \"64\"\n\n iex> Integer.to_string(-100, 16)\n \"-64\"\n\n iex> Integer.to_string(882_681_651, 36)\n \"ELIXIR\"\n\n \"\"\"\n @spec to_string(integer, 2..36) :: String.t()\n def to_string(integer, base) do\n :erlang.integer_to_binary(integer, base)\n end\n\n @doc \"\"\"\n Returns a charlist which corresponds to the text representation of the given `integer`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Integer.to_charlist(123)\n '123'\n\n iex> Integer.to_charlist(+456)\n '456'\n\n iex> Integer.to_charlist(-789)\n '-789'\n\n iex> Integer.to_charlist(0123)\n '123'\n\n \"\"\"\n @spec to_charlist(integer) :: charlist\n def to_charlist(integer) do\n :erlang.integer_to_list(integer)\n end\n\n @doc \"\"\"\n Returns a charlist which corresponds to the text representation of `integer` in the given `base`.\n\n `base` can be an integer between 2 and 36.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Integer.to_charlist(100, 16)\n '64'\n\n iex> Integer.to_charlist(-100, 16)\n '-64'\n\n iex> Integer.to_charlist(882_681_651, 36)\n 'ELIXIR'\n\n \"\"\"\n @spec to_charlist(integer, 2..36) :: charlist\n def to_charlist(integer, base) do\n :erlang.integer_to_list(integer, base)\n end\n\n @doc \"\"\"\n Returns the greatest common divisor of the two given integers.\n\n The greatest common divisor (GCD) of `integer1` and `integer2` is the largest positive\n integer that divides both `integer1` and `integer2` without leaving a remainder.\n\n By convention, `gcd(0, 0)` returns `0`.\n\n ## Examples\n\n iex> Integer.gcd(2, 3)\n 1\n\n iex> Integer.gcd(8, 12)\n 4\n\n iex> Integer.gcd(8, -12)\n 4\n\n iex> Integer.gcd(10, 0)\n 10\n\n iex> Integer.gcd(7, 7)\n 7\n\n iex> Integer.gcd(0, 0)\n 0\n\n \"\"\"\n @doc since: \"1.5.0\"\n @spec gcd(0, 0) :: 0\n @spec gcd(integer, integer) :: pos_integer\n def gcd(integer1, integer2) when is_integer(integer1) and is_integer(integer2) do\n gcd_positive(abs(integer1), abs(integer2))\n end\n\n defp gcd_positive(0, integer2), do: integer2\n defp gcd_positive(integer1, 0), do: integer1\n defp gcd_positive(integer1, integer2), do: gcd_positive(integer2, rem(integer1, integer2))\n\n # TODO: Remove by 2.0\n @doc false\n @deprecated \"Use Integer.to_charlist\/1 instead\"\n def to_char_list(integer), do: Integer.to_charlist(integer)\n\n # TODO: Remove by 2.0\n @doc false\n @deprecated \"Use Integer.to_charlist\/2 instead\"\n def to_char_list(integer, base), do: Integer.to_charlist(integer, base)\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"0eb3fbbf41eb0e9aede944b6dd7afa4a55b87f80","subject":"Update reference to Keyword.delete\/3 (#9394)","message":"Update reference to Keyword.delete\/3 (#9394)\n\nExDoc is giving a warning since it has been deprecated and @doc is set to false.\r\n> warning: documentation references Keyword.delete\/3 but it doesn't exist or it's listed as @doc false (parsing Keyword docs)\r\n","repos":"pedrosnk\/elixir,kimshrier\/elixir,joshprice\/elixir,kimshrier\/elixir,ggcampinho\/elixir,elixir-lang\/elixir,kelvinst\/elixir,michalmuskala\/elixir,kelvinst\/elixir,ggcampinho\/elixir,pedrosnk\/elixir","old_file":"lib\/elixir\/lib\/keyword.ex","new_file":"lib\/elixir\/lib\/keyword.ex","new_contents":"defmodule Keyword do\n @moduledoc \"\"\"\n Keyword lists are lists of two-element tuples, where the first\n element of the tuple is an atom and the second element can be any\n value, used mostly to work with optional values.\n\n For example, the following is a keyword list:\n\n [{:exit_on_close, true}, {:active, :once}, {:packet_size, 1024}]\n\n Elixir provides a special and more concise syntax for keyword lists\n that looks like this:\n\n [exit_on_close: true, active: :once, packet_size: 1024]\n\n This is also the syntax that Elixir uses to inspect keyword lists:\n\n iex> [{:active, :once}]\n [active: :once]\n\n The two syntaxes are completely equivalent. Like atoms, keywords\n must be composed of Unicode characters such as letters, numbers,\n underscore, and `@`. If the keyword has a character that does not\n belong to the category above, such as spaces, you can wrap it in\n quotes:\n\n iex> [\"exit on close\": true]\n [\"exit on close\": true]\n\n Wrapping a keyword in quotes does not make it a string. Keywords are\n always atoms. If you use quotes when all characters are a valid part\n of a keyword without quotes, Elixir will warn.\n\n Note that when keyword lists are passed as the last argument to a function,\n if the shorthand syntax is used then the square brackets around the keyword\n list can be omitted as well. For example, the following:\n\n String.split(\"1-0\", \"-\", trim: true, parts: 2)\n\n is equivalent to:\n\n String.split(\"1-0\", \"-\", [trim: true, parts: 2])\n\n A keyword may have duplicated keys so it is not strictly\n a key-value store. However most of the functions in this module\n behave exactly as a key-value so they work similarly to\n the functions you would find in the `Map` module.\n\n For example, `Keyword.get\/3` will get the first entry matching\n the given key, regardless if duplicated entries exist.\n Similarly, `Keyword.put\/3` and `Keyword.delete\/2` ensure all\n duplicated entries for a given key are removed when invoked.\n Note that operations that require keys to be found in the keyword\n list (like `Keyword.get\/3`) need to traverse the list in order\n to find keys, so these operations may be slower than their map\n counterparts.\n\n A handful of functions exist to handle duplicated keys, in\n particular, `Enum.into\/2` allows creating new keywords without\n removing duplicated keys, `get_values\/2` returns all values for\n a given key and `delete_first\/2` deletes just one of the existing\n entries.\n\n The functions in `Keyword` do not guarantee any property when\n it comes to ordering. However, since a keyword list is simply a\n list, all the operations defined in `Enum` and `List` can be\n applied too, especially when ordering is required.\n\n Most of the functions in this module work in linear time. This means\n that, the time it takes to perform an operation grows at the same\n rate as the length of the list.\n \"\"\"\n\n @compile :inline_list_funcs\n\n @type key :: atom\n @type value :: any\n\n @type t :: [{key, value}]\n @type t(value) :: [{key, value}]\n\n @doc \"\"\"\n Returns `true` if `term` is a keyword list; otherwise returns `false`.\n\n ## Examples\n\n iex> Keyword.keyword?([])\n true\n iex> Keyword.keyword?(a: 1)\n true\n iex> Keyword.keyword?([{Foo, 1}])\n true\n iex> Keyword.keyword?([{}])\n false\n iex> Keyword.keyword?([:key])\n false\n iex> Keyword.keyword?(%{})\n false\n\n \"\"\"\n @spec keyword?(term) :: boolean\n def keyword?(term)\n\n def keyword?([{key, _value} | rest]) when is_atom(key), do: keyword?(rest)\n def keyword?([]), do: true\n def keyword?(_other), do: false\n\n @doc \"\"\"\n Returns an empty keyword list, i.e. an empty list.\n\n ## Examples\n\n iex> Keyword.new()\n []\n\n \"\"\"\n @spec new :: []\n def new, do: []\n\n @doc \"\"\"\n Creates a keyword list from an enumerable.\n\n Duplicated entries are removed, the latest one prevails.\n Unlike `Enum.into(enumerable, [])`, `Keyword.new(enumerable)`\n guarantees the keys are unique.\n\n ## Examples\n\n iex> Keyword.new([{:b, 1}, {:a, 2}])\n [b: 1, a: 2]\n\n iex> Keyword.new([{:a, 1}, {:a, 2}, {:a, 3}])\n [a: 3]\n\n \"\"\"\n @spec new(Enum.t()) :: t\n def new(pairs) do\n new(pairs, fn pair -> pair end)\n end\n\n @doc \"\"\"\n Creates a keyword list from an enumerable via the transformation function.\n\n Duplicated entries are removed, the latest one prevails.\n Unlike `Enum.into(enumerable, [], fun)`,\n `Keyword.new(enumerable, fun)` guarantees the keys are unique.\n\n ## Examples\n\n iex> Keyword.new([:a, :b], fn x -> {x, x} end)\n [a: :a, b: :b]\n\n \"\"\"\n @spec new(Enum.t(), (term -> {key, value})) :: t\n def new(pairs, transform) when is_function(transform, 1) do\n fun = fn el, acc ->\n {k, v} = transform.(el)\n put_new(acc, k, v)\n end\n\n :lists.foldl(fun, [], Enum.reverse(pairs))\n end\n\n @doc \"\"\"\n Gets the value for a specific `key`.\n\n If `key` does not exist, return the default value\n (`nil` if no default value).\n\n If duplicated entries exist, the first one is returned.\n Use `get_values\/2` to retrieve all entries.\n\n ## Examples\n\n iex> Keyword.get([], :a)\n nil\n iex> Keyword.get([a: 1], :a)\n 1\n iex> Keyword.get([a: 1], :b)\n nil\n iex> Keyword.get([a: 1], :b, 3)\n 3\n\n With duplicated keys:\n\n iex> Keyword.get([a: 1, a: 2], :a, 3)\n 1\n iex> Keyword.get([a: 1, a: 2], :b, 3)\n 3\n\n \"\"\"\n @spec get(t, key, value) :: value\n def get(keywords, key, default \\\\ nil) when is_list(keywords) and is_atom(key) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, value} -> value\n false -> default\n end\n end\n\n @doc \"\"\"\n Gets the value for a specific `key`.\n\n If `key` does not exist, lazily evaluates `fun` and returns its result.\n\n This is useful if the default value is very expensive to calculate or\n generally difficult to setup and teardown again.\n\n If duplicated entries exist, the first one is returned.\n Use `get_values\/2` to retrieve all entries.\n\n ## Examples\n\n iex> keyword = [a: 1]\n iex> fun = fn ->\n ...> # some expensive operation here\n ...> 13\n ...> end\n iex> Keyword.get_lazy(keyword, :a, fun)\n 1\n iex> Keyword.get_lazy(keyword, :b, fun)\n 13\n\n \"\"\"\n @spec get_lazy(t, key, (() -> value)) :: value\n def get_lazy(keywords, key, fun)\n when is_list(keywords) and is_atom(key) and is_function(fun, 0) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, value} -> value\n false -> fun.()\n end\n end\n\n @doc \"\"\"\n Gets the value from `key` and updates it, all in one pass.\n\n This `fun` argument receives the value of `key` (or `nil` if `key`\n is not present) and must return a two-element tuple: the \"get\" value\n (the retrieved value, which can be operated on before being returned)\n and the new value to be stored under `key`. The `fun` may also\n return `:pop`, implying the current value shall be removed from the\n keyword list and returned.\n\n The returned value is a tuple with the \"get\" value returned by\n `fun` and a new keyword list with the updated value under `key`.\n\n ## Examples\n\n iex> Keyword.get_and_update([a: 1], :a, fn current_value ->\n ...> {current_value, \"new value!\"}\n ...> end)\n {1, [a: \"new value!\"]}\n\n iex> Keyword.get_and_update([a: 1], :b, fn current_value ->\n ...> {current_value, \"new value!\"}\n ...> end)\n {nil, [b: \"new value!\", a: 1]}\n\n iex> Keyword.get_and_update([a: 1], :a, fn _ -> :pop end)\n {1, []}\n\n iex> Keyword.get_and_update([a: 1], :b, fn _ -> :pop end)\n {nil, [a: 1]}\n\n \"\"\"\n @spec get_and_update(t, key, (value -> {get, value} | :pop)) :: {get, t} when get: term\n def get_and_update(keywords, key, fun)\n when is_list(keywords) and is_atom(key),\n do: get_and_update(keywords, [], key, fun)\n\n defp get_and_update([{key, current} | t], acc, key, fun) do\n case fun.(current) do\n {get, value} ->\n {get, :lists.reverse(acc, [{key, value} | t])}\n\n :pop ->\n {current, :lists.reverse(acc, t)}\n\n other ->\n raise \"the given function must return a two-element tuple or :pop, got: #{inspect(other)}\"\n end\n end\n\n defp get_and_update([{_, _} = h | t], acc, key, fun), do: get_and_update(t, [h | acc], key, fun)\n\n defp get_and_update([], acc, key, fun) do\n case fun.(nil) do\n {get, update} ->\n {get, [{key, update} | :lists.reverse(acc)]}\n\n :pop ->\n {nil, :lists.reverse(acc)}\n\n other ->\n raise \"the given function must return a two-element tuple or :pop, got: #{inspect(other)}\"\n end\n end\n\n @doc \"\"\"\n Gets the value from `key` and updates it. Raises if there is no `key`.\n\n This `fun` argument receives the value of `key` and must return a\n two-element tuple: the \"get\" value (the retrieved value, which can be\n operated on before being returned) and the new value to be stored under\n `key`.\n\n The returned value is a tuple with the \"get\" value returned by `fun` and a new\n keyword list with the updated value under `key`.\n\n ## Examples\n\n iex> Keyword.get_and_update!([a: 1], :a, fn current_value ->\n ...> {current_value, \"new value!\"}\n ...> end)\n {1, [a: \"new value!\"]}\n\n iex> Keyword.get_and_update!([a: 1], :b, fn current_value ->\n ...> {current_value, \"new value!\"}\n ...> end)\n ** (KeyError) key :b not found in: [a: 1]\n\n iex> Keyword.get_and_update!([a: 1], :a, fn _ ->\n ...> :pop\n ...> end)\n {1, []}\n\n \"\"\"\n @spec get_and_update!(t, key, (value -> {get, value})) :: {get, t} when get: term\n def get_and_update!(keywords, key, fun) do\n get_and_update!(keywords, key, fun, [])\n end\n\n defp get_and_update!([{key, value} | keywords], key, fun, acc) do\n case fun.(value) do\n {get, value} ->\n {get, :lists.reverse(acc, [{key, value} | delete(keywords, key)])}\n\n :pop ->\n {value, :lists.reverse(acc, keywords)}\n\n other ->\n raise \"the given function must return a two-element tuple or :pop, got: #{inspect(other)}\"\n end\n end\n\n defp get_and_update!([{_, _} = e | keywords], key, fun, acc) do\n get_and_update!(keywords, key, fun, [e | acc])\n end\n\n defp get_and_update!([], key, _fun, acc) when is_atom(key) do\n raise(KeyError, key: key, term: acc)\n end\n\n @doc \"\"\"\n Fetches the value for a specific `key` and returns it in a tuple.\n\n If the `key` does not exist, returns `:error`.\n\n ## Examples\n\n iex> Keyword.fetch([a: 1], :a)\n {:ok, 1}\n iex> Keyword.fetch([a: 1], :b)\n :error\n\n \"\"\"\n @spec fetch(t, key) :: {:ok, value} | :error\n def fetch(keywords, key) when is_list(keywords) and is_atom(key) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, value} -> {:ok, value}\n false -> :error\n end\n end\n\n @doc \"\"\"\n Fetches the value for specific `key`.\n\n If `key` does not exist, a `KeyError` is raised.\n\n ## Examples\n\n iex> Keyword.fetch!([a: 1], :a)\n 1\n iex> Keyword.fetch!([a: 1], :b)\n ** (KeyError) key :b not found in: [a: 1]\n\n \"\"\"\n @spec fetch!(t, key) :: value\n def fetch!(keywords, key) when is_list(keywords) and is_atom(key) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, value} -> value\n false -> raise(KeyError, key: key, term: keywords)\n end\n end\n\n @doc \"\"\"\n Gets all values for a specific `key`.\n\n ## Examples\n\n iex> Keyword.get_values([], :a)\n []\n iex> Keyword.get_values([a: 1], :a)\n [1]\n iex> Keyword.get_values([a: 1, a: 2], :a)\n [1, 2]\n\n \"\"\"\n @spec get_values(t, key) :: [value]\n def get_values(keywords, key) when is_list(keywords) and is_atom(key) do\n get_values(keywords, key, [])\n end\n\n defp get_values([{key, value} | tail], key, values), do: get_values(tail, key, [value | values])\n defp get_values([{_, _} | tail], key, values), do: get_values(tail, key, values)\n defp get_values([], _key, values), do: :lists.reverse(values)\n\n @doc \"\"\"\n Returns all keys from the keyword list.\n\n Duplicated keys appear duplicated in the final list of keys.\n\n ## Examples\n\n iex> Keyword.keys(a: 1, b: 2)\n [:a, :b]\n iex> Keyword.keys(a: 1, b: 2, a: 3)\n [:a, :b, :a]\n\n \"\"\"\n @spec keys(t) :: [key]\n def keys(keywords) when is_list(keywords) do\n :lists.map(fn {k, _} -> k end, keywords)\n end\n\n @doc \"\"\"\n Returns all values from the keyword list.\n\n Values from duplicated keys will be kept in the final list of values.\n\n ## Examples\n\n iex> Keyword.values(a: 1, b: 2)\n [1, 2]\n iex> Keyword.values(a: 1, b: 2, a: 3)\n [1, 2, 3]\n\n \"\"\"\n @spec values(t) :: [value]\n def values(keywords) when is_list(keywords) do\n :lists.map(fn {_, v} -> v end, keywords)\n end\n\n @doc false\n @deprecated \"Use Keyword.fetch\/2 + Keyword.delete\/2 instead\"\n def delete(keywords, key, value) when is_list(keywords) and is_atom(key) do\n case :lists.keymember(key, 1, keywords) do\n true -> delete_key_value(keywords, key, value)\n _ -> keywords\n end\n end\n\n defp delete_key_value([{key, value} | tail], key, value) do\n delete_key_value(tail, key, value)\n end\n\n defp delete_key_value([{_, _} = pair | tail], key, value) do\n [pair | delete_key_value(tail, key, value)]\n end\n\n defp delete_key_value([], _key, _value) do\n []\n end\n\n @doc \"\"\"\n Deletes the entries in the keyword list for a specific `key`.\n\n If the `key` does not exist, returns the keyword list unchanged.\n Use `delete_first\/2` to delete just the first entry in case of\n duplicated keys.\n\n ## Examples\n\n iex> Keyword.delete([a: 1, b: 2], :a)\n [b: 2]\n iex> Keyword.delete([a: 1, b: 2, a: 3], :a)\n [b: 2]\n iex> Keyword.delete([b: 2], :a)\n [b: 2]\n\n \"\"\"\n @spec delete(t, key) :: t\n @compile {:inline, delete: 2}\n def delete(keywords, key) when is_list(keywords) and is_atom(key) do\n case :lists.keymember(key, 1, keywords) do\n true -> delete_key(keywords, key)\n _ -> keywords\n end\n end\n\n defp delete_key([{key, _} | tail], key), do: delete_key(tail, key)\n defp delete_key([{_, _} = pair | tail], key), do: [pair | delete_key(tail, key)]\n defp delete_key([], _key), do: []\n\n @doc \"\"\"\n Deletes the first entry in the keyword list for a specific `key`.\n\n If the `key` does not exist, returns the keyword list unchanged.\n\n ## Examples\n\n iex> Keyword.delete_first([a: 1, b: 2, a: 3], :a)\n [b: 2, a: 3]\n iex> Keyword.delete_first([b: 2], :a)\n [b: 2]\n\n \"\"\"\n @spec delete_first(t, key) :: t\n def delete_first(keywords, key) when is_list(keywords) and is_atom(key) do\n case :lists.keymember(key, 1, keywords) do\n true -> delete_first_key(keywords, key)\n _ -> keywords\n end\n end\n\n defp delete_first_key([{key, _} | tail], key) do\n tail\n end\n\n defp delete_first_key([{_, _} = pair | tail], key) do\n [pair | delete_first_key(tail, key)]\n end\n\n defp delete_first_key([], _key) do\n []\n end\n\n @doc \"\"\"\n Puts the given `value` under `key`.\n\n If a previous value is already stored, all entries are\n removed and the value is overridden.\n\n ## Examples\n\n iex> Keyword.put([a: 1], :b, 2)\n [b: 2, a: 1]\n iex> Keyword.put([a: 1, b: 2], :a, 3)\n [a: 3, b: 2]\n iex> Keyword.put([a: 1, b: 2, a: 4], :a, 3)\n [a: 3, b: 2]\n\n \"\"\"\n @spec put(t, key, value) :: t\n def put(keywords, key, value) when is_list(keywords) and is_atom(key) do\n [{key, value} | delete(keywords, key)]\n end\n\n @doc \"\"\"\n Evaluates `fun` and puts the result under `key`\n in keyword list unless `key` is already present.\n\n This is useful if the value is very expensive to calculate or\n generally difficult to setup and teardown again.\n\n ## Examples\n\n iex> keyword = [a: 1]\n iex> fun = fn ->\n ...> # some expensive operation here\n ...> 3\n ...> end\n iex> Keyword.put_new_lazy(keyword, :a, fun)\n [a: 1]\n iex> Keyword.put_new_lazy(keyword, :b, fun)\n [b: 3, a: 1]\n\n \"\"\"\n @spec put_new_lazy(t, key, (() -> value)) :: t\n def put_new_lazy(keywords, key, fun)\n when is_list(keywords) and is_atom(key) and is_function(fun, 0) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, _} -> keywords\n false -> [{key, fun.()} | keywords]\n end\n end\n\n @doc \"\"\"\n Puts the given `value` under `key` unless the entry `key`\n already exists.\n\n ## Examples\n\n iex> Keyword.put_new([a: 1], :b, 2)\n [b: 2, a: 1]\n iex> Keyword.put_new([a: 1, b: 2], :a, 3)\n [a: 1, b: 2]\n\n \"\"\"\n @spec put_new(t, key, value) :: t\n def put_new(keywords, key, value) when is_list(keywords) and is_atom(key) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, _} -> keywords\n false -> [{key, value} | keywords]\n end\n end\n\n @doc false\n @deprecated \"Use Keyword.fetch\/2 + Keyword.put\/3 instead\"\n def replace(keywords, key, value) when is_list(keywords) and is_atom(key) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, _} -> [{key, value} | delete(keywords, key)]\n false -> keywords\n end\n end\n\n @doc \"\"\"\n Alters the value stored under `key` to `value`, but only\n if the entry `key` already exists in `keywords`.\n\n If `key` is not present in `keywords`, a `KeyError` exception is raised.\n\n ## Examples\n\n iex> Keyword.replace!([a: 1, b: 2, a: 3], :a, :new)\n [a: :new, b: 2]\n iex> Keyword.replace!([a: 1, b: 2, c: 3, b: 4], :b, :new)\n [a: 1, b: :new, c: 3]\n\n iex> Keyword.replace!([a: 1], :b, 2)\n ** (KeyError) key :b not found in: [a: 1]\n\n \"\"\"\n @doc since: \"1.5.0\"\n @spec replace!(t, key, value) :: t\n def replace!(keywords, key, value) when is_list(keywords) and is_atom(key) do\n replace!(keywords, key, value, keywords)\n end\n\n defp replace!([{key, _} | keywords], key, value, _original) do\n [{key, value} | delete(keywords, key)]\n end\n\n defp replace!([{_, _} = e | keywords], key, value, original) do\n [e | replace!(keywords, key, value, original)]\n end\n\n defp replace!([], key, _value, original) when is_atom(key) do\n raise(KeyError, key: key, term: original)\n end\n\n @doc \"\"\"\n Checks if two keywords are equal.\n\n Two keywords are considered to be equal if they contain\n the same keys and those keys contain the same values.\n\n ## Examples\n\n iex> Keyword.equal?([a: 1, b: 2], [b: 2, a: 1])\n true\n iex> Keyword.equal?([a: 1, b: 2], [b: 1, a: 2])\n false\n iex> Keyword.equal?([a: 1, b: 2, a: 3], [b: 2, a: 3, a: 1])\n true\n\n \"\"\"\n @spec equal?(t, t) :: boolean\n def equal?(left, right) when is_list(left) and is_list(right) do\n :lists.sort(left) == :lists.sort(right)\n end\n\n @doc \"\"\"\n Merges two keyword lists into one.\n\n All keys, including duplicated keys, given in `keywords2` will be added\n to `keywords1`, overriding any existing one.\n\n There are no guarantees about the order of keys in the returned keyword.\n\n ## Examples\n\n iex> Keyword.merge([a: 1, b: 2], [a: 3, d: 4])\n [b: 2, a: 3, d: 4]\n\n iex> Keyword.merge([a: 1, b: 2], [a: 3, d: 4, a: 5])\n [b: 2, a: 3, d: 4, a: 5]\n\n iex> Keyword.merge([a: 1], [2, 3])\n ** (ArgumentError) expected a keyword list as the second argument, got: [2, 3]\n\n \"\"\"\n @spec merge(t, t) :: t\n def merge(keywords1, keywords2)\n\n def merge(keywords1, []) when is_list(keywords1), do: keywords1\n def merge([], keywords2) when is_list(keywords2), do: keywords2\n\n def merge(keywords1, keywords2) when is_list(keywords1) and is_list(keywords2) do\n if keyword?(keywords2) do\n fun = fn\n {key, _value} when is_atom(key) ->\n not has_key?(keywords2, key)\n\n _ ->\n raise ArgumentError,\n \"expected a keyword list as the first argument, got: #{inspect(keywords1)}\"\n end\n\n :lists.filter(fun, keywords1) ++ keywords2\n else\n raise ArgumentError,\n \"expected a keyword list as the second argument, got: #{inspect(keywords2)}\"\n end\n end\n\n @doc \"\"\"\n Merges two keyword lists into one.\n\n All keys, including duplicated keys, given in `keywords2` will be added\n to `keywords1`. The given function will be invoked to solve conflicts.\n\n If `keywords2` has duplicate keys, the given function will be invoked\n for each matching pair in `keywords1`.\n\n There are no guarantees about the order of keys in the returned keyword.\n\n ## Examples\n\n iex> Keyword.merge([a: 1, b: 2], [a: 3, d: 4], fn _k, v1, v2 ->\n ...> v1 + v2\n ...> end)\n [b: 2, a: 4, d: 4]\n\n iex> Keyword.merge([a: 1, b: 2], [a: 3, d: 4, a: 5], fn :a, v1, v2 ->\n ...> v1 + v2\n ...> end)\n [b: 2, a: 4, d: 4, a: 5]\n\n iex> Keyword.merge([a: 1, b: 2, a: 3], [a: 3, d: 4, a: 5], fn :a, v1, v2 ->\n ...> v1 + v2\n ...> end)\n [b: 2, a: 4, d: 4, a: 8]\n\n iex> Keyword.merge([a: 1, b: 2], [:a, :b], fn :a, v1, v2 ->\n ...> v1 + v2\n ...> end)\n ** (ArgumentError) expected a keyword list as the second argument, got: [:a, :b]\n\n \"\"\"\n @spec merge(t, t, (key, value, value -> value)) :: t\n def merge(keywords1, keywords2, fun)\n when is_list(keywords1) and is_list(keywords2) and is_function(fun, 3) do\n if keyword?(keywords1) do\n do_merge(keywords2, [], keywords1, keywords1, fun, keywords2)\n else\n raise ArgumentError,\n \"expected a keyword list as the first argument, got: #{inspect(keywords1)}\"\n end\n end\n\n defp do_merge([{key, value2} | tail], acc, rest, original, fun, keywords2) when is_atom(key) do\n case :lists.keyfind(key, 1, original) do\n {^key, value1} ->\n acc = [{key, fun.(key, value1, value2)} | acc]\n original = :lists.keydelete(key, 1, original)\n do_merge(tail, acc, delete(rest, key), original, fun, keywords2)\n\n false ->\n do_merge(tail, [{key, value2} | acc], rest, original, fun, keywords2)\n end\n end\n\n defp do_merge([], acc, rest, _original, _fun, _keywords2) do\n rest ++ :lists.reverse(acc)\n end\n\n defp do_merge(_other, _acc, _rest, _original, _fun, keywords2) do\n raise ArgumentError,\n \"expected a keyword list as the second argument, got: #{inspect(keywords2)}\"\n end\n\n @doc \"\"\"\n Returns whether a given `key` exists in the given `keywords`.\n\n ## Examples\n\n iex> Keyword.has_key?([a: 1], :a)\n true\n iex> Keyword.has_key?([a: 1], :b)\n false\n\n \"\"\"\n @spec has_key?(t, key) :: boolean\n def has_key?(keywords, key) when is_list(keywords) and is_atom(key) do\n :lists.keymember(key, 1, keywords)\n end\n\n @doc \"\"\"\n Updates the `key` with the given function.\n\n If the `key` does not exist, raises `KeyError`.\n\n If there are duplicated keys, they are all removed and only the first one\n is updated.\n\n ## Examples\n\n iex> Keyword.update!([a: 1, b: 2, a: 3], :a, &(&1 * 2))\n [a: 2, b: 2]\n iex> Keyword.update!([a: 1, b: 2, c: 3], :b, &(&1 * 2))\n [a: 1, b: 4, c: 3]\n\n iex> Keyword.update!([a: 1], :b, &(&1 * 2))\n ** (KeyError) key :b not found in: [a: 1]\n\n \"\"\"\n @spec update!(t, key, (value -> value)) :: t\n def update!(keywords, key, fun)\n when is_list(keywords) and is_atom(key) and is_function(fun, 1) do\n update!(keywords, key, fun, keywords)\n end\n\n defp update!([{key, value} | keywords], key, fun, _original) do\n [{key, fun.(value)} | delete(keywords, key)]\n end\n\n defp update!([{_, _} = e | keywords], key, fun, original) do\n [e | update!(keywords, key, fun, original)]\n end\n\n defp update!([], key, _fun, original) when is_atom(key) do\n raise(KeyError, key: key, term: original)\n end\n\n @doc \"\"\"\n Updates the `key` in `keywords` with the given function.\n\n If the `key` does not exist, inserts the given `initial` value.\n\n If there are duplicated keys, they are all removed and only the first one\n is updated.\n\n ## Examples\n\n iex> Keyword.update([a: 1], :a, 13, &(&1 * 2))\n [a: 2]\n iex> Keyword.update([a: 1, a: 2], :a, 13, &(&1 * 2))\n [a: 2]\n iex> Keyword.update([a: 1], :b, 11, &(&1 * 2))\n [a: 1, b: 11]\n\n \"\"\"\n @spec update(t, key, value, (value -> value)) :: t\n def update(keywords, key, initial, fun)\n\n def update([{key, value} | keywords], key, _initial, fun) do\n [{key, fun.(value)} | delete(keywords, key)]\n end\n\n def update([{_, _} = e | keywords], key, initial, fun) do\n [e | update(keywords, key, initial, fun)]\n end\n\n def update([], key, initial, _fun) when is_atom(key) do\n [{key, initial}]\n end\n\n @doc \"\"\"\n Takes all entries corresponding to the given keys and extracts them into a\n separate keyword list.\n\n Returns a tuple with the new list and the old list with removed keys.\n\n Keys for which there are no entries in the keyword list are ignored.\n\n Entries with duplicated keys end up in the same keyword list.\n\n ## Examples\n\n iex> Keyword.split([a: 1, b: 2, c: 3], [:a, :c, :e])\n {[a: 1, c: 3], [b: 2]}\n iex> Keyword.split([a: 1, b: 2, c: 3, a: 4], [:a, :c, :e])\n {[a: 1, c: 3, a: 4], [b: 2]}\n\n \"\"\"\n @spec split(t, [key]) :: {t, t}\n def split(keywords, keys) when is_list(keywords) and is_list(keys) do\n fun = fn {k, v}, {take, drop} ->\n case k in keys do\n true -> {[{k, v} | take], drop}\n false -> {take, [{k, v} | drop]}\n end\n end\n\n acc = {[], []}\n {take, drop} = :lists.foldl(fun, acc, keywords)\n {:lists.reverse(take), :lists.reverse(drop)}\n end\n\n @doc \"\"\"\n Takes all entries corresponding to the given keys and returns them in a new\n keyword list.\n\n Duplicated keys are preserved in the new keyword list.\n\n ## Examples\n\n iex> Keyword.take([a: 1, b: 2, c: 3], [:a, :c, :e])\n [a: 1, c: 3]\n iex> Keyword.take([a: 1, b: 2, c: 3, a: 5], [:a, :c, :e])\n [a: 1, c: 3, a: 5]\n\n \"\"\"\n @spec take(t, [key]) :: t\n def take(keywords, keys) when is_list(keywords) and is_list(keys) do\n :lists.filter(fn {k, _} -> k in keys end, keywords)\n end\n\n @doc \"\"\"\n Drops the given keys from the keyword list.\n\n Duplicated keys are preserved in the new keyword list.\n\n ## Examples\n\n iex> Keyword.drop([a: 1, b: 2, c: 3], [:b, :d])\n [a: 1, c: 3]\n iex> Keyword.drop([a: 1, b: 2, b: 3, c: 3, a: 5], [:b, :d])\n [a: 1, c: 3, a: 5]\n\n \"\"\"\n @spec drop(t, [key]) :: t\n def drop(keywords, keys) when is_list(keywords) and is_list(keys) do\n :lists.filter(fn {key, _} -> key not in keys end, keywords)\n end\n\n @doc \"\"\"\n Returns the first value for `key` and removes all associated entries in the keyword list.\n\n It returns a tuple where the first element is the first value for `key` and the\n second element is a keyword list with all entries associated with `key` removed.\n If the `key` is not present in the keyword list, `{default, keyword_list}` is\n returned.\n\n If you don't want to remove all the entries associated with `key` use `pop_first\/3`\n instead, that function will remove only the first entry.\n\n ## Examples\n\n iex> Keyword.pop([a: 1], :a)\n {1, []}\n iex> Keyword.pop([a: 1], :b)\n {nil, [a: 1]}\n iex> Keyword.pop([a: 1], :b, 3)\n {3, [a: 1]}\n iex> Keyword.pop([a: 1, a: 2], :a)\n {1, []}\n\n \"\"\"\n @spec pop(t, key, value) :: {value, t}\n def pop(keywords, key, default \\\\ nil) when is_list(keywords) and is_atom(key) do\n case fetch(keywords, key) do\n {:ok, value} -> {value, delete(keywords, key)}\n :error -> {default, keywords}\n end\n end\n\n @doc \"\"\"\n Returns the first value for `key` and removes all associated antries in the keyword list,\n raising if `key` is not present.\n\n This function behaves like `pop\/3`, but raises in cases the `key` is not present in the\n given `keywords`.\n\n ## Examples\n\n iex> Keyword.pop!([a: 1], :a)\n {1, []}\n iex> Keyword.pop!([a: 1, a: 2], :a)\n {1, []}\n iex> Keyword.pop!([a: 1], :b)\n ** (KeyError) key :b not found in: [a: 1]\n\n \"\"\"\n @doc since: \"1.10.0\"\n @spec pop!(t, key) :: {value, t}\n def pop!(keywords, key) when is_list(keywords) and is_atom(key) do\n case fetch(keywords, key) do\n {:ok, value} -> {value, delete(keywords, key)}\n :error -> raise KeyError, key: key, term: keywords\n end\n end\n\n @doc \"\"\"\n Returns all values for `key` and removes all associated entries in the keyword list.\n\n It returns a tuple where the first element is a list of values for `key` and the\n second element is a keyword list with all entries associated with `key` removed.\n If the `key` is not present in the keyword list, `{[], keyword_list}` is\n returned.\n\n If you don't want to remove all the entries associated with `key` use `pop_first\/3`\n instead, that function will remove only the first entry.\n\n ## Examples\n\n iex> Keyword.pop_values([a: 1], :a)\n {[1], []}\n iex> Keyword.pop_values([a: 1], :b)\n {[], [a: 1]}\n iex> Keyword.pop_values([a: 1, a: 2], :a)\n {[1, 2], []}\n\n \"\"\"\n @doc since: \"1.10.0\"\n @spec pop_values(t, key) :: {[value], t}\n def pop_values(keywords, key) when is_list(keywords) and is_atom(key) do\n pop_values(:lists.reverse(keywords), key, [], [])\n end\n\n defp pop_values([{key, value} | tail], key, values, acc),\n do: pop_values(tail, key, [value | values], acc)\n\n defp pop_values([{_, _} = pair | tail], key, values, acc),\n do: pop_values(tail, key, values, [pair | acc])\n\n defp pop_values([], _key, values, acc),\n do: {values, acc}\n\n @doc \"\"\"\n Lazily returns and removes all values associated with `key` in the keyword list.\n\n This is useful if the default value is very expensive to calculate or\n generally difficult to setup and teardown again.\n\n All duplicated keys are removed. See `pop_first\/3` for\n removing only the first entry.\n\n ## Examples\n\n iex> keyword = [a: 1]\n iex> fun = fn ->\n ...> # some expensive operation here\n ...> 13\n ...> end\n iex> Keyword.pop_lazy(keyword, :a, fun)\n {1, []}\n iex> Keyword.pop_lazy(keyword, :b, fun)\n {13, [a: 1]}\n\n \"\"\"\n @spec pop_lazy(t, key, (() -> value)) :: {value, t}\n def pop_lazy(keywords, key, fun)\n when is_list(keywords) and is_atom(key) and is_function(fun, 0) do\n case fetch(keywords, key) do\n {:ok, value} ->\n {value, delete(keywords, key)}\n\n :error ->\n {fun.(), keywords}\n end\n end\n\n @doc \"\"\"\n Returns and removes the first value associated with `key` in the keyword list.\n\n Duplicated keys are not removed.\n\n ## Examples\n\n iex> Keyword.pop_first([a: 1], :a)\n {1, []}\n iex> Keyword.pop_first([a: 1], :b)\n {nil, [a: 1]}\n iex> Keyword.pop_first([a: 1], :b, 3)\n {3, [a: 1]}\n iex> Keyword.pop_first([a: 1, a: 2], :a)\n {1, [a: 2]}\n\n \"\"\"\n @spec pop_first(t, key, value) :: {value, t}\n def pop_first(keywords, key, default \\\\ nil) when is_list(keywords) and is_atom(key) do\n case :lists.keytake(key, 1, keywords) do\n {:value, {^key, value}, rest} -> {value, rest}\n false -> {default, keywords}\n end\n end\n\n @doc \"\"\"\n Returns the keyword list itself.\n\n ## Examples\n\n iex> Keyword.to_list(a: 1)\n [a: 1]\n\n \"\"\"\n @spec to_list(t) :: t\n def to_list(keyword) when is_list(keyword) do\n keyword\n end\n\n @doc false\n @deprecated \"Use Kernel.length\/1 instead\"\n def size(keyword) do\n length(keyword)\n end\nend\n","old_contents":"defmodule Keyword do\n @moduledoc \"\"\"\n Keyword lists are lists of two-element tuples, where the first\n element of the tuple is an atom and the second element can be any\n value, used mostly to work with optional values.\n\n For example, the following is a keyword list:\n\n [{:exit_on_close, true}, {:active, :once}, {:packet_size, 1024}]\n\n Elixir provides a special and more concise syntax for keyword lists\n that looks like this:\n\n [exit_on_close: true, active: :once, packet_size: 1024]\n\n This is also the syntax that Elixir uses to inspect keyword lists:\n\n iex> [{:active, :once}]\n [active: :once]\n\n The two syntaxes are completely equivalent. Like atoms, keywords\n must be composed of Unicode characters such as letters, numbers,\n underscore, and `@`. If the keyword has a character that does not\n belong to the category above, such as spaces, you can wrap it in\n quotes:\n\n iex> [\"exit on close\": true]\n [\"exit on close\": true]\n\n Wrapping a keyword in quotes does not make it a string. Keywords are\n always atoms. If you use quotes when all characters are a valid part\n of a keyword without quotes, Elixir will warn.\n\n Note that when keyword lists are passed as the last argument to a function,\n if the shorthand syntax is used then the square brackets around the keyword\n list can be omitted as well. For example, the following:\n\n String.split(\"1-0\", \"-\", trim: true, parts: 2)\n\n is equivalent to:\n\n String.split(\"1-0\", \"-\", [trim: true, parts: 2])\n\n A keyword may have duplicated keys so it is not strictly\n a key-value store. However most of the functions in this module\n behave exactly as a key-value so they work similarly to\n the functions you would find in the `Map` module.\n\n For example, `Keyword.get\/3` will get the first entry matching\n the given key, regardless if duplicated entries exist.\n Similarly, `Keyword.put\/3` and `Keyword.delete\/3` ensure all\n duplicated entries for a given key are removed when invoked.\n Note that operations that require keys to be found in the keyword\n list (like `Keyword.get\/3`) need to traverse the list in order\n to find keys, so these operations may be slower than their map\n counterparts.\n\n A handful of functions exist to handle duplicated keys, in\n particular, `Enum.into\/2` allows creating new keywords without\n removing duplicated keys, `get_values\/2` returns all values for\n a given key and `delete_first\/2` deletes just one of the existing\n entries.\n\n The functions in `Keyword` do not guarantee any property when\n it comes to ordering. However, since a keyword list is simply a\n list, all the operations defined in `Enum` and `List` can be\n applied too, especially when ordering is required.\n\n Most of the functions in this module work in linear time. This means\n that, the time it takes to perform an operation grows at the same\n rate as the length of the list.\n \"\"\"\n\n @compile :inline_list_funcs\n\n @type key :: atom\n @type value :: any\n\n @type t :: [{key, value}]\n @type t(value) :: [{key, value}]\n\n @doc \"\"\"\n Returns `true` if `term` is a keyword list; otherwise returns `false`.\n\n ## Examples\n\n iex> Keyword.keyword?([])\n true\n iex> Keyword.keyword?(a: 1)\n true\n iex> Keyword.keyword?([{Foo, 1}])\n true\n iex> Keyword.keyword?([{}])\n false\n iex> Keyword.keyword?([:key])\n false\n iex> Keyword.keyword?(%{})\n false\n\n \"\"\"\n @spec keyword?(term) :: boolean\n def keyword?(term)\n\n def keyword?([{key, _value} | rest]) when is_atom(key), do: keyword?(rest)\n def keyword?([]), do: true\n def keyword?(_other), do: false\n\n @doc \"\"\"\n Returns an empty keyword list, i.e. an empty list.\n\n ## Examples\n\n iex> Keyword.new()\n []\n\n \"\"\"\n @spec new :: []\n def new, do: []\n\n @doc \"\"\"\n Creates a keyword list from an enumerable.\n\n Duplicated entries are removed, the latest one prevails.\n Unlike `Enum.into(enumerable, [])`, `Keyword.new(enumerable)`\n guarantees the keys are unique.\n\n ## Examples\n\n iex> Keyword.new([{:b, 1}, {:a, 2}])\n [b: 1, a: 2]\n\n iex> Keyword.new([{:a, 1}, {:a, 2}, {:a, 3}])\n [a: 3]\n\n \"\"\"\n @spec new(Enum.t()) :: t\n def new(pairs) do\n new(pairs, fn pair -> pair end)\n end\n\n @doc \"\"\"\n Creates a keyword list from an enumerable via the transformation function.\n\n Duplicated entries are removed, the latest one prevails.\n Unlike `Enum.into(enumerable, [], fun)`,\n `Keyword.new(enumerable, fun)` guarantees the keys are unique.\n\n ## Examples\n\n iex> Keyword.new([:a, :b], fn x -> {x, x} end)\n [a: :a, b: :b]\n\n \"\"\"\n @spec new(Enum.t(), (term -> {key, value})) :: t\n def new(pairs, transform) when is_function(transform, 1) do\n fun = fn el, acc ->\n {k, v} = transform.(el)\n put_new(acc, k, v)\n end\n\n :lists.foldl(fun, [], Enum.reverse(pairs))\n end\n\n @doc \"\"\"\n Gets the value for a specific `key`.\n\n If `key` does not exist, return the default value\n (`nil` if no default value).\n\n If duplicated entries exist, the first one is returned.\n Use `get_values\/2` to retrieve all entries.\n\n ## Examples\n\n iex> Keyword.get([], :a)\n nil\n iex> Keyword.get([a: 1], :a)\n 1\n iex> Keyword.get([a: 1], :b)\n nil\n iex> Keyword.get([a: 1], :b, 3)\n 3\n\n With duplicated keys:\n\n iex> Keyword.get([a: 1, a: 2], :a, 3)\n 1\n iex> Keyword.get([a: 1, a: 2], :b, 3)\n 3\n\n \"\"\"\n @spec get(t, key, value) :: value\n def get(keywords, key, default \\\\ nil) when is_list(keywords) and is_atom(key) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, value} -> value\n false -> default\n end\n end\n\n @doc \"\"\"\n Gets the value for a specific `key`.\n\n If `key` does not exist, lazily evaluates `fun` and returns its result.\n\n This is useful if the default value is very expensive to calculate or\n generally difficult to setup and teardown again.\n\n If duplicated entries exist, the first one is returned.\n Use `get_values\/2` to retrieve all entries.\n\n ## Examples\n\n iex> keyword = [a: 1]\n iex> fun = fn ->\n ...> # some expensive operation here\n ...> 13\n ...> end\n iex> Keyword.get_lazy(keyword, :a, fun)\n 1\n iex> Keyword.get_lazy(keyword, :b, fun)\n 13\n\n \"\"\"\n @spec get_lazy(t, key, (() -> value)) :: value\n def get_lazy(keywords, key, fun)\n when is_list(keywords) and is_atom(key) and is_function(fun, 0) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, value} -> value\n false -> fun.()\n end\n end\n\n @doc \"\"\"\n Gets the value from `key` and updates it, all in one pass.\n\n This `fun` argument receives the value of `key` (or `nil` if `key`\n is not present) and must return a two-element tuple: the \"get\" value\n (the retrieved value, which can be operated on before being returned)\n and the new value to be stored under `key`. The `fun` may also\n return `:pop`, implying the current value shall be removed from the\n keyword list and returned.\n\n The returned value is a tuple with the \"get\" value returned by\n `fun` and a new keyword list with the updated value under `key`.\n\n ## Examples\n\n iex> Keyword.get_and_update([a: 1], :a, fn current_value ->\n ...> {current_value, \"new value!\"}\n ...> end)\n {1, [a: \"new value!\"]}\n\n iex> Keyword.get_and_update([a: 1], :b, fn current_value ->\n ...> {current_value, \"new value!\"}\n ...> end)\n {nil, [b: \"new value!\", a: 1]}\n\n iex> Keyword.get_and_update([a: 1], :a, fn _ -> :pop end)\n {1, []}\n\n iex> Keyword.get_and_update([a: 1], :b, fn _ -> :pop end)\n {nil, [a: 1]}\n\n \"\"\"\n @spec get_and_update(t, key, (value -> {get, value} | :pop)) :: {get, t} when get: term\n def get_and_update(keywords, key, fun)\n when is_list(keywords) and is_atom(key),\n do: get_and_update(keywords, [], key, fun)\n\n defp get_and_update([{key, current} | t], acc, key, fun) do\n case fun.(current) do\n {get, value} ->\n {get, :lists.reverse(acc, [{key, value} | t])}\n\n :pop ->\n {current, :lists.reverse(acc, t)}\n\n other ->\n raise \"the given function must return a two-element tuple or :pop, got: #{inspect(other)}\"\n end\n end\n\n defp get_and_update([{_, _} = h | t], acc, key, fun), do: get_and_update(t, [h | acc], key, fun)\n\n defp get_and_update([], acc, key, fun) do\n case fun.(nil) do\n {get, update} ->\n {get, [{key, update} | :lists.reverse(acc)]}\n\n :pop ->\n {nil, :lists.reverse(acc)}\n\n other ->\n raise \"the given function must return a two-element tuple or :pop, got: #{inspect(other)}\"\n end\n end\n\n @doc \"\"\"\n Gets the value from `key` and updates it. Raises if there is no `key`.\n\n This `fun` argument receives the value of `key` and must return a\n two-element tuple: the \"get\" value (the retrieved value, which can be\n operated on before being returned) and the new value to be stored under\n `key`.\n\n The returned value is a tuple with the \"get\" value returned by `fun` and a new\n keyword list with the updated value under `key`.\n\n ## Examples\n\n iex> Keyword.get_and_update!([a: 1], :a, fn current_value ->\n ...> {current_value, \"new value!\"}\n ...> end)\n {1, [a: \"new value!\"]}\n\n iex> Keyword.get_and_update!([a: 1], :b, fn current_value ->\n ...> {current_value, \"new value!\"}\n ...> end)\n ** (KeyError) key :b not found in: [a: 1]\n\n iex> Keyword.get_and_update!([a: 1], :a, fn _ ->\n ...> :pop\n ...> end)\n {1, []}\n\n \"\"\"\n @spec get_and_update!(t, key, (value -> {get, value})) :: {get, t} when get: term\n def get_and_update!(keywords, key, fun) do\n get_and_update!(keywords, key, fun, [])\n end\n\n defp get_and_update!([{key, value} | keywords], key, fun, acc) do\n case fun.(value) do\n {get, value} ->\n {get, :lists.reverse(acc, [{key, value} | delete(keywords, key)])}\n\n :pop ->\n {value, :lists.reverse(acc, keywords)}\n\n other ->\n raise \"the given function must return a two-element tuple or :pop, got: #{inspect(other)}\"\n end\n end\n\n defp get_and_update!([{_, _} = e | keywords], key, fun, acc) do\n get_and_update!(keywords, key, fun, [e | acc])\n end\n\n defp get_and_update!([], key, _fun, acc) when is_atom(key) do\n raise(KeyError, key: key, term: acc)\n end\n\n @doc \"\"\"\n Fetches the value for a specific `key` and returns it in a tuple.\n\n If the `key` does not exist, returns `:error`.\n\n ## Examples\n\n iex> Keyword.fetch([a: 1], :a)\n {:ok, 1}\n iex> Keyword.fetch([a: 1], :b)\n :error\n\n \"\"\"\n @spec fetch(t, key) :: {:ok, value} | :error\n def fetch(keywords, key) when is_list(keywords) and is_atom(key) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, value} -> {:ok, value}\n false -> :error\n end\n end\n\n @doc \"\"\"\n Fetches the value for specific `key`.\n\n If `key` does not exist, a `KeyError` is raised.\n\n ## Examples\n\n iex> Keyword.fetch!([a: 1], :a)\n 1\n iex> Keyword.fetch!([a: 1], :b)\n ** (KeyError) key :b not found in: [a: 1]\n\n \"\"\"\n @spec fetch!(t, key) :: value\n def fetch!(keywords, key) when is_list(keywords) and is_atom(key) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, value} -> value\n false -> raise(KeyError, key: key, term: keywords)\n end\n end\n\n @doc \"\"\"\n Gets all values for a specific `key`.\n\n ## Examples\n\n iex> Keyword.get_values([], :a)\n []\n iex> Keyword.get_values([a: 1], :a)\n [1]\n iex> Keyword.get_values([a: 1, a: 2], :a)\n [1, 2]\n\n \"\"\"\n @spec get_values(t, key) :: [value]\n def get_values(keywords, key) when is_list(keywords) and is_atom(key) do\n get_values(keywords, key, [])\n end\n\n defp get_values([{key, value} | tail], key, values), do: get_values(tail, key, [value | values])\n defp get_values([{_, _} | tail], key, values), do: get_values(tail, key, values)\n defp get_values([], _key, values), do: :lists.reverse(values)\n\n @doc \"\"\"\n Returns all keys from the keyword list.\n\n Duplicated keys appear duplicated in the final list of keys.\n\n ## Examples\n\n iex> Keyword.keys(a: 1, b: 2)\n [:a, :b]\n iex> Keyword.keys(a: 1, b: 2, a: 3)\n [:a, :b, :a]\n\n \"\"\"\n @spec keys(t) :: [key]\n def keys(keywords) when is_list(keywords) do\n :lists.map(fn {k, _} -> k end, keywords)\n end\n\n @doc \"\"\"\n Returns all values from the keyword list.\n\n Values from duplicated keys will be kept in the final list of values.\n\n ## Examples\n\n iex> Keyword.values(a: 1, b: 2)\n [1, 2]\n iex> Keyword.values(a: 1, b: 2, a: 3)\n [1, 2, 3]\n\n \"\"\"\n @spec values(t) :: [value]\n def values(keywords) when is_list(keywords) do\n :lists.map(fn {_, v} -> v end, keywords)\n end\n\n @doc false\n @deprecated \"Use Keyword.fetch\/2 + Keyword.delete\/2 instead\"\n def delete(keywords, key, value) when is_list(keywords) and is_atom(key) do\n case :lists.keymember(key, 1, keywords) do\n true -> delete_key_value(keywords, key, value)\n _ -> keywords\n end\n end\n\n defp delete_key_value([{key, value} | tail], key, value) do\n delete_key_value(tail, key, value)\n end\n\n defp delete_key_value([{_, _} = pair | tail], key, value) do\n [pair | delete_key_value(tail, key, value)]\n end\n\n defp delete_key_value([], _key, _value) do\n []\n end\n\n @doc \"\"\"\n Deletes the entries in the keyword list for a specific `key`.\n\n If the `key` does not exist, returns the keyword list unchanged.\n Use `delete_first\/2` to delete just the first entry in case of\n duplicated keys.\n\n ## Examples\n\n iex> Keyword.delete([a: 1, b: 2], :a)\n [b: 2]\n iex> Keyword.delete([a: 1, b: 2, a: 3], :a)\n [b: 2]\n iex> Keyword.delete([b: 2], :a)\n [b: 2]\n\n \"\"\"\n @spec delete(t, key) :: t\n @compile {:inline, delete: 2}\n def delete(keywords, key) when is_list(keywords) and is_atom(key) do\n case :lists.keymember(key, 1, keywords) do\n true -> delete_key(keywords, key)\n _ -> keywords\n end\n end\n\n defp delete_key([{key, _} | tail], key), do: delete_key(tail, key)\n defp delete_key([{_, _} = pair | tail], key), do: [pair | delete_key(tail, key)]\n defp delete_key([], _key), do: []\n\n @doc \"\"\"\n Deletes the first entry in the keyword list for a specific `key`.\n\n If the `key` does not exist, returns the keyword list unchanged.\n\n ## Examples\n\n iex> Keyword.delete_first([a: 1, b: 2, a: 3], :a)\n [b: 2, a: 3]\n iex> Keyword.delete_first([b: 2], :a)\n [b: 2]\n\n \"\"\"\n @spec delete_first(t, key) :: t\n def delete_first(keywords, key) when is_list(keywords) and is_atom(key) do\n case :lists.keymember(key, 1, keywords) do\n true -> delete_first_key(keywords, key)\n _ -> keywords\n end\n end\n\n defp delete_first_key([{key, _} | tail], key) do\n tail\n end\n\n defp delete_first_key([{_, _} = pair | tail], key) do\n [pair | delete_first_key(tail, key)]\n end\n\n defp delete_first_key([], _key) do\n []\n end\n\n @doc \"\"\"\n Puts the given `value` under `key`.\n\n If a previous value is already stored, all entries are\n removed and the value is overridden.\n\n ## Examples\n\n iex> Keyword.put([a: 1], :b, 2)\n [b: 2, a: 1]\n iex> Keyword.put([a: 1, b: 2], :a, 3)\n [a: 3, b: 2]\n iex> Keyword.put([a: 1, b: 2, a: 4], :a, 3)\n [a: 3, b: 2]\n\n \"\"\"\n @spec put(t, key, value) :: t\n def put(keywords, key, value) when is_list(keywords) and is_atom(key) do\n [{key, value} | delete(keywords, key)]\n end\n\n @doc \"\"\"\n Evaluates `fun` and puts the result under `key`\n in keyword list unless `key` is already present.\n\n This is useful if the value is very expensive to calculate or\n generally difficult to setup and teardown again.\n\n ## Examples\n\n iex> keyword = [a: 1]\n iex> fun = fn ->\n ...> # some expensive operation here\n ...> 3\n ...> end\n iex> Keyword.put_new_lazy(keyword, :a, fun)\n [a: 1]\n iex> Keyword.put_new_lazy(keyword, :b, fun)\n [b: 3, a: 1]\n\n \"\"\"\n @spec put_new_lazy(t, key, (() -> value)) :: t\n def put_new_lazy(keywords, key, fun)\n when is_list(keywords) and is_atom(key) and is_function(fun, 0) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, _} -> keywords\n false -> [{key, fun.()} | keywords]\n end\n end\n\n @doc \"\"\"\n Puts the given `value` under `key` unless the entry `key`\n already exists.\n\n ## Examples\n\n iex> Keyword.put_new([a: 1], :b, 2)\n [b: 2, a: 1]\n iex> Keyword.put_new([a: 1, b: 2], :a, 3)\n [a: 1, b: 2]\n\n \"\"\"\n @spec put_new(t, key, value) :: t\n def put_new(keywords, key, value) when is_list(keywords) and is_atom(key) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, _} -> keywords\n false -> [{key, value} | keywords]\n end\n end\n\n @doc false\n @deprecated \"Use Keyword.fetch\/2 + Keyword.put\/3 instead\"\n def replace(keywords, key, value) when is_list(keywords) and is_atom(key) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, _} -> [{key, value} | delete(keywords, key)]\n false -> keywords\n end\n end\n\n @doc \"\"\"\n Alters the value stored under `key` to `value`, but only\n if the entry `key` already exists in `keywords`.\n\n If `key` is not present in `keywords`, a `KeyError` exception is raised.\n\n ## Examples\n\n iex> Keyword.replace!([a: 1, b: 2, a: 3], :a, :new)\n [a: :new, b: 2]\n iex> Keyword.replace!([a: 1, b: 2, c: 3, b: 4], :b, :new)\n [a: 1, b: :new, c: 3]\n\n iex> Keyword.replace!([a: 1], :b, 2)\n ** (KeyError) key :b not found in: [a: 1]\n\n \"\"\"\n @doc since: \"1.5.0\"\n @spec replace!(t, key, value) :: t\n def replace!(keywords, key, value) when is_list(keywords) and is_atom(key) do\n replace!(keywords, key, value, keywords)\n end\n\n defp replace!([{key, _} | keywords], key, value, _original) do\n [{key, value} | delete(keywords, key)]\n end\n\n defp replace!([{_, _} = e | keywords], key, value, original) do\n [e | replace!(keywords, key, value, original)]\n end\n\n defp replace!([], key, _value, original) when is_atom(key) do\n raise(KeyError, key: key, term: original)\n end\n\n @doc \"\"\"\n Checks if two keywords are equal.\n\n Two keywords are considered to be equal if they contain\n the same keys and those keys contain the same values.\n\n ## Examples\n\n iex> Keyword.equal?([a: 1, b: 2], [b: 2, a: 1])\n true\n iex> Keyword.equal?([a: 1, b: 2], [b: 1, a: 2])\n false\n iex> Keyword.equal?([a: 1, b: 2, a: 3], [b: 2, a: 3, a: 1])\n true\n\n \"\"\"\n @spec equal?(t, t) :: boolean\n def equal?(left, right) when is_list(left) and is_list(right) do\n :lists.sort(left) == :lists.sort(right)\n end\n\n @doc \"\"\"\n Merges two keyword lists into one.\n\n All keys, including duplicated keys, given in `keywords2` will be added\n to `keywords1`, overriding any existing one.\n\n There are no guarantees about the order of keys in the returned keyword.\n\n ## Examples\n\n iex> Keyword.merge([a: 1, b: 2], [a: 3, d: 4])\n [b: 2, a: 3, d: 4]\n\n iex> Keyword.merge([a: 1, b: 2], [a: 3, d: 4, a: 5])\n [b: 2, a: 3, d: 4, a: 5]\n\n iex> Keyword.merge([a: 1], [2, 3])\n ** (ArgumentError) expected a keyword list as the second argument, got: [2, 3]\n\n \"\"\"\n @spec merge(t, t) :: t\n def merge(keywords1, keywords2)\n\n def merge(keywords1, []) when is_list(keywords1), do: keywords1\n def merge([], keywords2) when is_list(keywords2), do: keywords2\n\n def merge(keywords1, keywords2) when is_list(keywords1) and is_list(keywords2) do\n if keyword?(keywords2) do\n fun = fn\n {key, _value} when is_atom(key) ->\n not has_key?(keywords2, key)\n\n _ ->\n raise ArgumentError,\n \"expected a keyword list as the first argument, got: #{inspect(keywords1)}\"\n end\n\n :lists.filter(fun, keywords1) ++ keywords2\n else\n raise ArgumentError,\n \"expected a keyword list as the second argument, got: #{inspect(keywords2)}\"\n end\n end\n\n @doc \"\"\"\n Merges two keyword lists into one.\n\n All keys, including duplicated keys, given in `keywords2` will be added\n to `keywords1`. The given function will be invoked to solve conflicts.\n\n If `keywords2` has duplicate keys, the given function will be invoked\n for each matching pair in `keywords1`.\n\n There are no guarantees about the order of keys in the returned keyword.\n\n ## Examples\n\n iex> Keyword.merge([a: 1, b: 2], [a: 3, d: 4], fn _k, v1, v2 ->\n ...> v1 + v2\n ...> end)\n [b: 2, a: 4, d: 4]\n\n iex> Keyword.merge([a: 1, b: 2], [a: 3, d: 4, a: 5], fn :a, v1, v2 ->\n ...> v1 + v2\n ...> end)\n [b: 2, a: 4, d: 4, a: 5]\n\n iex> Keyword.merge([a: 1, b: 2, a: 3], [a: 3, d: 4, a: 5], fn :a, v1, v2 ->\n ...> v1 + v2\n ...> end)\n [b: 2, a: 4, d: 4, a: 8]\n\n iex> Keyword.merge([a: 1, b: 2], [:a, :b], fn :a, v1, v2 ->\n ...> v1 + v2\n ...> end)\n ** (ArgumentError) expected a keyword list as the second argument, got: [:a, :b]\n\n \"\"\"\n @spec merge(t, t, (key, value, value -> value)) :: t\n def merge(keywords1, keywords2, fun)\n when is_list(keywords1) and is_list(keywords2) and is_function(fun, 3) do\n if keyword?(keywords1) do\n do_merge(keywords2, [], keywords1, keywords1, fun, keywords2)\n else\n raise ArgumentError,\n \"expected a keyword list as the first argument, got: #{inspect(keywords1)}\"\n end\n end\n\n defp do_merge([{key, value2} | tail], acc, rest, original, fun, keywords2) when is_atom(key) do\n case :lists.keyfind(key, 1, original) do\n {^key, value1} ->\n acc = [{key, fun.(key, value1, value2)} | acc]\n original = :lists.keydelete(key, 1, original)\n do_merge(tail, acc, delete(rest, key), original, fun, keywords2)\n\n false ->\n do_merge(tail, [{key, value2} | acc], rest, original, fun, keywords2)\n end\n end\n\n defp do_merge([], acc, rest, _original, _fun, _keywords2) do\n rest ++ :lists.reverse(acc)\n end\n\n defp do_merge(_other, _acc, _rest, _original, _fun, keywords2) do\n raise ArgumentError,\n \"expected a keyword list as the second argument, got: #{inspect(keywords2)}\"\n end\n\n @doc \"\"\"\n Returns whether a given `key` exists in the given `keywords`.\n\n ## Examples\n\n iex> Keyword.has_key?([a: 1], :a)\n true\n iex> Keyword.has_key?([a: 1], :b)\n false\n\n \"\"\"\n @spec has_key?(t, key) :: boolean\n def has_key?(keywords, key) when is_list(keywords) and is_atom(key) do\n :lists.keymember(key, 1, keywords)\n end\n\n @doc \"\"\"\n Updates the `key` with the given function.\n\n If the `key` does not exist, raises `KeyError`.\n\n If there are duplicated keys, they are all removed and only the first one\n is updated.\n\n ## Examples\n\n iex> Keyword.update!([a: 1, b: 2, a: 3], :a, &(&1 * 2))\n [a: 2, b: 2]\n iex> Keyword.update!([a: 1, b: 2, c: 3], :b, &(&1 * 2))\n [a: 1, b: 4, c: 3]\n\n iex> Keyword.update!([a: 1], :b, &(&1 * 2))\n ** (KeyError) key :b not found in: [a: 1]\n\n \"\"\"\n @spec update!(t, key, (value -> value)) :: t\n def update!(keywords, key, fun)\n when is_list(keywords) and is_atom(key) and is_function(fun, 1) do\n update!(keywords, key, fun, keywords)\n end\n\n defp update!([{key, value} | keywords], key, fun, _original) do\n [{key, fun.(value)} | delete(keywords, key)]\n end\n\n defp update!([{_, _} = e | keywords], key, fun, original) do\n [e | update!(keywords, key, fun, original)]\n end\n\n defp update!([], key, _fun, original) when is_atom(key) do\n raise(KeyError, key: key, term: original)\n end\n\n @doc \"\"\"\n Updates the `key` in `keywords` with the given function.\n\n If the `key` does not exist, inserts the given `initial` value.\n\n If there are duplicated keys, they are all removed and only the first one\n is updated.\n\n ## Examples\n\n iex> Keyword.update([a: 1], :a, 13, &(&1 * 2))\n [a: 2]\n iex> Keyword.update([a: 1, a: 2], :a, 13, &(&1 * 2))\n [a: 2]\n iex> Keyword.update([a: 1], :b, 11, &(&1 * 2))\n [a: 1, b: 11]\n\n \"\"\"\n @spec update(t, key, value, (value -> value)) :: t\n def update(keywords, key, initial, fun)\n\n def update([{key, value} | keywords], key, _initial, fun) do\n [{key, fun.(value)} | delete(keywords, key)]\n end\n\n def update([{_, _} = e | keywords], key, initial, fun) do\n [e | update(keywords, key, initial, fun)]\n end\n\n def update([], key, initial, _fun) when is_atom(key) do\n [{key, initial}]\n end\n\n @doc \"\"\"\n Takes all entries corresponding to the given keys and extracts them into a\n separate keyword list.\n\n Returns a tuple with the new list and the old list with removed keys.\n\n Keys for which there are no entries in the keyword list are ignored.\n\n Entries with duplicated keys end up in the same keyword list.\n\n ## Examples\n\n iex> Keyword.split([a: 1, b: 2, c: 3], [:a, :c, :e])\n {[a: 1, c: 3], [b: 2]}\n iex> Keyword.split([a: 1, b: 2, c: 3, a: 4], [:a, :c, :e])\n {[a: 1, c: 3, a: 4], [b: 2]}\n\n \"\"\"\n @spec split(t, [key]) :: {t, t}\n def split(keywords, keys) when is_list(keywords) and is_list(keys) do\n fun = fn {k, v}, {take, drop} ->\n case k in keys do\n true -> {[{k, v} | take], drop}\n false -> {take, [{k, v} | drop]}\n end\n end\n\n acc = {[], []}\n {take, drop} = :lists.foldl(fun, acc, keywords)\n {:lists.reverse(take), :lists.reverse(drop)}\n end\n\n @doc \"\"\"\n Takes all entries corresponding to the given keys and returns them in a new\n keyword list.\n\n Duplicated keys are preserved in the new keyword list.\n\n ## Examples\n\n iex> Keyword.take([a: 1, b: 2, c: 3], [:a, :c, :e])\n [a: 1, c: 3]\n iex> Keyword.take([a: 1, b: 2, c: 3, a: 5], [:a, :c, :e])\n [a: 1, c: 3, a: 5]\n\n \"\"\"\n @spec take(t, [key]) :: t\n def take(keywords, keys) when is_list(keywords) and is_list(keys) do\n :lists.filter(fn {k, _} -> k in keys end, keywords)\n end\n\n @doc \"\"\"\n Drops the given keys from the keyword list.\n\n Duplicated keys are preserved in the new keyword list.\n\n ## Examples\n\n iex> Keyword.drop([a: 1, b: 2, c: 3], [:b, :d])\n [a: 1, c: 3]\n iex> Keyword.drop([a: 1, b: 2, b: 3, c: 3, a: 5], [:b, :d])\n [a: 1, c: 3, a: 5]\n\n \"\"\"\n @spec drop(t, [key]) :: t\n def drop(keywords, keys) when is_list(keywords) and is_list(keys) do\n :lists.filter(fn {key, _} -> key not in keys end, keywords)\n end\n\n @doc \"\"\"\n Returns the first value for `key` and removes all associated entries in the keyword list.\n\n It returns a tuple where the first element is the first value for `key` and the\n second element is a keyword list with all entries associated with `key` removed.\n If the `key` is not present in the keyword list, `{default, keyword_list}` is\n returned.\n\n If you don't want to remove all the entries associated with `key` use `pop_first\/3`\n instead, that function will remove only the first entry.\n\n ## Examples\n\n iex> Keyword.pop([a: 1], :a)\n {1, []}\n iex> Keyword.pop([a: 1], :b)\n {nil, [a: 1]}\n iex> Keyword.pop([a: 1], :b, 3)\n {3, [a: 1]}\n iex> Keyword.pop([a: 1, a: 2], :a)\n {1, []}\n\n \"\"\"\n @spec pop(t, key, value) :: {value, t}\n def pop(keywords, key, default \\\\ nil) when is_list(keywords) and is_atom(key) do\n case fetch(keywords, key) do\n {:ok, value} -> {value, delete(keywords, key)}\n :error -> {default, keywords}\n end\n end\n\n @doc \"\"\"\n Returns the first value for `key` and removes all associated antries in the keyword list,\n raising if `key` is not present.\n\n This function behaves like `pop\/3`, but raises in cases the `key` is not present in the\n given `keywords`.\n\n ## Examples\n\n iex> Keyword.pop!([a: 1], :a)\n {1, []}\n iex> Keyword.pop!([a: 1, a: 2], :a)\n {1, []}\n iex> Keyword.pop!([a: 1], :b)\n ** (KeyError) key :b not found in: [a: 1]\n\n \"\"\"\n @doc since: \"1.10.0\"\n @spec pop!(t, key) :: {value, t}\n def pop!(keywords, key) when is_list(keywords) and is_atom(key) do\n case fetch(keywords, key) do\n {:ok, value} -> {value, delete(keywords, key)}\n :error -> raise KeyError, key: key, term: keywords\n end\n end\n\n @doc \"\"\"\n Returns all values for `key` and removes all associated entries in the keyword list.\n\n It returns a tuple where the first element is a list of values for `key` and the\n second element is a keyword list with all entries associated with `key` removed.\n If the `key` is not present in the keyword list, `{[], keyword_list}` is\n returned.\n\n If you don't want to remove all the entries associated with `key` use `pop_first\/3`\n instead, that function will remove only the first entry.\n\n ## Examples\n\n iex> Keyword.pop_values([a: 1], :a)\n {[1], []}\n iex> Keyword.pop_values([a: 1], :b)\n {[], [a: 1]}\n iex> Keyword.pop_values([a: 1, a: 2], :a)\n {[1, 2], []}\n\n \"\"\"\n @doc since: \"1.10.0\"\n @spec pop_values(t, key) :: {[value], t}\n def pop_values(keywords, key) when is_list(keywords) and is_atom(key) do\n pop_values(:lists.reverse(keywords), key, [], [])\n end\n\n defp pop_values([{key, value} | tail], key, values, acc),\n do: pop_values(tail, key, [value | values], acc)\n\n defp pop_values([{_, _} = pair | tail], key, values, acc),\n do: pop_values(tail, key, values, [pair | acc])\n\n defp pop_values([], _key, values, acc),\n do: {values, acc}\n\n @doc \"\"\"\n Lazily returns and removes all values associated with `key` in the keyword list.\n\n This is useful if the default value is very expensive to calculate or\n generally difficult to setup and teardown again.\n\n All duplicated keys are removed. See `pop_first\/3` for\n removing only the first entry.\n\n ## Examples\n\n iex> keyword = [a: 1]\n iex> fun = fn ->\n ...> # some expensive operation here\n ...> 13\n ...> end\n iex> Keyword.pop_lazy(keyword, :a, fun)\n {1, []}\n iex> Keyword.pop_lazy(keyword, :b, fun)\n {13, [a: 1]}\n\n \"\"\"\n @spec pop_lazy(t, key, (() -> value)) :: {value, t}\n def pop_lazy(keywords, key, fun)\n when is_list(keywords) and is_atom(key) and is_function(fun, 0) do\n case fetch(keywords, key) do\n {:ok, value} ->\n {value, delete(keywords, key)}\n\n :error ->\n {fun.(), keywords}\n end\n end\n\n @doc \"\"\"\n Returns and removes the first value associated with `key` in the keyword list.\n\n Duplicated keys are not removed.\n\n ## Examples\n\n iex> Keyword.pop_first([a: 1], :a)\n {1, []}\n iex> Keyword.pop_first([a: 1], :b)\n {nil, [a: 1]}\n iex> Keyword.pop_first([a: 1], :b, 3)\n {3, [a: 1]}\n iex> Keyword.pop_first([a: 1, a: 2], :a)\n {1, [a: 2]}\n\n \"\"\"\n @spec pop_first(t, key, value) :: {value, t}\n def pop_first(keywords, key, default \\\\ nil) when is_list(keywords) and is_atom(key) do\n case :lists.keytake(key, 1, keywords) do\n {:value, {^key, value}, rest} -> {value, rest}\n false -> {default, keywords}\n end\n end\n\n @doc \"\"\"\n Returns the keyword list itself.\n\n ## Examples\n\n iex> Keyword.to_list(a: 1)\n [a: 1]\n\n \"\"\"\n @spec to_list(t) :: t\n def to_list(keyword) when is_list(keyword) do\n keyword\n end\n\n @doc false\n @deprecated \"Use Kernel.length\/1 instead\"\n def size(keyword) do\n length(keyword)\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"241aa62ffa7d8da1f3fc0c40851c29ad7723305c","subject":"Add `@spec` for `Keyword.pop\/3` and `Keyword.pop_first\/3`","message":"Add `@spec` for `Keyword.pop\/3` and `Keyword.pop_first\/3`\n","repos":"lexmag\/elixir,beedub\/elixir,beedub\/elixir,antipax\/elixir,kimshrier\/elixir,ggcampinho\/elixir,gfvcastro\/elixir,pedrosnk\/elixir,lexmag\/elixir,ggcampinho\/elixir,kimshrier\/elixir,kelvinst\/elixir,kelvinst\/elixir,gfvcastro\/elixir,pedrosnk\/elixir,elixir-lang\/elixir,michalmuskala\/elixir,joshprice\/elixir,antipax\/elixir","old_file":"lib\/elixir\/lib\/keyword.ex","new_file":"lib\/elixir\/lib\/keyword.ex","new_contents":"defmodule Keyword do\n @moduledoc \"\"\"\n A keyword is a list of tuples where the first element\n of the tuple is an atom and the second element can be\n any value.\n\n A keyword may have duplicated keys so it is not strictly\n a dictionary. However most of the functions in this module\n behave exactly as a dictionary and mimic the API defined\n by the `Dict` behaviour.\n\n For example, `Keyword.get\/3` will get the first entry matching\n the given key, regardless if duplicated entries exist.\n Similarly, `Keyword.put\/3` and `Keyword.delete\/3` ensure all\n duplicated entries for a given key are removed when invoked.\n\n A handful of functions exist to handle duplicated keys, in\n particular, `Enum.into\/2` allows creating new keywords without\n removing duplicated keys, `get_values\/2` returns all values for\n a given key and `delete_first\/2` deletes just one of the existing\n entries.\n\n The functions in Keyword do not guarantee any property when\n it comes to ordering. However, since a keyword list is simply a\n list, all the operations defined in `Enum` and `List` can be\n applied too, specially when ordering is required.\n \"\"\"\n\n @compile :inline_list_funcs\n @behaviour Dict\n\n @type key :: atom\n @type value :: any\n\n @type t :: [{key, value}]\n @type t(value) :: [{key, value}]\n\n @doc \"\"\"\n Checks if the given argument is a keyword list or not.\n \"\"\"\n @spec keyword?(term) :: boolean\n def keyword?([{key, _value} | rest]) when is_atom(key) do\n keyword?(rest)\n end\n\n def keyword?([]), do: true\n def keyword?(_other), do: false\n\n @doc \"\"\"\n Returns an empty keyword list, i.e. an empty list.\n \"\"\"\n @spec new :: t\n def new do\n []\n end\n\n @doc \"\"\"\n Creates a keyword from an enumerable.\n\n Duplicated entries are removed, the latest one prevails.\n Unlike `Enum.into(enumerable, [])`,\n `Keyword.new(enumerable)` guarantees the keys are unique.\n\n ## Examples\n\n iex> Keyword.new([{:b, 1}, {:a, 2}])\n [a: 2, b: 1]\n\n \"\"\"\n @spec new(Enum.t) :: t\n def new(pairs) do\n Enum.reduce pairs, [], fn {k, v}, keywords ->\n put(keywords, k, v)\n end\n end\n\n @doc \"\"\"\n Creates a keyword from an enumerable via the transformation function.\n\n Duplicated entries are removed, the latest one prevails.\n Unlike `Enum.into(enumerable, [], fun)`,\n `Keyword.new(enumerable, fun)` guarantees the keys are unique.\n\n ## Examples\n\n iex> Keyword.new([:a, :b], fn (x) -> {x, x} end) |> Enum.sort\n [a: :a, b: :b]\n\n \"\"\"\n @spec new(Enum.t, ({key, value} -> {key, value})) :: t\n def new(pairs, transform) do\n Enum.reduce pairs, [], fn i, keywords ->\n {k, v} = transform.(i)\n put(keywords, k, v)\n end\n end\n\n @doc \"\"\"\n Gets the value for a specific `key`.\n\n If `key` does not exist, return the default value (`nil` if no default value).\n\n If duplicated entries exist, the first one is returned.\n Use `get_values\/2` to retrieve all entries.\n\n ## Examples\n\n iex> Keyword.get([a: 1], :a)\n 1\n\n iex> Keyword.get([a: 1], :b)\n nil\n\n iex> Keyword.get([a: 1], :b, 3)\n 3\n\n \"\"\"\n @spec get(t, key) :: value\n @spec get(t, key, value) :: value\n def get(keywords, key, default \\\\ nil) when is_list(keywords) and is_atom(key) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, value} -> value\n false -> default\n end\n end\n\n @doc \"\"\"\n Gets the value for a specific `key`.\n\n If `key` does not exist, lazily evaluates `fun` and returns its result.\n\n This is useful if the default value is very expensive to calculate or\n generally difficult to set-up and tear-down again.\n\n If duplicated entries exist, the first one is returned.\n Use `get_values\/2` to retrieve all entries.\n\n ## Examples\n\n iex> keyword = [a: 1]\n iex> fun = fn ->\n ...> # some expensive operation here\n ...> :result\n ...> end\n iex> Keyword.get_lazy(keyword, :a, fun)\n 1\n iex> Keyword.get_lazy(keyword, :b, fun)\n :result\n\n \"\"\"\n @spec get_lazy(t, key, (() -> value)) :: value\n def get_lazy(keywords, key, fun)\n when is_list(keywords) and is_atom(key) and is_function(fun, 0) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, value} -> value\n false -> fun.()\n end\n end\n\n @doc \"\"\"\n Gets the value from `key` and updates it, all in one pass.\n\n This `fun` argument receives the value of `key` (or `nil` if `key`\n is not present) and must return a two-elements tuple: the \"get\" value (the\n retrieved value, which can be operated on before being returned) and the new\n value to be stored under `key`.\n\n The returned value is a tuple with the \"get\" value returned by `fun` and a new\n keyword list with the updated value under `key`.\n\n ## Examples\n\n iex> Keyword.get_and_update [a: 1], :a, fn(current_value) ->\n ...> {current_value, \"new value!\"}\n ...> end\n {1, [a: \"new value!\"]}\n\n \"\"\"\n @spec get_and_update(t, key, (value -> {value, value})) :: {value, t}\n def get_and_update(keywords, key, fun)\n when is_list(keywords) and is_atom(key),\n do: get_and_update(keywords, [], key, fun)\n\n defp get_and_update([{key, value}|t], acc, key, fun) do\n {get, new_value} = fun.(value)\n {get, :lists.reverse(acc, [{key, new_value}|t])}\n end\n\n defp get_and_update([h|t], acc, key, fun) do\n get_and_update(t, [h|acc], key, fun)\n end\n\n defp get_and_update([], acc, key, fun) do\n {get, update} = fun.(nil)\n {get, [{key, update}|List.reverse(acc)]}\n end\n\n @doc \"\"\"\n Fetches the value for a specific `key` and returns it in a tuple.\n\n If the `key` does not exist, returns `:error`.\n\n ## Examples\n\n iex> Keyword.fetch([a: 1], :a)\n {:ok, 1}\n\n iex> Keyword.fetch([a: 1], :b)\n :error\n\n \"\"\"\n @spec fetch(t, key) :: {:ok, value} | :error\n def fetch(keywords, key) when is_list(keywords) and is_atom(key) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, value} -> {:ok, value}\n false -> :error\n end\n end\n\n @doc \"\"\"\n Fetches the value for specific `key`.\n\n If `key` does not exist, a `KeyError` is raised.\n\n ## Examples\n\n iex> Keyword.fetch!([a: 1], :a)\n 1\n\n iex> Keyword.fetch!([a: 1], :b)\n ** (KeyError) key :b not found in: [a: 1]\n\n \"\"\"\n @spec fetch!(t, key) :: value | no_return\n def fetch!(keywords, key) when is_list(keywords) and is_atom(key) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, value} -> value\n false -> raise(KeyError, key: key, term: keywords)\n end\n end\n\n @doc \"\"\"\n Gets all values for a specific `key`.\n\n ## Examples\n\n iex> Keyword.get_values([a: 1, a: 2], :a)\n [1,2]\n\n \"\"\"\n @spec get_values(t, key) :: [value]\n def get_values(keywords, key) when is_list(keywords) and is_atom(key) do\n fun = fn\n {k, v} when k === key -> {true, v}\n {_, _} -> false\n end\n\n :lists.filtermap(fun, keywords)\n end\n\n @doc \"\"\"\n Returns all keys from the keyword list.\n\n Duplicated keys appear duplicated in the final list of keys.\n\n ## Examples\n\n iex> Keyword.keys([a: 1, b: 2])\n [:a,:b]\n\n iex> Keyword.keys([a: 1, b: 2, a: 3])\n [:a,:b,:a]\n\n \"\"\"\n @spec keys(t) :: [key]\n def keys(keywords) when is_list(keywords) do\n :lists.map(fn {k, _} -> k end, keywords)\n end\n\n @doc \"\"\"\n Returns all values from the keyword list.\n\n ## Examples\n\n iex> Keyword.values([a: 1, b: 2])\n [1,2]\n\n \"\"\"\n @spec values(t) :: [value]\n def values(keywords) when is_list(keywords) do\n :lists.map(fn {_, v} -> v end, keywords)\n end\n\n @doc \"\"\"\n Deletes the entries in the keyword list for a `key` with `value`.\n\n If no `key` with `value` exists, returns the keyword list unchanged.\n\n ## Examples\n\n iex> Keyword.delete([a: 1, b: 2], :a, 1)\n [b: 2]\n\n iex> Keyword.delete([a: 1, b: 2, a: 3], :a, 3)\n [a: 1, b: 2]\n\n iex> Keyword.delete([b: 2], :a, 5)\n [b: 2]\n\n \"\"\"\n @spec delete(t, key, value) :: t\n def delete(keywords, key, value) when is_list(keywords) and is_atom(key) do\n :lists.filter(fn {k, v} -> k != key or v != value end, keywords)\n end\n\n @doc \"\"\"\n Deletes the entries in the keyword list for a specific `key`.\n\n If the `key` does not exist, returns the keyword list unchanged.\n Use `delete_first\/2` to delete just the first entry in case of\n duplicated keys.\n\n ## Examples\n\n iex> Keyword.delete([a: 1, b: 2], :a)\n [b: 2]\n\n iex> Keyword.delete([a: 1, b: 2, a: 3], :a)\n [b: 2]\n\n iex> Keyword.delete([b: 2], :a)\n [b: 2]\n\n \"\"\"\n @spec delete(t, key) :: t\n def delete(keywords, key) when is_list(keywords) and is_atom(key) do\n :lists.filter(fn {k, _} -> k != key end, keywords)\n end\n\n @doc \"\"\"\n Deletes the first entry in the keyword list for a specific `key`.\n\n If the `key` does not exist, returns the keyword list unchanged.\n\n ## Examples\n\n iex> Keyword.delete_first([a: 1, b: 2, a: 3], :a)\n [b: 2, a: 3]\n\n iex> Keyword.delete_first([b: 2], :a)\n [b: 2]\n\n \"\"\"\n @spec delete_first(t, key) :: t\n def delete_first(keywords, key) when is_list(keywords) and is_atom(key) do\n :lists.keydelete(key, 1, keywords)\n end\n\n @doc \"\"\"\n Puts the given `value` under `key`.\n\n If a previous value is already stored, all entries are\n removed and the value is overridden.\n\n ## Examples\n\n iex> Keyword.put([a: 1, b: 2], :a, 3)\n [a: 3, b: 2]\n\n iex> Keyword.put([a: 1, b: 2, a: 4], :a, 3)\n [a: 3, b: 2]\n\n \"\"\"\n @spec put(t, key, value) :: t\n def put(keywords, key, value) when is_list(keywords) and is_atom(key) do\n [{key, value}|delete(keywords, key)]\n end\n\n @doc \"\"\"\n Evaluates `fun` and puts the result under `key`\n in keyword list unless `key` is already present.\n\n This is useful if the value is very expensive to calculate or generally\n difficult to set-up and tear-down again.\n\n ## Examples\n\n iex> keyword = [a: 1]\n iex> fun = fn ->\n ...> # some expensive operation here\n ...> 3\n ...> end\n iex> Keyword.put_new_lazy(keyword, :a, fun)\n [a: 1]\n iex> Keyword.put_new_lazy(keyword, :b, fun)\n [b: 3, a: 1]\n\n \"\"\"\n @spec put_new_lazy(t, key, (() -> value)) :: t\n def put_new_lazy(keywords, key, fun)\n when is_list(keywords) and is_atom(key) and is_function(fun, 0) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, _} -> keywords\n false -> [{key, fun.()}|keywords]\n end\n end\n\n @doc \"\"\"\n Puts the given `value` under `key` unless the entry `key`\n already exists.\n\n ## Examples\n\n iex> Keyword.put_new([a: 1], :b, 2)\n [b: 2, a: 1]\n\n iex> Keyword.put_new([a: 1, b: 2], :a, 3)\n [a: 1, b: 2]\n\n \"\"\"\n @spec put_new(t, key, value) :: t\n def put_new(keywords, key, value) when is_list(keywords) and is_atom(key) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, _} -> keywords\n false -> [{key, value}|keywords]\n end\n end\n\n @doc \"\"\"\n Checks if two keywords are equal.\n\n Two keywords are considered to be equal if they contain\n the same keys and those keys contain the same values.\n\n ## Examples\n\n iex> Keyword.equal?([a: 1, b: 2], [b: 2, a: 1])\n true\n\n \"\"\"\n @spec equal?(t, t) :: boolean\n def equal?(left, right) when is_list(left) and is_list(right) do\n :lists.sort(left) == :lists.sort(right)\n end\n\n @doc \"\"\"\n Merges two keyword lists into one.\n\n If they have duplicated keys, the one given in the second argument wins.\n\n ## Examples\n\n iex> Keyword.merge([a: 1, b: 2], [a: 3, d: 4])\n [a: 3, d: 4, b: 2]\n\n \"\"\"\n @spec merge(t, t) :: t\n def merge(d1, d2) when is_list(d1) and is_list(d2) do\n fun = fn {k, _v} -> not has_key?(d2, k) end\n d2 ++ :lists.filter(fun, d1)\n end\n\n @doc \"\"\"\n Merges two keyword lists into one.\n\n If they have duplicated keys, the given function is invoked to solve conflicts.\n\n ## Examples\n\n iex> Keyword.merge([a: 1, b: 2], [a: 3, d: 4], fn (_k, v1, v2) ->\n ...> v1 + v2\n ...> end)\n [a: 4, b: 2, d: 4]\n\n \"\"\"\n @spec merge(t, t, (key, value, value -> value)) :: t\n def merge(d1, d2, fun) when is_list(d1) and is_list(d2) do\n do_merge(d2, d1, fun)\n end\n\n defp do_merge([{k, v2}|t], acc, fun) do\n do_merge t, update(acc, k, v2, fn(v1) -> fun.(k, v1, v2) end), fun\n end\n\n defp do_merge([], acc, _fun) do\n acc\n end\n\n @doc \"\"\"\n Returns whether a given `key` exists in the given `keywords`.\n\n ## Examples\n\n iex> Keyword.has_key?([a: 1], :a)\n true\n\n iex> Keyword.has_key?([a: 1], :b)\n false\n\n \"\"\"\n @spec has_key?(t, key) :: boolean\n def has_key?(keywords, key) when is_list(keywords) and is_atom(key) do\n :lists.keymember(key, 1, keywords)\n end\n\n @doc \"\"\"\n Updates the `key` with the given function.\n\n If the `key` does not exist, raises `KeyError`.\n\n If there are duplicated keys, they are all removed and only the first one\n is updated.\n\n ## Examples\n\n iex> Keyword.update!([a: 1], :a, &(&1 * 2))\n [a: 2]\n\n iex> Keyword.update!([a: 1], :b, &(&1 * 2))\n ** (KeyError) key :b not found in: [a: 1]\n\n \"\"\"\n @spec update!(t, key, (value -> value)) :: t | no_return\n def update!(keywords, key, fun) do\n update!(keywords, key, fun, keywords)\n end\n\n defp update!([{key, value}|keywords], key, fun, _dict) do\n [{key, fun.(value)}|delete(keywords, key)]\n end\n\n defp update!([{_, _} = e|keywords], key, fun, dict) do\n [e|update!(keywords, key, fun, dict)]\n end\n\n defp update!([], key, _fun, dict) when is_atom(key) do\n raise(KeyError, key: key, term: dict)\n end\n\n @doc \"\"\"\n Updates the `key` with the given function.\n\n If the `key` does not exist, inserts the given `initial` value.\n\n If there are duplicated keys, they are all removed and only the first one\n is updated.\n\n ## Examples\n\n iex> Keyword.update([a: 1], :a, 13, &(&1 * 2))\n [a: 2]\n\n iex> Keyword.update([a: 1], :b, 11, &(&1 * 2))\n [a: 1, b: 11]\n\n \"\"\"\n @spec update(t, key, value, (value -> value)) :: t\n def update([{key, value}|keywords], key, _initial, fun) do\n [{key, fun.(value)}|delete(keywords, key)]\n end\n\n def update([{_, _} = e|keywords], key, initial, fun) do\n [e|update(keywords, key, initial, fun)]\n end\n\n def update([], key, initial, _fun) when is_atom(key) do\n [{key, initial}]\n end\n\n @doc \"\"\"\n Takes all entries corresponding to the given keys and extracts them into a\n separate keyword list.\n\n Returns a tuple with the new list and the old list with removed keys.\n\n Keys for which there are no entires in the keyword list are ignored.\n\n Entries with duplicated keys end up in the same keyword list.\n\n ## Examples\n\n iex> d = [a: 1, b: 2, c: 3, d: 4]\n iex> Keyword.split(d, [:a, :c, :e])\n {[a: 1, c: 3], [b: 2, d: 4]}\n\n iex> d = [a: 1, b: 2, c: 3, d: 4, a: 5]\n iex> Keyword.split(d, [:a, :c, :e])\n {[a: 1, c: 3, a: 5], [b: 2, d: 4]}\n\n \"\"\"\n def split(keywords, keys) when is_list(keywords) do\n fun = fn {k, v}, {take, drop} ->\n case k in keys do\n true -> {[{k, v}|take], drop}\n false -> {take, [{k, v}|drop]}\n end\n end\n\n acc = {[], []}\n {take, drop} = :lists.foldl(fun, acc, keywords)\n {:lists.reverse(take), :lists.reverse(drop)}\n end\n\n @doc \"\"\"\n Takes all entries corresponding to the given keys and returns them in a new\n keyword list.\n\n Duplicated keys are preserved in the new keyword list.\n\n ## Examples\n\n iex> d = [a: 1, b: 2, c: 3, d: 4]\n iex> Keyword.take(d, [:a, :c, :e])\n [a: 1, c: 3]\n\n iex> d = [a: 1, b: 2, c: 3, d: 4, a: 5]\n iex> Keyword.take(d, [:a, :c, :e])\n [a: 1, c: 3, a: 5]\n\n \"\"\"\n def take(keywords, keys) when is_list(keywords) do\n :lists.filter(fn {k, _} -> k in keys end, keywords)\n end\n\n @doc \"\"\"\n Drops the given keys from the keyword list.\n\n Duplicated keys are preserved in the new keyword list.\n\n ## Examples\n\n iex> d = [a: 1, b: 2, c: 3, d: 4]\n iex> Keyword.drop(d, [:b, :d])\n [a: 1, c: 3]\n\n iex> d = [a: 1, b: 2, b: 3, c: 3, d: 4, a: 5]\n iex> Keyword.drop(d, [:b, :d])\n [a: 1, c: 3, a: 5]\n\n \"\"\"\n def drop(keywords, keys) when is_list(keywords) do\n :lists.filter(fn {k, _} -> not k in keys end, keywords)\n end\n\n @doc \"\"\"\n Returns the first value associated with `key` in the keyword\n list as well as the keyword list without `key`.\n\n All duplicated keys are removed. See `pop_first\/3` for\n removing only the first entry.\n\n ## Examples\n\n iex> Keyword.pop [a: 1], :a\n {1,[]}\n\n iex> Keyword.pop [a: 1], :b\n {nil,[a: 1]}\n\n iex> Keyword.pop [a: 1], :b, 3\n {3,[a: 1]}\n\n iex> Keyword.pop [a: 1], :b, 3\n {3,[a: 1]}\n\n iex> Keyword.pop [a: 1, a: 2], :a\n {1,[]}\n\n \"\"\"\n @spec pop(t, key, value) :: {value, t}\n def pop(keywords, key, default \\\\ nil) when is_list(keywords) do\n {get(keywords, key, default), delete(keywords, key)}\n end\n\n @doc \"\"\"\n Returns the first value associated with `key` in the keyword\n list as well as the keyword list without `key`.\n\n This is useful if the default value is very expensive to calculate or\n generally difficult to set-up and tear-down again.\n\n All duplicated keys are removed. See `pop_first\/3` for\n removing only the first entry.\n\n ## Examples\n\n iex> keyword = [a: 1]\n iex> fun = fn ->\n ...> # some expensive operation here\n ...> :result\n ...> end\n iex> Keyword.pop_lazy(keyword, :a, fun)\n {1,[]}\n iex> Keyword.pop_lazy(keyword, :b, fun)\n {:result,[a: 1]}\n\n \"\"\"\n @spec pop_lazy(t, key, (() -> value)) :: {value, t}\n def pop_lazy(keywords, key, fun) when is_list(keywords) do\n {get_lazy(keywords, key, fun), delete(keywords, key)}\n end\n\n @doc \"\"\"\n Returns the first value associated with `key` in the keyword\n list as well as the keyword list without that particular occurrence\n of `key`.\n\n Duplicated keys are not removed.\n\n ## Examples\n\n iex> Keyword.pop_first [a: 1], :a\n {1,[]}\n\n iex> Keyword.pop_first [a: 1], :b\n {nil,[a: 1]}\n\n iex> Keyword.pop_first [a: 1], :b, 3\n {3,[a: 1]}\n\n iex> Keyword.pop_first [a: 1], :b, 3\n {3,[a: 1]}\n\n iex> Keyword.pop_first [a: 1, a: 2], :a\n {1,[a: 2]}\n\n \"\"\"\n @spec pop_first(t, key, value) :: {value, t}\n def pop_first(keywords, key, default \\\\ nil) when is_list(keywords) do\n {get(keywords, key, default), delete_first(keywords, key)}\n end\n\n # Dict callbacks\n\n @doc false\n def size(keyword) do\n length(keyword)\n end\n\n @doc false\n def to_list(keyword) do\n keyword\n end\nend\n","old_contents":"defmodule Keyword do\n @moduledoc \"\"\"\n A keyword is a list of tuples where the first element\n of the tuple is an atom and the second element can be\n any value.\n\n A keyword may have duplicated keys so it is not strictly\n a dictionary. However most of the functions in this module\n behave exactly as a dictionary and mimic the API defined\n by the `Dict` behaviour.\n\n For example, `Keyword.get\/3` will get the first entry matching\n the given key, regardless if duplicated entries exist.\n Similarly, `Keyword.put\/3` and `Keyword.delete\/3` ensure all\n duplicated entries for a given key are removed when invoked.\n\n A handful of functions exist to handle duplicated keys, in\n particular, `Enum.into\/2` allows creating new keywords without\n removing duplicated keys, `get_values\/2` returns all values for\n a given key and `delete_first\/2` deletes just one of the existing\n entries.\n\n The functions in Keyword do not guarantee any property when\n it comes to ordering. However, since a keyword list is simply a\n list, all the operations defined in `Enum` and `List` can be\n applied too, specially when ordering is required.\n \"\"\"\n\n @compile :inline_list_funcs\n @behaviour Dict\n\n @type key :: atom\n @type value :: any\n\n @type t :: [{key, value}]\n @type t(value) :: [{key, value}]\n\n @doc \"\"\"\n Checks if the given argument is a keyword list or not.\n \"\"\"\n @spec keyword?(term) :: boolean\n def keyword?([{key, _value} | rest]) when is_atom(key) do\n keyword?(rest)\n end\n\n def keyword?([]), do: true\n def keyword?(_other), do: false\n\n @doc \"\"\"\n Returns an empty keyword list, i.e. an empty list.\n \"\"\"\n @spec new :: t\n def new do\n []\n end\n\n @doc \"\"\"\n Creates a keyword from an enumerable.\n\n Duplicated entries are removed, the latest one prevails.\n Unlike `Enum.into(enumerable, [])`,\n `Keyword.new(enumerable)` guarantees the keys are unique.\n\n ## Examples\n\n iex> Keyword.new([{:b, 1}, {:a, 2}])\n [a: 2, b: 1]\n\n \"\"\"\n @spec new(Enum.t) :: t\n def new(pairs) do\n Enum.reduce pairs, [], fn {k, v}, keywords ->\n put(keywords, k, v)\n end\n end\n\n @doc \"\"\"\n Creates a keyword from an enumerable via the transformation function.\n\n Duplicated entries are removed, the latest one prevails.\n Unlike `Enum.into(enumerable, [], fun)`,\n `Keyword.new(enumerable, fun)` guarantees the keys are unique.\n\n ## Examples\n\n iex> Keyword.new([:a, :b], fn (x) -> {x, x} end) |> Enum.sort\n [a: :a, b: :b]\n\n \"\"\"\n @spec new(Enum.t, ({key, value} -> {key, value})) :: t\n def new(pairs, transform) do\n Enum.reduce pairs, [], fn i, keywords ->\n {k, v} = transform.(i)\n put(keywords, k, v)\n end\n end\n\n @doc \"\"\"\n Gets the value for a specific `key`.\n\n If `key` does not exist, return the default value (`nil` if no default value).\n\n If duplicated entries exist, the first one is returned.\n Use `get_values\/2` to retrieve all entries.\n\n ## Examples\n\n iex> Keyword.get([a: 1], :a)\n 1\n\n iex> Keyword.get([a: 1], :b)\n nil\n\n iex> Keyword.get([a: 1], :b, 3)\n 3\n\n \"\"\"\n @spec get(t, key) :: value\n @spec get(t, key, value) :: value\n def get(keywords, key, default \\\\ nil) when is_list(keywords) and is_atom(key) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, value} -> value\n false -> default\n end\n end\n\n @doc \"\"\"\n Gets the value for a specific `key`.\n\n If `key` does not exist, lazily evaluates `fun` and returns its result.\n\n This is useful if the default value is very expensive to calculate or\n generally difficult to set-up and tear-down again.\n\n If duplicated entries exist, the first one is returned.\n Use `get_values\/2` to retrieve all entries.\n\n ## Examples\n\n iex> keyword = [a: 1]\n iex> fun = fn ->\n ...> # some expensive operation here\n ...> :result\n ...> end\n iex> Keyword.get_lazy(keyword, :a, fun)\n 1\n iex> Keyword.get_lazy(keyword, :b, fun)\n :result\n\n \"\"\"\n @spec get_lazy(t, key, (() -> value)) :: value\n def get_lazy(keywords, key, fun)\n when is_list(keywords) and is_atom(key) and is_function(fun, 0) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, value} -> value\n false -> fun.()\n end\n end\n\n @doc \"\"\"\n Gets the value from `key` and updates it, all in one pass.\n\n This `fun` argument receives the value of `key` (or `nil` if `key`\n is not present) and must return a two-elements tuple: the \"get\" value (the\n retrieved value, which can be operated on before being returned) and the new\n value to be stored under `key`.\n\n The returned value is a tuple with the \"get\" value returned by `fun` and a new\n keyword list with the updated value under `key`.\n\n ## Examples\n\n iex> Keyword.get_and_update [a: 1], :a, fn(current_value) ->\n ...> {current_value, \"new value!\"}\n ...> end\n {1, [a: \"new value!\"]}\n\n \"\"\"\n @spec get_and_update(t, key, (value -> {value, value})) :: {value, t}\n def get_and_update(keywords, key, fun)\n when is_list(keywords) and is_atom(key),\n do: get_and_update(keywords, [], key, fun)\n\n defp get_and_update([{key, value}|t], acc, key, fun) do\n {get, new_value} = fun.(value)\n {get, :lists.reverse(acc, [{key, new_value}|t])}\n end\n\n defp get_and_update([h|t], acc, key, fun) do\n get_and_update(t, [h|acc], key, fun)\n end\n\n defp get_and_update([], acc, key, fun) do\n {get, update} = fun.(nil)\n {get, [{key, update}|List.reverse(acc)]}\n end\n\n @doc \"\"\"\n Fetches the value for a specific `key` and returns it in a tuple.\n\n If the `key` does not exist, returns `:error`.\n\n ## Examples\n\n iex> Keyword.fetch([a: 1], :a)\n {:ok, 1}\n\n iex> Keyword.fetch([a: 1], :b)\n :error\n\n \"\"\"\n @spec fetch(t, key) :: {:ok, value} | :error\n def fetch(keywords, key) when is_list(keywords) and is_atom(key) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, value} -> {:ok, value}\n false -> :error\n end\n end\n\n @doc \"\"\"\n Fetches the value for specific `key`.\n\n If `key` does not exist, a `KeyError` is raised.\n\n ## Examples\n\n iex> Keyword.fetch!([a: 1], :a)\n 1\n\n iex> Keyword.fetch!([a: 1], :b)\n ** (KeyError) key :b not found in: [a: 1]\n\n \"\"\"\n @spec fetch!(t, key) :: value | no_return\n def fetch!(keywords, key) when is_list(keywords) and is_atom(key) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, value} -> value\n false -> raise(KeyError, key: key, term: keywords)\n end\n end\n\n @doc \"\"\"\n Gets all values for a specific `key`.\n\n ## Examples\n\n iex> Keyword.get_values([a: 1, a: 2], :a)\n [1,2]\n\n \"\"\"\n @spec get_values(t, key) :: [value]\n def get_values(keywords, key) when is_list(keywords) and is_atom(key) do\n fun = fn\n {k, v} when k === key -> {true, v}\n {_, _} -> false\n end\n\n :lists.filtermap(fun, keywords)\n end\n\n @doc \"\"\"\n Returns all keys from the keyword list.\n\n Duplicated keys appear duplicated in the final list of keys.\n\n ## Examples\n\n iex> Keyword.keys([a: 1, b: 2])\n [:a,:b]\n\n iex> Keyword.keys([a: 1, b: 2, a: 3])\n [:a,:b,:a]\n\n \"\"\"\n @spec keys(t) :: [key]\n def keys(keywords) when is_list(keywords) do\n :lists.map(fn {k, _} -> k end, keywords)\n end\n\n @doc \"\"\"\n Returns all values from the keyword list.\n\n ## Examples\n\n iex> Keyword.values([a: 1, b: 2])\n [1,2]\n\n \"\"\"\n @spec values(t) :: [value]\n def values(keywords) when is_list(keywords) do\n :lists.map(fn {_, v} -> v end, keywords)\n end\n\n @doc \"\"\"\n Deletes the entries in the keyword list for a `key` with `value`.\n\n If no `key` with `value` exists, returns the keyword list unchanged.\n\n ## Examples\n\n iex> Keyword.delete([a: 1, b: 2], :a, 1)\n [b: 2]\n\n iex> Keyword.delete([a: 1, b: 2, a: 3], :a, 3)\n [a: 1, b: 2]\n\n iex> Keyword.delete([b: 2], :a, 5)\n [b: 2]\n\n \"\"\"\n @spec delete(t, key, value) :: t\n def delete(keywords, key, value) when is_list(keywords) and is_atom(key) do\n :lists.filter(fn {k, v} -> k != key or v != value end, keywords)\n end\n\n @doc \"\"\"\n Deletes the entries in the keyword list for a specific `key`.\n\n If the `key` does not exist, returns the keyword list unchanged.\n Use `delete_first\/2` to delete just the first entry in case of\n duplicated keys.\n\n ## Examples\n\n iex> Keyword.delete([a: 1, b: 2], :a)\n [b: 2]\n\n iex> Keyword.delete([a: 1, b: 2, a: 3], :a)\n [b: 2]\n\n iex> Keyword.delete([b: 2], :a)\n [b: 2]\n\n \"\"\"\n @spec delete(t, key) :: t\n def delete(keywords, key) when is_list(keywords) and is_atom(key) do\n :lists.filter(fn {k, _} -> k != key end, keywords)\n end\n\n @doc \"\"\"\n Deletes the first entry in the keyword list for a specific `key`.\n\n If the `key` does not exist, returns the keyword list unchanged.\n\n ## Examples\n\n iex> Keyword.delete_first([a: 1, b: 2, a: 3], :a)\n [b: 2, a: 3]\n\n iex> Keyword.delete_first([b: 2], :a)\n [b: 2]\n\n \"\"\"\n @spec delete_first(t, key) :: t\n def delete_first(keywords, key) when is_list(keywords) and is_atom(key) do\n :lists.keydelete(key, 1, keywords)\n end\n\n @doc \"\"\"\n Puts the given `value` under `key`.\n\n If a previous value is already stored, all entries are\n removed and the value is overridden.\n\n ## Examples\n\n iex> Keyword.put([a: 1, b: 2], :a, 3)\n [a: 3, b: 2]\n\n iex> Keyword.put([a: 1, b: 2, a: 4], :a, 3)\n [a: 3, b: 2]\n\n \"\"\"\n @spec put(t, key, value) :: t\n def put(keywords, key, value) when is_list(keywords) and is_atom(key) do\n [{key, value}|delete(keywords, key)]\n end\n\n @doc \"\"\"\n Evaluates `fun` and puts the result under `key`\n in keyword list unless `key` is already present.\n\n This is useful if the value is very expensive to calculate or generally\n difficult to set-up and tear-down again.\n\n ## Examples\n\n iex> keyword = [a: 1]\n iex> fun = fn ->\n ...> # some expensive operation here\n ...> 3\n ...> end\n iex> Keyword.put_new_lazy(keyword, :a, fun)\n [a: 1]\n iex> Keyword.put_new_lazy(keyword, :b, fun)\n [b: 3, a: 1]\n\n \"\"\"\n @spec put_new_lazy(t, key, (() -> value)) :: t\n def put_new_lazy(keywords, key, fun)\n when is_list(keywords) and is_atom(key) and is_function(fun, 0) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, _} -> keywords\n false -> [{key, fun.()}|keywords]\n end\n end\n\n @doc \"\"\"\n Puts the given `value` under `key` unless the entry `key`\n already exists.\n\n ## Examples\n\n iex> Keyword.put_new([a: 1], :b, 2)\n [b: 2, a: 1]\n\n iex> Keyword.put_new([a: 1, b: 2], :a, 3)\n [a: 1, b: 2]\n\n \"\"\"\n @spec put_new(t, key, value) :: t\n def put_new(keywords, key, value) when is_list(keywords) and is_atom(key) do\n case :lists.keyfind(key, 1, keywords) do\n {^key, _} -> keywords\n false -> [{key, value}|keywords]\n end\n end\n\n @doc \"\"\"\n Checks if two keywords are equal.\n\n Two keywords are considered to be equal if they contain\n the same keys and those keys contain the same values.\n\n ## Examples\n\n iex> Keyword.equal?([a: 1, b: 2], [b: 2, a: 1])\n true\n\n \"\"\"\n @spec equal?(t, t) :: boolean\n def equal?(left, right) when is_list(left) and is_list(right) do\n :lists.sort(left) == :lists.sort(right)\n end\n\n @doc \"\"\"\n Merges two keyword lists into one.\n\n If they have duplicated keys, the one given in the second argument wins.\n\n ## Examples\n\n iex> Keyword.merge([a: 1, b: 2], [a: 3, d: 4])\n [a: 3, d: 4, b: 2]\n\n \"\"\"\n @spec merge(t, t) :: t\n def merge(d1, d2) when is_list(d1) and is_list(d2) do\n fun = fn {k, _v} -> not has_key?(d2, k) end\n d2 ++ :lists.filter(fun, d1)\n end\n\n @doc \"\"\"\n Merges two keyword lists into one.\n\n If they have duplicated keys, the given function is invoked to solve conflicts.\n\n ## Examples\n\n iex> Keyword.merge([a: 1, b: 2], [a: 3, d: 4], fn (_k, v1, v2) ->\n ...> v1 + v2\n ...> end)\n [a: 4, b: 2, d: 4]\n\n \"\"\"\n @spec merge(t, t, (key, value, value -> value)) :: t\n def merge(d1, d2, fun) when is_list(d1) and is_list(d2) do\n do_merge(d2, d1, fun)\n end\n\n defp do_merge([{k, v2}|t], acc, fun) do\n do_merge t, update(acc, k, v2, fn(v1) -> fun.(k, v1, v2) end), fun\n end\n\n defp do_merge([], acc, _fun) do\n acc\n end\n\n @doc \"\"\"\n Returns whether a given `key` exists in the given `keywords`.\n\n ## Examples\n\n iex> Keyword.has_key?([a: 1], :a)\n true\n\n iex> Keyword.has_key?([a: 1], :b)\n false\n\n \"\"\"\n @spec has_key?(t, key) :: boolean\n def has_key?(keywords, key) when is_list(keywords) and is_atom(key) do\n :lists.keymember(key, 1, keywords)\n end\n\n @doc \"\"\"\n Updates the `key` with the given function.\n\n If the `key` does not exist, raises `KeyError`.\n\n If there are duplicated keys, they are all removed and only the first one\n is updated.\n\n ## Examples\n\n iex> Keyword.update!([a: 1], :a, &(&1 * 2))\n [a: 2]\n\n iex> Keyword.update!([a: 1], :b, &(&1 * 2))\n ** (KeyError) key :b not found in: [a: 1]\n\n \"\"\"\n @spec update!(t, key, (value -> value)) :: t | no_return\n def update!(keywords, key, fun) do\n update!(keywords, key, fun, keywords)\n end\n\n defp update!([{key, value}|keywords], key, fun, _dict) do\n [{key, fun.(value)}|delete(keywords, key)]\n end\n\n defp update!([{_, _} = e|keywords], key, fun, dict) do\n [e|update!(keywords, key, fun, dict)]\n end\n\n defp update!([], key, _fun, dict) when is_atom(key) do\n raise(KeyError, key: key, term: dict)\n end\n\n @doc \"\"\"\n Updates the `key` with the given function.\n\n If the `key` does not exist, inserts the given `initial` value.\n\n If there are duplicated keys, they are all removed and only the first one\n is updated.\n\n ## Examples\n\n iex> Keyword.update([a: 1], :a, 13, &(&1 * 2))\n [a: 2]\n\n iex> Keyword.update([a: 1], :b, 11, &(&1 * 2))\n [a: 1, b: 11]\n\n \"\"\"\n @spec update(t, key, value, (value -> value)) :: t\n def update([{key, value}|keywords], key, _initial, fun) do\n [{key, fun.(value)}|delete(keywords, key)]\n end\n\n def update([{_, _} = e|keywords], key, initial, fun) do\n [e|update(keywords, key, initial, fun)]\n end\n\n def update([], key, initial, _fun) when is_atom(key) do\n [{key, initial}]\n end\n\n @doc \"\"\"\n Takes all entries corresponding to the given keys and extracts them into a\n separate keyword list.\n\n Returns a tuple with the new list and the old list with removed keys.\n\n Keys for which there are no entires in the keyword list are ignored.\n\n Entries with duplicated keys end up in the same keyword list.\n\n ## Examples\n\n iex> d = [a: 1, b: 2, c: 3, d: 4]\n iex> Keyword.split(d, [:a, :c, :e])\n {[a: 1, c: 3], [b: 2, d: 4]}\n\n iex> d = [a: 1, b: 2, c: 3, d: 4, a: 5]\n iex> Keyword.split(d, [:a, :c, :e])\n {[a: 1, c: 3, a: 5], [b: 2, d: 4]}\n\n \"\"\"\n def split(keywords, keys) when is_list(keywords) do\n fun = fn {k, v}, {take, drop} ->\n case k in keys do\n true -> {[{k, v}|take], drop}\n false -> {take, [{k, v}|drop]}\n end\n end\n\n acc = {[], []}\n {take, drop} = :lists.foldl(fun, acc, keywords)\n {:lists.reverse(take), :lists.reverse(drop)}\n end\n\n @doc \"\"\"\n Takes all entries corresponding to the given keys and returns them in a new\n keyword list.\n\n Duplicated keys are preserved in the new keyword list.\n\n ## Examples\n\n iex> d = [a: 1, b: 2, c: 3, d: 4]\n iex> Keyword.take(d, [:a, :c, :e])\n [a: 1, c: 3]\n\n iex> d = [a: 1, b: 2, c: 3, d: 4, a: 5]\n iex> Keyword.take(d, [:a, :c, :e])\n [a: 1, c: 3, a: 5]\n\n \"\"\"\n def take(keywords, keys) when is_list(keywords) do\n :lists.filter(fn {k, _} -> k in keys end, keywords)\n end\n\n @doc \"\"\"\n Drops the given keys from the keyword list.\n\n Duplicated keys are preserved in the new keyword list.\n\n ## Examples\n\n iex> d = [a: 1, b: 2, c: 3, d: 4]\n iex> Keyword.drop(d, [:b, :d])\n [a: 1, c: 3]\n\n iex> d = [a: 1, b: 2, b: 3, c: 3, d: 4, a: 5]\n iex> Keyword.drop(d, [:b, :d])\n [a: 1, c: 3, a: 5]\n\n \"\"\"\n def drop(keywords, keys) when is_list(keywords) do\n :lists.filter(fn {k, _} -> not k in keys end, keywords)\n end\n\n @doc \"\"\"\n Returns the first value associated with `key` in the keyword\n list as well as the keyword list without `key`.\n\n All duplicated keys are removed. See `pop_first\/3` for\n removing only the first entry.\n\n ## Examples\n\n iex> Keyword.pop [a: 1], :a\n {1,[]}\n\n iex> Keyword.pop [a: 1], :b\n {nil,[a: 1]}\n\n iex> Keyword.pop [a: 1], :b, 3\n {3,[a: 1]}\n\n iex> Keyword.pop [a: 1], :b, 3\n {3,[a: 1]}\n\n iex> Keyword.pop [a: 1, a: 2], :a\n {1,[]}\n\n \"\"\"\n def pop(keywords, key, default \\\\ nil) when is_list(keywords) do\n {get(keywords, key, default), delete(keywords, key)}\n end\n\n @doc \"\"\"\n Returns the first value associated with `key` in the keyword\n list as well as the keyword list without `key`.\n\n This is useful if the default value is very expensive to calculate or\n generally difficult to set-up and tear-down again.\n\n All duplicated keys are removed. See `pop_first\/3` for\n removing only the first entry.\n\n ## Examples\n\n iex> keyword = [a: 1]\n iex> fun = fn ->\n ...> # some expensive operation here\n ...> :result\n ...> end\n iex> Keyword.pop_lazy(keyword, :a, fun)\n {1,[]}\n iex> Keyword.pop_lazy(keyword, :b, fun)\n {:result,[a: 1]}\n\n \"\"\"\n @spec pop_lazy(t, key, (() -> value)) :: {value, t}\n def pop_lazy(keywords, key, fun) when is_list(keywords) do\n {get_lazy(keywords, key, fun), delete(keywords, key)}\n end\n\n @doc \"\"\"\n Returns the first value associated with `key` in the keyword\n list as well as the keyword list without that particular occurrence\n of `key`.\n\n Duplicated keys are not removed.\n\n ## Examples\n\n iex> Keyword.pop_first [a: 1], :a\n {1,[]}\n\n iex> Keyword.pop_first [a: 1], :b\n {nil,[a: 1]}\n\n iex> Keyword.pop_first [a: 1], :b, 3\n {3,[a: 1]}\n\n iex> Keyword.pop_first [a: 1], :b, 3\n {3,[a: 1]}\n\n iex> Keyword.pop_first [a: 1, a: 2], :a\n {1,[a: 2]}\n\n \"\"\"\n def pop_first(keywords, key, default \\\\ nil) when is_list(keywords) do\n {get(keywords, key, default), delete_first(keywords, key)}\n end\n\n # Dict callbacks\n\n @doc false\n def size(keyword) do\n length(keyword)\n end\n\n @doc false\n def to_list(keyword) do\n keyword\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"1333bf31adb87bc137c019b26770f1682cfc0e52","subject":"Add missing comments about inlining in Process","message":"Add missing comments about inlining in Process\n","repos":"kimshrier\/elixir,antipax\/elixir,beedub\/elixir,ggcampinho\/elixir,kelvinst\/elixir,michalmuskala\/elixir,kimshrier\/elixir,elixir-lang\/elixir,pedrosnk\/elixir,lexmag\/elixir,antipax\/elixir,gfvcastro\/elixir,ggcampinho\/elixir,kelvinst\/elixir,gfvcastro\/elixir,beedub\/elixir,lexmag\/elixir,pedrosnk\/elixir,joshprice\/elixir","old_file":"lib\/elixir\/lib\/process.ex","new_file":"lib\/elixir\/lib\/process.ex","new_contents":"defmodule Process do\n @moduledoc \"\"\"\n Conveniences for working with processes and the process dictionary.\n\n Besides the functions available in this module, the `Kernel` module\n exposes and auto-imports some basic functionality related to processes\n available through the functions:\n\n * `Kernel.spawn\/1` and `Kernel.spawn\/3`\n * `Kernel.spawn_link\/1` and `Kernel.spawn_link\/3`\n * `Kernel.spawn_monitor\/1` and `Kernel.spawn_monitor\/3`\n * `Kernel.self\/0`\n * `Kernel.send\/2`\n\n \"\"\"\n\n @doc \"\"\"\n Returns `true` if the process exists and is alive (i.e. it is not exiting\n and has not exited yet). Otherwise, returns `false`.\n\n `pid` must refer to a process at the local node.\n\n Inlined by the compiler.\n \"\"\"\n @spec alive?(pid) :: boolean\n def alive?(pid) do\n :erlang.is_process_alive(pid)\n end\n\n @doc \"\"\"\n Returns all key-values in the dictionary.\n\n Inlined by the compiler.\n \"\"\"\n @spec get :: [{term, term}]\n def get do\n :erlang.get()\n end\n\n @doc \"\"\"\n Returns the value for the given `key`.\n \"\"\"\n @spec get(term) :: term\n @spec get(term, default :: term) :: term\n def get(key, default \\\\ nil) do\n case :erlang.get(key) do\n :undefined ->\n default\n value ->\n value\n end\n end\n\n @doc \"\"\"\n Returns all keys in the process dictionary.\n\n Inlined by the compiler.\n \"\"\"\n @spec get_keys() :: [term]\n def get_keys() do\n :erlang.get_keys()\n end\n\n @doc \"\"\"\n Returns all keys that have the given `value`.\n\n Inlined by the compiler.\n \"\"\"\n @spec get_keys(term) :: [term]\n def get_keys(value) do\n :erlang.get_keys(value)\n end\n\n @doc \"\"\"\n Stores the given key-value in the process dictionary.\n\n The return value is the value that was previously stored under the key `key`\n (or `nil` in case no value was stored under `key`).\n \"\"\"\n @spec put(term, term) :: term | nil\n def put(key, value) do\n nillify :erlang.put(key, value)\n end\n\n @doc \"\"\"\n Deletes the given `key` from the dictionary.\n \"\"\"\n @spec delete(term) :: term | nil\n def delete(key) do\n nillify :erlang.erase(key)\n end\n\n @doc \"\"\"\n Sends an exit signal with the given reason to the pid.\n\n The following behaviour applies if reason is any term except `:normal` or `:kill`:\n\n 1. If pid is not trapping exits, pid will exit with the given reason.\n\n 2. If pid is trapping exits, the exit signal is transformed into a message\n `{:EXIT, from, reason}` and delivered to the message queue of pid.\n\n 3. If reason is the atom `:normal`, pid will not exit (unless it is the calling\n process's pid, in which case it will exit with the reason `:normal`).\n If it is trapping exits, the exit signal is transformed into a message\n `{:EXIT, from, :normal}` and delivered to its message queue.\n\n 4. If reason is the atom `:kill`, that is if `exit(pid, :kill)` is called,\n an untrappable exit signal is sent to pid which will unconditionally\n exit with exit reason `:killed`.\n\n Inlined by the compiler.\n\n ## Examples\n\n Process.exit(pid, :kill)\n\n \"\"\"\n @spec exit(pid, term) :: true\n def exit(pid, reason) do\n :erlang.exit(pid, reason)\n end\n\n @doc \"\"\"\n Sends a message to the given process.\n\n If the option `:noconnect` is used and sending the message would require an\n auto-connection to another node the message is not sent and `:noconnect` is\n returned.\n\n If the option `:nosuspend` is used and sending the message would cause the\n sender to be suspended the message is not sent and `:nosuspend` is returned.\n\n Otherwise the message is sent and `:ok` is returned.\n\n ## Examples\n\n iex> Process.send({:name, :node_does_not_exist}, :hi, [:noconnect])\n :noconnect\n\n \"\"\"\n @spec send(dest, msg, [option]) :: :ok | :noconnect | :nosuspend when\n dest: pid | port | atom | {atom, node},\n msg: any,\n option: :noconnect | :nosuspend\n def send(dest, msg, options) do\n :erlang.send(dest, msg, options)\n end\n\n @doc \"\"\"\n Sends `msg` to `dest` after `time` milliseconds.\n\n If `dest` is a pid, it must be the pid of a local process, dead or alive.\n If `dest` is an atom, it must be the name of a registered process\n which is looked up at the time of delivery. No error is given if the name does\n not refer to a process.\n\n This function returns a timer reference, which can be read or canceled with\n `read_timer\/1` and `cancel_timer\/1`.\n\n Finally, the timer will be automatically canceled if the given `dest` is a pid\n which is not alive or when the given pid exits. Note that timers will not be\n automatically canceled when `dest` is an atom (as the atom resolution is done\n on delivery).\n \"\"\"\n @spec send_after(pid | atom, term, non_neg_integer) :: reference\n def send_after(dest, msg, time) do\n :erlang.send_after(time, dest, msg)\n end\n\n @doc \"\"\"\n Cancels a timer created by `send_after\/3`.\n\n When the result is an integer, it represents the time in milli-seconds\n left until the timer will expire.\n\n When the result is `false`, a timer corresponding to `timer_ref` could\n not be found. This can be either because the timer expired, already has\n been canceled, or because `timer_ref` never corresponded to a timer.\n\n If the timer has expired, the timeout message has been sent, but it does\n not tell you whether or not it has arrived at its destination yet.\n\n Inlined by the compiler.\n \"\"\"\n @spec cancel_timer(reference) :: non_neg_integer | false\n def cancel_timer(timer_ref) do\n :erlang.cancel_timer(timer_ref)\n end\n\n @doc \"\"\"\n Reads a timer created by `send_after\/3`.\n\n When the result is an integer, it represents the time in milli-seconds\n left until the timer will expire.\n\n When the result is `false`, a timer corresponding to `timer_ref` could\n not be found. This can be either because the timer expired, already has\n been canceled, or because `timer_ref` never corresponded to a timer.\n\n If the timer has expired, the timeout message has been sent, but it does\n not tell you whether or not it has arrived at its destination yet.\n\n Inlined by the compiler.\n \"\"\"\n @spec read_timer(reference) :: non_neg_integer | false\n def read_timer(timer_ref) do\n :erlang.read_timer(timer_ref)\n end\n\n @type spawn_opt :: :link | :monitor | {:priority, :low | :normal | :high} |\n {:fullsweep_after, non_neg_integer} |\n {:min_heap_size, non_neg_integer} |\n {:min_bin_vheap_size, non_neg_integer}\n @type spawn_opts :: [spawn_opt]\n\n @doc \"\"\"\n Spawns the given module and function passing the given args\n according to the given options.\n\n The result depends on the given options. In particular,\n if `:monitor` is given as an option, it will return a tuple\n containing the pid and the monitoring reference, otherwise\n just the spawned process pid.\n\n It also accepts extra options, for the list of available options\n check [`:erlang.spawn_opt\/4`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#spawn_opt-4).\n\n Inlined by the compiler.\n \"\"\"\n @spec spawn((() -> any), spawn_opts) :: pid | {pid, reference}\n def spawn(fun, opts) do\n :erlang.spawn_opt(fun, opts)\n end\n\n @doc \"\"\"\n Spawns the given module and function passing the given args\n according to the given options.\n\n The result depends on the given options. In particular,\n if `:monitor` is given as an option, it will return a tuple\n containing the pid and the monitoring reference, otherwise\n just the spawned process pid.\n\n It also accepts extra options, for the list of available options\n check [`:erlang.spawn_opt\/4`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#spawn_opt-4).\n\n Inlined by the compiler.\n \"\"\"\n @spec spawn(module, atom, list, spawn_opts) :: pid | {pid, reference}\n def spawn(mod, fun, args, opts) do\n :erlang.spawn_opt(mod, fun, args, opts)\n end\n\n @doc \"\"\"\n The calling process starts monitoring the item given.\n It returns the monitor reference.\n\n See [the need for monitoring](http:\/\/elixir-lang.org\/getting-started\/mix-otp\/genserver.html#the-need-for-monitoring)\n for an example.\n See [`:erlang.monitor\/2`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#monitor-2) for more info.\n\n Inlined by the compiler.\n \"\"\"\n @spec monitor(pid | {reg_name :: atom, node :: atom} | reg_name :: atom) :: reference\n def monitor(item) do\n :erlang.monitor(:process, item)\n end\n\n @doc \"\"\"\n If `monitor_ref` is a reference which the calling process\n obtained by calling `monitor\/1`, this monitoring is turned off.\n If the monitoring is already turned off, nothing happens.\n\n See [`:erlang.demonitor\/2`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#demonitor-2) for more info.\n\n Inlined by the compiler.\n \"\"\"\n @spec demonitor(reference) :: true\n @spec demonitor(reference, options :: [:flush | :info]) :: boolean\n def demonitor(monitor_ref, options \\\\ []) do\n :erlang.demonitor(monitor_ref, options)\n end\n\n @doc \"\"\"\n Returns a list of process identifiers corresponding to all the\n processes currently existing on the local node.\n\n Note that a process that is exiting, exists but is not alive, i.e.,\n `alive?\/1` will return `false` for a process that is exiting,\n but its process identifier will be part of the result returned.\n\n See [`:erlang.processes\/0`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#processes-0) for more info.\n \"\"\"\n @spec list :: [pid]\n def list do\n :erlang.processes()\n end\n\n @doc \"\"\"\n Creates a link between the calling process and another process\n (or port) `pid`, if there is not such a link already.\n\n See [`:erlang.link\/1`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#link-1) for more info.\n\n Inlined by the compiler.\n \"\"\"\n @spec link(pid | port) :: true\n def link(pid) do\n :erlang.link(pid)\n end\n\n @doc \"\"\"\n Removes the link, if there is one, between the calling process and\n the process or port referred to by `pid`. Returns `true` and does not\n fail, even if there is no link or `id` does not exist\n\n See [`:erlang.unlink\/1`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#unlink-1) for more info.\n\n Inlined by the compiler.\n \"\"\"\n @spec unlink(pid | port) :: true\n def unlink(pid) do\n :erlang.unlink(pid)\n end\n\n @doc \"\"\"\n Associates the name with a pid or a port identifier. `name`, which must\n be an atom, can be used instead of the pid \/ port identifier with the\n `Kernel.send\/2` function.\n\n `Process.register\/2` will fail with `ArgumentError` if the pid supplied\n is no longer alive, (check with `alive?\/1`) or if the name is\n already registered (check with `whereis\/1`).\n \"\"\"\n @spec register(pid | port, atom) :: true\n def register(pid, name) when not name in [nil, false, true] do\n :erlang.register(name, pid)\n end\n\n @doc \"\"\"\n Removes the registered name, associated with a pid or a port identifier.\n\n See [`:erlang.unregister\/1`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#unregister-1) for more info.\n \"\"\"\n @spec unregister(atom) :: true\n def unregister(name) do\n :erlang.unregister(name)\n end\n\n @doc \"\"\"\n Returns the pid or port identifier with the registered name.\n Returns `nil` if the name is not registered.\n\n See [`:erlang.whereis\/1`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#whereis-1) for more info.\n \"\"\"\n @spec whereis(atom) :: pid | port | nil\n def whereis(name) do\n nillify :erlang.whereis(name)\n end\n\n @doc \"\"\"\n Returns the pid of the group leader for the process which evaluates the function.\n \"\"\"\n @spec group_leader :: pid\n def group_leader do\n :erlang.group_leader\n end\n\n @doc \"\"\"\n Sets the group leader of `pid` to `leader`. Typically, this is used when a processes\n started from a certain shell should have a group leader other than `:init`.\n \"\"\"\n @spec group_leader(pid, leader :: pid) :: true\n def group_leader(pid, leader) do\n :erlang.group_leader(leader, pid)\n end\n\n @doc \"\"\"\n Returns a list of names which have been registered using `register\/2`.\n \"\"\"\n @spec registered :: [atom]\n def registered do\n :erlang.registered()\n end\n\n @typep process_flag :: :trap_exit | :error_handler | :min_heap_size |\n :min_bin_vheap_size | :priority | :save_calls |\n :sensitive\n @doc \"\"\"\n Sets certain flags for the process which calls this function.\n Returns the old value of the flag.\n\n See [`:erlang.process_flag\/2`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#process_flag-2) for more info.\n \"\"\"\n @spec flag(process_flag, term) :: term\n def flag(flag, value) do\n :erlang.process_flag(flag, value)\n end\n\n @doc \"\"\"\n Sets certain flags for the process `pid`, in the same manner as `flag\/2`.\n Returns the old value of the flag. The allowed values for `flag` are\n only a subset of those allowed in `flag\/2`, namely: `save_calls`.\n\n See [`:erlang.process_flag\/3`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#process_flag-3) for more info.\n \"\"\"\n @spec flag(pid, :save_calls, non_neg_integer) :: non_neg_integer\n def flag(pid, flag, value) do\n :erlang.process_flag(pid, flag, value)\n end\n\n @doc \"\"\"\n Returns information about the process identified by `pid` or `nil` if the process\n is not alive.\n Use this only for debugging information.\n\n See [`:erlang.process_info\/1`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#process_info-1) for more info.\n \"\"\"\n @spec info(pid) :: Keyword.t\n def info(pid) do\n nillify :erlang.process_info(pid)\n end\n\n @doc \"\"\"\n Returns information about the process identified by `pid`\n or `nil` if the process is not alive.\n\n See [`:erlang.process_info\/2`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#process_info-2) for more info.\n \"\"\"\n @spec info(pid, atom | [atom]) :: {atom, term} | [{atom, term}] | nil\n def info(pid, spec)\n\n def info(pid, :registered_name) do\n case :erlang.process_info(pid, :registered_name) do\n :undefined -> nil\n [] -> {:registered_name, []}\n other -> other\n end\n end\n\n def info(pid, spec) when is_atom(spec) or is_list(spec) do\n nillify :erlang.process_info(pid, spec)\n end\n\n @doc \"\"\"\n Puts the calling process into a wait state\n where its memory allocation has been reduced as much as possible,\n which is useful if the process does not expect to receive any messages\n in the near future.\n\n See [`:erlang.hibernate\/3`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#hibernate-3) for more info.\n\n Inlined by the compiler.\n \"\"\"\n @spec hibernate(module, atom, list) :: no_return\n def hibernate(mod, fun, args) do\n :erlang.hibernate(mod, fun, args)\n end\n\n @compile {:inline, nillify: 1}\n defp nillify(:undefined), do: nil\n defp nillify(other), do: other\nend\n","old_contents":"defmodule Process do\n @moduledoc \"\"\"\n Conveniences for working with processes and the process dictionary.\n\n Besides the functions available in this module, the `Kernel` module\n exposes and auto-imports some basic functionality related to processes\n available through the functions:\n\n * `Kernel.spawn\/1` and `Kernel.spawn\/3`\n * `Kernel.spawn_link\/1` and `Kernel.spawn_link\/3`\n * `Kernel.spawn_monitor\/1` and `Kernel.spawn_monitor\/3`\n * `Kernel.self\/0`\n * `Kernel.send\/2`\n\n \"\"\"\n\n @doc \"\"\"\n Returns `true` if the process exists and is alive (i.e. it is not exiting\n and has not exited yet). Otherwise, returns `false`.\n\n `pid` must refer to a process at the local node.\n\n Inlined by the compiler.\n \"\"\"\n @spec alive?(pid) :: boolean\n def alive?(pid) do\n :erlang.is_process_alive(pid)\n end\n\n @doc \"\"\"\n Returns all key-values in the dictionary.\n\n Inlined by the compiler.\n \"\"\"\n @spec get :: [{term, term}]\n def get do\n :erlang.get()\n end\n\n @doc \"\"\"\n Returns the value for the given `key`.\n \"\"\"\n @spec get(term) :: term\n @spec get(term, default :: term) :: term\n def get(key, default \\\\ nil) do\n case :erlang.get(key) do\n :undefined ->\n default\n value ->\n value\n end\n end\n\n @doc \"\"\"\n Returns all keys in the process dictionary.\n\n Inlined by the compiler.\n \"\"\"\n @spec get_keys() :: [term]\n def get_keys() do\n :erlang.get_keys()\n end\n\n @doc \"\"\"\n Returns all keys that have the given `value`.\n\n Inlined by the compiler.\n \"\"\"\n @spec get_keys(term) :: [term]\n def get_keys(value) do\n :erlang.get_keys(value)\n end\n\n @doc \"\"\"\n Stores the given key-value in the process dictionary.\n\n The return value is the value that was previously stored under the key `key`\n (or `nil` in case no value was stored under `key`).\n \"\"\"\n @spec put(term, term) :: term | nil\n def put(key, value) do\n nillify :erlang.put(key, value)\n end\n\n @doc \"\"\"\n Deletes the given `key` from the dictionary.\n \"\"\"\n @spec delete(term) :: term | nil\n def delete(key) do\n nillify :erlang.erase(key)\n end\n\n @doc \"\"\"\n Sends an exit signal with the given reason to the pid.\n\n The following behaviour applies if reason is any term except `:normal` or `:kill`:\n\n 1. If pid is not trapping exits, pid will exit with the given reason.\n\n 2. If pid is trapping exits, the exit signal is transformed into a message\n `{:EXIT, from, reason}` and delivered to the message queue of pid.\n\n 3. If reason is the atom `:normal`, pid will not exit (unless it is the calling\n process's pid, in which case it will exit with the reason `:normal`).\n If it is trapping exits, the exit signal is transformed into a message\n `{:EXIT, from, :normal}` and delivered to its message queue.\n\n 4. If reason is the atom `:kill`, that is if `exit(pid, :kill)` is called,\n an untrappable exit signal is sent to pid which will unconditionally\n exit with exit reason `:killed`.\n\n Inlined by the compiler.\n\n ## Examples\n\n Process.exit(pid, :kill)\n\n \"\"\"\n @spec exit(pid, term) :: true\n def exit(pid, reason) do\n :erlang.exit(pid, reason)\n end\n\n @doc \"\"\"\n Sends a message to the given process.\n\n If the option `:noconnect` is used and sending the message would require an\n auto-connection to another node the message is not sent and `:noconnect` is\n returned.\n\n If the option `:nosuspend` is used and sending the message would cause the\n sender to be suspended the message is not sent and `:nosuspend` is returned.\n\n Otherwise the message is sent and `:ok` is returned.\n\n ## Examples\n\n iex> Process.send({:name, :node_does_not_exist}, :hi, [:noconnect])\n :noconnect\n\n \"\"\"\n @spec send(dest, msg, [option]) :: :ok | :noconnect | :nosuspend when\n dest: pid | port | atom | {atom, node},\n msg: any,\n option: :noconnect | :nosuspend\n def send(dest, msg, options) do\n :erlang.send(dest, msg, options)\n end\n\n @doc \"\"\"\n Sends `msg` to `dest` after `time` milliseconds.\n\n If `dest` is a pid, it must be the pid of a local process, dead or alive.\n If `dest` is an atom, it must be the name of a registered process\n which is looked up at the time of delivery. No error is given if the name does\n not refer to a process.\n\n This function returns a timer reference, which can be read or canceled with\n `read_timer\/1` and `cancel_timer\/1`.\n\n Finally, the timer will be automatically canceled if the given `dest` is a pid\n which is not alive or when the given pid exits. Note that timers will not be\n automatically canceled when `dest` is an atom (as the atom resolution is done\n on delivery).\n \"\"\"\n @spec send_after(pid | atom, term, non_neg_integer) :: reference\n def send_after(dest, msg, time) do\n :erlang.send_after(time, dest, msg)\n end\n\n @doc \"\"\"\n Cancels a timer created by `send_after\/3`.\n\n When the result is an integer, it represents the time in milli-seconds\n left until the timer will expire.\n\n When the result is `false`, a timer corresponding to `timer_ref` could\n not be found. This can be either because the timer expired, already has\n been canceled, or because `timer_ref` never corresponded to a timer.\n\n If the timer has expired, the timeout message has been sent, but it does\n not tell you whether or not it has arrived at its destination yet.\n \"\"\"\n @spec cancel_timer(reference) :: non_neg_integer | false\n def cancel_timer(timer_ref) do\n :erlang.cancel_timer(timer_ref)\n end\n\n @doc \"\"\"\n Reads a timer created by `send_after\/3`.\n\n When the result is an integer, it represents the time in milli-seconds\n left until the timer will expire.\n\n When the result is `false`, a timer corresponding to `timer_ref` could\n not be found. This can be either because the timer expired, already has\n been canceled, or because `timer_ref` never corresponded to a timer.\n\n If the timer has expired, the timeout message has been sent, but it does\n not tell you whether or not it has arrived at its destination yet.\n \"\"\"\n @spec read_timer(reference) :: non_neg_integer | false\n def read_timer(timer_ref) do\n :erlang.read_timer(timer_ref)\n end\n\n @type spawn_opt :: :link | :monitor | {:priority, :low | :normal | :high} |\n {:fullsweep_after, non_neg_integer} |\n {:min_heap_size, non_neg_integer} |\n {:min_bin_vheap_size, non_neg_integer}\n @type spawn_opts :: [spawn_opt]\n\n @doc \"\"\"\n Spawns the given module and function passing the given args\n according to the given options.\n\n The result depends on the given options. In particular,\n if `:monitor` is given as an option, it will return a tuple\n containing the pid and the monitoring reference, otherwise\n just the spawned process pid.\n\n It also accepts extra options, for the list of available options\n check [`:erlang.spawn_opt\/4`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#spawn_opt-4).\n\n Inlined by the compiler.\n \"\"\"\n @spec spawn((() -> any), spawn_opts) :: pid | {pid, reference}\n def spawn(fun, opts) do\n :erlang.spawn_opt(fun, opts)\n end\n\n @doc \"\"\"\n Spawns the given module and function passing the given args\n according to the given options.\n\n The result depends on the given options. In particular,\n if `:monitor` is given as an option, it will return a tuple\n containing the pid and the monitoring reference, otherwise\n just the spawned process pid.\n\n It also accepts extra options, for the list of available options\n check [`:erlang.spawn_opt\/4`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#spawn_opt-4).\n\n Inlined by the compiler.\n \"\"\"\n @spec spawn(module, atom, list, spawn_opts) :: pid | {pid, reference}\n def spawn(mod, fun, args, opts) do\n :erlang.spawn_opt(mod, fun, args, opts)\n end\n\n @doc \"\"\"\n The calling process starts monitoring the item given.\n It returns the monitor reference.\n\n See [the need for monitoring](http:\/\/elixir-lang.org\/getting-started\/mix-otp\/genserver.html#the-need-for-monitoring)\n for an example.\n See [`:erlang.monitor\/2`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#monitor-2) for more info.\n\n Inlined by the compiler.\n \"\"\"\n @spec monitor(pid | {reg_name :: atom, node :: atom} | reg_name :: atom) :: reference\n def monitor(item) do\n :erlang.monitor(:process, item)\n end\n\n @doc \"\"\"\n If `monitor_ref` is a reference which the calling process\n obtained by calling `monitor\/1`, this monitoring is turned off.\n If the monitoring is already turned off, nothing happens.\n\n See [`:erlang.demonitor\/2`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#demonitor-2) for more info.\n\n Inlined by the compiler.\n \"\"\"\n @spec demonitor(reference) :: true\n @spec demonitor(reference, options :: [:flush | :info]) :: boolean\n def demonitor(monitor_ref, options \\\\ []) do\n :erlang.demonitor(monitor_ref, options)\n end\n\n @doc \"\"\"\n Returns a list of process identifiers corresponding to all the\n processes currently existing on the local node.\n\n Note that a process that is exiting, exists but is not alive, i.e.,\n `alive?\/1` will return `false` for a process that is exiting,\n but its process identifier will be part of the result returned.\n\n See [`:erlang.processes\/0`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#processes-0) for more info.\n \"\"\"\n @spec list :: [pid]\n def list do\n :erlang.processes()\n end\n\n @doc \"\"\"\n Creates a link between the calling process and another process\n (or port) `pid`, if there is not such a link already.\n\n See [`:erlang.link\/1`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#link-1) for more info.\n\n Inlined by the compiler.\n \"\"\"\n @spec link(pid | port) :: true\n def link(pid) do\n :erlang.link(pid)\n end\n\n @doc \"\"\"\n Removes the link, if there is one, between the calling process and\n the process or port referred to by `pid`. Returns `true` and does not\n fail, even if there is no link or `id` does not exist\n\n See [`:erlang.unlink\/1`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#unlink-1) for more info.\n\n Inlined by the compiler.\n \"\"\"\n @spec unlink(pid | port) :: true\n def unlink(pid) do\n :erlang.unlink(pid)\n end\n\n @doc \"\"\"\n Associates the name with a pid or a port identifier. `name`, which must\n be an atom, can be used instead of the pid \/ port identifier with the\n `Kernel.send\/2` function.\n\n `Process.register\/2` will fail with `ArgumentError` if the pid supplied\n is no longer alive, (check with `alive?\/1`) or if the name is\n already registered (check with `whereis\/1`).\n \"\"\"\n @spec register(pid | port, atom) :: true\n def register(pid, name) when not name in [nil, false, true] do\n :erlang.register(name, pid)\n end\n\n @doc \"\"\"\n Removes the registered name, associated with a pid or a port identifier.\n\n See [`:erlang.unregister\/1`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#unregister-1) for more info.\n \"\"\"\n @spec unregister(atom) :: true\n def unregister(name) do\n :erlang.unregister(name)\n end\n\n @doc \"\"\"\n Returns the pid or port identifier with the registered name.\n Returns `nil` if the name is not registered.\n\n See [`:erlang.whereis\/1`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#whereis-1) for more info.\n \"\"\"\n @spec whereis(atom) :: pid | port | nil\n def whereis(name) do\n nillify :erlang.whereis(name)\n end\n\n @doc \"\"\"\n Returns the pid of the group leader for the process which evaluates the function.\n \"\"\"\n @spec group_leader :: pid\n def group_leader do\n :erlang.group_leader\n end\n\n @doc \"\"\"\n Sets the group leader of `pid` to `leader`. Typically, this is used when a processes\n started from a certain shell should have a group leader other than `:init`.\n \"\"\"\n @spec group_leader(pid, leader :: pid) :: true\n def group_leader(pid, leader) do\n :erlang.group_leader(leader, pid)\n end\n\n @doc \"\"\"\n Returns a list of names which have been registered using `register\/2`.\n \"\"\"\n @spec registered :: [atom]\n def registered do\n :erlang.registered()\n end\n\n @typep process_flag :: :trap_exit | :error_handler | :min_heap_size |\n :min_bin_vheap_size | :priority | :save_calls |\n :sensitive\n @doc \"\"\"\n Sets certain flags for the process which calls this function.\n Returns the old value of the flag.\n\n See [`:erlang.process_flag\/2`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#process_flag-2) for more info.\n \"\"\"\n @spec flag(process_flag, term) :: term\n def flag(flag, value) do\n :erlang.process_flag(flag, value)\n end\n\n @doc \"\"\"\n Sets certain flags for the process `pid`, in the same manner as `flag\/2`.\n Returns the old value of the flag. The allowed values for `flag` are\n only a subset of those allowed in `flag\/2`, namely: `save_calls`.\n\n See [`:erlang.process_flag\/3`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#process_flag-3) for more info.\n \"\"\"\n @spec flag(pid, :save_calls, non_neg_integer) :: non_neg_integer\n def flag(pid, flag, value) do\n :erlang.process_flag(pid, flag, value)\n end\n\n @doc \"\"\"\n Returns information about the process identified by `pid` or `nil` if the process\n is not alive.\n Use this only for debugging information.\n\n See [`:erlang.process_info\/1`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#process_info-1) for more info.\n \"\"\"\n @spec info(pid) :: Keyword.t\n def info(pid) do\n nillify :erlang.process_info(pid)\n end\n\n @doc \"\"\"\n Returns information about the process identified by `pid`\n or `nil` if the process is not alive.\n\n See [`:erlang.process_info\/2`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#process_info-2) for more info.\n \"\"\"\n @spec info(pid, atom | [atom]) :: {atom, term} | [{atom, term}] | nil\n def info(pid, spec)\n\n def info(pid, :registered_name) do\n case :erlang.process_info(pid, :registered_name) do\n :undefined -> nil\n [] -> {:registered_name, []}\n other -> other\n end\n end\n\n def info(pid, spec) when is_atom(spec) or is_list(spec) do\n nillify :erlang.process_info(pid, spec)\n end\n\n @doc \"\"\"\n Puts the calling process into a wait state\n where its memory allocation has been reduced as much as possible,\n which is useful if the process does not expect to receive any messages\n in the near future.\n\n See [`:erlang.hibernate\/3`](http:\/\/www.erlang.org\/doc\/man\/erlang.html#hibernate-3) for more info.\n\n Inlined by the compiler.\n \"\"\"\n @spec hibernate(module, atom, list) :: no_return\n def hibernate(mod, fun, args) do\n :erlang.hibernate(mod, fun, args)\n end\n\n @compile {:inline, nillify: 1}\n defp nillify(:undefined), do: nil\n defp nillify(other), do: other\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"a6b81bffd1beb974851ff8011b8c8c5d625ee775","subject":"Inline nillify in Process","message":"Inline nillify in Process\n","repos":"ggcampinho\/elixir,lexmag\/elixir,kimshrier\/elixir,lexmag\/elixir,antipax\/elixir,gfvcastro\/elixir,kimshrier\/elixir,kelvinst\/elixir,beedub\/elixir,elixir-lang\/elixir,ggcampinho\/elixir,pedrosnk\/elixir,beedub\/elixir,gfvcastro\/elixir,kelvinst\/elixir,pedrosnk\/elixir,michalmuskala\/elixir,joshprice\/elixir,antipax\/elixir","old_file":"lib\/elixir\/lib\/process.ex","new_file":"lib\/elixir\/lib\/process.ex","new_contents":"defmodule Process do\n @moduledoc \"\"\"\n This module provides convenience functions around processes and\n the process dictionary. In Erlang, most of these functions are\n auto-imported, but in Elixir they are grouped in a module for\n convenience. Notice that these functions, different from Erlang's,\n always return nil instead of undefined. You can use their Erlang\n version if you want the undefined value.\n \"\"\"\n\n @doc \"\"\"\n Returns true if the process exists and is alive, that is,\n is not exiting and has not exited. Otherwise, returns false.\n\n `pid` must refer to a process at the local node.\n \"\"\"\n @spec alive?(pid) :: boolean\n def alive?(pid) do\n :erlang.is_process_alive(pid)\n end\n\n @doc \"\"\"\n Returns all key-values in the dictionary.\n \"\"\"\n @spec get :: [{term, term}]\n def get do\n :erlang.get()\n end\n\n @doc \"\"\"\n Returns the value for the given key.\n \"\"\"\n @spec get(term) :: term\n @spec get(term, default :: term) :: term\n def get(key, default \/\/ nil) do\n case :erlang.get(key) do\n :undefined ->\n default\n value ->\n value\n end\n end\n\n @doc \"\"\"\n Returns all keys that have the given `value`.\n \"\"\"\n @spec get_keys(term) :: [term]\n def get_keys(value) do\n :erlang.get_keys(value)\n end\n\n @doc \"\"\"\n Stores the given key-value in the process dictionary.\n \"\"\"\n @spec put(term, term) :: term | nil\n def put(key, value) do\n nillify :erlang.put(key, value)\n end\n\n @doc \"\"\"\n Deletes all items in the dictionary.\n \"\"\"\n @spec delete :: [{term, term}]\n def delete() do\n :erlang.erase()\n end\n\n @doc \"\"\"\n Deletes the given key from the dictionary.\n \"\"\"\n @spec delete(term) :: term | nil\n def delete(key) do\n nillify :erlang.erase(key)\n end\n\n @doc \"\"\"\n Sends an exit signal with the given reason to the pid.\n\n The following behavior apply if reason is any term except `:normal` or `:kill`:\n\n 1) If pid is not trapping exits, pid itself will exist with the given reason;\n\n 2) If pid is trapping exits, the exit signal is transformed into a message\n {'EXIT', from, reason} and delivered to the message queue of pid;\n\n 3) If reason is the atom `:normal`, pid will not exit. If it is trapping exits,\n the exit signal is transformed into a message {'EXIT', from, :normal} and\n delivered to its message queue;\n\n 4) If reason is the atom `:kill`, that is if `exit(pid, :kill)` is called, an\n untrappable exit signal is sent to pid which will unconditionally exit with\n exit reason `:killed`.\n\n ## Examples\n\n Process.exit(pid, :kill)\n\n \"\"\"\n @spec exit(pid, term) :: true\n def exit(pid, reason) do\n :erlang.exit(pid, reason)\n end\n\n @doc \"\"\"\n Returns the pid of a new process started by the application of `fun`.\n It behaves exactly the same as `Kernel.spawn\/1`.\n \"\"\"\n @spec spawn((() -> any)) :: pid\n def spawn(fun) do\n :erlang.spawn(fun)\n end\n\n @type spawn_opt :: :link | :monitor | {:priority, :low | :normal | :high} |\n {:fullsweep_after, non_neg_integer} |\n {:min_heap_size, non_neg_integer} |\n {:min_bin_vheap_size, non_neg_integer}\n @type spawn_opts :: [spawn_opt]\n\n @doc \"\"\"\n Returns the pid of a new process started by the application of `fun`.\n\n It also accepts extra options, for the list of available options\n check http:\/\/www.erlang.org\/doc\/man\/erlang.html#spawn_opt-2\n \"\"\"\n @spec spawn((() -> any), spawn_opts) :: pid | {pid, reference}\n def spawn(fun, opts) do\n :erlang.spawn_opt(fun, opts)\n end\n\n @doc \"\"\"\n Returns the pid of a new process started by the application of\n `module.function(args)`. The new process created will be placed in the system\n scheduler queue and be run some time later.\n\n It behaves exactly the same as the `Kernel.spawn\/3` function.\n \"\"\"\n @spec spawn(module, atom, [any]) :: pid\n def spawn(mod, fun, args) do\n :erlang.spawn(mod, fun, args)\n end\n\n @doc \"\"\"\n Returns the pid of a new process started by the application of\n `module.function(args)`. The new process created will be placed in the system\n scheduler queue and be run some time later.\n\n It also accepts extra options, for the list of available options\n check http:\/\/www.erlang.org\/doc\/man\/erlang.html#spawn_opt-4\n\n \"\"\"\n @spec spawn(module, atom, [any], spawn_opts) :: pid | {pid, reference}\n def spawn(mod, fun, args, opts) do\n :erlang.spawn_opt(mod, fun, args, opts)\n end\n\n @doc \"\"\"\n Returns the pid of a new process started by the application of `fun`.\n A link is created between the calling process and the new\n process, atomically.\n \"\"\"\n @spec spawn_link((() -> any)) :: pid\n def spawn_link(fun) do\n :erlang.spawn_link(fun)\n end\n\n @doc \"\"\"\n Returns the pid of a new process started by the application of\n `module.function(args)`. A link is created between the calling process\n and the new process, atomically. Otherwise works like spawn\/3.\n \"\"\"\n @spec spawn_link(module, atom, [any]) :: pid\n def spawn_link(mod, fun, args) do\n :erlang.spawn_link(mod, fun, args)\n end\n\n @doc \"\"\"\n Returns the pid of a new process started by the application of `fun`\n and reference for a monitor created to the new process.\n \"\"\"\n @spec spawn_monitor((() -> any)) :: {pid, reference}\n def spawn_monitor(fun) do\n :erlang.spawn_monitor(fun)\n end\n\n @doc \"\"\"\n A new process is started by the application of `module.function(args)`\n and the process is monitored at the same time. Returns the pid and a\n reference for the monitor. Otherwise works like spawn\/3.\n \"\"\"\n @spec spawn_monitor(module, atom, [any]) :: {pid, reference}\n def spawn_monitor(mod, fun, args) do\n :erlang.spawn_monitor(mod, fun, args)\n end\n\n @doc \"\"\"\n The calling process starts monitoring the item given.\n It returns the monitor reference.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#monitor-2 for more info.\n \"\"\"\n @spec monitor(pid | {reg_name :: atom, node :: atom} | reg_name :: atom) :: reference\n def monitor(item) do\n :erlang.monitor(:process, item)\n end\n\n @doc \"\"\"\n If monitor_ref is a reference which the calling process\n obtained by calling monitor\/1, this monitoring is turned off.\n If the monitoring is already turned off, nothing happens.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#demonitor-2 for more info.\n \"\"\"\n @spec demonitor(reference) :: true\n @spec demonitor(reference, options :: [:flush | :info]) :: boolean\n def demonitor(monitor_ref, options \/\/ []) do\n :erlang.demonitor(monitor_ref, options)\n end\n\n @doc \"\"\"\n Returns a list of process identifiers corresponding to all the\n processes currently existing on the local node.\n\n Note that a process that is exiting, exists but is not alive, i.e.,\n alive?\/1 will return false for a process that is exiting,\n but its process identifier will be part of the result returned.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#processes-0 for more info.\n \"\"\"\n @spec list :: [pid]\n def list do\n :erlang.processes()\n end\n\n @doc \"\"\"\n Creates a link between the calling process and another process\n (or port) `pid`, if there is not such a link already.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#link-1 for more info.\n \"\"\"\n @spec link(pid | port) :: true\n def link(pid) do\n :erlang.link(pid)\n end\n\n @doc \"\"\"\n Removes the link, if there is one, between the calling process and\n the process or port referred to by `pid`. Returns true and does not\n fail, even if there is no link or `id` does not exist\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#unlink-1 for more info.\n \"\"\"\n @spec unlink(pid | port) :: true\n def unlink(pid) do\n :erlang.unlink(pid)\n end\n\n @doc \"\"\"\n Associates the name with a pid or a port identifier. name, which must\n be an atom, can be used instead of the pid \/ port identifier in the\n send operator (name <- message).\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#register-2 for more info.\n \"\"\"\n @spec register(pid | port, atom) :: true\n def register(pid, name) do\n :erlang.register(name, pid)\n end\n\n @doc \"\"\"\n Removes the registered name, associated with a pid or a port identifier.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#unregister-1 for more info.\n \"\"\"\n @spec unregister(atom) :: true\n def unregister(name) do\n :erlang.unregister(name)\n end\n\n @doc \"\"\"\n Returns the pid or port identifier with the registered name.\n Returns undefined if the name is not registered.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#whereis-1 for more info.\n \"\"\"\n @spec whereis(atom) :: pid | port | nil\n def whereis(name) do\n nillify :erlang.whereis(name)\n end\n\n @doc \"\"\"\n Returns the pid of the group leader for the process which evaluates the function.\n \"\"\"\n @spec group_leader :: pid\n def group_leader do\n :erlang.group_leader\n end\n\n @doc \"\"\"\n Sets the group leader of Pid to GroupLeader. Typically, this is used when a processes\n started from a certain shell should have another group leader than `:init`.\n \"\"\"\n @spec group_leader(leader :: pid, pid) :: true\n def group_leader(leader, pid) do\n :erlang.group_leader(leader, pid)\n end\n\n @doc \"\"\"\n Returns a list of names which have been registered using register\/2.\n \"\"\"\n @spec registered :: [atom]\n def registered do\n :erlang.registered()\n end\n\n @typep process_flag :: :trap_exit | :error_handler | :min_heap_size |\n :min_bin_vheap_size | :priority | :save_calls |\n :sensitive\n @doc \"\"\"\n Sets certain flags for the process which calls this function.\n Returns the old value of the flag.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#process_flag-2 for more info.\n \"\"\"\n @spec flag(process_flag, term) :: term\n def flag(flag, value) do\n :erlang.process_flag(flag, value)\n end\n\n @doc \"\"\"\n Sets certain flags for the process Pid, in the same manner as flag\/2.\n Returns the old value of the flag. The allowed values for Flag are\n only a subset of those allowed in flag\/2, namely: save_calls.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#process_flag-3 for more info.\n \"\"\"\n @spec flag(pid, process_flag, term) :: term\n def flag(pid, flag, value) do\n :erlang.process_flag(pid, flag, value)\n end\n\n @doc \"\"\"\n Returns information about the process identified by pid.\n Use this only for debugging information.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#process_info-1 for more info.\n \"\"\"\n @spec info(pid) :: Keyword.t\n def info(pid) do\n :erlang.process_info(pid)\n end\n\n @doc \"\"\"\n Returns information about the process identified by pid\n or undefined if the process is not alive.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#process_info-2 for more info.\n \"\"\"\n @spec info(pid, atom) :: {atom, term}\n def info(pid, spec) do\n :erlang.process_info(pid, spec)\n end\n\n @compile { :inline, nillify: 1 }\n defp nillify(:undefined), do: nil\n defp nillify(other), do: other\nend\n","old_contents":"defmodule Process do\n @moduledoc \"\"\"\n This module provides convenience functions around processes and\n the process dictionary. In Erlang, most of these functions are\n auto-imported, but in Elixir they are grouped in a module for\n convenience. Notice that these functions, different from Erlang's,\n always return nil instead of undefined. You can use their Erlang\n version if you want the undefined value.\n \"\"\"\n\n @doc \"\"\"\n Returns true if the process exists and is alive, that is,\n is not exiting and has not exited. Otherwise, returns false.\n\n `pid` must refer to a process at the local node.\n \"\"\"\n @spec alive?(pid) :: boolean\n def alive?(pid) do\n :erlang.is_process_alive(pid)\n end\n\n @doc \"\"\"\n Returns all key-values in the dictionary.\n \"\"\"\n @spec get :: [{term, term}]\n def get do\n :erlang.get()\n end\n\n @doc \"\"\"\n Returns the value for the given key.\n \"\"\"\n @spec get(term) :: term\n @spec get(term, default :: term) :: term\n def get(key, default \/\/ nil) do\n case :erlang.get(key) do\n :undefined ->\n default\n value ->\n value\n end\n end\n\n @doc \"\"\"\n Returns all keys that have the given `value`.\n \"\"\"\n @spec get_keys(term) :: [term]\n def get_keys(value) do\n :erlang.get_keys(value)\n end\n\n @doc \"\"\"\n Stores the given key-value in the process dictionary.\n \"\"\"\n @spec put(term, term) :: term | nil\n def put(key, value) do\n nillify :erlang.put(key, value)\n end\n\n @doc \"\"\"\n Deletes all items in the dictionary.\n \"\"\"\n @spec delete :: [{term, term}]\n def delete() do\n :erlang.erase()\n end\n\n @doc \"\"\"\n Deletes the given key from the dictionary.\n \"\"\"\n @spec delete(term) :: term | nil\n def delete(key) do\n nillify :erlang.erase(key)\n end\n\n @doc \"\"\"\n Sends an exit signal with the given reason to the pid.\n\n The following behavior apply if reason is any term except `:normal` or `:kill`:\n\n 1) If pid is not trapping exits, pid itself will exist with the given reason;\n\n 2) If pid is trapping exits, the exit signal is transformed into a message\n {'EXIT', from, reason} and delivered to the message queue of pid;\n\n 3) If reason is the atom `:normal`, pid will not exit. If it is trapping exits,\n the exit signal is transformed into a message {'EXIT', from, :normal} and\n delivered to its message queue;\n\n 4) If reason is the atom `:kill`, that is if `exit(pid, :kill)` is called, an\n untrappable exit signal is sent to pid which will unconditionally exit with\n exit reason `:killed`.\n\n ## Examples\n\n Process.exit(pid, :kill)\n\n \"\"\"\n @spec exit(pid, term) :: true\n def exit(pid, reason) do\n :erlang.exit(pid, reason)\n end\n\n @doc \"\"\"\n Returns the pid of a new process started by the application of `fun`.\n It behaves exactly the same as `Kernel.spawn\/1`.\n \"\"\"\n @spec spawn((() -> any)) :: pid\n def spawn(fun) do\n :erlang.spawn(fun)\n end\n\n @type spawn_opt :: :link | :monitor | {:priority, :low | :normal | :high} |\n {:fullsweep_after, non_neg_integer} |\n {:min_heap_size, non_neg_integer} |\n {:min_bin_vheap_size, non_neg_integer}\n @type spawn_opts :: [spawn_opt]\n\n @doc \"\"\"\n Returns the pid of a new process started by the application of `fun`.\n\n It also accepts extra options, for the list of available options\n check http:\/\/www.erlang.org\/doc\/man\/erlang.html#spawn_opt-2\n \"\"\"\n @spec spawn((() -> any), spawn_opts) :: pid | {pid, reference}\n def spawn(fun, opts) do\n :erlang.spawn_opt(fun, opts)\n end\n\n @doc \"\"\"\n Returns the pid of a new process started by the application of\n `module.function(args)`. The new process created will be placed in the system\n scheduler queue and be run some time later.\n\n It behaves exactly the same as the `Kernel.spawn\/3` function.\n \"\"\"\n @spec spawn(module, atom, [any]) :: pid\n def spawn(mod, fun, args) do\n :erlang.spawn(mod, fun, args)\n end\n\n @doc \"\"\"\n Returns the pid of a new process started by the application of\n `module.function(args)`. The new process created will be placed in the system\n scheduler queue and be run some time later.\n\n It also accepts extra options, for the list of available options\n check http:\/\/www.erlang.org\/doc\/man\/erlang.html#spawn_opt-4\n\n \"\"\"\n @spec spawn(module, atom, [any], spawn_opts) :: pid | {pid, reference}\n def spawn(mod, fun, args, opts) do\n :erlang.spawn_opt(mod, fun, args, opts)\n end\n\n @doc \"\"\"\n Returns the pid of a new process started by the application of `fun`.\n A link is created between the calling process and the new\n process, atomically.\n \"\"\"\n @spec spawn_link((() -> any)) :: pid\n def spawn_link(fun) do\n :erlang.spawn_link(fun)\n end\n\n @doc \"\"\"\n Returns the pid of a new process started by the application of\n `module.function(args)`. A link is created between the calling process\n and the new process, atomically. Otherwise works like spawn\/3.\n \"\"\"\n @spec spawn_link(module, atom, [any]) :: pid\n def spawn_link(mod, fun, args) do\n :erlang.spawn_link(mod, fun, args)\n end\n\n @doc \"\"\"\n Returns the pid of a new process started by the application of `fun`\n and reference for a monitor created to the new process.\n \"\"\"\n @spec spawn_monitor((() -> any)) :: {pid, reference}\n def spawn_monitor(fun) do\n :erlang.spawn_monitor(fun)\n end\n\n @doc \"\"\"\n A new process is started by the application of `module.function(args)`\n and the process is monitored at the same time. Returns the pid and a\n reference for the monitor. Otherwise works like spawn\/3.\n \"\"\"\n @spec spawn_monitor(module, atom, [any]) :: {pid, reference}\n def spawn_monitor(mod, fun, args) do\n :erlang.spawn_monitor(mod, fun, args)\n end\n\n @doc \"\"\"\n The calling process starts monitoring the item given.\n It returns the monitor reference.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#monitor-2 for more info.\n \"\"\"\n @spec monitor(pid | {reg_name :: atom, node :: atom} | reg_name :: atom) :: reference\n def monitor(item) do\n :erlang.monitor(:process, item)\n end\n\n @doc \"\"\"\n If monitor_ref is a reference which the calling process\n obtained by calling monitor\/1, this monitoring is turned off.\n If the monitoring is already turned off, nothing happens.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#demonitor-2 for more info.\n \"\"\"\n @spec demonitor(reference) :: true\n @spec demonitor(reference, options :: [:flush | :info]) :: boolean\n def demonitor(monitor_ref, options \/\/ []) do\n :erlang.demonitor(monitor_ref, options)\n end\n\n @doc \"\"\"\n Returns a list of process identifiers corresponding to all the\n processes currently existing on the local node.\n\n Note that a process that is exiting, exists but is not alive, i.e.,\n alive?\/1 will return false for a process that is exiting,\n but its process identifier will be part of the result returned.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#processes-0 for more info.\n \"\"\"\n @spec list :: [pid]\n def list do\n :erlang.processes()\n end\n\n @doc \"\"\"\n Creates a link between the calling process and another process\n (or port) `pid`, if there is not such a link already.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#link-1 for more info.\n \"\"\"\n @spec link(pid | port) :: true\n def link(pid) do\n :erlang.link(pid)\n end\n\n @doc \"\"\"\n Removes the link, if there is one, between the calling process and\n the process or port referred to by `pid`. Returns true and does not\n fail, even if there is no link or `id` does not exist\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#unlink-1 for more info.\n \"\"\"\n @spec unlink(pid | port) :: true\n def unlink(pid) do\n :erlang.unlink(pid)\n end\n\n @doc \"\"\"\n Associates the name with a pid or a port identifier. name, which must\n be an atom, can be used instead of the pid \/ port identifier in the\n send operator (name <- message).\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#register-2 for more info.\n \"\"\"\n @spec register(pid | port, atom) :: true\n def register(pid, name) do\n :erlang.register(name, pid)\n end\n\n @doc \"\"\"\n Removes the registered name, associated with a pid or a port identifier.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#unregister-1 for more info.\n \"\"\"\n @spec unregister(atom) :: true\n def unregister(name) do\n :erlang.unregister(name)\n end\n\n @doc \"\"\"\n Returns the pid or port identifier with the registered name.\n Returns undefined if the name is not registered.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#whereis-1 for more info.\n \"\"\"\n @spec whereis(atom) :: pid | port | nil\n def whereis(name) do\n nillify :erlang.whereis(name)\n end\n\n @doc \"\"\"\n Returns the pid of the group leader for the process which evaluates the function.\n \"\"\"\n @spec group_leader :: pid\n def group_leader do\n :erlang.group_leader\n end\n\n @doc \"\"\"\n Sets the group leader of Pid to GroupLeader. Typically, this is used when a processes\n started from a certain shell should have another group leader than `:init`.\n \"\"\"\n @spec group_leader(leader :: pid, pid) :: true\n def group_leader(leader, pid) do\n :erlang.group_leader(leader, pid)\n end\n\n @doc \"\"\"\n Returns a list of names which have been registered using register\/2.\n \"\"\"\n @spec registered :: [atom]\n def registered do\n :erlang.registered()\n end\n\n @typep process_flag :: :trap_exit | :error_handler | :min_heap_size |\n :min_bin_vheap_size | :priority | :save_calls |\n :sensitive\n @doc \"\"\"\n Sets certain flags for the process which calls this function.\n Returns the old value of the flag.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#process_flag-2 for more info.\n \"\"\"\n @spec flag(process_flag, term) :: term\n def flag(flag, value) do\n :erlang.process_flag(flag, value)\n end\n\n @doc \"\"\"\n Sets certain flags for the process Pid, in the same manner as flag\/2.\n Returns the old value of the flag. The allowed values for Flag are\n only a subset of those allowed in flag\/2, namely: save_calls.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#process_flag-3 for more info.\n \"\"\"\n @spec flag(pid, process_flag, term) :: term\n def flag(pid, flag, value) do\n :erlang.process_flag(pid, flag, value)\n end\n\n @doc \"\"\"\n Returns information about the process identified by pid.\n Use this only for debugging information.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#process_info-1 for more info.\n \"\"\"\n @spec info(pid) :: Keyword.t\n def info(pid) do\n :erlang.process_info(pid)\n end\n\n @doc \"\"\"\n Returns information about the process identified by pid\n or undefined if the process is not alive.\n\n See http:\/\/www.erlang.org\/doc\/man\/erlang.html#process_info-2 for more info.\n \"\"\"\n @spec info(pid, atom) :: {atom, term}\n def info(pid, spec) do\n :erlang.process_info(pid, spec)\n end\n\n defp nillify(:undefined), do: nil\n defp nillify(other), do: other\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"ab3a6124acc2ee5e51b70b8af1f0607166401800","subject":"Fix compiler warning on Elixir 1.4","message":"Fix compiler warning on Elixir 1.4\n\nDict.merge calls now emit deprecation warnings.\n","repos":"obmarg\/kazan","old_file":"lib\/kazan\/codegen\/apis.ex","new_file":"lib\/kazan\/codegen\/apis.ex","new_contents":"defmodule Kazan.Codegen.Apis do\n @moduledoc false\n # Macros for generating API clients from OAI specs.\n import Kazan.Swagger, only: [swagger_to_op_map: 1]\n alias Kazan.Codegen.Apis.{Operation, Parameter}\n\n require EEx\n\n @doc \"\"\"\n Generates API client modules for all the operations defined in an OAPI spec.\n\n This reads the provided file at compile time and uses it to generate functions\n and their corresponding models.\n\n The modules will be defined by the tags for each of the operations, and the\n functions will be named using a camel case version of the operationId.\n\n Currently the operationId has some tag-related data embedded in it, which we\n remove for the sake of brevity.\n \"\"\"\n defmacro from_spec(spec_file) do\n api_groups =\n File.read!(spec_file)\n |> Poison.decode!\n |> swagger_to_op_map\n |> Map.values\n |> Enum.flat_map(&duplicate_on_tags\/1)\n |> Enum.map(&Operation.from_oai_desc\/1)\n |> Enum.group_by(fn (op) -> op.api_name end)\n\n module_forms = for {module_name, functions} <- api_groups do\n function_forms = Enum.map(functions, &function_form\/1)\n module_doc = module_doc(module_name)\n\n quote do\n defmodule unquote(module_name) do\n @moduledoc unquote(module_doc)\n\n unquote_splicing(function_forms)\n end\n end\n end\n\n quote do\n @external_resource unquote(spec_file)\n\n unquote_splicing(module_forms)\n end\n end\n\n @doc \"\"\"\n Builds an api_name from a tag on an OAI operation.\n \"\"\"\n @spec api_name(String.t) :: atom\n def api_name(operation_tag) do\n api_name = Macro.camelize(operation_tag)\n Module.concat(Kazan.Apis, api_name)\n end\n\n @doc \"\"\"\n Builds a function name from the operationId of an OAI operation.\n\n We take the operation tag in here too, because the Kube OAI operations use IDs\n like listCoreV1ConfigMapForAllNamespaces where the operation is on the core_v1\n API. We don't want to have such large function names, so we try to strip the\n API name out.\n \"\"\"\n @spec function_name(String.t, String.t | atom) :: atom\n def function_name(operation_id, tag) when is_binary(tag) do\n operation_id\n |> String.replace(Macro.camelize(tag), \"\")\n |> Macro.underscore\n |> String.to_atom\n end\n\n # Swagger tags are a list. There _appears_ to only be one tag per operation,\n # but there could be more. We handle that by duplicating on tags.\n # Once this function is finished, we will have a bunch of operations with a\n # single tag.\n @spec duplicate_on_tags(Map.t) :: [Map.t]\n defp duplicate_on_tags(operation) do\n for tag <- operation[\"tags\"] do\n operation |> Map.put(\"tag\", tag) |> Map.delete(\"tags\")\n end\n end\n\n # Builds the quoted function form for an operation function.\n @spec function_form(Operation.t) :: term\n defp function_form(operation) do\n param_groups = Enum.group_by(\n operation.parameters,\n fn (param) -> param.type end\n )\n\n is_required = fn (param) -> param.required end\n query_params = Map.get(param_groups, :query, [])\n\n path_params =\n param_groups |> Map.get(:path, []) |> sort_path_params(operation.path)\n\n # The main arguments our function will take:\n argument_params =\n Map.get(param_groups, :body, [])\n ++ path_params\n ++ Enum.filter(query_params, is_required)\n\n optional_params = Enum.reject(query_params, is_required)\n\n arguments = argument_forms(argument_params, optional_params)\n docs = function_docs(\n operation.description, argument_params, optional_params,\n operation.response_schema\n )\n\n param_unpacking = if Enum.empty?(argument_params) do\n quote do\n %{}\n end\n else\n argument_map_pairs = for arg <- argument_params do\n {arg.var_name, Macro.var(arg.var_name, __MODULE__)}\n end\n quote location: :keep do\n %{unquote_splicing(argument_map_pairs)}\n end\n end\n\n option_merging = cond do\n Enum.empty?(optional_params) ->\n quote do\n end\n Enum.empty?(argument_params) ->\n quote location: :keep do\n Enum.into(options, %{})\n end\n :otherwise ->\n quote location: :keep do\n Map.merge(Enum.into(options, %{}), params)\n end\n end\n\n transform_map = for parameter <- operation.parameters, into: %{} do\n {parameter.var_name, parameter.field_name}\n end\n\n bang_function_name = String.to_atom(\n Atom.to_string(operation.function_name) <> \"!\"\n )\n argument_forms_in_call = argument_call_forms(\n argument_params, optional_params\n )\n\n quote location: :keep do\n @doc unquote(docs)\n def unquote(operation.function_name)(unquote_splicing(arguments)) do\n params = unquote(param_unpacking)\n params = unquote(option_merging)\n {:ok, req} = Kazan.Request.create(\n unquote(operation.operation_id),\n Kazan.Codegen.Apis.transform_request_parameters(\n unquote(Macro.escape(transform_map)),\n params\n )\n )\n end\n\n @doc unquote(docs)\n def unquote(bang_function_name)(unquote_splicing(arguments)) do\n rv = unquote(operation.function_name)(\n unquote_splicing(argument_forms_in_call)\n )\n case rv do\n {:ok, result} -> result\n {:err, reason} ->\n raise Kazan.BuildRequestError,\n reason: reason, operation: unquote(operation.function_name)\n end\n end\n end\n end\n\n # Transforms a map of function arguments into a map of request parameters.\n def transform_request_parameters(parameter_descs, parameters) do\n for {k, v} <- parameters, into: %{} do\n {parameter_descs[k], v}\n end\n end\n\n # List of argument forms to go in function argument lists.\n @spec argument_forms([Map.t], [Map.t]) :: [term]\n defp argument_forms(argument_params, []) do\n for param <- argument_params do\n Macro.var(param.var_name, __MODULE__)\n end\n end\n defp argument_forms(argument_params, _optional_params) do\n argument_forms(argument_params, [])\n ++ [{:\\\\, [], [Macro.var(:options, __MODULE__), []]}]\n end\n\n # List of arugment forms to go in call to function from bang function.\n @spec argument_call_forms([Map.t], [Map.t]) :: [term]\n defp argument_call_forms(argument_params, []) do\n for param <- argument_params do\n Macro.var(param.var_name, __MODULE__)\n end\n end\n defp argument_call_forms(argument_params, _optional_params) do\n argument_forms(argument_params, [])\n ++ [Macro.var(:options, __MODULE__)]\n end\n\n # The Kube API specs provide path parameters in an unintuitive order,\n # so we sort them by the order they appear in the request path here.\n @spec sort_path_params([Parameter.t], String.t) :: [Parameter.t]\n defp sort_path_params(parameters, path) do\n Enum.sort(parameters, fn (param1, param2) ->\n loc1 = str_index(\"{#{param1.field_name}}\", path)\n loc2 = str_index(\"{#{param2.field_name}}\", path)\n loc1 <= loc2\n end)\n end\n\n # I can't believe I'm having to implement this myself :\/\n defp str_index(needle, haystack) do\n case String.split(haystack, needle, parts: 2) do\n [left, _] -> String.length(left)\n [_] -> nil\n end\n end\n\n EEx.function_from_string(:defp, :function_docs, \"\"\"\n <%= if description do description end %>\n\n <%= unless Enum.empty?(parameters) do %>\n ### Parameters\n\n <%= for param <- parameters do %>\n * `<%= param.var_name %>` - <%= param.description %><%= if param.schema do %>See `<%= doc_ref(param.schema) %>`. <% end %> <% end %>\n <% end %>\n\n <%= unless Enum.empty?(options) do %>\n\n ### Options\n\n <%= for option <- options do %>\n * `<%= option.var_name %>` - <%= option.description %>\n <% end %>\n <% end %>\n\n <%= if response_schema do %>\n ### Response\n\n See `<%= doc_ref(response_schema) %>`\n <% end %>\n\n \"\"\", [:description, :parameters, :options, :response_schema])\n\n defp module_doc(module_name) do\n module_name =\n module_name |> Atom.to_string |> String.split(\".\") |> List.last\n \"\"\"\n Contains functions for the #{module_name} API.\n\n Each of these functions will output a Kazan.Request suitable for passing to\n Kazan.Client.\n \"\"\"\n end\n\n # Strips the `Elixir.` prefix from an atom for use in documentation.\n # Atoms will not be linked if they include the Elixir. prefix.\n defp doc_ref(str) do\n str |> Atom.to_string |> String.replace(~r\/^Elixir.\/, \"\")\n end\nend\n","old_contents":"defmodule Kazan.Codegen.Apis do\n @moduledoc false\n # Macros for generating API clients from OAI specs.\n import Kazan.Swagger, only: [swagger_to_op_map: 1]\n alias Kazan.Codegen.Apis.{Operation, Parameter}\n\n require EEx\n\n @doc \"\"\"\n Generates API client modules for all the operations defined in an OAPI spec.\n\n This reads the provided file at compile time and uses it to generate functions\n and their corresponding models.\n\n The modules will be defined by the tags for each of the operations, and the\n functions will be named using a camel case version of the operationId.\n\n Currently the operationId has some tag-related data embedded in it, which we\n remove for the sake of brevity.\n \"\"\"\n defmacro from_spec(spec_file) do\n api_groups =\n File.read!(spec_file)\n |> Poison.decode!\n |> swagger_to_op_map\n |> Map.values\n |> Enum.flat_map(&duplicate_on_tags\/1)\n |> Enum.map(&Operation.from_oai_desc\/1)\n |> Enum.group_by(fn (op) -> op.api_name end)\n\n module_forms = for {module_name, functions} <- api_groups do\n function_forms = Enum.map(functions, &function_form\/1)\n module_doc = module_doc(module_name)\n\n quote do\n defmodule unquote(module_name) do\n @moduledoc unquote(module_doc)\n\n unquote_splicing(function_forms)\n end\n end\n end\n\n quote do\n @external_resource unquote(spec_file)\n\n unquote_splicing(module_forms)\n end\n end\n\n @doc \"\"\"\n Builds an api_name from a tag on an OAI operation.\n \"\"\"\n @spec api_name(String.t) :: atom\n def api_name(operation_tag) do\n api_name = Macro.camelize(operation_tag)\n Module.concat(Kazan.Apis, api_name)\n end\n\n @doc \"\"\"\n Builds a function name from the operationId of an OAI operation.\n\n We take the operation tag in here too, because the Kube OAI operations use IDs\n like listCoreV1ConfigMapForAllNamespaces where the operation is on the core_v1\n API. We don't want to have such large function names, so we try to strip the\n API name out.\n \"\"\"\n @spec function_name(String.t, String.t | atom) :: atom\n def function_name(operation_id, tag) when is_binary(tag) do\n operation_id\n |> String.replace(Macro.camelize(tag), \"\")\n |> Macro.underscore\n |> String.to_atom\n end\n\n # Swagger tags are a list. There _appears_ to only be one tag per operation,\n # but there could be more. We handle that by duplicating on tags.\n # Once this function is finished, we will have a bunch of operations with a\n # single tag.\n @spec duplicate_on_tags(Map.t) :: [Map.t]\n defp duplicate_on_tags(operation) do\n for tag <- operation[\"tags\"] do\n operation |> Map.put(\"tag\", tag) |> Map.delete(\"tags\")\n end\n end\n\n # Builds the quoted function form for an operation function.\n @spec function_form(Operation.t) :: term\n defp function_form(operation) do\n param_groups = Enum.group_by(\n operation.parameters,\n fn (param) -> param.type end\n )\n\n is_required = fn (param) -> param.required end\n query_params = Map.get(param_groups, :query, [])\n\n path_params =\n param_groups |> Map.get(:path, []) |> sort_path_params(operation.path)\n\n # The main arguments our function will take:\n argument_params =\n Map.get(param_groups, :body, [])\n ++ path_params\n ++ Enum.filter(query_params, is_required)\n\n optional_params = Enum.reject(query_params, is_required)\n\n arguments = argument_forms(argument_params, optional_params)\n docs = function_docs(\n operation.description, argument_params, optional_params,\n operation.response_schema\n )\n\n param_unpacking = if Enum.empty?(argument_params) do\n quote do\n %{}\n end\n else\n argument_map_pairs = for arg <- argument_params do\n {arg.var_name, Macro.var(arg.var_name, __MODULE__)}\n end\n quote location: :keep do\n %{unquote_splicing(argument_map_pairs)}\n end\n end\n\n option_merging = cond do\n Enum.empty?(optional_params) ->\n quote do\n end\n Enum.empty?(argument_params) ->\n quote location: :keep do\n Enum.into(options, %{})\n end\n :otherwise ->\n quote location: :keep do\n Dict.merge(Enum.into(options, %{}), params)\n end\n end\n\n transform_map = for parameter <- operation.parameters, into: %{} do\n {parameter.var_name, parameter.field_name}\n end\n\n bang_function_name = String.to_atom(\n Atom.to_string(operation.function_name) <> \"!\"\n )\n argument_forms_in_call = argument_call_forms(\n argument_params, optional_params\n )\n\n quote location: :keep do\n @doc unquote(docs)\n def unquote(operation.function_name)(unquote_splicing(arguments)) do\n params = unquote(param_unpacking)\n params = unquote(option_merging)\n {:ok, req} = Kazan.Request.create(\n unquote(operation.operation_id),\n Kazan.Codegen.Apis.transform_request_parameters(\n unquote(Macro.escape(transform_map)),\n params\n )\n )\n end\n\n @doc unquote(docs)\n def unquote(bang_function_name)(unquote_splicing(arguments)) do\n rv = unquote(operation.function_name)(\n unquote_splicing(argument_forms_in_call)\n )\n case rv do\n {:ok, result} -> result\n {:err, reason} ->\n raise Kazan.BuildRequestError,\n reason: reason, operation: unquote(operation.function_name)\n end\n end\n end\n end\n\n # Transforms a map of function arguments into a map of request parameters.\n def transform_request_parameters(parameter_descs, parameters) do\n for {k, v} <- parameters, into: %{} do\n {parameter_descs[k], v}\n end\n end\n\n # List of argument forms to go in function argument lists.\n @spec argument_forms([Map.t], [Map.t]) :: [term]\n defp argument_forms(argument_params, []) do\n for param <- argument_params do\n Macro.var(param.var_name, __MODULE__)\n end\n end\n defp argument_forms(argument_params, _optional_params) do\n argument_forms(argument_params, [])\n ++ [{:\\\\, [], [Macro.var(:options, __MODULE__), []]}]\n end\n\n # List of arugment forms to go in call to function from bang function.\n @spec argument_call_forms([Map.t], [Map.t]) :: [term]\n defp argument_call_forms(argument_params, []) do\n for param <- argument_params do\n Macro.var(param.var_name, __MODULE__)\n end\n end\n defp argument_call_forms(argument_params, _optional_params) do\n argument_forms(argument_params, [])\n ++ [Macro.var(:options, __MODULE__)]\n end\n\n # The Kube API specs provide path parameters in an unintuitive order,\n # so we sort them by the order they appear in the request path here.\n @spec sort_path_params([Parameter.t], String.t) :: [Parameter.t]\n defp sort_path_params(parameters, path) do\n Enum.sort(parameters, fn (param1, param2) ->\n loc1 = str_index(\"{#{param1.field_name}}\", path)\n loc2 = str_index(\"{#{param2.field_name}}\", path)\n loc1 <= loc2\n end)\n end\n\n # I can't believe I'm having to implement this myself :\/\n defp str_index(needle, haystack) do\n case String.split(haystack, needle, parts: 2) do\n [left, _] -> String.length(left)\n [_] -> nil\n end\n end\n\n EEx.function_from_string(:defp, :function_docs, \"\"\"\n <%= if description do description end %>\n\n <%= unless Enum.empty?(parameters) do %>\n ### Parameters\n\n <%= for param <- parameters do %>\n * `<%= param.var_name %>` - <%= param.description %><%= if param.schema do %>See `<%= doc_ref(param.schema) %>`. <% end %> <% end %>\n <% end %>\n\n <%= unless Enum.empty?(options) do %>\n\n ### Options\n\n <%= for option <- options do %>\n * `<%= option.var_name %>` - <%= option.description %>\n <% end %>\n <% end %>\n\n <%= if response_schema do %>\n ### Response\n\n See `<%= doc_ref(response_schema) %>`\n <% end %>\n\n \"\"\", [:description, :parameters, :options, :response_schema])\n\n defp module_doc(module_name) do\n module_name =\n module_name |> Atom.to_string |> String.split(\".\") |> List.last\n \"\"\"\n Contains functions for the #{module_name} API.\n\n Each of these functions will output a Kazan.Request suitable for passing to\n Kazan.Client.\n \"\"\"\n end\n\n # Strips the `Elixir.` prefix from an atom for use in documentation.\n # Atoms will not be linked if they include the Elixir. prefix.\n defp doc_ref(str) do\n str |> Atom.to_string |> String.replace(~r\/^Elixir.\/, \"\")\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"362cbf77c008d08eebdb05e553ebac95b28a592e","subject":"Rename function. format_result() -> inspirational_quote()","message":"Rename function. format_result() -> inspirational_quote()\n","repos":"elixirkoans\/elixir-koans,samstarling\/elixir-koans","old_file":"lib\/koans\/13_functions.ex","new_file":"lib\/koans\/13_functions.ex","new_contents":"defmodule Functions do\n use Koans\n\n @intro \"Functions\"\n\n def greet(name) do\n \"Hello, #{name}!\"\n end\n\n koan \"Functions map arguments to outputs\" do\n assert greet(\"World\") == ___\n end\n\n def multiply(a, b), do: a * b\n\n koan \"Single line functions are cool, but mind the comma and the colon!\" do\n assert 6 == multiply(2, ___)\n end\n\n def first(foo, bar), do: \"#{foo} and #{bar}\"\n def first(foo), do: \"Only #{foo}\"\n\n koan \"Functions with the same name are distinguished by the number of arguments they take\" do\n assert first(\"One\", \"Two\") == ___\n assert first(\"One\") == ___\n end\n\n def repeat_again(message, times \\\\ 5) do\n String.duplicate(message, times)\n end\n\n koan \"Functions can have default argument values\" do\n assert repeat_again(\"Hello \") == ___\n assert repeat_again(\"Hello \", 2) == ___\n end\n\n def sum_up(thing) when is_list(thing), do: :entire_list\n def sum_up(_thing), do: :single_thing\n\n koan \"Functions can have guard expressions\" do\n assert sum_up([1, 2, 3]) == ___\n assert sum_up(1) == ___\n end\n\n def bigger(a, b) when a > b, do: \"#{a} is bigger than #{b}\"\n def bigger(a, b) when a <= b, do: \"#{a} is not bigger than #{b}\"\n\n koan \"Intricate guards are possible, but be mindful of the reader\" do\n assert bigger(10, 5) == ___\n assert bigger(4, 27) == ___\n end\n\n def get_number(0), do: \"The number was zero\"\n def get_number(number), do: \"The number was #{number}\"\n\n koan \"For simpler cases, pattern matching is effective\" do\n assert get_number(0) == ___\n assert get_number(5) == ___\n end\n\n koan \"Little anonymous functions are common, and called with a dot\" do\n multiply = fn a, b -> a * b end\n assert multiply.(2, 3) == ___\n end\n\n koan \"You can even go shorter, by using capture syntax `&()` and positional arguments\" do\n multiply = &(&1 * &2)\n assert multiply.(2, 3) == ___\n end\n\n koan \"Prefix a string with & to build a simple anonymous greet function\" do\n greet = &\"Hi, #{&1}!\"\n assert greet.(\"Foo\") == ___\n end\n\n koan \"You can build anonymous functions out of any elixir expression by prefixing it with &\" do\n three_times = &[&1, &1, &1]\n assert three_times.(\"foo\") == ___\n end\n\n koan \"You can use pattern matching to define multiple cases for anonymous functions\" do\n inspirational_quote = fn\n {:ok, result} -> \"Success is #{result}\"\n {:error, reason} -> \"You just lost #{reason}\"\n end\n\n assert inspirational_quote.({:ok, \"no accident\"}) == ___\n assert inspirational_quote.({:error, \"the game\"}) == ___\n end\n\n def times_five_and_then(number, fun), do: fun.(number * 5)\n def square(number), do: number * number\n\n koan \"You can pass functions around as arguments. Place an '&' before the name and state the arity\" do\n assert times_five_and_then(2, &square\/1) == ___\n end\n\n koan \"The '&' operation is not needed for anonymous functions\" do\n cube = fn number -> number * number * number end\n assert times_five_and_then(2, cube) == ___\n end\n\n koan \"The result of a function can be piped into another function as its first argument\" do\n result =\n \"full-name\"\n |> String.split(\"-\")\n |> Enum.map(&String.capitalize\/1)\n |> Enum.join(\" \")\n\n assert result == ___\n end\n\n koan \"Conveniently keyword lists can be used for function options\" do\n transform = fn str, opts ->\n if opts[:upcase] do\n String.upcase(str)\n else\n str\n end\n end\n\n assert transform.(\"good\", upcase: true) == ___\n assert transform.(\"good\", upcase: false) == ___\n end\nend\n","old_contents":"defmodule Functions do\n use Koans\n\n @intro \"Functions\"\n\n def greet(name) do\n \"Hello, #{name}!\"\n end\n\n koan \"Functions map arguments to outputs\" do\n assert greet(\"World\") == ___\n end\n\n def multiply(a, b), do: a * b\n\n koan \"Single line functions are cool, but mind the comma and the colon!\" do\n assert 6 == multiply(2, ___)\n end\n\n def first(foo, bar), do: \"#{foo} and #{bar}\"\n def first(foo), do: \"Only #{foo}\"\n\n koan \"Functions with the same name are distinguished by the number of arguments they take\" do\n assert first(\"One\", \"Two\") == ___\n assert first(\"One\") == ___\n end\n\n def repeat_again(message, times \\\\ 5) do\n String.duplicate(message, times)\n end\n\n koan \"Functions can have default argument values\" do\n assert repeat_again(\"Hello \") == ___\n assert repeat_again(\"Hello \", 2) == ___\n end\n\n def sum_up(thing) when is_list(thing), do: :entire_list\n def sum_up(_thing), do: :single_thing\n\n koan \"Functions can have guard expressions\" do\n assert sum_up([1, 2, 3]) == ___\n assert sum_up(1) == ___\n end\n\n def bigger(a, b) when a > b, do: \"#{a} is bigger than #{b}\"\n def bigger(a, b) when a <= b, do: \"#{a} is not bigger than #{b}\"\n\n koan \"Intricate guards are possible, but be mindful of the reader\" do\n assert bigger(10, 5) == ___\n assert bigger(4, 27) == ___\n end\n\n def get_number(0), do: \"The number was zero\"\n def get_number(number), do: \"The number was #{number}\"\n\n koan \"For simpler cases, pattern matching is effective\" do\n assert get_number(0) == ___\n assert get_number(5) == ___\n end\n\n koan \"Little anonymous functions are common, and called with a dot\" do\n multiply = fn a, b -> a * b end\n assert multiply.(2, 3) == ___\n end\n\n koan \"You can even go shorter, by using capture syntax `&()` and positional arguments\" do\n multiply = &(&1 * &2)\n assert multiply.(2, 3) == ___\n end\n\n koan \"Prefix a string with & to build a simple anonymous greet function\" do\n greet = &\"Hi, #{&1}!\"\n assert greet.(\"Foo\") == ___\n end\n\n koan \"You can build anonymous functions out of any elixir expression by prefixing it with &\" do\n three_times = &[&1, &1, &1]\n assert three_times.(\"foo\") == ___\n end\n\n koan \"You can use pattern matching to define multiple cases for anonymous functions\" do\n format_result = fn\n {:ok, result} -> \"Success is #{result}\"\n {:error, reason} -> \"You just lost #{reason}\"\n end\n\n assert format_result.({:ok, \"no accident\"}) == ___\n assert format_result.({:error, \"the game\"}) == ___\n end\n\n def times_five_and_then(number, fun), do: fun.(number * 5)\n def square(number), do: number * number\n\n koan \"You can pass functions around as arguments. Place an '&' before the name and state the arity\" do\n assert times_five_and_then(2, &square\/1) == ___\n end\n\n koan \"The '&' operation is not needed for anonymous functions\" do\n cube = fn number -> number * number * number end\n assert times_five_and_then(2, cube) == ___\n end\n\n koan \"The result of a function can be piped into another function as its first argument\" do\n result =\n \"full-name\"\n |> String.split(\"-\")\n |> Enum.map(&String.capitalize\/1)\n |> Enum.join(\" \")\n\n assert result == ___\n end\n\n koan \"Conveniently keyword lists can be used for function options\" do\n transform = fn str, opts ->\n if opts[:upcase] do\n String.upcase(str)\n else\n str\n end\n end\n\n assert transform.(\"good\", upcase: true) == ___\n assert transform.(\"good\", upcase: false) == ___\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"f534d1dc9654a80b86079b7a55df02b46c1a06b8","subject":"Fix typo","message":"Fix typo","repos":"elixirkoans\/elixir-koans,samstarling\/elixir-koans","old_file":"lib\/koans\/18_protocols.ex","new_file":"lib\/koans\/18_protocols.ex","new_contents":"defmodule Protocols do\n use Koans\n\n @intro \"Want to follow the rules? Adhere to the protocol!\"\n\n defprotocol School, do: def enrol(person)\n\n defimpl School, for: Any do\n def enrol(_) do\n \"Pupil enrolled at school\"\n end\n end\n\n defmodule Student do\n @derive School\n defstruct name: \"\"\n end\n\n defmodule Musician, do: defstruct name: \"\", instrument: \"\"\n defmodule Dancer, do: defstruct name: \"\", dance_style: \"\"\n defmodule Baker, do: defstruct name: \"\"\n\n defimpl School, for: Musician do\n def enrol(musician) do\n \"#{musician.name} signed up for #{musician.instrument}\"\n end\n end\n\n defimpl School, for: Dancer do\n def enrol(dancer), do: \"#{dancer.name} enrolled for #{dancer.dance_style}\"\n end\n\n koan \"Sharing an interface is the secret at school\" do\n musician = %Musician{name: \"Andre\", instrument: \"violin\"}\n dancer = %Dancer{name: \"Darcy\", dance_style: \"ballet\"}\n\n assert School.enrol(musician) == ___\n assert School.enrol(dancer) == ___\n end\n\n koan \"Sometimes we all use the same\" do\n student = %Student{name: \"Emily\"}\n assert School.enrol(student) == ___\n end\n\n koan \"If you don't comply you can't get in\" do\n assert_raise ___, fn ->\n School.enrol(%Baker{name: \"Delia\"})\n end\n end\nend\n","old_contents":"defmodule Protocols do\n use Koans\n\n @intro \"Wan't to follow the rules? Adhere to the protocol!\"\n\n defprotocol School, do: def enrol(person)\n\n defimpl School, for: Any do\n def enrol(_) do\n \"Pupil enrolled at school\"\n end\n end\n\n defmodule Student do\n @derive School\n defstruct name: \"\"\n end\n\n defmodule Musician, do: defstruct name: \"\", instrument: \"\"\n defmodule Dancer, do: defstruct name: \"\", dance_style: \"\"\n defmodule Baker, do: defstruct name: \"\"\n\n defimpl School, for: Musician do\n def enrol(musician) do\n \"#{musician.name} signed up for #{musician.instrument}\"\n end\n end\n\n defimpl School, for: Dancer do\n def enrol(dancer), do: \"#{dancer.name} enrolled for #{dancer.dance_style}\"\n end\n\n koan \"Sharing an interface is the secret at school\" do\n musician = %Musician{name: \"Andre\", instrument: \"violin\"}\n dancer = %Dancer{name: \"Darcy\", dance_style: \"ballet\"}\n\n assert School.enrol(musician) == ___\n assert School.enrol(dancer) == ___\n end\n\n koan \"Sometimes we all use the same\" do\n student = %Student{name: \"Emily\"}\n assert School.enrol(student) == ___\n end\n\n koan \"If you don't comply you can't get in\" do\n assert_raise ___, fn ->\n School.enrol(%Baker{name: \"Delia\"})\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"3a39923c6d61af7173942514201c7a7074e866d5","subject":"fix enum_to_spec warning","message":"fix enum_to_spec warning\n","repos":"tony612\/protobuf-elixir","old_file":"lib\/protobuf\/type_util.ex","new_file":"lib\/protobuf\/type_util.ex","new_contents":"defmodule Protobuf.TypeUtil do\n def from_enum(:TYPE_DOUBLE), do: :double\n def from_enum(:TYPE_FLOAT), do: :float\n def from_enum(:TYPE_INT64), do: :int64\n def from_enum(:TYPE_UINT64), do: :uint64\n def from_enum(:TYPE_INT32), do: :int32\n def from_enum(:TYPE_FIXED64), do: :fixed64\n def from_enum(:TYPE_FIXED32), do: :fixed32\n def from_enum(:TYPE_BOOL), do: :bool\n def from_enum(:TYPE_STRING), do: :string\n def from_enum(:TYPE_GROUP), do: :group\n def from_enum(:TYPE_MESSAGE), do: :message\n def from_enum(:TYPE_BYTES), do: :bytes\n def from_enum(:TYPE_UINT32), do: :uint32\n def from_enum(:TYPE_ENUM), do: :enum\n def from_enum(:TYPE_SFIXED32), do: :sfixed32\n def from_enum(:TYPE_SFIXED64), do: :sfixed64\n def from_enum(:TYPE_SINT32), do: :sint32\n def from_enum(:TYPE_SINT64), do: :sint64\n\n def enum_to_spec(:TYPE_DOUBLE), do: \"float\"\n def enum_to_spec(:TYPE_FLOAT), do: \"float\"\n def enum_to_spec(:TYPE_INT64), do: \"integer\"\n def enum_to_spec(:TYPE_UINT64), do: \"non_neg_integer\"\n def enum_to_spec(:TYPE_INT32), do: \"integer\"\n def enum_to_spec(:TYPE_FIXED64), do: \"non_neg_integer\"\n def enum_to_spec(:TYPE_FIXED32), do: \"non_neg_integer\"\n def enum_to_spec(:TYPE_BOOL), do: \"boolean\"\n def enum_to_spec(:TYPE_STRING), do: \"String.t\"\n def enum_to_spec(:TYPE_BYTES), do: \"binary\"\n def enum_to_spec(:TYPE_UINT32), do: \"non_neg_integer\"\n def enum_to_spec(:TYPE_ENUM), do: \"integer\"\n def enum_to_spec(:TYPE_SFIXED32), do: \"integer\"\n def enum_to_spec(:TYPE_SFIXED64), do: \"integer\"\n def enum_to_spec(:TYPE_SINT32), do: \"integer\"\n def enum_to_spec(:TYPE_SINT64), do: \"integer\"\n def enum_to_spec(_), do: \"any\"\n def enum_to_spec(:TYPE_MESSAGE, type, true = _repeated), do: \"#{type}.t\"\n def enum_to_spec(:TYPE_MESSAGE, type, false = _repeated), do: \"#{type}.t | nil\"\nend\n","old_contents":"defmodule Protobuf.TypeUtil do\n def from_enum(:TYPE_DOUBLE), do: :double\n def from_enum(:TYPE_FLOAT), do: :float\n def from_enum(:TYPE_INT64), do: :int64\n def from_enum(:TYPE_UINT64), do: :uint64\n def from_enum(:TYPE_INT32), do: :int32\n def from_enum(:TYPE_FIXED64), do: :fixed64\n def from_enum(:TYPE_FIXED32), do: :fixed32\n def from_enum(:TYPE_BOOL), do: :bool\n def from_enum(:TYPE_STRING), do: :string\n def from_enum(:TYPE_GROUP), do: :group\n def from_enum(:TYPE_MESSAGE), do: :message\n def from_enum(:TYPE_BYTES), do: :bytes\n def from_enum(:TYPE_UINT32), do: :uint32\n def from_enum(:TYPE_ENUM), do: :enum\n def from_enum(:TYPE_SFIXED32), do: :sfixed32\n def from_enum(:TYPE_SFIXED64), do: :sfixed64\n def from_enum(:TYPE_SINT32), do: :sint32\n def from_enum(:TYPE_SINT64), do: :sint64\n\n def enum_to_spec(:TYPE_DOUBLE), do: \"float\"\n def enum_to_spec(:TYPE_FLOAT), do: \"float\"\n def enum_to_spec(:TYPE_INT64), do: \"integer\"\n def enum_to_spec(:TYPE_UINT64), do: \"non_neg_integer\"\n def enum_to_spec(:TYPE_INT32), do: \"integer\"\n def enum_to_spec(:TYPE_FIXED64), do: \"non_neg_integer\"\n def enum_to_spec(:TYPE_FIXED32), do: \"non_neg_integer\"\n def enum_to_spec(:TYPE_BOOL), do: \"boolean\"\n def enum_to_spec(:TYPE_STRING), do: \"String.t\"\n def enum_to_spec(:TYPE_BYTES), do: \"binary\"\n def enum_to_spec(:TYPE_UINT32), do: \"non_neg_integer\"\n def enum_to_spec(:TYPE_ENUM), do: \"integer\"\n def enum_to_spec(:TYPE_SFIXED32), do: \"integer\"\n def enum_to_spec(:TYPE_SFIXED64), do: \"integer\"\n def enum_to_spec(:TYPE_SINT32), do: \"integer\"\n def enum_to_spec(:TYPE_SINT64), do: \"integer\"\n def enum_to_spec(:TYPE_MESSAGE, type, true = _repeated), do: \"#{type}.t\"\n def enum_to_spec(:TYPE_MESSAGE, type, false = _repeated), do: \"#{type}.t | nil\"\n def enum_to_spec(_), do: \"any\"\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"0bab05b4df7698b5b9f3164accf44c1d3ec7eabb","subject":"dot in mint docs","message":"dot in mint docs\n","repos":"teamon\/tesla,monterail\/tesla","old_file":"lib\/tesla\/adapter\/mint.ex","new_file":"lib\/tesla\/adapter\/mint.ex","new_contents":"if Code.ensure_loaded?(Mint.HTTP) do\n defmodule Tesla.Adapter.Mint do\n @moduledoc \"\"\"\n Adapter for [mint](https:\/\/github.com\/elixir-mint\/mint).\n\n Caution: The minimum supported Elixir version for mint is 1.5.0\n\n Remember to add `{:mint, \"~> 1.0\"}` and `{:castore, \"~> 0.1\"}` to dependencies.\n Also, you need to recompile tesla after adding `:mint` dependency:\n\n ```\n mix deps.clean tesla\n mix deps.compile tesla\n ```\n\n ## Example usage\n\n ```\n # set globally in config\/config.exs\n config :tesla, :adapter, Tesla.Adapter.Mint\n # set per module\n defmodule MyClient do\n use Tesla\n adapter Tesla.Adapter.Mint\n end\n # set global custom cacertfile\n config :tesla, Tesla.Adapter.Mint, cacert: [\"path_to_cacert\"]\n ```\n\n ## Adapter specific options:\n\n - `:timeout` - Time in milliseconds, while process, will wait for mint messages. Defaults to `2_000`.\n - `:body_as` - What will be returned in `%Tesla.Env{}` body key. Possible values - `:plain`, `:stream`, `:chunks`. Defaults to `:plain`.\n - `:plain` - as binary.\n - `:stream` - as stream. If you don't want to close connection (because you want to reuse it later) pass `close_conn: false` in adapter opts.\n - `:chunks` - as chunks. You can get response body in chunks using `Tesla.Adapter.Mint.read_chunk\/3` function.\n Processing of the chunks and checking body size must be done by yourself. Example of processing function is in `test\/tesla\/adapter\/mint_test.exs` - `Tesla.Adapter.MintTest.read_body\/4`. If you don't need connection later don't forget to close it with `Tesla.Adapter.Mint.close\/1`.\n - `:max_body` - Max response body size in bytes. Works only with `body_as: :plain`, with other settings you need to check response body size by yourself.\n - `:conn` - Opened connection with mint. Is used for reusing mint connections.\n - `:original` - Original host with port, for which reused connection was open. Needed for `Tesla.Middleware.FollowRedirects`. Otherwise adapter will use connection for another open host.\n - `:close_conn` - Close connection or not after receiving full response body. Is used for reusing mint connections. Defaults to `true`.\n - `:proxy` - Proxy settings. E.g.: `{:http, \"localhost\", 8888, []}`, `{:http, \"127.0.0.1\", 8888, []}`\n \"\"\"\n\n @behaviour Tesla.Adapter\n\n import Tesla.Adapter.Shared\n alias Tesla.Multipart\n alias Mint.HTTP\n\n @default timeout: 2_000, body_as: :plain, close_conn: true, mode: :active\n\n @impl Tesla.Adapter\n def call(env, opts) do\n opts = Tesla.Adapter.opts(@default, env, opts)\n\n with {:ok, status, headers, body} <- request(env, opts) do\n {:ok, %{env | status: status, headers: headers, body: body}}\n end\n end\n\n @doc \"\"\"\n Reads chunk of the response body.\n Returns `{:fin, HTTP.t(), binary()}` if all body received, otherwise returns `{:nofin, HTTP.t(), binary()}`.\n \"\"\"\n\n @spec read_chunk(HTTP.t(), reference(), keyword()) ::\n {:fin, HTTP.t(), binary()} | {:nofin, HTTP.t(), binary()}\n def read_chunk(conn, ref, opts) do\n with {:ok, conn, acc} <- receive_packet(conn, ref, opts),\n {state, data} <- response_state(acc) do\n {:ok, conn} =\n if state == :fin and opts[:close_conn] do\n close(conn)\n else\n {:ok, conn}\n end\n\n {state, conn, data}\n end\n end\n\n @doc \"\"\"\n Closes mint connection.\n \"\"\"\n @spec close(HTTP.t()) :: {:ok, HTTP.t()}\n defdelegate close(conn), to: HTTP\n\n defp request(env, opts) do\n request(\n format_method(env.method),\n Tesla.build_url(env.url, env.query),\n env.headers,\n env.body,\n Enum.into(opts, %{})\n )\n end\n\n defp request(method, url, headers, %Stream{} = body, opts) do\n fun = stream_to_fun(body)\n request(method, url, headers, fun, opts)\n end\n\n defp request(method, url, headers, %Multipart{} = body, opts) do\n headers = headers ++ Multipart.headers(body)\n fun = stream_to_fun(Multipart.body(body))\n request(method, url, headers, fun, opts)\n end\n\n defp request(method, url, headers, body, opts),\n do: do_request(method, url, headers, body, opts)\n\n defp do_request(method, url, headers, body, opts) do\n with uri <- URI.parse(url),\n path <- prepare_path(uri.path, uri.query),\n opts <- check_original(uri, opts),\n {:ok, conn, opts} <- open_conn(uri, opts),\n {:ok, conn, ref} <- make_request(conn, method, path, headers, body) do\n format_response(conn, ref, opts)\n end\n end\n\n defp check_original(uri, %{original: original} = opts) do\n Map.put(opts, :original_matches, original == \"#{uri.host}:#{uri.port}\")\n end\n\n defp check_original(_uri, opts), do: opts\n\n defp open_conn(_uri, %{conn: conn, original_matches: true} = opts) do\n {:ok, conn, opts}\n end\n\n defp open_conn(uri, %{conn: conn, original_matches: false} = opts) do\n opts =\n opts\n |> Map.put_new(:old_conn, conn)\n |> Map.delete(:conn)\n\n open_conn(uri, opts)\n end\n\n defp open_conn(uri, opts) do\n opts =\n with \"https\" <- uri.scheme,\n global_cacertfile when not is_nil(global_cacertfile) <-\n Application.get_env(:tesla, Tesla.Adapter.Mint)[:cacert] do\n Map.update(opts, :transport_opts, [cacertfile: global_cacertfile], fn tr_opts ->\n Keyword.put_new(tr_opts, :cacertfile, global_cacertfile)\n end)\n else\n _ -> opts\n end\n\n with {:ok, conn} <-\n HTTP.connect(String.to_atom(uri.scheme), uri.host, uri.port, Enum.into(opts, [])) do\n # If there were redirects, and passed `closed_conn: false`, we need to close opened connections to these intermediate hosts.\n {:ok, conn, Map.put(opts, :close_conn, true)}\n end\n end\n\n defp make_request(conn, method, path, headers, body) when is_function(body) do\n with {:ok, conn, ref} <-\n HTTP.request(\n conn,\n method,\n path,\n headers,\n :stream\n ),\n {:ok, conn} <- stream_request(conn, ref, body) do\n {:ok, conn, ref}\n end\n end\n\n defp make_request(conn, method, path, headers, body),\n do: HTTP.request(conn, method, path, headers, body)\n\n defp stream_request(conn, ref, fun) do\n case next_chunk(fun) do\n {:ok, item, fun} when is_list(item) ->\n chunk = List.to_string(item)\n {:ok, conn} = HTTP.stream_request_body(conn, ref, chunk)\n stream_request(conn, ref, fun)\n\n {:ok, item, fun} ->\n {:ok, conn} = HTTP.stream_request_body(conn, ref, item)\n stream_request(conn, ref, fun)\n\n :eof ->\n HTTP.stream_request_body(conn, ref, :eof)\n end\n end\n\n defp format_response(conn, ref, %{body_as: :plain} = opts) do\n with {:ok, response} <- receive_responses(conn, ref, opts) do\n {:ok, response[:status], response[:headers], response[:data]}\n end\n end\n\n defp format_response(conn, ref, %{body_as: :chunks} = opts) do\n with {:ok, conn, %{status: status, headers: headers} = acc} <-\n receive_headers_and_status(conn, ref, opts),\n {state, data} <-\n response_state(acc) do\n {:ok, conn} =\n if state == :fin and opts[:close_conn] do\n close(conn)\n else\n {:ok, conn}\n end\n\n {:ok, status, headers, %{conn: conn, ref: ref, opts: opts, body: {state, data}}}\n end\n end\n\n defp format_response(conn, ref, %{body_as: :stream} = opts) do\n # there can be some data already\n with {:ok, conn, %{status: status, headers: headers} = acc} <-\n receive_headers_and_status(conn, ref, opts) do\n body_as_stream =\n Stream.resource(\n fn -> %{conn: conn, data: acc[:data], done: acc[:done]} end,\n fn\n %{conn: conn, data: data, done: true} ->\n {[data], %{conn: conn, is_fin: true}}\n\n %{conn: conn, data: data} when is_binary(data) ->\n {[data], %{conn: conn}}\n\n %{conn: conn, is_fin: true} ->\n {:halt, %{conn: conn}}\n\n %{conn: conn} ->\n case receive_packet(conn, ref, opts) do\n {:ok, conn, %{done: true, data: data}} ->\n {[data], %{conn: conn, is_fin: true}}\n\n {:ok, conn, %{done: true}} ->\n {[], %{conn: conn, is_fin: true}}\n\n {:ok, conn, %{data: data}} ->\n {[data], %{conn: conn}}\n\n {:ok, conn, _} ->\n {[], %{conn: conn}}\n end\n end,\n fn %{conn: conn} -> if opts[:close_conn], do: {:ok, _conn} = close(conn) end\n )\n\n {:ok, status, headers, body_as_stream}\n end\n end\n\n defp receive_responses(conn, ref, opts, acc \\\\ %{}) do\n with {:ok, conn, acc} <- receive_packet(conn, ref, opts, acc),\n :ok <- check_data_size(acc, conn, opts) do\n if acc[:done] do\n if opts[:close_conn], do: {:ok, _conn} = close(conn)\n {:ok, acc}\n else\n receive_responses(conn, ref, opts, acc)\n end\n end\n end\n\n defp check_data_size(%{data: data}, conn, %{max_body: max_body} = opts)\n when is_binary(data) do\n if max_body - byte_size(data) >= 0 do\n :ok\n else\n if opts[:close_conn], do: {:ok, _conn} = close(conn)\n {:error, :body_too_large}\n end\n end\n\n defp check_data_size(_, _, _), do: :ok\n\n defp receive_headers_and_status(conn, ref, opts, acc \\\\ %{}) do\n with {:ok, conn, acc} <- receive_packet(conn, ref, opts, acc) do\n case acc do\n %{status: _status, headers: _headers} -> {:ok, conn, acc}\n # if we don't have status or headers we try to get them in next packet\n _ -> receive_headers_and_status(conn, ref, opts, acc)\n end\n end\n end\n\n defp response_state(%{done: true, data: data}), do: {:fin, data}\n defp response_state(%{data: data}), do: {:nofin, data}\n defp response_state(%{done: true}), do: {:fin, \"\"}\n defp response_state(_), do: {:nofin, \"\"}\n\n defp receive_packet(conn, ref, opts, acc \\\\ %{}) do\n with {:ok, conn, responses} <- receive_message(conn, opts),\n acc <- reduce_responses(responses, ref, acc) do\n {:ok, conn, acc}\n else\n {:error, error} ->\n if opts[:close_conn], do: {:ok, _conn} = close(conn)\n {:error, error}\n\n {:error, _conn, error, _res} ->\n if opts[:close_conn], do: {:ok, _conn} = close(conn)\n {:error, \"Encounter Mint error #{inspect(error)}\"}\n\n :unknown ->\n if opts[:close_conn], do: {:ok, _conn} = close(conn)\n {:error, :unknown}\n end\n end\n\n defp receive_message(conn, %{mode: :active} = opts) do\n receive do\n message ->\n HTTP.stream(conn, message)\n after\n opts[:timeout] -> {:error, :timeout}\n end\n end\n\n defp receive_message(conn, %{mode: :passive} = opts),\n do: HTTP.recv(conn, 0, opts[:timeout])\n\n defp reduce_responses(responses, ref, acc) do\n Enum.reduce(responses, acc, fn\n {:status, ^ref, code}, acc ->\n Map.put(acc, :status, code)\n\n {:headers, ^ref, headers}, acc ->\n Map.update(acc, :headers, headers, &(&1 ++ headers))\n\n {:data, ^ref, data}, acc ->\n Map.update(acc, :data, data, &(&1 <> data))\n\n {:done, ^ref}, acc ->\n Map.put(acc, :done, true)\n end)\n end\n end\nend\n","old_contents":"if Code.ensure_loaded?(Mint.HTTP) do\n defmodule Tesla.Adapter.Mint do\n @moduledoc \"\"\"\n Adapter for [mint](https:\/\/github.com\/elixir-mint\/mint).\n\n Caution: The minimum supported Elixir version for mint is 1.5.0\n\n Remember to add `{:mint, \"~> 1.0\"}` and `{:castore, \"~> 0.1\"}` to dependencies\n Also, you need to recompile tesla after adding `:mint` dependency:\n\n ```\n mix deps.clean tesla\n mix deps.compile tesla\n ```\n\n ## Example usage\n\n ```\n # set globally in config\/config.exs\n config :tesla, :adapter, Tesla.Adapter.Mint\n # set per module\n defmodule MyClient do\n use Tesla\n adapter Tesla.Adapter.Mint\n end\n # set global custom cacertfile\n config :tesla, Tesla.Adapter.Mint, cacert: [\"path_to_cacert\"]\n ```\n\n ## Adapter specific options:\n\n - `:timeout` - Time in milliseconds, while process, will wait for mint messages. Defaults to `2_000`.\n - `:body_as` - What will be returned in `%Tesla.Env{}` body key. Possible values - `:plain`, `:stream`, `:chunks`. Defaults to `:plain`.\n - `:plain` - as binary.\n - `:stream` - as stream. If you don't want to close connection (because you want to reuse it later) pass `close_conn: false` in adapter opts.\n - `:chunks` - as chunks. You can get response body in chunks using `Tesla.Adapter.Mint.read_chunk\/3` function.\n Processing of the chunks and checking body size must be done by yourself. Example of processing function is in `test\/tesla\/adapter\/mint_test.exs` - `Tesla.Adapter.MintTest.read_body\/4`. If you don't need connection later don't forget to close it with `Tesla.Adapter.Mint.close\/1`.\n - `:max_body` - Max response body size in bytes. Works only with `body_as: :plain`, with other settings you need to check response body size by yourself.\n - `:conn` - Opened connection with mint. Is used for reusing mint connections.\n - `:original` - Original host with port, for which reused connection was open. Needed for `Tesla.Middleware.FollowRedirects`. Otherwise adapter will use connection for another open host.\n - `:close_conn` - Close connection or not after receiving full response body. Is used for reusing mint connections. Defaults to `true`.\n - `:proxy` - Proxy settings. E.g.: `{:http, \"localhost\", 8888, []}`, `{:http, \"127.0.0.1\", 8888, []}`\n \"\"\"\n\n @behaviour Tesla.Adapter\n\n import Tesla.Adapter.Shared\n alias Tesla.Multipart\n alias Mint.HTTP\n\n @default timeout: 2_000, body_as: :plain, close_conn: true, mode: :active\n\n @impl Tesla.Adapter\n def call(env, opts) do\n opts = Tesla.Adapter.opts(@default, env, opts)\n\n with {:ok, status, headers, body} <- request(env, opts) do\n {:ok, %{env | status: status, headers: headers, body: body}}\n end\n end\n\n @doc \"\"\"\n Reads chunk of the response body.\n Returns `{:fin, HTTP.t(), binary()}` if all body received, otherwise returns `{:nofin, HTTP.t(), binary()}`.\n \"\"\"\n\n @spec read_chunk(HTTP.t(), reference(), keyword()) ::\n {:fin, HTTP.t(), binary()} | {:nofin, HTTP.t(), binary()}\n def read_chunk(conn, ref, opts) do\n with {:ok, conn, acc} <- receive_packet(conn, ref, opts),\n {state, data} <- response_state(acc) do\n {:ok, conn} =\n if state == :fin and opts[:close_conn] do\n close(conn)\n else\n {:ok, conn}\n end\n\n {state, conn, data}\n end\n end\n\n @doc \"\"\"\n Closes mint connection.\n \"\"\"\n @spec close(HTTP.t()) :: {:ok, HTTP.t()}\n defdelegate close(conn), to: HTTP\n\n defp request(env, opts) do\n request(\n format_method(env.method),\n Tesla.build_url(env.url, env.query),\n env.headers,\n env.body,\n Enum.into(opts, %{})\n )\n end\n\n defp request(method, url, headers, %Stream{} = body, opts) do\n fun = stream_to_fun(body)\n request(method, url, headers, fun, opts)\n end\n\n defp request(method, url, headers, %Multipart{} = body, opts) do\n headers = headers ++ Multipart.headers(body)\n fun = stream_to_fun(Multipart.body(body))\n request(method, url, headers, fun, opts)\n end\n\n defp request(method, url, headers, body, opts),\n do: do_request(method, url, headers, body, opts)\n\n defp do_request(method, url, headers, body, opts) do\n with uri <- URI.parse(url),\n path <- prepare_path(uri.path, uri.query),\n opts <- check_original(uri, opts),\n {:ok, conn, opts} <- open_conn(uri, opts),\n {:ok, conn, ref} <- make_request(conn, method, path, headers, body) do\n format_response(conn, ref, opts)\n end\n end\n\n defp check_original(uri, %{original: original} = opts) do\n Map.put(opts, :original_matches, original == \"#{uri.host}:#{uri.port}\")\n end\n\n defp check_original(_uri, opts), do: opts\n\n defp open_conn(_uri, %{conn: conn, original_matches: true} = opts) do\n {:ok, conn, opts}\n end\n\n defp open_conn(uri, %{conn: conn, original_matches: false} = opts) do\n opts =\n opts\n |> Map.put_new(:old_conn, conn)\n |> Map.delete(:conn)\n\n open_conn(uri, opts)\n end\n\n defp open_conn(uri, opts) do\n opts =\n with \"https\" <- uri.scheme,\n global_cacertfile when not is_nil(global_cacertfile) <-\n Application.get_env(:tesla, Tesla.Adapter.Mint)[:cacert] do\n Map.update(opts, :transport_opts, [cacertfile: global_cacertfile], fn tr_opts ->\n Keyword.put_new(tr_opts, :cacertfile, global_cacertfile)\n end)\n else\n _ -> opts\n end\n\n with {:ok, conn} <-\n HTTP.connect(String.to_atom(uri.scheme), uri.host, uri.port, Enum.into(opts, [])) do\n # If there were redirects, and passed `closed_conn: false`, we need to close opened connections to these intermediate hosts.\n {:ok, conn, Map.put(opts, :close_conn, true)}\n end\n end\n\n defp make_request(conn, method, path, headers, body) when is_function(body) do\n with {:ok, conn, ref} <-\n HTTP.request(\n conn,\n method,\n path,\n headers,\n :stream\n ),\n {:ok, conn} <- stream_request(conn, ref, body) do\n {:ok, conn, ref}\n end\n end\n\n defp make_request(conn, method, path, headers, body),\n do: HTTP.request(conn, method, path, headers, body)\n\n defp stream_request(conn, ref, fun) do\n case next_chunk(fun) do\n {:ok, item, fun} when is_list(item) ->\n chunk = List.to_string(item)\n {:ok, conn} = HTTP.stream_request_body(conn, ref, chunk)\n stream_request(conn, ref, fun)\n\n {:ok, item, fun} ->\n {:ok, conn} = HTTP.stream_request_body(conn, ref, item)\n stream_request(conn, ref, fun)\n\n :eof ->\n HTTP.stream_request_body(conn, ref, :eof)\n end\n end\n\n defp format_response(conn, ref, %{body_as: :plain} = opts) do\n with {:ok, response} <- receive_responses(conn, ref, opts) do\n {:ok, response[:status], response[:headers], response[:data]}\n end\n end\n\n defp format_response(conn, ref, %{body_as: :chunks} = opts) do\n with {:ok, conn, %{status: status, headers: headers} = acc} <-\n receive_headers_and_status(conn, ref, opts),\n {state, data} <-\n response_state(acc) do\n {:ok, conn} =\n if state == :fin and opts[:close_conn] do\n close(conn)\n else\n {:ok, conn}\n end\n\n {:ok, status, headers, %{conn: conn, ref: ref, opts: opts, body: {state, data}}}\n end\n end\n\n defp format_response(conn, ref, %{body_as: :stream} = opts) do\n # there can be some data already\n with {:ok, conn, %{status: status, headers: headers} = acc} <-\n receive_headers_and_status(conn, ref, opts) do\n body_as_stream =\n Stream.resource(\n fn -> %{conn: conn, data: acc[:data], done: acc[:done]} end,\n fn\n %{conn: conn, data: data, done: true} ->\n {[data], %{conn: conn, is_fin: true}}\n\n %{conn: conn, data: data} when is_binary(data) ->\n {[data], %{conn: conn}}\n\n %{conn: conn, is_fin: true} ->\n {:halt, %{conn: conn}}\n\n %{conn: conn} ->\n case receive_packet(conn, ref, opts) do\n {:ok, conn, %{done: true, data: data}} ->\n {[data], %{conn: conn, is_fin: true}}\n\n {:ok, conn, %{done: true}} ->\n {[], %{conn: conn, is_fin: true}}\n\n {:ok, conn, %{data: data}} ->\n {[data], %{conn: conn}}\n\n {:ok, conn, _} ->\n {[], %{conn: conn}}\n end\n end,\n fn %{conn: conn} -> if opts[:close_conn], do: {:ok, _conn} = close(conn) end\n )\n\n {:ok, status, headers, body_as_stream}\n end\n end\n\n defp receive_responses(conn, ref, opts, acc \\\\ %{}) do\n with {:ok, conn, acc} <- receive_packet(conn, ref, opts, acc),\n :ok <- check_data_size(acc, conn, opts) do\n if acc[:done] do\n if opts[:close_conn], do: {:ok, _conn} = close(conn)\n {:ok, acc}\n else\n receive_responses(conn, ref, opts, acc)\n end\n end\n end\n\n defp check_data_size(%{data: data}, conn, %{max_body: max_body} = opts)\n when is_binary(data) do\n if max_body - byte_size(data) >= 0 do\n :ok\n else\n if opts[:close_conn], do: {:ok, _conn} = close(conn)\n {:error, :body_too_large}\n end\n end\n\n defp check_data_size(_, _, _), do: :ok\n\n defp receive_headers_and_status(conn, ref, opts, acc \\\\ %{}) do\n with {:ok, conn, acc} <- receive_packet(conn, ref, opts, acc) do\n case acc do\n %{status: _status, headers: _headers} -> {:ok, conn, acc}\n # if we don't have status or headers we try to get them in next packet\n _ -> receive_headers_and_status(conn, ref, opts, acc)\n end\n end\n end\n\n defp response_state(%{done: true, data: data}), do: {:fin, data}\n defp response_state(%{data: data}), do: {:nofin, data}\n defp response_state(%{done: true}), do: {:fin, \"\"}\n defp response_state(_), do: {:nofin, \"\"}\n\n defp receive_packet(conn, ref, opts, acc \\\\ %{}) do\n with {:ok, conn, responses} <- receive_message(conn, opts),\n acc <- reduce_responses(responses, ref, acc) do\n {:ok, conn, acc}\n else\n {:error, error} ->\n if opts[:close_conn], do: {:ok, _conn} = close(conn)\n {:error, error}\n\n {:error, _conn, error, _res} ->\n if opts[:close_conn], do: {:ok, _conn} = close(conn)\n {:error, \"Encounter Mint error #{inspect(error)}\"}\n\n :unknown ->\n if opts[:close_conn], do: {:ok, _conn} = close(conn)\n {:error, :unknown}\n end\n end\n\n defp receive_message(conn, %{mode: :active} = opts) do\n receive do\n message ->\n HTTP.stream(conn, message)\n after\n opts[:timeout] -> {:error, :timeout}\n end\n end\n\n defp receive_message(conn, %{mode: :passive} = opts),\n do: HTTP.recv(conn, 0, opts[:timeout])\n\n defp reduce_responses(responses, ref, acc) do\n Enum.reduce(responses, acc, fn\n {:status, ^ref, code}, acc ->\n Map.put(acc, :status, code)\n\n {:headers, ^ref, headers}, acc ->\n Map.update(acc, :headers, headers, &(&1 ++ headers))\n\n {:data, ^ref, data}, acc ->\n Map.update(acc, :data, data, &(&1 <> data))\n\n {:done, ^ref}, acc ->\n Map.put(acc, :done, true)\n end)\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"4cc26a6153186efaa375b9c5250de3f9cdf921ce","subject":"Implement parsing","message":"Implement parsing\n\nThis is as recommended by the book, yet my feeling is that I would\nprobably structure it a bit differently.\n","repos":"thbar\/elixir-playground","old_file":"samples\/issues\/lib\/issues\/cli.ex","new_file":"samples\/issues\/lib\/issues\/cli.ex","new_contents":"defmodule Issues.CLI do\n @default_count 4\n @moduledoc \"\"\"\n Handle the command line parsing and the dispatch to\n the various functions that end up generating a table of the last\n _n_ issues in a github project\n \"\"\"\n\n def run(argv) do\n parse_args(argv)\n end\n\n @doc \"\"\"\n `argv` can be -h or --help, which returns :help.\n \n Otherwise it is a github user name, project name, and (optionally)\n the number of entries to format.\n \n Return a tuple of `{ user, project, count }` or `:help` if help was given.\n \"\"\"\n def parse_args(argv) do\n parse = OptionParser.parse(argv, switches: [help: :boolean],\n aliases: [h: :help])\n case parse do\n {[help: true], _, _} -> :help\n {_, [user, project, count], _} -> {user, project, count}\n {_, [user, project], _} -> {user, project, @default_count}\n _ -> :help\n end\n end\nend\n","old_contents":"defmodule Issues.CLI do\n @default_count 4\n @moduledoc \"\"\"\n Handle the command line parsing and the dispatch to\n the various functions that end up generating a table of the last\n _n_ issues in a github project\n \"\"\"\n\n def run(argv) do\n parse_args(argv)\n end\n\n @doc \"\"\"\n `argv` can be -h or --help, which returns :help.\n \n Otherwise it is a github user name, project name, and (optionally)\n the number of entries to format.\n \n Return a tuple of `{ user, project, count }` or `:help` if help was given.\n \"\"\"\n def parse_args(argv) do\n parse = OptionParser.parse(argv, switches: [help: :boolean],\n aliases: [h: :help])\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"0226f4b1e789409c36ec3967ab1d77f96741120e","subject":"send hook to vol_event_submission on confirm","message":"send hook to vol_event_submission on confirm\n","repos":"justicedemocrats\/admin,justicedemocrats\/admin,justicedemocrats\/admin","old_file":"lib\/admin\/webhooks.ex","new_file":"lib\/admin\/webhooks.ex","new_contents":"defmodule Admin.Webhooks do\n require Logger\n import ShortMaps\n\n @instance Application.get_env(:admin, :instance, \"jd\")\n @cosmic_config_slug Application.get_env(:admin, :cosmic_info_slug)\n\n def on(hook, body = %{event: event}) do\n processed = process_event(event)\n\n hook\n |> exec(Map.put(body, :event, processed))\n end\n\n def exec(\"confirmed\", contents = %{event: event, team_member: team_member}) do\n if @instance != \"jd\" do\n %{\"metadata\" => %{\"event_publish\" => hook}} = Cosmic.get(@cosmic_config_slug)\n IO.puts(\"Posting webhook to #{hook} because of confirmed\")\n IO.inspect(HTTPotion.post(hook, bodify(%{event: event, team_member: team_member})))\n else\n %{\"metadata\" => %{\"vol_event_submission\" => hook}} = Cosmic.get(@cosmic_config_slug)\n IO.puts(\"Posting webhook to #{hook} because of confirmed vol event\")\n IO.inspect(HTTPotion.post(hook, bodify(%{event: event, team_member: team_member})))\n\n email = event.contact.email_address\n\n info =\n flatten(contents)\n |> Enum.map(fn {key, val} ->\n {\"action_#{key}\", val}\n end)\n |> Enum.into(~m(email))\n\n IO.inspect(\n Ak.Signup.process_signup(&String.contains?(&1[\"title\"], \"ESM: Event Published\"), info)\n )\n end\n end\n\n def exec(\"rejected\", contents = %{event: event, reason: reason, team_member: team_member}) do\n if @instance != \"jd\" do\n %{\"metadata\" => %{\"event_rejected\" => hook}} = Cosmic.get(@cosmic_config_slug)\n IO.puts(\"Posting webhook to #{hook} because of rejected\")\n\n IO.inspect(\n HTTPotion.post(hook, bodify(%{event: event, reason: reason, team_member: team_member}))\n )\n else\n email = event.contact.email_address\n\n info =\n flatten(contents)\n |> Enum.map(fn {key, val} ->\n {\"action_#{key}\", val}\n end)\n |> Enum.into(~m(email))\n\n IO.inspect(\n Ak.Signup.process_signup(&String.contains?(&1[\"title\"], \"ESM: Event Rejected\"), info)\n )\n end\n end\n\n def exec(\"cancelled\", contents = %{event: event, team_member: team_member, reason: reason}) do\n if @instance != \"jd\" do\n %{\"metadata\" => %{\"event_cancelled\" => hook}} = Cosmic.get(@cosmic_config_slug)\n IO.puts(\"Posting webhook to #{hook} because of cancelled\")\n\n IO.inspect(\n HTTPotion.post(hook, bodify(%{event: event, team_member: team_member, reason: reason}))\n )\n else\n email = event.contact.email_address\n\n info =\n flatten(contents)\n |> Enum.map(fn {key, val} ->\n {\"action_#{key}\", val}\n end)\n |> Enum.into(~m(email))\n\n IO.inspect(\n Ak.Signup.process_signup(&String.contains?(&1[\"title\"], \"ESM: Event Cancelled\"), info)\n )\n end\n end\n\n def exec(\"tentative\", contents = %{event: event, team_member: team_member}) do\n if @instance != \"jd\" do\n %{\"metadata\" => %{\"event_unpublished\" => hook}} = Cosmic.get(@cosmic_config_slug)\n IO.puts(\"Posting webhook to #{hook} because of tentative\")\n IO.inspect(HTTPotion.post(hook, bodify(%{event: event, team_member: team_member})))\n else\n email = event.contact.email_address\n\n info =\n flatten(contents)\n |> Enum.map(fn {key, val} ->\n {\"action_#{key}\", val}\n end)\n |> Enum.into(~m(email))\n\n IO.inspect(\n Ak.Signup.process_signup(&String.contains?(&1[\"title\"], \"ESM: Event Unpublished\"), info)\n )\n end\n end\n\n def exec(\"edit\", %{event: event, edits: edits}) do\n %{\"metadata\" => %{\"event_edited\" => hook}} = Cosmic.get(@cosmic_config_slug)\n IO.puts(\"Posting webhook to #{hook} because of edit\")\n IO.inspect(HTTPotion.post(hook, bodify(%{event: event, edits: edits})))\n end\n\n def exec(\"message_host\", contents = ~m(event host message)a) do\n if @instance != \"jd\" do\n %{\"metadata\" => %{\"message_host\" => hook}} = Cosmic.get(@cosmic_config_slug)\n IO.puts(\"Posting webhook to #{hook} because of message-host\")\n IO.inspect(HTTPotion.post(hook, bodify(~m(event host message))))\n else\n email = event.contact.email_address\n\n info =\n flatten(contents)\n |> Enum.map(fn {key, val} ->\n {\"action_#{key}\", val}\n end)\n |> Enum.into(~m(email))\n\n IO.inspect(\n Ak.Signup.process_signup(&String.contains?(&1[\"title\"], \"ESM: Event Message Host\"), info)\n )\n end\n end\n\n def exec(hook_type = \"message_attendees\" <> _rest, ~m(event attendee_emails message)a) do\n hook = Cosmic.get(@cosmic_config_slug) |> get_in([\"metadata\", hook_type])\n IO.puts(\"Posting webhook to #{hook} because of #{hook_type}\")\n IO.inspect(HTTPotion.post(hook, bodify(~m(event attendee_emails message))))\n end\n\n def exec(other, %{event: event, team_member: _team_member}) do\n Logger.info(\"Untracked status change: #{other}, for event: #{inspect(event)}\")\n end\n\n defp bodify(body), do: [body: Poison.encode!(IO.inspect(body))]\n\n defp process_event(event) do\n event\n |> Map.put(:date_line, get_date_line(event))\n end\n\n def get_date_line(event) do\n humanize_date(event.start_date) <>\n \"from \" <> humanize_time(event.start_date) <> \" - \" <> humanize_time(event.end_date)\n end\n\n defp humanize_date(dt) do\n %DateTime{month: month, day: day} = parse(dt)\n\n month =\n [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\"\n ]\n |> Enum.at(month - 1)\n\n \"#{month} #{day} \"\n end\n\n defp humanize_time(dt) do\n %DateTime{hour: hour, minute: minute} = parse(dt)\n\n {hour, am_pm} = if hour >= 12, do: {hour - 12, \"PM\"}, else: {hour, \"AM\"}\n hour = if hour == 0, do: 12, else: hour\n minute = if minute == 0, do: \"\", else: \":#{minute}\"\n\n \"#{hour}#{minute} \" <> am_pm\n end\n\n def parse(nil) do\n DateTime.utc_now()\n end\n\n def zero_pad(int) do\n str = \"#{int}\"\n if String.length(str), do: str, else: \"0#{str}\"\n end\n\n def parse(dt = %DateTime{}) do\n dt\n end\n\n def parse(dt) do\n iso = if String.ends_with?(dt, \"Z\"), do: dt, else: dt <> \"Z\"\n {:ok, result, _} = DateTime.from_iso8601(iso)\n result\n end\n\n def flatten(%{} = map) do\n map\n |> Map.drop(~w(name))\n |> Map.to_list()\n |> to_flat_map(%{})\n end\n\n def flatten(%{} = map) when map == %{}, do: %{}\n\n defp to_flat_map([{_k, %{} = v} | t], acc), do: to_flat_map(Map.to_list(v), to_flat_map(t, acc))\n defp to_flat_map([{k, v} | t], acc), do: to_flat_map(t, Map.put_new(acc, k, v))\n defp to_flat_map([], acc), do: acc\nend\n","old_contents":"defmodule Admin.Webhooks do\n require Logger\n import ShortMaps\n\n @instance Application.get_env(:admin, :instance, \"jd\")\n @cosmic_config_slug Application.get_env(:admin, :cosmic_info_slug)\n\n def on(hook, body = %{event: event}) do\n processed = process_event(event)\n\n hook\n |> exec(Map.put(body, :event, processed))\n end\n\n def exec(\"confirmed\", contents = %{event: event, team_member: team_member}) do\n if @instance != \"jd\" do\n %{\"metadata\" => %{\"event_publish\" => hook}} = Cosmic.get(@cosmic_config_slug)\n IO.puts(\"Posting webhook to #{hook} because of confirmed\")\n IO.inspect(HTTPotion.post(hook, bodify(%{event: event, team_member: team_member})))\n else\n email = event.contact.email_address\n\n info =\n flatten(contents)\n |> Enum.map(fn {key, val} ->\n {\"action_#{key}\", val}\n end)\n |> Enum.into(~m(email))\n\n IO.inspect Ak.Signup.process_signup(&String.contains?(&1[\"title\"], \"ESM: Event Published\"), info)\n end\n end\n\n def exec(\"rejected\", contents = %{event: event, reason: reason, team_member: team_member}) do\n if @instance != \"jd\" do\n %{\"metadata\" => %{\"event_rejected\" => hook}} = Cosmic.get(@cosmic_config_slug)\n IO.puts(\"Posting webhook to #{hook} because of rejected\")\n\n IO.inspect(\n HTTPotion.post(hook, bodify(%{event: event, reason: reason, team_member: team_member}))\n )\n else\n email = event.contact.email_address\n\n info =\n flatten(contents)\n |> Enum.map(fn {key, val} ->\n {\"action_#{key}\", val}\n end)\n |> Enum.into(~m(email))\n\n IO.inspect Ak.Signup.process_signup(&String.contains?(&1[\"title\"], \"ESM: Event Rejected\"), info)\n end\n end\n\n def exec(\"cancelled\", contents = %{event: event, team_member: team_member, reason: reason}) do\n if @instance != \"jd\" do\n %{\"metadata\" => %{\"event_cancelled\" => hook}} = Cosmic.get(@cosmic_config_slug)\n IO.puts(\"Posting webhook to #{hook} because of cancelled\")\n\n IO.inspect(\n HTTPotion.post(hook, bodify(%{event: event, team_member: team_member, reason: reason}))\n )\n else\n email = event.contact.email_address\n\n info =\n flatten(contents)\n |> Enum.map(fn {key, val} ->\n {\"action_#{key}\", val}\n end)\n |> Enum.into(~m(email))\n\n IO.inspect Ak.Signup.process_signup(&String.contains?(&1[\"title\"], \"ESM: Event Cancelled\"), info)\n end\n end\n\n def exec(\"tentative\", contents = %{event: event, team_member: team_member}) do\n if @instance != \"jd\" do\n %{\"metadata\" => %{\"event_unpublished\" => hook}} = Cosmic.get(@cosmic_config_slug)\n IO.puts(\"Posting webhook to #{hook} because of tentative\")\n IO.inspect(HTTPotion.post(hook, bodify(%{event: event, team_member: team_member})))\n else\n email = event.contact.email_address\n\n info =\n flatten(contents)\n |> Enum.map(fn {key, val} ->\n {\"action_#{key}\", val}\n end)\n |> Enum.into(~m(email))\n\n IO.inspect Ak.Signup.process_signup(&String.contains?(&1[\"title\"], \"ESM: Event Unpublished\"), info)\n end\n end\n\n def exec(\"edit\", %{event: event, edits: edits}) do\n %{\"metadata\" => %{\"event_edited\" => hook}} = Cosmic.get(@cosmic_config_slug)\n IO.puts(\"Posting webhook to #{hook} because of edit\")\n IO.inspect(HTTPotion.post(hook, bodify(%{event: event, edits: edits})))\n end\n\n def exec(\"message_host\", contents = ~m(event host message)a) do\n if @instance != \"jd\" do\n %{\"metadata\" => %{\"message_host\" => hook}} = Cosmic.get(@cosmic_config_slug)\n IO.puts(\"Posting webhook to #{hook} because of message-host\")\n IO.inspect(HTTPotion.post(hook, bodify(~m(event host message))))\n else\n email = event.contact.email_address\n\n info =\n flatten(contents)\n |> Enum.map(fn {key, val} ->\n {\"action_#{key}\", val}\n end)\n |> Enum.into(~m(email))\n\n IO.inspect Ak.Signup.process_signup(&String.contains?(&1[\"title\"], \"ESM: Event Message Host\"), info)\n end\n end\n\n def exec(hook_type = \"message_attendees\" <> _rest, ~m(event attendee_emails message)a) do\n hook = Cosmic.get(@cosmic_config_slug) |> get_in([\"metadata\", hook_type])\n IO.puts(\"Posting webhook to #{hook} because of #{hook_type}\")\n IO.inspect(HTTPotion.post(hook, bodify(~m(event attendee_emails message))))\n end\n\n def exec(other, %{event: event, team_member: _team_member}) do\n Logger.info(\"Untracked status change: #{other}, for event: #{inspect(event)}\")\n end\n\n defp bodify(body), do: [body: Poison.encode!(IO.inspect(body))]\n\n defp process_event(event) do\n event\n |> Map.put(:date_line, get_date_line(event))\n end\n\n def get_date_line(event) do\n humanize_date(event.start_date) <>\n \"from \" <> humanize_time(event.start_date) <> \" - \" <> humanize_time(event.end_date)\n end\n\n defp humanize_date(dt) do\n %DateTime{month: month, day: day} = parse(dt)\n\n month =\n [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\"\n ]\n |> Enum.at(month - 1)\n\n \"#{month} #{day} \"\n end\n\n defp humanize_time(dt) do\n %DateTime{hour: hour, minute: minute} = parse(dt)\n\n {hour, am_pm} = if hour >= 12, do: {hour - 12, \"PM\"}, else: {hour, \"AM\"}\n hour = if hour == 0, do: 12, else: hour\n minute = if minute == 0, do: \"\", else: \":#{minute}\"\n\n \"#{hour}#{minute} \" <> am_pm\n end\n\n def parse(nil) do\n DateTime.utc_now()\n end\n\n def zero_pad(int) do\n str = \"#{int}\"\n if String.length(str), do: str, else: \"0#{str}\"\n end\n\n def parse(dt = %DateTime{}) do\n dt\n end\n\n def parse(dt) do\n iso = if String.ends_with?(dt, \"Z\"), do: dt, else: dt <> \"Z\"\n {:ok, result, _} = DateTime.from_iso8601(iso)\n result\n end\n\n def flatten(%{} = map) do\n map\n |> Map.drop(~w(name))\n |> Map.to_list()\n |> to_flat_map(%{})\n end\n\n def flatten(%{} = map) when map == %{}, do: %{}\n\n defp to_flat_map([{_k, %{} = v} | t], acc), do: to_flat_map(Map.to_list(v), to_flat_map(t, acc))\n defp to_flat_map([{k, v} | t], acc), do: to_flat_map(t, Map.put_new(acc, k, v))\n defp to_flat_map([], acc), do: acc\nend\n","returncode":0,"stderr":"","license":"agpl-3.0","lang":"Elixir"} {"commit":"79f51bb9986d219c2d3c11d152e2862bcea2f05e","subject":"style","message":"style\n","repos":"shopping-adventure\/gen_serverring","old_file":"lib\/gen_serverring.ex","new_file":"lib\/gen_serverring.ex","new_contents":"defmodule GenServerring do\n use GenServer\n require Crdtex.Set\n\n defstruct(\n node_set: Crdtex.Set.new,\n up_set: MapSet.new,\n forced_down: Crdtex.Set.new,\n payload: nil,\n counter: 0,\n callback: nil)\n\n defmacro __using__(_), do: []\n\n def start_link({name, callback}) do\n {:ok, payload} = callback.init([])\n GenServer.start_link(__MODULE__, {payload, callback}, [{:name, name}])\n end\n\n def init({payload, callback}) do\n :erlang.send_after(1_000, self(), :send_gossip)\n case File.read(ring_path) do\n {:ok, bin} ->\n set = :erlang.binary_to_term(bin)\n monitor(get_set(set))\n # should we call callback.handle_ring_change in such a situation ?\n {:ok, gen_ring(set, MapSet.new(get_set(set)), payload, 0, callback)}\n _ ->\n set = Crdtex.Set.new\n {:ok, set} = add(set, {node(), 1}, node())\n {:ok, gen_ring(set, MapSet.new([node()]), payload, 1, callback)}\n end\n end\n\n # payload management, mimicking a GenServer\n def call(server, action), do: GenServer.call(server, action)\n\n def cast(server, action), do: GenServer.cast(server, action)\n\n def reply(client, term), do: GenServer.reply(client, term)\n\n # cluster_management\n # we have to stop all nodes\n def stop({name, n} = server, reason \\\\ :normal, timeout \\\\ :infinity) do\n {:ok, ring} = get_ring(server)\n others = ring.up_set |> MapSet.delete(n)\n Enum.each(others, fn(n) -> GenServer.stop({name, n}, reason, timeout) end)\n Genserver.stop(server, reason, timeout)\n end\n\n def add_node(server, node) when is_binary(node),\n do: add_node(server, :\"#{node}\")\n def add_node(server, node) when is_atom(node),\n do: GenServer.cast(server, {:add_node, node})\n\n def del_node(server, node) when is_binary(node),\n do: del_node(server, :\"#{node}\")\n def del_node(server, node) when is_atom(node),\n do: GenServer.cast(server, {:del_node, node})\n\n # forbid the use of the given node (no gossip sent to it, gossip from it\n # ignored) but it might still be up, it will continue to be monitored as long\n # as it is up.\n def force_down(server, n), do: GenServer.call(server, {:forced_down, n})\n\n # remove a node of the forced_down state\n def unforce_down(server, n), do: GenServer.call(server, {:unforced_down, n})\n\n def all(server), do: GenServer.call(server, :get_all)\n def up(server), do: GenServer.call(server, :get_up)\n\n # classic GenServer callbacks\n def handle_call(:get_all, _, ring), do: {:reply, get_set(ring.node_set), ring}\n def handle_call(:get_up, _, ring),\n do: {:reply, MapSet.to_list(up_nodes(ring)), ring}\n def handle_call(:get_ring, _, ring), do: {:reply, {:ok, ring}, ring}\n def handle_call({:forced_down, n}, _, ring) do\n counter = ring.counter + 1\n {:ok, forced_down} = add(ring.forced_down, {node(), counter}, n)\n {:reply, get_set(forced_down),\n %{ring | forced_down: forced_down, counter: counter}}\n end\n def handle_call({:unforced_down, n}, _, ring) do\n counter = ring.counter + 1\n {:ok, forced_down} = delete(ring.forced_down, {node(), counter}, n)\n up_set = ring.up_set\n up_set =\n case MapSet.member?(up_set, n) do\n true -> up_set\n false ->\n Node.monitor(n, true)\n MapSet.put(up_set, n)\n end\n {:reply, get_set(forced_down),\n %{ring | forced_down: forced_down, up_set: up_set, counter: counter}}\n end\n def handle_call(other, from, ring) do\n payload = ring.payload\n up_load = fn(load) -> update_payload(ring, load) end\n case ring.callback.handle_call(other, from, payload) do\n {:reply, reply, new} -> {:reply, reply, up_load.(new)}\n {:reply, reply, new, timeout} -> {:reply, reply, up_load.(new), timeout}\n {:noreply, new} -> {:noreply, up_load.(new)}\n {:noreply, new, timeout} -> {:noreply, up_load.(new), timeout}\n {:stop, reason, reply, new} -> {:stop, reason, reply, up_load.(new)}\n {:stop, reason, new} -> {:stop, reason, up_load.(new)}\n end\n end\n\n def handle_cast({:reconcile, gossip}, ring) do\n from_node = gossip.from_node\n up_set_reconcile(from_node, ring.up_set)\n ring_reconcile(from_node, gossip, ring)\n end\n def handle_cast({:add_node, n}, ring) do\n case contain?(ring.node_set, n) do\n true ->\n {:noreply, ring}\n false ->\n new_up_set = MapSet.put(ring.up_set, n)\n {:ok, new_node_set} = add(ring.node_set, {node(), ring.counter + 1}, n)\n {ring, _} =\n update_ring(%GenServerring{ring | up_set: new_up_set},\n %{node_set: new_node_set, payload: ring.payload, from_node: [],\n forced_down: ring.forced_down})\n {:noreply, ring}\n end\n end\n def handle_cast({:del_node, n}, ring) do\n case contain?(ring.node_set, n) do\n false ->\n {:noreply, ring}\n true ->\n new_up_set = MapSet.delete(ring.up_set, n)\n {:ok, new_node_set} =\n delete(ring.node_set, {node(), ring.counter + 1}, n)\n {ring, _} =\n update_ring(%GenServerring{ring | up_set: new_up_set},\n %{node_set: new_node_set, payload: ring.payload, from_node: [],\n forced_down: ring.forced_down})\n {:noreply, ring}\n end\n end\n def handle_cast(other, ring) do\n payload = ring.payload\n up_load = fn(load) -> update_payload(ring, load) end\n case ring.callback.handle_cast(other, payload) do\n {:noreply, new} -> {:noreply, up_load.(new)}\n {:noreply, new, timeout} -> {:noreply, up_load.(new), timeout}\n {:stop, reason, new} -> {:stop, reason, up_load.(new)}\n end\n end\n\n def handle_info(:send_gossip, %GenServerring{node_set: node_set} = ring) do\n :erlang.send_after(1_000, self(), :send_gossip)\n if not contain?(node_set, node()) do\n :erlang.send_after(5_000, self(), :halt_node)\n end\n case up_nodes(ring) |> MapSet.delete(node()) |> MapSet.to_list do\n [] -> {:noreply, ring}\n active_nodes ->\n {:registered_name, name} = Process.info(self(), :registered_name)\n random_node =\n Enum.at(active_nodes, :random.uniform(length(active_nodes)) - 1)\n GenServer.cast(\n {name, random_node},\n {:reconcile,\n %{node_set: node_set,\n forced_down: ring.forced_down,\n payload: ring.payload,\n from_node: [node()]}})\n {:noreply, ring}\n end\n end\n def handle_info({:nodedown, n}, %GenServerring{up_set: up_set} = ring) do\n new_up_set =\n case MapSet.member?(up_set, n) do\n true ->\n set = MapSet.delete(up_set, n)\n {:registered_name, name} = Process.info(self(), :registered_name)\n ring.callback.handle_ring_change({MapSet.to_list(set), name,\n :nodedown})\n set\n false -> up_set\n end\n {:noreply, %{ring | up_set: new_up_set}}\n end\n def handle_info(:halt_node, s) do\n File.rm(ring_path)\n :init.stop()\n {:noreply, s}\n end\n def handle_info(other, ring) do\n up_load = fn(load) -> update_payload(ring, load) end\n case ring.callback.handle_info(other, ring.payload) do\n {:noreply, new} -> {:noreply, up_load.(new)}\n {:noreply, new, timeout} -> {:noreply, up_load.(new), timeout}\n {:stop, reason, new} -> {:stop, reason, up_load.(new)}\n end\n end\n\n # small utilities functions\n defp value(payload), do: Crdtex.value(payload)\n\n defp get_set(set), do: Crdtex.value(set)\n\n defp contain?(set, e), do: Crdtex.value(set, {:contains, e})\n\n defp add(set, actor, e), do: Crdtex.update(set, actor, {:add, e})\n\n defp delete(set, actor, e), do: Crdtex.update(set, actor, {:remove, e})\n\n defp merge(nil, crdt), do: crdt\n defp merge(crdt, crdt), do: crdt\n defp merge(crdt1, crdt2), do: Crdtex.merge(crdt1, crdt2)\n\n defp get_ring(server), do: GenServer.call(server, :get_ring)\n\n defp up_nodes(ring),\n do: MapSet.difference(ring.up_set, MapSet.new(get_set(ring.forced_down)))\n\n defp monitor(list) do\n list = List.delete(list, node())\n Enum.each(list, fn(n) -> Node.monitor(n, :true) end)\n end\n\n defp gen_ring(set, up, payload, counter, callback),\n do: gen_ring(set, up, payload, counter, callback, Crdtex.Set.new)\n defp gen_ring(set, up, payload, counter, callback, forced_down) do\n %GenServerring{node_set: set, up_set: up, forced_down: forced_down,\n payload: payload, counter: counter, callback: callback}\n end\n\n defp update_payload(ring, payload) do\n {ring, _} =\n update_ring(ring,\n %{node_set: ring.node_set, payload: payload, from_node: [],\n forced_down: ring.forced_down})\n ring\n end\n\n defp update_ring(ring, changes) do\n merged_node_set = merge(ring.node_set, changes.node_set)\n merged_payload = merge(ring.payload, changes.payload)\n merged_forced_down = merge(ring.forced_down, changes.forced_down)\n updated_counter = update_counter(merged_node_set, merged_payload, ring)\n\n up_set =\n notify_up_set(get_set(ring.node_set), get_set(merged_node_set),\n ring.up_set, changes.from_node, ring.callback)\n notify_node_set(ring.node_set, merged_node_set, changes.node_set)\n\n old_payload = ring.payload\n ring =\n gen_ring(merged_node_set, up_set, merged_payload, updated_counter,\n ring.callback, merged_forced_down)\n {ring, notify_payload(value(old_payload), value(changes.payload), ring)}\n end\n\n defp update_counter(merged_node_set, merged_payload, old_ring) do\n old_nodes = old_ring.node_set\n old_payload = old_ring.payload\n case {merged_node_set, merged_payload} do\n {^old_nodes, ^old_payload} -> old_ring.counter\n _ -> old_ring.counter + 1\n end\n end\n\n defp notify_up_set(set, set, old_up, [], _), do: old_up\n defp notify_up_set(set, set, old_up, [n], callback) do\n case MapSet.member?(old_up, n) do\n true -> old_up\n false -> notify_up_set(set, set, MapSet.put(old_up, n), callback)\n end\n end\n defp notify_up_set(old, merged, up, [], callback),\n do: notify_up_set(old, merged, up, callback)\n defp notify_up_set(old, merged, up, [n], callback),\n do: notify_up_set(old, merged, MapSet.put(up, n), callback)\n\n defp notify_up_set(old_set, merged_set, old_up, callback) do\n new_up = MapSet.difference(MapSet.new(merged_set), MapSet.new(old_set))\n Enum.each(new_up, fn(n) -> Node.monitor(n, :true) end)\n new_set = MapSet.union(new_up, old_up)\n GenEvent.notify(GenServerring.Events, {:new_up_set, old_up, new_set})\n {:registered_name, name} = Process.info(self(), :registered_name)\n callback.handle_ring_change({MapSet.to_list(new_set), name, :gossip})\n new_set\n end\n\n defp notify_node_set(set, set, _), do: :nothingtodo\n defp notify_node_set(old_set, _, new_set) do\n GenEvent.notify(GenServerring.Events,\n {:new_node_set, get_set(old_set), get_set(new_set)})\n File.write!(ring_path, new_set |> :erlang.term_to_binary)\n end\n\n defp notify_payload(payload, payload, _), do: :no_payload_change\n defp notify_payload(_, _, ring), do: ring.payload\n\n defp ring_path,\n do: \"#{Application.get_env(:gen_serverring, :data_dir, \".\/data\")}\/ring\"\n\n defp up_set_reconcile([], _), do: :nothingtodo\n defp up_set_reconcile([n], up_set) do\n case MapSet.member?(up_set, n) do\n true -> :nothingtodo\n false -> Node.monitor(n, true)\n end\n end\n\n defp ring_reconcile([n], gossip, ring) do\n case contain?(ring.forced_down, n) do\n true -> {:noreply, ring} # must ignore gossips from forced_down nodes\n false -> ring_reconcile([], gossip, ring)\n end\n end\n defp ring_reconcile([], gossip, ring) do\n {ring, payload} = update_ring(ring, gossip)\n case payload do\n :no_payload_change -> :nothingtodo\n _ -> ring.callback.handle_state_change(payload)\n end\n {:noreply, ring}\n end\nend\n\ndefmodule GenServerring.App do\n use Application\n\n def start(type, []) do\n name = Application.get_env(:gen_serverring, :name, :demo_ring)\n callback = Application.get_env(:gen_serverring, :callback, Demo)\n start(type, [{name, callback}])\n end\n def start(_type, args),\n do: Supervisor.start_link(GenServerring.App.Sup, args)\n\n defmodule Sup do\n use Supervisor\n\n def init(:no_child) do\n # just start a GenEvent, no event_handler are defined, add yours if you\n # need some\n event_name = GenServerring.Events\n child = [worker(:gen_event, [{:local, event_name}], id: event_name)]\n supervise(child, strategy: :one_for_one)\n end\n def init(arg) do\n event_name = GenServerring.Events\n children =\n [worker(:gen_event, [{:local, event_name}], id: event_name),\n worker(GenServerring, arg)]\n supervise(children, strategy: :one_for_one)\n end\n end\nend\n\n","old_contents":"defmodule GenServerring do\n use GenServer\n require Crdtex.Set\n\n defstruct(\n node_set: Crdtex.Set.new,\n up_set: MapSet.new,\n forced_down: Crdtex.Set.new,\n payload: nil,\n counter: 0,\n callback: nil)\n\n defmacro __using__(_), do: []\n\n def start_link({name, callback}) do\n {:ok, payload} = callback.init([])\n GenServer.start_link(__MODULE__, {payload, callback}, [{:name, name}])\n end\n\n def init({payload, callback}) do\n :erlang.send_after(1_000, self(), :send_gossip)\n case File.read(ring_path) do\n {:ok, bin} ->\n set = :erlang.binary_to_term(bin)\n monitor(get_set(set))\n # should we call callback.handle_ring_change in such a situation ?\n {:ok, gen_ring(set, MapSet.new(get_set(set)), payload, 0, callback)}\n _ ->\n set = Crdtex.Set.new\n {:ok, set} = add(set, {node(), 1}, node())\n {:ok, gen_ring(set, MapSet.new([node()]), payload, 1, callback)}\n end\n end\n\n # payload management, mimicking a GenServer\n def call(server, action), do: GenServer.call(server, action)\n\n def cast(server, action), do: GenServer.cast(server, action)\n\n def reply(client, term), do: GenServer.reply(client, term)\n\n # cluster_management\n # we have to stop all nodes\n def stop({name, n} = server, reason \\\\ :normal, timeout \\\\ :infinity) do\n {:ok, ring} = get_ring(server)\n others = ring.up_set |> MapSet.delete(n)\n Enum.each(others, fn(n) -> GenServer.stop({name, n}, reason, timeout) end)\n Genserver.stop(server, reason, timeout)\n end\n\n def add_node(server, node) when is_binary(node) do\n add_node(server, :\"#{node}\")\n end\n def add_node(server, node) when is_atom(node) do\n GenServer.cast(server, {:add_node, node})\n end\n\n def del_node(server, node) when is_binary(node) do\n del_node(server, :\"#{node}\")\n end\n def del_node(server, node) when is_atom(node) do\n GenServer.cast(server, {:del_node, node})\n end\n\n # forbid the use of the given node (no gossip sent to it, gossip from it\n # ignored) but it might still be up, it will continue to be monitored as long\n # as it is up.\n def force_down(server, n), do: GenServer.call(server, {:forced_down, n})\n\n # remove a node of the forced_down state\n def unforce_down(server, n), do: GenServer.call(server, {:unforced_down, n})\n\n def all(server), do: GenServer.call(server, :get_all)\n def up(server), do: GenServer.call(server, :get_up)\n\n # classic GenServer callbacks\n def handle_call(:get_all, _, ring), do: {:reply, get_set(ring.node_set), ring}\n def handle_call(:get_up, _, ring) do\n {:reply, MapSet.to_list(up_nodes(ring)), ring}\n end\n def handle_call(:get_ring, _, ring), do: {:reply, {:ok, ring}, ring}\n def handle_call({:forced_down, n}, _, ring) do\n counter = ring.counter + 1\n {:ok, forced_down} = add(ring.forced_down, {node(), counter}, n)\n {:reply, get_set(forced_down),\n %{ring | forced_down: forced_down, counter: counter}}\n end\n def handle_call({:unforced_down, n}, _, ring) do\n counter = ring.counter + 1\n {:ok, forced_down} = delete(ring.forced_down, {node(), counter}, n)\n up_set = ring.up_set\n up_set =\n case MapSet.member?(up_set, n) do\n true -> up_set\n false ->\n Node.monitor(n, true)\n MapSet.put(up_set, n)\n end\n {:reply, get_set(forced_down),\n %{ring | forced_down: forced_down, up_set: up_set, counter: counter}}\n end\n def handle_call(other, from, ring) do\n payload = ring.payload\n up_load = fn(load) -> update_payload(ring, load) end\n case ring.callback.handle_call(other, from, payload) do\n {:reply, reply, new} -> {:reply, reply, up_load.(new)}\n {:reply, reply, new, timeout} -> {:reply, reply, up_load.(new), timeout}\n {:noreply, new} -> {:noreply, up_load.(new)}\n {:noreply, new, timeout} -> {:noreply, up_load.(new), timeout}\n {:stop, reason, reply, new} -> {:stop, reason, reply, up_load.(new)}\n {:stop, reason, new} -> {:stop, reason, up_load.(new)}\n end\n end\n\n def handle_cast({:reconcile, gossip}, ring) do\n from_node = gossip.from_node\n up_set_reconcile(from_node, ring.up_set)\n ring_reconcile(from_node, gossip, ring)\n end\n def handle_cast({:add_node, n}, ring) do\n case contain?(ring.node_set, n) do\n true ->\n {:noreply, ring}\n false ->\n new_up_set = MapSet.put(ring.up_set, n)\n {:ok, new_node_set} = add(ring.node_set, {node(), ring.counter + 1}, n)\n {ring, _} =\n update_ring(%GenServerring{ring | up_set: new_up_set},\n %{node_set: new_node_set, payload: ring.payload, from_node: [],\n forced_down: ring.forced_down})\n {:noreply, ring}\n end\n end\n def handle_cast({:del_node, n}, ring) do\n case contain?(ring.node_set, n) do\n false ->\n {:noreply, ring}\n true ->\n new_up_set = MapSet.delete(ring.up_set, n)\n {:ok, new_node_set} =\n delete(ring.node_set, {node(), ring.counter + 1}, n)\n {ring, _} =\n update_ring(%GenServerring{ring | up_set: new_up_set},\n %{node_set: new_node_set, payload: ring.payload, from_node: [],\n forced_down: ring.forced_down})\n {:noreply, ring}\n end\n end\n def handle_cast(other, ring) do\n payload = ring.payload\n up_load = fn(load) -> update_payload(ring, load) end\n case ring.callback.handle_cast(other, payload) do\n {:noreply, new} -> {:noreply, up_load.(new)}\n {:noreply, new, timeout} -> {:noreply, up_load.(new), timeout}\n {:stop, reason, new} -> {:stop, reason, up_load.(new)}\n end\n end\n\n def handle_info(:send_gossip, %GenServerring{node_set: node_set} = ring) do\n :erlang.send_after(1_000, self(), :send_gossip)\n if not contain?(node_set, node()) do\n :erlang.send_after(5_000, self(), :halt_node)\n end\n case up_nodes(ring) |> MapSet.delete(node()) |> MapSet.to_list do\n [] -> {:noreply, ring}\n active_nodes ->\n {:registered_name, name} = Process.info(self(), :registered_name)\n random_node =\n Enum.at(active_nodes, :random.uniform(length(active_nodes)) - 1)\n GenServer.cast(\n {name, random_node},\n {:reconcile,\n %{node_set: node_set,\n forced_down: ring.forced_down,\n payload: ring.payload,\n from_node: [node()]}})\n {:noreply, ring}\n end\n end\n def handle_info({:nodedown, n}, %GenServerring{up_set: up_set} = ring) do\n new_up_set =\n case MapSet.member?(up_set, n) do\n true ->\n set = MapSet.delete(up_set, n)\n {:registered_name, name} = Process.info(self(), :registered_name)\n ring.callback.handle_ring_change({MapSet.to_list(set), name,\n :nodedown})\n set\n false -> up_set\n end\n {:noreply, %{ring | up_set: new_up_set}}\n end\n def handle_info(:halt_node, s) do\n File.rm(ring_path)\n :init.stop()\n {:noreply, s}\n end\n def handle_info(other, ring) do\n up_load = fn(load) -> update_payload(ring, load) end\n case ring.callback.handle_info(other, ring.payload) do\n {:noreply, new} -> {:noreply, up_load.(new)}\n {:noreply, new, timeout} -> {:noreply, up_load.(new), timeout}\n {:stop, reason, new} -> {:stop, reason, up_load.(new)}\n end\n end\n\n # small utilities functions\n defp value(payload), do: Crdtex.value(payload)\n\n defp get_set(set), do: Crdtex.value(set)\n\n defp contain?(set, e), do: Crdtex.value(set, {:contains, e})\n\n defp add(set, actor, e), do: Crdtex.update(set, actor, {:add, e})\n\n defp delete(set, actor, e), do: Crdtex.update(set, actor, {:remove, e})\n\n defp merge(nil, crdt), do: crdt\n defp merge(crdt, crdt), do: crdt\n defp merge(crdt1, crdt2), do: Crdtex.merge(crdt1, crdt2)\n\n defp get_ring(server), do: GenServer.call(server, :get_ring)\n\n defp up_nodes(ring) do\n MapSet.difference(ring.up_set, MapSet.new(get_set(ring.forced_down)))\n end\n\n defp monitor(list) do\n list = List.delete(list, node())\n Enum.each(list, fn(n) -> Node.monitor(n, :true) end)\n end\n\n defp gen_ring(set, up, payload, counter, callback) do\n gen_ring(set, up, payload, counter, callback, Crdtex.Set.new)\n end\n defp gen_ring(set, up, payload, counter, callback, forced_down) do\n %GenServerring{node_set: set, up_set: up, forced_down: forced_down,\n payload: payload, counter: counter, callback: callback}\n end\n\n defp update_payload(ring, payload) do\n {ring, _} =\n update_ring(ring,\n %{node_set: ring.node_set, payload: payload, from_node: [],\n forced_down: ring.forced_down})\n ring\n end\n\n defp update_ring(ring, changes) do\n merged_node_set = merge(ring.node_set, changes.node_set)\n merged_payload = merge(ring.payload, changes.payload)\n merged_forced_down = merge(ring.forced_down, changes.forced_down)\n updated_counter = update_counter(merged_node_set, merged_payload, ring)\n\n up_set =\n notify_up_set(get_set(ring.node_set), get_set(merged_node_set),\n ring.up_set, changes.from_node, ring.callback)\n notify_node_set(ring.node_set, merged_node_set, changes.node_set)\n\n old_payload = ring.payload\n ring =\n gen_ring(merged_node_set, up_set, merged_payload, updated_counter,\n ring.callback, merged_forced_down)\n {ring, notify_payload(value(old_payload), value(changes.payload), ring)}\n end\n\n defp update_counter(merged_node_set, merged_payload, old_ring) do\n old_nodes = old_ring.node_set\n old_payload = old_ring.payload\n case {merged_node_set, merged_payload} do\n {^old_nodes, ^old_payload} -> old_ring.counter\n _ -> old_ring.counter + 1\n end\n end\n\n defp notify_up_set(set, set, old_up, [], _), do: old_up\n defp notify_up_set(set, set, old_up, [n], callback) do\n case MapSet.member?(old_up, n) do\n true -> old_up\n false -> notify_up_set(set, set, MapSet.put(old_up, n), callback)\n end\n end\n defp notify_up_set(old, merged, up, [], callback) do\n notify_up_set(old, merged, up, callback)\n end\n defp notify_up_set(old, merged, up, [n], callback) do\n notify_up_set(old, merged, MapSet.put(up, n), callback)\n end\n\n defp notify_up_set(old_set, merged_set, old_up, callback) do\n new_up = MapSet.difference(MapSet.new(merged_set), MapSet.new(old_set))\n Enum.each(new_up, fn(n) -> Node.monitor(n, :true) end)\n new_set = MapSet.union(new_up, old_up)\n GenEvent.notify(GenServerring.Events, {:new_up_set, old_up, new_set})\n {:registered_name, name} = Process.info(self(), :registered_name)\n callback.handle_ring_change({MapSet.to_list(new_set), name, :gossip})\n new_set\n end\n\n defp notify_node_set(set, set, _), do: :nothingtodo\n defp notify_node_set(old_set, _, new_set) do\n GenEvent.notify(GenServerring.Events, {:new_node_set, get_set(old_set), get_set(new_set)})\n File.write!(ring_path, new_set |> :erlang.term_to_binary)\n end\n\n defp notify_payload(payload, payload, _), do: :no_payload_change\n defp notify_payload(_, _, ring), do: ring.payload\n\n defp ring_path,\n do: \"#{Application.get_env(:gen_serverring, :data_dir, \".\/data\")}\/ring\"\n\n defp up_set_reconcile([], _), do: :nothingtodo\n defp up_set_reconcile([n], up_set) do\n case MapSet.member?(up_set, n) do\n true -> :nothingtodo\n false -> Node.monitor(n, true)\n end\n end\n\n defp ring_reconcile([n], gossip, ring) do\n case contain?(ring.forced_down, n) do\n true -> {:noreply, ring} # must ignore gossips from forced_down nodes\n false -> ring_reconcile([], gossip, ring)\n end\n end\n defp ring_reconcile([], gossip, ring) do\n {ring, payload} = update_ring(ring, gossip)\n case payload do\n :no_payload_change -> :nothingtodo\n _ -> ring.callback.handle_state_change(payload)\n end\n {:noreply, ring}\n end\nend\n\ndefmodule GenServerring.App do\n use Application\n\n def start(type, []) do\n name = Application.get_env(:gen_serverring, :name, :demo_ring)\n callback = Application.get_env(:gen_serverring, :callback, Demo)\n start(type, [{name, callback}])\n end\n def start(_type, args) do\n Supervisor.start_link(GenServerring.App.Sup, args)\n end\n\n defmodule Sup do\n use Supervisor\n\n def init(:no_child) do\n # just start a GenEvent, no event_handler are defined, add yours if you\n # need some\n event_name = GenServerring.Events\n child = [worker(:gen_event, [{:local, event_name}], id: event_name)]\n supervise(child, strategy: :one_for_one)\n end\n def init(arg) do\n event_name = GenServerring.Events\n children =\n [worker(:gen_event, [{:local, event_name}], id: event_name),\n worker(GenServerring, arg)]\n supervise(children, strategy: :one_for_one)\n end\n end\nend\n\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"74882221af8d4fd96cd5d88e32fa6a6b3df44c77","subject":"fix github hook","message":"fix github hook\n","repos":"hamiltop\/ashes,hamiltop\/ashes","old_file":"lib\/ashes\/github_webhook_plug.ex","new_file":"lib\/ashes\/github_webhook_plug.ex","new_contents":"defmodule GithubWebhookPlug do\n import Plug.Conn\n \n def init(options) do\n options\n end\n\n def call(conn, options) do\n mount = Dict.get(options, :mount)\n case conn.path_info do\n [^mount] -> github_api(conn, options)\n _ -> conn\n end\n # if not mount matches => return\n # if no signature => error\n # if signature doesn't match => error\n # done.\n end\n\n def github_api(conn, options) do\n key = Dict.get(options, :secret)\n {:ok, body, _} = read_body(conn)\n signature = case get_req_header(conn, \"x-hub-signature\") do\n [\"sha1=\" <> signature | []] -> \n {:ok, signature} = Base.decode16(signature, case: :lower) \n signature\n x -> x\n end\n hmac = :crypto.hmac(:sha, key, body)\n case hmac do\n ^signature ->\n params = Poison.decode!(body)\n name = params[\"repository\"][\"name\"]\n GenServer.cast(JobManager, {:clone, name, params})\n conn\n |> put_resp_content_type(\"text\/plain\")\n |> send_resp(200, \"Hello world\")\n |> halt\n _ ->\n conn\n |> put_resp_content_type(\"text\/plain\")\n |> send_resp(401, \"Not Authorized\")\n |> halt\n end\n end\nend\n","old_contents":"defmodule GithubWebhookPlug do\n import Plug.Conn\n \n def init(options) do\n options\n end\n\n def call(conn, options) do\n mount = Dict.get(options, :mount)\n case hd(conn.path_info) do\n ^mount -> github_api(conn, options)\n _ -> conn\n end\n # if not mount matches => return\n # if no signature => error\n # if signature doesn't match => error\n # done.\n end\n\n def github_api(conn, options) do\n key = Dict.get(options, :secret)\n {:ok, body, _} = read_body(conn)\n signature = case get_req_header(conn, \"x-hub-signature\") do\n [\"sha1=\" <> signature | []] -> \n {:ok, signature} = Base.decode16(signature, case: :lower) \n signature\n x -> x\n end\n hmac = :crypto.hmac(:sha, key, body)\n case hmac do\n ^signature ->\n params = Poison.decode!(body)\n name = params[\"repository\"][\"name\"]\n GenServer.cast(JobManager, {:clone, name, params})\n conn\n |> put_resp_content_type(\"text\/plain\")\n |> send_resp(200, \"Hello world\")\n |> halt\n _ ->\n conn\n |> put_resp_content_type(\"text\/plain\")\n |> send_resp(401, \"Not Authorized\")\n |> halt\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"bd4f247aa0a841b95f4253af2f2ac2bf9bb2bb42","subject":"Remove unused unit parameter","message":"Remove unused unit parameter\n\nFor this version of the function, the label and separator are\nexplicit, so there is no need for the unit\n","repos":"PragTob\/benchee","old_file":"lib\/benchee\/conversion\/format.ex","new_file":"lib\/benchee\/conversion\/format.ex","new_contents":"defmodule Benchee.Conversion.Format do\n @moduledoc \"\"\"\n Functions for formatting values and their unit labels. Different domains\n handle this task differently, for example durations and counts.\n\n See `Benchee.Conversion.Count` and `Benchee.Conversion.Duration` for examples\n \"\"\"\n\n alias Benchee.Conversion.Unit\n\n @doc \"\"\"\n Formats a number as a string, with a unit label. See `Benchee.Conversion.Count`\n and `Benchee.Conversion.Duration` for examples\n \"\"\"\n @callback format(number) :: String.t\n\n # Generic formatting functions\n\n @doc \"\"\"\n Formats a unit value with specified label and separator\n \"\"\"\n def format(count, label, separator) do\n separator = separator(label, separator)\n \"~.#{float_precision(count)}f~ts~ts\"\n |> :io_lib.format([count, separator, label])\n |> to_string\n end\n\n @doc \"\"\"\n Formats a unit value in the domain described by `module`. The module should\n provide a `units\/0` function that returns a Map like\n\n %{ :unit_name => %Benchee.Conversion.Unit{ ... } }\n\n Additionally, `module` may specify a `separator\/0` function, which provides a\n custom separator string that will appear between the value and label in the\n formatted output. If no `separator\/0` function exists, the default separator\n (a single space) will be used.\n \"\"\"\n def format({count, unit}, module) do\n format(count, label(module, unit), separator(module))\n end\n\n @doc \"\"\"\n Scales a number to the most appropriate unit as defined in `module`, and\n formats the scaled value with a label. The module should provide a `units\/0`\n function that returns a Map like\n\n %{ :unit_name => %Benchee.Conversion.Unit{ ... } }\n \"\"\"\n def format(number, module) do\n number\n |> module.scale\n |> format(module)\n end\n\n # Returns the separator defined in `module.separator\/0`, or the default, a space\n defp separator(module) do\n case function_exported?(module, :separator, 0) do\n true -> module.separator()\n false -> \" \"\n end\n end\n\n # Returns the separator, or an empty string if there isn't a label\n defp separator(label, _separator) when label == \"\" or label == nil, do: \"\"\n defp separator(_label, separator), do: separator\n\n # Fetches the label for the given unit\n defp label(module, unit) do\n Unit.label(module, unit)\n end\n\n defp float_precision(float) when float < 0.01, do: 5\n defp float_precision(float) when float < 0.1, do: 4\n defp float_precision(float) when float < 0.2, do: 3\n defp float_precision(_float), do: 2\nend\n","old_contents":"defmodule Benchee.Conversion.Format do\n @moduledoc \"\"\"\n Functions for formatting values and their unit labels. Different domains\n handle this task differently, for example durations and counts.\n\n See `Benchee.Conversion.Count` and `Benchee.Conversion.Duration` for examples\n \"\"\"\n\n alias Benchee.Conversion.Unit\n\n @doc \"\"\"\n Formats a number as a string, with a unit label. See `Benchee.Conversion.Count`\n and `Benchee.Conversion.Duration` for examples\n \"\"\"\n @callback format(number) :: String.t\n\n # Generic formatting functions\n\n @doc \"\"\"\n Formats a unit value with specified label and separator\n \"\"\"\n def format({count, _unit}, label, separator) do\n separator = separator(label, separator)\n \"~.#{float_precision(count)}f~ts~ts\"\n |> :io_lib.format([count, separator, label])\n |> to_string\n end\n\n @doc \"\"\"\n Formats a unit value in the domain described by `module`. The module should\n provide a `units\/0` function that returns a Map like\n\n %{ :unit_name => %Benchee.Conversion.Unit{ ... } }\n\n Additionally, `module` may specify a `separator\/0` function, which provides a\n custom separator string that will appear between the value and label in the\n formatted output. If no `separator\/0` function exists, the default separator\n (a single space) will be used.\n \"\"\"\n def format({count, unit}, module) do\n format({count, unit}, label(module, unit), separator(module))\n end\n\n @doc \"\"\"\n Scales a number to the most appropriate unit as defined in `module`, and\n formats the scaled value with a label. The module should provide a `units\/0`\n function that returns a Map like\n\n %{ :unit_name => %Benchee.Conversion.Unit{ ... } }\n \"\"\"\n def format(number, module) do\n number\n |> module.scale\n |> format(module)\n end\n\n # Returns the separator defined in `module.separator\/0`, or the default, a space\n defp separator(module) do\n case function_exported?(module, :separator, 0) do\n true -> module.separator()\n false -> \" \"\n end\n end\n\n # Returns the separator, or an empty string if there isn't a label\n defp separator(label, _separator) when label == \"\" or label == nil, do: \"\"\n defp separator(_label, separator), do: separator\n\n # Fetches the label for the given unit\n defp label(module, unit) do\n Unit.label(module, unit)\n end\n\n defp float_precision(float) when float < 0.01, do: 5\n defp float_precision(float) when float < 0.1, do: 4\n defp float_precision(float) when float < 0.2, do: 3\n defp float_precision(_float), do: 2\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"98b76b1055621f862a6c183f5977065c62690fda","subject":"Fix ambiguous pipe","message":"Fix ambiguous pipe\n","repos":"FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os","old_file":"lib\/farmbot\/firmware\/firmware.ex","new_file":"lib\/farmbot\/firmware\/firmware.ex","new_contents":"defmodule Farmbot.Firmware do\n @moduledoc \"Allows communication with the firmware.\"\n\n use GenStage\n use Farmbot.Logger\n alias Farmbot.Bootstrap.SettingsSync\n alias Farmbot.Firmware.{Command, CompletionLogs, Vec3, EstopTimer, Utils}\n import Utils\n\n import Farmbot.System.ConfigStorage,\n only: [get_config_value: 3, update_config_value: 4, get_config_as_map: 0]\n\n import CompletionLogs,\n only: [maybe_log_complete: 2]\n\n # If any command takes longer than this, exit.\n @call_timeout 500_000\n\n @doc \"Move the bot to a position.\"\n def move_absolute(%Vec3{} = vec3, x_spd, y_spd, z_spd) do\n call = {:move_absolute, [vec3, x_spd, y_spd, z_spd]}\n GenStage.call(__MODULE__, call, @call_timeout)\n end\n\n @doc \"Calibrate an axis.\"\n def calibrate(axis) do\n GenStage.call(__MODULE__, {:calibrate, [axis]}, @call_timeout)\n end\n\n @doc \"Find home on an axis.\"\n def find_home(axis) do\n GenStage.call(__MODULE__, {:find_home, [axis]}, @call_timeout)\n end\n\n @doc \"Home every axis.\"\n def home_all() do\n GenStage.call(__MODULE__, {:home_all, []}, @call_timeout)\n end\n\n @doc \"Home an axis.\"\n def home(axis) do\n GenStage.call(__MODULE__, {:home, [axis]}, @call_timeout)\n end\n\n @doc \"Manually set an axis's current position to zero.\"\n def zero(axis) do\n GenStage.call(__MODULE__, {:zero, [axis]}, @call_timeout)\n end\n\n @doc \"\"\"\n Update a paramater.\n For a list of paramaters see `Farmbot.Firmware.Gcode.Param`\n \"\"\"\n def update_param(param, val) do\n GenStage.call(__MODULE__, {:update_param, [param, val]}, @call_timeout)\n end\n\n @doc false\n def read_all_params do\n GenStage.call(__MODULE__, {:read_all_params, []}, @call_timeout)\n end\n\n @doc \"\"\"\n Read a paramater.\n For a list of paramaters see `Farmbot.Firmware.Gcode.Param`\n \"\"\"\n def read_param(param) do\n GenStage.call(__MODULE__, {:read_param, [param]}, @call_timeout)\n end\n\n @doc \"Emergency lock Farmbot.\"\n def emergency_lock() do\n GenStage.call(__MODULE__, {:emergency_lock, []}, @call_timeout)\n end\n\n @doc \"Unlock Farmbot from Emergency state.\"\n def emergency_unlock() do\n GenStage.call(__MODULE__, {:emergency_unlock, []}, @call_timeout)\n end\n\n @doc \"Set a pin mode (`:input` | `:output` | `:input_pullup`)\"\n def set_pin_mode(pin, mode) do\n GenStage.call(__MODULE__, {:set_pin_mode, [pin, mode]}, @call_timeout)\n end\n\n @doc \"Read a pin.\"\n def read_pin(pin, mode) do\n GenStage.call(__MODULE__, {:read_pin, [pin, mode]}, @call_timeout)\n end\n\n @doc \"Write a pin.\"\n def write_pin(pin, mode, value) do\n GenStage.call(__MODULE__, {:write_pin, [pin, mode, value]}, @call_timeout)\n end\n\n @doc \"Request version.\"\n def request_software_version do\n GenStage.call(__MODULE__, {:request_software_version, []}, @call_timeout)\n end\n\n @doc \"Set angle of a servo pin.\"\n def set_servo_angle(pin, value) do\n GenStage.call(__MODULE__, {:set_servo_angle, [pin, value]}, @call_timeout)\n end\n\n @doc \"Flag for all params reported.\"\n def params_reported do\n GenStage.call(__MODULE__, :params_reported)\n end\n\n @doc \"Start the firmware services.\"\n def start_link do\n GenStage.start_link(__MODULE__, [], name: __MODULE__)\n end\n\n ## GenStage\n\n defmodule State do\n @moduledoc false\n defstruct [\n handler: nil,\n handler_mod: nil,\n idle: false,\n timer: nil,\n pins: %{},\n params: %{},\n params_reported: false,\n initialized: false,\n initializing: false,\n current: nil,\n timeout_ms: 150_000,\n queue: :queue.new(),\n x_needs_home_on_boot: false,\n y_needs_home_on_boot: false,\n z_needs_home_on_boot: false\n ]\n end\n\n defp needs_home_on_boot do\n x = (get_config_value(:float, \"hardware_params\", \"movement_home_at_boot_x\") || 0)\n |> num_to_bool()\n\n y = (get_config_value(:float, \"hardware_params\", \"movement_home_at_boot_y\") || 0)\n |> num_to_bool()\n\n z = (get_config_value(:float, \"hardware_params\", \"movement_home_at_boot_z\") || 0)\n |> num_to_bool()\n\n %{\n x_needs_home_on_boot: x,\n y_needs_home_on_boot: y,\n z_needs_home_on_boot: z,\n }\n end\n\n def init([]) do\n handler_mod =\n Application.get_env(:farmbot, :behaviour)[:firmware_handler] || raise(\"No fw handler.\")\n\n case handler_mod.start_link() do\n {:ok, handler} ->\n initial = Map.merge(needs_home_on_boot(), %{handler: handler, handler_mod: handler_mod})\n Process.flag(:trap_exit, true)\n {\n :producer_consumer,\n struct(State, initial),\n subscribe_to: [handler], dispatcher: GenStage.BroadcastDispatcher\n }\n {:error, reason} ->\n replace_firmware_handler(Farmbot.Firmware.StubHandler)\n Logger.error 1, \"Failed to initialize firmware: #{inspect reason} Falling back to stub implementation.\"\n init([])\n end\n\n end\n\n def terminate(reason, state) do\n unless reason in [:normal, :shutdown] do\n replace_firmware_handler(Farmbot.Firmware.StubHandler)\n end\n\n unless :queue.is_empty(state.queue) do\n list = :queue.to_list(state.queue)\n for cmd <- list do\n :ok = do_reply(%{state | current: cmd}, {:error, reason})\n end\n end\n end\n\n def handle_info({:EXIT, _pid, :normal}, state) do\n {:stop, :normal, state}\n end\n\n def handle_info({:EXIT, _, reason}, state) do\n Logger.error 1, \"Firmware handler: #{state.handler_mod} died: #{inspect reason}\"\n case state.handler_mod.start_link() do\n {:ok, handler} ->\n new_state = %{state | handler: handler}\n {:noreply, [{:informational_settings, %{busy: false}}], %{new_state | initialized: false, idle: false}}\n err -> {:stop, err, %{state | handler: false}}\n end\n end\n\n # TODO(Connor): Put some sort of exit strategy here.\n # If a firmware command keeps timingout\/failing, Farmbot OS just keeps trying\n # it. This can lead to infinate failures.\n def handle_info({:command_timeout, %Command{} = timeout_command}, state) do\n case state.current do\n # Check if this timeout is actually talking about the current command.\n ^timeout_command = current ->\n Logger.warn 1, \"Timed out waiting for Firmware response. Retrying #{inspect current}) \"\n case apply(state.handler_mod, current.fun, [state.handler | current.args]) do\n :ok ->\n timer = start_timer(current, state.timeout_ms)\n {:noreply, [], %{state | current: current, timer: timer}}\n {:error, _} = res ->\n do_reply(state, res)\n {:noreply, [], %{state | current: nil, queue: :queue.new()}}\n end\n\n # If this timeout was not talking about the current command\n %Command{} = current ->\n Logger.debug 3, \"Got stray timeout for command: #{inspect current}\"\n {:noreply, [], %{state | timer: nil}}\n\n # If there is no current command, we got a different kind of stray.\n # This is ok i guess.\n nil -> {:noreply, [], %{state | timer: nil}}\n\n end\n end\n\n def handle_call(:params_reported, _, state) do\n {:reply, state.params_reported, [], state}\n end\n\n def handle_call({fun, _}, _from, state = %{initialized: false})\n when fun not in [:read_all_params, :update_param, :emergency_unlock, :emergency_lock, :request_software_version] do\n {:reply, {:error, :uninitialized}, [], state}\n end\n\n def handle_call({fun, args}, from, state) do\n next_current = struct(Command, from: from, fun: fun, args: args)\n current_current = state.current\n cond do\n fun == :emergency_lock ->\n if current_current do\n do_reply(state, {:error, :emergency_lock})\n end\n do_begin_cmd(next_current, state, [])\n match?(%Command{}, current_current) ->\n do_queue_cmd(next_current, state)\n is_nil(current_current) ->\n do_begin_cmd(next_current, state, [])\n end\n end\n\n defp do_begin_cmd(%Command{fun: fun, args: args, from: _from} = current, state, dispatch) do\n case apply(state.handler_mod, fun, [state.handler | args]) do\n :ok ->\n timer = start_timer(current, state.timeout_ms)\n if fun == :emergency_unlock do\n Farmbot.System.GPIO.Leds.led_status_ok()\n new_dispatch = [{:informational_settings, %{busy: false, locked: false}} | dispatch]\n {:noreply, new_dispatch, %{state | current: current, timer: timer}}\n else\n {:noreply, dispatch, %{state | current: current, timer: timer}}\n end\n {:error, _} = res ->\n do_reply(%{state | current: current}, res)\n {:noreply, dispatch, %{state | current: nil}}\n end\n end\n\n defp do_queue_cmd(%Command{fun: _fun, args: _args, from: _from} = current, state) do\n # Logger.busy 3, \"FW Queuing: #{fun}: #{inspect from}\"\n new_q = :queue.in(current, state.queue)\n {:noreply, [], %{state | queue: new_q}}\n end\n\n def handle_events(gcodes, _from, state) do\n {diffs, state} = handle_gcodes(gcodes, state)\n # if after handling the current buffer of gcodes,\n # Try to start the next command in the queue if it exists.\n if List.last(gcodes) == :idle && state.current == nil do\n case :queue.out(state.queue) do\n {{:value, next_current}, new_queue} ->\n do_begin_cmd(next_current, %{state | queue: new_queue, current: next_current}, diffs)\n {:empty, queue} -> # nothing to do if the queue is empty.\n {:noreply, diffs, %{state | queue: queue}}\n end\n else\n {:noreply, diffs, state}\n end\n end\n\n defp handle_gcodes(codes, state, acc \\\\ [])\n\n defp handle_gcodes([], state, acc), do: {Enum.reverse(acc), state}\n\n defp handle_gcodes([code | rest], state, acc) do\n case handle_gcode(code, state) do\n {nil, new_state} -> handle_gcodes(rest, new_state, acc)\n {key, diff, new_state} -> handle_gcodes(rest, new_state, [{key, diff} | acc])\n end\n end\n\n defp handle_gcode({:debug_message, message}, state) do\n if get_config_value(:bool, \"settings\", \"arduino_debug_messages\") do\n Logger.debug 3, \"Arduino debug message: #{message}\"\n end\n {nil, state}\n end\n\n defp handle_gcode(code, state) when code in [:error, :invalid_command] do\n maybe_cancel_timer(state.timer, state.current)\n if state.current do\n Logger.error 1, \"Got #{code} while executing `#{inspect state.current}`.\"\n do_reply(state, {:error, :firmware_error})\n {nil, %{state | current: nil}}\n else\n {nil, state}\n end\n end\n\n defp handle_gcode(:report_no_config, state) do\n Logger.busy 1, \"Initializing Firmware.\"\n old = get_config_as_map()[\"hardware_params\"]\n spawn __MODULE__, :do_read_params, [Map.delete(old, \"param_version\")]\n {nil, %{state | initialized: false, initializing: true}}\n end\n\n defp handle_gcode(:report_params_complete, state) do\n {nil, %{state | initialized: true, initializing: false}}\n end\n\n defp handle_gcode(:idle, %{initialized: false, initializing: false} = state) do\n Logger.busy 1, \"Firmware not initialized yet. Waiting for R88 message.\"\n {nil, state}\n end\n\n defp handle_gcode(:idle, %{initialized: true, initializing: false, current: nil, z_needs_home_on_boot: true} = state) do\n Logger.info 2, \"Bootup homing Z axis\"\n spawn __MODULE__, :find_home, [:z]\n {nil, %{state | z_needs_home_on_boot: false}}\n end\n\n defp handle_gcode(:idle, %{initialized: true, initializing: false, current: nil, y_needs_home_on_boot: true} = state) do\n Logger.info 2, \"Bootup homing Y axis\"\n spawn __MODULE__, :find_home, [:y]\n {nil, %{state | y_needs_home_on_boot: false}}\n end\n\n defp handle_gcode(:idle, %{initialized: true, initializing: false, current: nil, x_needs_home_on_boot: true} = state) do\n Logger.info 2, \"Bootup homing X axis\"\n spawn __MODULE__, :find_home, [:x]\n {nil, %{state | x_needs_home_on_boot: false}}\n end\n\n defp handle_gcode(:idle, state) do\n maybe_cancel_timer(state.timer, state.current)\n Farmbot.BotState.set_busy(false)\n if state.current do\n # This might be a bug in the FW\n if state.current.fun in [:home, :home_all] do\n Logger.warn 1, \"Got idle during home.\"\n timer = start_timer(state.current, state.timeout_ms)\n {nil, %{state | timer: timer}}\n else\n Logger.warn 1, \"Got idle while executing a command.\"\n do_reply(state, {:error, :timeout})\n {:informational_settings, %{busy: false, locked: false}, %{state | current: nil, idle: true}}\n end\n else\n {:informational_settings, %{busy: false, locked: false}, %{state | idle: true}}\n end\n end\n\n defp handle_gcode({:report_current_position, x, y, z}, state) do\n {:location_data, %{position: %{x: round(x), y: round(y), z: round(z)}}, state}\n end\n\n defp handle_gcode({:report_encoder_position_scaled, x, y, z}, state) do\n {:location_data, %{scaled_encoders: %{x: x, y: y, z: z}}, state}\n end\n\n defp handle_gcode({:report_encoder_position_raw, x, y, z}, state) do\n {:location_data, %{raw_encoders: %{x: x, y: y, z: z}}, state}\n end\n\n defp handle_gcode({:report_end_stops, xa, xb, ya, yb, za, zb}, state) do\n diff = %{end_stops: %{xa: xa, xb: xb, ya: ya, yb: yb, za: za, zb: zb}}\n {:location_data, diff, state}\n {nil, state}\n end\n\n defp handle_gcode({:report_pin_mode, pin, mode_atom}, state) do\n # Logger.debug 3, \"Got pin mode report: #{pin}: #{mode_atom}\"\n mode = extract_pin_mode(mode_atom)\n case state.pins[pin] do\n %{mode: _, value: _} = pin_map ->\n {:pins, %{pin => %{pin_map | mode: mode}}, %{state | pins: %{state.pins | pin => %{pin_map | mode: mode}}}}\n nil ->\n {:pins, %{pin => %{mode: mode, value: -1}}, %{state | pins: Map.put(state.pins, pin, %{mode: mode, value: -1})}}\n end\n end\n\n defp handle_gcode({:report_pin_value, pin, value}, state) do\n # Logger.debug 3, \"Got pin value report: #{pin}: #{value} old: #{inspect state.pins[pin]}\"\n case state.pins[pin] do\n %{mode: _, value: _} = pin_map ->\n {:pins, %{pin => %{pin_map | value: value}}, %{state | pins: %{state.pins | pin => %{pin_map | value: value}}}}\n nil ->\n {:pins, %{pin => %{mode: nil, value: value}}, %{state | pins: Map.put(state.pins, pin, %{mode: nil, value: value})}}\n end\n end\n\n defp handle_gcode({:report_parameter_value, param, value}, state) when (value == -1) do\n maybe_update_param_from_report(to_string(param), nil)\n {:mcu_params, %{param => nil}, %{state | params: Map.put(state.params, param, value)}}\n end\n\n defp handle_gcode({:report_parameter_value, param, value}, state) when is_number(value) do\n maybe_update_param_from_report(to_string(param), value)\n {:mcu_params, %{param => value}, %{state | params: Map.put(state.params, param, value)}}\n end\n\n defp handle_gcode({:report_software_version, version}, state) do\n case String.last(version) do\n \"F\" ->\n update_config_value(:string, \"settings\", \"firmware_hardware\", \"farmduino\")\n \"R\" ->\n update_config_value(:string, \"settings\", \"firmware_hardware\", \"arduino\")\n \"G\" ->\n update_config_value(:string, \"settings\", \"firmware_hardware\", \"farmduino_k14\")\n _ -> :ok\n end\n {:informational_settings, %{firmware_version: version}, state}\n end\n\n defp handle_gcode(:report_axis_home_complete_x, state) do\n {nil, state}\n end\n\n defp handle_gcode(:report_axis_home_complete_y, state) do\n {nil, state}\n end\n\n defp handle_gcode(:report_axis_home_complete_z, state) do\n {nil, %{state | timer: nil}}\n end\n\n defp handle_gcode(:report_axis_timeout_x, state) do\n do_reply(state, {:error, :axis_timeout_x})\n {nil, %{state | timer: nil}}\n end\n\n defp handle_gcode(:report_axis_timeout_y, state) do\n do_reply(state, {:error, :axis_timeout_y})\n {nil, %{state | timer: nil}}\n end\n\n defp handle_gcode(:report_axis_timeout_z, state) do\n do_reply(state, {:error, :axis_timeout_z})\n {nil, %{state | timer: nil}}\n end\n\n defp handle_gcode({:report_axis_changed_x, _new_x} = msg, state) do\n new_current = Command.add_status(state.current, msg)\n {nil, %{state | current: new_current}}\n end\n\n defp handle_gcode({:report_axis_changed_y, _new_y} = msg, state) do\n new_current = Command.add_status(state.current, msg)\n {nil, %{state | current: new_current}}\n end\n\n defp handle_gcode({:report_axis_changed_z, _new_z} = msg, state) do\n new_current = Command.add_status(state.current, msg)\n {nil, %{state | current: new_current}}\n end\n\n defp handle_gcode(:busy, state) do\n Farmbot.BotState.set_busy(true)\n maybe_cancel_timer(state.timer, state.current)\n timer = if state.current do\n start_timer(state.current, state.timeout_ms)\n else\n nil\n end\n {:informational_settings, %{busy: true}, %{state | idle: false, timer: timer}}\n end\n\n defp handle_gcode(:done, state) do\n maybe_cancel_timer(state.timer, state.current)\n Farmbot.BotState.set_busy(false)\n if state.current do\n do_reply(state, :ok)\n {nil, %{state | current: nil}}\n else\n {nil, state}\n end\n end\n\n defp handle_gcode(:report_emergency_lock, state) do\n Farmbot.System.GPIO.Leds.led_status_err\n maybe_send_email()\n if state.current do\n do_reply(state, {:error, :emergency_lock})\n {:informational_settings, %{locked: true}, %{state | current: nil}}\n else\n {:informational_settings, %{locked: true}, state}\n end\n end\n\n defp handle_gcode({:report_calibration, axis, status}, state) do\n maybe_cancel_timer(state.timer, state.current)\n Logger.busy 1, \"Axis #{axis} calibration: #{status}\"\n {nil, state}\n end\n\n defp handle_gcode({:report_axis_calibration, param, val}, state) do\n spawn __MODULE__, :report_calibration_callback, [5, param, val]\n {nil, state}\n end\n\n defp handle_gcode(:noop, state) do\n {nil, state}\n end\n\n defp handle_gcode(:received, state) do\n {nil, state}\n end\n\n defp handle_gcode({:echo, _code}, state) do\n {nil, state}\n end\n\n defp handle_gcode(code, state) do\n Logger.warn(3, \"unhandled code: #{inspect(code)}\")\n {nil, state}\n end\n\n defp maybe_cancel_timer(nil, current_command) do\n if current_command do\n # Logger.debug 3, \"[WEIRD] - No timer to cancel for command: #{inspect current_command}\"\n :ok\n else\n # Logger.debug 3, \"[PROBABLY OK] - No timer to cancel, and no command here.\"\n :ok\n end\n end\n\n defp maybe_cancel_timer(timer, _current_command) do\n if Process.read_timer(timer) do\n # Logger.debug 3, \"[NORMAL] - Canceled timer: #{inspect timer} for command: #{inspect current_command}\"\n Process.cancel_timer(timer)\n :ok\n else\n :ok\n end\n end\n\n defp maybe_update_param_from_report(param, val) when is_binary(param) do\n real_val = if val, do: (val \/ 1), else: nil\n # Logger.debug 3, \"Firmware reported #{param} => #{val || -1}\"\n update_config_value(:float, \"hardware_params\", to_string(param), real_val)\n end\n\n @doc false\n def do_read_params(old) when is_map(old) do\n for {key, float_val} <- old do\n cond do\n (float_val == -1) -> :ok\n is_nil(float_val) -> :ok\n is_number(float_val) ->\n val = round(float_val)\n :ok = update_param(:\"#{key}\", val)\n end\n end\n :ok = update_param(:param_use_eeprom, 0)\n :ok = update_param(:param_config_ok, 1)\n read_all_params()\n :ok = request_software_version()\n end\n\n @doc false\n def report_calibration_callback(tries, param, value)\n\n def report_calibration_callback(0, _param, _value) do\n :ok\n end\n\n def report_calibration_callback(tries, param, val) do\n case Farmbot.Firmware.update_param(param, val) do\n :ok ->\n str_param = to_string(param)\n case get_config_value(:float, \"hardware_params\", str_param) do\n ^val ->\n Logger.success 1, \"Calibrated #{param}: #{val}\"\n SettingsSync.upload_fw_kv(str_param, val)\n :ok\n _ -> report_calibration_callback(tries - 1, param, val)\n end\n {:error, reason} ->\n Logger.error 1, \"Failed to set #{param}: #{val} (#{inspect reason})\"\n report_calibration_callback(tries - 1, param, val)\n end\n end\n\n defp do_reply(state, reply) do\n maybe_cancel_timer(state.timer, state.current)\n maybe_log_complete(state.current, reply)\n case state.current do\n %Command{fun: :emergency_unlock, from: from} ->\n # i really don't want this to be here..\n EstopTimer.cancel_timer()\n :ok = GenServer.reply from, reply\n %Command{fun: :emergency_lock, from: from} ->\n :ok = GenServer.reply from, {:error, :emergency_lock}\n %Command{fun: _fun, from: from} ->\n # Logger.success 3, \"FW Replying: #{fun}: #{inspect from}\"\n :ok = GenServer.reply from, reply\n nil ->\n Logger.error 1, \"FW Nothing to send reply: #{inspect reply} to!.\"\n :error\n end\n end\n\n defp maybe_send_email do\n if get_config_value(:bool, \"settings\", \"email_on_estop\") do\n if !EstopTimer.timer_active? do\n EstopTimer.start_timer()\n end\n end\n end\n\n defp start_timer(%Command{} = command, timeout) do\n Process.send_after(self(), {:command_timeout, command}, timeout)\n end\nend\n","old_contents":"defmodule Farmbot.Firmware do\n @moduledoc \"Allows communication with the firmware.\"\n\n use GenStage\n use Farmbot.Logger\n alias Farmbot.Bootstrap.SettingsSync\n alias Farmbot.Firmware.{Command, CompletionLogs, Vec3, EstopTimer, Utils}\n import Utils\n\n import Farmbot.System.ConfigStorage,\n only: [get_config_value: 3, update_config_value: 4, get_config_as_map: 0]\n\n import CompletionLogs,\n only: [maybe_log_complete: 2]\n\n # If any command takes longer than this, exit.\n @call_timeout 500_000\n\n @doc \"Move the bot to a position.\"\n def move_absolute(%Vec3{} = vec3, x_spd, y_spd, z_spd) do\n call = {:move_absolute, [vec3, x_spd, y_spd, z_spd]}\n GenStage.call(__MODULE__, call, @call_timeout)\n end\n\n @doc \"Calibrate an axis.\"\n def calibrate(axis) do\n GenStage.call(__MODULE__, {:calibrate, [axis]}, @call_timeout)\n end\n\n @doc \"Find home on an axis.\"\n def find_home(axis) do\n GenStage.call(__MODULE__, {:find_home, [axis]}, @call_timeout)\n end\n\n @doc \"Home every axis.\"\n def home_all() do\n GenStage.call(__MODULE__, {:home_all, []}, @call_timeout)\n end\n\n @doc \"Home an axis.\"\n def home(axis) do\n GenStage.call(__MODULE__, {:home, [axis]}, @call_timeout)\n end\n\n @doc \"Manually set an axis's current position to zero.\"\n def zero(axis) do\n GenStage.call(__MODULE__, {:zero, [axis]}, @call_timeout)\n end\n\n @doc \"\"\"\n Update a paramater.\n For a list of paramaters see `Farmbot.Firmware.Gcode.Param`\n \"\"\"\n def update_param(param, val) do\n GenStage.call(__MODULE__, {:update_param, [param, val]}, @call_timeout)\n end\n\n @doc false\n def read_all_params do\n GenStage.call(__MODULE__, {:read_all_params, []}, @call_timeout)\n end\n\n @doc \"\"\"\n Read a paramater.\n For a list of paramaters see `Farmbot.Firmware.Gcode.Param`\n \"\"\"\n def read_param(param) do\n GenStage.call(__MODULE__, {:read_param, [param]}, @call_timeout)\n end\n\n @doc \"Emergency lock Farmbot.\"\n def emergency_lock() do\n GenStage.call(__MODULE__, {:emergency_lock, []}, @call_timeout)\n end\n\n @doc \"Unlock Farmbot from Emergency state.\"\n def emergency_unlock() do\n GenStage.call(__MODULE__, {:emergency_unlock, []}, @call_timeout)\n end\n\n @doc \"Set a pin mode (`:input` | `:output` | `:input_pullup`)\"\n def set_pin_mode(pin, mode) do\n GenStage.call(__MODULE__, {:set_pin_mode, [pin, mode]}, @call_timeout)\n end\n\n @doc \"Read a pin.\"\n def read_pin(pin, mode) do\n GenStage.call(__MODULE__, {:read_pin, [pin, mode]}, @call_timeout)\n end\n\n @doc \"Write a pin.\"\n def write_pin(pin, mode, value) do\n GenStage.call(__MODULE__, {:write_pin, [pin, mode, value]}, @call_timeout)\n end\n\n @doc \"Request version.\"\n def request_software_version do\n GenStage.call(__MODULE__, {:request_software_version, []}, @call_timeout)\n end\n\n @doc \"Set angle of a servo pin.\"\n def set_servo_angle(pin, value) do\n GenStage.call(__MODULE__, {:set_servo_angle, [pin, value]}, @call_timeout)\n end\n\n @doc \"Flag for all params reported.\"\n def params_reported do\n GenStage.call(__MODULE__, :params_reported)\n end\n\n @doc \"Start the firmware services.\"\n def start_link do\n GenStage.start_link(__MODULE__, [], name: __MODULE__)\n end\n\n ## GenStage\n\n defmodule State do\n @moduledoc false\n defstruct [\n handler: nil,\n handler_mod: nil,\n idle: false,\n timer: nil,\n pins: %{},\n params: %{},\n params_reported: false,\n initialized: false,\n initializing: false,\n current: nil,\n timeout_ms: 150_000,\n queue: :queue.new(),\n x_needs_home_on_boot: false,\n y_needs_home_on_boot: false,\n z_needs_home_on_boot: false\n ]\n end\n\n defp needs_home_on_boot do\n x = get_config_value(:float, \"hardware_params\", \"movement_home_at_boot_x\") || 0\n |> num_to_bool()\n\n y = get_config_value(:float, \"hardware_params\", \"movement_home_at_boot_y\") || 0\n |> num_to_bool()\n\n z = get_config_value(:float, \"hardware_params\", \"movement_home_at_boot_z\") || 0\n |> num_to_bool()\n\n %{\n x_needs_home_on_boot: x,\n y_needs_home_on_boot: y,\n z_needs_home_on_boot: z,\n }\n end\n\n def init([]) do\n handler_mod =\n Application.get_env(:farmbot, :behaviour)[:firmware_handler] || raise(\"No fw handler.\")\n\n case handler_mod.start_link() do\n {:ok, handler} ->\n initial = Map.merge(needs_home_on_boot(), %{handler: handler, handler_mod: handler_mod})\n Process.flag(:trap_exit, true)\n {\n :producer_consumer,\n struct(State, initial),\n subscribe_to: [handler], dispatcher: GenStage.BroadcastDispatcher\n }\n {:error, reason} ->\n replace_firmware_handler(Farmbot.Firmware.StubHandler)\n Logger.error 1, \"Failed to initialize firmware: #{inspect reason} Falling back to stub implementation.\"\n init([])\n end\n\n end\n\n def terminate(reason, state) do\n unless reason in [:normal, :shutdown] do\n replace_firmware_handler(Farmbot.Firmware.StubHandler)\n end\n\n unless :queue.is_empty(state.queue) do\n list = :queue.to_list(state.queue)\n for cmd <- list do\n :ok = do_reply(%{state | current: cmd}, {:error, reason})\n end\n end\n end\n\n def handle_info({:EXIT, _pid, :normal}, state) do\n {:stop, :normal, state}\n end\n\n def handle_info({:EXIT, _, reason}, state) do\n Logger.error 1, \"Firmware handler: #{state.handler_mod} died: #{inspect reason}\"\n case state.handler_mod.start_link() do\n {:ok, handler} ->\n new_state = %{state | handler: handler}\n {:noreply, [{:informational_settings, %{busy: false}}], %{new_state | initialized: false, idle: false}}\n err -> {:stop, err, %{state | handler: false}}\n end\n end\n\n # TODO(Connor): Put some sort of exit strategy here.\n # If a firmware command keeps timingout\/failing, Farmbot OS just keeps trying\n # it. This can lead to infinate failures.\n def handle_info({:command_timeout, %Command{} = timeout_command}, state) do\n case state.current do\n # Check if this timeout is actually talking about the current command.\n ^timeout_command = current ->\n Logger.warn 1, \"Timed out waiting for Firmware response. Retrying #{inspect current}) \"\n case apply(state.handler_mod, current.fun, [state.handler | current.args]) do\n :ok ->\n timer = start_timer(current, state.timeout_ms)\n {:noreply, [], %{state | current: current, timer: timer}}\n {:error, _} = res ->\n do_reply(state, res)\n {:noreply, [], %{state | current: nil, queue: :queue.new()}}\n end\n\n # If this timeout was not talking about the current command\n %Command{} = current ->\n Logger.debug 3, \"Got stray timeout for command: #{inspect current}\"\n {:noreply, [], %{state | timer: nil}}\n\n # If there is no current command, we got a different kind of stray.\n # This is ok i guess.\n nil -> {:noreply, [], %{state | timer: nil}}\n\n end\n end\n\n def handle_call(:params_reported, _, state) do\n {:reply, state.params_reported, [], state}\n end\n\n def handle_call({fun, _}, _from, state = %{initialized: false})\n when fun not in [:read_all_params, :update_param, :emergency_unlock, :emergency_lock, :request_software_version] do\n {:reply, {:error, :uninitialized}, [], state}\n end\n\n def handle_call({fun, args}, from, state) do\n next_current = struct(Command, from: from, fun: fun, args: args)\n current_current = state.current\n cond do\n fun == :emergency_lock ->\n if current_current do\n do_reply(state, {:error, :emergency_lock})\n end\n do_begin_cmd(next_current, state, [])\n match?(%Command{}, current_current) ->\n do_queue_cmd(next_current, state)\n is_nil(current_current) ->\n do_begin_cmd(next_current, state, [])\n end\n end\n\n defp do_begin_cmd(%Command{fun: fun, args: args, from: _from} = current, state, dispatch) do\n case apply(state.handler_mod, fun, [state.handler | args]) do\n :ok ->\n timer = start_timer(current, state.timeout_ms)\n if fun == :emergency_unlock do\n Farmbot.System.GPIO.Leds.led_status_ok()\n new_dispatch = [{:informational_settings, %{busy: false, locked: false}} | dispatch]\n {:noreply, new_dispatch, %{state | current: current, timer: timer}}\n else\n {:noreply, dispatch, %{state | current: current, timer: timer}}\n end\n {:error, _} = res ->\n do_reply(%{state | current: current}, res)\n {:noreply, dispatch, %{state | current: nil}}\n end\n end\n\n defp do_queue_cmd(%Command{fun: _fun, args: _args, from: _from} = current, state) do\n # Logger.busy 3, \"FW Queuing: #{fun}: #{inspect from}\"\n new_q = :queue.in(current, state.queue)\n {:noreply, [], %{state | queue: new_q}}\n end\n\n def handle_events(gcodes, _from, state) do\n {diffs, state} = handle_gcodes(gcodes, state)\n # if after handling the current buffer of gcodes,\n # Try to start the next command in the queue if it exists.\n if List.last(gcodes) == :idle && state.current == nil do\n case :queue.out(state.queue) do\n {{:value, next_current}, new_queue} ->\n do_begin_cmd(next_current, %{state | queue: new_queue, current: next_current}, diffs)\n {:empty, queue} -> # nothing to do if the queue is empty.\n {:noreply, diffs, %{state | queue: queue}}\n end\n else\n {:noreply, diffs, state}\n end\n end\n\n defp handle_gcodes(codes, state, acc \\\\ [])\n\n defp handle_gcodes([], state, acc), do: {Enum.reverse(acc), state}\n\n defp handle_gcodes([code | rest], state, acc) do\n case handle_gcode(code, state) do\n {nil, new_state} -> handle_gcodes(rest, new_state, acc)\n {key, diff, new_state} -> handle_gcodes(rest, new_state, [{key, diff} | acc])\n end\n end\n\n defp handle_gcode({:debug_message, message}, state) do\n if get_config_value(:bool, \"settings\", \"arduino_debug_messages\") do\n Logger.debug 3, \"Arduino debug message: #{message}\"\n end\n {nil, state}\n end\n\n defp handle_gcode(code, state) when code in [:error, :invalid_command] do\n maybe_cancel_timer(state.timer, state.current)\n if state.current do\n Logger.error 1, \"Got #{code} while executing `#{inspect state.current}`.\"\n do_reply(state, {:error, :firmware_error})\n {nil, %{state | current: nil}}\n else\n {nil, state}\n end\n end\n\n defp handle_gcode(:report_no_config, state) do\n Logger.busy 1, \"Initializing Firmware.\"\n old = get_config_as_map()[\"hardware_params\"]\n spawn __MODULE__, :do_read_params, [Map.delete(old, \"param_version\")]\n {nil, %{state | initialized: false, initializing: true}}\n end\n\n defp handle_gcode(:report_params_complete, state) do\n {nil, %{state | initialized: true, initializing: false}}\n end\n\n defp handle_gcode(:idle, %{initialized: false, initializing: false} = state) do\n Logger.busy 1, \"Firmware not initialized yet. Waiting for R88 message.\"\n {nil, state}\n end\n\n defp handle_gcode(:idle, %{initialized: true, initializing: false, current: nil, z_needs_home_on_boot: true} = state) do\n Logger.info 2, \"Bootup homing Z axis\"\n spawn __MODULE__, :find_home, [:z]\n {nil, %{state | z_needs_home_on_boot: false}}\n end\n\n defp handle_gcode(:idle, %{initialized: true, initializing: false, current: nil, y_needs_home_on_boot: true} = state) do\n Logger.info 2, \"Bootup homing Y axis\"\n spawn __MODULE__, :find_home, [:y]\n {nil, %{state | y_needs_home_on_boot: false}}\n end\n\n defp handle_gcode(:idle, %{initialized: true, initializing: false, current: nil, x_needs_home_on_boot: true} = state) do\n Logger.info 2, \"Bootup homing X axis\"\n spawn __MODULE__, :find_home, [:x]\n {nil, %{state | x_needs_home_on_boot: false}}\n end\n\n defp handle_gcode(:idle, state) do\n maybe_cancel_timer(state.timer, state.current)\n Farmbot.BotState.set_busy(false)\n if state.current do\n # This might be a bug in the FW\n if state.current.fun in [:home, :home_all] do\n Logger.warn 1, \"Got idle during home.\"\n timer = start_timer(state.current, state.timeout_ms)\n {nil, %{state | timer: timer}}\n else\n Logger.warn 1, \"Got idle while executing a command.\"\n do_reply(state, {:error, :timeout})\n {:informational_settings, %{busy: false, locked: false}, %{state | current: nil, idle: true}}\n end\n else\n {:informational_settings, %{busy: false, locked: false}, %{state | idle: true}}\n end\n end\n\n defp handle_gcode({:report_current_position, x, y, z}, state) do\n {:location_data, %{position: %{x: round(x), y: round(y), z: round(z)}}, state}\n end\n\n defp handle_gcode({:report_encoder_position_scaled, x, y, z}, state) do\n {:location_data, %{scaled_encoders: %{x: x, y: y, z: z}}, state}\n end\n\n defp handle_gcode({:report_encoder_position_raw, x, y, z}, state) do\n {:location_data, %{raw_encoders: %{x: x, y: y, z: z}}, state}\n end\n\n defp handle_gcode({:report_end_stops, xa, xb, ya, yb, za, zb}, state) do\n diff = %{end_stops: %{xa: xa, xb: xb, ya: ya, yb: yb, za: za, zb: zb}}\n {:location_data, diff, state}\n {nil, state}\n end\n\n defp handle_gcode({:report_pin_mode, pin, mode_atom}, state) do\n # Logger.debug 3, \"Got pin mode report: #{pin}: #{mode_atom}\"\n mode = extract_pin_mode(mode_atom)\n case state.pins[pin] do\n %{mode: _, value: _} = pin_map ->\n {:pins, %{pin => %{pin_map | mode: mode}}, %{state | pins: %{state.pins | pin => %{pin_map | mode: mode}}}}\n nil ->\n {:pins, %{pin => %{mode: mode, value: -1}}, %{state | pins: Map.put(state.pins, pin, %{mode: mode, value: -1})}}\n end\n end\n\n defp handle_gcode({:report_pin_value, pin, value}, state) do\n # Logger.debug 3, \"Got pin value report: #{pin}: #{value} old: #{inspect state.pins[pin]}\"\n case state.pins[pin] do\n %{mode: _, value: _} = pin_map ->\n {:pins, %{pin => %{pin_map | value: value}}, %{state | pins: %{state.pins | pin => %{pin_map | value: value}}}}\n nil ->\n {:pins, %{pin => %{mode: nil, value: value}}, %{state | pins: Map.put(state.pins, pin, %{mode: nil, value: value})}}\n end\n end\n\n defp handle_gcode({:report_parameter_value, param, value}, state) when (value == -1) do\n maybe_update_param_from_report(to_string(param), nil)\n {:mcu_params, %{param => nil}, %{state | params: Map.put(state.params, param, value)}}\n end\n\n defp handle_gcode({:report_parameter_value, param, value}, state) when is_number(value) do\n maybe_update_param_from_report(to_string(param), value)\n {:mcu_params, %{param => value}, %{state | params: Map.put(state.params, param, value)}}\n end\n\n defp handle_gcode({:report_software_version, version}, state) do\n case String.last(version) do\n \"F\" ->\n update_config_value(:string, \"settings\", \"firmware_hardware\", \"farmduino\")\n \"R\" ->\n update_config_value(:string, \"settings\", \"firmware_hardware\", \"arduino\")\n \"G\" ->\n update_config_value(:string, \"settings\", \"firmware_hardware\", \"farmduino_k14\")\n _ -> :ok\n end\n {:informational_settings, %{firmware_version: version}, state}\n end\n\n defp handle_gcode(:report_axis_home_complete_x, state) do\n {nil, state}\n end\n\n defp handle_gcode(:report_axis_home_complete_y, state) do\n {nil, state}\n end\n\n defp handle_gcode(:report_axis_home_complete_z, state) do\n {nil, %{state | timer: nil}}\n end\n\n defp handle_gcode(:report_axis_timeout_x, state) do\n do_reply(state, {:error, :axis_timeout_x})\n {nil, %{state | timer: nil}}\n end\n\n defp handle_gcode(:report_axis_timeout_y, state) do\n do_reply(state, {:error, :axis_timeout_y})\n {nil, %{state | timer: nil}}\n end\n\n defp handle_gcode(:report_axis_timeout_z, state) do\n do_reply(state, {:error, :axis_timeout_z})\n {nil, %{state | timer: nil}}\n end\n\n defp handle_gcode({:report_axis_changed_x, _new_x} = msg, state) do\n new_current = Command.add_status(state.current, msg)\n {nil, %{state | current: new_current}}\n end\n\n defp handle_gcode({:report_axis_changed_y, _new_y} = msg, state) do\n new_current = Command.add_status(state.current, msg)\n {nil, %{state | current: new_current}}\n end\n\n defp handle_gcode({:report_axis_changed_z, _new_z} = msg, state) do\n new_current = Command.add_status(state.current, msg)\n {nil, %{state | current: new_current}}\n end\n\n defp handle_gcode(:busy, state) do\n Farmbot.BotState.set_busy(true)\n maybe_cancel_timer(state.timer, state.current)\n timer = if state.current do\n start_timer(state.current, state.timeout_ms)\n else\n nil\n end\n {:informational_settings, %{busy: true}, %{state | idle: false, timer: timer}}\n end\n\n defp handle_gcode(:done, state) do\n maybe_cancel_timer(state.timer, state.current)\n Farmbot.BotState.set_busy(false)\n if state.current do\n do_reply(state, :ok)\n {nil, %{state | current: nil}}\n else\n {nil, state}\n end\n end\n\n defp handle_gcode(:report_emergency_lock, state) do\n Farmbot.System.GPIO.Leds.led_status_err\n maybe_send_email()\n if state.current do\n do_reply(state, {:error, :emergency_lock})\n {:informational_settings, %{locked: true}, %{state | current: nil}}\n else\n {:informational_settings, %{locked: true}, state}\n end\n end\n\n defp handle_gcode({:report_calibration, axis, status}, state) do\n maybe_cancel_timer(state.timer, state.current)\n Logger.busy 1, \"Axis #{axis} calibration: #{status}\"\n {nil, state}\n end\n\n defp handle_gcode({:report_axis_calibration, param, val}, state) do\n spawn __MODULE__, :report_calibration_callback, [5, param, val]\n {nil, state}\n end\n\n defp handle_gcode(:noop, state) do\n {nil, state}\n end\n\n defp handle_gcode(:received, state) do\n {nil, state}\n end\n\n defp handle_gcode({:echo, _code}, state) do\n {nil, state}\n end\n\n defp handle_gcode(code, state) do\n Logger.warn(3, \"unhandled code: #{inspect(code)}\")\n {nil, state}\n end\n\n defp maybe_cancel_timer(nil, current_command) do\n if current_command do\n # Logger.debug 3, \"[WEIRD] - No timer to cancel for command: #{inspect current_command}\"\n :ok\n else\n # Logger.debug 3, \"[PROBABLY OK] - No timer to cancel, and no command here.\"\n :ok\n end\n end\n\n defp maybe_cancel_timer(timer, _current_command) do\n if Process.read_timer(timer) do\n # Logger.debug 3, \"[NORMAL] - Canceled timer: #{inspect timer} for command: #{inspect current_command}\"\n Process.cancel_timer(timer)\n :ok\n else\n :ok\n end\n end\n\n defp maybe_update_param_from_report(param, val) when is_binary(param) do\n real_val = if val, do: (val \/ 1), else: nil\n # Logger.debug 3, \"Firmware reported #{param} => #{val || -1}\"\n update_config_value(:float, \"hardware_params\", to_string(param), real_val)\n end\n\n @doc false\n def do_read_params(old) when is_map(old) do\n for {key, float_val} <- old do\n cond do\n (float_val == -1) -> :ok\n is_nil(float_val) -> :ok\n is_number(float_val) ->\n val = round(float_val)\n :ok = update_param(:\"#{key}\", val)\n end\n end\n :ok = update_param(:param_use_eeprom, 0)\n :ok = update_param(:param_config_ok, 1)\n read_all_params()\n :ok = request_software_version()\n end\n\n @doc false\n def report_calibration_callback(tries, param, value)\n\n def report_calibration_callback(0, _param, _value) do\n :ok\n end\n\n def report_calibration_callback(tries, param, val) do\n case Farmbot.Firmware.update_param(param, val) do\n :ok ->\n str_param = to_string(param)\n case get_config_value(:float, \"hardware_params\", str_param) do\n ^val ->\n Logger.success 1, \"Calibrated #{param}: #{val}\"\n SettingsSync.upload_fw_kv(str_param, val)\n :ok\n _ -> report_calibration_callback(tries - 1, param, val)\n end\n {:error, reason} ->\n Logger.error 1, \"Failed to set #{param}: #{val} (#{inspect reason})\"\n report_calibration_callback(tries - 1, param, val)\n end\n end\n\n defp do_reply(state, reply) do\n maybe_cancel_timer(state.timer, state.current)\n maybe_log_complete(state.current, reply)\n case state.current do\n %Command{fun: :emergency_unlock, from: from} ->\n # i really don't want this to be here..\n EstopTimer.cancel_timer()\n :ok = GenServer.reply from, reply\n %Command{fun: :emergency_lock, from: from} ->\n :ok = GenServer.reply from, {:error, :emergency_lock}\n %Command{fun: _fun, from: from} ->\n # Logger.success 3, \"FW Replying: #{fun}: #{inspect from}\"\n :ok = GenServer.reply from, reply\n nil ->\n Logger.error 1, \"FW Nothing to send reply: #{inspect reply} to!.\"\n :error\n end\n end\n\n defp maybe_send_email do\n if get_config_value(:bool, \"settings\", \"email_on_estop\") do\n if !EstopTimer.timer_active? do\n EstopTimer.start_timer()\n end\n end\n end\n\n defp start_timer(%Command{} = command, timeout) do\n Process.send_after(self(), {:command_timeout, command}, timeout)\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"40f40794c97921b2561ac3d4f85daf384cf6129a","subject":"Do not show duplicate docs for definitions with defaults, closes #7121","message":"Do not show duplicate docs for definitions with defaults, closes #7121\n","repos":"elixir-lang\/elixir,gfvcastro\/elixir,michalmuskala\/elixir,kelvinst\/elixir,kelvinst\/elixir,lexmag\/elixir,joshprice\/elixir,ggcampinho\/elixir,lexmag\/elixir,pedrosnk\/elixir,ggcampinho\/elixir,kimshrier\/elixir,gfvcastro\/elixir,kimshrier\/elixir,pedrosnk\/elixir","old_file":"lib\/iex\/lib\/iex\/introspection.ex","new_file":"lib\/iex\/lib\/iex\/introspection.ex","new_contents":"# Convenience helpers for showing docs, specs, types\n# and opening modules. Invoked directly from IEx.Helpers.\ndefmodule IEx.Introspection do\n @moduledoc false\n\n import IEx, only: [dont_display_result: 0]\n\n alias Kernel.Typespec\n\n @doc \"\"\"\n Decomposes an introspection call into `{mod, fun, arity}`,\n `{mod, fun}` or `mod`.\n \"\"\"\n @default_modules [IEx.Helpers, Kernel, Kernel.SpecialForms]\n\n def decompose({:\/, _, [call, arity]} = term) do\n case Macro.decompose_call(call) do\n {_mod, :__info__, []} when arity == 1 ->\n {:{}, [], [Module, :__info__, 1]}\n\n {mod, fun, []} ->\n {:{}, [], [mod, fun, arity]}\n\n {fun, []} ->\n {:{}, [], [find_decompose_fun_arity(fun, arity), fun, arity]}\n\n _ ->\n term\n end\n end\n\n def decompose(call) do\n case Macro.decompose_call(call) do\n {_mod, :__info__, []} ->\n Macro.escape({Module, :__info__, 1})\n\n {mod, fun, []} ->\n {mod, fun}\n\n {fun, []} ->\n {find_decompose_fun(fun), fun}\n\n _ ->\n call\n end\n end\n\n defp find_decompose_fun(fun) do\n Enum.find(@default_modules, Kernel, fn mod ->\n Keyword.has_key?(mod.__info__(:functions), fun) or\n Keyword.has_key?(mod.__info__(:macros), fun)\n end)\n end\n\n defp find_decompose_fun_arity(fun, arity) do\n pair = {fun, arity}\n\n Enum.find(@default_modules, Kernel, fn mod ->\n pair in mod.__info__(:functions) or pair in mod.__info__(:macros)\n end)\n end\n\n @doc \"\"\"\n Opens the given module, mfa, file\/line, binary.\n \"\"\"\n def open(module) when is_atom(module) do\n case open_mfa(module, :__info__, 1) do\n {source, nil, _} -> open(source)\n {_, tuple, _} -> open(tuple)\n :error -> puts_error(\"Could not open: #{inspect(module)}. Module is not available.\")\n end\n\n dont_display_result()\n end\n\n def open({module, function}) when is_atom(module) and is_atom(function) do\n case open_mfa(module, function, :*) do\n {_, _, nil} ->\n puts_error(\n \"Could not open: #{inspect(module)}.#{function}. Function\/macro is not available.\"\n )\n\n {_, _, tuple} ->\n open(tuple)\n\n :error ->\n puts_error(\"Could not open: #{inspect(module)}.#{function}. Module is not available.\")\n end\n\n dont_display_result()\n end\n\n def open({module, function, arity})\n when is_atom(module) and is_atom(function) and is_integer(arity) do\n case open_mfa(module, function, arity) do\n {_, _, nil} ->\n puts_error(\n \"Could not open: #{inspect(module)}.#{function}\/#{arity}. Function\/macro is not available.\"\n )\n\n {_, _, tuple} ->\n open(tuple)\n\n :error ->\n puts_error(\n \"Could not open: #{inspect(module)}.#{function}\/#{arity}. Module is not available.\"\n )\n end\n\n dont_display_result()\n end\n\n def open({file, line}) when is_binary(file) and is_integer(line) do\n cond do\n not File.regular?(file) ->\n puts_error(\"Could not open: #{inspect(file)}. File is not available.\")\n\n editor = System.get_env(\"ELIXIR_EDITOR\") || System.get_env(\"EDITOR\") ->\n command =\n if editor =~ \"__FILE__\" or editor =~ \"__LINE__\" do\n editor\n |> String.replace(\"__FILE__\", inspect(file))\n |> String.replace(\"__LINE__\", Integer.to_string(line))\n else\n \"#{editor} #{inspect(file)}:#{line}\"\n end\n\n IO.write(IEx.color(:eval_info, :os.cmd(String.to_charlist(command))))\n\n true ->\n puts_error(\n \"Could not open: #{inspect(file)}. \" <>\n \"Please set the ELIXIR_EDITOR or EDITOR environment variables with the \" <>\n \"command line invocation of your favorite EDITOR.\"\n )\n end\n\n dont_display_result()\n end\n\n def open(invalid) do\n puts_error(\"Invalid arguments for open helper: #{inspect(invalid)}\")\n dont_display_result()\n end\n\n defp open_mfa(module, fun, arity) do\n with {:module, _} <- Code.ensure_loaded(module),\n source when is_list(source) <- module.module_info(:compile)[:source] do\n source = rewrite_source(module, source)\n open_abstract_code(module, fun, arity, source)\n else\n _ -> :error\n end\n end\n\n defp open_abstract_code(module, fun, arity, source) do\n fun = Atom.to_string(fun)\n\n with [_ | _] = beam <- :code.which(module),\n {:ok, {_, [abstract_code: abstract_code]}} <- :beam_lib.chunks(beam, [:abstract_code]),\n {:raw_abstract_v1, code} <- abstract_code do\n {_, module_pair, fa_pair} =\n Enum.reduce(code, {source, nil, nil}, &open_abstract_code_reduce(&1, &2, fun, arity))\n\n {source, module_pair, fa_pair}\n else\n _ ->\n {source, nil, nil}\n end\n end\n\n defp open_abstract_code_reduce(entry, {file, module_pair, fa_pair}, fun, arity) do\n case entry do\n {:attribute, ann, :module, _} ->\n {file, {file, :erl_anno.line(ann)}, fa_pair}\n\n {:function, ann, ann_fun, ann_arity, _} ->\n case Atom.to_string(ann_fun) do\n \"MACRO-\" <> ^fun when arity == :* or ann_arity == arity + 1 ->\n {file, module_pair, fa_pair || {file, :erl_anno.line(ann)}}\n\n ^fun when arity == :* or ann_arity == arity ->\n {file, module_pair, fa_pair || {file, :erl_anno.line(ann)}}\n\n _ ->\n {file, module_pair, fa_pair}\n end\n\n _ ->\n {file, module_pair, fa_pair}\n end\n end\n\n @elixir_apps ~w(eex elixir ex_unit iex logger mix)a\n @otp_apps ~w(kernel stdlib)a\n @apps @elixir_apps ++ @otp_apps\n\n defp rewrite_source(module, source) do\n case :application.get_application(module) do\n {:ok, app} when app in @apps ->\n Application.app_dir(app, rewrite_source(source))\n\n _ ->\n beam_path = :code.which(module)\n\n if is_list(beam_path) and List.starts_with?(beam_path, :code.root_dir()) do\n app_vsn = beam_path |> Path.dirname() |> Path.dirname() |> Path.basename()\n Path.join([:code.root_dir(), \"lib\", app_vsn, rewrite_source(source)])\n else\n List.to_string(source)\n end\n end\n end\n\n defp rewrite_source(source) do\n {in_app, [lib_or_src | _]} =\n source\n |> Path.split()\n |> Enum.reverse()\n |> Enum.split_while(&(&1 not in [\"lib\", \"src\"]))\n\n Path.join([lib_or_src | Enum.reverse(in_app)])\n end\n\n @doc \"\"\"\n Prints documentation.\n \"\"\"\n def h(module) when is_atom(module) do\n case Code.ensure_loaded(module) do\n {:module, _} ->\n if elixir_module?(module) do\n case Code.get_docs(module, :moduledoc) do\n {_, binary} when is_binary(binary) ->\n print_doc(inspect(module), [], binary)\n\n {_, _} ->\n docs_not_found(inspect(module))\n\n _ ->\n no_docs(module)\n end\n else\n puts_error(\n \"Documentation is not available for non-Elixir modules, got: #{inspect(module)}\"\n )\n end\n\n {:error, reason} ->\n puts_error(\"Could not load module #{inspect(module)}, got: #{reason}\")\n end\n\n dont_display_result()\n end\n\n def h({module, function}) when is_atom(module) and is_atom(function) do\n case Code.ensure_loaded(module) do\n {:module, _} ->\n docs = Code.get_docs(module, :docs)\n\n exports =\n cond do\n docs ->\n Enum.map(docs, &elem(&1, 0))\n\n function_exported?(module, :__info__, 1) ->\n module.__info__(:functions) ++ module.__info__(:macros)\n\n true ->\n module.module_info(:exports)\n end\n\n result =\n for {^function, arity} <- exports,\n (if docs do\n find_doc(docs, function, arity)\n else\n get_spec(module, function, arity) != []\n end) do\n h_mod_fun_arity(module, function, arity)\n end\n\n cond do\n result != [] ->\n :ok\n\n docs && has_callback?(module, function) ->\n behaviour_found(\"#{inspect(module)}.#{function}\")\n\n elixir_module?(module) and is_nil(docs) ->\n no_docs(module)\n\n true ->\n docs_not_found(\"#{inspect(module)}.#{function}\")\n end\n\n {:error, reason} ->\n puts_error(\"Could not load module #{inspect(module)}, got: #{reason}\")\n end\n\n dont_display_result()\n end\n\n def h({module, function, arity})\n when is_atom(module) and is_atom(function) and is_integer(arity) do\n case Code.ensure_loaded(module) do\n {:module, _} ->\n case h_mod_fun_arity(module, function, arity) do\n :ok ->\n :ok\n\n :behaviour_found ->\n behaviour_found(\"#{inspect(module)}.#{function}\/#{arity}\")\n\n :no_docs ->\n no_docs(module)\n\n :not_found ->\n docs_not_found(\"#{inspect(module)}.#{function}\/#{arity}\")\n end\n\n {:error, reason} ->\n puts_error(\"Could not load module #{inspect(module)}, got: #{reason}\")\n end\n\n dont_display_result()\n end\n\n def h(invalid) do\n puts_error(\"Invalid arguments for h helper: #{inspect(invalid)}\")\n dont_display_result()\n end\n\n defp h_mod_fun_arity(mod, fun, arity) when is_atom(mod) do\n docs = Code.get_docs(mod, :docs)\n spec = get_spec(mod, fun, arity)\n\n cond do\n doc_tuple = find_doc(docs, fun, arity) ->\n print_fun(mod, doc_tuple, spec)\n :ok\n\n docs && has_callback?(mod, fun, arity) ->\n :behaviour_found\n\n is_nil(docs) and spec != [] ->\n message =\n if elixir_module?(mod) do\n \"Module was compiled without docs. Showing only specs.\"\n else\n \"Documentation is not available for non-Elixir modules. Showing only specs.\"\n end\n\n print_doc(\"#{inspect(mod)}.#{fun}\/#{arity}\", spec, message)\n :ok\n\n is_nil(docs) and elixir_module?(mod) ->\n :no_docs\n\n true ->\n :not_found\n end\n end\n\n defp has_callback?(mod, fun) do\n mod\n |> Code.get_docs(:callback_docs)\n |> Enum.any?(&match?({{^fun, _}, _, _, _}, &1))\n end\n\n defp has_callback?(mod, fun, arity) do\n mod\n |> Code.get_docs(:callback_docs)\n |> Enum.any?(&match?({{^fun, ^arity}, _, _, _}, &1))\n end\n\n defp find_doc(nil, _fun, _arity) do\n nil\n end\n\n defp find_doc(docs, fun, arity) do\n doc = List.keyfind(docs, {fun, arity}, 0) || find_doc_defaults(docs, fun, arity)\n if doc != nil and has_content?(doc), do: doc\n end\n\n defp find_doc_defaults(docs, function, min) do\n Enum.find(docs, fn doc ->\n case elem(doc, 0) do\n {^function, arity} when arity > min ->\n defaults = Enum.count(elem(doc, 3), &match?({:\\\\, _, _}, &1))\n arity <= min + defaults\n\n _ ->\n false\n end\n end)\n end\n\n defp has_content?({_, _, _, _, false}), do: false\n defp has_content?({{name, _}, _, _, _, nil}), do: hd(Atom.to_charlist(name)) != ?_\n defp has_content?({_, _, _, _, _}), do: true\n\n defp print_fun(mod, {{fun, arity}, _line, kind, args, doc}, spec) do\n if callback_module = is_nil(doc) and callback_module(mod, fun, arity) do\n filter = &match?({^fun, ^arity}, elem(&1, 0))\n\n case get_callback_docs(callback_module, filter) do\n {:ok, callback_docs} -> Enum.each(callback_docs, &print_typespec\/1)\n _ -> nil\n end\n else\n args = Enum.map_join(args, \", \", &format_doc_arg(&1))\n print_doc(\"#{kind} #{fun}(#{args})\", spec, doc)\n end\n end\n\n defp callback_module(mod, fun, arity) do\n predicate = &match?({{^fun, ^arity}, _}, &1)\n\n mod.module_info(:attributes)\n |> Keyword.get_values(:behaviour)\n |> Stream.concat()\n |> Enum.find(&Enum.any?(Typespec.beam_callbacks(&1), predicate))\n end\n\n defp format_doc_arg({:\\\\, _, [left, right]}) do\n format_doc_arg(left) <> \" \\\\\\\\ \" <> Macro.to_string(right)\n end\n\n defp format_doc_arg({var, _, _}) do\n Atom.to_string(var)\n end\n\n defp get_spec(module, name, arity) do\n all_specs = Typespec.beam_specs(module) || []\n\n case List.keyfind(all_specs, {name, arity}, 0) do\n {_, specs} ->\n formatted =\n Enum.map(specs, fn spec ->\n Typespec.spec_to_ast(name, spec)\n |> format_typespec(:spec)\n |> IO.iodata_to_binary()\n |> String.replace(\"\\n\", \"\\n \")\n |> prefix(\" \")\n |> pair(?\\n)\n end)\n\n [formatted, ?\\n]\n\n nil ->\n []\n end\n end\n\n @doc \"\"\"\n Prints the list of behaviour callbacks or a given callback.\n \"\"\"\n def b(mod) when is_atom(mod) do\n case get_callback_docs(mod, fn _ -> true end) do\n :no_beam -> no_beam(mod)\n :no_docs -> no_docs(mod)\n {:ok, []} -> puts_error(\"No callbacks for #{inspect(mod)} were found\")\n {:ok, docs} -> Enum.each(docs, fn {definition, _} -> IO.puts(definition) end)\n end\n\n dont_display_result()\n end\n\n def b({mod, fun}) when is_atom(mod) and is_atom(fun) do\n filter = &match?({^fun, _}, elem(&1, 0))\n\n case get_callback_docs(mod, filter) do\n :no_beam -> no_beam(mod)\n :no_docs -> no_docs(mod)\n {:ok, []} -> docs_not_found(\"#{inspect(mod)}.#{fun}\")\n {:ok, docs} -> Enum.each(docs, &print_typespec\/1)\n end\n\n dont_display_result()\n end\n\n def b({mod, fun, arity}) when is_atom(mod) and is_atom(fun) and is_integer(arity) do\n filter = &match?({^fun, ^arity}, elem(&1, 0))\n\n case get_callback_docs(mod, filter) do\n :no_beam -> no_beam(mod)\n :no_docs -> no_docs(mod)\n {:ok, []} -> docs_not_found(\"#{inspect(mod)}.#{fun}\/#{arity}\")\n {:ok, docs} -> Enum.each(docs, &print_typespec\/1)\n end\n\n dont_display_result()\n end\n\n def b(invalid) do\n puts_error(\"Invalid arguments for b helper: #{inspect(invalid)}\")\n dont_display_result()\n end\n\n defp get_callback_docs(mod, filter) do\n callbacks = Typespec.beam_callbacks(mod)\n docs = Code.get_docs(mod, :callback_docs)\n\n cond do\n is_nil(callbacks) ->\n :no_beam\n\n is_nil(docs) ->\n :no_docs\n\n true ->\n docs =\n docs\n |> Enum.filter(filter)\n |> Enum.map(fn\n {{fun, arity}, _, :macrocallback, doc} ->\n macro = {:\"MACRO-#{fun}\", arity + 1}\n {format_callback(:macrocallback, fun, macro, callbacks), doc}\n\n {{fun, arity}, _, kind, doc} ->\n {format_callback(kind, fun, {fun, arity}, callbacks), doc}\n end)\n\n {:ok, docs}\n end\n end\n\n defp format_callback(kind, name, key, callbacks) do\n {_, specs} = List.keyfind(callbacks, key, 0)\n\n Enum.map(specs, fn spec ->\n Typespec.spec_to_ast(name, spec)\n |> Macro.prewalk(&drop_macro_env\/1)\n |> format_typespec(kind)\n |> pair(?\\n)\n end)\n end\n\n defp drop_macro_env({name, meta, [{:::, _, [_, {{:., _, [Macro.Env, :t]}, _, _}]} | args]}),\n do: {name, meta, args}\n\n defp drop_macro_env(other), do: other\n\n @doc \"\"\"\n Prints the types for the given module and type documentation.\n \"\"\"\n def t(module) when is_atom(module) do\n case Typespec.beam_types(module) do\n nil ->\n no_beam(module)\n\n [] ->\n types_not_found(inspect(module))\n\n types ->\n Enum.each(types, &(&1 |> format_type() |> IO.puts()))\n end\n\n dont_display_result()\n end\n\n def t({module, type}) when is_atom(module) and is_atom(type) do\n case Typespec.beam_types(module) do\n nil ->\n no_beam(module)\n\n types ->\n printed =\n for {_, {^type, _, args}} = typespec <- types do\n doc = {format_type(typespec), type_doc(module, type, length(args))}\n print_typespec(doc)\n end\n\n if printed == [] do\n types_not_found(\"#{inspect(module)}.#{type}\")\n end\n end\n\n dont_display_result()\n end\n\n def t({module, type, arity}) when is_atom(module) and is_atom(type) and is_integer(arity) do\n case Typespec.beam_types(module) do\n nil ->\n no_beam(module)\n\n types ->\n printed =\n for {_, {^type, _, args}} = typespec <- types, length(args) == arity do\n doc = {format_type(typespec), type_doc(module, type, arity)}\n print_typespec(doc)\n end\n\n if printed == [] do\n types_not_found(\"#{inspect(module)}.#{type}\")\n end\n end\n\n dont_display_result()\n end\n\n def t(invalid) do\n puts_error(\"Invalid arguments for t helper: #{inspect(invalid)}\")\n dont_display_result()\n end\n\n defp type_doc(module, type, arity) do\n docs = Code.get_docs(module, :type_docs)\n {_, _, _, content} = Enum.find(docs, &match?({{^type, ^arity}, _, _, _}, &1))\n content\n end\n\n defp format_type({:opaque, type}) do\n {:::, _, [ast, _]} = Typespec.type_to_ast(type)\n [format_typespec(ast, :opaque), ?\\n]\n end\n\n defp format_type({kind, type}) do\n ast = Typespec.type_to_ast(type)\n [format_typespec(ast, kind), ?\\n]\n end\n\n ## Helpers\n\n defp format_typespec(definition, kind) do\n definition\n |> Macro.to_string()\n |> prefix(\"@#{kind} \")\n |> Code.format_string!(line_length: IEx.width())\n |> IO.iodata_to_binary()\n |> color_prefix_with_line()\n end\n\n defp prefix(string, prefix) do\n prefix <> string\n end\n\n defp pair(left, right) do\n [left, right]\n end\n\n defp color_prefix_with_line(string) do\n [left, right] = :binary.split(string, \" \")\n [IEx.color(:doc_inline_code, left), ?\\s, right]\n end\n\n defp print_doc(heading, types, doc) do\n doc = doc || \"\"\n\n if opts = IEx.Config.ansi_docs() do\n IO.ANSI.Docs.print_heading(heading, opts)\n IO.write(types)\n IO.ANSI.Docs.print(doc, opts)\n else\n IO.puts(\"* #{heading}\\n\")\n IO.write(types)\n IO.puts(doc)\n end\n end\n\n defp print_typespec({types, doc}) do\n IO.puts(types)\n\n if opts = IEx.Config.ansi_docs() do\n doc && IO.ANSI.Docs.print(doc, opts)\n else\n doc && IO.puts(doc)\n end\n end\n\n defp elixir_module?(module) do\n function_exported?(module, :__info__, 1)\n end\n\n defp no_beam(module) do\n case Code.ensure_loaded(module) do\n {:module, _} ->\n puts_error(\n \"Beam code not available for #{inspect(module)} or debug info is missing, cannot load typespecs\"\n )\n\n {:error, reason} ->\n puts_error(\"Could not load module #{inspect(module)}, got: #{reason}\")\n end\n end\n\n defp no_docs(module) do\n puts_error(\"#{inspect(module)} was not compiled with docs\")\n end\n\n defp types_not_found(for), do: not_found(for, \"type information\")\n defp docs_not_found(for), do: not_found(for, \"documentation\")\n\n defp behaviour_found(for) do\n puts_error(\"\"\"\n No documentation for function #{for} was found, but there is a callback with the same name.\n You can view callback documentations with the b\/1 helper.\n \"\"\")\n end\n\n defp not_found(for, type) do\n puts_error(\"No #{type} for #{for} was found\")\n end\n\n defp puts_error(string) do\n IO.puts(IEx.color(:eval_error, string))\n end\nend\n","old_contents":"# Convenience helpers for showing docs, specs, types\n# and opening modules. Invoked directly from IEx.Helpers.\ndefmodule IEx.Introspection do\n @moduledoc false\n\n import IEx, only: [dont_display_result: 0]\n\n alias Kernel.Typespec\n\n @doc \"\"\"\n Decomposes an introspection call into `{mod, fun, arity}`,\n `{mod, fun}` or `mod`.\n \"\"\"\n @default_modules [IEx.Helpers, Kernel, Kernel.SpecialForms]\n\n def decompose({:\/, _, [call, arity]} = term) do\n case Macro.decompose_call(call) do\n {_mod, :__info__, []} when arity == 1 ->\n {:{}, [], [Module, :__info__, 1]}\n\n {mod, fun, []} ->\n {:{}, [], [mod, fun, arity]}\n\n {fun, []} ->\n {:{}, [], [find_decompose_fun_arity(fun, arity), fun, arity]}\n\n _ ->\n term\n end\n end\n\n def decompose(call) do\n case Macro.decompose_call(call) do\n {_mod, :__info__, []} ->\n Macro.escape({Module, :__info__, 1})\n\n {mod, fun, []} ->\n {mod, fun}\n\n {fun, []} ->\n {find_decompose_fun(fun), fun}\n\n _ ->\n call\n end\n end\n\n defp find_decompose_fun(fun) do\n Enum.find(@default_modules, Kernel, fn mod ->\n Keyword.has_key?(mod.__info__(:functions), fun) or\n Keyword.has_key?(mod.__info__(:macros), fun)\n end)\n end\n\n defp find_decompose_fun_arity(fun, arity) do\n pair = {fun, arity}\n\n Enum.find(@default_modules, Kernel, fn mod ->\n pair in mod.__info__(:functions) or pair in mod.__info__(:macros)\n end)\n end\n\n @doc \"\"\"\n Opens the given module, mfa, file\/line, binary.\n \"\"\"\n def open(module) when is_atom(module) do\n case open_mfa(module, :__info__, 1) do\n {source, nil, _} -> open(source)\n {_, tuple, _} -> open(tuple)\n :error -> puts_error(\"Could not open: #{inspect(module)}. Module is not available.\")\n end\n\n dont_display_result()\n end\n\n def open({module, function}) when is_atom(module) and is_atom(function) do\n case open_mfa(module, function, :*) do\n {_, _, nil} ->\n puts_error(\n \"Could not open: #{inspect(module)}.#{function}. Function\/macro is not available.\"\n )\n\n {_, _, tuple} ->\n open(tuple)\n\n :error ->\n puts_error(\"Could not open: #{inspect(module)}.#{function}. Module is not available.\")\n end\n\n dont_display_result()\n end\n\n def open({module, function, arity})\n when is_atom(module) and is_atom(function) and is_integer(arity) do\n case open_mfa(module, function, arity) do\n {_, _, nil} ->\n puts_error(\n \"Could not open: #{inspect(module)}.#{function}\/#{arity}. Function\/macro is not available.\"\n )\n\n {_, _, tuple} ->\n open(tuple)\n\n :error ->\n puts_error(\n \"Could not open: #{inspect(module)}.#{function}\/#{arity}. Module is not available.\"\n )\n end\n\n dont_display_result()\n end\n\n def open({file, line}) when is_binary(file) and is_integer(line) do\n cond do\n not File.regular?(file) ->\n puts_error(\"Could not open: #{inspect(file)}. File is not available.\")\n\n editor = System.get_env(\"ELIXIR_EDITOR\") || System.get_env(\"EDITOR\") ->\n command =\n if editor =~ \"__FILE__\" or editor =~ \"__LINE__\" do\n editor\n |> String.replace(\"__FILE__\", inspect(file))\n |> String.replace(\"__LINE__\", Integer.to_string(line))\n else\n \"#{editor} #{inspect(file)}:#{line}\"\n end\n\n IO.write(IEx.color(:eval_info, :os.cmd(String.to_charlist(command))))\n\n true ->\n puts_error(\n \"Could not open: #{inspect(file)}. \" <>\n \"Please set the ELIXIR_EDITOR or EDITOR environment variables with the \" <>\n \"command line invocation of your favorite EDITOR.\"\n )\n end\n\n dont_display_result()\n end\n\n def open(invalid) do\n puts_error(\"Invalid arguments for open helper: #{inspect(invalid)}\")\n dont_display_result()\n end\n\n defp open_mfa(module, fun, arity) do\n with {:module, _} <- Code.ensure_loaded(module),\n source when is_list(source) <- module.module_info(:compile)[:source] do\n source = rewrite_source(module, source)\n open_abstract_code(module, fun, arity, source)\n else\n _ -> :error\n end\n end\n\n defp open_abstract_code(module, fun, arity, source) do\n fun = Atom.to_string(fun)\n\n with [_ | _] = beam <- :code.which(module),\n {:ok, {_, [abstract_code: abstract_code]}} <- :beam_lib.chunks(beam, [:abstract_code]),\n {:raw_abstract_v1, code} <- abstract_code do\n {_, module_pair, fa_pair} =\n Enum.reduce(code, {source, nil, nil}, &open_abstract_code_reduce(&1, &2, fun, arity))\n\n {source, module_pair, fa_pair}\n else\n _ ->\n {source, nil, nil}\n end\n end\n\n defp open_abstract_code_reduce(entry, {file, module_pair, fa_pair}, fun, arity) do\n case entry do\n {:attribute, ann, :module, _} ->\n {file, {file, :erl_anno.line(ann)}, fa_pair}\n\n {:function, ann, ann_fun, ann_arity, _} ->\n case Atom.to_string(ann_fun) do\n \"MACRO-\" <> ^fun when arity == :* or ann_arity == arity + 1 ->\n {file, module_pair, fa_pair || {file, :erl_anno.line(ann)}}\n\n ^fun when arity == :* or ann_arity == arity ->\n {file, module_pair, fa_pair || {file, :erl_anno.line(ann)}}\n\n _ ->\n {file, module_pair, fa_pair}\n end\n\n _ ->\n {file, module_pair, fa_pair}\n end\n end\n\n @elixir_apps ~w(eex elixir ex_unit iex logger mix)a\n @otp_apps ~w(kernel stdlib)a\n @apps @elixir_apps ++ @otp_apps\n\n defp rewrite_source(module, source) do\n case :application.get_application(module) do\n {:ok, app} when app in @apps ->\n Application.app_dir(app, rewrite_source(source))\n\n _ ->\n beam_path = :code.which(module)\n\n if is_list(beam_path) and List.starts_with?(beam_path, :code.root_dir()) do\n app_vsn = beam_path |> Path.dirname() |> Path.dirname() |> Path.basename()\n Path.join([:code.root_dir(), \"lib\", app_vsn, rewrite_source(source)])\n else\n List.to_string(source)\n end\n end\n end\n\n defp rewrite_source(source) do\n {in_app, [lib_or_src | _]} =\n source\n |> Path.split()\n |> Enum.reverse()\n |> Enum.split_while(&(&1 not in [\"lib\", \"src\"]))\n\n Path.join([lib_or_src | Enum.reverse(in_app)])\n end\n\n @doc \"\"\"\n Prints documentation.\n \"\"\"\n def h(module) when is_atom(module) do\n case Code.ensure_loaded(module) do\n {:module, _} ->\n if elixir_module?(module) do\n case Code.get_docs(module, :moduledoc) do\n {_, binary} when is_binary(binary) ->\n print_doc(inspect(module), [], binary)\n\n {_, _} ->\n docs_not_found(inspect(module))\n\n _ ->\n no_docs(module)\n end\n else\n puts_error(\n \"Documentation is not available for non-Elixir modules, got: #{inspect(module)}\"\n )\n end\n\n {:error, reason} ->\n puts_error(\"Could not load module #{inspect(module)}, got: #{reason}\")\n end\n\n dont_display_result()\n end\n\n def h({module, function}) when is_atom(module) and is_atom(function) do\n case Code.ensure_loaded(module) do\n {:module, _} ->\n docs = Code.get_docs(module, :docs)\n\n exports =\n if function_exported?(module, :__info__, 1) do\n module.__info__(:functions) ++ module.__info__(:macros)\n else\n module.module_info(:exports)\n end\n\n result =\n for {^function, arity} <- exports,\n (if docs do\n find_doc(docs, function, arity)\n else\n get_spec(module, function, arity) != []\n end) do\n h_mod_fun_arity(module, function, arity)\n end\n\n cond do\n result != [] ->\n :ok\n\n docs && has_callback?(module, function) ->\n behaviour_found(\"#{inspect(module)}.#{function}\")\n\n elixir_module?(module) and is_nil(docs) ->\n no_docs(module)\n\n true ->\n docs_not_found(\"#{inspect(module)}.#{function}\")\n end\n\n {:error, reason} ->\n puts_error(\"Could not load module #{inspect(module)}, got: #{reason}\")\n end\n\n dont_display_result()\n end\n\n def h({module, function, arity})\n when is_atom(module) and is_atom(function) and is_integer(arity) do\n case Code.ensure_loaded(module) do\n {:module, _} ->\n case h_mod_fun_arity(module, function, arity) do\n :ok ->\n :ok\n\n :behaviour_found ->\n behaviour_found(\"#{inspect(module)}.#{function}\/#{arity}\")\n\n :no_docs ->\n no_docs(module)\n\n :not_found ->\n docs_not_found(\"#{inspect(module)}.#{function}\/#{arity}\")\n end\n\n {:error, reason} ->\n puts_error(\"Could not load module #{inspect(module)}, got: #{reason}\")\n end\n\n dont_display_result()\n end\n\n def h(invalid) do\n puts_error(\"Invalid arguments for h helper: #{inspect(invalid)}\")\n dont_display_result()\n end\n\n defp h_mod_fun_arity(mod, fun, arity) when is_atom(mod) do\n docs = Code.get_docs(mod, :docs)\n spec = get_spec(mod, fun, arity)\n\n cond do\n doc_tuple = find_doc(docs, fun, arity) ->\n print_fun(mod, doc_tuple, spec)\n :ok\n\n docs && has_callback?(mod, fun, arity) ->\n :behaviour_found\n\n is_nil(docs) and spec != [] ->\n message =\n if elixir_module?(mod) do\n \"Module was compiled without docs. Showing only specs.\"\n else\n \"Documentation is not available for non-Elixir modules. Showing only specs.\"\n end\n\n print_doc(\"#{inspect(mod)}.#{fun}\/#{arity}\", spec, message)\n :ok\n\n is_nil(docs) and elixir_module?(mod) ->\n :no_docs\n\n true ->\n :not_found\n end\n end\n\n defp has_callback?(mod, fun) do\n mod\n |> Code.get_docs(:callback_docs)\n |> Enum.any?(&match?({{^fun, _}, _, _, _}, &1))\n end\n\n defp has_callback?(mod, fun, arity) do\n mod\n |> Code.get_docs(:callback_docs)\n |> Enum.any?(&match?({{^fun, ^arity}, _, _, _}, &1))\n end\n\n defp find_doc(nil, _fun, _arity) do\n nil\n end\n\n defp find_doc(docs, fun, arity) do\n doc = List.keyfind(docs, {fun, arity}, 0) || find_doc_defaults(docs, fun, arity)\n if doc != nil and has_content?(doc), do: doc\n end\n\n defp find_doc_defaults(docs, function, min) do\n Enum.find(docs, fn doc ->\n case elem(doc, 0) do\n {^function, arity} when arity > min ->\n defaults = Enum.count(elem(doc, 3), &match?({:\\\\, _, _}, &1))\n arity <= min + defaults\n\n _ ->\n false\n end\n end)\n end\n\n defp has_content?({_, _, _, _, false}), do: false\n defp has_content?({{name, _}, _, _, _, nil}), do: hd(Atom.to_charlist(name)) != ?_\n defp has_content?({_, _, _, _, _}), do: true\n\n defp print_fun(mod, {{fun, arity}, _line, kind, args, doc}, spec) do\n if callback_module = is_nil(doc) and callback_module(mod, fun, arity) do\n filter = &match?({^fun, ^arity}, elem(&1, 0))\n\n case get_callback_docs(callback_module, filter) do\n {:ok, callback_docs} -> Enum.each(callback_docs, &print_typespec\/1)\n _ -> nil\n end\n else\n args = Enum.map_join(args, \", \", &format_doc_arg(&1))\n print_doc(\"#{kind} #{fun}(#{args})\", spec, doc)\n end\n end\n\n defp callback_module(mod, fun, arity) do\n predicate = &match?({{^fun, ^arity}, _}, &1)\n\n mod.module_info(:attributes)\n |> Keyword.get_values(:behaviour)\n |> Stream.concat()\n |> Enum.find(&Enum.any?(Typespec.beam_callbacks(&1), predicate))\n end\n\n defp format_doc_arg({:\\\\, _, [left, right]}) do\n format_doc_arg(left) <> \" \\\\\\\\ \" <> Macro.to_string(right)\n end\n\n defp format_doc_arg({var, _, _}) do\n Atom.to_string(var)\n end\n\n defp get_spec(module, name, arity) do\n all_specs = Typespec.beam_specs(module) || []\n\n case List.keyfind(all_specs, {name, arity}, 0) do\n {_, specs} ->\n formatted =\n Enum.map(specs, fn spec ->\n Typespec.spec_to_ast(name, spec)\n |> format_typespec(:spec)\n |> IO.iodata_to_binary()\n |> String.replace(\"\\n\", \"\\n \")\n |> prefix(\" \")\n |> pair(?\\n)\n end)\n\n [formatted, ?\\n]\n\n nil ->\n []\n end\n end\n\n @doc \"\"\"\n Prints the list of behaviour callbacks or a given callback.\n \"\"\"\n def b(mod) when is_atom(mod) do\n case get_callback_docs(mod, fn _ -> true end) do\n :no_beam -> no_beam(mod)\n :no_docs -> no_docs(mod)\n {:ok, []} -> puts_error(\"No callbacks for #{inspect(mod)} were found\")\n {:ok, docs} -> Enum.each(docs, fn {definition, _} -> IO.puts(definition) end)\n end\n\n dont_display_result()\n end\n\n def b({mod, fun}) when is_atom(mod) and is_atom(fun) do\n filter = &match?({^fun, _}, elem(&1, 0))\n\n case get_callback_docs(mod, filter) do\n :no_beam -> no_beam(mod)\n :no_docs -> no_docs(mod)\n {:ok, []} -> docs_not_found(\"#{inspect(mod)}.#{fun}\")\n {:ok, docs} -> Enum.each(docs, &print_typespec\/1)\n end\n\n dont_display_result()\n end\n\n def b({mod, fun, arity}) when is_atom(mod) and is_atom(fun) and is_integer(arity) do\n filter = &match?({^fun, ^arity}, elem(&1, 0))\n\n case get_callback_docs(mod, filter) do\n :no_beam -> no_beam(mod)\n :no_docs -> no_docs(mod)\n {:ok, []} -> docs_not_found(\"#{inspect(mod)}.#{fun}\/#{arity}\")\n {:ok, docs} -> Enum.each(docs, &print_typespec\/1)\n end\n\n dont_display_result()\n end\n\n def b(invalid) do\n puts_error(\"Invalid arguments for b helper: #{inspect(invalid)}\")\n dont_display_result()\n end\n\n defp get_callback_docs(mod, filter) do\n callbacks = Typespec.beam_callbacks(mod)\n docs = Code.get_docs(mod, :callback_docs)\n\n cond do\n is_nil(callbacks) ->\n :no_beam\n\n is_nil(docs) ->\n :no_docs\n\n true ->\n docs =\n docs\n |> Enum.filter(filter)\n |> Enum.map(fn\n {{fun, arity}, _, :macrocallback, doc} ->\n macro = {:\"MACRO-#{fun}\", arity + 1}\n {format_callback(:macrocallback, fun, macro, callbacks), doc}\n\n {{fun, arity}, _, kind, doc} ->\n {format_callback(kind, fun, {fun, arity}, callbacks), doc}\n end)\n\n {:ok, docs}\n end\n end\n\n defp format_callback(kind, name, key, callbacks) do\n {_, specs} = List.keyfind(callbacks, key, 0)\n\n Enum.map(specs, fn spec ->\n Typespec.spec_to_ast(name, spec)\n |> Macro.prewalk(&drop_macro_env\/1)\n |> format_typespec(kind)\n |> pair(?\\n)\n end)\n end\n\n defp drop_macro_env({name, meta, [{:::, _, [_, {{:., _, [Macro.Env, :t]}, _, _}]} | args]}),\n do: {name, meta, args}\n\n defp drop_macro_env(other), do: other\n\n @doc \"\"\"\n Prints the types for the given module and type documentation.\n \"\"\"\n def t(module) when is_atom(module) do\n case Typespec.beam_types(module) do\n nil ->\n no_beam(module)\n\n [] ->\n types_not_found(inspect(module))\n\n types ->\n Enum.each(types, &(&1 |> format_type() |> IO.puts()))\n end\n\n dont_display_result()\n end\n\n def t({module, type}) when is_atom(module) and is_atom(type) do\n case Typespec.beam_types(module) do\n nil ->\n no_beam(module)\n\n types ->\n printed =\n for {_, {^type, _, args}} = typespec <- types do\n doc = {format_type(typespec), type_doc(module, type, length(args))}\n print_typespec(doc)\n end\n\n if printed == [] do\n types_not_found(\"#{inspect(module)}.#{type}\")\n end\n end\n\n dont_display_result()\n end\n\n def t({module, type, arity}) when is_atom(module) and is_atom(type) and is_integer(arity) do\n case Typespec.beam_types(module) do\n nil ->\n no_beam(module)\n\n types ->\n printed =\n for {_, {^type, _, args}} = typespec <- types, length(args) == arity do\n doc = {format_type(typespec), type_doc(module, type, arity)}\n print_typespec(doc)\n end\n\n if printed == [] do\n types_not_found(\"#{inspect(module)}.#{type}\")\n end\n end\n\n dont_display_result()\n end\n\n def t(invalid) do\n puts_error(\"Invalid arguments for t helper: #{inspect(invalid)}\")\n dont_display_result()\n end\n\n defp type_doc(module, type, arity) do\n docs = Code.get_docs(module, :type_docs)\n {_, _, _, content} = Enum.find(docs, &match?({{^type, ^arity}, _, _, _}, &1))\n content\n end\n\n defp format_type({:opaque, type}) do\n {:::, _, [ast, _]} = Typespec.type_to_ast(type)\n [format_typespec(ast, :opaque), ?\\n]\n end\n\n defp format_type({kind, type}) do\n ast = Typespec.type_to_ast(type)\n [format_typespec(ast, kind), ?\\n]\n end\n\n ## Helpers\n\n defp format_typespec(definition, kind) do\n definition\n |> Macro.to_string()\n |> prefix(\"@#{kind} \")\n |> Code.format_string!(line_length: IEx.width())\n |> IO.iodata_to_binary()\n |> color_prefix_with_line()\n end\n\n defp prefix(string, prefix) do\n prefix <> string\n end\n\n defp pair(left, right) do\n [left, right]\n end\n\n defp color_prefix_with_line(string) do\n [left, right] = :binary.split(string, \" \")\n [IEx.color(:doc_inline_code, left), ?\\s, right]\n end\n\n defp print_doc(heading, types, doc) do\n doc = doc || \"\"\n\n if opts = IEx.Config.ansi_docs() do\n IO.ANSI.Docs.print_heading(heading, opts)\n IO.write(types)\n IO.ANSI.Docs.print(doc, opts)\n else\n IO.puts(\"* #{heading}\\n\")\n IO.write(types)\n IO.puts(doc)\n end\n end\n\n defp print_typespec({types, doc}) do\n IO.puts(types)\n\n if opts = IEx.Config.ansi_docs() do\n doc && IO.ANSI.Docs.print(doc, opts)\n else\n doc && IO.puts(doc)\n end\n end\n\n defp elixir_module?(module) do\n function_exported?(module, :__info__, 1)\n end\n\n defp no_beam(module) do\n case Code.ensure_loaded(module) do\n {:module, _} ->\n puts_error(\n \"Beam code not available for #{inspect(module)} or debug info is missing, cannot load typespecs\"\n )\n\n {:error, reason} ->\n puts_error(\"Could not load module #{inspect(module)}, got: #{reason}\")\n end\n end\n\n defp no_docs(module) do\n puts_error(\"#{inspect(module)} was not compiled with docs\")\n end\n\n defp types_not_found(for), do: not_found(for, \"type information\")\n defp docs_not_found(for), do: not_found(for, \"documentation\")\n\n defp behaviour_found(for) do\n puts_error(\"\"\"\n No documentation for function #{for} was found, but there is a callback with the same name.\n You can view callback documentations with the b\/1 helper.\n \"\"\")\n end\n\n defp not_found(for, type) do\n puts_error(\"No #{type} for #{for} was found\")\n end\n\n defp puts_error(string) do\n IO.puts(IEx.color(:eval_error, string))\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"ffbfe9512bda39c9cb59a967274a36496b37b830","subject":"Removed empty autogenerated test","message":"Removed empty autogenerated test\n","repos":"savonarola\/smppex","old_file":"test\/smppex_test.exs","new_file":"test\/smppex_test.exs","new_contents":"","old_contents":"defmodule SmppexTest do\n use ExUnit.Case\n\n test \"the truth\" do\n assert 1 + 1 == 2\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"32bcc1165eb9eced1b1bcc3ee11edb5173a96450","subject":"Skip deps check when compiling deps","message":"Skip deps check when compiling deps\n","repos":"kimshrier\/elixir,gfvcastro\/elixir,elixir-lang\/elixir,pedrosnk\/elixir,michalmuskala\/elixir,beedub\/elixir,joshprice\/elixir,antipax\/elixir,antipax\/elixir,kelvinst\/elixir,ggcampinho\/elixir,lexmag\/elixir,lexmag\/elixir,kimshrier\/elixir,kelvinst\/elixir,gfvcastro\/elixir,ggcampinho\/elixir,pedrosnk\/elixir,beedub\/elixir","old_file":"lib\/mix\/lib\/mix\/tasks\/compile.ex","new_file":"lib\/mix\/lib\/mix\/tasks\/compile.ex","new_contents":"defmodule Mix.Tasks.Compile do\n use Mix.Task\n\n @shortdoc \"Compile source files\"\n\n @moduledoc \"\"\"\n A meta task that compile source files. It simply runs the\n compilers registered in your project. At the end of compilation\n it ensures load paths are set.\n\n ## Configuration\n\n * `:compilers` - compilers to be run, defaults to:\n\n [:elixir, :app]\n\n It can be configured to handle custom compilers, for example:\n\n [compilers: [:elixir, :mycompiler, :app]]\n\n ## Command line options\n\n * `--list` - List all enabled compilers.\n * `--no-check` - Skip dependencies check before compilation.\n\n \"\"\"\n def run([\"--list\"]) do\n Mix.Task.load_all\n\n shell = Mix.shell\n modules = Mix.Task.all_modules\n\n docs = lc module inlist modules,\n task = Mix.Task.task_name(module),\n match?(\"compile.\" <> _, task),\n doc = Mix.Task.shortdoc(module) do\n { task, doc }\n end\n\n max = Enum.reduce docs, 0, fn({ task, _ }, acc) ->\n max(size(task), acc)\n end\n\n sorted = Enum.qsort(docs)\n\n Enum.each sorted, fn({ task, doc }) ->\n shell.info format('mix ~-#{max}s # ~s', [task, doc])\n end\n\n shell.info \"\\nEnabled compilers: #{Enum.join get_compilers, \", \"}\"\n end\n\n def run(args) do\n ebin = Mix.project[:compile_path] || \"ebin\"\n remove_ebin ebin\n\n Mix.Task.run \"deps.loadpaths\", args\n\n changed = Enum.reduce get_compilers, false, fn(compiler, acc) ->\n res = Mix.Task.run(\"compile.#{compiler}\", args)\n acc or res != :noop\n end\n\n if changed, do: File.touch(ebin)\n Mix.Task.run \"loadpaths\", args\n end\n\n defp remove_ebin(ebin) do\n :code.del_path(ebin \/> File.expand_path \/> binary_to_list)\n end\n\n defp get_compilers do\n Mix.project[:compilers] || if Mix.Project.defined? do\n [:elixir, :app]\n else\n [:elixir]\n end\n end\n\n defp format(expression, args) do\n :io_lib.format(expression, args) \/> iolist_to_binary\n end\nend\n","old_contents":"defmodule Mix.Tasks.Compile do\n use Mix.Task\n\n @shortdoc \"Compile source files\"\n\n @moduledoc \"\"\"\n A meta task that compile source files. It simply runs the\n compilers registered in your project. At the end of compilation\n it ensures load paths are set.\n\n ## Configuration\n\n * `:compilers` - compilers to be run, defaults to:\n\n [:elixir, :app]\n\n It can be configured to handle custom compilers, for example:\n\n [compilers: [:elixir, :mycompiler, :app]]\n\n ## Command line options\n\n * `--list` - List all enabled compilers.\n * `--no-check` - Skip dependencies check before compilation.\n\n \"\"\"\n def run([\"--list\"]) do\n Mix.Task.load_all\n\n shell = Mix.shell\n modules = Mix.Task.all_modules\n\n docs = lc module inlist modules,\n task = Mix.Task.task_name(module),\n match?(\"compile.\" <> _, task),\n doc = Mix.Task.shortdoc(module) do\n { task, doc }\n end\n\n max = Enum.reduce docs, 0, fn({ task, _ }, acc) ->\n max(size(task), acc)\n end\n\n sorted = Enum.qsort(docs)\n\n Enum.each sorted, fn({ task, doc }) ->\n shell.info format('mix ~-#{max}s # ~s', [task, doc])\n end\n\n shell.info \"\\nEnabled compilers: #{Enum.join get_compilers, \", \"}\"\n end\n\n def run(args) do\n ebin = Mix.project[:compile_path] || \"ebin\"\n remove_ebin ebin\n\n Mix.Task.run \"deps.loadpaths\"\n\n changed = Enum.reduce get_compilers, false, fn(compiler, acc) ->\n res = Mix.Task.run(\"compile.#{compiler}\", args)\n acc or res != :noop\n end\n\n if changed, do: File.touch(ebin)\n Mix.Task.run \"loadpaths\"\n end\n\n defp remove_ebin(ebin) do\n :code.del_path(ebin \/> File.expand_path \/> binary_to_list)\n end\n\n defp get_compilers do\n Mix.project[:compilers] || if Mix.Project.defined? do\n [:elixir, :app]\n else\n [:elixir]\n end\n end\n\n defp format(expression, args) do\n :io_lib.format(expression, args) \/> iolist_to_binary\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"8f848dc9c75bf2a3ca4fe3a3cefb7eb2839a0a28","subject":"Support Unicode messages","message":"Support Unicode messages\n","repos":"Dalgona\/Serum","old_file":"lib\/serum\/io_proxy.ex","new_file":"lib\/serum\/io_proxy.ex","new_contents":"defmodule Serum.IOProxy do\n @moduledoc false\n\n use GenServer\n\n message_categories = [\n debug: {[:light_black_background, :black], [:light_black]},\n error: {[:red_background, :light_white], [:light_white]},\n gen: {[:light_green], []},\n info: {[:light_black_background, :white], []},\n mkdir: {[:light_cyan], []},\n plugin: {[:light_magenta], []},\n read: {[:light_yellow], []},\n theme: {[:light_magenta], []},\n warn: {[:yellow_background, :black], [:yellow]}\n ]\n\n @type config :: %{mute_msg: boolean(), mute_err: boolean()}\n\n @spec start_link(term()) :: GenServer.on_start()\n def start_link(_args) do\n GenServer.start_link(__MODULE__, [], name: __MODULE__)\n end\n\n @doc \"Gets the current configuration of `Serum.IOProxy`.\"\n @spec config() :: {:ok, config()}\n def config do\n GenServer.call(__MODULE__, :get_config)\n end\n\n @doc \"\"\"\n Configures `Serum.IOProxy`.\n\n ## Options\n\n - `mute_err` (boolean): Controls whether outputs to `:stderr` must be\n suppressed. Defaults to `false`.\n - `mute_msg` (boolean): Controls whether outputs to `:stdio` must be\n suppressed. Defaults to `false`.\n \"\"\"\n @spec config(keyword()) :: :ok\n def config(options) when is_list(options) do\n GenServer.call(__MODULE__, {:set_config, options})\n end\n\n @doc \"\"\"\n Prints a message to the standard output.\n\n Available categories are:\n `#{message_categories |> Keyword.keys() |> inspect()}`\n \"\"\"\n @spec put_msg(atom(), binary()) :: :ok\n def put_msg(category, msg) do\n GenServer.call(__MODULE__, {:put_msg, category, msg})\n end\n\n @doc \"\"\"\n Prints a message to the standard error output.\n\n Available categories are:\n `#{message_categories |> Keyword.keys() |> inspect()}`\n \"\"\"\n @spec put_err(atom(), binary()) :: :ok\n def put_err(category, msg) do\n GenServer.call(__MODULE__, {:put_err, category, msg})\n end\n\n @impl GenServer\n def init(_args) do\n {:ok, %{mute_msg: false, mute_err: false}}\n end\n\n @impl GenServer\n def handle_call(request, from, state)\n def handle_call(:get_config, _, state), do: {:reply, {:ok, state}, state}\n\n def handle_call({:set_config, conf}, _, state) do\n conf_map = conf |> Map.new() |> Map.take([:mute_msg, :mute_err])\n\n {:reply, :ok, Map.merge(state, conf_map)}\n end\n\n def handle_call({:put_msg, category, msg}, _, state) do\n unless(state.mute_msg, do: IO.puts(format_message(category, msg)))\n\n {:reply, :ok, state}\n end\n\n def handle_call({:put_err, category, msg}, _, state) do\n unless(state.mute_err, do: IO.puts(:stderr, format_message(category, msg)))\n\n {:reply, :ok, state}\n end\n\n max_length =\n message_categories\n |> Enum.map(fn {category, _} -> to_string(category) end)\n |> Enum.map(&String.length\/1)\n |> Enum.max()\n\n @spec format_message(atom(), binary()) :: IO.chardata()\n defp format_message(category, msg)\n\n Enum.each(message_categories, fn {category, {head_fmt, body_fmt}} ->\n cat_str = category |> to_string() |> String.upcase()\n\n header =\n [head_fmt, String.pad_leading(cat_str, max_length + 1), ?\\s]\n |> IO.ANSI.format(true)\n |> IO.iodata_to_binary()\n\n body_fmt =\n [body_fmt, \"~ts\"]\n |> IO.ANSI.format(true)\n |> IO.iodata_to_binary()\n\n defp format_message(unquote(category), msg) do\n formatted = :io_lib.format(unquote(body_fmt), [format_newlines(msg)])\n\n [?\\r, unquote(header), ?\\s, formatted]\n end\n end)\n\n @spec format_newlines(binary()) :: IO.chardata()\n defp format_newlines(msg) do\n lines = String.split(msg, ~r\/\\r?\\n\/)\n indent = String.duplicate(\" \", unquote(max_length) + 3)\n\n Enum.intersperse(lines, [\"\\n\", indent])\n end\nend\n","old_contents":"defmodule Serum.IOProxy do\n @moduledoc false\n\n use GenServer\n\n message_categories = [\n debug: {[:light_black_background, :black], [:light_black]},\n error: {[:red_background, :light_white], [:light_white]},\n gen: {[:light_green], []},\n info: {[:light_black_background, :white], []},\n mkdir: {[:light_cyan], []},\n plugin: {[:light_magenta], []},\n read: {[:light_yellow], []},\n theme: {[:light_magenta], []},\n warn: {[:yellow_background, :black], [:yellow]}\n ]\n\n @type config :: %{mute_msg: boolean(), mute_err: boolean()}\n\n @spec start_link(term()) :: GenServer.on_start()\n def start_link(_args) do\n GenServer.start_link(__MODULE__, [], name: __MODULE__)\n end\n\n @doc \"Gets the current configuration of `Serum.IOProxy`.\"\n @spec config() :: {:ok, config()}\n def config do\n GenServer.call(__MODULE__, :get_config)\n end\n\n @doc \"\"\"\n Configures `Serum.IOProxy`.\n\n ## Options\n\n - `mute_err` (boolean): Controls whether outputs to `:stderr` must be\n suppressed. Defaults to `false`.\n - `mute_msg` (boolean): Controls whether outputs to `:stdio` must be\n suppressed. Defaults to `false`.\n \"\"\"\n @spec config(keyword()) :: :ok\n def config(options) when is_list(options) do\n GenServer.call(__MODULE__, {:set_config, options})\n end\n\n @doc \"\"\"\n Prints a message to the standard output.\n\n Available categories are:\n `#{message_categories |> Keyword.keys() |> inspect()}`\n \"\"\"\n @spec put_msg(atom(), binary()) :: :ok\n def put_msg(category, msg) do\n GenServer.call(__MODULE__, {:put_msg, category, msg})\n end\n\n @doc \"\"\"\n Prints a message to the standard error output.\n\n Available categories are:\n `#{message_categories |> Keyword.keys() |> inspect()}`\n \"\"\"\n @spec put_err(atom(), binary()) :: :ok\n def put_err(category, msg) do\n GenServer.call(__MODULE__, {:put_err, category, msg})\n end\n\n @impl GenServer\n def init(_args) do\n {:ok, %{mute_msg: false, mute_err: false}}\n end\n\n @impl GenServer\n def handle_call(request, from, state)\n def handle_call(:get_config, _, state), do: {:reply, {:ok, state}, state}\n\n def handle_call({:set_config, conf}, _, state) do\n conf_map = conf |> Map.new() |> Map.take([:mute_msg, :mute_err])\n\n {:reply, :ok, Map.merge(state, conf_map)}\n end\n\n def handle_call({:put_msg, category, msg}, _, state) do\n unless(state.mute_msg, do: IO.puts(format_message(category, msg)))\n\n {:reply, :ok, state}\n end\n\n def handle_call({:put_err, category, msg}, _, state) do\n unless(state.mute_err, do: IO.puts(:stderr, format_message(category, msg)))\n\n {:reply, :ok, state}\n end\n\n max_length =\n message_categories\n |> Enum.map(fn {category, _} -> to_string(category) end)\n |> Enum.map(&String.length\/1)\n |> Enum.max()\n\n @spec format_message(atom(), binary()) :: IO.chardata()\n defp format_message(category, msg)\n\n Enum.each(message_categories, fn {category, {head_fmt, body_fmt}} ->\n cat_str = category |> to_string() |> String.upcase()\n\n header =\n [head_fmt, String.pad_leading(cat_str, max_length + 1), ?\\s]\n |> IO.ANSI.format(true)\n |> IO.iodata_to_binary()\n\n body_fmt =\n [body_fmt, \"~s\"]\n |> IO.ANSI.format(true)\n |> IO.iodata_to_binary()\n\n defp format_message(unquote(category), msg) do\n formatted = :io_lib.format(unquote(body_fmt), [format_newlines(msg)])\n\n [?\\r, unquote(header), ?\\s, formatted]\n end\n end)\n\n @spec format_newlines(binary()) :: IO.chardata()\n defp format_newlines(msg) do\n lines = String.split(msg, ~r\/\\r?\\n\/)\n indent = String.duplicate(\" \", unquote(max_length) + 3)\n\n Enum.intersperse(lines, [\"\\n\", indent])\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"56bd2148c71d6464b49d88b9e459bebc1ff04b60","subject":"Typo: using ';' in auth headers, should be ',' instead.","message":"Typo: using ';' in auth headers, should be ',' instead.\n","repos":"balena\/elixir-sippet,balena\/elixir-sippet","old_file":"lib\/sippet\/message.ex","new_file":"lib\/sippet\/message.ex","new_contents":"defmodule Sippet.Message do\n @moduledoc \"\"\"\n Message primitive for composing SIP messages.\n Build a SIP message with the `Sippet.Message` struct.\n\n request =\n Sippet.Message.build_request(\"INVITE\", \"sip:joe@example.com\")\n |> Sippet.Message.put_header(:to,\n {\"\", Sippet.URI.parse!(\"sip:joe@example.com\"), %{}})\n ...\n \"\"\"\n\n @behaviour Access\n\n alias Sippet.URI, as: URI\n alias Sippet.Message.RequestLine, as: RequestLine\n alias Sippet.Message.StatusLine, as: StatusLine\n\n defstruct start_line: nil,\n headers: %{},\n body: nil,\n target: nil\n\n @type uri :: URI.t()\n\n @type method :: atom | binary\n\n @type header :: atom | binary\n\n @type protocol :: atom | binary\n\n @type token :: binary\n\n @type params :: %{binary => binary}\n\n @type token_params ::\n {token :: binary, params}\n\n @type type_subtype_params ::\n {{type :: binary, subtype :: binary}, params}\n\n @type uri_params ::\n {display_name :: binary, uri :: URI.t(), params}\n\n @type name_uri_params ::\n {display_name :: binary, uri :: URI.t(), params}\n\n @type auth_params ::\n {scheme :: binary, params}\n\n @type via_value ::\n {{major :: integer, minor :: integer}, protocol, {host :: binary, port :: integer},\n params}\n\n @type headers :: %{\n optional(:accept) => [type_subtype_params, ...],\n optional(:accept_encoding) => [token_params, ...],\n optional(:accept_language) => [token_params, ...],\n optional(:alert_info) => [uri_params, ...],\n optional(:allow) => [token, ...],\n optional(:authentication_info) => params,\n optional(:authorization) => [auth_params, ...],\n required(:call_id) => token,\n optional(:call_info) => [uri_params, ...],\n optional(:contact) => <<_::1>> | [name_uri_params, ...],\n optional(:content_disposition) => token_params,\n optional(:content_encoding) => [token, ...],\n optional(:content_language) => [token, ...],\n optional(:content_length) => integer,\n optional(:content_type) => type_subtype_params,\n required(:cseq) => {integer, method},\n optional(:date) => NaiveDateTime.t(),\n optional(:error_info) => [uri_params, ...],\n optional(:expires) => integer,\n required(:from) => name_uri_params,\n optional(:in_reply_to) => [token, ...],\n required(:max_forwards) => integer,\n optional(:mime_version) => {major :: integer, minor :: integer},\n optional(:min_expires) => integer,\n optional(:organization) => binary,\n optional(:priority) => token,\n optional(:proxy_authenticate) => [auth_params, ...],\n optional(:proxy_authorization) => [auth_params, ...],\n optional(:proxy_require) => [token, ...],\n optional(:reason) => {binary, params},\n optional(:record_route) => [name_uri_params, ...],\n optional(:reply_to) => name_uri_params,\n optional(:require) => [token, ...],\n optional(:retry_after) => {integer, binary, params},\n optional(:route) => [name_uri_params, ...],\n optional(:server) => binary,\n optional(:subject) => binary,\n optional(:supported) => [token, ...],\n optional(:timestamp) => {timestamp :: float, delay :: float},\n required(:to) => name_uri_params,\n optional(:unsupported) => [token, ...],\n optional(:user_agent) => binary,\n required(:via) => [via_value, ...],\n optional(:warning) => [{integer, agent :: binary, binary}, ...],\n optional(:www_authenticate) => [auth_params, ...],\n optional(binary) => [binary, ...]\n }\n\n @type single_value ::\n binary\n | integer\n | {sequence :: integer, method}\n | {major :: integer, minor :: integer}\n | token_params\n | type_subtype_params\n | uri_params\n | name_uri_params\n | {delta_seconds :: integer, comment :: binary, params}\n | {timestamp :: integer, delay :: integer}\n | <<_::1>>\n | [name_uri_params, ...]\n | NaiveDateTime.t()\n\n @type multiple_value ::\n token_params\n | type_subtype_params\n | uri_params\n | name_uri_params\n | via_value\n | auth_params\n | params\n | {code :: integer, agent :: binary, text :: binary}\n\n @type value ::\n single_value\n | [multiple_value]\n\n @type t :: %__MODULE__{\n start_line: RequestLine.t() | StatusLine.t(),\n headers: %{header => value},\n body: binary | nil,\n target:\n nil\n | {\n protocol :: atom | binary,\n host :: binary,\n dport :: integer\n }\n }\n\n @type request :: %__MODULE__{\n start_line: RequestLine.t()\n }\n\n @type response :: %__MODULE__{\n start_line: StatusLine.t()\n }\n\n @external_resource protocols_path = Path.join([__DIR__, \"..\", \"..\", \"c_src\", \"protocol_list.h\"])\n\n known_protocols =\n for line <- File.stream!(protocols_path, [], :line),\n line |> String.starts_with?(\"SIP_PROTOCOL\") do\n [_, protocol] = Regex.run(~r\/SIP_PROTOCOL\\(([^,]+)\\)\/, line)\n atom = protocol |> String.downcase() |> String.to_atom()\n\n defp string_to_protocol(unquote(protocol)),\n do: unquote(atom)\n\n protocol\n end\n\n defp string_to_protocol(string), do: string\n\n @doc \"\"\"\n Returns a list of all known transport protocols, as a list of uppercase\n strings.\n\n ## Example:\n\n iex> Sippet.Message.known_protocols()\n [\"AMQP\", \"DCCP\", \"DTLS\", \"SCTP\", \"STOMP\", \"TCP\", \"TLS\", \"UDP\", \"WS\", \"WSS\"]\n \"\"\"\n @spec known_protocols() :: [String.t()]\n def known_protocols(), do: unquote(known_protocols)\n\n @doc \"\"\"\n Converts a string representing a known protocol into an atom, otherwise as an\n uppercase string.\n\n ## Example:\n\n iex> Sippet.Message.to_protocol(\"UDP\")\n :udp\n\n iex> Sippet.Message.to_protocol(\"uDp\")\n :udp\n\n iex> Sippet.Message.to_protocol(\"aaa\")\n \"AAA\"\n\n \"\"\"\n @spec to_protocol(String.t()) :: protocol\n def to_protocol(string), do: string_to_protocol(string |> String.upcase())\n\n @external_resource methods_path = Path.join([__DIR__, \"..\", \"..\", \"c_src\", \"method_list.h\"])\n\n known_methods =\n for line <- File.stream!(methods_path, [], :line),\n line |> String.starts_with?(\"SIP_METHOD\") do\n [_, method] = Regex.run(~r\/SIP_METHOD\\(([^,]+)\\)\/, line)\n atom = method |> String.downcase() |> String.to_atom()\n\n defp string_to_method(unquote(method)),\n do: unquote(atom)\n\n method\n end\n\n defp string_to_method(string), do: string\n\n @doc \"\"\"\n Returns a list of all known methods, as a list of uppercase strings.\n\n ## Example:\n\n iex> Sippet.Message.known_methods()\n [\"ACK\", \"BYE\", \"CANCEL\", \"INFO\", \"INVITE\", \"MESSAGE\", \"NOTIFY\", \"OPTIONS\",\n \"PRACK\", \"PUBLISH\", \"PULL\", \"PUSH\", \"REFER\", \"REGISTER\", \"STORE\", \"SUBSCRIBE\",\n \"UPDATE\"]\n \"\"\"\n @spec known_methods() :: [String.t()]\n def known_methods(), do: unquote(known_methods)\n\n @doc \"\"\"\n Converts a string representing a known method into an atom, otherwise as an\n uppercase string.\n\n ## Example:\n\n iex> Sippet.Message.to_method(\"INVITE\")\n :invite\n\n iex> Sippet.Message.to_method(\"InViTe\")\n :invite\n\n iex> Sippet.Message.to_method(\"aaa\")\n \"AAA\"\n\n \"\"\"\n @spec to_method(String.t()) :: method\n def to_method(string), do: string_to_method(string |> String.upcase())\n\n @doc \"\"\"\n Returns a SIP request created from its basic elements.\n\n If the `method` is a binary and is a known method, it will be converted to\n a lowercase atom; otherwise, it will be stored as an uppercase string. If\n `method` is an atom, it will be just kept.\n\n If the `request_uri` is a binary, it will be parsed as a `Sippet.URI` struct.\n Otherwise, if it's already a `Sippet.URI`, it will be stored unmodified.\n\n The newly created struct has an empty header map, and the body is `nil`.\n\n ## Examples:\n\n iex> req1 = Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n %Sippet.Message{body: nil, headers: %{},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n iex> req2 = Sippet.Message.build_request(\"INVITE\", \"sip:foo@bar.com\")\n iex> request_uri = Sippet.URI.parse!(\"sip:foo@bar.com\")\n iex> req3 = Sippet.Message.build_request(\"INVITE\", request_uri)\n iex> req1 == req2 and req2 == req3\n true\n\n \"\"\"\n @spec build_request(method, uri | binary) :: request\n def build_request(method, request_uri)\n\n def build_request(method, request_uri) when is_binary(method) do\n method =\n if String.upcase(method) in known_methods() do\n method |> String.downcase() |> String.to_atom()\n else\n method |> String.upcase()\n end\n\n do_build_request(method, request_uri)\n end\n\n def build_request(method, request_uri) when is_atom(method),\n do: do_build_request(method, request_uri)\n\n defp do_build_request(method, request_uri),\n do: %__MODULE__{start_line: RequestLine.new(method, request_uri)}\n\n @doc \"\"\"\n Returns a SIP response created from its basic elements.\n\n The `status` parameter can be a `Sippet.Message.StatusLine` struct or an\n integer in the range `100..699` representing the SIP response status code.\n In the latter case, a default reason phrase will be obtained from a default\n set; if there's none, then an exception will be raised.\n\n ## Examples:\n\n iex> resp1 = Sippet.Message.build_response 200\n %Sippet.Message{body: nil, headers: %{},\n start_line: %Sippet.Message.StatusLine{reason_phrase: \"OK\", status_code: 200,\n version: {2, 0}}, target: nil}\n iex> status_line = Sippet.Message.StatusLine.new(200)\n iex> resp2 = status_line |> Sippet.Message.build_response\n iex> resp1 == resp2\n true\n\n \"\"\"\n @spec build_response(100..699 | StatusLine.t()) :: response | no_return\n def build_response(status)\n\n def build_response(%StatusLine{} = status_line),\n do: %__MODULE__{start_line: status_line}\n\n def build_response(status_code) when is_integer(status_code),\n do: build_response(StatusLine.new(status_code))\n\n @doc \"\"\"\n Returns a SIP response with a custom reason phrase.\n\n The `status_code` should be an integer in the range `100..699` representing\n the SIP status code, and `reason_phrase` a binary representing the reason\n phrase text.\n\n iex> Sippet.Message.build_response 400, \"Bad Lorem Ipsum\"\n %Sippet.Message{body: nil, headers: %{},\n start_line: %Sippet.Message.StatusLine{reason_phrase: \"Bad Lorem Ipsum\",\n status_code: 400, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec build_response(100..699, String.t()) :: response\n def build_response(status_code, reason_phrase)\n when is_integer(status_code) and is_binary(reason_phrase),\n do: build_response(StatusLine.new(status_code, reason_phrase))\n\n @doc ~S'''\n Returns a response created from a request, using a given status code.\n\n The `request` should be a valid SIP request, or an exception will be thrown.\n\n The `status` parameter can be a `Sippet.Message.StatusLine` struct or an\n integer in the range `100..699` representing the SIP response status code.\n In the latter case, a default reason phrase will be obtained from a default\n set; if there's none, then an exception will be raised.\n\n ## Example:\n\n request =\n \"\"\"\n REGISTER sips:ss2.biloxi.example.com SIP\/2.0\n Via: SIP\/2.0\/TLS client.biloxi.example.com:5061;branch=z9hG4bKnashds7\n Max-Forwards: 70\n From: Bob ;tag=a73kszlfl\n To: Bob \n Call-ID: 1j9FpLxk3uxtm8tn@biloxi.example.com\n CSeq: 1 REGISTER\n Contact: \n Content-Length: 0\n \"\"\" |> Sippet.Message.parse!()\n request |> Sippet.Message.to_response(200) |> IO.puts\n SIP\/2.0 200 OK\n Via: SIP\/2.0\/TLS client.biloxi.example.com:5061;branch=z9hG4bKnashds7\n To: \"Bob\" ;tag=K2fizKkV\n From: \"Bob\" ;tag=a73kszlfl\n CSeq: 1 REGISTER\n Content-Length: 0\n Call-ID: 1j9FpLxk3uxtm8tn@biloxi.example.com\n\n\n :ok\n\n '''\n @spec to_response(request, integer | StatusLine.t()) :: response | no_return\n def to_response(request, status)\n\n def to_response(request, status_code) when is_integer(status_code),\n do: to_response(request, StatusLine.new(status_code))\n\n def to_response(\n %__MODULE__{start_line: %RequestLine{}} = request,\n %StatusLine{} = status_line\n ) do\n response =\n status_line\n |> build_response()\n |> put_header(:via, get_header(request, :via))\n |> put_header(:from, get_header(request, :from))\n |> put_header(:to, get_header(request, :to))\n |> put_header(:call_id, get_header(request, :call_id))\n |> put_header(:cseq, get_header(request, :cseq))\n\n response =\n if status_line.status_code > 100 and\n not Map.has_key?(elem(response.headers.to, 2), \"tag\") do\n {display_name, uri, params} = response.headers.to\n params = Map.put(params, \"tag\", create_tag())\n response |> put_header(:to, {display_name, uri, params})\n else\n response\n end\n\n if has_header?(request, :record_route) do\n response |> put_header(:record_route, get_header(request, :record_route))\n else\n response\n end\n end\n\n @doc ~S'''\n Returns a response created from a request, using a given status code and a\n custom reason phrase.\n\n The `request` should be a valid SIP request, or an exception will be thrown.\n\n The `status_code` parameter should be an integer in the range `100..699`\n representing the SIP response status code. A default reason phrase will be\n obtained from a default set; if there's none, then an exception will be\n raised.\n\n The `reason_phrase` can be any textual representation of the reason phrase\n the application needs to generate, in binary.\n\n ## Example:\n\n request =\n \"\"\"\n REGISTER sips:ss2.biloxi.example.com SIP\/2.0\n Via: SIP\/2.0\/TLS client.biloxi.example.com:5061;branch=z9hG4bKnashds7\n Max-Forwards: 70\n From: Bob ;tag=a73kszlfl\n To: Bob \n Call-ID: 1j9FpLxk3uxtm8tn@biloxi.example.com\n CSeq: 1 REGISTER\n Contact: \n Content-Length: 0\n \"\"\" |> Sippet.Message.parse!()\n request |> Sippet.Message.to_response(400, \"Bad Lorem Ipsum\") |> IO.puts\n SIP\/2.0 400 Bad Lorem Ipsum\n Via: SIP\/2.0\/TLS client.biloxi.example.com:5061;branch=z9hG4bKnashds7\n To: \"Bob\" ;tag=K2fizKkV\n From: \"Bob\" ;tag=a73kszlfl\n CSeq: 1 REGISTER\n Content-Length: 0\n Call-ID: 1j9FpLxk3uxtm8tn@biloxi.example.com\n\n\n :ok\n\n '''\n @spec to_response(request, integer, String.t()) :: response\n def to_response(request, status_code, reason_phrase)\n when is_integer(status_code) and is_binary(reason_phrase),\n do: to_response(request, StatusLine.new(status_code, reason_phrase))\n\n @doc \"\"\"\n Creates a local tag (48-bit random string, 8 characters long).\n\n ## Example:\n\n Sippet.Message.create_tag\n \"lnTMo9Zn\"\n\n \"\"\"\n @spec create_tag() :: binary\n def create_tag(), do: do_random_string(48)\n\n defp do_random_string(length) do\n round(Float.ceil(length \/ 8))\n |> :crypto.strong_rand_bytes()\n |> Base.url_encode64(padding: false)\n end\n\n @doc \"\"\"\n Returns the RFC 3261 compliance magic cookie, inserted in via-branch\n parameters.\n\n ## Example:\n\n iex> Sippet.Message.magic_cookie\n \"z9hG4bK\"\n\n \"\"\"\n @spec magic_cookie() :: binary\n def magic_cookie(), do: \"z9hG4bK\"\n\n @doc \"\"\"\n Creates an unique local branch (72-bit random string, 7+12 characters long).\n\n ## Example:\n\n Sippet.Message.create_branch\n \"z9hG4bKuQpiub9h7fBb\"\n\n \"\"\"\n @spec create_branch() :: binary\n def create_branch(), do: magic_cookie() <> do_random_string(72)\n\n @doc \"\"\"\n Creates an unique Call-ID (120-bit random string, 20 characters long).\n\n ## Example\n\n Sippet.create_call_id\n \"NlV4TfQwkmPlNJkyHPpF\"\n\n \"\"\"\n @spec create_call_id() :: binary\n def create_call_id(), do: do_random_string(120)\n\n @doc \"\"\"\n Shortcut to check if the message is a request.\n\n ## Examples:\n\n iex> req = Sippet.Message.build_request :invite, \"sip:foo@bar.com\"\n iex> req |> Sippet.Message.request?\n true\n\n \"\"\"\n @spec request?(t) :: boolean\n def request?(%__MODULE__{start_line: %RequestLine{}} = _), do: true\n def request?(_), do: false\n\n @doc \"\"\"\n Shortcut to check if the message is a response.\n\n ## Examples:\n\n iex> resp = Sippet.Message.build_response 200\n iex> resp |> Sippet.Message.response?\n true\n\n \"\"\"\n @spec response?(t) :: boolean\n def response?(%__MODULE__{start_line: %StatusLine{}} = _), do: true\n def response?(_), do: false\n\n @doc \"\"\"\n Returns whether a given `header` exists in the given `message`.\n\n ## Examples:\n\n iex> request =\n ...> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header(:cseq, {1, :invite})\n iex> request |> Sippet.Message.has_header?(:cseq)\n true\n\n \"\"\"\n @spec has_header?(t, header) :: boolean\n def has_header?(message, header),\n do: Map.has_key?(message.headers, header)\n\n @doc \"\"\"\n Puts the `value` under `header` on the `message`.\n\n If the header already exists, it will be overridden.\n\n ## Examples:\n\n iex> request = Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n iex> request |> Sippet.Message.put_header(:cseq, {1, :invite})\n %Sippet.Message{body: nil, headers: %{cseq: {1, :invite}},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec put_header(t, header, value) :: t\n def put_header(message, header, value),\n do: %{message | headers: Map.put(message.headers, header, value)}\n\n @doc \"\"\"\n Puts the `value` under `header` on the `message` unless the `header` already\n exists.\n\n ## Examples:\n\n iex> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_new_header(:max_forwards, 70)\n ...> |> Sippet.Message.put_new_header(:max_forwards, 1)\n %Sippet.Message{body: nil, headers: %{max_forwards: 70},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec put_new_header(t, header, value) :: t\n def put_new_header(message, header, value) do\n case has_header?(message, header) do\n true -> message\n false -> put_header(message, header, value)\n end\n end\n\n @doc \"\"\"\n Evaluates `fun` and puts the result under `header` in `message` unless\n `header` is already present.\n\n This function is useful in case you want to compute the value to put under\n `header` only if `header` is not already present (e.g., the value is\n expensive to calculate or generally difficult to setup and teardown again).\n\n ## Examples:\n\n iex> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_new_lazy_header(:max_forwards, fn -> 70 end)\n ...> |> Sippet.Message.put_new_lazy_header(:max_forwards, fn -> 1 end)\n %Sippet.Message{body: nil, headers: %{max_forwards: 70},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec put_new_lazy_header(t, header, (() -> value)) :: t\n def put_new_lazy_header(message, header, fun) when is_function(fun, 0) do\n case has_header?(message, header) do\n true -> message\n false -> put_header(message, header, fun.())\n end\n end\n\n @doc \"\"\"\n Puts the `value` under `header` on the `message`, as front element.\n\n If the parameter `value` is `nil`, then the empty list will be prefixed to\n the `header`.\n\n ## Examples:\n\n iex> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header_front(:content_language, \"de-DE\")\n ...> |> Sippet.Message.put_header_front(:content_language, \"en-US\")\n %Sippet.Message{body: nil, headers: %{content_language: [\"en-US\", \"de-DE\"]},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec put_header_front(t, header, multiple_value) :: t\n def put_header_front(message, header, value) do\n existing = get_header(message, header, [])\n\n new_list =\n case value do\n nil -> existing\n _ -> [value | existing]\n end\n\n put_header(message, header, new_list)\n end\n\n @doc \"\"\"\n Puts the `value` under `header` on the `message`, as last element.\n\n If the parameter `value` is `nil`, then the empty list will be appended to\n the `header`.\n\n ## Examples:\n\n iex> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header_back(:content_language, \"en-US\")\n ...> |> Sippet.Message.put_header_back(:content_language, \"de-DE\")\n %Sippet.Message{body: nil, headers: %{content_language: [\"en-US\", \"de-DE\"]},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec put_header_back(t, header, multiple_value) :: t\n def put_header_back(message, header, value) do\n existing = get_header(message, header, [])\n\n new_list =\n case value do\n nil -> existing\n _ -> List.foldr(existing, [value], fn x, acc -> [x | acc] end)\n end\n\n put_header(message, header, new_list)\n end\n\n @doc \"\"\"\n Deletes all `header` values in `message`.\n\n ## Examples:\n\n iex> request =\n ...> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header(:content_language, [\"en-US\", \"de-DE\"])\n ...> |> Sippet.Message.put_header(:max_forwards, 70)\n iex> request |> Sippet.Message.delete_header(:content_language)\n %Sippet.Message{body: nil, headers: %{max_forwards: 70},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec delete_header(t, header) :: t\n def delete_header(message, header) do\n %{message | headers: Map.delete(message.headers, header)}\n end\n\n @doc \"\"\"\n Deletes the first value of `header` in `message`.\n\n ## Examples:\n\n iex> request =\n ...> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header(:content_language, [\"en-US\", \"de-DE\"])\n ...> |> Sippet.Message.put_header(:max_forwards, 70)\n iex> request |> Sippet.Message.delete_header_front(:content_language)\n %Sippet.Message{body: nil,\n headers: %{content_language: [\"de-DE\"], max_forwards: 70},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec delete_header_front(t, header) :: t\n def delete_header_front(message, header) do\n case get_header(message, header) do\n nil -> message\n [_] -> delete_header(message, header)\n [_ | tail] -> put_header(message, header, tail)\n end\n end\n\n @doc \"\"\"\n Deletes the last value of `header` in `message`.\n\n ## Examples:\n\n iex> request =\n ...> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header(:content_language, [\"en-US\", \"de-DE\"])\n ...> |> Sippet.Message.put_header(:max_forwards, 70)\n iex> request |> Sippet.Message.delete_header_back(:content_language)\n %Sippet.Message{body: nil,\n headers: %{content_language: [\"en-US\"], max_forwards: 70},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec delete_header_back(t, header) :: t\n def delete_header_back(message, header) do\n case get_header(message, header) do\n nil -> message\n [_] -> delete_header(message, header)\n [_ | _] = values -> put_header(message, header, do_remove_last(values))\n end\n end\n\n defp do_remove_last(list) when is_list(list) do\n [_ | tail] = Enum.reverse(list)\n Enum.reverse(tail)\n end\n\n @doc \"\"\"\n Drops all given `headers` from `message`.\n\n ## Examples:\n\n iex> request =\n ...> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header(:content_language, [\"en-US\", \"de-DE\"])\n ...> |> Sippet.Message.put_header(:max_forwards, 70)\n iex> request |> Sippet.Message.drop_headers([:content_language, :max_forwards])\n %Sippet.Message{body: nil, headers: %{},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec drop_headers(t, [header]) :: t\n def drop_headers(message, headers),\n do: %{message | headers: Map.drop(message.headers, headers)}\n\n @doc \"\"\"\n Fetches all values for a specific `header` and returns it in a tuple.\n\n If the `header` does not exist, returns `:error`.\n\n ## Examples:\n\n iex> request =\n ...> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header(:content_language, [\"en-US\", \"de-DE\"])\n ...> |> Sippet.Message.put_header(:max_forwards, 70)\n iex> request |> Sippet.Message.fetch_header(:content_language)\n {:ok, [\"en-US\", \"de-DE\"]}\n iex> request |> Sippet.Message.fetch_header(:cseq)\n :error\n\n \"\"\"\n @spec fetch_header(t, header) :: {:ok, value} | :error\n def fetch_header(message, header),\n do: Map.fetch(message.headers, header)\n\n @doc \"\"\"\n Fetches the first value of a specific `header` and returns it in a tuple.\n\n If the `header` does not exist, or the value is not a list, returns `:error`.\n If the `header` exists but it is an empty list, returns `{:ok, nil}`.\n\n ## Examples:\n\n iex> request =\n ...> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header(:content_language, [\"en-US\", \"de-DE\"])\n ...> |> Sippet.Message.put_header(:max_forwards, 70)\n iex> request |> Sippet.Message.fetch_header_front(:content_language)\n {:ok, \"en-US\"}\n iex> request |> Sippet.Message.fetch_header_front(:max_forwards)\n :error\n iex> request |> Sippet.Message.fetch_header_front(:cseq)\n :error\n\n \"\"\"\n @spec fetch_header_front(t, header) ::\n {:ok, multiple_value} | :error\n def fetch_header_front(message, header) do\n case fetch_header(message, header) do\n {:ok, []} ->\n {:ok, nil}\n\n {:ok, [first | _]} ->\n {:ok, first}\n\n _otherwise ->\n :error\n end\n end\n\n @doc \"\"\"\n Fetches the last value of a specific `header` and returns it in a tuple.\n\n If the `header` does not exist, or the value is not a list, returns `:error`.\n If the `header` exists but it is an empty list, returns `{:ok, nil}`.\n\n ## Examples:\n\n iex> request =\n ...> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header(:content_language, [\"en-US\", \"de-DE\"])\n ...> |> Sippet.Message.put_header(:max_forwards, 70)\n iex> request |> Sippet.Message.fetch_header_back(:content_language)\n {:ok, \"de-DE\"}\n iex> request |> Sippet.Message.fetch_header_back(:max_forwards)\n :error\n iex> request |> Sippet.Message.fetch_header_back(:cseq)\n :error\n\n \"\"\"\n @spec fetch_header_back(t, header) :: {:ok, multiple_value} | :error\n def fetch_header_back(message, header) do\n case fetch_header(message, header) do\n {:ok, []} ->\n {:ok, nil}\n\n {:ok, [value]} ->\n {:ok, value}\n\n {:ok, [_ | rest]} ->\n {:ok, List.last(rest)}\n\n _otherwise ->\n :error\n end\n end\n\n @doc \"\"\"\n Fetches all values for a specific `header` in the given `message`, erroring\n out if `message` doesn't contain `header`.\n\n If `message` contains the given `header`, all corresponding values are\n returned in a list. If `message` doesn't contain the `header`, a `KeyError`\n exception is raised.\n \"\"\"\n @spec fetch_header!(t, header) :: value | no_return\n def fetch_header!(message, header),\n do: Map.fetch!(message.headers, header)\n\n @doc \"\"\"\n Fetches the first value of a specific `header` in the given `message`, erroring\n out if `message` doesn't contain `header`.\n\n If `message` contains the given `header`, the first value is returned, which\n may be `nil` case the values list is empty. If `message` doesn't contain the\n `header`, a `KeyError` exception is raised.\n \"\"\"\n @spec fetch_header_front!(t, header) :: multiple_value | no_return\n def fetch_header_front!(message, header) do\n values = fetch_header!(message, header)\n\n if Enum.empty?(values) do\n nil\n else\n List.first(values)\n end\n end\n\n @doc \"\"\"\n Fetches the last value of a specific `header` in the given `message`, erroring\n out if `message` doesn't contain `header`.\n\n If `message` contains the given `header`, the last value is returned, which\n may be `nil` case the values list is empty. If `message` doesn't contain the\n `header`, a `KeyError` exception is raised.\n \"\"\"\n @spec fetch_header_back!(t, header) :: multiple_value | no_return\n def fetch_header_back!(message, header) do\n values = fetch_header!(message, header)\n\n if Enum.empty?(values) do\n nil\n else\n List.last(values)\n end\n end\n\n @doc \"\"\"\n Gets all values for a specific `header` in `message`.\n\n If `header` is present in `message`, then all values are returned in a list.\n Otherwise, `default` is returned (which is `nil` unless specified otherwise).\n \"\"\"\n @spec get_header(t, header) :: value | nil\n @spec get_header(t, header, any) :: value | any\n def get_header(message, header, default \\\\ nil) do\n Map.get(message.headers, header, default)\n end\n\n @doc \"\"\"\n Gets the first value of a specific `header` in `message`.\n\n If `header` is present in `message`, then the first value is returned.\n Otherwise, `default` is returned (which is `nil` unless specified otherwise).\n \"\"\"\n @spec get_header_front(t, header) :: multiple_value | nil\n @spec get_header_front(t, header, any) :: multiple_value | any\n def get_header_front(message, header, default \\\\ nil) do\n case get_header(message, header, nil) do\n nil -> default\n values -> List.first(values)\n end\n end\n\n @doc \"\"\"\n Gets the last value of a specific `header` in `message`.\n\n If `header` is present in `message`, then the last value is returned.\n Otherwise, `default` is returned (which is `nil` unless specified otherwise).\n \"\"\"\n @spec get_header_back(t, header) :: multiple_value | nil\n @spec get_header_back(t, header, any) :: multiple_value | any\n def get_header_back(message, header, default \\\\ nil) do\n case get_header(message, header, nil) do\n nil -> default\n values -> List.last(values)\n end\n end\n\n @doc \"\"\"\n Updates the `header` in `message` with the given function.\n\n If `header` is present in `message` with value `value`, `fun` is invoked\n with argument `value` and its result is used as the new value of `header`.\n If `header` is not present in `message`, `initial` is inserted as the value\n of `header`.\n \"\"\"\n @spec update_header(t, header, value | nil, (value -> value)) :: t\n def update_header(message, header, initial \\\\ nil, fun) do\n %{message | headers: Map.update(message.headers, header, initial, fun)}\n end\n\n @doc \"\"\"\n Updates the first `header` value in `message` with the given function.\n\n If `header` is present in `message` with value `[value]`, `fun` is invoked\n with for first element of `[value]` and its result is used as the new value\n of `header` front. If `header` is not present in `message`, or it is an empty\n list, `initial` is inserted as the single value of `header`.\n \"\"\"\n @spec update_header_front(t, header, value | nil, (multiple_value -> multiple_value)) :: t\n def update_header_front(message, header, initial \\\\ nil, fun)\n when is_function(fun, 1) do\n update_header(message, header, List.wrap(initial), fn [head | tail] -> [fun.(head) | tail] end)\n end\n\n @doc \"\"\"\n Updates the last `header` value in `message` with the given function.\n\n If `header` is present in `message` with value `[value]`, `fun` is invoked\n with for last element of `[value]` and its result is used as the new value of\n `header` back. If `header` is not present in `message`, or it is an empty\n list, `initial` is inserted as the single value of `header`.\n \"\"\"\n @spec update_header_back(t, header, value | nil, (multiple_value -> multiple_value)) :: t\n def update_header_back(message, header, initial \\\\ nil, fun)\n when is_function(fun, 1) do\n update_header(message, header, List.wrap(initial), fn values ->\n do_update_last(values, fun)\n end)\n end\n\n defp do_update_last(values, fun) do\n [last | tail] = Enum.reverse(values)\n Enum.reduce(tail, [fun.(last)], fn x, acc -> [x | acc] end)\n end\n\n @doc \"\"\"\n Returns and removes the values associated with `header` in `message`.\n\n If `header` is present in `message` with values `[value]`, `{[value],\n new_message}` is returned where `new_message` is the result of removing\n `header` from `message`. If `header` is not present in `message`, `{default,\n message}` is returned.\n \"\"\"\n @spec pop_header(t, header) :: {value | nil, t}\n @spec pop_header(t, header, any) :: {value | any, t}\n def pop_header(message, header, default \\\\ nil) do\n {get, new_headers} = Map.pop(message.headers, header, default)\n {get, %{message | headers: new_headers}}\n end\n\n @doc \"\"\"\n Returns and removes the first value associated with `header` in `message`.\n\n If `header` is present in `message` with values `values`,\n `{List.first(values), new_message}` is returned where `new_message` is the\n result of removing `List.first(values)` from `header`. If `header` is not\n present in `message` or it is an empty list, `{default, message}` is\n returned. When the `header` results in an empty list, `message` gets updated\n by removing the header.\n \"\"\"\n @spec pop_header_front(t, header) :: {multiple_value | nil, t}\n @spec pop_header_front(t, header, any) :: {multiple_value | any, t}\n def pop_header_front(message, header, default \\\\ nil) do\n {values, new_headers} = Map.pop(message.headers, header, [])\n\n case values do\n [] ->\n {default, %{message | headers: new_headers}}\n\n [value] ->\n {value, %{message | headers: new_headers}}\n\n [head | tail] ->\n {head, %{message | headers: Map.put(message.headers, header, tail)}}\n end\n end\n\n @doc \"\"\"\n Returns and removes the last value associated with `header` in `message`.\n\n If `header` is present in `message` with values `values`,\n `{List.last(values), new_message}` is returned where `new_message` is the\n result of removing `List.last(values)` from `header`. If `header` is not\n present in `message` or it is an empty list, `{default, message}` is\n returned. When the `header` results in an empty list, `message` gets updated\n by removing the header.\n \"\"\"\n @spec pop_header_back(t, header) :: {multiple_value | nil, t}\n @spec pop_header_back(t, header, any) :: {multiple_value | any, t}\n def pop_header_back(message, header, default \\\\ nil) do\n {values, new_headers} = Map.pop(message.headers, header, [])\n\n case Enum.reverse(values) do\n [] ->\n {default, %{message | headers: new_headers}}\n\n [value] ->\n {value, %{message | headers: new_headers}}\n\n [last | tail] ->\n {last, %{message | headers: Map.put(message.headers, header, Enum.reverse(tail))}}\n end\n end\n\n @doc \"\"\"\n Gets the values from `header` and updates it, all in one pass.\n\n `fun` is called with the current values under `header` in `message` (or `nil`\n if `key` is not present in `message`) and must return a two-element tuple:\n the \"get\" value (the retrieved values, which can be operated on before being\n returned) and the new values to be stored under `header` in the resulting new\n message. `fun` may also return `:pop`, which means all current values shall\n be removed from `message` and returned (making this function behave like\n `Sippet.Message.pop_header(message, header)`. The returned value is a tuple\n with the \"get\" value returned by `fun` and a new message with the updated\n values under `header`.\n \"\"\"\n @spec get_and_update_header(t, header, (value -> {get, value} | :pop)) ::\n {get, t}\n when get: value\n def get_and_update_header(message, header, fun) when is_function(fun, 1) do\n {get, new_headers} = Map.get_and_update(message.headers, header, fun)\n {get, %{message | headers: new_headers}}\n end\n\n @doc \"\"\"\n Gets the first value from `header` and updates it, all in one pass.\n\n `fun` is called with the current first value under `header` in `message` (or\n `nil` if `key` is not present in `message`) and must return a two-element\n tuple: the \"get\" value (the retrieved value, which can be operated on before\n being returned) and the new value to be stored under `header` in the\n resulting new message. `fun` may also return `:pop`, which means the current\n value shall be removed from `message` and returned (making this function\n behave like `Sippet.Message.pop_header_front(message, header)`. The returned\n value is a tuple with the \"get\" value returned by `fun` and a new message\n with the updated values under `header`.\n \"\"\"\n @spec get_and_update_header_front(t, header, (multiple_value -> {get, multiple_value} | :pop)) ::\n {get, t}\n when get: multiple_value\n def get_and_update_header_front(message, header, fun)\n when is_function(fun, 1) do\n {get, new_headers} =\n Map.get_and_update(message.headers, header, &do_get_and_update_header_front(&1, fun))\n\n {get, %{message | headers: new_headers}}\n end\n\n defp do_get_and_update_header_front(nil, fun) do\n case fun.(nil) do\n {get, nil} -> {get, []}\n {get, value} -> {get, [value]}\n :pop -> :pop\n end\n end\n\n defp do_get_and_update_header_front([], fun) do\n case fun.(nil) do\n {get, nil} -> {get, []}\n {get, value} -> {get, [value]}\n :pop -> :pop\n end\n end\n\n defp do_get_and_update_header_front([head | tail], fun) do\n case fun.(head) do\n {get, nil} -> {get, [tail]}\n {get, value} -> {get, [value | tail]}\n :pop -> {head, tail}\n end\n end\n\n @doc \"\"\"\n Gets the last value from `header` and updates it, all in one pass.\n\n `fun` is called with the current last value under `header` in `message` (or\n `nil` if `key` is not present in `message`) and must return a two-element\n tuple: the \"get\" value (the retrieved value, which can be operated on before\n being returned) and the new value to be stored under `header` in the\n resulting new message. `fun` may also return `:pop`, which means the current\n value shall be removed from `message` and returned (making this function\n behave like `Sippet.Message.pop_header_back(message, header)`. The returned\n value is a tuple with the \"get\" value returned by `fun` and a new message\n with the updated values under `header`.\n \"\"\"\n @spec get_and_update_header_back(t, header, (multiple_value -> {get, multiple_value} | :pop)) ::\n {get, t}\n when get: multiple_value\n def get_and_update_header_back(message, header, fun)\n when is_function(fun, 1) do\n {get, new_headers} =\n Map.get_and_update(message.headers, header, &do_get_and_update_header_back(&1, fun))\n\n {get, %{message | headers: new_headers}}\n end\n\n defp do_get_and_update_header_back([], fun) do\n case fun.(nil) do\n {get, value} -> {get, [value]}\n :pop -> :pop\n end\n end\n\n defp do_get_and_update_header_back(values, fun) do\n [last | tail] = Enum.reverse(values)\n\n case fun.(last) do\n {get, new_value} -> {get, Enum.reduce(tail, [new_value], fn x, acc -> [x | acc] end)}\n :pop -> {last, Enum.reverse(last)}\n end\n end\n\n @doc \"\"\"\n Parses a SIP message header block as received by the transport layer.\n\n In order to correctly set the message body, you have to verify the\n `:content_length` header; if it exists, it reflects the body size and you\n have to set it manually on the returned message.\n \"\"\"\n @spec parse(iodata) :: {:ok, t} | {:error, atom}\n def parse(data) do\n binary_data = IO.iodata_to_binary(data)\n\n case Sippet.Parser.parse(IO.iodata_to_binary(binary_data)) do\n {:ok, message} ->\n case do_parse(message, binary_data) do\n {:error, reason} ->\n {:error, reason}\n\n message ->\n {:ok, message}\n end\n\n reason ->\n {:error, reason}\n end\n end\n\n defp do_parse(message, binary_data) do\n case do_parse_start_line(message.start_line) do\n {:error, reason} ->\n {:error, reason}\n\n start_line ->\n case do_parse_headers(message.headers) do\n {:error, reason} ->\n {:error, reason}\n\n headers ->\n %__MODULE__{\n start_line: start_line,\n headers: headers,\n body: get_body(binary_data)\n }\n end\n end\n end\n\n defp get_body(binary_data) do\n case String.split(binary_data, ~r{\\r?\\n\\r?\\n}, parts: 2) do\n [_, body] -> body\n [_] -> nil\n end\n end\n\n defp do_parse_start_line(%{method: _} = start_line) do\n case URI.parse(start_line.request_uri) do\n {:ok, uri} ->\n %RequestLine{\n method: start_line.method,\n request_uri: uri,\n version: start_line.version\n }\n\n other ->\n other\n end\n end\n\n defp do_parse_start_line(%{status_code: _} = start_line) do\n %StatusLine{\n status_code: start_line.status_code,\n reason_phrase: start_line.reason_phrase,\n version: start_line.version\n }\n end\n\n defp do_parse_headers(%{} = headers),\n do: do_parse_headers(Map.to_list(headers), [])\n\n defp do_parse_headers([], result), do: Map.new(result)\n\n defp do_parse_headers([{name, value} | tail], result) do\n case do_parse_header_value(value) do\n {:error, reason} ->\n {:error, reason}\n\n value ->\n do_parse_headers(tail, [{name, value} | result])\n end\n end\n\n defp do_parse_header_value(values) when is_list(values),\n do: do_parse_each_header_value(values, [])\n\n defp do_parse_header_value({{year, month, day}, {hour, minute, second}, microsecond}) do\n NaiveDateTime.from_erl!(\n {{year, month, day}, {hour, minute, second}},\n microsecond\n )\n end\n\n defp do_parse_header_value({display_name, uri, %{} = parameters}) do\n case URI.parse(uri) do\n {:ok, uri} ->\n {display_name, uri, parameters}\n\n other ->\n other\n end\n end\n\n defp do_parse_header_value(value), do: value\n\n defp do_parse_each_header_value([], result), do: Enum.reverse(result)\n\n defp do_parse_each_header_value([head | tail], result) do\n case do_parse_header_value(head) do\n {:error, reason} ->\n {:error, reason}\n\n value ->\n do_parse_each_header_value(tail, [value | result])\n end\n end\n\n @doc \"\"\"\n Parses a SIP message header block as received by the transport layer.\n\n Raises if the string is an invalid SIP header.\n\n In order to correctly set the message body, you have to verify the\n `:content_length` header; if it exists, it reflects the body size and you\n have to set it manually on the returned message.\n \"\"\"\n @spec parse!(String.t() | charlist) :: t | no_return\n def parse!(data) do\n case parse(data) do\n {:ok, message} ->\n message\n\n {:error, reason} ->\n raise ArgumentError,\n \"cannot convert #{inspect(data)} to SIP \" <>\n \"message, reason: #{inspect(reason)}\"\n end\n end\n\n @doc \"\"\"\n Returns the string representation of the given `Sippet.Message` struct.\n \"\"\"\n @spec to_string(t) :: binary\n defdelegate to_string(value), to: String.Chars.Sippet.Message\n\n @doc \"\"\"\n Returns the iodata representation of the given `Sippet.Message` struct.\n \"\"\"\n @spec to_iodata(t) :: iodata\n def to_iodata(%Sippet.Message{} = message) do\n start_line =\n case message.start_line do\n %RequestLine{} -> RequestLine.to_iodata(message.start_line)\n %StatusLine{} -> StatusLine.to_iodata(message.start_line)\n end\n\n # includes a Content-Length header case it does not have one\n message =\n if message.headers |> Map.has_key?(:content_length) do\n message\n else\n len = if(message.body == nil, do: 0, else: String.length(message.body))\n %{message | headers: Map.put(message.headers, :content_length, len)}\n end\n\n [\n start_line,\n \"\\r\\n\",\n do_headers(message.headers),\n \"\\r\\n\",\n if(message.body == nil, do: \"\", else: message.body)\n ]\n end\n\n defp do_headers(%{} = headers), do: do_headers(Map.to_list(headers), [])\n defp do_headers([], result), do: result\n\n defp do_headers([{name, value} | tail], result),\n do: do_headers(tail, [do_header(name, value) | result])\n\n defp do_header(name, value) do\n {name, multiple} =\n case name do\n :accept -> {\"Accept\", true}\n :accept_encoding -> {\"Accept-Encoding\", true}\n :accept_language -> {\"Accept-Language\", true}\n :alert_info -> {\"Alert-Info\", true}\n :allow -> {\"Allow\", true}\n :authentication_info -> {\"Authentication-Info\", false}\n :authorization -> {\"Authorization\", false}\n :call_id -> {\"Call-ID\", true}\n :call_info -> {\"Call-Info\", true}\n :contact -> {\"Contact\", true}\n :content_disposition -> {\"Content-Disposition\", true}\n :content_encoding -> {\"Content-Encoding\", true}\n :content_language -> {\"Content-Language\", true}\n :content_length -> {\"Content-Length\", true}\n :content_type -> {\"Content-Type\", true}\n :cseq -> {\"CSeq\", true}\n :date -> {\"Date\", true}\n :error_info -> {\"Error-Info\", true}\n :expires -> {\"Expires\", true}\n :from -> {\"From\", true}\n :in_reply_to -> {\"In-Reply-To\", true}\n :max_forwards -> {\"Max-Forwards\", true}\n :mime_version -> {\"MIME-Version\", true}\n :min_expires -> {\"Min-Expires\", true}\n :organization -> {\"Organization\", true}\n :priority -> {\"Priority\", true}\n :p_asserted_identity -> {\"P-Asserted-Identity\", true}\n :proxy_authenticate -> {\"Proxy-Authenticate\", false}\n :proxy_authorization -> {\"Proxy-Authorization\", false}\n :proxy_require -> {\"Proxy-Require\", true}\n :reason -> {\"Reason\", true}\n :record_route -> {\"Record-Route\", true}\n :reply_to -> {\"Reply-To\", true}\n :require -> {\"Require\", true}\n :retry_after -> {\"Retry-After\", true}\n :route -> {\"Route\", true}\n :server -> {\"Server\", true}\n :subject -> {\"Subject\", true}\n :supported -> {\"Supported\", true}\n :timestamp -> {\"Timestamp\", true}\n :to -> {\"To\", true}\n :unsupported -> {\"Unsupported\", true}\n :user_agent -> {\"User-Agent\", true}\n :via -> {\"Via\", true}\n :warning -> {\"Warning\", true}\n :www_authenticate -> {\"WWW-Authenticate\", false}\n other -> {other, true}\n end\n\n if multiple do\n [name, \": \", do_header_values(value, []), \"\\r\\n\"]\n else\n do_one_per_line(name, value)\n end\n end\n\n defp do_header_values([], values), do: values |> Enum.reverse()\n\n defp do_header_values([head | tail], values),\n do: do_header_values(tail, do_join(do_header_value(head), values, \", \"))\n\n defp do_header_values(value, _), do: do_header_value(value)\n\n defp do_header_value(value) when is_binary(value), do: value\n\n defp do_header_value(value) when is_integer(value), do: Integer.to_string(value)\n\n defp do_header_value({sequence, method}) when is_integer(sequence),\n do: [Integer.to_string(sequence), \" \", upcase_atom_or_string(method)]\n\n defp do_header_value({major, minor})\n when is_integer(major) and is_integer(minor),\n do: [Integer.to_string(major), \".\", Integer.to_string(minor)]\n\n defp do_header_value({token, %{} = parameters}) when is_binary(token),\n do: [token, do_parameters(parameters)]\n\n defp do_header_value({{type, subtype}, %{} = parameters})\n when is_binary(type) and is_binary(subtype),\n do: [type, \"\/\", subtype, do_parameters(parameters)]\n\n defp do_header_value({display_name, %URI{} = uri, %{} = parameters})\n when is_binary(display_name) do\n [\n if(display_name == \"\", do: \"\", else: [\"\\\"\", display_name, \"\\\" \"]),\n \"<\",\n URI.to_string(uri),\n \">\",\n do_parameters(parameters)\n ]\n end\n\n defp do_header_value({delta_seconds, comment, %{} = parameters})\n when is_integer(delta_seconds) and is_binary(comment) do\n [\n Integer.to_string(delta_seconds),\n if(comment != \"\", do: [\" (\", comment, \") \"], else: \"\"),\n do_parameters(parameters)\n ]\n end\n\n defp do_header_value({timestamp, delay})\n when is_float(timestamp) and is_float(delay) do\n [Float.to_string(timestamp), if(delay > 0, do: [\" \", Float.to_string(delay)], else: \"\")]\n end\n\n defp do_header_value({{major, minor}, protocol, {host, port}, %{} = parameters})\n when is_integer(major) and is_integer(minor) and\n is_binary(host) and is_integer(port) do\n [\n \"SIP\/\",\n Integer.to_string(major),\n \".\",\n Integer.to_string(minor),\n \"\/\",\n upcase_atom_or_string(protocol),\n \" \",\n host,\n if(port > 0, do: [\":\", Integer.to_string(port)], else: \"\"),\n do_parameters(parameters)\n ]\n end\n\n defp do_header_value({code, agent, text})\n when is_integer(code) and is_binary(agent) and is_binary(text) do\n [Integer.to_string(code), \" \", agent, \" \\\"\", text, \"\\\"\"]\n end\n\n defp do_header_value(%NaiveDateTime{} = value) do\n day_of_week =\n case Date.day_of_week(NaiveDateTime.to_date(value)) do\n 1 -> \"Mon\"\n 2 -> \"Tue\"\n 3 -> \"Wed\"\n 4 -> \"Thu\"\n 5 -> \"Fri\"\n 6 -> \"Sat\"\n 7 -> \"Sun\"\n end\n\n month =\n case value.month do\n 1 -> \"Jan\"\n 2 -> \"Feb\"\n 3 -> \"Mar\"\n 4 -> \"Apr\"\n 5 -> \"May\"\n 6 -> \"Jun\"\n 7 -> \"Jul\"\n 8 -> \"Aug\"\n 9 -> \"Sep\"\n 10 -> \"Oct\"\n 11 -> \"Nov\"\n 12 -> \"Dec\"\n end\n\n # Microsecond is explicitly removed here, as the RFC 3261 does not define\n # it. Therefore, while it is accepted, it won't be forwarded.\n [\n day_of_week,\n \", \",\n String.pad_leading(Integer.to_string(value.day), 2, \"0\"),\n \" \",\n month,\n \" \",\n Integer.to_string(value.year),\n \" \",\n String.pad_leading(Integer.to_string(value.hour), 2, \"0\"),\n \":\",\n String.pad_leading(Integer.to_string(value.minute), 2, \"0\"),\n \":\",\n String.pad_leading(Integer.to_string(value.second), 2, \"0\"),\n \" GMT\"\n ]\n end\n\n defp do_one_per_line(name, %{} = value),\n do: [name, \": \", do_one_per_line_value(value), \"\\r\\n\"]\n\n defp do_one_per_line(name, values) when is_list(values),\n do: do_one_per_line(name, values |> Enum.reverse(), [])\n\n defp do_one_per_line(_, [], result), do: result\n\n defp do_one_per_line(name, [head | tail], result),\n do: do_one_per_line(name, tail, [name, \": \", do_one_per_line_value(head), \"\\r\\n\" | result])\n\n defp do_one_per_line_value(%{} = parameters),\n do: do_one_per_line_value(Map.to_list(parameters), [])\n\n defp do_one_per_line_value({scheme, %{} = parameters}),\n do: [scheme, \" \", do_auth_parameters(parameters)]\n\n defp do_one_per_line_value([], result), do: result\n\n defp do_one_per_line_value([{name, value} | tail], result) do\n do_one_per_line_value(tail, do_join([name, \"=\", value], result, \", \"))\n end\n\n defp do_parameters(%{} = parameters),\n do: do_parameters(Map.to_list(parameters), [])\n\n defp do_parameters([], result), do: result\n\n defp do_parameters([{name, \"\"} | tail], result),\n do: do_parameters(tail, [\";\", name | result])\n\n defp do_parameters([{name, value} | tail], result),\n do: do_parameters(tail, [\";\", name, \"=\", value | result])\n\n defp do_join(head, [], _joiner), do: [head]\n defp do_join(head, tail, joiner), do: [head, joiner | tail]\n\n defp upcase_atom_or_string(s),\n do: if(is_atom(s), do: String.upcase(Atom.to_string(s)), else: s)\n\n defp do_auth_parameters(%{} = parameters),\n do: do_auth_parameters(Map.to_list(parameters), [])\n\n defp do_auth_parameters([], result), do: result |> Enum.reverse()\n\n defp do_auth_parameters([{name, value} | tail], [])\n when name in [\"username\", \"realm\", \"nonce\", \"uri\", \"response\", \"cnonce\", \"opaque\"],\n do: do_auth_parameters(tail, [[name, \"=\\\"\", value, \"\\\"\"]])\n\n defp do_auth_parameters([{name, value} | tail], []),\n do: do_auth_parameters(tail, [[name, \"=\", value]])\n\n defp do_auth_parameters([{name, value} | tail], result)\n when name in [\"username\", \"realm\", \"nonce\", \"uri\", \"response\", \"cnonce\", \"opaque\"],\n do: do_auth_parameters(tail, [[\",\", name, \"=\\\"\", value, \"\\\"\"] | result])\n\n defp do_auth_parameters([{name, value} | tail], result),\n do: do_auth_parameters(tail, [[\",\", name, \"=\", value] | result])\n\n @doc \"\"\"\n Checks whether a message is valid.\n \"\"\"\n @spec valid?(t) :: boolean\n def valid?(message) do\n case validate(message) do\n :ok -> true\n _ -> false\n end\n end\n\n @doc \"\"\"\n Checks whether a message is valid, also checking if it corresponds to the\n indicated incoming transport tuple `{protocol, host, port}`.\n \"\"\"\n @spec valid?(t, {protocol, host :: String.t(), port :: integer}) :: boolean\n def valid?(message, from) do\n case validate(message, from) do\n :ok -> true\n _ -> false\n end\n end\n\n @doc \"\"\"\n Validates if a message is valid, returning errors if found.\n \"\"\"\n @spec validate(t) :: :ok | {:error, reason :: term}\n def validate(message) do\n validators = [\n &has_valid_start_line_version\/1,\n &has_required_headers\/1,\n &has_valid_body\/1,\n &has_tag_on(&1, :from)\n ]\n\n validators =\n if request?(message) do\n validators ++\n [\n &has_matching_cseq\/1\n ]\n else\n validators\n end\n\n do_validate(validators, message)\n end\n\n defp do_validate([], _message), do: :ok\n\n defp do_validate([f | rest], message) do\n case f.(message) do\n :ok -> do_validate(rest, message)\n other -> other\n end\n end\n\n defp has_valid_start_line_version(message) do\n %{version: version} = message.start_line\n\n if version == {2, 0} do\n :ok\n else\n {:error, \"invalid status line version #{inspect(version)}\"}\n end\n end\n\n defp has_required_headers(message) do\n required = [:to, :from, :cseq, :call_id, :via]\n\n missing_headers =\n for header <- required, not (message |> has_header?(header)) do\n header\n end\n\n if Enum.empty?(missing_headers) do\n :ok\n else\n {:error, \"missing headers: #{inspect(missing_headers)}\"}\n end\n end\n\n defp has_valid_body(message) do\n case message.headers do\n %{content_length: content_length} ->\n cond do\n message.body != nil and byte_size(message.body) == content_length ->\n :ok\n\n message.body == nil and content_length == 0 ->\n :ok\n\n true ->\n {:error, \"Content-Length and message body size do not match\"}\n end\n\n _otherwise ->\n cond do\n message.body == nil ->\n :ok\n\n message.headers.via |> List.last() |> elem(1) == :udp ->\n # It is OK to not have Content-Length in an UDP message\n :ok\n\n true ->\n {:error, \"No Content-Length header, but body is not nil\"}\n end\n end\n end\n\n defp has_tag_on(message, header) do\n {_display_name, _uri, params} = message.headers[header]\n\n case params do\n %{\"tag\" => value} ->\n if String.length(value) > 0 do\n :ok\n else\n {:error, \"empty #{inspect(header)} tag\"}\n end\n\n _otherwise ->\n {:error, \"#{inspect(header)} does not have tag\"}\n end\n end\n\n defp has_matching_cseq(request) do\n method = request.start_line.method\n\n case request.headers.cseq do\n {_sequence, ^method} ->\n :ok\n\n _ ->\n {:error, \"CSeq method and request method do no match\"}\n end\n end\n\n @doc \"\"\"\n Validates if a message is valid, also checking if it corresponds to the\n indicated incoming transport tuple `{protocol, host, port}`. It returns the\n error if found.\n \"\"\"\n @spec validate(t, {protocol, host :: String.t(), port :: integer}) ::\n :ok | {:error, reason :: term}\n def validate(message, from) do\n case validate(message) do\n :ok ->\n validators = [\n &has_valid_via(&1, from)\n ]\n\n do_validate(validators, message)\n\n other ->\n other\n end\n end\n\n defp has_valid_via(message, {protocol1, _ip, _port}) do\n {_version, protocol2, _sent_by, _params} = hd(message.headers.via)\n\n if protocol1 != protocol2 do\n {:error, \"Via protocol doesn't match transport protocol\"}\n else\n has_valid_via(message, message.headers.via)\n end\n end\n\n defp has_valid_via(_, []), do: :ok\n\n defp has_valid_via(message, [via | rest]) do\n {version, _protocol, _sent_by, params} = via\n\n if version != {2, 0} do\n {:error, \"Via version #{inspect(version)} is unknown\"}\n else\n case params do\n %{\"branch\" => branch} ->\n if branch |> String.starts_with?(\"z9hG4bK\") do\n has_valid_via(message, rest)\n else\n {:error, \"Via branch doesn't start with the magic cookie\"}\n end\n\n _otherwise ->\n {:error, \"Via header doesn't have branch parameter\"}\n end\n end\n end\n\n @doc \"\"\"\n Extracts the remote address and port from an incoming request inspecting the\n `Via` header. If `;rport` is present, use it instead of the topmost `Via`\n port, if `;received` is present, use it instead of the topmost `Via` host.\n \"\"\"\n @spec get_remote(request) ::\n {:ok, {protocol :: atom | binary, host :: binary, port :: integer}}\n | {:error, reason :: term}\n def get_remote(%__MODULE__{start_line: %RequestLine{}, headers: %{via: [topmost_via | _]}}) do\n {_version, protocol, {host, port}, params} = topmost_via\n\n host =\n case params do\n %{\"received\" => received} ->\n received\n\n _otherwise ->\n host\n end\n\n port =\n case params do\n %{\"rport\" => rport} ->\n rport |> String.to_integer()\n\n _otherwise ->\n port\n end\n\n {:ok, {protocol, host, port}}\n end\n\n def get_remote(%__MODULE__{start_line: %RequestLine{}}),\n do: {:error, \"Missing Via header\"}\n\n def get_remote(%__MODULE__{}),\n do: {:error, \"Not a request\"}\n\n @doc \"\"\"\n Fetches the value for a specific `key` in the given `message`.\n \"\"\"\n def fetch(%__MODULE__{} = message, key), do: Map.fetch(message, key)\n\n @doc \"\"\"\n Gets the value from key and updates it, all in one pass.\n\n About the same as `Map.get_and_update\/3` except that this function actually\n does not remove the key from the struct case the passed function returns\n `:pop`; it puts `nil` for `:start_line`, `:body` and `:target` ands `%{}` for\n the `:headers` key.\n \"\"\"\n def get_and_update(%__MODULE__{} = message, key, fun)\n when key in [:start_line, :headers, :body, :target] do\n current = message[key]\n\n case fun.(current) do\n {get, update} ->\n {get, message |> Map.put(key, update)}\n\n :pop ->\n {current, pop(message, key)}\n\n other ->\n raise \"the given function must return a two-element tuple or :pop, got: #{inspect(other)}\"\n end\n end\n\n @doc \"\"\"\n Returns and removes the value associated with `key` in `message`.\n\n About the same as `Map.pop\/3` except that this function actually does not\n remove the key from the struct case the passed function returns `:pop`; it\n puts `nil` for `:start_line`, `:body` and `:target` ands `%{}` for the\n `:headers` key.\n \"\"\"\n def pop(message, key, default \\\\ nil)\n\n def pop(%__MODULE__{} = message, :headers, default) when default == nil or is_map(default),\n do: {message[:headers], %{message | headers: %{}}}\n\n def pop(%__MODULE__{}, :headers, _),\n do: raise(\"invalid :default, :headers must be nil or a map\")\n\n def pop(%__MODULE__{} = message, key, nil) when key in [:start_line, :body, :target],\n do: {message[key], %{message | key => nil}}\n\n def pop(%__MODULE__{} = message, :start_line, %RequestLine{} = start_line),\n do: {message[:start_line], %{message | start_line: start_line}}\n\n def pop(%__MODULE__{} = message, :start_line, %StatusLine{} = start_line),\n do: {message[:start_line], %{message | start_line: start_line}}\n\n def pop(%__MODULE__{}, :start_line, _),\n do: raise(\"invalid :default, :start_line must be nil, RequestLine or StatusLine\")\n\n def pop(%__MODULE__{} = message, :body, default) when is_binary(default),\n do: {message[:body], %{message | body: default}}\n\n def pop(%__MODULE__{}, :body, _),\n do: raise(\"invalid :default, :body must be nil or binary\")\n\n def pop(%__MODULE__{} = message, :target, {_protocol, _host, _port} = default),\n do: {message[:target], %{message | target: default}}\n\n def pop(%__MODULE__{}, :target, _),\n do: raise(\"invalid :default, :target must be nil or {protocol, host, port} tuple\")\nend\n\ndefimpl String.Chars, for: Sippet.Message do\n def to_string(%Sippet.Message{} = message),\n do: message |> Sippet.Message.to_iodata() |> IO.iodata_to_binary()\nend\n","old_contents":"defmodule Sippet.Message do\n @moduledoc \"\"\"\n Message primitive for composing SIP messages.\n Build a SIP message with the `Sippet.Message` struct.\n\n request =\n Sippet.Message.build_request(\"INVITE\", \"sip:joe@example.com\")\n |> Sippet.Message.put_header(:to,\n {\"\", Sippet.URI.parse!(\"sip:joe@example.com\"), %{}})\n ...\n \"\"\"\n\n @behaviour Access\n\n alias Sippet.URI, as: URI\n alias Sippet.Message.RequestLine, as: RequestLine\n alias Sippet.Message.StatusLine, as: StatusLine\n\n defstruct start_line: nil,\n headers: %{},\n body: nil,\n target: nil\n\n @type uri :: URI.t()\n\n @type method :: atom | binary\n\n @type header :: atom | binary\n\n @type protocol :: atom | binary\n\n @type token :: binary\n\n @type params :: %{binary => binary}\n\n @type token_params ::\n {token :: binary, params}\n\n @type type_subtype_params ::\n {{type :: binary, subtype :: binary}, params}\n\n @type uri_params ::\n {display_name :: binary, uri :: URI.t(), params}\n\n @type name_uri_params ::\n {display_name :: binary, uri :: URI.t(), params}\n\n @type auth_params ::\n {scheme :: binary, params}\n\n @type via_value ::\n {{major :: integer, minor :: integer}, protocol, {host :: binary, port :: integer},\n params}\n\n @type headers :: %{\n optional(:accept) => [type_subtype_params, ...],\n optional(:accept_encoding) => [token_params, ...],\n optional(:accept_language) => [token_params, ...],\n optional(:alert_info) => [uri_params, ...],\n optional(:allow) => [token, ...],\n optional(:authentication_info) => params,\n optional(:authorization) => [auth_params, ...],\n required(:call_id) => token,\n optional(:call_info) => [uri_params, ...],\n optional(:contact) => <<_::1>> | [name_uri_params, ...],\n optional(:content_disposition) => token_params,\n optional(:content_encoding) => [token, ...],\n optional(:content_language) => [token, ...],\n optional(:content_length) => integer,\n optional(:content_type) => type_subtype_params,\n required(:cseq) => {integer, method},\n optional(:date) => NaiveDateTime.t(),\n optional(:error_info) => [uri_params, ...],\n optional(:expires) => integer,\n required(:from) => name_uri_params,\n optional(:in_reply_to) => [token, ...],\n required(:max_forwards) => integer,\n optional(:mime_version) => {major :: integer, minor :: integer},\n optional(:min_expires) => integer,\n optional(:organization) => binary,\n optional(:priority) => token,\n optional(:proxy_authenticate) => [auth_params, ...],\n optional(:proxy_authorization) => [auth_params, ...],\n optional(:proxy_require) => [token, ...],\n optional(:reason) => {binary, params},\n optional(:record_route) => [name_uri_params, ...],\n optional(:reply_to) => name_uri_params,\n optional(:require) => [token, ...],\n optional(:retry_after) => {integer, binary, params},\n optional(:route) => [name_uri_params, ...],\n optional(:server) => binary,\n optional(:subject) => binary,\n optional(:supported) => [token, ...],\n optional(:timestamp) => {timestamp :: float, delay :: float},\n required(:to) => name_uri_params,\n optional(:unsupported) => [token, ...],\n optional(:user_agent) => binary,\n required(:via) => [via_value, ...],\n optional(:warning) => [{integer, agent :: binary, binary}, ...],\n optional(:www_authenticate) => [auth_params, ...],\n optional(binary) => [binary, ...]\n }\n\n @type single_value ::\n binary\n | integer\n | {sequence :: integer, method}\n | {major :: integer, minor :: integer}\n | token_params\n | type_subtype_params\n | uri_params\n | name_uri_params\n | {delta_seconds :: integer, comment :: binary, params}\n | {timestamp :: integer, delay :: integer}\n | <<_::1>>\n | [name_uri_params, ...]\n | NaiveDateTime.t()\n\n @type multiple_value ::\n token_params\n | type_subtype_params\n | uri_params\n | name_uri_params\n | via_value\n | auth_params\n | params\n | {code :: integer, agent :: binary, text :: binary}\n\n @type value ::\n single_value\n | [multiple_value]\n\n @type t :: %__MODULE__{\n start_line: RequestLine.t() | StatusLine.t(),\n headers: %{header => value},\n body: binary | nil,\n target:\n nil\n | {\n protocol :: atom | binary,\n host :: binary,\n dport :: integer\n }\n }\n\n @type request :: %__MODULE__{\n start_line: RequestLine.t()\n }\n\n @type response :: %__MODULE__{\n start_line: StatusLine.t()\n }\n\n @external_resource protocols_path = Path.join([__DIR__, \"..\", \"..\", \"c_src\", \"protocol_list.h\"])\n\n known_protocols =\n for line <- File.stream!(protocols_path, [], :line),\n line |> String.starts_with?(\"SIP_PROTOCOL\") do\n [_, protocol] = Regex.run(~r\/SIP_PROTOCOL\\(([^,]+)\\)\/, line)\n atom = protocol |> String.downcase() |> String.to_atom()\n\n defp string_to_protocol(unquote(protocol)),\n do: unquote(atom)\n\n protocol\n end\n\n defp string_to_protocol(string), do: string\n\n @doc \"\"\"\n Returns a list of all known transport protocols, as a list of uppercase\n strings.\n\n ## Example:\n\n iex> Sippet.Message.known_protocols()\n [\"AMQP\", \"DCCP\", \"DTLS\", \"SCTP\", \"STOMP\", \"TCP\", \"TLS\", \"UDP\", \"WS\", \"WSS\"]\n \"\"\"\n @spec known_protocols() :: [String.t()]\n def known_protocols(), do: unquote(known_protocols)\n\n @doc \"\"\"\n Converts a string representing a known protocol into an atom, otherwise as an\n uppercase string.\n\n ## Example:\n\n iex> Sippet.Message.to_protocol(\"UDP\")\n :udp\n\n iex> Sippet.Message.to_protocol(\"uDp\")\n :udp\n\n iex> Sippet.Message.to_protocol(\"aaa\")\n \"AAA\"\n\n \"\"\"\n @spec to_protocol(String.t()) :: protocol\n def to_protocol(string), do: string_to_protocol(string |> String.upcase())\n\n @external_resource methods_path = Path.join([__DIR__, \"..\", \"..\", \"c_src\", \"method_list.h\"])\n\n known_methods =\n for line <- File.stream!(methods_path, [], :line),\n line |> String.starts_with?(\"SIP_METHOD\") do\n [_, method] = Regex.run(~r\/SIP_METHOD\\(([^,]+)\\)\/, line)\n atom = method |> String.downcase() |> String.to_atom()\n\n defp string_to_method(unquote(method)),\n do: unquote(atom)\n\n method\n end\n\n defp string_to_method(string), do: string\n\n @doc \"\"\"\n Returns a list of all known methods, as a list of uppercase strings.\n\n ## Example:\n\n iex> Sippet.Message.known_methods()\n [\"ACK\", \"BYE\", \"CANCEL\", \"INFO\", \"INVITE\", \"MESSAGE\", \"NOTIFY\", \"OPTIONS\",\n \"PRACK\", \"PUBLISH\", \"PULL\", \"PUSH\", \"REFER\", \"REGISTER\", \"STORE\", \"SUBSCRIBE\",\n \"UPDATE\"]\n \"\"\"\n @spec known_methods() :: [String.t()]\n def known_methods(), do: unquote(known_methods)\n\n @doc \"\"\"\n Converts a string representing a known method into an atom, otherwise as an\n uppercase string.\n\n ## Example:\n\n iex> Sippet.Message.to_method(\"INVITE\")\n :invite\n\n iex> Sippet.Message.to_method(\"InViTe\")\n :invite\n\n iex> Sippet.Message.to_method(\"aaa\")\n \"AAA\"\n\n \"\"\"\n @spec to_method(String.t()) :: method\n def to_method(string), do: string_to_method(string |> String.upcase())\n\n @doc \"\"\"\n Returns a SIP request created from its basic elements.\n\n If the `method` is a binary and is a known method, it will be converted to\n a lowercase atom; otherwise, it will be stored as an uppercase string. If\n `method` is an atom, it will be just kept.\n\n If the `request_uri` is a binary, it will be parsed as a `Sippet.URI` struct.\n Otherwise, if it's already a `Sippet.URI`, it will be stored unmodified.\n\n The newly created struct has an empty header map, and the body is `nil`.\n\n ## Examples:\n\n iex> req1 = Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n %Sippet.Message{body: nil, headers: %{},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n iex> req2 = Sippet.Message.build_request(\"INVITE\", \"sip:foo@bar.com\")\n iex> request_uri = Sippet.URI.parse!(\"sip:foo@bar.com\")\n iex> req3 = Sippet.Message.build_request(\"INVITE\", request_uri)\n iex> req1 == req2 and req2 == req3\n true\n\n \"\"\"\n @spec build_request(method, uri | binary) :: request\n def build_request(method, request_uri)\n\n def build_request(method, request_uri) when is_binary(method) do\n method =\n if String.upcase(method) in known_methods() do\n method |> String.downcase() |> String.to_atom()\n else\n method |> String.upcase()\n end\n\n do_build_request(method, request_uri)\n end\n\n def build_request(method, request_uri) when is_atom(method),\n do: do_build_request(method, request_uri)\n\n defp do_build_request(method, request_uri),\n do: %__MODULE__{start_line: RequestLine.new(method, request_uri)}\n\n @doc \"\"\"\n Returns a SIP response created from its basic elements.\n\n The `status` parameter can be a `Sippet.Message.StatusLine` struct or an\n integer in the range `100..699` representing the SIP response status code.\n In the latter case, a default reason phrase will be obtained from a default\n set; if there's none, then an exception will be raised.\n\n ## Examples:\n\n iex> resp1 = Sippet.Message.build_response 200\n %Sippet.Message{body: nil, headers: %{},\n start_line: %Sippet.Message.StatusLine{reason_phrase: \"OK\", status_code: 200,\n version: {2, 0}}, target: nil}\n iex> status_line = Sippet.Message.StatusLine.new(200)\n iex> resp2 = status_line |> Sippet.Message.build_response\n iex> resp1 == resp2\n true\n\n \"\"\"\n @spec build_response(100..699 | StatusLine.t()) :: response | no_return\n def build_response(status)\n\n def build_response(%StatusLine{} = status_line),\n do: %__MODULE__{start_line: status_line}\n\n def build_response(status_code) when is_integer(status_code),\n do: build_response(StatusLine.new(status_code))\n\n @doc \"\"\"\n Returns a SIP response with a custom reason phrase.\n\n The `status_code` should be an integer in the range `100..699` representing\n the SIP status code, and `reason_phrase` a binary representing the reason\n phrase text.\n\n iex> Sippet.Message.build_response 400, \"Bad Lorem Ipsum\"\n %Sippet.Message{body: nil, headers: %{},\n start_line: %Sippet.Message.StatusLine{reason_phrase: \"Bad Lorem Ipsum\",\n status_code: 400, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec build_response(100..699, String.t()) :: response\n def build_response(status_code, reason_phrase)\n when is_integer(status_code) and is_binary(reason_phrase),\n do: build_response(StatusLine.new(status_code, reason_phrase))\n\n @doc ~S'''\n Returns a response created from a request, using a given status code.\n\n The `request` should be a valid SIP request, or an exception will be thrown.\n\n The `status` parameter can be a `Sippet.Message.StatusLine` struct or an\n integer in the range `100..699` representing the SIP response status code.\n In the latter case, a default reason phrase will be obtained from a default\n set; if there's none, then an exception will be raised.\n\n ## Example:\n\n request =\n \"\"\"\n REGISTER sips:ss2.biloxi.example.com SIP\/2.0\n Via: SIP\/2.0\/TLS client.biloxi.example.com:5061;branch=z9hG4bKnashds7\n Max-Forwards: 70\n From: Bob ;tag=a73kszlfl\n To: Bob \n Call-ID: 1j9FpLxk3uxtm8tn@biloxi.example.com\n CSeq: 1 REGISTER\n Contact: \n Content-Length: 0\n \"\"\" |> Sippet.Message.parse!()\n request |> Sippet.Message.to_response(200) |> IO.puts\n SIP\/2.0 200 OK\n Via: SIP\/2.0\/TLS client.biloxi.example.com:5061;branch=z9hG4bKnashds7\n To: \"Bob\" ;tag=K2fizKkV\n From: \"Bob\" ;tag=a73kszlfl\n CSeq: 1 REGISTER\n Content-Length: 0\n Call-ID: 1j9FpLxk3uxtm8tn@biloxi.example.com\n\n\n :ok\n\n '''\n @spec to_response(request, integer | StatusLine.t()) :: response | no_return\n def to_response(request, status)\n\n def to_response(request, status_code) when is_integer(status_code),\n do: to_response(request, StatusLine.new(status_code))\n\n def to_response(\n %__MODULE__{start_line: %RequestLine{}} = request,\n %StatusLine{} = status_line\n ) do\n response =\n status_line\n |> build_response()\n |> put_header(:via, get_header(request, :via))\n |> put_header(:from, get_header(request, :from))\n |> put_header(:to, get_header(request, :to))\n |> put_header(:call_id, get_header(request, :call_id))\n |> put_header(:cseq, get_header(request, :cseq))\n\n response =\n if status_line.status_code > 100 and\n not Map.has_key?(elem(response.headers.to, 2), \"tag\") do\n {display_name, uri, params} = response.headers.to\n params = Map.put(params, \"tag\", create_tag())\n response |> put_header(:to, {display_name, uri, params})\n else\n response\n end\n\n if has_header?(request, :record_route) do\n response |> put_header(:record_route, get_header(request, :record_route))\n else\n response\n end\n end\n\n @doc ~S'''\n Returns a response created from a request, using a given status code and a\n custom reason phrase.\n\n The `request` should be a valid SIP request, or an exception will be thrown.\n\n The `status_code` parameter should be an integer in the range `100..699`\n representing the SIP response status code. A default reason phrase will be\n obtained from a default set; if there's none, then an exception will be\n raised.\n\n The `reason_phrase` can be any textual representation of the reason phrase\n the application needs to generate, in binary.\n\n ## Example:\n\n request =\n \"\"\"\n REGISTER sips:ss2.biloxi.example.com SIP\/2.0\n Via: SIP\/2.0\/TLS client.biloxi.example.com:5061;branch=z9hG4bKnashds7\n Max-Forwards: 70\n From: Bob ;tag=a73kszlfl\n To: Bob \n Call-ID: 1j9FpLxk3uxtm8tn@biloxi.example.com\n CSeq: 1 REGISTER\n Contact: \n Content-Length: 0\n \"\"\" |> Sippet.Message.parse!()\n request |> Sippet.Message.to_response(400, \"Bad Lorem Ipsum\") |> IO.puts\n SIP\/2.0 400 Bad Lorem Ipsum\n Via: SIP\/2.0\/TLS client.biloxi.example.com:5061;branch=z9hG4bKnashds7\n To: \"Bob\" ;tag=K2fizKkV\n From: \"Bob\" ;tag=a73kszlfl\n CSeq: 1 REGISTER\n Content-Length: 0\n Call-ID: 1j9FpLxk3uxtm8tn@biloxi.example.com\n\n\n :ok\n\n '''\n @spec to_response(request, integer, String.t()) :: response\n def to_response(request, status_code, reason_phrase)\n when is_integer(status_code) and is_binary(reason_phrase),\n do: to_response(request, StatusLine.new(status_code, reason_phrase))\n\n @doc \"\"\"\n Creates a local tag (48-bit random string, 8 characters long).\n\n ## Example:\n\n Sippet.Message.create_tag\n \"lnTMo9Zn\"\n\n \"\"\"\n @spec create_tag() :: binary\n def create_tag(), do: do_random_string(48)\n\n defp do_random_string(length) do\n round(Float.ceil(length \/ 8))\n |> :crypto.strong_rand_bytes()\n |> Base.url_encode64(padding: false)\n end\n\n @doc \"\"\"\n Returns the RFC 3261 compliance magic cookie, inserted in via-branch\n parameters.\n\n ## Example:\n\n iex> Sippet.Message.magic_cookie\n \"z9hG4bK\"\n\n \"\"\"\n @spec magic_cookie() :: binary\n def magic_cookie(), do: \"z9hG4bK\"\n\n @doc \"\"\"\n Creates an unique local branch (72-bit random string, 7+12 characters long).\n\n ## Example:\n\n Sippet.Message.create_branch\n \"z9hG4bKuQpiub9h7fBb\"\n\n \"\"\"\n @spec create_branch() :: binary\n def create_branch(), do: magic_cookie() <> do_random_string(72)\n\n @doc \"\"\"\n Creates an unique Call-ID (120-bit random string, 20 characters long).\n\n ## Example\n\n Sippet.create_call_id\n \"NlV4TfQwkmPlNJkyHPpF\"\n\n \"\"\"\n @spec create_call_id() :: binary\n def create_call_id(), do: do_random_string(120)\n\n @doc \"\"\"\n Shortcut to check if the message is a request.\n\n ## Examples:\n\n iex> req = Sippet.Message.build_request :invite, \"sip:foo@bar.com\"\n iex> req |> Sippet.Message.request?\n true\n\n \"\"\"\n @spec request?(t) :: boolean\n def request?(%__MODULE__{start_line: %RequestLine{}} = _), do: true\n def request?(_), do: false\n\n @doc \"\"\"\n Shortcut to check if the message is a response.\n\n ## Examples:\n\n iex> resp = Sippet.Message.build_response 200\n iex> resp |> Sippet.Message.response?\n true\n\n \"\"\"\n @spec response?(t) :: boolean\n def response?(%__MODULE__{start_line: %StatusLine{}} = _), do: true\n def response?(_), do: false\n\n @doc \"\"\"\n Returns whether a given `header` exists in the given `message`.\n\n ## Examples:\n\n iex> request =\n ...> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header(:cseq, {1, :invite})\n iex> request |> Sippet.Message.has_header?(:cseq)\n true\n\n \"\"\"\n @spec has_header?(t, header) :: boolean\n def has_header?(message, header),\n do: Map.has_key?(message.headers, header)\n\n @doc \"\"\"\n Puts the `value` under `header` on the `message`.\n\n If the header already exists, it will be overridden.\n\n ## Examples:\n\n iex> request = Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n iex> request |> Sippet.Message.put_header(:cseq, {1, :invite})\n %Sippet.Message{body: nil, headers: %{cseq: {1, :invite}},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec put_header(t, header, value) :: t\n def put_header(message, header, value),\n do: %{message | headers: Map.put(message.headers, header, value)}\n\n @doc \"\"\"\n Puts the `value` under `header` on the `message` unless the `header` already\n exists.\n\n ## Examples:\n\n iex> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_new_header(:max_forwards, 70)\n ...> |> Sippet.Message.put_new_header(:max_forwards, 1)\n %Sippet.Message{body: nil, headers: %{max_forwards: 70},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec put_new_header(t, header, value) :: t\n def put_new_header(message, header, value) do\n case has_header?(message, header) do\n true -> message\n false -> put_header(message, header, value)\n end\n end\n\n @doc \"\"\"\n Evaluates `fun` and puts the result under `header` in `message` unless\n `header` is already present.\n\n This function is useful in case you want to compute the value to put under\n `header` only if `header` is not already present (e.g., the value is\n expensive to calculate or generally difficult to setup and teardown again).\n\n ## Examples:\n\n iex> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_new_lazy_header(:max_forwards, fn -> 70 end)\n ...> |> Sippet.Message.put_new_lazy_header(:max_forwards, fn -> 1 end)\n %Sippet.Message{body: nil, headers: %{max_forwards: 70},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec put_new_lazy_header(t, header, (() -> value)) :: t\n def put_new_lazy_header(message, header, fun) when is_function(fun, 0) do\n case has_header?(message, header) do\n true -> message\n false -> put_header(message, header, fun.())\n end\n end\n\n @doc \"\"\"\n Puts the `value` under `header` on the `message`, as front element.\n\n If the parameter `value` is `nil`, then the empty list will be prefixed to\n the `header`.\n\n ## Examples:\n\n iex> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header_front(:content_language, \"de-DE\")\n ...> |> Sippet.Message.put_header_front(:content_language, \"en-US\")\n %Sippet.Message{body: nil, headers: %{content_language: [\"en-US\", \"de-DE\"]},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec put_header_front(t, header, multiple_value) :: t\n def put_header_front(message, header, value) do\n existing = get_header(message, header, [])\n\n new_list =\n case value do\n nil -> existing\n _ -> [value | existing]\n end\n\n put_header(message, header, new_list)\n end\n\n @doc \"\"\"\n Puts the `value` under `header` on the `message`, as last element.\n\n If the parameter `value` is `nil`, then the empty list will be appended to\n the `header`.\n\n ## Examples:\n\n iex> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header_back(:content_language, \"en-US\")\n ...> |> Sippet.Message.put_header_back(:content_language, \"de-DE\")\n %Sippet.Message{body: nil, headers: %{content_language: [\"en-US\", \"de-DE\"]},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec put_header_back(t, header, multiple_value) :: t\n def put_header_back(message, header, value) do\n existing = get_header(message, header, [])\n\n new_list =\n case value do\n nil -> existing\n _ -> List.foldr(existing, [value], fn x, acc -> [x | acc] end)\n end\n\n put_header(message, header, new_list)\n end\n\n @doc \"\"\"\n Deletes all `header` values in `message`.\n\n ## Examples:\n\n iex> request =\n ...> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header(:content_language, [\"en-US\", \"de-DE\"])\n ...> |> Sippet.Message.put_header(:max_forwards, 70)\n iex> request |> Sippet.Message.delete_header(:content_language)\n %Sippet.Message{body: nil, headers: %{max_forwards: 70},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec delete_header(t, header) :: t\n def delete_header(message, header) do\n %{message | headers: Map.delete(message.headers, header)}\n end\n\n @doc \"\"\"\n Deletes the first value of `header` in `message`.\n\n ## Examples:\n\n iex> request =\n ...> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header(:content_language, [\"en-US\", \"de-DE\"])\n ...> |> Sippet.Message.put_header(:max_forwards, 70)\n iex> request |> Sippet.Message.delete_header_front(:content_language)\n %Sippet.Message{body: nil,\n headers: %{content_language: [\"de-DE\"], max_forwards: 70},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec delete_header_front(t, header) :: t\n def delete_header_front(message, header) do\n case get_header(message, header) do\n nil -> message\n [_] -> delete_header(message, header)\n [_ | tail] -> put_header(message, header, tail)\n end\n end\n\n @doc \"\"\"\n Deletes the last value of `header` in `message`.\n\n ## Examples:\n\n iex> request =\n ...> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header(:content_language, [\"en-US\", \"de-DE\"])\n ...> |> Sippet.Message.put_header(:max_forwards, 70)\n iex> request |> Sippet.Message.delete_header_back(:content_language)\n %Sippet.Message{body: nil,\n headers: %{content_language: [\"en-US\"], max_forwards: 70},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec delete_header_back(t, header) :: t\n def delete_header_back(message, header) do\n case get_header(message, header) do\n nil -> message\n [_] -> delete_header(message, header)\n [_ | _] = values -> put_header(message, header, do_remove_last(values))\n end\n end\n\n defp do_remove_last(list) when is_list(list) do\n [_ | tail] = Enum.reverse(list)\n Enum.reverse(tail)\n end\n\n @doc \"\"\"\n Drops all given `headers` from `message`.\n\n ## Examples:\n\n iex> request =\n ...> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header(:content_language, [\"en-US\", \"de-DE\"])\n ...> |> Sippet.Message.put_header(:max_forwards, 70)\n iex> request |> Sippet.Message.drop_headers([:content_language, :max_forwards])\n %Sippet.Message{body: nil, headers: %{},\n start_line: %Sippet.Message.RequestLine{method: :invite,\n request_uri: %Sippet.URI{authority: \"foo@bar.com\", headers: nil,\n host: \"bar.com\", parameters: nil, port: 5060, scheme: \"sip\",\n userinfo: \"foo\"}, version: {2, 0}}, target: nil}\n\n \"\"\"\n @spec drop_headers(t, [header]) :: t\n def drop_headers(message, headers),\n do: %{message | headers: Map.drop(message.headers, headers)}\n\n @doc \"\"\"\n Fetches all values for a specific `header` and returns it in a tuple.\n\n If the `header` does not exist, returns `:error`.\n\n ## Examples:\n\n iex> request =\n ...> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header(:content_language, [\"en-US\", \"de-DE\"])\n ...> |> Sippet.Message.put_header(:max_forwards, 70)\n iex> request |> Sippet.Message.fetch_header(:content_language)\n {:ok, [\"en-US\", \"de-DE\"]}\n iex> request |> Sippet.Message.fetch_header(:cseq)\n :error\n\n \"\"\"\n @spec fetch_header(t, header) :: {:ok, value} | :error\n def fetch_header(message, header),\n do: Map.fetch(message.headers, header)\n\n @doc \"\"\"\n Fetches the first value of a specific `header` and returns it in a tuple.\n\n If the `header` does not exist, or the value is not a list, returns `:error`.\n If the `header` exists but it is an empty list, returns `{:ok, nil}`.\n\n ## Examples:\n\n iex> request =\n ...> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header(:content_language, [\"en-US\", \"de-DE\"])\n ...> |> Sippet.Message.put_header(:max_forwards, 70)\n iex> request |> Sippet.Message.fetch_header_front(:content_language)\n {:ok, \"en-US\"}\n iex> request |> Sippet.Message.fetch_header_front(:max_forwards)\n :error\n iex> request |> Sippet.Message.fetch_header_front(:cseq)\n :error\n\n \"\"\"\n @spec fetch_header_front(t, header) ::\n {:ok, multiple_value} | :error\n def fetch_header_front(message, header) do\n case fetch_header(message, header) do\n {:ok, []} ->\n {:ok, nil}\n\n {:ok, [first | _]} ->\n {:ok, first}\n\n _otherwise ->\n :error\n end\n end\n\n @doc \"\"\"\n Fetches the last value of a specific `header` and returns it in a tuple.\n\n If the `header` does not exist, or the value is not a list, returns `:error`.\n If the `header` exists but it is an empty list, returns `{:ok, nil}`.\n\n ## Examples:\n\n iex> request =\n ...> Sippet.Message.build_request(:invite, \"sip:foo@bar.com\")\n ...> |> Sippet.Message.put_header(:content_language, [\"en-US\", \"de-DE\"])\n ...> |> Sippet.Message.put_header(:max_forwards, 70)\n iex> request |> Sippet.Message.fetch_header_back(:content_language)\n {:ok, \"de-DE\"}\n iex> request |> Sippet.Message.fetch_header_back(:max_forwards)\n :error\n iex> request |> Sippet.Message.fetch_header_back(:cseq)\n :error\n\n \"\"\"\n @spec fetch_header_back(t, header) :: {:ok, multiple_value} | :error\n def fetch_header_back(message, header) do\n case fetch_header(message, header) do\n {:ok, []} ->\n {:ok, nil}\n\n {:ok, [value]} ->\n {:ok, value}\n\n {:ok, [_ | rest]} ->\n {:ok, List.last(rest)}\n\n _otherwise ->\n :error\n end\n end\n\n @doc \"\"\"\n Fetches all values for a specific `header` in the given `message`, erroring\n out if `message` doesn't contain `header`.\n\n If `message` contains the given `header`, all corresponding values are\n returned in a list. If `message` doesn't contain the `header`, a `KeyError`\n exception is raised.\n \"\"\"\n @spec fetch_header!(t, header) :: value | no_return\n def fetch_header!(message, header),\n do: Map.fetch!(message.headers, header)\n\n @doc \"\"\"\n Fetches the first value of a specific `header` in the given `message`, erroring\n out if `message` doesn't contain `header`.\n\n If `message` contains the given `header`, the first value is returned, which\n may be `nil` case the values list is empty. If `message` doesn't contain the\n `header`, a `KeyError` exception is raised.\n \"\"\"\n @spec fetch_header_front!(t, header) :: multiple_value | no_return\n def fetch_header_front!(message, header) do\n values = fetch_header!(message, header)\n\n if Enum.empty?(values) do\n nil\n else\n List.first(values)\n end\n end\n\n @doc \"\"\"\n Fetches the last value of a specific `header` in the given `message`, erroring\n out if `message` doesn't contain `header`.\n\n If `message` contains the given `header`, the last value is returned, which\n may be `nil` case the values list is empty. If `message` doesn't contain the\n `header`, a `KeyError` exception is raised.\n \"\"\"\n @spec fetch_header_back!(t, header) :: multiple_value | no_return\n def fetch_header_back!(message, header) do\n values = fetch_header!(message, header)\n\n if Enum.empty?(values) do\n nil\n else\n List.last(values)\n end\n end\n\n @doc \"\"\"\n Gets all values for a specific `header` in `message`.\n\n If `header` is present in `message`, then all values are returned in a list.\n Otherwise, `default` is returned (which is `nil` unless specified otherwise).\n \"\"\"\n @spec get_header(t, header) :: value | nil\n @spec get_header(t, header, any) :: value | any\n def get_header(message, header, default \\\\ nil) do\n Map.get(message.headers, header, default)\n end\n\n @doc \"\"\"\n Gets the first value of a specific `header` in `message`.\n\n If `header` is present in `message`, then the first value is returned.\n Otherwise, `default` is returned (which is `nil` unless specified otherwise).\n \"\"\"\n @spec get_header_front(t, header) :: multiple_value | nil\n @spec get_header_front(t, header, any) :: multiple_value | any\n def get_header_front(message, header, default \\\\ nil) do\n case get_header(message, header, nil) do\n nil -> default\n values -> List.first(values)\n end\n end\n\n @doc \"\"\"\n Gets the last value of a specific `header` in `message`.\n\n If `header` is present in `message`, then the last value is returned.\n Otherwise, `default` is returned (which is `nil` unless specified otherwise).\n \"\"\"\n @spec get_header_back(t, header) :: multiple_value | nil\n @spec get_header_back(t, header, any) :: multiple_value | any\n def get_header_back(message, header, default \\\\ nil) do\n case get_header(message, header, nil) do\n nil -> default\n values -> List.last(values)\n end\n end\n\n @doc \"\"\"\n Updates the `header` in `message` with the given function.\n\n If `header` is present in `message` with value `value`, `fun` is invoked\n with argument `value` and its result is used as the new value of `header`.\n If `header` is not present in `message`, `initial` is inserted as the value\n of `header`.\n \"\"\"\n @spec update_header(t, header, value | nil, (value -> value)) :: t\n def update_header(message, header, initial \\\\ nil, fun) do\n %{message | headers: Map.update(message.headers, header, initial, fun)}\n end\n\n @doc \"\"\"\n Updates the first `header` value in `message` with the given function.\n\n If `header` is present in `message` with value `[value]`, `fun` is invoked\n with for first element of `[value]` and its result is used as the new value\n of `header` front. If `header` is not present in `message`, or it is an empty\n list, `initial` is inserted as the single value of `header`.\n \"\"\"\n @spec update_header_front(t, header, value | nil, (multiple_value -> multiple_value)) :: t\n def update_header_front(message, header, initial \\\\ nil, fun)\n when is_function(fun, 1) do\n update_header(message, header, List.wrap(initial), fn [head | tail] -> [fun.(head) | tail] end)\n end\n\n @doc \"\"\"\n Updates the last `header` value in `message` with the given function.\n\n If `header` is present in `message` with value `[value]`, `fun` is invoked\n with for last element of `[value]` and its result is used as the new value of\n `header` back. If `header` is not present in `message`, or it is an empty\n list, `initial` is inserted as the single value of `header`.\n \"\"\"\n @spec update_header_back(t, header, value | nil, (multiple_value -> multiple_value)) :: t\n def update_header_back(message, header, initial \\\\ nil, fun)\n when is_function(fun, 1) do\n update_header(message, header, List.wrap(initial), fn values ->\n do_update_last(values, fun)\n end)\n end\n\n defp do_update_last(values, fun) do\n [last | tail] = Enum.reverse(values)\n Enum.reduce(tail, [fun.(last)], fn x, acc -> [x | acc] end)\n end\n\n @doc \"\"\"\n Returns and removes the values associated with `header` in `message`.\n\n If `header` is present in `message` with values `[value]`, `{[value],\n new_message}` is returned where `new_message` is the result of removing\n `header` from `message`. If `header` is not present in `message`, `{default,\n message}` is returned.\n \"\"\"\n @spec pop_header(t, header) :: {value | nil, t}\n @spec pop_header(t, header, any) :: {value | any, t}\n def pop_header(message, header, default \\\\ nil) do\n {get, new_headers} = Map.pop(message.headers, header, default)\n {get, %{message | headers: new_headers}}\n end\n\n @doc \"\"\"\n Returns and removes the first value associated with `header` in `message`.\n\n If `header` is present in `message` with values `values`,\n `{List.first(values), new_message}` is returned where `new_message` is the\n result of removing `List.first(values)` from `header`. If `header` is not\n present in `message` or it is an empty list, `{default, message}` is\n returned. When the `header` results in an empty list, `message` gets updated\n by removing the header.\n \"\"\"\n @spec pop_header_front(t, header) :: {multiple_value | nil, t}\n @spec pop_header_front(t, header, any) :: {multiple_value | any, t}\n def pop_header_front(message, header, default \\\\ nil) do\n {values, new_headers} = Map.pop(message.headers, header, [])\n\n case values do\n [] ->\n {default, %{message | headers: new_headers}}\n\n [value] ->\n {value, %{message | headers: new_headers}}\n\n [head | tail] ->\n {head, %{message | headers: Map.put(message.headers, header, tail)}}\n end\n end\n\n @doc \"\"\"\n Returns and removes the last value associated with `header` in `message`.\n\n If `header` is present in `message` with values `values`,\n `{List.last(values), new_message}` is returned where `new_message` is the\n result of removing `List.last(values)` from `header`. If `header` is not\n present in `message` or it is an empty list, `{default, message}` is\n returned. When the `header` results in an empty list, `message` gets updated\n by removing the header.\n \"\"\"\n @spec pop_header_back(t, header) :: {multiple_value | nil, t}\n @spec pop_header_back(t, header, any) :: {multiple_value | any, t}\n def pop_header_back(message, header, default \\\\ nil) do\n {values, new_headers} = Map.pop(message.headers, header, [])\n\n case Enum.reverse(values) do\n [] ->\n {default, %{message | headers: new_headers}}\n\n [value] ->\n {value, %{message | headers: new_headers}}\n\n [last | tail] ->\n {last, %{message | headers: Map.put(message.headers, header, Enum.reverse(tail))}}\n end\n end\n\n @doc \"\"\"\n Gets the values from `header` and updates it, all in one pass.\n\n `fun` is called with the current values under `header` in `message` (or `nil`\n if `key` is not present in `message`) and must return a two-element tuple:\n the \"get\" value (the retrieved values, which can be operated on before being\n returned) and the new values to be stored under `header` in the resulting new\n message. `fun` may also return `:pop`, which means all current values shall\n be removed from `message` and returned (making this function behave like\n `Sippet.Message.pop_header(message, header)`. The returned value is a tuple\n with the \"get\" value returned by `fun` and a new message with the updated\n values under `header`.\n \"\"\"\n @spec get_and_update_header(t, header, (value -> {get, value} | :pop)) ::\n {get, t}\n when get: value\n def get_and_update_header(message, header, fun) when is_function(fun, 1) do\n {get, new_headers} = Map.get_and_update(message.headers, header, fun)\n {get, %{message | headers: new_headers}}\n end\n\n @doc \"\"\"\n Gets the first value from `header` and updates it, all in one pass.\n\n `fun` is called with the current first value under `header` in `message` (or\n `nil` if `key` is not present in `message`) and must return a two-element\n tuple: the \"get\" value (the retrieved value, which can be operated on before\n being returned) and the new value to be stored under `header` in the\n resulting new message. `fun` may also return `:pop`, which means the current\n value shall be removed from `message` and returned (making this function\n behave like `Sippet.Message.pop_header_front(message, header)`. The returned\n value is a tuple with the \"get\" value returned by `fun` and a new message\n with the updated values under `header`.\n \"\"\"\n @spec get_and_update_header_front(t, header, (multiple_value -> {get, multiple_value} | :pop)) ::\n {get, t}\n when get: multiple_value\n def get_and_update_header_front(message, header, fun)\n when is_function(fun, 1) do\n {get, new_headers} =\n Map.get_and_update(message.headers, header, &do_get_and_update_header_front(&1, fun))\n\n {get, %{message | headers: new_headers}}\n end\n\n defp do_get_and_update_header_front(nil, fun) do\n case fun.(nil) do\n {get, nil} -> {get, []}\n {get, value} -> {get, [value]}\n :pop -> :pop\n end\n end\n\n defp do_get_and_update_header_front([], fun) do\n case fun.(nil) do\n {get, nil} -> {get, []}\n {get, value} -> {get, [value]}\n :pop -> :pop\n end\n end\n\n defp do_get_and_update_header_front([head | tail], fun) do\n case fun.(head) do\n {get, nil} -> {get, [tail]}\n {get, value} -> {get, [value | tail]}\n :pop -> {head, tail}\n end\n end\n\n @doc \"\"\"\n Gets the last value from `header` and updates it, all in one pass.\n\n `fun` is called with the current last value under `header` in `message` (or\n `nil` if `key` is not present in `message`) and must return a two-element\n tuple: the \"get\" value (the retrieved value, which can be operated on before\n being returned) and the new value to be stored under `header` in the\n resulting new message. `fun` may also return `:pop`, which means the current\n value shall be removed from `message` and returned (making this function\n behave like `Sippet.Message.pop_header_back(message, header)`. The returned\n value is a tuple with the \"get\" value returned by `fun` and a new message\n with the updated values under `header`.\n \"\"\"\n @spec get_and_update_header_back(t, header, (multiple_value -> {get, multiple_value} | :pop)) ::\n {get, t}\n when get: multiple_value\n def get_and_update_header_back(message, header, fun)\n when is_function(fun, 1) do\n {get, new_headers} =\n Map.get_and_update(message.headers, header, &do_get_and_update_header_back(&1, fun))\n\n {get, %{message | headers: new_headers}}\n end\n\n defp do_get_and_update_header_back([], fun) do\n case fun.(nil) do\n {get, value} -> {get, [value]}\n :pop -> :pop\n end\n end\n\n defp do_get_and_update_header_back(values, fun) do\n [last | tail] = Enum.reverse(values)\n\n case fun.(last) do\n {get, new_value} -> {get, Enum.reduce(tail, [new_value], fn x, acc -> [x | acc] end)}\n :pop -> {last, Enum.reverse(last)}\n end\n end\n\n @doc \"\"\"\n Parses a SIP message header block as received by the transport layer.\n\n In order to correctly set the message body, you have to verify the\n `:content_length` header; if it exists, it reflects the body size and you\n have to set it manually on the returned message.\n \"\"\"\n @spec parse(iodata) :: {:ok, t} | {:error, atom}\n def parse(data) do\n binary_data = IO.iodata_to_binary(data)\n\n case Sippet.Parser.parse(IO.iodata_to_binary(binary_data)) do\n {:ok, message} ->\n case do_parse(message, binary_data) do\n {:error, reason} ->\n {:error, reason}\n\n message ->\n {:ok, message}\n end\n\n reason ->\n {:error, reason}\n end\n end\n\n defp do_parse(message, binary_data) do\n case do_parse_start_line(message.start_line) do\n {:error, reason} ->\n {:error, reason}\n\n start_line ->\n case do_parse_headers(message.headers) do\n {:error, reason} ->\n {:error, reason}\n\n headers ->\n %__MODULE__{\n start_line: start_line,\n headers: headers,\n body: get_body(binary_data)\n }\n end\n end\n end\n\n defp get_body(binary_data) do\n case String.split(binary_data, ~r{\\r?\\n\\r?\\n}, parts: 2) do\n [_, body] -> body\n [_] -> nil\n end\n end\n\n defp do_parse_start_line(%{method: _} = start_line) do\n case URI.parse(start_line.request_uri) do\n {:ok, uri} ->\n %RequestLine{\n method: start_line.method,\n request_uri: uri,\n version: start_line.version\n }\n\n other ->\n other\n end\n end\n\n defp do_parse_start_line(%{status_code: _} = start_line) do\n %StatusLine{\n status_code: start_line.status_code,\n reason_phrase: start_line.reason_phrase,\n version: start_line.version\n }\n end\n\n defp do_parse_headers(%{} = headers),\n do: do_parse_headers(Map.to_list(headers), [])\n\n defp do_parse_headers([], result), do: Map.new(result)\n\n defp do_parse_headers([{name, value} | tail], result) do\n case do_parse_header_value(value) do\n {:error, reason} ->\n {:error, reason}\n\n value ->\n do_parse_headers(tail, [{name, value} | result])\n end\n end\n\n defp do_parse_header_value(values) when is_list(values),\n do: do_parse_each_header_value(values, [])\n\n defp do_parse_header_value({{year, month, day}, {hour, minute, second}, microsecond}) do\n NaiveDateTime.from_erl!(\n {{year, month, day}, {hour, minute, second}},\n microsecond\n )\n end\n\n defp do_parse_header_value({display_name, uri, %{} = parameters}) do\n case URI.parse(uri) do\n {:ok, uri} ->\n {display_name, uri, parameters}\n\n other ->\n other\n end\n end\n\n defp do_parse_header_value(value), do: value\n\n defp do_parse_each_header_value([], result), do: Enum.reverse(result)\n\n defp do_parse_each_header_value([head | tail], result) do\n case do_parse_header_value(head) do\n {:error, reason} ->\n {:error, reason}\n\n value ->\n do_parse_each_header_value(tail, [value | result])\n end\n end\n\n @doc \"\"\"\n Parses a SIP message header block as received by the transport layer.\n\n Raises if the string is an invalid SIP header.\n\n In order to correctly set the message body, you have to verify the\n `:content_length` header; if it exists, it reflects the body size and you\n have to set it manually on the returned message.\n \"\"\"\n @spec parse!(String.t() | charlist) :: t | no_return\n def parse!(data) do\n case parse(data) do\n {:ok, message} ->\n message\n\n {:error, reason} ->\n raise ArgumentError,\n \"cannot convert #{inspect(data)} to SIP \" <>\n \"message, reason: #{inspect(reason)}\"\n end\n end\n\n @doc \"\"\"\n Returns the string representation of the given `Sippet.Message` struct.\n \"\"\"\n @spec to_string(t) :: binary\n defdelegate to_string(value), to: String.Chars.Sippet.Message\n\n @doc \"\"\"\n Returns the iodata representation of the given `Sippet.Message` struct.\n \"\"\"\n @spec to_iodata(t) :: iodata\n def to_iodata(%Sippet.Message{} = message) do\n start_line =\n case message.start_line do\n %RequestLine{} -> RequestLine.to_iodata(message.start_line)\n %StatusLine{} -> StatusLine.to_iodata(message.start_line)\n end\n\n # includes a Content-Length header case it does not have one\n message =\n if message.headers |> Map.has_key?(:content_length) do\n message\n else\n len = if(message.body == nil, do: 0, else: String.length(message.body))\n %{message | headers: Map.put(message.headers, :content_length, len)}\n end\n\n [\n start_line,\n \"\\r\\n\",\n do_headers(message.headers),\n \"\\r\\n\",\n if(message.body == nil, do: \"\", else: message.body)\n ]\n end\n\n defp do_headers(%{} = headers), do: do_headers(Map.to_list(headers), [])\n defp do_headers([], result), do: result\n\n defp do_headers([{name, value} | tail], result),\n do: do_headers(tail, [do_header(name, value) | result])\n\n defp do_header(name, value) do\n {name, multiple} =\n case name do\n :accept -> {\"Accept\", true}\n :accept_encoding -> {\"Accept-Encoding\", true}\n :accept_language -> {\"Accept-Language\", true}\n :alert_info -> {\"Alert-Info\", true}\n :allow -> {\"Allow\", true}\n :authentication_info -> {\"Authentication-Info\", false}\n :authorization -> {\"Authorization\", false}\n :call_id -> {\"Call-ID\", true}\n :call_info -> {\"Call-Info\", true}\n :contact -> {\"Contact\", true}\n :content_disposition -> {\"Content-Disposition\", true}\n :content_encoding -> {\"Content-Encoding\", true}\n :content_language -> {\"Content-Language\", true}\n :content_length -> {\"Content-Length\", true}\n :content_type -> {\"Content-Type\", true}\n :cseq -> {\"CSeq\", true}\n :date -> {\"Date\", true}\n :error_info -> {\"Error-Info\", true}\n :expires -> {\"Expires\", true}\n :from -> {\"From\", true}\n :in_reply_to -> {\"In-Reply-To\", true}\n :max_forwards -> {\"Max-Forwards\", true}\n :mime_version -> {\"MIME-Version\", true}\n :min_expires -> {\"Min-Expires\", true}\n :organization -> {\"Organization\", true}\n :priority -> {\"Priority\", true}\n :p_asserted_identity -> {\"P-Asserted-Identity\", true}\n :proxy_authenticate -> {\"Proxy-Authenticate\", false}\n :proxy_authorization -> {\"Proxy-Authorization\", false}\n :proxy_require -> {\"Proxy-Require\", true}\n :reason -> {\"Reason\", true}\n :record_route -> {\"Record-Route\", true}\n :reply_to -> {\"Reply-To\", true}\n :require -> {\"Require\", true}\n :retry_after -> {\"Retry-After\", true}\n :route -> {\"Route\", true}\n :server -> {\"Server\", true}\n :subject -> {\"Subject\", true}\n :supported -> {\"Supported\", true}\n :timestamp -> {\"Timestamp\", true}\n :to -> {\"To\", true}\n :unsupported -> {\"Unsupported\", true}\n :user_agent -> {\"User-Agent\", true}\n :via -> {\"Via\", true}\n :warning -> {\"Warning\", true}\n :www_authenticate -> {\"WWW-Authenticate\", false}\n other -> {other, true}\n end\n\n if multiple do\n [name, \": \", do_header_values(value, []), \"\\r\\n\"]\n else\n do_one_per_line(name, value)\n end\n end\n\n defp do_header_values([], values), do: values |> Enum.reverse()\n\n defp do_header_values([head | tail], values),\n do: do_header_values(tail, do_join(do_header_value(head), values, \", \"))\n\n defp do_header_values(value, _), do: do_header_value(value)\n\n defp do_header_value(value) when is_binary(value), do: value\n\n defp do_header_value(value) when is_integer(value), do: Integer.to_string(value)\n\n defp do_header_value({sequence, method}) when is_integer(sequence),\n do: [Integer.to_string(sequence), \" \", upcase_atom_or_string(method)]\n\n defp do_header_value({major, minor})\n when is_integer(major) and is_integer(minor),\n do: [Integer.to_string(major), \".\", Integer.to_string(minor)]\n\n defp do_header_value({token, %{} = parameters}) when is_binary(token),\n do: [token, do_parameters(parameters)]\n\n defp do_header_value({{type, subtype}, %{} = parameters})\n when is_binary(type) and is_binary(subtype),\n do: [type, \"\/\", subtype, do_parameters(parameters)]\n\n defp do_header_value({display_name, %URI{} = uri, %{} = parameters})\n when is_binary(display_name) do\n [\n if(display_name == \"\", do: \"\", else: [\"\\\"\", display_name, \"\\\" \"]),\n \"<\",\n URI.to_string(uri),\n \">\",\n do_parameters(parameters)\n ]\n end\n\n defp do_header_value({delta_seconds, comment, %{} = parameters})\n when is_integer(delta_seconds) and is_binary(comment) do\n [\n Integer.to_string(delta_seconds),\n if(comment != \"\", do: [\" (\", comment, \") \"], else: \"\"),\n do_parameters(parameters)\n ]\n end\n\n defp do_header_value({timestamp, delay})\n when is_float(timestamp) and is_float(delay) do\n [Float.to_string(timestamp), if(delay > 0, do: [\" \", Float.to_string(delay)], else: \"\")]\n end\n\n defp do_header_value({{major, minor}, protocol, {host, port}, %{} = parameters})\n when is_integer(major) and is_integer(minor) and\n is_binary(host) and is_integer(port) do\n [\n \"SIP\/\",\n Integer.to_string(major),\n \".\",\n Integer.to_string(minor),\n \"\/\",\n upcase_atom_or_string(protocol),\n \" \",\n host,\n if(port > 0, do: [\":\", Integer.to_string(port)], else: \"\"),\n do_parameters(parameters)\n ]\n end\n\n defp do_header_value({code, agent, text})\n when is_integer(code) and is_binary(agent) and is_binary(text) do\n [Integer.to_string(code), \" \", agent, \" \\\"\", text, \"\\\"\"]\n end\n\n defp do_header_value(%NaiveDateTime{} = value) do\n day_of_week =\n case Date.day_of_week(NaiveDateTime.to_date(value)) do\n 1 -> \"Mon\"\n 2 -> \"Tue\"\n 3 -> \"Wed\"\n 4 -> \"Thu\"\n 5 -> \"Fri\"\n 6 -> \"Sat\"\n 7 -> \"Sun\"\n end\n\n month =\n case value.month do\n 1 -> \"Jan\"\n 2 -> \"Feb\"\n 3 -> \"Mar\"\n 4 -> \"Apr\"\n 5 -> \"May\"\n 6 -> \"Jun\"\n 7 -> \"Jul\"\n 8 -> \"Aug\"\n 9 -> \"Sep\"\n 10 -> \"Oct\"\n 11 -> \"Nov\"\n 12 -> \"Dec\"\n end\n\n # Microsecond is explicitly removed here, as the RFC 3261 does not define\n # it. Therefore, while it is accepted, it won't be forwarded.\n [\n day_of_week,\n \", \",\n String.pad_leading(Integer.to_string(value.day), 2, \"0\"),\n \" \",\n month,\n \" \",\n Integer.to_string(value.year),\n \" \",\n String.pad_leading(Integer.to_string(value.hour), 2, \"0\"),\n \":\",\n String.pad_leading(Integer.to_string(value.minute), 2, \"0\"),\n \":\",\n String.pad_leading(Integer.to_string(value.second), 2, \"0\"),\n \" GMT\"\n ]\n end\n\n defp do_one_per_line(name, %{} = value),\n do: [name, \": \", do_one_per_line_value(value), \"\\r\\n\"]\n\n defp do_one_per_line(name, values) when is_list(values),\n do: do_one_per_line(name, values |> Enum.reverse(), [])\n\n defp do_one_per_line(_, [], result), do: result\n\n defp do_one_per_line(name, [head | tail], result),\n do: do_one_per_line(name, tail, [name, \": \", do_one_per_line_value(head), \"\\r\\n\" | result])\n\n defp do_one_per_line_value(%{} = parameters),\n do: do_one_per_line_value(Map.to_list(parameters), [])\n\n defp do_one_per_line_value({scheme, %{} = parameters}),\n do: [scheme, \" \", do_auth_parameters(parameters)]\n\n defp do_one_per_line_value([], result), do: result\n\n defp do_one_per_line_value([{name, value} | tail], result) do\n do_one_per_line_value(tail, do_join([name, \"=\", value], result, \", \"))\n end\n\n defp do_parameters(%{} = parameters),\n do: do_parameters(Map.to_list(parameters), [])\n\n defp do_parameters([], result), do: result\n\n defp do_parameters([{name, \"\"} | tail], result),\n do: do_parameters(tail, [\";\", name | result])\n\n defp do_parameters([{name, value} | tail], result),\n do: do_parameters(tail, [\";\", name, \"=\", value | result])\n\n defp do_join(head, [], _joiner), do: [head]\n defp do_join(head, tail, joiner), do: [head, joiner | tail]\n\n defp upcase_atom_or_string(s),\n do: if(is_atom(s), do: String.upcase(Atom.to_string(s)), else: s)\n\n defp do_auth_parameters(%{} = parameters),\n do: do_auth_parameters(Map.to_list(parameters), [])\n\n defp do_auth_parameters([], result), do: result |> Enum.reverse()\n\n defp do_auth_parameters([{name, value} | tail], [])\n when name in [\"username\", \"realm\", \"nonce\", \"uri\", \"response\", \"cnonce\", \"opaque\"],\n do: do_auth_parameters(tail, [[name, \"=\\\"\", value, \"\\\"\"]])\n\n defp do_auth_parameters([{name, value} | tail], []),\n do: do_auth_parameters(tail, [[name, \"=\", value]])\n\n defp do_auth_parameters([{name, value} | tail], result)\n when name in [\"username\", \"realm\", \"nonce\", \"uri\", \"response\", \"cnonce\", \"opaque\"],\n do: do_auth_parameters(tail, [[\";\", name, \"=\\\"\", value, \"\\\"\"] | result])\n\n defp do_auth_parameters([{name, value} | tail], result),\n do: do_auth_parameters(tail, [[\";\", name, \"=\", value] | result])\n\n @doc \"\"\"\n Checks whether a message is valid.\n \"\"\"\n @spec valid?(t) :: boolean\n def valid?(message) do\n case validate(message) do\n :ok -> true\n _ -> false\n end\n end\n\n @doc \"\"\"\n Checks whether a message is valid, also checking if it corresponds to the\n indicated incoming transport tuple `{protocol, host, port}`.\n \"\"\"\n @spec valid?(t, {protocol, host :: String.t(), port :: integer}) :: boolean\n def valid?(message, from) do\n case validate(message, from) do\n :ok -> true\n _ -> false\n end\n end\n\n @doc \"\"\"\n Validates if a message is valid, returning errors if found.\n \"\"\"\n @spec validate(t) :: :ok | {:error, reason :: term}\n def validate(message) do\n validators = [\n &has_valid_start_line_version\/1,\n &has_required_headers\/1,\n &has_valid_body\/1,\n &has_tag_on(&1, :from)\n ]\n\n validators =\n if request?(message) do\n validators ++\n [\n &has_matching_cseq\/1\n ]\n else\n validators\n end\n\n do_validate(validators, message)\n end\n\n defp do_validate([], _message), do: :ok\n\n defp do_validate([f | rest], message) do\n case f.(message) do\n :ok -> do_validate(rest, message)\n other -> other\n end\n end\n\n defp has_valid_start_line_version(message) do\n %{version: version} = message.start_line\n\n if version == {2, 0} do\n :ok\n else\n {:error, \"invalid status line version #{inspect(version)}\"}\n end\n end\n\n defp has_required_headers(message) do\n required = [:to, :from, :cseq, :call_id, :via]\n\n missing_headers =\n for header <- required, not (message |> has_header?(header)) do\n header\n end\n\n if Enum.empty?(missing_headers) do\n :ok\n else\n {:error, \"missing headers: #{inspect(missing_headers)}\"}\n end\n end\n\n defp has_valid_body(message) do\n case message.headers do\n %{content_length: content_length} ->\n cond do\n message.body != nil and byte_size(message.body) == content_length ->\n :ok\n\n message.body == nil and content_length == 0 ->\n :ok\n\n true ->\n {:error, \"Content-Length and message body size do not match\"}\n end\n\n _otherwise ->\n cond do\n message.body == nil ->\n :ok\n\n message.headers.via |> List.last() |> elem(1) == :udp ->\n # It is OK to not have Content-Length in an UDP message\n :ok\n\n true ->\n {:error, \"No Content-Length header, but body is not nil\"}\n end\n end\n end\n\n defp has_tag_on(message, header) do\n {_display_name, _uri, params} = message.headers[header]\n\n case params do\n %{\"tag\" => value} ->\n if String.length(value) > 0 do\n :ok\n else\n {:error, \"empty #{inspect(header)} tag\"}\n end\n\n _otherwise ->\n {:error, \"#{inspect(header)} does not have tag\"}\n end\n end\n\n defp has_matching_cseq(request) do\n method = request.start_line.method\n\n case request.headers.cseq do\n {_sequence, ^method} ->\n :ok\n\n _ ->\n {:error, \"CSeq method and request method do no match\"}\n end\n end\n\n @doc \"\"\"\n Validates if a message is valid, also checking if it corresponds to the\n indicated incoming transport tuple `{protocol, host, port}`. It returns the\n error if found.\n \"\"\"\n @spec validate(t, {protocol, host :: String.t(), port :: integer}) ::\n :ok | {:error, reason :: term}\n def validate(message, from) do\n case validate(message) do\n :ok ->\n validators = [\n &has_valid_via(&1, from)\n ]\n\n do_validate(validators, message)\n\n other ->\n other\n end\n end\n\n defp has_valid_via(message, {protocol1, _ip, _port}) do\n {_version, protocol2, _sent_by, _params} = hd(message.headers.via)\n\n if protocol1 != protocol2 do\n {:error, \"Via protocol doesn't match transport protocol\"}\n else\n has_valid_via(message, message.headers.via)\n end\n end\n\n defp has_valid_via(_, []), do: :ok\n\n defp has_valid_via(message, [via | rest]) do\n {version, _protocol, _sent_by, params} = via\n\n if version != {2, 0} do\n {:error, \"Via version #{inspect(version)} is unknown\"}\n else\n case params do\n %{\"branch\" => branch} ->\n if branch |> String.starts_with?(\"z9hG4bK\") do\n has_valid_via(message, rest)\n else\n {:error, \"Via branch doesn't start with the magic cookie\"}\n end\n\n _otherwise ->\n {:error, \"Via header doesn't have branch parameter\"}\n end\n end\n end\n\n @doc \"\"\"\n Extracts the remote address and port from an incoming request inspecting the\n `Via` header. If `;rport` is present, use it instead of the topmost `Via`\n port, if `;received` is present, use it instead of the topmost `Via` host.\n \"\"\"\n @spec get_remote(request) ::\n {:ok, {protocol :: atom | binary, host :: binary, port :: integer}}\n | {:error, reason :: term}\n def get_remote(%__MODULE__{start_line: %RequestLine{}, headers: %{via: [topmost_via | _]}}) do\n {_version, protocol, {host, port}, params} = topmost_via\n\n host =\n case params do\n %{\"received\" => received} ->\n received\n\n _otherwise ->\n host\n end\n\n port =\n case params do\n %{\"rport\" => rport} ->\n rport |> String.to_integer()\n\n _otherwise ->\n port\n end\n\n {:ok, {protocol, host, port}}\n end\n\n def get_remote(%__MODULE__{start_line: %RequestLine{}}),\n do: {:error, \"Missing Via header\"}\n\n def get_remote(%__MODULE__{}),\n do: {:error, \"Not a request\"}\n\n @doc \"\"\"\n Fetches the value for a specific `key` in the given `message`.\n \"\"\"\n def fetch(%__MODULE__{} = message, key), do: Map.fetch(message, key)\n\n @doc \"\"\"\n Gets the value from key and updates it, all in one pass.\n\n About the same as `Map.get_and_update\/3` except that this function actually\n does not remove the key from the struct case the passed function returns\n `:pop`; it puts `nil` for `:start_line`, `:body` and `:target` ands `%{}` for\n the `:headers` key.\n \"\"\"\n def get_and_update(%__MODULE__{} = message, key, fun)\n when key in [:start_line, :headers, :body, :target] do\n current = message[key]\n\n case fun.(current) do\n {get, update} ->\n {get, message |> Map.put(key, update)}\n\n :pop ->\n {current, pop(message, key)}\n\n other ->\n raise \"the given function must return a two-element tuple or :pop, got: #{inspect(other)}\"\n end\n end\n\n @doc \"\"\"\n Returns and removes the value associated with `key` in `message`.\n\n About the same as `Map.pop\/3` except that this function actually does not\n remove the key from the struct case the passed function returns `:pop`; it\n puts `nil` for `:start_line`, `:body` and `:target` ands `%{}` for the\n `:headers` key.\n \"\"\"\n def pop(message, key, default \\\\ nil)\n\n def pop(%__MODULE__{} = message, :headers, default) when default == nil or is_map(default),\n do: {message[:headers], %{message | headers: %{}}}\n\n def pop(%__MODULE__{}, :headers, _),\n do: raise(\"invalid :default, :headers must be nil or a map\")\n\n def pop(%__MODULE__{} = message, key, nil) when key in [:start_line, :body, :target],\n do: {message[key], %{message | key => nil}}\n\n def pop(%__MODULE__{} = message, :start_line, %RequestLine{} = start_line),\n do: {message[:start_line], %{message | start_line: start_line}}\n\n def pop(%__MODULE__{} = message, :start_line, %StatusLine{} = start_line),\n do: {message[:start_line], %{message | start_line: start_line}}\n\n def pop(%__MODULE__{}, :start_line, _),\n do: raise(\"invalid :default, :start_line must be nil, RequestLine or StatusLine\")\n\n def pop(%__MODULE__{} = message, :body, default) when is_binary(default),\n do: {message[:body], %{message | body: default}}\n\n def pop(%__MODULE__{}, :body, _),\n do: raise(\"invalid :default, :body must be nil or binary\")\n\n def pop(%__MODULE__{} = message, :target, {_protocol, _host, _port} = default),\n do: {message[:target], %{message | target: default}}\n\n def pop(%__MODULE__{}, :target, _),\n do: raise(\"invalid :default, :target must be nil or {protocol, host, port} tuple\")\nend\n\ndefimpl String.Chars, for: Sippet.Message do\n def to_string(%Sippet.Message{} = message),\n do: message |> Sippet.Message.to_iodata() |> IO.iodata_to_binary()\nend\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Elixir"} {"commit":"02c6e81fdd5e9413c644c6968fc01fda55162a61","subject":"Don't show rating in text if rating was 0.","message":"Don't show rating in text if rating was 0.\n","repos":"nicksergeant\/slacktapped","old_file":"lib\/checkins.ex","new_file":"lib\/checkins.ex","new_contents":"defmodule Slacktapped.Checkins do\n @instance_name System.get_env(\"INSTANCE_NAME\") ||\n Application.get_env(:slacktapped, :instance_name)\n @redis Application.get_env(:slacktapped, :redis)\n\n @doc \"\"\"\n Processes a checkin for use in a Slack post:\n\n 1. Verifies the checkin is eligible to post.\n 2. Parses the checkin to a Slack attachment.\n 3. Adds the attachment to the checkin.\n 4. Reports the checkin post to Redis.\n \"\"\"\n def process_checkin(checkin) do\n with {:ok, checkin} <- is_eligible_checkin_post(checkin),\n {:ok, attachment} <- parse_checkin(checkin),\n {:ok, checkin} <- Slacktapped.add_attachment({:ok, attachment}, checkin),\n {:ok, checkin} <- report_checkin_type({:ok, checkin}),\n do: {:ok, checkin}\n end\n\n @doc \"\"\"\n Determines if a checkin is eligible to be posted to Slack.\n\n Checkin is ineligible to post if:\n\n 1. There is a Redis key indicating that this checkin was posted under this\n instance, and had an image with it.\n 2. There is a Redis key indicating that this checkin was posted under this\n instance, and had no image with it, but the checkin we see now still does\n not have an image.\n\n ## Examples\n\n A checkin that was not already posted:\n\n iex> Slacktapped.Checkins.is_eligible_checkin_post(%{\"checkin_id\" => 9985})\n {:ok, %{\"checkin_id\" => 9985}}\n\n A checkin that was already posted, and had an image:\n\n iex> Slacktapped.Checkins.is_eligible_checkin_post(%{\"checkin_id\" => 9988})\n {:error, %{\"checkin_id\" => 9988}}\n\n A checkin that was already posted and had no image, and we do not currently\n have an image:\n\n iex> Slacktapped.Checkins.is_eligible_checkin_post(%{\"beer\" => %{}, \"checkin_id\" => 5566})\n {:error, %{\"beer\" => %{}, \"checkin_id\" => 5566}}\n\n A checkin that was already posted and had no image, and we now have an\n image:\n\n iex> Slacktapped.Checkins.is_eligible_checkin_post(%{\n ...> \"beer\" => %{},\n ...> \"checkin_id\" => 5566,\n ...> \"media\" => %{\n ...> \"items\" => [\n ...> %{\n ...> \"photo\" => %{\n ...> \"photo_id\" => 987,\n ...> \"photo_img_lg\" => \"http:\/\/path\/to\/beer\/image\"\n ...> }\n ...> }\n ...> ]\n ...> }\n ...> })\n {:ok, %{\n \"beer\" => %{},\n \"checkin_id\" => 5566,\n \"media\" => %{\n \"items\" => [\n %{\n \"photo\" => %{\n \"photo_id\" => 987,\n \"photo_img_lg\" => \"http:\/\/path\/to\/beer\/image\"\n }\n }\n ]\n }\n }}\n\n \"\"\"\n def is_eligible_checkin_post(checkin) do\n checkin_id = checkin[\"checkin_id\"] || \"\"\n media_items = checkin[\"media\"][\"items\"]\n has_image = is_list(media_items) and Enum.count(media_items) >= 1\n get_key = \"GET #{@instance_name}:#{checkin_id}\"\n\n cond do\n @redis.command(\"#{get_key}:with-image\") == {:ok, \"1\"} ->\n {:error, checkin}\n @redis.command(\"#{get_key}:without-image\") == {:ok, \"1\"} and not has_image ->\n {:error, checkin}\n true ->\n {:ok, checkin}\n end\n end\n\n @doc ~S\"\"\"\n Parses a checkin into an attachment for Slack.\n\n ## Examples\n\n A typical checkin with a rating and comment:\n\n iex> Slacktapped.Checkins.parse_checkin(%{\n ...> \"attachments\" => [],\n ...> \"user\" => %{\n ...> \"user_name\" => \"nicksergeant\",\n ...> \"user_avatar\" => \"http:\/\/path\/to\/user\/avatar\"\n ...> },\n ...> \"beer\" => %{\n ...> \"bid\" => 123,\n ...> \"beer_abv\" => 4.5,\n ...> \"beer_label\" => \"http:\/\/path\/to\/beer\/label\",\n ...> \"beer_name\" => \"IPA\",\n ...> \"beer_slug\" => \"two-lake-ipa\",\n ...> \"beer_style\" => \"American IPA\"\n ...> },\n ...> \"brewery\" => %{\n ...> \"brewery_id\" => 1,\n ...> \"brewery_label\" => \"http:\/\/path\/to\/brewery\/label\",\n ...> \"brewery_name\" => \"Two Lake\"\n ...> },\n ...> \"checkin_comment\" => \"Lovely!\",\n ...> \"checkin_id\" => 567,\n ...> \"rating_score\" => 3.5\n ...> })\n {:ok,\n %{\n \"author_icon\" => \"http:\/\/path\/to\/user\/avatar\",\n \"author_link\" => \"https:\/\/untappd.com\/user\/nicksergeant\",\n \"author_name\" => \"nicksergeant\",\n \"color\" => \"#FFCF0B\",\n \"fallback\" => \"Image of this checkin.\",\n \"footer\" => \"\",\n \"footer_icon\" => \"http:\/\/path\/to\/brewery\/label\",\n \"image_url\" => \"http:\/\/path\/to\/beer\/label\",\n \"text\" => \"\" <>\n \" is drinking \" <>\n \" \" <>\n \"(American IPA, 4.5% ABV).\" <>\n \"\\nThey rated it a 3.5 and said \\\"Lovely!\\\"\\n\" <>\n \"\",\n \"title\" => \"IPA\",\n \"title_link\" => \"https:\/\/untappd.com\/b\/two-lake-ipa\/123\"\n }\n }\n\n A checkin without a rating:\n\n iex> Slacktapped.Checkins.parse_checkin(%{\n ...> \"attachments\" => [],\n ...> \"checkin_comment\" => \"Lovely!\"\n ...> })\n {:ok,\n %{\n \"author_icon\" => nil,\n \"author_link\" => \"https:\/\/untappd.com\/user\/\",\n \"author_name\" => nil,\n \"color\" => \"#FFCF0B\",\n \"fallback\" => \"Image of this checkin.\",\n \"footer\" => \"\",\n \"footer_icon\" => nil,\n \"image_url\" => nil,\n \"text\" => \"\" <>\n \" is drinking \" <>\n \" (, % ABV).\" <>\n \"\\nThey said \\\"Lovely!\\\"\\n\" <>\n \"\",\n \"title\" => nil,\n \"title_link\" => \"https:\/\/untappd.com\/b\/\/\"\n }\n }\n\n A checkin without a comment:\n\n iex> Slacktapped.Checkins.parse_checkin(%{\"rating_score\" => 1.5})\n {:ok,\n %{\n \"author_icon\" => nil,\n \"author_link\" => \"https:\/\/untappd.com\/user\/\",\n \"author_name\" => nil,\n \"color\" => \"#FFCF0B\",\n \"fallback\" => \"Image of this checkin.\",\n \"footer\" => \"\",\n \"footer_icon\" => nil,\n \"image_url\" => nil,\n \"text\" => \"\" <>\n \" is drinking \" <>\n \" (, % ABV).\" <>\n \"\\nThey rated it a 1.5.\\n\" <>\n \"\",\n \"title\" => nil,\n \"title_link\" => \"https:\/\/untappd.com\/b\/\/\"\n }\n }\n\n A checkin without a comment or rating:\n\n iex> Slacktapped.Checkins.parse_checkin(%{})\n {:ok,\n %{\n \"author_icon\" => nil,\n \"author_link\" => \"https:\/\/untappd.com\/user\/\",\n \"author_name\" => nil,\n \"color\" => \"#FFCF0B\",\n \"fallback\" => \"Image of this checkin.\",\n \"footer\" => \"\",\n \"footer_icon\" => nil,\n \"image_url\" => nil,\n \"text\" => \"\" <>\n \" is drinking \" <>\n \" (, % ABV).\\n\" <>\n \"\",\n \"title\" => nil,\n \"title_link\" => \"https:\/\/untappd.com\/b\/\/\"\n }\n }\n\n A checkin with a rating of 0:\n\n iex> Slacktapped.Checkins.parse_checkin(%{\"rating_score\" => 0})\n {:ok,\n %{\n \"author_icon\" => nil,\n \"author_link\" => \"https:\/\/untappd.com\/user\/\",\n \"author_name\" => nil,\n \"color\" => \"#FFCF0B\",\n \"fallback\" => \"Image of this checkin.\",\n \"footer\" => \"\",\n \"footer_icon\" => nil,\n \"image_url\" => nil,\n \"text\" => \"\" <>\n \" is drinking \" <>\n \" (, % ABV).\\n\" <>\n \"\",\n \"title\" => nil,\n \"title_link\" => \"https:\/\/untappd.com\/b\/\/\"\n }\n }\n\n A checkin with an image:\n\n iex> Slacktapped.Checkins.parse_checkin(%{\n ...> \"media\" => %{\n ...> \"items\" => [\n ...> %{\n ...> \"photo\" => %{\n ...> \"photo_id\" => 987,\n ...> \"photo_img_lg\" => \"http:\/\/path\/to\/beer\/image\"\n ...> }\n ...> }\n ...> ]\n ...> }\n ...> })\n {:ok,\n %{\n \"author_icon\" => nil,\n \"author_link\" => \"https:\/\/untappd.com\/user\/\",\n \"author_name\" => nil,\n \"color\" => \"#FFCF0B\",\n \"fallback\" => \"Image of this checkin.\",\n \"footer\" => \"\",\n \"footer_icon\" => nil,\n \"image_url\" => \"http:\/\/path\/to\/beer\/image\",\n \"text\" => \"\" <>\n \" is drinking \" <>\n \" (, % ABV).\\n\" <>\n \"\",\n \"title\" => nil,\n \"title_link\" => \"https:\/\/untappd.com\/b\/\/\"\n }\n }\n\n A checkin with a venue:\n\n iex> Slacktapped.Checkins.parse_checkin(%{\n ...> \"attachments\" => [],\n ...> \"venue\" => %{\n ...> \"venue_id\" => 789,\n ...> \"venue_name\" => \"Venue Name\",\n ...> \"venue_slug\" => \"venue-slug\"\n ...> }\n ...> })\n {:ok,\n %{\n \"author_icon\" => nil,\n \"author_link\" => \"https:\/\/untappd.com\/user\/\",\n \"author_name\" => nil,\n \"color\" => \"#FFCF0B\",\n \"fallback\" => \"Image of this checkin.\",\n \"footer\" => \"\",\n \"footer_icon\" => nil,\n \"image_url\" => nil,\n \"text\" => \"\" <>\n \" is drinking \" <>\n \" (, % ABV) \" <>\n \"at .\\n\" <>\n \"\",\n \"title\" => nil,\n \"title_link\" => \"https:\/\/untappd.com\/b\/\/\"\n }\n }\n\n A checkin with an image, with a previously-posted checkin with no image:\n\n iex> Slacktapped.Checkins.parse_checkin(%{\n ...> \"checkin_id\" => 5566,\n ...> \"media\" => %{\n ...> \"items\" => [\n ...> %{\n ...> \"photo\" => %{\n ...> \"photo_id\" => 987,\n ...> \"photo_img_lg\" => \"http:\/\/path\/to\/beer\/image\"\n ...> }\n ...> }\n ...> ]\n ...> }\n ...> })\n {:ok,\n %{\n \"author_icon\" => nil,\n \"author_link\" => \"https:\/\/untappd.com\/user\/\",\n \"author_name\" => nil,\n \"color\" => \"#FFCF0B\",\n \"fallback\" => \"Image of this checkin.\",\n \"footer\" => \"\",\n \"footer_icon\" => nil,\n \"image_url\" => \"http:\/\/path\/to\/beer\/image\",\n \"text\" => \"\" <>\n \" added an image to \" <>\n \" of \" <>\n \".\",\n \"title\" => nil,\n \"title_link\" => \"https:\/\/untappd.com\/b\/\/\"\n }\n }\n\n The default Untappd beer label is ignored:\n\n iex> Slacktapped.Checkins.parse_checkin(%{\n ...> \"attachments\" => [],\n ...> \"beer\" => %{\n ...> \"beer_label\" => \"https:\/\/untappd.akamaized.net\/site\/assets\/images\/temp\/badge-beer-default.png\"\n ...> }\n ...> })\n {:ok,\n %{\n \"author_icon\" => nil,\n \"author_link\" => \"https:\/\/untappd.com\/user\/\",\n \"author_name\" => nil,\n \"color\" => \"#FFCF0B\",\n \"fallback\" => \"Image of this checkin.\",\n \"footer\" => \"\",\n \"footer_icon\" => nil,\n \"image_url\" => \"\",\n \"text\" => \"\" <>\n \" is drinking \" <>\n \" (, % ABV).\\n\" <>\n \"\",\n \"title\" => nil,\n \"title_link\" => \"https:\/\/untappd.com\/b\/\/\"\n }\n }\n\n \"\"\"\n def parse_checkin(checkin) do\n {:ok, user_name} = Slacktapped.parse_name(checkin[\"user\"])\n\n beer_abv = checkin[\"beer\"][\"beer_abv\"]\n beer_id = checkin[\"beer\"][\"bid\"]\n beer_label = checkin[\"beer\"][\"beer_label\"]\n beer_name = checkin[\"beer\"][\"beer_name\"]\n beer_slug = checkin[\"beer\"][\"beer_slug\"]\n beer_style = checkin[\"beer\"][\"beer_style\"]\n brewery_id = checkin[\"brewery\"][\"brewery_id\"]\n brewery_name = checkin[\"brewery\"][\"brewery_name\"]\n brewery_label = checkin[\"brewery\"][\"brewery_label\"]\n checkin_comment = checkin[\"checkin_comment\"]\n checkin_id = checkin[\"checkin_id\"]\n checkin_rating = checkin[\"rating_score\"]\n media_items = checkin[\"media\"][\"items\"]\n user_avatar = checkin[\"user\"][\"user_avatar\"]\n user_username = checkin[\"user\"][\"user_name\"]\n\n beer = \"\"\n toast = \"\"\n user = \"\"\n\n rating_and_comment = cond do\n is_binary(checkin_comment)\n and checkin_comment != \"\"\n and is_number(checkin_rating) -> \n \"\\nThey rated it a #{checkin_rating} and said \\\"#{checkin_comment}\\\"\"\n is_binary(checkin_comment)\n and checkin_comment != \"\" ->\n \"\\nThey said \\\"#{checkin_comment}\\\"\"\n is_number(checkin_rating) and checkin_rating > 0 ->\n \"\\nThey rated it a #{checkin_rating}.\"\n true -> \"\"\n end\n\n venue = if is_map(checkin[\"venue\"]) do\n venue_id = checkin[\"venue\"][\"venue_id\"]\n venue_name = checkin[\"venue\"][\"venue_name\"]\n venue_slug = checkin[\"venue\"][\"venue_slug\"]\n \" at \"\n end\n\n image_url = cond do\n is_list(media_items) and Enum.count(media_items) >= 1 ->\n media_items\n |> Enum.at(0)\n |> get_in([\"photo\", \"photo_img_lg\"])\n beer_label != \"https:\/\/untappd.akamaized.net\/site\/assets\/images\/temp\/badge-beer-default.png\" ->\n beer_label\n true -> \"\"\n end\n\n # If we have an image and there was already a post for this checkin\n # *without* an image, only indicate that an image was added.\n cmd = \"GET #{@instance_name}:#{checkin_id}:without-image\"\n text = if is_binary(image_url) and\n @redis.command(cmd) == {:ok, \"1\"} do\n \"#{user} added an image to \" <>\n \"\n \"their checkin> of #{beer}.\"\n else\n \"#{user} is drinking #{beer} (#{beer_style}, #{beer_abv}% ABV)\" <>\n \"#{venue}.#{rating_and_comment}\\n#{toast}\"\n end\n\n {:ok, %{\n \"author_icon\" => user_avatar,\n \"author_link\" => \"https:\/\/untappd.com\/user\/#{user_username}\",\n \"author_name\" => user_username,\n \"color\" => \"#FFCF0B\",\n \"fallback\" => \"Image of this checkin.\",\n \"footer\" => \"\",\n \"footer_icon\" => brewery_label,\n \"image_url\" => image_url,\n \"text\" => text,\n \"title\" => beer_name,\n \"title_link\" => \"https:\/\/untappd.com\/b\/#{beer_slug}\/#{beer_id}\"\n }}\n end\n\n @doc \"\"\"\n Reports that a checkin was posted to Slack by setting a Redis key. There are\n two possible Redis keys indicating a post was made:\n\n 1. ::with-image\n 2. ::without-image\n\n Already-posted checkins that were previously posted without an image are\n posted again indicating that the user added an image to the checkin. If a\n record exists for the checkin with an image, the checkin is not posted again.\n\n Examples\n \n iex> Slacktapped.Checkins.report_checkin_type({:ok, %{}})\n {:ok, %{\"reported_as\" => \"without-image\"}}\n \n iex> Slacktapped.Checkins.report_checkin_type({:ok, %{\n ...> \"media\" => %{\n ...> \"items\" => [\n ...> %{\n ...> \"photo\" => %{\n ...> \"photo_id\" => 987,\n ...> \"photo_img_lg\" => \"http:\/\/path\/to\/beer\/image\"\n ...> }\n ...> }\n ...> ]\n ...> }\n ...> }})\n {:ok, %{\n \"reported_as\" => \"with-image\",\n \"media\" => %{\n \"items\" => [\n %{\n \"photo\" => %{\n \"photo_id\" => 987,\n \"photo_img_lg\" => \"http:\/\/path\/to\/beer\/image\"\n }\n }\n ]\n }\n }}\n\n \"\"\"\n def report_checkin_type({:ok, checkin}) do\n checkin_id = checkin[\"checkin_id\"]\n media_items = checkin[\"media\"][\"items\"]\n has_image = is_list(media_items) and Enum.count(media_items) >= 1\n\n reported_as = cond do\n has_image == true ->\n @redis.command(\"SET #{@instance_name}:#{checkin_id}:with-image 1\")\n \"with-image\"\n true ->\n @redis.command(\"SET #{@instance_name}:#{checkin_id}:without-image 1\")\n \"without-image\"\n end\n\n checkin = Map.put(checkin, \"reported_as\", reported_as)\n\n {:ok, checkin}\n end\nend\n","old_contents":"defmodule Slacktapped.Checkins do\n @instance_name System.get_env(\"INSTANCE_NAME\") ||\n Application.get_env(:slacktapped, :instance_name)\n @redis Application.get_env(:slacktapped, :redis)\n\n @doc \"\"\"\n Processes a checkin for use in a Slack post:\n\n 1. Verifies the checkin is eligible to post.\n 2. Parses the checkin to a Slack attachment.\n 3. Adds the attachment to the checkin.\n 4. Reports the checkin post to Redis.\n \"\"\"\n def process_checkin(checkin) do\n with {:ok, checkin} <- is_eligible_checkin_post(checkin),\n {:ok, attachment} <- parse_checkin(checkin),\n {:ok, checkin} <- Slacktapped.add_attachment({:ok, attachment}, checkin),\n {:ok, checkin} <- report_checkin_type({:ok, checkin}),\n do: {:ok, checkin}\n end\n\n @doc \"\"\"\n Determines if a checkin is eligible to be posted to Slack.\n\n Checkin is ineligible to post if:\n\n 1. There is a Redis key indicating that this checkin was posted under this\n instance, and had an image with it.\n 2. There is a Redis key indicating that this checkin was posted under this\n instance, and had no image with it, but the checkin we see now still does\n not have an image.\n\n ## Examples\n\n A checkin that was not already posted:\n\n iex> Slacktapped.Checkins.is_eligible_checkin_post(%{\"checkin_id\" => 9985})\n {:ok, %{\"checkin_id\" => 9985}}\n\n A checkin that was already posted, and had an image:\n\n iex> Slacktapped.Checkins.is_eligible_checkin_post(%{\"checkin_id\" => 9988})\n {:error, %{\"checkin_id\" => 9988}}\n\n A checkin that was already posted and had no image, and we do not currently\n have an image:\n\n iex> Slacktapped.Checkins.is_eligible_checkin_post(%{\"beer\" => %{}, \"checkin_id\" => 5566})\n {:error, %{\"beer\" => %{}, \"checkin_id\" => 5566}}\n\n A checkin that was already posted and had no image, and we now have an\n image:\n\n iex> Slacktapped.Checkins.is_eligible_checkin_post(%{\n ...> \"beer\" => %{},\n ...> \"checkin_id\" => 5566,\n ...> \"media\" => %{\n ...> \"items\" => [\n ...> %{\n ...> \"photo\" => %{\n ...> \"photo_id\" => 987,\n ...> \"photo_img_lg\" => \"http:\/\/path\/to\/beer\/image\"\n ...> }\n ...> }\n ...> ]\n ...> }\n ...> })\n {:ok, %{\n \"beer\" => %{},\n \"checkin_id\" => 5566,\n \"media\" => %{\n \"items\" => [\n %{\n \"photo\" => %{\n \"photo_id\" => 987,\n \"photo_img_lg\" => \"http:\/\/path\/to\/beer\/image\"\n }\n }\n ]\n }\n }}\n\n \"\"\"\n def is_eligible_checkin_post(checkin) do\n checkin_id = checkin[\"checkin_id\"] || \"\"\n media_items = checkin[\"media\"][\"items\"]\n has_image = is_list(media_items) and Enum.count(media_items) >= 1\n get_key = \"GET #{@instance_name}:#{checkin_id}\"\n\n cond do\n @redis.command(\"#{get_key}:with-image\") == {:ok, \"1\"} ->\n {:error, checkin}\n @redis.command(\"#{get_key}:without-image\") == {:ok, \"1\"} and not has_image ->\n {:error, checkin}\n true ->\n {:ok, checkin}\n end\n end\n\n @doc ~S\"\"\"\n Parses a checkin into an attachment for Slack.\n\n ## Examples\n\n A typical checkin with a rating and comment:\n\n iex> Slacktapped.Checkins.parse_checkin(%{\n ...> \"attachments\" => [],\n ...> \"user\" => %{\n ...> \"user_name\" => \"nicksergeant\",\n ...> \"user_avatar\" => \"http:\/\/path\/to\/user\/avatar\"\n ...> },\n ...> \"beer\" => %{\n ...> \"bid\" => 123,\n ...> \"beer_abv\" => 4.5,\n ...> \"beer_label\" => \"http:\/\/path\/to\/beer\/label\",\n ...> \"beer_name\" => \"IPA\",\n ...> \"beer_slug\" => \"two-lake-ipa\",\n ...> \"beer_style\" => \"American IPA\"\n ...> },\n ...> \"brewery\" => %{\n ...> \"brewery_id\" => 1,\n ...> \"brewery_label\" => \"http:\/\/path\/to\/brewery\/label\",\n ...> \"brewery_name\" => \"Two Lake\"\n ...> },\n ...> \"checkin_comment\" => \"Lovely!\",\n ...> \"checkin_id\" => 567,\n ...> \"rating_score\" => 3.5\n ...> })\n {:ok,\n %{\n \"author_icon\" => \"http:\/\/path\/to\/user\/avatar\",\n \"author_link\" => \"https:\/\/untappd.com\/user\/nicksergeant\",\n \"author_name\" => \"nicksergeant\",\n \"color\" => \"#FFCF0B\",\n \"fallback\" => \"Image of this checkin.\",\n \"footer\" => \"\",\n \"footer_icon\" => \"http:\/\/path\/to\/brewery\/label\",\n \"image_url\" => \"http:\/\/path\/to\/beer\/label\",\n \"text\" => \"\" <>\n \" is drinking \" <>\n \" \" <>\n \"(American IPA, 4.5% ABV).\" <>\n \"\\nThey rated it a 3.5 and said \\\"Lovely!\\\"\\n\" <>\n \"\",\n \"title\" => \"IPA\",\n \"title_link\" => \"https:\/\/untappd.com\/b\/two-lake-ipa\/123\"\n }\n }\n\n A checkin without a rating:\n\n iex> Slacktapped.Checkins.parse_checkin(%{\n ...> \"attachments\" => [],\n ...> \"checkin_comment\" => \"Lovely!\"\n ...> })\n {:ok,\n %{\n \"author_icon\" => nil,\n \"author_link\" => \"https:\/\/untappd.com\/user\/\",\n \"author_name\" => nil,\n \"color\" => \"#FFCF0B\",\n \"fallback\" => \"Image of this checkin.\",\n \"footer\" => \"\",\n \"footer_icon\" => nil,\n \"image_url\" => nil,\n \"text\" => \"\" <>\n \" is drinking \" <>\n \" (, % ABV).\" <>\n \"\\nThey said \\\"Lovely!\\\"\\n\" <>\n \"\",\n \"title\" => nil,\n \"title_link\" => \"https:\/\/untappd.com\/b\/\/\"\n }\n }\n\n A checkin without a comment:\n\n iex> Slacktapped.Checkins.parse_checkin(%{\"rating_score\" => 1.5})\n {:ok,\n %{\n \"author_icon\" => nil,\n \"author_link\" => \"https:\/\/untappd.com\/user\/\",\n \"author_name\" => nil,\n \"color\" => \"#FFCF0B\",\n \"fallback\" => \"Image of this checkin.\",\n \"footer\" => \"\",\n \"footer_icon\" => nil,\n \"image_url\" => nil,\n \"text\" => \"\" <>\n \" is drinking \" <>\n \" (, % ABV).\" <>\n \"\\nThey rated it a 1.5.\\n\" <>\n \"\",\n \"title\" => nil,\n \"title_link\" => \"https:\/\/untappd.com\/b\/\/\"\n }\n }\n\n A checkin without a comment or rating:\n\n iex> Slacktapped.Checkins.parse_checkin(%{})\n {:ok,\n %{\n \"author_icon\" => nil,\n \"author_link\" => \"https:\/\/untappd.com\/user\/\",\n \"author_name\" => nil,\n \"color\" => \"#FFCF0B\",\n \"fallback\" => \"Image of this checkin.\",\n \"footer\" => \"\",\n \"footer_icon\" => nil,\n \"image_url\" => nil,\n \"text\" => \"\" <>\n \" is drinking \" <>\n \" (, % ABV).\\n\" <>\n \"\",\n \"title\" => nil,\n \"title_link\" => \"https:\/\/untappd.com\/b\/\/\"\n }\n }\n\n A checkin with an image:\n\n iex> Slacktapped.Checkins.parse_checkin(%{\n ...> \"media\" => %{\n ...> \"items\" => [\n ...> %{\n ...> \"photo\" => %{\n ...> \"photo_id\" => 987,\n ...> \"photo_img_lg\" => \"http:\/\/path\/to\/beer\/image\"\n ...> }\n ...> }\n ...> ]\n ...> }\n ...> })\n {:ok,\n %{\n \"author_icon\" => nil,\n \"author_link\" => \"https:\/\/untappd.com\/user\/\",\n \"author_name\" => nil,\n \"color\" => \"#FFCF0B\",\n \"fallback\" => \"Image of this checkin.\",\n \"footer\" => \"\",\n \"footer_icon\" => nil,\n \"image_url\" => \"http:\/\/path\/to\/beer\/image\",\n \"text\" => \"\" <>\n \" is drinking \" <>\n \" (, % ABV).\\n\" <>\n \"\",\n \"title\" => nil,\n \"title_link\" => \"https:\/\/untappd.com\/b\/\/\"\n }\n }\n\n A checkin with a venue:\n\n iex> Slacktapped.Checkins.parse_checkin(%{\n ...> \"attachments\" => [],\n ...> \"venue\" => %{\n ...> \"venue_id\" => 789,\n ...> \"venue_name\" => \"Venue Name\",\n ...> \"venue_slug\" => \"venue-slug\"\n ...> }\n ...> })\n {:ok,\n %{\n \"author_icon\" => nil,\n \"author_link\" => \"https:\/\/untappd.com\/user\/\",\n \"author_name\" => nil,\n \"color\" => \"#FFCF0B\",\n \"fallback\" => \"Image of this checkin.\",\n \"footer\" => \"\",\n \"footer_icon\" => nil,\n \"image_url\" => nil,\n \"text\" => \"\" <>\n \" is drinking \" <>\n \" (, % ABV) \" <>\n \"at .\\n\" <>\n \"\",\n \"title\" => nil,\n \"title_link\" => \"https:\/\/untappd.com\/b\/\/\"\n }\n }\n\n A checkin with an image, with a previously-posted checkin with no image:\n\n iex> Slacktapped.Checkins.parse_checkin(%{\n ...> \"checkin_id\" => 5566,\n ...> \"media\" => %{\n ...> \"items\" => [\n ...> %{\n ...> \"photo\" => %{\n ...> \"photo_id\" => 987,\n ...> \"photo_img_lg\" => \"http:\/\/path\/to\/beer\/image\"\n ...> }\n ...> }\n ...> ]\n ...> }\n ...> })\n {:ok,\n %{\n \"author_icon\" => nil,\n \"author_link\" => \"https:\/\/untappd.com\/user\/\",\n \"author_name\" => nil,\n \"color\" => \"#FFCF0B\",\n \"fallback\" => \"Image of this checkin.\",\n \"footer\" => \"\",\n \"footer_icon\" => nil,\n \"image_url\" => \"http:\/\/path\/to\/beer\/image\",\n \"text\" => \"\" <>\n \" added an image to \" <>\n \" of \" <>\n \".\",\n \"title\" => nil,\n \"title_link\" => \"https:\/\/untappd.com\/b\/\/\"\n }\n }\n\n The default Untappd beer label is ignored:\n\n iex> Slacktapped.Checkins.parse_checkin(%{\n ...> \"attachments\" => [],\n ...> \"beer\" => %{\n ...> \"beer_label\" => \"https:\/\/untappd.akamaized.net\/site\/assets\/images\/temp\/badge-beer-default.png\"\n ...> }\n ...> })\n {:ok,\n %{\n \"author_icon\" => nil,\n \"author_link\" => \"https:\/\/untappd.com\/user\/\",\n \"author_name\" => nil,\n \"color\" => \"#FFCF0B\",\n \"fallback\" => \"Image of this checkin.\",\n \"footer\" => \"\",\n \"footer_icon\" => nil,\n \"image_url\" => \"\",\n \"text\" => \"\" <>\n \" is drinking \" <>\n \" (, % ABV).\\n\" <>\n \"\",\n \"title\" => nil,\n \"title_link\" => \"https:\/\/untappd.com\/b\/\/\"\n }\n }\n\n \"\"\"\n def parse_checkin(checkin) do\n {:ok, user_name} = Slacktapped.parse_name(checkin[\"user\"])\n\n beer_abv = checkin[\"beer\"][\"beer_abv\"]\n beer_id = checkin[\"beer\"][\"bid\"]\n beer_label = checkin[\"beer\"][\"beer_label\"]\n beer_name = checkin[\"beer\"][\"beer_name\"]\n beer_slug = checkin[\"beer\"][\"beer_slug\"]\n beer_style = checkin[\"beer\"][\"beer_style\"]\n brewery_id = checkin[\"brewery\"][\"brewery_id\"]\n brewery_name = checkin[\"brewery\"][\"brewery_name\"]\n brewery_label = checkin[\"brewery\"][\"brewery_label\"]\n checkin_comment = checkin[\"checkin_comment\"]\n checkin_id = checkin[\"checkin_id\"]\n checkin_rating = checkin[\"rating_score\"]\n media_items = checkin[\"media\"][\"items\"]\n user_avatar = checkin[\"user\"][\"user_avatar\"]\n user_username = checkin[\"user\"][\"user_name\"]\n\n beer = \"\"\n toast = \"\"\n user = \"\"\n\n rating_and_comment = cond do\n is_binary(checkin_comment)\n and checkin_comment != \"\"\n and is_number(checkin_rating) -> \n \"\\nThey rated it a #{checkin_rating} and said \\\"#{checkin_comment}\\\"\"\n is_binary(checkin_comment)\n and checkin_comment != \"\" ->\n \"\\nThey said \\\"#{checkin_comment}\\\"\"\n is_number(checkin_rating) ->\n \"\\nThey rated it a #{checkin_rating}.\"\n true -> \"\"\n end\n\n venue = if is_map(checkin[\"venue\"]) do\n venue_id = checkin[\"venue\"][\"venue_id\"]\n venue_name = checkin[\"venue\"][\"venue_name\"]\n venue_slug = checkin[\"venue\"][\"venue_slug\"]\n \" at \"\n end\n\n image_url = cond do\n is_list(media_items) and Enum.count(media_items) >= 1 ->\n media_items\n |> Enum.at(0)\n |> get_in([\"photo\", \"photo_img_lg\"])\n beer_label != \"https:\/\/untappd.akamaized.net\/site\/assets\/images\/temp\/badge-beer-default.png\" ->\n beer_label\n true -> \"\"\n end\n\n # If we have an image and there was already a post for this checkin\n # *without* an image, only indicate that an image was added.\n cmd = \"GET #{@instance_name}:#{checkin_id}:without-image\"\n text = if is_binary(image_url) and\n @redis.command(cmd) == {:ok, \"1\"} do\n \"#{user} added an image to \" <>\n \"\n \"their checkin> of #{beer}.\"\n else\n \"#{user} is drinking #{beer} (#{beer_style}, #{beer_abv}% ABV)\" <>\n \"#{venue}.#{rating_and_comment}\\n#{toast}\"\n end\n\n {:ok, %{\n \"author_icon\" => user_avatar,\n \"author_link\" => \"https:\/\/untappd.com\/user\/#{user_username}\",\n \"author_name\" => user_username,\n \"color\" => \"#FFCF0B\",\n \"fallback\" => \"Image of this checkin.\",\n \"footer\" => \"\",\n \"footer_icon\" => brewery_label,\n \"image_url\" => image_url,\n \"text\" => text,\n \"title\" => beer_name,\n \"title_link\" => \"https:\/\/untappd.com\/b\/#{beer_slug}\/#{beer_id}\"\n }}\n end\n\n @doc \"\"\"\n Reports that a checkin was posted to Slack by setting a Redis key. There are\n two possible Redis keys indicating a post was made:\n\n 1. ::with-image\n 2. ::without-image\n\n Already-posted checkins that were previously posted without an image are\n posted again indicating that the user added an image to the checkin. If a\n record exists for the checkin with an image, the checkin is not posted again.\n\n Examples\n \n iex> Slacktapped.Checkins.report_checkin_type({:ok, %{}})\n {:ok, %{\"reported_as\" => \"without-image\"}}\n \n iex> Slacktapped.Checkins.report_checkin_type({:ok, %{\n ...> \"media\" => %{\n ...> \"items\" => [\n ...> %{\n ...> \"photo\" => %{\n ...> \"photo_id\" => 987,\n ...> \"photo_img_lg\" => \"http:\/\/path\/to\/beer\/image\"\n ...> }\n ...> }\n ...> ]\n ...> }\n ...> }})\n {:ok, %{\n \"reported_as\" => \"with-image\",\n \"media\" => %{\n \"items\" => [\n %{\n \"photo\" => %{\n \"photo_id\" => 987,\n \"photo_img_lg\" => \"http:\/\/path\/to\/beer\/image\"\n }\n }\n ]\n }\n }}\n\n \"\"\"\n def report_checkin_type({:ok, checkin}) do\n checkin_id = checkin[\"checkin_id\"]\n media_items = checkin[\"media\"][\"items\"]\n has_image = is_list(media_items) and Enum.count(media_items) >= 1\n\n reported_as = cond do\n has_image == true ->\n @redis.command(\"SET #{@instance_name}:#{checkin_id}:with-image 1\")\n \"with-image\"\n true ->\n @redis.command(\"SET #{@instance_name}:#{checkin_id}:without-image 1\")\n \"without-image\"\n end\n\n checkin = Map.put(checkin, \"reported_as\", reported_as)\n\n {:ok, checkin}\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"c5059db427fc1f04f5347c72181c9470ba69e211","subject":"Remove trailing whitespace","message":"Remove trailing whitespace\n","repos":"danielberkompas\/ex_twiml","old_file":"lib\/ex_twiml.ex","new_file":"lib\/ex_twiml.ex","new_contents":"defmodule ExTwiml do\n @moduledoc \"\"\"\n Contains macros to make generating TwiML from Elixir far easier and more\n efficient. Just `import ExTwiml` and go!\n\n ## Examples\n\n How to generate nested verbs, such as ``:\n\n # Options are passed before \"do\"\n gather digits: 1, finish_on_key: \"#\" do\n # More verbs here ...\n end\n\n # Generates\n <\/Gather>\n\n How to generate simpler verbs, such as ``:\n\n # Options are passed as the second argument\n say \"words to say\", voice: \"woman\"\n\n # Generates\n words to say<\/Say>\n\n How to generate command verbs, like `` or ``:\n\n # If the verb has no attributes, just write the name\n # of the verb:\n leave\n\n # Generates\n \n\n # If the verb has attributes, like , write them\n # after the name of the verb:\n pause length: 5\n\n # Generates\n \n\n A complete example:\n\n import ExTwiml\n\n twiml do\n play \"\/assets\/welcome.mp3\"\n gather digits: 1 do\n say \"For more menus, please press 1.\", voice: \"woman\"\n say \"To speak with a real person, please press 2.\", voice: \"woman\"\n end\n end\n\n Produces the following `string`:\n\n \n \n \/assets\/welcome.mp3<\/Play>\n \n For more menus, please press 1.<\/Say>\n To speak with a real person, please press 2.<\/Say>\n <\/Gather>\n <\/Response>\n\n You'd then need to render this string to the browser.\n \"\"\"\n\n import ExTwiml.Utilities\n\n alias ExTwiml.ReservedNameError\n\n @verbs [\n # Nested\n :gather, :dial, :message,\n\n # Non-nested\n :say, :number, :play, :sms, :sip, :client, :conference, :queue, :enqueue,\n :leave, :hangup, :reject, :pause, :record, :redirect, :body, :media\n ]\n\n @doc \"\"\"\n Start creating a TwiML document. Returns the rendered TwiML as a string.\n See the `ExTwiml` documentation to see how to call TwiML verbs from within\n the `twiml\/1` macro.\n\n ## Example\n\n iex> import ExTwiml\n ...> twiml do\n ...> say \"Hello World\"\n ...> end\n \"Hello World<\/Say><\/Response>\"\n \"\"\"\n defmacro twiml(do: block) do\n quote do\n header = \"\"\n\n # Create an Agent to store the buffer results, using var! to allow us to \n # continue to be able to update the buffer through multiple macros.\n # \n # The buffer's state is a list of XML fragments. New fragments are \n # inserted by other macros. Finally, all the fragments are joined\n # together in a string.\n {:ok, var!(buffer, Twiml)} = start_buffer([header])\n\n # Wrap the whole block in a tag\n tag :response do\n # Postwalk the AST, expanding all of the TwiML verbs into proper\n # `tag` and `text` macros. This gives the impression that there\n # is a macro for each verb, when in fact it all expands to only\n # two macros.\n unquote(block\n |> Macro.prewalk(&prewalk(&1, __CALLER__.file))\n |> Macro.postwalk(&postwalk\/1))\n end\n\n xml = render(var!(buffer, Twiml)) # Convert buffer to string\n :ok = stop_buffer(var!(buffer, Twiml)) # Kill the Agent\n\n xml # Return our pretty TwiML!\n end\n end\n\n @doc \"\"\"\n Use this macro to generate a tag not yet supported by this Twiml library. Note\n that you'll also need to use the `text` macro to include text within this tag.\n\n ## Examples\n\n tag :mms, to: \"1112223333\", from: \"2223334444\" do\n text \"How are you doing?\"\n end\n\n Will produce the following Twiml:\n\n How are you doing?<\/Mms>\n \"\"\"\n defmacro tag(name, options \\\\ [], do: inner) do\n quote do\n put_buffer var!(buffer, Twiml), create_tag(:opening, unquote(name), unquote(options))\n unquote(inner)\n put_buffer var!(buffer, Twiml), create_tag(:closing, unquote(name))\n end\n end\n\n @doc \"\"\"\n Adds whatever text is given to the current Twiml buffer, unmodified. As a\n result, this macro is really only useful when nested inside one of the other\n macros provided by this module.\n \"\"\"\n defmacro text(string) do\n quote do\n put_buffer var!(buffer, Twiml), to_string(unquote(string))\n end\n end\n\n @doc \"Start an Agent to store a given buffer state.\"\n @spec start_buffer(list) :: {:ok, pid}\n def start_buffer(state), do: Agent.start_link(fn -> state end)\n\n @doc \"Stop a buffer.\"\n @spec stop_buffer(pid) :: atom\n def stop_buffer(buff), do: Agent.stop(buff)\n\n @doc \"Update the buffer by pushing a new tag onto the beginning.\"\n @spec put_buffer(pid, any) :: atom\n def put_buffer(buff, content), do: Agent.update(buff, &[content | &1])\n\n @doc \"Get the current state of a buffer.\"\n @spec get_buffer(pid) :: list\n def get_buffer(buff), do: Agent.get(buff, &(&1)) |> Enum.reverse\n\n @doc \"Render the contents of the buffer into a string.\"\n @spec render(pid) :: String.t\n def render(buff), do: Agent.get(buff, &(&1)) |> Enum.reverse |> Enum.join\n\n ##\n # Private API\n ##\n\n # Check function definitions for reserved variable names\n defp prewalk({:fn, _, [{:-> , _, [[vars], _]}]} = ast, file_name) do\n assert_no_verbs!(vars, file_name)\n ast\n end\n\n defp prewalk(ast, _file_name), do: ast\n\n # {:text, [], [\"Hello World\"]}\n defp postwalk({:text, _meta, [string]}) do\n # Just add the text to the buffer. Nothing else needed.\n quote do: put_buffer(var!(buffer, Twiml), to_string(unquote(string)))\n end\n\n # {:gather, [], [[do: inner]]}\n defp postwalk({verb, _meta, [[do: inner]]}) when verb in @verbs do\n compile_nested(verb, [], inner)\n end\n\n # {:gather, [], [finish_on_key: \"#\", [do: inner]]}\n defp postwalk({verb, _meta, [options, [do: inner]]}) when verb in @verbs do\n compile_nested(verb, options, inner)\n end\n\n # {:say, [], [\"Hello World\", [voice: \"woman\"]}\n defp postwalk({verb, _meta, [string, options]}) when verb in @verbs and is_list(options) do\n compile_simple(verb, string, options)\n end\n\n # {:pause, [], [[length: 5]]}\n defp postwalk({verb, _meta, [options]}) when verb in @verbs and is_list(options) do\n compile_empty(verb, options)\n end\n\n # {:say, [], [\"Hello World\"]}\n # {:say, [], [\"Hello #{var}\"]} (String interpolation)\n defp postwalk({verb, _meta, [string]}) when verb in @verbs do\n compile_simple(verb, string)\n end\n\n # {:leave, [], Elixir}\n defp postwalk({verb, _meta, _args}) when verb in @verbs do\n compile_empty(verb)\n end\n\n # Don't modify any other ASTs.\n defp postwalk(ast), do: ast\n\n # For nested verbs, such as \n defp compile_nested(verb, options, inner) do\n quote do\n tag unquote(verb), unquote(options) do\n unquote(inner)\n end\n end\n end\n\n # For simple verbs, such as \n defp compile_simple(verb, string, options \\\\ []) do\n quote do\n tag unquote(verb), unquote(options) do\n text unquote(string)\n end\n end\n end\n\n # For verbs without content, like or \n defp compile_empty(verb, options \\\\ []) do\n quote do\n # Render only a single tag, with options\n put_buffer var!(buffer, Twiml), create_tag(:self_closed, unquote(verb), unquote(options))\n end\n end\n\n defp assert_no_verbs!({name, _, _} = var, file_name)\n when is_atom(name) and name in @verbs do\n raise ReservedNameError, [var, file_name]\n end\n\n defp assert_no_verbs!(vars, file_name) when is_tuple(elem(vars, 0)) do\n vars\n |> Tuple.to_list\n |> Enum.each(&assert_no_verbs!(&1, file_name))\n end\n\n defp assert_no_verbs!(vars, _file_name), do: vars\nend\n","old_contents":"defmodule ExTwiml do\n @moduledoc \"\"\"\n Contains macros to make generating TwiML from Elixir far easier and more \n efficient. Just `import ExTwiml` and go!\n\n ## Examples\n\n How to generate nested verbs, such as ``:\n\n # Options are passed before \"do\"\n gather digits: 1, finish_on_key: \"#\" do\n # More verbs here ...\n end\n\n # Generates\n <\/Gather>\n\n How to generate simpler verbs, such as ``:\n\n # Options are passed as the second argument\n say \"words to say\", voice: \"woman\"\n\n # Generates\n words to say<\/Say>\n\n How to generate command verbs, like `` or ``:\n \n # If the verb has no attributes, just write the name\n # of the verb:\n leave\n\n # Generates\n \n\n # If the verb has attributes, like , write them\n # after the name of the verb:\n pause length: 5\n\n # Generates\n \n\n A complete example:\n\n import ExTwiml\n\n twiml do\n play \"\/assets\/welcome.mp3\"\n gather digits: 1 do\n say \"For more menus, please press 1.\", voice: \"woman\"\n say \"To speak with a real person, please press 2.\", voice: \"woman\"\n end\n end\n\n Produces the following `string`:\n\n \n \n \/assets\/welcome.mp3<\/Play>\n \n For more menus, please press 1.<\/Say>\n To speak with a real person, please press 2.<\/Say>\n <\/Gather>\n <\/Response>\n\n You'd then need to render this string to the browser.\n \"\"\"\n\n import ExTwiml.Utilities\n\n alias ExTwiml.ReservedNameError\n\n @verbs [ \n # Nested\n :gather, :dial, :message, \n\n # Non-nested\n :say, :number, :play, :sms, :sip, :client, :conference, :queue, :enqueue, \n :leave, :hangup, :reject, :pause, :record, :redirect, :body, :media\n ]\n\n @doc \"\"\"\n Start creating a TwiML document. Returns the rendered TwiML as a string.\n See the `ExTwiml` documentation to see how to call TwiML verbs from within\n the `twiml\/1` macro.\n\n ## Example\n\n iex> import ExTwiml\n ...> twiml do\n ...> say \"Hello World\"\n ...> end\n \"Hello World<\/Say><\/Response>\"\n \"\"\"\n defmacro twiml(do: block) do\n quote do\n header = \"\"\n\n # Create an Agent to store the buffer results, using var! to allow us to \n # continue to be able to update the buffer through multiple macros.\n # \n # The buffer's state is a list of XML fragments. New fragments are \n # inserted by other macros. Finally, all the fragments are joined\n # together in a string.\n {:ok, var!(buffer, Twiml)} = start_buffer([header])\n\n # Wrap the whole block in a tag\n tag :response do\n # Postwalk the AST, expanding all of the TwiML verbs into proper\n # `tag` and `text` macros. This gives the impression that there\n # is a macro for each verb, when in fact it all expands to only\n # two macros.\n unquote(block\n |> Macro.prewalk(&prewalk(&1, __CALLER__.file))\n |> Macro.postwalk(&postwalk\/1))\n end\n\n xml = render(var!(buffer, Twiml)) # Convert buffer to string\n :ok = stop_buffer(var!(buffer, Twiml)) # Kill the Agent\n\n xml # Return our pretty TwiML!\n end\n end\n\n @doc \"\"\"\n Use this macro to generate a tag not yet supported by this Twiml library. Note\n that you'll also need to use the `text` macro to include text within this tag.\n\n ## Examples\n\n tag :mms, to: \"1112223333\", from: \"2223334444\" do\n text \"How are you doing?\"\n end\n\n Will produce the following Twiml:\n\n How are you doing?<\/Mms>\n \"\"\"\n defmacro tag(name, options \\\\ [], do: inner) do\n quote do\n put_buffer var!(buffer, Twiml), create_tag(:opening, unquote(name), unquote(options))\n unquote(inner)\n put_buffer var!(buffer, Twiml), create_tag(:closing, unquote(name))\n end\n end\n\n @doc \"\"\"\n Adds whatever text is given to the current Twiml buffer, unmodified. As a\n result, this macro is really only useful when nested inside one of the other\n macros provided by this module.\n \"\"\"\n defmacro text(string) do\n quote do\n put_buffer var!(buffer, Twiml), to_string(unquote(string))\n end\n end\n\n @doc \"Start an Agent to store a given buffer state.\"\n @spec start_buffer(list) :: {:ok, pid}\n def start_buffer(state), do: Agent.start_link(fn -> state end)\n\n @doc \"Stop a buffer.\"\n @spec stop_buffer(pid) :: atom\n def stop_buffer(buff), do: Agent.stop(buff)\n\n @doc \"Update the buffer by pushing a new tag onto the beginning.\"\n @spec put_buffer(pid, any) :: atom\n def put_buffer(buff, content), do: Agent.update(buff, &[content | &1])\n\n @doc \"Get the current state of a buffer.\"\n @spec get_buffer(pid) :: list\n def get_buffer(buff), do: Agent.get(buff, &(&1)) |> Enum.reverse\n\n @doc \"Render the contents of the buffer into a string.\"\n @spec render(pid) :: String.t\n def render(buff), do: Agent.get(buff, &(&1)) |> Enum.reverse |> Enum.join\n\n ##\n # Private API\n ##\n\n # Check function definitions for reserved variable names\n defp prewalk({:fn, _, [{:-> , _, [[vars], _]}]} = ast, file_name) do\n assert_no_verbs!(vars, file_name)\n ast\n end\n\n defp prewalk(ast, _file_name), do: ast\n\n # {:text, [], [\"Hello World\"]}\n defp postwalk({:text, _meta, [string]}) do\n # Just add the text to the buffer. Nothing else needed.\n quote do: put_buffer(var!(buffer, Twiml), to_string(unquote(string)))\n end\n\n # {:gather, [], [[do: inner]]}\n defp postwalk({verb, _meta, [[do: inner]]}) when verb in @verbs do\n compile_nested(verb, [], inner)\n end\n\n # {:gather, [], [finish_on_key: \"#\", [do: inner]]}\n defp postwalk({verb, _meta, [options, [do: inner]]}) when verb in @verbs do\n compile_nested(verb, options, inner)\n end\n\n # {:say, [], [\"Hello World\", [voice: \"woman\"]}\n defp postwalk({verb, _meta, [string, options]}) when verb in @verbs and is_list(options) do\n compile_simple(verb, string, options)\n end\n\n # {:pause, [], [[length: 5]]}\n defp postwalk({verb, _meta, [options]}) when verb in @verbs and is_list(options) do\n compile_empty(verb, options)\n end\n\n # {:say, [], [\"Hello World\"]}\n # {:say, [], [\"Hello #{var}\"]} (String interpolation)\n defp postwalk({verb, _meta, [string]}) when verb in @verbs do\n compile_simple(verb, string)\n end\n\n # {:leave, [], Elixir}\n defp postwalk({verb, _meta, _args}) when verb in @verbs do\n compile_empty(verb)\n end\n\n # Don't modify any other ASTs.\n defp postwalk(ast), do: ast\n\n # For nested verbs, such as \n defp compile_nested(verb, options, inner) do\n quote do\n tag unquote(verb), unquote(options) do\n unquote(inner)\n end\n end\n end\n\n # For simple verbs, such as \n defp compile_simple(verb, string, options \\\\ []) do\n quote do\n tag unquote(verb), unquote(options) do\n text unquote(string)\n end\n end\n end\n\n # For verbs without content, like or \n defp compile_empty(verb, options \\\\ []) do\n quote do\n # Render only a single tag, with options\n put_buffer var!(buffer, Twiml), create_tag(:self_closed, unquote(verb), unquote(options))\n end\n end\n\n defp assert_no_verbs!({name, _, _} = var, file_name)\n when is_atom(name) and name in @verbs do\n raise ReservedNameError, [var, file_name]\n end\n\n defp assert_no_verbs!(vars, file_name) when is_tuple(elem(vars, 0)) do\n vars\n |> Tuple.to_list\n |> Enum.each(&assert_no_verbs!(&1, file_name))\n end\n\n defp assert_no_verbs!(vars, _file_name), do: vars\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"2c23c09e5ab5f3f2343089ca5bf071ec2c650fc9","subject":"Note that handlers are run by monitor processes (#86)","message":"Note that handlers are run by monitor processes (#86)\n\n","repos":"koudelka\/honeydew","old_file":"lib\/honeydew.ex","new_file":"lib\/honeydew.ex","new_contents":"defmodule Honeydew do\n @moduledoc \"\"\"\n A pluggable job queue + worker pool for Elixir.\n \"\"\"\n\n alias Honeydew.Job\n alias Honeydew.JobMonitor\n alias Honeydew.Worker\n alias Honeydew.WorkerStarter\n alias Honeydew.WorkerGroupSupervisor\n alias Honeydew.Queue\n alias Honeydew.{Queues, Workers}\n require Logger\n\n @type mod_or_mod_args :: module | {module, args :: term}\n @type queue_name :: String.t | atom | {:global, String.t | atom}\n @type supervisor_opts :: Keyword.t\n @type async_opt :: {:reply, true} | {:delay_secs, pos_integer()}\n @type task :: {atom, [arg :: term]}\n @type filter :: (Job.t -> boolean) | atom\n\n @typedoc \"\"\"\n Result of a `Honeydew.Job`\n \"\"\"\n @type result :: term\n\n #\n # Parts of this module were lovingly stolen from\n # https:\/\/github.com\/elixir-lang\/elixir\/blob\/v1.3.2\/lib\/elixir\/lib\/task.ex#L320\n #\n\n @doc \"\"\"\n Runs a task asynchronously.\n\n Raises a `RuntimeError` if `queue` process is not available.\n\n You can provide any of the following `opts`:\n\n - `reply`: returns the result of the job via `yield\/1`, see below.\n - `delay_secs`: delays the execution of the job by the provided number of seconds.\n\n ## Examples\n\n To run a task asynchronously:\n\n Honeydew.async({:ping, [\"127.0.0.1\"]}, :my_queue)\n\n To run a task asynchronously and wait for result:\n\n # Without pipes\n job = Honeydew.async({:ping, [\"127.0.0.1\"]}, :my_queue, reply: true)\n Honeydew.yield(job)\n\n # With pipes\n :pong =\n {:ping, [\"127.0.0.1\"]}\n |> Honeydew.async(:my_queue, reply: true)\n |> Honeydew.yield()\n\n To run a task an hour later:\n\n Honeydew.async({:ping, [\"127.0.0.1\"]}, :my_queue, delay_secs: 60*60)\n \"\"\"\n @spec async(task, queue_name, [async_opt]) :: Job.t | no_return\n def async(task, queue, opts \\\\ []) do\n job = Job.new(task, queue)\n\n {:ok, job} =\n opts\n |> Enum.reduce(job, fn\n {:reply, true}, job ->\n %Job{job | from: {self(), make_ref()}}\n\n {:delay_secs, secs}, job when is_integer(secs) and secs >= 0 ->\n %Job{job | delay_secs: secs}\n\n {:delay_secs, thing}, job ->\n raise ArgumentError, invalid_delay_secs_error(job, thing)\n end)\n |> enqueue\n\n job\n end\n\n @doc \"\"\"\n Wait for a job to complete and return result.\n\n Returns the result of a job, or `nil` on timeout. Raises an `ArgumentError` if\n the job was not created with `reply: true` and in the current process.\n\n ## Example\n\n Calling `yield\/2` with different timeouts.\n\n iex> job = Honeydew.async({:ping, [\"127.0.0.1\"]}, :my_queue, reply: true)\n iex> Honeydew.yield(job, 500) # Wait half a second\n nil\n # Result comes in at 1 second\n iex> Honeydew.yield(job, 1000) # Wait up to a second\n {:ok, :pong}\n iex> Honeydew.yield(job, 0)\n nil # <- because the message has already arrived and been handled\n\n The only time `yield\/2` would ever return the result more than once is if\n the job executes more than once (as Honeydew aims for at-least-once\n execution).\n \"\"\"\n @spec yield(Job.t, timeout) :: {:ok, result} | nil | no_return\n def yield(job, timeout \\\\ 5000)\n def yield(%Job{from: nil} = job, _), do: raise ArgumentError, reply_not_requested_error(job)\n def yield(%Job{from: {owner, _}} = job, _) when owner != self(), do: raise ArgumentError, invalid_owner_error(job)\n\n def yield(%Job{from: {_, ref}}, timeout) do\n receive do\n %Job{from: {_, ^ref}, result: result} ->\n result # may be {:ok, term} or {:exit, term}\n after\n timeout ->\n nil\n end\n end\n\n @doc \"\"\"\n Suspends job processing for a queue.\n \"\"\"\n @spec suspend(queue_name) :: :ok\n def suspend(queue) do\n queue\n |> get_all_members(Queues)\n |> Enum.each(&Queue.suspend\/1)\n end\n\n @doc \"\"\"\n Resumes job processing for a queue.\n \"\"\"\n @spec resume(queue_name) :: :ok\n def resume(queue) do\n queue\n |> get_all_members(Queues)\n |> Enum.each(&Queue.resume\/1)\n end\n\n\n\n @doc \"\"\"\n Returns the currrent status of the queue and all attached workers.\n\n You can provide any of the following `opts`:\n\n - `timeout`: specifies the time (in miliseconds) the calling process will wait for the queue to return the status,\n note that this timeout does not cancel the status callback execution in the queue.\n \"\"\"\n @type status_opt :: {:timeout, pos_integer}\n @spec status(queue_name, [status_opt]) :: map()\n def status(queue, opts \\\\ []) do\n queue_status =\n queue\n |> get_queue\n |> Queue.status(opts)\n\n busy_workers =\n queue_status\n |> Map.get(:job_monitors)\n |> Enum.map(fn monitor ->\n try do\n JobMonitor.status(monitor)\n catch\n # the monitor may have shut down\n :exit, _ -> nil\n end\n end)\n |> Enum.reject(&(!&1))\n |> Enum.into(%{})\n\n workers =\n queue\n |> get_all_members(Workers)\n |> Enum.map(&{&1, nil})\n |> Enum.into(%{})\n |> Map.merge(busy_workers)\n\n %{queue: Map.delete(queue_status, :job_monitors), workers: workers}\n end\n\n @doc \"\"\"\n Filters the jobs currently on the queue.\n\n Filtration support depends on the queue implementation.\n\n ErlangQueue and Mnesia queues support filtering with functions.\n\n Ecto Poll Queues have pre-defined, named filters. At the moment, only `:abandoned` is implemented.\n\n Note:\n - This function returns a `List`, not a `Stream`, so calling it can be memory intensive when invoked on a large queue.\n - The filtration is done by the queue process, not the client, so a heavy filter will tie up the queue.\n\n ## Examples\n\n Filter jobs with a specific task.\n\n Honeydew.filter(:my_queue, &match?(%Honeydew.Job{task: {:ping, _}}, &1)) # ErlangQueue or Mnesia\n\n Honeydew.filter(:my_queue, %{task: {:ping, [\"127.0.0.1\"]}}) # Mnesia\n\n Honeydew.filter(:my_queue, :abandoned) # Ecto queue\n\n Return all jobs.\n\n Honeydew.filter(:my_queue, fn _ -> true end)\n \"\"\"\n @spec filter(queue_name, filter) :: [Job.t]\n def filter(queue, filter) do\n {:ok, jobs} =\n queue\n |> get_queue\n |> Queue.filter(filter)\n\n jobs\n end\n\n @doc \"\"\"\n Cancels a job.\n\n The return value depends on the status of the job.\n\n * `:ok` - Job had not been started and was able to be cancelled.\n * `{:error, :in_progress}` - Job was in progress and unable to be cancelled.\n * `{:error, :not_found}` - Job was not found on the queue (or already processed) and was unable to be cancelled.\n \"\"\"\n @spec cancel(Job.t) :: :ok | {:error, :in_progress} | {:error, :not_found}\n def cancel(%Job{queue: queue} = job) do\n queue\n |> get_queue\n |> Queue.cancel(job)\n end\n\n @doc \"\"\"\n Cancels the job associated with the first argument.\n\n For example, for the Ecto Poll Queue, the first argument is the value of an ID from your schema.\n\n The return value depends on the status of the job.\n\n * `:ok` - Job had not been started and was able to be cancelled.\n * `{:error, :in_progress}` - Job was in progress and unable to be cancelled, the Ecto Poll Queue does not support this return.\n * `{:error, :not_found}` - Job was not found on the queue (or already processed) and was unable to be cancelled.\n \"\"\"\n @spec cancel(Job.private(), queue_name) :: :ok | {:error, :in_progress} | {:error, :not_found}\n def cancel(private, queue) do\n %Job{private: private, queue: queue} |> cancel\n end\n\n @doc \"\"\"\n Moves a job to another queue.\n\n Raises a `RuntimeError` if `to_queue` is not available.\n\n This function first enqueues the job on `to_queue`, and then tries to\n cancel it on its current queue. This means there's a possiblity a job could\n be processed on both queues. This behavior is consistent with Honeydew's\n at-least-once execution goal.\n\n This function is most helpful on a queue where there a no workers\n (like a dead letter queue), because the job won't be processed out from under\n the queue.\n \"\"\"\n @spec move(Job.t, to_queue :: queue_name) :: Job.t | no_return\n def move(%Job{} = job, to_queue) do\n {:ok, new_job} = enqueue(%Job{job | queue: to_queue})\n\n # Don't worry if it fails to cancel.\n cancel(job)\n\n new_job\n end\n\n @doc false\n def enqueue(%Job{queue: queue} = job) do\n queue\n |> get_queue\n |> case do\n nil -> raise RuntimeError, no_queues_running_error(job)\n queue -> queue\n end\n |> Queue.enqueue(job)\n end\n\n @doc false\n def invalid_owner_error(job) do\n \"job #{inspect job} must be queried from the owner but was queried from #{inspect self()}\"\n end\n\n @doc false\n def invalid_delay_secs_error(job, secs) do\n \"invalid :delay_secs argument, #{inspect secs}, provided for job #{inspect job}, must be a non-negative integer\"\n end\n\n @doc false\n def reply_not_requested_error(job) do\n \"job #{inspect job} didn't request a reply when enqueued, set `:reply` to `true`, see `async\/3`\"\n end\n\n @doc false\n def no_queues_running_error(%Job{queue: {:global, _} = queue} = job) do\n \"can't enqueue job because there aren't any queue processes running for the distributed queue `#{inspect queue}, are you connected to the cluster? #{inspect job} `\"\n end\n\n @doc false\n def no_queues_running_error(%Job{queue: queue} = job) do\n \"can't enqueue job #{inspect job} because there aren't any queue processes running for `#{inspect queue}`\"\n end\n\n @deprecated \"Honeydew now supervises your queue processes, please use `Honeydew.start_queue\/2 instead.`\"\n def queue_spec(_name, _opts) do\n raise \"Honeydew now supervises your queue processes, please use `Honeydew.start_queue\/2 instead.`\"\n end\n\n @doc \"\"\"\n Returns a list of queues running on this node.\n \"\"\"\n @spec queues() :: [queue_name]\n defdelegate queues(), to: Queues\n\n @doc \"\"\"\n Returns a list of queues that have workers are running on this node.\n \"\"\"\n @spec workers() :: [queue_name]\n defdelegate workers(), to: Workers\n\n @type queue_spec_opt ::\n {:queue, mod_or_mod_args} |\n {:dispatcher, mod_or_mod_args} |\n {:failure_mode, mod_or_mod_args | nil} |\n {:success_mode, mod_or_mod_args | nil} |\n {:supervisor_opts, supervisor_opts} |\n {:suspended, boolean}\n\n @doc \"\"\"\n Starts a queue under Honeydew's supervision tree.\n\n `name` is how you'll refer to the queue to add a task.\n\n You can provide any of the following `opts`:\n\n - `queue`: is the module that queue will use. Defaults to\n `Honeydew.Queue.ErlangQueue`. You may also provide args to the queue's\n `c:Honeydew.Queue.init\/2` callback using the following format:\n `{module, args}`.\n - `dispatcher`: the job dispatching strategy, `{module, init_args}`.\n\n - `failure_mode`: the way that failed jobs should be handled. You can pass\n either a module, or `{module, args}`. The module must implement the\n `Honeydew.FailureMode` behaviour. Defaults to\n `{Honeydew.FailureMode.Abandon, []}`.\n\n - `success_mode`: a callback that runs when a job successfully completes. You\n can pass either a module, or `{module, args}`. The module must implement\n the `Honeydew.SuccessMode` behaviour. Defaults to `nil`.\n\n - `suspended`: Start queue in suspended state. Defaults to `false`.\n\n For example:\n\n - `Honeydew.start_queue(\"my_awesome_queue\")`\n\n - `Honeydew.start_queue(\"my_awesome_queue\", queue: {MyQueueModule, [ip: \"localhost\"]},\n dispatcher: {Honeydew.Dispatcher.MRU, []})`\n\n Note that the `failure_mode` or `success_mode` handler is run in the job's\n dedicated monitor process. This means the handlers for multiple jobs can run\n concurrently, but they can also crash that process.\n \"\"\"\n @spec start_queue(queue_name, [queue_spec_opt]) :: :ok\n defdelegate start_queue(name, opts \\\\ []), to: Queues\n\n @doc \"\"\"\n Stops the local instance of the provided queue name.\n \"\"\"\n @spec stop_queue(queue_name) :: :ok | {:error, :not_running}\n defdelegate stop_queue(name), to: Queues\n\n @type worker_opt ::\n {:num, non_neg_integer} |\n {:init_retry_secs, pos_integer} |\n {:shutdown, non_neg_integer} |\n {:nodes, [node]}\n\n @type worker_opts :: [worker_opt]\n\n @doc \"\"\"\n Starts workers under Honeydew's supervision tree.\n\n `name` is the name of the queue that the workers pull jobs from.\n\n `module` is the module that the workers in your queue will use. You may also\n provide `c:Honeydew.Worker.init\/1` args with `{module, args}`.\n\n You can provide any of the following `opts`:\n\n - `num`: the number of workers to start. Defaults to `10`.\n\n - `init_retry_secs`: the amount of time, in seconds, a stateful worker waits\n before trying to re-initialize after its `c:Honeydew.Worker.init\/1` function\n fails. You can also override this behavior by implementing the\n `c:Honeydew.Worker.init_failed\/0` callback, see `README\/workers.md`.\n\n - `shutdown`: if a worker is in the middle of a job, the amount of time, in\n milliseconds, to wait before brutally killing it. Defaults to `10_000`.\n\n - `nodes`: for :global queues, you can provide a list of nodes to stay\n connected to (your queue node and enqueuing nodes). Defaults to `[]`.\n\n For example:\n\n - `Honeydew.start_workers(\"my_awesome_queue\", MyJobModule)`\n\n - `Honeydew.start_workers(\"my_awesome_queue\", {MyJobModule, [key: \"secret key\"]}, num: 3)`\n\n - `Honeydew.start_workers({:global, \"my_awesome_queue\"}, MyJobModule, nodes: [:clientfacing@dax, :queue@dax])`\n \"\"\"\n defdelegate start_workers(name, module_and_args, opts \\\\ []), to: Honeydew.Workers\n\n @deprecated \"Honeydew now supervises your worker processes, please use `Honeydew.start_workers\/3 instead.`\"\n def worker_spec(_queue, _module_and_args, _opts) do\n raise \"Honeydew now supervises your worker processes, please use `Honeydew.start_workers\/3 instead.`\"\n end\n\n @doc \"\"\"\n Stops the local workers for the provided queue name.\n \"\"\"\n @spec stop_workers(queue_name) :: :ok | {:error, :not_running}\n defdelegate stop_workers(name), to: Workers\n\n @doc \"\"\"\n Re-initializes the given worker, this is intended to be used from\n within a worker's `c:Honeydew.Worker.failed_init\/0` callback. Using it otherwise\n may cause undefined behavior, at present, don't do it.\n \"\"\"\n @spec reinitialize_worker() :: :ok\n def reinitialize_worker do\n Worker.module_init(self())\n end\n\n @groups [Workers, Queues]\n\n Enum.each(@groups, fn group ->\n @doc false\n def group(queue, unquote(group)) do\n name(queue, unquote(group))\n end\n end)\n\n @processes [WorkerGroupSupervisor, WorkerStarter]\n\n Enum.each(@processes, fn process ->\n @doc false\n def process(queue, unquote(process)) do\n name(queue, unquote(process))\n end\n end)\n\n\n @doc false\n def create_groups(queue) do\n Enum.each(@groups, fn name ->\n queue |> group(name) |> :pg2.create\n end)\n end\n\n @doc false\n def delete_groups(queue) do\n Enum.each(@groups, fn name ->\n queue |> group(name) |> :pg2.delete\n end)\n end\n\n @doc false\n def get_all_members({:global, _} = queue, name) do\n queue |> group(name) |> :pg2.get_members\n end\n\n @doc false\n def get_all_members(queue, name) do\n get_all_local_members(queue, name)\n end\n\n # we need to know local members to shut down local components\n @doc false\n def get_all_local_members(queue, name) do\n queue |> group(name) |> :pg2.get_local_members\n end\n\n\n @doc false\n def get_queue(queue) do\n queue\n |> get_all_queues\n |> case do\n {:error, {:no_such_group, _queue}} -> []\n queues -> queues\n end\n |> List.first\n end\n\n @doc false\n def get_all_queues({:global, _name} = queue) do\n queue\n |> group(Queues)\n |> :pg2.get_members\n end\n\n @doc false\n def get_all_queues(queue) do\n queue\n |> group(Queues)\n |> :pg2.get_local_members\n end\n\n @doc false\n def table_name({:global, queue}) do\n \"global_#{queue}\"\n end\n\n @doc false\n def table_name(queue) do\n to_string(queue)\n end\n\n defp name({:global, queue}, component) do\n name([:global, queue], component)\n end\n\n defp name(queue, component) do\n [component, queue] |> List.flatten |> Enum.join(\".\") |> String.to_atom\n end\n\n @doc false\n defmacro debug(ast) do\n quote do\n fn ->\n Logger.debug unquote(ast)\n end\n end\n end\n\nend\n","old_contents":"defmodule Honeydew do\n @moduledoc \"\"\"\n A pluggable job queue + worker pool for Elixir.\n \"\"\"\n\n alias Honeydew.Job\n alias Honeydew.JobMonitor\n alias Honeydew.Worker\n alias Honeydew.WorkerStarter\n alias Honeydew.WorkerGroupSupervisor\n alias Honeydew.Queue\n alias Honeydew.{Queues, Workers}\n require Logger\n\n @type mod_or_mod_args :: module | {module, args :: term}\n @type queue_name :: String.t | atom | {:global, String.t | atom}\n @type supervisor_opts :: Keyword.t\n @type async_opt :: {:reply, true} | {:delay_secs, pos_integer()}\n @type task :: {atom, [arg :: term]}\n @type filter :: (Job.t -> boolean) | atom\n\n @typedoc \"\"\"\n Result of a `Honeydew.Job`\n \"\"\"\n @type result :: term\n\n #\n # Parts of this module were lovingly stolen from\n # https:\/\/github.com\/elixir-lang\/elixir\/blob\/v1.3.2\/lib\/elixir\/lib\/task.ex#L320\n #\n\n @doc \"\"\"\n Runs a task asynchronously.\n\n Raises a `RuntimeError` if `queue` process is not available.\n\n You can provide any of the following `opts`:\n\n - `reply`: returns the result of the job via `yield\/1`, see below.\n - `delay_secs`: delays the execution of the job by the provided number of seconds.\n\n ## Examples\n\n To run a task asynchronously:\n\n Honeydew.async({:ping, [\"127.0.0.1\"]}, :my_queue)\n\n To run a task asynchronously and wait for result:\n\n # Without pipes\n job = Honeydew.async({:ping, [\"127.0.0.1\"]}, :my_queue, reply: true)\n Honeydew.yield(job)\n\n # With pipes\n :pong =\n {:ping, [\"127.0.0.1\"]}\n |> Honeydew.async(:my_queue, reply: true)\n |> Honeydew.yield()\n\n To run a task an hour later:\n\n Honeydew.async({:ping, [\"127.0.0.1\"]}, :my_queue, delay_secs: 60*60)\n \"\"\"\n @spec async(task, queue_name, [async_opt]) :: Job.t | no_return\n def async(task, queue, opts \\\\ []) do\n job = Job.new(task, queue)\n\n {:ok, job} =\n opts\n |> Enum.reduce(job, fn\n {:reply, true}, job ->\n %Job{job | from: {self(), make_ref()}}\n\n {:delay_secs, secs}, job when is_integer(secs) and secs >= 0 ->\n %Job{job | delay_secs: secs}\n\n {:delay_secs, thing}, job ->\n raise ArgumentError, invalid_delay_secs_error(job, thing)\n end)\n |> enqueue\n\n job\n end\n\n @doc \"\"\"\n Wait for a job to complete and return result.\n\n Returns the result of a job, or `nil` on timeout. Raises an `ArgumentError` if\n the job was not created with `reply: true` and in the current process.\n\n ## Example\n\n Calling `yield\/2` with different timeouts.\n\n iex> job = Honeydew.async({:ping, [\"127.0.0.1\"]}, :my_queue, reply: true)\n iex> Honeydew.yield(job, 500) # Wait half a second\n nil\n # Result comes in at 1 second\n iex> Honeydew.yield(job, 1000) # Wait up to a second\n {:ok, :pong}\n iex> Honeydew.yield(job, 0)\n nil # <- because the message has already arrived and been handled\n\n The only time `yield\/2` would ever return the result more than once is if\n the job executes more than once (as Honeydew aims for at-least-once\n execution).\n \"\"\"\n @spec yield(Job.t, timeout) :: {:ok, result} | nil | no_return\n def yield(job, timeout \\\\ 5000)\n def yield(%Job{from: nil} = job, _), do: raise ArgumentError, reply_not_requested_error(job)\n def yield(%Job{from: {owner, _}} = job, _) when owner != self(), do: raise ArgumentError, invalid_owner_error(job)\n\n def yield(%Job{from: {_, ref}}, timeout) do\n receive do\n %Job{from: {_, ^ref}, result: result} ->\n result # may be {:ok, term} or {:exit, term}\n after\n timeout ->\n nil\n end\n end\n\n @doc \"\"\"\n Suspends job processing for a queue.\n \"\"\"\n @spec suspend(queue_name) :: :ok\n def suspend(queue) do\n queue\n |> get_all_members(Queues)\n |> Enum.each(&Queue.suspend\/1)\n end\n\n @doc \"\"\"\n Resumes job processing for a queue.\n \"\"\"\n @spec resume(queue_name) :: :ok\n def resume(queue) do\n queue\n |> get_all_members(Queues)\n |> Enum.each(&Queue.resume\/1)\n end\n\n\n\n @doc \"\"\"\n Returns the currrent status of the queue and all attached workers.\n\n You can provide any of the following `opts`:\n\n - `timeout`: specifies the time (in miliseconds) the calling process will wait for the queue to return the status,\n note that this timeout does not cancel the status callback execution in the queue.\n \"\"\"\n @type status_opt :: {:timeout, pos_integer}\n @spec status(queue_name, [status_opt]) :: map()\n def status(queue, opts \\\\ []) do\n queue_status =\n queue\n |> get_queue\n |> Queue.status(opts)\n\n busy_workers =\n queue_status\n |> Map.get(:job_monitors)\n |> Enum.map(fn monitor ->\n try do\n JobMonitor.status(monitor)\n catch\n # the monitor may have shut down\n :exit, _ -> nil\n end\n end)\n |> Enum.reject(&(!&1))\n |> Enum.into(%{})\n\n workers =\n queue\n |> get_all_members(Workers)\n |> Enum.map(&{&1, nil})\n |> Enum.into(%{})\n |> Map.merge(busy_workers)\n\n %{queue: Map.delete(queue_status, :job_monitors), workers: workers}\n end\n\n @doc \"\"\"\n Filters the jobs currently on the queue.\n\n Filtration support depends on the queue implementation.\n\n ErlangQueue and Mnesia queues support filtering with functions.\n\n Ecto Poll Queues have pre-defined, named filters. At the moment, only `:abandoned` is implemented.\n\n Note:\n - This function returns a `List`, not a `Stream`, so calling it can be memory intensive when invoked on a large queue.\n - The filtration is done by the queue process, not the client, so a heavy filter will tie up the queue.\n\n ## Examples\n\n Filter jobs with a specific task.\n\n Honeydew.filter(:my_queue, &match?(%Honeydew.Job{task: {:ping, _}}, &1)) # ErlangQueue or Mnesia\n\n Honeydew.filter(:my_queue, %{task: {:ping, [\"127.0.0.1\"]}}) # Mnesia\n\n Honeydew.filter(:my_queue, :abandoned) # Ecto queue\n\n Return all jobs.\n\n Honeydew.filter(:my_queue, fn _ -> true end)\n \"\"\"\n @spec filter(queue_name, filter) :: [Job.t]\n def filter(queue, filter) do\n {:ok, jobs} =\n queue\n |> get_queue\n |> Queue.filter(filter)\n\n jobs\n end\n\n @doc \"\"\"\n Cancels a job.\n\n The return value depends on the status of the job.\n\n * `:ok` - Job had not been started and was able to be cancelled.\n * `{:error, :in_progress}` - Job was in progress and unable to be cancelled.\n * `{:error, :not_found}` - Job was not found on the queue (or already processed) and was unable to be cancelled.\n \"\"\"\n @spec cancel(Job.t) :: :ok | {:error, :in_progress} | {:error, :not_found}\n def cancel(%Job{queue: queue} = job) do\n queue\n |> get_queue\n |> Queue.cancel(job)\n end\n\n @doc \"\"\"\n Cancels the job associated with the first argument.\n\n For example, for the Ecto Poll Queue, the first argument is the value of an ID from your schema.\n\n The return value depends on the status of the job.\n\n * `:ok` - Job had not been started and was able to be cancelled.\n * `{:error, :in_progress}` - Job was in progress and unable to be cancelled, the Ecto Poll Queue does not support this return.\n * `{:error, :not_found}` - Job was not found on the queue (or already processed) and was unable to be cancelled.\n \"\"\"\n @spec cancel(Job.private(), queue_name) :: :ok | {:error, :in_progress} | {:error, :not_found}\n def cancel(private, queue) do\n %Job{private: private, queue: queue} |> cancel\n end\n\n @doc \"\"\"\n Moves a job to another queue.\n\n Raises a `RuntimeError` if `to_queue` is not available.\n\n This function first enqueues the job on `to_queue`, and then tries to\n cancel it on its current queue. This means there's a possiblity a job could\n be processed on both queues. This behavior is consistent with Honeydew's\n at-least-once execution goal.\n\n This function is most helpful on a queue where there a no workers\n (like a dead letter queue), because the job won't be processed out from under\n the queue.\n \"\"\"\n @spec move(Job.t, to_queue :: queue_name) :: Job.t | no_return\n def move(%Job{} = job, to_queue) do\n {:ok, new_job} = enqueue(%Job{job | queue: to_queue})\n\n # Don't worry if it fails to cancel.\n cancel(job)\n\n new_job\n end\n\n @doc false\n def enqueue(%Job{queue: queue} = job) do\n queue\n |> get_queue\n |> case do\n nil -> raise RuntimeError, no_queues_running_error(job)\n queue -> queue\n end\n |> Queue.enqueue(job)\n end\n\n @doc false\n def invalid_owner_error(job) do\n \"job #{inspect job} must be queried from the owner but was queried from #{inspect self()}\"\n end\n\n @doc false\n def invalid_delay_secs_error(job, secs) do\n \"invalid :delay_secs argument, #{inspect secs}, provided for job #{inspect job}, must be a non-negative integer\"\n end\n\n @doc false\n def reply_not_requested_error(job) do\n \"job #{inspect job} didn't request a reply when enqueued, set `:reply` to `true`, see `async\/3`\"\n end\n\n @doc false\n def no_queues_running_error(%Job{queue: {:global, _} = queue} = job) do\n \"can't enqueue job because there aren't any queue processes running for the distributed queue `#{inspect queue}, are you connected to the cluster? #{inspect job} `\"\n end\n\n @doc false\n def no_queues_running_error(%Job{queue: queue} = job) do\n \"can't enqueue job #{inspect job} because there aren't any queue processes running for `#{inspect queue}`\"\n end\n\n @deprecated \"Honeydew now supervises your queue processes, please use `Honeydew.start_queue\/2 instead.`\"\n def queue_spec(_name, _opts) do\n raise \"Honeydew now supervises your queue processes, please use `Honeydew.start_queue\/2 instead.`\"\n end\n\n @doc \"\"\"\n Returns a list of queues running on this node.\n \"\"\"\n @spec queues() :: [queue_name]\n defdelegate queues(), to: Queues\n\n @doc \"\"\"\n Returns a list of queues that have workers are running on this node.\n \"\"\"\n @spec workers() :: [queue_name]\n defdelegate workers(), to: Workers\n\n @type queue_spec_opt ::\n {:queue, mod_or_mod_args} |\n {:dispatcher, mod_or_mod_args} |\n {:failure_mode, mod_or_mod_args | nil} |\n {:success_mode, mod_or_mod_args | nil} |\n {:supervisor_opts, supervisor_opts} |\n {:suspended, boolean}\n\n @doc \"\"\"\n Starts a queue under Honeydew's supervision tree.\n\n `name` is how you'll refer to the queue to add a task.\n\n You can provide any of the following `opts`:\n\n - `queue`: is the module that queue will use. Defaults to\n `Honeydew.Queue.ErlangQueue`. You may also provide args to the queue's\n `c:Honeydew.Queue.init\/2` callback using the following format:\n `{module, args}`.\n - `dispatcher`: the job dispatching strategy, `{module, init_args}`.\n\n - `failure_mode`: the way that failed jobs should be handled. You can pass\n either a module, or `{module, args}`. The module must implement the\n `Honeydew.FailureMode` behaviour. Defaults to\n `{Honeydew.FailureMode.Abandon, []}`.\n\n - `success_mode`: a callback that runs when a job successfully completes. You\n can pass either a module, or `{module, args}`. The module must implement\n the `Honeydew.SuccessMode` behaviour. Defaults to `nil`.\n\n - `suspended`: Start queue in suspended state. Defaults to `false`.\n\n For example:\n\n - `Honeydew.start_queue(\"my_awesome_queue\")`\n\n - `Honeydew.start_queue(\"my_awesome_queue\", queue: {MyQueueModule, [ip: \"localhost\"]},\n dispatcher: {Honeydew.Dispatcher.MRU, []})`\n \"\"\"\n @spec start_queue(queue_name, [queue_spec_opt]) :: :ok\n defdelegate start_queue(name, opts \\\\ []), to: Queues\n\n @doc \"\"\"\n Stops the local instance of the provided queue name.\n \"\"\"\n @spec stop_queue(queue_name) :: :ok | {:error, :not_running}\n defdelegate stop_queue(name), to: Queues\n\n @type worker_opt ::\n {:num, non_neg_integer} |\n {:init_retry_secs, pos_integer} |\n {:shutdown, non_neg_integer} |\n {:nodes, [node]}\n\n @type worker_opts :: [worker_opt]\n\n @doc \"\"\"\n Starts workers under Honeydew's supervision tree.\n\n `name` is the name of the queue that the workers pull jobs from.\n\n `module` is the module that the workers in your queue will use. You may also\n provide `c:Honeydew.Worker.init\/1` args with `{module, args}`.\n\n You can provide any of the following `opts`:\n\n - `num`: the number of workers to start. Defaults to `10`.\n\n - `init_retry_secs`: the amount of time, in seconds, a stateful worker waits\n before trying to re-initialize after its `c:Honeydew.Worker.init\/1` function\n fails. You can also override this behavior by implementing the\n `c:Honeydew.Worker.init_failed\/0` callback, see `README\/workers.md`.\n\n - `shutdown`: if a worker is in the middle of a job, the amount of time, in\n milliseconds, to wait before brutally killing it. Defaults to `10_000`.\n\n - `nodes`: for :global queues, you can provide a list of nodes to stay\n connected to (your queue node and enqueuing nodes). Defaults to `[]`.\n\n For example:\n\n - `Honeydew.start_workers(\"my_awesome_queue\", MyJobModule)`\n\n - `Honeydew.start_workers(\"my_awesome_queue\", {MyJobModule, [key: \"secret key\"]}, num: 3)`\n\n - `Honeydew.start_workers({:global, \"my_awesome_queue\"}, MyJobModule, nodes: [:clientfacing@dax, :queue@dax])`\n \"\"\"\n defdelegate start_workers(name, module_and_args, opts \\\\ []), to: Honeydew.Workers\n\n @deprecated \"Honeydew now supervises your worker processes, please use `Honeydew.start_workers\/3 instead.`\"\n def worker_spec(_queue, _module_and_args, _opts) do\n raise \"Honeydew now supervises your worker processes, please use `Honeydew.start_workers\/3 instead.`\"\n end\n\n @doc \"\"\"\n Stops the local workers for the provided queue name.\n \"\"\"\n @spec stop_workers(queue_name) :: :ok | {:error, :not_running}\n defdelegate stop_workers(name), to: Workers\n\n @doc \"\"\"\n Re-initializes the given worker, this is intended to be used from\n within a worker's `c:Honeydew.Worker.failed_init\/0` callback. Using it otherwise\n may cause undefined behavior, at present, don't do it.\n \"\"\"\n @spec reinitialize_worker() :: :ok\n def reinitialize_worker do\n Worker.module_init(self())\n end\n\n @groups [Workers, Queues]\n\n Enum.each(@groups, fn group ->\n @doc false\n def group(queue, unquote(group)) do\n name(queue, unquote(group))\n end\n end)\n\n @processes [WorkerGroupSupervisor, WorkerStarter]\n\n Enum.each(@processes, fn process ->\n @doc false\n def process(queue, unquote(process)) do\n name(queue, unquote(process))\n end\n end)\n\n\n @doc false\n def create_groups(queue) do\n Enum.each(@groups, fn name ->\n queue |> group(name) |> :pg2.create\n end)\n end\n\n @doc false\n def delete_groups(queue) do\n Enum.each(@groups, fn name ->\n queue |> group(name) |> :pg2.delete\n end)\n end\n\n @doc false\n def get_all_members({:global, _} = queue, name) do\n queue |> group(name) |> :pg2.get_members\n end\n\n @doc false\n def get_all_members(queue, name) do\n get_all_local_members(queue, name)\n end\n\n # we need to know local members to shut down local components\n @doc false\n def get_all_local_members(queue, name) do\n queue |> group(name) |> :pg2.get_local_members\n end\n\n\n @doc false\n def get_queue(queue) do\n queue\n |> get_all_queues\n |> case do\n {:error, {:no_such_group, _queue}} -> []\n queues -> queues\n end\n |> List.first\n end\n\n @doc false\n def get_all_queues({:global, _name} = queue) do\n queue\n |> group(Queues)\n |> :pg2.get_members\n end\n\n @doc false\n def get_all_queues(queue) do\n queue\n |> group(Queues)\n |> :pg2.get_local_members\n end\n\n @doc false\n def table_name({:global, queue}) do\n \"global_#{queue}\"\n end\n\n @doc false\n def table_name(queue) do\n to_string(queue)\n end\n\n defp name({:global, queue}, component) do\n name([:global, queue], component)\n end\n\n defp name(queue, component) do\n [component, queue] |> List.flatten |> Enum.join(\".\") |> String.to_atom\n end\n\n @doc false\n defmacro debug(ast) do\n quote do\n fn ->\n Logger.debug unquote(ast)\n end\n end\n end\n\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"b58e31aa14a18b0476fb88570fe221e079735dba","subject":"Reformat","message":"Reformat\n","repos":"hrzndhrn\/xema","old_file":"lib\/xema\/ref.ex","new_file":"lib\/xema\/ref.ex","new_contents":"defmodule Xema.Ref do\n @moduledoc \"\"\"\n This module contains a struct and function to represent and handle references.\n \"\"\"\n\n import Xema.Utils, only: [get_value: 2, update_nil: 2]\n\n alias Xema.Ref\n alias Xema.Schema\n alias Xema.SchemaError\n\n require Logger\n\n @type t :: %Xema.Ref{\n path: String.t() | nil,\n pointer: String.t(),\n remote: boolean(),\n url: String.t() | nil\n }\n\n defstruct pointer: nil,\n path: nil,\n remote: false,\n url: nil\n\n @doc \"\"\"\n Creates a new reference from the given `pointer`.\n\n ## Examples\n\n iex> Xema.Ref.new(\"http:\/\/foo.com\/bar\/baz.exon#\/definitions\/abc\")\n %Xema.Ref{\n path: \"\/bar\/baz.exon\",\n pointer: \"\/definitions\/abc\",\n remote: true,\n url: \"http:\/\/foo.com:80\"\n }\n\n \"\"\"\n @spec new(String.t()) :: Ref.t()\n def new(pointer) when is_binary(pointer) do\n uri = URI.parse(pointer)\n path = uri |> Map.get(:path)\n pointer = uri |> Map.get(:fragment)\n remote = !is_nil(path) && Regex.match?(~r\/(?:\\..+#)|(?:\\..+$)\/, path)\n\n url =\n unless is_nil(uri.scheme) do\n port =\n if is_nil(uri.port),\n do: \"\",\n else: \":#{Integer.to_string(uri.port)}\"\n\n \"#{uri.scheme}:\/\/#{uri.host}#{port}\"\n end\n\n %Ref{\n pointer: pointer,\n path: path,\n remote: remote,\n url: url\n }\n end\n\n @doc \"\"\"\n Validates the given value with the referenced schema.\n \"\"\"\n @spec validate(Ref.t(), any, keyword) :: :ok | {:error, map}\n def validate(ref, value, opts) do\n case get(ref, opts) do\n {:ok, %Schema{} = schema, opts} ->\n Xema.validate(schema, value, opts)\n\n {:ok, %Ref{} = ref, opts} ->\n validate(ref, value, opts)\n\n {:error, :not_found} ->\n raise SchemaError,\n message: \"Reference '#{Ref.get_pointer(ref)}' not found.\"\n end\n end\n\n defp get(%Ref{remote: false, path: nil, pointer: pointer}, opts) do\n with {:ok, schema} <- do_get(pointer, opts[:root]), do: {:ok, schema, opts}\n end\n\n defp get(%Ref{remote: false, path: path, pointer: nil}, opts) do\n id =\n opts[:id]\n |> URI.parse()\n |> Map.put(:path, Path.join(\"\/\", path))\n |> URI.to_string()\n\n with {:ok, ref} <- get_ref(opts[:root], id), do: {:ok, ref, opts}\n end\n\n defp get(%Ref{remote: true, url: nil, path: path, pointer: pointer}, opts) do\n uri = URI.parse(opts[:id])\n\n uri =\n case is_nil(uri.path) || !String.ends_with?(uri.path, \"\/\") do\n true -> Map.put(uri, :path, Path.join(\"\/\", path))\n false -> Map.put(uri, :path, Path.join(uri.path, path))\n end\n\n with {:ok, xema} <- get_xema(opts[:root], URI.to_string(uri)),\n {:ok, schema} <- do_get(pointer, xema),\n do: {:ok, schema, root: xema}\n end\n\n defp get(%Ref{remote: true, url: url, path: path, pointer: pointer}, opts) do\n uri = Path.join(url, path)\n\n # xema = Map.get(opts[:root].refs, uri)\n\n with {:ok, xema} <- get_xema(opts[:root], uri),\n {:ok, schema} <- do_get(pointer, xema),\n do: {:ok, schema, root: xema}\n end\n\n defp get(_ref, _opts), do: {:error, :not_found}\n\n defp do_get(_, nil), do: {:error, :not_found}\n\n defp do_get(pointer, %{__struct__: _, content: content}) do\n case pointer in [nil, \"\", \"#\"] do\n true -> {:ok, content}\n false -> do_get(pointer, content)\n end\n end\n\n defp do_get(pointer, schema)\n when is_binary(pointer),\n do:\n pointer\n |> String.trim(\"\/\")\n |> String.split(\"\/\")\n |> do_get(schema)\n\n defp do_get([], schema), do: {:ok, schema}\n\n defp do_get([step | steps], schema) when is_map(schema) do\n case get_value(schema, decode(step)) do\n {:ok, value} ->\n do_get(steps, value)\n\n {:error, _} ->\n {:error, :not_found}\n end\n end\n\n defp do_get([step | steps], schema) when is_list(schema) do\n with {:ok, index} <- to_integer(step) do\n case Enum.at(schema, index) do\n nil -> {:error, :not_found}\n value -> do_get(steps, value)\n end\n end\n end\n\n defp get_ref(%{ids: refs}, id) do\n case Map.get(refs, id) do\n nil -> {:error, :not_found}\n ref -> {:ok, ref}\n end\n end\n\n defp get_ref(_, _), do: {:error, :not_found}\n\n defp get_xema(%{refs: xemas}, pointer) do\n case Map.get(xemas, pointer) do\n nil ->\n {:error, :not_found}\n\n xema ->\n {:ok, xema}\n end\n end\n\n defp get_xema(_, _), do: {:error, :not_found}\n\n defp decode(str) do\n str\n |> String.replace(\"~0\", \"~\")\n |> String.replace(\"~1\", \"\/\")\n |> URI.decode()\n rescue\n _ -> str\n end\n\n defp to_integer(str) do\n case Regex.run(~r\/\\d+\/, str) do\n nil -> {:error, :not_found}\n [int] -> {:ok, String.to_integer(int)}\n end\n end\n\n @doc \"\"\"\n Returns the `pointer` of the given reference.\n \"\"\"\n @spec get_pointer(Ref.t()) :: String.t()\n def get_pointer(ref) do\n ref.url\n |> update_nil(\"\")\n |> URI.parse()\n |> Map.put(:path, ref.path)\n |> Map.put(:fragment, ref.pointer)\n |> URI.to_string()\n end\n\n @doc \"\"\"\n Returns the binary representation of a reference.\n\n ## Examples\n\n iex> \"http:\/\/foo.com\/bar\/baz.exon#\/definitions\/abc\"\n ...> |> Xema.Ref.new()\n ...> |> Xema.Ref.to_string()\n \"{:ref, \\\\\"http:\/\/foo.com\/bar\/baz.exon#\/definitions\/abc\\\\\"}\"\n\n \"\"\"\n @spec to_string(Ref.t()) :: String.t()\n def to_string(ref), do: \"{:ref, #{inspect(get_pointer(ref))}}\"\nend\n\ndefimpl String.Chars, for: Xema.Ref do\n @spec to_string(Xema.Ref.t()) :: String.t()\n def to_string(ref), do: Xema.Ref.to_string(ref)\nend\n","old_contents":"defmodule Xema.Ref do\n @moduledoc \"\"\"\n This module contains a struct and function to represent and handle references.\n \"\"\"\n\n import Xema.Utils, only: [get_value: 2, update_nil: 2]\n\n alias Xema.Ref\n alias Xema.Schema\n alias Xema.SchemaError\n\n require Logger\n\n @type t :: %Xema.Ref{\n path: String.t() | nil,\n pointer: String.t(),\n remote: boolean(),\n url: String.t() | nil\n }\n\n defstruct pointer: nil,\n path: nil,\n remote: false,\n url: nil\n\n @doc \"\"\"\n Creates a new reference from the given `pointer`.\n\n ## Examples\n\n iex> Xema.Ref.new(\"http:\/\/foo.com\/bar\/baz.exon#\/definitions\/abc\")\n %Xema.Ref{\n path: \"\/bar\/baz.exon\",\n pointer: \"\/definitions\/abc\",\n remote: true,\n url: \"http:\/\/foo.com:80\"\n }\n\n \"\"\"\n @spec new(String.t()) :: Ref.t()\n def new(pointer) when is_binary(pointer) do\n uri = URI.parse(pointer)\n path = uri |> Map.get(:path)\n pointer = uri |> Map.get(:fragment)\n remote = !is_nil(path) && Regex.match?(~r\/(?:\\..+#)|(?:\\..+$)\/, path)\n\n url =\n unless is_nil(uri.scheme) do\n port =\n if is_nil(uri.port),\n do: \"\",\n else: \":#{Integer.to_string(uri.port)}\"\n\n \"#{uri.scheme}:\/\/#{uri.host}#{port}\"\n end\n\n %Ref{\n pointer: pointer,\n path: path,\n remote: remote,\n url: url\n }\n end\n\n @doc \"\"\"\n Validates the given value with the referenced schema.\n \"\"\"\n @spec validate(Ref.t(), any, keyword) :: :ok | {:error, map}\n def validate(ref, value, opts) do\n case get(ref, opts) do\n {:ok, %Schema{} = schema, opts} ->\n Xema.validate(schema, value, opts)\n\n {:ok, %Ref{} = ref, opts} ->\n validate(ref, value, opts)\n\n {:error, :not_found} ->\n raise SchemaError,\n message: \"Reference '#{Ref.get_pointer(ref)}' not found.\"\n end\n end\n\n defp get(%Ref{remote: false, path: nil, pointer: pointer}, opts) do\n with {:ok, schema} <- do_get(pointer, opts[:root]), do: {:ok, schema, opts}\n end\n\n defp get(%Ref{remote: false, path: path, pointer: nil}, opts) do\n id =\n opts[:id]\n |> URI.parse()\n |> Map.put(:path, Path.join(\"\/\", path))\n |> URI.to_string()\n\n with {:ok, ref} <- get_ref(opts[:root], id), do: {:ok, ref, opts}\n end\n\n defp get(%Ref{remote: true, url: nil, path: path, pointer: pointer}, opts) do\n uri = URI.parse(opts[:id])\n\n uri =\n case is_nil(uri.path) || !String.ends_with?(uri.path, \"\/\") do\n true -> Map.put(uri, :path, Path.join(\"\/\", path))\n false -> Map.put(uri, :path, Path.join(uri.path, path))\n end\n\n # xema = Map.get(opts[:root].refs, URI.to_string(uri))\n\n with {:ok, xema} <- get_xema(opts[:root], URI.to_string(uri)),\n {:ok, schema} <- do_get(pointer, xema),\n do: {:ok, schema, root: xema}\n end\n\n defp get(%Ref{remote: true, url: url, path: path, pointer: pointer}, opts) do\n uri = Path.join(url, path)\n\n # xema = Map.get(opts[:root].refs, uri)\n\n with {:ok, xema} <- get_xema(opts[:root], uri),\n {:ok, schema} <- do_get(pointer, xema),\n do: {:ok, schema, root: xema}\n end\n\n defp get(_ref, _opts), do: {:error, :not_found}\n\n defp do_get(_, nil), do: {:error, :not_found}\n\n defp do_get(pointer, %{__struct__: _, content: content}) do\n case pointer in [nil, \"\", \"#\"] do\n true -> {:ok, content}\n false -> do_get(pointer, content)\n end\n end\n\n defp do_get(pointer, schema)\n when is_binary(pointer),\n do:\n pointer\n |> String.trim(\"\/\")\n |> String.split(\"\/\")\n |> do_get(schema)\n\n defp do_get([], schema), do: {:ok, schema}\n\n defp do_get([step | steps], schema) when is_map(schema) do\n case get_value(schema, decode(step)) do\n {:ok, value} ->\n do_get(steps, value)\n\n {:error, _} ->\n {:error, :not_found}\n end\n end\n\n defp do_get([step | steps], schema) when is_list(schema) do\n with {:ok, index} <- to_integer(step) do\n case Enum.at(schema, index) do\n nil -> {:error, :not_found}\n value -> do_get(steps, value)\n end\n end\n end\n\n defp get_ref(%{ids: refs}, id) do\n case Map.get(refs, id) do\n nil -> {:error, :not_found}\n ref -> {:ok, ref}\n end\n end\n\n defp get_ref(_, _), do: {:error, :not_found}\n\n defp get_xema(%{refs: xemas}, pointer) do\n case Map.get(xemas, pointer) do\n nil -> {:error, :not_found}\n xema -> {:ok, xema}\n end\n end\n\n defp get_xema(_, _), do: {:error, :not_found}\n\n defp decode(str) do\n str\n |> String.replace(\"~0\", \"~\")\n |> String.replace(\"~1\", \"\/\")\n |> URI.decode()\n rescue\n _ -> str\n end\n\n defp to_integer(str) do\n case Regex.run(~r\/\\d+\/, str) do\n nil -> {:error, :not_found}\n [int] -> {:ok, String.to_integer(int)}\n end\n end\n\n @doc \"\"\"\n Returns the `pointer` of the given reference.\n \"\"\"\n @spec get_pointer(Ref.t()) :: String.t()\n def get_pointer(ref) do\n ref.url\n |> update_nil(\"\")\n |> URI.parse()\n |> Map.put(:path, ref.path)\n |> Map.put(:fragment, ref.pointer)\n |> URI.to_string()\n end\n\n @doc \"\"\"\n Returns the binary representation of a reference.\n\n ## Examples\n\n iex> \"http:\/\/foo.com\/bar\/baz.exon#\/definitions\/abc\"\n ...> |> Xema.Ref.new()\n ...> |> Xema.Ref.to_string()\n \"{:ref, \\\\\"http:\/\/foo.com\/bar\/baz.exon#\/definitions\/abc\\\\\"}\"\n\n \"\"\"\n @spec to_string(Ref.t()) :: String.t()\n def to_string(ref), do: \"{:ref, #{inspect(get_pointer(ref))}}\"\nend\n\ndefimpl String.Chars, for: Xema.Ref do\n @spec to_string(Xema.Ref.t()) :: String.t()\n def to_string(ref), do: Xema.Ref.to_string(ref)\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"2289510207ea46092cfa85b70c9d5059ce724f0f","subject":"added number to number+ordinal suffix function","message":"added number to number+ordinal suffix function\n","repos":"danielberkompas\/number,danielberkompas\/number","old_file":"lib\/number\/human.ex","new_file":"lib\/number\/human.ex","new_contents":"defmodule Number.Human do\n @moduledoc \"\"\"\n Provides functions for converting numbers into more human readable strings.\n \"\"\"\n\n import Number.Delimit, only: [number_to_delimited: 2]\n import Decimal, only: [cmp: 2]\n\n @doc \"\"\"\n Formats and labels a number with the appropriate English word.\n\n ## Examples\n\n iex> Number.Human.number_to_human(123)\n \"123.00\"\n\n iex> Number.Human.number_to_human(1234)\n \"1.23 Thousand\"\n\n iex> Number.Human.number_to_human(999001)\n \"999.00 Thousand\"\n\n iex> Number.Human.number_to_human(1234567)\n \"1.23 Million\"\n\n iex> Number.Human.number_to_human(1234567890)\n \"1.23 Billion\"\n\n iex> Number.Human.number_to_human(1234567890123)\n \"1.23 Trillion\"\n\n iex> Number.Human.number_to_human(1234567890123456)\n \"1.23 Quadrillion\"\n\n iex> Number.Human.number_to_human(1234567890123456789)\n \"1,234.57 Quadrillion\"\n\n iex> Number.Human.number_to_human(Decimal.new(\"5000.0\"))\n \"5.00 Thousand\"\n \"\"\"\n def number_to_human(number, options \\\\ [])\n\n def number_to_human(number, options) when not is_map(number) do\n if Number.Conversion.impl_for(number) do\n number\n |> Number.Conversion.to_decimal\n |> number_to_human(options)\n else\n raise ArgumentError, \"\"\"\n number must be a float or integer, or implement `Number.Conversion` protocol,\n was #{inspect number}\"\n \"\"\"\n end\n end\n\n def number_to_human(number, options) do\n cond do\n cmp(number, ~d(999)) == :gt && cmp(number, ~d(1_000_000)) == :lt ->\n delimit(number, ~d(1_000), \"Thousand\", options)\n cmp(number, ~d(1_000_000)) in [:gt, :eq] and cmp(number, ~d(1_000_000_000)) == :lt ->\n delimit(number, ~d(1_000_000), \"Million\", options)\n cmp(number, ~d(1_000_000_000)) in [:gt, :eq] and cmp(number, ~d(1_000_000_000_000)) == :lt ->\n delimit(number, ~d(1_000_000_000), \"Billion\", options)\n cmp(number, ~d(1_000_000_000_000)) in [:gt, :eq] and cmp(number, ~d(1_000_000_000_000_000)) == :lt ->\n delimit(number, ~d(1_000_000_000_000), \"Trillion\", options)\n cmp(number, ~d(1_000_000_000_000_000)) in [:gt, :eq] ->\n delimit(number, ~d(1_000_000_000_000_000), \"Quadrillion\", options)\n true ->\n number_to_delimited(number, options)\n end\n end\n\n @doc \"\"\"\n Adds ordinal suffix (st, nd, rd or th) for the number\n \"\"\"\n def number_to_ordinal(number) when is_integer(number) do\n sfx = ~w(th st nd rd th th th th th th)\n\n if (rem(number, 100) >= 11) && (rem(number, 100) <= 13) do\n \"#{number}th\"\n else\n \"#{number}#{sfx |> Enum.at(rem(number, 10))}\"\n end\n end\n\n\n defp sigil_d(number, _modifiers) do\n number\n |> String.replace(\"_\", \"\")\n |> String.to_integer\n |> Decimal.new\n end\n\n defp delimit(number, divisor, label, options) do\n number =\n number\n |> Decimal.div(divisor)\n |> number_to_delimited(options)\n\n number <> \" \" <> label\n end\nend\n","old_contents":"defmodule Number.Human do\n @moduledoc \"\"\"\n Provides functions for converting numbers into more human readable strings.\n \"\"\"\n\n import Number.Delimit, only: [number_to_delimited: 2]\n import Decimal, only: [cmp: 2]\n\n @doc \"\"\"\n Formats and labels a number with the appropriate English word.\n\n ## Examples\n\n iex> Number.Human.number_to_human(123)\n \"123.00\"\n\n iex> Number.Human.number_to_human(1234)\n \"1.23 Thousand\"\n\n iex> Number.Human.number_to_human(999001)\n \"999.00 Thousand\"\n\n iex> Number.Human.number_to_human(1234567)\n \"1.23 Million\"\n\n iex> Number.Human.number_to_human(1234567890)\n \"1.23 Billion\"\n\n iex> Number.Human.number_to_human(1234567890123)\n \"1.23 Trillion\"\n\n iex> Number.Human.number_to_human(1234567890123456)\n \"1.23 Quadrillion\"\n\n iex> Number.Human.number_to_human(1234567890123456789)\n \"1,234.57 Quadrillion\"\n\n iex> Number.Human.number_to_human(Decimal.new(\"5000.0\"))\n \"5.00 Thousand\"\n \"\"\"\n def number_to_human(number, options \\\\ [])\n\n def number_to_human(number, options) when not is_map(number) do\n if Number.Conversion.impl_for(number) do\n number\n |> Number.Conversion.to_decimal\n |> number_to_human(options)\n else\n raise ArgumentError, \"\"\"\n number must be a float or integer, or implement `Number.Conversion` protocol,\n was #{inspect number}\"\n \"\"\"\n end\n end\n\n def number_to_human(number, options) do\n cond do\n cmp(number, ~d(999)) == :gt && cmp(number, ~d(1_000_000)) == :lt ->\n delimit(number, ~d(1_000), \"Thousand\", options)\n cmp(number, ~d(1_000_000)) in [:gt, :eq] and cmp(number, ~d(1_000_000_000)) == :lt ->\n delimit(number, ~d(1_000_000), \"Million\", options)\n cmp(number, ~d(1_000_000_000)) in [:gt, :eq] and cmp(number, ~d(1_000_000_000_000)) == :lt ->\n delimit(number, ~d(1_000_000_000), \"Billion\", options)\n cmp(number, ~d(1_000_000_000_000)) in [:gt, :eq] and cmp(number, ~d(1_000_000_000_000_000)) == :lt ->\n delimit(number, ~d(1_000_000_000_000), \"Trillion\", options)\n cmp(number, ~d(1_000_000_000_000_000)) in [:gt, :eq] ->\n delimit(number, ~d(1_000_000_000_000_000), \"Quadrillion\", options)\n true ->\n number_to_delimited(number, options)\n end\n end\n\n defp sigil_d(number, _modifiers) do\n number\n |> String.replace(\"_\", \"\")\n |> String.to_integer\n |> Decimal.new\n end\n\n defp delimit(number, divisor, label, options) do\n number =\n number\n |> Decimal.div(divisor)\n |> number_to_delimited(options)\n\n number <> \" \" <> label\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"c583be2363ed4be2a08b00c83eafa4ce5bbe6719","subject":"remove","message":"remove\n","repos":"ikeikeikeike\/panglao,ikeikeikeike\/panglao","old_file":"cron\/caller.ex","new_file":"cron\/caller.ex","new_contents":"","old_contents":"defmodule Panglao.Cron.Caller do\n\n @hoston Application.get_env(:panglao, __MODULE__)\n\n defp call(fun) do\n with {:ok, [{_, _, _}| _] = ifcnf} <- :inet.getif() do\n call fun, ifcnf\n else error ->\n error\n end\n end\n defp call(_, []) do\n {:error, \"N\/A\"}\n end\n defp call(fun, [{@hoston, _, _} | _]) do\n fun.()\n end\n defp call(fun, [_ | tail]) do\n call fun, tail\n end\n\n def remove_perform do\n call fn ->\n Panglao.Tasks.Remove.perform\n end\n end\n\n def remove_perform_disksize do\n call fn ->\n Panglao.Tasks.Remove.perform :disksize\n end\n end\n\n def cleanup_unses_files do\n call fn ->\n Panglao.Tasks.Cleanup.unses_files\n end\n end\n\n def touch_perform do\n call fn ->\n Panglao.Tasks.Touch.perform\n end\n end\n\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"10c192be46ba8f12665b357611bc5836bb57951d","subject":"Add deprecation hint about `@lint` attributes","message":"Add deprecation hint about `@lint` attributes\n","repos":"rrrene\/credo,rrrene\/credo","old_file":"lib\/credo\/check\/runner.ex","new_file":"lib\/credo\/check\/runner.ex","new_contents":"defmodule Credo.Check.Runner do\n alias Credo.CLI.Output.UI\n alias Credo.Config\n alias Credo.SourceFile\n alias Credo.Service.SourceFileIssues\n\n @doc false\n def run(source_files, config) when is_list(source_files) do\n {_time_run_on_all, source_files_after_run_on_all} =\n :timer.tc fn ->\n run_checks_that_run_on_all(source_files, config)\n end\n\n {_time_run, source_files} =\n :timer.tc fn ->\n source_files_after_run_on_all\n |> Enum.map(&Task.async(fn -> run(&1, config) end))\n |> Enum.map(&Task.await(&1, :infinity))\n end\n\n {source_files, config}\n end\n def run(%SourceFile{} = source_file, config) do\n checks =\n config\n |> Config.checks\n |> Enum.reject(&run_on_all_check?\/1)\n\n issues = run_checks(source_file, checks, config)\n\n %SourceFile{source_file | issues: source_file.issues ++ issues}\n end\n\n @doc \"\"\"\n Prepares the Config struct based on a given list of `source_files`.\n \"\"\"\n def prepare_config(config) do\n prepare_config(config, config.source_files)\n end\n def prepare_config(config, source_files) do\n # TODO: remove prepare_config\/2\n config\n |> set_lint_attributes(source_files)\n |> exclude_low_priority_checks(config.min_priority - 9)\n |> exclude_checks_based_on_elixir_version\n end\n\n defp set_lint_attributes(config, source_files) do\n lint_attribute_map =\n source_files\n |> run_linter_attribute_reader(config)\n |> Enum.reduce(%{}, fn(source_file, memo) ->\n # TODO: we should modify the config \"directly\" instead of going\n # through the SourceFile\n Map.put(memo, source_file.filename, source_file.lint_attributes)\n end)\n\n if Map.size(lint_attribute_map) > 0 do\n Credo.CLI.Output.UI.warn \"\"\n Credo.CLI.Output.UI.warn [:orange,\n \"@lint attributes will be deprecated in the Credo v0.8 because they trigger\\n\",\n \"compiler warnings on Elixir v1.4.\\n\\n\",\n \"Please consider reporting the cases where you needed @lint attributes\\n\",\n \"to help us devise a new solution: https:\/\/github.com\/rrrene\/credo\/issues\/new\"]\n Credo.CLI.Output.UI.warn \"\"\n end\n\n %Config{config | lint_attribute_map: lint_attribute_map}\n end\n\n defp run_linter_attribute_reader(source_files, config) do\n checks = [{Credo.Check.FindLintAttributes}]\n\n Enum.reduce(checks, source_files, fn(check_tuple, source_files) ->\n run_check(check_tuple, source_files, config)\n end)\n end\n\n defp exclude_low_priority_checks(config, below_priority) do\n checks =\n Enum.reject(config.checks, fn\n ({check}) -> check.base_priority < below_priority\n ({_check, false}) -> true\n ({check, opts}) ->\n (opts[:priority] || check.base_priority) < below_priority\n end)\n\n %Config{config | checks: checks}\n end\n\n defp exclude_checks_based_on_elixir_version(config) do\n version = System.version()\n skipped_checks = Enum.reject(config.checks, &matches_requirement?(&1, version))\n checks = Enum.filter(config.checks, &matches_requirement?(&1, version))\n\n %Config{config | checks: checks, skipped_checks: skipped_checks}\n end\n\n defp matches_requirement?({check, _}, version) do\n matches_requirement?({check}, version)\n end\n defp matches_requirement?({check}, version) do\n Version.match?(version, check.elixir_version)\n end\n\n defp run_checks_that_run_on_all(source_files, config) do\n checks =\n config\n |> Config.checks\n |> Enum.filter(&run_on_all_check?\/1)\n\n checks\n |> Enum.map(&Task.async(fn ->\n run_check(&1, source_files, config)\n end))\n |> Enum.each(&Task.await(&1, :infinity))\n\n SourceFileIssues.update_in_source_files(source_files)\n end\n\n defp run_checks(%SourceFile{} = source_file, checks, config) when is_list(checks) do\n Enum.flat_map(checks, &run_check(&1, source_file, config))\n end\n\n defp run_check({_check, false}, source_files, _config) when is_list(source_files) do\n source_files\n end\n defp run_check({_check, false}, _source_file, _config) do\n []\n end\n defp run_check({check}, source_file, config) do\n run_check({check, []}, source_file, config)\n end\n defp run_check({check, params}, source_file, config) do\n try do\n check.run(source_file, params)\n rescue\n error ->\n warn_about_failed_run(check, source_file)\n if config.crash_on_error do\n reraise error, System.stacktrace()\n else\n []\n end\n end\n end\n\n defp warn_about_failed_run(check, %SourceFile{} = source_file) do\n UI.warn(\"Error while running #{check} on #{source_file.filename}\")\n end\n defp warn_about_failed_run(check, _) do\n UI.warn(\"Error while running #{check}\")\n end\n\n defp run_on_all_check?({check}), do: check.run_on_all?\n defp run_on_all_check?({check, _params}), do: check.run_on_all?\nend\n","old_contents":"defmodule Credo.Check.Runner do\n alias Credo.CLI.Output.UI\n alias Credo.Config\n alias Credo.SourceFile\n alias Credo.Service.SourceFileIssues\n\n @doc false\n def run(source_files, config) when is_list(source_files) do\n {_time_run_on_all, source_files_after_run_on_all} =\n :timer.tc fn ->\n run_checks_that_run_on_all(source_files, config)\n end\n\n {_time_run, source_files} =\n :timer.tc fn ->\n source_files_after_run_on_all\n |> Enum.map(&Task.async(fn -> run(&1, config) end))\n |> Enum.map(&Task.await(&1, :infinity))\n end\n\n {source_files, config}\n end\n def run(%SourceFile{} = source_file, config) do\n checks =\n config\n |> Config.checks\n |> Enum.reject(&run_on_all_check?\/1)\n\n issues = run_checks(source_file, checks, config)\n\n %SourceFile{source_file | issues: source_file.issues ++ issues}\n end\n\n @doc \"\"\"\n Prepares the Config struct based on a given list of `source_files`.\n \"\"\"\n def prepare_config(config) do\n prepare_config(config, config.source_files)\n end\n def prepare_config(config, source_files) do\n # TODO: remove prepare_config\/2\n config\n |> set_lint_attributes(source_files)\n |> exclude_low_priority_checks(config.min_priority - 9)\n |> exclude_checks_based_on_elixir_version\n end\n\n defp set_lint_attributes(config, source_files) do\n lint_attribute_map =\n source_files\n |> run_linter_attribute_reader(config)\n |> Enum.reduce(%{}, fn(source_file, memo) ->\n # TODO: we should modify the config \"directly\" instead of going\n # through the SourceFile\n Map.put(memo, source_file.filename, source_file.lint_attributes)\n end)\n\n %Config{config | lint_attribute_map: lint_attribute_map}\n end\n\n defp run_linter_attribute_reader(source_files, config) do\n checks = [{Credo.Check.FindLintAttributes}]\n\n Enum.reduce(checks, source_files, fn(check_tuple, source_files) ->\n run_check(check_tuple, source_files, config)\n end)\n end\n\n defp exclude_low_priority_checks(config, below_priority) do\n checks =\n Enum.reject(config.checks, fn\n ({check}) -> check.base_priority < below_priority\n ({_check, false}) -> true\n ({check, opts}) ->\n (opts[:priority] || check.base_priority) < below_priority\n end)\n\n %Config{config | checks: checks}\n end\n\n defp exclude_checks_based_on_elixir_version(config) do\n version = System.version()\n skipped_checks = Enum.reject(config.checks, &matches_requirement?(&1, version))\n checks = Enum.filter(config.checks, &matches_requirement?(&1, version))\n\n %Config{config | checks: checks, skipped_checks: skipped_checks}\n end\n\n defp matches_requirement?({check, _}, version) do\n matches_requirement?({check}, version)\n end\n defp matches_requirement?({check}, version) do\n Version.match?(version, check.elixir_version)\n end\n\n defp run_checks_that_run_on_all(source_files, config) do\n checks =\n config\n |> Config.checks\n |> Enum.filter(&run_on_all_check?\/1)\n\n checks\n |> Enum.map(&Task.async(fn ->\n run_check(&1, source_files, config)\n end))\n |> Enum.each(&Task.await(&1, :infinity))\n\n SourceFileIssues.update_in_source_files(source_files)\n end\n\n defp run_checks(%SourceFile{} = source_file, checks, config) when is_list(checks) do\n Enum.flat_map(checks, &run_check(&1, source_file, config))\n end\n\n defp run_check({_check, false}, source_files, _config) when is_list(source_files) do\n source_files\n end\n defp run_check({_check, false}, _source_file, _config) do\n []\n end\n defp run_check({check}, source_file, config) do\n run_check({check, []}, source_file, config)\n end\n defp run_check({check, params}, source_file, config) do\n try do\n check.run(source_file, params)\n rescue\n error ->\n warn_about_failed_run(check, source_file)\n if config.crash_on_error do\n reraise error, System.stacktrace()\n else\n []\n end\n end\n end\n\n defp warn_about_failed_run(check, %SourceFile{} = source_file) do\n UI.warn(\"Error while running #{check} on #{source_file.filename}\")\n end\n defp warn_about_failed_run(check, _) do\n UI.warn(\"Error while running #{check}\")\n end\n\n defp run_on_all_check?({check}), do: check.run_on_all?\n defp run_on_all_check?({check, _params}), do: check.run_on_all?\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"d91469b797571554987c2b441b4c94b97c0bea10","subject":"List cookies","message":"List cookies\n","repos":"rozap\/exsoda","old_file":"lib\/exsoda\/auth_server.ex","new_file":"lib\/exsoda\/auth_server.ex","new_contents":"defmodule Exsoda.AuthServer do\n use GenServer\n\n @clear_timeout 10 * 60 * 1000\n\n defmodule State do\n defstruct pending: %{}, cookies: %{}\n end\n\n def start_link() do\n GenServer.start_link(__MODULE__, [], [name: __MODULE__])\n end\n\n def init([]) do\n :timer.apply_interval(@clear_timeout, __MODULE__, :clear_cookies, [])\n {:ok, %State{}}\n end\n\n def get_cookie(opts) do\n GenServer.call(__MODULE__, {:get_cookie, opts})\n end\n\n def list_cookies() do\n GenServer.call(__MODULE__, :list_cookies)\n end\n\n def clear_cookies() do\n GenServer.cast(__MODULE__, :clear_cookies)\n end\n\n def handle_call({:get_cookie, opts}, reply, %State{pending: pending, cookies: cookies} = state) do\n key = Map.take(opts, [:host, :domain, :api_root, :protocol, :spoof])\n case cookies[key] do\n nil ->\n {worker, _ref} = spawn_monitor(fn ->\n result = Exsoda.Http.get_cookie_impl(opts)\n GenServer.cast(__MODULE__, {:cookie_result, self(), reply, key, result})\n end)\n {:noreply, %State{state | pending: Map.put(pending, worker, reply)}}\n cookie ->\n {:reply, {:ok, cookie}, state}\n end\n end\n\n def handle_call(:list_cookies, _, %State{cookies: cookies} = state) do\n {:reply, cookies, state}\n end\n\n def handle_cast(:clear_cookies, %State{} = state) do\n {:noreply, %State{state | cookies: %{}}}\n end\n\n def handle_cast({:cookie_result, worker, reply, key, {:ok, cookie} = response}, %State{pending: pending, cookies: cookies} = state) do\n GenServer.reply(reply, response)\n {:noreply, %State{state | pending: Map.delete(pending, worker),\n cookies: Map.put(cookies, key, cookie)}}\n end\n def handle_cast({:cookie_result, worker, reply, _key, response}, %State{pending: pending} = state) do\n GenServer.reply(reply, response)\n {:noreply, %State{state | pending: Map.delete(pending, worker)}}\n end\n\n def handle_cast({:DOWN, _ref, _type, pid, info}, %State{pending: pending} = state) do\n case Map.get(pending, pid) do\n nil ->\n {:noreply, state}\n reply ->\n GenServer.reply(reply, {:error, info})\n {:noreply, %State{state | pending: Map.delete(pending, pid)}}\n end\n end\nend\n","old_contents":"defmodule Exsoda.AuthServer do\n use GenServer\n\n @clear_timeout 10 * 60 * 1000\n\n defmodule State do\n defstruct pending: %{}, cookies: %{}\n end\n\n def start_link() do\n GenServer.start_link(__MODULE__, [], [name: __MODULE__])\n end\n\n def init([]) do\n :timer.apply_interval(@clear_timeout, __MODULE__, :clear_cookies, [])\n {:ok, %State{}}\n end\n\n def get_cookie(opts) do\n GenServer.call(__MODULE__, {:get_cookie, opts})\n end\n\n def clear_cookies() do\n GenServer.cast(__MODULE__, :clear_cookies)\n end\n\n def handle_call({:get_cookie, opts}, reply, %State{pending: pending, cookies: cookies} = state) do\n key = Map.take(opts, [:host, :domain, :api_root, :protocol, :spoof])\n case cookies[key] do\n nil ->\n {worker, _ref} = spawn_monitor(fn ->\n result = Exsoda.Http.get_cookie_impl(opts)\n GenServer.cast(__MODULE__, {:cookie_result, self(), reply, key, result})\n end)\n {:noreply, %State{state | pending: Map.put(pending, worker, reply)}}\n cookie ->\n {:reply, {:ok, cookie}, state}\n end\n end\n\n def handle_cast(:clear_cookies, %State{} = state) do\n {:noreply, %State{state | cookies: %{}}}\n end\n\n def handle_cast({:cookie_result, worker, reply, key, {:ok, cookie} = response}, %State{pending: pending, cookies: cookies} = state) do\n GenServer.reply(reply, response)\n {:noreply, %State{state | pending: Map.delete(pending, worker),\n cookies: Map.put(cookies, key, cookie)}}\n end\n def handle_cast({:cookie_result, worker, reply, _key, response}, %State{pending: pending} = state) do\n GenServer.reply(reply, response)\n {:noreply, %State{state | pending: Map.delete(pending, worker)}}\n end\n\n def handle_cast({:DOWN, _ref, _type, pid, info}, %State{pending: pending} = state) do\n case Map.get(pending, pid) do\n nil ->\n {:noreply, state}\n reply ->\n GenServer.reply(reply, {:error, info})\n {:noreply, %State{state | pending: Map.delete(pending, pid)}}\n end\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"bc29450f67e1e899a677d7064e2cf37797115af7","subject":"Subjective word ordering","message":"Subjective word ordering\n\nSubjectively, I find this to read better. Perhaps it's part of my North\nAmerican dialect?\n","repos":"elixirkoans\/elixir-koans,samstarling\/elixir-koans","old_file":"lib\/koans\/10_processes.ex","new_file":"lib\/koans\/10_processes.ex","new_contents":"defmodule Processes do\n use Koans\n\n koan \"Tests run in a process\" do\n assert Process.alive?(self()) == ___\n end\n\n koan \"You can ask a process to introduce itself\" do\n information = Process.info(self())\n\n assert information[:status] == ___\n end\n\n koan \"You can send messages to any process you want\" do\n send self(), \"hola!\"\n assert_receive ___\n end\n\n koan \"A common pattern is to include the sender in the message\" do\n pid = spawn(fn -> receive do\n {:hello, sender} -> send sender, :how_are_you?\n _ -> assert false\n end\n end)\n\n send pid, {:hello, self()}\n assert_receive ___\n end\n\n koan \"Waiting for a message can get boring\" do\n parent = self()\n spawn(fn -> receive do\n after\n 5 -> send parent, {:waited_too_long, \"I am impatient\"}\n end\n end)\n\n assert_receive ___\n end\n\n koan \"Killing a process will terminate it\" do\n pid = spawn(fn -> Process.exit(self(), :kill) end)\n :timer.sleep(500)\n assert Process.alive?(pid) == ___\n end\n\n koan \"You can also terminate processes other than yourself\" do\n pid = spawn(fn -> receive do end end)\n\n assert Process.alive?(pid) == ___\n Process.exit(pid, :kill)\n assert Process.alive?(pid) == ___\n end\n\n koan \"Trapping will allow you to react to someone terminating the process\" do\n parent = self()\n pid = spawn(fn ->\n Process.flag(:trap_exit, true)\n send parent, :ready\n receive do\n {:EXIT, _pid, reason} -> send parent, {:exited, reason}\n end\n end)\n wait()\n Process.exit(pid, :random_reason)\n\n assert_receive ___\n end\n\n koan \"Trying to quit normally has no effect\" do\n pid = spawn(fn -> receive do\n end\n end)\n Process.exit(pid, :normal)\n assert Process.alive?(pid) == ___\n end\n\n koan \"Exiting yourself on the other hand DOES terminate you\" do\n pid = spawn(fn -> receive do\n :bye -> Process.exit(self(), :normal)\n end\n end)\n\n send pid, :bye\n :timer.sleep(100)\n assert Process.alive?(pid) == ___\n end\n\n koan \"Parent processes can be informed about exiting children, if they trap and link\" do\n parent = self()\n spawn(fn ->\n Process.flag(:trap_exit, true)\n spawn_link(fn -> Process.exit(self(), :normal) end)\n receive do\n {:EXIT, _pid ,reason} -> send parent, {:exited, reason}\n end\n end)\n\n assert_receive ___\n end\n\n koan \"If you monitor your children, you'll be automatically informed for their depature\" do\n parent = self()\n spawn(fn ->\n spawn_monitor(fn -> Process.exit(self(), :normal) end)\n receive do\n {:DOWN, _ref, :process, _pid, reason} -> send parent, {:exited, reason}\n end\n end)\n\n assert_receive ___\n end\n\n def wait do\n receive do\n :ready -> true\n end\n end\nend\n","old_contents":"defmodule Processes do\n use Koans\n\n koan \"Tests run in a process\" do\n assert Process.alive?(self()) == ___\n end\n\n koan \"You can ask a process to introduce itself\" do\n information = Process.info(self())\n\n assert information[:status] == ___\n end\n\n koan \"You can send messages to any process you want\" do\n send self(), \"hola!\"\n assert_receive ___\n end\n\n koan \"A common pattern is to include the sender in the message\" do\n pid = spawn(fn -> receive do\n {:hello, sender} -> send sender, :how_are_you?\n _ -> assert false\n end\n end)\n\n send pid, {:hello, self()}\n assert_receive ___\n end\n\n koan \"Waiting for a message can get boring\" do\n parent = self()\n spawn(fn -> receive do\n after\n 5 -> send parent, {:waited_too_long, \"I am impatient\"}\n end\n end)\n\n assert_receive ___\n end\n\n koan \"Killing a process will terminate it\" do\n pid = spawn(fn -> Process.exit(self(), :kill) end)\n :timer.sleep(500)\n assert Process.alive?(pid) == ___\n end\n\n koan \"You can also terminate other processes than yourself\" do\n pid = spawn(fn -> receive do end end)\n\n assert Process.alive?(pid) == ___\n Process.exit(pid, :kill)\n assert Process.alive?(pid) == ___\n end\n\n koan \"Trapping will allow you to react to someone terminating the process\" do\n parent = self()\n pid = spawn(fn ->\n Process.flag(:trap_exit, true)\n send parent, :ready\n receive do\n {:EXIT, _pid, reason} -> send parent, {:exited, reason}\n end\n end)\n wait()\n Process.exit(pid, :random_reason)\n\n assert_receive ___\n end\n\n koan \"Trying to quit normally has no effect\" do\n pid = spawn(fn -> receive do\n end\n end)\n Process.exit(pid, :normal)\n assert Process.alive?(pid) == ___\n end\n\n koan \"Exiting yourself on the other hand DOES terminate you\" do\n pid = spawn(fn -> receive do\n :bye -> Process.exit(self(), :normal)\n end\n end)\n\n send pid, :bye\n :timer.sleep(100)\n assert Process.alive?(pid) == ___\n end\n\n koan \"Parent processes can be informed about exiting children, if they trap and link\" do\n parent = self()\n spawn(fn ->\n Process.flag(:trap_exit, true)\n spawn_link(fn -> Process.exit(self(), :normal) end)\n receive do\n {:EXIT, _pid ,reason} -> send parent, {:exited, reason}\n end\n end)\n\n assert_receive ___\n end\n\n koan \"If you monitor your children, you'll be automatically informed for their depature\" do\n parent = self()\n spawn(fn ->\n spawn_monitor(fn -> Process.exit(self(), :normal) end)\n receive do\n {:DOWN, _ref, :process, _pid, reason} -> send parent, {:exited, reason}\n end\n end)\n\n assert_receive ___\n end\n\n def wait do\n receive do\n :ready -> true\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"79192173db21abf3de40569702d7438aea462009","subject":"Document Enum.EmptyError exception for Enum.reduce\/2 (#6986)","message":"Document Enum.EmptyError exception for Enum.reduce\/2 (#6986)\n\n","repos":"gfvcastro\/elixir,gfvcastro\/elixir,kimshrier\/elixir,lexmag\/elixir,michalmuskala\/elixir,kelvinst\/elixir,elixir-lang\/elixir,ggcampinho\/elixir,lexmag\/elixir,kelvinst\/elixir,ggcampinho\/elixir,pedrosnk\/elixir,kimshrier\/elixir,joshprice\/elixir,pedrosnk\/elixir","old_file":"lib\/elixir\/lib\/enum.ex","new_file":"lib\/elixir\/lib\/enum.ex","new_contents":"defprotocol Enumerable do\n @moduledoc \"\"\"\n Enumerable protocol used by `Enum` and `Stream` modules.\n\n When you invoke a function in the `Enum` module, the first argument\n is usually a collection that must implement this protocol.\n For example, the expression:\n\n Enum.map([1, 2, 3], &(&1 * 2))\n\n invokes `Enumerable.reduce\/3` to perform the reducing operation that\n builds a mapped list by calling the mapping function `&(&1 * 2)` on\n every element in the collection and consuming the element with an\n accumulated list.\n\n Internally, `Enum.map\/2` is implemented as follows:\n\n def map(enum, fun) do\n reducer = fn x, acc -> {:cont, [fun.(x) | acc]} end\n Enumerable.reduce(enum, {:cont, []}, reducer) |> elem(1) |> :lists.reverse()\n end\n\n Notice the user-supplied function is wrapped into a `t:reducer\/0` function.\n The `t:reducer\/0` function must return a tagged tuple after each step,\n as described in the `t:acc\/0` type. At the end, `Enumerable.reduce\/3`\n returns `t:result\/0`.\n\n This protocol uses tagged tuples to exchange information between the\n reducer function and the data type that implements the protocol. This\n allows enumeration of resources, such as files, to be done efficiently\n while also guaranteeing the resource will be closed at the end of the\n enumeration. This protocol also allows suspension of the enumeration,\n which is useful when interleaving between many enumerables is required\n (as in zip).\n\n This protocol requires four functions to be implemented, `reduce\/3`,\n `count\/1`, `member?\/2`, and `slice\/1`. The core of the protocol is the\n `reduce\/3` function. All other functions exist as optimizations paths\n for data structures that can implement certain properties in better\n than linear time.\n \"\"\"\n\n @typedoc \"\"\"\n The accumulator value for each step.\n\n It must be a tagged tuple with one of the following \"tags\":\n\n * `:cont` - the enumeration should continue\n * `:halt` - the enumeration should halt immediately\n * `:suspend` - the enumeration should be suspended immediately\n\n Depending on the accumulator value, the result returned by\n `Enumerable.reduce\/3` will change. Please check the `t:result\/0`\n type documentation for more information.\n\n In case a `t:reducer\/0` function returns a `:suspend` accumulator,\n it must be explicitly handled by the caller and never leak.\n \"\"\"\n @type acc :: {:cont, term} | {:halt, term} | {:suspend, term}\n\n @typedoc \"\"\"\n The reducer function.\n\n Should be called with the enumerable element and the\n accumulator contents.\n\n Returns the accumulator for the next enumeration step.\n \"\"\"\n @type reducer :: (term, term -> acc)\n\n @typedoc \"\"\"\n The result of the reduce operation.\n\n It may be *done* when the enumeration is finished by reaching\n its end, or *halted*\/*suspended* when the enumeration was halted\n or suspended by the `t:reducer\/0` function.\n\n In case a `t:reducer\/0` function returns the `:suspend` accumulator, the\n `:suspended` tuple must be explicitly handled by the caller and\n never leak. In practice, this means regular enumeration functions\n just need to be concerned about `:done` and `:halted` results.\n\n Furthermore, a `:suspend` call must always be followed by another call,\n eventually halting or continuing until the end.\n \"\"\"\n @type result ::\n {:done, term}\n | {:halted, term}\n | {:suspended, term, continuation}\n\n @typedoc \"\"\"\n A partially applied reduce function.\n\n The continuation is the closure returned as a result when\n the enumeration is suspended. When invoked, it expects\n a new accumulator and it returns the result.\n\n A continuation can be trivially implemented as long as the reduce\n function is defined in a tail recursive fashion. If the function\n is tail recursive, all the state is passed as arguments, so\n the continuation is the reducing function partially applied.\n \"\"\"\n @type continuation :: (acc -> result)\n\n @typedoc \"\"\"\n A slicing function that receives the initial position and the\n number of elements in the slice.\n\n The `start` position is a number `>= 0` and guaranteed to\n exist in the enumerable. The length is a number `>= 1` in a way\n that `start + length <= count`, where `count` is the maximum\n amount of elements in the enumerable.\n\n The function should return a non empty list where\n the amount of elements is equal to `length`.\n \"\"\"\n @type slicing_fun :: (start :: non_neg_integer, length :: pos_integer -> [term()])\n\n @doc \"\"\"\n Reduces the enumerable into an element.\n\n Most of the operations in `Enum` are implemented in terms of reduce.\n This function should apply the given `t:reducer\/0` function to each\n item in the enumerable and proceed as expected by the returned\n accumulator.\n\n See the documentation of the types `t:result\/0` and `t:acc\/0` for\n more information.\n\n ## Examples\n\n As an example, here is the implementation of `reduce` for lists:\n\n def reduce(_, {:halt, acc}, _fun), do: {:halted, acc}\n def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)}\n def reduce([], {:cont, acc}, _fun), do: {:done, acc}\n def reduce([h | t], {:cont, acc}, fun), do: reduce(t, fun.(h, acc), fun)\n\n \"\"\"\n @spec reduce(t, acc, reducer) :: result\n def reduce(enumerable, acc, fun)\n\n @doc \"\"\"\n Retrieves the number of elements in the enumerable.\n\n It should return `{:ok, count}` if you can count the number of elements\n in the enumerable.\n\n Otherwise it should return `{:error, __MODULE__}` and a default algorithm\n built on top of `reduce\/3` that runs in linear time will be used.\n \"\"\"\n @spec count(t) :: {:ok, non_neg_integer} | {:error, module}\n def count(enumerable)\n\n @doc \"\"\"\n Checks if an element exists within the enumerable.\n\n It should return `{:ok, boolean}` if you can check the membership of a\n given element in the enumerable with `===` without traversing the whole\n enumerable.\n\n Otherwise it should return `{:error, __MODULE__}` and a default algorithm\n built on top of `reduce\/3` that runs in linear time will be used.\n \"\"\"\n @spec member?(t, term) :: {:ok, boolean} | {:error, module}\n def member?(enumerable, element)\n\n @doc \"\"\"\n Returns a function that slices the data structure contiguously.\n\n It should return `{:ok, size, slicing_fun}` if the enumerable has\n a known bound and can access a position in the enumerable without\n traversing all previous elements.\n\n Otherwise it should return `{:error, __MODULE__}` and a default\n algorithm built on top of `reduce\/3` that runs in linear time will be\n used.\n\n ## Differences to `count\/1`\n\n The `size` value returned by this function is used for boundary checks,\n therefore it is extremely important that this function only returns `:ok`\n if retrieving the `size` of the enumerable is cheap, fast and takes constant\n time. Otherwise the simplest of operations, such as `Enum.at(enumerable, 0)`,\n will become too expensive.\n\n On the other hand, the `count\/1` function in this protocol should be\n implemented whenever you can count the number of elements in the collection.\n \"\"\"\n @spec slice(t) ::\n {:ok, size :: non_neg_integer(), slicing_fun()}\n | {:error, module()}\n def slice(enumerable)\nend\n\ndefmodule Enum do\n import Kernel, except: [max: 2, min: 2]\n\n @moduledoc \"\"\"\n Provides a set of algorithms that enumerate over enumerables according\n to the `Enumerable` protocol.\n\n iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end)\n [2, 4, 6]\n\n Some particular types, like maps, yield a specific format on enumeration.\n For example, the argument is always a `{key, value}` tuple for maps:\n\n iex> map = %{a: 1, b: 2}\n iex> Enum.map(map, fn {k, v} -> {k, v * 2} end)\n [a: 2, b: 4]\n\n Note that the functions in the `Enum` module are eager: they always\n start the enumeration of the given enumerable. The `Stream` module\n allows lazy enumeration of enumerables and provides infinite streams.\n\n Since the majority of the functions in `Enum` enumerate the whole\n enumerable and return a list as result, infinite streams need to\n be carefully used with such functions, as they can potentially run\n forever. For example:\n\n Enum.each Stream.cycle([1, 2, 3]), &IO.puts(&1)\n\n \"\"\"\n\n @compile :inline_list_funcs\n\n @type t :: Enumerable.t()\n @type acc :: any\n @type element :: any\n @type index :: integer\n @type default :: any\n\n # Require Stream.Reducers and its callbacks\n require Stream.Reducers, as: R\n\n defmacrop skip(acc) do\n acc\n end\n\n defmacrop next(_, entry, acc) do\n quote(do: [unquote(entry) | unquote(acc)])\n end\n\n defmacrop acc(head, state, _) do\n quote(do: {unquote(head), unquote(state)})\n end\n\n defmacrop next_with_acc(_, entry, head, state, _) do\n quote do\n {[unquote(entry) | unquote(head)], unquote(state)}\n end\n end\n\n @doc \"\"\"\n Returns true if the given `fun` evaluates to true on all of the items in the enumerable.\n\n It stops the iteration at the first invocation that returns `false` or `nil`.\n\n ## Examples\n\n iex> Enum.all?([2, 4, 6], fn(x) -> rem(x, 2) == 0 end)\n true\n\n iex> Enum.all?([2, 3, 4], fn(x) -> rem(x, 2) == 0 end)\n false\n\n If no function is given, it defaults to checking if\n all items in the enumerable are truthy values.\n\n iex> Enum.all?([1, 2, 3])\n true\n\n iex> Enum.all?([1, nil, 3])\n false\n\n \"\"\"\n @spec all?(t, (element -> as_boolean(term))) :: boolean\n\n def all?(enumerable, fun \\\\ fn x -> x end)\n\n def all?(enumerable, fun) when is_list(enumerable) do\n all_list(enumerable, fun)\n end\n\n def all?(enumerable, fun) do\n Enumerable.reduce(enumerable, {:cont, true}, fn entry, _ ->\n if fun.(entry), do: {:cont, true}, else: {:halt, false}\n end)\n |> elem(1)\n end\n\n @doc \"\"\"\n Returns true if the given `fun` evaluates to true on any of the items in the enumerable.\n\n It stops the iteration at the first invocation that returns a truthy value (not `false` or `nil`).\n\n ## Examples\n\n iex> Enum.any?([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n false\n\n iex> Enum.any?([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n true\n\n If no function is given, it defaults to checking if at least one item\n in the enumerable is a truthy value.\n\n iex> Enum.any?([false, false, false])\n false\n\n iex> Enum.any?([false, true, false])\n true\n\n \"\"\"\n @spec any?(t, (element -> as_boolean(term))) :: boolean\n\n def any?(enumerable, fun \\\\ fn x -> x end)\n\n def any?(enumerable, fun) when is_list(enumerable) do\n any_list(enumerable, fun)\n end\n\n def any?(enumerable, fun) do\n Enumerable.reduce(enumerable, {:cont, false}, fn entry, _ ->\n if fun.(entry), do: {:halt, true}, else: {:cont, false}\n end)\n |> elem(1)\n end\n\n @doc \"\"\"\n Finds the element at the given `index` (zero-based).\n\n Returns `default` if `index` is out of bounds.\n\n A negative `index` can be passed, which means the `enumerable` is\n enumerated once and the `index` is counted from the end (e.g.\n `-1` finds the last element).\n\n Note this operation takes linear time. In order to access\n the element at index `index`, it will need to traverse `index`\n previous elements.\n\n ## Examples\n\n iex> Enum.at([2, 4, 6], 0)\n 2\n\n iex> Enum.at([2, 4, 6], 2)\n 6\n\n iex> Enum.at([2, 4, 6], 4)\n nil\n\n iex> Enum.at([2, 4, 6], 4, :none)\n :none\n\n \"\"\"\n @spec at(t, index, default) :: element | default\n def at(enumerable, index, default \\\\ nil) do\n case slice_any(enumerable, index, 1) do\n [value] -> value\n [] -> default\n end\n end\n\n # Deprecate on v1.7\n @doc false\n def chunk(enumerable, count), do: chunk(enumerable, count, count, nil)\n\n # Deprecate on v1.7\n @doc false\n def chunk(enumerable, count, step, leftover \\\\ nil) do\n chunk_every(enumerable, count, step, leftover || :discard)\n end\n\n @doc \"\"\"\n Shortcut to `chunk_every(enumerable, count, count)`.\n \"\"\"\n @spec chunk_every(t, pos_integer) :: [list]\n def chunk_every(enumerable, count), do: chunk_every(enumerable, count, count, [])\n\n @doc \"\"\"\n Returns list of lists containing `count` items each, where\n each new chunk starts `step` elements into the enumerable.\n\n `step` is optional and, if not passed, defaults to `count`, i.e.\n chunks do not overlap.\n\n If the last chunk does not have `count` elements to fill the chunk,\n elements are taken from `leftover` to fill in the chunk. If `leftover`\n does not have enough elements to fill the chunk, then a partial chunk\n is returned with less than `count` elements.\n\n If `:discard` is given in `leftover`, the last chunk is discarded\n unless it has exactly `count` elements.\n\n ## Examples\n\n iex> Enum.chunk_every([1, 2, 3, 4, 5, 6], 2)\n [[1, 2], [3, 4], [5, 6]]\n\n iex> Enum.chunk_every([1, 2, 3, 4, 5, 6], 3, 2, :discard)\n [[1, 2, 3], [3, 4, 5]]\n\n iex> Enum.chunk_every([1, 2, 3, 4, 5, 6], 3, 2, [7])\n [[1, 2, 3], [3, 4, 5], [5, 6, 7]]\n\n iex> Enum.chunk_every([1, 2, 3, 4], 3, 3, [])\n [[1, 2, 3], [4]]\n\n iex> Enum.chunk_every([1, 2, 3, 4], 10)\n [[1, 2, 3, 4]]\n\n \"\"\"\n @spec chunk_every(t, pos_integer, pos_integer, t | :discard) :: [list]\n def chunk_every(enumerable, count, step, leftover \\\\ [])\n when is_integer(count) and count > 0 and is_integer(step) and step > 0 do\n R.chunk_every(&chunk_while\/4, enumerable, count, step, leftover)\n end\n\n @doc \"\"\"\n Chunks the `enum` with fine grained control when every chunk is emitted.\n\n `chunk_fun` receives the current element and the accumulator and\n must return `{:cont, element, acc}` to emit the given chunk and\n continue with accumulator or `{:cont, acc}` to not emit any chunk\n and continue with the return accumulator.\n\n `after_fun` is invoked when iteration is done and must also return\n `{:cont, element, acc}` or `{:cont, acc}`.\n\n Returns a list of lists.\n\n ## Examples\n\n iex> chunk_fun = fn i, acc ->\n ...> if rem(i, 2) == 0 do\n ...> {:cont, Enum.reverse([i | acc]), []}\n ...> else\n ...> {:cont, [i | acc]}\n ...> end\n ...> end\n iex> after_fun = fn\n ...> [] -> {:cont, []}\n ...> acc -> {:cont, Enum.reverse(acc), []}\n ...> end\n iex> Enum.chunk_while(1..10, [], chunk_fun, after_fun)\n [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]\n\n \"\"\"\n @spec chunk_while(\n t,\n acc,\n (element, acc -> {:cont, chunk, acc} | {:cont, acc} | {:halt, acc}),\n (acc -> {:cont, chunk, acc} | {:cont, acc})\n ) :: Enumerable.t()\n when chunk: any\n def chunk_while(enum, acc, chunk_fun, after_fun) do\n {_, {res, acc}} =\n Enumerable.reduce(enum, {:cont, {[], acc}}, fn entry, {buffer, acc} ->\n case chunk_fun.(entry, acc) do\n {:cont, emit, acc} -> {:cont, {[emit | buffer], acc}}\n {:cont, acc} -> {:cont, {buffer, acc}}\n {:halt, acc} -> {:halt, {buffer, acc}}\n end\n end)\n\n case after_fun.(acc) do\n {:cont, _acc} -> :lists.reverse(res)\n {:cont, elem, _acc} -> :lists.reverse([elem | res])\n end\n end\n\n @doc \"\"\"\n Splits enumerable on every element for which `fun` returns a new\n value.\n\n Returns a list of lists.\n\n ## Examples\n\n iex> Enum.chunk_by([1, 2, 2, 3, 4, 4, 6, 7, 7], &(rem(&1, 2) == 1))\n [[1], [2, 2], [3], [4, 4, 6], [7, 7]]\n\n \"\"\"\n @spec chunk_by(t, (element -> any)) :: [list]\n def chunk_by(enumerable, fun) do\n R.chunk_by(&chunk_while\/4, enumerable, fun)\n end\n\n @doc \"\"\"\n Given an enumerable of enumerables, concatenates the enumerables into\n a single list.\n\n ## Examples\n\n iex> Enum.concat([1..3, 4..6, 7..9])\n [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n iex> Enum.concat([[1, [2], 3], [4], [5, 6]])\n [1, [2], 3, 4, 5, 6]\n\n \"\"\"\n @spec concat(t) :: t\n def concat(enumerables) do\n fun = &[&1 | &2]\n reduce(enumerables, [], &reduce(&1, &2, fun)) |> :lists.reverse()\n end\n\n @doc \"\"\"\n Concatenates the enumerable on the right with the enumerable on the\n left.\n\n This function produces the same result as the `Kernel.++\/2` operator\n for lists.\n\n ## Examples\n\n iex> Enum.concat(1..3, 4..6)\n [1, 2, 3, 4, 5, 6]\n\n iex> Enum.concat([1, 2, 3], [4, 5, 6])\n [1, 2, 3, 4, 5, 6]\n\n \"\"\"\n @spec concat(t, t) :: t\n def concat(left, right) when is_list(left) and is_list(right) do\n left ++ right\n end\n\n def concat(left, right) do\n concat([left, right])\n end\n\n @doc \"\"\"\n Returns the size of the enumerable.\n\n ## Examples\n\n iex> Enum.count([1, 2, 3])\n 3\n\n \"\"\"\n @spec count(t) :: non_neg_integer\n def count(enumerable) when is_list(enumerable) do\n length(enumerable)\n end\n\n def count(enumerable) do\n case Enumerable.count(enumerable) do\n {:ok, value} when is_integer(value) ->\n value\n\n {:error, module} ->\n module.reduce(enumerable, {:cont, 0}, fn _, acc -> {:cont, acc + 1} end) |> elem(1)\n end\n end\n\n @doc \"\"\"\n Returns the count of items in the enumerable for which `fun` returns\n a truthy value.\n\n ## Examples\n\n iex> Enum.count([1, 2, 3, 4, 5], fn(x) -> rem(x, 2) == 0 end)\n 2\n\n \"\"\"\n @spec count(t, (element -> as_boolean(term))) :: non_neg_integer\n def count(enumerable, fun) do\n reduce(enumerable, 0, fn entry, acc ->\n if(fun.(entry), do: acc + 1, else: acc)\n end)\n end\n\n @doc \"\"\"\n Enumerates the `enumerable`, returning a list where all consecutive\n duplicated elements are collapsed to a single element.\n\n Elements are compared using `===`.\n\n If you want to remove all duplicated elements, regardless of order,\n see `uniq\/1`.\n\n ## Examples\n\n iex> Enum.dedup([1, 2, 3, 3, 2, 1])\n [1, 2, 3, 2, 1]\n\n iex> Enum.dedup([1, 1, 2, 2.0, :three, :\"three\"])\n [1, 2, 2.0, :three]\n\n \"\"\"\n @spec dedup(t) :: list\n def dedup(enumerable) do\n dedup_by(enumerable, fn x -> x end)\n end\n\n @doc \"\"\"\n Enumerates the `enumerable`, returning a list where all consecutive\n duplicated elements are collapsed to a single element.\n\n The function `fun` maps every element to a term which is used to\n determine if two elements are duplicates.\n\n ## Examples\n\n iex> Enum.dedup_by([{1, :a}, {2, :b}, {2, :c}, {1, :a}], fn {x, _} -> x end)\n [{1, :a}, {2, :b}, {1, :a}]\n\n iex> Enum.dedup_by([5, 1, 2, 3, 2, 1], fn x -> x > 2 end)\n [5, 1, 3, 2]\n\n \"\"\"\n @spec dedup_by(t, (element -> term)) :: list\n def dedup_by(enumerable, fun) do\n {list, _} = reduce(enumerable, {[], []}, R.dedup(fun))\n :lists.reverse(list)\n end\n\n @doc \"\"\"\n Drops the `amount` of items from the enumerable.\n\n If a negative `amount` is given, the `amount` of last values will be dropped.\n The `enumerable` will be enumerated once to retrieve the proper index and\n the remaining calculation is performed from the end.\n\n ## Examples\n\n iex> Enum.drop([1, 2, 3], 2)\n [3]\n\n iex> Enum.drop([1, 2, 3], 10)\n []\n\n iex> Enum.drop([1, 2, 3], 0)\n [1, 2, 3]\n\n iex> Enum.drop([1, 2, 3], -1)\n [1, 2]\n\n \"\"\"\n @spec drop(t, integer) :: list\n def drop(enumerable, amount)\n when is_list(enumerable) and is_integer(amount) and amount >= 0 do\n drop_list(enumerable, amount)\n end\n\n def drop(enumerable, amount) when is_integer(amount) and amount >= 0 do\n {result, _} = reduce(enumerable, {[], amount}, R.drop())\n if is_list(result), do: :lists.reverse(result), else: []\n end\n\n def drop(enumerable, amount) when is_integer(amount) and amount < 0 do\n {count, fun} = slice_count_and_fun(enumerable)\n amount = Kernel.min(amount + count, count)\n\n if amount > 0 do\n fun.(0, amount)\n else\n []\n end\n end\n\n @doc \"\"\"\n Returns a list of every `nth` item in the enumerable dropped,\n starting with the first element.\n\n The first item is always dropped, unless `nth` is 0.\n\n The second argument specifying every `nth` item must be a non-negative\n integer.\n\n ## Examples\n\n iex> Enum.drop_every(1..10, 2)\n [2, 4, 6, 8, 10]\n\n iex> Enum.drop_every(1..10, 0)\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n iex> Enum.drop_every([1, 2, 3], 1)\n []\n\n \"\"\"\n @spec drop_every(t, non_neg_integer) :: list\n def drop_every(enumerable, nth)\n\n def drop_every(_enumerable, 1), do: []\n def drop_every(enumerable, 0), do: to_list(enumerable)\n def drop_every([], nth) when is_integer(nth), do: []\n\n def drop_every(enumerable, nth) when is_integer(nth) and nth > 1 do\n {res, _} = reduce(enumerable, {[], :first}, R.drop_every(nth))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Drops items at the beginning of the enumerable while `fun` returns a\n truthy value.\n\n ## Examples\n\n iex> Enum.drop_while([1, 2, 3, 2, 1], fn(x) -> x < 3 end)\n [3, 2, 1]\n\n \"\"\"\n @spec drop_while(t, (element -> as_boolean(term))) :: list\n def drop_while(enumerable, fun) when is_list(enumerable) do\n drop_while_list(enumerable, fun)\n end\n\n def drop_while(enumerable, fun) do\n {res, _} = reduce(enumerable, {[], true}, R.drop_while(fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Invokes the given `fun` for each item in the enumerable.\n\n Returns `:ok`.\n\n ## Examples\n\n Enum.each([\"some\", \"example\"], fn(x) -> IO.puts x end)\n \"some\"\n \"example\"\n #=> :ok\n\n \"\"\"\n @spec each(t, (element -> any)) :: :ok\n def each(enumerable, fun) when is_list(enumerable) do\n :lists.foreach(fun, enumerable)\n :ok\n end\n\n def each(enumerable, fun) do\n reduce(enumerable, nil, fn entry, _ ->\n fun.(entry)\n nil\n end)\n\n :ok\n end\n\n @doc \"\"\"\n Determines if the enumerable is empty.\n\n Returns `true` if `enumerable` is empty, otherwise `false`.\n\n ## Examples\n\n iex> Enum.empty?([])\n true\n\n iex> Enum.empty?([1, 2, 3])\n false\n\n \"\"\"\n @spec empty?(t) :: boolean\n def empty?(enumerable) when is_list(enumerable) do\n enumerable == []\n end\n\n def empty?(enumerable) do\n case Enumerable.slice(enumerable) do\n {:ok, value, _} ->\n value == 0\n\n {:error, module} ->\n module.reduce(enumerable, {:cont, true}, fn _, _ -> {:halt, false} end)\n |> elem(1)\n end\n end\n\n @doc \"\"\"\n Finds the element at the given `index` (zero-based).\n\n Returns `{:ok, element}` if found, otherwise `:error`.\n\n A negative `index` can be passed, which means the `enumerable` is\n enumerated once and the `index` is counted from the end (e.g.\n `-1` fetches the last element).\n\n Note this operation takes linear time. In order to access\n the element at index `index`, it will need to traverse `index`\n previous elements.\n\n ## Examples\n\n iex> Enum.fetch([2, 4, 6], 0)\n {:ok, 2}\n\n iex> Enum.fetch([2, 4, 6], -3)\n {:ok, 2}\n\n iex> Enum.fetch([2, 4, 6], 2)\n {:ok, 6}\n\n iex> Enum.fetch([2, 4, 6], 4)\n :error\n\n \"\"\"\n @spec fetch(t, index) :: {:ok, element} | :error\n def fetch(enumerable, index) do\n case slice_any(enumerable, index, 1) do\n [value] -> {:ok, value}\n [] -> :error\n end\n end\n\n @doc \"\"\"\n Finds the element at the given `index` (zero-based).\n\n Raises `OutOfBoundsError` if the given `index` is outside the range of\n the enumerable.\n\n Note this operation takes linear time. In order to access the element\n at index `index`, it will need to traverse `index` previous elements.\n\n ## Examples\n\n iex> Enum.fetch!([2, 4, 6], 0)\n 2\n\n iex> Enum.fetch!([2, 4, 6], 2)\n 6\n\n iex> Enum.fetch!([2, 4, 6], 4)\n ** (Enum.OutOfBoundsError) out of bounds error\n\n \"\"\"\n @spec fetch!(t, index) :: element | no_return\n def fetch!(enumerable, index) do\n case slice_any(enumerable, index, 1) do\n [value] -> value\n [] -> raise Enum.OutOfBoundsError\n end\n end\n\n @doc \"\"\"\n Filters the enumerable, i.e. returns only those elements\n for which `fun` returns a truthy value.\n\n See also `reject\/2` which discards all elements where the\n function returns true.\n\n ## Examples\n\n iex> Enum.filter([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)\n [2]\n\n Keep in mind that `filter` is not capable of filtering and\n transforming an element at the same time. If you would like\n to do so, consider using `flat_map\/2`. For example, if you\n want to convert all strings that represent an integer and\n discard the invalid one in one pass:\n\n strings = [\"1234\", \"abc\", \"12ab\"]\n Enum.flat_map(strings, fn string ->\n case Integer.parse(string) do\n {int, _rest} -> [int] # transform to integer\n :error -> [] # skip the value\n end\n end)\n\n \"\"\"\n @spec filter(t, (element -> as_boolean(term))) :: list\n def filter(enumerable, fun) when is_list(enumerable) do\n filter_list(enumerable, fun)\n end\n\n def filter(enumerable, fun) do\n reduce(enumerable, [], R.filter(fun)) |> :lists.reverse()\n end\n\n @doc false\n # TODO: Remove on 2.0\n # (hard-deprecated in elixir_dispatch)\n def filter_map(enumerable, filter, mapper) when is_list(enumerable) do\n for item <- enumerable, filter.(item), do: mapper.(item)\n end\n\n def filter_map(enumerable, filter, mapper) do\n enumerable\n |> reduce([], R.filter_map(filter, mapper))\n |> :lists.reverse()\n end\n\n @doc \"\"\"\n Returns the first item for which `fun` returns a truthy value.\n If no such item is found, returns `default`.\n\n ## Examples\n\n iex> Enum.find([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n nil\n\n iex> Enum.find([2, 4, 6], 0, fn(x) -> rem(x, 2) == 1 end)\n 0\n\n iex> Enum.find([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n 3\n\n \"\"\"\n @spec find(t, default, (element -> any)) :: element | default\n def find(enumerable, default \\\\ nil, fun)\n\n def find(enumerable, default, fun) when is_list(enumerable) do\n find_list(enumerable, default, fun)\n end\n\n def find(enumerable, default, fun) do\n Enumerable.reduce(enumerable, {:cont, default}, fn entry, default ->\n if fun.(entry), do: {:halt, entry}, else: {:cont, default}\n end)\n |> elem(1)\n end\n\n @doc \"\"\"\n Similar to `find\/3`, but returns the index (zero-based)\n of the element instead of the element itself.\n\n ## Examples\n\n iex> Enum.find_index([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n nil\n\n iex> Enum.find_index([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n 1\n\n \"\"\"\n @spec find_index(t, (element -> any)) :: non_neg_integer | nil\n def find_index(enumerable, fun) when is_list(enumerable) do\n find_index_list(enumerable, 0, fun)\n end\n\n def find_index(enumerable, fun) do\n result =\n Enumerable.reduce(enumerable, {:cont, {:not_found, 0}}, fn entry, {_, index} ->\n if fun.(entry), do: {:halt, {:found, index}}, else: {:cont, {:not_found, index + 1}}\n end)\n\n case elem(result, 1) do\n {:found, index} -> index\n {:not_found, _} -> nil\n end\n end\n\n @doc \"\"\"\n Similar to `find\/3`, but returns the value of the function\n invocation instead of the element itself.\n\n ## Examples\n\n iex> Enum.find_value([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n nil\n\n iex> Enum.find_value([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n true\n\n iex> Enum.find_value([1, 2, 3], \"no bools!\", &is_boolean\/1)\n \"no bools!\"\n\n \"\"\"\n @spec find_value(t, any, (element -> any)) :: any | nil\n def find_value(enumerable, default \\\\ nil, fun)\n\n def find_value(enumerable, default, fun) when is_list(enumerable) do\n find_value_list(enumerable, default, fun)\n end\n\n def find_value(enumerable, default, fun) do\n Enumerable.reduce(enumerable, {:cont, default}, fn entry, default ->\n fun_entry = fun.(entry)\n if fun_entry, do: {:halt, fun_entry}, else: {:cont, default}\n end)\n |> elem(1)\n end\n\n @doc \"\"\"\n Maps the given `fun` over `enumerable` and flattens the result.\n\n This function returns a new enumerable built by appending the result of invoking `fun`\n on each element of `enumerable` together; conceptually, this is similar to a\n combination of `map\/2` and `concat\/1`.\n\n ## Examples\n\n iex> Enum.flat_map([:a, :b, :c], fn(x) -> [x, x] end)\n [:a, :a, :b, :b, :c, :c]\n\n iex> Enum.flat_map([{1, 3}, {4, 6}], fn({x, y}) -> x..y end)\n [1, 2, 3, 4, 5, 6]\n\n iex> Enum.flat_map([:a, :b, :c], fn(x) -> [[x]] end)\n [[:a], [:b], [:c]]\n\n \"\"\"\n @spec flat_map(t, (element -> t)) :: list\n def flat_map(enumerable, fun) when is_list(enumerable) do\n flat_map_list(enumerable, fun)\n end\n\n def flat_map(enumerable, fun) do\n reduce(enumerable, [], fn entry, acc ->\n case fun.(entry) do\n list when is_list(list) -> :lists.reverse(list, acc)\n other -> reduce(other, acc, &[&1 | &2])\n end\n end)\n |> :lists.reverse()\n end\n\n @doc \"\"\"\n Maps and reduces an enumerable, flattening the given results (only one level deep).\n\n It expects an accumulator and a function that receives each enumerable\n item, and must return a tuple containing a new enumerable (often a list)\n with the new accumulator or a tuple with `:halt` as first element and\n the accumulator as second.\n\n ## Examples\n\n iex> enum = 1..100\n iex> n = 3\n iex> Enum.flat_map_reduce(enum, 0, fn i, acc ->\n ...> if acc < n, do: {[i], acc + 1}, else: {:halt, acc}\n ...> end)\n {[1, 2, 3], 3}\n\n iex> Enum.flat_map_reduce(1..5, 0, fn(i, acc) -> {[[i]], acc + i} end)\n {[[1], [2], [3], [4], [5]], 15}\n\n \"\"\"\n @spec flat_map_reduce(t, acc, fun) :: {[any], any}\n when fun: (element, acc -> {t, acc} | {:halt, acc}),\n acc: any\n def flat_map_reduce(enumerable, acc, fun) do\n {_, {list, acc}} =\n Enumerable.reduce(enumerable, {:cont, {[], acc}}, fn entry, {list, acc} ->\n case fun.(entry, acc) do\n {:halt, acc} ->\n {:halt, {list, acc}}\n\n {[], acc} ->\n {:cont, {list, acc}}\n\n {[entry], acc} ->\n {:cont, {[entry | list], acc}}\n\n {entries, acc} ->\n {:cont, {reduce(entries, list, &[&1 | &2]), acc}}\n end\n end)\n\n {:lists.reverse(list), acc}\n end\n\n @doc \"\"\"\n Splits the enumerable into groups based on `key_fun`.\n\n The result is a map where each key is given by `key_fun`\n and each value is a list of elements given by `value_fun`.\n The order of elements within each list is preserved from the enumerable.\n However, like all maps, the resulting map is unordered.\n\n ## Examples\n\n iex> Enum.group_by(~w{ant buffalo cat dingo}, &String.length\/1)\n %{3 => [\"ant\", \"cat\"], 5 => [\"dingo\"], 7 => [\"buffalo\"]}\n\n iex> Enum.group_by(~w{ant buffalo cat dingo}, &String.length\/1, &String.first\/1)\n %{3 => [\"a\", \"c\"], 5 => [\"d\"], 7 => [\"b\"]}\n\n \"\"\"\n @spec group_by(t, (element -> any), (element -> any)) :: map\n def group_by(enumerable, key_fun, value_fun \\\\ fn x -> x end)\n\n def group_by(enumerable, key_fun, value_fun) when is_function(key_fun) do\n reduce(reverse(enumerable), %{}, fn entry, categories ->\n value = value_fun.(entry)\n Map.update(categories, key_fun.(entry), [value], &[value | &1])\n end)\n end\n\n # TODO: Remove on 2.0\n def group_by(enumerable, dict, fun) do\n IO.warn(\n \"Enum.group_by\/3 with a map\/dictionary as second element is deprecated. \" <>\n \"A map is used by default and it is no longer required to pass one to this function\"\n )\n\n # Avoid warnings about Dict\n dict_module = Dict\n\n reduce(reverse(enumerable), dict, fn entry, categories ->\n dict_module.update(categories, fun.(entry), [entry], &[entry | &1])\n end)\n end\n\n @doc \"\"\"\n Intersperses `element` between each element of the enumeration.\n\n Complexity: O(n).\n\n ## Examples\n\n iex> Enum.intersperse([1, 2, 3], 0)\n [1, 0, 2, 0, 3]\n\n iex> Enum.intersperse([1], 0)\n [1]\n\n iex> Enum.intersperse([], 0)\n []\n\n \"\"\"\n @spec intersperse(t, element) :: list\n def intersperse(enumerable, element) do\n list =\n reduce(enumerable, [], fn x, acc ->\n [x, element | acc]\n end)\n |> :lists.reverse()\n\n case list do\n [] ->\n []\n\n # Head is a superfluous intersperser element\n [_ | t] ->\n t\n end\n end\n\n @doc \"\"\"\n Inserts the given `enumerable` into a `collectable`.\n\n ## Examples\n\n iex> Enum.into([1, 2], [0])\n [0, 1, 2]\n\n iex> Enum.into([a: 1, b: 2], %{})\n %{a: 1, b: 2}\n\n iex> Enum.into(%{a: 1}, %{b: 2})\n %{a: 1, b: 2}\n\n iex> Enum.into([a: 1, a: 2], %{})\n %{a: 2}\n\n \"\"\"\n @spec into(Enumerable.t(), Collectable.t()) :: Collectable.t()\n def into(enumerable, collectable) when is_list(collectable) do\n collectable ++ to_list(enumerable)\n end\n\n def into(%_{} = enumerable, collectable) do\n into_protocol(enumerable, collectable)\n end\n\n def into(enumerable, %_{} = collectable) do\n into_protocol(enumerable, collectable)\n end\n\n def into(%{} = enumerable, %{} = collectable) do\n Map.merge(collectable, enumerable)\n end\n\n def into(enumerable, %{} = collectable) when is_list(enumerable) do\n Map.merge(collectable, :maps.from_list(enumerable))\n end\n\n def into(enumerable, %{} = collectable) do\n reduce(enumerable, collectable, fn {key, val}, acc ->\n Map.put(acc, key, val)\n end)\n end\n\n def into(enumerable, collectable) do\n into_protocol(enumerable, collectable)\n end\n\n defp into_protocol(enumerable, collectable) do\n {initial, fun} = Collectable.into(collectable)\n\n into(enumerable, initial, fun, fn entry, acc ->\n fun.(acc, {:cont, entry})\n end)\n end\n\n @doc \"\"\"\n Inserts the given `enumerable` into a `collectable` according to the\n transformation function.\n\n ## Examples\n\n iex> Enum.into([2, 3], [3], fn x -> x * 3 end)\n [3, 6, 9]\n\n iex> Enum.into(%{a: 1, b: 2}, %{c: 3}, fn {k, v} -> {k, v * 2} end)\n %{a: 2, b: 4, c: 3}\n\n \"\"\"\n @spec into(Enumerable.t(), Collectable.t(), (term -> term)) :: Collectable.t()\n\n def into(enumerable, collectable, transform) when is_list(collectable) do\n collectable ++ map(enumerable, transform)\n end\n\n def into(enumerable, collectable, transform) do\n {initial, fun} = Collectable.into(collectable)\n\n into(enumerable, initial, fun, fn entry, acc ->\n fun.(acc, {:cont, transform.(entry)})\n end)\n end\n\n defp into(enumerable, initial, fun, callback) do\n try do\n reduce(enumerable, initial, callback)\n catch\n kind, reason ->\n stacktrace = System.stacktrace()\n fun.(initial, :halt)\n :erlang.raise(kind, reason, stacktrace)\n else\n acc -> fun.(acc, :done)\n end\n end\n\n @doc \"\"\"\n Joins the given enumerable into a binary using `joiner` as a\n separator.\n\n If `joiner` is not passed at all, it defaults to the empty binary.\n\n All items in the enumerable must be convertible to a binary,\n otherwise an error is raised.\n\n ## Examples\n\n iex> Enum.join([1, 2, 3])\n \"123\"\n\n iex> Enum.join([1, 2, 3], \" = \")\n \"1 = 2 = 3\"\n\n \"\"\"\n @spec join(t, String.t()) :: String.t()\n def join(enumerable, joiner \\\\ \"\")\n\n def join(enumerable, joiner) when is_binary(joiner) do\n reduced =\n reduce(enumerable, :first, fn\n entry, :first -> entry_to_string(entry)\n entry, acc -> [acc, joiner | entry_to_string(entry)]\n end)\n\n if reduced == :first do\n \"\"\n else\n IO.iodata_to_binary(reduced)\n end\n end\n\n @doc \"\"\"\n Returns a list where each item is the result of invoking\n `fun` on each corresponding item of `enumerable`.\n\n For maps, the function expects a key-value tuple.\n\n ## Examples\n\n iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end)\n [2, 4, 6]\n\n iex> Enum.map([a: 1, b: 2], fn({k, v}) -> {k, -v} end)\n [a: -1, b: -2]\n\n \"\"\"\n @spec map(t, (element -> any)) :: list\n def map(enumerable, fun)\n\n def map(enumerable, fun) when is_list(enumerable) do\n :lists.map(fun, enumerable)\n end\n\n def map(enumerable, fun) do\n reduce(enumerable, [], R.map(fun)) |> :lists.reverse()\n end\n\n @doc \"\"\"\n Returns a list of results of invoking `fun` on every `nth`\n item of `enumerable`, starting with the first element.\n\n The first item is always passed to the given function, unless `nth` is `0`.\n\n The second argument specifying every `nth` item must be a non-negative\n integer.\n\n If `nth` is `0`, then `enumerable` is directly converted to a list,\n without `fun` being ever applied.\n\n ## Examples\n\n iex> Enum.map_every(1..10, 2, fn x -> x + 1000 end)\n [1001, 2, 1003, 4, 1005, 6, 1007, 8, 1009, 10]\n\n iex> Enum.map_every(1..10, 3, fn x -> x + 1000 end)\n [1001, 2, 3, 1004, 5, 6, 1007, 8, 9, 1010]\n\n iex> Enum.map_every(1..5, 0, fn x -> x + 1000 end)\n [1, 2, 3, 4, 5]\n\n iex> Enum.map_every([1, 2, 3], 1, fn x -> x + 1000 end)\n [1001, 1002, 1003]\n\n \"\"\"\n @spec map_every(t, non_neg_integer, (element -> any)) :: list\n def map_every(enumerable, nth, fun)\n\n def map_every(enumerable, 1, fun), do: map(enumerable, fun)\n def map_every(enumerable, 0, _fun), do: to_list(enumerable)\n def map_every([], nth, _fun) when is_integer(nth) and nth > 1, do: []\n\n def map_every(enumerable, nth, fun) when is_integer(nth) and nth > 1 do\n {res, _} = reduce(enumerable, {[], :first}, R.map_every(nth, fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Maps and joins the given enumerable in one pass.\n\n `joiner` can be either a binary or a list and the result will be of\n the same type as `joiner`.\n If `joiner` is not passed at all, it defaults to an empty binary.\n\n All items returned from invoking the `mapper` must be convertible to\n a binary, otherwise an error is raised.\n\n ## Examples\n\n iex> Enum.map_join([1, 2, 3], &(&1 * 2))\n \"246\"\n\n iex> Enum.map_join([1, 2, 3], \" = \", &(&1 * 2))\n \"2 = 4 = 6\"\n\n \"\"\"\n @spec map_join(t, String.t(), (element -> String.Chars.t())) :: String.t()\n def map_join(enumerable, joiner \\\\ \"\", mapper)\n\n def map_join(enumerable, joiner, mapper) when is_binary(joiner) do\n reduced =\n reduce(enumerable, :first, fn\n entry, :first -> entry_to_string(mapper.(entry))\n entry, acc -> [acc, joiner | entry_to_string(mapper.(entry))]\n end)\n\n if reduced == :first do\n \"\"\n else\n IO.iodata_to_binary(reduced)\n end\n end\n\n @doc \"\"\"\n Invokes the given function to each item in the enumerable to reduce\n it to a single element, while keeping an accumulator.\n\n Returns a tuple where the first element is the mapped enumerable and\n the second one is the final accumulator.\n\n The function, `fun`, receives two arguments: the first one is the\n element, and the second one is the accumulator. `fun` must return\n a tuple with two elements in the form of `{result, accumulator}`.\n\n For maps, the first tuple element must be a `{key, value}` tuple.\n\n ## Examples\n\n iex> Enum.map_reduce([1, 2, 3], 0, fn(x, acc) -> {x * 2, x + acc} end)\n {[2, 4, 6], 6}\n\n \"\"\"\n @spec map_reduce(t, any, (element, any -> {any, any})) :: {any, any}\n def map_reduce(enumerable, acc, fun) when is_list(enumerable) do\n :lists.mapfoldl(fun, acc, enumerable)\n end\n\n def map_reduce(enumerable, acc, fun) do\n {list, acc} =\n reduce(enumerable, {[], acc}, fn entry, {list, acc} ->\n {new_entry, acc} = fun.(entry, acc)\n {[new_entry | list], acc}\n end)\n\n {:lists.reverse(list), acc}\n end\n\n @doc \"\"\"\n Returns the maximal element in the enumerable according\n to Erlang's term ordering.\n\n If multiple elements are considered maximal, the first one that was found\n is returned.\n\n Calls the provided `empty_fallback` function and returns its value if\n `enumerable` is empty. The default `empty_fallback` raises `Enum.EmptyError`.\n\n ## Examples\n\n iex> Enum.max([1, 2, 3])\n 3\n\n iex> Enum.max([], fn -> 0 end)\n 0\n\n The fact this function uses Erlang's term ordering means that the comparison\n is structural and not semantic. For example:\n\n iex> Enum.max([~D[2017-03-31], ~D[2017-04-01]])\n ~D[2017-03-31]\n\n In the example above, `max\/1` returned March 31st instead of April 1st\n because the structural comparison compares the day before the year. This\n can be addressed by using `max_by\/1` and by relying on structures where\n the most significant digits come first. In this particular case, we can\n use `Date.to_erl\/1` to get a tuple representation with year, month and day\n fields:\n\n iex> Enum.max_by([~D[2017-03-31], ~D[2017-04-01]], &Date.to_erl\/1)\n ~D[2017-04-01]\n\n \"\"\"\n @spec max(t, (() -> empty_result)) :: element | empty_result | no_return when empty_result: any\n def max(enumerable, empty_fallback \\\\ fn -> raise Enum.EmptyError end) do\n aggregate(enumerable, &Kernel.max\/2, empty_fallback)\n end\n\n @doc \"\"\"\n Returns the maximal element in the enumerable as calculated\n by the given function.\n\n If multiple elements are considered maximal, the first one that was found\n is returned.\n\n Calls the provided `empty_fallback` function and returns its value if\n `enumerable` is empty. The default `empty_fallback` raises `Enum.EmptyError`.\n\n ## Examples\n\n iex> Enum.max_by([\"a\", \"aa\", \"aaa\"], fn(x) -> String.length(x) end)\n \"aaa\"\n\n iex> Enum.max_by([\"a\", \"aa\", \"aaa\", \"b\", \"bbb\"], &String.length\/1)\n \"aaa\"\n\n iex> Enum.max_by([], &String.length\/1, fn -> nil end)\n nil\n\n \"\"\"\n @spec max_by(t, (element -> any), (() -> empty_result)) :: element | empty_result | no_return\n when empty_result: any\n def max_by(enumerable, fun, empty_fallback \\\\ fn -> raise Enum.EmptyError end) do\n first_fun = &{&1, fun.(&1)}\n\n reduce_fun = fn entry, {_, fun_max} = old ->\n fun_entry = fun.(entry)\n if(fun_entry > fun_max, do: {entry, fun_entry}, else: old)\n end\n\n case reduce_by(enumerable, first_fun, reduce_fun) do\n :empty -> empty_fallback.()\n {entry, _} -> entry\n end\n end\n\n @doc \"\"\"\n Checks if `element` exists within the enumerable.\n\n Membership is tested with the match (`===`) operator.\n\n ## Examples\n\n iex> Enum.member?(1..10, 5)\n true\n iex> Enum.member?(1..10, 5.0)\n false\n\n iex> Enum.member?([1.0, 2.0, 3.0], 2)\n false\n iex> Enum.member?([1.0, 2.0, 3.0], 2.000)\n true\n\n iex> Enum.member?([:a, :b, :c], :d)\n false\n\n \"\"\"\n @spec member?(t, element) :: boolean\n def member?(enumerable, element) when is_list(enumerable) do\n :lists.member(element, enumerable)\n end\n\n def member?(enumerable, element) do\n case Enumerable.member?(enumerable, element) do\n {:ok, element} when is_boolean(element) ->\n element\n\n {:error, module} ->\n module.reduce(enumerable, {:cont, false}, fn\n v, _ when v === element -> {:halt, true}\n _, _ -> {:cont, false}\n end)\n |> elem(1)\n end\n end\n\n @doc \"\"\"\n Returns the minimal element in the enumerable according\n to Erlang's term ordering.\n\n If multiple elements are considered minimal, the first one that was found\n is returned.\n\n Calls the provided `empty_fallback` function and returns its value if\n `enumerable` is empty. The default `empty_fallback` raises `Enum.EmptyError`.\n\n ## Examples\n\n iex> Enum.min([1, 2, 3])\n 1\n\n iex> Enum.min([], fn -> 0 end)\n 0\n\n The fact this function uses Erlang's term ordering means that the comparison\n is structural and not semantic. For example:\n\n iex> Enum.min([~D[2017-03-31], ~D[2017-04-01]])\n ~D[2017-04-01]\n\n In the example above, `min\/1` returned April 1st instead of March 31st\n because the structural comparison compares the day before the year. This\n can be addressed by using `min_by\/1` and by relying on structures where\n the most significant digits come first. In this particular case, we can\n use `Date.to_erl\/1` to get a tuple representation with year, month and day\n fields:\n\n iex> Enum.min_by([~D[2017-03-31], ~D[2017-04-01]], &Date.to_erl\/1)\n ~D[2017-03-31]\n\n \"\"\"\n @spec min(t, (() -> empty_result)) :: element | empty_result | no_return when empty_result: any\n def min(enumerable, empty_fallback \\\\ fn -> raise Enum.EmptyError end) do\n aggregate(enumerable, &Kernel.min\/2, empty_fallback)\n end\n\n @doc \"\"\"\n Returns the minimal element in the enumerable as calculated\n by the given function.\n\n If multiple elements are considered minimal, the first one that was found\n is returned.\n\n Calls the provided `empty_fallback` function and returns its value if\n `enumerable` is empty. The default `empty_fallback` raises `Enum.EmptyError`.\n\n ## Examples\n\n iex> Enum.min_by([\"a\", \"aa\", \"aaa\"], fn(x) -> String.length(x) end)\n \"a\"\n\n iex> Enum.min_by([\"a\", \"aa\", \"aaa\", \"b\", \"bbb\"], &String.length\/1)\n \"a\"\n\n iex> Enum.min_by([], &String.length\/1, fn -> nil end)\n nil\n\n \"\"\"\n @spec min_by(t, (element -> any), (() -> empty_result)) :: element | empty_result | no_return\n when empty_result: any\n def min_by(enumerable, fun, empty_fallback \\\\ fn -> raise Enum.EmptyError end) do\n first_fun = &{&1, fun.(&1)}\n\n reduce_fun = fn entry, {_, fun_min} = old ->\n fun_entry = fun.(entry)\n if(fun_entry < fun_min, do: {entry, fun_entry}, else: old)\n end\n\n case reduce_by(enumerable, first_fun, reduce_fun) do\n :empty -> empty_fallback.()\n {entry, _} -> entry\n end\n end\n\n @doc \"\"\"\n Returns a tuple with the minimal and the maximal elements in the\n enumerable according to Erlang's term ordering.\n\n If multiple elements are considered maximal or minimal, the first one\n that was found is returned.\n\n Calls the provided `empty_fallback` function and returns its value if\n `enumerable` is empty. The default `empty_fallback` raises `Enum.EmptyError`.\n\n ## Examples\n\n iex> Enum.min_max([2, 3, 1])\n {1, 3}\n\n iex> Enum.min_max([], fn -> {nil, nil} end)\n {nil, nil}\n\n \"\"\"\n @spec min_max(t, (() -> empty_result)) :: {element, element} | empty_result | no_return\n when empty_result: any\n def min_max(enumerable, empty_fallback \\\\ fn -> raise Enum.EmptyError end)\n\n def min_max(left..right, _empty_fallback) do\n {Kernel.min(left, right), Kernel.max(left, right)}\n end\n\n def min_max(enumerable, empty_fallback) do\n first_fun = &{&1, &1}\n\n reduce_fun = fn entry, {min, max} ->\n {Kernel.min(entry, min), Kernel.max(entry, max)}\n end\n\n case reduce_by(enumerable, first_fun, reduce_fun) do\n :empty -> empty_fallback.()\n entry -> entry\n end\n end\n\n @doc \"\"\"\n Returns a tuple with the minimal and the maximal elements in the\n enumerable as calculated by the given function.\n\n If multiple elements are considered maximal or minimal, the first one\n that was found is returned.\n\n Calls the provided `empty_fallback` function and returns its value if\n `enumerable` is empty. The default `empty_fallback` raises `Enum.EmptyError`.\n\n ## Examples\n\n iex> Enum.min_max_by([\"aaa\", \"bb\", \"c\"], fn(x) -> String.length(x) end)\n {\"c\", \"aaa\"}\n\n iex> Enum.min_max_by([\"aaa\", \"a\", \"bb\", \"c\", \"ccc\"], &String.length\/1)\n {\"a\", \"aaa\"}\n\n iex> Enum.min_max_by([], &String.length\/1, fn -> {nil, nil} end)\n {nil, nil}\n\n \"\"\"\n @spec min_max_by(t, (element -> any), (() -> empty_result)) ::\n {element, element} | empty_result | no_return\n when empty_result: any\n def min_max_by(enumerable, fun, empty_fallback \\\\ fn -> raise Enum.EmptyError end)\n\n def min_max_by(enumerable, fun, empty_fallback) do\n first_fun = fn entry ->\n fun_entry = fun.(entry)\n {{entry, entry}, {fun_entry, fun_entry}}\n end\n\n reduce_fun = fn entry, {{prev_min, prev_max}, {fun_min, fun_max}} = acc ->\n fun_entry = fun.(entry)\n\n cond do\n fun_entry < fun_min ->\n {{entry, prev_max}, {fun_entry, fun_max}}\n\n fun_entry > fun_max ->\n {{prev_min, entry}, {fun_min, fun_entry}}\n\n true ->\n acc\n end\n end\n\n case reduce_by(enumerable, first_fun, reduce_fun) do\n :empty -> empty_fallback.()\n {entry, _} -> entry\n end\n end\n\n @doc \"\"\"\n Splits the `enumerable` in two lists according to the given function `fun`.\n\n Splits the given `enumerable` in two lists by calling `fun` with each element\n in the `enumerable` as its only argument. Returns a tuple with the first list\n containing all the elements in `enumerable` for which applying `fun` returned\n a truthy value, and a second list with all the elements for which applying\n `fun` returned a falsy value (`false` or `nil`).\n\n The elements in both the returned lists are in the same relative order as they\n were in the original enumerable (if such enumerable was ordered, e.g., a\n list); see the examples below.\n\n ## Examples\n\n iex> Enum.split_with([5, 4, 3, 2, 1, 0], fn(x) -> rem(x, 2) == 0 end)\n {[4, 2, 0], [5, 3, 1]}\n\n iex> Enum.split_with(%{a: 1, b: -2, c: 1, d: -3}, fn({_k, v}) -> v < 0 end)\n {[b: -2, d: -3], [a: 1, c: 1]}\n\n iex> Enum.split_with(%{a: 1, b: -2, c: 1, d: -3}, fn({_k, v}) -> v > 50 end)\n {[], [a: 1, b: -2, c: 1, d: -3]}\n\n iex> Enum.split_with(%{}, fn({_k, v}) -> v > 50 end)\n {[], []}\n\n \"\"\"\n @spec split_with(t, (element -> any)) :: {list, list}\n def split_with(enumerable, fun) do\n {acc1, acc2} =\n reduce(enumerable, {[], []}, fn entry, {acc1, acc2} ->\n if fun.(entry) do\n {[entry | acc1], acc2}\n else\n {acc1, [entry | acc2]}\n end\n end)\n\n {:lists.reverse(acc1), :lists.reverse(acc2)}\n end\n\n @doc false\n # TODO: Remove on 2.0\n # (hard-deprecated in elixir_dispatch)\n def partition(enumerable, fun) do\n split_with(enumerable, fun)\n end\n\n @doc \"\"\"\n Returns a random element of an enumerable.\n\n Raises `Enum.EmptyError` if `enumerable` is empty.\n\n This function uses Erlang's [`:rand` module](http:\/\/www.erlang.org\/doc\/man\/rand.html) to calculate\n the random value. Check its documentation for setting a\n different random algorithm or a different seed.\n\n The implementation is based on the\n [reservoir sampling](https:\/\/en.wikipedia.org\/wiki\/Reservoir_sampling#Relation_to_Fisher-Yates_shuffle)\n algorithm.\n It assumes that the sample being returned can fit into memory;\n the input `enumerable` doesn't have to, as it is traversed just once.\n\n If a range is passed into the function, this function will pick a\n random value between the range limits, without traversing the whole\n range (thus executing in constant time and constant memory).\n\n ## Examples\n\n # Although not necessary, let's seed the random algorithm\n iex> :rand.seed(:exsplus, {101, 102, 103})\n iex> Enum.random([1, 2, 3])\n 2\n iex> Enum.random([1, 2, 3])\n 1\n iex> Enum.random(1..1_000)\n 776\n\n \"\"\"\n @spec random(t) :: element | no_return\n def random(enumerable)\n\n def random(enumerable) when is_list(enumerable) do\n case take_random(enumerable, 1) do\n [] -> raise Enum.EmptyError\n [elem] -> elem\n end\n end\n\n def random(enumerable) do\n result =\n case Enumerable.slice(enumerable) do\n {:ok, 0, _} ->\n []\n\n {:ok, count, fun} when is_function(fun) ->\n fun.(random_integer(0, count - 1), 1)\n\n {:error, _} ->\n take_random(enumerable, 1)\n end\n\n case result do\n [] -> raise Enum.EmptyError\n [elem] -> elem\n end\n end\n\n @doc \"\"\"\n Invokes `fun` for each element in the `enumerable` with the\n accumulator.\n\n Raises `Enum.EmptyError` if `enumerable` is empty.\n\n The first element of the enumerable is used as the initial value\n of the accumulator. Then the function is invoked with the next\n element and the accumulator. The result returned by the function\n is used as the accumulator for the next iteration, recursively.\n When the enumerable is done, the last accumulator is returned.\n\n Since the first element of the enumerable is used as the initial\n value of the accumulator, `fun` will only be executed `n - 1` times\n where `n` is the length of the enumerable. This function won't call\n the specified function for enumerables that are one-element long.\n\n If you wish to use another value for the accumulator, use\n `Enum.reduce\/3`.\n\n ## Examples\n\n iex> Enum.reduce([1, 2, 3, 4], fn(x, acc) -> x * acc end)\n 24\n\n \"\"\"\n @spec reduce(t, (element, any -> any)) :: any\n def reduce(enumerable, fun)\n\n def reduce([h | t], fun) do\n reduce(t, h, fun)\n end\n\n def reduce([], _fun) do\n raise Enum.EmptyError\n end\n\n def reduce(enumerable, fun) do\n result =\n Enumerable.reduce(enumerable, {:cont, :first}, fn\n x, :first ->\n {:cont, {:acc, x}}\n\n x, {:acc, acc} ->\n {:cont, {:acc, fun.(x, acc)}}\n end)\n |> elem(1)\n\n case result do\n :first -> raise Enum.EmptyError\n {:acc, acc} -> acc\n end\n end\n\n @doc \"\"\"\n Invokes `fun` for each element in the `enumerable` with the accumulator.\n\n The initial value of the accumulator is `acc`. The function is invoked for\n each element in the enumerable with the accumulator. The result returned\n by the function is used as the accumulator for the next iteration.\n The function returns the last accumulator.\n\n ## Examples\n\n iex> Enum.reduce([1, 2, 3], 0, fn(x, acc) -> x + acc end)\n 6\n\n ## Reduce as a building block\n\n Reduce (sometimes called `fold`) is a basic building block in functional\n programming. Almost all of the functions in the `Enum` module can be\n implemented on top of reduce. Those functions often rely on other operations,\n such as `Enum.reverse\/1`, which are optimized by the runtime.\n\n For example, we could implement `map\/2` in terms of `reduce\/3` as follows:\n\n def my_map(enumerable, fun) do\n enumerable\n |> Enum.reduce([], fn(x, acc) -> [fun.(x) | acc] end)\n |> Enum.reverse\n end\n\n In the example above, `Enum.reduce\/3` accumulates the result of each call\n to `fun` into a list in reverse order, which is correctly ordered at the\n end by calling `Enum.reverse\/1`.\n\n Implementing functions like `map\/2`, `filter\/2` and others are a good\n exercise for understanding the power behind `Enum.reduce\/3`. When an\n operation cannot be expressed by any of the functions in the `Enum`\n module, developers will most likely resort to `reduce\/3`.\n \"\"\"\n @spec reduce(t, any, (element, any -> any)) :: any\n def reduce(enumerable, acc, fun) when is_list(enumerable) do\n :lists.foldl(fun, acc, enumerable)\n end\n\n def reduce(first..last, acc, fun) do\n if first <= last do\n reduce_range_inc(first, last, acc, fun)\n else\n reduce_range_dec(first, last, acc, fun)\n end\n end\n\n def reduce(%_{} = enumerable, acc, fun) do\n Enumerable.reduce(enumerable, {:cont, acc}, fn x, acc -> {:cont, fun.(x, acc)} end) |> elem(1)\n end\n\n def reduce(%{} = enumerable, acc, fun) do\n :maps.fold(fn k, v, acc -> fun.({k, v}, acc) end, acc, enumerable)\n end\n\n def reduce(enumerable, acc, fun) do\n Enumerable.reduce(enumerable, {:cont, acc}, fn x, acc -> {:cont, fun.(x, acc)} end) |> elem(1)\n end\n\n @doc \"\"\"\n Reduces the enumerable until `fun` returns `{:halt, term}`.\n\n The return value for `fun` is expected to be\n\n * `{:cont, acc}` to continue the reduction with `acc` as the new\n accumulator or\n * `{:halt, acc}` to halt the reduction and return `acc` as the return\n value of this function\n\n ## Examples\n\n iex> Enum.reduce_while(1..100, 0, fn i, acc ->\n ...> if i < 3, do: {:cont, acc + i}, else: {:halt, acc}\n ...> end)\n 3\n\n \"\"\"\n @spec reduce_while(t, any, (element, any -> {:cont, any} | {:halt, any})) :: any\n def reduce_while(enumerable, acc, fun) do\n Enumerable.reduce(enumerable, {:cont, acc}, fun) |> elem(1)\n end\n\n @doc \"\"\"\n Returns elements of `enumerable` for which the function `fun` returns\n `false` or `nil`.\n\n See also `filter\/2`.\n\n ## Examples\n\n iex> Enum.reject([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)\n [1, 3]\n\n \"\"\"\n @spec reject(t, (element -> as_boolean(term))) :: list\n def reject(enumerable, fun) when is_list(enumerable) do\n reject_list(enumerable, fun)\n end\n\n def reject(enumerable, fun) do\n reduce(enumerable, [], R.reject(fun)) |> :lists.reverse()\n end\n\n @doc \"\"\"\n Returns a list of elements in `enumerable` in reverse order.\n\n ## Examples\n\n iex> Enum.reverse([1, 2, 3])\n [3, 2, 1]\n\n \"\"\"\n @spec reverse(t) :: list\n def reverse(enumerable)\n\n def reverse([]), do: []\n def reverse([_] = list), do: list\n def reverse([item1, item2]), do: [item2, item1]\n def reverse([item1, item2 | rest]), do: :lists.reverse(rest, [item2, item1])\n def reverse(enumerable), do: reduce(enumerable, [], &[&1 | &2])\n\n @doc \"\"\"\n Reverses the elements in `enumerable`, appends the tail, and returns\n it as a list.\n\n This is an optimization for\n `Enum.concat(Enum.reverse(enumerable), tail)`.\n\n ## Examples\n\n iex> Enum.reverse([1, 2, 3], [4, 5, 6])\n [3, 2, 1, 4, 5, 6]\n\n \"\"\"\n @spec reverse(t, t) :: list\n def reverse(enumerable, tail) when is_list(enumerable) do\n :lists.reverse(enumerable, to_list(tail))\n end\n\n def reverse(enumerable, tail) do\n reduce(enumerable, to_list(tail), fn entry, acc ->\n [entry | acc]\n end)\n end\n\n @doc \"\"\"\n Reverses the enumerable in the range from initial position `start`\n through `count` elements.\n\n If `count` is greater than the size of the rest of the enumerable,\n then this function will reverse the rest of the enumerable.\n\n ## Examples\n\n iex> Enum.reverse_slice([1, 2, 3, 4, 5, 6], 2, 4)\n [1, 2, 6, 5, 4, 3]\n\n \"\"\"\n @spec reverse_slice(t, non_neg_integer, non_neg_integer) :: list\n def reverse_slice(enumerable, start, count)\n when is_integer(start) and start >= 0 and is_integer(count) and count >= 0 do\n list = reverse(enumerable)\n length = length(list)\n count = Kernel.min(count, length - start)\n\n if count > 0 do\n reverse_slice(list, length, start + count, count, [])\n else\n :lists.reverse(list)\n end\n end\n\n @doc \"\"\"\n Applies the given function to each element in the enumerable,\n storing the result in a list and passing it as the accumulator\n for the next computation. Uses the first element in the enumerable\n as the starting value.\n\n ## Examples\n\n iex> Enum.scan(1..5, &(&1 + &2))\n [1, 3, 6, 10, 15]\n\n \"\"\"\n @spec scan(t, (element, any -> any)) :: list\n def scan(enumerable, fun) do\n {res, _} = reduce(enumerable, {[], :first}, R.scan2(fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Applies the given function to each element in the enumerable,\n storing the result in a list and passing it as the accumulator\n for the next computation. Uses the given `acc` as the starting value.\n\n ## Examples\n\n iex> Enum.scan(1..5, 0, &(&1 + &2))\n [1, 3, 6, 10, 15]\n\n \"\"\"\n @spec scan(t, any, (element, any -> any)) :: list\n def scan(enumerable, acc, fun) do\n {res, _} = reduce(enumerable, {[], acc}, R.scan3(fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Returns a list with the elements of `enumerable` shuffled.\n\n This function uses Erlang's [`:rand` module](http:\/\/www.erlang.org\/doc\/man\/rand.html) to calculate\n the random value. Check its documentation for setting a\n different random algorithm or a different seed.\n\n ## Examples\n\n # Although not necessary, let's seed the random algorithm\n iex> :rand.seed(:exsplus, {1, 2, 3})\n iex> Enum.shuffle([1, 2, 3])\n [2, 1, 3]\n iex> Enum.shuffle([1, 2, 3])\n [2, 3, 1]\n\n \"\"\"\n @spec shuffle(t) :: list\n def shuffle(enumerable) do\n randomized =\n reduce(enumerable, [], fn x, acc ->\n [{:rand.uniform(), x} | acc]\n end)\n\n shuffle_unwrap(:lists.keysort(1, randomized), [])\n end\n\n @doc \"\"\"\n Returns a subset list of the given enumerable, from `range.first` to `range.last` positions.\n\n Given `enumerable`, it drops elements until element position `range.first`,\n then takes elements until element position `range.last` (inclusive).\n\n Positions are normalized, meaning that negative positions will be counted from the end\n (e.g. `-1` means the last element of the enumerable).\n If `range.last` is out of bounds, then it is assigned as the position of the last element.\n\n If the normalized `range.first` position is out of bounds of the given enumerable,\n or this one is greater than the normalized `range.last` position, then `[]` is returned.\n\n ## Examples\n\n iex> Enum.slice(1..100, 5..10)\n [6, 7, 8, 9, 10, 11]\n\n iex> Enum.slice(1..10, 5..20)\n [6, 7, 8, 9, 10]\n\n # last five elements (negative positions)\n iex> Enum.slice(1..30, -5..-1)\n [26, 27, 28, 29, 30]\n\n # last five elements (mixed positive and negative positions)\n iex> Enum.slice(1..30, 25..-1)\n [26, 27, 28, 29, 30]\n\n # out of bounds\n iex> Enum.slice(1..10, 11..20)\n []\n\n # range.first is greater than range.last\n iex> Enum.slice(1..10, 6..5)\n []\n\n \"\"\"\n @spec slice(t, Range.t()) :: list\n def slice(enumerable, first..last) do\n {count, fun} = slice_count_and_fun(enumerable)\n corr_first = if first >= 0, do: first, else: first + count\n corr_last = if last >= 0, do: last, else: last + count\n amount = corr_last - corr_first + 1\n\n if corr_first >= 0 and corr_first < count and amount > 0 do\n fun.(corr_first, Kernel.min(amount, count - corr_first))\n else\n []\n end\n end\n\n @doc \"\"\"\n Returns a subset list of the given enumerable, from `start` position with `amount` of elements if available.\n\n Given `enumerable`, it drops elements until element position `start`,\n then takes `amount` of elements until the end of the enumerable.\n\n If `start` is out of bounds, it returns `[]`.\n\n If `amount` is greater than `enumerable` length, it returns as many elements as possible.\n If `amount` is zero, then `[]` is returned.\n\n ## Examples\n\n iex> Enum.slice(1..100, 5, 10)\n [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n\n # amount to take is greater than the number of elements\n iex> Enum.slice(1..10, 5, 100)\n [6, 7, 8, 9, 10]\n\n iex> Enum.slice(1..10, 5, 0)\n []\n\n # out of bound start position\n iex> Enum.slice(1..10, 10, 5)\n []\n\n # out of bound start position (negative)\n iex> Enum.slice(1..10, -11, 5)\n []\n\n \"\"\"\n @spec slice(t, index, non_neg_integer) :: list\n def slice(_enumerable, start, 0) when is_integer(start), do: []\n\n def slice(enumerable, start, amount)\n when is_integer(start) and is_integer(amount) and amount >= 0 do\n slice_any(enumerable, start, amount)\n end\n\n @doc \"\"\"\n Sorts the enumerable according to Erlang's term ordering.\n\n Uses the merge sort algorithm.\n\n ## Examples\n\n iex> Enum.sort([3, 2, 1])\n [1, 2, 3]\n\n \"\"\"\n @spec sort(t) :: list\n def sort(enumerable) when is_list(enumerable) do\n :lists.sort(enumerable)\n end\n\n def sort(enumerable) do\n sort(enumerable, &(&1 <= &2))\n end\n\n @doc \"\"\"\n Sorts the enumerable by the given function.\n\n This function uses the merge sort algorithm. The given function should compare\n two arguments, and return `true` if the first argument precedes the second one.\n\n ## Examples\n\n iex> Enum.sort([1, 2, 3], &(&1 >= &2))\n [3, 2, 1]\n\n The sorting algorithm will be stable as long as the given function\n returns `true` for values considered equal:\n\n iex> Enum.sort [\"some\", \"kind\", \"of\", \"monster\"], &(byte_size(&1) <= byte_size(&2))\n [\"of\", \"some\", \"kind\", \"monster\"]\n\n If the function does not return `true` for equal values, the sorting\n is not stable and the order of equal terms may be shuffled.\n For example:\n\n iex> Enum.sort [\"some\", \"kind\", \"of\", \"monster\"], &(byte_size(&1) < byte_size(&2))\n [\"of\", \"kind\", \"some\", \"monster\"]\n\n \"\"\"\n @spec sort(t, (element, element -> boolean)) :: list\n def sort(enumerable, fun) when is_list(enumerable) do\n :lists.sort(fun, enumerable)\n end\n\n def sort(enumerable, fun) do\n reduce(enumerable, [], &sort_reducer(&1, &2, fun))\n |> sort_terminator(fun)\n end\n\n @doc \"\"\"\n Sorts the mapped results of the enumerable according to the provided `sorter`\n function.\n\n This function maps each element of the enumerable using the provided `mapper`\n function. The enumerable is then sorted by the mapped elements\n using the `sorter` function, which defaults to `Kernel.<=\/2`.\n\n `sort_by\/3` differs from `sort\/2` in that it only calculates the\n comparison value for each element in the enumerable once instead of\n once for each element in each comparison.\n If the same function is being called on both elements, it's also more\n compact to use `sort_by\/3`.\n\n ## Examples\n\n Using the default `sorter` of `<=\/2`:\n\n iex> Enum.sort_by([\"some\", \"kind\", \"of\", \"monster\"], &byte_size\/1)\n [\"of\", \"some\", \"kind\", \"monster\"]\n\n Using a custom `sorter` to override the order:\n\n iex> Enum.sort_by([\"some\", \"kind\", \"of\", \"monster\"], &byte_size\/1, &>=\/2)\n [\"monster\", \"some\", \"kind\", \"of\"]\n\n Sorting by multiple properties - first by size, then by first letter\n (this takes advantage of the fact that tuples are compared element-by-element):\n\n iex> Enum.sort_by([\"some\", \"kind\", \"of\", \"monster\"], &{byte_size(&1), String.first(&1)})\n [\"of\", \"kind\", \"some\", \"monster\"]\n\n \"\"\"\n @spec sort_by(t, (element -> mapped_element), (mapped_element, mapped_element -> boolean)) ::\n list\n when mapped_element: element\n\n def sort_by(enumerable, mapper, sorter \\\\ &<=\/2) do\n enumerable\n |> map(&{&1, mapper.(&1)})\n |> sort(&sorter.(elem(&1, 1), elem(&2, 1)))\n |> map(&elem(&1, 0))\n end\n\n @doc \"\"\"\n Splits the `enumerable` into two enumerables, leaving `count`\n elements in the first one.\n\n If `count` is a negative number, it starts counting from the\n back to the beginning of the enumerable.\n\n Be aware that a negative `count` implies the `enumerable`\n will be enumerated twice: once to calculate the position, and\n a second time to do the actual splitting.\n\n ## Examples\n\n iex> Enum.split([1, 2, 3], 2)\n {[1, 2], [3]}\n\n iex> Enum.split([1, 2, 3], 10)\n {[1, 2, 3], []}\n\n iex> Enum.split([1, 2, 3], 0)\n {[], [1, 2, 3]}\n\n iex> Enum.split([1, 2, 3], -1)\n {[1, 2], [3]}\n\n iex> Enum.split([1, 2, 3], -5)\n {[], [1, 2, 3]}\n\n \"\"\"\n @spec split(t, integer) :: {list, list}\n def split(enumerable, count) when is_list(enumerable) and count >= 0 do\n split_list(enumerable, count, [])\n end\n\n def split(enumerable, count) when count >= 0 do\n {_, list1, list2} =\n reduce(enumerable, {count, [], []}, fn entry, {counter, acc1, acc2} ->\n if counter > 0 do\n {counter - 1, [entry | acc1], acc2}\n else\n {counter, acc1, [entry | acc2]}\n end\n end)\n\n {:lists.reverse(list1), :lists.reverse(list2)}\n end\n\n def split(enumerable, count) when count < 0 do\n split_reverse_list(reverse(enumerable), -count, [])\n end\n\n @doc \"\"\"\n Splits enumerable in two at the position of the element for which\n `fun` returns `false` for the first time.\n\n ## Examples\n\n iex> Enum.split_while([1, 2, 3, 4], fn(x) -> x < 3 end)\n {[1, 2], [3, 4]}\n\n \"\"\"\n @spec split_while(t, (element -> as_boolean(term))) :: {list, list}\n def split_while(enumerable, fun) when is_list(enumerable) do\n split_while_list(enumerable, fun, [])\n end\n\n def split_while(enumerable, fun) do\n {list1, list2} =\n reduce(enumerable, {[], []}, fn\n entry, {acc1, []} ->\n if(fun.(entry), do: {[entry | acc1], []}, else: {acc1, [entry]})\n\n entry, {acc1, acc2} ->\n {acc1, [entry | acc2]}\n end)\n\n {:lists.reverse(list1), :lists.reverse(list2)}\n end\n\n @doc \"\"\"\n Returns the sum of all elements.\n\n Raises `ArithmeticError` if `enumerable` contains a non-numeric value.\n\n ## Examples\n\n iex> Enum.sum([1, 2, 3])\n 6\n\n \"\"\"\n @spec sum(t) :: number\n def sum(enumerable)\n\n def sum(first..last) do\n div((last + first) * (abs(last - first) + 1), 2)\n end\n\n def sum(enumerable) do\n reduce(enumerable, 0, &+\/2)\n end\n\n @doc \"\"\"\n Takes the first `amount` items from the enumerable.\n\n If a negative `amount` is given, the `amount` of last values will be taken.\n The `enumerable` will be enumerated once to retrieve the proper index and\n the remaining calculation is performed from the end.\n\n ## Examples\n\n iex> Enum.take([1, 2, 3], 2)\n [1, 2]\n\n iex> Enum.take([1, 2, 3], 10)\n [1, 2, 3]\n\n iex> Enum.take([1, 2, 3], 0)\n []\n\n iex> Enum.take([1, 2, 3], -1)\n [3]\n\n \"\"\"\n @spec take(t, integer) :: list\n def take(enumerable, amount)\n\n def take(_enumerable, 0), do: []\n\n def take(enumerable, amount)\n when is_list(enumerable) and is_integer(amount) and amount > 0 do\n take_list(enumerable, amount)\n end\n\n def take(enumerable, amount) when is_integer(amount) and amount > 0 do\n {_, {res, _}} =\n Enumerable.reduce(enumerable, {:cont, {[], amount}}, fn entry, {list, n} ->\n case n do\n 1 -> {:halt, {[entry | list], n - 1}}\n _ -> {:cont, {[entry | list], n - 1}}\n end\n end)\n\n :lists.reverse(res)\n end\n\n def take(enumerable, amount) when is_integer(amount) and amount < 0 do\n {count, fun} = slice_count_and_fun(enumerable)\n first = Kernel.max(amount + count, 0)\n fun.(first, count - first)\n end\n\n @doc \"\"\"\n Returns a list of every `nth` item in the enumerable,\n starting with the first element.\n\n The first item is always included, unless `nth` is 0.\n\n The second argument specifying every `nth` item must be a non-negative\n integer.\n\n ## Examples\n\n iex> Enum.take_every(1..10, 2)\n [1, 3, 5, 7, 9]\n\n iex> Enum.take_every(1..10, 0)\n []\n\n iex> Enum.take_every([1, 2, 3], 1)\n [1, 2, 3]\n\n \"\"\"\n @spec take_every(t, non_neg_integer) :: list\n def take_every(enumerable, nth)\n\n def take_every(enumerable, 1), do: to_list(enumerable)\n def take_every(_enumerable, 0), do: []\n def take_every([], nth) when is_integer(nth) and nth > 1, do: []\n\n def take_every(enumerable, nth) when is_integer(nth) and nth > 1 do\n {res, _} = reduce(enumerable, {[], :first}, R.take_every(nth))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Takes `count` random items from `enumerable`.\n\n Notice this function will traverse the whole `enumerable` to\n get the random sublist.\n\n See `random\/1` for notes on implementation and random seed.\n\n ## Examples\n\n # Although not necessary, let's seed the random algorithm\n iex> :rand.seed(:exsplus, {1, 2, 3})\n iex> Enum.take_random(1..10, 2)\n [5, 4]\n iex> Enum.take_random(?a..?z, 5)\n 'ipybz'\n\n \"\"\"\n @spec take_random(t, non_neg_integer) :: list\n def take_random(enumerable, count)\n def take_random(_enumerable, 0), do: []\n\n def take_random(enumerable, count) when is_integer(count) and count > 128 do\n reducer = fn elem, {idx, sample} ->\n jdx = random_integer(0, idx)\n\n cond do\n idx < count ->\n value = Map.get(sample, jdx)\n {idx + 1, Map.put(sample, idx, value) |> Map.put(jdx, elem)}\n\n jdx < count ->\n {idx + 1, Map.put(sample, jdx, elem)}\n\n true ->\n {idx + 1, sample}\n end\n end\n\n {size, sample} = reduce(enumerable, {0, %{}}, reducer)\n take_random(sample, Kernel.min(count, size), [])\n end\n\n def take_random(enumerable, count) when is_integer(count) and count > 0 do\n sample = Tuple.duplicate(nil, count)\n\n reducer = fn elem, {idx, sample} ->\n jdx = random_integer(0, idx)\n\n cond do\n idx < count ->\n value = elem(sample, jdx)\n {idx + 1, put_elem(sample, idx, value) |> put_elem(jdx, elem)}\n\n jdx < count ->\n {idx + 1, put_elem(sample, jdx, elem)}\n\n true ->\n {idx + 1, sample}\n end\n end\n\n {size, sample} = reduce(enumerable, {0, sample}, reducer)\n sample |> Tuple.to_list() |> take(Kernel.min(count, size))\n end\n\n defp take_random(_sample, 0, acc), do: acc\n\n defp take_random(sample, position, acc) do\n position = position - 1\n take_random(sample, position, [Map.get(sample, position) | acc])\n end\n\n @doc \"\"\"\n Takes the items from the beginning of the enumerable while `fun` returns\n a truthy value.\n\n ## Examples\n\n iex> Enum.take_while([1, 2, 3], fn(x) -> x < 3 end)\n [1, 2]\n\n \"\"\"\n @spec take_while(t, (element -> as_boolean(term))) :: list\n def take_while(enumerable, fun) when is_list(enumerable) do\n take_while_list(enumerable, fun)\n end\n\n def take_while(enumerable, fun) do\n {_, res} =\n Enumerable.reduce(enumerable, {:cont, []}, fn entry, acc ->\n if fun.(entry) do\n {:cont, [entry | acc]}\n else\n {:halt, acc}\n end\n end)\n\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Converts `enumerable` to a list.\n\n ## Examples\n\n iex> Enum.to_list(1..3)\n [1, 2, 3]\n\n \"\"\"\n @spec to_list(t) :: [element]\n def to_list(enumerable) when is_list(enumerable) do\n enumerable\n end\n\n def to_list(enumerable) do\n reverse(enumerable) |> :lists.reverse()\n end\n\n @doc \"\"\"\n Enumerates the `enumerable`, removing all duplicated elements.\n\n ## Examples\n\n iex> Enum.uniq([1, 2, 3, 3, 2, 1])\n [1, 2, 3]\n\n \"\"\"\n @spec uniq(t) :: list\n def uniq(enumerable) do\n uniq_by(enumerable, fn x -> x end)\n end\n\n @doc false\n # TODO: Remove on 2.0\n # (hard-deprecated in elixir_dispatch)\n def uniq(enumerable, fun) do\n uniq_by(enumerable, fun)\n end\n\n @doc \"\"\"\n Enumerates the `enumerable`, by removing the elements for which\n function `fun` returned duplicate items.\n\n The function `fun` maps every element to a term. Two elements are\n considered duplicates if the return value of `fun` is equal for\n both of them.\n\n The first occurrence of each element is kept.\n\n ## Example\n\n iex> Enum.uniq_by([{1, :x}, {2, :y}, {1, :z}], fn {x, _} -> x end)\n [{1, :x}, {2, :y}]\n\n iex> Enum.uniq_by([a: {:tea, 2}, b: {:tea, 2}, c: {:coffee, 1}], fn {_, y} -> y end)\n [a: {:tea, 2}, c: {:coffee, 1}]\n\n \"\"\"\n @spec uniq_by(t, (element -> term)) :: list\n\n def uniq_by(enumerable, fun) when is_list(enumerable) do\n uniq_list(enumerable, %{}, fun)\n end\n\n def uniq_by(enumerable, fun) do\n {list, _} = reduce(enumerable, {[], %{}}, R.uniq_by(fun))\n :lists.reverse(list)\n end\n\n @doc \"\"\"\n Opposite of `Enum.zip\/2`; extracts a two-element tuples from the\n enumerable and groups them together.\n\n It takes an enumerable with items being two-element tuples and returns\n a tuple with two lists, each of which is formed by the first and\n second element of each tuple, respectively.\n\n This function fails unless `enumerable` is or can be converted into a\n list of tuples with *exactly* two elements in each tuple.\n\n ## Examples\n\n iex> Enum.unzip([{:a, 1}, {:b, 2}, {:c, 3}])\n {[:a, :b, :c], [1, 2, 3]}\n\n iex> Enum.unzip(%{a: 1, b: 2})\n {[:a, :b], [1, 2]}\n\n \"\"\"\n @spec unzip(t) :: {[element], [element]}\n def unzip(enumerable) do\n {list1, list2} =\n reduce(enumerable, {[], []}, fn {el1, el2}, {list1, list2} ->\n {[el1 | list1], [el2 | list2]}\n end)\n\n {:lists.reverse(list1), :lists.reverse(list2)}\n end\n\n @doc \"\"\"\n Returns the enumerable with each element wrapped in a tuple\n alongside its index.\n\n If an `offset` is given, we will index from the given offset instead of from zero.\n\n ## Examples\n\n iex> Enum.with_index([:a, :b, :c])\n [a: 0, b: 1, c: 2]\n\n iex> Enum.with_index([:a, :b, :c], 3)\n [a: 3, b: 4, c: 5]\n\n \"\"\"\n @spec with_index(t, integer) :: [{element, index}]\n def with_index(enumerable, offset \\\\ 0) do\n map_reduce(enumerable, offset, fn x, acc ->\n {{x, acc}, acc + 1}\n end)\n |> elem(0)\n end\n\n @doc \"\"\"\n Zips corresponding elements from two enumerables into one list\n of tuples.\n\n The zipping finishes as soon as any enumerable completes.\n\n ## Examples\n\n iex> Enum.zip([1, 2, 3], [:a, :b, :c])\n [{1, :a}, {2, :b}, {3, :c}]\n\n iex> Enum.zip([1, 2, 3, 4, 5], [:a, :b, :c])\n [{1, :a}, {2, :b}, {3, :c}]\n\n \"\"\"\n @spec zip(t, t) :: [{any, any}]\n def zip(enumerable1, enumerable2)\n when is_list(enumerable1) and is_list(enumerable2) do\n zip_list(enumerable1, enumerable2)\n end\n\n def zip(enumerable1, enumerable2) do\n zip([enumerable1, enumerable2])\n end\n\n @doc \"\"\"\n Zips corresponding elements from a list of enumerables\n into one list of tuples.\n\n The zipping finishes as soon as any enumerable in the given list completes.\n\n ## Examples\n\n iex> Enum.zip([[1, 2, 3], [:a, :b, :c], [\"foo\", \"bar\", \"baz\"]])\n [{1, :a, \"foo\"}, {2, :b, \"bar\"}, {3, :c, \"baz\"}]\n\n iex> Enum.zip([[1, 2, 3, 4, 5], [:a, :b, :c]])\n [{1, :a}, {2, :b}, {3, :c}]\n\n \"\"\"\n @spec zip([t]) :: t\n\n def zip([]), do: []\n\n def zip(enumerables) when is_list(enumerables) do\n Stream.zip(enumerables).({:cont, []}, &{:cont, [&1 | &2]})\n |> elem(1)\n |> :lists.reverse()\n end\n\n ## Helpers\n\n @compile {:inline, aggregate: 3, entry_to_string: 1, reduce: 3, reduce_by: 3}\n\n defp entry_to_string(entry) when is_binary(entry), do: entry\n defp entry_to_string(entry), do: String.Chars.to_string(entry)\n\n defp aggregate([head | tail], fun, _empty) do\n :lists.foldl(fun, head, tail)\n end\n\n defp aggregate([], _fun, empty) do\n empty.()\n end\n\n defp aggregate(left..right, fun, _empty) do\n fun.(left, right)\n end\n\n defp aggregate(enumerable, fun, empty) do\n ref = make_ref()\n\n enumerable\n |> reduce(ref, fn\n element, ^ref -> element\n element, acc -> fun.(element, acc)\n end)\n |> case do\n ^ref -> empty.()\n result -> result\n end\n end\n\n defp reduce_by([head | tail], first, fun) do\n :lists.foldl(fun, first.(head), tail)\n end\n\n defp reduce_by([], _first, _fun) do\n :empty\n end\n\n defp reduce_by(enumerable, first, fun) do\n reduce(enumerable, :empty, fn\n element, {_, _} = acc -> fun.(element, acc)\n element, :empty -> first.(element)\n end)\n end\n\n defp random_integer(limit, limit) when is_integer(limit) do\n limit\n end\n\n defp random_integer(lower_limit, upper_limit) when upper_limit < lower_limit do\n random_integer(upper_limit, lower_limit)\n end\n\n defp random_integer(lower_limit, upper_limit) do\n lower_limit + :rand.uniform(upper_limit - lower_limit + 1) - 1\n end\n\n ## Implementations\n\n ## all?\n\n defp all_list([h | t], fun) do\n if fun.(h) do\n all_list(t, fun)\n else\n false\n end\n end\n\n defp all_list([], _) do\n true\n end\n\n ## any?\n\n defp any_list([h | t], fun) do\n if fun.(h) do\n true\n else\n any_list(t, fun)\n end\n end\n\n defp any_list([], _) do\n false\n end\n\n ## drop\n\n defp drop_list(list, 0), do: list\n defp drop_list([_ | tail], counter), do: drop_list(tail, counter - 1)\n defp drop_list([], _), do: []\n\n ## drop_while\n\n defp drop_while_list([head | tail], fun) do\n if fun.(head) do\n drop_while_list(tail, fun)\n else\n [head | tail]\n end\n end\n\n defp drop_while_list([], _) do\n []\n end\n\n ## filter\n\n defp filter_list([head | tail], fun) do\n if fun.(head) do\n [head | filter_list(tail, fun)]\n else\n filter_list(tail, fun)\n end\n end\n\n defp filter_list([], _fun) do\n []\n end\n\n ## find\n\n defp find_list([head | tail], default, fun) do\n if fun.(head) do\n head\n else\n find_list(tail, default, fun)\n end\n end\n\n defp find_list([], default, _) do\n default\n end\n\n ## find_index\n\n defp find_index_list([head | tail], counter, fun) do\n if fun.(head) do\n counter\n else\n find_index_list(tail, counter + 1, fun)\n end\n end\n\n defp find_index_list([], _, _) do\n nil\n end\n\n ## find_value\n\n defp find_value_list([head | tail], default, fun) do\n fun.(head) || find_value_list(tail, default, fun)\n end\n\n defp find_value_list([], default, _) do\n default\n end\n\n ## flat_map\n\n defp flat_map_list([head | tail], fun) do\n case fun.(head) do\n list when is_list(list) -> list ++ flat_map_list(tail, fun)\n other -> to_list(other) ++ flat_map_list(tail, fun)\n end\n end\n\n defp flat_map_list([], _fun) do\n []\n end\n\n ## reduce\n\n defp reduce_range_inc(first, first, acc, fun) do\n fun.(first, acc)\n end\n\n defp reduce_range_inc(first, last, acc, fun) do\n reduce_range_inc(first + 1, last, fun.(first, acc), fun)\n end\n\n defp reduce_range_dec(first, first, acc, fun) do\n fun.(first, acc)\n end\n\n defp reduce_range_dec(first, last, acc, fun) do\n reduce_range_dec(first - 1, last, fun.(first, acc), fun)\n end\n\n ## reject\n\n defp reject_list([head | tail], fun) do\n if fun.(head) do\n reject_list(tail, fun)\n else\n [head | reject_list(tail, fun)]\n end\n end\n\n defp reject_list([], _fun) do\n []\n end\n\n ## reverse_slice\n\n defp reverse_slice(rest, idx, idx, count, acc) do\n {slice, rest} = head_slice(rest, count, [])\n :lists.reverse(rest, :lists.reverse(slice, acc))\n end\n\n defp reverse_slice([elem | rest], idx, start, count, acc) do\n reverse_slice(rest, idx - 1, start, count, [elem | acc])\n end\n\n defp head_slice(rest, 0, acc), do: {acc, rest}\n\n defp head_slice([elem | rest], count, acc) do\n head_slice(rest, count - 1, [elem | acc])\n end\n\n ## shuffle\n\n defp shuffle_unwrap([{_, h} | enumerable], t) do\n shuffle_unwrap(enumerable, [h | t])\n end\n\n defp shuffle_unwrap([], t), do: t\n\n ## slice\n\n defp slice_any(enumerable, start, amount) when start < 0 do\n {count, fun} = slice_count_and_fun(enumerable)\n start = count + start\n\n if start >= 0 do\n fun.(start, Kernel.min(amount, count - start))\n else\n []\n end\n end\n\n defp slice_any(list, start, amount) when is_list(list) do\n Enumerable.List.slice(list, start, amount)\n end\n\n defp slice_any(enumerable, start, amount) do\n case Enumerable.slice(enumerable) do\n {:ok, count, _} when start >= count ->\n []\n\n {:ok, count, fun} when is_function(fun) ->\n fun.(start, Kernel.min(amount, count - start))\n\n {:error, module} ->\n slice_enum(enumerable, module, start, amount)\n end\n end\n\n defp slice_enum(enumerable, module, start, amount) do\n {_, {_, _, slice}} =\n module.reduce(enumerable, {:cont, {start, amount, []}}, fn\n _entry, {start, amount, _list} when start > 0 ->\n {:cont, {start - 1, amount, []}}\n\n entry, {start, amount, list} when amount > 1 ->\n {:cont, {start, amount - 1, [entry | list]}}\n\n entry, {start, amount, list} ->\n {:halt, {start, amount, [entry | list]}}\n end)\n\n :lists.reverse(slice)\n end\n\n defp slice_count_and_fun(enumerable) when is_list(enumerable) do\n {length(enumerable), &Enumerable.List.slice(enumerable, &1, &2)}\n end\n\n defp slice_count_and_fun(enumerable) do\n case Enumerable.slice(enumerable) do\n {:ok, count, fun} when is_function(fun) ->\n {count, fun}\n\n {:error, module} ->\n {_, {list, count}} =\n module.reduce(enumerable, {:cont, {[], 0}}, fn elem, {acc, count} ->\n {:cont, {[elem | acc], count + 1}}\n end)\n\n {count, &Enumerable.List.slice(:lists.reverse(list), &1, &2)}\n end\n end\n\n ## sort\n\n defp sort_reducer(entry, {:split, y, x, r, rs, bool}, fun) do\n cond do\n fun.(y, entry) == bool ->\n {:split, entry, y, [x | r], rs, bool}\n\n fun.(x, entry) == bool ->\n {:split, y, entry, [x | r], rs, bool}\n\n r == [] ->\n {:split, y, x, [entry], rs, bool}\n\n true ->\n {:pivot, y, x, r, rs, entry, bool}\n end\n end\n\n defp sort_reducer(entry, {:pivot, y, x, r, rs, s, bool}, fun) do\n cond do\n fun.(y, entry) == bool ->\n {:pivot, entry, y, [x | r], rs, s, bool}\n\n fun.(x, entry) == bool ->\n {:pivot, y, entry, [x | r], rs, s, bool}\n\n fun.(s, entry) == bool ->\n {:split, entry, s, [], [[y, x | r] | rs], bool}\n\n true ->\n {:split, s, entry, [], [[y, x | r] | rs], bool}\n end\n end\n\n defp sort_reducer(entry, [x], fun) do\n {:split, entry, x, [], [], fun.(x, entry)}\n end\n\n defp sort_reducer(entry, acc, _fun) do\n [entry | acc]\n end\n\n defp sort_terminator({:split, y, x, r, rs, bool}, fun) do\n sort_merge([[y, x | r] | rs], fun, bool)\n end\n\n defp sort_terminator({:pivot, y, x, r, rs, s, bool}, fun) do\n sort_merge([[s], [y, x | r] | rs], fun, bool)\n end\n\n defp sort_terminator(acc, _fun) do\n acc\n end\n\n defp sort_merge(list, fun, true), do: reverse_sort_merge(list, [], fun, true)\n\n defp sort_merge(list, fun, false), do: sort_merge(list, [], fun, false)\n\n defp sort_merge([t1, [h2 | t2] | l], acc, fun, true),\n do: sort_merge(l, [sort_merge1(t1, h2, t2, [], fun, false) | acc], fun, true)\n\n defp sort_merge([[h2 | t2], t1 | l], acc, fun, false),\n do: sort_merge(l, [sort_merge1(t1, h2, t2, [], fun, false) | acc], fun, false)\n\n defp sort_merge([l], [], _fun, _bool), do: l\n\n defp sort_merge([l], acc, fun, bool),\n do: reverse_sort_merge([:lists.reverse(l, []) | acc], [], fun, bool)\n\n defp sort_merge([], acc, fun, bool), do: reverse_sort_merge(acc, [], fun, bool)\n\n defp reverse_sort_merge([[h2 | t2], t1 | l], acc, fun, true),\n do: reverse_sort_merge(l, [sort_merge1(t1, h2, t2, [], fun, true) | acc], fun, true)\n\n defp reverse_sort_merge([t1, [h2 | t2] | l], acc, fun, false),\n do: reverse_sort_merge(l, [sort_merge1(t1, h2, t2, [], fun, true) | acc], fun, false)\n\n defp reverse_sort_merge([l], acc, fun, bool),\n do: sort_merge([:lists.reverse(l, []) | acc], [], fun, bool)\n\n defp reverse_sort_merge([], acc, fun, bool), do: sort_merge(acc, [], fun, bool)\n\n defp sort_merge1([h1 | t1], h2, t2, m, fun, bool) do\n if fun.(h1, h2) == bool do\n sort_merge2(h1, t1, t2, [h2 | m], fun, bool)\n else\n sort_merge1(t1, h2, t2, [h1 | m], fun, bool)\n end\n end\n\n defp sort_merge1([], h2, t2, m, _fun, _bool), do: :lists.reverse(t2, [h2 | m])\n\n defp sort_merge2(h1, t1, [h2 | t2], m, fun, bool) do\n if fun.(h1, h2) == bool do\n sort_merge2(h1, t1, t2, [h2 | m], fun, bool)\n else\n sort_merge1(t1, h2, t2, [h1 | m], fun, bool)\n end\n end\n\n defp sort_merge2(h1, t1, [], m, _fun, _bool), do: :lists.reverse(t1, [h1 | m])\n\n ## split\n\n defp split_list([head | tail], counter, acc) when counter > 0 do\n split_list(tail, counter - 1, [head | acc])\n end\n\n defp split_list(list, 0, acc) do\n {:lists.reverse(acc), list}\n end\n\n defp split_list([], _, acc) do\n {:lists.reverse(acc), []}\n end\n\n defp split_reverse_list([head | tail], counter, acc) when counter > 0 do\n split_reverse_list(tail, counter - 1, [head | acc])\n end\n\n defp split_reverse_list(list, 0, acc) do\n {:lists.reverse(list), acc}\n end\n\n defp split_reverse_list([], _, acc) do\n {[], acc}\n end\n\n ## split_while\n\n defp split_while_list([head | tail], fun, acc) do\n if fun.(head) do\n split_while_list(tail, fun, [head | acc])\n else\n {:lists.reverse(acc), [head | tail]}\n end\n end\n\n defp split_while_list([], _, acc) do\n {:lists.reverse(acc), []}\n end\n\n ## take\n\n defp take_list([head | _], 1), do: [head]\n defp take_list([head | tail], counter), do: [head | take_list(tail, counter - 1)]\n defp take_list([], _counter), do: []\n\n ## take_while\n\n defp take_while_list([head | tail], fun) do\n if fun.(head) do\n [head | take_while_list(tail, fun)]\n else\n []\n end\n end\n\n defp take_while_list([], _) do\n []\n end\n\n ## uniq\n\n defp uniq_list([head | tail], set, fun) do\n value = fun.(head)\n\n case set do\n %{^value => true} -> uniq_list(tail, set, fun)\n %{} -> [head | uniq_list(tail, Map.put(set, value, true), fun)]\n end\n end\n\n defp uniq_list([], _set, _fun) do\n []\n end\n\n ## zip\n\n defp zip_list([h1 | next1], [h2 | next2]) do\n [{h1, h2} | zip_list(next1, next2)]\n end\n\n defp zip_list(_, []), do: []\n defp zip_list([], _), do: []\nend\n\ndefimpl Enumerable, for: List do\n def count(_list), do: {:error, __MODULE__}\n def member?(_list, _value), do: {:error, __MODULE__}\n def slice(_list), do: {:error, __MODULE__}\n\n def reduce(_, {:halt, acc}, _fun), do: {:halted, acc}\n def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)}\n def reduce([], {:cont, acc}, _fun), do: {:done, acc}\n def reduce([h | t], {:cont, acc}, fun), do: reduce(t, fun.(h, acc), fun)\n\n @doc false\n def slice([], _start, _count), do: []\n def slice(_list, _start, 0), do: []\n def slice([head | tail], 0, count), do: [head | slice(tail, 0, count - 1)]\n def slice([_ | tail], start, count), do: slice(tail, start - 1, count)\nend\n\ndefimpl Enumerable, for: Map do\n def count(map) do\n {:ok, map_size(map)}\n end\n\n def member?(map, {key, value}) do\n {:ok, match?(%{^key => ^value}, map)}\n end\n\n def member?(_map, _other) do\n {:ok, false}\n end\n\n def slice(map) do\n {:ok, map_size(map), &Enumerable.List.slice(:maps.to_list(map), &1, &2)}\n end\n\n def reduce(map, acc, fun) do\n reduce_list(:maps.to_list(map), acc, fun)\n end\n\n defp reduce_list(_, {:halt, acc}, _fun), do: {:halted, acc}\n defp reduce_list(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce_list(list, &1, fun)}\n defp reduce_list([], {:cont, acc}, _fun), do: {:done, acc}\n defp reduce_list([h | t], {:cont, acc}, fun), do: reduce_list(t, fun.(h, acc), fun)\nend\n\ndefimpl Enumerable, for: Function do\n def count(_function), do: {:error, __MODULE__}\n def member?(_function, _value), do: {:error, __MODULE__}\n def slice(_function), do: {:error, __MODULE__}\n\n def reduce(function, acc, fun) when is_function(function, 2), do: function.(acc, fun)\n\n def reduce(function, _acc, _fun) do\n raise Protocol.UndefinedError,\n protocol: @protocol,\n value: function,\n description: \"only anonymous functions of arity 2 are enumerable\"\n end\nend\n","old_contents":"defprotocol Enumerable do\n @moduledoc \"\"\"\n Enumerable protocol used by `Enum` and `Stream` modules.\n\n When you invoke a function in the `Enum` module, the first argument\n is usually a collection that must implement this protocol.\n For example, the expression:\n\n Enum.map([1, 2, 3], &(&1 * 2))\n\n invokes `Enumerable.reduce\/3` to perform the reducing operation that\n builds a mapped list by calling the mapping function `&(&1 * 2)` on\n every element in the collection and consuming the element with an\n accumulated list.\n\n Internally, `Enum.map\/2` is implemented as follows:\n\n def map(enum, fun) do\n reducer = fn x, acc -> {:cont, [fun.(x) | acc]} end\n Enumerable.reduce(enum, {:cont, []}, reducer) |> elem(1) |> :lists.reverse()\n end\n\n Notice the user-supplied function is wrapped into a `t:reducer\/0` function.\n The `t:reducer\/0` function must return a tagged tuple after each step,\n as described in the `t:acc\/0` type. At the end, `Enumerable.reduce\/3`\n returns `t:result\/0`.\n\n This protocol uses tagged tuples to exchange information between the\n reducer function and the data type that implements the protocol. This\n allows enumeration of resources, such as files, to be done efficiently\n while also guaranteeing the resource will be closed at the end of the\n enumeration. This protocol also allows suspension of the enumeration,\n which is useful when interleaving between many enumerables is required\n (as in zip).\n\n This protocol requires four functions to be implemented, `reduce\/3`,\n `count\/1`, `member?\/2`, and `slice\/1`. The core of the protocol is the\n `reduce\/3` function. All other functions exist as optimizations paths\n for data structures that can implement certain properties in better\n than linear time.\n \"\"\"\n\n @typedoc \"\"\"\n The accumulator value for each step.\n\n It must be a tagged tuple with one of the following \"tags\":\n\n * `:cont` - the enumeration should continue\n * `:halt` - the enumeration should halt immediately\n * `:suspend` - the enumeration should be suspended immediately\n\n Depending on the accumulator value, the result returned by\n `Enumerable.reduce\/3` will change. Please check the `t:result\/0`\n type documentation for more information.\n\n In case a `t:reducer\/0` function returns a `:suspend` accumulator,\n it must be explicitly handled by the caller and never leak.\n \"\"\"\n @type acc :: {:cont, term} | {:halt, term} | {:suspend, term}\n\n @typedoc \"\"\"\n The reducer function.\n\n Should be called with the enumerable element and the\n accumulator contents.\n\n Returns the accumulator for the next enumeration step.\n \"\"\"\n @type reducer :: (term, term -> acc)\n\n @typedoc \"\"\"\n The result of the reduce operation.\n\n It may be *done* when the enumeration is finished by reaching\n its end, or *halted*\/*suspended* when the enumeration was halted\n or suspended by the `t:reducer\/0` function.\n\n In case a `t:reducer\/0` function returns the `:suspend` accumulator, the\n `:suspended` tuple must be explicitly handled by the caller and\n never leak. In practice, this means regular enumeration functions\n just need to be concerned about `:done` and `:halted` results.\n\n Furthermore, a `:suspend` call must always be followed by another call,\n eventually halting or continuing until the end.\n \"\"\"\n @type result ::\n {:done, term}\n | {:halted, term}\n | {:suspended, term, continuation}\n\n @typedoc \"\"\"\n A partially applied reduce function.\n\n The continuation is the closure returned as a result when\n the enumeration is suspended. When invoked, it expects\n a new accumulator and it returns the result.\n\n A continuation can be trivially implemented as long as the reduce\n function is defined in a tail recursive fashion. If the function\n is tail recursive, all the state is passed as arguments, so\n the continuation is the reducing function partially applied.\n \"\"\"\n @type continuation :: (acc -> result)\n\n @typedoc \"\"\"\n A slicing function that receives the initial position and the\n number of elements in the slice.\n\n The `start` position is a number `>= 0` and guaranteed to\n exist in the enumerable. The length is a number `>= 1` in a way\n that `start + length <= count`, where `count` is the maximum\n amount of elements in the enumerable.\n\n The function should return a non empty list where\n the amount of elements is equal to `length`.\n \"\"\"\n @type slicing_fun :: (start :: non_neg_integer, length :: pos_integer -> [term()])\n\n @doc \"\"\"\n Reduces the enumerable into an element.\n\n Most of the operations in `Enum` are implemented in terms of reduce.\n This function should apply the given `t:reducer\/0` function to each\n item in the enumerable and proceed as expected by the returned\n accumulator.\n\n See the documentation of the types `t:result\/0` and `t:acc\/0` for\n more information.\n\n ## Examples\n\n As an example, here is the implementation of `reduce` for lists:\n\n def reduce(_, {:halt, acc}, _fun), do: {:halted, acc}\n def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)}\n def reduce([], {:cont, acc}, _fun), do: {:done, acc}\n def reduce([h | t], {:cont, acc}, fun), do: reduce(t, fun.(h, acc), fun)\n\n \"\"\"\n @spec reduce(t, acc, reducer) :: result\n def reduce(enumerable, acc, fun)\n\n @doc \"\"\"\n Retrieves the number of elements in the enumerable.\n\n It should return `{:ok, count}` if you can count the number of elements\n in the enumerable.\n\n Otherwise it should return `{:error, __MODULE__}` and a default algorithm\n built on top of `reduce\/3` that runs in linear time will be used.\n \"\"\"\n @spec count(t) :: {:ok, non_neg_integer} | {:error, module}\n def count(enumerable)\n\n @doc \"\"\"\n Checks if an element exists within the enumerable.\n\n It should return `{:ok, boolean}` if you can check the membership of a\n given element in the enumerable with `===` without traversing the whole\n enumerable.\n\n Otherwise it should return `{:error, __MODULE__}` and a default algorithm\n built on top of `reduce\/3` that runs in linear time will be used.\n \"\"\"\n @spec member?(t, term) :: {:ok, boolean} | {:error, module}\n def member?(enumerable, element)\n\n @doc \"\"\"\n Returns a function that slices the data structure contiguously.\n\n It should return `{:ok, size, slicing_fun}` if the enumerable has\n a known bound and can access a position in the enumerable without\n traversing all previous elements.\n\n Otherwise it should return `{:error, __MODULE__}` and a default\n algorithm built on top of `reduce\/3` that runs in linear time will be\n used.\n\n ## Differences to `count\/1`\n\n The `size` value returned by this function is used for boundary checks,\n therefore it is extremely important that this function only returns `:ok`\n if retrieving the `size` of the enumerable is cheap, fast and takes constant\n time. Otherwise the simplest of operations, such as `Enum.at(enumerable, 0)`,\n will become too expensive.\n\n On the other hand, the `count\/1` function in this protocol should be\n implemented whenever you can count the number of elements in the collection.\n \"\"\"\n @spec slice(t) ::\n {:ok, size :: non_neg_integer(), slicing_fun()}\n | {:error, module()}\n def slice(enumerable)\nend\n\ndefmodule Enum do\n import Kernel, except: [max: 2, min: 2]\n\n @moduledoc \"\"\"\n Provides a set of algorithms that enumerate over enumerables according\n to the `Enumerable` protocol.\n\n iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end)\n [2, 4, 6]\n\n Some particular types, like maps, yield a specific format on enumeration.\n For example, the argument is always a `{key, value}` tuple for maps:\n\n iex> map = %{a: 1, b: 2}\n iex> Enum.map(map, fn {k, v} -> {k, v * 2} end)\n [a: 2, b: 4]\n\n Note that the functions in the `Enum` module are eager: they always\n start the enumeration of the given enumerable. The `Stream` module\n allows lazy enumeration of enumerables and provides infinite streams.\n\n Since the majority of the functions in `Enum` enumerate the whole\n enumerable and return a list as result, infinite streams need to\n be carefully used with such functions, as they can potentially run\n forever. For example:\n\n Enum.each Stream.cycle([1, 2, 3]), &IO.puts(&1)\n\n \"\"\"\n\n @compile :inline_list_funcs\n\n @type t :: Enumerable.t()\n @type acc :: any\n @type element :: any\n @type index :: integer\n @type default :: any\n\n # Require Stream.Reducers and its callbacks\n require Stream.Reducers, as: R\n\n defmacrop skip(acc) do\n acc\n end\n\n defmacrop next(_, entry, acc) do\n quote(do: [unquote(entry) | unquote(acc)])\n end\n\n defmacrop acc(head, state, _) do\n quote(do: {unquote(head), unquote(state)})\n end\n\n defmacrop next_with_acc(_, entry, head, state, _) do\n quote do\n {[unquote(entry) | unquote(head)], unquote(state)}\n end\n end\n\n @doc \"\"\"\n Returns true if the given `fun` evaluates to true on all of the items in the enumerable.\n\n It stops the iteration at the first invocation that returns `false` or `nil`.\n\n ## Examples\n\n iex> Enum.all?([2, 4, 6], fn(x) -> rem(x, 2) == 0 end)\n true\n\n iex> Enum.all?([2, 3, 4], fn(x) -> rem(x, 2) == 0 end)\n false\n\n If no function is given, it defaults to checking if\n all items in the enumerable are truthy values.\n\n iex> Enum.all?([1, 2, 3])\n true\n\n iex> Enum.all?([1, nil, 3])\n false\n\n \"\"\"\n @spec all?(t, (element -> as_boolean(term))) :: boolean\n\n def all?(enumerable, fun \\\\ fn x -> x end)\n\n def all?(enumerable, fun) when is_list(enumerable) do\n all_list(enumerable, fun)\n end\n\n def all?(enumerable, fun) do\n Enumerable.reduce(enumerable, {:cont, true}, fn entry, _ ->\n if fun.(entry), do: {:cont, true}, else: {:halt, false}\n end)\n |> elem(1)\n end\n\n @doc \"\"\"\n Returns true if the given `fun` evaluates to true on any of the items in the enumerable.\n\n It stops the iteration at the first invocation that returns a truthy value (not `false` or `nil`).\n\n ## Examples\n\n iex> Enum.any?([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n false\n\n iex> Enum.any?([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n true\n\n If no function is given, it defaults to checking if at least one item\n in the enumerable is a truthy value.\n\n iex> Enum.any?([false, false, false])\n false\n\n iex> Enum.any?([false, true, false])\n true\n\n \"\"\"\n @spec any?(t, (element -> as_boolean(term))) :: boolean\n\n def any?(enumerable, fun \\\\ fn x -> x end)\n\n def any?(enumerable, fun) when is_list(enumerable) do\n any_list(enumerable, fun)\n end\n\n def any?(enumerable, fun) do\n Enumerable.reduce(enumerable, {:cont, false}, fn entry, _ ->\n if fun.(entry), do: {:halt, true}, else: {:cont, false}\n end)\n |> elem(1)\n end\n\n @doc \"\"\"\n Finds the element at the given `index` (zero-based).\n\n Returns `default` if `index` is out of bounds.\n\n A negative `index` can be passed, which means the `enumerable` is\n enumerated once and the `index` is counted from the end (e.g.\n `-1` finds the last element).\n\n Note this operation takes linear time. In order to access\n the element at index `index`, it will need to traverse `index`\n previous elements.\n\n ## Examples\n\n iex> Enum.at([2, 4, 6], 0)\n 2\n\n iex> Enum.at([2, 4, 6], 2)\n 6\n\n iex> Enum.at([2, 4, 6], 4)\n nil\n\n iex> Enum.at([2, 4, 6], 4, :none)\n :none\n\n \"\"\"\n @spec at(t, index, default) :: element | default\n def at(enumerable, index, default \\\\ nil) do\n case slice_any(enumerable, index, 1) do\n [value] -> value\n [] -> default\n end\n end\n\n # Deprecate on v1.7\n @doc false\n def chunk(enumerable, count), do: chunk(enumerable, count, count, nil)\n\n # Deprecate on v1.7\n @doc false\n def chunk(enumerable, count, step, leftover \\\\ nil) do\n chunk_every(enumerable, count, step, leftover || :discard)\n end\n\n @doc \"\"\"\n Shortcut to `chunk_every(enumerable, count, count)`.\n \"\"\"\n @spec chunk_every(t, pos_integer) :: [list]\n def chunk_every(enumerable, count), do: chunk_every(enumerable, count, count, [])\n\n @doc \"\"\"\n Returns list of lists containing `count` items each, where\n each new chunk starts `step` elements into the enumerable.\n\n `step` is optional and, if not passed, defaults to `count`, i.e.\n chunks do not overlap.\n\n If the last chunk does not have `count` elements to fill the chunk,\n elements are taken from `leftover` to fill in the chunk. If `leftover`\n does not have enough elements to fill the chunk, then a partial chunk\n is returned with less than `count` elements.\n\n If `:discard` is given in `leftover`, the last chunk is discarded\n unless it has exactly `count` elements.\n\n ## Examples\n\n iex> Enum.chunk_every([1, 2, 3, 4, 5, 6], 2)\n [[1, 2], [3, 4], [5, 6]]\n\n iex> Enum.chunk_every([1, 2, 3, 4, 5, 6], 3, 2, :discard)\n [[1, 2, 3], [3, 4, 5]]\n\n iex> Enum.chunk_every([1, 2, 3, 4, 5, 6], 3, 2, [7])\n [[1, 2, 3], [3, 4, 5], [5, 6, 7]]\n\n iex> Enum.chunk_every([1, 2, 3, 4], 3, 3, [])\n [[1, 2, 3], [4]]\n\n iex> Enum.chunk_every([1, 2, 3, 4], 10)\n [[1, 2, 3, 4]]\n\n \"\"\"\n @spec chunk_every(t, pos_integer, pos_integer, t | :discard) :: [list]\n def chunk_every(enumerable, count, step, leftover \\\\ [])\n when is_integer(count) and count > 0 and is_integer(step) and step > 0 do\n R.chunk_every(&chunk_while\/4, enumerable, count, step, leftover)\n end\n\n @doc \"\"\"\n Chunks the `enum` with fine grained control when every chunk is emitted.\n\n `chunk_fun` receives the current element and the accumulator and\n must return `{:cont, element, acc}` to emit the given chunk and\n continue with accumulator or `{:cont, acc}` to not emit any chunk\n and continue with the return accumulator.\n\n `after_fun` is invoked when iteration is done and must also return\n `{:cont, element, acc}` or `{:cont, acc}`.\n\n Returns a list of lists.\n\n ## Examples\n\n iex> chunk_fun = fn i, acc ->\n ...> if rem(i, 2) == 0 do\n ...> {:cont, Enum.reverse([i | acc]), []}\n ...> else\n ...> {:cont, [i | acc]}\n ...> end\n ...> end\n iex> after_fun = fn\n ...> [] -> {:cont, []}\n ...> acc -> {:cont, Enum.reverse(acc), []}\n ...> end\n iex> Enum.chunk_while(1..10, [], chunk_fun, after_fun)\n [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]\n\n \"\"\"\n @spec chunk_while(\n t,\n acc,\n (element, acc -> {:cont, chunk, acc} | {:cont, acc} | {:halt, acc}),\n (acc -> {:cont, chunk, acc} | {:cont, acc})\n ) :: Enumerable.t()\n when chunk: any\n def chunk_while(enum, acc, chunk_fun, after_fun) do\n {_, {res, acc}} =\n Enumerable.reduce(enum, {:cont, {[], acc}}, fn entry, {buffer, acc} ->\n case chunk_fun.(entry, acc) do\n {:cont, emit, acc} -> {:cont, {[emit | buffer], acc}}\n {:cont, acc} -> {:cont, {buffer, acc}}\n {:halt, acc} -> {:halt, {buffer, acc}}\n end\n end)\n\n case after_fun.(acc) do\n {:cont, _acc} -> :lists.reverse(res)\n {:cont, elem, _acc} -> :lists.reverse([elem | res])\n end\n end\n\n @doc \"\"\"\n Splits enumerable on every element for which `fun` returns a new\n value.\n\n Returns a list of lists.\n\n ## Examples\n\n iex> Enum.chunk_by([1, 2, 2, 3, 4, 4, 6, 7, 7], &(rem(&1, 2) == 1))\n [[1], [2, 2], [3], [4, 4, 6], [7, 7]]\n\n \"\"\"\n @spec chunk_by(t, (element -> any)) :: [list]\n def chunk_by(enumerable, fun) do\n R.chunk_by(&chunk_while\/4, enumerable, fun)\n end\n\n @doc \"\"\"\n Given an enumerable of enumerables, concatenates the enumerables into\n a single list.\n\n ## Examples\n\n iex> Enum.concat([1..3, 4..6, 7..9])\n [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n iex> Enum.concat([[1, [2], 3], [4], [5, 6]])\n [1, [2], 3, 4, 5, 6]\n\n \"\"\"\n @spec concat(t) :: t\n def concat(enumerables) do\n fun = &[&1 | &2]\n reduce(enumerables, [], &reduce(&1, &2, fun)) |> :lists.reverse()\n end\n\n @doc \"\"\"\n Concatenates the enumerable on the right with the enumerable on the\n left.\n\n This function produces the same result as the `Kernel.++\/2` operator\n for lists.\n\n ## Examples\n\n iex> Enum.concat(1..3, 4..6)\n [1, 2, 3, 4, 5, 6]\n\n iex> Enum.concat([1, 2, 3], [4, 5, 6])\n [1, 2, 3, 4, 5, 6]\n\n \"\"\"\n @spec concat(t, t) :: t\n def concat(left, right) when is_list(left) and is_list(right) do\n left ++ right\n end\n\n def concat(left, right) do\n concat([left, right])\n end\n\n @doc \"\"\"\n Returns the size of the enumerable.\n\n ## Examples\n\n iex> Enum.count([1, 2, 3])\n 3\n\n \"\"\"\n @spec count(t) :: non_neg_integer\n def count(enumerable) when is_list(enumerable) do\n length(enumerable)\n end\n\n def count(enumerable) do\n case Enumerable.count(enumerable) do\n {:ok, value} when is_integer(value) ->\n value\n\n {:error, module} ->\n module.reduce(enumerable, {:cont, 0}, fn _, acc -> {:cont, acc + 1} end) |> elem(1)\n end\n end\n\n @doc \"\"\"\n Returns the count of items in the enumerable for which `fun` returns\n a truthy value.\n\n ## Examples\n\n iex> Enum.count([1, 2, 3, 4, 5], fn(x) -> rem(x, 2) == 0 end)\n 2\n\n \"\"\"\n @spec count(t, (element -> as_boolean(term))) :: non_neg_integer\n def count(enumerable, fun) do\n reduce(enumerable, 0, fn entry, acc ->\n if(fun.(entry), do: acc + 1, else: acc)\n end)\n end\n\n @doc \"\"\"\n Enumerates the `enumerable`, returning a list where all consecutive\n duplicated elements are collapsed to a single element.\n\n Elements are compared using `===`.\n\n If you want to remove all duplicated elements, regardless of order,\n see `uniq\/1`.\n\n ## Examples\n\n iex> Enum.dedup([1, 2, 3, 3, 2, 1])\n [1, 2, 3, 2, 1]\n\n iex> Enum.dedup([1, 1, 2, 2.0, :three, :\"three\"])\n [1, 2, 2.0, :three]\n\n \"\"\"\n @spec dedup(t) :: list\n def dedup(enumerable) do\n dedup_by(enumerable, fn x -> x end)\n end\n\n @doc \"\"\"\n Enumerates the `enumerable`, returning a list where all consecutive\n duplicated elements are collapsed to a single element.\n\n The function `fun` maps every element to a term which is used to\n determine if two elements are duplicates.\n\n ## Examples\n\n iex> Enum.dedup_by([{1, :a}, {2, :b}, {2, :c}, {1, :a}], fn {x, _} -> x end)\n [{1, :a}, {2, :b}, {1, :a}]\n\n iex> Enum.dedup_by([5, 1, 2, 3, 2, 1], fn x -> x > 2 end)\n [5, 1, 3, 2]\n\n \"\"\"\n @spec dedup_by(t, (element -> term)) :: list\n def dedup_by(enumerable, fun) do\n {list, _} = reduce(enumerable, {[], []}, R.dedup(fun))\n :lists.reverse(list)\n end\n\n @doc \"\"\"\n Drops the `amount` of items from the enumerable.\n\n If a negative `amount` is given, the `amount` of last values will be dropped.\n The `enumerable` will be enumerated once to retrieve the proper index and\n the remaining calculation is performed from the end.\n\n ## Examples\n\n iex> Enum.drop([1, 2, 3], 2)\n [3]\n\n iex> Enum.drop([1, 2, 3], 10)\n []\n\n iex> Enum.drop([1, 2, 3], 0)\n [1, 2, 3]\n\n iex> Enum.drop([1, 2, 3], -1)\n [1, 2]\n\n \"\"\"\n @spec drop(t, integer) :: list\n def drop(enumerable, amount)\n when is_list(enumerable) and is_integer(amount) and amount >= 0 do\n drop_list(enumerable, amount)\n end\n\n def drop(enumerable, amount) when is_integer(amount) and amount >= 0 do\n {result, _} = reduce(enumerable, {[], amount}, R.drop())\n if is_list(result), do: :lists.reverse(result), else: []\n end\n\n def drop(enumerable, amount) when is_integer(amount) and amount < 0 do\n {count, fun} = slice_count_and_fun(enumerable)\n amount = Kernel.min(amount + count, count)\n\n if amount > 0 do\n fun.(0, amount)\n else\n []\n end\n end\n\n @doc \"\"\"\n Returns a list of every `nth` item in the enumerable dropped,\n starting with the first element.\n\n The first item is always dropped, unless `nth` is 0.\n\n The second argument specifying every `nth` item must be a non-negative\n integer.\n\n ## Examples\n\n iex> Enum.drop_every(1..10, 2)\n [2, 4, 6, 8, 10]\n\n iex> Enum.drop_every(1..10, 0)\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n iex> Enum.drop_every([1, 2, 3], 1)\n []\n\n \"\"\"\n @spec drop_every(t, non_neg_integer) :: list\n def drop_every(enumerable, nth)\n\n def drop_every(_enumerable, 1), do: []\n def drop_every(enumerable, 0), do: to_list(enumerable)\n def drop_every([], nth) when is_integer(nth), do: []\n\n def drop_every(enumerable, nth) when is_integer(nth) and nth > 1 do\n {res, _} = reduce(enumerable, {[], :first}, R.drop_every(nth))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Drops items at the beginning of the enumerable while `fun` returns a\n truthy value.\n\n ## Examples\n\n iex> Enum.drop_while([1, 2, 3, 2, 1], fn(x) -> x < 3 end)\n [3, 2, 1]\n\n \"\"\"\n @spec drop_while(t, (element -> as_boolean(term))) :: list\n def drop_while(enumerable, fun) when is_list(enumerable) do\n drop_while_list(enumerable, fun)\n end\n\n def drop_while(enumerable, fun) do\n {res, _} = reduce(enumerable, {[], true}, R.drop_while(fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Invokes the given `fun` for each item in the enumerable.\n\n Returns `:ok`.\n\n ## Examples\n\n Enum.each([\"some\", \"example\"], fn(x) -> IO.puts x end)\n \"some\"\n \"example\"\n #=> :ok\n\n \"\"\"\n @spec each(t, (element -> any)) :: :ok\n def each(enumerable, fun) when is_list(enumerable) do\n :lists.foreach(fun, enumerable)\n :ok\n end\n\n def each(enumerable, fun) do\n reduce(enumerable, nil, fn entry, _ ->\n fun.(entry)\n nil\n end)\n\n :ok\n end\n\n @doc \"\"\"\n Determines if the enumerable is empty.\n\n Returns `true` if `enumerable` is empty, otherwise `false`.\n\n ## Examples\n\n iex> Enum.empty?([])\n true\n\n iex> Enum.empty?([1, 2, 3])\n false\n\n \"\"\"\n @spec empty?(t) :: boolean\n def empty?(enumerable) when is_list(enumerable) do\n enumerable == []\n end\n\n def empty?(enumerable) do\n case Enumerable.slice(enumerable) do\n {:ok, value, _} ->\n value == 0\n\n {:error, module} ->\n module.reduce(enumerable, {:cont, true}, fn _, _ -> {:halt, false} end)\n |> elem(1)\n end\n end\n\n @doc \"\"\"\n Finds the element at the given `index` (zero-based).\n\n Returns `{:ok, element}` if found, otherwise `:error`.\n\n A negative `index` can be passed, which means the `enumerable` is\n enumerated once and the `index` is counted from the end (e.g.\n `-1` fetches the last element).\n\n Note this operation takes linear time. In order to access\n the element at index `index`, it will need to traverse `index`\n previous elements.\n\n ## Examples\n\n iex> Enum.fetch([2, 4, 6], 0)\n {:ok, 2}\n\n iex> Enum.fetch([2, 4, 6], -3)\n {:ok, 2}\n\n iex> Enum.fetch([2, 4, 6], 2)\n {:ok, 6}\n\n iex> Enum.fetch([2, 4, 6], 4)\n :error\n\n \"\"\"\n @spec fetch(t, index) :: {:ok, element} | :error\n def fetch(enumerable, index) do\n case slice_any(enumerable, index, 1) do\n [value] -> {:ok, value}\n [] -> :error\n end\n end\n\n @doc \"\"\"\n Finds the element at the given `index` (zero-based).\n\n Raises `OutOfBoundsError` if the given `index` is outside the range of\n the enumerable.\n\n Note this operation takes linear time. In order to access the element\n at index `index`, it will need to traverse `index` previous elements.\n\n ## Examples\n\n iex> Enum.fetch!([2, 4, 6], 0)\n 2\n\n iex> Enum.fetch!([2, 4, 6], 2)\n 6\n\n iex> Enum.fetch!([2, 4, 6], 4)\n ** (Enum.OutOfBoundsError) out of bounds error\n\n \"\"\"\n @spec fetch!(t, index) :: element | no_return\n def fetch!(enumerable, index) do\n case slice_any(enumerable, index, 1) do\n [value] -> value\n [] -> raise Enum.OutOfBoundsError\n end\n end\n\n @doc \"\"\"\n Filters the enumerable, i.e. returns only those elements\n for which `fun` returns a truthy value.\n\n See also `reject\/2` which discards all elements where the\n function returns true.\n\n ## Examples\n\n iex> Enum.filter([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)\n [2]\n\n Keep in mind that `filter` is not capable of filtering and\n transforming an element at the same time. If you would like\n to do so, consider using `flat_map\/2`. For example, if you\n want to convert all strings that represent an integer and\n discard the invalid one in one pass:\n\n strings = [\"1234\", \"abc\", \"12ab\"]\n Enum.flat_map(strings, fn string ->\n case Integer.parse(string) do\n {int, _rest} -> [int] # transform to integer\n :error -> [] # skip the value\n end\n end)\n\n \"\"\"\n @spec filter(t, (element -> as_boolean(term))) :: list\n def filter(enumerable, fun) when is_list(enumerable) do\n filter_list(enumerable, fun)\n end\n\n def filter(enumerable, fun) do\n reduce(enumerable, [], R.filter(fun)) |> :lists.reverse()\n end\n\n @doc false\n # TODO: Remove on 2.0\n # (hard-deprecated in elixir_dispatch)\n def filter_map(enumerable, filter, mapper) when is_list(enumerable) do\n for item <- enumerable, filter.(item), do: mapper.(item)\n end\n\n def filter_map(enumerable, filter, mapper) do\n enumerable\n |> reduce([], R.filter_map(filter, mapper))\n |> :lists.reverse()\n end\n\n @doc \"\"\"\n Returns the first item for which `fun` returns a truthy value.\n If no such item is found, returns `default`.\n\n ## Examples\n\n iex> Enum.find([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n nil\n\n iex> Enum.find([2, 4, 6], 0, fn(x) -> rem(x, 2) == 1 end)\n 0\n\n iex> Enum.find([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n 3\n\n \"\"\"\n @spec find(t, default, (element -> any)) :: element | default\n def find(enumerable, default \\\\ nil, fun)\n\n def find(enumerable, default, fun) when is_list(enumerable) do\n find_list(enumerable, default, fun)\n end\n\n def find(enumerable, default, fun) do\n Enumerable.reduce(enumerable, {:cont, default}, fn entry, default ->\n if fun.(entry), do: {:halt, entry}, else: {:cont, default}\n end)\n |> elem(1)\n end\n\n @doc \"\"\"\n Similar to `find\/3`, but returns the index (zero-based)\n of the element instead of the element itself.\n\n ## Examples\n\n iex> Enum.find_index([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n nil\n\n iex> Enum.find_index([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n 1\n\n \"\"\"\n @spec find_index(t, (element -> any)) :: non_neg_integer | nil\n def find_index(enumerable, fun) when is_list(enumerable) do\n find_index_list(enumerable, 0, fun)\n end\n\n def find_index(enumerable, fun) do\n result =\n Enumerable.reduce(enumerable, {:cont, {:not_found, 0}}, fn entry, {_, index} ->\n if fun.(entry), do: {:halt, {:found, index}}, else: {:cont, {:not_found, index + 1}}\n end)\n\n case elem(result, 1) do\n {:found, index} -> index\n {:not_found, _} -> nil\n end\n end\n\n @doc \"\"\"\n Similar to `find\/3`, but returns the value of the function\n invocation instead of the element itself.\n\n ## Examples\n\n iex> Enum.find_value([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n nil\n\n iex> Enum.find_value([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n true\n\n iex> Enum.find_value([1, 2, 3], \"no bools!\", &is_boolean\/1)\n \"no bools!\"\n\n \"\"\"\n @spec find_value(t, any, (element -> any)) :: any | nil\n def find_value(enumerable, default \\\\ nil, fun)\n\n def find_value(enumerable, default, fun) when is_list(enumerable) do\n find_value_list(enumerable, default, fun)\n end\n\n def find_value(enumerable, default, fun) do\n Enumerable.reduce(enumerable, {:cont, default}, fn entry, default ->\n fun_entry = fun.(entry)\n if fun_entry, do: {:halt, fun_entry}, else: {:cont, default}\n end)\n |> elem(1)\n end\n\n @doc \"\"\"\n Maps the given `fun` over `enumerable` and flattens the result.\n\n This function returns a new enumerable built by appending the result of invoking `fun`\n on each element of `enumerable` together; conceptually, this is similar to a\n combination of `map\/2` and `concat\/1`.\n\n ## Examples\n\n iex> Enum.flat_map([:a, :b, :c], fn(x) -> [x, x] end)\n [:a, :a, :b, :b, :c, :c]\n\n iex> Enum.flat_map([{1, 3}, {4, 6}], fn({x, y}) -> x..y end)\n [1, 2, 3, 4, 5, 6]\n\n iex> Enum.flat_map([:a, :b, :c], fn(x) -> [[x]] end)\n [[:a], [:b], [:c]]\n\n \"\"\"\n @spec flat_map(t, (element -> t)) :: list\n def flat_map(enumerable, fun) when is_list(enumerable) do\n flat_map_list(enumerable, fun)\n end\n\n def flat_map(enumerable, fun) do\n reduce(enumerable, [], fn entry, acc ->\n case fun.(entry) do\n list when is_list(list) -> :lists.reverse(list, acc)\n other -> reduce(other, acc, &[&1 | &2])\n end\n end)\n |> :lists.reverse()\n end\n\n @doc \"\"\"\n Maps and reduces an enumerable, flattening the given results (only one level deep).\n\n It expects an accumulator and a function that receives each enumerable\n item, and must return a tuple containing a new enumerable (often a list)\n with the new accumulator or a tuple with `:halt` as first element and\n the accumulator as second.\n\n ## Examples\n\n iex> enum = 1..100\n iex> n = 3\n iex> Enum.flat_map_reduce(enum, 0, fn i, acc ->\n ...> if acc < n, do: {[i], acc + 1}, else: {:halt, acc}\n ...> end)\n {[1, 2, 3], 3}\n\n iex> Enum.flat_map_reduce(1..5, 0, fn(i, acc) -> {[[i]], acc + i} end)\n {[[1], [2], [3], [4], [5]], 15}\n\n \"\"\"\n @spec flat_map_reduce(t, acc, fun) :: {[any], any}\n when fun: (element, acc -> {t, acc} | {:halt, acc}),\n acc: any\n def flat_map_reduce(enumerable, acc, fun) do\n {_, {list, acc}} =\n Enumerable.reduce(enumerable, {:cont, {[], acc}}, fn entry, {list, acc} ->\n case fun.(entry, acc) do\n {:halt, acc} ->\n {:halt, {list, acc}}\n\n {[], acc} ->\n {:cont, {list, acc}}\n\n {[entry], acc} ->\n {:cont, {[entry | list], acc}}\n\n {entries, acc} ->\n {:cont, {reduce(entries, list, &[&1 | &2]), acc}}\n end\n end)\n\n {:lists.reverse(list), acc}\n end\n\n @doc \"\"\"\n Splits the enumerable into groups based on `key_fun`.\n\n The result is a map where each key is given by `key_fun`\n and each value is a list of elements given by `value_fun`.\n The order of elements within each list is preserved from the enumerable.\n However, like all maps, the resulting map is unordered.\n\n ## Examples\n\n iex> Enum.group_by(~w{ant buffalo cat dingo}, &String.length\/1)\n %{3 => [\"ant\", \"cat\"], 5 => [\"dingo\"], 7 => [\"buffalo\"]}\n\n iex> Enum.group_by(~w{ant buffalo cat dingo}, &String.length\/1, &String.first\/1)\n %{3 => [\"a\", \"c\"], 5 => [\"d\"], 7 => [\"b\"]}\n\n \"\"\"\n @spec group_by(t, (element -> any), (element -> any)) :: map\n def group_by(enumerable, key_fun, value_fun \\\\ fn x -> x end)\n\n def group_by(enumerable, key_fun, value_fun) when is_function(key_fun) do\n reduce(reverse(enumerable), %{}, fn entry, categories ->\n value = value_fun.(entry)\n Map.update(categories, key_fun.(entry), [value], &[value | &1])\n end)\n end\n\n # TODO: Remove on 2.0\n def group_by(enumerable, dict, fun) do\n IO.warn(\n \"Enum.group_by\/3 with a map\/dictionary as second element is deprecated. \" <>\n \"A map is used by default and it is no longer required to pass one to this function\"\n )\n\n # Avoid warnings about Dict\n dict_module = Dict\n\n reduce(reverse(enumerable), dict, fn entry, categories ->\n dict_module.update(categories, fun.(entry), [entry], &[entry | &1])\n end)\n end\n\n @doc \"\"\"\n Intersperses `element` between each element of the enumeration.\n\n Complexity: O(n).\n\n ## Examples\n\n iex> Enum.intersperse([1, 2, 3], 0)\n [1, 0, 2, 0, 3]\n\n iex> Enum.intersperse([1], 0)\n [1]\n\n iex> Enum.intersperse([], 0)\n []\n\n \"\"\"\n @spec intersperse(t, element) :: list\n def intersperse(enumerable, element) do\n list =\n reduce(enumerable, [], fn x, acc ->\n [x, element | acc]\n end)\n |> :lists.reverse()\n\n case list do\n [] ->\n []\n\n # Head is a superfluous intersperser element\n [_ | t] ->\n t\n end\n end\n\n @doc \"\"\"\n Inserts the given `enumerable` into a `collectable`.\n\n ## Examples\n\n iex> Enum.into([1, 2], [0])\n [0, 1, 2]\n\n iex> Enum.into([a: 1, b: 2], %{})\n %{a: 1, b: 2}\n\n iex> Enum.into(%{a: 1}, %{b: 2})\n %{a: 1, b: 2}\n\n iex> Enum.into([a: 1, a: 2], %{})\n %{a: 2}\n\n \"\"\"\n @spec into(Enumerable.t(), Collectable.t()) :: Collectable.t()\n def into(enumerable, collectable) when is_list(collectable) do\n collectable ++ to_list(enumerable)\n end\n\n def into(%_{} = enumerable, collectable) do\n into_protocol(enumerable, collectable)\n end\n\n def into(enumerable, %_{} = collectable) do\n into_protocol(enumerable, collectable)\n end\n\n def into(%{} = enumerable, %{} = collectable) do\n Map.merge(collectable, enumerable)\n end\n\n def into(enumerable, %{} = collectable) when is_list(enumerable) do\n Map.merge(collectable, :maps.from_list(enumerable))\n end\n\n def into(enumerable, %{} = collectable) do\n reduce(enumerable, collectable, fn {key, val}, acc ->\n Map.put(acc, key, val)\n end)\n end\n\n def into(enumerable, collectable) do\n into_protocol(enumerable, collectable)\n end\n\n defp into_protocol(enumerable, collectable) do\n {initial, fun} = Collectable.into(collectable)\n\n into(enumerable, initial, fun, fn entry, acc ->\n fun.(acc, {:cont, entry})\n end)\n end\n\n @doc \"\"\"\n Inserts the given `enumerable` into a `collectable` according to the\n transformation function.\n\n ## Examples\n\n iex> Enum.into([2, 3], [3], fn x -> x * 3 end)\n [3, 6, 9]\n\n iex> Enum.into(%{a: 1, b: 2}, %{c: 3}, fn {k, v} -> {k, v * 2} end)\n %{a: 2, b: 4, c: 3}\n\n \"\"\"\n @spec into(Enumerable.t(), Collectable.t(), (term -> term)) :: Collectable.t()\n\n def into(enumerable, collectable, transform) when is_list(collectable) do\n collectable ++ map(enumerable, transform)\n end\n\n def into(enumerable, collectable, transform) do\n {initial, fun} = Collectable.into(collectable)\n\n into(enumerable, initial, fun, fn entry, acc ->\n fun.(acc, {:cont, transform.(entry)})\n end)\n end\n\n defp into(enumerable, initial, fun, callback) do\n try do\n reduce(enumerable, initial, callback)\n catch\n kind, reason ->\n stacktrace = System.stacktrace()\n fun.(initial, :halt)\n :erlang.raise(kind, reason, stacktrace)\n else\n acc -> fun.(acc, :done)\n end\n end\n\n @doc \"\"\"\n Joins the given enumerable into a binary using `joiner` as a\n separator.\n\n If `joiner` is not passed at all, it defaults to the empty binary.\n\n All items in the enumerable must be convertible to a binary,\n otherwise an error is raised.\n\n ## Examples\n\n iex> Enum.join([1, 2, 3])\n \"123\"\n\n iex> Enum.join([1, 2, 3], \" = \")\n \"1 = 2 = 3\"\n\n \"\"\"\n @spec join(t, String.t()) :: String.t()\n def join(enumerable, joiner \\\\ \"\")\n\n def join(enumerable, joiner) when is_binary(joiner) do\n reduced =\n reduce(enumerable, :first, fn\n entry, :first -> entry_to_string(entry)\n entry, acc -> [acc, joiner | entry_to_string(entry)]\n end)\n\n if reduced == :first do\n \"\"\n else\n IO.iodata_to_binary(reduced)\n end\n end\n\n @doc \"\"\"\n Returns a list where each item is the result of invoking\n `fun` on each corresponding item of `enumerable`.\n\n For maps, the function expects a key-value tuple.\n\n ## Examples\n\n iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end)\n [2, 4, 6]\n\n iex> Enum.map([a: 1, b: 2], fn({k, v}) -> {k, -v} end)\n [a: -1, b: -2]\n\n \"\"\"\n @spec map(t, (element -> any)) :: list\n def map(enumerable, fun)\n\n def map(enumerable, fun) when is_list(enumerable) do\n :lists.map(fun, enumerable)\n end\n\n def map(enumerable, fun) do\n reduce(enumerable, [], R.map(fun)) |> :lists.reverse()\n end\n\n @doc \"\"\"\n Returns a list of results of invoking `fun` on every `nth`\n item of `enumerable`, starting with the first element.\n\n The first item is always passed to the given function, unless `nth` is `0`.\n\n The second argument specifying every `nth` item must be a non-negative\n integer.\n\n If `nth` is `0`, then `enumerable` is directly converted to a list,\n without `fun` being ever applied.\n\n ## Examples\n\n iex> Enum.map_every(1..10, 2, fn x -> x + 1000 end)\n [1001, 2, 1003, 4, 1005, 6, 1007, 8, 1009, 10]\n\n iex> Enum.map_every(1..10, 3, fn x -> x + 1000 end)\n [1001, 2, 3, 1004, 5, 6, 1007, 8, 9, 1010]\n\n iex> Enum.map_every(1..5, 0, fn x -> x + 1000 end)\n [1, 2, 3, 4, 5]\n\n iex> Enum.map_every([1, 2, 3], 1, fn x -> x + 1000 end)\n [1001, 1002, 1003]\n\n \"\"\"\n @spec map_every(t, non_neg_integer, (element -> any)) :: list\n def map_every(enumerable, nth, fun)\n\n def map_every(enumerable, 1, fun), do: map(enumerable, fun)\n def map_every(enumerable, 0, _fun), do: to_list(enumerable)\n def map_every([], nth, _fun) when is_integer(nth) and nth > 1, do: []\n\n def map_every(enumerable, nth, fun) when is_integer(nth) and nth > 1 do\n {res, _} = reduce(enumerable, {[], :first}, R.map_every(nth, fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Maps and joins the given enumerable in one pass.\n\n `joiner` can be either a binary or a list and the result will be of\n the same type as `joiner`.\n If `joiner` is not passed at all, it defaults to an empty binary.\n\n All items returned from invoking the `mapper` must be convertible to\n a binary, otherwise an error is raised.\n\n ## Examples\n\n iex> Enum.map_join([1, 2, 3], &(&1 * 2))\n \"246\"\n\n iex> Enum.map_join([1, 2, 3], \" = \", &(&1 * 2))\n \"2 = 4 = 6\"\n\n \"\"\"\n @spec map_join(t, String.t(), (element -> String.Chars.t())) :: String.t()\n def map_join(enumerable, joiner \\\\ \"\", mapper)\n\n def map_join(enumerable, joiner, mapper) when is_binary(joiner) do\n reduced =\n reduce(enumerable, :first, fn\n entry, :first -> entry_to_string(mapper.(entry))\n entry, acc -> [acc, joiner | entry_to_string(mapper.(entry))]\n end)\n\n if reduced == :first do\n \"\"\n else\n IO.iodata_to_binary(reduced)\n end\n end\n\n @doc \"\"\"\n Invokes the given function to each item in the enumerable to reduce\n it to a single element, while keeping an accumulator.\n\n Returns a tuple where the first element is the mapped enumerable and\n the second one is the final accumulator.\n\n The function, `fun`, receives two arguments: the first one is the\n element, and the second one is the accumulator. `fun` must return\n a tuple with two elements in the form of `{result, accumulator}`.\n\n For maps, the first tuple element must be a `{key, value}` tuple.\n\n ## Examples\n\n iex> Enum.map_reduce([1, 2, 3], 0, fn(x, acc) -> {x * 2, x + acc} end)\n {[2, 4, 6], 6}\n\n \"\"\"\n @spec map_reduce(t, any, (element, any -> {any, any})) :: {any, any}\n def map_reduce(enumerable, acc, fun) when is_list(enumerable) do\n :lists.mapfoldl(fun, acc, enumerable)\n end\n\n def map_reduce(enumerable, acc, fun) do\n {list, acc} =\n reduce(enumerable, {[], acc}, fn entry, {list, acc} ->\n {new_entry, acc} = fun.(entry, acc)\n {[new_entry | list], acc}\n end)\n\n {:lists.reverse(list), acc}\n end\n\n @doc \"\"\"\n Returns the maximal element in the enumerable according\n to Erlang's term ordering.\n\n If multiple elements are considered maximal, the first one that was found\n is returned.\n\n Calls the provided `empty_fallback` function and returns its value if\n `enumerable` is empty. The default `empty_fallback` raises `Enum.EmptyError`.\n\n ## Examples\n\n iex> Enum.max([1, 2, 3])\n 3\n\n iex> Enum.max([], fn -> 0 end)\n 0\n\n The fact this function uses Erlang's term ordering means that the comparison\n is structural and not semantic. For example:\n\n iex> Enum.max([~D[2017-03-31], ~D[2017-04-01]])\n ~D[2017-03-31]\n\n In the example above, `max\/1` returned March 31st instead of April 1st\n because the structural comparison compares the day before the year. This\n can be addressed by using `max_by\/1` and by relying on structures where\n the most significant digits come first. In this particular case, we can\n use `Date.to_erl\/1` to get a tuple representation with year, month and day\n fields:\n\n iex> Enum.max_by([~D[2017-03-31], ~D[2017-04-01]], &Date.to_erl\/1)\n ~D[2017-04-01]\n\n \"\"\"\n @spec max(t, (() -> empty_result)) :: element | empty_result | no_return when empty_result: any\n def max(enumerable, empty_fallback \\\\ fn -> raise Enum.EmptyError end) do\n aggregate(enumerable, &Kernel.max\/2, empty_fallback)\n end\n\n @doc \"\"\"\n Returns the maximal element in the enumerable as calculated\n by the given function.\n\n If multiple elements are considered maximal, the first one that was found\n is returned.\n\n Calls the provided `empty_fallback` function and returns its value if\n `enumerable` is empty. The default `empty_fallback` raises `Enum.EmptyError`.\n\n ## Examples\n\n iex> Enum.max_by([\"a\", \"aa\", \"aaa\"], fn(x) -> String.length(x) end)\n \"aaa\"\n\n iex> Enum.max_by([\"a\", \"aa\", \"aaa\", \"b\", \"bbb\"], &String.length\/1)\n \"aaa\"\n\n iex> Enum.max_by([], &String.length\/1, fn -> nil end)\n nil\n\n \"\"\"\n @spec max_by(t, (element -> any), (() -> empty_result)) :: element | empty_result | no_return\n when empty_result: any\n def max_by(enumerable, fun, empty_fallback \\\\ fn -> raise Enum.EmptyError end) do\n first_fun = &{&1, fun.(&1)}\n\n reduce_fun = fn entry, {_, fun_max} = old ->\n fun_entry = fun.(entry)\n if(fun_entry > fun_max, do: {entry, fun_entry}, else: old)\n end\n\n case reduce_by(enumerable, first_fun, reduce_fun) do\n :empty -> empty_fallback.()\n {entry, _} -> entry\n end\n end\n\n @doc \"\"\"\n Checks if `element` exists within the enumerable.\n\n Membership is tested with the match (`===`) operator.\n\n ## Examples\n\n iex> Enum.member?(1..10, 5)\n true\n iex> Enum.member?(1..10, 5.0)\n false\n\n iex> Enum.member?([1.0, 2.0, 3.0], 2)\n false\n iex> Enum.member?([1.0, 2.0, 3.0], 2.000)\n true\n\n iex> Enum.member?([:a, :b, :c], :d)\n false\n\n \"\"\"\n @spec member?(t, element) :: boolean\n def member?(enumerable, element) when is_list(enumerable) do\n :lists.member(element, enumerable)\n end\n\n def member?(enumerable, element) do\n case Enumerable.member?(enumerable, element) do\n {:ok, element} when is_boolean(element) ->\n element\n\n {:error, module} ->\n module.reduce(enumerable, {:cont, false}, fn\n v, _ when v === element -> {:halt, true}\n _, _ -> {:cont, false}\n end)\n |> elem(1)\n end\n end\n\n @doc \"\"\"\n Returns the minimal element in the enumerable according\n to Erlang's term ordering.\n\n If multiple elements are considered minimal, the first one that was found\n is returned.\n\n Calls the provided `empty_fallback` function and returns its value if\n `enumerable` is empty. The default `empty_fallback` raises `Enum.EmptyError`.\n\n ## Examples\n\n iex> Enum.min([1, 2, 3])\n 1\n\n iex> Enum.min([], fn -> 0 end)\n 0\n\n The fact this function uses Erlang's term ordering means that the comparison\n is structural and not semantic. For example:\n\n iex> Enum.min([~D[2017-03-31], ~D[2017-04-01]])\n ~D[2017-04-01]\n\n In the example above, `min\/1` returned April 1st instead of March 31st\n because the structural comparison compares the day before the year. This\n can be addressed by using `min_by\/1` and by relying on structures where\n the most significant digits come first. In this particular case, we can\n use `Date.to_erl\/1` to get a tuple representation with year, month and day\n fields:\n\n iex> Enum.min_by([~D[2017-03-31], ~D[2017-04-01]], &Date.to_erl\/1)\n ~D[2017-03-31]\n\n \"\"\"\n @spec min(t, (() -> empty_result)) :: element | empty_result | no_return when empty_result: any\n def min(enumerable, empty_fallback \\\\ fn -> raise Enum.EmptyError end) do\n aggregate(enumerable, &Kernel.min\/2, empty_fallback)\n end\n\n @doc \"\"\"\n Returns the minimal element in the enumerable as calculated\n by the given function.\n\n If multiple elements are considered minimal, the first one that was found\n is returned.\n\n Calls the provided `empty_fallback` function and returns its value if\n `enumerable` is empty. The default `empty_fallback` raises `Enum.EmptyError`.\n\n ## Examples\n\n iex> Enum.min_by([\"a\", \"aa\", \"aaa\"], fn(x) -> String.length(x) end)\n \"a\"\n\n iex> Enum.min_by([\"a\", \"aa\", \"aaa\", \"b\", \"bbb\"], &String.length\/1)\n \"a\"\n\n iex> Enum.min_by([], &String.length\/1, fn -> nil end)\n nil\n\n \"\"\"\n @spec min_by(t, (element -> any), (() -> empty_result)) :: element | empty_result | no_return\n when empty_result: any\n def min_by(enumerable, fun, empty_fallback \\\\ fn -> raise Enum.EmptyError end) do\n first_fun = &{&1, fun.(&1)}\n\n reduce_fun = fn entry, {_, fun_min} = old ->\n fun_entry = fun.(entry)\n if(fun_entry < fun_min, do: {entry, fun_entry}, else: old)\n end\n\n case reduce_by(enumerable, first_fun, reduce_fun) do\n :empty -> empty_fallback.()\n {entry, _} -> entry\n end\n end\n\n @doc \"\"\"\n Returns a tuple with the minimal and the maximal elements in the\n enumerable according to Erlang's term ordering.\n\n If multiple elements are considered maximal or minimal, the first one\n that was found is returned.\n\n Calls the provided `empty_fallback` function and returns its value if\n `enumerable` is empty. The default `empty_fallback` raises `Enum.EmptyError`.\n\n ## Examples\n\n iex> Enum.min_max([2, 3, 1])\n {1, 3}\n\n iex> Enum.min_max([], fn -> {nil, nil} end)\n {nil, nil}\n\n \"\"\"\n @spec min_max(t, (() -> empty_result)) :: {element, element} | empty_result | no_return\n when empty_result: any\n def min_max(enumerable, empty_fallback \\\\ fn -> raise Enum.EmptyError end)\n\n def min_max(left..right, _empty_fallback) do\n {Kernel.min(left, right), Kernel.max(left, right)}\n end\n\n def min_max(enumerable, empty_fallback) do\n first_fun = &{&1, &1}\n\n reduce_fun = fn entry, {min, max} ->\n {Kernel.min(entry, min), Kernel.max(entry, max)}\n end\n\n case reduce_by(enumerable, first_fun, reduce_fun) do\n :empty -> empty_fallback.()\n entry -> entry\n end\n end\n\n @doc \"\"\"\n Returns a tuple with the minimal and the maximal elements in the\n enumerable as calculated by the given function.\n\n If multiple elements are considered maximal or minimal, the first one\n that was found is returned.\n\n Calls the provided `empty_fallback` function and returns its value if\n `enumerable` is empty. The default `empty_fallback` raises `Enum.EmptyError`.\n\n ## Examples\n\n iex> Enum.min_max_by([\"aaa\", \"bb\", \"c\"], fn(x) -> String.length(x) end)\n {\"c\", \"aaa\"}\n\n iex> Enum.min_max_by([\"aaa\", \"a\", \"bb\", \"c\", \"ccc\"], &String.length\/1)\n {\"a\", \"aaa\"}\n\n iex> Enum.min_max_by([], &String.length\/1, fn -> {nil, nil} end)\n {nil, nil}\n\n \"\"\"\n @spec min_max_by(t, (element -> any), (() -> empty_result)) ::\n {element, element} | empty_result | no_return\n when empty_result: any\n def min_max_by(enumerable, fun, empty_fallback \\\\ fn -> raise Enum.EmptyError end)\n\n def min_max_by(enumerable, fun, empty_fallback) do\n first_fun = fn entry ->\n fun_entry = fun.(entry)\n {{entry, entry}, {fun_entry, fun_entry}}\n end\n\n reduce_fun = fn entry, {{prev_min, prev_max}, {fun_min, fun_max}} = acc ->\n fun_entry = fun.(entry)\n\n cond do\n fun_entry < fun_min ->\n {{entry, prev_max}, {fun_entry, fun_max}}\n\n fun_entry > fun_max ->\n {{prev_min, entry}, {fun_min, fun_entry}}\n\n true ->\n acc\n end\n end\n\n case reduce_by(enumerable, first_fun, reduce_fun) do\n :empty -> empty_fallback.()\n {entry, _} -> entry\n end\n end\n\n @doc \"\"\"\n Splits the `enumerable` in two lists according to the given function `fun`.\n\n Splits the given `enumerable` in two lists by calling `fun` with each element\n in the `enumerable` as its only argument. Returns a tuple with the first list\n containing all the elements in `enumerable` for which applying `fun` returned\n a truthy value, and a second list with all the elements for which applying\n `fun` returned a falsy value (`false` or `nil`).\n\n The elements in both the returned lists are in the same relative order as they\n were in the original enumerable (if such enumerable was ordered, e.g., a\n list); see the examples below.\n\n ## Examples\n\n iex> Enum.split_with([5, 4, 3, 2, 1, 0], fn(x) -> rem(x, 2) == 0 end)\n {[4, 2, 0], [5, 3, 1]}\n\n iex> Enum.split_with(%{a: 1, b: -2, c: 1, d: -3}, fn({_k, v}) -> v < 0 end)\n {[b: -2, d: -3], [a: 1, c: 1]}\n\n iex> Enum.split_with(%{a: 1, b: -2, c: 1, d: -3}, fn({_k, v}) -> v > 50 end)\n {[], [a: 1, b: -2, c: 1, d: -3]}\n\n iex> Enum.split_with(%{}, fn({_k, v}) -> v > 50 end)\n {[], []}\n\n \"\"\"\n @spec split_with(t, (element -> any)) :: {list, list}\n def split_with(enumerable, fun) do\n {acc1, acc2} =\n reduce(enumerable, {[], []}, fn entry, {acc1, acc2} ->\n if fun.(entry) do\n {[entry | acc1], acc2}\n else\n {acc1, [entry | acc2]}\n end\n end)\n\n {:lists.reverse(acc1), :lists.reverse(acc2)}\n end\n\n @doc false\n # TODO: Remove on 2.0\n # (hard-deprecated in elixir_dispatch)\n def partition(enumerable, fun) do\n split_with(enumerable, fun)\n end\n\n @doc \"\"\"\n Returns a random element of an enumerable.\n\n Raises `Enum.EmptyError` if `enumerable` is empty.\n\n This function uses Erlang's [`:rand` module](http:\/\/www.erlang.org\/doc\/man\/rand.html) to calculate\n the random value. Check its documentation for setting a\n different random algorithm or a different seed.\n\n The implementation is based on the\n [reservoir sampling](https:\/\/en.wikipedia.org\/wiki\/Reservoir_sampling#Relation_to_Fisher-Yates_shuffle)\n algorithm.\n It assumes that the sample being returned can fit into memory;\n the input `enumerable` doesn't have to, as it is traversed just once.\n\n If a range is passed into the function, this function will pick a\n random value between the range limits, without traversing the whole\n range (thus executing in constant time and constant memory).\n\n ## Examples\n\n # Although not necessary, let's seed the random algorithm\n iex> :rand.seed(:exsplus, {101, 102, 103})\n iex> Enum.random([1, 2, 3])\n 2\n iex> Enum.random([1, 2, 3])\n 1\n iex> Enum.random(1..1_000)\n 776\n\n \"\"\"\n @spec random(t) :: element | no_return\n def random(enumerable)\n\n def random(enumerable) when is_list(enumerable) do\n case take_random(enumerable, 1) do\n [] -> raise Enum.EmptyError\n [elem] -> elem\n end\n end\n\n def random(enumerable) do\n result =\n case Enumerable.slice(enumerable) do\n {:ok, 0, _} ->\n []\n\n {:ok, count, fun} when is_function(fun) ->\n fun.(random_integer(0, count - 1), 1)\n\n {:error, _} ->\n take_random(enumerable, 1)\n end\n\n case result do\n [] -> raise Enum.EmptyError\n [elem] -> elem\n end\n end\n\n @doc \"\"\"\n Invokes `fun` for each element in the `enumerable` with the\n accumulator.\n\n The first element of the enumerable is used as the initial value\n of the accumulator. Then the function is invoked with the next\n element and the accumulator. The result returned by the function\n is used as the accumulator for the next iteration, recursively.\n When the enumerable is done, the last accumulator is returned.\n\n Since the first element of the enumerable is used as the initial\n value of the accumulator, `fun` will only be executed `n - 1` times\n where `n` is the length of the enumerable. This function won't call\n the specified function for enumerables that are one-element long.\n\n If you wish to use another value for the accumulator, use\n `Enum.reduce\/3`.\n\n ## Examples\n\n iex> Enum.reduce([1, 2, 3, 4], fn(x, acc) -> x * acc end)\n 24\n\n \"\"\"\n @spec reduce(t, (element, any -> any)) :: any\n def reduce(enumerable, fun)\n\n def reduce([h | t], fun) do\n reduce(t, h, fun)\n end\n\n def reduce([], _fun) do\n raise Enum.EmptyError\n end\n\n def reduce(enumerable, fun) do\n result =\n Enumerable.reduce(enumerable, {:cont, :first}, fn\n x, :first ->\n {:cont, {:acc, x}}\n\n x, {:acc, acc} ->\n {:cont, {:acc, fun.(x, acc)}}\n end)\n |> elem(1)\n\n case result do\n :first -> raise Enum.EmptyError\n {:acc, acc} -> acc\n end\n end\n\n @doc \"\"\"\n Invokes `fun` for each element in the `enumerable` with the accumulator.\n\n The initial value of the accumulator is `acc`. The function is invoked for\n each element in the enumerable with the accumulator. The result returned\n by the function is used as the accumulator for the next iteration.\n The function returns the last accumulator.\n\n ## Examples\n\n iex> Enum.reduce([1, 2, 3], 0, fn(x, acc) -> x + acc end)\n 6\n\n ## Reduce as a building block\n\n Reduce (sometimes called `fold`) is a basic building block in functional\n programming. Almost all of the functions in the `Enum` module can be\n implemented on top of reduce. Those functions often rely on other operations,\n such as `Enum.reverse\/1`, which are optimized by the runtime.\n\n For example, we could implement `map\/2` in terms of `reduce\/3` as follows:\n\n def my_map(enumerable, fun) do\n enumerable\n |> Enum.reduce([], fn(x, acc) -> [fun.(x) | acc] end)\n |> Enum.reverse\n end\n\n In the example above, `Enum.reduce\/3` accumulates the result of each call\n to `fun` into a list in reverse order, which is correctly ordered at the\n end by calling `Enum.reverse\/1`.\n\n Implementing functions like `map\/2`, `filter\/2` and others are a good\n exercise for understanding the power behind `Enum.reduce\/3`. When an\n operation cannot be expressed by any of the functions in the `Enum`\n module, developers will most likely resort to `reduce\/3`.\n \"\"\"\n @spec reduce(t, any, (element, any -> any)) :: any\n def reduce(enumerable, acc, fun) when is_list(enumerable) do\n :lists.foldl(fun, acc, enumerable)\n end\n\n def reduce(first..last, acc, fun) do\n if first <= last do\n reduce_range_inc(first, last, acc, fun)\n else\n reduce_range_dec(first, last, acc, fun)\n end\n end\n\n def reduce(%_{} = enumerable, acc, fun) do\n Enumerable.reduce(enumerable, {:cont, acc}, fn x, acc -> {:cont, fun.(x, acc)} end) |> elem(1)\n end\n\n def reduce(%{} = enumerable, acc, fun) do\n :maps.fold(fn k, v, acc -> fun.({k, v}, acc) end, acc, enumerable)\n end\n\n def reduce(enumerable, acc, fun) do\n Enumerable.reduce(enumerable, {:cont, acc}, fn x, acc -> {:cont, fun.(x, acc)} end) |> elem(1)\n end\n\n @doc \"\"\"\n Reduces the enumerable until `fun` returns `{:halt, term}`.\n\n The return value for `fun` is expected to be\n\n * `{:cont, acc}` to continue the reduction with `acc` as the new\n accumulator or\n * `{:halt, acc}` to halt the reduction and return `acc` as the return\n value of this function\n\n ## Examples\n\n iex> Enum.reduce_while(1..100, 0, fn i, acc ->\n ...> if i < 3, do: {:cont, acc + i}, else: {:halt, acc}\n ...> end)\n 3\n\n \"\"\"\n @spec reduce_while(t, any, (element, any -> {:cont, any} | {:halt, any})) :: any\n def reduce_while(enumerable, acc, fun) do\n Enumerable.reduce(enumerable, {:cont, acc}, fun) |> elem(1)\n end\n\n @doc \"\"\"\n Returns elements of `enumerable` for which the function `fun` returns\n `false` or `nil`.\n\n See also `filter\/2`.\n\n ## Examples\n\n iex> Enum.reject([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)\n [1, 3]\n\n \"\"\"\n @spec reject(t, (element -> as_boolean(term))) :: list\n def reject(enumerable, fun) when is_list(enumerable) do\n reject_list(enumerable, fun)\n end\n\n def reject(enumerable, fun) do\n reduce(enumerable, [], R.reject(fun)) |> :lists.reverse()\n end\n\n @doc \"\"\"\n Returns a list of elements in `enumerable` in reverse order.\n\n ## Examples\n\n iex> Enum.reverse([1, 2, 3])\n [3, 2, 1]\n\n \"\"\"\n @spec reverse(t) :: list\n def reverse(enumerable)\n\n def reverse([]), do: []\n def reverse([_] = list), do: list\n def reverse([item1, item2]), do: [item2, item1]\n def reverse([item1, item2 | rest]), do: :lists.reverse(rest, [item2, item1])\n def reverse(enumerable), do: reduce(enumerable, [], &[&1 | &2])\n\n @doc \"\"\"\n Reverses the elements in `enumerable`, appends the tail, and returns\n it as a list.\n\n This is an optimization for\n `Enum.concat(Enum.reverse(enumerable), tail)`.\n\n ## Examples\n\n iex> Enum.reverse([1, 2, 3], [4, 5, 6])\n [3, 2, 1, 4, 5, 6]\n\n \"\"\"\n @spec reverse(t, t) :: list\n def reverse(enumerable, tail) when is_list(enumerable) do\n :lists.reverse(enumerable, to_list(tail))\n end\n\n def reverse(enumerable, tail) do\n reduce(enumerable, to_list(tail), fn entry, acc ->\n [entry | acc]\n end)\n end\n\n @doc \"\"\"\n Reverses the enumerable in the range from initial position `start`\n through `count` elements.\n\n If `count` is greater than the size of the rest of the enumerable,\n then this function will reverse the rest of the enumerable.\n\n ## Examples\n\n iex> Enum.reverse_slice([1, 2, 3, 4, 5, 6], 2, 4)\n [1, 2, 6, 5, 4, 3]\n\n \"\"\"\n @spec reverse_slice(t, non_neg_integer, non_neg_integer) :: list\n def reverse_slice(enumerable, start, count)\n when is_integer(start) and start >= 0 and is_integer(count) and count >= 0 do\n list = reverse(enumerable)\n length = length(list)\n count = Kernel.min(count, length - start)\n\n if count > 0 do\n reverse_slice(list, length, start + count, count, [])\n else\n :lists.reverse(list)\n end\n end\n\n @doc \"\"\"\n Applies the given function to each element in the enumerable,\n storing the result in a list and passing it as the accumulator\n for the next computation. Uses the first element in the enumerable\n as the starting value.\n\n ## Examples\n\n iex> Enum.scan(1..5, &(&1 + &2))\n [1, 3, 6, 10, 15]\n\n \"\"\"\n @spec scan(t, (element, any -> any)) :: list\n def scan(enumerable, fun) do\n {res, _} = reduce(enumerable, {[], :first}, R.scan2(fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Applies the given function to each element in the enumerable,\n storing the result in a list and passing it as the accumulator\n for the next computation. Uses the given `acc` as the starting value.\n\n ## Examples\n\n iex> Enum.scan(1..5, 0, &(&1 + &2))\n [1, 3, 6, 10, 15]\n\n \"\"\"\n @spec scan(t, any, (element, any -> any)) :: list\n def scan(enumerable, acc, fun) do\n {res, _} = reduce(enumerable, {[], acc}, R.scan3(fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Returns a list with the elements of `enumerable` shuffled.\n\n This function uses Erlang's [`:rand` module](http:\/\/www.erlang.org\/doc\/man\/rand.html) to calculate\n the random value. Check its documentation for setting a\n different random algorithm or a different seed.\n\n ## Examples\n\n # Although not necessary, let's seed the random algorithm\n iex> :rand.seed(:exsplus, {1, 2, 3})\n iex> Enum.shuffle([1, 2, 3])\n [2, 1, 3]\n iex> Enum.shuffle([1, 2, 3])\n [2, 3, 1]\n\n \"\"\"\n @spec shuffle(t) :: list\n def shuffle(enumerable) do\n randomized =\n reduce(enumerable, [], fn x, acc ->\n [{:rand.uniform(), x} | acc]\n end)\n\n shuffle_unwrap(:lists.keysort(1, randomized), [])\n end\n\n @doc \"\"\"\n Returns a subset list of the given enumerable, from `range.first` to `range.last` positions.\n\n Given `enumerable`, it drops elements until element position `range.first`,\n then takes elements until element position `range.last` (inclusive).\n\n Positions are normalized, meaning that negative positions will be counted from the end\n (e.g. `-1` means the last element of the enumerable).\n If `range.last` is out of bounds, then it is assigned as the position of the last element.\n\n If the normalized `range.first` position is out of bounds of the given enumerable,\n or this one is greater than the normalized `range.last` position, then `[]` is returned.\n\n ## Examples\n\n iex> Enum.slice(1..100, 5..10)\n [6, 7, 8, 9, 10, 11]\n\n iex> Enum.slice(1..10, 5..20)\n [6, 7, 8, 9, 10]\n\n # last five elements (negative positions)\n iex> Enum.slice(1..30, -5..-1)\n [26, 27, 28, 29, 30]\n\n # last five elements (mixed positive and negative positions)\n iex> Enum.slice(1..30, 25..-1)\n [26, 27, 28, 29, 30]\n\n # out of bounds\n iex> Enum.slice(1..10, 11..20)\n []\n\n # range.first is greater than range.last\n iex> Enum.slice(1..10, 6..5)\n []\n\n \"\"\"\n @spec slice(t, Range.t()) :: list\n def slice(enumerable, first..last) do\n {count, fun} = slice_count_and_fun(enumerable)\n corr_first = if first >= 0, do: first, else: first + count\n corr_last = if last >= 0, do: last, else: last + count\n amount = corr_last - corr_first + 1\n\n if corr_first >= 0 and corr_first < count and amount > 0 do\n fun.(corr_first, Kernel.min(amount, count - corr_first))\n else\n []\n end\n end\n\n @doc \"\"\"\n Returns a subset list of the given enumerable, from `start` position with `amount` of elements if available.\n\n Given `enumerable`, it drops elements until element position `start`,\n then takes `amount` of elements until the end of the enumerable.\n\n If `start` is out of bounds, it returns `[]`.\n\n If `amount` is greater than `enumerable` length, it returns as many elements as possible.\n If `amount` is zero, then `[]` is returned.\n\n ## Examples\n\n iex> Enum.slice(1..100, 5, 10)\n [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n\n # amount to take is greater than the number of elements\n iex> Enum.slice(1..10, 5, 100)\n [6, 7, 8, 9, 10]\n\n iex> Enum.slice(1..10, 5, 0)\n []\n\n # out of bound start position\n iex> Enum.slice(1..10, 10, 5)\n []\n\n # out of bound start position (negative)\n iex> Enum.slice(1..10, -11, 5)\n []\n\n \"\"\"\n @spec slice(t, index, non_neg_integer) :: list\n def slice(_enumerable, start, 0) when is_integer(start), do: []\n\n def slice(enumerable, start, amount)\n when is_integer(start) and is_integer(amount) and amount >= 0 do\n slice_any(enumerable, start, amount)\n end\n\n @doc \"\"\"\n Sorts the enumerable according to Erlang's term ordering.\n\n Uses the merge sort algorithm.\n\n ## Examples\n\n iex> Enum.sort([3, 2, 1])\n [1, 2, 3]\n\n \"\"\"\n @spec sort(t) :: list\n def sort(enumerable) when is_list(enumerable) do\n :lists.sort(enumerable)\n end\n\n def sort(enumerable) do\n sort(enumerable, &(&1 <= &2))\n end\n\n @doc \"\"\"\n Sorts the enumerable by the given function.\n\n This function uses the merge sort algorithm. The given function should compare\n two arguments, and return `true` if the first argument precedes the second one.\n\n ## Examples\n\n iex> Enum.sort([1, 2, 3], &(&1 >= &2))\n [3, 2, 1]\n\n The sorting algorithm will be stable as long as the given function\n returns `true` for values considered equal:\n\n iex> Enum.sort [\"some\", \"kind\", \"of\", \"monster\"], &(byte_size(&1) <= byte_size(&2))\n [\"of\", \"some\", \"kind\", \"monster\"]\n\n If the function does not return `true` for equal values, the sorting\n is not stable and the order of equal terms may be shuffled.\n For example:\n\n iex> Enum.sort [\"some\", \"kind\", \"of\", \"monster\"], &(byte_size(&1) < byte_size(&2))\n [\"of\", \"kind\", \"some\", \"monster\"]\n\n \"\"\"\n @spec sort(t, (element, element -> boolean)) :: list\n def sort(enumerable, fun) when is_list(enumerable) do\n :lists.sort(fun, enumerable)\n end\n\n def sort(enumerable, fun) do\n reduce(enumerable, [], &sort_reducer(&1, &2, fun))\n |> sort_terminator(fun)\n end\n\n @doc \"\"\"\n Sorts the mapped results of the enumerable according to the provided `sorter`\n function.\n\n This function maps each element of the enumerable using the provided `mapper`\n function. The enumerable is then sorted by the mapped elements\n using the `sorter` function, which defaults to `Kernel.<=\/2`.\n\n `sort_by\/3` differs from `sort\/2` in that it only calculates the\n comparison value for each element in the enumerable once instead of\n once for each element in each comparison.\n If the same function is being called on both elements, it's also more\n compact to use `sort_by\/3`.\n\n ## Examples\n\n Using the default `sorter` of `<=\/2`:\n\n iex> Enum.sort_by([\"some\", \"kind\", \"of\", \"monster\"], &byte_size\/1)\n [\"of\", \"some\", \"kind\", \"monster\"]\n\n Using a custom `sorter` to override the order:\n\n iex> Enum.sort_by([\"some\", \"kind\", \"of\", \"monster\"], &byte_size\/1, &>=\/2)\n [\"monster\", \"some\", \"kind\", \"of\"]\n\n Sorting by multiple properties - first by size, then by first letter\n (this takes advantage of the fact that tuples are compared element-by-element):\n\n iex> Enum.sort_by([\"some\", \"kind\", \"of\", \"monster\"], &{byte_size(&1), String.first(&1)})\n [\"of\", \"kind\", \"some\", \"monster\"]\n\n \"\"\"\n @spec sort_by(t, (element -> mapped_element), (mapped_element, mapped_element -> boolean)) ::\n list\n when mapped_element: element\n\n def sort_by(enumerable, mapper, sorter \\\\ &<=\/2) do\n enumerable\n |> map(&{&1, mapper.(&1)})\n |> sort(&sorter.(elem(&1, 1), elem(&2, 1)))\n |> map(&elem(&1, 0))\n end\n\n @doc \"\"\"\n Splits the `enumerable` into two enumerables, leaving `count`\n elements in the first one.\n\n If `count` is a negative number, it starts counting from the\n back to the beginning of the enumerable.\n\n Be aware that a negative `count` implies the `enumerable`\n will be enumerated twice: once to calculate the position, and\n a second time to do the actual splitting.\n\n ## Examples\n\n iex> Enum.split([1, 2, 3], 2)\n {[1, 2], [3]}\n\n iex> Enum.split([1, 2, 3], 10)\n {[1, 2, 3], []}\n\n iex> Enum.split([1, 2, 3], 0)\n {[], [1, 2, 3]}\n\n iex> Enum.split([1, 2, 3], -1)\n {[1, 2], [3]}\n\n iex> Enum.split([1, 2, 3], -5)\n {[], [1, 2, 3]}\n\n \"\"\"\n @spec split(t, integer) :: {list, list}\n def split(enumerable, count) when is_list(enumerable) and count >= 0 do\n split_list(enumerable, count, [])\n end\n\n def split(enumerable, count) when count >= 0 do\n {_, list1, list2} =\n reduce(enumerable, {count, [], []}, fn entry, {counter, acc1, acc2} ->\n if counter > 0 do\n {counter - 1, [entry | acc1], acc2}\n else\n {counter, acc1, [entry | acc2]}\n end\n end)\n\n {:lists.reverse(list1), :lists.reverse(list2)}\n end\n\n def split(enumerable, count) when count < 0 do\n split_reverse_list(reverse(enumerable), -count, [])\n end\n\n @doc \"\"\"\n Splits enumerable in two at the position of the element for which\n `fun` returns `false` for the first time.\n\n ## Examples\n\n iex> Enum.split_while([1, 2, 3, 4], fn(x) -> x < 3 end)\n {[1, 2], [3, 4]}\n\n \"\"\"\n @spec split_while(t, (element -> as_boolean(term))) :: {list, list}\n def split_while(enumerable, fun) when is_list(enumerable) do\n split_while_list(enumerable, fun, [])\n end\n\n def split_while(enumerable, fun) do\n {list1, list2} =\n reduce(enumerable, {[], []}, fn\n entry, {acc1, []} ->\n if(fun.(entry), do: {[entry | acc1], []}, else: {acc1, [entry]})\n\n entry, {acc1, acc2} ->\n {acc1, [entry | acc2]}\n end)\n\n {:lists.reverse(list1), :lists.reverse(list2)}\n end\n\n @doc \"\"\"\n Returns the sum of all elements.\n\n Raises `ArithmeticError` if `enumerable` contains a non-numeric value.\n\n ## Examples\n\n iex> Enum.sum([1, 2, 3])\n 6\n\n \"\"\"\n @spec sum(t) :: number\n def sum(enumerable)\n\n def sum(first..last) do\n div((last + first) * (abs(last - first) + 1), 2)\n end\n\n def sum(enumerable) do\n reduce(enumerable, 0, &+\/2)\n end\n\n @doc \"\"\"\n Takes the first `amount` items from the enumerable.\n\n If a negative `amount` is given, the `amount` of last values will be taken.\n The `enumerable` will be enumerated once to retrieve the proper index and\n the remaining calculation is performed from the end.\n\n ## Examples\n\n iex> Enum.take([1, 2, 3], 2)\n [1, 2]\n\n iex> Enum.take([1, 2, 3], 10)\n [1, 2, 3]\n\n iex> Enum.take([1, 2, 3], 0)\n []\n\n iex> Enum.take([1, 2, 3], -1)\n [3]\n\n \"\"\"\n @spec take(t, integer) :: list\n def take(enumerable, amount)\n\n def take(_enumerable, 0), do: []\n\n def take(enumerable, amount)\n when is_list(enumerable) and is_integer(amount) and amount > 0 do\n take_list(enumerable, amount)\n end\n\n def take(enumerable, amount) when is_integer(amount) and amount > 0 do\n {_, {res, _}} =\n Enumerable.reduce(enumerable, {:cont, {[], amount}}, fn entry, {list, n} ->\n case n do\n 1 -> {:halt, {[entry | list], n - 1}}\n _ -> {:cont, {[entry | list], n - 1}}\n end\n end)\n\n :lists.reverse(res)\n end\n\n def take(enumerable, amount) when is_integer(amount) and amount < 0 do\n {count, fun} = slice_count_and_fun(enumerable)\n first = Kernel.max(amount + count, 0)\n fun.(first, count - first)\n end\n\n @doc \"\"\"\n Returns a list of every `nth` item in the enumerable,\n starting with the first element.\n\n The first item is always included, unless `nth` is 0.\n\n The second argument specifying every `nth` item must be a non-negative\n integer.\n\n ## Examples\n\n iex> Enum.take_every(1..10, 2)\n [1, 3, 5, 7, 9]\n\n iex> Enum.take_every(1..10, 0)\n []\n\n iex> Enum.take_every([1, 2, 3], 1)\n [1, 2, 3]\n\n \"\"\"\n @spec take_every(t, non_neg_integer) :: list\n def take_every(enumerable, nth)\n\n def take_every(enumerable, 1), do: to_list(enumerable)\n def take_every(_enumerable, 0), do: []\n def take_every([], nth) when is_integer(nth) and nth > 1, do: []\n\n def take_every(enumerable, nth) when is_integer(nth) and nth > 1 do\n {res, _} = reduce(enumerable, {[], :first}, R.take_every(nth))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Takes `count` random items from `enumerable`.\n\n Notice this function will traverse the whole `enumerable` to\n get the random sublist.\n\n See `random\/1` for notes on implementation and random seed.\n\n ## Examples\n\n # Although not necessary, let's seed the random algorithm\n iex> :rand.seed(:exsplus, {1, 2, 3})\n iex> Enum.take_random(1..10, 2)\n [5, 4]\n iex> Enum.take_random(?a..?z, 5)\n 'ipybz'\n\n \"\"\"\n @spec take_random(t, non_neg_integer) :: list\n def take_random(enumerable, count)\n def take_random(_enumerable, 0), do: []\n\n def take_random(enumerable, count) when is_integer(count) and count > 128 do\n reducer = fn elem, {idx, sample} ->\n jdx = random_integer(0, idx)\n\n cond do\n idx < count ->\n value = Map.get(sample, jdx)\n {idx + 1, Map.put(sample, idx, value) |> Map.put(jdx, elem)}\n\n jdx < count ->\n {idx + 1, Map.put(sample, jdx, elem)}\n\n true ->\n {idx + 1, sample}\n end\n end\n\n {size, sample} = reduce(enumerable, {0, %{}}, reducer)\n take_random(sample, Kernel.min(count, size), [])\n end\n\n def take_random(enumerable, count) when is_integer(count) and count > 0 do\n sample = Tuple.duplicate(nil, count)\n\n reducer = fn elem, {idx, sample} ->\n jdx = random_integer(0, idx)\n\n cond do\n idx < count ->\n value = elem(sample, jdx)\n {idx + 1, put_elem(sample, idx, value) |> put_elem(jdx, elem)}\n\n jdx < count ->\n {idx + 1, put_elem(sample, jdx, elem)}\n\n true ->\n {idx + 1, sample}\n end\n end\n\n {size, sample} = reduce(enumerable, {0, sample}, reducer)\n sample |> Tuple.to_list() |> take(Kernel.min(count, size))\n end\n\n defp take_random(_sample, 0, acc), do: acc\n\n defp take_random(sample, position, acc) do\n position = position - 1\n take_random(sample, position, [Map.get(sample, position) | acc])\n end\n\n @doc \"\"\"\n Takes the items from the beginning of the enumerable while `fun` returns\n a truthy value.\n\n ## Examples\n\n iex> Enum.take_while([1, 2, 3], fn(x) -> x < 3 end)\n [1, 2]\n\n \"\"\"\n @spec take_while(t, (element -> as_boolean(term))) :: list\n def take_while(enumerable, fun) when is_list(enumerable) do\n take_while_list(enumerable, fun)\n end\n\n def take_while(enumerable, fun) do\n {_, res} =\n Enumerable.reduce(enumerable, {:cont, []}, fn entry, acc ->\n if fun.(entry) do\n {:cont, [entry | acc]}\n else\n {:halt, acc}\n end\n end)\n\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Converts `enumerable` to a list.\n\n ## Examples\n\n iex> Enum.to_list(1..3)\n [1, 2, 3]\n\n \"\"\"\n @spec to_list(t) :: [element]\n def to_list(enumerable) when is_list(enumerable) do\n enumerable\n end\n\n def to_list(enumerable) do\n reverse(enumerable) |> :lists.reverse()\n end\n\n @doc \"\"\"\n Enumerates the `enumerable`, removing all duplicated elements.\n\n ## Examples\n\n iex> Enum.uniq([1, 2, 3, 3, 2, 1])\n [1, 2, 3]\n\n \"\"\"\n @spec uniq(t) :: list\n def uniq(enumerable) do\n uniq_by(enumerable, fn x -> x end)\n end\n\n @doc false\n # TODO: Remove on 2.0\n # (hard-deprecated in elixir_dispatch)\n def uniq(enumerable, fun) do\n uniq_by(enumerable, fun)\n end\n\n @doc \"\"\"\n Enumerates the `enumerable`, by removing the elements for which\n function `fun` returned duplicate items.\n\n The function `fun` maps every element to a term. Two elements are\n considered duplicates if the return value of `fun` is equal for\n both of them.\n\n The first occurrence of each element is kept.\n\n ## Example\n\n iex> Enum.uniq_by([{1, :x}, {2, :y}, {1, :z}], fn {x, _} -> x end)\n [{1, :x}, {2, :y}]\n\n iex> Enum.uniq_by([a: {:tea, 2}, b: {:tea, 2}, c: {:coffee, 1}], fn {_, y} -> y end)\n [a: {:tea, 2}, c: {:coffee, 1}]\n\n \"\"\"\n @spec uniq_by(t, (element -> term)) :: list\n\n def uniq_by(enumerable, fun) when is_list(enumerable) do\n uniq_list(enumerable, %{}, fun)\n end\n\n def uniq_by(enumerable, fun) do\n {list, _} = reduce(enumerable, {[], %{}}, R.uniq_by(fun))\n :lists.reverse(list)\n end\n\n @doc \"\"\"\n Opposite of `Enum.zip\/2`; extracts a two-element tuples from the\n enumerable and groups them together.\n\n It takes an enumerable with items being two-element tuples and returns\n a tuple with two lists, each of which is formed by the first and\n second element of each tuple, respectively.\n\n This function fails unless `enumerable` is or can be converted into a\n list of tuples with *exactly* two elements in each tuple.\n\n ## Examples\n\n iex> Enum.unzip([{:a, 1}, {:b, 2}, {:c, 3}])\n {[:a, :b, :c], [1, 2, 3]}\n\n iex> Enum.unzip(%{a: 1, b: 2})\n {[:a, :b], [1, 2]}\n\n \"\"\"\n @spec unzip(t) :: {[element], [element]}\n def unzip(enumerable) do\n {list1, list2} =\n reduce(enumerable, {[], []}, fn {el1, el2}, {list1, list2} ->\n {[el1 | list1], [el2 | list2]}\n end)\n\n {:lists.reverse(list1), :lists.reverse(list2)}\n end\n\n @doc \"\"\"\n Returns the enumerable with each element wrapped in a tuple\n alongside its index.\n\n If an `offset` is given, we will index from the given offset instead of from zero.\n\n ## Examples\n\n iex> Enum.with_index([:a, :b, :c])\n [a: 0, b: 1, c: 2]\n\n iex> Enum.with_index([:a, :b, :c], 3)\n [a: 3, b: 4, c: 5]\n\n \"\"\"\n @spec with_index(t, integer) :: [{element, index}]\n def with_index(enumerable, offset \\\\ 0) do\n map_reduce(enumerable, offset, fn x, acc ->\n {{x, acc}, acc + 1}\n end)\n |> elem(0)\n end\n\n @doc \"\"\"\n Zips corresponding elements from two enumerables into one list\n of tuples.\n\n The zipping finishes as soon as any enumerable completes.\n\n ## Examples\n\n iex> Enum.zip([1, 2, 3], [:a, :b, :c])\n [{1, :a}, {2, :b}, {3, :c}]\n\n iex> Enum.zip([1, 2, 3, 4, 5], [:a, :b, :c])\n [{1, :a}, {2, :b}, {3, :c}]\n\n \"\"\"\n @spec zip(t, t) :: [{any, any}]\n def zip(enumerable1, enumerable2)\n when is_list(enumerable1) and is_list(enumerable2) do\n zip_list(enumerable1, enumerable2)\n end\n\n def zip(enumerable1, enumerable2) do\n zip([enumerable1, enumerable2])\n end\n\n @doc \"\"\"\n Zips corresponding elements from a list of enumerables\n into one list of tuples.\n\n The zipping finishes as soon as any enumerable in the given list completes.\n\n ## Examples\n\n iex> Enum.zip([[1, 2, 3], [:a, :b, :c], [\"foo\", \"bar\", \"baz\"]])\n [{1, :a, \"foo\"}, {2, :b, \"bar\"}, {3, :c, \"baz\"}]\n\n iex> Enum.zip([[1, 2, 3, 4, 5], [:a, :b, :c]])\n [{1, :a}, {2, :b}, {3, :c}]\n\n \"\"\"\n @spec zip([t]) :: t\n\n def zip([]), do: []\n\n def zip(enumerables) when is_list(enumerables) do\n Stream.zip(enumerables).({:cont, []}, &{:cont, [&1 | &2]})\n |> elem(1)\n |> :lists.reverse()\n end\n\n ## Helpers\n\n @compile {:inline, aggregate: 3, entry_to_string: 1, reduce: 3, reduce_by: 3}\n\n defp entry_to_string(entry) when is_binary(entry), do: entry\n defp entry_to_string(entry), do: String.Chars.to_string(entry)\n\n defp aggregate([head | tail], fun, _empty) do\n :lists.foldl(fun, head, tail)\n end\n\n defp aggregate([], _fun, empty) do\n empty.()\n end\n\n defp aggregate(left..right, fun, _empty) do\n fun.(left, right)\n end\n\n defp aggregate(enumerable, fun, empty) do\n ref = make_ref()\n\n enumerable\n |> reduce(ref, fn\n element, ^ref -> element\n element, acc -> fun.(element, acc)\n end)\n |> case do\n ^ref -> empty.()\n result -> result\n end\n end\n\n defp reduce_by([head | tail], first, fun) do\n :lists.foldl(fun, first.(head), tail)\n end\n\n defp reduce_by([], _first, _fun) do\n :empty\n end\n\n defp reduce_by(enumerable, first, fun) do\n reduce(enumerable, :empty, fn\n element, {_, _} = acc -> fun.(element, acc)\n element, :empty -> first.(element)\n end)\n end\n\n defp random_integer(limit, limit) when is_integer(limit) do\n limit\n end\n\n defp random_integer(lower_limit, upper_limit) when upper_limit < lower_limit do\n random_integer(upper_limit, lower_limit)\n end\n\n defp random_integer(lower_limit, upper_limit) do\n lower_limit + :rand.uniform(upper_limit - lower_limit + 1) - 1\n end\n\n ## Implementations\n\n ## all?\n\n defp all_list([h | t], fun) do\n if fun.(h) do\n all_list(t, fun)\n else\n false\n end\n end\n\n defp all_list([], _) do\n true\n end\n\n ## any?\n\n defp any_list([h | t], fun) do\n if fun.(h) do\n true\n else\n any_list(t, fun)\n end\n end\n\n defp any_list([], _) do\n false\n end\n\n ## drop\n\n defp drop_list(list, 0), do: list\n defp drop_list([_ | tail], counter), do: drop_list(tail, counter - 1)\n defp drop_list([], _), do: []\n\n ## drop_while\n\n defp drop_while_list([head | tail], fun) do\n if fun.(head) do\n drop_while_list(tail, fun)\n else\n [head | tail]\n end\n end\n\n defp drop_while_list([], _) do\n []\n end\n\n ## filter\n\n defp filter_list([head | tail], fun) do\n if fun.(head) do\n [head | filter_list(tail, fun)]\n else\n filter_list(tail, fun)\n end\n end\n\n defp filter_list([], _fun) do\n []\n end\n\n ## find\n\n defp find_list([head | tail], default, fun) do\n if fun.(head) do\n head\n else\n find_list(tail, default, fun)\n end\n end\n\n defp find_list([], default, _) do\n default\n end\n\n ## find_index\n\n defp find_index_list([head | tail], counter, fun) do\n if fun.(head) do\n counter\n else\n find_index_list(tail, counter + 1, fun)\n end\n end\n\n defp find_index_list([], _, _) do\n nil\n end\n\n ## find_value\n\n defp find_value_list([head | tail], default, fun) do\n fun.(head) || find_value_list(tail, default, fun)\n end\n\n defp find_value_list([], default, _) do\n default\n end\n\n ## flat_map\n\n defp flat_map_list([head | tail], fun) do\n case fun.(head) do\n list when is_list(list) -> list ++ flat_map_list(tail, fun)\n other -> to_list(other) ++ flat_map_list(tail, fun)\n end\n end\n\n defp flat_map_list([], _fun) do\n []\n end\n\n ## reduce\n\n defp reduce_range_inc(first, first, acc, fun) do\n fun.(first, acc)\n end\n\n defp reduce_range_inc(first, last, acc, fun) do\n reduce_range_inc(first + 1, last, fun.(first, acc), fun)\n end\n\n defp reduce_range_dec(first, first, acc, fun) do\n fun.(first, acc)\n end\n\n defp reduce_range_dec(first, last, acc, fun) do\n reduce_range_dec(first - 1, last, fun.(first, acc), fun)\n end\n\n ## reject\n\n defp reject_list([head | tail], fun) do\n if fun.(head) do\n reject_list(tail, fun)\n else\n [head | reject_list(tail, fun)]\n end\n end\n\n defp reject_list([], _fun) do\n []\n end\n\n ## reverse_slice\n\n defp reverse_slice(rest, idx, idx, count, acc) do\n {slice, rest} = head_slice(rest, count, [])\n :lists.reverse(rest, :lists.reverse(slice, acc))\n end\n\n defp reverse_slice([elem | rest], idx, start, count, acc) do\n reverse_slice(rest, idx - 1, start, count, [elem | acc])\n end\n\n defp head_slice(rest, 0, acc), do: {acc, rest}\n\n defp head_slice([elem | rest], count, acc) do\n head_slice(rest, count - 1, [elem | acc])\n end\n\n ## shuffle\n\n defp shuffle_unwrap([{_, h} | enumerable], t) do\n shuffle_unwrap(enumerable, [h | t])\n end\n\n defp shuffle_unwrap([], t), do: t\n\n ## slice\n\n defp slice_any(enumerable, start, amount) when start < 0 do\n {count, fun} = slice_count_and_fun(enumerable)\n start = count + start\n\n if start >= 0 do\n fun.(start, Kernel.min(amount, count - start))\n else\n []\n end\n end\n\n defp slice_any(list, start, amount) when is_list(list) do\n Enumerable.List.slice(list, start, amount)\n end\n\n defp slice_any(enumerable, start, amount) do\n case Enumerable.slice(enumerable) do\n {:ok, count, _} when start >= count ->\n []\n\n {:ok, count, fun} when is_function(fun) ->\n fun.(start, Kernel.min(amount, count - start))\n\n {:error, module} ->\n slice_enum(enumerable, module, start, amount)\n end\n end\n\n defp slice_enum(enumerable, module, start, amount) do\n {_, {_, _, slice}} =\n module.reduce(enumerable, {:cont, {start, amount, []}}, fn\n _entry, {start, amount, _list} when start > 0 ->\n {:cont, {start - 1, amount, []}}\n\n entry, {start, amount, list} when amount > 1 ->\n {:cont, {start, amount - 1, [entry | list]}}\n\n entry, {start, amount, list} ->\n {:halt, {start, amount, [entry | list]}}\n end)\n\n :lists.reverse(slice)\n end\n\n defp slice_count_and_fun(enumerable) when is_list(enumerable) do\n {length(enumerable), &Enumerable.List.slice(enumerable, &1, &2)}\n end\n\n defp slice_count_and_fun(enumerable) do\n case Enumerable.slice(enumerable) do\n {:ok, count, fun} when is_function(fun) ->\n {count, fun}\n\n {:error, module} ->\n {_, {list, count}} =\n module.reduce(enumerable, {:cont, {[], 0}}, fn elem, {acc, count} ->\n {:cont, {[elem | acc], count + 1}}\n end)\n\n {count, &Enumerable.List.slice(:lists.reverse(list), &1, &2)}\n end\n end\n\n ## sort\n\n defp sort_reducer(entry, {:split, y, x, r, rs, bool}, fun) do\n cond do\n fun.(y, entry) == bool ->\n {:split, entry, y, [x | r], rs, bool}\n\n fun.(x, entry) == bool ->\n {:split, y, entry, [x | r], rs, bool}\n\n r == [] ->\n {:split, y, x, [entry], rs, bool}\n\n true ->\n {:pivot, y, x, r, rs, entry, bool}\n end\n end\n\n defp sort_reducer(entry, {:pivot, y, x, r, rs, s, bool}, fun) do\n cond do\n fun.(y, entry) == bool ->\n {:pivot, entry, y, [x | r], rs, s, bool}\n\n fun.(x, entry) == bool ->\n {:pivot, y, entry, [x | r], rs, s, bool}\n\n fun.(s, entry) == bool ->\n {:split, entry, s, [], [[y, x | r] | rs], bool}\n\n true ->\n {:split, s, entry, [], [[y, x | r] | rs], bool}\n end\n end\n\n defp sort_reducer(entry, [x], fun) do\n {:split, entry, x, [], [], fun.(x, entry)}\n end\n\n defp sort_reducer(entry, acc, _fun) do\n [entry | acc]\n end\n\n defp sort_terminator({:split, y, x, r, rs, bool}, fun) do\n sort_merge([[y, x | r] | rs], fun, bool)\n end\n\n defp sort_terminator({:pivot, y, x, r, rs, s, bool}, fun) do\n sort_merge([[s], [y, x | r] | rs], fun, bool)\n end\n\n defp sort_terminator(acc, _fun) do\n acc\n end\n\n defp sort_merge(list, fun, true), do: reverse_sort_merge(list, [], fun, true)\n\n defp sort_merge(list, fun, false), do: sort_merge(list, [], fun, false)\n\n defp sort_merge([t1, [h2 | t2] | l], acc, fun, true),\n do: sort_merge(l, [sort_merge1(t1, h2, t2, [], fun, false) | acc], fun, true)\n\n defp sort_merge([[h2 | t2], t1 | l], acc, fun, false),\n do: sort_merge(l, [sort_merge1(t1, h2, t2, [], fun, false) | acc], fun, false)\n\n defp sort_merge([l], [], _fun, _bool), do: l\n\n defp sort_merge([l], acc, fun, bool),\n do: reverse_sort_merge([:lists.reverse(l, []) | acc], [], fun, bool)\n\n defp sort_merge([], acc, fun, bool), do: reverse_sort_merge(acc, [], fun, bool)\n\n defp reverse_sort_merge([[h2 | t2], t1 | l], acc, fun, true),\n do: reverse_sort_merge(l, [sort_merge1(t1, h2, t2, [], fun, true) | acc], fun, true)\n\n defp reverse_sort_merge([t1, [h2 | t2] | l], acc, fun, false),\n do: reverse_sort_merge(l, [sort_merge1(t1, h2, t2, [], fun, true) | acc], fun, false)\n\n defp reverse_sort_merge([l], acc, fun, bool),\n do: sort_merge([:lists.reverse(l, []) | acc], [], fun, bool)\n\n defp reverse_sort_merge([], acc, fun, bool), do: sort_merge(acc, [], fun, bool)\n\n defp sort_merge1([h1 | t1], h2, t2, m, fun, bool) do\n if fun.(h1, h2) == bool do\n sort_merge2(h1, t1, t2, [h2 | m], fun, bool)\n else\n sort_merge1(t1, h2, t2, [h1 | m], fun, bool)\n end\n end\n\n defp sort_merge1([], h2, t2, m, _fun, _bool), do: :lists.reverse(t2, [h2 | m])\n\n defp sort_merge2(h1, t1, [h2 | t2], m, fun, bool) do\n if fun.(h1, h2) == bool do\n sort_merge2(h1, t1, t2, [h2 | m], fun, bool)\n else\n sort_merge1(t1, h2, t2, [h1 | m], fun, bool)\n end\n end\n\n defp sort_merge2(h1, t1, [], m, _fun, _bool), do: :lists.reverse(t1, [h1 | m])\n\n ## split\n\n defp split_list([head | tail], counter, acc) when counter > 0 do\n split_list(tail, counter - 1, [head | acc])\n end\n\n defp split_list(list, 0, acc) do\n {:lists.reverse(acc), list}\n end\n\n defp split_list([], _, acc) do\n {:lists.reverse(acc), []}\n end\n\n defp split_reverse_list([head | tail], counter, acc) when counter > 0 do\n split_reverse_list(tail, counter - 1, [head | acc])\n end\n\n defp split_reverse_list(list, 0, acc) do\n {:lists.reverse(list), acc}\n end\n\n defp split_reverse_list([], _, acc) do\n {[], acc}\n end\n\n ## split_while\n\n defp split_while_list([head | tail], fun, acc) do\n if fun.(head) do\n split_while_list(tail, fun, [head | acc])\n else\n {:lists.reverse(acc), [head | tail]}\n end\n end\n\n defp split_while_list([], _, acc) do\n {:lists.reverse(acc), []}\n end\n\n ## take\n\n defp take_list([head | _], 1), do: [head]\n defp take_list([head | tail], counter), do: [head | take_list(tail, counter - 1)]\n defp take_list([], _counter), do: []\n\n ## take_while\n\n defp take_while_list([head | tail], fun) do\n if fun.(head) do\n [head | take_while_list(tail, fun)]\n else\n []\n end\n end\n\n defp take_while_list([], _) do\n []\n end\n\n ## uniq\n\n defp uniq_list([head | tail], set, fun) do\n value = fun.(head)\n\n case set do\n %{^value => true} -> uniq_list(tail, set, fun)\n %{} -> [head | uniq_list(tail, Map.put(set, value, true), fun)]\n end\n end\n\n defp uniq_list([], _set, _fun) do\n []\n end\n\n ## zip\n\n defp zip_list([h1 | next1], [h2 | next2]) do\n [{h1, h2} | zip_list(next1, next2)]\n end\n\n defp zip_list(_, []), do: []\n defp zip_list([], _), do: []\nend\n\ndefimpl Enumerable, for: List do\n def count(_list), do: {:error, __MODULE__}\n def member?(_list, _value), do: {:error, __MODULE__}\n def slice(_list), do: {:error, __MODULE__}\n\n def reduce(_, {:halt, acc}, _fun), do: {:halted, acc}\n def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)}\n def reduce([], {:cont, acc}, _fun), do: {:done, acc}\n def reduce([h | t], {:cont, acc}, fun), do: reduce(t, fun.(h, acc), fun)\n\n @doc false\n def slice([], _start, _count), do: []\n def slice(_list, _start, 0), do: []\n def slice([head | tail], 0, count), do: [head | slice(tail, 0, count - 1)]\n def slice([_ | tail], start, count), do: slice(tail, start - 1, count)\nend\n\ndefimpl Enumerable, for: Map do\n def count(map) do\n {:ok, map_size(map)}\n end\n\n def member?(map, {key, value}) do\n {:ok, match?(%{^key => ^value}, map)}\n end\n\n def member?(_map, _other) do\n {:ok, false}\n end\n\n def slice(map) do\n {:ok, map_size(map), &Enumerable.List.slice(:maps.to_list(map), &1, &2)}\n end\n\n def reduce(map, acc, fun) do\n reduce_list(:maps.to_list(map), acc, fun)\n end\n\n defp reduce_list(_, {:halt, acc}, _fun), do: {:halted, acc}\n defp reduce_list(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce_list(list, &1, fun)}\n defp reduce_list([], {:cont, acc}, _fun), do: {:done, acc}\n defp reduce_list([h | t], {:cont, acc}, fun), do: reduce_list(t, fun.(h, acc), fun)\nend\n\ndefimpl Enumerable, for: Function do\n def count(_function), do: {:error, __MODULE__}\n def member?(_function, _value), do: {:error, __MODULE__}\n def slice(_function), do: {:error, __MODULE__}\n\n def reduce(function, acc, fun) when is_function(function, 2), do: function.(acc, fun)\n\n def reduce(function, _acc, _fun) do\n raise Protocol.UndefinedError,\n protocol: @protocol,\n value: function,\n description: \"only anonymous functions of arity 2 are enumerable\"\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"969e8e0289a97ad69452236240a8747f1492b97e","subject":"Add --output to mix firmware to specify .fw path","message":"Add --output to mix firmware to specify .fw path\n","repos":"nerves-project\/nerves,nerves-project\/nerves","old_file":"lib\/mix\/tasks\/firmware.ex","new_file":"lib\/mix\/tasks\/firmware.ex","new_contents":"defmodule Mix.Tasks.Firmware do\n use Mix.Task\n import Mix.Nerves.Utils\n alias Mix.Nerves.Preflight\n\n @shortdoc \"Build a firmware bundle\"\n\n @moduledoc \"\"\"\n Build a firmware image for the selected target platform.\n\n This task builds the project, combines the generated OTP release with\n a Nerves system image, and creates a `.fw` file that may be written\n to an SDCard or sent to a device.\n\n ## Command line options\n\n * `--verbose` - produce detailed output about release assembly\n * `--output` - (Optional) The path to the .fw file used to write the patch\n firmware. Defaults to `Nerves.Env.firmware_path\/1`\n ## Environment variables\n\n * `NERVES_SYSTEM` - may be set to a local directory to specify the Nerves\n system image that is used\n\n * `NERVES_TOOLCHAIN` - may be set to a local directory to specify the\n Nerves toolchain (C\/C++ crosscompiler) that is used\n \"\"\"\n\n @switches [verbose: :boolean, output: :string]\n\n @impl true\n def run(args) do\n Preflight.check!()\n debug_info(\"Nerves Firmware Assembler\")\n\n {opts, _, _} = OptionParser.parse(args, switches: @switches)\n\n system_path = check_nerves_system_is_set!()\n\n check_nerves_toolchain_is_set!()\n\n # Check for required files\n if use_distillery?() do\n rel_config =\n File.cwd!()\n |> Path.join(\"rel\/config.exs\")\n\n if !File.exists?(rel_config) do\n Mix.raise(\"\"\"\n You are missing a release config file. Run nerves.release.init task first\n \"\"\")\n end\n else\n vm_args =\n File.cwd!()\n |> Path.join(\"rel\/vm.args.eex\")\n\n if !File.exists?(vm_args) do\n Mix.raise(\"\"\"\n rel\/vm.args needs to be moved to rel\/vm.args.eex\n \"\"\")\n end\n end\n\n # By this point, paths have already been loaded.\n # We just want to ensure any custom systems are compiled\n # via the precompile checks\n Mix.Task.run(\"nerves.precompile\", [\"--no-loadpaths\"])\n Mix.Task.run(\"compile\", [])\n\n Mix.Nerves.IO.shell_info(\"Building OTP Release...\")\n\n if use_distillery?() do\n clean_distillery_release(opts)\n build_distillery_release(opts)\n else\n build_release()\n end\n\n config = Mix.Project.config()\n fw_out = opts[:out] || Nerves.Env.firmware_path(config)\n build_firmware(config, system_path, fw_out)\n end\n\n @doc false\n def result({_, 0}), do: nil\n\n def result({result, _}),\n do:\n Mix.raise(\"\"\"\n Nerves encountered an error. #{inspect(result)}\n \"\"\")\n\n defp clean_distillery_release(opts) do\n verbosity = if opts[:verbose], do: \"--verbose\", else: \"--silent\"\n\n try do\n Mix.Task.run(\"distillery.release.clean\", [verbosity, \"--implode\", \"--no-confirm\"])\n catch\n :exit, _ -> :noop\n end\n end\n\n defp build_release() do\n Mix.Task.run(\"release\", [])\n end\n\n defp build_distillery_release(opts) do\n verbosity = if opts[:verbose], do: \"--verbose\", else: \"--quiet\"\n Mix.Task.run(\"distillery.release\", [verbosity, \"--no-tar\"])\n end\n\n defp build_firmware(config, system_path, fw_out) do\n otp_app = config[:app]\n compiler_check()\n firmware_config = Application.get_env(:nerves, :firmware)\n\n rootfs_priorities =\n Nerves.Env.package(:nerves_system_br)\n |> rootfs_priorities()\n\n rel2fw_path = Path.join(system_path, \"scripts\/rel2fw.sh\")\n cmd = \"bash\"\n args = [rel2fw_path]\n\n if firmware_config[:rootfs_additions] do\n Mix.shell().error(\n \"The :rootfs_additions configuration option has been deprecated. Please use :rootfs_overlay instead.\"\n )\n end\n\n build_rootfs_overlay = Path.join([Mix.Project.build_path(), \"nerves\", \"rootfs_overlay\"])\n File.mkdir_p(build_rootfs_overlay)\n\n write_erlinit_config(build_rootfs_overlay)\n\n project_rootfs_overlay =\n case firmware_config[:rootfs_overlay] || firmware_config[:rootfs_additions] do\n nil ->\n []\n\n overlays when is_list(overlays) ->\n overlays\n\n overlay ->\n [Path.expand(overlay)]\n end\n\n rootfs_overlays =\n [build_rootfs_overlay | project_rootfs_overlay]\n |> Enum.map(&[\"-a\", &1])\n |> List.flatten()\n\n fwup_conf =\n case firmware_config[:fwup_conf] do\n nil -> []\n fwup_conf -> [\"-c\", Path.join(File.cwd!(), fwup_conf)]\n end\n\n fw = [\"-f\", fw_out]\n release_path = Path.join(Mix.Project.build_path(), \"rel\/#{otp_app}\")\n output = [release_path]\n args = args ++ fwup_conf ++ rootfs_overlays ++ fw ++ rootfs_priorities ++ output\n env = standard_fwup_variables(config)\n\n set_provisioning(firmware_config[:provisioning])\n\n config\n |> Nerves.Env.images_path()\n |> File.mkdir_p()\n\n shell(cmd, args, env: env)\n |> result\n end\n\n defp standard_fwup_variables(config) do\n # Assuming the fwup.conf file respects these variable like the official\n # systems do, this will set the .fw metadata to what's in the mix.exs.\n [\n {\"NERVES_FW_VERSION\", config[:version]},\n {\"NERVES_FW_PRODUCT\", config[:name] || to_string(config[:app])},\n {\"NERVES_FW_DESCRIPTION\", config[:description]},\n {\"NERVES_FW_AUTHOR\", config[:author]}\n ]\n end\n\n # Need to check min version for nerves_system_br to check if passing the\n # rootfs priorities option is supported. This was added in the 1.7.1 release\n # https:\/\/github.com\/nerves-project\/nerves_system_br\/releases\/tag\/v1.7.1\n defp rootfs_priorities(%Nerves.Package{app: :nerves_system_br, version: vsn}) do\n case Version.compare(vsn, \"1.7.1\") do\n r when r in [:gt, :eq] ->\n rootfs_priorities_file =\n Path.join([Mix.Project.build_path(), \"nerves\", \"rootfs.priorities\"])\n\n if File.exists?(rootfs_priorities_file) do\n [\"-p\", rootfs_priorities_file]\n else\n []\n end\n\n _ ->\n []\n end\n end\n\n defp rootfs_priorities(_), do: []\n\n defp compiler_check() do\n with {:ok, otpc} <- module_compiler_version(:code),\n {:ok, otp_requirement} <- Version.parse_requirement(\"~> #{otpc.major}.#{otpc.minor}\"),\n {:ok, elixirc} <- module_compiler_version(Kernel) do\n unless Version.match?(elixirc, otp_requirement) do\n Mix.raise(\"\"\"\n The Erlang compiler that compiled Elixir is older than the compiler\n used to compile OTP.\n\n Elixir: #{elixirc.major}.#{elixirc.minor}.#{elixirc.patch}\n OTP: #{otpc.major}.#{otpc.minor}.#{otpc.patch}\n\n Please use a version of Elixir that was compiled using the same major\n version of OTP.\n\n For example:\n\n If your target is running OTP 22, you should use a version of Elixir\n that was compiled using OTP 22.\n\n If you're using asdf to manage Elixir versions, run:\n\n asdf install elixir #{System.version()}-otp-#{system_otp_release()}\n asdf global elixir #{System.version()}-otp-#{system_otp_release()}\n \"\"\")\n end\n else\n error ->\n Mix.raise(\"\"\"\n Nerves was unable to verify the Erlang compiler version.\n Error: #{error}\n \"\"\")\n end\n end\n\n def module_compiler_version(mod) do\n with {:file, path} <- :code.is_loaded(mod),\n {:ok, {_, [compile_info: compile_info]}} <- :beam_lib.chunks(path, [:compile_info]),\n {:ok, vsn} <- Keyword.fetch(compile_info, :version),\n vsn <- to_string(vsn) do\n parse_version(vsn)\n end\n end\n\n def system_otp_release do\n :erlang.system_info(:otp_release)\n |> to_string()\n end\n\n defp write_erlinit_config(build_overlay) do\n with user_opts <- Application.get_env(:nerves, :erlinit, []),\n {:ok, system_config_file} <- Nerves.Erlinit.system_config_file(Nerves.Env.system()),\n {:ok, system_config_file} <- File.read(system_config_file),\n system_opts <- Nerves.Erlinit.decode_config(system_config_file),\n erlinit_opts <- Nerves.Erlinit.merge_opts(system_opts, user_opts),\n erlinit_config <- Nerves.Erlinit.encode_config(erlinit_opts) do\n erlinit_config_file = Path.join(build_overlay, \"etc\/erlinit.config\")\n\n Path.dirname(erlinit_config_file)\n |> File.mkdir_p()\n\n header = erlinit_config_header(user_opts)\n\n File.write(erlinit_config_file, header <> erlinit_config)\n {:ok, erlinit_config_file}\n else\n {:error, :no_config} ->\n Nerves.Utils.Shell.warn(\"There was no system erlinit.config found\")\n :noop\n\n _e ->\n :noop\n end\n end\n\n def erlinit_config_header(opts) do\n \"\"\"\n # Generated from rootfs_overlay\/etc\/erlinit.config\n \"\"\" <>\n if opts != [] do\n \"\"\"\n # with overrides from the application config\n \"\"\"\n else\n \"\"\"\n \"\"\"\n end\n end\nend\n","old_contents":"defmodule Mix.Tasks.Firmware do\n use Mix.Task\n import Mix.Nerves.Utils\n alias Mix.Nerves.Preflight\n\n @shortdoc \"Build a firmware bundle\"\n\n @moduledoc \"\"\"\n Build a firmware image for the selected target platform.\n\n This task builds the project, combines the generated OTP release with\n a Nerves system image, and creates a `.fw` file that may be written\n to an SDCard or sent to a device.\n\n ## Command line options\n\n * `--verbose` - produce detailed output about release assembly\n\n ## Environment variables\n\n * `NERVES_SYSTEM` - may be set to a local directory to specify the Nerves\n system image that is used\n\n * `NERVES_TOOLCHAIN` - may be set to a local directory to specify the\n Nerves toolchain (C\/C++ crosscompiler) that is used\n \"\"\"\n\n @switches [verbose: :boolean]\n\n @impl true\n def run(args) do\n Preflight.check!()\n debug_info(\"Nerves Firmware Assembler\")\n\n {opts, _, _} = OptionParser.parse(args, switches: @switches)\n\n system_path = check_nerves_system_is_set!()\n\n check_nerves_toolchain_is_set!()\n\n # Check for required files\n if use_distillery?() do\n rel_config =\n File.cwd!()\n |> Path.join(\"rel\/config.exs\")\n\n if !File.exists?(rel_config) do\n Mix.raise(\"\"\"\n You are missing a release config file. Run nerves.release.init task first\n \"\"\")\n end\n else\n vm_args =\n File.cwd!()\n |> Path.join(\"rel\/vm.args.eex\")\n\n if !File.exists?(vm_args) do\n Mix.raise(\"\"\"\n rel\/vm.args needs to be moved to rel\/vm.args.eex\n \"\"\")\n end\n end\n\n # By this point, paths have already been loaded.\n # We just want to ensure any custom systems are compiled\n # via the precompile checks\n Mix.Task.run(\"nerves.precompile\", [\"--no-loadpaths\"])\n Mix.Task.run(\"compile\", [])\n\n Mix.Nerves.IO.shell_info(\"Building OTP Release...\")\n\n if use_distillery?() do\n clean_distillery_release(opts)\n build_distillery_release(opts)\n else\n build_release()\n end\n\n build_firmware(system_path)\n end\n\n @doc false\n def result({_, 0}), do: nil\n\n def result({result, _}),\n do:\n Mix.raise(\"\"\"\n Nerves encountered an error. #{inspect(result)}\n \"\"\")\n\n defp clean_distillery_release(opts) do\n verbosity = if opts[:verbose], do: \"--verbose\", else: \"--silent\"\n\n try do\n Mix.Task.run(\"distillery.release.clean\", [verbosity, \"--implode\", \"--no-confirm\"])\n catch\n :exit, _ -> :noop\n end\n end\n\n defp build_release() do\n Mix.Task.run(\"release\", [])\n end\n\n defp build_distillery_release(opts) do\n verbosity = if opts[:verbose], do: \"--verbose\", else: \"--quiet\"\n Mix.Task.run(\"distillery.release\", [verbosity, \"--no-tar\"])\n end\n\n defp build_firmware(system_path) do\n config = Mix.Project.config()\n otp_app = config[:app]\n\n compiler_check()\n firmware_config = Application.get_env(:nerves, :firmware)\n\n rootfs_priorities =\n Nerves.Env.package(:nerves_system_br)\n |> rootfs_priorities()\n\n rel2fw_path = Path.join(system_path, \"scripts\/rel2fw.sh\")\n cmd = \"bash\"\n args = [rel2fw_path]\n\n if firmware_config[:rootfs_additions] do\n Mix.shell().error(\n \"The :rootfs_additions configuration option has been deprecated. Please use :rootfs_overlay instead.\"\n )\n end\n\n build_rootfs_overlay = Path.join([Mix.Project.build_path(), \"nerves\", \"rootfs_overlay\"])\n File.mkdir_p(build_rootfs_overlay)\n\n write_erlinit_config(build_rootfs_overlay)\n\n project_rootfs_overlay =\n case firmware_config[:rootfs_overlay] || firmware_config[:rootfs_additions] do\n nil ->\n []\n\n overlays when is_list(overlays) ->\n overlays\n\n overlay ->\n [Path.expand(overlay)]\n end\n\n rootfs_overlays =\n [build_rootfs_overlay | project_rootfs_overlay]\n |> Enum.map(&[\"-a\", &1])\n |> List.flatten()\n\n fwup_conf =\n case firmware_config[:fwup_conf] do\n nil -> []\n fwup_conf -> [\"-c\", Path.join(File.cwd!(), fwup_conf)]\n end\n\n fw = [\"-f\", Nerves.Env.firmware_path(config)]\n release_path = Path.join(Mix.Project.build_path(), \"rel\/#{otp_app}\")\n output = [release_path]\n args = args ++ fwup_conf ++ rootfs_overlays ++ fw ++ rootfs_priorities ++ output\n env = standard_fwup_variables(config)\n\n set_provisioning(firmware_config[:provisioning])\n\n config\n |> Nerves.Env.images_path()\n |> File.mkdir_p()\n\n shell(cmd, args, env: env)\n |> result\n end\n\n defp standard_fwup_variables(config) do\n # Assuming the fwup.conf file respects these variable like the official\n # systems do, this will set the .fw metadata to what's in the mix.exs.\n [\n {\"NERVES_FW_VERSION\", config[:version]},\n {\"NERVES_FW_PRODUCT\", config[:name] || to_string(config[:app])},\n {\"NERVES_FW_DESCRIPTION\", config[:description]},\n {\"NERVES_FW_AUTHOR\", config[:author]}\n ]\n end\n\n # Need to check min version for nerves_system_br to check if passing the\n # rootfs priorities option is supported. This was added in the 1.7.1 release\n # https:\/\/github.com\/nerves-project\/nerves_system_br\/releases\/tag\/v1.7.1\n defp rootfs_priorities(%Nerves.Package{app: :nerves_system_br, version: vsn}) do\n case Version.compare(vsn, \"1.7.1\") do\n r when r in [:gt, :eq] ->\n rootfs_priorities_file =\n Path.join([Mix.Project.build_path(), \"nerves\", \"rootfs.priorities\"])\n\n if File.exists?(rootfs_priorities_file) do\n [\"-p\", rootfs_priorities_file]\n else\n []\n end\n\n _ ->\n []\n end\n end\n\n defp rootfs_priorities(_), do: []\n\n defp compiler_check() do\n with {:ok, otpc} <- module_compiler_version(:code),\n {:ok, otp_requirement} <- Version.parse_requirement(\"~> #{otpc.major}.#{otpc.minor}\"),\n {:ok, elixirc} <- module_compiler_version(Kernel) do\n unless Version.match?(elixirc, otp_requirement) do\n Mix.raise(\"\"\"\n The Erlang compiler that compiled Elixir is older than the compiler\n used to compile OTP.\n\n Elixir: #{elixirc.major}.#{elixirc.minor}.#{elixirc.patch}\n OTP: #{otpc.major}.#{otpc.minor}.#{otpc.patch}\n\n Please use a version of Elixir that was compiled using the same major\n version of OTP.\n\n For example:\n\n If your target is running OTP 22, you should use a version of Elixir\n that was compiled using OTP 22.\n\n If you're using asdf to manage Elixir versions, run:\n\n asdf install elixir #{System.version()}-otp-#{system_otp_release()}\n asdf global elixir #{System.version()}-otp-#{system_otp_release()}\n \"\"\")\n end\n else\n error ->\n Mix.raise(\"\"\"\n Nerves was unable to verify the Erlang compiler version.\n Error: #{error}\n \"\"\")\n end\n end\n\n def module_compiler_version(mod) do\n with {:file, path} <- :code.is_loaded(mod),\n {:ok, {_, [compile_info: compile_info]}} <- :beam_lib.chunks(path, [:compile_info]),\n {:ok, vsn} <- Keyword.fetch(compile_info, :version),\n vsn <- to_string(vsn) do\n parse_version(vsn)\n end\n end\n\n def system_otp_release do\n :erlang.system_info(:otp_release)\n |> to_string()\n end\n\n defp write_erlinit_config(build_overlay) do\n with user_opts <- Application.get_env(:nerves, :erlinit, []),\n {:ok, system_config_file} <- Nerves.Erlinit.system_config_file(Nerves.Env.system()),\n {:ok, system_config_file} <- File.read(system_config_file),\n system_opts <- Nerves.Erlinit.decode_config(system_config_file),\n erlinit_opts <- Nerves.Erlinit.merge_opts(system_opts, user_opts),\n erlinit_config <- Nerves.Erlinit.encode_config(erlinit_opts) do\n erlinit_config_file = Path.join(build_overlay, \"etc\/erlinit.config\")\n\n Path.dirname(erlinit_config_file)\n |> File.mkdir_p()\n\n header = erlinit_config_header(user_opts)\n\n File.write(erlinit_config_file, header <> erlinit_config)\n {:ok, erlinit_config_file}\n else\n {:error, :no_config} ->\n Nerves.Utils.Shell.warn(\"There was no system erlinit.config found\")\n :noop\n\n _e ->\n :noop\n end\n end\n\n def erlinit_config_header(opts) do\n \"\"\"\n # Generated from rootfs_overlay\/etc\/erlinit.config\n \"\"\" <>\n if opts != [] do\n \"\"\"\n # with overrides from the application config\n \"\"\"\n else\n \"\"\"\n \"\"\"\n end\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"33e42230648094c110c02152b3658b7a3fe1cec1","subject":"Optimize ensure content type implementation","message":"Optimize ensure content type implementation\n","repos":"lancehalvorsen\/phoenix,DavidAlphaFox\/phoenix,tony612\/phoenix,rafbgarcia\/phoenix,linearregression\/phoenix,bsodmike\/phoenix,FND\/phoenix,Gazler\/phoenix,daytonn\/phoenix,ybur-yug\/phoenix,mschae\/phoenix,ugisozols\/phoenix,jwarwick\/phoenix,mvidaurre\/phoenix,nshafer\/phoenix,ericmj\/phoenix,eksperimental\/phoenix,dmarkow\/phoenix,keathley\/phoenix,beni55\/phoenix,evax\/phoenix,gjaldon\/phoenix,trarbr\/phoenix,cas27\/phoenix,StevenNunez\/phoenix,Smulligan85\/phoenix,wsmoak\/phoenix,seejee\/phoenix,mitchellhenke\/phoenix,Fluxuous\/phoenix,jxs\/phoenix,omotenko\/phoenix_auth,jeffkreeftmeijer\/phoenix,SmartCasual\/phoenix,jamilabreu\/phoenix,mschae\/phoenix,lono-devices\/phoenix,CD1212\/phoenix,GabrielNicolasAvellaneda\/phoenix,paulcsmith\/phoenix,ahmetabdi\/phoenix,mitchellhenke\/phoenix,stefania11\/phoenix,jeffweiss\/phoenix,andrewvy\/phoenix,kidaa\/phoenix,bsmr-erlang\/phoenix,pap\/phoenix,marcioj\/phoenix,Rumel\/phoenix,Smulligan85\/phoenix,mvidaurre\/phoenix,yonglehou\/phoenix,Eventacular\/phoenix,0x00evil\/phoenix,nicrioux\/phoenix,manukall\/phoenix,wicliff\/phoenix,Ben-Evolently\/phoenix,jamilabreu\/phoenix,arthurcolle\/phoenix,bdtomlin\/phoenix,omotenko\/phoenix_auth,begleynk\/phoenix,rafbgarcia\/phoenix,Joe-noh\/phoenix,safi\/phoenix,ephe-meral\/phoenix,iStefo\/phoenix,michalmuskala\/phoenix,sadiqmmm\/phoenix,KazuCocoa\/phoenix,foxnewsnetwork\/phoenix,doron2402\/phoenix,Kosmas\/phoenix,kevinold\/phoenix,robhurring\/phoenix,ericmj\/phoenix,vic\/phoenix,iguberman\/phoenix,stevedomin\/phoenix,doomspork\/phoenix,justnoxx\/phoenix,nshafer\/phoenix,evax\/phoenix,rafbgarcia\/phoenix,vic\/phoenix,0x00evil\/phoenix,thegrubbsian\/phoenix,romul\/phoenix,lono-devices\/phoenix,robomc\/phoenix,scrogson\/phoenix,andrewvy\/phoenix,brucify\/phoenix,korobkov\/phoenix,gjaldon\/phoenix,kyledecot\/phoenix,keathley\/phoenix,greyhwndz\/phoenix,mobileoverlord\/phoenix,CultivateHQ\/phoenix,CultivateHQ\/phoenix,JHKennedy4\/phoenix,ACPK\/phoenix,hsavit1\/phoenix,kholbekj\/phoenix,jwarwick\/phoenix,jasond-s\/phoenix,optikfluffel\/phoenix,lancehalvorsen\/phoenix,wsmoak\/phoenix,rodrigues\/phoenix,esbullington\/phoenix-1,VictorZeng\/phoenix,milafrerichs\/phoenix,phoenixframework\/phoenix,dmarkow\/phoenix,pap\/phoenix,Joe-noh\/phoenix,hotvulcan\/phoenix,trarbr\/phoenix,0x00evil\/phoenix,switchflip\/phoenix,michalmuskala\/phoenix,Gazler\/phoenix,Kosmas\/phoenix,y-yagi\/phoenix,optikfluffel\/phoenix,phoenixframework\/phoenix,optikfluffel\/phoenix,DavidAlphaFox\/phoenix,elliotcm\/phoenix,yoavlt\/phoenix,Rumel\/phoenix,mobileoverlord\/phoenix,iStefo\/phoenix,henrik\/phoenix,Dahoon\/phoenix,stevedomin\/phoenix,phoenixframework\/phoenix,javimolla\/phoenix,korobkov\/phoenix,ybur-yug\/phoenix,nshafer\/phoenix,eksperimental\/phoenix,nickgartmann\/phoenix,ephe-meral\/phoenix,manukall\/phoenix,sdnorm\/phoenix,maxnordlund\/phoenix,cas27\/phoenix,seejee\/phoenix,bsmr-erlang\/phoenix,rodrigues\/phoenix,xtity\/simple_phoenix,fbjork\/phoenix","old_file":"lib\/phoenix\/controller.ex","new_file":"lib\/phoenix\/controller.ex","new_contents":"defmodule Phoenix.Controller do\n import Plug.Conn\n\n @moduledoc \"\"\"\n Controllers are used to group common functionality in the same\n (pluggable) module.\n\n For example, the route:\n\n get \"\/users\/:id\", UserController, :show\n\n will invoke the `show\/2` action in the `UserController`:\n\n defmodule UserController do\n use Phoenix.Controller\n\n plug :action\n\n def show(conn, %{\"id\" => id}) do\n user = Repo.get(User, id)\n render conn, \"show.html\", user: user\n end\n end\n\n An action is just a regular function that receives the connection\n and the request parameters as arguments. The connection is a\n `Plug.Conn` struct, as specified by the Plug library.\n\n ## Connection\n\n A controller by default provides many convenience functions for\n manipulating the connection, rendering templates, and more.\n\n Those functions are imported from two modules:\n\n * `Plug.Conn` - a bunch of low-level functions to work with\n the connection\n\n * `Phoenix.Controller` - functions provided by Phoenix\n to support rendering, and other Phoenix specific behaviour\n\n ## Rendering and layouts\n\n One of the main features provided by controllers is the ability\n to do content negotiation and render templates based on\n information sent by the client. Read `render\/3` to learn more.\n\n It is also important to not confuse `Phoenix.Controller.render\/3`\n with `Phoenix.View.render\/3` in the long term. The former expects\n a connection and relies on content negotiation while the latter is\n connection-agnostic and typically invoked from your views.\n\n ## Plug pipeline\n\n As routers, controllers also have their own plug pipeline. However,\n different from routers, controllers have a single pipeline:\n\n defmodule UserController do\n use Phoenix.Controller\n\n plug :authenticate, usernames: [\"jose\", \"eric\", \"sonny\"]\n plug :action\n\n def show(conn, params) do\n # authenticated users only\n end\n\n defp authenticate(conn, options) do\n if get_session(conn, :username) in options[:usernames] do\n conn\n else\n conn |> redirect(Router.root_path) |> halt\n end\n end\n end\n\n The `:action` plug must always be invoked and it represents the action\n to be dispatched to.\n\n Check `Phoenix.Controller.Pipeline` for more information on `plug\/2`\n and how to customize the plug pipeline.\n \"\"\"\n defmacro __using__(_options) do\n quote do\n import Plug.Conn\n import Phoenix.Controller\n\n use Phoenix.Controller.Pipeline\n\n plug Phoenix.Controller.Logger\n plug :put_new_layout, {Phoenix.Controller.__layout__(__MODULE__), :application}\n plug :put_new_view, Phoenix.Controller.__view__(__MODULE__)\n end\n end\n\n @doc \"\"\"\n Returns the action name as an atom, raises if unavailable.\n \"\"\"\n @spec action_name(Plug.Conn.t) :: atom\n def action_name(conn), do: conn.private.phoenix_action\n\n @doc \"\"\"\n Returns the controller module as an atom, raises if unavailable.\n \"\"\"\n @spec controller_module(Plug.Conn.t) :: atom\n def controller_module(conn), do: conn.private.phoenix_controller\n\n @doc \"\"\"\n Returns the router module as an atom, raises if unavailable.\n \"\"\"\n @spec router_module(Plug.Conn.t) :: atom\n def router_module(conn), do: conn.private.phoenix_router\n\n @doc \"\"\"\n Returns the endpoint module as an atom, raises if unavailable.\n \"\"\"\n @spec endpoint_module(Plug.Conn.t) :: atom\n def endpoint_module(conn), do: conn.private.phoenix_endpoint\n\n @doc \"\"\"\n Sends JSON response.\n\n It uses the configured `:format_encoders` under the `:phoenix`\n application for `:json` to pick up the encoder module.\n\n ## Examples\n\n iex> json conn, %{id: 123}\n\n \"\"\"\n @spec json(Plug.Conn.t, term) :: Plug.Conn.t\n def json(conn, data) do\n encoder =\n Application.get_env(:phoenix, :format_encoders)\n |> Keyword.get(:json, Poison)\n\n send_resp(conn, conn.status || 200, \"application\/json\", encoder.encode_to_iodata!(data))\n end\n\n @doc \"\"\"\n Sends text response.\n\n ## Examples\n\n iex> text conn, \"hello\"\n\n iex> text conn, :implements_to_string\n\n \"\"\"\n @spec text(Plug.Conn.t, String.Chars.t) :: Plug.Conn.t\n def text(conn, data) do\n send_resp(conn, conn.status || 200, \"text\/plain\", to_string(data))\n end\n\n @doc \"\"\"\n Sends html response.\n\n ## Examples\n\n iex> html conn, \"...\"\n\n \"\"\"\n @spec html(Plug.Conn.t, iodata) :: Plug.Conn.t\n def html(conn, data) do\n send_resp(conn, conn.status || 200, \"text\/html\", data)\n end\n\n @doc \"\"\"\n Sends redirect response to the given url.\n\n For security, `:to` only accepts paths. Use the `:external`\n option to redirect to any URL.\n\n ## Examples\n\n iex> redirect conn, to: \"\/login\"\n\n iex> redirect conn, external: \"http:\/\/elixir-lang.org\"\n\n \"\"\"\n def redirect(conn, opts) when is_list(opts) do\n url = url(opts)\n {:safe, html} = Phoenix.HTML.html_escape(url)\n body = \"You are being redirected<\/a>.<\/body><\/html>\"\n\n conn\n |> put_resp_header(\"Location\", url)\n |> send_resp(conn.status || 302, \"text\/html\", body)\n end\n\n defp url(opts) do\n cond do\n to = opts[:to] ->\n case to do\n \"\/\" <> _ -> to\n _ -> raise ArgumentError, \"the :to option in redirect expects a path\"\n end\n external = opts[:external] ->\n external\n true ->\n raise ArgumentError, \"expected :to or :external option in redirect\/2\"\n end\n end\n\n @doc \"\"\"\n Stores the view for rendering.\n \"\"\"\n @spec put_view(Plug.Conn.t, atom) :: Plug.Conn.t\n def put_view(conn, module) do\n put_private(conn, :phoenix_view, module)\n end\n\n @doc \"\"\"\n Stores the view for rendering if one was not stored yet.\n \"\"\"\n @spec put_new_view(Plug.Conn.t, atom) :: Plug.Conn.t\n def put_new_view(conn, module) do\n update_in conn.private, &Map.put_new(&1, :phoenix_view, module)\n end\n\n @doc \"\"\"\n Retrieves the current view.\n \"\"\"\n @spec view_module(Plug.Conn.t) :: atom\n def view_module(conn) do\n conn.private.phoenix_view\n end\n\n @doc \"\"\"\n Stores the layout for rendering.\n\n The layout must be a tuple, specifying the layout view and the layout\n name, or false. In case a previous layout is set, `put_layout` also\n accepts the layout name to be given as a string or as an atom. If a\n string, it must contain the format. Passing an atom means the layout\n format will be found at rendering time, similar to the template in\n `render\/3`.\n\n ## Examples\n\n iex> layout(conn)\n false\n\n iex> conn = put_layout conn, {AppView, \"application\"}\n iex> layout(conn)\n {AppView, \"application\"}\n\n iex> conn = put_layout conn, \"print\"\n iex> layout(conn)\n {AppView, \"print\"}\n\n iex> conn = put_layout :print\n iex> layout(conn)\n {AppView, :print}\n\n \"\"\"\n @spec put_layout(Plug.Conn.t, {atom, binary} | binary | false) :: Plug.Conn.t\n def put_layout(conn, layout)\n\n def put_layout(conn, false) do\n put_private(conn, :phoenix_layout, false)\n end\n\n def put_layout(conn, {mod, layout}) when is_atom(mod) do\n put_private(conn, :phoenix_layout, {mod, layout})\n end\n\n def put_layout(conn, layout) when is_binary(layout) or is_atom(layout) do\n update_in conn.private, fn private ->\n case Map.get(private, :phoenix_layout, false) do\n {mod, _} -> Map.put(private, :phoenix_layout, {mod, layout})\n false -> raise \"cannot use put_layout\/2 with atom\/binary when layout is false, use a tuple instead\"\n end\n end\n end\n\n @doc \"\"\"\n Stores the layout for rendering if one was not stored yet.\n \"\"\"\n @spec put_new_layout(Plug.Conn.t, {atom, binary} | false) :: Plug.Conn.t\n def put_new_layout(conn, layout)\n when tuple_size(layout) == 2\n when layout == false do\n update_in conn.private, &Map.put_new(&1, :phoenix_layout, layout)\n end\n\n @doc \"\"\"\n Sets which formats have a layout when rendering.\n\n ## Examples\n\n iex> layout_formats conn\n [\"html\"]\n\n iex> put_layout_formats conn, [\"html\", \"mobile\"]\n iex> layout_formats conn\n [\"html\", \"mobile\"]\n\n \"\"\"\n @spec put_layout_formats(Plug.Conn.t, [String.t]) :: Plug.Conn.t\n def put_layout_formats(conn, formats) when is_list(formats) do\n put_private(conn, :phoenix_layout_formats, formats)\n end\n\n @doc \"\"\"\n Retrieves current layout formats.\n \"\"\"\n @spec layout_formats(Plug.Conn.t) :: [String.t]\n def layout_formats(conn) do\n Map.get(conn.private, :phoenix_layout_formats, ~w(html))\n end\n\n @doc \"\"\"\n Retrieves the current layout.\n \"\"\"\n @spec layout(Plug.Conn.t) :: {atom, String.t} | false\n def layout(conn), do: conn.private |> Map.get(:phoenix_layout, false)\n\n @doc \"\"\"\n Render the given template or the default template\n specified by the current action with the given assigns.\n\n See `render\/3` for more information.\n \"\"\"\n @spec render(Plug.Conn.t, Dict.t | binary | atom) :: Plug.Conn.t\n def render(conn, template_or_assigns \\\\ [])\n\n def render(conn, template) when is_binary(template) or is_atom(template) do\n render(conn, template, [])\n end\n\n def render(conn, assigns) do\n render(conn, action_name(conn), assigns)\n end\n\n @doc \"\"\"\n Renders the given `template` and `assigns` based on the `conn` information.\n\n Once the template is rendered, the template format is set as the response\n content type (for example, an HTML template will set \"text\/html\" as response\n content type) and the data is sent to the client with default status of 200.\n\n ## Arguments\n\n * `conn` - the `Plug.Conn` struct\n\n * `template` - which may be an atom or a string. If an atom, like `:index`,\n it will render a template with the same format as the one found in\n `conn.params[\"format\"]`. For example, for an HTML request, it will render\n the \"index.html\" template. If the template is a string, it must contain\n the extension too, like \"index.json\"\n\n * `assigns` - a dictionary with the assigns to be used in the view. Those\n assigns are merged and have higher precedence than the connection assigns\n (`conn.assigns`)\n\n ## Examples\n\n defmodule MyApp.UserController do\n use Phoenix.Controller\n\n plug :action\n\n def show(conn) do\n render conn, \"show.html\", message: \"Hello\"\n end\n end\n\n The example above renders a template \"show.html\" from the `MyApp.UserView`\n and sets the response content type to \"text\/html\".\n\n In many cases, you may want the template format to be set dynamically based\n on the request. To do so, you can pass the template name as an atom (without\n the extension):\n\n def show(conn) do\n render conn, :show, message: \"Hello\"\n end\n\n In order for the example above to work, we need to do content negotiation with\n the accepts plug before rendering. You can do so by adding the following to your\n pipeline (in the router):\n\n plug :accepts, [\"html\"]\n\n ## Views\n\n By default, Controllers render templates in a view with a similar name to the\n controller. For example, `MyApp.UserController` will render templates inside\n the `MyApp.UserView`. This information can be changed any time by using the\n `put_view\/2` function:\n\n def show(conn) do\n conn\n |> put_view(MyApp.SpecialView)\n |> render(:show, message: \"Hello\")\n end\n.\n `put_view\/2` can also be used as a plug:\n\n defmodule MyApp.UserController do\n use Phoenix.Controller\n\n plug :put_view, MyApp.SpecialView\n plug :action\n\n def show(conn) do\n render conn, :show, message: \"Hello\"\n end\n end\n\n ## Layouts\n\n Templates are often rendered inside layouts. By default, Phoenix\n will render layouts for html requests. For example:\n\n defmodule MyApp.UserController do\n use Phoenix.Controller\n\n plug :action\n\n def show(conn) do\n render conn, \"show.html\", message: \"Hello\"\n end\n end\n\n will render the \"show.html\" template inside an \"application.html\"\n template specified in `MyApp.LayoutView`. `put_layout\/2` can be used\n to change the layout, similar to how `put_view\/2` can be used to change\n the view.\n\n `layout_formats\/2` and `put_layout_formats\/2` can be used to configure\n which formats support\/require layout rendering (defaults to \"html\" only).\n \"\"\"\n @spec render(Plug.Conn.t, binary | atom, Dict.t) :: Plug.Conn.t\n def render(conn, template, assigns) when is_atom(template) do\n format =\n conn.params[\"format\"] ||\n raise \"cannot render template #{inspect template} because conn.params[\\\"format\\\"] is not set. \" <>\n \"Please set `plug :accepts, %w(html json ...)` in your pipeline.\"\n render(conn, template_name(template, format), format, assigns)\n end\n\n def render(conn, template, assigns) when is_binary(template) do\n case Path.extname(template) do\n \".\" <> format ->\n render(conn, template, format, assigns)\n \"\" ->\n raise \"cannot render template #{inspect template} without format. Use an atom if the \" <>\n \"template format is meant to be set dynamically based on the request format\"\n end\n end\n\n def render(conn, template, format, assigns) do\n assigns = to_map(assigns)\n content_type = Plug.MIME.type(format)\n conn = prepare_assigns(conn, assigns, format)\n view = Map.get(conn.private, :phoenix_view) ||\n raise \"a view module was not specified, set one with put_view\/2\"\n data = Phoenix.View.render_to_iodata(view, template,\n Map.put(conn.assigns, :conn, conn))\n send_resp(conn, conn.status || 200, content_type, data)\n end\n\n @doc \"\"\"\n Scrubs the parameters from the request.\n\n This process is two-fold:\n\n * Checks to see if the `required_key` is present\n * Changes empty parameters of `required_key` (recursively) to nils\n\n This function is useful to remove empty strings sent\n via HTML forms. If you are providing an API, there\n is likely no need to invoke `scrub_params\/2`.\n\n If the `required_key` is not present, it will\n raise `Phoenix.MissingParamError`.\n\n ## Examples\n\n iex> scrub_params(conn, \"user\")\n\n \"\"\"\n @spec scrub_params(Plug.Conn.t, [String.t]) :: Plug.Conn.t\n def scrub_params(conn, required_key) when is_binary(required_key) do\n param = Map.get(conn.params, required_key) |> scrub_param()\n\n unless param do\n raise Phoenix.MissingParamError, key: required_key\n end\n\n params = Map.put(conn.params, required_key, param)\n %{conn | params: params}\n end\n\n defp scrub_param(%{__struct__: mod} = struct) when is_atom(mod) do\n struct\n end\n defp scrub_param(%{} = param) do\n Enum.reduce(param, %{}, fn({k, v}, acc) ->\n Map.put(acc, k, scrub_param(v))\n end)\n end\n defp scrub_param(param) when is_list(param) do\n Enum.map(param, &scrub_param\/1)\n end\n defp scrub_param(param) do\n if scrub?(param), do: nil, else: param\n end\n\n defp scrub?(\" \" <> rest), do: scrub?(rest)\n defp scrub?(\"\"), do: true\n defp scrub?(_), do: false\n\n defp prepare_assigns(conn, assigns, format) do\n layout =\n case layout(conn, assigns, format) do\n {mod, layout} -> {mod, template_name(layout, format)}\n false -> false\n end\n\n update_in conn.assigns,\n & &1 |> Map.merge(assigns) |> Map.put(:layout, layout)\n end\n\n defp layout(conn, assigns, format) do\n if format in layout_formats(conn) do\n case Map.fetch(assigns, :layout) do\n {:ok, layout} -> layout\n :error -> layout(conn)\n end\n else\n false\n end\n end\n\n defp to_map(assigns) when is_map(assigns), do: assigns\n defp to_map(assigns) when is_list(assigns), do: :maps.from_list(assigns)\n defp to_map(assigns), do: Dict.merge(%{}, assigns)\n\n defp template_name(name, format) when is_atom(name), do:\n Atom.to_string(name) <> \".\" <> format\n defp template_name(name, _format) when is_binary(name), do:\n name\n\n defp send_resp(conn, default_status, default_content_type, body) do\n conn\n |> ensure_resp_content_type(default_content_type)\n |> send_resp(conn.status || default_status, body)\n end\n\n defp ensure_resp_content_type(%{resp_headers: resp_headers} = conn, content_type) do\n if List.keyfind(resp_headers, \"content-type\", 0) do\n conn\n else\n content_type = content_type <> \"; charset=utf-8\"\n %{conn | resp_headers: [{\"content-type\", content_type}|resp_headers]}\n end\n end\n\n @doc \"\"\"\n Performs content negotiation based on the available formats.\n\n It receives a connection, a list of formats that the server\n is capable of rendering and then proceeds to perform content\n negotiation based on the request information. If the client\n accepts any of the given formats, the request proceeds.\n\n If the request contains a \"format\" parameter, it is\n considered to be the format desired by the client. If no\n \"format\" parameter is available, this function will parse\n the \"accept\" header and find a matching format accordingly.\n\n It is important to notice that browsers have historically\n sent bad accept headers. For this reason, this function will\n default to \"html\" format whenever:\n\n * the accepted list of arguments contains the \"html\" format\n\n * the accept header specified more than one media type preceeded\n or followed by the wildcard media type \"*\/*\"\n\n This function raises `Phoenix.NotAcceptableError`, which is rendered\n with status 406, whenever the server cannot serve a response in any\n of the formats expected by the client.\n\n ## Examples\n\n `accepts\/2` can be invoked as a function:\n\n iex> accepts(conn, [\"html\", \"json\"])\n\n or used as a plug:\n\n plug :accepts, [\"html\", \"json\"]\n plug :accepts, ~w(html json)\n\n \"\"\"\n @spec accepts(Plug.Conn.t, [binary]) :: Plug.Conn.t | no_return\n def accepts(conn, [_|_] = accepted) do\n case Map.fetch conn.params, \"format\" do\n {:ok, format} ->\n handle_params_accept(conn, format, accepted)\n :error ->\n handle_header_accept(conn, get_req_header(conn, \"accept\"), accepted)\n end\n end\n\n @doc \"\"\"\n Enables CSRF protection.\n\n Currently used as a wrapper function for `Plug.CSRFProtection`\n and mainly serves as a function plug in `YourApp.Router`.\n\n Check `get_csrf_token\/0` and `delete_csrf_token\/0` for\n retrieving and deleting CSRF tokens.\n \"\"\"\n def protect_from_forgery(conn, opts \\\\ []) do\n Plug.CSRFProtection.call(conn, opts)\n end\n\n @doc \"\"\"\n Gets the CSRF token.\n \"\"\"\n defdelegate get_csrf_token(), to: Plug.CSRFProtection\n\n @doc \"\"\"\n Deletes any CSRF token set.\n \"\"\"\n defdelegate delete_csrf_token(), to: Plug.CSRFProtection\n\n defp handle_params_accept(conn, format, accepted) do\n if format in accepted do\n conn\n else\n raise Phoenix.NotAcceptableError,\n message: \"unknown format #{inspect format}, expected one of #{inspect accepted}\"\n end\n end\n\n # In case there is no accept header or the header is *\/*\n # we use the first format specified in the accepts list.\n defp handle_header_accept(conn, header, [first|_]) when header == [] or header == [\"*\/*\"] do\n accept(conn, first)\n end\n\n # In case there is a header, we need to parse it.\n # But before we check for *\/* because if one exists and we serve html,\n # we unfortunately need to assume it is a browser sending us a request.\n defp handle_header_accept(conn, [header|_], accepted) do\n if header =~ \"*\/*\" and \"html\" in accepted do\n accept(conn, \"html\")\n else\n parse_header_accept(conn, String.split(header, \",\"), [], accepted)\n end\n end\n\n defp parse_header_accept(conn, [h|t], acc, accepted) do\n case Plug.Conn.Utils.media_type(h) do\n {:ok, type, subtype, args} ->\n exts = parse_exts(type <> \"\/\" <> subtype)\n q = parse_q(args)\n\n if q === 1.0 && (format = find_format(exts, accepted)) do\n accept(conn, format)\n else\n parse_header_accept(conn, t, [{-q, exts}|acc], accepted)\n end\n :error ->\n parse_header_accept(conn, t, acc, accepted)\n end\n end\n\n defp parse_header_accept(conn, [], acc, accepted) do\n acc\n |> Enum.sort()\n |> Enum.find_value(&parse_header_accept(conn, &1, accepted))\n |> Kernel.||(refuse(conn, accepted))\n end\n\n defp parse_header_accept(conn, {_, exts}, accepted) do\n if format = find_format(exts, accepted) do\n accept(conn, format)\n end\n end\n\n defp parse_q(args) do\n case Map.fetch(args, \"q\") do\n {:ok, float} ->\n case Float.parse(float) do\n {float, _} -> float\n :error -> 1.0\n end\n :error ->\n 1.0\n end\n end\n\n defp parse_exts(\"*\/*\" = type), do: type\n defp parse_exts(type), do: Plug.MIME.extensions(type)\n\n defp find_format(\"*\/*\", accepted), do: Enum.fetch!(accepted, 0)\n defp find_format(exts, accepted), do: Enum.find(exts, &(&1 in accepted))\n\n defp accept(conn, format) do\n put_in conn.params[\"format\"], format\n end\n\n defp refuse(_conn, accepted) do\n raise Phoenix.NotAcceptableError,\n message: \"no supported media type in accept header, expected one of #{inspect accepted}\"\n end\n\n @doc \"\"\"\n Fetches the flash so it can be used during the request.\n \"\"\"\n def fetch_flash(conn, _opts \\\\ []) do\n flash = get_session(conn, \"phoenix_flash\") || %{}\n conn = persist_flash(conn, flash)\n\n register_before_send conn, fn conn ->\n flash = conn.private.phoenix_flash\n\n cond do\n map_size(flash) == 0 ->\n conn\n conn.status in 300..308 ->\n put_session(conn, \"phoenix_flash\", flash)\n true ->\n delete_session(conn, \"phoenix_flash\")\n end\n end\n end\n\n @doc \"\"\"\n Persists a value in flash.\n\n Returns the updated connection.\n\n ## Examples\n\n iex> conn = put_flash(conn, :notice, \"Welcome Back!\")\n iex> get_flash(conn, :notice)\n \"Welcome Back!\"\n\n \"\"\"\n def put_flash(conn, key, message) do\n persist_flash(conn, Map.put(get_flash(conn), flash_key(key), message))\n end\n\n @doc \"\"\"\n Returns a previously set flash message or nil.\n\n ## Examples\n\n iex> conn = put_flash(conn, :notice, \"Welcome Back!\")\n iex> get_flash(conn)\n %{\"notice\" => \"Welcome Back!\"}\n\n \"\"\"\n def get_flash(conn) do\n Map.get(conn.private, :phoenix_flash) ||\n raise ArgumentError, message: \"flash not fetched, call fetch_flash\/2\"\n end\n\n @doc \"\"\"\n Returns a message from flash by key\n\n ## Examples\n\n iex> conn = put_flash(conn, :notice, \"Welcome Back!\")\n iex> get_flash(conn, :notice)\n \"Welcome Back!\"\n\n \"\"\"\n def get_flash(conn, key) do\n get_flash(conn)[flash_key(key)]\n end\n\n @doc \"\"\"\n Clears all flash messages.\n \"\"\"\n def clear_flash(conn) do\n persist_flash(conn, %{})\n end\n\n defp flash_key(binary) when is_binary(binary), do: binary\n defp flash_key(atom) when is_atom(atom), do: Atom.to_string(atom)\n\n defp persist_flash(conn, value) do\n put_private(conn, :phoenix_flash, value)\n end\n\n @doc false\n def __view__(controller_module) do\n controller_module\n |> Phoenix.Naming.unsuffix(\"Controller\")\n |> Kernel.<>(\"View\")\n |> Module.concat(nil)\n end\n\n @doc false\n def __layout__(controller_module) do\n Phoenix.Naming.base_concat(controller_module, \"LayoutView\")\n end\nend\n","old_contents":"defmodule Phoenix.Controller do\n import Plug.Conn\n\n @moduledoc \"\"\"\n Controllers are used to group common functionality in the same\n (pluggable) module.\n\n For example, the route:\n\n get \"\/users\/:id\", UserController, :show\n\n will invoke the `show\/2` action in the `UserController`:\n\n defmodule UserController do\n use Phoenix.Controller\n\n plug :action\n\n def show(conn, %{\"id\" => id}) do\n user = Repo.get(User, id)\n render conn, \"show.html\", user: user\n end\n end\n\n An action is just a regular function that receives the connection\n and the request parameters as arguments. The connection is a\n `Plug.Conn` struct, as specified by the Plug library.\n\n ## Connection\n\n A controller by default provides many convenience functions for\n manipulating the connection, rendering templates, and more.\n\n Those functions are imported from two modules:\n\n * `Plug.Conn` - a bunch of low-level functions to work with\n the connection\n\n * `Phoenix.Controller` - functions provided by Phoenix\n to support rendering, and other Phoenix specific behaviour\n\n ## Rendering and layouts\n\n One of the main features provided by controllers is the ability\n to do content negotiation and render templates based on\n information sent by the client. Read `render\/3` to learn more.\n\n It is also important to not confuse `Phoenix.Controller.render\/3`\n with `Phoenix.View.render\/3` in the long term. The former expects\n a connection and relies on content negotiation while the latter is\n connection-agnostic and typically invoked from your views.\n\n ## Plug pipeline\n\n As routers, controllers also have their own plug pipeline. However,\n different from routers, controllers have a single pipeline:\n\n defmodule UserController do\n use Phoenix.Controller\n\n plug :authenticate, usernames: [\"jose\", \"eric\", \"sonny\"]\n plug :action\n\n def show(conn, params) do\n # authenticated users only\n end\n\n defp authenticate(conn, options) do\n if get_session(conn, :username) in options[:usernames] do\n conn\n else\n conn |> redirect(Router.root_path) |> halt\n end\n end\n end\n\n The `:action` plug must always be invoked and it represents the action\n to be dispatched to.\n\n Check `Phoenix.Controller.Pipeline` for more information on `plug\/2`\n and how to customize the plug pipeline.\n \"\"\"\n defmacro __using__(_options) do\n quote do\n import Plug.Conn\n import Phoenix.Controller\n\n use Phoenix.Controller.Pipeline\n\n plug Phoenix.Controller.Logger\n plug :put_new_layout, {Phoenix.Controller.__layout__(__MODULE__), :application}\n plug :put_new_view, Phoenix.Controller.__view__(__MODULE__)\n end\n end\n\n @doc \"\"\"\n Returns the action name as an atom, raises if unavailable.\n \"\"\"\n @spec action_name(Plug.Conn.t) :: atom\n def action_name(conn), do: conn.private.phoenix_action\n\n @doc \"\"\"\n Returns the controller module as an atom, raises if unavailable.\n \"\"\"\n @spec controller_module(Plug.Conn.t) :: atom\n def controller_module(conn), do: conn.private.phoenix_controller\n\n @doc \"\"\"\n Returns the router module as an atom, raises if unavailable.\n \"\"\"\n @spec router_module(Plug.Conn.t) :: atom\n def router_module(conn), do: conn.private.phoenix_router\n\n @doc \"\"\"\n Returns the endpoint module as an atom, raises if unavailable.\n \"\"\"\n @spec endpoint_module(Plug.Conn.t) :: atom\n def endpoint_module(conn), do: conn.private.phoenix_endpoint\n\n @doc \"\"\"\n Sends JSON response.\n\n It uses the configured `:format_encoders` under the `:phoenix`\n application for `:json` to pick up the encoder module.\n\n ## Examples\n\n iex> json conn, %{id: 123}\n\n \"\"\"\n @spec json(Plug.Conn.t, term) :: Plug.Conn.t\n def json(conn, data) do\n encoder =\n Application.get_env(:phoenix, :format_encoders)\n |> Keyword.get(:json, Poison)\n\n send_resp(conn, conn.status || 200, \"application\/json\", encoder.encode_to_iodata!(data))\n end\n\n @doc \"\"\"\n Sends text response.\n\n ## Examples\n\n iex> text conn, \"hello\"\n\n iex> text conn, :implements_to_string\n\n \"\"\"\n @spec text(Plug.Conn.t, String.Chars.t) :: Plug.Conn.t\n def text(conn, data) do\n send_resp(conn, conn.status || 200, \"text\/plain\", to_string(data))\n end\n\n @doc \"\"\"\n Sends html response.\n\n ## Examples\n\n iex> html conn, \"...\"\n\n \"\"\"\n @spec html(Plug.Conn.t, iodata) :: Plug.Conn.t\n def html(conn, data) do\n send_resp(conn, conn.status || 200, \"text\/html\", data)\n end\n\n @doc \"\"\"\n Sends redirect response to the given url.\n\n For security, `:to` only accepts paths. Use the `:external`\n option to redirect to any URL.\n\n ## Examples\n\n iex> redirect conn, to: \"\/login\"\n\n iex> redirect conn, external: \"http:\/\/elixir-lang.org\"\n\n \"\"\"\n def redirect(conn, opts) when is_list(opts) do\n url = url(opts)\n {:safe, html} = Phoenix.HTML.html_escape(url)\n body = \"You are being redirected<\/a>.<\/body><\/html>\"\n\n conn\n |> put_resp_header(\"Location\", url)\n |> send_resp(conn.status || 302, \"text\/html\", body)\n end\n\n defp url(opts) do\n cond do\n to = opts[:to] ->\n case to do\n \"\/\" <> _ -> to\n _ -> raise ArgumentError, \"the :to option in redirect expects a path\"\n end\n external = opts[:external] ->\n external\n true ->\n raise ArgumentError, \"expected :to or :external option in redirect\/2\"\n end\n end\n\n @doc \"\"\"\n Stores the view for rendering.\n \"\"\"\n @spec put_view(Plug.Conn.t, atom) :: Plug.Conn.t\n def put_view(conn, module) do\n put_private(conn, :phoenix_view, module)\n end\n\n @doc \"\"\"\n Stores the view for rendering if one was not stored yet.\n \"\"\"\n @spec put_new_view(Plug.Conn.t, atom) :: Plug.Conn.t\n def put_new_view(conn, module) do\n update_in conn.private, &Map.put_new(&1, :phoenix_view, module)\n end\n\n @doc \"\"\"\n Retrieves the current view.\n \"\"\"\n @spec view_module(Plug.Conn.t) :: atom\n def view_module(conn) do\n conn.private.phoenix_view\n end\n\n @doc \"\"\"\n Stores the layout for rendering.\n\n The layout must be a tuple, specifying the layout view and the layout\n name, or false. In case a previous layout is set, `put_layout` also\n accepts the layout name to be given as a string or as an atom. If a\n string, it must contain the format. Passing an atom means the layout\n format will be found at rendering time, similar to the template in\n `render\/3`.\n\n ## Examples\n\n iex> layout(conn)\n false\n\n iex> conn = put_layout conn, {AppView, \"application\"}\n iex> layout(conn)\n {AppView, \"application\"}\n\n iex> conn = put_layout conn, \"print\"\n iex> layout(conn)\n {AppView, \"print\"}\n\n iex> conn = put_layout :print\n iex> layout(conn)\n {AppView, :print}\n\n \"\"\"\n @spec put_layout(Plug.Conn.t, {atom, binary} | binary | false) :: Plug.Conn.t\n def put_layout(conn, layout)\n\n def put_layout(conn, false) do\n put_private(conn, :phoenix_layout, false)\n end\n\n def put_layout(conn, {mod, layout}) when is_atom(mod) do\n put_private(conn, :phoenix_layout, {mod, layout})\n end\n\n def put_layout(conn, layout) when is_binary(layout) or is_atom(layout) do\n update_in conn.private, fn private ->\n case Map.get(private, :phoenix_layout, false) do\n {mod, _} -> Map.put(private, :phoenix_layout, {mod, layout})\n false -> raise \"cannot use put_layout\/2 with atom\/binary when layout is false, use a tuple instead\"\n end\n end\n end\n\n @doc \"\"\"\n Stores the layout for rendering if one was not stored yet.\n \"\"\"\n @spec put_new_layout(Plug.Conn.t, {atom, binary} | false) :: Plug.Conn.t\n def put_new_layout(conn, layout)\n when tuple_size(layout) == 2\n when layout == false do\n update_in conn.private, &Map.put_new(&1, :phoenix_layout, layout)\n end\n\n @doc \"\"\"\n Sets which formats have a layout when rendering.\n\n ## Examples\n\n iex> layout_formats conn\n [\"html\"]\n\n iex> put_layout_formats conn, [\"html\", \"mobile\"]\n iex> layout_formats conn\n [\"html\", \"mobile\"]\n\n \"\"\"\n @spec put_layout_formats(Plug.Conn.t, [String.t]) :: Plug.Conn.t\n def put_layout_formats(conn, formats) when is_list(formats) do\n put_private(conn, :phoenix_layout_formats, formats)\n end\n\n @doc \"\"\"\n Retrieves current layout formats.\n \"\"\"\n @spec layout_formats(Plug.Conn.t) :: [String.t]\n def layout_formats(conn) do\n Map.get(conn.private, :phoenix_layout_formats, ~w(html))\n end\n\n @doc \"\"\"\n Retrieves the current layout.\n \"\"\"\n @spec layout(Plug.Conn.t) :: {atom, String.t} | false\n def layout(conn), do: conn.private |> Map.get(:phoenix_layout, false)\n\n @doc \"\"\"\n Render the given template or the default template\n specified by the current action with the given assigns.\n\n See `render\/3` for more information.\n \"\"\"\n @spec render(Plug.Conn.t, Dict.t | binary | atom) :: Plug.Conn.t\n def render(conn, template_or_assigns \\\\ [])\n\n def render(conn, template) when is_binary(template) or is_atom(template) do\n render(conn, template, [])\n end\n\n def render(conn, assigns) do\n render(conn, action_name(conn), assigns)\n end\n\n @doc \"\"\"\n Renders the given `template` and `assigns` based on the `conn` information.\n\n Once the template is rendered, the template format is set as the response\n content type (for example, an HTML template will set \"text\/html\" as response\n content type) and the data is sent to the client with default status of 200.\n\n ## Arguments\n\n * `conn` - the `Plug.Conn` struct\n\n * `template` - which may be an atom or a string. If an atom, like `:index`,\n it will render a template with the same format as the one found in\n `conn.params[\"format\"]`. For example, for an HTML request, it will render\n the \"index.html\" template. If the template is a string, it must contain\n the extension too, like \"index.json\"\n\n * `assigns` - a dictionary with the assigns to be used in the view. Those\n assigns are merged and have higher precedence than the connection assigns\n (`conn.assigns`)\n\n ## Examples\n\n defmodule MyApp.UserController do\n use Phoenix.Controller\n\n plug :action\n\n def show(conn) do\n render conn, \"show.html\", message: \"Hello\"\n end\n end\n\n The example above renders a template \"show.html\" from the `MyApp.UserView`\n and sets the response content type to \"text\/html\".\n\n In many cases, you may want the template format to be set dynamically based\n on the request. To do so, you can pass the template name as an atom (without\n the extension):\n\n def show(conn) do\n render conn, :show, message: \"Hello\"\n end\n\n In order for the example above to work, we need to do content negotiation with\n the accepts plug before rendering. You can do so by adding the following to your\n pipeline (in the router):\n\n plug :accepts, [\"html\"]\n\n ## Views\n\n By default, Controllers render templates in a view with a similar name to the\n controller. For example, `MyApp.UserController` will render templates inside\n the `MyApp.UserView`. This information can be changed any time by using the\n `put_view\/2` function:\n\n def show(conn) do\n conn\n |> put_view(MyApp.SpecialView)\n |> render(:show, message: \"Hello\")\n end\n.\n `put_view\/2` can also be used as a plug:\n\n defmodule MyApp.UserController do\n use Phoenix.Controller\n\n plug :put_view, MyApp.SpecialView\n plug :action\n\n def show(conn) do\n render conn, :show, message: \"Hello\"\n end\n end\n\n ## Layouts\n\n Templates are often rendered inside layouts. By default, Phoenix\n will render layouts for html requests. For example:\n\n defmodule MyApp.UserController do\n use Phoenix.Controller\n\n plug :action\n\n def show(conn) do\n render conn, \"show.html\", message: \"Hello\"\n end\n end\n\n will render the \"show.html\" template inside an \"application.html\"\n template specified in `MyApp.LayoutView`. `put_layout\/2` can be used\n to change the layout, similar to how `put_view\/2` can be used to change\n the view.\n\n `layout_formats\/2` and `put_layout_formats\/2` can be used to configure\n which formats support\/require layout rendering (defaults to \"html\" only).\n \"\"\"\n @spec render(Plug.Conn.t, binary | atom, Dict.t) :: Plug.Conn.t\n def render(conn, template, assigns) when is_atom(template) do\n format =\n conn.params[\"format\"] ||\n raise \"cannot render template #{inspect template} because conn.params[\\\"format\\\"] is not set. \" <>\n \"Please set `plug :accepts, %w(html json ...)` in your pipeline.\"\n render(conn, template_name(template, format), format, assigns)\n end\n\n def render(conn, template, assigns) when is_binary(template) do\n case Path.extname(template) do\n \".\" <> format ->\n render(conn, template, format, assigns)\n \"\" ->\n raise \"cannot render template #{inspect template} without format. Use an atom if the \" <>\n \"template format is meant to be set dynamically based on the request format\"\n end\n end\n\n def render(conn, template, format, assigns) do\n assigns = to_map(assigns)\n content_type = Plug.MIME.type(format)\n conn = prepare_assigns(conn, assigns, format)\n view = Map.get(conn.private, :phoenix_view) ||\n raise \"a view module was not specified, set one with put_view\/2\"\n data = Phoenix.View.render_to_iodata(view, template,\n Map.put(conn.assigns, :conn, conn))\n send_resp(conn, conn.status || 200, content_type, data)\n end\n\n @doc \"\"\"\n Scrubs the parameters from the request.\n\n This process is two-fold:\n\n * Checks to see if the `required_key` is present\n * Changes empty parameters of `required_key` (recursively) to nils\n\n This function is useful to remove empty strings sent\n via HTML forms. If you are providing an API, there\n is likely no need to invoke `scrub_params\/2`.\n\n If the `required_key` is not present, it will\n raise `Phoenix.MissingParamError`.\n\n ## Examples\n\n iex> scrub_params(conn, \"user\")\n\n \"\"\"\n @spec scrub_params(Plug.Conn.t, [String.t]) :: Plug.Conn.t\n def scrub_params(conn, required_key) when is_binary(required_key) do\n param = Map.get(conn.params, required_key) |> scrub_param()\n\n unless param do\n raise Phoenix.MissingParamError, key: required_key\n end\n\n params = Map.put(conn.params, required_key, param)\n %{conn | params: params}\n end\n\n defp scrub_param(%{__struct__: mod} = struct) when is_atom(mod) do\n struct\n end\n defp scrub_param(%{} = param) do\n Enum.reduce(param, %{}, fn({k, v}, acc) ->\n Map.put(acc, k, scrub_param(v))\n end)\n end\n defp scrub_param(param) when is_list(param) do\n Enum.map(param, &scrub_param\/1)\n end\n defp scrub_param(param) do\n if scrub?(param), do: nil, else: param\n end\n\n defp scrub?(\" \" <> rest), do: scrub?(rest)\n defp scrub?(\"\"), do: true\n defp scrub?(_), do: false\n\n defp prepare_assigns(conn, assigns, format) do\n layout =\n case layout(conn, assigns, format) do\n {mod, layout} -> {mod, template_name(layout, format)}\n false -> false\n end\n\n update_in conn.assigns,\n & &1 |> Map.merge(assigns) |> Map.put(:layout, layout)\n end\n\n defp layout(conn, assigns, format) do\n if format in layout_formats(conn) do\n case Map.fetch(assigns, :layout) do\n {:ok, layout} -> layout\n :error -> layout(conn)\n end\n else\n false\n end\n end\n\n defp to_map(assigns) when is_map(assigns), do: assigns\n defp to_map(assigns) when is_list(assigns), do: :maps.from_list(assigns)\n defp to_map(assigns), do: Dict.merge(%{}, assigns)\n\n defp template_name(name, format) when is_atom(name), do:\n Atom.to_string(name) <> \".\" <> format\n defp template_name(name, _format) when is_binary(name), do:\n name\n\n defp send_resp(conn, default_status, default_content_type, body) do\n case get_resp_header(conn, \"content-type\") do\n [] -> put_resp_content_type(conn, default_content_type)\n _ -> conn\n end\n |> send_resp(conn.status || default_status, body)\n end\n\n @doc \"\"\"\n Performs content negotiation based on the available formats.\n\n It receives a connection, a list of formats that the server\n is capable of rendering and then proceeds to perform content\n negotiation based on the request information. If the client\n accepts any of the given formats, the request proceeds.\n\n If the request contains a \"format\" parameter, it is\n considered to be the format desired by the client. If no\n \"format\" parameter is available, this function will parse\n the \"accept\" header and find a matching format accordingly.\n\n It is important to notice that browsers have historically\n sent bad accept headers. For this reason, this function will\n default to \"html\" format whenever:\n\n * the accepted list of arguments contains the \"html\" format\n\n * the accept header specified more than one media type preceeded\n or followed by the wildcard media type \"*\/*\"\n\n This function raises `Phoenix.NotAcceptableError`, which is rendered\n with status 406, whenever the server cannot serve a response in any\n of the formats expected by the client.\n\n ## Examples\n\n `accepts\/2` can be invoked as a function:\n\n iex> accepts(conn, [\"html\", \"json\"])\n\n or used as a plug:\n\n plug :accepts, [\"html\", \"json\"]\n plug :accepts, ~w(html json)\n\n \"\"\"\n @spec accepts(Plug.Conn.t, [binary]) :: Plug.Conn.t | no_return\n def accepts(conn, [_|_] = accepted) do\n case Map.fetch conn.params, \"format\" do\n {:ok, format} ->\n handle_params_accept(conn, format, accepted)\n :error ->\n handle_header_accept(conn, get_req_header(conn, \"accept\"), accepted)\n end\n end\n\n @doc \"\"\"\n Enables CSRF protection.\n\n Currently used as a wrapper function for `Plug.CSRFProtection`\n and mainly serves as a function plug in `YourApp.Router`.\n\n Check `get_csrf_token\/0` and `delete_csrf_token\/0` for\n retrieving and deleting CSRF tokens.\n \"\"\"\n def protect_from_forgery(conn, opts \\\\ []) do\n Plug.CSRFProtection.call(conn, opts)\n end\n\n @doc \"\"\"\n Gets the CSRF token.\n \"\"\"\n defdelegate get_csrf_token(), to: Plug.CSRFProtection\n\n @doc \"\"\"\n Deletes any CSRF token set.\n \"\"\"\n defdelegate delete_csrf_token(), to: Plug.CSRFProtection\n\n defp handle_params_accept(conn, format, accepted) do\n if format in accepted do\n conn\n else\n raise Phoenix.NotAcceptableError,\n message: \"unknown format #{inspect format}, expected one of #{inspect accepted}\"\n end\n end\n\n # In case there is no accept header or the header is *\/*\n # we use the first format specified in the accepts list.\n defp handle_header_accept(conn, header, [first|_]) when header == [] or header == [\"*\/*\"] do\n accept(conn, first)\n end\n\n # In case there is a header, we need to parse it.\n # But before we check for *\/* because if one exists and we serve html,\n # we unfortunately need to assume it is a browser sending us a request.\n defp handle_header_accept(conn, [header|_], accepted) do\n if header =~ \"*\/*\" and \"html\" in accepted do\n accept(conn, \"html\")\n else\n parse_header_accept(conn, String.split(header, \",\"), [], accepted)\n end\n end\n\n defp parse_header_accept(conn, [h|t], acc, accepted) do\n case Plug.Conn.Utils.media_type(h) do\n {:ok, type, subtype, args} ->\n exts = parse_exts(type <> \"\/\" <> subtype)\n q = parse_q(args)\n\n if q === 1.0 && (format = find_format(exts, accepted)) do\n accept(conn, format)\n else\n parse_header_accept(conn, t, [{-q, exts}|acc], accepted)\n end\n :error ->\n parse_header_accept(conn, t, acc, accepted)\n end\n end\n\n defp parse_header_accept(conn, [], acc, accepted) do\n acc\n |> Enum.sort()\n |> Enum.find_value(&parse_header_accept(conn, &1, accepted))\n |> Kernel.||(refuse(conn, accepted))\n end\n\n defp parse_header_accept(conn, {_, exts}, accepted) do\n if format = find_format(exts, accepted) do\n accept(conn, format)\n end\n end\n\n defp parse_q(args) do\n case Map.fetch(args, \"q\") do\n {:ok, float} ->\n case Float.parse(float) do\n {float, _} -> float\n :error -> 1.0\n end\n :error ->\n 1.0\n end\n end\n\n defp parse_exts(\"*\/*\" = type), do: type\n defp parse_exts(type), do: Plug.MIME.extensions(type)\n\n defp find_format(\"*\/*\", accepted), do: Enum.fetch!(accepted, 0)\n defp find_format(exts, accepted), do: Enum.find(exts, &(&1 in accepted))\n\n defp accept(conn, format) do\n put_in conn.params[\"format\"], format\n end\n\n defp refuse(_conn, accepted) do\n raise Phoenix.NotAcceptableError,\n message: \"no supported media type in accept header, expected one of #{inspect accepted}\"\n end\n\n @doc \"\"\"\n Fetches the flash so it can be used during the request.\n \"\"\"\n def fetch_flash(conn, _opts \\\\ []) do\n flash = get_session(conn, \"phoenix_flash\") || %{}\n conn = persist_flash(conn, flash)\n\n register_before_send conn, fn conn ->\n flash = conn.private.phoenix_flash\n\n cond do\n map_size(flash) == 0 ->\n conn\n conn.status in 300..308 ->\n put_session(conn, \"phoenix_flash\", flash)\n true ->\n delete_session(conn, \"phoenix_flash\")\n end\n end\n end\n\n @doc \"\"\"\n Persists a value in flash.\n\n Returns the updated connection.\n\n ## Examples\n\n iex> conn = put_flash(conn, :notice, \"Welcome Back!\")\n iex> get_flash(conn, :notice)\n \"Welcome Back!\"\n\n \"\"\"\n def put_flash(conn, key, message) do\n persist_flash(conn, Map.put(get_flash(conn), flash_key(key), message))\n end\n\n @doc \"\"\"\n Returns a previously set flash message or nil.\n\n ## Examples\n\n iex> conn = put_flash(conn, :notice, \"Welcome Back!\")\n iex> get_flash(conn)\n %{\"notice\" => \"Welcome Back!\"}\n\n \"\"\"\n def get_flash(conn) do\n Map.get(conn.private, :phoenix_flash) ||\n raise ArgumentError, message: \"flash not fetched, call fetch_flash\/2\"\n end\n\n @doc \"\"\"\n Returns a message from flash by key\n\n ## Examples\n\n iex> conn = put_flash(conn, :notice, \"Welcome Back!\")\n iex> get_flash(conn, :notice)\n \"Welcome Back!\"\n\n \"\"\"\n def get_flash(conn, key) do\n get_flash(conn)[flash_key(key)]\n end\n\n @doc \"\"\"\n Clears all flash messages.\n \"\"\"\n def clear_flash(conn) do\n persist_flash(conn, %{})\n end\n\n defp flash_key(binary) when is_binary(binary), do: binary\n defp flash_key(atom) when is_atom(atom), do: Atom.to_string(atom)\n\n defp persist_flash(conn, value) do\n put_private(conn, :phoenix_flash, value)\n end\n\n @doc false\n def __view__(controller_module) do\n controller_module\n |> Phoenix.Naming.unsuffix(\"Controller\")\n |> Kernel.<>(\"View\")\n |> Module.concat(nil)\n end\n\n @doc false\n def __layout__(controller_module) do\n Phoenix.Naming.base_concat(controller_module, \"LayoutView\")\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"b27f954079be2148802e83074775e2439c15b560","subject":"adds docs and type specs to Discovery.put_belongs_to_many_categories","message":"adds docs and type specs to Discovery.put_belongs_to_many_categories\n","repos":"ello\/apex,ello\/apex,ello\/apex","old_file":"apps\/ello_core\/lib\/ello_core\/discovery.ex","new_file":"apps\/ello_core\/lib\/ello_core\/discovery.ex","new_contents":"defmodule Ello.Core.Discovery do\n import Ecto.Query\n alias Ello.Core.{Repo, Network, Discovery}\n alias Discovery.{Category, Promotional}\n alias Network.User\n\n @moduledoc \"\"\"\n Responsible for retreiving and loading categories and related data.\n\n Handles database queryies, preloading relations, and fetching cached values.\n \"\"\"\n\n @doc \"Find a single category by slug or id - including promotionals\"\n @spec category(String.t | integer, current_user :: User.t | nil) :: Category.t\n def category(id_or_slug, current_user \\\\ nil)\n def category(slug, current_user) when is_binary(slug) do\n Category\n |> Repo.get_by!(slug: slug)\n |> include_promotionals(current_user)\n |> load_images\n end\n def category(id, current_user) when is_number(id) do\n Category\n |> Repo.get!(id)\n |> include_promotionals(current_user)\n |> load_images\n end\n\n def categories_by_ids([]), do: []\n def categories_by_ids(ids) when is_list(ids) do\n Category\n |> where([c], c.id in ^ids)\n |> include_inactive_categories(false)\n |> include_meta_categories(false)\n |> Repo.all\n |> load_images\n end\n\n @type categorizable :: User.t | Post.t | [User.t | Post.t]\n\n @doc \"\"\"\n Fetches the categories for a user or post\n\n Given a user or post struct (or list of users or posts), this function will\n fetch all the categories and include them in the struct (or list of structs).\n \"\"\"\n @spec put_belongs_to_many_categories(categorizables :: categorizable | nil) :: categorizable | nil\n def put_belongs_to_many_categories(nil), do: nil\n def put_belongs_to_many_categories([]), do: []\n def put_belongs_to_many_categories(%{} = categorizable),\n do: hd(put_belongs_to_many_categories([categorizable]))\n def put_belongs_to_many_categories(categorizables) do\n categories = categorizables\n |> Enum.flat_map(&(&1.category_ids))\n |> Discovery.categories_by_ids\n |> Enum.group_by(&(&1.id))\n Enum.map categorizables, fn\n %{category_ids: []} = categorizable -> categorizable\n categorizable ->\n categorizable_categories = categories\n |> Map.take(categorizable.category_ids)\n |> Map.values\n |> List.flatten\n Map.put(categorizable, :categories, categorizable_categories)\n end\n end\n\n @doc \"\"\"\n Return all Categories with related promotionals their user.\n\n By default neither \"meta\" categories nor \"inactive\" categories are included\n in the results. Pass `meta: true` or `inactive: true` as opts to include them.\n \"\"\"\n @spec categories(current_user :: User.t, opts :: Keyword.t) :: [Category.t]\n def categories(current_user \\\\ nil, opts \\\\ []) do\n Category\n |> include_inactive_categories(opts[:inactive])\n |> include_meta_categories(opts[:meta])\n |> priority_order\n |> Repo.all\n |> include_promotionals(current_user)\n |> load_images\n end\n\n # Category Scopes\n defp priority_order(q),\n do: order_by(q, [:level, :order])\n\n defp include_inactive_categories(q, true), do: q\n defp include_inactive_categories(q, _),\n do: where(q, [c], not is_nil(c.level))\n\n defp include_meta_categories(q, true), do: q\n defp include_meta_categories(q, _),\n do: where(q, [c], c.level != \"meta\" or is_nil(c.level))\n\n defp include_promotionals(categories, current_user) do\n Repo.preload(categories, promotionals: [user: &Network.users(&1, current_user)])\n end\n\n defp load_images(categories) when is_list(categories) do\n Enum.map(categories, &load_images\/1)\n end\n defp load_images(%Category{promotionals: promos} = category) when is_list(promos) do\n category\n |> Category.load_images\n |> Map.put(:promotionals, Enum.map(promos, &Promotional.load_images\/1))\n end\n defp load_images(%Category{} = category) do\n Category.load_images(category)\n end\nend\n","old_contents":"defmodule Ello.Core.Discovery do\n import Ecto.Query\n alias Ello.Core.{Repo, Network, Discovery}\n alias Discovery.{Category, Promotional}\n alias Network.User\n\n @moduledoc \"\"\"\n Responsible for retreiving and loading categories and related data.\n\n Handles database queryies, preloading relations, and fetching cached values.\n \"\"\"\n\n @doc \"Find a single category by slug or id - including promotionals\"\n @spec category(String.t | integer, current_user :: User.t | nil) :: Category.t\n def category(id_or_slug, current_user \\\\ nil)\n def category(slug, current_user) when is_binary(slug) do\n Category\n |> Repo.get_by!(slug: slug)\n |> include_promotionals(current_user)\n |> load_images\n end\n def category(id, current_user) when is_number(id) do\n Category\n |> Repo.get!(id)\n |> include_promotionals(current_user)\n |> load_images\n end\n\n def categories_by_ids([]), do: []\n def categories_by_ids(ids) when is_list(ids) do\n Category\n |> where([c], c.id in ^ids)\n |> include_inactive_categories(false)\n |> include_meta_categories(false)\n |> Repo.all\n |> load_images\n end\n\n def put_belongs_to_many_categories(nil), do: nil\n def put_belongs_to_many_categories([]), do: []\n def put_belongs_to_many_categories(%{} = categorizable),\n do: hd(put_belongs_to_many_categories([categorizable]))\n def put_belongs_to_many_categories(categorizables) do\n categories = categorizables\n |> Enum.flat_map(&(&1.category_ids))\n |> Discovery.categories_by_ids\n |> Enum.group_by(&(&1.id))\n Enum.map categorizables, fn\n %{category_ids: []} = categorizable -> categorizable\n categorizable ->\n categorizable_categories = categories\n |> Map.take(categorizable.category_ids)\n |> Map.values\n |> List.flatten\n Map.put(categorizable, :categories, categorizable_categories)\n end\n end\n\n @doc \"\"\"\n Return all Categories with related promotionals their user.\n\n By default neither \"meta\" categories nor \"inactive\" categories are included\n in the results. Pass `meta: true` or `inactive: true` as opts to include them.\n \"\"\"\n @spec categories(current_user :: User.t, opts :: Keyword.t) :: [Category.t]\n def categories(current_user \\\\ nil, opts \\\\ []) do\n Category\n |> include_inactive_categories(opts[:inactive])\n |> include_meta_categories(opts[:meta])\n |> priority_order\n |> Repo.all\n |> include_promotionals(current_user)\n |> load_images\n end\n\n # Category Scopes\n defp priority_order(q),\n do: order_by(q, [:level, :order])\n\n defp include_inactive_categories(q, true), do: q\n defp include_inactive_categories(q, _),\n do: where(q, [c], not is_nil(c.level))\n\n defp include_meta_categories(q, true), do: q\n defp include_meta_categories(q, _),\n do: where(q, [c], c.level != \"meta\" or is_nil(c.level))\n\n defp include_promotionals(categories, current_user) do\n Repo.preload(categories, promotionals: [user: &Network.users(&1, current_user)])\n end\n\n defp load_images(categories) when is_list(categories) do\n Enum.map(categories, &load_images\/1)\n end\n defp load_images(%Category{promotionals: promos} = category) when is_list(promos) do\n category\n |> Category.load_images\n |> Map.put(:promotionals, Enum.map(promos, &Promotional.load_images\/1))\n end\n defp load_images(%Category{} = category) do\n Category.load_images(category)\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"ee4606b03bc9ed420fb63bf57221fe62ee623216","subject":"Fix SysCalls.sync() tests","message":"Fix SysCalls.sync() tests\n","repos":"FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os","old_file":"farmbot_os\/test\/farmbot_os\/sys_calls_test.exs","new_file":"farmbot_os\/test\/farmbot_os\/sys_calls_test.exs","new_contents":"defmodule FarmbotOS.SysCallsTest do\n use ExUnit.Case, async: true\n alias FarmbotOS.SysCalls\n alias FarmbotCore.Asset\n\n alias FarmbotCore.Asset.{\n Repo,\n Sequence,\n BoxLed\n }\n\n use Mimic\n setup :verify_on_exit!\n\n test \"emergency_unlock\" do\n expect(FarmbotFirmware, :command, fn {:command_emergency_unlock, []} ->\n :qqq\n end)\n\n assert :ok == SysCalls.emergency_unlock()\n end\n\n test \"emergency_lock\" do\n expect(FarmbotFirmware, :command, fn {:command_emergency_lock, []} ->\n :qqq\n end)\n\n assert :ok == SysCalls.emergency_lock()\n end\n\n test \"wait()\" do\n now = :os.system_time(:millisecond)\n SysCalls.wait(100)\n later = :os.system_time(:millisecond)\n assert later >= now + 100\n end\n\n test \"named_pin()\" do\n result1 = SysCalls.named_pin(\"x\", 1)\n assert result1 == {:error, \"unknown pin kind: x of id: 1\"}\n\n result2 = SysCalls.named_pin(\"BoxLed23\", 45)\n assert %BoxLed{id: 23} == result2\n\n expect(Asset, :get_sensor, fn id ->\n if id == 67 do\n %{id: id, is_mock: :yep}\n else\n nil\n end\n end)\n\n result3 = SysCalls.named_pin(\"Sensor\", 67)\n assert %{id: 67, is_mock: :yep} == result3\n\n result4 = SysCalls.named_pin(\"Sensor\", 89)\n assert {:error, \"Could not find peripheral by id: 89\"} == result4\n\n expect(Asset, :get_peripheral, fn [id: id] ->\n if id == 10 do\n %{id: id, is_mock: :yep}\n else\n nil\n end\n end)\n\n result5 = SysCalls.named_pin(\"Peripheral\", 10)\n assert %{id: 10, is_mock: :yep} == result5\n\n result6 = SysCalls.named_pin(\"Peripheral\", 11)\n assert {:error, \"Could not find peripheral by id: 11\"} == result6\n end\n\n test \"sync() success\" do\n # Expect 5 calls and an :ok response.\n expect(FarmbotExt.API.Reconciler, :sync_group, 5, fn changeset, _group ->\n changeset\n end)\n\n expect(FarmbotExt.API, :get_changeset, fn module ->\n {:ok, %{wut: module}}\n end)\n\n assert :ok == SysCalls.sync()\n end\n\n test \"sync() failure\" do\n # Expect 5 calls and an :ok response.\n expect(FarmbotExt.API, :get_changeset, fn FarmbotCore.Asset.Sync ->\n \"this is a test\"\n end)\n\n assert {:error, \"\\\"this is a test\\\"\"} == SysCalls.sync()\n end\n\n test \"get_sequence(id)\" do\n _ = Repo.delete_all(Sequence)\n fake_id = 28\n fake_name = \"X\"\n\n fake_params = %{\n id: fake_id,\n name: fake_name,\n args: %{\n sequence_name: fake_name\n },\n kind: \"sequence\",\n body: []\n }\n\n assert SysCalls.get_sequence(fake_id) == {:error, \"sequence not found\"}\n\n %Sequence{id: id} =\n %Sequence{}\n |> Sequence.changeset(fake_params)\n |> Repo.insert!()\n\n assert id == fake_id\n result = SysCalls.get_sequence(fake_id)\n assert result.args == fake_params[:args]\n assert result.kind == :sequence\n assert result.body == fake_params[:body]\n end\n\n test \"coordinate()\" do\n expected = %{x: 1, y: 2, z: 3}\n actual = SysCalls.coordinate(1, 2, 3)\n assert expected == actual\n end\n\n test \"nothing\" do\n assert SysCalls.nothing() == nil\n end\n\n test \"install_first_party_farmware()\" do\n expected = {:error, \"install_first_party_farmware not yet supported\"}\n actual = SysCalls.install_first_party_farmware()\n assert expected == actual\n end\nend\n","old_contents":"defmodule FarmbotOS.SysCallsTest do\n use ExUnit.Case, async: true\n alias FarmbotOS.SysCalls\n alias FarmbotCore.Asset\n\n alias FarmbotCore.Asset.{\n Repo,\n Sequence,\n BoxLed\n }\n\n use Mimic\n setup :verify_on_exit!\n\n test \"emergency_unlock\" do\n expect(FarmbotFirmware, :command, fn {:command_emergency_unlock, []} ->\n :qqq\n end)\n\n assert :ok == SysCalls.emergency_unlock()\n end\n\n test \"emergency_lock\" do\n expect(FarmbotFirmware, :command, fn {:command_emergency_lock, []} ->\n :qqq\n end)\n\n assert :ok == SysCalls.emergency_lock()\n end\n\n test \"wait()\" do\n now = :os.system_time(:millisecond)\n SysCalls.wait(100)\n later = :os.system_time(:millisecond)\n assert later >= now + 100\n end\n\n test \"named_pin()\" do\n result1 = SysCalls.named_pin(\"x\", 1)\n assert result1 == {:error, \"unknown pin kind: x of id: 1\"}\n\n result2 = SysCalls.named_pin(\"BoxLed23\", 45)\n assert %BoxLed{id: 23} == result2\n\n expect(Asset, :get_sensor, fn id ->\n if id == 67 do\n %{id: id, is_mock: :yep}\n else\n nil\n end\n end)\n\n result3 = SysCalls.named_pin(\"Sensor\", 67)\n assert %{id: 67, is_mock: :yep} == result3\n\n result4 = SysCalls.named_pin(\"Sensor\", 89)\n assert {:error, \"Could not find peripheral by id: 89\"} == result4\n\n expect(Asset, :get_peripheral, fn [id: id] ->\n if id == 10 do\n %{id: id, is_mock: :yep}\n else\n nil\n end\n end)\n\n result5 = SysCalls.named_pin(\"Peripheral\", 10)\n assert %{id: 10, is_mock: :yep} == result5\n\n result6 = SysCalls.named_pin(\"Peripheral\", 11)\n assert {:error, \"Could not find peripheral by id: 11\"} == result6\n end\n\n test \"sync() success\" do\n # Expect 5 calls and an :ok response.\n expect(FarmbotExt.API.Reconciler, :sync_group, 5, fn changeset, _group ->\n changeset\n end)\n\n assert :ok == SysCalls.sync()\n end\n\n test \"sync() failure\" do\n # Expect 5 calls and an :ok response.\n expect(FarmbotExt.API, :get_changeset, fn FarmbotCore.Asset.Sync ->\n \"this is a test\"\n end)\n\n assert {:error, \"\\\"this is a test\\\"\"} == SysCalls.sync()\n end\n\n test \"get_sequence(id)\" do\n _ = Repo.delete_all(Sequence)\n fake_id = 28\n fake_name = \"X\"\n\n fake_params = %{\n id: fake_id,\n name: fake_name,\n args: %{\n sequence_name: fake_name\n },\n kind: \"sequence\",\n body: []\n }\n\n assert SysCalls.get_sequence(fake_id) == {:error, \"sequence not found\"}\n\n %Sequence{id: id} =\n %Sequence{}\n |> Sequence.changeset(fake_params)\n |> Repo.insert!()\n\n assert id == fake_id\n result = SysCalls.get_sequence(fake_id)\n assert result.args == fake_params[:args]\n assert result.kind == :sequence\n assert result.body == fake_params[:body]\n end\n\n test \"coordinate()\" do\n expected = %{x: 1, y: 2, z: 3}\n actual = SysCalls.coordinate(1, 2, 3)\n assert expected == actual\n end\n\n test \"nothing\" do\n assert SysCalls.nothing() == nil\n end\n\n test \"install_first_party_farmware()\" do\n expected = {:error, \"install_first_party_farmware not yet supported\"}\n actual = SysCalls.install_first_party_farmware()\n assert expected == actual\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"2276447716c15d9c535a8b6958d0992221ef96fd","subject":"Added media.evercam.io -> www.evercam.io redirect","message":"Added media.evercam.io -> www.evercam.io redirect\n","repos":"shankardevy\/evercam-media,evercam\/evercam-media,shankardevy\/evercam-media,shankardevy\/evercam-media,pb-pravin\/evercam-media,evercam\/evercam-server,evercam\/evercam-server","old_file":"web\/controllers\/page_controller.ex","new_file":"web\/controllers\/page_controller.ex","new_contents":"defmodule Media.PageController do\n use Media.Web, :controller\n\n plug :action\n\n def index(conn, _params) do\n redirect conn, external: \"http:\/\/www.evercam.io\"\n end\nend\n","old_contents":"defmodule Media.PageController do\n use Media.Web, :controller\n\n plug :action\n\n def index(conn, _params) do\n render conn, \"index.html\"\n end\nend\n","returncode":0,"stderr":"","license":"agpl-3.0","lang":"Elixir"} {"commit":"708bf845056bc5f824f7d6acfe343f7a33bafbc9","subject":"Fix get_project()","message":"Fix get_project()\n","repos":"dainst\/idai-field-web,dainst\/idai-field-web,dainst\/idai-field-web","old_file":"api\/lib\/api\/documents\/index.ex","new_file":"api\/lib\/api\/documents\/index.ex","new_contents":"defmodule Api.Documents.Index do\n require Logger\n alias Api.Documents.Mapping\n alias Api.Documents.Query\n alias Api.Documents.Filter\n alias Core.ProjectConfigLoader\n\n @max_geometries 10000\n @exists_geometries [\"resource.geometry\"]\n @fields_geometries [\"resource.category\", \"resource.geometry\", \"resource.identifier\", \"resource.id\", \"project\"]\n\n def get(id) do\n Query.init(\"_id:#{id}\", 1)\n |> build_post_atomize()\n |> Mapping.map_single()\n end\n\n def search(q, size, from, filters, must_not, exists, readable_projects) do\n {filters, must_not, project_conf} = preprocess(filters, must_not)\n Query.init(q, size, from)\n |> Query.track_total\n |> Query.add_aggregations()\n |> Query.add_filters(filters)\n |> Query.add_must_not(must_not)\n |> Query.add_exists(exists)\n |> Query.set_readable_projects(readable_projects)\n |> build_post_atomize\n |> Mapping.map(project_conf)\n end\n\n def search_geometries(q, filters, must_not, exists, readable_projects) do\n {filters, must_not, project_conf} = preprocess(filters, must_not)\n Query.init(q, @max_geometries)\n |> Query.add_filters(filters)\n |> Query.add_must_not(must_not)\n |> Query.add_exists(exists)\n |> Query.add_exists(@exists_geometries)\n |> Query.only_fields(@fields_geometries)\n |> Query.set_readable_projects(readable_projects)\n |> build_post_atomize\n |> Mapping.map(project_conf)\n end\n\n defp preprocess(filters, must_not) do\n filters = Filter.parse(filters)\n project_conf = ProjectConfigLoader.get(get_project(filters))\n filters = Filter.expand(filters, project_conf)\n must_not = must_not |> Filter.parse |> Filter.expand(project_conf)\n {filters, must_not, project_conf}\n end\n\n defp get_project(nil), do: \"default\"\n defp get_project(filters) do\n case Enum.find(filters, fn {field, value} -> field == \"project\" end) do\n {\"project\", [project]} -> project\n _ -> \"default\"\n end\n end\n\n defp build_post_atomize(query) do\n query\n |> Query.build\n |> index_adapter().post_query\n |> Core.Utils.atomize_up_to(:_source)\n end\n\n defp index_adapter() do\n if Mix.env() == :test do\n Api.Documents.MockIndexAdapter\n else\n Api.Documents.ElasticsearchIndexAdapter\n end\n end\nend\n","old_contents":"defmodule Api.Documents.Index do\n require Logger\n alias Api.Documents.Mapping\n alias Api.Documents.Query\n alias Api.Documents.Filter\n alias Core.ProjectConfigLoader\n\n @max_geometries 10000\n @exists_geometries [\"resource.geometry\"]\n @fields_geometries [\"resource.category\", \"resource.geometry\", \"resource.identifier\", \"resource.id\", \"project\"]\n\n def get(id) do\n Query.init(\"_id:#{id}\", 1)\n |> build_post_atomize()\n |> Mapping.map_single()\n end\n\n def search(q, size, from, filters, must_not, exists, readable_projects) do\n {filters, must_not, project_conf} = preprocess(filters, must_not)\n Query.init(q, size, from)\n |> Query.track_total\n |> Query.add_aggregations()\n |> Query.add_filters(filters)\n |> Query.add_must_not(must_not)\n |> Query.add_exists(exists)\n |> Query.set_readable_projects(readable_projects)\n |> build_post_atomize\n |> Mapping.map(project_conf)\n end\n\n def search_geometries(q, filters, must_not, exists, readable_projects) do\n {filters, must_not, project_conf} = preprocess(filters, must_not)\n Query.init(q, @max_geometries)\n |> Query.add_filters(filters)\n |> Query.add_must_not(must_not)\n |> Query.add_exists(exists)\n |> Query.add_exists(@exists_geometries)\n |> Query.only_fields(@fields_geometries)\n |> Query.set_readable_projects(readable_projects)\n |> build_post_atomize\n |> Mapping.map(project_conf)\n end\n\n defp preprocess(filters, must_not) do\n filters = Filter.parse(filters)\n project_conf = ProjectConfigLoader.get(get_project(filters))\n filters = Filter.expand(filters, project_conf)\n must_not = must_not |> Filter.parse |> Filter.expand(project_conf)\n {filters, must_not, project_conf}\n end\n\n defp get_project(filters) do\n with [{\"project\", [project]}] <- filters, do: project, else: (_ -> \"default\")\n end\n\n defp build_post_atomize(query) do\n query\n |> Query.build\n |> index_adapter().post_query\n |> Core.Utils.atomize_up_to(:_source)\n end\n\n defp index_adapter() do\n if Mix.env() == :test do\n Api.Documents.MockIndexAdapter\n else\n Api.Documents.ElasticsearchIndexAdapter\n end\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"5b15b5c106e21f360120747edf77b7f9ea7eb3a6","subject":"Run code formatter on lib\/elixir\/test\/elixir\/kernel\/binary_test.exs (#6833)","message":"Run code formatter on lib\/elixir\/test\/elixir\/kernel\/binary_test.exs (#6833)\n\n","repos":"michalmuskala\/elixir,antipax\/elixir,pedrosnk\/elixir,ggcampinho\/elixir,kimshrier\/elixir,elixir-lang\/elixir,antipax\/elixir,lexmag\/elixir,kelvinst\/elixir,gfvcastro\/elixir,joshprice\/elixir,kelvinst\/elixir,pedrosnk\/elixir,beedub\/elixir,gfvcastro\/elixir,lexmag\/elixir,beedub\/elixir,kimshrier\/elixir,ggcampinho\/elixir","old_file":"lib\/elixir\/test\/elixir\/kernel\/binary_test.exs","new_file":"lib\/elixir\/test\/elixir\/kernel\/binary_test.exs","new_contents":"Code.require_file(\"..\/test_helper.exs\", __DIR__)\n\ndefmodule Kernel.BinaryTest do\n use ExUnit.Case, async: true\n\n test \"heredoc\" do\n assert 7 == __ENV__.line\n\n assert \"foo\\nbar\\n\" == \"\"\"\n foo\n bar\n \"\"\"\n\n assert 14 == __ENV__.line\n\n assert \"foo\\nbar \\\"\\\"\\\"\\n\" == \"\"\"\n foo\n bar \\\"\"\"\n \"\"\"\n end\n\n test \"aligned heredoc\" do\n assert \"foo\\nbar\\n\" == \"\"\"\n foo\n bar\n \"\"\"\n end\n\n test \"heredoc with interpolation\" do\n assert \"31\\n\" == \"\"\"\n #{__ENV__.line}\n \"\"\"\n\n assert \"\\n36\\n\" == \"\"\"\n\n #{__ENV__.line}\n \"\"\"\n end\n\n test \"heredoc in call\" do\n assert \"foo\\nbar\" ==\n Kernel.<>(\n \"\"\"\n foo\n \"\"\",\n \"bar\"\n )\n end\n\n test \"UTF-8\" do\n assert byte_size(\" \u3086\u3093\u3086\u3093\") == 13\n end\n\n test \"UTF-8 char\" do\n assert ?\u3086 == 12422\n assert ?\\\u3086 == 12422\n end\n\n test \"string concatenation as match\" do\n \"foo\" <> x = \"foobar\"\n assert x == \"bar\"\n\n <<\"foo\">> <> x = \"foobar\"\n assert x == \"bar\"\n\n <<\"f\", \"oo\">> <> x = \"foobar\"\n assert x == \"bar\"\n\n <> <> _ = \"foobar\"\n assert x == \"foo\"\n\n size = 3\n <> <> _ = \"foobar\"\n assert x == \"foo\"\n\n size = 16\n <> <> _ = \"foobar\"\n assert x == 26223\n\n <> <> _ = \"foobar\"\n assert x == \"foo\"\n\n <> <> _ = \"foobar\"\n assert x == \"foo\"\n\n <> <> _ = \"foobar\"\n assert x == \"foo\"\n\n assert_raise MatchError, fn ->\n Code.eval_string(~s{<> <> _ = \"foobar\"})\n end\n\n assert_raise MatchError, fn ->\n Code.eval_string(~s{<> <> _ = \"foobar\"})\n end\n end\n\n test \"hex\" do\n assert \"\\x76\" == \"v\"\n assert \"\\u00FF\" == \"\u00ff\"\n assert \"\\u{A}\" == \"\\n\"\n assert \"\\u{E9}\" == \"\u00e9\"\n assert \"\\u{10F}\" == <<196, 143>>\n assert \"\\u{10FF}\" == <<225, 131, 191>>\n assert \"\\u{10FFF}\" == <<240, 144, 191, 191>>\n assert \"\\u{10FFFF}\" == <<244, 143, 191, 191>>\n end\n\n test \"match\" do\n assert match?(<>, \"ab\")\n refute match?(<>, \"cd\")\n assert match?(<<_::utf8>> <> _, \"\u00e9f\")\n end\n\n test \"interpolation\" do\n res = \"hello \\\\abc\"\n assert \"hello #{\"\\\\abc\"}\" == res\n assert \"hello #{\"\\\\abc\" <> \"\"}\" == res\n end\n\n test \"pattern match\" do\n s = 16\n assert <<_a, _b::size(s)>> = \"foo\"\n end\n\n test \"pattern match with splice\" do\n assert <<1, <<2, 3, 4>>, 5>> = <<1, 2, 3, 4, 5>>\n end\n\n test \"partial application\" do\n assert (&<<&1, 2>>).(1) == <<1, 2>>\n assert (&<<&1, &2>>).(1, 2) == <<1, 2>>\n assert (&<<&2, &1>>).(2, 1) == <<1, 2>>\n end\n\n test \"literal\" do\n assert <<106, 111, 115, 195, 169>> == <<\"jos\u00e9\">>\n assert <<106, 111, 115, 195, 169>> == <<\"#{String.to_atom(\"jos\u00e9\")}\">>\n assert <<106, 111, 115, 195, 169>> == <<\"jos\u00e9\"::binary>>\n assert <<106, 111, 115, 195, 169>> == <<\"jos\u00e9\"::bits>>\n assert <<106, 111, 115, 195, 169>> == <<\"jos\u00e9\"::bitstring>>\n assert <<106, 111, 115, 195, 169>> == <<\"jos\u00e9\"::bytes>>\n\n assert <<106, 111, 115, 195, 169>> == <<\"jos\u00e9\"::utf8>>\n assert <<0, 106, 0, 111, 0, 115, 0, 233>> == <<\"jos\u00e9\"::utf16>>\n assert <<106, 0, 111, 0, 115, 0, 233, 0>> == <<\"jos\u00e9\"::little-utf16>>\n assert <<0, 0, 0, 106, 0, 0, 0, 111, 0, 0, 0, 115, 0, 0, 0, 233>> == <<\"jos\u00e9\"::utf32>>\n end\n\n test \"literal errors\" do\n assert_raise CompileError, fn ->\n Code.eval_string(~s[<<\"foo\"::integer>>])\n end\n\n assert_raise CompileError, fn ->\n Code.eval_string(~s[<<\"foo\"::float>>])\n end\n\n assert_raise CompileError, fn ->\n Code.eval_string(~s[<<'foo'::binary>>])\n end\n\n assert_raise ArgumentError, fn ->\n Code.eval_string(~s[<<1::4>> <> \"foo\"])\n end\n end\n\n @bitstring <<\"foo\", 16::4>>\n\n test \"bitstring attribute\" do\n assert @bitstring == <<\"foo\", 16::4>>\n end\n\n @binary \"new \"\n\n test \"bitsyntax expansion\" do\n assert <<@binary, \"world\">> == \"new world\"\n end\n\n test \"bitsyntax translation\" do\n refb = \"sample\"\n sec_data = \"another\"\n\n <<\n byte_size(refb)::size(1)-big-signed-integer-unit(8),\n refb::binary,\n byte_size(sec_data)::1*16-big-signed-integer,\n sec_data::binary\n >>\n end\n\n test \"bitsyntax size shortcut\" do\n assert <<1::3>> == <<1::size(3)>>\n assert <<1::3*8>> == <<1::size(3)-unit(8)>>\n end\n\n test \"bitsyntax variable size\" do\n x = 8\n assert <<_, _::size(x)>> = <>\n assert (fn <<_, _::size(x)>> -> true end).(<>)\n end\n\n defmacrop signed_16 do\n quote do\n big - signed - integer - unit(16)\n end\n end\n\n defmacrop refb_spec do\n quote do\n 1 * 8 - big - signed - integer\n end\n end\n\n test \"bitsyntax macro\" do\n refb = \"sample\"\n sec_data = \"another\"\n\n <<\n byte_size(refb)::refb_spec,\n refb::binary,\n byte_size(sec_data)::size(1)-signed_16,\n sec_data::binary\n >>\n end\nend\n","old_contents":"Code.require_file \"..\/test_helper.exs\", __DIR__\n\ndefmodule Kernel.BinaryTest do\n use ExUnit.Case, async: true\n\n test \"heredoc\" do\n assert 7 == __ENV__.line\n assert \"foo\\nbar\\n\" == \"\"\"\nfoo\nbar\n\"\"\"\n\n assert 13 == __ENV__.line\n assert \"foo\\nbar \\\"\\\"\\\"\\n\" == \"\"\"\nfoo\nbar \\\"\"\"\n\"\"\"\n end\n\n test \"aligned heredoc\" do\n assert \"foo\\nbar\\n\" == \"\"\"\n foo\n bar\n \"\"\"\n end\n\n test \"heredoc with interpolation\" do\n assert \"29\\n\" == \"\"\"\n #{__ENV__.line}\n \"\"\"\n\n assert \"\\n34\\n\" == \"\"\"\n\n #{__ENV__.line}\n \"\"\"\n end\n\n test \"heredoc in call\" do\n assert \"foo\\nbar\" == Kernel.<>(\"\"\"\n foo\n \"\"\", \"bar\")\n end\n\n test \"UTF-8\" do\n assert byte_size(\" \u3086\u3093\u3086\u3093\") == 13\n end\n\n test \"UTF-8 char\" do\n assert ?\u3086 == 12422\n assert ?\\\u3086 == 12422\n end\n\n test \"string concatenation as match\" do\n \"foo\" <> x = \"foobar\"\n assert x == \"bar\"\n\n <<\"foo\">> <> x = \"foobar\"\n assert x == \"bar\"\n\n <<\"f\", \"oo\">> <> x = \"foobar\"\n assert x == \"bar\"\n\n <> <> _ = \"foobar\"\n assert x == \"foo\"\n\n size = 3\n <> <> _ = \"foobar\"\n assert x == \"foo\"\n\n size = 16\n <> <> _ = \"foobar\"\n assert x == 26223\n\n <> <> _ = \"foobar\"\n assert x == \"foo\"\n\n <> <> _ = \"foobar\"\n assert x == \"foo\"\n\n <> <> _ = \"foobar\"\n assert x == \"foo\"\n\n assert_raise MatchError, fn ->\n Code.eval_string(~s{<> <> _ = \"foobar\"})\n end\n\n assert_raise MatchError, fn ->\n Code.eval_string(~s{<> <> _ = \"foobar\"})\n end\n end\n\n test \"hex\" do\n assert \"\\x76\" == \"v\"\n assert \"\\u00FF\" == \"\u00ff\"\n assert \"\\u{A}\"== \"\\n\"\n assert \"\\u{E9}\"== \"\u00e9\"\n assert \"\\u{10F}\" == <<196, 143>>\n assert \"\\u{10FF}\" == <<225, 131, 191>>\n assert \"\\u{10FFF}\" == <<240, 144, 191, 191>>\n assert \"\\u{10FFFF}\" == <<244, 143, 191, 191>>\n end\n\n test \"match\" do\n assert match?(<>, \"ab\")\n refute match?(<>, \"cd\")\n assert match?(<<_::utf8>> <> _, \"\u00e9f\")\n end\n\n test \"interpolation\" do\n res = \"hello \\\\abc\"\n assert \"hello #{\"\\\\abc\"}\" == res\n assert \"hello #{\"\\\\abc\" <> \"\"}\" == res\n end\n\n test \"pattern match\" do\n s = 16\n assert <<_a, _b :: size(s)>> = \"foo\"\n end\n\n test \"pattern match with splice\" do\n assert <<1, <<2, 3, 4>>, 5>> = <<1, 2, 3, 4, 5>>\n end\n\n test \"partial application\" do\n assert (&<<&1, 2>>).(1) == <<1, 2>>\n assert (&<<&1, &2>>).(1, 2) == <<1, 2>>\n assert (&<<&2, &1>>).(2, 1) == <<1, 2>>\n end\n\n test \"literal\" do\n assert <<106, 111, 115, 195, 169>> == <<\"jos\u00e9\">>\n assert <<106, 111, 115, 195, 169>> == <<\"#{:\"jos\u00e9\"}\">>\n assert <<106, 111, 115, 195, 169>> == <<\"jos\u00e9\"::binary>>\n assert <<106, 111, 115, 195, 169>> == <<\"jos\u00e9\"::bits>>\n assert <<106, 111, 115, 195, 169>> == <<\"jos\u00e9\"::bitstring>>\n assert <<106, 111, 115, 195, 169>> == <<\"jos\u00e9\"::bytes>>\n\n assert <<106, 111, 115, 195, 169>> == <<\"jos\u00e9\"::utf8>>\n assert <<0, 106, 0, 111, 0, 115, 0, 233>> == <<\"jos\u00e9\"::utf16>>\n assert <<106, 0, 111, 0, 115, 0, 233, 0>> == <<\"jos\u00e9\"::little-utf16>>\n assert <<0, 0, 0, 106, 0, 0, 0, 111, 0, 0, 0, 115, 0, 0, 0, 233>> == <<\"jos\u00e9\"::utf32>>\n end\n\n test \"literal errors\" do\n assert_raise CompileError, fn ->\n Code.eval_string(~s[<<\"foo\"::integer>>])\n end\n\n assert_raise CompileError, fn ->\n Code.eval_string(~s[<<\"foo\"::float>>])\n end\n\n assert_raise CompileError, fn ->\n Code.eval_string(~s[<<'foo'::binary>>])\n end\n\n assert_raise ArgumentError, fn ->\n Code.eval_string(~s[<<1::4>> <> \"foo\"])\n end\n end\n\n @bitstring <<\"foo\", 16::4>>\n\n test \"bitstring attribute\" do\n assert @bitstring == <<\"foo\", 16::4>>\n end\n\n @binary \"new \"\n\n test \"bitsyntax expansion\" do\n assert <<@binary, \"world\">> == \"new world\"\n end\n\n test \"bitsyntax translation\" do\n refb = \"sample\"\n sec_data = \"another\"\n <>\n end\n\n test \"bitsyntax size shortcut\" do\n assert <<1::3>> == <<1::size(3)>>\n assert <<1::3*8>> == <<1::size(3)-unit(8)>>\n end\n\n test \"bitsyntax variable size\" do\n x = 8\n assert <<_, _::size(x)>> = <>\n assert (fn <<_, _::size(x)>> -> true end).(<>)\n end\n\n defmacrop signed_16 do\n quote do\n big-signed-integer-unit(16)\n end\n end\n\n defmacrop refb_spec do\n quote do\n 1*8-big-signed-integer\n end\n end\n\n test \"bitsyntax macro\" do\n refb = \"sample\"\n sec_data = \"another\"\n <>\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"9042e6d92e46e60cfb05d3062e0dbd74c3c47838","subject":"chore: let game ws crash if game not running","message":"chore: let game ws crash if game not running\n\n[ci skip]\n","repos":"devstopfix\/elixoids,devstopfix\/elixoids,devstopfix\/elixoids,devstopfix\/elixoids,devstopfix\/elixoids","old_file":"lib\/elixoids\/server\/websocket_game_handler.ex","new_file":"lib\/elixoids\/server\/websocket_game_handler.ex","new_contents":"defmodule Elixoids.Server.WebsocketGameHandler do\n @moduledoc \"\"\"\n Websocket Handler for the graphics engine. Queries the game state at 30fps\n and publishes it to subscriber. Should the call from this process to the game\n process fail, the connection will close and the client is expected to reconnect.\n \"\"\"\n\n alias Elixoids.Api.State\n alias Elixoids.Game.Server, as: Game\n\n @fps 30\n @ms_between_frames div(1000, @fps)\n @pause_ms 1000\n @opts %{idle_timeout: 60 * 60 * 1000, compress: false}\n @explosions_per_frame 7\n\n @behaviour :cowboy_handler\n\n def init(req = %{bindings: %{game: game}}, _state) do\n {:cowboy_websocket, req, game, @opts}\n end\n\n def websocket_init(game) do\n with {game_id, \"\"} <- Integer.parse(game),\n {:ok, _pid} <- Elixoids.News.subscribe(game_id),\n state <- %{game_id: game_id, explosions: []},\n _ref <- :erlang.start_timer(@pause_ms, self(), state) do\n {:ok, state}\n else\n :error -> {:stop, game}\n end\n end\n\n def terminate(_reason, _state), do: :ok\n\n def websocket_handle({:text, _ignore}, state), do: {:ok, state}\n\n def websocket_handle(_inframe, state), do: {:ok, state}\n\n def websocket_info({:timeout, _ref, _}, %{game_id: game_id, explosions: explosions}) do\n :erlang.start_timer(@ms_between_frames, self(), [])\n\n game_state =\n game_id\n |> Game.state()\n |> Map.put(:x, explosions)\n |> convert()\n\n case Jason.encode(game_state) do\n {:ok, message} -> {:reply, {:text, message}, %{game_id: game_id, explosions: []}}\n {:error, _} -> {:ok, %{game_id: game_id, explosions: []}}\n end\n end\n\n # Keep a bounded FIFO list of the recent explosion\n def websocket_info({:explosion, x}, state = %{explosions: []}) do\n {:ok, %{state | explosions: [x]}}\n end\n\n def websocket_info({:explosion, x}, state = %{explosions: explosions}) do\n {:ok, %{state | explosions: Enum.take([x | explosions], @explosions_per_frame)}}\n end\n\n def websocket_info(_info, state), do: {:ok, state}\n\n defp convert(game_state) do\n game_state\n |> Map.update(:a, [], &to_json\/1)\n |> Map.update(:b, [], &to_json\/1)\n |> Map.update(:s, [], &to_json\/1)\n |> Map.update(:x, [], &to_json\/1)\n end\n\n defp to_json(xs), do: Enum.map(xs, fn m -> State.WorldJSON.to_json_list(m) end)\nend\n","old_contents":"defmodule Elixoids.Server.WebsocketGameHandler do\n @moduledoc \"\"\"\n Websocket Handler for the graphics engine. Queries the game state at 30fps\n and publishes it to subscriber.\n\n 1 hour idle timeout.\n \"\"\"\n\n alias Elixoids.Api.State\n alias Elixoids.Game.Server, as: Game\n\n @fps 30\n @ms_between_frames div(1000, @fps)\n @pause_ms 1000\n @opts %{idle_timeout: 60 * 60 * 1000, compress: false}\n @explosions_per_frame 7\n\n @behaviour :cowboy_handler\n\n def init(req = %{bindings: %{game: game}}, _state) do\n {:cowboy_websocket, req, game, @opts}\n end\n\n def websocket_init(game) do\n with {game_id, \"\"} <- Integer.parse(game),\n {:ok, _pid} <- Elixoids.News.subscribe(game_id),\n state <- %{game_id: game_id, explosions: []},\n _ref <- :erlang.start_timer(@pause_ms, self(), state) do\n {:ok, state}\n else\n :error -> {:stop, game}\n end\n end\n\n def terminate(_reason, _state), do: :ok\n\n def websocket_handle({:text, _ignore}, state), do: {:ok, state}\n\n def websocket_handle(_inframe, state), do: {:ok, state}\n\n def websocket_info({:timeout, _ref, _}, %{game_id: game_id, explosions: explosions}) do\n :erlang.start_timer(@ms_between_frames, self(), [])\n\n game_state =\n game_id\n # TODO this call can fail with :noproc\n |> Game.state()\n |> Map.put(:x, explosions)\n |> convert()\n\n case Jason.encode(game_state) do\n {:ok, message} -> {:reply, {:text, message}, %{game_id: game_id, explosions: []}}\n {:error, _} -> {:ok, %{game_id: game_id, explosions: []}}\n end\n end\n\n # Keep a bounded FIFO list of the recent explosion\n def websocket_info({:explosion, x}, state = %{explosions: []}) do\n {:ok, %{state | explosions: [x] }}\n end\n\n def websocket_info({:explosion, x}, state = %{explosions: explosions}) do\n {:ok, %{state | explosions: Enum.take([x | explosions], @explosions_per_frame)}}\n end\n\n def websocket_info(_info, state), do: {:ok, state}\n\n defp convert(game_state) do\n game_state\n |> Map.update(:a, [], &to_json\/1)\n |> Map.update(:b, [], &to_json\/1)\n |> Map.update(:s, [], &to_json\/1)\n |> Map.update(:x, [], &to_json\/1)\n end\n\n defp to_json(xs), do: Enum.map(xs, fn m -> State.WorldJSON.to_json_list(m) end)\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"6d376e649f861dc87cbfc568fae0d0323274600b","subject":"Revamp the test suite","message":"Revamp the test suite\n","repos":"whatyouhide\/redix","old_file":"test\/redix_test.exs","new_file":"test\/redix_test.exs","new_contents":"defmodule RedixTest do\n use ExUnit.Case\n\n import ExUnit.CaptureLog\n\n alias Redix.Error\n alias Redix.ConnectionError\n alias Redix.TestHelpers\n\n @host TestHelpers.test_host()\n @port TestHelpers.test_port()\n\n setup_all do\n {:ok, conn} = Redix.start_link(host: @host, port: @port)\n Redix.command!(conn, [\"FLUSHALL\"])\n Redix.stop(conn)\n :ok\n end\n\n describe \"start_link\/2\" do\n test \"specifying a database\" do\n {:ok, c} = Redix.start_link(host: @host, port: @port, database: 1)\n assert Redix.command(c, ~w(SET my_key my_value)) == {:ok, \"OK\"}\n\n # Let's check we didn't write to the default database (which is 0).\n {:ok, c} = Redix.start_link(host: @host, port: @port)\n assert Redix.command(c, ~w(GET my_key)) == {:ok, nil}\n end\n\n test \"specifying a non existing database\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n {:ok, pid} = Redix.start_link(host: @host, port: @port, database: 1000)\n\n assert_receive {:EXIT, ^pid, %Error{message: message}}, 500\n assert message in [\"ERR invalid DB index\", \"ERR DB index is out of range\"]\n end)\n end\n\n test \"specifying a password when no password is set\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n {:ok, pid} = Redix.start_link(host: @host, port: @port, password: \"foo\")\n\n error = %Error{message: \"ERR Client sent AUTH, but no password is set\"}\n assert_receive {:EXIT, ^pid, ^error}, 500\n end)\n end\n\n test \"when unable to connect to Redis with sync_connect: true\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n error = %Redix.ConnectionError{reason: :nxdomain}\n assert Redix.start_link(host: \"nonexistent\", sync_connect: true) == {:error, error}\n assert_receive {:EXIT, _pid, ^error}, 1000\n end)\n end\n\n test \"when unable to connect to Redis with sync_connect: false\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n {:ok, pid} = Redix.start_link(host: \"nonexistent\", sync_connect: false)\n refute_receive {:EXIT, ^pid, :nxdomain}, 200\n end)\n end\n\n test \"using a redis:\/\/ url\" do\n {:ok, pid} = Redix.start_link(\"redis:\/\/#{@host}:#{@port}\/3\")\n assert Redix.command(pid, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"name registration\" do\n {:ok, pid} = Redix.start_link(host: @host, port: @port, name: :redix_server)\n assert Process.whereis(:redix_server) == pid\n assert Redix.command(:redix_server, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"passing options along with a Redis URI\" do\n {:ok, pid} = Redix.start_link(\"redis:\/\/#{@host}:#{@port}\", name: :redix_uri)\n assert Process.whereis(:redix_uri) == pid\n end\n\n test \"the :log option must be a list\" do\n assert_raise ArgumentError, ~r\/the :log option must be a keyword list\/, fn ->\n Redix.start_link(host: @host, port: @port, log: :not_a_list)\n end\n end\n end\n\n test \"child_spec\/1\" do\n default_spec = %{\n id: Redix,\n start: {Redix, :start_link, []},\n type: :worker\n }\n\n args_path = [:start, Access.elem(2)]\n\n assert Redix.child_spec(\"redis:\/\/localhost\") ==\n put_in(default_spec, args_path, [\"redis:\/\/localhost\"])\n\n assert Redix.child_spec([]) == put_in(default_spec, args_path, [[]])\n assert Redix.child_spec(name: :redix) == put_in(default_spec, args_path, [[name: :redix]])\n\n assert Redix.child_spec({\"redis:\/\/localhost\", name: :redix}) ==\n put_in(default_spec, args_path, [\"redis:\/\/localhost\", [name: :redix]])\n end\n\n test \"stop\/1\" do\n {:ok, pid} = Redix.start_link(\"redis:\/\/#{@host}:#{@port}\/3\")\n ref = Process.monitor(pid)\n assert Redix.stop(pid) == :ok\n\n assert_receive {:DOWN, ^ref, _, _, :normal}, 500\n end\n\n describe \"command\/2\" do\n setup :connect\n\n test \"PING\", %{conn: c} do\n assert Redix.command(c, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"transactions - MULTI\/EXEC\", %{conn: c} do\n assert Redix.command(c, [\"MULTI\"]) == {:ok, \"OK\"}\n assert Redix.command(c, [\"INCR\", \"multifoo\"]) == {:ok, \"QUEUED\"}\n assert Redix.command(c, [\"INCR\", \"multibar\"]) == {:ok, \"QUEUED\"}\n assert Redix.command(c, [\"INCRBY\", \"multifoo\", 4]) == {:ok, \"QUEUED\"}\n assert Redix.command(c, [\"EXEC\"]) == {:ok, [1, 1, 5]}\n end\n\n test \"transactions - MULTI\/DISCARD\", %{conn: c} do\n Redix.command!(c, [\"SET\", \"discarding\", \"foo\"])\n\n assert Redix.command(c, [\"MULTI\"]) == {:ok, \"OK\"}\n assert Redix.command(c, [\"SET\", \"discarding\", \"bar\"]) == {:ok, \"QUEUED\"}\n # Discarding\n assert Redix.command(c, [\"DISCARD\"]) == {:ok, \"OK\"}\n assert Redix.command(c, [\"GET\", \"discarding\"]) == {:ok, \"foo\"}\n end\n\n test \"Lua scripting - EVAL\", %{conn: c} do\n script = \"\"\"\n redis.call(\"SET\", \"evalling\", \"yes\")\n return {KEYS[1],ARGV[1],ARGV[2]}\n \"\"\"\n\n cmds = [\"eval\", script, \"1\", \"key\", \"first\", \"second\"]\n\n assert Redix.command(c, cmds) == {:ok, [\"key\", \"first\", \"second\"]}\n assert Redix.command(c, [\"GET\", \"evalling\"]) == {:ok, \"yes\"}\n end\n\n test \"command\/2 - Lua scripting: SCRIPT LOAD, SCRIPT EXISTS, EVALSHA\", %{conn: c} do\n script = \"\"\"\n return 'hello world'\n \"\"\"\n\n {:ok, sha} = Redix.command(c, [\"SCRIPT\", \"LOAD\", script])\n assert is_binary(sha)\n assert Redix.command(c, [\"SCRIPT\", \"EXISTS\", sha, \"foo\"]) == {:ok, [1, 0]}\n\n # Eval'ing the script\n assert Redix.command(c, [\"EVALSHA\", sha, 0]) == {:ok, \"hello world\"}\n end\n\n test \"Redis errors\", %{conn: c} do\n {:ok, _} = Redix.command(c, ~w(SET errs foo))\n\n assert_raise Redix.Error, \"ERR value is not an integer or out of range\", fn ->\n Redix.command(c, ~w(INCR errs))\n end\n end\n\n test \"passing an empty list returns an error\", %{conn: c} do\n message = \"got an empty command ([]), which is not a valid Redis command\"\n assert_raise ArgumentError, message, fn -> Redix.command(c, []) end\n end\n\n test \"timeout\", %{conn: c} do\n assert {:error, %ConnectionError{reason: :timeout}} = Redix.command(c, ~W(PING), timeout: 0)\n end\n\n test \"Redix process crashes while waiting\", %{conn: c} do\n Process.flag(:trap_exit, true)\n pid = spawn_link(fn -> Redix.command!(c, ~w(BLPOP mid_command_disconnection 0)) end)\n Process.exit(c, :kill)\n assert_receive {:EXIT, ^pid, :killed}\n end\n\n test \"passing a non-list as the command\", %{conn: c} do\n message = \"expected a list of binaries as each Redis command, got: \\\"PING\\\"\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.command(c, \"PING\")\n end\n end\n end\n\n describe \"pipeline\/2\" do\n setup :connect\n\n test \"basic interaction\", %{conn: c} do\n commands = [\n [\"SET\", \"pipe\", \"10\"],\n [\"INCR\", \"pipe\"],\n [\"GET\", \"pipe\"]\n ]\n\n assert Redix.pipeline(c, commands) == {:ok, [\"OK\", 11, \"11\"]}\n end\n\n test \"a lot of commands so that TCP gets stressed\", %{conn: c} do\n assert {:ok, \"OK\"} = Redix.command(c, ~w(SET stress_pipeline foo))\n\n ncommands = 10000\n commands = List.duplicate(~w(GET stress_pipeline), ncommands)\n\n # Let's do it twice to be sure the server can handle the data.\n {:ok, results} = Redix.pipeline(c, commands)\n assert length(results) == ncommands\n {:ok, results} = Redix.pipeline(c, commands)\n assert length(results) == ncommands\n end\n\n test \"a single command should still return a list of results\", %{conn: c} do\n assert Redix.pipeline(c, [[\"PING\"]]) == {:ok, [\"PONG\"]}\n end\n\n test \"Redis errors in the response\", %{conn: c} do\n msg = \"ERR value is not an integer or out of range\"\n assert {:ok, resp} = Redix.pipeline(c, [~w(SET pipeline_errs foo), ~w(INCR pipeline_errs)])\n assert resp == [\"OK\", %Error{message: msg}]\n end\n\n test \"passing an empty list of commands raises an error\", %{conn: c} do\n msg = \"no commands passed to the pipeline\"\n assert_raise ArgumentError, msg, fn -> Redix.pipeline(c, []) end\n end\n\n test \"passing one or more empty commands returns an error\", %{conn: c} do\n message = \"got an empty command ([]), which is not a valid Redis command\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, [[]])\n end\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, [[\"PING\"], [], [\"PING\"]])\n end\n end\n\n test \"passing a PubSub command causes an error\", %{conn: c} do\n assert_raise ArgumentError, ~r{Redix doesn't support Pub\/Sub}, fn ->\n Redix.pipeline(c, [[\"PING\"], [\"SUBSCRIBE\", \"foo\"]])\n end\n end\n\n test \"timeout\", %{conn: c} do\n assert {:error, %ConnectionError{reason: :timeout}} =\n Redix.pipeline(c, [~w(PING), ~w(PING)], timeout: 0)\n end\n\n test \"commands must be lists of binaries\", %{conn: c} do\n message = \"expected a list of Redis commands, got: \\\"PING\\\"\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, \"PING\")\n end\n\n message = \"expected a list of binaries as each Redis command, got: \\\"PING\\\"\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, [\"PING\"])\n end\n end\n end\n\n describe \"command!\/2\" do\n setup :connect\n\n test \"simple commands\", %{conn: c} do\n assert Redix.command!(c, [\"PING\"]) == \"PONG\"\n assert Redix.command!(c, [\"SET\", \"bang\", \"foo\"]) == \"OK\"\n assert Redix.command!(c, [\"GET\", \"bang\"]) == \"foo\"\n end\n\n test \"Redis errors\", %{conn: c} do\n assert_raise Redix.Error, \"ERR unknown command 'NONEXISTENT'\", fn ->\n Redix.command!(c, [\"NONEXISTENT\"])\n end\n\n \"OK\" = Redix.command!(c, [\"SET\", \"bang_errors\", \"foo\"])\n\n assert_raise Redix.Error, \"ERR value is not an integer or out of range\", fn ->\n Redix.command!(c, [\"INCR\", \"bang_errors\"])\n end\n end\n\n test \"connection errors\", %{conn: c} do\n assert_raise Redix.ConnectionError, \":timeout\", fn ->\n Redix.command!(c, [\"PING\"], timeout: 0)\n end\n end\n end\n\n describe \"pipeline!\/2\" do\n setup :connect\n\n test \"simple commands\", %{conn: c} do\n assert Redix.pipeline!(c, [~w(SET ppbang foo), ~w(GET ppbang)]) == ~w(OK foo)\n end\n\n test \"Redis errors in the list of results\", %{conn: c} do\n commands = [~w(SET ppbang_errors foo), ~w(INCR ppbang_errors)]\n\n msg = \"ERR value is not an integer or out of range\"\n assert Redix.pipeline!(c, commands) == [\"OK\", %Redix.Error{message: msg}]\n end\n\n test \"connection errors\", %{conn: c} do\n assert_raise Redix.ConnectionError, \":timeout\", fn ->\n Redix.pipeline!(c, [[\"PING\"]], timeout: 0)\n end\n end\n end\n\n describe \"transaction_pipeline\/3\" do\n setup :connect\n\n test \"non-bang version\", %{conn: conn} do\n commands = [~w(SET transaction_pipeline_key 1), ~w(GET transaction_pipeline_key)]\n assert Redix.transaction_pipeline(conn, commands) == {:ok, [\"OK\", \"1\"]}\n end\n\n test \"bang version\", %{conn: conn} do\n commands = [~w(SET transaction_pipeline_key 1), ~w(GET transaction_pipeline_key)]\n assert Redix.transaction_pipeline!(conn, commands) == [\"OK\", \"1\"]\n end\n end\n\n describe \"noreply_* functions\" do\n setup :connect\n\n test \"noreply_pipeline\/3\", %{conn: conn} do\n commands = [~w(INCR noreply_pl_mykey), ~w(INCR noreply_pl_mykey)]\n assert Redix.noreply_pipeline(conn, commands) == :ok\n assert Redix.command!(conn, ~w(GET noreply_pl_mykey)) == \"2\"\n end\n\n test \"noreply_command\/3\", %{conn: conn} do\n assert Redix.noreply_command(conn, [\"SET\", \"noreply_cmd_mykey\", \"myvalue\"]) == :ok\n assert Redix.command!(conn, [\"GET\", \"noreply_cmd_mykey\"]) == \"myvalue\"\n end\n end\n\n describe \"timeouts and network errors\" do\n setup :connect\n\n test \"client suicide and reconnections\", %{conn: c} do\n capture_log(fn ->\n assert {:ok, _} = Redix.command(c, ~w(QUIT))\n\n # When the socket is closed, we reply with {:error, closed}. We sleep so\n # we're sure that the socket is closed (and we don't get {:error,\n # disconnected} before the socket closed after we sent the PING command\n # to Redix).\n :timer.sleep(100)\n assert Redix.command(c, ~w(PING)) == {:error, %ConnectionError{reason: :closed}}\n\n # Redix retries the first reconnection after 500ms, and we waited 100 already.\n :timer.sleep(500)\n assert {:ok, \"PONG\"} = Redix.command(c, ~w(PING))\n end)\n end\n\n test \"timeouts\", %{conn: c} do\n assert {:error, %ConnectionError{reason: :timeout}} = Redix.command(c, ~w(PING), timeout: 0)\n\n # Let's check that the Redix connection doesn't reply anyways, even if the\n # timeout happened.\n refute_receive {_ref, _message}\n end\n\n test \"mid-command disconnections\", %{conn: c} do\n capture_log(fn ->\n {_pid, ref} =\n Process.spawn(\n fn ->\n # BLPOP with a timeout of 0 blocks indefinitely\n assert Redix.command(c, ~w(BLPOP mid_command_disconnection 0)) ==\n {:error, %ConnectionError{reason: :disconnected}}\n end,\n [:monitor, :link]\n )\n\n Redix.command!(c, ~w(QUIT))\n assert_receive {:DOWN, ^ref, _, _, _}, 200\n end)\n end\n\n test \"no leaking messages when timeout happen at the same time as disconnections\", %{conn: c} do\n capture_log(fn ->\n {_pid, ref} =\n Process.spawn(\n fn ->\n error = %ConnectionError{reason: :timeout}\n assert Redix.command(c, ~w(BLPOP my_list 0), timeout: 0) == {:error, error}\n\n # The fact that we timed out should be respected here, even if the\n # connection is killed (no {:error, :disconnected} message should\n # arrive).\n refute_receive {_ref, _message}\n end,\n [:link, :monitor]\n )\n\n Redix.command!(c, ~w(QUIT))\n assert_receive {:DOWN, ^ref, _, _, _}, 200\n end)\n end\n end\n\n test \":exit_on_disconnection option\" do\n {:ok, c} = Redix.start_link(host: @host, port: @port, exit_on_disconnection: true)\n Process.flag(:trap_exit, true)\n\n capture_log(fn ->\n Redix.command!(c, ~w(QUIT))\n assert_receive {:EXIT, ^c, %ConnectionError{reason: :tcp_closed}}\n end)\n end\n\n defp connect(_context) do\n {:ok, conn} = Redix.start_link(host: @host, port: @port)\n {:ok, %{conn: conn}}\n end\nend\n","old_contents":"defmodule RedixTest do\n use ExUnit.Case\n\n import ExUnit.CaptureLog\n\n alias Redix.Error\n alias Redix.ConnectionError\n alias Redix.TestHelpers\n\n @host TestHelpers.test_host()\n @port TestHelpers.test_port()\n\n setup_all do\n {:ok, conn} = Redix.start_link(host: @host, port: @port)\n Redix.command!(conn, [\"FLUSHDB\"])\n Redix.stop(conn)\n :ok\n end\n\n setup context do\n if context[:no_setup] do\n {:ok, %{}}\n else\n {:ok, conn} = Redix.start_link(host: @host, port: @port)\n {:ok, %{conn: conn}}\n end\n end\n\n @tag :no_setup\n test \"start_link\/2: specifying a database\" do\n {:ok, c} = Redix.start_link(host: @host, port: @port, database: 1)\n assert Redix.command(c, ~w(SET my_key my_value)) == {:ok, \"OK\"}\n\n # Let's check we didn't write to the default database (which is 0).\n {:ok, c} = Redix.start_link(host: @host, port: @port)\n assert Redix.command(c, ~w(GET my_key)) == {:ok, nil}\n end\n\n @tag :no_setup\n test \"start_link\/2: specifying a non existing database\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n {:ok, pid} = Redix.start_link(host: @host, port: @port, database: 1000)\n\n assert_receive {:EXIT, ^pid, %Error{message: message}}, 500\n assert message in [\"ERR invalid DB index\", \"ERR DB index is out of range\"]\n end)\n end\n\n @tag :no_setup\n test \"start_link\/2: specifying a password when no password is set\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n {:ok, pid} = Redix.start_link(host: @host, port: @port, password: \"foo\")\n\n error = %Error{message: \"ERR Client sent AUTH, but no password is set\"}\n assert_receive {:EXIT, ^pid, ^error}, 500\n end)\n end\n\n @tag :no_setup\n test \"start_link\/2: when unable to connect to Redis with sync_connect: true\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n error = %Redix.ConnectionError{reason: :nxdomain}\n assert Redix.start_link(host: \"nonexistent\", sync_connect: true) == {:error, error}\n assert_receive {:EXIT, _pid, ^error}, 1000\n end)\n end\n\n @tag :no_setup\n test \"start_link\/2: when unable to connect to Redis with sync_connect: false\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n {:ok, pid} = Redix.start_link(host: \"nonexistent\", sync_connect: false)\n refute_receive {:EXIT, ^pid, :nxdomain}, 200\n end)\n end\n\n @tag :no_setup\n test \"start_link\/2: using a redis:\/\/ url\" do\n {:ok, pid} = Redix.start_link(\"redis:\/\/#{@host}:#{@port}\/3\")\n assert Redix.command(pid, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n @tag :no_setup\n test \"start_link\/2: name registration\" do\n {:ok, pid} = Redix.start_link(host: @host, port: @port, name: :redix_server)\n assert Process.whereis(:redix_server) == pid\n assert Redix.command(:redix_server, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n @tag :no_setup\n test \"start_link\/2: passing options along with a Redis URI\" do\n {:ok, pid} = Redix.start_link(\"redis:\/\/#{@host}:#{@port}\", name: :redix_uri)\n assert Process.whereis(:redix_uri) == pid\n end\n\n @tag :no_setup\n test \"stop\/1\" do\n {:ok, pid} = Redix.start_link(\"redis:\/\/#{@host}:#{@port}\/3\")\n ref = Process.monitor(pid)\n assert Redix.stop(pid) == :ok\n\n assert_receive {:DOWN, ^ref, _, _, :normal}, 500\n end\n\n @tag :no_setup\n test \"the :log option given to start_link\/2 must be a list\" do\n assert_raise ArgumentError, ~r\/the :log option must be a keyword list\/, fn ->\n Redix.start_link(host: @host, port: @port, log: :not_a_list)\n end\n end\n\n test \"command\/2\", %{conn: c} do\n assert Redix.command(c, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"command\/2: transactions - MULTI\/EXEC\", %{conn: c} do\n assert Redix.command(c, [\"MULTI\"]) == {:ok, \"OK\"}\n assert Redix.command(c, [\"INCR\", \"multifoo\"]) == {:ok, \"QUEUED\"}\n assert Redix.command(c, [\"INCR\", \"multibar\"]) == {:ok, \"QUEUED\"}\n assert Redix.command(c, [\"INCRBY\", \"multifoo\", 4]) == {:ok, \"QUEUED\"}\n assert Redix.command(c, [\"EXEC\"]) == {:ok, [1, 1, 5]}\n end\n\n test \"command\/2: transactions - MULTI\/DISCARD\", %{conn: c} do\n Redix.command!(c, [\"SET\", \"discarding\", \"foo\"])\n\n assert Redix.command(c, [\"MULTI\"]) == {:ok, \"OK\"}\n assert Redix.command(c, [\"SET\", \"discarding\", \"bar\"]) == {:ok, \"QUEUED\"}\n # Discarding\n assert Redix.command(c, [\"DISCARD\"]) == {:ok, \"OK\"}\n assert Redix.command(c, [\"GET\", \"discarding\"]) == {:ok, \"foo\"}\n end\n\n test \"command\/2: Lua scripting - EVAL\", %{conn: c} do\n script = \"\"\"\n redis.call(\"SET\", \"evalling\", \"yes\")\n return {KEYS[1],ARGV[1],ARGV[2]}\n \"\"\"\n\n cmds = [\"eval\", script, \"1\", \"key\", \"first\", \"second\"]\n\n assert Redix.command(c, cmds) == {:ok, [\"key\", \"first\", \"second\"]}\n assert Redix.command(c, [\"GET\", \"evalling\"]) == {:ok, \"yes\"}\n end\n\n test \"command\/2 - Lua scripting: SCRIPT LOAD, SCRIPT EXISTS, EVALSHA\", %{conn: c} do\n script = \"\"\"\n return 'hello world'\n \"\"\"\n\n {:ok, sha} = Redix.command(c, [\"SCRIPT\", \"LOAD\", script])\n assert is_binary(sha)\n assert Redix.command(c, [\"SCRIPT\", \"EXISTS\", sha, \"foo\"]) == {:ok, [1, 0]}\n\n # Eval'ing the script\n assert Redix.command(c, [\"EVALSHA\", sha, 0]) == {:ok, \"hello world\"}\n end\n\n test \"command\/2: Redis errors\", %{conn: c} do\n {:ok, _} = Redix.command(c, ~w(SET errs foo))\n\n assert_raise Redix.Error, \"ERR value is not an integer or out of range\", fn ->\n Redix.command(c, ~w(INCR errs))\n end\n end\n\n test \"command\/2: passing an empty list returns an error\", %{conn: c} do\n message = \"got an empty command ([]), which is not a valid Redis command\"\n assert_raise ArgumentError, message, fn -> Redix.command(c, []) end\n end\n\n test \"command\/2: timeout\", %{conn: c} do\n assert {:error, %ConnectionError{reason: :timeout}} = Redix.command(c, ~W(PING), timeout: 0)\n end\n\n test \"command\/2: Redix process crashes while waiting\", %{conn: c} do\n Process.flag(:trap_exit, true)\n pid = spawn_link(fn -> Redix.command!(c, ~w(BLPOP mid_command_disconnection 0)) end)\n Process.exit(c, :kill)\n assert_receive {:EXIT, ^pid, :killed}\n end\n\n test \"command\/2: passing a non-list as the command\", %{conn: c} do\n message = \"expected a list of binaries as each Redis command, got: \\\"PING\\\"\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.command(c, \"PING\")\n end\n end\n\n test \"pipeline\/2\", %{conn: c} do\n commands = [\n [\"SET\", \"pipe\", \"10\"],\n [\"INCR\", \"pipe\"],\n [\"GET\", \"pipe\"]\n ]\n\n assert Redix.pipeline(c, commands) == {:ok, [\"OK\", 11, \"11\"]}\n end\n\n test \"pipeline\/2: a lot of commands so that TCP gets stressed\", %{conn: c} do\n assert {:ok, \"OK\"} = Redix.command(c, ~w(SET stress_pipeline foo))\n\n ncommands = 10000\n commands = List.duplicate(~w(GET stress_pipeline), ncommands)\n\n # Let's do it twice to be sure the server can handle the data.\n {:ok, results} = Redix.pipeline(c, commands)\n assert length(results) == ncommands\n {:ok, results} = Redix.pipeline(c, commands)\n assert length(results) == ncommands\n end\n\n test \"pipeline\/2: a single command should still return a list of results\", %{conn: c} do\n assert Redix.pipeline(c, [[\"PING\"]]) == {:ok, [\"PONG\"]}\n end\n\n test \"pipeline\/2: Redis errors in the response\", %{conn: c} do\n msg = \"ERR value is not an integer or out of range\"\n assert {:ok, resp} = Redix.pipeline(c, [~w(SET pipeline_errs foo), ~w(INCR pipeline_errs)])\n assert resp == [\"OK\", %Error{message: msg}]\n end\n\n test \"pipeline\/2: passing an empty list of commands raises an error\", %{conn: c} do\n msg = \"no commands passed to the pipeline\"\n assert_raise ArgumentError, msg, fn -> Redix.pipeline(c, []) end\n end\n\n test \"pipeline\/2: passing one or more empty commands returns an error\", %{conn: c} do\n message = \"got an empty command ([]), which is not a valid Redis command\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, [[]])\n end\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, [[\"PING\"], [], [\"PING\"]])\n end\n end\n\n test \"pipeline\/2: passing a PubSub command causes an error\", %{conn: c} do\n assert_raise ArgumentError, ~r{Redix doesn't support Pub\/Sub}, fn ->\n Redix.pipeline(c, [[\"PING\"], [\"SUBSCRIBE\", \"foo\"]])\n end\n end\n\n test \"pipeline\/2: timeout\", %{conn: c} do\n assert {:error, %ConnectionError{reason: :timeout}} =\n Redix.pipeline(c, [~w(PING), ~w(PING)], timeout: 0)\n end\n\n test \"pipeline\/2: commands must be lists of binaries\", %{conn: c} do\n message = \"expected a list of Redis commands, got: \\\"PING\\\"\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, \"PING\")\n end\n\n message = \"expected a list of binaries as each Redis command, got: \\\"PING\\\"\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, [\"PING\"])\n end\n end\n\n test \"command!\/2: simple commands\", %{conn: c} do\n assert Redix.command!(c, [\"PING\"]) == \"PONG\"\n assert Redix.command!(c, [\"SET\", \"bang\", \"foo\"]) == \"OK\"\n assert Redix.command!(c, [\"GET\", \"bang\"]) == \"foo\"\n end\n\n test \"command!\/2: Redis errors\", %{conn: c} do\n assert_raise Redix.Error, \"ERR unknown command 'NONEXISTENT'\", fn ->\n Redix.command!(c, [\"NONEXISTENT\"])\n end\n\n \"OK\" = Redix.command!(c, [\"SET\", \"bang_errors\", \"foo\"])\n\n assert_raise Redix.Error, \"ERR value is not an integer or out of range\", fn ->\n Redix.command!(c, [\"INCR\", \"bang_errors\"])\n end\n end\n\n test \"command!\/2: connection errors\", %{conn: c} do\n assert_raise Redix.ConnectionError, \":timeout\", fn ->\n Redix.command!(c, [\"PING\"], timeout: 0)\n end\n end\n\n test \"pipeline!\/2: simple commands\", %{conn: c} do\n assert Redix.pipeline!(c, [~w(SET ppbang foo), ~w(GET ppbang)]) == ~w(OK foo)\n end\n\n test \"pipeline!\/2: Redis errors in the list of results\", %{conn: c} do\n commands = [~w(SET ppbang_errors foo), ~w(INCR ppbang_errors)]\n\n msg = \"ERR value is not an integer or out of range\"\n assert Redix.pipeline!(c, commands) == [\"OK\", %Redix.Error{message: msg}]\n end\n\n test \"pipeline!\/2: connection errors\", %{conn: c} do\n assert_raise Redix.ConnectionError, \":timeout\", fn ->\n Redix.pipeline!(c, [[\"PING\"]], timeout: 0)\n end\n end\n\n describe \"transaction_pipeline\/3\" do\n test \"non-bang version\", %{conn: conn} do\n commands = [~w(SET transaction_pipeline_key 1), ~w(GET transaction_pipeline_key)]\n assert Redix.transaction_pipeline(conn, commands) == {:ok, [\"OK\", \"1\"]}\n end\n\n test \"bang version\", %{conn: conn} do\n commands = [~w(SET transaction_pipeline_key 1), ~w(GET transaction_pipeline_key)]\n assert Redix.transaction_pipeline!(conn, commands) == [\"OK\", \"1\"]\n end\n end\n\n describe \"noreply_* functions\" do\n test \"noreply_pipeline\/3\", %{conn: conn} do\n commands = [~w(INCR noreply_pl_mykey), ~w(INCR noreply_pl_mykey)]\n assert Redix.noreply_pipeline(conn, commands) == :ok\n assert Redix.command!(conn, ~w(GET noreply_pl_mykey)) == \"2\"\n end\n\n test \"noreply_command\/3\", %{conn: conn} do\n assert Redix.noreply_command(conn, [\"SET\", \"noreply_cmd_mykey\", \"myvalue\"]) == :ok\n assert Redix.command!(conn, [\"GET\", \"noreply_cmd_mykey\"]) == \"myvalue\"\n end\n end\n\n @tag :no_setup\n test \"client suicide and reconnections\" do\n {:ok, c} = Redix.start_link(host: @host, port: @port)\n\n capture_log(fn ->\n assert {:ok, _} = Redix.command(c, ~w(QUIT))\n\n # When the socket is closed, we reply with {:error, closed}. We sleep so\n # we're sure that the socket is closed (and we don't get {:error,\n # disconnected} before the socket closed after we sent the PING command\n # to Redix).\n :timer.sleep(100)\n assert Redix.command(c, ~w(PING)) == {:error, %ConnectionError{reason: :closed}}\n\n # Redix retries the first reconnection after 500ms, and we waited 100 already.\n :timer.sleep(500)\n assert {:ok, \"PONG\"} = Redix.command(c, ~w(PING))\n end)\n end\n\n @tag :no_setup\n test \"timeouts\" do\n {:ok, c} = Redix.start_link(host: @host, port: @port)\n\n assert {:error, %ConnectionError{reason: :timeout}} = Redix.command(c, ~w(PING), timeout: 0)\n\n # Let's check that the Redix connection doesn't reply anyways, even if the\n # timeout happened.\n refute_receive {_ref, _message}\n end\n\n @tag :no_setup\n test \"mid-command disconnections\" do\n {:ok, c} = Redix.start_link(host: @host, port: @port)\n\n capture_log(fn ->\n {_pid, ref} =\n Process.spawn(\n fn ->\n # BLPOP with a timeout of 0 blocks indefinitely\n assert Redix.command(c, ~w(BLPOP mid_command_disconnection 0)) ==\n {:error, %ConnectionError{reason: :disconnected}}\n end,\n [:monitor, :link]\n )\n\n Redix.command!(c, ~w(QUIT))\n assert_receive {:DOWN, ^ref, _, _, _}, 200\n end)\n end\n\n @tag :no_setup\n test \"no leaking messages when timeout happen at the same time as disconnections\" do\n {:ok, c} = Redix.start_link(host: @host, port: @port)\n\n capture_log(fn ->\n {_pid, ref} =\n Process.spawn(\n fn ->\n error = %ConnectionError{reason: :timeout}\n assert Redix.command(c, ~w(BLPOP my_list 0), timeout: 0) == {:error, error}\n\n # The fact that we timed out should be respected here, even if the\n # connection is killed (no {:error, :disconnected} message should\n # arrive).\n refute_receive {_ref, _message}\n end,\n [:link, :monitor]\n )\n\n Redix.command!(c, ~w(QUIT))\n assert_receive {:DOWN, ^ref, _, _, _}, 200\n end)\n end\n\n @tag :no_setup\n test \":exit_on_disconnection option\" do\n {:ok, c} = Redix.start_link(host: @host, port: @port, exit_on_disconnection: true)\n Process.flag(:trap_exit, true)\n\n capture_log(fn ->\n Redix.command!(c, ~w(QUIT))\n assert_receive {:EXIT, ^c, %ConnectionError{reason: :tcp_closed}}\n end)\n end\n\n @tag :no_setup\n test \"child_spec\/1\" do\n default_spec = %{\n id: Redix,\n start: {Redix, :start_link, []},\n type: :worker\n }\n\n args_path = [:start, Access.elem(2)]\n\n assert Redix.child_spec(\"redis:\/\/localhost\") ==\n put_in(default_spec, args_path, [\"redis:\/\/localhost\"])\n\n assert Redix.child_spec([]) == put_in(default_spec, args_path, [[]])\n assert Redix.child_spec(name: :redix) == put_in(default_spec, args_path, [[name: :redix]])\n\n assert Redix.child_spec({\"redis:\/\/localhost\", name: :redix}) ==\n put_in(default_spec, args_path, [\"redis:\/\/localhost\", [name: :redix]])\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"d3084c501b3db7b9359f0f3effb01189e1b26a35","subject":"Fix a flaky test","message":"Fix a flaky test\n","repos":"whatyouhide\/redix","old_file":"test\/redix_test.exs","new_file":"test\/redix_test.exs","new_contents":"defmodule RedixTest do\n use ExUnit.Case, async: true\n\n import ExUnit.CaptureLog\n\n alias Redix.{\n ConnectionError,\n Error\n }\n\n setup_all do\n {:ok, conn} = Redix.start_link()\n Redix.command!(conn, [\"FLUSHALL\"])\n Redix.stop(conn)\n :ok\n end\n\n describe \"start_link\/2\" do\n test \"specifying a database\" do\n {:ok, c} = Redix.start_link(database: 1)\n assert Redix.command(c, ~w(SET my_key my_value)) == {:ok, \"OK\"}\n\n # Let's check we didn't write to the default database (which is 0).\n {:ok, c} = Redix.start_link()\n assert Redix.command(c, ~w(GET my_key)) == {:ok, nil}\n end\n\n test \"specifying a non existing database\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n {:ok, pid} = Redix.start_link(database: 1000)\n\n assert_receive {:EXIT, ^pid, %Error{message: message}}, 500\n assert message in [\"ERR invalid DB index\", \"ERR DB index is out of range\"]\n end)\n end\n\n test \"specifying a password when no password is set\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n {:ok, pid} = Redix.start_link(password: \"foo\")\n\n error = %Error{message: \"ERR Client sent AUTH, but no password is set\"}\n assert_receive {:EXIT, ^pid, ^error}, 500\n end)\n end\n\n test \"specifying a password when a password is set\" do\n {:ok, pid} = Redix.start_link(port: 16379, password: \"some-password\")\n assert Redix.command(pid, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"when unable to connect to Redis with sync_connect: true\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n\n assert {:error, %Redix.ConnectionError{reason: reason}} =\n Redix.start_link(host: \"nonexistent\", sync_connect: true)\n\n assert_receive {:EXIT, _pid, %Redix.ConnectionError{}}, 1000\n\n # Apparently somewhere the error reason is :nxdomain but some other times it's\n # :timeout.\n assert reason in [:nxdomain, :timeout]\n end)\n end\n\n test \"when unable to connect to Redis with sync_connect: false\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n {:ok, pid} = Redix.start_link(host: \"nonexistent\", sync_connect: false)\n refute_receive {:EXIT, ^pid, :nxdomain}, 200\n end)\n end\n\n test \"using a redis:\/\/ url\" do\n {:ok, pid} = Redix.start_link(\"redis:\/\/localhost:6379\/3\")\n assert Redix.command(pid, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"using a rediss:\/\/ url, ignoring certificate\" do\n {:ok, pid} =\n Redix.start_link(\"rediss:\/\/localhost:6384\/3\",\n socket_opts: [verify: :verify_none, reuse_sessions: false]\n )\n\n assert Redix.command(pid, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"using a rediss:\/\/ url, unknown certificate\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n\n assert {:error, error} =\n Redix.start_link(\"rediss:\/\/localhost:6384\/3\",\n socket_opts: [reuse_sessions: false],\n sync_connect: true\n )\n\n assert %Redix.ConnectionError{reason: {:tls_alert, _}} = error\n assert_receive {:EXIT, _pid, ^error}, 1000\n end)\n end\n\n test \"name registration\" do\n {:ok, pid} = Redix.start_link(name: :redix_server)\n assert Process.whereis(:redix_server) == pid\n assert Redix.command(:redix_server, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"passing options along with a Redis URI\" do\n {:ok, pid} = Redix.start_link(\"redis:\/\/localhost\", name: :redix_uri)\n assert Process.whereis(:redix_uri) == pid\n end\n\n test \"using gen_statem options\" do\n fullsweep_after = Enum.random(0..50000)\n {:ok, pid} = Redix.start_link(spawn_opt: [fullsweep_after: fullsweep_after])\n {:garbage_collection, info} = Process.info(pid, :garbage_collection)\n assert info[:fullsweep_after] == fullsweep_after\n end\n end\n\n test \"child_spec\/1\" do\n default_spec = %{\n id: Redix,\n start: {Redix, :start_link, []},\n type: :worker\n }\n\n args_path = [:start, Access.elem(2)]\n\n assert Redix.child_spec(\"redis:\/\/localhost\") ==\n put_in(default_spec, args_path, [\"redis:\/\/localhost\"])\n\n assert Redix.child_spec([]) == put_in(default_spec, args_path, [[]])\n assert Redix.child_spec(name: :redix) == put_in(default_spec, args_path, [[name: :redix]])\n\n assert Redix.child_spec({\"redis:\/\/localhost\", name: :redix}) ==\n put_in(default_spec, args_path, [\"redis:\/\/localhost\", [name: :redix]])\n end\n\n describe \"stop\/1\" do\n test \"stops the connection\" do\n {:ok, pid} = Redix.start_link()\n ref = Process.monitor(pid)\n assert Redix.stop(pid) == :ok\n\n assert_receive {:DOWN, ^ref, _, _, :normal}, 500\n end\n\n test \"closes the socket as well\" do\n {:ok, pid} = Redix.start_link(sync_connect: true)\n\n # This is a hack to get the socket. If I'll have a better idea, good for me :).\n {_, data} = :sys.get_state(pid)\n\n assert Port.info(data.socket) != nil\n assert Redix.stop(pid) == :ok\n assert Port.info(data.socket) == nil\n end\n end\n\n describe \"command\/2\" do\n setup :connect\n\n test \"PING\", %{conn: c} do\n assert Redix.command(c, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"transactions - MULTI\/EXEC\", %{conn: c} do\n assert Redix.command(c, [\"MULTI\"]) == {:ok, \"OK\"}\n assert Redix.command(c, [\"INCR\", \"multifoo\"]) == {:ok, \"QUEUED\"}\n assert Redix.command(c, [\"INCR\", \"multibar\"]) == {:ok, \"QUEUED\"}\n assert Redix.command(c, [\"INCRBY\", \"multifoo\", 4]) == {:ok, \"QUEUED\"}\n assert Redix.command(c, [\"EXEC\"]) == {:ok, [1, 1, 5]}\n end\n\n test \"transactions - MULTI\/DISCARD\", %{conn: c} do\n Redix.command!(c, [\"SET\", \"discarding\", \"foo\"])\n\n assert Redix.command(c, [\"MULTI\"]) == {:ok, \"OK\"}\n assert Redix.command(c, [\"SET\", \"discarding\", \"bar\"]) == {:ok, \"QUEUED\"}\n # Discarding\n assert Redix.command(c, [\"DISCARD\"]) == {:ok, \"OK\"}\n assert Redix.command(c, [\"GET\", \"discarding\"]) == {:ok, \"foo\"}\n end\n\n test \"Lua scripting - EVAL\", %{conn: c} do\n script = \"\"\"\n redis.call(\"SET\", \"evalling\", \"yes\")\n return {KEYS[1],ARGV[1],ARGV[2]}\n \"\"\"\n\n cmds = [\"eval\", script, \"1\", \"key\", \"first\", \"second\"]\n\n assert Redix.command(c, cmds) == {:ok, [\"key\", \"first\", \"second\"]}\n assert Redix.command(c, [\"GET\", \"evalling\"]) == {:ok, \"yes\"}\n end\n\n test \"command\/2 - Lua scripting: SCRIPT LOAD, SCRIPT EXISTS, EVALSHA\", %{conn: c} do\n script = \"\"\"\n return 'hello world'\n \"\"\"\n\n {:ok, sha} = Redix.command(c, [\"SCRIPT\", \"LOAD\", script])\n assert is_binary(sha)\n assert Redix.command(c, [\"SCRIPT\", \"EXISTS\", sha, \"foo\"]) == {:ok, [1, 0]}\n\n # Eval'ing the script\n assert Redix.command(c, [\"EVALSHA\", sha, 0]) == {:ok, \"hello world\"}\n end\n\n test \"Redis errors\", %{conn: c} do\n {:ok, _} = Redix.command(c, ~w(SET errs foo))\n\n message = \"ERR value is not an integer or out of range\"\n assert Redix.command(c, ~w(INCR errs)) == {:error, %Redix.Error{message: message}}\n end\n\n test \"passing an empty list returns an error\", %{conn: c} do\n message = \"got an empty command ([]), which is not a valid Redis command\"\n assert_raise ArgumentError, message, fn -> Redix.command(c, []) end\n end\n\n test \"timeout\", %{conn: c} do\n assert {:error, %ConnectionError{reason: :timeout}} = Redix.command(c, ~W(PING), timeout: 0)\n end\n\n test \"Redix process crashes while waiting\", %{conn: conn} do\n Process.flag(:trap_exit, true)\n\n pid =\n spawn_link(fn ->\n Redix.command(conn, ~w(BLPOP mid_command_disconnection 0))\n end)\n\n # We sleep to allow the task to issue the command to Redix.\n Process.sleep(100)\n\n Process.exit(conn, :kill)\n\n assert_receive {:EXIT, ^conn, :killed}\n assert_receive {:EXIT, ^pid, :killed}\n end\n\n test \"passing a non-list as the command\", %{conn: c} do\n message = \"expected a list of binaries as each Redis command, got: \\\"PING\\\"\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.command(c, \"PING\")\n end\n end\n end\n\n describe \"pipeline\/2\" do\n setup :connect\n\n test \"basic interaction\", %{conn: c} do\n commands = [\n [\"SET\", \"pipe\", \"10\"],\n [\"INCR\", \"pipe\"],\n [\"GET\", \"pipe\"]\n ]\n\n assert Redix.pipeline(c, commands) == {:ok, [\"OK\", 11, \"11\"]}\n end\n\n test \"a lot of commands so that TCP gets stressed\", %{conn: c} do\n assert {:ok, \"OK\"} = Redix.command(c, ~w(SET stress_pipeline foo))\n\n ncommands = 10000\n commands = List.duplicate(~w(GET stress_pipeline), ncommands)\n\n # Let's do it twice to be sure the server can handle the data.\n {:ok, results} = Redix.pipeline(c, commands)\n assert length(results) == ncommands\n {:ok, results} = Redix.pipeline(c, commands)\n assert length(results) == ncommands\n end\n\n test \"a single command should still return a list of results\", %{conn: c} do\n assert Redix.pipeline(c, [[\"PING\"]]) == {:ok, [\"PONG\"]}\n end\n\n test \"Redis errors in the response\", %{conn: c} do\n msg = \"ERR value is not an integer or out of range\"\n assert {:ok, resp} = Redix.pipeline(c, [~w(SET pipeline_errs foo), ~w(INCR pipeline_errs)])\n assert resp == [\"OK\", %Error{message: msg}]\n end\n\n test \"passing an empty list of commands raises an error\", %{conn: c} do\n msg = \"no commands passed to the pipeline\"\n assert_raise ArgumentError, msg, fn -> Redix.pipeline(c, []) end\n end\n\n test \"passing one or more empty commands returns an error\", %{conn: c} do\n message = \"got an empty command ([]), which is not a valid Redis command\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, [[]])\n end\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, [[\"PING\"], [], [\"PING\"]])\n end\n end\n\n test \"passing a PubSub command causes an error\", %{conn: c} do\n assert_raise ArgumentError, ~r{Redix doesn't support Pub\/Sub}, fn ->\n Redix.pipeline(c, [[\"PING\"], [\"SUBSCRIBE\", \"foo\"]])\n end\n end\n\n test \"timeout\", %{conn: c} do\n assert {:error, %ConnectionError{reason: :timeout}} =\n Redix.pipeline(c, [~w(PING), ~w(PING)], timeout: 0)\n end\n\n test \"commands must be lists of binaries\", %{conn: c} do\n message = \"expected a list of Redis commands, got: \\\"PING\\\"\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, \"PING\")\n end\n\n message = \"expected a list of binaries as each Redis command, got: \\\"PING\\\"\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, [\"PING\"])\n end\n end\n end\n\n describe \"command!\/2\" do\n setup :connect\n\n test \"simple commands\", %{conn: c} do\n assert Redix.command!(c, [\"PING\"]) == \"PONG\"\n assert Redix.command!(c, [\"SET\", \"bang\", \"foo\"]) == \"OK\"\n assert Redix.command!(c, [\"GET\", \"bang\"]) == \"foo\"\n end\n\n test \"Redis errors\", %{conn: c} do\n assert_raise Redix.Error, ~r\/ERR unknown command .NONEXISTENT.\/, fn ->\n Redix.command!(c, [\"NONEXISTENT\"])\n end\n\n \"OK\" = Redix.command!(c, [\"SET\", \"bang_errors\", \"foo\"])\n\n assert_raise Redix.Error, \"ERR value is not an integer or out of range\", fn ->\n Redix.command!(c, [\"INCR\", \"bang_errors\"])\n end\n end\n\n test \"connection errors\", %{conn: c} do\n assert_raise Redix.ConnectionError, \":timeout\", fn ->\n Redix.command!(c, [\"PING\"], timeout: 0)\n end\n end\n end\n\n describe \"pipeline!\/2\" do\n setup :connect\n\n test \"simple commands\", %{conn: c} do\n assert Redix.pipeline!(c, [~w(SET ppbang foo), ~w(GET ppbang)]) == ~w(OK foo)\n end\n\n test \"Redis errors in the list of results\", %{conn: c} do\n commands = [~w(SET ppbang_errors foo), ~w(INCR ppbang_errors)]\n\n msg = \"ERR value is not an integer or out of range\"\n assert Redix.pipeline!(c, commands) == [\"OK\", %Redix.Error{message: msg}]\n end\n\n test \"connection errors\", %{conn: c} do\n assert_raise Redix.ConnectionError, \":timeout\", fn ->\n Redix.pipeline!(c, [[\"PING\"]], timeout: 0)\n end\n end\n end\n\n describe \"transaction_pipeline\/3\" do\n setup :connect\n\n test \"non-bang version\", %{conn: conn} do\n commands = [~w(SET transaction_pipeline_key 1), ~w(GET transaction_pipeline_key)]\n assert Redix.transaction_pipeline(conn, commands) == {:ok, [\"OK\", \"1\"]}\n end\n\n test \"bang version\", %{conn: conn} do\n commands = [~w(SET transaction_pipeline_key 1), ~w(GET transaction_pipeline_key)]\n assert Redix.transaction_pipeline!(conn, commands) == [\"OK\", \"1\"]\n end\n end\n\n describe \"noreply_* functions\" do\n setup :connect\n\n test \"noreply_pipeline\/3\", %{conn: conn} do\n commands = [~w(INCR noreply_pl_mykey), ~w(INCR noreply_pl_mykey)]\n assert Redix.noreply_pipeline(conn, commands) == :ok\n assert Redix.command!(conn, ~w(GET noreply_pl_mykey)) == \"2\"\n end\n\n test \"noreply_command\/3\", %{conn: conn} do\n assert Redix.noreply_command(conn, [\"SET\", \"noreply_cmd_mykey\", \"myvalue\"]) == :ok\n assert Redix.command!(conn, [\"GET\", \"noreply_cmd_mykey\"]) == \"myvalue\"\n end\n end\n\n describe \"timeouts and network errors\" do\n setup :connect\n\n test \"client suicide and reconnections\", %{conn: c} do\n capture_log(fn ->\n assert {:ok, _} = Redix.command(c, ~w(QUIT))\n\n # When the socket is closed, we reply with {:error, closed}. We sleep so\n # we're sure that the socket is closed (and we don't get {:error,\n # disconnected} before the socket closed after we sent the PING command\n # to Redix).\n :timer.sleep(100)\n assert Redix.command(c, ~w(PING)) == {:error, %ConnectionError{reason: :closed}}\n\n # Redix retries the first reconnection after 500ms, and we waited 100 already.\n :timer.sleep(500)\n assert {:ok, \"PONG\"} = Redix.command(c, ~w(PING))\n end)\n end\n\n test \"timeouts\", %{conn: c} do\n assert {:error, %ConnectionError{reason: :timeout}} = Redix.command(c, ~w(PING), timeout: 0)\n\n # Let's check that the Redix connection doesn't reply anyways, even if the\n # timeout happened.\n refute_receive {_ref, _message}\n end\n\n test \"mid-command disconnections\", %{conn: conn} do\n {:ok, kill_conn} = Redix.start_link()\n\n capture_log(fn ->\n task = Task.async(fn -> Redix.command(conn, ~w(BLPOP mid_command_disconnection 0)) end)\n\n # Give the task the time to issue the command to Redis, then kill the connection.\n Process.sleep(50)\n Redix.command!(kill_conn, ~w(CLIENT KILL TYPE normal SKIPME yes))\n\n assert Task.await(task, 100) == {:error, %ConnectionError{reason: :disconnected}}\n end)\n end\n\n test \"no leaking messages when timeout happens at the same time as disconnections\", %{\n conn: conn\n } do\n {:ok, kill_conn} = Redix.start_link()\n\n capture_log(fn ->\n {_pid, ref} =\n Process.spawn(\n fn ->\n error = %ConnectionError{reason: :timeout}\n assert Redix.command(conn, ~w(BLPOP my_list 0), timeout: 0) == {:error, error}\n\n # The fact that we timed out should be respected here, even if the\n # connection is killed (no {:error, :disconnected} message should\n # arrive).\n refute_receive {_ref, _message}\n end,\n [:link, :monitor]\n )\n\n # Give the process time to issue the command to Redis, then kill the connection.\n Process.sleep(50)\n Redix.command!(kill_conn, ~w(CLIENT KILL TYPE normal SKIPME yes))\n\n assert_receive {:DOWN, ^ref, _, _, _}, 200\n end)\n end\n end\n\n test \":exit_on_disconnection option\" do\n {:ok, c} = Redix.start_link(exit_on_disconnection: true)\n Process.flag(:trap_exit, true)\n\n capture_log(fn ->\n Redix.command!(c, ~w(QUIT))\n assert_receive {:EXIT, ^c, %ConnectionError{reason: :tcp_closed}}\n end)\n end\n\n describe \"Telemetry\" do\n test \"emits events when starting a pipeline with pipeline\/3\" do\n {:ok, c} = Redix.start_link()\n {test_name, _arity} = __ENV__.function\n\n parent = self()\n ref = make_ref()\n\n handler = fn event, measurements, meta, _config ->\n if meta.connection == c do\n assert event == [:redix, :pipeline, :start]\n assert is_integer(measurements.system_time)\n assert meta.commands == [[\"PING\"]]\n end\n\n send(parent, ref)\n end\n\n :telemetry.attach(to_string(test_name), [:redix, :pipeline, :start], handler, :no_config)\n\n assert {:ok, [\"PONG\"]} = Redix.pipeline(c, [[\"PING\"]])\n\n assert_receive ^ref\n\n :telemetry.detach(to_string(test_name))\n end\n\n test \"emits events on successful pipelines with pipeline\/3\" do\n {:ok, c} = Redix.start_link()\n {test_name, _arity} = __ENV__.function\n\n parent = self()\n ref = make_ref()\n\n handler = fn event, measurements, meta, _config ->\n if meta.connection == c do\n assert event == [:redix, :pipeline, :stop]\n assert is_integer(measurements.duration) and measurements.duration > 0\n assert meta.commands == [[\"PING\"]]\n end\n\n send(parent, ref)\n end\n\n :telemetry.attach(to_string(test_name), [:redix, :pipeline, :stop], handler, :no_config)\n\n assert {:ok, [\"PONG\"]} = Redix.pipeline(c, [[\"PING\"]])\n\n assert_receive ^ref\n\n :telemetry.detach(to_string(test_name))\n end\n\n test \"emits events on error pipelines with pipeline\/3\" do\n {:ok, c} = Redix.start_link()\n {test_name, _arity} = __ENV__.function\n\n parent = self()\n ref = make_ref()\n\n handler = fn event, measurements, meta, _config ->\n if meta.connection == c do\n assert event == [:redix, :pipeline, :stop]\n assert is_integer(measurements.duration)\n assert meta.commands == [[\"PING\"], [\"PING\"]]\n assert meta.kind == :error\n assert meta.reason == %ConnectionError{reason: :timeout}\n end\n\n send(parent, ref)\n end\n\n :telemetry.attach(to_string(test_name), [:redix, :pipeline, :stop], handler, :no_config)\n\n assert {:error, %ConnectionError{reason: :timeout}} =\n Redix.pipeline(c, [~w(PING), ~w(PING)], timeout: 0)\n\n assert_receive ^ref\n\n :telemetry.detach(to_string(test_name))\n end\n\n test \"emits connection-related events on disconnections and reconnections\" do\n {test_name, _arity} = __ENV__.function\n\n parent = self()\n ref = make_ref()\n\n handler = fn event, measurements, meta, _config ->\n # We need to run this test only if was called for this Redix connection so that\n # we can run in parallel with the pubsub tests.\n if meta.connection == :redix_telemetry_test do\n assert measurements == %{}\n\n case event do\n [:redix, :connection] -> send(parent, {ref, :connected, meta})\n [:redix, :disconnection] -> send(parent, {ref, :disconnected, meta})\n end\n end\n end\n\n events = [[:redix, :connection], [:redix, :disconnection]]\n :ok = :telemetry.attach_many(to_string(test_name), events, handler, :no_config)\n\n {:ok, c} = Redix.start_link(name: :redix_telemetry_test)\n\n assert_receive {^ref, :connected, meta}, 1000\n assert %{address: \"localhost:6379\", connection: _, reconnection: false} = meta\n\n capture_log(fn ->\n assert {:ok, _} = Redix.command(c, ~w(QUIT))\n\n assert_receive {^ref, :disconnected, meta}, 1000\n assert %{address: \"localhost:6379\", connection: _} = meta\n\n assert_receive {^ref, :connected, meta}, 1000\n assert %{address: \"localhost:6379\", connection: _, reconnection: true} = meta\n end)\n end\n end\n\n defp connect(_context) do\n {:ok, conn} = Redix.start_link()\n {:ok, %{conn: conn}}\n end\nend\n","old_contents":"defmodule RedixTest do\n use ExUnit.Case, async: true\n\n import ExUnit.CaptureLog\n\n alias Redix.{\n ConnectionError,\n Error\n }\n\n setup_all do\n {:ok, conn} = Redix.start_link()\n Redix.command!(conn, [\"FLUSHALL\"])\n Redix.stop(conn)\n :ok\n end\n\n describe \"start_link\/2\" do\n test \"specifying a database\" do\n {:ok, c} = Redix.start_link(database: 1)\n assert Redix.command(c, ~w(SET my_key my_value)) == {:ok, \"OK\"}\n\n # Let's check we didn't write to the default database (which is 0).\n {:ok, c} = Redix.start_link()\n assert Redix.command(c, ~w(GET my_key)) == {:ok, nil}\n end\n\n test \"specifying a non existing database\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n {:ok, pid} = Redix.start_link(database: 1000)\n\n assert_receive {:EXIT, ^pid, %Error{message: message}}, 500\n assert message in [\"ERR invalid DB index\", \"ERR DB index is out of range\"]\n end)\n end\n\n test \"specifying a password when no password is set\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n {:ok, pid} = Redix.start_link(password: \"foo\")\n\n error = %Error{message: \"ERR Client sent AUTH, but no password is set\"}\n assert_receive {:EXIT, ^pid, ^error}, 500\n end)\n end\n\n test \"specifying a password when a password is set\" do\n {:ok, pid} = Redix.start_link(port: 16379, password: \"some-password\")\n assert Redix.command(pid, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"when unable to connect to Redis with sync_connect: true\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n error = %Redix.ConnectionError{reason: :nxdomain}\n assert Redix.start_link(host: \"nonexistent\", sync_connect: true) == {:error, error}\n assert_receive {:EXIT, _pid, ^error}, 1000\n end)\n end\n\n test \"when unable to connect to Redis with sync_connect: false\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n {:ok, pid} = Redix.start_link(host: \"nonexistent\", sync_connect: false)\n refute_receive {:EXIT, ^pid, :nxdomain}, 200\n end)\n end\n\n test \"using a redis:\/\/ url\" do\n {:ok, pid} = Redix.start_link(\"redis:\/\/localhost:6379\/3\")\n assert Redix.command(pid, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"using a rediss:\/\/ url, ignoring certificate\" do\n {:ok, pid} =\n Redix.start_link(\"rediss:\/\/localhost:6384\/3\",\n socket_opts: [verify: :verify_none, reuse_sessions: false]\n )\n\n assert Redix.command(pid, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"using a rediss:\/\/ url, unknown certificate\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n\n assert {:error, error} =\n Redix.start_link(\"rediss:\/\/localhost:6384\/3\",\n socket_opts: [reuse_sessions: false],\n sync_connect: true\n )\n\n assert %Redix.ConnectionError{reason: {:tls_alert, _}} = error\n assert_receive {:EXIT, _pid, ^error}, 1000\n end)\n end\n\n test \"name registration\" do\n {:ok, pid} = Redix.start_link(name: :redix_server)\n assert Process.whereis(:redix_server) == pid\n assert Redix.command(:redix_server, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"passing options along with a Redis URI\" do\n {:ok, pid} = Redix.start_link(\"redis:\/\/localhost\", name: :redix_uri)\n assert Process.whereis(:redix_uri) == pid\n end\n\n test \"using gen_statem options\" do\n fullsweep_after = Enum.random(0..50000)\n {:ok, pid} = Redix.start_link(spawn_opt: [fullsweep_after: fullsweep_after])\n {:garbage_collection, info} = Process.info(pid, :garbage_collection)\n assert info[:fullsweep_after] == fullsweep_after\n end\n end\n\n test \"child_spec\/1\" do\n default_spec = %{\n id: Redix,\n start: {Redix, :start_link, []},\n type: :worker\n }\n\n args_path = [:start, Access.elem(2)]\n\n assert Redix.child_spec(\"redis:\/\/localhost\") ==\n put_in(default_spec, args_path, [\"redis:\/\/localhost\"])\n\n assert Redix.child_spec([]) == put_in(default_spec, args_path, [[]])\n assert Redix.child_spec(name: :redix) == put_in(default_spec, args_path, [[name: :redix]])\n\n assert Redix.child_spec({\"redis:\/\/localhost\", name: :redix}) ==\n put_in(default_spec, args_path, [\"redis:\/\/localhost\", [name: :redix]])\n end\n\n describe \"stop\/1\" do\n test \"stops the connection\" do\n {:ok, pid} = Redix.start_link()\n ref = Process.monitor(pid)\n assert Redix.stop(pid) == :ok\n\n assert_receive {:DOWN, ^ref, _, _, :normal}, 500\n end\n\n test \"closes the socket as well\" do\n {:ok, pid} = Redix.start_link(sync_connect: true)\n\n # This is a hack to get the socket. If I'll have a better idea, good for me :).\n {_, data} = :sys.get_state(pid)\n\n assert Port.info(data.socket) != nil\n assert Redix.stop(pid) == :ok\n assert Port.info(data.socket) == nil\n end\n end\n\n describe \"command\/2\" do\n setup :connect\n\n test \"PING\", %{conn: c} do\n assert Redix.command(c, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"transactions - MULTI\/EXEC\", %{conn: c} do\n assert Redix.command(c, [\"MULTI\"]) == {:ok, \"OK\"}\n assert Redix.command(c, [\"INCR\", \"multifoo\"]) == {:ok, \"QUEUED\"}\n assert Redix.command(c, [\"INCR\", \"multibar\"]) == {:ok, \"QUEUED\"}\n assert Redix.command(c, [\"INCRBY\", \"multifoo\", 4]) == {:ok, \"QUEUED\"}\n assert Redix.command(c, [\"EXEC\"]) == {:ok, [1, 1, 5]}\n end\n\n test \"transactions - MULTI\/DISCARD\", %{conn: c} do\n Redix.command!(c, [\"SET\", \"discarding\", \"foo\"])\n\n assert Redix.command(c, [\"MULTI\"]) == {:ok, \"OK\"}\n assert Redix.command(c, [\"SET\", \"discarding\", \"bar\"]) == {:ok, \"QUEUED\"}\n # Discarding\n assert Redix.command(c, [\"DISCARD\"]) == {:ok, \"OK\"}\n assert Redix.command(c, [\"GET\", \"discarding\"]) == {:ok, \"foo\"}\n end\n\n test \"Lua scripting - EVAL\", %{conn: c} do\n script = \"\"\"\n redis.call(\"SET\", \"evalling\", \"yes\")\n return {KEYS[1],ARGV[1],ARGV[2]}\n \"\"\"\n\n cmds = [\"eval\", script, \"1\", \"key\", \"first\", \"second\"]\n\n assert Redix.command(c, cmds) == {:ok, [\"key\", \"first\", \"second\"]}\n assert Redix.command(c, [\"GET\", \"evalling\"]) == {:ok, \"yes\"}\n end\n\n test \"command\/2 - Lua scripting: SCRIPT LOAD, SCRIPT EXISTS, EVALSHA\", %{conn: c} do\n script = \"\"\"\n return 'hello world'\n \"\"\"\n\n {:ok, sha} = Redix.command(c, [\"SCRIPT\", \"LOAD\", script])\n assert is_binary(sha)\n assert Redix.command(c, [\"SCRIPT\", \"EXISTS\", sha, \"foo\"]) == {:ok, [1, 0]}\n\n # Eval'ing the script\n assert Redix.command(c, [\"EVALSHA\", sha, 0]) == {:ok, \"hello world\"}\n end\n\n test \"Redis errors\", %{conn: c} do\n {:ok, _} = Redix.command(c, ~w(SET errs foo))\n\n message = \"ERR value is not an integer or out of range\"\n assert Redix.command(c, ~w(INCR errs)) == {:error, %Redix.Error{message: message}}\n end\n\n test \"passing an empty list returns an error\", %{conn: c} do\n message = \"got an empty command ([]), which is not a valid Redis command\"\n assert_raise ArgumentError, message, fn -> Redix.command(c, []) end\n end\n\n test \"timeout\", %{conn: c} do\n assert {:error, %ConnectionError{reason: :timeout}} = Redix.command(c, ~W(PING), timeout: 0)\n end\n\n test \"Redix process crashes while waiting\", %{conn: conn} do\n Process.flag(:trap_exit, true)\n\n pid =\n spawn_link(fn ->\n Redix.command(conn, ~w(BLPOP mid_command_disconnection 0))\n end)\n\n # We sleep to allow the task to issue the command to Redix.\n Process.sleep(100)\n\n Process.exit(conn, :kill)\n\n assert_receive {:EXIT, ^conn, :killed}\n assert_receive {:EXIT, ^pid, :killed}\n end\n\n test \"passing a non-list as the command\", %{conn: c} do\n message = \"expected a list of binaries as each Redis command, got: \\\"PING\\\"\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.command(c, \"PING\")\n end\n end\n end\n\n describe \"pipeline\/2\" do\n setup :connect\n\n test \"basic interaction\", %{conn: c} do\n commands = [\n [\"SET\", \"pipe\", \"10\"],\n [\"INCR\", \"pipe\"],\n [\"GET\", \"pipe\"]\n ]\n\n assert Redix.pipeline(c, commands) == {:ok, [\"OK\", 11, \"11\"]}\n end\n\n test \"a lot of commands so that TCP gets stressed\", %{conn: c} do\n assert {:ok, \"OK\"} = Redix.command(c, ~w(SET stress_pipeline foo))\n\n ncommands = 10000\n commands = List.duplicate(~w(GET stress_pipeline), ncommands)\n\n # Let's do it twice to be sure the server can handle the data.\n {:ok, results} = Redix.pipeline(c, commands)\n assert length(results) == ncommands\n {:ok, results} = Redix.pipeline(c, commands)\n assert length(results) == ncommands\n end\n\n test \"a single command should still return a list of results\", %{conn: c} do\n assert Redix.pipeline(c, [[\"PING\"]]) == {:ok, [\"PONG\"]}\n end\n\n test \"Redis errors in the response\", %{conn: c} do\n msg = \"ERR value is not an integer or out of range\"\n assert {:ok, resp} = Redix.pipeline(c, [~w(SET pipeline_errs foo), ~w(INCR pipeline_errs)])\n assert resp == [\"OK\", %Error{message: msg}]\n end\n\n test \"passing an empty list of commands raises an error\", %{conn: c} do\n msg = \"no commands passed to the pipeline\"\n assert_raise ArgumentError, msg, fn -> Redix.pipeline(c, []) end\n end\n\n test \"passing one or more empty commands returns an error\", %{conn: c} do\n message = \"got an empty command ([]), which is not a valid Redis command\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, [[]])\n end\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, [[\"PING\"], [], [\"PING\"]])\n end\n end\n\n test \"passing a PubSub command causes an error\", %{conn: c} do\n assert_raise ArgumentError, ~r{Redix doesn't support Pub\/Sub}, fn ->\n Redix.pipeline(c, [[\"PING\"], [\"SUBSCRIBE\", \"foo\"]])\n end\n end\n\n test \"timeout\", %{conn: c} do\n assert {:error, %ConnectionError{reason: :timeout}} =\n Redix.pipeline(c, [~w(PING), ~w(PING)], timeout: 0)\n end\n\n test \"commands must be lists of binaries\", %{conn: c} do\n message = \"expected a list of Redis commands, got: \\\"PING\\\"\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, \"PING\")\n end\n\n message = \"expected a list of binaries as each Redis command, got: \\\"PING\\\"\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, [\"PING\"])\n end\n end\n end\n\n describe \"command!\/2\" do\n setup :connect\n\n test \"simple commands\", %{conn: c} do\n assert Redix.command!(c, [\"PING\"]) == \"PONG\"\n assert Redix.command!(c, [\"SET\", \"bang\", \"foo\"]) == \"OK\"\n assert Redix.command!(c, [\"GET\", \"bang\"]) == \"foo\"\n end\n\n test \"Redis errors\", %{conn: c} do\n assert_raise Redix.Error, ~r\/ERR unknown command .NONEXISTENT.\/, fn ->\n Redix.command!(c, [\"NONEXISTENT\"])\n end\n\n \"OK\" = Redix.command!(c, [\"SET\", \"bang_errors\", \"foo\"])\n\n assert_raise Redix.Error, \"ERR value is not an integer or out of range\", fn ->\n Redix.command!(c, [\"INCR\", \"bang_errors\"])\n end\n end\n\n test \"connection errors\", %{conn: c} do\n assert_raise Redix.ConnectionError, \":timeout\", fn ->\n Redix.command!(c, [\"PING\"], timeout: 0)\n end\n end\n end\n\n describe \"pipeline!\/2\" do\n setup :connect\n\n test \"simple commands\", %{conn: c} do\n assert Redix.pipeline!(c, [~w(SET ppbang foo), ~w(GET ppbang)]) == ~w(OK foo)\n end\n\n test \"Redis errors in the list of results\", %{conn: c} do\n commands = [~w(SET ppbang_errors foo), ~w(INCR ppbang_errors)]\n\n msg = \"ERR value is not an integer or out of range\"\n assert Redix.pipeline!(c, commands) == [\"OK\", %Redix.Error{message: msg}]\n end\n\n test \"connection errors\", %{conn: c} do\n assert_raise Redix.ConnectionError, \":timeout\", fn ->\n Redix.pipeline!(c, [[\"PING\"]], timeout: 0)\n end\n end\n end\n\n describe \"transaction_pipeline\/3\" do\n setup :connect\n\n test \"non-bang version\", %{conn: conn} do\n commands = [~w(SET transaction_pipeline_key 1), ~w(GET transaction_pipeline_key)]\n assert Redix.transaction_pipeline(conn, commands) == {:ok, [\"OK\", \"1\"]}\n end\n\n test \"bang version\", %{conn: conn} do\n commands = [~w(SET transaction_pipeline_key 1), ~w(GET transaction_pipeline_key)]\n assert Redix.transaction_pipeline!(conn, commands) == [\"OK\", \"1\"]\n end\n end\n\n describe \"noreply_* functions\" do\n setup :connect\n\n test \"noreply_pipeline\/3\", %{conn: conn} do\n commands = [~w(INCR noreply_pl_mykey), ~w(INCR noreply_pl_mykey)]\n assert Redix.noreply_pipeline(conn, commands) == :ok\n assert Redix.command!(conn, ~w(GET noreply_pl_mykey)) == \"2\"\n end\n\n test \"noreply_command\/3\", %{conn: conn} do\n assert Redix.noreply_command(conn, [\"SET\", \"noreply_cmd_mykey\", \"myvalue\"]) == :ok\n assert Redix.command!(conn, [\"GET\", \"noreply_cmd_mykey\"]) == \"myvalue\"\n end\n end\n\n describe \"timeouts and network errors\" do\n setup :connect\n\n test \"client suicide and reconnections\", %{conn: c} do\n capture_log(fn ->\n assert {:ok, _} = Redix.command(c, ~w(QUIT))\n\n # When the socket is closed, we reply with {:error, closed}. We sleep so\n # we're sure that the socket is closed (and we don't get {:error,\n # disconnected} before the socket closed after we sent the PING command\n # to Redix).\n :timer.sleep(100)\n assert Redix.command(c, ~w(PING)) == {:error, %ConnectionError{reason: :closed}}\n\n # Redix retries the first reconnection after 500ms, and we waited 100 already.\n :timer.sleep(500)\n assert {:ok, \"PONG\"} = Redix.command(c, ~w(PING))\n end)\n end\n\n test \"timeouts\", %{conn: c} do\n assert {:error, %ConnectionError{reason: :timeout}} = Redix.command(c, ~w(PING), timeout: 0)\n\n # Let's check that the Redix connection doesn't reply anyways, even if the\n # timeout happened.\n refute_receive {_ref, _message}\n end\n\n test \"mid-command disconnections\", %{conn: conn} do\n {:ok, kill_conn} = Redix.start_link()\n\n capture_log(fn ->\n task = Task.async(fn -> Redix.command(conn, ~w(BLPOP mid_command_disconnection 0)) end)\n\n # Give the task the time to issue the command to Redis, then kill the connection.\n Process.sleep(50)\n Redix.command!(kill_conn, ~w(CLIENT KILL TYPE normal SKIPME yes))\n\n assert Task.await(task, 100) == {:error, %ConnectionError{reason: :disconnected}}\n end)\n end\n\n test \"no leaking messages when timeout happens at the same time as disconnections\", %{\n conn: conn\n } do\n {:ok, kill_conn} = Redix.start_link()\n\n capture_log(fn ->\n {_pid, ref} =\n Process.spawn(\n fn ->\n error = %ConnectionError{reason: :timeout}\n assert Redix.command(conn, ~w(BLPOP my_list 0), timeout: 0) == {:error, error}\n\n # The fact that we timed out should be respected here, even if the\n # connection is killed (no {:error, :disconnected} message should\n # arrive).\n refute_receive {_ref, _message}\n end,\n [:link, :monitor]\n )\n\n # Give the process time to issue the command to Redis, then kill the connection.\n Process.sleep(50)\n Redix.command!(kill_conn, ~w(CLIENT KILL TYPE normal SKIPME yes))\n\n assert_receive {:DOWN, ^ref, _, _, _}, 200\n end)\n end\n end\n\n test \":exit_on_disconnection option\" do\n {:ok, c} = Redix.start_link(exit_on_disconnection: true)\n Process.flag(:trap_exit, true)\n\n capture_log(fn ->\n Redix.command!(c, ~w(QUIT))\n assert_receive {:EXIT, ^c, %ConnectionError{reason: :tcp_closed}}\n end)\n end\n\n describe \"Telemetry\" do\n test \"emits events when starting a pipeline with pipeline\/3\" do\n {:ok, c} = Redix.start_link()\n {test_name, _arity} = __ENV__.function\n\n parent = self()\n ref = make_ref()\n\n handler = fn event, measurements, meta, _config ->\n if meta.connection == c do\n assert event == [:redix, :pipeline, :start]\n assert is_integer(measurements.system_time)\n assert meta.commands == [[\"PING\"]]\n end\n\n send(parent, ref)\n end\n\n :telemetry.attach(to_string(test_name), [:redix, :pipeline, :start], handler, :no_config)\n\n assert {:ok, [\"PONG\"]} = Redix.pipeline(c, [[\"PING\"]])\n\n assert_receive ^ref\n\n :telemetry.detach(to_string(test_name))\n end\n\n test \"emits events on successful pipelines with pipeline\/3\" do\n {:ok, c} = Redix.start_link()\n {test_name, _arity} = __ENV__.function\n\n parent = self()\n ref = make_ref()\n\n handler = fn event, measurements, meta, _config ->\n if meta.connection == c do\n assert event == [:redix, :pipeline, :stop]\n assert is_integer(measurements.duration) and measurements.duration > 0\n assert meta.commands == [[\"PING\"]]\n end\n\n send(parent, ref)\n end\n\n :telemetry.attach(to_string(test_name), [:redix, :pipeline, :stop], handler, :no_config)\n\n assert {:ok, [\"PONG\"]} = Redix.pipeline(c, [[\"PING\"]])\n\n assert_receive ^ref\n\n :telemetry.detach(to_string(test_name))\n end\n\n test \"emits events on error pipelines with pipeline\/3\" do\n {:ok, c} = Redix.start_link()\n {test_name, _arity} = __ENV__.function\n\n parent = self()\n ref = make_ref()\n\n handler = fn event, measurements, meta, _config ->\n if meta.connection == c do\n assert event == [:redix, :pipeline, :stop]\n assert is_integer(measurements.duration)\n assert meta.commands == [[\"PING\"], [\"PING\"]]\n assert meta.kind == :error\n assert meta.reason == %ConnectionError{reason: :timeout}\n end\n\n send(parent, ref)\n end\n\n :telemetry.attach(to_string(test_name), [:redix, :pipeline, :stop], handler, :no_config)\n\n assert {:error, %ConnectionError{reason: :timeout}} =\n Redix.pipeline(c, [~w(PING), ~w(PING)], timeout: 0)\n\n assert_receive ^ref\n\n :telemetry.detach(to_string(test_name))\n end\n\n test \"emits connection-related events on disconnections and reconnections\" do\n {test_name, _arity} = __ENV__.function\n\n parent = self()\n ref = make_ref()\n\n handler = fn event, measurements, meta, _config ->\n # We need to run this test only if was called for this Redix connection so that\n # we can run in parallel with the pubsub tests.\n if meta.connection == :redix_telemetry_test do\n assert measurements == %{}\n\n case event do\n [:redix, :connection] -> send(parent, {ref, :connected, meta})\n [:redix, :disconnection] -> send(parent, {ref, :disconnected, meta})\n end\n end\n end\n\n events = [[:redix, :connection], [:redix, :disconnection]]\n :ok = :telemetry.attach_many(to_string(test_name), events, handler, :no_config)\n\n {:ok, c} = Redix.start_link(name: :redix_telemetry_test)\n\n assert_receive {^ref, :connected, meta}, 1000\n assert %{address: \"localhost:6379\", connection: _, reconnection: false} = meta\n\n capture_log(fn ->\n assert {:ok, _} = Redix.command(c, ~w(QUIT))\n\n assert_receive {^ref, :disconnected, meta}, 1000\n assert %{address: \"localhost:6379\", connection: _} = meta\n\n assert_receive {^ref, :connected, meta}, 1000\n assert %{address: \"localhost:6379\", connection: _, reconnection: true} = meta\n end)\n end\n end\n\n defp connect(_context) do\n {:ok, conn} = Redix.start_link()\n {:ok, %{conn: conn}}\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"16fd141a924cf7aa804b84de5d742423a0e3339a","subject":"get elixir iex hot code reloading","message":"get elixir iex hot code reloading\n\nhttp:\/\/stackoverflow.com\/q\/32540703\n","repos":"atweiden\/dotfiles,atweiden\/dotfiles,atweiden\/dotfiles,atweiden\/dotfiles,atweiden\/dotfiles","old_file":".iex.exs","new_file":".iex.exs","new_contents":"IEx.configure colors: [ eval_result: [:cyan,:bright] ]\n\ndefmodule R do\n def reload! do\n Mix.Task.reenable \"compile.elixir\"\n Application.stop(Mix.Project.config[:app])\n Mix.Task.run \"compile.elixir\"\n Application.start(Mix.Project.config[:app], :permanent)\n end\nend\n","old_contents":"IEx.configure colors: [ eval_result: [:cyan,:bright] ]\n","returncode":0,"stderr":"","license":"unlicense","lang":"Elixir"} {"commit":"32cc18a8a667873de5b9ad69ffdd99d9ae24c94d","subject":"Bump agent to d54a76a","message":"Bump agent to d54a76a\n\n- Add APPSIGNAL_IGNORE_NAMESPACES config option. Agent PR 255\n- Reorder arguments of record_event function. Agent PR 259\n","repos":"appsignal\/appsignal-elixir,appsignal\/appsignal-elixir,appsignal\/appsignal-elixir,appsignal\/appsignal-elixir","old_file":"agent.ex","new_file":"agent.ex","new_contents":"defmodule Appsignal.Agent do\n def version, do: \"d54a76a\"\n\n def triples do\n %{\n \"x86_64-linux\" => %{\n checksum: \"281d91b060365e05fc2df94eb88b0b8d7f6fde06c439829bdd170f202f5aa5b1\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/d54a76a\/appsignal-x86_64-linux-all-static.tar.gz\"\n },\n \"i686-linux\" => %{\n checksum: \"91e9d317a45d0a5e1a03b5a12480c221182b8f460638532181b58b362941d3d5\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/d54a76a\/appsignal-i686-linux-all-static.tar.gz\"\n },\n \"x86-linux\" => %{\n checksum: \"91e9d317a45d0a5e1a03b5a12480c221182b8f460638532181b58b362941d3d5\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/d54a76a\/appsignal-i686-linux-all-static.tar.gz\"\n },\n \"x86_64-darwin\" => %{\n checksum: \"f9732af3f4913341d0ec70474d893472fd1bf9720c5cea098a24be92379872aa\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/d54a76a\/appsignal-x86_64-darwin-all-static.tar.gz\"\n },\n \"universal-darwin\" => %{\n checksum: \"f9732af3f4913341d0ec70474d893472fd1bf9720c5cea098a24be92379872aa\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/d54a76a\/appsignal-x86_64-darwin-all-static.tar.gz\"\n },\n }\n end\nend\n","old_contents":"defmodule Appsignal.Agent do\n def version, do: \"f16607c\"\n\n def triples do\n %{\n \"x86_64-linux\" => %{\n checksum: \"0479e8b0aeba95360e9fd8cfd7e7f7f4c1a8dfc555f6149c0c35d27593a05193\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/f16607c\/appsignal-x86_64-linux-all-static.tar.gz\"\n },\n \"i686-linux\" => %{\n checksum: \"3c3c63f26bec0304649cad4fb69410dd6b13313a178f3db7cdeba72b24834715\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/f16607c\/appsignal-i686-linux-all-static.tar.gz\"\n },\n \"x86-linux\" => %{\n checksum: \"3c3c63f26bec0304649cad4fb69410dd6b13313a178f3db7cdeba72b24834715\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/f16607c\/appsignal-i686-linux-all-static.tar.gz\"\n },\n \"x86_64-darwin\" => %{\n checksum: \"853398d93cda5f16edd2a931346f97fedea4c16f729bb987564cfbc29e73ef33\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/f16607c\/appsignal-x86_64-darwin-all-static.tar.gz\"\n },\n \"universal-darwin\" => %{\n checksum: \"853398d93cda5f16edd2a931346f97fedea4c16f729bb987564cfbc29e73ef33\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/f16607c\/appsignal-x86_64-darwin-all-static.tar.gz\"\n },\n }\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"d4ea2d82d43a5b938dc1ca520cd549bdf2b36174","subject":"TrialServer: Save generated trial in store agent","message":"TrialServer: Save generated trial in store agent\n","repos":"SteffenBauer\/mia_elixir,SteffenBauer\/mia_elixir","old_file":"trial_server\/lib\/trial_server\/store.ex","new_file":"trial_server\/lib\/trial_server\/store.ex","new_contents":"defmodule TrialServer.Store do\n\n require Logger\n\n defstruct addr: nil, port: nil, uuid: nil,\n solution: nil, trials: 5, correct: 0, wrong: 0\n\n def init() do\n Logger.debug(\"TrialServer Store started\")\n []\n end\n\n def addr_in_store?(addr) do\n Agent.get(__MODULE__, fn e -> Enum.any?(e, &(&1.addr == addr)) end)\n end\n\n def new_trial(addr, port, uuid, solution) do\n Agent.update(__MODULE__, &(&1 ++ [%TrialServer.Store{addr: addr, port: port, uuid: uuid, solution: solution}]))\n Logger.debug(\"In store now: #{inspect Agent.get(__MODULE__, &(&1))}\")\n end\n\nend\n","old_contents":"defmodule TrialServer.Store do\n\n require Logger\n\n defstruct addr: nil, port: nil, uuid: nil,\n solution: nil, trials: nil, correct: 0, wrong: 0\n\n def init() do\n Logger.debug(\"TrialServer Store started\")\n []\n end\n\n def addr_in_store?(addr) do\n Agent.get(__MODULE__, fn e -> Enum.any?(e, &(&1.addr == addr)) end)\n end\n\n def new_trial(addr, port, uuid, solution) do\n\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"18c8efcb91b45bfab708c990c7a28dd607fd7111","subject":"Support for IoCmd command args, as cd:","message":"Support for IoCmd command args, as cd:\n","repos":"serverboards\/serverboards,serverboards\/serverboards,serverboards\/serverboards,serverboards\/serverboards,serverboards\/serverboards","old_file":"backend\/apps\/io_cmd\/lib\/io_cmd.ex","new_file":"backend\/apps\/io_cmd\/lib\/io_cmd.ex","new_contents":"require Logger\n\ndefmodule Serverboards.IoCmd do\n\tuse GenServer\n\n\t@doc ~S\"\"\"\n\tRuns a command (to properly shlex), and returns the handler to be able to\n\tcomunicate with it\n\n\t\tiex> {:ok, ls} = Serverboards.IoCmd.start_link(\"test\/ls\/ls.py\")\n\t\tiex> Serverboards.IoCmd.call( ls, \"ls\", [\".\"])\n\t\t[\".gitignore\", \"test\", \"lib\", \"mix.exs\", \"config\", \"README.md\"]\n\t\tiex> Serverboards.IoCmd.call( ls, \"ls\", [\".\"])\n\t\t[\".gitignore\", \"test\", \"lib\", \"mix.exs\", \"config\", \"README.md\"]\n\n\t\"\"\"\n\tdef start_link(cmd, args \\\\ [], cmdopts \\\\ [], opts \\\\ []) do\n\t\tGenServer.start_link(__MODULE__, {cmd, args, cmdopts}, opts)\n\tend\n\n\tdef init({cmd, args, cmdopts}) do\n\t\tfullcmd=\"#{System.cwd}\/#{cmd}\"\n\n\t\tcmdopts = cmdopts ++ [:stream, :line, :use_stdio, args: args]\n\t\tport = Port.open({:spawn_executable, cmd}, cmdopts)\n\t\tLogger.debug(\"Starting command #{fullcmd} at port #{inspect port}\")\n\t\tPort.connect(port, self())\n\n\t\tstate=%{\n\t\t\tcmd: cmd,\n\t\t\tport: port,\n\t\t\tmsgid: 0, # increases on each new message\n\t\t\twaiting: %{}, # msgid we are still waiting answer from, and port to send it\n\t\t}\n\t\t{:ok, state}\n\tend\n\n\t@doc ~S\"\"\"\n\tBlocking call to the given process, returns the result.\n\t\"\"\"\n\tdef call(server, method, params) do\n\t\tLogger.debug(\"Calling #{method}(#{inspect params})\")\n\t\tGenServer.call(server, {:call, %{ method: method, params: params}})\n\tend\n\n\tdef handle_call({:call, msg}, from, %{ msgid: msgid, waiting: waiting, port: port } = state) do\n\t\t{:ok, json} = JSON.encode( Map.put( msg, :id, msgid ) ) # FIXME id has to change over time\n\t\tstate=%{state | msgid: msgid+1, waiting: Map.put(waiting, msgid, from) }\n\t\t#Logger.debug(\"Calling #{inspect state.port} method with this json: #{json}\")\n\t\t# Send command and \\n\n\t\tPort.command(port, \"#{json}\\n\")\n\n\t\t{:noreply, state}\n\tend\n\n\tdef handle_cast(msg, state) do\n\t\tLogger.debug(\"Got cast #{inspect msg}\")\n\t\t{:noreply, state}\n\tend\n\n\tdef handle_info({ _, {:data, {:eol, json}}}, state) do\n\n\t\t{:ok, msg} = JSON.decode( json )\n\t\tstate = case msg do\n\t\t\t%{\"result\" => result, \"id\" => msgid} -> # response\n\t\t\t\tto = Map.get(state.waiting, msgid)\n\t\t\t\tLogger.debug(\"Answer is #{inspect result} for id #{msgid}\")\n\t\t\t\tGenServer.reply(to, result)\n\t\t\t\t%{ state | waiting: Map.drop(state.waiting, [msgid]) }\n\t\t\t\tstate\n\t\t\t%{\"method\" => _, \"params\" => _} -> # new call, async\n\t\t\t\tLogger.debug(\"No broadcast messages yet\")\n\t\t\t\tstate\n\t\t\tother ->\n\t\t\t\tLogger.debug(\"Dont know how to process #{inspect other}\")\n\t\t\t\tstate\n\t\tend\n {:noreply, state}\n end\nend\n","old_contents":"require Logger\n\ndefmodule Serverboards.IoCmd do\n\tuse GenServer\n\n\t@doc ~S\"\"\"\n\tRuns a command (to properly shlex), and returns the handler to be able to\n\tcomunicate with it\n\n\t\tiex> {:ok, ls} = Serverboards.IoCmd.start_link(\"test\/ls\/ls.py\")\n\t\tiex> Serverboards.IoCmd.call( ls, \"ls\", [\".\"])\n\t\t[\".gitignore\", \"test\", \"lib\", \"mix.exs\", \"config\", \"README.md\"]\n\t\tiex> Serverboards.IoCmd.call( ls, \"ls\", [\".\"])\n\t\t[\".gitignore\", \"test\", \"lib\", \"mix.exs\", \"config\", \"README.md\"]\n\n\t\"\"\"\n\tdef start_link(cmd, opts \\\\ []) do\n\t\tGenServer.start_link(__MODULE__, cmd, opts)\n\tend\n\n\tdef init(cmd) do\n\t\tfullcmd=\"#{System.cwd}\/#{cmd}\"\n\t\tport = Port.open({:spawn_executable, cmd}, [:stream, :line, :use_stdio])\n\t\tLogger.debug(\"Starting command #{fullcmd} at port #{inspect port}\")\n\t\tPort.connect(port, self())\n\n\t\tstate=%{\n\t\t\tcmd: cmd,\n\t\t\tport: port,\n\t\t\tmsgid: 0, # increases on each new message\n\t\t\twaiting: %{}, # msgid we are still waiting answer from, and port to send it\n\t\t}\n\t\t{:ok, state}\n\tend\n\n\t@doc ~S\"\"\"\n\tBlocking call to the given process, returns the result.\n\t\"\"\"\n\tdef call(server, method, params) do\n\t\tLogger.debug(\"Calling #{method}(#{inspect params})\")\n\t\tGenServer.call(server, {:call, %{ method: method, params: params}})\n\tend\n\n\tdef handle_call({:call, msg}, from, %{ msgid: msgid, waiting: waiting, port: port } = state) do\n\t\t{:ok, json} = JSON.encode( Map.put( msg, :id, msgid ) ) # FIXME id has to change over time\n\t\tstate=%{state | msgid: msgid+1, waiting: Map.put(waiting, msgid, from) }\n\t\t#Logger.debug(\"Calling #{inspect state.port} method with this json: #{json}\")\n\t\t# Send command and \\n\n\t\tPort.command(port, \"#{json}\\n\")\n\n\t\t{:noreply, state}\n\tend\n\n\tdef handle_cast(msg, state) do\n\t\tLogger.debug(\"Got cast #{inspect msg}\")\n\t\t{:noreply, state}\n\tend\n\n\tdef handle_info({ _, {:data, {:eol, json}}}, state) do\n\n\t\t{:ok, msg} = JSON.decode( json )\n\t\tstate = case msg do\n\t\t\t%{\"result\" => result, \"id\" => msgid} -> # response\n\t\t\t\tto = Map.get(state.waiting, msgid)\n\t\t\t\tLogger.debug(\"Answer is #{inspect result} for id #{msgid}\")\n\t\t\t\tGenServer.reply(to, result)\n\t\t\t\t%{ state | waiting: Map.drop(state.waiting, [msgid]) }\n\t\t\t\tstate\n\t\t\t%{\"method\" => _, \"params\" => _} -> # new call, async\n\t\t\t\tLogger.debug(\"No broadcast messages yet\")\n\t\t\t\tstate\n\t\t\tother ->\n\t\t\t\tLogger.debug(\"Dont know how to process #{inspect other}\")\n\t\t\t\tstate\n\t\tend\n {:noreply, state}\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"6c6c8c8d48cbb82a2f03f7fb778e1efb6f227d8e","subject":"Fix use of new router at io_tcp.","message":"Fix use of new router at io_tcp.\n","repos":"serverboards\/serverboards,serverboards\/serverboards,serverboards\/serverboards,serverboards\/serverboards,serverboards\/serverboards","old_file":"backend\/apps\/io_tcp\/lib\/io_tcp.ex","new_file":"backend\/apps\/io_tcp\/lib\/io_tcp.ex","new_contents":"require Logger\nrequire JSON\n\ndefmodule Serverboards.IoTcp do\n\tuse Application\n\talias Serverboards.{IoTcp, Router, Peer}\n\n\tdef start(_type, _args) do\n\t\timport Supervisor.Spec\n\n\t\t{:ok, router} = Router.Basic.start_link\n\n\t\tchildren = [\n\t\t\tworker(Task, [IoTcp, :accept, [router, 4040]])\n\t\t]\n\n\t\topts = [strategy: :one_for_one, name: IoTcp.Supervisor]\n\n\t\tSupervisor.start_link(children, opts)\n\tend\n\n\tdef accept(router, port) do\n\t\t{:ok, socket} = :gen_tcp.listen(port,\n\t\t \t[:binary, packet: :line, active: false, reuseaddr: true])\n\t\tLogger.info(\"Accepting TCP connections at #{port}\")\n\n\t\tloop_acceptor(router, socket)\n\tend\n\n\tdef close(socket) do\n\t\t:gen_tcp.close(socket)\n\tend\n\n\tdef loop_acceptor(router, listen_socket) do\n\t\tcase :gen_tcp.accept(listen_socket) do\n\t\t\t{:ok, client} ->\n\t\t\t\tserve(router, client)\n\t\t\t\tloop_acceptor(router, listen_socket)\n\t\t\t{:error, :closed } ->\n\t\t\t\tnil\n\t\tend\n\tend\n\n\tdef serve(router, socket) do\n\t\tcase :gen_tcp.recv(socket, 0) do\n\t\t\t{:ok, line} ->\n\t\t\t\t#Logger.debug(\"Got data #{line}\")\n\t\t\t\t{:ok, %{ \"method\" => method, \"params\" => params, \"id\" => id}} = JSON.decode(line)\n\t\t\t\t{:ok, callable, method} = Router.lookup(router, method)\n\n\t\t\t\t#Logger.debug(\"Found #{inspect {callable,method}}\")\n\n\t\t\t\tres=Peer.call(callable, method, params)\n\t\t\t\t{:ok, res}=JSON.encode( %{ \"result\" => res, \"id\" => id})\n\t\t\t\t#Logger.debug(\"Got answer #{res}, writing to #{inspect socket}\")\n\n\t\t\t\t:gen_tcp.send(socket, res <> \"\\n\")\n\n\t\t\t\tserve(router, socket)\n\t\t\t{:error, :closed} ->\n\t\t\t\tnil\n\t\tend\n\tend\nend\n","old_contents":"require Logger\nrequire JSON\n\ndefmodule Serverboards.IoTcp do\n\tuse Application\n\talias Serverboards.IoTcp, as: IoTcp\n\talias Serverboards.Router, as: Router\n\n\tdef start(_type, _args) do\n\t\timport Supervisor.Spec\n\n\t\trouter=Router\n\n\t\tchildren = [\n\t\t\tworker(Task, [IoTcp, :accept, [router, 4040]])\n\t\t]\n\n\t\topts = [strategy: :one_for_one, name: IoTcp.Supervisor]\n\n\t\tSupervisor.start_link(children, opts)\n\tend\n\n\tdef accept(router, port) do\n\t\t{:ok, socket} = :gen_tcp.listen(port,\n\t\t \t[:binary, packet: :line, active: false, reuseaddr: true])\n\t\tLogger.info(\"Accepting TCP connections at #{port}\")\n\n\t\tloop_acceptor(router, socket)\n\tend\n\n\tdef close(socket) do\n\t\t:gen_tcp.close(socket)\n\tend\n\n\tdef loop_acceptor(router, listen_socket) do\n\t\tcase :gen_tcp.accept(listen_socket) do\n\t\t\t{:ok, client} ->\n\t\t\t\tserve(router, client)\n\t\t\t\tloop_acceptor(router, listen_socket)\n\t\t\t{:error, :closed } ->\n\t\t\t\tnil\n\t\tend\n\tend\n\n\tdef serve(router, socket) do\n\t\tcase :gen_tcp.recv(socket, 0) do\n\t\t\t{:ok, line} ->\n\t\t\t\t#Logger.debug(\"Got data #{line}\")\n\t\t\t\tres = Router.call_json(router, line)\n\t\t\t\t#Logger.debug(\"Got answer #{line}\")\n\n\t\t\t\t:gen_tcp.send(socket, res <> \"\\n\")\n\n\t\t\t\tserve(router, socket)\n\t\t\t{:error, :closed} ->\n\t\t\t\tnil\n\t\tend\n\tend\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"f648af41fc8bfe84c1072773b695e757125c7f09","subject":"Fixing tests for expand macro","message":"Fixing tests for expand macro\n","repos":"msaraiva\/atom-elixir","old_file":"lib\/alchemist-server\/test\/server_test.exs","new_file":"lib\/alchemist-server\/test\/server_test.exs","new_contents":"Code.require_file \"test_helper.exs\", __DIR__\nCode.require_file \"..\/lib\/server.exs\", __DIR__\n\ndefmodule ServerTest do\n use ExUnit.Case\n import ExUnit.CaptureIO\n\n @buffer_file \"#{__DIR__}\/my_module.ex\"\n\n setup_all do\n on_exit fn ->\n {_status, files} = File.ls Path.expand(\"fixtures\", __DIR__)\n files |> Enum.each(fn(file) ->\n unless file == \".gitkeep\" do\n File.rm Path.expand(\"fixtures\/#{file}\", __DIR__)\n end\n end)\n end\n end\n\n test \"Expression completion\" do\n assert send_signal(\"COMP { 'def', \\\"#{@buffer_file}\\\", 2}\") =~ \"\"\"\n defoverridable\/1;macro;keywords;Kernel;Makes the given functions in the current module overridable.;\n \"\"\"\n end\n\n test \"Documentation lookup\" do\n assert send_signal(\"DOCL { 'List', \\\"#{@buffer_file}\\\", 2}\") =~ \"\"\"\n > List\\n\\nSpecialized functions that only work on lists.\n \"\"\"\n end\n\n test \"Getting the definition source file information of code\" do\n assert send_signal(\"DEFL {\\\"List,delete\\\", \\\"#{@buffer_file}\\\", \\\"#{@buffer_file}\\\", 2}\") =~ \"\/lib\/elixir\/lib\/list.ex\"\n end\n\n test \"Evaluate the content of a file\" do\n filename = Path.expand(\"fixtures\/eval_fixture.exs\", __DIR__)\n File.write(filename, \"1+1\")\n assert send_signal(\"EVAL { :eval, '#{filename}' }\") =~ \"2\"\n end\n\n test \"Evaluate and quote the content of a file\" do\n filename = Path.expand(\"fixtures\/eval_and_quote_fixture.exs\", __DIR__)\n File.write(filename, \"[4,2,1,3] |> Enum.sort\")\n assert send_signal(\"EVAL { :quote, '#{filename}' }\") =~ \"\"\"\n {{:., [line: 1], [{:__aliases__, [counter: 0, line: 1], [:Enum]}, :sort]},\\n [line: 1], []}]}\n \"\"\"\n end\n\n test \"Expand macro once\" do\n filename = Path.expand(\"fixtures\/macro_expand_once_fixture.exs\", __DIR__)\n File.write(filename, \"unless true, do: IO.puts \\\"this should never be printed\\\"\")\n assert send_signal(\"EVAL { :expand_once, '#{filename}', '#{filename}', 1 }\") =~ \"\"\"\n if(true) do\n nil\n else\n IO.puts(\"this should never be printed\")\n end\n \"\"\"\n end\n\n test \"Expand macro\" do\n filename = Path.expand(\"fixtures\/macro_expand_fixture.exs\", __DIR__)\n File.write(filename, \"unless true, do: IO.puts \\\"this should never be printed\\\"\")\n assert send_signal(\"EVAL { :expand, '#{filename}', '#{filename}', 1 }\") =~ \"\"\"\n case(true) do\n x when x in [false, nil] ->\n IO.puts(\"this should never be printed\")\n _ ->\n nil\n end\n \"\"\"\n end\n\n test \"Get all available application modules\" do\n assert send_signal(\"INFO { :type, :modules }\") =~ \"\"\"\n Elixir.Logger\n Elixir.Logger.Formatter\n Elixir.Logger.Translator\n \"\"\"\n end\n\n test \"Get all available mix tasks by name\" do\n assert send_signal(\"INFO { :type, :mixtasks }\") =~ \"\"\"\n app.start\n archive\n archive.build\n archive.install\n archive.uninstall\n clean\n cmd\n compile\n \"\"\"\n end\n\n # The IEx.Helpers.t and IEx.Helpers.i are functionality which come with\n # Elixir version 1.2.0\n if Version.match?(System.version, \">=1.2.0-rc.0\") do\n test \"Get information from data type\" do\n assert send_signal(\"INFO { :type, :info, List}\") =~ \"\"\"\n Reference modules\\e[0m\\n\\e[22m Module, Atom\\e[0m\\nEND-OF-INFO\n \"\"\"\n end\n\n test \"Don't crash server if data type argument is faulty\" do\n assert send_signal(\"INFO { :type, :info, whatever}\") =~ \"\"\"\n END-OF-INFO\n \"\"\"\n end\n\n test \"Prints the types for the given module or for the given function\/arity pair\" do\n assert send_signal(\"INFO { :type, :types, 'Agent'}\") =~ \"\"\"\n @type agent() :: pid() | {atom(), node()} | name()\\e[0m\\n\\e[22m@type state() :: term()\\e[0m\\nEND-OF-INFO\n \"\"\"\n\n assert send_signal(\"INFO { :type, :types, 'Agent.on_start\/0'}\") =~ \"\"\"\n @type on_start() :: {:ok, pid()} | {:error, {:already_started, pid()} | term()}\\e[0m\n \"\"\"\n end\n end\n\n defp send_signal(signal) do\n capture_io(fn ->\n Alchemist.Server.read_input(signal)\n end)\n end\nend\n","old_contents":"Code.require_file \"test_helper.exs\", __DIR__\nCode.require_file \"..\/lib\/server.exs\", __DIR__\n\ndefmodule ServerTest do\n use ExUnit.Case\n import ExUnit.CaptureIO\n\n @buffer_file \"#{__DIR__}\/my_module.ex\"\n\n setup_all do\n on_exit fn ->\n {_status, files} = File.ls Path.expand(\"fixtures\", __DIR__)\n files |> Enum.each(fn(file) ->\n unless file == \".gitkeep\" do\n File.rm Path.expand(\"fixtures\/#{file}\", __DIR__)\n end\n end)\n end\n end\n\n test \"Expression completion\" do\n assert send_signal(\"COMP { 'def', \\\"#{@buffer_file}\\\", 2}\") =~ \"\"\"\n defoverridable\/1;macro;keywords;Kernel;Makes the given functions in the current module overridable.;\n \"\"\"\n end\n\n test \"Documentation lookup\" do\n assert send_signal(\"DOCL { 'List', \\\"#{@buffer_file}\\\", 2}\") =~ \"\"\"\n > List\\n\\nSpecialized functions that only work on lists.\n \"\"\"\n end\n\n test \"Getting the definition source file information of code\" do\n assert send_signal(\"DEFL {\\\"List,delete\\\", \\\"#{@buffer_file}\\\", \\\"#{@buffer_file}\\\", 2}\") =~ \"\/lib\/elixir\/lib\/list.ex\"\n end\n\n test \"Evaluate the content of a file\" do\n filename = Path.expand(\"fixtures\/eval_fixture.exs\", __DIR__)\n File.write(filename, \"1+1\")\n assert send_signal(\"EVAL { :eval, '#{filename}' }\") =~ \"2\"\n end\n\n test \"Evaluate and quote the content of a file\" do\n filename = Path.expand(\"fixtures\/eval_and_quote_fixture.exs\", __DIR__)\n File.write(filename, \"[4,2,1,3] |> Enum.sort\")\n assert send_signal(\"EVAL { :quote, '#{filename}' }\") =~ \"\"\"\n {{:., [line: 1], [{:__aliases__, [counter: 0, line: 1], [:Enum]}, :sort]},\\n [line: 1], []}]}\n \"\"\"\n end\n\n test \"Expand macro once\" do\n filename = Path.expand(\"fixtures\/macro_expand_once_fixture.exs\", __DIR__)\n File.write(filename, \"unless true, do: IO.puts \\\"this should never be printed\\\"\")\n assert send_signal(\"EVAL { :expand_once, '#{filename}' }\") =~ \"\"\"\n if(true) do\n nil\n else\n IO.puts(\"this should never be printed\")\n end\n \"\"\"\n end\n\n test \"Expand macro\" do\n filename = Path.expand(\"fixtures\/macro_expand_fixture.exs\", __DIR__)\n File.write(filename, \"unless true, do: IO.puts \\\"this should never be printed\\\"\")\n assert send_signal(\"EVAL { :expand, '#{filename}' }\") =~ \"\"\"\n case(true) do\n x when x in [false, nil] ->\n IO.puts(\"this should never be printed\")\n _ ->\n nil\n end\n \"\"\"\n end\n\n test \"Get all available application modules\" do\n assert send_signal(\"INFO { :type, :modules }\") =~ \"\"\"\n Elixir.Logger\n Elixir.Logger.Formatter\n Elixir.Logger.Translator\n \"\"\"\n end\n\n test \"Get all available mix tasks by name\" do\n assert send_signal(\"INFO { :type, :mixtasks }\") =~ \"\"\"\n app.start\n archive\n archive.build\n archive.install\n archive.uninstall\n clean\n cmd\n compile\n \"\"\"\n end\n\n # The IEx.Helpers.t and IEx.Helpers.i are functionality which come with\n # Elixir version 1.2.0\n if Version.match?(System.version, \">=1.2.0-rc.0\") do\n test \"Get information from data type\" do\n assert send_signal(\"INFO { :type, :info, List}\") =~ \"\"\"\n Reference modules\\e[0m\\n\\e[22m Module, Atom\\e[0m\\nEND-OF-INFO\n \"\"\"\n end\n\n test \"Don't crash server if data type argument is faulty\" do\n assert send_signal(\"INFO { :type, :info, whatever}\") =~ \"\"\"\n END-OF-INFO\n \"\"\"\n end\n\n test \"Prints the types for the given module or for the given function\/arity pair\" do\n assert send_signal(\"INFO { :type, :types, 'Agent'}\") =~ \"\"\"\n @type agent() :: pid() | {atom(), node()} | name()\\e[0m\\n\\e[22m@type state() :: term()\\e[0m\\nEND-OF-INFO\n \"\"\"\n\n assert send_signal(\"INFO { :type, :types, 'Agent.on_start\/0'}\") =~ \"\"\"\n @type on_start() :: {:ok, pid()} | {:error, {:already_started, pid()} | term()}\\e[0m\n \"\"\"\n end\n end\n\n defp send_signal(signal) do\n capture_io(fn ->\n Alchemist.Server.read_input(signal)\n end)\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"7637ceab74cc6deaa84da0358ec9c942f5e9bfc9","subject":"test smtp without to","message":"test smtp without to","repos":"swoosh\/swoosh","old_file":"test\/swoosh\/email\/smtp_test.exs","new_file":"test\/swoosh\/email\/smtp_test.exs","new_contents":"defmodule Swoosh.Email.SMTPTest do\n use ExUnit.Case, async: true\n\n alias Swoosh.Adapters.SMTP.Helpers\n\n import Swoosh.Email\n\n setup_all do\n valid_email =\n new()\n |> from(\"tony@stark.com\")\n |> to(\"steve@rogers.com\")\n |> subject(\"Hello, Avengers!\")\n |> html_body(\"

Hello<\/h1>\")\n |> text_body(\"Hello\")\n\n {:ok, valid_email: valid_email}\n end\n\n test \"simple email\", %{valid_email: email} do\n email = email |> html_body(nil)\n\n assert Helpers.prepare_message(email, []) ==\n {\"text\", \"plain\",\n [\n {\"Content-Type\", \"text\/plain; charset=\\\"utf-8\\\"\"},\n {\"From\", \"tony@stark.com\"},\n {\"To\", \"steve@rogers.com\"},\n {\"Subject\", \"Hello, Avengers!\"},\n {\"MIME-Version\", \"1.0\"}\n ], \"Hello\"}\n end\n\n test \"simple email without to\", %{valid_email: email} do\n email = email |> html_body(nil) |> put_to(nil)\n\n assert Helpers.prepare_message(email, []) ==\n {\"text\", \"plain\",\n [\n {\"Content-Type\", \"text\/plain; charset=\\\"utf-8\\\"\"},\n {\"From\", \"tony@stark.com\"},\n {\"Subject\", \"Hello, Avengers!\"},\n {\"MIME-Version\", \"1.0\"}\n ], \"Hello\"}\n end\n\n test \"simple email with all basic fields\", %{valid_email: email} do\n email =\n email\n |> html_body(nil)\n |> to({\"Janet Pym\", \"wasp@avengers.com\"})\n |> cc({\"Bruce Banner\", \"hulk@smash.com\"})\n |> cc(\"thor@odinson.com\")\n |> bcc({\"Clinton Francis Barton\", \"hawk@eye.com\"})\n |> bcc(\"beast@avengers.com\")\n |> reply_to(\"black@widow.com\")\n |> header(\"X-Custom-ID\", \"4f034001\")\n |> header(\"X-Feedback-ID\", \"403f4983b02a\")\n\n assert Helpers.prepare_message(email, []) ==\n {\"text\", \"plain\",\n [\n {\"Content-Type\", \"text\/plain; charset=\\\"utf-8\\\"\"},\n {\"From\", \"tony@stark.com\"},\n {\"To\", \"\\\"Janet Pym\\\" , steve@rogers.com\"},\n {\"Cc\", \"thor@odinson.com, \\\"Bruce Banner\\\" \"},\n {\"Bcc\", \"beast@avengers.com, \\\"Clinton Francis Barton\\\" \"},\n {\"Subject\", \"Hello, Avengers!\"},\n {\"Reply-To\", \"black@widow.com\"},\n {\"MIME-Version\", \"1.0\"},\n {\"X-Custom-ID\", \"4f034001\"},\n {\"X-Feedback-ID\", \"403f4983b02a\"}\n ], \"Hello\"}\n end\n\n test \"simple email with multiple recipients\", %{valid_email: email} do\n email = email |> html_body(nil) |> to({\"Bruce Banner\", \"bruce@banner.com\"})\n\n assert Helpers.prepare_message(email, []) ==\n {\"text\", \"plain\",\n [\n {\"Content-Type\", \"text\/plain; charset=\\\"utf-8\\\"\"},\n {\"From\", \"tony@stark.com\"},\n {\"To\", \"\\\"Bruce Banner\\\" , steve@rogers.com\"},\n {\"Subject\", \"Hello, Avengers!\"},\n {\"MIME-Version\", \"1.0\"}\n ], \"Hello\"}\n end\n\n test \"simple email with multiple cc recipients\", %{valid_email: email} do\n email =\n email\n |> html_body(nil)\n |> to({\"Bruce Banner\", \"bruce@banner.com\"})\n |> cc(\"thor@odinson.com\")\n\n assert Helpers.prepare_message(email, []) ==\n {\"text\", \"plain\",\n [\n {\"Content-Type\", \"text\/plain; charset=\\\"utf-8\\\"\"},\n {\"From\", \"tony@stark.com\"},\n {\"To\", \"\\\"Bruce Banner\\\" , steve@rogers.com\"},\n {\"Cc\", \"thor@odinson.com\"},\n {\"Subject\", \"Hello, Avengers!\"},\n {\"MIME-Version\", \"1.0\"}\n ], \"Hello\"}\n end\n\n test \"simple html email\", %{valid_email: email} do\n email = email |> text_body(nil)\n\n assert Helpers.prepare_message(email, []) ==\n {\"text\", \"html\",\n [\n {\"Content-Type\", \"text\/html; charset=\\\"utf-8\\\"\"},\n {\"From\", \"tony@stark.com\"},\n {\"To\", \"steve@rogers.com\"},\n {\"Subject\", \"Hello, Avengers!\"},\n {\"MIME-Version\", \"1.0\"}\n ], \"

Hello<\/h1>\"}\n end\n\n test \"multipart\/alternative email\", %{valid_email: email} do\n assert Helpers.prepare_message(email, []) ==\n {\"multipart\", \"alternative\",\n [\n {\"From\", \"tony@stark.com\"},\n {\"To\", \"steve@rogers.com\"},\n {\"Subject\", \"Hello, Avengers!\"},\n {\"MIME-Version\", \"1.0\"}\n ],\n [\n {\"text\", \"plain\",\n [\n {\"Content-Type\", \"text\/plain; charset=\\\"utf-8\\\"\"},\n {\"Content-Transfer-Encoding\", \"quoted-printable\"}\n ],\n %{\n content_type_params: [{\"charset\", \"utf-8\"}],\n disposition: \"inline\",\n disposition_params: []\n }, \"Hello\"},\n {\"text\", \"html\",\n [\n {\"Content-Type\", \"text\/html; charset=\\\"utf-8\\\"\"},\n {\"Content-Transfer-Encoding\", \"quoted-printable\"}\n ],\n %{\n content_type_params: [{\"charset\", \"utf-8\"}],\n disposition: \"inline\",\n disposition_params: []\n }, \"

Hello<\/h1>\"}\n ]}\n end\nend\n","old_contents":"defmodule Swoosh.Email.SMTPTest do\n use ExUnit.Case, async: true\n\n alias Swoosh.Adapters.SMTP.Helpers\n\n import Swoosh.Email\n\n setup_all do\n valid_email =\n new()\n |> from(\"tony@stark.com\")\n |> to(\"steve@rogers.com\")\n |> subject(\"Hello, Avengers!\")\n |> html_body(\"

Hello<\/h1>\")\n |> text_body(\"Hello\")\n\n {:ok, valid_email: valid_email}\n end\n\n test \"simple email\", %{valid_email: email} do\n email = email |> html_body(nil)\n\n assert Helpers.prepare_message(email, []) ==\n {\"text\", \"plain\",\n [\n {\"Content-Type\", \"text\/plain; charset=\\\"utf-8\\\"\"},\n {\"From\", \"tony@stark.com\"},\n {\"To\", \"steve@rogers.com\"},\n {\"Subject\", \"Hello, Avengers!\"},\n {\"MIME-Version\", \"1.0\"}\n ], \"Hello\"}\n end\n\n test \"simple email with all basic fields\", %{valid_email: email} do\n email =\n email\n |> html_body(nil)\n |> to({\"Janet Pym\", \"wasp@avengers.com\"})\n |> cc({\"Bruce Banner\", \"hulk@smash.com\"})\n |> cc(\"thor@odinson.com\")\n |> bcc({\"Clinton Francis Barton\", \"hawk@eye.com\"})\n |> bcc(\"beast@avengers.com\")\n |> reply_to(\"black@widow.com\")\n |> header(\"X-Custom-ID\", \"4f034001\")\n |> header(\"X-Feedback-ID\", \"403f4983b02a\")\n\n assert Helpers.prepare_message(email, []) ==\n {\"text\", \"plain\",\n [\n {\"Content-Type\", \"text\/plain; charset=\\\"utf-8\\\"\"},\n {\"From\", \"tony@stark.com\"},\n {\"To\", \"\\\"Janet Pym\\\" , steve@rogers.com\"},\n {\"Cc\", \"thor@odinson.com, \\\"Bruce Banner\\\" \"},\n {\"Bcc\", \"beast@avengers.com, \\\"Clinton Francis Barton\\\" \"},\n {\"Subject\", \"Hello, Avengers!\"},\n {\"Reply-To\", \"black@widow.com\"},\n {\"MIME-Version\", \"1.0\"},\n {\"X-Custom-ID\", \"4f034001\"},\n {\"X-Feedback-ID\", \"403f4983b02a\"}\n ], \"Hello\"}\n end\n\n test \"simple email with multiple recipients\", %{valid_email: email} do\n email = email |> html_body(nil) |> to({\"Bruce Banner\", \"bruce@banner.com\"})\n\n assert Helpers.prepare_message(email, []) ==\n {\"text\", \"plain\",\n [\n {\"Content-Type\", \"text\/plain; charset=\\\"utf-8\\\"\"},\n {\"From\", \"tony@stark.com\"},\n {\"To\", \"\\\"Bruce Banner\\\" , steve@rogers.com\"},\n {\"Subject\", \"Hello, Avengers!\"},\n {\"MIME-Version\", \"1.0\"}\n ], \"Hello\"}\n end\n\n test \"simple email with multiple cc recipients\", %{valid_email: email} do\n email =\n email\n |> html_body(nil)\n |> to({\"Bruce Banner\", \"bruce@banner.com\"})\n |> cc(\"thor@odinson.com\")\n\n assert Helpers.prepare_message(email, []) ==\n {\"text\", \"plain\",\n [\n {\"Content-Type\", \"text\/plain; charset=\\\"utf-8\\\"\"},\n {\"From\", \"tony@stark.com\"},\n {\"To\", \"\\\"Bruce Banner\\\" , steve@rogers.com\"},\n {\"Cc\", \"thor@odinson.com\"},\n {\"Subject\", \"Hello, Avengers!\"},\n {\"MIME-Version\", \"1.0\"}\n ], \"Hello\"}\n end\n\n test \"simple html email\", %{valid_email: email} do\n email = email |> text_body(nil)\n\n assert Helpers.prepare_message(email, []) ==\n {\"text\", \"html\",\n [\n {\"Content-Type\", \"text\/html; charset=\\\"utf-8\\\"\"},\n {\"From\", \"tony@stark.com\"},\n {\"To\", \"steve@rogers.com\"},\n {\"Subject\", \"Hello, Avengers!\"},\n {\"MIME-Version\", \"1.0\"}\n ], \"

Hello<\/h1>\"}\n end\n\n test \"multipart\/alternative email\", %{valid_email: email} do\n assert Helpers.prepare_message(email, []) ==\n {\"multipart\", \"alternative\",\n [\n {\"From\", \"tony@stark.com\"},\n {\"To\", \"steve@rogers.com\"},\n {\"Subject\", \"Hello, Avengers!\"},\n {\"MIME-Version\", \"1.0\"}\n ],\n [\n {\"text\", \"plain\",\n [\n {\"Content-Type\", \"text\/plain; charset=\\\"utf-8\\\"\"},\n {\"Content-Transfer-Encoding\", \"quoted-printable\"}\n ],\n %{\n content_type_params: [{\"charset\", \"utf-8\"}],\n disposition: \"inline\",\n disposition_params: []\n }, \"Hello\"},\n {\"text\", \"html\",\n [\n {\"Content-Type\", \"text\/html; charset=\\\"utf-8\\\"\"},\n {\"Content-Transfer-Encoding\", \"quoted-printable\"}\n ],\n %{\n content_type_params: [{\"charset\", \"utf-8\"}],\n disposition: \"inline\",\n disposition_params: []\n }, \"

Hello<\/h1>\"}\n ]}\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"a610cd8bfb271d251714e2630876544084cfff09","subject":"Organize test helper","message":"Organize test helper\n","repos":"mozillo\/weber,mozillo\/weber,elixir-web\/weber,elixir-web\/weber","old_file":"test\/weber_helper_html_test.exs","new_file":"test\/weber_helper_html_test.exs","new_contents":"","old_contents":"defmodule WeberHelperHtmlTest do\n use ExUnit.Case\n\n import Weber.Helper.Html\n\n test \"Create a tag without attributes within text\" do\n html = tag(:p, \"test\") \n assert(html == \"

test<\/p>\")\n end\n\n test \"Create tag with attributes\" do\n html = tag(:p, \"test\", [class: \"test_class\", id: \"test_id\"])\n assert(html == \"

test<\/p>\")\n end\n\n test \"Create tag with attributes boolean\" do\n html = tag(:p, \"test\", [class: \"test_class\", id: \"test_id\", required: true])\n assert(html == \"

test<\/p>\")\n end\n\n test \"Create tag with another tags inside\" do\n html = tag(:div) do\n tag(:p, \"test\", [class: \"test\"])\n end\n assert(html == \"

test<\/p><\/div>\")\n end\n\n test \"Create tag with attributes and another tags inside\" do\n html = tag(:div, [class: \"div_test\", id: \"id_test\"]) do\n tag(:span, [class: \"span_class\"]) do\n tag(:p, \"test\", [class: \"test\"])\n end\n end\n\n assert(html == \"

test<\/p><\/span><\/div>\")\n end\n\n test \"Create tags without end\" do\n html = tag(:img, [src: \"path\/to\/file.png\"])\n assert(html == \"\")\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"d731a9589731ed2dad628d43bc84d7c92ae3beba","subject":"Refactor","message":"Refactor","repos":"xeejp\/xee,xeejp\/xee,xeejp\/xee,xeejp\/xee,xeejp\/xee","old_file":"web\/views\/host_view.ex","new_file":"web\/views\/host_view.ex","new_contents":"defmodule Xee.HostView do\n use Xee.Web, :view\nend\n","old_contents":"defmodule Xee.HostView do\n use Xee.Web, :view\nend\n\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"cbc85d4718f989aab5c42af0af1a1ec070ac41cf","subject":"fix fix","message":"fix fix\n","repos":"zan-kusterle\/Liquio,zan-kusterle\/Liquio,zan-kusterle\/Liquio","old_file":"web\/views\/utils\/number_format.ex","new_file":"web\/views\/utils\/number_format.ex","new_contents":"defmodule Democracy.NumberFormat do\n\tuse Phoenix.HTML\n\n\tdef number_format(x) do\n\t\traw(format_number(x))\n\tend\n\n\tdef number_format_simple(x) do\n\t\ts = :erlang.float_to_binary(x, [:compact, { :decimals, 2 }])\n\t\t|> String.trim_trailing(\".0\")\n\t\traw(s)\n\tend\n\n\tdef for_choice_format(for_choice, choice_type) do\n\t\tif choice_type == \"probability\" do\n\t\t\tcase for_choice do\n\t\t\t\t0.0 -> raw('NEGATIVE<\/span>')\n\t\t\t\t1.0 -> raw('POSITIVE<\/span>')\n\t\t\t\tx -> raw(\"#{format_number(x * 100)}%\")\n\t\t\tend\n\t\telse\n\t\t\traw(format_number(for_choice))\n\t\tend\n\tend\n\n\tdef score_format(score, choice_type) do\n\t\tif choice_type == \"probability\" do\n\t\t\tcase score do\n\t\t\t\t0.0 -> raw('FALSE<\/span>')\n\t\t\t\t1.0 -> raw('TRUE<\/span>')\n\t\t\t\tx -> raw(\"#{format_number(x * 100)}%\")\n\t\t\tend\n\t\telse\n\t\t\traw(format_number(score))\n\t\tend\n\tend\n\n\tdef score_format(score) do\n\t\tscore_format(score, \"probability\")\n\tend\n\n\tdef format_number(x) do\n\t\tx = x * 1.0\n\t\t{value, suffix} = cond do\n\t\t\tx > 999999999.999999 ->\n\t\t\t\t{x \/ 1000000000, \" x 109<\/sup>\"}\n\t\t\tx > 999999.999999 ->\n\t\t\t\t{x \/ 1000000, \" x 106<\/sup>\"}\n\t\t\ttrue ->\n\t\t\t\t{x, \"\"}\n\t\tend\n\n\t\ts = (:erlang.float_to_binary(value, [:compact, { :decimals, 2 }])\n\t\t|> String.trim_trailing(\".0\")) <> suffix\n\tend\nend","old_contents":"defmodule Democracy.NumberFormat do\n\tuse Phoenix.HTML\n\n\tdef number_format(x) do\n\t\traw(format_number(x))\n\tend\n\n\tdef number_format_simple(x) do\n\t\ts = :erlang.float_to_binary(x, [:compact, { :decimals, 2 }])\n\t\t|> String.trim_trailing(\".0\")\n\t\traw(s)\n\tend\n\n\tdef for_choice_format(for_choice, choice_type) do\n\t\tif choice_type == \"probability\" do\n\t\t\tcase for_choice do\n\t\t\t\t0.0 -> raw('NEGATIVE<\/span>')\n\t\t\t\t1.0 -> raw('POSITIVE<\/span>')\n\t\t\t\tx -> raw(\"#{format_number(x * 100)}%\")\n\t\t\tend\n\t\telse\n\t\t\traw(format_number(for_choice))\n\t\tend\n\tend\n\n\tdef score_format(score, choice_type) do\n\t\tif choice_type == \"probability\" do\n\t\t\tcase score do\n\t\t\t\t0.0 -> raw('FALSE<\/span>')\n\t\t\t\t1.0 -> raw('TRUE<\/span>')\n\t\t\t\tx -> raw(\"#{format_number(x * 100)}%\")\n\t\t\tend\n\t\telse\n\t\t\traw(format_number(score))\n\t\tend\n\tend\n\n\tdef score_format(score) do\n\t\tscore_format(score, \"probability\")\n\tend\n\n\tdef format_number(x) do\n\t\tx = x * 1.0\n\t\t{value, suffix} = cond do\n\t\t\tx > 999999999.999999 ->\n\t\t\t\t{x \/ 1000000000, \" x 109<\/sup>\"}\n\t\t\tx > 999999.999999 ->\n\t\t\t\t{x \/ 1000000, \" x 106<\/sup>\"}\n\t\t\ttrue ->\n\t\t\t\t{x, \"\"}\n\t\tend\n\n\t\ts = (:erlang.float_to_binary(value, [:compact, { :decimals, 2 }])\n\t\t|> String.trim_trailing(\".0\", \"\")) <> suffix\n\tend\nend","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"b9b1a58b89179f0802d6726cb05baa9db6f88a94","subject":"When checking for koans, make sure we talk about loaded modules first.","message":"When checking for koans, make sure we talk about loaded modules first.\n","repos":"elixirkoans\/elixir-koans,samstarling\/elixir-koans","old_file":"lib\/runner.ex","new_file":"lib\/runner.ex","new_contents":"defmodule Runner do\n use GenServer\n\n def koan?(koan) do\n case Code.ensure_loaded(koan) do\n {:module, _} -> Keyword.has_key?(koan.__info__(:functions), :all_koans)\n _ -> false\n end\n end\n\n def modules do\n {:ok, modules} = :application.get_key(:elixir_koans, :modules)\n\n modules\n |> Stream.map(&(&1.module_info |> get_in([:compile, :source])))\n |> Stream.map(&to_string\/1) # Paths are charlists\n |> Stream.zip(modules)\n |> Stream.filter(fn {_path, mod} -> koan?(mod) end)\n |> Stream.map(fn {path, mod} -> {path_to_number(path), mod} end)\n |> Enum.sort_by(fn {number, _mod} -> number end)\n |> Enum.map(fn {_number, mod} -> mod end)\n end\n\n @koan_path_pattern ~r\/lib\\\/koans\\\/(\\d+)_\\w+.ex$\/\n\n def path_to_number(path) do\n [_path, number] = Regex.run(@koan_path_pattern, path)\n String.to_integer(number)\n end\n\n def modules_to_run(start_module), do: Enum.drop_while(modules(), &(&1 != start_module))\n\n def start_link do\n GenServer.start_link(__MODULE__, [], name: __MODULE__)\n end\n\n def handle_cast({:run, modules}, _) do\n flush()\n send(self(), :run_modules)\n {:noreply, modules}\n end\n\n def handle_info(:run_modules, []) do\n {:noreply, []}\n end\n\n def handle_info(:run_modules, [module | rest]) do\n Display.clear_screen()\n\n case run_module(module) do\n :passed ->\n send(self(), :run_modules)\n {:noreply, rest}\n\n _ ->\n {:noreply, []}\n end\n end\n\n def run(modules) do\n GenServer.cast(__MODULE__, {:run, modules})\n end\n\n defp run_module(module) do\n module\n |> Execute.run_module(&track\/3)\n |> display\n end\n\n defp track(:passed, module, koan), do: Tracker.completed(module, koan)\n defp track(_, _, _), do: nil\n\n defp display({:failed, error, module, name}) do\n Display.show_failure(error, module, name)\n :failed\n end\n defp display(_), do: :passed\n\n defp flush do\n receive do\n _ -> flush()\n after\n 0 -> :ok\n end\n end\nend\n","old_contents":"defmodule Runner do\n use GenServer\n\n def koan?(koan) do\n Keyword.has_key?(koan.__info__(:functions), :all_koans)\n end\n\n def modules do\n {:ok, modules} = :application.get_key(:elixir_koans, :modules)\n\n modules\n |> Stream.map(&(&1.module_info |> get_in([:compile, :source])))\n |> Stream.map(&to_string\/1) # Paths are charlists\n |> Stream.zip(modules)\n |> Stream.filter(fn {_path, mod} -> koan?(mod) end)\n |> Stream.map(fn {path, mod} -> {path_to_number(path), mod} end)\n |> Enum.sort_by(fn {number, _mod} -> number end)\n |> Enum.map(fn {_number, mod} -> mod end)\n end\n\n @koan_path_pattern ~r\/lib\\\/koans\\\/(\\d+)_\\w+.ex$\/\n\n def path_to_number(path) do\n [_path, number] = Regex.run(@koan_path_pattern, path)\n String.to_integer(number)\n end\n\n def modules_to_run(start_module), do: Enum.drop_while(modules(), &(&1 != start_module))\n\n def start_link do\n GenServer.start_link(__MODULE__, [], name: __MODULE__)\n end\n\n def handle_cast({:run, modules}, _) do\n flush()\n send(self(), :run_modules)\n {:noreply, modules}\n end\n\n def handle_info(:run_modules, []) do\n {:noreply, []}\n end\n\n def handle_info(:run_modules, [module | rest]) do\n Display.clear_screen()\n\n case run_module(module) do\n :passed ->\n send(self(), :run_modules)\n {:noreply, rest}\n\n _ ->\n {:noreply, []}\n end\n end\n\n def run(modules) do\n GenServer.cast(__MODULE__, {:run, modules})\n end\n\n defp run_module(module) do\n module\n |> Execute.run_module(&track\/3)\n |> display\n end\n\n defp track(:passed, module, koan), do: Tracker.completed(module, koan)\n defp track(_, _, _), do: nil\n\n defp display({:failed, error, module, name}) do\n Display.show_failure(error, module, name)\n :failed\n end\n defp display(_), do: :passed\n\n defp flush do\n receive do\n _ -> flush()\n after\n 0 -> :ok\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"13d6f47c17cd0a8aaa8c7b3f37aa5f10a536a364","subject":"make dummy depend on distillery","message":"make dummy depend on distillery\n","repos":"schnittchen\/carafe,schnittchen\/carafe","old_file":"dummies\/dummy1\/mix.exs","new_file":"dummies\/dummy1\/mix.exs","new_contents":"defmodule Dummy1.Mixfile do\n use Mix.Project\n\n def project do\n [app: :dummy1,\n version: \"0.1.0\",\n elixir: \"~> 1.4\",\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n deps: deps()]\n end\n\n # Configuration for the OTP application\n #\n # Type \"mix help compile.app\" for more information\n def application do\n # Specify extra applications you'll use from Erlang\/Elixir\n [extra_applications: [:logger, :edeliver]]\n end\n\n # Dependencies can be Hex packages:\n #\n # {:my_dep, \"~> 0.3.0\"}\n #\n # Or git\/path repositories:\n #\n # {:my_dep, git: \"https:\/\/github.com\/elixir-lang\/my_dep.git\", tag: \"0.1.0\"}\n #\n # Type \"mix help deps\" for more examples and options\n defp deps do\n [\n {:edeliver, \"~> 1.4.2\"},\n {:distillery, \"~> 0.9\"}, # even though onartsipac already depends on distillery,\n # edeliver complains it cannot detect it.\n {:onartsipac, path: \"__ONARTSIPAC_BASE__\"} # the path will be replaced in CI\n ]\n end\nend\n","old_contents":"defmodule Dummy1.Mixfile do\n use Mix.Project\n\n def project do\n [app: :dummy1,\n version: \"0.1.0\",\n elixir: \"~> 1.4\",\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n deps: deps()]\n end\n\n # Configuration for the OTP application\n #\n # Type \"mix help compile.app\" for more information\n def application do\n # Specify extra applications you'll use from Erlang\/Elixir\n [extra_applications: [:logger, :edeliver]]\n end\n\n # Dependencies can be Hex packages:\n #\n # {:my_dep, \"~> 0.3.0\"}\n #\n # Or git\/path repositories:\n #\n # {:my_dep, git: \"https:\/\/github.com\/elixir-lang\/my_dep.git\", tag: \"0.1.0\"}\n #\n # Type \"mix help deps\" for more examples and options\n defp deps do\n [\n {:edeliver, \"~> 1.4.2\"},\n {:onartsipac, path: \"__ONARTSIPAC_BASE__\"} # the path will be replaced in CI\n ]\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"8003822f7d698b4d5da57b1ff63434fa52083c0f","subject":"rename bool funcs in feature runner","message":"rename bool funcs in feature runner\n","repos":"meadsteve\/white-bread","old_file":"lib\/white_bread\/runners\/feature_runner.ex","new_file":"lib\/white_bread\/runners\/feature_runner.ex","new_contents":"defmodule WhiteBread.Runners.FeatureRunner do\n\n def run(feature, context, output_pid) do\n %{scenarios: scenarios, background_steps: background_steps} = feature\n results = scenarios\n |> run_all_scenarios_for_context(context, background_steps)\n |> flatten_any_result_lists\n |> output_results(feature, output_pid)\n\n %{\n successes: results |> Enum.filter(&success?\/1),\n failures: results |> Enum.filter(&failure?\/1)\n }\n end\n\n defp run_all_scenarios_for_context(scenarios, context, background_steps) do\n starting_state = apply(context, :feature_state, [])\n scenarios\n |> Stream.map(&run_scenario(&1,context, background_steps, starting_state))\n end\n\n defp run_scenario(scenario,context, background_steps, starting_state) do\n result = run(scenario, context, background_steps, starting_state)\n {scenario, result}\n end\n\n defp flatten_any_result_lists(results) do\n flatten = fn\n ({scenario, results}) when is_list(results) ->\n results |> Enum.map(fn(result) -> {scenario, result} end)\n (single) ->\n [single]\n end\n results |> Stream.flat_map(flatten)\n end\n\n defp output_results(results, feature, output_pid) do\n send_results = fn({scenario, result}) ->\n send(output_pid, {:scenario_result, result, scenario, feature})\n end\n results\n |> Stream.each(send_results)\n |> Stream.run\n\n results\n end\n\n defp success?({_scenario, {success, _}}), do: success == :ok\n defp failure?({_scenario, {success, _}}), do: success == :failed\n\n defp run(scenario, context, background_steps, starting_state) do\n scenario\n |> WhiteBread.Runners.run(context, background_steps, starting_state)\n end\n\nend\n","old_contents":"defmodule WhiteBread.Runners.FeatureRunner do\n\n def run(feature, context, output_pid) do\n %{scenarios: scenarios, background_steps: background_steps} = feature\n results = scenarios\n |> run_all_scenarios_for_context(context, background_steps)\n |> flatten_any_result_lists\n |> output_results(feature, output_pid)\n\n %{\n successes: results |> Enum.filter(&is_success\/1),\n failures: results |> Enum.filter(&is_failure\/1)\n }\n end\n\n defp run_all_scenarios_for_context(scenarios, context, background_steps) do\n starting_state = apply(context, :feature_state, [])\n scenarios\n |> Stream.map(&run_scenario(&1,context, background_steps, starting_state))\n end\n\n defp run_scenario(scenario,context, background_steps, starting_state) do\n result = run(scenario, context, background_steps, starting_state)\n {scenario, result}\n end\n\n defp flatten_any_result_lists(results) do\n flatten = fn\n ({scenario, results}) when is_list(results) ->\n results |> Enum.map(fn(result) -> {scenario, result} end)\n (single) ->\n [single]\n end\n results |> Stream.flat_map(flatten)\n end\n\n defp output_results(results, feature, output_pid) do\n send_results = fn({scenario, result}) ->\n send(output_pid, {:scenario_result, result, scenario, feature})\n end\n results\n |> Stream.each(send_results)\n |> Stream.run\n\n results\n end\n\n defp is_success({_scenario, {success, _}}) do\n success == :ok\n end\n\n defp is_failure({_scenario, {success, _}}) do\n success == :failed\n end\n\n defp run(scenario, context, background_steps, starting_state) do\n scenario\n |> WhiteBread.Runners.run(context, background_steps, starting_state)\n end\n\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"08911a8db07252c64069eefdd01b23df465f35f6","subject":"Remove duplicate :metadata key in test","message":"Remove duplicate :metadata key in test\n","repos":"code-corps\/code-corps-api,code-corps\/code-corps-api","old_file":"test\/lib\/code_corps\/stripe_service\/adapters\/stripe_platform_card_test.exs","new_file":"test\/lib\/code_corps\/stripe_service\/adapters\/stripe_platform_card_test.exs","new_contents":"defmodule CodeCorps.StripeService.Adapters.StripePlatformCardTest do\n use ExUnit.Case, async: true\n\n import CodeCorps.StripeService.Adapters.StripePlatformCardAdapter, only: [to_params: 2]\n\n @stripe_platform_card %Stripe.Card{\n id: \"card_123\",\n address_city: nil,\n address_country: nil,\n address_line1: nil,\n address_line1_check: nil,\n address_line2: nil,\n address_state: nil,\n address_zip: nil,\n address_zip_check: nil,\n brand: \"Visa\",\n country: \"US\",\n customer: \"cus_123\",\n cvc_check: \"unchecked\",\n dynamic_last4: nil,\n exp_month: 11,\n exp_year: 2016,\n funding: \"credit\",\n last4: \"4242\",\n metadata: %{},\n name: nil,\n tokenization_method: nil\n }\n\n @local_map %{\n \"id_from_stripe\" => \"card_123\",\n \"brand\" => \"Visa\",\n \"exp_month\" => 11,\n \"exp_year\" => 2016,\n \"last4\" => \"4242\",\n \"customer_id_from_stripe\" => \"cus_123\",\n \"cvc_check\" => \"unchecked\",\n \"name\" => nil\n }\n\n describe \"to_params\/2\" do\n test \"converts from stripe map to local properly\" do\n test_attributes = %{\n \"user_id\" => 123,\n \"foo\" => \"bar\"\n }\n expected_attributes = %{\n \"user_id\" => 123,\n }\n\n {:ok, result} = to_params(@stripe_platform_card, test_attributes)\n expected_map = Map.merge(@local_map, expected_attributes)\n\n assert result == expected_map\n end\n end\nend\n","old_contents":"defmodule CodeCorps.StripeService.Adapters.StripePlatformCardTest do\n use ExUnit.Case, async: true\n\n import CodeCorps.StripeService.Adapters.StripePlatformCardAdapter, only: [to_params: 2]\n\n @stripe_platform_card %Stripe.Card{\n id: \"card_123\",\n metadata: %{},\n address_city: nil,\n address_country: nil,\n address_line1: nil,\n address_line1_check: nil,\n address_line2: nil,\n address_state: nil,\n address_zip: nil,\n address_zip_check: nil,\n brand: \"Visa\",\n country: \"US\",\n customer: \"cus_123\",\n cvc_check: \"unchecked\",\n dynamic_last4: nil,\n exp_month: 11,\n exp_year: 2016,\n funding: \"credit\",\n last4: \"4242\",\n metadata: %{},\n name: nil,\n tokenization_method: nil\n }\n\n @local_map %{\n \"id_from_stripe\" => \"card_123\",\n \"brand\" => \"Visa\",\n \"exp_month\" => 11,\n \"exp_year\" => 2016,\n \"last4\" => \"4242\",\n \"customer_id_from_stripe\" => \"cus_123\",\n \"cvc_check\" => \"unchecked\",\n \"name\" => nil\n }\n\n describe \"to_params\/2\" do\n test \"converts from stripe map to local properly\" do\n test_attributes = %{\n \"user_id\" => 123,\n \"foo\" => \"bar\"\n }\n expected_attributes = %{\n \"user_id\" => 123,\n }\n\n {:ok, result} = to_params(@stripe_platform_card, test_attributes)\n expected_map = Map.merge(@local_map, expected_attributes)\n\n assert result == expected_map\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"c1610314a1d66a1b5394f8dbb5dfffb3a2dcef3d","subject":"R\u00e9solution du premier exercice pour Elixir dans exercism","message":"R\u00e9solution du premier exercice pour Elixir dans exercism\n","repos":"TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts","old_file":"exercism\/elixir\/hello-world\/hello_world.exs","new_file":"exercism\/elixir\/hello-world\/hello_world.exs","new_contents":"defmodule HelloWorld do\n @doc \"\"\"\n Simply returns \"Hello, World!\"\n \"\"\"\n @spec hello :: String.t()\n def hello do\n \"Hello, World!\"\n end\nend\n","old_contents":"defmodule HelloWorld do\n @doc \"\"\"\n Simply returns \"Hello, World!\"\n \"\"\"\n @spec hello :: String.t()\n def hello do\n \"Your implementation goes here\"\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"81b52bfb78a9f6c920577a1e342d30f1f0583ad8","subject":"Add Serum.Build.FragmentGeneratorTest","message":"Add Serum.Build.FragmentGeneratorTest\n","repos":"Dalgona\/Serum","old_file":"test\/serum\/build\/fragment_generator_test.exs","new_file":"test\/serum\/build\/fragment_generator_test.exs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"mit","lang":"Elixir"} {"commit":"ca44de864e7886f3e796a772604ef3c6cdaa36b7","subject":"Uses Map.get to retrieve params","message":"Uses Map.get to retrieve params\n","repos":"underhilllabs\/phx-bookmarks","old_file":"web\/controllers\/bookmark_controller.ex","new_file":"web\/controllers\/bookmark_controller.ex","new_contents":"defmodule PhxBkmark.BookmarkController do\n use PhxBkmark.Web, :controller\n import Ecto.Query, only: [from: 2]\n @per_page 20\n plug :action\n\n def index(conn, params) do\n page = Map.get(params, \"page\", \"1\") |> String.to_integer\n \n bookmarks = bookmark_query |> paginate(page, @per_page) |> Repo.all |> Repo.preload [:user, :tags]\n render(conn, \"index.html\", bookmarks: bookmarks)\n end\n\n def new(conn, _params) do\n render conn, \"new.html\"\n end\n\n # We will use the params, so no _!\n def create(conn, params) do\n render conn, \"index.html\"\n end\n\n def bookmark_query do\n from b in PhxBkmark.Bookmark,\n order_by: [desc: b.updated_at],\n select: b\n end\n\n def paginate(query, page, per_page) do\n offset = (page - 1) * per_page\n from query,\n offset: ^offset,\n limit: ^per_page\n end\nend\n","old_contents":"defmodule PhxBkmark.BookmarkController do\n use PhxBkmark.Web, :controller\n import Ecto.Query, only: [from: 2]\n @per_page 20\n plug :action\n\n def index(conn, %{\"page\" => page}) do\n if page do\n page = String.to_integer(page)\n else\n page = 1\n end\n \n bookmarks = bookmark_query |> paginate(page, @per_page) |> Repo.all |> Repo.preload [:user, :tags]\n render(conn, \"index.html\", bookmarks: bookmarks)\n end\n\n def new(conn, _params) do\n render conn, \"new.html\"\n end\n\n # We will use the params, so no _!\n def create(conn, params) do\n render conn, \"index.html\"\n end\n\n def bookmark_query do\n from b in PhxBkmark.Bookmark,\n order_by: [desc: b.updated_at],\n select: b\n end\n\n def paginate(query, page, per_page) do\n offset = (page - 1) * per_page\n from query,\n offset: ^offset,\n limit: ^per_page\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"6fe09f72e2884613f465047e0e53e89e3b06eec2","subject":"Adding grade to resource_review","message":"Adding grade to resource_review\n","repos":"houshuang\/survey,houshuang\/survey","old_file":"web\/controllers\/resource_controller.ex","new_file":"web\/controllers\/resource_controller.ex","new_contents":"defmodule Survey.ResourceController do\n use Survey.Web, :controller\n\n require Logger\n alias Survey.Resource\n import Prelude\n alias Survey.Resource\n alias Survey.ResourceTag\n alias Survey.Repo\n\n plug :action\n\n def add(conn, params) do\n if params[\"f\"] do\n Logger.info(\"Saving new resource\")\n save_to_db(conn, params[\"f\"])\n Survey.Grade.submit_grade(conn, \"add_resource\", 1.0)\n end\n\n already = Resource.user_submitted_no(conn.assigns.user.id)\n if already > 0 do\n conn = put_flash(conn, :info, \n \"Thank you for submitting #{already} #{resource_word(already)}. Your participation has already been graded. You are welcome to submit more resources, or move on to other parts of the course.\")\n end\n\n sig = conn.assigns.user.sig_id\n tags = ResourceTag.get_tags(sig)\n\n conn\n |> put_layout(\"minimal.html\")\n |> render \"resource.html\", tags: tags\n end\n\n def resource_word(cnt) when cnt > 1, do: \"resources\"\n def resource_word(cnt), do: \"resource\"\n\n #---------------------------------------- \n\n def tag_cloud(conn, params) do\n sig = conn.assigns.user.sig_id\n if params[\"all\"], do: sig = nil\n tagfreq = Resource.tag_freq(sig)\n conn\n |> put_layout(\"minimal.html\")\n |> render \"tag_cloud.html\", tagfreq: tagfreq\n end\n \n def list(conn, params) do\n sig = conn.assigns.user.sig_id\n if params[\"tag\"] do\n tag = params[\"tag\"]\n resources = Resource.resource_list(sig, params[\"tag\"])\n else\n tag = nil\n resources = Resource.resource_list(sig)\n end\n\n conn\n |> put_layout(\"minimal.html\")\n |> render \"list.html\", resources: resources, tag: tag\n end\n #---------------------------------------- \n\n def review(conn, params) do \n if params[\"list\"] do\n conn = put_session(conn, :review_redirect, true)\n redirect = :list\n else\n redirect = :next\n conn = delete_session(conn, :review_redirect)\n end\n user = conn.assigns.user\n already = Resource.user_reviewed_no(conn.assigns.user.id)\n if already > 0 do\n conn = put_flash(conn, :info, \n \"Thank you for reviewing #{already} #{resource_word(already)}. You are welcome to review more resources, or move on to other parts of the course.\")\n Survey.Grade.submit_grade(conn, \"review_resource\", 1.0)\n end\n \n if params[\"id\"] do\n id = String.to_integer(params[\"id\"])\n Resource.update_seen(user, id)\n else\n id = Resource.get_random(conn.assigns.user)\n end\n\n if !id do\n html conn, \"Sorry, we could not find any new resources for you to review. Try back in a little while.\"\n else\n sig = conn.assigns.user.sig_id\n tags = ResourceTag.get_tags(sig)\n resource = Resource.get_resource(id)\n\n if !resource do\n ParamSession.redirect(conn, \"\/resource\/review\")\n else\n seen = Resource.user_seen?(user, resource.id)\n\n rtype = if resource.generic do\n \"NOTE: This is a GENERIC Resource, meaning that the person who added it felt that it would be applicable to more than one SIG\"\n else\n \"\"\n end\n\n conn\n |> put_layout(\"minimal.html\")\n |> render \"review.html\", tags: tags, resource: resource,\n resourcetype: rtype, redirect: redirect, seen: seen\n end\n end\n end\n\n def review_submit(conn, params) do\n user = conn.assigns.user\n resource = Repo.get(Resource, params[\"resource_id\"])\n form = params[\"f\"] \n |> Enum.map(fn {k, v} -> {k, String.strip(v)} end)\n |> Enum.into(%{})\n\n # COMMENTS\n comments = resource.comments || []\n if string_param_exists(form[\"comment\"]) do\n newcom = %{nick: user.nick, user_id: user.id, text: form[\"comment\"],\n date: Ecto.DateTime.local}\n comments = [ newcom | comments ]\n end\n\n # DESCRIPTION\n description = resource.description\n old_desc = resource.old_desc\n if string_param_exists(form[\"description\"]) &&\n String.strip(form[\"description\"]) != String.strip(resource.description) do\n description = String.strip(form[\"description\"])\n\n cur = %{description: form[\"description\"], user_id: user.id, \n date: Ecto.DateTime.local}\n\n # either append, or create old_desc with orig as first entry\n if old_desc do\n old_desc = [ cur | old_desc ]\n else\n orig = %{description: resource.description, \n user_id: resource.user_id, date: resource.inserted_at}\n old_desc = [cur, orig]\n end\n end\n\n # SCORE\n score = resource.score || 0.0\n old_score = resource.old_score || []\n if string_param_exists(form[\"rating\"]) do\n {newscore, _} = Float.parse(form[\"rating\"])\n new_old_score = %{ \"user\" => user.id, \"score\" => newscore, \n \"date\" => Ecto.DateTime.local }\n old_score = [ new_old_score | old_score ]\n score_sum = old_score\n |> Enum.map(fn x -> x[\"score\"] end)\n |> Enum.sum\n score = score_sum \/ length(old_score)\n end\n\n # TAGS\n tags = resource.tags\n if !(resource.generic || !form[\"tags\"] || form[\"tags\"] == \"\") do\n old_tags = resource.old_tags\n raw_tags = String.split(form[\"tags\"], \"|\")\n new_tags = set_difference(raw_tags, tags)\n if !Enum.empty?(new_tags) do\n \n tags = raw_tags\n cur = %{tags: new_tags, user_id: user.id, \n date: Ecto.DateTime.local}\n\n # either append, or create old_desc with orig as first entry\n if old_tags do\n old_tags = [ cur | old_tags ]\n else\n orig = %{tags: resource.tags, \n user_id: resource.user_id, date: resource.inserted_at}\n old_tags = [cur, orig]\n end\n end\n end\n \n # INSERT DB\n %{ resource | \n tags: tags, old_tags: old_tags, score: score, old_score: old_score,\n description: description, old_desc: old_desc, comments: comments}\n |> Repo.update!\n\n redir_url = if get_session(conn, :review_redirect) do\n \"\/resource\/list\"\n else\n \"\/resource\/review\"\n end\n Survey.Grade.submit_grade(conn, \"review_resource\", 1.0)\n \n conn\n |> ParamSession.redirect redir_url\n end\n #---------------------------------------- \n\n def set(x) when is_list(x) do\n Enum.into(x, HashSet.new)\n end\n\n def different_as_set?(x, y) when is_list(x) and is_list(y) do\n !Enum.empty?(set_difference(x, y))\n end\n\n def set_difference(x, y) when is_list(x) and is_list(y) do\n Set.difference(set(x), set(y))\n |> Enum.to_list\n end\n\n def preview(conn, params) do\n tags = ResourceTag.get_tags(2)\n conn\n |> put_layout(\"minimal.html\")\n |> render \"resource.html\", tags: tags\n end\n\n def report(conn, _) do\n resources = Resource.get_all_by_sigs\n conn\n |> put_layout(\"minimal.html\")\n |> render \"report.html\", resources: resources\n end\n #---------------------------------------- \n\n def save_to_db(conn, params) do\n if !Resource.find_url(params[\"url\"], conn.assigns.user.sig_id) do\n resource = params\n |> Map.update(\"generic\", false, fn x -> x == \"true\" end)\n |> Map.put(\"user_id\", conn.assigns.user.id)\n |> Map.put(\"sig_id\", conn.assigns.user.sig_id)\n |> atomify_map\n |> proc_tags\n\n struct(Resource, resource)\n |> Repo.insert!\n\n ResourceTag.update_tags(conn.assigns.user.sig_id, resource.tags)\n else\n Logger.warn(\"Tried inserting resource with same URL twice\")\n end\n end\n\n defp proc_tags(%{tags: tags} = h), do: %{h | tags: String.split(tags, \"|\") }\n defp proc_tags(x), do: x\n\n def check_url(conn, params) do\n sig = conn.assigns.user.sig_id\n url = params[\"url\"] |> String.strip\n if id = Resource.find_url(url, sig) do\n json conn, %{result: \"exists\", id: id}\n else\n json conn, %{result: \"success\"}\n end\n end\n\n defp bad_status(s) do\n s |> Integer.to_string |> String.starts_with?(\"4\")\n end\n\n defp string_param_exists(s) do\n s && String.strip(s) != \"\"\n end\nend\n","old_contents":"defmodule Survey.ResourceController do\n use Survey.Web, :controller\n\n require Logger\n alias Survey.Resource\n import Prelude\n alias Survey.Resource\n alias Survey.ResourceTag\n alias Survey.Repo\n\n plug :action\n\n def add(conn, params) do\n if params[\"f\"] do\n Logger.info(\"Saving new resource\")\n save_to_db(conn, params[\"f\"])\n Survey.Grade.submit_grade(conn, \"add_resource\", 1.0)\n end\n\n already = Resource.user_submitted_no(conn.assigns.user.id)\n if already > 0 do\n conn = put_flash(conn, :info, \n \"Thank you for submitting #{already} #{resource_word(already)}. Your participation has already been graded. You are welcome to submit more resources, or move on to other parts of the course.\")\n end\n\n sig = conn.assigns.user.sig_id\n tags = ResourceTag.get_tags(sig)\n\n conn\n |> put_layout(\"minimal.html\")\n |> render \"resource.html\", tags: tags\n end\n\n def resource_word(cnt) when cnt > 1, do: \"resources\"\n def resource_word(cnt), do: \"resource\"\n\n #---------------------------------------- \n\n def tag_cloud(conn, params) do\n sig = conn.assigns.user.sig_id\n if params[\"all\"], do: sig = nil\n tagfreq = Resource.tag_freq(sig)\n conn\n |> put_layout(\"minimal.html\")\n |> render \"tag_cloud.html\", tagfreq: tagfreq\n end\n \n def list(conn, params) do\n sig = conn.assigns.user.sig_id\n if params[\"tag\"] do\n tag = params[\"tag\"]\n resources = Resource.resource_list(sig, params[\"tag\"])\n else\n tag = nil\n resources = Resource.resource_list(sig)\n end\n\n conn\n |> put_layout(\"minimal.html\")\n |> render \"list.html\", resources: resources, tag: tag\n end\n #---------------------------------------- \n\n def review(conn, params) do \n if params[\"list\"] do\n conn = put_session(conn, :review_redirect, true)\n redirect = :list\n else\n redirect = :next\n conn = delete_session(conn, :review_redirect)\n end\n user = conn.assigns.user\n already = Resource.user_reviewed_no(conn.assigns.user.id)\n if already > 0 do\n conn = put_flash(conn, :info, \n \"Thank you for reviewing #{already} #{resource_word(already)}. You are welcome to review more resources, or move on to other parts of the course.\")\n end\n \n if params[\"id\"] do\n id = String.to_integer(params[\"id\"])\n Resource.update_seen(user, id)\n else\n id = Resource.get_random(conn.assigns.user)\n end\n\n if !id do\n html conn, \"Sorry, we could not find any new resources for you to review. Try back in a little while.\"\n else\n sig = conn.assigns.user.sig_id\n tags = ResourceTag.get_tags(sig)\n resource = Resource.get_resource(id)\n\n if !resource do\n ParamSession.redirect(conn, \"\/resource\/review\")\n else\n seen = Resource.user_seen?(user, resource.id)\n\n rtype = if resource.generic do\n \"NOTE: This is a GENERIC Resource, meaning that the person who added it felt that it would be applicable to more than one SIG\"\n else\n \"\"\n end\n\n conn\n |> put_layout(\"minimal.html\")\n |> render \"review.html\", tags: tags, resource: resource,\n resourcetype: rtype, redirect: redirect, seen: seen\n end\n end\n end\n\n def review_submit(conn, params) do\n user = conn.assigns.user\n resource = Repo.get(Resource, params[\"resource_id\"])\n form = params[\"f\"] \n |> Enum.map(fn {k, v} -> {k, String.strip(v)} end)\n |> Enum.into(%{})\n\n # COMMENTS\n comments = resource.comments || []\n if string_param_exists(form[\"comment\"]) do\n newcom = %{nick: user.nick, user_id: user.id, text: form[\"comment\"],\n date: Ecto.DateTime.local}\n comments = [ newcom | comments ]\n end\n\n # DESCRIPTION\n description = resource.description\n old_desc = resource.old_desc\n if string_param_exists(form[\"description\"]) &&\n String.strip(form[\"description\"]) != String.strip(resource.description) do\n description = String.strip(form[\"description\"])\n\n cur = %{description: form[\"description\"], user_id: user.id, \n date: Ecto.DateTime.local}\n\n # either append, or create old_desc with orig as first entry\n if old_desc do\n old_desc = [ cur | old_desc ]\n else\n orig = %{description: resource.description, \n user_id: resource.user_id, date: resource.inserted_at}\n old_desc = [cur, orig]\n end\n end\n\n # SCORE\n score = resource.score || 0.0\n old_score = resource.old_score || []\n if string_param_exists(form[\"rating\"]) do\n {newscore, _} = Float.parse(form[\"rating\"])\n new_old_score = %{ \"user\" => user.id, \"score\" => newscore, \n \"date\" => Ecto.DateTime.local }\n old_score = [ new_old_score | old_score ]\n score_sum = old_score\n |> Enum.map(fn x -> x[\"score\"] end)\n |> Enum.sum\n score = score_sum \/ length(old_score)\n end\n\n # TAGS\n tags = resource.tags\n if !(resource.generic || !form[\"tags\"] || form[\"tags\"] == \"\") do\n old_tags = resource.old_tags\n raw_tags = String.split(form[\"tags\"], \"|\")\n new_tags = set_difference(raw_tags, tags)\n if !Enum.empty?(new_tags) do\n \n tags = raw_tags\n cur = %{tags: new_tags, user_id: user.id, \n date: Ecto.DateTime.local}\n\n # either append, or create old_desc with orig as first entry\n if old_tags do\n old_tags = [ cur | old_tags ]\n else\n orig = %{tags: resource.tags, \n user_id: resource.user_id, date: resource.inserted_at}\n old_tags = [cur, orig]\n end\n end\n end\n \n # INSERT DB\n %{ resource | \n tags: tags, old_tags: old_tags, score: score, old_score: old_score,\n description: description, old_desc: old_desc, comments: comments}\n |> Repo.update!\n\n redir_url = if get_session(conn, :review_redirect) do\n \"\/resource\/list\"\n else\n \"\/resource\/review\"\n end\n \n conn\n |> ParamSession.redirect redir_url\n end\n #---------------------------------------- \n\n def set(x) when is_list(x) do\n Enum.into(x, HashSet.new)\n end\n\n def different_as_set?(x, y) when is_list(x) and is_list(y) do\n !Enum.empty?(set_difference(x, y))\n end\n\n def set_difference(x, y) when is_list(x) and is_list(y) do\n Set.difference(set(x), set(y))\n |> Enum.to_list\n end\n\n def preview(conn, params) do\n tags = ResourceTag.get_tags(2)\n conn\n |> put_layout(\"minimal.html\")\n |> render \"resource.html\", tags: tags\n end\n\n def report(conn, _) do\n resources = Resource.get_all_by_sigs\n conn\n |> put_layout(\"minimal.html\")\n |> render \"report.html\", resources: resources\n end\n #---------------------------------------- \n\n def save_to_db(conn, params) do\n if !Resource.find_url(params[\"url\"], conn.assigns.user.sig_id) do\n resource = params\n |> Map.update(\"generic\", false, fn x -> x == \"true\" end)\n |> Map.put(\"user_id\", conn.assigns.user.id)\n |> Map.put(\"sig_id\", conn.assigns.user.sig_id)\n |> atomify_map\n |> proc_tags\n\n struct(Resource, resource)\n |> Repo.insert!\n\n ResourceTag.update_tags(conn.assigns.user.sig_id, resource.tags)\n else\n Logger.warn(\"Tried inserting resource with same URL twice\")\n end\n end\n\n defp proc_tags(%{tags: tags} = h), do: %{h | tags: String.split(tags, \"|\") }\n defp proc_tags(x), do: x\n\n def check_url(conn, params) do\n sig = conn.assigns.user.sig_id\n url = params[\"url\"] |> String.strip\n if id = Resource.find_url(url, sig) do\n json conn, %{result: \"exists\", id: id}\n else\n json conn, %{result: \"success\"}\n end\n end\n\n defp bad_status(s) do\n s |> Integer.to_string |> String.starts_with?(\"4\")\n end\n\n defp string_param_exists(s) do\n s && String.strip(s) != \"\"\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"e036b9efb4d1adfba25887fdda95d98c5f94b50f","subject":"Add inline adapter configuration documentation","message":"Add inline adapter configuration documentation\n","repos":"elixir-geolix\/adapter_mmdb2,elixir-geolix\/adapter_mmdb2","old_file":"lib\/mmdb2.ex","new_file":"lib\/mmdb2.ex","new_contents":"defmodule Geolix.Adapter.MMDB2 do\n @moduledoc \"\"\"\n Adapter for Geolix to work with MMDB2 databases.\n\n ## Adapter Configuration\n\n To start using the adapter with a compatible database you need to add the\n required configuration entry to your `:geolix` configuration:\n\n config :geolix,\n databases: [\n %{\n id: :my_mmdb_database,\n adapter: Geolix.Adapter.MMDB2,\n source: \"\/absolute\/path\/to\/my\/database.mmdb\"\n }\n ]\n \"\"\"\n\n alias Geolix.Adapter.MMDB2.Database\n alias Geolix.Adapter.MMDB2.Loader\n alias Geolix.Adapter.MMDB2.Storage\n\n @behaviour Geolix.Adapter\n\n @impl Geolix.Adapter\n def database_workers do\n import Supervisor.Spec\n\n [\n worker(Storage.Data, []),\n worker(Storage.Metadata, []),\n worker(Storage.Tree, [])\n ]\n end\n\n @impl Geolix.Adapter\n def load_database(database), do: Loader.load_database(database)\n\n @impl Geolix.Adapter\n def lookup(ip, opts), do: Database.lookup(ip, opts)\n\n @impl Geolix.Adapter\n def unload_database(database), do: Loader.unload_database(database)\nend\n","old_contents":"defmodule Geolix.Adapter.MMDB2 do\n @moduledoc \"\"\"\n Adapter for Geolix to work with MMDB2 databases.\n \"\"\"\n\n alias Geolix.Adapter.MMDB2.Database\n alias Geolix.Adapter.MMDB2.Loader\n alias Geolix.Adapter.MMDB2.Storage\n\n @behaviour Geolix.Adapter\n\n @impl Geolix.Adapter\n def database_workers do\n import Supervisor.Spec\n\n [\n worker(Storage.Data, []),\n worker(Storage.Metadata, []),\n worker(Storage.Tree, [])\n ]\n end\n\n @impl Geolix.Adapter\n def load_database(database), do: Loader.load_database(database)\n\n @impl Geolix.Adapter\n def lookup(ip, opts), do: Database.lookup(ip, opts)\n\n @impl Geolix.Adapter\n def unload_database(database), do: Loader.unload_database(database)\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"d07d91cfeaa43179e92749572676e1daeff1b950","subject":"better naming","message":"better naming\n","repos":"gertjana\/ocpp16-backend,gertjana\/ocpp16-backend","old_file":"lib\/utils.ex","new_file":"lib\/utils.ex","new_contents":"defmodule Utils do\n use Timex\n\n def time_as_string do\n {hh, mm, ss} = :erlang.time()\n :io_lib.format(\"~2.10.0B:~2.10.0B:~2.10.0B\", [hh, mm, ss])\n |> :erlang.list_to_binary()\n end\n\n def datetime_as_string do\n \t{:ok, dt_string} = Timex.format(Timex.now, \"{ISO:Extended}\")\n \tdt_string\n end\n\n def datetime_as_string(shift_minutes) do\n {:ok, dt_string} = Timex.format(Timex.shift(Timex.now, minutes: shift_minutes), \"{ISO:Extended}\")\n \tdt_string\n end\n\n def default(val, default) do\n case val do\n nil -> default\n _ -> val\n end\n end\n\nend","old_contents":"defmodule Utils do\n use Timex\n\n def time_as_string do\n {hh, mm, ss} = :erlang.time()\n :io_lib.format(\"~2.10.0B:~2.10.0B:~2.10.0B\", [hh, mm, ss])\n |> :erlang.list_to_binary()\n end\n\n def datetime_as_string do\n \t{:ok, default_str} = Timex.format(Timex.now, \"{ISO:Extended}\")\n \tdefault_str\n end\n\n def datetime_as_string(shift_minutes) do\n {:ok, default_str} = Timex.format(Timex.shift(Timex.now, minutes: shift_minutes), \"{ISO:Extended}\")\n \tdefault_str\n end\n\n def default(val, default) do\n case val do\n nil -> default\n _ -> val\n end\n end\n\nend","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"32b7fa3269793e9cd4f620475ab4861a376c5663","subject":"Avoid reading files multiple times when expanding macros","message":"Avoid reading files multiple times when expanding macros\n","repos":"msaraiva\/atom-elixir","old_file":"lib\/alchemist-server\/lib\/api\/eval.exs","new_file":"lib\/alchemist-server\/lib\/api\/eval.exs","new_contents":"Code.require_file \"..\/helpers\/introspection.exs\", __DIR__\nCode.require_file \"..\/code\/metadata.exs\", __DIR__\nCode.require_file \"..\/code\/parser.exs\", __DIR__\nCode.require_file \"..\/code\/ast.exs\", __DIR__\n\ndefmodule Alchemist.API.Eval do\n\n @moduledoc false\n\n alias Alchemist.Code.Metadata\n alias Alchemist.Code.Parser\n alias Alchemist.Code.Ast\n\n def request(args) do\n args\n |> normalize\n |> process\n\n IO.puts \"END-OF-EVAL\"\n end\n\n def process({:eval, file}) do\n try do\n File.read!(\"#{file}\")\n |> Code.eval_string\n |> Tuple.to_list\n |> List.first\n |> IO.inspect\n rescue\n e -> IO.inspect e\n end\n end\n\n def process({:match, file}) do\n try do\n file_content = File.read!(\"#{file}\")\n {:=, _, [pattern|_]} = file_content |> Code.string_to_quoted!\n vars = extract_vars(pattern)\n\n bindings = file_content\n |> Code.eval_string\n |> Tuple.to_list\n |> List.last\n\n if Enum.empty?(vars) do\n IO.puts \"# No bindings\"\n else\n IO.puts \"# Bindings\"\n end\n\n Enum.each(vars, fn var ->\n IO.puts \"\"\n IO.write \"#{var} = \"\n IO.inspect Keyword.get(bindings, var)\n end)\n rescue\n e -> print_match_error(e)\n end\n end\n\n def process({:quote, file}) do\n try do\n File.read!(\"#{file}\")\n |> Code.string_to_quoted\n |> Tuple.to_list\n |> List.last\n |> IO.inspect\n rescue\n e -> IO.inspect e\n end\n end\n\n def process({:expand_once, buffer_file, file, line}) do\n try do\n {_, expr} = File.read!(\"#{file}\") |> Code.string_to_quoted\n env = create_env(buffer_file, line)\n expand_and_print(&Macro.expand_once\/2, expr, env)\n rescue\n e -> IO.inspect e\n end\n end\n\n def process({:expand, buffer_file, file, line}) do\n try do\n {_, expr} = File.read!(\"#{file}\") |> Code.string_to_quoted\n env = create_env(buffer_file, line)\n expand_and_print(&Macro.expand\/2, expr, env)\n rescue\n e -> IO.inspect e\n end\n end\n\n def process({:expand_partial, buffer_file, file, line}) do\n try do\n {_, expr} = File.read!(\"#{file}\")\n |> Code.string_to_quoted\n env = create_env(buffer_file, line)\n expand_and_print(&Ast.expand_partial\/2, expr, env)\n rescue\n e -> IO.inspect e\n end\n end\n\n def process({:expand_all, buffer_file, file, line}) do\n try do\n {_, expr} = File.read!(\"#{file}\") |> Code.string_to_quoted\n env = create_env(buffer_file, line)\n expand_and_print(&Ast.expand_all\/2, expr, env)\n rescue\n e -> IO.inspect e\n end\n end\n\n def process({:expand_full, buffer_file, file, line}) do\n try do\n {_, expr} = File.read!(\"#{file}\") |> Code.string_to_quoted\n env = create_env(buffer_file, line)\n expand_and_print(&Macro.expand_once\/2, expr, env)\n IO.puts(\"\\u000B\")\n expand_and_print(&Macro.expand\/2, expr, env)\n IO.puts(\"\\u000B\")\n expand_and_print(&Ast.expand_partial\/2, expr, env)\n IO.puts(\"\\u000B\")\n expand_and_print(&Ast.expand_all\/2, expr, env)\n rescue\n e -> IO.inspect e\n end\n end\n\n defp expand_and_print(expand_func, expr, env) do\n expand_func.(expr, env)\n |> Macro.to_string\n |> IO.puts\n end\n\n def normalize(request) do\n {expr , _} = Code.eval_string(request)\n expr\n end\n\n defp extract_vars(ast) do\n {_ast, acc} = Macro.postwalk(ast, [], &extract_var\/2)\n acc |> Enum.reverse\n end\n\n defp extract_var(ast = {var_name, [line: _], nil}, acc) when is_atom(var_name) and var_name != :_ do\n {ast, [var_name|acc]}\n end\n\n defp extract_var(ast, acc) do\n {ast, acc}\n end\n\n defp print_match_error(%{__struct__: type, description: description, line: line}) do\n IO.puts \"# #{Introspection.module_to_string(type)} on line #{line}: \\n# \u21b3 #{description}\"\n end\n\n defp print_match_error(%MatchError{}) do\n IO.puts \"# No match\"\n end\n\n defp print_match_error(e) do\n IO.inspect(e)\n end\n\n defp create_env(file, line) do\n %{requires: requires, imports: imports, module: module} =\n file\n |> Parser.parse_file(true, true, line)\n |> Metadata.get_env(line)\n\n __ENV__\n |> Ast.add_requires_to_env(requires)\n |> Ast.add_imports_to_env(imports)\n |> Ast.set_module_for_env(module)\n end\n\nend\n","old_contents":"Code.require_file \"..\/helpers\/introspection.exs\", __DIR__\nCode.require_file \"..\/code\/metadata.exs\", __DIR__\nCode.require_file \"..\/code\/parser.exs\", __DIR__\nCode.require_file \"..\/code\/ast.exs\", __DIR__\n\ndefmodule Alchemist.API.Eval do\n\n @moduledoc false\n\n alias Alchemist.Code.Metadata\n alias Alchemist.Code.Parser\n alias Alchemist.Code.Ast\n\n def request(args) do\n args\n |> normalize\n |> process\n\n IO.puts \"END-OF-EVAL\"\n end\n\n def process({:eval, file}) do\n try do\n File.read!(\"#{file}\")\n |> Code.eval_string\n |> Tuple.to_list\n |> List.first\n |> IO.inspect\n rescue\n e -> IO.inspect e\n end\n end\n\n def process({:match, file}) do\n try do\n file_content = File.read!(\"#{file}\")\n {:=, _, [pattern|_]} = file_content |> Code.string_to_quoted!\n vars = extract_vars(pattern)\n\n bindings = file_content\n |> Code.eval_string\n |> Tuple.to_list\n |> List.last\n\n if Enum.empty?(vars) do\n IO.puts \"# No bindings\"\n else\n IO.puts \"# Bindings\"\n end\n\n Enum.each(vars, fn var ->\n IO.puts \"\"\n IO.write \"#{var} = \"\n IO.inspect Keyword.get(bindings, var)\n end)\n rescue\n e -> print_match_error(e)\n end\n end\n\n def process({:quote, file}) do\n try do\n File.read!(\"#{file}\")\n |> Code.string_to_quoted\n |> Tuple.to_list\n |> List.last\n |> IO.inspect\n rescue\n e -> IO.inspect e\n end\n end\n\n def process({:expand, buffer_file, file, line}) do\n try do\n {_, expr} = File.read!(\"#{file}\")\n |> Code.string_to_quoted\n env = create_env(buffer_file, line)\n res = Macro.expand(expr, env)\n IO.puts Macro.to_string(res)\n rescue\n e -> IO.inspect e\n end\n end\n\n def process({:expand_once, buffer_file, file, line}) do\n try do\n {_, expr} = File.read!(\"#{file}\")\n |> Code.string_to_quoted\n env = create_env(buffer_file, line)\n res = Macro.expand_once(expr, env)\n IO.puts Macro.to_string(res)\n rescue\n e -> IO.inspect e\n end\n end\n\n def process({:expand_partial, buffer_file, file, line}) do\n try do\n {_, expr} = File.read!(\"#{file}\")\n |> Code.string_to_quoted\n env = create_env(buffer_file, line)\n res = Ast.expand_partial(expr, env)\n IO.puts Macro.to_string(res)\n rescue\n e -> IO.inspect e\n end\n end\n\n def process({:expand_all, buffer_file, file, line}) do\n try do\n {_, expr} = File.read!(\"#{file}\")\n |> Code.string_to_quoted\n env = create_env(buffer_file, line)\n res = Ast.expand_all(expr, env)\n IO.puts Macro.to_string(res)\n rescue\n e -> IO.inspect e\n end\n end\n\n def process({:expand_full, buffer_file, file, line}) do\n process({:expand_once, buffer_file, file, line})\n IO.puts(\"\\u000B\")\n process({:expand, buffer_file, file, line})\n IO.puts(\"\\u000B\")\n process({:expand_partial, buffer_file, file, line})\n IO.puts(\"\\u000B\")\n process({:expand_all, buffer_file, file, line})\n end\n\n def normalize(request) do\n {expr , _} = Code.eval_string(request)\n expr\n end\n\n defp extract_vars(ast) do\n {_ast, acc} = Macro.postwalk(ast, [], &extract_var\/2)\n acc |> Enum.reverse\n end\n\n defp extract_var(ast = {var_name, [line: _], nil}, acc) when is_atom(var_name) and var_name != :_ do\n {ast, [var_name|acc]}\n end\n\n defp extract_var(ast, acc) do\n {ast, acc}\n end\n\n defp print_match_error(%{__struct__: type, description: description, line: line}) do\n IO.puts \"# #{Introspection.module_to_string(type)} on line #{line}: \\n# \u21b3 #{description}\"\n end\n\n defp print_match_error(%MatchError{}) do\n IO.puts \"# No match\"\n end\n\n defp print_match_error(e) do\n IO.inspect(e)\n end\n\n defp create_env(file, line) do\n %{requires: requires, imports: imports, module: module} =\n file\n |> Parser.parse_file(true, true, line)\n |> Metadata.get_env(line)\n\n __ENV__\n |> Ast.add_requires_to_env(requires)\n |> Ast.add_imports_to_env(imports)\n |> Ast.set_module_for_env(module)\n end\n\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"41852a171ce51cd019065da494b3e934202a1fb0","subject":"fix broken sync","message":"fix broken sync\n","repos":"envato\/iodized,envato\/iodized","old_file":"lib\/yodado\/feature_persistence\/mnesia.ex","new_file":"lib\/yodado\/feature_persistence\/mnesia.ex","new_contents":"defmodule Yodado.FeaturePersistence.Mnesia do\n\n @table_record Yodado.Feature.Feature\n\n @all_features_matcher Yodado.Feature.Feature.__record__(:fields) |>\n Enum.map(fn({key, _default}) -> {key, :_} end) |>\n Yodado.Feature.Feature.new\n\n def all() do\n features = :mnesia.dirty_match_object(@all_features_matcher)\n {:ok, features}\n end\n\n def find_feature({:key, feature_id}) do\n features = :mnesia.dirty_read(@table_record, feature_id)\n case features do\n [feature] ->\n {:ok, feature}\n [] ->\n :not_found\n end\n end\n\n def find_feature(feature_id) do\n find_feature({:key, key(feature_id)})\n end\n\n def save_feature(feature) do\n :ok = :mnesia.transaction(fn() ->\n :mnesia.write(feature)\n end)\n {:ok, true}\n end\n\n def delete_feature({:key, feature_id}) do\n :ok = :mnesia.transaction(fn() ->\n :mnesia.delete({@table_record, feature_id})\n end)\n {:ok, true}\n end\n\n def delete_feature(feature_id) do\n delete_feature({:key, feature_id})\n end\n\n #TODO this must die. only used by old JS client\n def sync(features) do\n {:atomic, :ok} = :mnesia.transaction(fn() ->\n #TODO slow, and hacky...\n keys = :mnesia.all_keys(@table_record)\n Enum.each(keys, fn(k) ->\n :ok = :mnesia.delete({@table_record, k})\n end)\n\n Enum.each(features, fn(f) ->\n :ok = :mnesia.write(f)\n end)\n end)\n {:ok, true}\n end\n\n defp key(feature) when is_record(feature, @table_record) do\n feature.title\n end\n\n defp key(feature_id) do\n feature_id\n end\nend\n","old_contents":"defmodule Yodado.FeaturePersistence.Mnesia do\n\n @table_record Yodado.Feature.Feature\n\n @all_features_matcher Yodado.Feature.Feature.__record__(:fields) |>\n Enum.map(fn({key, _default}) -> {key, :_} end) |>\n Yodado.Feature.Feature.new\n\n def all() do\n features = :mnesia.dirty_match_object(@all_features_matcher)\n {:ok, features}\n end\n\n def find_feature({:key, feature_id}) do\n features = :mnesia.dirty_read(@table_record, feature_id)\n case features do\n [feature] ->\n {:ok, feature}\n [] ->\n :not_found\n end\n end\n\n def find_feature(feature_id) do\n find_feature({:key, key(feature_id)})\n end\n\n def save_feature(feature) do\n :ok = :mnesia.transaction(fn() ->\n :mnesia.write(feature)\n end)\n {:ok, true}\n end\n\n def delete_feature({:key, feature_id}) do\n :ok = :mnesia.transaction(fn() ->\n :mnesia.delete({@table_record, feature_id})\n end)\n {:ok, true}\n end\n\n def delete_feature(feature_id) do\n delete_feature({:key, feature_id})\n end\n\n #TODO this must die\n def sync(features) do\n # TODO not transactional. tut, tut, tut\n {:atomic, :ok} = :mnesia.clear_table(@table_record)\n :mnesia.transaction(fn() ->\n Enum.each(features, fn(f) ->\n {:atomic, :ok} = :mnesia.write(f)\n end)\n end)\n {:ok, true}\n end\n\n defp key(feature) when is_record(feature, @table_record) do\n feature.title\n end\n\n defp key(feature_id) do\n feature_id\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"ffb5b0c61f64c3437fae4a0d22d4800a24d9c256","subject":"Refactored monitor so there can be multiple running supervised","message":"Refactored monitor so there can be multiple running supervised\n","repos":"gtcode\/phoenix-trello,gtcode\/phoenix-trello,bigardone\/phoenix-trello,knightbk\/trollo,bigardone\/phoenix-trello,knightbk\/trollo","old_file":"lib\/phoenix_trello\/board_channel\/monitor.ex","new_file":"lib\/phoenix_trello\/board_channel\/monitor.ex","new_contents":"defmodule PhoenixTrello.BoardChannel.Monitor do\n @moduledoc \"\"\"\n Board monitor that keeps track of connected users.\n \"\"\"\n\n use GenServer\n\n #####\n # External API\n\n def create(board_id) do\n case GenServer.whereis(ref(board_id)) do\n nil ->\n Supervisor.start_child(PhoenixTrello.BoardChannel.Supervisor, [board_id])\n _board ->\n {:error, :board_already_exists}\n end\n end\n\n def start_link(board_id) do\n GenServer.start_link(__MODULE__, [], name: ref(board_id))\n end\n\n def user_joined(board_id, user) do\n try_call board_id, {:user_joined, user}\n end\n\n def users_in_board_id(board_id) do\n try_call board_id, {:users_in_board_id}\n end\n\n def user_left(board_id, user) do\n try_call board_id, {:user_left, user}\n end\n\n #####\n # GenServer implementation\n\n def handle_call({:user_joined, user}, _from, users) do\n users = [user] ++ users\n |> Enum.uniq\n\n {:reply, users, users}\n end\n\n def handle_call({:users_in_board_id}, _from, users) do\n { :reply, users, users }\n end\n\n def handle_call({:user_left, user}, _from, users) do\n users = List.delete(users, user)\n {:reply, users, users}\n end\n\n defp ref(board_id) do\n {:global, {:board, board_id}}\n end\n\n defp try_call(board_id, call_function) do\n case GenServer.whereis(ref(board_id)) do\n nil ->\n {:error, :invalid_board}\n board ->\n GenServer.call(board, call_function)\n end\n end\nend\n","old_contents":"defmodule PhoenixTrello.BoardChannel.Monitor do\n @moduledoc \"\"\"\n Board channel monitor that keeps track of connected users per board.\n \"\"\"\n\n use GenServer\n\n #####\n # External API\n\n def start_link(initial_state) do\n GenServer.start_link(__MODULE__, initial_state, name: __MODULE__)\n end\n\n def user_joined(channel, user) do\n GenServer.call(__MODULE__, {:user_joined, channel, user})\n end\n\n def users_in_channel(channel) do\n GenServer.call(__MODULE__, {:users_in_channel, channel})\n end\n\n def user_left(channel, user_id) do\n GenServer.call(__MODULE__, {:user_left, channel, user_id})\n end\n\n #####\n # GenServer implementation\n\n def handle_call({:user_joined, channel, user}, _from, state) do\n state = case Map.get(state, channel) do\n nil ->\n state |> Map.put(channel, [user])\n users ->\n state |> Map.put(channel, Enum.uniq([user | users]))\n end\n\n {:reply, state, state}\n end\n\n def handle_call({:users_in_channel, channel}, _from, state) do\n { :reply, Map.get(state, channel), state }\n end\n\n def handle_call({:user_left, channel, user_id}, _from, state) do\n new_users = state\n |> Map.get(channel)\n |> Enum.reject(&(&1.id == user_id))\n\n state = state\n |> Map.update!(channel, fn(_) -> new_users end)\n\n {:reply, state, state}\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"08e7da305cbac7ea83df46461d4d76f71073df42","subject":"Fixed typos in file.ex docs","message":"Fixed typos in file.ex docs\n","repos":"antipax\/elixir,antipax\/elixir,kimshrier\/elixir,pedrosnk\/elixir,lexmag\/elixir,gfvcastro\/elixir,kimshrier\/elixir,beedub\/elixir,ggcampinho\/elixir,elixir-lang\/elixir,pedrosnk\/elixir,kelvinst\/elixir,gfvcastro\/elixir,kelvinst\/elixir,ggcampinho\/elixir,michalmuskala\/elixir,lexmag\/elixir,joshprice\/elixir,beedub\/elixir","old_file":"lib\/elixir\/lib\/file.ex","new_file":"lib\/elixir\/lib\/file.ex","new_contents":"defrecord File.Stat, Record.extract(:file_info, from_lib: \"kernel\/include\/file.hrl\") do\n @moduledoc \"\"\"\n A record responsible to hold file information. Its fields are:\n\n * `size` - Size of file in bytes.\n * `type` - `:device`, `:directory`, `:regular`, `:other`. The type of the file.\n * `access` - `:read`, `:write`, `:read_write`, `:none`. The current system access to\n the file.\n * `atime` - The last time the file was read.\n * `mtime` - The last time the file was written.\n * `ctime` - The interpretation of this time field depends on the operating\n system. On Unix, it is the last time the file or the inode was\n changed. In Windows, it is the create time.\n * `mode` - The file permissions.\n * `links` - The number of links to this file. This is always 1 for file\n systems which have no concept of links.\n * `major_device` - Identifies the file system where the file is located.\n In windows, the number indicates a drive as follows:\n 0 means A:, 1 means B:, and so on.\n * `minor_device` - Only valid for character devices on Unix. In all other\n cases, this field is zero.\n * `inode` - Gives the inode number. On non-Unix file systems, this field\n will be zero.\n * `uid` - Indicates the owner of the file.\n * `gid` - Gives the group that the owner of the file belongs to. Will be\n zero for non-Unix file systems.\n\n The time type returned in `atime`, `mtime`, and `ctime` is dependent on the\n time type set in options. `{:time, type}` where type can be `:local`,\n `:universal`, or `:posix`. Default is `:local`.\n \"\"\"\nend\n\ndefexception File.Error, [reason: nil, action: \"\", path: nil] do\n def message(exception) do\n formatted = list_to_binary(:file.format_error(reason exception))\n \"could not #{action exception} #{path exception}: #{formatted}\"\n end\nend\n\ndefexception File.CopyError, [reason: nil, action: \"\", source: nil, destination: nil, on: nil] do\n def message(exception) do\n formatted = list_to_binary(:file.format_error(reason exception))\n location = if on = on(exception), do: \". #{on}\", else: \"\"\n \"could not #{action exception} from #{source exception} to \" <>\n \"#{destination exception}#{location}: #{formatted}\"\n end\nend\n\ndefexception File.IteratorError, reason: nil do\n def message(exception) do\n formatted = list_to_binary(:file.format_error(reason exception))\n \"error during file iteration: #{formatted}\"\n end\nend\n\ndefmodule File do\n @moduledoc \"\"\"\n This module contains functions to manipulate files.\n\n Some of those functions are low-level, allowing the user\n to interact with the file or IO devices, like `File.open\/2`,\n `File.copy\/3` and others. This module also provides higher\n level functions that works with filenames and have their naming\n based on UNIX variants. For example, one can copy a file\n via `File.cp\/3` and remove files and directories recursively\n via `File.rm_rf\/2`\n\n In order to write and read files, one must use the functions\n in the IO module. By default, a file is opened in binary mode\n which requires the functions `IO.binread`, `IO.binwrite` and\n `IO.binreadline` to interact with the file. A developer may\n pass `:utf8` as an option when opening the file and then all\n other functions from IO are available, since they work directly\n with Unicode data.\n\n Most of the functions in this module return `:ok` or\n `{ :ok, result }` in case of success, `{ :error, reason }`\n otherwise. Those function are also followed by a variant\n that ends with `!` which returns the result (without the\n `{ :ok, result }` tuple) in case of success or raises an\n exception in case it fails. For example:\n\n File.read(\"hello.txt\")\n #=> { :ok, \"World\" }\n\n File.read(\"invalid.txt\")\n #=> { :error, :enoent }\n\n File.read!(\"hello.txt\")\n #=> \"World\"\n\n File.read!(\"invalid.txt\")\n #=> raises File.Error\n\n In general, a developer should use the former in case he wants\n to react if the file does not exist. The latter should be used\n when the developer expects his software to fail in case the\n file cannot be read (i.e. it is literally an exception).\n \"\"\"\n\n alias :file, as: F\n alias :filename, as: FN\n alias :filelib, as: FL\n\n @doc \"\"\"\n Returns true if the path is a regular file.\n\n ## Examples\n\n File.regular? __FILE__ #=> true\n\n \"\"\"\n def regular?(path) do\n FL.is_regular(path)\n end\n\n @doc \"\"\"\n Returns true if the path is a directory.\n \"\"\"\n def dir?(path) do\n FL.is_dir(path)\n end\n\n @doc \"\"\"\n Returns true if the given path exists.\n It can be regular file, directory, socket,\n symbolic link, named pipe or device file.\n\n ## Examples\n\n File.exists?(\"test\/\")\n #=> true\n\n File.exists?(\"missing.txt\")\n #=> false\n\n File.exists?(\"\/dev\/null\")\n #=> true\n\n \"\"\"\n def exists?(path) do\n match?({ :ok, _ }, F.read_file_info(path))\n end\n\n @doc \"\"\"\n Tries to create the directory `path`. Missing parent directories are not created.\n Returns `:ok` if successful, or `{:error, reason}` if an error occurs.\n\n Typical error reasons are:\n\n * :eacces - Missing search or write permissions for the parent directories of `path`.\n * :eexist - There is already a file or directory named `path`.\n * :enoent - A component of `path` does not exist.\n * :enospc - There is a no space left on the device.\n * :enotdir - A component of `path` is not a directory\n On some platforms, `:enoent` is returned instead.\n \"\"\"\n def mkdir(path) do\n F.make_dir(path)\n end\n\n @doc \"\"\"\n Same as `mkdir`, but raises an exception in case of failure. Otherwise `:ok`.\n \"\"\"\n def mkdir!(path) do\n case mkdir(path) do\n :ok -> :ok\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"make directory\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Tries to create the directory `path`. Missing parent directories are created.\n Returns `:ok` if successful, or `{:error, reason}` if an error occurs.\n\n Typical error reasons are:\n\n * :eacces - Missing search or write permissions for the parent directories of `path`.\n * :enospc - There is a no space left on the device.\n * :enotdir - A component of `path` is not a directory.\n \"\"\"\n def mkdir_p(path) do\n FL.ensure_dir(FN.join(path, \".\"))\n end\n\n @doc \"\"\"\n Same as `mkdir_p`, but raises an exception in case of failure. Otherwise `:ok`.\n \"\"\"\n def mkdir_p!(path) do\n case mkdir_p(path) do\n :ok -> :ok\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"make directory (with -p)\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Returns `{:ok, binary}`, where `binary` is a binary data object that contains the contents\n of `path`, or `{:error, reason}` if an error occurs.\n\n Typical error reasons:\n\n * :enoent - The file does not exist.\n * :eacces - Missing permission for reading the file,\n or for searching one of the parent directories.\n * :eisdir - The named file is a directory.\n * :enotdir - A component of the file name is not a directory.\n On some platforms, `:enoent` is returned instead.\n * :enomem - There is not enough memory for the contents of the file.\n\n You can use `:file.format_error(reason)` to get a descriptive string of the error.\n \"\"\"\n def read(path) do\n F.read_file(path)\n end\n\n @doc \"\"\"\n Returns binary with the contents of the given filename or raises\n File.Error if an error occurs.\n \"\"\"\n def read!(path) do\n case read(path) do\n { :ok, binary } ->\n binary\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"read file\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Returns information about the `path`. If it exists, it\n returns a `{ :ok, info }` tuple, where info is a\n `File.Info` record. Retuns `{ :error, reason }` with\n the same reasons as `File.read` if a failure occurs.\n\n ## Options\n\n The accepted options are:\n\n * `:time` if the time should be local, universal or posix.\n Default is local.\n\n \"\"\"\n def stat(path, opts \/\/ []) do\n case F.read_file_info(path, opts) do\n {:ok, fileinfo} ->\n {:ok, File.Stat.new fileinfo}\n error ->\n error\n end\n end\n\n @doc \"\"\"\n Same as `stat` but returns the `File.Stat` directly and\n throws `File.Error` if an error is returned.\n \"\"\"\n def stat!(path, opts \/\/ []) do\n case stat(path, opts) do\n {:ok, info} -> info\n {:error, reason} ->\n raise File.Error, reason: reason, action: \"read file stats\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Writes the given `File.Stat` back to the filesystem at the given\n path. Returns `:ok` or `{ :error, reason }`.\n \"\"\"\n def write_stat(path, File.Stat[] = stat, opts \/\/ []) do\n F.write_file_info(path, set_elem(stat, 0, :file_info), opts)\n end\n\n @doc \"\"\"\n Same as `write_stat\/3` but raises an exception if it fails.\n Returns `:ok` otherwise.\n \"\"\"\n def write_stat!(path, File.Stat[] = stat, opts \/\/ []) do\n case write_stat(path, stat, opts) do\n :ok -> :ok\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"write file stats\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Updates modification time (mtime) and access time (atime) of\n the given file. File is created if it doesn\u2019t exist.\n \"\"\"\n def touch(path, time \/\/ :calendar.local_time) do\n case F.change_time(path, time) do\n { :error, :enoent } -> write(path, \"\")\n other -> other\n end\n end\n\n @doc \"\"\"\n Same as `touch\/1` but raises an exception if it fails.\n Returns `:ok` otherwise.\n \"\"\"\n def touch!(path, time \/\/ :calendar.local_time) do\n case touch(path, time) do\n :ok -> :ok\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"touch\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Copies the contents of `source` to `destination`.\n\n Both parameters can be a filename or an io device opened\n with `File.open\/2`. `bytes_count` specifies the number of\n bytes to copy, the default being `:infinity`.\n\n If file `destination` already exists, it is overwritten\n by the contents in `source`.\n\n Returns `{ :ok, bytes_copied }` if successful,\n `{ :error, reason }` otherwise.\n\n Compared to the `File.cp\/3`, this function is more low-level,\n allowing a copy from device to device limited by a number of\n bytes. On the other hand, `File.cp\/3` performs more extensive\n checks on both source and destination and it also preserves\n the file mode after copy.\n\n Typical error reasons are the same as in `open\/2`,\n `read\/1` and `write\/2`.\n \"\"\"\n def copy(source, destination, bytes_count \/\/ :infinity) do\n F.copy(source, destination, bytes_count)\n end\n\n @doc \"\"\"\n The same as `copy\/3` but raises an `File.CopyError` if it fails.\n Returns the `bytes_copied` otherwise.\n \"\"\"\n def copy!(source, destination, bytes_count \/\/ :infinity) do\n case copy(source, destination, bytes_count) do\n { :ok, bytes_count } -> bytes_count\n { :error, reason } ->\n raise File.CopyError, reason: reason, action: \"copy\",\n source: :unicode.characters_to_binary(source), destination: :unicode.characters_to_binary(destination)\n end\n end\n\n @doc \"\"\"\n Copies the contents in `source` to `destination` preserving its mode.\n\n Similar to the command `cp` in Unix systems, this function\n behaves differently depending if `destination` is a directory\n or not. In particular, if `destination` is a directory, it\n copies the contents of `source` to `destination\/source`.\n\n If a file already exists in the destination, it invokes a\n callback which should return true if the existing file\n should be overwritten, false otherwise. It defaults to return true.\n\n It returns `:ok` in case of success, returns\n `{ :error, reason }` otherwise.\n\n If you want to copy contents from an io device to another device\n or do a straight copy from a source to a destination without\n preserving modes, check `File.copy\/3` instead.\n \"\"\"\n def cp(source, destination, callback \/\/ fn(_, _) -> true end) do\n output =\n if dir?(destination) do\n mkdir(destination)\n FN.join(destination, FN.basename(source))\n else\n destination\n end\n\n case do_cp_file(source, output, callback, []) do\n { :error, reason, _ } -> { :error, reason }\n _ -> :ok\n end\n end\n\n @doc \"\"\"\n The same as `cp\/3`, but raises File.CopyError if it fails.\n Returns the list of copied files otherwise.\n \"\"\"\n def cp!(source, destination, callback \/\/ fn(_, _) -> true end) do\n case cp(source, destination, callback) do\n :ok -> :ok\n { :error, reason } ->\n raise File.CopyError, reason: reason, action: \"copy recursively\",\n source: :unicode.characters_to_binary(source),\n destination: :unicode.characters_to_binary(destination)\n end\n end\n\n @doc %B\"\"\"\n Copies the contents in source to destination.\n Similar to the command `cp -r` in Unix systems,\n this function behaves differently depending\n if `source` and `destination` are a file or a directory.\n\n If both are files, it simply copies `source` to\n `destination`. However, if `destination` is a directory,\n it copies the contents of `source` to `destination\/source`\n recursively.\n\n If a file already exists in the destination,\n it invokes a callback which should return\n true if the existing file should be overwritten,\n false otherwise. It defaults to return true.\n\n If a directory already exists in the destination\n where a file is meant to be (or otherwise), this\n function will fail.\n\n This function may fail while copying files,\n in such cases, it will leave the destination\n directory in a dirty state, where already\n copied files won't be removed.\n\n It returns `{ :ok, files_and_directories }` in case of\n success with all files and directories copied in no\n specific order, `{ :error, reason }` otherwise.\n\n ## Examples\n\n # Copies \"a.txt\" to \"tmp\/a.txt\"\n File.cp_r \"a.txt\", \"tmp\"\n\n # Copies all files in \"samples\" to \"tmp\/samples\"\n File.cp_r \"samples\", \"tmp\"\n\n # Copies all files in \"samples\" to \"tmp\"\n File.cp_r \"samples\/.\", \"tmp\"\n\n # Same as before, but asks the user how to proceed in case of conflicts\n File.cp_r \"samples\/.\", \"tmp\", fn(source, destination) ->\n IO.gets(\"Overwriting #{destination} by #{source}. Type y to confirm.\") == \"y\"\n end\n\n \"\"\"\n def cp_r(source, destination, callback \/\/ fn(_, _) -> true end) when is_function(callback) do\n output =\n if dir?(destination) || dir?(source) do\n mkdir(destination)\n FN.join(destination, FN.basename(source))\n else\n destination\n end\n\n case do_cp_r(source, output, callback, []) do\n { :error, _, _ } = error -> error\n res -> { :ok, res }\n end\n end\n\n @doc \"\"\"\n The same as `cp_r\/3`, but raises File.CopyError if it fails.\n Returns the list of copied files otherwise.\n \"\"\"\n def cp_r!(source, destination, callback \/\/ fn(_, _) -> true end) do\n case cp_r(source, destination, callback) do\n { :ok, files } -> files\n { :error, reason, file } ->\n raise File.CopyError, reason: reason, action: \"copy recursively\",\n source: :unicode.characters_to_binary(source),\n destination: :unicode.characters_to_binary(destination),\n on: file\n end\n end\n\n # src may be a file or a directory, dest is definitely\n # a directory. Returns nil unless an error is found.\n defp do_cp_r(src, dest, callback, acc) when is_list(acc) do\n case :elixir.file_type(src) do\n { :ok, :regular } ->\n do_cp_file(src, dest, callback, acc)\n { :ok, :symlink } ->\n case F.read_link(src) do\n { :ok, link } -> do_cp_link(link, src, dest, callback, acc)\n { :error, reason } -> { :error, reason, :unicode.characters_to_binary(src) }\n end\n { :ok, :directory } ->\n case F.list_dir(src) do\n { :ok, files } ->\n case mkdir(dest) do\n success in [:ok, { :error, :eexist }] ->\n Enum.reduce(files, [dest|acc], fn(x, acc) ->\n do_cp_r(FN.join(src, x), FN.join(dest, x), callback, acc)\n end)\n { :error, reason } -> { :error, reason, :unicode.characters_to_binary(dest) }\n end\n { :error, reason } -> { :error, reason, :unicode.characters_to_binary(src) }\n end\n { :ok, _ } -> { :error, :eio, src }\n { :error, reason } -> { :error, reason, :unicode.characters_to_binary(src) }\n end\n end\n\n # If we reach this clause, there was an error while\n # processing a file.\n defp do_cp_r(_, _, _, acc) do\n acc\n end\n\n defp copy_file_mode!(src, dest) do\n src_stat = File.stat!(src)\n dest_stat = File.stat!(dest)\n File.write_stat!(dest, File.Stat.mode(File.Stat.mode(src_stat), dest_stat))\n end\n\n # Both src and dest are files.\n defp do_cp_file(src, dest, callback, acc) do\n case copy(src, { dest, [:exclusive] }) do\n { :ok, _ } ->\n copy_file_mode!(src, dest)\n [dest|acc]\n { :error, :eexist } ->\n if callback.(src, dest) do\n rm(dest)\n case copy(src, dest) do\n { :ok, _ } ->\n copy_file_mode!(src, dest)\n [dest|acc]\n { :error, reason } -> { :error, reason, :unicode.characters_to_binary(src) }\n end\n else\n acc\n end\n { :error, reason } -> { :error, reason, :unicode.characters_to_binary(src) }\n end\n end\n\n # Both src and dest are files.\n defp do_cp_link(link, src, dest, callback, acc) do\n case F.make_symlink(link, dest) do\n :ok ->\n [dest|acc]\n { :error, :eexist } ->\n if callback.(src, dest) do\n rm(dest)\n case F.make_symlink(link, dest) do\n :ok -> [dest|acc]\n { :error, reason } -> { :error, reason, :unicode.characters_to_binary(src) }\n end\n else\n acc\n end\n { :error, reason } -> { :error, reason, :unicode.characters_to_binary(src) }\n end\n end\n\n @doc \"\"\"\n Writes `content` to the file `path`. The file is created if it\n does not exist. If it exists, the previous contents are overwritten.\n Returns `:ok` if successful, or `{:error, reason}` if an error occurs.\n\n Typical error reasons are:\n\n * :enoent - A component of the file name does not exist.\n * :enotdir - A component of the file name is not a directory.\n On some platforms, enoent is returned instead.\n * :enospc - There is a no space left on the device.\n * :eacces - Missing permission for writing the file or searching one of the parent directories.\n * :eisdir - The named file is a directory.\n \"\"\"\n def write(path, content, modes \/\/ []) do\n F.write_file(path, content, modes)\n end\n\n @doc \"\"\"\n Same as `write\/3` but raises an exception if it fails, returns `:ok` otherwise.\n \"\"\"\n def write!(path, content, modes \/\/ []) do\n case F.write_file(path, content, modes) do\n :ok -> :ok\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"write to file\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Tries to delete the file `path`.\n Returns `:ok` if successful, or `{:error, reason}` if an error occurs.\n\n Typical error reasons are:\n\n * :enoent - The file does not exist.\n * :eacces - Missing permission for the file or one of its parents.\n * :eperm - The file is a directory and user is not super-user.\n * :enotdir - A component of the file name is not a directory.\n On some platforms, enoent is returned instead.\n * :einval - Filename had an improper type, such as tuple.\n\n ## Examples\n\n File.rm('file.txt')\n #=> :ok\n\n File.rm('tmp_dir\/')\n #=> {:error, :eperm}\n\n \"\"\"\n def rm(path) do\n F.delete(path)\n end\n\n @doc \"\"\"\n Same as `rm`, but raises an exception in case of failure. Otherwise `:ok`.\n \"\"\"\n def rm!(path) do\n case rm(path) do\n :ok -> :ok\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"remove file\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Tries to delete the dir at `path`.\n Returns `:ok` if successful, or `{:error, reason}` if an error occurs.\n\n ## Examples\n\n File.rddir('tmp_dir')\n #=> :ok\n\n File.rmdir('file.txt')\n #=> {:error, :enotdir}\n\n \"\"\"\n def rmdir(path) do\n F.del_dir(path)\n end\n\n @doc \"\"\"\n Same as `rmdir\/1`, but raises an exception in case of failure. Otherwise `:ok`.\n \"\"\"\n def rmdir!(path) do\n case rmdir(path) do\n :ok -> :ok\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"remove directory\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Remove files and directories recursively at the given `path`.\n Symlinks are not followed but simply removed, non-existing\n files are simply ignored (i.e. doesn't make this function fail).\n\n Returns `{ :ok, files_and_directories }` with all files and\n directories removed in no specific order, `{ :error, reason }`\n otherwise.\n\n ## Examples\n\n File.rm_rf \"samples\"\n #=> { :ok, [\"samples\", \"samples\/1.txt\"] }\n\n File.rm_rf \"unknown\"\n #=> { :ok, [] }\n\n \"\"\"\n def rm_rf(path) do\n do_rm_rf(path, { :ok, [] })\n end\n\n defp do_rm_rf(path, { :ok, acc } = entry) do\n case safe_list_dir(path) do\n { :ok, files } ->\n res =\n Enum.reduce files, entry, fn(file, tuple) ->\n do_rm_rf(FN.join(path, file), tuple)\n end\n\n case res do\n { :ok, acc } ->\n case rmdir(path) do\n :ok -> { :ok, [path|acc] }\n { :error, :enoent } -> res\n reason -> { :error, reason, :unicode.characters_to_binary(path) }\n end\n reason -> { :error, reason, :unicode.characters_to_binary(path) }\n end\n { :error, reason } when reason in [:enotdir, :eio] ->\n case rm(path) do\n :ok -> { :ok, [path|acc] }\n { :error, reason } when reason in [:enoent, :enotdir] -> entry\n reason -> { :error, reason, :unicode.characters_to_binary(path) }\n end\n { :error, :enoent } -> entry\n { :error, reason } -> { :error, reason, :unicode.characters_to_binary(path) }\n end\n end\n\n defp do_rm_rf(_, reason) do\n reason\n end\n\n defp safe_list_dir(path) do\n case F.read_link(path) do\n { :ok, _ } -> { :error, :enotdir }\n _ -> F.list_dir(path)\n end\n end\n\n @doc \"\"\"\n Same as `rm_rf\/1` but raises `File.Error` in case of failures,\n otherwise the list of files or directories removed.\n \"\"\"\n def rm_rf!(path) do\n case rm_rf(path) do\n { :ok, files } -> files\n { :error, reason, _ } ->\n raise File.Error, reason: reason,\n action: \"remove files and directories recursively from\",\n path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Opens the given `path` according to the given list of modes.\n\n In order to write and read files, one must use the functions\n in the IO module. By default, a file is opened in binary mode\n which requires the functions `IO.binread`, `IO.binwrite` and\n `IO.binreadline` to interact with the file. A developer may pass\n `:utf8` as an option when opening the file and then all other\n functions from IO are available, since they work directly with\n Unicode data.\n\n The allowed modes:\n\n * `:read` - The file, which must exist, is opened for reading.\n\n * `:write` - The file is opened for writing. It is created if it does not exist.\n If the file exists, and if write is not combined with read, the file will be truncated.\n\n * `:append` - The file will be opened for writing, and it will be created if it does not exist.\n Every write operation to a file opened with append will take place at the end of the file.\n\n * `:exclusive` - The file, when opened for writing, is created if it does not exist.\n If the file exists, open will return { :error, :eexist }.\n\n * `:charlist` - When this term is given, read operations on the file will return char lists rather than binaries;\n\n * `:compressed` - Makes it possible to read or write gzip compressed files.\n The compressed option must be combined with either read or write, but not both.\n Note that the file size obtained with `stat\/1` will most probably not\n match the number of bytes that can be read from a compressed file.\n\n * `:utf8` - This option denotes how data is actually stored in the disk file and\n makes the file perform automatic translation of characters to and from utf-8.\n If data is sent to a file in a format that cannot be converted to the utf-8\n or if data is read by a function that returns data in a format that cannot cope\n with the character range of the data, an error occurs and the file will be closed.\n\n If a function is given to modes (instead of a list), it dispatches to `open\/3`.\n\n Check `http:\/\/www.erlang.org\/doc\/man\/file.html#open-2` for more information about\n other options as `read_ahead` and `delayed_write`.\n\n This function returns:\n\n * `{ :ok, io_device }` - The file has been opened in the requested mode.\n `io_device` is actually the pid of the process which handles the file.\n This process is linked to the process which originally opened the file.\n If any process to which the `io_device` is linked terminates, the file will\n be closed and the process itself will be terminated. An `io_device` returned\n from this call can be used as an argument to the `IO` module functions.\n\n * `{ :error, reason }` - The file could not be opened.\n\n ## Examples\n\n { :ok, file } = File.open(\"foo.tar.gz\", [:read, :compressed])\n IO.readline(file)\n File.close(file)\n\n \"\"\"\n def open(path, modes \/\/ [])\n\n def open(path, modes) when is_list(modes) do\n F.open(path, open_defaults(modes, true))\n end\n\n def open(path, function) when is_function(function) do\n open(path, [], function)\n end\n\n @doc \"\"\"\n Similar to `open\/2` but expects a function as last argument.\n\n The file is opened, given to the function as argument and\n automatically closed after the function returns, regardless\n if there was an error or not.\n\n It returns `{ :ok, function_result }` in case of success,\n `{ :error, reason }` otherwise.\n\n Do not use this function with :delayed_write option\n since automatically closing the file may fail\n (as writes are delayed).\n\n ## Examples\n\n File.open(\"file.txt\", [:read, :write], fn(file) ->\n IO.readline(file)\n end)\n\n \"\"\"\n def open(path, modes, function) do\n case open(path, modes) do\n { :ok, device } ->\n try do\n { :ok, function.(device) }\n after\n :ok = close(device)\n end\n other -> other\n end\n end\n\n @doc \"\"\"\n Same as `open\/2` but raises an error if file could not be opened.\n Returns the `io_device` otherwise.\n \"\"\"\n def open!(path, modes \/\/ []) do\n case open(path, modes) do\n { :ok, device } -> device\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"open\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Same as `open\/3` but raises an error if file could not be opened.\n Returns the function result otherwise.\n \"\"\"\n def open!(path, modes, function) do\n case open(path, modes, function) do\n { :ok, device } -> device\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"open\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Gets the current working directory. In rare circumstances, this function can\n fail on Unix. It may happen if read permission does not exist for the parent\n directories of the current directory. For this reason, returns `{ :ok, cwd }`\n in case of success, `{ :error, reason }` otherwise.\n \"\"\"\n def cwd() do\n case F.get_cwd do\n { :ok, cwd } -> { :ok, :unicode.characters_to_binary(cwd) }\n { :error, _ } = error -> error\n end\n end\n\n @doc \"\"\"\n The same as `cwd\/0`, but raises an exception if it fails.\n \"\"\"\n def cwd!() do\n case F.get_cwd do\n { :ok, cwd } -> :unicode.characters_to_binary(cwd)\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"get current working directory\"\n end\n end\n\n @doc \"\"\"\n Sets the current working directory. Returns `:ok` if successful,\n `{ :error, reason }` otherwise.\n \"\"\"\n def cd(path) do\n F.set_cwd(path)\n end\n\n @doc \"\"\"\n The same as `cd\/0`, but raises an exception if it fails.\n \"\"\"\n def cd!(path) do\n case F.set_cwd(path) do\n :ok -> :ok\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"set current working directory to\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Changes the current directory to the given `path`,\n executes the given function and then revert back\n to the previous path regardless if there is an exception.\n\n Raises an error if retrieving or changing the current\n directory fails.\n \"\"\"\n def cd!(path, function) do\n old = cwd!\n cd!(path)\n try do\n function.()\n after\n cd!(old)\n end\n end\n\n @doc \"\"\"\n Returns list of files in the given directory.\n\n It returns `{ :ok, [files] }` in case of success,\n `{ :error, reason }` otherwise.\n \"\"\"\n def ls(path \/\/ \".\") do\n case F.list_dir(path) do\n { :ok, file_list } -> { :ok, Enum.map file_list, :unicode.characters_to_binary(&1) }\n { :error, _ } = error -> error\n end\n end\n\n @doc \"\"\"\n The same as `ls\/1` but raises `File.Error`\n in case of an error.\n \"\"\"\n def ls!(dir \/\/ \".\") do\n case ls(dir) do\n { :ok, value } -> value\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"list directory\", path: :unicode.characters_to_binary(dir)\n end\n end\n\n @doc \"\"\"\n Closes the file referenced by `io_device`. It mostly returns `:ok`, except\n for some severe errors such as out of memory.\n\n Note that if the option `:delayed_write` was used when opening the file,\n `close\/1` might return an old write error and not even try to close the file.\n See `open\/2`.\n \"\"\"\n def close(io_device) do\n F.close(io_device)\n end\n\n @doc \"\"\"\n Converts the file device into an iterator that can be\n passed into `Enum`. The device is iterated line\n by line, at the end of iteration the file is closed.\n\n This reads the file as utf-8. Check out `File.biniterator`\n to handle the file as a raw binary.\n\n ## Examples\n\n An example that lazily iterates a file replacing all double\n quotes per single quotes and writes each line to a target file\n is shown below:\n\n { :ok, device } = File.open(\"README.md\")\n source = File.iterator(device)\n File.open \"NEWREADME.md\", [:write], fn(target) ->\n Enum.each source, fn(line) ->\n IO.write target, Regex.replace(%r\/\"\/, line, \"'\")\n end\n end\n\n \"\"\"\n def iterator(device) do\n fn(fun, acc) ->\n do_iterator(device, fun, acc)\n end\n end\n\n @doc \"\"\"\n Opens the given `file` with the given `mode` and\n returns its iterator. The returned iterator will\n fail for the same reasons as `File.open!`. Note\n that the file is opened when the iteration begins.\n \"\"\"\n def iterator!(file, mode \/\/ []) do\n fn(fun, acc) ->\n device = open!(file, mode)\n try do\n do_iterator(device, fun, acc)\n after\n F.close(device)\n end\n end\n end\n\n @doc \"\"\"\n Converts the file device into an iterator that can\n be passed into `Enum` to iterate line by line as a\n binary. Check `iterator\/1` for more information.\n \"\"\"\n def biniterator(device) do\n fn(fun, acc) ->\n do_biniterator(device, fun, acc)\n end\n end\n\n @doc \"\"\"\n Opens the given `file` with the given `mode` and\n returns its biniterator. The returned iterator will\n fail for the same reasons as `File.open!`. Note\n that the file is opened when the iteration begins.\n \"\"\"\n def biniterator!(file, mode \/\/ []) do\n fn(fun, acc) ->\n device = open!(file, mode)\n try do\n do_biniterator(device, fun, acc)\n after\n F.close(device)\n end\n end\n end\n\n ## Helpers\n\n defp open_defaults([:charlist|t], _add_binary) do\n open_defaults(t, false)\n end\n\n defp open_defaults([:utf8|t], add_binary) do\n open_defaults([{ :encoding, :utf8 }|t], add_binary)\n end\n\n defp open_defaults([h|t], add_binary) do\n [h|open_defaults(t, add_binary)]\n end\n\n defp open_defaults([], true), do: [:binary]\n defp open_defaults([], false), do: []\n\n defp do_iterator(device, acc, fun) do\n case :io.get_line(device, '') do\n :eof ->\n acc\n { :error, reason } ->\n raise File.IteratorError, reason: reason\n data ->\n do_iterator(device, fun.(data, acc), fun)\n end\n end\n\n defp do_biniterator(device, acc, fun) do\n case F.read_line(device) do\n :eof ->\n acc\n { :error, reason } ->\n raise File.IteratorError, reason: reason\n { :ok, data } ->\n do_iterator(device, fun.(data, acc), fun)\n end\n end\nend\n","old_contents":"defrecord File.Stat, Record.extract(:file_info, from_lib: \"kernel\/include\/file.hrl\") do\n @moduledoc \"\"\"\n A record responsible to hold file information. Its fields are:\n\n * `size` - Size of file in bytes.\n * `type` - `:device`, `:directory`, `:regular`, `:other`. The type of the file.\n * `access` - `:read`, `:write`, `:read_write`, `:none`. The current system access to\n the file.\n * `atime` - The last time the file was read.\n * `mtime` - The last time the file was written.\n * `ctime` - The interpretation of this time field depends on the operating\n system. On Unix, it is the last time the file or the inode was\n changed. In Windows, it is the create time.\n * `mode` - The file permissions.\n * `links` - The number of links to this file. This is always 1 for file\n systems which have no concept of links.\n * `major_device` - Identifies the file system where the file is located.\n In windows, the number indicates a drive as follows:\n 0 means A:, 1 means B:, and so on.\n * `minor_device` - Only valid for character devices on Unix. In all other\n cases, this field is zero.\n * `inode` - Gives the inode number. On non-Unix file systems, this field\n will be zero.\n * `uid` - Indicates the owner of the file.\n * `gid` - Gives the group that the owner of the file belongs to. Will be\n zero for non-Unix file systems.\n\n The time type returned in `atime`, `mtime`, and `ctime` is dependent on the\n time type set in options. `{:time, type}` where type can be `:local`,\n `:universal`, or `:posix`. Default is `:local`.\n \"\"\"\nend\n\ndefexception File.Error, [reason: nil, action: \"\", path: nil] do\n def message(exception) do\n formatted = list_to_binary(:file.format_error(reason exception))\n \"could not #{action exception} #{path exception}: #{formatted}\"\n end\nend\n\ndefexception File.CopyError, [reason: nil, action: \"\", source: nil, destination: nil, on: nil] do\n def message(exception) do\n formatted = list_to_binary(:file.format_error(reason exception))\n location = if on = on(exception), do: \". #{on}\", else: \"\"\n \"could not #{action exception} from #{source exception} to \" <>\n \"#{destination exception}#{location}: #{formatted}\"\n end\nend\n\ndefexception File.IteratorError, reason: nil do\n def message(exception) do\n formatted = list_to_binary(:file.format_error(reason exception))\n \"error during file iteration: #{formatted}\"\n end\nend\n\ndefmodule File do\n @moduledoc \"\"\"\n This module contains functions to manipulate files.\n\n Some of those functions are low-level, allowing the user\n to interact with the file or IO devices, like `File.open\/2`,\n `File.copy\/3` and others. This module also provides higher\n level functions that works with filenames and have their naming\n based on UNIX variants. For example, one can copy a file\n via `File.cp\/3` and remove files and directories recursively\n via `File.rm_rf\/2`\n\n In order to write and read files, one must use the functions\n in the IO module. By default, a file is opened in binary mode\n which requires the functions `IO.binread`, `IO.binwrite` and\n `IO.binreadline` to interact with the file. A developer may\n pass `:utf8` as an option when opening the file and then all\n other functions from IO are available, since they work directly\n with Unicode data.\n\n Most of the functions in this module return `:ok` or\n `{ :ok, result }` in case of success, `{ :error, reason }`\n otherwise. Those function are also followed by a variant\n that ends with `!` which returns the result (without the\n `{ :ok, result }` tuple) in case of success or raises an\n exception in case it fails. For example:\n\n File.read(\"hello.txt\")\n #=> { :ok, \"World\" }\n\n File.read(\"invalid.txt\")\n #=> { :error, :enoent }\n\n File.read!(\"hello.txt\")\n #=> \"World\"\n\n File.read!(\"invalid.txt\")\n #=> raises File.Error\n\n In general, a developer should use the former in case he wants\n to react in the fie does not exist. The latter should be used\n when the developer expects his software to fail in case the\n file cannot be read (i.e. it is literally an exception).\n \"\"\"\n\n alias :file, as: F\n alias :filename, as: FN\n alias :filelib, as: FL\n\n @doc \"\"\"\n Returns true if the path is a regular file.\n\n ## Examples\n\n File.regular? __FILE__ #=> true\n\n \"\"\"\n def regular?(path) do\n FL.is_regular(path)\n end\n\n @doc \"\"\"\n Returns true if the path is a directory.\n \"\"\"\n def dir?(path) do\n FL.is_dir(path)\n end\n\n @doc \"\"\"\n Returns true if the given argument exists.\n It can be regular file, directory, socket,\n symbolic link, named pipe or device file.\n\n ## Examples\n\n File.exists?(\"test\/\")\n #=> true\n\n File.exists?(\"missing.txt\")\n #=> false\n\n File.exists?(\"\/dev\/null\")\n #=> true\n\n \"\"\"\n def exists?(path) do\n match?({ :ok, _ }, F.read_file_info(path))\n end\n\n @doc \"\"\"\n Tries to create the directory `path`. Missing parent directories are not created.\n Returns `:ok` if successful, or `{:error, reason}` if an error occurs.\n\n Typical error reasons are:\n\n * :eacces - Missing search or write permissions for the parent directories of `path`.\n * :eexist - There is already a file or directory named `path`.\n * :enoent - A component of `path` does not exist.\n * :enospc - There is a no space left on the device.\n * :enotdir - A component of `path` is not a directory\n On some platforms, `:enoent` is returned instead.\n \"\"\"\n def mkdir(path) do\n F.make_dir(path)\n end\n\n @doc \"\"\"\n Same as `mkdir`, but raises an exception in case of failure. Otherwise `:ok`.\n \"\"\"\n def mkdir!(path) do\n case mkdir(path) do\n :ok -> :ok\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"make directory\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Tries to create the directory `path`. Missing parent directories are created.\n Returns `:ok` if successful, or `{:error, reason}` if an error occurs.\n\n Typical error reasons are:\n\n * :eacces - Missing search or write permissions for the parent directories of `path`.\n * :enospc - There is a no space left on the device.\n * :enotdir - A component of `path` is not a directory.\n \"\"\"\n def mkdir_p(path) do\n FL.ensure_dir(FN.join(path, \".\"))\n end\n\n @doc \"\"\"\n Same as `mkdir_p`, but raises an exception in case of failure. Otherwise `:ok`.\n \"\"\"\n def mkdir_p!(path) do\n case mkdir_p(path) do\n :ok -> :ok\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"make directory (with -p)\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Returns `{:ok, binary}`, where `binary` is a binary data object that contains the contents\n of `path`, or `{:error, reason}` if an error occurs.\n\n Typical error reasons:\n\n * :enoent - The file does not exist.\n * :eacces - Missing permission for reading the file,\n or for searching one of the parent directories.\n * :eisdir - The named file is a directory.\n * :enotdir - A component of the file name is not a directory.\n On some platforms, `:enoent` is returned instead.\n * :enomem - There is not enough memory for the contents of the file.\n\n You can use `:file.format_error(reason)` to get a descriptive string of the error.\n \"\"\"\n def read(path) do\n F.read_file(path)\n end\n\n @doc \"\"\"\n Returns binary with the contents of the given filename or raises\n File.Error if an error occurs.\n \"\"\"\n def read!(path) do\n case read(path) do\n { :ok, binary } ->\n binary\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"read file\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Returns information about the `path`. If it exists, it\n returns a `{ :ok, info }` tuple, where info is as a\n `File.Info` record. Retuns `{ :error, reason }` with\n the same reasons as `File.read` if a failure occurs.\n\n ## Options\n\n The accepted options are:\n\n * `:time` if the time should be local, universal or posix.\n Default is local.\n\n \"\"\"\n def stat(path, opts \/\/ []) do\n case F.read_file_info(path, opts) do\n {:ok, fileinfo} ->\n {:ok, File.Stat.new fileinfo}\n error ->\n error\n end\n end\n\n @doc \"\"\"\n Same as `stat` but returns the `File.Stat` directly and\n throws `File.Error` if an error is returned.\n \"\"\"\n def stat!(path, opts \/\/ []) do\n case stat(path, opts) do\n {:ok, info} -> info\n {:error, reason} ->\n raise File.Error, reason: reason, action: \"read file stats\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Writes the given `File.Stat` back to the filesystem at the given\n path. Returns `:ok` or `{ :error, reason }`.\n \"\"\"\n def write_stat(path, File.Stat[] = stat, opts \/\/ []) do\n F.write_file_info(path, set_elem(stat, 0, :file_info), opts)\n end\n\n @doc \"\"\"\n Same as `write_stat\/3` but raises an exception if it fails.\n Returns `:ok` otherwise.\n \"\"\"\n def write_stat!(path, File.Stat[] = stat, opts \/\/ []) do\n case write_stat(path, stat, opts) do\n :ok -> :ok\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"write file stats\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Updates modification time (mtime) and access time (atime) of\n the given file. File is created if it doesn\u2019t exist.\n \"\"\"\n def touch(path, time \/\/ :calendar.local_time) do\n case F.change_time(path, time) do\n { :error, :enoent } -> write(path, \"\")\n other -> other\n end\n end\n\n @doc \"\"\"\n Same as `touch\/1` but raises an exception if it fails.\n Returns `:ok` otherwise.\n \"\"\"\n def touch!(path, time \/\/ :calendar.local_time) do\n case touch(path, time) do\n :ok -> :ok\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"touch\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Copies the contents of `source` to `destination`.\n\n Both parameters can be a filename or an io device opened\n with `File.open\/2`. `bytes_count` specifies the number of\n bytes to copy, the default being `:infinity`.\n\n If file `destination` already exists, it is overriden\n by the contents in `source`.\n\n Returns `{ :ok, bytes_copied }` if successful,\n `{ :error, reason }` otherwise.\n\n Compared to the `File.cp\/3`, this function is more low-level,\n allowing a copy from device to device limited by a number of\n bytes. On the other hand, `File.cp\/3` performs more extensive\n checks on both source and destination and it also preserves\n the file mode after copy.\n\n Typical error reasons are the same as in `open\/2`,\n `read\/1` and `write\/2`.\n \"\"\"\n def copy(source, destination, bytes_count \/\/ :infinity) do\n F.copy(source, destination, bytes_count)\n end\n\n @doc \"\"\"\n The same as `copy\/3` but raises an `File.CopyError` if it fails.\n Returns the `bytes_copied` otherwise.\n \"\"\"\n def copy!(source, destination, bytes_count \/\/ :infinity) do\n case copy(source, destination, bytes_count) do\n { :ok, bytes_count } -> bytes_count\n { :error, reason } ->\n raise File.CopyError, reason: reason, action: \"copy\",\n source: :unicode.characters_to_binary(source), destination: :unicode.characters_to_binary(destination)\n end\n end\n\n @doc \"\"\"\n Copies the contents in `source` to `destination` preserving its mode.\n\n Similar to the command `cp` in Unix systems, this function\n behaves differently depending if `destination` is a directory\n or not. In paritcular, if `destination` is a directory, it\n copies the contents of `source` to `destination\/source`.\n\n If a file already exists in the destination, it invokes a\n callback which should return true if the existing file\n should be overriden, false otherwise. It defaults to return true.\n\n It returns `:ok` in case of success, returns\n `{ :error, reason }` otherwise.\n\n If you want to copy contents from an io device to another device\n or do a straight copy from a source to a destination without\n preserving modes, check `File.copy\/3` instead.\n \"\"\"\n def cp(source, destination, callback \/\/ fn(_, _) -> true end) do\n output =\n if dir?(destination) do\n mkdir(destination)\n FN.join(destination, FN.basename(source))\n else\n destination\n end\n\n case do_cp_file(source, output, callback, []) do\n { :error, reason, _ } -> { :error, reason }\n _ -> :ok\n end\n end\n\n @doc \"\"\"\n The same as `cp\/3`, but raises File.CopyError if it fails.\n Returns the list of copied files otherwise.\n \"\"\"\n def cp!(source, destination, callback \/\/ fn(_, _) -> true end) do\n case cp(source, destination, callback) do\n :ok -> :ok\n { :error, reason } ->\n raise File.CopyError, reason: reason, action: \"copy recursively\",\n source: :unicode.characters_to_binary(source),\n destination: :unicode.characters_to_binary(destination)\n end\n end\n\n @doc %B\"\"\"\n Copies the contents in source to destination.\n Similar to the command `cp -r` in Unix systems,\n this function behaves differently depending\n if `source` and `destination` are a file or a directory.\n\n If both are files, it simply copies `source` to\n `destination`. However, if `destination` is a directory,\n it copies the contents of `source` to `destination\/source`\n recursively.\n\n If a file already exists in the destination,\n it invokes a callback which should return\n true if the existing file should be overriden,\n false otherwise. It defaults to return true.\n\n If a directory already exists in the destination\n where a file is meant to be (or otherwise), this\n function will fail.\n\n This function may fail while copying files,\n in such cases, it will leave the destination\n directory in a dirty state, where already\n copied files won't be removed.\n\n It returns `{ :ok, files_and_directories }` in case of\n success with all files and directories copied in no\n specific order, `{ :error, reason }` otherwise.\n\n ## Examples\n\n # Copies \"a.txt\" to \"tmp\/a.txt\"\n File.cp_r \"a.txt\", \"tmp\"\n\n # Copies all files in \"samples\" to \"tmp\/samples\"\n File.cp_r \"samples\", \"tmp\"\n\n # Copies all files in \"samples\" to \"tmp\"\n File.cp_r \"samples\/.\", \"tmp\"\n\n # Same as before, but asks the user how to proceed in case of conflicts\n File.cp_r \"samples\/.\", \"tmp\", fn(source, destination) ->\n IO.gets(\"Overriding #{destination} by #{source}. Type y to confirm.\") == \"y\"\n end\n\n \"\"\"\n def cp_r(source, destination, callback \/\/ fn(_, _) -> true end) when is_function(callback) do\n output =\n if dir?(destination) || dir?(source) do\n mkdir(destination)\n FN.join(destination, FN.basename(source))\n else\n destination\n end\n\n case do_cp_r(source, output, callback, []) do\n { :error, _, _ } = error -> error\n res -> { :ok, res }\n end\n end\n\n @doc \"\"\"\n The same as `cp_r\/3`, but raises File.CopyError if it fails.\n Returns the list of copied files otherwise.\n \"\"\"\n def cp_r!(source, destination, callback \/\/ fn(_, _) -> true end) do\n case cp_r(source, destination, callback) do\n { :ok, files } -> files\n { :error, reason, file } ->\n raise File.CopyError, reason: reason, action: \"copy recursively\",\n source: :unicode.characters_to_binary(source),\n destination: :unicode.characters_to_binary(destination),\n on: file\n end\n end\n\n # src may be a file or a directory, dest is definitely\n # a directory. Returns nil unless an error is found.\n defp do_cp_r(src, dest, callback, acc) when is_list(acc) do\n case :elixir.file_type(src) do\n { :ok, :regular } ->\n do_cp_file(src, dest, callback, acc)\n { :ok, :symlink } ->\n case F.read_link(src) do\n { :ok, link } -> do_cp_link(link, src, dest, callback, acc)\n { :error, reason } -> { :error, reason, :unicode.characters_to_binary(src) }\n end\n { :ok, :directory } ->\n case F.list_dir(src) do\n { :ok, files } ->\n case mkdir(dest) do\n success in [:ok, { :error, :eexist }] ->\n Enum.reduce(files, [dest|acc], fn(x, acc) ->\n do_cp_r(FN.join(src, x), FN.join(dest, x), callback, acc)\n end)\n { :error, reason } -> { :error, reason, :unicode.characters_to_binary(dest) }\n end\n { :error, reason } -> { :error, reason, :unicode.characters_to_binary(src) }\n end\n { :ok, _ } -> { :error, :eio, src }\n { :error, reason } -> { :error, reason, :unicode.characters_to_binary(src) }\n end\n end\n\n # If we reach this clause, there was an error while\n # processing a file.\n defp do_cp_r(_, _, _, acc) do\n acc\n end\n\n defp copy_file_mode!(src, dest) do\n src_stat = File.stat!(src)\n dest_stat = File.stat!(dest)\n File.write_stat!(dest, File.Stat.mode(File.Stat.mode(src_stat), dest_stat))\n end\n\n # Both src and dest are files.\n defp do_cp_file(src, dest, callback, acc) do\n case copy(src, { dest, [:exclusive] }) do\n { :ok, _ } ->\n copy_file_mode!(src, dest)\n [dest|acc]\n { :error, :eexist } ->\n if callback.(src, dest) do\n rm(dest)\n case copy(src, dest) do\n { :ok, _ } ->\n copy_file_mode!(src, dest)\n [dest|acc]\n { :error, reason } -> { :error, reason, :unicode.characters_to_binary(src) }\n end\n else\n acc\n end\n { :error, reason } -> { :error, reason, :unicode.characters_to_binary(src) }\n end\n end\n\n # Both src and dest are files.\n defp do_cp_link(link, src, dest, callback, acc) do\n case F.make_symlink(link, dest) do\n :ok ->\n [dest|acc]\n { :error, :eexist } ->\n if callback.(src, dest) do\n rm(dest)\n case F.make_symlink(link, dest) do\n :ok -> [dest|acc]\n { :error, reason } -> { :error, reason, :unicode.characters_to_binary(src) }\n end\n else\n acc\n end\n { :error, reason } -> { :error, reason, :unicode.characters_to_binary(src) }\n end\n end\n\n @doc \"\"\"\n Writes `content` to the file `path`. The file is created if it\n does not exist. If it exists, the previous contents are overwritten.\n Returns `:ok` if successful, or `{:error, reason}` if an error occurs.\n\n Typical error reasons are:\n\n * :enoent - A component of the file name does not exist.\n * :enotdir - A component of the file name is not a directory.\n On some platforms, enoent is returned instead.\n * :enospc - There is a no space left on the device.\n * :eacces - Missing permission for writing the file or searching one of the parent directories.\n * :eisdir - The named file is a directory.\n \"\"\"\n def write(path, content, modes \/\/ []) do\n F.write_file(path, content, modes)\n end\n\n @doc \"\"\"\n Same as `write\/3` but raises an exception if it fails, returns `:ok` otherwise.\n \"\"\"\n def write!(path, content, modes \/\/ []) do\n case F.write_file(path, content, modes) do\n :ok -> :ok\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"write to file\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Tries to delete the file `path`.\n Returns `:ok` if successful, or `{:error, reason}` if an error occurs.\n\n Typical error reasons are:\n\n * :enoent - The file does not exist.\n * :eacces - Missing permission for the file or one of its parents.\n * :eperm - The file is a directory and user is not super-user.\n * :enotdir - A component of the file name is not a directory.\n On some platforms, enoent is returned instead.\n * :einval - Filename had an improper type, such as tuple.\n\n ## Examples\n\n File.rm('file.txt')\n #=> :ok\n\n File.rm('tmp_dir\/')\n #=> {:error, :eperm}\n\n \"\"\"\n def rm(path) do\n F.delete(path)\n end\n\n @doc \"\"\"\n Same as `rm`, but raises an exception in case of failure. Otherwise `:ok`.\n \"\"\"\n def rm!(path) do\n case rm(path) do\n :ok -> :ok\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"remove file\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Tries to delete the dir at `path`.\n Returns `:ok` if successful, or `{:error, reason}` if an error occurs.\n\n ## Examples\n\n File.rddir('tmp_dir')\n #=> :ok\n\n File.rmdir('file.txt')\n #=> {:error, :enotdir}\n\n \"\"\"\n def rmdir(path) do\n F.del_dir(path)\n end\n\n @doc \"\"\"\n Same as `rmdir\/1`, but raises an exception in case of failure. Otherwise `:ok`.\n \"\"\"\n def rmdir!(path) do\n case rmdir(path) do\n :ok -> :ok\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"remove directory\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Remove files and directories recursively at the given `path`.\n Symlinks are not followed but simply removed, non existing\n files are simply ignored (i.e. doesn't make this function fail).\n\n Returns `{ :ok, files_and_directories }` with all files and\n directories removed in no specific order, `{ :error, reason }`\n otherwise.\n\n ## Examples\n\n File.rm_rf \"samples\"\n #=> { :ok, [\"samples\", \"samples\/1.txt\"] }\n\n File.rm_rf \"unknown\"\n #=> { :ok, [] }\n\n \"\"\"\n def rm_rf(path) do\n do_rm_rf(path, { :ok, [] })\n end\n\n defp do_rm_rf(path, { :ok, acc } = entry) do\n case safe_list_dir(path) do\n { :ok, files } ->\n res =\n Enum.reduce files, entry, fn(file, tuple) ->\n do_rm_rf(FN.join(path, file), tuple)\n end\n\n case res do\n { :ok, acc } ->\n case rmdir(path) do\n :ok -> { :ok, [path|acc] }\n { :error, :enoent } -> res\n reason -> { :error, reason, :unicode.characters_to_binary(path) }\n end\n reason -> { :error, reason, :unicode.characters_to_binary(path) }\n end\n { :error, reason } when reason in [:enotdir, :eio] ->\n case rm(path) do\n :ok -> { :ok, [path|acc] }\n { :error, reason } when reason in [:enoent, :enotdir] -> entry\n reason -> { :error, reason, :unicode.characters_to_binary(path) }\n end\n { :error, :enoent } -> entry\n { :error, reason } -> { :error, reason, :unicode.characters_to_binary(path) }\n end\n end\n\n defp do_rm_rf(_, reason) do\n reason\n end\n\n defp safe_list_dir(path) do\n case F.read_link(path) do\n { :ok, _ } -> { :error, :enotdir }\n _ -> F.list_dir(path)\n end\n end\n\n @doc \"\"\"\n Same as `rm_rf\/1` but raises `File.Error` in case of failures,\n otherwise the list of files or directories removed.\n \"\"\"\n def rm_rf!(path) do\n case rm_rf(path) do\n { :ok, files } -> files\n { :error, reason, _ } ->\n raise File.Error, reason: reason,\n action: \"remove files and directories recursively from\",\n path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Opens the given `path` according to the given list of modes.\n\n In order to write and read files, one must use the functions\n in the IO module. By default, a file is opened in binary mode\n which requires the functions `IO.binread`, `IO.binwrite` and\n `IO.binreadline` to interact with the file. A developer may pass\n `:utf8` as an option when opening the file and then all other\n functions from IO are available, since they work directly with\n Unicode data.\n\n The allowed modes:\n\n * `:read` - The file, which must exist, is opened for reading.\n\n * `:write` - The file is opened for writing. It is created if it does not exist.\n If the file exists, and if write is not combined with read, the file will be truncated.\n\n * `:append` - The file will be opened for writing, and it will be created if it does not exist.\n Every write operation to a file opened with append will take place at the end of the file.\n\n * `:exclusive` - The file, when opened for writing, is created if it does not exist.\n If the file exists, open will return { :error, :eexist }.\n\n * `:charlist` - When this term is given, read operations on the file will return char lists rather than binaries;\n\n * `:compressed` - Makes it possible to read or write gzip compressed files.\n The compressed option must be combined with either read or write, but not both.\n Note that the file size obtained with `stat\/1` will most probably not\n match the number of bytes that can be read from a compressed file.\n\n * `:utf8` - This option denotes how data is actually stored in the disk file and\n makes the file perform automatic translation of characters to and from utf-8.\n If data is sent to a file in a format that cannot be converted to the utf-8\n or if data is read by a function that returns data in a format that cannot cope\n with the character range of the data, an error occurs and the file will be closed.\n\n If a function is given to modes (instead of a list), it dispatches to `open\/3`.\n\n Check `http:\/\/www.erlang.org\/doc\/man\/file.html#open-2` for more information about\n other options as `read_ahead` and `delayed_write`.\n\n This function returns:\n\n * { :ok, io_device } - The file has been opened in the requested mode.\n `io_device` is actually the pid of the process which handles the file.\n This process is linked to the process which originally opened the file.\n If any process to which the io_device is linked terminates, the file will\n be closed and the process itself will be terminated. An io_device returned\n from this call can be used as an argument to the `IO` module functions.\n\n * { :error, reason } - The file could not be opened.\n\n ## Examples\n\n { :ok, file } = File.open(\"foo.tar.gz\", [:read, :compressed])\n IO.readline(file)\n File.close(file)\n\n \"\"\"\n def open(path, modes \/\/ [])\n\n def open(path, modes) when is_list(modes) do\n F.open(path, open_defaults(modes, true))\n end\n\n def open(path, function) when is_function(function) do\n open(path, [], function)\n end\n\n @doc \"\"\"\n Similar to `open\/2` but expects a function as last argument.\n\n The file is opened, given to the function as argument and\n automatically closed after the function returns, regardless\n if there was an error or not.\n\n It returns `{ :ok, function_result }` in case of success,\n `{ :error, reason }` otherwise.\n\n Do not use this function with :delayed_write option\n since automatically closing the file may fail\n (as writes are delayed).\n\n ## Examples\n\n File.open(\"file.txt\", [:read, :write], fn(file) ->\n IO.readline(file)\n end)\n\n \"\"\"\n def open(path, modes, function) do\n case open(path, modes) do\n { :ok, device } ->\n try do\n { :ok, function.(device) }\n after\n :ok = close(device)\n end\n other -> other\n end\n end\n\n @doc \"\"\"\n Same as `open\/2` but raises an error if file could not be opened.\n Returns the `io_device` otherwise.\n \"\"\"\n def open!(path, modes \/\/ []) do\n case open(path, modes) do\n { :ok, device } -> device\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"open\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Same as `open\/3` but raises an error if file could not be opened.\n Returns the function result otherwise.\n \"\"\"\n def open!(path, modes, function) do\n case open(path, modes, function) do\n { :ok, device } -> device\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"open\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Gets the current working directory. In rare circumstances, this function can\n fail on Unix. It may happen if read permission does not exist for the parent\n directories of the current directory. For this reason, returns `{ :ok, cwd }`\n in case of success, `{ :error, reason }` otherwise.\n \"\"\"\n def cwd() do\n case F.get_cwd do\n { :ok, cwd } -> { :ok, :unicode.characters_to_binary(cwd) }\n { :error, _ } = error -> error\n end\n end\n\n @doc \"\"\"\n The same as `cwd\/0`, but raises an exception if it fails.\n \"\"\"\n def cwd!() do\n case F.get_cwd do\n { :ok, cwd } -> :unicode.characters_to_binary(cwd)\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"get current working directory\"\n end\n end\n\n @doc \"\"\"\n Sets the current working directory. Returns `:ok` if successful,\n `{ :error, reason }` otherwise.\n \"\"\"\n def cd(path) do\n F.set_cwd(path)\n end\n\n @doc \"\"\"\n The same as `cd\/0`, but raises an exception if it fails.\n \"\"\"\n def cd!(path) do\n case F.set_cwd(path) do\n :ok -> :ok\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"set current working directory to\", path: :unicode.characters_to_binary(path)\n end\n end\n\n @doc \"\"\"\n Changes the current directory to the given `path`,\n executes the given function and then revert back\n to the previous path regardless if there is an exception.\n\n Raises an error if retrieving or changing the current\n directory fails.\n \"\"\"\n def cd!(path, function) do\n old = cwd!\n cd!(path)\n try do\n function.()\n after\n cd!(old)\n end\n end\n\n @doc \"\"\"\n Returns list of files in the given directory.\n\n It returns `{ :ok, [files] }` in case of success,\n `{ :error, reason }` otherwise.\n \"\"\"\n def ls(path \/\/ \".\") do\n case F.list_dir(path) do\n { :ok, file_list } -> { :ok, Enum.map file_list, :unicode.characters_to_binary(&1) }\n { :error, _ } = error -> error\n end\n end\n\n @doc \"\"\"\n The same as `ls\/1` but raises `File.Error`\n in case of an error.\n \"\"\"\n def ls!(dir \/\/ \".\") do\n case ls(dir) do\n { :ok, value } -> value\n { :error, reason } ->\n raise File.Error, reason: reason, action: \"list directory\", path: :unicode.characters_to_binary(dir)\n end\n end\n\n @doc \"\"\"\n Closes the file referenced by `io_device`. It mostly returns `:ok`, except\n for some severe errors such as out of memory.\n\n Note that if the option `:delayed_write` was used when opening the file,\n `close\/1` might return an old write error and not even try to close the file.\n See `open\/2`.\n \"\"\"\n def close(io_device) do\n F.close(io_device)\n end\n\n @doc \"\"\"\n Converts the file device into an iterator that can be\n passed into `Enum`. The device is iterated line\n by line, at the end of iteration the file is closed.\n\n This reads the file as utf-8. CHeck out `File.biniterator`\n to handle the file as a raw binary.\n\n ## Examples\n\n An example that lazily iterates a file replacing all double\n quotes per single quotes and write each line to a target file\n is shown below:\n\n { :ok, device } = File.open(\"README.md\")\n source = File.iterator(device)\n File.open \"NEWREADME.md\", [:write], fn(target) ->\n Enum.each source, fn(line) ->\n IO.write target, Regex.replace(%r\/\"\/, line, \"'\")\n end\n end\n\n \"\"\"\n def iterator(device) do\n fn(fun, acc) ->\n do_iterator(device, fun, acc)\n end\n end\n\n @doc \"\"\"\n Opens the given `file` with the given `mode` and\n returns its iterator. The returned iterator will\n fail for the same reasons as `File.open!`. Note\n that the file is opened when the iteration begins.\n \"\"\"\n def iterator!(file, mode \/\/ []) do\n fn(fun, acc) ->\n device = open!(file, mode)\n try do\n do_iterator(device, fun, acc)\n after\n F.close(device)\n end\n end\n end\n\n @doc \"\"\"\n Converts the file device into an iterator that can\n be passed into `Enum` to iterate line by line as a\n binary. Check `iterator\/1` for more information.\n \"\"\"\n def biniterator(device) do\n fn(fun, acc) ->\n do_biniterator(device, fun, acc)\n end\n end\n\n @doc \"\"\"\n Opens the given `file` with the given `mode` and\n returns its biniterator. The returned iterator will\n fail for the same reasons as `File.open!`. Note\n that the file is opened when the iteration begins.\n \"\"\"\n def biniterator!(file, mode \/\/ []) do\n fn(fun, acc) ->\n device = open!(file, mode)\n try do\n do_biniterator(device, fun, acc)\n after\n F.close(device)\n end\n end\n end\n\n ## Helpers\n\n defp open_defaults([:charlist|t], _add_binary) do\n open_defaults(t, false)\n end\n\n defp open_defaults([:utf8|t], add_binary) do\n open_defaults([{ :encoding, :utf8 }|t], add_binary)\n end\n\n defp open_defaults([h|t], add_binary) do\n [h|open_defaults(t, add_binary)]\n end\n\n defp open_defaults([], true), do: [:binary]\n defp open_defaults([], false), do: []\n\n defp do_iterator(device, acc, fun) do\n case :io.get_line(device, '') do\n :eof ->\n acc\n { :error, reason } ->\n raise File.IteratorError, reason: reason\n data ->\n do_iterator(device, fun.(data, acc), fun)\n end\n end\n\n defp do_biniterator(device, acc, fun) do\n case F.read_line(device) do\n :eof ->\n acc\n { :error, reason } ->\n raise File.IteratorError, reason: reason\n { :ok, data } ->\n do_iterator(device, fun.(data, acc), fun)\n end\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"aa9dfa0f704c617d30aa0aae84c5f2d26d08ec6d","subject":"Hide \u201cfake fork\u201d repos","message":"Hide \u201cfake fork\u201d repos\n","repos":"mirego\/mirego-open-web,mirego\/mirego-open-web","old_file":"lib\/repo\/serializer.ex","new_file":"lib\/repo\/serializer.ex","new_contents":"defmodule OpenMirego.Repo.Serializer do\n use Timex\n alias OpenMirego.Repo.Resource\n\n @hidden_repos ~w(\n heroku-buildpack-bower\n RentThis-iOS\n Feedback-iOS\n mirego-open-web\n )\n\n @deprecated_repo_description \"[Deprecated]\"\n @fork_repo_description \"[Fork]\"\n\n # Hide specific repositories\n for name <- @hidden_repos do\n def serialize(%{\"name\" => unquote(name)}) do\n %Resource{visible: false}\n end\n end\n\n # Hide it if it\u2019s not visible\n def serialize(%{\"visible\" => false}), do: %Resource{visible: false}\n\n # Hide it if it\u2019s a fork\n def serialize(%{\"fork\" => true}), do: %Resource{visible: false}\n\n # Hide it if it\u2019s a private repo\n def serialize(%{\"private\" => true}), do: %Resource{visible: false}\n\n # Hide it if it\u2019s a deprecated repo\n def serialize(%{\"description\" => @deprecated_repo_description <> _}), do: %Resource{visible: false}\n\n # Hide it if it\u2019s a fake-fork repo\n def serialize(%{\"description\" => @fork_repo_description <> _}), do: %Resource{visible: false}\n\n # Otherwise, return a resource\n def serialize(%{\"name\" => name, \"description\" => description, \"language\" => language, \"html_url\" => html_url, \"pushed_at\" => pushed_at, \"stargazers_count\" => stargazers_count}) do\n %Resource{\n name: name,\n description: sanitize_description(description),\n language: parsed_language(language),\n pretty_language: parsed_pretty_language(language),\n url: html_url,\n raw_pushed_at: pushed_at,\n pushed_at: parsed_time(pushed_at),\n stargazers_count: stargazers_count,\n visible: true\n }\n end\n\n # Remove prefix emoji shortname from description\n defp sanitize_description(nil), do: \"\"\n defp sanitize_description(description), do: Regex.replace(~r\/^:[^:]+:\\s*\/, description, \"\")\n\n defp parsed_language(\"Objective-C\"), do: \"pod\"\n defp parsed_language(\"Ruby\"), do: \"gem\"\n defp parsed_language(\"JavaScript\"), do: \"js\"\n defp parsed_language(\"CSS\"), do: \"css\"\n defp parsed_language(\"Java\"), do: \"java\"\n defp parsed_language(\"Swift\"), do: \"swift\"\n defp parsed_language(\"Shell\"), do: \"shell\"\n defp parsed_language(nil), do: \"none\"\n defp parsed_language(lang), do: lang\n\n defp parsed_pretty_language(\"Objective-C\"), do: \"Obj-C\"\n defp parsed_pretty_language(\"Ruby\"), do: \"Ruby\"\n defp parsed_pretty_language(\"JavaScript\"), do: \"JS\"\n defp parsed_pretty_language(\"CSS\"), do: \"CSS\"\n defp parsed_pretty_language(\"Java\"), do: \"Java\"\n defp parsed_pretty_language(\"Swift\"), do: \"Swift\"\n defp parsed_pretty_language(\"Shell\"), do: \"Shell\"\n defp parsed_pretty_language(nil), do: \"\"\n defp parsed_pretty_language(lang), do: lang\n\n defp parsed_time(time) do\n {:ok, date} = DateFormat.parse(time, \"{ISOz}\")\n\n date_secs = date |> Date.to_secs\n Time.now(:secs) - date_secs\n end\nend\n","old_contents":"defmodule OpenMirego.Repo.Serializer do\n use Timex\n alias OpenMirego.Repo.Resource\n\n @hidden_repos ~w(\n heroku-buildpack-bower\n RentThis-iOS\n Feedback-iOS\n mirego-open-web\n )\n\n @deprecated_repo_description \"[Deprecated]\"\n\n # Hide specific repositories\n for name <- @hidden_repos do\n def serialize(%{\"name\" => unquote(name)}) do\n %Resource{visible: false}\n end\n end\n\n # Hide it if it\u2019s not visible\n def serialize(%{\"visible\" => false}), do: %Resource{visible: false}\n\n # Hide it if it\u2019s a fork\n def serialize(%{\"fork\" => true}), do: %Resource{visible: false}\n\n # Hide it if it\u2019s a private repo\n def serialize(%{\"private\" => true}), do: %Resource{visible: false}\n\n # Hide it if it\u2019s a deprecated repo\n def serialize(%{\"description\" => @deprecated_repo_description <> _}), do: %Resource{visible: false}\n\n # Otherwise, return a resource\n def serialize(%{\"name\" => name, \"description\" => description, \"language\" => language, \"html_url\" => html_url, \"pushed_at\" => pushed_at, \"stargazers_count\" => stargazers_count}) do\n %Resource{\n name: name,\n description: sanitize_description(description),\n language: parsed_language(language),\n pretty_language: parsed_pretty_language(language),\n url: html_url,\n raw_pushed_at: pushed_at,\n pushed_at: parsed_time(pushed_at),\n stargazers_count: stargazers_count,\n visible: true\n }\n end\n\n # Remove prefix emoji shortname from description\n defp sanitize_description(nil), do: \"\"\n defp sanitize_description(description), do: Regex.replace(~r\/^:[^:]+:\\s*\/, description, \"\")\n\n defp parsed_language(\"Objective-C\"), do: \"pod\"\n defp parsed_language(\"Ruby\"), do: \"gem\"\n defp parsed_language(\"JavaScript\"), do: \"js\"\n defp parsed_language(\"CSS\"), do: \"css\"\n defp parsed_language(\"Java\"), do: \"java\"\n defp parsed_language(\"Swift\"), do: \"swift\"\n defp parsed_language(\"Shell\"), do: \"shell\"\n defp parsed_language(nil), do: \"none\"\n defp parsed_language(lang), do: lang\n\n defp parsed_pretty_language(\"Objective-C\"), do: \"Obj-C\"\n defp parsed_pretty_language(\"Ruby\"), do: \"Ruby\"\n defp parsed_pretty_language(\"JavaScript\"), do: \"JS\"\n defp parsed_pretty_language(\"CSS\"), do: \"CSS\"\n defp parsed_pretty_language(\"Java\"), do: \"Java\"\n defp parsed_pretty_language(\"Swift\"), do: \"Swift\"\n defp parsed_pretty_language(\"Shell\"), do: \"Shell\"\n defp parsed_pretty_language(nil), do: \"\"\n defp parsed_pretty_language(lang), do: lang\n\n defp parsed_time(time) do\n {:ok, date} = DateFormat.parse(time, \"{ISOz}\")\n\n date_secs = date |> Date.to_secs\n Time.now(:secs) - date_secs\n end\nend\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"Elixir"} {"commit":"8d4de37a4115c5d927e753ea9d7b8ce2cac09eac","subject":"Increment version [ci skip]","message":"Increment version [ci skip]\n","repos":"edenlabllc\/ehealth.api,edenlabllc\/ehealth.api","old_file":"mix.exs","new_file":"mix.exs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"apache-2.0","lang":"Elixir"} {"commit":"abc7636612852cb074c02c46e7acf3cac3847953","subject":"Update license to Public Domain","message":"Update license to Public Domain\n\nI will bump the Version a major version as a license change needs to be communicated clearly","repos":"arianvp\/elixir-isaac","old_file":"mix.exs","new_file":"mix.exs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"unlicense","lang":"Elixir"} {"commit":"34b8981724ba91d49d36db33165d2d1746c637c0","subject":"elixir: typo","message":"elixir: typo\n","repos":"HaliteChallenge\/Halite-II,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite-II","old_file":"airesources\/Elixir\/lib\/elixirbot\/game.ex","new_file":"airesources\/Elixir\/lib\/elixirbot\/game.ex","new_contents":"defmodule Elixirbot.Game do\n require Logger\n require Map\n\n defmodule GameMap do\n defstruct player_id: nil, width: nil, height: nil\n end\n\n defmodule Player do\n defstruct player_id: nil, ships: []\n end\n\n defmodule Ship do\n defstruct id: nil, owner: nil, x: nil, y: nil, radius: nil, health: nil, docking_status: nil, docking_progress: nil, planet: nil\n end\n\n defmodule Planet do\n defstruct id: nil, owner: nil, x: nil, y: nil, radius: nil, health: nil, docking_spots: nil, docked_ship_ids: nil, docked_ships: nil\n end\n\n def connect(name) do\n player_id = read_from_input()\n set_up_logging(name, player_id)\n [width, height] = read_ints_from_input\n Logger.info \"game size: #{width} x #{height}\"\n write_to_output(name)\n {players, planets} = fetch_map_state\n map = %GameMap{player_id: parse_int(player_id), width: width, height: height}\n prepare_game(map, players, planets)\n map\n end\n\n def prepare_game(map, players, planets) do\n # We now have 1 full minute to analyse the initial map.\n make_move(map, players, planets)\n |> Enum.join(\" \")\n |> write_to_output\n end\n\n defp read_from_input() do\n input_line = IO.gets(\"\") |> String.strip\n Logger.debug \"received: #{input_line}\"\n input_line\n end\n\n defp set_up_logging(name, player_id) do\n Logger.add_backend {LoggerFileBackend, :debug}\n Logger.configure_backend {LoggerFileBackend, :debug}, path: \"#{player_id}_#{name}.log\"\n Logger.info \"Starting new game for #{name}:#{player_id}\"\n Logger.info \"Setting up logger\"\n end\n\n def read_ints_from_input do\n read_from_input()\n |> String.split(\" \")\n |> Enum.map(fn(x) -> parse_int(x) end)\n end\n\n defp write_to_output(message) do\n message = \"#{String.strip(message)}\\n\"\n Logger.info(\"Sending: #{message}\")\n IO.puts(message)\n end\n\n def fetch_map_state do\n tokens = read_from_input() |> String.split(\" \")\n {tokens, players} = read_from_input() |> String.split(\" \") |> parse_players\n {[], planets} = tokens |> parse_planets\n {players, planets}\n end\n\n def update_map(map) do\n {players, planets} = fetch_map_state\n make_move(map, players, planets)\n |> Enum.join(\" \")\n |> write_to_output\n update_map(map)\n end\n\n def make_move(map, players, planets) do\n Logger.info(\"finding player #{map.player_id}\")\n player = Enum.find(players, fn(player) -> Logger.info(\"finding player #{inspect(player)}, #{inspect(player.player_id)} == #{inspect(map.player_id)} = #{player.player_id == map.player_id}\"); player.player_id == map.player_id end)\n Logger.info(\"found player #{inspect(player)}\")\n opponent_ships = Enum.flat_map(players, fn(player) -> if (player.player_id == map.player_id), do: [], else: player.ships end)\n Enum.map(player.ships, fn(ship) -> make_move_for_ship(ship, opponent_ships, planets) end)\n end\n\n def make_move_for_ship(ship, opponent_ships, planets) do\n Logger.info(\"making move for ship: #{inspect(ship)}\")\n \"t #{ship.id} #{Enum.random(1..7)} #{Enum.random(0..359)}\"\n end\n\n def parse_players(tokens) do\n [count_of_players|tokens] = tokens\n Logger.info \"Parsing #{count_of_players} players\"\n\n {players, tokens} = parse_players(parse_int(count_of_players), tokens)\n\n Logger.debug \"Parsed players: #{inspect(players)}\"\n {tokens, players}\n end\n\n def parse_players(0, tokens), do: {[], tokens}\n def parse_players(count_of_players, tokens) do\n [player_id|tokens] = tokens\n player_id = parse_int(player_id)\n {ships, tokens} = parse_ships(player_id, tokens)\n\n player = %Player{player_id: player_id, ships: ships}\n Logger.debug \"Parsed player: #{inspect(player)}\"\n\n {players, tokens} = parse_players(count_of_players-1, tokens)\n {players++[player], tokens}\n end\n\n def parse_ships(player_id, tokens) do\n [count_of_ships|tokens] = tokens\n\n {ships, tokens} = parse_ships(parse_int(count_of_ships), player_id, tokens)\n Logger.debug \"Parsed ships: #{inspect(ships)}\"\n\n {ships, tokens}\n end\n\n def parse_ships(0, _, tokens), do: {[], tokens}\n def parse_ships(count_of_ships, player_id, tokens) do\n [id, x, y, hp, _, _, status, planet, progress, _|tokens] = tokens\n id = parse_int(id)\n\n ship = %Ship{id: id,\n owner: player_id,\n x: parse_float(x),\n y: parse_float(y),\n radius: nil,\n health: parse_int(hp),\n docking_status: parse_int(status),\n docking_progress: parse_int(progress),\n planet: parse_int(planet)}\n Logger.debug \"Parsed ship: #{inspect(ship)}\"\n\n {ships, tokens} = parse_ships(count_of_ships-1, player_id, tokens)\n {ships++[ship], tokens}\n end\n\n def parse_planets(tokens) do\n [count_of_planets|tokens] = tokens\n planets = %{}\n\n {planets, tokens} = parse_planets(parse_int(count_of_planets), tokens)\n\n Logger.debug \"Parsed planets: #{inspect(planets)}\"\n {tokens, planets}\n end\n\n def parse_planets(0, tokens), do: {%{}, tokens}\n def parse_planets(count_of_planets, tokens) do\n [id, x, y, hp, r, docking_spots, _, _, is_owned, owner, ship_count|tokens] = tokens\n id = parse_int(id)\n owner = parse_int(owner)\n\n # Fetch the ship ids from the tokens array\n docked_ships = parse_docked_ships(parse_int(ship_count), tokens)\n\n planet = %Planet{id: id,\n x: parse_float(x),\n y: parse_float(y),\n health: parse_int(hp),\n radius: parse_float(r),\n docking_spots: parse_int(docking_spots),\n owner: owner,\n docked_ships: docked_ships}\n Logger.debug \"Parsed planet: #{inspect(planet)}\"\n\n {planets, tokens} = parse_planets(count_of_planets-1, tokens)\n {Map.merge(%{id => planet}, planets), tokens}\n end\n\n defp parse_docked_ships(0, tokens), do: {[], tokens}\n defp parse_docked_ships(ship_count, tokens) do\n [ship|tokens] = tokens\n {ships, tokens} = parse_docked_ships(ship_count-1, tokens)\n {ships++[ship], tokens}\n end\n\n defp parse_int(nil), do: nil\n defp parse_int(str) do\n str |> String.to_integer\n end\n\n defp parse_float(nil), do: nil\n defp parse_float(str) do\n str |> String.to_float\n end\nend\n","old_contents":"defmodule Elixirbot.Game do\n require Logger\n require Map\n\n defmodule GameMap do\n defstruct player_id: nil, width: nil, height: nil\n end\n\n defmodule Player do\n defstruct player_id: nil, ships: []\n end\n\n defmodule Ship do\n defstruct id: nil, owner: nil, x: nil, y: nil, radius: nil, health: nil, docking_status: nil, docking_progress: nil, planet: nil\n end\n\n defmodule Planet do\n defstruct id: nil, owner: nil, x: nil, y: nil, radius: nil, health: nil, docking_spots: nil, docked_ship_ids: nil, docked_ships: nil\n end\n\n def connect(name) do\n player_id = read_from_input()\n set_up_logging(name, player_id)\n [width, height] = read_ints_from_input\n Logger.info \"game size: #{width} x #{height}\"\n write_to_output(name)\n {players, planets} = fetch_map_state\n map = %GameMap{player_id: parse_int(player_id), width: width, height: height}\n prepare_game(map, players, planets)\n map\n end\n\n def prepare_game(map, players, planets) do\n # We now have 1 full minute to analyse the initial map.\n make_move(map, players, planets)\n |> Enum.join(\" \")\n |> write_to_output\n end\n\n defp read_from_input() do\n input_line = IO.gets(\"\") |> String.strip\n Logger.debug \"recieved: #{input_line}\"\n input_line\n end\n\n defp set_up_logging(name, player_id) do\n Logger.add_backend {LoggerFileBackend, :debug}\n Logger.configure_backend {LoggerFileBackend, :debug}, path: \"#{player_id}_#{name}.log\"\n Logger.info \"Starting new game for #{name}:#{player_id}\"\n Logger.info \"Setting up logger\"\n end\n\n def read_ints_from_input do\n read_from_input()\n |> String.split(\" \")\n |> Enum.map(fn(x) -> parse_int(x) end)\n end\n\n defp write_to_output(message) do\n message = \"#{String.strip(message)}\\n\"\n Logger.info(\"Sending: #{message}\")\n IO.puts(message)\n end\n\n def fetch_map_state do\n tokens = read_from_input() |> String.split(\" \")\n {tokens, players} = read_from_input() |> String.split(\" \") |> parse_players\n {[], planets} = tokens |> parse_planets\n {players, planets}\n end\n\n def update_map(map) do\n {players, planets} = fetch_map_state\n make_move(map, players, planets)\n |> Enum.join(\" \")\n |> write_to_output\n update_map(map)\n end\n\n def make_move(map, players, planets) do\n Logger.info(\"finding player #{map.player_id}\")\n player = Enum.find(players, fn(player) -> Logger.info(\"finding player #{inspect(player)}, #{inspect(player.player_id)} == #{inspect(map.player_id)} = #{player.player_id == map.player_id}\"); player.player_id == map.player_id end)\n Logger.info(\"found player #{inspect(player)}\")\n opponent_ships = Enum.flat_map(players, fn(player) -> if (player.player_id == map.player_id), do: [], else: player.ships end)\n Enum.map(player.ships, fn(ship) -> make_move_for_ship(ship, opponent_ships, planets) end)\n end\n\n def make_move_for_ship(ship, opponent_ships, planets) do\n Logger.info(\"making move for ship: #{inspect(ship)}\")\n \"t #{ship.id} #{Enum.random(1..7)} #{Enum.random(0..359)}\"\n end\n\n def parse_players(tokens) do\n [count_of_players|tokens] = tokens\n Logger.info \"Parsing #{count_of_players} players\"\n\n {players, tokens} = parse_players(parse_int(count_of_players), tokens)\n\n Logger.debug \"Parsed players: #{inspect(players)}\"\n {tokens, players}\n end\n\n def parse_players(0, tokens), do: {[], tokens}\n def parse_players(count_of_players, tokens) do\n [player_id|tokens] = tokens\n player_id = parse_int(player_id)\n {ships, tokens} = parse_ships(player_id, tokens)\n\n player = %Player{player_id: player_id, ships: ships}\n Logger.debug \"Parsed player: #{inspect(player)}\"\n\n {players, tokens} = parse_players(count_of_players-1, tokens)\n {players++[player], tokens}\n end\n\n def parse_ships(player_id, tokens) do\n [count_of_ships|tokens] = tokens\n\n {ships, tokens} = parse_ships(parse_int(count_of_ships), player_id, tokens)\n Logger.debug \"Parsed ships: #{inspect(ships)}\"\n\n {ships, tokens}\n end\n\n def parse_ships(0, _, tokens), do: {[], tokens}\n def parse_ships(count_of_ships, player_id, tokens) do\n [id, x, y, hp, _, _, status, planet, progress, _|tokens] = tokens\n id = parse_int(id)\n\n ship = %Ship{id: id,\n owner: player_id,\n x: parse_float(x),\n y: parse_float(y),\n radius: nil,\n health: parse_int(hp),\n docking_status: parse_int(status),\n docking_progress: parse_int(progress),\n planet: parse_int(planet)}\n Logger.debug \"Parsed ship: #{inspect(ship)}\"\n\n {ships, tokens} = parse_ships(count_of_ships-1, player_id, tokens)\n {ships++[ship], tokens}\n end\n\n def parse_planets(tokens) do\n [count_of_planets|tokens] = tokens\n planets = %{}\n\n {planets, tokens} = parse_planets(parse_int(count_of_planets), tokens)\n\n Logger.debug \"Parsed planets: #{inspect(planets)}\"\n {tokens, planets}\n end\n\n def parse_planets(0, tokens), do: {%{}, tokens}\n def parse_planets(count_of_planets, tokens) do\n [id, x, y, hp, r, docking_spots, _, _, is_owned, owner, ship_count|tokens] = tokens\n id = parse_int(id)\n owner = parse_int(owner)\n\n # Fetch the ship ids from the tokens array\n docked_ships = parse_docked_ships(parse_int(ship_count), tokens)\n\n planet = %Planet{id: id,\n x: parse_float(x),\n y: parse_float(y),\n health: parse_int(hp),\n radius: parse_float(r),\n docking_spots: parse_int(docking_spots),\n owner: owner,\n docked_ships: docked_ships}\n Logger.debug \"Parsed planet: #{inspect(planet)}\"\n\n {planets, tokens} = parse_planets(count_of_planets-1, tokens)\n {Map.merge(%{id => planet}, planets), tokens}\n end\n\n defp parse_docked_ships(0, tokens), do: {[], tokens}\n defp parse_docked_ships(ship_count, tokens) do\n [ship|tokens] = tokens\n {ships, tokens} = parse_docked_ships(ship_count-1, tokens)\n {ships++[ship], tokens}\n end\n\n defp parse_int(nil), do: nil\n defp parse_int(str) do\n str |> String.to_integer\n end\n\n defp parse_float(nil), do: nil\n defp parse_float(str) do\n str |> String.to_float\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"407a7e2cff9661578f89fb0cb60663c1bab45198","subject":"made commands easier to type.","message":"made commands easier to type.\n","repos":"Hammatt\/tougou_bot","old_file":"lib\/tag.ex","new_file":"lib\/tag.ex","new_contents":"defmodule TougouBot.Tag do\n @moduledoc \"\"\"\n A `tag` is a simple mapping from a word to some contents. \n\n Since the bot won't stay up 24\/7 we need to keep this stored as a file.\n \"\"\"\n use Alchemy.Cogs\n\n #pre-defined messages\n @tag_already \"\u3048\u30fc\u3001\u3067\u3082\u3001\u3053\u306e\u8a00\u8449\u3082\u3046\u77e5\u3066\u308b\"\n\n #at the moment, this will only remember one \"word\", \n # anything after whitespace will be dropped\n Cogs.def ntag(tag, contents) do\n case all_tags[tag] do\n nil -> \n write_new_tag(tag, contents)\n Cogs.say \"\u3042\u301c\u3001\"<>tag<>\" \u306f \"<>contents<>\"\u3001\u306a\u308b\u307b\u3069\"\n _ ->\n Cogs.say @tag_already\n end\n end\n Cogs.def ntag(tag) do\n case all_tags[tag] do\n nil ->\n Cogs.say tag<>\"\u306f\u4f55\uff1f (!ntag )\"\n _ ->\n Cogs.say @tag_already\n end\n end\n\n Cogs.def dtag(tag) do\n case all_tags[tag] do\n nil -> Cogs.say tag<>\"\u306f\u4f55\uff1f\"\n _ ->\n delete_tag(tag)\n Cogs.say \"\u306f\u3044\u3088\u3001\"<>tag<>\"\u304c\u5fd8\u308c\u3063\u305f\"\n end\n end\n\n Cogs.def tag(tag) do\n Cogs.say tag_contents(tag, all_tags)\n end\n\n # The heavy lifting #\n\n @tag_file \"tags.data\"\n\n defp write_new_tag(tag, contents) do\n case File.read(@tag_file) do\n {:ok, \"\"} -> #tags data exists but is empty\n {_, new_data} = Poison.encode(%{tag => contents})\n File.write(@tag_file, new_data)\n {:ok, old_data} -> #add to existing tags data\n {_, data} = Poison.decode(old_data)\n {_, new_data} = Poison.encode(Map.merge(%{tag => contents}, data))\n File.write(@tag_file, new_data)\n {:error, :enoent} -> #file doesn't exist, write it and call self\n IO.puts(\"tags.data not found, creating file\")\n File.write(@tag_file, \"\")\n write_new_tag(tag, contents)\n end\n end\n\n #get all of the tags as a map, remove the one, then write back.\n defp delete_tag(tag) do\n tags = all_tags\n tags = Map.drop(tags, [tag])\n {_, new_data} = Poison.encode(tags)\n File.write(@tag_file, new_data)\n end\n\n defp tag_contents(tag, tags) do\n case tags[tag] do\n nil -> tag<>\"\u306f\u4f55\uff1f\"\n contents -> contents\n end\n end\n\n defp all_tags do\n case File.read(@tag_file) do\n {:ok, \"\"} -> #there are no tags\n %{}\n {:ok, data} ->\n {_, tags} = Poison.decode(data)\n tags\n end\n end\nend","old_contents":"defmodule TougouBot.Tag do\n @moduledoc \"\"\"\n A `tag` is a simple mapping from a word to some contents. \n\n Since the bot won't stay up 24\/7 we need to keep this stored as a file.\n \"\"\"\n use Alchemy.Cogs\n\n #pre-defined messages\n @tag_already \"\u3048\u30fc\u3001\u3067\u3082\u3001\u3053\u306e\u8a00\u8449\u3082\u3046\u77e5\u3066\u308b\"\n\n #at the moment, this will only remember one \"word\", \n # anything after whitespace will be dropped\n Cogs.def newtag(tag, contents) do\n case all_tags[tag] do\n nil -> \n write_new_tag(tag, contents)\n Cogs.say \"\u3042\u301c\u3001\"<>tag<>\" \u306f \"<>contents<>\"\u3001\u306a\u308b\u307b\u3069\"\n _ ->\n Cogs.say @tag_already\n end\n end\n Cogs.def newtag(tag) do\n case all_tags[tag] do\n nil ->\n Cogs.say tag<>\"\u306f\u4f55\uff1f\"\n _ ->\n Cogs.say @tag_already\n end\n end\n\n Cogs.def deletetag(tag) do\n case all_tags[tag] do\n nil -> Cogs.say tag<>\"\u306f\u4f55\uff1f\"\n _ ->\n delete_tag(tag)\n Cogs.say \"\u306f\u3044\u3088\u3001\"<>tag<>\"\u304c\u5fd8\u308c\u3063\u305f\"\n end\n end\n\n Cogs.def tag(tag) do\n Cogs.say tag_contents(tag, all_tags)\n end\n\n # The heavy lifting #\n\n @tag_file \"tags.data\"\n\n defp write_new_tag(tag, contents) do\n case File.read(@tag_file) do\n {:ok, \"\"} -> #tags data exists but is empty\n {_, new_data} = Poison.encode(%{tag => contents})\n File.write(@tag_file, new_data)\n {:ok, old_data} -> #add to existing tags data\n {_, data} = Poison.decode(old_data)\n {_, new_data} = Poison.encode(Map.merge(%{tag => contents}, data))\n File.write(@tag_file, new_data)\n {:error, :enoent} -> #file doesn't exist, write it and call self\n IO.puts(\"tags.data not found, creating file\")\n File.write(@tag_file, \"\")\n write_new_tag(tag, contents)\n end\n end\n\n #get all of the tags as a map, remove the one, then write back.\n defp delete_tag(tag) do\n tags = all_tags\n tags = Map.drop(tags, [tag])\n {_, new_data} = Poison.encode(tags)\n File.write(@tag_file, new_data)\n end\n\n defp tag_contents(tag, tags) do\n case tags[tag] do\n nil -> tag<>\"\u306f\u4f55\uff1f\"\n contents -> contents\n end\n end\n\n defp all_tags do\n case File.read(@tag_file) do\n {:ok, \"\"} -> #there are no tags\n %{}\n {:ok, data} ->\n {_, tags} = Poison.decode(data)\n tags\n end\n end\nend","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"2c106ef8649d81ac88dd94990c66eb6f9c73f8b3","subject":"fixing issue where worker group stops restarting under rapid error conditions","message":"fixing issue where worker group stops restarting under rapid error conditions\n","repos":"koudelka\/honeydew","old_file":"lib\/honeydew\/worker_root_supervisor.ex","new_file":"lib\/honeydew\/worker_root_supervisor.ex","new_contents":"defmodule Honeydew.WorkerRootSupervisor do\n alias Honeydew.{WorkerGroupsSupervisor, WorkerStarter}\n\n def start_link(queue, %{nodes: nodes} = opts) do\n import Supervisor.Spec\n\n Honeydew.create_groups(queue)\n\n children = [supervisor(WorkerGroupsSupervisor, [queue, opts]),\n worker(WorkerStarter, [queue])]\n\n # if the worker groups supervisor shuts down due to too many groups\n # restarting (hits max intensity), we also want the WorkerStarter to die\n # so that it may restart the necessary worker groups when the groups\n # supervisor comes back up\n supervisor_opts = [strategy: :rest_for_one,\n name: Honeydew.supervisor(queue, :worker_root)]\n\n queue\n |> case do\n {:global, _} -> children ++ [supervisor(Honeydew.NodeMonitorSupervisor, [queue, nodes])]\n _ -> children\n end\n |> Supervisor.start_link(supervisor_opts)\n end\nend\n","old_contents":"defmodule Honeydew.WorkerRootSupervisor do\n alias Honeydew.{WorkerGroupsSupervisor, WorkerStarter}\n\n def start_link(queue, %{nodes: nodes} = opts) do\n import Supervisor.Spec\n\n Honeydew.create_groups(queue)\n\n children = [supervisor(WorkerGroupsSupervisor, [queue, opts]),\n worker(WorkerStarter, [queue])]\n\n supervisor_opts = [strategy: :one_for_one,\n name: Honeydew.supervisor(queue, :worker_root)]\n\n queue\n |> case do\n {:global, _} -> children ++ [supervisor(Honeydew.NodeMonitorSupervisor, [queue, nodes])]\n _ -> children\n end\n |> Supervisor.start_link(supervisor_opts)\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"acc0187ea5057c2a8e64b1d8390086262d02d6f2","subject":"and now form validation with behaviours","message":"and now form validation with behaviours\n","repos":"CrowdHailer\/Tokumei,CrowdHailer\/Tokumei","old_file":"web_form\/test\/web_form_test.exs","new_file":"web_form\/test\/web_form_test.exs","new_contents":"defprotocol WebForm.Input do\n def take(field, mount, map)\n\n def check_blank(field, raw)\nend\n\ndefmodule WebForm.Input.Text do\n defstruct [:pattern]\n\n def new(opts \\\\ []) do\n struct(__MODULE__, opts)\n end\nend\n\ndefimpl WebForm.Input, for: WebForm.Input.Text do\n def take(self, key, map) do\n {:ok, raw} = Map.fetch(map, \"#{key}\")\n WebForm.Input.check_blank(self, raw)\n |> IO.inspect\n {key, {:ok, :out}}\n end\nend\ndefimpl WebForm.Input, for: Any do\n def check_blank(self, x) do\n IO.inspect(self)\n end\nend\n\n\ndefmodule Input.Text do\n defmacro __using__(_) do\n quote do\n def take(key, options, map) do\n {:ok, raw} = Map.fetch(map, \"#{key}\")\n {key, coerce(raw, options)}\n end\n def coerce(raw, opts) do\n IO.inspect(raw)\n\n raw\n end\n defoverridable [take: 3, coerce: 2]\n end\n end\nend\n\ndefmodule MyApp.Fields do\n defmodule Email do\n use Input.Text\n\n def coerce(raw, _) do\n {:email, raw}\n end\n end\n\n def username do\n WebForm.Input.Text.new(pattern: ~r\/[a-z]+\/)\n end\nend\n\ndefmodule MyApp.SignUpForm do\n\n def validate(form) do\n validator = %{\n username: {MyApp.Fields.Email, []},\n other: MyApp.Fields.Email\n }\n\n for {key, validator} <- validators do\n case validator do\n {field, options} ->\n field.take(key, options, form)\n end\n end\n end\nend\n\n\ndefmodule WebFormTest do\n use ExUnit.Case\n doctest WebForm\n\n test \"the truth\" do\n form = %{\"username\" => \"baz\"}\n MyApp.SignUpForm.validate(form)\n |> IO.inspect\n end\nend\n","old_contents":"defprotocol WebForm.Input do\n def take(data, key, map)\nend\n\ndefmodule WebForm.Input.Text do\n defstruct [:pattern]\n\n def new(opts \\\\ []) do\n struct(__MODULE__, opts)\n end\nend\n\ndefimpl WebForm.Input, for: WebForm.Input.Text do\n def take(self, key, map) do\n {:ok, raw} = Map.fetch(map, \"#{key}\")\n # check_blank(raw)\n {key, {:ok, :out}}\n end\nend\n\ndefmodule WebForm do\n\nend\n\ndefmodule MyApp.Fields do\n def username do\n WebForm.Input.Text.new(pattern: ~r\/[a-z]+\/)\n end\nend\n\ndefmodule MyApp.SignUpForm do\n\n def validate(form) do\n validator = %{username: WebForm.Input.Text.new}\n\n for {mount, field} <- validator do\n WebForm.Input.take(field, mount, form)\n end\n end\nend\n\n\ndefmodule WebFormTest do\n use ExUnit.Case\n doctest WebForm\n\n test \"the truth\" do\n form = %{\"username\" => \"baz\"}\n MyApp.SignUpForm.validate(form)\n |> IO.inspect\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"4affad5fd4257810933d9b5bebd762dae0bd4732","subject":"Fix code style","message":"Fix code style\n","repos":"ne1ro\/argo,ne1ro\/argo","old_file":"lib\/argo\/guardian_serializer.ex","new_file":"lib\/argo\/guardian_serializer.ex","new_contents":"defmodule Argo.GuardianSerializer do\n @behaviour Guardian.Serializer\n\n alias Argo.Repo\n alias Argo.User\n\n def for_token(user = %User{}), do: {:ok, \"User:#{user.id}\"}\n def for_token(_), do: {:error, \"Unknown resource type\"}\n\n def from_token(\"User:\" <> id), do: {:ok, Repo.get(User, id)}\n def from_token(_), do: {:error, \"Unknown resource type\"}\nend\n","old_contents":"defmodule Argo.GuardianSerializer do\n @behaviour Guardian.Serializer\n\n alias Argo.Repo\n alias Argo.User\n\n def for_token(user = %User{}), do: { :ok, \"User:#{user.id}\" }\n def for_token(_), do: { :error, \"Unknown resource type\" }\n\n def from_token(\"User:\" <> id), do: { :ok, Repo.get(User, id) }\n def from_token(_), do: { :error, \"Unknown resource type\" }\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"ab48cf6573a1f26f7dba6b83a42659fe6c83a2cd","subject":"Improve first-run mock","message":"Improve first-run mock\n","repos":"rrrene\/credo,rrrene\/credo","old_file":"lib\/credo\/cli\/output\/summary.ex","new_file":"lib\/credo\/cli\/output\/summary.ex","new_contents":"defmodule Credo.CLI.Output.Summary do\n @moduledoc false\n\n # This module is responsible for printing the summary at the end of the analysis.\n\n @category_wording [\n {:consistency, \"consistency issue\", \"consistency issues\"},\n {:warning, \"warning\", \"warnings\"},\n {:refactor, \"refactoring opportunity\", \"refactoring opportunities\"},\n {:readability, \"code readability issue\", \"code readability issues\"},\n {:design, \"software design suggestion\", \"software design suggestions\"}\n ]\n @cry_for_help \"Please report incorrect results: https:\/\/github.com\/rrrene\/credo\/issues\"\n\n alias Credo.CLI.Output\n alias Credo.CLI.Output.UI\n alias Credo.Execution\n alias Credo.SourceFile\n\n def print(\n _source_files,\n %Execution{format: \"flycheck\"},\n _time_load,\n _time_run\n ) do\n nil\n end\n\n def print(_source_files, %Execution{format: \"oneline\"}, _time_load, _time_run) do\n nil\n end\n\n def print(source_files, exec, time_load, time_run) do\n issues = Execution.get_issues(exec)\n source_file_count = exec |> Execution.get_source_files() |> Enum.count()\n checks_count = count_checks(exec)\n\n UI.puts()\n UI.puts([:faint, @cry_for_help])\n UI.puts()\n UI.puts([:faint, format_time_spent(checks_count, source_file_count, time_load, time_run)])\n\n UI.puts(summary_parts(source_files, issues))\n UI.puts()\n\n print_priority_hint(exec)\n print_first_run_hint(exec)\n end\n\n defp latest_tag do\n case System.cmd(\"git\", ~w\"describe --tags --abbrev=0\") do\n {output, 0} -> String.trim(output)\n _ -> nil\n end\n end\n\n defp default_branch do\n remote_name = default_remote_name()\n\n case System.cmd(\"git\", ~w\"symbolic-ref refs\/remotes\/#{remote_name}\/HEAD\") do\n {output, 0} -> Regex.run(~r\"refs\/remotes\/#{remote_name}\/(.+)$\", output) |> Enum.at(1)\n _ -> nil\n end\n end\n\n defp default_remote_name do\n \"origin\"\n end\n\n defp latest_commit_on_default_branch do\n case System.cmd(\"git\", ~w\"rev-parse --short #{default_remote_name()}\/#{default_branch()}\") do\n {output, 0} -> String.trim(output)\n _ -> nil\n end\n end\n\n defp now do\n \"2020-12-01 19:58:09\"\n\n Calendar.strftime(DateTime.utc_now(), \"%Y-%m-%d\")\n end\n\n defp print_first_run_hint(_exec) do\n term_width = Output.term_columns()\n now = now()\n default_branch = default_branch()\n latest_commit_on_default_branch = latest_commit_on_default_branch()\n latest_tag = latest_tag()\n\n headline = \" 8< \"\n bar = String.pad_leading(\"\", div(term_width - String.length(headline), 2), \"-\")\n\n UI.puts()\n UI.puts()\n UI.puts([:magenta, :bright, \"#{bar} 8< #{bar}\"])\n UI.puts()\n UI.puts()\n\n UI.puts([\n :reset,\n :orange,\n \"\"\"\n # Where to start?\n \"\"\",\n :reset,\n \"\"\"\n\n That's a lot of issues to deal with at once.\n \"\"\",\n \"\"\"\n\n You can use `diff` to only show the issues that were introduced on this branch:\n \"\"\",\n :cyan,\n \"\"\"\n\n mix credo diff #{default_branch}\n\n \"\"\",\n :reset,\n :orange,\n \"\"\"\n ## Compare to a point in history\n \"\"\",\n :reset,\n \"\"\"\n\n You can use `diff` to only show the issues that were introduced after a certain tag or commit:\n\n \"\"\",\n :cyan,\n \" mix credo diff #{latest_tag} \",\n :faint,\n \" # use the latest tag\",\n \"\\n\\n\",\n :reset,\n :cyan,\n \" mix credo diff #{latest_commit_on_default_branch}\",\n :faint,\n \" # use the current HEAD of master\",\n \"\\n\\n\",\n :reset,\n \"\"\"\n Lastly, you can compare your working dir against this point in time:\n\n \"\"\",\n :cyan,\n \" mix credo diff --since #{now}\",\n :faint,\n \" # use the current time\",\n \"\\n\\n\",\n :reset,\n :orange,\n \"\"\"\n ## Every project is different\n \"\"\",\n :reset,\n \"\"\"\n\n This is true, especially when it comes to introducing code analysis to an existing codebase.\n Doing so should not be about following any \"best practice\" in particular, it should be about\n helping you to get to know the ropes and make the changes you want.\n \"\"\"\n ])\n\n UI.puts(\"Try the options outlined above to see which one is working for this project!\")\n end\n\n defp count_checks(exec) do\n {result, _only_matching, _ignore_matching} = Execution.checks(exec)\n\n Enum.count(result)\n end\n\n defp print_priority_hint(%Execution{min_priority: min_priority})\n when min_priority >= 0 do\n UI.puts([\n :faint,\n \"Showing priority issues: \u2191 \u2197 \u2192 (use `mix credo explain` to explain issues, `mix credo --help` for options).\"\n ])\n end\n\n defp print_priority_hint(_) do\n UI.puts([\n :faint,\n \"Use `mix credo explain` to explain issues, `mix credo --help` for options.\"\n ])\n end\n\n defp format_time_spent(check_count, source_file_count, time_load, time_run) do\n time_run = time_run |> div(10_000)\n time_load = time_load |> div(10_000)\n\n formatted_total = format_in_seconds(time_run + time_load)\n\n time_to_load = format_in_seconds(time_load)\n time_to_run = format_in_seconds(time_run)\n\n total_in_seconds =\n case formatted_total do\n \"1.0\" -> \"1 second\"\n value -> \"#{value} seconds\"\n end\n\n checks =\n if check_count == 1 do\n \"1 check\"\n else\n \"#{check_count} checks\"\n end\n\n source_files =\n if source_file_count == 1 do\n \"1 file\"\n else\n \"#{source_file_count} files\"\n end\n\n breakdown = \"#{time_to_load}s to load, #{time_to_run}s running #{checks} on #{source_files}\"\n\n \"Analysis took #{total_in_seconds} (#{breakdown})\"\n end\n\n defp format_in_seconds(t) do\n if t < 10 do\n \"0.0#{t}\"\n else\n t = div(t, 10)\n \"#{div(t, 10)}.#{rem(t, 10)}\"\n end\n end\n\n defp category_count(issues, category) do\n issues\n |> Enum.filter(&(&1.category == category))\n |> Enum.count()\n end\n\n defp summary_parts(source_files, issues) do\n parts =\n @category_wording\n |> Enum.flat_map(&summary_part(&1, issues))\n\n parts =\n parts\n |> List.update_at(Enum.count(parts) - 1, fn last_part ->\n String.replace(last_part, \", \", \"\")\n end)\n\n parts =\n if Enum.empty?(parts) do\n \"no issues\"\n else\n parts\n end\n\n [\n :green,\n \"#{scope_count(source_files)} mods\/funs, \",\n :reset,\n \"found \",\n parts,\n \".\"\n ]\n end\n\n defp summary_part({category, singular, plural}, issues) do\n color = Output.check_color(category)\n\n case category_count(issues, category) do\n 0 -> []\n 1 -> [color, \"1 #{singular}, \"]\n x -> [color, \"#{x} #{plural}, \"]\n end\n end\n\n defp scope_count(%SourceFile{} = source_file) do\n Credo.Code.prewalk(source_file, &scope_count_traverse\/2, 0)\n end\n\n defp scope_count([]), do: 0\n\n defp scope_count(source_files) when is_list(source_files) do\n source_files\n |> Enum.map(&Task.async(fn -> scope_count(&1) end))\n |> Enum.map(&Task.await\/1)\n |> Enum.reduce(&(&1 + &2))\n end\n\n @def_ops [:defmodule, :def, :defp, :defmacro]\n for op <- @def_ops do\n defp scope_count_traverse({unquote(op), _, _} = ast, count) do\n {ast, count + 1}\n end\n end\n\n defp scope_count_traverse(ast, count) do\n {ast, count}\n end\nend\n","old_contents":"defmodule Credo.CLI.Output.Summary do\n @moduledoc false\n\n # This module is responsible for printing the summary at the end of the analysis.\n\n @category_wording [\n {:consistency, \"consistency issue\", \"consistency issues\"},\n {:warning, \"warning\", \"warnings\"},\n {:refactor, \"refactoring opportunity\", \"refactoring opportunities\"},\n {:readability, \"code readability issue\", \"code readability issues\"},\n {:design, \"software design suggestion\", \"software design suggestions\"}\n ]\n @cry_for_help \"Please report incorrect results: https:\/\/github.com\/rrrene\/credo\/issues\"\n\n alias Credo.CLI.Output\n alias Credo.CLI.Output.UI\n alias Credo.Execution\n alias Credo.SourceFile\n\n def print(\n _source_files,\n %Execution{format: \"flycheck\"},\n _time_load,\n _time_run\n ) do\n nil\n end\n\n def print(_source_files, %Execution{format: \"oneline\"}, _time_load, _time_run) do\n nil\n end\n\n def print(source_files, exec, time_load, time_run) do\n issues = Execution.get_issues(exec)\n source_file_count = exec |> Execution.get_source_files() |> Enum.count()\n checks_count = count_checks(exec)\n\n UI.puts()\n UI.puts([:faint, @cry_for_help])\n UI.puts()\n UI.puts([:faint, format_time_spent(checks_count, source_file_count, time_load, time_run)])\n\n UI.puts(summary_parts(source_files, issues))\n UI.puts()\n\n print_priority_hint(exec)\n\n UI.puts(\"\"\"\n\n That's a lot of issue to deal with at once.\n\n You can use `diff` to only show the issues that were introduced on this branch.\n\n mix credo diff master\n\n You can use `diff` to only show the issues that were introduced since a certain tag or commit:\n\n # latest tag seems to be `v1.5.1`\n mix credo diff v1.5.1\n\n Lastly, you can compare your working dir against this point in time\n\n # use the current datetime\n mix credo diff --since \"2020-12-01 19:58:09\"\n\n # use the current HEAD of master\n mix credo diff 879742a\n\n Every project is different, especially when it comes to introducing code analysis.\n\n It should not be about following any \"best practice\", the linter actually has to be helping you.\n\n Try the commands above in a second terminal to see which one is working for this project!\n \"\"\")\n end\n\n defp count_checks(exec) do\n {result, _only_matching, _ignore_matching} = Execution.checks(exec)\n\n Enum.count(result)\n end\n\n defp print_priority_hint(%Execution{min_priority: min_priority})\n when min_priority >= 0 do\n UI.puts([\n :faint,\n \"Showing priority issues: \u2191 \u2197 \u2192 (use `mix credo explain` to explain issues, `mix credo --help` for options).\"\n ])\n end\n\n defp print_priority_hint(_) do\n UI.puts([\n :faint,\n \"Use `mix credo explain` to explain issues, `mix credo --help` for options.\"\n ])\n end\n\n defp format_time_spent(check_count, source_file_count, time_load, time_run) do\n time_run = time_run |> div(10_000)\n time_load = time_load |> div(10_000)\n\n formatted_total = format_in_seconds(time_run + time_load)\n\n time_to_load = format_in_seconds(time_load)\n time_to_run = format_in_seconds(time_run)\n\n total_in_seconds =\n case formatted_total do\n \"1.0\" -> \"1 second\"\n value -> \"#{value} seconds\"\n end\n\n checks =\n if check_count == 1 do\n \"1 check\"\n else\n \"#{check_count} checks\"\n end\n\n source_files =\n if source_file_count == 1 do\n \"1 file\"\n else\n \"#{source_file_count} files\"\n end\n\n breakdown = \"#{time_to_load}s to load, #{time_to_run}s running #{checks} on #{source_files}\"\n\n \"Analysis took #{total_in_seconds} (#{breakdown})\"\n end\n\n defp format_in_seconds(t) do\n if t < 10 do\n \"0.0#{t}\"\n else\n t = div(t, 10)\n \"#{div(t, 10)}.#{rem(t, 10)}\"\n end\n end\n\n defp category_count(issues, category) do\n issues\n |> Enum.filter(&(&1.category == category))\n |> Enum.count()\n end\n\n defp summary_parts(source_files, issues) do\n parts =\n @category_wording\n |> Enum.flat_map(&summary_part(&1, issues))\n\n parts =\n parts\n |> List.update_at(Enum.count(parts) - 1, fn last_part ->\n String.replace(last_part, \", \", \"\")\n end)\n\n parts =\n if Enum.empty?(parts) do\n \"no issues\"\n else\n parts\n end\n\n [\n :green,\n \"#{scope_count(source_files)} mods\/funs, \",\n :reset,\n \"found \",\n parts,\n \".\"\n ]\n end\n\n defp summary_part({category, singular, plural}, issues) do\n color = Output.check_color(category)\n\n case category_count(issues, category) do\n 0 -> []\n 1 -> [color, \"1 #{singular}, \"]\n x -> [color, \"#{x} #{plural}, \"]\n end\n end\n\n defp scope_count(%SourceFile{} = source_file) do\n Credo.Code.prewalk(source_file, &scope_count_traverse\/2, 0)\n end\n\n defp scope_count([]), do: 0\n\n defp scope_count(source_files) when is_list(source_files) do\n source_files\n |> Enum.map(&Task.async(fn -> scope_count(&1) end))\n |> Enum.map(&Task.await\/1)\n |> Enum.reduce(&(&1 + &2))\n end\n\n @def_ops [:defmodule, :def, :defp, :defmacro]\n for op <- @def_ops do\n defp scope_count_traverse({unquote(op), _, _} = ast, count) do\n {ast, count + 1}\n end\n end\n\n defp scope_count_traverse(ast, count) do\n {ast, count}\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"ef2ffea6aa6af7c321a0f1359e80c9f2888a0bc7","subject":"switch startup port","message":"switch startup port\n","repos":"CrowdHailer\/Tokumei,CrowdHailer\/Tokumei","old_file":"lib\/baobab.ex","new_file":"lib\/baobab.ex","new_contents":"defmodule RootPage do\n defmodule Header do\n use HtmlView, %{template_file: \"lib\/header.html.eex\"}\n end\n defmodule UserPartial do\n use HtmlView, %{template_file: \"lib\/user_partial.html.eex\"}\n end\n\n use HtmlView\n\n def header do\n Header.html\n end\n\n def user_partial(user) do\n UserPartial.html(user)\n end\nend\ndefmodule NotFound do\n use HtmlView, %{template_file: \"lib\/not_found.html.eex\"}\nend\ndefmodule UploadPage do\n use HtmlView, %{template_file: \"lib\/upload_page.html.eex\"}\nend\n\ndefmodule Baobab do\n defmodule RootController do\n import Plug.Conn\n\n def init(opts) do\n opts\n |> Map.put(:greeting, \"Hello\")\n |> Map.put(:other, \"

&<\/h1>\")\n |> Map.put(:users, [%{name: \"jimmey\"}, %{name: \"Briany\"}])\n end\n\n def call(conn = %{path_info: []}, opts) do\n send_resp(conn, 200, RootPage.html(opts))\n end\n def call(conn = %{path_info: [\"upload\"], method: \"GET\"}, opts) do\n send_resp(conn, 200, UploadPage.html(opts))\n end\n def call(conn = %{path_info: [\"upload\"], method: \"POST\"}, opts) do\n IO.inspect(parse(conn))\n send_resp(conn, 200, \"OP\")\n end\n\n def parse(conn, opts \\\\ []) do\n opts = Keyword.put_new(opts, :parsers, [Plug.Parsers.URLENCODED, Plug.Parsers.MULTIPART])\n Plug.Parsers.call(conn, Plug.Parsers.init(opts))\n end\n\n use Plug.Builder\n # plug Plug.Parsers, parsers: [:urlencoded, :multipart]\n plug Plug.Static,\n at: \"\/\",\n from: __DIR__\n plug :not_found\n\n def not_found(conn, _) do\n send_resp(conn, 404, NotFound.html)\n end\n end\n use Application\n\n def start(_type, _args) do\n Plug.Adapters.Cowboy.http(RootController, %{}, port: 8080)\n end\nend\n","old_contents":"defmodule RootPage do\n defmodule Header do\n use HtmlView, %{template_file: \"lib\/header.html.eex\"}\n end\n defmodule UserPartial do\n use HtmlView, %{template_file: \"lib\/user_partial.html.eex\"}\n end\n\n use HtmlView\n\n def header do\n Header.html\n end\n\n def user_partial(user) do\n UserPartial.html(user)\n end\nend\ndefmodule NotFound do\n use HtmlView, %{template_file: \"lib\/not_found.html.eex\"}\nend\ndefmodule UploadPage do\n use HtmlView, %{template_file: \"lib\/upload_page.html.eex\"}\nend\n\ndefmodule Baobab do\n defmodule RootController do\n import Plug.Conn\n\n def init(opts) do\n opts\n |> Map.put(:greeting, \"Hello\")\n |> Map.put(:other, \"

&<\/h1>\")\n |> Map.put(:users, [%{name: \"jimmey\"}, %{name: \"Briany\"}])\n end\n\n def call(conn = %{path_info: []}, opts) do\n send_resp(conn, 200, RootPage.html(opts))\n end\n def call(conn = %{path_info: [\"upload\"], method: \"GET\"}, opts) do\n send_resp(conn, 200, UploadPage.html(opts))\n end\n def call(conn = %{path_info: [\"upload\"], method: \"POST\"}, opts) do\n IO.inspect(parse(conn))\n send_resp(conn, 200, \"OP\")\n end\n\n def parse(conn, opts \\\\ []) do\n opts = Keyword.put_new(opts, :parsers, [Plug.Parsers.URLENCODED, Plug.Parsers.MULTIPART])\n Plug.Parsers.call(conn, Plug.Parsers.init(opts))\n end\n\n use Plug.Builder\n # plug Plug.Parsers, parsers: [:urlencoded, :multipart]\n plug Plug.Static,\n at: \"\/\",\n from: __DIR__\n plug :not_found\n\n def not_found(conn, _) do\n send_resp(conn, 404, NotFound.html)\n end\n end\n use Application\n\n def start(_type, _args) do\n Plug.Adapters.Cowboy.http(RootController, %{})\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"b23f2fc360f30698e788b6cefad97224a904af8d","subject":"Mix.ShellTest aware of Windows newline behavior","message":"Mix.ShellTest aware of Windows newline behavior\n","repos":"lexmag\/elixir,lexmag\/elixir,gfvcastro\/elixir,beedub\/elixir,antipax\/elixir,pedrosnk\/elixir,beedub\/elixir,kimshrier\/elixir,ggcampinho\/elixir,joshprice\/elixir,kelvinst\/elixir,kelvinst\/elixir,michalmuskala\/elixir,elixir-lang\/elixir,pedrosnk\/elixir,antipax\/elixir,gfvcastro\/elixir,ggcampinho\/elixir,kimshrier\/elixir","old_file":"lib\/mix\/test\/mix\/shell_test.exs","new_file":"lib\/mix\/test\/mix\/shell_test.exs","new_contents":"Code.require_file \"..\/test_helper.exs\", __DIR__\n\ndefmodule Mix.ShellTest do\n use MixTest.Case\n\n defp capture_io(somefunc) do\n ExUnit.CaptureIO.capture_io(somefunc) |> String.replace(\"\\r\\n\",\"\\n\")\n end\n\n defp capture_io(from, somefunc) do\n ExUnit.CaptureIO.capture_io(from, somefunc) |> String.replace(\"\\r\\n\",\"\\n\")\n end\n\n test \"shell process\" do\n Mix.shell.info \"abc\"\n Mix.shell.error \"def\"\n assert_received {:mix_shell, :info, [\"abc\"]}\n assert_received {:mix_shell, :error, [\"def\"]}\n\n send self, {:mix_shell_input, :prompt, \"world\"}\n assert Mix.shell.prompt(\"hello?\") == \"world\"\n assert_received {:mix_shell, :prompt, [\"hello?\"]}\n\n send self, {:mix_shell_input, :yes?, true}\n assert Mix.shell.yes?(\"hello?\")\n assert_received {:mix_shell, :yes?, [\"hello?\"]}\n\n assert Mix.shell.cmd(\"echo first\") == 0\n assert_received {:mix_shell, :run, [\"first\" <> os_newline]}\n end\n\n test \"shell io\" do\n Mix.shell Mix.Shell.IO\n\n assert capture_io(fn -> Mix.shell.info \"abc\" end) ==\n \"abc\\n\"\n\n assert capture_io(:stderr, fn -> Mix.shell.error \"def\" end) ==\n (IO.ANSI.escape \"%{red,bright}def\") <> \"\\n\"\n\n assert capture_io(\"world\", fn -> assert Mix.shell.prompt(\"hello?\") == \"world\" end) ==\n \"hello? \"\n\n assert capture_io(\"Yes\", fn -> assert Mix.shell.yes?(\"hello?\") end) ==\n \"hello? [Yn] \"\n\n assert capture_io(fn -> assert Mix.shell.cmd(\"echo first\") == 0 end) ==\n \"first\\n\"\n end\n\n test \"shell cmd supports expressions\" do\n Mix.shell Mix.Shell.IO\n\n assert (capture_io(fn ->\n assert Mix.shell.cmd(\"echo first && echo second\") == 0\n end) |> String.replace(\" \\n\", \"\\n\")) == \"first\\nsecond\\n\"\n end\n\n teardown do\n Mix.shell(Mix.Shell.Process)\n :ok\n end\n\n defp os_newline do\n case :os.type do\n {:win32, _} -> \"\\r\\n\"\n _ -> \"\\n\"\n end\n end\nend\n","old_contents":"Code.require_file \"..\/test_helper.exs\", __DIR__\n\ndefmodule Mix.ShellTest do\n use MixTest.Case\n\n defp capture_io(somefunc) do\n ExUnit.CaptureIO.capture_io(somefunc) |> String.replace(\"\\r\\n\",\"\\n\")\n end\n\n defp capture_io(from, somefunc) do\n ExUnit.CaptureIO.capture_io(from, somefunc) |> String.replace(\"\\r\\n\",\"\\n\")\n end\n\n test \"shell process\" do\n Mix.shell.info \"abc\"\n Mix.shell.error \"def\"\n assert_received {:mix_shell, :info, [\"abc\"]}\n assert_received {:mix_shell, :error, [\"def\"]}\n\n send self, {:mix_shell_input, :prompt, \"world\"}\n assert Mix.shell.prompt(\"hello?\") == \"world\"\n assert_received {:mix_shell, :prompt, [\"hello?\"]}\n\n send self, {:mix_shell_input, :yes?, true}\n assert Mix.shell.yes?(\"hello?\")\n assert_received {:mix_shell, :yes?, [\"hello?\"]}\n\n assert Mix.shell.cmd(\"echo first\") == 0\n assert_received {:mix_shell, :run, [\"first\\n\"]}\n end\n\n test \"shell io\" do\n Mix.shell Mix.Shell.IO\n\n assert capture_io(fn -> Mix.shell.info \"abc\" end) ==\n \"abc\\n\"\n\n assert capture_io(:stderr, fn -> Mix.shell.error \"def\" end) ==\n (IO.ANSI.escape \"%{red,bright}def\") <> \"\\n\"\n\n assert capture_io(\"world\", fn -> assert Mix.shell.prompt(\"hello?\") == \"world\" end) ==\n \"hello? \"\n\n assert capture_io(\"Yes\", fn -> assert Mix.shell.yes?(\"hello?\") end) ==\n \"hello? [Yn] \"\n\n assert capture_io(fn -> assert Mix.shell.cmd(\"echo first\") == 0 end) ==\n \"first\\n\"\n end\n\n test \"shell cmd supports expressions\" do\n Mix.shell Mix.Shell.IO\n\n assert capture_io(fn ->\n assert Mix.shell.cmd(\"echo first && echo second\") == 0\n end) == \"first\\nsecond\\n\"\n end\n\n teardown do\n Mix.shell(Mix.Shell.Process)\n :ok\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"25e25adcedc9f70e44a45593252cfeff71a96791","subject":"Formatting fix.","message":"Formatting fix.\n","repos":"FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os","old_file":"farmbot_os\/lib\/farmbot_os\/configurator\/captive_dns.ex","new_file":"farmbot_os\/lib\/farmbot_os\/configurator\/captive_dns.ex","new_contents":"defmodule FarmbotOS.Configurator.CaptiveDNS do\n use GenServer\n alias __MODULE__, as: State\n\n defstruct [:dns_socket, :dns_port, :ifname]\n\n def start_link(ifname, port) do\n GenServer.start_link(__MODULE__, [ifname, port])\n end\n\n @impl GenServer\n def init([ifname, port]) do\n send(self(), :open_dns)\n # use charlist here because :inet module works with charlists\n {:ok, %State{dns_port: port, ifname: to_charlist(ifname)}}\n end\n\n @impl GenServer\n # open a UDP socket on port 53\n def handle_info(:open_dns, state) do\n case :gen_udp.open(state.dns_port, [:binary, active: true, reuseaddr: true]) do\n {:ok, socket} ->\n {:noreply, %State{state | dns_socket: socket}}\n\n error ->\n {:stop, error, state}\n end\n end\n\n # binary dns message from the socket\n def handle_info(\n {:udp, socket, ip, port, packet},\n %{dns_socket: socket} = state\n ) do\n record = DNS.Record.decode(packet)\n {answers, state} = handle_dns(record.qdlist, [], state)\n response = DNS.Record.encode(%{record | anlist: answers})\n _ = :gen_udp.send(socket, ip, port, response)\n {:noreply, state}\n end\n\n # recursively check for dns queries, respond to each of them with the local ip address.\n\n # respond to `a` with our current ip address\n defp handle_dns(\n [%{type: :a} = q | rest],\n answers,\n state\n ) do\n ifname = state.ifname\n {:ok, interfaces} = :inet.getifaddrs()\n {^ifname, ifinfo} = List.keyfind(interfaces, ifname, 0)\n\n addr =\n Enum.find_value(ifinfo, fn\n {:addr, {_, _, _, _} = ipv4_addr} -> ipv4_addr\n _ -> false\n end)\n\n answer = make_record(q.domain, q.type, 120, addr)\n handle_dns(rest, [answer | answers], state)\n end\n\n # stop recursing when qdlist is fully enumerated\n defp handle_dns([_misc | rest], answers, state) do\n handle_dns(rest, answers, state)\n end\n\n # stop recursing when qdlist is fully enumerated\n defp handle_dns([], answers, state) do\n # IO.inspect(answers, label: \"==== DNS ANSWERS\")\n # IO.inspect(answers, label: \"==== DNS STATE\")\n {Enum.reverse(answers), state}\n end\n\n defp make_record(domain, type, ttl, data) do\n %DNS.Resource{\n domain: domain,\n class: :in,\n type: type,\n ttl: ttl,\n data: data\n }\n end\nend\n\nFarmbotOS.Configurator.CaptiveDNS.start_link(\"lo0\", 4040)\n","old_contents":"defmodule FarmbotOS.Configurator.CaptiveDNS do\n use GenServer\n alias __MODULE__, as: State\n\n defstruct [:dns_socket, :dns_port, :ifname]\n\n def start_link(ifname, port) do\n GenServer.start_link(__MODULE__, [ifname, port])\n end\n\n @impl GenServer\n def init([ifname, port]) do\n send(self(), :open_dns)\n # use charlist here because :inet module works with charlists\n {:ok, %State{dns_port: port, ifname: to_charlist(ifname)}}\n end\n\n @impl GenServer\n # open a UDP socket on port 53\n def handle_info(:open_dns, state) do\n case :gen_udp.open(state.dns_port, [:binary, active: true, reuseaddr: true]) do\n {:ok, socket} ->\n {:noreply, %State{state | dns_socket: socket}}\n\n error ->\n {:stop, error, state}\n end\n end\n\n # binary dns message from the socket\n def handle_info(\n {:udp, socket, ip, port, packet},\n %{dns_socket: socket} = state\n ) do\n record = DNS.Record.decode(packet)\n {answers, state} = handle_dns(record.qdlist, [], state)\n response = DNS.Record.encode(%{record | anlist: answers})\n _ = :gen_udp.send(socket, ip, port, response)\n {:noreply, state}\n end\n\n # recursively check for dns queries, respond to each of them with the local ip address.\n\n # respond to `a` with our current ip address\n defp handle_dns(\n [%{type: :a} = q | rest],\n answers,\n state\n ) do\n ifname = state.ifname\n {:ok, interfaces} = :inet.getifaddrs()\n {^ifname, ifinfo} = List.keyfind(interfaces, ifname, 0)\n\n addr =\n Enum.find_value(ifinfo, fn\n {:addr, {_, _, _, _} = ipv4_addr} -> ipv4_addr\n _ -> false\n end)\n\n answer = make_record(q.domain, q.type, 120, addr)\n handle_dns(rest, [answer | answers], state)\n end\n\n # stop recursing when qdlist is fully enumerated\n defp handle_dns([_misc | rest], answers, state) do\n handle_dns(rest, answers, state)\n end\n\n # stop recursing when qdlist is fully enumerated\n defp handle_dns([], answers, state) do\n # IO.inspect(answers, label: \"==== DNS ANSWERS\")\n # IO.inspect(answers, label: \"==== DNS STATE\")\n {Enum.reverse(answers), state}\n end\n\n defp make_record(domain, type, ttl, data) do\n %DNS.Resource{\n domain: domain,\n class: :in,\n type: type,\n ttl: ttl,\n data: data\n }\n end\nend\nFarmbotOS.Configurator.CaptiveDNS.start_link(\"lo0\", 4040)\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"f0ac76c45a08fa84ad868022e65bc5916bfebbd2","subject":"Bump timeout on cookie tests","message":"Bump timeout on cookie tests\n","repos":"bitwalker\/distillery,bitwalker\/distillery","old_file":"test\/distillery_cookies_test.exs","new_file":"test\/distillery_cookies_test.exs","new_contents":"defmodule Distillery.Cookies.Test do\n use ExUnit.Case, async: true\n use PropCheck\n\n @tag timeout: 60_000 * 5\n property \"generated cookies are always valid\", [:noshrink, :quiet] do\n numtests(100, forall c <- Distillery.Cookies.generate() do\n is_valid_cookie(c)\n end)\n end\n\n defp is_valid_cookie(x) when is_atom(x) do\n str = Atom.to_string(x)\n chars = String.to_charlist(str)\n with false <- String.contains?(str, [\"-\", \"+\", \"'\", \"\\\"\", \"\\\\\", \"#\"]),\n false <- Enum.any?(chars, fn b -> not (b >= ?! && b <= ?~) end),\n 64 <- byte_size(str),\n true <- is_parsed_by_command_line(str) do\n true\n else\n _ -> false\n end\n end\n defp is_valid_cookie(_x), do: false\n\n defp is_parsed_by_command_line(cookie) do\n case System.cmd(\"erl\", [\"-hidden\", \"-setcookie\", cookie, \"-noshell\", \"-s\", \"init\", \"stop\"]) do\n {_, 0} -> true\n _ -> false\n end\n end\nend\n","old_contents":"defmodule Distillery.Cookies.Test do\n use ExUnit.Case, async: true\n use PropCheck\n\n @tag timeout: 180_000\n property \"generated cookies are always valid\", [:noshrink, :quiet] do\n numtests(100, forall c <- Distillery.Cookies.generate() do\n is_valid_cookie(c)\n end)\n end\n\n defp is_valid_cookie(x) when is_atom(x) do\n str = Atom.to_string(x)\n chars = String.to_charlist(str)\n with false <- String.contains?(str, [\"-\", \"+\", \"'\", \"\\\"\", \"\\\\\", \"#\"]),\n false <- Enum.any?(chars, fn b -> not (b >= ?! && b <= ?~) end),\n 64 <- byte_size(str),\n true <- is_parsed_by_command_line(str) do\n true\n else\n _ -> false\n end\n end\n defp is_valid_cookie(_x), do: false\n\n defp is_parsed_by_command_line(cookie) do\n case System.cmd(\"erl\", [\"-hidden\", \"-setcookie\", cookie, \"-noshell\", \"-s\", \"init\", \"stop\"]) do\n {_, 0} -> true\n _ -> false\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"754f4db314063c114f4320d6e4733677c09cb454","subject":"fix: import SMTP config","message":"fix: import SMTP config\n","repos":"ckruse\/wwwtech.de,ckruse\/wwwtech.de,ckruse\/wwwtech.de","old_file":"config\/prod.exs","new_file":"config\/prod.exs","new_contents":"use Mix.Config\n\n# For production, we configure the host to read the PORT\n# from the system environment. Therefore, you will need\n# to set PORT=80 before running your server.\n#\n# You should also configure the url host to something\n# meaningful, we use this information when generating URLs.\n#\n# Finally, we also include the path to a manifest\n# containing the digested version of static files. This\n# manifest is generated by the mix phoenix.digest task\n# which you typically run after static files are built.\nconfig :wwwtech, Wwwtech.Endpoint,\n http: [ip: {127,0,0,1}, port: 4000],\n url: [scheme: \"https\", host: \"wwwtech.de\", port: 443],\n force_ssl: [rewrite_on: [:x_forwarded_proto]],\n cache_static_manifest: \"priv\/static\/manifest.json\"\n\n# Do not print debug messages in production\nconfig :logger, backends: [{LoggerFileBackend, :out_log}]\nconfig :logger, :out_log,\n path: \"log\/std.log\",\n level: :info\n\n\nconfig :wwwtech, storage_path: \"\/home\/ckruse\/pictures_wwwtech\"\nconfig :wwwtech, cache_path: \"\/home\/ckruse\/cache_wwwtech\"\n\n# ## SSL Support\n#\n# To get SSL working, you will need to add the `https` key\n# to the previous section and set your `:url` port to 443:\n#\n# config :wwwtech, Wwwtech.Endpoint,\n# ...\n# url: [host: \"example.com\", port: 443],\n# https: [port: 443,\n# keyfile: System.get_env(\"SOME_APP_SSL_KEY_PATH\"),\n# certfile: System.get_env(\"SOME_APP_SSL_CERT_PATH\")]\n#\n# Where those two env variables return an absolute path to\n# the key and cert in disk or a relative path inside priv,\n# for example \"priv\/ssl\/server.key\".\n#\n# We also recommend setting `force_ssl`, ensuring no data is\n# ever sent via http, always redirecting to https:\n#\n# config :wwwtech, Wwwtech.Endpoint,\n# force_ssl: [hsts: true]\n#\n# Check `Plug.SSL` for all available options in `force_ssl`.\n\n# ## Using releases\n#\n# If you are doing OTP releases, you need to instruct Phoenix\n# to start the server for all endpoints:\n#\n# config :phoenix, :serve_endpoints, true\n#\n# Alternatively, you can configure exactly which server to\n# start per endpoint:\n#\n# config :wwwtech, Wwwtech.Endpoint, server: true\n#\n# You will also need to set the application root to `.` in order\n# for the new static assets to be served after a hot upgrade:\n#\n# config :wwwtech, Wwwtech.Endpoint, root: \".\"\n\n# Finally import the config\/prod.secret.exs\n# which should be versioned separately.\n\nimport_config \"smtp.exs\"\nimport_config \"prod.secret.exs\"\n","old_contents":"use Mix.Config\n\n# For production, we configure the host to read the PORT\n# from the system environment. Therefore, you will need\n# to set PORT=80 before running your server.\n#\n# You should also configure the url host to something\n# meaningful, we use this information when generating URLs.\n#\n# Finally, we also include the path to a manifest\n# containing the digested version of static files. This\n# manifest is generated by the mix phoenix.digest task\n# which you typically run after static files are built.\nconfig :wwwtech, Wwwtech.Endpoint,\n http: [ip: {127,0,0,1}, port: 4000],\n url: [scheme: \"https\", host: \"wwwtech.de\", port: 443],\n force_ssl: [rewrite_on: [:x_forwarded_proto]],\n cache_static_manifest: \"priv\/static\/manifest.json\"\n\n# Do not print debug messages in production\nconfig :logger, backends: [{LoggerFileBackend, :out_log}]\nconfig :logger, :out_log,\n path: \"log\/std.log\",\n level: :info\n\n\nconfig :wwwtech, storage_path: \"\/home\/ckruse\/pictures_wwwtech\"\nconfig :wwwtech, cache_path: \"\/home\/ckruse\/cache_wwwtech\"\n\n# ## SSL Support\n#\n# To get SSL working, you will need to add the `https` key\n# to the previous section and set your `:url` port to 443:\n#\n# config :wwwtech, Wwwtech.Endpoint,\n# ...\n# url: [host: \"example.com\", port: 443],\n# https: [port: 443,\n# keyfile: System.get_env(\"SOME_APP_SSL_KEY_PATH\"),\n# certfile: System.get_env(\"SOME_APP_SSL_CERT_PATH\")]\n#\n# Where those two env variables return an absolute path to\n# the key and cert in disk or a relative path inside priv,\n# for example \"priv\/ssl\/server.key\".\n#\n# We also recommend setting `force_ssl`, ensuring no data is\n# ever sent via http, always redirecting to https:\n#\n# config :wwwtech, Wwwtech.Endpoint,\n# force_ssl: [hsts: true]\n#\n# Check `Plug.SSL` for all available options in `force_ssl`.\n\n# ## Using releases\n#\n# If you are doing OTP releases, you need to instruct Phoenix\n# to start the server for all endpoints:\n#\n# config :phoenix, :serve_endpoints, true\n#\n# Alternatively, you can configure exactly which server to\n# start per endpoint:\n#\n# config :wwwtech, Wwwtech.Endpoint, server: true\n#\n# You will also need to set the application root to `.` in order\n# for the new static assets to be served after a hot upgrade:\n#\n# config :wwwtech, Wwwtech.Endpoint, root: \".\"\n\n# Finally import the config\/prod.secret.exs\n# which should be versioned separately.\nimport_config \"prod.secret.exs\"\n","returncode":0,"stderr":"","license":"agpl-3.0","lang":"Elixir"} {"commit":"6f0088e590d788ba4ba5668b6fdefe50b05f318e","subject":"Use SSL for database","message":"Use SSL for database\n","repos":"danbee\/chess,danbee\/chess,danbee\/chess","old_file":"config\/prod.exs","new_file":"config\/prod.exs","new_contents":"use Mix.Config\n\nconfig :chess, ChessWeb.Endpoint,\n http: [port: {:system, \"PORT\"}],\n url: [host: \"localhost\", port: {:system, \"PORT\"}],\n cache_static_manifest: \"priv\/static\/cache_manifest.json\",\n server: true,\n root: \".\/assets\",\n version: Application.spec(:myapp, :vsn),\n secret_key_base: \"${SECRET_KEY_BASE}\"\n\nconfig :chess, Chess.Repo,\n adapter: Ecto.Adapters.Postgres,\n url: \"${DATABASE_URL}\",\n database: \"\",\n ssl: true,\n pool_size: 1\n","old_contents":"use Mix.Config\n\nconfig :chess, ChessWeb.Endpoint,\n http: [port: {:system, \"PORT\"}],\n url: [host: \"localhost\", port: {:system, \"PORT\"}],\n cache_static_manifest: \"priv\/static\/cache_manifest.json\",\n server: true,\n root: \".\/assets\",\n version: Application.spec(:myapp, :vsn),\n secret_key_base: \"${SECRET_KEY_BASE}\"\n\nconfig :chess, Chess.Repo,\n adapter: Ecto.Adapters.Postgres,\n url: \"${DATABASE_URL}\",\n database: \"\",\n pool_size: 1\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"787e31bfa654f49b5bd0591c426dab19f36fad06","subject":"Ugh, missed rename in refactor, thanks @keathley!","message":"Ugh, missed rename in refactor, thanks @keathley!","repos":"fcapovilla\/open_pantry,bglusman\/open_pantry,openpantry\/open_pantry,bglusman\/open_pantry,MasbiaSoupKitchenNetwork\/open_pantry,fcapovilla\/open_pantry,openpantry\/open_pantry,MasbiaSoupKitchenNetwork\/open_pantry,MasbiaSoupKitchenNetwork\/open_pantry,openpantry\/open_pantry,fcapovilla\/open_pantry,bglusman\/open_pantry,MasbiaSoupKitchenNetwork\/open_pantry,openpantry\/open_pantry,fcapovilla\/open_pantry","old_file":"config\/test.exs","new_file":"config\/test.exs","new_contents":"use Mix.Config\n\ndefmodule Ownership do\n def timeout do\n try do\n String.to_integer(System.get_env(\"DB_TIMEOUT\"))\n rescue\n ArgumentError -> 25_000\n end\n end\nend\n\n# We don't run a server during test. If one is required,\n# you can enable the server option below.\nconfig :open_pantry, OpenPantry.Web.Endpoint,\n http: [port: 4001],\n server: true\n\nconfig :open_pantry, :sql_sandbox, true\n\n# Print only warnings and errors during test\nconfig :logger, level: :warn\n\n# Configure your database\nconfig :open_pantry, OpenPantry.Repo,\n adapter: Ecto.Adapters.Postgres,\n types: OpenPantry.PostgresTypes,\n username: \"postgres\",\n password: \"postgres\",\n database: \"open_pantry_test\",\n hostname: \"localhost\",\n ownership_timeout: Ownership.timeout,\n pool: Ecto.Adapters.SQL.Sandbox\n","old_contents":"use Mix.Config\n\ndefmodule Ownership do\n def timeout do\n try do\n String.to_integer(System.get_env(\"DB_TIMEOUT\"))\n rescue\n ArgumentError -> 25_000\n end\n end\nend\n\n# We don't run a server during test. If one is required,\n# you can enable the server option below.\nconfig :open_pantry, OpenPantry.Endpoint,\n http: [port: 4001],\n server: true\n\nconfig :open_pantry, :sql_sandbox, true\n\n# Print only warnings and errors during test\nconfig :logger, level: :warn\n\n# Configure your database\nconfig :open_pantry, OpenPantry.Repo,\n adapter: Ecto.Adapters.Postgres,\n types: OpenPantry.PostgresTypes,\n username: \"postgres\",\n password: \"postgres\",\n database: \"open_pantry_test\",\n hostname: \"localhost\",\n ownership_timeout: Ownership.timeout,\n pool: Ecto.Adapters.SQL.Sandbox\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"93ff190fbc1f84d083e3be91b6e358db9820bfeb","subject":"Run dialog tests only if the driver supports it","message":"Run dialog tests only if the driver supports it\n","repos":"jontonsoup\/hound,manukall\/hound,lowks\/hound,lowks\/hound,manukall\/hound,esbullington\/hound,HashNuke\/hound,esbullington\/hound,HashNuke\/hound,jontonsoup\/hound,oivoodoo\/hound,oivoodoo\/hound","old_file":"test\/json_driver\/dialog_test.exs","new_file":"test\/json_driver\/dialog_test.exs","new_contents":"defmodule DialogTest do\n use ExUnit.Case\n use Hound.Helpers\n\n if Hound.InternalHelpers.driver_supports?(\"dialog_text\") do\n\n hound_session\n\n test \"Get dialog text\" do\n navigate_to \"http:\/\/localhost:9090\/page1.html\"\n execute_script(\"alert('hello')\")\n assert dialog_text() == \"hello\"\n end\n\n\n test \"Dismiss dialog\" do\n navigate_to \"http:\/\/localhost:9090\/page1.html\"\n execute_script(\"return window.isItReal = confirm('Is it true?')\")\n dismiss_dialog()\n assert execute_script(\"return window.isItReal\") == false\n end\n\n\n test \"Accept dialog\" do\n navigate_to \"http:\/\/localhost:9090\/page1.html\"\n execute_script(\"return window.isItReal = confirm('Is it true?')\")\n accept_dialog()\n assert execute_script(\"return window.isItReal\") == true\n end\n\n\n test \"Input into prompt\" do\n navigate_to \"http:\/\/localhost:9090\/page1.html\"\n execute_script(\"return window.isItReal = prompt('Is it true?')\")\n input_into_prompt(\"Yes it is\")\n accept_dialog()\n assert execute_script(\"return window.isItReal\") == \"Yes it is\"\n end\n\n end\nend\n","old_contents":"defmodule DialogTest do\n use ExUnit.Case\n use Hound.Helpers\n\n hound_session\n\n test \"Get dialog text\" do\n if Hound.InternalHelpers.driver_supports?(\"dialog_text\") do\n navigate_to \"http:\/\/localhost:9090\/page1.html\"\n execute_script(\"alert('hello')\")\n assert dialog_text() == \"hello\"\n else\n assert true\n end\n end\n\n\n test \"Dismiss dialog\" do\n if Hound.InternalHelpers.driver_supports?(\"dismiss_dialog\") do\n navigate_to \"http:\/\/localhost:9090\/page1.html\"\n execute_script(\"return window.isItReal = confirm('Is it true?')\")\n dismiss_dialog()\n assert execute_script(\"return window.isItReal\") == false\n else\n assert true\n end\n end\n\n\n test \"Accept dialog\" do\n if Hound.InternalHelpers.driver_supports?(\"accept_dialog\") do\n navigate_to \"http:\/\/localhost:9090\/page1.html\"\n execute_script(\"return window.isItReal = confirm('Is it true?')\")\n accept_dialog()\n assert execute_script(\"return window.isItReal\") == true\n else\n assert true\n end\n end\n\n\n test \"Input into prompt\" do\n if Hound.InternalHelpers.driver_supports?(\"input_into_prompt\") do\n navigate_to \"http:\/\/localhost:9090\/page1.html\"\n execute_script(\"return window.isItReal = prompt('Is it true?')\")\n input_into_prompt(\"Yes it is\")\n accept_dialog()\n assert execute_script(\"return window.isItReal\") == \"Yes it is\"\n else\n assert true\n end\n end\n\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"156b81957f6fb0e3a5abc4c8d125255f1bb9d802","subject":"Fix init line","message":"Fix init line\n","repos":"bors-ng\/bors-ng,bors-ng\/bors-ng,bors-ng\/bors-ng","old_file":"apps\/bors_github\/lib\/github\/server.ex","new_file":"apps\/bors_github\/lib\/github\/server.ex","new_contents":"defmodule BorsNG.GitHub.Server do\n use GenServer\n\n @moduledoc \"\"\"\n Provides a real connection to GitHub's REST API.\n This doesn't currently do rate limiting, but it will.\n \"\"\"\n\n def start_link do\n GenServer.start_link(__MODULE__, :ok, name: BorsNG.GitHub)\n end\n\n @installation_content_type \"application\/vnd.github.machine-man-preview+json\"\n @content_type_raw \"application\/vnd.github.v3.raw\"\n @content_type \"application\/vnd.github.v3+json\"\n\n @type tconn :: BorsNG.GitHub.tconn\n @type ttoken :: BorsNG.GitHub.ttoken\n @type trepo :: BorsNG.GitHub.trepo\n @type tpr :: BorsNG.GitHub.tpr\n\n @typedoc \"\"\"\n The token cache.\n \"\"\"\n @type ttokenreg :: %{number => {binary, number}}\n\n @spec config() :: keyword\n defp config do\n Application.get_env(:bors_github, BorsNG.GitHub.Server)\n end\n\n @spec site() :: bitstring\n defp site do\n Application.get_env(:bors_github, :site)\n end\n\n def init(:ok) do\n {:ok, %{}}\n end\n\n def handle_call({type, {{_, _} = token, repo_xref}, args}, _from, _state) do\n {token, state} = raw_token!(token, %{})\n res = do_handle_call(type, {token, repo_xref}, args)\n {:reply, res, state}\n end\n\n def handle_call({type, {_, _} = token, args}, _from, _state) do\n {token, state} = raw_token!(token, %{})\n res = do_handle_call(type, token, args)\n {:reply, res, state}\n end\n\n def do_handle_call(:get_pr, repo_conn, {pr_xref}) do\n case get!(repo_conn, \"pulls\/#{pr_xref}\") do\n %{body: raw, status_code: 200} ->\n pr = raw\n |> Poison.decode!()\n |> BorsNG.GitHub.Pr.from_json!()\n {:ok, pr}\n e ->\n {:error, :get_pr, e.status_code, pr_xref}\n end\n end\n\n def do_handle_call(:get_open_prs, {{:raw, token}, repo_xref}, {}) do\n {:ok, get_open_prs_!(\n token,\n \"#{site()}\/repositories\/#{repo_xref}\/pulls?state=open\",\n [])}\n end\n\n def do_handle_call(:push, repo_conn, {sha, to}) do\n repo_conn\n |> patch!(\"git\/refs\/heads\/#{to}\", Poison.encode!(%{ \"sha\": sha }))\n |> case do\n %{body: _, status_code: 200} ->\n {:ok, sha}\n _ ->\n {:error, :push}\n end\n end\n\n def do_handle_call(:get_branch, repo_conn, {branch}) do\n case get!(repo_conn, \"branches\/#{branch}\") do\n %{body: raw, status_code: 200} ->\n r = Poison.decode!(raw)[\"commit\"]\n {:ok, %{commit: r[\"sha\"], tree: r[\"commit\"][\"tree\"][\"sha\"]}}\n _ ->\n {:error, :get_branch}\n end\n end\n\n def do_handle_call(:delete_branch, repo_conn, {branch}) do\n case delete!(repo_conn, \"git\/refs\/heads\/#{branch}\") do\n %{status_code: 204} ->\n :ok\n _ ->\n {:error, :delete_branch}\n end\n end\n\n def do_handle_call(:merge_branch, repo_conn, {%{\n from: from,\n to: to,\n commit_message: commit_message}}) do\n msg = %{ \"base\": to, \"head\": from, \"commit_message\": commit_message }\n repo_conn\n |> post!(\"merges\", Poison.encode!(msg))\n |> case do\n %{body: raw, status_code: 201} ->\n data = Poison.decode!(raw)\n res = %{\n commit: data[\"sha\"],\n tree: data[\"commit\"][\"tree\"][\"sha\"]\n }\n {:ok, res}\n %{status_code: 409} ->\n {:ok, :conflict}\n _ ->\n {:error, :merge_branch}\n end\n end\n\n def do_handle_call(:synthesize_commit, repo_conn, {%{\n branch: branch,\n tree: tree,\n parents: parents,\n commit_message: commit_message}}) do\n msg = %{ \"parents\": parents, \"tree\": tree, \"message\": commit_message }\n repo_conn\n |> post!(\"git\/commits\", Poison.encode!(msg))\n |> case do\n %{body: raw, status_code: 201} ->\n sha = Poison.decode!(raw)[\"sha\"]\n do_handle_call(:force_push, repo_conn, {sha, branch})\n _ ->\n {:error, :synthesize_commit}\n end\n end\n\n def do_handle_call(:force_push, repo_conn, {sha, to}) do\n repo_conn\n |> get!(\"branches\/#{to}\")\n |> case do\n %{status_code: 404} ->\n msg = %{ \"ref\": \"refs\/heads\/#{to}\", \"sha\": sha }\n repo_conn\n |> post!(\"git\/refs\", Poison.encode!(msg))\n |> case do\n %{status_code: 201} ->\n {:ok, sha}\n _ ->\n {:error, :force_push}\n end\n %{body: raw, status_code: 200} ->\n if sha != Poison.decode!(raw)[\"commit\"][\"sha\"] do\n msg = %{ \"force\": true, \"sha\": sha }\n repo_conn\n |> patch!(\"git\/refs\/heads\/#{to}\", Poison.encode!(msg))\n |> case do\n %{status_code: 200} ->\n {:ok, sha}\n _ ->\n {:error, :force_push}\n end\n else\n {:ok, sha}\n end\n _ ->\n {:error, :force_push}\n end\n end\n\n def do_handle_call(:get_commit_status, repo_conn, {sha}) do\n repo_conn\n |> get!(\"commits\/#{sha}\/status\")\n |> case do\n %{body: raw, status_code: 200} ->\n res = Poison.decode!(raw)[\"statuses\"]\n |> Enum.map(&{\n &1[\"context\"],\n BorsNG.GitHub.map_state_to_status(&1[\"state\"])})\n |> Map.new()\n {:ok, res}\n _ ->\n {:error, :get_commit_status}\n end\n end\n\n def do_handle_call(:get_labels, repo_conn, {issue_xref}) do\n repo_conn\n |> get!(\"issues\/#{issue_xref}\/labels\")\n |> case do\n %{body: raw, status_code: 200} ->\n res = Poison.decode!(raw)\n |> Enum.map(fn %{ \"name\" => name } -> name end)\n {:ok, res}\n _ ->\n {:error, :get_labels}\n end\n end\n\n def do_handle_call(:get_file, repo_conn, {branch, path}) do\n %{body: raw, status_code: status_code} = get!(\n repo_conn,\n \"contents\/#{path}\",\n [{\"Accept\", @content_type_raw}],\n [params: [ref: branch]])\n res = case status_code do\n 404 -> nil\n 200 -> raw\n end\n {:ok, res}\n end\n\n def do_handle_call(:post_comment, repo_conn, {number, body}) do\n repo_conn\n |> post!(\"issues\/#{number}\/comments\", Poison.encode!(%{body: body}))\n |> case do\n %{status_code: 201} ->\n :ok\n _ ->\n {:error, :post_comment}\n end\n end\n\n def do_handle_call(:post_commit_status, repo_conn, {sha, status, msg}) do\n state = BorsNG.GitHub.map_status_to_state(status)\n body = %{state: state, context: \"bors\", description: msg}\n repo_conn\n |> post!(\"statuses\/#{sha}\", Poison.encode!(body))\n |> case do\n %{status_code: 201} ->\n :ok\n _ ->\n {:error, :post_commit_status}\n end\n end\n\n def do_handle_call(\n :get_user_by_login, {:raw, token}, {login}\n ) do\n \"#{site()}\/users\/#{login}\"\n |> HTTPoison.get!([{\"Authorization\", \"token #{token}\"}])\n |> case do\n %{body: raw, status_code: 200} ->\n user = raw\n |> Poison.decode!()\n |> BorsNG.GitHub.User.from_json!()\n {:ok, user}\n %{status_code: 404} ->\n {:ok, nil}\n _ ->\n {:error, :get_user_by_login}\n end\n end\n\n def do_handle_call(:get_installation_repos, {:raw, token}, {}) do\n {:ok, get_installation_repos_!(\n token,\n \"#{site()}\/installation\/repositories\",\n [])}\n end\n\n @spec get_installation_repos_!(binary, binary, [trepo]) :: [trepo]\n\n defp get_installation_repos_!(_, nil, repos) do\n repos\n end\n\n defp get_installation_repos_!(token, url, append) do\n params = case URI.parse(url).query do\n nil -> []\n qry -> URI.query_decoder(qry) |> Enum.to_list()\n end\n %{body: raw, status_code: 200, headers: headers} = HTTPoison.get!(\n url,\n [\n {\"Authorization\", \"token #{token}\"},\n {\"Accept\", @installation_content_type}],\n [params: params])\n repositories = Poison.decode!(raw)[\"repositories\"]\n |> Enum.map(&BorsNG.GitHub.Repo.from_json!\/1)\n |> Enum.concat(append)\n next_headers = headers\n |> Enum.filter(&(elem(&1, 0) == \"Link\"))\n |> Enum.map(&(ExLinkHeader.parse!(elem(&1, 1))))\n |> Enum.filter(&!is_nil(&1.next))\n case next_headers do\n [] -> repositories\n [next] -> get_installation_repos_!(token, next.next.url, repositories)\n end\n end\n\n @spec get_open_prs_!(binary, binary, [tpr]) :: [tpr]\n defp get_open_prs_!(token, url, append) do\n params = URI.parse(url).query |> URI.query_decoder() |> Enum.to_list()\n %{body: raw, status_code: 200, headers: headers} = HTTPoison.get!(\n url,\n [{\"Authorization\", \"token #{token}\"}, {\"Accept\", @content_type}],\n [params: params])\n prs = Poison.decode!(raw)\n |> Enum.map(&BorsNG.GitHub.Pr.from_json!\/1)\n |> Enum.concat(append)\n next_headers = headers\n |> Enum.filter(&(elem(&1, 0) == \"Link\"))\n |> Enum.map(&(ExLinkHeader.parse!(elem(&1, 1))))\n |> Enum.filter(&!is_nil(&1.next))\n case next_headers do\n [] -> prs\n [next] -> get_open_prs_!(token, next.next.url, prs)\n end\n end\n\n @spec post!(tconn, binary, binary, list) :: map\n defp post!(\n {{:raw, token}, repo_xref},\n path,\n body,\n headers \\\\ []\n ) do\n HTTPoison.post!(\n \"#{site()}\/repositories\/#{repo_xref}\/#{path}\",\n body,\n [{\"Authorization\", \"token #{token}\"}] ++ headers)\n end\n\n @spec patch!(tconn, binary, binary, list) :: map\n defp patch!(\n {{:raw, token}, repo_xref},\n path,\n body,\n headers \\\\ []\n ) do\n HTTPoison.patch!(\n \"#{site()}\/repositories\/#{repo_xref}\/#{path}\",\n body,\n [{\"Authorization\", \"token #{token}\"}] ++ headers)\n end\n\n @spec get!(tconn, binary, list, list) :: map\n defp get!(\n {{:raw, token}, repo_xref},\n path,\n headers \\\\ [],\n params \\\\ []\n ) do\n HTTPoison.get!(\n \"#{site()}\/repositories\/#{repo_xref}\/#{path}\",\n [{\"Authorization\", \"token #{token}\"}] ++ headers,\n params)\n end\n\n @spec delete!(tconn, binary, list, list) :: map\n defp delete!(\n {{:raw, token}, repo_xref},\n path,\n headers \\\\ [],\n params \\\\ []\n ) do\n HTTPoison.delete!(\n \"#{site()}\/repositories\/#{repo_xref}\/#{path}\",\n [{\"Authorization\", \"token #{token}\"}] ++ headers,\n params)\n end\n\n @token_exp 60\n\n @spec get_installation_token!(number) :: binary\n def get_installation_token!(installation_xref) do\n import Joken\n cfg = config()\n pem = JOSE.JWK.from_pem(cfg[:pem])\n jwt_token = %{\n \"iat\" => current_time(),\n \"exp\" => current_time() + @token_exp,\n \"iss\" => cfg[:iss]}\n |> token()\n |> sign(rs256(pem))\n |> get_compact()\n %{body: raw, status_code: 201} = HTTPoison.post!(\n \"#{site()}\/installations\/#{installation_xref}\/access_tokens\",\n \"\",\n [\n {\"Authorization\", \"Bearer #{jwt_token}\"},\n {\"Accept\", @installation_content_type}])\n Poison.decode!(raw)[\"token\"]\n end\n\n @doc \"\"\"\n Given an {:installation, installation_xref},\n look it up in the token cache.\n If it's there, and it's still usable, use it.\n Otherwise, fetch a new one.\n \"\"\"\n @spec raw_token!(ttoken, ttokenreg) :: {{:raw, binary}, ttokenreg}\n def raw_token!({:installation, installation_xref}, state) do\n now = Joken.current_time()\n case state[installation_xref] do\n {token, expires} when expires < now ->\n {{:raw, token}, state}\n _ ->\n token = get_installation_token!(installation_xref)\n exp = now + (@token_exp \/ 2) # Give us a little slack to work with.\n state = Map.put(state, installation_xref, {token, exp})\n {{:raw, token}, state}\n end\n end\n\n def raw_token!({:raw, _} = raw, state) do\n {raw, state}\n end\nend\n","old_contents":"defmodule BorsNG.GitHub.Server do\n use GenServer\n\n @moduledoc \"\"\"\n Provides a real connection to GitHub's REST API.\n This doesn't currently do rate limiting, but it will.\n \"\"\"\n\n def start_link do\n GenServer.start_link(__MODULE__, :ok, name: BorsNG.GitHub)\n end\n\n @installation_content_type \"application\/vnd.github.machine-man-preview+json\"\n @content_type_raw \"application\/vnd.github.v3.raw\"\n @content_type \"application\/vnd.github.v3+json\"\n\n @type tconn :: BorsNG.GitHub.tconn\n @type ttoken :: BorsNG.GitHub.ttoken\n @type trepo :: BorsNG.GitHub.trepo\n @type tpr :: BorsNG.GitHub.tpr\n\n @typedoc \"\"\"\n The token cache.\n \"\"\"\n @type ttokenreg :: %{number => {binary, number}}\n\n @spec config() :: keyword\n defp config do\n Application.get_env(:bors_github, BorsNG.GitHub.Server)\n end\n\n @spec site() :: bitstring\n defp site do\n Application.get_env(:bors_github, :site)\n end\n\n def init(:ok) do\n {:ok, {}}\n end\n\n def handle_call({type, {{_, _} = token, repo_xref}, args}, _from, state) do\n {token, state} = raw_token!(token, state)\n res = do_handle_call(type, {token, repo_xref}, args)\n {:reply, res, state}\n end\n\n def handle_call({type, {_, _} = token, args}, _from, _state) do\n {token, state} = raw_token!(token, %{})\n res = do_handle_call(type, token, args)\n {:reply, res, state}\n end\n\n def do_handle_call(:get_pr, repo_conn, {pr_xref}) do\n case get!(repo_conn, \"pulls\/#{pr_xref}\") do\n %{body: raw, status_code: 200} ->\n pr = raw\n |> Poison.decode!()\n |> BorsNG.GitHub.Pr.from_json!()\n {:ok, pr}\n e ->\n {:error, :get_pr, e.status_code, pr_xref}\n end\n end\n\n def do_handle_call(:get_open_prs, {{:raw, token}, repo_xref}, {}) do\n {:ok, get_open_prs_!(\n token,\n \"#{site()}\/repositories\/#{repo_xref}\/pulls?state=open\",\n [])}\n end\n\n def do_handle_call(:push, repo_conn, {sha, to}) do\n repo_conn\n |> patch!(\"git\/refs\/heads\/#{to}\", Poison.encode!(%{ \"sha\": sha }))\n |> case do\n %{body: _, status_code: 200} ->\n {:ok, sha}\n _ ->\n {:error, :push}\n end\n end\n\n def do_handle_call(:get_branch, repo_conn, {branch}) do\n case get!(repo_conn, \"branches\/#{branch}\") do\n %{body: raw, status_code: 200} ->\n r = Poison.decode!(raw)[\"commit\"]\n {:ok, %{commit: r[\"sha\"], tree: r[\"commit\"][\"tree\"][\"sha\"]}}\n _ ->\n {:error, :get_branch}\n end\n end\n\n def do_handle_call(:delete_branch, repo_conn, {branch}) do\n case delete!(repo_conn, \"git\/refs\/heads\/#{branch}\") do\n %{status_code: 204} ->\n :ok\n _ ->\n {:error, :delete_branch}\n end\n end\n\n def do_handle_call(:merge_branch, repo_conn, {%{\n from: from,\n to: to,\n commit_message: commit_message}}) do\n msg = %{ \"base\": to, \"head\": from, \"commit_message\": commit_message }\n repo_conn\n |> post!(\"merges\", Poison.encode!(msg))\n |> case do\n %{body: raw, status_code: 201} ->\n data = Poison.decode!(raw)\n res = %{\n commit: data[\"sha\"],\n tree: data[\"commit\"][\"tree\"][\"sha\"]\n }\n {:ok, res}\n %{status_code: 409} ->\n {:ok, :conflict}\n _ ->\n {:error, :merge_branch}\n end\n end\n\n def do_handle_call(:synthesize_commit, repo_conn, {%{\n branch: branch,\n tree: tree,\n parents: parents,\n commit_message: commit_message}}) do\n msg = %{ \"parents\": parents, \"tree\": tree, \"message\": commit_message }\n repo_conn\n |> post!(\"git\/commits\", Poison.encode!(msg))\n |> case do\n %{body: raw, status_code: 201} ->\n sha = Poison.decode!(raw)[\"sha\"]\n do_handle_call(:force_push, repo_conn, {sha, branch})\n _ ->\n {:error, :synthesize_commit}\n end\n end\n\n def do_handle_call(:force_push, repo_conn, {sha, to}) do\n repo_conn\n |> get!(\"branches\/#{to}\")\n |> case do\n %{status_code: 404} ->\n msg = %{ \"ref\": \"refs\/heads\/#{to}\", \"sha\": sha }\n repo_conn\n |> post!(\"git\/refs\", Poison.encode!(msg))\n |> case do\n %{status_code: 201} ->\n {:ok, sha}\n _ ->\n {:error, :force_push}\n end\n %{body: raw, status_code: 200} ->\n if sha != Poison.decode!(raw)[\"commit\"][\"sha\"] do\n msg = %{ \"force\": true, \"sha\": sha }\n repo_conn\n |> patch!(\"git\/refs\/heads\/#{to}\", Poison.encode!(msg))\n |> case do\n %{status_code: 200} ->\n {:ok, sha}\n _ ->\n {:error, :force_push}\n end\n else\n {:ok, sha}\n end\n _ ->\n {:error, :force_push}\n end\n end\n\n def do_handle_call(:get_commit_status, repo_conn, {sha}) do\n repo_conn\n |> get!(\"commits\/#{sha}\/status\")\n |> case do\n %{body: raw, status_code: 200} ->\n res = Poison.decode!(raw)[\"statuses\"]\n |> Enum.map(&{\n &1[\"context\"],\n BorsNG.GitHub.map_state_to_status(&1[\"state\"])})\n |> Map.new()\n {:ok, res}\n _ ->\n {:error, :get_commit_status}\n end\n end\n\n def do_handle_call(:get_labels, repo_conn, {issue_xref}) do\n repo_conn\n |> get!(\"issues\/#{issue_xref}\/labels\")\n |> case do\n %{body: raw, status_code: 200} ->\n res = Poison.decode!(raw)\n |> Enum.map(fn %{ \"name\" => name } -> name end)\n {:ok, res}\n _ ->\n {:error, :get_labels}\n end\n end\n\n def do_handle_call(:get_file, repo_conn, {branch, path}) do\n %{body: raw, status_code: status_code} = get!(\n repo_conn,\n \"contents\/#{path}\",\n [{\"Accept\", @content_type_raw}],\n [params: [ref: branch]])\n res = case status_code do\n 404 -> nil\n 200 -> raw\n end\n {:ok, res}\n end\n\n def do_handle_call(:post_comment, repo_conn, {number, body}) do\n repo_conn\n |> post!(\"issues\/#{number}\/comments\", Poison.encode!(%{body: body}))\n |> case do\n %{status_code: 201} ->\n :ok\n _ ->\n {:error, :post_comment}\n end\n end\n\n def do_handle_call(:post_commit_status, repo_conn, {sha, status, msg}) do\n state = BorsNG.GitHub.map_status_to_state(status)\n body = %{state: state, context: \"bors\", description: msg}\n repo_conn\n |> post!(\"statuses\/#{sha}\", Poison.encode!(body))\n |> case do\n %{status_code: 201} ->\n :ok\n _ ->\n {:error, :post_commit_status}\n end\n end\n\n def do_handle_call(\n :get_user_by_login, {:raw, token}, {login}\n ) do\n \"#{site()}\/users\/#{login}\"\n |> HTTPoison.get!([{\"Authorization\", \"token #{token}\"}])\n |> case do\n %{body: raw, status_code: 200} ->\n user = raw\n |> Poison.decode!()\n |> BorsNG.GitHub.User.from_json!()\n {:ok, user}\n %{status_code: 404} ->\n {:ok, nil}\n _ ->\n {:error, :get_user_by_login}\n end\n end\n\n def do_handle_call(:get_installation_repos, {:raw, token}, {}) do\n {:ok, get_installation_repos_!(\n token,\n \"#{site()}\/installation\/repositories\",\n [])}\n end\n\n @spec get_installation_repos_!(binary, binary, [trepo]) :: [trepo]\n\n defp get_installation_repos_!(_, nil, repos) do\n repos\n end\n\n defp get_installation_repos_!(token, url, append) do\n params = case URI.parse(url).query do\n nil -> []\n qry -> URI.query_decoder(qry) |> Enum.to_list()\n end\n %{body: raw, status_code: 200, headers: headers} = HTTPoison.get!(\n url,\n [\n {\"Authorization\", \"token #{token}\"},\n {\"Accept\", @installation_content_type}],\n [params: params])\n repositories = Poison.decode!(raw)[\"repositories\"]\n |> Enum.map(&BorsNG.GitHub.Repo.from_json!\/1)\n |> Enum.concat(append)\n next_headers = headers\n |> Enum.filter(&(elem(&1, 0) == \"Link\"))\n |> Enum.map(&(ExLinkHeader.parse!(elem(&1, 1))))\n |> Enum.filter(&!is_nil(&1.next))\n case next_headers do\n [] -> repositories\n [next] -> get_installation_repos_!(token, next.next.url, repositories)\n end\n end\n\n @spec get_open_prs_!(binary, binary, [tpr]) :: [tpr]\n defp get_open_prs_!(token, url, append) do\n params = URI.parse(url).query |> URI.query_decoder() |> Enum.to_list()\n %{body: raw, status_code: 200, headers: headers} = HTTPoison.get!(\n url,\n [{\"Authorization\", \"token #{token}\"}, {\"Accept\", @content_type}],\n [params: params])\n prs = Poison.decode!(raw)\n |> Enum.map(&BorsNG.GitHub.Pr.from_json!\/1)\n |> Enum.concat(append)\n next_headers = headers\n |> Enum.filter(&(elem(&1, 0) == \"Link\"))\n |> Enum.map(&(ExLinkHeader.parse!(elem(&1, 1))))\n |> Enum.filter(&!is_nil(&1.next))\n case next_headers do\n [] -> prs\n [next] -> get_open_prs_!(token, next.next.url, prs)\n end\n end\n\n @spec post!(tconn, binary, binary, list) :: map\n defp post!(\n {{:raw, token}, repo_xref},\n path,\n body,\n headers \\\\ []\n ) do\n HTTPoison.post!(\n \"#{site()}\/repositories\/#{repo_xref}\/#{path}\",\n body,\n [{\"Authorization\", \"token #{token}\"}] ++ headers)\n end\n\n @spec patch!(tconn, binary, binary, list) :: map\n defp patch!(\n {{:raw, token}, repo_xref},\n path,\n body,\n headers \\\\ []\n ) do\n HTTPoison.patch!(\n \"#{site()}\/repositories\/#{repo_xref}\/#{path}\",\n body,\n [{\"Authorization\", \"token #{token}\"}] ++ headers)\n end\n\n @spec get!(tconn, binary, list, list) :: map\n defp get!(\n {{:raw, token}, repo_xref},\n path,\n headers \\\\ [],\n params \\\\ []\n ) do\n HTTPoison.get!(\n \"#{site()}\/repositories\/#{repo_xref}\/#{path}\",\n [{\"Authorization\", \"token #{token}\"}] ++ headers,\n params)\n end\n\n @spec delete!(tconn, binary, list, list) :: map\n defp delete!(\n {{:raw, token}, repo_xref},\n path,\n headers \\\\ [],\n params \\\\ []\n ) do\n HTTPoison.delete!(\n \"#{site()}\/repositories\/#{repo_xref}\/#{path}\",\n [{\"Authorization\", \"token #{token}\"}] ++ headers,\n params)\n end\n\n @token_exp 60\n\n @spec get_installation_token!(number) :: binary\n def get_installation_token!(installation_xref) do\n import Joken\n cfg = config()\n pem = JOSE.JWK.from_pem(cfg[:pem])\n jwt_token = %{\n \"iat\" => current_time(),\n \"exp\" => current_time() + @token_exp,\n \"iss\" => cfg[:iss]}\n |> token()\n |> sign(rs256(pem))\n |> get_compact()\n %{body: raw, status_code: 201} = HTTPoison.post!(\n \"#{site()}\/installations\/#{installation_xref}\/access_tokens\",\n \"\",\n [\n {\"Authorization\", \"Bearer #{jwt_token}\"},\n {\"Accept\", @installation_content_type}])\n Poison.decode!(raw)[\"token\"]\n end\n\n @doc \"\"\"\n Given an {:installation, installation_xref},\n look it up in the token cache.\n If it's there, and it's still usable, use it.\n Otherwise, fetch a new one.\n \"\"\"\n @spec raw_token!(ttoken, ttokenreg) :: {{:raw, binary}, ttokenreg}\n def raw_token!({:installation, installation_xref}, state) do\n now = Joken.current_time()\n case state[installation_xref] do\n {token, expires} when expires < now ->\n {{:raw, token}, state}\n _ ->\n token = get_installation_token!(installation_xref)\n exp = now + (@token_exp \/ 2) # Give us a little slack to work with.\n state = Map.put(state, installation_xref, {token, exp})\n {{:raw, token}, state}\n end\n end\n\n def raw_token!({:raw, _} = raw, state) do\n {raw, state}\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"85bb3d18fd30285592d2bf9766cfed600f47483e","subject":"Fix path to maked lib","message":"Fix path to maked lib\n","repos":"plus3x\/privilegex","old_file":"lib\/setuid.ex","new_file":"lib\/setuid.ex","new_contents":"defmodule Setuid do\n @on_load :load_nifs\n\n def load_nifs do\n path = :filename.join(:code.priv_dir(:setuid), 'setuid')\n :erlang.load_nif(path, 0)\n end\n\n def getuid, do: raise \"NIF getuid\/0 not implemented\"\n def setuid(_uid), do: raise \"NIF setuid\/1 not implemented\"\n def getgid, do: raise \"NIF getgid\/0 not implemented\"\n def setgid(_gid), do: raise \"NIF setgid\/1 not implemented\"\nend\n","old_contents":"defmodule Setuid do\n @on_load :load_nifs\n\n def load_nifs, do: :erlang.load_nif('.\/priv\/setuid', 0)\n\n def getuid, do: raise \"NIF getuid\/0 not implemented\"\n def setuid(_uid), do: raise \"NIF setuid\/1 not implemented\"\n def getgid, do: raise \"NIF getgid\/0 not implemented\"\n def setgid(_gid), do: raise \"NIF setgid\/1 not implemented\"\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"0c6302be536a9ef3beb03f38216ae08a62fba0f0","subject":"404 errors","message":"404 errors\n","repos":"FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os","old_file":"apps\/farmbot_configurator\/lib\/router.ex","new_file":"apps\/farmbot_configurator\/lib\/router.ex","new_contents":"defmodule Farmbot.Configurator.Router do\n @moduledoc \"\"\"\n Routes incoming connections.\n \"\"\"\n alias Farmbot.System.FS.ConfigStorage\n alias Farmbot.System.Network, as: NetMan\n require Logger\n\n use Plug.Router\n # this is so we can serve the bundle.js file.\n plug Plug.Static, at: \"\/\", from: :farmbot_configurator\n plug :match\n plug :dispatch\n plug CORSPlug\n\n get \"\/\", do: conn |> send_resp(200, make_html())\n\n get \"\/api\/config\" do\n # Already in json form.\n {:ok, config} = ConfigStorage.read_config_file\n conn |> send_resp(200, config)\n end\n\n post \"\/api\/config\" do\n {:ok, body, _} = read_body(conn)\n rbody = Poison.decode!(body)\n # TODO THIS NEEDS SOME HARD CHECKING. PROBABLY IN THE CONFIG STORAGE MODULE\n ConfigStorage.replace_config_file(rbody)\n conn |> send_resp(200,body)\n end\n\n post \"\/api\/config\/creds\" do\n {:ok, body, _} = read_body(conn)\n %{\"email\" => email,\"pass\" => pass,\"server\" => server} = Poison.decode!(body)\n Farmbot.Auth.interim(email, pass, server)\n conn |> send_resp(200, \"ok\")\n end\n\n get \"\/api\/network\/scan\" do\n {:ok, body, _} = read_body(conn)\n %{\"iface\" => iface} = Poison.decode!(body)\n scan = NetMan.scan(iface)\n case scan do\n {:error, reason} -> conn |> send_resp(500, \"could not scan: #{inspect reason}\")\n ssids -> conn |> send_resp(200, Poison.encode!(ssids))\n end\n end\n\n post \"\/api\/factory_reset\" do\n Logger.debug \"goodbye.\"\n spawn fn() ->\n # sleep to allow the request to finish.\n Process.sleep(100)\n Farmbot.System.factory_reset\n end\n conn |> send_resp(204, \"GoodByeWorld!\")\n end\n\n post \"\/api\/try_log_in\" do\n Logger.debug \"Trying to log in. \"\n spawn fn() ->\n # sleep to allow the request to finish.\n Process.sleep(100)\n Logger.debug \"THAT ISNT WORKINGF YET!!!\"\n end\n conn |> send_resp(200, \"OK\")\n end\n\n # anything that doesn't match a rest end point gets the index.\n match _, do: conn |> send_resp(404, \"not found\")\n\n def make_html do\n \"#{:code.priv_dir(:farmbot_configurator)}\/static\/index.html\" |> File.read!\n end\nend\n","old_contents":"defmodule Farmbot.Configurator.Router do\n @moduledoc \"\"\"\n Routes incoming connections.\n \"\"\"\n alias Farmbot.System.FS.ConfigStorage\n alias Farmbot.System.Network, as: NetMan\n require Logger\n\n use Plug.Router\n # this is so we can serve the bundle.js file.\n plug Plug.Static, at: \"\/\", from: :farmbot_configurator\n plug :match\n plug :dispatch\n plug CORSPlug\n\n get \"\/api\/config\" do\n # Already in json form.\n {:ok, config} = ConfigStorage.read_config_file\n conn |> send_resp(200, config)\n end\n\n post \"\/api\/config\" do\n {:ok, body, _} = read_body(conn)\n rbody = Poison.decode!(body)\n # TODO THIS NEEDS SOME HARD CHECKING. PROBABLY IN THE CONFIG STORAGE MODULE\n ConfigStorage.replace_config_file(rbody)\n conn |> send_resp(200,body)\n end\n\n post \"\/api\/config\/creds\" do\n {:ok, body, _} = read_body(conn)\n %{\"email\" => email,\"pass\" => pass,\"server\" => server} = Poison.decode!(body)\n Farmbot.Auth.interim(email, pass, server)\n conn |> send_resp(200, \"ok\")\n end\n\n get \"\/api\/network\/scan\" do\n {:ok, body, _} = read_body(conn)\n %{\"iface\" => iface} = Poison.decode!(body)\n scan = NetMan.scan(iface)\n case scan do\n {:error, reason} -> conn |> send_resp(500, \"could not scan: #{inspect reason}\")\n ssids -> conn |> send_resp(200, Poison.encode!(ssids))\n end\n end\n\n post \"\/api\/factory_reset\" do\n Logger.debug \"goodbye.\"\n spawn fn() ->\n # sleep to allow the request to finish.\n Process.sleep(100)\n Farmbot.System.factory_reset\n end\n conn |> send_resp(204, \"GoodByeWorld!\")\n end\n\n post \"\/api\/try_log_in\" do\n Logger.debug \"Trying to log in. \"\n spawn fn() ->\n # sleep to allow the request to finish.\n Process.sleep(100)\n Logger.debug \"THAT ISNT WORKINGF YET!!!\"\n end\n conn |> send_resp(200, \"OK\")\n end\n\n # anything that doesn't match a rest end point gets the index.\n match _, do: conn |> send_resp(200, make_html())\n\n def make_html do\n \"#{:code.priv_dir(:farmbot_configurator)}\/static\/index.html\" |> File.read!\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"556bd254db79ae0c3287a0d6773dce3e96882691","subject":"Improve wording in Map module (#10318)","message":"Improve wording in Map module (#10318)\n\n","repos":"elixir-lang\/elixir,pedrosnk\/elixir,kelvinst\/elixir,kelvinst\/elixir,kimshrier\/elixir,kimshrier\/elixir,michalmuskala\/elixir,pedrosnk\/elixir,joshprice\/elixir,ggcampinho\/elixir,ggcampinho\/elixir","old_file":"lib\/elixir\/lib\/map.ex","new_file":"lib\/elixir\/lib\/map.ex","new_contents":"defmodule Map do\n @moduledoc \"\"\"\n Maps are the \"go to\" key-value data structure in Elixir.\n\n Maps can be created with the `%{}` syntax, and key-value pairs can be\n expressed as `key => value`:\n\n iex> %{}\n %{}\n iex> %{\"one\" => :two, 3 => \"four\"}\n %{3 => \"four\", \"one\" => :two}\n\n Key-value pairs in a map do not follow any order (that's why the printed map\n in the example above has a different order than the map that was created).\n\n Maps do not impose any restriction on the key type: anything can be a key in a\n map. As a key-value structure, maps do not allow duplicated keys. Keys are\n compared using the exact-equality operator (`===\/2`). If colliding keys are defined\n in a map literal, the last one prevails.\n\n When the key in a key-value pair is an atom, the `key: value` shorthand syntax\n can be used (as in many other special forms), provided key-value pairs are put at\n the end:\n\n iex> %{\"hello\" => \"world\", a: 1, b: 2}\n %{:a => 1, :b => 2, \"hello\" => \"world\"}\n\n Keys in maps can be accessed through some of the functions in this module\n (such as `Map.get\/3` or `Map.fetch\/2`) or through the `map[]` syntax provided\n by the `Access` module:\n\n iex> map = %{a: 1, b: 2}\n iex> Map.fetch(map, :a)\n {:ok, 1}\n iex> map[:b]\n 2\n iex> map[\"non_existing_key\"]\n nil\n\n To access atom keys, one may also use the `map.key` notation. Note that `map.key`\n will raise a `KeyError` if the `map` doesn't contain the key `:key`, compared to\n `map[:key]`, that would return `nil`.\n\n map = %{foo: \"bar\", baz: \"bong\"}\n map.foo\n #=> \"bar\"\n map.non_existing_key\n #=> ** (KeyError) key :non_existing_key not found in: %{baz: \"bong\", foo: \"bar\"}\n\n > Note: do not add parens when accessing fields, such as in `data.key()`.\n > If parenthesis are used, Elixir will consider it to be a function call\n > on `data`, which would be expected to be an atom.\n\n The two syntaxes for accessing keys reveal the dual nature of maps. The `map[key]`\n syntax is used for dynamically created maps that may have any key, of any type.\n `map.key` is used with maps that hold a predetermined set of atoms keys, which are\n expected to always be present. Structs, defined via `defstruct\/1`, are one example\n of such \"static maps\", where the keys can also be checked during compile time.\n\n Maps can be pattern matched on. When a map is on the left-hand side of a\n pattern match, it will match if the map on the right-hand side contains the\n keys on the left-hand side and their values match the ones on the left-hand\n side. This means that an empty map matches every map.\n\n iex> %{} = %{foo: \"bar\"}\n %{foo: \"bar\"}\n iex> %{a: a} = %{:a => 1, \"b\" => 2, [:c, :e, :e] => 3}\n iex> a\n 1\n\n But this will raise a `MatchError` exception:\n\n %{:c => 3} = %{:a => 1, 2 => :b}\n\n Variables can be used as map keys both when writing map literals as well as\n when matching:\n\n iex> n = 1\n 1\n iex> %{n => :one}\n %{1 => :one}\n iex> %{^n => :one} = %{1 => :one, 2 => :two, 3 => :three}\n %{1 => :one, 2 => :two, 3 => :three}\n\n Maps also support a specific update syntax to update the value stored under\n *existing* atom keys:\n\n iex> map = %{one: 1, two: 2}\n iex> %{map | one: \"one\"}\n %{one: \"one\", two: 2}\n\n When a key that does not exist in the map is updated a `KeyError` exception will be raised:\n\n %{map | three: 3}\n\n The functions in this module that need to find a specific key work in logarithmic time.\n This means that the time it takes to find keys grows as the map grows, but it's not\n directly proportional to the map size. In comparison to finding an element in a list,\n it performs better because lists have a linear time complexity. Some functions,\n such as `keys\/1` and `values\/1`, run in linear time because they need to get to every\n element in the map.\n\n Maps also implement the `Enumerable` protocol, so many functions to work with maps\n are found in the `Enum` module. Additionally, the following functions for maps are\n found in `Kernel`:\n\n * `map_size\/1`\n\n \"\"\"\n\n @type key :: any\n @type value :: any\n @compile {:inline, fetch: 2, fetch!: 2, get: 2, put: 3, delete: 2, has_key?: 2, replace!: 3}\n\n @doc \"\"\"\n Returns all keys from `map`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.keys(%{a: 1, b: 2})\n [:a, :b]\n\n \"\"\"\n @spec keys(map) :: [key]\n defdelegate keys(map), to: :maps\n\n @doc \"\"\"\n Returns all values from `map`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.values(%{a: 1, b: 2})\n [1, 2]\n\n \"\"\"\n @spec values(map) :: [value]\n defdelegate values(map), to: :maps\n\n @doc \"\"\"\n Converts `map` to a list.\n\n Each key-value pair in the map is converted to a two-element tuple `{key,\n value}` in the resulting list.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.to_list(%{a: 1})\n [a: 1]\n iex> Map.to_list(%{1 => 2})\n [{1, 2}]\n\n \"\"\"\n @spec to_list(map) :: [{term, term}]\n defdelegate to_list(map), to: :maps\n\n @doc \"\"\"\n Returns a new empty map.\n\n ## Examples\n\n iex> Map.new()\n %{}\n\n \"\"\"\n @spec new :: map\n def new, do: %{}\n\n @doc \"\"\"\n Creates a map from an `enumerable`.\n\n Duplicated keys are removed; the latest one prevails.\n\n ## Examples\n\n iex> Map.new([{:b, 1}, {:a, 2}])\n %{a: 2, b: 1}\n iex> Map.new(a: 1, a: 2, a: 3)\n %{a: 3}\n\n \"\"\"\n @spec new(Enumerable.t()) :: map\n def new(enumerable)\n def new(list) when is_list(list), do: :maps.from_list(list)\n def new(%_{} = struct), do: new_from_enum(struct)\n def new(%{} = map), do: map\n def new(enum), do: new_from_enum(enum)\n\n defp new_from_enum(enumerable) do\n enumerable\n |> Enum.to_list()\n |> :maps.from_list()\n end\n\n @doc \"\"\"\n Creates a map from an `enumerable` via the given transformation function.\n\n Duplicated keys are removed; the latest one prevails.\n\n ## Examples\n\n iex> Map.new([:a, :b], fn x -> {x, x} end)\n %{a: :a, b: :b}\n\n \"\"\"\n @spec new(Enumerable.t(), (term -> {key, value})) :: map\n def new(enumerable, transform) when is_function(transform, 1) do\n enumerable\n |> Enum.to_list()\n |> new_transform(transform, [])\n end\n\n defp new_transform([], _fun, acc) do\n acc\n |> :lists.reverse()\n |> :maps.from_list()\n end\n\n defp new_transform([element | rest], fun, acc) do\n new_transform(rest, fun, [fun.(element) | acc])\n end\n\n @doc \"\"\"\n Returns whether the given `key` exists in the given `map`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.has_key?(%{a: 1}, :a)\n true\n iex> Map.has_key?(%{a: 1}, :b)\n false\n\n \"\"\"\n @spec has_key?(map, key) :: boolean\n def has_key?(map, key), do: :maps.is_key(key, map)\n\n @doc \"\"\"\n Fetches the value for a specific `key` in the given `map`.\n\n If `map` contains the given `key` then its value is returned in the shape of `{:ok, value}`.\n If `map` doesn't contain `key`, `:error` is returned.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.fetch(%{a: 1}, :a)\n {:ok, 1}\n iex> Map.fetch(%{a: 1}, :b)\n :error\n\n \"\"\"\n @spec fetch(map, key) :: {:ok, value} | :error\n def fetch(map, key), do: :maps.find(key, map)\n\n @doc \"\"\"\n Fetches the value for a specific `key` in the given `map`, erroring out if\n `map` doesn't contain `key`.\n\n If `map` contains `key`, the corresponding value is returned. If\n `map` doesn't contain `key`, a `KeyError` exception is raised.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.fetch!(%{a: 1}, :a)\n 1\n\n \"\"\"\n @spec fetch!(map, key) :: value\n def fetch!(map, key) do\n :maps.get(key, map)\n end\n\n @doc \"\"\"\n Puts the given `value` under `key` unless the entry `key`\n already exists in `map`.\n\n ## Examples\n\n iex> Map.put_new(%{a: 1}, :b, 2)\n %{a: 1, b: 2}\n iex> Map.put_new(%{a: 1, b: 2}, :a, 3)\n %{a: 1, b: 2}\n\n \"\"\"\n @spec put_new(map, key, value) :: map\n def put_new(map, key, value) do\n case map do\n %{^key => _value} ->\n map\n\n %{} ->\n put(map, key, value)\n\n other ->\n :erlang.error({:badmap, other})\n end\n end\n\n @doc \"\"\"\n Puts a value under `key` only if the `key` already exists in `map`.\n\n ## Examples\n\n iex> Map.replace(%{a: 1, b: 2}, :a, 3)\n %{a: 3, b: 2}\n\n iex> Map.replace(%{a: 1}, :b, 2)\n %{a: 1}\n\n \"\"\"\n @doc since: \"1.11.0\"\n @spec replace(map, key, value) :: map\n def replace(map, key, value) do\n case map do\n %{^key => _value} ->\n put(map, key, value)\n\n %{} ->\n map\n\n other ->\n :erlang.error({:badmap, other})\n end\n end\n\n @doc \"\"\"\n Puts a value under `key` only if the `key` already exists in `map`.\n\n If `key` is not present in `map`, a `KeyError` exception is raised.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.replace!(%{a: 1, b: 2}, :a, 3)\n %{a: 3, b: 2}\n\n iex> Map.replace!(%{a: 1}, :b, 2)\n ** (KeyError) key :b not found in: %{a: 1}\n\n \"\"\"\n @doc since: \"1.5.0\"\n @spec replace!(map, key, value) :: map\n def replace!(map, key, value) do\n :maps.update(key, value, map)\n end\n\n @doc \"\"\"\n Evaluates `fun` and puts the result under `key`\n in `map` unless `key` is already present.\n\n This function is useful in case you want to compute the value to put under\n `key` only if `key` is not already present, as for example, when the value is expensive to\n calculate or generally difficult to setup and teardown again.\n\n ## Examples\n\n iex> map = %{a: 1}\n iex> fun = fn ->\n ...> # some expensive operation here\n ...> 3\n ...> end\n iex> Map.put_new_lazy(map, :a, fun)\n %{a: 1}\n iex> Map.put_new_lazy(map, :b, fun)\n %{a: 1, b: 3}\n\n \"\"\"\n @spec put_new_lazy(map, key, (() -> value)) :: map\n def put_new_lazy(map, key, fun) when is_function(fun, 0) do\n case map do\n %{^key => _value} ->\n map\n\n %{} ->\n put(map, key, fun.())\n\n other ->\n :erlang.error({:badmap, other})\n end\n end\n\n @doc \"\"\"\n Returns a new map with all the key-value pairs in `map` where the key\n is in `keys`.\n\n If `keys` contains keys that are not in `map`, they're simply ignored.\n\n ## Examples\n\n iex> Map.take(%{a: 1, b: 2, c: 3}, [:a, :c, :e])\n %{a: 1, c: 3}\n\n \"\"\"\n @spec take(map, [key]) :: map\n def take(map, keys)\n\n def take(map, keys) when is_map(map) and is_list(keys) do\n take(keys, map, _acc = [])\n end\n\n def take(map, keys) when is_map(map) do\n IO.warn(\n \"Map.take\/2 with an Enumerable of keys that is not a list is deprecated. \" <>\n \" Use a list of keys instead.\"\n )\n\n take(map, Enum.to_list(keys))\n end\n\n def take(non_map, _keys) do\n :erlang.error({:badmap, non_map})\n end\n\n defp take([], _map, acc) do\n :maps.from_list(acc)\n end\n\n defp take([key | rest], map, acc) do\n acc =\n case map do\n %{^key => value} -> [{key, value} | acc]\n %{} -> acc\n end\n\n take(rest, map, acc)\n end\n\n @doc \"\"\"\n Gets the value for a specific `key` in `map`.\n\n If `key` is present in `map` then its value `value` is\n returned. Otherwise, `default` is returned.\n\n If `default` is not provided, `nil` is used.\n\n ## Examples\n\n iex> Map.get(%{}, :a)\n nil\n iex> Map.get(%{a: 1}, :a)\n 1\n iex> Map.get(%{a: 1}, :b)\n nil\n iex> Map.get(%{a: 1}, :b, 3)\n 3\n\n \"\"\"\n @spec get(map, key, value) :: value\n def get(map, key, default \\\\ nil) do\n case map do\n %{^key => value} ->\n value\n\n %{} ->\n default\n\n other ->\n :erlang.error({:badmap, other}, [map, key, default])\n end\n end\n\n @doc \"\"\"\n Gets the value for a specific `key` in `map`.\n\n If `key` is present in `map` then its value `value` is\n returned. Otherwise, `fun` is evaluated and its result is returned.\n\n This is useful if the default value is very expensive to calculate or\n generally difficult to setup and teardown again.\n\n ## Examples\n\n iex> map = %{a: 1}\n iex> fun = fn ->\n ...> # some expensive operation here\n ...> 13\n ...> end\n iex> Map.get_lazy(map, :a, fun)\n 1\n iex> Map.get_lazy(map, :b, fun)\n 13\n\n \"\"\"\n @spec get_lazy(map, key, (() -> value)) :: value\n def get_lazy(map, key, fun) when is_function(fun, 0) do\n case map do\n %{^key => value} ->\n value\n\n %{} ->\n fun.()\n\n other ->\n :erlang.error({:badmap, other}, [map, key, fun])\n end\n end\n\n @doc \"\"\"\n Puts the given `value` under `key` in `map`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.put(%{a: 1}, :b, 2)\n %{a: 1, b: 2}\n iex> Map.put(%{a: 1, b: 2}, :a, 3)\n %{a: 3, b: 2}\n\n \"\"\"\n @spec put(map, key, value) :: map\n def put(map, key, value) do\n :maps.put(key, value, map)\n end\n\n @doc \"\"\"\n Deletes the entry in `map` for a specific `key`.\n\n If the `key` does not exist, returns `map` unchanged.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.delete(%{a: 1, b: 2}, :a)\n %{b: 2}\n iex> Map.delete(%{b: 2}, :a)\n %{b: 2}\n\n \"\"\"\n @spec delete(map, key) :: map\n def delete(map, key), do: :maps.remove(key, map)\n\n @doc \"\"\"\n Merges two maps into one.\n\n All keys in `map2` will be added to `map1`, overriding any existing one\n (i.e., the keys in `map2` \"have precedence\" over the ones in `map1`).\n\n If you have a struct and you would like to merge a set of keys into the\n struct, do not use this function, as it would merge all keys on the right\n side into the struct, even if the key is not part of the struct. Instead,\n use `Kernel.struct\/2`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.merge(%{a: 1, b: 2}, %{a: 3, d: 4})\n %{a: 3, b: 2, d: 4}\n\n \"\"\"\n @spec merge(map, map) :: map\n defdelegate merge(map1, map2), to: :maps\n\n @doc \"\"\"\n Merges two maps into one, resolving conflicts through the given `fun`.\n\n All keys in `map2` will be added to `map1`. The given function will be invoked\n when there are duplicate keys; its arguments are `key` (the duplicate key),\n `value1` (the value of `key` in `map1`), and `value2` (the value of `key` in\n `map2`). The value returned by `fun` is used as the value under `key` in\n the resulting map.\n\n ## Examples\n\n iex> Map.merge(%{a: 1, b: 2}, %{a: 3, d: 4}, fn _k, v1, v2 ->\n ...> v1 + v2\n ...> end)\n %{a: 4, b: 2, d: 4}\n\n \"\"\"\n @spec merge(map, map, (key, value, value -> value)) :: map\n def merge(map1, map2, fun) when is_function(fun, 3) do\n if map_size(map1) > map_size(map2) do\n folder = fn key, val2, acc ->\n update(acc, key, val2, fn val1 -> fun.(key, val1, val2) end)\n end\n\n :maps.fold(folder, map1, map2)\n else\n folder = fn key, val2, acc ->\n update(acc, key, val2, fn val1 -> fun.(key, val2, val1) end)\n end\n\n :maps.fold(folder, map2, map1)\n end\n end\n\n @doc \"\"\"\n Updates the `key` in `map` with the given function.\n\n If `key` is present in `map` then the existing value is passed to `fun` and its result is\n used as the updated value of `key`. If `key` is\n not present in `map`, `default` is inserted as the value of `key`. The default\n value will not be passed through the update function.\n\n ## Examples\n\n iex> Map.update(%{a: 1}, :a, 13, fn existing_value -> existing_value * 2 end)\n %{a: 2}\n iex> Map.update(%{a: 1}, :b, 11, fn existing_value -> existing_value * 2 end)\n %{a: 1, b: 11}\n\n \"\"\"\n @spec update(map, key, default :: value, (existing_value :: value -> updated_value :: value)) ::\n map\n def update(map, key, default, fun) when is_function(fun, 1) do\n case map do\n %{^key => value} ->\n put(map, key, fun.(value))\n\n %{} ->\n put(map, key, default)\n\n other ->\n :erlang.error({:badmap, other}, [map, key, default, fun])\n end\n end\n\n @doc \"\"\"\n Removes the value associated with `key` in `map` and returns the value and the updated map.\n\n If `key` is present in `map`, it returns `{value, new_map}` where `value` is the value of\n the key and `new_map` is the result of removing `key` from `map`. If `key`\n is not present in `map`, `{default, map}` is returned.\n\n ## Examples\n\n iex> Map.pop(%{a: 1}, :a)\n {1, %{}}\n iex> Map.pop(%{a: 1}, :b)\n {nil, %{a: 1}}\n iex> Map.pop(%{a: 1}, :b, 3)\n {3, %{a: 1}}\n\n \"\"\"\n @spec pop(map, key, value) :: {value, new_map :: map}\n def pop(map, key, default \\\\ nil) do\n case :maps.take(key, map) do\n {_, _} = tuple -> tuple\n :error -> {default, map}\n end\n end\n\n @doc \"\"\"\n Returns and removes the value associated with `key` in `map` or raises\n if `key` is not present.\n\n Behaves the same as `pop\/3` but raises if `key` is not present in `map`.\n\n ## Examples\n\n iex> Map.pop!(%{a: 1}, :a)\n {1, %{}}\n iex> Map.pop!(%{a: 1, b: 2}, :a)\n {1, %{b: 2}}\n iex> Map.pop!(%{a: 1}, :b)\n ** (KeyError) key :b not found in: %{a: 1}\n\n \"\"\"\n @doc since: \"1.10.0\"\n @spec pop!(map, key) :: {value, map}\n def pop!(map, key) do\n case :maps.take(key, map) do\n {_, _} = tuple -> tuple\n :error -> raise KeyError, key: key, term: map\n end\n end\n\n @doc \"\"\"\n Lazily returns and removes the value associated with `key` in `map`.\n\n If `key` is present in `map`, it returns `{value, new_map}` where `value` is the value of\n the key and `new_map` is the result of removing `key` from `map`. If `key`\n is not present in `map`, `{fun_result, map}` is returned, where `fun_result`\n is the result of applying `fun`.\n\n This is useful if the default value is very expensive to calculate or\n generally difficult to setup and teardown again.\n\n ## Examples\n\n iex> map = %{a: 1}\n iex> fun = fn ->\n ...> # some expensive operation here\n ...> 13\n ...> end\n iex> Map.pop_lazy(map, :a, fun)\n {1, %{}}\n iex> Map.pop_lazy(map, :b, fun)\n {13, %{a: 1}}\n\n \"\"\"\n @spec pop_lazy(map, key, (() -> value)) :: {value, map}\n def pop_lazy(map, key, fun) when is_function(fun, 0) do\n case :maps.take(key, map) do\n {_, _} = tuple -> tuple\n :error -> {fun.(), map}\n end\n end\n\n @doc \"\"\"\n Drops the given `keys` from `map`.\n\n If `keys` contains keys that are not in `map`, they're simply ignored.\n\n ## Examples\n\n iex> Map.drop(%{a: 1, b: 2, c: 3}, [:b, :d])\n %{a: 1, c: 3}\n\n \"\"\"\n @spec drop(map, [key]) :: map\n def drop(map, keys)\n\n def drop(map, keys) when is_map(map) and is_list(keys) do\n drop_keys(keys, map)\n end\n\n def drop(map, keys) when is_map(map) do\n IO.warn(\n \"Map.drop\/2 with an Enumerable of keys that is not a list is deprecated. \" <>\n \" Use a list of keys instead.\"\n )\n\n drop(map, Enum.to_list(keys))\n end\n\n def drop(non_map, keys) do\n :erlang.error({:badmap, non_map}, [non_map, keys])\n end\n\n defp drop_keys([], acc), do: acc\n\n defp drop_keys([key | rest], acc) do\n drop_keys(rest, delete(acc, key))\n end\n\n @doc \"\"\"\n Takes all entries corresponding to the given `keys` in `map` and extracts\n them into a separate map.\n\n Returns a tuple with the new map and the old map with removed keys.\n\n Keys for which there are no entries in `map` are ignored.\n\n ## Examples\n\n iex> Map.split(%{a: 1, b: 2, c: 3}, [:a, :c, :e])\n {%{a: 1, c: 3}, %{b: 2}}\n\n \"\"\"\n @spec split(map, [key]) :: {map, map}\n def split(map, keys)\n\n def split(map, keys) when is_map(map) and is_list(keys) do\n split(keys, [], map)\n end\n\n def split(map, keys) when is_map(map) do\n IO.warn(\n \"Map.split\/2 with an Enumerable of keys that is not a list is deprecated. \" <>\n \" Use a list of keys instead.\"\n )\n\n split(map, Enum.to_list(keys))\n end\n\n def split(non_map, keys) do\n :erlang.error({:badmap, non_map}, [non_map, keys])\n end\n\n defp split([], included, excluded) do\n {:maps.from_list(included), excluded}\n end\n\n defp split([key | rest], included, excluded) do\n case excluded do\n %{^key => value} ->\n split(rest, [{key, value} | included], delete(excluded, key))\n\n _other ->\n split(rest, included, excluded)\n end\n end\n\n @doc \"\"\"\n Updates `key` with the given function.\n\n If `key` is present in `map` then the existing value is passed to `fun` and its result is\n used as the updated value of `key`. If `key` is\n not present in `map`, a `KeyError` exception is raised.\n\n ## Examples\n\n iex> Map.update!(%{a: 1}, :a, &(&1 * 2))\n %{a: 2}\n\n iex> Map.update!(%{a: 1}, :b, &(&1 * 2))\n ** (KeyError) key :b not found in: %{a: 1}\n\n \"\"\"\n @spec update!(map, key, (existing_value :: value -> updated_value :: value)) :: map\n def update!(map, key, fun) when is_function(fun, 1) do\n value = fetch!(map, key)\n put(map, key, fun.(value))\n end\n\n @doc \"\"\"\n Gets the value from `key` and updates it, all in one pass.\n\n `fun` is called with the current value under `key` in `map` (or `nil` if `key`\n is not present in `map`) and must return a two-element tuple: the current value\n (the retrieved value, which can be operated on before being returned) and the\n new value to be stored under `key` in the resulting new map. `fun` may also\n return `:pop`, which means the current value shall be removed from `map` and\n returned (making this function behave like `Map.pop(map, key)`).\n\n The returned value is a two-element tuple with the current value returned by\n `fun` and a new map with the updated value under `key`.\n\n ## Examples\n\n iex> Map.get_and_update(%{a: 1}, :a, fn current_value ->\n ...> {current_value, \"new value!\"}\n ...> end)\n {1, %{a: \"new value!\"}}\n\n iex> Map.get_and_update(%{a: 1}, :b, fn current_value ->\n ...> {current_value, \"new value!\"}\n ...> end)\n {nil, %{b: \"new value!\", a: 1}}\n\n iex> Map.get_and_update(%{a: 1}, :a, fn _ -> :pop end)\n {1, %{}}\n\n iex> Map.get_and_update(%{a: 1}, :b, fn _ -> :pop end)\n {nil, %{a: 1}}\n\n \"\"\"\n @spec get_and_update(map, key, (value -> {current_value, new_value :: value} | :pop)) ::\n {current_value, map}\n when current_value: value\n def get_and_update(map, key, fun) when is_function(fun, 1) do\n current = get(map, key)\n\n case fun.(current) do\n {get, update} ->\n {get, put(map, key, update)}\n\n :pop ->\n {current, delete(map, key)}\n\n other ->\n raise \"the given function must return a two-element tuple or :pop, got: #{inspect(other)}\"\n end\n end\n\n @doc \"\"\"\n Gets the value from `key` and updates it, all in one pass. Raises if there is no `key`.\n\n Behaves exactly like `get_and_update\/3`, but raises a `KeyError` exception if\n `key` is not present in `map`.\n\n ## Examples\n\n iex> Map.get_and_update!(%{a: 1}, :a, fn current_value ->\n ...> {current_value, \"new value!\"}\n ...> end)\n {1, %{a: \"new value!\"}}\n\n iex> Map.get_and_update!(%{a: 1}, :b, fn current_value ->\n ...> {current_value, \"new value!\"}\n ...> end)\n ** (KeyError) key :b not found in: %{a: 1}\n\n iex> Map.get_and_update!(%{a: 1}, :a, fn _ ->\n ...> :pop\n ...> end)\n {1, %{}}\n\n \"\"\"\n @spec get_and_update!(map, key, (value -> {current_value, new_value :: value} | :pop)) ::\n {current_value, map}\n when current_value: value\n def get_and_update!(map, key, fun) when is_function(fun, 1) do\n value = fetch!(map, key)\n\n case fun.(value) do\n {get, update} ->\n {get, put(map, key, update)}\n\n :pop ->\n {value, delete(map, key)}\n\n other ->\n raise \"the given function must return a two-element tuple or :pop, got: #{inspect(other)}\"\n end\n end\n\n @doc \"\"\"\n Converts a `struct` to map.\n\n It accepts the struct module or a struct itself and\n simply removes the `__struct__` field from the given struct\n or from a new struct generated from the given module.\n\n ## Example\n\n defmodule User do\n defstruct [:name]\n end\n\n Map.from_struct(User)\n #=> %{name: nil}\n\n Map.from_struct(%User{name: \"john\"})\n #=> %{name: \"john\"}\n\n \"\"\"\n @spec from_struct(atom | struct) :: map\n def from_struct(struct) when is_atom(struct) do\n delete(struct.__struct__(), :__struct__)\n end\n\n def from_struct(%_{} = struct) do\n delete(struct, :__struct__)\n end\n\n @doc \"\"\"\n Checks if two maps are equal.\n\n Two maps are considered to be equal if they contain\n the same keys and those keys contain the same values.\n\n ## Examples\n\n iex> Map.equal?(%{a: 1, b: 2}, %{b: 2, a: 1})\n true\n iex> Map.equal?(%{a: 1, b: 2}, %{b: 1, a: 2})\n false\n\n \"\"\"\n @spec equal?(map, map) :: boolean\n def equal?(map1, map2)\n\n def equal?(%{} = map1, %{} = map2), do: map1 === map2\n def equal?(%{} = map1, map2), do: :erlang.error({:badmap, map2}, [map1, map2])\n def equal?(term, other), do: :erlang.error({:badmap, term}, [term, other])\n\n @doc false\n @deprecated \"Use Kernel.map_size\/1 instead\"\n def size(map) do\n map_size(map)\n end\nend\n","old_contents":"defmodule Map do\n @moduledoc \"\"\"\n Maps are the \"go to\" key-value data structure in Elixir.\n\n Maps can be created with the `%{}` syntax, and key-value pairs can be\n expressed as `key => value`:\n\n iex> %{}\n %{}\n iex> %{\"one\" => :two, 3 => \"four\"}\n %{3 => \"four\", \"one\" => :two}\n\n Key-value pairs in a map do not follow any order (that's why the printed map\n in the example above has a different order than the map that was created).\n\n Maps do not impose any restriction on the key type: anything can be a key in a\n map. As a key-value structure, maps do not allow duplicated keys. Keys are\n compared using the exact-equality operator (`===\/2`). If colliding keys are defined\n in a map literal, the last one prevails.\n\n When the key in a key-value pair is an atom, the `key: value` shorthand syntax\n can be used (as in many other special forms), provided key-value pairs are put at\n the end:\n\n iex> %{\"hello\" => \"world\", a: 1, b: 2}\n %{:a => 1, :b => 2, \"hello\" => \"world\"}\n\n Keys in maps can be accessed through some of the functions in this module\n (such as `Map.get\/3` or `Map.fetch\/2`) or through the `map[]` syntax provided\n by the `Access` module:\n\n iex> map = %{a: 1, b: 2}\n iex> Map.fetch(map, :a)\n {:ok, 1}\n iex> map[:b]\n 2\n iex> map[\"non_existing_key\"]\n nil\n\n To access atom keys, one may also use the `map.key` notation. Note that `map.key`\n will raise a `KeyError` if the `map` doesn't contain the key `:key`, compared to\n `map[:key]`, that would return `nil`.\n\n map = %{foo: \"bar\", baz: \"bong\"}\n map.foo\n #=> \"bar\"\n map.non_existing_key\n #=> ** (KeyError) key :non_existing_key not found in: %{baz: \"bong\", foo: \"bar\"}\n\n > Note: do not add parens when accessing fields, such as in `data.key()`.\n > If parenthesis are used, Elixir will consider it to be a function call\n > on `data`, which would be expected to be an atom.\n\n The two syntaxes for accessing keys reveal the dual nature of maps. The `map[key]`\n syntax is used for dynamically created maps that may have any key, of any type.\n `map.key` is used with maps that hold a predetermined set of atoms keys, which are\n expected to always be present. Structs, defined via `defstruct\/1`, are one example\n of such \"static maps\", where the keys can also be checked during compile time.\n\n Maps can be pattern matched on. When a map is on the left-hand side of a\n pattern match, it will match if the map on the right-hand side contains the\n keys on the left-hand side and their values match the ones on the left-hand\n side. This means that an empty map matches every map.\n\n iex> %{} = %{foo: \"bar\"}\n %{foo: \"bar\"}\n iex> %{a: a} = %{:a => 1, \"b\" => 2, [:c, :e, :e] => 3}\n iex> a\n 1\n\n But this will raise a `MatchError` exception:\n\n %{:c => 3} = %{:a => 1, 2 => :b}\n\n Variables can be used as map keys both when writing map literals as well as\n when matching:\n\n iex> n = 1\n 1\n iex> %{n => :one}\n %{1 => :one}\n iex> %{^n => :one} = %{1 => :one, 2 => :two, 3 => :three}\n %{1 => :one, 2 => :two, 3 => :three}\n\n Maps also support a specific update syntax to update the value stored under\n *existing* atom keys:\n\n iex> map = %{one: 1, two: 2}\n iex> %{map | one: \"one\"}\n %{one: \"one\", two: 2}\n\n When a key that does not exist in the map is updated a `KeyError` exception will be raised:\n\n %{map | three: 3}\n\n The functions in this module that need to find a specific key work in logarithmic time.\n This means that the time it takes to find keys grows as the map grows, but it's not\n directly proportional to the map size. In comparison to finding an element in a list,\n it performs better because lists have a linear time complexity. Some functions,\n such as `keys\/1` and `values\/1`, run in linear time because they need to get to every\n element in the map.\n\n Maps also implement the `Enumerable` protocol, so many functions to work with maps\n are found in the `Enum` module. Additionally, the following functions for maps are\n found in `Kernel`:\n\n * `map_size\/1`\n\n \"\"\"\n\n @type key :: any\n @type value :: any\n @compile {:inline, fetch: 2, fetch!: 2, get: 2, put: 3, delete: 2, has_key?: 2, replace!: 3}\n\n @doc \"\"\"\n Returns all keys from `map`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.keys(%{a: 1, b: 2})\n [:a, :b]\n\n \"\"\"\n @spec keys(map) :: [key]\n defdelegate keys(map), to: :maps\n\n @doc \"\"\"\n Returns all values from `map`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.values(%{a: 1, b: 2})\n [1, 2]\n\n \"\"\"\n @spec values(map) :: [value]\n defdelegate values(map), to: :maps\n\n @doc \"\"\"\n Converts `map` to a list.\n\n Each key-value pair in the map is converted to a two-element tuple `{key,\n value}` in the resulting list.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.to_list(%{a: 1})\n [a: 1]\n iex> Map.to_list(%{1 => 2})\n [{1, 2}]\n\n \"\"\"\n @spec to_list(map) :: [{term, term}]\n defdelegate to_list(map), to: :maps\n\n @doc \"\"\"\n Returns a new empty map.\n\n ## Examples\n\n iex> Map.new()\n %{}\n\n \"\"\"\n @spec new :: map\n def new, do: %{}\n\n @doc \"\"\"\n Creates a map from an `enumerable`.\n\n Duplicated keys are removed; the latest one prevails.\n\n ## Examples\n\n iex> Map.new([{:b, 1}, {:a, 2}])\n %{a: 2, b: 1}\n iex> Map.new(a: 1, a: 2, a: 3)\n %{a: 3}\n\n \"\"\"\n @spec new(Enumerable.t()) :: map\n def new(enumerable)\n def new(list) when is_list(list), do: :maps.from_list(list)\n def new(%_{} = struct), do: new_from_enum(struct)\n def new(%{} = map), do: map\n def new(enum), do: new_from_enum(enum)\n\n defp new_from_enum(enumerable) do\n enumerable\n |> Enum.to_list()\n |> :maps.from_list()\n end\n\n @doc \"\"\"\n Creates a map from an `enumerable` via the given transformation function.\n\n Duplicated keys are removed; the latest one prevails.\n\n ## Examples\n\n iex> Map.new([:a, :b], fn x -> {x, x} end)\n %{a: :a, b: :b}\n\n \"\"\"\n @spec new(Enumerable.t(), (term -> {key, value})) :: map\n def new(enumerable, transform) when is_function(transform, 1) do\n enumerable\n |> Enum.to_list()\n |> new_transform(transform, [])\n end\n\n defp new_transform([], _fun, acc) do\n acc\n |> :lists.reverse()\n |> :maps.from_list()\n end\n\n defp new_transform([element | rest], fun, acc) do\n new_transform(rest, fun, [fun.(element) | acc])\n end\n\n @doc \"\"\"\n Returns whether the given `key` exists in the given `map`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.has_key?(%{a: 1}, :a)\n true\n iex> Map.has_key?(%{a: 1}, :b)\n false\n\n \"\"\"\n @spec has_key?(map, key) :: boolean\n def has_key?(map, key), do: :maps.is_key(key, map)\n\n @doc \"\"\"\n Fetches the value for a specific `key` in the given `map`.\n\n If `map` contains the given `key` with value `value`, then `{:ok, value}` is\n returned. If `map` doesn't contain `key`, `:error` is returned.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.fetch(%{a: 1}, :a)\n {:ok, 1}\n iex> Map.fetch(%{a: 1}, :b)\n :error\n\n \"\"\"\n @spec fetch(map, key) :: {:ok, value} | :error\n def fetch(map, key), do: :maps.find(key, map)\n\n @doc \"\"\"\n Fetches the value for a specific `key` in the given `map`, erroring out if\n `map` doesn't contain `key`.\n\n If `map` contains the given `key`, the corresponding value is returned. If\n `map` doesn't contain `key`, a `KeyError` exception is raised.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.fetch!(%{a: 1}, :a)\n 1\n\n \"\"\"\n @spec fetch!(map, key) :: value\n def fetch!(map, key) do\n :maps.get(key, map)\n end\n\n @doc \"\"\"\n Puts the given `value` under `key` unless the entry `key`\n already exists in `map`.\n\n ## Examples\n\n iex> Map.put_new(%{a: 1}, :b, 2)\n %{a: 1, b: 2}\n iex> Map.put_new(%{a: 1, b: 2}, :a, 3)\n %{a: 1, b: 2}\n\n \"\"\"\n @spec put_new(map, key, value) :: map\n def put_new(map, key, value) do\n case map do\n %{^key => _value} ->\n map\n\n %{} ->\n put(map, key, value)\n\n other ->\n :erlang.error({:badmap, other})\n end\n end\n\n @doc \"\"\"\n Puts a value under `key` only if the `key` already exists in `map`.\n\n ## Examples\n\n iex> Map.replace(%{a: 1, b: 2}, :a, 3)\n %{a: 3, b: 2}\n\n iex> Map.replace(%{a: 1}, :b, 2)\n %{a: 1}\n\n \"\"\"\n @doc since: \"1.11.0\"\n @spec replace(map, key, value) :: map\n def replace(map, key, value) do\n case map do\n %{^key => _value} ->\n put(map, key, value)\n\n %{} ->\n map\n\n other ->\n :erlang.error({:badmap, other})\n end\n end\n\n @doc \"\"\"\n Puts a value under `key` only if the `key` already exists in `map`.\n\n If `key` is not present in `map`, a `KeyError` exception is raised.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.replace!(%{a: 1, b: 2}, :a, 3)\n %{a: 3, b: 2}\n\n iex> Map.replace!(%{a: 1}, :b, 2)\n ** (KeyError) key :b not found in: %{a: 1}\n\n \"\"\"\n @doc since: \"1.5.0\"\n @spec replace!(map, key, value) :: map\n def replace!(map, key, value) do\n :maps.update(key, value, map)\n end\n\n @doc \"\"\"\n Evaluates `fun` and puts the result under `key`\n in `map` unless `key` is already present.\n\n This function is useful in case you want to compute the value to put under\n `key` only if `key` is not already present, as for example, when the value is expensive to\n calculate or generally difficult to setup and teardown again.\n\n ## Examples\n\n iex> map = %{a: 1}\n iex> fun = fn ->\n ...> # some expensive operation here\n ...> 3\n ...> end\n iex> Map.put_new_lazy(map, :a, fun)\n %{a: 1}\n iex> Map.put_new_lazy(map, :b, fun)\n %{a: 1, b: 3}\n\n \"\"\"\n @spec put_new_lazy(map, key, (() -> value)) :: map\n def put_new_lazy(map, key, fun) when is_function(fun, 0) do\n case map do\n %{^key => _value} ->\n map\n\n %{} ->\n put(map, key, fun.())\n\n other ->\n :erlang.error({:badmap, other})\n end\n end\n\n @doc \"\"\"\n Returns a new map with all the key-value pairs in `map` where the key\n is in `keys`.\n\n If `keys` contains keys that are not in `map`, they're simply ignored.\n\n ## Examples\n\n iex> Map.take(%{a: 1, b: 2, c: 3}, [:a, :c, :e])\n %{a: 1, c: 3}\n\n \"\"\"\n @spec take(map, [key]) :: map\n def take(map, keys)\n\n def take(map, keys) when is_map(map) and is_list(keys) do\n take(keys, map, _acc = [])\n end\n\n def take(map, keys) when is_map(map) do\n IO.warn(\n \"Map.take\/2 with an Enumerable of keys that is not a list is deprecated. \" <>\n \" Use a list of keys instead.\"\n )\n\n take(map, Enum.to_list(keys))\n end\n\n def take(non_map, _keys) do\n :erlang.error({:badmap, non_map})\n end\n\n defp take([], _map, acc) do\n :maps.from_list(acc)\n end\n\n defp take([key | rest], map, acc) do\n acc =\n case map do\n %{^key => value} -> [{key, value} | acc]\n %{} -> acc\n end\n\n take(rest, map, acc)\n end\n\n @doc \"\"\"\n Gets the value for a specific `key` in `map`.\n\n If `key` is present in `map` with value `value`, then `value` is\n returned. Otherwise, `default` is returned.\n\n If `default` is not provided, `nil` is used.\n\n ## Examples\n\n iex> Map.get(%{}, :a)\n nil\n iex> Map.get(%{a: 1}, :a)\n 1\n iex> Map.get(%{a: 1}, :b)\n nil\n iex> Map.get(%{a: 1}, :b, 3)\n 3\n\n \"\"\"\n @spec get(map, key, value) :: value\n def get(map, key, default \\\\ nil) do\n case map do\n %{^key => value} ->\n value\n\n %{} ->\n default\n\n other ->\n :erlang.error({:badmap, other}, [map, key, default])\n end\n end\n\n @doc \"\"\"\n Gets the value for a specific `key` in `map`.\n\n If `key` is present in `map` with value `value`, then `value` is\n returned. Otherwise, `fun` is evaluated and its result is returned.\n\n This is useful if the default value is very expensive to calculate or\n generally difficult to setup and teardown again.\n\n ## Examples\n\n iex> map = %{a: 1}\n iex> fun = fn ->\n ...> # some expensive operation here\n ...> 13\n ...> end\n iex> Map.get_lazy(map, :a, fun)\n 1\n iex> Map.get_lazy(map, :b, fun)\n 13\n\n \"\"\"\n @spec get_lazy(map, key, (() -> value)) :: value\n def get_lazy(map, key, fun) when is_function(fun, 0) do\n case map do\n %{^key => value} ->\n value\n\n %{} ->\n fun.()\n\n other ->\n :erlang.error({:badmap, other}, [map, key, fun])\n end\n end\n\n @doc \"\"\"\n Puts the given `value` under `key` in `map`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.put(%{a: 1}, :b, 2)\n %{a: 1, b: 2}\n iex> Map.put(%{a: 1, b: 2}, :a, 3)\n %{a: 3, b: 2}\n\n \"\"\"\n @spec put(map, key, value) :: map\n def put(map, key, value) do\n :maps.put(key, value, map)\n end\n\n @doc \"\"\"\n Deletes the entry in `map` for a specific `key`.\n\n If the `key` does not exist, returns `map` unchanged.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.delete(%{a: 1, b: 2}, :a)\n %{b: 2}\n iex> Map.delete(%{b: 2}, :a)\n %{b: 2}\n\n \"\"\"\n @spec delete(map, key) :: map\n def delete(map, key), do: :maps.remove(key, map)\n\n @doc \"\"\"\n Merges two maps into one.\n\n All keys in `map2` will be added to `map1`, overriding any existing one\n (i.e., the keys in `map2` \"have precedence\" over the ones in `map1`).\n\n If you have a struct and you would like to merge a set of keys into the\n struct, do not use this function, as it would merge all keys on the right\n side into the struct, even if the key is not part of the struct. Instead,\n use `Kernel.struct\/2`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> Map.merge(%{a: 1, b: 2}, %{a: 3, d: 4})\n %{a: 3, b: 2, d: 4}\n\n \"\"\"\n @spec merge(map, map) :: map\n defdelegate merge(map1, map2), to: :maps\n\n @doc \"\"\"\n Merges two maps into one, resolving conflicts through the given `fun`.\n\n All keys in `map2` will be added to `map1`. The given function will be invoked\n when there are duplicate keys; its arguments are `key` (the duplicate key),\n `value1` (the value of `key` in `map1`), and `value2` (the value of `key` in\n `map2`). The value returned by `fun` is used as the value under `key` in\n the resulting map.\n\n ## Examples\n\n iex> Map.merge(%{a: 1, b: 2}, %{a: 3, d: 4}, fn _k, v1, v2 ->\n ...> v1 + v2\n ...> end)\n %{a: 4, b: 2, d: 4}\n\n \"\"\"\n @spec merge(map, map, (key, value, value -> value)) :: map\n def merge(map1, map2, fun) when is_function(fun, 3) do\n if map_size(map1) > map_size(map2) do\n folder = fn key, val2, acc ->\n update(acc, key, val2, fn val1 -> fun.(key, val1, val2) end)\n end\n\n :maps.fold(folder, map1, map2)\n else\n folder = fn key, val2, acc ->\n update(acc, key, val2, fn val1 -> fun.(key, val2, val1) end)\n end\n\n :maps.fold(folder, map2, map1)\n end\n end\n\n @doc \"\"\"\n Updates the `key` in `map` with the given function.\n\n If `key` is present in `map` with value `value`, `fun` is invoked with\n argument `value` and its result is used as the new value of `key`. If `key` is\n not present in `map`, `default` is inserted as the value of `key`. The default\n value will not be passed through the update function.\n\n ## Examples\n\n iex> Map.update(%{a: 1}, :a, 13, fn existing_value -> existing_value * 2 end)\n %{a: 2}\n iex> Map.update(%{a: 1}, :b, 11, fn existing_value -> existing_value * 2 end)\n %{a: 1, b: 11}\n\n \"\"\"\n @spec update(map, key, default :: value, (existing_value :: value -> updated_value :: value)) ::\n map\n def update(map, key, default, fun) when is_function(fun, 1) do\n case map do\n %{^key => value} ->\n put(map, key, fun.(value))\n\n %{} ->\n put(map, key, default)\n\n other ->\n :erlang.error({:badmap, other}, [map, key, default, fun])\n end\n end\n\n @doc \"\"\"\n Returns and removes the value associated with `key` in `map`.\n\n If `key` is present in `map` with value `value`, `{value, new_map}` is\n returned where `new_map` is the result of removing `key` from `map`. If `key`\n is not present in `map`, `{default, map}` is returned.\n\n ## Examples\n\n iex> Map.pop(%{a: 1}, :a)\n {1, %{}}\n iex> Map.pop(%{a: 1}, :b)\n {nil, %{a: 1}}\n iex> Map.pop(%{a: 1}, :b, 3)\n {3, %{a: 1}}\n\n \"\"\"\n @spec pop(map, key, value) :: {value, map}\n def pop(map, key, default \\\\ nil) do\n case :maps.take(key, map) do\n {_, _} = tuple -> tuple\n :error -> {default, map}\n end\n end\n\n @doc \"\"\"\n Returns and removes the value associated with `key` in `map` or raises\n if `key` is not present.\n\n Behaves the same as `pop\/3` but raises if `key` is not present in `map`.\n\n ## Examples\n\n iex> Map.pop!(%{a: 1}, :a)\n {1, %{}}\n iex> Map.pop!(%{a: 1, b: 2}, :a)\n {1, %{b: 2}}\n iex> Map.pop!(%{a: 1}, :b)\n ** (KeyError) key :b not found in: %{a: 1}\n\n \"\"\"\n @doc since: \"1.10.0\"\n @spec pop!(map, key) :: {value, map}\n def pop!(map, key) do\n case :maps.take(key, map) do\n {_, _} = tuple -> tuple\n :error -> raise KeyError, key: key, term: map\n end\n end\n\n @doc \"\"\"\n Lazily returns and removes the value associated with `key` in `map`.\n\n If `key` is present in `map` with value `value`, `{value, new_map}` is\n returned where `new_map` is the result of removing `key` from `map`. If `key`\n is not present in `map`, `{fun_result, map}` is returned, where `fun_result`\n is the result of applying `fun`.\n\n This is useful if the default value is very expensive to calculate or\n generally difficult to setup and teardown again.\n\n ## Examples\n\n iex> map = %{a: 1}\n iex> fun = fn ->\n ...> # some expensive operation here\n ...> 13\n ...> end\n iex> Map.pop_lazy(map, :a, fun)\n {1, %{}}\n iex> Map.pop_lazy(map, :b, fun)\n {13, %{a: 1}}\n\n \"\"\"\n @spec pop_lazy(map, key, (() -> value)) :: {value, map}\n def pop_lazy(map, key, fun) when is_function(fun, 0) do\n case :maps.take(key, map) do\n {_, _} = tuple -> tuple\n :error -> {fun.(), map}\n end\n end\n\n @doc \"\"\"\n Drops the given `keys` from `map`.\n\n If `keys` contains keys that are not in `map`, they're simply ignored.\n\n ## Examples\n\n iex> Map.drop(%{a: 1, b: 2, c: 3}, [:b, :d])\n %{a: 1, c: 3}\n\n \"\"\"\n @spec drop(map, [key]) :: map\n def drop(map, keys)\n\n def drop(map, keys) when is_map(map) and is_list(keys) do\n drop_keys(keys, map)\n end\n\n def drop(map, keys) when is_map(map) do\n IO.warn(\n \"Map.drop\/2 with an Enumerable of keys that is not a list is deprecated. \" <>\n \" Use a list of keys instead.\"\n )\n\n drop(map, Enum.to_list(keys))\n end\n\n def drop(non_map, keys) do\n :erlang.error({:badmap, non_map}, [non_map, keys])\n end\n\n defp drop_keys([], acc), do: acc\n\n defp drop_keys([key | rest], acc) do\n drop_keys(rest, delete(acc, key))\n end\n\n @doc \"\"\"\n Takes all entries corresponding to the given `keys` in `map` and extracts\n them into a separate map.\n\n Returns a tuple with the new map and the old map with removed keys.\n\n Keys for which there are no entries in `map` are ignored.\n\n ## Examples\n\n iex> Map.split(%{a: 1, b: 2, c: 3}, [:a, :c, :e])\n {%{a: 1, c: 3}, %{b: 2}}\n\n \"\"\"\n @spec split(map, [key]) :: {map, map}\n def split(map, keys)\n\n def split(map, keys) when is_map(map) and is_list(keys) do\n split(keys, [], map)\n end\n\n def split(map, keys) when is_map(map) do\n IO.warn(\n \"Map.split\/2 with an Enumerable of keys that is not a list is deprecated. \" <>\n \" Use a list of keys instead.\"\n )\n\n split(map, Enum.to_list(keys))\n end\n\n def split(non_map, keys) do\n :erlang.error({:badmap, non_map}, [non_map, keys])\n end\n\n defp split([], included, excluded) do\n {:maps.from_list(included), excluded}\n end\n\n defp split([key | rest], included, excluded) do\n case excluded do\n %{^key => value} ->\n split(rest, [{key, value} | included], delete(excluded, key))\n\n _other ->\n split(rest, included, excluded)\n end\n end\n\n @doc \"\"\"\n Updates `key` with the given function.\n\n If `key` is present in `map` with value `value`, `fun` is invoked with\n argument `value` and its result is used as the new value of `key`. If `key` is\n not present in `map`, a `KeyError` exception is raised.\n\n ## Examples\n\n iex> Map.update!(%{a: 1}, :a, &(&1 * 2))\n %{a: 2}\n\n iex> Map.update!(%{a: 1}, :b, &(&1 * 2))\n ** (KeyError) key :b not found in: %{a: 1}\n\n \"\"\"\n @spec update!(map, key, (current_value :: value -> new_value :: value)) :: map\n def update!(map, key, fun) when is_function(fun, 1) do\n value = fetch!(map, key)\n put(map, key, fun.(value))\n end\n\n @doc \"\"\"\n Gets the value from `key` and updates it, all in one pass.\n\n `fun` is called with the current value under `key` in `map` (or `nil` if `key`\n is not present in `map`) and must return a two-element tuple: the current value\n (the retrieved value, which can be operated on before being returned) and the\n new value to be stored under `key` in the resulting new map. `fun` may also\n return `:pop`, which means the current value shall be removed from `map` and\n returned (making this function behave like `Map.pop(map, key)`).\n\n The returned value is a two-element tuple with the current value returned by\n `fun` and a new map with the updated value under `key`.\n\n ## Examples\n\n iex> Map.get_and_update(%{a: 1}, :a, fn current_value ->\n ...> {current_value, \"new value!\"}\n ...> end)\n {1, %{a: \"new value!\"}}\n\n iex> Map.get_and_update(%{a: 1}, :b, fn current_value ->\n ...> {current_value, \"new value!\"}\n ...> end)\n {nil, %{b: \"new value!\", a: 1}}\n\n iex> Map.get_and_update(%{a: 1}, :a, fn _ -> :pop end)\n {1, %{}}\n\n iex> Map.get_and_update(%{a: 1}, :b, fn _ -> :pop end)\n {nil, %{a: 1}}\n\n \"\"\"\n @spec get_and_update(map, key, (value -> {current_value, new_value :: value} | :pop)) ::\n {current_value, map}\n when current_value: value\n def get_and_update(map, key, fun) when is_function(fun, 1) do\n current = get(map, key)\n\n case fun.(current) do\n {get, update} ->\n {get, put(map, key, update)}\n\n :pop ->\n {current, delete(map, key)}\n\n other ->\n raise \"the given function must return a two-element tuple or :pop, got: #{inspect(other)}\"\n end\n end\n\n @doc \"\"\"\n Gets the value from `key` and updates it, all in one pass. Raises if there is no `key`.\n\n Behaves exactly like `get_and_update\/3`, but raises a `KeyError` exception if\n `key` is not present in `map`.\n\n ## Examples\n\n iex> Map.get_and_update!(%{a: 1}, :a, fn current_value ->\n ...> {current_value, \"new value!\"}\n ...> end)\n {1, %{a: \"new value!\"}}\n\n iex> Map.get_and_update!(%{a: 1}, :b, fn current_value ->\n ...> {current_value, \"new value!\"}\n ...> end)\n ** (KeyError) key :b not found in: %{a: 1}\n\n iex> Map.get_and_update!(%{a: 1}, :a, fn _ ->\n ...> :pop\n ...> end)\n {1, %{}}\n\n \"\"\"\n @spec get_and_update!(map, key, (value -> {current_value, new_value :: value} | :pop)) ::\n {current_value, map}\n when current_value: value\n def get_and_update!(map, key, fun) when is_function(fun, 1) do\n value = fetch!(map, key)\n\n case fun.(value) do\n {get, update} ->\n {get, put(map, key, update)}\n\n :pop ->\n {value, delete(map, key)}\n\n other ->\n raise \"the given function must return a two-element tuple or :pop, got: #{inspect(other)}\"\n end\n end\n\n @doc \"\"\"\n Converts a `struct` to map.\n\n It accepts the struct module or a struct itself and\n simply removes the `__struct__` field from the given struct\n or from a new struct generated from the given module.\n\n ## Example\n\n defmodule User do\n defstruct [:name]\n end\n\n Map.from_struct(User)\n #=> %{name: nil}\n\n Map.from_struct(%User{name: \"john\"})\n #=> %{name: \"john\"}\n\n \"\"\"\n @spec from_struct(atom | struct) :: map\n def from_struct(struct) when is_atom(struct) do\n delete(struct.__struct__(), :__struct__)\n end\n\n def from_struct(%_{} = struct) do\n delete(struct, :__struct__)\n end\n\n @doc \"\"\"\n Checks if two maps are equal.\n\n Two maps are considered to be equal if they contain\n the same keys and those keys contain the same values.\n\n ## Examples\n\n iex> Map.equal?(%{a: 1, b: 2}, %{b: 2, a: 1})\n true\n iex> Map.equal?(%{a: 1, b: 2}, %{b: 1, a: 2})\n false\n\n \"\"\"\n @spec equal?(map, map) :: boolean\n def equal?(map1, map2)\n\n def equal?(%{} = map1, %{} = map2), do: map1 === map2\n def equal?(%{} = map1, map2), do: :erlang.error({:badmap, map2}, [map1, map2])\n def equal?(term, other), do: :erlang.error({:badmap, term}, [term, other])\n\n @doc false\n @deprecated \"Use Kernel.map_size\/1 instead\"\n def size(map) do\n map_size(map)\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"dd1c92790ec2bd6a3fe23aa328b1c3029c35adba","subject":"Ensure records can be created with no field, closes #299","message":"Ensure records can be created with no field, closes #299\n","repos":"kimshrier\/elixir,kelvinst\/elixir,gfvcastro\/elixir,michalmuskala\/elixir,antipax\/elixir,elixir-lang\/elixir,lexmag\/elixir,joshprice\/elixir,ggcampinho\/elixir,lexmag\/elixir,gfvcastro\/elixir,ggcampinho\/elixir,antipax\/elixir,beedub\/elixir,pedrosnk\/elixir,kimshrier\/elixir,beedub\/elixir,kelvinst\/elixir,pedrosnk\/elixir","old_file":"test\/elixir\/record_test.exs","new_file":"test\/elixir\/record_test.exs","new_contents":"Code.require_file \"..\/test_helper\", __FILE__\n\ndefrecord RecordTest.FileInfo,\n Record.extract(:file_info, from_lib: \"kernel\/include\/file.hrl\")\n\nname = RecordTest.DynamicName\ndefrecord name, a: 0, b: 1\n\ndefrecord RecordTest.WithNoField, []\n\ndefmodule RecordTest do\n use ExUnit.Case\n\n test :record_constructor_with_dict do\n record = RecordTest.FileInfo.new(type: :regular)\n assert record.type == :regular\n assert record.access == nil\n end\n\n test :record_accessors do\n record = RecordTest.FileInfo.new(file_info)\n assert record.type == :regular\n assert record.access == :read_write\n\n new_record = record.access :read\n assert new_record.access == :read\n end\n\n test :dynamic_record_name do\n record = RecordTest.DynamicName.new\n assert record.a == 0\n assert record.b == 1\n end\n\n test :dynamic_update do\n record = RecordTest.DynamicName.new\n assert record.update_a(10 + &1).a == 10\n end\n\n test :is_record do\n assert is_record(RecordTest.FileInfo.new, RecordTest.FileInfo)\n refute is_record(a_list, RecordTest.FileInfo)\n refute is_record(RecordTest.FileInfo.new, List)\n end\n\n defp file_info do\n { :ok, file_info } = Erlang.file.read_file_info(__FILE__)\n file_info\n end\n\n defp a_list do\n [:a, :b, :c]\n end\nend\n","old_contents":"Code.require_file \"..\/test_helper\", __FILE__\n\ndefrecord RecordTest.FileInfo,\n Record.extract(:file_info, from_lib: \"kernel\/include\/file.hrl\")\n\nname = RecordTest.DynamicName\ndefrecord name, a: 0, b: 1\n\ndefmodule RecordTest do\n use ExUnit.Case\n\n test :record_constructor_with_dict do\n record = RecordTest.FileInfo.new(type: :regular)\n assert record.type == :regular\n assert record.access == nil\n end\n\n test :record_accessors do\n record = RecordTest.FileInfo.new(file_info)\n assert record.type == :regular\n assert record.access == :read_write\n\n new_record = record.access :read\n assert new_record.access == :read\n end\n\n test :dynamic_record_name do\n record = RecordTest.DynamicName.new\n assert record.a == 0\n assert record.b == 1\n end\n\n test :dynamic_update do\n record = RecordTest.DynamicName.new\n assert record.update_a(10 + &1).a == 10\n end\n\n test :is_record do\n assert is_record(RecordTest.FileInfo.new, RecordTest.FileInfo)\n refute is_record(a_list, RecordTest.FileInfo)\n refute is_record(RecordTest.FileInfo.new, List)\n end\n\n defp file_info do\n { :ok, file_info } = Erlang.file.read_file_info(__FILE__)\n file_info\n end\n\n defp a_list do\n [:a, :b, :c]\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"782162ac6bbdace2a57bd70410cc4d131c5a8329","subject":"Improve lookup\/3 typespec","message":"Improve lookup\/3 typespec\n","repos":"elixir-geolix\/adapter_mmdb2,elixir-geolix\/adapter_mmdb2","old_file":"lib\/mmdb2\/database.ex","new_file":"lib\/mmdb2\/database.ex","new_contents":"defmodule Geolix.Adapter.MMDB2.Database do\n @moduledoc false\n\n alias Geolix.Adapter.MMDB2.Result\n alias Geolix.Adapter.MMDB2.Storage\n alias MMDB2Decoder.Metadata\n\n @mmdb2_opts [double_precision: 8, float_precision: 4, map_keys: :atoms]\n\n @doc \"\"\"\n Performs a lookup in a loaded database.\n \"\"\"\n @spec lookup(:inet.ip_address(), Keyword.t(), %{id: atom}) :: map | nil\n def lookup(ip, opts, %{id: id}) do\n case Storage.get(id) do\n {meta, tree, data} when is_map(meta) and is_binary(tree) and is_binary(data) ->\n lookup(ip, meta, tree, data, opts)\n\n _ ->\n nil\n end\n end\n\n @doc \"\"\"\n Returns the metadata for a loaded database.\n \"\"\"\n @spec metadata(%{id: atom}) :: Metadata.t() | nil\n def metadata(%{id: id}) do\n case Storage.get(id) do\n {meta, _, _} when is_map(meta) ->\n meta\n\n _ ->\n nil\n end\n end\n\n defp lookup(ip, meta, tree, data, opts) do\n case MMDB2Decoder.lookup(ip, meta, tree, data, @mmdb2_opts) do\n {:ok, result} when is_map(result) ->\n result_as = Keyword.get(opts, :as, :struct)\n\n result\n |> Map.put(:ip_address, ip)\n |> maybe_to_struct(result_as, meta, opts)\n\n _ ->\n nil\n end\n end\n\n defp maybe_to_struct(result, :raw, _, _), do: result\n\n defp maybe_to_struct(result, :struct, %{database_type: type}, opts) do\n locale = Keyword.get(opts, :locale, :en)\n\n Result.to_struct(type, result, locale)\n end\nend\n","old_contents":"defmodule Geolix.Adapter.MMDB2.Database do\n @moduledoc false\n\n alias Geolix.Adapter.MMDB2.Result\n alias Geolix.Adapter.MMDB2.Storage\n alias MMDB2Decoder.Metadata\n\n @mmdb2_opts [double_precision: 8, float_precision: 4, map_keys: :atoms]\n\n @doc \"\"\"\n Performs a lookup in a loaded database.\n \"\"\"\n @spec lookup(tuple, Keyword.t(), map) :: map | nil\n def lookup(ip, opts, %{id: id}) do\n case Storage.get(id) do\n {meta, tree, data} when is_map(meta) and is_binary(tree) and is_binary(data) ->\n lookup(ip, meta, tree, data, opts)\n\n _ ->\n nil\n end\n end\n\n @doc \"\"\"\n Returns the metadata for a loaded database.\n \"\"\"\n @spec metadata(%{id: atom}) :: Metadata.t() | nil\n def metadata(%{id: id}) do\n case Storage.get(id) do\n {meta, _, _} when is_map(meta) ->\n meta\n\n _ ->\n nil\n end\n end\n\n defp lookup(ip, meta, tree, data, opts) do\n case MMDB2Decoder.lookup(ip, meta, tree, data, @mmdb2_opts) do\n {:ok, result} when is_map(result) ->\n result_as = Keyword.get(opts, :as, :struct)\n\n result\n |> Map.put(:ip_address, ip)\n |> maybe_to_struct(result_as, meta, opts)\n\n _ ->\n nil\n end\n end\n\n defp maybe_to_struct(result, :raw, _, _), do: result\n\n defp maybe_to_struct(result, :struct, %{database_type: type}, opts) do\n locale = Keyword.get(opts, :locale, :en)\n\n Result.to_struct(type, result, locale)\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"8b0097a50d4a73060d1dfe349a3b244eac014312","subject":"Cleanup Page documentation.","message":"Cleanup Page documentation.\n","repos":"shinyscorpion\/wobserver,shinyscorpion\/wobserver","old_file":"lib\/wobserver\/page.ex","new_file":"lib\/wobserver\/page.ex","new_contents":"defmodule Wobserver.Page do\n @moduledoc \"\"\"\n Page management for custom commands and pages in api and wobserver.\n \"\"\"\n\n alias Wobserver.Page\n\n @pages_table :wobserver_pages\n\n @typedoc ~S\"\"\"\n Accepted page formats.\n \"\"\"\n @type data ::\n Page.t\n | map\n | {String.t, atom, fun}\n | {String.t, atom, fun, boolean}\n\n @typedoc ~S\"\"\"\n Page structure.\n\n Fields:\n - `title`, the name of the page. Is used for the web interface menu.\n - `command`, single atom to associate the page with.\n - `callback`, function to be evaluated, when the a api is called or page is viewd.\n The result is converted to JSON and displayed.\n - `options`, map containing options for the page.\n\n Options:\n - `api_only` (`boolean`), if set to true the page won't show up in the web interface, but will only be available as API.\n - `refresh` (`float`, 0-1), sets the refresh time factor. Used in the web interface to refresh the data on the page. Set to `0` for no refresh.\n \"\"\"\n @type t :: %__MODULE__{\n title: String.t,\n command: atom,\n callback: fun,\n options: keyword,\n }\n\n defstruct [\n :title,\n :command,\n :callback,\n options: %{\n api_only: false,\n refresh: 1,\n },\n ]\n\n @doc ~S\"\"\"\n List all registered pages.\n\n For every page the following information is given:\n - `title`\n - `command`\n - `api_only`\n - `refresh`\n \"\"\"\n @spec list :: list(map)\n def list do\n ensure_table()\n\n @pages_table\n |> :ets.match(:\"$1\")\n |> Enum.map(fn [{command, %Page{title: title, options: options}}] ->\n %{\n title: title,\n command: command,\n api_only: options.api_only,\n refresh: options.refresh,\n }\n end)\n end\n\n @doc ~S\"\"\"\n Find the page for a given `command`\n\n Returns `:page_not_found`, if no page can be found.\n \"\"\"\n @spec find(command :: atom) :: Page.t\n def find(command) do\n ensure_table()\n\n case :ets.lookup(@pages_table, command) do\n [{^command, page}] -> page\n _ -> :page_not_found\n end\n end\n\n @doc ~S\"\"\"\n Calls the function associated with the `command`\/page.\n\n Returns the result of the function or `:page_not_found`, if the page can not be found.\n \"\"\"\n @spec call(Page.t | atom) :: any\n def call(:page_not_found), do: :page_not_found\n def call(%Page{callback: callback}), do: callback.()\n def call(command) when is_atom(command), do: command |> find() |> call()\n def call(_), do: :page_not_found\n\n @doc ~S\"\"\"\n Registers a `page` with `:wobserver`.\n\n Returns true if succesfully added. (otherwise false)\n\n The following inputs are accepted:\n - `{title, command, callback}`\n - `{title, command, callback, options}`\n - a `map` with the following fields:\n - `title`\n - `command`\n - `callback`\n - `options` (optional)\n\n The fields are used as followed:\n - `title`, the name of the page. Is used for the web interface menu.\n - `command`, single atom to associate the page with.\n - `callback`, function to be evaluated, when the a api is called or page is viewd.\n The result is converted to JSON and displayed.\n - `options`, options for the page.\n\n The following options can be set:\n - `api_only` (`boolean`), if set to true the page won't show up in the web interface, but will only be available as API.\n - `refresh` (`float`, 0-1), sets the refresh time factor. Used in the web interface to refresh the data on the page. Set to `0` for no refresh.\n \"\"\"\n @spec register(page :: Page.data) :: boolean\n def register(page)\n\n def register({title, command, callback}),\n do: register(title, command, callback)\n def register({title, command, callback, options}),\n do: register(title, command, callback, options)\n\n def register(page = %Page{}) do\n ensure_table()\n :ets.insert @pages_table, {page.command, page}\n end\n\n def register(%{title: t, command: command, callback: call, options: options}),\n do: register(t, command, call, options)\n def register(%{title: title, command: command, callback: callback}),\n do: register(title, command, callback)\n def register(_), do: false\n\n @doc ~S\"\"\"\n Registers a `page` with `:wobserver`.\n\n The arguments are used as followed:\n - `title`, the name of the page. Is used for the web interface menu.\n - `command`, single atom to associate the page with.\n - `callback`, function to be evaluated, when the a api is called or page is viewd.\n The result is converted to JSON and displayed.\n - `options`, options for the page.\n\n The following options can be set:\n - `api_only` (`boolean`), if set to true the page won't show up in the web interface, but will only be available as API.\n - `refresh` (`float`, 0-1), sets the refresh time factor. Used in the web interface to refresh the data on the page. Set to `0` for no refresh.\n \"\"\"\n @spec register(\n title :: String.t,\n command :: atom,\n callback :: fun,\n options :: keyword\n ) :: boolean\n def register(title, command, callback, options \\\\ []) do\n register(%Page{\n title: title,\n command: command,\n callback: callback,\n options: %{\n api_only: Keyword.get(options, :api_only, false),\n refresh: Keyword.get(options, :refresh, 1.0)\n },\n })\n end\n\n @doc ~S\"\"\"\n Loads custom pages from configuration and adds them to `:wobserver`.\n\n To add custom pages set the `:pages` option.\n The `:pages` option must be a list of page data.\n\n The page data can be formatted as:\n - `{title, command, callback}`\n - `{title, command, callback, options}`\n - a `map` with the following fields:\n - `title`\n - `command`\n - `callback`\n - `options` (optional)\n\n For more information and types see: `Wobserver.Page.register\/1`.\n\n Example:\n ```elixir\n config :wobserver,\n pages: [\n {\"Example\", :example, fn -> %{x: 9} end}\n ]\n ```\n \"\"\"\n @spec load_config :: [any]\n def load_config do\n ensure_table()\n\n :wobserver\n |> Application.get_env(:pages, [])\n |> Enum.map(®ister\/1)\n end\n\n # Helpers\n\n defp ensure_table do\n case :ets.info(@pages_table) do\n :undefined ->\n :ets.new @pages_table, [:named_table, :public]\n true\n _ ->\n true\n end\n end\nend\n","old_contents":"defmodule Wobserver.Page do\n @moduledoc \"\"\"\n Page management for custom commands and pages in api and wobserver.\n \"\"\"\n\n alias Wobserver.Page\n\n @pages_table :wobserver_pages\n\n @typedoc ~S\"\"\"\n Accepted page formats.\n \"\"\"\n @type data ::\n Page.t\n | map\n | {String.t, atom, fun}\n | {String.t, atom, fun, boolean}\n\n @typedoc ~S\"\"\"\n Page structure.\n\n Fields:\n - `title`, the name of the page. Is used for the web interface menu.\n - `command`, single atom to associate the page with.\n - `callback`, function to be evaluated, when the a api is called or page is viewd.\n The result is converted to JSON and displayed.\n - `options`, map containing options for the page.\n\n Options:\n - `api_only` (`boolean`), if set to true the page won't show up in the web interface, but will only be available as API.\n - `refresh` (`float`, 0-1), sets the refresh time factor. Used in the web interface to refresh the data on the page. Set to `0` for no refresh.\n \"\"\"\n @type t :: %__MODULE__{\n title: String.t,\n command: atom,\n callback: fun,\n options: keyword,\n }\n\n defstruct [\n :title,\n :command,\n :callback,\n options: %{\n api_only: false,\n refresh: 1,\n },\n ]\n\n @doc ~S\"\"\"\n List all registered pages.\n\n For every page the following information is given:\n - `title`\n - `command`\n - `api_only`\n - `refresh`\n \"\"\"\n @spec list :: list(map)\n def list do\n ensure_table()\n\n @pages_table\n |> :ets.match(:\"$1\")\n |> Enum.map(fn [{command, %Page{title: title, options: options}}] ->\n %{\n title: title,\n command: command,\n api_only: options.api_only,\n refresh: options.refresh,\n }\n end)\n end\n\n @doc ~S\"\"\"\n Find the page for a given command.\n\n Returns `:page_not_found`, if no page can be found.\n \"\"\"\n @spec find(command :: atom) :: Page.t\n def find(command) do\n ensure_table()\n\n case :ets.lookup(@pages_table, command) do\n [{^command, page}] -> page\n _ -> :page_not_found\n end\n end\n\n @doc ~S\"\"\"\n Calls the function associated with the command\/page.\n\n Returns the result of the function or `:page_not_found`, if the page can not be found.\n \"\"\"\n @spec call(Page.t | atom) :: any\n def call(:page_not_found), do: :page_not_found\n def call(%Page{callback: callback}), do: callback.()\n def call(command) when is_atom(command), do: command |> find() |> call()\n def call(_), do: :page_not_found\n\n @doc ~S\"\"\"\n Registers a page with `:wobserver`.\n\n Returns true if succesfully added. (otherwise false)\n\n The following inputs are accepted:\n - `{title, command, callback}`\n - `{title, command, callback, options}`\n - a `map` with the following fields:\n - `title`\n - `command`\n - `callback`\n - `options` (optional)\n\n The fields are used as followed:\n - `title`, the name of the page. Is used for the web interface menu.\n - `command`, single atom to associate the page with.\n - `callback`, function to be evaluated, when the a api is called or page is viewd.\n The result is converted to JSON and displayed.\n - `options`, options for the page.\n\n The following options can be set:\n - `api_only` (`boolean`), if set to true the page won't show up in the web interface, but will only be available as API.\n - `refresh` (`float`, 0-1), sets the refresh time factor. Used in the web interface to refresh the data on the page. Set to `0` for no refresh.\n \"\"\"\n @spec register(page :: Page.data) :: boolean\n def register(page)\n\n def register({title, command, callback}),\n do: register(title, command, callback)\n def register({title, command, callback, options}),\n do: register(title, command, callback, options)\n\n def register(page = %Page{}) do\n ensure_table()\n :ets.insert @pages_table, {page.command, page}\n end\n\n def register(%{title: t, command: command, callback: call, options: options}),\n do: register(t, command, call, options)\n def register(%{title: title, command: command, callback: callback}),\n do: register(title, command, callback)\n def register(_), do: false\n\n @doc ~S\"\"\"\n Registers a page with `:wobserver`.\n\n For more information and types see: `Wobserver.Page.register\/1`.\n \"\"\"\n @spec register(\n title :: String.t,\n command :: atom,\n callback :: fun,\n options :: keyword\n ) :: boolean\n def register(title, command, callback, options \\\\ []) do\n register(%Page{\n title: title,\n command: command,\n callback: callback,\n options: %{\n api_only: Keyword.get(options, :api_only, false),\n refresh: Keyword.get(options, :refresh, 1.0)\n },\n })\n end\n\n @doc ~S\"\"\"\n Loads custom pages from configuration and adds them to `:wobserver`.\n\n To add custom pages set the `:pages` option.\n The `:pages` option must be a list of page data.\n\n The page data can be formatted as:\n - `{title, command, callback}`\n - `{title, command, callback, options}`\n - a `map` with the following fields:\n - `title`\n - `command`\n - `callback`\n - `options` (optional)\n\n For more information and types see: `Wobserver.Page.register\/1`.\n\n Example:\n ```elixir\n config :wobserver,\n pages: [\n {\"Example\", :example, fn -> %{x: 9} end}\n ]\n ```\n \"\"\"\n @spec load_config :: [any]\n def load_config do\n ensure_table()\n\n :wobserver\n |> Application.get_env(:pages, [])\n |> Enum.map(®ister\/1)\n end\n\n # Helpers\n\n defp ensure_table do\n case :ets.info(@pages_table) do\n :undefined ->\n :ets.new @pages_table, [:named_table, :public]\n true\n _ ->\n true\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"7826ae785fb5458aeb345f803c52481b83a1c0a4","subject":"Improve formatting and naming","message":"Improve formatting and naming\n","repos":"PragTob\/benchee","old_file":"lib\/benchee\/formatters\/console.ex","new_file":"lib\/benchee\/formatters\/console.ex","new_contents":"defmodule Benchee.Formatters.Console do\n @moduledoc \"\"\"\n Formatter to transform the statistics output into a structure suitable for\n output through `IO.puts` on the console.\n \"\"\"\n\n alias Benchee.Statistics\n alias Benchee.Unit.{Count, Duration}\n\n @default_label_width 4 # Length of column header\n @ips_width 13\n @average_width 15\n @deviation_width 13\n @median_width 15\n\n @doc \"\"\"\n \b\bFormats the benchmark statistis using `Benchee.Formatters.Console.format\/1`\n and then prints it out directly to the console using `IO.puts\/2`\n \"\"\"\n def output(suite) do\n suite\n |> format\n |> IO.puts\n end\n\n @doc \"\"\"\n Formats the benchmark statistics to a report suitable for output on the CLI.\n\n ## Examples\n\n ```\n iex> jobs = %{\"My Job\" => %{average: 200.0, ips: 5000.0, std_dev_ratio: 0.1, median: 190.0}}\n iex> Benchee.Formatters.Console.format(%{statistics: jobs, config: %{print: %{comparison: false}}})\n [\"\\nName ips average deviation median\\n\",\n \"My Job 5.00 K 200.00 \u03bcs (\u00b110.00%) 190.00 \u03bcs\"]\n\n ```\n\n \"\"\"\n def format(%{statistics: job_stats, config: config}) do\n sorted_stats = Statistics.sort(job_stats)\n units = units(sorted_stats)\n label_width = label_width job_stats\n [column_descriptors(label_width) | job_reports(sorted_stats, units, label_width)\n ++ comparison_report(sorted_stats, units, label_width, config)]\n |> remove_last_blank_line\n end\n\n defp column_descriptors(label_width) do\n \"\\n~*s~*s~*s~*s~*s\\n\"\n |> :io_lib.format([-label_width, \"Name\", @ips_width, \"ips\",\n @average_width, \"average\",\n @deviation_width, \"deviation\", @median_width, \"median\"])\n |> to_string\n end\n\n defp label_width(jobs) do\n max_label_width = jobs\n |> Enum.map(fn({job_name, _}) -> String.length(job_name) end)\n |> Stream.concat([@default_label_width])\n |> Enum.max\n max_label_width + 1\n end\n\n defp job_reports(jobs, units, label_width) do\n Enum.map(jobs, fn(job) -> format_job job, units, label_width end)\n end\n\n defp units(jobs) do\n # Produces a map like\n # %{run_time: [12345, 15431, 13222], ips: [1, 2, 3]}\n collected_values =\n jobs\n |> Enum.flat_map(fn({_name, job}) -> Map.to_list(job) end)\n # TODO: Simplify when dropping support for 1.2\n # For compatibility with Elixir 1.2. In 1.3, the following group-reduce-map\n # can b replaced by a single call to `group_by\/3`\n # Enum.group_by(fn({stat_name, _}) -> stat_name end, fn({_, value}) -> value end)\n |> Enum.group_by(fn({stat_name, _value}) -> stat_name end)\n |> Enum.reduce(%{}, fn({stat_name, occurrences}, acc) ->\n Map.put(acc, stat_name, Enum.map(occurrences, fn({_stat_name, value}) -> value end))\n end)\n\n %{\n run_time: Duration.best(collected_values.average),\n ips: Count.best(collected_values.ips),\n }\n end\n\n defp format_job({name, %{average: average,\n ips: ips,\n std_dev_ratio: std_dev_ratio,\n median: median}\n },\n %{run_time: run_time_unit,\n ips: ips_unit,\n }, label_width) do\n \"~*s~*ts~*ts~*ts~*ts\\n\"\n |> :io_lib.format([-label_width, name, @ips_width, ips_out(ips, ips_unit),\n @average_width, run_time_out(average, run_time_unit),\n @deviation_width, deviation_out(std_dev_ratio),\n @median_width, run_time_out(median, run_time_unit)])\n |> to_string\n end\n\n defp ips_out(ips, unit) do\n Count.format(Count.scale(ips, unit))\n end\n\n defp run_time_out(average, unit) do\n Duration.format(Duration.scale(average, unit))\n end\n\n defp deviation_out(std_dev_ratio) do\n \"(~ts~.2f%)\"\n |> :io_lib.format([\"\u00b1\", std_dev_ratio * 100.0])\n |> to_string\n end\n\n defp comparison_report([_reference], _, _, _config) do\n [] # No need for a comparison when only one benchmark was run\n end\n defp comparison_report(_, _, _, %{console: %{comparison: false}}) do\n []\n end\n defp comparison_report([reference | other_jobs], units, label_width, _config) do\n [\n comparison_descriptor,\n reference_report(reference, units, label_width) |\n comparisons(reference, units, label_width, other_jobs)\n ]\n end\n\n defp reference_report({name, %{ips: ips}}, %{ips: ips_unit}, label_width) do\n \"~*s~*s\\n\"\n |> :io_lib.format([-label_width, name, @ips_width, ips_out(ips, ips_unit)])\n |> to_string\n end\n\n defp comparisons({_, reference_stats}, units, label_width, jobs_to_compare) do\n Enum.map jobs_to_compare, fn(job = {_, job_stats}) ->\n format_comparison(job, units, label_width, (reference_stats.ips \/ job_stats.ips))\n end\n end\n\n defp format_comparison({name, %{ips: ips}}, %{ips: ips_unit}, label_width, times_slower) do\n \"~*s~*s - ~.2fx slower\\n\"\n |> :io_lib.format([-label_width, name, @ips_width, ips_out(ips, ips_unit), times_slower])\n |> to_string\n end\n\n defp comparison_descriptor do\n \"\\nComparison: \\n\"\n end\n\n defp remove_last_blank_line([head]) do\n [String.rstrip(head)]\n end\n defp remove_last_blank_line([head | tail]) do\n [head | remove_last_blank_line(tail)]\n end\n\nend\n","old_contents":"defmodule Benchee.Formatters.Console do\n @moduledoc \"\"\"\n Formatter to transform the statistics output into a structure suitable for\n output through `IO.puts` on the console.\n \"\"\"\n\n alias Benchee.Statistics\n alias Benchee.Unit.{Count, Duration}\n\n @default_label_width 4 # Length of column header\n @ips_width 13\n @average_width 15\n @deviation_width 13\n @median_width 15\n\n @doc \"\"\"\n \b\bFormats the benchmark statistis using `Benchee.Formatters.Console.format\/1`\n and then prints it out directly to the console using `IO.puts\/2`\n \"\"\"\n def output(suite) do\n suite\n |> format\n |> IO.puts\n end\n\n @doc \"\"\"\n Formats the benchmark statistics to a report suitable for output on the CLI.\n\n ## Examples\n\n ```\n iex> jobs = %{\"My Job\" => %{average: 200.0, ips: 5000.0, std_dev_ratio: 0.1, median: 190.0}}\n iex> Benchee.Formatters.Console.format(%{statistics: jobs, config: %{print: %{comparison: false}}})\n [\"\\nName ips average deviation median\\n\",\n \"My Job 5.00 K 200.00 \u03bcs (\u00b110.00%) 190.00 \u03bcs\"]\n\n ```\n\n \"\"\"\n def format(%{statistics: job_stats, config: config}) do\n sorted_stats = Statistics.sort(job_stats)\n units = units(sorted_stats)\n label_width = label_width job_stats\n [column_descriptors(label_width) | job_reports(sorted_stats, units, label_width)\n ++ comparison_report(sorted_stats, units, label_width, config)]\n |> remove_last_blank_line\n end\n\n defp column_descriptors(label_width) do\n \"\\n~*s~*s~*s~*s~*s\\n\"\n |> :io_lib.format([-label_width, \"Name\", @ips_width, \"ips\",\n @average_width, \"average\",\n @deviation_width, \"deviation\", @median_width, \"median\"])\n |> to_string\n end\n\n defp label_width(jobs) do\n max_label_width = jobs\n |> Enum.map(fn({job_name, _}) -> String.length(job_name) end)\n |> Stream.concat([@default_label_width])\n |> Enum.max\n max_label_width + 1\n end\n\n defp job_reports(jobs, units, label_width) do\n Enum.map(jobs, fn(job) -> format_job job, units, label_width end)\n end\n\n defp units(jobs) do\n # Produces a map like\n # %{run_time: [12345, 15431, 13222], ips: [1, 2, 3]}\n collected_values = jobs\n |> Enum.flat_map(fn({_name, job}) -> Map.to_list(job) end)\n # TODO: Simplify when dropping support for 1.2\n # For compatibility with Elixir 1.2. In 1.3, the following group-reduce-map\n # can b replaced by a single call to `group_by\/3`\n # Enum.group_by(fn({measurement, _}) -> measurement end, fn({_, value}) -> value end)\n |> Enum.group_by(fn({measurement, _unit}) -> measurement end)\n |> Enum.reduce(%{}, fn({measurement, occurrences}, acc) ->\n Map.put(acc, measurement, Enum.map(occurrences, fn({_meas, value}) -> value end))\n end)\n\n %{\n run_time: Duration.best(collected_values.average),\n ips: Count.best(collected_values.ips),\n }\n end\n\n defp format_job({name, %{average: average,\n ips: ips,\n std_dev_ratio: std_dev_ratio,\n median: median}\n },\n %{run_time: run_time_unit,\n ips: ips_unit,\n }, label_width) do\n \"~*s~*ts~*ts~*ts~*ts\\n\"\n |> :io_lib.format([-label_width, name, @ips_width, ips_out(ips, ips_unit),\n @average_width, run_time_out(average, run_time_unit),\n @deviation_width, deviation_out(std_dev_ratio),\n @median_width, run_time_out(median, run_time_unit)])\n |> to_string\n end\n\n defp ips_out(ips, unit) do\n Count.format(Count.scale(ips, unit))\n end\n\n defp run_time_out(average, unit) do\n Duration.format(Duration.scale(average, unit))\n end\n\n defp deviation_out(std_dev_ratio) do\n \"(~ts~.2f%)\"\n |> :io_lib.format([\"\u00b1\", std_dev_ratio * 100.0])\n |> to_string\n end\n\n defp comparison_report([_reference], _, _, _config) do\n [] # No need for a comparison when only one benchmark was run\n end\n defp comparison_report(_, _, _, %{console: %{comparison: false}}) do\n []\n end\n defp comparison_report([reference | other_jobs], units, label_width, _config) do\n [\n comparison_descriptor,\n reference_report(reference, units, label_width) |\n comparisons(reference, units, label_width, other_jobs)\n ]\n end\n\n defp reference_report({name, %{ips: ips}}, %{ips: ips_unit}, label_width) do\n \"~*s~*s\\n\"\n |> :io_lib.format([-label_width, name, @ips_width, ips_out(ips, ips_unit)])\n |> to_string\n end\n\n defp comparisons({_, reference_stats}, units, label_width, jobs_to_compare) do\n Enum.map jobs_to_compare, fn(job = {_, job_stats}) ->\n format_comparison(job, units, label_width, (reference_stats.ips \/ job_stats.ips))\n end\n end\n\n defp format_comparison({name, %{ips: ips}}, %{ips: ips_unit}, label_width, times_slower) do\n \"~*s~*s - ~.2fx slower\\n\"\n |> :io_lib.format([-label_width, name, @ips_width, ips_out(ips, ips_unit), times_slower])\n |> to_string\n end\n\n defp comparison_descriptor do\n \"\\nComparison: \\n\"\n end\n\n defp remove_last_blank_line([head]) do\n [String.rstrip(head)]\n end\n defp remove_last_blank_line([head | tail]) do\n [head | remove_last_blank_line(tail)]\n end\n\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"aa735deee30a2b002d1949ea566d61e510984bdc","subject":"Remove commented code","message":"Remove commented code\n","repos":"milmazz\/ex_doc_epub","old_file":"lib\/ex_doc_epub\/formatter\/epub.ex","new_file":"lib\/ex_doc_epub\/formatter\/epub.ex","new_contents":"defmodule ExDocEPUB.Formatter.EPUB do\n @moduledoc \"\"\"\n Provide EPUB documentation\n \"\"\"\n\n alias ExDoc.Formatter.HTML\n alias ExDocEPUB.Formatter.EPUB.Templates\n\n @doc \"\"\"\n Generate EPUB documentation for the given modules\n \"\"\"\n @spec run(list, %ExDoc.Config{}) :: String.t\n def run(module_nodes, config) when is_map(config) do\n output = Path.expand(config.output)\n File.rm_rf!(output)\n :ok = File.mkdir_p(\"#{output}\/OEBPS\")\n\n generate_assets(output, config)\n\n all = HTML.Autolink.all(module_nodes)\n modules = HTML.filter_list(:modules, all)\n exceptions = HTML.filter_list(:exceptions, all)\n protocols = HTML.filter_list(:protocols, all)\n\n generate_mimetype(output)\n generate_container(output)\n generate_content(output, config, all)\n generate_toc(output, config, all)\n generate_title(output, config)\n generate_list(output, config, modules)\n generate_list(output, config, exceptions)\n generate_list(output, config, protocols)\n\n #generate_epub(output)\n #File.rm_rf!(output)\n end\n\n defp templates_path(other) do\n Path.expand(\"epub\/templates\/#{other}\", __DIR__)\n end\n\n defp assets do\n [{ templates_path(\"css\/*.css\"), \".\" }]\n end\n\n defp generate_assets(output, _config) do\n Enum.each assets, fn({pattern, _dir}) ->\n Enum.map Path.wildcard(pattern), fn(file) ->\n base = Path.basename(file)\n File.copy(file, \"#{output}\/OEBPS\/#{base}\")\n end\n end\n end\n\n defp generate_mimetype(output) do\n content = \"application\/epub+zip\"\n File.write(\"#{output}\/mimetype\", content)\n end\n\n defp generate_container(output) do\n content = Templates.container_template()\n File.mkdir_p(\"#{output}\/META-INF\")\n File.write(\"#{output}\/META-INF\/container.xml\", content)\n end\n\n defp generate_content(output, config, all) do\n content = Templates.content_template(config, all)\n File.write(\"#{output}\/OEBPS\/content.opf\", content)\n end\n\n defp generate_toc(output, config, all) do\n content = Templates.toc_template(config, all)\n File.write(\"#{output}\/OEBPS\/toc.ncx\", content)\n end\n\n defp generate_title(output, config) do\n content = Templates.title_template(config)\n File.write(\"#{output}\/OEBPS\/title.html\", content)\n end\n\n defp generate_list(output, config, nodes) do\n File.mkdir_p(\"#{output}\/OEBPS\/modules\")\n nodes\n |> Enum.map(&Task.async(fn -> generate_module_page(output, config, &1) end))\n |> Enum.map(&Task.await\/1)\n end\n\n defp generate_module_page(output, config, node) do\n content = Templates.module_page(config, node)\n File.write(\"#{output}\/OEBPS\/modules\/#{node.id}.html\", content)\n end\n\n #defp generate_epub(output) do\n #zip -0Xq book.epub mimetype\n #zip -Xr9Dq book.epub *\n #project = \"elixir.epub\"\n #{:ok, _} = :zip.create(String.to_char_list(project),\n # files_to_add(output),\n # uncompress: ['mimetype'])\n #:ok\n #end\nend\n","old_contents":"defmodule ExDocEPUB.Formatter.EPUB do\n @moduledoc \"\"\"\n Provide EPUB documentation\n \"\"\"\n\n alias ExDoc.Formatter.HTML\n alias ExDocEPUB.Formatter.EPUB.Templates\n\n @doc \"\"\"\n Generate EPUB documentation for the given modules\n \"\"\"\n @spec run(list, %ExDoc.Config{}) :: String.t\n def run(module_nodes, config) when is_map(config) do\n output = Path.expand(config.output)\n File.rm_rf!(output)\n :ok = File.mkdir_p(\"#{output}\/OEBPS\")\n\n generate_assets(output, config)\n\n all = HTML.Autolink.all(module_nodes)\n modules = HTML.filter_list(:modules, all)\n exceptions = HTML.filter_list(:exceptions, all)\n protocols = HTML.filter_list(:protocols, all)\n\n #has_readme = config.readme && generate_readme(output, module_nodes, config, modules, exceptions, protocols)\n #generate_overview(modules, exceptions, protocols, output, config, has_readme)\n\n generate_mimetype(output)\n generate_container(output)\n generate_content(output, config, all)\n generate_toc(output, config, all)\n generate_title(output, config)\n generate_list(output, config, modules)\n generate_list(output, config, exceptions)\n generate_list(output, config, protocols)\n\n #generate_epub(output)\n #File.rm_rf!(output)\n end\n\n #defp generate_overview(modules, exceptions, protocols, output, config, has_readme) do\n # content = Templates.overview_template(config, modules, exceptions, protocols, has_readme)\n # :ok = File.write(\"#{output}\/overview.html\", content)\n #end\n\n defp templates_path(other) do\n Path.expand(\"epub\/templates\/#{other}\", __DIR__)\n end\n\n defp assets do\n [{ templates_path(\"css\/*.css\"), \".\" }]\n end\n\n defp generate_assets(output, _config) do\n Enum.each assets, fn({pattern, _dir}) ->\n Enum.map Path.wildcard(pattern), fn(file) ->\n base = Path.basename(file)\n File.copy(file, \"#{output}\/OEBPS\/#{base}\")\n end\n end\n end\n\n defp generate_mimetype(output) do\n content = \"application\/epub+zip\"\n File.write(\"#{output}\/mimetype\", content)\n end\n\n defp generate_container(output) do\n content = Templates.container_template()\n File.mkdir_p(\"#{output}\/META-INF\")\n File.write(\"#{output}\/META-INF\/container.xml\", content)\n end\n\n defp generate_content(output, config, all) do\n content = Templates.content_template(config, all)\n File.write(\"#{output}\/OEBPS\/content.opf\", content)\n end\n\n defp generate_toc(output, config, all) do\n content = Templates.toc_template(config, all)\n File.write(\"#{output}\/OEBPS\/toc.ncx\", content)\n end\n\n defp generate_title(output, config) do\n content = Templates.title_template(config)\n File.write(\"#{output}\/OEBPS\/title.html\", content)\n end\n\n defp generate_list(output, config, nodes) do\n File.mkdir_p(\"#{output}\/OEBPS\/modules\")\n nodes\n |> Enum.map(&Task.async(fn -> generate_module_page(output, config, &1) end))\n |> Enum.map(&Task.await\/1)\n end\n\n defp generate_module_page(output, config, node) do\n content = Templates.module_page(config, node)\n File.write(\"#{output}\/OEBPS\/modules\/#{node.id}.html\", content)\n end\n\n #defp generate_epub(output) do\n #zip -0Xq book.epub mimetype\n #zip -Xr9Dq book.epub *\n #project = \"elixir.epub\"\n #{:ok, _} = :zip.create(String.to_char_list(project),\n # files_to_add(output),\n # uncompress: ['mimetype'])\n #:ok\n #end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"b03f06986177dd83092308a283f1b564bf4605b0","subject":"Set the manager before going into the dep","message":"Set the manager before going into the dep\n","repos":"kimshrier\/elixir,gfvcastro\/elixir,michalmuskala\/elixir,pedrosnk\/elixir,kelvinst\/elixir,lexmag\/elixir,ggcampinho\/elixir,kelvinst\/elixir,gfvcastro\/elixir,antipax\/elixir,beedub\/elixir,lexmag\/elixir,elixir-lang\/elixir,joshprice\/elixir,pedrosnk\/elixir,beedub\/elixir,antipax\/elixir,kimshrier\/elixir,ggcampinho\/elixir","old_file":"lib\/mix\/lib\/mix\/deps\/retriever.ex","new_file":"lib\/mix\/lib\/mix\/deps\/retriever.ex","new_contents":"# This module is responsible for retrieving\n# dependencies of a given project. This\n# module and its functions are private to Mix.\ndefmodule Mix.Deps.Retriever do\n @moduledoc false\n\n @doc \"\"\"\n Gets all direct children of the current `Mix.Project`\n as a `Mix.Dep` record. Umbrella project dependencies\n are included as children.\n \"\"\"\n def children do\n scms = Mix.SCM.available\n from = current_source(:mix)\n Enum.map(Mix.project[:deps] || [], &to_dep(&1, scms, from)) ++\n Mix.Deps.Umbrella.children\n end\n\n @doc \"\"\"\n Fetches the given dependency information, including its\n latest status and children.\n \"\"\"\n def fetch(dep, config) do\n Mix.Dep[manager: manager, scm: scm, opts: opts] = dep\n dep = dep.status(scm_status(scm, opts))\n\n validate_app(cond do\n not ok?(dep.status) ->\n dep\n\n manager == :rebar ->\n rebar_dep(dep, config)\n\n mixfile?(dep) ->\n mix_dep(dep.manager(:mix), config)\n\n rebarconfig?(dep) or rebarexec?(dep) ->\n rebar_dep(dep.manager(:rebar), config)\n\n makefile?(dep) ->\n dep.manager(:make)\n\n true ->\n mix_dep(dep.manager(:mix), config)\n end)\n end\n\n ## Helpers\n\n defp current_source(manager) do\n case manager do\n :mix -> \"mix.exs\"\n :rebar -> \"rebar.config\"\n end |> Path.absname\n end\n\n defp to_dep(tuple, scms, from, manager \/\/ nil) do\n dep = with_scm_and_app(tuple, scms).from(from).manager(manager)\n\n if match?({ _, req, _ } when is_regex(req), tuple) and\n not String.ends_with?(from, \"rebar.config\") do\n invalid_dep_format(tuple)\n end\n\n dep\n end\n\n defp mix_dep(Mix.Dep[opts: opts, app: app, status: status] = dep, config) do\n Mix.Deps.in_dependency(dep, config, fn _ ->\n default =\n if Mix.Project.umbrella? do\n false\n else\n Path.join(Mix.project[:compile_path], \"#{app}.app\")\n end\n\n opts = Keyword.put_new(opts, :app, default)\n stat = if vsn = old_elixir_lock(), do: { :elixirlock, vsn }, else: status\n dep.manager(:mix).opts(opts).deps(children).status(stat)\n end)\n end\n\n defp rebar_dep(Mix.Dep[] = dep, config) do\n Mix.Deps.in_dependency(dep, config, fn _ ->\n config = Mix.Rebar.load_config(\".\")\n extra = Dict.take(config, [:sub_dirs])\n dep.manager(:rebar).extra(extra).deps(rebar_children(config))\n end)\n end\n\n defp rebar_children(root_config) do\n scms = Mix.SCM.available\n from = current_source(:rebar)\n Mix.Rebar.recur(root_config, fn config ->\n Mix.Rebar.deps(config) |> Enum.map(&to_dep(&1, scms, from, :rebar))\n end) |> Enum.concat\n end\n\n defp with_scm_and_app({ app, opts }, scms) when is_atom(app) and is_list(opts) do\n with_scm_and_app({ app, nil, opts }, scms)\n end\n\n defp with_scm_and_app({ app, req, opts }, scms) when is_atom(app) and\n (is_binary(req) or is_regex(req) or req == nil) and is_list(opts) do\n\n path = Path.join(Mix.project[:deps_path], app)\n opts = Keyword.put(opts, :dest, path)\n\n { scm, opts } = Enum.find_value scms, { nil, [] }, fn(scm) ->\n (new = scm.accepts_options(app, opts)) && { scm, new }\n end\n\n if scm do\n Mix.Dep[\n scm: scm,\n app: app,\n requirement: req,\n status: scm_status(scm, opts),\n opts: opts\n ]\n else\n raise Mix.Error, message: \"#{inspect Mix.Project.get} did not specify a supported scm \" <>\n \"for app #{inspect app}, expected one of :git, :path or :in_umbrella\"\n end\n end\n\n defp with_scm_and_app(other, _scms) do\n invalid_dep_format(other)\n end\n\n defp scm_status(scm, opts) do\n if scm.checked_out? opts do\n { :ok, nil }\n else\n { :unavailable, opts[:dest] }\n end\n end\n\n defp validate_app(Mix.Dep[opts: opts, requirement: req, app: app, status: status] = dep) do\n opts_app = opts[:app]\n\n if not ok?(status) or opts_app == false do\n dep\n else\n path = if is_binary(opts_app), do: opts_app, else: \"ebin\/#{app}.app\"\n path = Path.expand(path, opts[:dest])\n dep.status app_status(path, app, req)\n end\n end\n\n defp app_status(app_path, app, req) do\n case :file.consult(app_path) do\n { :ok, [{ :application, ^app, config }] } ->\n case List.keyfind(config, :vsn, 0) do\n { :vsn, actual } when is_list(actual) ->\n actual = iolist_to_binary(actual)\n if vsn_match?(req, actual) do\n { :ok, actual }\n else\n { :nomatchvsn, actual }\n end\n { :vsn, actual } ->\n { :invalidvsn, actual }\n nil ->\n { :invalidvsn, nil }\n end\n { :ok, _ } -> { :invalidapp, app_path }\n { :error, _ } -> { :noappfile, app_path }\n end\n end\n\n defp vsn_match?(nil, _actual), do: true\n defp vsn_match?(req, actual) when is_regex(req), do: actual =~ req\n defp vsn_match?(req, actual) when is_binary(req) do\n Version.match?(actual, req)\n end\n\n defp mixfile?(dep) do\n File.regular?(Path.join(dep.opts[:dest], \"mix.exs\"))\n end\n\n defp rebarexec?(dep) do\n File.regular?(Path.join(dep.opts[:dest], \"rebar\"))\n end\n\n defp rebarconfig?(dep) do\n Enum.any?([\"rebar.config\", \"rebar.config.script\"], fn file ->\n File.regular?(Path.join(dep.opts[:dest], file))\n end)\n end\n\n defp makefile?(dep) do\n File.regular? Path.join(dep.opts[:dest], \"Makefile\")\n end\n\n defp ok?({ :ok, _ }), do: true\n defp ok?(_), do: false\n\n defp invalid_dep_format(dep) do\n raise Mix.Error, message: %s(Dependency specified in the wrong format: #{inspect dep}, ) <>\n %s(expected { app :: atom, opts :: Keyword.t } | { app :: atom, requirement :: String.t, opts :: Keyword.t })\n end\n\n defp old_elixir_lock do\n old_vsn = Mix.Deps.Lock.elixir_vsn\n if old_vsn && old_vsn != System.version do\n old_vsn\n end\n end\nend\n","old_contents":"# This module is responsible for retrieving\n# dependencies of a given project. This\n# module and its functions are private to Mix.\ndefmodule Mix.Deps.Retriever do\n @moduledoc false\n\n @doc \"\"\"\n Gets all direct children of the current `Mix.Project`\n as a `Mix.Dep` record. Umbrella project dependencies\n are included as children.\n \"\"\"\n def children do\n scms = Mix.SCM.available\n from = current_source(:mix)\n Enum.map(Mix.project[:deps] || [], &to_dep(&1, scms, from)) ++\n Mix.Deps.Umbrella.children\n end\n\n @doc \"\"\"\n Fetches the given dependency information, including its\n latest status and children.\n \"\"\"\n def fetch(dep, config) do\n Mix.Dep[manager: manager, scm: scm, opts: opts] = dep\n dep = dep.status(scm_status(scm, opts))\n\n validate_app(cond do\n not ok?(dep.status) ->\n dep\n\n manager == :rebar ->\n rebar_dep(dep, config)\n\n mixfile?(dep) ->\n mix_dep(dep, config)\n\n rebarconfig?(dep) or rebarexec?(dep) ->\n rebar_dep(dep, config)\n\n makefile?(dep) ->\n make_dep(dep)\n\n true ->\n mix_dep(dep, config)\n end)\n end\n\n ## Helpers\n\n defp current_source(manager) do\n case manager do\n :mix -> \"mix.exs\"\n :rebar -> \"rebar.config\"\n end |> Path.absname\n end\n\n defp to_dep(tuple, scms, from, manager \/\/ nil) do\n dep = with_scm_and_app(tuple, scms).from(from).manager(manager)\n\n if match?({ _, req, _ } when is_regex(req), tuple) and\n not String.ends_with?(from, \"rebar.config\") do\n invalid_dep_format(tuple)\n end\n\n dep\n end\n\n defp mix_dep(Mix.Dep[opts: opts, app: app, status: status] = dep, config) do\n Mix.Deps.in_dependency(dep, config, fn _ ->\n default =\n if Mix.Project.umbrella? do\n false\n else\n Path.join(Mix.project[:compile_path], \"#{app}.app\")\n end\n\n opts = Keyword.put_new(opts, :app, default)\n stat = if vsn = old_elixir_lock(), do: { :elixirlock, vsn }, else: status\n dep.manager(:mix).opts(opts).deps(children).status(stat)\n end)\n end\n\n defp rebar_dep(Mix.Dep[opts: opts] = dep, config) do\n Mix.Deps.in_dependency(dep, config, fn _ ->\n config = Mix.Rebar.load_config(opts[:dest])\n extra = Dict.take(config, [:sub_dirs])\n dep.manager(:rebar).extra(extra).deps(rebar_children(config))\n end)\n end\n\n defp rebar_children(root_config) do\n scms = Mix.SCM.available\n from = current_source(:rebar)\n Mix.Rebar.recur(root_config, fn config ->\n Mix.Rebar.deps(config) |> Enum.map(&to_dep(&1, scms, from, :rebar))\n end) |> Enum.concat\n end\n\n defp make_dep(Mix.Dep[] = dep) do\n dep.manager(:make)\n end\n\n defp with_scm_and_app({ app, opts }, scms) when is_atom(app) and is_list(opts) do\n with_scm_and_app({ app, nil, opts }, scms)\n end\n\n defp with_scm_and_app({ app, req, opts }, scms) when is_atom(app) and\n (is_binary(req) or is_regex(req) or req == nil) and is_list(opts) do\n\n path = Path.join(Mix.project[:deps_path], app)\n opts = Keyword.put(opts, :dest, path)\n\n { scm, opts } = Enum.find_value scms, { nil, [] }, fn(scm) ->\n (new = scm.accepts_options(app, opts)) && { scm, new }\n end\n\n if scm do\n Mix.Dep[\n scm: scm,\n app: app,\n requirement: req,\n status: scm_status(scm, opts),\n opts: opts\n ]\n else\n raise Mix.Error, message: \"#{inspect Mix.Project.get} did not specify a supported scm \" <>\n \"for app #{inspect app}, expected one of :git, :path or :in_umbrella\"\n end\n end\n\n defp with_scm_and_app(other, _scms) do\n invalid_dep_format(other)\n end\n\n defp scm_status(scm, opts) do\n if scm.checked_out? opts do\n { :ok, nil }\n else\n { :unavailable, opts[:dest] }\n end\n end\n\n defp validate_app(Mix.Dep[opts: opts, requirement: req, app: app, status: status] = dep) do\n opts_app = opts[:app]\n\n if not ok?(status) or opts_app == false do\n dep\n else\n path = if is_binary(opts_app), do: opts_app, else: \"ebin\/#{app}.app\"\n path = Path.expand(path, opts[:dest])\n dep.status app_status(path, app, req)\n end\n end\n\n defp app_status(app_path, app, req) do\n case :file.consult(app_path) do\n { :ok, [{ :application, ^app, config }] } ->\n case List.keyfind(config, :vsn, 0) do\n { :vsn, actual } when is_list(actual) ->\n actual = iolist_to_binary(actual)\n if vsn_match?(req, actual) do\n { :ok, actual }\n else\n { :nomatchvsn, actual }\n end\n { :vsn, actual } ->\n { :invalidvsn, actual }\n nil ->\n { :invalidvsn, nil }\n end\n { :ok, _ } -> { :invalidapp, app_path }\n { :error, _ } -> { :noappfile, app_path }\n end\n end\n\n defp vsn_match?(nil, _actual), do: true\n defp vsn_match?(req, actual) when is_regex(req), do: actual =~ req\n defp vsn_match?(req, actual) when is_binary(req) do\n Version.match?(actual, req)\n end\n\n defp mixfile?(dep) do\n File.regular?(Path.join(dep.opts[:dest], \"mix.exs\"))\n end\n\n defp rebarexec?(dep) do\n File.regular?(Path.join(dep.opts[:dest], \"rebar\"))\n end\n\n defp rebarconfig?(dep) do\n Enum.any?([\"rebar.config\", \"rebar.config.script\"], fn file ->\n File.regular?(Path.join(dep.opts[:dest], file))\n end)\n end\n\n defp makefile?(dep) do\n File.regular? Path.join(dep.opts[:dest], \"Makefile\")\n end\n\n defp ok?({ :ok, _ }), do: true\n defp ok?(_), do: false\n\n defp invalid_dep_format(dep) do\n raise Mix.Error, message: %s(Dependency specified in the wrong format: #{inspect dep}, ) <>\n %s(expected { app :: atom, opts :: Keyword.t } | { app :: atom, requirement :: String.t, opts :: Keyword.t })\n end\n\n defp old_elixir_lock do\n old_vsn = Mix.Deps.Lock.elixir_vsn\n if old_vsn && old_vsn != System.version do\n old_vsn\n end\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"4cfbf95d90fcd2f90e002fd383eae1398cbbb0d7","subject":"Fallback to first facility on invalid\/missing subdomain","message":"Fallback to first facility on invalid\/missing subdomain\n","repos":"fcapovilla\/open_pantry,fcapovilla\/open_pantry,openpantry\/open_pantry,openpantry\/open_pantry,openpantry\/open_pantry,MasbiaSoupKitchenNetwork\/open_pantry,MasbiaSoupKitchenNetwork\/open_pantry,fcapovilla\/open_pantry,MasbiaSoupKitchenNetwork\/open_pantry,openpantry\/open_pantry,fcapovilla\/open_pantry,MasbiaSoupKitchenNetwork\/open_pantry","old_file":"lib\/open_pantry\/plugs\/facility.ex","new_file":"lib\/open_pantry\/plugs\/facility.ex","new_contents":"defmodule OpenPantry.Plugs.Facility do\n import Ecto.Query, only: [from: 2]\n\n alias OpenPantry.{Repo, Facility}\n\n def init(_opts) do\n Application.get_env(:open_pantry, OpenPantry.Web.Endpoint)[:url][:host]\n |> String.length()\n end\n\n def call(conn, domain_length) do\n subdomain = subdomain(conn.host, domain_length)\n\n facility =\n case Repo.get_by(Facility, subdomain: subdomain) do\n nil -> Repo.one!(from Facility, limit: 1)\n facility -> facility\n end\n\n Plug.Conn.assign(conn, :facility, facility)\n end\n\n defp subdomain(host, domain_length) do\n to = -domain_length - 2\n String.slice(host, 0..to)\n end\nend\n","old_contents":"defmodule OpenPantry.Plugs.Facility do\n alias OpenPantry.{Repo, Facility}\n\n def init(_opts) do\n Application.get_env(:open_pantry, OpenPantry.Web.Endpoint)[:url][:host]\n |> String.length()\n end\n\n def call(conn, domain_length) do\n subdomain = subdomain(conn.host, domain_length)\n facility = Repo.get_by!(Facility, subdomain: subdomain)\n\n Plug.Conn.assign(conn, :facility, facility)\n end\n\n defp subdomain(host, domain_length) do\n to = -domain_length - 2\n String.slice(host, 0..to)\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"bf1bc4f3d8f40087a670e498dc603bc59796b0a2","subject":"Run project synchronization even if it exists already","message":"Run project synchronization even if it exists already\n\nFixes #413\n","repos":"bors-ng\/bors-ng,bors-ng\/bors-ng,bors-ng\/bors-ng","old_file":"lib\/worker\/syncer_installation.ex","new_file":"lib\/worker\/syncer_installation.ex","new_contents":"defmodule BorsNG.Worker.SyncerInstallation do\n @moduledoc \"\"\"\n A background task that pulls a full list of repositories that bors is on.\n Projects that don't come up get removed,\n and projects hat don't exist get created.\n \"\"\"\n\n alias BorsNG.Worker.Syncer\n alias BorsNG.Worker.SyncerInstallation\n alias BorsNG.Database.Installation\n alias BorsNG.Database.Project\n alias BorsNG.Database.Repo\n alias BorsNG.GitHub\n\n import Ecto.Query\n\n require Logger\n\n def start_synchronize_all_installations do\n {:ok, _} = Task.Supervisor.start_child(\n Syncer.Supervisor,\n fn -> synchronize_all_installations() end)\n end\n\n def start_synchronize_installation(installation) do\n {:ok, _} = Task.Supervisor.start_child(\n Syncer.Supervisor,\n fn -> synchronize_installation(installation) end)\n end\n\n def synchronize_all_installations do\n GitHub.get_installation_list!()\n |> Enum.each(&synchronize_installation(\n %Installation{installation_xref: &1}))\n end\n\n def synchronize_installation(installation = %Installation{\n installation_xref: x,\n id: id,\n }) when is_integer(x) and is_integer(id) do\n {:ok, _} = Registry.register(SyncerInstallation.Registry, x, {})\n allow_private = Confex.fetch_env!(:bors, BorsNG)[:allow_private_repos]\n repos = GitHub.get_installation_repos!({:installation, x})\n projects = Repo.all(from p in Project, where: p.installation_id == ^id)\n plan_synchronize(allow_private, repos, projects)\n |> Enum.each(fn {action, payload} ->\n apply(__MODULE__, action, [installation, payload])\n end)\n end\n\n def synchronize_installation(installation = %Installation{\n installation_xref: x,\n }) when is_integer(x) do\n Installation\n |> Repo.get_by(installation_xref: x)\n |> case do\n nil -> Repo.insert!(installation)\n installation -> installation\n end\n |> synchronize_installation()\n end\n\n def synchronize_installation(id) when is_integer(id) do\n Installation\n |> Repo.get!(id)\n |> synchronize_installation()\n end\n\n def plan_synchronize(allow_private, repos, projects) do\n repos = Enum.flat_map(repos, fn repo = %{id: xref, private: private} ->\n if allow_private || !private, do: [{xref, repo}], else: []\n end)\n |> Map.new()\n projects = projects\n |> Enum.map(&{&1.repo_xref, &1})\n |> Map.new()\n adds = Enum.flat_map(repos, fn {xref, repo} ->\n if Map.has_key?(projects, xref), do: [], else: [{:add, repo}]\n end)\n removes = Enum.flat_map(projects, fn {xref, project} ->\n if Map.has_key?(repos, xref), do: [{:sync, project}], else: [{:remove, project}]\n end)\n adds ++ removes\n end\n\n def add(%{id: installation_id}, %{id: repo_xref, name: name}) do\n %Project{\n auto_reviewer_required_perm: :push,\n repo_xref: repo_xref,\n name: name,\n installation_id: installation_id}\n |> Repo.insert!()\n |> Syncer.synchronize_project()\n end\n\n def remove(_installation, project) do\n project\n |> Repo.delete!()\n end\n\n def sync(_installation, project) do\n project\n |> Syncer.synchronize_project()\n end\n\n @doc \"\"\"\n Wait for synchronization to finish by hot-spinning.\n Used in test cases.\n \"\"\"\n def wait_hot_spin_xref(installation_xref) do\n i = Repo.get_by(Installation, installation_xref: installation_xref)\n l = Registry.lookup(SyncerInstallation.Registry, installation_xref)\n case {i, l} do\n # Keep spinning if the installation doesn't exist\n {nil, _} -> wait_hot_spin_xref(installation_xref)\n # Keep spinning if the installation is in the process of syncing\n {_, [{_, _}]} -> wait_hot_spin_xref(installation_xref)\n # Stop spinning otherwise\n _ -> :ok\n end\n end\nend\n","old_contents":"defmodule BorsNG.Worker.SyncerInstallation do\n @moduledoc \"\"\"\n A background task that pulls a full list of repositories that bors is on.\n Projects that don't come up get removed,\n and projects hat don't exist get created.\n \"\"\"\n\n alias BorsNG.Worker.Syncer\n alias BorsNG.Worker.SyncerInstallation\n alias BorsNG.Database.Installation\n alias BorsNG.Database.Project\n alias BorsNG.Database.Repo\n alias BorsNG.GitHub\n\n import Ecto.Query\n\n require Logger\n\n def start_synchronize_all_installations do\n {:ok, _} = Task.Supervisor.start_child(\n Syncer.Supervisor,\n fn -> synchronize_all_installations() end)\n end\n\n def start_synchronize_installation(installation) do\n {:ok, _} = Task.Supervisor.start_child(\n Syncer.Supervisor,\n fn -> synchronize_installation(installation) end)\n end\n\n def synchronize_all_installations do\n GitHub.get_installation_list!()\n |> Enum.each(&synchronize_installation(\n %Installation{installation_xref: &1}))\n end\n\n def synchronize_installation(installation = %Installation{\n installation_xref: x,\n id: id,\n }) when is_integer(x) and is_integer(id) do\n {:ok, _} = Registry.register(SyncerInstallation.Registry, x, {})\n allow_private = Confex.fetch_env!(:bors, BorsNG)[:allow_private_repos]\n repos = GitHub.get_installation_repos!({:installation, x})\n projects = Repo.all(from p in Project, where: p.installation_id == ^id)\n plan_synchronize(allow_private, repos, projects)\n |> Enum.each(fn {action, payload} ->\n apply(__MODULE__, action, [installation, payload])\n end)\n end\n\n def synchronize_installation(installation = %Installation{\n installation_xref: x,\n }) when is_integer(x) do\n Installation\n |> Repo.get_by(installation_xref: x)\n |> case do\n nil -> Repo.insert!(installation)\n installation -> installation\n end\n |> synchronize_installation()\n end\n\n def synchronize_installation(id) when is_integer(id) do\n Installation\n |> Repo.get!(id)\n |> synchronize_installation()\n end\n\n def plan_synchronize(allow_private, repos, projects) do\n repos = Enum.flat_map(repos, fn repo = %{id: xref, private: private} ->\n if allow_private || !private, do: [{xref, repo}], else: []\n end)\n |> Map.new()\n projects = projects\n |> Enum.map(&{&1.repo_xref, &1})\n |> Map.new()\n adds = Enum.flat_map(repos, fn {xref, repo} ->\n if Map.has_key?(projects, xref), do: [], else: [{:add, repo}]\n end)\n removes = Enum.flat_map(projects, fn {xref, project} ->\n if Map.has_key?(repos, xref), do: [], else: [{:remove, project}]\n end)\n adds ++ removes\n end\n\n def add(%{id: installation_id}, %{id: repo_xref, name: name}) do\n %Project{\n auto_reviewer_required_perm: :push,\n repo_xref: repo_xref,\n name: name,\n installation_id: installation_id}\n |> Repo.insert!()\n |> Syncer.synchronize_project()\n end\n\n def remove(_installation, project) do\n project\n |> Repo.delete!()\n end\n\n @doc \"\"\"\n Wait for synchronization to finish by hot-spinning.\n Used in test cases.\n \"\"\"\n def wait_hot_spin_xref(installation_xref) do\n i = Repo.get_by(Installation, installation_xref: installation_xref)\n l = Registry.lookup(SyncerInstallation.Registry, installation_xref)\n case {i, l} do\n # Keep spinning if the installation doesn't exist\n {nil, _} -> wait_hot_spin_xref(installation_xref)\n # Keep spinning if the installation is in the process of syncing\n {_, [{_, _}]} -> wait_hot_spin_xref(installation_xref)\n # Stop spinning otherwise\n _ -> :ok\n end\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"9cdd6ca61c8d6a8b042947725556be381d8c34d1","subject":"Update middlewares to not expect simplified parts.","message":"Update middlewares to not expect simplified parts.\n","repos":"CrowdHailer\/raxx","old_file":"test\/raxx\/pipeline_test.exs","new_file":"test\/raxx\/pipeline_test.exs","new_contents":"defmodule Raxx.PipelineTest do\n use ExUnit.Case\n\n alias Raxx.Middleware\n alias Raxx.Pipeline\n\n defmodule HomePage do\n use Raxx.Server\n\n @impl Raxx.Server\n def handle_request(_request, _state) do\n response(:ok)\n |> set_body(\"Home page\")\n end\n end\n\n defmodule NoOp do\n @behaviour Middleware\n\n @impl Middleware\n def handle_head(request, config, pipeline) do\n {parts, pipeline} = Pipeline.handle_head(request, pipeline)\n {parts, {config, :head}, pipeline}\n end\n\n @impl Middleware\n def handle_data(data, {_, prev}, pipeline) do\n {parts, pipeline} = Pipeline.handle_data(data, pipeline)\n {parts, {prev, :data}, pipeline}\n end\n\n @impl Middleware\n def handle_tail(tail, {_, prev}, pipeline) do\n {parts, pipeline} = Pipeline.handle_tail(tail, pipeline)\n {parts, {prev, :tail}, pipeline}\n end\n\n @impl Middleware\n def handle_info(message, {_, prev}, pipeline) do\n {parts, pipeline} = Pipeline.handle_info(message, pipeline)\n {parts, {prev, :info}, pipeline}\n end\n end\n\n test \"a couple of NoOp Middlewares don't modify the response of a simple controller\" do\n middlewares = [{NoOp, :irrelevant}, {NoOp, 42}]\n pipeline = Pipeline.create(middlewares, HomePage, :controller_initial)\n\n request =\n Raxx.request(:POST, \"\/\")\n |> Raxx.set_content_length(3)\n |> Raxx.set_body(true)\n\n assert {[], pipeline} = Pipeline.handle_head(request, pipeline)\n assert {[], pipeline} = Pipeline.handle_data(\"abc\", pipeline)\n\n assert {[response], _pipeline} = Pipeline.handle_tail([], pipeline)\n\n assert %Raxx.Response{\n body: \"Home page\",\n headers: [{\"content-length\", \"9\"}],\n status: 200\n } = response\n\n # NOTE these assertions work when Raxx.simplify_parts\/1 is used\n # middleware simplifies \"compound\" server responses (full responses)\n # assert {[head, body, tail], _pipeline} = Pipeline.handle_tail([], pipeline)\n # assert %Raxx.Response{status: 200, body: true} = head\n # assert %Raxx.Data{data: \"Home page\"} = body\n # assert %Raxx.Tail{headers: []} = tail\n end\n\n defmodule Meddler do\n @behaviour Middleware\n @impl Middleware\n def handle_head(request, config, pipeline) do\n request =\n case Keyword.get(config, :request_header) do\n nil ->\n request\n\n value ->\n request\n |> Raxx.delete_header(\"x-request-header\")\n |> Raxx.set_header(\"x-request-header\", value)\n end\n\n {parts, pipeline} = Pipeline.handle_head(request, pipeline)\n parts = modify_parts(parts, config)\n {parts, config, pipeline}\n end\n\n @impl Middleware\n def handle_data(data, config, pipeline) do\n {parts, pipeline} = Pipeline.handle_data(data, pipeline)\n parts = modify_parts(parts, config)\n {parts, config, pipeline}\n end\n\n @impl Middleware\n def handle_tail(tail, config, pipeline) do\n {parts, pipeline} = Pipeline.handle_tail(tail, pipeline)\n parts = modify_parts(parts, config)\n {parts, config, pipeline}\n end\n\n @impl Middleware\n def handle_info(message, config, pipeline) do\n {parts, pipeline} = Pipeline.handle_info(message, pipeline)\n parts = modify_parts(parts, config)\n {parts, config, pipeline}\n end\n\n defp modify_parts(parts, config) do\n Enum.map(parts, &modify_part(&1, config))\n end\n\n defp modify_part(data = %Raxx.Data{data: contents}, config) do\n new_contents = modify_contents(contents, config)\n %Raxx.Data{data | data: new_contents}\n end\n\n # NOTE this function head is necessary if Pipeline doesn't do Raxx.simplify_parts\/1\n defp modify_part(response = %Raxx.Response{body: contents}, config)\n when is_binary(contents) do\n new_contents = modify_contents(contents, config)\n %Raxx.Response{response | body: new_contents}\n end\n\n defp modify_part(part, _state) do\n part\n end\n\n defp modify_contents(contents, config) do\n case Keyword.get(config, :response_body) do\n nil ->\n contents\n\n replacement when is_binary(replacement) ->\n String.replace(contents, ~r\/.\/, replacement)\n # make sure it's the same length\n |> String.slice(0, String.length(contents))\n end\n end\n end\n\n defmodule SpyServer do\n use Raxx.Server\n # this server is deliberately weird to trip up any assumptions\n @impl Raxx.Server\n def handle_head(request = %{body: false}, state) do\n send(self(), {__MODULE__, :handle_head, request, state})\n\n response =\n Raxx.response(:ok) |> Raxx.set_body(\"SpyServer responds to a request with no body\")\n\n {[response], state}\n end\n\n def handle_head(request, state) do\n send(self(), {__MODULE__, :handle_head, request, state})\n {[], 1}\n end\n\n def handle_data(data, state) do\n send(self(), {__MODULE__, :handle_data, data, state})\n\n headers =\n response(:ok)\n |> set_content_length(10)\n |> set_body(true)\n\n {[headers], state + 1}\n end\n\n def handle_tail(tail, state) do\n send(self(), {__MODULE__, :handle_tail, tail, state})\n {[data(\"spy server\"), tail([{\"x-response-trailer\", \"spy-trailer\"}])], -1 * state}\n end\n end\n\n test \"middlewares can modify the request\" do\n middlewares = [{Meddler, [request_header: \"foo\"]}, {Meddler, [request_header: \"bar\"]}]\n pipeline = Pipeline.create(middlewares, SpyServer, :controller_initial)\n\n request =\n Raxx.request(:POST, \"\/\")\n |> Raxx.set_content_length(3)\n |> Raxx.set_body(true)\n\n assert {[], pipeline} = Pipeline.handle_head(request, pipeline)\n\n assert_receive {SpyServer, :handle_head, server_request, :controller_initial}\n assert %Raxx.Request{} = server_request\n assert \"bar\" == Raxx.get_header(server_request, \"x-request-header\")\n assert 3 == Raxx.get_content_length(server_request)\n\n assert {[headers], pipeline} = Pipeline.handle_data(\"abc\", pipeline)\n assert_receive {SpyServer, :handle_data, \"abc\", 1}\n assert %Raxx.Response{body: true, status: 200} = headers\n\n assert {[data, tail], pipeline} = Pipeline.handle_tail([], pipeline)\n assert_receive {SpyServer, :handle_tail, [], 2}\n assert %Raxx.Data{data: \"spy server\"} = data\n assert %Raxx.Tail{headers: [{\"x-response-trailer\", \"spy-trailer\"}]} == tail\n end\n\n test \"middlewares can modify the response\" do\n middlewares = [{Meddler, [response_body: \"foo\"]}, {Meddler, [response_body: \"bar\"]}]\n pipeline = Pipeline.create(middlewares, SpyServer, :controller_initial)\n\n request =\n Raxx.request(:POST, \"\/\")\n |> Raxx.set_content_length(3)\n |> Raxx.set_body(true)\n\n assert {[], pipeline} = Pipeline.handle_head(request, pipeline)\n\n assert_receive {SpyServer, :handle_head, server_request, :controller_initial}\n assert %Raxx.Request{} = server_request\n assert nil == Raxx.get_header(server_request, \"x-request-header\")\n assert 3 == Raxx.get_content_length(server_request)\n\n assert {[headers], pipeline} = Pipeline.handle_data(\"abc\", pipeline)\n assert_receive {SpyServer, :handle_data, \"abc\", 1}\n assert %Raxx.Response{body: true, status: 200} = headers\n\n assert {[data, tail], pipeline} = Pipeline.handle_tail([], pipeline)\n assert_receive {SpyServer, :handle_tail, [], 2}\n assert %Raxx.Data{data: \"foofoofoof\"} = data\n assert %Raxx.Tail{headers: [{\"x-response-trailer\", \"spy-trailer\"}]} == tail\n end\n\n test \"middlewares' state is correctly updated\" do\n middlewares = [{Meddler, [response_body: \"foo\"]}, {NoOp, :config}]\n pipeline = Pipeline.create(middlewares, SpyServer, :controller_initial)\n\n request =\n Raxx.request(:POST, \"\/\")\n |> Raxx.set_content_length(3)\n |> Raxx.set_body(true)\n\n assert {_, pipeline} = Pipeline.handle_head(request, pipeline)\n # NOTE this test breaks the encapsulation of the pipeline,\n # but the alternative would be a bit convoluted\n assert [{Meddler, [response_body: \"foo\"]}, {NoOp, {:config, :head}}, {SpyServer, 1}] ==\n pipeline\n\n {_, pipeline} = Pipeline.handle_data(\"z\", pipeline)\n assert [{Meddler, [response_body: \"foo\"]}, {NoOp, {:head, :data}}, {SpyServer, 2}] == pipeline\n\n {_, pipeline} = Pipeline.handle_data(\"zz\", pipeline)\n assert [{Meddler, [response_body: \"foo\"]}, {NoOp, {:data, :data}}, {SpyServer, 3}] == pipeline\n\n {_, pipeline} = Pipeline.handle_tail([{\"x-foo\", \"bar\"}], pipeline)\n\n assert [{Meddler, _}, {NoOp, {:data, :tail}}, {SpyServer, -3}] = pipeline\n end\n\n test \"a pipeline with no middlewares is functional\" do\n pipeline = Pipeline.create([], SpyServer, :controller_initial)\n\n request =\n Raxx.request(:POST, \"\/\")\n |> Raxx.set_content_length(3)\n |> Raxx.set_body(true)\n\n {pipeline_result_1, pipeline} = Pipeline.handle_head(request, pipeline)\n {pipeline_result_2, pipeline} = Pipeline.handle_data(\"xxx\", pipeline)\n {pipeline_result_3, _pipeline} = Pipeline.handle_tail([], pipeline)\n\n {server_result_1, state} = SpyServer.handle_head(request, :controller_initial)\n {server_result_2, state} = SpyServer.handle_data(\"xxx\", state)\n {server_result_3, _state} = SpyServer.handle_tail([], state)\n\n assert pipeline_result_1 == server_result_1\n assert pipeline_result_2 == server_result_2\n assert pipeline_result_3 == server_result_3\n end\n\n defmodule AlwaysForbidden do\n @behaviour Middleware\n\n @impl Middleware\n def handle_head(_request, _config, pipeline) do\n response =\n Raxx.response(:forbidden)\n |> Raxx.set_body(\"Forbidden!\")\n\n {[response], nil, pipeline}\n end\n\n @impl Middleware\n def handle_data(_data, _state, pipeline) do\n {[], nil, pipeline}\n end\n\n @impl Middleware\n def handle_tail(_tail, _state, pipeline) do\n {[], nil, pipeline}\n end\n\n @impl Middleware\n def handle_info(_message, _state, pipeline) do\n {[], nil, pipeline}\n end\n end\n\n test \"middlewares can \\\"short circuit\\\" processing (not call through)\" do\n middlewares = [{NoOp, nil}, {AlwaysForbidden, nil}]\n pipeline = Pipeline.create(middlewares, SpyServer, :whatever)\n request = Raxx.request(:GET, \"\/\")\n\n assert {[response], _pipeline} = Pipeline.handle_head(request, pipeline)\n assert %Raxx.Response{body: \"Forbidden!\"} = response\n\n refute_receive _\n\n pipeline = Pipeline.create([{NoOp, nil}], SpyServer, :whatever)\n assert {[response], _pipeline} = Pipeline.handle_head(request, pipeline)\n assert response.body =~ \"SpyServer\"\n\n assert_receive {SpyServer, _, _, _}\n\n # NOTE these assertions work when Raxx.simplify_parts\/1 is used\n # assert {[_head, data, _tail], _pipeline} = Pipeline.handle_head(request, pipeline)\n # assert %Raxx.Data{data: \"Forbidden!\"} == data\n\n # refute_receive _\n\n # pipeline = Pipeline.create([{NoOp, nil}], SpyServer, :whatever)\n # assert {[_head, data, _tail], _pipeline} = Pipeline.handle_head(request, pipeline)\n # assert data.data =~ \"SpyServer\"\n\n # assert_receive {SpyServer, _, _, _}\n end\nend\n","old_contents":"defmodule Raxx.PipelineTest do\n use ExUnit.Case\n\n alias Raxx.Middleware\n alias Raxx.Pipeline\n\n defmodule HomePage do\n use Raxx.Server\n\n @impl Raxx.Server\n def handle_request(_request, _state) do\n response(:ok)\n |> set_body(\"Home page\")\n end\n end\n\n defmodule NoOp do\n @behaviour Middleware\n\n @impl Middleware\n def handle_head(request, config, pipeline) do\n {parts, pipeline} = Pipeline.handle_head(request, pipeline)\n {parts, {config, :head}, pipeline}\n end\n\n @impl Middleware\n def handle_data(data, {_, prev}, pipeline) do\n {parts, pipeline} = Pipeline.handle_data(data, pipeline)\n {parts, {prev, :data}, pipeline}\n end\n\n @impl Middleware\n def handle_tail(tail, {_, prev}, pipeline) do\n {parts, pipeline} = Pipeline.handle_tail(tail, pipeline)\n {parts, {prev, :tail}, pipeline}\n end\n\n @impl Middleware\n def handle_info(message, {_, prev}, pipeline) do\n {parts, pipeline} = Pipeline.handle_info(message, pipeline)\n {parts, {prev, :info}, pipeline}\n end\n end\n\n test \"a couple of NoOp Middlewares don't modify the response of a simple controller\" do\n middlewares = [{NoOp, :irrelevant}, {NoOp, 42}]\n pipeline = Pipeline.create(middlewares, HomePage, :controller_initial)\n\n request =\n Raxx.request(:POST, \"\/\")\n |> Raxx.set_content_length(3)\n |> Raxx.set_body(true)\n\n assert {[], pipeline} = Pipeline.handle_head(request, pipeline)\n assert {[], pipeline} = Pipeline.handle_data(\"abc\", pipeline)\n\n assert {[response], _pipeline} = Pipeline.handle_tail([], pipeline)\n\n assert %Raxx.Response{\n body: \"Home page\",\n headers: [{\"content-length\", \"9\"}],\n status: 200\n } = response\n\n # NOTE these assertions work when Raxx.simplify_parts\/1 is used\n # middleware simplifies \"compound\" server responses (full responses)\n # assert {[head, body, tail], _pipeline} = Pipeline.handle_tail([], pipeline)\n # assert %Raxx.Response{status: 200, body: true} = head\n # assert %Raxx.Data{data: \"Home page\"} = body\n # assert %Raxx.Tail{headers: []} = tail\n end\n\n defmodule Meddler do\n @behaviour Middleware\n @impl Middleware\n def handle_head(request, config, pipeline) do\n request =\n case Keyword.get(config, :request_header) do\n nil ->\n request\n\n value ->\n request\n |> Raxx.delete_header(\"x-request-header\")\n |> Raxx.set_header(\"x-request-header\", value)\n end\n\n {parts, pipeline} = Pipeline.handle_head(request, pipeline)\n parts = modify_parts(parts, config)\n {parts, config, pipeline}\n end\n\n @impl Middleware\n def handle_data(data, config, pipeline) do\n {parts, pipeline} = Pipeline.handle_data(data, pipeline)\n parts = modify_parts(parts, config)\n {parts, config, pipeline}\n end\n\n @impl Middleware\n def handle_tail(tail, config, pipeline) do\n {parts, pipeline} = Pipeline.handle_tail(tail, pipeline)\n parts = modify_parts(parts, config)\n {parts, config, pipeline}\n end\n\n @impl Middleware\n def handle_info(message, config, pipeline) do\n {parts, pipeline} = Pipeline.handle_info(message, pipeline)\n parts = modify_parts(parts, config)\n {parts, config, pipeline}\n end\n\n defp modify_parts(parts, config) do\n Enum.map(parts, &modify_part(&1, config))\n end\n\n defp modify_part(data = %Raxx.Data{data: contents}, config) do\n case Keyword.get(config, :response_body) do\n nil ->\n data\n\n replacement when is_binary(replacement) ->\n new_contents =\n String.replace(contents, ~r\/.\/, replacement)\n # make sure it's the same length\n |> String.slice(0, String.length(contents))\n\n %Raxx.Data{data: new_contents}\n end\n end\n\n defp modify_part(part, _state) do\n part\n end\n end\n\n defmodule SpyServer do\n use Raxx.Server\n # this server is deliberately weird to trip up any assumptions\n @impl Raxx.Server\n def handle_head(request = %{body: false}, state) do\n send(self(), {__MODULE__, :handle_head, request, state})\n\n response =\n Raxx.response(:ok) |> Raxx.set_body(\"SpyServer responds to a request with no body\")\n\n {[response], state}\n end\n\n def handle_head(request, state) do\n send(self(), {__MODULE__, :handle_head, request, state})\n {[], 1}\n end\n\n def handle_data(data, state) do\n send(self(), {__MODULE__, :handle_data, data, state})\n\n headers =\n response(:ok)\n |> set_content_length(10)\n |> set_body(true)\n\n {[headers], state + 1}\n end\n\n def handle_tail(tail, state) do\n send(self(), {__MODULE__, :handle_tail, tail, state})\n {[data(\"spy server\"), tail([{\"x-response-trailer\", \"spy-trailer\"}])], -1 * state}\n end\n end\n\n test \"middlewares can modify the request\" do\n middlewares = [{Meddler, [request_header: \"foo\"]}, {Meddler, [request_header: \"bar\"]}]\n pipeline = Pipeline.create(middlewares, SpyServer, :controller_initial)\n\n request =\n Raxx.request(:POST, \"\/\")\n |> Raxx.set_content_length(3)\n |> Raxx.set_body(true)\n\n assert {[], pipeline} = Pipeline.handle_head(request, pipeline)\n\n assert_receive {SpyServer, :handle_head, server_request, :controller_initial}\n assert %Raxx.Request{} = server_request\n assert \"bar\" == Raxx.get_header(server_request, \"x-request-header\")\n assert 3 == Raxx.get_content_length(server_request)\n\n assert {[headers], pipeline} = Pipeline.handle_data(\"abc\", pipeline)\n assert_receive {SpyServer, :handle_data, \"abc\", 1}\n assert %Raxx.Response{body: true, status: 200} = headers\n\n assert {[data, tail], pipeline} = Pipeline.handle_tail([], pipeline)\n assert_receive {SpyServer, :handle_tail, [], 2}\n assert %Raxx.Data{data: \"spy server\"} = data\n assert %Raxx.Tail{headers: [{\"x-response-trailer\", \"spy-trailer\"}]} == tail\n end\n\n test \"middlewares can modify the response\" do\n middlewares = [{Meddler, [response_body: \"foo\"]}, {Meddler, [response_body: \"bar\"]}]\n pipeline = Pipeline.create(middlewares, SpyServer, :controller_initial)\n\n request =\n Raxx.request(:POST, \"\/\")\n |> Raxx.set_content_length(3)\n |> Raxx.set_body(true)\n\n assert {[], pipeline} = Pipeline.handle_head(request, pipeline)\n\n assert_receive {SpyServer, :handle_head, server_request, :controller_initial}\n assert %Raxx.Request{} = server_request\n assert nil == Raxx.get_header(server_request, \"x-request-header\")\n assert 3 == Raxx.get_content_length(server_request)\n\n assert {[headers], pipeline} = Pipeline.handle_data(\"abc\", pipeline)\n assert_receive {SpyServer, :handle_data, \"abc\", 1}\n assert %Raxx.Response{body: true, status: 200} = headers\n\n assert {[data, tail], pipeline} = Pipeline.handle_tail([], pipeline)\n assert_receive {SpyServer, :handle_tail, [], 2}\n assert %Raxx.Data{data: \"foofoofoof\"} = data\n assert %Raxx.Tail{headers: [{\"x-response-trailer\", \"spy-trailer\"}]} == tail\n end\n\n test \"middlewares' state is correctly updated\" do\n middlewares = [{Meddler, [response_body: \"foo\"]}, {NoOp, :config}]\n pipeline = Pipeline.create(middlewares, SpyServer, :controller_initial)\n\n request =\n Raxx.request(:POST, \"\/\")\n |> Raxx.set_content_length(3)\n |> Raxx.set_body(true)\n\n assert {_, pipeline} = Pipeline.handle_head(request, pipeline)\n # NOTE this test breaks the encapsulation of the pipeline,\n # but the alternative would be a bit convoluted\n assert [{Meddler, [response_body: \"foo\"]}, {NoOp, {:config, :head}}, {SpyServer, 1}] ==\n pipeline\n\n {_, pipeline} = Pipeline.handle_data(\"z\", pipeline)\n assert [{Meddler, [response_body: \"foo\"]}, {NoOp, {:head, :data}}, {SpyServer, 2}] == pipeline\n\n {_, pipeline} = Pipeline.handle_data(\"zz\", pipeline)\n assert [{Meddler, [response_body: \"foo\"]}, {NoOp, {:data, :data}}, {SpyServer, 3}] == pipeline\n\n {_, pipeline} = Pipeline.handle_tail([{\"x-foo\", \"bar\"}], pipeline)\n\n assert [{Meddler, _}, {NoOp, {:data, :tail}}, {SpyServer, -3}] = pipeline\n end\n\n test \"a pipeline with no middlewares is functional\" do\n pipeline = Pipeline.create([], SpyServer, :controller_initial)\n\n request =\n Raxx.request(:POST, \"\/\")\n |> Raxx.set_content_length(3)\n |> Raxx.set_body(true)\n\n {pipeline_result_1, pipeline} = Pipeline.handle_head(request, pipeline)\n {pipeline_result_2, pipeline} = Pipeline.handle_data(\"xxx\", pipeline)\n {pipeline_result_3, _pipeline} = Pipeline.handle_tail([], pipeline)\n\n {server_result_1, state} = SpyServer.handle_head(request, :controller_initial)\n {server_result_2, state} = SpyServer.handle_data(\"xxx\", state)\n {server_result_3, _state} = SpyServer.handle_tail([], state)\n\n assert pipeline_result_1 == server_result_1\n assert pipeline_result_2 == server_result_2\n assert pipeline_result_3 == server_result_3\n end\n\n defmodule AlwaysForbidden do\n @behaviour Middleware\n\n @impl Middleware\n def handle_head(_request, _config, pipeline) do\n response =\n Raxx.response(:forbidden)\n |> Raxx.set_body(\"Forbidden!\")\n\n {[response], nil, pipeline}\n end\n\n @impl Middleware\n def handle_data(_data, _state, pipeline) do\n {[], nil, pipeline}\n end\n\n @impl Middleware\n def handle_tail(_tail, _state, pipeline) do\n {[], nil, pipeline}\n end\n\n @impl Middleware\n def handle_info(_message, _state, pipeline) do\n {[], nil, pipeline}\n end\n end\n\n test \"middlewares can \\\"short circuit\\\" processing (not call through)\" do\n middlewares = [{NoOp, nil}, {AlwaysForbidden, nil}]\n pipeline = Pipeline.create(middlewares, SpyServer, :whatever)\n request = Raxx.request(:GET, \"\/\")\n\n assert {[response], _pipeline} = Pipeline.handle_head(request, pipeline)\n assert %Raxx.Response{body: \"Forbidden!\"} = response\n\n refute_receive _\n\n pipeline = Pipeline.create([{NoOp, nil}], SpyServer, :whatever)\n assert {[response], _pipeline} = Pipeline.handle_head(request, pipeline)\n assert response.body =~ \"SpyServer\"\n\n assert_receive {SpyServer, _, _, _}\n\n # NOTE these assertions work when Raxx.simplify_parts\/1 is used\n # assert {[_head, data, _tail], _pipeline} = Pipeline.handle_head(request, pipeline)\n # assert %Raxx.Data{data: \"Forbidden!\"} == data\n\n # refute_receive _\n\n # pipeline = Pipeline.create([{NoOp, nil}], SpyServer, :whatever)\n # assert {[_head, data, _tail], _pipeline} = Pipeline.handle_head(request, pipeline)\n # assert data.data =~ \"SpyServer\"\n\n # assert_receive {SpyServer, _, _, _}\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"76c075e8ff7dff5f16a795f6a2f99a99989ef165","subject":"Docs for lead custom field id","message":"Docs for lead custom field id\n","repos":"nested-tech\/closex","old_file":"test\/support\/mock_client.ex","new_file":"test\/support\/mock_client.ex","new_contents":"defmodule Closex.MockClient do\n @behaviour Closex.ClientBehaviour\n\n @moduledoc \"\"\"\n This module is for testing, it allows you to stub requests to CloseIO.\n\n It behaves like the standard client so you can drop it into your code via\n configuration in your testing environment.\n\n First you ned to set the default client you want to use, either HTTPClient\n or CachingClient.\n\n ```\n $ cat your_app\/config\/config.exs\n\n config :yourapp,\n closeio_client: Closex.HTTPClient,\n ...other configuration...\n ```\n\n Then in your tests you can set the MockClient:\n\n ```\n $ cat your_app\/config\/test.exs\n\n config :yourapp,\n closeio_client: Closex.MockClient,\n ...other configuration...\n ```\n\n Next, use it in your code:\n\n ```\n $ cat your_app\/lib\/module_which_uses_closeio.ex\n\n defmodule YourApp.ModuleWhichUsesCloseIO do\n \n @closeio_client Application.fetch_env!(:your_app, :closeio_client)\n\n def do_things_with_a_close_io_lead(id) do\n @closeio_client.get_lead(id)\n # do things\n end\n end\n ```\n\n In test env, the client will return the test values for each method.\n\n For more detail on the test objects see the `test\/fixtures\/*.json` files.\n\n If you'd like to emulate not finding an object, pass in the `Closex.MockClient.get_not_found_id` value.\n \"\"\"\n\n @not_found_id \"not_found\"\n def get_not_found_id do\n @not_found_id\n end\n\n @lead_id \"lead_IIDHIStmFcFQZZP0BRe99V1MCoXWz2PGCm6EDmR9v2O\"\n def get_lead_id do\n @lead_id\n end\n\n @opportunity_id \"oppo_8eB77gAdf8FMy6GsNHEy84f7uoeEWv55slvUjKQZpJt\"\n def get_opportunity_id do\n @opportunity_id\n end\n\n @lead_custom_field_id \"lcf_v6S011I6MqcbVvB2FA5Nk8dr5MkL8sWuCiG8cUleO9c\"\n def get_lead_custom_field_id do\n @lead_custom_field_id\n end\n\n @doc \"\"\"\n Gets a lead from CloseIO.\n\n Returns `{:ok, lead}`.\n\n ## Examples\n\n iex> Closex.MockClient.get_lead(\"1\")\n nil\n > Closex.MockClient.get_lead(Closex.MockClient.get_lead_id)\n ...contents of test\/fixtures\/lead.json...\n iex> Closex.MockClient.get_lead(Closex.MockClient.get_not_found_id)\n {:error, :mock_not_found}\n \"\"\"\n def get_lead(id, opts \\\\ [])\n def get_lead(id = @lead_id, opts) do\n lead = load(\"lead.json\")\n send self(), {:closex_mock_client, :get_lead, [id, opts]}\n {:ok, lead}\n end\n def get_lead(id = @not_found_id, opts) do\n send self(), {:closex_mock_client, :get_lead, [id, opts]}\n {:error, :mock_not_found}\n end\n\n @doc \"\"\"\n Gets an opportunity from CloseIO.\n\n Returns `{:ok, opportunity}`.\n\n ## Examples\n\n iex> Closex.MockClient.get_opportunity(\"1\")\n nil\n > Closex.MockClient.get_opportunity(Closex.MockClient.get_opportunity_id)\n ...contents of test\/fixtures\/opportunity.json...\n iex> Closex.MockClient.get_opportunity(Closex.MockClient.get_not_found_id)\n {:error, :mock_not_found}\n \"\"\"\n def get_opportunity(id, opts \\\\ [])\n def get_opportunity(id = @opportunity_id, opts) do\n lead = load(\"opportunity.json\")\n send self(), {:closex_mock_client, :get_opportunity, [id, opts]}\n {:ok, lead}\n end\n def get_opportunity(id = @not_found_id, opts) do\n send self(), {:closex_mock_client, :get_opportunity, [id, opts]}\n {:error, :mock_not_found}\n end\n\n @doc \"\"\"\n Gets a lead_custom_field from CloseIO.\n\n Returns `{:ok, lead_custom_field}`.\n\n ## Examples\n\n iex> Closex.MockClient.get_lead_custom_field(\"1\")\n nil\n > Closex.MockClient.get_lead_custom_field(Closex.MockClient.get_lead_custom_field_id)\n ...contents of test\/fixtures\/lead_custom_field.json...\n iex> Closex.MockClient.get_lead_custom_field(Closex.MockClient.get_not_found_id)\n {:error, :mock_not_found}\n \"\"\"\n def get_lead_custom_field(id, opts \\\\ [])\n def get_lead_custom_field(id = @lead_custom_field_id, opts) do\n lead_custom_field = load(\"lead_custom_field.json\")\n send self(), {:closex_mock_client, :get_lead_custom_field, [id, opts]}\n {:ok, lead_custom_field}\n end\n def get_lead_custom_field(id = @not_found_id, opts) do\n send self(), {:closex_mock_client, :get_lead_custom_field, [id, opts]}\n {:error, :mock_not_found}\n end\n\n def get_organization(id, opts \\\\ [])\n def get_organization(id = \"orga_bwwWG475zqWiQGur0thQshwVXo8rIYecQHDWFanqhen\", opts) do\n organization = load(\"organization.json\")\n send self(), {:closex_mock_client, :get_organization, [id, opts]}\n {:ok, organization}\n end\n def get_organization(id = @not_found_id, opts) do\n send self(), {:closex_mock_client, :get_organization, [id, opts]}\n {:error, :mock_not_found}\n end\n\n def get_lead_statuses(opts \\\\ []) do\n lead_statuses = load(\"lead_statuses.json\")\n send self(), {:closex_mock_client, :get_lead_statuses, [opts]}\n {:ok, lead_statuses}\n end\n\n def get_opportunity_statuses(opts \\\\ []) do\n opportunity_statuses = load(\"opportunity_statuses.json\")\n send self(), {:closex_mock_client, :get_opportunity_statuses, [opts]}\n {:ok, opportunity_statuses}\n end\n\n def get_users(opts \\\\ []) do\n users = load(\"users.json\")\n send self(), {:closex_mock_client, :get_users, [opts]}\n {:ok, users}\n end\n\n # TODO: implement these mocks\n def create_lead(_payload, _opts \\\\ []), do: :noop\n def update_lead(lead_id, payload, opts \\\\ []) do\n lead = load(\"lead.json\")\n |> Map.merge(payload)\n |> Map.merge(%{\"id\" => lead_id})\n send self(), {:closex_mock_client, :update_lead, [lead_id, payload, opts]}\n {:ok, lead}\n end\n def create_opportunity(_payload, _opts \\\\ []), do: :noop\n def update_opportunity(opportunity_id, payload, opts \\\\ []) do\n opportunity = load(\"opportunity.json\")\n |> Map.merge(payload)\n |> Map.merge(%{\"id\" => opportunity_id})\n send self(), {:closex_mock_client, :update_opportunity, [opportunity_id, payload, opts]}\n {:ok, opportunity}\n end\n def send_email(_payload, _opts \\\\ []), do: :noop\n def find_leads(_search_term, _opts \\\\ []), do: :noop\n\n @fixtures_path Path.join([File.cwd!, \"test\", \"fixtures\"])\n defp load(filename) do\n [@fixtures_path, filename]\n |> Path.join\n |> File.read!\n |> Poison.decode!\n end\nend\n","old_contents":"defmodule Closex.MockClient do\n @behaviour Closex.ClientBehaviour\n\n @moduledoc \"\"\"\n This module is for testing, it allows you to stub requests to CloseIO.\n\n It behaves like the standard client so you can drop it into your code via\n configuration in your testing environment.\n\n First you ned to set the default client you want to use, either HTTPClient\n or CachingClient.\n\n ```\n $ cat your_app\/config\/config.exs\n\n config :yourapp,\n closeio_client: Closex.HTTPClient,\n ...other configuration...\n ```\n\n Then in your tests you can set the MockClient:\n\n ```\n $ cat your_app\/config\/test.exs\n\n config :yourapp,\n closeio_client: Closex.MockClient,\n ...other configuration...\n ```\n\n Next, use it in your code:\n\n ```\n $ cat your_app\/lib\/module_which_uses_closeio.ex\n\n defmodule YourApp.ModuleWhichUsesCloseIO do\n \n @closeio_client Application.fetch_env!(:your_app, :closeio_client)\n\n def do_things_with_a_close_io_lead(id) do\n @closeio_client.get_lead(id)\n # do things\n end\n end\n ```\n\n In test env, the client will return the test values for each method.\n\n For more detail on the test objects see the `test\/fixtures\/*.json` files.\n\n If you'd like to emulate not finding an object, pass in the `Closex.MockClient.get_not_found_id` value.\n \"\"\"\n\n @not_found_id \"not_found\"\n def get_not_found_id do\n @not_found_id\n end\n\n @lead_id \"lead_IIDHIStmFcFQZZP0BRe99V1MCoXWz2PGCm6EDmR9v2O\"\n def get_lead_id do\n @lead_id\n end\n\n @opportunity_id \"oppo_8eB77gAdf8FMy6GsNHEy84f7uoeEWv55slvUjKQZpJt\"\n def get_opportunity_id do\n @opportunity_id\n end\n\n @doc \"\"\"\n Gets a lead from CloseIO.\n\n Returns `{:ok, lead}`.\n\n ## Examples\n\n iex> Closex.MockClient.get_lead(\"1\")\n nil\n > Closex.MockClient.get_lead(Closex.MockClient.get_lead_id)\n ...contents of test\/fixtures\/lead.json...\n iex> Closex.MockClient.get_lead(Closex.MockClient.get_not_found_id)\n {:error, :mock_not_found}\n \"\"\"\n def get_lead(id, opts \\\\ [])\n def get_lead(id = @lead_id, opts) do\n lead = load(\"lead.json\")\n send self(), {:closex_mock_client, :get_lead, [id, opts]}\n {:ok, lead}\n end\n def get_lead(id = @not_found_id, opts) do\n send self(), {:closex_mock_client, :get_lead, [id, opts]}\n {:error, :mock_not_found}\n end\n\n @doc \"\"\"\n Gets an opportunity from CloseIO.\n\n Returns `{:ok, opportunity}`.\n\n ## Examples\n\n iex> Closex.MockClient.get_opportunity(\"1\")\n nil\n > Closex.MockClient.get_opportunity(Closex.MockClient.get_opportunity_id)\n ...contents of test\/fixtures\/opportunity.json...\n iex> Closex.MockClient.get_opportunity(Closex.MockClient.get_not_found_id)\n {:error, :mock_not_found}\n \"\"\"\n def get_opportunity(id, opts \\\\ [])\n<<<<<<< HEAD\n=======\n def get_opportunity(id = @opportunity_id, opts) do\n lead = load(\"opportunity.json\")\n send self(), {:closex_mock_client, :get_opportunity, [id, opts]}\n {:ok, lead}\n end\n>>>>>>> Docs for opportunity id\n def get_opportunity(id = @not_found_id, opts) do\n send self(), {:closex_mock_client, :get_opportunity, [id, opts]}\n {:error, :mock_not_found}\n end\n def get_opportunity(id, opts) do\n opportunity = load(\"opportunity.json\")\n |> Map.merge(%{\"id\" => id})\n send self(), {:closex_mock_client, :get_opportunity, [id, opts]}\n {:ok, opportunity}\n end\n\n def get_lead_custom_field(id, opts \\\\ [])\n def get_lead_custom_field(id = \"lcf_v6S011I6MqcbVvB2FA5Nk8dr5MkL8sWuCiG8cUleO9c\", opts) do\n lead_custom_field = load(\"lead_custom_field.json\")\n send self(), {:closex_mock_client, :get_lead_custom_field, [id, opts]}\n {:ok, lead_custom_field}\n end\n def get_lead_custom_field(id = @not_found_id, opts) do\n send self(), {:closex_mock_client, :get_lead_custom_field, [id, opts]}\n {:error, :mock_not_found}\n end\n\n def get_organization(id, opts \\\\ [])\n def get_organization(id = \"orga_bwwWG475zqWiQGur0thQshwVXo8rIYecQHDWFanqhen\", opts) do\n organization = load(\"organization.json\")\n send self(), {:closex_mock_client, :get_organization, [id, opts]}\n {:ok, organization}\n end\n def get_organization(id = @not_found_id, opts) do\n send self(), {:closex_mock_client, :get_organization, [id, opts]}\n {:error, :mock_not_found}\n end\n\n def get_lead_statuses(opts \\\\ []) do\n lead_statuses = load(\"lead_statuses.json\")\n send self(), {:closex_mock_client, :get_lead_statuses, [opts]}\n {:ok, lead_statuses}\n end\n\n def get_opportunity_statuses(opts \\\\ []) do\n opportunity_statuses = load(\"opportunity_statuses.json\")\n send self(), {:closex_mock_client, :get_opportunity_statuses, [opts]}\n {:ok, opportunity_statuses}\n end\n\n def get_users(opts \\\\ []) do\n users = load(\"users.json\")\n send self(), {:closex_mock_client, :get_users, [opts]}\n {:ok, users}\n end\n\n # TODO: implement these mocks\n def create_lead(_payload, _opts \\\\ []), do: :noop\n def update_lead(lead_id, payload, opts \\\\ []) do\n lead = load(\"lead.json\")\n |> Map.merge(payload)\n |> Map.merge(%{\"id\" => lead_id})\n send self(), {:closex_mock_client, :update_lead, [lead_id, payload, opts]}\n {:ok, lead}\n end\n def create_opportunity(_payload, _opts \\\\ []), do: :noop\n def update_opportunity(opportunity_id, payload, opts \\\\ []) do\n opportunity = load(\"opportunity.json\")\n |> Map.merge(payload)\n |> Map.merge(%{\"id\" => opportunity_id})\n send self(), {:closex_mock_client, :update_opportunity, [opportunity_id, payload, opts]}\n {:ok, opportunity}\n end\n def send_email(_payload, _opts \\\\ []), do: :noop\n def find_leads(_search_term, _opts \\\\ []), do: :noop\n\n @fixtures_path Path.join([File.cwd!, \"test\", \"fixtures\"])\n defp load(filename) do\n [@fixtures_path, filename]\n |> Path.join\n |> File.read!\n |> Poison.decode!\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"c82e1fc075c47b5102d51f68482fa14c79e2b636","subject":"Improve test coverage for the Redix module","message":"Improve test coverage for the Redix module\n","repos":"whatyouhide\/redix","old_file":"test\/redix_test.exs","new_file":"test\/redix_test.exs","new_contents":"defmodule RedixTest do\n use ExUnit.Case, async: true\n\n import ExUnit.CaptureLog\n\n alias Redix.{\n ConnectionError,\n Error\n }\n\n setup_all do\n {:ok, conn} = Redix.start_link()\n Redix.command!(conn, [\"FLUSHALL\"])\n Redix.stop(conn)\n :ok\n end\n\n describe \"start_link\/2\" do\n test \"specifying a database\" do\n {:ok, c} = Redix.start_link(database: 1)\n assert Redix.command(c, ~w(SET my_key my_value)) == {:ok, \"OK\"}\n\n # Let's check we didn't write to the default database (which is 0).\n {:ok, c} = Redix.start_link()\n assert Redix.command(c, ~w(GET my_key)) == {:ok, nil}\n end\n\n test \"specifying a non existing database\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n {:ok, pid} = Redix.start_link(database: 1000)\n\n assert_receive {:EXIT, ^pid, %Error{message: message}}, 500\n assert message in [\"ERR invalid DB index\", \"ERR DB index is out of range\"]\n end)\n end\n\n test \"specifying a password when no password is set\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n {:ok, pid} = Redix.start_link(password: \"foo\")\n\n assert_receive {:EXIT, ^pid, %Error{message: message}}, 500\n\n assert message =~ \"ERR Client sent AUTH\" or\n message =~ \"ERR AUTH called without any password\"\n end)\n end\n\n test \"specifying a password when a password is set\" do\n {:ok, pid} = Redix.start_link(port: 16379, password: \"some-password\")\n assert Redix.command(pid, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"when unable to connect to Redis with sync_connect: true\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n\n assert {:error, %Redix.ConnectionError{reason: reason}} =\n Redix.start_link(host: \"nonexistent\", sync_connect: true)\n\n assert_receive {:EXIT, _pid, %Redix.ConnectionError{}}, 1000\n\n # Apparently somewhere the error reason is :nxdomain but some other times it's\n # :timeout.\n assert reason in [:nxdomain, :timeout]\n end)\n end\n\n test \"when unable to connect to Redis with sync_connect: false\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n {:ok, pid} = Redix.start_link(host: \"nonexistent\", sync_connect: false)\n refute_receive {:EXIT, ^pid, :nxdomain}, 200\n end)\n end\n\n test \"using a redis:\/\/ url\" do\n {:ok, pid} = Redix.start_link(\"redis:\/\/localhost:6379\/3\")\n assert Redix.command(pid, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"using a rediss:\/\/ url, ignoring certificate\" do\n {:ok, pid} =\n Redix.start_link(\"rediss:\/\/localhost:6384\/3\",\n socket_opts: [verify: :verify_none, reuse_sessions: false]\n )\n\n assert Redix.command(pid, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"using a rediss:\/\/ url, unknown certificate\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n\n assert {:error, error} =\n Redix.start_link(\"rediss:\/\/localhost:6384\/3\",\n socket_opts: [reuse_sessions: false],\n sync_connect: true\n )\n\n assert %Redix.ConnectionError{reason: {:tls_alert, _}} = error\n assert_receive {:EXIT, _pid, ^error}, 1000\n end)\n end\n\n test \"name registration\" do\n {:ok, pid} = Redix.start_link(name: :redix_server)\n assert Process.whereis(:redix_server) == pid\n assert Redix.command(:redix_server, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"passing options along with a Redis URI\" do\n {:ok, pid} = Redix.start_link(\"redis:\/\/localhost\", name: :redix_uri)\n assert Process.whereis(:redix_uri) == pid\n end\n\n test \"using gen_statem options\" do\n fullsweep_after = Enum.random(0..50000)\n {:ok, pid} = Redix.start_link(spawn_opt: [fullsweep_after: fullsweep_after])\n {:garbage_collection, info} = Process.info(pid, :garbage_collection)\n assert info[:fullsweep_after] == fullsweep_after\n end\n end\n\n test \"child_spec\/1\" do\n default_spec = %{\n id: Redix,\n start: {Redix, :start_link, []},\n type: :worker\n }\n\n args_path = [:start, Access.elem(2)]\n\n assert Redix.child_spec(\"redis:\/\/localhost\") ==\n put_in(default_spec, args_path, [\"redis:\/\/localhost\"])\n\n assert Redix.child_spec([]) == put_in(default_spec, args_path, [[]])\n assert Redix.child_spec(name: :redix) == put_in(default_spec, args_path, [[name: :redix]])\n\n assert Redix.child_spec({\"redis:\/\/localhost\", name: :redix}) ==\n put_in(default_spec, args_path, [\"redis:\/\/localhost\", [name: :redix]])\n end\n\n describe \"stop\/1\" do\n test \"stops the connection\" do\n {:ok, pid} = Redix.start_link()\n ref = Process.monitor(pid)\n assert Redix.stop(pid) == :ok\n\n assert_receive {:DOWN, ^ref, _, _, :normal}, 500\n end\n\n test \"closes the socket as well\" do\n {:ok, pid} = Redix.start_link(sync_connect: true)\n\n # This is a hack to get the socket. If I'll have a better idea, good for me :).\n {_, data} = :sys.get_state(pid)\n\n assert Port.info(data.socket) != nil\n assert Redix.stop(pid) == :ok\n assert Port.info(data.socket) == nil\n end\n end\n\n describe \"command\/2\" do\n setup :connect\n\n test \"PING\", %{conn: c} do\n assert Redix.command(c, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"transactions - MULTI\/EXEC\", %{conn: c} do\n assert Redix.command(c, [\"MULTI\"]) == {:ok, \"OK\"}\n assert Redix.command(c, [\"INCR\", \"multifoo\"]) == {:ok, \"QUEUED\"}\n assert Redix.command(c, [\"INCR\", \"multibar\"]) == {:ok, \"QUEUED\"}\n assert Redix.command(c, [\"INCRBY\", \"multifoo\", 4]) == {:ok, \"QUEUED\"}\n assert Redix.command(c, [\"EXEC\"]) == {:ok, [1, 1, 5]}\n end\n\n test \"transactions - MULTI\/DISCARD\", %{conn: c} do\n Redix.command!(c, [\"SET\", \"discarding\", \"foo\"])\n\n assert Redix.command(c, [\"MULTI\"]) == {:ok, \"OK\"}\n assert Redix.command(c, [\"SET\", \"discarding\", \"bar\"]) == {:ok, \"QUEUED\"}\n # Discarding\n assert Redix.command(c, [\"DISCARD\"]) == {:ok, \"OK\"}\n assert Redix.command(c, [\"GET\", \"discarding\"]) == {:ok, \"foo\"}\n end\n\n test \"Lua scripting - EVAL\", %{conn: c} do\n script = \"\"\"\n redis.call(\"SET\", \"evalling\", \"yes\")\n return {KEYS[1],ARGV[1],ARGV[2]}\n \"\"\"\n\n cmds = [\"eval\", script, \"1\", \"key\", \"first\", \"second\"]\n\n assert Redix.command(c, cmds) == {:ok, [\"key\", \"first\", \"second\"]}\n assert Redix.command(c, [\"GET\", \"evalling\"]) == {:ok, \"yes\"}\n end\n\n test \"command\/2 - Lua scripting: SCRIPT LOAD, SCRIPT EXISTS, EVALSHA\", %{conn: c} do\n script = \"\"\"\n return 'hello world'\n \"\"\"\n\n {:ok, sha} = Redix.command(c, [\"SCRIPT\", \"LOAD\", script])\n assert is_binary(sha)\n assert Redix.command(c, [\"SCRIPT\", \"EXISTS\", sha, \"foo\"]) == {:ok, [1, 0]}\n\n # Eval'ing the script\n assert Redix.command(c, [\"EVALSHA\", sha, 0]) == {:ok, \"hello world\"}\n end\n\n test \"Redis errors\", %{conn: c} do\n {:ok, _} = Redix.command(c, ~w(SET errs foo))\n\n message = \"ERR value is not an integer or out of range\"\n assert Redix.command(c, ~w(INCR errs)) == {:error, %Redix.Error{message: message}}\n end\n\n test \"passing an empty list returns an error\", %{conn: c} do\n message = \"got an empty command ([]), which is not a valid Redis command\"\n assert_raise ArgumentError, message, fn -> Redix.command(c, []) end\n end\n\n test \"timeout\", %{conn: c} do\n assert {:error, %ConnectionError{reason: :timeout}} = Redix.command(c, ~W(PING), timeout: 0)\n end\n\n test \"Redix process crashes while waiting\", %{conn: conn} do\n Process.flag(:trap_exit, true)\n\n pid =\n spawn_link(fn ->\n Redix.command(conn, ~w(BLPOP mid_command_disconnection 0))\n end)\n\n # We sleep to allow the task to issue the command to Redix.\n Process.sleep(100)\n\n Process.exit(conn, :kill)\n\n assert_receive {:EXIT, ^conn, :killed}\n assert_receive {:EXIT, ^pid, :killed}\n end\n\n test \"passing a non-list as the command\", %{conn: c} do\n message = \"expected a list of binaries as each Redis command, got: \\\"PING\\\"\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.command(c, \"PING\")\n end\n end\n end\n\n describe \"pipeline\/2\" do\n setup :connect\n\n test \"basic interaction\", %{conn: c} do\n commands = [\n [\"SET\", \"pipe\", \"10\"],\n [\"INCR\", \"pipe\"],\n [\"GET\", \"pipe\"]\n ]\n\n assert Redix.pipeline(c, commands) == {:ok, [\"OK\", 11, \"11\"]}\n end\n\n test \"a lot of commands so that TCP gets stressed\", %{conn: c} do\n assert {:ok, \"OK\"} = Redix.command(c, ~w(SET stress_pipeline foo))\n\n ncommands = 10000\n commands = List.duplicate(~w(GET stress_pipeline), ncommands)\n\n # Let's do it twice to be sure the server can handle the data.\n {:ok, results} = Redix.pipeline(c, commands)\n assert length(results) == ncommands\n {:ok, results} = Redix.pipeline(c, commands)\n assert length(results) == ncommands\n end\n\n test \"a single command should still return a list of results\", %{conn: c} do\n assert Redix.pipeline(c, [[\"PING\"]]) == {:ok, [\"PONG\"]}\n end\n\n test \"Redis errors in the response\", %{conn: c} do\n msg = \"ERR value is not an integer or out of range\"\n assert {:ok, resp} = Redix.pipeline(c, [~w(SET pipeline_errs foo), ~w(INCR pipeline_errs)])\n assert resp == [\"OK\", %Error{message: msg}]\n end\n\n test \"passing an empty list of commands raises an error\", %{conn: c} do\n msg = \"no commands passed to the pipeline\"\n assert_raise ArgumentError, msg, fn -> Redix.pipeline(c, []) end\n end\n\n test \"passing one or more empty commands returns an error\", %{conn: c} do\n message = \"got an empty command ([]), which is not a valid Redis command\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, [[]])\n end\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, [[\"PING\"], [], [\"PING\"]])\n end\n end\n\n test \"passing a PubSub command causes an error\", %{conn: c} do\n assert_raise ArgumentError, ~r{Redix doesn't support Pub\/Sub}, fn ->\n Redix.pipeline(c, [[\"PING\"], [\"SUBSCRIBE\", \"foo\"]])\n end\n end\n\n test \"passing CLIENT REPLY commands causes an error\", %{conn: c} do\n assert_raise ArgumentError, ~r{CLIENT REPLY commands are forbidden}, fn ->\n Redix.pipeline(c, [[\"CLIENT\", \"REPLY\", \"ON\"]])\n end\n end\n\n test \"timeout\", %{conn: c} do\n assert {:error, %ConnectionError{reason: :timeout}} =\n Redix.pipeline(c, [~w(PING), ~w(PING)], timeout: 0)\n end\n\n test \"commands must be lists of binaries\", %{conn: c} do\n message = \"expected a list of Redis commands, got: \\\"PING\\\"\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, \"PING\")\n end\n\n message = \"expected a list of binaries as each Redis command, got: \\\"PING\\\"\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, [\"PING\"])\n end\n end\n end\n\n describe \"command!\/2\" do\n setup :connect\n\n test \"simple commands\", %{conn: c} do\n assert Redix.command!(c, [\"PING\"]) == \"PONG\"\n assert Redix.command!(c, [\"SET\", \"bang\", \"foo\"]) == \"OK\"\n assert Redix.command!(c, [\"GET\", \"bang\"]) == \"foo\"\n end\n\n test \"Redis errors\", %{conn: c} do\n assert_raise Redix.Error, ~r\/ERR unknown command .NONEXISTENT.\/, fn ->\n Redix.command!(c, [\"NONEXISTENT\"])\n end\n\n \"OK\" = Redix.command!(c, [\"SET\", \"bang_errors\", \"foo\"])\n\n assert_raise Redix.Error, \"ERR value is not an integer or out of range\", fn ->\n Redix.command!(c, [\"INCR\", \"bang_errors\"])\n end\n end\n\n test \"connection errors\", %{conn: c} do\n assert_raise Redix.ConnectionError, \":timeout\", fn ->\n Redix.command!(c, [\"PING\"], timeout: 0)\n end\n end\n end\n\n describe \"pipeline!\/2\" do\n setup :connect\n\n test \"simple commands\", %{conn: c} do\n assert Redix.pipeline!(c, [~w(SET ppbang foo), ~w(GET ppbang)]) == ~w(OK foo)\n end\n\n test \"Redis errors in the list of results\", %{conn: c} do\n commands = [~w(SET ppbang_errors foo), ~w(INCR ppbang_errors)]\n\n msg = \"ERR value is not an integer or out of range\"\n assert Redix.pipeline!(c, commands) == [\"OK\", %Redix.Error{message: msg}]\n end\n\n test \"connection errors\", %{conn: c} do\n assert_raise Redix.ConnectionError, \":timeout\", fn ->\n Redix.pipeline!(c, [[\"PING\"]], timeout: 0)\n end\n end\n end\n\n describe \"transaction_pipeline\/3\" do\n setup :connect\n\n test \"non-bang version\", %{conn: conn} do\n commands = [~w(SET transaction_pipeline_key 1), ~w(GET transaction_pipeline_key)]\n assert Redix.transaction_pipeline(conn, commands) == {:ok, [\"OK\", \"1\"]}\n\n assert Redix.transaction_pipeline(conn, commands, timeout: 0) ==\n {:error, %ConnectionError{reason: :timeout}}\n end\n\n test \"bang version\", %{conn: conn} do\n commands = [~w(SET transaction_pipeline_key 1), ~w(GET transaction_pipeline_key)]\n assert Redix.transaction_pipeline!(conn, commands) == [\"OK\", \"1\"]\n\n assert_raise Redix.ConnectionError, fn ->\n Redix.transaction_pipeline!(conn, commands, timeout: 0)\n end\n end\n end\n\n describe \"noreply_* functions\" do\n setup :connect\n\n test \"noreply_pipeline\/3\", %{conn: conn} do\n commands = [~w(INCR noreply_pl_mykey), ~w(INCR noreply_pl_mykey)]\n assert Redix.noreply_pipeline(conn, commands) == :ok\n assert Redix.command!(conn, ~w(GET noreply_pl_mykey)) == \"2\"\n\n assert Redix.noreply_pipeline(conn, commands, timeout: 0) ==\n {:error, %ConnectionError{reason: :timeout}}\n end\n\n test \"noreply_pipeline!\/3\", %{conn: conn} do\n commands = [~w(INCR noreply_pl_bang_mykey), ~w(INCR noreply_pl_bang_mykey)]\n assert Redix.noreply_pipeline!(conn, commands) == :ok\n assert Redix.command!(conn, ~w(GET noreply_pl_bang_mykey)) == \"2\"\n\n assert_raise Redix.ConnectionError, fn ->\n Redix.noreply_pipeline!(conn, commands, timeout: 0)\n end\n end\n\n test \"noreply_command\/3\", %{conn: conn} do\n assert Redix.noreply_command(conn, [\"SET\", \"noreply_cmd_mykey\", \"myvalue\"]) == :ok\n assert Redix.command!(conn, [\"GET\", \"noreply_cmd_mykey\"]) == \"myvalue\"\n\n assert Redix.noreply_command(conn, [\"SET\", \"noreply_cmd_mykey\", \"myvalue\"], timeout: 0) ==\n {:error, %ConnectionError{reason: :timeout}}\n end\n\n test \"noreply_command!\/3\", %{conn: conn} do\n assert Redix.noreply_command!(conn, [\"SET\", \"noreply_cmd_bang_mykey\", \"myvalue\"]) == :ok\n assert Redix.command!(conn, [\"GET\", \"noreply_cmd_bang_mykey\"]) == \"myvalue\"\n\n assert_raise Redix.ConnectionError, fn ->\n Redix.noreply_command!(conn, [\"SET\", \"noreply_cmd_bang_mykey\", \"myvalue\"], timeout: 0)\n end\n end\n end\n\n describe \"timeouts and network errors\" do\n setup :connect\n\n test \"client suicide and reconnections\", %{conn: c} do\n capture_log(fn ->\n assert {:ok, _} = Redix.command(c, ~w(QUIT))\n\n # When the socket is closed, we reply with {:error, closed}. We sleep so\n # we're sure that the socket is closed (and we don't get {:error,\n # disconnected} before the socket closed after we sent the PING command\n # to Redix).\n :timer.sleep(100)\n assert Redix.command(c, ~w(PING)) == {:error, %ConnectionError{reason: :closed}}\n\n # Redix retries the first reconnection after 500ms, and we waited 100 already.\n :timer.sleep(500)\n assert {:ok, \"PONG\"} = Redix.command(c, ~w(PING))\n end)\n end\n\n test \"timeouts\", %{conn: c} do\n assert {:error, %ConnectionError{reason: :timeout}} = Redix.command(c, ~w(PING), timeout: 0)\n\n # Let's check that the Redix connection doesn't reply anyways, even if the\n # timeout happened.\n refute_receive {_ref, _message}\n end\n\n test \"mid-command disconnections\", %{conn: conn} do\n {:ok, kill_conn} = Redix.start_link()\n\n capture_log(fn ->\n task = Task.async(fn -> Redix.command(conn, ~w(BLPOP mid_command_disconnection 0)) end)\n\n # Give the task the time to issue the command to Redis, then kill the connection.\n Process.sleep(50)\n Redix.command!(kill_conn, ~w(CLIENT KILL TYPE normal SKIPME yes))\n\n assert Task.await(task, 100) == {:error, %ConnectionError{reason: :disconnected}}\n end)\n end\n\n test \"no leaking messages when timeout happens at the same time as disconnections\", %{\n conn: conn\n } do\n {:ok, kill_conn} = Redix.start_link()\n\n capture_log(fn ->\n {_pid, ref} =\n Process.spawn(\n fn ->\n error = %ConnectionError{reason: :timeout}\n assert Redix.command(conn, ~w(BLPOP my_list 0), timeout: 0) == {:error, error}\n\n # The fact that we timed out should be respected here, even if the\n # connection is killed (no {:error, :disconnected} message should\n # arrive).\n refute_receive {_ref, _message}\n end,\n [:link, :monitor]\n )\n\n # Give the process time to issue the command to Redis, then kill the connection.\n Process.sleep(50)\n Redix.command!(kill_conn, ~w(CLIENT KILL TYPE normal SKIPME yes))\n\n assert_receive {:DOWN, ^ref, _, _, _}, 200\n end)\n end\n end\n\n test \":exit_on_disconnection option\" do\n {:ok, c} = Redix.start_link(exit_on_disconnection: true)\n Process.flag(:trap_exit, true)\n\n capture_log(fn ->\n Redix.command!(c, ~w(QUIT))\n assert_receive {:EXIT, ^c, %ConnectionError{reason: :tcp_closed}}\n end)\n end\n\n describe \"Telemetry\" do\n test \"emits events when starting a pipeline with pipeline\/3\" do\n {:ok, c} = Redix.start_link()\n {test_name, _arity} = __ENV__.function\n\n parent = self()\n ref = make_ref()\n\n handler = fn event, measurements, meta, _config ->\n if meta.connection == c do\n assert event == [:redix, :pipeline, :start]\n assert is_integer(measurements.system_time)\n assert meta.commands == [[\"PING\"]]\n end\n\n send(parent, ref)\n end\n\n :telemetry.attach(to_string(test_name), [:redix, :pipeline, :start], handler, :no_config)\n\n assert {:ok, [\"PONG\"]} = Redix.pipeline(c, [[\"PING\"]])\n\n assert_receive ^ref\n\n :telemetry.detach(to_string(test_name))\n end\n\n test \"emits events on successful pipelines with pipeline\/3\" do\n {:ok, c} = Redix.start_link()\n {test_name, _arity} = __ENV__.function\n\n parent = self()\n ref = make_ref()\n\n handler = fn event, measurements, meta, _config ->\n if meta.connection == c do\n assert event == [:redix, :pipeline, :stop]\n assert is_integer(measurements.duration) and measurements.duration > 0\n assert meta.commands == [[\"PING\"]]\n end\n\n send(parent, ref)\n end\n\n :telemetry.attach(to_string(test_name), [:redix, :pipeline, :stop], handler, :no_config)\n\n assert {:ok, [\"PONG\"]} = Redix.pipeline(c, [[\"PING\"]])\n\n assert_receive ^ref\n\n :telemetry.detach(to_string(test_name))\n end\n\n test \"emits events on error pipelines with pipeline\/3\" do\n {:ok, c} = Redix.start_link()\n {test_name, _arity} = __ENV__.function\n\n parent = self()\n ref = make_ref()\n\n handler = fn event, measurements, meta, _config ->\n if meta.connection == c do\n assert event == [:redix, :pipeline, :stop]\n assert is_integer(measurements.duration)\n assert meta.commands == [[\"PING\"], [\"PING\"]]\n assert meta.kind == :error\n assert meta.reason == %ConnectionError{reason: :timeout}\n end\n\n send(parent, ref)\n end\n\n :telemetry.attach(to_string(test_name), [:redix, :pipeline, :stop], handler, :no_config)\n\n assert {:error, %ConnectionError{reason: :timeout}} =\n Redix.pipeline(c, [~w(PING), ~w(PING)], timeout: 0)\n\n assert_receive ^ref\n\n :telemetry.detach(to_string(test_name))\n end\n\n test \"emits connection-related events on disconnections and reconnections\" do\n {test_name, _arity} = __ENV__.function\n\n parent = self()\n ref = make_ref()\n\n handler = fn event, measurements, meta, _config ->\n # We need to run this test only if was called for this Redix connection so that\n # we can run in parallel with the pubsub tests.\n if meta.connection == :redix_telemetry_test do\n assert measurements == %{}\n\n case event do\n [:redix, :connection] -> send(parent, {ref, :connected, meta})\n [:redix, :disconnection] -> send(parent, {ref, :disconnected, meta})\n end\n end\n end\n\n events = [[:redix, :connection], [:redix, :disconnection]]\n :ok = :telemetry.attach_many(to_string(test_name), events, handler, :no_config)\n\n {:ok, c} = Redix.start_link(name: :redix_telemetry_test)\n\n assert_receive {^ref, :connected, meta}, 1000\n assert %{address: \"localhost:6379\", connection: _, reconnection: false} = meta\n\n capture_log(fn ->\n assert {:ok, _} = Redix.command(c, ~w(QUIT))\n\n assert_receive {^ref, :disconnected, meta}, 1000\n assert %{address: \"localhost:6379\", connection: _} = meta\n\n assert_receive {^ref, :connected, meta}, 1000\n assert %{address: \"localhost:6379\", connection: _, reconnection: true} = meta\n end)\n end\n end\n\n defp connect(_context) do\n {:ok, conn} = Redix.start_link()\n {:ok, %{conn: conn}}\n end\nend\n","old_contents":"defmodule RedixTest do\n use ExUnit.Case, async: true\n\n import ExUnit.CaptureLog\n\n alias Redix.{\n ConnectionError,\n Error\n }\n\n setup_all do\n {:ok, conn} = Redix.start_link()\n Redix.command!(conn, [\"FLUSHALL\"])\n Redix.stop(conn)\n :ok\n end\n\n describe \"start_link\/2\" do\n test \"specifying a database\" do\n {:ok, c} = Redix.start_link(database: 1)\n assert Redix.command(c, ~w(SET my_key my_value)) == {:ok, \"OK\"}\n\n # Let's check we didn't write to the default database (which is 0).\n {:ok, c} = Redix.start_link()\n assert Redix.command(c, ~w(GET my_key)) == {:ok, nil}\n end\n\n test \"specifying a non existing database\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n {:ok, pid} = Redix.start_link(database: 1000)\n\n assert_receive {:EXIT, ^pid, %Error{message: message}}, 500\n assert message in [\"ERR invalid DB index\", \"ERR DB index is out of range\"]\n end)\n end\n\n test \"specifying a password when no password is set\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n {:ok, pid} = Redix.start_link(password: \"foo\")\n\n assert_receive {:EXIT, ^pid, %Error{message: message}}, 500\n\n assert message =~ \"ERR Client sent AUTH\" or\n message =~ \"ERR AUTH called without any password\"\n end)\n end\n\n test \"specifying a password when a password is set\" do\n {:ok, pid} = Redix.start_link(port: 16379, password: \"some-password\")\n assert Redix.command(pid, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"when unable to connect to Redis with sync_connect: true\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n\n assert {:error, %Redix.ConnectionError{reason: reason}} =\n Redix.start_link(host: \"nonexistent\", sync_connect: true)\n\n assert_receive {:EXIT, _pid, %Redix.ConnectionError{}}, 1000\n\n # Apparently somewhere the error reason is :nxdomain but some other times it's\n # :timeout.\n assert reason in [:nxdomain, :timeout]\n end)\n end\n\n test \"when unable to connect to Redis with sync_connect: false\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n {:ok, pid} = Redix.start_link(host: \"nonexistent\", sync_connect: false)\n refute_receive {:EXIT, ^pid, :nxdomain}, 200\n end)\n end\n\n test \"using a redis:\/\/ url\" do\n {:ok, pid} = Redix.start_link(\"redis:\/\/localhost:6379\/3\")\n assert Redix.command(pid, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"using a rediss:\/\/ url, ignoring certificate\" do\n {:ok, pid} =\n Redix.start_link(\"rediss:\/\/localhost:6384\/3\",\n socket_opts: [verify: :verify_none, reuse_sessions: false]\n )\n\n assert Redix.command(pid, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"using a rediss:\/\/ url, unknown certificate\" do\n capture_log(fn ->\n Process.flag(:trap_exit, true)\n\n assert {:error, error} =\n Redix.start_link(\"rediss:\/\/localhost:6384\/3\",\n socket_opts: [reuse_sessions: false],\n sync_connect: true\n )\n\n assert %Redix.ConnectionError{reason: {:tls_alert, _}} = error\n assert_receive {:EXIT, _pid, ^error}, 1000\n end)\n end\n\n test \"name registration\" do\n {:ok, pid} = Redix.start_link(name: :redix_server)\n assert Process.whereis(:redix_server) == pid\n assert Redix.command(:redix_server, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"passing options along with a Redis URI\" do\n {:ok, pid} = Redix.start_link(\"redis:\/\/localhost\", name: :redix_uri)\n assert Process.whereis(:redix_uri) == pid\n end\n\n test \"using gen_statem options\" do\n fullsweep_after = Enum.random(0..50000)\n {:ok, pid} = Redix.start_link(spawn_opt: [fullsweep_after: fullsweep_after])\n {:garbage_collection, info} = Process.info(pid, :garbage_collection)\n assert info[:fullsweep_after] == fullsweep_after\n end\n end\n\n test \"child_spec\/1\" do\n default_spec = %{\n id: Redix,\n start: {Redix, :start_link, []},\n type: :worker\n }\n\n args_path = [:start, Access.elem(2)]\n\n assert Redix.child_spec(\"redis:\/\/localhost\") ==\n put_in(default_spec, args_path, [\"redis:\/\/localhost\"])\n\n assert Redix.child_spec([]) == put_in(default_spec, args_path, [[]])\n assert Redix.child_spec(name: :redix) == put_in(default_spec, args_path, [[name: :redix]])\n\n assert Redix.child_spec({\"redis:\/\/localhost\", name: :redix}) ==\n put_in(default_spec, args_path, [\"redis:\/\/localhost\", [name: :redix]])\n end\n\n describe \"stop\/1\" do\n test \"stops the connection\" do\n {:ok, pid} = Redix.start_link()\n ref = Process.monitor(pid)\n assert Redix.stop(pid) == :ok\n\n assert_receive {:DOWN, ^ref, _, _, :normal}, 500\n end\n\n test \"closes the socket as well\" do\n {:ok, pid} = Redix.start_link(sync_connect: true)\n\n # This is a hack to get the socket. If I'll have a better idea, good for me :).\n {_, data} = :sys.get_state(pid)\n\n assert Port.info(data.socket) != nil\n assert Redix.stop(pid) == :ok\n assert Port.info(data.socket) == nil\n end\n end\n\n describe \"command\/2\" do\n setup :connect\n\n test \"PING\", %{conn: c} do\n assert Redix.command(c, [\"PING\"]) == {:ok, \"PONG\"}\n end\n\n test \"transactions - MULTI\/EXEC\", %{conn: c} do\n assert Redix.command(c, [\"MULTI\"]) == {:ok, \"OK\"}\n assert Redix.command(c, [\"INCR\", \"multifoo\"]) == {:ok, \"QUEUED\"}\n assert Redix.command(c, [\"INCR\", \"multibar\"]) == {:ok, \"QUEUED\"}\n assert Redix.command(c, [\"INCRBY\", \"multifoo\", 4]) == {:ok, \"QUEUED\"}\n assert Redix.command(c, [\"EXEC\"]) == {:ok, [1, 1, 5]}\n end\n\n test \"transactions - MULTI\/DISCARD\", %{conn: c} do\n Redix.command!(c, [\"SET\", \"discarding\", \"foo\"])\n\n assert Redix.command(c, [\"MULTI\"]) == {:ok, \"OK\"}\n assert Redix.command(c, [\"SET\", \"discarding\", \"bar\"]) == {:ok, \"QUEUED\"}\n # Discarding\n assert Redix.command(c, [\"DISCARD\"]) == {:ok, \"OK\"}\n assert Redix.command(c, [\"GET\", \"discarding\"]) == {:ok, \"foo\"}\n end\n\n test \"Lua scripting - EVAL\", %{conn: c} do\n script = \"\"\"\n redis.call(\"SET\", \"evalling\", \"yes\")\n return {KEYS[1],ARGV[1],ARGV[2]}\n \"\"\"\n\n cmds = [\"eval\", script, \"1\", \"key\", \"first\", \"second\"]\n\n assert Redix.command(c, cmds) == {:ok, [\"key\", \"first\", \"second\"]}\n assert Redix.command(c, [\"GET\", \"evalling\"]) == {:ok, \"yes\"}\n end\n\n test \"command\/2 - Lua scripting: SCRIPT LOAD, SCRIPT EXISTS, EVALSHA\", %{conn: c} do\n script = \"\"\"\n return 'hello world'\n \"\"\"\n\n {:ok, sha} = Redix.command(c, [\"SCRIPT\", \"LOAD\", script])\n assert is_binary(sha)\n assert Redix.command(c, [\"SCRIPT\", \"EXISTS\", sha, \"foo\"]) == {:ok, [1, 0]}\n\n # Eval'ing the script\n assert Redix.command(c, [\"EVALSHA\", sha, 0]) == {:ok, \"hello world\"}\n end\n\n test \"Redis errors\", %{conn: c} do\n {:ok, _} = Redix.command(c, ~w(SET errs foo))\n\n message = \"ERR value is not an integer or out of range\"\n assert Redix.command(c, ~w(INCR errs)) == {:error, %Redix.Error{message: message}}\n end\n\n test \"passing an empty list returns an error\", %{conn: c} do\n message = \"got an empty command ([]), which is not a valid Redis command\"\n assert_raise ArgumentError, message, fn -> Redix.command(c, []) end\n end\n\n test \"timeout\", %{conn: c} do\n assert {:error, %ConnectionError{reason: :timeout}} = Redix.command(c, ~W(PING), timeout: 0)\n end\n\n test \"Redix process crashes while waiting\", %{conn: conn} do\n Process.flag(:trap_exit, true)\n\n pid =\n spawn_link(fn ->\n Redix.command(conn, ~w(BLPOP mid_command_disconnection 0))\n end)\n\n # We sleep to allow the task to issue the command to Redix.\n Process.sleep(100)\n\n Process.exit(conn, :kill)\n\n assert_receive {:EXIT, ^conn, :killed}\n assert_receive {:EXIT, ^pid, :killed}\n end\n\n test \"passing a non-list as the command\", %{conn: c} do\n message = \"expected a list of binaries as each Redis command, got: \\\"PING\\\"\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.command(c, \"PING\")\n end\n end\n end\n\n describe \"pipeline\/2\" do\n setup :connect\n\n test \"basic interaction\", %{conn: c} do\n commands = [\n [\"SET\", \"pipe\", \"10\"],\n [\"INCR\", \"pipe\"],\n [\"GET\", \"pipe\"]\n ]\n\n assert Redix.pipeline(c, commands) == {:ok, [\"OK\", 11, \"11\"]}\n end\n\n test \"a lot of commands so that TCP gets stressed\", %{conn: c} do\n assert {:ok, \"OK\"} = Redix.command(c, ~w(SET stress_pipeline foo))\n\n ncommands = 10000\n commands = List.duplicate(~w(GET stress_pipeline), ncommands)\n\n # Let's do it twice to be sure the server can handle the data.\n {:ok, results} = Redix.pipeline(c, commands)\n assert length(results) == ncommands\n {:ok, results} = Redix.pipeline(c, commands)\n assert length(results) == ncommands\n end\n\n test \"a single command should still return a list of results\", %{conn: c} do\n assert Redix.pipeline(c, [[\"PING\"]]) == {:ok, [\"PONG\"]}\n end\n\n test \"Redis errors in the response\", %{conn: c} do\n msg = \"ERR value is not an integer or out of range\"\n assert {:ok, resp} = Redix.pipeline(c, [~w(SET pipeline_errs foo), ~w(INCR pipeline_errs)])\n assert resp == [\"OK\", %Error{message: msg}]\n end\n\n test \"passing an empty list of commands raises an error\", %{conn: c} do\n msg = \"no commands passed to the pipeline\"\n assert_raise ArgumentError, msg, fn -> Redix.pipeline(c, []) end\n end\n\n test \"passing one or more empty commands returns an error\", %{conn: c} do\n message = \"got an empty command ([]), which is not a valid Redis command\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, [[]])\n end\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, [[\"PING\"], [], [\"PING\"]])\n end\n end\n\n test \"passing a PubSub command causes an error\", %{conn: c} do\n assert_raise ArgumentError, ~r{Redix doesn't support Pub\/Sub}, fn ->\n Redix.pipeline(c, [[\"PING\"], [\"SUBSCRIBE\", \"foo\"]])\n end\n end\n\n test \"timeout\", %{conn: c} do\n assert {:error, %ConnectionError{reason: :timeout}} =\n Redix.pipeline(c, [~w(PING), ~w(PING)], timeout: 0)\n end\n\n test \"commands must be lists of binaries\", %{conn: c} do\n message = \"expected a list of Redis commands, got: \\\"PING\\\"\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, \"PING\")\n end\n\n message = \"expected a list of binaries as each Redis command, got: \\\"PING\\\"\"\n\n assert_raise ArgumentError, message, fn ->\n Redix.pipeline(c, [\"PING\"])\n end\n end\n end\n\n describe \"command!\/2\" do\n setup :connect\n\n test \"simple commands\", %{conn: c} do\n assert Redix.command!(c, [\"PING\"]) == \"PONG\"\n assert Redix.command!(c, [\"SET\", \"bang\", \"foo\"]) == \"OK\"\n assert Redix.command!(c, [\"GET\", \"bang\"]) == \"foo\"\n end\n\n test \"Redis errors\", %{conn: c} do\n assert_raise Redix.Error, ~r\/ERR unknown command .NONEXISTENT.\/, fn ->\n Redix.command!(c, [\"NONEXISTENT\"])\n end\n\n \"OK\" = Redix.command!(c, [\"SET\", \"bang_errors\", \"foo\"])\n\n assert_raise Redix.Error, \"ERR value is not an integer or out of range\", fn ->\n Redix.command!(c, [\"INCR\", \"bang_errors\"])\n end\n end\n\n test \"connection errors\", %{conn: c} do\n assert_raise Redix.ConnectionError, \":timeout\", fn ->\n Redix.command!(c, [\"PING\"], timeout: 0)\n end\n end\n end\n\n describe \"pipeline!\/2\" do\n setup :connect\n\n test \"simple commands\", %{conn: c} do\n assert Redix.pipeline!(c, [~w(SET ppbang foo), ~w(GET ppbang)]) == ~w(OK foo)\n end\n\n test \"Redis errors in the list of results\", %{conn: c} do\n commands = [~w(SET ppbang_errors foo), ~w(INCR ppbang_errors)]\n\n msg = \"ERR value is not an integer or out of range\"\n assert Redix.pipeline!(c, commands) == [\"OK\", %Redix.Error{message: msg}]\n end\n\n test \"connection errors\", %{conn: c} do\n assert_raise Redix.ConnectionError, \":timeout\", fn ->\n Redix.pipeline!(c, [[\"PING\"]], timeout: 0)\n end\n end\n end\n\n describe \"transaction_pipeline\/3\" do\n setup :connect\n\n test \"non-bang version\", %{conn: conn} do\n commands = [~w(SET transaction_pipeline_key 1), ~w(GET transaction_pipeline_key)]\n assert Redix.transaction_pipeline(conn, commands) == {:ok, [\"OK\", \"1\"]}\n end\n\n test \"bang version\", %{conn: conn} do\n commands = [~w(SET transaction_pipeline_key 1), ~w(GET transaction_pipeline_key)]\n assert Redix.transaction_pipeline!(conn, commands) == [\"OK\", \"1\"]\n end\n end\n\n describe \"noreply_* functions\" do\n setup :connect\n\n test \"noreply_pipeline\/3\", %{conn: conn} do\n commands = [~w(INCR noreply_pl_mykey), ~w(INCR noreply_pl_mykey)]\n assert Redix.noreply_pipeline(conn, commands) == :ok\n assert Redix.command!(conn, ~w(GET noreply_pl_mykey)) == \"2\"\n end\n\n test \"noreply_command\/3\", %{conn: conn} do\n assert Redix.noreply_command(conn, [\"SET\", \"noreply_cmd_mykey\", \"myvalue\"]) == :ok\n assert Redix.command!(conn, [\"GET\", \"noreply_cmd_mykey\"]) == \"myvalue\"\n end\n end\n\n describe \"timeouts and network errors\" do\n setup :connect\n\n test \"client suicide and reconnections\", %{conn: c} do\n capture_log(fn ->\n assert {:ok, _} = Redix.command(c, ~w(QUIT))\n\n # When the socket is closed, we reply with {:error, closed}. We sleep so\n # we're sure that the socket is closed (and we don't get {:error,\n # disconnected} before the socket closed after we sent the PING command\n # to Redix).\n :timer.sleep(100)\n assert Redix.command(c, ~w(PING)) == {:error, %ConnectionError{reason: :closed}}\n\n # Redix retries the first reconnection after 500ms, and we waited 100 already.\n :timer.sleep(500)\n assert {:ok, \"PONG\"} = Redix.command(c, ~w(PING))\n end)\n end\n\n test \"timeouts\", %{conn: c} do\n assert {:error, %ConnectionError{reason: :timeout}} = Redix.command(c, ~w(PING), timeout: 0)\n\n # Let's check that the Redix connection doesn't reply anyways, even if the\n # timeout happened.\n refute_receive {_ref, _message}\n end\n\n test \"mid-command disconnections\", %{conn: conn} do\n {:ok, kill_conn} = Redix.start_link()\n\n capture_log(fn ->\n task = Task.async(fn -> Redix.command(conn, ~w(BLPOP mid_command_disconnection 0)) end)\n\n # Give the task the time to issue the command to Redis, then kill the connection.\n Process.sleep(50)\n Redix.command!(kill_conn, ~w(CLIENT KILL TYPE normal SKIPME yes))\n\n assert Task.await(task, 100) == {:error, %ConnectionError{reason: :disconnected}}\n end)\n end\n\n test \"no leaking messages when timeout happens at the same time as disconnections\", %{\n conn: conn\n } do\n {:ok, kill_conn} = Redix.start_link()\n\n capture_log(fn ->\n {_pid, ref} =\n Process.spawn(\n fn ->\n error = %ConnectionError{reason: :timeout}\n assert Redix.command(conn, ~w(BLPOP my_list 0), timeout: 0) == {:error, error}\n\n # The fact that we timed out should be respected here, even if the\n # connection is killed (no {:error, :disconnected} message should\n # arrive).\n refute_receive {_ref, _message}\n end,\n [:link, :monitor]\n )\n\n # Give the process time to issue the command to Redis, then kill the connection.\n Process.sleep(50)\n Redix.command!(kill_conn, ~w(CLIENT KILL TYPE normal SKIPME yes))\n\n assert_receive {:DOWN, ^ref, _, _, _}, 200\n end)\n end\n end\n\n test \":exit_on_disconnection option\" do\n {:ok, c} = Redix.start_link(exit_on_disconnection: true)\n Process.flag(:trap_exit, true)\n\n capture_log(fn ->\n Redix.command!(c, ~w(QUIT))\n assert_receive {:EXIT, ^c, %ConnectionError{reason: :tcp_closed}}\n end)\n end\n\n describe \"Telemetry\" do\n test \"emits events when starting a pipeline with pipeline\/3\" do\n {:ok, c} = Redix.start_link()\n {test_name, _arity} = __ENV__.function\n\n parent = self()\n ref = make_ref()\n\n handler = fn event, measurements, meta, _config ->\n if meta.connection == c do\n assert event == [:redix, :pipeline, :start]\n assert is_integer(measurements.system_time)\n assert meta.commands == [[\"PING\"]]\n end\n\n send(parent, ref)\n end\n\n :telemetry.attach(to_string(test_name), [:redix, :pipeline, :start], handler, :no_config)\n\n assert {:ok, [\"PONG\"]} = Redix.pipeline(c, [[\"PING\"]])\n\n assert_receive ^ref\n\n :telemetry.detach(to_string(test_name))\n end\n\n test \"emits events on successful pipelines with pipeline\/3\" do\n {:ok, c} = Redix.start_link()\n {test_name, _arity} = __ENV__.function\n\n parent = self()\n ref = make_ref()\n\n handler = fn event, measurements, meta, _config ->\n if meta.connection == c do\n assert event == [:redix, :pipeline, :stop]\n assert is_integer(measurements.duration) and measurements.duration > 0\n assert meta.commands == [[\"PING\"]]\n end\n\n send(parent, ref)\n end\n\n :telemetry.attach(to_string(test_name), [:redix, :pipeline, :stop], handler, :no_config)\n\n assert {:ok, [\"PONG\"]} = Redix.pipeline(c, [[\"PING\"]])\n\n assert_receive ^ref\n\n :telemetry.detach(to_string(test_name))\n end\n\n test \"emits events on error pipelines with pipeline\/3\" do\n {:ok, c} = Redix.start_link()\n {test_name, _arity} = __ENV__.function\n\n parent = self()\n ref = make_ref()\n\n handler = fn event, measurements, meta, _config ->\n if meta.connection == c do\n assert event == [:redix, :pipeline, :stop]\n assert is_integer(measurements.duration)\n assert meta.commands == [[\"PING\"], [\"PING\"]]\n assert meta.kind == :error\n assert meta.reason == %ConnectionError{reason: :timeout}\n end\n\n send(parent, ref)\n end\n\n :telemetry.attach(to_string(test_name), [:redix, :pipeline, :stop], handler, :no_config)\n\n assert {:error, %ConnectionError{reason: :timeout}} =\n Redix.pipeline(c, [~w(PING), ~w(PING)], timeout: 0)\n\n assert_receive ^ref\n\n :telemetry.detach(to_string(test_name))\n end\n\n test \"emits connection-related events on disconnections and reconnections\" do\n {test_name, _arity} = __ENV__.function\n\n parent = self()\n ref = make_ref()\n\n handler = fn event, measurements, meta, _config ->\n # We need to run this test only if was called for this Redix connection so that\n # we can run in parallel with the pubsub tests.\n if meta.connection == :redix_telemetry_test do\n assert measurements == %{}\n\n case event do\n [:redix, :connection] -> send(parent, {ref, :connected, meta})\n [:redix, :disconnection] -> send(parent, {ref, :disconnected, meta})\n end\n end\n end\n\n events = [[:redix, :connection], [:redix, :disconnection]]\n :ok = :telemetry.attach_many(to_string(test_name), events, handler, :no_config)\n\n {:ok, c} = Redix.start_link(name: :redix_telemetry_test)\n\n assert_receive {^ref, :connected, meta}, 1000\n assert %{address: \"localhost:6379\", connection: _, reconnection: false} = meta\n\n capture_log(fn ->\n assert {:ok, _} = Redix.command(c, ~w(QUIT))\n\n assert_receive {^ref, :disconnected, meta}, 1000\n assert %{address: \"localhost:6379\", connection: _} = meta\n\n assert_receive {^ref, :connected, meta}, 1000\n assert %{address: \"localhost:6379\", connection: _, reconnection: true} = meta\n end)\n end\n end\n\n defp connect(_context) do\n {:ok, conn} = Redix.start_link()\n {:ok, %{conn: conn}}\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"e83b20b5bc9ca8df37be601768ac6247aa9f4e5a","subject":"Move NTP check to when an interface comes up","message":"Move NTP check to when an interface comes up\n\nThis will lead to a few dropped sync requests, but\nshould hopefully stabalize NTP starting\n","repos":"FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os","old_file":"farmbot_os\/platform\/target\/network.ex","new_file":"farmbot_os\/platform\/target\/network.ex","new_contents":"defmodule FarmbotOS.Platform.Target.Network do\n @moduledoc \"Manages Network Connections\"\n use GenServer, shutdown: 10_000\n require Logger\n require FarmbotCore.Logger\n import FarmbotOS.Platform.Target.Network.Utils\n alias FarmbotOS.Platform.Target.Network.{Distribution, PreSetup}\n alias FarmbotOS.Platform.Target.Configurator.{Validator, CaptivePortal}\n alias FarmbotCore.{Asset, Config}\n\n @default_network_not_found_timer_minutes 20\n\n def host do\n %{\n type: CaptivePortal,\n wifi: %{\n ssid: build_hostap_ssid(),\n mode: :host,\n key_mgmt: :none\n },\n ipv4: %{\n method: :static,\n address: \"192.168.24.1\",\n netmask: \"255.255.255.0\"\n },\n dnsmasq: %{\n domain: \"farmbot\",\n server: \"192.168.24.1\",\n address: \"192.168.24.1\",\n start: \"192.168.24.2\",\n end: \"192.168.24.10\"\n }\n }\n end\n\n def null do\n %{type: VintageNet.Technology.Null}\n end\n\n def presetup do\n %{type: PreSetup}\n end\n\n def is_first_connect?() do\n # email = Config.get_config_value(:string, \"authorization\", \"email\")\n # password = Config.get_config_value(:string, \"authorization\", \"password\")\n # server = Config.get_config_value(:string, \"authorization\", \"server\")\n token = Config.get_config_value(:string, \"authorization\", \"token\")\n is_nil(token)\n end\n\n def start_link(args) do\n GenServer.start_link(__MODULE__, args, name: __MODULE__)\n end\n\n @impl GenServer\n def init(_args) do\n _ = maybe_hack_tzdata()\n send(self(), :setup)\n # If a secret exists, assume that \n # farmbot at one point has been connected to the internet\n first_connect? = is_first_connect?()\n\n if first_connect? do\n :ok = VintageNet.configure(\"wlan0\", null())\n Process.sleep(1500)\n :ok = VintageNet.configure(\"wlan0\", host())\n end\n\n {:ok, %{network_not_found_timer: nil, first_connect?: first_connect?, distribution: nil}}\n end\n\n @impl GenServer\n def terminate(_, _) do\n :ok = VintageNet.configure(\"wlan0\", null())\n :ok = VintageNet.configure(\"eth0\", null())\n end\n\n @impl GenServer\n def handle_info(:setup, state) do\n configs = Config.get_all_network_configs()\n\n case configs do\n [] ->\n Process.send_after(self(), :setup, 5_000)\n {:noreply, state}\n\n _ ->\n _ = VintageNet.subscribe([\"interface\", \"wlan0\"])\n _ = VintageNet.subscribe([\"interface\", \"eth0\"])\n :ok = VintageNet.configure(\"wlan0\", presetup())\n :ok = VintageNet.configure(\"eth0\", presetup())\n Process.sleep(1500)\n {:noreply, state}\n end\n end\n\n def handle_info({VintageNet, [\"interface\", ifname, \"type\"], _old, type, _meta}, state)\n when type in [PreSetup, VintageNet.Technology.Null] do\n FarmbotCore.Logger.debug(1, \"Network interface needs configuration: #{ifname}\")\n\n case Config.get_network_config(ifname) do\n %Config.NetworkInterface{} = config ->\n FarmbotCore.Logger.busy(3, \"Setting up network interface: #{ifname}\")\n {:ok, hostname} = :inet.gethostname()\n\n distribution_opts = %{\n ifname: config.name,\n mdns_domain: \"#{hostname}.local\",\n node_name: \"farmbot\",\n node_host: :mdns_domain\n }\n\n {:ok, distribution_pid} = Distribution.start_link(distribution_opts)\n\n case reset_ntp() do\n :ok ->\n :ok\n\n error ->\n FarmbotCore.Logger.error(1, \"\"\"\n Failed to configure NTP: #{inspect(error)}\n \"\"\")\n end\n\n vintage_net_config = to_vintage_net(config)\n configure_result = VintageNet.configure(config.name, vintage_net_config)\n\n FarmbotCore.Logger.success(3, \"#{config.name} setup: #{inspect(configure_result)}\")\n\n state = start_network_not_found_timer(state)\n {:noreply, %{state | distribution: distribution_pid}}\n\n nil ->\n {:noreply, state}\n end\n end\n\n def handle_info({VintageNet, [\"interface\", ifname, \"lower_up\"], _old, false, _meta}, state) do\n FarmbotCore.Logger.error(1, \"Interface #{ifname} disconnected from access point\")\n state = start_network_not_found_timer(state)\n {:noreply, state}\n end\n\n def handle_info({VintageNet, [\"interface\", ifname, \"lower_up\"], _old, true, _meta}, state) do\n FarmbotCore.Logger.success(1, \"Interface #{ifname} connected access point\")\n state = cancel_network_not_found_timer(state)\n {:noreply, state}\n end\n\n def handle_info(\n {VintageNet, [\"interface\", ifname, \"connection\"], :disconnected, :lan, _meta},\n state\n ) do\n FarmbotCore.Logger.warn(1, \"Interface #{ifname} connected to local area network\")\n {:noreply, state}\n end\n\n def handle_info(\n {VintageNet, [\"interface\", ifname, \"connection\"], :lan, :internet, _meta},\n state\n ) do\n FarmbotCore.Logger.warn(1, \"Interface #{ifname} connected to internet\")\n state = cancel_network_not_found_timer(state)\n {:noreply, %{state | first_connect?: false}}\n end\n\n def handle_info(\n {VintageNet, [\"interface\", ifname, \"connection\"], :internet, ifstate, _meta},\n state\n ) do\n FarmbotCore.Logger.warn(1, \"Interface #{ifname} disconnected from the internet: #{ifstate}\")\n FarmbotExt.AMQP.ConnectionWorker.close()\n\n if state.network_not_found_timer do\n {:noreply, state}\n else\n state = start_network_not_found_timer(state)\n {:noreply, state}\n end\n end\n\n def handle_info(\n {VintageNet, [\"interface\", _, \"wifi\", \"access_points\"], _old, _new, _meta},\n state\n ) do\n {:noreply, state}\n end\n\n def handle_info({VintageNet, property, old, new, _meta}, state) do\n Logger.debug(\"\"\"\n Unknown property change: #{inspect(property)}\n old: \n\n #{inspect(old, limit: :infinity)}\n\n new: \n\n #{inspect(new, limit: :infinity)}\n \"\"\")\n\n {:noreply, state}\n end\n\n def handle_info({:network_not_found_timer, minutes}, state) do\n FarmbotCore.Logger.warn(1, \"\"\"\n Farmbot has been disconnected from the network for \n #{minutes} minutes. Going down for factory reset.\n \"\"\")\n\n FarmbotOS.System.factory_reset(\"\"\"\n Farmbot has been disconnected from the network for \n #{minutes} minutes.\n \"\"\")\n\n {:noreply, state}\n end\n\n def to_vintage_net(%Config.NetworkInterface{} = config) do\n %{\n type: Validator,\n network_type: config.type,\n ssid: config.ssid,\n security: config.security,\n psk: config.psk,\n identity: config.identity,\n password: config.password,\n domain: config.domain,\n name_servers: config.name_servers,\n ipv4_method: config.ipv4_method,\n ipv4_address: config.ipv4_address,\n ipv4_gateway: config.ipv4_gateway,\n ipv4_subnet_mask: config.ipv4_subnet_mask,\n regulatory_domain: config.regulatory_domain\n }\n end\n\n defp cancel_network_not_found_timer(state) do\n FarmbotCore.Logger.success(\n 1,\n \"Farmbot has been reconnected. Canceling scheduled factory reset\"\n )\n\n old_timer = state.network_not_found_timer\n old_timer && Process.cancel_timer(old_timer)\n %{state | network_not_found_timer: nil}\n end\n\n defp start_network_not_found_timer(state) do\n state = cancel_network_not_found_timer(state)\n # Stored in minutes\n minutes = network_not_found_timer_minutes(state)\n millis = minutes * 60000\n new_timer = Process.send_after(self(), {:network_not_found_timer, minutes}, millis)\n\n FarmbotCore.Logger.warn(1, \"\"\"\n FarmBot will factory reset in #{minutes} minutes if the network does not \n reassociate. \n If you see this message directly after configuration, this message can be safely ignored.\n \"\"\")\n\n %{state | network_not_found_timer: new_timer}\n end\n\n # if the network has never connected before, make a low\n # thresh so that user won't have to wait 20 minutes to reconfigurate\n # due to bad wifi credentials.\n defp network_not_found_timer_minutes(%{first_connect?: true}), do: 1\n\n defp network_not_found_timer_minutes(_state) do\n Asset.fbos_config(:network_not_found_timer) || @default_network_not_found_timer_minutes\n end\n\n def reset_ntp do\n ntp_server_1 = Config.get_config_value(:string, \"settings\", \"default_ntp_server_1\")\n ntp_server_2 = Config.get_config_value(:string, \"settings\", \"default_ntp_server_2\")\n\n if ntp_server_1 || ntp_server_2 do\n Logger.info(\"Setting NTP servers: [#{ntp_server_1}, #{ntp_server_2}]\")\n\n [ntp_server_1, ntp_server_2]\n |> Enum.reject(&is_nil\/1)\n |> Nerves.Time.set_ntp_servers()\n else\n Logger.info(\"Using default NTP servers\")\n :ok\n end\n end\nend\n","old_contents":"defmodule FarmbotOS.Platform.Target.Network do\n @moduledoc \"Manages Network Connections\"\n use GenServer, shutdown: 10_000\n require Logger\n require FarmbotCore.Logger\n import FarmbotOS.Platform.Target.Network.Utils\n alias FarmbotOS.Platform.Target.Network.{Distribution, PreSetup}\n alias FarmbotOS.Platform.Target.Configurator.{Validator, CaptivePortal}\n alias FarmbotCore.{Asset, Config}\n\n @default_network_not_found_timer_minutes 20\n\n def host do\n %{\n type: CaptivePortal,\n wifi: %{\n ssid: build_hostap_ssid(),\n mode: :host,\n key_mgmt: :none\n },\n ipv4: %{\n method: :static,\n address: \"192.168.24.1\",\n netmask: \"255.255.255.0\"\n },\n dnsmasq: %{\n domain: \"farmbot\",\n server: \"192.168.24.1\",\n address: \"192.168.24.1\",\n start: \"192.168.24.2\",\n end: \"192.168.24.10\"\n }\n }\n end\n\n def null do\n %{type: VintageNet.Technology.Null}\n end\n\n def presetup do\n %{type: PreSetup}\n end\n\n def is_first_connect?() do\n # email = Config.get_config_value(:string, \"authorization\", \"email\")\n # password = Config.get_config_value(:string, \"authorization\", \"password\")\n # server = Config.get_config_value(:string, \"authorization\", \"server\")\n token = Config.get_config_value(:string, \"authorization\", \"token\")\n is_nil(token)\n end\n\n def start_link(args) do\n GenServer.start_link(__MODULE__, args, name: __MODULE__)\n end\n\n @impl GenServer\n def init(_args) do\n _ = maybe_hack_tzdata()\n send(self(), :setup)\n # If a secret exists, assume that \n # farmbot at one point has been connected to the internet\n first_connect? = is_first_connect?()\n\n if first_connect? do\n :ok = VintageNet.configure(\"wlan0\", null())\n Process.sleep(1500)\n :ok = VintageNet.configure(\"wlan0\", host())\n end\n\n {:ok, %{network_not_found_timer: nil, first_connect?: first_connect?, distribution: nil}}\n end\n\n @impl GenServer\n def terminate(_, _) do\n :ok = VintageNet.configure(\"wlan0\", null())\n :ok = VintageNet.configure(\"eth0\", null())\n end\n\n @impl GenServer\n def handle_info(:setup, state) do\n configs = Config.get_all_network_configs()\n\n case configs do\n [] ->\n Process.send_after(self(), :setup, 5_000)\n {:noreply, state}\n\n _ ->\n _ = VintageNet.subscribe([\"interface\", \"wlan0\"])\n _ = VintageNet.subscribe([\"interface\", \"eth0\"])\n :ok = VintageNet.configure(\"wlan0\", presetup())\n :ok = VintageNet.configure(\"eth0\", presetup())\n Process.sleep(1500)\n {:noreply, state}\n end\n end\n\n def handle_info({VintageNet, [\"interface\", ifname, \"type\"], _old, type, _meta}, state)\n when type in [PreSetup, VintageNet.Technology.Null] do\n FarmbotCore.Logger.debug(1, \"Network interface needs configuration: #{ifname}\")\n\n case Config.get_network_config(ifname) do\n %Config.NetworkInterface{} = config ->\n FarmbotCore.Logger.busy(3, \"Setting up network interface: #{ifname}\")\n {:ok, hostname} = :inet.gethostname()\n\n distribution_opts = %{\n ifname: config.name,\n mdns_domain: \"#{hostname}.local\",\n node_name: \"farmbot\",\n node_host: :mdns_domain\n }\n\n {:ok, distribution_pid} = Distribution.start_link(distribution_opts)\n\n vintage_net_config = to_vintage_net(config)\n configure_result = VintageNet.configure(config.name, vintage_net_config)\n\n FarmbotCore.Logger.success(3, \"#{config.name} setup: #{inspect(configure_result)}\")\n\n state = start_network_not_found_timer(state)\n {:noreply, %{state | distribution: distribution_pid}}\n\n nil ->\n {:noreply, state}\n end\n end\n\n def handle_info({VintageNet, [\"interface\", ifname, \"lower_up\"], _old, false, _meta}, state) do\n FarmbotCore.Logger.error(1, \"Interface #{ifname} disconnected from access point\")\n state = start_network_not_found_timer(state)\n {:noreply, state}\n end\n\n def handle_info({VintageNet, [\"interface\", ifname, \"lower_up\"], _old, true, _meta}, state) do\n FarmbotCore.Logger.success(1, \"Interface #{ifname} connected access point\")\n state = cancel_network_not_found_timer(state)\n {:noreply, state}\n end\n\n def handle_info(\n {VintageNet, [\"interface\", ifname, \"connection\"], :disconnected, :lan, _meta},\n state\n ) do\n FarmbotCore.Logger.warn(1, \"Interface #{ifname} connected to local area network\")\n {:noreply, state}\n end\n\n def handle_info(\n {VintageNet, [\"interface\", ifname, \"connection\"], :lan, :internet, _meta},\n state\n ) do\n FarmbotCore.Logger.warn(1, \"Interface #{ifname} connected to internet\")\n state = cancel_network_not_found_timer(state)\n\n case reset_ntp() do\n :ok ->\n :ok\n\n error ->\n FarmbotCore.Logger.error(1, \"\"\"\n Failed to configure NTP: #{inspect(error)}\n \"\"\")\n end\n\n {:noreply, %{state | first_connect?: false}}\n end\n\n def handle_info(\n {VintageNet, [\"interface\", ifname, \"connection\"], :internet, ifstate, _meta},\n state\n ) do\n FarmbotCore.Logger.warn(1, \"Interface #{ifname} disconnected from the internet: #{ifstate}\")\n FarmbotExt.AMQP.ConnectionWorker.close()\n\n if state.network_not_found_timer do\n {:noreply, state}\n else\n state = start_network_not_found_timer(state)\n {:noreply, state}\n end\n end\n\n def handle_info(\n {VintageNet, [\"interface\", _, \"wifi\", \"access_points\"], _old, _new, _meta},\n state\n ) do\n {:noreply, state}\n end\n\n def handle_info({VintageNet, property, old, new, _meta}, state) do\n Logger.debug(\"\"\"\n Unknown property change: #{inspect(property)}\n old: \n\n #{inspect(old, limit: :infinity)}\n\n new: \n\n #{inspect(new, limit: :infinity)}\n \"\"\")\n\n {:noreply, state}\n end\n\n def handle_info({:network_not_found_timer, minutes}, state) do\n FarmbotCore.Logger.warn(1, \"\"\"\n Farmbot has been disconnected from the network for \n #{minutes} minutes. Going down for factory reset.\n \"\"\")\n\n FarmbotOS.System.factory_reset(\"\"\"\n Farmbot has been disconnected from the network for \n #{minutes} minutes.\n \"\"\")\n\n {:noreply, state}\n end\n\n def to_vintage_net(%Config.NetworkInterface{} = config) do\n %{\n type: Validator,\n network_type: config.type,\n ssid: config.ssid,\n security: config.security,\n psk: config.psk,\n identity: config.identity,\n password: config.password,\n domain: config.domain,\n name_servers: config.name_servers,\n ipv4_method: config.ipv4_method,\n ipv4_address: config.ipv4_address,\n ipv4_gateway: config.ipv4_gateway,\n ipv4_subnet_mask: config.ipv4_subnet_mask,\n regulatory_domain: config.regulatory_domain\n }\n end\n\n defp cancel_network_not_found_timer(state) do\n FarmbotCore.Logger.success(\n 1,\n \"Farmbot has been reconnected. Canceling scheduled factory reset\"\n )\n\n old_timer = state.network_not_found_timer\n old_timer && Process.cancel_timer(old_timer)\n %{state | network_not_found_timer: nil}\n end\n\n defp start_network_not_found_timer(state) do\n state = cancel_network_not_found_timer(state)\n # Stored in minutes\n minutes = network_not_found_timer_minutes(state)\n millis = minutes * 60000\n new_timer = Process.send_after(self(), {:network_not_found_timer, minutes}, millis)\n\n FarmbotCore.Logger.warn(1, \"\"\"\n FarmBot will factory reset in #{minutes} minutes if the network does not \n reassociate. \n If you see this message directly after configuration, this message can be safely ignored.\n \"\"\")\n\n %{state | network_not_found_timer: new_timer}\n end\n\n # if the network has never connected before, make a low\n # thresh so that user won't have to wait 20 minutes to reconfigurate\n # due to bad wifi credentials.\n defp network_not_found_timer_minutes(%{first_connect?: true}), do: 1\n\n defp network_not_found_timer_minutes(_state) do\n Asset.fbos_config(:network_not_found_timer) || @default_network_not_found_timer_minutes\n end\n\n defp reset_ntp do\n ntp_server_1 = Config.get_config_value(:string, \"settings\", \"default_ntp_server_1\")\n ntp_server_2 = Config.get_config_value(:string, \"settings\", \"default_ntp_server_2\")\n\n if ntp_server_1 || ntp_server_2 do\n Logger.info(\"Setting NTP servers: [#{ntp_server_1}, #{ntp_server_2}]\")\n\n [ntp_server_1, ntp_server_2]\n |> Enum.reject(&is_nil\/1)\n |> Nerves.Time.set_ntp_servers()\n else\n Logger.info(\"Using default NTP servers\")\n :ok\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"6b1de67e2405fca7c3d24ca14719319b7900a3f0","subject":"Returns more information on uknown_var eval.","message":"Returns more information on uknown_var eval.\n","repos":"serverboards\/serverboards,serverboards\/serverboards,serverboards\/serverboards,serverboards\/serverboards,serverboards\/serverboards","old_file":"backend\/apps\/serverboards\/lib\/exeval\/exeval.ex","new_file":"backend\/apps\/serverboards\/lib\/exeval\/exeval.ex","new_contents":"require Logger\n\ndefmodule ExEval do\n def eval(expr), do: eval(expr, [])\n def eval(expr, context) do\n # Logger.info(\"Try parse #{inspect expr} with context #{inspect context}\")\n\n tokens = tokenize(expr)\n # Logger.info(\"tokens #{inspect tokens}\")\n {:ok, ast} = parse_ast(tokens)\n # Logger.info(\"ast #{inspect ast}\")\n\n eval_ast(ast, context)\n end\n\n\n @all_expr_regex [\n {:ignore, ~r\/^ \/, :ignore},\n {:open_paren, ~r\/^\\(\/, :ignore},\n {:close_paren, ~r\/^\\)\/, :ignore},\n\n {:literal, ~r\/^true\/, true},\n {:literal, ~r\/^false\/, false},\n {:literal, ~r\/^[0-9][0-9.]*\/, :number},\n {:literal, ~r\/^'[^']*'\/, :string},\n {:literal, ~r\/^\"[^\"]*\"\/, :string},\n\n {:unary_op, ~r\/^not\/, :not},\n\n {{:op, 6}, ~r\/^or\/, :or},\n {{:op, 5}, ~r\/^and\/, :and},\n {{:op, 4}, ~r\/^\\*\/, :mul},\n {{:op, 3}, ~r\/^\\\/\/, :div},\n {{:op, 2}, ~r\/^\\+\/, :plus},\n {{:op, 2}, ~r\/^-\/, :minus},\n {{:op, 1}, ~r\/^==\/, :equal},\n {{:op, 1}, ~r\/^!=\/, :not_equal},\n\n {:var, ~r\/^[a-z][a-z0-9.]*\/i, :ignore},\n ]\n @max_op_pri 7\n\n @doc ~S\"\"\"\n tokenizes the expression.\n\n It returns a list of tokens, in which each is an identifier of the type, the\n original string and data dependant on the token type.\n [\n {:open_paren, \"(\"},\n {:literal, \"1\", :number},\n {:operator, \"+\", :plus}\n {:literal, \"2\", :number},\n {:close_paren, \")\"},\n {:operator, \"*\", :mul},\n {:literal, \"3\", 3}\n ]\n\n Spaces are ignored but used as token separators\n \"\"\"\n def tokenize(\"\"), do: []\n def tokenize(expr) do\n # Logger.debug(\"Tokenize: #{inspect expr}\")\n token = which_token(expr, @all_expr_regex)\n {_, rest} = String.split_at(expr, String.length( elem(token, 1) ))\n case token do\n {:ignore, _, _} -> tokenize( rest )\n _ -> [token] ++ tokenize( rest )\n end\n end\n\n def which_token(expr, [{type, regex, extradata} | rest]) do\n # Logger.debug(\"which token: #{inspect expr} \/\/ #{inspect type}\")\n case Regex.run(regex, expr) do\n nil -> which_token(expr, rest)\n [result] -> {type, result, extradata}\n end\n end\n\n @doc ~S\"\"\"\n The parse tree BNF is:\n\n ROOT = EXPR1[1]\n EXPR[pri] =\n EXPR[>pri] (OP[pri] EXPR[pri])*\n | UNARY_OP EXPR[pri]\n EXPR[max_pri] =\n LITERAL\n | ( EXPR[1] )\n\n \"\"\"\n def parse_ast(tokens) do\n {:ok, ast, []} = parse_expr(tokens, 1)\n {:ok, ast}\n end\n def parse_expr([{:literal, literal, type} | rest], @max_op_pri) do\n literal = parse_literal(literal, type)\n {:ok, {:literal, literal}, rest}\n end\n def parse_expr([{:var, literal, _} | rest], @max_op_pri) do\n {:ok, {:var, literal}, rest}\n end\n def parse_expr([{:open_paren, _, _} | rest], @max_op_pri) do\n {:ok, expr, [{:close_paren, _, _} | rest ]} = parse_expr(rest, 1)\n {:ok, expr, rest}\n end\n def parse_expr([{type, lit, _} | rest ], @max_op_pri) do\n {:error, {:invalid_token, type, lit}}\n end\n def parse_expr(tokens, pri) do\n {:ok, op1, rest} = parse_expr(tokens, pri+1)\n case rest do\n [ {{:op, ^pri}, _, op} | rest ] ->\n {:ok, op2, rest} = parse_expr(rest, pri)\n {:ok, {op, op1, op2}, rest}\n _ ->\n {:ok, op1, rest}\n end\n end\n def parse_expr([{:unary_op, _, :not} | rest], pri) do\n {:ok, ast, rest } = parse_expr(rest, pri)\n {:ok, {:not, ast}, rest}\n end\n\n def parse_literal(_, true), do: true\n def parse_literal(_, false), do: false\n def parse_literal(lit, :number) do\n {f, \"\"} = Float.parse(lit)\n f\n end\n def parse_literal(lit, :string) do\n # {f, \"\"} = Float.parse(lit)\n String.slice(lit, 1, String.length(lit) - 2)\n end\n\n\n def eval_ast({:literal, v}, context) do\n {:ok, v}\n end\n def eval_ast({:var, v}, context) do\n case get_var(String.split(v,\".\"), context) do\n {:error, :unknown_var} ->\n {:error, {:unknown_var, v, context}}\n other -> other\n end\n end\n def eval_ast({:equal, op1, op2}, context) do\n with {:ok, op1} <- eval_ast(op1, context),\n {:ok, op2} <- eval_ast(op2, context),\n do: {:ok, op1 == op2}\n end\n def eval_ast({:not_equal, op1, op2}, context) do\n with {:ok, op1} <- eval_ast(op1, context),\n {:ok, op2} <- eval_ast(op2, context),\n do: {:ok, op1 != op2}\n end\n def eval_ast({:or, op1, op2}, context) do\n with {:ok, op1} <- eval_ast(op1, context),\n {:ok, op2} <- eval_ast(op2, context),\n do: {:ok, op1 || op2}\n end\n def eval_ast({:and, op1, op2}, context) do\n with {:ok, op1} <- eval_ast(op1, context),\n {:ok, op2} <- eval_ast(op2, context),\n do: {:ok, op1 && op2}\n end\n def eval_ast({:plus, op1, op2}, context) do\n with {:ok, op1} <- eval_ast(op1, context),\n {:ok, op2} <- eval_ast(op2, context)\n do\n case op1 do\n op1 when is_number(op1) ->\n {:ok, op1 + op2}\n op1 when is_binary(op1) ->\n {:ok, op1 <> op2}\n end\n end\n end\n def eval_ast({:minus, op1, op2}, context) do\n with {:ok, op1} <- eval_ast(op1, context),\n {:ok, op2} <- eval_ast(op2, context),\n do: {:ok, op1 + op2}\n end\n def eval_ast({:mul, op1, op2}, context) do\n with {:ok, op1} <- eval_ast(op1, context),\n {:ok, op2} <- eval_ast(op2, context),\n do: {:ok, op1 * op2}\n end\n def eval_ast({:div, op1, op2}, context) do\n with {:ok, op1} <- eval_ast(op1, context),\n {:ok, op2} <- eval_ast(op2, context),\n do: {:ok, op1 \/ op2}\n end\n\n def get_var(_, []) do\n {:error, :unknown_var}\n end\n def get_var([], _) do\n {:error, :unknown_var}\n end\n def get_var([var], [ccontext | rest]) do\n case Map.get(ccontext, var, nil) do\n nil -> get_var([var],rest)\n other -> {:ok, other}\n end\n end\n def get_var([var | varrest] = fullvar, [ccontext | rest]) do\n case Map.get(ccontext, var, nil) do\n nil -> get_var(fullvar,rest)\n newcontext -> get_var(varrest, [newcontext])\n end\n end\nend\n","old_contents":"require Logger\n\ndefmodule ExEval do\n def eval(expr), do: eval(expr, [])\n def eval(expr, context) do\n # Logger.info(\"Try parse #{inspect expr} with context #{inspect context}\")\n\n tokens = tokenize(expr)\n # Logger.info(\"tokens #{inspect tokens}\")\n {:ok, ast} = parse_ast(tokens)\n # Logger.info(\"ast #{inspect ast}\")\n\n eval_ast(ast, context)\n end\n\n\n @all_expr_regex [\n {:ignore, ~r\/^ \/, :ignore},\n {:open_paren, ~r\/^\\(\/, :ignore},\n {:close_paren, ~r\/^\\)\/, :ignore},\n\n {:literal, ~r\/^true\/, true},\n {:literal, ~r\/^false\/, false},\n {:literal, ~r\/^[0-9][0-9.]*\/, :number},\n {:literal, ~r\/^'[^']*'\/, :string},\n {:literal, ~r\/^\"[^\"]*\"\/, :string},\n\n {:unary_op, ~r\/^not\/, :not},\n\n {{:op, 6}, ~r\/^or\/, :or},\n {{:op, 5}, ~r\/^and\/, :and},\n {{:op, 4}, ~r\/^\\*\/, :mul},\n {{:op, 3}, ~r\/^\\\/\/, :div},\n {{:op, 2}, ~r\/^\\+\/, :plus},\n {{:op, 2}, ~r\/^-\/, :minus},\n {{:op, 1}, ~r\/^==\/, :equal},\n {{:op, 1}, ~r\/^!=\/, :not_equal},\n\n {:var, ~r\/^[a-z][a-z0-9.]*\/i, :ignore},\n ]\n @max_op_pri 7\n\n @doc ~S\"\"\"\n tokenizes the expression.\n\n It returns a list of tokens, in which each is an identifier of the type, the\n original string and data dependant on the token type.\n [\n {:open_paren, \"(\"},\n {:literal, \"1\", :number},\n {:operator, \"+\", :plus}\n {:literal, \"2\", :number},\n {:close_paren, \")\"},\n {:operator, \"*\", :mul},\n {:literal, \"3\", 3}\n ]\n\n Spaces are ignored but used as token separators\n \"\"\"\n def tokenize(\"\"), do: []\n def tokenize(expr) do\n # Logger.debug(\"Tokenize: #{inspect expr}\")\n token = which_token(expr, @all_expr_regex)\n {_, rest} = String.split_at(expr, String.length( elem(token, 1) ))\n case token do\n {:ignore, _, _} -> tokenize( rest )\n _ -> [token] ++ tokenize( rest )\n end\n end\n\n def which_token(expr, [{type, regex, extradata} | rest]) do\n # Logger.debug(\"which token: #{inspect expr} \/\/ #{inspect type}\")\n case Regex.run(regex, expr) do\n nil -> which_token(expr, rest)\n [result] -> {type, result, extradata}\n end\n end\n\n @doc ~S\"\"\"\n The parse tree BNF is:\n\n ROOT = EXPR1[1]\n EXPR[pri] =\n EXPR[>pri] (OP[pri] EXPR[pri])*\n | UNARY_OP EXPR[pri]\n EXPR[max_pri] =\n LITERAL\n | ( EXPR[1] )\n\n \"\"\"\n def parse_ast(tokens) do\n {:ok, ast, []} = parse_expr(tokens, 1)\n {:ok, ast}\n end\n def parse_expr([{:literal, literal, type} | rest], @max_op_pri) do\n literal = parse_literal(literal, type)\n {:ok, {:literal, literal}, rest}\n end\n def parse_expr([{:var, literal, _} | rest], @max_op_pri) do\n {:ok, {:var, literal}, rest}\n end\n def parse_expr([{:open_paren, _, _} | rest], @max_op_pri) do\n {:ok, expr, [{:close_paren, _, _} | rest ]} = parse_expr(rest, 1)\n {:ok, expr, rest}\n end\n def parse_expr([{type, lit, _} | rest ], @max_op_pri) do\n {:error, {:invalid_token, type, lit}}\n end\n def parse_expr(tokens, pri) do\n {:ok, op1, rest} = parse_expr(tokens, pri+1)\n case rest do\n [ {{:op, ^pri}, _, op} | rest ] ->\n {:ok, op2, rest} = parse_expr(rest, pri)\n {:ok, {op, op1, op2}, rest}\n _ ->\n {:ok, op1, rest}\n end\n end\n def parse_expr([{:unary_op, _, :not} | rest], pri) do\n {:ok, ast, rest } = parse_expr(rest, pri)\n {:ok, {:not, ast}, rest}\n end\n\n def parse_literal(_, true), do: true\n def parse_literal(_, false), do: false\n def parse_literal(lit, :number) do\n {f, \"\"} = Float.parse(lit)\n f\n end\n def parse_literal(lit, :string) do\n # {f, \"\"} = Float.parse(lit)\n String.slice(lit, 1, String.length(lit) - 2)\n end\n\n\n def eval_ast({:literal, v}, context) do\n {:ok, v}\n end\n def eval_ast({:var, v}, context) do\n get_var(String.split(v,\".\"), context)\n end\n def eval_ast({:equal, op1, op2}, context) do\n with {:ok, op1} <- eval_ast(op1, context),\n {:ok, op2} <- eval_ast(op2, context),\n do: {:ok, op1 == op2}\n end\n def eval_ast({:not_equal, op1, op2}, context) do\n with {:ok, op1} <- eval_ast(op1, context),\n {:ok, op2} <- eval_ast(op2, context),\n do: {:ok, op1 != op2}\n end\n def eval_ast({:or, op1, op2}, context) do\n with {:ok, op1} <- eval_ast(op1, context),\n {:ok, op2} <- eval_ast(op2, context),\n do: {:ok, op1 || op2}\n end\n def eval_ast({:and, op1, op2}, context) do\n with {:ok, op1} <- eval_ast(op1, context),\n {:ok, op2} <- eval_ast(op2, context),\n do: {:ok, op1 && op2}\n end\n def eval_ast({:plus, op1, op2}, context) do\n with {:ok, op1} <- eval_ast(op1, context),\n {:ok, op2} <- eval_ast(op2, context)\n do\n case op1 do\n op1 when is_number(op1) ->\n {:ok, op1 + op2}\n op1 when is_binary(op1) ->\n {:ok, op1 <> op2}\n end\n end\n end\n def eval_ast({:minus, op1, op2}, context) do\n with {:ok, op1} <- eval_ast(op1, context),\n {:ok, op2} <- eval_ast(op2, context),\n do: {:ok, op1 + op2}\n end\n def eval_ast({:mul, op1, op2}, context) do\n with {:ok, op1} <- eval_ast(op1, context),\n {:ok, op2} <- eval_ast(op2, context),\n do: {:ok, op1 * op2}\n end\n def eval_ast({:div, op1, op2}, context) do\n with {:ok, op1} <- eval_ast(op1, context),\n {:ok, op2} <- eval_ast(op2, context),\n do: {:ok, op1 \/ op2}\n end\n\n def get_var(_, []) do\n {:error, :unknown_var}\n end\n def get_var([], _) do\n {:error, :unknown_var}\n end\n def get_var([var], [ccontext | rest]) do\n case Map.get(ccontext, var, nil) do\n nil -> get_var([var],rest)\n other -> {:ok, other}\n end\n end\n def get_var([var | varrest] = fullvar, [ccontext | rest]) do\n case Map.get(ccontext, var, nil) do\n nil -> get_var(fullvar,rest)\n newcontext -> get_var(varrest, [newcontext])\n end\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"3deb76e5a83af4275873ff4612f6cc317840b131","subject":"Update tests to create questions","message":"Update tests to create questions\n","repos":"exacs\/liqen-core,exacs\/liqen-core","old_file":"test\/controllers\/question_controller_test.exs","new_file":"test\/controllers\/question_controller_test.exs","new_contents":"defmodule Core.QuestionControllerTest do\n @moduledoc \"\"\"\n Test for Core.QuestionController\n \"\"\"\n use Core.ConnCase\n\n setup do\n user = insert_user(%{}, true)\n {:ok, jwt, _} = Guardian.encode_and_sign(user)\n\n conn = build_conn()\n |> put_req_header(\"accept\", \"application\/json\")\n |> put_req_header(\"authorization\", \"Bearer #{jwt}\")\n\n {:ok, %{conn: conn}}\n end\n\n test \"List of Questions\", %{conn: conn} do\n conn = conn\n |> get(question_path(conn, :index))\n\n assert json_response(conn, :ok)\n end\n\n test \"Create a question\", %{conn: conn} do\n\n tag = insert_tag(%{})\n conn1 = conn\n |> post(question_path(conn, :create), %{\"title\" => \"x\",\n \"answer\" => []})\n\n conn2 = conn\n |> post(question_path(conn, :create), %{\"title\" => \"x\",\n \"answer\" => [%{\"tag\" => tag.id}]})\n\n connF = conn\n |> post(question_path(conn, :create), %{\"title\" => \"\"})\n\n assert json_response(conn1, :created)\n assert json_response(conn2, :created)\n assert json_response(connF, :unprocessable_entity)\n end\n\n test \"Show a question\", %{conn: conn} do\n question = insert_question()\n\n conn = conn\n |> get(question_path(conn, :show, question.id))\n\n assert json_response(conn, :ok)\n end\n\n test \"Update a question\", %{conn: conn} do\n question = insert_question()\n\n conn1 = conn\n |> put(question_path(conn, :update, question.id), %{\"title\" => \"b\"})\n\n conn2 = conn\n |> put(question_path(conn, :update, question.id), %{\"title\" => \"\"})\n\n assert json_response(conn1, :ok)\n assert json_response(conn2, :unprocessable_entity)\n end\n\n test \"Delete a question\", %{conn: conn} do\n question = insert_question()\n\n conn = conn\n |> delete(question_path(conn, :delete, question.id))\n\n assert response(conn, :no_content)\n end\n\n test \"Resource not found\", %{conn: conn} do\n conn1 = get(conn, question_path(conn, :show, 0))\n conn2 = get(conn, question_path(conn, :update, 0, %{}))\n conn3 = get(conn, question_path(conn, :delete, 0))\n\n assert json_response(conn1, :not_found)\n assert json_response(conn2, :not_found)\n assert json_response(conn3, :not_found)\n end\nend\n","old_contents":"defmodule Core.QuestionControllerTest do\n @moduledoc \"\"\"\n Test for Core.QuestionController\n \"\"\"\n use Core.ConnCase\n\n setup do\n user = insert_user(%{}, true)\n {:ok, jwt, _} = Guardian.encode_and_sign(user)\n\n conn = build_conn()\n |> put_req_header(\"accept\", \"application\/json\")\n |> put_req_header(\"authorization\", \"Bearer #{jwt}\")\n\n {:ok, %{conn: conn}}\n end\n\n test \"List of Questions\", %{conn: conn} do\n conn = conn\n |> get(question_path(conn, :index))\n\n assert json_response(conn, :ok)\n end\n\n test \"Create a question\", %{conn: conn} do\n conn1 = conn\n |> post(question_path(conn, :create), %{\"title\" => \"x\"})\n\n conn2 = conn\n |> post(question_path(conn, :create), %{\"title\" => \"\"})\n\n assert json_response(conn1, :created)\n assert json_response(conn2, :unprocessable_entity)\n end\n\n test \"Show a question\", %{conn: conn} do\n question = insert_question()\n\n conn = conn\n |> get(question_path(conn, :show, question.id))\n\n assert json_response(conn, :ok)\n end\n\n test \"Update a question\", %{conn: conn} do\n question = insert_question()\n\n conn1 = conn\n |> put(question_path(conn, :update, question.id), %{\"title\" => \"b\"})\n\n conn2 = conn\n |> put(question_path(conn, :update, question.id), %{\"title\" => \"\"})\n\n assert json_response(conn1, :ok)\n assert json_response(conn2, :unprocessable_entity)\n end\n\n test \"Delete a question\", %{conn: conn} do\n question = insert_question()\n\n conn = conn\n |> delete(question_path(conn, :delete, question.id))\n\n assert response(conn, :no_content)\n end\n\n test \"Resource not found\", %{conn: conn} do\n conn1 = get(conn, question_path(conn, :show, 0))\n conn2 = get(conn, question_path(conn, :update, 0, %{}))\n conn3 = get(conn, question_path(conn, :delete, 0))\n\n assert json_response(conn1, :not_found)\n assert json_response(conn2, :not_found)\n assert json_response(conn3, :not_found)\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"63ed24126ee6102a570352a8c31c6760a9b7ba79","subject":"Alias `Wallaby.DSL.Actions` for nicer reading","message":"Alias `Wallaby.DSL.Actions` for nicer reading\n","repos":"hashrocket\/tilex,hashrocket\/tilex,hashrocket\/tilex","old_file":"test\/features\/developer_creates_post_test.exs","new_file":"test\/features\/developer_creates_post_test.exs","new_contents":"defmodule DeveloperCreatesPostTest do\n use Tilex.IntegrationCase, async: true\n\n alias Tilex.Post\n alias Wallaby.DSL.Actions\n\n test \"fills out form and submits\", %{session: session} do\n\n EctoFactory.insert(:channel, name: \"phoenix\")\n\n visit(session, \"\/posts\/new\")\n h1_heading = get_text(session, \"main header h1\")\n assert h1_heading == \"Create Post\"\n\n session\n |> fill_in(\"Title\", with: \"Example Title\")\n |> fill_in(\"Body\", with: \"Example Body\")\n |> Actions.select(\"Channel\", option: \"phoenix\")\n |> click_on('Submit')\n\n post = Enum.reverse(Tilex.Repo.all(Post)) |> hd\n assert post.body == \"Example Body\"\n assert post.title == \"Example Title\"\n\n index_h1_heading = get_text(session, \"header.site_head div h1\")\n page_body = get_text(session, \"body\")\n post_footer = get_text(session, \".post aside\")\n\n assert index_h1_heading =~ ~r\/Today I Learned\/i\n assert page_body =~ ~r\/Example Title\/\n assert page_body =~ ~r\/Example Body\/\n assert post_footer =~ ~r\/#phoenix\/i\n end\n\n test \"cancels submission\", %{session: session} do\n\n session\n |> visit(\"\/posts\/new\")\n |> click_link(\"cancel\")\n\n path = get_current_path(session)\n\n assert path == \"\/\"\n end\n\n test \"fails to enter things\", %{session: session} do\n\n session\n |> visit(\"\/posts\/new\")\n |> click_on(\"Submit\")\n\n body = get_text(session, \"body\")\n\n assert body =~ ~r\/Title can't be blank\/\n assert body =~ ~r\/Body can't be blank\/\n assert body =~ ~r\/Channel can't be blank\/\n end\n\n test \"enters a title that is too long\", %{session: session} do\n\n session\n |> visit(\"\/posts\/new\")\n |> fill_in(\"Title\", with: String.duplicate(\"I can codez \", 10))\n |> click_on(\"Submit\")\n\n body = get_text(session, \"body\")\n\n assert body =~ ~r\/Title should be at most 50 character\\(s\\)\/\n end\n\n test \"enters a body that is too long\", %{session: session} do\n\n session\n |> visit(\"\/posts\/new\")\n |> fill_in(\"Body\", with: String.duplicate(\"wordy \", 201))\n |> click_on(\"Submit\")\n\n body = get_text(session, \"body\")\n\n assert body =~ ~r\/Body should be at most 200 word\\(s\\)\/\n end\n\n test \"enters markdown code into the body\", %{session: session} do\n\n EctoFactory.insert(:channel, name: \"phoenix\")\n\n session\n |> visit(\"\/posts\/new\")\n |> fill_in(\"Title\", with: \"Example Title\")\n |> fill_in(\"Body\", with: \"`code`\")\n |> Wallaby.DSL.Actions.select(\"Channel\", option: \"phoenix\")\n |> click_on('Submit')\n\n assert find(session, \"code\", text: \"code\")\n end\nend\n","old_contents":"defmodule DeveloperCreatesPostTest do\n use Tilex.IntegrationCase, async: true\n\n alias Tilex.Post\n\n test \"fills out form and submits\", %{session: session} do\n\n EctoFactory.insert(:channel, name: \"phoenix\")\n\n visit(session, \"\/posts\/new\")\n h1_heading = get_text(session, \"main header h1\")\n assert h1_heading == \"Create Post\"\n\n session\n |> fill_in(\"Title\", with: \"Example Title\")\n |> fill_in(\"Body\", with: \"Example Body\")\n |> Wallaby.DSL.Actions.select(\"Channel\", option: \"phoenix\")\n |> click_on('Submit')\n\n post = Enum.reverse(Tilex.Repo.all(Post)) |> hd\n assert post.body == \"Example Body\"\n assert post.title == \"Example Title\"\n\n index_h1_heading = get_text(session, \"header.site_head div h1\")\n page_body = get_text(session, \"body\")\n post_footer = get_text(session, \".post aside\")\n\n assert index_h1_heading =~ ~r\/Today I Learned\/i\n assert page_body =~ ~r\/Example Title\/\n assert page_body =~ ~r\/Example Body\/\n assert post_footer =~ ~r\/#phoenix\/i\n end\n\n test \"cancels submission\", %{session: session} do\n\n session\n |> visit(\"\/posts\/new\")\n |> click_link(\"cancel\")\n\n path = get_current_path(session)\n\n assert path == \"\/\"\n end\n\n test \"fails to enter things\", %{session: session} do\n\n session\n |> visit(\"\/posts\/new\")\n |> click_on(\"Submit\")\n\n body = get_text(session, \"body\")\n\n assert body =~ ~r\/Title can't be blank\/\n assert body =~ ~r\/Body can't be blank\/\n assert body =~ ~r\/Channel can't be blank\/\n end\n\n test \"enters a title that is too long\", %{session: session} do\n\n session\n |> visit(\"\/posts\/new\")\n |> fill_in(\"Title\", with: String.duplicate(\"I can codez \", 10))\n |> click_on(\"Submit\")\n\n body = get_text(session, \"body\")\n\n assert body =~ ~r\/Title should be at most 50 character\\(s\\)\/\n end\n\n test \"enters a body that is too long\", %{session: session} do\n\n session\n |> visit(\"\/posts\/new\")\n |> fill_in(\"Body\", with: String.duplicate(\"wordy \", 201))\n |> click_on(\"Submit\")\n\n body = get_text(session, \"body\")\n\n assert body =~ ~r\/Body should be at most 200 word\\(s\\)\/\n end\n\n test \"enters markdown code into the body\", %{session: session} do\n\n EctoFactory.insert(:channel, name: \"phoenix\")\n\n session\n |> visit(\"\/posts\/new\")\n |> fill_in(\"Title\", with: \"Example Title\")\n |> fill_in(\"Body\", with: \"`code`\")\n |> Wallaby.DSL.Actions.select(\"Channel\", option: \"phoenix\")\n |> click_on('Submit')\n\n assert find(session, \"code\", text: \"code\")\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"cd43f618e03a35fb4e3058dca4a7263af6b79868","subject":"CLI\/Compile: added a test to showcase the new behaviour","message":"CLI\/Compile: added a test to showcase the new behaviour\n","repos":"pedrosnk\/elixir,beedub\/elixir,michalmuskala\/elixir,lexmag\/elixir,gfvcastro\/elixir,ggcampinho\/elixir,kelvinst\/elixir,lexmag\/elixir,beedub\/elixir,joshprice\/elixir,pedrosnk\/elixir,antipax\/elixir,ggcampinho\/elixir,kelvinst\/elixir,kimshrier\/elixir,antipax\/elixir,kimshrier\/elixir,gfvcastro\/elixir,elixir-lang\/elixir","old_file":"lib\/elixir\/test\/elixir\/kernel\/cli_test.exs","new_file":"lib\/elixir\/test\/elixir\/kernel\/cli_test.exs","new_contents":"Code.require_file \"..\/test_helper.exs\", __DIR__\n\nimport PathHelpers\n\ndefmodule Kernel.CLI.InitTest do\n use ExUnit.Case, async: true\n\n test :code_init do\n assert elixir('-e \"IO.puts [?3]\"') == '3\\n'\n\n result = elixir('-e \"IO.puts inspect(System.argv)\" #{fixture_path(\"init_sample.exs\")} -o 1 2 3')\n assert result == '#{inspect [\"-o\", \"1\", \"2\", \"3\"]}\\n3\\n'\n end\nend\n\ndefmodule Kernel.CLI.OptionParsingTest do\n use ExUnit.Case, async: true\n\n test :path do\n root = fixture_path(\"..\/..\/..\") |> to_char_list\n list = elixir('-pa \"#{root}\/*\" -pz \"#{root}\/lib\/*\" -e \"IO.inspect(:code.get_path, limit: :infinity)\"')\n { path, _ } = Code.eval_string list, []\n\n # pa\n assert Path.expand('ebin', root) in path\n assert Path.expand('lib', root) in path\n assert Path.expand('src', root) in path\n\n # pz\n assert Path.expand('lib\/list', root) in path\n end\nend\n\ndefmodule Kernel.CLI.AtExitTest do\n use ExUnit.Case, async: true\n\n test :at_exit do\n assert elixir(fixture_path(\"at_exit.exs\") |> to_char_list) ==\n 'goodbye cruel world with status 0\\n'\n end\nend\n\ndefmodule Kernel.CLI.ErrorTest do\n use ExUnit.Case, async: true\n\n test :code_error do\n assert :string.str('** (throw) 1', elixir('-e \"throw 1\"')) == 0\n assert :string.str('** (ErlangError) erlang error: 1', elixir('-e \"error 1\"')) == 0\n\n # It does not catch exits with integers nor strings...\n assert elixir('-e \"exit 1\"') == ''\n end\nend\n\ndefmodule Kernel.CLI.SyntaxErrorTest do\n use ExUnit.Case, async: true\n\n defp check_output(elixir_cmd, expected_msg) do\n o = elixir(elixir_cmd)\n assert :string.str(o, expected_msg) == 1, \"Expected this output: `#{expected_msg}`\\nbut got this output: `#{o}`\"\n end\n\n test :syntax_code_error do\n check_output('-e \"[1,2\"', '** (TokenMissingError) nofile:1: missing terminator: ]')\n check_output('-e \"case 1 end\"', %C\"** (SyntaxError) nofile:1: unexpected token: end\")\n end\nend\n\ndefmodule Kernel.CLI.CompileTest do\n use ExUnit.Case, async: true\n\n test :compile_code do\n fixture = fixture_path \"compile_sample.ex\"\n assert elixirc('#{fixture} -o #{tmp_path}') == ''\n assert File.regular?(tmp_path \"Elixir.CompileSample.beam\")\n after\n File.rm(tmp_path(\"Elixir.CompileSample.beam\"))\n end\n\n test :compile_code_verbose do\n fixture = fixture_path \"compile_sample.ex\"\n assert elixirc('#{fixture} -o #{tmp_path} --verbose') ==\n 'Compiled #{fixture}\\n'\n assert File.regular?(tmp_path \"Elixir.CompileSample.beam\")\n after\n File.rm(tmp_path(\"Elixir.CompileSample.beam\"))\n end\n\n test :possible_deadlock do\n output = elixirc('#{fixture_path(\"parallel_deadlock\")} -o #{tmp_path}')\n foo = '* #{fixture_path \"parallel_deadlock\/foo.ex\"} is missing module Bar'\n bar = '* #{fixture_path \"parallel_deadlock\/bar.ex\"} is missing module Foo'\n assert :string.str(output, foo) > 0, \"expected foo.ex to miss module Bar\"\n assert :string.str(output, bar) > 0, \"expected bar.ex to miss module Foo\"\n assert :string.str(output, 'elixir_compiler') == 0, \"expected elixir_compiler to not be in output\"\n end\n\n test :compile_missing_patterns do\n fixture = fixture_path \"compile_sample.ex\"\n output = elixirc('#{fixture} non_existing.ex -o #{tmp_path}')\n assert :string.str(output, 'non_existing.ex') > 0, \"expected non_existing.ex to be mentionned\"\n assert :string.str(output, 'compile_sample.ex') == 0, \"expected compile_sample.ex to not be mentionned\"\n refute File.exists?(tmp_path(\"Elixir.CompileSample.beam\")) , \"expected the sample to not be compiled\"\n end\nend\n\ndefmodule Kernel.CLI.ParallelCompilerTest do\n use ExUnit.Case\n import ExUnit.CaptureIO\n\n test :files do\n fixtures = [fixture_path(\"parallel_compiler\/bar.ex\"), fixture_path(\"parallel_compiler\/foo.ex\")]\n assert capture_io(fn ->\n assert [Bar, Foo] = Kernel.ParallelCompiler.files fixtures\n end) =~ \"message_from_foo\"\n end\n\n test :warnings_as_errors do\n warnings_as_errors = Code.compiler_options[:warnings_as_errors]\n\n try do\n Code.compiler_options(warnings_as_errors: true)\n\n assert_raise CompileError, fn ->\n capture_io :stderr, fn ->\n Kernel.ParallelCompiler.files [fixture_path(\"warnings_sample.ex\")]\n end\n end\n after\n Code.compiler_options(warnings_as_errors: warnings_as_errors)\n end\n end\nend\n","old_contents":"Code.require_file \"..\/test_helper.exs\", __DIR__\n\nimport PathHelpers\n\ndefmodule Kernel.CLI.InitTest do\n use ExUnit.Case, async: true\n\n test :code_init do\n assert elixir('-e \"IO.puts [?3]\"') == '3\\n'\n\n result = elixir('-e \"IO.puts inspect(System.argv)\" #{fixture_path(\"init_sample.exs\")} -o 1 2 3')\n assert result == '#{inspect [\"-o\", \"1\", \"2\", \"3\"]}\\n3\\n'\n end\nend\n\ndefmodule Kernel.CLI.OptionParsingTest do\n use ExUnit.Case, async: true\n\n test :path do\n root = fixture_path(\"..\/..\/..\") |> to_char_list\n list = elixir('-pa \"#{root}\/*\" -pz \"#{root}\/lib\/*\" -e \"IO.inspect(:code.get_path, limit: :infinity)\"')\n { path, _ } = Code.eval_string list, []\n\n # pa\n assert Path.expand('ebin', root) in path\n assert Path.expand('lib', root) in path\n assert Path.expand('src', root) in path\n\n # pz\n assert Path.expand('lib\/list', root) in path\n end\nend\n\ndefmodule Kernel.CLI.AtExitTest do\n use ExUnit.Case, async: true\n\n test :at_exit do\n assert elixir(fixture_path(\"at_exit.exs\") |> to_char_list) ==\n 'goodbye cruel world with status 0\\n'\n end\nend\n\ndefmodule Kernel.CLI.ErrorTest do\n use ExUnit.Case, async: true\n\n test :code_error do\n assert :string.str('** (throw) 1', elixir('-e \"throw 1\"')) == 0\n assert :string.str('** (ErlangError) erlang error: 1', elixir('-e \"error 1\"')) == 0\n\n # It does not catch exits with integers nor strings...\n assert elixir('-e \"exit 1\"') == ''\n end\nend\n\ndefmodule Kernel.CLI.SyntaxErrorTest do\n use ExUnit.Case, async: true\n\n defp check_output(elixir_cmd, expected_msg) do\n o = elixir(elixir_cmd)\n assert :string.str(o, expected_msg) == 1, \"Expected this output: `#{expected_msg}`\\nbut got this output: `#{o}`\"\n end\n\n test :syntax_code_error do\n check_output('-e \"[1,2\"', '** (TokenMissingError) nofile:1: missing terminator: ]')\n check_output('-e \"case 1 end\"', %C\"** (SyntaxError) nofile:1: unexpected token: end\")\n end\nend\n\ndefmodule Kernel.CLI.CompileTest do\n use ExUnit.Case, async: true\n\n test :compile_code do\n fixture = fixture_path \"compile_sample.ex\"\n assert elixirc('#{fixture} -o #{tmp_path}') == ''\n assert File.regular?(tmp_path \"Elixir.CompileSample.beam\")\n after\n File.rm(tmp_path(\"Elixir.CompileSample.beam\"))\n end\n\n test :compile_code_verbose do\n fixture = fixture_path \"compile_sample.ex\"\n assert elixirc('#{fixture} -o #{tmp_path} --verbose') ==\n 'Compiled #{fixture}\\n'\n assert File.regular?(tmp_path \"Elixir.CompileSample.beam\")\n after\n File.rm(tmp_path(\"Elixir.CompileSample.beam\"))\n end\n\n test :possible_deadlock do\n output = elixirc('#{fixture_path(\"parallel_deadlock\")} -o #{tmp_path}')\n foo = '* #{fixture_path \"parallel_deadlock\/foo.ex\"} is missing module Bar'\n bar = '* #{fixture_path \"parallel_deadlock\/bar.ex\"} is missing module Foo'\n assert :string.str(output, foo) > 0, \"expected foo.ex to miss module Bar\"\n assert :string.str(output, bar) > 0, \"expected bar.ex to miss module Foo\"\n assert :string.str(output, 'elixir_compiler') == 0, \"expected elixir_compiler to not be in output\"\n end\nend\n\ndefmodule Kernel.CLI.ParallelCompilerTest do\n use ExUnit.Case\n import ExUnit.CaptureIO\n\n test :files do\n fixtures = [fixture_path(\"parallel_compiler\/bar.ex\"), fixture_path(\"parallel_compiler\/foo.ex\")]\n assert capture_io(fn ->\n assert [Bar, Foo] = Kernel.ParallelCompiler.files fixtures\n end) =~ \"message_from_foo\"\n end\n\n test :warnings_as_errors do\n warnings_as_errors = Code.compiler_options[:warnings_as_errors]\n\n try do\n Code.compiler_options(warnings_as_errors: true)\n\n assert_raise CompileError, fn ->\n capture_io :stderr, fn ->\n Kernel.ParallelCompiler.files [fixture_path(\"warnings_sample.ex\")]\n end\n end\n after\n Code.compiler_options(warnings_as_errors: warnings_as_errors)\n end\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"fd27c2053fe12941a58213f9036692ad9a7f185f","subject":"Run the formatter on translator tests","message":"Run the formatter on translator tests\n","repos":"kelvinst\/elixir,ggcampinho\/elixir,kelvinst\/elixir,joshprice\/elixir,elixir-lang\/elixir,lexmag\/elixir,kimshrier\/elixir,pedrosnk\/elixir,pedrosnk\/elixir,kimshrier\/elixir,ggcampinho\/elixir,lexmag\/elixir,michalmuskala\/elixir","old_file":"lib\/logger\/test\/logger\/translator_test.exs","new_file":"lib\/logger\/test\/logger\/translator_test.exs","new_contents":"defmodule Logger.TranslatorTest do\n use Logger.Case\n\n defmodule MyGenServer do\n use GenServer\n\n def init(args) do\n {:ok, args}\n end\n\n def handle_cast(:error, _) do\n raise \"oops\"\n end\n\n def handle_call(:exit, _, _) do\n exit(:oops)\n end\n\n def handle_call(:error, _, _) do\n raise \"oops\"\n end\n\n def handle_call(:error_on_down, {pid, _}, _) do\n mon = Process.monitor(pid)\n assert_receive {:DOWN, ^mon, _, _, _}\n raise \"oops\"\n end\n end\n\n defmodule MyGenEvent do\n @behaviour :gen_event\n\n def init(args) do\n {:ok, args}\n end\n\n def handle_event(_event, state) do\n {:ok, state}\n end\n\n def handle_call(:error, _) do\n raise \"oops\"\n end\n\n def handle_info(_msg, state) do\n {:ok, state}\n end\n\n def code_change(_old_vsn, state, _extra) do\n {:ok, state}\n end\n\n def terminate(_reason, _state) do\n :ok\n end\n end\n\n defmodule MyBridge do\n @behaviour :supervisor_bridge\n\n def init(reason) do\n {:ok, pid} = Task.start_link(Kernel, :exit, [reason])\n {:ok, pid, pid}\n end\n\n def terminate(_reason, pid) do\n Process.exit(pid, :shutdown)\n end\n end\n\n setup_all do\n sasl_reports? = Application.get_env(:logger, :handle_sasl_reports, false)\n Application.put_env(:logger, :handle_sasl_reports, true)\n\n # Configure backend specific for tests to assert on metadata\n # We could rely exclusively on this backend and skip the console one\n # but using capture_log+console is desired as an integration test\n Logger.add_backend(Logger.TestBackend)\n\n # Restart the app but change the level before to avoid warnings\n level = Logger.level()\n Logger.configure(level: :error)\n Logger.App.stop()\n Application.start(:logger)\n Logger.configure(level: level)\n\n on_exit(fn ->\n Logger.remove_backend(Logger.TestBackend)\n Application.put_env(:logger, :handle_sasl_reports, sasl_reports?)\n Logger.App.stop()\n Application.start(:logger)\n end)\n end\n\n setup do\n Logger.configure_backend(Logger.TestBackend, callback_pid: self())\n end\n\n test \"translates GenServer crashes\" do\n {:ok, pid} = GenServer.start(MyGenServer, :ok)\n\n assert capture_log(:info, fn ->\n catch_exit(GenServer.call(pid, :error))\n end) =~ \"\"\"\n [error] GenServer #{inspect(pid)} terminating\n ** (RuntimeError) oops\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"GenServer \" <> _ | _], _ts, gen_server_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(gen_server_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates GenServer crashes with custom inspect options\" do\n {:ok, pid} = GenServer.start(MyGenServer, List.duplicate(:ok, 1000))\n Application.put_env(:logger, :translator_inspect_opts, limit: 3)\n\n assert capture_log(:debug, fn ->\n catch_exit(GenServer.call(pid, :error))\n end) =~ \"\"\"\n [:ok, :ok, :ok, ...]\n \"\"\"\n after\n Application.put_env(:logger, :translator_inspect_opts, [])\n end\n\n # TODO: Remove this check once we depend only on 20\n if :erlang.system_info(:otp_release) >= '20' do\n test \"translates GenServer crashes on debug\" do\n {:ok, pid} = GenServer.start(MyGenServer, :ok)\n\n assert capture_log(:debug, fn ->\n catch_exit(GenServer.call(pid, :error))\n end) =~ ~r\"\"\"\n \\[error\\] GenServer #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Last message \\(from #PID<\\d+\\.\\d+\\.\\d+>\\): :error\n State: :ok\n Client #PID<\\d+\\.\\d+\\.\\d+> is alive\n .*\n \"\"\"s\n\n assert_receive {:error, _pid,\n {Logger, [[\"GenServer \" <> _ | _] | _], _ts, gen_server_metadata}}\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(gen_server_metadata, :crash_reason)\n\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n\n test \"translates GenServer crashes with named client on debug\" do\n {:ok, pid} = GenServer.start(MyGenServer, :ok)\n\n assert capture_log(:debug, fn ->\n Process.register(self(), :named_client)\n catch_exit(GenServer.call(pid, :error))\n end) =~ ~r\"\"\"\n \\[error\\] GenServer #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Last message \\(from :named_client\\): :error\n State: :ok\n Client :named_client is alive\n .*\n \"\"\"s\n end\n\n test \"translates GenServer crashes with dead client on debug\" do\n {:ok, pid} = GenServer.start(MyGenServer, :ok)\n\n assert capture_log(:debug, fn ->\n mon = Process.monitor(pid)\n\n spawn_link(fn ->\n catch_exit(GenServer.call(pid, :error_on_down, 0))\n end)\n\n assert_receive {:DOWN, ^mon, _, _, _}\n end) =~ ~r\"\"\"\n \\[error\\] GenServer #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Last message \\(from #PID<\\d+\\.\\d+\\.\\d+>\\): :error_on_down\n State: :ok\n Client #PID<\\d+\\.\\d+\\.\\d+> is dead\n \"\"\"s\n end\n else\n test \"translates GenServer crashes on debug\" do\n {:ok, pid} = GenServer.start(MyGenServer, :ok)\n\n assert capture_log(:debug, fn ->\n catch_exit(GenServer.call(pid, :error))\n end) =~ ~r\"\"\"\n \\[error\\] GenServer #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Last message: :error\n State: :ok\n \"\"\"s\n\n assert_receive {:error, _pid,\n {Logger, [[\"GenServer \" <> _ | _] | _], _ts, gen_server_metadata}}\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(gen_server_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n end\n\n test \"translates GenServer crashes with no client\" do\n {:ok, pid} = GenServer.start(MyGenServer, :ok)\n\n assert capture_log(:debug, fn ->\n mon = Process.monitor(pid)\n GenServer.cast(pid, :error)\n assert_receive {:DOWN, ^mon, _, _, _}\n end) =~ ~r\"\"\"\n \\[error\\] GenServer #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Last message: {:\"\\$gen_cast\", :error}\n State: :ok\n \"\"\"s\n end\n\n test \"translates GenServer crashes with no client on debug\" do\n {:ok, pid} = GenServer.start(MyGenServer, :ok)\n\n refute capture_log(:debug, fn ->\n mon = Process.monitor(pid)\n GenServer.cast(pid, :error)\n assert_receive {:DOWN, ^mon, _, _, _}\n end) =~ \"Client\"\n\n assert_receive {:error, _pid,\n {Logger, [[\"GenServer \" <> _ | _] | _], _ts, gen_server_metadata}}\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n end\n\n test \"translates :gen_event crashes\" do\n {:ok, pid} = :gen_event.start()\n :ok = :gen_event.add_handler(pid, MyGenEvent, :ok)\n\n assert capture_log(:info, fn ->\n :gen_event.call(pid, MyGenEvent, :error)\n end) =~ \"\"\"\n [error] :gen_event handler Logger.TranslatorTest.MyGenEvent installed in #{\n inspect(pid)\n } terminating\n ** (RuntimeError) oops\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\":gen_event handler \" <> _ | _], _ts, metadata}}\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} = Keyword.get(metadata, :crash_reason)\n end\n\n test \"translates :gen_event crashes on debug\" do\n {:ok, pid} = :gen_event.start()\n :ok = :gen_event.add_handler(pid, MyGenEvent, :ok)\n\n assert capture_log(:debug, fn ->\n :gen_event.call(pid, MyGenEvent, :error)\n end) =~ ~r\"\"\"\n \\[error\\] :gen_event handler Logger.TranslatorTest.MyGenEvent installed in #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Last message: :error\n State: :ok\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [[\":gen_event handler \" <> _ | _] | _], _ts, metadata}}\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} = Keyword.get(metadata, :crash_reason)\n end\n\n test \"translates Task crashes\" do\n {:ok, pid} = Task.start_link(__MODULE__, :task, [self()])\n\n assert capture_log(fn ->\n ref = Process.monitor(pid)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[error\\] Task #PID<\\d+\\.\\d+\\.\\d+> started from #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Function: &Logger.TranslatorTest.task\\\/1\n Args: \\[#PID<\\d+\\.\\d+\\.\\d+>\\]\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} = Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Task async_stream crashes with neighbour\" do\n fun = fn -> Task.async_stream([:oops], :erlang, :error, []) |> Enum.to_list() end\n {:ok, pid} = Task.start(__MODULE__, :task, [self(), fun])\n\n assert capture_log(:debug, fn ->\n ref = Process.monitor(pid)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n Neighbours:\n #{inspect(pid)}\n Initial Call: Logger\\.TranslatorTest\\.task\/2\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert {:oops, [_ | _]} = Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%ErlangError{original: :oops}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Task undef module crash\" do\n assert capture_log(fn ->\n {:ok, pid} = Task.start(:module_does_not_exist, :undef, [])\n ref = Process.monitor(pid)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[error\\] Task #PID<\\d+\\.\\d+\\.\\d+> started from #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(UndefinedFunctionError\\) function :module_does_not_exist.undef\/0 is undefined \\(module :module_does_not_exist is not available\\)\n .*\n Function: &:module_does_not_exist.undef\/0\n Args: \\[\\]\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n assert {%UndefinedFunctionError{function: :undef}, [_ | _]} =\n Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%UndefinedFunctionError{function: :undef}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Task undef function crash\" do\n assert capture_log(fn ->\n {:ok, pid} = Task.start(__MODULE__, :undef, [])\n ref = Process.monitor(pid)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[error\\] Task #PID<\\d+\\.\\d+\\.\\d+> started from #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(UndefinedFunctionError\\) function Logger.TranslatorTest.undef\/0 is undefined or private\n .*\n Function: &Logger.TranslatorTest.undef\/0\n Args: \\[\\]\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n assert {%UndefinedFunctionError{function: :undef}, [_ | _]} =\n Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%UndefinedFunctionError{function: :undef}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Task raising ErlangError\" do\n assert capture_log(fn ->\n exception =\n try do\n :erlang.error(:foo)\n rescue\n x ->\n x\n end\n\n {:ok, pid} = Task.start(:erlang, :error, [exception])\n ref = Process.monitor(pid)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[error\\] Task #PID<\\d+\\.\\d+\\.\\d+> started from #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(ErlangError\\) Erlang error: :foo\n .*\n Function: &:erlang\\.error\/1\n Args: \\[%ErlangError{.*}\\]\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert {%ErlangError{original: :foo}, [_ | _]} = Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%ErlangError{original: :foo}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Task raising Erlang badarg error\" do\n assert capture_log(fn ->\n {:ok, pid} = Task.start(:erlang, :error, [:badarg])\n ref = Process.monitor(pid)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[error\\] Task #PID<\\d+\\.\\d+\\.\\d+> started from #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(ArgumentError\\) argument error\n .*\n Function: &:erlang\\.error\/1\n Args: \\[:badarg\\]\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n assert {%ArgumentError{message: \"argument error\"}, [_ | _]} =\n Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%ArgumentError{message: \"argument error\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Task exiting abnormally\" do\n assert capture_log(fn ->\n {:ok, pid} = Task.start(:erlang, :exit, [:abnormal])\n ref = Process.monitor(pid)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[error\\] Task #PID<\\d+\\.\\d+\\.\\d+> started from #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(stop\\) :abnormal\n .*\n Function: &:erlang\\.exit\/1\n Args: \\[:abnormal\\]\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert {:abnormal, [_ | _]} = Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:abnormal, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates application start\" do\n assert capture_log(fn ->\n Application.start(:eex)\n Application.stop(:eex)\n end) =~ \"\"\"\n Application eex started at #{inspect(node())}\n \"\"\"\n end\n\n test \"translates application stop\" do\n assert capture_log(fn ->\n :ok = Application.start(:eex)\n Application.stop(:eex)\n end) =~ \"\"\"\n Application eex exited: :stopped\n \"\"\"\n end\n\n test \"translates bare process crashes\" do\n assert capture_log(:info, fn ->\n {_, ref} = spawn_monitor(fn -> raise \"oops\" end)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n # Even though the monitor has been received the emulator may not have\n # sent the message to the error logger\n Process.sleep(200)\n end) =~ ~r\"\"\"\n \\[error\\] Process #PID<\\d+\\.\\d+\\.\\d+>\\ raised an exception\n \\*\\* \\(RuntimeError\\) oops\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates :proc_lib crashes\" do\n fun = fn ->\n Logger.metadata(foo: :bar)\n raise \"oops\"\n end\n\n pid = :proc_lib.spawn_link(__MODULE__, :task, [self(), fun])\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[error\\] Process #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Initial Call: Logger.TranslatorTest.task\/2\n Ancestors: \\[#PID<\\d+\\.\\d+\\.\\d+>\\]\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n assert Keyword.get(process_metadata, :foo) == :bar\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"skips :proc_lib crashes with disabled metadata\" do\n fun = fn ->\n Logger.disable(self())\n raise \"oops\"\n end\n\n pid = :proc_lib.spawn_link(__MODULE__, :task, [self(), fun])\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) == \"\"\n end\n\n test \"translates :proc_lib crashes with name\" do\n fun = fn ->\n Process.register(self(), __MODULE__)\n raise \"oops\"\n end\n\n pid = :proc_lib.spawn_link(__MODULE__, :task, [self(), fun])\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n send(pid, :message)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[error\\] Process Logger.TranslatorTest \\(#PID<\\d+\\.\\d+\\.\\d+>\\) terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Initial Call: Logger.TranslatorTest.task\/2\n Ancestors: \\[#PID<\\d+\\.\\d+\\.\\d+>\\]\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates :proc_lib crashes without initial call\" do\n fun = fn ->\n Process.delete(:\"$initial_call\")\n raise \"oops\"\n end\n\n pid = :proc_lib.spawn_link(__MODULE__, :task, [self(), fun])\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n send(pid, :message)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[error\\] Process #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Ancestors: \\[#PID<\\d+\\.\\d+\\.\\d+>\\]\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates :proc_lib crashes with neighbour\" do\n {:ok, pid} = Task.start_link(__MODULE__, :sub_task, [self()])\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n send(pid, :message)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n Ancestors: \\[#PID<\\d+\\.\\d+\\.\\d+>\\]\n Neighbours:\n #PID<\\d+\\.\\d+\\.\\d+>\n Initial Call: Logger.TranslatorTest.sleep\/1\n Current Call: Logger.TranslatorTest.sleep\/1\n Ancestors: \\[#PID<\\d+\\.\\d+\\.\\d+>, #PID<\\d+\\.\\d+\\.\\d+>\\]\n \"\"\"\n end\n\n test \"translates :proc_lib crashes with neighbour with name\" do\n fun = fn pid2 ->\n Process.register(pid2, __MODULE__)\n raise \"oops\"\n end\n\n {:ok, pid} = Task.start_link(__MODULE__, :sub_task, [self(), fun])\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n send(pid, :message)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n Ancestors: \\[#PID<\\d+\\.\\d+\\.\\d+>\\]\n Neighbours:\n Logger.TranslatorTest \\(#PID<\\d+\\.\\d+\\.\\d+>\\)\n Initial Call: Logger.TranslatorTest.sleep\/1\n Current Call: Logger.TranslatorTest.sleep\/1\n Ancestors: \\[#PID<\\d+\\.\\d+\\.\\d+>, #PID<\\d+\\.\\d+\\.\\d+>\\]\n \"\"\"\n end\n\n test \"translates :proc_lib crashes on debug\" do\n {:ok, pid} = Task.start_link(__MODULE__, :task, [self()])\n\n assert capture_log(:debug, fn ->\n ref = Process.monitor(pid)\n send(pid, :message)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n Ancestors: \\[#PID<\\d+\\.\\d+\\.\\d+>\\](?:\n Message Queue Length: 1(?#TODO: Require once depend on Erlang\/OTP 20)|)\n Messages: \\[:message\\]\n Links: \\[\\]\n Dictionary: \\[\\]\n Trapping Exits: false\n Status: :running\n Heap Size: \\d+\n Stack Size: \\d+\n Reductions: \\d+\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} = Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates :proc_lib crashes with neighbour on debug\" do\n {:ok, pid} = Task.start_link(__MODULE__, :sub_task, [self()])\n\n assert capture_log(:debug, fn ->\n ref = Process.monitor(pid)\n send(pid, :message)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n Ancestors: \\[#PID<\\d+\\.\\d+\\.\\d+>, #PID<\\d+\\.\\d+\\.\\d+>\\](?:\n Message Queue Length: 0|\n Messages: \\[\\](?# TODO: Remove once depend on 20))\n Links: \\[#PID<\\d+\\.\\d+\\.\\d+>\\](?:|\n Dictionary: \\[\\](?# TODO: Remove once depend on 20))\n Trapping Exits: false\n Status: :waiting\n Heap Size: \\d+\n Stack Size: \\d+\n Reductions: \\d+(?:\n Current Stacktrace:\n test\/logger\/translator_test.exs:\\d+: Logger.TranslatorTest.sleep\/1(?#TODO: Require once depend on Erlang\/OTP 20)|)\n \"\"\"\n end\n\n test \"translates Supervisor progress\" do\n {:ok, pid} = Supervisor.start_link([], strategy: :one_for_one)\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n Supervisor.start_child(pid, worker(Task, [__MODULE__, :sleep, [self()]]))\n Process.exit(pid, :normal)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[info\\] Child Task of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Supervisor\\.Default\\) started\n Pid: #PID<\\d+\\.\\d+\\.\\d+>\n Start Call: Task.start_link\\(Logger.TranslatorTest, :sleep, \\[#PID<\\d+\\.\\d+\\.\\d+>\\]\\)\n \"\"\"\n end\n\n test \"translates Supervisor progress with name\" do\n {:ok, pid} = Supervisor.start_link([], strategy: :one_for_one, name: __MODULE__)\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n Supervisor.start_child(pid, worker(Task, [__MODULE__, :sleep, [self()]]))\n Process.exit(pid, :normal)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[info\\] Child Task of Supervisor Logger.TranslatorTest started\n \"\"\"\n\n {:ok, pid} = Supervisor.start_link([], strategy: :one_for_one, name: {:global, __MODULE__})\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n Supervisor.start_child(pid, worker(Task, [__MODULE__, :sleep, [self()]]))\n Process.exit(pid, :normal)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[info\\] Child Task of Supervisor Logger.TranslatorTest started\n \"\"\"\n\n {:ok, pid} =\n Supervisor.start_link([], strategy: :one_for_one, name: {:via, :global, __MODULE__})\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n Supervisor.start_child(pid, worker(Task, [__MODULE__, :sleep, [self()]]))\n Process.exit(pid, :normal)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[info\\] Child Task of Supervisor Logger.TranslatorTest started\n \"\"\"\n end\n\n test \"translates Supervisor progress on debug\" do\n {:ok, pid} = Supervisor.start_link([], strategy: :one_for_one)\n\n assert capture_log(:debug, fn ->\n ref = Process.monitor(pid)\n Supervisor.start_child(pid, worker(Task, [__MODULE__, :sleep, [self()]]))\n Process.exit(pid, :normal)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n Start Call: Task.start_link\\(Logger.TranslatorTest, :sleep, \\[#PID<\\d+\\.\\d+\\.\\d+>\\]\\)\n Restart: :permanent\n Shutdown: 5000\n Type: :worker\n \"\"\"\n end\n\n test \"translates Supervisor reports start error\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n children = [worker(__MODULE__, [], function: :error)]\n Supervisor.start_link(children, strategy: :one_for_one)\n receive do: ({:EXIT, _, {:shutdown, {:failed_to_start_child, _, _}}} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[error\\] Child Logger.TranslatorTest of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Supervisor\\.Default\\) failed to start\n \\*\\* \\(exit\\) :stop\n Start Call: Logger.TranslatorTest.error\\(\\)\n \"\"\"\n end\n\n test \"translates Supervisor reports start error with raise\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n children = [worker(__MODULE__, [], function: :undef)]\n Supervisor.start_link(children, strategy: :one_for_one)\n receive do: ({:EXIT, _, {:shutdown, {:failed_to_start_child, _, _}}} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[error\\] Child Logger.TranslatorTest of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Supervisor\\.Default\\) failed to start\n \\*\\* \\(exit\\) an exception was raised:\n \\*\\* \\(UndefinedFunctionError\\) function Logger.TranslatorTest.undef\/0 is undefined or private\n .*\n Start Call: Logger.TranslatorTest.undef\\(\\)\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Child \" | _], _ts, _child_metadata}}\n end\n\n test \"translates Supervisor reports terminated\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n children = [worker(Task, [Kernel, :exit, [:stop]])]\n {:ok, pid} = Supervisor.start_link(children, strategy: :one_for_one, max_restarts: 0)\n receive do: ({:EXIT, ^pid, _} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[error\\] Child Task of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Supervisor\\.Default\\) terminated\n \\*\\* \\(exit\\) :stop\n Pid: #PID<\\d+\\.\\d+\\.\\d+>\n Start Call: Task.start_link\\(Kernel, :exit, \\[:stop\\]\\)\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \" | _], _ts, _child_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \", \"Task\" | _], _ts, _child_task_metadata}}\n assert {:stop, [_ | _]} = Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:stop, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Supervisor reports max restarts shutdown\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n children = [worker(Task, [Kernel, :exit, [:stop]])]\n {:ok, pid} = Supervisor.start_link(children, strategy: :one_for_one, max_restarts: 0)\n receive do: ({:EXIT, ^pid, _} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[error\\] Child Task of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Supervisor\\.Default\\) caused shutdown\n \\*\\* \\(exit\\) :reached_max_restart_intensity\n Start Call: Task.start_link\\(Kernel, :exit, \\[:stop\\]\\)\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \" | _], _ts, _child_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \", \"Task\" | _], _ts, _child_task_metadata}}\n assert {:stop, [_ | _]} = Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:stop, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Supervisor reports abnormal shutdown\" do\n assert capture_log(:info, fn ->\n children = [worker(__MODULE__, [], function: :abnormal)]\n {:ok, pid} = Supervisor.start_link(children, strategy: :one_for_one)\n :ok = Supervisor.terminate_child(pid, __MODULE__)\n end) =~ ~r\"\"\"\n \\[error\\] Child Logger.TranslatorTest of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Supervisor\\.Default\\) shutdown abnormally\n \\*\\* \\(exit\\) :stop\n Pid: #PID<\\d+\\.\\d+\\.\\d+>\n Start Call: Logger.TranslatorTest.abnormal\\(\\)\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \" | _], _ts, _child_metadata}}\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:stop, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Supervisor reports abnormal shutdown on debug\" do\n assert capture_log(:debug, fn ->\n children = [\n worker(__MODULE__, [], function: :abnormal, restart: :permanent, shutdown: 5000)\n ]\n\n {:ok, pid} = Supervisor.start_link(children, strategy: :one_for_one)\n :ok = Supervisor.terminate_child(pid, __MODULE__)\n end) =~ ~r\"\"\"\n \\*\\* \\(exit\\) :stop\n Pid: #PID<\\d+\\.\\d+\\.\\d+>\n Start Call: Logger.TranslatorTest.abnormal\\(\\)\n Restart: :permanent\n Shutdown: 5000\n Type: :worker\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \" | _], _ts, _child_metadata}}\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:stop, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Supervisor reports abnormal shutdown in simple_one_for_one\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n children = [worker(__MODULE__, [], function: :abnormal)]\n {:ok, pid} = Supervisor.start_link(children, strategy: :simple_one_for_one)\n {:ok, _pid2} = Supervisor.start_child(pid, [])\n Process.exit(pid, :normal)\n receive do: ({:EXIT, ^pid, _} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[error\\] Children Logger.TranslatorTest of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Supervisor\\.Default\\) shutdown abnormally\n \\*\\* \\(exit\\) :stop\n Number: 1\n Start Call: Logger.TranslatorTest.abnormal\\(\\)\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Children \" | _], _ts, _children_metadata}}\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:stop, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates DynamicSupervisor reports abnormal shutdown\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n child = %{id: __MODULE__, start: {__MODULE__, :abnormal, []}}\n {:ok, pid} = DynamicSupervisor.start_link(strategy: :one_for_one)\n {:ok, _pid2} = DynamicSupervisor.start_child(pid, child)\n Process.exit(pid, :normal)\n receive do: ({:EXIT, ^pid, _} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[error\\] Child :undefined of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Supervisor\\.Default\\) shutdown abnormally\n \\*\\* \\(exit\\) :stop\n Pid: #PID<\\d+\\.\\d+\\.\\d+>\n Start Call: Logger.TranslatorTest.abnormal\\(\\)\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \" | _], _ts, child_metadata}}\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:stop, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates DynamicSupervisor reports abnormal shutdown including extra_arguments\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n\n {:ok, pid} =\n DynamicSupervisor.start_link(strategy: :one_for_one, extra_arguments: [:extra])\n\n child = %{id: __MODULE__, start: {__MODULE__, :abnormal, [:args]}}\n {:ok, _pid2} = DynamicSupervisor.start_child(pid, child)\n Process.exit(pid, :normal)\n receive do: ({:EXIT, ^pid, _} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[error\\] Child :undefined of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Supervisor\\.Default\\) shutdown abnormally\n \\*\\* \\(exit\\) :stop\n Pid: #PID<\\d+\\.\\d+\\.\\d+>\n Start Call: Logger.TranslatorTest.abnormal\\(:extra, :args\\)\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \" | _], _ts, _child_metadata}}\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:stop, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates named DynamicSupervisor reports abnormal shutdown\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n child = %{id: __MODULE__, start: {__MODULE__, :abnormal, []}}\n {:ok, pid} = DynamicSupervisor.start_link(strategy: :one_for_one, name: __MODULE__)\n {:ok, _pid2} = DynamicSupervisor.start_child(pid, child)\n Process.exit(pid, :normal)\n receive do: ({:EXIT, ^pid, _} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[error\\] Child :undefined of Supervisor Logger.TranslatorTest shutdown abnormally\n \\*\\* \\(exit\\) :stop\n Pid: #PID<\\d+\\.\\d+\\.\\d+>\n Start Call: Logger.TranslatorTest.abnormal\\(\\)\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \" | _], _ts, _child_metadata}}\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:stop, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates :supervisor_bridge progress\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n {:ok, pid} = :supervisor_bridge.start_link(MyBridge, :normal)\n receive do: ({:EXIT, ^pid, _} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[info\\] Child of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Logger\\.TranslatorTest\\.MyBridge\\) started\n Pid: #PID<\\d+\\.\\d+\\.\\d+>\n Start Call: Logger.TranslatorTest.MyBridge.init\\(:normal\\)\n \"\"\"\n end\n\n test \"translates :supervisor_bridge reports\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n {:ok, pid} = :supervisor_bridge.start_link(MyBridge, :stop)\n receive do: ({:EXIT, ^pid, _} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[error\\] Child of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Logger\\.TranslatorTest\\.MyBridge\\) terminated\n \\*\\* \\(exit\\) :stop\n Pid: #PID<\\d+\\.\\d+\\.\\d+>\n Start Module: Logger.TranslatorTest.MyBridge\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child of Supervisor \" | _], _ts, _child_metadata}}\n\n assert {:stop, [_ | _]} = Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:stop, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"reports :undefined MFA properly\" do\n defmodule WeirdFunctionNamesGenServer do\n use GenServer\n\n def unquote(:\"start link\")(), do: GenServer.start_link(__MODULE__, [])\n def init(args), do: {:ok, args}\n def handle_call(_call, _from, _state), do: raise(\"oops\")\n end\n\n child_opts = [restart: :temporary, function: :\"start link\"]\n children = [worker(WeirdFunctionNamesGenServer, [], child_opts)]\n {:ok, sup} = Supervisor.start_link(children, strategy: :simple_one_for_one)\n\n log =\n capture_log(:info, fn ->\n {:ok, pid} = Supervisor.start_child(sup, [])\n catch_exit(GenServer.call(pid, :error))\n [] = Supervisor.which_children(sup)\n end)\n\n assert log =~ ~s(Start Call: Logger.TranslatorTest.WeirdFunctionNamesGenServer.\"start link\"\/?)\n assert_receive {:error, _pid, {Logger, [\"GenServer \" <> _ | _], _ts, server_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \" | _], _ts, child_metadata}}\n\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} = Keyword.get(server_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n after\n :code.purge(WeirdFunctionNamesGenServer)\n :code.delete(WeirdFunctionNamesGenServer)\n end\n\n def task(parent, fun \\\\ fn -> raise \"oops\" end) do\n mon = Process.monitor(parent)\n Process.unlink(parent)\n\n receive do\n :go ->\n fun.()\n\n {:DOWN, ^mon, _, _, _} ->\n exit(:shutdown)\n end\n end\n\n def sub_task(parent, fun \\\\ fn _ -> raise \"oops\" end) do\n mon = Process.monitor(parent)\n Process.unlink(parent)\n {:ok, pid} = Task.start_link(__MODULE__, :sleep, [self()])\n receive do: (:sleeping -> :ok)\n\n receive do\n :go ->\n fun.(pid)\n\n {:DOWN, ^mon, _, _, _} ->\n exit(:shutdown)\n end\n end\n\n def sleep(pid) do\n mon = Process.monitor(pid)\n send(pid, :sleeping)\n receive do: ({:DOWN, ^mon, _, _, _} -> exit(:shutdown))\n end\n\n def error(), do: {:error, :stop}\n\n def abnormal() do\n :proc_lib.start_link(__MODULE__, :abnormal_init, [])\n end\n\n def abnormal(:extra, :args) do\n :proc_lib.start_link(__MODULE__, :abnormal_init, [])\n end\n\n def abnormal_init() do\n Process.flag(:trap_exit, true)\n :proc_lib.init_ack({:ok, self()})\n receive do: ({:EXIT, _, _} -> exit(:stop))\n end\n\n defp worker(name, args, opts \\\\ []) do\n Enum.into(opts, %{id: name, start: {name, opts[:function] || :start_link, args}})\n end\nend\n","old_contents":"defmodule Logger.TranslatorTest do\n use Logger.Case\n\n defmodule MyGenServer do\n use GenServer\n\n def init(args) do\n {:ok, args}\n end\n\n def handle_cast(:error, _) do\n raise \"oops\"\n end\n\n def handle_call(:exit, _, _) do\n exit(:oops)\n end\n\n def handle_call(:error, _, _) do\n raise \"oops\"\n end\n\n def handle_call(:error_on_down, {pid, _}, _) do\n mon = Process.monitor(pid)\n assert_receive {:DOWN, ^mon, _, _, _}\n raise \"oops\"\n end\n end\n\n defmodule MyGenEvent do\n @behaviour :gen_event\n\n def init(args) do\n {:ok, args}\n end\n\n def handle_event(_event, state) do\n {:ok, state}\n end\n\n def handle_call(:error, _) do\n raise \"oops\"\n end\n\n def handle_info(_msg, state) do\n {:ok, state}\n end\n\n def code_change(_old_vsn, state, _extra) do\n {:ok, state}\n end\n\n def terminate(_reason, _state) do\n :ok\n end\n end\n\n defmodule MyBridge do\n @behaviour :supervisor_bridge\n\n def init(reason) do\n {:ok, pid} = Task.start_link(Kernel, :exit, [reason])\n {:ok, pid, pid}\n end\n\n def terminate(_reason, pid) do\n Process.exit(pid, :shutdown)\n end\n end\n\n setup_all do\n sasl_reports? = Application.get_env(:logger, :handle_sasl_reports, false)\n Application.put_env(:logger, :handle_sasl_reports, true)\n\n # Configure backend specific for tests to assert on metadata\n # We could rely exclusively on this backend and skip the console one\n # but using capture_log+console is desired as an integration test\n Logger.add_backend(Logger.TestBackend)\n\n # Restart the app but change the level before to avoid warnings\n level = Logger.level()\n Logger.configure(level: :error)\n Logger.App.stop()\n Application.start(:logger)\n Logger.configure(level: level)\n\n on_exit(fn ->\n Logger.remove_backend(Logger.TestBackend)\n Application.put_env(:logger, :handle_sasl_reports, sasl_reports?)\n Logger.App.stop()\n Application.start(:logger)\n end)\n end\n\n setup do\n Logger.configure_backend(Logger.TestBackend, callback_pid: self())\n end\n\n test \"translates GenServer crashes\" do\n {:ok, pid} = GenServer.start(MyGenServer, :ok)\n\n assert capture_log(:info, fn ->\n catch_exit(GenServer.call(pid, :error))\n end) =~ \"\"\"\n [error] GenServer #{inspect(pid)} terminating\n ** (RuntimeError) oops\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"GenServer \" <> _ | _], _ts, gen_server_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(gen_server_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates GenServer crashes with custom inspect options\" do\n {:ok, pid} = GenServer.start(MyGenServer, List.duplicate(:ok, 1000))\n Application.put_env(:logger, :translator_inspect_opts, limit: 3)\n\n assert capture_log(:debug, fn ->\n catch_exit(GenServer.call(pid, :error))\n end) =~ \"\"\"\n [:ok, :ok, :ok, ...]\n \"\"\"\n after\n Application.put_env(:logger, :translator_inspect_opts, [])\n end\n\n # TODO: Remove this check once we depend only on 20\n if :erlang.system_info(:otp_release) >= '20' do\n test \"translates GenServer crashes on debug\" do\n {:ok, pid} = GenServer.start(MyGenServer, :ok)\n\n assert capture_log(:debug, fn ->\n catch_exit(GenServer.call(pid, :error))\n end) =~ ~r\"\"\"\n \\[error\\] GenServer #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Last message \\(from #PID<\\d+\\.\\d+\\.\\d+>\\): :error\n State: :ok\n Client #PID<\\d+\\.\\d+\\.\\d+> is alive\n .*\n \"\"\"s\n\n assert_receive {:error, _pid,\n {Logger, [[\"GenServer \" <> _ | _] | _], _ts, gen_server_metadata}}\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(gen_server_metadata, :crash_reason)\n\n\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n\n test \"translates GenServer crashes with named client on debug\" do\n {:ok, pid} = GenServer.start(MyGenServer, :ok)\n\n assert capture_log(:debug, fn ->\n Process.register(self(), :named_client)\n catch_exit(GenServer.call(pid, :error))\n end) =~ ~r\"\"\"\n \\[error\\] GenServer #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Last message \\(from :named_client\\): :error\n State: :ok\n Client :named_client is alive\n .*\n \"\"\"s\n\n end\n\n test \"translates GenServer crashes with dead client on debug\" do\n {:ok, pid} = GenServer.start(MyGenServer, :ok)\n\n assert capture_log(:debug, fn ->\n mon = Process.monitor(pid)\n\n spawn_link(fn ->\n catch_exit(GenServer.call(pid, :error_on_down, 0))\n end)\n\n assert_receive {:DOWN, ^mon, _, _, _}\n end) =~ ~r\"\"\"\n \\[error\\] GenServer #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Last message \\(from #PID<\\d+\\.\\d+\\.\\d+>\\): :error_on_down\n State: :ok\n Client #PID<\\d+\\.\\d+\\.\\d+> is dead\n \"\"\"s\n\n end\n else\n test \"translates GenServer crashes on debug\" do\n {:ok, pid} = GenServer.start(MyGenServer, :ok)\n\n assert capture_log(:debug, fn ->\n catch_exit(GenServer.call(pid, :error))\n end) =~ ~r\"\"\"\n \\[error\\] GenServer #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Last message: :error\n State: :ok\n \"\"\"s\n\n assert_receive {:error, _pid,\n {Logger, [[\"GenServer \" <> _ | _] | _], _ts, gen_server_metadata}}\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(gen_server_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n end\n\n test \"translates GenServer crashes with no client\" do\n {:ok, pid} = GenServer.start(MyGenServer, :ok)\n\n assert capture_log(:debug, fn ->\n mon = Process.monitor(pid)\n GenServer.cast(pid, :error)\n assert_receive {:DOWN, ^mon, _, _, _}\n end) =~ ~r\"\"\"\n \\[error\\] GenServer #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Last message: {:\"\\$gen_cast\", :error}\n State: :ok\n \"\"\"s\n\n end\n\n test \"translates GenServer crashes with no client on debug\" do\n {:ok, pid} = GenServer.start(MyGenServer, :ok)\n\n refute capture_log(:debug, fn ->\n mon = Process.monitor(pid)\n GenServer.cast(pid, :error)\n assert_receive {:DOWN, ^mon, _, _, _}\n end) =~ \"Client\"\n\n assert_receive {:error, _pid,\n {Logger, [[\"GenServer \" <> _ | _] | _], _ts, gen_server_metadata}}\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n end\n\n test \"translates :gen_event crashes\" do\n {:ok, pid} = :gen_event.start()\n :ok = :gen_event.add_handler(pid, MyGenEvent, :ok)\n\n assert capture_log(:info, fn ->\n :gen_event.call(pid, MyGenEvent, :error)\n end) =~ \"\"\"\n [error] :gen_event handler Logger.TranslatorTest.MyGenEvent installed in #{\n inspect(pid)\n } terminating\n ** (RuntimeError) oops\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\":gen_event handler \" <> _ | _], _ts, metadata}}\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} = Keyword.get(metadata, :crash_reason)\n end\n\n test \"translates :gen_event crashes on debug\" do\n {:ok, pid} = :gen_event.start()\n :ok = :gen_event.add_handler(pid, MyGenEvent, :ok)\n\n assert capture_log(:debug, fn ->\n :gen_event.call(pid, MyGenEvent, :error)\n end) =~ ~r\"\"\"\n \\[error\\] :gen_event handler Logger.TranslatorTest.MyGenEvent installed in #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Last message: :error\n State: :ok\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [[\":gen_event handler \" <> _ | _] | _], _ts, metadata}}\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} = Keyword.get(metadata, :crash_reason)\n end\n\n test \"translates Task crashes\" do\n {:ok, pid} = Task.start_link(__MODULE__, :task, [self()])\n\n assert capture_log(fn ->\n ref = Process.monitor(pid)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[error\\] Task #PID<\\d+\\.\\d+\\.\\d+> started from #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Function: &Logger.TranslatorTest.task\\\/1\n Args: \\[#PID<\\d+\\.\\d+\\.\\d+>\\]\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} = Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Task async_stream crashes with neighbour\" do\n fun = fn -> Task.async_stream([:oops], :erlang, :error, []) |> Enum.to_list() end\n {:ok, pid} = Task.start(__MODULE__, :task, [self(), fun])\n\n assert capture_log(:debug, fn ->\n ref = Process.monitor(pid)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n Neighbours:\n #{inspect(pid)}\n Initial Call: Logger\\.TranslatorTest\\.task\/2\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert {:oops, [_ | _]} = Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%ErlangError{original: :oops}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Task undef module crash\" do\n assert capture_log(fn ->\n {:ok, pid} = Task.start(:module_does_not_exist, :undef, [])\n ref = Process.monitor(pid)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[error\\] Task #PID<\\d+\\.\\d+\\.\\d+> started from #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(UndefinedFunctionError\\) function :module_does_not_exist.undef\/0 is undefined \\(module :module_does_not_exist is not available\\)\n .*\n Function: &:module_does_not_exist.undef\/0\n Args: \\[\\]\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n assert {%UndefinedFunctionError{function: :undef}, [_ | _]} =\n Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%UndefinedFunctionError{function: :undef}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Task undef function crash\" do\n assert capture_log(fn ->\n {:ok, pid} = Task.start(__MODULE__, :undef, [])\n ref = Process.monitor(pid)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[error\\] Task #PID<\\d+\\.\\d+\\.\\d+> started from #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(UndefinedFunctionError\\) function Logger.TranslatorTest.undef\/0 is undefined or private\n .*\n Function: &Logger.TranslatorTest.undef\/0\n Args: \\[\\]\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n assert {%UndefinedFunctionError{function: :undef}, [_ | _]} =\n Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%UndefinedFunctionError{function: :undef}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Task raising ErlangError\" do\n assert capture_log(fn ->\n exception =\n try do\n :erlang.error(:foo)\n rescue\n x ->\n x\n end\n\n {:ok, pid} = Task.start(:erlang, :error, [exception])\n ref = Process.monitor(pid)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[error\\] Task #PID<\\d+\\.\\d+\\.\\d+> started from #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(ErlangError\\) Erlang error: :foo\n .*\n Function: &:erlang\\.error\/1\n Args: \\[%ErlangError{.*}\\]\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert {%ErlangError{original: :foo}, [_ | _]} = Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%ErlangError{original: :foo}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Task raising Erlang badarg error\" do\n assert capture_log(fn ->\n {:ok, pid} = Task.start(:erlang, :error, [:badarg])\n ref = Process.monitor(pid)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[error\\] Task #PID<\\d+\\.\\d+\\.\\d+> started from #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(ArgumentError\\) argument error\n .*\n Function: &:erlang\\.error\/1\n Args: \\[:badarg\\]\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n assert {%ArgumentError{message: \"argument error\"}, [_ | _]} =\n Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%ArgumentError{message: \"argument error\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Task exiting abnormally\" do\n assert capture_log(fn ->\n {:ok, pid} = Task.start(:erlang, :exit, [:abnormal])\n ref = Process.monitor(pid)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[error\\] Task #PID<\\d+\\.\\d+\\.\\d+> started from #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(stop\\) :abnormal\n .*\n Function: &:erlang\\.exit\/1\n Args: \\[:abnormal\\]\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert {:abnormal, [_ | _]} = Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:abnormal, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates application start\" do\n assert capture_log(fn ->\n Application.start(:eex)\n Application.stop(:eex)\n end) =~ \"\"\"\n Application eex started at #{inspect(node())}\n \"\"\"\n end\n\n test \"translates application stop\" do\n assert capture_log(fn ->\n :ok = Application.start(:eex)\n Application.stop(:eex)\n end) =~ \"\"\"\n Application eex exited: :stopped\n \"\"\"\n end\n\n test \"translates bare process crashes\" do\n assert capture_log(:info, fn ->\n {_, ref} = spawn_monitor(fn -> raise \"oops\" end)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n # Even though the monitor has been received the emulator may not have\n # sent the message to the error logger\n Process.sleep(200)\n end) =~ ~r\"\"\"\n \\[error\\] Process #PID<\\d+\\.\\d+\\.\\d+>\\ raised an exception\n \\*\\* \\(RuntimeError\\) oops\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates :proc_lib crashes\" do\n fun = fn ->\n Logger.metadata(foo: :bar)\n raise \"oops\"\n end\n\n pid = :proc_lib.spawn_link(__MODULE__, :task, [self(), fun])\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[error\\] Process #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Initial Call: Logger.TranslatorTest.task\/2\n Ancestors: \\[#PID<\\d+\\.\\d+\\.\\d+>\\]\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n assert Keyword.get(process_metadata, :foo) == :bar\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\ntest \"skips :proc_lib crashes with disabled metadata\" do\n fun = fn ->\n Logger.disable(self())\n raise \"oops\"\n end\n\n pid = :proc_lib.spawn_link(__MODULE__, :task, [self(), fun])\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) == \"\"\n end\n\n test \"translates :proc_lib crashes with name\" do\n fun = fn ->\n Process.register(self(), __MODULE__)\n raise \"oops\"\n end\n\n pid = :proc_lib.spawn_link(__MODULE__, :task, [self(), fun])\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n send(pid, :message)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[error\\] Process Logger.TranslatorTest \\(#PID<\\d+\\.\\d+\\.\\d+>\\) terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Initial Call: Logger.TranslatorTest.task\/2\n Ancestors: \\[#PID<\\d+\\.\\d+\\.\\d+>\\]\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates :proc_lib crashes without initial call\" do\n fun = fn ->\n Process.delete(:\"$initial_call\")\n raise \"oops\"\n end\n\n pid = :proc_lib.spawn_link(__MODULE__, :task, [self(), fun])\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n send(pid, :message)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[error\\] Process #PID<\\d+\\.\\d+\\.\\d+> terminating\n \\*\\* \\(RuntimeError\\) oops\n .*\n Ancestors: \\[#PID<\\d+\\.\\d+\\.\\d+>\\]\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates :proc_lib crashes with neighbour\" do\n {:ok, pid} = Task.start_link(__MODULE__, :sub_task, [self()])\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n send(pid, :message)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n Ancestors: \\[#PID<\\d+\\.\\d+\\.\\d+>\\]\n Neighbours:\n #PID<\\d+\\.\\d+\\.\\d+>\n Initial Call: Logger.TranslatorTest.sleep\/1\n Current Call: Logger.TranslatorTest.sleep\/1\n Ancestors: \\[#PID<\\d+\\.\\d+\\.\\d+>, #PID<\\d+\\.\\d+\\.\\d+>\\]\n \"\"\"\n end\n\n test \"translates :proc_lib crashes with neighbour with name\" do\n fun = fn pid2 ->\n Process.register(pid2, __MODULE__)\n raise \"oops\"\n end\n\n {:ok, pid} = Task.start_link(__MODULE__, :sub_task, [self(), fun])\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n send(pid, :message)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n Ancestors: \\[#PID<\\d+\\.\\d+\\.\\d+>\\]\n Neighbours:\n Logger.TranslatorTest \\(#PID<\\d+\\.\\d+\\.\\d+>\\)\n Initial Call: Logger.TranslatorTest.sleep\/1\n Current Call: Logger.TranslatorTest.sleep\/1\n Ancestors: \\[#PID<\\d+\\.\\d+\\.\\d+>, #PID<\\d+\\.\\d+\\.\\d+>\\]\n \"\"\"\n end\n\n test \"translates :proc_lib crashes on debug\" do\n {:ok, pid} = Task.start_link(__MODULE__, :task, [self()])\n\n assert capture_log(:debug, fn ->\n ref = Process.monitor(pid)\n send(pid, :message)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n Ancestors: \\[#PID<\\d+\\.\\d+\\.\\d+>\\](?:\n Message Queue Length: 1(?#TODO: Require once depend on Erlang\/OTP 20)|)\n Messages: \\[:message\\]\n Links: \\[\\]\n Dictionary: \\[\\]\n Trapping Exits: false\n Status: :running\n Heap Size: \\d+\n Stack Size: \\d+\n Reductions: \\d+\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} = Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates :proc_lib crashes with neighbour on debug\" do\n {:ok, pid} = Task.start_link(__MODULE__, :sub_task, [self()])\n\n assert capture_log(:debug, fn ->\n ref = Process.monitor(pid)\n send(pid, :message)\n send(pid, :go)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n Ancestors: \\[#PID<\\d+\\.\\d+\\.\\d+>, #PID<\\d+\\.\\d+\\.\\d+>\\](?:\n Message Queue Length: 0|\n Messages: \\[\\](?# TODO: Remove once depend on 20))\n Links: \\[#PID<\\d+\\.\\d+\\.\\d+>\\](?:|\n Dictionary: \\[\\](?# TODO: Remove once depend on 20))\n Trapping Exits: false\n Status: :waiting\n Heap Size: \\d+\n Stack Size: \\d+\n Reductions: \\d+(?:\n Current Stacktrace:\n test\/logger\/translator_test.exs:\\d+: Logger.TranslatorTest.sleep\/1(?#TODO: Require once depend on Erlang\/OTP 20)|)\n \"\"\"\n end\n\n test \"translates Supervisor progress\" do\n {:ok, pid} = Supervisor.start_link([], strategy: :one_for_one)\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n Supervisor.start_child(pid, worker(Task, [__MODULE__, :sleep, [self()]]))\n Process.exit(pid, :normal)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[info\\] Child Task of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Supervisor\\.Default\\) started\n Pid: #PID<\\d+\\.\\d+\\.\\d+>\n Start Call: Task.start_link\\(Logger.TranslatorTest, :sleep, \\[#PID<\\d+\\.\\d+\\.\\d+>\\]\\)\n \"\"\"\n end\n\n test \"translates Supervisor progress with name\" do\n {:ok, pid} = Supervisor.start_link([], strategy: :one_for_one, name: __MODULE__)\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n Supervisor.start_child(pid, worker(Task, [__MODULE__, :sleep, [self()]]))\n Process.exit(pid, :normal)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[info\\] Child Task of Supervisor Logger.TranslatorTest started\n \"\"\"\n\n {:ok, pid} = Supervisor.start_link([], strategy: :one_for_one, name: {:global, __MODULE__})\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n Supervisor.start_child(pid, worker(Task, [__MODULE__, :sleep, [self()]]))\n Process.exit(pid, :normal)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[info\\] Child Task of Supervisor Logger.TranslatorTest started\n \"\"\"\n\n {:ok, pid} =\n Supervisor.start_link([], strategy: :one_for_one, name: {:via, :global, __MODULE__})\n\n assert capture_log(:info, fn ->\n ref = Process.monitor(pid)\n Supervisor.start_child(pid, worker(Task, [__MODULE__, :sleep, [self()]]))\n Process.exit(pid, :normal)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n \\[info\\] Child Task of Supervisor Logger.TranslatorTest started\n \"\"\"\n end\n\n test \"translates Supervisor progress on debug\" do\n {:ok, pid} = Supervisor.start_link([], strategy: :one_for_one)\n\n assert capture_log(:debug, fn ->\n ref = Process.monitor(pid)\n Supervisor.start_child(pid, worker(Task, [__MODULE__, :sleep, [self()]]))\n Process.exit(pid, :normal)\n receive do: ({:DOWN, ^ref, _, _, _} -> :ok)\n end) =~ ~r\"\"\"\n Start Call: Task.start_link\\(Logger.TranslatorTest, :sleep, \\[#PID<\\d+\\.\\d+\\.\\d+>\\]\\)\n Restart: :permanent\n Shutdown: 5000\n Type: :worker\n \"\"\"\n end\n\n test \"translates Supervisor reports start error\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n children = [worker(__MODULE__, [], function: :error)]\n Supervisor.start_link(children, strategy: :one_for_one)\n receive do: ({:EXIT, _, {:shutdown, {:failed_to_start_child, _, _}}} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[error\\] Child Logger.TranslatorTest of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Supervisor\\.Default\\) failed to start\n \\*\\* \\(exit\\) :stop\n Start Call: Logger.TranslatorTest.error\\(\\)\n \"\"\"\n end\n\n test \"translates Supervisor reports start error with raise\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n children = [worker(__MODULE__, [], function: :undef)]\n Supervisor.start_link(children, strategy: :one_for_one)\n receive do: ({:EXIT, _, {:shutdown, {:failed_to_start_child, _, _}}} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[error\\] Child Logger.TranslatorTest of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Supervisor\\.Default\\) failed to start\n \\*\\* \\(exit\\) an exception was raised:\n \\*\\* \\(UndefinedFunctionError\\) function Logger.TranslatorTest.undef\/0 is undefined or private\n .*\n Start Call: Logger.TranslatorTest.undef\\(\\)\n \"\"\"s\n\n assert_receive {:error, _pid, {Logger, [\"Child \" | _], _ts, _child_metadata}}\n end\n\n test \"translates Supervisor reports terminated\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n children = [worker(Task, [Kernel, :exit, [:stop]])]\n {:ok, pid} = Supervisor.start_link(children, strategy: :one_for_one, max_restarts: 0)\n receive do: ({:EXIT, ^pid, _} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[error\\] Child Task of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Supervisor\\.Default\\) terminated\n \\*\\* \\(exit\\) :stop\n Pid: #PID<\\d+\\.\\d+\\.\\d+>\n Start Call: Task.start_link\\(Kernel, :exit, \\[:stop\\]\\)\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \" | _], _ts, _child_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \", \"Task\" | _], _ts, _child_task_metadata}}\n assert {:stop, [_ | _]} = Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:stop, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Supervisor reports max restarts shutdown\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n children = [worker(Task, [Kernel, :exit, [:stop]])]\n {:ok, pid} = Supervisor.start_link(children, strategy: :one_for_one, max_restarts: 0)\n receive do: ({:EXIT, ^pid, _} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[error\\] Child Task of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Supervisor\\.Default\\) caused shutdown\n \\*\\* \\(exit\\) :reached_max_restart_intensity\n Start Call: Task.start_link\\(Kernel, :exit, \\[:stop\\]\\)\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \" | _], _ts, _child_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \", \"Task\" | _], _ts, _child_task_metadata}}\n assert {:stop, [_ | _]} = Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:stop, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Supervisor reports abnormal shutdown\" do\n assert capture_log(:info, fn ->\n children = [worker(__MODULE__, [], function: :abnormal)]\n {:ok, pid} = Supervisor.start_link(children, strategy: :one_for_one)\n :ok = Supervisor.terminate_child(pid, __MODULE__)\n end) =~ ~r\"\"\"\n \\[error\\] Child Logger.TranslatorTest of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Supervisor\\.Default\\) shutdown abnormally\n \\*\\* \\(exit\\) :stop\n Pid: #PID<\\d+\\.\\d+\\.\\d+>\n Start Call: Logger.TranslatorTest.abnormal\\(\\)\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \" | _], _ts, _child_metadata}}\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:stop, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Supervisor reports abnormal shutdown on debug\" do\n assert capture_log(:debug, fn ->\n children = [\n worker(__MODULE__, [], function: :abnormal, restart: :permanent, shutdown: 5000)\n ]\n\n {:ok, pid} = Supervisor.start_link(children, strategy: :one_for_one)\n :ok = Supervisor.terminate_child(pid, __MODULE__)\n end) =~ ~r\"\"\"\n \\*\\* \\(exit\\) :stop\n Pid: #PID<\\d+\\.\\d+\\.\\d+>\n Start Call: Logger.TranslatorTest.abnormal\\(\\)\n Restart: :permanent\n Shutdown: 5000\n Type: :worker\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \" | _], _ts, _child_metadata}}\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:stop, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates Supervisor reports abnormal shutdown in simple_one_for_one\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n children = [worker(__MODULE__, [], function: :abnormal)]\n {:ok, pid} = Supervisor.start_link(children, strategy: :simple_one_for_one)\n {:ok, _pid2} = Supervisor.start_child(pid, [])\n Process.exit(pid, :normal)\n receive do: ({:EXIT, ^pid, _} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[error\\] Children Logger.TranslatorTest of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Supervisor\\.Default\\) shutdown abnormally\n \\*\\* \\(exit\\) :stop\n Number: 1\n Start Call: Logger.TranslatorTest.abnormal\\(\\)\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Children \" | _], _ts, _children_metadata}}\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:stop, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates DynamicSupervisor reports abnormal shutdown\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n child = %{id: __MODULE__, start: {__MODULE__, :abnormal, []}}\n {:ok, pid} = DynamicSupervisor.start_link(strategy: :one_for_one)\n {:ok, _pid2} = DynamicSupervisor.start_child(pid, child)\n Process.exit(pid, :normal)\n receive do: ({:EXIT, ^pid, _} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[error\\] Child :undefined of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Supervisor\\.Default\\) shutdown abnormally\n \\*\\* \\(exit\\) :stop\n Pid: #PID<\\d+\\.\\d+\\.\\d+>\n Start Call: Logger.TranslatorTest.abnormal\\(\\)\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \" | _], _ts, child_metadata}}\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:stop, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates DynamicSupervisor reports abnormal shutdown including extra_arguments\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n\n {:ok, pid} =\n DynamicSupervisor.start_link(strategy: :one_for_one, extra_arguments: [:extra])\n\n child = %{id: __MODULE__, start: {__MODULE__, :abnormal, [:args]}}\n {:ok, _pid2} = DynamicSupervisor.start_child(pid, child)\n Process.exit(pid, :normal)\n receive do: ({:EXIT, ^pid, _} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[error\\] Child :undefined of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Supervisor\\.Default\\) shutdown abnormally\n \\*\\* \\(exit\\) :stop\n Pid: #PID<\\d+\\.\\d+\\.\\d+>\n Start Call: Logger.TranslatorTest.abnormal\\(:extra, :args\\)\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \" | _], _ts, _child_metadata}}\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:stop, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates named DynamicSupervisor reports abnormal shutdown\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n child = %{id: __MODULE__, start: {__MODULE__, :abnormal, []}}\n {:ok, pid} = DynamicSupervisor.start_link(strategy: :one_for_one, name: __MODULE__)\n {:ok, _pid2} = DynamicSupervisor.start_child(pid, child)\n Process.exit(pid, :normal)\n receive do: ({:EXIT, ^pid, _} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[error\\] Child :undefined of Supervisor Logger.TranslatorTest shutdown abnormally\n \\*\\* \\(exit\\) :stop\n Pid: #PID<\\d+\\.\\d+\\.\\d+>\n Start Call: Logger.TranslatorTest.abnormal\\(\\)\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \" | _], _ts, _child_metadata}}\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:stop, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"translates :supervisor_bridge progress\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n {:ok, pid} = :supervisor_bridge.start_link(MyBridge, :normal)\n receive do: ({:EXIT, ^pid, _} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[info\\] Child of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Logger\\.TranslatorTest\\.MyBridge\\) started\n Pid: #PID<\\d+\\.\\d+\\.\\d+>\n Start Call: Logger.TranslatorTest.MyBridge.init\\(:normal\\)\n \"\"\"\n end\n\n test \"translates :supervisor_bridge reports\" do\n assert capture_log(:info, fn ->\n trap = Process.flag(:trap_exit, true)\n {:ok, pid} = :supervisor_bridge.start_link(MyBridge, :stop)\n receive do: ({:EXIT, ^pid, _} -> :ok)\n Process.flag(:trap_exit, trap)\n end) =~ ~r\"\"\"\n \\[error\\] Child of Supervisor #PID<\\d+\\.\\d+\\.\\d+> \\(Logger\\.TranslatorTest\\.MyBridge\\) terminated\n \\*\\* \\(exit\\) :stop\n Pid: #PID<\\d+\\.\\d+\\.\\d+>\n Start Module: Logger.TranslatorTest.MyBridge\n \"\"\"\n\n assert_receive {:error, _pid, {Logger, [\"Task \" <> _ | _], _ts, task_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child of Supervisor \" | _], _ts, _child_metadata}}\n\n assert {:stop, [_ | _]} = Keyword.get(task_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {:stop, [_ | _]} = Keyword.get(process_metadata, :crash_reason)\n end\n end\n\n test \"reports :undefined MFA properly\" do\n defmodule WeirdFunctionNamesGenServer do\n use GenServer\n\n def unquote(:\"start link\")(), do: GenServer.start_link(__MODULE__, [])\n def init(args), do: {:ok, args}\n def handle_call(_call, _from, _state), do: raise(\"oops\")\n end\n\n child_opts = [restart: :temporary, function: :\"start link\"]\n children = [worker(WeirdFunctionNamesGenServer, [], child_opts)]\n {:ok, sup} = Supervisor.start_link(children, strategy: :simple_one_for_one)\n\n log =\n capture_log(:info, fn ->\n {:ok, pid} = Supervisor.start_child(sup, [])\n catch_exit(GenServer.call(pid, :error))\n [] = Supervisor.which_children(sup)\n end)\n\n assert log =~ ~s(Start Call: Logger.TranslatorTest.WeirdFunctionNamesGenServer.\"start link\"\/?)\n assert_receive {:error, _pid, {Logger, [\"GenServer \" <> _ | _], _ts, server_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Process \" | _], _ts, process_metadata}}\n assert_receive {:error, _pid, {Logger, [\"Child \" | _], _ts, child_metadata}}\n\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} = Keyword.get(server_metadata, :crash_reason)\n\n if :erlang.system_info(:otp_release) >= '20' do\n assert {%RuntimeError{message: \"oops\"}, [_ | _]} =\n Keyword.get(process_metadata, :crash_reason)\n end\n after\n :code.purge(WeirdFunctionNamesGenServer)\n :code.delete(WeirdFunctionNamesGenServer)\n end\n\n def task(parent, fun \\\\ fn -> raise \"oops\" end) do\n mon = Process.monitor(parent)\n Process.unlink(parent)\n\n receive do\n :go ->\n fun.()\n\n {:DOWN, ^mon, _, _, _} ->\n exit(:shutdown)\n end\n end\n\n def sub_task(parent, fun \\\\ fn _ -> raise \"oops\" end) do\n mon = Process.monitor(parent)\n Process.unlink(parent)\n {:ok, pid} = Task.start_link(__MODULE__, :sleep, [self()])\n receive do: (:sleeping -> :ok)\n\n receive do\n :go ->\n fun.(pid)\n\n {:DOWN, ^mon, _, _, _} ->\n exit(:shutdown)\n end\n end\n\n def sleep(pid) do\n mon = Process.monitor(pid)\n send(pid, :sleeping)\n receive do: ({:DOWN, ^mon, _, _, _} -> exit(:shutdown))\n end\n\n def error(), do: {:error, :stop}\n\n def abnormal() do\n :proc_lib.start_link(__MODULE__, :abnormal_init, [])\n end\n\n def abnormal(:extra, :args) do\n :proc_lib.start_link(__MODULE__, :abnormal_init, [])\n end\n\n def abnormal_init() do\n Process.flag(:trap_exit, true)\n :proc_lib.init_ack({:ok, self()})\n receive do: ({:EXIT, _, _} -> exit(:stop))\n end\n\n defp worker(name, args, opts \\\\ []) do\n Enum.into(opts, %{id: name, start: {name, opts[:function] || :start_link, args}})\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"449eb88290651686d7d36172be1c6c0ed867518a","subject":"Make feature spec more readable","message":"Make feature spec more readable\n","repos":"stride-nyc\/remote_retro,stride-nyc\/remote_retro,stride-nyc\/remote_retro","old_file":"test\/features\/grouping_stage_test.exs","new_file":"test\/features\/grouping_stage_test.exs","new_contents":"defmodule GroupingStageTest do\n use RemoteRetro.IntegrationCase, async: false\n alias RemoteRetro.Idea\n\n import ShorterMaps\n describe \"ideas in the grouping stage\" do\n setup [:persist_ideas_for_retro]\n\n @tag [\n retro_stage: \"grouping\",\n ideas: [%Idea{category: \"sad\", body: \"splinters in the codebase\", x: 105.5, y: 100.1}],\n ]\n\n test \"appear on the interface with coordinates mapped to transforms\", ~M{retro, session} do\n retro_path = \"\/retros\/\" <> retro.id\n session = visit(session, retro_path)\n\n idea_coordinates = parse_transform_coordinates_for_card(session, \"splinters in the codebase\")\n\n assert %{\"x\" => \"105.5\", \"y\" => \"100.1\"} = idea_coordinates\n end\n\n @tag [\n retro_stage: \"grouping\",\n ideas: [%Idea{category: \"sad\", body: \"rampant sickness\", x: 80.5, y: 300.3}],\n ]\n test \"can be drag-and-dropped on one client and have their position update across all clients\", ~M{retro, session, non_facilitator} do\n retro_path = \"\/retros\/\" <> retro.id\n session_one = visit(session, retro_path)\n\n session_two = new_authenticated_browser_session(non_facilitator)\n session_two = visit(session_two, retro_path)\n\n idea_coordinates_before =\n session_two\n |> parse_transform_coordinates_for_card(\"rampant sickness\")\n\n drag_idea(session_one, \"rampant sickness\", to_center_of: \".grouping-board\")\n\n idea_coordinates_after =\n session_two\n |> parse_transform_coordinates_for_card(\"rampant sickness\")\n\n refute idea_coordinates_before == idea_coordinates_after\n end\n\n @tag [\n retro_stage: \"grouping\",\n ideas: [\n %Idea{category: \"sad\", body: \"rampant sickness\", x: 0.0, y: 200.0},\n %Idea{category: \"sad\", body: \"getting sickness\", x: 10.0, y: 210.0},\n ],\n ]\n test \"ideas dynamically remove bolding when out of proximity\", ~M{retro, session} do\n retro_path = \"\/retros\/\" <> retro.id\n session = visit(session, retro_path)\n\n session |> assert_count_of_emboldened_ideas_to_be(2)\n\n session |> drag_idea(\"rampant sickness\", to_center_of: \".grouping-board\")\n\n session |> assert_count_of_emboldened_ideas_to_be(0)\n end\n\n @tag [\n retro_stage: \"grouping\",\n ideas: [\n %Idea{category: \"sad\", body: \"rampant sickness\", x: 0.0, y: 200.0},\n %Idea{category: \"sad\", body: \"getting sickness\", x: 10.0, y: 210.0},\n ],\n ]\n test \"ideas can be visible in contrast mode\", ~M{retro, session} do\n retro_path = \"\/retros\/\" <> retro.id\n session = visit(session, retro_path)\n\n click(session, Query.css(\"button\", text: \"Turn High Contrast On\"))\n\n assert_count_of_high_contrast_color_borders_is(session, 2)\n\n click(session, Query.css(\"button\", text: \"Turn High Contrast Off\"))\n\n assert_count_of_high_contrast_color_borders_is(session, 0)\n end\n end\n\n defp parse_transform_coordinates_for_card(session, idea_text) do\n inline_style_string =\n find(session, Query.css(\"p\", text: idea_text))\n |> Wallaby.Element.attr(\"style\")\n\n ~r\/transform: translate\\((?.*)px,\\s?(?.*)px\\)\/\n |> Regex.named_captures(inline_style_string)\n end\n\n defp assert_count_of_emboldened_ideas_to_be(session, count) do\n assert_has(session, Query.xpath(\"\/\/p[contains(@style, 'box-shadow')]\", count: count))\n end\n\n def assert_count_of_high_contrast_color_borders_is(session, count) do\n assert_has(session, Query.xpath(\"\/\/p[contains(@style, 'box-shadow: rgb(0, 0, 0)')]\", count: count))\n end\nend\n","old_contents":"defmodule GroupingStageTest do\n use RemoteRetro.IntegrationCase, async: false\n alias RemoteRetro.Idea\n\n import ShorterMaps\n describe \"ideas in the grouping stage\" do\n setup [:persist_ideas_for_retro]\n\n @tag [\n retro_stage: \"grouping\",\n ideas: [%Idea{category: \"sad\", body: \"splinters in the codebase\", x: 105.5, y: 100.1}],\n ]\n\n test \"appear on the interface with coordinates mapped to transforms\", ~M{retro, session} do\n retro_path = \"\/retros\/\" <> retro.id\n session = visit(session, retro_path)\n\n idea_coordinates = parse_transform_coordinates_for_card(session, \"splinters in the codebase\")\n\n assert %{\"x\" => \"105.5\", \"y\" => \"100.1\"} = idea_coordinates\n end\n\n @tag [\n retro_stage: \"grouping\",\n ideas: [%Idea{category: \"sad\", body: \"rampant sickness\", x: 80.5, y: 300.3}],\n ]\n test \"can be drag-and-dropped on one client and have their position update across all clients\", ~M{retro, session, non_facilitator} do\n retro_path = \"\/retros\/\" <> retro.id\n session_one = visit(session, retro_path)\n\n session_two = new_authenticated_browser_session(non_facilitator)\n session_two = visit(session_two, retro_path)\n\n idea_coordinates_before =\n session_two\n |> parse_transform_coordinates_for_card(\"rampant sickness\")\n\n drag_idea(session_one, \"rampant sickness\", to_center_of: \".grouping-board\")\n\n idea_coordinates_after =\n session_two\n |> parse_transform_coordinates_for_card(\"rampant sickness\")\n\n refute idea_coordinates_before == idea_coordinates_after\n end\n\n @tag [\n retro_stage: \"grouping\",\n ideas: [\n %Idea{category: \"sad\", body: \"rampant sickness\", x: 0.0, y: 200.0},\n %Idea{category: \"sad\", body: \"getting sickness\", x: 10.0, y: 210.0},\n ],\n ]\n test \"ideas dynamically remove bolding when out of proximity\", ~M{retro, session} do\n retro_path = \"\/retros\/\" <> retro.id\n session = visit(session, retro_path)\n\n session |> assert_count_of_emboldened_ideas_to_be(2)\n\n session |> drag_idea(\"rampant sickness\", to_center_of: \".grouping-board\")\n\n session |> assert_count_of_emboldened_ideas_to_be(0)\n end\n\n @tag [\n retro_stage: \"grouping\",\n ideas: [\n %Idea{category: \"sad\", body: \"rampant sickness\", x: 0.0, y: 200.0},\n %Idea{category: \"sad\", body: \"getting sickness\", x: 10.0, y: 210.0},\n ],\n ]\n test \"ideas can be visible in contrast mode\", ~M{retro, session} do\n retro_path = \"\/retros\/\" <> retro.id\n session = visit(session, retro_path)\n\n click(session, Query.css(\"button\", text: \"Turn High Contrast On\"))\n\n assert_has(session, Query.xpath(\"\/\/p[contains(@style, 'box-shadow: rgb(0, 0, 0)')]\", count: 2))\n\n click(session, Query.css(\"button\", text: \"Turn High Contrast Off\"))\n\n assert_has(session, Query.xpath(\"\/\/p[contains(@style, 'box-shadow: rgb(0, 0, 0)')]\", count: 0))\n end\n end\n\n defp parse_transform_coordinates_for_card(session, idea_text) do\n inline_style_string =\n find(session, Query.css(\"p\", text: idea_text))\n |> Wallaby.Element.attr(\"style\")\n\n ~r\/transform: translate\\((?.*)px,\\s?(?.*)px\\)\/\n |> Regex.named_captures(inline_style_string)\n end\n\n defp assert_count_of_emboldened_ideas_to_be(session, count) do\n assert_has(session, Query.xpath(\"\/\/p[contains(@style, 'box-shadow')]\", count: count))\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"4e957136e9d1a176e9e706714d02185ba13f1f28","subject":"fixed error when save message","message":"fixed error when save message","repos":"erickgnavar\/issue_reporter,erickgnavar\/issue_reporter","old_file":"web\/models\/issue.ex","new_file":"web\/models\/issue.ex","new_contents":"defmodule IssueReporter.Issue do\n use IssueReporter.Web, :model\n\n schema \"issues\" do\n field :type, :string\n field :latitude, :float\n field :longitude, :float\n field :fixed, :boolean, default: false\n field :message, :string\n\n timestamps\n end\n\n @required_fields ~w(type latitude longitude fixed)\n @optional_fields ~w(message)\n\n @doc \"\"\"\n Creates a changeset based on the `model` and `params`.\n\n If no params are provided, an invalid changeset is returned\n with no validation performed.\n \"\"\"\n def changeset(model, params \\\\ :empty) do\n model\n |> cast(params, @required_fields, @optional_fields)\n end\nend\n","old_contents":"defmodule IssueReporter.Issue do\n use IssueReporter.Web, :model\n\n schema \"issues\" do\n field :type, :string\n field :latitude, :float\n field :longitude, :float\n field :fixed, :boolean, default: false\n field :message, :string\n\n timestamps\n end\n\n @required_fields ~w(type latitude longitude fixed)\n @optional_fields ~w()\n\n @doc \"\"\"\n Creates a changeset based on the `model` and `params`.\n\n If no params are provided, an invalid changeset is returned\n with no validation performed.\n \"\"\"\n def changeset(model, params \\\\ :empty) do\n model\n |> cast(params, @required_fields, @optional_fields)\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"9750489b59afe0b89a084caae4a9708ba1bc4a5b","subject":"change logger times","message":"change logger times\n","repos":"FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os","old_file":"lib\/logger\/backends\/farmbot_logger.ex","new_file":"lib\/logger\/backends\/farmbot_logger.ex","new_contents":"defmodule Logger.Backends.FarmbotLogger do\n @moduledoc \"\"\"\n Logger backend for logging to the frontend and dumping to the API.\n Takes messages that were logged useing Logger, if they can be\n jsonified, adds them too a buffer, when that buffer hits a certain\n size, it tries to dump the messages onto the API.\n \"\"\"\n alias Farmbot.Sync\n alias Farmbot.HTTP\n use GenEvent\n require Logger\n use Farmbot.DebugLog\n @save_path Application.get_env(:farmbot, :path) <> \"\/logs.txt\"\n\n # ten megs. i promise\n @max_file_size 1.0e+7\n @filtered \"[FILTERED]\"\n\n @typedoc \"\"\"\n The state of the logger\n \"\"\"\n @type state :: %{logs: [log_message], posting: boolean}\n\n @typedoc \"\"\"\n Type of message for ticker\n \"\"\"\n @type rpc_log_type\n :: :success\n | :busy\n | :warn\n | :error\n | :info\n | :fun\n\n @typedoc \"\"\"\n Elixir Logger level type\n \"\"\"\n @type logger_level\n :: :info\n | :debug\n | :warn\n | :error\n\n @typedoc \"\"\"\n One day this will me more\n \"\"\"\n @type channel :: :toast\n\n @type log_message\n :: %{message: String.t,\n channels: [channel],\n created_at: integer,\n meta: %{type: rpc_log_type}}\n\n def init(_), do: {:ok, %{logs: [], posting: false}}\n\n # The example said ignore messages for other nodes, so im ignoring messages\n # for other nodes.\n def handle_event({_, gl, {Logger, _, _, _}}, state) when node(gl) != node() do\n {:ok, state}\n end\n\n # The logger event.\n def handle_event({level, _, {Logger, message, timestamp, metadata}}, state) do\n # if there is type key in the meta we need that to have priority\n type = Keyword.get(metadata, :type, level)\n channels = Keyword.get(metadata, :channels, [])\n created_at = parse_created_at(timestamp)\n san_m = sanitize(message, metadata)\n log = build_log(san_m, created_at, type, channels)\n :ok = GenServer.cast(Farmbot.Transport, {:log, log})\n logs = [log | state.logs]\n if !state.posting and Enum.count(logs) >= 50 do\n # If not already posting, and more than 50 messages\n spawn fn ->\n filterd_logs = Enum.filter(logs, fn(log) ->\n log.message != @filtered\n end)\n do_post(filterd_logs)\n end\n {:ok, %{state | logs: logs, posting: true}}\n else\n {:ok, %{state | logs: logs}}\n end\n end\n\n def handle_event(:flush, _state), do: {:ok, %{logs: [], posting: false}}\n\n def handle_call(:post_success, state) do\n debug_log \"Logs uploaded!\"\n write_file(Enum.reverse(state.logs))\n {:ok, :ok, %{state | posting: false, logs: []}}\n end\n\n def handle_call(:post_fail, state) do\n debug_log \"Logs failed to upload!\"\n {:ok, :ok, %{state | posting: false}}\n end\n\n def handle_call(:messages, state) do\n {:ok, Enum.reverse(state.logs), state}\n end\n\n def handle_call(:get_state, state), do: {:ok, state, state}\n\n @spec do_post([log_message]) :: no_return\n defp do_post(logs) do\n try do\n HTTP.post!(\"\/api\/logs\", Poison.encode!(logs))\n GenEvent.call(Elixir.Logger, __MODULE__, :post_success)\n rescue\n _ -> GenEvent.call(Elixir.Logger, __MODULE__, :post_fail)\n end\n end\n\n @spec write_file([log_message]) :: no_return\n defp write_file(logs) do\n debug_log(\"Writing log file!\")\n old = read_file()\n new_file = Enum.reduce(logs, old, fn(log, acc) ->\n if log.message != @filtered do\n acc <> log.message <> \"\\r\\n\"\n else\n acc\n end\n end)\n\n bin = fifo(new_file)\n\n Farmbot.System.FS.transaction fn ->\n File.write(@save_path, bin <> \"\\r\\n\")\n end\n end\n\n # reads the current file.\n # if the file isnt found, returns an empty string\n @spec read_file :: binary\n defp read_file do\n case File.read(@save_path) do\n {:ok, bin} -> bin\n _ -> \"\"\n end\n end\n\n # if the file is to big, fifo it\n # trim lines off the file until it is smaller than @max_file_size\n @spec fifo(binary) :: binary\n defp fifo(new_file) when byte_size(new_file) > @max_file_size do\n [_ | rest] = String.split(new_file, \"\\r\\n\")\n fifo(Enum.join(rest, \"\\r\\n\"))\n end\n\n defp fifo(new_file), do: new_file\n\n # if this backend crashes just pop it out of the logger backends.\n # if we don't do this it bacomes a huge mess because of Logger\n # trying to restart this module\n # then this module dying again\n # then printing a HUGE supervisor report\n # then Logger trying to add it again etc\n def terminate(_,_), do: spawn fn -> Logger.remove_backend(__MODULE__) end\n\n @spec sanitize(binary, [any]) :: String.t\n defp sanitize(message, meta) do\n module = Keyword.get(meta, :module)\n unless meta[:nopub] do\n message\n |> filter_module(module)\n |> filter_text()\n end\n end\n\n @modules [\n :\"Elixir.Nerves.InterimWiFi\",\n :\"Elixir.Nerves.NetworkInterface\",\n :\"Elixir.Nerves.InterimWiFi.WiFiManager.EventHandler\",\n :\"Elixir.Nerves.InterimWiFi.WiFiManager\",\n :\"Elixir.Nerves.InterimWiFi.DHCPManager\",\n :\"Elixir.Nerves.InterimWiFi.Udhcpc\",\n :\"Elixir.Nerves.NetworkInterface.Worker\",\n :\"Elixir.Nerves.InterimWiFi.DHCPManager.EventHandler\",\n :\"Elixir.Nerves.WpaSupplicant\",\n :\"Elixir.Farmbot.System.NervesCommon.EventManager\",\n ]\n\n for module <- @modules, do: defp filter_module(_, unquote(module)), do: @filtered\n defp filter_module(message, _module), do: message\n\n defp filter_text(\">>\" <> m), do: filter_text(\"#{Sync.device_name()}\" <> m)\n defp filter_text(m) when is_binary(m) do\n try do\n Poison.encode!(m)\n m\n rescue\n _ -> @filtered\n end\n end\n defp filter_text(_message), do: @filtered\n\n # Couuld probably do this inline but wheres the fun in that. its a functional\n # language isn't it?\n # Takes Loggers time stamp and converts it into a unix timestamp.\n defp parse_created_at({{year, month, day}, {hour, minute, second, _mil}}) do\n %DateTime{year: year,\n month: month,\n day: day,\n hour: hour,\n minute: minute,\n second: second,\n microsecond: {0,0},\n std_offset: 0,\n time_zone: \"Etc\/UTC\",\n utc_offset: 0,\n zone_abbr: \"UTC\"}\n |> DateTime.to_unix#(:milliseconds)\n end\n\n @spec build_log(String.t, number, rpc_log_type, [channel]) :: log_message\n defp build_log(message, created_at, type, channels) do\n %{message: message,\n created_at: created_at,\n channels: channels,\n meta: %{type: type, x: 0, y: 0, z: 0}}\n end\nend\n","old_contents":"defmodule Logger.Backends.FarmbotLogger do\n @moduledoc \"\"\"\n Logger backend for logging to the frontend and dumping to the API.\n Takes messages that were logged useing Logger, if they can be\n jsonified, adds them too a buffer, when that buffer hits a certain\n size, it tries to dump the messages onto the API.\n \"\"\"\n alias Farmbot.Sync\n alias Farmbot.HTTP\n use GenEvent\n require Logger\n use Farmbot.DebugLog\n @save_path Application.get_env(:farmbot, :path) <> \"\/logs.txt\"\n\n # ten megs. i promise\n @max_file_size 1.0e+7\n @filtered \"[FILTERED]\"\n\n @typedoc \"\"\"\n The state of the logger\n \"\"\"\n @type state :: %{logs: [log_message], posting: boolean}\n\n @typedoc \"\"\"\n Type of message for ticker\n \"\"\"\n @type rpc_log_type\n :: :success\n | :busy\n | :warn\n | :error\n | :info\n | :fun\n\n @typedoc \"\"\"\n Elixir Logger level type\n \"\"\"\n @type logger_level\n :: :info\n | :debug\n | :warn\n | :error\n\n @typedoc \"\"\"\n One day this will me more\n \"\"\"\n @type channel :: :toast\n\n @type log_message\n :: %{message: String.t,\n channels: [channel],\n created_at: integer,\n meta: %{type: rpc_log_type}}\n\n def init(_), do: {:ok, %{logs: [], posting: false}}\n\n # The example said ignore messages for other nodes, so im ignoring messages\n # for other nodes.\n def handle_event({_, gl, {Logger, _, _, _}}, state) when node(gl) != node() do\n {:ok, state}\n end\n\n # The logger event.\n def handle_event({level, _, {Logger, message, timestamp, metadata}}, state) do\n # if there is type key in the meta we need that to have priority\n type = Keyword.get(metadata, :type, level)\n channels = Keyword.get(metadata, :channels, [])\n created_at = parse_created_at(timestamp)\n san_m = sanitize(message, metadata)\n log = build_log(san_m, created_at, type, channels)\n :ok = GenServer.cast(Farmbot.Transport, {:log, log})\n logs = [log | state.logs]\n if !state.posting and Enum.count(logs) >= 50 do\n # If not already posting, and more than 50 messages\n spawn fn ->\n filterd_logs = Enum.filter(logs, fn(log) ->\n log.message != @filtered\n end)\n do_post(filterd_logs)\n end\n {:ok, %{state | logs: logs, posting: true}}\n else\n {:ok, %{state | logs: logs}}\n end\n end\n\n def handle_event(:flush, _state), do: {:ok, %{logs: [], posting: false}}\n\n def handle_call(:post_success, state) do\n debug_log \"Logs uploaded!\"\n write_file(Enum.reverse(state.logs))\n {:ok, :ok, %{state | posting: false, logs: []}}\n end\n\n def handle_call(:post_fail, state) do\n debug_log \"Logs failed to upload!\"\n {:ok, :ok, %{state | posting: false}}\n end\n\n def handle_call(:messages, state) do\n {:ok, Enum.reverse(state.logs), state}\n end\n\n def handle_call(:get_state, state), do: {:ok, state, state}\n\n @spec do_post([log_message]) :: no_return\n defp do_post(logs) do\n try do\n HTTP.post!(\"\/api\/logs\", Poison.encode!(logs))\n GenEvent.call(Elixir.Logger, __MODULE__, :post_success)\n rescue\n _ -> GenEvent.call(Elixir.Logger, __MODULE__, :post_fail)\n end\n end\n\n @spec write_file([log_message]) :: no_return\n defp write_file(logs) do\n debug_log(\"Writing log file!\")\n old = read_file()\n new_file = Enum.reduce(logs, old, fn(log, acc) ->\n if log.message != @filtered do\n acc <> log.message <> \"\\r\\n\"\n else\n acc\n end\n end)\n\n bin = fifo(new_file)\n\n Farmbot.System.FS.transaction fn ->\n File.write(@save_path, bin <> \"\\r\\n\")\n end\n end\n\n # reads the current file.\n # if the file isnt found, returns an empty string\n @spec read_file :: binary\n defp read_file do\n case File.read(@save_path) do\n {:ok, bin} -> bin\n _ -> \"\"\n end\n end\n\n # if the file is to big, fifo it\n # trim lines off the file until it is smaller than @max_file_size\n @spec fifo(binary) :: binary\n defp fifo(new_file) when byte_size(new_file) > @max_file_size do\n [_ | rest] = String.split(new_file, \"\\r\\n\")\n fifo(Enum.join(rest, \"\\r\\n\"))\n end\n\n defp fifo(new_file), do: new_file\n\n # if this backend crashes just pop it out of the logger backends.\n # if we don't do this it bacomes a huge mess because of Logger\n # trying to restart this module\n # then this module dying again\n # then printing a HUGE supervisor report\n # then Logger trying to add it again etc\n def terminate(_,_), do: spawn fn -> Logger.remove_backend(__MODULE__) end\n\n @spec sanitize(binary, [any]) :: String.t\n defp sanitize(message, meta) do\n module = Keyword.get(meta, :module)\n unless meta[:nopub] do\n message\n |> filter_module(module)\n |> filter_text()\n end\n end\n\n @modules [\n :\"Elixir.Nerves.InterimWiFi\",\n :\"Elixir.Nerves.NetworkInterface\",\n :\"Elixir.Nerves.InterimWiFi.WiFiManager.EventHandler\",\n :\"Elixir.Nerves.InterimWiFi.WiFiManager\",\n :\"Elixir.Nerves.InterimWiFi.DHCPManager\",\n :\"Elixir.Nerves.InterimWiFi.Udhcpc\",\n :\"Elixir.Nerves.NetworkInterface.Worker\",\n :\"Elixir.Nerves.InterimWiFi.DHCPManager.EventHandler\",\n :\"Elixir.Nerves.WpaSupplicant\",\n :\"Elixir.Farmbot.System.NervesCommon.EventManager\",\n ]\n\n for module <- @modules, do: defp filter_module(_, unquote(module)), do: @filtered\n defp filter_module(message, _module), do: message\n\n defp filter_text(\">>\" <> m), do: filter_text(\"#{Sync.device_name()}\" <> m)\n defp filter_text(m) when is_binary(m) do\n try do\n Poison.encode!(m)\n m\n rescue\n _ -> @filtered\n end\n end\n defp filter_text(_message), do: @filtered\n\n # Couuld probably do this inline but wheres the fun in that. its a functional\n # language isn't it?\n # Takes Loggers time stamp and converts it into a unix timestamp.\n defp parse_created_at({{year, month, day}, {hour, minute, second, _mil}}) do\n %DateTime{year: year,\n month: month,\n day: day,\n hour: hour,\n minute: minute,\n second: second,\n microsecond: {0,0},\n std_offset: 0,\n time_zone: \"Etc\/UTC\",\n utc_offset: 0,\n zone_abbr: \"UTC\"}\n |> DateTime.to_iso8601\n end\n\n @spec build_log(String.t, number, rpc_log_type, [channel]) :: log_message\n defp build_log(message, created_at, type, channels) do\n %{message: message,\n created_at: created_at,\n channels: channels,\n meta: %{type: type, x: 0, y: 0, z: 0}}\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"11bee474d4901974ea1cb3a004f8c404ed83d4bf","subject":"Strip name from checksum file (#11561)","message":"Strip name from checksum file (#11561)\n\nCurrently, the notify.exs will generate the checksum to:\r\n\r\n```\r\n * Docs.zip - sha1sum - 3812e2db7c71a6a8b03b75d06ca6debb46aebc55 Docs.zip\r\n\r\n * Docs.zip - sha256sum - cafe86adc01fcc700c83f353aedf746eeffd3b6e1542cedff18af64956ae539b Docs.zip\r\n\r\n * elixir-otp-23.zip - sha1sum - 35f999b98cbfa5888fefbeafaaf73f661a903bb7 elixir-otp-23.zip\r\n\r\n * elixir-otp-23.zip - sha256sum - 11f970adc3ddc759f349b0e00b6aecd06a1d460f21488d2ffe8f6738f2518728 elixir-otp-23.zip\r\n\r\n * elixir-otp-24.zip - sha1sum - c4224ce1b78247d7c5e04c7cd4576496fd49f002 elixir-otp-24.zip\r\n\r\n * elixir-otp-24.zip - sha256sum - 677fe7a147a40e5ee876eeb7bb8e4b968d2a8a9c42793561b61a08269ca91c19 elixir-otp-24.zip\r\n```\r\n\r\nThe result have a file name and newline at the end of each line. This change strip\r\nthat, so the result will be:\r\n\r\n```\r\n * Docs.zip - sha1sum - 3812e2db7c71a6a8b03b75d06ca6debb46aebc55\r\n * Docs.zip - sha256sum - cafe86adc01fcc700c83f353aedf746eeffd3b6e1542cedff18af64956ae539b\r\n * elixir-otp-23.zip - sha1sum - 35f999b98cbfa5888fefbeafaaf73f661a903bb7\r\n * elixir-otp-23.zip - sha256sum - 11f970adc3ddc759f349b0e00b6aecd06a1d460f21488d2ffe8f6738f2518728\r\n * elixir-otp-24.zip - sha1sum - c4224ce1b78247d7c5e04c7cd4576496fd49f002\r\n * elixir-otp-24.zip - sha256sum - 677fe7a147a40e5ee876eeb7bb8e4b968d2a8a9c42793561b61a08269ca91c19\r\n```","repos":"joshprice\/elixir,elixir-lang\/elixir,michalmuskala\/elixir","old_file":".github\/workflows\/notify.exs","new_file":".github\/workflows\/notify.exs","new_contents":"# #!\/usr\/bin\/env elixir\n[tag] = System.argv()\n\nMix.install([\n {:req, \"~> 0.2.1\"},\n {:jason, \"~> 1.0\"}\n])\n\n%{status: 200, body: body} =\n Req.get!(\"https:\/\/api.github.com\/repos\/elixir-lang\/elixir\/releases\/tags\/#{tag}\")\n\nif body[\"draft\"] do\n raise \"cannot notify a draft release\"\nend\n\n## Notify on elixir-lang-ann\n\nnames_and_checksums =\n for asset <- body[\"assets\"],\n name = asset[\"name\"],\n name =~ ~r\/.sha\\d+sum$\/,\n do: {name, Req.get!(asset[\"browser_download_url\"]).body}\n\nline_items =\n for {name, checksum_and_name} <- Enum.sort(names_and_checksums) do\n [checksum | _] = String.split(checksum_and_name, \" \")\n root = Path.rootname(name)\n \".\" <> type = Path.extname(name)\n \" * #{root} - #{type} - #{checksum}\\n\"\n end\n\nheaders = %{\n \"X-Postmark-Server-Token\" => System.fetch_env!(\"ELIXIR_LANG_ANN_TOKEN\")\n}\n\nbody = %{\n \"From\" => \"jose.valim@dashbit.co\",\n \"To\" => \"elixir-lang-ann@googlegroups.com\",\n \"Subject\" => \"Elixir #{tag} released\",\n \"HtmlBody\" => \"https:\/\/github.com\/elixir-lang\/elixir\/releases\/tag\/#{tag}\\n\\n#{line_items}\",\n \"MessageStream\": \"outbound\"\n}\n\nresp = Req.post!(\"https:\/\/api.postmarkapp.com\/email\", {:json, body}, headers: headers)\nIO.puts(\"#{resp.status} elixir-lang-ann\\n#{inspect(resp.body)}\")\n\n## Notify on Elixir Forum\n\nheaders = %{\n \"api-key\" => System.fetch_env!(\"ELIXIR_FORUM_TOKEN\"),\n \"api-username\" => \"Elixir\"\n}\n\nbody = %{\n \"title\" => \"Elixir #{tag} released\",\n \"raw\" => \"https:\/\/github.com\/elixir-lang\/elixir\/releases\/tag\/#{tag}\\n\\n#{body[\"body\"]}\",\n # Elixir News\n \"category\" => 28\n}\n\nresp = Req.post!(\"https:\/\/elixirforum.com\/posts.json\", {:json, body}, headers: headers)\nIO.puts(\"#{resp.status} Elixir Forum\\n#{inspect(resp.body)}\")\n","old_contents":"# #!\/usr\/bin\/env elixir\n[tag] = System.argv()\n\nMix.install([\n {:req, \"~> 0.2.1\"},\n {:jason, \"~> 1.0\"}\n])\n\n%{status: 200, body: body} =\n Req.get!(\"https:\/\/api.github.com\/repos\/elixir-lang\/elixir\/releases\/tags\/#{tag}\")\n\nif body[\"draft\"] do\n raise \"cannot notify a draft release\"\nend\n\n## Notify on elixir-lang-ann\n\nnames_and_checksums =\n for asset <- body[\"assets\"],\n name = asset[\"name\"],\n name =~ ~r\/.sha\\d+sum$\/,\n do: {name, Req.get!(asset[\"browser_download_url\"]).body}\n\nline_items =\n for {name, checksum} <- Enum.sort(names_and_checksums) do\n root = Path.rootname(name)\n \".\" <> type = Path.extname(name)\n \" * #{root} - #{type} - #{checksum}\\n\"\n end\n\nheaders = %{\n \"X-Postmark-Server-Token\" => System.fetch_env!(\"ELIXIR_LANG_ANN_TOKEN\")\n}\n\nbody = %{\n \"From\" => \"jose.valim@dashbit.co\",\n \"To\" => \"elixir-lang-ann@googlegroups.com\",\n \"Subject\" => \"Elixir #{tag} released\",\n \"HtmlBody\" => \"https:\/\/github.com\/elixir-lang\/elixir\/releases\/tag\/#{tag}\\n\\n#{line_items}\",\n \"MessageStream\": \"outbound\"\n}\n\nresp = Req.post!(\"https:\/\/api.postmarkapp.com\/email\", {:json, body}, headers: headers)\nIO.puts(\"#{resp.status} elixir-lang-ann\\n#{inspect(resp.body)}\")\n\n## Notify on Elixir Forum\n\nheaders = %{\n \"api-key\" => System.fetch_env!(\"ELIXIR_FORUM_TOKEN\"),\n \"api-username\" => \"Elixir\"\n}\n\nbody = %{\n \"title\" => \"Elixir #{tag} released\",\n \"raw\" => \"https:\/\/github.com\/elixir-lang\/elixir\/releases\/tag\/#{tag}\\n\\n#{body[\"body\"]}\",\n # Elixir News\n \"category\" => 28\n}\n\nresp = Req.post!(\"https:\/\/elixirforum.com\/posts.json\", {:json, body}, headers: headers)\nIO.puts(\"#{resp.status} Elixir Forum\\n#{inspect(resp.body)}\")\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"d223fce04a730b5f2c9e4a30849a3dabb7d1a930","subject":"deliver\/1 spec (#352)","message":"deliver\/1 spec (#352)\n\nChange prepared `@spec deliver(any()) :: no_return()` because function ignore parameters (now only `Bamboo.Email.t` required).","repos":"thoughtbot\/bamboo","old_file":"lib\/bamboo\/mailer.ex","new_file":"lib\/bamboo\/mailer.ex","new_contents":"defmodule Bamboo.Mailer do\n @moduledoc \"\"\"\n Sets up mailers that make it easy to configure and swap adapters.\n\n Adds `deliver_now\/1` and `deliver_later\/1` functions to the mailer module it is used by.\n\n ## Bamboo ships with the following adapters\n\n * `Bamboo.MandrillAdapter`\n * `Bamboo.LocalAdapter`\n * `Bamboo.TestAdapter`\n * or create your own with `Bamboo.Adapter`\n\n ## Example\n\n # In your config\/config.exs file\n config :my_app, MyApp.Mailer,\n adapter: Bamboo.MandrillAdapter,\n api_key: \"my_api_key\"\n\n # Somewhere in your application. Maybe lib\/my_app\/mailer.ex\n defmodule MyApp.Mailer do\n # Adds deliver_now\/1 and deliver_later\/1\n use Bamboo.Mailer, otp_app: :my_app\n end\n\n # Set up your emails\n defmodule MyApp.Email do\n import Bamboo.Email\n\n def welcome_email do\n new_mail(\n to: \"foo@example.com\",\n from: \"me@example.com\",\n subject: \"Welcome!!!\",\n html_body: \"WELCOME<\/strong>\",\n text_body: \"WELCOME\"\n )\n end\n end\n\n # In a Phoenix controller or some other module\n defmodule MyApp.Foo do\n alias MyApp.Email\n alias MyApp.Mailer\n\n def register_user do\n # Create a user and whatever else is needed\n # Could also have called Mailer.deliver_later\n Email.welcome_email |> Mailer.deliver_now\n end\n end\n \"\"\"\n\n @cannot_call_directly_error \"\"\"\n cannot call Bamboo.Mailer directly. Instead implement your own Mailer module\n with: use Bamboo.Mailer, otp_app: :my_app\n \"\"\"\n\n require Logger\n alias Bamboo.Formatter\n\n defmacro __using__(opts) do\n quote bind_quoted: [opts: opts] do\n\n @spec deliver_now(Bamboo.Email.t) :: Bamboo.Email.t\n def deliver_now(email) do\n config = build_config()\n Bamboo.Mailer.deliver_now(config.adapter, email, config)\n end\n\n @spec deliver_later(Bamboo.Email.t) :: Bamboo.Email.t\n def deliver_later(email) do\n config = build_config()\n Bamboo.Mailer.deliver_later(config.adapter, email, config)\n end\n\n otp_app = Keyword.fetch!(opts, :otp_app)\n\n defp build_config, do: Bamboo.Mailer.build_config(__MODULE__, unquote(otp_app))\n\n @spec deliver(any()) :: no_return()\n def deliver(_email) do\n raise \"\"\"\n you called deliver\/1, but it has been renamed to deliver_now\/1 to add clarity.\n\n Use deliver_now\/1 to send right away, or deliver_later\/1 to send in the background.\n \"\"\"\n end\n end\n end\n\n @doc \"\"\"\n Deliver an email right away\n\n Call your mailer with `deliver_now\/1` to send an email right away. Call\n `deliver_later\/1` if you want to send in the background to speed things up.\n \"\"\"\n def deliver_now(_email) do\n raise @cannot_call_directly_error\n end\n\n @doc \"\"\"\n Deliver an email in the background\n\n Call your mailer with `deliver_later\/1` to send an email using the configured\n `deliver_later_strategy`. If no `deliver_later_strategy` is set,\n `Bamboo.TaskSupervisorStrategy` will be used. See\n `Bamboo.DeliverLaterStrategy` to learn how to change how emails are delivered\n with `deliver_later\/1`.\n \"\"\"\n def deliver_later(_email) do\n raise @cannot_call_directly_error\n end\n\n @doc false\n def deliver_now(adapter, email, config) do\n email = email |> validate_and_normalize(adapter)\n\n if email.to == [] && email.cc == [] && email.bcc == [] do\n debug_unsent(email)\n else\n debug_sent(email, adapter)\n adapter.deliver(email, config)\n end\n email\n end\n\n @doc false\n def deliver_later(adapter, email, config) do\n email = email |> validate_and_normalize(adapter)\n\n if email.to == [] && email.cc == [] && email.bcc == [] do\n debug_unsent(email)\n else\n debug_sent(email, adapter)\n config.deliver_later_strategy.deliver_later(adapter, email, config)\n end\n email\n end\n\n defp debug_sent(email, adapter) do\n Logger.debug \"\"\"\n Sending email with #{inspect adapter}:\n\n #{inspect email, limit: :infinity}\n \"\"\"\n end\n\n defp debug_unsent(email) do\n Logger.debug \"\"\"\n Email was not sent because recipients are empty.\n\n Full email - #{inspect email, limit: :infinity}\n \"\"\"\n end\n\n defp validate_and_normalize(email, adapter) do\n email |> validate(adapter) |> normalize_addresses\n end\n\n defp validate(email, adapter) do\n email\n |> validate_from_address\n |> validate_recipients\n |> validate_attachment_support(adapter)\n end\n\n defp validate_attachment_support(%{attachments: []} = email, _adapter), do: email\n defp validate_attachment_support(email, adapter) do\n if function_exported?(adapter, :supports_attachments?, 0) && adapter.supports_attachments? do\n email\n else\n raise \"the #{adapter} does not support attachments yet.\"\n end\n end\n\n defp validate_from_address(%{from: nil}) do\n raise Bamboo.EmptyFromAddressError, nil\n end\n defp validate_from_address(%{from: {_, nil}}) do\n raise Bamboo.EmptyFromAddressError, nil\n end\n defp validate_from_address(email), do: email\n\n defp validate_recipients(%Bamboo.Email{} = email) do\n if Enum.all?(\n Enum.map([:to, :cc, :bcc], &Map.get(email, &1)),\n &is_nil_recipient?\/1\n ) do\n raise Bamboo.NilRecipientsError, email\n else\n email\n end\n end\n\n defp is_nil_recipient?(nil), do: true\n defp is_nil_recipient?({_, nil}), do: true\n defp is_nil_recipient?([]), do: false\n defp is_nil_recipient?([_|_] = recipients) do\n Enum.all?(recipients, &is_nil_recipient?\/1)\n end\n defp is_nil_recipient?(_), do: false\n\n @doc \"\"\"\n Wraps to, cc and bcc addresses in a list and normalizes email addresses.\n\n Also formats the from address. Email normalization\/formatting is done by the\n [Bamboo.Formatter] protocol.\n \"\"\"\n def normalize_addresses(email) do\n %{email |\n from: format(email.from, :from),\n to: format(List.wrap(email.to), :to),\n cc: format(List.wrap(email.cc), :cc),\n bcc: format(List.wrap(email.bcc), :bcc)\n }\n end\n\n defp format(record, type) do\n Formatter.format_email_address(record, %{type: type})\n end\n\n @doc false\n def parse_opts(mailer, opts) do\n Logger.warn(\"#{__MODULE__}.parse_opts\/2 has been deprecated. Use #{__MODULE__}.build_config\/2\")\n\n otp_app = Keyword.fetch!(opts, :otp_app)\n build_config(mailer, otp_app)\n end\n\n def build_config(mailer, otp_app) do\n otp_app\n |> Application.fetch_env!(mailer)\n |> Map.new\n |> handle_adapter_config\n end\n\n defp handle_adapter_config(base_config = %{adapter: adapter}) do\n adapter.handle_config(base_config)\n |> Map.put_new(:deliver_later_strategy, Bamboo.TaskSupervisorStrategy)\n end\nend\n","old_contents":"defmodule Bamboo.Mailer do\n @moduledoc \"\"\"\n Sets up mailers that make it easy to configure and swap adapters.\n\n Adds `deliver_now\/1` and `deliver_later\/1` functions to the mailer module it is used by.\n\n ## Bamboo ships with the following adapters\n\n * `Bamboo.MandrillAdapter`\n * `Bamboo.LocalAdapter`\n * `Bamboo.TestAdapter`\n * or create your own with `Bamboo.Adapter`\n\n ## Example\n\n # In your config\/config.exs file\n config :my_app, MyApp.Mailer,\n adapter: Bamboo.MandrillAdapter,\n api_key: \"my_api_key\"\n\n # Somewhere in your application. Maybe lib\/my_app\/mailer.ex\n defmodule MyApp.Mailer do\n # Adds deliver_now\/1 and deliver_later\/1\n use Bamboo.Mailer, otp_app: :my_app\n end\n\n # Set up your emails\n defmodule MyApp.Email do\n import Bamboo.Email\n\n def welcome_email do\n new_mail(\n to: \"foo@example.com\",\n from: \"me@example.com\",\n subject: \"Welcome!!!\",\n html_body: \"WELCOME<\/strong>\",\n text_body: \"WELCOME\"\n )\n end\n end\n\n # In a Phoenix controller or some other module\n defmodule MyApp.Foo do\n alias MyApp.Email\n alias MyApp.Mailer\n\n def register_user do\n # Create a user and whatever else is needed\n # Could also have called Mailer.deliver_later\n Email.welcome_email |> Mailer.deliver_now\n end\n end\n \"\"\"\n\n @cannot_call_directly_error \"\"\"\n cannot call Bamboo.Mailer directly. Instead implement your own Mailer module\n with: use Bamboo.Mailer, otp_app: :my_app\n \"\"\"\n\n require Logger\n alias Bamboo.Formatter\n\n defmacro __using__(opts) do\n quote bind_quoted: [opts: opts] do\n\n @spec deliver_now(Bamboo.Email.t) :: Bamboo.Email.t\n def deliver_now(email) do\n config = build_config()\n Bamboo.Mailer.deliver_now(config.adapter, email, config)\n end\n\n @spec deliver_later(Bamboo.Email.t) :: Bamboo.Email.t\n def deliver_later(email) do\n config = build_config()\n Bamboo.Mailer.deliver_later(config.adapter, email, config)\n end\n\n otp_app = Keyword.fetch!(opts, :otp_app)\n\n defp build_config, do: Bamboo.Mailer.build_config(__MODULE__, unquote(otp_app))\n\n @spec deliver(Bamboo.Email.t) :: no_return()\n def deliver(_email) do\n raise \"\"\"\n you called deliver\/1, but it has been renamed to deliver_now\/1 to add clarity.\n\n Use deliver_now\/1 to send right away, or deliver_later\/1 to send in the background.\n \"\"\"\n end\n end\n end\n\n @doc \"\"\"\n Deliver an email right away\n\n Call your mailer with `deliver_now\/1` to send an email right away. Call\n `deliver_later\/1` if you want to send in the background to speed things up.\n \"\"\"\n def deliver_now(_email) do\n raise @cannot_call_directly_error\n end\n\n @doc \"\"\"\n Deliver an email in the background\n\n Call your mailer with `deliver_later\/1` to send an email using the configured\n `deliver_later_strategy`. If no `deliver_later_strategy` is set,\n `Bamboo.TaskSupervisorStrategy` will be used. See\n `Bamboo.DeliverLaterStrategy` to learn how to change how emails are delivered\n with `deliver_later\/1`.\n \"\"\"\n def deliver_later(_email) do\n raise @cannot_call_directly_error\n end\n\n @doc false\n def deliver_now(adapter, email, config) do\n email = email |> validate_and_normalize(adapter)\n\n if email.to == [] && email.cc == [] && email.bcc == [] do\n debug_unsent(email)\n else\n debug_sent(email, adapter)\n adapter.deliver(email, config)\n end\n email\n end\n\n @doc false\n def deliver_later(adapter, email, config) do\n email = email |> validate_and_normalize(adapter)\n\n if email.to == [] && email.cc == [] && email.bcc == [] do\n debug_unsent(email)\n else\n debug_sent(email, adapter)\n config.deliver_later_strategy.deliver_later(adapter, email, config)\n end\n email\n end\n\n defp debug_sent(email, adapter) do\n Logger.debug \"\"\"\n Sending email with #{inspect adapter}:\n\n #{inspect email, limit: :infinity}\n \"\"\"\n end\n\n defp debug_unsent(email) do\n Logger.debug \"\"\"\n Email was not sent because recipients are empty.\n\n Full email - #{inspect email, limit: :infinity}\n \"\"\"\n end\n\n defp validate_and_normalize(email, adapter) do\n email |> validate(adapter) |> normalize_addresses\n end\n\n defp validate(email, adapter) do\n email\n |> validate_from_address\n |> validate_recipients\n |> validate_attachment_support(adapter)\n end\n\n defp validate_attachment_support(%{attachments: []} = email, _adapter), do: email\n defp validate_attachment_support(email, adapter) do\n if function_exported?(adapter, :supports_attachments?, 0) && adapter.supports_attachments? do\n email\n else\n raise \"the #{adapter} does not support attachments yet.\"\n end\n end\n\n defp validate_from_address(%{from: nil}) do\n raise Bamboo.EmptyFromAddressError, nil\n end\n defp validate_from_address(%{from: {_, nil}}) do\n raise Bamboo.EmptyFromAddressError, nil\n end\n defp validate_from_address(email), do: email\n\n defp validate_recipients(%Bamboo.Email{} = email) do\n if Enum.all?(\n Enum.map([:to, :cc, :bcc], &Map.get(email, &1)),\n &is_nil_recipient?\/1\n ) do\n raise Bamboo.NilRecipientsError, email\n else\n email\n end\n end\n\n defp is_nil_recipient?(nil), do: true\n defp is_nil_recipient?({_, nil}), do: true\n defp is_nil_recipient?([]), do: false\n defp is_nil_recipient?([_|_] = recipients) do\n Enum.all?(recipients, &is_nil_recipient?\/1)\n end\n defp is_nil_recipient?(_), do: false\n\n @doc \"\"\"\n Wraps to, cc and bcc addresses in a list and normalizes email addresses.\n\n Also formats the from address. Email normalization\/formatting is done by the\n [Bamboo.Formatter] protocol.\n \"\"\"\n def normalize_addresses(email) do\n %{email |\n from: format(email.from, :from),\n to: format(List.wrap(email.to), :to),\n cc: format(List.wrap(email.cc), :cc),\n bcc: format(List.wrap(email.bcc), :bcc)\n }\n end\n\n defp format(record, type) do\n Formatter.format_email_address(record, %{type: type})\n end\n\n @doc false\n def parse_opts(mailer, opts) do\n Logger.warn(\"#{__MODULE__}.parse_opts\/2 has been deprecated. Use #{__MODULE__}.build_config\/2\")\n\n otp_app = Keyword.fetch!(opts, :otp_app)\n build_config(mailer, otp_app)\n end\n\n def build_config(mailer, otp_app) do\n otp_app\n |> Application.fetch_env!(mailer)\n |> Map.new\n |> handle_adapter_config\n end\n\n defp handle_adapter_config(base_config = %{adapter: adapter}) do\n adapter.handle_config(base_config)\n |> Map.put_new(:deliver_later_strategy, Bamboo.TaskSupervisorStrategy)\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"f3d5ef996d4cf086e22e801142e11f1dc18ba6d0","subject":"Fix test to match updated Door#show","message":"Fix test to match updated Door#show","repos":"alkaloid\/gatekeeper,alkaloid\/gatekeeper,alkaloid\/gatekeeper","old_file":"test\/controllers\/door_controller_test.exs","new_file":"test\/controllers\/door_controller_test.exs","new_contents":"defmodule Gatekeeper.DoorControllerTest do\n use Gatekeeper.ConnCase\n\n import Gatekeeper.Factory\n\n alias Gatekeeper.Door\n alias Gatekeeper.DoorGroup\n\n @valid_attrs %{name: \"some content\"}\n @invalid_attrs %{}\n\n setup do\n conn = conn()\n {:ok, conn: conn}\n end\n\n test \"lists all entries on index\", %{conn: conn} do\n conn = get conn, door_path(conn, :index)\n assert html_response(conn, 200) =~ \"Listing doors\"\n end\n\n test \"renders form for new resources\", %{conn: conn} do\n conn = get conn, door_path(conn, :new)\n assert html_response(conn, 200) =~ \"New door\"\n end\n\n test \"creates resource and redirects when data is valid\", %{conn: conn} do\n conn = post conn, door_path(conn, :create), door: @valid_attrs\n assert redirected_to(conn) == door_path(conn, :index)\n assert Repo.get_by(Door, @valid_attrs)\n end\n\n test \"does not create resource and renders errors when data is invalid\", %{conn: conn} do\n conn = post conn, door_path(conn, :create), door: @invalid_attrs\n assert html_response(conn, 200) =~ \"New door\"\n end\n\n test \"shows chosen resource\", %{conn: conn} do\n door = Repo.insert! %Door{}\n conn = get conn, door_path(conn, :show, door)\n assert html_response(conn, 200) =~ \"

#{door.name}<\/h1>\"\n end\n\n test \"renders page not found when id is nonexistent\", %{conn: conn} do\n assert_raise Ecto.NoResultsError, fn ->\n get conn, door_path(conn, :show, -1)\n end\n end\n\n test \"renders form for editing chosen resource\", %{conn: conn} do\n door = Repo.insert! %Door{}\n conn = get conn, door_path(conn, :edit, door)\n assert html_response(conn, 200) =~ \"Edit door\"\n end\n\n test \"updates chosen resource and redirects when data is valid\", %{conn: conn} do\n door = Repo.insert! %Door{}\n conn = put conn, door_path(conn, :update, door), door: @valid_attrs\n assert redirected_to(conn) == door_path(conn, :show, door)\n assert Repo.get_by(Door, @valid_attrs)\n end\n\n test \"updates door group with associated doors and redirects when data is valid\", %{conn: conn} do\n door_group = create_door_group\n door = create_door\n # We can't dynamically construct a map with a variable without this\n # See: http:\/\/stackoverflow.com\/questions\/29837103\/how-to-put-key-value-pair-into-map-with-variable-key-name\n # \"Note that variables cannot be used as keys to add items to a map:\"\n # See: http:\/\/elixir-lang.org\/getting-started\/maps-and-dicts.html#maps\n doors_param = Map.put(%{}, \"#{door.id}\", \"on\")\n conn = put conn, door_group_path(conn, :update, door_group), door_group: Dict.merge(@valid_attrs, %{doors: doors_param })\n assert redirected_to(conn) == door_group_path(conn, :show, door_group)\n door_group = Repo.get_by(DoorGroup, @valid_attrs) |> Repo.preload :doors\n assert door_group\n assert [door.id] == Enum.map(door_group.doors, &(&1.id))\n end\n\n test \"removes unchecked associated door groups from a company\", %{conn: conn} do\n door_group = create_door_group\n door = create_door\n Repo.insert! %Gatekeeper.DoorGroupDoor{door_id: door.id, door_group_id: door_group.id}\n\n conn = put conn, door_group_path(conn, :update, door_group), door_group: Dict.merge(@valid_attrs, id: door_group.id)\n assert redirected_to(conn) == door_group_path(conn, :show, door_group)\n door_group = Repo.get!(DoorGroup, door_group.id) |> Repo.preload :doors\n assert door_group\n assert [] == Enum.map(door_group.doors, &(&1.id))\n end\n\n test \"does not update chosen resource and renders errors when data is invalid\", %{conn: conn} do\n door = Repo.insert! %Door{}\n conn = put conn, door_path(conn, :update, door), door: @invalid_attrs\n assert html_response(conn, 200) =~ \"Edit door\"\n end\n\n test \"deletes chosen resource\", %{conn: conn} do\n door = Repo.insert! %Door{}\n conn = delete conn, door_path(conn, :delete, door)\n assert redirected_to(conn) == door_path(conn, :index)\n refute Repo.get(Door, door.id)\n end\nend\n","old_contents":"defmodule Gatekeeper.DoorControllerTest do\n use Gatekeeper.ConnCase\n\n import Gatekeeper.Factory\n\n alias Gatekeeper.Door\n alias Gatekeeper.DoorGroup\n\n @valid_attrs %{name: \"some content\"}\n @invalid_attrs %{}\n\n setup do\n conn = conn()\n {:ok, conn: conn}\n end\n\n test \"lists all entries on index\", %{conn: conn} do\n conn = get conn, door_path(conn, :index)\n assert html_response(conn, 200) =~ \"Listing doors\"\n end\n\n test \"renders form for new resources\", %{conn: conn} do\n conn = get conn, door_path(conn, :new)\n assert html_response(conn, 200) =~ \"New door\"\n end\n\n test \"creates resource and redirects when data is valid\", %{conn: conn} do\n conn = post conn, door_path(conn, :create), door: @valid_attrs\n assert redirected_to(conn) == door_path(conn, :index)\n assert Repo.get_by(Door, @valid_attrs)\n end\n\n test \"does not create resource and renders errors when data is invalid\", %{conn: conn} do\n conn = post conn, door_path(conn, :create), door: @invalid_attrs\n assert html_response(conn, 200) =~ \"New door\"\n end\n\n test \"shows chosen resource\", %{conn: conn} do\n door = Repo.insert! %Door{}\n conn = get conn, door_path(conn, :show, door)\n assert html_response(conn, 200) =~ \"Show door\"\n end\n\n test \"renders page not found when id is nonexistent\", %{conn: conn} do\n assert_raise Ecto.NoResultsError, fn ->\n get conn, door_path(conn, :show, -1)\n end\n end\n\n test \"renders form for editing chosen resource\", %{conn: conn} do\n door = Repo.insert! %Door{}\n conn = get conn, door_path(conn, :edit, door)\n assert html_response(conn, 200) =~ \"Edit door\"\n end\n\n test \"updates chosen resource and redirects when data is valid\", %{conn: conn} do\n door = Repo.insert! %Door{}\n conn = put conn, door_path(conn, :update, door), door: @valid_attrs\n assert redirected_to(conn) == door_path(conn, :show, door)\n assert Repo.get_by(Door, @valid_attrs)\n end\n\n test \"updates door group with associated doors and redirects when data is valid\", %{conn: conn} do\n door_group = create_door_group\n door = create_door\n # We can't dynamically construct a map with a variable without this\n # See: http:\/\/stackoverflow.com\/questions\/29837103\/how-to-put-key-value-pair-into-map-with-variable-key-name\n # \"Note that variables cannot be used as keys to add items to a map:\"\n # See: http:\/\/elixir-lang.org\/getting-started\/maps-and-dicts.html#maps\n doors_param = Map.put(%{}, \"#{door.id}\", \"on\")\n conn = put conn, door_group_path(conn, :update, door_group), door_group: Dict.merge(@valid_attrs, %{doors: doors_param })\n assert redirected_to(conn) == door_group_path(conn, :show, door_group)\n door_group = Repo.get_by(DoorGroup, @valid_attrs) |> Repo.preload :doors\n assert door_group\n assert [door.id] == Enum.map(door_group.doors, &(&1.id))\n end\n\n test \"removes unchecked associated door groups from a company\", %{conn: conn} do\n door_group = create_door_group\n door = create_door\n Repo.insert! %Gatekeeper.DoorGroupDoor{door_id: door.id, door_group_id: door_group.id}\n\n conn = put conn, door_group_path(conn, :update, door_group), door_group: Dict.merge(@valid_attrs, id: door_group.id)\n assert redirected_to(conn) == door_group_path(conn, :show, door_group)\n door_group = Repo.get!(DoorGroup, door_group.id) |> Repo.preload :doors\n assert door_group\n assert [] == Enum.map(door_group.doors, &(&1.id))\n end\n\n test \"does not update chosen resource and renders errors when data is invalid\", %{conn: conn} do\n door = Repo.insert! %Door{}\n conn = put conn, door_path(conn, :update, door), door: @invalid_attrs\n assert html_response(conn, 200) =~ \"Edit door\"\n end\n\n test \"deletes chosen resource\", %{conn: conn} do\n door = Repo.insert! %Door{}\n conn = delete conn, door_path(conn, :delete, door)\n assert redirected_to(conn) == door_path(conn, :index)\n refute Repo.get(Door, door.id)\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"d8b3d9966f61fde5ba607cf987001513a8a65a38","subject":"Use a better tag for integration tests","message":"Use a better tag for integration tests\n","repos":"bitwalker\/distillery,bitwalker\/distillery","old_file":"test\/integration_test.exs","new_file":"test\/integration_test.exs","new_contents":"defmodule IntegrationTest do\n use ExUnit.Case, async: false\n\n alias Mix.Releases.Utils\n import MixTestHelper\n\n @moduletag integration: true\n @moduletag timeout: 60_000 * 5\n\n @standard_app_path Path.join([__DIR__, \"fixtures\", \"standard_app\"])\n @standard_output_path Path.join([\n __DIR__,\n \"fixtures\",\n \"standard_app\",\n \"_build\",\n \"prod\",\n \"rel\",\n \"standard_app\"\n ])\n\n defmacrop with_standard_app(body) do\n quote do\n clean_up_standard_app!()\n old_dir = File.cwd!()\n File.cd!(@standard_app_path)\n {:ok, _} = File.rm_rf(Path.join(@standard_app_path, \"_build\"))\n _ = File.rm(Path.join(@standard_app_path, \"mix.lock\"))\n {:ok, _} = mix(\"deps.get\")\n {:ok, _} = mix(\"compile\")\n {:ok, _} = mix(\"release.clean\")\n unquote(body)\n File.cd!(old_dir)\n end\n end\n\n defp run_cmd(command, args) when is_list(args) do\n case System.cmd(command, args) do\n {output, 0} ->\n if System.get_env(\"VERBOSE_TESTS\") do\n IO.puts(output)\n end\n\n {:ok, output}\n\n {output, non_zero_exit} ->\n IO.puts(output)\n {:error, non_zero_exit, output}\n end\n end\n\n {:ok, req} = Version.parse_requirement(\"< 1.4.0\")\n\n if Version.match?(Version.parse!(System.version()), req) do\n @time_unit :milliseconds\n else\n @time_unit :millisecond\n end\n\n # Wait for VM and application to start\n defp wait_for_app(bin_path) do\n parent = self()\n pid = spawn_link(fn -> ping_loop(bin_path, parent) end)\n do_wait_for_app(pid, 30_000)\n end\n\n defp do_wait_for_app(pid, time_remaining) when time_remaining <= 0 do\n send(pid, :die)\n :timeout\n end\n\n defp do_wait_for_app(pid, time_remaining) do\n start = System.monotonic_time(@time_unit)\n\n if System.get_env(\"VERBOSE_TESTS\") do\n IO.puts(\"Waiting #{time_remaining}ms for app..\")\n end\n\n receive do\n {:ok, :pong} ->\n :ok\n\n _other ->\n ts = System.monotonic_time(@time_unit)\n do_wait_for_app(pid, time_remaining - (ts - start))\n after\n time_remaining ->\n send(pid, :die)\n :timeout\n end\n end\n\n defp ping_loop(bin_path, parent) do\n case System.cmd(bin_path, [\"ping\"]) do\n {\"pong\\n\", 0} ->\n send(parent, {:ok, :pong})\n\n {output, _exit_code} ->\n receive do\n :die ->\n if System.get_env(\"VERBOSE_TESTS\") do\n IO.puts(output)\n end\n\n :ok\n after\n 1_000 ->\n ping_loop(bin_path, parent)\n end\n end\n end\n\n describe \"standard application\" do\n test \"can build release and start it\" do\n with_standard_app do\n # Build release\n assert {:ok, output} = mix(\"release\", [\"--verbose\", \"--env=prod\"])\n\n for callback <- ~w(before_assembly after_assembly before_package after_package) do\n assert output =~ \"Prod Plugin - #{callback}\"\n end\n\n refute String.contains?(output, \"Release Plugin\")\n\n assert [\"0.0.1\"] == Utils.get_release_versions(@standard_output_path)\n # Boot it, ping it, and shut it down\n assert {:ok, tmpdir} = Utils.insecure_mkdir_temp()\n bin_path = Path.join([tmpdir, \"bin\", \"standard_app\"])\n\n try do\n tarfile = Path.join([@standard_output_path, \"releases\", \"0.0.1\", \"standard_app.tar.gz\"])\n assert :ok = :erl_tar.extract('#{tarfile}', [{:cwd, '#{tmpdir}'}, :compressed])\n assert File.exists?(bin_path)\n\n case :os.type() do\n {:win32, _} ->\n assert {:ok, _} = run_cmd(bin_path, [\"install\"])\n\n _ ->\n :ok\n end\n\n :ok = create_additional_config_file(tmpdir)\n\n assert {:ok, _} = run_cmd(bin_path, [\"start\"])\n assert :ok = wait_for_app(bin_path)\n\n assert {:ok, \"2\\n\"} =\n run_cmd(bin_path, [\"rpc\", \"Application.get_env(:standard_app, :num_procs)\"])\n\n # Additional config items should exist\n assert {:ok, \":bar\\n\"} =\n run_cmd(bin_path, [\"rpc\", \"Application.get_env(:standard_app, :foo)\"])\n\n case :os.type() do\n {:win32, _} ->\n assert {:ok, output} = run_cmd(bin_path, [\"stop\"])\n assert output =~ \"stopped\"\n assert {:ok, _} = run_cmd(bin_path, [\"uninstall\"])\n\n _ ->\n assert {:ok, \"ok\\n\"} = run_cmd(bin_path, [\"stop\"])\n end\n rescue\n e ->\n run_cmd(bin_path, [\"stop\"])\n\n case :os.type() do\n {:win32, _} ->\n run_cmd(bin_path, [\"uninstall\"])\n\n _ ->\n :ok\n end\n\n reraise e, System.stacktrace()\n after\n File.rm_rf!(tmpdir)\n :ok\n end\n end\n end\n\n test \"can build and deploy hot upgrade\" do\n with_standard_app do\n # Build v1 release\n assert {:ok, _} = mix(\"release\", [\"--verbose\", \"--env=prod\"])\n update_config_and_code_to_v2()\n # Build v2 release\n assert {:ok, _} = mix(\"compile\")\n assert {:ok, _} = mix(\"release\", [\"--verbose\", \"--env=prod\", \"--upgrade\"])\n assert [\"0.0.2\", \"0.0.1\"] == Utils.get_release_versions(@standard_output_path)\n # Deploy it\n assert {:ok, tmpdir} = Utils.insecure_mkdir_temp()\n bin_path = Path.join([tmpdir, \"bin\", \"standard_app\"])\n\n try do\n unpack_old_release(tmpdir)\n copy_new_release(tmpdir)\n\n # Boot it, ping it, upgrade it, rpc to verify, then shut it down\n assert File.exists?(bin_path)\n\n case :os.type() do\n {:win32, _} ->\n assert {:ok, _} = run_cmd(bin_path, [\"install\"])\n\n _ ->\n :ok\n end\n\n :ok = create_additional_config_file(tmpdir)\n assert {:ok, _} = run_cmd(bin_path, [\"start\"])\n assert :ok = wait_for_app(bin_path)\n assert {:ok, \":ok\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.A.push(1)\"])\n assert {:ok, \":ok\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.A.push(2)\"])\n assert {:ok, \":ok\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.B.push(1)\"])\n assert {:ok, \":ok\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.B.push(2)\"])\n assert {:ok, output} = run_cmd(bin_path, [\"upgrade\", \"0.0.2\"])\n assert output =~ \"Made release standard_app:0.0.2 permanent\"\n assert {:ok, \"{:ok, 2}\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.A.pop()\"])\n assert {:ok, \"{:ok, 2}\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.B.pop()\"])\n\n assert {:ok, \"4\\n\"} =\n run_cmd(bin_path, [\"rpc\", \"Application.get_env(:standard_app, :num_procs)\"])\n\n case :os.type() do\n {:win32, _} ->\n assert {:ok, output} = run_cmd(bin_path, [\"stop\"])\n assert output =~ \"stopped\"\n assert {:ok, _} = run_cmd(bin_path, [\"uninstall\"])\n\n _ ->\n assert {:ok, \"ok\\n\"} = run_cmd(bin_path, [\"stop\"])\n :ok\n end\n rescue\n e ->\n run_cmd(bin_path, [\"stop\"])\n\n case :os.type() do\n {:win32, _} ->\n run_cmd(bin_path, [\"uninstall\"])\n\n _ ->\n :ok\n end\n\n reraise e, System.stacktrace()\n after\n _ = File.rm_rf(tmpdir)\n clean_up_standard_app!()\n :ok\n end\n end\n end\n\n test \"can build and deploy hot upgrade with previously generated appup\" do\n with_standard_app do\n # Build v1 release\n assert {:ok, _} = mix(\"release\", [\"--verbose\", \"--env=prod\"])\n update_config_and_code_to_v2()\n # Build v2 release\n assert {:ok, _} = mix(\"compile\")\n assert {:ok, _} = mix(\"release.gen.appup\", [\"--app=standard_app\"])\n assert {:ok, _} = mix(\"release\", [\"--verbose\", \"--env=prod\", \"--upgrade\"])\n assert [\"0.0.2\", \"0.0.1\"] == Utils.get_release_versions(@standard_output_path)\n # Deploy it\n assert {:ok, tmpdir} = Utils.insecure_mkdir_temp()\n bin_path = Path.join([tmpdir, \"bin\", \"standard_app\"])\n\n try do\n unpack_old_release(tmpdir)\n copy_new_release(tmpdir)\n\n # Boot it, ping it, upgrade it, rpc to verify, then shut it down\n assert File.exists?(bin_path)\n\n case :os.type() do\n {:win32, _} ->\n assert {:ok, _} = run_cmd(bin_path, [\"install\"])\n\n _ ->\n :ok\n end\n\n :ok = create_additional_config_file(tmpdir)\n assert {:ok, _} = run_cmd(bin_path, [\"start\"])\n assert :ok = wait_for_app(bin_path)\n assert {:ok, \":ok\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.A.push(1)\"])\n assert {:ok, \":ok\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.A.push(2)\"])\n assert {:ok, \":ok\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.B.push(1)\"])\n assert {:ok, \":ok\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.B.push(2)\"])\n assert {:ok, output} = run_cmd(bin_path, [\"upgrade\", \"0.0.2\"])\n assert output =~ \"Made release standard_app:0.0.2 permanent\"\n assert {:ok, \"{:ok, 2}\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.A.pop()\"])\n assert {:ok, \"{:ok, 2}\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.B.pop()\"])\n\n assert {:ok, \"4\\n\"} =\n run_cmd(bin_path, [\"rpc\", \"Application.get_env(:standard_app, :num_procs)\"])\n\n case :os.type() do\n {:win32, _} ->\n assert {:ok, output} = run_cmd(bin_path, [\"stop\"])\n assert output =~ \"stopped\"\n assert {:ok, _} = run_cmd(bin_path, [\"uninstall\"])\n\n _ ->\n assert {:ok, \"ok\\n\"} = run_cmd(bin_path, [\"stop\"])\n :ok\n end\n rescue\n e ->\n run_cmd(bin_path, [\"stop\"])\n\n case :os.type() do\n {:win32, _} ->\n run_cmd(bin_path, [\"uninstall\"])\n\n _ ->\n :ok\n end\n\n reraise e, System.stacktrace()\n after\n _ = File.rm_rf(tmpdir)\n clean_up_standard_app!()\n :ok\n end\n end\n end\n\n test \"when installation directory contains a space\" do\n with_standard_app do\n # Build v1 release\n assert {:ok, _} = mix(\"release\", [\"--verbose\", \"--env=prod\"])\n\n # Untar the release into a path that contains a space character then\n # try to run it.\n assert {:ok, tmpdir} = Utils.insecure_mkdir_temp()\n tmpdir = Path.join(tmpdir, \"dir with space\")\n bin_path = Path.join([tmpdir, \"bin\", \"standard_app\"])\n\n try do\n tarfile = Path.join([@standard_output_path, \"releases\", \"0.0.1\", \"standard_app.tar.gz\"])\n assert :ok = :erl_tar.extract('#{tarfile}', [{:cwd, '#{tmpdir}'}, :compressed])\n assert File.exists?(bin_path)\n\n case :os.type() do\n {:win32, _} ->\n assert {:ok, _} = run_cmd(bin_path, [\"install\"])\n\n _ ->\n :ok\n end\n\n :ok = create_additional_config_file(tmpdir)\n\n assert {:ok, _} = run_cmd(bin_path, [\"start\"])\n assert :ok = wait_for_app(bin_path)\n\n assert {:ok, \"2\\n\"} =\n run_cmd(bin_path, [\"rpc\", \"Application.get_env(:standard_app, :num_procs)\"])\n\n # Additional config items should exist\n assert {:ok, \":bar\\n\"} =\n run_cmd(bin_path, [\"rpc\", \"Application.get_env(:standard_app, :foo)\"])\n\n case :os.type() do\n {:win32, _} ->\n assert {:ok, output} = run_cmd(bin_path, [\"stop\"])\n assert output =~ \"stopped\"\n assert {:ok, _} = run_cmd(bin_path, [\"uninstall\"])\n\n _ ->\n assert {:ok, \"ok\\n\"} = run_cmd(bin_path, [\"stop\"])\n end\n rescue\n e ->\n run_cmd(bin_path, [\"stop\"])\n\n case :os.type() do\n {:win32, _} ->\n run_cmd(bin_path, [\"uninstall\"])\n\n _ ->\n :ok\n end\n\n reraise e, System.stacktrace()\n after\n File.rm_rf!(tmpdir)\n :ok\n end\n end\n end\n end\n\n # Create a configuration file inside the release directory\n defp create_additional_config_file(directory) do\n extra_config_path = Path.join([directory, \"extra.config\"])\n Mix.Releases.Utils.write_term(extra_config_path, standard_app: [foo: :bar])\n :ok\n end\n\n defp clean_up_standard_app! do\n project_path = Path.join(@standard_app_path, \"mix.exs.v1\")\n\n if File.exists?(project_path) do\n File.cp!(project_path, Path.join(@standard_app_path, \"mix.exs\"))\n File.rm!(project_path)\n end\n\n config_path = Path.join([@standard_app_path, \"config\", \"config.exs.v1\"])\n\n if File.exists?(config_path) do\n File.cp!(config_path, Path.join([@standard_app_path, \"config\", \"config.exs\"]))\n File.rm!(config_path)\n end\n\n rel_config_path = Path.join([@standard_app_path, \"rel\", \"config.exs.v1\"])\n\n if File.exists?(rel_config_path) do\n File.cp!(rel_config_path, Path.join([@standard_app_path, \"rel\", \"config.exs\"]))\n File.rm!(rel_config_path)\n end\n\n a_mod_path = Path.join([@standard_app_path, \"lib\", \"standard_app\", \"a.ex.v1\"])\n\n if File.exists?(a_mod_path) do\n File.cp!(a_mod_path, Path.join([@standard_app_path, \"lib\", \"standard_app\", \"a.ex\"]))\n File.rm!(a_mod_path)\n end\n\n b_mod_path = Path.join([@standard_app_path, \"lib\", \"standard_app\", \"b.ex.v1\"])\n\n if File.exists?(b_mod_path) do\n File.cp!(b_mod_path, Path.join([@standard_app_path, \"lib\", \"standard_app\", \"b.ex\"]))\n File.rm!(b_mod_path)\n end\n\n File.rm_rf!(Path.join([@standard_app_path, \"rel\", \"standard_app\"]))\n File.rm_rf!(Path.join([@standard_app_path, \"rel\", \"appups\", \"standard_app\"]))\n :ok\n end\n\n defp update_config_and_code_to_v2 do\n # Update config for v2\n project_config_path = Path.join(@standard_app_path, \"mix.exs\")\n project = File.read!(project_config_path)\n config_path = Path.join([@standard_app_path, \"config\", \"config.exs\"])\n config = File.read!(config_path)\n rel_config_path = Path.join([@standard_app_path, \"rel\", \"config.exs\"])\n rel_config = File.read!(rel_config_path)\n # Write updates to modules\n a_mod_path = Path.join([@standard_app_path, \"lib\", \"standard_app\", \"a.ex\"])\n a_mod = File.read!(a_mod_path)\n b_mod_path = Path.join([@standard_app_path, \"lib\", \"standard_app\", \"b.ex\"])\n b_mod = File.read!(b_mod_path)\n # Save orig\n File.cp!(project_config_path, Path.join(@standard_app_path, \"mix.exs.v1\"))\n File.cp!(config_path, Path.join([@standard_app_path, \"config\", \"config.exs.v1\"]))\n File.cp!(rel_config_path, Path.join([@standard_app_path, \"rel\", \"config.exs.v1\"]))\n File.cp!(a_mod_path, Path.join([@standard_app_path, \"lib\", \"standard_app\", \"a.ex.v1\"]))\n File.cp!(b_mod_path, Path.join([@standard_app_path, \"lib\", \"standard_app\", \"b.ex.v1\"]))\n # Write new config\n new_project_config = String.replace(project, \"version: \\\"0.0.1\\\"\", \"version: \\\"0.0.2\\\"\")\n new_config = String.replace(config, \"num_procs: 2\", \"num_procs: 4\")\n\n new_rel_config =\n String.replace(rel_config, \"set version: \\\"0.0.1\\\"\", \"set version: \\\"0.0.2\\\"\")\n\n File.write!(project_config_path, new_project_config)\n File.write!(config_path, new_config)\n File.write!(rel_config_path, new_rel_config)\n # Write updated modules\n new_a_mod = String.replace(a_mod, \"{:ok, {1, []}}\", \"{:ok, {2, []}}\")\n\n new_b_mod =\n String.replace(b_mod, \"loop({1, []}, parent, debug)\", \"loop({2, []}, parent, debug)\")\n\n File.write!(a_mod_path, new_a_mod)\n File.write!(b_mod_path, new_b_mod)\n end\n\n defp unpack_old_release(tmpdir) do\n tarfile = Path.join([@standard_output_path, \"releases\", \"0.0.1\", \"standard_app.tar.gz\"])\n assert :ok = :erl_tar.extract('#{tarfile}', [{:cwd, '#{tmpdir}'}, :compressed])\n end\n\n defp copy_new_release(tmpdir) do\n File.mkdir_p!(Path.join([tmpdir, \"releases\", \"0.0.2\"]))\n File.cp!(\n Path.join([@standard_output_path, \"releases\", \"0.0.2\", \"standard_app.tar.gz\"]),\n Path.join([tmpdir, \"releases\", \"0.0.2\", \"standard_app.tar.gz\"])\n )\n end\nend\n","old_contents":"defmodule IntegrationTest do\n use ExUnit.Case, async: false\n\n alias Mix.Releases.Utils\n import MixTestHelper\n\n @standard_app_path Path.join([__DIR__, \"fixtures\", \"standard_app\"])\n @standard_output_path Path.join([\n __DIR__,\n \"fixtures\",\n \"standard_app\",\n \"_build\",\n \"prod\",\n \"rel\",\n \"standard_app\"\n ])\n\n defmacrop with_standard_app(body) do\n quote do\n clean_up_standard_app!()\n old_dir = File.cwd!()\n File.cd!(@standard_app_path)\n {:ok, _} = File.rm_rf(Path.join(@standard_app_path, \"_build\"))\n _ = File.rm(Path.join(@standard_app_path, \"mix.lock\"))\n {:ok, _} = mix(\"deps.get\")\n {:ok, _} = mix(\"compile\")\n {:ok, _} = mix(\"release.clean\")\n unquote(body)\n File.cd!(old_dir)\n end\n end\n\n defp run_cmd(command, args) when is_list(args) do\n case System.cmd(command, args) do\n {output, 0} ->\n if System.get_env(\"VERBOSE_TESTS\") do\n IO.puts(output)\n end\n\n {:ok, output}\n\n {output, non_zero_exit} ->\n IO.puts(output)\n {:error, non_zero_exit, output}\n end\n end\n\n {:ok, req} = Version.parse_requirement(\"< 1.4.0\")\n\n if Version.match?(Version.parse!(System.version()), req) do\n @time_unit :milliseconds\n else\n @time_unit :millisecond\n end\n\n # Wait for VM and application to start\n defp wait_for_app(bin_path) do\n parent = self()\n pid = spawn_link(fn -> ping_loop(bin_path, parent) end)\n do_wait_for_app(pid, 30_000)\n end\n\n defp do_wait_for_app(pid, time_remaining) when time_remaining <= 0 do\n send(pid, :die)\n :timeout\n end\n\n defp do_wait_for_app(pid, time_remaining) do\n start = System.monotonic_time(@time_unit)\n\n if System.get_env(\"VERBOSE_TESTS\") do\n IO.puts(\"Waiting #{time_remaining}ms for app..\")\n end\n\n receive do\n {:ok, :pong} ->\n :ok\n\n _other ->\n ts = System.monotonic_time(@time_unit)\n do_wait_for_app(pid, time_remaining - (ts - start))\n after\n time_remaining ->\n send(pid, :die)\n :timeout\n end\n end\n\n defp ping_loop(bin_path, parent) do\n case System.cmd(bin_path, [\"ping\"]) do\n {\"pong\\n\", 0} ->\n send(parent, {:ok, :pong})\n\n {output, _exit_code} ->\n receive do\n :die ->\n if System.get_env(\"VERBOSE_TESTS\") do\n IO.puts(output)\n end\n\n :ok\n after\n 1_000 ->\n ping_loop(bin_path, parent)\n end\n end\n end\n\n describe \"standard application\" do\n @tag :expensive\n # 5m\n @tag timeout: 60_000 * 5\n test \"can build release and start it\" do\n with_standard_app do\n # Build release\n assert {:ok, output} = mix(\"release\", [\"--verbose\", \"--env=prod\"])\n\n for callback <- ~w(before_assembly after_assembly before_package after_package) do\n assert output =~ \"Prod Plugin - #{callback}\"\n end\n\n refute String.contains?(output, \"Release Plugin\")\n\n assert [\"0.0.1\"] == Utils.get_release_versions(@standard_output_path)\n # Boot it, ping it, and shut it down\n assert {:ok, tmpdir} = Utils.insecure_mkdir_temp()\n bin_path = Path.join([tmpdir, \"bin\", \"standard_app\"])\n\n try do\n tarfile = Path.join([@standard_output_path, \"releases\", \"0.0.1\", \"standard_app.tar.gz\"])\n assert :ok = :erl_tar.extract('#{tarfile}', [{:cwd, '#{tmpdir}'}, :compressed])\n assert File.exists?(bin_path)\n\n case :os.type() do\n {:win32, _} ->\n assert {:ok, _} = run_cmd(bin_path, [\"install\"])\n\n _ ->\n :ok\n end\n\n :ok = create_additional_config_file(tmpdir)\n\n assert {:ok, _} = run_cmd(bin_path, [\"start\"])\n assert :ok = wait_for_app(bin_path)\n\n assert {:ok, \"2\\n\"} =\n run_cmd(bin_path, [\"rpc\", \"Application.get_env(:standard_app, :num_procs)\"])\n\n # Additional config items should exist\n assert {:ok, \":bar\\n\"} =\n run_cmd(bin_path, [\"rpc\", \"Application.get_env(:standard_app, :foo)\"])\n\n case :os.type() do\n {:win32, _} ->\n assert {:ok, output} = run_cmd(bin_path, [\"stop\"])\n assert output =~ \"stopped\"\n assert {:ok, _} = run_cmd(bin_path, [\"uninstall\"])\n\n _ ->\n assert {:ok, \"ok\\n\"} = run_cmd(bin_path, [\"stop\"])\n end\n rescue\n e ->\n run_cmd(bin_path, [\"stop\"])\n\n case :os.type() do\n {:win32, _} ->\n run_cmd(bin_path, [\"uninstall\"])\n\n _ ->\n :ok\n end\n\n reraise e, System.stacktrace()\n after\n File.rm_rf!(tmpdir)\n :ok\n end\n end\n end\n\n @tag :expensive\n # 5m\n @tag timeout: 60_000 * 5\n test \"can build and deploy hot upgrade\" do\n with_standard_app do\n # Build v1 release\n assert {:ok, _} = mix(\"release\", [\"--verbose\", \"--env=prod\"])\n update_config_and_code_to_v2()\n # Build v2 release\n assert {:ok, _} = mix(\"compile\")\n assert {:ok, _} = mix(\"release\", [\"--verbose\", \"--env=prod\", \"--upgrade\"])\n assert [\"0.0.2\", \"0.0.1\"] == Utils.get_release_versions(@standard_output_path)\n # Deploy it\n assert {:ok, tmpdir} = Utils.insecure_mkdir_temp()\n bin_path = Path.join([tmpdir, \"bin\", \"standard_app\"])\n\n try do\n unpack_old_release(tmpdir)\n copy_new_release(tmpdir)\n\n # Boot it, ping it, upgrade it, rpc to verify, then shut it down\n assert File.exists?(bin_path)\n\n case :os.type() do\n {:win32, _} ->\n assert {:ok, _} = run_cmd(bin_path, [\"install\"])\n\n _ ->\n :ok\n end\n\n :ok = create_additional_config_file(tmpdir)\n assert {:ok, _} = run_cmd(bin_path, [\"start\"])\n assert :ok = wait_for_app(bin_path)\n assert {:ok, \":ok\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.A.push(1)\"])\n assert {:ok, \":ok\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.A.push(2)\"])\n assert {:ok, \":ok\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.B.push(1)\"])\n assert {:ok, \":ok\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.B.push(2)\"])\n assert {:ok, output} = run_cmd(bin_path, [\"upgrade\", \"0.0.2\"])\n assert output =~ \"Made release standard_app:0.0.2 permanent\"\n assert {:ok, \"{:ok, 2}\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.A.pop()\"])\n assert {:ok, \"{:ok, 2}\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.B.pop()\"])\n\n assert {:ok, \"4\\n\"} =\n run_cmd(bin_path, [\"rpc\", \"Application.get_env(:standard_app, :num_procs)\"])\n\n case :os.type() do\n {:win32, _} ->\n assert {:ok, output} = run_cmd(bin_path, [\"stop\"])\n assert output =~ \"stopped\"\n assert {:ok, _} = run_cmd(bin_path, [\"uninstall\"])\n\n _ ->\n assert {:ok, \"ok\\n\"} = run_cmd(bin_path, [\"stop\"])\n :ok\n end\n rescue\n e ->\n run_cmd(bin_path, [\"stop\"])\n\n case :os.type() do\n {:win32, _} ->\n run_cmd(bin_path, [\"uninstall\"])\n\n _ ->\n :ok\n end\n\n reraise e, System.stacktrace()\n after\n _ = File.rm_rf(tmpdir)\n clean_up_standard_app!()\n :ok\n end\n end\n end\n\n @tag :expensive\n # 5m\n @tag timeout: 60_000 * 5\n test \"can build and deploy hot upgrade with previously generated appup\" do\n with_standard_app do\n # Build v1 release\n assert {:ok, _} = mix(\"release\", [\"--verbose\", \"--env=prod\"])\n update_config_and_code_to_v2()\n # Build v2 release\n assert {:ok, _} = mix(\"compile\")\n assert {:ok, _} = mix(\"release.gen.appup\", [\"--app=standard_app\"])\n assert {:ok, _} = mix(\"release\", [\"--verbose\", \"--env=prod\", \"--upgrade\"])\n assert [\"0.0.2\", \"0.0.1\"] == Utils.get_release_versions(@standard_output_path)\n # Deploy it\n assert {:ok, tmpdir} = Utils.insecure_mkdir_temp()\n bin_path = Path.join([tmpdir, \"bin\", \"standard_app\"])\n\n try do\n unpack_old_release(tmpdir)\n copy_new_release(tmpdir)\n\n # Boot it, ping it, upgrade it, rpc to verify, then shut it down\n assert File.exists?(bin_path)\n\n case :os.type() do\n {:win32, _} ->\n assert {:ok, _} = run_cmd(bin_path, [\"install\"])\n\n _ ->\n :ok\n end\n\n :ok = create_additional_config_file(tmpdir)\n assert {:ok, _} = run_cmd(bin_path, [\"start\"])\n assert :ok = wait_for_app(bin_path)\n assert {:ok, \":ok\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.A.push(1)\"])\n assert {:ok, \":ok\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.A.push(2)\"])\n assert {:ok, \":ok\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.B.push(1)\"])\n assert {:ok, \":ok\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.B.push(2)\"])\n assert {:ok, output} = run_cmd(bin_path, [\"upgrade\", \"0.0.2\"])\n assert output =~ \"Made release standard_app:0.0.2 permanent\"\n assert {:ok, \"{:ok, 2}\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.A.pop()\"])\n assert {:ok, \"{:ok, 2}\\n\"} = run_cmd(bin_path, [\"rpc\", \"StandardApp.B.pop()\"])\n\n assert {:ok, \"4\\n\"} =\n run_cmd(bin_path, [\"rpc\", \"Application.get_env(:standard_app, :num_procs)\"])\n\n case :os.type() do\n {:win32, _} ->\n assert {:ok, output} = run_cmd(bin_path, [\"stop\"])\n assert output =~ \"stopped\"\n assert {:ok, _} = run_cmd(bin_path, [\"uninstall\"])\n\n _ ->\n assert {:ok, \"ok\\n\"} = run_cmd(bin_path, [\"stop\"])\n :ok\n end\n rescue\n e ->\n run_cmd(bin_path, [\"stop\"])\n\n case :os.type() do\n {:win32, _} ->\n run_cmd(bin_path, [\"uninstall\"])\n\n _ ->\n :ok\n end\n\n reraise e, System.stacktrace()\n after\n _ = File.rm_rf(tmpdir)\n clean_up_standard_app!()\n :ok\n end\n end\n end\n\n @tag :expensive\n # 5m\n @tag timeout: 60_000 * 5\n test \"when installation directory contains a space\" do\n with_standard_app do\n # Build v1 release\n assert {:ok, _} = mix(\"release\", [\"--verbose\", \"--env=prod\"])\n\n # Untar the release into a path that contains a space character then\n # try to run it.\n assert {:ok, tmpdir} = Utils.insecure_mkdir_temp()\n tmpdir = Path.join(tmpdir, \"dir with space\")\n bin_path = Path.join([tmpdir, \"bin\", \"standard_app\"])\n\n try do\n tarfile = Path.join([@standard_output_path, \"releases\", \"0.0.1\", \"standard_app.tar.gz\"])\n assert :ok = :erl_tar.extract('#{tarfile}', [{:cwd, '#{tmpdir}'}, :compressed])\n assert File.exists?(bin_path)\n\n case :os.type() do\n {:win32, _} ->\n assert {:ok, _} = run_cmd(bin_path, [\"install\"])\n\n _ ->\n :ok\n end\n\n :ok = create_additional_config_file(tmpdir)\n\n assert {:ok, _} = run_cmd(bin_path, [\"start\"])\n assert :ok = wait_for_app(bin_path)\n\n assert {:ok, \"2\\n\"} =\n run_cmd(bin_path, [\"rpc\", \"Application.get_env(:standard_app, :num_procs)\"])\n\n # Additional config items should exist\n assert {:ok, \":bar\\n\"} =\n run_cmd(bin_path, [\"rpc\", \"Application.get_env(:standard_app, :foo)\"])\n\n case :os.type() do\n {:win32, _} ->\n assert {:ok, output} = run_cmd(bin_path, [\"stop\"])\n assert output =~ \"stopped\"\n assert {:ok, _} = run_cmd(bin_path, [\"uninstall\"])\n\n _ ->\n assert {:ok, \"ok\\n\"} = run_cmd(bin_path, [\"stop\"])\n end\n rescue\n e ->\n run_cmd(bin_path, [\"stop\"])\n\n case :os.type() do\n {:win32, _} ->\n run_cmd(bin_path, [\"uninstall\"])\n\n _ ->\n :ok\n end\n\n reraise e, System.stacktrace()\n after\n File.rm_rf!(tmpdir)\n :ok\n end\n end\n end\n end\n\n # Create a configuration file inside the release directory\n defp create_additional_config_file(directory) do\n extra_config_path = Path.join([directory, \"extra.config\"])\n Mix.Releases.Utils.write_term(extra_config_path, standard_app: [foo: :bar])\n :ok\n end\n\n defp clean_up_standard_app! do\n project_path = Path.join(@standard_app_path, \"mix.exs.v1\")\n\n if File.exists?(project_path) do\n File.cp!(project_path, Path.join(@standard_app_path, \"mix.exs\"))\n File.rm!(project_path)\n end\n\n config_path = Path.join([@standard_app_path, \"config\", \"config.exs.v1\"])\n\n if File.exists?(config_path) do\n File.cp!(config_path, Path.join([@standard_app_path, \"config\", \"config.exs\"]))\n File.rm!(config_path)\n end\n\n rel_config_path = Path.join([@standard_app_path, \"rel\", \"config.exs.v1\"])\n\n if File.exists?(rel_config_path) do\n File.cp!(rel_config_path, Path.join([@standard_app_path, \"rel\", \"config.exs\"]))\n File.rm!(rel_config_path)\n end\n\n a_mod_path = Path.join([@standard_app_path, \"lib\", \"standard_app\", \"a.ex.v1\"])\n\n if File.exists?(a_mod_path) do\n File.cp!(a_mod_path, Path.join([@standard_app_path, \"lib\", \"standard_app\", \"a.ex\"]))\n File.rm!(a_mod_path)\n end\n\n b_mod_path = Path.join([@standard_app_path, \"lib\", \"standard_app\", \"b.ex.v1\"])\n\n if File.exists?(b_mod_path) do\n File.cp!(b_mod_path, Path.join([@standard_app_path, \"lib\", \"standard_app\", \"b.ex\"]))\n File.rm!(b_mod_path)\n end\n\n File.rm_rf!(Path.join([@standard_app_path, \"rel\", \"standard_app\"]))\n File.rm_rf!(Path.join([@standard_app_path, \"rel\", \"appups\", \"standard_app\"]))\n :ok\n end\n\n defp update_config_and_code_to_v2 do\n # Update config for v2\n project_config_path = Path.join(@standard_app_path, \"mix.exs\")\n project = File.read!(project_config_path)\n config_path = Path.join([@standard_app_path, \"config\", \"config.exs\"])\n config = File.read!(config_path)\n rel_config_path = Path.join([@standard_app_path, \"rel\", \"config.exs\"])\n rel_config = File.read!(rel_config_path)\n # Write updates to modules\n a_mod_path = Path.join([@standard_app_path, \"lib\", \"standard_app\", \"a.ex\"])\n a_mod = File.read!(a_mod_path)\n b_mod_path = Path.join([@standard_app_path, \"lib\", \"standard_app\", \"b.ex\"])\n b_mod = File.read!(b_mod_path)\n # Save orig\n File.cp!(project_config_path, Path.join(@standard_app_path, \"mix.exs.v1\"))\n File.cp!(config_path, Path.join([@standard_app_path, \"config\", \"config.exs.v1\"]))\n File.cp!(rel_config_path, Path.join([@standard_app_path, \"rel\", \"config.exs.v1\"]))\n File.cp!(a_mod_path, Path.join([@standard_app_path, \"lib\", \"standard_app\", \"a.ex.v1\"]))\n File.cp!(b_mod_path, Path.join([@standard_app_path, \"lib\", \"standard_app\", \"b.ex.v1\"]))\n # Write new config\n new_project_config = String.replace(project, \"version: \\\"0.0.1\\\"\", \"version: \\\"0.0.2\\\"\")\n new_config = String.replace(config, \"num_procs: 2\", \"num_procs: 4\")\n\n new_rel_config =\n String.replace(rel_config, \"set version: \\\"0.0.1\\\"\", \"set version: \\\"0.0.2\\\"\")\n\n File.write!(project_config_path, new_project_config)\n File.write!(config_path, new_config)\n File.write!(rel_config_path, new_rel_config)\n # Write updated modules\n new_a_mod = String.replace(a_mod, \"{:ok, {1, []}}\", \"{:ok, {2, []}}\")\n\n new_b_mod =\n String.replace(b_mod, \"loop({1, []}, parent, debug)\", \"loop({2, []}, parent, debug)\")\n\n File.write!(a_mod_path, new_a_mod)\n File.write!(b_mod_path, new_b_mod)\n end\n\n defp unpack_old_release(tmpdir) do\n tarfile = Path.join([@standard_output_path, \"releases\", \"0.0.1\", \"standard_app.tar.gz\"])\n assert :ok = :erl_tar.extract('#{tarfile}', [{:cwd, '#{tmpdir}'}, :compressed])\n end\n\n defp copy_new_release(tmpdir) do\n File.mkdir_p!(Path.join([tmpdir, \"releases\", \"0.0.2\"]))\n File.cp!(\n Path.join([@standard_output_path, \"releases\", \"0.0.2\", \"standard_app.tar.gz\"]),\n Path.join([tmpdir, \"releases\", \"0.0.2\", \"standard_app.tar.gz\"])\n )\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"1970858b8dbec094589ba6899882204f07f15039","subject":"Added ability to replace default layout. #77","message":"Added ability to replace default layout. #77\n","repos":"kleinernik\/ex_admin,smpallen99\/ex_admin,smpallen99\/ex_admin,whitepaperclip\/ex_admin,romul\/ex_admin,kleinernik\/ex_admin,Kociamber\/ex_admin,romul\/ex_admin,whitepaperclip\/ex_admin,Kociamber\/ex_admin","old_file":"web\/web.ex","new_file":"web\/web.ex","new_contents":"defmodule ExAdmin.Web do\n @moduledoc false\n\n def model do\n quote do\n use Ecto.Schema\n\n import Ecto\n import Ecto.Changeset\n import Ecto.Query, only: [from: 1, from: 2]\n end\n end\n\n def controller do\n quote do\n use Phoenix.Controller\n\n import Ecto.Model\n import Ecto.Query, only: [from: 1, from: 2]\n\n import ExAdmin.Router.Helpers\n import ExAdmin.Utils, only: [admin_path: 0, admin_path: 2, admin_resource_path: 3, admin_association_path: 4]\n import ExAdmin.Controller\n\n defp set_theme(conn, _) do\n assign(conn, :theme, ExAdmin.theme)\n end\n\n defp set_layout(conn, _) do\n layout = Application.get_env(:ex_admin, :layout) || \"#{conn.assigns.theme.name}.html\"\n put_layout(conn, layout)\n end\n end\n end\n\n def view do\n quote do\n require Logger\n\n\n file_path = __ENV__.file\n |> Path.dirname\n |> String.split(\"\/views\")\n |> hd\n |> Path.join(\"templates\")\n\n use Phoenix.View, root: file_path\n # use Phoenix.View, root: \"web\/templates\"\n\n # Import convenience functions from controllers\n import Phoenix.Controller, only: [view_module: 1]\n\n # Use all HTML functionality (forms, tags, etc)\n use Phoenix.HTML\n\n import ExAdmin.Router.Helpers\n #import ExAuth\n import ExAdmin.ViewHelpers\n end\n end\n\n def router do\n quote do\n use Phoenix.Router\n end\n end\n\n def channel do\n quote do\n use Phoenix.Channel\n\n # alias Application.get_env(:ex_admin, :repo)\n # import Application.get_env(:ex_admin, :repo)\n import Ecto\n import Ecto.Query, only: [from: 1, from: 2]\n\n end\n end\n\n @doc \"\"\"\n When used, dispatch to the appropriate controller\/view\/etc.\n \"\"\"\n defmacro __using__(which) when is_atom(which) do\n apply(__MODULE__, which, [])\n end\nend\n","old_contents":"defmodule ExAdmin.Web do\n @moduledoc false\n\n def model do\n quote do\n use Ecto.Schema\n\n import Ecto\n import Ecto.Changeset\n import Ecto.Query, only: [from: 1, from: 2]\n end\n end\n\n def controller do\n quote do\n use Phoenix.Controller\n\n import Ecto.Model\n import Ecto.Query, only: [from: 1, from: 2]\n\n import ExAdmin.Router.Helpers\n import ExAdmin.Utils, only: [admin_path: 0, admin_path: 2, admin_resource_path: 3, admin_association_path: 4]\n import ExAdmin.Controller\n\n defp set_theme(conn, _) do\n assign(conn, :theme, ExAdmin.theme)\n end\n\n defp set_layout(conn, _) do\n put_layout(conn, \"#{conn.assigns.theme.name}.html\")\n end\n end\n end\n\n def view do\n quote do\n require Logger\n\n\n file_path = __ENV__.file\n |> Path.dirname\n |> String.split(\"\/views\")\n |> hd\n |> Path.join(\"templates\")\n\n use Phoenix.View, root: file_path\n # use Phoenix.View, root: \"web\/templates\"\n\n # Import convenience functions from controllers\n import Phoenix.Controller, only: [view_module: 1]\n\n # Use all HTML functionality (forms, tags, etc)\n use Phoenix.HTML\n\n import ExAdmin.Router.Helpers\n #import ExAuth\n import ExAdmin.ViewHelpers\n end\n end\n\n def router do\n quote do\n use Phoenix.Router\n end\n end\n\n def channel do\n quote do\n use Phoenix.Channel\n\n # alias Application.get_env(:ex_admin, :repo)\n # import Application.get_env(:ex_admin, :repo)\n import Ecto\n import Ecto.Query, only: [from: 1, from: 2]\n\n end\n end\n\n @doc \"\"\"\n When used, dispatch to the appropriate controller\/view\/etc.\n \"\"\"\n defmacro __using__(which) when is_atom(which) do\n apply(__MODULE__, which, [])\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"0cc8bb826c7451ab81b64842ff7056cbc7fbceac","subject":"Add \"skipped\" action result","message":"Add \"skipped\" action result\n\nFixes #1109\n","repos":"bors-ng\/bors-ng,bors-ng\/bors-ng,bors-ng\/bors-ng","old_file":"lib\/github\/github.ex","new_file":"lib\/github\/github.ex","new_contents":"require Logger\n\ndefmodule BorsNG.GitHub do\n @moduledoc \"\"\"\n Wrappers around the GitHub REST API.\n \"\"\"\n\n @typedoc \"\"\"\n An authentication token;\n this may be a raw token (as on oAuth)\n or an installation xref (in which case the server will look it up).\n \"\"\"\n @type ttoken :: {:installation, number} | {:raw, binary}\n\n @typedoc \"\"\"\n A repository connection;\n it packages a repository with the permissions to access it.\n \"\"\"\n @type tconn :: {ttoken, number} | {ttoken, number}\n\n @type tuser :: BorsNG.GitHub.User.t()\n @type trepo :: BorsNG.GitHub.Repo.t()\n @type tpr :: BorsNG.GitHub.Pr.t()\n @type tstatus :: :ok | :running | :error\n @type trepo_perm :: :admin | :push | :pull\n @type tuser_repo_perms :: %{admin: boolean, push: boolean, pull: boolean}\n @type tcollaborator :: %{user: tuser, perms: tuser_repo_perms}\n @type tcommitter :: %{name: bitstring, email: bitstring}\n\n @spec get_pr_files!(tconn, integer) :: [BorsNG.GitHub.File.t()]\n def get_pr_files!(repo_conn, pr_xref) do\n {:ok, pr} = get_pr_files(repo_conn, pr_xref)\n pr\n end\n\n @spec get_pr_files(tconn, integer) ::\n {:ok, [BorsNG.GitHub.File.t()]} | {:error, term}\n def get_pr_files(repo_conn, pr_xref) do\n GenServer.call(\n BorsNG.GitHub,\n {:get_pr_files, repo_conn, {pr_xref}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n @spec get_pr!(tconn, integer | bitstring) :: BorsNG.GitHub.Pr.t()\n def get_pr!(repo_conn, pr_xref) do\n {:ok, pr} = get_pr(repo_conn, pr_xref)\n pr\n end\n\n @spec get_pr(tconn, integer | bitstring) ::\n {:ok, BorsNG.GitHub.Pr.t()} | {:error, term}\n def get_pr(repo_conn, pr_xref) do\n GenServer.call(\n BorsNG.GitHub,\n {:get_pr, repo_conn, {pr_xref}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n @spec update_pr_base!(tconn, BorsNG.GitHub.Pr.t()) :: BorsNG.GitHub.Pr.t()\n def update_pr_base!(repo_conn, pr) do\n {:ok, pr} = update_pr_base(repo_conn, pr)\n pr\n end\n\n @spec update_pr!(tconn, BorsNG.GitHub.Pr.t()) :: BorsNG.GitHub.Pr.t()\n def update_pr!(repo_conn, pr) do\n {:ok, pr} = update_pr(repo_conn, pr)\n pr\n end\n\n @spec update_pr_base(tconn, BorsNG.GitHub.Pr.t()) ::\n {:ok, BorsNG.GitHub.Pr.t()} | {:error, term}\n def update_pr_base(repo_conn, pr) do\n GenServer.call(\n BorsNG.GitHub,\n {:update_pr_base, repo_conn, pr},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n @spec update_pr(tconn, BorsNG.GitHub.Pr.t()) ::\n {:ok, BorsNG.GitHub.Pr.t()} | {:error, term}\n def update_pr(repo_conn, pr) do\n GenServer.call(\n BorsNG.GitHub,\n {:update_pr, repo_conn, pr},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n @spec get_pr_commits!(tconn, integer | bitstring) :: [BorsNG.GitHub.Commit.t()]\n def get_pr_commits!(repo_conn, pr_xref) do\n {:ok, commits} = get_pr_commits(repo_conn, pr_xref)\n commits\n end\n\n @spec get_pr_commits(tconn, integer | bitstring) ::\n {:ok, [BorsNG.GitHub.Commit.t()]} | {:error, term}\n def get_pr_commits(repo_conn, pr_xref) do\n GenServer.call(\n BorsNG.GitHub,\n {:get_pr_commits, repo_conn, {pr_xref}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n @spec get_open_prs!(tconn) :: [tpr]\n def get_open_prs!(repo_conn) do\n {:ok, prs} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_open_prs, repo_conn, {}},\n 100_000\n )\n\n prs\n end\n\n @spec get_open_prs_with_base!(tconn, binary) :: [tpr]\n def get_open_prs_with_base!(repo_conn, base) do\n {:ok, prs} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_open_prs_with_base, repo_conn, {base}},\n 100_000\n )\n\n prs\n end\n\n @spec push!(tconn, binary, binary) :: binary\n def push!(repo_conn, sha, to) do\n {:ok, sha} =\n GenServer.call(\n BorsNG.GitHub,\n {:push, repo_conn, {sha, to}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n sha\n end\n\n @spec push(tconn, binary, binary) :: {:ok, binary} | {:error, term, term, term}\n def push(repo_conn, sha, to) do\n GenServer.call(\n BorsNG.GitHub,\n {:push, repo_conn, {sha, to}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n @spec get_branch!(tconn, binary) :: %{commit: bitstring, tree: bitstring}\n def get_branch!(repo_conn, from) do\n {:ok, commit} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_branch, repo_conn, {from}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n commit\n end\n\n @spec delete_branch!(tconn, binary) :: :ok\n def delete_branch!(repo_conn, branch) do\n :ok =\n GenServer.call(\n BorsNG.GitHub,\n {:delete_branch, repo_conn, {branch}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n :ok\n end\n\n @spec merge_branch!(tconn, %{\n from: bitstring,\n to: bitstring,\n commit_message: bitstring\n }) :: %{commit: binary, tree: binary} | :conflict\n def merge_branch!(repo_conn, info) do\n {:ok, commit} =\n GenServer.call(\n BorsNG.GitHub,\n {:merge_branch, repo_conn, {info}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n commit\n end\n\n @spec synthesize_commit!(tconn, %{\n branch: bitstring,\n tree: bitstring,\n parents: [bitstring],\n commit_message: bitstring,\n committer: tcommitter | nil\n }) :: binary\n def synthesize_commit!(repo_conn, info) do\n {:ok, sha} =\n GenServer.call(\n BorsNG.GitHub,\n {:synthesize_commit, repo_conn, {info}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n sha\n end\n\n @spec create_commit!(tconn, %{\n tree: bitstring,\n parents: [bitstring],\n commit_message: bitstring,\n committer: tcommitter | nil\n }) :: binary\n def create_commit!(repo_conn, info) do\n {:ok, sha} =\n GenServer.call(\n BorsNG.GitHub,\n {:create_commit, repo_conn, {info}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n sha\n end\n\n @spec create_commit(tconn, %{\n tree: bitstring,\n parents: [bitstring],\n commit_message: bitstring,\n committer: tcommitter | nil\n }) :: {:ok, binary} | {:error, term, term}\n def create_commit(repo_conn, info) do\n GenServer.call(\n BorsNG.GitHub,\n {:create_commit, repo_conn, {info}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n @spec force_push!(tconn, binary, binary) :: binary\n def force_push!(repo_conn, sha, to) do\n {:ok, sha} =\n GenServer.call(\n BorsNG.GitHub,\n {:force_push, repo_conn, {sha, to}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n sha\n end\n\n @spec get_commit_status!(tconn, binary) :: %{\n binary => tstatus\n }\n def get_commit_status!(repo_conn, sha) do\n {:ok, status} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_commit_status, repo_conn, {sha}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n status\n end\n\n @spec get_labels!(tconn, integer | bitstring) :: [bitstring]\n def get_labels!(repo_conn, issue_xref) do\n {:ok, labels} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_labels, repo_conn, {issue_xref}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n labels\n end\n\n @spec get_reviews!(tconn, integer | bitstring) :: map\n def get_reviews!(repo_conn, issue_xref) do\n {:ok, labels} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_reviews, repo_conn, {issue_xref}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n labels\n end\n\n @spec get_commit_reviews!(tconn, integer | bitstring, binary) :: map\n def get_commit_reviews!(repo_conn, issue_xref, sha) do\n {:ok, labels} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_reviews, repo_conn, {issue_xref, sha}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n labels\n end\n\n @spec get_file!(tconn, binary, binary) :: binary | nil\n def get_file!(repo_conn, branch, path) do\n {:ok, file} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_file, repo_conn, {branch, path}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n file\n end\n\n @spec post_comment!(tconn, number, binary) :: :ok\n def post_comment!(repo_conn, number, body) do\n :ok =\n GenServer.call(\n BorsNG.GitHub,\n {:post_comment, repo_conn, {number, body}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n :ok\n end\n\n @spec post_commit_status!(tconn, {binary, tstatus, binary, binary}) :: :ok\n def post_commit_status!(repo_conn, {sha, status, msg, url}) do\n # Auto-retry\n first_try =\n GenServer.call(\n BorsNG.GitHub,\n {:post_commit_status, repo_conn, {sha, status, msg, url}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n case first_try do\n :ok ->\n :ok\n\n _ ->\n Process.sleep(11)\n\n :ok =\n GenServer.call(\n BorsNG.GitHub,\n {:post_commit_status, repo_conn, {sha, status, msg, url}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n :ok\n end\n\n @spec get_user_by_login!(ttoken, binary) :: {:ok, tuser} | :error | nil\n def get_user_by_login!(token, login) do\n {:ok, user} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_user_by_login, token, {String.trim(login)}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n user\n end\n\n @spec belongs_to_team?(tconn, String.t(), String.t(), String.t()) ::\n boolean\n def belongs_to_team?(repo_conn, org, team_slug, username) do\n GenServer.call(\n BorsNG.GitHub,\n {:belongs_to_team, repo_conn, {org, team_slug, username}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n @spec get_collaborators_by_repo(tconn) ::\n {:ok, [tcollaborator]} | :error\n def get_collaborators_by_repo(repo_conn) do\n GenServer.call(\n BorsNG.GitHub,\n {:get_collaborators_by_repo, repo_conn, {}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n @spec get_app!() :: String.t()\n def get_app! do\n {:ok, app_link} =\n GenServer.call(BorsNG.GitHub, :get_app, Confex.fetch_env!(:bors, :api_github_timeout))\n\n app_link\n end\n\n @spec get_installation_repos!(ttoken) :: [trepo]\n def get_installation_repos!(token) do\n {:ok, repos} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_installation_repos, token, {}},\n 100_000\n )\n\n repos\n end\n\n @spec get_installation_list! :: [integer]\n def get_installation_list! do\n {:ok, installations} =\n GenServer.call(\n BorsNG.GitHub,\n :get_installation_list,\n 100_000\n )\n\n installations\n end\n\n @spec map_state_to_status(binary) :: tstatus\n def map_state_to_status(state) do\n case state do\n \"pending\" -> :running\n \"success\" -> :ok\n \"neutral\" -> :ok\n \"skipped\" -> :ok\n \"failure\" -> :error\n \"error\" -> :error\n end\n end\n\n @spec map_check_to_status(binary) :: tstatus\n def map_check_to_status(conclusion) do\n case conclusion do\n nil -> :running\n \"success\" -> :ok\n _ -> :error\n end\n end\n\n @spec map_status_to_state(tstatus) :: binary\n def map_status_to_state(state) do\n case state do\n :running -> \"pending\"\n :ok -> \"success\"\n :error -> \"failure\"\n end\n end\n\n @spec map_changed_status(binary) :: binary\n def map_changed_status(check_name) do\n case check_name do\n \"Travis CI - Branch\" -> \"continuous-integration\/travis-ci\/push\"\n check_name -> check_name\n end\n end\nend\n","old_contents":"require Logger\n\ndefmodule BorsNG.GitHub do\n @moduledoc \"\"\"\n Wrappers around the GitHub REST API.\n \"\"\"\n\n @typedoc \"\"\"\n An authentication token;\n this may be a raw token (as on oAuth)\n or an installation xref (in which case the server will look it up).\n \"\"\"\n @type ttoken :: {:installation, number} | {:raw, binary}\n\n @typedoc \"\"\"\n A repository connection;\n it packages a repository with the permissions to access it.\n \"\"\"\n @type tconn :: {ttoken, number} | {ttoken, number}\n\n @type tuser :: BorsNG.GitHub.User.t()\n @type trepo :: BorsNG.GitHub.Repo.t()\n @type tpr :: BorsNG.GitHub.Pr.t()\n @type tstatus :: :ok | :running | :error\n @type trepo_perm :: :admin | :push | :pull\n @type tuser_repo_perms :: %{admin: boolean, push: boolean, pull: boolean}\n @type tcollaborator :: %{user: tuser, perms: tuser_repo_perms}\n @type tcommitter :: %{name: bitstring, email: bitstring}\n\n @spec get_pr_files!(tconn, integer) :: [BorsNG.GitHub.File.t()]\n def get_pr_files!(repo_conn, pr_xref) do\n {:ok, pr} = get_pr_files(repo_conn, pr_xref)\n pr\n end\n\n @spec get_pr_files(tconn, integer) ::\n {:ok, [BorsNG.GitHub.File.t()]} | {:error, term}\n def get_pr_files(repo_conn, pr_xref) do\n GenServer.call(\n BorsNG.GitHub,\n {:get_pr_files, repo_conn, {pr_xref}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n @spec get_pr!(tconn, integer | bitstring) :: BorsNG.GitHub.Pr.t()\n def get_pr!(repo_conn, pr_xref) do\n {:ok, pr} = get_pr(repo_conn, pr_xref)\n pr\n end\n\n @spec get_pr(tconn, integer | bitstring) ::\n {:ok, BorsNG.GitHub.Pr.t()} | {:error, term}\n def get_pr(repo_conn, pr_xref) do\n GenServer.call(\n BorsNG.GitHub,\n {:get_pr, repo_conn, {pr_xref}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n @spec update_pr_base!(tconn, BorsNG.GitHub.Pr.t()) :: BorsNG.GitHub.Pr.t()\n def update_pr_base!(repo_conn, pr) do\n {:ok, pr} = update_pr_base(repo_conn, pr)\n pr\n end\n\n @spec update_pr!(tconn, BorsNG.GitHub.Pr.t()) :: BorsNG.GitHub.Pr.t()\n def update_pr!(repo_conn, pr) do\n {:ok, pr} = update_pr(repo_conn, pr)\n pr\n end\n\n @spec update_pr_base(tconn, BorsNG.GitHub.Pr.t()) ::\n {:ok, BorsNG.GitHub.Pr.t()} | {:error, term}\n def update_pr_base(repo_conn, pr) do\n GenServer.call(\n BorsNG.GitHub,\n {:update_pr_base, repo_conn, pr},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n @spec update_pr(tconn, BorsNG.GitHub.Pr.t()) ::\n {:ok, BorsNG.GitHub.Pr.t()} | {:error, term}\n def update_pr(repo_conn, pr) do\n GenServer.call(\n BorsNG.GitHub,\n {:update_pr, repo_conn, pr},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n @spec get_pr_commits!(tconn, integer | bitstring) :: [BorsNG.GitHub.Commit.t()]\n def get_pr_commits!(repo_conn, pr_xref) do\n {:ok, commits} = get_pr_commits(repo_conn, pr_xref)\n commits\n end\n\n @spec get_pr_commits(tconn, integer | bitstring) ::\n {:ok, [BorsNG.GitHub.Commit.t()]} | {:error, term}\n def get_pr_commits(repo_conn, pr_xref) do\n GenServer.call(\n BorsNG.GitHub,\n {:get_pr_commits, repo_conn, {pr_xref}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n @spec get_open_prs!(tconn) :: [tpr]\n def get_open_prs!(repo_conn) do\n {:ok, prs} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_open_prs, repo_conn, {}},\n 100_000\n )\n\n prs\n end\n\n @spec get_open_prs_with_base!(tconn, binary) :: [tpr]\n def get_open_prs_with_base!(repo_conn, base) do\n {:ok, prs} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_open_prs_with_base, repo_conn, {base}},\n 100_000\n )\n\n prs\n end\n\n @spec push!(tconn, binary, binary) :: binary\n def push!(repo_conn, sha, to) do\n {:ok, sha} =\n GenServer.call(\n BorsNG.GitHub,\n {:push, repo_conn, {sha, to}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n sha\n end\n\n @spec push(tconn, binary, binary) :: {:ok, binary} | {:error, term, term, term}\n def push(repo_conn, sha, to) do\n GenServer.call(\n BorsNG.GitHub,\n {:push, repo_conn, {sha, to}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n @spec get_branch!(tconn, binary) :: %{commit: bitstring, tree: bitstring}\n def get_branch!(repo_conn, from) do\n {:ok, commit} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_branch, repo_conn, {from}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n commit\n end\n\n @spec delete_branch!(tconn, binary) :: :ok\n def delete_branch!(repo_conn, branch) do\n :ok =\n GenServer.call(\n BorsNG.GitHub,\n {:delete_branch, repo_conn, {branch}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n :ok\n end\n\n @spec merge_branch!(tconn, %{\n from: bitstring,\n to: bitstring,\n commit_message: bitstring\n }) :: %{commit: binary, tree: binary} | :conflict\n def merge_branch!(repo_conn, info) do\n {:ok, commit} =\n GenServer.call(\n BorsNG.GitHub,\n {:merge_branch, repo_conn, {info}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n commit\n end\n\n @spec synthesize_commit!(tconn, %{\n branch: bitstring,\n tree: bitstring,\n parents: [bitstring],\n commit_message: bitstring,\n committer: tcommitter | nil\n }) :: binary\n def synthesize_commit!(repo_conn, info) do\n {:ok, sha} =\n GenServer.call(\n BorsNG.GitHub,\n {:synthesize_commit, repo_conn, {info}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n sha\n end\n\n @spec create_commit!(tconn, %{\n tree: bitstring,\n parents: [bitstring],\n commit_message: bitstring,\n committer: tcommitter | nil\n }) :: binary\n def create_commit!(repo_conn, info) do\n {:ok, sha} =\n GenServer.call(\n BorsNG.GitHub,\n {:create_commit, repo_conn, {info}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n sha\n end\n\n @spec create_commit(tconn, %{\n tree: bitstring,\n parents: [bitstring],\n commit_message: bitstring,\n committer: tcommitter | nil\n }) :: {:ok, binary} | {:error, term, term}\n def create_commit(repo_conn, info) do\n GenServer.call(\n BorsNG.GitHub,\n {:create_commit, repo_conn, {info}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n @spec force_push!(tconn, binary, binary) :: binary\n def force_push!(repo_conn, sha, to) do\n {:ok, sha} =\n GenServer.call(\n BorsNG.GitHub,\n {:force_push, repo_conn, {sha, to}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n sha\n end\n\n @spec get_commit_status!(tconn, binary) :: %{\n binary => tstatus\n }\n def get_commit_status!(repo_conn, sha) do\n {:ok, status} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_commit_status, repo_conn, {sha}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n status\n end\n\n @spec get_labels!(tconn, integer | bitstring) :: [bitstring]\n def get_labels!(repo_conn, issue_xref) do\n {:ok, labels} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_labels, repo_conn, {issue_xref}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n labels\n end\n\n @spec get_reviews!(tconn, integer | bitstring) :: map\n def get_reviews!(repo_conn, issue_xref) do\n {:ok, labels} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_reviews, repo_conn, {issue_xref}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n labels\n end\n\n @spec get_commit_reviews!(tconn, integer | bitstring, binary) :: map\n def get_commit_reviews!(repo_conn, issue_xref, sha) do\n {:ok, labels} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_reviews, repo_conn, {issue_xref, sha}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n labels\n end\n\n @spec get_file!(tconn, binary, binary) :: binary | nil\n def get_file!(repo_conn, branch, path) do\n {:ok, file} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_file, repo_conn, {branch, path}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n file\n end\n\n @spec post_comment!(tconn, number, binary) :: :ok\n def post_comment!(repo_conn, number, body) do\n :ok =\n GenServer.call(\n BorsNG.GitHub,\n {:post_comment, repo_conn, {number, body}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n :ok\n end\n\n @spec post_commit_status!(tconn, {binary, tstatus, binary, binary}) :: :ok\n def post_commit_status!(repo_conn, {sha, status, msg, url}) do\n # Auto-retry\n first_try =\n GenServer.call(\n BorsNG.GitHub,\n {:post_commit_status, repo_conn, {sha, status, msg, url}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n case first_try do\n :ok ->\n :ok\n\n _ ->\n Process.sleep(11)\n\n :ok =\n GenServer.call(\n BorsNG.GitHub,\n {:post_commit_status, repo_conn, {sha, status, msg, url}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n :ok\n end\n\n @spec get_user_by_login!(ttoken, binary) :: {:ok, tuser} | :error | nil\n def get_user_by_login!(token, login) do\n {:ok, user} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_user_by_login, token, {String.trim(login)}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n\n user\n end\n\n @spec belongs_to_team?(tconn, String.t(), String.t(), String.t()) ::\n boolean\n def belongs_to_team?(repo_conn, org, team_slug, username) do\n GenServer.call(\n BorsNG.GitHub,\n {:belongs_to_team, repo_conn, {org, team_slug, username}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n @spec get_collaborators_by_repo(tconn) ::\n {:ok, [tcollaborator]} | :error\n def get_collaborators_by_repo(repo_conn) do\n GenServer.call(\n BorsNG.GitHub,\n {:get_collaborators_by_repo, repo_conn, {}},\n Confex.fetch_env!(:bors, :api_github_timeout)\n )\n end\n\n @spec get_app!() :: String.t()\n def get_app! do\n {:ok, app_link} =\n GenServer.call(BorsNG.GitHub, :get_app, Confex.fetch_env!(:bors, :api_github_timeout))\n\n app_link\n end\n\n @spec get_installation_repos!(ttoken) :: [trepo]\n def get_installation_repos!(token) do\n {:ok, repos} =\n GenServer.call(\n BorsNG.GitHub,\n {:get_installation_repos, token, {}},\n 100_000\n )\n\n repos\n end\n\n @spec get_installation_list! :: [integer]\n def get_installation_list! do\n {:ok, installations} =\n GenServer.call(\n BorsNG.GitHub,\n :get_installation_list,\n 100_000\n )\n\n installations\n end\n\n @spec map_state_to_status(binary) :: tstatus\n def map_state_to_status(state) do\n case state do\n \"pending\" -> :running\n \"success\" -> :ok\n \"neutral\" -> :ok\n \"failure\" -> :error\n \"error\" -> :error\n end\n end\n\n @spec map_check_to_status(binary) :: tstatus\n def map_check_to_status(conclusion) do\n case conclusion do\n nil -> :running\n \"success\" -> :ok\n _ -> :error\n end\n end\n\n @spec map_status_to_state(tstatus) :: binary\n def map_status_to_state(state) do\n case state do\n :running -> \"pending\"\n :ok -> \"success\"\n :error -> \"failure\"\n end\n end\n\n @spec map_changed_status(binary) :: binary\n def map_changed_status(check_name) do\n case check_name do\n \"Travis CI - Branch\" -> \"continuous-integration\/travis-ci\/push\"\n check_name -> check_name\n end\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"b32bf4d697651fbb2613bf3b405ab04d007998eb","subject":"Use Ecto.Type if possible to provide new callbacks (#108)","message":"Use Ecto.Type if possible to provide new callbacks (#108)\n\nCloses #107 and prevents other issues of its type through\r\n`use Ecto.Type` if available to provide default implementations\r\nof `c:embed_as\/1`, `c:equal\/1`, and anything else they add later\r\nthat's backward-compatible.\r\n\r\nRemoves compilation warning for Ecto 3.2 or above, but not necessary for\r\ncorrect operation because `embed_as\/2` checks before calling.","repos":"koudelka\/honeydew","old_file":"lib\/honeydew\/sources\/ecto\/erlang_term.ex","new_file":"lib\/honeydew\/sources\/ecto\/erlang_term.ex","new_contents":"if Code.ensure_loaded?(Ecto) do\n defmodule Honeydew.EctoSource.ErlangTerm do\n @moduledoc false\n\n if macro_exported?(Ecto.Type, :__using__, 1) do\n use Ecto.Type\n else\n @behaviour Ecto.Type\n end\n\n @impl true\n def type, do: :binary\n\n @impl true\n def cast(term) do\n {:ok, term}\n end\n\n @impl true\n def load(binary) when is_binary(binary) do\n {:ok, :erlang.binary_to_term(binary)}\n end\n\n @impl true\n def dump(term) do\n {:ok, :erlang.term_to_binary(term)}\n end\n end\nend\n","old_contents":"if Code.ensure_loaded?(Ecto) do\n defmodule Honeydew.EctoSource.ErlangTerm do\n @moduledoc false\n\n @behaviour Ecto.Type\n\n @impl true\n def type, do: :binary\n\n @impl true\n def cast(term) do\n {:ok, term}\n end\n\n @impl true\n def load(binary) when is_binary(binary) do\n {:ok, :erlang.binary_to_term(binary)}\n end\n\n @impl true\n def dump(term) do\n {:ok, :erlang.term_to_binary(term)}\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"4320f86a115b40a507cbb2d5c7cedcd4a546a2b9","subject":"Update controller_helpers.ex","message":"Update controller_helpers.ex\n\nEnsure expired? returns for nil data","repos":"smpallen99\/coherence,ghatighorias\/coherence","old_file":"web\/controllers\/controller_helpers.ex","new_file":"web\/controllers\/controller_helpers.ex","new_contents":"defmodule Coherence.ControllerHelpers do\n @moduledoc \"\"\"\n Common helper functions for Coherence Controllers.\n \"\"\"\n alias Coherence.Config\n require Logger\n import Phoenix.Controller, only: [put_flash: 3, redirect: 2]\n import Plug.Conn, only: [halt: 1]\n alias Coherence.Schema.{Confirmable}\n @lockable_failure \"Failed to update lockable attributes \"\n\n @doc \"\"\"\n Get the MyProject.Router.Helpers module.\n\n Returns the projects Router.Helpers module.\n \"\"\"\n def router_helpers do\n Module.concat(Config.module, Router.Helpers)\n end\n\n @doc \"\"\"\n Get the configured logged_out_url.\n \"\"\"\n def logged_out_url(conn) do\n Config.logged_out_url || Module.concat(Config.module, Router.Helpers).session_path(conn, :new)\n end\n\n @doc \"\"\"\n Get the configured logged_in_url.\n \"\"\"\n def logged_in_url(_conn) do\n Config.logged_in_url || \"\/\"\n end\n\n @doc \"\"\"\n Get a random string of given length.\n\n Returns a random url safe encoded64 string of the given length.\n Used to generate tokens for the various modules that require unique tokens.\n \"\"\"\n def random_string(length) do\n :crypto.strong_rand_bytes(length)\n |> Base.url_encode64\n |> binary_part(0, length)\n end\n\n @doc \"\"\"\n Test if a datetime has expired.\n\n Convert the datetime from Ecto.DateTime format to Timex format to do\n the comparison given the time during in opts.\n\n ## Examples\n\n expired?(user.expire_at, days: 5)\n expired?(user.expire_at, minutes: 10)\n \"\"\"\n def expired?(nil, _), do: true\n def expired?(datetime, opts) do\n expire_on? = datetime\n |> Ecto.DateTime.to_erl\n |> Timex.DateTime.from_erl\n |> Timex.shift(opts)\n not Timex.before?(Timex.DateTime.now, expire_on?)\n end\n\n @doc \"\"\"\n Log an error message when lockable update fails.\n \"\"\"\n def lockable_failure(changeset) do\n Logger.error @lockable_failure <> inspect(changeset.errors)\n end\n\n @doc \"\"\"\n Send a user email.\n\n Sends a user email given the module, model, and url. Logs the email for\n debug purposes.\n\n Note: This function uses an apply to avoid compile warnings if the\n mailer is not selected as an option.\n \"\"\"\n def send_user_email(fun, model, url) do\n email = apply(Module.concat(Config.module, Coherence.UserEmail), fun, [model, url])\n Logger.debug fn -> \"#{fun} email: #{inspect email}\" end\n apply(Module.concat(Config.module, Coherence.Mailer), :deliver, [email])\n end\n\n @doc \"\"\"\n Send confirmation email with token.\n\n If the user supports confirmable, generate a token and send the email.\n \"\"\"\n def send_confirmation(conn, user, user_schema) do\n if user_schema.confirmable? do\n token = random_string 48\n url = router_helpers.confirmation_url(conn, :edit, token)\n Logger.debug \"confirmation email url: #{inspect url}\"\n dt = Ecto.DateTime.utc\n user_schema.changeset(user,\n %{confirmation_token: token, confirmation_sent_at: dt})\n |> Config.repo.update!\n\n send_user_email :confirmation, user, url\n conn\n |> put_flash(:info, \"Confirmation email sent.\")\n else\n conn\n |> put_flash(:info, \"Registration created successfully.\")\n end\n end\n\n #############\n # User Schema\n\n @doc \"\"\"\n Confirm a user account.\n\n Adds the `:confirmed_at` datetime field on the user model and updates the database\n \"\"\"\n def confirm!(user) do\n changeset = Confirmable.confirm(user)\n unless Confirmable.confirmed? user do\n Config.repo.update changeset\n else\n changeset = Ecto.Changeset.add_error changeset, :confirmed_at, \"already confirmed\"\n {:error, changeset}\n end\n end\n\n @doc \"\"\"\n Lock a use account.\n\n Sets the `:locked_at` field on the user model to the current date and time unless\n provided a value for the optional parameter.\n\n You can provide a date in the future to override the configured lock expiry time. You\n can set this data far in the future to do a pseudo permanent lock.\n \"\"\"\n\n def lock!(user, locked_at \\\\ Ecto.DateTime.utc) do\n user_schema = Config.user_schema\n changeset = user_schema.lock user, locked_at\n unless user_schema.locked?(user) do\n changeset\n |> Config.repo.update\n else\n changeset = Ecto.Changeset.add_error changeset, :locked_at, \"already locked\"\n {:error, changeset}\n end\n end\n\n @doc \"\"\"\n Unlock a user account.\n\n Clears the `:locked_at` field on the user model and updates the database.\n \"\"\"\n def unlock!(user) do\n user_schema = Config.user_schema\n changeset = user_schema.unlock user\n if user_schema.locked?(user) do\n changeset\n |> Config.repo.update\n else\n changeset = Ecto.Changeset.add_error changeset, :locked_at, \"not locked\"\n {:error, changeset}\n end\n end\n\n\n @doc \"\"\"\n Plug to redirect already logged in users.\n \"\"\"\n def redirect_logged_in(conn, _params) do\n if Coherence.logged_in?(conn) do\n conn\n |> put_flash(:info, \"Already logged in.\" )\n |> redirect(to: logged_in_url(conn))\n |> halt\n else\n conn\n end\n end\n\n def redirect_to(conn, path, params) do\n apply(Coherence.Redirects, path, [conn, params])\n end\n def redirect_to(conn, path, params, user) do\n apply(Coherence.Redirects, path, [conn, params, user])\n end\n\n def changeset(which, module, model, params \\\\ %{}) do\n {mod, fun, args} = case Application.get_env :coherence, :changeset do\n nil -> {module, :changeset, [model, params]}\n {mod, fun} -> {mod, fun, [model, params, which]}\n end\n apply mod, fun, args\n end\n\n @doc \"\"\"\n Login a user.\n\n Logs in a user and redirects them to the session_create page.\n \"\"\"\n def login_user(conn, user, params) do\n apply(Config.auth_module, Config.create_login, [conn, user, [id_key: Config.schema_key]])\n |> track_login(user, Config.user_schema.trackable?)\n |> redirect_to(:session_create, params)\n end\n\n @doc \"\"\"\n Track user login details.\n\n Saves the ip address and timestamp when the user logs in.\n \"\"\"\n def track_login(conn, _, false), do: conn\n def track_login(conn, user, true) do\n ip = conn.peer |> elem(0) |> inspect\n now = Ecto.DateTime.utc\n {last_at, last_ip} = cond do\n is_nil(user.last_sign_in_at) and is_nil(user.current_sign_in_at) ->\n {now, ip}\n !!user.current_sign_in_at ->\n {user.current_sign_in_at, user.current_sign_in_ip}\n true ->\n {user.last_sign_in_at, user.last_sign_in_ip}\n end\n\n changeset(:session, user.__struct__, user,\n %{\n sign_in_count: user.sign_in_count + 1,\n current_sign_in_at: Ecto.DateTime.utc,\n current_sign_in_ip: ip,\n last_sign_in_at: last_at,\n last_sign_in_ip: last_ip\n })\n |> Config.repo.update\n |> case do\n {:ok, _} -> nil\n {:error, _changeset} ->\n Logger.error (\"Failed to update tracking!\")\n end\n conn\n end\n\n\nend\n","old_contents":"defmodule Coherence.ControllerHelpers do\n @moduledoc \"\"\"\n Common helper functions for Coherence Controllers.\n \"\"\"\n alias Coherence.Config\n require Logger\n import Phoenix.Controller, only: [put_flash: 3, redirect: 2]\n import Plug.Conn, only: [halt: 1]\n alias Coherence.Schema.{Confirmable}\n @lockable_failure \"Failed to update lockable attributes \"\n\n @doc \"\"\"\n Get the MyProject.Router.Helpers module.\n\n Returns the projects Router.Helpers module.\n \"\"\"\n def router_helpers do\n Module.concat(Config.module, Router.Helpers)\n end\n\n @doc \"\"\"\n Get the configured logged_out_url.\n \"\"\"\n def logged_out_url(conn) do\n Config.logged_out_url || Module.concat(Config.module, Router.Helpers).session_path(conn, :new)\n end\n\n @doc \"\"\"\n Get the configured logged_in_url.\n \"\"\"\n def logged_in_url(_conn) do\n Config.logged_in_url || \"\/\"\n end\n\n @doc \"\"\"\n Get a random string of given length.\n\n Returns a random url safe encoded64 string of the given length.\n Used to generate tokens for the various modules that require unique tokens.\n \"\"\"\n def random_string(length) do\n :crypto.strong_rand_bytes(length)\n |> Base.url_encode64\n |> binary_part(0, length)\n end\n\n @doc \"\"\"\n Test if a datetime has expired.\n\n Convert the datetime from Ecto.DateTime format to Timex format to do\n the comparison given the time during in opts.\n\n ## Examples\n\n expired?(user.expire_at, days: 5)\n expired?(user.expire_at, minutes: 10)\n \"\"\"\n def expired?(datetime, opts) do\n expire_on? = datetime\n |> Ecto.DateTime.to_erl\n |> Timex.DateTime.from_erl\n |> Timex.shift(opts)\n not Timex.before?(Timex.DateTime.now, expire_on?)\n end\n\n @doc \"\"\"\n Log an error message when lockable update fails.\n \"\"\"\n def lockable_failure(changeset) do\n Logger.error @lockable_failure <> inspect(changeset.errors)\n end\n\n @doc \"\"\"\n Send a user email.\n\n Sends a user email given the module, model, and url. Logs the email for\n debug purposes.\n\n Note: This function uses an apply to avoid compile warnings if the\n mailer is not selected as an option.\n \"\"\"\n def send_user_email(fun, model, url) do\n email = apply(Module.concat(Config.module, Coherence.UserEmail), fun, [model, url])\n Logger.debug fn -> \"#{fun} email: #{inspect email}\" end\n apply(Module.concat(Config.module, Coherence.Mailer), :deliver, [email])\n end\n\n @doc \"\"\"\n Send confirmation email with token.\n\n If the user supports confirmable, generate a token and send the email.\n \"\"\"\n def send_confirmation(conn, user, user_schema) do\n if user_schema.confirmable? do\n token = random_string 48\n url = router_helpers.confirmation_url(conn, :edit, token)\n Logger.debug \"confirmation email url: #{inspect url}\"\n dt = Ecto.DateTime.utc\n user_schema.changeset(user,\n %{confirmation_token: token, confirmation_sent_at: dt})\n |> Config.repo.update!\n\n send_user_email :confirmation, user, url\n conn\n |> put_flash(:info, \"Confirmation email sent.\")\n else\n conn\n |> put_flash(:info, \"Registration created successfully.\")\n end\n end\n\n #############\n # User Schema\n\n @doc \"\"\"\n Confirm a user account.\n\n Adds the `:confirmed_at` datetime field on the user model and updates the database\n \"\"\"\n def confirm!(user) do\n changeset = Confirmable.confirm(user)\n unless Confirmable.confirmed? user do\n Config.repo.update changeset\n else\n changeset = Ecto.Changeset.add_error changeset, :confirmed_at, \"already confirmed\"\n {:error, changeset}\n end\n end\n\n @doc \"\"\"\n Lock a use account.\n\n Sets the `:locked_at` field on the user model to the current date and time unless\n provided a value for the optional parameter.\n\n You can provide a date in the future to override the configured lock expiry time. You\n can set this data far in the future to do a pseudo permanent lock.\n \"\"\"\n\n def lock!(user, locked_at \\\\ Ecto.DateTime.utc) do\n user_schema = Config.user_schema\n changeset = user_schema.lock user, locked_at\n unless user_schema.locked?(user) do\n changeset\n |> Config.repo.update\n else\n changeset = Ecto.Changeset.add_error changeset, :locked_at, \"already locked\"\n {:error, changeset}\n end\n end\n\n @doc \"\"\"\n Unlock a user account.\n\n Clears the `:locked_at` field on the user model and updates the database.\n \"\"\"\n def unlock!(user) do\n user_schema = Config.user_schema\n changeset = user_schema.unlock user\n if user_schema.locked?(user) do\n changeset\n |> Config.repo.update\n else\n changeset = Ecto.Changeset.add_error changeset, :locked_at, \"not locked\"\n {:error, changeset}\n end\n end\n\n\n @doc \"\"\"\n Plug to redirect already logged in users.\n \"\"\"\n def redirect_logged_in(conn, _params) do\n if Coherence.logged_in?(conn) do\n conn\n |> put_flash(:info, \"Already logged in.\" )\n |> redirect(to: logged_in_url(conn))\n |> halt\n else\n conn\n end\n end\n\n def redirect_to(conn, path, params) do\n apply(Coherence.Redirects, path, [conn, params])\n end\n def redirect_to(conn, path, params, user) do\n apply(Coherence.Redirects, path, [conn, params, user])\n end\n\n def changeset(which, module, model, params \\\\ %{}) do\n {mod, fun, args} = case Application.get_env :coherence, :changeset do\n nil -> {module, :changeset, [model, params]}\n {mod, fun} -> {mod, fun, [model, params, which]}\n end\n apply mod, fun, args\n end\n\n @doc \"\"\"\n Login a user.\n\n Logs in a user and redirects them to the session_create page.\n \"\"\"\n def login_user(conn, user, params) do\n apply(Config.auth_module, Config.create_login, [conn, user, [id_key: Config.schema_key]])\n |> track_login(user, Config.user_schema.trackable?)\n |> redirect_to(:session_create, params)\n end\n\n @doc \"\"\"\n Track user login details.\n\n Saves the ip address and timestamp when the user logs in.\n \"\"\"\n def track_login(conn, _, false), do: conn\n def track_login(conn, user, true) do\n ip = conn.peer |> elem(0) |> inspect\n now = Ecto.DateTime.utc\n {last_at, last_ip} = cond do\n is_nil(user.last_sign_in_at) and is_nil(user.current_sign_in_at) ->\n {now, ip}\n !!user.current_sign_in_at ->\n {user.current_sign_in_at, user.current_sign_in_ip}\n true ->\n {user.last_sign_in_at, user.last_sign_in_ip}\n end\n\n changeset(:session, user.__struct__, user,\n %{\n sign_in_count: user.sign_in_count + 1,\n current_sign_in_at: Ecto.DateTime.utc,\n current_sign_in_ip: ip,\n last_sign_in_at: last_at,\n last_sign_in_ip: last_ip\n })\n |> Config.repo.update\n |> case do\n {:ok, _} -> nil\n {:error, _changeset} ->\n Logger.error (\"Failed to update tracking!\")\n end\n conn\n end\n\n\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"56c0661b491fca6db6f4d75d28aef06f704cb5e8","subject":"Emails now use a proper to: field","message":"Emails now use a proper to: field\n\nCloses #302\n","repos":"vutuv\/vutuv,vutuv\/vutuv","old_file":"lib\/vutuv\/emailer.ex","new_file":"lib\/vutuv\/emailer.ex","new_contents":"defmodule Vutuv.Emailer do\n import Bamboo.Email\n require Vutuv.Gettext\n use Bamboo.Phoenix, view: Vutuv.EmailView\n\n def login_email(link, email, user) do\n gen_email(link, email, user, \"login_email_#{if (user.locale), do: user.locale, else: \"en\"}\")\n end\n\n def email_creation_email(link, email, user) do\n gen_email(link, email, user,\"email_creation_email_#{if (user.locale), do: user.locale, else: \"en\"}\")\n end\n\n def user_deletion_email(link, email, user) do\n gen_email(link, email, user,\"user_deletion_email_#{if (user.locale), do: user.locale, else: \"en\"}\")\n end\n\n defp gen_email(link, email, user, template) do\n url = Application.get_env(:vutuv, Vutuv.Endpoint)[:public_url]\n\n new_email\n |> put_text_layout({Vutuv.EmailView, \"#{template}.text\"})\n |> assign(:link, link)\n |> assign(:url, url)\n |> assign(:user, user)\n |> to(\"#{Vutuv.UserHelpers.full_name(user)} <#{email}>\")\n |> from(\"vutuv \")\n |> subject(Vutuv.Gettext.gettext(\"vutuv verification email\"))\n |> render(\"#{template}.text\")\n end\nend\n","old_contents":"defmodule Vutuv.Emailer do\n import Bamboo.Email\n require Vutuv.Gettext\n use Bamboo.Phoenix, view: Vutuv.EmailView\n\n def login_email(link, email, user) do\n gen_email(link, email, user, \"login_email_#{if (user.locale), do: user.locale, else: \"en\"}\")\n end\n\n def email_creation_email(link, email, user) do\n gen_email(link, email, user,\"email_creation_email_#{if (user.locale), do: user.locale, else: \"en\"}\")\n end\n\n def user_deletion_email(link, email, user) do\n gen_email(link, email, user,\"user_deletion_email_#{if (user.locale), do: user.locale, else: \"en\"}\")\n end\n\n defp gen_email(link, email, user, template) do\n url = Application.get_env(:vutuv, Vutuv.Endpoint)[:public_url]\n\n new_email\n |> put_text_layout({Vutuv.EmailView, \"#{template}.text\"})\n |> assign(:link, link)\n |> assign(:url, url)\n |> assign(:user, user)\n |> to(email)\n |> from(\"vutuv \")\n |> subject(Vutuv.Gettext.gettext(\"vutuv verification email\"))\n |> render(\"#{template}.text\")\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"d35cb77455741654447283e60cb298d3b8be8333","subject":"Raise when attempting to prepare simple query","message":"Raise when attempting to prepare simple query\n","repos":"lexhide\/xandra","old_file":"lib\/xandra\/simple.ex","new_file":"lib\/xandra\/simple.ex","new_contents":"defmodule Xandra.Simple do\n @moduledoc false\n\n defstruct [:statement, :values]\n\n @opaque t :: %__MODULE__{\n statement: Xandra.statement,\n values: Xandra.values | nil,\n }\n\n defimpl DBConnection.Query do\n alias Xandra.{Frame, Protocol}\n\n def parse(query, _options) do\n raise \"cannot prepare #{inspect(query)}\"\n end\n\n def encode(query, values, options) do\n Frame.new(:query)\n |> Protocol.encode_request(%{query | values: values}, options)\n |> Frame.encode(options[:compressor])\n end\n\n def decode(query, %Frame{} = frame, _options) do\n Protocol.decode_response(frame, query)\n end\n\n def describe(query, _options) do\n raise \"cannot prepare #{inspect(query)}\"\n end\n end\nend\n","old_contents":"defmodule Xandra.Simple do\n @moduledoc false\n\n defstruct [:statement, :values]\n\n @opaque t :: %__MODULE__{\n statement: Xandra.statement,\n values: Xandra.values | nil,\n }\n\n defimpl DBConnection.Query do\n alias Xandra.{Frame, Protocol}\n\n def parse(query, _options) do\n query\n end\n\n def encode(query, values, options) do\n Frame.new(:query)\n |> Protocol.encode_request(%{query | values: values}, options)\n |> Frame.encode(options[:compressor])\n end\n\n def decode(query, %Frame{} = frame, _options) do\n Protocol.decode_response(frame, query)\n end\n\n def describe(query, _options) do\n query\n end\n end\nend\n","returncode":0,"stderr":"","license":"isc","lang":"Elixir"} {"commit":"150e87d1be869cb712e1340d4ac36e2f74a5ff78","subject":"tidy up","message":"tidy up\n","repos":"highmobility\/bluex","old_file":"lib\/bluex\/dbus_discovery.ex","new_file":"lib\/bluex\/dbus_discovery.ex","new_contents":"defmodule Bluex.DBusDiscovery do\n @callback device_found(%Bluex.Device{}) :: :ok | :ignore | :error\n\n @dbus_name Application.get_env(:bluex, :dbus_name)\n @iface_dbus_name Application.get_env(:bluex, :iface_dbus_name)\n @device_dbus_name Application.get_env(:bluex, :device_dbus_name)\n @dbus_bluez_path Application.get_env(:bluex, :dbus_bluez_path)\n @dbus_type Application.get_env(:bluex, :bus_type)\n\n use GenServer\n\n @doc \"\"\"\n Gets list of adapters\n \"\"\"\n def get_adapters(pid) do\n GenServer.call(pid, :get_adapters)\n end\n\n @doc \"\"\"\n Gets list of devices\n \"\"\"\n def get_devices(pid) do\n GenServer.call(pid, :get_devices)\n end\n\n @doc false\n def device_found(pid, device) do\n GenServer.cast(pid, {:device_found, device})\n end\n\n def start_link(module, opts \\\\ []) do\n GenServer.start_link(__MODULE__, [module, opts], name: module)\n end\n\n @doc \"\"\"\n Starts Bluetooth discovery\n \"\"\"\n def start_discovery(pid) do\n GenServer.cast(pid, :start_discovery)\n end\n\n @doc false\n def init([module, opts]) do\n {:ok, bus} = :dbus_bus_connection.connect(@dbus_type)\n {:ok, adapter_manager} = :dbus_proxy.start_link(bus, @dbus_name, @dbus_bluez_path)\n {:ok, bluez_manager} = :dbus_proxy.start_link(bus, @dbus_name, \"\/\")\n\n {:ok, %{bus: bus, adapter_manager: adapter_manager, devices: [], adapters: [], bluez_manager: bluez_manager, module: module}}\n end\n\n @doc false\n def handle_call(:get_adapters, _, state) do\n {:reply, state[:adapters], state}\n end\n\n @doc false\n def handle_call(:get_devices, _, state) do\n {:reply, state[:devices], state}\n end\n\n @doc false\n def handle_info({:dbus_signal, _}, state) do\n GenServer.cast(state[:module], :get_adapters)\n {:noreply, state}\n end\n\n @doc false\n def handle_cast(:get_adapters, state) do\n adapters = :dbus_proxy.children(state[:adapter_manager])\n |> Stream.map(&Path.basename\/1)\n |> Stream.map(fn (adapter) ->\n bluez_path = \"#{@dbus_bluez_path}\/#{adapter}\"\n {:ok, adapter_proxy} = :dbus_proxy.start_link(state[:bus], @dbus_name, bluez_path)\n :dbus_proxy.has_interface(adapter_proxy, @iface_dbus_name)\n {adapter, %{path: bluez_path, proxy: adapter_proxy}}\n end)\n |> Stream.filter(fn ({_, %{proxy: adapter_proxy}}) ->\n #TODO close invalid adapter\n :dbus_proxy.has_interface(adapter_proxy, @iface_dbus_name)\n end)\n |> Enum.into(%{})\n\n state = Map.put(state, :adapters, adapters)\n {:noreply, state}\n end\n\n @doc false\n def handle_cast(:start_discovery, state) do\n #TODO: ???get list of devices now and call the device_found callback before leaving this function\n add_interface = fn(sender, \"org.freedesktop.DBus.ObjectManager\", \"InterfacesAdded\", path, args, pid) ->\n case args do\n {interface_bluez_path, %{@device_dbus_name => device_details}} ->\n device = %Bluex.Device{mac_address: device_details[\"Address\"], manufacturer_data: device_details[\"ManufacturerData\"], rssi: device_details[\"RSSI\"], uuids: device_details[\"UUIDs\"], adapter: \"hci1\"}\n Bluex.DBusDiscovery.device_found(pid, device)\n _ -> :ok\n end\n end\n :dbus_proxy.connect_signal(state[:bluez_manager],\n \"org.freedesktop.DBus.ObjectManager\",\n \"InterfacesAdded\",\n {add_interface, self})\n :dbus_proxy.children(state[:bluez_manager])\n state[:adapters]\n |> Enum.each(fn ({_, %{proxy: adapter_proxy}}) ->\n #TODO: to filter_services\n #:ok = :dbus_proxy.call(adapter_proxy, @iface_dbus_name, \"SetDiscoveryFilter\", [%{\"UUIDs\" => [\"5842aec9-3aee-a150-5a8c-159d686d6363\"]}])\n :ok = :dbus_proxy.call(adapter_proxy, @iface_dbus_name, \"StartDiscovery\", [])\n end)\n {:noreply, state}\n end\n\n @doc false\n def handle_cast({:device_found, device}, state) do\n state = case apply(state[:module], :device_found, [device]) do\n :ok ->\n Map.put(state, :devices, [device])\n _ ->\n state\n end\n {:noreply, state}\n end\n\n defmacro __using__(opts) do\n quote [unquote: false, location: :keep] do\n @behaviour Bluex.DBusDiscovery\n import Bluex.DBusDiscovery\n use GenServer\n\n @doc false\n def start_link do\n Bluex.DBusDiscovery.start_link(__MODULE__, [])\n end\n\n @doc \"\"\"\n Starts Bluetooth discovery\n \"\"\"\n def start_discovery do\n Bluex.DBusDiscovery.start_discovery(__MODULE__)\n end\n end\n end\nend\n","old_contents":"defmodule Bluex.DBusDiscovery do\n @callback device_found(%Bluex.Device{}) :: :ok | :ignore | :error\n\n @dbus_name Application.get_env(:bluex, :dbus_name)\n @iface_dbus_name Application.get_env(:bluex, :iface_dbus_name)\n @device_dbus_name Application.get_env(:bluex, :device_dbus_name)\n @dbus_bluez_path Application.get_env(:bluex, :dbus_bluez_path)\n @dbus_type Application.get_env(:bluex, :bus_type)\n\n use GenServer\n\n @doc \"\"\"\n Gets list of adapters\n \"\"\"\n def get_adapters(pid) do\n GenServer.call(pid, :get_adapters)\n end\n\n @doc \"\"\"\n Gets list of devices\n \"\"\"\n def get_devices(pid) do\n GenServer.call(pid, :get_devices)\n end\n\n @doc false\n def device_found(pid, device) do\n GenServer.cast(pid, {:device_found, device})\n end\n\n def start_link(module, opts \\\\ []) do\n GenServer.start_link(__MODULE__, [module, opts], name: module)\n end\n\n @doc \"\"\"\n Starts Bluetooth discovery\n \"\"\"\n def start_discovery(pid) do\n GenServer.cast(pid, :start_discovery)\n end\n\n @doc false\n def init([module, opts]) do\n {:ok, bus} = :dbus_bus_connection.connect(@dbus_type)\n {:ok, adapter_manager} = :dbus_proxy.start_link(bus, @dbus_name, @dbus_bluez_path)\n {:ok, bluez_manager} = :dbus_proxy.start_link(bus, @dbus_name, \"\/\")\n\n {:ok, %{bus: bus, adapter_manager: adapter_manager, devices: [], adapters: [], bluez_manager: bluez_manager, module: module}}\n end\n\n @doc false\n def handle_call(:get_adapters, _, state) do\n {:reply, state[:adapters], state}\n end\n\n @doc false\n def handle_call(:get_devices, _, state) do\n {:reply, state[:devices], state}\n end\n\n @doc false\n def handle_info({:dbus_signal, _}, state) do\n GenServer.cast(state[:module], :get_adapters)\n {:noreply, state}\n end\n\n @doc false\n def handle_cast(:get_adapters, state) do\n adapters = :dbus_proxy.children(state[:adapter_manager])\n |> Stream.map(&Path.basename\/1)\n |> Stream.map(fn (adapter) ->\n bluez_path = \"#{@dbus_bluez_path}\/#{adapter}\"\n {:ok, adapter_proxy} = :dbus_proxy.start_link(state[:bus], @dbus_name, bluez_path)\n :dbus_proxy.has_interface(adapter_proxy, @iface_dbus_name)\n {adapter, %{path: bluez_path, proxy: adapter_proxy}}\n end)\n |> Stream.filter(fn ({_, %{proxy: adapter_proxy}}) ->\n #TODO close invalid adapter\n :dbus_proxy.has_interface(adapter_proxy, @iface_dbus_name)\n end)\n |> Enum.into(%{})\n\n state = Map.put(state, :adapters, adapters)\n {:noreply, state}\n end\n\n #path: \"\/\", args: {\"\/org\/bluez\/hci1\/dev_C0_CB_38_EB_74_13\", %{\"org.bluez.Device1\" => %{\"Adapter\" => \"\/org\/bluez\/hci1\", \"Address\" => \"C0:CB:38:EB:74:13\", \"Alias\" => \"ubuntu-0\", \"Blocked\" => false, \"Class\" => 7078144, \"Connected\" => false, \"Icon\" => \"computer\", \"LegacyPairing\" => false, \"Name\" => \"ubuntu-0\", \"Paired\" => false, \"RSSI\" => -71, \"Trusted\" => false, \"TxPower\" => 0, \"UUIDs\" => [\"0000112d-0000-1000-8000-00805f9b34fb\", \"00001112-0000-1000-8000-00805f9b34fb\", \"0000111f-0000-1000-8000-00805f9b34fb\", \"0000111e-0000-1000-8000-00805f9b34fb\", \"0000110c-0000-1000-8000-00805f9b34fb\", \"0000110e-0000-1000-8000-00805f9b34fb\", \"0000110a-0000-1000-8000-00805f9b34fb\", \"0000110b-0000-1000-8000-00805f9b34fb\"]}, \"org.freedesktop.DBus.Introspectable\" => %{}, \"org.freedesktop.DBus.Properties\" => %{}}}\n\n @doc false\n def handle_cast(:start_discovery, state) do\n #TODO: ???get list of devices now and call the device_found callback before leaving this function\n add_interface = fn(sender, \"org.freedesktop.DBus.ObjectManager\", \"InterfacesAdded\", path, args, pid) ->\n case args do\n {interface_bluez_path, %{@device_dbus_name => device_details}} ->\n device = %Bluex.Device{mac_address: device_details[\"Address\"], manufacturer_data: device_details[\"ManufacturerData\"], rssi: device_details[\"RSSI\"], uuids: device_details[\"UUIDs\"], adapter: \"hci1\"}\n Bluex.DBusDiscovery.device_found(pid, device)\n _ -> :ok\n end\n end\n :dbus_proxy.connect_signal(state[:bluez_manager],\n \"org.freedesktop.DBus.ObjectManager\",\n \"InterfacesAdded\",\n {add_interface, self})\n :dbus_proxy.children(state[:bluez_manager])\n state[:adapters]\n |> Enum.each(fn ({_, %{proxy: adapter_proxy}}) ->\n #TODO: to filter_services\n #:ok = :dbus_proxy.call(adapter_proxy, @iface_dbus_name, \"SetDiscoveryFilter\", [%{\"UUIDs\" => [\"5842aec9-3aee-a150-5a8c-159d686d6363\"]}])\n :ok = :dbus_proxy.call(adapter_proxy, @iface_dbus_name, \"StartDiscovery\", [])\n end)\n {:noreply, state}\n end\n\n @doc false\n def handle_cast({:device_found, device}, state) do\n state = case apply(state[:module], :device_found, [device]) do\n :ok ->\n Map.put(state, :devices, [device])\n _ ->\n state\n end\n {:noreply, state}\n end\n\n defmacro __using__(opts) do\n quote [unquote: false, location: :keep] do\n @behaviour Bluex.DBusDiscovery\n import Bluex.DBusDiscovery\n use GenServer\n\n @doc false\n def start_link do\n Bluex.DBusDiscovery.start_link(__MODULE__, [])\n end\n\n @doc \"\"\"\n Starts Bluetooth discovery\n \"\"\"\n def start_discovery do\n Bluex.DBusDiscovery.start_discovery(__MODULE__)\n end\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"56da26f0dae1e91169a57aa96979ef030f33a00a","subject":"Use newer child syntax","message":"Use newer child syntax\n","repos":"keathley\/wallaby,keathley\/wallaby","old_file":"lib\/wallaby.ex","new_file":"lib\/wallaby.ex","new_contents":"defmodule Wallaby do\n @moduledoc \"\"\"\n A concurrent feature testing library.\n\n ## Configuration\n\n Wallaby supports the following options:\n\n * `:otp_app` - The name of your OTP application. This is used to check out your Ecto repos into the SQL Sandbox.\n * `:screenshot_dir` - The directory to store screenshots.\n * `:screenshot_on_failure` - if Wallaby should take screenshots on test failures (defaults to `false`).\n * `:max_wait_time` - The amount of time that Wallaby should wait to find an element on the page. (defaults to `3_000`)\n * `:js_errors` - if Wallaby should re-throw javascript errors in elixir (defaults to true).\n * `:js_logger` - IO device where javascript console logs are written to. Defaults to :stdio. This option can also be set to a file or any other io device. You can disable javascript console logging by setting this to `nil`.\n \"\"\"\n\n @drivers %{\n \"chrome\" => Wallaby.Chrome,\n \"selenium\" => Wallaby.Selenium\n }\n\n use Application\n\n alias Wallaby.Session\n alias Wallaby.SessionStore\n\n @doc false\n def start(_type, _args) do\n import Supervisor.Spec, warn: false\n\n case driver().validate() do\n :ok -> :ok\n {:error, exception} -> raise exception\n end\n\n children = [\n {driver(), [name: Wallaby.Driver.Supervisor]},\n :hackney_pool.child_spec(:wallaby_pool, timeout: 15_000, max_connections: 4),\n {Wallaby.SessionStore, [name: Wallaby.SessionStore]}\n ]\n\n opts = [strategy: :one_for_one, name: Wallaby.Supervisor]\n Supervisor.start_link(children, opts)\n end\n\n @type reason :: any\n @type start_session_opts :: {atom, any}\n\n @doc \"\"\"\n Starts a browser session.\n\n ## Multiple sessions\n\n Each session runs in its own browser so that each test runs in isolation.\n Because of this isolation multiple sessions can be created for a test:\n\n ```\n @message_field Query.text_field(\"Share Message\")\n @share_button Query.button(\"Share\")\n @message_list Query.css(\".messages\")\n\n test \"That multiple sessions work\" do\n {:ok, user1} = Wallaby.start_session\n user1\n |> visit(\"\/page.html\")\n |> fill_in(@message_field, with: \"Hello there!\")\n |> click(@share_button)\n\n {:ok, user2} = Wallaby.start_session\n user2\n |> visit(\"\/page.html\")\n |> fill_in(@message_field, with: \"Hello yourself\")\n |> click(@share_button)\n\n assert user1 |> find(@message_list) |> List.last |> text == \"Hello yourself\"\n assert user2 |> find(@message_list) |> List.first |> text == \"Hello there\"\n end\n ```\n \"\"\"\n @spec start_session([start_session_opts]) :: {:ok, Session.t()} | {:error, reason}\n def start_session(opts \\\\ []) do\n with {:ok, session} <- driver().start_session(opts),\n :ok <- SessionStore.monitor(session),\n do: {:ok, session}\n end\n\n @doc \"\"\"\n Ends a browser session.\n \"\"\"\n @spec end_session(Session.t()) :: :ok | {:error, reason}\n def end_session(%Session{driver: driver} = session) do\n with :ok <- SessionStore.demonitor(session),\n :ok <- driver.end_session(session),\n do: :ok\n end\n\n @doc false\n def screenshot_on_failure? do\n Application.get_env(:wallaby, :screenshot_on_failure)\n end\n\n @doc false\n def js_errors? do\n Application.get_env(:wallaby, :js_errors, true)\n end\n\n @doc false\n def js_logger do\n Application.get_env(:wallaby, :js_logger, :stdio)\n end\n\n def driver do\n Map.get(\n @drivers,\n System.get_env(\"WALLABY_DRIVER\"),\n Application.get_env(:wallaby, :driver, Wallaby.Chrome)\n )\n end\nend\n","old_contents":"defmodule Wallaby do\n @moduledoc \"\"\"\n A concurrent feature testing library.\n\n ## Configuration\n\n Wallaby supports the following options:\n\n * `:otp_app` - The name of your OTP application. This is used to check out your Ecto repos into the SQL Sandbox.\n * `:screenshot_dir` - The directory to store screenshots.\n * `:screenshot_on_failure` - if Wallaby should take screenshots on test failures (defaults to `false`).\n * `:max_wait_time` - The amount of time that Wallaby should wait to find an element on the page. (defaults to `3_000`)\n * `:js_errors` - if Wallaby should re-throw javascript errors in elixir (defaults to true).\n * `:js_logger` - IO device where javascript console logs are written to. Defaults to :stdio. This option can also be set to a file or any other io device. You can disable javascript console logging by setting this to `nil`.\n \"\"\"\n\n @drivers %{\n \"chrome\" => Wallaby.Chrome,\n \"selenium\" => Wallaby.Selenium\n }\n\n use Application\n\n alias Wallaby.Session\n alias Wallaby.SessionStore\n\n @doc false\n def start(_type, _args) do\n import Supervisor.Spec, warn: false\n\n case driver().validate() do\n :ok -> :ok\n {:error, exception} -> raise exception\n end\n\n children = [\n supervisor(Wallaby.Driver.ProcessWorkspace.ServerSupervisor, []),\n supervisor(driver(), [[name: Wallaby.Driver.Supervisor]]),\n :hackney_pool.child_spec(:wallaby_pool, timeout: 15_000, max_connections: 4),\n worker(Wallaby.SessionStore, [])\n ]\n\n opts = [strategy: :one_for_one, name: Wallaby.Supervisor]\n Supervisor.start_link(children, opts)\n end\n\n @type reason :: any\n @type start_session_opts :: {atom, any}\n\n @doc \"\"\"\n Starts a browser session.\n\n ## Multiple sessions\n\n Each session runs in its own browser so that each test runs in isolation.\n Because of this isolation multiple sessions can be created for a test:\n\n ```\n @message_field Query.text_field(\"Share Message\")\n @share_button Query.button(\"Share\")\n @message_list Query.css(\".messages\")\n\n test \"That multiple sessions work\" do\n {:ok, user1} = Wallaby.start_session\n user1\n |> visit(\"\/page.html\")\n |> fill_in(@message_field, with: \"Hello there!\")\n |> click(@share_button)\n\n {:ok, user2} = Wallaby.start_session\n user2\n |> visit(\"\/page.html\")\n |> fill_in(@message_field, with: \"Hello yourself\")\n |> click(@share_button)\n\n assert user1 |> find(@message_list) |> List.last |> text == \"Hello yourself\"\n assert user2 |> find(@message_list) |> List.first |> text == \"Hello there\"\n end\n ```\n \"\"\"\n @spec start_session([start_session_opts]) :: {:ok, Session.t()} | {:error, reason}\n def start_session(opts \\\\ []) do\n with {:ok, session} <- driver().start_session(opts),\n :ok <- SessionStore.monitor(session),\n do: {:ok, session}\n end\n\n @doc \"\"\"\n Ends a browser session.\n \"\"\"\n @spec end_session(Session.t()) :: :ok | {:error, reason}\n def end_session(%Session{driver: driver} = session) do\n with :ok <- SessionStore.demonitor(session),\n :ok <- driver.end_session(session),\n do: :ok\n end\n\n @doc false\n def screenshot_on_failure? do\n Application.get_env(:wallaby, :screenshot_on_failure)\n end\n\n @doc false\n def js_errors? do\n Application.get_env(:wallaby, :js_errors, true)\n end\n\n @doc false\n def js_logger do\n Application.get_env(:wallaby, :js_logger, :stdio)\n end\n\n def driver do\n Map.get(\n @drivers,\n System.get_env(\"WALLABY_DRIVER\"),\n Application.get_env(:wallaby, :driver, Wallaby.Chrome)\n )\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"c4b0d3e26623d3bb0e7f76c297ab58c725f5bdd6","subject":"fix bug in random episode display","message":"fix bug in random episode display\n","repos":"PanoptikumIO\/pan,PanoptikumIO\/pan","old_file":"web\/controllers\/recommendation_frontend_controller.ex","new_file":"web\/controllers\/recommendation_frontend_controller.ex","new_contents":"defmodule Pan.RecommendationFrontendController do\n use Pan.Web, :controller\n use Crutches\n alias Pan.Podcast\n alias Pan.Episode\n alias Pan.Category\n alias Pan.Chapter\n alias Pan.Recommendation\n alias Pan.Subscription\n alias Pan.Message\n\n\n def action(conn, _) do\n apply(__MODULE__, action_name(conn), [conn, conn.params, conn.assigns.current_user])\n end\n\n\n def index(conn, params, _) do\n recommendations = from(p in Recommendation, order_by: [desc: :inserted_at],\n preload: [:user, :podcast, episode: :podcast,\n chapter: [episode: :podcast]])\n |> Repo.paginate(params)\n\n render(conn, \"index.html\", recommendations: recommendations)\n end\n\n\n def my_recommendations(conn,_params, user) do\n podcast_recommendations = Repo.all(from r in Recommendation, where: r.user_id == ^user.id and\n not is_nil(r.podcast_id) and\n is_nil(r.episode_id) and\n is_nil(r.chapter_id),\n order_by: [desc: :inserted_at],\n preload: :podcast)\n\n subscribed_podcast_ids = Repo.all(from s in Subscription, where: s.user_id == ^user.id,\n select: s.podcast_id)\n recommended_podcast_ids = Enum.map(podcast_recommendations, fn(recommendation) -> recommendation.podcast_id end)\n unrecommonded_podcast_ids = Enum.filter(subscribed_podcast_ids, fn(id) ->\n not Enum.member?(recommended_podcast_ids, id)\n end)\n unrecommended_podcasts = Repo.all(from p in Podcast, where: p.id in ^unrecommonded_podcast_ids)\n\n changeset = Recommendation.changeset(%Recommendation{})\n\n render(conn, \"my_recommendations.html\", podcast_recommendations: podcast_recommendations,\n unrecommended_podcasts: unrecommended_podcasts,\n changeset: changeset)\n end\n\n\n def random(conn, _params, _user) do\n podcast = Repo.all(Podcast)\n |> Enum.random\n |> Repo.preload(:categories)\n\n category = Repo.get(Category, List.first(podcast.categories).id)\n |> Repo.preload([:parent, :children, :podcasts])\n\n podcast = Repo.get(Podcast, podcast.id)\n |> Repo.preload([:episodes, :languages, :categories, :feeds, engagements: :persona])\n\n episode = Enum.random(podcast.episodes)\n episode = Repo.get(Episode, episode.id)\n |> Repo.preload([:podcast, :enclosures, [chapters: :recommendations],\n :contributors, :recommendations])\n\n changeset = Recommendation.changeset(%Recommendation{})\n\n render(conn, \"random.html\", category: category,\n podcast: podcast,\n episode: episode,\n player: \"podigee\",\n changeset: changeset)\n end\n\n\n def create(conn, %{\"recommendation\" => recommendation_params}, user) do\n recommendation_params = Map.put(recommendation_params, \"user_id\", user.id)\n changeset = Recommendation.changeset(%Recommendation{}, recommendation_params)\n\n e =\n cond do\n podcast_id_param = recommendation_params[\"podcast_id\"] ->\n podcast_id = String.to_integer(podcast_id_param)\n\n %Event{topic: \"podcasts\",\n subtopic: podcast_id_param,\n podcast_id: podcast_id,\n episode_id: nil,\n chapter_id: nil,\n notification_text: \"Podcast \" <> Repo.get!(Podcast, podcast_id).title <> \"<\/b>\"}\n\n episode_id_param = recommendation_params[\"episode_id\"] ->\n episode_id = String.to_integer(episode_id_param)\n episode = Repo.get!(Episode, episode_id)\n |> Repo.preload(:podcast)\n\n %Event{topic: \"podcasts\",\n subtopic: Integer.to_string(episode.podcast.id),\n podcast_id: episode.podcast.id,\n episode_id: episode_id,\n chapter_id: nil,\n notification_text: \"Episode \" <> episode.title <>\n \"<\/b> from \" <> episode.podcast.title <> \"<\/b>\"}\n\n chapter_id_param = recommendation_params[\"chapter_id\"] ->\n chapter_id = String.to_integer(chapter_id_param)\n chapter = Repo.get!(Chapter, chapter_id)\n |> Repo.preload([episode: :podcast])\n\n %Event{topic: \"podcasts\",\n subtopic: Integer.to_string(chapter.episode.podcast.id),\n podcast_id: chapter.episode.podcast.id,\n episode_id: chapter.episode.id,\n chapter_id: chapter_id,\n notification_text: \"Chapter \" <> chapter.title <> \"<\/b> in \" <>\n chapter.episode.title <> \"<\/b> from \" <>\n chapter.episode.podcast.title <> \"<\/b>\"}\n end\n\n e = %{e | current_user_id: user.id,\n type: \"success\",\n event: \"recommend\",\n content: C.String.truncate(\"\u00ab recommended \" <>\n e.notification_text <> \" \u00bb \" <>\n recommendation_params[\"comment\"], 255) }\n\n Repo.insert(changeset)\n Message.persist_event(e)\n Event.notify_subscribers(e)\n\n conn\n |> put_flash(:info, \"Your recommendation has been added.\")\n |> redirect_to_back\n end\n\n\n defp redirect_to_back( conn) do\n path =\n conn\n |> Plug.Conn.get_req_header(\"referer\")\n |> List.first\n |> URI.parse\n |> Map.get(:path)\n\n conn\n |> assign(:refer_path, path)\n |> redirect(to: path)\n end\nend\n","old_contents":"defmodule Pan.RecommendationFrontendController do\n use Pan.Web, :controller\n use Crutches\n alias Pan.Podcast\n alias Pan.Episode\n alias Pan.Category\n alias Pan.Chapter\n alias Pan.Recommendation\n alias Pan.Subscription\n alias Pan.Message\n\n\n def action(conn, _) do\n apply(__MODULE__, action_name(conn), [conn, conn.params, conn.assigns.current_user])\n end\n\n\n def index(conn, params, _) do\n recommendations = from(p in Recommendation, order_by: [desc: :inserted_at],\n preload: [:user, :podcast, episode: :podcast,\n chapter: [episode: :podcast]])\n |> Repo.paginate(params)\n\n render(conn, \"index.html\", recommendations: recommendations)\n end\n\n\n def my_recommendations(conn,_params, user) do\n podcast_recommendations = Repo.all(from r in Recommendation, where: r.user_id == ^user.id and\n not is_nil(r.podcast_id) and\n is_nil(r.episode_id) and\n is_nil(r.chapter_id),\n order_by: [desc: :inserted_at],\n preload: :podcast)\n\n subscribed_podcast_ids = Repo.all(from s in Subscription, where: s.user_id == ^user.id,\n select: s.podcast_id)\n recommended_podcast_ids = Enum.map(podcast_recommendations, fn(recommendation) -> recommendation.podcast_id end)\n unrecommonded_podcast_ids = Enum.filter(subscribed_podcast_ids, fn(id) ->\n not Enum.member?(recommended_podcast_ids, id)\n end)\n unrecommended_podcasts = Repo.all(from p in Podcast, where: p.id in ^unrecommonded_podcast_ids)\n\n changeset = Recommendation.changeset(%Recommendation{})\n\n render(conn, \"my_recommendations.html\", podcast_recommendations: podcast_recommendations,\n unrecommended_podcasts: unrecommended_podcasts,\n changeset: changeset)\n end\n\n\n def random(conn, _params, _user) do\n podcast = Repo.all(Podcast)\n |> Enum.random\n |> Repo.preload(:categories)\n\n category = Repo.get(Category, List.first(podcast.categories).id)\n |> Repo.preload([:parent, :children, :podcasts])\n\n podcast = Repo.get(Podcast, podcast.id)\n |> Repo.preload([:episodes, :languages, :categories, :feeds])\n\n episode = Enum.random(podcast.episodes)\n episode = Repo.get(Episode, episode.id)\n |> Repo.preload([:podcast, :enclosures, [chapters: :recommendations],\n :contributors, :recommendations])\n\n changeset = Recommendation.changeset(%Recommendation{})\n\n render(conn, \"random.html\", category: category,\n podcast: podcast,\n episode: episode,\n player: \"podigee\",\n changeset: changeset)\n end\n\n\n def create(conn, %{\"recommendation\" => recommendation_params}, user) do\n recommendation_params = Map.put(recommendation_params, \"user_id\", user.id)\n changeset = Recommendation.changeset(%Recommendation{}, recommendation_params)\n\n e =\n cond do\n podcast_id_param = recommendation_params[\"podcast_id\"] ->\n podcast_id = String.to_integer(podcast_id_param)\n\n %Event{topic: \"podcasts\",\n subtopic: podcast_id_param,\n podcast_id: podcast_id,\n episode_id: nil,\n chapter_id: nil,\n notification_text: \"Podcast \" <> Repo.get!(Podcast, podcast_id).title <> \"<\/b>\"}\n\n episode_id_param = recommendation_params[\"episode_id\"] ->\n episode_id = String.to_integer(episode_id_param)\n episode = Repo.get!(Episode, episode_id)\n |> Repo.preload(:podcast)\n\n %Event{topic: \"podcasts\",\n subtopic: Integer.to_string(episode.podcast.id),\n podcast_id: episode.podcast.id,\n episode_id: episode_id,\n chapter_id: nil,\n notification_text: \"Episode \" <> episode.title <>\n \"<\/b> from \" <> episode.podcast.title <> \"<\/b>\"}\n\n chapter_id_param = recommendation_params[\"chapter_id\"] ->\n chapter_id = String.to_integer(chapter_id_param)\n chapter = Repo.get!(Chapter, chapter_id)\n |> Repo.preload([episode: :podcast])\n\n %Event{topic: \"podcasts\",\n subtopic: Integer.to_string(chapter.episode.podcast.id),\n podcast_id: chapter.episode.podcast.id,\n episode_id: chapter.episode.id,\n chapter_id: chapter_id,\n notification_text: \"Chapter \" <> chapter.title <> \"<\/b> in \" <>\n chapter.episode.title <> \"<\/b> from \" <>\n chapter.episode.podcast.title <> \"<\/b>\"}\n end\n\n e = %{e | current_user_id: user.id,\n type: \"success\",\n event: \"recommend\",\n content: C.String.truncate(\"\u00ab recommended \" <>\n e.notification_text <> \" \u00bb \" <>\n recommendation_params[\"comment\"], 255) }\n\n Repo.insert(changeset)\n Message.persist_event(e)\n Event.notify_subscribers(e)\n\n conn\n |> put_flash(:info, \"Your recommendation has been added.\")\n |> redirect_to_back\n end\n\n\n defp redirect_to_back( conn) do\n path =\n conn\n |> Plug.Conn.get_req_header(\"referer\")\n |> List.first\n |> URI.parse\n |> Map.get(:path)\n\n conn\n |> assign(:refer_path, path)\n |> redirect(to: path)\n end\nend\n","returncode":0,"stderr":"","license":"agpl-3.0","lang":"Elixir"} {"commit":"9cb92420e54f3c400e287d63c8003a667ac8d576","subject":"phoenix template: use path as title instead of name to avoid grouping of templates that belong to different views","message":"phoenix template: use path as title instead of name to avoid grouping of\ntemplates that belong to different views\n","repos":"appsignal\/appsignal-elixir,appsignal\/appsignal-elixir,appsignal\/appsignal-elixir,appsignal\/appsignal-elixir","old_file":"lib\/appsignal\/phoenix\/template_instrumenter.ex","new_file":"lib\/appsignal\/phoenix\/template_instrumenter.ex","new_contents":"if Appsignal.phoenix? do\n defmodule Appsignal.Phoenix.TemplateInstrumenter do\n @moduledoc \"\"\"\n Instrument Phoenix template engines\n\n As documented in the [phoenix\n guidelines](http:\/\/docs.appsignal.com\/elixir\/integrations\/phoenix.html),\n The AppSignal Elixir library comes with default template engines to\n instrument renders to `.eex` and `.exs` template files.\n\n When you use another template engine in your Phoenix project, you\n can create a module which wraps the template renderer to also\n instrument those template files.\n\n To instrument the\n [phoenix_markdown](https:\/\/github.com\/boydm\/phoenix_markdown)\n library, you would create the following renderer engine module:\n\n ```\n defmodule MyApp.InstrumentedMarkdownEngine do\n use Appsignal.Phoenix.TemplateInstrumenter, engine: PhoenixMarkdown.Engine\n endmodule\n ```\n\n And then register the `.md` extension as a template as follows:\n\n ```\n config :phoenix, :template_engines,\n md: MyApp.InstrumentedMarkdownEngine\n ```\n\n \"\"\"\n\n @doc false\n defmacro __using__(opts) do\n quote do\n @behaviour Phoenix.Template.Engine\n\n def compile(path, name) do\n expr = unquote(opts[:engine]).compile(path, name)\n quote do\n Appsignal.Instrumentation.Helpers.instrument(\n self(),\n \"render.phoenix_template\",\n unquote(path),\n fn() -> unquote(expr) end\n )\n end\n end\n end\n end\n end\nend\n","old_contents":"if Appsignal.phoenix? do\n defmodule Appsignal.Phoenix.TemplateInstrumenter do\n @moduledoc \"\"\"\n Instrument Phoenix template engines\n\n As documented in the [phoenix\n guidelines](http:\/\/docs.appsignal.com\/elixir\/integrations\/phoenix.html),\n The AppSignal Elixir library comes with default template engines to\n instrument renders to `.eex` and `.exs` template files.\n\n When you use another template engine in your Phoenix project, you\n can create a module which wraps the template renderer to also\n instrument those template files.\n\n To instrument the\n [phoenix_markdown](https:\/\/github.com\/boydm\/phoenix_markdown)\n library, you would create the following renderer engine module:\n\n ```\n defmodule MyApp.InstrumentedMarkdownEngine do\n use Appsignal.Phoenix.TemplateInstrumenter, engine: PhoenixMarkdown.Engine\n endmodule\n ```\n\n And then register the `.md` extension as a template as follows:\n\n ```\n config :phoenix, :template_engines,\n md: MyApp.InstrumentedMarkdownEngine\n ```\n\n \"\"\"\n\n @doc false\n defmacro __using__(opts) do\n quote do\n @behaviour Phoenix.Template.Engine\n\n def compile(path, name) do\n expr = unquote(opts[:engine]).compile(path, name)\n quote do\n Appsignal.Instrumentation.Helpers.instrument(\n self(),\n \"render.phoenix_template\",\n unquote(name),\n fn() -> unquote(expr) end\n )\n end\n end\n end\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"c5e3284c8979313568af4a5ca4c65ac9de606e5c","subject":"Improve error message in case of lockfile eval failure","message":"Improve error message in case of lockfile eval failure\n","repos":"lexmag\/elixir,antipax\/elixir,pedrosnk\/elixir,gfvcastro\/elixir,beedub\/elixir,kimshrier\/elixir,ggcampinho\/elixir,antipax\/elixir,pedrosnk\/elixir,michalmuskala\/elixir,elixir-lang\/elixir,kimshrier\/elixir,beedub\/elixir,lexmag\/elixir,ggcampinho\/elixir,kelvinst\/elixir,kelvinst\/elixir,gfvcastro\/elixir,joshprice\/elixir","old_file":"lib\/mix\/lib\/mix\/dep\/lock.ex","new_file":"lib\/mix\/lib\/mix\/dep\/lock.ex","new_contents":"# This module keeps a lock file and the manifest for the lock file.\n# The lockfile keeps the latest dependency information while the\n# manifest is used whenever a dependency is affected via any of the\n# deps.* tasks. We also keep the Elixir version in the manifest file.\ndefmodule Mix.Dep.Lock do\n @moduledoc false\n @manifest \".compile.lock\"\n\n @doc \"\"\"\n Returns the manifest file for dependencies.\n \"\"\"\n @spec manifest(Path.t) :: Path.t\n def manifest(manifest_path \\\\ Mix.Project.manifest_path) do\n Path.join(manifest_path, @manifest)\n end\n\n @doc \"\"\"\n Touches the manifest timestamp unless it is an umbrella application.\n \"\"\"\n @spec touch() :: :ok\n def touch() do\n _ = unless Mix.Project.umbrella?, do: touch(Mix.Project.manifest_path)\n :ok\n end\n\n @doc \"\"\"\n Touches the manifest timestamp and updates the elixir version.\n \"\"\"\n @spec touch(Path.t) :: :ok\n def touch(manifest_path) do\n File.mkdir_p!(manifest_path)\n File.write!(Path.join(manifest_path, @manifest), System.version)\n end\n\n @doc \"\"\"\n Returns the elixir version in the lock manifest.\n \"\"\"\n @spec elixir_vsn() :: binary | nil\n def elixir_vsn() do\n elixir_vsn(Mix.Project.manifest_path)\n end\n\n @doc \"\"\"\n Returns the elixir version in the lock manifest in the given path.\n \"\"\"\n @spec elixir_vsn(Path.t) :: binary | nil\n def elixir_vsn(manifest_path) do\n case File.read(manifest(manifest_path)) do\n {:ok, contents} ->\n contents\n {:error, _} ->\n nil\n end\n end\n\n @doc \"\"\"\n Read the lockfile, returns a map containing\n each app name and its current lock information.\n \"\"\"\n @spec read() :: map\n def read() do\n case File.read(lockfile) do\n {:ok, info} ->\n case Code.eval_string(info, [], file: lockfile) do\n # lock could be a keyword list\n {lock, _binding} when is_list(lock) -> Enum.into(lock, %{})\n {lock, _binding} when is_map(lock) -> lock\n {nil, _binding} -> %{}\n end\n {:error, _} ->\n %{}\n end\n end\n\n @doc \"\"\"\n Receives a map and writes it as the latest lock.\n \"\"\"\n @spec write(map) :: :ok\n def write(map) do\n unless map == read do\n lines =\n for {app, rev} <- Enum.sort(map), rev != nil do\n ~s(\"#{app}\": #{inspect rev, limit: :infinity})\n end\n File.write! lockfile, \"%{\" <> Enum.join(lines, \",\\n \") <> \"}\\n\"\n touch\n end\n :ok\n end\n\n defp lockfile do\n Mix.Project.config[:lockfile]\n end\nend\n","old_contents":"# This module keeps a lock file and the manifest for the lock file.\n# The lockfile keeps the latest dependency information while the\n# manifest is used whenever a dependency is affected via any of the\n# deps.* tasks. We also keep the Elixir version in the manifest file.\ndefmodule Mix.Dep.Lock do\n @moduledoc false\n @manifest \".compile.lock\"\n\n @doc \"\"\"\n Returns the manifest file for dependencies.\n \"\"\"\n @spec manifest(Path.t) :: Path.t\n def manifest(manifest_path \\\\ Mix.Project.manifest_path) do\n Path.join(manifest_path, @manifest)\n end\n\n @doc \"\"\"\n Touches the manifest timestamp unless it is an umbrella application.\n \"\"\"\n @spec touch() :: :ok\n def touch() do\n _ = unless Mix.Project.umbrella?, do: touch(Mix.Project.manifest_path)\n :ok\n end\n\n @doc \"\"\"\n Touches the manifest timestamp and updates the elixir version.\n \"\"\"\n @spec touch(Path.t) :: :ok\n def touch(manifest_path) do\n File.mkdir_p!(manifest_path)\n File.write!(Path.join(manifest_path, @manifest), System.version)\n end\n\n @doc \"\"\"\n Returns the elixir version in the lock manifest.\n \"\"\"\n @spec elixir_vsn() :: binary | nil\n def elixir_vsn() do\n elixir_vsn(Mix.Project.manifest_path)\n end\n\n @doc \"\"\"\n Returns the elixir version in the lock manifest in the given path.\n \"\"\"\n @spec elixir_vsn(Path.t) :: binary | nil\n def elixir_vsn(manifest_path) do\n case File.read(manifest(manifest_path)) do\n {:ok, contents} ->\n contents\n {:error, _} ->\n nil\n end\n end\n\n @doc \"\"\"\n Read the lockfile, returns a map containing\n each app name and its current lock information.\n \"\"\"\n @spec read() :: map\n def read() do\n case File.read(lockfile) do\n {:ok, info} ->\n case Code.eval_string(info) do\n # lock could be a keyword list\n {lock, _binding} when is_list(lock) -> Enum.into(lock, %{})\n {lock, _binding} when is_map(lock) -> lock\n {nil, _binding} -> %{}\n end\n {:error, _} ->\n %{}\n end\n end\n\n @doc \"\"\"\n Receives a map and writes it as the latest lock.\n \"\"\"\n @spec write(map) :: :ok\n def write(map) do\n unless map == read do\n lines =\n for {app, rev} <- Enum.sort(map), rev != nil do\n ~s(\"#{app}\": #{inspect rev, limit: :infinity})\n end\n File.write! lockfile, \"%{\" <> Enum.join(lines, \",\\n \") <> \"}\\n\"\n touch\n end\n :ok\n end\n\n defp lockfile do\n Mix.Project.config[:lockfile]\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"5001830236e8c671f406484ab58a4290044949b6","subject":"Code style","message":"Code style\n","repos":"Nebo15\/tokenizer.api","old_file":"lib\/tokenizer\/supervisor.ex","new_file":"lib\/tokenizer\/supervisor.ex","new_contents":"defmodule Tokenizer.Supervisor do\n @moduledoc \"\"\"\n This supervisor allows to asynchronously start workers and maintain they availability.\n Polling is done on AMQP level by `prefetch_count` option.\n \"\"\"\n use Supervisor\n require Logger\n alias Repo.Schemas.Card\n alias Tokenizer.Encryptor\n\n @token_prefix \"card-token\"\n\n def start_link do\n Supervisor.start_link(__MODULE__, [], name: __MODULE__)\n end\n\n @doc false\n def init(_) do\n children = [\n supervisor(Tokenizer.Card, [], restart: :transient)\n ]\n\n supervise(children, strategy: :simple_one_for_one)\n end\n\n @doc \"\"\"\n Save card to a GenServer process that will allow to read it's data only once.\n\n Card data is encrypted in two rounds:\n 1. By user-token that is generated by this Supervisor\n 2. By key that is set in environment config.\n\n In this way we make sure that card data can't be decoded without server-key if user-key is stolen,\n and by user-key if server is hacked.\n \"\"\"\n def save_card(%Card{number: card_number} = card) do\n token = card_number\n |> generate_token\n\n card_data = card\n |> Poison.encode!\n |> Encryptor.encrypt(get_encryption_keys(token))\n\n child_name = get_card_process_via_tuple(token)\n expires_in = Confex.get(:gateway_api, :card_token_expires_in)\n\n {:ok, _pid} = Supervisor.start_child(__MODULE__, [[\n card_data: card_data,\n expires_in: expires_in,\n name: child_name]])\n\n expires_at = Timex.now\n |> Timex.shift(microseconds: expires_in)\n\n {:ok, %Repo.Schemas.CardToken{token: token, token_expires_at: expires_at}}\n end\n\n @doc \"\"\"\n Get saved card data.\n\n This method requires user card token to find card process and decrypt card data.\n\n It can return:\n * `{:error, reason}` - when card decryption is impossible (`:invalid_key_or_signature`)\n or card is not found (`:card_not_found`).\n * `{:ok, card}` - where `card` is decrypted card details.\n\n For a single card this method can be called only once, because card data will destroy itself after decryption.\n \"\"\"\n def get_card(token) do\n name = token\n |> get_card_process_name()\n\n Tokenizer.Registry\n |> Registry.lookup(name)\n |> get_card_data(token)\n end\n\n defp get_card_data([], _token),\n do: {:error, :card_not_found}\n defp get_card_data([{pid, _}], token) do\n message = pid\n |> Tokenizer.Card.get_data()\n |> Encryptor.decrypt(get_decryption_keys(token))\n\n case message do\n {:error, reason} ->\n {:error, reason}\n _ ->\n card = message\n |> Poison.decode!\n |> to_struct(Card)\n\n {:ok, card}\n end\n end\n\n defp to_struct(attrs, kind) do\n struct = struct(kind)\n Enum.reduce Map.to_list(struct), struct, fn {k, _}, acc ->\n case Map.fetch(attrs, Atom.to_string(k)) do\n {:ok, v} -> %{acc | k => v}\n :error -> acc\n end\n end\n end\n\n @doc \"\"\"\n Generate card token for a given card number or last 4 digits of card number.\n \"\"\"\n def generate_token(card_number) when byte_size(card_number) > 4 do\n card_number\n |> String.slice(-4..-1)\n |> generate_token\n end\n\n def generate_token(last4) when is_binary(last4) do\n salt = {last4, :os.timestamp()}\n |> :erlang.term_to_binary\n\n id = :sha\n |> :crypto.hash(salt <> :crypto.strong_rand_bytes(16))\n |> Base.encode16\n |> String.downcase\n\n @token_prefix <> \"-\" <> last4 <> \"-\" <> id\n end\n\n defp get_encryption_keys(<<@token_prefix, \"-\", _last4::bytes-size(4), \"-\", user_key::bytes>>) do\n [\n user_key,\n Confex.get(:gateway_api, :card_data_encryption_key)\n ]\n end\n\n defp get_decryption_keys(<<@token_prefix, \"-\", _last4::bytes-size(4), \"-\", _user_key::bytes>> = token) do\n token\n |> get_encryption_keys\n |> Enum.reverse\n end\n\n defp get_card_process_via_tuple(token),\n do: {:via, Registry, {Tokenizer.Registry, get_card_process_name(token)}}\n\n defp get_card_process_name(token),\n do: \"Cards.\" <> token\nend\n","old_contents":"defmodule Tokenizer.Supervisor do\n @moduledoc \"\"\"\n This supervisor allows to asynchronously start workers and maintain they availability.\n Polling is done on AMQP level by `prefetch_count` option.\n \"\"\"\n use Supervisor\n require Logger\n alias Repo.Schemas.Card\n alias Tokenizer.Encryptor\n\n @token_prefix \"card-token\"\n\n def start_link do\n Supervisor.start_link(__MODULE__, [], name: __MODULE__)\n end\n\n @doc \"\"\"\n Save card to a GenServer process that will allow to read it's data only once.\n\n Card data is encrypted in two rounds:\n 1. By user-token that is generated by this Supervisor\n 2. By key that is set in environment config.\n\n In this way we make sure that card data can't be decoded without server-key if user-key is stolen,\n and by user-key if server is hacked.\n \"\"\"\n def save_card(%Card{number: card_number} = card) do\n token = card_number\n |> generate_token\n\n card_data = card\n |> Poison.encode!\n |> Encryptor.encrypt(get_encryption_keys(token))\n\n child_name = get_card_process_via_tuple(token)\n expires_in = Confex.get(:gateway_api, :card_token_expires_in)\n\n {:ok, _pid} = Supervisor.start_child(__MODULE__, [[\n card_data: card_data,\n expires_in: expires_in,\n name: child_name]])\n\n expires_at = Timex.now\n |> Timex.shift(microseconds: expires_in)\n\n {:ok, %Repo.Schemas.CardToken{token: token, token_expires_at: expires_at}}\n end\n\n @doc \"\"\"\n Get saved card data.\n\n This method requires user card token to find card process and decrypt card data.\n\n It can return:\n * `{:error, reason}` - when card decryption is impossible (`:invalid_key_or_signature`)\n or card is not found (`:card_not_found`).\n * `{:ok, card}` - where `card` is decrypted card details.\n\n For a single card this method can be called only once, because card data will destroy itself after decryption.\n \"\"\"\n def get_card(token) do\n name = token\n |> get_card_process_name()\n\n Tokenizer.Registry\n |> Registry.lookup(name)\n |> get_card_data(token)\n end\n\n defp get_card_data([], _token),\n do: {:error, :card_not_found}\n defp get_card_data([{pid, _}], token) do\n message = pid\n |> Tokenizer.Card.get_data()\n |> Encryptor.decrypt(get_decryption_keys(token))\n\n case message do\n {:error, reason} ->\n {:error, reason}\n _ ->\n card = message\n |> Poison.decode!\n |> to_struct(Card)\n\n {:ok, card}\n end\n end\n\n defp to_struct(attrs, kind) do\n struct = struct(kind)\n Enum.reduce Map.to_list(struct), struct, fn {k, _}, acc ->\n case Map.fetch(attrs, Atom.to_string(k)) do\n {:ok, v} -> %{acc | k => v}\n :error -> acc\n end\n end\n end\n\n @doc \"\"\"\n Generate card token for a given card number or last 4 digits of card number.\n \"\"\"\n def generate_token(card_number) when byte_size(card_number) > 4 do\n card_number\n |> String.slice(-4..-1)\n |> generate_token\n end\n\n def generate_token(last4) when is_binary(last4) do\n salt = {last4, :os.timestamp()}\n |> :erlang.term_to_binary\n\n id = :sha\n |> :crypto.hash(salt <> :crypto.strong_rand_bytes(16))\n |> Base.encode16\n |> String.downcase\n\n @token_prefix <> \"-\" <> last4 <> \"-\" <> id\n end\n\n defp get_encryption_keys(<<@token_prefix, \"-\", _last4::bytes-size(4), \"-\", user_key::bytes>>) do\n [\n user_key,\n Confex.get(:gateway_api, :card_data_encryption_key)\n ]\n end\n\n defp get_decryption_keys(<<@token_prefix, \"-\", _last4::bytes-size(4), \"-\", _user_key::bytes>> = token) do\n token\n |> get_encryption_keys\n |> Enum.reverse\n end\n\n def get_card_process_via_tuple(token),\n do: {:via, Registry, {Tokenizer.Registry, get_card_process_name(token)}}\n\n def get_card_process_name(token),\n do: \"Cards.\" <> token\n\n @doc false\n def init(_) do\n children = [\n supervisor(Tokenizer.Card, [], restart: :transient)\n ]\n\n supervise(children, strategy: :simple_one_for_one)\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"0dfb995a5d7eb196d47c10744403836db4b2c078","subject":"Update broken link to Message API","message":"Update broken link to Message API\n","repos":"danielberkompas\/ex_twilio,danielberkompas\/ex_twilio","old_file":"lib\/ex_twilio\/resources\/message.ex","new_file":"lib\/ex_twilio\/resources\/message.ex","new_contents":"defmodule ExTwilio.Message do\n @moduledoc \"\"\"\n Represents an Message resource in the Twilio API.\n\n - [Twilio docs](https:\/\/www.twilio.com\/docs\/sms\/api\/message-resource)\n\n Here is an example of sending an SMS message:\n\n {target_number, twilio_number_you_own, body} = {\"+12223334444\", \"+19223334444\", \"Hello World\"}\n\n ExTwilio.Message.create(to: target_number, from: twilio_number_you_own, body: body)\n \"\"\"\n\n defstruct sid: nil,\n date_created: nil,\n date_updated: nil,\n date_sent: nil,\n account_sid: nil,\n from: nil,\n to: nil,\n body: nil,\n num_media: nil,\n num_segments: nil,\n status: nil,\n error_code: nil,\n error_message: nil,\n direction: nil,\n price: nil,\n price_unit: nil,\n api_version: nil,\n uri: nil,\n subresource_uri: nil,\n messaging_service_sid: nil\n\n use ExTwilio.Resource,\n import: [\n :stream,\n :all,\n :find,\n :create,\n :update,\n :destroy\n ]\n\n def parents, do: [:account]\nend\n","old_contents":"defmodule ExTwilio.Message do\n @moduledoc \"\"\"\n Represents an Message resource in the Twilio API.\n\n - [Twilio docs](https:\/\/www.twilio.com\/docs\/api\/rest\/messages)\n\n Here is an example of sending an SMS message:\n\n {target_number, twilio_number_you_own, body} = {\"+12223334444\", \"+19223334444\", \"Hello World\"}\n\n ExTwilio.Message.create(to: target_number, from: twilio_number_you_own, body: body)\n \"\"\"\n\n defstruct sid: nil,\n date_created: nil,\n date_updated: nil,\n date_sent: nil,\n account_sid: nil,\n from: nil,\n to: nil,\n body: nil,\n num_media: nil,\n num_segments: nil,\n status: nil,\n error_code: nil,\n error_message: nil,\n direction: nil,\n price: nil,\n price_unit: nil,\n api_version: nil,\n uri: nil,\n subresource_uri: nil,\n messaging_service_sid: nil\n\n use ExTwilio.Resource,\n import: [\n :stream,\n :all,\n :find,\n :create,\n :update,\n :destroy\n ]\n\n def parents, do: [:account]\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"0b3fcb254a41e88db7ead04ef703294749422fb4","subject":"Docs: change Dict.merge description to read more naturally","message":"Docs: change Dict.merge description to read more naturally\n\nPreviously there was an additional \"dict\" - this is as a result of it\npreviously saying \"dict `a`\"\n","repos":"lexmag\/elixir,beedub\/elixir,ggcampinho\/elixir,beedub\/elixir,kelvinst\/elixir,kelvinst\/elixir,pedrosnk\/elixir,kimshrier\/elixir,antipax\/elixir,ggcampinho\/elixir,joshprice\/elixir,pedrosnk\/elixir,elixir-lang\/elixir,gfvcastro\/elixir,michalmuskala\/elixir,kimshrier\/elixir,gfvcastro\/elixir,lexmag\/elixir,antipax\/elixir","old_file":"lib\/elixir\/lib\/dict.ex","new_file":"lib\/elixir\/lib\/dict.ex","new_contents":"defmodule Dict do\n @moduledoc ~S\"\"\"\n This module specifies the Dict API expected to be\n implemented by different dictionaries. It also provides\n functions that redirect to the underlying Dict, allowing\n a developer to work with different Dict implementations\n using one API.\n\n To create a new dict, use the `new` functions defined\n by each dict type:\n\n HashDict.new #=> creates an empty HashDict\n\n In the examples below, `dict_impl` means a specific\n `Dict` implementation, for example `HashDict` or `Map`.\n\n ## Protocols\n\n Besides implementing the functions in this module, all\n dictionaries are required to implement the `Access`\n protocol:\n\n iex> dict = dict_impl.new\n iex> dict = Dict.put(dict, :hello, :world)\n iex> dict[:hello]\n :world\n\n As well as the `Enumerable` and `Collectable` protocols.\n\n ## Match\n\n Dictionaries are required to implement all operations\n using the match (`===`) operator.\n\n ## Default implementation\n\n Default implementations for some functions in the `Dict` module\n are provided via `use Dict`.\n\n For example:\n\n defmodule MyDict do\n use Dict\n\n # implement required functions (see below)\n # override default implementations if optimization\n # is needed\n end\n\n The client module must contain the following functions:\n\n * `delete\/2`\n * `fetch\/2`\n * `put\/3`\n * `reduce\/3`\n * `size\/1`\n\n All functions, except `reduce\/3`, are required by the Dict behaviour.\n `reduce\/3` must be implemtented as per the Enumerable protocol.\n\n Based on these functions, `Dict` generates default implementations\n for the following functions:\n\n * `drop\/2`\n * `equal?\/2`\n * `fetch!\/2`\n * `get\/2`\n * `get\/3`\n * `has_key?\/2`\n * `keys\/1`\n * `merge\/2`\n * `merge\/3`\n * `pop\/2`\n * `pop\/3`\n * `put_new\/3`\n * `split\/2`\n * `take\/2`\n * `to_list\/1`\n * `update\/4`\n * `update!\/3`\n * `values\/1`\n\n All of these functions are defined as overridable, so you can provide\n your own implementation if needed.\n\n Note you can also test your custom module via `Dict`'s doctests:\n\n defmodule MyDict do\n # ...\n end\n\n defmodule MyTests do\n use ExUnit.Case\n doctest Dict\n defp dict_impl, do: MyDict\n end\n\n \"\"\"\n\n use Behaviour\n\n @type key :: any\n @type value :: any\n @type t :: list | map\n\n defcallback new :: t\n defcallback delete(t, key) :: t\n defcallback drop(t, Enum.t) :: t\n defcallback equal?(t, t) :: boolean\n defcallback get(t, key) :: value\n defcallback get(t, key, value) :: value\n defcallback fetch(t, key) :: {:ok, value} | :error\n defcallback fetch!(t, key) :: value | no_return\n defcallback has_key?(t, key) :: boolean\n defcallback keys(t) :: [key]\n defcallback merge(t, t) :: t\n defcallback merge(t, t, (key, value, value -> value)) :: t\n defcallback pop(t, key) :: {value, t}\n defcallback pop(t, key, value) :: {value, t}\n defcallback put(t, key, value) :: t\n defcallback put_new(t, key, value) :: t\n defcallback size(t) :: non_neg_integer()\n defcallback split(t, Enum.t) :: {t, t}\n defcallback take(t, Enum.t) :: t\n defcallback to_list(t) :: list()\n defcallback update(t, key, value, (value -> value)) :: t\n defcallback update!(t, key, (value -> value)) :: t | no_return\n defcallback values(t) :: list(value)\n\n defmacro __using__(_) do\n # Use this import to guarantee proper code expansion\n import Kernel, except: [size: 1]\n\n quote do\n @behaviour Dict\n\n def get(dict, key, default \\\\ nil) do\n case fetch(dict, key) do\n {:ok, value} -> value\n :error -> default\n end\n end\n\n def fetch!(dict, key) do\n case fetch(dict, key) do\n {:ok, value} -> value\n :error -> raise KeyError, key: key, term: dict\n end\n end\n\n def has_key?(dict, key) do\n match? {:ok, _}, fetch(dict, key)\n end\n\n def put_new(dict, key, value) do\n case has_key?(dict, key) do\n true -> dict\n false -> put(dict, key, value)\n end\n end\n\n def drop(dict, keys) do\n Enum.reduce(keys, dict, &delete(&2, &1))\n end\n\n def take(dict, keys) do\n Enum.reduce(keys, new, fn key, acc ->\n case fetch(dict, key) do\n {:ok, value} -> put(acc, key, value)\n :error -> acc\n end\n end)\n end\n\n def to_list(dict) do\n reduce(dict, {:cont, []}, fn\n kv, acc -> {:cont, [kv|acc]}\n end) |> elem(1) |> :lists.reverse\n end\n\n def keys(dict) do\n reduce(dict, {:cont, []}, fn\n {k, _}, acc -> {:cont, [k|acc]}\n end) |> elem(1) |> :lists.reverse\n end\n\n def values(dict) do\n reduce(dict, {:cont, []}, fn\n {_, v}, acc -> {:cont, [v|acc]}\n end) |> elem(1) |> :lists.reverse\n end\n\n def equal?(dict1, dict2) do\n # Use this import to avoid conflicts in the user code\n import Kernel, except: [size: 1]\n\n case size(dict1) == size(dict2) do\n false -> false\n true ->\n reduce(dict1, {:cont, true}, fn({k, v}, _acc) ->\n case fetch(dict2, k) do\n {:ok, ^v} -> {:cont, true}\n _ -> {:halt, false}\n end\n end) |> elem(1)\n end\n end\n\n def merge(dict1, dict2, fun \\\\ fn(_k, _v1, v2) -> v2 end) do\n # Use this import to avoid conflicts in the user code\n import Kernel, except: [size: 1]\n\n if size(dict1) < size(dict2) do\n reduce(dict1, {:cont, dict2}, fn {k, v1}, acc ->\n {:cont, update(acc, k, v1, &fun.(k, v1, &1))}\n end)\n else\n reduce(dict2, {:cont, dict1}, fn {k, v2}, acc ->\n {:cont, update(acc, k, v2, &fun.(k, &1, v2))}\n end)\n end |> elem(1)\n end\n\n def update(dict, key, initial, fun) do\n case fetch(dict, key) do\n {:ok, value} ->\n put(dict, key, fun.(value))\n :error ->\n put(dict, key, initial)\n end\n end\n\n def update!(dict, key, fun) do\n case fetch(dict, key) do\n {:ok, value} ->\n put(dict, key, fun.(value))\n :error ->\n raise KeyError, key: key, term: dict\n end\n end\n\n def pop(dict, key, default \\\\ nil) do\n case fetch(dict, key) do\n {:ok, value} ->\n {value, delete(dict, key)}\n :error ->\n {default, dict}\n end\n end\n\n def split(dict, keys) do\n Enum.reduce(keys, {new, dict}, fn key, {inc, exc} = acc ->\n case fetch(exc, key) do\n {:ok, value} ->\n {put(inc, key, value), delete(exc, key)}\n :error ->\n acc\n end\n end)\n end\n\n defoverridable merge: 2, merge: 3, equal?: 2, to_list: 1, keys: 1,\n values: 1, take: 2, drop: 2, get: 2, get: 3, fetch!: 2,\n has_key?: 2, put_new: 3, pop: 2, pop: 3, split: 2,\n update: 4, update!: 3\n end\n end\n\n\n defmacrop target(dict) do\n quote do\n case unquote(dict) do\n %{__struct__: x} when is_atom(x) ->\n x\n %{} ->\n Map\n x when is_list(x) ->\n Keyword\n x ->\n unsupported_dict(x)\n end\n end\n end\n\n @doc \"\"\"\n Returns a list of all keys in `dict`.\n The keys are not guaranteed to be in any order.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> Enum.sort(Dict.keys(dict))\n [:a,:b]\n\n \"\"\"\n @spec keys(t) :: [key]\n def keys(dict) do\n target(dict).keys(dict)\n end\n\n @doc \"\"\"\n Returns a list of all values in `dict`.\n The values are not guaranteed to be in any order.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> Enum.sort(Dict.values(dict))\n [1,2]\n\n \"\"\"\n @spec values(t) :: [value]\n def values(dict) do\n target(dict).values(dict)\n end\n\n @doc \"\"\"\n Returns the number of elements in `dict`.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> Dict.size(dict)\n 2\n\n \"\"\"\n @spec size(t) :: non_neg_integer\n def size(dict) do\n target(dict).size(dict)\n end\n\n @doc \"\"\"\n Returns whether the given `key` exists in the given `dict`.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1], dict_impl.new)\n iex> Dict.has_key?(dict, :a)\n true\n iex> Dict.has_key?(dict, :b)\n false\n\n \"\"\"\n @spec has_key?(t, key) :: boolean\n def has_key?(dict, key) do\n target(dict).has_key?(dict, key)\n end\n\n @doc \"\"\"\n Returns the value associated with `key` in `dict`. If `dict` does not\n contain `key`, returns `default` (or `nil` if not provided).\n\n ## Examples\n\n iex> dict = Enum.into([a: 1], dict_impl.new)\n iex> Dict.get(dict, :a)\n 1\n iex> Dict.get(dict, :b)\n nil\n iex> Dict.get(dict, :b, 3)\n 3\n \"\"\"\n @spec get(t, key, value) :: value\n def get(dict, key, default \\\\ nil) do\n target(dict).get(dict, key, default)\n end\n\n @doc \"\"\"\n Returns `{:ok, value}` associated with `key` in `dict`.\n If `dict` does not contain `key`, returns `:error`.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1], dict_impl.new)\n iex> Dict.fetch(dict, :a)\n {:ok, 1}\n iex> Dict.fetch(dict, :b)\n :error\n\n \"\"\"\n @spec fetch(t, key) :: value\n def fetch(dict, key) do\n target(dict).fetch(dict, key)\n end\n\n @doc \"\"\"\n Returns the value associated with `key` in `dict`. If `dict` does not\n contain `key`, it raises `KeyError`.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1], dict_impl.new)\n iex> Dict.fetch!(dict, :a)\n 1\n\n \"\"\"\n @spec fetch!(t, key) :: value | no_return\n def fetch!(dict, key) do\n target(dict).fetch!(dict, key)\n end\n\n @doc \"\"\"\n Stores the given `value` under `key` in `dict`.\n If `dict` already has `key`, the stored value is replaced by the new one.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict = Dict.put(dict, :a, 3)\n iex> Dict.get(dict, :a)\n 3\n\n \"\"\"\n @spec put(t, key, value) :: t\n def put(dict, key, val) do\n target(dict).put(dict, key, val)\n end\n\n @doc \"\"\"\n Puts the given `value` under `key` in `dict` unless `key` already exists.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict = Dict.put_new(dict, :a, 3)\n iex> Dict.get(dict, :a)\n 1\n\n \"\"\"\n @spec put_new(t, key, value) :: t\n def put_new(dict, key, val) do\n target(dict).put_new(dict, key, val)\n end\n\n @doc \"\"\"\n Removes the entry stored under the given `key` from `dict`.\n If `dict` does not contain `key`, returns the dictionary unchanged.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict = Dict.delete(dict, :a)\n iex> Dict.get(dict, :a)\n nil\n\n iex> dict = Enum.into([b: 2], dict_impl.new)\n iex> Dict.delete(dict, :a) == dict\n true\n\n \"\"\"\n @spec delete(t, key) :: t\n def delete(dict, key) do\n target(dict).delete(dict, key)\n end\n\n @doc \"\"\"\n Merges the dict `dict2` into dict `dict1`.\n\n If one of the `dict2` entries already exists in `dict1`, the\n functions in entries in `dict2` have higher precedence unless a\n function is given to resolve conflicts.\n\n Notice this function is polymorphic as it merges dicts of any\n type. Each dict implementation also provides a `merge` function,\n but they can only merge dicts of the same type.\n\n ## Examples\n\n iex> dict1 = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict2 = Enum.into([a: 3, d: 4], dict_impl.new)\n iex> dict = Dict.merge(dict1, dict2)\n iex> [a: Dict.get(dict, :a), b: Dict.get(dict, :b), d: Dict.get(dict, :d)]\n [a: 3, b: 2, d: 4]\n\n iex> dict1 = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict2 = Enum.into([a: 3, d: 4], dict_impl.new)\n iex> dict = Dict.merge(dict1, dict2, fn(_k, v1, v2) ->\n ...> v1 + v2\n ...> end)\n iex> [a: Dict.get(dict, :a), b: Dict.get(dict, :b), d: Dict.get(dict, :d)]\n [a: 4, b: 2, d: 4]\n\n \"\"\"\n @spec merge(t, t, (key, value, value -> value)) :: t\n def merge(dict1, dict2, fun \\\\ fn(_k, _v1, v2) -> v2 end) do\n target1 = target(dict1)\n target2 = target(dict2)\n\n if target1 == target2 do\n target1.merge(dict1, dict2, fun)\n else\n Enumerable.reduce(dict2, {:cont, dict1}, fn({k, v}, acc) ->\n {:cont, target1.update(acc, k, v, fn(other) -> fun.(k, other, v) end)}\n end) |> elem(1)\n end\n end\n\n @doc \"\"\"\n Returns the value associated with `key` in `dict` as\n well as the `dict` without `key`.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1], dict_impl.new)\n iex> {v, dict} = Dict.pop dict, :a\n iex> {v, Enum.sort(dict)}\n {1,[]}\n\n iex> dict = Enum.into([a: 1], dict_impl.new)\n iex> {v, dict} = Dict.pop dict, :b\n iex> {v, Enum.sort(dict)}\n {nil,[a: 1]}\n\n iex> dict = Enum.into([a: 1], dict_impl.new)\n iex> {v, dict} = Dict.pop dict, :b, 3\n iex> {v, Enum.sort(dict)}\n {3,[a: 1]}\n\n \"\"\"\n @spec pop(t, key, value) :: {value, t}\n def pop(dict, key, default \\\\ nil) do\n target(dict).pop(dict, key, default)\n end\n\n @doc \"\"\"\n Update a value in `dict` by calling `fun` on the value to get a new\n value. An exception is generated if `key` is not present in the dict.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict = Dict.update!(dict, :a, fn(val) -> -val end)\n iex> Dict.get(dict, :a)\n -1\n\n \"\"\"\n @spec update!(t, key, (value -> value)) :: t\n def update!(dict, key, fun) do\n target(dict).update!(dict, key, fun)\n end\n\n @doc \"\"\"\n Update a value in `dict` by calling `fun` on the value to get a new value. If\n `key` is not present in `dict` then `initial` will be stored as the first\n value.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict = Dict.update(dict, :c, 3, fn(val) -> -val end)\n iex> Dict.get(dict, :c)\n 3\n\n \"\"\"\n @spec update(t, key, value, (value -> value)) :: t\n def update(dict, key, initial, fun) do\n target(dict).update(dict, key, initial, fun)\n end\n\n @doc \"\"\"\n Returns a tuple of two dicts, where the first dict contains only\n entries from `dict` with keys in `keys`, and the second dict\n contains only entries from `dict` with keys not in `keys`\n\n Any non-member keys are ignored.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2, c: 3, d: 4], dict_impl.new)\n iex> {dict1, dict2} = Dict.split(dict, [:a, :c, :e])\n iex> {Dict.to_list(dict1) |> Enum.sort, Dict.to_list(dict2) |> Enum.sort}\n {[a: 1, c: 3], [b: 2, d: 4]}\n\n iex> dict = Enum.into([], dict_impl.new)\n iex> {dict1, dict2} = Dict.split(dict, [:a, :c])\n iex> {Dict.to_list(dict1), Dict.to_list(dict2)}\n {[], []}\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> {dict1, dict2} = Dict.split(dict, [:a, :b, :c])\n iex> {Dict.to_list(dict1) |> Enum.sort, Dict.to_list(dict2)}\n {[a: 1, b: 2], []}\n\n \"\"\"\n @spec split(t, [key]) :: {t, t}\n def split(dict, keys) do\n target(dict).split(dict, keys)\n end\n\n @doc \"\"\"\n Returns a new dict where the given `keys` are removed from `dict`.\n Any non-member keys are ignored.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict = Dict.drop(dict, [:a, :c, :d])\n iex> Dict.to_list(dict)\n [b: 2]\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict = Dict.drop(dict, [:c, :d])\n iex> Dict.to_list(dict) |> Enum.sort\n [a: 1, b: 2]\n\n \"\"\"\n @spec drop(t, [key]) :: t\n def drop(dict, keys) do\n target(dict).drop(dict, keys)\n end\n\n @doc \"\"\"\n Returns a new dict where only the keys in `keys` from `dict` are included.\n\n Any non-member keys are ignored.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict = Dict.take(dict, [:a, :c, :d])\n iex> Dict.to_list(dict)\n [a: 1]\n iex> dict = Dict.take(dict, [:c, :d])\n iex> Dict.to_list(dict)\n []\n\n \"\"\"\n @spec take(t, [key]) :: t\n def take(dict, keys) do\n target(dict).take(dict, keys)\n end\n\n @doc false\n @spec empty(t) :: t\n def empty(dict) do\n target(dict).empty(dict)\n end\n\n @doc \"\"\"\n Check if two dicts are equal using `===`.\n\n Notice this function is polymorphic as it compares dicts of any\n type. Each dict implementation also provides an `equal?` function,\n but they can only compare dicts of the same type.\n\n ## Examples\n\n iex> dict1 = Enum.into([a: 2, b: 3, f: 5, c: 123], dict_impl.new)\n iex> dict2 = [a: 2, b: 3, f: 5, c: 123]\n iex> Dict.equal?(dict1, dict2)\n true\n\n iex> dict1 = Enum.into([a: 2, b: 3, f: 5, c: 123], dict_impl.new)\n iex> dict2 = []\n iex> Dict.equal?(dict1, dict2)\n false\n\n \"\"\"\n @spec equal?(t, t) :: boolean\n def equal?(dict1, dict2) do\n target1 = target(dict1)\n target2 = target(dict2)\n\n cond do\n target1 == target2 ->\n target1.equal?(dict1, dict2)\n\n target1.size(dict1) == target2.size(dict2) ->\n Enumerable.reduce(dict2, {:cont, true}, fn({k, v}, _acc) ->\n case target1.fetch(dict1, k) do\n {:ok, ^v} -> {:cont, true}\n _ -> {:halt, false}\n end\n end) |> elem(1)\n\n true ->\n false\n end\n end\n\n @doc \"\"\"\n Returns a list of key-value pairs stored in `dict`.\n No particular order is enforced.\n \"\"\"\n @spec to_list(t) :: list\n def to_list(dict) do\n target(dict).to_list(dict)\n end\n\n defp unsupported_dict(dict) do\n raise ArgumentError, \"unsupported dict: #{inspect dict}\"\n end\nend\n","old_contents":"defmodule Dict do\n @moduledoc ~S\"\"\"\n This module specifies the Dict API expected to be\n implemented by different dictionaries. It also provides\n functions that redirect to the underlying Dict, allowing\n a developer to work with different Dict implementations\n using one API.\n\n To create a new dict, use the `new` functions defined\n by each dict type:\n\n HashDict.new #=> creates an empty HashDict\n\n In the examples below, `dict_impl` means a specific\n `Dict` implementation, for example `HashDict` or `Map`.\n\n ## Protocols\n\n Besides implementing the functions in this module, all\n dictionaries are required to implement the `Access`\n protocol:\n\n iex> dict = dict_impl.new\n iex> dict = Dict.put(dict, :hello, :world)\n iex> dict[:hello]\n :world\n\n As well as the `Enumerable` and `Collectable` protocols.\n\n ## Match\n\n Dictionaries are required to implement all operations\n using the match (`===`) operator.\n\n ## Default implementation\n\n Default implementations for some functions in the `Dict` module\n are provided via `use Dict`.\n\n For example:\n\n defmodule MyDict do\n use Dict\n\n # implement required functions (see below)\n # override default implementations if optimization\n # is needed\n end\n\n The client module must contain the following functions:\n\n * `delete\/2`\n * `fetch\/2`\n * `put\/3`\n * `reduce\/3`\n * `size\/1`\n\n All functions, except `reduce\/3`, are required by the Dict behaviour.\n `reduce\/3` must be implemtented as per the Enumerable protocol.\n\n Based on these functions, `Dict` generates default implementations\n for the following functions:\n\n * `drop\/2`\n * `equal?\/2`\n * `fetch!\/2`\n * `get\/2`\n * `get\/3`\n * `has_key?\/2`\n * `keys\/1`\n * `merge\/2`\n * `merge\/3`\n * `pop\/2`\n * `pop\/3`\n * `put_new\/3`\n * `split\/2`\n * `take\/2`\n * `to_list\/1`\n * `update\/4`\n * `update!\/3`\n * `values\/1`\n\n All of these functions are defined as overridable, so you can provide\n your own implementation if needed.\n\n Note you can also test your custom module via `Dict`'s doctests:\n\n defmodule MyDict do\n # ...\n end\n\n defmodule MyTests do\n use ExUnit.Case\n doctest Dict\n defp dict_impl, do: MyDict\n end\n\n \"\"\"\n\n use Behaviour\n\n @type key :: any\n @type value :: any\n @type t :: list | map\n\n defcallback new :: t\n defcallback delete(t, key) :: t\n defcallback drop(t, Enum.t) :: t\n defcallback equal?(t, t) :: boolean\n defcallback get(t, key) :: value\n defcallback get(t, key, value) :: value\n defcallback fetch(t, key) :: {:ok, value} | :error\n defcallback fetch!(t, key) :: value | no_return\n defcallback has_key?(t, key) :: boolean\n defcallback keys(t) :: [key]\n defcallback merge(t, t) :: t\n defcallback merge(t, t, (key, value, value -> value)) :: t\n defcallback pop(t, key) :: {value, t}\n defcallback pop(t, key, value) :: {value, t}\n defcallback put(t, key, value) :: t\n defcallback put_new(t, key, value) :: t\n defcallback size(t) :: non_neg_integer()\n defcallback split(t, Enum.t) :: {t, t}\n defcallback take(t, Enum.t) :: t\n defcallback to_list(t) :: list()\n defcallback update(t, key, value, (value -> value)) :: t\n defcallback update!(t, key, (value -> value)) :: t | no_return\n defcallback values(t) :: list(value)\n\n defmacro __using__(_) do\n # Use this import to guarantee proper code expansion\n import Kernel, except: [size: 1]\n\n quote do\n @behaviour Dict\n\n def get(dict, key, default \\\\ nil) do\n case fetch(dict, key) do\n {:ok, value} -> value\n :error -> default\n end\n end\n\n def fetch!(dict, key) do\n case fetch(dict, key) do\n {:ok, value} -> value\n :error -> raise KeyError, key: key, term: dict\n end\n end\n\n def has_key?(dict, key) do\n match? {:ok, _}, fetch(dict, key)\n end\n\n def put_new(dict, key, value) do\n case has_key?(dict, key) do\n true -> dict\n false -> put(dict, key, value)\n end\n end\n\n def drop(dict, keys) do\n Enum.reduce(keys, dict, &delete(&2, &1))\n end\n\n def take(dict, keys) do\n Enum.reduce(keys, new, fn key, acc ->\n case fetch(dict, key) do\n {:ok, value} -> put(acc, key, value)\n :error -> acc\n end\n end)\n end\n\n def to_list(dict) do\n reduce(dict, {:cont, []}, fn\n kv, acc -> {:cont, [kv|acc]}\n end) |> elem(1) |> :lists.reverse\n end\n\n def keys(dict) do\n reduce(dict, {:cont, []}, fn\n {k, _}, acc -> {:cont, [k|acc]}\n end) |> elem(1) |> :lists.reverse\n end\n\n def values(dict) do\n reduce(dict, {:cont, []}, fn\n {_, v}, acc -> {:cont, [v|acc]}\n end) |> elem(1) |> :lists.reverse\n end\n\n def equal?(dict1, dict2) do\n # Use this import to avoid conflicts in the user code\n import Kernel, except: [size: 1]\n\n case size(dict1) == size(dict2) do\n false -> false\n true ->\n reduce(dict1, {:cont, true}, fn({k, v}, _acc) ->\n case fetch(dict2, k) do\n {:ok, ^v} -> {:cont, true}\n _ -> {:halt, false}\n end\n end) |> elem(1)\n end\n end\n\n def merge(dict1, dict2, fun \\\\ fn(_k, _v1, v2) -> v2 end) do\n # Use this import to avoid conflicts in the user code\n import Kernel, except: [size: 1]\n\n if size(dict1) < size(dict2) do\n reduce(dict1, {:cont, dict2}, fn {k, v1}, acc ->\n {:cont, update(acc, k, v1, &fun.(k, v1, &1))}\n end)\n else\n reduce(dict2, {:cont, dict1}, fn {k, v2}, acc ->\n {:cont, update(acc, k, v2, &fun.(k, &1, v2))}\n end)\n end |> elem(1)\n end\n\n def update(dict, key, initial, fun) do\n case fetch(dict, key) do\n {:ok, value} ->\n put(dict, key, fun.(value))\n :error ->\n put(dict, key, initial)\n end\n end\n\n def update!(dict, key, fun) do\n case fetch(dict, key) do\n {:ok, value} ->\n put(dict, key, fun.(value))\n :error ->\n raise KeyError, key: key, term: dict\n end\n end\n\n def pop(dict, key, default \\\\ nil) do\n case fetch(dict, key) do\n {:ok, value} ->\n {value, delete(dict, key)}\n :error ->\n {default, dict}\n end\n end\n\n def split(dict, keys) do\n Enum.reduce(keys, {new, dict}, fn key, {inc, exc} = acc ->\n case fetch(exc, key) do\n {:ok, value} ->\n {put(inc, key, value), delete(exc, key)}\n :error ->\n acc\n end\n end)\n end\n\n defoverridable merge: 2, merge: 3, equal?: 2, to_list: 1, keys: 1,\n values: 1, take: 2, drop: 2, get: 2, get: 3, fetch!: 2,\n has_key?: 2, put_new: 3, pop: 2, pop: 3, split: 2,\n update: 4, update!: 3\n end\n end\n\n\n defmacrop target(dict) do\n quote do\n case unquote(dict) do\n %{__struct__: x} when is_atom(x) ->\n x\n %{} ->\n Map\n x when is_list(x) ->\n Keyword\n x ->\n unsupported_dict(x)\n end\n end\n end\n\n @doc \"\"\"\n Returns a list of all keys in `dict`.\n The keys are not guaranteed to be in any order.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> Enum.sort(Dict.keys(dict))\n [:a,:b]\n\n \"\"\"\n @spec keys(t) :: [key]\n def keys(dict) do\n target(dict).keys(dict)\n end\n\n @doc \"\"\"\n Returns a list of all values in `dict`.\n The values are not guaranteed to be in any order.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> Enum.sort(Dict.values(dict))\n [1,2]\n\n \"\"\"\n @spec values(t) :: [value]\n def values(dict) do\n target(dict).values(dict)\n end\n\n @doc \"\"\"\n Returns the number of elements in `dict`.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> Dict.size(dict)\n 2\n\n \"\"\"\n @spec size(t) :: non_neg_integer\n def size(dict) do\n target(dict).size(dict)\n end\n\n @doc \"\"\"\n Returns whether the given `key` exists in the given `dict`.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1], dict_impl.new)\n iex> Dict.has_key?(dict, :a)\n true\n iex> Dict.has_key?(dict, :b)\n false\n\n \"\"\"\n @spec has_key?(t, key) :: boolean\n def has_key?(dict, key) do\n target(dict).has_key?(dict, key)\n end\n\n @doc \"\"\"\n Returns the value associated with `key` in `dict`. If `dict` does not\n contain `key`, returns `default` (or `nil` if not provided).\n\n ## Examples\n\n iex> dict = Enum.into([a: 1], dict_impl.new)\n iex> Dict.get(dict, :a)\n 1\n iex> Dict.get(dict, :b)\n nil\n iex> Dict.get(dict, :b, 3)\n 3\n \"\"\"\n @spec get(t, key, value) :: value\n def get(dict, key, default \\\\ nil) do\n target(dict).get(dict, key, default)\n end\n\n @doc \"\"\"\n Returns `{:ok, value}` associated with `key` in `dict`.\n If `dict` does not contain `key`, returns `:error`.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1], dict_impl.new)\n iex> Dict.fetch(dict, :a)\n {:ok, 1}\n iex> Dict.fetch(dict, :b)\n :error\n\n \"\"\"\n @spec fetch(t, key) :: value\n def fetch(dict, key) do\n target(dict).fetch(dict, key)\n end\n\n @doc \"\"\"\n Returns the value associated with `key` in `dict`. If `dict` does not\n contain `key`, it raises `KeyError`.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1], dict_impl.new)\n iex> Dict.fetch!(dict, :a)\n 1\n\n \"\"\"\n @spec fetch!(t, key) :: value | no_return\n def fetch!(dict, key) do\n target(dict).fetch!(dict, key)\n end\n\n @doc \"\"\"\n Stores the given `value` under `key` in `dict`.\n If `dict` already has `key`, the stored value is replaced by the new one.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict = Dict.put(dict, :a, 3)\n iex> Dict.get(dict, :a)\n 3\n\n \"\"\"\n @spec put(t, key, value) :: t\n def put(dict, key, val) do\n target(dict).put(dict, key, val)\n end\n\n @doc \"\"\"\n Puts the given `value` under `key` in `dict` unless `key` already exists.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict = Dict.put_new(dict, :a, 3)\n iex> Dict.get(dict, :a)\n 1\n\n \"\"\"\n @spec put_new(t, key, value) :: t\n def put_new(dict, key, val) do\n target(dict).put_new(dict, key, val)\n end\n\n @doc \"\"\"\n Removes the entry stored under the given `key` from `dict`.\n If `dict` does not contain `key`, returns the dictionary unchanged.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict = Dict.delete(dict, :a)\n iex> Dict.get(dict, :a)\n nil\n\n iex> dict = Enum.into([b: 2], dict_impl.new)\n iex> Dict.delete(dict, :a) == dict\n true\n\n \"\"\"\n @spec delete(t, key) :: t\n def delete(dict, key) do\n target(dict).delete(dict, key)\n end\n\n @doc \"\"\"\n Merges the dict `dict2` into dict `dict1`.\n\n If one of the dict `dict2` entries already exists in the `dict`,\n the functions in entries in `dict2` have higher precedence unless a\n function is given to resolve conflicts.\n\n Notice this function is polymorphic as it merges dicts of any\n type. Each dict implementation also provides a `merge` function,\n but they can only merge dicts of the same type.\n\n ## Examples\n\n iex> dict1 = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict2 = Enum.into([a: 3, d: 4], dict_impl.new)\n iex> dict = Dict.merge(dict1, dict2)\n iex> [a: Dict.get(dict, :a), b: Dict.get(dict, :b), d: Dict.get(dict, :d)]\n [a: 3, b: 2, d: 4]\n\n iex> dict1 = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict2 = Enum.into([a: 3, d: 4], dict_impl.new)\n iex> dict = Dict.merge(dict1, dict2, fn(_k, v1, v2) ->\n ...> v1 + v2\n ...> end)\n iex> [a: Dict.get(dict, :a), b: Dict.get(dict, :b), d: Dict.get(dict, :d)]\n [a: 4, b: 2, d: 4]\n\n \"\"\"\n @spec merge(t, t, (key, value, value -> value)) :: t\n def merge(dict1, dict2, fun \\\\ fn(_k, _v1, v2) -> v2 end) do\n target1 = target(dict1)\n target2 = target(dict2)\n\n if target1 == target2 do\n target1.merge(dict1, dict2, fun)\n else\n Enumerable.reduce(dict2, {:cont, dict1}, fn({k, v}, acc) ->\n {:cont, target1.update(acc, k, v, fn(other) -> fun.(k, other, v) end)}\n end) |> elem(1)\n end\n end\n\n @doc \"\"\"\n Returns the value associated with `key` in `dict` as\n well as the `dict` without `key`.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1], dict_impl.new)\n iex> {v, dict} = Dict.pop dict, :a\n iex> {v, Enum.sort(dict)}\n {1,[]}\n\n iex> dict = Enum.into([a: 1], dict_impl.new)\n iex> {v, dict} = Dict.pop dict, :b\n iex> {v, Enum.sort(dict)}\n {nil,[a: 1]}\n\n iex> dict = Enum.into([a: 1], dict_impl.new)\n iex> {v, dict} = Dict.pop dict, :b, 3\n iex> {v, Enum.sort(dict)}\n {3,[a: 1]}\n\n \"\"\"\n @spec pop(t, key, value) :: {value, t}\n def pop(dict, key, default \\\\ nil) do\n target(dict).pop(dict, key, default)\n end\n\n @doc \"\"\"\n Update a value in `dict` by calling `fun` on the value to get a new\n value. An exception is generated if `key` is not present in the dict.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict = Dict.update!(dict, :a, fn(val) -> -val end)\n iex> Dict.get(dict, :a)\n -1\n\n \"\"\"\n @spec update!(t, key, (value -> value)) :: t\n def update!(dict, key, fun) do\n target(dict).update!(dict, key, fun)\n end\n\n @doc \"\"\"\n Update a value in `dict` by calling `fun` on the value to get a new value. If\n `key` is not present in `dict` then `initial` will be stored as the first\n value.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict = Dict.update(dict, :c, 3, fn(val) -> -val end)\n iex> Dict.get(dict, :c)\n 3\n\n \"\"\"\n @spec update(t, key, value, (value -> value)) :: t\n def update(dict, key, initial, fun) do\n target(dict).update(dict, key, initial, fun)\n end\n\n @doc \"\"\"\n Returns a tuple of two dicts, where the first dict contains only\n entries from `dict` with keys in `keys`, and the second dict\n contains only entries from `dict` with keys not in `keys`\n\n Any non-member keys are ignored.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2, c: 3, d: 4], dict_impl.new)\n iex> {dict1, dict2} = Dict.split(dict, [:a, :c, :e])\n iex> {Dict.to_list(dict1) |> Enum.sort, Dict.to_list(dict2) |> Enum.sort}\n {[a: 1, c: 3], [b: 2, d: 4]}\n\n iex> dict = Enum.into([], dict_impl.new)\n iex> {dict1, dict2} = Dict.split(dict, [:a, :c])\n iex> {Dict.to_list(dict1), Dict.to_list(dict2)}\n {[], []}\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> {dict1, dict2} = Dict.split(dict, [:a, :b, :c])\n iex> {Dict.to_list(dict1) |> Enum.sort, Dict.to_list(dict2)}\n {[a: 1, b: 2], []}\n\n \"\"\"\n @spec split(t, [key]) :: {t, t}\n def split(dict, keys) do\n target(dict).split(dict, keys)\n end\n\n @doc \"\"\"\n Returns a new dict where the given `keys` are removed from `dict`.\n Any non-member keys are ignored.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict = Dict.drop(dict, [:a, :c, :d])\n iex> Dict.to_list(dict)\n [b: 2]\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict = Dict.drop(dict, [:c, :d])\n iex> Dict.to_list(dict) |> Enum.sort\n [a: 1, b: 2]\n\n \"\"\"\n @spec drop(t, [key]) :: t\n def drop(dict, keys) do\n target(dict).drop(dict, keys)\n end\n\n @doc \"\"\"\n Returns a new dict where only the keys in `keys` from `dict` are included.\n\n Any non-member keys are ignored.\n\n ## Examples\n\n iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)\n iex> dict = Dict.take(dict, [:a, :c, :d])\n iex> Dict.to_list(dict)\n [a: 1]\n iex> dict = Dict.take(dict, [:c, :d])\n iex> Dict.to_list(dict)\n []\n\n \"\"\"\n @spec take(t, [key]) :: t\n def take(dict, keys) do\n target(dict).take(dict, keys)\n end\n\n @doc false\n @spec empty(t) :: t\n def empty(dict) do\n target(dict).empty(dict)\n end\n\n @doc \"\"\"\n Check if two dicts are equal using `===`.\n\n Notice this function is polymorphic as it compares dicts of any\n type. Each dict implementation also provides an `equal?` function,\n but they can only compare dicts of the same type.\n\n ## Examples\n\n iex> dict1 = Enum.into([a: 2, b: 3, f: 5, c: 123], dict_impl.new)\n iex> dict2 = [a: 2, b: 3, f: 5, c: 123]\n iex> Dict.equal?(dict1, dict2)\n true\n\n iex> dict1 = Enum.into([a: 2, b: 3, f: 5, c: 123], dict_impl.new)\n iex> dict2 = []\n iex> Dict.equal?(dict1, dict2)\n false\n\n \"\"\"\n @spec equal?(t, t) :: boolean\n def equal?(dict1, dict2) do\n target1 = target(dict1)\n target2 = target(dict2)\n\n cond do\n target1 == target2 ->\n target1.equal?(dict1, dict2)\n\n target1.size(dict1) == target2.size(dict2) ->\n Enumerable.reduce(dict2, {:cont, true}, fn({k, v}, _acc) ->\n case target1.fetch(dict1, k) do\n {:ok, ^v} -> {:cont, true}\n _ -> {:halt, false}\n end\n end) |> elem(1)\n\n true ->\n false\n end\n end\n\n @doc \"\"\"\n Returns a list of key-value pairs stored in `dict`.\n No particular order is enforced.\n \"\"\"\n @spec to_list(t) :: list\n def to_list(dict) do\n target(dict).to_list(dict)\n end\n\n defp unsupported_dict(dict) do\n raise ArgumentError, \"unsupported dict: #{inspect dict}\"\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"5cee19067d6b6bf97d0022cab71b73fcb9313c71","subject":"Enum.join\/2 and Enum.map_join\/3 now uses iolists","message":"Enum.join\/2 and Enum.map_join\/3 now uses iolists\n","repos":"beedub\/elixir,beedub\/elixir,gfvcastro\/elixir,kimshrier\/elixir,lexmag\/elixir,michalmuskala\/elixir,joshprice\/elixir,pedrosnk\/elixir,kelvinst\/elixir,kimshrier\/elixir,ggcampinho\/elixir,antipax\/elixir,elixir-lang\/elixir,kelvinst\/elixir,lexmag\/elixir,antipax\/elixir,pedrosnk\/elixir,gfvcastro\/elixir,ggcampinho\/elixir","old_file":"lib\/elixir\/lib\/enum.ex","new_file":"lib\/elixir\/lib\/enum.ex","new_contents":"defprotocol Enumerable do\n @moduledoc \"\"\"\n Enumerable protocol used by `Enum` and `Stream` modules.\n\n When you invoke a function in the `Enum` module, the first argument\n is usually a collection that must implement this protocol. For example,\n the expression\n\n Enum.map([1, 2, 3], &(&1 * 2))\n\n invokes underneath `Enumerable.reduce\/3` to perform the reducing\n operation that builds a mapped list by calling the mapping function\n `&(&1 * 2)` on every element in the collection and cons'ing the\n element with an accumulated list.\n\n Internally, `Enum.map\/2` is implemented as follows:\n\n def map(enum, fun) do\n reducer = fn x, acc -> {:cont, [fun.(x)|acc]} end\n Enumerable.reduce(enum, {:cont, []}, reducer) |> elem(1) |> :lists.reverse()\n end\n\n Notice the user given function is wrapped into a `reducer` function.\n The `reducer` function must return a tagged tuple after each step,\n as described in the `acc\/0` type.\n\n The reason the accumulator requires a tagged tuple is to allow the\n reducer function to communicate to the underlying enumerable the end\n of enumeration, allowing any open resource to be properly closed. It\n also allows suspension of the enumeration, which is useful when\n interleaving between many enumerables is required (as in zip).\n\n Finally, `Enumerable.reduce\/3` will return another tagged tuple,\n as represented by the `result\/0` type.\n \"\"\"\n\n @typedoc \"\"\"\n The accumulator value for each step.\n\n It must be a tagged tuple with one of the following \"tags\":\n\n * `:cont` - the enumeration should continue\n * `:halt` - the enumeration should halt immediately\n * `:suspend` - the enumeration should be suspended immediately\n\n Depending on the accumulator value, the result returned by\n `Enumerable.reduce\/3` will change. Please check the `result`\n type docs for more information.\n\n In case a reducer function returns a `:suspend` accumulator,\n it must be explicitly handled by the caller and never leak.\n \"\"\"\n @type acc :: {:cont, term} | {:halt, term} | {:suspend, term}\n\n @typedoc \"\"\"\n The reducer function.\n\n Should be called with the collection element and the\n accumulator contents. Returns the accumulator for\n the next enumeration step.\n \"\"\"\n @type reducer :: (term, term -> acc)\n\n @typedoc \"\"\"\n The result of the reduce operation.\n\n It may be *done* when the enumeration is finished by reaching\n its end, or *halted*\/*suspended* when the enumeration was halted\n or suspended by the reducer function.\n\n In case a reducer function returns the `:suspend` accumulator, the\n `:suspended` tuple must be explicitly handled by the caller and\n never leak. In practice, this means regular enumeration functions\n just need to be concerned about `:done` and `:halted` results.\n\n Furthermore, a `:suspend` call must always be followed by another call,\n eventually halting or continuing until the end.\n \"\"\"\n @type result :: {:done, term} | {:halted, term} | {:suspended, term, continuation}\n\n @typedoc \"\"\"\n A partially applied reduce function.\n\n The continuation is the closure returned as a result when\n the enumeration is suspended. When invoked, it expects\n a new accumulator and it returns the result.\n\n A continuation is easily implemented as long as the reduce\n function is defined in a tail recursive fashion. If the function\n is tail recursive, all the state is passed as arguments, so\n the continuation would simply be the reducing function partially\n applied.\n \"\"\"\n @type continuation :: (acc -> result)\n\n @doc \"\"\"\n Reduces the collection into a value.\n\n Most of the operations in `Enum` are implemented in terms of reduce.\n This function should apply the given `reducer` function to each\n item in the collection and proceed as expected by the returned accumulator.\n\n As an example, here is the implementation of `reduce` for lists:\n\n def reduce(_, {:halt, acc}, _fun), do: {:halted, acc}\n def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)}\n def reduce([], {:cont, acc}, _fun), do: {:done, acc}\n def reduce([h|t], {:cont, acc}, fun), do: reduce(t, fun.(h, acc), fun)\n\n \"\"\"\n @spec reduce(t, acc, reducer) :: result\n def reduce(collection, acc, fun)\n\n @doc \"\"\"\n Checks if a value exists within the collection.\n\n It should return `{:ok, boolean}`.\n\n If `{:error, __MODULE__}` is returned a default algorithm using `reduce` and\n the match (`===`) operator is used. This algorithm runs in linear time.\n\n Please force use of the default algorithm unless you can implement an\n algorithm that is significantly faster.\n \"\"\"\n @spec member?(t, term) :: {:ok, boolean} | {:error, module}\n def member?(collection, value)\n\n @doc \"\"\"\n Retrieves the collection's size.\n\n It should return `{:ok, size}`.\n\n If `{:error, __MODULE__}` is returned a default algorithm using `reduce` and\n the match (`===`) operator is used. This algorithm runs in linear time.\n\n Please force use of the default algorithm unless you can implement an\n algorithm that is significantly faster.\n \"\"\"\n @spec count(t) :: {:ok, non_neg_integer} | {:error, module}\n def count(collection)\nend\n\ndefmodule Enum do\n import Kernel, except: [max: 2, min: 2]\n\n @moduledoc \"\"\"\n Provides a set of algorithms that enumerate over collections according to the\n `Enumerable` protocol:\n\n iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end)\n [2,4,6]\n\n Some particular types, like dictionaries, yield a specific format on\n enumeration. For dicts, the argument is always a `{key, value}` tuple:\n\n iex> dict = %{a: 1, b: 2}\n iex> Enum.map(dict, fn {k, v} -> {k, v * 2} end)\n [a: 2, b: 4]\n\n Note that the functions in the `Enum` module are eager: they always start\n the enumeration of the given collection. The `Stream` module allows\n lazy enumeration of collections and provides infinite streams.\n\n Since the majority of the functions in `Enum` enumerate the whole\n collection and return a list as result, infinite streams need to\n be carefully used with such functions, as they can potentially run\n forever. For example:\n\n Enum.each Stream.cycle([1,2,3]), &IO.puts(&1)\n\n \"\"\"\n\n @compile :inline_list_funcs\n\n @type t :: Enumerable.t\n @type element :: any\n @type index :: non_neg_integer\n @type default :: any\n\n # Require Stream.Reducers and its callbacks\n require Stream.Reducers, as: R\n\n defmacrop cont(_, entry, acc) do\n quote do: {:cont, [unquote(entry)|unquote(acc)]}\n end\n\n defmacrop acc(h, n, _) do\n quote do: {unquote(h), unquote(n)}\n end\n\n defmacrop cont_with_acc(f, entry, h, n, _) do\n quote do\n {:cont, {[unquote(entry)|unquote(h)], unquote(n)}}\n end\n end\n\n @doc \"\"\"\n Invokes the given `fun` for each item in the `collection` and returns `false`\n if at least one invocation returns `false`. Otherwise returns `true`.\n\n ## Examples\n\n iex> Enum.all?([2, 4, 6], fn(x) -> rem(x, 2) == 0 end)\n true\n\n iex> Enum.all?([2, 3, 4], fn(x) -> rem(x, 2) == 0 end)\n false\n\n If no function is given, it defaults to checking if\n all items in the collection evaluate to `true`.\n\n iex> Enum.all?([1, 2, 3])\n true\n\n iex> Enum.all?([1, nil, 3])\n false\n\n \"\"\"\n @spec all?(t) :: boolean\n @spec all?(t, (element -> as_boolean(term))) :: boolean\n\n def all?(collection, fun \\\\ fn(x) -> x end)\n\n def all?(collection, fun) when is_list(collection) do\n do_all?(collection, fun)\n end\n\n def all?(collection, fun) do\n Enumerable.reduce(collection, {:cont, true}, fn(entry, _) ->\n if fun.(entry), do: {:cont, true}, else: {:halt, false}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Invokes the given `fun` for each item in the `collection` and returns `true` if\n at least one invocation returns `true`. Returns `false` otherwise.\n\n ## Examples\n\n iex> Enum.any?([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n false\n\n iex> Enum.any?([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n true\n\n If no function is given, it defaults to checking if\n at least one item in the collection evaluates to `true`.\n\n iex> Enum.any?([false, false, false])\n false\n\n iex> Enum.any?([false, true, false])\n true\n\n \"\"\"\n @spec any?(t) :: boolean\n @spec any?(t, (element -> as_boolean(term))) :: boolean\n\n def any?(collection, fun \\\\ fn(x) -> x end)\n\n def any?(collection, fun) when is_list(collection) do\n do_any?(collection, fun)\n end\n\n def any?(collection, fun) do\n Enumerable.reduce(collection, {:cont, false}, fn(entry, _) ->\n if fun.(entry), do: {:halt, true}, else: {:cont, false}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Finds the element at the given index (zero-based).\n Returns `default` if index is out of bounds.\n\n ## Examples\n\n iex> Enum.at([2, 4, 6], 0)\n 2\n\n iex> Enum.at([2, 4, 6], 2)\n 6\n\n iex> Enum.at([2, 4, 6], 4)\n nil\n\n iex> Enum.at([2, 4, 6], 4, :none)\n :none\n\n \"\"\"\n @spec at(t, integer) :: element | nil\n @spec at(t, integer, default) :: element | default\n def at(collection, n, default \\\\ nil) do\n case fetch(collection, n) do\n {:ok, h} -> h\n :error -> default\n end\n end\n\n @doc \"\"\"\n Shortcut to `chunk(coll, n, n)`.\n \"\"\"\n @spec chunk(t, non_neg_integer) :: [list]\n def chunk(coll, n), do: chunk(coll, n, n, nil)\n\n @doc \"\"\"\n Returns a collection of lists containing `n` items each, where\n each new chunk starts `step` elements into the collection.\n\n `step` is optional and, if not passed, defaults to `n`, i.e.\n chunks do not overlap. If the final chunk does not have `n`\n elements to fill the chunk, elements are taken as necessary\n from `pad` if it was passed. If `pad` is passed and does not\n have enough elements to fill the chunk, then the chunk is\n returned anyway with less than `n` elements. If `pad` is not\n passed at all or is `nil`, then the partial chunk is discarded\n from the result.\n\n ## Examples\n\n iex> Enum.chunk([1, 2, 3, 4, 5, 6], 2)\n [[1, 2], [3, 4], [5, 6]]\n\n iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 2)\n [[1, 2, 3], [3, 4, 5]]\n\n iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 2, [7])\n [[1, 2, 3], [3, 4, 5], [5, 6, 7]]\n\n iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 3, [])\n [[1, 2, 3], [4, 5, 6]]\n\n \"\"\"\n @spec chunk(t, non_neg_integer, non_neg_integer) :: [list]\n @spec chunk(t, non_neg_integer, non_neg_integer, t | nil) :: [list]\n def chunk(coll, n, step, pad \\\\ nil) when n > 0 and step > 0 do\n limit = :erlang.max(n, step)\n\n {_, {acc, {buffer, i}}} =\n Enumerable.reduce(coll, {:cont, {[], {[], 0}}}, R.chunk(n, step, limit))\n\n if nil?(pad) || i == 0 do\n :lists.reverse(acc)\n else\n buffer = :lists.reverse(buffer) ++ take(pad, n - i)\n :lists.reverse([buffer|acc])\n end\n end\n\n @doc \"\"\"\n Splits `coll` on every element for which `fun` returns a new value.\n\n ## Examples\n\n iex> Enum.chunk_by([1, 2, 2, 3, 4, 4, 6, 7, 7], &(rem(&1, 2) == 1))\n [[1], [2, 2], [3], [4, 4, 6], [7, 7]]\n\n \"\"\"\n @spec chunk_by(t, (element -> any)) :: [list]\n def chunk_by(coll, fun) do\n {_, {acc, res}} =\n Enumerable.reduce(coll, {:cont, {[], nil}}, R.chunk_by(fun))\n\n case res do\n {buffer, _} ->\n :lists.reverse([:lists.reverse(buffer) | acc])\n nil ->\n []\n end\n end\n\n @doc \"\"\"\n Given an enumerable of enumerables, concatenate the enumerables into a single list.\n\n ## Examples\n\n iex> Enum.concat([1..3, 4..6, 7..9])\n [1,2,3,4,5,6,7,8,9]\n\n iex> Enum.concat([[1, [2], 3], [4], [5, 6]])\n [1,[2],3,4,5,6]\n\n \"\"\"\n @spec concat(t) :: t\n def concat(enumerables) do\n do_concat(enumerables)\n end\n\n @doc \"\"\"\n Concatenates the enumerable on the right with the enumerable on the left.\n\n This function produces the same result as the `Kernel.++\/2` operator for lists.\n\n ## Examples\n\n iex> Enum.concat(1..3, 4..6)\n [1,2,3,4,5,6]\n\n iex> Enum.concat([1, 2, 3], [4, 5, 6])\n [1,2,3,4,5,6]\n\n \"\"\"\n @spec concat(t, t) :: t\n def concat(left, right) when is_list(left) and is_list(right) do\n left ++ right\n end\n\n def concat(left, right) do\n do_concat([left, right])\n end\n\n defp do_concat(enumerable) do\n fun = &[&1|&2]\n reduce(enumerable, [], &reduce(&1, &2, fun)) |> :lists.reverse\n end\n\n @doc \"\"\"\n Returns the collection's size.\n\n ## Examples\n\n iex> Enum.count([1, 2, 3])\n 3\n\n \"\"\"\n @spec count(t) :: non_neg_integer\n def count(collection) when is_list(collection) do\n :erlang.length(collection)\n end\n\n def count(collection) do\n case Enumerable.count(collection) do\n {:ok, value} when is_integer(value) ->\n value\n {:error, module} ->\n module.reduce(collection, {:cont, 0}, fn\n _, acc -> {:cont, acc + 1}\n end) |> elem(1)\n end\n end\n\n @doc \"\"\"\n Returns the count of items in the collection for which\n `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.count([1, 2, 3, 4, 5], fn(x) -> rem(x, 2) == 0 end)\n 2\n\n \"\"\"\n @spec count(t, (element -> as_boolean(term))) :: non_neg_integer\n def count(collection, fun) do\n Enumerable.reduce(collection, {:cont, 0}, fn(entry, acc) ->\n {:cont, if(fun.(entry), do: acc + 1, else: acc)}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Drops the first `count` items from `collection`.\n\n If a negative value `count` is given, the last `count`\n values will be dropped. The collection is enumerated\n once to retrieve the proper index and the remaining\n calculation is performed from the end.\n\n ## Examples\n\n iex> Enum.drop([1, 2, 3], 2)\n [3]\n\n iex> Enum.drop([1, 2, 3], 10)\n []\n\n iex> Enum.drop([1, 2, 3], 0)\n [1,2,3]\n\n iex> Enum.drop([1, 2, 3], -1)\n [1,2]\n\n \"\"\"\n @spec drop(t, integer) :: list\n def drop(collection, count) when is_list(collection) and count >= 0 do\n do_drop(collection, count)\n end\n\n def drop(collection, count) when count >= 0 do\n res =\n reduce(collection, count, fn\n x, acc when is_list(acc) -> [x|acc]\n x, 0 -> [x]\n _, acc when acc > 0 -> acc - 1\n end)\n if is_list(res), do: :lists.reverse(res), else: []\n end\n\n def drop(collection, count) when count < 0 do\n do_drop(reverse(collection), abs(count)) |> :lists.reverse\n end\n\n @doc \"\"\"\n Drops items at the beginning of `collection` while `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.drop_while([1, 2, 3, 4, 5], fn(x) -> x < 3 end)\n [3,4,5]\n\n \"\"\"\n @spec drop_while(t, (element -> as_boolean(term))) :: list\n def drop_while(collection, fun) when is_list(collection) do\n do_drop_while(collection, fun)\n end\n\n def drop_while(collection, fun) do\n {_, {res, _}} =\n Enumerable.reduce(collection, {:cont, {[], true}}, R.drop_while(fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Invokes the given `fun` for each item in the `collection`.\n Returns `:ok`.\n\n ## Examples\n\n Enum.each([\"some\", \"example\"], fn(x) -> IO.puts x end)\n \"some\"\n \"example\"\n #=> :ok\n\n \"\"\"\n @spec each(t, (element -> any)) :: :ok\n def each(collection, fun) when is_list(collection) do\n :lists.foreach(fun, collection)\n :ok\n end\n\n def each(collection, fun) do\n reduce(collection, nil, fn(entry, _) ->\n fun.(entry)\n nil\n end)\n :ok\n end\n\n @doc \"\"\"\n Returns `true` if the collection is empty, otherwise `false`.\n\n ## Examples\n\n iex> Enum.empty?([])\n true\n\n iex> Enum.empty?([1, 2, 3])\n false\n\n \"\"\"\n @spec empty?(t) :: boolean\n def empty?(collection) when is_list(collection) do\n collection == []\n end\n\n def empty?(collection) do\n Enumerable.reduce(collection, {:cont, true}, fn(_, _) -> {:halt, false} end) |> elem(1)\n end\n\n @doc \"\"\"\n Finds the element at the given index (zero-based).\n Returns `{:ok, element}` if found, otherwise `:error`.\n\n A negative index can be passed, which means the collection is\n enumerated once and the index is counted from the end (i.e.\n `-1` fetches the last element).\n\n ## Examples\n\n iex> Enum.fetch([2, 4, 6], 0)\n {:ok, 2}\n\n iex> Enum.fetch([2, 4, 6], 2)\n {:ok, 6}\n\n iex> Enum.fetch([2, 4, 6], 4)\n :error\n\n \"\"\"\n @spec fetch(t, integer) :: {:ok, element} | :error\n def fetch(collection, n) when is_list(collection) and n >= 0 do\n do_fetch(collection, n)\n end\n\n def fetch(collection, n) when n >= 0 do\n res =\n Enumerable.reduce(collection, {:cont, 0}, fn(entry, acc) ->\n if acc == n do\n {:halt, entry}\n else\n {:cont, acc + 1}\n end\n end)\n\n case res do\n {:halted, entry} -> {:ok, entry}\n {:done, _} -> :error\n end\n end\n\n def fetch(collection, n) when n < 0 do\n do_fetch(reverse(collection), abs(n + 1))\n end\n\n @doc \"\"\"\n Finds the element at the given index (zero-based).\n Raises `OutOfBoundsError` if the given position\n is outside the range of the collection.\n\n ## Examples\n\n iex> Enum.fetch!([2, 4, 6], 0)\n 2\n\n iex> Enum.fetch!([2, 4, 6], 2)\n 6\n\n iex> Enum.fetch!([2, 4, 6], 4)\n ** (Enum.OutOfBoundsError) out of bounds error\n\n \"\"\"\n @spec fetch!(t, integer) :: element | no_return\n def fetch!(collection, n) do\n case fetch(collection, n) do\n {:ok, h} -> h\n :error -> raise Enum.OutOfBoundsError\n end\n end\n\n @doc \"\"\"\n Filters the collection, i.e. returns only those elements\n for which `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.filter([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)\n [2]\n\n \"\"\"\n @spec filter(t, (element -> as_boolean(term))) :: list\n def filter(collection, fun) when is_list(collection) do\n for item <- collection, fun.(item), do: item\n end\n\n def filter(collection, fun) do\n Enumerable.reduce(collection, {:cont, []}, R.filter(fun))\n |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Filters the collection and maps its values in one pass.\n\n ## Examples\n\n iex> Enum.filter_map([1, 2, 3], fn(x) -> rem(x, 2) == 0 end, &(&1 * 2))\n [4]\n\n \"\"\"\n @spec filter_map(t, (element -> as_boolean(term)), (element -> element)) :: list\n def filter_map(collection, filter, mapper) when is_list(collection) do\n for item <- collection, filter.(item), do: mapper.(item)\n end\n\n def filter_map(collection, filter, mapper) do\n Enumerable.reduce(collection, {:cont, []}, R.filter_map(filter, mapper))\n |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Returns the first item for which `fun` returns a truthy value. If no such\n item is found, returns `ifnone`.\n\n ## Examples\n\n iex> Enum.find([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n nil\n\n iex> Enum.find([2, 4, 6], 0, fn(x) -> rem(x, 2) == 1 end)\n 0\n\n iex> Enum.find([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n 3\n\n \"\"\"\n @spec find(t, (element -> any)) :: element | nil\n @spec find(t, default, (element -> any)) :: element | default\n def find(collection, ifnone \\\\ nil, fun)\n\n def find(collection, ifnone, fun) when is_list(collection) do\n do_find(collection, ifnone, fun)\n end\n\n def find(collection, ifnone, fun) do\n Enumerable.reduce(collection, {:cont, ifnone}, fn(entry, ifnone) ->\n if fun.(entry), do: {:halt, entry}, else: {:cont, ifnone}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Similar to `find\/3`, but returns the value of the function\n invocation instead of the element itself.\n\n ## Examples\n\n iex> Enum.find_value([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n nil\n\n iex> Enum.find_value([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n true\n\n \"\"\"\n @spec find_value(t, (element -> any)) :: any | :nil\n @spec find_value(t, any, (element -> any)) :: any | :nil\n def find_value(collection, ifnone \\\\ nil, fun)\n\n def find_value(collection, ifnone, fun) when is_list(collection) do\n do_find_value(collection, ifnone, fun)\n end\n\n def find_value(collection, ifnone, fun) do\n Enumerable.reduce(collection, {:cont, ifnone}, fn(entry, ifnone) ->\n fun_entry = fun.(entry)\n if fun_entry, do: {:halt, fun_entry}, else: {:cont, ifnone}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Similar to `find\/3`, but returns the index (zero-based)\n of the element instead of the element itself.\n\n ## Examples\n\n iex> Enum.find_index([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n nil\n\n iex> Enum.find_index([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n 1\n\n \"\"\"\n @spec find_index(t, (element -> any)) :: index | :nil\n def find_index(collection, fun) when is_list(collection) do\n do_find_index(collection, 0, fun)\n end\n\n def find_index(collection, fun) do\n res =\n Enumerable.reduce(collection, {:cont, 0}, fn(entry, acc) ->\n if fun.(entry), do: {:halt, acc}, else: {:cont, acc + 1}\n end)\n\n case res do\n {:halted, entry} -> entry\n {:done, _} -> nil\n end\n end\n\n @doc \"\"\"\n Returns a new collection appending the result of invoking `fun`\n on each corresponding item of `collection`.\n\n The given function should return an enumerable.\n\n ## Examples\n\n iex> Enum.flat_map([:a, :b, :c], fn(x) -> [x, x] end)\n [:a, :a, :b, :b, :c, :c]\n\n iex> Enum.flat_map([{1,3}, {4,6}], fn({x,y}) -> x..y end)\n [1, 2, 3, 4, 5, 6]\n\n \"\"\"\n @spec flat_map(t, (element -> t)) :: list\n def flat_map(collection, fun) do\n reduce(collection, [], fn(entry, acc) ->\n reduce(fun.(entry), acc, &[&1|&2])\n end) |> :lists.reverse\n end\n\n @doc \"\"\"\n Maps and reduces a collection, flattening the given results.\n\n It expects an accumulator and a function that receives each stream item\n and an accumulator, and must return a tuple containing a new stream\n (often a list) with the new accumulator or a tuple with `:halt` as first\n element and the accumulator as second.\n\n ## Examples\n\n iex> enum = 1..100\n iex> n = 3\n iex> Enum.flat_map_reduce(enum, 0, fn i, acc ->\n ...> if acc < n, do: {[i], acc + 1}, else: {:halt, acc}\n ...> end)\n {[1,2,3], 3}\n\n \"\"\"\n @spec flat_map_reduce(t, acc, fun) :: {[any], any} when\n fun: (element, acc -> {t, acc} | {:halt, acc}),\n acc: any\n def flat_map_reduce(collection, acc, fun) do\n {_, {list, acc}} =\n Enumerable.reduce(collection, {:cont, {[], acc}}, fn(entry, {list, acc}) ->\n case fun.(entry, acc) do\n {:halt, acc} ->\n {:halt, {list, acc}}\n {entries, acc} ->\n {:cont, {reduce(entries, list, &[&1|&2]), acc}}\n end\n end)\n\n {:lists.reverse(list), acc}\n end\n\n @doc \"\"\"\n Intersperses `element` between each element of the enumeration.\n\n Complexity: O(n)\n\n ## Examples\n\n iex> Enum.intersperse([1, 2, 3], 0)\n [1, 0, 2, 0, 3]\n\n iex> Enum.intersperse([1], 0)\n [1]\n\n iex> Enum.intersperse([], 0)\n []\n\n \"\"\"\n @spec intersperse(t, element) :: list\n def intersperse(collection, element) do\n list =\n reduce(collection, [], fn(x, acc) ->\n [x, element | acc]\n end) |> :lists.reverse()\n\n case list do\n [] -> []\n [_|t] -> t # Head is a superfluous intersperser element\n end\n end\n\n @doc \"\"\"\n Inserts the given enumerable into a collectable.\n\n ## Examples\n\n iex> Enum.into([1, 2], [0])\n [0, 1, 2]\n\n iex> Enum.into([a: 1, b: 2], %{})\n %{a: 1, b: 2}\n\n \"\"\"\n @spec into(Enumerable.t, Collectable.t) :: Collectable.t\n def into(collection, list) when is_list(list) do\n list ++ to_list(collection)\n end\n\n def into(collection, %{} = map) when is_list(collection) and map_size(map) == 0 do\n :maps.from_list(collection)\n end\n\n def into(collection, collectable) do\n {initial, fun} = Collectable.into(collectable)\n into(collection, initial, fun, fn x, acc ->\n fun.(acc, {:cont, x})\n end)\n end\n\n @doc \"\"\"\n Inserts the given enumerable into a collectable\n according to the transformation function.\n\n ## Examples\n\n iex> Enum.into([2, 3], [3], fn x -> x * 3 end)\n [3, 6, 9]\n\n \"\"\"\n @spec into(Enumerable.t, Collectable.t, (term -> term)) :: Collectable.t\n\n def into(collection, list, transform) when is_list(list) and is_function(transform, 1) do\n list ++ map(collection, transform)\n end\n\n def into(collection, collectable, transform) when is_function(transform, 1) do\n {initial, fun} = Collectable.into(collectable)\n into(collection, initial, fun, fn x, acc ->\n fun.(acc, {:cont, transform.(x)})\n end)\n end\n\n defp into(collection, initial, fun, callback) do\n try do\n reduce(collection, initial, callback)\n catch\n kind, reason ->\n stacktrace = System.stacktrace\n fun.(initial, :halt)\n :erlang.raise(kind, reason, stacktrace)\n else\n acc -> fun.(acc, :done)\n end\n end\n\n @doc \"\"\"\n Joins the given `collection` according to `joiner`.\n `joiner` can be either a binary or a list and the\n result will be of the same type as `joiner`. If\n `joiner` is not passed at all, it defaults to an\n empty binary.\n\n All items in the collection must be convertible\n to a binary, otherwise an error is raised.\n\n ## Examples\n\n iex> Enum.join([1, 2, 3])\n \"123\"\n\n iex> Enum.join([1, 2, 3], \" = \")\n \"1 = 2 = 3\"\n\n \"\"\"\n @spec join(t) :: String.t\n @spec join(t, String.t) :: String.t\n def join(collection, joiner \\\\ \"\")\n\n def join(collection, joiner) when is_binary(joiner) do\n reduced = reduce(collection, :first, fn\n entry, :first -> [enum_to_string(entry)]\n entry, acc -> [enum_to_string(entry), joiner|acc]\n end)\n if reduced == :first do\n \"\"\n else\n IO.chardata_to_string :lists.reverse(reduced)\n end\n end\n\n @doc \"\"\"\n Returns a new collection, where each item is the result\n of invoking `fun` on each corresponding item of `collection`.\n\n For dicts, the function expects a key-value tuple.\n\n ## Examples\n\n iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end)\n [2, 4, 6]\n\n iex> Enum.map([a: 1, b: 2], fn({k, v}) -> {k, -v} end)\n [a: -1, b: -2]\n\n \"\"\"\n @spec map(t, (element -> any)) :: list\n def map(collection, fun) when is_list(collection) do\n for item <- collection, do: fun.(item)\n end\n\n def map(collection, fun) do\n Enumerable.reduce(collection, {:cont, []}, R.map(fun)) |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Maps and joins the given `collection` in one pass.\n `joiner` can be either a binary or a list and the\n result will be of the same type as `joiner`. If\n `joiner` is not passed at all, it defaults to an\n empty binary.\n\n All items in the collection must be convertible\n to a binary, otherwise an error is raised.\n\n ## Examples\n\n iex> Enum.map_join([1, 2, 3], &(&1 * 2))\n \"246\"\n\n iex> Enum.map_join([1, 2, 3], \" = \", &(&1 * 2))\n \"2 = 4 = 6\"\n\n \"\"\"\n @spec map_join(t, (element -> any)) :: String.t\n @spec map_join(t, String.t, (element -> any)) :: String.t\n def map_join(collection, joiner \\\\ \"\", mapper)\n\n def map_join(collection, joiner, mapper) when is_binary(joiner) do\n reduced = reduce(collection, :first, fn\n entry, :first -> [enum_to_string(mapper.(entry))]\n entry, acc -> [enum_to_string(mapper.(entry)), joiner|acc]\n end)\n\n if reduced == :first do\n \"\"\n else\n IO.chardata_to_string :lists.reverse(reduced)\n end\n end\n\n @doc \"\"\"\n Invokes the given `fun` for each item in the `collection`\n while also keeping an accumulator. Returns a tuple where\n the first element is the mapped collection and the second\n one is the final accumulator.\n\n For dicts, the first tuple element must be a `{key, value}`\n tuple.\n\n ## Examples\n\n iex> Enum.map_reduce([1, 2, 3], 0, fn(x, acc) -> {x * 2, x + acc} end)\n {[2, 4, 6], 6}\n\n \"\"\"\n @spec map_reduce(t, any, (element, any -> any)) :: any\n def map_reduce(collection, acc, fun) when is_list(collection) do\n :lists.mapfoldl(fun, acc, collection)\n end\n\n def map_reduce(collection, acc, fun) do\n {list, acc} = reduce(collection, {[], acc}, fn(entry, {list, acc}) ->\n {new_entry, acc} = fun.(entry, acc)\n {[new_entry|list], acc}\n end)\n {:lists.reverse(list), acc}\n end\n\n @doc \"\"\"\n Returns the maximum value.\n Raises `EmptyError` if the collection is empty.\n\n ## Examples\n\n iex> Enum.max([1, 2, 3])\n 3\n\n \"\"\"\n @spec max(t) :: element | no_return\n def max(collection) do\n reduce(collection, &Kernel.max(&1, &2))\n end\n\n @doc \"\"\"\n Returns the maximum value as calculated by the given function.\n Raises `EmptyError` if the collection is empty.\n\n ## Examples\n\n iex> Enum.max_by([\"a\", \"aa\", \"aaa\"], fn(x) -> String.length(x) end)\n \"aaa\"\n\n \"\"\"\n @spec max_by(t, (element -> any)) :: element | no_return\n def max_by([h|t], fun) do\n reduce(t, {h, fun.(h)}, fn(entry, {_, fun_max} = old) ->\n fun_entry = fun.(entry)\n if(fun_entry > fun_max, do: {entry, fun_entry}, else: old)\n end) |> elem(0)\n end\n\n def max_by([], _fun) do\n raise Enum.EmptyError\n end\n\n def max_by(collection, fun) do\n result =\n reduce(collection, :first, fn\n entry, {_, fun_max} = old ->\n fun_entry = fun.(entry)\n if(fun_entry > fun_max, do: {entry, fun_entry}, else: old)\n entry, :first ->\n {entry, fun.(entry)}\n end)\n\n case result do\n :first -> raise Enum.EmptyError\n {entry, _} -> entry\n end\n end\n\n @doc \"\"\"\n Checks if `value` exists within the `collection`.\n\n Membership is tested with the match (`===`) operator, although\n enumerables like ranges may include floats inside the given\n range.\n\n ## Examples\n\n iex> Enum.member?(1..10, 5)\n true\n\n iex> Enum.member?([:a, :b, :c], :d)\n false\n\n \"\"\"\n @spec member?(t, element) :: boolean\n def member?(collection, value) when is_list(collection) do\n :lists.member(value, collection)\n end\n\n def member?(collection, value) do\n case Enumerable.member?(collection, value) do\n {:ok, value} when is_boolean(value) ->\n value\n {:error, module} ->\n module.reduce(collection, {:cont, false}, fn\n v, _ when v === value -> {:halt, true}\n _, _ -> {:cont, false}\n end) |> elem(1)\n end\n end\n\n @doc \"\"\"\n Returns the minimum value.\n Raises `EmptyError` if the collection is empty.\n\n ## Examples\n\n iex> Enum.min([1, 2, 3])\n 1\n\n \"\"\"\n @spec min(t) :: element | no_return\n def min(collection) do\n reduce(collection, &Kernel.min(&1, &2))\n end\n\n @doc \"\"\"\n Returns the minimum value as calculated by the given function.\n Raises `EmptyError` if the collection is empty.\n\n ## Examples\n\n iex> Enum.min_by([\"a\", \"aa\", \"aaa\"], fn(x) -> String.length(x) end)\n \"a\"\n\n \"\"\"\n @spec min_by(t, (element -> any)) :: element | no_return\n def min_by([h|t], fun) do\n reduce(t, {h, fun.(h)}, fn(entry, {_, fun_min} = old) ->\n fun_entry = fun.(entry)\n if(fun_entry < fun_min, do: {entry, fun_entry}, else: old)\n end) |> elem(0)\n end\n\n def min_by([], _fun) do\n raise Enum.EmptyError\n end\n\n def min_by(collection, fun) do\n result =\n reduce(collection, :first, fn\n entry, {_, fun_min} = old ->\n fun_entry = fun.(entry)\n if(fun_entry < fun_min, do: {entry, fun_entry}, else: old)\n entry, :first ->\n {entry, fun.(entry)}\n end)\n\n case result do\n :first -> raise Enum.EmptyError\n {entry, _} -> entry\n end\n end\n\n @doc \"\"\"\n Returns the sum of all values.\n\n Raises `ArithmeticError` if collection contains a non-numeric value.\n\n ## Examples\n\n iex> Enum.sum([1, 2, 3])\n 6\n\n \"\"\"\n @spec sum(t) :: number\n def sum(collection) do\n reduce(collection, 0, &+\/2)\n end\n\n @doc \"\"\"\n Partitions `collection` into two collections, where the first one contains elements\n for which `fun` returns a truthy value, and the second one -- for which `fun`\n returns `false` or `nil`.\n\n ## Examples\n\n iex> Enum.partition([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)\n {[2], [1,3]}\n\n \"\"\"\n @spec partition(t, (element -> any)) :: {list, list}\n def partition(collection, fun) do\n {acc1, acc2} =\n reduce(collection, {[], []}, fn(entry, {acc1, acc2}) ->\n if fun.(entry) do\n {[entry|acc1], acc2}\n else\n {acc1, [entry|acc2]}\n end\n end)\n\n {:lists.reverse(acc1), :lists.reverse(acc2)}\n end\n\n @doc \"\"\"\n Splits `collection` into groups based on `fun`.\n\n The result is a dict (by default a map) where each key is\n a group and each value is a list of elements from `collection`\n for which `fun` returned that group. Ordering is not necessarily\n preserved.\n\n ## Examples\n\n iex> Enum.group_by(~w{ant buffalo cat dingo}, &String.length\/1)\n %{3 => [\"cat\", \"ant\"], 7 => [\"buffalo\"], 5 => [\"dingo\"]}\n\n \"\"\"\n @spec group_by(t, dict, (element -> any)) :: dict when dict: Dict.t\n def group_by(collection, dict \\\\ %{}, fun) do\n reduce(collection, dict, fn(entry, categories) ->\n Dict.update(categories, fun.(entry), [entry], &[entry|&1])\n end)\n end\n\n @doc \"\"\"\n Invokes `fun` for each element in the collection passing that element and the\n accumulator `acc` as arguments. `fun`'s return value is stored in `acc`.\n Returns the accumulator.\n\n ## Examples\n\n iex> Enum.reduce([1, 2, 3], 0, fn(x, acc) -> x + acc end)\n 6\n\n \"\"\"\n @spec reduce(t, any, (element, any -> any)) :: any\n def reduce(collection, acc, fun) when is_list(collection) do\n :lists.foldl(fun, acc, collection)\n end\n\n def reduce(collection, acc, fun) do\n Enumerable.reduce(collection, {:cont, acc},\n fn x, acc -> {:cont, fun.(x, acc)} end) |> elem(1)\n end\n\n @doc \"\"\"\n Invokes `fun` for each element in the collection passing that element and the\n accumulator `acc` as arguments. `fun`'s return value is stored in `acc`.\n The first element of the collection is used as the initial value of `acc`.\n Returns the accumulator.\n\n ## Examples\n\n iex> Enum.reduce([1, 2, 3, 4], fn(x, acc) -> x * acc end)\n 24\n\n \"\"\"\n @spec reduce(t, (element, any -> any)) :: any\n def reduce([h|t], fun) do\n reduce(t, h, fun)\n end\n\n def reduce([], _fun) do\n raise Enum.EmptyError\n end\n\n def reduce(collection, fun) do\n result =\n Enumerable.reduce(collection, {:cont, :first}, fn\n x, :first ->\n {:cont, {:acc, x}}\n x, {:acc, acc} ->\n {:cont, {:acc, fun.(x, acc)}}\n end) |> elem(1)\n\n case result do\n :first -> raise Enum.EmptyError\n {:acc, acc} -> acc\n end\n end\n\n @doc \"\"\"\n Returns elements of collection for which `fun` returns `false`.\n\n ## Examples\n\n iex> Enum.reject([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)\n [1, 3]\n\n \"\"\"\n @spec reject(t, (element -> as_boolean(term))) :: list\n def reject(collection, fun) when is_list(collection) do\n for item <- collection, !fun.(item), do: item\n end\n\n def reject(collection, fun) do\n Enumerable.reduce(collection, {:cont, []}, R.reject(fun)) |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Reverses the collection.\n\n ## Examples\n\n iex> Enum.reverse([1, 2, 3])\n [3, 2, 1]\n\n \"\"\"\n @spec reverse(t) :: list\n def reverse(collection) when is_list(collection) do\n :lists.reverse(collection)\n end\n\n def reverse(collection) do\n reverse(collection, [])\n end\n\n @doc \"\"\"\n Reverses the collection and appends the tail.\n This is an optimization for\n `Enum.concat(Enum.reverse(collection), tail)`.\n\n ## Examples\n\n iex> Enum.reverse([1, 2, 3], [4, 5, 6])\n [3, 2, 1, 4, 5, 6]\n\n \"\"\"\n @spec reverse(t, t) :: list\n def reverse(collection, tail) when is_list(collection) and is_list(tail) do\n :lists.reverse(collection, tail)\n end\n\n def reverse(collection, tail) do\n reduce(collection, to_list(tail), fn(entry, acc) ->\n [entry|acc]\n end)\n end\n\n @doc \"\"\"\n Applies the given function to each element in the collection,\n storing the result in a list and passing it as the accumulator\n for the next computation.\n\n ## Examples\n\n iex> Enum.scan(1..5, &(&1 + &2))\n [1,3,6,10,15]\n\n \"\"\"\n @spec scan(t, (element, any -> any)) :: list\n def scan(enum, fun) do\n {_, {res, _}} =\n Enumerable.reduce(enum, {:cont, {[], :first}}, R.scan_2(fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Applies the given function to each element in the collection,\n storing the result in a list and passing it as the accumulator\n for the next computation. Uses the given `acc` as the starting value.\n\n ## Examples\n\n iex> Enum.scan(1..5, 0, &(&1 + &2))\n [1,3,6,10,15]\n\n \"\"\"\n @spec scan(t, any, (element, any -> any)) :: list\n def scan(enum, acc, fun) do\n {_, {res, _}} =\n Enumerable.reduce(enum, {:cont, {[], acc}}, R.scan_3(fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Returns a list of collection elements shuffled.\n\n Notice that you need to explicitly call `:random.seed\/1` and\n set a seed value for the random algorithm. Otherwise, the\n default seed will be set which will always return the same\n result. For example, one could do the following to set a seed\n dynamically:\n\n :random.seed(:erlang.now)\n\n ## Examples\n\n iex> Enum.shuffle([1, 2, 3])\n [3, 2, 1]\n iex> Enum.shuffle([1, 2, 3])\n [3, 1, 2]\n\n \"\"\"\n @spec shuffle(t) :: list\n def shuffle(collection) do\n randomized = reduce(collection, [], fn x, acc ->\n [{:random.uniform, x}|acc]\n end)\n unwrap(:lists.keysort(1, randomized), [])\n end\n\n @doc \"\"\"\n Returns a subset list of the given collection. Drops elements\n until element position `start`, then takes `count` elements.\n \n If the count is greater than collection length, it returns as\n much as possible. If zero, then it returns `[]`.\n\n ## Examples\n\n iex> Enum.slice(1..100, 5, 10)\n [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n\n iex> Enum.slice(1..10, 5, 100)\n [6, 7, 8, 9, 10]\n\n iex> Enum.slice(1..10, 5, 0)\n []\n\n \"\"\"\n @spec slice(t, integer, non_neg_integer) :: list\n \n def slice(_coll, _start, 0), do: []\n\n def slice(coll, start, count) when start < 0 do\n {list, new_start} = enumerate_and_count(coll, start)\n if new_start >= 0 do\n slice(list, new_start, count)\n else\n []\n end\n end\n\n def slice(coll, start, count) when is_list(coll) and start >= 0 and count > 0 do\n do_slice(coll, start, count)\n end\n\n def slice(coll, start, count) when start >= 0 and count > 0 do\n {_, _, list} = Enumerable.reduce(coll, {:cont, {start, count, []}}, fn\n _entry, {start, count, _list} when start > 0 ->\n {:cont, {start-1, count, []}}\n entry, {start, count, list} when count > 1 ->\n {:cont, {start, count-1, [entry|list]}}\n entry, {start, count, list} ->\n {:halt, {start, count, [entry|list]}}\n end) |> elem(1)\n\n :lists.reverse(list)\n end\n\n @doc \"\"\"\n Returns a subset list of the given collection. Drops elements\n until element position `range.first`, then takes elements until element\n position `range.last` (inclusive).\n\n Positions are calculated by adding the number of items in the collection to\n negative positions (so position -3 in a collection with count 5 becomes\n position 2).\n\n The first position (after adding count to negative positions) must be smaller\n or equal to the last position.\n\n If the start of the range is not a valid offset for the given\n collection or if the range is in reverse order, returns `[]`.\n\n ## Examples\n\n iex> Enum.slice(1..100, 5..10)\n [6, 7, 8, 9, 10, 11]\n\n iex> Enum.slice(1..10, 5..20)\n [6, 7, 8, 9, 10]\n\n iex> Enum.slice(1..10, 11..20)\n []\n\n iex> Enum.slice(1..10, 6..5)\n []\n\n \"\"\"\n @spec slice(t, Range.t) :: list\n def slice(coll, first..last) when first >= 0 and last >= 0 do\n # Simple case, which works on infinite collections\n if last - first >= 0 do\n slice(coll, first, last - first + 1)\n else\n []\n end\n end\n\n def slice(coll, first..last) do\n {list, count} = enumerate_and_count(coll, 0)\n corr_first = if first >= 0, do: first, else: first + count\n corr_last = if last >= 0, do: last, else: last + count\n length = corr_last - corr_first + 1\n if corr_first >= 0 and length > 0 do\n slice(list, corr_first, length)\n else\n []\n end\n end\n\n @doc \"\"\"\n Sorts the collection according to Elixir's term ordering.\n\n Uses the merge sort algorithm.\n\n ## Examples\n\n iex> Enum.sort([3, 2, 1])\n [1, 2, 3]\n\n \"\"\"\n @spec sort(t) :: list\n def sort(collection) when is_list(collection) do\n :lists.sort(collection)\n end\n\n def sort(collection) do\n sort(collection, &(&1 <= &2))\n end\n\n @doc \"\"\"\n Sorts the collection by the given function.\n\n This function uses the merge sort algorithm. The given function\n must return false if the first argument is less than right one.\n\n ## Examples\n\n iex> Enum.sort([1, 2, 3], &(&1 > &2))\n [3, 2, 1]\n\n The sorting algorithm will be stable as long as the given function\n returns true for values considered equal:\n\n iex> Enum.sort [\"some\", \"kind\", \"of\", \"monster\"], &(byte_size(&1) <= byte_size(&2))\n [\"of\", \"some\", \"kind\", \"monster\"]\n\n If the function does not return true, the sorting is not stable and\n the order of equal terms may be shuffled:\n\n iex> Enum.sort [\"some\", \"kind\", \"of\", \"monster\"], &(byte_size(&1) < byte_size(&2))\n [\"of\", \"kind\", \"some\", \"monster\"]\n\n \"\"\"\n @spec sort(t, (element, element -> boolean)) :: list\n def sort(collection, fun) when is_list(collection) do\n :lists.sort(fun, collection)\n end\n\n def sort(collection, fun) do\n reduce(collection, [], &sort_reducer(&1, &2, fun)) |> sort_terminator(fun)\n end\n\n @doc \"\"\"\n Splits the enumerable into two collections, leaving `count`\n elements in the first one. If `count` is a negative number,\n it starts counting from the back to the beginning of the\n collection.\n\n Be aware that a negative `count` implies the collection\n will be enumerated twice: once to calculate the position, and\n a second time to do the actual splitting.\n\n ## Examples\n\n iex> Enum.split([1, 2, 3], 2)\n {[1,2], [3]}\n\n iex> Enum.split([1, 2, 3], 10)\n {[1,2,3], []}\n\n iex> Enum.split([1, 2, 3], 0)\n {[], [1,2,3]}\n\n iex> Enum.split([1, 2, 3], -1)\n {[1,2], [3]}\n\n iex> Enum.split([1, 2, 3], -5)\n {[], [1,2,3]}\n\n \"\"\"\n @spec split(t, integer) :: {list, list}\n def split(collection, count) when is_list(collection) and count >= 0 do\n do_split(collection, count, [])\n end\n\n def split(collection, count) when count >= 0 do\n {_, list1, list2} =\n reduce(collection, {count, [], []}, fn(entry, {counter, acc1, acc2}) ->\n if counter > 0 do\n {counter - 1, [entry|acc1], acc2}\n else\n {counter, acc1, [entry|acc2]}\n end\n end)\n\n {:lists.reverse(list1), :lists.reverse(list2)}\n end\n\n def split(collection, count) when count < 0 do\n do_split_reverse(reverse(collection), abs(count), [])\n end\n\n @doc \"\"\"\n Splits `collection` in two while `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.split_while([1, 2, 3, 4], fn(x) -> x < 3 end)\n {[1, 2], [3, 4]}\n\n \"\"\"\n @spec split_while(t, (element -> as_boolean(term))) :: {list, list}\n def split_while(collection, fun) when is_list(collection) do\n do_split_while(collection, fun, [])\n end\n\n def split_while(collection, fun) do\n {list1, list2} =\n reduce(collection, {[], []}, fn\n entry, {acc1, []} ->\n if(fun.(entry), do: {[entry|acc1], []}, else: {acc1, [entry]})\n entry, {acc1, acc2} ->\n {acc1, [entry|acc2]}\n end)\n\n {:lists.reverse(list1), :lists.reverse(list2)}\n end\n\n @doc \"\"\"\n Takes the first `count` items from the collection.\n\n If a negative `count` is given, the last `count` values will\n be taken. For such, the collection is fully enumerated keeping up\n to `2 * count` elements in memory. Once the end of the collection is\n reached, the last `count` elements are returned.\n\n ## Examples\n\n iex> Enum.take([1, 2, 3], 2)\n [1,2]\n\n iex> Enum.take([1, 2, 3], 10)\n [1,2,3]\n\n iex> Enum.take([1, 2, 3], 0)\n []\n\n iex> Enum.take([1, 2, 3], -1)\n [3]\n\n \"\"\"\n @spec take(t, integer) :: list\n\n def take(_collection, 0) do\n []\n end\n\n def take(collection, count) when is_list(collection) and count > 0 do\n do_take(collection, count)\n end\n\n def take(collection, count) when count > 0 do\n {_, {res, _}} =\n Enumerable.reduce(collection, {:cont, {[], count}}, fn(entry, {list, count}) ->\n if count > 1 do\n {:cont, {[entry|list], count - 1}}\n else\n {:halt, {[entry|list], count}}\n end\n end)\n :lists.reverse(res)\n end\n\n def take(collection, count) when count < 0 do\n Stream.take(collection, count).({:cont, []}, &{:cont, [&1|&2]})\n |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Returns a collection of every `nth` item in the collection,\n starting with the first element.\n\n ## Examples\n\n iex> Enum.take_every(1..10, 2)\n [1, 3, 5, 7, 9]\n\n \"\"\"\n @spec take_every(t, integer) :: list\n def take_every(_collection, 0), do: []\n def take_every(collection, nth) do\n {_, {res, _}} =\n Enumerable.reduce(collection, {:cont, {[], :first}}, R.take_every(nth))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Takes the items at the beginning of `collection` while `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.take_while([1, 2, 3], fn(x) -> x < 3 end)\n [1, 2]\n\n \"\"\"\n @spec take_while(t, (element -> as_boolean(term))) :: list\n def take_while(collection, fun) when is_list(collection) do\n do_take_while(collection, fun)\n end\n\n def take_while(collection, fun) do\n Enumerable.reduce(collection, {:cont, []}, R.take_while(fun))\n |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Convert `collection` to a list.\n\n ## Examples\n\n iex> Enum.to_list(1 .. 3)\n [1, 2, 3]\n\n \"\"\"\n @spec to_list(t) :: [term]\n def to_list(collection) when is_list(collection) do\n collection\n end\n\n def to_list(collection) do\n reverse(collection) |> :lists.reverse\n end\n\n\n @doc \"\"\"\n Traverses the given enumerable keeping its shape.\n\n It also expects the enumerable to implement the `Collectable` protocol.\n\n ## Examples\n\n iex> Enum.traverse(%{a: 1, b: 2}, fn {k, v} -> {k, v * 2} end)\n %{a: 2, b: 4}\n\n \"\"\"\n @spec traverse(Enumerable.t, (term -> term)) :: Collectable.t\n def traverse(collection, transform) when is_list(collection) do\n :lists.map(transform, collection)\n end\n\n def traverse(collection, transform) do\n into(collection, Collectable.empty(collection), transform)\n end\n\n @doc \"\"\"\n Enumerates the collection, removing all duplicated items.\n\n ## Examples\n\n iex> Enum.uniq([1, 2, 3, 2, 1])\n [1, 2, 3]\n\n iex> Enum.uniq([{1, :x}, {2, :y}, {1, :z}], fn {x, _} -> x end)\n [{1,:x}, {2,:y}]\n\n \"\"\"\n @spec uniq(t) :: list\n @spec uniq(t, (element -> term)) :: list\n def uniq(collection, fun \\\\ fn x -> x end)\n\n def uniq(collection, fun) when is_list(collection) do\n do_uniq(collection, [], fun)\n end\n\n def uniq(collection, fun) do\n {_, {list, _}} =\n Enumerable.reduce(collection, {:cont, {[], []}}, R.uniq(fun))\n :lists.reverse(list)\n end\n\n @doc \"\"\"\n Zips corresponding elements from two collections into one list\n of tuples.\n\n The zipping finishes as soon as any enumerable completes.\n\n ## Examples\n\n iex> Enum.zip([1, 2, 3], [:a, :b, :c])\n [{1,:a},{2,:b},{3,:c}]\n\n iex> Enum.zip([1,2,3,4,5], [:a, :b, :c])\n [{1,:a},{2,:b},{3,:c}]\n\n \"\"\"\n @spec zip(t, t) :: [{any, any}]\n def zip(coll1, coll2) when is_list(coll1) and is_list(coll2) do\n do_zip(coll1, coll2)\n end\n\n def zip(coll1, coll2) do\n Stream.zip(coll1, coll2).({:cont, []}, &{:cont, [&1|&2]}) |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Returns the collection with each element wrapped in a tuple\n alongside its index.\n\n ## Examples\n\n iex> Enum.with_index [1,2,3]\n [{1,0},{2,1},{3,2}]\n\n \"\"\"\n @spec with_index(t) :: list({element, non_neg_integer})\n def with_index(collection) do\n map_reduce(collection, 0, fn x, acc ->\n {{x, acc}, acc + 1}\n end) |> elem(0)\n end\n\n ## Helpers\n\n @compile {:inline, enum_to_string: 1}\n\n defp enumerate_and_count(collection, count) when is_list(collection) do\n {collection, length(collection) - abs(count)}\n end\n\n defp enumerate_and_count(collection, count) do\n map_reduce(collection, -abs(count), fn(x, acc) -> {x, acc + 1} end)\n end\n\n defp enum_to_string(entry) when is_binary(entry), do: entry\n defp enum_to_string(entry), do: String.Chars.to_string(entry)\n\n ## Implementations\n\n ## all?\n\n defp do_all?([h|t], fun) do\n if fun.(h) do\n do_all?(t, fun)\n else\n false\n end\n end\n\n defp do_all?([], _) do\n true\n end\n\n ## any?\n\n defp do_any?([h|t], fun) do\n if fun.(h) do\n true\n else\n do_any?(t, fun)\n end\n end\n\n defp do_any?([], _) do\n false\n end\n\n ## fetch\n\n defp do_fetch([h|_], 0), do: {:ok, h}\n defp do_fetch([_|t], n), do: do_fetch(t, n - 1)\n defp do_fetch([], _), do: :error\n\n ## drop\n\n defp do_drop([_|t], counter) when counter > 0 do\n do_drop(t, counter - 1)\n end\n\n defp do_drop(list, 0) do\n list\n end\n\n defp do_drop([], _) do\n []\n end\n\n ## drop_while\n\n defp do_drop_while([h|t], fun) do\n if fun.(h) do\n do_drop_while(t, fun)\n else\n [h|t]\n end\n end\n\n defp do_drop_while([], _) do\n []\n end\n\n ## find\n\n defp do_find([h|t], ifnone, fun) do\n if fun.(h) do\n h\n else\n do_find(t, ifnone, fun)\n end\n end\n\n defp do_find([], ifnone, _) do\n ifnone\n end\n\n ## find_index\n\n defp do_find_index([h|t], counter, fun) do\n if fun.(h) do\n counter\n else\n do_find_index(t, counter + 1, fun)\n end\n end\n\n defp do_find_index([], _, _) do\n nil\n end\n\n ## find_value\n\n defp do_find_value([h|t], ifnone, fun) do\n fun.(h) || do_find_value(t, ifnone, fun)\n end\n\n defp do_find_value([], ifnone, _) do\n ifnone\n end\n\n ## shuffle\n\n defp unwrap([{_, h} | collection], t) do\n unwrap(collection, [h|t])\n end\n\n defp unwrap([], t), do: t\n\n ## sort\n\n defp sort_reducer(entry, {:split, y, x, r, rs, bool}, fun) do\n cond do\n fun.(y, entry) == bool ->\n {:split, entry, y, [x|r], rs, bool}\n fun.(x, entry) == bool ->\n {:split, y, entry, [x|r], rs, bool}\n r == [] ->\n {:split, y, x, [entry], rs, bool}\n true ->\n {:pivot, y, x, r, rs, entry, bool}\n end\n end\n\n defp sort_reducer(entry, {:pivot, y, x, r, rs, s, bool}, fun) do\n cond do\n fun.(y, entry) == bool ->\n {:pivot, entry, y, [x | r], rs, s, bool}\n fun.(x, entry) == bool ->\n {:pivot, y, entry, [x | r], rs, s, bool}\n fun.(s, entry) == bool ->\n {:split, entry, s, [], [[y, x | r] | rs], bool}\n true ->\n {:split, s, entry, [], [[y, x | r] | rs], bool}\n end\n end\n\n defp sort_reducer(entry, [x], fun) do\n {:split, entry, x, [], [], fun.(x, entry)}\n end\n\n defp sort_reducer(entry, acc, _fun) do\n [entry|acc]\n end\n\n defp sort_terminator({:split, y, x, r, rs, bool}, fun) do\n sort_merge([[y, x | r] | rs], fun, bool)\n end\n\n defp sort_terminator({:pivot, y, x, r, rs, s, bool}, fun) do\n sort_merge([[s], [y, x | r] | rs], fun, bool)\n end\n\n defp sort_terminator(acc, _fun) do\n acc\n end\n\n defp sort_merge(list, fun, true), do:\n reverse_sort_merge(list, [], fun, true)\n\n defp sort_merge(list, fun, false), do:\n sort_merge(list, [], fun, false)\n\n\n defp sort_merge([t1, [h2 | t2] | l], acc, fun, true), do:\n sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, false) | acc], fun, true)\n\n defp sort_merge([[h2 | t2], t1 | l], acc, fun, false), do:\n sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, false) | acc], fun, false)\n\n defp sort_merge([l], [], _fun, _bool), do: l\n\n defp sort_merge([l], acc, fun, bool), do:\n reverse_sort_merge([:lists.reverse(l, []) | acc], [], fun, bool)\n\n defp sort_merge([], acc, fun, bool), do:\n reverse_sort_merge(acc, [], fun, bool)\n\n\n defp reverse_sort_merge([[h2 | t2], t1 | l], acc, fun, true), do:\n reverse_sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, true) | acc], fun, true)\n\n defp reverse_sort_merge([t1, [h2 | t2] | l], acc, fun, false), do:\n reverse_sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, true) | acc], fun, false)\n\n defp reverse_sort_merge([l], acc, fun, bool), do:\n sort_merge([:lists.reverse(l, []) | acc], [], fun, bool)\n\n defp reverse_sort_merge([], acc, fun, bool), do:\n sort_merge(acc, [], fun, bool)\n\n\n defp sort_merge_1([h1 | t1], h2, t2, m, fun, bool) do\n if fun.(h1, h2) == bool do\n sort_merge_2(h1, t1, t2, [h2 | m], fun, bool)\n else\n sort_merge_1(t1, h2, t2, [h1 | m], fun, bool)\n end\n end\n\n defp sort_merge_1([], h2, t2, m, _fun, _bool), do:\n :lists.reverse(t2, [h2 | m])\n\n\n defp sort_merge_2(h1, t1, [h2 | t2], m, fun, bool) do\n if fun.(h1, h2) == bool do\n sort_merge_2(h1, t1, t2, [h2 | m], fun, bool)\n else\n sort_merge_1(t1, h2, t2, [h1 | m], fun, bool)\n end\n end\n\n defp sort_merge_2(h1, t1, [], m, _fun, _bool), do:\n :lists.reverse(t1, [h1 | m])\n\n ## split\n\n defp do_split([h|t], counter, acc) when counter > 0 do\n do_split(t, counter - 1, [h|acc])\n end\n\n defp do_split(list, 0, acc) do\n {:lists.reverse(acc), list}\n end\n\n defp do_split([], _, acc) do\n {:lists.reverse(acc), []}\n end\n\n defp do_split_reverse([h|t], counter, acc) when counter > 0 do\n do_split_reverse(t, counter - 1, [h|acc])\n end\n\n defp do_split_reverse(list, 0, acc) do\n {:lists.reverse(list), acc}\n end\n\n defp do_split_reverse([], _, acc) do\n {[], acc}\n end\n\n ## split_while\n\n defp do_split_while([h|t], fun, acc) do\n if fun.(h) do\n do_split_while(t, fun, [h|acc])\n else\n {:lists.reverse(acc), [h|t]}\n end\n end\n\n defp do_split_while([], _, acc) do\n {:lists.reverse(acc), []}\n end\n\n ## take\n\n defp do_take([h|t], counter) when counter > 0 do\n [h|do_take(t, counter - 1)]\n end\n\n defp do_take(_list, 0) do\n []\n end\n\n defp do_take([], _) do\n []\n end\n\n ## take_while\n\n defp do_take_while([h|t], fun) do\n if fun.(h) do\n [h|do_take_while(t, fun)]\n else\n []\n end\n end\n\n defp do_take_while([], _) do\n []\n end\n\n ## uniq\n\n defp do_uniq([h|t], acc, fun) do\n fun_h = fun.(h)\n case :lists.member(fun_h, acc) do\n true -> do_uniq(t, acc, fun)\n false -> [h|do_uniq(t, [fun_h|acc], fun)]\n end\n end\n\n defp do_uniq([], _acc, _fun) do\n []\n end\n\n ## zip\n\n defp do_zip([h1|next1], [h2|next2]) do\n [{h1, h2}|do_zip(next1, next2)]\n end\n\n defp do_zip(_, []), do: []\n defp do_zip([], _), do: []\n\n ## slice\n\n defp do_slice([], _start, _count) do\n []\n end\n\n defp do_slice(_list, _start, 0) do\n []\n end\n\n defp do_slice([h|t], 0, count) do\n [h|do_slice(t, 0, count-1)]\n end\n\n defp do_slice([_|t], start, count) do\n do_slice(t, start-1, count)\n end\nend\n\ndefimpl Enumerable, for: List do\n def reduce(_, {:halt, acc}, _fun), do: {:halted, acc}\n def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)}\n def reduce([], {:cont, acc}, _fun), do: {:done, acc}\n def reduce([h|t], {:cont, acc}, fun), do: reduce(t, fun.(h, acc), fun)\n\n def member?(_list, _value),\n do: {:error, __MODULE__}\n def count(_list),\n do: {:error, __MODULE__}\nend\n\ndefimpl Enumerable, for: Map do\n def reduce(map, acc, fun) do\n do_reduce(:maps.to_list(map), acc, fun)\n end\n\n defp do_reduce(_, {:halt, acc}, _fun), do: {:halted, acc}\n defp do_reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &do_reduce(list, &1, fun)}\n defp do_reduce([], {:cont, acc}, _fun), do: {:done, acc}\n defp do_reduce([h|t], {:cont, acc}, fun), do: do_reduce(t, fun.(h, acc), fun)\n\n def member?(map, {key, value}) do\n {:ok, match?({:ok, ^value}, :maps.find(key, map))}\n end\n\n def member?(_map, _other) do\n {:ok, false}\n end\n\n def count(map) do\n {:ok, map_size(map)}\n end\nend\n\ndefimpl Enumerable, for: Function do\n def reduce(function, acc, fun) when is_function(function, 2),\n do: function.(acc, fun)\n def member?(_function, _value),\n do: {:error, __MODULE__}\n def count(_function),\n do: {:error, __MODULE__}\nend\n","old_contents":"defprotocol Enumerable do\n @moduledoc \"\"\"\n Enumerable protocol used by `Enum` and `Stream` modules.\n\n When you invoke a function in the `Enum` module, the first argument\n is usually a collection that must implement this protocol. For example,\n the expression\n\n Enum.map([1, 2, 3], &(&1 * 2))\n\n invokes underneath `Enumerable.reduce\/3` to perform the reducing\n operation that builds a mapped list by calling the mapping function\n `&(&1 * 2)` on every element in the collection and cons'ing the\n element with an accumulated list.\n\n Internally, `Enum.map\/2` is implemented as follows:\n\n def map(enum, fun) do\n reducer = fn x, acc -> {:cont, [fun.(x)|acc]} end\n Enumerable.reduce(enum, {:cont, []}, reducer) |> elem(1) |> :lists.reverse()\n end\n\n Notice the user given function is wrapped into a `reducer` function.\n The `reducer` function must return a tagged tuple after each step,\n as described in the `acc\/0` type.\n\n The reason the accumulator requires a tagged tuple is to allow the\n reducer function to communicate to the underlying enumerable the end\n of enumeration, allowing any open resource to be properly closed. It\n also allows suspension of the enumeration, which is useful when\n interleaving between many enumerables is required (as in zip).\n\n Finally, `Enumerable.reduce\/3` will return another tagged tuple,\n as represented by the `result\/0` type.\n \"\"\"\n\n @typedoc \"\"\"\n The accumulator value for each step.\n\n It must be a tagged tuple with one of the following \"tags\":\n\n * `:cont` - the enumeration should continue\n * `:halt` - the enumeration should halt immediately\n * `:suspend` - the enumeration should be suspended immediately\n\n Depending on the accumulator value, the result returned by\n `Enumerable.reduce\/3` will change. Please check the `result`\n type docs for more information.\n\n In case a reducer function returns a `:suspend` accumulator,\n it must be explicitly handled by the caller and never leak.\n \"\"\"\n @type acc :: {:cont, term} | {:halt, term} | {:suspend, term}\n\n @typedoc \"\"\"\n The reducer function.\n\n Should be called with the collection element and the\n accumulator contents. Returns the accumulator for\n the next enumeration step.\n \"\"\"\n @type reducer :: (term, term -> acc)\n\n @typedoc \"\"\"\n The result of the reduce operation.\n\n It may be *done* when the enumeration is finished by reaching\n its end, or *halted*\/*suspended* when the enumeration was halted\n or suspended by the reducer function.\n\n In case a reducer function returns the `:suspend` accumulator, the\n `:suspended` tuple must be explicitly handled by the caller and\n never leak. In practice, this means regular enumeration functions\n just need to be concerned about `:done` and `:halted` results.\n\n Furthermore, a `:suspend` call must always be followed by another call,\n eventually halting or continuing until the end.\n \"\"\"\n @type result :: {:done, term} | {:halted, term} | {:suspended, term, continuation}\n\n @typedoc \"\"\"\n A partially applied reduce function.\n\n The continuation is the closure returned as a result when\n the enumeration is suspended. When invoked, it expects\n a new accumulator and it returns the result.\n\n A continuation is easily implemented as long as the reduce\n function is defined in a tail recursive fashion. If the function\n is tail recursive, all the state is passed as arguments, so\n the continuation would simply be the reducing function partially\n applied.\n \"\"\"\n @type continuation :: (acc -> result)\n\n @doc \"\"\"\n Reduces the collection into a value.\n\n Most of the operations in `Enum` are implemented in terms of reduce.\n This function should apply the given `reducer` function to each\n item in the collection and proceed as expected by the returned accumulator.\n\n As an example, here is the implementation of `reduce` for lists:\n\n def reduce(_, {:halt, acc}, _fun), do: {:halted, acc}\n def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)}\n def reduce([], {:cont, acc}, _fun), do: {:done, acc}\n def reduce([h|t], {:cont, acc}, fun), do: reduce(t, fun.(h, acc), fun)\n\n \"\"\"\n @spec reduce(t, acc, reducer) :: result\n def reduce(collection, acc, fun)\n\n @doc \"\"\"\n Checks if a value exists within the collection.\n\n It should return `{:ok, boolean}`.\n\n If `{:error, __MODULE__}` is returned a default algorithm using `reduce` and\n the match (`===`) operator is used. This algorithm runs in linear time.\n\n Please force use of the default algorithm unless you can implement an\n algorithm that is significantly faster.\n \"\"\"\n @spec member?(t, term) :: {:ok, boolean} | {:error, module}\n def member?(collection, value)\n\n @doc \"\"\"\n Retrieves the collection's size.\n\n It should return `{:ok, size}`.\n\n If `{:error, __MODULE__}` is returned a default algorithm using `reduce` and\n the match (`===`) operator is used. This algorithm runs in linear time.\n\n Please force use of the default algorithm unless you can implement an\n algorithm that is significantly faster.\n \"\"\"\n @spec count(t) :: {:ok, non_neg_integer} | {:error, module}\n def count(collection)\nend\n\ndefmodule Enum do\n import Kernel, except: [max: 2, min: 2]\n\n @moduledoc \"\"\"\n Provides a set of algorithms that enumerate over collections according to the\n `Enumerable` protocol:\n\n iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end)\n [2,4,6]\n\n Some particular types, like dictionaries, yield a specific format on\n enumeration. For dicts, the argument is always a `{key, value}` tuple:\n\n iex> dict = %{a: 1, b: 2}\n iex> Enum.map(dict, fn {k, v} -> {k, v * 2} end)\n [a: 2, b: 4]\n\n Note that the functions in the `Enum` module are eager: they always start\n the enumeration of the given collection. The `Stream` module allows\n lazy enumeration of collections and provides infinite streams.\n\n Since the majority of the functions in `Enum` enumerate the whole\n collection and return a list as result, infinite streams need to\n be carefully used with such functions, as they can potentially run\n forever. For example:\n\n Enum.each Stream.cycle([1,2,3]), &IO.puts(&1)\n\n \"\"\"\n\n @compile :inline_list_funcs\n\n @type t :: Enumerable.t\n @type element :: any\n @type index :: non_neg_integer\n @type default :: any\n\n # Require Stream.Reducers and its callbacks\n require Stream.Reducers, as: R\n\n defmacrop cont(_, entry, acc) do\n quote do: {:cont, [unquote(entry)|unquote(acc)]}\n end\n\n defmacrop acc(h, n, _) do\n quote do: {unquote(h), unquote(n)}\n end\n\n defmacrop cont_with_acc(f, entry, h, n, _) do\n quote do\n {:cont, {[unquote(entry)|unquote(h)], unquote(n)}}\n end\n end\n\n @doc \"\"\"\n Invokes the given `fun` for each item in the `collection` and returns `false`\n if at least one invocation returns `false`. Otherwise returns `true`.\n\n ## Examples\n\n iex> Enum.all?([2, 4, 6], fn(x) -> rem(x, 2) == 0 end)\n true\n\n iex> Enum.all?([2, 3, 4], fn(x) -> rem(x, 2) == 0 end)\n false\n\n If no function is given, it defaults to checking if\n all items in the collection evaluate to `true`.\n\n iex> Enum.all?([1, 2, 3])\n true\n\n iex> Enum.all?([1, nil, 3])\n false\n\n \"\"\"\n @spec all?(t) :: boolean\n @spec all?(t, (element -> as_boolean(term))) :: boolean\n\n def all?(collection, fun \\\\ fn(x) -> x end)\n\n def all?(collection, fun) when is_list(collection) do\n do_all?(collection, fun)\n end\n\n def all?(collection, fun) do\n Enumerable.reduce(collection, {:cont, true}, fn(entry, _) ->\n if fun.(entry), do: {:cont, true}, else: {:halt, false}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Invokes the given `fun` for each item in the `collection` and returns `true` if\n at least one invocation returns `true`. Returns `false` otherwise.\n\n ## Examples\n\n iex> Enum.any?([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n false\n\n iex> Enum.any?([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n true\n\n If no function is given, it defaults to checking if\n at least one item in the collection evaluates to `true`.\n\n iex> Enum.any?([false, false, false])\n false\n\n iex> Enum.any?([false, true, false])\n true\n\n \"\"\"\n @spec any?(t) :: boolean\n @spec any?(t, (element -> as_boolean(term))) :: boolean\n\n def any?(collection, fun \\\\ fn(x) -> x end)\n\n def any?(collection, fun) when is_list(collection) do\n do_any?(collection, fun)\n end\n\n def any?(collection, fun) do\n Enumerable.reduce(collection, {:cont, false}, fn(entry, _) ->\n if fun.(entry), do: {:halt, true}, else: {:cont, false}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Finds the element at the given index (zero-based).\n Returns `default` if index is out of bounds.\n\n ## Examples\n\n iex> Enum.at([2, 4, 6], 0)\n 2\n\n iex> Enum.at([2, 4, 6], 2)\n 6\n\n iex> Enum.at([2, 4, 6], 4)\n nil\n\n iex> Enum.at([2, 4, 6], 4, :none)\n :none\n\n \"\"\"\n @spec at(t, integer) :: element | nil\n @spec at(t, integer, default) :: element | default\n def at(collection, n, default \\\\ nil) do\n case fetch(collection, n) do\n {:ok, h} -> h\n :error -> default\n end\n end\n\n @doc \"\"\"\n Shortcut to `chunk(coll, n, n)`.\n \"\"\"\n @spec chunk(t, non_neg_integer) :: [list]\n def chunk(coll, n), do: chunk(coll, n, n, nil)\n\n @doc \"\"\"\n Returns a collection of lists containing `n` items each, where\n each new chunk starts `step` elements into the collection.\n\n `step` is optional and, if not passed, defaults to `n`, i.e.\n chunks do not overlap. If the final chunk does not have `n`\n elements to fill the chunk, elements are taken as necessary\n from `pad` if it was passed. If `pad` is passed and does not\n have enough elements to fill the chunk, then the chunk is\n returned anyway with less than `n` elements. If `pad` is not\n passed at all or is `nil`, then the partial chunk is discarded\n from the result.\n\n ## Examples\n\n iex> Enum.chunk([1, 2, 3, 4, 5, 6], 2)\n [[1, 2], [3, 4], [5, 6]]\n\n iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 2)\n [[1, 2, 3], [3, 4, 5]]\n\n iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 2, [7])\n [[1, 2, 3], [3, 4, 5], [5, 6, 7]]\n\n iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 3, [])\n [[1, 2, 3], [4, 5, 6]]\n\n \"\"\"\n @spec chunk(t, non_neg_integer, non_neg_integer) :: [list]\n @spec chunk(t, non_neg_integer, non_neg_integer, t | nil) :: [list]\n def chunk(coll, n, step, pad \\\\ nil) when n > 0 and step > 0 do\n limit = :erlang.max(n, step)\n\n {_, {acc, {buffer, i}}} =\n Enumerable.reduce(coll, {:cont, {[], {[], 0}}}, R.chunk(n, step, limit))\n\n if nil?(pad) || i == 0 do\n :lists.reverse(acc)\n else\n buffer = :lists.reverse(buffer) ++ take(pad, n - i)\n :lists.reverse([buffer|acc])\n end\n end\n\n @doc \"\"\"\n Splits `coll` on every element for which `fun` returns a new value.\n\n ## Examples\n\n iex> Enum.chunk_by([1, 2, 2, 3, 4, 4, 6, 7, 7], &(rem(&1, 2) == 1))\n [[1], [2, 2], [3], [4, 4, 6], [7, 7]]\n\n \"\"\"\n @spec chunk_by(t, (element -> any)) :: [list]\n def chunk_by(coll, fun) do\n {_, {acc, res}} =\n Enumerable.reduce(coll, {:cont, {[], nil}}, R.chunk_by(fun))\n\n case res do\n {buffer, _} ->\n :lists.reverse([:lists.reverse(buffer) | acc])\n nil ->\n []\n end\n end\n\n @doc \"\"\"\n Given an enumerable of enumerables, concatenate the enumerables into a single list.\n\n ## Examples\n\n iex> Enum.concat([1..3, 4..6, 7..9])\n [1,2,3,4,5,6,7,8,9]\n\n iex> Enum.concat([[1, [2], 3], [4], [5, 6]])\n [1,[2],3,4,5,6]\n\n \"\"\"\n @spec concat(t) :: t\n def concat(enumerables) do\n do_concat(enumerables)\n end\n\n @doc \"\"\"\n Concatenates the enumerable on the right with the enumerable on the left.\n\n This function produces the same result as the `Kernel.++\/2` operator for lists.\n\n ## Examples\n\n iex> Enum.concat(1..3, 4..6)\n [1,2,3,4,5,6]\n\n iex> Enum.concat([1, 2, 3], [4, 5, 6])\n [1,2,3,4,5,6]\n\n \"\"\"\n @spec concat(t, t) :: t\n def concat(left, right) when is_list(left) and is_list(right) do\n left ++ right\n end\n\n def concat(left, right) do\n do_concat([left, right])\n end\n\n defp do_concat(enumerable) do\n fun = &[&1|&2]\n reduce(enumerable, [], &reduce(&1, &2, fun)) |> :lists.reverse\n end\n\n @doc \"\"\"\n Returns the collection's size.\n\n ## Examples\n\n iex> Enum.count([1, 2, 3])\n 3\n\n \"\"\"\n @spec count(t) :: non_neg_integer\n def count(collection) when is_list(collection) do\n :erlang.length(collection)\n end\n\n def count(collection) do\n case Enumerable.count(collection) do\n {:ok, value} when is_integer(value) ->\n value\n {:error, module} ->\n module.reduce(collection, {:cont, 0}, fn\n _, acc -> {:cont, acc + 1}\n end) |> elem(1)\n end\n end\n\n @doc \"\"\"\n Returns the count of items in the collection for which\n `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.count([1, 2, 3, 4, 5], fn(x) -> rem(x, 2) == 0 end)\n 2\n\n \"\"\"\n @spec count(t, (element -> as_boolean(term))) :: non_neg_integer\n def count(collection, fun) do\n Enumerable.reduce(collection, {:cont, 0}, fn(entry, acc) ->\n {:cont, if(fun.(entry), do: acc + 1, else: acc)}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Drops the first `count` items from `collection`.\n\n If a negative value `count` is given, the last `count`\n values will be dropped. The collection is enumerated\n once to retrieve the proper index and the remaining\n calculation is performed from the end.\n\n ## Examples\n\n iex> Enum.drop([1, 2, 3], 2)\n [3]\n\n iex> Enum.drop([1, 2, 3], 10)\n []\n\n iex> Enum.drop([1, 2, 3], 0)\n [1,2,3]\n\n iex> Enum.drop([1, 2, 3], -1)\n [1,2]\n\n \"\"\"\n @spec drop(t, integer) :: list\n def drop(collection, count) when is_list(collection) and count >= 0 do\n do_drop(collection, count)\n end\n\n def drop(collection, count) when count >= 0 do\n res =\n reduce(collection, count, fn\n x, acc when is_list(acc) -> [x|acc]\n x, 0 -> [x]\n _, acc when acc > 0 -> acc - 1\n end)\n if is_list(res), do: :lists.reverse(res), else: []\n end\n\n def drop(collection, count) when count < 0 do\n do_drop(reverse(collection), abs(count)) |> :lists.reverse\n end\n\n @doc \"\"\"\n Drops items at the beginning of `collection` while `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.drop_while([1, 2, 3, 4, 5], fn(x) -> x < 3 end)\n [3,4,5]\n\n \"\"\"\n @spec drop_while(t, (element -> as_boolean(term))) :: list\n def drop_while(collection, fun) when is_list(collection) do\n do_drop_while(collection, fun)\n end\n\n def drop_while(collection, fun) do\n {_, {res, _}} =\n Enumerable.reduce(collection, {:cont, {[], true}}, R.drop_while(fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Invokes the given `fun` for each item in the `collection`.\n Returns `:ok`.\n\n ## Examples\n\n Enum.each([\"some\", \"example\"], fn(x) -> IO.puts x end)\n \"some\"\n \"example\"\n #=> :ok\n\n \"\"\"\n @spec each(t, (element -> any)) :: :ok\n def each(collection, fun) when is_list(collection) do\n :lists.foreach(fun, collection)\n :ok\n end\n\n def each(collection, fun) do\n reduce(collection, nil, fn(entry, _) ->\n fun.(entry)\n nil\n end)\n :ok\n end\n\n @doc \"\"\"\n Returns `true` if the collection is empty, otherwise `false`.\n\n ## Examples\n\n iex> Enum.empty?([])\n true\n\n iex> Enum.empty?([1, 2, 3])\n false\n\n \"\"\"\n @spec empty?(t) :: boolean\n def empty?(collection) when is_list(collection) do\n collection == []\n end\n\n def empty?(collection) do\n Enumerable.reduce(collection, {:cont, true}, fn(_, _) -> {:halt, false} end) |> elem(1)\n end\n\n @doc \"\"\"\n Finds the element at the given index (zero-based).\n Returns `{:ok, element}` if found, otherwise `:error`.\n\n A negative index can be passed, which means the collection is\n enumerated once and the index is counted from the end (i.e.\n `-1` fetches the last element).\n\n ## Examples\n\n iex> Enum.fetch([2, 4, 6], 0)\n {:ok, 2}\n\n iex> Enum.fetch([2, 4, 6], 2)\n {:ok, 6}\n\n iex> Enum.fetch([2, 4, 6], 4)\n :error\n\n \"\"\"\n @spec fetch(t, integer) :: {:ok, element} | :error\n def fetch(collection, n) when is_list(collection) and n >= 0 do\n do_fetch(collection, n)\n end\n\n def fetch(collection, n) when n >= 0 do\n res =\n Enumerable.reduce(collection, {:cont, 0}, fn(entry, acc) ->\n if acc == n do\n {:halt, entry}\n else\n {:cont, acc + 1}\n end\n end)\n\n case res do\n {:halted, entry} -> {:ok, entry}\n {:done, _} -> :error\n end\n end\n\n def fetch(collection, n) when n < 0 do\n do_fetch(reverse(collection), abs(n + 1))\n end\n\n @doc \"\"\"\n Finds the element at the given index (zero-based).\n Raises `OutOfBoundsError` if the given position\n is outside the range of the collection.\n\n ## Examples\n\n iex> Enum.fetch!([2, 4, 6], 0)\n 2\n\n iex> Enum.fetch!([2, 4, 6], 2)\n 6\n\n iex> Enum.fetch!([2, 4, 6], 4)\n ** (Enum.OutOfBoundsError) out of bounds error\n\n \"\"\"\n @spec fetch!(t, integer) :: element | no_return\n def fetch!(collection, n) do\n case fetch(collection, n) do\n {:ok, h} -> h\n :error -> raise Enum.OutOfBoundsError\n end\n end\n\n @doc \"\"\"\n Filters the collection, i.e. returns only those elements\n for which `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.filter([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)\n [2]\n\n \"\"\"\n @spec filter(t, (element -> as_boolean(term))) :: list\n def filter(collection, fun) when is_list(collection) do\n for item <- collection, fun.(item), do: item\n end\n\n def filter(collection, fun) do\n Enumerable.reduce(collection, {:cont, []}, R.filter(fun))\n |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Filters the collection and maps its values in one pass.\n\n ## Examples\n\n iex> Enum.filter_map([1, 2, 3], fn(x) -> rem(x, 2) == 0 end, &(&1 * 2))\n [4]\n\n \"\"\"\n @spec filter_map(t, (element -> as_boolean(term)), (element -> element)) :: list\n def filter_map(collection, filter, mapper) when is_list(collection) do\n for item <- collection, filter.(item), do: mapper.(item)\n end\n\n def filter_map(collection, filter, mapper) do\n Enumerable.reduce(collection, {:cont, []}, R.filter_map(filter, mapper))\n |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Returns the first item for which `fun` returns a truthy value. If no such\n item is found, returns `ifnone`.\n\n ## Examples\n\n iex> Enum.find([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n nil\n\n iex> Enum.find([2, 4, 6], 0, fn(x) -> rem(x, 2) == 1 end)\n 0\n\n iex> Enum.find([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n 3\n\n \"\"\"\n @spec find(t, (element -> any)) :: element | nil\n @spec find(t, default, (element -> any)) :: element | default\n def find(collection, ifnone \\\\ nil, fun)\n\n def find(collection, ifnone, fun) when is_list(collection) do\n do_find(collection, ifnone, fun)\n end\n\n def find(collection, ifnone, fun) do\n Enumerable.reduce(collection, {:cont, ifnone}, fn(entry, ifnone) ->\n if fun.(entry), do: {:halt, entry}, else: {:cont, ifnone}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Similar to `find\/3`, but returns the value of the function\n invocation instead of the element itself.\n\n ## Examples\n\n iex> Enum.find_value([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n nil\n\n iex> Enum.find_value([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n true\n\n \"\"\"\n @spec find_value(t, (element -> any)) :: any | :nil\n @spec find_value(t, any, (element -> any)) :: any | :nil\n def find_value(collection, ifnone \\\\ nil, fun)\n\n def find_value(collection, ifnone, fun) when is_list(collection) do\n do_find_value(collection, ifnone, fun)\n end\n\n def find_value(collection, ifnone, fun) do\n Enumerable.reduce(collection, {:cont, ifnone}, fn(entry, ifnone) ->\n fun_entry = fun.(entry)\n if fun_entry, do: {:halt, fun_entry}, else: {:cont, ifnone}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Similar to `find\/3`, but returns the index (zero-based)\n of the element instead of the element itself.\n\n ## Examples\n\n iex> Enum.find_index([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n nil\n\n iex> Enum.find_index([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n 1\n\n \"\"\"\n @spec find_index(t, (element -> any)) :: index | :nil\n def find_index(collection, fun) when is_list(collection) do\n do_find_index(collection, 0, fun)\n end\n\n def find_index(collection, fun) do\n res =\n Enumerable.reduce(collection, {:cont, 0}, fn(entry, acc) ->\n if fun.(entry), do: {:halt, acc}, else: {:cont, acc + 1}\n end)\n\n case res do\n {:halted, entry} -> entry\n {:done, _} -> nil\n end\n end\n\n @doc \"\"\"\n Returns a new collection appending the result of invoking `fun`\n on each corresponding item of `collection`.\n\n The given function should return an enumerable.\n\n ## Examples\n\n iex> Enum.flat_map([:a, :b, :c], fn(x) -> [x, x] end)\n [:a, :a, :b, :b, :c, :c]\n\n iex> Enum.flat_map([{1,3}, {4,6}], fn({x,y}) -> x..y end)\n [1, 2, 3, 4, 5, 6]\n\n \"\"\"\n @spec flat_map(t, (element -> t)) :: list\n def flat_map(collection, fun) do\n reduce(collection, [], fn(entry, acc) ->\n reduce(fun.(entry), acc, &[&1|&2])\n end) |> :lists.reverse\n end\n\n @doc \"\"\"\n Maps and reduces a collection, flattening the given results.\n\n It expects an accumulator and a function that receives each stream item\n and an accumulator, and must return a tuple containing a new stream\n (often a list) with the new accumulator or a tuple with `:halt` as first\n element and the accumulator as second.\n\n ## Examples\n\n iex> enum = 1..100\n iex> n = 3\n iex> Enum.flat_map_reduce(enum, 0, fn i, acc ->\n ...> if acc < n, do: {[i], acc + 1}, else: {:halt, acc}\n ...> end)\n {[1,2,3], 3}\n\n \"\"\"\n @spec flat_map_reduce(t, acc, fun) :: {[any], any} when\n fun: (element, acc -> {t, acc} | {:halt, acc}),\n acc: any\n def flat_map_reduce(collection, acc, fun) do\n {_, {list, acc}} =\n Enumerable.reduce(collection, {:cont, {[], acc}}, fn(entry, {list, acc}) ->\n case fun.(entry, acc) do\n {:halt, acc} ->\n {:halt, {list, acc}}\n {entries, acc} ->\n {:cont, {reduce(entries, list, &[&1|&2]), acc}}\n end\n end)\n\n {:lists.reverse(list), acc}\n end\n\n @doc \"\"\"\n Intersperses `element` between each element of the enumeration.\n\n Complexity: O(n)\n\n ## Examples\n\n iex> Enum.intersperse([1, 2, 3], 0)\n [1, 0, 2, 0, 3]\n\n iex> Enum.intersperse([1], 0)\n [1]\n\n iex> Enum.intersperse([], 0)\n []\n\n \"\"\"\n @spec intersperse(t, element) :: list\n def intersperse(collection, element) do\n list =\n reduce(collection, [], fn(x, acc) ->\n [x, element | acc]\n end) |> :lists.reverse()\n\n case list do\n [] -> []\n [_|t] -> t # Head is a superfluous intersperser element\n end\n end\n\n @doc \"\"\"\n Inserts the given enumerable into a collectable.\n\n ## Examples\n\n iex> Enum.into([1, 2], [0])\n [0, 1, 2]\n\n iex> Enum.into([a: 1, b: 2], %{})\n %{a: 1, b: 2}\n\n \"\"\"\n @spec into(Enumerable.t, Collectable.t) :: Collectable.t\n def into(collection, list) when is_list(list) do\n list ++ to_list(collection)\n end\n\n def into(collection, %{} = map) when is_list(collection) and map_size(map) == 0 do\n :maps.from_list(collection)\n end\n\n def into(collection, collectable) do\n {initial, fun} = Collectable.into(collectable)\n into(collection, initial, fun, fn x, acc ->\n fun.(acc, {:cont, x})\n end)\n end\n\n @doc \"\"\"\n Inserts the given enumerable into a collectable\n according to the transformation function.\n\n ## Examples\n\n iex> Enum.into([2, 3], [3], fn x -> x * 3 end)\n [3, 6, 9]\n\n \"\"\"\n @spec into(Enumerable.t, Collectable.t, (term -> term)) :: Collectable.t\n\n def into(collection, list, transform) when is_list(list) and is_function(transform, 1) do\n list ++ map(collection, transform)\n end\n\n def into(collection, collectable, transform) when is_function(transform, 1) do\n {initial, fun} = Collectable.into(collectable)\n into(collection, initial, fun, fn x, acc ->\n fun.(acc, {:cont, transform.(x)})\n end)\n end\n\n defp into(collection, initial, fun, callback) do\n try do\n reduce(collection, initial, callback)\n catch\n kind, reason ->\n stacktrace = System.stacktrace\n fun.(initial, :halt)\n :erlang.raise(kind, reason, stacktrace)\n else\n acc -> fun.(acc, :done)\n end\n end\n\n @doc \"\"\"\n Joins the given `collection` according to `joiner`.\n `joiner` can be either a binary or a list and the\n result will be of the same type as `joiner`. If\n `joiner` is not passed at all, it defaults to an\n empty binary.\n\n All items in the collection must be convertible\n to a binary, otherwise an error is raised.\n\n ## Examples\n\n iex> Enum.join([1, 2, 3])\n \"123\"\n\n iex> Enum.join([1, 2, 3], \" = \")\n \"1 = 2 = 3\"\n\n \"\"\"\n @spec join(t) :: String.t\n @spec join(t, String.t) :: String.t\n def join(collection, joiner \\\\ \"\")\n\n def join(collection, joiner) when is_binary(joiner) do\n reduced = reduce(collection, :first, fn\n entry, :first -> to_string(entry)\n entry, acc -> acc <> joiner <> to_string(entry)\n end)\n if reduced == :first do\n \"\"\n else\n reduced\n end\n end\n\n @doc \"\"\"\n Returns a new collection, where each item is the result\n of invoking `fun` on each corresponding item of `collection`.\n\n For dicts, the function expects a key-value tuple.\n\n ## Examples\n\n iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end)\n [2, 4, 6]\n\n iex> Enum.map([a: 1, b: 2], fn({k, v}) -> {k, -v} end)\n [a: -1, b: -2]\n\n \"\"\"\n @spec map(t, (element -> any)) :: list\n def map(collection, fun) when is_list(collection) do\n for item <- collection, do: fun.(item)\n end\n\n def map(collection, fun) do\n Enumerable.reduce(collection, {:cont, []}, R.map(fun)) |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Maps and joins the given `collection` in one pass.\n `joiner` can be either a binary or a list and the\n result will be of the same type as `joiner`. If\n `joiner` is not passed at all, it defaults to an\n empty binary.\n\n All items in the collection must be convertible\n to a binary, otherwise an error is raised.\n\n ## Examples\n\n iex> Enum.map_join([1, 2, 3], &(&1 * 2))\n \"246\"\n\n iex> Enum.map_join([1, 2, 3], \" = \", &(&1 * 2))\n \"2 = 4 = 6\"\n\n \"\"\"\n @spec map_join(t, (element -> any)) :: String.t\n @spec map_join(t, String.t, (element -> any)) :: String.t\n def map_join(collection, joiner \\\\ \"\", mapper)\n\n def map_join(collection, joiner, mapper) when is_binary(joiner) do\n reduced = reduce(collection, :first, fn\n entry, :first -> to_string(mapper, entry)\n entry, acc -> acc <> joiner <> to_string(mapper, entry)\n end)\n\n if reduced == :first do\n \"\"\n else\n reduced\n end\n end\n\n @doc \"\"\"\n Invokes the given `fun` for each item in the `collection`\n while also keeping an accumulator. Returns a tuple where\n the first element is the mapped collection and the second\n one is the final accumulator.\n\n For dicts, the first tuple element must be a `{key, value}`\n tuple.\n\n ## Examples\n\n iex> Enum.map_reduce([1, 2, 3], 0, fn(x, acc) -> {x * 2, x + acc} end)\n {[2, 4, 6], 6}\n\n \"\"\"\n @spec map_reduce(t, any, (element, any -> any)) :: any\n def map_reduce(collection, acc, fun) when is_list(collection) do\n :lists.mapfoldl(fun, acc, collection)\n end\n\n def map_reduce(collection, acc, fun) do\n {list, acc} = reduce(collection, {[], acc}, fn(entry, {list, acc}) ->\n {new_entry, acc} = fun.(entry, acc)\n {[new_entry|list], acc}\n end)\n {:lists.reverse(list), acc}\n end\n\n @doc \"\"\"\n Returns the maximum value.\n Raises `EmptyError` if the collection is empty.\n\n ## Examples\n\n iex> Enum.max([1, 2, 3])\n 3\n\n \"\"\"\n @spec max(t) :: element | no_return\n def max(collection) do\n reduce(collection, &Kernel.max(&1, &2))\n end\n\n @doc \"\"\"\n Returns the maximum value as calculated by the given function.\n Raises `EmptyError` if the collection is empty.\n\n ## Examples\n\n iex> Enum.max_by([\"a\", \"aa\", \"aaa\"], fn(x) -> String.length(x) end)\n \"aaa\"\n\n \"\"\"\n @spec max_by(t, (element -> any)) :: element | no_return\n def max_by([h|t], fun) do\n reduce(t, {h, fun.(h)}, fn(entry, {_, fun_max} = old) ->\n fun_entry = fun.(entry)\n if(fun_entry > fun_max, do: {entry, fun_entry}, else: old)\n end) |> elem(0)\n end\n\n def max_by([], _fun) do\n raise Enum.EmptyError\n end\n\n def max_by(collection, fun) do\n result =\n reduce(collection, :first, fn\n entry, {_, fun_max} = old ->\n fun_entry = fun.(entry)\n if(fun_entry > fun_max, do: {entry, fun_entry}, else: old)\n entry, :first ->\n {entry, fun.(entry)}\n end)\n\n case result do\n :first -> raise Enum.EmptyError\n {entry, _} -> entry\n end\n end\n\n @doc \"\"\"\n Checks if `value` exists within the `collection`.\n\n Membership is tested with the match (`===`) operator, although\n enumerables like ranges may include floats inside the given\n range.\n\n ## Examples\n\n iex> Enum.member?(1..10, 5)\n true\n\n iex> Enum.member?([:a, :b, :c], :d)\n false\n\n \"\"\"\n @spec member?(t, element) :: boolean\n def member?(collection, value) when is_list(collection) do\n :lists.member(value, collection)\n end\n\n def member?(collection, value) do\n case Enumerable.member?(collection, value) do\n {:ok, value} when is_boolean(value) ->\n value\n {:error, module} ->\n module.reduce(collection, {:cont, false}, fn\n v, _ when v === value -> {:halt, true}\n _, _ -> {:cont, false}\n end) |> elem(1)\n end\n end\n\n @doc \"\"\"\n Returns the minimum value.\n Raises `EmptyError` if the collection is empty.\n\n ## Examples\n\n iex> Enum.min([1, 2, 3])\n 1\n\n \"\"\"\n @spec min(t) :: element | no_return\n def min(collection) do\n reduce(collection, &Kernel.min(&1, &2))\n end\n\n @doc \"\"\"\n Returns the minimum value as calculated by the given function.\n Raises `EmptyError` if the collection is empty.\n\n ## Examples\n\n iex> Enum.min_by([\"a\", \"aa\", \"aaa\"], fn(x) -> String.length(x) end)\n \"a\"\n\n \"\"\"\n @spec min_by(t, (element -> any)) :: element | no_return\n def min_by([h|t], fun) do\n reduce(t, {h, fun.(h)}, fn(entry, {_, fun_min} = old) ->\n fun_entry = fun.(entry)\n if(fun_entry < fun_min, do: {entry, fun_entry}, else: old)\n end) |> elem(0)\n end\n\n def min_by([], _fun) do\n raise Enum.EmptyError\n end\n\n def min_by(collection, fun) do\n result =\n reduce(collection, :first, fn\n entry, {_, fun_min} = old ->\n fun_entry = fun.(entry)\n if(fun_entry < fun_min, do: {entry, fun_entry}, else: old)\n entry, :first ->\n {entry, fun.(entry)}\n end)\n\n case result do\n :first -> raise Enum.EmptyError\n {entry, _} -> entry\n end\n end\n\n @doc \"\"\"\n Returns the sum of all values.\n\n Raises `ArithmeticError` if collection contains a non-numeric value.\n\n ## Examples\n\n iex> Enum.sum([1, 2, 3])\n 6\n\n \"\"\"\n @spec sum(t) :: number\n def sum(collection) do\n reduce(collection, 0, &+\/2)\n end\n\n @doc \"\"\"\n Partitions `collection` into two collections, where the first one contains elements\n for which `fun` returns a truthy value, and the second one -- for which `fun`\n returns `false` or `nil`.\n\n ## Examples\n\n iex> Enum.partition([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)\n {[2], [1,3]}\n\n \"\"\"\n @spec partition(t, (element -> any)) :: {list, list}\n def partition(collection, fun) do\n {acc1, acc2} =\n reduce(collection, {[], []}, fn(entry, {acc1, acc2}) ->\n if fun.(entry) do\n {[entry|acc1], acc2}\n else\n {acc1, [entry|acc2]}\n end\n end)\n\n {:lists.reverse(acc1), :lists.reverse(acc2)}\n end\n\n @doc \"\"\"\n Splits `collection` into groups based on `fun`.\n\n The result is a dict (by default a map) where each key is\n a group and each value is a list of elements from `collection`\n for which `fun` returned that group. Ordering is not necessarily\n preserved.\n\n ## Examples\n\n iex> Enum.group_by(~w{ant buffalo cat dingo}, &String.length\/1)\n %{3 => [\"cat\", \"ant\"], 7 => [\"buffalo\"], 5 => [\"dingo\"]}\n\n \"\"\"\n @spec group_by(t, dict, (element -> any)) :: dict when dict: Dict.t\n def group_by(collection, dict \\\\ %{}, fun) do\n reduce(collection, dict, fn(entry, categories) ->\n Dict.update(categories, fun.(entry), [entry], &[entry|&1])\n end)\n end\n\n @doc \"\"\"\n Invokes `fun` for each element in the collection passing that element and the\n accumulator `acc` as arguments. `fun`'s return value is stored in `acc`.\n Returns the accumulator.\n\n ## Examples\n\n iex> Enum.reduce([1, 2, 3], 0, fn(x, acc) -> x + acc end)\n 6\n\n \"\"\"\n @spec reduce(t, any, (element, any -> any)) :: any\n def reduce(collection, acc, fun) when is_list(collection) do\n :lists.foldl(fun, acc, collection)\n end\n\n def reduce(collection, acc, fun) do\n Enumerable.reduce(collection, {:cont, acc},\n fn x, acc -> {:cont, fun.(x, acc)} end) |> elem(1)\n end\n\n @doc \"\"\"\n Invokes `fun` for each element in the collection passing that element and the\n accumulator `acc` as arguments. `fun`'s return value is stored in `acc`.\n The first element of the collection is used as the initial value of `acc`.\n Returns the accumulator.\n\n ## Examples\n\n iex> Enum.reduce([1, 2, 3, 4], fn(x, acc) -> x * acc end)\n 24\n\n \"\"\"\n @spec reduce(t, (element, any -> any)) :: any\n def reduce([h|t], fun) do\n reduce(t, h, fun)\n end\n\n def reduce([], _fun) do\n raise Enum.EmptyError\n end\n\n def reduce(collection, fun) do\n result =\n Enumerable.reduce(collection, {:cont, :first}, fn\n x, :first ->\n {:cont, {:acc, x}}\n x, {:acc, acc} ->\n {:cont, {:acc, fun.(x, acc)}}\n end) |> elem(1)\n\n case result do\n :first -> raise Enum.EmptyError\n {:acc, acc} -> acc\n end\n end\n\n @doc \"\"\"\n Returns elements of collection for which `fun` returns `false`.\n\n ## Examples\n\n iex> Enum.reject([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)\n [1, 3]\n\n \"\"\"\n @spec reject(t, (element -> as_boolean(term))) :: list\n def reject(collection, fun) when is_list(collection) do\n for item <- collection, !fun.(item), do: item\n end\n\n def reject(collection, fun) do\n Enumerable.reduce(collection, {:cont, []}, R.reject(fun)) |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Reverses the collection.\n\n ## Examples\n\n iex> Enum.reverse([1, 2, 3])\n [3, 2, 1]\n\n \"\"\"\n @spec reverse(t) :: list\n def reverse(collection) when is_list(collection) do\n :lists.reverse(collection)\n end\n\n def reverse(collection) do\n reverse(collection, [])\n end\n\n @doc \"\"\"\n Reverses the collection and appends the tail.\n This is an optimization for\n `Enum.concat(Enum.reverse(collection), tail)`.\n\n ## Examples\n\n iex> Enum.reverse([1, 2, 3], [4, 5, 6])\n [3, 2, 1, 4, 5, 6]\n\n \"\"\"\n @spec reverse(t, t) :: list\n def reverse(collection, tail) when is_list(collection) and is_list(tail) do\n :lists.reverse(collection, tail)\n end\n\n def reverse(collection, tail) do\n reduce(collection, to_list(tail), fn(entry, acc) ->\n [entry|acc]\n end)\n end\n\n @doc \"\"\"\n Applies the given function to each element in the collection,\n storing the result in a list and passing it as the accumulator\n for the next computation.\n\n ## Examples\n\n iex> Enum.scan(1..5, &(&1 + &2))\n [1,3,6,10,15]\n\n \"\"\"\n @spec scan(t, (element, any -> any)) :: list\n def scan(enum, fun) do\n {_, {res, _}} =\n Enumerable.reduce(enum, {:cont, {[], :first}}, R.scan_2(fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Applies the given function to each element in the collection,\n storing the result in a list and passing it as the accumulator\n for the next computation. Uses the given `acc` as the starting value.\n\n ## Examples\n\n iex> Enum.scan(1..5, 0, &(&1 + &2))\n [1,3,6,10,15]\n\n \"\"\"\n @spec scan(t, any, (element, any -> any)) :: list\n def scan(enum, acc, fun) do\n {_, {res, _}} =\n Enumerable.reduce(enum, {:cont, {[], acc}}, R.scan_3(fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Returns a list of collection elements shuffled.\n\n Notice that you need to explicitly call `:random.seed\/1` and\n set a seed value for the random algorithm. Otherwise, the\n default seed will be set which will always return the same\n result. For example, one could do the following to set a seed\n dynamically:\n\n :random.seed(:erlang.now)\n\n ## Examples\n\n iex> Enum.shuffle([1, 2, 3])\n [3, 2, 1]\n iex> Enum.shuffle([1, 2, 3])\n [3, 1, 2]\n\n \"\"\"\n @spec shuffle(t) :: list\n def shuffle(collection) do\n randomized = reduce(collection, [], fn x, acc ->\n [{:random.uniform, x}|acc]\n end)\n unwrap(:lists.keysort(1, randomized), [])\n end\n\n @doc \"\"\"\n Returns a subset list of the given collection. Drops elements\n until element position `start`, then takes `count` elements.\n \n If the count is greater than collection length, it returns as\n much as possible. If zero, then it returns `[]`.\n\n ## Examples\n\n iex> Enum.slice(1..100, 5, 10)\n [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n\n iex> Enum.slice(1..10, 5, 100)\n [6, 7, 8, 9, 10]\n\n iex> Enum.slice(1..10, 5, 0)\n []\n\n \"\"\"\n @spec slice(t, integer, non_neg_integer) :: list\n \n def slice(_coll, _start, 0), do: []\n\n def slice(coll, start, count) when start < 0 do\n {list, new_start} = enumerate_and_count(coll, start)\n if new_start >= 0 do\n slice(list, new_start, count)\n else\n []\n end\n end\n\n def slice(coll, start, count) when is_list(coll) and start >= 0 and count > 0 do\n do_slice(coll, start, count)\n end\n\n def slice(coll, start, count) when start >= 0 and count > 0 do\n {_, _, list} = Enumerable.reduce(coll, {:cont, {start, count, []}}, fn\n _entry, {start, count, _list} when start > 0 ->\n {:cont, {start-1, count, []}}\n entry, {start, count, list} when count > 1 ->\n {:cont, {start, count-1, [entry|list]}}\n entry, {start, count, list} ->\n {:halt, {start, count, [entry|list]}}\n end) |> elem(1)\n\n :lists.reverse(list)\n end\n\n @doc \"\"\"\n Returns a subset list of the given collection. Drops elements\n until element position `range.first`, then takes elements until element\n position `range.last` (inclusive).\n\n Positions are calculated by adding the number of items in the collection to\n negative positions (so position -3 in a collection with count 5 becomes\n position 2).\n\n The first position (after adding count to negative positions) must be smaller\n or equal to the last position.\n\n If the start of the range is not a valid offset for the given\n collection or if the range is in reverse order, returns `[]`.\n\n ## Examples\n\n iex> Enum.slice(1..100, 5..10)\n [6, 7, 8, 9, 10, 11]\n\n iex> Enum.slice(1..10, 5..20)\n [6, 7, 8, 9, 10]\n\n iex> Enum.slice(1..10, 11..20)\n []\n\n iex> Enum.slice(1..10, 6..5)\n []\n\n \"\"\"\n @spec slice(t, Range.t) :: list\n def slice(coll, first..last) when first >= 0 and last >= 0 do\n # Simple case, which works on infinite collections\n if last - first >= 0 do\n slice(coll, first, last - first + 1)\n else\n []\n end\n end\n\n def slice(coll, first..last) do\n {list, count} = enumerate_and_count(coll, 0)\n corr_first = if first >= 0, do: first, else: first + count\n corr_last = if last >= 0, do: last, else: last + count\n length = corr_last - corr_first + 1\n if corr_first >= 0 and length > 0 do\n slice(list, corr_first, length)\n else\n []\n end\n end\n\n @doc \"\"\"\n Sorts the collection according to Elixir's term ordering.\n\n Uses the merge sort algorithm.\n\n ## Examples\n\n iex> Enum.sort([3, 2, 1])\n [1, 2, 3]\n\n \"\"\"\n @spec sort(t) :: list\n def sort(collection) when is_list(collection) do\n :lists.sort(collection)\n end\n\n def sort(collection) do\n sort(collection, &(&1 <= &2))\n end\n\n @doc \"\"\"\n Sorts the collection by the given function.\n\n This function uses the merge sort algorithm. The given function\n must return false if the first argument is less than right one.\n\n ## Examples\n\n iex> Enum.sort([1, 2, 3], &(&1 > &2))\n [3, 2, 1]\n\n The sorting algorithm will be stable as long as the given function\n returns true for values considered equal:\n\n iex> Enum.sort [\"some\", \"kind\", \"of\", \"monster\"], &(byte_size(&1) <= byte_size(&2))\n [\"of\", \"some\", \"kind\", \"monster\"]\n\n If the function does not return true, the sorting is not stable and\n the order of equal terms may be shuffled:\n\n iex> Enum.sort [\"some\", \"kind\", \"of\", \"monster\"], &(byte_size(&1) < byte_size(&2))\n [\"of\", \"kind\", \"some\", \"monster\"]\n\n \"\"\"\n @spec sort(t, (element, element -> boolean)) :: list\n def sort(collection, fun) when is_list(collection) do\n :lists.sort(fun, collection)\n end\n\n def sort(collection, fun) do\n reduce(collection, [], &sort_reducer(&1, &2, fun)) |> sort_terminator(fun)\n end\n\n @doc \"\"\"\n Splits the enumerable into two collections, leaving `count`\n elements in the first one. If `count` is a negative number,\n it starts counting from the back to the beginning of the\n collection.\n\n Be aware that a negative `count` implies the collection\n will be enumerated twice: once to calculate the position, and\n a second time to do the actual splitting.\n\n ## Examples\n\n iex> Enum.split([1, 2, 3], 2)\n {[1,2], [3]}\n\n iex> Enum.split([1, 2, 3], 10)\n {[1,2,3], []}\n\n iex> Enum.split([1, 2, 3], 0)\n {[], [1,2,3]}\n\n iex> Enum.split([1, 2, 3], -1)\n {[1,2], [3]}\n\n iex> Enum.split([1, 2, 3], -5)\n {[], [1,2,3]}\n\n \"\"\"\n @spec split(t, integer) :: {list, list}\n def split(collection, count) when is_list(collection) and count >= 0 do\n do_split(collection, count, [])\n end\n\n def split(collection, count) when count >= 0 do\n {_, list1, list2} =\n reduce(collection, {count, [], []}, fn(entry, {counter, acc1, acc2}) ->\n if counter > 0 do\n {counter - 1, [entry|acc1], acc2}\n else\n {counter, acc1, [entry|acc2]}\n end\n end)\n\n {:lists.reverse(list1), :lists.reverse(list2)}\n end\n\n def split(collection, count) when count < 0 do\n do_split_reverse(reverse(collection), abs(count), [])\n end\n\n @doc \"\"\"\n Splits `collection` in two while `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.split_while([1, 2, 3, 4], fn(x) -> x < 3 end)\n {[1, 2], [3, 4]}\n\n \"\"\"\n @spec split_while(t, (element -> as_boolean(term))) :: {list, list}\n def split_while(collection, fun) when is_list(collection) do\n do_split_while(collection, fun, [])\n end\n\n def split_while(collection, fun) do\n {list1, list2} =\n reduce(collection, {[], []}, fn\n entry, {acc1, []} ->\n if(fun.(entry), do: {[entry|acc1], []}, else: {acc1, [entry]})\n entry, {acc1, acc2} ->\n {acc1, [entry|acc2]}\n end)\n\n {:lists.reverse(list1), :lists.reverse(list2)}\n end\n\n @doc \"\"\"\n Takes the first `count` items from the collection.\n\n If a negative `count` is given, the last `count` values will\n be taken. For such, the collection is fully enumerated keeping up\n to `2 * count` elements in memory. Once the end of the collection is\n reached, the last `count` elements are returned.\n\n ## Examples\n\n iex> Enum.take([1, 2, 3], 2)\n [1,2]\n\n iex> Enum.take([1, 2, 3], 10)\n [1,2,3]\n\n iex> Enum.take([1, 2, 3], 0)\n []\n\n iex> Enum.take([1, 2, 3], -1)\n [3]\n\n \"\"\"\n @spec take(t, integer) :: list\n\n def take(_collection, 0) do\n []\n end\n\n def take(collection, count) when is_list(collection) and count > 0 do\n do_take(collection, count)\n end\n\n def take(collection, count) when count > 0 do\n {_, {res, _}} =\n Enumerable.reduce(collection, {:cont, {[], count}}, fn(entry, {list, count}) ->\n if count > 1 do\n {:cont, {[entry|list], count - 1}}\n else\n {:halt, {[entry|list], count}}\n end\n end)\n :lists.reverse(res)\n end\n\n def take(collection, count) when count < 0 do\n Stream.take(collection, count).({:cont, []}, &{:cont, [&1|&2]})\n |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Returns a collection of every `nth` item in the collection,\n starting with the first element.\n\n ## Examples\n\n iex> Enum.take_every(1..10, 2)\n [1, 3, 5, 7, 9]\n\n \"\"\"\n @spec take_every(t, integer) :: list\n def take_every(_collection, 0), do: []\n def take_every(collection, nth) do\n {_, {res, _}} =\n Enumerable.reduce(collection, {:cont, {[], :first}}, R.take_every(nth))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Takes the items at the beginning of `collection` while `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.take_while([1, 2, 3], fn(x) -> x < 3 end)\n [1, 2]\n\n \"\"\"\n @spec take_while(t, (element -> as_boolean(term))) :: list\n def take_while(collection, fun) when is_list(collection) do\n do_take_while(collection, fun)\n end\n\n def take_while(collection, fun) do\n Enumerable.reduce(collection, {:cont, []}, R.take_while(fun))\n |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Convert `collection` to a list.\n\n ## Examples\n\n iex> Enum.to_list(1 .. 3)\n [1, 2, 3]\n\n \"\"\"\n @spec to_list(t) :: [term]\n def to_list(collection) when is_list(collection) do\n collection\n end\n\n def to_list(collection) do\n reverse(collection) |> :lists.reverse\n end\n\n\n @doc \"\"\"\n Traverses the given enumerable keeping its shape.\n\n It also expects the enumerable to implement the `Collectable` protocol.\n\n ## Examples\n\n iex> Enum.traverse(%{a: 1, b: 2}, fn {k, v} -> {k, v * 2} end)\n %{a: 2, b: 4}\n\n \"\"\"\n @spec traverse(Enumerable.t, (term -> term)) :: Collectable.t\n def traverse(collection, transform) when is_list(collection) do\n :lists.map(transform, collection)\n end\n\n def traverse(collection, transform) do\n into(collection, Collectable.empty(collection), transform)\n end\n\n @doc \"\"\"\n Enumerates the collection, removing all duplicated items.\n\n ## Examples\n\n iex> Enum.uniq([1, 2, 3, 2, 1])\n [1, 2, 3]\n\n iex> Enum.uniq([{1, :x}, {2, :y}, {1, :z}], fn {x, _} -> x end)\n [{1,:x}, {2,:y}]\n\n \"\"\"\n @spec uniq(t) :: list\n @spec uniq(t, (element -> term)) :: list\n def uniq(collection, fun \\\\ fn x -> x end)\n\n def uniq(collection, fun) when is_list(collection) do\n do_uniq(collection, [], fun)\n end\n\n def uniq(collection, fun) do\n {_, {list, _}} =\n Enumerable.reduce(collection, {:cont, {[], []}}, R.uniq(fun))\n :lists.reverse(list)\n end\n\n @doc \"\"\"\n Zips corresponding elements from two collections into one list\n of tuples.\n\n The zipping finishes as soon as any enumerable completes.\n\n ## Examples\n\n iex> Enum.zip([1, 2, 3], [:a, :b, :c])\n [{1,:a},{2,:b},{3,:c}]\n\n iex> Enum.zip([1,2,3,4,5], [:a, :b, :c])\n [{1,:a},{2,:b},{3,:c}]\n\n \"\"\"\n @spec zip(t, t) :: [{any, any}]\n def zip(coll1, coll2) when is_list(coll1) and is_list(coll2) do\n do_zip(coll1, coll2)\n end\n\n def zip(coll1, coll2) do\n Stream.zip(coll1, coll2).({:cont, []}, &{:cont, [&1|&2]}) |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Returns the collection with each element wrapped in a tuple\n alongside its index.\n\n ## Examples\n\n iex> Enum.with_index [1,2,3]\n [{1,0},{2,1},{3,2}]\n\n \"\"\"\n @spec with_index(t) :: list({element, non_neg_integer})\n def with_index(collection) do\n map_reduce(collection, 0, fn x, acc ->\n {{x, acc}, acc + 1}\n end) |> elem(0)\n end\n\n ## Helpers\n\n @compile {:inline, to_string: 2}\n\n defp enumerate_and_count(collection, count) when is_list(collection) do\n {collection, length(collection) - abs(count)}\n end\n\n defp enumerate_and_count(collection, count) do\n map_reduce(collection, -abs(count), fn(x, acc) -> {x, acc + 1} end)\n end\n\n defp to_string(mapper, entry) do\n case mapper.(entry) do\n x when is_binary(x) -> x\n o -> String.Chars.to_string(o)\n end\n end\n\n ## Implementations\n\n ## all?\n\n defp do_all?([h|t], fun) do\n if fun.(h) do\n do_all?(t, fun)\n else\n false\n end\n end\n\n defp do_all?([], _) do\n true\n end\n\n ## any?\n\n defp do_any?([h|t], fun) do\n if fun.(h) do\n true\n else\n do_any?(t, fun)\n end\n end\n\n defp do_any?([], _) do\n false\n end\n\n ## fetch\n\n defp do_fetch([h|_], 0), do: {:ok, h}\n defp do_fetch([_|t], n), do: do_fetch(t, n - 1)\n defp do_fetch([], _), do: :error\n\n ## drop\n\n defp do_drop([_|t], counter) when counter > 0 do\n do_drop(t, counter - 1)\n end\n\n defp do_drop(list, 0) do\n list\n end\n\n defp do_drop([], _) do\n []\n end\n\n ## drop_while\n\n defp do_drop_while([h|t], fun) do\n if fun.(h) do\n do_drop_while(t, fun)\n else\n [h|t]\n end\n end\n\n defp do_drop_while([], _) do\n []\n end\n\n ## find\n\n defp do_find([h|t], ifnone, fun) do\n if fun.(h) do\n h\n else\n do_find(t, ifnone, fun)\n end\n end\n\n defp do_find([], ifnone, _) do\n ifnone\n end\n\n ## find_index\n\n defp do_find_index([h|t], counter, fun) do\n if fun.(h) do\n counter\n else\n do_find_index(t, counter + 1, fun)\n end\n end\n\n defp do_find_index([], _, _) do\n nil\n end\n\n ## find_value\n\n defp do_find_value([h|t], ifnone, fun) do\n fun.(h) || do_find_value(t, ifnone, fun)\n end\n\n defp do_find_value([], ifnone, _) do\n ifnone\n end\n\n ## shuffle\n\n defp unwrap([{_, h} | collection], t) do\n unwrap(collection, [h|t])\n end\n\n defp unwrap([], t), do: t\n\n ## sort\n\n defp sort_reducer(entry, {:split, y, x, r, rs, bool}, fun) do\n cond do\n fun.(y, entry) == bool ->\n {:split, entry, y, [x|r], rs, bool}\n fun.(x, entry) == bool ->\n {:split, y, entry, [x|r], rs, bool}\n r == [] ->\n {:split, y, x, [entry], rs, bool}\n true ->\n {:pivot, y, x, r, rs, entry, bool}\n end\n end\n\n defp sort_reducer(entry, {:pivot, y, x, r, rs, s, bool}, fun) do\n cond do\n fun.(y, entry) == bool ->\n {:pivot, entry, y, [x | r], rs, s, bool}\n fun.(x, entry) == bool ->\n {:pivot, y, entry, [x | r], rs, s, bool}\n fun.(s, entry) == bool ->\n {:split, entry, s, [], [[y, x | r] | rs], bool}\n true ->\n {:split, s, entry, [], [[y, x | r] | rs], bool}\n end\n end\n\n defp sort_reducer(entry, [x], fun) do\n {:split, entry, x, [], [], fun.(x, entry)}\n end\n\n defp sort_reducer(entry, acc, _fun) do\n [entry|acc]\n end\n\n defp sort_terminator({:split, y, x, r, rs, bool}, fun) do\n sort_merge([[y, x | r] | rs], fun, bool)\n end\n\n defp sort_terminator({:pivot, y, x, r, rs, s, bool}, fun) do\n sort_merge([[s], [y, x | r] | rs], fun, bool)\n end\n\n defp sort_terminator(acc, _fun) do\n acc\n end\n\n defp sort_merge(list, fun, true), do:\n reverse_sort_merge(list, [], fun, true)\n\n defp sort_merge(list, fun, false), do:\n sort_merge(list, [], fun, false)\n\n\n defp sort_merge([t1, [h2 | t2] | l], acc, fun, true), do:\n sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, false) | acc], fun, true)\n\n defp sort_merge([[h2 | t2], t1 | l], acc, fun, false), do:\n sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, false) | acc], fun, false)\n\n defp sort_merge([l], [], _fun, _bool), do: l\n\n defp sort_merge([l], acc, fun, bool), do:\n reverse_sort_merge([:lists.reverse(l, []) | acc], [], fun, bool)\n\n defp sort_merge([], acc, fun, bool), do:\n reverse_sort_merge(acc, [], fun, bool)\n\n\n defp reverse_sort_merge([[h2 | t2], t1 | l], acc, fun, true), do:\n reverse_sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, true) | acc], fun, true)\n\n defp reverse_sort_merge([t1, [h2 | t2] | l], acc, fun, false), do:\n reverse_sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, true) | acc], fun, false)\n\n defp reverse_sort_merge([l], acc, fun, bool), do:\n sort_merge([:lists.reverse(l, []) | acc], [], fun, bool)\n\n defp reverse_sort_merge([], acc, fun, bool), do:\n sort_merge(acc, [], fun, bool)\n\n\n defp sort_merge_1([h1 | t1], h2, t2, m, fun, bool) do\n if fun.(h1, h2) == bool do\n sort_merge_2(h1, t1, t2, [h2 | m], fun, bool)\n else\n sort_merge_1(t1, h2, t2, [h1 | m], fun, bool)\n end\n end\n\n defp sort_merge_1([], h2, t2, m, _fun, _bool), do:\n :lists.reverse(t2, [h2 | m])\n\n\n defp sort_merge_2(h1, t1, [h2 | t2], m, fun, bool) do\n if fun.(h1, h2) == bool do\n sort_merge_2(h1, t1, t2, [h2 | m], fun, bool)\n else\n sort_merge_1(t1, h2, t2, [h1 | m], fun, bool)\n end\n end\n\n defp sort_merge_2(h1, t1, [], m, _fun, _bool), do:\n :lists.reverse(t1, [h1 | m])\n\n ## split\n\n defp do_split([h|t], counter, acc) when counter > 0 do\n do_split(t, counter - 1, [h|acc])\n end\n\n defp do_split(list, 0, acc) do\n {:lists.reverse(acc), list}\n end\n\n defp do_split([], _, acc) do\n {:lists.reverse(acc), []}\n end\n\n defp do_split_reverse([h|t], counter, acc) when counter > 0 do\n do_split_reverse(t, counter - 1, [h|acc])\n end\n\n defp do_split_reverse(list, 0, acc) do\n {:lists.reverse(list), acc}\n end\n\n defp do_split_reverse([], _, acc) do\n {[], acc}\n end\n\n ## split_while\n\n defp do_split_while([h|t], fun, acc) do\n if fun.(h) do\n do_split_while(t, fun, [h|acc])\n else\n {:lists.reverse(acc), [h|t]}\n end\n end\n\n defp do_split_while([], _, acc) do\n {:lists.reverse(acc), []}\n end\n\n ## take\n\n defp do_take([h|t], counter) when counter > 0 do\n [h|do_take(t, counter - 1)]\n end\n\n defp do_take(_list, 0) do\n []\n end\n\n defp do_take([], _) do\n []\n end\n\n ## take_while\n\n defp do_take_while([h|t], fun) do\n if fun.(h) do\n [h|do_take_while(t, fun)]\n else\n []\n end\n end\n\n defp do_take_while([], _) do\n []\n end\n\n ## uniq\n\n defp do_uniq([h|t], acc, fun) do\n fun_h = fun.(h)\n case :lists.member(fun_h, acc) do\n true -> do_uniq(t, acc, fun)\n false -> [h|do_uniq(t, [fun_h|acc], fun)]\n end\n end\n\n defp do_uniq([], _acc, _fun) do\n []\n end\n\n ## zip\n\n defp do_zip([h1|next1], [h2|next2]) do\n [{h1, h2}|do_zip(next1, next2)]\n end\n\n defp do_zip(_, []), do: []\n defp do_zip([], _), do: []\n\n ## slice\n\n defp do_slice([], _start, _count) do\n []\n end\n\n defp do_slice(_list, _start, 0) do\n []\n end\n\n defp do_slice([h|t], 0, count) do\n [h|do_slice(t, 0, count-1)]\n end\n\n defp do_slice([_|t], start, count) do\n do_slice(t, start-1, count)\n end\nend\n\ndefimpl Enumerable, for: List do\n def reduce(_, {:halt, acc}, _fun), do: {:halted, acc}\n def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)}\n def reduce([], {:cont, acc}, _fun), do: {:done, acc}\n def reduce([h|t], {:cont, acc}, fun), do: reduce(t, fun.(h, acc), fun)\n\n def member?(_list, _value),\n do: {:error, __MODULE__}\n def count(_list),\n do: {:error, __MODULE__}\nend\n\ndefimpl Enumerable, for: Map do\n def reduce(map, acc, fun) do\n do_reduce(:maps.to_list(map), acc, fun)\n end\n\n defp do_reduce(_, {:halt, acc}, _fun), do: {:halted, acc}\n defp do_reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &do_reduce(list, &1, fun)}\n defp do_reduce([], {:cont, acc}, _fun), do: {:done, acc}\n defp do_reduce([h|t], {:cont, acc}, fun), do: do_reduce(t, fun.(h, acc), fun)\n\n def member?(map, {key, value}) do\n {:ok, match?({:ok, ^value}, :maps.find(key, map))}\n end\n\n def member?(_map, _other) do\n {:ok, false}\n end\n\n def count(map) do\n {:ok, map_size(map)}\n end\nend\n\ndefimpl Enumerable, for: Function do\n def reduce(function, acc, fun) when is_function(function, 2),\n do: function.(acc, fun)\n def member?(_function, _value),\n do: {:error, __MODULE__}\n def count(_function),\n do: {:error, __MODULE__}\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"70159ec8e35c239a99d2565010dab640d954eb34","subject":"fix Enum.sample docs","message":"fix Enum.sample docs\n\n* sample\/2 doc was empty\n* clarify impl notes, add link to algorithm\n* use :os.timestamp in examples of setting the seed\n","repos":"lexmag\/elixir,kelvinst\/elixir,joshprice\/elixir,gfvcastro\/elixir,pedrosnk\/elixir,beedub\/elixir,lexmag\/elixir,antipax\/elixir,gfvcastro\/elixir,antipax\/elixir,kimshrier\/elixir,beedub\/elixir,elixir-lang\/elixir,ggcampinho\/elixir,pedrosnk\/elixir,kimshrier\/elixir,kelvinst\/elixir,michalmuskala\/elixir,ggcampinho\/elixir","old_file":"lib\/elixir\/lib\/enum.ex","new_file":"lib\/elixir\/lib\/enum.ex","new_contents":"defprotocol Enumerable do\n @moduledoc \"\"\"\n Enumerable protocol used by `Enum` and `Stream` modules.\n\n When you invoke a function in the `Enum` module, the first argument\n is usually a collection that must implement this protocol. For example,\n the expression\n\n Enum.map([1, 2, 3], &(&1 * 2))\n\n invokes underneath `Enumerable.reduce\/3` to perform the reducing\n operation that builds a mapped list by calling the mapping function\n `&(&1 * 2)` on every element in the collection and cons'ing the\n element with an accumulated list.\n\n Internally, `Enum.map\/2` is implemented as follows:\n\n def map(enum, fun) do\n reducer = fn x, acc -> {:cont, [fun.(x)|acc]} end\n Enumerable.reduce(enum, {:cont, []}, reducer) |> elem(1) |> :lists.reverse()\n end\n\n Notice the user given function is wrapped into a `reducer` function.\n The `reducer` function must return a tagged tuple after each step,\n as described in the `acc\/0` type.\n\n The reason the accumulator requires a tagged tuple is to allow the\n reducer function to communicate to the underlying enumerable the end\n of enumeration, allowing any open resource to be properly closed. It\n also allows suspension of the enumeration, which is useful when\n interleaving between many enumerables is required (as in zip).\n\n Finally, `Enumerable.reduce\/3` will return another tagged tuple,\n as represented by the `result\/0` type.\n \"\"\"\n\n @typedoc \"\"\"\n The accumulator value for each step.\n\n It must be a tagged tuple with one of the following \"tags\":\n\n * `:cont` - the enumeration should continue\n * `:halt` - the enumeration should halt immediately\n * `:suspend` - the enumeration should be suspended immediately\n\n Depending on the accumulator value, the result returned by\n `Enumerable.reduce\/3` will change. Please check the `result`\n type docs for more information.\n\n In case a reducer function returns a `:suspend` accumulator,\n it must be explicitly handled by the caller and never leak.\n \"\"\"\n @type acc :: {:cont, term} | {:halt, term} | {:suspend, term}\n\n @typedoc \"\"\"\n The reducer function.\n\n Should be called with the collection element and the\n accumulator contents. Returns the accumulator for\n the next enumeration step.\n \"\"\"\n @type reducer :: (term, term -> acc)\n\n @typedoc \"\"\"\n The result of the reduce operation.\n\n It may be *done* when the enumeration is finished by reaching\n its end, or *halted*\/*suspended* when the enumeration was halted\n or suspended by the reducer function.\n\n In case a reducer function returns the `:suspend` accumulator, the\n `:suspended` tuple must be explicitly handled by the caller and\n never leak. In practice, this means regular enumeration functions\n just need to be concerned about `:done` and `:halted` results.\n\n Furthermore, a `:suspend` call must always be followed by another call,\n eventually halting or continuing until the end.\n \"\"\"\n @type result :: {:done, term} | {:halted, term} | {:suspended, term, continuation}\n\n @typedoc \"\"\"\n A partially applied reduce function.\n\n The continuation is the closure returned as a result when\n the enumeration is suspended. When invoked, it expects\n a new accumulator and it returns the result.\n\n A continuation is easily implemented as long as the reduce\n function is defined in a tail recursive fashion. If the function\n is tail recursive, all the state is passed as arguments, so\n the continuation would simply be the reducing function partially\n applied.\n \"\"\"\n @type continuation :: (acc -> result)\n\n @doc \"\"\"\n Reduces the collection into a value.\n\n Most of the operations in `Enum` are implemented in terms of reduce.\n This function should apply the given `reducer` function to each\n item in the collection and proceed as expected by the returned accumulator.\n\n As an example, here is the implementation of `reduce` for lists:\n\n def reduce(_, {:halt, acc}, _fun), do: {:halted, acc}\n def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)}\n def reduce([], {:cont, acc}, _fun), do: {:done, acc}\n def reduce([h|t], {:cont, acc}, fun), do: reduce(t, fun.(h, acc), fun)\n\n \"\"\"\n @spec reduce(t, acc, reducer) :: result\n def reduce(collection, acc, fun)\n\n @doc \"\"\"\n Checks if a value exists within the collection.\n\n It should return `{:ok, boolean}`.\n\n If `{:error, __MODULE__}` is returned a default algorithm using `reduce` and\n the match (`===`) operator is used. This algorithm runs in linear time.\n\n Please force use of the default algorithm unless you can implement an\n algorithm that is significantly faster.\n \"\"\"\n @spec member?(t, term) :: {:ok, boolean} | {:error, module}\n def member?(collection, value)\n\n @doc \"\"\"\n Retrieves the collection's size.\n\n It should return `{:ok, size}`.\n\n If `{:error, __MODULE__}` is returned a default algorithm using `reduce` and\n the match (`===`) operator is used. This algorithm runs in linear time.\n\n Please force use of the default algorithm unless you can implement an\n algorithm that is significantly faster.\n \"\"\"\n @spec count(t) :: {:ok, non_neg_integer} | {:error, module}\n def count(collection)\nend\n\ndefmodule Enum do\n import Kernel, except: [max: 2, min: 2]\n\n @moduledoc \"\"\"\n Provides a set of algorithms that enumerate over collections according to the\n `Enumerable` protocol:\n\n iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end)\n [2,4,6]\n\n Some particular types, like dictionaries, yield a specific format on\n enumeration. For dicts, the argument is always a `{key, value}` tuple:\n\n iex> dict = %{a: 1, b: 2}\n iex> Enum.map(dict, fn {k, v} -> {k, v * 2} end)\n [a: 2, b: 4]\n\n Note that the functions in the `Enum` module are eager: they always start\n the enumeration of the given collection. The `Stream` module allows\n lazy enumeration of collections and provides infinite streams.\n\n Since the majority of the functions in `Enum` enumerate the whole\n collection and return a list as result, infinite streams need to\n be carefully used with such functions, as they can potentially run\n forever. For example:\n\n Enum.each Stream.cycle([1,2,3]), &IO.puts(&1)\n\n \"\"\"\n\n @compile :inline_list_funcs\n\n @type t :: Enumerable.t\n @type element :: any\n @type index :: non_neg_integer\n @type default :: any\n\n # Require Stream.Reducers and its callbacks\n require Stream.Reducers, as: R\n\n defmacrop cont(_, entry, acc) do\n quote do: {:cont, [unquote(entry)|unquote(acc)]}\n end\n\n defmacrop acc(h, n, _) do\n quote do: {unquote(h), unquote(n)}\n end\n\n defmacrop cont_with_acc(f, entry, h, n, _) do\n quote do\n {:cont, {[unquote(entry)|unquote(h)], unquote(n)}}\n end\n end\n\n @doc \"\"\"\n Invokes the given `fun` for each item in the `collection` and returns `false`\n if at least one invocation returns `false`. Otherwise returns `true`.\n\n ## Examples\n\n iex> Enum.all?([2, 4, 6], fn(x) -> rem(x, 2) == 0 end)\n true\n\n iex> Enum.all?([2, 3, 4], fn(x) -> rem(x, 2) == 0 end)\n false\n\n If no function is given, it defaults to checking if\n all items in the collection evaluate to `true`.\n\n iex> Enum.all?([1, 2, 3])\n true\n\n iex> Enum.all?([1, nil, 3])\n false\n\n \"\"\"\n @spec all?(t) :: boolean\n @spec all?(t, (element -> as_boolean(term))) :: boolean\n\n def all?(collection, fun \\\\ fn(x) -> x end)\n\n def all?(collection, fun) when is_list(collection) do\n do_all?(collection, fun)\n end\n\n def all?(collection, fun) do\n Enumerable.reduce(collection, {:cont, true}, fn(entry, _) ->\n if fun.(entry), do: {:cont, true}, else: {:halt, false}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Invokes the given `fun` for each item in the `collection` and returns `true` if\n at least one invocation returns `true`. Returns `false` otherwise.\n\n ## Examples\n\n iex> Enum.any?([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n false\n\n iex> Enum.any?([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n true\n\n If no function is given, it defaults to checking if\n at least one item in the collection evaluates to `true`.\n\n iex> Enum.any?([false, false, false])\n false\n\n iex> Enum.any?([false, true, false])\n true\n\n \"\"\"\n @spec any?(t) :: boolean\n @spec any?(t, (element -> as_boolean(term))) :: boolean\n\n def any?(collection, fun \\\\ fn(x) -> x end)\n\n def any?(collection, fun) when is_list(collection) do\n do_any?(collection, fun)\n end\n\n def any?(collection, fun) do\n Enumerable.reduce(collection, {:cont, false}, fn(entry, _) ->\n if fun.(entry), do: {:halt, true}, else: {:cont, false}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Finds the element at the given index (zero-based).\n\n Returns `default` if index is out of bounds.\n\n Note this operation takes linear time. In order to access\n the element at index `n`, it will need to traverse `n`\n previous elements.\n\n ## Examples\n\n iex> Enum.at([2, 4, 6], 0)\n 2\n\n iex> Enum.at([2, 4, 6], 2)\n 6\n\n iex> Enum.at([2, 4, 6], 4)\n nil\n\n iex> Enum.at([2, 4, 6], 4, :none)\n :none\n\n \"\"\"\n @spec at(t, integer, default) :: element | default\n def at(collection, n, default \\\\ nil) do\n case fetch(collection, n) do\n {:ok, h} -> h\n :error -> default\n end\n end\n\n @doc \"\"\"\n Shortcut to `chunk(coll, n, n)`.\n \"\"\"\n @spec chunk(t, non_neg_integer) :: [list]\n def chunk(coll, n), do: chunk(coll, n, n, nil)\n\n @doc \"\"\"\n Returns a collection of lists containing `n` items each, where\n each new chunk starts `step` elements into the collection.\n\n `step` is optional and, if not passed, defaults to `n`, i.e.\n chunks do not overlap. If the final chunk does not have `n`\n elements to fill the chunk, elements are taken as necessary\n from `pad` if it was passed. If `pad` is passed and does not\n have enough elements to fill the chunk, then the chunk is\n returned anyway with less than `n` elements. If `pad` is not\n passed at all or is `nil`, then the partial chunk is discarded\n from the result.\n\n ## Examples\n\n iex> Enum.chunk([1, 2, 3, 4, 5, 6], 2)\n [[1, 2], [3, 4], [5, 6]]\n\n iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 2)\n [[1, 2, 3], [3, 4, 5]]\n\n iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 2, [7])\n [[1, 2, 3], [3, 4, 5], [5, 6, 7]]\n\n iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 3, [])\n [[1, 2, 3], [4, 5, 6]]\n\n \"\"\"\n @spec chunk(t, non_neg_integer, non_neg_integer, t | nil) :: [list]\n def chunk(coll, n, step, pad \\\\ nil) when n > 0 and step > 0 do\n limit = :erlang.max(n, step)\n\n {_, {acc, {buffer, i}}} =\n Enumerable.reduce(coll, {:cont, {[], {[], 0}}}, R.chunk(n, step, limit))\n\n if nil?(pad) || i == 0 do\n :lists.reverse(acc)\n else\n buffer = :lists.reverse(buffer) ++ take(pad, n - i)\n :lists.reverse([buffer|acc])\n end\n end\n\n @doc \"\"\"\n Splits `coll` on every element for which `fun` returns a new value.\n\n ## Examples\n\n iex> Enum.chunk_by([1, 2, 2, 3, 4, 4, 6, 7, 7], &(rem(&1, 2) == 1))\n [[1], [2, 2], [3], [4, 4, 6], [7, 7]]\n\n \"\"\"\n @spec chunk_by(t, (element -> any)) :: [list]\n def chunk_by(coll, fun) do\n {_, {acc, res}} =\n Enumerable.reduce(coll, {:cont, {[], nil}}, R.chunk_by(fun))\n\n case res do\n {buffer, _} ->\n :lists.reverse([:lists.reverse(buffer) | acc])\n nil ->\n []\n end\n end\n\n @doc \"\"\"\n Given an enumerable of enumerables, concatenate the enumerables into a single list.\n\n ## Examples\n\n iex> Enum.concat([1..3, 4..6, 7..9])\n [1,2,3,4,5,6,7,8,9]\n\n iex> Enum.concat([[1, [2], 3], [4], [5, 6]])\n [1,[2],3,4,5,6]\n\n \"\"\"\n @spec concat(t) :: t\n def concat(enumerables) do\n do_concat(enumerables)\n end\n\n @doc \"\"\"\n Concatenates the enumerable on the right with the enumerable on the left.\n\n This function produces the same result as the `Kernel.++\/2` operator for lists.\n\n ## Examples\n\n iex> Enum.concat(1..3, 4..6)\n [1,2,3,4,5,6]\n\n iex> Enum.concat([1, 2, 3], [4, 5, 6])\n [1,2,3,4,5,6]\n\n \"\"\"\n @spec concat(t, t) :: t\n def concat(left, right) when is_list(left) and is_list(right) do\n left ++ right\n end\n\n def concat(left, right) do\n do_concat([left, right])\n end\n\n defp do_concat(enumerable) do\n fun = &[&1|&2]\n reduce(enumerable, [], &reduce(&1, &2, fun)) |> :lists.reverse\n end\n\n @doc \"\"\"\n Returns the collection's size.\n\n ## Examples\n\n iex> Enum.count([1, 2, 3])\n 3\n\n \"\"\"\n @spec count(t) :: non_neg_integer\n def count(collection) when is_list(collection) do\n :erlang.length(collection)\n end\n\n def count(collection) do\n case Enumerable.count(collection) do\n {:ok, value} when is_integer(value) ->\n value\n {:error, module} ->\n module.reduce(collection, {:cont, 0}, fn\n _, acc -> {:cont, acc + 1}\n end) |> elem(1)\n end\n end\n\n @doc \"\"\"\n Returns the count of items in the collection for which\n `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.count([1, 2, 3, 4, 5], fn(x) -> rem(x, 2) == 0 end)\n 2\n\n \"\"\"\n @spec count(t, (element -> as_boolean(term))) :: non_neg_integer\n def count(collection, fun) do\n Enumerable.reduce(collection, {:cont, 0}, fn(entry, acc) ->\n {:cont, if(fun.(entry), do: acc + 1, else: acc)}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Drops the first `count` items from `collection`.\n\n If a negative value `count` is given, the last `count`\n values will be dropped. The collection is enumerated\n once to retrieve the proper index and the remaining\n calculation is performed from the end.\n\n ## Examples\n\n iex> Enum.drop([1, 2, 3], 2)\n [3]\n\n iex> Enum.drop([1, 2, 3], 10)\n []\n\n iex> Enum.drop([1, 2, 3], 0)\n [1,2,3]\n\n iex> Enum.drop([1, 2, 3], -1)\n [1,2]\n\n \"\"\"\n @spec drop(t, integer) :: list\n def drop(collection, count) when is_list(collection) and count >= 0 do\n do_drop(collection, count)\n end\n\n def drop(collection, count) when count >= 0 do\n res =\n reduce(collection, count, fn\n x, acc when is_list(acc) -> [x|acc]\n x, 0 -> [x]\n _, acc when acc > 0 -> acc - 1\n end)\n if is_list(res), do: :lists.reverse(res), else: []\n end\n\n def drop(collection, count) when count < 0 do\n do_drop(reverse(collection), abs(count)) |> :lists.reverse\n end\n\n @doc \"\"\"\n Drops items at the beginning of `collection` while `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.drop_while([1, 2, 3, 4, 5], fn(x) -> x < 3 end)\n [3,4,5]\n\n \"\"\"\n @spec drop_while(t, (element -> as_boolean(term))) :: list\n def drop_while(collection, fun) when is_list(collection) do\n do_drop_while(collection, fun)\n end\n\n def drop_while(collection, fun) do\n {_, {res, _}} =\n Enumerable.reduce(collection, {:cont, {[], true}}, R.drop_while(fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Invokes the given `fun` for each item in the `collection`.\n Returns `:ok`.\n\n ## Examples\n\n Enum.each([\"some\", \"example\"], fn(x) -> IO.puts x end)\n \"some\"\n \"example\"\n #=> :ok\n\n \"\"\"\n @spec each(t, (element -> any)) :: :ok\n def each(collection, fun) when is_list(collection) do\n :lists.foreach(fun, collection)\n :ok\n end\n\n def each(collection, fun) do\n reduce(collection, nil, fn(entry, _) ->\n fun.(entry)\n nil\n end)\n :ok\n end\n\n @doc \"\"\"\n Returns `true` if the collection is empty, otherwise `false`.\n\n ## Examples\n\n iex> Enum.empty?([])\n true\n\n iex> Enum.empty?([1, 2, 3])\n false\n\n \"\"\"\n @spec empty?(t) :: boolean\n def empty?(collection) when is_list(collection) do\n collection == []\n end\n\n def empty?(collection) do\n Enumerable.reduce(collection, {:cont, true}, fn(_, _) -> {:halt, false} end) |> elem(1)\n end\n\n @doc \"\"\"\n Finds the element at the given index (zero-based).\n\n Returns `{:ok, element}` if found, otherwise `:error`.\n\n A negative index can be passed, which means the collection is\n enumerated once and the index is counted from the end (i.e.\n `-1` fetches the last element).\n\n Note this operation takes linear time. In order to access\n the element at index `n`, it will need to traverse `n`\n previous elements.\n\n ## Examples\n\n iex> Enum.fetch([2, 4, 6], 0)\n {:ok, 2}\n\n iex> Enum.fetch([2, 4, 6], 2)\n {:ok, 6}\n\n iex> Enum.fetch([2, 4, 6], 4)\n :error\n\n \"\"\"\n @spec fetch(t, integer) :: {:ok, element} | :error\n def fetch(collection, n) when is_list(collection) and n >= 0 do\n do_fetch(collection, n)\n end\n\n def fetch(collection, n) when n >= 0 do\n res =\n Enumerable.reduce(collection, {:cont, 0}, fn(entry, acc) ->\n if acc == n do\n {:halt, entry}\n else\n {:cont, acc + 1}\n end\n end)\n\n case res do\n {:halted, entry} -> {:ok, entry}\n {:done, _} -> :error\n end\n end\n\n def fetch(collection, n) when n < 0 do\n do_fetch(reverse(collection), abs(n + 1))\n end\n\n @doc \"\"\"\n Finds the element at the given index (zero-based).\n\n Raises `OutOfBoundsError` if the given position\n is outside the range of the collection.\n\n Note this operation takes linear time. In order to access\n the element at index `n`, it will need to traverse `n`\n previous elements.\n\n ## Examples\n\n iex> Enum.fetch!([2, 4, 6], 0)\n 2\n\n iex> Enum.fetch!([2, 4, 6], 2)\n 6\n\n iex> Enum.fetch!([2, 4, 6], 4)\n ** (Enum.OutOfBoundsError) out of bounds error\n\n \"\"\"\n @spec fetch!(t, integer) :: element | no_return\n def fetch!(collection, n) do\n case fetch(collection, n) do\n {:ok, h} -> h\n :error -> raise Enum.OutOfBoundsError\n end\n end\n\n @doc \"\"\"\n Filters the collection, i.e. returns only those elements\n for which `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.filter([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)\n [2]\n\n \"\"\"\n @spec filter(t, (element -> as_boolean(term))) :: list\n def filter(collection, fun) when is_list(collection) do\n for item <- collection, fun.(item), do: item\n end\n\n def filter(collection, fun) do\n Enumerable.reduce(collection, {:cont, []}, R.filter(fun))\n |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Filters the collection and maps its values in one pass.\n\n ## Examples\n\n iex> Enum.filter_map([1, 2, 3], fn(x) -> rem(x, 2) == 0 end, &(&1 * 2))\n [4]\n\n \"\"\"\n @spec filter_map(t, (element -> as_boolean(term)), (element -> element)) :: list\n def filter_map(collection, filter, mapper) when is_list(collection) do\n for item <- collection, filter.(item), do: mapper.(item)\n end\n\n def filter_map(collection, filter, mapper) do\n Enumerable.reduce(collection, {:cont, []}, R.filter_map(filter, mapper))\n |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Returns the first item for which `fun` returns a truthy value. If no such\n item is found, returns `ifnone`.\n\n ## Examples\n\n iex> Enum.find([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n nil\n\n iex> Enum.find([2, 4, 6], 0, fn(x) -> rem(x, 2) == 1 end)\n 0\n\n iex> Enum.find([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n 3\n\n \"\"\"\n @spec find(t, default, (element -> any)) :: element | default\n def find(collection, ifnone \\\\ nil, fun)\n\n def find(collection, ifnone, fun) when is_list(collection) do\n do_find(collection, ifnone, fun)\n end\n\n def find(collection, ifnone, fun) do\n Enumerable.reduce(collection, {:cont, ifnone}, fn(entry, ifnone) ->\n if fun.(entry), do: {:halt, entry}, else: {:cont, ifnone}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Similar to `find\/3`, but returns the value of the function\n invocation instead of the element itself.\n\n ## Examples\n\n iex> Enum.find_value([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n nil\n\n iex> Enum.find_value([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n true\n\n \"\"\"\n @spec find_value(t, any, (element -> any)) :: any | :nil\n def find_value(collection, ifnone \\\\ nil, fun)\n\n def find_value(collection, ifnone, fun) when is_list(collection) do\n do_find_value(collection, ifnone, fun)\n end\n\n def find_value(collection, ifnone, fun) do\n Enumerable.reduce(collection, {:cont, ifnone}, fn(entry, ifnone) ->\n fun_entry = fun.(entry)\n if fun_entry, do: {:halt, fun_entry}, else: {:cont, ifnone}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Similar to `find\/3`, but returns the index (zero-based)\n of the element instead of the element itself.\n\n ## Examples\n\n iex> Enum.find_index([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n nil\n\n iex> Enum.find_index([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n 1\n\n \"\"\"\n @spec find_index(t, (element -> any)) :: index | :nil\n def find_index(collection, fun) when is_list(collection) do\n do_find_index(collection, 0, fun)\n end\n\n def find_index(collection, fun) do\n res =\n Enumerable.reduce(collection, {:cont, 0}, fn(entry, acc) ->\n if fun.(entry), do: {:halt, acc}, else: {:cont, acc + 1}\n end)\n\n case res do\n {:halted, entry} -> entry\n {:done, _} -> nil\n end\n end\n\n @doc \"\"\"\n Returns a new collection appending the result of invoking `fun`\n on each corresponding item of `collection`.\n\n The given function should return an enumerable.\n\n ## Examples\n\n iex> Enum.flat_map([:a, :b, :c], fn(x) -> [x, x] end)\n [:a, :a, :b, :b, :c, :c]\n\n iex> Enum.flat_map([{1,3}, {4,6}], fn({x,y}) -> x..y end)\n [1, 2, 3, 4, 5, 6]\n\n \"\"\"\n @spec flat_map(t, (element -> t)) :: list\n def flat_map(collection, fun) do\n reduce(collection, [], fn(entry, acc) ->\n reduce(fun.(entry), acc, &[&1|&2])\n end) |> :lists.reverse\n end\n\n @doc \"\"\"\n Maps and reduces a collection, flattening the given results.\n\n It expects an accumulator and a function that receives each stream item\n and an accumulator, and must return a tuple containing a new stream\n (often a list) with the new accumulator or a tuple with `:halt` as first\n element and the accumulator as second.\n\n ## Examples\n\n iex> enum = 1..100\n iex> n = 3\n iex> Enum.flat_map_reduce(enum, 0, fn i, acc ->\n ...> if acc < n, do: {[i], acc + 1}, else: {:halt, acc}\n ...> end)\n {[1,2,3], 3}\n\n \"\"\"\n @spec flat_map_reduce(t, acc, fun) :: {[any], any} when\n fun: (element, acc -> {t, acc} | {:halt, acc}),\n acc: any\n def flat_map_reduce(collection, acc, fun) do\n {_, {list, acc}} =\n Enumerable.reduce(collection, {:cont, {[], acc}}, fn(entry, {list, acc}) ->\n case fun.(entry, acc) do\n {:halt, acc} ->\n {:halt, {list, acc}}\n {entries, acc} ->\n {:cont, {reduce(entries, list, &[&1|&2]), acc}}\n end\n end)\n\n {:lists.reverse(list), acc}\n end\n\n @doc \"\"\"\n Intersperses `element` between each element of the enumeration.\n\n Complexity: O(n)\n\n ## Examples\n\n iex> Enum.intersperse([1, 2, 3], 0)\n [1, 0, 2, 0, 3]\n\n iex> Enum.intersperse([1], 0)\n [1]\n\n iex> Enum.intersperse([], 0)\n []\n\n \"\"\"\n @spec intersperse(t, element) :: list\n def intersperse(collection, element) do\n list =\n reduce(collection, [], fn(x, acc) ->\n [x, element | acc]\n end) |> :lists.reverse()\n\n case list do\n [] -> []\n [_|t] -> t # Head is a superfluous intersperser element\n end\n end\n\n @doc \"\"\"\n Inserts the given enumerable into a collectable.\n\n ## Examples\n\n iex> Enum.into([1, 2], [0])\n [0, 1, 2]\n\n iex> Enum.into([a: 1, b: 2], %{})\n %{a: 1, b: 2}\n\n \"\"\"\n @spec into(Enumerable.t, Collectable.t) :: Collectable.t\n def into(collection, list) when is_list(list) do\n list ++ to_list(collection)\n end\n\n def into(collection, %{} = map) when is_list(collection) and map_size(map) == 0 do\n :maps.from_list(collection)\n end\n\n def into(collection, collectable) do\n {initial, fun} = Collectable.into(collectable)\n into(collection, initial, fun, fn x, acc ->\n fun.(acc, {:cont, x})\n end)\n end\n\n @doc \"\"\"\n Inserts the given enumerable into a collectable\n according to the transformation function.\n\n ## Examples\n\n iex> Enum.into([2, 3], [3], fn x -> x * 3 end)\n [3, 6, 9]\n\n \"\"\"\n @spec into(Enumerable.t, Collectable.t, (term -> term)) :: Collectable.t\n\n def into(collection, list, transform) when is_list(list) and is_function(transform, 1) do\n list ++ map(collection, transform)\n end\n\n def into(collection, collectable, transform) when is_function(transform, 1) do\n {initial, fun} = Collectable.into(collectable)\n into(collection, initial, fun, fn x, acc ->\n fun.(acc, {:cont, transform.(x)})\n end)\n end\n\n defp into(collection, initial, fun, callback) do\n try do\n reduce(collection, initial, callback)\n catch\n kind, reason ->\n stacktrace = System.stacktrace\n fun.(initial, :halt)\n :erlang.raise(kind, reason, stacktrace)\n else\n acc -> fun.(acc, :done)\n end\n end\n\n @doc \"\"\"\n Joins the given `collection` according to `joiner`.\n `joiner` can be either a binary or a list and the\n result will be of the same type as `joiner`. If\n `joiner` is not passed at all, it defaults to an\n empty binary.\n\n All items in the collection must be convertible\n to a binary, otherwise an error is raised.\n\n ## Examples\n\n iex> Enum.join([1, 2, 3])\n \"123\"\n\n iex> Enum.join([1, 2, 3], \" = \")\n \"1 = 2 = 3\"\n\n \"\"\"\n @spec join(t, String.t) :: String.t\n def join(collection, joiner \\\\ \"\")\n\n def join(collection, joiner) when is_binary(joiner) do\n reduced = reduce(collection, :first, fn\n entry, :first -> enum_to_string(entry)\n entry, acc -> [acc, joiner|enum_to_string(entry)]\n end)\n if reduced == :first do\n \"\"\n else\n IO.iodata_to_binary reduced\n end\n end\n\n @doc \"\"\"\n Returns a new collection, where each item is the result\n of invoking `fun` on each corresponding item of `collection`.\n\n For dicts, the function expects a key-value tuple.\n\n ## Examples\n\n iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end)\n [2, 4, 6]\n\n iex> Enum.map([a: 1, b: 2], fn({k, v}) -> {k, -v} end)\n [a: -1, b: -2]\n\n \"\"\"\n @spec map(t, (element -> any)) :: list\n def map(collection, fun) when is_list(collection) do\n for item <- collection, do: fun.(item)\n end\n\n def map(collection, fun) do\n Enumerable.reduce(collection, {:cont, []}, R.map(fun)) |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Maps and joins the given `collection` in one pass.\n `joiner` can be either a binary or a list and the\n result will be of the same type as `joiner`. If\n `joiner` is not passed at all, it defaults to an\n empty binary.\n\n All items in the collection must be convertible\n to a binary, otherwise an error is raised.\n\n ## Examples\n\n iex> Enum.map_join([1, 2, 3], &(&1 * 2))\n \"246\"\n\n iex> Enum.map_join([1, 2, 3], \" = \", &(&1 * 2))\n \"2 = 4 = 6\"\n\n \"\"\"\n @spec map_join(t, String.t, (element -> any)) :: String.t\n def map_join(collection, joiner \\\\ \"\", mapper)\n\n def map_join(collection, joiner, mapper) when is_binary(joiner) do\n reduced = reduce(collection, :first, fn\n entry, :first -> enum_to_string(mapper.(entry))\n entry, acc -> [acc, joiner|enum_to_string(mapper.(entry))]\n end)\n\n if reduced == :first do\n \"\"\n else\n IO.iodata_to_binary reduced\n end\n end\n\n @doc \"\"\"\n Invokes the given `fun` for each item in the `collection`\n while also keeping an accumulator. Returns a tuple where\n the first element is the mapped collection and the second\n one is the final accumulator.\n\n For dicts, the first tuple element must be a `{key, value}`\n tuple.\n\n ## Examples\n\n iex> Enum.map_reduce([1, 2, 3], 0, fn(x, acc) -> {x * 2, x + acc} end)\n {[2, 4, 6], 6}\n\n \"\"\"\n @spec map_reduce(t, any, (element, any -> any)) :: any\n def map_reduce(collection, acc, fun) when is_list(collection) do\n :lists.mapfoldl(fun, acc, collection)\n end\n\n def map_reduce(collection, acc, fun) do\n {list, acc} = reduce(collection, {[], acc}, fn(entry, {list, acc}) ->\n {new_entry, acc} = fun.(entry, acc)\n {[new_entry|list], acc}\n end)\n {:lists.reverse(list), acc}\n end\n\n @doc \"\"\"\n Returns the maximum value.\n Raises `EmptyError` if the collection is empty.\n\n ## Examples\n\n iex> Enum.max([1, 2, 3])\n 3\n\n \"\"\"\n @spec max(t) :: element | no_return\n def max(collection) do\n reduce(collection, &Kernel.max(&1, &2))\n end\n\n @doc \"\"\"\n Returns the maximum value as calculated by the given function.\n Raises `EmptyError` if the collection is empty.\n\n ## Examples\n\n iex> Enum.max_by([\"a\", \"aa\", \"aaa\"], fn(x) -> String.length(x) end)\n \"aaa\"\n\n \"\"\"\n @spec max_by(t, (element -> any)) :: element | no_return\n def max_by([h|t], fun) do\n reduce(t, {h, fun.(h)}, fn(entry, {_, fun_max} = old) ->\n fun_entry = fun.(entry)\n if(fun_entry > fun_max, do: {entry, fun_entry}, else: old)\n end) |> elem(0)\n end\n\n def max_by([], _fun) do\n raise Enum.EmptyError\n end\n\n def max_by(collection, fun) do\n result =\n reduce(collection, :first, fn\n entry, {_, fun_max} = old ->\n fun_entry = fun.(entry)\n if(fun_entry > fun_max, do: {entry, fun_entry}, else: old)\n entry, :first ->\n {entry, fun.(entry)}\n end)\n\n case result do\n :first -> raise Enum.EmptyError\n {entry, _} -> entry\n end\n end\n\n @doc \"\"\"\n Checks if `value` exists within the `collection`.\n\n Membership is tested with the match (`===`) operator, although\n enumerables like ranges may include floats inside the given\n range.\n\n ## Examples\n\n iex> Enum.member?(1..10, 5)\n true\n\n iex> Enum.member?([:a, :b, :c], :d)\n false\n\n \"\"\"\n @spec member?(t, element) :: boolean\n def member?(collection, value) when is_list(collection) do\n :lists.member(value, collection)\n end\n\n def member?(collection, value) do\n case Enumerable.member?(collection, value) do\n {:ok, value} when is_boolean(value) ->\n value\n {:error, module} ->\n module.reduce(collection, {:cont, false}, fn\n v, _ when v === value -> {:halt, true}\n _, _ -> {:cont, false}\n end) |> elem(1)\n end\n end\n\n @doc \"\"\"\n Returns the minimum value.\n Raises `EmptyError` if the collection is empty.\n\n ## Examples\n\n iex> Enum.min([1, 2, 3])\n 1\n\n \"\"\"\n @spec min(t) :: element | no_return\n def min(collection) do\n reduce(collection, &Kernel.min(&1, &2))\n end\n\n @doc \"\"\"\n Returns the minimum value as calculated by the given function.\n Raises `EmptyError` if the collection is empty.\n\n ## Examples\n\n iex> Enum.min_by([\"a\", \"aa\", \"aaa\"], fn(x) -> String.length(x) end)\n \"a\"\n\n \"\"\"\n @spec min_by(t, (element -> any)) :: element | no_return\n def min_by([h|t], fun) do\n reduce(t, {h, fun.(h)}, fn(entry, {_, fun_min} = old) ->\n fun_entry = fun.(entry)\n if(fun_entry < fun_min, do: {entry, fun_entry}, else: old)\n end) |> elem(0)\n end\n\n def min_by([], _fun) do\n raise Enum.EmptyError\n end\n\n def min_by(collection, fun) do\n result =\n reduce(collection, :first, fn\n entry, {_, fun_min} = old ->\n fun_entry = fun.(entry)\n if(fun_entry < fun_min, do: {entry, fun_entry}, else: old)\n entry, :first ->\n {entry, fun.(entry)}\n end)\n\n case result do\n :first -> raise Enum.EmptyError\n {entry, _} -> entry\n end\n end\n\n @doc \"\"\"\n Returns the sum of all values.\n\n Raises `ArithmeticError` if collection contains a non-numeric value.\n\n ## Examples\n\n iex> Enum.sum([1, 2, 3])\n 6\n\n \"\"\"\n @spec sum(t) :: number\n def sum(collection) do\n reduce(collection, 0, &+\/2)\n end\n\n @doc \"\"\"\n Partitions `collection` into two collections, where the first one contains elements\n for which `fun` returns a truthy value, and the second one -- for which `fun`\n returns `false` or `nil`.\n\n ## Examples\n\n iex> Enum.partition([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)\n {[2], [1,3]}\n\n \"\"\"\n @spec partition(t, (element -> any)) :: {list, list}\n def partition(collection, fun) do\n {acc1, acc2} =\n reduce(collection, {[], []}, fn(entry, {acc1, acc2}) ->\n if fun.(entry) do\n {[entry|acc1], acc2}\n else\n {acc1, [entry|acc2]}\n end\n end)\n\n {:lists.reverse(acc1), :lists.reverse(acc2)}\n end\n\n @doc \"\"\"\n Splits `collection` into groups based on `fun`.\n\n The result is a dict (by default a map) where each key is\n a group and each value is a list of elements from `collection`\n for which `fun` returned that group. Ordering is not necessarily\n preserved.\n\n ## Examples\n\n iex> Enum.group_by(~w{ant buffalo cat dingo}, &String.length\/1)\n %{3 => [\"cat\", \"ant\"], 7 => [\"buffalo\"], 5 => [\"dingo\"]}\n\n \"\"\"\n @spec group_by(t, dict, (element -> any)) :: dict when dict: Dict.t\n def group_by(collection, dict \\\\ %{}, fun) do\n reduce(collection, dict, fn(entry, categories) ->\n Dict.update(categories, fun.(entry), [entry], &[entry|&1])\n end)\n end\n\n @doc \"\"\"\n Invokes `fun` for each element in the collection passing that element and the\n accumulator `acc` as arguments. `fun`'s return value is stored in `acc`.\n Returns the accumulator.\n\n ## Examples\n\n iex> Enum.reduce([1, 2, 3], 0, fn(x, acc) -> x + acc end)\n 6\n\n \"\"\"\n @spec reduce(t, any, (element, any -> any)) :: any\n def reduce(collection, acc, fun) when is_list(collection) do\n :lists.foldl(fun, acc, collection)\n end\n\n def reduce(collection, acc, fun) do\n Enumerable.reduce(collection, {:cont, acc},\n fn x, acc -> {:cont, fun.(x, acc)} end) |> elem(1)\n end\n\n @doc \"\"\"\n Invokes `fun` for each element in the collection passing that element and the\n accumulator `acc` as arguments. `fun`'s return value is stored in `acc`.\n The first element of the collection is used as the initial value of `acc`.\n Returns the accumulator.\n\n ## Examples\n\n iex> Enum.reduce([1, 2, 3, 4], fn(x, acc) -> x * acc end)\n 24\n\n \"\"\"\n @spec reduce(t, (element, any -> any)) :: any\n def reduce([h|t], fun) do\n reduce(t, h, fun)\n end\n\n def reduce([], _fun) do\n raise Enum.EmptyError\n end\n\n def reduce(collection, fun) do\n result =\n Enumerable.reduce(collection, {:cont, :first}, fn\n x, :first ->\n {:cont, {:acc, x}}\n x, {:acc, acc} ->\n {:cont, {:acc, fun.(x, acc)}}\n end) |> elem(1)\n\n case result do\n :first -> raise Enum.EmptyError\n {:acc, acc} -> acc\n end\n end\n\n @doc \"\"\"\n Returns elements of collection for which `fun` returns `false`.\n\n ## Examples\n\n iex> Enum.reject([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)\n [1, 3]\n\n \"\"\"\n @spec reject(t, (element -> as_boolean(term))) :: list\n def reject(collection, fun) when is_list(collection) do\n for item <- collection, !fun.(item), do: item\n end\n\n def reject(collection, fun) do\n Enumerable.reduce(collection, {:cont, []}, R.reject(fun)) |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Reverses the collection.\n\n ## Examples\n\n iex> Enum.reverse([1, 2, 3])\n [3, 2, 1]\n\n \"\"\"\n @spec reverse(t) :: list\n def reverse(collection) when is_list(collection) do\n :lists.reverse(collection)\n end\n\n def reverse(collection) do\n reverse(collection, [])\n end\n\n @doc \"\"\"\n Reverses the collection and appends the tail.\n This is an optimization for\n `Enum.concat(Enum.reverse(collection), tail)`.\n\n ## Examples\n\n iex> Enum.reverse([1, 2, 3], [4, 5, 6])\n [3, 2, 1, 4, 5, 6]\n\n \"\"\"\n @spec reverse(t, t) :: list\n def reverse(collection, tail) when is_list(collection) and is_list(tail) do\n :lists.reverse(collection, tail)\n end\n\n def reverse(collection, tail) do\n reduce(collection, to_list(tail), fn(entry, acc) ->\n [entry|acc]\n end)\n end\n\n @doc \"\"\"\n Returns a random element of a collection.\n\n Notice that you need to explicitly call `:random.seed\/1` and\n set a seed value for the random algorithm. Otherwise, the\n default seed will be set which will always return the same\n result. For example, one could do the following to set a seed\n dynamically:\n\n :random.seed(:os.timestamp)\n\n The implementation is based on the\n [reservoir sampling](http:\/\/en.wikipedia.org\/wiki\/Reservoir_sampling#Relation_to_Fisher-Yates_shuffle)\n algorithm.\n It assumes that the sample being returned can fit into memory;\n the input collection doesn't have to - it is traversed just once.\n\n ## Examples\n\n iex> Enum.sample([1,2,3])\n 1\n iex> Enum.sample([1,2,3])\n 2\n\n \"\"\"\n @spec sample(t) :: element | nil\n def sample(collection) do\n sample(collection, 1) |> List.first\n end\n\n @doc \"\"\"\n Returns a random sublist of a collection.\n\n See `sample\/1` for notes on implementation and random seed.\n\n ## Examples\n\n iex> Enum.sample(1..10, 2)\n [1, 5]\n iex> Enum.sample(?a..?z, 5)\n 'tfesm'\n\n \"\"\"\n @spec sample(t, integer) :: list\n def sample(collection, count) when count > 0 do\n sample = List.duplicate(nil, count) |> List.to_tuple\n\n reducer = fn x, {i, sample} ->\n if i < count do\n j = random_index(i)\n swapped = sample |> elem(j)\n {i + 1, sample |> put_elem(i, swapped) |> put_elem(j, x)}\n else\n j = random_index(i)\n if j < count, do: sample = sample |> put_elem(j, x)\n {i + 1, sample}\n end\n end\n\n {n, sample} = reduce(collection, {0, sample}, reducer)\n sample |> Tuple.to_list |> Enum.take(Kernel.min(count, n))\n end\n\n def sample(_collection, 0), do: []\n\n @doc \"\"\"\n Applies the given function to each element in the collection,\n storing the result in a list and passing it as the accumulator\n for the next computation.\n\n ## Examples\n\n iex> Enum.scan(1..5, &(&1 + &2))\n [1,3,6,10,15]\n\n \"\"\"\n @spec scan(t, (element, any -> any)) :: list\n def scan(enum, fun) do\n {_, {res, _}} =\n Enumerable.reduce(enum, {:cont, {[], :first}}, R.scan_2(fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Applies the given function to each element in the collection,\n storing the result in a list and passing it as the accumulator\n for the next computation. Uses the given `acc` as the starting value.\n\n ## Examples\n\n iex> Enum.scan(1..5, 0, &(&1 + &2))\n [1,3,6,10,15]\n\n \"\"\"\n @spec scan(t, any, (element, any -> any)) :: list\n def scan(enum, acc, fun) do\n {_, {res, _}} =\n Enumerable.reduce(enum, {:cont, {[], acc}}, R.scan_3(fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Returns a list of collection elements shuffled.\n\n Notice that you need to explicitly call `:random.seed\/1` and\n set a seed value for the random algorithm. Otherwise, the\n default seed will be set which will always return the same\n result. For example, one could do the following to set a seed\n dynamically:\n\n :random.seed(:erlang.now)\n\n ## Examples\n\n iex> Enum.shuffle([1, 2, 3])\n [3, 2, 1]\n iex> Enum.shuffle([1, 2, 3])\n [3, 1, 2]\n\n \"\"\"\n @spec shuffle(t) :: list\n def shuffle(collection) do\n randomized = reduce(collection, [], fn x, acc ->\n [{:random.uniform, x}|acc]\n end)\n unwrap(:lists.keysort(1, randomized), [])\n end\n\n @doc \"\"\"\n Returns a subset list of the given collection. Drops elements\n until element position `start`, then takes `count` elements.\n \n If the count is greater than collection length, it returns as\n much as possible. If zero, then it returns `[]`.\n\n ## Examples\n\n iex> Enum.slice(1..100, 5, 10)\n [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n\n iex> Enum.slice(1..10, 5, 100)\n [6, 7, 8, 9, 10]\n\n iex> Enum.slice(1..10, 5, 0)\n []\n\n \"\"\"\n @spec slice(t, integer, non_neg_integer) :: list\n \n def slice(_coll, _start, 0), do: []\n\n def slice(coll, start, count) when start < 0 do\n {list, new_start} = enumerate_and_count(coll, start)\n if new_start >= 0 do\n slice(list, new_start, count)\n else\n []\n end\n end\n\n def slice(coll, start, count) when is_list(coll) and start >= 0 and count > 0 do\n do_slice(coll, start, count)\n end\n\n def slice(coll, start, count) when start >= 0 and count > 0 do\n {_, _, list} = Enumerable.reduce(coll, {:cont, {start, count, []}}, fn\n _entry, {start, count, _list} when start > 0 ->\n {:cont, {start-1, count, []}}\n entry, {start, count, list} when count > 1 ->\n {:cont, {start, count-1, [entry|list]}}\n entry, {start, count, list} ->\n {:halt, {start, count, [entry|list]}}\n end) |> elem(1)\n\n :lists.reverse(list)\n end\n\n @doc \"\"\"\n Returns a subset list of the given collection. Drops elements\n until element position `range.first`, then takes elements until element\n position `range.last` (inclusive).\n\n Positions are calculated by adding the number of items in the collection to\n negative positions (so position -3 in a collection with count 5 becomes\n position 2).\n\n The first position (after adding count to negative positions) must be smaller\n or equal to the last position.\n\n If the start of the range is not a valid offset for the given\n collection or if the range is in reverse order, returns `[]`.\n\n ## Examples\n\n iex> Enum.slice(1..100, 5..10)\n [6, 7, 8, 9, 10, 11]\n\n iex> Enum.slice(1..10, 5..20)\n [6, 7, 8, 9, 10]\n\n iex> Enum.slice(1..10, 11..20)\n []\n\n iex> Enum.slice(1..10, 6..5)\n []\n\n \"\"\"\n @spec slice(t, Range.t) :: list\n def slice(coll, first..last) when first >= 0 and last >= 0 do\n # Simple case, which works on infinite collections\n if last - first >= 0 do\n slice(coll, first, last - first + 1)\n else\n []\n end\n end\n\n def slice(coll, first..last) do\n {list, count} = enumerate_and_count(coll, 0)\n corr_first = if first >= 0, do: first, else: first + count\n corr_last = if last >= 0, do: last, else: last + count\n length = corr_last - corr_first + 1\n if corr_first >= 0 and length > 0 do\n slice(list, corr_first, length)\n else\n []\n end\n end\n\n @doc \"\"\"\n Sorts the collection according to Elixir's term ordering.\n\n Uses the merge sort algorithm.\n\n ## Examples\n\n iex> Enum.sort([3, 2, 1])\n [1, 2, 3]\n\n \"\"\"\n @spec sort(t) :: list\n def sort(collection) when is_list(collection) do\n :lists.sort(collection)\n end\n\n def sort(collection) do\n sort(collection, &(&1 <= &2))\n end\n\n @doc \"\"\"\n Sorts the collection by the given function.\n\n This function uses the merge sort algorithm. The given function\n must return false if the first argument is less than right one.\n\n ## Examples\n\n iex> Enum.sort([1, 2, 3], &(&1 > &2))\n [3, 2, 1]\n\n The sorting algorithm will be stable as long as the given function\n returns true for values considered equal:\n\n iex> Enum.sort [\"some\", \"kind\", \"of\", \"monster\"], &(byte_size(&1) <= byte_size(&2))\n [\"of\", \"some\", \"kind\", \"monster\"]\n\n If the function does not return true, the sorting is not stable and\n the order of equal terms may be shuffled:\n\n iex> Enum.sort [\"some\", \"kind\", \"of\", \"monster\"], &(byte_size(&1) < byte_size(&2))\n [\"of\", \"kind\", \"some\", \"monster\"]\n\n \"\"\"\n @spec sort(t, (element, element -> boolean)) :: list\n def sort(collection, fun) when is_list(collection) do\n :lists.sort(fun, collection)\n end\n\n def sort(collection, fun) do\n reduce(collection, [], &sort_reducer(&1, &2, fun)) |> sort_terminator(fun)\n end\n\n @doc \"\"\"\n Sorts the mapped results of the `collection` according to the `sorter` function.\n\n This function maps each element of the collection using the `mapper`\n function. The collection is then sorted by the mapped elements using the\n `sorter` function, which defaults to `<=\/2`\n\n `sort_by\/3` differs from `sort\/2` in that it only calculates the comparison\n value for each element in the collection once instead of once for each\n element in each comparison. If the same function is being called on both\n element, it's also more compact to use `sort_by\/3`.\n\n This technique is also known as a\n [Schwartzian Transform](https:\/\/en.wikipedia.org\/wiki\/Schwartzian_transform),\n or the Lisp decorate-sort-undecorate idiom as the `mapper` is decorating the\n original `collection`, then `sorter` is sorting the decorations, and finally\n the `collection` is being undecorated so only the original elements remain,\n but now in sorted order.\n\n ## Examples\n\n Using the default `sorter` of `<=\/2`:\n\n iex> Enum.sort_by [\"some\", \"kind\", \"of\", \"monster\"], &byte_size\/1\n [\"of\", \"some\", \"kind\", \"monster\"]\n\n Using a custom `sorter` to override the order:\n\n iex> Enum.sort_by [\"some\", \"kind\", \"of\", \"monster\"], &byte_size\/1, &>=\/2\n [\"monster\", \"some\", \"kind\", \"of\"]\n\n \"\"\"\n @spec sort_by(t, (element -> mapped_element), (mapped_element, mapped_element -> boolean)) :: list when mapped_element: element\n def sort_by(collection, mapper, sorter \\\\ &<=\/2) do\n collection \n |> map(&{&1, mapper.(&1)})\n |> sort(&sorter.(elem(&1, 1), elem(&2, 1)))\n |> map(&elem(&1, 0))\n end\n\n @doc \"\"\"\n Splits the enumerable into two collections, leaving `count`\n elements in the first one. If `count` is a negative number,\n it starts counting from the back to the beginning of the\n collection.\n\n Be aware that a negative `count` implies the collection\n will be enumerated twice: once to calculate the position, and\n a second time to do the actual splitting.\n\n ## Examples\n\n iex> Enum.split([1, 2, 3], 2)\n {[1,2], [3]}\n\n iex> Enum.split([1, 2, 3], 10)\n {[1,2,3], []}\n\n iex> Enum.split([1, 2, 3], 0)\n {[], [1,2,3]}\n\n iex> Enum.split([1, 2, 3], -1)\n {[1,2], [3]}\n\n iex> Enum.split([1, 2, 3], -5)\n {[], [1,2,3]}\n\n \"\"\"\n @spec split(t, integer) :: {list, list}\n def split(collection, count) when is_list(collection) and count >= 0 do\n do_split(collection, count, [])\n end\n\n def split(collection, count) when count >= 0 do\n {_, list1, list2} =\n reduce(collection, {count, [], []}, fn(entry, {counter, acc1, acc2}) ->\n if counter > 0 do\n {counter - 1, [entry|acc1], acc2}\n else\n {counter, acc1, [entry|acc2]}\n end\n end)\n\n {:lists.reverse(list1), :lists.reverse(list2)}\n end\n\n def split(collection, count) when count < 0 do\n do_split_reverse(reverse(collection), abs(count), [])\n end\n\n @doc \"\"\"\n Splits `collection` in two while `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.split_while([1, 2, 3, 4], fn(x) -> x < 3 end)\n {[1, 2], [3, 4]}\n\n \"\"\"\n @spec split_while(t, (element -> as_boolean(term))) :: {list, list}\n def split_while(collection, fun) when is_list(collection) do\n do_split_while(collection, fun, [])\n end\n\n def split_while(collection, fun) do\n {list1, list2} =\n reduce(collection, {[], []}, fn\n entry, {acc1, []} ->\n if(fun.(entry), do: {[entry|acc1], []}, else: {acc1, [entry]})\n entry, {acc1, acc2} ->\n {acc1, [entry|acc2]}\n end)\n\n {:lists.reverse(list1), :lists.reverse(list2)}\n end\n\n @doc \"\"\"\n Takes the first `count` items from the collection.\n\n If a negative `count` is given, the last `count` values will\n be taken. For such, the collection is fully enumerated keeping up\n to `2 * count` elements in memory. Once the end of the collection is\n reached, the last `count` elements are returned.\n\n ## Examples\n\n iex> Enum.take([1, 2, 3], 2)\n [1,2]\n\n iex> Enum.take([1, 2, 3], 10)\n [1,2,3]\n\n iex> Enum.take([1, 2, 3], 0)\n []\n\n iex> Enum.take([1, 2, 3], -1)\n [3]\n\n \"\"\"\n @spec take(t, integer) :: list\n\n def take(_collection, 0) do\n []\n end\n\n def take(collection, count) when is_list(collection) and count > 0 do\n do_take(collection, count)\n end\n\n def take(collection, count) when count > 0 do\n {_, {res, _}} =\n Enumerable.reduce(collection, {:cont, {[], count}}, fn(entry, {list, count}) ->\n if count > 1 do\n {:cont, {[entry|list], count - 1}}\n else\n {:halt, {[entry|list], count}}\n end\n end)\n :lists.reverse(res)\n end\n\n def take(collection, count) when count < 0 do\n Stream.take(collection, count).({:cont, []}, &{:cont, [&1|&2]})\n |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Returns a collection of every `nth` item in the collection,\n starting with the first element.\n\n ## Examples\n\n iex> Enum.take_every(1..10, 2)\n [1, 3, 5, 7, 9]\n\n \"\"\"\n @spec take_every(t, integer) :: list\n def take_every(_collection, 0), do: []\n def take_every(collection, nth) do\n {_, {res, _}} =\n Enumerable.reduce(collection, {:cont, {[], :first}}, R.take_every(nth))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Takes the items at the beginning of `collection` while `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.take_while([1, 2, 3], fn(x) -> x < 3 end)\n [1, 2]\n\n \"\"\"\n @spec take_while(t, (element -> as_boolean(term))) :: list\n def take_while(collection, fun) when is_list(collection) do\n do_take_while(collection, fun)\n end\n\n def take_while(collection, fun) do\n Enumerable.reduce(collection, {:cont, []}, R.take_while(fun))\n |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Convert `collection` to a list.\n\n ## Examples\n\n iex> Enum.to_list(1 .. 3)\n [1, 2, 3]\n\n \"\"\"\n @spec to_list(t) :: [term]\n def to_list(collection) when is_list(collection) do\n collection\n end\n\n def to_list(collection) do\n reverse(collection) |> :lists.reverse\n end\n\n\n @doc \"\"\"\n Traverses the given enumerable keeping its shape.\n\n It also expects the enumerable to implement the `Collectable` protocol.\n\n ## Examples\n\n iex> Enum.traverse(%{a: 1, b: 2}, fn {k, v} -> {k, v * 2} end)\n %{a: 2, b: 4}\n\n \"\"\"\n @spec traverse(Enumerable.t, (term -> term)) :: Collectable.t\n def traverse(collection, transform) when is_list(collection) do\n :lists.map(transform, collection)\n end\n\n def traverse(collection, transform) do\n into(collection, Collectable.empty(collection), transform)\n end\n\n @doc \"\"\"\n Enumerates the collection, removing all duplicated items.\n\n ## Examples\n\n iex> Enum.uniq([1, 2, 3, 2, 1])\n [1, 2, 3]\n\n iex> Enum.uniq([{1, :x}, {2, :y}, {1, :z}], fn {x, _} -> x end)\n [{1,:x}, {2,:y}]\n\n \"\"\"\n @spec uniq(t) :: list\n @spec uniq(t, (element -> term)) :: list\n def uniq(collection, fun \\\\ fn x -> x end)\n\n def uniq(collection, fun) when is_list(collection) do\n do_uniq(collection, [], fun)\n end\n\n def uniq(collection, fun) do\n {_, {list, _}} =\n Enumerable.reduce(collection, {:cont, {[], []}}, R.uniq(fun))\n :lists.reverse(list)\n end\n\n @doc \"\"\"\n Zips corresponding elements from two collections into one list\n of tuples.\n\n The zipping finishes as soon as any enumerable completes.\n\n ## Examples\n\n iex> Enum.zip([1, 2, 3], [:a, :b, :c])\n [{1,:a},{2,:b},{3,:c}]\n\n iex> Enum.zip([1,2,3,4,5], [:a, :b, :c])\n [{1,:a},{2,:b},{3,:c}]\n\n \"\"\"\n @spec zip(t, t) :: [{any, any}]\n def zip(coll1, coll2) when is_list(coll1) and is_list(coll2) do\n do_zip(coll1, coll2)\n end\n\n def zip(coll1, coll2) do\n Stream.zip(coll1, coll2).({:cont, []}, &{:cont, [&1|&2]}) |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Returns the collection with each element wrapped in a tuple\n alongside its index.\n\n ## Examples\n\n iex> Enum.with_index [1,2,3]\n [{1,0},{2,1},{3,2}]\n\n \"\"\"\n @spec with_index(t) :: list({element, non_neg_integer})\n def with_index(collection) do\n map_reduce(collection, 0, fn x, acc ->\n {{x, acc}, acc + 1}\n end) |> elem(0)\n end\n\n ## Helpers\n\n @compile {:inline, enum_to_string: 1}\n\n defp enumerate_and_count(collection, count) when is_list(collection) do\n {collection, length(collection) - abs(count)}\n end\n\n defp enumerate_and_count(collection, count) do\n map_reduce(collection, -abs(count), fn(x, acc) -> {x, acc + 1} end)\n end\n\n defp enum_to_string(entry) when is_binary(entry), do: entry\n defp enum_to_string(entry), do: String.Chars.to_string(entry)\n\n defp random_index(n) do\n :random.uniform(n + 1) - 1\n end\n\n ## Implementations\n\n ## all?\n\n defp do_all?([h|t], fun) do\n if fun.(h) do\n do_all?(t, fun)\n else\n false\n end\n end\n\n defp do_all?([], _) do\n true\n end\n\n ## any?\n\n defp do_any?([h|t], fun) do\n if fun.(h) do\n true\n else\n do_any?(t, fun)\n end\n end\n\n defp do_any?([], _) do\n false\n end\n\n ## fetch\n\n defp do_fetch([h|_], 0), do: {:ok, h}\n defp do_fetch([_|t], n), do: do_fetch(t, n - 1)\n defp do_fetch([], _), do: :error\n\n ## drop\n\n defp do_drop([_|t], counter) when counter > 0 do\n do_drop(t, counter - 1)\n end\n\n defp do_drop(list, 0) do\n list\n end\n\n defp do_drop([], _) do\n []\n end\n\n ## drop_while\n\n defp do_drop_while([h|t], fun) do\n if fun.(h) do\n do_drop_while(t, fun)\n else\n [h|t]\n end\n end\n\n defp do_drop_while([], _) do\n []\n end\n\n ## find\n\n defp do_find([h|t], ifnone, fun) do\n if fun.(h) do\n h\n else\n do_find(t, ifnone, fun)\n end\n end\n\n defp do_find([], ifnone, _) do\n ifnone\n end\n\n ## find_index\n\n defp do_find_index([h|t], counter, fun) do\n if fun.(h) do\n counter\n else\n do_find_index(t, counter + 1, fun)\n end\n end\n\n defp do_find_index([], _, _) do\n nil\n end\n\n ## find_value\n\n defp do_find_value([h|t], ifnone, fun) do\n fun.(h) || do_find_value(t, ifnone, fun)\n end\n\n defp do_find_value([], ifnone, _) do\n ifnone\n end\n\n ## shuffle\n\n defp unwrap([{_, h} | collection], t) do\n unwrap(collection, [h|t])\n end\n\n defp unwrap([], t), do: t\n\n ## sort\n\n defp sort_reducer(entry, {:split, y, x, r, rs, bool}, fun) do\n cond do\n fun.(y, entry) == bool ->\n {:split, entry, y, [x|r], rs, bool}\n fun.(x, entry) == bool ->\n {:split, y, entry, [x|r], rs, bool}\n r == [] ->\n {:split, y, x, [entry], rs, bool}\n true ->\n {:pivot, y, x, r, rs, entry, bool}\n end\n end\n\n defp sort_reducer(entry, {:pivot, y, x, r, rs, s, bool}, fun) do\n cond do\n fun.(y, entry) == bool ->\n {:pivot, entry, y, [x | r], rs, s, bool}\n fun.(x, entry) == bool ->\n {:pivot, y, entry, [x | r], rs, s, bool}\n fun.(s, entry) == bool ->\n {:split, entry, s, [], [[y, x | r] | rs], bool}\n true ->\n {:split, s, entry, [], [[y, x | r] | rs], bool}\n end\n end\n\n defp sort_reducer(entry, [x], fun) do\n {:split, entry, x, [], [], fun.(x, entry)}\n end\n\n defp sort_reducer(entry, acc, _fun) do\n [entry|acc]\n end\n\n defp sort_terminator({:split, y, x, r, rs, bool}, fun) do\n sort_merge([[y, x | r] | rs], fun, bool)\n end\n\n defp sort_terminator({:pivot, y, x, r, rs, s, bool}, fun) do\n sort_merge([[s], [y, x | r] | rs], fun, bool)\n end\n\n defp sort_terminator(acc, _fun) do\n acc\n end\n\n defp sort_merge(list, fun, true), do:\n reverse_sort_merge(list, [], fun, true)\n\n defp sort_merge(list, fun, false), do:\n sort_merge(list, [], fun, false)\n\n\n defp sort_merge([t1, [h2 | t2] | l], acc, fun, true), do:\n sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, false) | acc], fun, true)\n\n defp sort_merge([[h2 | t2], t1 | l], acc, fun, false), do:\n sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, false) | acc], fun, false)\n\n defp sort_merge([l], [], _fun, _bool), do: l\n\n defp sort_merge([l], acc, fun, bool), do:\n reverse_sort_merge([:lists.reverse(l, []) | acc], [], fun, bool)\n\n defp sort_merge([], acc, fun, bool), do:\n reverse_sort_merge(acc, [], fun, bool)\n\n\n defp reverse_sort_merge([[h2 | t2], t1 | l], acc, fun, true), do:\n reverse_sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, true) | acc], fun, true)\n\n defp reverse_sort_merge([t1, [h2 | t2] | l], acc, fun, false), do:\n reverse_sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, true) | acc], fun, false)\n\n defp reverse_sort_merge([l], acc, fun, bool), do:\n sort_merge([:lists.reverse(l, []) | acc], [], fun, bool)\n\n defp reverse_sort_merge([], acc, fun, bool), do:\n sort_merge(acc, [], fun, bool)\n\n\n defp sort_merge_1([h1 | t1], h2, t2, m, fun, bool) do\n if fun.(h1, h2) == bool do\n sort_merge_2(h1, t1, t2, [h2 | m], fun, bool)\n else\n sort_merge_1(t1, h2, t2, [h1 | m], fun, bool)\n end\n end\n\n defp sort_merge_1([], h2, t2, m, _fun, _bool), do:\n :lists.reverse(t2, [h2 | m])\n\n\n defp sort_merge_2(h1, t1, [h2 | t2], m, fun, bool) do\n if fun.(h1, h2) == bool do\n sort_merge_2(h1, t1, t2, [h2 | m], fun, bool)\n else\n sort_merge_1(t1, h2, t2, [h1 | m], fun, bool)\n end\n end\n\n defp sort_merge_2(h1, t1, [], m, _fun, _bool), do:\n :lists.reverse(t1, [h1 | m])\n\n ## split\n\n defp do_split([h|t], counter, acc) when counter > 0 do\n do_split(t, counter - 1, [h|acc])\n end\n\n defp do_split(list, 0, acc) do\n {:lists.reverse(acc), list}\n end\n\n defp do_split([], _, acc) do\n {:lists.reverse(acc), []}\n end\n\n defp do_split_reverse([h|t], counter, acc) when counter > 0 do\n do_split_reverse(t, counter - 1, [h|acc])\n end\n\n defp do_split_reverse(list, 0, acc) do\n {:lists.reverse(list), acc}\n end\n\n defp do_split_reverse([], _, acc) do\n {[], acc}\n end\n\n ## split_while\n\n defp do_split_while([h|t], fun, acc) do\n if fun.(h) do\n do_split_while(t, fun, [h|acc])\n else\n {:lists.reverse(acc), [h|t]}\n end\n end\n\n defp do_split_while([], _, acc) do\n {:lists.reverse(acc), []}\n end\n\n ## take\n\n defp do_take([h|t], counter) when counter > 0 do\n [h|do_take(t, counter - 1)]\n end\n\n defp do_take(_list, 0) do\n []\n end\n\n defp do_take([], _) do\n []\n end\n\n ## take_while\n\n defp do_take_while([h|t], fun) do\n if fun.(h) do\n [h|do_take_while(t, fun)]\n else\n []\n end\n end\n\n defp do_take_while([], _) do\n []\n end\n\n ## uniq\n\n defp do_uniq([h|t], acc, fun) do\n fun_h = fun.(h)\n case :lists.member(fun_h, acc) do\n true -> do_uniq(t, acc, fun)\n false -> [h|do_uniq(t, [fun_h|acc], fun)]\n end\n end\n\n defp do_uniq([], _acc, _fun) do\n []\n end\n\n ## zip\n\n defp do_zip([h1|next1], [h2|next2]) do\n [{h1, h2}|do_zip(next1, next2)]\n end\n\n defp do_zip(_, []), do: []\n defp do_zip([], _), do: []\n\n ## slice\n\n defp do_slice([], _start, _count) do\n []\n end\n\n defp do_slice(_list, _start, 0) do\n []\n end\n\n defp do_slice([h|t], 0, count) do\n [h|do_slice(t, 0, count-1)]\n end\n\n defp do_slice([_|t], start, count) do\n do_slice(t, start-1, count)\n end\nend\n\ndefimpl Enumerable, for: List do\n def reduce(_, {:halt, acc}, _fun), do: {:halted, acc}\n def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)}\n def reduce([], {:cont, acc}, _fun), do: {:done, acc}\n def reduce([h|t], {:cont, acc}, fun), do: reduce(t, fun.(h, acc), fun)\n\n def member?(_list, _value),\n do: {:error, __MODULE__}\n def count(_list),\n do: {:error, __MODULE__}\nend\n\ndefimpl Enumerable, for: Map do\n def reduce(map, acc, fun) do\n do_reduce(:maps.to_list(map), acc, fun)\n end\n\n defp do_reduce(_, {:halt, acc}, _fun), do: {:halted, acc}\n defp do_reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &do_reduce(list, &1, fun)}\n defp do_reduce([], {:cont, acc}, _fun), do: {:done, acc}\n defp do_reduce([h|t], {:cont, acc}, fun), do: do_reduce(t, fun.(h, acc), fun)\n\n def member?(map, {key, value}) do\n {:ok, match?({:ok, ^value}, :maps.find(key, map))}\n end\n\n def member?(_map, _other) do\n {:ok, false}\n end\n\n def count(map) do\n {:ok, map_size(map)}\n end\nend\n\ndefimpl Enumerable, for: Function do\n def reduce(function, acc, fun) when is_function(function, 2),\n do: function.(acc, fun)\n def member?(_function, _value),\n do: {:error, __MODULE__}\n def count(_function),\n do: {:error, __MODULE__}\nend\n","old_contents":"defprotocol Enumerable do\n @moduledoc \"\"\"\n Enumerable protocol used by `Enum` and `Stream` modules.\n\n When you invoke a function in the `Enum` module, the first argument\n is usually a collection that must implement this protocol. For example,\n the expression\n\n Enum.map([1, 2, 3], &(&1 * 2))\n\n invokes underneath `Enumerable.reduce\/3` to perform the reducing\n operation that builds a mapped list by calling the mapping function\n `&(&1 * 2)` on every element in the collection and cons'ing the\n element with an accumulated list.\n\n Internally, `Enum.map\/2` is implemented as follows:\n\n def map(enum, fun) do\n reducer = fn x, acc -> {:cont, [fun.(x)|acc]} end\n Enumerable.reduce(enum, {:cont, []}, reducer) |> elem(1) |> :lists.reverse()\n end\n\n Notice the user given function is wrapped into a `reducer` function.\n The `reducer` function must return a tagged tuple after each step,\n as described in the `acc\/0` type.\n\n The reason the accumulator requires a tagged tuple is to allow the\n reducer function to communicate to the underlying enumerable the end\n of enumeration, allowing any open resource to be properly closed. It\n also allows suspension of the enumeration, which is useful when\n interleaving between many enumerables is required (as in zip).\n\n Finally, `Enumerable.reduce\/3` will return another tagged tuple,\n as represented by the `result\/0` type.\n \"\"\"\n\n @typedoc \"\"\"\n The accumulator value for each step.\n\n It must be a tagged tuple with one of the following \"tags\":\n\n * `:cont` - the enumeration should continue\n * `:halt` - the enumeration should halt immediately\n * `:suspend` - the enumeration should be suspended immediately\n\n Depending on the accumulator value, the result returned by\n `Enumerable.reduce\/3` will change. Please check the `result`\n type docs for more information.\n\n In case a reducer function returns a `:suspend` accumulator,\n it must be explicitly handled by the caller and never leak.\n \"\"\"\n @type acc :: {:cont, term} | {:halt, term} | {:suspend, term}\n\n @typedoc \"\"\"\n The reducer function.\n\n Should be called with the collection element and the\n accumulator contents. Returns the accumulator for\n the next enumeration step.\n \"\"\"\n @type reducer :: (term, term -> acc)\n\n @typedoc \"\"\"\n The result of the reduce operation.\n\n It may be *done* when the enumeration is finished by reaching\n its end, or *halted*\/*suspended* when the enumeration was halted\n or suspended by the reducer function.\n\n In case a reducer function returns the `:suspend` accumulator, the\n `:suspended` tuple must be explicitly handled by the caller and\n never leak. In practice, this means regular enumeration functions\n just need to be concerned about `:done` and `:halted` results.\n\n Furthermore, a `:suspend` call must always be followed by another call,\n eventually halting or continuing until the end.\n \"\"\"\n @type result :: {:done, term} | {:halted, term} | {:suspended, term, continuation}\n\n @typedoc \"\"\"\n A partially applied reduce function.\n\n The continuation is the closure returned as a result when\n the enumeration is suspended. When invoked, it expects\n a new accumulator and it returns the result.\n\n A continuation is easily implemented as long as the reduce\n function is defined in a tail recursive fashion. If the function\n is tail recursive, all the state is passed as arguments, so\n the continuation would simply be the reducing function partially\n applied.\n \"\"\"\n @type continuation :: (acc -> result)\n\n @doc \"\"\"\n Reduces the collection into a value.\n\n Most of the operations in `Enum` are implemented in terms of reduce.\n This function should apply the given `reducer` function to each\n item in the collection and proceed as expected by the returned accumulator.\n\n As an example, here is the implementation of `reduce` for lists:\n\n def reduce(_, {:halt, acc}, _fun), do: {:halted, acc}\n def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)}\n def reduce([], {:cont, acc}, _fun), do: {:done, acc}\n def reduce([h|t], {:cont, acc}, fun), do: reduce(t, fun.(h, acc), fun)\n\n \"\"\"\n @spec reduce(t, acc, reducer) :: result\n def reduce(collection, acc, fun)\n\n @doc \"\"\"\n Checks if a value exists within the collection.\n\n It should return `{:ok, boolean}`.\n\n If `{:error, __MODULE__}` is returned a default algorithm using `reduce` and\n the match (`===`) operator is used. This algorithm runs in linear time.\n\n Please force use of the default algorithm unless you can implement an\n algorithm that is significantly faster.\n \"\"\"\n @spec member?(t, term) :: {:ok, boolean} | {:error, module}\n def member?(collection, value)\n\n @doc \"\"\"\n Retrieves the collection's size.\n\n It should return `{:ok, size}`.\n\n If `{:error, __MODULE__}` is returned a default algorithm using `reduce` and\n the match (`===`) operator is used. This algorithm runs in linear time.\n\n Please force use of the default algorithm unless you can implement an\n algorithm that is significantly faster.\n \"\"\"\n @spec count(t) :: {:ok, non_neg_integer} | {:error, module}\n def count(collection)\nend\n\ndefmodule Enum do\n import Kernel, except: [max: 2, min: 2]\n\n @moduledoc \"\"\"\n Provides a set of algorithms that enumerate over collections according to the\n `Enumerable` protocol:\n\n iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end)\n [2,4,6]\n\n Some particular types, like dictionaries, yield a specific format on\n enumeration. For dicts, the argument is always a `{key, value}` tuple:\n\n iex> dict = %{a: 1, b: 2}\n iex> Enum.map(dict, fn {k, v} -> {k, v * 2} end)\n [a: 2, b: 4]\n\n Note that the functions in the `Enum` module are eager: they always start\n the enumeration of the given collection. The `Stream` module allows\n lazy enumeration of collections and provides infinite streams.\n\n Since the majority of the functions in `Enum` enumerate the whole\n collection and return a list as result, infinite streams need to\n be carefully used with such functions, as they can potentially run\n forever. For example:\n\n Enum.each Stream.cycle([1,2,3]), &IO.puts(&1)\n\n \"\"\"\n\n @compile :inline_list_funcs\n\n @type t :: Enumerable.t\n @type element :: any\n @type index :: non_neg_integer\n @type default :: any\n\n # Require Stream.Reducers and its callbacks\n require Stream.Reducers, as: R\n\n defmacrop cont(_, entry, acc) do\n quote do: {:cont, [unquote(entry)|unquote(acc)]}\n end\n\n defmacrop acc(h, n, _) do\n quote do: {unquote(h), unquote(n)}\n end\n\n defmacrop cont_with_acc(f, entry, h, n, _) do\n quote do\n {:cont, {[unquote(entry)|unquote(h)], unquote(n)}}\n end\n end\n\n @doc \"\"\"\n Invokes the given `fun` for each item in the `collection` and returns `false`\n if at least one invocation returns `false`. Otherwise returns `true`.\n\n ## Examples\n\n iex> Enum.all?([2, 4, 6], fn(x) -> rem(x, 2) == 0 end)\n true\n\n iex> Enum.all?([2, 3, 4], fn(x) -> rem(x, 2) == 0 end)\n false\n\n If no function is given, it defaults to checking if\n all items in the collection evaluate to `true`.\n\n iex> Enum.all?([1, 2, 3])\n true\n\n iex> Enum.all?([1, nil, 3])\n false\n\n \"\"\"\n @spec all?(t) :: boolean\n @spec all?(t, (element -> as_boolean(term))) :: boolean\n\n def all?(collection, fun \\\\ fn(x) -> x end)\n\n def all?(collection, fun) when is_list(collection) do\n do_all?(collection, fun)\n end\n\n def all?(collection, fun) do\n Enumerable.reduce(collection, {:cont, true}, fn(entry, _) ->\n if fun.(entry), do: {:cont, true}, else: {:halt, false}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Invokes the given `fun` for each item in the `collection` and returns `true` if\n at least one invocation returns `true`. Returns `false` otherwise.\n\n ## Examples\n\n iex> Enum.any?([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n false\n\n iex> Enum.any?([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n true\n\n If no function is given, it defaults to checking if\n at least one item in the collection evaluates to `true`.\n\n iex> Enum.any?([false, false, false])\n false\n\n iex> Enum.any?([false, true, false])\n true\n\n \"\"\"\n @spec any?(t) :: boolean\n @spec any?(t, (element -> as_boolean(term))) :: boolean\n\n def any?(collection, fun \\\\ fn(x) -> x end)\n\n def any?(collection, fun) when is_list(collection) do\n do_any?(collection, fun)\n end\n\n def any?(collection, fun) do\n Enumerable.reduce(collection, {:cont, false}, fn(entry, _) ->\n if fun.(entry), do: {:halt, true}, else: {:cont, false}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Finds the element at the given index (zero-based).\n\n Returns `default` if index is out of bounds.\n\n Note this operation takes linear time. In order to access\n the element at index `n`, it will need to traverse `n`\n previous elements.\n\n ## Examples\n\n iex> Enum.at([2, 4, 6], 0)\n 2\n\n iex> Enum.at([2, 4, 6], 2)\n 6\n\n iex> Enum.at([2, 4, 6], 4)\n nil\n\n iex> Enum.at([2, 4, 6], 4, :none)\n :none\n\n \"\"\"\n @spec at(t, integer, default) :: element | default\n def at(collection, n, default \\\\ nil) do\n case fetch(collection, n) do\n {:ok, h} -> h\n :error -> default\n end\n end\n\n @doc \"\"\"\n Shortcut to `chunk(coll, n, n)`.\n \"\"\"\n @spec chunk(t, non_neg_integer) :: [list]\n def chunk(coll, n), do: chunk(coll, n, n, nil)\n\n @doc \"\"\"\n Returns a collection of lists containing `n` items each, where\n each new chunk starts `step` elements into the collection.\n\n `step` is optional and, if not passed, defaults to `n`, i.e.\n chunks do not overlap. If the final chunk does not have `n`\n elements to fill the chunk, elements are taken as necessary\n from `pad` if it was passed. If `pad` is passed and does not\n have enough elements to fill the chunk, then the chunk is\n returned anyway with less than `n` elements. If `pad` is not\n passed at all or is `nil`, then the partial chunk is discarded\n from the result.\n\n ## Examples\n\n iex> Enum.chunk([1, 2, 3, 4, 5, 6], 2)\n [[1, 2], [3, 4], [5, 6]]\n\n iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 2)\n [[1, 2, 3], [3, 4, 5]]\n\n iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 2, [7])\n [[1, 2, 3], [3, 4, 5], [5, 6, 7]]\n\n iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 3, [])\n [[1, 2, 3], [4, 5, 6]]\n\n \"\"\"\n @spec chunk(t, non_neg_integer, non_neg_integer, t | nil) :: [list]\n def chunk(coll, n, step, pad \\\\ nil) when n > 0 and step > 0 do\n limit = :erlang.max(n, step)\n\n {_, {acc, {buffer, i}}} =\n Enumerable.reduce(coll, {:cont, {[], {[], 0}}}, R.chunk(n, step, limit))\n\n if nil?(pad) || i == 0 do\n :lists.reverse(acc)\n else\n buffer = :lists.reverse(buffer) ++ take(pad, n - i)\n :lists.reverse([buffer|acc])\n end\n end\n\n @doc \"\"\"\n Splits `coll` on every element for which `fun` returns a new value.\n\n ## Examples\n\n iex> Enum.chunk_by([1, 2, 2, 3, 4, 4, 6, 7, 7], &(rem(&1, 2) == 1))\n [[1], [2, 2], [3], [4, 4, 6], [7, 7]]\n\n \"\"\"\n @spec chunk_by(t, (element -> any)) :: [list]\n def chunk_by(coll, fun) do\n {_, {acc, res}} =\n Enumerable.reduce(coll, {:cont, {[], nil}}, R.chunk_by(fun))\n\n case res do\n {buffer, _} ->\n :lists.reverse([:lists.reverse(buffer) | acc])\n nil ->\n []\n end\n end\n\n @doc \"\"\"\n Given an enumerable of enumerables, concatenate the enumerables into a single list.\n\n ## Examples\n\n iex> Enum.concat([1..3, 4..6, 7..9])\n [1,2,3,4,5,6,7,8,9]\n\n iex> Enum.concat([[1, [2], 3], [4], [5, 6]])\n [1,[2],3,4,5,6]\n\n \"\"\"\n @spec concat(t) :: t\n def concat(enumerables) do\n do_concat(enumerables)\n end\n\n @doc \"\"\"\n Concatenates the enumerable on the right with the enumerable on the left.\n\n This function produces the same result as the `Kernel.++\/2` operator for lists.\n\n ## Examples\n\n iex> Enum.concat(1..3, 4..6)\n [1,2,3,4,5,6]\n\n iex> Enum.concat([1, 2, 3], [4, 5, 6])\n [1,2,3,4,5,6]\n\n \"\"\"\n @spec concat(t, t) :: t\n def concat(left, right) when is_list(left) and is_list(right) do\n left ++ right\n end\n\n def concat(left, right) do\n do_concat([left, right])\n end\n\n defp do_concat(enumerable) do\n fun = &[&1|&2]\n reduce(enumerable, [], &reduce(&1, &2, fun)) |> :lists.reverse\n end\n\n @doc \"\"\"\n Returns the collection's size.\n\n ## Examples\n\n iex> Enum.count([1, 2, 3])\n 3\n\n \"\"\"\n @spec count(t) :: non_neg_integer\n def count(collection) when is_list(collection) do\n :erlang.length(collection)\n end\n\n def count(collection) do\n case Enumerable.count(collection) do\n {:ok, value} when is_integer(value) ->\n value\n {:error, module} ->\n module.reduce(collection, {:cont, 0}, fn\n _, acc -> {:cont, acc + 1}\n end) |> elem(1)\n end\n end\n\n @doc \"\"\"\n Returns the count of items in the collection for which\n `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.count([1, 2, 3, 4, 5], fn(x) -> rem(x, 2) == 0 end)\n 2\n\n \"\"\"\n @spec count(t, (element -> as_boolean(term))) :: non_neg_integer\n def count(collection, fun) do\n Enumerable.reduce(collection, {:cont, 0}, fn(entry, acc) ->\n {:cont, if(fun.(entry), do: acc + 1, else: acc)}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Drops the first `count` items from `collection`.\n\n If a negative value `count` is given, the last `count`\n values will be dropped. The collection is enumerated\n once to retrieve the proper index and the remaining\n calculation is performed from the end.\n\n ## Examples\n\n iex> Enum.drop([1, 2, 3], 2)\n [3]\n\n iex> Enum.drop([1, 2, 3], 10)\n []\n\n iex> Enum.drop([1, 2, 3], 0)\n [1,2,3]\n\n iex> Enum.drop([1, 2, 3], -1)\n [1,2]\n\n \"\"\"\n @spec drop(t, integer) :: list\n def drop(collection, count) when is_list(collection) and count >= 0 do\n do_drop(collection, count)\n end\n\n def drop(collection, count) when count >= 0 do\n res =\n reduce(collection, count, fn\n x, acc when is_list(acc) -> [x|acc]\n x, 0 -> [x]\n _, acc when acc > 0 -> acc - 1\n end)\n if is_list(res), do: :lists.reverse(res), else: []\n end\n\n def drop(collection, count) when count < 0 do\n do_drop(reverse(collection), abs(count)) |> :lists.reverse\n end\n\n @doc \"\"\"\n Drops items at the beginning of `collection` while `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.drop_while([1, 2, 3, 4, 5], fn(x) -> x < 3 end)\n [3,4,5]\n\n \"\"\"\n @spec drop_while(t, (element -> as_boolean(term))) :: list\n def drop_while(collection, fun) when is_list(collection) do\n do_drop_while(collection, fun)\n end\n\n def drop_while(collection, fun) do\n {_, {res, _}} =\n Enumerable.reduce(collection, {:cont, {[], true}}, R.drop_while(fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Invokes the given `fun` for each item in the `collection`.\n Returns `:ok`.\n\n ## Examples\n\n Enum.each([\"some\", \"example\"], fn(x) -> IO.puts x end)\n \"some\"\n \"example\"\n #=> :ok\n\n \"\"\"\n @spec each(t, (element -> any)) :: :ok\n def each(collection, fun) when is_list(collection) do\n :lists.foreach(fun, collection)\n :ok\n end\n\n def each(collection, fun) do\n reduce(collection, nil, fn(entry, _) ->\n fun.(entry)\n nil\n end)\n :ok\n end\n\n @doc \"\"\"\n Returns `true` if the collection is empty, otherwise `false`.\n\n ## Examples\n\n iex> Enum.empty?([])\n true\n\n iex> Enum.empty?([1, 2, 3])\n false\n\n \"\"\"\n @spec empty?(t) :: boolean\n def empty?(collection) when is_list(collection) do\n collection == []\n end\n\n def empty?(collection) do\n Enumerable.reduce(collection, {:cont, true}, fn(_, _) -> {:halt, false} end) |> elem(1)\n end\n\n @doc \"\"\"\n Finds the element at the given index (zero-based).\n\n Returns `{:ok, element}` if found, otherwise `:error`.\n\n A negative index can be passed, which means the collection is\n enumerated once and the index is counted from the end (i.e.\n `-1` fetches the last element).\n\n Note this operation takes linear time. In order to access\n the element at index `n`, it will need to traverse `n`\n previous elements.\n\n ## Examples\n\n iex> Enum.fetch([2, 4, 6], 0)\n {:ok, 2}\n\n iex> Enum.fetch([2, 4, 6], 2)\n {:ok, 6}\n\n iex> Enum.fetch([2, 4, 6], 4)\n :error\n\n \"\"\"\n @spec fetch(t, integer) :: {:ok, element} | :error\n def fetch(collection, n) when is_list(collection) and n >= 0 do\n do_fetch(collection, n)\n end\n\n def fetch(collection, n) when n >= 0 do\n res =\n Enumerable.reduce(collection, {:cont, 0}, fn(entry, acc) ->\n if acc == n do\n {:halt, entry}\n else\n {:cont, acc + 1}\n end\n end)\n\n case res do\n {:halted, entry} -> {:ok, entry}\n {:done, _} -> :error\n end\n end\n\n def fetch(collection, n) when n < 0 do\n do_fetch(reverse(collection), abs(n + 1))\n end\n\n @doc \"\"\"\n Finds the element at the given index (zero-based).\n\n Raises `OutOfBoundsError` if the given position\n is outside the range of the collection.\n\n Note this operation takes linear time. In order to access\n the element at index `n`, it will need to traverse `n`\n previous elements.\n\n ## Examples\n\n iex> Enum.fetch!([2, 4, 6], 0)\n 2\n\n iex> Enum.fetch!([2, 4, 6], 2)\n 6\n\n iex> Enum.fetch!([2, 4, 6], 4)\n ** (Enum.OutOfBoundsError) out of bounds error\n\n \"\"\"\n @spec fetch!(t, integer) :: element | no_return\n def fetch!(collection, n) do\n case fetch(collection, n) do\n {:ok, h} -> h\n :error -> raise Enum.OutOfBoundsError\n end\n end\n\n @doc \"\"\"\n Filters the collection, i.e. returns only those elements\n for which `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.filter([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)\n [2]\n\n \"\"\"\n @spec filter(t, (element -> as_boolean(term))) :: list\n def filter(collection, fun) when is_list(collection) do\n for item <- collection, fun.(item), do: item\n end\n\n def filter(collection, fun) do\n Enumerable.reduce(collection, {:cont, []}, R.filter(fun))\n |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Filters the collection and maps its values in one pass.\n\n ## Examples\n\n iex> Enum.filter_map([1, 2, 3], fn(x) -> rem(x, 2) == 0 end, &(&1 * 2))\n [4]\n\n \"\"\"\n @spec filter_map(t, (element -> as_boolean(term)), (element -> element)) :: list\n def filter_map(collection, filter, mapper) when is_list(collection) do\n for item <- collection, filter.(item), do: mapper.(item)\n end\n\n def filter_map(collection, filter, mapper) do\n Enumerable.reduce(collection, {:cont, []}, R.filter_map(filter, mapper))\n |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Returns the first item for which `fun` returns a truthy value. If no such\n item is found, returns `ifnone`.\n\n ## Examples\n\n iex> Enum.find([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n nil\n\n iex> Enum.find([2, 4, 6], 0, fn(x) -> rem(x, 2) == 1 end)\n 0\n\n iex> Enum.find([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n 3\n\n \"\"\"\n @spec find(t, default, (element -> any)) :: element | default\n def find(collection, ifnone \\\\ nil, fun)\n\n def find(collection, ifnone, fun) when is_list(collection) do\n do_find(collection, ifnone, fun)\n end\n\n def find(collection, ifnone, fun) do\n Enumerable.reduce(collection, {:cont, ifnone}, fn(entry, ifnone) ->\n if fun.(entry), do: {:halt, entry}, else: {:cont, ifnone}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Similar to `find\/3`, but returns the value of the function\n invocation instead of the element itself.\n\n ## Examples\n\n iex> Enum.find_value([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n nil\n\n iex> Enum.find_value([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n true\n\n \"\"\"\n @spec find_value(t, any, (element -> any)) :: any | :nil\n def find_value(collection, ifnone \\\\ nil, fun)\n\n def find_value(collection, ifnone, fun) when is_list(collection) do\n do_find_value(collection, ifnone, fun)\n end\n\n def find_value(collection, ifnone, fun) do\n Enumerable.reduce(collection, {:cont, ifnone}, fn(entry, ifnone) ->\n fun_entry = fun.(entry)\n if fun_entry, do: {:halt, fun_entry}, else: {:cont, ifnone}\n end) |> elem(1)\n end\n\n @doc \"\"\"\n Similar to `find\/3`, but returns the index (zero-based)\n of the element instead of the element itself.\n\n ## Examples\n\n iex> Enum.find_index([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)\n nil\n\n iex> Enum.find_index([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)\n 1\n\n \"\"\"\n @spec find_index(t, (element -> any)) :: index | :nil\n def find_index(collection, fun) when is_list(collection) do\n do_find_index(collection, 0, fun)\n end\n\n def find_index(collection, fun) do\n res =\n Enumerable.reduce(collection, {:cont, 0}, fn(entry, acc) ->\n if fun.(entry), do: {:halt, acc}, else: {:cont, acc + 1}\n end)\n\n case res do\n {:halted, entry} -> entry\n {:done, _} -> nil\n end\n end\n\n @doc \"\"\"\n Returns a new collection appending the result of invoking `fun`\n on each corresponding item of `collection`.\n\n The given function should return an enumerable.\n\n ## Examples\n\n iex> Enum.flat_map([:a, :b, :c], fn(x) -> [x, x] end)\n [:a, :a, :b, :b, :c, :c]\n\n iex> Enum.flat_map([{1,3}, {4,6}], fn({x,y}) -> x..y end)\n [1, 2, 3, 4, 5, 6]\n\n \"\"\"\n @spec flat_map(t, (element -> t)) :: list\n def flat_map(collection, fun) do\n reduce(collection, [], fn(entry, acc) ->\n reduce(fun.(entry), acc, &[&1|&2])\n end) |> :lists.reverse\n end\n\n @doc \"\"\"\n Maps and reduces a collection, flattening the given results.\n\n It expects an accumulator and a function that receives each stream item\n and an accumulator, and must return a tuple containing a new stream\n (often a list) with the new accumulator or a tuple with `:halt` as first\n element and the accumulator as second.\n\n ## Examples\n\n iex> enum = 1..100\n iex> n = 3\n iex> Enum.flat_map_reduce(enum, 0, fn i, acc ->\n ...> if acc < n, do: {[i], acc + 1}, else: {:halt, acc}\n ...> end)\n {[1,2,3], 3}\n\n \"\"\"\n @spec flat_map_reduce(t, acc, fun) :: {[any], any} when\n fun: (element, acc -> {t, acc} | {:halt, acc}),\n acc: any\n def flat_map_reduce(collection, acc, fun) do\n {_, {list, acc}} =\n Enumerable.reduce(collection, {:cont, {[], acc}}, fn(entry, {list, acc}) ->\n case fun.(entry, acc) do\n {:halt, acc} ->\n {:halt, {list, acc}}\n {entries, acc} ->\n {:cont, {reduce(entries, list, &[&1|&2]), acc}}\n end\n end)\n\n {:lists.reverse(list), acc}\n end\n\n @doc \"\"\"\n Intersperses `element` between each element of the enumeration.\n\n Complexity: O(n)\n\n ## Examples\n\n iex> Enum.intersperse([1, 2, 3], 0)\n [1, 0, 2, 0, 3]\n\n iex> Enum.intersperse([1], 0)\n [1]\n\n iex> Enum.intersperse([], 0)\n []\n\n \"\"\"\n @spec intersperse(t, element) :: list\n def intersperse(collection, element) do\n list =\n reduce(collection, [], fn(x, acc) ->\n [x, element | acc]\n end) |> :lists.reverse()\n\n case list do\n [] -> []\n [_|t] -> t # Head is a superfluous intersperser element\n end\n end\n\n @doc \"\"\"\n Inserts the given enumerable into a collectable.\n\n ## Examples\n\n iex> Enum.into([1, 2], [0])\n [0, 1, 2]\n\n iex> Enum.into([a: 1, b: 2], %{})\n %{a: 1, b: 2}\n\n \"\"\"\n @spec into(Enumerable.t, Collectable.t) :: Collectable.t\n def into(collection, list) when is_list(list) do\n list ++ to_list(collection)\n end\n\n def into(collection, %{} = map) when is_list(collection) and map_size(map) == 0 do\n :maps.from_list(collection)\n end\n\n def into(collection, collectable) do\n {initial, fun} = Collectable.into(collectable)\n into(collection, initial, fun, fn x, acc ->\n fun.(acc, {:cont, x})\n end)\n end\n\n @doc \"\"\"\n Inserts the given enumerable into a collectable\n according to the transformation function.\n\n ## Examples\n\n iex> Enum.into([2, 3], [3], fn x -> x * 3 end)\n [3, 6, 9]\n\n \"\"\"\n @spec into(Enumerable.t, Collectable.t, (term -> term)) :: Collectable.t\n\n def into(collection, list, transform) when is_list(list) and is_function(transform, 1) do\n list ++ map(collection, transform)\n end\n\n def into(collection, collectable, transform) when is_function(transform, 1) do\n {initial, fun} = Collectable.into(collectable)\n into(collection, initial, fun, fn x, acc ->\n fun.(acc, {:cont, transform.(x)})\n end)\n end\n\n defp into(collection, initial, fun, callback) do\n try do\n reduce(collection, initial, callback)\n catch\n kind, reason ->\n stacktrace = System.stacktrace\n fun.(initial, :halt)\n :erlang.raise(kind, reason, stacktrace)\n else\n acc -> fun.(acc, :done)\n end\n end\n\n @doc \"\"\"\n Joins the given `collection` according to `joiner`.\n `joiner` can be either a binary or a list and the\n result will be of the same type as `joiner`. If\n `joiner` is not passed at all, it defaults to an\n empty binary.\n\n All items in the collection must be convertible\n to a binary, otherwise an error is raised.\n\n ## Examples\n\n iex> Enum.join([1, 2, 3])\n \"123\"\n\n iex> Enum.join([1, 2, 3], \" = \")\n \"1 = 2 = 3\"\n\n \"\"\"\n @spec join(t, String.t) :: String.t\n def join(collection, joiner \\\\ \"\")\n\n def join(collection, joiner) when is_binary(joiner) do\n reduced = reduce(collection, :first, fn\n entry, :first -> enum_to_string(entry)\n entry, acc -> [acc, joiner|enum_to_string(entry)]\n end)\n if reduced == :first do\n \"\"\n else\n IO.iodata_to_binary reduced\n end\n end\n\n @doc \"\"\"\n Returns a new collection, where each item is the result\n of invoking `fun` on each corresponding item of `collection`.\n\n For dicts, the function expects a key-value tuple.\n\n ## Examples\n\n iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end)\n [2, 4, 6]\n\n iex> Enum.map([a: 1, b: 2], fn({k, v}) -> {k, -v} end)\n [a: -1, b: -2]\n\n \"\"\"\n @spec map(t, (element -> any)) :: list\n def map(collection, fun) when is_list(collection) do\n for item <- collection, do: fun.(item)\n end\n\n def map(collection, fun) do\n Enumerable.reduce(collection, {:cont, []}, R.map(fun)) |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Maps and joins the given `collection` in one pass.\n `joiner` can be either a binary or a list and the\n result will be of the same type as `joiner`. If\n `joiner` is not passed at all, it defaults to an\n empty binary.\n\n All items in the collection must be convertible\n to a binary, otherwise an error is raised.\n\n ## Examples\n\n iex> Enum.map_join([1, 2, 3], &(&1 * 2))\n \"246\"\n\n iex> Enum.map_join([1, 2, 3], \" = \", &(&1 * 2))\n \"2 = 4 = 6\"\n\n \"\"\"\n @spec map_join(t, String.t, (element -> any)) :: String.t\n def map_join(collection, joiner \\\\ \"\", mapper)\n\n def map_join(collection, joiner, mapper) when is_binary(joiner) do\n reduced = reduce(collection, :first, fn\n entry, :first -> enum_to_string(mapper.(entry))\n entry, acc -> [acc, joiner|enum_to_string(mapper.(entry))]\n end)\n\n if reduced == :first do\n \"\"\n else\n IO.iodata_to_binary reduced\n end\n end\n\n @doc \"\"\"\n Invokes the given `fun` for each item in the `collection`\n while also keeping an accumulator. Returns a tuple where\n the first element is the mapped collection and the second\n one is the final accumulator.\n\n For dicts, the first tuple element must be a `{key, value}`\n tuple.\n\n ## Examples\n\n iex> Enum.map_reduce([1, 2, 3], 0, fn(x, acc) -> {x * 2, x + acc} end)\n {[2, 4, 6], 6}\n\n \"\"\"\n @spec map_reduce(t, any, (element, any -> any)) :: any\n def map_reduce(collection, acc, fun) when is_list(collection) do\n :lists.mapfoldl(fun, acc, collection)\n end\n\n def map_reduce(collection, acc, fun) do\n {list, acc} = reduce(collection, {[], acc}, fn(entry, {list, acc}) ->\n {new_entry, acc} = fun.(entry, acc)\n {[new_entry|list], acc}\n end)\n {:lists.reverse(list), acc}\n end\n\n @doc \"\"\"\n Returns the maximum value.\n Raises `EmptyError` if the collection is empty.\n\n ## Examples\n\n iex> Enum.max([1, 2, 3])\n 3\n\n \"\"\"\n @spec max(t) :: element | no_return\n def max(collection) do\n reduce(collection, &Kernel.max(&1, &2))\n end\n\n @doc \"\"\"\n Returns the maximum value as calculated by the given function.\n Raises `EmptyError` if the collection is empty.\n\n ## Examples\n\n iex> Enum.max_by([\"a\", \"aa\", \"aaa\"], fn(x) -> String.length(x) end)\n \"aaa\"\n\n \"\"\"\n @spec max_by(t, (element -> any)) :: element | no_return\n def max_by([h|t], fun) do\n reduce(t, {h, fun.(h)}, fn(entry, {_, fun_max} = old) ->\n fun_entry = fun.(entry)\n if(fun_entry > fun_max, do: {entry, fun_entry}, else: old)\n end) |> elem(0)\n end\n\n def max_by([], _fun) do\n raise Enum.EmptyError\n end\n\n def max_by(collection, fun) do\n result =\n reduce(collection, :first, fn\n entry, {_, fun_max} = old ->\n fun_entry = fun.(entry)\n if(fun_entry > fun_max, do: {entry, fun_entry}, else: old)\n entry, :first ->\n {entry, fun.(entry)}\n end)\n\n case result do\n :first -> raise Enum.EmptyError\n {entry, _} -> entry\n end\n end\n\n @doc \"\"\"\n Checks if `value` exists within the `collection`.\n\n Membership is tested with the match (`===`) operator, although\n enumerables like ranges may include floats inside the given\n range.\n\n ## Examples\n\n iex> Enum.member?(1..10, 5)\n true\n\n iex> Enum.member?([:a, :b, :c], :d)\n false\n\n \"\"\"\n @spec member?(t, element) :: boolean\n def member?(collection, value) when is_list(collection) do\n :lists.member(value, collection)\n end\n\n def member?(collection, value) do\n case Enumerable.member?(collection, value) do\n {:ok, value} when is_boolean(value) ->\n value\n {:error, module} ->\n module.reduce(collection, {:cont, false}, fn\n v, _ when v === value -> {:halt, true}\n _, _ -> {:cont, false}\n end) |> elem(1)\n end\n end\n\n @doc \"\"\"\n Returns the minimum value.\n Raises `EmptyError` if the collection is empty.\n\n ## Examples\n\n iex> Enum.min([1, 2, 3])\n 1\n\n \"\"\"\n @spec min(t) :: element | no_return\n def min(collection) do\n reduce(collection, &Kernel.min(&1, &2))\n end\n\n @doc \"\"\"\n Returns the minimum value as calculated by the given function.\n Raises `EmptyError` if the collection is empty.\n\n ## Examples\n\n iex> Enum.min_by([\"a\", \"aa\", \"aaa\"], fn(x) -> String.length(x) end)\n \"a\"\n\n \"\"\"\n @spec min_by(t, (element -> any)) :: element | no_return\n def min_by([h|t], fun) do\n reduce(t, {h, fun.(h)}, fn(entry, {_, fun_min} = old) ->\n fun_entry = fun.(entry)\n if(fun_entry < fun_min, do: {entry, fun_entry}, else: old)\n end) |> elem(0)\n end\n\n def min_by([], _fun) do\n raise Enum.EmptyError\n end\n\n def min_by(collection, fun) do\n result =\n reduce(collection, :first, fn\n entry, {_, fun_min} = old ->\n fun_entry = fun.(entry)\n if(fun_entry < fun_min, do: {entry, fun_entry}, else: old)\n entry, :first ->\n {entry, fun.(entry)}\n end)\n\n case result do\n :first -> raise Enum.EmptyError\n {entry, _} -> entry\n end\n end\n\n @doc \"\"\"\n Returns the sum of all values.\n\n Raises `ArithmeticError` if collection contains a non-numeric value.\n\n ## Examples\n\n iex> Enum.sum([1, 2, 3])\n 6\n\n \"\"\"\n @spec sum(t) :: number\n def sum(collection) do\n reduce(collection, 0, &+\/2)\n end\n\n @doc \"\"\"\n Partitions `collection` into two collections, where the first one contains elements\n for which `fun` returns a truthy value, and the second one -- for which `fun`\n returns `false` or `nil`.\n\n ## Examples\n\n iex> Enum.partition([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)\n {[2], [1,3]}\n\n \"\"\"\n @spec partition(t, (element -> any)) :: {list, list}\n def partition(collection, fun) do\n {acc1, acc2} =\n reduce(collection, {[], []}, fn(entry, {acc1, acc2}) ->\n if fun.(entry) do\n {[entry|acc1], acc2}\n else\n {acc1, [entry|acc2]}\n end\n end)\n\n {:lists.reverse(acc1), :lists.reverse(acc2)}\n end\n\n @doc \"\"\"\n Splits `collection` into groups based on `fun`.\n\n The result is a dict (by default a map) where each key is\n a group and each value is a list of elements from `collection`\n for which `fun` returned that group. Ordering is not necessarily\n preserved.\n\n ## Examples\n\n iex> Enum.group_by(~w{ant buffalo cat dingo}, &String.length\/1)\n %{3 => [\"cat\", \"ant\"], 7 => [\"buffalo\"], 5 => [\"dingo\"]}\n\n \"\"\"\n @spec group_by(t, dict, (element -> any)) :: dict when dict: Dict.t\n def group_by(collection, dict \\\\ %{}, fun) do\n reduce(collection, dict, fn(entry, categories) ->\n Dict.update(categories, fun.(entry), [entry], &[entry|&1])\n end)\n end\n\n @doc \"\"\"\n Invokes `fun` for each element in the collection passing that element and the\n accumulator `acc` as arguments. `fun`'s return value is stored in `acc`.\n Returns the accumulator.\n\n ## Examples\n\n iex> Enum.reduce([1, 2, 3], 0, fn(x, acc) -> x + acc end)\n 6\n\n \"\"\"\n @spec reduce(t, any, (element, any -> any)) :: any\n def reduce(collection, acc, fun) when is_list(collection) do\n :lists.foldl(fun, acc, collection)\n end\n\n def reduce(collection, acc, fun) do\n Enumerable.reduce(collection, {:cont, acc},\n fn x, acc -> {:cont, fun.(x, acc)} end) |> elem(1)\n end\n\n @doc \"\"\"\n Invokes `fun` for each element in the collection passing that element and the\n accumulator `acc` as arguments. `fun`'s return value is stored in `acc`.\n The first element of the collection is used as the initial value of `acc`.\n Returns the accumulator.\n\n ## Examples\n\n iex> Enum.reduce([1, 2, 3, 4], fn(x, acc) -> x * acc end)\n 24\n\n \"\"\"\n @spec reduce(t, (element, any -> any)) :: any\n def reduce([h|t], fun) do\n reduce(t, h, fun)\n end\n\n def reduce([], _fun) do\n raise Enum.EmptyError\n end\n\n def reduce(collection, fun) do\n result =\n Enumerable.reduce(collection, {:cont, :first}, fn\n x, :first ->\n {:cont, {:acc, x}}\n x, {:acc, acc} ->\n {:cont, {:acc, fun.(x, acc)}}\n end) |> elem(1)\n\n case result do\n :first -> raise Enum.EmptyError\n {:acc, acc} -> acc\n end\n end\n\n @doc \"\"\"\n Returns elements of collection for which `fun` returns `false`.\n\n ## Examples\n\n iex> Enum.reject([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)\n [1, 3]\n\n \"\"\"\n @spec reject(t, (element -> as_boolean(term))) :: list\n def reject(collection, fun) when is_list(collection) do\n for item <- collection, !fun.(item), do: item\n end\n\n def reject(collection, fun) do\n Enumerable.reduce(collection, {:cont, []}, R.reject(fun)) |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Reverses the collection.\n\n ## Examples\n\n iex> Enum.reverse([1, 2, 3])\n [3, 2, 1]\n\n \"\"\"\n @spec reverse(t) :: list\n def reverse(collection) when is_list(collection) do\n :lists.reverse(collection)\n end\n\n def reverse(collection) do\n reverse(collection, [])\n end\n\n @doc \"\"\"\n Reverses the collection and appends the tail.\n This is an optimization for\n `Enum.concat(Enum.reverse(collection), tail)`.\n\n ## Examples\n\n iex> Enum.reverse([1, 2, 3], [4, 5, 6])\n [3, 2, 1, 4, 5, 6]\n\n \"\"\"\n @spec reverse(t, t) :: list\n def reverse(collection, tail) when is_list(collection) and is_list(tail) do\n :lists.reverse(collection, tail)\n end\n\n def reverse(collection, tail) do\n reduce(collection, to_list(tail), fn(entry, acc) ->\n [entry|acc]\n end)\n end\n\n @doc \"\"\"\n Returns a random element or random sublist of a collection.\n\n Notice that you need to explicitly call `:random.seed\/1` and\n set a seed value for the random algorithm. Otherwise, the\n default seed will be set which will always return the same\n result. For example, one could do the following to set a seed\n dynamically:\n\n :random.seed(:erlang.now)\n\n The implementation assumes that the sample being returned\n can fit into memory.\n\n ## Examples\n\n iex> Enum.sample([1,2,3])\n 1\n iex> Enum.sample([1,2,3])\n 2\n iex> Enum.sample(1..10, 2)\n [5, 8]\n iex> Enum.sample(?a..?z, 5)\n 'vxmks'\n\n \"\"\"\n @spec sample(t) :: element | nil\n def sample(collection) do\n sample(collection, 1) |> List.first\n end\n\n @spec sample(t, integer) :: list\n def sample(collection, count) when count > 0 do\n sample = List.duplicate(nil, count) |> List.to_tuple\n\n reducer = fn x, {i, sample} ->\n if i < count do\n j = random_index(i)\n swapped = sample |> elem(j)\n {i + 1, sample |> put_elem(i, swapped) |> put_elem(j, x)}\n else\n j = random_index(i)\n if j < count, do: sample = sample |> put_elem(j, x)\n {i + 1, sample}\n end\n end\n\n {n, sample} = reduce(collection, {0, sample}, reducer)\n sample |> Tuple.to_list |> Enum.take(Kernel.min(count, n))\n end\n\n def sample(_collection, 0), do: []\n\n @doc \"\"\"\n Applies the given function to each element in the collection,\n storing the result in a list and passing it as the accumulator\n for the next computation.\n\n ## Examples\n\n iex> Enum.scan(1..5, &(&1 + &2))\n [1,3,6,10,15]\n\n \"\"\"\n @spec scan(t, (element, any -> any)) :: list\n def scan(enum, fun) do\n {_, {res, _}} =\n Enumerable.reduce(enum, {:cont, {[], :first}}, R.scan_2(fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Applies the given function to each element in the collection,\n storing the result in a list and passing it as the accumulator\n for the next computation. Uses the given `acc` as the starting value.\n\n ## Examples\n\n iex> Enum.scan(1..5, 0, &(&1 + &2))\n [1,3,6,10,15]\n\n \"\"\"\n @spec scan(t, any, (element, any -> any)) :: list\n def scan(enum, acc, fun) do\n {_, {res, _}} =\n Enumerable.reduce(enum, {:cont, {[], acc}}, R.scan_3(fun))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Returns a list of collection elements shuffled.\n\n Notice that you need to explicitly call `:random.seed\/1` and\n set a seed value for the random algorithm. Otherwise, the\n default seed will be set which will always return the same\n result. For example, one could do the following to set a seed\n dynamically:\n\n :random.seed(:erlang.now)\n\n ## Examples\n\n iex> Enum.shuffle([1, 2, 3])\n [3, 2, 1]\n iex> Enum.shuffle([1, 2, 3])\n [3, 1, 2]\n\n \"\"\"\n @spec shuffle(t) :: list\n def shuffle(collection) do\n randomized = reduce(collection, [], fn x, acc ->\n [{:random.uniform, x}|acc]\n end)\n unwrap(:lists.keysort(1, randomized), [])\n end\n\n @doc \"\"\"\n Returns a subset list of the given collection. Drops elements\n until element position `start`, then takes `count` elements.\n \n If the count is greater than collection length, it returns as\n much as possible. If zero, then it returns `[]`.\n\n ## Examples\n\n iex> Enum.slice(1..100, 5, 10)\n [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n\n iex> Enum.slice(1..10, 5, 100)\n [6, 7, 8, 9, 10]\n\n iex> Enum.slice(1..10, 5, 0)\n []\n\n \"\"\"\n @spec slice(t, integer, non_neg_integer) :: list\n \n def slice(_coll, _start, 0), do: []\n\n def slice(coll, start, count) when start < 0 do\n {list, new_start} = enumerate_and_count(coll, start)\n if new_start >= 0 do\n slice(list, new_start, count)\n else\n []\n end\n end\n\n def slice(coll, start, count) when is_list(coll) and start >= 0 and count > 0 do\n do_slice(coll, start, count)\n end\n\n def slice(coll, start, count) when start >= 0 and count > 0 do\n {_, _, list} = Enumerable.reduce(coll, {:cont, {start, count, []}}, fn\n _entry, {start, count, _list} when start > 0 ->\n {:cont, {start-1, count, []}}\n entry, {start, count, list} when count > 1 ->\n {:cont, {start, count-1, [entry|list]}}\n entry, {start, count, list} ->\n {:halt, {start, count, [entry|list]}}\n end) |> elem(1)\n\n :lists.reverse(list)\n end\n\n @doc \"\"\"\n Returns a subset list of the given collection. Drops elements\n until element position `range.first`, then takes elements until element\n position `range.last` (inclusive).\n\n Positions are calculated by adding the number of items in the collection to\n negative positions (so position -3 in a collection with count 5 becomes\n position 2).\n\n The first position (after adding count to negative positions) must be smaller\n or equal to the last position.\n\n If the start of the range is not a valid offset for the given\n collection or if the range is in reverse order, returns `[]`.\n\n ## Examples\n\n iex> Enum.slice(1..100, 5..10)\n [6, 7, 8, 9, 10, 11]\n\n iex> Enum.slice(1..10, 5..20)\n [6, 7, 8, 9, 10]\n\n iex> Enum.slice(1..10, 11..20)\n []\n\n iex> Enum.slice(1..10, 6..5)\n []\n\n \"\"\"\n @spec slice(t, Range.t) :: list\n def slice(coll, first..last) when first >= 0 and last >= 0 do\n # Simple case, which works on infinite collections\n if last - first >= 0 do\n slice(coll, first, last - first + 1)\n else\n []\n end\n end\n\n def slice(coll, first..last) do\n {list, count} = enumerate_and_count(coll, 0)\n corr_first = if first >= 0, do: first, else: first + count\n corr_last = if last >= 0, do: last, else: last + count\n length = corr_last - corr_first + 1\n if corr_first >= 0 and length > 0 do\n slice(list, corr_first, length)\n else\n []\n end\n end\n\n @doc \"\"\"\n Sorts the collection according to Elixir's term ordering.\n\n Uses the merge sort algorithm.\n\n ## Examples\n\n iex> Enum.sort([3, 2, 1])\n [1, 2, 3]\n\n \"\"\"\n @spec sort(t) :: list\n def sort(collection) when is_list(collection) do\n :lists.sort(collection)\n end\n\n def sort(collection) do\n sort(collection, &(&1 <= &2))\n end\n\n @doc \"\"\"\n Sorts the collection by the given function.\n\n This function uses the merge sort algorithm. The given function\n must return false if the first argument is less than right one.\n\n ## Examples\n\n iex> Enum.sort([1, 2, 3], &(&1 > &2))\n [3, 2, 1]\n\n The sorting algorithm will be stable as long as the given function\n returns true for values considered equal:\n\n iex> Enum.sort [\"some\", \"kind\", \"of\", \"monster\"], &(byte_size(&1) <= byte_size(&2))\n [\"of\", \"some\", \"kind\", \"monster\"]\n\n If the function does not return true, the sorting is not stable and\n the order of equal terms may be shuffled:\n\n iex> Enum.sort [\"some\", \"kind\", \"of\", \"monster\"], &(byte_size(&1) < byte_size(&2))\n [\"of\", \"kind\", \"some\", \"monster\"]\n\n \"\"\"\n @spec sort(t, (element, element -> boolean)) :: list\n def sort(collection, fun) when is_list(collection) do\n :lists.sort(fun, collection)\n end\n\n def sort(collection, fun) do\n reduce(collection, [], &sort_reducer(&1, &2, fun)) |> sort_terminator(fun)\n end\n\n @doc \"\"\"\n Sorts the mapped results of the `collection` according to the `sorter` function.\n\n This function maps each element of the collection using the `mapper`\n function. The collection is then sorted by the mapped elements using the\n `sorter` function, which defaults to `<=\/2`\n\n `sort_by\/3` differs from `sort\/2` in that it only calculates the comparison\n value for each element in the collection once instead of once for each\n element in each comparison. If the same function is being called on both\n element, it's also more compact to use `sort_by\/3`.\n\n This technique is also known as a\n [Schwartzian Transform](https:\/\/en.wikipedia.org\/wiki\/Schwartzian_transform),\n or the Lisp decorate-sort-undecorate idiom as the `mapper` is decorating the\n original `collection`, then `sorter` is sorting the decorations, and finally\n the `collection` is being undecorated so only the original elements remain,\n but now in sorted order.\n\n ## Examples\n\n Using the default `sorter` of `<=\/2`:\n\n iex> Enum.sort_by [\"some\", \"kind\", \"of\", \"monster\"], &byte_size\/1\n [\"of\", \"some\", \"kind\", \"monster\"]\n\n Using a custom `sorter` to override the order:\n\n iex> Enum.sort_by [\"some\", \"kind\", \"of\", \"monster\"], &byte_size\/1, &>=\/2\n [\"monster\", \"some\", \"kind\", \"of\"]\n\n \"\"\"\n @spec sort_by(t, (element -> mapped_element), (mapped_element, mapped_element -> boolean)) :: list when mapped_element: element\n def sort_by(collection, mapper, sorter \\\\ &<=\/2) do\n collection \n |> map(&{&1, mapper.(&1)})\n |> sort(&sorter.(elem(&1, 1), elem(&2, 1)))\n |> map(&elem(&1, 0))\n end\n\n @doc \"\"\"\n Splits the enumerable into two collections, leaving `count`\n elements in the first one. If `count` is a negative number,\n it starts counting from the back to the beginning of the\n collection.\n\n Be aware that a negative `count` implies the collection\n will be enumerated twice: once to calculate the position, and\n a second time to do the actual splitting.\n\n ## Examples\n\n iex> Enum.split([1, 2, 3], 2)\n {[1,2], [3]}\n\n iex> Enum.split([1, 2, 3], 10)\n {[1,2,3], []}\n\n iex> Enum.split([1, 2, 3], 0)\n {[], [1,2,3]}\n\n iex> Enum.split([1, 2, 3], -1)\n {[1,2], [3]}\n\n iex> Enum.split([1, 2, 3], -5)\n {[], [1,2,3]}\n\n \"\"\"\n @spec split(t, integer) :: {list, list}\n def split(collection, count) when is_list(collection) and count >= 0 do\n do_split(collection, count, [])\n end\n\n def split(collection, count) when count >= 0 do\n {_, list1, list2} =\n reduce(collection, {count, [], []}, fn(entry, {counter, acc1, acc2}) ->\n if counter > 0 do\n {counter - 1, [entry|acc1], acc2}\n else\n {counter, acc1, [entry|acc2]}\n end\n end)\n\n {:lists.reverse(list1), :lists.reverse(list2)}\n end\n\n def split(collection, count) when count < 0 do\n do_split_reverse(reverse(collection), abs(count), [])\n end\n\n @doc \"\"\"\n Splits `collection` in two while `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.split_while([1, 2, 3, 4], fn(x) -> x < 3 end)\n {[1, 2], [3, 4]}\n\n \"\"\"\n @spec split_while(t, (element -> as_boolean(term))) :: {list, list}\n def split_while(collection, fun) when is_list(collection) do\n do_split_while(collection, fun, [])\n end\n\n def split_while(collection, fun) do\n {list1, list2} =\n reduce(collection, {[], []}, fn\n entry, {acc1, []} ->\n if(fun.(entry), do: {[entry|acc1], []}, else: {acc1, [entry]})\n entry, {acc1, acc2} ->\n {acc1, [entry|acc2]}\n end)\n\n {:lists.reverse(list1), :lists.reverse(list2)}\n end\n\n @doc \"\"\"\n Takes the first `count` items from the collection.\n\n If a negative `count` is given, the last `count` values will\n be taken. For such, the collection is fully enumerated keeping up\n to `2 * count` elements in memory. Once the end of the collection is\n reached, the last `count` elements are returned.\n\n ## Examples\n\n iex> Enum.take([1, 2, 3], 2)\n [1,2]\n\n iex> Enum.take([1, 2, 3], 10)\n [1,2,3]\n\n iex> Enum.take([1, 2, 3], 0)\n []\n\n iex> Enum.take([1, 2, 3], -1)\n [3]\n\n \"\"\"\n @spec take(t, integer) :: list\n\n def take(_collection, 0) do\n []\n end\n\n def take(collection, count) when is_list(collection) and count > 0 do\n do_take(collection, count)\n end\n\n def take(collection, count) when count > 0 do\n {_, {res, _}} =\n Enumerable.reduce(collection, {:cont, {[], count}}, fn(entry, {list, count}) ->\n if count > 1 do\n {:cont, {[entry|list], count - 1}}\n else\n {:halt, {[entry|list], count}}\n end\n end)\n :lists.reverse(res)\n end\n\n def take(collection, count) when count < 0 do\n Stream.take(collection, count).({:cont, []}, &{:cont, [&1|&2]})\n |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Returns a collection of every `nth` item in the collection,\n starting with the first element.\n\n ## Examples\n\n iex> Enum.take_every(1..10, 2)\n [1, 3, 5, 7, 9]\n\n \"\"\"\n @spec take_every(t, integer) :: list\n def take_every(_collection, 0), do: []\n def take_every(collection, nth) do\n {_, {res, _}} =\n Enumerable.reduce(collection, {:cont, {[], :first}}, R.take_every(nth))\n :lists.reverse(res)\n end\n\n @doc \"\"\"\n Takes the items at the beginning of `collection` while `fun` returns `true`.\n\n ## Examples\n\n iex> Enum.take_while([1, 2, 3], fn(x) -> x < 3 end)\n [1, 2]\n\n \"\"\"\n @spec take_while(t, (element -> as_boolean(term))) :: list\n def take_while(collection, fun) when is_list(collection) do\n do_take_while(collection, fun)\n end\n\n def take_while(collection, fun) do\n Enumerable.reduce(collection, {:cont, []}, R.take_while(fun))\n |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Convert `collection` to a list.\n\n ## Examples\n\n iex> Enum.to_list(1 .. 3)\n [1, 2, 3]\n\n \"\"\"\n @spec to_list(t) :: [term]\n def to_list(collection) when is_list(collection) do\n collection\n end\n\n def to_list(collection) do\n reverse(collection) |> :lists.reverse\n end\n\n\n @doc \"\"\"\n Traverses the given enumerable keeping its shape.\n\n It also expects the enumerable to implement the `Collectable` protocol.\n\n ## Examples\n\n iex> Enum.traverse(%{a: 1, b: 2}, fn {k, v} -> {k, v * 2} end)\n %{a: 2, b: 4}\n\n \"\"\"\n @spec traverse(Enumerable.t, (term -> term)) :: Collectable.t\n def traverse(collection, transform) when is_list(collection) do\n :lists.map(transform, collection)\n end\n\n def traverse(collection, transform) do\n into(collection, Collectable.empty(collection), transform)\n end\n\n @doc \"\"\"\n Enumerates the collection, removing all duplicated items.\n\n ## Examples\n\n iex> Enum.uniq([1, 2, 3, 2, 1])\n [1, 2, 3]\n\n iex> Enum.uniq([{1, :x}, {2, :y}, {1, :z}], fn {x, _} -> x end)\n [{1,:x}, {2,:y}]\n\n \"\"\"\n @spec uniq(t) :: list\n @spec uniq(t, (element -> term)) :: list\n def uniq(collection, fun \\\\ fn x -> x end)\n\n def uniq(collection, fun) when is_list(collection) do\n do_uniq(collection, [], fun)\n end\n\n def uniq(collection, fun) do\n {_, {list, _}} =\n Enumerable.reduce(collection, {:cont, {[], []}}, R.uniq(fun))\n :lists.reverse(list)\n end\n\n @doc \"\"\"\n Zips corresponding elements from two collections into one list\n of tuples.\n\n The zipping finishes as soon as any enumerable completes.\n\n ## Examples\n\n iex> Enum.zip([1, 2, 3], [:a, :b, :c])\n [{1,:a},{2,:b},{3,:c}]\n\n iex> Enum.zip([1,2,3,4,5], [:a, :b, :c])\n [{1,:a},{2,:b},{3,:c}]\n\n \"\"\"\n @spec zip(t, t) :: [{any, any}]\n def zip(coll1, coll2) when is_list(coll1) and is_list(coll2) do\n do_zip(coll1, coll2)\n end\n\n def zip(coll1, coll2) do\n Stream.zip(coll1, coll2).({:cont, []}, &{:cont, [&1|&2]}) |> elem(1) |> :lists.reverse\n end\n\n @doc \"\"\"\n Returns the collection with each element wrapped in a tuple\n alongside its index.\n\n ## Examples\n\n iex> Enum.with_index [1,2,3]\n [{1,0},{2,1},{3,2}]\n\n \"\"\"\n @spec with_index(t) :: list({element, non_neg_integer})\n def with_index(collection) do\n map_reduce(collection, 0, fn x, acc ->\n {{x, acc}, acc + 1}\n end) |> elem(0)\n end\n\n ## Helpers\n\n @compile {:inline, enum_to_string: 1}\n\n defp enumerate_and_count(collection, count) when is_list(collection) do\n {collection, length(collection) - abs(count)}\n end\n\n defp enumerate_and_count(collection, count) do\n map_reduce(collection, -abs(count), fn(x, acc) -> {x, acc + 1} end)\n end\n\n defp enum_to_string(entry) when is_binary(entry), do: entry\n defp enum_to_string(entry), do: String.Chars.to_string(entry)\n\n defp random_index(n) do\n :random.uniform(n + 1) - 1\n end\n\n ## Implementations\n\n ## all?\n\n defp do_all?([h|t], fun) do\n if fun.(h) do\n do_all?(t, fun)\n else\n false\n end\n end\n\n defp do_all?([], _) do\n true\n end\n\n ## any?\n\n defp do_any?([h|t], fun) do\n if fun.(h) do\n true\n else\n do_any?(t, fun)\n end\n end\n\n defp do_any?([], _) do\n false\n end\n\n ## fetch\n\n defp do_fetch([h|_], 0), do: {:ok, h}\n defp do_fetch([_|t], n), do: do_fetch(t, n - 1)\n defp do_fetch([], _), do: :error\n\n ## drop\n\n defp do_drop([_|t], counter) when counter > 0 do\n do_drop(t, counter - 1)\n end\n\n defp do_drop(list, 0) do\n list\n end\n\n defp do_drop([], _) do\n []\n end\n\n ## drop_while\n\n defp do_drop_while([h|t], fun) do\n if fun.(h) do\n do_drop_while(t, fun)\n else\n [h|t]\n end\n end\n\n defp do_drop_while([], _) do\n []\n end\n\n ## find\n\n defp do_find([h|t], ifnone, fun) do\n if fun.(h) do\n h\n else\n do_find(t, ifnone, fun)\n end\n end\n\n defp do_find([], ifnone, _) do\n ifnone\n end\n\n ## find_index\n\n defp do_find_index([h|t], counter, fun) do\n if fun.(h) do\n counter\n else\n do_find_index(t, counter + 1, fun)\n end\n end\n\n defp do_find_index([], _, _) do\n nil\n end\n\n ## find_value\n\n defp do_find_value([h|t], ifnone, fun) do\n fun.(h) || do_find_value(t, ifnone, fun)\n end\n\n defp do_find_value([], ifnone, _) do\n ifnone\n end\n\n ## shuffle\n\n defp unwrap([{_, h} | collection], t) do\n unwrap(collection, [h|t])\n end\n\n defp unwrap([], t), do: t\n\n ## sort\n\n defp sort_reducer(entry, {:split, y, x, r, rs, bool}, fun) do\n cond do\n fun.(y, entry) == bool ->\n {:split, entry, y, [x|r], rs, bool}\n fun.(x, entry) == bool ->\n {:split, y, entry, [x|r], rs, bool}\n r == [] ->\n {:split, y, x, [entry], rs, bool}\n true ->\n {:pivot, y, x, r, rs, entry, bool}\n end\n end\n\n defp sort_reducer(entry, {:pivot, y, x, r, rs, s, bool}, fun) do\n cond do\n fun.(y, entry) == bool ->\n {:pivot, entry, y, [x | r], rs, s, bool}\n fun.(x, entry) == bool ->\n {:pivot, y, entry, [x | r], rs, s, bool}\n fun.(s, entry) == bool ->\n {:split, entry, s, [], [[y, x | r] | rs], bool}\n true ->\n {:split, s, entry, [], [[y, x | r] | rs], bool}\n end\n end\n\n defp sort_reducer(entry, [x], fun) do\n {:split, entry, x, [], [], fun.(x, entry)}\n end\n\n defp sort_reducer(entry, acc, _fun) do\n [entry|acc]\n end\n\n defp sort_terminator({:split, y, x, r, rs, bool}, fun) do\n sort_merge([[y, x | r] | rs], fun, bool)\n end\n\n defp sort_terminator({:pivot, y, x, r, rs, s, bool}, fun) do\n sort_merge([[s], [y, x | r] | rs], fun, bool)\n end\n\n defp sort_terminator(acc, _fun) do\n acc\n end\n\n defp sort_merge(list, fun, true), do:\n reverse_sort_merge(list, [], fun, true)\n\n defp sort_merge(list, fun, false), do:\n sort_merge(list, [], fun, false)\n\n\n defp sort_merge([t1, [h2 | t2] | l], acc, fun, true), do:\n sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, false) | acc], fun, true)\n\n defp sort_merge([[h2 | t2], t1 | l], acc, fun, false), do:\n sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, false) | acc], fun, false)\n\n defp sort_merge([l], [], _fun, _bool), do: l\n\n defp sort_merge([l], acc, fun, bool), do:\n reverse_sort_merge([:lists.reverse(l, []) | acc], [], fun, bool)\n\n defp sort_merge([], acc, fun, bool), do:\n reverse_sort_merge(acc, [], fun, bool)\n\n\n defp reverse_sort_merge([[h2 | t2], t1 | l], acc, fun, true), do:\n reverse_sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, true) | acc], fun, true)\n\n defp reverse_sort_merge([t1, [h2 | t2] | l], acc, fun, false), do:\n reverse_sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, true) | acc], fun, false)\n\n defp reverse_sort_merge([l], acc, fun, bool), do:\n sort_merge([:lists.reverse(l, []) | acc], [], fun, bool)\n\n defp reverse_sort_merge([], acc, fun, bool), do:\n sort_merge(acc, [], fun, bool)\n\n\n defp sort_merge_1([h1 | t1], h2, t2, m, fun, bool) do\n if fun.(h1, h2) == bool do\n sort_merge_2(h1, t1, t2, [h2 | m], fun, bool)\n else\n sort_merge_1(t1, h2, t2, [h1 | m], fun, bool)\n end\n end\n\n defp sort_merge_1([], h2, t2, m, _fun, _bool), do:\n :lists.reverse(t2, [h2 | m])\n\n\n defp sort_merge_2(h1, t1, [h2 | t2], m, fun, bool) do\n if fun.(h1, h2) == bool do\n sort_merge_2(h1, t1, t2, [h2 | m], fun, bool)\n else\n sort_merge_1(t1, h2, t2, [h1 | m], fun, bool)\n end\n end\n\n defp sort_merge_2(h1, t1, [], m, _fun, _bool), do:\n :lists.reverse(t1, [h1 | m])\n\n ## split\n\n defp do_split([h|t], counter, acc) when counter > 0 do\n do_split(t, counter - 1, [h|acc])\n end\n\n defp do_split(list, 0, acc) do\n {:lists.reverse(acc), list}\n end\n\n defp do_split([], _, acc) do\n {:lists.reverse(acc), []}\n end\n\n defp do_split_reverse([h|t], counter, acc) when counter > 0 do\n do_split_reverse(t, counter - 1, [h|acc])\n end\n\n defp do_split_reverse(list, 0, acc) do\n {:lists.reverse(list), acc}\n end\n\n defp do_split_reverse([], _, acc) do\n {[], acc}\n end\n\n ## split_while\n\n defp do_split_while([h|t], fun, acc) do\n if fun.(h) do\n do_split_while(t, fun, [h|acc])\n else\n {:lists.reverse(acc), [h|t]}\n end\n end\n\n defp do_split_while([], _, acc) do\n {:lists.reverse(acc), []}\n end\n\n ## take\n\n defp do_take([h|t], counter) when counter > 0 do\n [h|do_take(t, counter - 1)]\n end\n\n defp do_take(_list, 0) do\n []\n end\n\n defp do_take([], _) do\n []\n end\n\n ## take_while\n\n defp do_take_while([h|t], fun) do\n if fun.(h) do\n [h|do_take_while(t, fun)]\n else\n []\n end\n end\n\n defp do_take_while([], _) do\n []\n end\n\n ## uniq\n\n defp do_uniq([h|t], acc, fun) do\n fun_h = fun.(h)\n case :lists.member(fun_h, acc) do\n true -> do_uniq(t, acc, fun)\n false -> [h|do_uniq(t, [fun_h|acc], fun)]\n end\n end\n\n defp do_uniq([], _acc, _fun) do\n []\n end\n\n ## zip\n\n defp do_zip([h1|next1], [h2|next2]) do\n [{h1, h2}|do_zip(next1, next2)]\n end\n\n defp do_zip(_, []), do: []\n defp do_zip([], _), do: []\n\n ## slice\n\n defp do_slice([], _start, _count) do\n []\n end\n\n defp do_slice(_list, _start, 0) do\n []\n end\n\n defp do_slice([h|t], 0, count) do\n [h|do_slice(t, 0, count-1)]\n end\n\n defp do_slice([_|t], start, count) do\n do_slice(t, start-1, count)\n end\nend\n\ndefimpl Enumerable, for: List do\n def reduce(_, {:halt, acc}, _fun), do: {:halted, acc}\n def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)}\n def reduce([], {:cont, acc}, _fun), do: {:done, acc}\n def reduce([h|t], {:cont, acc}, fun), do: reduce(t, fun.(h, acc), fun)\n\n def member?(_list, _value),\n do: {:error, __MODULE__}\n def count(_list),\n do: {:error, __MODULE__}\nend\n\ndefimpl Enumerable, for: Map do\n def reduce(map, acc, fun) do\n do_reduce(:maps.to_list(map), acc, fun)\n end\n\n defp do_reduce(_, {:halt, acc}, _fun), do: {:halted, acc}\n defp do_reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &do_reduce(list, &1, fun)}\n defp do_reduce([], {:cont, acc}, _fun), do: {:done, acc}\n defp do_reduce([h|t], {:cont, acc}, fun), do: do_reduce(t, fun.(h, acc), fun)\n\n def member?(map, {key, value}) do\n {:ok, match?({:ok, ^value}, :maps.find(key, map))}\n end\n\n def member?(_map, _other) do\n {:ok, false}\n end\n\n def count(map) do\n {:ok, map_size(map)}\n end\nend\n\ndefimpl Enumerable, for: Function do\n def reduce(function, acc, fun) when is_function(function, 2),\n do: function.(acc, fun)\n def member?(_function, _value),\n do: {:error, __MODULE__}\n def count(_function),\n do: {:error, __MODULE__}\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"78872181cf9929334a39a9fa3a8b7351b67876a7","subject":"Add collapse lines to algebra","message":"Add collapse lines to algebra\n","repos":"beedub\/elixir,lexmag\/elixir,ggcampinho\/elixir,kelvinst\/elixir,joshprice\/elixir,lexmag\/elixir,elixir-lang\/elixir,antipax\/elixir,kelvinst\/elixir,gfvcastro\/elixir,kimshrier\/elixir,pedrosnk\/elixir,ggcampinho\/elixir,gfvcastro\/elixir,michalmuskala\/elixir,pedrosnk\/elixir,beedub\/elixir,antipax\/elixir,kimshrier\/elixir","old_file":"lib\/elixir\/lib\/inspect\/algebra.ex","new_file":"lib\/elixir\/lib\/inspect\/algebra.ex","new_contents":"defmodule Inspect.Opts do\n @moduledoc \"\"\"\n Defines the Inspect.Opts used by the Inspect protocol.\n\n The following fields are available:\n\n * `:structs` - when `false`, structs are not formatted by the inspect\n protocol, they are instead printed as maps, defaults to `true`.\n\n * `:binaries` - when `:as_strings` all binaries will be printed as strings,\n non-printable bytes will be escaped.\n\n When `:as_binaries` all binaries will be printed in bit syntax.\n\n When the default `:infer`, the binary will be printed as a string if it\n is printable, otherwise in bit syntax.\n\n * `:charlists` - when `:as_charlists` all lists will be printed as char\n lists, non-printable elements will be escaped.\n\n When `:as_lists` all lists will be printed as lists.\n\n When the default `:infer`, the list will be printed as a charlist if it\n is printable, otherwise as list.\n\n * `:limit` - limits the number of items that are printed for tuples,\n bitstrings, maps, lists and any other collection of items. It does not\n apply to strings nor charlists and defaults to 50.\n\n * `:printable_limit` - limits the number of bytes that are printed for strings\n and char lists. Defaults to 4096.\n\n * `:pretty` - if set to `true` enables pretty printing, defaults to `false`.\n\n * `:width` - defaults to 80 characters, used when pretty is `true` or when\n printing to IO devices. Set to 0 to force each item to be printed on its\n own line.\n\n * `:base` - prints integers as `:binary`, `:octal`, `:decimal`, or `:hex`,\n defaults to `:decimal`. When inspecting binaries any `:base` other than\n `:decimal` implies `binaries: :as_binaries`.\n\n * `:safe` - when `false`, failures while inspecting structs will be raised\n as errors instead of being wrapped in the `Inspect.Error` exception. This\n is useful when debugging failures and crashes for custom inspect\n implementations\n\n * `:syntax_colors` - when set to a keyword list of colors the output will\n be colorized. The keys are types and the values are the colors to use for\n each type. e.g. `[number: :red, atom: :blue]`. Types can include\n `:number`, `:atom`, `regex`, `:tuple`, `:map`, `:list`, and `:reset`.\n Colors can be any `t:IO.ANSI.ansidata\/0` as accepted by `IO.ANSI.format\/1`.\n \"\"\"\n\n # TODO: Remove :char_lists key by 2.0\n defstruct structs: true,\n binaries: :infer,\n charlists: :infer,\n char_lists: :infer,\n limit: 50,\n printable_limit: 4096,\n width: 80,\n base: :decimal,\n pretty: false,\n safe: true,\n syntax_colors: []\n\n @type color_key :: atom\n\n # TODO: Remove :char_lists key and :as_char_lists value by 2.0\n @type t :: %__MODULE__{\n structs: boolean,\n binaries: :infer | :as_binaries | :as_strings,\n charlists: :infer | :as_lists | :as_charlists,\n char_lists: :infer | :as_lists | :as_char_lists,\n limit: pos_integer | :infinity,\n printable_limit: pos_integer | :infinity,\n width: pos_integer | :infinity,\n base: :decimal | :binary | :hex | :octal,\n pretty: boolean,\n safe: boolean,\n syntax_colors: [{color_key, IO.ANSI.ansidata}]\n }\nend\n\ndefmodule Inspect.Error do\n @moduledoc \"\"\"\n Raised when a struct cannot be inspected.\n \"\"\"\n defexception [:message]\nend\n\ndefmodule Inspect.Algebra do\n @moduledoc ~S\"\"\"\n A set of functions for creating and manipulating algebra\n documents.\n\n This module implements the functionality described in\n [\"Strictly Pretty\" (2000) by Christian Lindig][0] with small\n additions, like support for binary nodes and a break mode that\n maximises use of horizontal space.\n\n iex> Inspect.Algebra.empty\n :doc_nil\n\n iex> \"foo\"\n \"foo\"\n\n With the functions in this module, we can concatenate different\n elements together and render them:\n\n iex> doc = Inspect.Algebra.concat(Inspect.Algebra.empty, \"foo\")\n iex> Inspect.Algebra.format(doc, 80)\n [\"foo\"]\n\n The functions `nest\/2`, `space\/2` and `line\/2` help you put the\n document together into a rigid structure. However, the document\n algebra gets interesting when using functions like `glue\/3` and\n `group\/1`. A glue inserts a break between two documents. A group\n indicates a document that must fit the current line, otherwise\n breaks are rendered as new lines. Let's glue two docs together\n with a break, group it and then render it:\n\n iex> doc = Inspect.Algebra.glue(\"a\", \" \", \"b\")\n iex> doc = Inspect.Algebra.group(doc)\n iex> Inspect.Algebra.format(doc, 80)\n [\"a\", \" \", \"b\"]\n\n Notice the break was represented as is, because we haven't reached\n a line limit. Once we do, it is replaced by a newline:\n\n iex> doc = Inspect.Algebra.glue(String.duplicate(\"a\", 20), \" \", \"b\")\n iex> doc = Inspect.Algebra.group(doc)\n iex> Inspect.Algebra.format(doc, 10)\n [\"aaaaaaaaaaaaaaaaaaaa\", \"\\n\", \"b\"]\n\n This module uses the byte size to compute how much space there is\n left. If your document contains strings, then those need to be\n wrapped in `string\/1`, which then relies on `String.length\/1` to\n precompute the document size.\n\n Finally, this module also contains Elixir related functions, a bit\n tied to Elixir formatting, namely `surround\/3` and `surround_many\/5`.\n\n ## Implementation details\n\n The original Haskell implementation of the algorithm by [Wadler][1]\n relies on lazy evaluation to unfold document groups on two alternatives:\n `:flat` (breaks as spaces) and `:break` (breaks as newlines).\n Implementing the same logic in a strict language such as Elixir leads\n to an exponential growth of possible documents, unless groups are explicitly\n encoded. Those groups are then reduced to a simple document, where the\n layout is already decided, per [Lindig][0].\n\n This implementation has two types of breaks: `:strict` and `:flex`. When\n a group does not fit, all strict breaks are treated as breaks. The flex\n breaks however are re-evaluated and may still be rendered as spaces.\n\n This implementation also adds `force_break\/1` and `cancel_break\/2` which\n give more control over the document fitting.\n\n Custom pretty printers can be implemented using the documents returned\n by this module and by providing their own rendering functions.\n\n [0]: http:\/\/citeseerx.ist.psu.edu\/viewdoc\/summary?doi=10.1.1.34.2200\n [1]: http:\/\/homepages.inf.ed.ac.uk\/wadler\/papers\/prettier\/prettier.pdf\n\n \"\"\"\n\n @surround_separator \",\"\n @tail_separator \" |\"\n @newline \"\\n\"\n @break :flex\n @cancel_break :enabled\n\n # Functional interface to \"doc\" records\n\n @type t ::\n binary\n | :doc_nil\n | :doc_line\n | doc_string\n | doc_cons\n | doc_nest\n | doc_break\n | doc_group\n | doc_color\n | doc_force\n | doc_cancel\n | doc_collapse\n\n @typep doc_string :: {:doc_string, t, non_neg_integer}\n defmacrop doc_string(string, length) do\n quote do: {:doc_string, unquote(string), unquote(length)}\n end\n\n @typep doc_cons :: {:doc_cons, t, t}\n defmacrop doc_cons(left, right) do\n quote do: {:doc_cons, unquote(left), unquote(right)}\n end\n\n @typep doc_nest :: {:doc_nest, t, :cursor | :reset | non_neg_integer, :always | :break}\n defmacrop doc_nest(doc, indent, always_or_break) do\n quote do: {:doc_nest, unquote(doc), unquote(indent), unquote(always_or_break)}\n end\n\n @typep doc_break :: {:doc_break, binary, :flex | :strict}\n defmacrop doc_break(break, mode) do\n quote do: {:doc_break, unquote(break), unquote(mode)}\n end\n\n @typep doc_group :: {:doc_group, t}\n defmacrop doc_group(group) do\n quote do: {:doc_group, unquote(group)}\n end\n\n @typep doc_cancel :: {:doc_cancel, t, :enabled | :disabled}\n defmacrop doc_cancel(group, mode) do\n quote do: {:doc_cancel, unquote(group), unquote(mode)}\n end\n\n @typep doc_force :: {:doc_force, t}\n defmacrop doc_force(group) do\n quote do: {:doc_force, unquote(group)}\n end\n\n @typep doc_collapse :: {:doc_collapse, pos_integer()}\n defmacrop doc_collapse(count) do\n quote do: {:doc_collapse, unquote(count)}\n end\n\n @typep doc_color :: {:doc_color, t, IO.ANSI.ansidata}\n defmacrop doc_color(doc, color) do\n quote do: {:doc_color, unquote(doc), unquote(color)}\n end\n\n defmacrop is_doc(doc) do\n if Macro.Env.in_guard?(__CALLER__) do\n do_is_doc(doc)\n else\n var = quote do: doc\n quote do\n unquote(var) = unquote(doc)\n unquote(do_is_doc(var))\n end\n end\n end\n\n defp do_is_doc(doc) do\n quote do\n is_binary(unquote(doc)) or\n unquote(doc) in [:doc_nil, :doc_line] or\n (is_tuple(unquote(doc)) and\n elem(unquote(doc), 0) in [:doc_string, :doc_cons, :doc_nest, :doc_break, :doc_group,\n :doc_color, :doc_force, :doc_cancel, :doc_collapse])\n end\n end\n\n @doc \"\"\"\n Converts an Elixir term to an algebra document\n according to the `Inspect` protocol.\n \"\"\"\n @spec to_doc(any, Inspect.Opts.t) :: t\n def to_doc(term, opts)\n\n def to_doc(%_{} = struct, %Inspect.Opts{} = opts) do\n if opts.structs do\n try do\n Inspect.inspect(struct, opts)\n rescue\n caught_exception ->\n stacktrace = System.stacktrace\n\n # Because we try to raise a nice error message in case\n # we can't inspect a struct, there is a chance the error\n # message itself relies on the struct being printed, so\n # we need to trap the inspected messages to guarantee\n # we won't try to render any failed instruct when building\n # the error message.\n if Process.get(:inspect_trap) do\n Inspect.Map.inspect(struct, opts)\n else\n try do\n Process.put(:inspect_trap, true)\n\n res = Inspect.Map.inspect(struct, %{opts | syntax_colors: []})\n res = IO.iodata_to_binary(format(res, :infinity))\n\n message =\n \"got #{inspect caught_exception.__struct__} with message \" <>\n \"#{inspect Exception.message(caught_exception)} while inspecting #{res}\"\n exception = Inspect.Error.exception(message: message)\n\n if opts.safe do\n Inspect.inspect(exception, opts)\n else\n reraise(exception, stacktrace)\n end\n after\n Process.delete(:inspect_trap)\n end\n end\n end\n else\n Inspect.Map.inspect(struct, opts)\n end\n end\n\n def to_doc(arg, %Inspect.Opts{} = opts) do\n Inspect.inspect(arg, opts)\n end\n\n @doc \"\"\"\n Returns a document entity used to represent nothingness.\n\n ## Examples\n\n iex> Inspect.Algebra.empty\n :doc_nil\n\n \"\"\"\n @spec empty() :: :doc_nil\n def empty, do: :doc_nil\n\n @doc ~S\"\"\"\n Creates a document represented by string.\n\n While `Inspect.Algebra` accepts binaries as documents,\n those are counted by binary size. On the other hand,\n `string` documents are measured in terms of graphemes\n towards the document size.\n\n ## Examples\n\n The following document has 10 bytes and therefore it\n does not format to width 9 without breaks:\n\n iex> doc = Inspect.Algebra.glue(\"ol\u00e1\", \" \", \"mundo\")\n iex> doc = Inspect.Algebra.group(doc)\n iex> Inspect.Algebra.format(doc, 9)\n [\"ol\u00e1\", \"\\n\", \"mundo\"]\n\n However, if we use `string`, then the string length is\n used, instead of byte size, correctly fitting:\n\n iex> string = Inspect.Algebra.string(\"ol\u00e1\")\n iex> doc = Inspect.Algebra.glue(string, \" \", \"mundo\")\n iex> doc = Inspect.Algebra.group(doc)\n iex> Inspect.Algebra.format(doc, 9)\n [\"ol\u00e1\", \" \", \"mundo\"]\n\n \"\"\"\n @spec string(String.t) :: doc_string\n def string(string) when is_binary(string) do\n doc_string(string, String.length(string))\n end\n\n @doc ~S\"\"\"\n Concatenates two document entities returning a new document.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.concat(\"hello\", \"world\")\n iex> Inspect.Algebra.format(doc, 80)\n [\"hello\", \"world\"]\n\n \"\"\"\n @spec concat(t, t) :: t\n def concat(doc1, doc2) when is_doc(doc1) and is_doc(doc2) do\n doc_cons(doc1, doc2)\n end\n\n @doc ~S\"\"\"\n Concatenates a list of documents returning a new document.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.concat([\"a\", \"b\", \"c\"])\n iex> Inspect.Algebra.format(doc, 80)\n [\"a\", \"b\", \"c\"]\n\n \"\"\"\n @spec concat([t]) :: t\n def concat(docs) when is_list(docs) do\n fold_doc(docs, &concat(&1, &2))\n end\n\n @doc ~S\"\"\"\n Colors a document if the `color_key` has a color in the options.\n \"\"\"\n @spec color(t, Inspect.Opts.color_key, Inspect.Opts.t) :: doc_color\n def color(doc, color_key, %Inspect.Opts{syntax_colors: syntax_colors}) when is_doc(doc) do\n if precolor = Keyword.get(syntax_colors, color_key) do\n postcolor = Keyword.get(syntax_colors, :reset, :reset)\n concat(doc_color(doc, precolor), doc_color(empty(), postcolor))\n else\n doc\n end\n end\n\n @doc ~S\"\"\"\n Nests the given document at the given `level`.\n\n If `level` is an integer, that's the indentation appended\n to line breaks whenever they occur. If the level is `:cursor`,\n the current position of the \"cursor\" in the document becomes\n the nesting. If the level is `:reset`, it is set back to 0.\n\n `mode` can be `:always`, which means nesting always happen,\n or `:break`, which means nesting only happens inside a group\n that has been broken.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.nest(Inspect.Algebra.glue(\"hello\", \"world\"), 5)\n iex> doc = Inspect.Algebra.group(doc)\n iex> Inspect.Algebra.format(doc, 5)\n [\"hello\", \"\\n \", \"world\"]\n\n \"\"\"\n @spec nest(t, non_neg_integer) :: doc_nest\n def nest(doc, level, mode \\\\ :always)\n\n def nest(doc, :cursor, mode) when is_doc(doc) and mode in [:always, :break] do\n doc_nest(doc, :cursor, mode)\n end\n\n def nest(doc, :reset, mode) when is_doc(doc) and mode in [:always, :break] do\n doc_nest(doc, :reset, mode)\n end\n\n def nest(doc, 0, _mode) when is_doc(doc) do\n doc\n end\n\n def nest(doc, level, mode)\n when is_doc(doc) and is_integer(level) and level > 0 and mode in [:always, :break] do\n doc_nest(doc, level, mode)\n end\n\n @doc ~S\"\"\"\n Returns a document entity representing a break based on the given\n `string`.\n\n This break can be rendered as a linebreak or as the given `string`,\n depending on the `mode` of the chosen layout.\n\n ## Examples\n\n Let's create a document by concatenating two strings with a break between\n them:\n\n iex> doc = Inspect.Algebra.concat([\"a\", Inspect.Algebra.break(\"\\t\"), \"b\"])\n iex> Inspect.Algebra.format(doc, 80)\n [\"a\", \"\\t\", \"b\"]\n\n Notice the break was represented with the given string, because we didn't\n reach a line limit. Once we do, it is replaced by a newline:\n\n iex> break = Inspect.Algebra.break(\"\\t\")\n iex> doc = Inspect.Algebra.concat([String.duplicate(\"a\", 20), break, \"b\"])\n iex> doc = Inspect.Algebra.group(doc)\n iex> Inspect.Algebra.format(doc, 10)\n [\"aaaaaaaaaaaaaaaaaaaa\", \"\\n\", \"b\"]\n\n \"\"\"\n @spec break(binary) :: doc_break\n def break(string \\\\ \" \") when is_binary(string) do\n doc_break(string, :strict)\n end\n\n @doc \"\"\"\n Collapse any new lines and whitespace following this\n node and emitting up to `max` new lines.\n \"\"\"\n @spec collapse_lines(pos_integer) :: doc_collapse\n def collapse_lines(max) when is_integer(max) and max > 0 do\n doc_collapse(max)\n end\n\n @doc \"\"\"\n Considers the next break as fit.\n\n `mode` can be `:enabled` or `:disabled`. When `:enabled`,\n it will consider the document as fit as soon as it finds\n the next break, effectively cancelling the break. It will\n also ignore any `force_break\/1`.\n\n When disabled, it behaves as usual and it will ignore\n any furtger `cancel_break\/2` instruction.\n \"\"\"\n @spec cancel_break(t) :: doc_cancel\n def cancel_break(doc, mode \\\\ @cancel_break) when is_doc(doc) do\n doc_cancel(doc, mode)\n end\n\n @doc \"\"\"\n Forces the document to break.\n \"\"\"\n @spec force_break(t) :: doc_force\n def force_break(doc) when is_doc(doc) do\n doc_force(doc)\n end\n\n @doc \"\"\"\n Introduces a flex break.\n\n A flex break still causes a group to break, like\n a regular break, but it is re-evaluated when the\n documented is processed.\n\n This function is used by `surround\/4` and friends\n to the maximum amount of entries on the same line.\n \"\"\"\n @spec flex_break(binary) :: doc_break\n def flex_break(string \\\\ \" \") when is_binary(string) do\n doc_break(string, :flex)\n end\n\n @doc \"\"\"\n Glues two documents (`doc1` and `doc2`) inserting a\n `flex_break\/1` given by `break_string` between them.\n\n This function is used by `surround\/4` and friends\n to the maximum amount of entries on the same line.\n \"\"\"\n @spec flex_glue(t, binary, t) :: t\n def flex_glue(doc1, break_string \\\\ \" \", doc2) when is_binary(break_string) do\n concat(doc1, concat(flex_break(break_string), doc2))\n end\n\n @doc ~S\"\"\"\n Glues two documents (`doc1` and `doc2`) inserting the given\n break `break_string` between them.\n\n For more information on how the break is inserted, see `break\/1`.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.glue(\"hello\", \"world\")\n iex> Inspect.Algebra.format(doc, 80)\n [\"hello\", \" \", \"world\"]\n\n iex> doc = Inspect.Algebra.glue(\"hello\", \"\\t\", \"world\")\n iex> Inspect.Algebra.format(doc, 80)\n [\"hello\", \"\\t\", \"world\"]\n\n \"\"\"\n @spec glue(t, binary, t) :: t\n def glue(doc1, break_string \\\\ \" \", doc2) when is_binary(break_string) do\n concat(doc1, concat(break(break_string), doc2))\n end\n\n @doc ~S\"\"\"\n Returns a group containing the specified document `doc`.\n\n Documents in a group are attempted to be rendered together\n to the best of the renderer ability.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.group(\n ...> Inspect.Algebra.concat(\n ...> Inspect.Algebra.group(\n ...> Inspect.Algebra.concat(\n ...> \"Hello,\",\n ...> Inspect.Algebra.concat(\n ...> Inspect.Algebra.break,\n ...> \"A\"\n ...> )\n ...> )\n ...> ),\n ...> Inspect.Algebra.concat(\n ...> Inspect.Algebra.break,\n ...> \"B\"\n ...> )\n ...> ))\n iex> Inspect.Algebra.format(doc, 80)\n [\"Hello,\", \" \", \"A\", \" \", \"B\"]\n iex> Inspect.Algebra.format(doc, 6)\n [\"Hello,\", \"\\n\", \"A\", \"\\n\", \"B\"]\n\n \"\"\"\n @spec group(t) :: doc_group\n def group(doc) when is_doc(doc) do\n doc_group(doc)\n end\n\n @doc ~S\"\"\"\n Inserts a mandatory single space between two documents.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.space(\"Hughes\", \"Wadler\")\n iex> Inspect.Algebra.format(doc, 5)\n [\"Hughes\", \" \", \"Wadler\"]\n\n \"\"\"\n @spec space(t, t) :: t\n def space(doc1, doc2), do: concat(doc1, concat(\" \", doc2))\n\n @doc ~S\"\"\"\n A mandatory linebreak.\n\n A group with linebreaks will fit if all lines in the group fit.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.concat(\n ...> Inspect.Algebra.concat(\n ...> \"Hughes\",\n ...> Inspect.Algebra.line()\n ...> ), \"Wadler\"\n ...> )\n iex> Inspect.Algebra.format(doc, 80)\n [\"Hughes\", \"\\n\", \"Wadler\"]\n\n \"\"\"\n @spec line() :: t\n def line(), do: :doc_line\n\n @doc ~S\"\"\"\n Inserts a mandatory linebreak between two documents.\n\n See `line\/1`.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.line(\"Hughes\", \"Wadler\")\n iex> Inspect.Algebra.format(doc, 80)\n [\"Hughes\", \"\\n\", \"Wadler\"]\n\n \"\"\"\n @spec line(t, t) :: t\n def line(doc1, doc2), do: concat(doc1, concat(line(), doc2))\n\n @doc ~S\"\"\"\n Folds a list of documents into a document using the given folder function.\n\n The list of documents is folded \"from the right\"; in that, this function is\n similar to `List.foldr\/3`, except that it doesn't expect an initial\n accumulator and uses the last element of `docs` as the initial accumulator.\n\n ## Examples\n\n iex> docs = [\"A\", \"B\", \"C\"]\n iex> docs = Inspect.Algebra.fold_doc(docs, fn(doc, acc) ->\n ...> Inspect.Algebra.concat([doc, \"!\", acc])\n ...> end)\n iex> Inspect.Algebra.format(docs, 80)\n [\"A\", \"!\", \"B\", \"!\", \"C\"]\n\n \"\"\"\n @spec fold_doc([t], ((t, t) -> t)) :: t\n def fold_doc(docs, folder_fun)\n\n def fold_doc([], _folder_fun),\n do: empty()\n def fold_doc([doc], _folder_fun),\n do: doc\n def fold_doc([doc | docs], folder_fun) when is_function(folder_fun, 2),\n do: folder_fun.(doc, fold_doc(docs, folder_fun))\n\n # Elixir conveniences\n\n @doc ~S\"\"\"\n Surrounds a document with characters.\n\n Puts the given document `doc` between the `left` and `right` documents enclosing\n and nesting it. The document is marked as a group, to show the maximum as\n possible concisely together.\n\n ## Options\n\n * `:break` - controls if the break is `:strict` or `:flex`, see `group\/2`\n\n ## Examples\n\n iex> doc = Inspect.Algebra.surround(\"[\", Inspect.Algebra.glue(\"a\", \"b\"), \"]\")\n iex> doc = Inspect.Algebra.group(doc)\n iex> Inspect.Algebra.format(doc, 3)\n [\"[\", \"a\", \"\\n \", \"b\", \"]\"]\n\n \"\"\"\n # TODO: Reflect the @break default and nesting for flex on the formatter\n @spec surround(t, t, t, keyword()) :: t\n def surround(left, doc, right, opts \\\\ [])\n when is_doc(left) and is_doc(doc) and is_doc(right) and is_list(opts) do\n case Keyword.get(opts, :break, @break) do\n :flex ->\n concat(concat(left, nest(doc, 1)), right)\n :strict ->\n group(glue(nest(glue(left, \"\", doc), 2), \"\", right))\n end\n end\n\n @doc ~S\"\"\"\n Maps and glues a collection of items.\n\n It uses the given `left` and `right` documents as surrounding and the\n separator document `separator` to separate items in `docs`. A limit can be\n passed: when this limit is reached, this function stops gluing and outputs\n `\"...\"` instead.\n\n ## Options\n\n * `:separator` - the separator used between each doc\n\n Plus all options in `surround\/4`.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.surround_many(\"[\", Enum.to_list(1..5), \"]\",\n ...> %Inspect.Opts{limit: :infinity}, fn i, _opts -> to_string(i) end)\n iex> Inspect.Algebra.format(doc, 5) |> IO.iodata_to_binary\n \"[1,\\n 2,\\n 3,\\n 4,\\n 5]\"\n\n iex> doc = Inspect.Algebra.surround_many(\"[\", Enum.to_list(1..5), \"]\",\n ...> %Inspect.Opts{limit: 3}, fn i, _opts -> to_string(i) end)\n iex> Inspect.Algebra.format(doc, 20) |> IO.iodata_to_binary\n \"[1, 2, 3, ...]\"\n\n iex> doc = Inspect.Algebra.surround_many(\"[\", Enum.to_list(1..5), \"]\",\n ...> %Inspect.Opts{limit: 3}, fn i, _opts -> to_string(i) end, \"!\")\n iex> Inspect.Algebra.format(doc, 20) |> IO.iodata_to_binary\n \"[1! 2! 3! ...]\"\n\n \"\"\"\n @spec surround_many(t, [any], t, Inspect.Opts.t, (term, Inspect.Opts.t -> t), keyword) :: t\n def surround_many(left, docs, right, %Inspect.Opts{} = inspect, fun, opts \\\\ [])\n when is_doc(left) and is_list(docs) and is_doc(right) and is_function(fun, 2) do\n cond do\n is_list(opts) ->\n {separator, opts} = Keyword.pop(opts, :separator, @surround_separator)\n surround_many(left, docs, right, inspect, fun, separator, opts)\n is_doc(opts) ->\n # TODO: Deprecate on Elixir v1.8\n surround_many(left, docs, right, inspect, fun, opts, [])\n end\n end\n\n defp surround_many(left, [], right, _inspect, _fun, _sep, _opts) do\n concat(left, right)\n end\n\n defp surround_many(left, docs, right, inspect, fun, sep, opts) do\n break = Keyword.get(opts, :break, @break)\n surround(left, surround_each(docs, inspect.limit, inspect, fun, break, sep), right, opts)\n end\n\n defp surround_each(_, 0, _opts, _fun, _break, _sep) do\n \"...\"\n end\n\n defp surround_each([], _limit, _opts, _fun, _break, _sep) do\n :doc_nil\n end\n\n defp surround_each([h], limit, opts, fun, _break, _sep) do\n fun.(h, %{opts | limit: limit})\n end\n\n defp surround_each([h | t], limit, opts, fun, break, sep) when is_list(t) do\n limit = decrement(limit)\n h = fun.(h, %{opts | limit: limit})\n t = surround_each(t, limit, opts, fun, break, sep)\n do_join(h, t, break, sep)\n end\n\n defp surround_each([h | t], limit, opts, fun, break, _sep) do\n limit = decrement(limit)\n h = fun.(h, %{opts | limit: limit})\n t = fun.(t, %{opts | limit: limit})\n do_join(h, t, break, @tail_separator)\n end\n\n defp do_join(:doc_nil, :doc_nil, _, _), do: :doc_nil\n defp do_join(h, :doc_nil, _, _), do: h\n defp do_join(:doc_nil, t, _, _), do: t\n defp do_join(h, t, :strict, sep), do: glue(concat(h, sep), t)\n defp do_join(h, t, :flex, sep), do: flex_glue(concat(h, sep), t)\n\n defp decrement(:infinity), do: :infinity\n defp decrement(counter), do: counter - 1\n\n @doc ~S\"\"\"\n Formats a given document for a given width.\n\n Takes the maximum width and a document to print as its arguments\n and returns an IO data representation of the best layout for the\n document to fit in the given width.\n\n The document starts flat (without breaks) until a group is found.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.glue(\"hello\", \" \", \"world\")\n iex> doc = Inspect.Algebra.group(doc)\n iex> doc |> Inspect.Algebra.format(30) |> IO.iodata_to_binary()\n \"hello world\"\n iex> doc |> Inspect.Algebra.format(10) |> IO.iodata_to_binary()\n \"hello\\nworld\"\n\n \"\"\"\n @spec format(t, non_neg_integer | :infinity) :: iodata\n def format(doc, width) when is_doc(doc) and (width == :infinity or width >= 0) do\n format(width, 0, [{0, :flat, doc}])\n end\n\n # Type representing the document mode to be rendered\n #\n # * break - represents a fitted document with breaks as breaks\n # * flat - represents a fitted document with breaks as flats\n # * cancel - represents a document being fitted that will cancel (fit) the next break\n # * no_cancel - represents a document being fitted that will not accept cancelations\n #\n @typep mode :: :break | :flat | :cancel | :no_cancel\n\n @spec fits?(integer, integer, [{integer, mode, t}]) :: boolean\n defp fits?(w, k, _) when k > w, do: false\n defp fits?(_, _, []), do: true\n\n defp fits?(w, k, [{i, _, doc_cancel(x, :disabled)} | t]), do: fits?(w, k, [{i, :no_cancel, x} | t])\n defp fits?(w, k, [{i, :no_cancel, doc_group(x)} | t]), do: fits?(w, k, [{i, :no_cancel, x} | t])\n defp fits?(w, k, [{i, :no_cancel, doc_cancel(x, _)} | t]), do: fits?(w, k, [{i, :no_cancel, x} | t])\n\n defp fits?(w, k, [{i, _, doc_cancel(x, :enabled)} | t]), do: fits?(w, k, [{i, :cancel, x} | t])\n defp fits?(w, k, [{i, :cancel, doc_force(x)} | t]), do: fits?(w, k, [{i, :cancel, x} | t])\n defp fits?(w, k, [{i, :cancel, doc_group(x)} | t]), do: fits?(w, k, [{i, :cancel, x} | t])\n defp fits?(_, _, [{_, :cancel, doc_break(_, _)} | _]), do: true\n defp fits?(_, _, [{_, :cancel, :doc_line} | _]), do: true\n\n defp fits?(w, k, [{_, _, :doc_nil} | t]), do: fits?(w, k, t)\n defp fits?(w, _, [{i, _, :doc_line} | t]), do: fits?(w, i, t)\n defp fits?(w, _, [{i, _, doc_collapse(_)} | t]), do: fits?(w, i, t)\n defp fits?(w, k, [{i, m, doc_cons(x, y)} | t]), do: fits?(w, k, [{i, m, x} | [{i, m, y} | t]])\n defp fits?(w, k, [{i, m, doc_color(x, _)} | t]), do: fits?(w, k, [{i, m, x} | t])\n defp fits?(w, k, [{i, m, doc_nest(x, _, :break)} | t]), do: fits?(w, k, [{i, m, x} | t])\n defp fits?(w, k, [{i, m, doc_nest(x, j, _)} | t]), do: fits?(w, k, [{apply_nesting(i, k, j), m, x} | t])\n defp fits?(w, k, [{i, _, doc_group(x)} | t]), do: fits?(w, k, [{i, :flat, x} | t])\n defp fits?(w, k, [{_, _, doc_string(_, l)} | t]), do: fits?(w, k + l, t)\n defp fits?(w, k, [{_, _, s} | t]) when is_binary(s), do: fits?(w, k + byte_size(s), t)\n defp fits?(_, _, [{_, _, doc_force(_)} | _]), do: false\n defp fits?(_, _, [{_, :break, doc_break(_, _)} | _]), do: true\n defp fits?(w, k, [{_, _, doc_break(s, _)} | t]), do: fits?(w, k + byte_size(s), t)\n\n @spec format(integer | :infinity, integer, [{integer, mode, t}]) :: [binary]\n defp format(_, _, []), do: []\n defp format(w, k, [{_, _, :doc_nil} | t]), do: format(w, k, t)\n defp format(w, _, [{i, _, :doc_line} | t]), do: [indent(i) | format(w, i, t)]\n defp format(w, k, [{i, m, doc_cons(x, y)} | t]), do: format(w, k, [{i, m, x} | [{i, m, y} | t]])\n defp format(w, k, [{i, m, doc_color(x, c)} | t]), do: [ansi(c) | format(w, k, [{i, m, x} | t])]\n defp format(w, k, [{_, _, doc_string(s, l)} | t]), do: [s | format(w, k + l, t)]\n defp format(w, k, [{_, _, s} | t]) when is_binary(s), do: [s | format(w, k + byte_size(s), t)]\n defp format(w, k, [{i, m, doc_force(x)} | t]), do: format(w, k, [{i, m, x} | t])\n defp format(w, k, [{i, m, doc_cancel(x, _)} | t]), do: format(w, k, [{i, m, x} | t])\n defp format(w, _, [{i, _, doc_collapse(max)} | t]), do: collapse(format(w, i, t), max, 0, i)\n\n # Flex breaks are not conditional to the mode\n defp format(w, k, [{i, _, doc_break(s, :flex)} | t]) do\n k = k + byte_size(s)\n\n if w == :infinity or fits?(w, k, t) do\n [s | format(w, k, t)]\n else\n [indent(i) | format(w, i, t)]\n end\n end\n\n # Strict breaks are conditional to the mode\n defp format(w, k, [{i, mode, doc_break(s, :strict)} | t]) do\n if mode == :break do\n [indent(i) | format(w, i, t)]\n else\n [s | format(w, k + byte_size(s), t)]\n end\n end\n\n # Nesting is conditional to the mode.\n defp format(w, k, [{i, mode, doc_nest(x, j, nest)} | t]) do\n if nest == :always or (nest == :break and mode == :break) do\n format(w, k, [{apply_nesting(i, k, j), mode, x} | t])\n else\n format(w, k, [{i, mode, x} | t])\n end\n end\n\n # Groups must do the fitting decision.\n defp format(w, k, [{i, _, doc_group(x)} | t]) do\n if w == :infinity or fits?(w, k, [{i, :flat, x}]) do\n format(w, k, [{i, :flat, x} | t])\n else\n format(w, k, [{i, :break, x} | t])\n end\n end\n\n defp collapse([\"\\n\" <> _ | t], max, count, i) do\n collapse(t, max, count + 1, i)\n end\n defp collapse([\"\" | t], max, count, i) do\n collapse(t, max, count, i)\n end\n defp collapse(t, max, count, i) do\n [:binary.copy(\"\\n\", min(max, count)) <> :binary.copy(\" \", i) | t]\n end\n\n defp apply_nesting(_, k, :cursor), do: k\n defp apply_nesting(_, _, :reset), do: 0\n defp apply_nesting(i, _, j), do: i + j\n\n defp ansi(color) do\n IO.ANSI.format_fragment(color, true)\n end\n\n defp indent(0), do: @newline\n defp indent(i), do: @newline <> :binary.copy(\" \", i)\nend\n","old_contents":"defmodule Inspect.Opts do\n @moduledoc \"\"\"\n Defines the Inspect.Opts used by the Inspect protocol.\n\n The following fields are available:\n\n * `:structs` - when `false`, structs are not formatted by the inspect\n protocol, they are instead printed as maps, defaults to `true`.\n\n * `:binaries` - when `:as_strings` all binaries will be printed as strings,\n non-printable bytes will be escaped.\n\n When `:as_binaries` all binaries will be printed in bit syntax.\n\n When the default `:infer`, the binary will be printed as a string if it\n is printable, otherwise in bit syntax.\n\n * `:charlists` - when `:as_charlists` all lists will be printed as char\n lists, non-printable elements will be escaped.\n\n When `:as_lists` all lists will be printed as lists.\n\n When the default `:infer`, the list will be printed as a charlist if it\n is printable, otherwise as list.\n\n * `:limit` - limits the number of items that are printed for tuples,\n bitstrings, maps, lists and any other collection of items. It does not\n apply to strings nor charlists and defaults to 50.\n\n * `:printable_limit` - limits the number of bytes that are printed for strings\n and char lists. Defaults to 4096.\n\n * `:pretty` - if set to `true` enables pretty printing, defaults to `false`.\n\n * `:width` - defaults to 80 characters, used when pretty is `true` or when\n printing to IO devices. Set to 0 to force each item to be printed on its\n own line.\n\n * `:base` - prints integers as `:binary`, `:octal`, `:decimal`, or `:hex`,\n defaults to `:decimal`. When inspecting binaries any `:base` other than\n `:decimal` implies `binaries: :as_binaries`.\n\n * `:safe` - when `false`, failures while inspecting structs will be raised\n as errors instead of being wrapped in the `Inspect.Error` exception. This\n is useful when debugging failures and crashes for custom inspect\n implementations\n\n * `:syntax_colors` - when set to a keyword list of colors the output will\n be colorized. The keys are types and the values are the colors to use for\n each type. e.g. `[number: :red, atom: :blue]`. Types can include\n `:number`, `:atom`, `regex`, `:tuple`, `:map`, `:list`, and `:reset`.\n Colors can be any `t:IO.ANSI.ansidata\/0` as accepted by `IO.ANSI.format\/1`.\n \"\"\"\n\n # TODO: Remove :char_lists key by 2.0\n defstruct structs: true,\n binaries: :infer,\n charlists: :infer,\n char_lists: :infer,\n limit: 50,\n printable_limit: 4096,\n width: 80,\n base: :decimal,\n pretty: false,\n safe: true,\n syntax_colors: []\n\n @type color_key :: atom\n\n # TODO: Remove :char_lists key and :as_char_lists value by 2.0\n @type t :: %__MODULE__{\n structs: boolean,\n binaries: :infer | :as_binaries | :as_strings,\n charlists: :infer | :as_lists | :as_charlists,\n char_lists: :infer | :as_lists | :as_char_lists,\n limit: pos_integer | :infinity,\n printable_limit: pos_integer | :infinity,\n width: pos_integer | :infinity,\n base: :decimal | :binary | :hex | :octal,\n pretty: boolean,\n safe: boolean,\n syntax_colors: [{color_key, IO.ANSI.ansidata}]\n }\nend\n\ndefmodule Inspect.Error do\n @moduledoc \"\"\"\n Raised when a struct cannot be inspected.\n \"\"\"\n defexception [:message]\nend\n\ndefmodule Inspect.Algebra do\n @moduledoc ~S\"\"\"\n A set of functions for creating and manipulating algebra\n documents.\n\n This module implements the functionality described in\n [\"Strictly Pretty\" (2000) by Christian Lindig][0] with small\n additions, like support for binary nodes and a break mode that\n maximises use of horizontal space.\n\n iex> Inspect.Algebra.empty\n :doc_nil\n\n iex> \"foo\"\n \"foo\"\n\n With the functions in this module, we can concatenate different\n elements together and render them:\n\n iex> doc = Inspect.Algebra.concat(Inspect.Algebra.empty, \"foo\")\n iex> Inspect.Algebra.format(doc, 80)\n [\"foo\"]\n\n The functions `nest\/2`, `space\/2` and `line\/2` help you put the\n document together into a rigid structure. However, the document\n algebra gets interesting when using functions like `glue\/3` and\n `group\/1`. A glue inserts a break between two documents. A group\n indicates a document that must fit the current line, otherwise\n breaks are rendered as new lines. Let's glue two docs together\n with a break, group it and then render it:\n\n iex> doc = Inspect.Algebra.glue(\"a\", \" \", \"b\")\n iex> doc = Inspect.Algebra.group(doc)\n iex> Inspect.Algebra.format(doc, 80)\n [\"a\", \" \", \"b\"]\n\n Notice the break was represented as is, because we haven't reached\n a line limit. Once we do, it is replaced by a newline:\n\n iex> doc = Inspect.Algebra.glue(String.duplicate(\"a\", 20), \" \", \"b\")\n iex> doc = Inspect.Algebra.group(doc)\n iex> Inspect.Algebra.format(doc, 10)\n [\"aaaaaaaaaaaaaaaaaaaa\", \"\\n\", \"b\"]\n\n This module uses the byte size to compute how much space there is\n left. If your document contains strings, then those need to be\n wrapped in `string\/1`, which then relies on `String.length\/1` to\n precompute the document size.\n\n Finally, this module also contains Elixir related functions, a bit\n tied to Elixir formatting, namely `surround\/3` and `surround_many\/5`.\n\n ## Implementation details\n\n The original Haskell implementation of the algorithm by [Wadler][1]\n relies on lazy evaluation to unfold document groups on two alternatives:\n `:flat` (breaks as spaces) and `:break` (breaks as newlines).\n Implementing the same logic in a strict language such as Elixir leads\n to an exponential growth of possible documents, unless groups are explicitly\n encoded. Those groups are then reduced to a simple document, where the\n layout is already decided, per [Lindig][0].\n\n This implementation has two types of breaks: `:strict` and `:flex`. When\n a group does not fit, all strict breaks are treated as breaks. The flex\n breaks however are re-evaluated and may still be rendered as spaces.\n\n This implementation also adds `force_break\/1` and `cancel_break\/2` which\n give more control over the document fitting.\n\n Custom pretty printers can be implemented using the documents returned\n by this module and by providing their own rendering functions.\n\n [0]: http:\/\/citeseerx.ist.psu.edu\/viewdoc\/summary?doi=10.1.1.34.2200\n [1]: http:\/\/homepages.inf.ed.ac.uk\/wadler\/papers\/prettier\/prettier.pdf\n\n \"\"\"\n\n @surround_separator \",\"\n @tail_separator \" |\"\n @newline \"\\n\"\n @break :flex\n @cancel_break :enabled\n\n # Functional interface to \"doc\" records\n\n @type t ::\n binary\n | :doc_nil\n | :doc_line\n | doc_string\n | doc_cons\n | doc_nest\n | doc_break\n | doc_group\n | doc_color\n | doc_force\n | doc_cancel\n\n @typep doc_string :: {:doc_string, t, non_neg_integer}\n defmacrop doc_string(string, length) do\n quote do: {:doc_string, unquote(string), unquote(length)}\n end\n\n @typep doc_cons :: {:doc_cons, t, t}\n defmacrop doc_cons(left, right) do\n quote do: {:doc_cons, unquote(left), unquote(right)}\n end\n\n @typep doc_nest :: {:doc_nest, t, :cursor | :reset | non_neg_integer, :always | :break}\n defmacrop doc_nest(doc, indent, always_or_break) do\n quote do: {:doc_nest, unquote(doc), unquote(indent), unquote(always_or_break)}\n end\n\n @typep doc_break :: {:doc_break, binary, :flex | :strict}\n defmacrop doc_break(break, mode) do\n quote do: {:doc_break, unquote(break), unquote(mode)}\n end\n\n @typep doc_group :: {:doc_group, t}\n defmacrop doc_group(group) do\n quote do: {:doc_group, unquote(group)}\n end\n\n @typep doc_cancel :: {:doc_cancel, t, :enabled | :disabled}\n defmacrop doc_cancel(group, mode) do\n quote do: {:doc_cancel, unquote(group), unquote(mode)}\n end\n\n @typep doc_force :: {:doc_force, t}\n defmacrop doc_force(group) do\n quote do: {:doc_force, unquote(group)}\n end\n\n @typep doc_color :: {:doc_color, t, IO.ANSI.ansidata}\n defmacrop doc_color(doc, color) do\n quote do: {:doc_color, unquote(doc), unquote(color)}\n end\n\n defmacrop is_doc(doc) do\n if Macro.Env.in_guard?(__CALLER__) do\n do_is_doc(doc)\n else\n var = quote do: doc\n quote do\n unquote(var) = unquote(doc)\n unquote(do_is_doc(var))\n end\n end\n end\n\n defp do_is_doc(doc) do\n quote do\n is_binary(unquote(doc)) or\n unquote(doc) in [:doc_nil, :doc_line] or\n (is_tuple(unquote(doc)) and\n elem(unquote(doc), 0) in [:doc_string, :doc_cons, :doc_nest, :doc_break, :doc_group,\n :doc_color, :doc_force, :doc_cancel])\n end\n end\n\n @doc \"\"\"\n Converts an Elixir term to an algebra document\n according to the `Inspect` protocol.\n \"\"\"\n @spec to_doc(any, Inspect.Opts.t) :: t\n def to_doc(term, opts)\n\n def to_doc(%_{} = struct, %Inspect.Opts{} = opts) do\n if opts.structs do\n try do\n Inspect.inspect(struct, opts)\n rescue\n caught_exception ->\n stacktrace = System.stacktrace\n\n # Because we try to raise a nice error message in case\n # we can't inspect a struct, there is a chance the error\n # message itself relies on the struct being printed, so\n # we need to trap the inspected messages to guarantee\n # we won't try to render any failed instruct when building\n # the error message.\n if Process.get(:inspect_trap) do\n Inspect.Map.inspect(struct, opts)\n else\n try do\n Process.put(:inspect_trap, true)\n\n res = Inspect.Map.inspect(struct, %{opts | syntax_colors: []})\n res = IO.iodata_to_binary(format(res, :infinity))\n\n message =\n \"got #{inspect caught_exception.__struct__} with message \" <>\n \"#{inspect Exception.message(caught_exception)} while inspecting #{res}\"\n exception = Inspect.Error.exception(message: message)\n\n if opts.safe do\n Inspect.inspect(exception, opts)\n else\n reraise(exception, stacktrace)\n end\n after\n Process.delete(:inspect_trap)\n end\n end\n end\n else\n Inspect.Map.inspect(struct, opts)\n end\n end\n\n def to_doc(arg, %Inspect.Opts{} = opts) do\n Inspect.inspect(arg, opts)\n end\n\n @doc \"\"\"\n Returns a document entity used to represent nothingness.\n\n ## Examples\n\n iex> Inspect.Algebra.empty\n :doc_nil\n\n \"\"\"\n @spec empty() :: :doc_nil\n def empty, do: :doc_nil\n\n @doc ~S\"\"\"\n Creates a document represented by string.\n\n While `Inspect.Algebra` accepts binaries as documents,\n those are counted by binary size. On the other hand,\n `string` documents are measured in terms of graphemes\n towards the document size.\n\n ## Examples\n\n The following document has 10 bytes and therefore it\n does not format to width 9 without breaks:\n\n iex> doc = Inspect.Algebra.glue(\"ol\u00e1\", \" \", \"mundo\")\n iex> doc = Inspect.Algebra.group(doc)\n iex> Inspect.Algebra.format(doc, 9)\n [\"ol\u00e1\", \"\\n\", \"mundo\"]\n\n However, if we use `string`, then the string length is\n used, instead of byte size, correctly fitting:\n\n iex> string = Inspect.Algebra.string(\"ol\u00e1\")\n iex> doc = Inspect.Algebra.glue(string, \" \", \"mundo\")\n iex> doc = Inspect.Algebra.group(doc)\n iex> Inspect.Algebra.format(doc, 9)\n [\"ol\u00e1\", \" \", \"mundo\"]\n\n \"\"\"\n @spec string(String.t) :: doc_string\n def string(string) when is_binary(string) do\n doc_string(string, String.length(string))\n end\n\n @doc ~S\"\"\"\n Concatenates two document entities returning a new document.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.concat(\"hello\", \"world\")\n iex> Inspect.Algebra.format(doc, 80)\n [\"hello\", \"world\"]\n\n \"\"\"\n @spec concat(t, t) :: t\n def concat(doc1, doc2) when is_doc(doc1) and is_doc(doc2) do\n doc_cons(doc1, doc2)\n end\n\n @doc ~S\"\"\"\n Concatenates a list of documents returning a new document.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.concat([\"a\", \"b\", \"c\"])\n iex> Inspect.Algebra.format(doc, 80)\n [\"a\", \"b\", \"c\"]\n\n \"\"\"\n @spec concat([t]) :: t\n def concat(docs) when is_list(docs) do\n fold_doc(docs, &concat(&1, &2))\n end\n\n @doc ~S\"\"\"\n Colors a document if the `color_key` has a color in the options.\n \"\"\"\n @spec color(t, Inspect.Opts.color_key, Inspect.Opts.t) :: doc_color\n def color(doc, color_key, %Inspect.Opts{syntax_colors: syntax_colors}) when is_doc(doc) do\n if precolor = Keyword.get(syntax_colors, color_key) do\n postcolor = Keyword.get(syntax_colors, :reset, :reset)\n concat(doc_color(doc, precolor), doc_color(empty(), postcolor))\n else\n doc\n end\n end\n\n @doc ~S\"\"\"\n Nests the given document at the given `level`.\n\n If `level` is an integer, that's the indentation appended\n to line breaks whenever they occur. If the level is `:cursor`,\n the current position of the \"cursor\" in the document becomes\n the nesting. If the level is `:reset`, it is set back to 0.\n\n `mode` can be `:always`, which means nesting always happen,\n or `:break`, which means nesting only happens inside a group\n that has been broken.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.nest(Inspect.Algebra.glue(\"hello\", \"world\"), 5)\n iex> doc = Inspect.Algebra.group(doc)\n iex> Inspect.Algebra.format(doc, 5)\n [\"hello\", \"\\n \", \"world\"]\n\n \"\"\"\n @spec nest(t, non_neg_integer) :: doc_nest\n def nest(doc, level, mode \\\\ :always)\n\n def nest(doc, :cursor, mode) when is_doc(doc) and mode in [:always, :break] do\n doc_nest(doc, :cursor, mode)\n end\n\n def nest(doc, :reset, mode) when is_doc(doc) and mode in [:always, :break] do\n doc_nest(doc, :reset, mode)\n end\n\n def nest(doc, 0, _mode) when is_doc(doc) do\n doc\n end\n\n def nest(doc, level, mode)\n when is_doc(doc) and is_integer(level) and level > 0 and mode in [:always, :break] do\n doc_nest(doc, level, mode)\n end\n\n @doc ~S\"\"\"\n Returns a document entity representing a break based on the given\n `string`.\n\n This break can be rendered as a linebreak or as the given `string`,\n depending on the `mode` of the chosen layout.\n\n ## Examples\n\n Let's create a document by concatenating two strings with a break between\n them:\n\n iex> doc = Inspect.Algebra.concat([\"a\", Inspect.Algebra.break(\"\\t\"), \"b\"])\n iex> Inspect.Algebra.format(doc, 80)\n [\"a\", \"\\t\", \"b\"]\n\n Notice the break was represented with the given string, because we didn't\n reach a line limit. Once we do, it is replaced by a newline:\n\n iex> break = Inspect.Algebra.break(\"\\t\")\n iex> doc = Inspect.Algebra.concat([String.duplicate(\"a\", 20), break, \"b\"])\n iex> doc = Inspect.Algebra.group(doc)\n iex> Inspect.Algebra.format(doc, 10)\n [\"aaaaaaaaaaaaaaaaaaaa\", \"\\n\", \"b\"]\n\n \"\"\"\n @spec break(binary) :: doc_break\n def break(string \\\\ \" \") when is_binary(string) do\n doc_break(string, :strict)\n end\n\n @doc \"\"\"\n Considers the next break as fit.\n\n `mode` can be `:enabled` or `:disabled`. When `:enabled`,\n it will consider the document as fit as soon as it finds\n the next break, effectively cancelling the break. It will\n also ignore any `force_break\/1`.\n\n When disabled, it behaves as usual and it will ignore\n any furtger `cancel_break\/2` instruction.\n \"\"\"\n @spec cancel_break(t) :: doc_cancel\n def cancel_break(doc, mode \\\\ @cancel_break) when is_doc(doc) do\n doc_cancel(doc, mode)\n end\n\n @doc \"\"\"\n Forces the document to break.\n \"\"\"\n @spec force_break(t) :: doc_force\n def force_break(doc) when is_doc(doc) do\n doc_force(doc)\n end\n\n @doc \"\"\"\n Introduces a flex break.\n\n A flex break still causes a group to break, like\n a regular break, but it is re-evaluated when the\n documented is processed.\n\n This function is used by `surround\/4` and friends\n to the maximum amount of entries on the same line.\n \"\"\"\n @spec flex_break(binary) :: doc_break\n def flex_break(string \\\\ \" \") when is_binary(string) do\n doc_break(string, :flex)\n end\n\n @doc \"\"\"\n Glues two documents (`doc1` and `doc2`) inserting a\n `flex_break\/1` given by `break_string` between them.\n\n This function is used by `surround\/4` and friends\n to the maximum amount of entries on the same line.\n \"\"\"\n @spec flex_glue(t, binary, t) :: t\n def flex_glue(doc1, break_string \\\\ \" \", doc2) when is_binary(break_string) do\n concat(doc1, concat(flex_break(break_string), doc2))\n end\n\n @doc ~S\"\"\"\n Glues two documents (`doc1` and `doc2`) inserting the given\n break `break_string` between them.\n\n For more information on how the break is inserted, see `break\/1`.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.glue(\"hello\", \"world\")\n iex> Inspect.Algebra.format(doc, 80)\n [\"hello\", \" \", \"world\"]\n\n iex> doc = Inspect.Algebra.glue(\"hello\", \"\\t\", \"world\")\n iex> Inspect.Algebra.format(doc, 80)\n [\"hello\", \"\\t\", \"world\"]\n\n \"\"\"\n @spec glue(t, binary, t) :: t\n def glue(doc1, break_string \\\\ \" \", doc2) when is_binary(break_string) do\n concat(doc1, concat(break(break_string), doc2))\n end\n\n @doc ~S\"\"\"\n Returns a group containing the specified document `doc`.\n\n Documents in a group are attempted to be rendered together\n to the best of the renderer ability.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.group(\n ...> Inspect.Algebra.concat(\n ...> Inspect.Algebra.group(\n ...> Inspect.Algebra.concat(\n ...> \"Hello,\",\n ...> Inspect.Algebra.concat(\n ...> Inspect.Algebra.break,\n ...> \"A\"\n ...> )\n ...> )\n ...> ),\n ...> Inspect.Algebra.concat(\n ...> Inspect.Algebra.break,\n ...> \"B\"\n ...> )\n ...> ))\n iex> Inspect.Algebra.format(doc, 80)\n [\"Hello,\", \" \", \"A\", \" \", \"B\"]\n iex> Inspect.Algebra.format(doc, 6)\n [\"Hello,\", \"\\n\", \"A\", \"\\n\", \"B\"]\n\n \"\"\"\n @spec group(t) :: doc_group\n def group(doc) when is_doc(doc) do\n doc_group(doc)\n end\n\n @doc ~S\"\"\"\n Inserts a mandatory single space between two documents.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.space(\"Hughes\", \"Wadler\")\n iex> Inspect.Algebra.format(doc, 5)\n [\"Hughes\", \" \", \"Wadler\"]\n\n \"\"\"\n @spec space(t, t) :: t\n def space(doc1, doc2), do: concat(doc1, concat(\" \", doc2))\n\n @doc ~S\"\"\"\n A mandatory linebreak.\n\n A group with linebreaks will fit if all lines in the group fit.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.concat(\n ...> Inspect.Algebra.concat(\n ...> \"Hughes\",\n ...> Inspect.Algebra.line()\n ...> ), \"Wadler\"\n ...> )\n iex> Inspect.Algebra.format(doc, 80)\n [\"Hughes\", \"\\n\", \"Wadler\"]\n\n \"\"\"\n @spec line() :: t\n def line(), do: :doc_line\n\n @doc ~S\"\"\"\n Inserts a mandatory linebreak between two documents.\n\n See `line\/1`.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.line(\"Hughes\", \"Wadler\")\n iex> Inspect.Algebra.format(doc, 80)\n [\"Hughes\", \"\\n\", \"Wadler\"]\n\n \"\"\"\n @spec line(t, t) :: t\n def line(doc1, doc2), do: concat(doc1, concat(line(), doc2))\n\n @doc ~S\"\"\"\n Folds a list of documents into a document using the given folder function.\n\n The list of documents is folded \"from the right\"; in that, this function is\n similar to `List.foldr\/3`, except that it doesn't expect an initial\n accumulator and uses the last element of `docs` as the initial accumulator.\n\n ## Examples\n\n iex> docs = [\"A\", \"B\", \"C\"]\n iex> docs = Inspect.Algebra.fold_doc(docs, fn(doc, acc) ->\n ...> Inspect.Algebra.concat([doc, \"!\", acc])\n ...> end)\n iex> Inspect.Algebra.format(docs, 80)\n [\"A\", \"!\", \"B\", \"!\", \"C\"]\n\n \"\"\"\n @spec fold_doc([t], ((t, t) -> t)) :: t\n def fold_doc(docs, folder_fun)\n\n def fold_doc([], _folder_fun),\n do: empty()\n def fold_doc([doc], _folder_fun),\n do: doc\n def fold_doc([doc | docs], folder_fun) when is_function(folder_fun, 2),\n do: folder_fun.(doc, fold_doc(docs, folder_fun))\n\n # Elixir conveniences\n\n @doc ~S\"\"\"\n Surrounds a document with characters.\n\n Puts the given document `doc` between the `left` and `right` documents enclosing\n and nesting it. The document is marked as a group, to show the maximum as\n possible concisely together.\n\n ## Options\n\n * `:break` - controls if the break is `:strict` or `:flex`, see `group\/2`\n\n ## Examples\n\n iex> doc = Inspect.Algebra.surround(\"[\", Inspect.Algebra.glue(\"a\", \"b\"), \"]\")\n iex> doc = Inspect.Algebra.group(doc)\n iex> Inspect.Algebra.format(doc, 3)\n [\"[\", \"a\", \"\\n \", \"b\", \"]\"]\n\n \"\"\"\n # TODO: Reflect the @break default and nesting for flex on the formatter\n @spec surround(t, t, t, keyword()) :: t\n def surround(left, doc, right, opts \\\\ [])\n when is_doc(left) and is_doc(doc) and is_doc(right) and is_list(opts) do\n case Keyword.get(opts, :break, @break) do\n :flex ->\n concat(concat(left, nest(doc, 1)), right)\n :strict ->\n group(glue(nest(glue(left, \"\", doc), 2), \"\", right))\n end\n end\n\n @doc ~S\"\"\"\n Maps and glues a collection of items.\n\n It uses the given `left` and `right` documents as surrounding and the\n separator document `separator` to separate items in `docs`. A limit can be\n passed: when this limit is reached, this function stops gluing and outputs\n `\"...\"` instead.\n\n ## Options\n\n * `:separator` - the separator used between each doc\n\n Plus all options in `surround\/4`.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.surround_many(\"[\", Enum.to_list(1..5), \"]\",\n ...> %Inspect.Opts{limit: :infinity}, fn i, _opts -> to_string(i) end)\n iex> Inspect.Algebra.format(doc, 5) |> IO.iodata_to_binary\n \"[1,\\n 2,\\n 3,\\n 4,\\n 5]\"\n\n iex> doc = Inspect.Algebra.surround_many(\"[\", Enum.to_list(1..5), \"]\",\n ...> %Inspect.Opts{limit: 3}, fn i, _opts -> to_string(i) end)\n iex> Inspect.Algebra.format(doc, 20) |> IO.iodata_to_binary\n \"[1, 2, 3, ...]\"\n\n iex> doc = Inspect.Algebra.surround_many(\"[\", Enum.to_list(1..5), \"]\",\n ...> %Inspect.Opts{limit: 3}, fn i, _opts -> to_string(i) end, \"!\")\n iex> Inspect.Algebra.format(doc, 20) |> IO.iodata_to_binary\n \"[1! 2! 3! ...]\"\n\n \"\"\"\n @spec surround_many(t, [any], t, Inspect.Opts.t, (term, Inspect.Opts.t -> t), keyword) :: t\n def surround_many(left, docs, right, %Inspect.Opts{} = inspect, fun, opts \\\\ [])\n when is_doc(left) and is_list(docs) and is_doc(right) and is_function(fun, 2) do\n cond do\n is_list(opts) ->\n {separator, opts} = Keyword.pop(opts, :separator, @surround_separator)\n surround_many(left, docs, right, inspect, fun, separator, opts)\n is_doc(opts) ->\n # TODO: Deprecate on Elixir v1.8\n surround_many(left, docs, right, inspect, fun, opts, [])\n end\n end\n\n defp surround_many(left, [], right, _inspect, _fun, _sep, _opts) do\n concat(left, right)\n end\n\n defp surround_many(left, docs, right, inspect, fun, sep, opts) do\n break = Keyword.get(opts, :break, @break)\n surround(left, surround_each(docs, inspect.limit, inspect, fun, break, sep), right, opts)\n end\n\n defp surround_each(_, 0, _opts, _fun, _break, _sep) do\n \"...\"\n end\n\n defp surround_each([], _limit, _opts, _fun, _break, _sep) do\n :doc_nil\n end\n\n defp surround_each([h], limit, opts, fun, _break, _sep) do\n fun.(h, %{opts | limit: limit})\n end\n\n defp surround_each([h | t], limit, opts, fun, break, sep) when is_list(t) do\n limit = decrement(limit)\n h = fun.(h, %{opts | limit: limit})\n t = surround_each(t, limit, opts, fun, break, sep)\n do_join(h, t, break, sep)\n end\n\n defp surround_each([h | t], limit, opts, fun, break, _sep) do\n limit = decrement(limit)\n h = fun.(h, %{opts | limit: limit})\n t = fun.(t, %{opts | limit: limit})\n do_join(h, t, break, @tail_separator)\n end\n\n defp do_join(:doc_nil, :doc_nil, _, _), do: :doc_nil\n defp do_join(h, :doc_nil, _, _), do: h\n defp do_join(:doc_nil, t, _, _), do: t\n defp do_join(h, t, :strict, sep), do: glue(concat(h, sep), t)\n defp do_join(h, t, :flex, sep), do: flex_glue(concat(h, sep), t)\n\n defp decrement(:infinity), do: :infinity\n defp decrement(counter), do: counter - 1\n\n @doc ~S\"\"\"\n Formats a given document for a given width.\n\n Takes the maximum width and a document to print as its arguments\n and returns an IO data representation of the best layout for the\n document to fit in the given width.\n\n The document starts flat (without breaks) until a group is found.\n\n ## Examples\n\n iex> doc = Inspect.Algebra.glue(\"hello\", \" \", \"world\")\n iex> doc = Inspect.Algebra.group(doc)\n iex> doc |> Inspect.Algebra.format(30) |> IO.iodata_to_binary()\n \"hello world\"\n iex> doc |> Inspect.Algebra.format(10) |> IO.iodata_to_binary()\n \"hello\\nworld\"\n\n \"\"\"\n @spec format(t, non_neg_integer | :infinity) :: iodata\n def format(doc, width) when is_doc(doc) and (width == :infinity or width >= 0) do\n format(width, 0, [{0, :flat, doc}])\n end\n\n # Type representing the document mode to be rendered\n #\n # * break - represents a fitted document with breaks as breaks\n # * flat - represents a fitted document with breaks as flats\n # * cancel - represents a document being fitted that will cancel (fit) the next break\n # * no_cancel - represents a document being fitted that will not accept cancelations\n #\n @typep mode :: :break | :flat | :cancel | :no_cancel\n\n @spec fits?(integer, integer, [{integer, mode, t}]) :: boolean\n defp fits?(w, k, _) when k > w, do: false\n defp fits?(_, _, []), do: true\n\n defp fits?(w, k, [{i, _, doc_cancel(x, :disabled)} | t]), do: fits?(w, k, [{i, :no_cancel, x} | t])\n defp fits?(w, k, [{i, :no_cancel, doc_group(x)} | t]), do: fits?(w, k, [{i, :no_cancel, x} | t])\n defp fits?(w, k, [{i, :no_cancel, doc_cancel(x, _)} | t]), do: fits?(w, k, [{i, :no_cancel, x} | t])\n\n defp fits?(w, k, [{i, _, doc_cancel(x, :enabled)} | t]), do: fits?(w, k, [{i, :cancel, x} | t])\n defp fits?(w, k, [{i, :cancel, doc_force(x)} | t]), do: fits?(w, k, [{i, :cancel, x} | t])\n defp fits?(w, k, [{i, :cancel, doc_group(x)} | t]), do: fits?(w, k, [{i, :cancel, x} | t])\n defp fits?(_, _, [{_, :cancel, doc_break(_, _)} | _]), do: true\n defp fits?(_, _, [{_, :cancel, :doc_line} | _]), do: true\n\n defp fits?(w, k, [{_, _, :doc_nil} | t]), do: fits?(w, k, t)\n defp fits?(w, _, [{i, _, :doc_line} | t]), do: fits?(w, i, t)\n defp fits?(w, k, [{i, m, doc_cons(x, y)} | t]), do: fits?(w, k, [{i, m, x} | [{i, m, y} | t]])\n defp fits?(w, k, [{i, m, doc_color(x, _)} | t]), do: fits?(w, k, [{i, m, x} | t])\n defp fits?(w, k, [{i, m, doc_nest(x, _, :break)} | t]), do: fits?(w, k, [{i, m, x} | t])\n defp fits?(w, k, [{i, m, doc_nest(x, j, _)} | t]), do: fits?(w, k, [{apply_nesting(i, k, j), m, x} | t])\n defp fits?(w, k, [{i, _, doc_group(x)} | t]), do: fits?(w, k, [{i, :flat, x} | t])\n defp fits?(w, k, [{_, _, doc_string(_, l)} | t]), do: fits?(w, k + l, t)\n defp fits?(w, k, [{_, _, s} | t]) when is_binary(s), do: fits?(w, k + byte_size(s), t)\n defp fits?(_, _, [{_, _, doc_force(_)} | _]), do: false\n defp fits?(_, _, [{_, :break, doc_break(_, _)} | _]), do: true\n defp fits?(w, k, [{_, _, doc_break(s, _)} | t]), do: fits?(w, k + byte_size(s), t)\n\n @spec format(integer | :infinity, integer, [{integer, mode, t}]) :: [binary]\n defp format(_, _, []), do: []\n defp format(w, k, [{_, _, :doc_nil} | t]), do: format(w, k, t)\n defp format(w, _, [{i, _, :doc_line} | t]), do: [indent(i) | format(w, i, t)]\n defp format(w, k, [{i, m, doc_cons(x, y)} | t]), do: format(w, k, [{i, m, x} | [{i, m, y} | t]])\n defp format(w, k, [{i, m, doc_color(x, c)} | t]), do: [ansi(c) | format(w, k, [{i, m, x} | t])]\n defp format(w, k, [{_, _, doc_string(s, l)} | t]), do: [s | format(w, k + l, t)]\n defp format(w, k, [{_, _, s} | t]) when is_binary(s), do: [s | format(w, k + byte_size(s), t)]\n defp format(w, k, [{i, m, doc_force(x)} | t]), do: format(w, k, [{i, m, x} | t])\n defp format(w, k, [{i, m, doc_cancel(x, _)} | t]), do: format(w, k, [{i, m, x} | t])\n\n # Flex breaks are not conditional to the mode\n defp format(w, k, [{i, _, doc_break(s, :flex)} | t]) do\n k = k + byte_size(s)\n\n if w == :infinity or fits?(w, k, t) do\n [s | format(w, k, t)]\n else\n [indent(i) | format(w, i, t)]\n end\n end\n\n # Strict breaks are conditional to the mode\n defp format(w, k, [{i, mode, doc_break(s, :strict)} | t]) do\n if mode == :break do\n [indent(i) | format(w, i, t)]\n else\n [s | format(w, k + byte_size(s), t)]\n end\n end\n\n # Nesting is conditional to the mode.\n defp format(w, k, [{i, mode, doc_nest(x, j, nest)} | t]) do\n if nest == :always or (nest == :break and mode == :break) do\n format(w, k, [{apply_nesting(i, k, j), mode, x} | t])\n else\n format(w, k, [{i, mode, x} | t])\n end\n end\n\n # Groups must do the fitting decision.\n defp format(w, k, [{i, _, doc_group(x)} | t]) do\n if w == :infinity or fits?(w, k, [{i, :flat, x}]) do\n format(w, k, [{i, :flat, x} | t])\n else\n format(w, k, [{i, :break, x} | t])\n end\n end\n\n defp apply_nesting(_, k, :cursor), do: k\n defp apply_nesting(_, _, :reset), do: 0\n defp apply_nesting(i, _, j), do: i + j\n\n defp ansi(color) do\n IO.ANSI.format_fragment(color, true)\n end\n\n defp indent(0), do: @newline\n defp indent(i), do: @newline <> :binary.copy(\" \", i)\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"7afbdae53cc55d8383d0ac84966f99c6f09d854e","subject":"Improve error message when deps.loadpaths\/loadpaths\/compile has not run","message":"Improve error message when deps.loadpaths\/loadpaths\/compile has not run\n\nCloses #8803.\n","repos":"kelvinst\/elixir,kelvinst\/elixir,pedrosnk\/elixir,joshprice\/elixir,ggcampinho\/elixir,ggcampinho\/elixir,kimshrier\/elixir,michalmuskala\/elixir,lexmag\/elixir,pedrosnk\/elixir,elixir-lang\/elixir,kimshrier\/elixir,lexmag\/elixir","old_file":"lib\/mix\/lib\/mix\/dep.ex","new_file":"lib\/mix\/lib\/mix\/dep.ex","new_contents":"defmodule Mix.Dep do\n @moduledoc false\n\n @doc \"\"\"\n The Mix.Dep struct keeps information about your project dependencies.\n\n It contains:\n\n * `scm` - a module representing the source code management tool (SCM)\n operations\n\n * `app` - the application name as an atom\n\n * `requirement` - a binary or regular expression with the dependency's requirement\n\n * `status` - the current status of the dependency, check\n `Mix.Dep.format_status\/1` for more information\n\n * `opts` - the options given by the developer\n\n * `deps` - dependencies of this dependency\n\n * `top_level` - true if dependency was defined in the top-level project\n\n * `manager` - the project management, possible values:\n `:rebar` | `:rebar3` | `:mix` | `:make` | `nil`\n\n * `from` - path to the file where the dependency was defined\n\n * `extra` - a slot for adding extra configuration based on the manager;\n the information on this field is private to the manager and should not be\n relied on\n\n * `system_env` - an enumerable of key-value tuples of binaries to be set as environment variables\n when loading or compiling the dependency\n\n A dependency is in two specific states: loaded and unloaded.\n\n When a dependency is unloaded, it means Mix only parsed its specification\n and made no attempt to actually load the dependency or validate its\n status. When the dependency is loaded, it means Mix attempted to fetch,\n load and validate it, the status is set in the status field.\n\n Furthermore, in the `opts` fields, Mix keeps some internal options, which\n can be accessed by SCMs:\n\n * `:app` - the application name\n * `:dest` - the destination path for the dependency\n * `:lock` - the lock information retrieved from mix.lock\n * `:build` - the build path for the dependency\n\n \"\"\"\n defstruct scm: nil,\n app: nil,\n requirement: nil,\n status: nil,\n opts: [],\n deps: [],\n top_level: false,\n extra: [],\n manager: nil,\n from: nil,\n system_env: []\n\n @type t :: %__MODULE__{\n scm: module,\n app: atom,\n requirement: String.t() | Regex.t() | nil,\n status: atom,\n opts: keyword,\n top_level: boolean,\n manager: :rebar | :rebar3 | :mix | :make | nil,\n from: String.t(),\n extra: term,\n system_env: keyword\n }\n\n @doc \"\"\"\n Returns loaded dependencies from the cache for the current environment.\n\n If dependencies have not been cached yet, they are loaded\n and then cached.\n\n Because the dependencies are cached during deps.loadpaths,\n their status may be outdated (for example, `:compile` did not\n yet become `:ok`). Therefore it is recommended to not rely\n on their status, also given they haven't been checked\n against the lock.\n \"\"\"\n def cached() do\n if project = Mix.Project.get() do\n read_cached_deps(project, {Mix.env(), Mix.target()}) || load_and_cache()\n else\n load_and_cache()\n end\n end\n\n @doc \"\"\"\n Returns loaded dependencies recursively and caches it.\n\n The result is cached for future `cached\/0` calls.\n\n ## Exceptions\n\n This function raises an exception if any of the dependencies\n provided in the project are in the wrong format.\n \"\"\"\n def load_and_cache() do\n env = Mix.env()\n target = Mix.target()\n\n case Mix.ProjectStack.top_and_bottom() do\n {%{name: top, config: config}, %{name: bottom}} ->\n write_cached_deps(top, {env, target}, load_and_cache(config, top, bottom, env, target))\n\n _ ->\n converge(env: env, target: target)\n end\n end\n\n defp load_and_cache(_config, top, top, env, target) do\n converge(env: env, target: target)\n end\n\n defp load_and_cache(config, _top, bottom, _env, _target) do\n {_, deps} =\n Mix.ProjectStack.read_cache({:cached_deps, bottom}) ||\n raise \"cannot retrieve dependencies information because dependencies were not loaded. \" <>\n \"Please invoke one of \\\"deps.loadpaths\\\", \\\"loadpaths\\\", or \\\"compile\\\" Mix task\"\n\n app = Keyword.fetch!(config, :app)\n seen = populate_seen(MapSet.new(), [app])\n children = get_deps(deps, tl(Enum.uniq(get_children(deps, seen, [app]))))\n\n top_level =\n for dep <- deps,\n dep.app == app,\n child <- dep.deps,\n do: {child.app, Keyword.get(child.opts, :optional, false)},\n into: %{}\n\n Enum.map(children, fn %{app: app, opts: opts} = dep ->\n # optional only matters at the top level. Any non-top level dependency\n # that is optional and is still available means it has been fulfilled.\n case top_level do\n %{^app => optional} ->\n %{dep | top_level: true, opts: Keyword.put(opts, :optional, optional)}\n\n %{} ->\n %{dep | top_level: false, opts: Keyword.delete(opts, :optional)}\n end\n end)\n end\n\n defp read_cached_deps(project, env_target) do\n case Mix.ProjectStack.read_cache({:cached_deps, project}) do\n {^env_target, deps} -> deps\n _ -> nil\n end\n end\n\n defp write_cached_deps(project, env_target, deps) do\n Mix.ProjectStack.write_cache({:cached_deps, project}, {env_target, deps})\n deps\n end\n\n @doc \"\"\"\n Clears loaded dependencies from the cache for the current environment.\n \"\"\"\n def clear_cached() do\n if project = Mix.Project.get() do\n key = {:cached_deps, project}\n Mix.ProjectStack.delete_cache(key)\n end\n end\n\n @doc \"\"\"\n Returns loaded dependencies recursively on the given environment.\n\n If no environment is passed, dependencies are loaded across all\n environments. The result is not cached.\n\n ## Exceptions\n\n This function raises an exception if any of the dependencies\n provided in the project are in the wrong format.\n \"\"\"\n def load_on_environment(opts) do\n converge(opts)\n end\n\n defp converge(opts) do\n Mix.Dep.Converger.converge(nil, nil, opts, &{&1, &2, &3}) |> elem(0)\n end\n\n @doc \"\"\"\n Filters the given dependencies by name.\n\n Raises if any of the names are missing.\n \"\"\"\n def filter_by_name(given, all_deps, opts \\\\ []) do\n # Ensure all apps are atoms\n apps = to_app_names(given)\n\n deps =\n if opts[:include_children] do\n seen = populate_seen(MapSet.new(), apps)\n get_deps(all_deps, Enum.uniq(get_children(all_deps, seen, apps)))\n else\n get_deps(all_deps, apps)\n end\n\n Enum.each(apps, fn app ->\n unless Enum.any?(all_deps, &(&1.app == app)) do\n Mix.raise(\"Unknown dependency #{app} for environment #{Mix.env()}\")\n end\n end)\n\n deps\n end\n\n defp get_deps(all_deps, apps) do\n Enum.filter(all_deps, &(&1.app in apps))\n end\n\n defp get_children(_all_deps, _seen, []), do: []\n\n defp get_children(all_deps, seen, apps) do\n children_apps =\n for %{deps: children} <- get_deps(all_deps, apps),\n %{app: app} <- children,\n app not in seen,\n do: app\n\n apps ++ get_children(all_deps, populate_seen(seen, children_apps), children_apps)\n end\n\n defp populate_seen(seen, apps) do\n Enum.reduce(apps, seen, &MapSet.put(&2, &1))\n end\n\n @doc \"\"\"\n Runs the given `fun` inside the given dependency project by\n changing the current working directory and loading the given\n project onto the project stack.\n\n It expects a loaded dependency as argument.\n \"\"\"\n def in_dependency(dep, post_config \\\\ [], fun)\n\n def in_dependency(%Mix.Dep{app: app, opts: opts, scm: scm}, config, fun) do\n # Set the app_path to be the one stored in the dependency.\n # This is important because the name of application in the\n # mix.exs file can be different than the actual name and we\n # choose to respect the one in the mix.exs\n config =\n Keyword.merge(Mix.Project.deps_config(), config)\n |> Keyword.put(:app_path, opts[:build])\n |> Keyword.put(:build_scm, scm)\n\n env = opts[:env] || :prod\n old_env = Mix.env()\n\n try do\n Mix.env(env)\n Mix.Project.in_project(app, opts[:dest], config, fun)\n after\n Mix.env(old_env)\n end\n end\n\n @doc \"\"\"\n Formats the status of a dependency.\n \"\"\"\n def format_status(%Mix.Dep{status: {:ok, _vsn}}) do\n \"ok\"\n end\n\n def format_status(%Mix.Dep{status: {:noappfile, path}}) do\n \"could not find an app file at #{inspect(Path.relative_to_cwd(path))}. \" <>\n \"This may happen if the dependency was not yet compiled, \" <>\n \"or you specified the wrong application name in your deps, \" <>\n \"or the dependency indeed has no app file (then you can pass app: false as option)\"\n end\n\n def format_status(%Mix.Dep{status: {:invalidapp, path}}) do\n \"the app file at #{inspect(Path.relative_to_cwd(path))} is invalid\"\n end\n\n def format_status(%Mix.Dep{status: {:invalidvsn, vsn}}) do\n \"the app file contains an invalid version: #{inspect(vsn)}\"\n end\n\n def format_status(%Mix.Dep{status: {:nosemver, vsn}, requirement: req}) do\n \"the app file specified a non-Semantic Versioning format: #{inspect(vsn)}. Mix can only match the \" <>\n \"requirement #{inspect(req)} against semantic versions. Please fix the application version \" <>\n \"or use a regular expression as a requirement to match against any version\"\n end\n\n def format_status(%Mix.Dep{status: {:nomatchvsn, vsn}, requirement: req}) do\n \"the dependency does not match the requirement #{inspect(req)}, got #{inspect(vsn)}\"\n end\n\n def format_status(%Mix.Dep{status: {:lockmismatch, _}}) do\n \"lock mismatch: the dependency is out of date. To fetch locked version run \\\"mix deps.get\\\"\"\n end\n\n def format_status(%Mix.Dep{status: :lockoutdated}) do\n \"lock outdated: the lock is outdated compared to the options in your mix.exs. To fetch \" <>\n \"locked version run \\\"mix deps.get\\\"\"\n end\n\n def format_status(%Mix.Dep{status: :nolock}) do\n \"the dependency is not locked. To generate the \\\"mix.lock\\\" file run \\\"mix deps.get\\\"\"\n end\n\n def format_status(%Mix.Dep{status: :compile}) do\n \"the dependency build is outdated, please run \\\"#{mix_env_var()}mix deps.compile\\\"\"\n end\n\n def format_status(%Mix.Dep{app: app, status: {:divergedreq, vsn, other}} = dep) do\n \"the dependency #{app} #{vsn}\\n\" <>\n dep_status(dep) <>\n \"\\n does not match the requirement specified\\n\" <>\n dep_status(other) <>\n \"\\n Ensure they match or specify one of the above in your deps and set \\\"override: true\\\"\"\n end\n\n def format_status(%Mix.Dep{app: app, status: {:divergedonly, other}} = dep) do\n recommendation =\n if Keyword.has_key?(other.opts, :only) do\n \"Ensure you specify at least the same environments in :only in your dep\"\n else\n \"Remove the :only restriction from your dep\"\n end\n\n \"the :only option for dependency #{app}\\n\" <>\n dep_status(dep) <>\n \"\\n does not match the :only option calculated for\\n\" <>\n dep_status(other) <> \"\\n #{recommendation}\"\n end\n\n def format_status(%Mix.Dep{app: app, status: {:divergedtargets, other}} = dep) do\n recommendation =\n if Keyword.has_key?(other.opts, :targets) do\n \"Ensure you specify at least the same targets in :targets in your dep\"\n else\n \"Remove the :targets restriction from your dep\"\n end\n\n \"the :targets option for dependency #{app}\\n\" <>\n dep_status(dep) <>\n \"\\n does not match the :targets option calculated for\\n\" <>\n dep_status(other) <> \"\\n #{recommendation}\"\n end\n\n def format_status(%Mix.Dep{app: app, status: {:diverged, other}} = dep) do\n \"different specs were given for the #{app} app:\\n\" <>\n \"#{dep_status(dep)}#{dep_status(other)}\" <>\n \"\\n Ensure they match or specify one of the above in your deps and set \\\"override: true\\\"\"\n end\n\n def format_status(%Mix.Dep{app: app, status: {:overridden, other}} = dep) do\n \"the dependency #{app} in #{Path.relative_to_cwd(dep.from)} is overriding a child dependency:\\n\" <>\n \"#{dep_status(dep)}#{dep_status(other)}\" <>\n \"\\n Ensure they match or specify one of the above in your deps and set \\\"override: true\\\"\"\n end\n\n def format_status(%Mix.Dep{status: {:unavailable, _}, scm: scm}) do\n if scm.fetchable?() do\n \"the dependency is not available, run \\\"mix deps.get\\\"\"\n else\n \"the dependency is not available\"\n end\n end\n\n def format_status(%Mix.Dep{status: {:elixirlock, _}}) do\n \"the dependency was built with an out-of-date Elixir version, run \\\"#{mix_env_var()}mix deps.compile\\\"\"\n end\n\n def format_status(%Mix.Dep{status: {:scmlock, _}}) do\n \"the dependency was built with another SCM, run \\\"#{mix_env_var()}mix deps.compile\\\"\"\n end\n\n defp dep_status(%Mix.Dep{} = dep) do\n %{\n app: app,\n requirement: req,\n manager: manager,\n opts: opts,\n from: from,\n system_env: system_env\n } = dep\n\n opts =\n []\n |> Kernel.++(if manager, do: [manager: manager], else: [])\n |> Kernel.++(if system_env != [], do: [system_env: system_env], else: [])\n |> Kernel.++(opts)\n |> Keyword.drop([:dest, :build, :lock, :manager, :checkout])\n\n info = if req, do: {app, req, opts}, else: {app, opts}\n \"\\n > In #{Path.relative_to_cwd(from)}:\\n #{inspect(info)}\\n\"\n end\n\n @doc \"\"\"\n Checks the lock for the given dependency and update its status accordingly.\n \"\"\"\n def check_lock(%Mix.Dep{scm: scm, opts: opts} = dep) do\n if available?(dep) do\n case scm.lock_status(opts) do\n :mismatch ->\n status = if rev = opts[:lock], do: {:lockmismatch, rev}, else: :nolock\n %{dep | status: status}\n\n :outdated ->\n # Don't include the lock in the dependency if it is outdated\n %{dep | status: :lockoutdated}\n\n :ok ->\n check_manifest(dep, opts[:build])\n end\n else\n dep\n end\n end\n\n defp check_manifest(%{scm: scm} = dep, build_path) do\n vsn = {System.version(), :erlang.system_info(:otp_release)}\n\n case Mix.Dep.ElixirSCM.read(Path.join(build_path, \".mix\")) do\n {:ok, old_vsn, _} when old_vsn != vsn ->\n %{dep | status: {:elixirlock, old_vsn}}\n\n {:ok, _, old_scm} when old_scm != scm ->\n %{dep | status: {:scmlock, old_scm}}\n\n _ ->\n dep\n end\n end\n\n @doc \"\"\"\n Returns `true` if the dependency is ok.\n \"\"\"\n def ok?(%Mix.Dep{status: {:ok, _}}), do: true\n def ok?(%Mix.Dep{}), do: false\n\n @doc \"\"\"\n Checks if a dependency is available.\n\n Available dependencies are the ones that can be loaded.\n \"\"\"\n def available?(%Mix.Dep{status: {:unavailable, _}}), do: false\n def available?(dep), do: not diverged?(dep)\n\n @doc \"\"\"\n Checks if a dependency has diverged.\n \"\"\"\n def diverged?(%Mix.Dep{status: {:overridden, _}}), do: true\n def diverged?(%Mix.Dep{status: {:diverged, _}}), do: true\n def diverged?(%Mix.Dep{status: {:divergedreq, _}}), do: true\n def diverged?(%Mix.Dep{status: {:divergedonly, _}}), do: true\n def diverged?(%Mix.Dep{status: {:divergedtargets, _}}), do: true\n def diverged?(%Mix.Dep{}), do: false\n\n @doc \"\"\"\n Returns `true` if the dependency is compilable.\n \"\"\"\n def compilable?(%Mix.Dep{status: {:elixirlock, _}}), do: true\n def compilable?(%Mix.Dep{status: {:noappfile, _}}), do: true\n def compilable?(%Mix.Dep{status: {:scmlock, _}}), do: true\n def compilable?(%Mix.Dep{status: :compile}), do: true\n def compilable?(_), do: false\n\n @doc \"\"\"\n Formats a dependency for printing.\n \"\"\"\n def format_dep(%Mix.Dep{scm: scm, app: app, status: status, opts: opts}) do\n version =\n case status do\n {:ok, vsn} when vsn != nil -> \"#{vsn} \"\n _ -> \"\"\n end\n\n \"#{app} #{version}(#{scm.format(opts)})\"\n end\n\n @doc \"\"\"\n Returns all load paths for the given dependency.\n\n Automatically derived from source paths.\n \"\"\"\n def load_paths(%Mix.Dep{opts: opts} = dep) do\n build_path = Path.dirname(opts[:build])\n\n Enum.map(source_paths(dep), fn {_, base} ->\n Path.join([build_path, base, \"ebin\"])\n end)\n end\n\n @doc \"\"\"\n Returns all source paths.\n\n Source paths are the directories that contain ebin files for a given\n dependency. All managers, except `:rebar`, have only one source path.\n \"\"\"\n def source_paths(%Mix.Dep{manager: :rebar, app: app, opts: opts, extra: extra}) do\n sub_dirs = extra[:sub_dirs] || []\n dest = opts[:dest]\n\n # Add root dir and all sub dirs with ebin\/ directory\n in_sub_dirs =\n for sub_dir <- sub_dirs,\n path <- Path.wildcard(Path.join(dest, sub_dir)),\n File.dir?(Path.join(path, \"ebin\")),\n do: {path, Path.basename(path)}\n\n [{opts[:dest], Atom.to_string(app)}] ++ in_sub_dirs\n end\n\n def source_paths(%Mix.Dep{app: app, opts: opts}) do\n [{opts[:dest], Atom.to_string(app)}]\n end\n\n @doc \"\"\"\n Returns `true` if dependency is a Mix project.\n \"\"\"\n def mix?(%Mix.Dep{manager: manager}) do\n manager == :mix\n end\n\n @doc \"\"\"\n Returns `true` if dependency is a Rebar project.\n \"\"\"\n def rebar?(%Mix.Dep{manager: manager}) do\n manager in [:rebar, :rebar3]\n end\n\n @doc \"\"\"\n Returns `true` if dependency is a Make project.\n \"\"\"\n def make?(%Mix.Dep{manager: manager}) do\n manager == :make\n end\n\n ## Helpers\n\n defp mix_env_var do\n if Mix.env() == :dev do\n \"\"\n else\n \"MIX_ENV=#{Mix.env()} \"\n end\n end\n\n defp to_app_names(given) do\n Enum.map(given, fn app ->\n if is_binary(app), do: String.to_atom(app), else: app\n end)\n end\nend\n","old_contents":"defmodule Mix.Dep do\n @moduledoc false\n\n @doc \"\"\"\n The Mix.Dep struct keeps information about your project dependencies.\n\n It contains:\n\n * `scm` - a module representing the source code management tool (SCM)\n operations\n\n * `app` - the application name as an atom\n\n * `requirement` - a binary or regular expression with the dependency's requirement\n\n * `status` - the current status of the dependency, check\n `Mix.Dep.format_status\/1` for more information\n\n * `opts` - the options given by the developer\n\n * `deps` - dependencies of this dependency\n\n * `top_level` - true if dependency was defined in the top-level project\n\n * `manager` - the project management, possible values:\n `:rebar` | `:rebar3` | `:mix` | `:make` | `nil`\n\n * `from` - path to the file where the dependency was defined\n\n * `extra` - a slot for adding extra configuration based on the manager;\n the information on this field is private to the manager and should not be\n relied on\n\n * `system_env` - an enumerable of key-value tuples of binaries to be set as environment variables\n when loading or compiling the dependency\n\n A dependency is in two specific states: loaded and unloaded.\n\n When a dependency is unloaded, it means Mix only parsed its specification\n and made no attempt to actually load the dependency or validate its\n status. When the dependency is loaded, it means Mix attempted to fetch,\n load and validate it, the status is set in the status field.\n\n Furthermore, in the `opts` fields, Mix keeps some internal options, which\n can be accessed by SCMs:\n\n * `:app` - the application name\n * `:dest` - the destination path for the dependency\n * `:lock` - the lock information retrieved from mix.lock\n * `:build` - the build path for the dependency\n\n \"\"\"\n defstruct scm: nil,\n app: nil,\n requirement: nil,\n status: nil,\n opts: [],\n deps: [],\n top_level: false,\n extra: [],\n manager: nil,\n from: nil,\n system_env: []\n\n @type t :: %__MODULE__{\n scm: module,\n app: atom,\n requirement: String.t() | Regex.t() | nil,\n status: atom,\n opts: keyword,\n top_level: boolean,\n manager: :rebar | :rebar3 | :mix | :make | nil,\n from: String.t(),\n extra: term,\n system_env: keyword\n }\n\n @doc \"\"\"\n Returns loaded dependencies from the cache for the current environment.\n\n If dependencies have not been cached yet, they are loaded\n and then cached.\n\n Because the dependencies are cached during deps.loadpaths,\n their status may be outdated (for example, `:compile` did not\n yet become `:ok`). Therefore it is recommended to not rely\n on their status, also given they haven't been checked\n against the lock.\n \"\"\"\n def cached() do\n if project = Mix.Project.get() do\n read_cached_deps(project, {Mix.env(), Mix.target()}) || load_and_cache()\n else\n load_and_cache()\n end\n end\n\n @doc \"\"\"\n Returns loaded dependencies recursively and caches it.\n\n The result is cached for future `cached\/0` calls.\n\n ## Exceptions\n\n This function raises an exception if any of the dependencies\n provided in the project are in the wrong format.\n \"\"\"\n def load_and_cache() do\n env = Mix.env()\n target = Mix.target()\n\n case Mix.ProjectStack.top_and_bottom() do\n {%{name: top, config: config}, %{name: bottom}} ->\n write_cached_deps(top, {env, target}, load_and_cache(config, top, bottom, env, target))\n\n _ ->\n converge(env: env, target: target)\n end\n end\n\n defp load_and_cache(_config, top, top, env, target) do\n converge(env: env, target: target)\n end\n\n defp load_and_cache(config, _top, bottom, _env, _target) do\n {_, deps} = Mix.ProjectStack.read_cache({:cached_deps, bottom})\n app = Keyword.fetch!(config, :app)\n seen = populate_seen(MapSet.new(), [app])\n children = get_deps(deps, tl(Enum.uniq(get_children(deps, seen, [app]))))\n\n top_level =\n for dep <- deps,\n dep.app == app,\n child <- dep.deps,\n do: {child.app, Keyword.get(child.opts, :optional, false)},\n into: %{}\n\n Enum.map(children, fn %{app: app, opts: opts} = dep ->\n # optional only matters at the top level. Any non-top level dependency\n # that is optional and is still available means it has been fulfilled.\n case top_level do\n %{^app => optional} ->\n %{dep | top_level: true, opts: Keyword.put(opts, :optional, optional)}\n\n %{} ->\n %{dep | top_level: false, opts: Keyword.delete(opts, :optional)}\n end\n end)\n end\n\n defp read_cached_deps(project, env_target) do\n case Mix.ProjectStack.read_cache({:cached_deps, project}) do\n {^env_target, deps} -> deps\n _ -> nil\n end\n end\n\n defp write_cached_deps(project, env_target, deps) do\n Mix.ProjectStack.write_cache({:cached_deps, project}, {env_target, deps})\n deps\n end\n\n @doc \"\"\"\n Clears loaded dependencies from the cache for the current environment.\n \"\"\"\n def clear_cached() do\n if project = Mix.Project.get() do\n key = {:cached_deps, project}\n Mix.ProjectStack.delete_cache(key)\n end\n end\n\n @doc \"\"\"\n Returns loaded dependencies recursively on the given environment.\n\n If no environment is passed, dependencies are loaded across all\n environments. The result is not cached.\n\n ## Exceptions\n\n This function raises an exception if any of the dependencies\n provided in the project are in the wrong format.\n \"\"\"\n def load_on_environment(opts) do\n converge(opts)\n end\n\n defp converge(opts) do\n Mix.Dep.Converger.converge(nil, nil, opts, &{&1, &2, &3}) |> elem(0)\n end\n\n @doc \"\"\"\n Filters the given dependencies by name.\n\n Raises if any of the names are missing.\n \"\"\"\n def filter_by_name(given, all_deps, opts \\\\ []) do\n # Ensure all apps are atoms\n apps = to_app_names(given)\n\n deps =\n if opts[:include_children] do\n seen = populate_seen(MapSet.new(), apps)\n get_deps(all_deps, Enum.uniq(get_children(all_deps, seen, apps)))\n else\n get_deps(all_deps, apps)\n end\n\n Enum.each(apps, fn app ->\n unless Enum.any?(all_deps, &(&1.app == app)) do\n Mix.raise(\"Unknown dependency #{app} for environment #{Mix.env()}\")\n end\n end)\n\n deps\n end\n\n defp get_deps(all_deps, apps) do\n Enum.filter(all_deps, &(&1.app in apps))\n end\n\n defp get_children(_all_deps, _seen, []), do: []\n\n defp get_children(all_deps, seen, apps) do\n children_apps =\n for %{deps: children} <- get_deps(all_deps, apps),\n %{app: app} <- children,\n app not in seen,\n do: app\n\n apps ++ get_children(all_deps, populate_seen(seen, children_apps), children_apps)\n end\n\n defp populate_seen(seen, apps) do\n Enum.reduce(apps, seen, &MapSet.put(&2, &1))\n end\n\n @doc \"\"\"\n Runs the given `fun` inside the given dependency project by\n changing the current working directory and loading the given\n project onto the project stack.\n\n It expects a loaded dependency as argument.\n \"\"\"\n def in_dependency(dep, post_config \\\\ [], fun)\n\n def in_dependency(%Mix.Dep{app: app, opts: opts, scm: scm}, config, fun) do\n # Set the app_path to be the one stored in the dependency.\n # This is important because the name of application in the\n # mix.exs file can be different than the actual name and we\n # choose to respect the one in the mix.exs\n config =\n Keyword.merge(Mix.Project.deps_config(), config)\n |> Keyword.put(:app_path, opts[:build])\n |> Keyword.put(:build_scm, scm)\n\n env = opts[:env] || :prod\n old_env = Mix.env()\n\n try do\n Mix.env(env)\n Mix.Project.in_project(app, opts[:dest], config, fun)\n after\n Mix.env(old_env)\n end\n end\n\n @doc \"\"\"\n Formats the status of a dependency.\n \"\"\"\n def format_status(%Mix.Dep{status: {:ok, _vsn}}) do\n \"ok\"\n end\n\n def format_status(%Mix.Dep{status: {:noappfile, path}}) do\n \"could not find an app file at #{inspect(Path.relative_to_cwd(path))}. \" <>\n \"This may happen if the dependency was not yet compiled, \" <>\n \"or you specified the wrong application name in your deps, \" <>\n \"or the dependency indeed has no app file (then you can pass app: false as option)\"\n end\n\n def format_status(%Mix.Dep{status: {:invalidapp, path}}) do\n \"the app file at #{inspect(Path.relative_to_cwd(path))} is invalid\"\n end\n\n def format_status(%Mix.Dep{status: {:invalidvsn, vsn}}) do\n \"the app file contains an invalid version: #{inspect(vsn)}\"\n end\n\n def format_status(%Mix.Dep{status: {:nosemver, vsn}, requirement: req}) do\n \"the app file specified a non-Semantic Versioning format: #{inspect(vsn)}. Mix can only match the \" <>\n \"requirement #{inspect(req)} against semantic versions. Please fix the application version \" <>\n \"or use a regular expression as a requirement to match against any version\"\n end\n\n def format_status(%Mix.Dep{status: {:nomatchvsn, vsn}, requirement: req}) do\n \"the dependency does not match the requirement #{inspect(req)}, got #{inspect(vsn)}\"\n end\n\n def format_status(%Mix.Dep{status: {:lockmismatch, _}}) do\n \"lock mismatch: the dependency is out of date. To fetch locked version run \\\"mix deps.get\\\"\"\n end\n\n def format_status(%Mix.Dep{status: :lockoutdated}) do\n \"lock outdated: the lock is outdated compared to the options in your mix.exs. To fetch \" <>\n \"locked version run \\\"mix deps.get\\\"\"\n end\n\n def format_status(%Mix.Dep{status: :nolock}) do\n \"the dependency is not locked. To generate the \\\"mix.lock\\\" file run \\\"mix deps.get\\\"\"\n end\n\n def format_status(%Mix.Dep{status: :compile}) do\n \"the dependency build is outdated, please run \\\"#{mix_env_var()}mix deps.compile\\\"\"\n end\n\n def format_status(%Mix.Dep{app: app, status: {:divergedreq, vsn, other}} = dep) do\n \"the dependency #{app} #{vsn}\\n\" <>\n dep_status(dep) <>\n \"\\n does not match the requirement specified\\n\" <>\n dep_status(other) <>\n \"\\n Ensure they match or specify one of the above in your deps and set \\\"override: true\\\"\"\n end\n\n def format_status(%Mix.Dep{app: app, status: {:divergedonly, other}} = dep) do\n recommendation =\n if Keyword.has_key?(other.opts, :only) do\n \"Ensure you specify at least the same environments in :only in your dep\"\n else\n \"Remove the :only restriction from your dep\"\n end\n\n \"the :only option for dependency #{app}\\n\" <>\n dep_status(dep) <>\n \"\\n does not match the :only option calculated for\\n\" <>\n dep_status(other) <> \"\\n #{recommendation}\"\n end\n\n def format_status(%Mix.Dep{app: app, status: {:divergedtargets, other}} = dep) do\n recommendation =\n if Keyword.has_key?(other.opts, :targets) do\n \"Ensure you specify at least the same targets in :targets in your dep\"\n else\n \"Remove the :targets restriction from your dep\"\n end\n\n \"the :targets option for dependency #{app}\\n\" <>\n dep_status(dep) <>\n \"\\n does not match the :targets option calculated for\\n\" <>\n dep_status(other) <> \"\\n #{recommendation}\"\n end\n\n def format_status(%Mix.Dep{app: app, status: {:diverged, other}} = dep) do\n \"different specs were given for the #{app} app:\\n\" <>\n \"#{dep_status(dep)}#{dep_status(other)}\" <>\n \"\\n Ensure they match or specify one of the above in your deps and set \\\"override: true\\\"\"\n end\n\n def format_status(%Mix.Dep{app: app, status: {:overridden, other}} = dep) do\n \"the dependency #{app} in #{Path.relative_to_cwd(dep.from)} is overriding a child dependency:\\n\" <>\n \"#{dep_status(dep)}#{dep_status(other)}\" <>\n \"\\n Ensure they match or specify one of the above in your deps and set \\\"override: true\\\"\"\n end\n\n def format_status(%Mix.Dep{status: {:unavailable, _}, scm: scm}) do\n if scm.fetchable?() do\n \"the dependency is not available, run \\\"mix deps.get\\\"\"\n else\n \"the dependency is not available\"\n end\n end\n\n def format_status(%Mix.Dep{status: {:elixirlock, _}}) do\n \"the dependency was built with an out-of-date Elixir version, run \\\"#{mix_env_var()}mix deps.compile\\\"\"\n end\n\n def format_status(%Mix.Dep{status: {:scmlock, _}}) do\n \"the dependency was built with another SCM, run \\\"#{mix_env_var()}mix deps.compile\\\"\"\n end\n\n defp dep_status(%Mix.Dep{} = dep) do\n %{\n app: app,\n requirement: req,\n manager: manager,\n opts: opts,\n from: from,\n system_env: system_env\n } = dep\n\n opts =\n []\n |> Kernel.++(if manager, do: [manager: manager], else: [])\n |> Kernel.++(if system_env != [], do: [system_env: system_env], else: [])\n |> Kernel.++(opts)\n |> Keyword.drop([:dest, :build, :lock, :manager, :checkout])\n\n info = if req, do: {app, req, opts}, else: {app, opts}\n \"\\n > In #{Path.relative_to_cwd(from)}:\\n #{inspect(info)}\\n\"\n end\n\n @doc \"\"\"\n Checks the lock for the given dependency and update its status accordingly.\n \"\"\"\n def check_lock(%Mix.Dep{scm: scm, opts: opts} = dep) do\n if available?(dep) do\n case scm.lock_status(opts) do\n :mismatch ->\n status = if rev = opts[:lock], do: {:lockmismatch, rev}, else: :nolock\n %{dep | status: status}\n\n :outdated ->\n # Don't include the lock in the dependency if it is outdated\n %{dep | status: :lockoutdated}\n\n :ok ->\n check_manifest(dep, opts[:build])\n end\n else\n dep\n end\n end\n\n defp check_manifest(%{scm: scm} = dep, build_path) do\n vsn = {System.version(), :erlang.system_info(:otp_release)}\n\n case Mix.Dep.ElixirSCM.read(Path.join(build_path, \".mix\")) do\n {:ok, old_vsn, _} when old_vsn != vsn ->\n %{dep | status: {:elixirlock, old_vsn}}\n\n {:ok, _, old_scm} when old_scm != scm ->\n %{dep | status: {:scmlock, old_scm}}\n\n _ ->\n dep\n end\n end\n\n @doc \"\"\"\n Returns `true` if the dependency is ok.\n \"\"\"\n def ok?(%Mix.Dep{status: {:ok, _}}), do: true\n def ok?(%Mix.Dep{}), do: false\n\n @doc \"\"\"\n Checks if a dependency is available.\n\n Available dependencies are the ones that can be loaded.\n \"\"\"\n def available?(%Mix.Dep{status: {:unavailable, _}}), do: false\n def available?(dep), do: not diverged?(dep)\n\n @doc \"\"\"\n Checks if a dependency has diverged.\n \"\"\"\n def diverged?(%Mix.Dep{status: {:overridden, _}}), do: true\n def diverged?(%Mix.Dep{status: {:diverged, _}}), do: true\n def diverged?(%Mix.Dep{status: {:divergedreq, _}}), do: true\n def diverged?(%Mix.Dep{status: {:divergedonly, _}}), do: true\n def diverged?(%Mix.Dep{status: {:divergedtargets, _}}), do: true\n def diverged?(%Mix.Dep{}), do: false\n\n @doc \"\"\"\n Returns `true` if the dependency is compilable.\n \"\"\"\n def compilable?(%Mix.Dep{status: {:elixirlock, _}}), do: true\n def compilable?(%Mix.Dep{status: {:noappfile, _}}), do: true\n def compilable?(%Mix.Dep{status: {:scmlock, _}}), do: true\n def compilable?(%Mix.Dep{status: :compile}), do: true\n def compilable?(_), do: false\n\n @doc \"\"\"\n Formats a dependency for printing.\n \"\"\"\n def format_dep(%Mix.Dep{scm: scm, app: app, status: status, opts: opts}) do\n version =\n case status do\n {:ok, vsn} when vsn != nil -> \"#{vsn} \"\n _ -> \"\"\n end\n\n \"#{app} #{version}(#{scm.format(opts)})\"\n end\n\n @doc \"\"\"\n Returns all load paths for the given dependency.\n\n Automatically derived from source paths.\n \"\"\"\n def load_paths(%Mix.Dep{opts: opts} = dep) do\n build_path = Path.dirname(opts[:build])\n\n Enum.map(source_paths(dep), fn {_, base} ->\n Path.join([build_path, base, \"ebin\"])\n end)\n end\n\n @doc \"\"\"\n Returns all source paths.\n\n Source paths are the directories that contain ebin files for a given\n dependency. All managers, except `:rebar`, have only one source path.\n \"\"\"\n def source_paths(%Mix.Dep{manager: :rebar, app: app, opts: opts, extra: extra}) do\n sub_dirs = extra[:sub_dirs] || []\n dest = opts[:dest]\n\n # Add root dir and all sub dirs with ebin\/ directory\n in_sub_dirs =\n for sub_dir <- sub_dirs,\n path <- Path.wildcard(Path.join(dest, sub_dir)),\n File.dir?(Path.join(path, \"ebin\")),\n do: {path, Path.basename(path)}\n\n [{opts[:dest], Atom.to_string(app)}] ++ in_sub_dirs\n end\n\n def source_paths(%Mix.Dep{app: app, opts: opts}) do\n [{opts[:dest], Atom.to_string(app)}]\n end\n\n @doc \"\"\"\n Returns `true` if dependency is a Mix project.\n \"\"\"\n def mix?(%Mix.Dep{manager: manager}) do\n manager == :mix\n end\n\n @doc \"\"\"\n Returns `true` if dependency is a Rebar project.\n \"\"\"\n def rebar?(%Mix.Dep{manager: manager}) do\n manager in [:rebar, :rebar3]\n end\n\n @doc \"\"\"\n Returns `true` if dependency is a Make project.\n \"\"\"\n def make?(%Mix.Dep{manager: manager}) do\n manager == :make\n end\n\n ## Helpers\n\n defp mix_env_var do\n if Mix.env() == :dev do\n \"\"\n else\n \"MIX_ENV=#{Mix.env()} \"\n end\n end\n\n defp to_app_names(given) do\n Enum.map(given, fn app ->\n if is_binary(app), do: String.to_atom(app), else: app\n end)\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"f411260100a600e9f07b5e102d8fc0567284c848","subject":"Get field from changeset properly.","message":"Get field from changeset properly.\n","repos":"digitalnatives\/course_planner,digitalnatives\/course_planner,digitalnatives\/course_planner","old_file":"web\/models\/class\/class.ex","new_file":"web\/models\/class\/class.ex","new_contents":"defmodule CoursePlanner.Class do\n @moduledoc \"\"\"\n This module holds the model for the class table\n \"\"\"\n use CoursePlanner.Web, :model\n\n alias CoursePlanner.{Repo, OfferedCourse, Attendance}\n alias Ecto.{Time, Date, Changeset}\n\n schema \"classes\" do\n field :date, Date\n field :starting_at, Time\n field :finishes_at, Time\n field :classroom, :string\n belongs_to :offered_course, OfferedCourse\n has_many :attendances, Attendance, on_delete: :delete_all\n has_many :students, through: [:offered_course, :students]\n\n timestamps()\n end\n\n @doc \"\"\"\n Builds a changeset based on the `struct` and `params`.\n \"\"\"\n def changeset(struct, params \\\\ %{}) do\n cast_params =\n [:offered_course_id, :date, :starting_at, :finishes_at, :classroom]\n\n struct\n |> cast(params, cast_params)\n |> validate_required([:offered_course_id, :date, :starting_at, :finishes_at])\n |> validate_date()\n end\n\n def changeset(struct, params, :create) do\n struct\n |> changeset(params)\n |> validate_offered_course()\n |> validate_duration()\n end\n\n def changeset(struct, params, :update) do\n struct\n |> changeset(params)\n |> validate_duration()\n end\n\n def validate_duration(%{changes: changes, valid?: true} = changeset) do\n starting_at = Map.get(changes, :starting_at) || Map.get(changeset.data, :starting_at)\n finishes_at = Map.get(changes, :finishes_at) || Map.get(changeset.data, :finishes_at)\n\n cond do\n Time.compare(starting_at, Time.from_erl({0, 0, 0})) == :eq ->\n add_error(changeset, :starting_at, \"Starting time cannot be zero\")\n\n Time.compare(finishes_at, Time.from_erl({0, 0, 0})) == :eq ->\n add_error(changeset, :finishes_at, \"Finishing time cannot be zero\")\n\n Time.compare(starting_at, finishes_at) != :lt ->\n add_error(changeset, :finishes_at,\n \"Finishing time should be greater than the starting time\")\n\n true -> changeset\n end\n end\n\n def validate_duration(changeset), do: changeset\n\n def validate_offered_course(%{changes: changes, valid?: true} = changeset) do\n offered_course_id = Map.get(changes, :offered_course_id)\n\n query = from oc in OfferedCourse,\n join: t in assoc(oc, :teachers),\n join: s in assoc(oc, :students),\n preload: [teachers: t, students: s],\n where: oc.id == ^offered_course_id\n\n case Repo.one(query) do\n nil -> add_error(changeset, :offered_course_status,\n \"Attached course should have at least one teacher and one student\")\n _ -> changeset\n end\n end\n def validate_offered_course(changeset), do: changeset\n\n defp validate_date(%{valid?: true} = changeset) do\n term = OfferedCourse\n |> Repo.get(Changeset.get_field(changeset, :offered_course_id))\n |> Repo.preload([:term])\n |> Map.get(:term)\n\n st = term\n |> Map.get(:start_date)\n |> Date.cast!()\n\n en = term\n |> Map.get(:end_date)\n |> Date.cast!()\n\n date = Changeset.get_field(changeset, :date)\n\n case {Date.compare(st, date), Date.compare(en, date)} do\n {:gt, _} -> Changeset.add_error(changeset, :date,\n \"is before term's beginning\")\n {_, :lt} -> Changeset.add_error(changeset, :date,\n \"is after term's end\")\n {_, _} -> changeset\n end\n end\n defp validate_date(changeset), do: changeset\nend\n","old_contents":"defmodule CoursePlanner.Class do\n @moduledoc \"\"\"\n This module holds the model for the class table\n \"\"\"\n use CoursePlanner.Web, :model\n\n alias CoursePlanner.{Repo, OfferedCourse, Attendance}\n alias Ecto.{Time, Date, Changeset}\n\n schema \"classes\" do\n field :date, Date\n field :starting_at, Time\n field :finishes_at, Time\n field :classroom, :string\n belongs_to :offered_course, OfferedCourse\n has_many :attendances, Attendance, on_delete: :delete_all\n has_many :students, through: [:offered_course, :students]\n\n timestamps()\n end\n\n @doc \"\"\"\n Builds a changeset based on the `struct` and `params`.\n \"\"\"\n def changeset(struct, params \\\\ %{}) do\n cast_params =\n [:offered_course_id, :date, :starting_at, :finishes_at, :classroom]\n\n struct\n |> cast(params, cast_params)\n |> validate_required([:offered_course_id, :date, :starting_at, :finishes_at])\n |> validate_date()\n end\n\n def changeset(struct, params, :create) do\n struct\n |> changeset(params)\n |> validate_offered_course()\n |> validate_duration()\n end\n\n def changeset(struct, params, :update) do\n struct\n |> changeset(params)\n |> validate_duration()\n end\n\n def validate_duration(%{changes: changes, valid?: true} = changeset) do\n starting_at = Map.get(changes, :starting_at) || Map.get(changeset.data, :starting_at)\n finishes_at = Map.get(changes, :finishes_at) || Map.get(changeset.data, :finishes_at)\n\n cond do\n Time.compare(starting_at, Time.from_erl({0, 0, 0})) == :eq ->\n add_error(changeset, :starting_at, \"Starting time cannot be zero\")\n\n Time.compare(finishes_at, Time.from_erl({0, 0, 0})) == :eq ->\n add_error(changeset, :finishes_at, \"Finishing time cannot be zero\")\n\n Time.compare(starting_at, finishes_at) != :lt ->\n add_error(changeset, :finishes_at,\n \"Finishing time should be greater than the starting time\")\n\n true -> changeset\n end\n end\n\n def validate_duration(changeset), do: changeset\n\n def validate_offered_course(%{changes: changes, valid?: true} = changeset) do\n offered_course_id = Map.get(changes, :offered_course_id)\n\n query = from oc in OfferedCourse,\n join: t in assoc(oc, :teachers),\n join: s in assoc(oc, :students),\n preload: [teachers: t, students: s],\n where: oc.id == ^offered_course_id\n\n case Repo.one(query) do\n nil -> add_error(changeset, :offered_course_status,\n \"Attached course should have at least one teacher and one student\")\n _ -> changeset\n end\n end\n def validate_offered_course(changeset), do: changeset\n\n defp validate_date(%{valid?: true, changes: %{date: date} = changes} = changeset) do\n term = OfferedCourse\n |> Repo.get(changes[:offered_course_id] || changeset.data.offered_course_id)\n |> Repo.preload([:term])\n |> Map.get(:term)\n\n st = term\n |> Map.get(:start_date)\n |> Date.cast!()\n\n en = term\n |> Map.get(:end_date)\n |> Date.cast!()\n\n case {Date.compare(st, date), Date.compare(en, date)} do\n {:gt, _} -> Changeset.add_error(changeset, :date,\n \"is before term's beginning\")\n {_, :lt} -> Changeset.add_error(changeset, :date,\n \"is after term's end\")\n {_, _} -> changeset\n end\n end\n defp validate_date(changeset), do: changeset\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"a9008c07c35cc9f91bd0a64f9c1e4e5fef3f6930","subject":"re-namespaces lookup benchmark","message":"re-namespaces lookup benchmark\n","repos":"mneudert\/geolix,mneudert\/geolix","old_file":"bench\/lookup.exs","new_file":"bench\/lookup.exs","new_contents":"defmodule Geolix.Benchmark.Lookup do\n def run() do\n database =\n [Geolix.TestData.dir(:mmdb2), \"Benchmark.mmdb\"]\n |> Path.join()\n |> Path.expand()\n\n case File.exists?(database) do\n true ->\n Geolix.load_database(%{\n id: :benchmark,\n adapter: Geolix.Adapter.MMDB2,\n source: database\n })\n\n :ok = wait_for_database_loader()\n\n run_benchmark()\n\n false ->\n IO.warn(\"Expected database not found at #{database}\")\n end\n end\n\n defp run_benchmark() do\n {:ok, lookup_ipv4} = :inet.parse_address('1.1.1.1')\n {:ok, lookup_ipv4_in_ipv6} = :inet.parse_address('::1.1.1.1')\n\n Benchee.run(\n %{\n \"IPv4 in IPV6 lookup\" => fn ->\n Geolix.lookup(lookup_ipv4_in_ipv6, where: :benchmark)\n end,\n \"IPv4 lookup\" => fn ->\n Geolix.lookup(lookup_ipv4, where: :benchmark)\n end\n },\n warmup: 2,\n time: 10\n )\n end\n\n defp wait_for_database_loader(), do: wait_for_database_loader(30_000)\n\n defp wait_for_database_loader(0) do\n IO.puts(\"Loading database took longer than 30 seconds. Aborting...\")\n :error\n end\n\n defp wait_for_database_loader(timeout) do\n delay = 50\n loaded = Geolix.Database.Loader.loaded_databases()\n registered = Geolix.Database.Loader.registered_databases()\n\n if 0 < length(registered) && loaded == registered do\n :ok\n else\n :timer.sleep(delay)\n wait_for_database_loader(timeout - delay)\n end\n end\nend\n\nGeolix.Benchmark.Lookup.run()\n","old_contents":"defmodule Geolix.Benchmark do\n def run() do\n database =\n [Geolix.TestData.dir(:mmdb2), \"Benchmark.mmdb\"]\n |> Path.join()\n |> Path.expand()\n\n case File.exists?(database) do\n true ->\n Geolix.load_database(%{\n id: :benchmark,\n adapter: Geolix.Adapter.MMDB2,\n source: database\n })\n\n :ok = wait_for_database_loader()\n\n run_benchmark()\n\n false ->\n IO.warn(\"Expected database not found at #{database}\")\n end\n end\n\n defp run_benchmark() do\n {:ok, lookup_ipv4} = :inet.parse_address('1.1.1.1')\n {:ok, lookup_ipv4_in_ipv6} = :inet.parse_address('::1.1.1.1')\n\n Benchee.run(\n %{\n \"IPv4 in IPV6 lookup\" => fn ->\n Geolix.lookup(lookup_ipv4_in_ipv6, where: :benchmark)\n end,\n \"IPv4 lookup\" => fn ->\n Geolix.lookup(lookup_ipv4, where: :benchmark)\n end\n },\n warmup: 2,\n time: 10\n )\n end\n\n defp wait_for_database_loader(), do: wait_for_database_loader(30_000)\n\n defp wait_for_database_loader(0) do\n IO.puts(\"Loading database took longer than 30 seconds. Aborting...\")\n :error\n end\n\n defp wait_for_database_loader(timeout) do\n delay = 50\n loaded = Geolix.Database.Loader.loaded_databases()\n registered = Geolix.Database.Loader.registered_databases()\n\n if 0 < length(registered) && loaded == registered do\n :ok\n else\n :timer.sleep(delay)\n wait_for_database_loader(timeout - delay)\n end\n end\nend\n\nGeolix.Benchmark.run()\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"f4d145c3a0fc173390c3ba5920c03d615bfe3381","subject":"Fix dependency compilation order","message":"Fix dependency compilation order\n","repos":"lexmag\/elixir,elixir-lang\/elixir,ggcampinho\/elixir,pedrosnk\/elixir,gfvcastro\/elixir,antipax\/elixir,kelvinst\/elixir,kimshrier\/elixir,gfvcastro\/elixir,beedub\/elixir,pedrosnk\/elixir,joshprice\/elixir,beedub\/elixir,antipax\/elixir,michalmuskala\/elixir,kelvinst\/elixir,kimshrier\/elixir,lexmag\/elixir,ggcampinho\/elixir","old_file":"lib\/mix\/lib\/mix\/tasks\/deps.check.ex","new_file":"lib\/mix\/lib\/mix\/tasks\/deps.check.ex","new_contents":"defmodule Mix.Tasks.Deps.Check do\n use Mix.Task\n\n import Mix.Deps, only: [loaded: 0, loaded_by_name: 1, format_dep: 1,\n format_status: 1, check_lock: 2, ok?: 1]\n\n @moduledoc \"\"\"\n Checks if all dependencies are valid and if not, abort.\n Prints the invalid dependencies' status before aborting.\n\n This task is not shown in `mix help` but it is part\n of the `mix` public API and can be depended on.\n\n ## Command line options\n\n * `--no-compile` - do not compile dependencies\n * `--quiet` - do not output on compilation\n\n \"\"\"\n def run(args) do\n { opts, _, _ } = OptionParser.parse(args, switches: [quiet: :boolean])\n lock = Mix.Deps.Lock.read\n all = Enum.map loaded, &check_lock(&1, lock)\n\n prune_deps(all)\n { not_ok, compile } = partition_deps(all, [], [])\n\n cond do\n not_ok != [] ->\n show_not_ok(not_ok)\n compile == [] or opts[:no_compile] ->\n :ok\n true ->\n Mix.Tasks.Deps.Compile.compile(compile, opts)\n show_not_ok compile\n |> Enum.map(& &1.app)\n |> loaded_by_name\n |> Enum.filter(&(not ok?(&1)))\n end\n end\n\n defp partition_deps([dep|deps], not_ok, compile) do\n cond do\n ok?(dep) -> partition_deps(deps, not_ok, compile)\n compile?(dep) -> partition_deps(deps, not_ok, [dep|compile])\n true -> partition_deps(deps, [dep|not_ok], compile)\n end\n end\n\n defp partition_deps([], not_ok, compile) do\n { Enum.reverse(not_ok), Enum.reverse(compile) }\n end\n\n defp compile?(Mix.Dep[status: { :noappfile, _ }]), do: true\n defp compile?(Mix.Dep[status: :compile]), do: true\n defp compile?(_), do: false\n\n # If the build is per environment, we should be able to look\n # at all dependencies and remove the builds that no longer\n # has a dependnecy defined for them.\n #\n # Notice we require the build_path to be nil. If the build_path\n # is not nil, it means it was set by a parent application and\n # the parent application should be the one to do the pruning.\n defp prune_deps(all) do\n config = Mix.project\n\n if nil?(config[:build_path]) && config[:build_per_environment] do\n paths = Mix.Project.build_path(config)\n |> Path.join(\"lib\/*\/ebin\")\n |> Path.wildcard\n |> List.delete(not Mix.Project.umbrella? && Mix.Project.compile_path(config))\n\n to_prune = Enum.reduce(all, paths, &(&2 -- Mix.Deps.load_paths(&1)))\n\n Enum.map(to_prune, fn path ->\n Code.delete_path(path)\n File.rm_rf!(path |> Path.dirname)\n end)\n end\n end\n\n defp show_not_ok([]) do\n :ok\n end\n\n defp show_not_ok(deps) do\n shell = Mix.shell\n shell.error \"Unchecked dependencies for environment #{Mix.env}:\"\n\n Enum.each deps, fn(dep) ->\n shell.error \"* #{format_dep(dep)}\"\n shell.error \" #{format_status dep}\"\n end\n\n raise Mix.Error, message: \"Can't continue due to errors on dependencies\"\n end\nend\n","old_contents":"defmodule Mix.Tasks.Deps.Check do\n use Mix.Task\n\n import Mix.Deps, only: [loaded: 0, loaded_by_name: 1, format_dep: 1,\n format_status: 1, check_lock: 2, ok?: 1]\n\n @moduledoc \"\"\"\n Checks if all dependencies are valid and if not, abort.\n Prints the invalid dependencies' status before aborting.\n\n This task is not shown in `mix help` but it is part\n of the `mix` public API and can be depended on.\n\n ## Command line options\n\n * `--no-compile` - do not compile dependencies\n * `--quiet` - do not output on compilation\n\n \"\"\"\n def run(args) do\n { opts, _, _ } = OptionParser.parse(args, switches: [quiet: :boolean])\n lock = Mix.Deps.Lock.read\n all = Enum.map loaded, &check_lock(&1, lock)\n\n prune_deps(all)\n { not_ok, compile } = partition_deps(all, [], [])\n\n cond do\n not_ok != [] ->\n show_not_ok(not_ok)\n compile == [] or opts[:no_compile] ->\n :ok\n true ->\n Mix.Tasks.Deps.Compile.compile(compile, opts)\n show_not_ok compile\n |> Enum.map(& &1.app)\n |> loaded_by_name\n |> Enum.filter(&(not ok?(&1)))\n end\n end\n\n defp partition_deps([dep|deps], not_ok, compile) do\n cond do\n ok?(dep) -> partition_deps(deps, not_ok, compile)\n compile?(dep) -> partition_deps(deps, not_ok, [dep|compile])\n true -> partition_deps(deps, [dep|not_ok], compile)\n end\n end\n\n defp partition_deps([], not_ok, compile) do\n { not_ok, compile }\n end\n\n defp compile?(Mix.Dep[status: { :noappfile, _ }]), do: true\n defp compile?(Mix.Dep[status: :compile]), do: true\n defp compile?(_), do: false\n\n # If the build is per environment, we should be able to look\n # at all dependencies and remove the builds that no longer\n # has a dependnecy defined for them.\n #\n # Notice we require the build_path to be nil. If the build_path\n # is not nil, it means it was set by a parent application and\n # the parent application should be the one to do the pruning.\n defp prune_deps(all) do\n config = Mix.project\n\n if nil?(config[:build_path]) && config[:build_per_environment] do\n paths = Mix.Project.build_path(config)\n |> Path.join(\"lib\/*\/ebin\")\n |> Path.wildcard\n |> List.delete(not Mix.Project.umbrella? && Mix.Project.compile_path(config))\n\n to_prune = Enum.reduce(all, paths, &(&2 -- Mix.Deps.load_paths(&1)))\n\n Enum.map(to_prune, fn path ->\n Code.delete_path(path)\n File.rm_rf!(path |> Path.dirname)\n end)\n end\n end\n\n defp show_not_ok([]) do\n :ok\n end\n\n defp show_not_ok(deps) do\n shell = Mix.shell\n shell.error \"Unchecked dependencies for environment #{Mix.env}:\"\n\n Enum.each deps, fn(dep) ->\n shell.error \"* #{format_dep(dep)}\"\n shell.error \" #{format_status dep}\"\n end\n\n raise Mix.Error, message: \"Can't continue due to errors on dependencies\"\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"fb81ae4a005ec6db6301d663ffae8c31445388a8","subject":"Do not check for symlinks on umbrella apps, closes #2773","message":"Do not check for symlinks on umbrella apps, closes #2773\n","repos":"optikfluffel\/phoenix,nshafer\/phoenix,mschae\/phoenix,rafbgarcia\/phoenix,nshafer\/phoenix,mschae\/phoenix,Kosmas\/phoenix,mobileoverlord\/phoenix,dmarkow\/phoenix,0x00evil\/phoenix,mitchellhenke\/phoenix,0x00evil\/phoenix,jwarwick\/phoenix,phoenixframework\/phoenix,Kosmas\/phoenix,dmarkow\/phoenix,michalmuskala\/phoenix,evax\/phoenix,keathley\/phoenix,eksperimental\/phoenix,nshafer\/phoenix,pap\/phoenix,michalmuskala\/phoenix,Joe-noh\/phoenix,mitchellhenke\/phoenix,keathley\/phoenix,Gazler\/phoenix,phoenixframework\/phoenix,phoenixframework\/phoenix,eksperimental\/phoenix,mobileoverlord\/phoenix,0x00evil\/phoenix,optikfluffel\/phoenix,jwarwick\/phoenix,Joe-noh\/phoenix,rafbgarcia\/phoenix,optikfluffel\/phoenix,rafbgarcia\/phoenix,pap\/phoenix,evax\/phoenix,Gazler\/phoenix","old_file":"lib\/phoenix\/code_reloader\/server.ex","new_file":"lib\/phoenix\/code_reloader\/server.ex","new_contents":"defmodule Phoenix.CodeReloader.Server do\n @moduledoc false\n use GenServer\n\n require Logger\n alias Phoenix.CodeReloader.Proxy\n\n def start_link() do\n GenServer.start_link(__MODULE__, false, name: __MODULE__)\n end\n\n def check_symlinks do\n GenServer.call(__MODULE__, :check_symlinks, :infinity)\n end\n\n def reload!(endpoint) do\n GenServer.call(__MODULE__, {:reload!, endpoint}, :infinity)\n end\n\n ## Callbacks\n\n def init(false) do\n {:ok, false}\n end\n\n def handle_call(:check_symlinks, _from, checked?) do\n if not checked? and Code.ensure_loaded?(Mix.Project) and not Mix.Project.umbrella? do\n priv_path = \"#{Mix.Project.app_path}\/priv\"\n\n case :file.read_link(priv_path) do\n {:ok, _} ->\n :ok\n\n {:error, _} ->\n if can_symlink?() do\n File.rm_rf(priv_path)\n Mix.Project.build_structure\n else\n Logger.warn \"Phoenix is unable to create symlinks. Phoenix' code reloader will run \" <>\n \"considerably faster if symlinks are allowed.\" <> os_symlink(:os.type)\n end\n end\n end\n\n {:reply, :ok, true}\n end\n\n def handle_call({:reload!, endpoint}, from, state) do\n compilers = endpoint.config(:reloadable_compilers)\n backup = load_backup(endpoint)\n froms = all_waiting([from], endpoint)\n\n {res, out} =\n proxy_io(fn ->\n try do\n mix_compile(Code.ensure_loaded(Mix.Task), compilers)\n catch\n :exit, {:shutdown, 1} ->\n :error\n kind, reason ->\n IO.puts Exception.format(kind, reason, System.stacktrace)\n :error\n end\n end)\n\n reply =\n case res do\n :ok ->\n :ok\n :error ->\n write_backup(backup)\n {:error, out}\n end\n\n Enum.each(froms, &GenServer.reply(&1, reply))\n {:noreply, state}\n end\n\n def handle_info(_, state) do\n {:noreply, state}\n end\n\n defp os_symlink({:win32, _}),\n do: \" On Windows, the lack of symlinks may even cause empty assets to be served. \" <>\n \"Luckily, you can address this issue by starting your Windows terminal at least \" <>\n \"once with \\\"Run as Administrator\\\" and then running your Phoenix application.\"\n defp os_symlink(_),\n do: \"\"\n\n defp can_symlink?() do\n build_path = Mix.Project.build_path()\n symlink = Path.join(Path.dirname(build_path), \"__phoenix__\")\n\n case File.ln_s(build_path, symlink) do\n :ok ->\n File.rm_rf(symlink)\n true\n\n {:error, :eexist} ->\n File.rm_rf(symlink)\n true\n\n {:error, _} ->\n false\n end\n end\n\n defp load_backup(mod) do\n mod\n |> :code.which()\n |> read_backup()\n end\n defp read_backup(path) when is_list(path) do\n case File.read(path) do\n {:ok, binary} -> {:ok, path, binary}\n _ -> :error\n end\n end\n defp read_backup(_path), do: :error\n\n defp write_backup({:ok, path, file}), do: File.write!(path, file)\n defp write_backup(:error), do: :ok\n\n defp all_waiting(acc, endpoint) do\n receive do\n {:\"$gen_call\", from, {:reload!, ^endpoint}} -> all_waiting([from | acc], endpoint)\n after\n 0 -> acc\n end\n end\n\n defp mix_compile({:module, Mix.Task}, compilers) do\n if Mix.Project.umbrella? do\n Enum.each Mix.Dep.Umbrella.cached, fn dep ->\n Mix.Dep.in_dependency(dep, fn _ ->\n mix_compile_unless_stale_config(compilers)\n end)\n end\n else\n mix_compile_unless_stale_config(compilers)\n :ok\n end\n end\n defp mix_compile({:error, _reason}, _) do\n raise \"the Code Reloader is enabled but Mix is not available. If you want to \" <>\n \"use the Code Reloader in production or inside an escript, you must add \" <>\n \":mix to your applications list. Otherwise, you must disable code reloading \" <>\n \"in such environments\"\n end\n\n defp mix_compile_unless_stale_config(compilers) do\n manifests = Mix.Tasks.Compile.Elixir.manifests\n configs = Mix.Project.config_files\n\n case Mix.Utils.extract_stale(configs, manifests) do\n [] ->\n mix_compile(compilers)\n files ->\n raise \"\"\"\n could not compile application: #{Mix.Project.config[:app]}.\n\n You must restart your server after changing the following config or lib files:\n\n * #{Enum.map_join(files, \"\\n * \", &Path.relative_to_cwd\/1)}\n \"\"\"\n end\n end\n\n defp mix_compile(compilers) do\n all = Mix.Project.config[:compilers] || Mix.compilers\n\n compilers =\n for compiler <- compilers, compiler in all do\n Mix.Task.reenable(\"compile.#{compiler}\")\n compiler\n end\n\n # We call build_structure mostly for Windows so new\n # assets in priv are copied to the build directory.\n Mix.Project.build_structure\n res = Enum.map(compilers, &Mix.Task.run(\"compile.#{&1}\", []))\n\n if :ok in res && consolidate_protocols?() do\n Mix.Task.reenable(\"compile.protocols\")\n Mix.Task.run(\"compile.protocols\", [])\n end\n\n res\n end\n\n defp consolidate_protocols? do\n Mix.Project.config[:consolidate_protocols]\n end\n\n defp proxy_io(fun) do\n original_gl = Process.group_leader\n {:ok, proxy_gl} = Proxy.start()\n Process.group_leader(self(), proxy_gl)\n\n try do\n {fun.(), Proxy.stop(proxy_gl)}\n after\n Process.group_leader(self(), original_gl)\n Process.exit(proxy_gl, :kill)\n end\n end\nend\n","old_contents":"defmodule Phoenix.CodeReloader.Server do\n @moduledoc false\n use GenServer\n\n require Logger\n alias Phoenix.CodeReloader.Proxy\n\n def start_link() do\n GenServer.start_link(__MODULE__, false, name: __MODULE__)\n end\n\n def check_symlinks do\n GenServer.call(__MODULE__, :check_symlinks, :infinity)\n end\n\n def reload!(endpoint) do\n GenServer.call(__MODULE__, {:reload!, endpoint}, :infinity)\n end\n\n ## Callbacks\n\n def init(false) do\n {:ok, false}\n end\n\n def handle_call(:check_symlinks, _from, checked?) do\n if not checked? and Code.ensure_loaded?(Mix.Project) do\n priv_path = \"#{Mix.Project.app_path}\/priv\"\n\n case :file.read_link(priv_path) do\n {:ok, _} ->\n :ok\n\n {:error, _} ->\n if can_symlink?() do\n File.rm_rf(priv_path)\n Mix.Project.build_structure\n else\n Logger.warn \"Phoenix is unable to create symlinks. Phoenix' code reloader will run \" <>\n \"considerably faster if symlinks are allowed.\" <> os_symlink(:os.type)\n end\n end\n end\n\n {:reply, :ok, true}\n end\n\n def handle_call({:reload!, endpoint}, from, state) do\n compilers = endpoint.config(:reloadable_compilers)\n backup = load_backup(endpoint)\n froms = all_waiting([from], endpoint)\n\n {res, out} =\n proxy_io(fn ->\n try do\n mix_compile(Code.ensure_loaded(Mix.Task), compilers)\n catch\n :exit, {:shutdown, 1} ->\n :error\n kind, reason ->\n IO.puts Exception.format(kind, reason, System.stacktrace)\n :error\n end\n end)\n\n reply =\n case res do\n :ok ->\n :ok\n :error ->\n write_backup(backup)\n {:error, out}\n end\n\n Enum.each(froms, &GenServer.reply(&1, reply))\n {:noreply, state}\n end\n\n def handle_info(_, state) do\n {:noreply, state}\n end\n\n defp os_symlink({:win32, _}),\n do: \" On Windows, the lack of symlinks may even cause empty assets to be served. \" <>\n \"Luckily, you can address this issue by starting your Windows terminal at least \" <>\n \"once with \\\"Run as Administrator\\\" and then running your Phoenix application.\"\n defp os_symlink(_),\n do: \"\"\n\n defp can_symlink?() do\n build_path = Mix.Project.build_path()\n symlink = Path.join(Path.dirname(build_path), \"__phoenix__\")\n\n case File.ln_s(build_path, symlink) do\n :ok ->\n File.rm_rf(symlink)\n true\n\n {:error, :eexist} ->\n File.rm_rf(symlink)\n true\n\n {:error, _} ->\n false\n end\n end\n\n defp load_backup(mod) do\n mod\n |> :code.which()\n |> read_backup()\n end\n defp read_backup(path) when is_list(path) do\n case File.read(path) do\n {:ok, binary} -> {:ok, path, binary}\n _ -> :error\n end\n end\n defp read_backup(_path), do: :error\n\n defp write_backup({:ok, path, file}), do: File.write!(path, file)\n defp write_backup(:error), do: :ok\n\n defp all_waiting(acc, endpoint) do\n receive do\n {:\"$gen_call\", from, {:reload!, ^endpoint}} -> all_waiting([from | acc], endpoint)\n after\n 0 -> acc\n end\n end\n\n defp mix_compile({:module, Mix.Task}, compilers) do\n if Mix.Project.umbrella? do\n Enum.each Mix.Dep.Umbrella.cached, fn dep ->\n Mix.Dep.in_dependency(dep, fn _ ->\n mix_compile_unless_stale_config(compilers)\n end)\n end\n else\n mix_compile_unless_stale_config(compilers)\n :ok\n end\n end\n defp mix_compile({:error, _reason}, _) do\n raise \"the Code Reloader is enabled but Mix is not available. If you want to \" <>\n \"use the Code Reloader in production or inside an escript, you must add \" <>\n \":mix to your applications list. Otherwise, you must disable code reloading \" <>\n \"in such environments\"\n end\n\n defp mix_compile_unless_stale_config(compilers) do\n manifests = Mix.Tasks.Compile.Elixir.manifests\n configs = Mix.Project.config_files\n\n case Mix.Utils.extract_stale(configs, manifests) do\n [] ->\n mix_compile(compilers)\n files ->\n raise \"\"\"\n could not compile application: #{Mix.Project.config[:app]}.\n\n You must restart your server after changing the following config or lib files:\n\n * #{Enum.map_join(files, \"\\n * \", &Path.relative_to_cwd\/1)}\n \"\"\"\n end\n end\n\n defp mix_compile(compilers) do\n all = Mix.Project.config[:compilers] || Mix.compilers\n\n compilers =\n for compiler <- compilers, compiler in all do\n Mix.Task.reenable(\"compile.#{compiler}\")\n compiler\n end\n\n # We call build_structure mostly for Windows so new\n # assets in priv are copied to the build directory.\n Mix.Project.build_structure\n res = Enum.map(compilers, &Mix.Task.run(\"compile.#{&1}\", []))\n\n if :ok in res && consolidate_protocols?() do\n Mix.Task.reenable(\"compile.protocols\")\n Mix.Task.run(\"compile.protocols\", [])\n end\n\n res\n end\n\n defp consolidate_protocols? do\n Mix.Project.config[:consolidate_protocols]\n end\n\n defp proxy_io(fun) do\n original_gl = Process.group_leader\n {:ok, proxy_gl} = Proxy.start()\n Process.group_leader(self(), proxy_gl)\n\n try do\n {fun.(), Proxy.stop(proxy_gl)}\n after\n Process.group_leader(self(), original_gl)\n Process.exit(proxy_gl, :kill)\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"4822cb230c6f376952ab6eba348d45469f500ef5","subject":"Fix typo in comment (#10211)","message":"Fix typo in comment (#10211)\n\n","repos":"kimshrier\/elixir,joshprice\/elixir,kelvinst\/elixir,kelvinst\/elixir,ggcampinho\/elixir,pedrosnk\/elixir,elixir-lang\/elixir,pedrosnk\/elixir,ggcampinho\/elixir,kimshrier\/elixir,michalmuskala\/elixir","old_file":"lib\/elixir\/lib\/module\/locals_tracker.ex","new_file":"lib\/elixir\/lib\/module\/locals_tracker.ex","new_contents":"# This is an Elixir module responsible for tracking\n# calls in order to extract Elixir modules' behaviour\n# during compilation time.\n#\n# ## Implementation\n#\n# The implementation uses ETS to track all dependencies\n# resembling a graph. The keys and what they point to are:\n#\n# * `:reattach` points to `{name, arity}`\n# * `{:local, {name, arity}}` points to `{{name, arity}, line, macro_dispatch?}`\n# * `{:import, {name, arity}}` points to `Module`\n#\n# This is built on top of the internal module tables.\ndefmodule Module.LocalsTracker do\n @moduledoc false\n\n @defmacros [:defmacro, :defmacrop]\n\n @doc \"\"\"\n Adds and tracks defaults for a definition into the tracker.\n \"\"\"\n def add_defaults({_set, bag}, kind, {name, arity} = pair, defaults, meta) do\n for i <- :lists.seq(arity - defaults, arity - 1) do\n put_edge(bag, {:local, {name, i}}, {pair, get_line(meta), kind in @defmacros})\n end\n\n :ok\n end\n\n @doc \"\"\"\n Adds a local dispatch from-to the given target.\n \"\"\"\n def add_local({_set, bag}, from, to, meta, macro_dispatch?)\n when is_tuple(from) and is_tuple(to) and is_boolean(macro_dispatch?) do\n put_edge(bag, {:local, from}, {to, get_line(meta), macro_dispatch?})\n :ok\n end\n\n @doc \"\"\"\n Adds an import dispatch to the given target.\n \"\"\"\n def add_import({set, _bag}, function, module, imported)\n when is_tuple(function) and is_atom(module) do\n put_edge(set, {:import, imported}, module)\n :ok\n end\n\n @doc \"\"\"\n Yanks a local node. Returns its in and out vertices in a tuple.\n \"\"\"\n def yank({_set, bag}, local) do\n :lists.usort(take_out_neighbours(bag, {:local, local}))\n end\n\n @doc \"\"\"\n Reattach a previously yanked node.\n \"\"\"\n def reattach({_set, bag}, tuple, kind, function, out_neighbours, meta) do\n for out_neighbour <- out_neighbours do\n put_edge(bag, {:local, function}, out_neighbour)\n end\n\n # Make a call from the old function to the new one\n if function != tuple do\n put_edge(bag, {:local, function}, {tuple, get_line(meta), kind in @defmacros})\n end\n\n # Finally marked the new one as reattached\n put_edge(bag, :reattach, tuple)\n :ok\n end\n\n # Collecting all conflicting imports with the given functions\n @doc false\n def collect_imports_conflicts({set, _bag}, all_defined) do\n for {pair, _, meta, _} <- all_defined, n = out_neighbour(set, {:import, pair}) do\n {meta, {n, pair}}\n end\n end\n\n @doc \"\"\"\n Collect all unused definitions based on the private\n given, also accounting the expected number of default\n clauses a private function have.\n \"\"\"\n def collect_unused_locals({_set, bag}, all_defined, private) do\n reachable =\n Enum.reduce(all_defined, %{}, fn {pair, kind, _, _}, acc ->\n if kind in [:def, :defmacro] do\n reachable_from(bag, pair, acc)\n else\n acc\n end\n end)\n\n reattached = :lists.usort(out_neighbours(bag, :reattach))\n {unreachable(reachable, reattached, private), collect_warnings(reachable, private)}\n end\n\n @doc \"\"\"\n Collect undefined functions based on local calls and existing definitions.\n \"\"\"\n def collect_undefined_locals({set, bag}, all_defined) do\n undefined =\n for {pair, _, meta, _} <- all_defined,\n {local, line, macro_dispatch?} <- out_neighbours(bag, {:local, pair}),\n error = undefined_local_error(set, local, macro_dispatch?),\n do: {build_meta(line, meta), local, error}\n\n :lists.usort(undefined)\n end\n\n defp undefined_local_error(set, local, true) do\n case :ets.member(set, {:def, local}) do\n true -> false\n false -> :undefined_function\n end\n end\n\n defp undefined_local_error(set, local, false) do\n try do\n if :ets.lookup_element(set, {:def, local}, 2) in @defmacros do\n :incorrect_dispatch\n else\n false\n end\n catch\n _, _ -> :undefined_function\n end\n end\n\n defp unreachable(reachable, reattached, private) do\n for {tuple, kind, _, _} <- private,\n not reachable?(tuple, kind, reachable, reattached),\n do: tuple\n end\n\n defp reachable?(tuple, :defmacrop, reachable, reattached) do\n # All private macros are unreachable unless they have been\n # reattached and they are reachable.\n :lists.member(tuple, reattached) and Map.has_key?(reachable, tuple)\n end\n\n defp reachable?(tuple, :defp, reachable, _reattached) do\n Map.has_key?(reachable, tuple)\n end\n\n defp collect_warnings(reachable, private) do\n :lists.foldl(&collect_warnings(&1, &2, reachable), [], private)\n end\n\n defp collect_warnings({_, _, false, _}, acc, _reachable) do\n acc\n end\n\n defp collect_warnings({tuple, kind, meta, 0}, acc, reachable) do\n if Map.has_key?(reachable, tuple) do\n acc\n else\n [{meta, {:unused_def, tuple, kind}} | acc]\n end\n end\n\n defp collect_warnings({tuple, kind, meta, default}, acc, reachable) when default > 0 do\n {name, arity} = tuple\n min = arity - default\n max = arity\n\n case min_reachable_default(max, min, :none, name, reachable) do\n :none -> [{meta, {:unused_def, tuple, kind}} | acc]\n ^min -> acc\n ^max -> [{meta, {:unused_args, tuple}} | acc]\n diff -> [{meta, {:unused_args, tuple, diff}} | acc]\n end\n end\n\n defp min_reachable_default(max, min, last, name, reachable) when max >= min do\n case Map.has_key?(reachable, {name, max}) do\n true -> min_reachable_default(max - 1, min, max, name, reachable)\n false -> min_reachable_default(max - 1, min, last, name, reachable)\n end\n end\n\n defp min_reachable_default(_max, _min, last, _name, _reachable) do\n last\n end\n\n @doc \"\"\"\n Returns all local nodes reachable from `vertex`.\n\n By default, all public functions are reachable.\n A private function is only reachable if it has\n a public function that it invokes directly.\n \"\"\"\n def reachable_from({_, bag}, local) do\n bag\n |> reachable_from(local, %{})\n |> Map.keys()\n end\n\n defp reachable_from(bag, local, vertices) do\n vertices = Map.put(vertices, local, true)\n\n Enum.reduce(out_neighbours(bag, {:local, local}), vertices, fn {local, _line, _}, acc ->\n case acc do\n %{^local => true} -> acc\n _ -> reachable_from(bag, local, acc)\n end\n end)\n end\n\n defp get_line(meta), do: Keyword.get(meta, :line)\n\n defp build_meta(nil, _meta), do: []\n\n # We need to transform any file annotation in the function\n # definition into a keep annotation that is used by the\n # error handling system in order to respect line\/file.\n defp build_meta(line, meta) do\n case Keyword.get(meta, :file) do\n {file, _} -> [keep: {file, line}]\n _ -> [line: line]\n end\n end\n\n ## Lightweight digraph implementation\n\n defp put_edge(d, from, to) do\n :ets.insert(d, {from, to})\n end\n\n defp out_neighbour(d, from) do\n try do\n :ets.lookup_element(d, from, 2)\n catch\n :error, :badarg -> nil\n end\n end\n\n defp out_neighbours(d, from) do\n try do\n :ets.lookup_element(d, from, 2)\n catch\n :error, :badarg -> []\n end\n end\n\n defp take_out_neighbours(d, from) do\n Keyword.values(:ets.take(d, from))\n end\nend\n","old_contents":"# This is an Elixir module responsible for tracking\n# calls in order to extract Elixir modules' behaviour\n# during compilation time.\n#\n# ## Implementation\n#\n# The implementation uses ETS to track all dependencies\n# resembling a graph. The keys and what they point to are:\n#\n# * `:reattach` points to `{name, arity}`\n# * `{:local, {name, arity}}` points to `{{name, arity}, line, macro_dispatch?}`\n# * `{:import, {name, arity}}` points to `Module`\n#\n# This is built on top of the internal module tables.\ndefmodule Module.LocalsTracker do\n @moduledoc false\n\n @defmacros [:defmacro, :defmacrop]\n\n @doc \"\"\"\n Adds and tracks defaults for a definition into the tracker.\n \"\"\"\n def add_defaults({_set, bag}, kind, {name, arity} = pair, defaults, meta) do\n for i <- :lists.seq(arity - defaults, arity - 1) do\n put_edge(bag, {:local, {name, i}}, {pair, get_line(meta), kind in @defmacros})\n end\n\n :ok\n end\n\n @doc \"\"\"\n Adds a local dispatch from-to the given target.\n \"\"\"\n def add_local({_set, bag}, from, to, meta, macro_dispatch?)\n when is_tuple(from) and is_tuple(to) and is_boolean(macro_dispatch?) do\n put_edge(bag, {:local, from}, {to, get_line(meta), macro_dispatch?})\n :ok\n end\n\n @doc \"\"\"\n Adds an import dispatch to the given target.\n \"\"\"\n def add_import({set, _bag}, function, module, imported)\n when is_tuple(function) and is_atom(module) do\n put_edge(set, {:import, imported}, module)\n :ok\n end\n\n @doc \"\"\"\n Yanks a local node. Returns its in and out vertices in a tuple.\n \"\"\"\n def yank({_set, bag}, local) do\n :lists.usort(take_out_neighbours(bag, {:local, local}))\n end\n\n @doc \"\"\"\n Reattach a previously yanked node.\n \"\"\"\n def reattach({_set, bag}, tuple, kind, function, out_neighbours, meta) do\n for out_neighbour <- out_neighbours do\n put_edge(bag, {:local, function}, out_neighbour)\n end\n\n # Make a call from the old function to the new one\n if function != tuple do\n put_edge(bag, {:local, function}, {tuple, get_line(meta), kind in @defmacros})\n end\n\n # Finally marked the new one as reattached\n put_edge(bag, :reattach, tuple)\n :ok\n end\n\n # Collecting all conflicting imports with the given functions\n @doc false\n def collect_imports_conflicts({set, _bag}, all_defined) do\n for {pair, _, meta, _} <- all_defined, n = out_neighbour(set, {:import, pair}) do\n {meta, {n, pair}}\n end\n end\n\n @doc \"\"\"\n Collect all unused definitions based on the private\n given, also accounting the expected number of default\n clauses a private function have.\n \"\"\"\n def collect_unused_locals({_set, bag}, all_defined, private) do\n reachable =\n Enum.reduce(all_defined, %{}, fn {pair, kind, _, _}, acc ->\n if kind in [:def, :defmacro] do\n reachable_from(bag, pair, acc)\n else\n acc\n end\n end)\n\n reattached = :lists.usort(out_neighbours(bag, :reattach))\n {unreachable(reachable, reattached, private), collect_warnings(reachable, private)}\n end\n\n @doc \"\"\"\n Collect undefined functions based on local calls and existing definitions.\n \"\"\"\n def collect_undefined_locals({set, bag}, all_defined) do\n undefined =\n for {pair, _, meta, _} <- all_defined,\n {local, line, macro_dispatch?} <- out_neighbours(bag, {:local, pair}),\n error = undefined_local_error(set, local, macro_dispatch?),\n do: {build_meta(line, meta), local, error}\n\n :lists.usort(undefined)\n end\n\n defp undefined_local_error(set, local, true) do\n case :ets.member(set, {:def, local}) do\n true -> false\n false -> :undefined_function\n end\n end\n\n defp undefined_local_error(set, local, false) do\n try do\n if :ets.lookup_element(set, {:def, local}, 2) in @defmacros do\n :incorrect_dispatch\n else\n false\n end\n catch\n _, _ -> :undefined_function\n end\n end\n\n defp unreachable(reachable, reattached, private) do\n for {tuple, kind, _, _} <- private,\n not reachable?(tuple, kind, reachable, reattached),\n do: tuple\n end\n\n defp reachable?(tuple, :defmacrop, reachable, reattached) do\n # All private micros are unreachable unless they have been\n # reattached and they are reachable.\n :lists.member(tuple, reattached) and Map.has_key?(reachable, tuple)\n end\n\n defp reachable?(tuple, :defp, reachable, _reattached) do\n Map.has_key?(reachable, tuple)\n end\n\n defp collect_warnings(reachable, private) do\n :lists.foldl(&collect_warnings(&1, &2, reachable), [], private)\n end\n\n defp collect_warnings({_, _, false, _}, acc, _reachable) do\n acc\n end\n\n defp collect_warnings({tuple, kind, meta, 0}, acc, reachable) do\n if Map.has_key?(reachable, tuple) do\n acc\n else\n [{meta, {:unused_def, tuple, kind}} | acc]\n end\n end\n\n defp collect_warnings({tuple, kind, meta, default}, acc, reachable) when default > 0 do\n {name, arity} = tuple\n min = arity - default\n max = arity\n\n case min_reachable_default(max, min, :none, name, reachable) do\n :none -> [{meta, {:unused_def, tuple, kind}} | acc]\n ^min -> acc\n ^max -> [{meta, {:unused_args, tuple}} | acc]\n diff -> [{meta, {:unused_args, tuple, diff}} | acc]\n end\n end\n\n defp min_reachable_default(max, min, last, name, reachable) when max >= min do\n case Map.has_key?(reachable, {name, max}) do\n true -> min_reachable_default(max - 1, min, max, name, reachable)\n false -> min_reachable_default(max - 1, min, last, name, reachable)\n end\n end\n\n defp min_reachable_default(_max, _min, last, _name, _reachable) do\n last\n end\n\n @doc \"\"\"\n Returns all local nodes reachable from `vertex`.\n\n By default, all public functions are reachable.\n A private function is only reachable if it has\n a public function that it invokes directly.\n \"\"\"\n def reachable_from({_, bag}, local) do\n bag\n |> reachable_from(local, %{})\n |> Map.keys()\n end\n\n defp reachable_from(bag, local, vertices) do\n vertices = Map.put(vertices, local, true)\n\n Enum.reduce(out_neighbours(bag, {:local, local}), vertices, fn {local, _line, _}, acc ->\n case acc do\n %{^local => true} -> acc\n _ -> reachable_from(bag, local, acc)\n end\n end)\n end\n\n defp get_line(meta), do: Keyword.get(meta, :line)\n\n defp build_meta(nil, _meta), do: []\n\n # We need to transform any file annotation in the function\n # definition into a keep annotation that is used by the\n # error handling system in order to respect line\/file.\n defp build_meta(line, meta) do\n case Keyword.get(meta, :file) do\n {file, _} -> [keep: {file, line}]\n _ -> [line: line]\n end\n end\n\n ## Lightweight digraph implementation\n\n defp put_edge(d, from, to) do\n :ets.insert(d, {from, to})\n end\n\n defp out_neighbour(d, from) do\n try do\n :ets.lookup_element(d, from, 2)\n catch\n :error, :badarg -> nil\n end\n end\n\n defp out_neighbours(d, from) do\n try do\n :ets.lookup_element(d, from, 2)\n catch\n :error, :badarg -> []\n end\n end\n\n defp take_out_neighbours(d, from) do\n Keyword.values(:ets.take(d, from))\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"99e332d469510e8b3932152e96c95140084abfb3","subject":"Solve race condition in tests","message":"Solve race condition in tests","repos":"lexmag\/elixir,pedrosnk\/elixir,ggcampinho\/elixir,beedub\/elixir,gfvcastro\/elixir,kelvinst\/elixir,elixir-lang\/elixir,antipax\/elixir,ggcampinho\/elixir,gfvcastro\/elixir,kelvinst\/elixir,kimshrier\/elixir,joshprice\/elixir,beedub\/elixir,kimshrier\/elixir,antipax\/elixir,pedrosnk\/elixir,michalmuskala\/elixir,lexmag\/elixir","old_file":"lib\/elixir\/test\/elixir\/process_test.exs","new_file":"lib\/elixir\/test\/elixir\/process_test.exs","new_contents":"Code.require_file \"test_helper.exs\", __DIR__\n\ndefmodule ProcessTest do\n use ExUnit.Case, async: true\n\n doctest Process\n\n test \"dictionary\" do\n assert Process.put(:foo, :bar) == nil\n assert Process.put(:foo, :baz) == :bar\n\n assert Process.get_keys() == [:foo]\n assert Process.get_keys(:bar) == []\n assert Process.get_keys(:baz) == [:foo]\n\n assert Process.get(:foo) == :baz\n assert Process.delete(:foo) == :baz\n assert Process.get(:foo) == nil\n end\n\n test \"group_leader\/2 and group_leader\/0\" do\n another = spawn_link(fn -> Process.sleep(1000) end)\n assert Process.group_leader(self(), another)\n assert Process.group_leader == another\n end\n\n test \"monitoring functions are inlined by the compiler\" do\n assert expand(quote(do: Process.monitor(pid())), __ENV__) ==\n quote(do: :erlang.monitor(:process, pid()))\n end\n\n test \"sleep\/1\" do\n assert Process.sleep(0) == :ok\n end\n\n test \"info\/2\" do\n pid = spawn fn -> Process.sleep(1000) end\n assert Process.info(pid, :priority) == {:priority, :normal}\n assert Process.info(pid, [:priority]) == [priority: :normal]\n\n Process.exit(pid, :kill)\n assert Process.info(pid, :backtrace) == nil\n assert Process.info(pid, [:backtrace, :status]) == nil\n end\n\n test \"info\/2 with registered name\" do\n pid = spawn fn -> nil end\n Process.exit(pid, :kill)\n assert Process.info(pid, :registered_name) ==\n nil\n assert Process.info(pid, [:registered_name]) ==\n nil\n\n assert Process.info(self(), :registered_name) ==\n {:registered_name, []}\n assert Process.info(self(), [:registered_name]) ==\n [registered_name: []]\n\n Process.register(self(), __MODULE__)\n assert Process.info(self(), :registered_name) ==\n {:registered_name, __MODULE__}\n assert Process.info(self(), [:registered_name]) ==\n [registered_name: __MODULE__]\n end\n\n test \"send_after\/3 sends messages once expired\" do\n Process.send_after(self(), :hello, 10)\n assert_receive :hello\n end\n\n test \"send_after\/4 with absolute time sends message once expired\" do\n time = System.monotonic_time(:millisecond) + 10\n Process.send_after(self(), :hello, time, abs: true)\n assert_receive :hello\n end\n\n test \"send_after\/3 returns a timer reference that can be read or cancelled\" do\n timer = Process.send_after(self(), :hello, 100_000)\n refute_received :hello\n assert is_integer(Process.read_timer(timer))\n assert is_integer(Process.cancel_timer(timer))\n\n timer = Process.send_after(self(), :hello, 0)\n assert_receive :hello\n assert Process.read_timer(timer) == false\n assert Process.cancel_timer(timer) == false\n\n timer = Process.send_after(self(), :hello, 100_000)\n assert Process.cancel_timer(timer, async: true)\n assert_receive {:cancel_timer, ^timer, result}\n assert is_integer(result)\n end\n\n test \"exit(pid, :normal) does not cause the target process to exit\" do\n pid = spawn_link fn ->\n receive do\n :done -> nil\n end\n end\n\n trap = Process.flag(:trap_exit, true)\n true = Process.exit(pid, :normal)\n refute_receive {:EXIT, ^pid, :normal}\n assert Process.alive?(pid)\n\n # now exit the process for real so it doesn't hang around\n true = Process.exit(pid, :abnormal)\n assert_receive {:EXIT, ^pid, :abnormal}\n refute Process.alive?(pid)\n\n Process.flag(:trap_exit, trap)\n end\n\n test \"exit(pid, :normal) makes the process receive a message if it traps exits\" do\n parent = self()\n pid = spawn_link fn ->\n Process.flag(:trap_exit, true)\n receive do\n {:EXIT, ^parent, :normal} -> send(parent, {:ok, self()})\n end\n end\n\n refute_receive _\n Process.exit(pid, :normal)\n assert_receive {:ok, ^pid}\n refute Process.alive?(pid)\n end\n\n test \"exit(self(), :normal) causes the calling process to exit\" do\n trap = Process.flag(:trap_exit, true)\n\n pid = spawn_link fn -> Process.exit(self(), :normal) end\n\n assert_receive {:EXIT, ^pid, :normal}\n refute Process.alive?(pid)\n\n Process.flag(:trap_exit, trap)\n end\n\n defp expand(expr, env) do\n {expr, _env} = :elixir_expand.expand(expr, env)\n expr\n end\nend\n","old_contents":"Code.require_file \"test_helper.exs\", __DIR__\n\ndefmodule ProcessTest do\n use ExUnit.Case, async: true\n\n doctest Process\n\n test \"dictionary\" do\n assert Process.put(:foo, :bar) == nil\n assert Process.put(:foo, :baz) == :bar\n\n assert Process.get_keys() == [:foo]\n assert Process.get_keys(:bar) == []\n assert Process.get_keys(:baz) == [:foo]\n\n assert Process.get(:foo) == :baz\n assert Process.delete(:foo) == :baz\n assert Process.get(:foo) == nil\n end\n\n test \"group_leader\/2 and group_leader\/0\" do\n another = spawn_link(fn -> Process.sleep(1000) end)\n assert Process.group_leader(self(), another)\n assert Process.group_leader == another\n end\n\n test \"monitoring functions are inlined by the compiler\" do\n assert expand(quote(do: Process.monitor(pid())), __ENV__) ==\n quote(do: :erlang.monitor(:process, pid()))\n end\n\n test \"sleep\/1\" do\n assert Process.sleep(0) == :ok\n end\n\n test \"info\/2\" do\n pid = spawn fn -> Process.sleep(1000) end\n assert Process.info(pid, :priority) == {:priority, :normal}\n assert Process.info(pid, [:priority]) == [priority: :normal]\n\n Process.exit(pid, :kill)\n assert Process.info(pid, :backtrace) == nil\n assert Process.info(pid, [:backtrace, :status]) == nil\n end\n\n test \"info\/2 with registered name\" do\n pid = spawn fn -> nil end\n Process.exit(pid, :kill)\n assert Process.info(pid, :registered_name) ==\n nil\n assert Process.info(pid, [:registered_name]) ==\n nil\n\n assert Process.info(self(), :registered_name) ==\n {:registered_name, []}\n assert Process.info(self(), [:registered_name]) ==\n [registered_name: []]\n\n Process.register(self(), __MODULE__)\n assert Process.info(self(), :registered_name) ==\n {:registered_name, __MODULE__}\n assert Process.info(self(), [:registered_name]) ==\n [registered_name: __MODULE__]\n end\n\n test \"send_after\/3 sends messages once expired\" do\n Process.send_after(self(), :hello, 10)\n assert_receive :hello\n end\n\n test \"send_after\/4 with absolute time sends message once expired\" do\n time = System.monotonic_time(:millisecond) + 10\n Process.send_after(self(), :hello, time, abs: true)\n assert_receive :hello\n end\n\n test \"send_after\/3 returns a timer reference that can be read or cancelled\" do\n timer = Process.send_after(self(), :hello, 100_000)\n refute_received :hello\n assert is_integer(Process.read_timer(timer))\n assert is_integer(Process.cancel_timer(timer))\n\n timer = Process.send_after(self(), :hello, 0)\n assert_receive :hello\n assert Process.read_timer(timer) == false\n assert Process.cancel_timer(timer) == false\n\n timer = Process.send_after(self(), :hello, 100_000)\n assert Process.cancel_timer(timer, async: true)\n assert_receive {:cancel_timer, ^timer, result}\n assert is_integer(result)\n assert Process.cancel_timer(timer, info: false) == :ok\n end\n\n test \"exit(pid, :normal) does not cause the target process to exit\" do\n pid = spawn_link fn ->\n receive do\n :done -> nil\n end\n end\n\n trap = Process.flag(:trap_exit, true)\n true = Process.exit(pid, :normal)\n refute_receive {:EXIT, ^pid, :normal}\n assert Process.alive?(pid)\n\n # now exit the process for real so it doesn't hang around\n true = Process.exit(pid, :abnormal)\n assert_receive {:EXIT, ^pid, :abnormal}\n refute Process.alive?(pid)\n\n Process.flag(:trap_exit, trap)\n end\n\n test \"exit(pid, :normal) makes the process receive a message if it traps exits\" do\n parent = self()\n pid = spawn_link fn ->\n Process.flag(:trap_exit, true)\n receive do\n {:EXIT, ^parent, :normal} -> send(parent, {:ok, self()})\n end\n end\n\n refute_receive _\n Process.exit(pid, :normal)\n assert_receive {:ok, ^pid}\n refute Process.alive?(pid)\n end\n\n test \"exit(self(), :normal) causes the calling process to exit\" do\n trap = Process.flag(:trap_exit, true)\n\n pid = spawn_link fn -> Process.exit(self(), :normal) end\n\n assert_receive {:EXIT, ^pid, :normal}\n refute Process.alive?(pid)\n\n Process.flag(:trap_exit, trap)\n end\n\n defp expand(expr, env) do\n {expr, _env} = :elixir_expand.expand(expr, env)\n expr\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"495bde6da748210eebf60c807d3183fc6c8b153a","subject":"Load applications to have access to versions","message":"Load applications to have access to versions\n\nSee: https:\/\/elixirforum.com\/t\/retrieve-the-used-version-of-a-development-dependency-at-runtime\/12397\n","repos":"PragTob\/benchee_html,PragTob\/benchee_html","old_file":"lib\/benchee\/formatters\/html.ex","new_file":"lib\/benchee\/formatters\/html.ex","new_contents":"defmodule Benchee.Formatters.HTML do\n use Benchee.Formatter\n\n require EEx\n alias Benchee.{Suite, Statistics, Configuration}\n alias Benchee.Conversion\n alias Benchee.Conversion.{Duration, Count, DeviationPercent}\n alias Benchee.Utility.FileCreation\n alias Benchee.Formatters.JSON\n\n # Major pages\n EEx.function_from_file :defp, :comparison,\n \"priv\/templates\/comparison.html.eex\",\n [:input_name, :suite, :units, :suite_json, :inline_assets]\n EEx.function_from_file :defp, :job_detail,\n \"priv\/templates\/job_detail.html.eex\",\n [:input_name, :job_name, :job_statistics, :system,\n :units, :job_json, :inline_assets]\n EEx.function_from_file :defp, :index,\n \"priv\/templates\/index.html.eex\",\n [:names_to_paths, :system, :inline_assets]\n\n # Partials\n EEx.function_from_file :defp, :head,\n \"priv\/templates\/partials\/head.html.eex\",\n [:inline_assets]\n EEx.function_from_file :defp, :header,\n \"priv\/templates\/partials\/header.html.eex\",\n [:input_name]\n EEx.function_from_file :defp, :js_includes,\n \"priv\/templates\/partials\/js_includes.html.eex\",\n [:inline_assets]\n EEx.function_from_file :defp, :version_note,\n \"priv\/templates\/partials\/version_note.html.eex\",\n []\n EEx.function_from_file :defp, :input_label,\n \"priv\/templates\/partials\/input_label.html.eex\",\n [:input_name]\n EEx.function_from_file :defp, :data_table,\n \"priv\/templates\/partials\/data_table.html.eex\",\n [:statistics, :units, :options]\n EEx.function_from_file :defp, :system_info,\n \"priv\/templates\/partials\/system_info.html.eex\",\n [:system, :options]\n EEx.function_from_file :defp, :footer,\n \"priv\/templates\/partials\/footer.html.eex\",\n [:dependencies]\n\n # Small wrappers to have default arguments\n defp render_data_table(statistics, units, options \\\\ []) do\n data_table statistics, units, options\n end\n\n defp render_system_info(system, options \\\\ [visible: false]) do\n system_info(system, options)\n end\n\n defp render_footer do\n footer(%{\n benchee: Application.spec(:benchee, :vsn),\n benchee_html: Application.spec(:benchee_html, :vsn)\n })\n end\n\n @moduledoc \"\"\"\n Functionality for converting Benchee benchmarking results to an HTML page\n with plotly.js generated graphs and friends.\n\n ## Examples\n\n list = Enum.to_list(1..10_000)\n map_fun = fn(i) -> [i, i * i] end\n\n Benchee.run(%{\n \"flat_map\" => fn -> Enum.flat_map(list, map_fun) end,\n \"map.flatten\" => fn -> list |> Enum.map(map_fun) |> List.flatten end\n },\n formatters: [\n &Benchee.Formatters.HTML.output\/1,\n &Benchee.Formatters.Console.output\/1\n ],\n formatter_options: [html: [file: \"samples_output\/flat_map.html\"]],\n )\n\n \"\"\"\n\n @doc \"\"\"\n Transforms the statistical results from benchmarking to html to be written\n somewhere, such as a file through `IO.write\/2`.\n\n Returns a map from file name\/path to file content along with formatter options.\n \"\"\"\n @spec format(Suite.t) :: {%{Suite.key => String.t}, map}\n def format(suite) do\n suite\n |> default_configuration\n |> do_format\n end\n\n @default_filename \"benchmarks\/output\/results.html\"\n @default_auto_open true\n @default_inline_assets false\n defp default_configuration(suite) do\n opts = suite.configuration.formatter_options\n |> Map.get(:html, %{})\n |> Map.put_new(:file, @default_filename)\n |> Map.put_new(:auto_open, @default_auto_open)\n |> Map.put_new(:inline_assets, @default_inline_assets)\n updated_configuration = %Configuration{suite.configuration | formatter_options: %{html: opts}}\n load_specs_for_versions()\n %Suite{suite | configuration: updated_configuration}\n end\n\n defp load_specs_for_versions do\n _ = Application.load :benchee\n _ = Application.load :benchee_html\n end\n\n defp do_format(%Suite{scenarios: scenarios, system: system,\n configuration: %{\n formatter_options: %{html: options = %{file: filename, inline_assets: inline_assets}},\n unit_scaling: unit_scaling\n }}) do\n data = scenarios\n |> Enum.group_by(fn(scenario) -> scenario.input_name end)\n |> Enum.map(fn(tagged_scenarios) ->\n reports_for_input(tagged_scenarios, system, filename, unit_scaling, inline_assets)\n end)\n |> add_index(filename, system, inline_assets)\n |> List.flatten\n |> Map.new\n\n {data, options}\n end\n\n @doc \"\"\"\n Uses output of `Benchee.Formatters.HTML.format\/1` to transform the statistics\n output to HTML with JS, but also already writes it to files defined in the\n initial configuration under `formatter_options: [html: [file:\n \"benchmark_out\/my.html\"]]`.\n\n Generates the following files:\n\n * index file (exactly like `file` is named)\n * a comparison of all the benchmarked jobs (one per benchmarked input)\n * for each job a detail page with more detailed run time graphs for that\n particular job (one per benchmark input)\n \"\"\"\n @spec write({%{Suite.key => String.t}, map}) :: :ok\n def write({data, %{file: filename, auto_open: auto_open?, inline_assets: inline_assets?}}) do\n prepare_folder_structure(filename, inline_assets?)\n\n FileCreation.each(data, filename)\n\n if auto_open?, do: open_report(filename)\n\n :ok\n end\n\n defp prepare_folder_structure(filename, inline_assets?) do\n base_directory = create_base_directory(filename)\n\n unless inline_assets?, do: copy_asset_files(base_directory)\n\n base_directory\n end\n\n defp create_base_directory(filename) do\n base_directory = Path.dirname filename\n File.mkdir_p! base_directory\n base_directory\n end\n\n @asset_directory \"assets\"\n defp copy_asset_files(base_directory) do\n asset_target_directory = Path.join(base_directory, @asset_directory)\n asset_source_directory = Application.app_dir(:benchee_html, \"priv\/assets\/\")\n File.cp_r! asset_source_directory, asset_target_directory\n end\n\n defp reports_for_input({input_name, scenarios}, system, filename, unit_scaling, inline_assets) do\n units = Conversion.units(scenarios, unit_scaling)\n job_reports = job_reports(input_name, scenarios, system, units, inline_assets)\n comparison = comparison_report(input_name, scenarios, system, filename, units, inline_assets)\n [comparison | job_reports]\n end\n\n defp job_reports(input_name, scenarios, system, units, inline_assets) do\n # extract some of me to benchee_json pretty please?\n Enum.map(scenarios, fn(scenario) ->\n job_json = JSON.encode!(%{\n statistics: scenario.run_time_statistics,\n run_times: scenario.run_times\n })\n {\n [input_name, scenario.name],\n job_detail(input_name, scenario.name, scenario.run_time_statistics, system, units, job_json, inline_assets)\n }\n end)\n end\n\n defp comparison_report(input_name, scenarios, system, filename, units, inline_assets) do\n input_json = JSON.format_scenarios_for_input(scenarios)\n\n sorted_statistics = scenarios\n |> Statistics.sort()\n |> Enum.map(fn(scenario) -> {scenario.name, %{run_time_statistics: scenario.run_time_statistics}} end)\n |> Map.new\n\n input_run_times = scenarios\n |> Enum.map(fn(scenario) -> {scenario.name, scenario.run_times} end)\n |> Map.new\n input_suite = %{\n statistics: sorted_statistics,\n run_times: input_run_times,\n system: system,\n job_count: length(scenarios),\n filename: filename\n }\n\n {[input_name, \"comparison\"], comparison(input_name, input_suite, units, input_json, inline_assets)}\n end\n\n defp add_index(grouped_main_contents, filename, system, inline_assets) do\n index_structure = inputs_to_paths(grouped_main_contents, filename)\n index_entry = {[], index(index_structure, system, inline_assets)}\n [index_entry | grouped_main_contents]\n end\n\n defp inputs_to_paths(grouped_main_contents, filename) do\n grouped_main_contents\n |> Enum.map(fn(reports) -> input_to_paths(reports, filename) end)\n |> Map.new\n end\n\n defp input_to_paths(input_reports, filename) do\n [{[input_name | _], _} | _] = input_reports\n\n paths = Enum.map input_reports, fn({tags, _content}) ->\n relative_file_path(filename, tags)\n end\n {input_name, paths}\n end\n\n defp relative_file_path(filename, tags) do\n filename\n |> Path.basename\n |> FileCreation.interleave(tags)\n end\n\n defp format_duration(duration, unit) do\n Duration.format({Duration.scale(duration, unit), unit})\n end\n\n defp format_count(count, unit) do\n Count.format({Count.scale(count, unit), unit})\n end\n\n defp format_percent(deviation_percent) do\n DeviationPercent.format deviation_percent\n end\n\n @no_input Benchee.Benchmark.no_input()\n defp inputs_supplied?(@no_input), do: false\n defp inputs_supplied?(_), do: true\n\n defp input_headline(input_name) do\n if inputs_supplied?(input_name) do\n \" (#{input_name})\"\n else\n \"\"\n end\n end\n\n @job_count_class \"job-count-\"\n # there seems to be no way to set a maximum bar width other than through chart\n # allowed width... or I can't find it.\n defp max_width_class(job_count) when job_count < 7 do\n \"#{@job_count_class}#{job_count}\"\n end\n defp max_width_class(_job_count), do: \"\"\n\n defp open_report(filename) do\n browser = get_browser()\n {_, exit_code} = System.cmd(browser, [filename])\n unless exit_code > 0, do: IO.puts \"Opened report using #{browser}\"\n end\n\n defp get_browser do\n case :os.type() do\n {:unix, :darwin} -> \"open\"\n {:unix, _} -> \"xdg-open\"\n {:win32, _} -> \"explorer\"\n end\n end\nend\n","old_contents":"defmodule Benchee.Formatters.HTML do\n use Benchee.Formatter\n\n require EEx\n alias Benchee.{Suite, Statistics, Configuration}\n alias Benchee.Conversion\n alias Benchee.Conversion.{Duration, Count, DeviationPercent}\n alias Benchee.Utility.FileCreation\n alias Benchee.Formatters.JSON\n\n # Major pages\n EEx.function_from_file :defp, :comparison,\n \"priv\/templates\/comparison.html.eex\",\n [:input_name, :suite, :units, :suite_json, :inline_assets]\n EEx.function_from_file :defp, :job_detail,\n \"priv\/templates\/job_detail.html.eex\",\n [:input_name, :job_name, :job_statistics, :system,\n :units, :job_json, :inline_assets]\n EEx.function_from_file :defp, :index,\n \"priv\/templates\/index.html.eex\",\n [:names_to_paths, :system, :inline_assets]\n\n # Partials\n EEx.function_from_file :defp, :head,\n \"priv\/templates\/partials\/head.html.eex\",\n [:inline_assets]\n EEx.function_from_file :defp, :header,\n \"priv\/templates\/partials\/header.html.eex\",\n [:input_name]\n EEx.function_from_file :defp, :js_includes,\n \"priv\/templates\/partials\/js_includes.html.eex\",\n [:inline_assets]\n EEx.function_from_file :defp, :version_note,\n \"priv\/templates\/partials\/version_note.html.eex\",\n []\n EEx.function_from_file :defp, :input_label,\n \"priv\/templates\/partials\/input_label.html.eex\",\n [:input_name]\n EEx.function_from_file :defp, :data_table,\n \"priv\/templates\/partials\/data_table.html.eex\",\n [:statistics, :units, :options]\n EEx.function_from_file :defp, :system_info,\n \"priv\/templates\/partials\/system_info.html.eex\",\n [:system, :options]\n EEx.function_from_file :defp, :footer,\n \"priv\/templates\/partials\/footer.html.eex\",\n [:dependencies]\n\n # Small wrappers to have default arguments\n defp render_data_table(statistics, units, options \\\\ []) do\n data_table statistics, units, options\n end\n\n defp render_system_info(system, options \\\\ [visible: false]) do\n system_info(system, options)\n end\n\n defp render_footer do\n footer(%{\n benchee: Application.spec(:benchee, :vsn),\n benchee_html: Application.spec(:benchee_html, :vsn)\n })\n end\n\n @moduledoc \"\"\"\n Functionality for converting Benchee benchmarking results to an HTML page\n with plotly.js generated graphs and friends.\n\n ## Examples\n\n list = Enum.to_list(1..10_000)\n map_fun = fn(i) -> [i, i * i] end\n\n Benchee.run(%{\n \"flat_map\" => fn -> Enum.flat_map(list, map_fun) end,\n \"map.flatten\" => fn -> list |> Enum.map(map_fun) |> List.flatten end\n },\n formatters: [\n &Benchee.Formatters.HTML.output\/1,\n &Benchee.Formatters.Console.output\/1\n ],\n formatter_options: [html: [file: \"samples_output\/flat_map.html\"]],\n )\n\n \"\"\"\n\n @doc \"\"\"\n Transforms the statistical results from benchmarking to html to be written\n somewhere, such as a file through `IO.write\/2`.\n\n Returns a map from file name\/path to file content along with formatter options.\n \"\"\"\n @spec format(Suite.t) :: {%{Suite.key => String.t}, map}\n def format(suite) do\n suite\n |> default_configuration\n |> do_format\n end\n\n @default_filename \"benchmarks\/output\/results.html\"\n @default_auto_open true\n @default_inline_assets false\n defp default_configuration(suite) do\n opts = suite.configuration.formatter_options\n |> Map.get(:html, %{})\n |> Map.put_new(:file, @default_filename)\n |> Map.put_new(:auto_open, @default_auto_open)\n |> Map.put_new(:inline_assets, @default_inline_assets)\n updated_configuration = %Configuration{suite.configuration | formatter_options: %{html: opts}}\n %Suite{suite | configuration: updated_configuration}\n end\n\n defp do_format(%Suite{scenarios: scenarios, system: system,\n configuration: %{\n formatter_options: %{html: options = %{file: filename, inline_assets: inline_assets}},\n unit_scaling: unit_scaling\n }}) do\n data = scenarios\n |> Enum.group_by(fn(scenario) -> scenario.input_name end)\n |> Enum.map(fn(tagged_scenarios) ->\n reports_for_input(tagged_scenarios, system, filename, unit_scaling, inline_assets)\n end)\n |> add_index(filename, system, inline_assets)\n |> List.flatten\n |> Map.new\n\n {data, options}\n end\n\n @doc \"\"\"\n Uses output of `Benchee.Formatters.HTML.format\/1` to transform the statistics\n output to HTML with JS, but also already writes it to files defined in the\n initial configuration under `formatter_options: [html: [file:\n \"benchmark_out\/my.html\"]]`.\n\n Generates the following files:\n\n * index file (exactly like `file` is named)\n * a comparison of all the benchmarked jobs (one per benchmarked input)\n * for each job a detail page with more detailed run time graphs for that\n particular job (one per benchmark input)\n \"\"\"\n @spec write({%{Suite.key => String.t}, map}) :: :ok\n def write({data, %{file: filename, auto_open: auto_open?, inline_assets: inline_assets?}}) do\n prepare_folder_structure(filename, inline_assets?)\n\n FileCreation.each(data, filename)\n\n if auto_open?, do: open_report(filename)\n\n :ok\n end\n\n defp prepare_folder_structure(filename, inline_assets?) do\n base_directory = create_base_directory(filename)\n\n unless inline_assets?, do: copy_asset_files(base_directory)\n\n base_directory\n end\n\n defp create_base_directory(filename) do\n base_directory = Path.dirname filename\n File.mkdir_p! base_directory\n base_directory\n end\n\n @asset_directory \"assets\"\n defp copy_asset_files(base_directory) do\n asset_target_directory = Path.join(base_directory, @asset_directory)\n asset_source_directory = Application.app_dir(:benchee_html, \"priv\/assets\/\")\n File.cp_r! asset_source_directory, asset_target_directory\n end\n\n defp reports_for_input({input_name, scenarios}, system, filename, unit_scaling, inline_assets) do\n units = Conversion.units(scenarios, unit_scaling)\n job_reports = job_reports(input_name, scenarios, system, units, inline_assets)\n comparison = comparison_report(input_name, scenarios, system, filename, units, inline_assets)\n [comparison | job_reports]\n end\n\n defp job_reports(input_name, scenarios, system, units, inline_assets) do\n # extract some of me to benchee_json pretty please?\n Enum.map(scenarios, fn(scenario) ->\n job_json = JSON.encode!(%{\n statistics: scenario.run_time_statistics,\n run_times: scenario.run_times\n })\n {\n [input_name, scenario.name],\n job_detail(input_name, scenario.name, scenario.run_time_statistics, system, units, job_json, inline_assets)\n }\n end)\n end\n\n defp comparison_report(input_name, scenarios, system, filename, units, inline_assets) do\n input_json = JSON.format_scenarios_for_input(scenarios)\n\n sorted_statistics = scenarios\n |> Statistics.sort()\n |> Enum.map(fn(scenario) -> {scenario.name, %{run_time_statistics: scenario.run_time_statistics}} end)\n |> Map.new\n\n input_run_times = scenarios\n |> Enum.map(fn(scenario) -> {scenario.name, scenario.run_times} end)\n |> Map.new\n input_suite = %{\n statistics: sorted_statistics,\n run_times: input_run_times,\n system: system,\n job_count: length(scenarios),\n filename: filename\n }\n\n {[input_name, \"comparison\"], comparison(input_name, input_suite, units, input_json, inline_assets)}\n end\n\n defp add_index(grouped_main_contents, filename, system, inline_assets) do\n index_structure = inputs_to_paths(grouped_main_contents, filename)\n index_entry = {[], index(index_structure, system, inline_assets)}\n [index_entry | grouped_main_contents]\n end\n\n defp inputs_to_paths(grouped_main_contents, filename) do\n grouped_main_contents\n |> Enum.map(fn(reports) -> input_to_paths(reports, filename) end)\n |> Map.new\n end\n\n defp input_to_paths(input_reports, filename) do\n [{[input_name | _], _} | _] = input_reports\n\n paths = Enum.map input_reports, fn({tags, _content}) ->\n relative_file_path(filename, tags)\n end\n {input_name, paths}\n end\n\n defp relative_file_path(filename, tags) do\n filename\n |> Path.basename\n |> FileCreation.interleave(tags)\n end\n\n defp format_duration(duration, unit) do\n Duration.format({Duration.scale(duration, unit), unit})\n end\n\n defp format_count(count, unit) do\n Count.format({Count.scale(count, unit), unit})\n end\n\n defp format_percent(deviation_percent) do\n DeviationPercent.format deviation_percent\n end\n\n @no_input Benchee.Benchmark.no_input()\n defp inputs_supplied?(@no_input), do: false\n defp inputs_supplied?(_), do: true\n\n defp input_headline(input_name) do\n if inputs_supplied?(input_name) do\n \" (#{input_name})\"\n else\n \"\"\n end\n end\n\n @job_count_class \"job-count-\"\n # there seems to be no way to set a maximum bar width other than through chart\n # allowed width... or I can't find it.\n defp max_width_class(job_count) when job_count < 7 do\n \"#{@job_count_class}#{job_count}\"\n end\n defp max_width_class(_job_count), do: \"\"\n\n defp open_report(filename) do\n browser = get_browser()\n {_, exit_code} = System.cmd(browser, [filename])\n unless exit_code > 0, do: IO.puts \"Opened report using #{browser}\"\n end\n\n defp get_browser do\n case :os.type() do\n {:unix, :darwin} -> \"open\"\n {:unix, _} -> \"xdg-open\"\n {:win32, _} -> \"explorer\"\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"fb1d2021e3cf80b19a0c5e92c06333b1758229bb","subject":"Add artifact url to nerves.exs","message":"Add artifact url to nerves.exs\n","repos":"uldza\/nerves_system_zynq","old_file":"nerves.exs","new_file":"nerves.exs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"apache-2.0","lang":"Elixir"} {"commit":"d8d0b89c0e759556882abce387a25752afcf8f5b","subject":"removing debug stuff","message":"removing debug stuff\n","repos":"GBH\/loaded.bike,GBH\/loaded.bike","old_file":"lib\/loaded_bike\/models\/user.ex","new_file":"lib\/loaded_bike\/models\/user.ex","new_contents":"defmodule LoadedBike.User do\n use LoadedBike.Web, :model\n use Arc.Ecto.Schema\n\n schema \"users\" do\n field :email, :string\n field :name, :string\n field :bio, :string\n field :twitter, :string\n field :instagram, :string\n field :password_hash, :string\n field :password, :string, virtual: true\n field :password_reset_token, :string\n field :verification_token, :string\n\n field :avatar, LoadedBike.Web.AvatarUploader.Type\n\n has_many :tours, LoadedBike.Tour\n\n timestamps()\n end\n\n def changeset(struct, params \\\\ %{}) do\n struct\n |> cast(params, [:email, :name, :password, :twitter, :bio, :instagram])\n |> cast_attachments(params, [:avatar])\n |> validate_required([:email, :name])\n |> validate_format(:email, ~r\/@\/)\n |> validate_email_uniqueness\n |> changeset_set_password\n |> changeset_set_verification_token\n end\n\n def generate_password_reset_token!(struct) do\n struct\n |> change(password_reset_token: SecureRandom.urlsafe_base64)\n |> Repo.update!\n end\n\n def verify!(user) do\n user\n |> change(verification_token: nil)\n |> Repo.update()\n end\n\n def change_password!(struct, password) do\n struct\n |> changeset(%{password: password})\n |> put_change(:password_reset_token, nil)\n |> Repo.update()\n end\n\n defp changeset_set_password(changeset) do\n state = Ecto.get_meta(changeset.data, :state)\n new_password = get_change(changeset, :password)\n\n cond do\n state == :built or new_password ->\n changeset\n |> validate_required([:password])\n |> validate_length(:password, min: 6, max: 100)\n |> hash_password()\n true ->\n changeset\n end\n end\n\n defp validate_email_uniqueness(changeset) do\n email = get_change(changeset, :email)\n if __MODULE__ |> where(email: ^email) |> Repo.one do\n changeset |> add_error(:email, \"Email address already taken\")\n else\n changeset\n end\n end\n\n defp changeset_set_verification_token(changeset) do\n case Ecto.get_meta(changeset.data, :state) do\n :built ->\n put_change(changeset, :verification_token, SecureRandom.urlsafe_base64)\n _ ->\n changeset\n end\n end\n\n defp hash_password(changeset) do\n case changeset do\n %Ecto.Changeset{valid?: true, changes: %{password: password}} ->\n put_change(changeset, :password_hash, Comeonin.Bcrypt.hashpwsalt(password))\n _ ->\n changeset\n end\n end\nend\n","old_contents":"defmodule LoadedBike.User do\n use LoadedBike.Web, :model\n use Arc.Ecto.Schema\n\n require IEx\n\n schema \"users\" do\n field :email, :string\n field :name, :string\n field :bio, :string\n field :twitter, :string\n field :instagram, :string\n field :password_hash, :string\n field :password, :string, virtual: true\n field :password_reset_token, :string\n field :verification_token, :string\n\n field :avatar, LoadedBike.Web.AvatarUploader.Type\n\n has_many :tours, LoadedBike.Tour\n\n timestamps()\n end\n\n def changeset(struct, params \\\\ %{}) do\n struct\n |> cast(params, [:email, :name, :password, :twitter, :bio, :instagram])\n |> cast_attachments(params, [:avatar])\n |> validate_required([:email, :name])\n |> validate_format(:email, ~r\/@\/)\n |> validate_email_uniqueness\n |> changeset_set_password\n |> changeset_set_verification_token\n end\n\n def generate_password_reset_token!(struct) do\n struct\n |> change(password_reset_token: SecureRandom.urlsafe_base64)\n |> Repo.update!\n end\n\n def verify!(user) do\n user\n |> change(verification_token: nil)\n |> Repo.update()\n end\n\n def change_password!(struct, password) do\n struct\n |> changeset(%{password: password})\n |> put_change(:password_reset_token, nil)\n |> Repo.update()\n end\n\n defp changeset_set_password(changeset) do\n state = Ecto.get_meta(changeset.data, :state)\n new_password = get_change(changeset, :password)\n\n cond do\n state == :built or new_password ->\n changeset\n |> validate_required([:password])\n |> validate_length(:password, min: 6, max: 100)\n |> hash_password()\n true ->\n changeset\n end\n end\n\n defp validate_email_uniqueness(changeset) do\n email = get_change(changeset, :email)\n if __MODULE__ |> where(email: ^email) |> Repo.one do\n changeset |> add_error(:email, \"Email address already taken\")\n else\n changeset\n end\n end\n\n defp changeset_set_verification_token(changeset) do\n case Ecto.get_meta(changeset.data, :state) do\n :built ->\n put_change(changeset, :verification_token, SecureRandom.urlsafe_base64)\n _ ->\n changeset\n end\n end\n\n defp hash_password(changeset) do\n case changeset do\n %Ecto.Changeset{valid?: true, changes: %{password: password}} ->\n put_change(changeset, :password_hash, Comeonin.Bcrypt.hashpwsalt(password))\n _ ->\n changeset\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"83ca2cf46cb76cab3619a824b0b06d5fac80c462","subject":"Correct overtime tax calculation for Mar 2022 payroll and future","message":"Correct overtime tax calculation for Mar 2022 payroll and future\n","repos":"imprest\/mgp,imprest\/mgp","old_file":"lib\/mgp\/sync\/import_payroll.ex","new_file":"lib\/mgp\/sync\/import_payroll.ex","new_contents":"defmodule Mgp.Sync.ImportPayroll do\n @moduledoc \"Import and check payroll data\"\n\n import Mgp.Utils, only: [to_date: 1, to_time: 1]\n alias Mgp.Sync.DbaseParser\n\n @root_folder \"\/home\/hvaria\/backup\/HPMG22\/\"\n @expat_salary \"\/home\/hvaria\/backup\/salary.csv\"\n @employee_master \"H1EMP.DBF\"\n @calculated_payroll \"H1DETPAY.DBF\"\n\n def get_management_payroll(month), do: get_management_pay(determine_management_month(month))\n defp get_management_pay(nil), do: []\n\n defp get_management_pay(m) do\n File.read!(@expat_salary)\n |> String.trim()\n |> String.split(\"\\n\")\n |> Enum.drop(1)\n |> Enum.map(fn x ->\n [\n month,\n id,\n tin_no,\n name,\n position,\n salary,\n living_percent,\n vehicle,\n non_cash_percent,\n ssnit_ded,\n ssnit_no\n ] = String.split(x, \",\")\n\n if month === m do\n earned_salary = salary\n tax_year = 2020\n\n {ssnit_amount, ssnit_emp_contrib, ssnit_total, ssnit_tier_1, ssnit_tier_2} =\n ssnit_computations(tax_year, id, earned_salary, ssnit_ded)\n\n living = Decimal.mult(earned_salary, string_to_percent(living_percent))\n non_cash = Decimal.mult(earned_salary, string_to_percent(non_cash_percent))\n total_additions = Decimal.add(Decimal.add(living, non_cash), vehicle)\n taxable_income = Decimal.sub(Decimal.add(earned_salary, total_additions), ssnit_amount)\n tax_ded = gra_income_tax(taxable_income, determine_tax_year(month))\n\n %{\n month: month,\n id: id,\n tin_no: tin_no,\n ssnit_no: ssnit_no,\n name: name,\n gra_category: position,\n base_salary: earned_salary,\n earned_salary: String.to_integer(earned_salary),\n cash_allowance: 0,\n total_cash: earned_salary,\n ssnit_ded: string_to_percent(ssnit_ded),\n ssnit_amount: ssnit_amount,\n ssnit_emp_contrib: ssnit_emp_contrib,\n ssnit_total: ssnit_total,\n ssnit_tier_1: ssnit_tier_1,\n ssnit_tier_2: ssnit_tier_2,\n pf_amount: 0,\n living_percent: string_to_percent(living_percent),\n living: living,\n vehicle: vehicle,\n non_cash_percent: string_to_percent(non_cash_percent),\n non_cash: non_cash,\n total_additions: total_additions,\n total_gra_income: Decimal.add(earned_salary, total_additions),\n total_relief: ssnit_amount,\n taxable_income: taxable_income,\n tax_ded: tax_ded,\n overtime_earned: 0,\n overtime_tax: 0,\n total_tax: tax_ded,\n net_pay: Decimal.sub(Decimal.sub(earned_salary, tax_ded), ssnit_amount)\n }\n else\n []\n end\n end)\n |> :lists.flatten()\n end\n\n defp string_to_percent(t), do: Decimal.div(Decimal.new(t), 100)\n\n def determine_management_month(month) do\n File.read!(@expat_salary)\n |> String.trim()\n |> String.split(\"\\n\")\n |> Enum.drop(1)\n |> Enum.map(fn x -> hd(String.split(x, \",\")) end)\n |> Enum.uniq()\n |> Enum.find(fn x -> x <= month end)\n end\n\n def import_month(folder \\\\ @root_folder, month) do\n files = generate_file_paths(folder)\n\n with employees <- parse_employee_master(files.employee_master),\n payroll <- parse_and_calculate_monthly_payroll(files.payroll, month, employees) do\n Enum.sort_by(payroll, fn x -> x.id end)\n end\n end\n\n defp generate_file_paths(folder) do\n %{\n payroll: folder <> @calculated_payroll,\n employee_master: folder <> @employee_master\n }\n end\n\n def parse_employee_master(dbf_file) do\n DbaseParser.parse(\n dbf_file,\n [\n \"EMP_NO\",\n \"EMP_NM\",\n \"EMP_JOINDT\",\n \"EMP_DISCDT\",\n \"EMP_RTBASE\",\n \"EMP_SSNO\",\n \"EMP_FNO1\",\n \"EMP_FNO2\",\n \"EMP_FNO3\"\n ],\n fn x ->\n %{\n id: x[\"EMP_NO\"],\n name: x[\"EMP_NM\"],\n start_date: parse_date(x[\"EMP_JOINDT\"]),\n end_date: parse_date(x[\"EMP_DISCDT\"]),\n is_terminated: parse_terminated(x[\"EMP_RTBASE\"]),\n ssnit_no: x[\"EMP_SSNO\"],\n tin_no: x[\"EMP_FNO1\"],\n ssnit_t2: x[\"EMP_FNO2\"],\n pf_no: x[\"EMP_FNO3\"]\n }\n end\n )\n |> Enum.reduce(%{}, fn x, acc ->\n Map.put(acc, x.id, x)\n end)\n end\n\n defp determine_tax_year(month) do\n cond do\n month > \"2112M\" -> 2022\n month > \"1912M\" -> 2020\n month > \"1812M\" -> 2019\n month <= \"1812M\" -> 2018\n end\n end\n\n defp parse_and_calculate_monthly_payroll(dbf_file, month, employees) do\n tax_year = determine_tax_year(month)\n\n DbaseParser.parse(\n dbf_file,\n [\n \"PD_MTH\",\n \"PD_EMPNO\",\n \"PD_RATE\",\n \"PD_DEPT\",\n \"PD_SDEPT\",\n \"PD_DESIG\",\n \"PD_CAT\",\n \"PD_OTAMT\",\n \"PD_DAYS\",\n \"PD_OTHALL\",\n \"PD_LOAN\",\n \"PD_ADV\",\n \"PD_PLADV\",\n \"PD_SSRT\",\n \"PD_TUCRT\",\n \"PD_DEDRT1\",\n \"PD_DEDRT2\",\n \"PD_TOTAL\",\n \"PD_CB\",\n \"PD_BKDET\",\n \"PD_LMU\",\n \"PD_LMD\",\n \"PD_LMT\"\n ],\n fn x ->\n if x[\"PD_MTH\"] === month do\n %{\n month: x[\"PD_MTH\"],\n id: x[\"PD_EMPNO\"],\n base_salary: x[\"PD_RATE\"],\n dept: parse_dept(x[\"PD_DEPT\"]),\n sub_dept: parse_sub_dept(x[\"PD_SDEPT\"]),\n title: x[\"PD_DESIG\"],\n gra_category: x[\"PD_CAT\"],\n overtime_earned: x[\"PD_OTAMT\"],\n days_worked: x[\"PD_DAYS\"],\n cash_allowance: x[\"PD_OTHALL\"],\n loan: x[\"PD_LOAN\"],\n advance: x[\"PD_ADV\"],\n pvt_loan: x[\"PD_PLADV\"],\n ssnit_ded: parse_ssnit_ded(Decimal.to_string(x[\"PD_SSRT\"]), x[\"PD_EMPNO\"]),\n tuc_ded: parse_tuc_ded(Decimal.to_string(x[\"PD_TUCRT\"])),\n staff_welfare_ded: x[\"PD_DEDRT1\"],\n pf_ded: x[\"PD_DEDRT2\"],\n net_pay: x[\"PD_TOTAL\"],\n is_cash: parse_cash(x[\"PD_CB\"]),\n bank: x[\"PD_BKDET\"],\n lmu: x[\"PD_LMU\"],\n lmd: to_date(x[\"PD_LMD\"]),\n lmt: to_time(x[\"PD_LMT\"])\n }\n else\n nil\n end\n end\n )\n |> Task.async_stream(&parse_payroll_record(&1, employees, tax_year))\n |> Stream.map(fn {:ok, res} -> res end)\n # |> Stream.map(&parse_payroll_record(&1))\n |> Enum.to_list()\n end\n\n ### Private Functions ###\n defp parse_payroll_record(emp, employees, tax_year) do\n earned_salary =\n Decimal.round(Decimal.mult(emp.base_salary, Decimal.div(emp.days_worked, 27)), 2)\n\n {ssnit_amount, ssnit_emp_contrib, ssnit_total, ssnit_tier_1, ssnit_tier_2} =\n ssnit_computations(tax_year, emp.id, earned_salary, emp.ssnit_ded)\n\n pf_amount = Decimal.round(Decimal.mult(Decimal.div(emp.pf_ded, 100), earned_salary), 2)\n\n total_cash = Decimal.add(earned_salary, emp.cash_allowance)\n\n total_relief = Decimal.add(ssnit_amount, pf_amount)\n\n taxable_income = Decimal.sub(total_cash, total_relief)\n\n tax_ded = gra_income_tax(taxable_income, tax_year)\n\n overtime_tax = gra_overtime_tax(emp.overtime_earned, earned_salary)\n\n total_tax = Decimal.add(tax_ded, overtime_tax)\n\n tuc_amount = Decimal.round(Decimal.mult(Decimal.div(emp.tuc_ded, 100), earned_salary), 2)\n\n total_ded =\n Decimal.add(\n emp.advance,\n Decimal.add(\n emp.loan,\n Decimal.add(\n emp.pvt_loan,\n Decimal.add(emp.staff_welfare_ded, tuc_amount)\n )\n )\n )\n\n total_pay = Decimal.sub(taxable_income, Decimal.add(total_tax, total_ded))\n\n Map.merge(\n emp,\n Map.merge(\n employees[emp.id],\n %{\n earned_salary: earned_salary,\n ssnit_emp_contrib: ssnit_emp_contrib,\n ssnit_amount: ssnit_amount,\n ssnit_total: ssnit_total,\n ssnit_tier_1: ssnit_tier_1,\n ssnit_tier_2: ssnit_tier_2,\n pf_amount: pf_amount,\n taxable_income: taxable_income,\n total_cash: total_cash,\n total_relief: total_relief,\n tax_ded: tax_ded,\n overtime_tax: overtime_tax,\n total_tax: total_tax,\n tuc_amount: tuc_amount,\n total_ded: total_ded,\n total_pay: total_pay\n }\n )\n )\n end\n\n defp ssnit_computations(tax_year, emp_id, earned_salary, ssnit_ded) do\n ssnit_amount =\n if emp_id === \"E0053\" do\n if tax_year < 2020 do\n Decimal.round(Decimal.mult(Decimal.div(ssnit_ded, 100), earned_salary), 2)\n else\n Decimal.new(0)\n end\n else\n Decimal.round(Decimal.mult(Decimal.div(ssnit_ded, 100), earned_salary), 2)\n end\n\n {ssnit_emp_contrib, ssnit_total, ssnit_tier_1, ssnit_tier_2} =\n case emp_id === \"E0053\" do\n true ->\n if tax_year < 2020 do\n # 12.5 div 5\n ssnit_emp_contrib =\n Decimal.round(Decimal.mult(Decimal.from_float(2.5), ssnit_amount), 2)\n\n ssnit_total = Decimal.add(ssnit_amount, ssnit_emp_contrib)\n ssnit_tier_1 = ssnit_total\n ssnit_tier_2 = Decimal.new(0)\n {ssnit_emp_contrib, ssnit_total, ssnit_tier_1, ssnit_tier_2}\n else\n ssnit_emp_contrib = Decimal.new(0)\n ssnit_total = Decimal.new(0)\n ssnit_tier_1 = Decimal.new(0)\n ssnit_tier_2 = Decimal.new(0)\n {ssnit_emp_contrib, ssnit_total, ssnit_tier_1, ssnit_tier_2}\n end\n\n false ->\n # 13 div 5.5\n ssnit_emp_contrib =\n Decimal.round(Decimal.mult(Decimal.from_float(2.363636364), ssnit_amount), 2)\n\n ssnit_total = Decimal.add(ssnit_amount, ssnit_emp_contrib)\n\n ssnit_tier_1 =\n Decimal.round(Decimal.mult(Decimal.from_float(0.72972973), ssnit_total), 2)\n\n ssnit_tier_2 = Decimal.sub(ssnit_total, ssnit_tier_1)\n {ssnit_emp_contrib, ssnit_total, ssnit_tier_1, ssnit_tier_2}\n end\n\n {ssnit_amount, ssnit_emp_contrib, ssnit_total, ssnit_tier_1, ssnit_tier_2}\n end\n\n defp gra_overtime_tax(o, earned_salary) do\n half_earned_salary = Decimal.div(earned_salary, 2)\n\n case Decimal.compare(o, half_earned_salary) do\n :gt ->\n excess_tax = Decimal.mult(Decimal.sub(o, half_earned_salary), Decimal.new(\"0.1\"))\n\n Decimal.round(\n Decimal.add(excess_tax, Decimal.mult(half_earned_salary, Decimal.new(\"0.05\"))),\n 2\n )\n\n _ ->\n Decimal.round(Decimal.mult(o, Decimal.new(\"0.05\")), 2)\n end\n end\n\n defp compute_tax(income, [[tax_bracket, rate, cum_tax] | t], prev_tax_bracket) do\n if Decimal.compare(income, tax_bracket) != :gt do\n Decimal.round(\n Decimal.add(\n Decimal.mult(\n Decimal.sub(income, prev_tax_bracket),\n rate\n ),\n cum_tax\n ),\n 2\n )\n else\n compute_tax(income, t, tax_bracket)\n end\n end\n\n defp gra_income_tax(taxable_income, 2022) do\n tax_table = [\n # [Chargeable income, % rate, cumulative tax]\n [Decimal.new(365), Decimal.new(0), Decimal.new(0)],\n [Decimal.new(475), Decimal.new(\"0.050\"), Decimal.new(0)],\n [Decimal.new(605), Decimal.new(\"0.100\"), Decimal.new(\"5.5\")],\n [Decimal.new(3605), Decimal.new(\"0.175\"), Decimal.new(\"18.5\")],\n [Decimal.new(20000), Decimal.new(\"0.250\"), Decimal.new(\"543.5\")],\n [%Decimal{coef: :inf}, Decimal.new(\"0.300\"), Decimal.new(\"4642.25\")]\n ]\n\n compute_tax(taxable_income, tax_table, Decimal.new(0))\n end\n\n defp gra_income_tax(taxable_income, 2020) do\n tax_table = [\n # [Chargeable income, % rate, cumulative tax]\n [Decimal.new(319), Decimal.new(0), Decimal.new(0)],\n [Decimal.new(419), Decimal.new(\"0.050\"), Decimal.new(0)],\n [Decimal.new(539), Decimal.new(\"0.100\"), Decimal.new(5)],\n [Decimal.new(3539), Decimal.new(\"0.175\"), Decimal.new(17)],\n [Decimal.new(20000), Decimal.new(\"0.250\"), Decimal.new(542)],\n [%Decimal{coef: :inf}, Decimal.new(\"0.300\"), Decimal.new(\"4657.25\")]\n ]\n\n compute_tax(taxable_income, tax_table, Decimal.new(0))\n end\n\n defp gra_income_tax(taxable_income, 2019) do\n tax_table = [\n [Decimal.new(288), Decimal.new(0), Decimal.new(0)],\n [Decimal.new(388), Decimal.new(\"0.050\"), Decimal.new(0)],\n [Decimal.new(528), Decimal.new(\"0.100\"), Decimal.new(5)],\n [Decimal.new(3528), Decimal.new(\"0.175\"), Decimal.new(19)],\n [Decimal.new(20000), Decimal.new(\"0.250\"), Decimal.new(544)],\n [%Decimal{coef: :inf}, Decimal.new(\"0.300\"), Decimal.new(4662)]\n ]\n\n compute_tax(taxable_income, tax_table, Decimal.new(0))\n end\n\n defp gra_income_tax(taxable_income, _) do\n tax_table = [\n [Decimal.new(216), Decimal.new(0), Decimal.new(0)],\n [Decimal.new(331), Decimal.new(\"0.050\"), Decimal.new(0)],\n [Decimal.new(431), Decimal.new(\"0.100\"), Decimal.new(\"3.5\")],\n [Decimal.new(3241), Decimal.new(\"0.175\"), Decimal.new(\"13.5\")],\n [Decimal.new(10000), Decimal.new(\"0.250\"), Decimal.new(\"505.25\")],\n [%Decimal{coef: :inf}, Decimal.new(\"0.350\"), Decimal.new(2195)]\n ]\n\n compute_tax(taxable_income, tax_table, Decimal.new(0))\n end\n\n defp parse_ssnit_ded(_, \"E0053\"), do: Decimal.new(5)\n defp parse_ssnit_ded(\"5.50\", _), do: Decimal.new(\"5.5\")\n defp parse_ssnit_ded(\"0.00\", _), do: Decimal.new(0)\n defp parse_ssnit_ded(\"N\", _), do: Decimal.new(0)\n defp parse_ssnit_ded(\"Y\", \"E0053\"), do: Decimal.new(5)\n defp parse_ssnit_ded(\"Y\", _), do: Decimal.new(\"5.5\")\n\n defp parse_dept(\"M001\"), do: \"ADMINSTRATION\"\n defp parse_dept(\"M002\"), do: \"FACTORY\"\n defp parse_dept(_), do: \"\"\n\n defp parse_sub_dept(\"S001\"), do: \"DRIVERS\"\n defp parse_sub_dept(\"S002\"), do: \"MARKETING\"\n defp parse_sub_dept(\"S003\"), do: \"SECURITY\"\n defp parse_sub_dept(\"S004\"), do: \"STORES\"\n defp parse_sub_dept(\"S005\"), do: \"WORKERS\"\n defp parse_sub_dept(\"S006\"), do: \"QUALITY CONTROL\"\n defp parse_sub_dept(\"S007\"), do: \"MAINTENANCE\"\n defp parse_sub_dept(\"S008\"), do: \"OTHERS\"\n defp parse_sub_dept(_), do: \"\"\n\n defp parse_terminated(\"M\"), do: false\n defp parse_terminated(\"X\"), do: true\n defp parse_terminated(\"D\"), do: true\n\n defp parse_cash(\"C\"), do: true\n defp parse_cash(\"B\"), do: false\n\n defp parse_tuc_ded(\"2.00\"), do: Decimal.new(2)\n defp parse_tuc_ded(\"0.00\"), do: Decimal.new(0)\n defp parse_tuc_ded(\"Y\"), do: Decimal.new(2)\n defp parse_tuc_ded(\"N\"), do: Decimal.new(0)\n\n defp parse_date(\"\"), do: nil\n defp parse_date(date), do: to_date(date)\nend\n","old_contents":"defmodule Mgp.Sync.ImportPayroll do\n @moduledoc \"Import and check payroll data\"\n\n import Mgp.Utils, only: [to_date: 1, to_time: 1]\n alias Mgp.Sync.DbaseParser\n\n @root_folder \"\/home\/hvaria\/backup\/HPMG22\/\"\n @expat_salary \"\/home\/hvaria\/backup\/salary.csv\"\n @employee_master \"H1EMP.DBF\"\n @calculated_payroll \"H1DETPAY.DBF\"\n\n @decimal_50 Decimal.new(\"50\")\n\n def get_management_payroll(month), do: get_management_pay(determine_management_month(month))\n defp get_management_pay(nil), do: []\n\n defp get_management_pay(m) do\n File.read!(@expat_salary)\n |> String.trim()\n |> String.split(\"\\n\")\n |> Enum.drop(1)\n |> Enum.map(fn x ->\n [\n month,\n id,\n tin_no,\n name,\n position,\n salary,\n living_percent,\n vehicle,\n non_cash_percent,\n ssnit_ded,\n ssnit_no\n ] = String.split(x, \",\")\n\n if month === m do\n earned_salary = salary\n tax_year = 2020\n\n {ssnit_amount, ssnit_emp_contrib, ssnit_total, ssnit_tier_1, ssnit_tier_2} =\n ssnit_computations(tax_year, id, earned_salary, ssnit_ded)\n\n living = Decimal.mult(earned_salary, string_to_percent(living_percent))\n non_cash = Decimal.mult(earned_salary, string_to_percent(non_cash_percent))\n total_additions = Decimal.add(Decimal.add(living, non_cash), vehicle)\n taxable_income = Decimal.sub(Decimal.add(earned_salary, total_additions), ssnit_amount)\n tax_ded = gra_income_tax(taxable_income, determine_tax_year(month))\n\n %{\n month: month,\n id: id,\n tin_no: tin_no,\n ssnit_no: ssnit_no,\n name: name,\n gra_category: position,\n base_salary: earned_salary,\n earned_salary: String.to_integer(earned_salary),\n cash_allowance: 0,\n total_cash: earned_salary,\n ssnit_ded: string_to_percent(ssnit_ded),\n ssnit_amount: ssnit_amount,\n ssnit_emp_contrib: ssnit_emp_contrib,\n ssnit_total: ssnit_total,\n ssnit_tier_1: ssnit_tier_1,\n ssnit_tier_2: ssnit_tier_2,\n pf_amount: 0,\n living_percent: string_to_percent(living_percent),\n living: living,\n vehicle: vehicle,\n non_cash_percent: string_to_percent(non_cash_percent),\n non_cash: non_cash,\n total_additions: total_additions,\n total_gra_income: Decimal.add(earned_salary, total_additions),\n total_relief: ssnit_amount,\n taxable_income: taxable_income,\n tax_ded: tax_ded,\n overtime_earned: 0,\n overtime_tax: 0,\n total_tax: tax_ded,\n net_pay: Decimal.sub(Decimal.sub(earned_salary, tax_ded), ssnit_amount)\n }\n else\n []\n end\n end)\n |> :lists.flatten()\n end\n\n defp string_to_percent(t), do: Decimal.div(Decimal.new(t), 100)\n\n def determine_management_month(month) do\n File.read!(@expat_salary)\n |> String.trim()\n |> String.split(\"\\n\")\n |> Enum.drop(1)\n |> Enum.map(fn x -> hd(String.split(x, \",\")) end)\n |> Enum.uniq()\n |> Enum.find(fn x -> x <= month end)\n end\n\n def import_month(folder \\\\ @root_folder, month) do\n files = generate_file_paths(folder)\n\n with employees <- parse_employee_master(files.employee_master),\n payroll <- parse_and_calculate_monthly_payroll(files.payroll, month, employees) do\n Enum.sort_by(payroll, fn x -> x.id end)\n end\n end\n\n defp generate_file_paths(folder) do\n %{\n payroll: folder <> @calculated_payroll,\n employee_master: folder <> @employee_master\n }\n end\n\n def parse_employee_master(dbf_file) do\n DbaseParser.parse(\n dbf_file,\n [\n \"EMP_NO\",\n \"EMP_NM\",\n \"EMP_JOINDT\",\n \"EMP_DISCDT\",\n \"EMP_RTBASE\",\n \"EMP_SSNO\",\n \"EMP_FNO1\",\n \"EMP_FNO2\",\n \"EMP_FNO3\"\n ],\n fn x ->\n %{\n id: x[\"EMP_NO\"],\n name: x[\"EMP_NM\"],\n start_date: parse_date(x[\"EMP_JOINDT\"]),\n end_date: parse_date(x[\"EMP_DISCDT\"]),\n is_terminated: parse_terminated(x[\"EMP_RTBASE\"]),\n ssnit_no: x[\"EMP_SSNO\"],\n tin_no: x[\"EMP_FNO1\"],\n ssnit_t2: x[\"EMP_FNO2\"],\n pf_no: x[\"EMP_FNO3\"]\n }\n end\n )\n |> Enum.reduce(%{}, fn x, acc ->\n Map.put(acc, x.id, x)\n end)\n end\n\n defp determine_tax_year(month) do\n cond do\n month > \"2112M\" -> 2022\n month > \"1912M\" -> 2020\n month > \"1812M\" -> 2019\n month <= \"1812M\" -> 2018\n end\n end\n\n defp parse_and_calculate_monthly_payroll(dbf_file, month, employees) do\n tax_year = determine_tax_year(month)\n\n DbaseParser.parse(\n dbf_file,\n [\n \"PD_MTH\",\n \"PD_EMPNO\",\n \"PD_RATE\",\n \"PD_DEPT\",\n \"PD_SDEPT\",\n \"PD_DESIG\",\n \"PD_CAT\",\n \"PD_OTAMT\",\n \"PD_DAYS\",\n \"PD_OTHALL\",\n \"PD_LOAN\",\n \"PD_ADV\",\n \"PD_PLADV\",\n \"PD_SSRT\",\n \"PD_TUCRT\",\n \"PD_DEDRT1\",\n \"PD_DEDRT2\",\n \"PD_TOTAL\",\n \"PD_CB\",\n \"PD_BKDET\",\n \"PD_LMU\",\n \"PD_LMD\",\n \"PD_LMT\"\n ],\n fn x ->\n if x[\"PD_MTH\"] === month do\n %{\n month: x[\"PD_MTH\"],\n id: x[\"PD_EMPNO\"],\n base_salary: x[\"PD_RATE\"],\n dept: parse_dept(x[\"PD_DEPT\"]),\n sub_dept: parse_sub_dept(x[\"PD_SDEPT\"]),\n title: x[\"PD_DESIG\"],\n gra_category: x[\"PD_CAT\"],\n overtime_earned: x[\"PD_OTAMT\"],\n days_worked: x[\"PD_DAYS\"],\n cash_allowance: x[\"PD_OTHALL\"],\n loan: x[\"PD_LOAN\"],\n advance: x[\"PD_ADV\"],\n pvt_loan: x[\"PD_PLADV\"],\n ssnit_ded: parse_ssnit_ded(Decimal.to_string(x[\"PD_SSRT\"]), x[\"PD_EMPNO\"]),\n tuc_ded: parse_tuc_ded(Decimal.to_string(x[\"PD_TUCRT\"])),\n staff_welfare_ded: x[\"PD_DEDRT1\"],\n pf_ded: x[\"PD_DEDRT2\"],\n net_pay: x[\"PD_TOTAL\"],\n is_cash: parse_cash(x[\"PD_CB\"]),\n bank: x[\"PD_BKDET\"],\n lmu: x[\"PD_LMU\"],\n lmd: to_date(x[\"PD_LMD\"]),\n lmt: to_time(x[\"PD_LMT\"])\n }\n else\n nil\n end\n end\n )\n |> Task.async_stream(&parse_payroll_record(&1, employees, tax_year))\n |> Stream.map(fn {:ok, res} -> res end)\n # |> Stream.map(&parse_payroll_record(&1))\n |> Enum.to_list()\n end\n\n ### Private Functions ###\n defp parse_payroll_record(emp, employees, tax_year) do\n earned_salary =\n Decimal.round(Decimal.mult(emp.base_salary, Decimal.div(emp.days_worked, 27)), 2)\n\n {ssnit_amount, ssnit_emp_contrib, ssnit_total, ssnit_tier_1, ssnit_tier_2} =\n ssnit_computations(tax_year, emp.id, earned_salary, emp.ssnit_ded)\n\n pf_amount = Decimal.round(Decimal.mult(Decimal.div(emp.pf_ded, 100), earned_salary), 2)\n\n total_cash = Decimal.add(earned_salary, emp.cash_allowance)\n\n total_relief = Decimal.add(ssnit_amount, pf_amount)\n\n taxable_income = Decimal.sub(total_cash, total_relief)\n\n tax_ded = gra_income_tax(taxable_income, tax_year)\n\n overtime_tax = gra_overtime_tax(emp.overtime_earned, emp.base_salary)\n\n total_tax = Decimal.add(tax_ded, overtime_tax)\n\n tuc_amount = Decimal.round(Decimal.mult(Decimal.div(emp.tuc_ded, 100), earned_salary), 2)\n\n total_ded =\n Decimal.add(\n emp.advance,\n Decimal.add(\n emp.loan,\n Decimal.add(\n emp.pvt_loan,\n Decimal.add(emp.staff_welfare_ded, tuc_amount)\n )\n )\n )\n\n total_pay = Decimal.sub(taxable_income, Decimal.add(total_tax, total_ded))\n\n Map.merge(\n emp,\n Map.merge(\n employees[emp.id],\n %{\n earned_salary: earned_salary,\n ssnit_emp_contrib: ssnit_emp_contrib,\n ssnit_amount: ssnit_amount,\n ssnit_total: ssnit_total,\n ssnit_tier_1: ssnit_tier_1,\n ssnit_tier_2: ssnit_tier_2,\n pf_amount: pf_amount,\n taxable_income: taxable_income,\n total_cash: total_cash,\n total_relief: total_relief,\n tax_ded: tax_ded,\n overtime_tax: overtime_tax,\n total_tax: total_tax,\n tuc_amount: tuc_amount,\n total_ded: total_ded,\n total_pay: total_pay\n }\n )\n )\n end\n\n defp ssnit_computations(tax_year, emp_id, earned_salary, ssnit_ded) do\n ssnit_amount =\n if emp_id === \"E0053\" do\n if tax_year < 2020 do\n Decimal.round(Decimal.mult(Decimal.div(ssnit_ded, 100), earned_salary), 2)\n else\n Decimal.new(0)\n end\n else\n Decimal.round(Decimal.mult(Decimal.div(ssnit_ded, 100), earned_salary), 2)\n end\n\n {ssnit_emp_contrib, ssnit_total, ssnit_tier_1, ssnit_tier_2} =\n case emp_id === \"E0053\" do\n true ->\n if tax_year < 2020 do\n # 12.5 div 5\n ssnit_emp_contrib =\n Decimal.round(Decimal.mult(Decimal.from_float(2.5), ssnit_amount), 2)\n\n ssnit_total = Decimal.add(ssnit_amount, ssnit_emp_contrib)\n ssnit_tier_1 = ssnit_total\n ssnit_tier_2 = Decimal.new(0)\n {ssnit_emp_contrib, ssnit_total, ssnit_tier_1, ssnit_tier_2}\n else\n ssnit_emp_contrib = Decimal.new(0)\n ssnit_total = Decimal.new(0)\n ssnit_tier_1 = Decimal.new(0)\n ssnit_tier_2 = Decimal.new(0)\n {ssnit_emp_contrib, ssnit_total, ssnit_tier_1, ssnit_tier_2}\n end\n\n false ->\n # 13 div 5.5\n ssnit_emp_contrib =\n Decimal.round(Decimal.mult(Decimal.from_float(2.363636364), ssnit_amount), 2)\n\n ssnit_total = Decimal.add(ssnit_amount, ssnit_emp_contrib)\n\n ssnit_tier_1 =\n Decimal.round(Decimal.mult(Decimal.from_float(0.72972973), ssnit_total), 2)\n\n ssnit_tier_2 = Decimal.sub(ssnit_total, ssnit_tier_1)\n {ssnit_emp_contrib, ssnit_total, ssnit_tier_1, ssnit_tier_2}\n end\n\n {ssnit_amount, ssnit_emp_contrib, ssnit_total, ssnit_tier_1, ssnit_tier_2}\n end\n\n defp gra_overtime_tax(o, earned_salary) do\n percent = Decimal.mult(Decimal.div(o, earned_salary), 100)\n\n case Decimal.compare(percent, @decimal_50) do\n :gt ->\n Decimal.round(Decimal.mult(o, Decimal.new(\"0.1\")), 2)\n\n _ ->\n Decimal.round(Decimal.mult(o, Decimal.new(\"0.05\")), 2)\n end\n end\n\n defp compute_tax(income, [[tax_bracket, rate, cum_tax] | t], prev_tax_bracket) do\n if Decimal.compare(income, tax_bracket) != :gt do\n Decimal.round(\n Decimal.add(\n Decimal.mult(\n Decimal.sub(income, prev_tax_bracket),\n rate\n ),\n cum_tax\n ),\n 2\n )\n else\n compute_tax(income, t, tax_bracket)\n end\n end\n\n defp gra_income_tax(taxable_income, 2022) do\n tax_table = [\n # [Chargeable income, % rate, cumulative tax]\n [Decimal.new(365), Decimal.new(0), Decimal.new(0)],\n [Decimal.new(475), Decimal.new(\"0.050\"), Decimal.new(0)],\n [Decimal.new(605), Decimal.new(\"0.100\"), Decimal.new(\"5.5\")],\n [Decimal.new(3605), Decimal.new(\"0.175\"), Decimal.new(\"18.5\")],\n [Decimal.new(20000), Decimal.new(\"0.250\"), Decimal.new(\"543.5\")],\n [%Decimal{coef: :inf}, Decimal.new(\"0.300\"), Decimal.new(\"4642.25\")]\n ]\n\n compute_tax(taxable_income, tax_table, Decimal.new(0))\n end\n\n defp gra_income_tax(taxable_income, 2020) do\n tax_table = [\n # [Chargeable income, % rate, cumulative tax]\n [Decimal.new(319), Decimal.new(0), Decimal.new(0)],\n [Decimal.new(419), Decimal.new(\"0.050\"), Decimal.new(0)],\n [Decimal.new(539), Decimal.new(\"0.100\"), Decimal.new(5)],\n [Decimal.new(3539), Decimal.new(\"0.175\"), Decimal.new(17)],\n [Decimal.new(20000), Decimal.new(\"0.250\"), Decimal.new(542)],\n [%Decimal{coef: :inf}, Decimal.new(\"0.300\"), Decimal.new(\"4657.25\")]\n ]\n\n compute_tax(taxable_income, tax_table, Decimal.new(0))\n end\n\n defp gra_income_tax(taxable_income, 2019) do\n tax_table = [\n [Decimal.new(288), Decimal.new(0), Decimal.new(0)],\n [Decimal.new(388), Decimal.new(\"0.050\"), Decimal.new(0)],\n [Decimal.new(528), Decimal.new(\"0.100\"), Decimal.new(5)],\n [Decimal.new(3528), Decimal.new(\"0.175\"), Decimal.new(19)],\n [Decimal.new(20000), Decimal.new(\"0.250\"), Decimal.new(544)],\n [%Decimal{coef: :inf}, Decimal.new(\"0.300\"), Decimal.new(4662)]\n ]\n\n compute_tax(taxable_income, tax_table, Decimal.new(0))\n end\n\n defp gra_income_tax(taxable_income, _) do\n tax_table = [\n [Decimal.new(216), Decimal.new(0), Decimal.new(0)],\n [Decimal.new(331), Decimal.new(\"0.050\"), Decimal.new(0)],\n [Decimal.new(431), Decimal.new(\"0.100\"), Decimal.new(\"3.5\")],\n [Decimal.new(3241), Decimal.new(\"0.175\"), Decimal.new(\"13.5\")],\n [Decimal.new(10000), Decimal.new(\"0.250\"), Decimal.new(\"505.25\")],\n [%Decimal{coef: :inf}, Decimal.new(\"0.350\"), Decimal.new(2195)]\n ]\n\n compute_tax(taxable_income, tax_table, Decimal.new(0))\n end\n\n defp parse_ssnit_ded(_, \"E0053\"), do: Decimal.new(5)\n defp parse_ssnit_ded(\"5.50\", _), do: Decimal.new(\"5.5\")\n defp parse_ssnit_ded(\"0.00\", _), do: Decimal.new(0)\n defp parse_ssnit_ded(\"N\", _), do: Decimal.new(0)\n defp parse_ssnit_ded(\"Y\", \"E0053\"), do: Decimal.new(5)\n defp parse_ssnit_ded(\"Y\", _), do: Decimal.new(\"5.5\")\n\n defp parse_dept(\"M001\"), do: \"ADMINSTRATION\"\n defp parse_dept(\"M002\"), do: \"FACTORY\"\n defp parse_dept(_), do: \"\"\n\n defp parse_sub_dept(\"S001\"), do: \"DRIVERS\"\n defp parse_sub_dept(\"S002\"), do: \"MARKETING\"\n defp parse_sub_dept(\"S003\"), do: \"SECURITY\"\n defp parse_sub_dept(\"S004\"), do: \"STORES\"\n defp parse_sub_dept(\"S005\"), do: \"WORKERS\"\n defp parse_sub_dept(\"S006\"), do: \"QUALITY CONTROL\"\n defp parse_sub_dept(\"S007\"), do: \"MAINTENANCE\"\n defp parse_sub_dept(\"S008\"), do: \"OTHERS\"\n defp parse_sub_dept(_), do: \"\"\n\n defp parse_terminated(\"M\"), do: false\n defp parse_terminated(\"X\"), do: true\n defp parse_terminated(\"D\"), do: true\n\n defp parse_cash(\"C\"), do: true\n defp parse_cash(\"B\"), do: false\n\n defp parse_tuc_ded(\"2.00\"), do: Decimal.new(2)\n defp parse_tuc_ded(\"0.00\"), do: Decimal.new(0)\n defp parse_tuc_ded(\"Y\"), do: Decimal.new(2)\n defp parse_tuc_ded(\"N\"), do: Decimal.new(0)\n\n defp parse_date(\"\"), do: nil\n defp parse_date(date), do: to_date(date)\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"517b5280d09fa0f2075992cd4764a602f8d02908","subject":"remove redundant Supervisor.Spec import","message":"remove redundant Supervisor.Spec import\n","repos":"gjaldon\/phoenix,pap\/phoenix,mvidaurre\/phoenix,Gazler\/phoenix,Smulligan85\/phoenix,CultivateHQ\/phoenix,ybur-yug\/phoenix,evax\/phoenix,lono-devices\/phoenix,wsmoak\/phoenix,evax\/phoenix,manukall\/phoenix,mvidaurre\/phoenix,ybur-yug\/phoenix,bsmr-erlang\/phoenix,Kosmas\/phoenix,michalmuskala\/phoenix,DavidAlphaFox\/phoenix,Ben-Evolently\/phoenix,ericmj\/phoenix,DavidAlphaFox\/phoenix,rodrigues\/phoenix,optikfluffel\/phoenix,trarbr\/phoenix,0x00evil\/phoenix,Smulligan85\/phoenix,phoenixframework\/phoenix,mschae\/phoenix,cas27\/phoenix,iStefo\/phoenix,lancehalvorsen\/phoenix,Kosmas\/phoenix,jwarwick\/phoenix,phoenixframework\/phoenix,ephe-meral\/phoenix,Joe-noh\/phoenix,stevedomin\/phoenix,ericmj\/phoenix,stevedomin\/phoenix,optikfluffel\/phoenix,vic\/phoenix,dmarkow\/phoenix,keathley\/phoenix,mitchellhenke\/phoenix,rodrigues\/phoenix,rafbgarcia\/phoenix,pap\/phoenix,phoenixframework\/phoenix,foxnewsnetwork\/phoenix,iStefo\/phoenix,Rumel\/phoenix,nshafer\/phoenix,nshafer\/phoenix,korobkov\/phoenix,jamilabreu\/phoenix,korobkov\/phoenix,0x00evil\/phoenix,mobileoverlord\/phoenix,ephe-meral\/phoenix,tony612\/phoenix,omotenko\/phoenix_auth,vic\/phoenix,Gazler\/phoenix,cas27\/phoenix,mitchellhenke\/phoenix,manukall\/phoenix,mschae\/phoenix,wsmoak\/phoenix,keathley\/phoenix,CultivateHQ\/phoenix,mobileoverlord\/phoenix,michalmuskala\/phoenix,omotenko\/phoenix_auth,eksperimental\/phoenix,Joe-noh\/phoenix,seejee\/phoenix,seejee\/phoenix,lancehalvorsen\/phoenix,eksperimental\/phoenix,lono-devices\/phoenix,nshafer\/phoenix,jamilabreu\/phoenix,andrewvy\/phoenix,Rumel\/phoenix,gjaldon\/phoenix,dmarkow\/phoenix,jwarwick\/phoenix,0x00evil\/phoenix,rafbgarcia\/phoenix,trarbr\/phoenix,optikfluffel\/phoenix,bsmr-erlang\/phoenix,andrewvy\/phoenix,rafbgarcia\/phoenix","old_file":"lib\/phoenix\/endpoint\/server.ex","new_file":"lib\/phoenix\/endpoint\/server.ex","new_contents":"defmodule Phoenix.Endpoint.Server do\n # The supervisor for the underlying handlers.\n @moduledoc false\n @handler Phoenix.Endpoint.CowboyHandler\n\n use Supervisor\n require Logger\n\n def start_link(otp_app, endpoint, opts \\\\ []) do\n Supervisor.start_link(__MODULE__, {otp_app, endpoint}, opts)\n end\n\n def init({otp_app, endpoint}) do\n children = []\n\n if config = endpoint.config(:http) do\n children =\n [@handler.child_spec(:http, endpoint, default(config, otp_app, 4000))|children]\n end\n\n if config = endpoint.config(:https) do\n {:ok, _} = Application.ensure_all_started(:ssl)\n children =\n [@handler.child_spec(:https, endpoint, default(config, otp_app, 4040))|children]\n end\n\n supervise(children, strategy: :one_for_one)\n end\n\n defp default(config, otp_app, port) do\n config =\n config\n |> Keyword.put_new(:otp_app, otp_app)\n |> Keyword.put_new(:port, port)\n\n Keyword.put(config, :port, to_port(config[:port]))\n end\n\n defp to_port(nil) do\n Logger.error \"Server can't start because :port in config is nil, please use a valid port number\"\n exit(:shutdown)\n end\n defp to_port(binary) when is_binary(binary), do: String.to_integer(binary)\n defp to_port(integer) when is_integer(integer), do: integer\n defp to_port({:system, env_var}), do: to_port(System.get_env(env_var))\nend\n","old_contents":"defmodule Phoenix.Endpoint.Server do\n # The supervisor for the underlying handlers.\n @moduledoc false\n @handler Phoenix.Endpoint.CowboyHandler\n\n use Supervisor\n require Logger\n\n def start_link(otp_app, endpoint, opts \\\\ []) do\n Supervisor.start_link(__MODULE__, {otp_app, endpoint}, opts)\n end\n\n def init({otp_app, endpoint}) do\n import Supervisor.Spec\n\n children = []\n\n if config = endpoint.config(:http) do\n children =\n [@handler.child_spec(:http, endpoint, default(config, otp_app, 4000))|children]\n end\n\n if config = endpoint.config(:https) do\n {:ok, _} = Application.ensure_all_started(:ssl)\n children =\n [@handler.child_spec(:https, endpoint, default(config, otp_app, 4040))|children]\n end\n\n supervise(children, strategy: :one_for_one)\n end\n\n defp default(config, otp_app, port) do\n config =\n config\n |> Keyword.put_new(:otp_app, otp_app)\n |> Keyword.put_new(:port, port)\n\n Keyword.put(config, :port, to_port(config[:port]))\n end\n\n defp to_port(nil) do\n Logger.error \"Server can't start because :port in config is nil, please use a valid port number\"\n exit(:shutdown)\n end\n defp to_port(binary) when is_binary(binary), do: String.to_integer(binary)\n defp to_port(integer) when is_integer(integer), do: integer\n defp to_port({:system, env_var}), do: to_port(System.get_env(env_var))\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"a284806c5f4ff465ab4daa4337d5a5986aef2122","subject":"Gracefully stop the server on EOF (Ctrl+D)","message":"Gracefully stop the server on EOF (Ctrl+D)\n","repos":"Dalgona\/Serum","old_file":"lib\/serum\/dev_server\/looper.ex","new_file":"lib\/serum\/dev_server\/looper.ex","new_contents":"defmodule Serum.DevServer.Looper do\n @moduledoc \"\"\"\n A looper which accepts user inputs as server commands and processes them.\n \"\"\"\n\n import Serum.Util\n alias Serum.DevServer.Service\n\n @doc \"Starts the infinite command prompt loop.\"\n @spec looper() :: no_return()\n def looper do\n IO.write(\"#{Service.port()}> \")\n\n case IO.gets(\"\") do\n :eof ->\n run_command(\"quit\", [Service.site_dir()])\n\n command when is_binary(command) ->\n run_command(String.trim(command), [Service.site_dir()])\n looper()\n end\n end\n\n @spec run_command(binary(), list()) :: :ok | no_return()\n def run_command(command, args)\n def run_command(\"\", _), do: :ok\n\n def run_command(\"help\", _) do\n \"\"\"\n Available commands are:\n help Displays this help message\n build Rebuilds the project\n quit Stops the server and quit\n \"\"\"\n |> IO.write()\n end\n\n def run_command(\"build\", _) do\n Service.rebuild()\n end\n\n def run_command(\"quit\", [site_dir]) do\n IO.puts(\"Removing temporary directory \\\"#{site_dir}\\\"...\")\n File.rm_rf!(site_dir)\n IO.puts(\"Shutting down...\")\n System.halt(0)\n end\n\n def run_command(_, _) do\n warn(\"Type \\\"help\\\" for the list of available commands.\")\n end\nend\n","old_contents":"defmodule Serum.DevServer.Looper do\n @moduledoc \"\"\"\n A looper which accepts user inputs as server commands and processes them.\n \"\"\"\n\n import Serum.Util\n alias Serum.DevServer.Service\n\n @doc \"Starts the infinite command prompt loop.\"\n @spec looper() :: no_return()\n def looper do\n IO.write(\"#{Service.port()}> \")\n command = \"\" |> IO.gets() |> String.trim()\n\n run_command(command, [Service.site_dir()])\n looper()\n end\n\n @spec run_command(binary(), list()) :: :ok | no_return()\n def run_command(command, args)\n def run_command(\"\", _), do: :ok\n\n def run_command(\"help\", _) do\n \"\"\"\n Available commands are:\n help Displays this help message\n build Rebuilds the project\n quit Stops the server and quit\n \"\"\"\n |> IO.write()\n end\n\n def run_command(\"build\", _) do\n Service.rebuild()\n end\n\n def run_command(\"quit\", [site_dir]) do\n IO.puts(\"Removing temporary directory \\\"#{site_dir}\\\"...\")\n File.rm_rf!(site_dir)\n IO.puts(\"Shutting down...\")\n System.halt(0)\n end\n\n def run_command(_, _) do\n warn(\"Type \\\"help\\\" for the list of available commands.\")\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"40cca1a50a869555c49f019d6ea156fc9630c84b","subject":"use right variable","message":"use right variable\n","repos":"BrandNewCongress\/core,BrandNewCongress\/core,BrandNewCongress\/core","old_file":"web\/controllers\/typeform_controller.ex","new_file":"web\/controllers\/typeform_controller.ex","new_contents":"defmodule Core.TypeformController do\n use Core.Web, :controller\n\n def submit_event(conn, %{\"form_response\" => %{\"answers\" => answers, \"definition\" => definition}}) do\n questions =\n definition[\"fields\"]\n |> Enum.map(&field_name\/1)\n\n responses =\n answers\n |> Enum.map(&get_answer\/1)\n\n together = questions |> Enum.zip(responses) |> Enum.into(%{})\n\n names = String.split(together[\"host_name\"], \" \")\n first_name = List.first(names)\n last_name = if length(names) > 1 do\n List.last(names)\n else\n \"\"\n end\n\n person = %{\n email: together[\"host_email\"],\n phone: together[\"host_phone\"],\n first_name: first_name,\n last_name: last_name\n }\n\n IO.puts \"Inspecting person\"\n IO.inspect person\n\n # TODO - NB create person\n\n event = %{\n contact: %{\n name: together[\"host_name\"],\n phone: together[\"host_phone\"],\n email: together[\"host_email\"]\n },\n rsvp_form: %{\n phone: \"optional\",\n address: \"optional\",\n accept_rsvps: true,\n gather_volunteers: true,\n allow_guests: true\n },\n venue: %{\n name: together[\"venue_name\"],\n address: %{\n address1: \"venue_address\",\n city: \"venue_city\",\n state: \"venue_state\"\n }\n }\n }\n\n IO.puts \"Inspecting event\"\n IO.inspect event\n end\n\n defp field_name(%{\"title\" => \"What's your name?\"}), do: \"host_name\"\n defp field_name(%{\"title\" => \"What's your email?\"}), do: \"host_email\"\n defp field_name(%{\"title\" => \"What's your phone number?\"}), do: \"host_phone\"\n defp field_name(%{\"title\" => \"When will it be?\"}), do: \"start_time\"\n defp field_name(%{\"title\" => \"When will it start?\"}), do: \"start_time\"\n defp field_name(%{\"title\" => \"When will it end?\"}), do: \"end_time\"\n defp field_name(%{\"title\" => \"What should we call it?\"}), do: \"event_name\"\n defp field_name(%{\"title\" => \"Give us a little description...\"}), do: \"intro\"\n defp field_name(%{\"title\" => \"What is the place called?\"}), do: \"venue_name\"\n defp field_name(%{\"title\" => \"What's the address?\"}), do: \"venue_address\"\n defp field_name(%{\"title\" => \"What city is it in?\"}), do: \"venue_city\"\n defp field_name(%{\"title\" => \"What state is it in?\"}), do: \"venue_state\"\n defp field_name(%{\"title\" => \"Can we share the address of the event on our map?\"}), do: \"sharing_permission\"\n defp field_name(%{\"title\" => \"What's your zip code?\"}), do: \"venue_zip\"\n\n defp get_answer(%{\"text\" => val}), do: val\n defp get_answer(%{\"email\" => val}), do: val\n defp get_answer(%{\"date\" => val}), do: val\n defp get_answer(%{\"choice\" => %{\"label\" => val}}), do: val\n defp get_answer(%{\"boolean\" => val}), do: val\n defp get_answer(%{\"number\" => val}), do: val\n\nend\n","old_contents":"defmodule Core.TypeformController do\n use Core.Web, :controller\n\n def submit_event(conn, %{\"form_response\" => %{\"answers\" => answers, \"definition\" => definition}}) do\n questions =\n definition[\"fields\"]\n |> Enum.map(&field_name\/1)\n\n responses =\n answers\n |> Enum.map(&get_answer\/1)\n\n together = questions |> Enum.zip(answers) |> Enum.into(%{})\n\n names = String.split(together[\"host_name\"], \" \")\n first_name = List.first(names)\n last_name = if length(names) > 1 do\n List.last(names)\n else\n \"\"\n end\n\n person = %{\n email: together[\"host_email\"],\n phone: together[\"host_phone\"],\n first_name: first_name,\n last_name: last_name\n }\n\n IO.puts \"Inspecting person\"\n IO.inspect person\n\n # TODO - NB create person\n\n event = %{\n contact: %{\n name: together[\"host_name\"],\n phone: together[\"host_phone\"],\n email: together[\"host_email\"]\n },\n rsvp_form: %{\n phone: \"optional\",\n address: \"optional\",\n accept_rsvps: true,\n gather_volunteers: true,\n allow_guests: true\n },\n venue: %{\n name: together[\"venue_name\"],\n address: %{\n address1: \"venue_address\",\n city: \"venue_city\",\n state: \"venue_state\"\n }\n }\n }\n\n IO.puts \"Inspecting event\"\n IO.inspect event\n end\n\n defp field_name(%{\"title\" => \"What's your name?\"}), do: \"host_name\"\n defp field_name(%{\"title\" => \"What's your email?\"}), do: \"host_email\"\n defp field_name(%{\"title\" => \"What's your phone number?\"}), do: \"host_phone\"\n defp field_name(%{\"title\" => \"When will it be?\"}), do: \"start_time\"\n defp field_name(%{\"title\" => \"When will it start?\"}), do: \"start_time\"\n defp field_name(%{\"title\" => \"When will it end?\"}), do: \"end_time\"\n defp field_name(%{\"title\" => \"What should we call it?\"}), do: \"event_name\"\n defp field_name(%{\"title\" => \"Give us a little description...\"}), do: \"intro\"\n defp field_name(%{\"title\" => \"What is the place called?\"}), do: \"venue_name\"\n defp field_name(%{\"title\" => \"What's the address?\"}), do: \"venue_address\"\n defp field_name(%{\"title\" => \"What city is it in?\"}), do: \"venue_city\"\n defp field_name(%{\"title\" => \"What state is it in?\"}), do: \"venue_state\"\n defp field_name(%{\"title\" => \"Can we share the address of the event on our map?\"}), do: \"sharing_permission\"\n defp field_name(%{\"title\" => \"What's your zip code?\"}), do: \"venue_zip\"\n\n defp get_answer(%{\"text\" => val}), do: val\n defp get_answer(%{\"email\" => val}), do: val\n defp get_answer(%{\"date\" => val}), do: val\n defp get_answer(%{\"choice\" => %{\"label\" => val}}), do: val\n defp get_answer(%{\"boolean\" => val}), do: val\n defp get_answer(%{\"number\" => val}), do: val\n\nend\n","returncode":0,"stderr":"","license":"agpl-3.0","lang":"Elixir"} {"commit":"28eb012a9495e26198ef59a27fdc19a0337ed727","subject":"fix for Bearer login","message":"fix for Bearer login\n","repos":"LouisProulx\/test-peepchat-backend","old_file":"web\/router.ex","new_file":"web\/router.ex","new_contents":"defmodule Peepchat.Router do\n use Peepchat.Web, :router\n\n pipeline :api do\n plug :accepts, [\"json\", \"json-api\"]\n end\n\n pipeline :api_auth do\n plug :accepts, [\"json\", \"json-api\"]\n plug Guardian.Plug.VerifyHeader, realm: \"Bearer\"\n plug Guardian.Plug.LoadResource\n end\n\n scope \"\/api\", Peepchat do\n pipe_through :api\n post \"\/register\", RegistrationController, :create\n post \"\/token\", SessionController, :create, as: :login\n end\n\n scope \"\/api\", Peepchat do\n pipe_through :api_auth\n get \"\/user\/current\" ,UserController, :current\n end\nend\n","old_contents":"defmodule Peepchat.Router do\n use Peepchat.Web, :router\n\n pipeline :api do\n plug :accepts, [\"json\", \"json-api\"]\n end\n\n pipeline :api_auth do\n plug :accepts, [\"json\", \"json-api\"]\n plug Guardian.Plug.VerifyHeader\n plug Guardian.Plug.LoadResource\n end\n\n scope \"\/api\", Peepchat do\n pipe_through :api\n post \"\/register\", RegistrationController, :create\n post \"\/token\", SessionController, :create, as: :login\n end\n\n scope \"\/api\", Peepchat do\n pipe_through :api_auth\n get \"\/user\/current\" ,UserController, :current\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"e10bd3e1736ebca4942d06b05142c18e6854a97b","subject":"Reset stability timer at 28 minutes, not 1.5 seconds lol","message":"Reset stability timer at 28 minutes, not 1.5 seconds lol\n","repos":"FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os","old_file":"lib\/farmbot\/repo\/worker.ex","new_file":"lib\/farmbot\/repo\/worker.ex","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"mit","lang":"Elixir"} {"commit":"1365019c2929ca5561cdd467e0b7772b9d4802dc","subject":"Bump agent","message":"Bump agent\n","repos":"appsignal\/appsignal-elixir,appsignal\/appsignal-elixir,appsignal\/appsignal-elixir,appsignal\/appsignal-elixir","old_file":"agent.exs","new_file":"agent.exs","new_contents":"defmodule Appsignal.Agent do\n def version, do: \"c55fb2c\"\n\n def triples do\n %{\n \"x86_64-darwin\" => %{\n checksum: \"fd287b7efa38d821331d75f4a8d4dd0585f1fc01993406e2c5ebf224d13ac178\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/c55fb2c\/appsignal-x86_64-darwin-all-static.tar.gz\"\n },\n \"universal-darwin\" => %{\n checksum: \"fd287b7efa38d821331d75f4a8d4dd0585f1fc01993406e2c5ebf224d13ac178\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/c55fb2c\/appsignal-x86_64-darwin-all-static.tar.gz\"\n },\n \"i686-linux\" => %{\n checksum: \"c6c0a54524d1b4483aee03677e32969ca896d1a5561e12d9cb3e45fb5c2deeb6\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/c55fb2c\/appsignal-i686-linux-all-static.tar.gz\"\n },\n \"x86-linux\" => %{\n checksum: \"c6c0a54524d1b4483aee03677e32969ca896d1a5561e12d9cb3e45fb5c2deeb6\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/c55fb2c\/appsignal-i686-linux-all-static.tar.gz\"\n },\n \"x86_64-linux\" => %{\n checksum: \"b60e7514677a0622dbd093b75a353a547661734202dbc76c36842848f90f0461\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/c55fb2c\/appsignal-x86_64-linux-all-static.tar.gz\"\n },\n \"x86_64-linux-musl\" => %{\n checksum: \"69dd6789e1e13177e2e9827a6f1a93d7557cc66d3f4f58a843d46f6d7741eab9\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/c55fb2c\/appsignal-x86_64-linux-musl-all-static.tar.gz\"\n },\n \"x86_64-freebsd\" => %{\n checksum: \"6a669fe6a894558c83c780f32fb886f4100e1775dcfd490523420c569f315416\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/c55fb2c\/appsignal-x86_64-freebsd-all-static.tar.gz\"\n },\n \"amd64-freebsd\" => %{\n checksum: \"6a669fe6a894558c83c780f32fb886f4100e1775dcfd490523420c569f315416\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/c55fb2c\/appsignal-x86_64-freebsd-all-static.tar.gz\"\n },\n }\n end\nend\n","old_contents":"defmodule Appsignal.Agent do\n def version, do: \"f9d2b57\"\n\n def triples do\n %{\n \"x86_64-darwin\" => %{\n checksum: \"96b144b211525c83e29dc4c337f4addee3f168ffd82de7256f551d30c538445c\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/f9d2b57\/appsignal-x86_64-darwin-all-static.tar.gz\"\n },\n \"universal-darwin\" => %{\n checksum: \"96b144b211525c83e29dc4c337f4addee3f168ffd82de7256f551d30c538445c\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/f9d2b57\/appsignal-x86_64-darwin-all-static.tar.gz\"\n },\n \"i686-linux\" => %{\n checksum: \"0f58d7ab6c430c42d4b2b6ca31a029654a79022f4752f053364e9862efcce43f\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/f9d2b57\/appsignal-i686-linux-all-static.tar.gz\"\n },\n \"x86-linux\" => %{\n checksum: \"0f58d7ab6c430c42d4b2b6ca31a029654a79022f4752f053364e9862efcce43f\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/f9d2b57\/appsignal-i686-linux-all-static.tar.gz\"\n },\n \"x86_64-linux\" => %{\n checksum: \"131d8eac0bb9b0640f670834b136fbea581d9f96a31299e18ca4b7450a95df6d\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/f9d2b57\/appsignal-x86_64-linux-all-static.tar.gz\"\n },\n \"x86_64-linux-musl\" => %{\n checksum: \"c8f5e866b7c9786fc24e198125e71239ef0cffe829dcda9a40c8aab5205db3d0\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/f9d2b57\/appsignal-x86_64-linux-musl-all-static.tar.gz\"\n },\n \"x86_64-freebsd\" => %{\n checksum: \"9c30322a2685ac246380cc4dab6e24b2fd3d7a42fffaf12c901e2c2a9e7bc741\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/f9d2b57\/appsignal-x86_64-freebsd-all-static.tar.gz\"\n },\n \"amd64-freebsd\" => %{\n checksum: \"9c30322a2685ac246380cc4dab6e24b2fd3d7a42fffaf12c901e2c2a9e7bc741\",\n download_url: \"https:\/\/appsignal-agent-releases.global.ssl.fastly.net\/f9d2b57\/appsignal-x86_64-freebsd-all-static.tar.gz\"\n },\n }\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"95f996afe81375390a7efd5abfea013effabdccd","subject":"process: fix a code of supervisor","message":"process: fix a code of supervisor\n","repos":"mrk21\/study_elixir,mrk21\/study_elixir,mrk21\/study_elixir","old_file":"process\/main.exs","new_file":"process\/main.exs","new_contents":"IO.puts \"## Base\"\nsend self(), {:hello, \"world\"}\n\nIO.inspect(receive do\n {:hello, msg} -> msg\n {:world, _} -> \"won't match\"\nend)\nIO.puts \"\"\n\n\nIO.puts \"## Config Process\"\ndefmodule KV do\n def start_link do\n {:ok, spawn_link(fn -> loop(%{}) end)}\n end\n \n defp loop(map) do\n receive do\n {:get, key, caller} ->\n send caller, Map.get(map, key)\n loop(map)\n {:put, key, value} ->\n loop(Map.put(map, key, value))\n end\n end\nend\n\nIO.inspect {:ok, pid} = KV.start_link\nIO.inspect send pid, {:put, :hello, :world}\nIO.inspect send pid, {:get, :hello, self()}\n\nreceive do\n value -> IO.inspect value\nend\nIO.puts \"\"\n\n\nIO.puts \"## OTP: GenServer\"\ndefmodule KV2 do\n use GenServer\n \n def start_link do\n GenServer.start_link(__MODULE__, %{})\n end\n \n def get(pid, key) do\n GenServer.call(pid, {:get, key})\n end\n \n def put(pid, key, value) do\n GenServer.call(pid, {:put, key, value})\n end\n \n def handle_call({:get, key}, _from, state) do\n {:reply, Map.get(state, key), state}\n end\n \n def handle_call({:put, key, value}, _from, state) do\n {:reply, value, Map.put(state, key, value)}\n end\nend\nIO.inspect {:ok, pid} = KV2.start_link\nIO.inspect KV2.get(pid, :a)\nIO.inspect KV2.put(pid, :a, 1)\nIO.inspect KV2.get(pid, :a)\nIO.puts \"\"\n\n\nIO.puts \"## OTP: Agent\"\ndefmodule KV3 do\n def start_link do\n Agent.start_link fn -> %{} end\n end\n \n def get(pid, key) do\n Agent.get pid, fn (map) -> Map.get(map, key) end\n end\n \n def put(pid, key, value) do\n Agent.update pid, fn (map) -> Map.put(map, key, value) end\n end\nend\n\nIO.inspect {:ok, pid} = KV3.start_link\nIO.inspect KV3.get(pid, :a)\nIO.inspect KV3.put(pid, :a, 1)\nIO.inspect KV3.get(pid, :a)\nIO.puts \"\"\n\n\nIO.puts \"## OTP: Task\"\ndefmodule TaskModule do\n def parallel do\n [\n fn -> :timer.sleep(200); IO.puts 1 end,\n fn -> :timer.sleep(400); IO.puts 2 end,\n fn -> :timer.sleep(600); IO.puts 3 end,\n fn -> :timer.sleep(800); IO.puts 4 end\n ]\n |> Enum.map(&Task.async\/1)\n |> Enum.map(&Task.await\/1)\n end\nend\nTaskModule.parallel()\nIO.puts \"\"\n\n\nIO.puts \"## Process.monitor\"\npid = spawn fn ->\n :timer.sleep(100)\n raise RuntimeError\nend\nProcess.monitor pid\n\nreceive do\n {:DOWN, ref, :process, pid, msg} ->\n IO.inspect ref\n IO.inspect pid\n IO.inspect msg\nend\nIO.puts \"\"\n\n\nIO.puts \"## OTP: Process.link\"\npid = spawn fn ->\n pid = spawn fn ->\n :timer.sleep(500)\n raise RuntimeError\n end\n Process.link pid\n IO.puts \"start to link with other process\"\n :timer.sleep(2000)\n IO.puts \"never display this message\"\nend\nProcess.monitor pid\nIO.puts \"start the linking process\"\nIO.inspect pid\n\nreceive do\n {:DOWN, ref, :process, pid, msg} ->\n IO.puts \"killed the linking process\"\n IO.inspect pid\n IO.inspect msg\nend\nIO.puts \"\"\n\n\nIO.puts \"## OTP: spawn_link\"\npid = spawn fn ->\n pid = spawn_link fn ->\n :timer.sleep(500)\n raise RuntimeError\n end\n IO.puts \"start to link with other process\"\n :timer.sleep(2000)\n IO.puts \"never display this message\"\nend\nProcess.monitor pid\nIO.puts \"start the linking process\"\nIO.inspect pid\n\nreceive do\n {:DOWN, ref, :process, pid, msg} ->\n IO.puts \"killed the linking process\"\n IO.inspect pid\n IO.inspect msg\nend\nIO.puts \"\"\n\n\nIO.puts \"## OTP: Supervisor\"\ndefmodule Echo.Server do\n use GenServer\n \n def start_link do\n GenServer.start_link(__MODULE__, [], name: __MODULE__)\n end\n \n def crash! do\n GenServer.cast(__MODULE__, :crash)\n end\n \n def handle_cast(:crash, _) do\n raise RuntimeError, message: \"Opps!\"\n end\n \n def echo(term) do\n GenServer.call(__MODULE__, {:echo, term})\n end\n \n def handle_call({:echo, str}, _, s) do\n {:reply, str, s}\n end\nend\n\ndefmodule SupervisorTest do\n def run do\n import Supervisor.Spec, warn: false\n \n children = [worker(Echo.Server, [])]\n opts = [\n strategy: :one_for_one,\n name: Echo.Supervisor\n ]\n IO.inspect {:ok, pid} = Supervisor.start_link(children, opts)\n IO.inspect Echo.Server.echo \"hey\"\n IO.inspect Echo.Server.crash!\n :timer.sleep(100)\n IO.inspect Echo.Server.echo \"foo\"\n end\nend\nspawn fn ->\n SupervisorTest.run\nend\n:timer.sleep(300)\n\n\nIO.puts \"### ModuleBased Supervisor\"\ndefmodule Echo.Supervisor do\n use Supervisor\n \n def start_link do\n Supervisor.start_link(__MODULE__, [])\n end\n \n def init([]) do\n children = [\n worker(Echo.Server, [])\n ]\n opts = [\n strategy: :one_for_one,\n name: Echo.Supervisor\n ]\n supervise(children, opts)\n end\nend\n\ndefmodule ModuleBasedSupervisorTest do\n def run do\n IO.inspect {:ok, pid} = Echo.Supervisor.start_link()\n IO.inspect Echo.Server.echo \"hey\"\n IO.inspect Echo.Server.crash!\n :timer.sleep(100)\n IO.inspect Echo.Server.echo \"foo\"\n end\nend\nspawn fn ->\n ModuleBasedSupervisorTest.run()\nend\n:timer.sleep(300)\nIO.puts \"\"\n","old_contents":"IO.puts \"## Base\"\nsend self(), {:hello, \"world\"}\n\nIO.inspect(receive do\n {:hello, msg} -> msg\n {:world, _} -> \"won't match\"\nend)\nIO.puts \"\"\n\n\nIO.puts \"## Config Process\"\ndefmodule KV do\n def start_link do\n {:ok, spawn_link(fn -> loop(%{}) end)}\n end\n \n defp loop(map) do\n receive do\n {:get, key, caller} ->\n send caller, Map.get(map, key)\n loop(map)\n {:put, key, value} ->\n loop(Map.put(map, key, value))\n end\n end\nend\n\nIO.inspect {:ok, pid} = KV.start_link\nIO.inspect send pid, {:put, :hello, :world}\nIO.inspect send pid, {:get, :hello, self()}\n\nreceive do\n value -> IO.inspect value\nend\nIO.puts \"\"\n\n\nIO.puts \"## OTP: GenServer\"\ndefmodule KV2 do\n use GenServer\n \n def start_link do\n GenServer.start_link(__MODULE__, %{})\n end\n \n def get(pid, key) do\n GenServer.call(pid, {:get, key})\n end\n \n def put(pid, key, value) do\n GenServer.call(pid, {:put, key, value})\n end\n \n def handle_call({:get, key}, _from, state) do\n {:reply, Map.get(state, key), state}\n end\n \n def handle_call({:put, key, value}, _from, state) do\n {:reply, value, Map.put(state, key, value)}\n end\nend\nIO.inspect {:ok, pid} = KV2.start_link\nIO.inspect KV2.get(pid, :a)\nIO.inspect KV2.put(pid, :a, 1)\nIO.inspect KV2.get(pid, :a)\nIO.puts \"\"\n\n\nIO.puts \"## OTP: Agent\"\ndefmodule KV3 do\n def start_link do\n Agent.start_link fn -> %{} end\n end\n \n def get(pid, key) do\n Agent.get pid, fn (map) -> Map.get(map, key) end\n end\n \n def put(pid, key, value) do\n Agent.update pid, fn (map) -> Map.put(map, key, value) end\n end\nend\n\nIO.inspect {:ok, pid} = KV3.start_link\nIO.inspect KV3.get(pid, :a)\nIO.inspect KV3.put(pid, :a, 1)\nIO.inspect KV3.get(pid, :a)\nIO.puts \"\"\n\n\nIO.puts \"## OTP: Task\"\ndefmodule TaskModule do\n def parallel do\n [\n fn -> :timer.sleep(200); IO.puts 1 end,\n fn -> :timer.sleep(400); IO.puts 2 end,\n fn -> :timer.sleep(600); IO.puts 3 end,\n fn -> :timer.sleep(800); IO.puts 4 end\n ]\n |> Enum.map(&Task.async\/1)\n |> Enum.map(&Task.await\/1)\n end\nend\nTaskModule.parallel()\nIO.puts \"\"\n\n\nIO.puts \"## Process.monitor\"\npid = spawn fn ->\n :timer.sleep(100)\n raise RuntimeError\nend\nProcess.monitor pid\n\nreceive do\n {:DOWN, ref, :process, pid, msg} ->\n IO.inspect ref\n IO.inspect pid\n IO.inspect msg\nend\nIO.puts \"\"\n\n\nIO.puts \"## OTP: Process.link\"\npid = spawn fn ->\n pid = spawn fn ->\n :timer.sleep(500)\n raise RuntimeError\n end\n Process.link pid\n IO.puts \"start to link with other process\"\n :timer.sleep(2000)\n IO.puts \"never display this message\"\nend\nProcess.monitor pid\nIO.puts \"start the linking process\"\nIO.inspect pid\n\nreceive do\n {:DOWN, ref, :process, pid, msg} ->\n IO.puts \"killed the linking process\"\n IO.inspect pid\n IO.inspect msg\nend\nIO.puts \"\"\n\n\nIO.puts \"## OTP: spawn_link\"\npid = spawn fn ->\n pid = spawn_link fn ->\n :timer.sleep(500)\n raise RuntimeError\n end\n IO.puts \"start to link with other process\"\n :timer.sleep(2000)\n IO.puts \"never display this message\"\nend\nProcess.monitor pid\nIO.puts \"start the linking process\"\nIO.inspect pid\n\nreceive do\n {:DOWN, ref, :process, pid, msg} ->\n IO.puts \"killed the linking process\"\n IO.inspect pid\n IO.inspect msg\nend\nIO.puts \"\"\n\n\nIO.puts \"## OTP: Supervisor\"\ndefmodule Echo.Server do\n use GenServer\n \n def start_link do\n GenServer.start_link(__MODULE__, [], name: __MODULE__)\n end\n \n def crash! do\n GenServer.cast(__MODULE__, :crash)\n end\n \n def handle_cast(:crash, _) do\n raise RuntimeError, message: \"Opps!\"\n end\n \n def echo(term) do\n GenServer.call(__MODULE__, {:echo, term})\n end\n \n def handle_call({:echo, str}, _, s) do\n {:reply, str, s}\n end\nend\n\ndefmodule SupervisorTest do\n def run do\n import Supervisor.Spec, warn: false\n \n children = [worker(Echo.Server, [])]\n opts = [\n strategy: :one_for_one,\n name: Echo.Supervisor\n ]\n IO.inspect {:ok, pid} = Supervisor.start_link(children, opts)\n IO.inspect Echo.Server.echo \"hey\"\n IO.inspect Echo.Server.crash!\n :timer.sleep(1000)\n IO.inspect Echo.Server.echo \"foo\"\n end\nend\n# SupervisorTest.run\n\nIO.puts \"### ModuleBased Supervisor\"\ndefmodule Echo.Supervisor do\n use Supervisor\n \n def start_link do\n Supervisor.start_link(__MODULE__, [])\n end\n \n def init([]) do\n children = [\n worker(Echo.Server, [])\n ]\n opts = [\n strategy: :one_for_one,\n name: Echo.Supervisor\n ]\n supervise(children, opts)\n end\nend\n\ndefmodule ModuleBasedSupervisorTest do\n def run do\n IO.inspect {:ok, pid} = Echo.Supervisor.start_link()\n IO.inspect Echo.Server.echo \"hey\"\n IO.inspect Echo.Server.crash!\n :timer.sleep(1000)\n IO.inspect Echo.Server.echo \"foo\"\n end\nend\nModuleBasedSupervisorTest.run()\nIO.puts \"\"\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"ecca080c661a5bcede625ea747ffa666032d47f2","subject":"Increment version [ci skip]","message":"Increment version [ci skip]\n","repos":"edenlabllc\/ehealth.api,edenlabllc\/ehealth.api","old_file":"mix.exs","new_file":"mix.exs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"apache-2.0","lang":"Elixir"} {"commit":"3a1e915879cf69b09b403fa005b6e4c1d3bdcd14","subject":"Release 0.3.2","message":"Release 0.3.2\n","repos":"IoraHealth\/braise","old_file":"mix.exs","new_file":"mix.exs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"mit","lang":"Elixir"} {"commit":"cf4df15709c0a0c12e7d30ccc20e9135fb8407a4","subject":"v0.5.1","message":"v0.5.1\n","repos":"jj1bdx\/plug_static_ls","old_file":"mix.exs","new_file":"mix.exs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"apache-2.0","lang":"Elixir"} {"commit":"570877235b6490fc440d97aa428ee786174b66e7","subject":"Requires newer version","message":"Requires newer version\n","repos":"olafura\/json_diff_ex,olafura\/json_diff_ex","old_file":"mix.exs","new_file":"mix.exs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"apache-2.0","lang":"Elixir"} {"commit":"747ee296d20a7aa72b718fe646ae5f5208219cfb","subject":"Fix documentation generation config","message":"Fix documentation generation config","repos":"asaaki\/cmark.ex,asaaki\/cmark.ex","old_file":"mix.exs","new_file":"mix.exs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"mit","lang":"Elixir"} {"commit":"c705c2b4bc49ce9dee20b808a40f71eaf1640967","subject":"bump version","message":"bump version\n","repos":"exterm\/scripture,exterm\/scripture","old_file":"mix.exs","new_file":"mix.exs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"mit","lang":"Elixir"} {"commit":"ac44b7a77a042be3ffbf2561c10b81828a06c509","subject":"Version bumpup","message":"Version bumpup\n","repos":"savonarola\/smppex","old_file":"mix.exs","new_file":"mix.exs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"mit","lang":"Elixir"} {"commit":"1c0fca8227da642943c56d54df3fddf78aef4448","subject":"Increment version [ci skip]","message":"Increment version [ci skip]\n","repos":"edenlabllc\/ehealth.api,edenlabllc\/ehealth.api","old_file":"mix.exs","new_file":"mix.exs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"apache-2.0","lang":"Elixir"} {"commit":"324efe522b9101a10ad0365a448ad8e94ac4d919","subject":"version bump","message":"version bump","repos":"izelnakri\/paper_trail","old_file":"mix.exs","new_file":"mix.exs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"mit","lang":"Elixir"} {"commit":"2e75bc98a4fe5b8c23ed6390b85f448e157a9703","subject":"Add ex_doc deps","message":"Add ex_doc deps\n","repos":"ricn\/rapport","old_file":"mix.exs","new_file":"mix.exs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"mit","lang":"Elixir"} {"commit":"29bf127e2c8938b57f2a951e309048646ea3242d","subject":"Increment version [ci skip]","message":"Increment version [ci skip]\n","repos":"edenlabllc\/ehealth.api,edenlabllc\/ehealth.api","old_file":"mix.exs","new_file":"mix.exs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"apache-2.0","lang":"Elixir"} {"commit":"18c2e25e66b60ab49ea4db07f3504b1e3e1353f1","subject":"Upgrade to a newer version of elixir-oauth2","message":"Upgrade to a newer version of elixir-oauth2\n\nThe local fork will be abandoned once this fix lands:\n\nhttps:\/\/github.com\/scrogson\/oauth2\/pull\/89\n","repos":"bors-ng\/bors-ng,bors-ng\/bors-ng,bors-ng\/bors-ng","old_file":"mix.exs","new_file":"mix.exs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"apache-2.0","lang":"Elixir"} {"commit":"9333195caa3e08a0404e99a34989b11380843e1f","subject":"Releases 0.2.1","message":"Releases 0.2.1\n","repos":"sproutapp\/pavlov","old_file":"mix.exs","new_file":"mix.exs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"mit","lang":"Elixir"} {"commit":"f9919d61268286a6d7dd644e5342f251740b0795","subject":"Update gen_smtp to 0.15","message":"Update gen_smtp to 0.15\n","repos":"kamilc\/mailman","old_file":"mix.exs","new_file":"mix.exs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"mit","lang":"Elixir"} {"commit":"7a977307c2eb41f65c3296fa8f75b4fa5d20f488","subject":"URI.decode_query returns a map, not a HashDict","message":"URI.decode_query returns a map, not a HashDict","repos":"kimshrier\/elixir,pedrosnk\/elixir,ggcampinho\/elixir,antipax\/elixir,gfvcastro\/elixir,kelvinst\/elixir,elixir-lang\/elixir,gfvcastro\/elixir,joshprice\/elixir,lexmag\/elixir,beedub\/elixir,beedub\/elixir,michalmuskala\/elixir,antipax\/elixir,lexmag\/elixir,ggcampinho\/elixir,kimshrier\/elixir,pedrosnk\/elixir,kelvinst\/elixir","old_file":"lib\/elixir\/lib\/uri.ex","new_file":"lib\/elixir\/lib\/uri.ex","new_contents":"defmodule URI do\n @moduledoc \"\"\"\n Utilities for working with and creating URIs.\n \"\"\"\n\n defstruct scheme: nil, path: nil, query: nil,\n fragment: nil, authority: nil,\n userinfo: nil, host: nil, port: nil\n\n import Bitwise\n\n @ports %{\n \"ftp\" => 21,\n \"http\" => 80,\n \"https\" => 443,\n \"ldap\" => 389,\n \"sftp\" => 22,\n \"tftp\" => 69,\n }\n\n Enum.each @ports, fn {scheme, port} ->\n def normalize_scheme(unquote(scheme)), do: unquote(scheme)\n def default_port(unquote(scheme)), do: unquote(port)\n end\n\n @doc \"\"\"\n Normalizes the scheme according to the spec by downcasing it.\n \"\"\"\n def normalize_scheme(nil), do: nil\n def normalize_scheme(scheme), do: String.downcase(scheme)\n\n @doc \"\"\"\n Returns the default port for a given scheme.\n\n If the scheme is unknown to URI, returns `nil`.\n Any scheme may be registered via `default_port\/2`.\n\n ## Examples\n\n iex> URI.default_port(\"ftp\")\n 21\n\n iex> URI.default_port(\"ponzi\")\n nil\n\n \"\"\"\n def default_port(scheme) when is_binary(scheme) do\n {:ok, dict} = Application.fetch_env(:elixir, :uri)\n Map.get(dict, scheme)\n end\n\n @doc \"\"\"\n Registers a scheme with a default port.\n\n It is recommended for this function to be invoked in your\n application start callback in case you want to register\n new URIs.\n \"\"\"\n def default_port(scheme, port) when is_binary(scheme) and port > 0 do\n {:ok, dict} = Application.fetch_env(:elixir, :uri)\n Application.put_env(:elixir, :uri, Map.put(dict, scheme, port), persist: true)\n end\n\n @doc \"\"\"\n Encodes an enumerable into a query string.\n\n Takes an enumerable (containing a sequence of two-item tuples)\n and returns a string of the form \"key1=value1&key2=value2...\" where\n keys and values are URL encoded as per `encode\/1`.\n\n Keys and values can be any term that implements the `String.Chars`\n protocol, except lists which are explicitly forbidden.\n\n ## Examples\n\n iex> hd = %{\"foo\" => 1, \"bar\" => 2}\n iex> URI.encode_query(hd)\n \"bar=2&foo=1\"\n\n \"\"\"\n def encode_query(l), do: Enum.map_join(l, \"&\", &pair\/1)\n\n @doc \"\"\"\n Decodes a query string into a dictionary (by default uses a map).\n\n Given a query string of the form \"key1=value1&key2=value2...\", produces a\n map with one entry for each key-value pair. Each key and value will be a\n binary. Keys and values will be percent-unescaped.\n\n Use `query_decoder\/1` if you want to iterate over each value manually.\n\n ## Examples\n\n iex> URI.decode_query(\"foo=1&bar=2\")\n %{\"bar\" => \"2\", \"foo\" => \"1\"}\n\n \"\"\"\n def decode_query(q, dict \\\\ %{}) when is_binary(q) do\n Enum.reduce query_decoder(q), dict, fn({k, v}, acc) -> Dict.put(acc, k, v) end\n end\n\n @doc \"\"\"\n Returns an iterator function over the query string that decodes\n the query string in steps.\n\n ## Examples\n\n iex> URI.query_decoder(\"foo=1&bar=2\") |> Enum.map &(&1)\n [{\"foo\", \"1\"}, {\"bar\", \"2\"}]\n\n \"\"\"\n def query_decoder(q) when is_binary(q) do\n Stream.unfold(q, &do_decoder\/1)\n end\n\n defp do_decoder(\"\") do\n nil\n end\n\n defp do_decoder(q) do\n {first, next} =\n case :binary.split(q, \"&\") do\n [first, rest] -> {first, rest}\n [first] -> {first, \"\"}\n end\n\n current =\n case :binary.split(first, \"=\") do\n [ key, value ] -> {decode(key), decode(value)}\n [ key ] -> {decode(key), nil}\n end\n\n {current, next}\n end\n\n defp pair({k, _}) when is_list(k) do\n raise ArgumentError, message: \"encode_query\/1 keys cannot be lists, got: #{inspect k}\"\n end\n\n defp pair({_, v}) when is_list(v) do\n raise ArgumentError, message: \"encode_query\/1 values cannot be lists, got: #{inspect v}\"\n end\n\n defp pair({k, v}) do\n encode(to_string(k)) <> \"=\" <> encode(to_string(v))\n end\n\n @doc \"\"\"\n Percent-escape a URI.\n\n ## Example\n\n iex> URI.encode(\"http:\/\/elixir-lang.org\/getting_started\/2.html\")\n \"http%3A%2F%2Felixir-lang.org%2Fgetting_started%2F2.html\"\n\n \"\"\"\n def encode(s), do: for(<>, into: \"\", do: percent(c))\n\n defp percent(32), do: <>\n defp percent(?-), do: <>\n defp percent(?_), do: <>\n defp percent(?.), do: <>\n\n defp percent(c)\n when c >= ?0 and c <= ?9\n when c >= ?a and c <= ?z\n when c >= ?A and c <= ?Z do\n <>\n end\n\n defp percent(c), do: \"%\" <> hex(bsr(c, 4)) <> hex(band(c, 15))\n\n defp hex(n) when n <= 9, do: <>\n defp hex(n), do: <>\n\n @doc \"\"\"\n Percent-unescape a URI.\n\n ## Examples\n\n iex> URI.decode(\"http%3A%2F%2Felixir-lang.org\")\n \"http:\/\/elixir-lang.org\"\n\n \"\"\"\n def decode(uri) do\n decode(uri, uri)\n end\n\n def decode(<>, uri) do\n << bsl(hex2dec(hex1, uri), 4) + hex2dec(hex2, uri) >> <> decode(tail, uri)\n end\n\n def decode(<>, uri) do\n <> <> decode(tail, uri)\n end\n\n def decode(<<>>, _uri), do: <<>>\n\n defp hex2dec(n, _uri) when n in ?A..?F, do: n - ?A + 10\n defp hex2dec(n, _uri) when n in ?a..?f, do: n - ?a + 10\n defp hex2dec(n, _uri) when n in ?0..?9, do: n - ?0\n defp hex2dec(_n, uri) do\n raise ArgumentError, message: \"malformed URI #{inspect uri}\"\n end\n\n defp check_plus(?+), do: 32\n defp check_plus(c), do: c\n\n @doc \"\"\"\n Parses a URI into components.\n\n URIs have portions that are handled specially for the particular\n scheme of the URI. For example, http and https have different\n default ports. Such values can be accessed and registered via\n `URI.default_port\/1` and `URI.default_port\/2`.\n\n ## Examples\n\n iex> URI.parse(\"http:\/\/elixir-lang.org\/\")\n %URI{scheme: \"http\", path: \"\/\", query: nil, fragment: nil,\n authority: \"elixir-lang.org\", userinfo: nil,\n host: \"elixir-lang.org\", port: 80}\n\n \"\"\"\n def parse(s) when is_binary(s) do\n # From http:\/\/tools.ietf.org\/html\/rfc3986#appendix-B\n regex = ~r\/^(([^:\\\/?#]+):)?(\\\/\\\/([^\\\/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?\/\n parts = nillify(Regex.run(regex, s))\n\n destructure [_, _, scheme, _, authority, path, _, query, _, fragment], parts\n {userinfo, host, port} = split_authority(authority)\n\n if authority do\n authority = \"\"\n\n if userinfo, do: authority = authority <> userinfo <> \"@\"\n if host, do: authority = authority <> host\n if port, do: authority = authority <> \":\" <> integer_to_binary(port)\n end\n\n scheme = normalize_scheme(scheme)\n\n if nil?(port) and not nil?(scheme) do\n port = default_port(scheme)\n end\n\n %URI{\n scheme: scheme, path: path, query: query,\n fragment: fragment, authority: authority,\n userinfo: userinfo, host: host, port: port\n }\n end\n\n # Split an authority into its userinfo, host and port parts.\n defp split_authority(s) do\n s = s || \"\"\n components = Regex.run ~r\/(^(.*)@)?(\\[[a-zA-Z0-9:.]*\\]|[^:]*)(:(\\d*))?\/, s\n\n destructure [_, _, userinfo, host, _, port], nillify(components)\n port = if port, do: binary_to_integer(port)\n host = if host, do: host |> String.lstrip(?[) |> String.rstrip(?])\n\n {userinfo, host, port}\n end\n\n # Regex.run returns empty strings sometimes. We want\n # to replace those with nil for consistency.\n defp nillify(l) do\n for s <- l do\n if size(s) > 0, do: s, else: nil\n end\n end\nend\n\ndefimpl String.Chars, for: URI do\n def to_string(uri) do\n scheme = uri.scheme\n\n if scheme && (port = URI.default_port(scheme)) do\n if uri.port == port, do: uri = %{uri | port: nil}\n end\n\n result = \"\"\n\n if uri.scheme, do: result = result <> uri.scheme <> \":\/\/\"\n if uri.userinfo, do: result = result <> uri.userinfo <> \"@\"\n if uri.host, do: result = result <> uri.host\n if uri.port, do: result = result <> \":\" <> integer_to_binary(uri.port)\n if uri.path, do: result = result <> uri.path\n if uri.query, do: result = result <> \"?\" <> uri.query\n if uri.fragment, do: result = result <> \"#\" <> uri.fragment\n\n result\n end\nend\n","old_contents":"defmodule URI do\n @moduledoc \"\"\"\n Utilities for working with and creating URIs.\n \"\"\"\n\n defstruct scheme: nil, path: nil, query: nil,\n fragment: nil, authority: nil,\n userinfo: nil, host: nil, port: nil\n\n import Bitwise\n\n @ports %{\n \"ftp\" => 21,\n \"http\" => 80,\n \"https\" => 443,\n \"ldap\" => 389,\n \"sftp\" => 22,\n \"tftp\" => 69,\n }\n\n Enum.each @ports, fn {scheme, port} ->\n def normalize_scheme(unquote(scheme)), do: unquote(scheme)\n def default_port(unquote(scheme)), do: unquote(port)\n end\n\n @doc \"\"\"\n Normalizes the scheme according to the spec by downcasing it.\n \"\"\"\n def normalize_scheme(nil), do: nil\n def normalize_scheme(scheme), do: String.downcase(scheme)\n\n @doc \"\"\"\n Returns the default port for a given scheme.\n\n If the scheme is unknown to URI, returns `nil`.\n Any scheme may be registered via `default_port\/2`.\n\n ## Examples\n\n iex> URI.default_port(\"ftp\")\n 21\n\n iex> URI.default_port(\"ponzi\")\n nil\n\n \"\"\"\n def default_port(scheme) when is_binary(scheme) do\n {:ok, dict} = Application.fetch_env(:elixir, :uri)\n Map.get(dict, scheme)\n end\n\n @doc \"\"\"\n Registers a scheme with a default port.\n\n It is recommended for this function to be invoked in your\n application start callback in case you want to register\n new URIs.\n \"\"\"\n def default_port(scheme, port) when is_binary(scheme) and port > 0 do\n {:ok, dict} = Application.fetch_env(:elixir, :uri)\n Application.put_env(:elixir, :uri, Map.put(dict, scheme, port), persist: true)\n end\n\n @doc \"\"\"\n Encodes an enumerable into a query string.\n\n Takes an enumerable (containing a sequence of two-item tuples)\n and returns a string of the form \"key1=value1&key2=value2...\" where\n keys and values are URL encoded as per `encode\/1`.\n\n Keys and values can be any term that implements the `String.Chars`\n protocol, except lists which are explicitly forbidden.\n\n ## Examples\n\n iex> hd = %{\"foo\" => 1, \"bar\" => 2}\n iex> URI.encode_query(hd)\n \"bar=2&foo=1\"\n\n \"\"\"\n def encode_query(l), do: Enum.map_join(l, \"&\", &pair\/1)\n\n @doc \"\"\"\n Decodes a query string into a dictionary (by default uses a map).\n\n Given a query string of the form \"key1=value1&key2=value2...\", produces a\n `HashDict` with one entry for each key-value pair. Each key and value will be a\n binary. Keys and values will be percent-unescaped.\n\n Use `query_decoder\/1` if you want to iterate over each value manually.\n\n ## Examples\n\n iex> URI.decode_query(\"foo=1&bar=2\")\n %{\"bar\" => \"2\", \"foo\" => \"1\"}\n\n \"\"\"\n def decode_query(q, dict \\\\ %{}) when is_binary(q) do\n Enum.reduce query_decoder(q), dict, fn({k, v}, acc) -> Dict.put(acc, k, v) end\n end\n\n @doc \"\"\"\n Returns an iterator function over the query string that decodes\n the query string in steps.\n\n ## Examples\n\n iex> URI.query_decoder(\"foo=1&bar=2\") |> Enum.map &(&1)\n [{\"foo\", \"1\"}, {\"bar\", \"2\"}]\n\n \"\"\"\n def query_decoder(q) when is_binary(q) do\n Stream.unfold(q, &do_decoder\/1)\n end\n\n defp do_decoder(\"\") do\n nil\n end\n\n defp do_decoder(q) do\n {first, next} =\n case :binary.split(q, \"&\") do\n [first, rest] -> {first, rest}\n [first] -> {first, \"\"}\n end\n\n current =\n case :binary.split(first, \"=\") do\n [ key, value ] -> {decode(key), decode(value)}\n [ key ] -> {decode(key), nil}\n end\n\n {current, next}\n end\n\n defp pair({k, _}) when is_list(k) do\n raise ArgumentError, message: \"encode_query\/1 keys cannot be lists, got: #{inspect k}\"\n end\n\n defp pair({_, v}) when is_list(v) do\n raise ArgumentError, message: \"encode_query\/1 values cannot be lists, got: #{inspect v}\"\n end\n\n defp pair({k, v}) do\n encode(to_string(k)) <> \"=\" <> encode(to_string(v))\n end\n\n @doc \"\"\"\n Percent-escape a URI.\n\n ## Example\n\n iex> URI.encode(\"http:\/\/elixir-lang.org\/getting_started\/2.html\")\n \"http%3A%2F%2Felixir-lang.org%2Fgetting_started%2F2.html\"\n\n \"\"\"\n def encode(s), do: for(<>, into: \"\", do: percent(c))\n\n defp percent(32), do: <>\n defp percent(?-), do: <>\n defp percent(?_), do: <>\n defp percent(?.), do: <>\n\n defp percent(c)\n when c >= ?0 and c <= ?9\n when c >= ?a and c <= ?z\n when c >= ?A and c <= ?Z do\n <>\n end\n\n defp percent(c), do: \"%\" <> hex(bsr(c, 4)) <> hex(band(c, 15))\n\n defp hex(n) when n <= 9, do: <>\n defp hex(n), do: <>\n\n @doc \"\"\"\n Percent-unescape a URI.\n\n ## Examples\n\n iex> URI.decode(\"http%3A%2F%2Felixir-lang.org\")\n \"http:\/\/elixir-lang.org\"\n\n \"\"\"\n def decode(uri) do\n decode(uri, uri)\n end\n\n def decode(<>, uri) do\n << bsl(hex2dec(hex1, uri), 4) + hex2dec(hex2, uri) >> <> decode(tail, uri)\n end\n\n def decode(<>, uri) do\n <> <> decode(tail, uri)\n end\n\n def decode(<<>>, _uri), do: <<>>\n\n defp hex2dec(n, _uri) when n in ?A..?F, do: n - ?A + 10\n defp hex2dec(n, _uri) when n in ?a..?f, do: n - ?a + 10\n defp hex2dec(n, _uri) when n in ?0..?9, do: n - ?0\n defp hex2dec(_n, uri) do\n raise ArgumentError, message: \"malformed URI #{inspect uri}\"\n end\n\n defp check_plus(?+), do: 32\n defp check_plus(c), do: c\n\n @doc \"\"\"\n Parses a URI into components.\n\n URIs have portions that are handled specially for the particular\n scheme of the URI. For example, http and https have different\n default ports. Such values can be accessed and registered via\n `URI.default_port\/1` and `URI.default_port\/2`.\n\n ## Examples\n\n iex> URI.parse(\"http:\/\/elixir-lang.org\/\")\n %URI{scheme: \"http\", path: \"\/\", query: nil, fragment: nil,\n authority: \"elixir-lang.org\", userinfo: nil,\n host: \"elixir-lang.org\", port: 80}\n\n \"\"\"\n def parse(s) when is_binary(s) do\n # From http:\/\/tools.ietf.org\/html\/rfc3986#appendix-B\n regex = ~r\/^(([^:\\\/?#]+):)?(\\\/\\\/([^\\\/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?\/\n parts = nillify(Regex.run(regex, s))\n\n destructure [_, _, scheme, _, authority, path, _, query, _, fragment], parts\n {userinfo, host, port} = split_authority(authority)\n\n if authority do\n authority = \"\"\n\n if userinfo, do: authority = authority <> userinfo <> \"@\"\n if host, do: authority = authority <> host\n if port, do: authority = authority <> \":\" <> integer_to_binary(port)\n end\n\n scheme = normalize_scheme(scheme)\n\n if nil?(port) and not nil?(scheme) do\n port = default_port(scheme)\n end\n\n %URI{\n scheme: scheme, path: path, query: query,\n fragment: fragment, authority: authority,\n userinfo: userinfo, host: host, port: port\n }\n end\n\n # Split an authority into its userinfo, host and port parts.\n defp split_authority(s) do\n s = s || \"\"\n components = Regex.run ~r\/(^(.*)@)?(\\[[a-zA-Z0-9:.]*\\]|[^:]*)(:(\\d*))?\/, s\n\n destructure [_, _, userinfo, host, _, port], nillify(components)\n port = if port, do: binary_to_integer(port)\n host = if host, do: host |> String.lstrip(?[) |> String.rstrip(?])\n\n {userinfo, host, port}\n end\n\n # Regex.run returns empty strings sometimes. We want\n # to replace those with nil for consistency.\n defp nillify(l) do\n for s <- l do\n if size(s) > 0, do: s, else: nil\n end\n end\nend\n\ndefimpl String.Chars, for: URI do\n def to_string(uri) do\n scheme = uri.scheme\n\n if scheme && (port = URI.default_port(scheme)) do\n if uri.port == port, do: uri = %{uri | port: nil}\n end\n\n result = \"\"\n\n if uri.scheme, do: result = result <> uri.scheme <> \":\/\/\"\n if uri.userinfo, do: result = result <> uri.userinfo <> \"@\"\n if uri.host, do: result = result <> uri.host\n if uri.port, do: result = result <> \":\" <> integer_to_binary(uri.port)\n if uri.path, do: result = result <> uri.path\n if uri.query, do: result = result <> \"?\" <> uri.query\n if uri.fragment, do: result = result <> \"#\" <> uri.fragment\n\n result\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"f6f7730fa2c93fbff54ea04bcef46167657f5496","subject":"Don't ignore params and pass them to init as the referenced plug expects (#3409)","message":"Don't ignore params and pass them to init as the referenced plug expects (#3409)\n\n","repos":"jwarwick\/phoenix,michalmuskala\/phoenix,eksperimental\/phoenix,0x00evil\/phoenix,rafbgarcia\/phoenix,nshafer\/phoenix,rafbgarcia\/phoenix,michalmuskala\/phoenix,0x00evil\/phoenix,phoenixframework\/phoenix,nshafer\/phoenix,optikfluffel\/phoenix,nshafer\/phoenix,Gazler\/phoenix,0x00evil\/phoenix,phoenixframework\/phoenix,rafbgarcia\/phoenix,keathley\/phoenix,jwarwick\/phoenix,phoenixframework\/phoenix,eksperimental\/phoenix,keathley\/phoenix,Gazler\/phoenix,optikfluffel\/phoenix,optikfluffel\/phoenix","old_file":"lib\/phoenix\/router.ex","new_file":"lib\/phoenix\/router.ex","new_contents":"defmodule Phoenix.Router do\n defmodule NoRouteError do\n @moduledoc \"\"\"\n Exception raised when no route is found.\n \"\"\"\n defexception plug_status: 404, message: \"no route found\", conn: nil, router: nil\n\n def exception(opts) do\n conn = Keyword.fetch!(opts, :conn)\n router = Keyword.fetch!(opts, :router)\n path = \"\/\" <> Enum.join(conn.path_info, \"\/\")\n\n %NoRouteError{message: \"no route found for #{conn.method} #{path} (#{inspect router})\",\n conn: conn, router: router}\n end\n end\n\n @moduledoc \"\"\"\n Defines a Phoenix router.\n\n The router provides a set of macros for generating routes\n that dispatch to specific controllers and actions. Those\n macros are named after HTTP verbs. For example:\n\n defmodule MyAppWeb.Router do\n use Phoenix.Router\n\n get \"\/pages\/:page\", PageController, :show\n end\n\n The `get\/3` macro above accepts a request of format `\"\/pages\/VALUE\"` and\n dispatches it to the show action in the `PageController`.\n\n Routes can also match glob-like patterns, routing any path with a common\n base to the same controller. For example:\n\n get \"\/dynamic*anything\", DynamicController, :show\n\n Phoenix's router is extremely efficient, as it relies on Elixir\n pattern matching for matching routes and serving requests.\n\n ## Helpers\n\n Phoenix automatically generates a module `Helpers` inside your router\n which contains named helpers to help developers generate and keep\n their routes up to date.\n\n Helpers are automatically generated based on the controller name.\n For example, the route:\n\n get \"\/pages\/:page\", PageController, :show\n\n will generate the following named helper:\n\n MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, \"hello\")\n \"\/pages\/hello\"\n\n MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, \"hello\", some: \"query\")\n \"\/pages\/hello?some=query\"\n\n MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, \"hello\")\n \"http:\/\/example.com\/pages\/hello\"\n\n MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, \"hello\", some: \"query\")\n \"http:\/\/example.com\/pages\/hello?some=query\"\n\n If the route contains glob-like patterns, parameters for those have to be given as\n list:\n\n MyAppWeb.Router.Helpers.dynamic_path(conn_or_endpoint, :show, [\"dynamic\", \"something\"])\n \"\/dynamic\/something\"\n\n The URL generated in the named URL helpers is based on the configuration for\n `:url`, `:http` and `:https`. However, if for some reason you need to manually\n control the URL generation, the url helpers also allow you to pass in a `URI`\n struct:\n\n uri = %URI{scheme: \"https\", host: \"other.example.com\"}\n MyAppWeb.Router.Helpers.page_url(uri, :show, \"hello\")\n \"https:\/\/other.example.com\/pages\/hello\"\n\n The named helper can also be customized with the `:as` option. Given\n the route:\n\n get \"\/pages\/:page\", PageController, :show, as: :special_page\n\n the named helper will be:\n\n MyAppWeb.Router.Helpers.special_page_path(conn, :show, \"hello\")\n \"\/pages\/hello\"\n\n ## Scopes and Resources\n\n It is very common in Phoenix applications to namespace all of your\n routes under the application scope:\n\n scope \"\/\", MyAppWeb do\n get \"\/pages\/:id\", PageController, :show\n end\n\n The route above will dispatch to `MyAppWeb.PageController`. This syntax\n is not only convenient for developers, since we don't have to repeat\n the `MyAppWeb.` prefix on all routes, but it also allows Phoenix to put\n less pressure on the Elixir compiler. If instead we had written:\n\n get \"\/pages\/:id\", MyAppWeb.PageController, :show\n\n The Elixir compiler would infer that the router depends directly on\n `MyAppWeb.PageController`, which is not true. By using scopes, Phoenix\n can properly hint to the Elixir compiler the controller is not an\n actual dependency of the router. This provides more efficient\n compilation times.\n\n Scopes allow us to scope on any path or even on the helper name:\n\n scope \"\/api\/v1\", MyAppWeb, as: :api_v1 do\n get \"\/pages\/:id\", PageController, :show\n end\n\n For example, the route above will match on the path `\"\/api\/v1\/pages\/:id\"`\n and the named route will be `api_v1_page_path`, as expected from the\n values given to `scope\/2` option.\n\n Phoenix also provides a `resources\/4` macro that allows developers\n to generate \"RESTful\" routes to a given resource:\n\n defmodule MyAppWeb.Router do\n use Phoenix.Router\n\n resources \"\/pages\", PageController, only: [:show]\n resources \"\/users\", UserController, except: [:delete]\n end\n\n Finally, Phoenix ships with a `mix phx.routes` task that nicely\n formats all routes in a given router. We can use it to verify all\n routes included in the router above:\n\n $ mix phx.routes\n page_path GET \/pages\/:id PageController.show\/2\n user_path GET \/users UserController.index\/2\n user_path GET \/users\/:id\/edit UserController.edit\/2\n user_path GET \/users\/new UserController.new\/2\n user_path GET \/users\/:id UserController.show\/2\n user_path POST \/users UserController.create\/2\n user_path PATCH \/users\/:id UserController.update\/2\n PUT \/users\/:id UserController.update\/2\n\n One can also pass a router explicitly as an argument to the task:\n\n $ mix phx.routes MyAppWeb.Router\n\n Check `scope\/2` and `resources\/4` for more information.\n\n ## Pipelines and plugs\n\n Once a request arrives at the Phoenix router, it performs\n a series of transformations through pipelines until the\n request is dispatched to a desired end-point.\n\n Such transformations are defined via plugs, as defined\n in the [Plug](http:\/\/github.com\/elixir-lang\/plug) specification.\n Once a pipeline is defined, it can be piped through per scope.\n\n For example:\n\n defmodule MyAppWeb.Router do\n use Phoenix.Router\n\n pipeline :browser do\n plug :fetch_session\n plug :accepts, [\"html\"]\n end\n\n scope \"\/\" do\n pipe_through :browser\n\n # browser related routes and resources\n end\n end\n\n `Phoenix.Router` imports functions from both `Plug.Conn` and `Phoenix.Controller`\n to help define plugs. In the example above, `fetch_session\/2`\n comes from `Plug.Conn` while `accepts\/2` comes from `Phoenix.Controller`.\n\n Note that router pipelines are only invoked after a route is found.\n No plug is invoked in case no matches were found.\n \"\"\"\n\n alias Phoenix.Router.{Resource, Scope, Route, Helpers}\n\n @http_methods [:get, :post, :put, :patch, :delete, :options, :connect, :trace, :head]\n\n @doc false\n defmacro __using__(_) do\n quote do\n unquote(prelude())\n unquote(defs())\n unquote(match_dispatch())\n end\n end\n\n defp prelude() do\n quote do\n Module.register_attribute __MODULE__, :phoenix_routes, accumulate: true\n @phoenix_forwards %{}\n\n import Phoenix.Router\n\n # TODO v2: No longer automatically import dependencies\n import Plug.Conn\n import Phoenix.Controller\n\n # Set up initial scope\n @phoenix_pipeline nil\n Phoenix.Router.Scope.init(__MODULE__)\n @before_compile unquote(__MODULE__)\n end\n end\n\n # Because those macros are executed multiple times,\n # we end-up generating a huge scope that drastically\n # affects compilation. We work around it by defining\n # those functions only once and calling it over and\n # over again.\n defp defs() do\n quote unquote: false do\n var!(add_resources, Phoenix.Router) = fn resource ->\n path = resource.path\n ctrl = resource.controller\n opts = resource.route\n\n if resource.singleton do\n Enum.each resource.actions, fn\n :show -> get path, ctrl, :show, opts\n :new -> get path <> \"\/new\", ctrl, :new, opts\n :edit -> get path <> \"\/edit\", ctrl, :edit, opts\n :create -> post path, ctrl, :create, opts\n :delete -> delete path, ctrl, :delete, opts\n :update ->\n patch path, ctrl, :update, opts\n put path, ctrl, :update, Keyword.put(opts, :as, nil)\n end\n else\n param = resource.param\n\n Enum.each resource.actions, fn\n :index -> get path, ctrl, :index, opts\n :show -> get path <> \"\/:\" <> param, ctrl, :show, opts\n :new -> get path <> \"\/new\", ctrl, :new, opts\n :edit -> get path <> \"\/:\" <> param <> \"\/edit\", ctrl, :edit, opts\n :create -> post path, ctrl, :create, opts\n :delete -> delete path <> \"\/:\" <> param, ctrl, :delete, opts\n :update ->\n patch path <> \"\/:\" <> param, ctrl, :update, opts\n put path <> \"\/:\" <> param, ctrl, :update, Keyword.put(opts, :as, nil)\n end\n end\n end\n end\n end\n\n @doc false\n def __call__({%Plug.Conn{private: %{phoenix_router: router, phoenix_bypass: {router, pipes}}} = conn, _pipeline, _dispatch}) do\n Enum.reduce(pipes, conn, fn pipe, acc -> apply(router, pipe, [acc, []]) end)\n end\n def __call__({%Plug.Conn{private: %{phoenix_bypass: :all}} = conn, _pipeline, _dispatch}) do\n conn\n end\n def __call__({conn, pipeline, {plug, opts}}) do\n case pipeline.(conn) do\n %Plug.Conn{halted: true} = halted_conn ->\n halted_conn\n %Plug.Conn{} = piped_conn ->\n try do\n plug.call(piped_conn, plug.init(opts))\n rescue\n e in Plug.Conn.WrapperError ->\n Plug.Conn.WrapperError.reraise(e)\n catch\n :error, reason ->\n Plug.Conn.WrapperError.reraise(piped_conn, :error, reason, System.stacktrace())\n end\n end\n end\n\n defp match_dispatch() do\n quote location: :keep do\n @behaviour Plug\n\n @doc \"\"\"\n Callback required by Plug that initializes the router\n for serving web requests.\n \"\"\"\n def init(opts) do\n opts\n end\n\n @doc \"\"\"\n Callback invoked by Plug on every request.\n \"\"\"\n def call(conn, _opts) do\n conn\n |> prepare()\n |> __match_route__(conn.method, Enum.map(conn.path_info, &URI.decode\/1), conn.host)\n |> Phoenix.Router.__call__()\n end\n\n defoverridable [init: 1, call: 2]\n end\n end\n\n @anno (if :erlang.system_info(:otp_release) >= '19' do\n [generated: true]\n else\n [line: -1]\n end)\n\n @doc false\n defmacro __before_compile__(env) do\n routes = env.module |> Module.get_attribute(:phoenix_routes) |> Enum.reverse\n routes_with_exprs = Enum.map(routes, &{&1, Route.exprs(&1)})\n\n Helpers.define(env, routes_with_exprs)\n {matches, _} = Enum.map_reduce(routes_with_exprs, %{}, &build_match\/2)\n\n checks =\n for {%{line: line}, %{dispatch: {plug, params}}} <- routes_with_exprs, into: %{} do\n quote line: line do\n {unquote(plug).init(unquote(params)), true}\n end\n end\n\n # @anno is used here to avoid warnings if forwarding to root path\n match_404 =\n quote @anno do\n def __match_route__(conn, _method, _path_info, _host) do\n raise NoRouteError, conn: conn, router: __MODULE__\n end\n end\n\n quote do\n @doc false\n def __routes__, do: unquote(Macro.escape(routes))\n\n @doc false\n def __checks__, do: unquote({:__block__, [], Map.keys(checks)})\n\n @doc false\n def __helpers__, do: __MODULE__.Helpers\n\n defp prepare(conn) do\n update_in conn.private,\n &(&1\n |> Map.put(:phoenix_router, __MODULE__)\n |> Map.put(__MODULE__, {conn.script_name, @phoenix_forwards}))\n end\n\n unquote(matches)\n unquote(match_404)\n end\n end\n\n defp build_match({route, exprs}, known_pipelines) do\n %{pipe_through: pipe_through} = route\n\n %{\n prepare: prepare,\n dispatch: dispatch,\n verb_match: verb_match,\n path: path,\n host: host\n } = exprs\n\n {pipe_name, pipe_definition, known_pipelines} =\n case known_pipelines do\n %{^pipe_through => name} ->\n {name, :ok, known_pipelines}\n\n %{} ->\n name = :\"__pipe_through#{map_size(known_pipelines)}__\"\n {name, build_pipes(name, pipe_through), Map.put(known_pipelines, pipe_through, name)}\n end\n\n quoted =\n quote line: route.line do\n unquote(pipe_definition)\n\n @doc false\n def __match_route__(var!(conn), unquote(verb_match), unquote(path), unquote(host)) do\n {unquote(prepare), &unquote(Macro.var(pipe_name, __MODULE__))\/1, unquote(dispatch)}\n end\n end\n\n {quoted, known_pipelines}\n end\n\n defp build_pipes(name, []) do\n quote do\n defp unquote(name)(conn) do\n Plug.Conn.put_private(conn, :phoenix_pipelines, [])\n end\n end\n end\n\n defp build_pipes(name, pipe_through) do\n plugs = pipe_through |> Enum.reverse |> Enum.map(&{&1, [], true})\n {conn, body} = Plug.Builder.compile(__ENV__, plugs, init_mode: Phoenix.plug_init_mode())\n\n quote do\n defp unquote(name)(unquote(conn)) do\n unquote(conn) = Plug.Conn.put_private(unquote(conn), :phoenix_pipelines, unquote(pipe_through))\n unquote(body)\n end\n end\n end\n\n @doc \"\"\"\n Generates a route match based on an arbitrary HTTP method.\n\n Useful for defining routes not included in the builtin macros:\n\n #{Enum.map_join(@http_methods, \", \", &\"`#{&1}`\")}\n\n The catch-all verb, `:*`, may also be used to match all HTTP methods.\n\n ## Examples\n\n match(:move, \"\/events\/:id\", EventController, :move)\n\n match(:*, \"\/any\", SomeController, :any)\n\n \"\"\"\n defmacro match(verb, path, plug, plug_opts, options \\\\ []) do\n add_route(:match, verb, path, plug, plug_opts, options)\n end\n\n for verb <- @http_methods do\n @doc \"\"\"\n Generates a route to handle a #{verb} request to the given path.\n \"\"\"\n defmacro unquote(verb)(path, plug, plug_opts, options \\\\ []) do\n add_route(:match, unquote(verb), path, plug, plug_opts, options)\n end\n end\n\n defp add_route(kind, verb, path, plug, plug_opts, options) do\n quote do\n @phoenix_routes Scope.route(\n __ENV__.line,\n __ENV__.module,\n unquote(kind),\n unquote(verb),\n unquote(path),\n unquote(plug),\n unquote(plug_opts),\n unquote(options)\n )\n end\n end\n\n @doc \"\"\"\n Defines a plug pipeline.\n\n Pipelines are defined at the router root and can be used\n from any scope.\n\n ## Examples\n\n pipeline :api do\n plug :token_authentication\n plug :dispatch\n end\n\n A scope may then use this pipeline as:\n\n scope \"\/\" do\n pipe_through :api\n end\n\n Every time `pipe_through\/1` is called, the new pipelines\n are appended to the ones previously given.\n \"\"\"\n defmacro pipeline(plug, do: block) do\n block =\n quote do\n plug = unquote(plug)\n @phoenix_pipeline []\n unquote(block)\n end\n\n compiler =\n quote unquote: false do\n Scope.pipeline(__MODULE__, plug)\n {conn, body} = Plug.Builder.compile(__ENV__, @phoenix_pipeline,\n init_mode: Phoenix.plug_init_mode())\n\n def unquote(plug)(unquote(conn), _) do\n try do\n unquote(body)\n rescue\n e in Plug.Conn.WrapperError ->\n Plug.Conn.WrapperError.reraise(e)\n catch\n :error, reason ->\n Plug.Conn.WrapperError.reraise(unquote(conn), :error, reason, System.stacktrace())\n end\n end\n @phoenix_pipeline nil\n end\n\n quote do\n try do\n unquote(block)\n unquote(compiler)\n after\n :ok\n end\n end\n end\n\n @doc \"\"\"\n Defines a plug inside a pipeline.\n\n See `pipeline\/2` for more information.\n \"\"\"\n defmacro plug(plug, opts \\\\ []) do\n quote do\n if pipeline = @phoenix_pipeline do\n @phoenix_pipeline [{unquote(plug), unquote(opts), true}|pipeline]\n else\n raise \"cannot define plug at the router level, plug must be defined inside a pipeline\"\n end\n end\n end\n\n @doc \"\"\"\n Defines a pipeline to send the connection through.\n\n See `pipeline\/2` for more information.\n \"\"\"\n defmacro pipe_through(pipes) do\n quote do\n if pipeline = @phoenix_pipeline do\n raise \"cannot pipe_through inside a pipeline\"\n else\n Scope.pipe_through(__MODULE__, unquote(pipes))\n end\n end\n end\n\n @doc \"\"\"\n Defines \"RESTful\" routes for a resource.\n\n The given definition:\n\n resources \"\/users\", UserController\n\n will include routes to the following actions:\n\n * `GET \/users` => `:index`\n * `GET \/users\/new` => `:new`\n * `POST \/users` => `:create`\n * `GET \/users\/:id` => `:show`\n * `GET \/users\/:id\/edit` => `:edit`\n * `PATCH \/users\/:id` => `:update`\n * `PUT \/users\/:id` => `:update`\n * `DELETE \/users\/:id` => `:delete`\n\n ## Options\n\n This macro accepts a set of options:\n\n * `:only` - a list of actions to generate routes for, for example: `[:show, :edit]`\n * `:except` - a list of actions to exclude generated routes from, for example: `[:delete]`\n * `:param` - the name of the parameter for this resource, defaults to `\"id\"`\n * `:name` - the prefix for this resource. This is used for the named helper\n and as the prefix for the parameter in nested resources. The default value\n is automatically derived from the controller name, i.e. `UserController` will\n have name `\"user\"`\n * `:as` - configures the named helper exclusively\n * `:singleton` - defines routes for a singleton resource that is looked up by\n the client without referencing an ID. Read below for more information\n\n ## Singleton resources\n\n When a resource needs to be looked up without referencing an ID, because\n it contains only a single entry in the given context, the `:singleton`\n option can be used to generate a set of routes that are specific to\n such single resource:\n\n * `GET \/user` => `:show`\n * `GET \/user\/new` => `:new`\n * `POST \/user` => `:create`\n * `GET \/user\/edit` => `:edit`\n * `PATCH \/user` => `:update`\n * `PUT \/user` => `:update`\n * `DELETE \/user` => `:delete`\n\n Usage example:\n\n resources \"\/account\", AccountController, only: [:show], singleton: true\n\n ## Nested Resources\n\n This macro also supports passing a nested block of route definitions.\n This is helpful for nesting children resources within their parents to\n generate nested routes.\n\n The given definition:\n\n resources \"\/users\", UserController do\n resources \"\/posts\", PostController\n end\n\n will include the following routes:\n\n user_post_path GET \/users\/:user_id\/posts PostController :index\n user_post_path GET \/users\/:user_id\/posts\/:id\/edit PostController :edit\n user_post_path GET \/users\/:user_id\/posts\/new PostController :new\n user_post_path GET \/users\/:user_id\/posts\/:id PostController :show\n user_post_path POST \/users\/:user_id\/posts PostController :create\n user_post_path PATCH \/users\/:user_id\/posts\/:id PostController :update\n PUT \/users\/:user_id\/posts\/:id PostController :update\n user_post_path DELETE \/users\/:user_id\/posts\/:id PostController :delete\n\n \"\"\"\n defmacro resources(path, controller, opts, do: nested_context) do\n add_resources path, controller, opts, do: nested_context\n end\n\n @doc \"\"\"\n See `resources\/4`.\n \"\"\"\n defmacro resources(path, controller, do: nested_context) do\n add_resources path, controller, [], do: nested_context\n end\n\n defmacro resources(path, controller, opts) do\n add_resources path, controller, opts, do: nil\n end\n\n @doc \"\"\"\n See `resources\/4`.\n \"\"\"\n defmacro resources(path, controller) do\n add_resources path, controller, [], do: nil\n end\n\n defp add_resources(path, controller, options, do: context) do\n scope =\n if context do\n quote do\n scope resource.member, do: unquote(context)\n end\n end\n\n quote do\n resource = Resource.build(unquote(path), unquote(controller), unquote(options))\n var!(add_resources, Phoenix.Router).(resource)\n unquote(scope)\n end\n end\n\n @doc \"\"\"\n Defines a scope in which routes can be nested.\n\n ## Examples\n\n scope path: \"\/api\/v1\", as: :api_v1, alias: API.V1 do\n get \"\/pages\/:id\", PageController, :show\n end\n\n The generated route above will match on the path `\"\/api\/v1\/pages\/:id\"`\n and will dispatch to `:show` action in `API.V1.PageController`. A named\n helper `api_v1_page_path` will also be generated.\n\n ## Options\n\n The supported options are:\n\n * `:path` - a string containing the path scope\n * `:as` - a string or atom containing the named helper scope\n * `:alias` - an alias (atom) containing the controller scope.\n When set, this value may be overridden per route by passing `alias: false`\n to route definitions, such as `get`, `post`, etc.\n * `:host` - a string containing the host scope, or prefix host scope,\n ie `\"foo.bar.com\"`, `\"foo.\"`\n * `:private` - a map of private data to merge into the connection when a route matches\n * `:assigns` - a map of data to merge into the connection when a route matches\n\n \"\"\"\n defmacro scope(options, do: context) do\n do_scope(options, context)\n end\n\n @doc \"\"\"\n Define a scope with the given path.\n\n This function is a shortcut for:\n\n scope path: path do\n ...\n end\n\n ## Examples\n\n scope \"\/api\/v1\", as: :api_v1, alias: API.V1 do\n get \"\/pages\/:id\", PageController, :show\n end\n\n \"\"\"\n defmacro scope(path, options, do: context) do\n options = quote do\n path = unquote(path)\n case unquote(options) do\n alias when is_atom(alias) -> [path: path, alias: alias]\n options when is_list(options) -> Keyword.put(options, :path, path)\n end\n end\n do_scope(options, context)\n end\n\n @doc \"\"\"\n Defines a scope with the given path and alias.\n\n This function is a shortcut for:\n\n scope path: path, alias: alias do\n ...\n end\n\n ## Examples\n\n scope \"\/api\/v1\", API.V1, as: :api_v1 do\n get \"\/pages\/:id\", PageController, :show\n end\n\n \"\"\"\n defmacro scope(path, alias, options, do: context) do\n options = quote do\n unquote(options)\n |> Keyword.put(:path, unquote(path))\n |> Keyword.put(:alias, unquote(alias))\n end\n do_scope(options, context)\n end\n\n defp do_scope(options, context) do\n quote do\n Scope.push(__MODULE__, unquote(options))\n try do\n unquote(context)\n after\n Scope.pop(__MODULE__)\n end\n end\n end\n\n @doc \"\"\"\n Returns the full alias with the current scope's aliased prefix.\n\n Useful for applying the same short-hand alias handling to\n other values besides the second argument in route definitions.\n\n ## Examples\n\n scope \"\/\", MyPrefix do\n get \"\/\", ProxyPlug, controller: scoped_alias(__MODULE__, MyController)\n end\n \"\"\"\n def scoped_alias(router_module, alias) do\n Scope.expand_alias(router_module, alias)\n end\n\n @doc \"\"\"\n Forwards a request at the given path to a plug.\n\n All paths that match the forwarded prefix will be sent to\n the forwarded plug. This is useful for sharing a router between\n applications or even breaking a big router into smaller ones.\n The router pipelines will be invoked prior to forwarding the\n connection.\n\n The forwarded plug will be initialized at compile time.\n\n Note, however, that we don't advise forwarding to another\n endpoint. The reason is that plugs defined by your app\n and the forwarded endpoint would be invoked twice, which\n may lead to errors.\n\n ## Examples\n\n scope \"\/\", MyApp do\n pipe_through [:browser, :admin]\n\n forward \"\/admin\", SomeLib.AdminDashboard\n forward \"\/api\", ApiRouter\n end\n\n \"\"\"\n defmacro forward(path, plug, plug_opts \\\\ [], router_opts \\\\ []) do\n router_opts = Keyword.put(router_opts, :as, nil)\n\n quote unquote: true, bind_quoted: [path: path, plug: plug] do\n plug = Scope.register_forwards(__MODULE__, path, plug)\n unquote(add_route(:forward, :*, path, plug, plug_opts, router_opts))\n end\n end\nend\n","old_contents":"defmodule Phoenix.Router do\n defmodule NoRouteError do\n @moduledoc \"\"\"\n Exception raised when no route is found.\n \"\"\"\n defexception plug_status: 404, message: \"no route found\", conn: nil, router: nil\n\n def exception(opts) do\n conn = Keyword.fetch!(opts, :conn)\n router = Keyword.fetch!(opts, :router)\n path = \"\/\" <> Enum.join(conn.path_info, \"\/\")\n\n %NoRouteError{message: \"no route found for #{conn.method} #{path} (#{inspect router})\",\n conn: conn, router: router}\n end\n end\n\n @moduledoc \"\"\"\n Defines a Phoenix router.\n\n The router provides a set of macros for generating routes\n that dispatch to specific controllers and actions. Those\n macros are named after HTTP verbs. For example:\n\n defmodule MyAppWeb.Router do\n use Phoenix.Router\n\n get \"\/pages\/:page\", PageController, :show\n end\n\n The `get\/3` macro above accepts a request of format `\"\/pages\/VALUE\"` and\n dispatches it to the show action in the `PageController`.\n\n Routes can also match glob-like patterns, routing any path with a common\n base to the same controller. For example:\n\n get \"\/dynamic*anything\", DynamicController, :show\n\n Phoenix's router is extremely efficient, as it relies on Elixir\n pattern matching for matching routes and serving requests.\n\n ## Helpers\n\n Phoenix automatically generates a module `Helpers` inside your router\n which contains named helpers to help developers generate and keep\n their routes up to date.\n\n Helpers are automatically generated based on the controller name.\n For example, the route:\n\n get \"\/pages\/:page\", PageController, :show\n\n will generate the following named helper:\n\n MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, \"hello\")\n \"\/pages\/hello\"\n\n MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, \"hello\", some: \"query\")\n \"\/pages\/hello?some=query\"\n\n MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, \"hello\")\n \"http:\/\/example.com\/pages\/hello\"\n\n MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, \"hello\", some: \"query\")\n \"http:\/\/example.com\/pages\/hello?some=query\"\n\n If the route contains glob-like patterns, parameters for those have to be given as\n list:\n\n MyAppWeb.Router.Helpers.dynamic_path(conn_or_endpoint, :show, [\"dynamic\", \"something\"])\n \"\/dynamic\/something\"\n\n The URL generated in the named URL helpers is based on the configuration for\n `:url`, `:http` and `:https`. However, if for some reason you need to manually\n control the URL generation, the url helpers also allow you to pass in a `URI`\n struct:\n\n uri = %URI{scheme: \"https\", host: \"other.example.com\"}\n MyAppWeb.Router.Helpers.page_url(uri, :show, \"hello\")\n \"https:\/\/other.example.com\/pages\/hello\"\n\n The named helper can also be customized with the `:as` option. Given\n the route:\n\n get \"\/pages\/:page\", PageController, :show, as: :special_page\n\n the named helper will be:\n\n MyAppWeb.Router.Helpers.special_page_path(conn, :show, \"hello\")\n \"\/pages\/hello\"\n\n ## Scopes and Resources\n\n It is very common in Phoenix applications to namespace all of your\n routes under the application scope:\n\n scope \"\/\", MyAppWeb do\n get \"\/pages\/:id\", PageController, :show\n end\n\n The route above will dispatch to `MyAppWeb.PageController`. This syntax\n is not only convenient for developers, since we don't have to repeat\n the `MyAppWeb.` prefix on all routes, but it also allows Phoenix to put\n less pressure on the Elixir compiler. If instead we had written:\n\n get \"\/pages\/:id\", MyAppWeb.PageController, :show\n\n The Elixir compiler would infer that the router depends directly on\n `MyAppWeb.PageController`, which is not true. By using scopes, Phoenix\n can properly hint to the Elixir compiler the controller is not an\n actual dependency of the router. This provides more efficient\n compilation times.\n\n Scopes allow us to scope on any path or even on the helper name:\n\n scope \"\/api\/v1\", MyAppWeb, as: :api_v1 do\n get \"\/pages\/:id\", PageController, :show\n end\n\n For example, the route above will match on the path `\"\/api\/v1\/pages\/:id\"`\n and the named route will be `api_v1_page_path`, as expected from the\n values given to `scope\/2` option.\n\n Phoenix also provides a `resources\/4` macro that allows developers\n to generate \"RESTful\" routes to a given resource:\n\n defmodule MyAppWeb.Router do\n use Phoenix.Router\n\n resources \"\/pages\", PageController, only: [:show]\n resources \"\/users\", UserController, except: [:delete]\n end\n\n Finally, Phoenix ships with a `mix phx.routes` task that nicely\n formats all routes in a given router. We can use it to verify all\n routes included in the router above:\n\n $ mix phx.routes\n page_path GET \/pages\/:id PageController.show\/2\n user_path GET \/users UserController.index\/2\n user_path GET \/users\/:id\/edit UserController.edit\/2\n user_path GET \/users\/new UserController.new\/2\n user_path GET \/users\/:id UserController.show\/2\n user_path POST \/users UserController.create\/2\n user_path PATCH \/users\/:id UserController.update\/2\n PUT \/users\/:id UserController.update\/2\n\n One can also pass a router explicitly as an argument to the task:\n\n $ mix phx.routes MyAppWeb.Router\n\n Check `scope\/2` and `resources\/4` for more information.\n\n ## Pipelines and plugs\n\n Once a request arrives at the Phoenix router, it performs\n a series of transformations through pipelines until the\n request is dispatched to a desired end-point.\n\n Such transformations are defined via plugs, as defined\n in the [Plug](http:\/\/github.com\/elixir-lang\/plug) specification.\n Once a pipeline is defined, it can be piped through per scope.\n\n For example:\n\n defmodule MyAppWeb.Router do\n use Phoenix.Router\n\n pipeline :browser do\n plug :fetch_session\n plug :accepts, [\"html\"]\n end\n\n scope \"\/\" do\n pipe_through :browser\n\n # browser related routes and resources\n end\n end\n\n `Phoenix.Router` imports functions from both `Plug.Conn` and `Phoenix.Controller`\n to help define plugs. In the example above, `fetch_session\/2`\n comes from `Plug.Conn` while `accepts\/2` comes from `Phoenix.Controller`.\n\n Note that router pipelines are only invoked after a route is found.\n No plug is invoked in case no matches were found.\n \"\"\"\n\n alias Phoenix.Router.{Resource, Scope, Route, Helpers}\n\n @http_methods [:get, :post, :put, :patch, :delete, :options, :connect, :trace, :head]\n\n @doc false\n defmacro __using__(_) do\n quote do\n unquote(prelude())\n unquote(defs())\n unquote(match_dispatch())\n end\n end\n\n defp prelude() do\n quote do\n Module.register_attribute __MODULE__, :phoenix_routes, accumulate: true\n @phoenix_forwards %{}\n\n import Phoenix.Router\n\n # TODO v2: No longer automatically import dependencies\n import Plug.Conn\n import Phoenix.Controller\n\n # Set up initial scope\n @phoenix_pipeline nil\n Phoenix.Router.Scope.init(__MODULE__)\n @before_compile unquote(__MODULE__)\n end\n end\n\n # Because those macros are executed multiple times,\n # we end-up generating a huge scope that drastically\n # affects compilation. We work around it by defining\n # those functions only once and calling it over and\n # over again.\n defp defs() do\n quote unquote: false do\n var!(add_resources, Phoenix.Router) = fn resource ->\n path = resource.path\n ctrl = resource.controller\n opts = resource.route\n\n if resource.singleton do\n Enum.each resource.actions, fn\n :show -> get path, ctrl, :show, opts\n :new -> get path <> \"\/new\", ctrl, :new, opts\n :edit -> get path <> \"\/edit\", ctrl, :edit, opts\n :create -> post path, ctrl, :create, opts\n :delete -> delete path, ctrl, :delete, opts\n :update ->\n patch path, ctrl, :update, opts\n put path, ctrl, :update, Keyword.put(opts, :as, nil)\n end\n else\n param = resource.param\n\n Enum.each resource.actions, fn\n :index -> get path, ctrl, :index, opts\n :show -> get path <> \"\/:\" <> param, ctrl, :show, opts\n :new -> get path <> \"\/new\", ctrl, :new, opts\n :edit -> get path <> \"\/:\" <> param <> \"\/edit\", ctrl, :edit, opts\n :create -> post path, ctrl, :create, opts\n :delete -> delete path <> \"\/:\" <> param, ctrl, :delete, opts\n :update ->\n patch path <> \"\/:\" <> param, ctrl, :update, opts\n put path <> \"\/:\" <> param, ctrl, :update, Keyword.put(opts, :as, nil)\n end\n end\n end\n end\n end\n\n @doc false\n def __call__({%Plug.Conn{private: %{phoenix_router: router, phoenix_bypass: {router, pipes}}} = conn, _pipeline, _dispatch}) do\n Enum.reduce(pipes, conn, fn pipe, acc -> apply(router, pipe, [acc, []]) end)\n end\n def __call__({%Plug.Conn{private: %{phoenix_bypass: :all}} = conn, _pipeline, _dispatch}) do\n conn\n end\n def __call__({conn, pipeline, {plug, opts}}) do\n case pipeline.(conn) do\n %Plug.Conn{halted: true} = halted_conn ->\n halted_conn\n %Plug.Conn{} = piped_conn ->\n try do\n plug.call(piped_conn, plug.init(opts))\n rescue\n e in Plug.Conn.WrapperError ->\n Plug.Conn.WrapperError.reraise(e)\n catch\n :error, reason ->\n Plug.Conn.WrapperError.reraise(piped_conn, :error, reason, System.stacktrace())\n end\n end\n end\n\n defp match_dispatch() do\n quote location: :keep do\n @behaviour Plug\n\n @doc \"\"\"\n Callback required by Plug that initializes the router\n for serving web requests.\n \"\"\"\n def init(opts) do\n opts\n end\n\n @doc \"\"\"\n Callback invoked by Plug on every request.\n \"\"\"\n def call(conn, _opts) do\n conn\n |> prepare()\n |> __match_route__(conn.method, Enum.map(conn.path_info, &URI.decode\/1), conn.host)\n |> Phoenix.Router.__call__()\n end\n\n defoverridable [init: 1, call: 2]\n end\n end\n\n @anno (if :erlang.system_info(:otp_release) >= '19' do\n [generated: true]\n else\n [line: -1]\n end)\n\n @doc false\n defmacro __before_compile__(env) do\n routes = env.module |> Module.get_attribute(:phoenix_routes) |> Enum.reverse\n routes_with_exprs = Enum.map(routes, &{&1, Route.exprs(&1)})\n\n Helpers.define(env, routes_with_exprs)\n {matches, _} = Enum.map_reduce(routes_with_exprs, %{}, &build_match\/2)\n\n checks =\n for {%{line: line}, %{dispatch: {plug, _}}} <- routes_with_exprs, into: %{} do\n quote line: line do\n {unquote(plug).init([]), true}\n end\n end\n\n # @anno is used here to avoid warnings if forwarding to root path\n match_404 =\n quote @anno do\n def __match_route__(conn, _method, _path_info, _host) do\n raise NoRouteError, conn: conn, router: __MODULE__\n end\n end\n\n quote do\n @doc false\n def __routes__, do: unquote(Macro.escape(routes))\n\n @doc false\n def __checks__, do: unquote({:__block__, [], Map.keys(checks)})\n\n @doc false\n def __helpers__, do: __MODULE__.Helpers\n\n defp prepare(conn) do\n update_in conn.private,\n &(&1\n |> Map.put(:phoenix_router, __MODULE__)\n |> Map.put(__MODULE__, {conn.script_name, @phoenix_forwards}))\n end\n\n unquote(matches)\n unquote(match_404)\n end\n end\n\n defp build_match({route, exprs}, known_pipelines) do\n %{pipe_through: pipe_through} = route\n\n %{\n prepare: prepare,\n dispatch: dispatch,\n verb_match: verb_match,\n path: path,\n host: host\n } = exprs\n\n {pipe_name, pipe_definition, known_pipelines} =\n case known_pipelines do\n %{^pipe_through => name} ->\n {name, :ok, known_pipelines}\n\n %{} ->\n name = :\"__pipe_through#{map_size(known_pipelines)}__\"\n {name, build_pipes(name, pipe_through), Map.put(known_pipelines, pipe_through, name)}\n end\n\n quoted =\n quote line: route.line do\n unquote(pipe_definition)\n\n @doc false\n def __match_route__(var!(conn), unquote(verb_match), unquote(path), unquote(host)) do\n {unquote(prepare), &unquote(Macro.var(pipe_name, __MODULE__))\/1, unquote(dispatch)}\n end\n end\n\n {quoted, known_pipelines}\n end\n\n defp build_pipes(name, []) do\n quote do\n defp unquote(name)(conn) do\n Plug.Conn.put_private(conn, :phoenix_pipelines, [])\n end\n end\n end\n\n defp build_pipes(name, pipe_through) do\n plugs = pipe_through |> Enum.reverse |> Enum.map(&{&1, [], true})\n {conn, body} = Plug.Builder.compile(__ENV__, plugs, init_mode: Phoenix.plug_init_mode())\n\n quote do\n defp unquote(name)(unquote(conn)) do\n unquote(conn) = Plug.Conn.put_private(unquote(conn), :phoenix_pipelines, unquote(pipe_through))\n unquote(body)\n end\n end\n end\n\n @doc \"\"\"\n Generates a route match based on an arbitrary HTTP method.\n\n Useful for defining routes not included in the builtin macros:\n\n #{Enum.map_join(@http_methods, \", \", &\"`#{&1}`\")}\n\n The catch-all verb, `:*`, may also be used to match all HTTP methods.\n\n ## Examples\n\n match(:move, \"\/events\/:id\", EventController, :move)\n\n match(:*, \"\/any\", SomeController, :any)\n\n \"\"\"\n defmacro match(verb, path, plug, plug_opts, options \\\\ []) do\n add_route(:match, verb, path, plug, plug_opts, options)\n end\n\n for verb <- @http_methods do\n @doc \"\"\"\n Generates a route to handle a #{verb} request to the given path.\n \"\"\"\n defmacro unquote(verb)(path, plug, plug_opts, options \\\\ []) do\n add_route(:match, unquote(verb), path, plug, plug_opts, options)\n end\n end\n\n defp add_route(kind, verb, path, plug, plug_opts, options) do\n quote do\n @phoenix_routes Scope.route(\n __ENV__.line,\n __ENV__.module,\n unquote(kind),\n unquote(verb),\n unquote(path),\n unquote(plug),\n unquote(plug_opts),\n unquote(options)\n )\n end\n end\n\n @doc \"\"\"\n Defines a plug pipeline.\n\n Pipelines are defined at the router root and can be used\n from any scope.\n\n ## Examples\n\n pipeline :api do\n plug :token_authentication\n plug :dispatch\n end\n\n A scope may then use this pipeline as:\n\n scope \"\/\" do\n pipe_through :api\n end\n\n Every time `pipe_through\/1` is called, the new pipelines\n are appended to the ones previously given.\n \"\"\"\n defmacro pipeline(plug, do: block) do\n block =\n quote do\n plug = unquote(plug)\n @phoenix_pipeline []\n unquote(block)\n end\n\n compiler =\n quote unquote: false do\n Scope.pipeline(__MODULE__, plug)\n {conn, body} = Plug.Builder.compile(__ENV__, @phoenix_pipeline,\n init_mode: Phoenix.plug_init_mode())\n\n def unquote(plug)(unquote(conn), _) do\n try do\n unquote(body)\n rescue\n e in Plug.Conn.WrapperError ->\n Plug.Conn.WrapperError.reraise(e)\n catch\n :error, reason ->\n Plug.Conn.WrapperError.reraise(unquote(conn), :error, reason, System.stacktrace())\n end\n end\n @phoenix_pipeline nil\n end\n\n quote do\n try do\n unquote(block)\n unquote(compiler)\n after\n :ok\n end\n end\n end\n\n @doc \"\"\"\n Defines a plug inside a pipeline.\n\n See `pipeline\/2` for more information.\n \"\"\"\n defmacro plug(plug, opts \\\\ []) do\n quote do\n if pipeline = @phoenix_pipeline do\n @phoenix_pipeline [{unquote(plug), unquote(opts), true}|pipeline]\n else\n raise \"cannot define plug at the router level, plug must be defined inside a pipeline\"\n end\n end\n end\n\n @doc \"\"\"\n Defines a pipeline to send the connection through.\n\n See `pipeline\/2` for more information.\n \"\"\"\n defmacro pipe_through(pipes) do\n quote do\n if pipeline = @phoenix_pipeline do\n raise \"cannot pipe_through inside a pipeline\"\n else\n Scope.pipe_through(__MODULE__, unquote(pipes))\n end\n end\n end\n\n @doc \"\"\"\n Defines \"RESTful\" routes for a resource.\n\n The given definition:\n\n resources \"\/users\", UserController\n\n will include routes to the following actions:\n\n * `GET \/users` => `:index`\n * `GET \/users\/new` => `:new`\n * `POST \/users` => `:create`\n * `GET \/users\/:id` => `:show`\n * `GET \/users\/:id\/edit` => `:edit`\n * `PATCH \/users\/:id` => `:update`\n * `PUT \/users\/:id` => `:update`\n * `DELETE \/users\/:id` => `:delete`\n\n ## Options\n\n This macro accepts a set of options:\n\n * `:only` - a list of actions to generate routes for, for example: `[:show, :edit]`\n * `:except` - a list of actions to exclude generated routes from, for example: `[:delete]`\n * `:param` - the name of the parameter for this resource, defaults to `\"id\"`\n * `:name` - the prefix for this resource. This is used for the named helper\n and as the prefix for the parameter in nested resources. The default value\n is automatically derived from the controller name, i.e. `UserController` will\n have name `\"user\"`\n * `:as` - configures the named helper exclusively\n * `:singleton` - defines routes for a singleton resource that is looked up by\n the client without referencing an ID. Read below for more information\n\n ## Singleton resources\n\n When a resource needs to be looked up without referencing an ID, because\n it contains only a single entry in the given context, the `:singleton`\n option can be used to generate a set of routes that are specific to\n such single resource:\n\n * `GET \/user` => `:show`\n * `GET \/user\/new` => `:new`\n * `POST \/user` => `:create`\n * `GET \/user\/edit` => `:edit`\n * `PATCH \/user` => `:update`\n * `PUT \/user` => `:update`\n * `DELETE \/user` => `:delete`\n\n Usage example:\n\n resources \"\/account\", AccountController, only: [:show], singleton: true\n\n ## Nested Resources\n\n This macro also supports passing a nested block of route definitions.\n This is helpful for nesting children resources within their parents to\n generate nested routes.\n\n The given definition:\n\n resources \"\/users\", UserController do\n resources \"\/posts\", PostController\n end\n\n will include the following routes:\n\n user_post_path GET \/users\/:user_id\/posts PostController :index\n user_post_path GET \/users\/:user_id\/posts\/:id\/edit PostController :edit\n user_post_path GET \/users\/:user_id\/posts\/new PostController :new\n user_post_path GET \/users\/:user_id\/posts\/:id PostController :show\n user_post_path POST \/users\/:user_id\/posts PostController :create\n user_post_path PATCH \/users\/:user_id\/posts\/:id PostController :update\n PUT \/users\/:user_id\/posts\/:id PostController :update\n user_post_path DELETE \/users\/:user_id\/posts\/:id PostController :delete\n\n \"\"\"\n defmacro resources(path, controller, opts, do: nested_context) do\n add_resources path, controller, opts, do: nested_context\n end\n\n @doc \"\"\"\n See `resources\/4`.\n \"\"\"\n defmacro resources(path, controller, do: nested_context) do\n add_resources path, controller, [], do: nested_context\n end\n\n defmacro resources(path, controller, opts) do\n add_resources path, controller, opts, do: nil\n end\n\n @doc \"\"\"\n See `resources\/4`.\n \"\"\"\n defmacro resources(path, controller) do\n add_resources path, controller, [], do: nil\n end\n\n defp add_resources(path, controller, options, do: context) do\n scope =\n if context do\n quote do\n scope resource.member, do: unquote(context)\n end\n end\n\n quote do\n resource = Resource.build(unquote(path), unquote(controller), unquote(options))\n var!(add_resources, Phoenix.Router).(resource)\n unquote(scope)\n end\n end\n\n @doc \"\"\"\n Defines a scope in which routes can be nested.\n\n ## Examples\n\n scope path: \"\/api\/v1\", as: :api_v1, alias: API.V1 do\n get \"\/pages\/:id\", PageController, :show\n end\n\n The generated route above will match on the path `\"\/api\/v1\/pages\/:id\"`\n and will dispatch to `:show` action in `API.V1.PageController`. A named\n helper `api_v1_page_path` will also be generated.\n\n ## Options\n\n The supported options are:\n\n * `:path` - a string containing the path scope\n * `:as` - a string or atom containing the named helper scope\n * `:alias` - an alias (atom) containing the controller scope.\n When set, this value may be overridden per route by passing `alias: false`\n to route definitions, such as `get`, `post`, etc.\n * `:host` - a string containing the host scope, or prefix host scope,\n ie `\"foo.bar.com\"`, `\"foo.\"`\n * `:private` - a map of private data to merge into the connection when a route matches\n * `:assigns` - a map of data to merge into the connection when a route matches\n\n \"\"\"\n defmacro scope(options, do: context) do\n do_scope(options, context)\n end\n\n @doc \"\"\"\n Define a scope with the given path.\n\n This function is a shortcut for:\n\n scope path: path do\n ...\n end\n\n ## Examples\n\n scope \"\/api\/v1\", as: :api_v1, alias: API.V1 do\n get \"\/pages\/:id\", PageController, :show\n end\n\n \"\"\"\n defmacro scope(path, options, do: context) do\n options = quote do\n path = unquote(path)\n case unquote(options) do\n alias when is_atom(alias) -> [path: path, alias: alias]\n options when is_list(options) -> Keyword.put(options, :path, path)\n end\n end\n do_scope(options, context)\n end\n\n @doc \"\"\"\n Defines a scope with the given path and alias.\n\n This function is a shortcut for:\n\n scope path: path, alias: alias do\n ...\n end\n\n ## Examples\n\n scope \"\/api\/v1\", API.V1, as: :api_v1 do\n get \"\/pages\/:id\", PageController, :show\n end\n\n \"\"\"\n defmacro scope(path, alias, options, do: context) do\n options = quote do\n unquote(options)\n |> Keyword.put(:path, unquote(path))\n |> Keyword.put(:alias, unquote(alias))\n end\n do_scope(options, context)\n end\n\n defp do_scope(options, context) do\n quote do\n Scope.push(__MODULE__, unquote(options))\n try do\n unquote(context)\n after\n Scope.pop(__MODULE__)\n end\n end\n end\n\n @doc \"\"\"\n Returns the full alias with the current scope's aliased prefix.\n\n Useful for applying the same short-hand alias handling to\n other values besides the second argument in route definitions.\n\n ## Examples\n\n scope \"\/\", MyPrefix do\n get \"\/\", ProxyPlug, controller: scoped_alias(__MODULE__, MyController)\n end\n \"\"\"\n def scoped_alias(router_module, alias) do\n Scope.expand_alias(router_module, alias)\n end\n\n @doc \"\"\"\n Forwards a request at the given path to a plug.\n\n All paths that match the forwarded prefix will be sent to\n the forwarded plug. This is useful for sharing a router between\n applications or even breaking a big router into smaller ones.\n The router pipelines will be invoked prior to forwarding the\n connection.\n\n The forwarded plug will be initialized at compile time.\n\n Note, however, that we don't advise forwarding to another\n endpoint. The reason is that plugs defined by your app\n and the forwarded endpoint would be invoked twice, which\n may lead to errors.\n\n ## Examples\n\n scope \"\/\", MyApp do\n pipe_through [:browser, :admin]\n\n forward \"\/admin\", SomeLib.AdminDashboard\n forward \"\/api\", ApiRouter\n end\n\n \"\"\"\n defmacro forward(path, plug, plug_opts \\\\ [], router_opts \\\\ []) do\n router_opts = Keyword.put(router_opts, :as, nil)\n\n quote unquote: true, bind_quoted: [path: path, plug: plug] do\n plug = Scope.register_forwards(__MODULE__, path, plug)\n unquote(add_route(:forward, :*, path, plug, plug_opts, router_opts))\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"bec94c2c49488c947f30b43edcc9c6e2e05749b6","subject":"fix decimals","message":"fix decimals\n","repos":"mbenatti\/neo-scan,mbenatti\/neo-scan,mbenatti\/neo-scan","old_file":"apps\/neoscan\/lib\/neoscan\/claims\/unclaimed.ex","new_file":"apps\/neoscan\/lib\/neoscan\/claims\/unclaimed.ex","new_contents":"defmodule Neoscan.Claims.Unclaimed do\n @moduledoc false\n import Ecto.Query, warn: false\n alias Decimal, as: D\n alias Neoscan.Repo\n alias Neoscan.Vouts.Vout\n alias NeoscanMonitor.Api\n alias Neoscan.Blocks.Block\n\n #total amount of available NEO\n def total_neo, do: 100_000_000\n D.set_context(%D.Context{D.get_context | precision: 10})\n\n #calculate unclaimed gas bonus\n def calculate_bonus(address_id) do\n get_unclaimed_vouts(address_id)\n |> add_end_height\n |> route_if_there_is_unclaimed\n |> divide(total_neo())\n end\n\n defp divide(a, b) do\n a \/ b\n end\n\n #calculate unclaimed gas bonus\n def calculate_vouts_bonus(address_id) do\n get_unclaimed_vouts(address_id)\n |> filter_end_height\n |> route_if_there_is_unclaimed_but_dont_add\n end\n\n #proceed calculus if there are unclaimed results, otherwise return 0\n def route_if_there_is_unclaimed([]) do\n 0\n end\n def route_if_there_is_unclaimed(unclaimed) do\n blocks_with_gas = get_unclaimed_block_range(unclaimed)\n |> get_blocks_gas\n\n Enum.reduce(\n unclaimed,\n 0,\n fn (vout, acc) -> acc + compute_vout_bonus(vout, blocks_with_gas) end\n )\n end\n\n #proceed calculus if there are unclaimed results, otherwise return 0\n def route_if_there_is_unclaimed_but_dont_add([]) do\n []\n end\n def route_if_there_is_unclaimed_but_dont_add(unclaimed) do\n blocks_with_gas = get_unclaimed_block_range(unclaimed)\n |> get_blocks_gas\n\n Enum.map(\n unclaimed,\n fn %{:value => value} = vout -> Map.merge(vout, %{\n :unclaimed => compute_vout_bonus(vout, blocks_with_gas),\n :value => round(value),\n }) end\n )\n end\n\n #compute bonus for a singel vout\n def compute_vout_bonus(\n %{\n :value => value,\n :start_height => start_height,\n :end_height => end_height\n },\n blocks_with_gas\n ) do\n total_gas = Enum.filter(\n blocks_with_gas,\n fn %{:index => index} ->\n index > start_height && index <= end_height end\n )\n |> Enum.reduce(0, fn (%{:gas => gas}, acc) -> acc + gas end)\n\n round(value) * total_gas\n end\n\n #get all unclaimed transaction vouts\n def get_unclaimed_vouts(address_id) do\n query = from v in Vout,\n where: v.address_id == ^address_id\n and v.claimed == false\n and v.asset == \"c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b\",\n select: map(v, [:value, :start_height, :end_height, :n, :txid])\n\n Repo.all(query)\n end\n\n def add_end_height(unclaimed_vouts) do\n Enum.map(\n unclaimed_vouts,\n fn %{:end_height => height} = vout ->\n Map.put(vout, :end_height, check_end_height(height)) end\n )\n end\n\n def filter_end_height(unclaimed_vouts) do\n Enum.filter(\n unclaimed_vouts,\n fn %{:end_height => height} ->\n height != nil end\n )\n end\n\n #get block range of unclaimed transaction vouts\n def get_unclaimed_block_range(unclaimed_vouts) do\n end_height_list = Enum.map(\n unclaimed_vouts,\n fn %{:end_height => end_height} -> check_end_height(end_height) end\n )\n\n max = end_height_list\n |> Enum.max\n\n min = Enum.map(\n unclaimed_vouts,\n fn %{:start_height => start_height} -> start_height end\n )\n |> Enum.min\n\n {min, max}\n end\n\n #check end_height and use current height when transaction vout wasn't used\n def check_end_height(nil) do\n {:ok, height} = Api.get_height\n height\n end\n def check_end_height(number) do\n number\n end\n\n #get total gas distribution amount for all blocks in a given range tuple\n def get_blocks_gas({min, max}) do\n query = from b in Block,\n where: b.index > ^min and b.index <= ^max,\n select: map(b, [:index, :total_sys_fee, :gas_generated])\n\n Repo.all(query)\n |> Enum.map(\n fn %{:index => index, :total_sys_fee => sys, :gas_generated => gen} ->\n sys = sys\n |> round()\n\n gen = gen\n |> round()\n %{:index => index, :gas => sys + gen}\n end\n )\n end\n\nend\n","old_contents":"defmodule Neoscan.Claims.Unclaimed do\n @moduledoc false\n import Ecto.Query, warn: false\n alias Decimal, as: D\n alias Neoscan.Repo\n alias Neoscan.Vouts.Vout\n alias NeoscanMonitor.Api\n alias Neoscan.Blocks.Block\n\n #total amount of available NEO\n def total_neo, do: 100_000_000\n D.set_context(%D.Context{D.get_context | precision: 10})\n\n #calculate unclaimed gas bonus\n def calculate_bonus(address_id) do\n get_unclaimed_vouts(address_id)\n |> add_end_height\n |> route_if_there_is_unclaimed\n |> divide(total_neo())\n end\n\n defp divide(a, b) do\n a \/ b\n end\n\n #calculate unclaimed gas bonus\n def calculate_vouts_bonus(address_id) do\n get_unclaimed_vouts(address_id)\n |> filter_end_height\n |> route_if_there_is_unclaimed_but_dont_add\n end\n\n #proceed calculus if there are unclaimed results, otherwise return 0\n def route_if_there_is_unclaimed([]) do\n 0\n end\n def route_if_there_is_unclaimed(unclaimed) do\n blocks_with_gas = get_unclaimed_block_range(unclaimed)\n |> get_blocks_gas\n\n Enum.reduce(\n unclaimed,\n 0,\n fn (vout, acc) -> acc + compute_vout_bonus(vout, blocks_with_gas) end\n )\n end\n\n #proceed calculus if there are unclaimed results, otherwise return 0\n def route_if_there_is_unclaimed_but_dont_add([]) do\n []\n end\n def route_if_there_is_unclaimed_but_dont_add(unclaimed) do\n blocks_with_gas = get_unclaimed_block_range(unclaimed)\n |> get_blocks_gas\n\n Enum.map(\n unclaimed,\n fn %{:value => value} = vout -> Map.merge(vout, %{\n :unclaimed => compute_vout_bonus(vout, blocks_with_gas),\n :value => round(value),\n }) end\n )\n end\n\n #compute bonus for a singel vout\n def compute_vout_bonus(\n %{\n :value => value,\n :start_height => start_height,\n :end_height => end_height\n },\n blocks_with_gas\n ) do\n total_gas = Enum.filter(\n blocks_with_gas,\n fn %{:index => index} ->\n index >= start_height && index <= end_height end\n )\n |> Enum.reduce(0, fn (%{:gas => gas}, acc) -> acc + gas end)\n\n round(value) * total_gas\n end\n\n #get all unclaimed transaction vouts\n def get_unclaimed_vouts(address_id) do\n query = from v in Vout,\n where: v.address_id == ^address_id\n and v.claimed == false\n and v.asset == \"c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b\",\n select: map(v, [:value, :start_height, :end_height, :n, :txid])\n\n Repo.all(query)\n end\n\n def add_end_height(unclaimed_vouts) do\n Enum.map(\n unclaimed_vouts,\n fn %{:end_height => height} = vout ->\n Map.put(vout, :end_height, check_end_height(height)) end\n )\n end\n\n def filter_end_height(unclaimed_vouts) do\n Enum.filter(\n unclaimed_vouts,\n fn %{:end_height => height} ->\n height != nil end\n )\n end\n\n #get block range of unclaimed transaction vouts\n def get_unclaimed_block_range(unclaimed_vouts) do\n end_height_list = Enum.map(\n unclaimed_vouts,\n fn %{:end_height => end_height} -> check_end_height(end_height) end\n )\n\n max = end_height_list\n |> Enum.max\n\n min = Enum.map(\n unclaimed_vouts,\n fn %{:start_height => start_height} -> start_height end\n )\n |> Enum.min\n\n {min, max}\n end\n\n #check end_height and use current height when transaction vout wasn't used\n def check_end_height(nil) do\n {:ok, height} = Api.get_height\n height\n end\n def check_end_height(number) do\n number\n end\n\n #get total gas distribution amount for all blocks in a given range tuple\n def get_blocks_gas({min, max}) do\n query = from b in Block,\n where: b.index > ^min and b.index <= ^max,\n select: map(b, [:index, :total_sys_fee, :gas_generated])\n\n Repo.all(query)\n |> Enum.map(\n fn %{:index => index, :total_sys_fee => sys, :gas_generated => gen} ->\n sys = sys\n |> round()\n\n gen = gen\n |> round()\n %{:index => index, :gas => sys + gen}\n end\n )\n end\n\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"7f59a10667f3c0bb869253057fd02dd54b097fee","subject":"Added new get active timer action","message":"Added new get active timer action\n","repos":"bigardone\/phoenix-toggl,bigardone\/phoenix-toggl","old_file":"web\/actions\/time_entry_actions.ex","new_file":"web\/actions\/time_entry_actions.ex","new_contents":"defmodule PhoenixToggl.TimeEntryActions do\n alias PhoenixToggl.{Repo, TimeEntry}\n\n @doc \"\"\"\n Returns the active TimeEntry for a user from the database\n \"\"\"\n def get_active_for_user(user_id) do\n TimeEntry\n |> TimeEntry.active_for_user(user_id)\n |> Repo.one\n end\n\n @doc \"\"\"\n Creates a new TimeEntry\n \"\"\"\n def start(%{user_id: user_id} = time_entry_params) do\n case get_active_for_user(user_id) do\n nil ->\n perform_start(time_entry_params)\n _time_entry_params ->\n {:error, :active_time_entry_params_exists}\n end\n end\n\n defp perform_start(time_entry_params) do\n %TimeEntry{}\n |> TimeEntry.start(time_entry_params)\n |> Repo.insert!\n end\nend\n","old_contents":"defmodule PhoenixToggl.TimeEntryActions do\n alias PhoenixToggl.{Repo, TimeEntry}\n\n def start(%{user_id: user_id} = time_entry_params) do\n TimeEntry\n |> TimeEntry.active_for_user(user_id)\n |> Repo.one\n |> case do\n nil ->\n perform_start(time_entry_params)\n _time_entry_params ->\n {:error, :active_time_entry_params_exists}\n end\n end\n\n defp perform_start(time_entry_params) do\n %TimeEntry{}\n |> TimeEntry.start(time_entry_params)\n |> Repo.insert!\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"2154f4d4c4a5b2a53e31abf780909882268a6bae","subject":"hotsort \/tags","message":"hotsort \/tags\n","repos":"hrefhref\/news,hrefhref\/news","old_file":"web\/controllers\/tag_controller.ex","new_file":"web\/controllers\/tag_controller.ex","new_contents":"defmodule News.TagController do\n use News.Web, :controller\n\n alias News.Tag\n alias News.Story\n\n plug :scrub_params, \"tag\" when action in [:create, :update]\n plug News.Plug.Authenticate, ~w(admin) when action in [:edit, :create, :update, :delete]\n\n def index(conn, _params) do\n tags = Repo.all from tag in Tag,\n left_join: taggings in assoc(tag, :taggings),\n left_join: story in assoc(taggings, :story),\n group_by: tag.id,\n order_by: fragment(\"round(cast(log(greatest(abs(?), 1)) * sign(?) + (cast(extract(epoch from ?) as integer) - 1134028003) \/ 45000.0 as numeric), 7) DESC\", sum(story.score), sum(story.score), max(story.inserted_at))\n render(conn, \"index.html\", tags: tags)\n end\n\n def show(conn, %{\"name\" => name}) do\n name = String.downcase(name)\n tag = Repo.one from t in Tag,\n where: fragment(\"lower(?)\", t.name) == ^name,\n preload: [:taggings]\n if tag do\n stories = Repo.all from story in Story,\n left_join: user in assoc(story, :user),\n left_join: comments in assoc(story, :comments),\n left_join: taggings in assoc(story, :taggings),\n left_join: tag in assoc(taggings, :tag),\n left_join: v in News.Vote, on: v.votable_id == story.id and v.votable_type == \"story\",\n where: taggings.tag_id == ^tag.id and story.score > 0,\n order_by: fragment(\"LOG(10,ABS(?)+1)*SIGN(?) + cast(extract(epoch from ?) as integer)\/300000 DESC\", story.score, story.score, story.inserted_at),\n preload: [user: user, tags: tag, comments: comments, votes: v]\n conn\n |> assign(:title, tag.name)\n |> render(\"show.html\", tag: tag, stories: stories)\n else\n error_not_found conn\n end\n end\n\n def edit(conn, %{\"id\" => id}) do\n tag = Repo.get!(Tag, id)\n changeset = Tag.changeset(tag)\n render(conn, \"edit.html\", tag: tag, changeset: changeset)\n end\n\n def update(conn, %{\"id\" => id, \"tag\" => tag_params}) do\n tag = Repo.get!(Tag, id)\n changeset = Tag.changeset(tag, tag_params)\n\n if changeset.valid? do\n Repo.update!(changeset)\n\n conn\n |> put_flash(:info, \"Tag updated successfully.\")\n |> redirect(to: tag_path(conn, :index))\n else\n render(conn, \"edit.html\", tag: tag, changeset: changeset)\n end\n end\n\n def delete(conn, %{\"id\" => id}) do\n tag = Repo.get!(Tag, id)\n Repo.delete!(tag)\n\n conn\n |> put_flash(:info, \"Tag deleted successfully.\")\n |> redirect(to: tag_path(conn, :index))\n end\nend\n","old_contents":"defmodule News.TagController do\n use News.Web, :controller\n\n alias News.Tag\n alias News.Story\n\n plug :scrub_params, \"tag\" when action in [:create, :update]\n plug News.Plug.Authenticate, ~w(admin) when action in [:edit, :create, :update, :delete]\n\n def index(conn, _params) do\n tags = Repo.all(Tag)\n render(conn, \"index.html\", tags: tags)\n end\n\n def show(conn, %{\"name\" => name}) do\n name = String.downcase(name)\n tag = Repo.one from t in Tag,\n where: fragment(\"lower(?)\", t.name) == ^name,\n preload: [:taggings]\n if tag do\n stories = Repo.all from story in Story,\n left_join: user in assoc(story, :user),\n left_join: comments in assoc(story, :comments),\n left_join: taggings in assoc(story, :taggings),\n left_join: tag in assoc(taggings, :tag),\n left_join: v in News.Vote, on: v.votable_id == story.id and v.votable_type == \"story\",\n where: taggings.tag_id == ^tag.id and story.score > 0,\n order_by: fragment(\"LOG(10,ABS(?)+1)*SIGN(?) + cast(extract(epoch from ?) as integer)\/300000 DESC\", story.score, story.score, story.inserted_at),\n preload: [user: user, tags: tag, comments: comments, votes: v]\n conn\n |> assign(:title, tag.name)\n |> render(\"show.html\", tag: tag, stories: stories)\n else\n error_not_found conn\n end\n end\n\n def edit(conn, %{\"id\" => id}) do\n tag = Repo.get!(Tag, id)\n changeset = Tag.changeset(tag)\n render(conn, \"edit.html\", tag: tag, changeset: changeset)\n end\n\n def update(conn, %{\"id\" => id, \"tag\" => tag_params}) do\n tag = Repo.get!(Tag, id)\n changeset = Tag.changeset(tag, tag_params)\n\n if changeset.valid? do\n Repo.update!(changeset)\n\n conn\n |> put_flash(:info, \"Tag updated successfully.\")\n |> redirect(to: tag_path(conn, :index))\n else\n render(conn, \"edit.html\", tag: tag, changeset: changeset)\n end\n end\n\n def delete(conn, %{\"id\" => id}) do\n tag = Repo.get!(Tag, id)\n Repo.delete!(tag)\n\n conn\n |> put_flash(:info, \"Tag deleted successfully.\")\n |> redirect(to: tag_path(conn, :index))\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"29a6ef17aa1e073990601560b06028c6eb0eb790","subject":"Version 0.14.7","message":"Version 0.14.7\n","repos":"keichan34\/exrm,HashNuke\/exrm,ymmtmsys\/exrm,bitwalker\/exrm,coonce\/exrm,liveforeverx\/exrm,GalaxyGorilla\/exrm,adam12\/exrm,appunite\/exrm,ContentSafe\/exrm,thz\/exrm,MSNexploder\/exrm,manukall\/exrm,skirino\/exrm,beni55\/exrm,xerions\/exrm,umatomba\/exrm","old_file":"mix.exs","new_file":"mix.exs","new_contents":"docs_task = \"tasks\/docs.exs\"\nif File.exists?(docs_task) do\n Code.eval_file \"tasks\/docs.exs\"\nend\n\ndefmodule ReleaseManager.Mixfile do\n use Mix.Project\n\n def project do\n [ app: :exrm,\n version: \"0.14.7\",\n elixir: \"~> 1.0.0\",\n description: description,\n package: package,\n deps: [{:conform, \"~> 0.10.4\"}] ]\n end\n\n def application, do: []\n\n defp description do\n \"\"\"\n Exrm, or Elixir Release Manager, provides mix tasks for building, \n upgrading, and controlling release packages for your application.\n \"\"\"\n end\n\n defp package do\n [ files: [\"lib\", \"priv\", \"mix.exs\", \"README.md\", \"LICENSE\"],\n contributors: [\"Paul Schoenfelder\"],\n licenses: [\"MIT\"],\n links: %{ \"GitHub\": \"https:\/\/github.com\/bitwalker\/exrm\" } ]\n end\n\nend\n","old_contents":"docs_task = \"tasks\/docs.exs\"\nif File.exists?(docs_task) do\n Code.eval_file \"tasks\/docs.exs\"\nend\n\ndefmodule ReleaseManager.Mixfile do\n use Mix.Project\n\n def project do\n [ app: :exrm,\n version: \"0.14.6\",\n elixir: \"~> 1.0.0\",\n description: description,\n package: package,\n deps: [{:conform, \"~> 0.10.4\"}] ]\n end\n\n def application, do: []\n\n defp description do\n \"\"\"\n Exrm, or Elixir Release Manager, provides mix tasks for building, \n upgrading, and controlling release packages for your application.\n \"\"\"\n end\n\n defp package do\n [ files: [\"lib\", \"priv\", \"mix.exs\", \"README.md\", \"LICENSE\"],\n contributors: [\"Paul Schoenfelder\"],\n licenses: [\"MIT\"],\n links: %{ \"GitHub\": \"https:\/\/github.com\/bitwalker\/exrm\" } ]\n end\n\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"a723b197b7f92859194bf906722b3859f99b805d","subject":"Use aliases and explicit parens in mix.exs","message":"Use aliases and explicit parens in mix.exs","repos":"nerves-project\/nerves,nerves-project\/nerves","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Nerves.Mixfile do\n use Mix.Project\n\n def project do\n [app: :nerves,\n name: \"Nerves\",\n source_url: \"https:\/\/github.com\/nerves-project\/nerves\",\n homepage_url: \"http:\/\/nerves-project.org\/\",\n version: \"0.3.2\",\n elixir: \"~> 1.2.4 or ~> 1.3.0-dev\",\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n deps: deps(),\n description: description(),\n package: package(),\n aliases: [\"docs\": [\"docs\", ©_images\/1]],\n docs: docs()]\n end\n\n def application do\n []\n end\n\n defp deps do\n [\n {:exrm, \"~> 1.0.4\"},\n {:earmark, \"~> 0.1\", only: :dev},\n {:ex_doc, \"~> 0.11\", only: :dev},\n {:porcelain, \"~> 2.0\"}\n ]\n end\n\n defp docs do\n [main: \"getting-started\",\n logo: \"resources\/logo.png\",\n extras: [\n \"docs\/Installation.md\",\n \"docs\/Getting Started.md\",\n \"docs\/Targets.md\",\n \"docs\/Systems.md\",\n \"docs\/User Interfaces.md\",\n \"docs\/Advanced Configuration.md\"\n ]]\n end\n\n # Copy the images referenced by docs, since ex_doc doesn't do this.\n defp copy_images(_) do\n File.cp_r \"resources\", \"doc\/resources\"\n end\n\n defp description do\n \"\"\"\n Nerves - Create firmware for embedded devices like Raspberry Pi, BeagleBone Black, and more\n \"\"\"\n end\n\n defp package do\n [maintainers: [\"Frank Hunleth\", \"Garth Hitchens\", \"Justin Schneck\", \"Greg Mefford\"],\n licenses: [\"Apache 2.0\"],\n links: %{\"Github\" => \"https:\/\/github.com\/nerves-project\/nerves\"}]\n end\nend\n","old_contents":"defmodule Mix.Tasks.CopyImages do\n @shortdoc \"Copy the images referenced by docs, since ex_doc doesn't do this.\"\n use Mix.Task\n def run(_) do\n File.cp_r \"resources\", \"doc\/resources\"\n end\nend\n\n\ndefmodule Nerves.Mixfile do\n use Mix.Project\n\n def project do\n [app: :nerves,\n name: \"Nerves\",\n source_url: \"https:\/\/github.com\/nerves-project\/nerves\",\n homepage_url: \"http:\/\/nerves-project.org\/\",\n version: \"0.3.2\",\n elixir: \"~> 1.2.4 or ~> 1.3.0-dev\",\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n deps: deps,\n description: description,\n package: package,\n aliases: [\"docs\": [\"docs\", \"copy_images\"]],\n docs: docs]\n end\n\n def application do\n []\n end\n\n defp deps do\n [\n {:exrm, \"~> 1.0.4\"},\n {:earmark, \"~> 0.1\", only: :dev},\n {:ex_doc, \"~> 0.11\", only: :dev},\n {:porcelain, \"~> 2.0\"}\n ]\n end\n\n defp docs do\n [main: \"getting-started\",\n logo: \"resources\/logo.png\",\n extras: [\n \"docs\/Installation.md\",\n \"docs\/Getting Started.md\",\n \"docs\/Targets.md\",\n \"docs\/Systems.md\",\n \"docs\/User Interfaces.md\",\n \"docs\/Advanced Configuration.md\"\n ]]\n end\n\n defp description do\n \"\"\"\n Nerves - Create firmware for embedded devices like Raspberry Pi, BeagleBone Black, and more\n \"\"\"\n end\n\n defp package do\n [maintainers: [\"Frank Hunleth\", \"Garth Hitchens\", \"Justin Schneck\", \"Greg Mefford\"],\n licenses: [\"Apache 2.0\"],\n links: %{\"Github\" => \"https:\/\/github.com\/nerves-project\/nerves\"}]\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"517ef558356d631450f4487897f7798028519471","subject":"Fix mix.exs","message":"Fix mix.exs\n","repos":"knmsyk\/cazoc,cazoc\/cazoc,cazoc\/cazoc,cazoc\/cazoc,knmsyk\/cazoc,knmsyk\/cazoc","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Cazoc.Mixfile do\n use Mix.Project\n\n def project do\n [app: :cazoc,\n version: \"0.2.1\",\n elixir: \"~> 1.3.2\",\n elixirc_paths: elixirc_paths(Mix.env),\n compilers: [:phoenix, :gettext] ++ Mix.compilers,\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n aliases: aliases,\n deps: deps]\n end\n\n # Configuration for the OTP application.\n #\n # Type `mix help compile.app` for more information.\n def application do\n [mod: {Cazoc, []},\n applications: [:comeonin,\n :connection,\n :cowboy,\n :ex_admin,\n :gettext,\n :git_cli,\n :logger,\n :pandex,\n :phoenix, :phoenix_ecto, :phoenix_html, :phoenix_slime,\n :postgrex,\n :scrivener,\n :ssl,\n :tentacat,\n :timex,\n :timex_ecto,\n :tzdata,\n :secure_random,\n :ueberauth,\n :ueberauth_github]]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"web\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\", \"web\"]\n\n defp deps do\n [{:phoenix, \"~> 1.2.1\"},\n {:phoenix_ecto, \"~> 3.0.1\"},\n {:postgrex, \">= 0.0.0\"},\n {:phoenix_html, \"~> 2.6\"},\n {:phoenix_slime, \"~> 0.7\"},\n {:phoenix_live_reload, \"~> 1.0\", only: :dev},\n {:cowboy, \"~> 1.0\"},\n {:comeonin, \"~> 2.5\"},\n {:ecto, \"~> 1.1 or ~> 2.0\", [optional: false, hex: :ecto, manager: :mix, override: true]},\n {:exrm, \"~> 1.0\"},\n {:ex_admin, github: \"smpallen99\/ex_admin\"},\n {:gettext, \"~> 0.11\"},\n {:git_cli, \"~> 0.2\"},\n {:pandex, \"~> 0.1.0\"},\n {:tentacat, \"~> 0.5\"},\n {:timex, \"~> 3.0\"},\n {:timex_ecto, \"~> 3.0\"},\n {:secure_random, \"~> 0.5\"},\n {:ueberauth, \"~> 0.3\"},\n {:ueberauth_github, \"~> 0.2\"}\n ]\n end\n\n defp aliases do\n [\"ecto.setup\": [\"ecto.create\", \"ecto.migrate\", \"run priv\/repo\/seeds.exs\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"]]\n end\nend\n","old_contents":"defmodule Cazoc.Mixfile do\n use Mix.Project\n\n def project do\n [app: :cazoc,\n version: \"0.2.1\",\n elixir: \"~> 1.3.2\",\n elixirc_paths: elixirc_paths(Mix.env),\n compilers: [:phoenix, :gettext] ++ Mix.compilers,\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n aliases: aliases,\n deps: deps]\n end\n\n # Configuration for the OTP application.\n #\n # Type `mix help compile.app` for more information.\n def application do\n [mod: {Cazoc, []},\n applications: [:comeonin,\n :connection,\n :cowboy,\n :ex_admin,\n :gettext,\n :git_cli,\n :logger,\n :pandex,\n :phoenix, :phoenix_ecto, :phoenix_html, :phoenix_slime, :phoenix_live_reload,\n :postgrex,\n :scrivener,\n :ssl,\n :tentacat,\n :timex,\n :timex_ecto,\n :tzdata,\n :secure_random,\n :ueberauth,\n :ueberauth_github]]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"web\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\", \"web\"]\n\n defp deps do\n [{:phoenix, \"~> 1.2.1\"},\n {:phoenix_ecto, \"~> 3.0.1\"},\n {:postgrex, \">= 0.0.0\"},\n {:phoenix_html, \"~> 2.6\"},\n {:phoenix_slime, \"~> 0.7\"},\n {:phoenix_live_reload, \"~> 1.0\", only: :dev},\n {:cowboy, \"~> 1.0\"},\n {:comeonin, \"~> 2.5\"},\n {:ecto, \"~> 1.1 or ~> 2.0\", [optional: false, hex: :ecto, manager: :mix, override: true]},\n {:exrm, \"~> 1.0\"},\n {:ex_admin, github: \"smpallen99\/ex_admin\"},\n {:gettext, \"~> 0.11\"},\n {:git_cli, \"~> 0.2\"},\n {:pandex, \"~> 0.1.0\"},\n {:tentacat, \"~> 0.5\"},\n {:timex, \"~> 3.0\"},\n {:timex_ecto, \"~> 3.0\"},\n {:secure_random, \"~> 0.5\"},\n {:ueberauth, \"~> 0.3\"},\n {:ueberauth_github, \"~> 0.2\"}\n ]\n end\n\n defp aliases do\n [\"ecto.setup\": [\"ecto.create\", \"ecto.migrate\", \"run priv\/repo\/seeds.exs\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"]]\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"4eed24d5a80cc3170b75fcf7bda7d47d92372834","subject":"bump version to 1.0.5","message":"bump version to 1.0.5\n\n- it removes some deprecation warnings\n","repos":"ma2gedev\/breadcrumble_ex","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Breadcrumble.Mixfile do\n use Mix.Project\n\n def project do\n [\n app: :breadcrumble,\n version: \"1.0.5\",\n elixir: \"~> 1.9\",\n description: \"Elixir port of Breadcrumble library\",\n package: [\n maintainers: [\"Takayuki Matsubara\"],\n licenses: [\"MIT\"],\n links: %{\"GitHub\" => \"https:\/\/github.com\/ma2gedev\/breadcrumble_ex\"}\n ],\n build_embedded: Mix.env() == :prod,\n start_permanent: Mix.env() == :prod,\n deps: deps()\n ]\n end\n\n # Configuration for the OTP application\n #\n # Type `mix help compile.app` for more information\n def application do\n [extra_applications: [:logger, :eex]]\n end\n\n # Dependencies can be Hex packages:\n #\n # {:mydep, \"~> 0.3.0\"}\n #\n # Or git\/path repositories:\n #\n # {:mydep, git: \"https:\/\/github.com\/elixir-lang\/mydep.git\", tag: \"0.1.0\"}\n #\n # Type `mix help deps` for more examples and options\n defp deps do\n [\n {:plug, \">= 0.12.0 and < 2.0.0\"},\n {:power_assert, \"~> 0.3.0\", only: :test}\n ]\n end\nend\n","old_contents":"defmodule Breadcrumble.Mixfile do\n use Mix.Project\n\n def project do\n [\n app: :breadcrumble,\n version: \"1.0.4\",\n elixir: \"~> 1.9\",\n description: \"Elixir port of Breadcrumble library\",\n package: [\n maintainers: [\"Takayuki Matsubara\"],\n licenses: [\"MIT\"],\n links: %{\"GitHub\" => \"https:\/\/github.com\/ma2gedev\/breadcrumble_ex\"}\n ],\n build_embedded: Mix.env() == :prod,\n start_permanent: Mix.env() == :prod,\n deps: deps()\n ]\n end\n\n # Configuration for the OTP application\n #\n # Type `mix help compile.app` for more information\n def application do\n [extra_applications: [:logger, :eex]]\n end\n\n # Dependencies can be Hex packages:\n #\n # {:mydep, \"~> 0.3.0\"}\n #\n # Or git\/path repositories:\n #\n # {:mydep, git: \"https:\/\/github.com\/elixir-lang\/mydep.git\", tag: \"0.1.0\"}\n #\n # Type `mix help deps` for more examples and options\n defp deps do\n [\n {:plug, \">= 0.12.0 and < 2.0.0\"},\n {:power_assert, \"~> 0.3.0\", only: :test}\n ]\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"ea7f8c793d848254ee2363d125dad83f558e7f98","subject":"Increment version [ci skip]","message":"Increment version [ci skip]\n","repos":"Nebo15\/annon.api,Nebo15\/annon.api","old_file":"mix.exs","new_file":"mix.exs","new_contents":"defmodule Gateway.Mixfile do\n use Mix.Project\n\n @version \"0.1.20\"\n\n def project do\n [app: :gateway,\n description: \"Add description to your package.\",\n package: package(),\n version: @version,\n elixir: \"~> 1.3\",\n elixirc_paths: elixirc_paths(Mix.env),\n compilers: [] ++ Mix.compilers,\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n aliases: aliases(),\n deps: deps(),\n test_coverage: [tool: ExCoveralls],\n preferred_cli_env: [coveralls: :test],\n docs: [source_ref: \"v#\\{@version\\}\", main: \"readme\", extras: [\"README.md\"]]]\n end\n\n # Configuration for the OTP application\n #\n # Type \"mix help compile.app\" for more information\n def application do\n [\n applications: [:logger, :confex, :cowboy, :plug, :postgrex, :ecto, :ecto_enum, :timex, :joken, :nex_json_schema,\n :poison, :httpoison, :ex_statsd, :libcluster, :eview],\n mod: {Gateway, []}\n ]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\"]\n\n # Dependencies can be Hex packages:\n #\n # {:mydep, \"~> 0.3.0\"}\n #\n # Or git\/path repositories:\n #\n # {:mydep, git: \"https:\/\/github.com\/elixir-lang\/mydep.git\", tag: \"0.1.0\"}\n #\n # To depend on another app inside the umbrella:\n #\n # {:myapp, in_umbrella: true}\n #\n # Type \"mix help deps\" for more examples and options\n defp deps do\n [{:distillery, \"~> 0.10.1\"},\n {:libcluster, github: \"gmile\/libcluster\", branch: \"master\"},\n {:confex, \"~> 1.4.2\"},\n {:plug, \">= 0.0.0\"},\n {:cowboy, \">= 0.0.0\"},\n {:postgrex, \">= 0.0.0\", override: true},\n {:ecto, \">= 2.1.0-rc.3\", override: true},\n {:ecto_enum, git: \"https:\/\/github.com\/gjaldon\/ecto_enum\", branch: \"ecto-2.0\", override: true},\n {:timex, \"~> 3.0\"},\n {:poison, \"~> 2.0\"},\n {:joken, \"~> 1.3\"},\n {:nex_json_schema, \"~> 0.5.1\"},\n {:httpoison, \">= 0.0.0\"},\n {:httpoison, \">= 0.0.0\"},\n {:ex_statsd, \">= 0.5.1\"},\n {:eview, \">= 0.0.0\"},\n {:faker, \"~> 0.7.0\", only: [:dev, :test]},\n {:dogma, \"> 0.1.0\", only: [:dev, :test]},\n {:benchfella, \"~> 0.3\", only: [:dev, :test]},\n {:ex_doc, \">= 0.0.0\", only: [:dev, :test]},\n {:excoveralls, \"~> 0.5\", only: [:dev, :test]},\n {:credo, \">= 0.4.8\", only: [:dev, :test]},\n ]\n end\n\n # Settings for publishing in Hex package manager:\n defp package do\n [contributors: [\"Nebo #15\"],\n maintainers: [\"Nebo #15\"],\n licenses: [\"LISENSE.md\"],\n links: %{github: \"https:\/\/github.com\/Nebo15\/os.gateway\"},\n files: ~w(lib LICENSE.md mix.exs README.md)]\n end\n\n defp aliases do\n [\"ecto.setup\": [\"ecto.create --quiet\",\n \"ecto.migrate\",\n \"run priv\/repos\/seeds.exs\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"],\n \"test\": [\"ecto.create --quiet\",\n \"ecto.migrate\",\n \"test\"]]\n end\nend\n","old_contents":"defmodule Gateway.Mixfile do\n use Mix.Project\n\n @version \"0.1.19\"\n\n def project do\n [app: :gateway,\n description: \"Add description to your package.\",\n package: package(),\n version: @version,\n elixir: \"~> 1.3\",\n elixirc_paths: elixirc_paths(Mix.env),\n compilers: [] ++ Mix.compilers,\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n aliases: aliases(),\n deps: deps(),\n test_coverage: [tool: ExCoveralls],\n preferred_cli_env: [coveralls: :test],\n docs: [source_ref: \"v#\\{@version\\}\", main: \"readme\", extras: [\"README.md\"]]]\n end\n\n # Configuration for the OTP application\n #\n # Type \"mix help compile.app\" for more information\n def application do\n [\n applications: [:logger, :confex, :cowboy, :plug, :postgrex, :ecto, :ecto_enum, :timex, :joken, :nex_json_schema,\n :poison, :httpoison, :ex_statsd, :libcluster, :eview],\n mod: {Gateway, []}\n ]\n end\n\n # Specifies which paths to compile per environment.\n defp elixirc_paths(:test), do: [\"lib\", \"test\/support\"]\n defp elixirc_paths(_), do: [\"lib\"]\n\n # Dependencies can be Hex packages:\n #\n # {:mydep, \"~> 0.3.0\"}\n #\n # Or git\/path repositories:\n #\n # {:mydep, git: \"https:\/\/github.com\/elixir-lang\/mydep.git\", tag: \"0.1.0\"}\n #\n # To depend on another app inside the umbrella:\n #\n # {:myapp, in_umbrella: true}\n #\n # Type \"mix help deps\" for more examples and options\n defp deps do\n [{:distillery, \"~> 0.10.1\"},\n {:libcluster, github: \"gmile\/libcluster\", branch: \"master\"},\n {:confex, \"~> 1.4.2\"},\n {:plug, \">= 0.0.0\"},\n {:cowboy, \">= 0.0.0\"},\n {:postgrex, \">= 0.0.0\", override: true},\n {:ecto, \">= 2.1.0-rc.3\", override: true},\n {:ecto_enum, git: \"https:\/\/github.com\/gjaldon\/ecto_enum\", branch: \"ecto-2.0\", override: true},\n {:timex, \"~> 3.0\"},\n {:poison, \"~> 2.0\"},\n {:joken, \"~> 1.3\"},\n {:nex_json_schema, \"~> 0.5.1\"},\n {:httpoison, \">= 0.0.0\"},\n {:httpoison, \">= 0.0.0\"},\n {:ex_statsd, \">= 0.5.1\"},\n {:eview, \">= 0.0.0\"},\n {:faker, \"~> 0.7.0\", only: [:dev, :test]},\n {:dogma, \"> 0.1.0\", only: [:dev, :test]},\n {:benchfella, \"~> 0.3\", only: [:dev, :test]},\n {:ex_doc, \">= 0.0.0\", only: [:dev, :test]},\n {:excoveralls, \"~> 0.5\", only: [:dev, :test]},\n {:credo, \">= 0.4.8\", only: [:dev, :test]},\n ]\n end\n\n # Settings for publishing in Hex package manager:\n defp package do\n [contributors: [\"Nebo #15\"],\n maintainers: [\"Nebo #15\"],\n licenses: [\"LISENSE.md\"],\n links: %{github: \"https:\/\/github.com\/Nebo15\/os.gateway\"},\n files: ~w(lib LICENSE.md mix.exs README.md)]\n end\n\n defp aliases do\n [\"ecto.setup\": [\"ecto.create --quiet\",\n \"ecto.migrate\",\n \"run priv\/repos\/seeds.exs\"],\n \"ecto.reset\": [\"ecto.drop\", \"ecto.setup\"],\n \"test\": [\"ecto.create --quiet\",\n \"ecto.migrate\",\n \"test\"]]\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"8715ecbffb95d8322479faf72b223a038a35588a","subject":"test unclaimed","message":"test unclaimed\n","repos":"mbenatti\/neo-scan,mbenatti\/neo-scan,mbenatti\/neo-scan","old_file":"apps\/neoscan\/lib\/neoscan\/claims\/unclaimed.ex","new_file":"apps\/neoscan\/lib\/neoscan\/claims\/unclaimed.ex","new_contents":"defmodule Neoscan.Claims.Unclaimed do\n @moduledoc false\n import Ecto.Query, warn: false\n alias Decimal, as: D\n alias Neoscan.Repo\n alias Neoscan.Vouts.Vout\n alias NeoscanMonitor.Api\n alias Neoscan.Blocks.Block\n alias Neoscan.Helpers\n\n #total amount of available NEO\n def total_neo, do: 100_000_000\n D.set_context(%D.Context{D.get_context | precision: 10})\n\n #calculate unclaimed gas bonus\n def calculate_bonus(address_id) do\n get_unclaimed_vouts(address_id)\n |> add_end_height\n |> route_if_there_is_unclaimed\n |> Helpers.round_or_not()\n end\n\n #calculate unclaimed gas bonus\n def calculate_vouts_bonus(address_id) do\n get_unclaimed_vouts(address_id)\n |> filter_end_height\n |> route_if_there_is_unclaimed_but_dont_add\n end\n\n #proceed calculus if there are unclaimed results, otherwise return 0\n def route_if_there_is_unclaimed([]) do\n 0\n end\n def route_if_there_is_unclaimed(unclaimed) do\n blocks_with_gas = get_unclaimed_block_range(unclaimed)\n |> get_blocks_gas\n\n Enum.reduce(\n unclaimed,\n 0,\n fn (vout, acc) -> acc + compute_vout_bonus(vout, blocks_with_gas) end\n )\n end\n\n #proceed calculus if there are unclaimed results, otherwise return 0\n def route_if_there_is_unclaimed_but_dont_add([]) do\n []\n end\n def route_if_there_is_unclaimed_but_dont_add(unclaimed) do\n blocks_with_gas = get_unclaimed_block_range(unclaimed)\n |> get_blocks_gas\n\n Enum.map(\n unclaimed,\n fn %{:value => value} = vout -> Map.merge(vout, %{\n :unclaimed => compute_vout_bonus(vout, blocks_with_gas),\n :value => Helpers.round_or_not(value),\n }) end\n )\n end\n\n #compute bonus for a singel vout\n def compute_vout_bonus(\n %{\n :value => value,\n :start_height => start_height,\n :end_height => end_height\n },\n blocks_with_gas\n ) do\n total_gas = Enum.filter(\n blocks_with_gas,\n fn %{:index => index} ->\n index >= start_height && index <= end_height end\n )\n |> Enum.reduce(0, fn (%{:gas => gas}, acc) -> acc + gas end)\n\n D.mult(D.new(value), D.new(total_gas))\n |> D.div(D.new(100_000_000))\n |> D.to_float()\n end\n\n #get all unclaimed transaction vouts\n def get_unclaimed_vouts(address_id) do\n query = from v in Vout,\n where: v.address_id == ^address_id\n and v.claimed == false\n and v.asset == \"c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b\",\n select: map(v, [:value, :start_height, :end_height, :n, :txid])\n\n Repo.all(query)\n end\n\n def add_end_height(unclaimed_vouts) do\n Enum.map(\n unclaimed_vouts,\n fn %{:end_height => height} = vout ->\n Map.put(vout, :end_height, check_end_height(height)) end\n )\n end\n\n def filter_end_height(unclaimed_vouts) do\n Enum.filter(\n unclaimed_vouts,\n fn %{:end_height => height} ->\n height != nil end\n )\n end\n\n #get block range of unclaimed transaction vouts\n def get_unclaimed_block_range(unclaimed_vouts) do\n end_height_list = Enum.map(\n unclaimed_vouts,\n fn %{:end_height => end_height} -> check_end_height(end_height) end\n )\n\n max = end_height_list\n |> Enum.max\n\n min = Enum.map(\n unclaimed_vouts,\n fn %{:start_height => start_height} -> start_height end\n )\n |> Enum.min\n\n {min, max}\n end\n\n #check end_height and use current height when transaction vout wasn't used\n def check_end_height(nil) do\n {:ok, height} = Api.get_height\n height\n end\n def check_end_height(number) do\n number\n end\n\n #get total gas distribution amount for all blocks in a given range tuple\n def get_blocks_gas({min, max}) do\n query = from b in Block,\n where: b.index >= ^min and b.index <= ^max,\n select: map(b, [:index, :total_sys_fee, :gas_generated])\n\n Repo.all(query)\n |> Enum.map(\n fn %{:index => index, :total_sys_fee => sys, :gas_generated => gen} ->\n sys = sys\n |> round()\n\n gen = gen\n |> round\n %{:index => index, :gas => sys + gen}\n end\n )\n end\n\nend\n","old_contents":"defmodule Neoscan.Claims.Unclaimed do\n @moduledoc false\n import Ecto.Query, warn: false\n alias Decimal, as: D\n alias Neoscan.Repo\n alias Neoscan.Vouts.Vout\n alias NeoscanMonitor.Api\n alias Neoscan.Blocks.Block\n alias Neoscan.Helpers\n\n #total amount of available NEO\n def total_neo, do: 100_000_000\n D.set_context(%D.Context{D.get_context | precision: 10})\n\n #calculate unclaimed gas bonus\n def calculate_bonus(address_id) do\n get_unclaimed_vouts(address_id)\n |> add_end_height\n |> route_if_there_is_unclaimed\n |> Helpers.round_or_not()\n end\n\n #calculate unclaimed gas bonus\n def calculate_vouts_bonus(address_id) do\n get_unclaimed_vouts(address_id)\n |> filter_end_height\n |> route_if_there_is_unclaimed_but_dont_add\n end\n\n #proceed calculus if there are unclaimed results, otherwise return 0\n def route_if_there_is_unclaimed([]) do\n 0\n end\n def route_if_there_is_unclaimed(unclaimed) do\n blocks_with_gas = get_unclaimed_block_range(unclaimed)\n |> get_blocks_gas\n\n Enum.reduce(\n unclaimed,\n 0,\n fn (vout, acc) -> acc + compute_vout_bonus(vout, blocks_with_gas) end\n )\n end\n\n #proceed calculus if there are unclaimed results, otherwise return 0\n def route_if_there_is_unclaimed_but_dont_add([]) do\n []\n end\n def route_if_there_is_unclaimed_but_dont_add(unclaimed) do\n blocks_with_gas = get_unclaimed_block_range(unclaimed)\n |> get_blocks_gas\n\n Enum.map(\n unclaimed,\n fn %{:value => value} = vout -> Map.merge(vout, %{\n :unclaimed => compute_vout_bonus(vout, blocks_with_gas),\n :value => Helpers.round_or_not(value),\n }) end\n )\n end\n\n #compute bonus for a singel vout\n def compute_vout_bonus(\n %{\n :value => value,\n :start_height => start_height,\n :end_height => end_height\n },\n blocks_with_gas\n ) do\n total_gas = Enum.filter(\n blocks_with_gas,\n fn %{:index => index} ->\n index >= start_height && index <= end_height end\n )\n |> Enum.reduce(0, fn (%{:gas => gas}, acc) -> acc + gas end)\n\n fact = D.div(D.new(value), D.new(total_neo()))\n\n D.mult(D.new(total_gas), D.new(fact))\n |> D.div(D.new(100_000_000))\n |> D.to_float()\n end\n\n #get all unclaimed transaction vouts\n def get_unclaimed_vouts(address_id) do\n query = from v in Vout,\n where: v.address_id == ^address_id\n and v.claimed == false\n and v.asset == \"c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b\",\n select: map(v, [:value, :start_height, :end_height, :n, :txid])\n\n Repo.all(query)\n end\n\n def add_end_height(unclaimed_vouts) do\n Enum.map(\n unclaimed_vouts,\n fn %{:end_height => height} = vout ->\n Map.put(vout, :end_height, check_end_height(height)) end\n )\n end\n\n def filter_end_height(unclaimed_vouts) do\n Enum.filter(\n unclaimed_vouts,\n fn %{:end_height => height} ->\n height != nil end\n )\n end\n\n #get block range of unclaimed transaction vouts\n def get_unclaimed_block_range(unclaimed_vouts) do\n end_height_list = Enum.map(\n unclaimed_vouts,\n fn %{:end_height => end_height} -> check_end_height(end_height) end\n )\n\n max = end_height_list\n |> Enum.max\n\n min = Enum.map(\n unclaimed_vouts,\n fn %{:start_height => start_height} -> start_height end\n )\n |> Enum.min\n\n {min, max}\n end\n\n #check end_height and use current height when transaction vout wasn't used\n def check_end_height(nil) do\n {:ok, height} = Api.get_height\n height\n end\n def check_end_height(number) do\n number\n end\n\n #get total gas distribution amount for all blocks in a given range tuple\n def get_blocks_gas({min, max}) do\n query = from b in Block,\n where: b.index >= ^min and b.index <= ^max,\n select: map(b, [:index, :total_sys_fee, :gas_generated])\n\n Repo.all(query)\n |> Enum.map(\n fn %{:index => index, :total_sys_fee => sys, :gas_generated => gen} ->\n sys = sys * 100_000_000\n |> round()\n\n gen = gen * 100_000_000\n |> round\n %{:index => index, :gas => sys + gen}\n end\n )\n end\n\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"9bf9656f83aef2a878e562a75063bc49e7fec178","subject":"Ensure logs are silenced on endpoint test.","message":"Ensure logs are silenced on endpoint test.\n","repos":"bsmr-erlang\/phoenix,Gazler\/phoenix,rafbgarcia\/phoenix,mschae\/phoenix,pap\/phoenix,CultivateHQ\/phoenix,wsmoak\/phoenix,dmarkow\/phoenix,nshafer\/phoenix,pap\/phoenix,trarbr\/phoenix,Ben-Evolently\/phoenix,mitchellhenke\/phoenix,Joe-noh\/phoenix,jamilabreu\/phoenix,jamilabreu\/phoenix,optikfluffel\/phoenix,0x00evil\/phoenix,Kosmas\/phoenix,korobkov\/phoenix,korobkov\/phoenix,mobileoverlord\/phoenix,gjaldon\/phoenix,ybur-yug\/phoenix,cas27\/phoenix,evax\/phoenix,rafbgarcia\/phoenix,mschae\/phoenix,nshafer\/phoenix,mitchellhenke\/phoenix,CultivateHQ\/phoenix,iStefo\/phoenix,evax\/phoenix,rafbgarcia\/phoenix,eksperimental\/phoenix,keathley\/phoenix,ericmj\/phoenix,0x00evil\/phoenix,ephe-meral\/phoenix,jwarwick\/phoenix,stevedomin\/phoenix,michalmuskala\/phoenix,bsmr-erlang\/phoenix,iStefo\/phoenix,michalmuskala\/phoenix,phoenixframework\/phoenix,nshafer\/phoenix,Kosmas\/phoenix,ericmj\/phoenix,phoenixframework\/phoenix,phoenixframework\/phoenix,optikfluffel\/phoenix,gjaldon\/phoenix,0x00evil\/phoenix,cas27\/phoenix,eksperimental\/phoenix,keathley\/phoenix,dmarkow\/phoenix,ybur-yug\/phoenix,Joe-noh\/phoenix,optikfluffel\/phoenix,stevedomin\/phoenix,wsmoak\/phoenix,Gazler\/phoenix,mobileoverlord\/phoenix,ephe-meral\/phoenix,jwarwick\/phoenix,trarbr\/phoenix","old_file":"test\/phoenix\/integration\/endpoint_test.exs","new_file":"test\/phoenix\/integration\/endpoint_test.exs","new_contents":"Code.require_file \"..\/..\/support\/http_client.exs\", __DIR__\n\ndefmodule Phoenix.Integration.EndpointTest do\n # Cannot run async because of serve endpoints\n use ExUnit.Case\n import ExUnit.CaptureLog\n\n alias Phoenix.Integration.AdapterTest.ProdEndpoint\n alias Phoenix.Integration.AdapterTest.DevEndpoint\n\n Application.put_env(:endpoint_int, ProdEndpoint,\n http: [port: \"4807\"], url: [host: \"example.com\"], server: true)\n Application.put_env(:endpoint_int, DevEndpoint,\n http: [port: \"4808\"], debug_errors: true)\n\n defmodule Router do\n @moduledoc \"\"\"\n Let's use a plug router to test this endpoint.\n \"\"\"\n use Plug.Router\n\n plug :match\n plug :dispatch\n\n get \"\/\" do\n send_resp conn, 200, \"ok\"\n end\n\n get \"\/router\/oops\" do\n _ = conn\n raise \"oops\"\n end\n\n match _ do\n raise Phoenix.Router.NoRouteError, conn: conn, router: __MODULE__\n end\n end\n\n defmodule Wrapper do\n @moduledoc \"\"\"\n A wrapper around the endpoint call to extract information.\n\n This exists so we can verify that the exception handling\n in the Phoenix endpoint is working as expected. In order\n to do that, we need to wrap the endpoint.call\/2 in a\n before compile callback so it wraps the whole stack,\n including render errors and debug errors functionality.\n \"\"\"\n\n defmacro __before_compile__(_) do\n quote do\n defoverridable [call: 2]\n\n def call(conn, opts) do\n # Assert we never have a lingering sent message in the inbox\n refute_received {:plug_conn, :sent}\n\n try do\n super(conn, opts)\n after\n # When we pipe downstream, downstream will always render,\n # either because the router is responding or because the\n # endpoint error layer is kicking in.\n assert_received {:plug_conn, :sent}\n send self(), {:plug_conn, :sent}\n end\n end\n end\n end\n end\n\n for mod <- [ProdEndpoint, DevEndpoint] do\n defmodule mod do\n use Phoenix.Endpoint, otp_app: :endpoint_int\n @before_compile Wrapper\n\n plug :oops\n plug Router\n\n @doc \"\"\"\n Verify errors from the plug stack too (before the router).\n \"\"\"\n def oops(conn, _opts) do\n if conn.path_info == ~w(oops) do\n raise \"oops\"\n else\n conn\n end\n end\n end\n end\n\n @prod 4807\n @dev 4808\n\n alias Phoenix.Integration.HTTPClient\n\n test \"adapters starts on configured port and serves requests and stops for prod\" do\n capture_log fn ->\n # Has server: true\n {:ok, _} = ProdEndpoint.start_link()\n\n # Requests\n {:ok, resp} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@prod}\", %{})\n assert resp.status == 200\n assert resp.body == \"ok\"\n\n {:ok, resp} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@prod}\/unknown\", %{})\n assert resp.status == 404\n assert resp.body == \"404.html from Phoenix.ErrorView\"\n\n assert capture_log(fn ->\n {:ok, resp} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@prod}\/oops\", %{})\n assert resp.status == 500\n assert resp.body == \"500.html from Phoenix.ErrorView\"\n end) =~ \"** (RuntimeError) oops\"\n\n assert capture_log(fn ->\n {:ok, resp} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@prod}\/router\/oops\", %{})\n assert resp.status == 500\n assert resp.body == \"500.html from Phoenix.ErrorView\"\n end) =~ \"** (RuntimeError) oops\"\n\n Supervisor.stop(ProdEndpoint)\n {:error, _reason} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@prod}\", %{})\n end\n end\n\n test \"adapters starts on configured port and serves requests and stops for dev\" do\n # Toggle globally\n serve_endpoints(true)\n on_exit(fn -> serve_endpoints(false) end)\n\n capture_log fn ->\n # Has server: false\n {:ok, _} = DevEndpoint.start_link\n\n # Requests\n {:ok, resp} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@dev}\", %{})\n assert resp.status == 200\n assert resp.body == \"ok\"\n\n {:ok, resp} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@dev}\/unknown\", %{})\n assert resp.status == 404\n assert resp.body =~ \"NoRouteError at GET \/unknown\"\n\n assert capture_log(fn ->\n {:ok, resp} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@dev}\/oops\", %{})\n assert resp.status == 500\n assert resp.body =~ \"RuntimeError at GET \/oops\"\n end) =~ \"** (RuntimeError) oops\"\n\n assert capture_log(fn ->\n {:ok, resp} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@dev}\/router\/oops\", %{})\n assert resp.status == 500\n assert resp.body =~ \"RuntimeError at GET \/router\/oops\"\n end) =~ \"** (RuntimeError) oops\"\n\n Supervisor.stop(DevEndpoint)\n {:error, _reason} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@dev}\", %{})\n end\n end\n\n defp serve_endpoints(bool) do\n Application.put_env(:phoenix, :serve_endpoints, bool)\n end\nend\n","old_contents":"Code.require_file \"..\/..\/support\/http_client.exs\", __DIR__\n\ndefmodule Phoenix.Integration.EndpointTest do\n # Cannot run async because of serve endpoints\n use ExUnit.Case\n import ExUnit.CaptureLog\n\n alias Phoenix.Integration.AdapterTest.ProdEndpoint\n alias Phoenix.Integration.AdapterTest.DevEndpoint\n\n Application.put_env(:endpoint_int, ProdEndpoint,\n http: [port: \"4807\"], url: [host: \"example.com\"], server: true)\n Application.put_env(:endpoint_int, DevEndpoint,\n http: [port: \"4808\"], debug_errors: true)\n\n defmodule Router do\n @moduledoc \"\"\"\n Let's use a plug router to test this endpoint.\n \"\"\"\n use Plug.Router\n\n plug :match\n plug :dispatch\n\n get \"\/\" do\n send_resp conn, 200, \"ok\"\n end\n\n get \"\/router\/oops\" do\n _ = conn\n raise \"oops\"\n end\n\n match _ do\n raise Phoenix.Router.NoRouteError, conn: conn, router: __MODULE__\n end\n end\n\n defmodule Wrapper do\n @moduledoc \"\"\"\n A wrapper around the endpoint call to extract information.\n\n This exists so we can verify that the exception handling\n in the Phoenix endpoint is working as expected. In order\n to do that, we need to wrap the endpoint.call\/2 in a\n before compile callback so it wraps the whole stack,\n including render errors and debug errors functionality.\n \"\"\"\n\n defmacro __before_compile__(_) do\n quote do\n defoverridable [call: 2]\n\n def call(conn, opts) do\n # Assert we never have a lingering sent message in the inbox\n refute_received {:plug_conn, :sent}\n\n try do\n super(conn, opts)\n after\n # When we pipe downstream, downstream will always render,\n # either because the router is responding or because the\n # endpoint error layer is kicking in.\n assert_received {:plug_conn, :sent}\n send self(), {:plug_conn, :sent}\n end\n end\n end\n end\n end\n\n for mod <- [ProdEndpoint, DevEndpoint] do\n defmodule mod do\n use Phoenix.Endpoint, otp_app: :endpoint_int\n @before_compile Wrapper\n\n plug :oops\n plug Router\n\n @doc \"\"\"\n Verify errors from the plug stack too (before the router).\n \"\"\"\n def oops(conn, _opts) do\n if conn.path_info == ~w(oops) do\n raise \"oops\"\n else\n conn\n end\n end\n end\n end\n\n @prod 4807\n @dev 4808\n\n alias Phoenix.Integration.HTTPClient\n\n test \"adapters starts on configured port and serves requests and stops for prod\" do\n capture_log fn ->\n # Has server: true\n {:ok, _} = ProdEndpoint.start_link()\n\n # Requests\n {:ok, resp} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@prod}\", %{})\n assert resp.status == 200\n assert resp.body == \"ok\"\n\n {:ok, resp} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@prod}\/unknown\", %{})\n assert resp.status == 404\n assert resp.body == \"404.html from Phoenix.ErrorView\"\n end\n\n assert capture_log(fn ->\n {:ok, resp} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@prod}\/oops\", %{})\n assert resp.status == 500\n assert resp.body == \"500.html from Phoenix.ErrorView\"\n end) =~ \"** (RuntimeError) oops\"\n\n assert capture_log(fn ->\n {:ok, resp} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@prod}\/router\/oops\", %{})\n assert resp.status == 500\n assert resp.body == \"500.html from Phoenix.ErrorView\"\n end) =~ \"** (RuntimeError) oops\"\n\n Supervisor.stop(ProdEndpoint)\n {:error, _reason} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@prod}\", %{})\n end\n\n test \"adapters starts on configured port and serves requests and stops for dev\" do\n # Has server: false\n {:ok, _} = DevEndpoint.start_link\n {:error, _reason} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@dev}\", %{})\n Supervisor.stop(DevEndpoint)\n\n # Toggle globally\n serve_endpoints(true)\n on_exit(fn -> serve_endpoints(false) end)\n capture_log fn -> {:ok, _} = DevEndpoint.start_link end\n\n # Requests\n {:ok, resp} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@dev}\", %{})\n assert resp.status == 200\n assert resp.body == \"ok\"\n\n capture_log(fn ->\n {:ok, resp} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@dev}\/unknown\", %{})\n assert resp.status == 404\n assert resp.body =~ \"NoRouteError at GET \/unknown\"\n end)\n\n assert capture_log(fn ->\n {:ok, resp} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@dev}\/oops\", %{})\n assert resp.status == 500\n assert resp.body =~ \"RuntimeError at GET \/oops\"\n end) =~ \"** (RuntimeError) oops\"\n\n assert capture_log(fn ->\n {:ok, resp} = HTTPClient.request(:get, \"http:\/\/127.0.0.1:#{@dev}\/router\/oops\", %{})\n assert resp.status == 500\n assert resp.body =~ \"RuntimeError at GET \/router\/oops\"\n end) =~ \"** (RuntimeError) oops\"\n end\n\n defp serve_endpoints(bool) do\n Application.put_env(:phoenix, :serve_endpoints, bool)\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"7ecc66d5610b2e841143607778d3f230c6232134","subject":"chore(rel\/config): update to template ellie.service in prod","message":"chore(rel\/config): update to template ellie.service in prod\n","repos":"lukewestby\/ellie,lukewestby\/ellie,lukewestby\/ellie","old_file":"rel\/config.exs","new_file":"rel\/config.exs","new_contents":"# Import all plugins from `rel\/plugins`\n# They can then be used by adding `plugin MyPlugin` to\n# either an environment, or release definition, where\n# `MyPlugin` is the name of the plugin module.\n~w(rel plugins *.exs)\n|> Path.join()\n|> Path.wildcard()\n|> Enum.map(&Code.eval_file(&1))\n\nuse Mix.Releases.Config,\n # This sets the default release built by `mix release`\n default_release: :default,\n # This sets the default environment used by `mix release`\n default_environment: Mix.env()\n\n# For a full list of config options for both releases\n# and environments, visit https:\/\/hexdocs.pm\/distillery\/config\/distillery.html\n\n\n# You may define one or more environments in this file,\n# an environment's settings will override those of a release\n# when building in that environment, this combination of release\n# and environment configuration is called a profile\n\nenvironment :dev do\n # If you are running Phoenix, you should make sure that\n # server: true is set and the code reloader is disabled,\n # even in dev mode.\n # It is recommended that you build with MIX_ENV=prod and pass\n # the --env flag to Distillery explicitly if you want to use\n # dev mode.\n set dev_mode: true\n set include_erts: false\n set cookie: :\"^`~K6{^:HDz8{Cbq`.~c`l\/!ROE4?0Y&N_.\/t$@33fo(=WcsM>5=bfN02R,K;v*b\"\nend\n\nenvironment :prod do\n set include_erts: true\n set include_src: false\n set cookie: :\"pBpq3i>h9Eoa1(F~fw8`;IYq1G]M$Nifih Path.join()\n|> Path.wildcard()\n|> Enum.map(&Code.eval_file(&1))\n\nuse Mix.Releases.Config,\n # This sets the default release built by `mix release`\n default_release: :default,\n # This sets the default environment used by `mix release`\n default_environment: Mix.env()\n\n# For a full list of config options for both releases\n# and environments, visit https:\/\/hexdocs.pm\/distillery\/config\/distillery.html\n\n\n# You may define one or more environments in this file,\n# an environment's settings will override those of a release\n# when building in that environment, this combination of release\n# and environment configuration is called a profile\n\nenvironment :dev do\n # If you are running Phoenix, you should make sure that\n # server: true is set and the code reloader is disabled,\n # even in dev mode.\n # It is recommended that you build with MIX_ENV=prod and pass\n # the --env flag to Distillery explicitly if you want to use\n # dev mode.\n set dev_mode: true\n set include_erts: false\n set cookie: :\"^`~K6{^:HDz8{Cbq`.~c`l\/!ROE4?0Y&N_.\/t$@33fo(=WcsM>5=bfN02R,K;v*b\"\nend\n\nenvironment :prod do\n set include_erts: true\n set include_src: false\n set cookie: :\"pBpq3i>h9Eoa1(F~fw8`;IYq1G]M$Nifih\n # do some heave processing here...\n reply = perform_work()\n {:reply, {:ok, reply}, socket}\n end)\n end\n end\n\n ### Adding channel payloads\n\n To add channel payloads, use `channel_action\/5`:\n\n defmodule SomeApp.MyChannel do\n import Appsignal.Phoenix.Channel, only: [channel_action: 5]\n\n def handle_in(\"ping\" = action, payload, socket) do\n channel_action(__MODULE__, action, socket, payload, fn ->\n # do some heave processing here...\n reply = perform_work()\n {:reply, {:ok, reply}, socket}\n end)\n end\n end\n \"\"\"\n\n @doc \"\"\"\n Record a channel action. Meant to be called from the 'channel_action' instrumentation decorator.\n \"\"\"\n @spec channel_action(atom | String.t(), String.t(), Phoenix.Socket.t(), fun) :: any\n def channel_action(module, name, %Phoenix.Socket{} = socket, function) do\n channel_action(module, name, %Phoenix.Socket{} = socket, %{}, function)\n end\n\n @spec channel_action(atom | String.t(), String.t(), Phoenix.Socket.t(), map, fun) :: any\n def channel_action(module, name, %Phoenix.Socket{} = socket, params, function) do\n transaction =\n @transaction.generate_id()\n |> @transaction.start(:channel)\n |> @transaction.set_action(\"#{module_name(module)}##{name}\")\n\n try do\n function.()\n catch\n kind, reason ->\n stacktrace = System.stacktrace()\n ErrorHandler.set_error(transaction, reason, stacktrace)\n finish_with_socket(transaction, socket, params)\n TransactionRegistry.ignore(self())\n :erlang.raise(kind, reason, stacktrace)\n else\n result ->\n finish_with_socket(transaction, socket, params)\n result\n end\n end\n\n @spec finish_with_socket(Transaction.t() | nil, Phoenix.Socket.t(), map()) :: :ok | nil\n defp finish_with_socket(transaction, socket, params) do\n if @transaction.finish(transaction) == :sample do\n transaction\n |> @transaction.set_sample_data(\"params\", MapFilter.filter_parameters(params))\n |> @transaction.set_sample_data(\"environment\", request_environment(socket))\n end\n\n @transaction.complete(transaction)\n end\n\n @doc \"\"\"\n Given the `Appsignal.Transaction` and a `Phoenix.Socket`, add the\n socket metadata to the transaction.\n \"\"\"\n @spec set_metadata(Transaction.t(), Phoenix.Socket.t()) :: Transaction.t()\n def set_metadata(transaction, socket) do\n IO.warn(\n \"Appsignal.Channel.set_metadata\/1 is deprecated. Set params and environment data directly with Appsignal.Transaction.set_sample_data\/2 instead.\"\n )\n\n transaction\n |> @transaction.set_sample_data(\"params\", MapFilter.filter_parameters(socket.assigns))\n |> @transaction.set_sample_data(\"environment\", request_environment(socket))\n end\n\n @socket_fields ~w(id channel endpoint handler ref topic transport)a\n @spec request_environment(Phoenix.Socket.t()) :: map\n defp request_environment(socket) do\n @socket_fields\n |> Enum.into(%{}, fn k -> {k, Map.get(socket, k)} end)\n end\n end\nend\n","old_contents":"if Appsignal.phoenix?() do\n defmodule Appsignal.Phoenix.Channel do\n alias Appsignal.{ErrorHandler, Transaction, TransactionRegistry, Utils.MapFilter}\n import Appsignal.Utils\n @transaction Application.get_env(:appsignal, :appsignal_transaction, Transaction)\n\n @moduledoc \"\"\"\n Instrumentation for channel events\n\n ## Instrumenting a channel's `handle_in\/3`\n\n Currently, incoming channel requests can be instrumented, by adding\n code to the `handle_in` function of your application. We use\n [function decorators](https:\/\/github.com\/arjan\/decorator) to\n minimize the amount of code you have to add to your channel.\n\n defmodule SomeApp.MyChannel do\n use Appsignal.Instrumentation.Decorators\n\n @decorate channel_action\n def handle_in(\"ping\", _payload, socket) do\n # your code here..\n end\n end\n\n Channel events will be displayed under the \"Background jobs\" tab,\n showing the channel module and the action argument that you entered.\n\n ### Adding channel payloads\n\n Channel payloads aren't included by default, but can be added by using\n `Appsignal.Transaction.set_sample_data\/2` using the \"params\" key:\n\n defmodule SomeApp.MyChannel do\n use Appsignal.Instrumentation.Decorators\n\n @decorate channel_action\n def handle_in(\"ping\", payload, socket) do\n Appsignal.Transaction.set_sample_data(\n \"params\", Appsignal.Utils.MapFilter.filter_parameters(payload)\n )\n\n # your code here..\n end\n end\n\n ## Instrumenting without decorators\n\n You can also decide not to use function decorators. In that case,\n use the `channel_action\/4` function directly, passing in a name for\n the channel action, the socket and the actual code that you are\n executing in the channel handler:\n\n defmodule SomeApp.MyChannel do\n import Appsignal.Phoenix.Channel, only: [channel_action: 4]\n\n def handle_in(\"ping\" = action, _payload, socket) do\n channel_action(__MODULE__, action, socket, fn ->\n # do some heave processing here...\n reply = perform_work()\n {:reply, {:ok, reply}, socket}\n end)\n end\n end\n\n ### Adding channel payloads\n\n To add channel payloads, use `channel_action\/5`:\n\n defmodule SomeApp.MyChannel do\n import Appsignal.Phoenix.Channel, only: [channel_action: 5]\n\n def handle_in(\"ping\" = action, payload, socket) do\n channel_action(__MODULE__, action, socket, payload, fn ->\n # do some heave processing here...\n reply = perform_work()\n {:reply, {:ok, reply}, socket}\n end)\n end\n end\n \"\"\"\n\n @doc \"\"\"\n Record a channel action. Meant to be called from the 'channel_action' instrumentation decorator.\n \"\"\"\n @spec channel_action(atom, String.t(), Phoenix.Socket.t(), fun) :: any\n def channel_action(module, name, %Phoenix.Socket{} = socket, function) do\n channel_action(module, name, %Phoenix.Socket{} = socket, %{}, function)\n end\n\n @spec channel_action(atom, String.t(), Phoenix.Socket.t(), map, fun) :: any\n def channel_action(module, name, %Phoenix.Socket{} = socket, params, function) do\n transaction =\n @transaction.generate_id()\n |> @transaction.start(:channel)\n |> @transaction.set_action(\"#{module_name(module)}##{name}\")\n\n try do\n function.()\n catch\n kind, reason ->\n stacktrace = System.stacktrace()\n ErrorHandler.set_error(transaction, reason, stacktrace)\n finish_with_socket(transaction, socket, params)\n TransactionRegistry.ignore(self())\n :erlang.raise(kind, reason, stacktrace)\n else\n result ->\n finish_with_socket(transaction, socket, params)\n result\n end\n end\n\n @spec finish_with_socket(Transaction.t() | nil, Phoenix.Socket.t(), map()) :: :ok | nil\n defp finish_with_socket(transaction, socket, params) do\n if @transaction.finish(transaction) == :sample do\n transaction\n |> @transaction.set_sample_data(\"params\", MapFilter.filter_parameters(params))\n |> @transaction.set_sample_data(\"environment\", request_environment(socket))\n end\n\n @transaction.complete(transaction)\n end\n\n @doc \"\"\"\n Given the `Appsignal.Transaction` and a `Phoenix.Socket`, add the\n socket metadata to the transaction.\n \"\"\"\n @spec set_metadata(Transaction.t(), Phoenix.Socket.t()) :: Transaction.t()\n def set_metadata(transaction, socket) do\n IO.warn(\n \"Appsignal.Channel.set_metadata\/1 is deprecated. Set params and environment data directly with Appsignal.Transaction.set_sample_data\/2 instead.\"\n )\n\n transaction\n |> @transaction.set_sample_data(\"params\", MapFilter.filter_parameters(socket.assigns))\n |> @transaction.set_sample_data(\"environment\", request_environment(socket))\n end\n\n @socket_fields ~w(id channel endpoint handler ref topic transport)a\n @spec request_environment(Phoenix.Socket.t()) :: map\n defp request_environment(socket) do\n @socket_fields\n |> Enum.into(%{}, fn k -> {k, Map.get(socket, k)} end)\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"d2f9a9b4d04037764e097663e4960b3681fe2f20","subject":"Remove stub line","message":"Remove stub line\n","repos":"HashNuke\/hound,HashNuke\/hound,manukall\/hound,esbullington\/hound,oivoodoo\/hound,lowks\/hound,manukall\/hound,lowks\/hound,oivoodoo\/hound,esbullington\/hound,jontonsoup\/hound,jontonsoup\/hound,knewter\/hound","old_file":"lib\/hound\/json_driver\/session.ex","new_file":"lib\/hound\/json_driver\/session.ex","new_contents":"defmodule Hound.JsonDriver.Session do\n import Hound.JsonDriver.Utils\n\n @doc \"Get server's current status\"\n @spec server_status(Dict.t) :: Dict.t\n def server_status(connection) do\n make_req(connection, :get, \"status\")\n end\n\n\n @doc \"Get list of active sessions\"\n @spec active_sessions(Dict.t) :: Dict.t\n def active_sessions(connection) do\n make_req(connection, :get, \"sessions\")\n end\n\n\n @doc \"Create a session\"\n @spec create_session(Dict.t) :: String.t\n def create_session(connection) do\n make_req(connection, :post, \"sessions\")\n end\n\n\n @doc \"Get capabilities of a particular session\"\n @spec session(Dict.t, String.t) :: Dict.t\n def session(connection, session_id) do\n make_req(connection, :get, \"session\/#{session_id}\")\n end\n\n\n @doc \"Delete a session\"\n @spec delete_session(Dict.t, String.t) :: :ok\n def delete_session(connection, session_id) do\n make_req(connection, :delete, \"session\/#{session_id}\")\n end\n\n\n @doc \"Set the timeout for a particular type of operation\"\n @spec set_timeout(Dict.t, String.t, String.t, Integer.t) :: :ok\n def set_timeout(connection, session_id, operation, time) do\n make_req(connection, :post, \"session\/#{session_id}\/timeouts\", [type: operation, ms: time])\n end\nend\n","old_contents":"defmodule Hound.JsonDriver.Session do\n import Hound.JsonDriver.Utils\n\n @doc \"Get server's current status\"\n @spec server_status(Dict.t) :: Dict.t\n def server_status(connection) do\n make_req(connection, :get, \"status\")\n end\n\n\n @doc \"Get list of active sessions\"\n @spec active_sessions(Dict.t) :: Dict.t\n def active_sessions(connection) do\n make_req(connection, :get, \"sessions\")\n end\n\n\n @doc \"Create a session\"\n @spec create_session(Dict.t) :: String.t\n def create_session(connection) do\n \"some-session-id\"\n # make_req(connection, :post, \"sessions\")\n end\n\n\n @doc \"Get capabilities of a particular session\"\n @spec session(Dict.t, String.t) :: Dict.t\n def session(connection, session_id) do\n make_req(connection, :get, \"session\/#{session_id}\")\n end\n\n\n @doc \"Delete a session\"\n @spec delete_session(Dict.t, String.t) :: :ok\n def delete_session(connection, session_id) do\n make_req(connection, :delete, \"session\/#{session_id}\")\n end\n\n\n @doc \"Set the timeout for a particular type of operation\"\n @spec set_timeout(Dict.t, String.t, String.t, Integer.t) :: :ok\n def set_timeout(connection, session_id, operation, time) do\n make_req(connection, :post, \"session\/#{session_id}\/timeouts\", [type: operation, ms: time])\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"0a6672b3f261d351f404f857e369236e32f12afa","subject":"check for apns required ciphers while starting application","message":"check for apns required ciphers while starting application\n","repos":"esl\/MongoosePush,esl\/MongoosePush,esl\/MongoosePush","old_file":"lib\/mongoose_push\/application.ex","new_file":"lib\/mongoose_push\/application.ex","new_contents":"defmodule MongoosePush.Application do\n # See http:\/\/elixir-lang.org\/docs\/stable\/elixir\/Application.html\n # for more information on OTP Applications\n @moduledoc false\n\n use Application\n require Logger\n\n @typedoc \"Possible keys in FCM config\"\n @type fcm_key :: :key | :pool_size | :mode | :endpoint\n @typedoc \"Possible keys in APNS config\"\n @type apns_key :: :cert | :key | :pool_size | :mode | :endpoint | :use_2197\n\n @typedoc \"\"\"\n In FCM `:key` and `:pool_size` are required and `:mode` has to be either `:dev` or `:prod`\n \"\"\"\n @type fcm_config :: [{fcm_key, String.t() | atom | integer}]\n @typedoc \"\"\"\n In APNS `:cert`, `:key` and `:pool_size` are required. `:mode` has to be either `:dev` or `:prod`\n \"\"\"\n @type apns_config :: [{apns_key, String.t() | atom | integer}]\n\n @type pool_name :: atom()\n @type pool_definition :: {pool_name, fcm_config | apns_config}\n\n @spec start(atom, list(term)) :: {:ok, pid}\n def start(_type, _args) do\n # Logger setup\n loglevel = Application.get_env(:mongoose_push, :logging)[:level] || :info\n logformat = Application.get_env(:mongoose_push, :logging)[:format] || :logfmt\n set_loglevel(loglevel)\n set_logformat(logformat)\n\n :ok = check_apns_ciphers()\n\n # Mostly status logging\n _ = check_runtime_configuration_status()\n\n # Define workers and child supervisors to be supervised\n # The MongoosePush.Metrics.TelemetryMetrics child is started first to capture possible events\n # when services start\n children =\n [MongoosePush.Metrics.TelemetryMetrics] ++\n MongoosePush.Metrics.TelemetryMetrics.pooler() ++\n service_children() ++ [MongoosePushWeb.Endpoint]\n\n # See http:\/\/elixir-lang.org\/docs\/stable\/elixir\/Supervisor.html\n # for other strategies and supported options\n opts = [strategy: :one_for_one, name: MongoosePush.Supervisor]\n Supervisor.start_link(children, opts)\n end\n\n @spec pools_config(MongoosePush.service()) :: [pool_definition]\n def pools_config(service) do\n enabled_opt = String.to_atom(~s\"#{service}_enabled\")\n service_config = Application.get_env(:mongoose_push, service, nil)\n\n pools_config =\n case Application.get_env(:mongoose_push, enabled_opt, !is_nil(service_config)) do\n false -> []\n true -> service_config\n end\n\n Enum.map(Enum.with_index(pools_config), fn {{pool_name, pool_config}, index} ->\n normalized_pool_config =\n pool_config\n |> generate_pool_id(service, index)\n |> fix_priv_paths(service)\n |> ensure_mode()\n |> ensure_tls_opts()\n\n {pool_name, normalized_pool_config}\n end)\n end\n\n def services do\n Application.get_env(:mongoose_push, MongoosePush.Service)\n end\n\n def backend_module, do: Application.fetch_env!(:mongoose_push, :backend_module)\n\n defp service_children do\n List.foldl(services(), [], fn {service, module}, acc ->\n pools_config = pools_config(service)\n\n case pools_config do\n [] ->\n acc\n\n _ ->\n [module.supervisor_entry(pools_config) | acc]\n end\n end)\n end\n\n defp generate_pool_id(config, service, index) do\n id = String.to_atom(\"#{service}.pool.ID.#{index}\")\n Keyword.merge(config, id: id)\n end\n\n defp ensure_mode(config) do\n case config[:mode] do\n nil ->\n Keyword.merge(config, mode: mode(config))\n\n _ ->\n config\n end\n end\n\n defp fix_priv_paths(config, service) do\n path_keys =\n case service do\n :apns ->\n [:cert, :key, :p8_file_path]\n\n :fcm ->\n [:appfile]\n end\n\n case service do\n :fcm ->\n check_paths(config, path_keys)\n\n :apns ->\n Keyword.update!(config, :auth, fn auth -> check_paths(auth, path_keys) end)\n end\n end\n\n defp check_paths(config, path_keys) do\n Enum.map(config, fn {key, value} ->\n case Enum.member?(path_keys, key) do\n true ->\n {key, Application.app_dir(:mongoose_push, value)}\n\n false ->\n {key, value}\n end\n end)\n end\n\n defp ensure_tls_opts(config) do\n case Application.get_env(:mongoose_push, :tls_server_cert_validation, nil) do\n false ->\n Keyword.put(config, :tls_opts, [])\n\n _ ->\n config\n end\n end\n\n defp mode(config), do: config[:mode] || :prod\n\n defp set_loglevel(level) do\n Logger.configure(level: level)\n\n # This project uses some Erlang deps, so lager may be present\n case Code.ensure_loaded?(:lager) do\n true ->\n :lager.set_loglevel(:lager_file_backend, level)\n :lager.set_loglevel(:lager_console_backend, level)\n\n false ->\n :ok\n end\n end\n\n defp set_logformat(:logfmt), do: set_logformat(MongoosePush.Logger.LogFmt)\n\n defp set_logformat(:json), do: set_logformat(MongoosePush.Logger.JSON)\n\n defp set_logformat(module) do\n Logger.configure_backend(:console, format: {module, :format}, metadata: :all)\n end\n\n defp check_runtime_configuration_status() do\n toml_configuration = Application.get_env(:mongoose_push, :toml_configuration)\n\n case toml_configuration[:status] do\n {:ok, :loaded} ->\n Logger.info(\"Loaded TOML configuration\",\n what: :toml_configuration,\n status: :loaded,\n path: toml_configuration[:path]\n )\n\n {:ok, :skipped} ->\n Logger.info(\"Skipping TOML configuration due to file not present\",\n what: :toml_configuration,\n status: :skipped,\n reason: :enoent,\n path: toml_configuration[:path]\n )\n\n {:error, reason} ->\n Logger.error(\"Unable to parse TOML config file\",\n what: :toml_configuration,\n status: :error,\n reason: inspect(reason),\n path: toml_configuration[:path]\n )\n\n nil ->\n Logger.info(\"Skipping TOML configuration due to non-release boot\",\n what: :toml_configuration,\n status: :error,\n reason: :no_release\n )\n end\n end\n\n defp check_apns_ciphers() do\n all_ciphers = :ssl.cipher_suites()\n\n apns_ciphers =\n Enum.filter(all_ciphers, fn cipher ->\n case cipher do\n {:ecdhe_rsa, :aes_128_gcm, _, :sha256} ->\n true\n\n {:ecdhe_rsa, :aes_256_gcm, _, :sha384} ->\n true\n\n _ ->\n false\n end\n end)\n\n case length(apns_ciphers) > 0 do\n true ->\n :ok\n\n false ->\n Logger.error(\"APNS required ciphers missing\",\n what: :tls_configuration,\n status: :error,\n reason: :no_apns_ciphers\n )\n\n throw({:error, :no_apns_ciphers})\n end\n end\nend\n","old_contents":"defmodule MongoosePush.Application do\n # See http:\/\/elixir-lang.org\/docs\/stable\/elixir\/Application.html\n # for more information on OTP Applications\n @moduledoc false\n\n use Application\n require Logger\n\n @typedoc \"Possible keys in FCM config\"\n @type fcm_key :: :key | :pool_size | :mode | :endpoint\n @typedoc \"Possible keys in APNS config\"\n @type apns_key :: :cert | :key | :pool_size | :mode | :endpoint | :use_2197\n\n @typedoc \"\"\"\n In FCM `:key` and `:pool_size` are required and `:mode` has to be either `:dev` or `:prod`\n \"\"\"\n @type fcm_config :: [{fcm_key, String.t() | atom | integer}]\n @typedoc \"\"\"\n In APNS `:cert`, `:key` and `:pool_size` are required. `:mode` has to be either `:dev` or `:prod`\n \"\"\"\n @type apns_config :: [{apns_key, String.t() | atom | integer}]\n\n @type pool_name :: atom()\n @type pool_definition :: {pool_name, fcm_config | apns_config}\n\n @spec start(atom, list(term)) :: {:ok, pid}\n def start(_type, _args) do\n # Logger setup\n loglevel = Application.get_env(:mongoose_push, :logging)[:level] || :info\n logformat = Application.get_env(:mongoose_push, :logging)[:format] || :logfmt\n set_loglevel(loglevel)\n set_logformat(logformat)\n\n # Mostly status logging\n _ = check_runtime_configuration_status()\n\n # Define workers and child supervisors to be supervised\n # The MongoosePush.Metrics.TelemetryMetrics child is started first to capture possible events\n # when services start\n children =\n [MongoosePush.Metrics.TelemetryMetrics] ++\n MongoosePush.Metrics.TelemetryMetrics.pooler() ++\n service_children() ++ [MongoosePushWeb.Endpoint]\n\n # See http:\/\/elixir-lang.org\/docs\/stable\/elixir\/Supervisor.html\n # for other strategies and supported options\n opts = [strategy: :one_for_one, name: MongoosePush.Supervisor]\n Supervisor.start_link(children, opts)\n end\n\n @spec pools_config(MongoosePush.service()) :: [pool_definition]\n def pools_config(service) do\n enabled_opt = String.to_atom(~s\"#{service}_enabled\")\n service_config = Application.get_env(:mongoose_push, service, nil)\n\n pools_config =\n case Application.get_env(:mongoose_push, enabled_opt, !is_nil(service_config)) do\n false -> []\n true -> service_config\n end\n\n Enum.map(Enum.with_index(pools_config), fn {{pool_name, pool_config}, index} ->\n normalized_pool_config =\n pool_config\n |> generate_pool_id(service, index)\n |> fix_priv_paths(service)\n |> ensure_mode()\n |> ensure_tls_opts()\n\n {pool_name, normalized_pool_config}\n end)\n end\n\n def services do\n Application.get_env(:mongoose_push, MongoosePush.Service)\n end\n\n def backend_module, do: Application.fetch_env!(:mongoose_push, :backend_module)\n\n defp service_children do\n List.foldl(services(), [], fn {service, module}, acc ->\n pools_config = pools_config(service)\n\n case pools_config do\n [] ->\n acc\n\n _ ->\n [module.supervisor_entry(pools_config) | acc]\n end\n end)\n end\n\n defp generate_pool_id(config, service, index) do\n id = String.to_atom(\"#{service}.pool.ID.#{index}\")\n Keyword.merge(config, id: id)\n end\n\n defp ensure_mode(config) do\n case config[:mode] do\n nil ->\n Keyword.merge(config, mode: mode(config))\n\n _ ->\n config\n end\n end\n\n defp fix_priv_paths(config, service) do\n path_keys =\n case service do\n :apns ->\n [:cert, :key, :p8_file_path]\n\n :fcm ->\n [:appfile]\n end\n\n case service do\n :fcm ->\n check_paths(config, path_keys)\n\n :apns ->\n Keyword.update!(config, :auth, fn auth -> check_paths(auth, path_keys) end)\n end\n end\n\n defp check_paths(config, path_keys) do\n Enum.map(config, fn {key, value} ->\n case Enum.member?(path_keys, key) do\n true ->\n {key, Application.app_dir(:mongoose_push, value)}\n\n false ->\n {key, value}\n end\n end)\n end\n\n defp ensure_tls_opts(config) do\n case Application.get_env(:mongoose_push, :tls_server_cert_validation, nil) do\n false ->\n Keyword.put(config, :tls_opts, [])\n\n _ ->\n config\n end\n end\n\n defp mode(config), do: config[:mode] || :prod\n\n defp set_loglevel(level) do\n Logger.configure(level: level)\n\n # This project uses some Erlang deps, so lager may be present\n case Code.ensure_loaded?(:lager) do\n true ->\n :lager.set_loglevel(:lager_file_backend, level)\n :lager.set_loglevel(:lager_console_backend, level)\n\n false ->\n :ok\n end\n end\n\n defp set_logformat(:logfmt), do: set_logformat(MongoosePush.Logger.LogFmt)\n\n defp set_logformat(:json), do: set_logformat(MongoosePush.Logger.JSON)\n\n defp set_logformat(module) do\n Logger.configure_backend(:console, format: {module, :format}, metadata: :all)\n end\n\n defp check_runtime_configuration_status() do\n toml_configuration = Application.get_env(:mongoose_push, :toml_configuration)\n\n case toml_configuration[:status] do\n {:ok, :loaded} ->\n Logger.info(\"Loaded TOML configuration\",\n what: :toml_configuration,\n status: :loaded,\n path: toml_configuration[:path]\n )\n\n {:ok, :skipped} ->\n Logger.info(\"Skipping TOML configuration due to file not present\",\n what: :toml_configuration,\n status: :skipped,\n reason: :enoent,\n path: toml_configuration[:path]\n )\n\n {:error, reason} ->\n Logger.error(\"Unable to parse TOML config file\",\n what: :toml_configuration,\n status: :error,\n reason: inspect(reason),\n path: toml_configuration[:path]\n )\n\n nil ->\n Logger.info(\"Skipping TOML configuration due to non-release boot\",\n what: :toml_configuration,\n status: :error,\n reason: :no_release\n )\n end\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"8de6200bbcfc44c8f28982f57f5504bc18c025ff","subject":"Fix label test","message":"Fix label test\n","repos":"jamilabreu\/phoenix,0x00evil\/phoenix,ephe-meral\/phoenix,korobkov\/phoenix,rafbgarcia\/phoenix,Joe-noh\/phoenix,rafbgarcia\/phoenix,phoenixframework\/phoenix,bsmr-erlang\/phoenix,bsmr-erlang\/phoenix,korobkov\/phoenix,stevedomin\/phoenix,jwarwick\/phoenix,keathley\/phoenix,Gazler\/phoenix,pap\/phoenix,evax\/phoenix,ephe-meral\/phoenix,iStefo\/phoenix,nshafer\/phoenix,optikfluffel\/phoenix,Smulligan85\/phoenix,0x00evil\/phoenix,seejee\/phoenix,keathley\/phoenix,0x00evil\/phoenix,mvidaurre\/phoenix,seejee\/phoenix,dmarkow\/phoenix,vic\/phoenix,mitchellhenke\/phoenix,jwarwick\/phoenix,Ben-Evolently\/phoenix,nshafer\/phoenix,rafbgarcia\/phoenix,michalmuskala\/phoenix,optikfluffel\/phoenix,andrewvy\/phoenix,trarbr\/phoenix,wsmoak\/phoenix,ericmj\/phoenix,mvidaurre\/phoenix,evax\/phoenix,mitchellhenke\/phoenix,mobileoverlord\/phoenix,cas27\/phoenix,ericmj\/phoenix,mschae\/phoenix,wsmoak\/phoenix,trarbr\/phoenix,iStefo\/phoenix,ybur-yug\/phoenix,gjaldon\/phoenix,eksperimental\/phoenix,cas27\/phoenix,michalmuskala\/phoenix,Joe-noh\/phoenix,mschae\/phoenix,ybur-yug\/phoenix,Rumel\/phoenix,Gazler\/phoenix,CultivateHQ\/phoenix,mobileoverlord\/phoenix,nshafer\/phoenix,optikfluffel\/phoenix,Rumel\/phoenix,Kosmas\/phoenix,stevedomin\/phoenix,andrewvy\/phoenix,Kosmas\/phoenix,vic\/phoenix,DavidAlphaFox\/phoenix,pap\/phoenix,DavidAlphaFox\/phoenix,eksperimental\/phoenix,dmarkow\/phoenix,Smulligan85\/phoenix,CultivateHQ\/phoenix,jamilabreu\/phoenix,phoenixframework\/phoenix,gjaldon\/phoenix,phoenixframework\/phoenix","old_file":"test\/mix\/tasks\/phoenix.gen.html_test.exs","new_file":"test\/mix\/tasks\/phoenix.gen.html_test.exs","new_contents":"Code.require_file \"..\/..\/..\/installer\/test\/mix_helper.exs\", __DIR__\n\ndefmodule Phoenix.DupHTMLController do\nend\n\ndefmodule Phoenix.DupHTMLView do\nend\n\ndefmodule Mix.Tasks.Phoenix.Gen.HtmlTest do\n use ExUnit.Case\n import MixHelper\n\n setup do\n Mix.Task.clear\n :ok\n end\n\n test \"generates html resource\" do\n in_tmp \"generates html resource\", fn ->\n Mix.Tasks.Phoenix.Gen.Html.run [\"user\", \"users\", \"name\", \"age:integer\", \"height:decimal\",\n \"nicks:array:text\", \"famous:boolean\", \"born_at:datetime\",\n \"secret:uuid\", \"first_login:date\", \"alarm:time\",\n \"address_id:references:addresses\"]\n\n assert_file \"web\/models\/user.ex\"\n assert_file \"test\/models\/user_test.exs\"\n assert [_] = Path.wildcard(\"priv\/repo\/migrations\/*_create_user.exs\")\n\n assert_file \"web\/controllers\/user_controller.ex\", fn file ->\n assert file =~ \"defmodule Phoenix.UserController\"\n assert file =~ \"use Phoenix.Web, :controller\"\n assert file =~ \"Repo.get!\"\n end\n\n assert_file \"web\/views\/user_view.ex\", fn file ->\n assert file =~ \"defmodule Phoenix.UserView do\"\n assert file =~ \"use Phoenix.Web, :view\"\n end\n\n assert_file \"web\/templates\/user\/edit.html.eex\", fn file ->\n assert file =~ \"action: user_path(@conn, :update, @user)\"\n end\n\n assert_file \"web\/templates\/user\/form.html.eex\", fn file ->\n assert file =~ ~s(<%= text_input f, :name, class: \"form-control\" %>)\n assert file =~ ~s(<%= number_input f, :age, class: \"form-control\" %>)\n assert file =~ ~s(<%= number_input f, :height, step: \"any\", class: \"form-control\" %>)\n assert file =~ ~s(<%= checkbox f, :famous, class: \"form-control\" %>)\n assert file =~ ~s(<%= datetime_select f, :born_at, class: \"form-control\" %>)\n assert file =~ ~s(<%= text_input f, :secret, class: \"form-control\" %>)\n assert file =~ ~s(<%= label f, :name, class: \"control-label\" %>)\n assert file =~ ~s(<%= label f, :age, class: \"control-label\" %>)\n assert file =~ ~s(<%= label f, :height, class: \"control-label\" %>)\n assert file =~ ~s(<%= label f, :famous, class: \"control-label\" %>)\n assert file =~ ~s(<%= label f, :born_at, class: \"control-label\" %>)\n assert file =~ ~s(<%= label f, :secret, class: \"control-label\" %>)\n\n refute file =~ ~s(<%= label f, :address_id)\n refute file =~ ~s(<%= number_input f, :address_id)\n refute file =~ \":nicks\"\n end\n\n assert_file \"web\/templates\/user\/index.html.eex\", fn file ->\n assert file =~ \"Name<\/th>\"\n assert file =~ \"<%= for user <- @users do %>\"\n assert file =~ \"<%= user.name %><\/td>\"\n end\n\n assert_file \"web\/templates\/user\/new.html.eex\", fn file ->\n assert file =~ \"action: user_path(@conn, :create)\"\n end\n\n assert_file \"web\/templates\/user\/show.html.eex\", fn file ->\n assert file =~ \"Name:<\/strong>\"\n assert file =~ \"<%= @user.name %>\"\n end\n\n assert_file \"test\/controllers\/user_controller_test.exs\", fn file ->\n assert file =~ \"defmodule Phoenix.UserControllerTest\"\n assert file =~ \"use Phoenix.ConnCase\"\n\n assert file =~ ~S|@valid_attrs %{age: 42|\n assert file =~ ~S|@invalid_attrs %{}|\n refute file =~ ~S|address_id: nil|\n\n assert file =~ ~S|test \"lists all entries on index\"|\n assert file =~ ~S|conn = get conn, user_path(conn, :index)|\n assert file =~ ~S|assert html_response(conn, 200) =~ \"Listing users\"|\n\n assert file =~ ~S|test \"renders form for new resources\"|\n assert file =~ ~S|conn = get conn, user_path(conn, :new)|\n assert file =~ ~S|assert html_response(conn, 200) =~ \"New user\"|\n\n assert file =~ ~S|test \"creates resource and redirects when data is valid\"|\n assert file =~ ~S|conn = post conn, user_path(conn, :create), user: @valid_attrs|\n assert file =~ ~S|assert redirected_to(conn) == user_path(conn, :index)|\n assert file =~ ~r\/creates.*when data is valid.*?assert Repo\\.get_by\\(User, @valid_attrs\\).*?end\/s\n\n assert file =~ ~S|test \"does not create resource and renders errors when data is invalid\"|\n assert file =~ ~S|conn = post conn, user_path(conn, :create), user: @invalid_attrs|\n\n assert file =~ ~S|test \"shows chosen resource\"|\n assert file =~ ~S|user = Repo.insert! %User{}|\n assert file =~ ~S|assert html_response(conn, 200) =~ \"Show user\"|\n\n assert file =~ ~S|test \"renders form for editing chosen resource\"|\n assert file =~ ~S|assert html_response(conn, 200) =~ \"Edit user\"|\n\n assert file =~ ~S|test \"updates chosen resource and redirects when data is valid\"|\n assert file =~ ~S|conn = put conn, user_path(conn, :update, user), user: @valid_attrs|\n assert file =~ ~r\/updates.*when data is valid.*?assert Repo\\.get_by\\(User, @valid_attrs\\).*?end\/s\n\n assert file =~ ~S|test \"does not update chosen resource and renders errors when data is invalid\"|\n assert file =~ ~S|conn = put conn, user_path(conn, :update, user), user: @invalid_attrs|\n\n assert file =~ ~S|test \"deletes chosen resource\"|\n assert file =~ ~S|conn = delete conn, user_path(conn, :delete, user)|\n end\n\n assert_received {:mix_shell, :info, [\"\\nAdd the resource\" <> _ = message]}\n assert message =~ ~s(resources \"\/users\", UserController)\n end\n end\n\n test \"generates nested resource\" do\n in_tmp \"generates nested resource\", fn ->\n Mix.Tasks.Phoenix.Gen.Html.run [\"Admin.SuperUser\", \"super_users\", \"name:string\"]\n\n assert_file \"web\/models\/admin\/super_user.ex\"\n assert [_] = Path.wildcard(\"priv\/repo\/migrations\/*_create_admin_super_user.exs\")\n\n assert_file \"web\/controllers\/admin\/super_user_controller.ex\", fn file ->\n assert file =~ \"defmodule Phoenix.Admin.SuperUserController\"\n assert file =~ \"use Phoenix.Web, :controller\"\n assert file =~ \"Repo.get!\"\n end\n\n assert_file \"web\/views\/admin\/super_user_view.ex\", fn file ->\n assert file =~ \"defmodule Phoenix.Admin.SuperUserView do\"\n assert file =~ \"use Phoenix.Web, :view\"\n end\n\n assert_file \"web\/templates\/admin\/super_user\/edit.html.eex\", fn file ->\n assert file =~ \"

Edit super user<\/h2>\"\n assert file =~ \"action: super_user_path(@conn, :update, @super_user)\"\n end\n\n assert_file \"web\/templates\/admin\/super_user\/form.html.eex\", fn file ->\n assert file =~ ~s(<%= text_input f, :name, class: \"form-control\" %>)\n end\n\n assert_file \"web\/templates\/admin\/super_user\/index.html.eex\", fn file ->\n assert file =~ \"

Listing super users<\/h2>\"\n assert file =~ \"Name<\/th>\"\n assert file =~ \"<%= for super_user <- @super_users do %>\"\n end\n\n assert_file \"web\/templates\/admin\/super_user\/new.html.eex\", fn file ->\n assert file =~ \"

New super user<\/h2>\"\n assert file =~ \"action: super_user_path(@conn, :create)\"\n end\n\n assert_file \"web\/templates\/admin\/super_user\/show.html.eex\", fn file ->\n assert file =~ \"

Show super user<\/h2>\"\n assert file =~ \"Name:<\/strong>\"\n assert file =~ \"<%= @super_user.name %>\"\n end\n\n assert_file \"test\/controllers\/admin\/super_user_controller_test.exs\", fn file ->\n assert file =~ ~S|assert html_response(conn, 200) =~ \"Listing super users\"|\n assert file =~ ~S|assert html_response(conn, 200) =~ \"New super user\"|\n assert file =~ ~S|assert html_response(conn, 200) =~ \"Show super user\"|\n assert file =~ ~S|assert html_response(conn, 200) =~ \"Edit super user\"|\n end\n\n assert_received {:mix_shell, :info, [\"\\nAdd the resource\" <> _ = message]}\n assert message =~ ~s(resources \"\/admin\/super_users\", Admin.SuperUserController)\n end\n end\n\n test \"generates html resource without model\" do\n in_tmp \"generates html resource without model\", fn ->\n Mix.Tasks.Phoenix.Gen.Html.run [\"Admin.User\", \"users\", \"--no-model\", \"name:string\"]\n\n refute File.exists? \"web\/models\/admin\/user.ex\"\n assert [] = Path.wildcard(\"priv\/repo\/migrations\/*_create_admin_user.exs\")\n\n assert_file \"web\/templates\/admin\/user\/form.html.eex\", fn file ->\n refute file =~ ~s(--no-model)\n end\n end\n end\n\n test \"plural can't contain a colon\" do\n assert_raise Mix.Error, fn ->\n Mix.Tasks.Phoenix.Gen.Html.run [\"Admin.User\", \"name:string\", \"foo:string\"]\n end\n end\n\n test \"plural can't have uppercased characters or camelized format\" do\n assert_raise Mix.Error, fn ->\n Mix.Tasks.Phoenix.Gen.Html.run [\"Admin.User\", \"Users\", \"foo:string\"]\n end\n\n assert_raise Mix.Error, fn ->\n Mix.Tasks.Phoenix.Gen.Html.run [\"Admin.User\", \"AdminUsers\", \"foo:string\"]\n end\n end\n\n test \"name is already defined\" do\n assert_raise Mix.Error, fn ->\n Mix.Tasks.Phoenix.Gen.Html.run [\"DupHTML\", \"duphtmls\"]\n end\n end\nend\n","old_contents":"Code.require_file \"..\/..\/..\/installer\/test\/mix_helper.exs\", __DIR__\n\ndefmodule Phoenix.DupHTMLController do\nend\n\ndefmodule Phoenix.DupHTMLView do\nend\n\ndefmodule Mix.Tasks.Phoenix.Gen.HtmlTest do\n use ExUnit.Case\n import MixHelper\n\n setup do\n Mix.Task.clear\n :ok\n end\n\n test \"generates html resource\" do\n in_tmp \"generates html resource\", fn ->\n Mix.Tasks.Phoenix.Gen.Html.run [\"user\", \"users\", \"name\", \"age:integer\", \"height:decimal\",\n \"nicks:array:text\", \"famous:boolean\", \"born_at:datetime\",\n \"secret:uuid\", \"first_login:date\", \"alarm:time\",\n \"address_id:references:addresses\"]\n\n assert_file \"web\/models\/user.ex\"\n assert_file \"test\/models\/user_test.exs\"\n assert [_] = Path.wildcard(\"priv\/repo\/migrations\/*_create_user.exs\")\n\n assert_file \"web\/controllers\/user_controller.ex\", fn file ->\n assert file =~ \"defmodule Phoenix.UserController\"\n assert file =~ \"use Phoenix.Web, :controller\"\n assert file =~ \"Repo.get!\"\n end\n\n assert_file \"web\/views\/user_view.ex\", fn file ->\n assert file =~ \"defmodule Phoenix.UserView do\"\n assert file =~ \"use Phoenix.Web, :view\"\n end\n\n assert_file \"web\/templates\/user\/edit.html.eex\", fn file ->\n assert file =~ \"action: user_path(@conn, :update, @user)\"\n end\n\n assert_file \"web\/templates\/user\/form.html.eex\", fn file ->\n assert file =~ ~s(<%= text_input f, :name, class: \"form-control\" %>)\n assert file =~ ~s(<%= number_input f, :age, class: \"form-control\" %>)\n assert file =~ ~s(<%= number_input f, :height, step: \"any\", class: \"form-control\" %>)\n assert file =~ ~s(<%= checkbox f, :famous, class: \"form-control\" %>)\n assert file =~ ~s(<%= datetime_select f, :born_at, class: \"form-control\" %>)\n assert file =~ ~s(<%= text_input f, :secret, class: \"form-control\" %>)\n assert file =~ ~s(<%= label f, :name, \"Name\", class: \"control-label\" %>)\n assert file =~ ~s(<%= label f, :age, \"Age\", class: \"control-label\" %>)\n assert file =~ ~s(<%= label f, :height, \"Height\", class: \"control-label\" %>)\n assert file =~ ~s(<%= label f, :famous, \"Famous\", class: \"control-label\" %>)\n assert file =~ ~s(<%= label f, :born_at, \"Born at\", class: \"control-label\" %>)\n assert file =~ ~s(<%= label f, :secret, \"Secret\", class: \"control-label\" %>)\n\n refute file =~ ~s(<%= label f, :address_id)\n refute file =~ ~s(<%= number_input f, :address_id)\n refute file =~ \":nicks\"\n end\n\n assert_file \"web\/templates\/user\/index.html.eex\", fn file ->\n assert file =~ \"Name<\/th>\"\n assert file =~ \"<%= for user <- @users do %>\"\n assert file =~ \"<%= user.name %><\/td>\"\n end\n\n assert_file \"web\/templates\/user\/new.html.eex\", fn file ->\n assert file =~ \"action: user_path(@conn, :create)\"\n end\n\n assert_file \"web\/templates\/user\/show.html.eex\", fn file ->\n assert file =~ \"Name:<\/strong>\"\n assert file =~ \"<%= @user.name %>\"\n end\n\n assert_file \"test\/controllers\/user_controller_test.exs\", fn file ->\n assert file =~ \"defmodule Phoenix.UserControllerTest\"\n assert file =~ \"use Phoenix.ConnCase\"\n\n assert file =~ ~S|@valid_attrs %{age: 42|\n assert file =~ ~S|@invalid_attrs %{}|\n refute file =~ ~S|address_id: nil|\n\n assert file =~ ~S|test \"lists all entries on index\"|\n assert file =~ ~S|conn = get conn, user_path(conn, :index)|\n assert file =~ ~S|assert html_response(conn, 200) =~ \"Listing users\"|\n\n assert file =~ ~S|test \"renders form for new resources\"|\n assert file =~ ~S|conn = get conn, user_path(conn, :new)|\n assert file =~ ~S|assert html_response(conn, 200) =~ \"New user\"|\n\n assert file =~ ~S|test \"creates resource and redirects when data is valid\"|\n assert file =~ ~S|conn = post conn, user_path(conn, :create), user: @valid_attrs|\n assert file =~ ~S|assert redirected_to(conn) == user_path(conn, :index)|\n assert file =~ ~r\/creates.*when data is valid.*?assert Repo\\.get_by\\(User, @valid_attrs\\).*?end\/s\n\n assert file =~ ~S|test \"does not create resource and renders errors when data is invalid\"|\n assert file =~ ~S|conn = post conn, user_path(conn, :create), user: @invalid_attrs|\n\n assert file =~ ~S|test \"shows chosen resource\"|\n assert file =~ ~S|user = Repo.insert! %User{}|\n assert file =~ ~S|assert html_response(conn, 200) =~ \"Show user\"|\n\n assert file =~ ~S|test \"renders form for editing chosen resource\"|\n assert file =~ ~S|assert html_response(conn, 200) =~ \"Edit user\"|\n\n assert file =~ ~S|test \"updates chosen resource and redirects when data is valid\"|\n assert file =~ ~S|conn = put conn, user_path(conn, :update, user), user: @valid_attrs|\n assert file =~ ~r\/updates.*when data is valid.*?assert Repo\\.get_by\\(User, @valid_attrs\\).*?end\/s\n\n assert file =~ ~S|test \"does not update chosen resource and renders errors when data is invalid\"|\n assert file =~ ~S|conn = put conn, user_path(conn, :update, user), user: @invalid_attrs|\n\n assert file =~ ~S|test \"deletes chosen resource\"|\n assert file =~ ~S|conn = delete conn, user_path(conn, :delete, user)|\n end\n\n assert_received {:mix_shell, :info, [\"\\nAdd the resource\" <> _ = message]}\n assert message =~ ~s(resources \"\/users\", UserController)\n end\n end\n\n test \"generates nested resource\" do\n in_tmp \"generates nested resource\", fn ->\n Mix.Tasks.Phoenix.Gen.Html.run [\"Admin.SuperUser\", \"super_users\", \"name:string\"]\n\n assert_file \"web\/models\/admin\/super_user.ex\"\n assert [_] = Path.wildcard(\"priv\/repo\/migrations\/*_create_admin_super_user.exs\")\n\n assert_file \"web\/controllers\/admin\/super_user_controller.ex\", fn file ->\n assert file =~ \"defmodule Phoenix.Admin.SuperUserController\"\n assert file =~ \"use Phoenix.Web, :controller\"\n assert file =~ \"Repo.get!\"\n end\n\n assert_file \"web\/views\/admin\/super_user_view.ex\", fn file ->\n assert file =~ \"defmodule Phoenix.Admin.SuperUserView do\"\n assert file =~ \"use Phoenix.Web, :view\"\n end\n\n assert_file \"web\/templates\/admin\/super_user\/edit.html.eex\", fn file ->\n assert file =~ \"

Edit super user<\/h2>\"\n assert file =~ \"action: super_user_path(@conn, :update, @super_user)\"\n end\n\n assert_file \"web\/templates\/admin\/super_user\/form.html.eex\", fn file ->\n assert file =~ ~s(<%= text_input f, :name, class: \"form-control\" %>)\n end\n\n assert_file \"web\/templates\/admin\/super_user\/index.html.eex\", fn file ->\n assert file =~ \"

Listing super users<\/h2>\"\n assert file =~ \"Name<\/th>\"\n assert file =~ \"<%= for super_user <- @super_users do %>\"\n end\n\n assert_file \"web\/templates\/admin\/super_user\/new.html.eex\", fn file ->\n assert file =~ \"

New super user<\/h2>\"\n assert file =~ \"action: super_user_path(@conn, :create)\"\n end\n\n assert_file \"web\/templates\/admin\/super_user\/show.html.eex\", fn file ->\n assert file =~ \"

Show super user<\/h2>\"\n assert file =~ \"Name:<\/strong>\"\n assert file =~ \"<%= @super_user.name %>\"\n end\n\n assert_file \"test\/controllers\/admin\/super_user_controller_test.exs\", fn file ->\n assert file =~ ~S|assert html_response(conn, 200) =~ \"Listing super users\"|\n assert file =~ ~S|assert html_response(conn, 200) =~ \"New super user\"|\n assert file =~ ~S|assert html_response(conn, 200) =~ \"Show super user\"|\n assert file =~ ~S|assert html_response(conn, 200) =~ \"Edit super user\"|\n end\n\n assert_received {:mix_shell, :info, [\"\\nAdd the resource\" <> _ = message]}\n assert message =~ ~s(resources \"\/admin\/super_users\", Admin.SuperUserController)\n end\n end\n\n test \"generates html resource without model\" do\n in_tmp \"generates html resource without model\", fn ->\n Mix.Tasks.Phoenix.Gen.Html.run [\"Admin.User\", \"users\", \"--no-model\", \"name:string\"]\n\n refute File.exists? \"web\/models\/admin\/user.ex\"\n assert [] = Path.wildcard(\"priv\/repo\/migrations\/*_create_admin_user.exs\")\n\n assert_file \"web\/templates\/admin\/user\/form.html.eex\", fn file ->\n refute file =~ ~s(--no-model)\n end\n end\n end\n\n test \"plural can't contain a colon\" do\n assert_raise Mix.Error, fn ->\n Mix.Tasks.Phoenix.Gen.Html.run [\"Admin.User\", \"name:string\", \"foo:string\"]\n end\n end\n\n test \"plural can't have uppercased characters or camelized format\" do\n assert_raise Mix.Error, fn ->\n Mix.Tasks.Phoenix.Gen.Html.run [\"Admin.User\", \"Users\", \"foo:string\"]\n end\n\n assert_raise Mix.Error, fn ->\n Mix.Tasks.Phoenix.Gen.Html.run [\"Admin.User\", \"AdminUsers\", \"foo:string\"]\n end\n end\n\n test \"name is already defined\" do\n assert_raise Mix.Error, fn ->\n Mix.Tasks.Phoenix.Gen.Html.run [\"DupHTML\", \"duphtmls\"]\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"d09d3cd0b0eab6f730b5dffe2a5690311e5bdcfb","subject":"shadow buffer","message":"shadow buffer\n","repos":"grych\/drab,grych\/drab,grych\/drab","old_file":"lib\/drab\/live\/eex_engine.ex","new_file":"lib\/drab\/live\/eex_engine.ex","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"mit","lang":"Elixir"} {"commit":"c0a12a5622828729d9cf4d75e465a3a70d57d2ec","subject":"Int\u00e9gration des retours du mentor sur l'exercice \"Word Count\" de Exercism dans la track Elixir","message":"Int\u00e9gration des retours du mentor sur l'exercice \"Word Count\" de Exercism dans la track Elixir\n","repos":"TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts,TGITS\/programming-workouts","old_file":"exercism\/elixir\/word-count\/lib\/word_count.ex","new_file":"exercism\/elixir\/word-count\/lib\/word_count.ex","new_contents":"defmodule WordCount do\n @doc \"\"\"\n Count the number of words in the sentence.\n\n Words are compared case-insensitively.\n \"\"\"\n @spec count(String.t()) :: map\n def count(sentence) do\n sentence \n |> String.downcase()\n |> String.split(~r\/[^[:alnum:]-]+\/u, trim: true)\n |> Enum.frequencies()\n end\nend\n","old_contents":"defmodule WordCount do\n @doc \"\"\"\n Count the number of words in the sentence.\n\n Words are compared case-insensitively.\n \"\"\"\n @spec count(String.t()) :: map\n def count(sentence) do\n String.split(String.downcase(sentence),~r\/[^[:alnum:]-]+\/u, trim: true)\n |> Enum.frequencies()\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"ecd6c79fc2bc2d2a3f160033b579b4b1da589319","subject":"send 'CountPostView' event from V2.PostController","message":"send 'CountPostView' event from V2.PostController\n","repos":"ello\/apex,ello\/apex,ello\/apex","old_file":"apps\/ello_v2\/web\/controllers\/post_controller.ex","new_file":"apps\/ello_v2\/web\/controllers\/post_controller.ex","new_contents":"defmodule Ello.V2.PostController do\n use Ello.V2.Web, :controller\n alias Ello.Core.{Content, Content.Post}\n alias Ello.Events\n alias Ello.Events.CountPostView\n\n def show(conn, params) do\n with %Post{} = post <- load_post(conn, params),\n true <- owned_by_user(post, params) do\n track_post_view(conn, post)\n render(conn, post: post)\n else\n _ -> send_resp(conn, 404, \"\")\n end\n end\n\n defp load_post(conn, %{\"id\" => id_or_slug}) do\n Content.post(id_or_slug,\n conn.assigns[:current_user],\n conn.assigns[:allow_nsfw],\n conn.assigns[:allow_nudity]\n )\n end\n\n defp track_post_view(%{assigns: assigns} = conn, post) do\n current_user_id = case assigns[:current_user] do\n %{id: id} -> id\n _ -> nil\n end\n\n event = %CountPostView{\n post_ids: [post.id],\n current_user_id: current_user_id,\n stream_kind: \"post\",\n }\n Ello.Events.publish(event)\n end\n\n defp owned_by_user(post, %{\"user_id\" => \"~\" <> username}),\n do: post.author.username == username\n defp owned_by_user(post, %{\"user_id\" => user_id}),\n do: \"#{post.author.id}\" == user_id\n defp owned_by_user(_, _), do: true\n\nend\n","old_contents":"defmodule Ello.V2.PostController do\n use Ello.V2.Web, :controller\n alias Ello.Core.{Content, Content.Post}\n\n def show(conn, params) do\n with %Post{} = post <- load_post(conn, params),\n true <- owned_by_user(post, params) do\n render(conn, post: post)\n else\n _ -> send_resp(conn, 404, \"\")\n end\n end\n\n defp load_post(conn, %{\"id\" => id_or_slug}) do\n Content.post(id_or_slug,\n conn.assigns[:current_user],\n conn.assigns[:allow_nsfw],\n conn.assigns[:allow_nudity]\n )\n end\n\n defp owned_by_user(post, %{\"user_id\" => \"~\" <> username}),\n do: post.author.username == username\n defp owned_by_user(post, %{\"user_id\" => user_id}),\n do: \"#{post.author.id}\" == user_id\n defp owned_by_user(_, _), do: true\n\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"414599791d1c0bfe804fd6988230f9f47369e20a","subject":"refactor","message":"refactor\n","repos":"daewon\/til,daewon\/til,daewon\/til,daewon\/til,daewon\/til,daewon\/til","old_file":"exercism\/elixir\/zipper\/zipper.exs","new_file":"exercism\/elixir\/zipper\/zipper.exs","new_contents":"defmodule BinTree do\n @moduledoc \"\"\"\n A node in a binary tree.\n\n `value` is the value of a node.\n `left` is the left subtree (nil if no subtree).\n `right` is the right subtree (nil if no subtree).\n \"\"\"\n @type t :: %BinTree{ value: any,\n left: BinTree.t | nil,\n right: BinTree.t | nil }\n defstruct value: nil, left: nil, right: nil\nend\n\ndefmodule Zipper do\n # if trail is [], the position of zipper is root\n defstruct value: nil, left: nil, right: nil, trail: []\n\n def from_tree(bt) do\n %Zipper{value: bt.value, left: bt.left, right: bt.right}\n end\n\n def to_tree(%Zipper{trail: []} = z) do\n %BinTree{value: z.value, left: z.left, right: z.right}\n end\n def to_tree(%Zipper{trail: _} = z), do: z |> up |> to_tree\n\n def value(z), do: z.value\n\n def left(%Zipper{left: nil}), do: nil\n def left(%Zipper{left: left}=z) do\n %Zipper{value: left.value, left: left.left, right: left.right,\n trail: [{:left, z.value, z.right} | z.trail]}\n end\n\n def right(%Zipper{right: nil}), do: nil\n def right(%Zipper{right: right}=z) do\n %Zipper{value: right.value, left: right.left, right: right.right,\n trail: [{:right, z.value, z.left} | z.trail]}\n end\n\n def up(%Zipper{trail: []}), do: nil\n def up(%Zipper{trail: [{:left, val, right} | trail]} = z) do\n left = %BinTree{value: z.value, left: z.left, right: z.right}\n %Zipper{value: val, left: left, right: right, trail: trail}\n end\n def up(%Zipper{trail: [{:right, val, left}|trail]} = z) do\n right = %BinTree{value: z.value, left: z.left, right: z.right}\n %Zipper{value: val, left: left, right: right, trail: trail}\n end\n\n def set_value(z, v), do: %{z | value: v}\n def set_left(z, l), do: %{z | left: l}\n def set_right(z, r), do: %{z | right: r}\nend\n","old_contents":"defmodule BinTree do\n @moduledoc \"\"\"\n A node in a binary tree.\n\n `value` is the value of a node.\n `left` is the left subtree (nil if no subtree).\n `right` is the right subtree (nil if no subtree).\n \"\"\"\n @type t :: %BinTree{ value: any,\n left: BinTree.t | nil,\n right: BinTree.t | nil }\n defstruct value: nil, left: nil, right: nil\nend\n\ndefmodule Zipper do\n # if trail is [], the position of zipper is root\n defstruct value: nil, left: nil, right: nil, trail: []\n\n def from_tree(bt) do\n %Zipper{value: bt.value, left: bt.left, right: bt.right}\n end\n\n def to_tree(%Zipper{trail: []} = z) do\n %BinTree{value: z.value, left: z.left, right: z.right}\n end\n def to_tree(%Zipper{trail: _} = z), do: z |> up |> to_tree\n\n def value(z), do: z.value\n\n def left(%Zipper{left: nil}), do: nil\n def left(%Zipper{left: focus}=z) do\n %Zipper{value: focus.value, left: focus.left, right: focus.right,\n trail: [{:left, z.value, z.right} | z.trail]}\n end\n\n def right(%Zipper{right: nil}), do: nil\n def right(%Zipper{right: focus}=z) do\n %Zipper{value: focus.value, left: focus.left, right: focus.right,\n trail: [{:right, z.value, z.left} | z.trail]}\n end\n\n def up(%Zipper{trail: []}), do: nil\n def up(%Zipper{trail: [{:left, val, right} | trail]} = z) do\n left = %BinTree{value: z.value, left: z.left, right: z.right}\n %Zipper{value: val,\n left: left,\n right: right,\n trail: trail}\n end\n def up(%Zipper{trail: [{:right, val, left}|trail]} = z) do\n right = %BinTree{value: z.value, left: z.left, right: z.right}\n %Zipper{value: val,\n left: left,\n right: right,\n trail: trail}\n end\n\n def set_value(z, v), do: %{z | value: v}\n def set_left(z, l), do: %{z | left: l}\n def set_right(z, r), do: %{z | right: r}\nend\n","returncode":0,"stderr":"","license":"mpl-2.0","lang":"Elixir"} {"commit":"80f8ea51209ceab091d759a1cf19f0f5f3d01e28","subject":"Correct test expectation","message":"Correct test expectation\n","repos":"thetamind\/elixir_phoenix_poker,thetamind\/elixir_phoenix_poker","old_file":"apps\/poker_cli\/test\/poker_cli_test.exs","new_file":"apps\/poker_cli\/test\/poker_cli_test.exs","new_contents":"defmodule Poker.CLITest do\n use ExUnit.Case\n\n import ExUnit.CaptureIO\n\n doctest Poker.CLI\n\n test \"prints help\" do\n execute_main = fn ->\n Poker.CLI.main([\"help\"])\n end\n\n assert capture_io(execute_main) =~ \"Poker CLI\"\n end\n\n test \"simple game\" do\n execute_main = fn ->\n Poker.CLI.main([\"--seed\", \"AAAAAAAAAAAAAAAA\"])\n end\n\n assert capture_io(execute_main) =~ \"Your hand: 6d Kd 10d Ah Qh\"\n end\n\n test \"simple game seed\" do\n execute_main = fn ->\n Poker.CLI.main([\"--seed\", \"BBBBBBBBBBBBBBBB\"])\n end\n\n assert capture_io(execute_main) =~ \"Your hand: Kd 4c 10s Qc Qd\"\n end\nend\n","old_contents":"defmodule Poker.CLITest do\n use ExUnit.Case\n\n import ExUnit.CaptureIO\n\n doctest Poker.CLI\n\n test \"prints help\" do\n execute_main = fn ->\n Poker.CLI.main([\"help\"])\n end\n\n assert capture_io(execute_main) =~ \"Poker CLI\"\n end\n\n test \"simple game\" do\n execute_main = fn ->\n Poker.CLI.main([\"--seed\", \"AAAAAAAAAAAAAAAA\"])\n end\n\n assert capture_io(execute_main) =~ \"Your hand: As Kd Qh Jc\"\n end\n\n test \"simple game seed\" do\n execute_main = fn ->\n Poker.CLI.main([\"--seed\", \"BBBBBBBBBBBBBBBB\"])\n end\n\n assert capture_io(execute_main) =~ \"Your hand: Kd 4c 10s Qc Qd\"\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"85a0ed9ba46d78e7f9f95cef5f98069a694c1ccf","subject":"Fix call to Index.search in tiles controller","message":"Fix call to Index.search in tiles controller\n","repos":"dainst\/idai-field-web,dainst\/idai-field-web,dainst\/idai-field-web","old_file":"api\/lib\/worker\/images\/tiles_controller.ex","new_file":"api\/lib\/worker\/images\/tiles_controller.ex","new_contents":"defmodule Worker.Images.TilesController do\n\n alias Core.Config\n alias Worker.Images.TilesCreator\n\n def make_tiles do\n projects = Config.get(:couchdb_databases)\n make_tiles(projects)\n end\n def make_tiles(projects) do\n entries = projects\n |> Enum.flat_map(&tiles_for_project\/1)\n Enum.map(entries, &TilesCreator.create_tiles\/1)\n end\n\n defp tiles_for_project(project) do\n %{ documents: docs } = Api.Documents.Index.search(\"*\", 10, 0, nil, nil, [\"resource.georeference\"], nil, nil, [project])\n Enum.map(docs, fn %{resource: %{ :id => id, \"width\" => width, \"height\" => height }} ->\n {project, id, {width, height}}\n end)\n end\nend\n","old_contents":"defmodule Worker.Images.TilesController do\n\n alias Core.Config\n alias Worker.Images.TilesCreator\n\n def make_tiles do\n projects = Config.get(:couchdb_databases)\n make_tiles(projects)\n end\n def make_tiles(projects) do\n entries = projects\n |> Enum.flat_map(&tiles_for_project\/1)\n Enum.map(entries, &TilesCreator.create_tiles\/1)\n end\n\n defp tiles_for_project(project) do\n %{ documents: docs } = Api.Documents.Index.search \"*\", 10, 0, nil, nil, [\"resource.georeference\"], [project]\n Enum.map(docs, fn %{resource: %{ :id => id, \"width\" => width, \"height\" => height }} ->\n {project, id, {width, height}}\n end)\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"8512c361f05c90719514507fbfb39fb4e9887528","subject":"author sync orchestrator prototype","message":"author sync orchestrator prototype\n","repos":"grctest\/glasnost,grctest\/glasnost,cyberpunk-ventures\/glasnost,cyberpunk-ventures\/glasnost,grctest\/glasnost,cyberpunk-ventures\/glasnost","old_file":"lib\/glasnost\/blockchain\/sync_orchestrator.ex","new_file":"lib\/glasnost\/blockchain\/sync_orchestrator.ex","new_contents":"defmodule Glasnost.Orchestrator.AuthorSyncSup do\n use Supervisor\n alias Glasnost.Wrk\n\n def start_link(arg) do\n Supervisor.start_link(__MODULE__, arg)\n end\n\n def init(arg) do\n author_configs = RuntimeConfig.get(:authors) |> AtomicMap.convert(safe: false)\n Enum.each(author_configs, &validate_author_config\/1)\n children = for config <- author_configs do\n worker(Wrk.AuthorSync, [config])\n end\n\n supervise(children, strategy: :simple_one_for_one)\n end\n\n def validate_author_config(config) do\n %{tags: %{blacklist: _, whitelist: _}, account_name: _, author_alias:_ } = config\n end\nend\n","old_contents":"defmodule Glasnost.Orchestrator.AuthorSyncSup do\n use Supervisor\n\n def start_link(arg) do\n Supervisor.start_link(__MODULE__, arg)\n end\n\n def init(arg) do\n children = [\n worker(MyWorker, [arg], restart: :temporary)\n ]\n\n supervise(children, strategy: :simple_one_for_one)\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"cf5a14a9a4d656ba922b52b1c9ff0ec2812ea96a","subject":"Use get_format instead of conn.private","message":"Use get_format instead of conn.private\n\nThis abstraction allows Phoenix to change how they are storing the\nformat on the conn, and is the antonym to put_format which we use in\nFormatInjector plug.\n","repos":"hashrocket\/tilex,hashrocket\/tilex,hashrocket\/tilex","old_file":"lib\/tilex_web\/controllers\/post_controller.ex","new_file":"lib\/tilex_web\/controllers\/post_controller.ex","new_contents":"defmodule TilexWeb.PostController do\n use TilexWeb, :controller\n import Ecto.Query\n\n plug :load_channels when action in [:new, :create, :edit, :update]\n plug :extract_slug when action in [:show, :edit, :update]\n\n plug Guardian.Plug.EnsureAuthenticated, [handler: __MODULE__] when action in [:new, :create, :edit, :update]\n\n def unauthenticated(conn, _) do\n conn\n |> put_status(302)\n |> put_flash(:info, \"Authentication required\")\n |> redirect(to: \"\/\")\n end\n\n alias Tilex.{Post, Channel, Posts}\n\n def index(conn, %{\"q\" => search_query} = params) do\n page = params\n |> Map.get(\"page\", \"1\")\n |> String.to_integer\n\n {posts, posts_count} = Posts.by_search(search_query, page)\n render(conn, \"search_results.html\",\n posts: posts,\n posts_count: posts_count,\n page: page,\n query: search_query\n )\n end\n\n def index(conn, %{\"format\" => format}) when format in ~w(rss atom), do: redirect(conn, to: \"\/rss\")\n\n def index(conn, params) do\n page = params\n |> Map.get(\"page\", \"1\")\n |> String.to_integer\n\n posts = Posts.all(page)\n\n render(conn, \"index.html\", posts: posts, page: page)\n end\n\n def show(%{assigns: %{slug: slug}} = conn, _) do\n format = Phoenix.Controller.get_format(conn)\n post = Post\n |> Repo.get_by!(slug: slug)\n |> Repo.preload([:channel])\n |> Repo.preload([:developer])\n\n canonical_post = Application.get_env(:tilex, :canonical_domain) <> post_path(conn, :show, post)\n\n conn\n |> assign(:canonical_url, canonical_post)\n |> render(\"show.#{format}\", post: post)\n end\n\n def random(conn, _) do\n query = from post in Post,\n order_by: fragment(\"random()\"),\n limit: 1,\n preload: [:channel, :developer]\n\n post = Repo.one(query)\n\n render(conn, \"show.html\", post: post)\n end\n\n def new(conn, _params) do\n changeset = Post.changeset(%Post{})\n render conn, \"new.html\", changeset: changeset\n end\n\n def like(conn, %{\"slug\" => slug}) do\n likes = Tilex.Liking.like(slug)\n\n conn\n |> put_resp_content_type(\"application\/json\")\n |> send_resp(200, Poison.encode!(%{likes: likes}))\n end\n\n def unlike(conn, %{\"slug\" => slug}) do\n likes = Tilex.Liking.unlike(slug)\n\n conn\n |> put_resp_content_type(\"application\/json\")\n |> send_resp(200, Poison.encode!(%{likes: likes}))\n end\n\n def create(conn, %{\"post\" => post_params}) do\n developer = Guardian.Plug.current_resource(conn)\n\n changeset =\n %Post{}\n |> Map.put(:developer_id, developer.id)\n |> Post.changeset(post_params)\n\n case Repo.insert(changeset) do\n {:ok, post} ->\n conn\n |> put_flash(:info, \"Post created\")\n |> redirect(to: post_path(conn, :index))\n |> Tilex.Integrations.notify(post)\n\n {:error, changeset} ->\n render(conn, \"new.html\", changeset: changeset)\n end\n end\n\n def edit(conn, _params) do\n current_user = Guardian.Plug.current_resource(conn)\n\n post = case current_user.admin do\n false -> current_user\n |> assoc(:posts)\n |> Repo.get_by!(slug: conn.assigns.slug)\n true -> Repo.get_by!(Post, slug: conn.assigns.slug)\n end\n\n changeset = Post.changeset(post)\n\n render(conn, \"edit.html\", post: post, changeset: changeset)\n end\n\n def update(conn, %{\"post\" => post_params}) do\n current_user = Guardian.Plug.current_resource(conn)\n\n post = case current_user.admin do\n false -> current_user\n |> assoc(:posts)\n |> Repo.get_by!(slug: conn.assigns.slug)\n true -> Repo.get_by!(Post, slug: conn.assigns.slug)\n end\n\n changeset = Post.changeset(post, post_params)\n\n case Repo.update(changeset) do\n {:ok, post} ->\n conn\n |> put_flash(:info, \"Post Updated\")\n |> redirect(to: post_path(conn, :show, post))\n {:error, changeset} ->\n render(conn, \"edit.html\", post: post, changeset: changeset)\n end\n end\n\n defp load_channels(conn, _) do\n query = Channel\n |> Channel.names_and_ids\n |> Channel.alphabetized\n\n channels = Repo.all(query)\n assign(conn, :channels, channels)\n end\n\n defp extract_slug(conn, _) do\n case extracted_slug(conn.params[\"titled_slug\"]) do\n {:ok, slug} ->\n assign(conn, :slug, slug)\n :error ->\n conn\n |> put_status(404)\n |> render(TilexWeb.ErrorView, \"404.html\")\n |> halt()\n end\n end\n\n defp extracted_slug(<>), do: {:ok, slug}\n defp extracted_slug(_), do: :error\nend\n","old_contents":"defmodule TilexWeb.PostController do\n use TilexWeb, :controller\n import Ecto.Query\n\n plug :load_channels when action in [:new, :create, :edit, :update]\n plug :extract_slug when action in [:show, :edit, :update]\n\n plug Guardian.Plug.EnsureAuthenticated, [handler: __MODULE__] when action in [:new, :create, :edit, :update]\n\n def unauthenticated(conn, _) do\n conn\n |> put_status(302)\n |> put_flash(:info, \"Authentication required\")\n |> redirect(to: \"\/\")\n end\n\n alias Tilex.{Post, Channel, Posts}\n\n def index(conn, %{\"q\" => search_query} = params) do\n page = params\n |> Map.get(\"page\", \"1\")\n |> String.to_integer\n\n {posts, posts_count} = Posts.by_search(search_query, page)\n render(conn, \"search_results.html\",\n posts: posts,\n posts_count: posts_count,\n page: page,\n query: search_query\n )\n end\n\n def index(conn, %{\"format\" => format}) when format in ~w(rss atom), do: redirect(conn, to: \"\/rss\")\n\n def index(conn, params) do\n page = params\n |> Map.get(\"page\", \"1\")\n |> String.to_integer\n\n posts = Posts.all(page)\n\n render(conn, \"index.html\", posts: posts, page: page)\n end\n\n def show(conn, _) do\n %{assigns: %{slug: slug}, private: %{phoenix_format: format}} = conn\n post = Post\n |> Repo.get_by!(slug: slug)\n |> Repo.preload([:channel])\n |> Repo.preload([:developer])\n\n canonical_post = Application.get_env(:tilex, :canonical_domain) <> post_path(conn, :show, post)\n\n conn\n |> assign(:canonical_url, canonical_post)\n |> render(\"show.#{format}\", post: post)\n end\n\n def random(conn, _) do\n query = from post in Post,\n order_by: fragment(\"random()\"),\n limit: 1,\n preload: [:channel, :developer]\n\n post = Repo.one(query)\n\n render(conn, \"show.html\", post: post)\n end\n\n def new(conn, _params) do\n changeset = Post.changeset(%Post{})\n render conn, \"new.html\", changeset: changeset\n end\n\n def like(conn, %{\"slug\" => slug}) do\n likes = Tilex.Liking.like(slug)\n\n conn\n |> put_resp_content_type(\"application\/json\")\n |> send_resp(200, Poison.encode!(%{likes: likes}))\n end\n\n def unlike(conn, %{\"slug\" => slug}) do\n likes = Tilex.Liking.unlike(slug)\n\n conn\n |> put_resp_content_type(\"application\/json\")\n |> send_resp(200, Poison.encode!(%{likes: likes}))\n end\n\n def create(conn, %{\"post\" => post_params}) do\n developer = Guardian.Plug.current_resource(conn)\n\n changeset =\n %Post{}\n |> Map.put(:developer_id, developer.id)\n |> Post.changeset(post_params)\n\n case Repo.insert(changeset) do\n {:ok, post} ->\n conn\n |> put_flash(:info, \"Post created\")\n |> redirect(to: post_path(conn, :index))\n |> Tilex.Integrations.notify(post)\n\n {:error, changeset} ->\n render(conn, \"new.html\", changeset: changeset)\n end\n end\n\n def edit(conn, _params) do\n current_user = Guardian.Plug.current_resource(conn)\n\n post = case current_user.admin do\n false -> current_user\n |> assoc(:posts)\n |> Repo.get_by!(slug: conn.assigns.slug)\n true -> Repo.get_by!(Post, slug: conn.assigns.slug)\n end\n\n changeset = Post.changeset(post)\n\n render(conn, \"edit.html\", post: post, changeset: changeset)\n end\n\n def update(conn, %{\"post\" => post_params}) do\n current_user = Guardian.Plug.current_resource(conn)\n\n post = case current_user.admin do\n false -> current_user\n |> assoc(:posts)\n |> Repo.get_by!(slug: conn.assigns.slug)\n true -> Repo.get_by!(Post, slug: conn.assigns.slug)\n end\n\n changeset = Post.changeset(post, post_params)\n\n case Repo.update(changeset) do\n {:ok, post} ->\n conn\n |> put_flash(:info, \"Post Updated\")\n |> redirect(to: post_path(conn, :show, post))\n {:error, changeset} ->\n render(conn, \"edit.html\", post: post, changeset: changeset)\n end\n end\n\n defp load_channels(conn, _) do\n query = Channel\n |> Channel.names_and_ids\n |> Channel.alphabetized\n\n channels = Repo.all(query)\n assign(conn, :channels, channels)\n end\n\n defp extract_slug(conn, _) do\n case extracted_slug(conn.params[\"titled_slug\"]) do\n {:ok, slug} ->\n assign(conn, :slug, slug)\n :error ->\n conn\n |> put_status(404)\n |> render(TilexWeb.ErrorView, \"404.html\")\n |> halt()\n end\n end\n\n defp extracted_slug(<>), do: {:ok, slug}\n defp extracted_slug(_), do: :error\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"6715c528df2e372fde478e3f87fddfb8beb6523a","subject":"Improve error messages from typespecs, closes #1401","message":"Improve error messages from typespecs, closes #1401\n","repos":"antipax\/elixir,kimshrier\/elixir,ggcampinho\/elixir,ggcampinho\/elixir,kelvinst\/elixir,kimshrier\/elixir,lexmag\/elixir,michalmuskala\/elixir,lexmag\/elixir,joshprice\/elixir,gfvcastro\/elixir,antipax\/elixir,pedrosnk\/elixir,pedrosnk\/elixir,kelvinst\/elixir,gfvcastro\/elixir,beedub\/elixir,beedub\/elixir,elixir-lang\/elixir","old_file":"lib\/elixir\/lib\/kernel\/typespec.ex","new_file":"lib\/elixir\/lib\/kernel\/typespec.ex","new_contents":"defmodule Kernel.Typespec do\n @moduledoc \"\"\"\n Provides macros and functions for working with typespecs.\n\n The attributes `@type`, `@opaque`, `@typep`, `@spec` and\n `@callback` available in modules are handled by the equivalent\n macros defined by this module.\n\n ## Defining a type\n\n @type type_name :: type\n @typep type_name :: type\n @opaque type_name :: type\n\n For more details, see documentation for `deftype`, `deftypep` and `defopaque`\n below.\n\n ## Defining a specification\n\n @spec function_name(type, type) :: type\n @callback function_name(type, type) :: type\n\n For more details, see documentation for `defspec` and `defcallback` below.\n\n ## Types\n\n The type syntax provided by Elixir is fairly similar to the one\n in Erlang.\n\n Most of the built-in types provided in Erlang (for example, `pid()`)\n are expressed the same way: `pid()` or simply `pid`. Parametrized types\n are also supported (`list(integer())`) and so are remote types (`Enum.t`).\n\n Certain data type shortcuts (`[...]`, `<<>>` and `{...}`) are supported as\n well.\n\n Main differences lie in how bit strings and functions are defined:\n\n ### Bit Strings\n\n Bit string with a base size of 3:\n\n <<_ :: 3>>\n\n Bit string with a unit size of 8:\n\n <<_ :: _ * 8>>\n\n ### Anonymous functions\n\n Any anonymous function:\n\n ((...) -> any)\n or\n (... -> any)\n\n Anonymous function with arity of zero:\n\n (() -> type)\n\n Anonymous function with some arity:\n\n ((type, type) -> type)\n or\n (type, type -> type)\n\n ## Notes\n\n Elixir discourages the use of type `string()` as it might be confused\n with binaries which are referred to as \"strings\" in Elixir (as opposed to\n character lists). In order to use the type that is called `string()` in Erlang,\n one has to use the `char_list()` type which is a synonym for `string()`. If you\n use `string()`, you'll get a warning from the compiler.\n\n If you want to refer to the \"string\" type (the one operated by functions in the\n String module), use `String.t()` type instead.\n\n See http:\/\/www.erlang.org\/doc\/reference_manual\/typespec.html\n for more information.\n \"\"\"\n\n @doc \"\"\"\n Defines a type.\n This macro is the one responsible for handling the attribute `@type`.\n\n ## Examples\n\n @type my_type :: atom\n\n \"\"\"\n defmacro deftype(type) do\n quote do\n Kernel.Typespec.deftype(:type, unquote(Macro.escape type), __ENV__)\n end\n end\n\n @doc \"\"\"\n Defines an opaque type.\n This macro is the one responsible for handling the attribute `@opaque`.\n\n ## Examples\n\n @opaque my_type :: atom\n\n \"\"\"\n defmacro defopaque(type) do\n quote do\n Kernel.Typespec.deftype(:opaque, unquote(Macro.escape type), __ENV__)\n end\n end\n\n @doc \"\"\"\n Defines a private type.\n This macro is the one responsible for handling the attribute `@typep`.\n\n ## Examples\n\n @typep my_type :: atom\n\n \"\"\"\n defmacro deftypep(type) do\n quote do\n Kernel.Typespec.deftype(:typep, unquote(Macro.escape type), __ENV__)\n end\n end\n\n @doc \"\"\"\n Defines a spec.\n This macro is the one responsible for handling the attribute `@spec`.\n\n ## Examples\n\n @spec add(number, number) :: number\n\n \"\"\"\n defmacro defspec(spec) do\n quote do\n Kernel.Typespec.defspec(:spec, unquote(Macro.escape spec), __ENV__)\n end\n end\n\n @doc \"\"\"\n Defines a callback.\n This macro is the one responsible for handling the attribute `@callback`.\n\n ## Examples\n\n @callback add(number, number) :: number\n\n \"\"\"\n defmacro defcallback(spec) do\n quote do\n Kernel.Typespec.defspec(:callback, unquote(Macro.escape spec), __ENV__)\n end\n end\n\n ## Helpers\n\n @doc \"\"\"\n Defines a `type`, `typep` or `opaque` by receiving Erlang's typespec.\n \"\"\"\n def define_type(module, kind, { name, _, vars } = type) when kind in [:type, :typep, :opaque] do\n { kind, export } =\n case kind do\n :type -> { :type, true }\n :typep -> { :type, false }\n :opaque -> { :opaque, true }\n end\n\n Module.compile_typespec module, kind, type\n if export, do:\n Module.compile_typespec(module, :export_type, [{ name, length(vars) }])\n type\n end\n\n @doc \"\"\"\n Defines a `spec` by receiving Erlang's typespec.\n \"\"\"\n def define_spec(module, tuple, definition) do\n Module.compile_typespec module, :spec, { tuple, definition }\n end\n\n @doc \"\"\"\n Defines a `callback` by receiving Erlang's typespec.\n \"\"\"\n def define_callback(module, tuple, definition) do\n Module.compile_typespec module, :callback, { tuple, definition }\n end\n\n @doc \"\"\"\n Returns `true` if the current module defines a given type\n (private, opaque or not). This function is only available\n for modules being compiled.\n \"\"\"\n def defines_type?(module, name, arity) do\n finder = match?({ ^name, _, vars } when length(vars) == arity, &1)\n :lists.any(finder, Module.get_attribute(module, :type)) or\n :lists.any(finder, Module.get_attribute(module, :opaque))\n end\n\n @doc \"\"\"\n Returns `true` if the current module defines a given spec.\n This function is only available for modules being compiled.\n \"\"\"\n def defines_spec?(module, name, arity) do\n tuple = { name, arity }\n :lists.any(match?(^tuple, &1), Module.get_attribute(module, :spec))\n end\n\n @doc \"\"\"\n Returns `true` if the current module defines a callback.\n This function is only available for modules being compiled.\n \"\"\"\n def defines_callback?(module, name, arity) do\n tuple = { name, arity }\n :lists.any(match?(^tuple, &1), Module.get_attribute(module, :callback))\n end\n\n @doc \"\"\"\n Converts a spec clause back to Elixir AST.\n \"\"\"\n def spec_to_ast(name, { :type, line, :fun, [{:type, _, :product, args}, result] }) do\n args = lc arg inlist args, do: typespec_to_ast(arg)\n { :::, [line: line], [{ name, [line: line], args }, typespec_to_ast(result)] }\n end\n\n def spec_to_ast(name, { :type, line, :fun, [] }) do\n { :::, [line: line], [{ name, [line: line], [] }, quote(do: term)] }\n end\n\n def spec_to_ast(name, { :type, line, :bounded_fun, [{ :type, _, :fun, [{ :type, _, :product, args }, result] }, constraints] }) do\n [h|t] =\n lc {:type, line, :constraint, [{:atom, _, :is_subtype}, [var, type]]} inlist constraints do\n { :is_subtype, [line: line], [typespec_to_ast(var), typespec_to_ast(type)] }\n end\n\n args = lc arg inlist args, do: typespec_to_ast(arg)\n guards = Enum.reduce t, h, fn(x, acc) -> { :and, line, [acc, x] } end\n\n { :::, [line: line], [{ :when, [line: line], [{ name, [line: line], args }, guards] }, typespec_to_ast(result)] }\n end\n\n @doc \"\"\"\n Converts a type clause back to Elixir AST.\n \"\"\"\n def type_to_ast({ { :record, record }, fields, args }) when is_atom(record) do\n fields = lc field inlist fields, do: typespec_to_ast(field)\n args = lc arg inlist args, do: typespec_to_ast(arg)\n type = { :{}, [], [record|fields] }\n quote do: unquote(record)(unquote_splicing(args)) :: unquote(type)\n end\n\n def type_to_ast({ name, type, args }) do\n args = lc arg inlist args, do: typespec_to_ast(arg)\n quote do: unquote(name)(unquote_splicing(args)) :: unquote(typespec_to_ast(type))\n end\n\n @doc \"\"\"\n Returns all types available from the module's beam code.\n\n It is returned as a list of tuples where the first\n element is the type (`:typep`, `:type` and `:opaque`).\n\n The module has to have a corresponding beam file on the disk which can be\n located by the runtime system.\n \"\"\"\n def beam_types(module) do\n case abstract_code(module) do\n { :ok, abstract_code } ->\n exported_types = lc { :attribute, _, :export_type, types } inlist abstract_code, do: types\n exported_types = List.flatten(exported_types)\n\n lc { :attribute, _, kind, { name, _, args } = type } inlist abstract_code, kind in [:opaque, :type] do\n cond do\n kind == :opaque -> { :opaque, type }\n :lists.member({ name, length(args) }, exported_types) -> { :type, type }\n true -> { :typep, type }\n end\n end\n _ ->\n []\n end\n end\n\n @doc \"\"\"\n Returns all specs available from the module's beam code.\n\n It is returned as a list of tuples where the first\n element is spec name and arity and the second is the spec.\n\n The module has to have a corresponding beam file on the disk which can be\n located by the runtime system.\n \"\"\"\n def beam_specs(module) do\n from_abstract_code(module, :spec)\n end\n\n @doc \"\"\"\n Returns all callbacks available from the module's beam code.\n\n It is returned as a list of tuples where the first\n element is spec name and arity and the second is the spec.\n\n The module has to have a corresponding beam file on the disk which can be\n located by the runtime system.\n \"\"\"\n def beam_callbacks(module) do\n from_abstract_code(module, :callback)\n end\n\n defp from_abstract_code(module, kind) do\n case abstract_code(module) do\n { :ok, abstract_code } ->\n lc { :attribute, _, abs_kind, value } inlist abstract_code, kind == abs_kind, do: value\n _ ->\n []\n end\n end\n\n defp abstract_code(module) do\n case :beam_lib.chunks(abstract_code_beam(module), [:abstract_code]) do\n {:ok, { _, [{ :abstract_code, { _raw_abstract_v1, abstract_code } }] } } ->\n { :ok, abstract_code }\n _ ->\n []\n end\n end\n\n defp abstract_code_beam(module) when is_atom(module) do\n case :code.get_object_code(module) do\n { ^module, beam, _filename } -> beam\n :error -> module\n end\n end\n\n defp abstract_code_beam(binary) when is_binary(binary) do\n binary\n end\n\n ## Macro callbacks\n\n @doc false\n def deftype(kind, { :::, _, [type, definition] }, caller) do\n do_deftype(kind, type, definition, caller)\n end\n\n def deftype(kind, {name, _meta, args} = type, caller)\n when is_atom(name) and not is_list(args) do\n do_deftype(kind, type, { :term, [line: caller.line], nil }, caller)\n end\n\n def deftype(_kind, other, caller) do\n type_spec = Macro.to_string(other)\n compile_error caller, \"invalid type specification #{type_spec}\"\n end\n\n defp do_deftype(kind, { name, _, args }, definition, caller) do\n args =\n if is_atom(args) do\n []\n else\n lc(arg inlist args, do: variable(arg))\n end\n\n vars = lc { :var, _, var } inlist args, do: var\n spec = typespec(definition, vars, caller)\n\n vars = lc { :var, _, _ } = var inlist args, do: var\n type = { name, spec, vars }\n\n define_type(caller.module, kind, type)\n end\n\n @doc false\n def defspec(type, {:::, _, [{ :when, _, [{ name, meta, args }, constraints_guard] }, return] }, caller) do\n if is_atom(args), do: args = []\n constraints = guard_to_constraints(constraints_guard, caller)\n spec = { :type, line(meta), :fun, fn_args(meta, args, return, Keyword.keys(constraints), caller) }\n spec = { :type, line(meta), :bounded_fun, [spec, Keyword.values(constraints)] }\n code = { { name, Kernel.length(args) }, spec }\n Module.compile_typespec(caller.module, type, code)\n code\n end\n\n def defspec(type, {:::, _, [{ name, meta, args }, return]}, caller) do\n if is_atom(args), do: args = []\n spec = { :type, line(meta), :fun, fn_args(meta, args, return, [], caller) }\n code = { { name, Kernel.length(args) }, spec }\n Module.compile_typespec(caller.module, type, code)\n code\n end\n\n def defspec(_type, other, caller) do\n spec = Macro.to_string(other)\n compile_error caller, \"invalid function type specification #{spec}\"\n end\n\n defp guard_to_constraints({ :is_subtype, meta, [{ name, _, _ }, type] }, caller) do\n line = line(meta)\n contraints = [{ :atom, line, :is_subtype }, [{:var, line, name}, typespec(type, [], caller)]]\n [{ name, { :type, line, :constraint, contraints } }]\n end\n\n defp guard_to_constraints({ :and, _, [left, right] }, caller) do\n guard_to_constraints(left, caller) ++ guard_to_constraints(right, caller)\n end\n\n ## To AST conversion\n\n defp typespec_to_ast({ :type, line, :tuple, :any }) do\n typespec_to_ast({:type, line, :tuple, []})\n end\n\n defp typespec_to_ast({ :type, line, :tuple, args }) do\n args = lc arg inlist args, do: typespec_to_ast(arg)\n { :{}, [line: line], args }\n end\n\n defp typespec_to_ast({ :type, _line, :list, [arg] }) do\n case unpack_typespec_kw(arg, []) do\n { :ok, ast } -> ast\n :error -> [typespec_to_ast(arg)]\n end\n end\n\n defp typespec_to_ast({ :type, _line, :list, args }) do\n lc arg inlist args, do: typespec_to_ast(arg)\n end\n\n defp typespec_to_ast({ :type, line, :binary, [arg1, arg2] }) do\n [arg1, arg2] = lc arg inlist [arg1, arg2], do: typespec_to_ast(arg)\n cond do\n arg2 == 0 ->\n quote line: line, do: <<_ :: unquote(arg1)>>\n arg1 == 0 ->\n quote line: line, do: <<_ :: _ * unquote(arg2)>>\n true ->\n quote line: line, do: <<_ :: unquote(arg1) * unquote(arg2)>>\n end\n end\n\n defp typespec_to_ast({ :type, line, :union, args }) do\n args = lc arg inlist args, do: typespec_to_ast(arg)\n Enum.reduce tl(args), hd(args),\n fn(arg, expr) -> { :|, [line: line], [expr, arg] } end\n end\n\n defp typespec_to_ast({ :type, line, :fun, [{:type, _, :product, args}, result] }) do\n args = lc arg inlist args, do: typespec_to_ast(arg)\n { :->, [line: line], [{args, [line: line], typespec_to_ast(result)}] }\n end\n\n defp typespec_to_ast({ :type, line, :fun, [args, result] }) do\n { :->, [line: line], [{[typespec_to_ast(args)], [line: line], typespec_to_ast(result)}] }\n end\n\n defp typespec_to_ast({ :type, line, :fun, [] }) do\n typespec_to_ast({ :type, line, :fun, [{:type, line, :any}, {:type, line, :any, []} ] })\n end\n\n defp typespec_to_ast({ :type, line, :range, [left, right] }) do\n { :\"..\", [line: line], [typespec_to_ast(left), typespec_to_ast(right)] }\n end\n\n defp typespec_to_ast({ :type, line, name, args }) do\n args = lc arg inlist args, do: typespec_to_ast(arg)\n { name, [line: line], args }\n end\n\n defp typespec_to_ast({ :var, line, var }) do\n var =\n case atom_to_binary(var) do\n <<\"_\", c :: [binary, size(1)], rest :: binary>> ->\n binary_to_atom(\"_#{String.downcase(c)}#{rest}\")\n <> ->\n binary_to_atom(\"#{String.downcase(c)}#{rest}\")\n end\n { var, line, nil }\n end\n\n # Special shortcut(s)\n defp typespec_to_ast({ :remote_type, line, [{:atom, _, :elixir}, {:atom, _, :char_list}, []] }) do\n typespec_to_ast({:type, line, :char_list, []})\n end\n\n defp typespec_to_ast({ :remote_type, line, [{:atom, _, :elixir}, {:atom, _, :as_boolean}, [arg]] }) do\n typespec_to_ast({:type, line, :as_boolean, [arg]})\n end\n\n defp typespec_to_ast({ :remote_type, line, [mod, name, args] }) do\n args = lc arg inlist args, do: typespec_to_ast(arg)\n dot = { :., [line: line], [typespec_to_ast(mod), typespec_to_ast(name)] }\n { dot, [line: line], args }\n end\n\n defp typespec_to_ast({ :ann_type, line, [var, type] }) do\n { :::, [line: line], [typespec_to_ast(var), typespec_to_ast(type)] }\n end\n\n defp typespec_to_ast({ :typed_record_field,\n { :record_field, line, { :atom, line1, name }},\n type }) do\n typespec_to_ast({ :ann_type, line, [{ :var, line1, name }, type] })\n end\n\n defp typespec_to_ast({:type, _, :any}) do\n quote do: ...\n end\n\n defp typespec_to_ast({:paren_type, _, [type]}) do\n typespec_to_ast(type)\n end\n\n defp typespec_to_ast({ t, _line, atom }) when is_atom(t) do\n atom\n end\n\n defp typespec_to_ast(other), do: other\n\n ## From AST conversion\n\n defp line(meta) do\n case :lists.keyfind(:line, 1, meta) do\n { :line, line } -> line\n false -> 0\n end\n end\n\n # Handle unions\n defp typespec({ :|, meta, [_, _] } = exprs, vars, caller) do\n exprs = Enum.reverse(collect_union(exprs))\n union = lc e inlist exprs, do: typespec(e, vars, caller)\n { :type, line(meta), :union, union }\n end\n\n # Handle binaries\n defp typespec({:<<>>, meta, []}, _, _) do\n {:type, line(meta), :binary, [{:integer, line(meta), 0}, {:integer, line(meta), 0}]}\n end\n\n defp typespec({:<<>>, meta, [{:::, _, [{:_, meta1, atom}, {:*, _, [{:_, meta2, atom}, unit]}]}]}, _, _) when is_atom(atom) do\n {:type, line(meta), :binary, [{:integer, line(meta1), 0}, {:integer, line(meta2), unit}]}\n end\n\n defp typespec({:<<>>, meta, [{:::, meta1, [{:_, meta2, atom}, base]}]}, _, _) when is_atom(atom) do\n {:type, line(meta), :binary, [{:integer, line(meta1), base}, {:integer, line(meta2), 0}]}\n end\n\n # Handle ranges\n defp typespec({:\"..\", meta, args}, vars, caller) do\n typespec({:range, meta, args}, vars, caller)\n end\n\n # Handle special forms\n defp typespec({:__MODULE__, _, atom}, vars, caller) when is_atom(atom) do\n typespec(caller.module, vars, caller)\n end\n\n defp typespec({:__aliases__, _, _} = alias, vars, caller) do\n atom = Macro.expand alias, caller\n typespec(atom, vars, caller)\n end\n\n # Handle funs\n defp typespec({:->, meta, [{[{:fun, _, arguments}], cmeta, return}]}, vars, caller) when is_list(arguments) do\n typespec({:->, meta, [{arguments, cmeta, return}]}, vars, caller)\n end\n\n defp typespec({:->, meta, [{arguments, _, return}]}, vars, caller) when is_list(arguments) do\n args = fn_args(meta, arguments, return, vars, caller)\n { :type, line(meta), :fun, args }\n end\n\n # Handle type operator\n defp typespec({:\"::\", meta, [var, expr] }, vars, caller) do\n left = typespec(var, [elem(var, 0)|vars], caller)\n right = typespec(expr, vars, caller)\n { :ann_type, line(meta), [left, right] }\n end\n\n # Handle unary ops\n defp typespec({op, meta, [integer]}, _, _) when op in [:+, :-] and is_integer(integer) do\n { :op, line(meta), op, {:integer, line(meta), integer} }\n end\n\n # Handle access macro\n defp typespec({{:., meta, [Kernel, :access]}, meta1, [target, args]}, vars, caller) do\n access = {{:., meta, [Kernel, :access]}, meta1,\n [target, args ++ [_: { :any, [], [] }]]}\n typespec(Macro.expand(access, caller), vars, caller)\n end\n\n # Handle remote calls\n defp typespec({{:., meta, [remote, name]}, _, args} = orig, vars, caller) do\n remote = Macro.expand remote, caller\n unless is_atom(remote) do\n compile_error(caller, \"invalid remote in typespec: #{Macro.to_string(orig)}\")\n end\n remote_type({typespec(remote, vars, caller), meta, typespec(name, vars, caller), args}, vars, caller)\n end\n\n # Handle tuples\n defp typespec({:tuple, meta, atom}, vars, caller) when is_atom(atom) do\n typespec({:{}, meta, []}, vars, caller)\n end\n\n defp typespec({:{}, meta, []}, _, _) do\n { :type, line(meta), :tuple, :any }\n end\n\n defp typespec({:{}, meta, t}, vars, caller) when is_list(t) do\n args = lc e inlist t, do: typespec(e, vars, caller)\n { :type, line(meta), :tuple, args }\n end\n\n # Handle blocks\n defp typespec({:__block__, _meta, [arg]}, vars, caller) do\n typespec(arg, vars, caller)\n end\n\n # Handle variables or local calls\n defp typespec({name, meta, atom}, vars, caller) when is_atom(atom) do\n if :lists.member(name, vars) do\n { :var, line(meta), name }\n else\n typespec({name, meta, []}, vars, caller)\n end\n end\n\n # Handle local calls\n defp typespec({:string, meta, arguments}, vars, caller) do\n IO.write \"warning: string() type use is discouraged. For character lists, use \" <>\n \"char_list() type, for strings, String.t()\\n#{Exception.format_stacktrace(caller.stacktrace)}\"\n arguments = lc arg inlist arguments, do: typespec(arg, vars, caller)\n { :type, line(meta), :string, arguments }\n end\n\n defp typespec({:char_list, _meta, arguments}, vars, caller) do\n typespec((quote do: :elixir.char_list(unquote_splicing(arguments))), vars, caller)\n end\n\n defp typespec({:as_boolean, _meta, arguments}, vars, caller) do\n typespec((quote do: :elixir.as_boolean(unquote_splicing(arguments))), vars, caller)\n end\n\n defp typespec({name, meta, arguments}, vars, caller) do\n arguments = lc arg inlist arguments, do: typespec(arg, vars, caller)\n { :type, line(meta), name, arguments }\n end\n\n # Handle literals\n defp typespec(atom, _, _) when is_atom(atom) do\n { :atom, 0, atom }\n end\n\n defp typespec(integer, _, _) when is_integer(integer) do\n { :integer, 0, integer }\n end\n\n defp typespec([], vars, caller) do\n typespec({ nil, [], [] }, vars, caller)\n end\n\n defp typespec([spec], vars, caller) do\n typespec({ :list, [], [spec] }, vars, caller)\n end\n\n defp typespec([spec, {:\"...\", _, quoted}], vars, caller) when is_atom(quoted) do\n typespec({ :nonempty_list, [], [spec] }, vars, caller)\n end\n\n defp typespec([h|t] = l, vars, caller) do\n union = Enum.reduce(t, validate_kw(h, l, caller), fn(x, acc) ->\n { :|, [], [acc, validate_kw(x, l, caller)] }\n end)\n typespec({ :list, [], [union] }, vars, caller)\n end\n\n defp typespec(t, vars, caller) when is_tuple(t) do\n args = lc e inlist tuple_to_list(t), do: typespec(e, vars, caller)\n { :type, 0, :tuple, args }\n end\n\n ## Helpers\n\n defp compile_error(caller, desc) do\n raise CompileError, file: caller.file, line: caller.line, description: desc\n end\n\n defp remote_type({remote, meta, name, arguments}, vars, caller) do\n arguments = lc arg inlist arguments, do: typespec(arg, vars, caller)\n { :remote_type, line(meta), [ remote, name, arguments ] }\n end\n\n defp collect_union({ :|, _, [a, b] }), do: [b|collect_union(a)]\n defp collect_union(v), do: [v]\n\n defp validate_kw({ key, _ } = t, _, _caller) when is_atom(key), do: t\n defp validate_kw(_, original, caller) do\n compile_error(caller, \"unexpected list #{Macro.to_string original} in typespec\")\n end\n\n defp fn_args(meta, args, return, vars, caller) do\n case [fn_args(meta, args, vars, caller), typespec(return, vars, caller)] do\n [{:type, _, :any}, {:type, _, :any, []}] -> []\n x -> x\n end\n end\n\n defp fn_args(meta, [{:\"...\", _, _}], _vars, _caller) do\n { :type, line(meta), :any }\n end\n\n defp fn_args(meta, args, vars, caller) do\n args = lc arg inlist args, do: typespec(arg, vars, caller)\n { :type, line(meta), :product, args }\n end\n\n defp variable({name, meta, _}) do\n {:var, line(meta), name}\n end\n\n defp unpack_typespec_kw({ :type, _, :union, [\n next,\n { :type, _, :tuple, [{ :atom, _, atom }, type] }\n ] }, acc) do\n unpack_typespec_kw(next, [{atom, typespec_to_ast(type)}|acc])\n end\n\n defp unpack_typespec_kw({ :type, _, :tuple, [{ :atom, _, atom }, type] }, acc) do\n { :ok, [{atom, typespec_to_ast(type)}|acc] }\n end\n\n defp unpack_typespec_kw(_, _acc) do\n :error\n end\nend\n","old_contents":"defmodule Kernel.Typespec do\n @moduledoc \"\"\"\n Provides macros and functions for working with typespecs.\n\n The attributes `@type`, `@opaque`, `@typep`, `@spec` and\n `@callback` available in modules are handled by the equivalent\n macros defined by this module.\n\n ## Defining a type\n\n @type type_name :: type\n @typep type_name :: type\n @opaque type_name :: type\n\n For more details, see documentation for `deftype`, `deftypep` and `defopaque`\n below.\n\n ## Defining a specification\n\n @spec function_name(type, type) :: type\n @callback function_name(type, type) :: type\n\n For more details, see documentation for `defspec` and `defcallback` below.\n\n ## Types\n\n The type syntax provided by Elixir is fairly similar to the one\n in Erlang.\n\n Most of the built-in types provided in Erlang (for example, `pid()`)\n are expressed the same way: `pid()` or simply `pid`. Parametrized types\n are also supported (`list(integer())`) and so are remote types (`Enum.t`).\n\n Certain data type shortcuts (`[...]`, `<<>>` and `{...}`) are supported as\n well.\n\n Main differences lie in how bit strings and functions are defined:\n\n ### Bit Strings\n\n Bit string with a base size of 3:\n\n <<_ :: 3>>\n\n Bit string with a unit size of 8:\n\n <<_ :: _ * 8>>\n\n ### Anonymous functions\n\n Any anonymous function:\n\n ((...) -> any)\n or\n (... -> any)\n\n Anonymous function with arity of zero:\n\n (() -> type)\n\n Anonymous function with some arity:\n\n ((type, type) -> type)\n or\n (type, type -> type)\n\n ## Notes\n\n Elixir discourages the use of type `string()` as it might be confused\n with binaries which are referred to as \"strings\" in Elixir (as opposed to\n character lists). In order to use the type that is called `string()` in Erlang,\n one has to use the `char_list()` type which is a synonym for `string()`. If you\n use `string()`, you'll get a warning from the compiler.\n\n If you want to refer to the \"string\" type (the one operated by functions in the\n String module), use `String.t()` type instead.\n\n See http:\/\/www.erlang.org\/doc\/reference_manual\/typespec.html\n for more information.\n \"\"\"\n\n @doc \"\"\"\n Defines a type.\n This macro is the one responsible for handling the attribute `@type`.\n\n ## Examples\n\n @type my_type :: atom\n\n \"\"\"\n defmacro deftype(type) do\n quote do\n Kernel.Typespec.deftype(:type, unquote(Macro.escape type), __ENV__)\n end\n end\n\n @doc \"\"\"\n Defines an opaque type.\n This macro is the one responsible for handling the attribute `@opaque`.\n\n ## Examples\n\n @opaque my_type :: atom\n\n \"\"\"\n defmacro defopaque(type) do\n quote do\n Kernel.Typespec.deftype(:opaque, unquote(Macro.escape type), __ENV__)\n end\n end\n\n @doc \"\"\"\n Defines a private type.\n This macro is the one responsible for handling the attribute `@typep`.\n\n ## Examples\n\n @typep my_type :: atom\n\n \"\"\"\n defmacro deftypep(type) do\n quote do\n Kernel.Typespec.deftype(:typep, unquote(Macro.escape type), __ENV__)\n end\n end\n\n @doc \"\"\"\n Defines a spec.\n This macro is the one responsible for handling the attribute `@spec`.\n\n ## Examples\n\n @spec add(number, number) :: number\n\n \"\"\"\n defmacro defspec(spec) do\n quote do\n Kernel.Typespec.defspec(:spec, unquote(Macro.escape spec), __ENV__)\n end\n end\n\n @doc \"\"\"\n Defines a callback.\n This macro is the one responsible for handling the attribute `@callback`.\n\n ## Examples\n\n @callback add(number, number) :: number\n\n \"\"\"\n defmacro defcallback(spec) do\n quote do\n Kernel.Typespec.defspec(:callback, unquote(Macro.escape spec), __ENV__)\n end\n end\n\n ## Helpers\n\n @doc \"\"\"\n Defines a `type`, `typep` or `opaque` by receiving Erlang's typespec.\n \"\"\"\n def define_type(module, kind, { name, _, vars } = type) when kind in [:type, :typep, :opaque] do\n { kind, export } =\n case kind do\n :type -> { :type, true }\n :typep -> { :type, false }\n :opaque -> { :opaque, true }\n end\n\n Module.compile_typespec module, kind, type\n if export, do:\n Module.compile_typespec(module, :export_type, [{ name, length(vars) }])\n type\n end\n\n @doc \"\"\"\n Defines a `spec` by receiving Erlang's typespec.\n \"\"\"\n def define_spec(module, tuple, definition) do\n Module.compile_typespec module, :spec, { tuple, definition }\n end\n\n @doc \"\"\"\n Defines a `callback` by receiving Erlang's typespec.\n \"\"\"\n def define_callback(module, tuple, definition) do\n Module.compile_typespec module, :callback, { tuple, definition }\n end\n\n @doc \"\"\"\n Returns `true` if the current module defines a given type\n (private, opaque or not). This function is only available\n for modules being compiled.\n \"\"\"\n def defines_type?(module, name, arity) do\n finder = match?({ ^name, _, vars } when length(vars) == arity, &1)\n :lists.any(finder, Module.get_attribute(module, :type)) or\n :lists.any(finder, Module.get_attribute(module, :opaque))\n end\n\n @doc \"\"\"\n Returns `true` if the current module defines a given spec.\n This function is only available for modules being compiled.\n \"\"\"\n def defines_spec?(module, name, arity) do\n tuple = { name, arity }\n :lists.any(match?(^tuple, &1), Module.get_attribute(module, :spec))\n end\n\n @doc \"\"\"\n Returns `true` if the current module defines a callback.\n This function is only available for modules being compiled.\n \"\"\"\n def defines_callback?(module, name, arity) do\n tuple = { name, arity }\n :lists.any(match?(^tuple, &1), Module.get_attribute(module, :callback))\n end\n\n @doc \"\"\"\n Converts a spec clause back to Elixir AST.\n \"\"\"\n def spec_to_ast(name, { :type, line, :fun, [{:type, _, :product, args}, result] }) do\n args = lc arg inlist args, do: typespec_to_ast(arg)\n { :::, [line: line], [{ name, [line: line], args }, typespec_to_ast(result)] }\n end\n\n def spec_to_ast(name, { :type, line, :fun, [] }) do\n { :::, [line: line], [{ name, [line: line], [] }, quote(do: term)] }\n end\n\n def spec_to_ast(name, { :type, line, :bounded_fun, [{ :type, _, :fun, [{ :type, _, :product, args }, result] }, constraints] }) do\n [h|t] =\n lc {:type, line, :constraint, [{:atom, _, :is_subtype}, [var, type]]} inlist constraints do\n { :is_subtype, [line: line], [typespec_to_ast(var), typespec_to_ast(type)] }\n end\n\n args = lc arg inlist args, do: typespec_to_ast(arg)\n guards = Enum.reduce t, h, fn(x, acc) -> { :and, line, [acc, x] } end\n\n { :::, [line: line], [{ :when, [line: line], [{ name, [line: line], args }, guards] }, typespec_to_ast(result)] }\n end\n\n @doc \"\"\"\n Converts a type clause back to Elixir AST.\n \"\"\"\n def type_to_ast({ { :record, record }, fields, args }) when is_atom(record) do\n fields = lc field inlist fields, do: typespec_to_ast(field)\n args = lc arg inlist args, do: typespec_to_ast(arg)\n type = { :{}, [], [record|fields] }\n quote do: unquote(record)(unquote_splicing(args)) :: unquote(type)\n end\n\n def type_to_ast({ name, type, args }) do\n args = lc arg inlist args, do: typespec_to_ast(arg)\n quote do: unquote(name)(unquote_splicing(args)) :: unquote(typespec_to_ast(type))\n end\n\n @doc \"\"\"\n Returns all types available from the module's beam code.\n\n It is returned as a list of tuples where the first\n element is the type (`:typep`, `:type` and `:opaque`).\n\n The module has to have a corresponding beam file on the disk which can be\n located by the runtime system.\n \"\"\"\n def beam_types(module) do\n case abstract_code(module) do\n { :ok, abstract_code } ->\n exported_types = lc { :attribute, _, :export_type, types } inlist abstract_code, do: types\n exported_types = List.flatten(exported_types)\n\n lc { :attribute, _, kind, { name, _, args } = type } inlist abstract_code, kind in [:opaque, :type] do\n cond do\n kind == :opaque -> { :opaque, type }\n :lists.member({ name, length(args) }, exported_types) -> { :type, type }\n true -> { :typep, type }\n end\n end\n _ ->\n []\n end\n end\n\n @doc \"\"\"\n Returns all specs available from the module's beam code.\n\n It is returned as a list of tuples where the first\n element is spec name and arity and the second is the spec.\n\n The module has to have a corresponding beam file on the disk which can be\n located by the runtime system.\n \"\"\"\n def beam_specs(module) do\n from_abstract_code(module, :spec)\n end\n\n @doc \"\"\"\n Returns all callbacks available from the module's beam code.\n\n It is returned as a list of tuples where the first\n element is spec name and arity and the second is the spec.\n\n The module has to have a corresponding beam file on the disk which can be\n located by the runtime system.\n \"\"\"\n def beam_callbacks(module) do\n from_abstract_code(module, :callback)\n end\n\n defp from_abstract_code(module, kind) do\n case abstract_code(module) do\n { :ok, abstract_code } ->\n lc { :attribute, _, abs_kind, value } inlist abstract_code, kind == abs_kind, do: value\n _ ->\n []\n end\n end\n\n defp abstract_code(module) do\n case :beam_lib.chunks(abstract_code_beam(module), [:abstract_code]) do\n {:ok, { _, [{ :abstract_code, { _raw_abstract_v1, abstract_code } }] } } ->\n { :ok, abstract_code }\n _ ->\n []\n end\n end\n\n defp abstract_code_beam(module) when is_atom(module) do\n case :code.get_object_code(module) do\n { ^module, beam, _filename } -> beam\n :error -> module\n end\n end\n\n defp abstract_code_beam(binary) when is_binary(binary) do\n binary\n end\n\n ## Macro callbacks\n\n @doc false\n def deftype(kind, { :::, _, [type, definition] }, caller) do\n do_deftype(kind, type, definition, caller)\n end\n\n def deftype(kind, {name, _meta, args} = type, caller)\n when is_atom(name) and not is_list(args) do\n do_deftype(kind, type, { :term, [line: caller.line], nil }, caller)\n end\n\n def deftype(_kind, other, _caller) do\n type_spec = Macro.to_string(other)\n raise ArgumentError, message: \"invalid type specification #{type_spec}\"\n end\n\n defp do_deftype(kind, { name, _, args }, definition, caller) do\n args =\n if is_atom(args) do\n []\n else\n lc(arg inlist args, do: variable(arg))\n end\n\n vars = lc { :var, _, var } inlist args, do: var\n spec = typespec(definition, vars, caller)\n\n vars = lc { :var, _, _ } = var inlist args, do: var\n type = { name, spec, vars }\n\n define_type(caller.module, kind, type)\n end\n\n @doc false\n def defspec(type, {:::, _, [{ :when, _, [{ name, meta, args }, constraints_guard] }, return] }, caller) do\n if is_atom(args), do: args = []\n constraints = guard_to_constraints(constraints_guard, caller)\n spec = { :type, line(meta), :fun, fn_args(meta, args, return, Keyword.keys(constraints), caller) }\n spec = { :type, line(meta), :bounded_fun, [spec, Keyword.values(constraints)] }\n code = { { name, Kernel.length(args) }, spec }\n Module.compile_typespec(caller.module, type, code)\n code\n end\n\n def defspec(type, {:::, _, [{ name, meta, args }, return]}, caller) do\n if is_atom(args), do: args = []\n spec = { :type, line(meta), :fun, fn_args(meta, args, return, [], caller) }\n code = { { name, Kernel.length(args) }, spec }\n Module.compile_typespec(caller.module, type, code)\n code\n end\n\n def defspec(_type, other, _caller) do\n spec = Macro.to_string(other)\n raise ArgumentError, message: \"invalid function type specification #{spec}\"\n end\n\n defp guard_to_constraints({ :is_subtype, meta, [{ name, _, _ }, type] }, caller) do\n line = line(meta)\n contraints = [{ :atom, line, :is_subtype }, [{:var, line, name}, typespec(type, [], caller)]]\n [{ name, { :type, line, :constraint, contraints } }]\n end\n\n defp guard_to_constraints({ :and, _, [left, right] }, caller) do\n guard_to_constraints(left, caller) ++ guard_to_constraints(right, caller)\n end\n\n ## To AST conversion\n\n defp typespec_to_ast({ :type, line, :tuple, :any }) do\n typespec_to_ast({:type, line, :tuple, []})\n end\n\n defp typespec_to_ast({ :type, line, :tuple, args }) do\n args = lc arg inlist args, do: typespec_to_ast(arg)\n { :{}, [line: line], args }\n end\n\n defp typespec_to_ast({ :type, _line, :list, [arg] }) do\n case unpack_typespec_kw(arg, []) do\n { :ok, ast } -> ast\n :error -> [typespec_to_ast(arg)]\n end\n end\n\n defp typespec_to_ast({ :type, _line, :list, args }) do\n lc arg inlist args, do: typespec_to_ast(arg)\n end\n\n defp typespec_to_ast({ :type, line, :binary, [arg1, arg2] }) do\n [arg1, arg2] = lc arg inlist [arg1, arg2], do: typespec_to_ast(arg)\n cond do\n arg2 == 0 ->\n quote line: line, do: <<_ :: unquote(arg1)>>\n arg1 == 0 ->\n quote line: line, do: <<_ :: _ * unquote(arg2)>>\n true ->\n quote line: line, do: <<_ :: unquote(arg1) * unquote(arg2)>>\n end\n end\n\n defp typespec_to_ast({ :type, line, :union, args }) do\n args = lc arg inlist args, do: typespec_to_ast(arg)\n Enum.reduce tl(args), hd(args),\n fn(arg, expr) -> { :|, [line: line], [expr, arg] } end\n end\n\n defp typespec_to_ast({ :type, line, :fun, [{:type, _, :product, args}, result] }) do\n args = lc arg inlist args, do: typespec_to_ast(arg)\n { :->, [line: line], [{args, [line: line], typespec_to_ast(result)}] }\n end\n\n defp typespec_to_ast({ :type, line, :fun, [args, result] }) do\n { :->, [line: line], [{[typespec_to_ast(args)], [line: line], typespec_to_ast(result)}] }\n end\n\n defp typespec_to_ast({ :type, line, :fun, [] }) do\n typespec_to_ast({ :type, line, :fun, [{:type, line, :any}, {:type, line, :any, []} ] })\n end\n\n defp typespec_to_ast({ :type, line, :range, [left, right] }) do\n { :\"..\", [line: line], [typespec_to_ast(left), typespec_to_ast(right)] }\n end\n\n defp typespec_to_ast({ :type, line, name, args }) do\n args = lc arg inlist args, do: typespec_to_ast(arg)\n { name, [line: line], args }\n end\n\n defp typespec_to_ast({ :var, line, var }) do\n var =\n case atom_to_binary(var) do\n <<\"_\", c :: [binary, size(1)], rest :: binary>> ->\n binary_to_atom(\"_#{String.downcase(c)}#{rest}\")\n <> ->\n binary_to_atom(\"#{String.downcase(c)}#{rest}\")\n end\n { var, line, nil }\n end\n\n # Special shortcut(s)\n defp typespec_to_ast({ :remote_type, line, [{:atom, _, :elixir}, {:atom, _, :char_list}, []] }) do\n typespec_to_ast({:type, line, :char_list, []})\n end\n\n defp typespec_to_ast({ :remote_type, line, [{:atom, _, :elixir}, {:atom, _, :as_boolean}, [arg]] }) do\n typespec_to_ast({:type, line, :as_boolean, [arg]})\n end\n\n defp typespec_to_ast({ :remote_type, line, [mod, name, args] }) do\n args = lc arg inlist args, do: typespec_to_ast(arg)\n dot = { :., [line: line], [typespec_to_ast(mod), typespec_to_ast(name)] }\n { dot, [line: line], args }\n end\n\n defp typespec_to_ast({ :ann_type, line, [var, type] }) do\n { :::, [line: line], [typespec_to_ast(var), typespec_to_ast(type)] }\n end\n\n defp typespec_to_ast({ :typed_record_field,\n { :record_field, line, { :atom, line1, name }},\n type }) do\n typespec_to_ast({ :ann_type, line, [{ :var, line1, name }, type] })\n end\n\n defp typespec_to_ast({:type, _, :any}) do\n quote do: ...\n end\n\n defp typespec_to_ast({:paren_type, _, [type]}) do\n typespec_to_ast(type)\n end\n\n defp typespec_to_ast({ t, _line, atom }) when is_atom(t) do\n atom\n end\n\n defp typespec_to_ast(other), do: other\n\n ## From AST conversion\n\n defp line(meta) do\n case :lists.keyfind(:line, 1, meta) do\n { :line, line } -> line\n false -> 0\n end\n end\n\n # Handle unions\n defp typespec({ :|, meta, [_, _] } = exprs, vars, caller) do\n exprs = Enum.reverse(collect_union(exprs))\n union = lc e inlist exprs, do: typespec(e, vars, caller)\n { :type, line(meta), :union, union }\n end\n\n # Handle binaries\n defp typespec({:<<>>, meta, []}, _, _) do\n {:type, line(meta), :binary, [{:integer, line(meta), 0}, {:integer, line(meta), 0}]}\n end\n\n defp typespec({:<<>>, meta, [{:::, _, [{:_, meta1, atom}, {:*, _, [{:_, meta2, atom}, unit]}]}]}, _, _) when is_atom(atom) do\n {:type, line(meta), :binary, [{:integer, line(meta1), 0}, {:integer, line(meta2), unit}]}\n end\n\n defp typespec({:<<>>, meta, [{:::, meta1, [{:_, meta2, atom}, base]}]}, _, _) when is_atom(atom) do\n {:type, line(meta), :binary, [{:integer, line(meta1), base}, {:integer, line(meta2), 0}]}\n end\n\n # Handle ranges\n defp typespec({:\"..\", meta, args}, vars, caller) do\n typespec({:range, meta, args}, vars, caller)\n end\n\n # Handle special forms\n defp typespec({:__MODULE__, _, atom}, vars, caller) when is_atom(atom) do\n typespec(caller.module, vars, caller)\n end\n\n defp typespec({:__aliases__, _, _} = alias, vars, caller) do\n atom = Macro.expand alias, caller\n typespec(atom, vars, caller)\n end\n\n # Handle funs\n defp typespec({:->, meta, [{[{:fun, _, arguments}], cmeta, return}]}, vars, caller) when is_list(arguments) do\n typespec({:->, meta, [{arguments, cmeta, return}]}, vars, caller)\n end\n\n defp typespec({:->, meta, [{arguments, _, return}]}, vars, caller) when is_list(arguments) do\n args = fn_args(meta, arguments, return, vars, caller)\n { :type, line(meta), :fun, args }\n end\n\n # Handle type operator\n defp typespec({:\"::\", meta, [var, expr] }, vars, caller) do\n left = typespec(var, [elem(var, 0)|vars], caller)\n right = typespec(expr, vars, caller)\n { :ann_type, line(meta), [left, right] }\n end\n\n # Handle unary ops\n defp typespec({op, meta, [integer]}, _, _) when op in [:+, :-] and is_integer(integer) do\n { :op, line(meta), op, {:integer, line(meta), integer} }\n end\n\n # Handle access macro\n defp typespec({{:., meta, [Kernel, :access]}, meta1, [target, args]}, vars, caller) do\n access = {{:., meta, [Kernel, :access]}, meta1,\n [target, args ++ [_: { :any, [], [] }]]}\n typespec(Macro.expand(access, caller), vars, caller)\n end\n\n # Handle remote calls\n defp typespec({{:., meta, [remote, name]}, _, args}, vars, caller) do\n remote = Macro.expand remote, caller\n unless is_atom(remote), do: raise(ArgumentError, message: \"invalid remote in typespec\")\n remote_type({typespec(remote, vars, caller), meta, typespec(name, vars, caller), args}, vars, caller)\n end\n\n # Handle tuples\n defp typespec({:tuple, meta, atom}, vars, caller) when is_atom(atom) do\n typespec({:{}, meta, []}, vars, caller)\n end\n\n defp typespec({:{}, meta, []}, _, _) do\n { :type, line(meta), :tuple, :any }\n end\n\n defp typespec({:{}, meta, t}, vars, caller) when is_list(t) do\n args = lc e inlist t, do: typespec(e, vars, caller)\n { :type, line(meta), :tuple, args }\n end\n\n # Handle blocks\n defp typespec({:__block__, _meta, [arg]}, vars, caller) do\n typespec(arg, vars, caller)\n end\n\n # Handle variables or local calls\n defp typespec({name, meta, atom}, vars, caller) when is_atom(atom) do\n if :lists.member(name, vars) do\n { :var, line(meta), name }\n else\n typespec({name, meta, []}, vars, caller)\n end\n end\n\n # Handle local calls\n defp typespec({:string, meta, arguments}, vars, caller) do\n IO.write \"warning: string() type use is discouraged. For character lists, use \" <>\n \"char_list() type, for strings, String.t()\\n#{Exception.format_stacktrace(caller.stacktrace)}\"\n arguments = lc arg inlist arguments, do: typespec(arg, vars, caller)\n { :type, line(meta), :string, arguments }\n end\n\n defp typespec({:char_list, _meta, arguments}, vars, caller) do\n typespec((quote do: :elixir.char_list(unquote_splicing(arguments))), vars, caller)\n end\n\n defp typespec({:as_boolean, _meta, arguments}, vars, caller) do\n typespec((quote do: :elixir.as_boolean(unquote_splicing(arguments))), vars, caller)\n end\n\n defp typespec({name, meta, arguments}, vars, caller) do\n arguments = lc arg inlist arguments, do: typespec(arg, vars, caller)\n { :type, line(meta), name, arguments }\n end\n\n # Handle literals\n defp typespec(atom, _, _) when is_atom(atom) do\n { :atom, 0, atom }\n end\n\n defp typespec(integer, _, _) when is_integer(integer) do\n { :integer, 0, integer }\n end\n\n defp typespec([], vars, caller) do\n typespec({ nil, [], [] }, vars, caller)\n end\n\n defp typespec([spec], vars, caller) do\n typespec({ :list, [], [spec] }, vars, caller)\n end\n\n defp typespec([spec, {:\"...\", _, quoted}], vars, caller) when is_atom(quoted) do\n typespec({ :nonempty_list, [], [spec] }, vars, caller)\n end\n\n defp typespec([h|t] = l, vars, caller) do\n union = Enum.reduce(t, validate_kw(h, l), fn(x, acc) ->\n { :|, [], [acc, validate_kw(x, l)] }\n end)\n typespec({ :list, [], [union] }, vars, caller)\n end\n\n defp typespec(t, vars, caller) when is_tuple(t) do\n args = lc e inlist tuple_to_list(t), do: typespec(e, vars, caller)\n { :type, 0, :tuple, args }\n end\n\n ## Helpers\n\n defp remote_type({remote, meta, name, arguments}, vars, caller) do\n arguments = lc arg inlist arguments, do: typespec(arg, vars, caller)\n { :remote_type, line(meta), [ remote, name, arguments ] }\n end\n\n defp collect_union({ :|, _, [a, b] }), do: [b|collect_union(a)]\n defp collect_union(v), do: [v]\n\n defp validate_kw({ key, _ } = t, _) when is_atom(key), do: t\n defp validate_kw(_, original) do\n raise ArgumentError, message: \"unexpected list #{inspect original} in typespec\"\n end\n\n defp fn_args(meta, args, return, vars, caller) do\n case [fn_args(meta, args, vars, caller), typespec(return, vars, caller)] do\n [{:type, _, :any}, {:type, _, :any, []}] -> []\n x -> x\n end\n end\n\n defp fn_args(meta, [{:\"...\", _, _}], _vars, _caller) do\n { :type, line(meta), :any }\n end\n\n defp fn_args(meta, args, vars, caller) do\n args = lc arg inlist args, do: typespec(arg, vars, caller)\n { :type, line(meta), :product, args }\n end\n\n defp variable({name, meta, _}) do\n {:var, line(meta), name}\n end\n\n defp unpack_typespec_kw({ :type, _, :union, [\n next,\n { :type, _, :tuple, [{ :atom, _, atom }, type] }\n ] }, acc) do\n unpack_typespec_kw(next, [{atom, typespec_to_ast(type)}|acc])\n end\n\n defp unpack_typespec_kw({ :type, _, :tuple, [{ :atom, _, atom }, type] }, acc) do\n { :ok, [{atom, typespec_to_ast(type)}|acc] }\n end\n\n defp unpack_typespec_kw(_, _acc) do\n :error\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"c91665de86a799e4d7e6ada222ccbb46aef11aa3","subject":"Disable debug messages in farm event manager.","message":"Disable debug messages in farm event manager.\n","repos":"FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os","old_file":"lib\/farmbot\/farm_event\/manager.ex","new_file":"lib\/farmbot\/farm_event\/manager.ex","new_contents":"defmodule Farmbot.FarmEvent.Manager do\n @moduledoc \"\"\"\n Manages execution of FarmEvents.\n\n ## Rules for FarmEvent execution.\n * Regimen\n * ignore `end_time`.\n * ignore calendar.\n * if start_time is more than 60 seconds passed due, assume it already started, and don't start it again.\n * Sequence\n * if `start_time` is late, check the calendar.\n * for each item in the calendar, check if it's event is more than 60 seconds in the past. if not, execute it.\n * if there is only one event in the calendar, ignore the `end_time`\n \"\"\"\n\n # credo:disable-for-this-file Credo.Check.Refactor.FunctionArity\n\n use GenServer\n use Farmbot.Logger\n alias Farmbot.FarmEvent.Execution\n alias Farmbot.Repo.FarmEvent\n\n @checkup_time 20_000\n\n def wait_for_sync do\n GenServer.call(__MODULE__, :wait_for_sync, :infinity)\n end\n\n def resume do\n GenServer.call(__MODULE__, :resume)\n end\n\n ## GenServer\n\n defmodule State do\n @moduledoc false\n defstruct [timer: nil, last_time_index: %{}, wait_for_sync: true]\n end\n\n @doc false\n def start_link do\n GenServer.start_link(__MODULE__, [], [name: __MODULE__])\n end\n\n def init([]) do\n {:ok, struct(State)}\n end\n\n def handle_call(:wait_for_sync, _, state) do\n if state.timer do\n Process.cancel_timer(state.timer)\n end\n Logger.busy 3, \"Pausing FarmEvent Execution until sync.\"\n {:reply, :ok, %{state | wait_for_sync: true}}\n end\n\n def handle_call(:resume, _, state) do\n send self(), :checkup\n Logger.success 3, \"Resuming FarmEvents.\"\n {:reply, :ok, %{state | wait_for_sync: false}}\n end\n\n def handle_info(:checkup, %{wait_for_sync: true} = state) do\n Logger.warn 3, \"Waiting for sync before running FarmEvents.\"\n {:noreply, state}\n end\n\n def handle_info(:checkup, %{wait_for_sync: false} = state) do\n now = get_now()\n\n all_events = Farmbot.Repo.current_repo().all(Farmbot.Repo.FarmEvent)\n\n # do checkup is the bulk of the work.\n {late_events, new} = do_checkup(all_events, now, state)\n\n #TODO(Connor) Conditionally start events based on some state info.\n unless Enum.empty?(late_events) do\n Logger.info 3, \"Time for event to run at: #{now.hour}:#{now.minute}\"\n start_events(late_events, now)\n end\n\n # Start a new timer.\n timer = Process.send_after self(), :checkup, @checkup_time\n {:noreply, %{new | timer: timer}}\n end\n\n defp do_checkup(list, time, late_events \\\\ [], state)\n\n defp do_checkup([], _now, late_events, state), do: {late_events, state}\n\n defp do_checkup([farm_event | rest], now, late_events, state) do\n # new_late will be a executable event (Regimen or Sequence.)\n {new_late_event, last_time} = check_event(farm_event, now, state.last_time_index[farm_event.id])\n\n # update state.\n new_state = %{state | last_time_index: Map.put(state.last_time_index, farm_event.id, last_time)}\n case new_late_event do\n # if `new_late_event` is nil, don't accumulate it.\n nil -> do_checkup(rest, now, late_events, new_state)\n # if there is a new event, accumulate it.\n event -> do_checkup(rest, now, [event | late_events], new_state)\n end\n end\n\n defp check_event(%FarmEvent{} = f, now, last_time) do\n # Get the executable out of the database this may fail.\n # mod_list = [\"Farmbot\", \"Repo\", f.executable_type]\n mod = Module.safe_concat([f.executable_type])\n\n event = lookup(mod, f.executable_id)\n\n # build a local start time and end time\n start_time = Timex.parse! f.start_time, \"{ISO:Extended}\"\n end_time = Timex.parse! f.end_time, \"{ISO:Extended}\"\n # start_time = f.start_time\n # end_time = f.end_time\n # get local bool of if the event is started and finished.\n started? = Timex.after? now, start_time\n finished? = Timex.after? now, end_time\n\n case f.executable_type do\n \"Elixir.Farmbot.Repo.Regimen\" -> maybe_start_regimen(started?, start_time, last_time, event, now)\n \"Elixir.Farmbot.Repo.Sequence\" -> maybe_start_sequence(started?, finished?, f, last_time, event, now)\n end\n end\n\n defp maybe_start_regimen(started?, start_time, last_time, event, now)\n defp maybe_start_regimen(true = _started?, start_time, last_time, event, now) do\n case is_too_old?(now, start_time) do\n true ->\n Logger.debug 3, \"regimen #{event.name} (#{event.id}) is too old to start.\"\n {nil, last_time}\n false ->\n Logger.debug 3, \"regimen #{event.name} (#{event.id}) not to old; starting.\"\n {event, now}\n end\n end\n\n defp maybe_start_regimen(false = _started?, start_time, last_time, event, _) do\n Logger.debug 3, \"regimen #{event.name} (#{event.id}) is not started yet. (#{inspect start_time}) (#{inspect Timex.now()})\"\n {nil, last_time}\n end\n\n defp lookup(module, sr_id) do\n case Farmbot.Repo.current_repo().get(module, sr_id) do\n nil -> raise \"Could not find #{module} by id: #{sr_id}\"\n item -> item\n end\n end\n\n # signals the start of a sequence based on the described logic.\n defp maybe_start_sequence(started?, finished?, farm_event, last_time, event, now)\n\n # We only want to check if the sequence is started, and not finished.\n defp maybe_start_sequence(true = _started?, false = _finished?, farm_event, last_time, event, now) do\n {run?, next_time} = should_run_sequence?(farm_event.calendar, last_time, now)\n case run? do\n true -> {event, next_time}\n false -> {nil, last_time}\n end\n end\n\n # if `farm_event.time_unit` is \"never\" we can't use the `end_time`.\n # if we have no `last_time`, time to execute.\n defp maybe_start_sequence(true = _started?, _, %{time_unit: \"never\"} = f, nil = _last_time, event, now) do\n # Logger.debug 3, \"Ignoring end_time.\"\n case should_run_sequence?(f.calendar, nil, now) do\n {true, next} -> {event, next}\n {false, _} -> {nil, nil}\n end\n end\n\n # if started is false, the event isn't ready to be executed.\n defp maybe_start_sequence(false = _started?, _fin, _farm_event, last_time, event, _now) do\n # Logger.debug 3, \"sequence #{event.name} (#{event.id}) is not started yet.\"\n {nil, last_time}\n end\n\n # if the event is finished (but not a \"never\" time_unit), we don't execute.\n defp maybe_start_sequence(_started?, true = _finished?, _farm_event, last_time, event, _now) do\n Logger.success 3, \"sequence #{event.name} (#{event.id}) is finished.\"\n {nil, last_time}\n end\n\n # Checks if we shoudl run a sequence or not. returns {event | nil, time | nil}\n defp should_run_sequence?(calendar, last_time, now)\n\n # if there is no last time, check if time is passed now within 60 seconds.\n defp should_run_sequence?([first_time | _], nil, now) do\n\n # Logger.debug 3, \"Checking sequence event that hasn't run before #{first_time}\"\n # convert the first_time to a DateTime\n dt = Timex.parse! first_time, \"{ISO:Extended}\"\n # if now is after the time, we are in fact late\n if Timex.after?(now, dt) do\n {true, now}\n else\n # make sure to return nil as the last time because it stil hasnt executed yet.\n # Logger.debug 3, \"Sequence Event not ready yet.\"\n {false, nil}\n end\n end\n\n defp should_run_sequence?(nil, last_time, now) do\n # Logger.debug 3, \"Checking sequence with no calendar.\"\n if is_nil(last_time) do\n {true, now}\n else\n {false, last_time}\n end\n end\n\n defp should_run_sequence?(calendar, last_time, now) do\n # get rid of all the items that happened before last_time\n filtered_calendar = Enum.filter(calendar, fn(iso_time) ->\n dt = Timex.parse! iso_time, \"{ISO:Extended}\"\n # we only want this time if it happened after the last_time\n Timex.after?(dt, last_time)\n end)\n\n # if after filtering, there are events that need to be run\n # check if they are older than a minute ago,\n case filtered_calendar do\n [iso_time | _] ->\n dt = Timex.parse! iso_time, \"{ISO:Extended}\"\n if Timex.after?(now, dt) do\n {true, dt}\n # too_old? = is_too_old?(now, dt)\n # if too_old?, do: {false, last_time}, else: {true, dt}\n else\n # Logger.debug 3, \"Sequence Event not ready yet.\"\n {false, dt}\n end\n [] ->\n # Logger.debug 3, \"No items in calendar.\"\n {false, last_time}\n end\n end\n\n # Enumeration is complete.\n defp start_events([], _now), do: :ok\n\n # Enumerate the events to be started.\n defp start_events([event | rest], now) do\n # Spawn to be non blocking here. Maybe link to this process?\n spawn fn() -> Execution.execute_event(event, now) end\n # Continue enumeration.\n start_events(rest, now)\n end\n\n # is then more than 1 minute in the past?\n defp is_too_old?(now, then) do\n time_str_fun = fn(dt) -> \"#{dt.hour}:#{dt.minute}:#{dt.second}\" end\n seconds = DateTime.to_unix(now, :second) - DateTime.to_unix(then, :second)\n c = seconds > 60 # not in MS here\n # Logger.debug 3, \"is checking #{time_str_fun.(now)} - #{time_str_fun.(then)} = #{seconds} seconds ago. is_too_old? => #{c}\"\n c\n end\n\n defp get_now(), do: Timex.now()\nend\n","old_contents":"defmodule Farmbot.FarmEvent.Manager do\n @moduledoc \"\"\"\n Manages execution of FarmEvents.\n\n ## Rules for FarmEvent execution.\n * Regimen\n * ignore `end_time`.\n * ignore calendar.\n * if start_time is more than 60 seconds passed due, assume it already started, and don't start it again.\n * Sequence\n * if `start_time` is late, check the calendar.\n * for each item in the calendar, check if it's event is more than 60 seconds in the past. if not, execute it.\n * if there is only one event in the calendar, ignore the `end_time`\n \"\"\"\n\n # credo:disable-for-this-file Credo.Check.Refactor.FunctionArity\n\n use GenServer\n use Farmbot.Logger\n alias Farmbot.FarmEvent.Execution\n alias Farmbot.Repo.FarmEvent\n\n @checkup_time 20_000\n\n def wait_for_sync do\n GenServer.call(__MODULE__, :wait_for_sync, :infinity)\n end\n\n def resume do\n GenServer.call(__MODULE__, :resume)\n end\n\n ## GenServer\n\n defmodule State do\n @moduledoc false\n defstruct [timer: nil, last_time_index: %{}, wait_for_sync: true]\n end\n\n @doc false\n def start_link do\n GenServer.start_link(__MODULE__, [], [name: __MODULE__])\n end\n\n def init([]) do\n {:ok, struct(State)}\n end\n\n def handle_call(:wait_for_sync, _, state) do\n if state.timer do\n Process.cancel_timer(state.timer)\n end\n Logger.warn 3, \"Pausing FarmEvent Execution until sync.\"\n {:reply, :ok, %{state | wait_for_sync: true}}\n end\n\n def handle_call(:resume, _, state) do\n send self(), :checkup\n Logger.success 3, \"Resuming FarmEvents.\"\n {:reply, :ok, %{state | wait_for_sync: false}}\n end\n\n def handle_info(:checkup, %{wait_for_sync: true} = state) do\n Logger.warn 3, \"Waiting for sync before running FarmEvents.\"\n {:noreply, state}\n end\n\n def handle_info(:checkup, %{wait_for_sync: false} = state) do\n now = get_now()\n\n all_events = Farmbot.Repo.current_repo().all(Farmbot.Repo.FarmEvent)\n\n # do checkup is the bulk of the work.\n {late_events, new} = do_checkup(all_events, now, state)\n\n #TODO(Connor) Conditionally start events based on some state info.\n unless Enum.empty?(late_events) do\n Logger.info 3, \"Time for event to run at: #{now.hour}:#{now.minute}\"\n start_events(late_events, now)\n end\n\n # Start a new timer.\n timer = Process.send_after self(), :checkup, @checkup_time\n {:noreply, %{new | timer: timer}}\n end\n\n defp do_checkup(list, time, late_events \\\\ [], state)\n\n defp do_checkup([], _now, late_events, state), do: {late_events, state}\n\n defp do_checkup([farm_event | rest], now, late_events, state) do\n # new_late will be a executable event (Regimen or Sequence.)\n {new_late_event, last_time} = check_event(farm_event, now, state.last_time_index[farm_event.id])\n\n # update state.\n new_state = %{state | last_time_index: Map.put(state.last_time_index, farm_event.id, last_time)}\n case new_late_event do\n # if `new_late_event` is nil, don't accumulate it.\n nil -> do_checkup(rest, now, late_events, new_state)\n # if there is a new event, accumulate it.\n event -> do_checkup(rest, now, [event | late_events], new_state)\n end\n end\n\n defp check_event(%FarmEvent{} = f, now, last_time) do\n # Get the executable out of the database this may fail.\n # mod_list = [\"Farmbot\", \"Repo\", f.executable_type]\n mod = Module.safe_concat([f.executable_type])\n\n event = lookup(mod, f.executable_id)\n\n # build a local start time and end time\n start_time = Timex.parse! f.start_time, \"{ISO:Extended}\"\n end_time = Timex.parse! f.end_time, \"{ISO:Extended}\"\n # start_time = f.start_time\n # end_time = f.end_time\n # get local bool of if the event is started and finished.\n started? = Timex.after? now, start_time\n finished? = Timex.after? now, end_time\n\n case f.executable_type do\n \"Elixir.Farmbot.Repo.Regimen\" -> maybe_start_regimen(started?, start_time, last_time, event, now)\n \"Elixir.Farmbot.Repo.Sequence\" -> maybe_start_sequence(started?, finished?, f, last_time, event, now)\n end\n end\n\n defp maybe_start_regimen(started?, start_time, last_time, event, now)\n defp maybe_start_regimen(true = _started?, start_time, last_time, event, now) do\n case is_too_old?(now, start_time) do\n true ->\n Logger.debug 3, \"regimen #{event.name} (#{event.id}) is too old to start.\"\n {nil, last_time}\n false ->\n Logger.debug 3, \"regimen #{event.name} (#{event.id}) not to old; starting.\"\n {event, now}\n end\n end\n\n defp maybe_start_regimen(false = _started?, start_time, last_time, event, _) do\n Logger.debug 3, \"regimen #{event.name} (#{event.id}) is not started yet. (#{inspect start_time}) (#{inspect Timex.now()})\"\n {nil, last_time}\n end\n\n defp lookup(module, sr_id) do\n case Farmbot.Repo.current_repo().get(module, sr_id) do\n nil -> raise \"Could not find #{module} by id: #{sr_id}\"\n item -> item\n end\n end\n\n # signals the start of a sequence based on the described logic.\n defp maybe_start_sequence(started?, finished?, farm_event, last_time, event, now)\n\n # We only want to check if the sequence is started, and not finished.\n defp maybe_start_sequence(true = _started?, false = _finished?, farm_event, last_time, event, now) do\n {run?, next_time} = should_run_sequence?(farm_event.calendar, last_time, now)\n case run? do\n true -> {event, next_time}\n false -> {nil, last_time}\n end\n end\n\n # if `farm_event.time_unit` is \"never\" we can't use the `end_time`.\n # if we have no `last_time`, time to execute.\n defp maybe_start_sequence(true = _started?, _, %{time_unit: \"never\"} = f, nil = _last_time, event, now) do\n Logger.debug 3, \"Ignoring end_time.\"\n case should_run_sequence?(f.calendar, nil, now) do\n {true, next} -> {event, next}\n {false, _} -> {nil, nil}\n end\n end\n\n # if started is false, the event isn't ready to be executed.\n defp maybe_start_sequence(false = _started?, _fin, _farm_event, last_time, event, _now) do\n Logger.debug 3, \"sequence #{event.name} (#{event.id}) is not started yet.\"\n {nil, last_time}\n end\n\n # if the event is finished (but not a \"never\" time_unit), we don't execute.\n defp maybe_start_sequence(_started?, true = _finished?, _farm_event, last_time, event, _now) do\n Logger.success 3, \"sequence #{event.name} (#{event.id}) is finished.\"\n {nil, last_time}\n end\n\n # Checks if we shoudl run a sequence or not. returns {event | nil, time | nil}\n defp should_run_sequence?(calendar, last_time, now)\n\n # if there is no last time, check if time is passed now within 60 seconds.\n defp should_run_sequence?([first_time | _], nil, now) do\n\n Logger.debug 3, \"Checking sequence event that hasn't run before #{first_time}\"\n # convert the first_time to a DateTime\n dt = Timex.parse! first_time, \"{ISO:Extended}\"\n # if now is after the time, we are in fact late\n if Timex.after?(now, dt) do\n {true, now}\n else\n # make sure to return nil as the last time because it stil hasnt executed yet.\n Logger.debug 3, \"Sequence Event not ready yet.\"\n {false, nil}\n end\n end\n\n defp should_run_sequence?(nil, last_time, now) do\n Logger.debug 3, \"Checking sequence with no calendar.\"\n if is_nil(last_time) do\n {true, now}\n else\n {false, last_time}\n end\n end\n\n defp should_run_sequence?(calendar, last_time, now) do\n # get rid of all the items that happened before last_time\n filtered_calendar = Enum.filter(calendar, fn(iso_time) ->\n dt = Timex.parse! iso_time, \"{ISO:Extended}\"\n # we only want this time if it happened after the last_time\n Timex.after?(dt, last_time)\n end)\n\n # if after filtering, there are events that need to be run\n # check if they are older than a minute ago,\n case filtered_calendar do\n [iso_time | _] ->\n dt = Timex.parse! iso_time, \"{ISO:Extended}\"\n if Timex.after?(now, dt) do\n {true, dt}\n # too_old? = is_too_old?(now, dt)\n # if too_old?, do: {false, last_time}, else: {true, dt}\n else\n Logger.debug 3, \"Sequence Event not ready yet.\"\n {false, dt}\n end\n [] ->\n Logger.debug 3, \"No items in calendar.\"\n {false, last_time}\n end\n end\n\n # Enumeration is complete.\n defp start_events([], _now), do: :ok\n\n # Enumerate the events to be started.\n defp start_events([event | rest], now) do\n # Spawn to be non blocking here. Maybe link to this process?\n spawn fn() -> Execution.execute_event(event, now) end\n # Continue enumeration.\n start_events(rest, now)\n end\n\n # is then more than 1 minute in the past?\n defp is_too_old?(now, then) do\n time_str_fun = fn(dt) -> \"#{dt.hour}:#{dt.minute}:#{dt.second}\" end\n seconds = DateTime.to_unix(now, :second) - DateTime.to_unix(then, :second)\n c = seconds > 60 # not in MS here\n Logger.debug 3, \"is checking #{time_str_fun.(now)} - #{time_str_fun.(then)} = #{seconds} seconds ago. is_too_old? => #{c}\"\n c\n end\n\n defp get_now(), do: Timex.now()\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"f7186aa46870b9f7f0bc572a23abdd75a75ac5d0","subject":"Fix #198 - Fix broken handling of removed applications during hot upgrades","message":"Fix #198 - Fix broken handling of removed applications during hot upgrades\n","repos":"bitwalker\/distillery,bitwalker\/distillery","old_file":"lib\/mix\/lib\/releases\/assembler.ex","new_file":"lib\/mix\/lib\/releases\/assembler.ex","new_contents":"defmodule Mix.Releases.Assembler do\n @moduledoc \"\"\"\n This module is responsible for assembling a release based on a `Mix.Releases.Config`\n struct. It creates the release directory, copies applications, and generates release-specific\n files required by `:systools` and `:release_handler`.\n \"\"\"\n alias Mix.Releases.{Config, Release, Environment, Profile, App}\n alias Mix.Releases.{Utils, Logger, Appup, Plugin, Overlays}\n\n require Record\n Record.defrecordp :file_info, Record.extract(:file_info, from_lib: \"kernel\/include\/file.hrl\")\n\n @doc \"\"\"\n This function takes a Config struct and assembles the release.\n\n **Note: This operation has side-effects!** It creates files, directories,\n copies files from other filesystem locations. If failures occur, no cleanup\n of files\/directories is performed. However, all files\/directories created by\n this function are scoped to the current project's `rel` directory, and cannot\n impact the filesystem outside of this directory.\n \"\"\"\n @spec assemble(Config.t) :: {:ok, Config.t} | {:error, term}\n def assemble(%Config{} = config) do\n with {:ok, environment} <- select_environment(config),\n {:ok, release} <- select_release(config),\n {:ok, release} <- apply_environment(release, environment),\n :ok <- validate_configuration(release),\n {:ok, release} <- apply_configuration(release, config),\n :ok <- File.mkdir_p(release.profile.output_dir),\n {:ok, release} <- Plugin.before_assembly(release),\n {:ok, release} <- generate_overlay_vars(release),\n {:ok, release} <- copy_applications(release),\n :ok <- create_release_info(release),\n {:ok, release} <- apply_overlays(release),\n {:ok, release} <- Plugin.after_assembly(release),\n do: {:ok, release}\n end\n\n # Determines the correct environment to assemble in\n @spec select_environment(Config.t) :: {:ok, Environment.t} | {:error, :no_environments}\n def select_environment(%Config{selected_environment: :default, default_environment: :default} = c),\n do: select_environment(Map.fetch(c.environments, :default))\n def select_environment(%Config{selected_environment: :default, default_environment: name} = c),\n do: select_environment(Map.fetch(c.environments, name))\n def select_environment(%Config{selected_environment: name} = c),\n do: select_environment(Map.fetch(c.environments, name))\n def select_environment({:ok, _} = e), do: e\n def select_environment(_), do: {:error, :no_environments}\n\n # Determines the correct release to assemble\n @spec select_release(Config.t) :: {:ok, Release.t} | {:error, :no_releases}\n def select_release(%Config{selected_release: :default, default_release: :default} = c),\n do: {:ok, List.first(Map.values(c.releases))}\n def select_release(%Config{selected_release: :default, default_release: name} = c),\n do: select_release(Map.fetch(c.releases, name))\n def select_release(%Config{selected_release: name} = c),\n do: select_release(Map.fetch(c.releases, name))\n def select_release({:ok, _} = r), do: r\n def select_release(_), do: {:error, :no_releases}\n\n # Applies the environment profile to the release profile.\n @spec apply_environment(Release.t, Environment.t) :: {:ok, Release.t} | {:error, term}\n def apply_environment(%Release{profile: rel_profile} = r, %Environment{profile: env_profile} = e) do\n Logger.info \"Building release #{r.name}:#{r.version} using environment #{e.name}\"\n env_profile = Map.from_struct(env_profile)\n profile = Enum.reduce(env_profile, rel_profile, fn {k, v}, acc ->\n case v do\n ignore when ignore in [nil, []] -> acc\n _ -> Map.put(acc, k, v)\n end\n end)\n {:ok, %{r | :profile => profile}}\n end\n\n @spec validate_configuration(Release.t) :: :ok | {:error, term}\n def validate_configuration(%Release{version: _, profile: profile}) do\n with :ok <- Utils.validate_erts(profile.include_erts) do\n # Warn if not including ERTS when not obviously running in a dev configuration\n if profile.dev_mode == false and profile.include_erts == false do\n Logger.notice \"IMPORTANT: You have opted to *not* include the Erlang runtime system (ERTS).\\n\" <>\n \"You must ensure that the version of Erlang this release is built with matches\\n\" <>\n \"the version the release will be run with once deployed. It will fail to run otherwise.\"\n end\n :ok\n end\n end\n\n # Applies global configuration options to the release profile\n @spec apply_configuration(Release.t, Config.t) :: {:ok, Release.t} | {:error, term}\n def apply_configuration(%Release{version: current_version, profile: profile} = release, %Config{} = config) do\n config_path = case profile.config do\n p when is_binary(p) -> p\n _ -> Keyword.get(Mix.Project.config, :config_path)\n end\n base_release = %{release | :profile => %{profile | :config => config_path}}\n release = check_cookie(base_release)\n case Utils.get_apps(release) do\n {:error, _} = err -> err\n release_apps ->\n release = %{release | :applications => release_apps}\n case config.is_upgrade do\n true ->\n case config.upgrade_from do\n :latest ->\n upfrom = case Utils.get_release_versions(release.profile.output_dir) do\n [] -> :no_upfrom\n [^current_version, v|_] -> v\n [v|_] -> v\n end\n case upfrom do\n :no_upfrom ->\n Logger.warn \"An upgrade was requested, but there are no \" <>\n \"releases to upgrade from, no upgrade will be performed.\"\n {:ok, %{release | :is_upgrade => false, :upgrade_from => nil}}\n v ->\n {:ok, %{release | :is_upgrade => true, :upgrade_from => v}}\n end\n ^current_version ->\n Logger.error \"Upgrade from #{current_version} to #{current_version} failed:\\n \" <>\n \"Upfrom version and current version are the same\"\n {:error, :bad_upgrade_spec}\n version when is_binary(version) ->\n Logger.debug \"Upgrading #{release.name} from #{version} to #{current_version}\"\n upfrom_path = Path.join([release.profile.output_dir, \"releases\", version])\n case File.exists?(upfrom_path) do\n false ->\n Logger.error \"Upgrade from #{version} to #{current_version} failed:\\n \" <>\n \"#{version} does not exist at #{upfrom_path}\"\n {:error, :bad_upgrade_spec}\n true ->\n {:ok, %{release | :is_upgrade => true, :upgrade_from => version}}\n end\n end\n false ->\n {:ok, release}\n end\n end\n end\n\n # Copies application beams to the output directory\n defp copy_applications(%Release{profile: %Profile{output_dir: output_dir}} = release) do\n Logger.debug \"Copying applications to #{output_dir}\"\n try do\n File.mkdir_p!(Path.join(output_dir, \"lib\"))\n for app <- release.applications do\n copy_app(app, release)\n end\n # Copy consolidated .beams\n build_path = Mix.Project.build_path(Mix.Project.config)\n consolidated_dest = Path.join([output_dir, \"lib\", \"#{release.name}-#{release.version}\", \"consolidated\"])\n File.mkdir_p!(consolidated_dest)\n consolidated_src = Path.join(build_path, \"consolidated\")\n if File.exists?(consolidated_src) do\n {:ok, _} = File.cp_r(consolidated_src, consolidated_dest)\n end\n {:ok, release}\n catch\n kind, err ->\n {:error, Exception.format(kind, err, System.stacktrace)}\n end\n end\n\n # Copies a specific application to the output directory\n defp copy_app(app, %Release{profile: %Profile{\n output_dir: output_dir,\n dev_mode: dev_mode?,\n include_src: include_src?,\n include_erts: include_erts?}}) do\n app_name = app.name\n app_version = app.vsn\n app_dir = app.path\n lib_dir = Path.join(output_dir, \"lib\")\n target_dir = Path.join(lib_dir, \"#{app_name}-#{app_version}\")\n remove_symlink_or_dir!(target_dir)\n case include_erts? do\n true ->\n copy_app(app_dir, target_dir, dev_mode?, include_src?)\n p when is_binary(p) ->\n copy_app(app_dir, target_dir, dev_mode?, include_src?)\n _ ->\n case Utils.is_erts_lib?(app_dir) do\n true ->\n :ok\n false ->\n copy_app(app_dir, target_dir, dev_mode?, include_src?)\n end\n end\n end\n defp copy_app(app_dir, target_dir, true, _include_src?) do\n case File.ln_s(app_dir, target_dir) do\n :ok -> :ok\n {:error, reason} ->\n raise \"unable to link app directory:\\n \" <>\n \"#{app_dir} -> #{target_dir}\\n \" <>\n \"Reason: #{reason}\"\n end\n end\n defp copy_app(app_dir, target_dir, false, include_src?) do\n case File.mkdir_p(target_dir) do\n {:error, reason} ->\n raise \"unable to create app directory:\\n \" <>\n \"#{target_dir}\\n \" <>\n \"Reason: #{reason}\"\n :ok ->\n valid_dirs = cond do\n include_src? ->\n [\"ebin\", \"include\", \"priv\", \"lib\", \"src\"]\n :else ->\n [\"ebin\", \"include\", \"priv\"]\n end\n Path.wildcard(Path.join(app_dir, \"*\"))\n |> Enum.filter(fn p -> Path.basename(p) in valid_dirs end)\n |> Enum.each(fn p ->\n t = Path.join(target_dir, Path.basename(p))\n if symlink?(p) do\n # We need to follow the symlink\n File.mkdir_p!(t)\n Path.wildcard(Path.join(p, \"*\"))\n |> Enum.each(fn child ->\n tc = Path.join(t, Path.basename(child))\n case File.cp_r(child, tc) do\n {:ok, _} -> :ok\n {:error, reason, file} ->\n raise \"unable to copy app directory:\\n \" <>\n \"#{child} -> #{tc}\\n \" <>\n \"File: #{file}\\n \" <>\n \"Reason: #{reason}\"\n end\n end)\n else\n case File.cp_r(p, t) do\n {:ok, _} -> :ok\n {:error, reason, file} ->\n raise \"unable to copy app directory:\\n \" <>\n \"#{p} -> #{t}\\n \" <>\n \"File: #{file}\\n \" <>\n \"Reason: #{reason}\"\n end\n end\n end)\n end\n end\n\n defp remove_symlink_or_dir!(path) do\n case File.exists?(path) do\n true ->\n File.rm_rf!(path)\n false ->\n if symlink?(path) do\n File.rm!(path)\n end\n end\n :ok\n end\n\n defp symlink?(path) do\n case :file.read_link_info('#{path}') do\n {:ok, info} ->\n elem(info, 2) == :symlink\n _ ->\n false\n end\n end\n\n # Creates release metadata files\n defp create_release_info(%Release{name: relname, profile: %Profile{output_dir: output_dir}} = release) do\n rel_dir = Path.join([output_dir, \"releases\", \"#{release.version}\"])\n case File.mkdir_p(rel_dir) do\n {:error, reason} ->\n {:error, \"failed to create release directory: #{rel_dir}\\n Reason: #{reason}\"}\n :ok ->\n release_file = Path.join(rel_dir, \"#{relname}.rel\")\n start_clean_file = Path.join(rel_dir, \"start_clean.rel\")\n start_clean_rel = %{release |\n :applications => Enum.filter(release.applications, fn %App{name: n} ->\n n in [:kernel, :stdlib, :compiler, :elixir, :iex]\n end)}\n with :ok <- write_relfile(release_file, release),\n :ok <- write_relfile(start_clean_file, start_clean_rel),\n :ok <- write_binfile(release, rel_dir),\n :ok <- generate_relup(release, rel_dir), do: :ok\n end\n end\n\n # Creates the .rel file for the release\n defp write_relfile(path, %Release{applications: apps} = release) do\n case get_erts_version(release) do\n {:error, _} = err -> err\n {:ok, erts_vsn} ->\n relfile = {:release,\n {'#{release.name}', '#{release.version}'},\n {:erts, '#{erts_vsn}'},\n apps\n |> Enum.with_index\n |> Enum.sort_by(fn\n {%App{name: :kernel}, _idx} -> -2\n {%App{name: :stdlib}, _idx} -> -1\n {%App{}, idx} -> idx\n end)\n |> Enum.map(fn {%App{name: name, vsn: vsn, start_type: start_type}, _idx} ->\n case start_type do\n nil ->\n {name, '#{vsn}'}\n t ->\n {name, '#{vsn}', t}\n end\n end)}\n Utils.write_term(path, relfile)\n end\n end\n\n # Creates the .boot files, nodetool, vm.args, sys.config, start_erl.data, and includes ERTS into\n # the release if so configured\n defp write_binfile(release, rel_dir) do\n name = \"#{release.name}\"\n bin_dir = Path.join(release.profile.output_dir, \"bin\")\n bootloader_path = Path.join(bin_dir, name)\n boot_path = Path.join(rel_dir, \"#{name}.sh\")\n template_params = release.profile.overlay_vars\n\n with :ok <- File.mkdir_p(bin_dir),\n :ok <- generate_nodetool(bin_dir),\n {:ok, bootloader_contents} <- Utils.template(:boot_loader, template_params),\n {:ok, boot_contents} <- Utils.template(:boot, template_params),\n :ok <- File.write(bootloader_path, bootloader_contents),\n :ok <- File.write(boot_path, boot_contents),\n :ok <- File.chmod(bootloader_path, 0o777),\n :ok <- File.chmod!(boot_path, 0o777),\n :ok <- generate_start_erl_data(release, rel_dir),\n :ok <- generate_vm_args(release, rel_dir),\n :ok <- generate_sys_config(release, rel_dir),\n :ok <- include_erts(release),\n :ok <- make_boot_script(release, rel_dir), do: :ok\n end\n\n # Generates a relup and .appup for all upgraded applications during upgrade releases\n defp generate_relup(%Release{is_upgrade: false}, _rel_dir), do: :ok\n defp generate_relup(%Release{name: name, upgrade_from: upfrom, profile: %Profile{output_dir: output_dir}} = release, rel_dir) do\n Logger.debug \"Generating relup for #{name}\"\n v1_rel = Path.join([output_dir, \"releases\", upfrom, \"#{name}.rel\"])\n v2_rel = Path.join(rel_dir, \"#{name}.rel\")\n case {File.exists?(v1_rel), File.exists?(v2_rel)} do\n {false, true} ->\n {:error, \"Missing .rel for #{name}:#{upfrom} at #{v1_rel}\"}\n {true, false} ->\n {:error, \"Missing .rel for #{name}:#{release.version} at #{v2_rel}\"}\n {false, false} ->\n {:error, \"Missing .rels\\n \" <>\n \"#{name}:#{upfrom} @ #{v1_rel}\\n \" <>\n \"#{name}:#{release.version} @ #{v2_rel}\"}\n {true, true} ->\n v1_apps = extract_relfile_apps(v1_rel)\n v2_apps = extract_relfile_apps(v2_rel)\n changed = get_changed_apps(v1_apps, v2_apps)\n added = get_added_apps(v2_apps, changed)\n removed = get_removed_apps(v1_apps, v2_apps)\n case generate_appups(changed, output_dir) do\n {:error, _} = err ->\n err\n :ok ->\n current_rel = Path.join([output_dir, \"releases\", release.version, \"#{name}\"])\n upfrom_rel = Path.join([output_dir, \"releases\", release.upgrade_from, \"#{name}\"])\n result = :systools.make_relup(\n String.to_charlist(current_rel),\n [String.to_charlist(upfrom_rel)],\n [String.to_charlist(upfrom_rel)],\n [{:outdir, String.to_charlist(rel_dir)},\n {:path, get_relup_code_paths(added, changed, removed, output_dir)},\n :silent,\n :no_warn_sasl]\n )\n case result do\n {:ok, relup, _mod, []} ->\n Logger.info \"Relup successfully created\"\n Utils.write_term(Path.join(rel_dir, \"relup\"), relup)\n {:ok, relup, mod, warnings} ->\n Logger.warn format_systools_warning(mod, warnings)\n Logger.info \"Relup successfully created\"\n Utils.write_term(Path.join(rel_dir, \"relup\"), relup)\n {:error, mod, errors} ->\n error = format_systools_error(mod, errors)\n {:error, error}\n end\n end\n end\n end\n\n defp format_systools_warning(mod, warnings) do\n warning = mod.format_warning(warnings)\n |> IO.iodata_to_binary\n |> String.split(\"\\n\")\n |> Enum.map(fn e -> \" \" <> e end)\n |> Enum.join(\"\\n\")\n |> String.trim_trailing\n \"\\n#{warning}\"\n end\n\n defp format_systools_error(mod, errors) do\n error = mod.format_error(errors)\n |> IO.iodata_to_binary\n |> String.split(\"\\n\")\n |> Enum.map(fn e -> \" \" <> e end)\n |> Enum.join(\"\\n\")\n |> String.trim_trailing\n \"\\n#{error}\"\n end\n\n # Get a list of applications from the .rel file at the given path\n defp extract_relfile_apps(path) do\n case Utils.read_terms(path) do\n {:error, err} -> raise err\n {:ok, [{:release, _rel, _erts, apps}]} ->\n Enum.map(apps, fn {a, v} -> {a, v}; {a, v, _start_type} -> {a, v} end)\n {:ok, other} -> raise \"malformed relfile (#{path}): #{inspect other}\"\n end\n end\n\n # Determine the set of apps which have changed between two versions\n defp get_changed_apps(a, b) do\n as = Enum.map(a, fn app -> elem(app, 0) end) |> MapSet.new\n bs = Enum.map(b, fn app -> elem(app, 0) end) |> MapSet.new\n shared = MapSet.to_list(MapSet.intersection(as, bs))\n a_versions = Enum.map(shared, fn n -> {n, elem(List.keyfind(a, n, 0), 1)} end) |> MapSet.new\n b_versions = Enum.map(shared, fn n -> {n, elem(List.keyfind(b, n, 0), 1)} end) |> MapSet.new\n MapSet.difference(b_versions, a_versions)\n |> MapSet.to_list\n |> Enum.map(fn {n, v2} ->\n v1 = List.keyfind(a, n, 0) |> elem(1)\n {n, \"#{v1}\", \"#{v2}\"}\n end)\n end\n\n # Determine the set of apps which were added between two versions\n defp get_added_apps(v2_apps, changed) do\n changed_apps = Enum.map(changed, &elem(&1, 0))\n Enum.reject(v2_apps, fn a ->\n elem(a, 0) in changed_apps\n end)\n end\n\n # Determine the set of apps removed from v1 to v2\n defp get_removed_apps(a, b) do\n as = Enum.map(a, fn app -> elem(app, 0) end) |> MapSet.new\n bs = Enum.map(b, fn app -> elem(app, 0) end) |> MapSet.new\n MapSet.difference(as, bs)\n |> MapSet.to_list\n |> Enum.map(fn n -> {n, elem(List.keyfind(a, n, 0), 1)} end)\n end\n\n # Generate .appup files for a list of {app, v1, v2}\n defp generate_appups([], _output_dir), do: :ok\n defp generate_appups([{app, v1, v2}|apps], output_dir) do\n v1_path = Path.join([output_dir, \"lib\", \"#{app}-#{v1}\"])\n v2_path = Path.join([output_dir, \"lib\", \"#{app}-#{v2}\"])\n appup_path = Path.join([v2_path, \"ebin\", \"#{app}.appup\"])\n appup_exists? = File.exists?(appup_path)\n appup_valid? = case :file.consult(~c[#{appup_path}]) do\n {:ok, [{upto_ver, [{downto_ver, _}], [{downto_ver, _}]}]} ->\n cond do\n upto_ver == ~c[#{v2}] and downto_ver == ~c[#{v1}] ->\n true\n :else ->\n false\n end\n _other ->\n false\n end\n cond do\n appup_exists? && appup_valid? ->\n Logger.debug \"#{app} requires an appup, and one was provided, skipping generation..\"\n generate_appups(apps, output_dir)\n appup_exists? ->\n Logger.warn \"#{app} has an appup file, but it is invalid for this release,\\n\" <>\n \" Backing up appfile with .bak extension and generating new one..\"\n :ok = File.cp!(appup_path, \"#{appup_path}.bak\")\n case Appup.make(app, v1, v2, v1_path, v2_path) do\n {:error, reason} ->\n {:error, \"Failed to generate appup for #{app}:\\n \" <>\n inspect(reason)}\n {:ok, appup} ->\n :ok = Utils.write_term(appup_path, appup)\n Logger.info \"Generated .appup for #{app} #{v1} -> #{v2}\"\n generate_appups(apps, output_dir)\n end\n :else ->\n Logger.debug \"#{app} requires an appup, but it wasn't provided, one will be generated for you..\"\n case Appup.make(app, v1, v2, v1_path, v2_path) do\n {:error, reason} ->\n {:error, \"Failed to generate appup for #{app}:\\n \" <>\n inspect(reason)}\n {:ok, appup} ->\n :ok = Utils.write_term(appup_path, appup)\n Logger.info \"Generated .appup for #{app} #{v1} -> #{v2}\"\n generate_appups(apps, output_dir)\n end\n end\n end\n\n # Get a list of code paths containing only those paths which have beams\n # from the two versions in the release being upgraded\n defp get_relup_code_paths(added, changed, removed, output_dir) do\n added_paths = get_added_relup_code_paths(added, output_dir, [])\n changed_paths = get_changed_relup_code_paths(changed, output_dir, [], [])\n removed_paths = get_removed_relup_code_paths(removed, output_dir, [])\n added_paths ++ changed_paths ++ removed_paths\n end\n defp get_changed_relup_code_paths([], _output_dir, v1_paths, v2_paths) do\n v2_paths ++ v1_paths\n end\n defp get_changed_relup_code_paths([{app, v1, v2}|apps], output_dir, v1_paths, v2_paths) do\n v1_path = Path.join([output_dir, \"lib\", \"#{app}-#{v1}\", \"ebin\"]) |> String.to_charlist\n v2_path = Path.join([output_dir, \"lib\", \"#{app}-#{v2}\", \"ebin\"]) |> String.to_charlist\n v2_path_consolidated = Path.join([output_dir, \"lib\", \"#{app}-#{v2}\", \"consolidated\"]) |> String.to_charlist\n get_changed_relup_code_paths(\n apps,\n output_dir,\n [v1_path|v1_paths],\n [v2_path_consolidated, v2_path|v2_paths])\n end\n defp get_added_relup_code_paths([], _output_dir, paths), do: paths\n defp get_added_relup_code_paths([{app, v2}|apps], output_dir, paths) do\n v2_path = Path.join([output_dir, \"lib\", \"#{app}-#{v2}\", \"ebin\"]) |> String.to_charlist\n v2_path_consolidated = Path.join([output_dir, \"lib\", \"#{app}-#{v2}\", \"consolidated\"]) |> String.to_charlist\n get_added_relup_code_paths(apps, output_dir, [v2_path_consolidated, v2_path|paths])\n end\n defp get_removed_relup_code_paths([], _output_dir, paths), do: paths\n defp get_removed_relup_code_paths([{app, v1}|apps], output_dir, paths) do\n v1_path = Path.join([output_dir, \"lib\", \"#{app}-#{v1}\", \"ebin\"]) |> String.to_charlist\n v1_path_consolidated = Path.join([output_dir, \"lib\", \"#{app}-#{v1}\", \"consolidated\"]) |> String.to_charlist\n get_removed_relup_code_paths(apps, output_dir, [v1_path_consolidated, v1_path | paths])\n end\n\n # Generates the nodetool utility\n defp generate_nodetool(bin_dir) do\n Logger.debug \"Generating nodetool\"\n with {:ok, node_tool_file} = Utils.template(:nodetool),\n {:ok, release_utils_file} = Utils.template(:release_utils),\n :ok <- File.write(Path.join(bin_dir, \"nodetool\"), node_tool_file),\n :ok <- File.write(Path.join(bin_dir, \"release_utils.escript\"), release_utils_file),\n do: :ok\n end\n\n # Generates start_erl.data\n defp generate_start_erl_data(%Release{version: version, profile: %Profile{include_erts: false}}, rel_dir) do\n Logger.debug \"Generating start_erl.data\"\n contents = \"ERTS_VSN #{version}\"\n File.write(Path.join([rel_dir, \"..\", \"start_erl.data\"]), contents)\n end\n defp generate_start_erl_data(%Release{profile: %Profile{include_erts: path}} = release, rel_dir)\n when is_binary(path) do\n Logger.debug \"Generating start_erl.data\"\n case Utils.detect_erts_version(path) do\n {:error, _} = err -> err\n {:ok, vsn} ->\n contents = \"#{vsn} #{release.version}\"\n File.write(Path.join([rel_dir, \"..\", \"start_erl.data\"]), contents)\n end\n end\n defp generate_start_erl_data(release, rel_dir) do\n Logger.debug \"Generating start_erl.data\"\n contents = \"#{Utils.erts_version} #{release.version}\"\n File.write(Path.join([rel_dir, \"..\", \"start_erl.data\"]), contents)\n end\n\n # Generates vm.args\n defp generate_vm_args(%Release{profile: %Profile{vm_args: nil}} = rel, rel_dir) do\n Logger.debug \"Generating vm.args\"\n overlay_vars = rel.profile.overlay_vars\n with {:ok, contents} <- Utils.template(\"vm.args\", overlay_vars),\n :ok <- File.write(Path.join(rel_dir, \"vm.args\"), contents),\n do: :ok\n end\n defp generate_vm_args(%Release{profile: %Profile{vm_args: path}} = rel, rel_dir) do\n Logger.debug \"Generating vm.args from #{Path.relative_to_cwd(path)}\"\n overlay_vars = rel.profile.overlay_vars\n with {:ok, path} <- Overlays.template_str(path, overlay_vars),\n {:ok, templated} <- Overlays.template_file(path, overlay_vars),\n :ok <- File.write(Path.join(rel_dir, \"vm.args\"), templated),\n do: :ok\n end\n\n # Generates sys.config\n defp generate_sys_config(%Release{profile: %Profile{config: base_config_path, sys_config: config_path}} = rel, rel_dir)\n when is_binary(config_path) do\n Logger.debug \"Generating sys.config from #{Path.relative_to_cwd(config_path)}\"\n overlay_vars = rel.profile.overlay_vars\n base_config = generate_base_config(base_config_path)\n res = with {:ok, path} <- Overlays.template_str(config_path, overlay_vars),\n {:ok, templated} <- Overlays.template_file(path, overlay_vars),\n {:ok, tokens, _} <- :erl_scan.string(String.to_charlist(templated)),\n {:ok, sys_config} <- :erl_parse.parse_term(tokens),\n :ok <- validate_sys_config(sys_config),\n merged <- Mix.Config.merge(base_config, sys_config),\n do: Utils.write_term(Path.join(rel_dir, \"sys.config\"), merged)\n case res do\n {:error, :invalid_sys_config, reason} ->\n {:error, \"invalid sys.config: #{reason}\"}\n {:error, {_loc, _module, description}, {line, col}} ->\n {:error, \"invalid sys.config at line #{line}, column #{col}: #{inspect description}\"}\n {:error, {_loc, _module, description}, line} ->\n {:error, \"invalid sys.config at line #{line}: #{inspect description}\"}\n {:error, {line, _module, description}} ->\n {:error, \"could not parse sys.config at line #{line}: #{inspect description}\"}\n other ->\n other\n end\n end\n defp generate_sys_config(%Release{profile: %Profile{config: config_path}}, rel_dir) do\n Logger.debug \"Generating sys.config from #{Path.relative_to_cwd(config_path)}\"\n config = generate_base_config(config_path)\n Utils.write_term(Path.join(rel_dir, \"sys.config\"), config)\n end\n\n defp generate_base_config(base_config_path) do\n config = Mix.Config.read!(base_config_path)\n case Keyword.get(config, :sasl) do\n nil ->\n Keyword.put(config, :sasl, [errlog_type: :error])\n sasl ->\n case Keyword.get(sasl, :errlog_type) do\n nil -> put_in(config, [:sasl, :errlog_type], :error)\n _ -> config\n end\n end\n end\n\n defp validate_sys_config(sys_config) when is_list(sys_config) do\n cond do\n Keyword.keyword?(sys_config) ->\n is_config? = Enum.reduce(sys_config, true, fn\n {app, config}, acc when is_atom(app) and is_list(config) ->\n acc && Keyword.keyword?(config)\n {_app, _config}, _acc ->\n false\n end)\n cond do\n is_config? ->\n :ok\n :else ->\n {:error, :invalid_sys_config, \"must be a list of {:app_name, [{:key, value}]} tuples\"}\n end\n :else ->\n {:error, :invalid_sys_config, \"must be a keyword list\"}\n end\n end\n defp validate_sys_config(_sys_config), do: {:error, :invalid_sys_config, \"must be a keyword list\"}\n\n # Adds ERTS to the release, if so configured\n defp include_erts(%Release{profile: %Profile{include_erts: false}, is_upgrade: false}), do: :ok\n defp include_erts(%Release{profile: %Profile{include_erts: false}, is_upgrade: true}) do\n {:error, \"Hot upgrades will fail when include_erts: false is set,\\n\" <>\n \" you need to set include_erts to true or a path if you plan to use them!\"}\n end\n defp include_erts(%Release{profile: %Profile{include_erts: include_erts, output_dir: output_dir}} = release) do\n prefix = case include_erts do\n true -> \"#{:code.root_dir}\"\n p when is_binary(p) ->\n Path.expand(p)\n end\n erts_vsn = case include_erts do\n true -> Utils.erts_version()\n p when is_binary(p) ->\n case Utils.detect_erts_version(prefix) do\n {:ok, vsn} ->\n # verify that the path given was actually the right one\n case File.exists?(Path.join(prefix, \"bin\")) do\n true -> vsn\n false ->\n pfx = Path.relative_to_cwd(prefix)\n maybe_path = Path.relative_to_cwd(Path.expand(Path.join(prefix, \"..\")))\n {:error, \"invalid ERTS path, did you mean #{maybe_path} instead of #{pfx}?\"}\n end\n {:error, _} = err -> err\n end\n end\n case erts_vsn do\n {:error, _} = err ->\n err\n _ ->\n erts_dir = Path.join([prefix, \"erts-#{erts_vsn}\"])\n\n Logger.info \"Including ERTS #{erts_vsn} from #{Path.relative_to_cwd(erts_dir)}\"\n\n erts_output_dir = Path.join(output_dir, \"erts-#{erts_vsn}\")\n erl_path = Path.join([erts_output_dir, \"bin\", \"erl\"])\n nodetool_path = Path.join([output_dir, \"bin\", \"nodetool\"])\n nodetool_dest = Path.join([erts_output_dir, \"bin\", \"nodetool\"])\n with :ok <- remove_if_exists(erts_output_dir),\n :ok <- File.mkdir_p(erts_output_dir),\n {:ok, _} <- File.cp_r(erts_dir, erts_output_dir),\n {:ok, _} <- File.rm_rf(erl_path),\n {:ok, erl_script} <- Utils.template(:erl_script, release.profile.overlay_vars),\n :ok <- File.write(erl_path, erl_script),\n :ok <- File.chmod(erl_path, 0o755),\n :ok <- File.cp(nodetool_path, nodetool_dest),\n :ok <- File.chmod(nodetool_dest, 0o755) do\n :ok\n else\n {:error, reason} ->\n {:error, \"Failed during include_erts: #{inspect reason}\"}\n {:error, reason, file} ->\n {:error, \"Failed to remove file during include_erts: #{inspect reason} #{file}\"}\n end\n end\n end\n\n defp remove_if_exists(path) do\n case File.exists?(path) do\n false -> :ok\n true ->\n case File.rm_rf(path) do\n {:ok, _} -> :ok\n {:error, _, _} = err -> err\n end\n end\n end\n\n # Generates .boot script\n defp make_boot_script(%Release{profile: %Profile{output_dir: output_dir}} = release, rel_dir) do\n Logger.debug \"Generating boot script\"\n erts_lib_dir = case release.profile.include_erts do\n false -> :code.lib_dir()\n true -> :code.lib_dir()\n p -> String.to_charlist(Path.expand(Path.join(p, \"lib\")))\n end\n options = [{:path, ['#{rel_dir}' | Release.get_code_paths(release)]},\n {:outdir, '#{rel_dir}'},\n {:variables, [{'ERTS_LIB_DIR', erts_lib_dir}]},\n :no_warn_sasl,\n :no_module_tests,\n :silent]\n rel_name = '#{release.name}'\n release_file = Path.join(rel_dir, \"#{release.name}.rel\")\n case :systools.make_script(rel_name, options) do\n :ok ->\n with :ok <- create_RELEASES(output_dir, Path.join([\"releases\", \"#{release.version}\", \"#{release.name}.rel\"])),\n :ok <- create_start_clean(rel_dir, output_dir, options), do: :ok\n {:ok, _, []} ->\n with :ok <- create_RELEASES(output_dir, Path.join([\"releases\", \"#{release.version}\", \"#{release.name}.rel\"])),\n :ok <- create_start_clean(rel_dir, output_dir, options), do: :ok\n :error ->\n {:error, {:unknown, release_file}}\n {:ok, mod, warnings} ->\n Logger.warn format_systools_warning(mod, warnings)\n :ok\n {:error, mod, errors} ->\n error = format_systools_error(mod, errors)\n {:error, error}\n end\n end\n\n # Generates RELEASES\n defp create_RELEASES(output_dir, relfile) do\n Logger.debug \"Generating RELEASES\"\n # NOTE: The RELEASES file must contain the correct paths to all libs,\n # including ERTS libs. When include_erts: false, the ERTS path, and thus\n # the paths to all ERTS libs, are not known until runtime. That means the\n # RELEASES file we generate here is invalid, which also means that performing\n # hot upgrades with include_erts: false will fail.\n #\n # This is annoying, but makes sense in the context of how release_handler works,\n # it must be able to handle upgrades where ERTS itself is also upgraded, and that\n # clearly can't happen if there is only one ERTS version (the host). It would be\n # possible to handle this if we could update the release_handler's state after it\n # unpacks a release in order to \"fix\" the invalid ERTS lib paths, but unfortunately\n # this is not exposed, and short of re-writing release_handler from scratch, there is\n # no work around for this\n old_cwd = File.cwd!\n File.cd!(output_dir)\n :ok = :release_handler.create_RELEASES('.\/', 'releases', '#{relfile}', [])\n File.cd!(old_cwd)\n :ok\n end\n\n # Generates start_clean.boot\n defp create_start_clean(rel_dir, output_dir, options) do\n Logger.debug \"Generating start_clean.boot\"\n case :systools.make_script('start_clean', options) do\n :ok ->\n with :ok <- File.cp(Path.join(rel_dir, \"start_clean.boot\"),\n Path.join([output_dir, \"bin\", \"start_clean.boot\"])),\n :ok <- File.rm(Path.join(rel_dir, \"start_clean.rel\")),\n :ok <- File.rm(Path.join(rel_dir, \"start_clean.script\")) do\n :ok\n else\n {:error, reason} ->\n {:error, \"Failed during create_start_clean: #{inspect reason}\"}\n end\n :error ->\n {:error, {:unknown, :create_start_clean}}\n {:ok, _, []} ->\n with :ok <- File.cp(Path.join(rel_dir, \"start_clean.boot\"),\n Path.join([output_dir, \"bin\", \"start_clean.boot\"])),\n :ok <- File.rm(Path.join(rel_dir, \"start_clean.rel\")),\n :ok <- File.rm(Path.join(rel_dir, \"start_clean.script\")) do\n :ok\n else\n {:error, reason} ->\n {:error, \"Failed during create_start_clean: #{inspect reason}\"}\n end\n {:ok, mod, warnings} ->\n Logger.warn format_systools_warning(mod, warnings)\n :ok\n {:error, mod, errors} ->\n error = format_systools_error(mod, errors)\n {:error, error}\n end\n end\n\n defp apply_overlays(%Release{} = release) do\n Logger.debug \"Applying overlays\"\n overlay_vars = release.profile.overlay_vars\n hooks_dir = \"releases\/<%= release_version %>\/hooks\"\n hook_overlays = [\n {:mkdir, hooks_dir},\n {:mkdir, \"#{hooks_dir}\/pre_start.d\"},\n {:mkdir, \"#{hooks_dir}\/post_start.d\"},\n {:mkdir, \"#{hooks_dir}\/pre_stop.d\"},\n {:mkdir, \"#{hooks_dir}\/post_stop.d\"},\n {:mkdir, \"#{hooks_dir}\/pre_upgrade.d\"},\n {:mkdir, \"#{hooks_dir}\/post_upgrade.d\"},\n {:copy, release.profile.pre_start_hook, \"#{hooks_dir}\/pre_start.d\/00_pre_start_hook.sh\"},\n {:copy, release.profile.post_start_hook, \"#{hooks_dir}\/post_start.d\/00_post_start_hook.sh\"},\n {:copy, release.profile.pre_stop_hook, \"#{hooks_dir}\/pre_stop.d\/00_pre_stop_hook.sh\"},\n {:copy, release.profile.post_stop_hook, \"#{hooks_dir}\/post_stop.d\/00_post_stop_hook.sh\"},\n {:copy, release.profile.pre_upgrade_hook, \"#{hooks_dir}\/pre_upgrade.d\/00_pre_upgrade_hook.sh\"},\n {:copy, release.profile.post_upgrade_hook, \"#{hooks_dir}\/post_upgrade.d\/00_post_upgrade_hook.sh\"},\n {:copy, release.profile.pre_start_hooks, \"#{hooks_dir}\/pre_start.d\"},\n {:copy, release.profile.post_start_hooks, \"#{hooks_dir}\/post_start.d\"},\n {:copy, release.profile.pre_stop_hooks, \"#{hooks_dir}\/pre_stop.d\"},\n {:copy, release.profile.post_stop_hooks, \"#{hooks_dir}\/post_stop.d\"},\n {:copy, release.profile.pre_upgrade_hooks, \"#{hooks_dir}\/pre_upgrade.d\"},\n {:copy, release.profile.post_upgrade_hooks, \"#{hooks_dir}\/post_upgrade.d\"},\n {:mkdir, \"releases\/<%= release_version %>\/commands\"} |\n Enum.map(release.profile.commands, fn {name, path} ->\n {:copy, path, \"releases\/<%= release_version %>\/commands\/#{name}\"}\n end)\n ] |> Enum.filter(fn {:copy, nil, _} -> false; _ -> true end)\n\n output_dir = release.profile.output_dir\n overlays = hook_overlays ++ release.profile.overlays\n case Overlays.apply(output_dir, overlays, overlay_vars) do\n {:ok, paths} ->\n release = %{release | :resolved_overlays => Enum.map(paths, fn path ->\n {'#{path}', '#{Path.join([output_dir, path])}'}\n end)}\n {:ok, release}\n {:error, _} = err ->\n err\n end\n end\n\n defp generate_overlay_vars(release) do\n case get_erts_version(release) do\n {:error, _} = err ->\n err\n {:ok, erts_vsn} ->\n vars = [release: release,\n release_name: release.name,\n release_version: release.version,\n is_upgrade: release.is_upgrade,\n upgrade_from: release.upgrade_from,\n dev_mode: release.profile.dev_mode,\n include_erts: release.profile.include_erts,\n include_src: release.profile.include_src,\n include_system_libs: release.profile.include_system_libs,\n erl_opts: release.profile.erl_opts,\n erts_vsn: erts_vsn,\n output_dir: release.profile.output_dir] ++ release.profile.overlay_vars\n Logger.debug \"Generated overlay vars:\"\n inspected = Enum.map(vars, fn\n {:release, _} -> nil\n {k, v} -> \"#{k}=#{inspect v}\"\n end)\n |> Enum.filter(fn nil -> false; _ -> true end)\n |> Enum.join(\"\\n \")\n Logger.debug \" #{inspected}\", :plain\n {:ok, %{release | :profile => %{release.profile | :overlay_vars => vars}}}\n end\n end\n\n @spec get_erts_version(Release.t) :: {:ok, String.t} | {:error, term}\n defp get_erts_version(%Release{profile: %Profile{include_erts: path}}) when is_binary(path),\n do: Utils.detect_erts_version(path)\n defp get_erts_version(%Release{profile: %Profile{include_erts: _}}),\n do: {:ok, Utils.erts_version()}\n\n defp check_cookie(%Release{profile: %Profile{cookie: cookie} = profile} = release) do\n cond do\n !cookie ->\n Logger.warn \"Attention! You did not provide a cookie for the erlang distribution protocol in rel\/config.exs\\n\" <>\n \" For backwards compatibility, the release name will be used as a cookie, which is potentially a security risk!\\n\" <>\n \" Please generate a secure cookie and use it with `set cookie: ` in rel\/config.exs.\\n\" <>\n \" This will be an error in a future release.\"\n %{release | :profile => %{profile | :cookie => release.name}}\n not is_atom(cookie) ->\n %{release | :profile => %{profile | :cookie => :\"#{cookie}\"}}\n String.contains?(Atom.to_string(cookie), \"insecure\") ->\n Logger.warn \"Attention! You have an insecure cookie for the erlang distribution protocol in rel\/config.exs\\n\" <>\n \"This is probably because a secure cookie could not be auto-generated.\\n\" <>\n \"Please generate a secure cookie and use it with `set cookie: ` in rel\/config.exs.\" <>\n release\n :else ->\n release\n end\n end\n\nend\n","old_contents":"defmodule Mix.Releases.Assembler do\n @moduledoc \"\"\"\n This module is responsible for assembling a release based on a `Mix.Releases.Config`\n struct. It creates the release directory, copies applications, and generates release-specific\n files required by `:systools` and `:release_handler`.\n \"\"\"\n alias Mix.Releases.{Config, Release, Environment, Profile, App}\n alias Mix.Releases.{Utils, Logger, Appup, Plugin, Overlays}\n\n require Record\n Record.defrecordp :file_info, Record.extract(:file_info, from_lib: \"kernel\/include\/file.hrl\")\n\n @doc \"\"\"\n This function takes a Config struct and assembles the release.\n\n **Note: This operation has side-effects!** It creates files, directories,\n copies files from other filesystem locations. If failures occur, no cleanup\n of files\/directories is performed. However, all files\/directories created by\n this function are scoped to the current project's `rel` directory, and cannot\n impact the filesystem outside of this directory.\n \"\"\"\n @spec assemble(Config.t) :: {:ok, Config.t} | {:error, term}\n def assemble(%Config{} = config) do\n with {:ok, environment} <- select_environment(config),\n {:ok, release} <- select_release(config),\n {:ok, release} <- apply_environment(release, environment),\n :ok <- validate_configuration(release),\n {:ok, release} <- apply_configuration(release, config),\n :ok <- File.mkdir_p(release.profile.output_dir),\n {:ok, release} <- Plugin.before_assembly(release),\n {:ok, release} <- generate_overlay_vars(release),\n {:ok, release} <- copy_applications(release),\n :ok <- create_release_info(release),\n {:ok, release} <- apply_overlays(release),\n {:ok, release} <- Plugin.after_assembly(release),\n do: {:ok, release}\n end\n\n # Determines the correct environment to assemble in\n @spec select_environment(Config.t) :: {:ok, Environment.t} | {:error, :no_environments}\n def select_environment(%Config{selected_environment: :default, default_environment: :default} = c),\n do: select_environment(Map.fetch(c.environments, :default))\n def select_environment(%Config{selected_environment: :default, default_environment: name} = c),\n do: select_environment(Map.fetch(c.environments, name))\n def select_environment(%Config{selected_environment: name} = c),\n do: select_environment(Map.fetch(c.environments, name))\n def select_environment({:ok, _} = e), do: e\n def select_environment(_), do: {:error, :no_environments}\n\n # Determines the correct release to assemble\n @spec select_release(Config.t) :: {:ok, Release.t} | {:error, :no_releases}\n def select_release(%Config{selected_release: :default, default_release: :default} = c),\n do: {:ok, List.first(Map.values(c.releases))}\n def select_release(%Config{selected_release: :default, default_release: name} = c),\n do: select_release(Map.fetch(c.releases, name))\n def select_release(%Config{selected_release: name} = c),\n do: select_release(Map.fetch(c.releases, name))\n def select_release({:ok, _} = r), do: r\n def select_release(_), do: {:error, :no_releases}\n\n # Applies the environment profile to the release profile.\n @spec apply_environment(Release.t, Environment.t) :: {:ok, Release.t} | {:error, term}\n def apply_environment(%Release{profile: rel_profile} = r, %Environment{profile: env_profile} = e) do\n Logger.info \"Building release #{r.name}:#{r.version} using environment #{e.name}\"\n env_profile = Map.from_struct(env_profile)\n profile = Enum.reduce(env_profile, rel_profile, fn {k, v}, acc ->\n case v do\n ignore when ignore in [nil, []] -> acc\n _ -> Map.put(acc, k, v)\n end\n end)\n {:ok, %{r | :profile => profile}}\n end\n\n @spec validate_configuration(Release.t) :: :ok | {:error, term}\n def validate_configuration(%Release{version: _, profile: profile}) do\n with :ok <- Utils.validate_erts(profile.include_erts) do\n # Warn if not including ERTS when not obviously running in a dev configuration\n if profile.dev_mode == false and profile.include_erts == false do\n Logger.notice \"IMPORTANT: You have opted to *not* include the Erlang runtime system (ERTS).\\n\" <>\n \"You must ensure that the version of Erlang this release is built with matches\\n\" <>\n \"the version the release will be run with once deployed. It will fail to run otherwise.\"\n end\n :ok\n end\n end\n\n # Applies global configuration options to the release profile\n @spec apply_configuration(Release.t, Config.t) :: {:ok, Release.t} | {:error, term}\n def apply_configuration(%Release{version: current_version, profile: profile} = release, %Config{} = config) do\n config_path = case profile.config do\n p when is_binary(p) -> p\n _ -> Keyword.get(Mix.Project.config, :config_path)\n end\n base_release = %{release | :profile => %{profile | :config => config_path}}\n release = check_cookie(base_release)\n case Utils.get_apps(release) do\n {:error, _} = err -> err\n release_apps ->\n release = %{release | :applications => release_apps}\n case config.is_upgrade do\n true ->\n case config.upgrade_from do\n :latest ->\n upfrom = case Utils.get_release_versions(release.profile.output_dir) do\n [] -> :no_upfrom\n [^current_version, v|_] -> v\n [v|_] -> v\n end\n case upfrom do\n :no_upfrom ->\n Logger.warn \"An upgrade was requested, but there are no \" <>\n \"releases to upgrade from, no upgrade will be performed.\"\n {:ok, %{release | :is_upgrade => false, :upgrade_from => nil}}\n v ->\n {:ok, %{release | :is_upgrade => true, :upgrade_from => v}}\n end\n ^current_version ->\n Logger.error \"Upgrade from #{current_version} to #{current_version} failed:\\n \" <>\n \"Upfrom version and current version are the same\"\n {:error, :bad_upgrade_spec}\n version when is_binary(version) ->\n Logger.debug \"Upgrading #{release.name} from #{version} to #{current_version}\"\n upfrom_path = Path.join([release.profile.output_dir, \"releases\", version])\n case File.exists?(upfrom_path) do\n false ->\n Logger.error \"Upgrade from #{version} to #{current_version} failed:\\n \" <>\n \"#{version} does not exist at #{upfrom_path}\"\n {:error, :bad_upgrade_spec}\n true ->\n {:ok, %{release | :is_upgrade => true, :upgrade_from => version}}\n end\n end\n false ->\n {:ok, release}\n end\n end\n end\n\n # Copies application beams to the output directory\n defp copy_applications(%Release{profile: %Profile{output_dir: output_dir}} = release) do\n Logger.debug \"Copying applications to #{output_dir}\"\n try do\n File.mkdir_p!(Path.join(output_dir, \"lib\"))\n for app <- release.applications do\n copy_app(app, release)\n end\n # Copy consolidated .beams\n build_path = Mix.Project.build_path(Mix.Project.config)\n consolidated_dest = Path.join([output_dir, \"lib\", \"#{release.name}-#{release.version}\", \"consolidated\"])\n File.mkdir_p!(consolidated_dest)\n consolidated_src = Path.join(build_path, \"consolidated\")\n if File.exists?(consolidated_src) do\n {:ok, _} = File.cp_r(consolidated_src, consolidated_dest)\n end\n {:ok, release}\n catch\n kind, err ->\n {:error, Exception.format(kind, err, System.stacktrace)}\n end\n end\n\n # Copies a specific application to the output directory\n defp copy_app(app, %Release{profile: %Profile{\n output_dir: output_dir,\n dev_mode: dev_mode?,\n include_src: include_src?,\n include_erts: include_erts?}}) do\n app_name = app.name\n app_version = app.vsn\n app_dir = app.path\n lib_dir = Path.join(output_dir, \"lib\")\n target_dir = Path.join(lib_dir, \"#{app_name}-#{app_version}\")\n remove_symlink_or_dir!(target_dir)\n case include_erts? do\n true ->\n copy_app(app_dir, target_dir, dev_mode?, include_src?)\n p when is_binary(p) ->\n copy_app(app_dir, target_dir, dev_mode?, include_src?)\n _ ->\n case Utils.is_erts_lib?(app_dir) do\n true ->\n :ok\n false ->\n copy_app(app_dir, target_dir, dev_mode?, include_src?)\n end\n end\n end\n defp copy_app(app_dir, target_dir, true, _include_src?) do\n case File.ln_s(app_dir, target_dir) do\n :ok -> :ok\n {:error, reason} ->\n raise \"unable to link app directory:\\n \" <>\n \"#{app_dir} -> #{target_dir}\\n \" <>\n \"Reason: #{reason}\"\n end\n end\n defp copy_app(app_dir, target_dir, false, include_src?) do\n case File.mkdir_p(target_dir) do\n {:error, reason} ->\n raise \"unable to create app directory:\\n \" <>\n \"#{target_dir}\\n \" <>\n \"Reason: #{reason}\"\n :ok ->\n valid_dirs = cond do\n include_src? ->\n [\"ebin\", \"include\", \"priv\", \"lib\", \"src\"]\n :else ->\n [\"ebin\", \"include\", \"priv\"]\n end\n Path.wildcard(Path.join(app_dir, \"*\"))\n |> Enum.filter(fn p -> Path.basename(p) in valid_dirs end)\n |> Enum.each(fn p ->\n t = Path.join(target_dir, Path.basename(p))\n if symlink?(p) do\n # We need to follow the symlink\n File.mkdir_p!(t)\n Path.wildcard(Path.join(p, \"*\"))\n |> Enum.each(fn child ->\n tc = Path.join(t, Path.basename(child))\n case File.cp_r(child, tc) do\n {:ok, _} -> :ok\n {:error, reason, file} ->\n raise \"unable to copy app directory:\\n \" <>\n \"#{child} -> #{tc}\\n \" <>\n \"File: #{file}\\n \" <>\n \"Reason: #{reason}\"\n end\n end)\n else\n case File.cp_r(p, t) do\n {:ok, _} -> :ok\n {:error, reason, file} ->\n raise \"unable to copy app directory:\\n \" <>\n \"#{p} -> #{t}\\n \" <>\n \"File: #{file}\\n \" <>\n \"Reason: #{reason}\"\n end\n end\n end)\n end\n end\n\n defp remove_symlink_or_dir!(path) do\n case File.exists?(path) do\n true ->\n File.rm_rf!(path)\n false ->\n if symlink?(path) do\n File.rm!(path)\n end\n end\n :ok\n end\n\n defp symlink?(path) do\n case :file.read_link_info('#{path}') do\n {:ok, info} ->\n elem(info, 2) == :symlink\n _ ->\n false\n end\n end\n\n # Creates release metadata files\n defp create_release_info(%Release{name: relname, profile: %Profile{output_dir: output_dir}} = release) do\n rel_dir = Path.join([output_dir, \"releases\", \"#{release.version}\"])\n case File.mkdir_p(rel_dir) do\n {:error, reason} ->\n {:error, \"failed to create release directory: #{rel_dir}\\n Reason: #{reason}\"}\n :ok ->\n release_file = Path.join(rel_dir, \"#{relname}.rel\")\n start_clean_file = Path.join(rel_dir, \"start_clean.rel\")\n start_clean_rel = %{release |\n :applications => Enum.filter(release.applications, fn %App{name: n} ->\n n in [:kernel, :stdlib, :compiler, :elixir, :iex]\n end)}\n with :ok <- write_relfile(release_file, release),\n :ok <- write_relfile(start_clean_file, start_clean_rel),\n :ok <- write_binfile(release, rel_dir),\n :ok <- generate_relup(release, rel_dir), do: :ok\n end\n end\n\n # Creates the .rel file for the release\n defp write_relfile(path, %Release{applications: apps} = release) do\n case get_erts_version(release) do\n {:error, _} = err -> err\n {:ok, erts_vsn} ->\n relfile = {:release,\n {'#{release.name}', '#{release.version}'},\n {:erts, '#{erts_vsn}'},\n apps\n |> Enum.with_index\n |> Enum.sort_by(fn\n {%App{name: :kernel}, _idx} -> -2\n {%App{name: :stdlib}, _idx} -> -1\n {%App{}, idx} -> idx\n end)\n |> Enum.map(fn {%App{name: name, vsn: vsn, start_type: start_type}, _idx} ->\n case start_type do\n nil ->\n {name, '#{vsn}'}\n t ->\n {name, '#{vsn}', t}\n end\n end)}\n Utils.write_term(path, relfile)\n end\n end\n\n # Creates the .boot files, nodetool, vm.args, sys.config, start_erl.data, and includes ERTS into\n # the release if so configured\n defp write_binfile(release, rel_dir) do\n name = \"#{release.name}\"\n bin_dir = Path.join(release.profile.output_dir, \"bin\")\n bootloader_path = Path.join(bin_dir, name)\n boot_path = Path.join(rel_dir, \"#{name}.sh\")\n template_params = release.profile.overlay_vars\n\n with :ok <- File.mkdir_p(bin_dir),\n :ok <- generate_nodetool(bin_dir),\n {:ok, bootloader_contents} <- Utils.template(:boot_loader, template_params),\n {:ok, boot_contents} <- Utils.template(:boot, template_params),\n :ok <- File.write(bootloader_path, bootloader_contents),\n :ok <- File.write(boot_path, boot_contents),\n :ok <- File.chmod(bootloader_path, 0o777),\n :ok <- File.chmod!(boot_path, 0o777),\n :ok <- generate_start_erl_data(release, rel_dir),\n :ok <- generate_vm_args(release, rel_dir),\n :ok <- generate_sys_config(release, rel_dir),\n :ok <- include_erts(release),\n :ok <- make_boot_script(release, rel_dir), do: :ok\n end\n\n # Generates a relup and .appup for all upgraded applications during upgrade releases\n defp generate_relup(%Release{is_upgrade: false}, _rel_dir), do: :ok\n defp generate_relup(%Release{name: name, upgrade_from: upfrom, profile: %Profile{output_dir: output_dir}} = release, rel_dir) do\n Logger.debug \"Generating relup for #{name}\"\n v1_rel = Path.join([output_dir, \"releases\", upfrom, \"#{name}.rel\"])\n v2_rel = Path.join(rel_dir, \"#{name}.rel\")\n case {File.exists?(v1_rel), File.exists?(v2_rel)} do\n {false, true} ->\n {:error, \"Missing .rel for #{name}:#{upfrom} at #{v1_rel}\"}\n {true, false} ->\n {:error, \"Missing .rel for #{name}:#{release.version} at #{v2_rel}\"}\n {false, false} ->\n {:error, \"Missing .rels\\n \" <>\n \"#{name}:#{upfrom} @ #{v1_rel}\\n \" <>\n \"#{name}:#{release.version} @ #{v2_rel}\"}\n {true, true} ->\n v1_apps = extract_relfile_apps(v1_rel)\n v2_apps = extract_relfile_apps(v2_rel)\n changed = get_changed_apps(v1_apps, v2_apps)\n added = get_added_apps(v2_apps, changed)\n case generate_appups(changed, output_dir) do\n {:error, _} = err ->\n err\n :ok ->\n current_rel = Path.join([output_dir, \"releases\", release.version, \"#{name}\"])\n upfrom_rel = Path.join([output_dir, \"releases\", release.upgrade_from, \"#{name}\"])\n result = :systools.make_relup(\n String.to_charlist(current_rel),\n [String.to_charlist(upfrom_rel)],\n [String.to_charlist(upfrom_rel)],\n [{:outdir, String.to_charlist(rel_dir)},\n {:path, get_relup_code_paths(added, changed, output_dir)},\n :silent,\n :no_warn_sasl]\n )\n case result do\n {:ok, relup, _mod, []} ->\n Logger.info \"Relup successfully created\"\n Utils.write_term(Path.join(rel_dir, \"relup\"), relup)\n {:ok, relup, mod, warnings} ->\n Logger.warn format_systools_warning(mod, warnings)\n Logger.info \"Relup successfully created\"\n Utils.write_term(Path.join(rel_dir, \"relup\"), relup)\n {:error, mod, errors} ->\n error = format_systools_error(mod, errors)\n {:error, error}\n end\n end\n end\n end\n\n defp format_systools_warning(mod, warnings) do\n warning = mod.format_warning(warnings)\n |> IO.iodata_to_binary\n |> String.split(\"\\n\")\n |> Enum.map(fn e -> \" \" <> e end)\n |> Enum.join(\"\\n\")\n |> String.trim_trailing\n \"\\n#{warning}\"\n end\n\n defp format_systools_error(mod, errors) do\n error = mod.format_error(errors)\n |> IO.iodata_to_binary\n |> String.split(\"\\n\")\n |> Enum.map(fn e -> \" \" <> e end)\n |> Enum.join(\"\\n\")\n |> String.trim_trailing\n \"\\n#{error}\"\n end\n\n # Get a list of applications from the .rel file at the given path\n defp extract_relfile_apps(path) do\n case Utils.read_terms(path) do\n {:error, err} -> raise err\n {:ok, [{:release, _rel, _erts, apps}]} ->\n Enum.map(apps, fn {a, v} -> {a, v}; {a, v, _start_type} -> {a, v} end)\n {:ok, other} -> raise \"malformed relfile (#{path}): #{inspect other}\"\n end\n end\n\n # Determine the set of apps which have changed between two versions\n defp get_changed_apps(a, b) do\n as = Enum.map(a, fn app -> elem(app, 0) end) |> MapSet.new\n bs = Enum.map(b, fn app -> elem(app, 0) end) |> MapSet.new\n shared = MapSet.to_list(MapSet.intersection(as, bs))\n a_versions = Enum.map(shared, fn n -> {n, elem(List.keyfind(a, n, 0), 1)} end) |> MapSet.new\n b_versions = Enum.map(shared, fn n -> {n, elem(List.keyfind(b, n, 0), 1)} end) |> MapSet.new\n MapSet.difference(b_versions, a_versions)\n |> MapSet.to_list\n |> Enum.map(fn {n, v2} ->\n v1 = List.keyfind(a, n, 0) |> elem(1)\n {n, \"#{v1}\", \"#{v2}\"}\n end)\n end\n\n # Determine the set of apps which were added between two versions\n defp get_added_apps(v2_apps, changed) do\n changed_apps = Enum.map(changed, &elem(&1, 0))\n Enum.reject(v2_apps, fn a ->\n elem(a, 0) in changed_apps\n end)\n end\n\n # Generate .appup files for a list of {app, v1, v2}\n defp generate_appups([], _output_dir), do: :ok\n defp generate_appups([{app, v1, v2}|apps], output_dir) do\n v1_path = Path.join([output_dir, \"lib\", \"#{app}-#{v1}\"])\n v2_path = Path.join([output_dir, \"lib\", \"#{app}-#{v2}\"])\n appup_path = Path.join([v2_path, \"ebin\", \"#{app}.appup\"])\n appup_exists? = File.exists?(appup_path)\n appup_valid? = case :file.consult(~c[#{appup_path}]) do\n {:ok, [{upto_ver, [{downto_ver, _}], [{downto_ver, _}]}]} ->\n cond do\n upto_ver == ~c[#{v2}] and downto_ver == ~c[#{v1}] ->\n true\n :else ->\n false\n end\n _other ->\n false\n end\n cond do\n appup_exists? && appup_valid? ->\n Logger.debug \"#{app} requires an appup, and one was provided, skipping generation..\"\n generate_appups(apps, output_dir)\n appup_exists? ->\n Logger.warn \"#{app} has an appup file, but it is invalid for this release,\\n\" <>\n \" Backing up appfile with .bak extension and generating new one..\"\n :ok = File.cp!(appup_path, \"#{appup_path}.bak\")\n case Appup.make(app, v1, v2, v1_path, v2_path) do\n {:error, reason} ->\n {:error, \"Failed to generate appup for #{app}:\\n \" <>\n inspect(reason)}\n {:ok, appup} ->\n :ok = Utils.write_term(appup_path, appup)\n Logger.info \"Generated .appup for #{app} #{v1} -> #{v2}\"\n generate_appups(apps, output_dir)\n end\n :else ->\n Logger.debug \"#{app} requires an appup, but it wasn't provided, one will be generated for you..\"\n case Appup.make(app, v1, v2, v1_path, v2_path) do\n {:error, reason} ->\n {:error, \"Failed to generate appup for #{app}:\\n \" <>\n inspect(reason)}\n {:ok, appup} ->\n :ok = Utils.write_term(appup_path, appup)\n Logger.info \"Generated .appup for #{app} #{v1} -> #{v2}\"\n generate_appups(apps, output_dir)\n end\n end\n end\n\n # Get a list of code paths containing only those paths which have beams\n # from the two versions in the release being upgraded\n defp get_relup_code_paths(added, changed, output_dir) do\n added_paths = get_added_relup_code_paths(added, output_dir, [])\n changed_paths = get_changed_relup_code_paths(changed, output_dir, [], [])\n added_paths ++ changed_paths\n end\n defp get_changed_relup_code_paths([], _output_dir, v1_paths, v2_paths) do\n v2_paths ++ v1_paths\n end\n defp get_changed_relup_code_paths([{app, v1, v2}|apps], output_dir, v1_paths, v2_paths) do\n v1_path = Path.join([output_dir, \"lib\", \"#{app}-#{v1}\", \"ebin\"]) |> String.to_charlist\n v2_path = Path.join([output_dir, \"lib\", \"#{app}-#{v2}\", \"ebin\"]) |> String.to_charlist\n v2_path_consolidated = Path.join([output_dir, \"lib\", \"#{app}-#{v2}\", \"consolidated\"]) |> String.to_charlist\n get_changed_relup_code_paths(\n apps,\n output_dir,\n [v1_path|v1_paths],\n [v2_path_consolidated, v2_path|v2_paths])\n end\n defp get_added_relup_code_paths([], _output_dir, paths), do: paths\n defp get_added_relup_code_paths([{app, v2}|apps], output_dir, paths) do\n v2_path = Path.join([output_dir, \"lib\", \"#{app}-#{v2}\", \"ebin\"]) |> String.to_charlist\n v2_path_consolidated = Path.join([output_dir, \"lib\", \"#{app}-#{v2}\", \"consolidated\"]) |> String.to_charlist\n get_added_relup_code_paths(apps, output_dir, [v2_path_consolidated, v2_path|paths])\n end\n\n # Generates the nodetool utility\n defp generate_nodetool(bin_dir) do\n Logger.debug \"Generating nodetool\"\n with {:ok, node_tool_file} = Utils.template(:nodetool),\n {:ok, release_utils_file} = Utils.template(:release_utils),\n :ok <- File.write(Path.join(bin_dir, \"nodetool\"), node_tool_file),\n :ok <- File.write(Path.join(bin_dir, \"release_utils.escript\"), release_utils_file),\n do: :ok\n end\n\n # Generates start_erl.data\n defp generate_start_erl_data(%Release{version: version, profile: %Profile{include_erts: false}}, rel_dir) do\n Logger.debug \"Generating start_erl.data\"\n contents = \"ERTS_VSN #{version}\"\n File.write(Path.join([rel_dir, \"..\", \"start_erl.data\"]), contents)\n end\n defp generate_start_erl_data(%Release{profile: %Profile{include_erts: path}} = release, rel_dir)\n when is_binary(path) do\n Logger.debug \"Generating start_erl.data\"\n case Utils.detect_erts_version(path) do\n {:error, _} = err -> err\n {:ok, vsn} ->\n contents = \"#{vsn} #{release.version}\"\n File.write(Path.join([rel_dir, \"..\", \"start_erl.data\"]), contents)\n end\n end\n defp generate_start_erl_data(release, rel_dir) do\n Logger.debug \"Generating start_erl.data\"\n contents = \"#{Utils.erts_version} #{release.version}\"\n File.write(Path.join([rel_dir, \"..\", \"start_erl.data\"]), contents)\n end\n\n # Generates vm.args\n defp generate_vm_args(%Release{profile: %Profile{vm_args: nil}} = rel, rel_dir) do\n Logger.debug \"Generating vm.args\"\n overlay_vars = rel.profile.overlay_vars\n with {:ok, contents} <- Utils.template(\"vm.args\", overlay_vars),\n :ok <- File.write(Path.join(rel_dir, \"vm.args\"), contents),\n do: :ok\n end\n defp generate_vm_args(%Release{profile: %Profile{vm_args: path}} = rel, rel_dir) do\n Logger.debug \"Generating vm.args from #{Path.relative_to_cwd(path)}\"\n overlay_vars = rel.profile.overlay_vars\n with {:ok, path} <- Overlays.template_str(path, overlay_vars),\n {:ok, templated} <- Overlays.template_file(path, overlay_vars),\n :ok <- File.write(Path.join(rel_dir, \"vm.args\"), templated),\n do: :ok\n end\n\n # Generates sys.config\n defp generate_sys_config(%Release{profile: %Profile{config: base_config_path, sys_config: config_path}} = rel, rel_dir)\n when is_binary(config_path) do\n Logger.debug \"Generating sys.config from #{Path.relative_to_cwd(config_path)}\"\n overlay_vars = rel.profile.overlay_vars\n base_config = generate_base_config(base_config_path)\n res = with {:ok, path} <- Overlays.template_str(config_path, overlay_vars),\n {:ok, templated} <- Overlays.template_file(path, overlay_vars),\n {:ok, tokens, _} <- :erl_scan.string(String.to_charlist(templated)),\n {:ok, sys_config} <- :erl_parse.parse_term(tokens),\n :ok <- validate_sys_config(sys_config),\n merged <- Mix.Config.merge(base_config, sys_config),\n do: Utils.write_term(Path.join(rel_dir, \"sys.config\"), merged)\n case res do\n {:error, :invalid_sys_config, reason} ->\n {:error, \"invalid sys.config: #{reason}\"}\n {:error, {_loc, _module, description}, {line, col}} ->\n {:error, \"invalid sys.config at line #{line}, column #{col}: #{inspect description}\"}\n {:error, {_loc, _module, description}, line} ->\n {:error, \"invalid sys.config at line #{line}: #{inspect description}\"}\n {:error, {line, _module, description}} ->\n {:error, \"could not parse sys.config at line #{line}: #{inspect description}\"}\n other ->\n other\n end\n end\n defp generate_sys_config(%Release{profile: %Profile{config: config_path}}, rel_dir) do\n Logger.debug \"Generating sys.config from #{Path.relative_to_cwd(config_path)}\"\n config = generate_base_config(config_path)\n Utils.write_term(Path.join(rel_dir, \"sys.config\"), config)\n end\n\n defp generate_base_config(base_config_path) do\n config = Mix.Config.read!(base_config_path)\n case Keyword.get(config, :sasl) do\n nil ->\n Keyword.put(config, :sasl, [errlog_type: :error])\n sasl ->\n case Keyword.get(sasl, :errlog_type) do\n nil -> put_in(config, [:sasl, :errlog_type], :error)\n _ -> config\n end\n end\n end\n\n defp validate_sys_config(sys_config) when is_list(sys_config) do\n cond do\n Keyword.keyword?(sys_config) ->\n is_config? = Enum.reduce(sys_config, true, fn\n {app, config}, acc when is_atom(app) and is_list(config) ->\n acc && Keyword.keyword?(config)\n {_app, _config}, _acc ->\n false\n end)\n cond do\n is_config? ->\n :ok\n :else ->\n {:error, :invalid_sys_config, \"must be a list of {:app_name, [{:key, value}]} tuples\"}\n end\n :else ->\n {:error, :invalid_sys_config, \"must be a keyword list\"}\n end\n end\n defp validate_sys_config(_sys_config), do: {:error, :invalid_sys_config, \"must be a keyword list\"}\n\n # Adds ERTS to the release, if so configured\n defp include_erts(%Release{profile: %Profile{include_erts: false}, is_upgrade: false}), do: :ok\n defp include_erts(%Release{profile: %Profile{include_erts: false}, is_upgrade: true}) do\n {:error, \"Hot upgrades will fail when include_erts: false is set,\\n\" <>\n \" you need to set include_erts to true or a path if you plan to use them!\"}\n end\n defp include_erts(%Release{profile: %Profile{include_erts: include_erts, output_dir: output_dir}} = release) do\n prefix = case include_erts do\n true -> \"#{:code.root_dir}\"\n p when is_binary(p) ->\n Path.expand(p)\n end\n erts_vsn = case include_erts do\n true -> Utils.erts_version()\n p when is_binary(p) ->\n case Utils.detect_erts_version(prefix) do\n {:ok, vsn} ->\n # verify that the path given was actually the right one\n case File.exists?(Path.join(prefix, \"bin\")) do\n true -> vsn\n false ->\n pfx = Path.relative_to_cwd(prefix)\n maybe_path = Path.relative_to_cwd(Path.expand(Path.join(prefix, \"..\")))\n {:error, \"invalid ERTS path, did you mean #{maybe_path} instead of #{pfx}?\"}\n end\n {:error, _} = err -> err\n end\n end\n case erts_vsn do\n {:error, _} = err ->\n err\n _ ->\n erts_dir = Path.join([prefix, \"erts-#{erts_vsn}\"])\n\n Logger.info \"Including ERTS #{erts_vsn} from #{Path.relative_to_cwd(erts_dir)}\"\n\n erts_output_dir = Path.join(output_dir, \"erts-#{erts_vsn}\")\n erl_path = Path.join([erts_output_dir, \"bin\", \"erl\"])\n nodetool_path = Path.join([output_dir, \"bin\", \"nodetool\"])\n nodetool_dest = Path.join([erts_output_dir, \"bin\", \"nodetool\"])\n with :ok <- remove_if_exists(erts_output_dir),\n :ok <- File.mkdir_p(erts_output_dir),\n {:ok, _} <- File.cp_r(erts_dir, erts_output_dir),\n {:ok, _} <- File.rm_rf(erl_path),\n {:ok, erl_script} <- Utils.template(:erl_script, release.profile.overlay_vars),\n :ok <- File.write(erl_path, erl_script),\n :ok <- File.chmod(erl_path, 0o755),\n :ok <- File.cp(nodetool_path, nodetool_dest),\n :ok <- File.chmod(nodetool_dest, 0o755) do\n :ok\n else\n {:error, reason} ->\n {:error, \"Failed during include_erts: #{inspect reason}\"}\n {:error, reason, file} ->\n {:error, \"Failed to remove file during include_erts: #{inspect reason} #{file}\"}\n end\n end\n end\n\n defp remove_if_exists(path) do\n case File.exists?(path) do\n false -> :ok\n true ->\n case File.rm_rf(path) do\n {:ok, _} -> :ok\n {:error, _, _} = err -> err\n end\n end\n end\n\n # Generates .boot script\n defp make_boot_script(%Release{profile: %Profile{output_dir: output_dir}} = release, rel_dir) do\n Logger.debug \"Generating boot script\"\n erts_lib_dir = case release.profile.include_erts do\n false -> :code.lib_dir()\n true -> :code.lib_dir()\n p -> String.to_charlist(Path.expand(Path.join(p, \"lib\")))\n end\n options = [{:path, ['#{rel_dir}' | Release.get_code_paths(release)]},\n {:outdir, '#{rel_dir}'},\n {:variables, [{'ERTS_LIB_DIR', erts_lib_dir}]},\n :no_warn_sasl,\n :no_module_tests,\n :silent]\n rel_name = '#{release.name}'\n release_file = Path.join(rel_dir, \"#{release.name}.rel\")\n case :systools.make_script(rel_name, options) do\n :ok ->\n with :ok <- create_RELEASES(output_dir, Path.join([\"releases\", \"#{release.version}\", \"#{release.name}.rel\"])),\n :ok <- create_start_clean(rel_dir, output_dir, options), do: :ok\n {:ok, _, []} ->\n with :ok <- create_RELEASES(output_dir, Path.join([\"releases\", \"#{release.version}\", \"#{release.name}.rel\"])),\n :ok <- create_start_clean(rel_dir, output_dir, options), do: :ok\n :error ->\n {:error, {:unknown, release_file}}\n {:ok, mod, warnings} ->\n Logger.warn format_systools_warning(mod, warnings)\n :ok\n {:error, mod, errors} ->\n error = format_systools_error(mod, errors)\n {:error, error}\n end\n end\n\n # Generates RELEASES\n defp create_RELEASES(output_dir, relfile) do\n Logger.debug \"Generating RELEASES\"\n # NOTE: The RELEASES file must contain the correct paths to all libs,\n # including ERTS libs. When include_erts: false, the ERTS path, and thus\n # the paths to all ERTS libs, are not known until runtime. That means the\n # RELEASES file we generate here is invalid, which also means that performing\n # hot upgrades with include_erts: false will fail.\n #\n # This is annoying, but makes sense in the context of how release_handler works,\n # it must be able to handle upgrades where ERTS itself is also upgraded, and that\n # clearly can't happen if there is only one ERTS version (the host). It would be\n # possible to handle this if we could update the release_handler's state after it\n # unpacks a release in order to \"fix\" the invalid ERTS lib paths, but unfortunately\n # this is not exposed, and short of re-writing release_handler from scratch, there is\n # no work around for this\n old_cwd = File.cwd!\n File.cd!(output_dir)\n :ok = :release_handler.create_RELEASES('.\/', 'releases', '#{relfile}', [])\n File.cd!(old_cwd)\n :ok\n end\n\n # Generates start_clean.boot\n defp create_start_clean(rel_dir, output_dir, options) do\n Logger.debug \"Generating start_clean.boot\"\n case :systools.make_script('start_clean', options) do\n :ok ->\n with :ok <- File.cp(Path.join(rel_dir, \"start_clean.boot\"),\n Path.join([output_dir, \"bin\", \"start_clean.boot\"])),\n :ok <- File.rm(Path.join(rel_dir, \"start_clean.rel\")),\n :ok <- File.rm(Path.join(rel_dir, \"start_clean.script\")) do\n :ok\n else\n {:error, reason} ->\n {:error, \"Failed during create_start_clean: #{inspect reason}\"}\n end\n :error ->\n {:error, {:unknown, :create_start_clean}}\n {:ok, _, []} ->\n with :ok <- File.cp(Path.join(rel_dir, \"start_clean.boot\"),\n Path.join([output_dir, \"bin\", \"start_clean.boot\"])),\n :ok <- File.rm(Path.join(rel_dir, \"start_clean.rel\")),\n :ok <- File.rm(Path.join(rel_dir, \"start_clean.script\")) do\n :ok\n else\n {:error, reason} ->\n {:error, \"Failed during create_start_clean: #{inspect reason}\"}\n end\n {:ok, mod, warnings} ->\n Logger.warn format_systools_warning(mod, warnings)\n :ok\n {:error, mod, errors} ->\n error = format_systools_error(mod, errors)\n {:error, error}\n end\n end\n\n defp apply_overlays(%Release{} = release) do\n Logger.debug \"Applying overlays\"\n overlay_vars = release.profile.overlay_vars\n hooks_dir = \"releases\/<%= release_version %>\/hooks\"\n hook_overlays = [\n {:mkdir, hooks_dir},\n {:mkdir, \"#{hooks_dir}\/pre_start.d\"},\n {:mkdir, \"#{hooks_dir}\/post_start.d\"},\n {:mkdir, \"#{hooks_dir}\/pre_stop.d\"},\n {:mkdir, \"#{hooks_dir}\/post_stop.d\"},\n {:mkdir, \"#{hooks_dir}\/pre_upgrade.d\"},\n {:mkdir, \"#{hooks_dir}\/post_upgrade.d\"},\n {:copy, release.profile.pre_start_hook, \"#{hooks_dir}\/pre_start.d\/00_pre_start_hook.sh\"},\n {:copy, release.profile.post_start_hook, \"#{hooks_dir}\/post_start.d\/00_post_start_hook.sh\"},\n {:copy, release.profile.pre_stop_hook, \"#{hooks_dir}\/pre_stop.d\/00_pre_stop_hook.sh\"},\n {:copy, release.profile.post_stop_hook, \"#{hooks_dir}\/post_stop.d\/00_post_stop_hook.sh\"},\n {:copy, release.profile.pre_upgrade_hook, \"#{hooks_dir}\/pre_upgrade.d\/00_pre_upgrade_hook.sh\"},\n {:copy, release.profile.post_upgrade_hook, \"#{hooks_dir}\/post_upgrade.d\/00_post_upgrade_hook.sh\"},\n {:copy, release.profile.pre_start_hooks, \"#{hooks_dir}\/pre_start.d\"},\n {:copy, release.profile.post_start_hooks, \"#{hooks_dir}\/post_start.d\"},\n {:copy, release.profile.pre_stop_hooks, \"#{hooks_dir}\/pre_stop.d\"},\n {:copy, release.profile.post_stop_hooks, \"#{hooks_dir}\/post_stop.d\"},\n {:copy, release.profile.pre_upgrade_hooks, \"#{hooks_dir}\/pre_upgrade.d\"},\n {:copy, release.profile.post_upgrade_hooks, \"#{hooks_dir}\/post_upgrade.d\"},\n {:mkdir, \"releases\/<%= release_version %>\/commands\"} |\n Enum.map(release.profile.commands, fn {name, path} ->\n {:copy, path, \"releases\/<%= release_version %>\/commands\/#{name}\"}\n end)\n ] |> Enum.filter(fn {:copy, nil, _} -> false; _ -> true end)\n\n output_dir = release.profile.output_dir\n overlays = hook_overlays ++ release.profile.overlays\n case Overlays.apply(output_dir, overlays, overlay_vars) do\n {:ok, paths} ->\n release = %{release | :resolved_overlays => Enum.map(paths, fn path ->\n {'#{path}', '#{Path.join([output_dir, path])}'}\n end)}\n {:ok, release}\n {:error, _} = err ->\n err\n end\n end\n\n defp generate_overlay_vars(release) do\n case get_erts_version(release) do\n {:error, _} = err ->\n err\n {:ok, erts_vsn} ->\n vars = [release: release,\n release_name: release.name,\n release_version: release.version,\n is_upgrade: release.is_upgrade,\n upgrade_from: release.upgrade_from,\n dev_mode: release.profile.dev_mode,\n include_erts: release.profile.include_erts,\n include_src: release.profile.include_src,\n include_system_libs: release.profile.include_system_libs,\n erl_opts: release.profile.erl_opts,\n erts_vsn: erts_vsn,\n output_dir: release.profile.output_dir] ++ release.profile.overlay_vars\n Logger.debug \"Generated overlay vars:\"\n inspected = Enum.map(vars, fn\n {:release, _} -> nil\n {k, v} -> \"#{k}=#{inspect v}\"\n end)\n |> Enum.filter(fn nil -> false; _ -> true end)\n |> Enum.join(\"\\n \")\n Logger.debug \" #{inspected}\", :plain\n {:ok, %{release | :profile => %{release.profile | :overlay_vars => vars}}}\n end\n end\n\n @spec get_erts_version(Release.t) :: {:ok, String.t} | {:error, term}\n defp get_erts_version(%Release{profile: %Profile{include_erts: path}}) when is_binary(path),\n do: Utils.detect_erts_version(path)\n defp get_erts_version(%Release{profile: %Profile{include_erts: _}}),\n do: {:ok, Utils.erts_version()}\n\n defp check_cookie(%Release{profile: %Profile{cookie: cookie} = profile} = release) do\n cond do\n !cookie ->\n Logger.warn \"Attention! You did not provide a cookie for the erlang distribution protocol in rel\/config.exs\\n\" <>\n \" For backwards compatibility, the release name will be used as a cookie, which is potentially a security risk!\\n\" <>\n \" Please generate a secure cookie and use it with `set cookie: ` in rel\/config.exs.\\n\" <>\n \" This will be an error in a future release.\"\n %{release | :profile => %{profile | :cookie => release.name}}\n not is_atom(cookie) ->\n %{release | :profile => %{profile | :cookie => :\"#{cookie}\"}}\n String.contains?(Atom.to_string(cookie), \"insecure\") ->\n Logger.warn \"Attention! You have an insecure cookie for the erlang distribution protocol in rel\/config.exs\\n\" <>\n \"This is probably because a secure cookie could not be auto-generated.\\n\" <>\n \"Please generate a secure cookie and use it with `set cookie: ` in rel\/config.exs.\" <>\n release\n :else ->\n release\n end\n end\n\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"fdb318bd23da444cc31bf2636db64db1b590535e","subject":"Handle :closed message on receive, error on :error","message":"Handle :closed message on receive, error on :error\n\nBy handing the unexpected error return in the case statement, the error\nwould be silently swallowed.\n\nAdditional small whitespace cleanup -- couldn't resist.\n","repos":"MyMedsAndMe\/spell","old_file":"examples\/rpc.exs","new_file":"examples\/rpc.exs","new_contents":"# This example want to show how to call a Remote Procedure.\n# Inside the module RPC we have the module Callee where the procedure\n# is defined and the module Calleer who will call the procedure.\n#\n# Run this script from the Spell root with\n#\n# mix spell.example.rpc\n\ndefmodule RPC do\n @moduledoc \"\"\"\n The `RPC` module implements the example for asynchronous Remote Procedure Call.\n \"\"\"\n\n defmodule Caller do\n @moduledoc \"\"\"\n This Caller need to be initialised with the `procedure` where the Callee is subscribed\n and the `params` used within the remote procedure\n\n iex> Caller.start_link(\"com.spell.math.sum\", [arguments: [1, 2, 3]])\n \"\"\"\n require Logger\n defstruct [:caller, :procedure, :params, interval: 1500]\n\n # Public Functions\n\n @doc \"\"\"\n Initialize the caller\n \"\"\"\n def start_link(procedure, params \\\\ [], options \\\\ []) do\n {:ok, spawn_link(fn -> init(procedure, params, options) end)}\n end\n\n # Private Functions\n\n defp init(procedure, params, options) do\n {:ok, caller} = RPC.new_peer([Spell.Role.Caller], options)\n %__MODULE__{caller: caller,\n procedure: procedure,\n params: params}\n |> struct(options)\n |> loop()\n end\n\n defp loop(state) do\n # `Spell.cast_call` performs an asyncronous call to the remote procedure, the result will\n # be intercepted and parsed by the block `Spell.receive_result`\n {:ok, call_id} = Spell.cast_call(state.caller, state.procedure, state.params)\n Logger.info(\" send params: #{inspect(state.params)}\")\n\n case Spell.receive_result(state.caller, call_id) do\n {:ok, result} -> handle_result(state, result)\n {:closed, reason} -> :ok\n end\n\n :timer.sleep(1000)\n loop(state)\n end\n\n def handle_result(state, [_result_id, _options, _arguments, %{\"result\" => res}]) do\n Logger.info(\" received result: #{inspect(res)}\")\n end\n end\n\n defmodule Callee do\n use GenServer\n @moduledoc \"\"\"\n The callee need to be registered to the WAMP Dealer in order to be accesseble and expose\n the procedure.\n\n iex> Callee.start_link()\n\n Once it is registered it will wait an invocation from the Dealer and yield\n the result back. in this case we have two function exposed:\n\n - `spell.math.sum`\n - `spell.math.multiply`\n \"\"\"\n\n @doc \"\"\"\n Function that return the map of the functions exposed to the remote procedure\n \"\"\"\n def function_list do\n %{\n \"spell.math.sum\" => &Math.sum\/1,\n \"spell.math.multiply\" => &Math.multiply\/1\n }\n end\n\n require Logger\n defstruct [:callee, register: %{}, timeout: 1000]\n\n # Public Functions\n\n @doc \"\"\"\n Start the callee with the passed procedure.\n \"\"\"\n def start_link(options \\\\ []) do\n GenServer.start_link(__MODULE__, [options], name: __MODULE__)\n end\n\n def stop, do: GenServer.cast(__MODULE__, :stop)\n\n # Private Functions\n\n def init(options) do\n {:ok, callee} = RPC.new_peer([Spell.Role.Callee], options)\n\n # `Spell.cast_register` receive the callee and the procedure where it\n # has to be registered\n state = %__MODULE__{callee: callee}\n\n new_register = for {proc, function} <- function_list do\n {:ok, reg_id} = Spell.call_register(callee, proc)\n {reg_id, function}\n end\n |> Enum.into %{}\n\n state = Map.put(state, :register, new_register)\n {:ok, state}\n end\n\n def handle_cast(:stop, state), do: {:stop, :normal, state}\n\n def handle_info({Spell.Peer, pid, %Spell.Message{args: [request, reg_id, _msg, params], type: :invocation}}, (%{callee: callee}) = state) do\n rpc = state.register[reg_id]\n Spell.cast_yield(callee, request, [arguments_kw: %{result: rpc.(params)}])\n {:noreply, state}\n end\n end\n\n # Public Interface\n\n @doc \"\"\"\n Shared helper function for create a new peer configured with `roles` and\n `options`.\n \"\"\"\n def new_peer(roles, options) do\n uri = Keyword.get(options, :uri, Crossbar.uri)\n realm = Keyword.get(options, :realm, Crossbar.get_realm())\n Spell.connect(uri, realm: realm, roles: roles)\n end\nend\n\ndefmodule Math do\n @doc \"\"\"\n Module to provide some simple mathematic operations\n \"\"\"\n def sum(list), do: sum(list, 0)\n def sum([], acc), do: acc\n def sum(int, acc) when is_integer(int), do: sum([int], acc)\n def sum([h | t] = list, acc) when is_list(list) and is_integer(h), do: sum(t, acc + h)\n def sum([h | t] = list, acc) when is_list(list), do: sum(t, acc + String.to_integer(h))\n\n def multiply(list), do: multiply(list, 1)\n def multiply([], acc), do: acc\n def multiply(int, acc) when is_integer(int), do: multiply([int], acc)\n def multiply([h | t] = list, acc) when is_list(list) and is_integer(h), do: multiply(t, acc * h)\n def multiply([h | t] = list, acc) when is_list(list), do: multiply(t, acc * String.to_integer(h))\nend\n\nalias RPC.Callee\nalias RPC.Caller\nrequire Logger\n\nLogger.info(\"Starting the Crossbar.io test server...\")\n\n# Start the crossbar testing server\n{:ok, _pid} = Crossbar.start()\n\n# Register callee to the WAMP router\n{:ok, _callee} = Callee.start_link()\n\n# Call the remote procedure passing the agruments\n{:ok, _caller} = Caller.start_link(\"spell.math.sum\", [arguments: [1, 2, 3]])\n{:ok, _caller} = Caller.start_link(\"spell.math.multiply\", [arguments: [10, 4]])\n:timer.sleep(10000)\n\nLogger.info(\"DONE... Stopping Crossbar.io server\")\n\n# Stop the callee\n:ok = Callee.stop()\n# Stop the crossbar.io testing server\n:ok = Crossbar.stop()\n\nLogger.info(\"DONE.\")\n","old_contents":"# This example want to show how to call a Remote Procedure.\n# Inside the module RPC we have the module Callee where the procedure\n# is defined and the module Calleer who will call the procedure.\n#\n# Run this script from the Spell root with\n#\n# mix spell.example.rpc\n\ndefmodule RPC do\n @moduledoc \"\"\"\n The `RPC` module implements the example for asynchronous Remote Procedure Call.\n \"\"\"\n\n defmodule Caller do\n @moduledoc \"\"\"\n This Caller need to be initialised with the `procedure` where the Callee is subscribed\n and the `params` used within the remote procedure\n\n iex> Caller.start_link(\"com.spell.math.sum\", [arguments: [1, 2, 3]])\n \"\"\"\n require Logger\n defstruct [:caller, :procedure, :params, interval: 1500]\n\n # Public Functions\n\n @doc \"\"\"\n Initialize the caller\n \"\"\"\n def start_link(procedure, params \\\\ [], options \\\\ []) do\n {:ok, spawn_link(fn -> init(procedure, params, options) end)}\n end\n\n # Private Functions\n\n defp init(procedure, params, options) do\n {:ok, caller} = RPC.new_peer([Spell.Role.Caller], options)\n %__MODULE__{caller: caller,\n procedure: procedure,\n params: params}\n |> struct(options)\n |> loop()\n end\n\n defp loop(state) do\n\n\n # `Spell.cast_call` performs an asyncronous call to the remote procedure, the result will\n # be intercepted and parsed by the block `Spell.receive_result`\n {:ok, call_id} = Spell.cast_call(state.caller, state.procedure, state.params)\n Logger.info(\" send params: #{inspect(state.params)}\")\n\n case Spell.receive_result(state.caller, call_id) do\n {:ok, result} -> IO.inspect handle_result(state, result)\n {:error, reason} -> {:error, reason}\n end\n\n :timer.sleep(1000)\n loop(state)\n end\n\n def handle_result(state, [_result_id, _options, _arguments, %{\"result\" => res}]) do\n Logger.info(\" received result: #{inspect(res)}\")\n end\n end\n\n defmodule Callee do\n use GenServer\n @moduledoc \"\"\"\n The callee need to be registered to the WAMP Dealer in order to be accesseble and expose\n the procedure.\n\n iex> Callee.start_link()\n\n Once it is registered it will wait an invocation from the Dealer and yield\n the result back. in this case we have two function exposed:\n\n - `spell.math.sum`\n - `spell.math.multiply`\n \"\"\"\n\n @doc \"\"\"\n Function that return the map of the functions exposed to the remote procedure\n \"\"\"\n def function_list do\n %{\n \"spell.math.sum\" => &Math.sum\/1,\n \"spell.math.multiply\" => &Math.multiply\/1\n }\n end\n\n require Logger\n defstruct [:callee, register: %{}, timeout: 1000]\n\n # Public Functions\n\n @doc \"\"\"\n Start the callee with the passed procedure.\n \"\"\"\n def start_link(options \\\\ []) do\n GenServer.start_link(__MODULE__, [options], name: __MODULE__)\n end\n\n def stop, do: GenServer.cast(__MODULE__, :stop)\n\n # Private Functions\n\n def init(options) do\n {:ok, callee} = RPC.new_peer([Spell.Role.Callee], options)\n\n # `Spell.cast_register` receive the callee and the procedure where it\n # has to be registered\n state = %__MODULE__{callee: callee}\n\n new_register = for {proc, function} <- function_list do\n {:ok, reg_id} = Spell.call_register(callee, proc)\n {reg_id, function}\n end\n |> Enum.into %{}\n\n state = Map.put(state, :register, new_register)\n {:ok, state}\n end\n\n def handle_cast(:stop, state), do: {:stop, :normal, state}\n\n def handle_info({Spell.Peer, pid, %Spell.Message{args: [request, reg_id, _msg, params], type: :invocation}}, (%{callee: callee}) = state) do\n rpc = state.register[reg_id]\n Spell.cast_yield(callee, request, [arguments_kw: %{result: rpc.(params)}])\n {:noreply, state}\n end\n end\n\n # Public Interface\n\n @doc \"\"\"\n Shared helper function for create a new peer configured with `roles` and\n `options`.\n \"\"\"\n def new_peer(roles, options) do\n uri = Keyword.get(options, :uri, Crossbar.uri)\n realm = Keyword.get(options, :realm, Crossbar.get_realm())\n Spell.connect(uri, realm: realm, roles: roles)\n end\nend\n\ndefmodule Math do\n @doc \"\"\"\n Module to provide some simple mathematic operations\n \"\"\"\n def sum(list), do: sum(list, 0)\n def sum([], acc), do: acc\n def sum(int, acc) when is_integer(int), do: sum([int], acc)\n def sum([h | t] = list, acc) when is_list(list) and is_integer(h), do: sum(t, acc + h)\n def sum([h | t] = list, acc) when is_list(list), do: sum(t, acc + String.to_integer(h))\n\n def multiply(list), do: multiply(list, 1)\n def multiply([], acc), do: acc\n def multiply(int, acc) when is_integer(int), do: multiply([int], acc)\n def multiply([h | t] = list, acc) when is_list(list) and is_integer(h), do: multiply(t, acc * h)\n def multiply([h | t] = list, acc) when is_list(list), do: multiply(t, acc * String.to_integer(h))\nend\n\nalias RPC.Callee\nalias RPC.Caller\nrequire Logger\n\nLogger.info(\"Starting the Crossbar.io test server...\")\n\n# Start the crossbar testing server\n{:ok, _pid} = Crossbar.start()\n\n# Register callee to the WAMP router\n{:ok, _callee} = Callee.start_link()\n\n# Call the remote procedure passing the agruments\n{:ok, _caller} = Caller.start_link(\"spell.math.sum\", [arguments: [1, 2, 3]])\n{:ok, _caller} = Caller.start_link(\"spell.math.multiply\", [arguments: [10, 4]])\n:timer.sleep(10000)\n\nLogger.info(\"DONE... Stopping Crossbar.io server\")\n\n# Stop the callee\n:ok = Callee.stop()\n# Stop the crossbar.io testing server\n:ok = Crossbar.stop()\n\nLogger.info(\"DONE.\")\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"f89e99265b1422b51783d7840c00fbae055dd3ca","subject":"Use Enum.chuck instead of Enum.chunk_every","message":"Use Enum.chuck instead of Enum.chunk_every\n","repos":"xou\/elixlsx","old_file":"example.exs","new_file":"example.exs","new_contents":"#!\/usr\/bin\/elixir -pa _build\/dev\/lib\/elixlsx\/ebin\/\n\nrequire Elixlsx\n\nalias Elixlsx.Sheet\nalias Elixlsx.Workbook\n\n\nsheet1 = Sheet.with_name(\"First\")\n# Set cell B2 to the string \"Hi\". :)\n |> Sheet.set_cell(\"B2\", \"Hi\")\n# Optionally, set font properties:\n |> Sheet.set_cell(\"B3\", \"Hello World\", bold: true, underline: true, color: \"#ffaa00\")\n# Set background color\n |> Sheet.set_cell(\"B4\", \"Background color \\\\o\/\", bg_color: \"#ffff00\")\n# Number formatting can be applied like this:\n |> Sheet.set_cell(\"A1\", 123.4, num_format: \"0.00\")\n# Two date formats are accepted, erlang's :calendar format and UNIX timestamps.\n# the datetime: true parameter automatically applies conversion to Excels internal format.\n |> Sheet.set_cell(\"A2\", {{2015, 11, 30}, {21, 20, 38}}, datetime: true)\n |> Sheet.set_cell(\"A3\", 1448882362, datetime: true)\n# datetime: true ouputs date and time, yyyymmdd limits the output to just the date\n |> Sheet.set_cell(\"A4\", 1448882362, yyyymmdd: true)\n# make some room in the first column, otherwise the date will only show up as ###\n |> Sheet.set_col_width(\"A\", 18.0)\n# Cell borders\n |> Sheet.set_cell(\"A5\", \"Double border\", border: [bottom: [style: :double, color: \"#cc3311\"]])\n# Formatting with empty content\n |> Sheet.set_cell(\"A5\", :empty, bg_color: \"#ffff00\", border: [bottom: [style: :double, color: \"#cc3311\"]])\n# Boolean value\n |> Sheet.set_cell(\"A6\", true)\n# Formula\n |> Sheet.set_cell(\"E1\", 1.2, num_format: \"0.00\")\n |> Sheet.set_cell(\"E2\", 2, num_format: \"0.00\")\n |> Sheet.set_cell(\"E3\", 3.5, num_format: \"0.00\")\n |> Sheet.set_cell(\"E4\", 4, num_format: \"0.00\")\n |> Sheet.set_cell(\"E5\", 5, num_format: \"0.00\")\n # Show `value` if there is no calculated value (example: Mac OS preview):\n |> Sheet.set_cell(\"E6\", {:formula, \"SUM(E1:E5)\", value: 15.70}, num_format: \"0.00\", bold: true)\n |> Sheet.set_cell(\"F1\", {:formula, \"NOW()\"}, num_format: \"yyyy-mm-dd hh:MM:ss\")\n |> Sheet.set_col_width(\"F\", 18.0)\n\nworkbook = %Workbook{sheets: [sheet1]}\n\n# it is also possible to add a custom \"created\" date to workbook, otherwise,\n# the current date is used.\n\nworkbook = %Workbook{workbook | datetime: \"2015-12-01T13:40:59Z\"}\n\n# It is also possible to create a sheet as a list of rows:\nsheet2 = %Sheet{name: \"Third\", rows: [[1,2,3,4,5],\n [1,2],\n [\"increased row height\"],\n [\"hello\", \"world\"]]}\n |> Sheet.set_row_height(3, 40)\n\nworkbook = Workbook.append_sheet(workbook, sheet2)\n\n# For the list of rows approach, cells with properties can be encoded by using a\n# list with the value at the head and the properties in the tail:\nsheet3 = %Sheet{name: \"Second\", rows:\n [[1,2,3],\n [4,5,6, [\"goat\", bold: true]],\n [[\"Bold\", bold: true], [\"Italic\", italic: true], [\"Underline\", underline: true], [\"Strike!\", strike: true],\n [\"Large\", size: 22]],\n # wrap_text makes text wrap, but it does not increase the row height\n # (see row_heights below).\n [[\"This is a cell with quite a bit of text.\", wrap_text: true],\n # make some vertical alignment\n [\"Top\", align_vertical: :top],\n # also set font name\n [\"Middle\", align_vertical: :center, font: \"Courier New\"],\n [\"Bottom\", align_vertical: :bottom]],\n# Unicode should work as well:\n [[\"M\u00fc\u0142ti\", bold: true, italic: true, underline: true, strike: true]],\n# Change horizontal alignment\n [[\"left\", align_horizontal: :left], [\"right\", align_horizontal: :right],\n [\"center\", align_horizontal: :center], [\"justify\", align_horizontal: :justify],\n [\"general\", align_horizontal: :general], [\"fill\", align_horizontal: :fill]]\n ],\n row_heights: %{4 => 60}}\n\n# Insert sheet3 as the second sheet:\nworkbook = Workbook.insert_sheet(workbook, sheet3, 1)\n\n# It is possible to merge blocks of cells. The top-left cells' value will be retained\n# in the block, all others will be dropped.\nsheet4 = %Sheet{name: \"Merged Cells\",\n rows: List.duplicate([\"A\", \"B\", \"C\", \"D\", \"E\"], 5),\n merge_cells: [{\"A1\", \"A3\"}, {\"C1\", \"E1\"}, {\"C3\", \"E5\"}]}\n\n# You can set pane freeze.\nsheet4\n|> Sheet.set_pane_freeze(1, 1) # first row and first column frozen\n|> Sheet.set_pane_freeze(2, 1) # first and second row and first column frozen\n|> Sheet.remove_pane_freeze # unfreeze pane\n\nsheet5 = %Sheet{name: \"No gridlines shown\", show_grid_lines: false}\n |> Sheet.set_at(0, 0, \"Just this cell\")\n\n# Rows\/columns can be grouped.\nsheet6 = %Sheet{\n name: \"Row and Column Groups\",\n rows: 1..100 |> Enum.chunk(10),\n group_rows: [{2..3, collapsed: true}, 6..7], # collapse and hide rows 2 to 3\n group_cols: [2..9, 2..5] # nest\n}\n|> Sheet.group_cols(\"C\", \"D\") # nest further\n\nWorkbook.append_sheet(workbook, sheet4)\n|> Workbook.append_sheet(sheet5)\n|> Workbook.append_sheet(sheet6)\n|> Elixlsx.write_to(\"example.xlsx\")\n","old_contents":"#!\/usr\/bin\/elixir -pa _build\/dev\/lib\/elixlsx\/ebin\/\n\nrequire Elixlsx\n\nalias Elixlsx.Sheet\nalias Elixlsx.Workbook\n\n\nsheet1 = Sheet.with_name(\"First\")\n# Set cell B2 to the string \"Hi\". :)\n |> Sheet.set_cell(\"B2\", \"Hi\")\n# Optionally, set font properties:\n |> Sheet.set_cell(\"B3\", \"Hello World\", bold: true, underline: true, color: \"#ffaa00\")\n# Set background color\n |> Sheet.set_cell(\"B4\", \"Background color \\\\o\/\", bg_color: \"#ffff00\")\n# Number formatting can be applied like this:\n |> Sheet.set_cell(\"A1\", 123.4, num_format: \"0.00\")\n# Two date formats are accepted, erlang's :calendar format and UNIX timestamps.\n# the datetime: true parameter automatically applies conversion to Excels internal format.\n |> Sheet.set_cell(\"A2\", {{2015, 11, 30}, {21, 20, 38}}, datetime: true)\n |> Sheet.set_cell(\"A3\", 1448882362, datetime: true)\n# datetime: true ouputs date and time, yyyymmdd limits the output to just the date\n |> Sheet.set_cell(\"A4\", 1448882362, yyyymmdd: true)\n# make some room in the first column, otherwise the date will only show up as ###\n |> Sheet.set_col_width(\"A\", 18.0)\n# Cell borders\n |> Sheet.set_cell(\"A5\", \"Double border\", border: [bottom: [style: :double, color: \"#cc3311\"]])\n# Formatting with empty content\n |> Sheet.set_cell(\"A5\", :empty, bg_color: \"#ffff00\", border: [bottom: [style: :double, color: \"#cc3311\"]])\n# Boolean value\n |> Sheet.set_cell(\"A6\", true)\n# Formula\n |> Sheet.set_cell(\"E1\", 1.2, num_format: \"0.00\")\n |> Sheet.set_cell(\"E2\", 2, num_format: \"0.00\")\n |> Sheet.set_cell(\"E3\", 3.5, num_format: \"0.00\")\n |> Sheet.set_cell(\"E4\", 4, num_format: \"0.00\")\n |> Sheet.set_cell(\"E5\", 5, num_format: \"0.00\")\n # Show `value` if there is no calculated value (example: Mac OS preview):\n |> Sheet.set_cell(\"E6\", {:formula, \"SUM(E1:E5)\", value: 15.70}, num_format: \"0.00\", bold: true)\n |> Sheet.set_cell(\"F1\", {:formula, \"NOW()\"}, num_format: \"yyyy-mm-dd hh:MM:ss\")\n |> Sheet.set_col_width(\"F\", 18.0)\n\nworkbook = %Workbook{sheets: [sheet1]}\n\n# it is also possible to add a custom \"created\" date to workbook, otherwise,\n# the current date is used.\n\nworkbook = %Workbook{workbook | datetime: \"2015-12-01T13:40:59Z\"}\n\n# It is also possible to create a sheet as a list of rows:\nsheet2 = %Sheet{name: \"Third\", rows: [[1,2,3,4,5],\n [1,2],\n [\"increased row height\"],\n [\"hello\", \"world\"]]}\n |> Sheet.set_row_height(3, 40)\n\nworkbook = Workbook.append_sheet(workbook, sheet2)\n\n# For the list of rows approach, cells with properties can be encoded by using a\n# list with the value at the head and the properties in the tail:\nsheet3 = %Sheet{name: \"Second\", rows:\n [[1,2,3],\n [4,5,6, [\"goat\", bold: true]],\n [[\"Bold\", bold: true], [\"Italic\", italic: true], [\"Underline\", underline: true], [\"Strike!\", strike: true],\n [\"Large\", size: 22]],\n # wrap_text makes text wrap, but it does not increase the row height\n # (see row_heights below).\n [[\"This is a cell with quite a bit of text.\", wrap_text: true],\n # make some vertical alignment\n [\"Top\", align_vertical: :top],\n # also set font name\n [\"Middle\", align_vertical: :center, font: \"Courier New\"],\n [\"Bottom\", align_vertical: :bottom]],\n# Unicode should work as well:\n [[\"M\u00fc\u0142ti\", bold: true, italic: true, underline: true, strike: true]],\n# Change horizontal alignment\n [[\"left\", align_horizontal: :left], [\"right\", align_horizontal: :right],\n [\"center\", align_horizontal: :center], [\"justify\", align_horizontal: :justify],\n [\"general\", align_horizontal: :general], [\"fill\", align_horizontal: :fill]]\n ],\n row_heights: %{4 => 60}}\n\n# Insert sheet3 as the second sheet:\nworkbook = Workbook.insert_sheet(workbook, sheet3, 1)\n\n# It is possible to merge blocks of cells. The top-left cells' value will be retained\n# in the block, all others will be dropped.\nsheet4 = %Sheet{name: \"Merged Cells\",\n rows: List.duplicate([\"A\", \"B\", \"C\", \"D\", \"E\"], 5),\n merge_cells: [{\"A1\", \"A3\"}, {\"C1\", \"E1\"}, {\"C3\", \"E5\"}]}\n\n# You can set pane freeze.\nsheet4\n|> Sheet.set_pane_freeze(1, 1) # first row and first column frozen\n|> Sheet.set_pane_freeze(2, 1) # first and second row and first column frozen\n|> Sheet.remove_pane_freeze # unfreeze pane\n\nsheet5 = %Sheet{name: \"No gridlines shown\", show_grid_lines: false}\n |> Sheet.set_at(0, 0, \"Just this cell\")\n\n# Rows\/columns can be grouped.\nsheet6 = %Sheet{\n name: \"Row and Column Groups\",\n rows: 1..100 |> Enum.chunk_every(10),\n group_rows: [{2..3, collapsed: true}, 6..7], # collapse and hide rows 2 to 3\n group_cols: [2..9, 2..5] # nest\n}\n|> Sheet.group_cols(\"C\", \"D\") # nest further\n\nWorkbook.append_sheet(workbook, sheet4)\n|> Workbook.append_sheet(sheet5)\n|> Workbook.append_sheet(sheet6)\n|> Elixlsx.write_to(\"example.xlsx\")\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"0a8ac6822069f70424261bfcb96bd6d1b2baa02e","subject":"Uncomment out insert functions in seeds\/initial_data to populate DB.","message":"Uncomment out insert functions in seeds\/initial_data to populate DB.\n","repos":"ParkisonsUK-fuse\/what3things,ParkisonsUK-fuse\/what3things","old_file":"priv\/repo\/seeds\/initial_data.exs","new_file":"priv\/repo\/seeds\/initial_data.exs","new_contents":"# Script for populating the database. You can run it as:\n#\n# mix run priv\/repo\/seeds.exs\n#\n# Inside the script, you can read and write to any of your\n# repositories directly:\n#\n# What3things.Repo.insert!(%What3things.SomeModel{})\n#\n# We recommend using the bang functions (`insert!`, `update!`\n# and so on) as they will fail if something goes wrong.\n\nalias What3things.{Service, Quote, Repo, Weight}\n\nquotes =\n [\"I\u2019d feel most comfortable if support staff came to see me at home.\",\n \"I\u2019ll just wait and see what information and support I\u2019m offered.\",\n \"I want to say what I feel without anyone knowing who I am, but know that someone will still be there listening and supporting me.\",\n \"I want to find somewhere local where I can meet other people with Parkinson\u2019s and share my experiences.\",\n \"I don\u2019t want to wait for someone to help me, I want to go out and help myself.\",\n \"There\u2019s something specific I want to know about Parkinson\u2019s and how it\u2019s going to affect me.\",\n \"I want to have a private one-to-one quite soon to talk things through\",\n \"I\u2019m happy chatting on forums and social media.\",\n \"I want to understand my condition so I can plan for the long term.\"]\n |> Enum.map(fn(q) -> %{body: q} end)\n\n\nservices =\n [\"Peer Support Service\",\n \"Forum\",\n \"Groups\",\n \"Parkinson's Nurse\",\n \"Self-management programme\",\n \"Parkinson's Local Advisor\",\n \"First Steps\",\n \"Helpline\",\n \"Facebook\",\n \"Newly diagnosed landing page\",\n \"Early onset web page\",\n \"Publications\"]\n |> Enum.map(fn(s) -> %{title: s, body: \"lorem ipsum\", cta: \"lorem\", url: \"www.#{s |> String.replace(\" \", \"\")}.com\"} end)\n\n all_weights =\n [[0,0, 0, 0.5, 0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0.25, 0, 0.5, 0, 0, 0.25, 0, 0],\n [0.5, 1, 0, 0, 0, 0, 0, 0.5, 0.25, 0, 0, 0],\n [0, 0, 1, 0, 0.25, 0, 0.5, 0, 0, 0, 0, 0],\n [0, 0, 0.25, 0, 0, 0, 0, 0, 0.25, 1, 0.5, 0.5],\n [0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0.25, 0, 1],\n [0.25, 0, 0, 0.25, 0, 0.5, 0, 1, 0, 0, 0, 0],\n [0, 0.75, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0.25, 0.5, 0.5, 0, 0, 0, 0.25, 0.25, 0.5]]\n |> Enum.map(fn(x) -> Enum.map(x, fn(y) -> y * 1.0 end) end)\n\nRepo.insert_all(Quote, quotes)\nRepo.insert_all(Service, services)\n\nquotes = Repo.all(Quote)\nservices = Repo.all(Service)\n\nservices_weight_zip = for weights <- all_weights do\n services\n |> Enum.map(fn(x) -> %{service_id: x.id} end)\n |> Enum.zip(weights)\nend\n\nzip_all =\n quotes\n |> Enum.map(fn(x) -> %{quote_id: x.id} end)\n |> Enum.zip(services_weight_zip)\n |> Enum.map(fn({q, s_weights}) -> Enum.map(s_weights, fn({s, w}) -> %{service_id: s.service_id, quote_id: q.quote_id, weight: w} end) end)\n |> List.flatten()\n\nRepo.insert_all(Weight, zip_all)\n","old_contents":"# Script for populating the database. You can run it as:\n#\n# mix run priv\/repo\/seeds.exs\n#\n# Inside the script, you can read and write to any of your\n# repositories directly:\n#\n# What3things.Repo.insert!(%What3things.SomeModel{})\n#\n# We recommend using the bang functions (`insert!`, `update!`\n# and so on) as they will fail if something goes wrong.\n\nalias What3things.{Service, Quote, Repo, Weight}\n\nquotes =\n [\"I\u2019d feel most comfortable if support staff came to see me at home.\",\n \"I\u2019ll just wait and see what information and support I\u2019m offered.\",\n \"I want to say what I feel without anyone knowing who I am, but know that someone will still be there listening and supporting me.\",\n \"I want to find somewhere local where I can meet other people with Parkinson\u2019s and share my experiences.\",\n \"I don\u2019t want to wait for someone to help me, I want to go out and help myself.\",\n \"There\u2019s something specific I want to know about Parkinson\u2019s and how it\u2019s going to affect me.\",\n \"I want to have a private one-to-one quite soon to talk things through\",\n \"I\u2019m happy chatting on forums and social media.\",\n \"I want to understand my condition so I can plan for the long term.\"]\n |> Enum.map(fn(q) -> %{body: q} end)\n\n\nservices =\n [\"Peer Support Service\",\n \"Forum\",\n \"Groups\",\n \"Parkinson's Nurse\",\n \"Self-management programme\",\n \"Parkinson's Local Advisor\",\n \"First Steps\",\n \"Helpline\",\n \"Facebook\",\n \"Newly diagnosed landing page\",\n \"Early onset web page\",\n \"Publications\"]\n |> Enum.map(fn(s) -> %{title: s, body: \"lorem ipsum\", cta: \"lorem\", url: \"www.#{s |> String.replace(\" \", \"\")}.com\"} end)\n\n all_weights =\n [[0,0, 0, 0.5, 0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0.25, 0, 0.5, 0, 0, 0.25, 0, 0],\n [0.5, 1, 0, 0, 0, 0, 0, 0.5, 0.25, 0, 0, 0],\n [0, 0, 1, 0, 0.25, 0, 0.5, 0, 0, 0, 0, 0],\n [0, 0, 0.25, 0, 0, 0, 0, 0, 0.25, 1, 0.5, 0.5],\n [0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0.25, 0, 1],\n [0.25, 0, 0, 0.25, 0, 0.5, 0, 1, 0, 0, 0, 0],\n [0, 0.75, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0.25, 0.5, 0.5, 0, 0, 0, 0.25, 0.25, 0.5]]\n |> Enum.map(fn(x) -> Enum.map(x, fn(y) -> y * 1.0 end) end)\n\n# Repo.insert_all(Quote, quotes)\n# Repo.insert_all(Service, services)\n\nquotes = Repo.all(Quote)\nservices = Repo.all(Service)\n\nservices_weight_zip = for weights <- all_weights do\n services\n |> Enum.map(fn(x) -> %{service_id: x.id} end)\n |> Enum.zip(weights)\nend\n\nzip_all =\n quotes\n |> Enum.map(fn(x) -> %{quote_id: x.id} end)\n |> Enum.zip(services_weight_zip)\n |> Enum.map(fn({q, s_weights}) -> Enum.map(s_weights, fn({s, w}) -> %{service_id: s.service_id, quote_id: q.quote_id, weight: w} end) end)\n |> List.flatten()\n\n# Repo.insert_all(Weight, zip_all)\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"c8813e042a9d9168e7c8e5890c246986b01d6632","subject":"Add debug symbols to `:dev` releases","message":"Add debug symbols to `:dev` releases\n","repos":"FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os","old_file":"farmbot_os\/mix.exs","new_file":"farmbot_os\/mix.exs","new_contents":"defmodule FarmbotOS.MixProject do\n use Mix.Project\n\n @all_targets [:rpi3, :rpi0, :rpi]\n @version Path.join([__DIR__, \"..\", \"VERSION\"]) |> File.read!() |> String.trim()\n @branch System.cmd(\"git\", ~w\"rev-parse --abbrev-ref HEAD\") |> elem(0) |> String.trim()\n @commit System.cmd(\"git\", ~w\"rev-parse --verify HEAD\") |> elem(0) |> String.trim()\n System.put_env(\"NERVES_FW_VCS_IDENTIFIER\", @commit)\n System.put_env(\"NERVES_FW_MISC\", @branch)\n @elixir_version Path.join([__DIR__, \"..\", \"ELIXIR_VERSION\"]) |> File.read!() |> String.trim()\n\n System.put_env(\"NERVES_FW_VCS_IDENTIFIER\", @commit)\n\n def project do\n [\n app: :farmbot,\n elixir: @elixir_version,\n version: @version,\n branch: @branch,\n commit: @commit,\n releases: [{:farmbot, release()}],\n elixirc_options: [warnings_as_errors: true, ignore_module_conflict: true],\n archives: [nerves_bootstrap: \"~> 1.6\"],\n start_permanent: Mix.env() == :prod,\n build_embedded: false,\n compilers: [:elixir_make | Mix.compilers()],\n aliases: [loadconfig: [&bootstrap\/1]],\n elixirc_paths: elixirc_paths(Mix.env(), Mix.target()),\n deps_path: \"deps\/#{Mix.target()}\",\n build_path: \"_build\/#{Mix.target()}\",\n test_coverage: [tool: ExCoveralls],\n preferred_cli_target: [run: :host, test: :host],\n preferred_cli_env: [\n coveralls: :test,\n \"coveralls.detail\": :test,\n \"coveralls.post\": :test,\n \"coveralls.html\": :test\n ],\n deps: deps()\n ]\n end\n\n def release do\n [\n overwrite: true,\n cookie: \"democookie\",\n include_erts: &Nerves.Release.erts\/0,\n strip_beams: Mix.env() == :prod,\n steps: [&Nerves.Release.init\/1, :assemble]\n ]\n end\n\n # Starting nerves_bootstrap adds the required aliases to Mix.Project.config()\n # Aliases are only added if MIX_TARGET is set.\n def bootstrap(args) do\n Application.start(:nerves_bootstrap)\n Mix.Task.run(\"loadconfig\", args)\n end\n\n # Run \"mix help compile.app\" to learn about applications.\n def application do\n [\n mod: {FarmbotOS, []},\n extra_applications: [:logger, :runtime_tools, :eex]\n ]\n end\n\n # Run \"mix help deps\" to learn about dependencies.\n defp deps do\n [\n # Farmbot stuff\n {:farmbot_core, path: \"..\/farmbot_core\", env: Mix.env()},\n {:farmbot_ext, path: \"..\/farmbot_ext\", env: Mix.env()},\n\n # Configurator stuff\n {:cors_plug, \"~> 2.0\"},\n {:plug_cowboy, \"~> 2.0\"},\n {:phoenix_html, \"~> 2.13\"},\n\n # Nerves stuff.\n {:nerves, \"~> 1.5\", runtime: false},\n {:nerves_hub_cli, \"~> 0.7\", runtime: false},\n {:shoehorn, \"~> 0.6\"},\n {:ring_logger, \"~> 0.8\"},\n\n # Host\/test only dependencies.\n {:excoveralls, \"~> 0.10\", only: [:test], targets: [:host]},\n {:dialyxir, \"~> 1.0.0-rc.3\", only: [:dev], targets: [:host], runtime: false},\n {:ex_doc, \"~> 0.19\", only: [:dev], targets: [:host], runtime: false},\n {:elixir_make, \"~> 0.5\", runtime: false},\n\n # Target only deps\n {:nerves_runtime, \"~> 0.10\", targets: @all_targets},\n {:nerves_time, \"~> 0.2\", targets: @all_targets},\n {:nerves_hub, \"~> 0.7\", targets: @all_targets},\n {:mdns, \"~> 1.0\", targets: @all_targets},\n {:nerves_firmware_ssh, \"~> 0.4\", targets: @all_targets},\n {:circuits_gpio, \"~> 0.4\", targets: @all_targets},\n {:toolshed, \"~> 0.2\", targets: @all_targets},\n # {:vintage_net, \"~> 0.3.1\", targets: @all_targets},\n {:vintage_net,\n github: \"nerves-networking\/vintage_net\", tag: \"master\", targets: @all_targets},\n {:busybox, \"~> 0.1.2\", targets: @all_targets},\n {:farmbot_system_rpi3, \"1.8.0-farmbot.2\", runtime: false, targets: :rpi3},\n {:farmbot_system_rpi0, \"1.8.0-farmbot.0\", runtime: false, targets: :rpi0},\n {:farmbot_system_rpi, \"1.8.0-farmbot.0\", runtime: false, targets: :rpi}\n ]\n end\n\n defp elixirc_paths(:test, :host) do\n [\".\/lib\", \".\/platform\/host\", \".\/test\/support\"]\n end\n\n defp elixirc_paths(_, :host) do\n [\".\/lib\", \".\/platform\/host\"]\n end\n\n defp elixirc_paths(_env, _target) do\n [\".\/lib\", \".\/platform\/target\"]\n end\nend\n","old_contents":"defmodule FarmbotOS.MixProject do\n use Mix.Project\n\n @all_targets [:rpi3, :rpi0, :rpi]\n @version Path.join([__DIR__, \"..\", \"VERSION\"]) |> File.read!() |> String.trim()\n @branch System.cmd(\"git\", ~w\"rev-parse --abbrev-ref HEAD\") |> elem(0) |> String.trim()\n @commit System.cmd(\"git\", ~w\"rev-parse --verify HEAD\") |> elem(0) |> String.trim()\n System.put_env(\"NERVES_FW_VCS_IDENTIFIER\", @commit)\n System.put_env(\"NERVES_FW_MISC\", @branch)\n @elixir_version Path.join([__DIR__, \"..\", \"ELIXIR_VERSION\"]) |> File.read!() |> String.trim()\n\n System.put_env(\"NERVES_FW_VCS_IDENTIFIER\", @commit)\n\n def project do\n [\n app: :farmbot,\n elixir: @elixir_version,\n version: @version,\n branch: @branch,\n commit: @commit,\n releases: [{:farmbot, release()}],\n elixirc_options: [warnings_as_errors: true, ignore_module_conflict: true],\n archives: [nerves_bootstrap: \"~> 1.6\"],\n start_permanent: Mix.env() == :prod,\n build_embedded: false,\n compilers: [:elixir_make | Mix.compilers()],\n aliases: [loadconfig: [&bootstrap\/1]],\n elixirc_paths: elixirc_paths(Mix.env(), Mix.target()),\n deps_path: \"deps\/#{Mix.target()}\",\n build_path: \"_build\/#{Mix.target()}\",\n test_coverage: [tool: ExCoveralls],\n preferred_cli_target: [run: :host, test: :host],\n preferred_cli_env: [\n coveralls: :test,\n \"coveralls.detail\": :test,\n \"coveralls.post\": :test,\n \"coveralls.html\": :test\n ],\n deps: deps()\n ]\n end\n\n def release do\n [\n overwrite: true,\n cookie: \"democookie\",\n include_erts: &Nerves.Release.erts\/0,\n steps: [&Nerves.Release.init\/1, :assemble]\n ]\n end\n\n # Starting nerves_bootstrap adds the required aliases to Mix.Project.config()\n # Aliases are only added if MIX_TARGET is set.\n def bootstrap(args) do\n Application.start(:nerves_bootstrap)\n Mix.Task.run(\"loadconfig\", args)\n end\n\n # Run \"mix help compile.app\" to learn about applications.\n def application do\n [\n mod: {FarmbotOS, []},\n extra_applications: [:logger, :runtime_tools, :eex]\n ]\n end\n\n # Run \"mix help deps\" to learn about dependencies.\n defp deps do\n [\n # Farmbot stuff\n {:farmbot_core, path: \"..\/farmbot_core\", env: Mix.env()},\n {:farmbot_ext, path: \"..\/farmbot_ext\", env: Mix.env()},\n\n # Configurator stuff\n {:cors_plug, \"~> 2.0\"},\n {:plug_cowboy, \"~> 2.0\"},\n {:phoenix_html, \"~> 2.13\"},\n\n # Nerves stuff.\n {:nerves, \"~> 1.5\", runtime: false},\n {:nerves_hub_cli, \"~> 0.7\", runtime: false},\n {:shoehorn, \"~> 0.6\"},\n {:ring_logger, \"~> 0.8\"},\n\n # Host\/test only dependencies.\n {:excoveralls, \"~> 0.10\", only: [:test], targets: [:host]},\n {:dialyxir, \"~> 1.0.0-rc.3\", only: [:dev], targets: [:host], runtime: false},\n {:ex_doc, \"~> 0.19\", only: [:dev], targets: [:host], runtime: false},\n {:elixir_make, \"~> 0.5\", runtime: false},\n\n # Target only deps\n {:nerves_runtime, \"~> 0.10\", targets: @all_targets},\n {:nerves_time, \"~> 0.2\", targets: @all_targets},\n {:nerves_hub, \"~> 0.7\", targets: @all_targets},\n {:mdns, \"~> 1.0\", targets: @all_targets},\n {:nerves_firmware_ssh, \"~> 0.4\", targets: @all_targets},\n {:circuits_gpio, \"~> 0.4\", targets: @all_targets},\n {:toolshed, \"~> 0.2\", targets: @all_targets},\n # {:vintage_net, \"~> 0.3.1\", targets: @all_targets},\n {:vintage_net,\n github: \"nerves-networking\/vintage_net\", tag: \"master\", targets: @all_targets},\n {:busybox, \"~> 0.1.2\", targets: @all_targets},\n {:farmbot_system_rpi3, \"1.8.0-farmbot.2\", runtime: false, targets: :rpi3},\n {:farmbot_system_rpi0, \"1.8.0-farmbot.0\", runtime: false, targets: :rpi0},\n {:farmbot_system_rpi, \"1.8.0-farmbot.0\", runtime: false, targets: :rpi}\n ]\n end\n\n defp elixirc_paths(:test, :host) do\n [\".\/lib\", \".\/platform\/host\", \".\/test\/support\"]\n end\n\n defp elixirc_paths(_, :host) do\n [\".\/lib\", \".\/platform\/host\"]\n end\n\n defp elixirc_paths(_env, _target) do\n [\".\/lib\", \".\/platform\/target\"]\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"fe282b0678e5ce91ab0bb56f41644227dae843b4","subject":"Use secret.exs","message":"Use secret.exs\n","repos":"tsurupin\/job_search,tsurupin\/job_search","old_file":"apps\/customer\/config\/prod.exs","new_file":"apps\/customer\/config\/prod.exs","new_contents":"use Mix.Config\n\n# For production, we configure the host to read the PORT\n# from the system environment. Therefore, you will need\n# to set PORT=80 before running your server.\n#\n# You should also configure the url host to something\n# meaningful, we use this information when generating URLs.\n#\n# Finally, we also include the path to a manifest\n# containing the digested version of static files. This\n# manifest is generated by the mix phoenix.digest task\n# which you typically run after static files are built.\n\n# Do not print debug messages in production\nconfig :logger, level: :info\n\nconfig :exsentry,\n otp_app: :customer,\n dsn: \"\"\n\nconfig :quantum,\n cron: [\n es_reindex: [\n schedule: \"0 1 * * *\",\n task: \"Customer.Builders.EsReindex.perform\",\n args: []\n ],\n \"0 0 * * 0\": {Customer.Builder, :perform}\n]\n# ## SSL Support\n#\n# To get SSL working, you will need to add the `https` key\n# to the previous section and set your `:url` port to 443:\n#\n# config :customer, Customer.Endpoint,\n# ...\n# url: [host: \"example.com\", port: 443],\n# https: [port: 443,\n# keyfile: System.get_env(\"SOME_APP_SSL_KEY_PATH\"),\n# certfile: System.get_env(\"SOME_APP_SSL_CERT_PATH\")]\n#\n# Where those two env variables return an absolute path to\n# the key and cert in disk or a relative path inside priv,\n# for example \"priv\/ssl\/server.key\".\n#\n# We also recommend setting `force_ssl`, ensuring no data is\n# ever sent via http, always redirecting to https:\n#\n# config :customer, Customer.Endpoint,\n# force_ssl: [hsts: true]\n#\n# Check `Plug.SSL` for all available options in `force_ssl`.\n\n# ## Using releases\n#\n# If you are doing OTP releases, you need to instruct Phoenix\n# to start the server for all endpoints:\n#\n# config :phoenix, :serve_endpoints, true\n#\n# Alternatively, you can configure exactly which server to\n# start per endpoint:\n#\n# config :customer, Customer.Endpoint, server: true\n#\n\n# Finally import the config\/prod.secret.exs\n# which should be versioned separately.\nimport_config \"prod.secret.exs\"\n","old_contents":"use Mix.Config\n\n# For production, we configure the host to read the PORT\n# from the system environment. Therefore, you will need\n# to set PORT=80 before running your server.\n#\n# You should also configure the url host to something\n# meaningful, we use this information when generating URLs.\n#\n# Finally, we also include the path to a manifest\n# containing the digested version of static files. This\n# manifest is generated by the mix phoenix.digest task\n# which you typically run after static files are built.\nconfig :customer, Customer.Web.Endpoint,\n http: [port: {:system, \"PORT\"}],\n url: [host: \"example.com\", port: 80],\n cache_static_manifest: \"priv\/static\/manifest.json\"\n\n# Do not print debug messages in production\nconfig :logger, level: :info\n\nconfig :exsentry,\n otp_app: :customer,\n dsn: \"\"\n\nconfig :quantum,\n cron: [\n es_reindex: [\n schedule: \"0 1 * * *\",\n task: \"Customer.Builders.EsReindex.perform\",\n args: []\n ],\n \"0 0 * * 0\": {Customer.Builder, :perform}\n]\n# ## SSL Support\n#\n# To get SSL working, you will need to add the `https` key\n# to the previous section and set your `:url` port to 443:\n#\n# config :customer, Customer.Endpoint,\n# ...\n# url: [host: \"example.com\", port: 443],\n# https: [port: 443,\n# keyfile: System.get_env(\"SOME_APP_SSL_KEY_PATH\"),\n# certfile: System.get_env(\"SOME_APP_SSL_CERT_PATH\")]\n#\n# Where those two env variables return an absolute path to\n# the key and cert in disk or a relative path inside priv,\n# for example \"priv\/ssl\/server.key\".\n#\n# We also recommend setting `force_ssl`, ensuring no data is\n# ever sent via http, always redirecting to https:\n#\n# config :customer, Customer.Endpoint,\n# force_ssl: [hsts: true]\n#\n# Check `Plug.SSL` for all available options in `force_ssl`.\n\n# ## Using releases\n#\n# If you are doing OTP releases, you need to instruct Phoenix\n# to start the server for all endpoints:\n#\n# config :phoenix, :serve_endpoints, true\n#\n# Alternatively, you can configure exactly which server to\n# start per endpoint:\n#\n# config :customer, Customer.Endpoint, server: true\n#\n\n# Finally import the config\/prod.secret.exs\n# which should be versioned separately.\n# import_config \"prod.secret.exs\"\n\nconfig :customer, Customer.Web.Endpoint,\n http: [port: 80],\n url: [host: \"localhost\", port: 80],\n secret_key_base: System.get_env(\"SECRET_KEY_BASE\"),\n debug_errors: false,\n server: true\n\n# Configure your database\nconfig :customer, Customer.Repo,\n adapter: Ecto.Adapters.Postgres,\n username: System.get_env(\"DB_USERNAME\"),\n password: System.get_env(\"DB_PASSWORD\"),\n database: System.get_env(\"DB_DATABASE_NAME\"),\n hostname: System.get_env(\"DB_HOSTNAME\"),\n port: System.get_env(\"DB_PORT\") || 5432,\n pool_size: 20\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"ae15ea31de724533a9f54f6697173a0400bff616","subject":"remove","message":"remove\n","repos":"ikeikeikeike\/somequeue,ikeikeikeike\/somequeue,ikeikeikeike\/somequeue,ikeikeikeike\/somequeue,ikeikeikeike\/somequeue","old_file":"exqueue\/web\/jobs\/echo_job.ex","new_file":"exqueue\/web\/jobs\/echo_job.ex","new_contents":"","old_contents":"defmodule ActiveJob.QueueAdapters.SidekiqAdapter.JobWrapper do\n def perform(%{\"job_class\"=>\"EchoJob\", \"queue_name\"=>\"default\", \"arguments\"=>arguments}) do\n IO.inspect(arguments)\n end\n\n def perform(msg) when is_map(msg) do\n IO.inspect(msg)\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"d80c9eeb42b044db82f462546abcd1dd410d7228","subject":"updated explain documentation","message":"updated explain documentation\n","repos":"rrrene\/credo,rrrene\/credo","old_file":"lib\/credo\/check\/warning\/forbidden_module.ex","new_file":"lib\/credo\/check\/warning\/forbidden_module.ex","new_contents":"defmodule Credo.Check.Warning.ForbiddenModule do\n use Credo.Check,\n base_priority: :high,\n category: :warning,\n param_defaults: [modules: []],\n explanations: [\n check: \"\"\"\n Some modules that are included by a package may be hazardous\n if used by your application. Use this check to allow these modules in\n your dependencies but forbid them to be used in your application.\n\n Examples:\n\n The `:ecto_sql` package includes the `Ecto.Adapters.SQL` module,\n but direct usage of the `Ecto.Adapters.SQL.query\/4` function, and related functions, may\n cause issues when using Ecto's dynamic repositories.\n \"\"\",\n params: [modules: \"List of Modules or {Module, \\\"Error message\\\"} Tuples that must not be used.\"]\n ]\n\n alias Credo.Code\n\n @impl Credo.Check\n def run(source_file = %SourceFile{}, params) do\n modules = Params.get(params, :modules, __MODULE__)\n\n Code.prewalk(source_file, &traverse(&1, &2, modules, IssueMeta.for(source_file, params)))\n end\n\n defp traverse(ast = {:__aliases__, meta, modules}, issues, modules_param, issue_meta) do\n module = Module.concat(modules)\n\n forbidden_modules =\n if Keyword.keyword?(modules_param), do: Keyword.keys(modules_param), else: modules_param\n\n if found_module?(forbidden_modules, module) do\n {ast, [issue_for(issue_meta, meta[:line], module, modules_param) | issues]}\n else\n {ast, issues}\n end\n end\n\n defp traverse(ast, issues, _, _), do: {ast, issues}\n\n defp found_module?(forbidden_modules, module)\n when is_list(forbidden_modules) and is_atom(module) do\n Enum.member?(forbidden_modules, module)\n end\n\n defp found_module?(_, _), do: false\n\n defp issue_for(issue_meta, line_no, module, modules_param) do\n trigger = module |> Code.Module.name()\n\n format_issue(\n issue_meta,\n message: message(modules_param, module, \"The `#{trigger}` module is not allowed.\"),\n trigger: trigger,\n line_no: line_no\n )\n end\n\n defp message(modules_param, module, default) do\n with true <- Keyword.keyword?(modules_param),\n value when not is_nil(value) <- Keyword.get(modules_param, module) do\n value\n else\n _ -> default\n end\n end\nend\n","old_contents":"defmodule Credo.Check.Warning.ForbiddenModule do\n use Credo.Check,\n base_priority: :high,\n category: :warning,\n param_defaults: [modules: []],\n explanations: [\n check: \"\"\"\n Some modules that are included by a package may be hazardous\n if used by your application. Use this check to allow these modules in\n your dependencies but forbid them to be used in your application.\n\n Examples:\n\n The `:ecto_sql` package includes the `Ecto.Adapters.SQL` module,\n but direct usage of the `Ecto.Adapters.SQL.query\/4` function, and related functions, may\n cause issues when using Ecto's dynamic repositories.\n \"\"\",\n params: [modules: \"Modules that must not be used.\"]\n ]\n\n alias Credo.Code\n\n @impl Credo.Check\n def run(source_file = %SourceFile{}, params) do\n modules = Params.get(params, :modules, __MODULE__)\n\n Code.prewalk(source_file, &traverse(&1, &2, modules, IssueMeta.for(source_file, params)))\n end\n\n defp traverse(ast = {:__aliases__, meta, modules}, issues, modules_param, issue_meta) do\n module = Module.concat(modules)\n\n forbidden_modules =\n if Keyword.keyword?(modules_param), do: Keyword.keys(modules_param), else: modules_param\n\n if found_module?(forbidden_modules, module) do\n {ast, [issue_for(issue_meta, meta[:line], module, modules_param) | issues]}\n else\n {ast, issues}\n end\n end\n\n defp traverse(ast, issues, _, _), do: {ast, issues}\n\n defp found_module?(forbidden_modules, module)\n when is_list(forbidden_modules) and is_atom(module) do\n Enum.member?(forbidden_modules, module)\n end\n\n defp found_module?(_, _), do: false\n\n defp issue_for(issue_meta, line_no, module, forbidden_modules) do\n trigger = module |> Code.Module.name()\n\n format_issue(\n issue_meta,\n message: message(forbidden_modules, module, \"The `#{trigger}` module is not allowed.\"),\n trigger: trigger,\n line_no: line_no\n )\n end\n\n defp message(forbidden_modules, module, default) do\n with true <- Keyword.keyword?(forbidden_modules),\n value when not is_nil(value) <- Keyword.get(forbidden_modules, module) do\n value\n else\n _ -> default\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"194bd60d6a62287324adf747c4d3ba6bc73d86a1","subject":"improve lookback db stage","message":"improve lookback db stage\n","repos":"cyberpunk-ventures\/glasnost,cyberpunk-ventures\/glasnost,cyberpunk-ventures\/glasnost","old_file":"lib\/glasnost\/blockchain\/lookback_db_sync.ex","new_file":"lib\/glasnost\/blockchain\/lookback_db_sync.ex","new_contents":"defmodule Glasnost.Stage.LookbackBlocks do\n use GenStage\n alias Glasnost.Repo\n require Logger\n @blocks_per_tick 5\n @lookback_max_blocks 201_600\n\n def start_link(args, options) do\n GenStage.start_link(__MODULE__, args, options)\n end\n\n def init(%Glasnost.AgentConfig{} = config) do\n Logger.info(\"LookbackBlocks producer is initializing...\")\n {:ok, %{head_block_number: head_block}} = config.client.get_dynamic_global_properties\n\n config = config\n |> Map.put_new(:starting_block, head_block)\n |> Map.put_new(:current_block, head_block)\n Process.send_after(self(), :next_blocks, 5_000)\n {:producer, config, dispatcher: GenStage.BroadcastDispatcher, buffer_size: 100_000}\n end\n\n def handle_demand(demand, state) do\n {:noreply, [], state}\n end\n\n def handle_info(:next_blocks, state) do\n import Ecto.Query\n Logger.info(\"Starting to import blocks from #{state.current_block}\")\n cur_block = state.current_block\n start_block = state.starting_block\n event_mod = Module.concat([state.client, Event])\n tasks = for height <- cur_block..cur_block - @blocks_per_tick do\n Task.async(fn ->\n state.client.get_block(height)\n end)\n end\n blocks = Task.yield_many(tasks, 10_000)\n blocks = for {_, {:ok, {:ok, block}}} <- blocks do\n struct(event_mod, %{data: block, metadata: %{}})\n end\n if cur_block > start_block - @lookback_max_blocks do\n Process.send_after(self(), :next_blocks, 3_000)\n state = put_in(state.current_block, cur_block - @blocks_per_tick)\n else\n Logger.info(\"Lookbacks stage finished extracting past blocks...\")\n end\n {:noreply, blocks, state}\n end\n\nend\n","old_contents":"defmodule Glasnost.Stage.LookbackBlocks do\n use GenStage\n alias Glasnost.Repo\n require Logger\n @blocks_per_tick 5\n\n def start_link(args, options) do\n GenStage.start_link(__MODULE__, args, options)\n end\n\n def init(%Glasnost.AgentConfig{} = config) do\n Logger.info(\"LookbackBlocks producer is initializing...\")\n {:ok, %{head_block_number: head_block}} = config.client.get_dynamic_global_properties\n config = Map.put_new(config, :starting_block, head_block)\n config = Map.put_new(config, :current_block, head_block)\n Process.send_after(self(), :next_blocks, 5_000)\n {:producer, config, dispatcher: GenStage.BroadcastDispatcher, buffer_size: 100_000}\n end\n\n def handle_demand(demand, state) do\n {:noreply, [], state}\n end\n\n def handle_info(:next_blocks, state) do\n import Ecto.Query\n Logger.info(\"Starting to import blocks from #{state.current_block}\")\n cur_block = state.current_block\n tasks = for height <- cur_block..cur_block - @blocks_per_tick do\n Task.async(fn ->\n {:ok, block} = state.client.get_block(height)\n block\n end)\n end\n blocks = Task.yield_many(tasks, 10_000)\n blocks = for {_, {:ok, block}} <- blocks do\n struct(Golos.Event, %{data: block, metadata: %{}})\n end\n Process.send_after(self(), :next_blocks, 3_000)\n state = put_in(state.current_block, state.current_block - @blocks_per_tick)\n {:noreply, blocks, state}\n end\n\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"4952fab247db12ef797b7fc5f4371a093bfc328b","subject":"Set the user and group in the entrypoint script.","message":"Set the user and group in the entrypoint script.\n","repos":"nerves-project\/nerves,nerves-project\/nerves","old_file":"lib\/nerves\/artifact\/build_runners\/docker.ex","new_file":"lib\/nerves\/artifact\/build_runners\/docker.ex","new_contents":"defmodule Nerves.Artifact.BuildRunners.Docker do\n @moduledoc \"\"\"\n Produce an artifact for a package using Docker.\n\n The Nerves Docker artifact build_runner will use docker to create the artifact\n for the package. The output in Mix will be limited to the headlines from the\n process and the full build log can be found in the file `build.log` located\n root of the package path.\n\n ## Images\n\n Docker containers will be created based off the image that is loaded.\n By default, containers will use the default image\n `nervesproject\/nerves_system_br:latest`. Sometimes additional host tools\n are required to build a package. Therefore, packages can provide their own\n images by specifying it in the package config under `:build_runner_config`.\n the file is specified as a tuple `{\"path\/to\/Dockerfile\", tag_name}`.\n\n Example:\n\n build_runner_config: [\n docker: {\"Dockerfile\", \"my_system:0.1.0\"}\n ]\n\n ## Volumes and Cache\n\n Nerves will mount several volumes to the container for use in building\n the artifact.\n\n Mounted from the host:\n\n * `\/nerves\/env\/` - The package being built.\n * `\/nerves\/env\/platform` - The package platform package.\n * `\/nerves\/host\/artifacts` - The host artifact directory.\n\n Nerves will also mount the host NERVES_DL_DIR to save downloaded assets the\n build platform requires for producing the artifact.\n This is mounted at `\/nerves\/dl`. This volume can significally reduce build\n times but has potential for corruption. If you suspect that your build is\n failing due to a faulty downloaded cached data, you can manually mount\n the offending container and remove the file from this location or delete the\n entire directory.\n\n Nerves uses a docker volume to attach the build files. The volume name is\n defined as the package name and a unique id that is stored at\n `ARTIFACT_DIR\/.docker_id`. The build directory is mounted to the container at\n `\/nerves\/build` and is configured as the current working directory.\n\n ## Cleanup\n\n Perodically, you may want to destroy all unused volumes to clean up.\n Please refer to the Docker documentation for more information on how to\n do this.\n\n When the build_runner is finished, the artifact is decompressed on the host at\n the packages defined artifact directory.\n \"\"\"\n\n @behaviour Nerves.Artifact.BuildRunner\n\n alias Nerves.Artifact\n alias Nerves.Artifact.BuildRunners.Docker\n import Docker.Utils\n\n @version \"~> 1.12 or ~> 1.12.0-rc2 or >= 17.0.0\"\n\n @working_dir \"\/nerves\/build\"\n\n @doc \"\"\"\n Create an artifact for the package\n\n Opts:\n `make_args:` - Extra arguments to be passed to make.\n\n For example:\n\n You can configure the number of parallel jobs that buildroot\n can use for execution. This is useful for situations where you may\n have a machine with a lot of CPUs but not enough ram.\n\n # mix.exs\n defp nerves_package do\n [\n # ...\n build_runner_opts: [make_args: [\"PARALLEL_JOBS=8\"]],\n ]\n end\n \"\"\"\n @spec build(Nerves.Package.t(), Nerves.Package.t(), term) :: :ok\n def build(pkg, _toolchain, opts) do\n preflight(pkg)\n\n {:ok, pid} = Nerves.Utils.Stream.start_link(file: build_log_path())\n stream = IO.stream(pid, :line)\n\n :ok = create_build(pkg, stream)\n :ok = make(pkg, stream, opts)\n Mix.shell().info(\"\\n\")\n :ok = make_artifact(pkg, stream)\n Mix.shell().info(\"\\n\")\n {:ok, path} = copy_artifact(pkg, stream)\n Mix.shell().info(\"\\n\")\n _ = Nerves.Utils.Stream.stop(pid)\n {:ok, path}\n end\n\n @spec archive(Nerves.Package.t(), Nerves.Package.t(), term) :: :ok\n def archive(pkg, _toolchain, _opts) do\n {:ok, pid} = Nerves.Utils.Stream.start_link(file: \"archive.log\")\n stream = IO.stream(pid, :line)\n\n make_artifact(pkg, stream)\n copy_artifact(pkg, stream)\n end\n\n def clean(pkg) do\n Docker.Volume.name(pkg)\n |> Docker.Volume.delete()\n\n Artifact.Cache.path(pkg)\n |> File.rm_rf()\n end\n\n @doc \"\"\"\n Connect to a system configuration shell in a Docker container\n \"\"\"\n @spec system_shell(Nerves.Package.t()) :: :ok\n def system_shell(pkg) do\n preflight(pkg)\n {_, image} = config(pkg)\n platform_config = pkg.config[:platform_config][:defconfig]\n defconfig = Path.join(\"\/nerves\/env\/#{pkg.app}\", platform_config)\n\n initial_input = [\n \"echo Updating build directory.\",\n \"echo This will take a while if it is the first time...\",\n \"\/nerves\/env\/platform\/create-build.sh #{defconfig} #{@working_dir} >\/dev\/null\"\n ]\n\n mounts = Enum.join(mounts(pkg), \" \")\n ssh_agent = Enum.join(ssh_agent(), \" \")\n env_vars = Enum.join(env(), \" \")\n\n cmd =\n \"docker run --rm -it -w #{@working_dir} #{env_vars} #{mounts} #{ssh_agent} #{image} \/bin\/bash\"\n\n set_volume_permissions(pkg)\n\n Mix.Nerves.Shell.open(cmd, initial_input)\n end\n\n defp preflight(pkg) do\n Docker.Volume.id(pkg) || Docker.Volume.create_id(pkg)\n name = Docker.Volume.name(pkg)\n _ = host_check()\n _ = config_check(pkg, name)\n name\n end\n\n # Build Commands\n\n defp create_build(pkg, stream) do\n platform_config = pkg.config[:platform_config][:defconfig]\n defconfig = Path.join(\"\/nerves\/env\/#{pkg.app}\", platform_config)\n cmd = [\"\/nerves\/env\/platform\/create-build.sh\", defconfig, @working_dir]\n shell_info(\"Starting Build... (this may take a while)\")\n run(pkg, cmd, stream)\n end\n\n defp make(pkg, stream, opts) do\n make_args = Keyword.get(opts, :make_args, [])\n run(pkg, [\"make\" | make_args], stream)\n end\n\n defp make_artifact(pkg, stream) do\n name = Artifact.download_name(pkg)\n shell_info(\"Creating artifact archive\")\n cmd = [\"make\", \"system\", \"NERVES_ARTIFACT_NAME=#{name}\"]\n run(pkg, cmd, stream)\n end\n\n defp copy_artifact(pkg, stream) do\n shell_info(\"Copying artifact archive to host\")\n name = Artifact.download_name(pkg) <> Artifact.ext(pkg)\n cmd = [\"cp\", name, \"\/nerves\/dl\/#{name}\"]\n\n run(pkg, cmd, stream)\n path = Artifact.download_path(pkg)\n {:ok, path}\n end\n\n # Helpers\n\n defp run(pkg, cmd, stream) do\n set_volume_permissions(pkg)\n\n {_dockerfile, image} = config(pkg)\n\n args =\n [\n \"run\",\n \"--rm\",\n \"-w=#{@working_dir}\",\n \"-a\",\n \"stdout\",\n \"-a\",\n \"stderr\"\n ] ++ env() ++ mounts(pkg) ++ ssh_agent() ++ [image | cmd]\n\n case Mix.Nerves.Utils.shell(\"docker\", args, stream: stream) do\n {_result, 0} ->\n :ok\n\n {_result, _} ->\n Mix.raise(\"\"\"\n The Nerves Docker build_runner encountered an error while building:\n\n -----\n #{end_of_build_log()}\n -----\n\n See #{build_log_path()}.\n \"\"\")\n end\n end\n\n defp set_volume_permissions(pkg) do\n {_dockerfile, image} = config(pkg)\n\n # (chown)\n # Set the permissions of the build volume\n # to match those of the host user:group.\n # (--rm)\n # Remove the container when finished.\n args =\n [\n \"run\",\n \"--rm\",\n \"-w=#{@working_dir}\"\n ] ++ env(:root) ++ mounts(pkg) ++ [image | [\"chown\", \"#{uid()}:#{gid()}\", @working_dir]]\n\n case Mix.Nerves.Utils.shell(\"docker\", args) do\n {_result, 0} ->\n :ok\n\n {result, _} ->\n Mix.raise(\"\"\"\n The Nerves Docker build_runner encountered an error while setting permissions:\n\n #{inspect(result)}\n \"\"\")\n end\n end\n\n defp env(), do: env(uid(), gid())\n defp env(:root), do: env(0, 0)\n\n defp env(uid, gid) do\n [\"--env\", \"UID=#{uid}\", \"--env\", \"GID=#{gid}\"]\n end\n\n defp uid() do\n {uid, _} = System.cmd(\"id\", [\"-u\"])\n String.trim(uid)\n end\n\n defp gid() do\n {gid, _} = System.cmd(\"id\", [\"-g\"])\n String.trim(gid)\n end\n\n defp end_of_build_log() do\n {lines, _rc} = System.cmd(\"tail\", [\"-16\", build_log_path()])\n lines\n end\n\n defp build_log_path() do\n File.cwd!()\n |> Path.join(\"build.log\")\n end\n\n defp mounts(pkg) do\n build_paths = build_paths(pkg)\n build_volume = Docker.Volume.name(pkg)\n download_dir = Nerves.Env.download_dir() |> Path.expand()\n mounts = [\"--env\", \"NERVES_BR_DL_DIR=\/nerves\/dl\"]\n\n mounts =\n Enum.reduce(build_paths, mounts, fn {_, host, target}, acc ->\n [\"--mount\", \"type=bind,src=#{host},target=#{target}\" | acc]\n end)\n\n mounts = [\"--mount\", \"type=bind,src=#{download_dir},target=\/nerves\/dl\" | mounts]\n [\"--mount\", \"type=volume,src=#{build_volume},target=#{@working_dir}\" | mounts]\n end\n\n defp ssh_agent() do\n ssh_auth_sock = System.get_env(\"SSH_AUTH_SOCK\")\n [\"-v\", \"#{ssh_auth_sock}:\/ssh-agent\", \"-e\", \"SSH_AUTH_SOCK=\/ssh-agent\"]\n end\n\n defp build_paths(pkg) do\n system_br = Nerves.Env.package(:nerves_system_br)\n\n [\n {:platform, system_br.path, \"\/nerves\/env\/platform\"},\n {:package, pkg.path, \"\/nerves\/env\/#{pkg.app}\"}\n ]\n end\n\n defp host_check() do\n try do\n case System.cmd(\"docker\", [\"--version\"]) do\n {result, 0} ->\n <<\"Docker version \", vsn::binary>> = result\n {:ok, requirement} = Version.parse_requirement(@version)\n {:ok, vsn} = parse_docker_version(vsn)\n\n unless Version.match?(vsn, requirement) do\n error_invalid_version(vsn)\n end\n\n :ok\n\n _ ->\n error_not_installed()\n end\n rescue\n ErlangError -> error_not_installed()\n end\n end\n\n defp config_check(pkg, name) do\n {dockerfile, tag} = config(pkg)\n\n # Check for the Build Volume\n unless Docker.Volume.exists?(name) do\n Docker.Volume.create(name)\n end\n\n unless Docker.Image.exists?(tag) do\n Docker.Image.pull(tag)\n\n unless Docker.Image.exists?(tag) do\n Docker.Image.create(dockerfile, tag)\n end\n end\n\n :ok\n end\n\n defp config(pkg) do\n {dockerfile, tag} =\n (pkg.config[:build_runner_config] || [])\n |> Keyword.get(:docker, default_docker_config())\n\n dockerfile =\n dockerfile\n |> Path.relative_to_cwd()\n |> Path.expand()\n\n {dockerfile, tag}\n end\n\n defp default_docker_config() do\n [platform] = Nerves.Env.packages_by_type(:system_platform)\n dockerfile = Path.join(platform.path, \"support\/docker\/#{platform.app}\")\n tag = \"nervesproject\/#{platform.app}:#{platform.version}\"\n {dockerfile, tag}\n end\n\n defp error_not_installed do\n Mix.raise(\"\"\"\n Docker is not installed on your machine.\n Please install docker #{@version} or later\n \"\"\")\n end\n\n defp error_invalid_version(vsn) do\n Mix.raise(\"\"\"\n Your version of docker: #{vsn}\n does not meet the requirements: #{@version}\n \"\"\")\n end\n\n def parse_docker_version(vsn) do\n [vsn | _] = String.split(vsn, \",\", parts: 2)\n\n Regex.replace(~r\/(\\.|^)0+(?=\\d)\/, vsn, \"\\\\1\")\n |> Version.parse()\n end\nend\n","old_contents":"defmodule Nerves.Artifact.BuildRunners.Docker do\n @moduledoc \"\"\"\n Produce an artifact for a package using Docker.\n\n The Nerves Docker artifact build_runner will use docker to create the artifact\n for the package. The output in Mix will be limited to the headlines from the\n process and the full build log can be found in the file `build.log` located\n root of the package path.\n\n ## Images\n\n Docker containers will be created based off the image that is loaded.\n By default, containers will use the default image\n `nervesproject\/nerves_system_br:latest`. Sometimes additional host tools\n are required to build a package. Therefore, packages can provide their own\n images by specifying it in the package config under `:build_runner_config`.\n the file is specified as a tuple `{\"path\/to\/Dockerfile\", tag_name}`.\n\n Example:\n\n build_runner_config: [\n docker: {\"Dockerfile\", \"my_system:0.1.0\"}\n ]\n\n ## Volumes and Cache\n\n Nerves will mount several volumes to the container for use in building\n the artifact.\n\n Mounted from the host:\n\n * `\/nerves\/env\/` - The package being built.\n * `\/nerves\/env\/platform` - The package platform package.\n * `\/nerves\/host\/artifacts` - The host artifact directory.\n\n Nerves will also mount the host NERVES_DL_DIR to save downloaded assets the\n build platform requires for producing the artifact.\n This is mounted at `\/nerves\/dl`. This volume can significally reduce build\n times but has potential for corruption. If you suspect that your build is\n failing due to a faulty downloaded cached data, you can manually mount\n the offending container and remove the file from this location or delete the\n entire directory.\n\n Nerves uses a docker volume to attach the build files. The volume name is\n defined as the package name and a unique id that is stored at\n `ARTIFACT_DIR\/.docker_id`. The build directory is mounted to the container at\n `\/nerves\/build` and is configured as the current working directory.\n\n ## Cleanup\n\n Perodically, you may want to destroy all unused volumes to clean up.\n Please refer to the Docker documentation for more information on how to\n do this.\n\n When the build_runner is finished, the artifact is decompressed on the host at\n the packages defined artifact directory.\n \"\"\"\n\n @behaviour Nerves.Artifact.BuildRunner\n\n alias Nerves.Artifact\n alias Nerves.Artifact.BuildRunners.Docker\n import Docker.Utils\n\n @version \"~> 1.12 or ~> 1.12.0-rc2 or >= 17.0.0\"\n\n @working_dir \"\/nerves\/build\"\n\n @doc \"\"\"\n Create an artifact for the package\n\n Opts:\n `make_args:` - Extra arguments to be passed to make.\n\n For example:\n\n You can configure the number of parallel jobs that buildroot\n can use for execution. This is useful for situations where you may\n have a machine with a lot of CPUs but not enough ram.\n\n # mix.exs\n defp nerves_package do\n [\n # ...\n build_runner_opts: [make_args: [\"PARALLEL_JOBS=8\"]],\n ]\n end\n \"\"\"\n @spec build(Nerves.Package.t(), Nerves.Package.t(), term) :: :ok\n def build(pkg, _toolchain, opts) do\n preflight(pkg)\n\n {:ok, pid} = Nerves.Utils.Stream.start_link(file: build_log_path())\n stream = IO.stream(pid, :line)\n\n :ok = create_build(pkg, stream)\n :ok = make(pkg, stream, opts)\n Mix.shell().info(\"\\n\")\n :ok = make_artifact(pkg, stream)\n Mix.shell().info(\"\\n\")\n {:ok, path} = copy_artifact(pkg, stream)\n Mix.shell().info(\"\\n\")\n _ = Nerves.Utils.Stream.stop(pid)\n {:ok, path}\n end\n\n @spec archive(Nerves.Package.t(), Nerves.Package.t(), term) :: :ok\n def archive(pkg, _toolchain, _opts) do\n {:ok, pid} = Nerves.Utils.Stream.start_link(file: \"archive.log\")\n stream = IO.stream(pid, :line)\n\n make_artifact(pkg, stream)\n copy_artifact(pkg, stream)\n end\n\n def clean(pkg) do\n Docker.Volume.name(pkg)\n |> Docker.Volume.delete()\n\n Artifact.Cache.path(pkg)\n |> File.rm_rf()\n end\n\n @doc \"\"\"\n Connect to a system configuration shell in a Docker container\n \"\"\"\n @spec system_shell(Nerves.Package.t()) :: :ok\n def system_shell(pkg) do\n preflight(pkg)\n {_, image} = config(pkg)\n platform_config = pkg.config[:platform_config][:defconfig]\n defconfig = Path.join(\"\/nerves\/env\/#{pkg.app}\", platform_config)\n\n initial_input = [\n \"echo Updating build directory.\",\n \"echo This will take a while if it is the first time...\",\n \"\/nerves\/env\/platform\/create-build.sh #{defconfig} #{@working_dir} >\/dev\/null\"\n ]\n\n mounts = Enum.join(mounts(pkg), \" \")\n ssh_agent = Enum.join(ssh_agent(), \" \")\n\n cmd =\n \"docker run --rm -it --user #{uid()}:#{gid()} -w #{@working_dir} #{mounts} #{ssh_agent} #{\n image\n }\"\n\n set_volume_permissions(pkg)\n Mix.Nerves.Shell.open(cmd, initial_input)\n end\n\n defp preflight(pkg) do\n Docker.Volume.id(pkg) || Docker.Volume.create_id(pkg)\n name = Docker.Volume.name(pkg)\n _ = host_check()\n _ = config_check(pkg, name)\n name\n end\n\n # Build Commands\n\n defp create_build(pkg, stream) do\n platform_config = pkg.config[:platform_config][:defconfig]\n defconfig = Path.join(\"\/nerves\/env\/#{pkg.app}\", platform_config)\n cmd = [\"\/nerves\/env\/platform\/create-build.sh\", defconfig, @working_dir]\n shell_info(\"Starting Build... (this may take a while)\")\n run(pkg, cmd, stream)\n end\n\n defp make(pkg, stream, opts) do\n make_args = Keyword.get(opts, :make_args, [])\n run(pkg, [\"make\" | make_args], stream)\n end\n\n defp make_artifact(pkg, stream) do\n name = Artifact.download_name(pkg)\n shell_info(\"Creating artifact archive\")\n cmd = [\"make\", \"system\", \"NERVES_ARTIFACT_NAME=#{name}\"]\n run(pkg, cmd, stream)\n end\n\n defp copy_artifact(pkg, stream) do\n shell_info(\"Copying artifact archive to host\")\n name = Artifact.download_name(pkg) <> Artifact.ext(pkg)\n cmd = [\"cp\", name, \"\/nerves\/dl\/#{name}\"]\n\n run(pkg, cmd, stream)\n path = Artifact.download_path(pkg)\n {:ok, path}\n end\n\n # Helpers\n\n defp run(pkg, cmd, stream) do\n set_volume_permissions(pkg)\n\n {_dockerfile, image} = config(pkg)\n\n args =\n [\n \"run\",\n \"--rm\",\n \"-w=#{@working_dir}\",\n \"-a\",\n \"stdout\",\n \"-a\",\n \"stderr\",\n \"--user\",\n \"#{uid()}:#{gid()}\"\n ] ++ mounts(pkg) ++ ssh_agent() ++ [image | cmd]\n\n case Mix.Nerves.Utils.shell(\"docker\", args, stream: stream) do\n {_result, 0} ->\n :ok\n\n {_result, _} ->\n Mix.raise(\"\"\"\n The Nerves Docker build_runner encountered an error while building:\n\n -----\n #{end_of_build_log()}\n -----\n\n See #{build_log_path()}.\n \"\"\")\n end\n end\n\n defp set_volume_permissions(pkg) do\n {_dockerfile, image} = config(pkg)\n\n # (chown)\n # Set the permissions of the build volume\n # to match those of the host user:group.\n # (--rm)\n # Remove the container when finished.\n args =\n [\n \"run\",\n \"--rm\",\n \"-w=#{@working_dir}\"\n ] ++ mounts(pkg) ++ [image | [\"chown\", \"#{uid()}:#{gid()}\", @working_dir]]\n\n case Mix.Nerves.Utils.shell(\"docker\", args) do\n {_result, 0} ->\n :ok\n\n {result, _} ->\n Mix.raise(\"\"\"\n The Nerves Docker build_runner encountered an error while setting permissions:\n\n #{inspect(result)}\n \"\"\")\n end\n end\n\n defp uid() do\n {uid, _} = System.cmd(\"id\", [\"-u\"])\n String.trim(uid)\n end\n\n defp gid() do\n {gid, _} = System.cmd(\"id\", [\"-g\"])\n String.trim(gid)\n end\n\n defp end_of_build_log() do\n {lines, _rc} = System.cmd(\"tail\", [\"-16\", build_log_path()])\n lines\n end\n\n defp build_log_path() do\n File.cwd!()\n |> Path.join(\"build.log\")\n end\n\n defp mounts(pkg) do\n build_paths = build_paths(pkg)\n build_volume = Docker.Volume.name(pkg)\n download_dir = Nerves.Env.download_dir() |> Path.expand()\n mounts = [\"--env\", \"NERVES_BR_DL_DIR=\/nerves\/dl\"]\n\n mounts =\n Enum.reduce(build_paths, mounts, fn {_, host, target}, acc ->\n [\"--mount\", \"type=bind,src=#{host},target=#{target}\" | acc]\n end)\n\n mounts = [\"--mount\", \"type=bind,src=#{download_dir},target=\/nerves\/dl\" | mounts]\n [\"--mount\", \"type=volume,src=#{build_volume},target=#{@working_dir}\" | mounts]\n end\n\n defp ssh_agent() do\n ssh_auth_sock = System.get_env(\"SSH_AUTH_SOCK\")\n [\"-v\", \"#{ssh_auth_sock}:\/ssh-agent\", \"-e\", \"SSH_AUTH_SOCK=\/ssh-agent\"]\n end\n\n defp build_paths(pkg) do\n system_br = Nerves.Env.package(:nerves_system_br)\n\n [\n {:platform, system_br.path, \"\/nerves\/env\/platform\"},\n {:package, pkg.path, \"\/nerves\/env\/#{pkg.app}\"}\n ]\n end\n\n defp host_check() do\n try do\n case System.cmd(\"docker\", [\"--version\"]) do\n {result, 0} ->\n <<\"Docker version \", vsn::binary>> = result\n {:ok, requirement} = Version.parse_requirement(@version)\n {:ok, vsn} = parse_docker_version(vsn)\n\n unless Version.match?(vsn, requirement) do\n error_invalid_version(vsn)\n end\n\n :ok\n\n _ ->\n error_not_installed()\n end\n rescue\n ErlangError -> error_not_installed()\n end\n end\n\n defp config_check(pkg, name) do\n {dockerfile, tag} = config(pkg)\n\n # Check for the Build Volume\n unless Docker.Volume.exists?(name) do\n Docker.Volume.create(name)\n end\n\n unless Docker.Image.exists?(tag) do\n Docker.Image.pull(tag)\n\n unless Docker.Image.exists?(tag) do\n Docker.Image.create(dockerfile, tag)\n end\n end\n\n :ok\n end\n\n defp config(pkg) do\n {dockerfile, tag} =\n (pkg.config[:build_runner_config] || [])\n |> Keyword.get(:docker, default_docker_config())\n\n dockerfile =\n dockerfile\n |> Path.relative_to_cwd()\n |> Path.expand()\n\n {dockerfile, tag}\n end\n\n defp default_docker_config() do\n [platform] = Nerves.Env.packages_by_type(:system_platform)\n dockerfile = Path.join(platform.path, \"support\/docker\/#{platform.app}\")\n tag = \"nervesproject\/#{platform.app}:#{platform.version}\"\n {dockerfile, tag}\n end\n\n defp error_not_installed do\n Mix.raise(\"\"\"\n Docker is not installed on your machine.\n Please install docker #{@version} or later\n \"\"\")\n end\n\n defp error_invalid_version(vsn) do\n Mix.raise(\"\"\"\n Your version of docker: #{vsn}\n does not meet the requirements: #{@version}\n \"\"\")\n end\n\n def parse_docker_version(vsn) do\n [vsn | _] = String.split(vsn, \",\", parts: 2)\n\n Regex.replace(~r\/(\\.|^)0+(?=\\d)\/, vsn, \"\\\\1\")\n |> Version.parse()\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"8e279dd2d7ec3ead32f5b7a6aa2b1716695c42ee","subject":"Refactor CLI.main\/1","message":"Refactor CLI.main\/1\n","repos":"rrrene\/credo,rrrene\/credo","old_file":"lib\/credo\/cli.ex","new_file":"lib\/credo\/cli.ex","new_contents":"defmodule Credo.CLI do\n @moduledoc \"\"\"\n `Credo.CLI` is the entrypoint for both the Mix task and the escript.\n \"\"\"\n\n alias Credo.Execution\n\n @doc \"\"\"\n Runs Credo with the given `argv` and exits the process.\n\n See `Credo.run\/1` if you want to run Credo programmatically.\n \"\"\"\n def main(argv \\\\ []) do\n Credo.Application.start(nil, nil)\n\n {options, _argv_rest, _errors} = OptionParser.parse(argv, strict: [watch: :boolean])\n\n if options[:watch] do\n run_to_watch(argv)\n else\n run_to_halt(argv)\n end\n end\n\n defp run_to_watch(argv) do\n Credo.Watcher.run(argv)\n\n receive do\n _ -> nil\n end\n end\n\n defp run_to_halt(argv) do\n argv\n |> Credo.run()\n |> halt_if_exit_status_assigned()\n end\n\n defp halt_if_exit_status_assigned(%Execution{mute_exit_status: true}) do\n # Skip if exit status is muted\n end\n\n defp halt_if_exit_status_assigned(exec) do\n exec\n |> Execution.get_assign(\"credo.exit_status\", 0)\n |> halt_if_failed()\n end\n\n defp halt_if_failed(0), do: nil\n defp halt_if_failed(exit_status), do: exit({:shutdown, exit_status})\nend\n","old_contents":"defmodule Credo.CLI do\n @moduledoc \"\"\"\n `Credo.CLI` is the entrypoint for both the Mix task and the escript.\n \"\"\"\n\n alias Credo.Execution\n\n @doc \"\"\"\n Runs Credo with the given `argv` and exits the process.\n\n See `Credo.run\/1` if you want to run Credo programmatically.\n \"\"\"\n def main(argv \\\\ []) do\n Credo.Application.start(nil, nil)\n\n {options, _argv_rest, _errors} = OptionParser.parse(argv, strict: [watch: :boolean])\n\n if options[:watch] do\n Credo.Watcher.run(argv)\n\n receive do\n _ -> nil\n end\n else\n argv\n |> Credo.run()\n |> halt_if_exit_status_assigned()\n end\n end\n\n defp halt_if_exit_status_assigned(%Execution{mute_exit_status: true}) do\n # Skip if exit status is muted\n end\n\n defp halt_if_exit_status_assigned(exec) do\n exec\n |> Execution.get_assign(\"credo.exit_status\", 0)\n |> halt_if_failed()\n end\n\n defp halt_if_failed(0), do: nil\n defp halt_if_failed(exit_status), do: exit({:shutdown, exit_status})\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"a017ae65a27c09fd16ec3fec2069175055264ea0","subject":"Fix bug in release plugin","message":"Fix bug in release plugin\n","repos":"bitwalker\/conform","old_file":"lib\/conform\/releases\/plugin.ex","new_file":"lib\/conform\/releases\/plugin.ex","new_contents":"defmodule Conform.ReleasePlugin do\n Module.register_attribute __MODULE__, :name, accumulate: false, persist: true\n Module.register_attribute __MODULE__, :moduledoc, accumulate: false, persist: true\n Module.register_attribute __MODULE__, :shortdoc, accumulate: false, persist: true\n @name \"conform\"\n @shortdoc \"Generates a .conf for your release\"\n @moduledoc \"\"\"\n Generates a .conf for your release\n\n This plugin ensures that your application has a .schema.exs\n and .conf file for setting up configuration via the `conform`\n library. This .conf file then offers a simplified interface\n for sysadmins and other deployment staff for easily configuring\n your release in production.\n \"\"\"\n def before_assembly(%{profile: %{overlays: overlays} = profile} = release) do\n pre_configure_src = Path.join([\"#{:code.priv_dir(:conform)}\", \"bin\", \"pre_configure.sh\"])\n pre_upgrade_src = Path.join([\"#{:code.priv_dir(:conform)}\", \"bin\", \"pre_upgrade.sh\"])\n post_upgrade_src = Path.join([\"#{:code.priv_dir(:conform)}\", \"bin\", \"post_upgrade.sh\"])\n debug \"loading schema\"\n\n conf_src = get_conf_path(release)\n schema_src = get_schema_path(release)\n\n # Define overlays\n conform_overlays = [\n {:copy, pre_configure_src, \"releases\/<%= release_version %>\/hooks\/pre_start.d\/00_conform_pre_configure.sh\"},\n {:copy, pre_configure_src, \"releases\/<%= release_version %>\/hooks\/pre_configure.d\/00_conform_pre_configure.sh\"},\n {:copy, pre_upgrade_src, \"releases\/<%= release_version %>\/hooks\/pre_upgrade.d\/00_conform_pre_upgrade.sh\"},\n {:copy, post_upgrade_src, \"releases\/<%= release_version %>\/hooks\/post_upgrade.d\/00_conform_post_upgrade.sh\"},\n {:copy, schema_src, \"releases\/<%= release_version %>\/<%= release_name %>.schema.exs\"}]\n\n if File.exists?(schema_src) do\n conform_overlays =\n conform_overlays\n |> add_archive(release, schema_src)\n |> add_conf(release, conf_src)\n |> add_escript(release)\n debug \"done!\"\n %{release | :profile => %{profile | :overlays => overlays ++ conform_overlays}}\n else\n debug \"no schema found, skipping\"\n release\n end\n end\n\n def after_assembly(_release), do: nil\n def before_package(_release), do: nil\n def after_package(_release), do: nil\n def after_cleanup(_args), do: nil\n\n defp debug(message), do: apply(Mix.Releases.Logger, :debug, [\"conform: \" <> message])\n\n defp add_archive(conform_overlays, release, schema_src) do\n # generate archive\n result = Mix.Tasks.Conform.Archive.run([\"#{schema_src}\"])\n # add archive to the overlays\n case result do\n {_, _, []} ->\n {:ok, cwd} = File.cwd\n arch = \"#{cwd}\/rel\/releases\/#{release.version}\/#{release.name}.schema.ez\"\n case File.exists?(arch) do\n true -> File.rm(arch)\n false -> :ok\n end\n conform_overlays\n {_, zip_path, _} ->\n [{:copy,\n \"#{zip_path}\",\n \"releases\/<%= release_version %>\/<%= release_name %>.schema.ez\"} | conform_overlays]\n end\n end\n\n defp add_conf(conform_overlays, _release, conf_src) do\n case File.exists?(conf_src) do\n true ->\n [{:copy,\n conf_src,\n \"releases\/<%= release_version %>\/<%= release_name %>.conf\"} | conform_overlays]\n false -> conform_overlays\n end\n end\n\n defp add_escript(conform_overlays, _release) do\n debug \"generating escript\"\n escript_path = Path.join([\"#{:code.priv_dir(:conform)}\", \"bin\", \"conform\"])\n [{:copy, escript_path, \"releases\/<%= release_version %>\/conform\"} | conform_overlays]\n end\n\n defp generate_umbrella_schema(release) do\n schemas = Enum.reduce(umbrella_apps_paths(), [], fn({name, path}, acc) ->\n schema =\n path\n |> Path.join(\"config\/#{name}.schema.exs\")\n |> Conform.Schema.load\n\n case schema do\n {:ok, schema} ->\n debug \"merging schema #{name}\"\n [schema | acc]\n {:error, msg} ->\n debug msg\n acc\n end\n end)\n\n {:ok, tmp_dir} = Mix.Releases.Utils.insecure_mkdir_temp\n schema = Conform.Schema.coalesce(schemas)\n\n tmp_schema_src = Path.join(tmp_dir, \"#{release.name}.schema.exs\")\n Conform.Schema.write(schema, tmp_schema_src)\n\n tmp_schema_src\n end\n\n ## Concatenantes all conf files into a single umbrella conf file\n defp generate_umbrella_conf(release) do\n conf_files = Enum.reduce(umbrella_apps_paths(), [], fn({name, path}, acc) ->\n conf_path = case File.exists?(Path.join(path, \"config\/#{name}.#{Mix.env}.conf\")) do\n true -> Path.join(path, \"config\/#{name}.#{Mix.env}.conf\")\n false -> Path.join(path, \"config\/#{name}.conf\")\n end\n case File.read(conf_path) do\n {:ok, data} ->\n debug \"merging config #{name}\"\n [data | acc]\n {:error, _} ->\n debug \"no conf found, skipping #{conf_path}\"\n acc\n end\n end)\n\n {:ok, tmp_dir} = Mix.Releases.Utils.insecure_mkdir_temp\n conf = Enum.join(conf_files, \"\\n\")\n\n tmp_conf_src = Path.join(tmp_dir, \"#{release.name}.conf\")\n File.write!(tmp_conf_src, conf)\n tmp_conf_src\n end\n\n ## Backport from Elixir 1.4.0 `Mix.Project.apps_paths\/1`\n defp umbrella_apps_paths do\n config = Mix.Project.config\n if apps_path = config[:apps_path] do\n apps_path\n |> Path.join(\"*\/mix.exs\")\n |> Path.wildcard()\n |> Enum.map(&Path.dirname\/1)\n |> extract_umbrella\n |> filter_umbrella(config[:apps])\n |> Map.new\n end\n end\n\n defp umbrella_child_names do\n umbrella_apps_paths() |> Map.keys\n end\n\n ## Umbrella apps don't have a name in their mix project.\n ## Instead we check to see if the release is an umbrella release, and that the\n ## name of the release *is not* one of the apps in the umbrella.\n defp releasing_umbrella?(name) do\n case Mix.Project.umbrella? do\n true -> !Enum.member?(umbrella_child_names(), name)\n false -> false\n end\n end\n\n defp extract_umbrella(paths) do\n for path <- paths do\n app = path |> Path.basename |> String.downcase |> String.to_atom\n {app, path}\n end\n end\n\n defp filter_umbrella(pairs, nil), do: pairs\n defp filter_umbrella(pairs, apps) when is_list(apps) do\n for {app, _} = pair <- pairs, app in apps, do: pair\n end\n\n defp get_conf_path(release) do\n case releasing_umbrella?(release.name) do\n true -> generate_umbrella_conf(release)\n false ->\n src_dir = Conform.Utils.src_conf_dir(release.name)\n case File.exists?(Path.join(src_dir, \"#{release.name}.#{Mix.env}.conf\")) do\n true ->\n Path.join(src_dir, \"#{release.name}.#{Mix.env}.conf\")\n false ->\n Path.join(src_dir, \"#{release.name}.conf\")\n end\n end\n end\n\n defp get_schema_path(release) do\n case releasing_umbrella?(release.name) do\n true -> generate_umbrella_schema(release)\n false -> Conform.Schema.schema_path(release.name)\n end\n end\nend\n","old_contents":"defmodule Conform.ReleasePlugin do\n Module.register_attribute __MODULE__, :name, accumulate: false, persist: true\n Module.register_attribute __MODULE__, :moduledoc, accumulate: false, persist: true\n Module.register_attribute __MODULE__, :shortdoc, accumulate: false, persist: true\n @name \"conform\"\n @shortdoc \"Generates a .conf for your release\"\n @moduledoc \"\"\"\n Generates a .conf for your release\n\n This plugin ensures that your application has a .schema.exs\n and .conf file for setting up configuration via the `conform`\n library. This .conf file then offers a simplified interface\n for sysadmins and other deployment staff for easily configuring\n your release in production.\n \"\"\"\n def before_assembly(%{profile: %{overlays: overlays} = profile} = release) do\n pre_configure_src = Path.join([\"#{:code.priv_dir(:conform)}\", \"bin\", \"pre_configure.sh\"])\n pre_upgrade_src = Path.join([\"#{:code.priv_dir(:conform)}\", \"bin\", \"pre_upgrade.sh\"])\n post_upgrade_src = Path.join([\"#{:code.priv_dir(:conform)}\", \"bin\", \"post_upgrade.sh\"])\n debug \"loading schema\"\n\n conf_src = get_conf_path(release)\n schema_src = get_schema_path(release)\n\n # Define overlays\n conform_overlays = [\n {:copy, pre_configure_src, \"releases\/<%= release_version %>\/hooks\/pre_start.d\/00_conform_pre_configure.sh\"},\n {:copy, pre_configure_src, \"releases\/<%= release_version %>\/hooks\/pre_configure.d\/00_conform_pre_configure.sh\"},\n {:copy, pre_upgrade_src, \"releases\/<%= release_version %>\/hooks\/pre_upgrade.d\/00_conform_pre_upgrade.sh\"},\n {:copy, post_upgrade_src, \"releases\/<%= release_version %>\/hooks\/post_upgrade.d\/00_conform_post_upgrade.sh\"},\n {:copy, schema_src, \"releases\/<%= release_version %>\/<%= release_name %>.schema.exs\"}]\n\n if File.exists?(schema_src) do\n conform_overlays =\n conform_overlays\n |> add_archive(release, schema_src)\n |> add_conf(release, conf_src)\n |> add_escript(release)\n debug \"done!\"\n %{release | :profile => %{profile | :overlays => overlays ++ conform_overlays}}\n else\n debug \"no schema found, skipping\"\n release\n end\n end\n\n def after_assembly(_release), do: nil\n def before_package(_release), do: nil\n def after_package(_release), do: nil\n def after_cleanup(_args), do: nil\n\n defp debug(message), do: apply(Mix.Releases.Logger, :debug, [\"conform: \" <> message])\n\n defp add_archive(conform_overlays, release, schema_src) do\n # generate archive\n result = Mix.Tasks.Conform.Archive.run([\"#{schema_src}\"])\n # add archive to the overlays\n case result do\n {_, _, []} ->\n {:ok, cwd} = File.cwd\n arch = \"#{cwd}\/rel\/releases\/#{release.version}\/#{release.name}.schema.ez\"\n case File.exists?(arch) do\n true -> File.rm(arch)\n false -> :ok\n end\n conform_overlays\n {_, zip_path, _} ->\n [{:copy,\n \"#{zip_path}\",\n \"releases\/<%= release_version %>\/<%= release_name %>.schema.ez\"} | conform_overlays]\n end\n end\n\n defp add_conf(conform_overlays, _release, conf_src) do\n case File.exists?(conf_src) do\n true ->\n [{:copy,\n conf_src,\n \"releases\/<%= release_version %>\/<%= release_name %>.conf\"} | conform_overlays]\n false -> conform_overlays\n end\n end\n\n defp add_escript(conform_overlays, _release) do\n debug \"generating escript\"\n escript_path = Path.join([\"#{:code.priv_dir(:conform)}\", \"bin\", \"conform\"])\n [{:copy, escript_path, \"releases\/<%= release_version %>\/conform\"} | conform_overlays]\n end\n\n defp generate_umbrella_schema(release) do\n schemas = Enum.reduce(umbrella_apps_paths(), [], fn({name, path}, acc) ->\n schema =\n path\n |> Path.join(\"config\/#{name}.schema.exs\")\n |> Conform.Schema.load\n\n case schema do\n {:ok, schema} ->\n debug \"merging schema #{name}\"\n [schema | acc]\n {:error, msg} ->\n debug msg\n acc\n end\n end)\n\n {:ok, tmp_dir} = Mix.Releases.Utils.insecure_mkdir_temp\n schema = Conform.Schema.coalesce(schemas)\n\n tmp_schema_src = Path.join(tmp_dir, \"#{release.name}.schema.exs\")\n Conform.Schema.write(schema, tmp_schema_src)\n\n tmp_schema_src\n end\n\n ## Concatenantes all conf files into a single umbrella conf file\n defp generate_umbrella_conf(release) do\n conf_files = Enum.reduce(umbrella_apps_paths(), [], fn({name, path}, acc) ->\n conf_path = case File.exists(Path.join(path, \"config\/#{name}.#{Mix.env}.conf\")) do\n true -> Path.join(path, \"config\/#{name}.#{Mix.env}.conf\")\n false -> Path.join(path, \"config\/#{name}.conf\")\n end\n case File.read(conf_path) do\n {:ok, data} ->\n debug \"merging config #{name}\"\n [data | acc]\n {:error, _} ->\n debug \"no conf found, skipping #{conf_path}\"\n acc\n end\n end)\n\n {:ok, tmp_dir} = Mix.Releases.Utils.insecure_mkdir_temp\n conf = Enum.join(conf_files, \"\\n\")\n\n tmp_conf_src = Path.join(tmp_dir, \"#{release.name}.conf\")\n File.write!(tmp_conf_src, conf)\n tmp_conf_src\n end\n\n ## Backport from Elixir 1.4.0 `Mix.Project.apps_paths\/1`\n defp umbrella_apps_paths do\n config = Mix.Project.config\n if apps_path = config[:apps_path] do\n apps_path\n |> Path.join(\"*\/mix.exs\")\n |> Path.wildcard()\n |> Enum.map(&Path.dirname\/1)\n |> extract_umbrella\n |> filter_umbrella(config[:apps])\n |> Map.new\n end\n end\n\n defp umbrella_child_names do\n umbrella_apps_paths() |> Map.keys\n end\n\n ## Umbrella apps don't have a name in their mix project.\n ## Instead we check to see if the release is an umbrella release, and that the\n ## name of the release *is not* one of the apps in the umbrella.\n defp releasing_umbrella?(name) do\n case Mix.Project.umbrella? do\n true -> !Enum.member?(umbrella_child_names(), name)\n false -> false\n end\n end\n\n defp extract_umbrella(paths) do\n for path <- paths do\n app = path |> Path.basename |> String.downcase |> String.to_atom\n {app, path}\n end\n end\n\n defp filter_umbrella(pairs, nil), do: pairs\n defp filter_umbrella(pairs, apps) when is_list(apps) do\n for {app, _} = pair <- pairs, app in apps, do: pair\n end\n\n defp get_conf_path(release) do\n case releasing_umbrella?(release.name) do\n true -> generate_umbrella_conf(release)\n false ->\n src_dir = Conform.Utils.src_conf_dir(release.name)\n case File.exists?(Path.join(src_dir, \"#{release.name}.#{Mix.env}.conf\")) do\n true ->\n Path.join(src_dir, \"#{release.name}.#{Mix.env}.conf\")\n false ->\n Path.join(src_dir, \"#{release.name}.conf\")\n end\n end\n end\n\n defp get_schema_path(release) do\n case releasing_umbrella?(release.name) do\n true -> generate_umbrella_schema(release)\n false -> Conform.Schema.schema_path(release.name)\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"81b865516c216f8383b71ace7386cf9bb3911739","subject":"Update valid_mentions","message":"Update valid_mentions\n","repos":"polleverywhere\/FOMObot-hipchat","old_file":"lib\/fomobot\/fomobot_hipchat.ex","new_file":"lib\/fomobot\/fomobot_hipchat.ex","new_contents":"defmodule Fomobot.Hipchat do\n alias Fomobot.Task\n use Hedwig.Handler\n\n @valid_mentions [\"@fomobot\", \"fomobot\", \"@FOMObot\", \"FOMObot\"]\n\n def init_keepalive do\n Enum.each Application.get_env(:hedwig, :clients), fn(%{jid: jid}) ->\n %{event_manager: pid} = jid |> String.to_atom |> Process.whereis |> :sys.get_state\n GenEvent.notify(pid, :init_keepalive)\n end\n end\n\n def handle_event(%Message{} = message, opts) do\n case has_valid_mention?(message) do\n false -> :ok\n true -> Task.process_message(message)\n end\n {:ok, opts}\n end\n\n def handle_event(:init_keepalive, opts) do\n delay = Application.get_env(:fomobot, :keepalive_delay)\n :erlang.send_after(delay, self, :send_keepalive)\n {:ok, opts}\n end\n\n def handle_event(_event, opts) do\n {:ok, opts}\n end\n\n def handle_info({_from, {:send_reply, message, reply}}, opts) do\n reply(message, Stanza.body(reply))\n {:ok, opts}\n end\n\n def handle_info(:send_keepalive, opts) do\n pid = opts.client.jid |> String.to_atom |> Process.whereis\n client = Hedwig.Client.client_for(opts.client.jid)\n\n stanza = Hedwig.Stanza.join(hd(client.rooms), client.nickname)\n Hedwig.Client.reply(pid, stanza)\n\n delay = Application.get_env(:fomobot, :keepalive_delay)\n :erlang.send_after(delay, self, :send_keepalive)\n {:ok, opts}\n end\n\n def handle_info(_msg, opts) do\n {:ok, opts}\n end\n\n defp has_valid_mention?(message) do\n message.body\n |> String.strip\n |> String.starts_with?(@valid_mentions)\n end\nend\n","old_contents":"defmodule Fomobot.Hipchat do\n alias Fomobot.Task\n use Hedwig.Handler\n\n @valid_mentions [\"@fomobot\", \"fomobot\"]\n\n def init_keepalive do\n Enum.each Application.get_env(:hedwig, :clients), fn(%{jid: jid}) ->\n %{event_manager: pid} = jid |> String.to_atom |> Process.whereis |> :sys.get_state\n GenEvent.notify(pid, :init_keepalive)\n end\n end\n\n def handle_event(%Message{} = message, opts) do\n case has_valid_mention?(message) do\n false -> :ok\n true -> Task.process_message(message)\n end\n {:ok, opts}\n end\n\n def handle_event(:init_keepalive, opts) do\n delay = Application.get_env(:fomobot, :keepalive_delay)\n :erlang.send_after(delay, self, :send_keepalive)\n {:ok, opts}\n end\n\n def handle_event(_event, opts) do\n {:ok, opts}\n end\n\n def handle_info({_from, {:send_reply, message, reply}}, opts) do\n reply(message, Stanza.body(reply))\n {:ok, opts}\n end\n\n def handle_info(:send_keepalive, opts) do\n pid = opts.client.jid |> String.to_atom |> Process.whereis\n client = Hedwig.Client.client_for(opts.client.jid)\n\n stanza = Hedwig.Stanza.join(hd(client.rooms), client.nickname)\n Hedwig.Client.reply(pid, stanza)\n\n delay = Application.get_env(:fomobot, :keepalive_delay)\n :erlang.send_after(delay, self, :send_keepalive)\n {:ok, opts}\n end\n\n def handle_info(_msg, opts) do\n {:ok, opts}\n end\n\n defp has_valid_mention?(message) do\n message.body\n |> String.strip\n |> String.starts_with?(@valid_mentions)\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"ed12fa46225bd1c524a5c12c3d4ffa1c57d8aa08","subject":"Replace private Ecto SQL ensure_started\/2 with app start","message":"Replace private Ecto SQL ensure_started\/2 with app start\n","repos":"hashrocket\/tilex,hashrocket\/tilex,hashrocket\/tilex","old_file":"lib\/mix\/tasks\/tilex\/streaks.ex","new_file":"lib\/mix\/tasks\/tilex\/streaks.ex","new_contents":"defmodule Mix.Tasks.Tilex.Streaks do\n use Mix.Task\n import Mix.Ecto, only: [parse_repo: 1]\n\n @shortdoc \"Tilex Stats: Days in a row a til was posted\"\n\n @moduledoc \"\"\"\n Run `mix tilex.streaks` to get days in a row a til was posted.\n Run `mix tilex.streaks chriserin` to get days in a row a til was posted by chriserin.\n \"\"\"\n\n def run([]), do: run([\"%\"])\n\n def run([username] = args) do\n repo =\n args\n |> parse_repo\n |> hd\n\n streaks_sql = \"\"\"\n with days as (\n select generate_series('4-12-2015'::date, now()::date, '1 day'::interval)::date as series_date\n ), specific_posts as (\n select\n p.inserted_at,\n developers.username\n from posts p\n inner join developers on p.developer_id = developers.id\n where username like $1\n ), all_til_days as (\n select\n inserted_at::date post_inserted,\n d.series_date series_date,\n username\n from specific_posts p\n right join days d on d.series_date = p.inserted_at::date\n ), partitioned_days as (\n select\n post_inserted,\n username,\n (select max(sub.series_date) from all_til_days sub where sub.post_inserted is null and sub.series_date < orig.series_date) last_unposted_day\n from all_til_days orig where post_inserted is not null\n ), streaks as (\n select\n count(distinct post_inserted) streak_length,\n min(post_inserted) start_date,\n max(post_inserted) end_date,\n array_agg(distinct username)\n from partitioned_days\n group by last_unposted_day\n having count(distinct post_inserted) >= 5\n order by streak_length desc\n )\n select * from streaks;\n \"\"\"\n\n Mix.Task.run(\"app.start\")\n\n {:ok, result} = repo.query(streaks_sql, [username], log: false)\n\n Enum.each(result.rows, fn [streak_length, start_date, end_date, _people] ->\n formatted_start_date = Timex.format!(start_date, \"%m\/%d\/%Y\", :strftime)\n formatted_end_date = Timex.format!(end_date, \"%m\/%d\/%Y\", :strftime)\n\n IO.puts(\"#{streak_length} days from #{formatted_start_date} to #{formatted_end_date}\")\n end)\n end\nend\n","old_contents":"defmodule Mix.Tasks.Tilex.Streaks do\n use Mix.Task\n import Mix.Ecto, only: [parse_repo: 1]\n import Mix.EctoSQL, only: [ensure_started: 2]\n\n @shortdoc \"Tilex Stats: Days in a row a til was posted\"\n\n @moduledoc \"\"\"\n Run `mix tilex.streaks` to get days in a row a til was posted.\n Run `mix tilex.streaks chriserin` to get days in a row a til was posted by chriserin.\n \"\"\"\n\n def run([]), do: run([\"%\"])\n\n def run([username] = args) do\n repo =\n args\n |> parse_repo\n |> hd\n\n streaks_sql = \"\"\"\n with days as (\n select generate_series('4-12-2015'::date, now()::date, '1 day'::interval)::date as series_date\n ), specific_posts as (\n select\n p.inserted_at,\n developers.username\n from posts p\n inner join developers on p.developer_id = developers.id\n where username like $1\n ), all_til_days as (\n select\n inserted_at::date post_inserted,\n d.series_date series_date,\n username\n from specific_posts p\n right join days d on d.series_date = p.inserted_at::date\n ), partitioned_days as (\n select\n post_inserted,\n username,\n (select max(sub.series_date) from all_til_days sub where sub.post_inserted is null and sub.series_date < orig.series_date) last_unposted_day\n from all_til_days orig where post_inserted is not null\n ), streaks as (\n select\n count(distinct post_inserted) streak_length,\n min(post_inserted) start_date,\n max(post_inserted) end_date,\n array_agg(distinct username)\n from partitioned_days\n group by last_unposted_day\n having count(distinct post_inserted) >= 5\n order by streak_length desc\n )\n select * from streaks;\n \"\"\"\n\n ensure_started(repo, [])\n\n {:ok, result} = repo.query(streaks_sql, [username], log: false)\n\n Enum.each(result.rows, fn [streak_length, start_date, end_date, _people] ->\n formatted_start_date = Timex.format!(start_date, \"%m\/%d\/%Y\", :strftime)\n formatted_end_date = Timex.format!(end_date, \"%m\/%d\/%Y\", :strftime)\n\n IO.puts(\"#{streak_length} days from #{formatted_start_date} to #{formatted_end_date}\")\n end)\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"d215a40014043001b98f36df84f0efb1322d2ea7","subject":"Monitor instead of link","message":"Monitor instead of link\n","repos":"ernie\/venture,ernie\/venture,ernie\/venture","old_file":"lib\/venture\/channel_monitor.ex","new_file":"lib\/venture\/channel_monitor.ex","new_contents":"defmodule Venture.ChannelMonitor do\n use GenServer\n\n ## Client API\n\n def monitor(server_name, pid, mfa) do\n GenServer.call(server_name, {:monitor, pid, mfa})\n end\n\n def demonitor(server_name, pid, mfa) do\n GenServer.call(server_name, {:demonitor, pid, mfa})\n end\n\n ## Server Callbacks\n\n def start_link(name) do\n GenServer.start_link(__MODULE__, :ok, name: name)\n end\n\n def init(:ok) do\n {:ok, %{channels: %{}}}\n end\n\n def handle_call({:monitor, pid, mfa}, _from, state) do\n ref = Process.monitor(pid)\n {:reply, :ok, put_channel(state, pid, {ref, mfa})}\n end\n\n def handle_call({:demonitor, pid}, _from, state) do\n case Map.fetch(state.channels, pid) do\n :error -> {:reply, :ok, state}\n {:ok, {ref, _mfa}} ->\n Process.demonitor(ref)\n {:reply, :ok, drop_channel(state, pid)}\n end\n end\n\n def handle_info({:DOWN, ref, :process, pid, _reason}, state) do\n Process.demonitor(ref)\n case Map.fetch(state.channels, pid) do\n :error -> {:noreply, state}\n {:ok, {_ref, {mod, func, args}}} ->\n Task.Supervisor.start_child(Venture.TaskSupervisor, mod, func, args)\n {:noreply, drop_channel(state, pid)}\n end\n end\n\n defp drop_channel(state, pid) do\n %{state | channels: Map.delete(state.channels, pid)}\n end\n\n defp put_channel(state, pid, {ref, mfa}) do\n %{state | channels: Map.put(state.channels, pid, {ref, mfa})}\n end\n\nend\n","old_contents":"defmodule Venture.ChannelMonitor do\n use GenServer\n\n ## Client API\n\n def monitor(server_name, pid, mfa) do\n GenServer.call(server_name, {:monitor, pid, mfa})\n end\n\n def demonitor(server_name, pid, mfa) do\n GenServer.call(server_name, {:demonitor, pid, mfa})\n end\n\n ## Server Callbacks\n\n def start_link(name) do\n GenServer.start_link(__MODULE__, :ok, name: name)\n end\n\n def init(:ok) do\n Process.flag(:trap_exit, true)\n {:ok, %{channels: %{}}}\n end\n\n def handle_call({:monitor, pid, mfa}, _from, state) do\n Process.link(pid)\n {:reply, :ok, put_channel(state, pid, mfa)}\n end\n\n def handle_call({:demonitor, pid}, _from, state) do\n case Map.fetch(state.channels, pid) do\n :error -> {:reply, :ok, state}\n {:ok, _mfa} ->\n Process.unlink(pid)\n {:reply, :ok, drop_channel(state, pid)}\n end\n end\n\n def handle_info({:EXIT, pid, _reason}, state) do\n case Map.fetch(state.channels, pid) do\n :error -> {:noreply, state}\n {:ok, {mod, func, args}} ->\n Task.Supervisor.start_child(Venture.TaskSupervisor, mod, func, args)\n {:noreply, drop_channel(state, pid)}\n end\n end\n\n defp drop_channel(state, pid) do\n %{state | channels: Map.delete(state.channels, pid)}\n end\n\n defp put_channel(state, pid, mfa) do\n %{state | channels: Map.put(state.channels, pid, mfa)}\n end\n\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"8269753a72d736bd561ca561598c247ee4ba8ff8","subject":"busStatus","message":"busStatus\n","repos":"knathan2\/dot,knathan2\/dot","old_file":"web\/controllers\/dot_controller.ex","new_file":"web\/controllers\/dot_controller.ex","new_contents":"defmodule Dot.DotController do \n use Dot.Web, :controller\n require Logger\n def mytime(conn, params) do\n \n %{\"request\" => %{\"intent\" => %{\"name\" => \"HelloWorld\", \"slots\" => %{\"Date\" => %{\"name\" => \"Date\", \"value\" => busDate}}}}} = params\n busStatus = Bus.get(busDate)\n Logger.info(\"#{inspect status}\")\n json conn, \n %{\n \"version\" => \"1.0\",\n \"sessionAttributes\" => %{},\n \"response\" => %{\n \"outputSpeech\" => %{\n \"type\" => \"PlainText\",\n \"text\" => \"The bus status for \" <> busDate <> \" is \" <> busStatus <> \"\",\n },\n \"shouldEndSession\" => true\n }\n }\n end\nend\n","old_contents":"defmodule Dot.DotController do \n use Dot.Web, :controller\n require Logger\n def mytime(conn, params) do\n \n %{\"request\" => %{\"intent\" => %{\"name\" => \"HelloWorld\", \"slots\" => %{\"Date\" => %{\"name\" => \"Date\", \"value\" => busDate}}}}} = params\n status = Bus.get(busDate)\n Logger.info(\"#{inspect status}\")\n json conn, \n %{\n \"version\" => \"1.0\",\n \"sessionAttributes\" => %{},\n \"response\" => %{\n \"outputSpeech\" => %{\n \"type\" => \"PlainText\",\n \"text\" => \"The bus status for \" <> busDate <> \" is \" <> status,\n },\n \"shouldEndSession\" => true\n }\n }\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"deedadb528f4346dd848cc8a75ded12cdd54d584","subject":"Remove wrong traversable reference","message":"Remove wrong traversable reference\n","repos":"kelvinst\/elixir,gfvcastro\/elixir,pedrosnk\/elixir,antipax\/elixir,ggcampinho\/elixir,michalmuskala\/elixir,elixir-lang\/elixir,ggcampinho\/elixir,beedub\/elixir,lexmag\/elixir,beedub\/elixir,kimshrier\/elixir,kimshrier\/elixir,joshprice\/elixir,kelvinst\/elixir,pedrosnk\/elixir,antipax\/elixir,lexmag\/elixir,gfvcastro\/elixir","old_file":"lib\/elixir\/lib\/kernel\/special_forms.ex","new_file":"lib\/elixir\/lib\/kernel\/special_forms.ex","new_contents":"defmodule Kernel.SpecialForms do\n @moduledoc \"\"\"\n In this module we define Elixir special forms. Special forms\n cannot be overridden by the developer and are the basic\n building blocks of Elixir code.\n\n Some of those forms are lexical (like `alias`, `case`, etc).\n The macros `{}` and `<<>>` are also special forms used to define\n tuple and binary data structures respectively.\n\n This module also documents Elixir's pseudo variables (`__ENV__`,\n `__MODULE__`, `__DIR__` and `__CALLER__`). Pseudo variables return\n information about Elixir's compilation environment and can only\n be read, never assigned to.\n\n Finally, it also documents 2 special forms, `__block__` and\n `__aliases__`, which are not intended to be called directly by the\n developer but they appear in quoted contents since they are essential\n in Elixir's constructs.\n \"\"\"\n\n @doc \"\"\"\n Creates a tuple.\n\n Only two item tuples are considered literals in Elixir.\n Therefore all other tuples are represented in the AST\n as a call to the special form `:{}`.\n\n Conveniences for manipulating tuples can be found in the\n `Tuple` module. Some functions for working with tuples are\n also available in `Kernel`, namely `Kernel.elem\/2`,\n `Kernel.set_elem\/3` and `Kernel.tuple_size\/1`.\n\n ## Examples\n\n iex> { 1, 2, 3 }\n { 1, 2, 3 }\n iex> quote do: { 1, 2, 3 }\n { :{}, [], [1,2,3] }\n\n \"\"\"\n defmacro unquote(:{})(args)\n\n @doc \"\"\"\n Creates a map.\n\n Maps are key-value stores where keys are compared \n using the match operator (`===`). Maps can be created with\n the `%{}` special form where keys are associated via `=>`:\n\n %{ 1 => 2 }\n\n Maps also support the keyword notation, as other special forms,\n as long as they are at the end of the argument list:\n\n %{ hello: :world, with: :keywords }\n %{ :hello => :world, with: :keywords }\n\n If a map has duplicated keys, the last key will always have\n higher precedence:\n\n iex> %{ a: :b, a: :c }\n %{ a: :c }\n\n Conveniences for manipulating maps can be found in the\n `Map` module.\n\n ## Access syntax\n\n Besides the access functions available in the `Map` module,\n like `Map.get\/3` and `Map.fetch\/2`, a map can be accessed using the\n `.` operator:\n\n iex> map = %{ a: :b }\n iex> map.a\n :b\n\n Note that the `.` operator expects the field to exist in the map.\n If not, an `ArgumentError` is raised.\n\n ## Update syntax\n\n Maps also support an update syntax:\n\n iex> map = %{ :a => :b }\n iex> %{ map | :a => :c }\n %{ :a => :c }\n\n Notice the update syntax requires the given keys to exist.\n Trying to update a key that does not exist will raise an `ArgumentError`.\n\n ## AST representation\n\n Regardless if `=>` or the keywords syntax is used, Maps are\n always represented internally as a list of two-items tuples\n for simplicity:\n\n iex> quote do: %{ :a => :b, c: :d }\n { :%{}, [], [{:a, :b}, {:c, :d}] }\n\n \"\"\"\n defmacro unquote(:%{})(args)\n\n @doc \"\"\"\n Creates a struct.\n\n A struct is a tagged map that allows developers to provide\n default values for keys, tags to be used in polymorphic\n dispatches and compile time assertions.\n\n To define a struct, you just need to implement the `__struct__\/0`\n function in a module:\n\n defmodule User do\n def __struct__ do\n %{ name: \"jos\u00e9\", age: 27 }\n end\n end\n\n Now a struct can be created as follow:\n\n %User{}\n\n Underneath, a struct is just a map with a `__struct__` field\n pointing to the User module:\n\n %User{} == %{ __struct__: User, name: \"jos\u00e9\", age: 27 }\n\n A struct also validates the given keys are part of the defined\n struct. The example below will fail because there is no key\n `:full_name` in the user struct:\n\n %User{ full_name: \"Jos\u00e9 Valim\" }\n\n Note that a struct specifies a minimum set of keys required\n for operations. Other keys can be added to structs via the\n regular map operations:\n\n user = %User{}\n %{ user | a_non_struct_key: :value }\n\n An update operation specific for structs is also available:\n\n %User{ user | age: 28 }\n\n The syntax above will guarantee the given keys are valid at\n compilation time and it will guarantee at runtime the given\n argument is a struct, failing with `BadStructError` otherwise.\n\n Check `Kernel.defprotocol\/2` for more information on how structs\n can be used with protocols for polymorphic dispatch.\n \"\"\"\n defmacro unquote(:%)(struct, map)\n\n @doc \"\"\"\n Defines a new bitstring.\n\n ## Examples\n\n iex> << 1, 2, 3 >>\n << 1, 2, 3 >>\n\n ## Bitstring types\n\n A bitstring is made of many segments. Each segment has a\n type, which defaults to integer:\n\n iex> <<1, 2, 3>>\n <<1, 2, 3>>\n\n Elixir also accepts by default the segment to be a literal\n string or a literal char list, which are by expanded to integers:\n\n iex> <<0, \"foo\">>\n <<0, 102, 111, 111>>\n\n Any other type needs to be explicitly tagged. For example,\n in order to store a float type in the binary, one has to do:\n\n iex> <<3.14 :: float>>\n <<64, 9, 30, 184, 81, 235, 133, 31>>\n\n This also means that variables need to be explicitly tagged,\n otherwise Elixir defaults to integer:\n\n iex> rest = \"oo\"\n iex> <<102, rest>>\n ** (ArgumentError) argument error\n\n We can solve this by explicitly tagging it as a binary:\n\n <<102, rest :: binary>>\n\n The type can be integer, float, bitstring\/bits, binary\/bytes,\n utf8, utf16 or utf32, e.g.:\n\n <<102 :: float, rest :: binary>>\n\n An integer can be any arbitrary precision integer. A float is an\n IEEE 754 binary32 or binary64 floating point number. A bitstring\n is an arbitrary series of bits. A binary is a special case of\n bitstring that has a total size divisible by 8.\n\n The utf8, utf16, and utf32 types are for UTF code points. They\n can also be applied to literal strings and char lists:\n\n iex> <<\"foo\" :: utf16>>\n <<0,102,0,111,0,111>>\n\n The bits type is an alias for bitstring. The bytes type is an\n alias for binary.\n\n The signedness can also be given as signed or unsigned. The\n signedness only matters for matching. If unspecified, it\n defaults to unsigned. Example:\n\n iex> <<-100 :: signed, _rest :: binary>> = <<-100, \"foo\">>\n <<156,102,111,111>>\n\n This match would have failed if we did not specify that the\n value -100 is signed. If we're matching into a variable instead\n of a value, the signedness won't be checked; rather, the number\n will simply be interpreted as having the given (or implied)\n signedness, e.g.:\n\n iex> <> = <<-100, \"foo\">>\n ...> val\n 156\n\n Here, `val` is interpreted as unsigned.\n\n Signedness is only relevant on integers.\n\n The endianness of a segment can be big, little or native (the\n latter meaning it will be resolved at VM load time). Passing\n many options can be done by giving a list:\n\n <<102 :: [integer, native], rest :: binary>>\n\n Or:\n\n <<102 :: [unsigned, big, integer], rest :: binary>>\n\n And so on.\n\n Endianness only makes sense for integers and some UTF code\n point types (utf16 and utf32).\n\n Finally, we can also specify size and unit for each segment. The\n unit is multiplied by the size to give the effective size of\n the segment:\n\n iex> <<102, _rest :: [size(2), unit(8)]>> = \"foo\"\n \"foo\"\n\n iex> <<102, _rest :: size(16)>> = \"foo\"\n \"foo\"\n\n iex> <<102, _rest :: size(32)>> = \"foo\"\n ** (MatchError) no match of right hand side value: \"foo\"\n\n In the example above, the first two expressions matches\n because the string \"foo\" takes 24 bits and we are matching\n against a segment of 24 bits as well, 8 of which are taken by\n the integer 102 and the remaining 16 bits are specified on\n the rest. On the last example, we expect a rest with size 32,\n which won't match.\n\n Size and unit are not applicable to utf8, utf16, and utf32.\n\n The default size for integers is 8. For floats, it is 64. For\n binaries, it is the size of the binary. Only the last binary\n in a binary match can use the default size (all others must\n have their size specified explicitly). Bitstrings do not have\n a default size.\n\n Size can also be specified using a syntax shortcut. Instead of\n writing `size(8)`, one can write just `8` and it will be interpreted\n as `size(8)`\n\n iex> << 1 :: 3 >> == << 1 :: size(3) >>\n true\n\n The default unit for integers, floats, and bitstrings is 1. For\n binaries, it is 8.\n\n For floats, unit * size must result in 32 or 64, corresponding\n to binary32 and binary64, respectively.\n \"\"\"\n defmacro unquote(:<<>>)(args)\n\n @doc \"\"\"\n Defines a remote call or an alias.\n\n The dot (`.`) in Elixir can be used for remote calls:\n\n iex> String.downcase(\"FOO\")\n \"foo\"\n\n In this example above, we have used `.` to invoke `downcase` in the\n `String` alias, passing \"FOO\" as argument. We can also use the dot\n for creating aliases:\n\n iex> Hello.World\n Hello.World\n\n This time, we have joined two aliases, defining the final alias\n `Hello.World`.\n\n ## Syntax\n\n The right side of `.` may be a word starting in upcase, which represents\n an alias, a word starting with lowercase or underscore, any valid language\n operator or any name wrapped in single- or double-quotes. Those are all valid\n examples:\n\n iex> Kernel.Sample\n Kernel.Sample\n iex> Kernel.length([1,2,3])\n 3\n iex> Kernel.+(1, 2)\n 3\n iex> Kernel.\"length\"([1,2,3])\n 3\n iex> Kernel.'+'(1, 2)\n 3\n\n Note that `Kernel.\"HELLO\"` will be treated as a remote call and not an alias.\n This choice was done so every time single- or double-quotes are used, we have\n a remote call irregardless of the quote contents. This decision is also reflected\n in the quoted expressions discussed below.\n\n ## Runtime (dynamic) behaviour\n\n The result returned by `.` is always specified by the right-side:\n\n iex> x = String\n iex> x.downcase(\"FOO\")\n \"foo\"\n iex> x.Sample\n String.Sample\n\n In case the right-side is also dynamic, `.`'s behaviour can be reproduced\n at runtime via `apply\/3` and `Module.concat\/2`:\n\n iex> apply(:erlang, :+, [1,2])\n 3\n iex> Module.concat(Kernel, Sample)\n Kernel.Sample\n\n ## Quoted expression\n\n When `.` is used, the quoted expression may take two distinct\n forms. When the right side starts with a lowercase letter (or\n underscore):\n\n iex> quote do: String.downcase(\"FOO\")\n {{:., [], [{:__aliases__, [alias: false], [:String]}, :downcase]}, [], [\"FOO\"]}\n\n Notice we have an inner tuple, containing the atom `:.` representing\n the dot as first element:\n\n {:., [], [{:__aliases__, [alias: false], [:String]}, :downcase]}\n\n This tuple follows the general quoted expression structure in Elixir,\n with the name as first argument, some keyword list as metadata as second,\n and the number of arguments as third. In this case, the arguments is the\n alias `String` and the atom `:downcase`. The second argument is **always**\n an atom:\n\n iex> quote do: String.\"downcase\"(\"FOO\")\n {{:., [], [{:__aliases__, [alias: false], [:String]}, :downcase]}, [], [\"FOO\"]}\n\n The tuple containing `:.` is wrapped in another tuple, which actually\n represents the function call, and has `\"FOO\"` as argument.\n\n When the right side is an alias (i.e. starts with uppercase), we get instead:\n\n iex> quote do: Hello.World\n {:__aliases__, [alias: false], [:Hello, :World]}\n\n We got into more details about aliases in the `__aliases__` special form\n documentation.\n\n ## Unquoting\n\n We can also use unquote to generate a remote call in a quoted expression:\n\n iex> x = :downcase\n iex> quote do: String.unquote(x)(\"FOO\")\n {{:., [], [{:__aliases__, [alias: false], [:String]}, :downcase]}, [], [\"FOO\"]}\n\n Similar to `Kernel.\"HELLO\"`, `unquote(x)` will always generate a remote call,\n independent of the value of `x`. To generate an alias via the quoted expression,\n one needs to rely on `Module.concat\/2`:\n\n iex> x = Sample\n iex> quote do: Module.concat(String, unquote(x))\n {{:., [], [{:__aliases__, [alias: false], [:Module]}, :concat]}, [],\n [{:__aliases__, [alias: false], [:String]}, Sample]}\n\n \"\"\"\n defmacro unquote(:.)(left, right)\n\n @doc \"\"\"\n `alias` is used to setup aliases, often useful with modules names.\n\n ## Examples\n\n `alias` can be used to setup an alias for any module:\n\n defmodule Math do\n alias MyKeyword, as: Keyword\n end\n\n In the example above, we have set up `MyKeyword` to be aliased\n as `Keyword`. So now, any reference to `Keyword` will be\n automatically replaced by `MyKeyword`.\n\n In case one wants to access the original `Keyword`, it can be done\n by accessing `Elixir`:\n\n Keyword.values #=> uses MyKeyword.values\n Elixir.Keyword.values #=> uses Keyword.values\n\n Notice that calling `alias` without the `as:` option automatically\n sets an alias based on the last part of the module. For example:\n\n alias Foo.Bar.Baz\n\n Is the same as:\n\n alias Foo.Bar.Baz, as: Baz\n\n ## Lexical scope\n\n `import`, `require` and `alias` are called directives and all\n have lexical scope. This means you can set up aliases inside\n specific functions and it won't affect the overall scope.\n\n ## Warnings\n\n If you alias a module and you don't use the alias, Elixir is\n going to issue a warning implying the alias is not being used.\n\n In case the alias is generated automatically by a macro,\n Elixir won't emit any warnings though, since the alias\n was not explicitly defined.\n\n Both warning behaviours could be changed by explicitly\n setting the `:warn` option to true or false.\n \"\"\"\n defmacro alias(module, opts)\n\n @doc \"\"\"\n Requires a given module to be compiled and loaded.\n\n ## Examples\n\n Notice that usually modules should not be required before usage,\n the only exception is if you want to use the macros from a module.\n In such cases, you need to explicitly require them.\n\n Let's suppose you created your own `if` implementation in the module\n `MyMacros`. If you want to invoke it, you need to first explicitly\n require the `MyMacros`:\n\n defmodule Math do\n require MyMacros\n MyMacros.if do_something, it_works\n end\n\n An attempt to call a macro that was not loaded will raise an error.\n\n ## Alias shortcut\n\n `require` also accepts `as:` as an option so it automatically sets\n up an alias. Please check `alias` for more information.\n\n \"\"\"\n defmacro require(module, opts)\n\n @doc \"\"\"\n Imports function and macros from other modules.\n\n `import` allows one to easily access functions or macros from\n others modules without using the qualified name.\n\n ## Examples\n\n If you are using several functions from a given module, you can\n import those functions and reference them as local functions,\n for example:\n\n iex> import List\n ...> flatten([1, [2], 3])\n [1,2,3]\n\n ## Selector\n\n By default, Elixir imports functions and macros from the given\n module, except the ones starting with underscore (which are\n usually callbacks):\n\n import List\n\n A developer can filter to import only macros or functions via\n the only option:\n\n import List, only: :functions\n import List, only: :macros\n\n Alternatively, Elixir allows a developer to pass pairs of\n name\/arities to `:only` or `:except` as a fine grained control\n on what to import (or not):\n\n import List, only: [flatten: 1]\n import String, except: [split: 2]\n\n Notice that calling `except` for a previously declared `import`\n simply filters the previously imported elements. For example:\n\n import List, only: [flatten: 1, keyfind: 3]\n import List, except: [flatten: 1]\n\n After the two import calls above, only `List.keyfind\/3` will be\n imported.\n\n ## Lexical scope\n\n It is important to notice that `import` is lexical. This means you\n can import specific macros inside specific functions:\n\n defmodule Math do\n def some_function do\n # 1) Disable `if\/2` from Kernel\n import Kernel, except: [if: 2]\n\n # 2) Require the new `if` macro from MyMacros\n import MyMacros\n\n # 3) Use the new macro\n if do_something, it_works\n end\n end\n\n In the example above, we imported macros from `MyMacros`,\n replacing the original `if\/2` implementation by our own\n within that specific function. All other functions in that\n module will still be able to use the original one.\n\n ## Warnings\n\n If you import a module and you don't use any of the imported\n functions or macros from this module, Elixir is going to issue\n a warning implying the import is not being used.\n\n In case the import is generated automatically by a macro,\n Elixir won't emit any warnings though, since the import\n was not explicitly defined.\n\n Both warning behaviours could be changed by explicitly\n setting the `:warn` option to true or false.\n\n ## Ambiguous function\/macro names\n\n If two modules `A` and `B` are imported and they both contain\n a `foo` function with an arity of `1`, an error is only emitted\n if an ambiguous call to `foo\/1` is actually made; that is, the\n errors are emitted lazily, not eagerly.\n \"\"\"\n defmacro import(module, opts)\n\n @doc \"\"\"\n Returns the current environment information as a `Macro.Env[]` record.\n\n In the environment you can access the current filename,\n line numbers, set up aliases, the current function and others.\n \"\"\"\n defmacro __ENV__\n\n @doc \"\"\"\n Returns the current module name as an atom or `nil` otherwise.\n\n Although the module can be accessed in the `__ENV__`, this macro\n is a convenient shortcut.\n \"\"\"\n defmacro __MODULE__\n\n @doc \"\"\"\n Returns the current directory as a binary.\n\n Although the directory can be accessed as `Path.dirname(__ENV__.file)`,\n this macro is a convenient shortcut.\n \"\"\"\n defmacro __DIR__\n\n @doc \"\"\"\n Accesses an already bound variable in match clauses.\n\n ## Examples\n\n Elixir allows variables to be rebound via static single assignment:\n\n iex> x = 1\n iex> x = 2\n iex> x\n 2\n\n However, in some situations, it is useful to match against an existing\n value, instead of rebinding. This can be done with the `^` special form:\n\n iex> x = 1\n iex> ^x = List.first([1])\n iex> ^x = List.first([2])\n ** (MatchError) no match of right hand side value: 2\n\n Note that `^` always refers to the value of x prior to the match. The\n following example will match:\n\n iex> x = 0\n iex> { x, ^x } = { 1, 0 }\n iex> x\n 1\n\n \"\"\"\n defmacro ^(var)\n\n @doc ~S\"\"\"\n Gets the representation of any expression.\n\n ## Examples\n\n quote do: sum(1, 2, 3)\n #=> { :sum, [], [1, 2, 3] }\n\n ## Explanation\n\n Any Elixir code can be represented using Elixir data structures.\n The building block of Elixir macros is a tuple with three elements,\n for example:\n\n { :sum, [], [1, 2, 3] }\n\n The tuple above represents a function call to `sum` passing 1, 2 and\n 3 as arguments. The tuple elements are:\n\n * The first element of the tuple is always an atom or\n another tuple in the same representation;\n * The second element of the tuple represents metadata;\n * The third element of the tuple are the arguments for the\n function call. The third argument may be an atom, which is\n usually a variable (or a local call);\n\n ## Options\n\n * `:unquote` - When false, disables unquoting. Useful when you have a quote\n inside another quote and want to control what quote is\n able to unquote;\n * `:location` - When set to `:keep`, keeps the current line and file from quote.\n Read the Stacktrace information section below for more information;\n * `:hygiene` - Allows a developer to disable hygiene selectively;\n * `:context` - Sets the resolution context;\n * `:bind_quoted` - Passes a binding to the macro. Whenever a binding is given,\n `unquote` is automatically disabled;\n\n ## Quote literals\n\n Besides the tuple described above, Elixir has a few literals that\n when quoted return themselves. They are:\n\n :sum #=> Atoms\n 1 #=> Integers\n 2.0 #=> Floats\n [1, 2] #=> Lists\n \"strings\" #=> Strings\n {key, value} #=> Tuples with two elements\n\n ## Quote and macros\n\n `quote` is commonly used with macros for code generation. As an exercise,\n let's define a macro that multiplies a number by itself (squared). Note\n there is no reason to define such as a macro (and it would actually be\n seen as a bad practice), but it is simple enough that it allows us to focus\n on the important aspects of quotes and macros:\n\n defmodule Math do\n defmacro squared(x) do\n quote do\n unquote(x) * unquote(x)\n end\n end\n end\n\n We can invoke it as:\n\n import Math\n IO.puts \"Got #{squared(5)}\"\n\n At first, there is nothing in this example that actually reveals it is a\n macro. But what is happening is that, at compilation time, `squared(5)`\n becomes `5 * 5`. The argument `5` is duplicated in the produced code, we\n can see this behaviour in practice though because our macro actually has\n a bug:\n\n import Math\n my_number = fn ->\n IO.puts \"Returning 5\"\n 5\n end\n IO.puts \"Got #{squared(my_number.())}\"\n\n The example above will print:\n\n Returning 5\n Returning 5\n 25\n\n Notice how \"Returning 5\" was printed twice, instead of just once. This is\n because a macro receives an expression and not a value (which is what we\n would expect in a regular function). This means that:\n\n squared(my_number.())\n\n Actually expands to:\n\n my_number.() * my_number.()\n\n Which invokes the function twice, explaining why we get the printed value\n twice! In the majority of the cases, this is actually unexpected behaviour,\n and that's why one of the first things you need to keep in mind when it\n comes to macros is to **not unquote the same value more than once**.\n\n Let's fix our macro:\n\n defmodule Math do\n defmacro squared(x) do\n quote do\n x = unquote(x)\n x * x\n end\n end\n end\n\n Now invoking `square(my_number.())` as before will print the value just\n once.\n\n In fact, this pattern is so common that most of the times you will want\n to use the `bind_quoted` option with `quote`:\n\n defmodule Math do\n defmacro squared(x) do\n quote bind_quoted: [x: x] do\n x * x\n end\n end\n end\n\n `:bind_quoted` will translate to the same code as the example above.\n `:bind_quoted` can be used in many cases and is seen as good practice,\n not only because it helps us from running into common mistakes but also\n because it allows us to leverage other tools exposed by macros, such as\n unquote fragments discussed in some sections below.\n\n Before we finish this brief introduction, you will notice that, even though\n we defined a variable `x` inside our quote:\n\n quote do\n x = unquote(x)\n x * x\n end\n\n When we call:\n\n import Math\n squared(5)\n x #=> ** (RuntimeError) undefined function or variable: x\n\n We can see that `x` did not leak to the user context. This happens\n because Elixir macros are hygienic, a topic we will discuss at length\n in the next sections as well.\n\n ## Hygiene in variables\n\n Consider the following example:\n\n defmodule Hygiene do\n defmacro no_interference do\n quote do: a = 1\n end\n end\n\n require Hygiene\n\n a = 10\n Hygiene.no_interference\n a #=> 10\n\n In the example above, `a` returns 10 even if the macro\n is apparently setting it to 1 because variables defined\n in the macro does not affect the context the macro is executed in.\n If you want to set or get a variable in the caller's context, you\n can do it with the help of the `var!` macro:\n\n defmodule NoHygiene do\n defmacro interference do\n quote do: var!(a) = 1\n end\n end\n\n require NoHygiene\n\n a = 10\n NoHygiene.interference\n a #=> 1\n\n Note that you cannot even access variables defined in the same\n module unless you explicitly give it a context:\n\n defmodule Hygiene do\n defmacro write do\n quote do\n a = 1\n end\n end\n\n defmacro read do\n quote do\n a\n end\n end\n end\n\n Hygiene.write\n Hygiene.read\n #=> ** (RuntimeError) undefined function or variable: a\n\n For such, you can explicitly pass the current module scope as\n argument:\n\n defmodule ContextHygiene do\n defmacro write do\n quote do\n var!(a, ContextHygiene) = 1\n end\n end\n\n defmacro read do\n quote do\n var!(a, ContextHygiene)\n end\n end\n end\n\n ContextHygiene.write\n ContextHygiene.read\n #=> 1\n\n Hygiene for variables can be disabled overall as:\n\n quote hygiene: [vars: false], do: x\n\n ## Hygiene in aliases\n\n Aliases inside quote are hygienic by default.\n Consider the following example:\n\n defmodule Hygiene do\n alias HashDict, as: D\n\n defmacro no_interference do\n quote do: D.new\n end\n end\n\n require Hygiene\n Hygiene.no_interference #=> #HashDict<[]>\n\n Notice that, even though the alias `D` is not available\n in the context the macro is expanded, the code above works\n because `D` still expands to `HashDict`.\n\n Similarly, even if we defined an alias with the same name\n before invoking a macro, it won't affect the macro's result:\n\n defmodule Hygiene do\n alias HashDict, as: D\n\n defmacro no_interference do\n quote do: D.new\n end\n end\n\n require Hygiene\n alias SomethingElse, as: D\n Hygiene.no_interference #=> #HashDict<[]>\n\n In some cases, you want to access an alias or a module defined\n in the caller. For such, you can use the `alias!` macro:\n\n defmodule Hygiene do\n # This will expand to Elixir.Nested.hello\n defmacro no_interference do\n quote do: Nested.hello\n end\n\n # This will expand to Nested.hello for\n # whatever is Nested in the caller\n defmacro interference do\n quote do: alias!(Nested).hello\n end\n end\n\n defmodule Parent do\n defmodule Nested do\n def hello, do: \"world\"\n end\n\n require Hygiene\n Hygiene.no_interference\n #=> ** (UndefinedFunctionError) ...\n\n Hygiene.interference\n #=> \"world\"\n end\n\n ## Hygiene in imports\n\n Similar to aliases, imports in Elixir are hygienic. Consider the\n following code:\n\n defmodule Hygiene do\n defmacrop get_size do\n quote do\n size(\"hello\")\n end\n end\n\n def return_size do\n import Kernel, except: [size: 1]\n get_size\n end\n end\n\n Hygiene.return_size #=> 5\n\n Notice how `return_size` returns 5 even though the `size\/1`\n function is not imported. In fact, even if `return_size` imported\n a function from another module, it wouldn't affect the function\n result:\n\n def return_size do\n import Dict, only: [size: 1]\n get_size\n end\n\n Calling this new `return_size` will still return 5 as result.\n\n Elixir is smart enough to delay the resolution to the latest\n moment possible. So, if you call `size(\"hello\")` inside quote,\n but no `size\/1` function is available, it is then expanded in\n the caller:\n\n defmodule Lazy do\n defmacrop get_size do\n import Kernel, except: [size: 1]\n\n quote do\n size([a: 1, b: 2])\n end\n end\n\n def return_size do\n import Kernel, except: [size: 1]\n import Dict, only: [size: 1]\n get_size\n end\n end\n\n Lazy.return_size #=> 2\n\n As in aliases, import expansion can be explicitly disabled\n via the `hygiene: [imports: false]` option.\n\n ## Stacktrace information\n\n When defining functions via macros, developers have the option of\n choosing if runtime errors will be reported from the caller or from\n inside the quote. Let's see an example:\n\n # adder.ex\n defmodule Adder do\n @doc \"Defines a function that adds two numbers\"\n defmacro defadd do\n quote location: :keep do\n def add(a, b), do: a + b\n end\n end\n end\n\n # sample.ex\n defmodule Sample do\n import Adder\n defadd\n end\n\n When using `location: :keep` and invalid arguments are given to\n `Sample.add\/2`, the stacktrace information will point to the file\n and line inside the quote. Without `location: :keep`, the error is\n reported to where `defadd` was invoked. Note `location: :keep` affects\n only definitions inside the quote.\n\n ## Binding and unquote fragments\n\n Elixir quote\/unquote mechanisms provides a functionality called\n unquote fragments. Unquote fragments provide an easy way to generate\n functions on the fly. Consider this example:\n\n kv = [foo: 1, bar: 2]\n Enum.each kv, fn { k, v } ->\n def unquote(k)(), do: unquote(v)\n end\n\n In the example above, we have generated the functions `foo\/0` and\n `bar\/0` dynamically. Now, imagine that, we want to convert this\n functionality into a macro:\n\n defmacro defkv(kv) do\n Enum.map kv, fn { k, v } ->\n quote do\n def unquote(k)(), do: unquote(v)\n end\n end\n end\n\n We can invoke this macro as:\n\n defkv [foo: 1, bar: 2]\n\n However, we can't invoke it as follows:\n\n kv = [foo: 1, bar: 2]\n defkv kv\n\n This is because the macro is expecting its arguments to be a\n keyword list at **compilation** time. Since in the example above\n we are passing the representation of the variable `kv`, our\n code fails.\n\n This is actually a common pitfall when developing macros. In\n practice, we want to avoid doing work at compilation time as\n much as possible. That said, let's attempt to improve our macro:\n\n defmacro defkv(kv) do\n quote do\n Enum.each unquote(kv), fn { k, v } ->\n def unquote(k)(), do: unquote(v)\n end\n end\n end\n\n If you try to run our new macro, you will notice it won't\n even compile, complaining that the variables `k` and `v`\n does not exist. This is because of the ambiguity: `unquote(k)`\n can either be an unquote fragment, as previously, or a regular\n unquote as in `unquote(kv)`.\n\n One solution to this problem is to disable unquoting in the\n macro, however, doing that would make it impossible to inject the\n `kv` representation into the tree. That's when the `:bind_quoted`\n option comes to the rescue (again!). By using `:bind_quoted`, we\n can automatically disable unquoting while still injecting the\n desired variables into the tree:\n\n defmacro defkv(kv) do\n quote bind_quoted: [kv: kv] do\n Enum.each kv, fn { k, v } ->\n def unquote(k)(), do: unquote(v)\n end\n end\n end\n\n In fact, the `:bind_quoted` option is recommended every time\n one desires to inject a value into the quote.\n \"\"\"\n defmacro quote(opts, block)\n\n @doc \"\"\"\n Unquotes the given expression from inside a macro.\n\n ## Examples\n\n Imagine the situation you have a variable `name` and\n you want to inject it inside some quote. The first attempt\n would be:\n\n value = 13\n quote do: sum(1, value, 3)\n\n Which would then return:\n\n { :sum, [], [1, { :value, [], quoted }, 3] }\n\n Which is not the expected result. For this, we use unquote:\n\n value = 13\n quote do: sum(1, unquote(value), 3)\n #=> { :sum, [], [1, 13, 3] }\n\n \"\"\"\n defmacro unquote(:unquote)(expr)\n\n @doc \"\"\"\n Unquotes the given list expanding its arguments. Similar\n to unquote.\n\n ## Examples\n\n values = [2, 3, 4]\n quote do: sum(1, unquote_splicing(values), 5)\n #=> { :sum, [], [1, 2, 3, 4, 5] }\n\n \"\"\"\n defmacro unquote(:unquote_splicing)(expr)\n\n @doc ~S\"\"\"\n Comprehensions allow you to quickly build a data structure from\n an enumerable or a bitstring.\n\n Let's start with an example:\n\n iex> for n <- [1, 2, 3, 4], do: n * 2\n [2, 4, 6, 8]\n\n A comprehension accepts many generators and filters. Enumerable\n generators are defined using `<-`:\n\n # A list generator:\n iex> for n <- [1, 2, 3, 4], do: n * 2\n [2, 4, 6, 8]\n\n # A comprehension with two generators\n iex> for x <- [1, 2], y <- [2, 3], do: x*y\n [2, 3, 4, 6]\n\n Filters can also be given:\n\n # A comprehension with a generator and a filter\n iex> for n <- [1, 2, 3, 4, 5, 6], rem(n, 2) == 0, do: n\n [2, 4, 6]\n\n Bitstring generators are also supported and are very useful when you\n need to organize bitstring streams:\n\n iex> pixels = <<213, 45, 132, 64, 76, 32, 76, 0, 0, 234, 32, 15>>\n iex> for <>, do: {r, g, b}\n [{213,45,132},{64,76,32},{76,0,0},{234,32,15}]\n\n Variable assignments inside the comprehension, be it in generators,\n filters or inside the block, are not reflected outside of the\n comprehension.\n\n ## Into\n\n In the examples above, the result returned by the comprehension was\n always a list. The returned result can be configured by passing an\n `:into` option, that accepts any structure as long as it implements\n the `Collectable` protocol.\n\n For example, we can use bitstring generators with the `:into` option\n to easily remove all spaces in a string:\n\n iex> for <>, c != ?\\s, into: \"\", do: <>\n \"helloworld\"\n\n The `IO` module provides streams, that are both `Enumerable` and\n `Collectable`, here is an upcase echo server using comprehensions:\n\n for line <- IO.stream(:stdio), into: IO.stream(:stdio) do\n String.upcase(line)\n end\n\n \"\"\"\n defmacro for(args)\n\n @doc \"\"\"\n Defines an anonymous function.\n\n ## Examples\n\n iex> add = fn a, b -> a + b end\n iex> add.(1, 2)\n 3\n\n \"\"\"\n defmacro unquote(:fn)(clauses)\n\n @doc \"\"\"\n Internal special form for block expressions.\n\n This is the special form used whenever we have a block\n of expressions in Elixir. This special form is private\n and should not be invoked directly:\n\n iex> quote do: (1; 2; 3)\n { :__block__, [], [1, 2, 3] }\n\n \"\"\"\n defmacro __block__(args)\n\n @doc \"\"\"\n Captures an anonymous function.\n\n The most common format to capture a function is via module,\n name and arity:\n\n iex> fun = &Kernel.is_atom\/1\n iex> fun.(:atom)\n true\n iex> fun.(\"string\")\n false\n\n Local functions, including private ones, and imported ones\n can also be captured by omitting the module name:\n\n &local_function\/1\n\n A capture also allows the captured functions to be partially\n applied, for example:\n\n iex> fun = &is_record(&1, Range)\n iex> fun.(1..3)\n true\n\n In the example above, we use &1 as a placeholder, generating\n a function with one argument. We could also use `&2` and `&3`\n to delimit more arguments:\n\n iex> fun = &is_record(&1, &2)\n iex> fun.(1..3, Range)\n true\n\n Since operators are calls, they are also supported, although\n they require explicit parentheses around:\n\n iex> fun = &(&1 + &2)\n iex> fun.(1, 2)\n 3\n\n And even more complex call expressions:\n\n iex> fun = &(&1 + &2 + &3)\n iex> fun.(1, 2, 3)\n 6\n\n Record-like calls are also allowed:\n\n iex> fun = &(&1.first)\n iex> fun.(1..3)\n 1\n\n Remember tuple and lists are represented as calls in the AST and\n therefore are also allowed:\n\n iex> fun = &{&1, &2}\n iex> fun.(1, 2)\n { 1, 2 }\n\n iex> fun = &[&1|&2]\n iex> fun.(1, 2)\n [1|2]\n\n Anything that is not a call is not allowed though, examples:\n\n # An atom is not a call\n &:foo\n\n # A var is not a call\n var = 1\n &var\n\n # A block expression is not a call\n &(foo(&1, &2); &3 + &4)\n\n \"\"\"\n defmacro unquote(:&)(expr)\n\n @doc \"\"\"\n Internal special form to hold aliases information.\n\n It is usually compiled to an atom:\n\n iex> quote do: Foo.Bar\n {:__aliases__, [alias: false], [:Foo, :Bar]}\n\n Elixir represents `Foo.Bar` as `__aliases__` so calls can be\n unambiguously identified by the operator `:.`. For example:\n\n iex> quote do: Foo.bar\n {{:., [], [{:__aliases__, [alias: false], [:Foo]}, :bar]}, [], []}\n\n Whenever an expression iterator sees a `:.` as the tuple key,\n it can be sure that it represents a call and the second argument\n in the list is an atom.\n\n On the other hand, aliases holds some properties:\n\n 1) The head element of aliases can be any term;\n\n 2) The tail elements of aliases are guaranteed to always be atoms;\n\n 3) When the head element of aliases is the atom `:Elixir`, no expansion happen;\n\n 4) When the head element of aliases is not an atom, it is expanded at runtime:\n\n quote do: some_var.Foo\n {:__aliases__, [], [{:some_var, [], Elixir}, :Foo]}\n\n Since `some_var` is not available at compilation time, the compiler\n expands such expression to:\n\n Module.concat [some_var, Foo]\n\n \"\"\"\n defmacro __aliases__(args)\n\n @doc \"\"\"\n Calls the overriden function when overriding it with `defoverridable`.\n See `Kernel.defoverridable` for more information and documentation.\n \"\"\"\n defmacro super(args)\n\n @doc \"\"\"\n Matches the given expression against the given clauses.\n\n ## Examples\n\n case thing do\n { :selector, i, value } when is_integer(i) ->\n value\n value ->\n value\n end\n\n In the example above, we match `thing` against each clause \"head\"\n and execute the clause \"body\" corresponding to the first clause\n that matches. If no clause matches, an error is raised.\n\n ## Variables handling\n\n Notice that variables bound in a clause \"head\" do not leak to the\n outer context:\n\n case data do\n { :ok, value } -> value\n :error -> nil\n end\n\n value #=> unbound variable value\n\n However, variables explicitly bound in the clause \"body\" are\n accessible from the outer context:\n\n value = 7\n\n case lucky? do\n false -> value = 13\n true -> true\n end\n\n value #=> 7 or 13\n\n In the example above, value is going to be `7` or `13` depending on\n the value of `lucky?`. In case `value` has no previous value before\n case, clauses that do not explicitly bind a value have the variable\n bound to nil.\n \"\"\"\n defmacro case(condition, blocks)\n\n @doc \"\"\"\n Evaluate the given expressions and handle any error, exit\n or throw that may have happened.\n\n ## Examples\n\n try do\n do_something_that_may_fail(some_arg)\n rescue\n ArgumentError ->\n IO.puts \"Invalid argument given\"\n catch\n value ->\n IO.puts \"caught \\#{value}\"\n else\n value ->\n IO.puts \"Success! The result was \\#{value}\"\n after\n IO.puts \"This is printed regardless if it failed or succeed\"\n end\n\n The rescue clause is used to handle exceptions, while the catch\n clause can be used to catch thrown values. The else clause can\n be used to control flow based on the result of the expression.\n Catch, rescue and else clauses work based on pattern matching.\n\n Note that calls inside `try` are not tail recursive since the VM\n needs to keep the stacktrace in case an exception happens.\n\n ## Rescue clauses\n\n Besides relying on pattern matching, rescue clauses provides some\n conveniences around exceptions that allows one to rescue an\n exception by its name. All the following formats are valid rescue\n expressions:\n\n try do\n UndefinedModule.undefined_function\n rescue\n UndefinedFunctionError -> nil\n end\n\n try do\n UndefinedModule.undefined_function\n rescue\n [UndefinedFunctionError] -> nil\n end\n\n # rescue and bind to x\n try do\n UndefinedModule.undefined_function\n rescue\n x in [UndefinedFunctionError] -> nil\n end\n\n # rescue all and bind to x\n try do\n UndefinedModule.undefined_function\n rescue\n x -> nil\n end\n\n ## Catching exits and Erlang errors\n\n The catch clause works exactly the same as in erlang. Therefore,\n one can also handle exits\/errors coming from Erlang as below:\n\n try do\n exit(1)\n catch\n :exit, 1 -> IO.puts \"Exited with 1\"\n end\n\n try do\n error(:sample)\n catch\n :error, :sample ->\n IO.puts \"sample error\"\n end\n\n Although the second form should be avoided in favor of raise\/rescue\n control mechanisms.\n\n ## Else clauses\n\n Else clauses allow the result of the expression to be pattern\n matched on:\n\n x = 2\n try do\n 1 \/ x\n rescue\n ArithmeticError ->\n :infinity\n else\n y when y < 1 and y > -1 ->\n :small\n _ ->\n :large\n end\n\n If an else clause is not present the result of the expression will\n be return, if no exceptions are raised:\n\n x = 1\n ^x =\n try do\n 1 \/ x\n rescue\n ArithmeticError ->\n :infinity\n end\n\n However when an else clause is present but the result of the expression\n does not match any of the patterns an exception will be raised. This\n exception will not be caught by a catch or rescue in the same try:\n\n x = 1\n try do\n try do\n 1 \/ x\n rescue\n # The TryClauseError can not be rescued here:\n TryClauseError ->\n :error_a\n else\n 0 ->\n :small\n end\n rescue\n # The TryClauseError is rescued here:\n TryClauseError ->\n :error_b\n end\n\n Similarly an exception inside an else clause is not caught or rescued\n inside the same try:\n\n try do\n try do\n nil\n catch\n # The exit(1) call below can not be caught here:\n :exit, _ ->\n :exit_a\n else\n _ ->\n exit(1)\n end\n catch\n # The exit is caught here:\n :exit, _ ->\n :exit_b\n end\n\n This means the VM no longer needs to keep the stacktrace once inside\n an else clause and so tail recursion is possible when using a `try`\n with a tail call as the final call inside an else clause. The same\n is true for rescue and catch clauses.\n\n ## Variable handling\n\n Since an expression inside `try` may not have been evaluated\n due to an exception, any variable created inside `try` cannot\n be accessed externally. For instance:\n\n try do\n x = 1\n do_something_that_may_fail(same_arg)\n :ok\n catch\n _, _ -> :failed\n end\n\n x #=> unbound variable `x`\n\n In the example above, `x` cannot be accessed since it was defined\n inside the `try` clause. A common practice to address this issue\n is to return the variables defined inside `try`:\n\n x =\n try do\n x = 1\n do_something_that_may_fail(same_arg)\n x\n catch\n _, _ -> :failed\n end\n\n \"\"\"\n defmacro try(args)\n\n @doc \"\"\"\n Checks if there is a message matching the given clauses\n in the current process mailbox.\n\n In case there is no such message, the current process hangs\n until a message arrives or waits until a given timeout value.\n\n ## Examples\n\n receive do\n { :selector, i, value } when is_integer(i) ->\n value\n value when is_atom(value) ->\n value\n _ ->\n IO.puts :stderr, \"Unexpected message received\"\n end\n\n An optional after clause can be given in case the message was not\n received after the specified period of time:\n\n receive do\n { :selector, i, value } when is_integer(i) ->\n value\n value when is_atom(value) ->\n value\n _ ->\n IO.puts :stderr, \"Unexpected message received\"\n after\n 5000 ->\n IO.puts :stderr, \"No message in 5 seconds\"\n end\n\n The `after` clause can be specified even if there are no match clauses.\n There are two special cases for the timeout value given to `after`\n\n * `:infinity` - The process should wait indefinitely for a matching\n message, this is the same as not using a timeout.\n\n * 0 - if there is no matching message in the mailbox, the timeout\n will occur immediately.\n\n ## Variables handling\n\n The `receive` special form handles variables exactly as the `case`\n special macro. For more information, check the docs for `case\/2`.\n \"\"\"\n defmacro receive(args)\nend\n","old_contents":"defmodule Kernel.SpecialForms do\n @moduledoc \"\"\"\n In this module we define Elixir special forms. Special forms\n cannot be overridden by the developer and are the basic\n building blocks of Elixir code.\n\n Some of those forms are lexical (like `alias`, `case`, etc).\n The macros `{}` and `<<>>` are also special forms used to define\n tuple and binary data structures respectively.\n\n This module also documents Elixir's pseudo variables (`__ENV__`,\n `__MODULE__`, `__DIR__` and `__CALLER__`). Pseudo variables return\n information about Elixir's compilation environment and can only\n be read, never assigned to.\n\n Finally, it also documents 2 special forms, `__block__` and\n `__aliases__`, which are not intended to be called directly by the\n developer but they appear in quoted contents since they are essential\n in Elixir's constructs.\n \"\"\"\n\n @doc \"\"\"\n Creates a tuple.\n\n Only two item tuples are considered literals in Elixir.\n Therefore all other tuples are represented in the AST\n as a call to the special form `:{}`.\n\n Conveniences for manipulating tuples can be found in the\n `Tuple` module. Some functions for working with tuples are\n also available in `Kernel`, namely `Kernel.elem\/2`,\n `Kernel.set_elem\/3` and `Kernel.tuple_size\/1`.\n\n ## Examples\n\n iex> { 1, 2, 3 }\n { 1, 2, 3 }\n iex> quote do: { 1, 2, 3 }\n { :{}, [], [1,2,3] }\n\n \"\"\"\n defmacro unquote(:{})(args)\n\n @doc \"\"\"\n Creates a map.\n\n Maps are key-value stores where keys are compared \n using the match operator (`===`). Maps can be created with\n the `%{}` special form where keys are associated via `=>`:\n\n %{ 1 => 2 }\n\n Maps also support the keyword notation, as other special forms,\n as long as they are at the end of the argument list:\n\n %{ hello: :world, with: :keywords }\n %{ :hello => :world, with: :keywords }\n\n If a map has duplicated keys, the last key will always have\n higher precedence:\n\n iex> %{ a: :b, a: :c }\n %{ a: :c }\n\n Conveniences for manipulating maps can be found in the\n `Map` module.\n\n ## Access syntax\n\n Besides the access functions available in the `Map` module,\n like `Map.get\/3` and `Map.fetch\/2`, a map can be accessed using the\n `.` operator:\n\n iex> map = %{ a: :b }\n iex> map.a\n :b\n\n Note that the `.` operator expects the field to exist in the map.\n If not, an `ArgumentError` is raised.\n\n ## Update syntax\n\n Maps also support an update syntax:\n\n iex> map = %{ :a => :b }\n iex> %{ map | :a => :c }\n %{ :a => :c }\n\n Notice the update syntax requires the given keys to exist.\n Trying to update a key that does not exist will raise an `ArgumentError`.\n\n ## AST representation\n\n Regardless if `=>` or the keywords syntax is used, Maps are\n always represented internally as a list of two-items tuples\n for simplicity:\n\n iex> quote do: %{ :a => :b, c: :d }\n { :%{}, [], [{:a, :b}, {:c, :d}] }\n\n \"\"\"\n defmacro unquote(:%{})(args)\n\n @doc \"\"\"\n Creates a struct.\n\n A struct is a tagged map that allows developers to provide\n default values for keys, tags to be used in polymorphic\n dispatches and compile time assertions.\n\n To define a struct, you just need to implement the `__struct__\/0`\n function in a module:\n\n defmodule User do\n def __struct__ do\n %{ name: \"jos\u00e9\", age: 27 }\n end\n end\n\n Now a struct can be created as follow:\n\n %User{}\n\n Underneath, a struct is just a map with a `__struct__` field\n pointing to the User module:\n\n %User{} == %{ __struct__: User, name: \"jos\u00e9\", age: 27 }\n\n A struct also validates the given keys are part of the defined\n struct. The example below will fail because there is no key\n `:full_name` in the user struct:\n\n %User{ full_name: \"Jos\u00e9 Valim\" }\n\n Note that a struct specifies a minimum set of keys required\n for operations. Other keys can be added to structs via the\n regular map operations:\n\n user = %User{}\n %{ user | a_non_struct_key: :value }\n\n An update operation specific for structs is also available:\n\n %User{ user | age: 28 }\n\n The syntax above will guarantee the given keys are valid at\n compilation time and it will guarantee at runtime the given\n argument is a struct, failing with `BadStructError` otherwise.\n\n Check `Kernel.defprotocol\/2` for more information on how structs\n can be used with protocols for polymorphic dispatch.\n \"\"\"\n defmacro unquote(:%)(struct, map)\n\n @doc \"\"\"\n Defines a new bitstring.\n\n ## Examples\n\n iex> << 1, 2, 3 >>\n << 1, 2, 3 >>\n\n ## Bitstring types\n\n A bitstring is made of many segments. Each segment has a\n type, which defaults to integer:\n\n iex> <<1, 2, 3>>\n <<1, 2, 3>>\n\n Elixir also accepts by default the segment to be a literal\n string or a literal char list, which are by expanded to integers:\n\n iex> <<0, \"foo\">>\n <<0, 102, 111, 111>>\n\n Any other type needs to be explicitly tagged. For example,\n in order to store a float type in the binary, one has to do:\n\n iex> <<3.14 :: float>>\n <<64, 9, 30, 184, 81, 235, 133, 31>>\n\n This also means that variables need to be explicitly tagged,\n otherwise Elixir defaults to integer:\n\n iex> rest = \"oo\"\n iex> <<102, rest>>\n ** (ArgumentError) argument error\n\n We can solve this by explicitly tagging it as a binary:\n\n <<102, rest :: binary>>\n\n The type can be integer, float, bitstring\/bits, binary\/bytes,\n utf8, utf16 or utf32, e.g.:\n\n <<102 :: float, rest :: binary>>\n\n An integer can be any arbitrary precision integer. A float is an\n IEEE 754 binary32 or binary64 floating point number. A bitstring\n is an arbitrary series of bits. A binary is a special case of\n bitstring that has a total size divisible by 8.\n\n The utf8, utf16, and utf32 types are for UTF code points. They\n can also be applied to literal strings and char lists:\n\n iex> <<\"foo\" :: utf16>>\n <<0,102,0,111,0,111>>\n\n The bits type is an alias for bitstring. The bytes type is an\n alias for binary.\n\n The signedness can also be given as signed or unsigned. The\n signedness only matters for matching. If unspecified, it\n defaults to unsigned. Example:\n\n iex> <<-100 :: signed, _rest :: binary>> = <<-100, \"foo\">>\n <<156,102,111,111>>\n\n This match would have failed if we did not specify that the\n value -100 is signed. If we're matching into a variable instead\n of a value, the signedness won't be checked; rather, the number\n will simply be interpreted as having the given (or implied)\n signedness, e.g.:\n\n iex> <> = <<-100, \"foo\">>\n ...> val\n 156\n\n Here, `val` is interpreted as unsigned.\n\n Signedness is only relevant on integers.\n\n The endianness of a segment can be big, little or native (the\n latter meaning it will be resolved at VM load time). Passing\n many options can be done by giving a list:\n\n <<102 :: [integer, native], rest :: binary>>\n\n Or:\n\n <<102 :: [unsigned, big, integer], rest :: binary>>\n\n And so on.\n\n Endianness only makes sense for integers and some UTF code\n point types (utf16 and utf32).\n\n Finally, we can also specify size and unit for each segment. The\n unit is multiplied by the size to give the effective size of\n the segment:\n\n iex> <<102, _rest :: [size(2), unit(8)]>> = \"foo\"\n \"foo\"\n\n iex> <<102, _rest :: size(16)>> = \"foo\"\n \"foo\"\n\n iex> <<102, _rest :: size(32)>> = \"foo\"\n ** (MatchError) no match of right hand side value: \"foo\"\n\n In the example above, the first two expressions matches\n because the string \"foo\" takes 24 bits and we are matching\n against a segment of 24 bits as well, 8 of which are taken by\n the integer 102 and the remaining 16 bits are specified on\n the rest. On the last example, we expect a rest with size 32,\n which won't match.\n\n Size and unit are not applicable to utf8, utf16, and utf32.\n\n The default size for integers is 8. For floats, it is 64. For\n binaries, it is the size of the binary. Only the last binary\n in a binary match can use the default size (all others must\n have their size specified explicitly). Bitstrings do not have\n a default size.\n\n Size can also be specified using a syntax shortcut. Instead of\n writing `size(8)`, one can write just `8` and it will be interpreted\n as `size(8)`\n\n iex> << 1 :: 3 >> == << 1 :: size(3) >>\n true\n\n The default unit for integers, floats, and bitstrings is 1. For\n binaries, it is 8.\n\n For floats, unit * size must result in 32 or 64, corresponding\n to binary32 and binary64, respectively.\n \"\"\"\n defmacro unquote(:<<>>)(args)\n\n @doc \"\"\"\n Defines a remote call or an alias.\n\n The dot (`.`) in Elixir can be used for remote calls:\n\n iex> String.downcase(\"FOO\")\n \"foo\"\n\n In this example above, we have used `.` to invoke `downcase` in the\n `String` alias, passing \"FOO\" as argument. We can also use the dot\n for creating aliases:\n\n iex> Hello.World\n Hello.World\n\n This time, we have joined two aliases, defining the final alias\n `Hello.World`.\n\n ## Syntax\n\n The right side of `.` may be a word starting in upcase, which represents\n an alias, a word starting with lowercase or underscore, any valid language\n operator or any name wrapped in single- or double-quotes. Those are all valid\n examples:\n\n iex> Kernel.Sample\n Kernel.Sample\n iex> Kernel.length([1,2,3])\n 3\n iex> Kernel.+(1, 2)\n 3\n iex> Kernel.\"length\"([1,2,3])\n 3\n iex> Kernel.'+'(1, 2)\n 3\n\n Note that `Kernel.\"HELLO\"` will be treated as a remote call and not an alias.\n This choice was done so every time single- or double-quotes are used, we have\n a remote call irregardless of the quote contents. This decision is also reflected\n in the quoted expressions discussed below.\n\n ## Runtime (dynamic) behaviour\n\n The result returned by `.` is always specified by the right-side:\n\n iex> x = String\n iex> x.downcase(\"FOO\")\n \"foo\"\n iex> x.Sample\n String.Sample\n\n In case the right-side is also dynamic, `.`'s behaviour can be reproduced\n at runtime via `apply\/3` and `Module.concat\/2`:\n\n iex> apply(:erlang, :+, [1,2])\n 3\n iex> Module.concat(Kernel, Sample)\n Kernel.Sample\n\n ## Quoted expression\n\n When `.` is used, the quoted expression may take two distinct\n forms. When the right side starts with a lowercase letter (or\n underscore):\n\n iex> quote do: String.downcase(\"FOO\")\n {{:., [], [{:__aliases__, [alias: false], [:String]}, :downcase]}, [], [\"FOO\"]}\n\n Notice we have an inner tuple, containing the atom `:.` representing\n the dot as first element:\n\n {:., [], [{:__aliases__, [alias: false], [:String]}, :downcase]}\n\n This tuple follows the general quoted expression structure in Elixir,\n with the name as first argument, some keyword list as metadata as second,\n and the number of arguments as third. In this case, the arguments is the\n alias `String` and the atom `:downcase`. The second argument is **always**\n an atom:\n\n iex> quote do: String.\"downcase\"(\"FOO\")\n {{:., [], [{:__aliases__, [alias: false], [:String]}, :downcase]}, [], [\"FOO\"]}\n\n The tuple containing `:.` is wrapped in another tuple, which actually\n represents the function call, and has `\"FOO\"` as argument.\n\n When the right side is an alias (i.e. starts with uppercase), we get instead:\n\n iex> quote do: Hello.World\n {:__aliases__, [alias: false], [:Hello, :World]}\n\n We got into more details about aliases in the `__aliases__` special form\n documentation.\n\n ## Unquoting\n\n We can also use unquote to generate a remote call in a quoted expression:\n\n iex> x = :downcase\n iex> quote do: String.unquote(x)(\"FOO\")\n {{:., [], [{:__aliases__, [alias: false], [:String]}, :downcase]}, [], [\"FOO\"]}\n\n Similar to `Kernel.\"HELLO\"`, `unquote(x)` will always generate a remote call,\n independent of the value of `x`. To generate an alias via the quoted expression,\n one needs to rely on `Module.concat\/2`:\n\n iex> x = Sample\n iex> quote do: Module.concat(String, unquote(x))\n {{:., [], [{:__aliases__, [alias: false], [:Module]}, :concat]}, [],\n [{:__aliases__, [alias: false], [:String]}, Sample]}\n\n \"\"\"\n defmacro unquote(:.)(left, right)\n\n @doc \"\"\"\n `alias` is used to setup aliases, often useful with modules names.\n\n ## Examples\n\n `alias` can be used to setup an alias for any module:\n\n defmodule Math do\n alias MyKeyword, as: Keyword\n end\n\n In the example above, we have set up `MyKeyword` to be aliased\n as `Keyword`. So now, any reference to `Keyword` will be\n automatically replaced by `MyKeyword`.\n\n In case one wants to access the original `Keyword`, it can be done\n by accessing `Elixir`:\n\n Keyword.values #=> uses MyKeyword.values\n Elixir.Keyword.values #=> uses Keyword.values\n\n Notice that calling `alias` without the `as:` option automatically\n sets an alias based on the last part of the module. For example:\n\n alias Foo.Bar.Baz\n\n Is the same as:\n\n alias Foo.Bar.Baz, as: Baz\n\n ## Lexical scope\n\n `import`, `require` and `alias` are called directives and all\n have lexical scope. This means you can set up aliases inside\n specific functions and it won't affect the overall scope.\n\n ## Warnings\n\n If you alias a module and you don't use the alias, Elixir is\n going to issue a warning implying the alias is not being used.\n\n In case the alias is generated automatically by a macro,\n Elixir won't emit any warnings though, since the alias\n was not explicitly defined.\n\n Both warning behaviours could be changed by explicitly\n setting the `:warn` option to true or false.\n \"\"\"\n defmacro alias(module, opts)\n\n @doc \"\"\"\n Requires a given module to be compiled and loaded.\n\n ## Examples\n\n Notice that usually modules should not be required before usage,\n the only exception is if you want to use the macros from a module.\n In such cases, you need to explicitly require them.\n\n Let's suppose you created your own `if` implementation in the module\n `MyMacros`. If you want to invoke it, you need to first explicitly\n require the `MyMacros`:\n\n defmodule Math do\n require MyMacros\n MyMacros.if do_something, it_works\n end\n\n An attempt to call a macro that was not loaded will raise an error.\n\n ## Alias shortcut\n\n `require` also accepts `as:` as an option so it automatically sets\n up an alias. Please check `alias` for more information.\n\n \"\"\"\n defmacro require(module, opts)\n\n @doc \"\"\"\n Imports function and macros from other modules.\n\n `import` allows one to easily access functions or macros from\n others modules without using the qualified name.\n\n ## Examples\n\n If you are using several functions from a given module, you can\n import those functions and reference them as local functions,\n for example:\n\n iex> import List\n ...> flatten([1, [2], 3])\n [1,2,3]\n\n ## Selector\n\n By default, Elixir imports functions and macros from the given\n module, except the ones starting with underscore (which are\n usually callbacks):\n\n import List\n\n A developer can filter to import only macros or functions via\n the only option:\n\n import List, only: :functions\n import List, only: :macros\n\n Alternatively, Elixir allows a developer to pass pairs of\n name\/arities to `:only` or `:except` as a fine grained control\n on what to import (or not):\n\n import List, only: [flatten: 1]\n import String, except: [split: 2]\n\n Notice that calling `except` for a previously declared `import`\n simply filters the previously imported elements. For example:\n\n import List, only: [flatten: 1, keyfind: 3]\n import List, except: [flatten: 1]\n\n After the two import calls above, only `List.keyfind\/3` will be\n imported.\n\n ## Lexical scope\n\n It is important to notice that `import` is lexical. This means you\n can import specific macros inside specific functions:\n\n defmodule Math do\n def some_function do\n # 1) Disable `if\/2` from Kernel\n import Kernel, except: [if: 2]\n\n # 2) Require the new `if` macro from MyMacros\n import MyMacros\n\n # 3) Use the new macro\n if do_something, it_works\n end\n end\n\n In the example above, we imported macros from `MyMacros`,\n replacing the original `if\/2` implementation by our own\n within that specific function. All other functions in that\n module will still be able to use the original one.\n\n ## Warnings\n\n If you import a module and you don't use any of the imported\n functions or macros from this module, Elixir is going to issue\n a warning implying the import is not being used.\n\n In case the import is generated automatically by a macro,\n Elixir won't emit any warnings though, since the import\n was not explicitly defined.\n\n Both warning behaviours could be changed by explicitly\n setting the `:warn` option to true or false.\n\n ## Ambiguous function\/macro names\n\n If two modules `A` and `B` are imported and they both contain\n a `foo` function with an arity of `1`, an error is only emitted\n if an ambiguous call to `foo\/1` is actually made; that is, the\n errors are emitted lazily, not eagerly.\n \"\"\"\n defmacro import(module, opts)\n\n @doc \"\"\"\n Returns the current environment information as a `Macro.Env[]` record.\n\n In the environment you can access the current filename,\n line numbers, set up aliases, the current function and others.\n \"\"\"\n defmacro __ENV__\n\n @doc \"\"\"\n Returns the current module name as an atom or `nil` otherwise.\n\n Although the module can be accessed in the `__ENV__`, this macro\n is a convenient shortcut.\n \"\"\"\n defmacro __MODULE__\n\n @doc \"\"\"\n Returns the current directory as a binary.\n\n Although the directory can be accessed as `Path.dirname(__ENV__.file)`,\n this macro is a convenient shortcut.\n \"\"\"\n defmacro __DIR__\n\n @doc \"\"\"\n Accesses an already bound variable in match clauses.\n\n ## Examples\n\n Elixir allows variables to be rebound via static single assignment:\n\n iex> x = 1\n iex> x = 2\n iex> x\n 2\n\n However, in some situations, it is useful to match against an existing\n value, instead of rebinding. This can be done with the `^` special form:\n\n iex> x = 1\n iex> ^x = List.first([1])\n iex> ^x = List.first([2])\n ** (MatchError) no match of right hand side value: 2\n\n Note that `^` always refers to the value of x prior to the match. The\n following example will match:\n\n iex> x = 0\n iex> { x, ^x } = { 1, 0 }\n iex> x\n 1\n\n \"\"\"\n defmacro ^(var)\n\n @doc ~S\"\"\"\n Gets the representation of any expression.\n\n ## Examples\n\n quote do: sum(1, 2, 3)\n #=> { :sum, [], [1, 2, 3] }\n\n ## Explanation\n\n Any Elixir code can be represented using Elixir data structures.\n The building block of Elixir macros is a tuple with three elements,\n for example:\n\n { :sum, [], [1, 2, 3] }\n\n The tuple above represents a function call to `sum` passing 1, 2 and\n 3 as arguments. The tuple elements are:\n\n * The first element of the tuple is always an atom or\n another tuple in the same representation;\n * The second element of the tuple represents metadata;\n * The third element of the tuple are the arguments for the\n function call. The third argument may be an atom, which is\n usually a variable (or a local call);\n\n ## Options\n\n * `:unquote` - When false, disables unquoting. Useful when you have a quote\n inside another quote and want to control what quote is\n able to unquote;\n * `:location` - When set to `:keep`, keeps the current line and file from quote.\n Read the Stacktrace information section below for more information;\n * `:hygiene` - Allows a developer to disable hygiene selectively;\n * `:context` - Sets the resolution context;\n * `:bind_quoted` - Passes a binding to the macro. Whenever a binding is given,\n `unquote` is automatically disabled;\n\n ## Quote literals\n\n Besides the tuple described above, Elixir has a few literals that\n when quoted return themselves. They are:\n\n :sum #=> Atoms\n 1 #=> Integers\n 2.0 #=> Floats\n [1, 2] #=> Lists\n \"strings\" #=> Strings\n {key, value} #=> Tuples with two elements\n\n ## Quote and macros\n\n `quote` is commonly used with macros for code generation. As an exercise,\n let's define a macro that multiplies a number by itself (squared). Note\n there is no reason to define such as a macro (and it would actually be\n seen as a bad practice), but it is simple enough that it allows us to focus\n on the important aspects of quotes and macros:\n\n defmodule Math do\n defmacro squared(x) do\n quote do\n unquote(x) * unquote(x)\n end\n end\n end\n\n We can invoke it as:\n\n import Math\n IO.puts \"Got #{squared(5)}\"\n\n At first, there is nothing in this example that actually reveals it is a\n macro. But what is happening is that, at compilation time, `squared(5)`\n becomes `5 * 5`. The argument `5` is duplicated in the produced code, we\n can see this behaviour in practice though because our macro actually has\n a bug:\n\n import Math\n my_number = fn ->\n IO.puts \"Returning 5\"\n 5\n end\n IO.puts \"Got #{squared(my_number.())}\"\n\n The example above will print:\n\n Returning 5\n Returning 5\n 25\n\n Notice how \"Returning 5\" was printed twice, instead of just once. This is\n because a macro receives an expression and not a value (which is what we\n would expect in a regular function). This means that:\n\n squared(my_number.())\n\n Actually expands to:\n\n my_number.() * my_number.()\n\n Which invokes the function twice, explaining why we get the printed value\n twice! In the majority of the cases, this is actually unexpected behaviour,\n and that's why one of the first things you need to keep in mind when it\n comes to macros is to **not unquote the same value more than once**.\n\n Let's fix our macro:\n\n defmodule Math do\n defmacro squared(x) do\n quote do\n x = unquote(x)\n x * x\n end\n end\n end\n\n Now invoking `square(my_number.())` as before will print the value just\n once.\n\n In fact, this pattern is so common that most of the times you will want\n to use the `bind_quoted` option with `quote`:\n\n defmodule Math do\n defmacro squared(x) do\n quote bind_quoted: [x: x] do\n x * x\n end\n end\n end\n\n `:bind_quoted` will translate to the same code as the example above.\n `:bind_quoted` can be used in many cases and is seen as good practice,\n not only because it helps us from running into common mistakes but also\n because it allows us to leverage other tools exposed by macros, such as\n unquote fragments discussed in some sections below.\n\n Before we finish this brief introduction, you will notice that, even though\n we defined a variable `x` inside our quote:\n\n quote do\n x = unquote(x)\n x * x\n end\n\n When we call:\n\n import Math\n squared(5)\n x #=> ** (RuntimeError) undefined function or variable: x\n\n We can see that `x` did not leak to the user context. This happens\n because Elixir macros are hygienic, a topic we will discuss at length\n in the next sections as well.\n\n ## Hygiene in variables\n\n Consider the following example:\n\n defmodule Hygiene do\n defmacro no_interference do\n quote do: a = 1\n end\n end\n\n require Hygiene\n\n a = 10\n Hygiene.no_interference\n a #=> 10\n\n In the example above, `a` returns 10 even if the macro\n is apparently setting it to 1 because variables defined\n in the macro does not affect the context the macro is executed in.\n If you want to set or get a variable in the caller's context, you\n can do it with the help of the `var!` macro:\n\n defmodule NoHygiene do\n defmacro interference do\n quote do: var!(a) = 1\n end\n end\n\n require NoHygiene\n\n a = 10\n NoHygiene.interference\n a #=> 1\n\n Note that you cannot even access variables defined in the same\n module unless you explicitly give it a context:\n\n defmodule Hygiene do\n defmacro write do\n quote do\n a = 1\n end\n end\n\n defmacro read do\n quote do\n a\n end\n end\n end\n\n Hygiene.write\n Hygiene.read\n #=> ** (RuntimeError) undefined function or variable: a\n\n For such, you can explicitly pass the current module scope as\n argument:\n\n defmodule ContextHygiene do\n defmacro write do\n quote do\n var!(a, ContextHygiene) = 1\n end\n end\n\n defmacro read do\n quote do\n var!(a, ContextHygiene)\n end\n end\n end\n\n ContextHygiene.write\n ContextHygiene.read\n #=> 1\n\n Hygiene for variables can be disabled overall as:\n\n quote hygiene: [vars: false], do: x\n\n ## Hygiene in aliases\n\n Aliases inside quote are hygienic by default.\n Consider the following example:\n\n defmodule Hygiene do\n alias HashDict, as: D\n\n defmacro no_interference do\n quote do: D.new\n end\n end\n\n require Hygiene\n Hygiene.no_interference #=> #HashDict<[]>\n\n Notice that, even though the alias `D` is not available\n in the context the macro is expanded, the code above works\n because `D` still expands to `HashDict`.\n\n Similarly, even if we defined an alias with the same name\n before invoking a macro, it won't affect the macro's result:\n\n defmodule Hygiene do\n alias HashDict, as: D\n\n defmacro no_interference do\n quote do: D.new\n end\n end\n\n require Hygiene\n alias SomethingElse, as: D\n Hygiene.no_interference #=> #HashDict<[]>\n\n In some cases, you want to access an alias or a module defined\n in the caller. For such, you can use the `alias!` macro:\n\n defmodule Hygiene do\n # This will expand to Elixir.Nested.hello\n defmacro no_interference do\n quote do: Nested.hello\n end\n\n # This will expand to Nested.hello for\n # whatever is Nested in the caller\n defmacro interference do\n quote do: alias!(Nested).hello\n end\n end\n\n defmodule Parent do\n defmodule Nested do\n def hello, do: \"world\"\n end\n\n require Hygiene\n Hygiene.no_interference\n #=> ** (UndefinedFunctionError) ...\n\n Hygiene.interference\n #=> \"world\"\n end\n\n ## Hygiene in imports\n\n Similar to aliases, imports in Elixir are hygienic. Consider the\n following code:\n\n defmodule Hygiene do\n defmacrop get_size do\n quote do\n size(\"hello\")\n end\n end\n\n def return_size do\n import Kernel, except: [size: 1]\n get_size\n end\n end\n\n Hygiene.return_size #=> 5\n\n Notice how `return_size` returns 5 even though the `size\/1`\n function is not imported. In fact, even if `return_size` imported\n a function from another module, it wouldn't affect the function\n result:\n\n def return_size do\n import Dict, only: [size: 1]\n get_size\n end\n\n Calling this new `return_size` will still return 5 as result.\n\n Elixir is smart enough to delay the resolution to the latest\n moment possible. So, if you call `size(\"hello\")` inside quote,\n but no `size\/1` function is available, it is then expanded in\n the caller:\n\n defmodule Lazy do\n defmacrop get_size do\n import Kernel, except: [size: 1]\n\n quote do\n size([a: 1, b: 2])\n end\n end\n\n def return_size do\n import Kernel, except: [size: 1]\n import Dict, only: [size: 1]\n get_size\n end\n end\n\n Lazy.return_size #=> 2\n\n As in aliases, import expansion can be explicitly disabled\n via the `hygiene: [imports: false]` option.\n\n ## Stacktrace information\n\n When defining functions via macros, developers have the option of\n choosing if runtime errors will be reported from the caller or from\n inside the quote. Let's see an example:\n\n # adder.ex\n defmodule Adder do\n @doc \"Defines a function that adds two numbers\"\n defmacro defadd do\n quote location: :keep do\n def add(a, b), do: a + b\n end\n end\n end\n\n # sample.ex\n defmodule Sample do\n import Adder\n defadd\n end\n\n When using `location: :keep` and invalid arguments are given to\n `Sample.add\/2`, the stacktrace information will point to the file\n and line inside the quote. Without `location: :keep`, the error is\n reported to where `defadd` was invoked. Note `location: :keep` affects\n only definitions inside the quote.\n\n ## Binding and unquote fragments\n\n Elixir quote\/unquote mechanisms provides a functionality called\n unquote fragments. Unquote fragments provide an easy way to generate\n functions on the fly. Consider this example:\n\n kv = [foo: 1, bar: 2]\n Enum.each kv, fn { k, v } ->\n def unquote(k)(), do: unquote(v)\n end\n\n In the example above, we have generated the functions `foo\/0` and\n `bar\/0` dynamically. Now, imagine that, we want to convert this\n functionality into a macro:\n\n defmacro defkv(kv) do\n Enum.map kv, fn { k, v } ->\n quote do\n def unquote(k)(), do: unquote(v)\n end\n end\n end\n\n We can invoke this macro as:\n\n defkv [foo: 1, bar: 2]\n\n However, we can't invoke it as follows:\n\n kv = [foo: 1, bar: 2]\n defkv kv\n\n This is because the macro is expecting its arguments to be a\n keyword list at **compilation** time. Since in the example above\n we are passing the representation of the variable `kv`, our\n code fails.\n\n This is actually a common pitfall when developing macros. In\n practice, we want to avoid doing work at compilation time as\n much as possible. That said, let's attempt to improve our macro:\n\n defmacro defkv(kv) do\n quote do\n Enum.each unquote(kv), fn { k, v } ->\n def unquote(k)(), do: unquote(v)\n end\n end\n end\n\n If you try to run our new macro, you will notice it won't\n even compile, complaining that the variables `k` and `v`\n does not exist. This is because of the ambiguity: `unquote(k)`\n can either be an unquote fragment, as previously, or a regular\n unquote as in `unquote(kv)`.\n\n One solution to this problem is to disable unquoting in the\n macro, however, doing that would make it impossible to inject the\n `kv` representation into the tree. That's when the `:bind_quoted`\n option comes to the rescue (again!). By using `:bind_quoted`, we\n can automatically disable unquoting while still injecting the\n desired variables into the tree:\n\n defmacro defkv(kv) do\n quote bind_quoted: [kv: kv] do\n Enum.each kv, fn { k, v } ->\n def unquote(k)(), do: unquote(v)\n end\n end\n end\n\n In fact, the `:bind_quoted` option is recommended every time\n one desires to inject a value into the quote.\n \"\"\"\n defmacro quote(opts, block)\n\n @doc \"\"\"\n Unquotes the given expression from inside a macro.\n\n ## Examples\n\n Imagine the situation you have a variable `name` and\n you want to inject it inside some quote. The first attempt\n would be:\n\n value = 13\n quote do: sum(1, value, 3)\n\n Which would then return:\n\n { :sum, [], [1, { :value, [], quoted }, 3] }\n\n Which is not the expected result. For this, we use unquote:\n\n value = 13\n quote do: sum(1, unquote(value), 3)\n #=> { :sum, [], [1, 13, 3] }\n\n \"\"\"\n defmacro unquote(:unquote)(expr)\n\n @doc \"\"\"\n Unquotes the given list expanding its arguments. Similar\n to unquote.\n\n ## Examples\n\n values = [2, 3, 4]\n quote do: sum(1, unquote_splicing(values), 5)\n #=> { :sum, [], [1, 2, 3, 4, 5] }\n\n \"\"\"\n defmacro unquote(:unquote_splicing)(expr)\n\n @doc ~S\"\"\"\n Comprehensions allow you to quickly build a data structure from\n an enumerable or a bitstring.\n\n Let's start with an example:\n\n iex> for n <- [1, 2, 3, 4], do: n * 2\n [2, 4, 6, 8]\n\n A comprehension accepts many generators and filters. Enumerable\n generators are defined using `<-`:\n\n # A list generator:\n iex> for n <- [1, 2, 3, 4], do: n * 2\n [2, 4, 6, 8]\n\n # A comprehension with two generators\n iex> for x <- [1, 2], y <- [2, 3], do: x*y\n [2, 3, 4, 6]\n\n Filters can also be given:\n\n # A comprehension with a generator and a filter\n iex> for n <- [1, 2, 3, 4, 5, 6], rem(n, 2) == 0, do: n\n [2, 4, 6]\n\n Bitstring generators are also supported and are very useful when you\n need to organize bitstring streams:\n\n iex> pixels = <<213, 45, 132, 64, 76, 32, 76, 0, 0, 234, 32, 15>>\n iex> for <>, do: {r, g, b}\n [{213,45,132},{64,76,32},{76,0,0},{234,32,15}]\n\n Variable assignments inside the comprehension, be it in generators,\n filters or inside the block, are not reflected outside of the\n comprehension.\n\n ## Into\n\n In the examples above, the result returned by the comprehension was\n always a list. The returned result can be configured by passing an\n `:into` option, that accepts any structure as long as it implements\n the `Collectable` protocol.\n\n For example, we can use bitstring generators with the `:into` option\n to easily remove all spaces in a string:\n\n iex> for <>, c != ?\\s, into: \"\", do: <>\n \"helloworld\"\n\n Since both `IO` and `File` modules provide streams, that are both\n `Enumerable` and `Traversable`, here is an upcase echo server using\n comprehensions:\n\n for line <- IO.stream(:stdio), into: IO.stream(:stdio) do\n String.upcase(line)\n end\n\n \"\"\"\n defmacro for(args)\n\n @doc \"\"\"\n Defines an anonymous function.\n\n ## Examples\n\n iex> add = fn a, b -> a + b end\n iex> add.(1, 2)\n 3\n\n \"\"\"\n defmacro unquote(:fn)(clauses)\n\n @doc \"\"\"\n Internal special form for block expressions.\n\n This is the special form used whenever we have a block\n of expressions in Elixir. This special form is private\n and should not be invoked directly:\n\n iex> quote do: (1; 2; 3)\n { :__block__, [], [1, 2, 3] }\n\n \"\"\"\n defmacro __block__(args)\n\n @doc \"\"\"\n Captures an anonymous function.\n\n The most common format to capture a function is via module,\n name and arity:\n\n iex> fun = &Kernel.is_atom\/1\n iex> fun.(:atom)\n true\n iex> fun.(\"string\")\n false\n\n Local functions, including private ones, and imported ones\n can also be captured by omitting the module name:\n\n &local_function\/1\n\n A capture also allows the captured functions to be partially\n applied, for example:\n\n iex> fun = &is_record(&1, Range)\n iex> fun.(1..3)\n true\n\n In the example above, we use &1 as a placeholder, generating\n a function with one argument. We could also use `&2` and `&3`\n to delimit more arguments:\n\n iex> fun = &is_record(&1, &2)\n iex> fun.(1..3, Range)\n true\n\n Since operators are calls, they are also supported, although\n they require explicit parentheses around:\n\n iex> fun = &(&1 + &2)\n iex> fun.(1, 2)\n 3\n\n And even more complex call expressions:\n\n iex> fun = &(&1 + &2 + &3)\n iex> fun.(1, 2, 3)\n 6\n\n Record-like calls are also allowed:\n\n iex> fun = &(&1.first)\n iex> fun.(1..3)\n 1\n\n Remember tuple and lists are represented as calls in the AST and\n therefore are also allowed:\n\n iex> fun = &{&1, &2}\n iex> fun.(1, 2)\n { 1, 2 }\n\n iex> fun = &[&1|&2]\n iex> fun.(1, 2)\n [1|2]\n\n Anything that is not a call is not allowed though, examples:\n\n # An atom is not a call\n &:foo\n\n # A var is not a call\n var = 1\n &var\n\n # A block expression is not a call\n &(foo(&1, &2); &3 + &4)\n\n \"\"\"\n defmacro unquote(:&)(expr)\n\n @doc \"\"\"\n Internal special form to hold aliases information.\n\n It is usually compiled to an atom:\n\n iex> quote do: Foo.Bar\n {:__aliases__, [alias: false], [:Foo, :Bar]}\n\n Elixir represents `Foo.Bar` as `__aliases__` so calls can be\n unambiguously identified by the operator `:.`. For example:\n\n iex> quote do: Foo.bar\n {{:., [], [{:__aliases__, [alias: false], [:Foo]}, :bar]}, [], []}\n\n Whenever an expression iterator sees a `:.` as the tuple key,\n it can be sure that it represents a call and the second argument\n in the list is an atom.\n\n On the other hand, aliases holds some properties:\n\n 1) The head element of aliases can be any term;\n\n 2) The tail elements of aliases are guaranteed to always be atoms;\n\n 3) When the head element of aliases is the atom `:Elixir`, no expansion happen;\n\n 4) When the head element of aliases is not an atom, it is expanded at runtime:\n\n quote do: some_var.Foo\n {:__aliases__, [], [{:some_var, [], Elixir}, :Foo]}\n\n Since `some_var` is not available at compilation time, the compiler\n expands such expression to:\n\n Module.concat [some_var, Foo]\n\n \"\"\"\n defmacro __aliases__(args)\n\n @doc \"\"\"\n Calls the overriden function when overriding it with `defoverridable`.\n See `Kernel.defoverridable` for more information and documentation.\n \"\"\"\n defmacro super(args)\n\n @doc \"\"\"\n Matches the given expression against the given clauses.\n\n ## Examples\n\n case thing do\n { :selector, i, value } when is_integer(i) ->\n value\n value ->\n value\n end\n\n In the example above, we match `thing` against each clause \"head\"\n and execute the clause \"body\" corresponding to the first clause\n that matches. If no clause matches, an error is raised.\n\n ## Variables handling\n\n Notice that variables bound in a clause \"head\" do not leak to the\n outer context:\n\n case data do\n { :ok, value } -> value\n :error -> nil\n end\n\n value #=> unbound variable value\n\n However, variables explicitly bound in the clause \"body\" are\n accessible from the outer context:\n\n value = 7\n\n case lucky? do\n false -> value = 13\n true -> true\n end\n\n value #=> 7 or 13\n\n In the example above, value is going to be `7` or `13` depending on\n the value of `lucky?`. In case `value` has no previous value before\n case, clauses that do not explicitly bind a value have the variable\n bound to nil.\n \"\"\"\n defmacro case(condition, blocks)\n\n @doc \"\"\"\n Evaluate the given expressions and handle any error, exit\n or throw that may have happened.\n\n ## Examples\n\n try do\n do_something_that_may_fail(some_arg)\n rescue\n ArgumentError ->\n IO.puts \"Invalid argument given\"\n catch\n value ->\n IO.puts \"caught \\#{value}\"\n else\n value ->\n IO.puts \"Success! The result was \\#{value}\"\n after\n IO.puts \"This is printed regardless if it failed or succeed\"\n end\n\n The rescue clause is used to handle exceptions, while the catch\n clause can be used to catch thrown values. The else clause can\n be used to control flow based on the result of the expression.\n Catch, rescue and else clauses work based on pattern matching.\n\n Note that calls inside `try` are not tail recursive since the VM\n needs to keep the stacktrace in case an exception happens.\n\n ## Rescue clauses\n\n Besides relying on pattern matching, rescue clauses provides some\n conveniences around exceptions that allows one to rescue an\n exception by its name. All the following formats are valid rescue\n expressions:\n\n try do\n UndefinedModule.undefined_function\n rescue\n UndefinedFunctionError -> nil\n end\n\n try do\n UndefinedModule.undefined_function\n rescue\n [UndefinedFunctionError] -> nil\n end\n\n # rescue and bind to x\n try do\n UndefinedModule.undefined_function\n rescue\n x in [UndefinedFunctionError] -> nil\n end\n\n # rescue all and bind to x\n try do\n UndefinedModule.undefined_function\n rescue\n x -> nil\n end\n\n ## Catching exits and Erlang errors\n\n The catch clause works exactly the same as in erlang. Therefore,\n one can also handle exits\/errors coming from Erlang as below:\n\n try do\n exit(1)\n catch\n :exit, 1 -> IO.puts \"Exited with 1\"\n end\n\n try do\n error(:sample)\n catch\n :error, :sample ->\n IO.puts \"sample error\"\n end\n\n Although the second form should be avoided in favor of raise\/rescue\n control mechanisms.\n\n ## Else clauses\n\n Else clauses allow the result of the expression to be pattern\n matched on:\n\n x = 2\n try do\n 1 \/ x\n rescue\n ArithmeticError ->\n :infinity\n else\n y when y < 1 and y > -1 ->\n :small\n _ ->\n :large\n end\n\n If an else clause is not present the result of the expression will\n be return, if no exceptions are raised:\n\n x = 1\n ^x =\n try do\n 1 \/ x\n rescue\n ArithmeticError ->\n :infinity\n end\n\n However when an else clause is present but the result of the expression\n does not match any of the patterns an exception will be raised. This\n exception will not be caught by a catch or rescue in the same try:\n\n x = 1\n try do\n try do\n 1 \/ x\n rescue\n # The TryClauseError can not be rescued here:\n TryClauseError ->\n :error_a\n else\n 0 ->\n :small\n end\n rescue\n # The TryClauseError is rescued here:\n TryClauseError ->\n :error_b\n end\n\n Similarly an exception inside an else clause is not caught or rescued\n inside the same try:\n\n try do\n try do\n nil\n catch\n # The exit(1) call below can not be caught here:\n :exit, _ ->\n :exit_a\n else\n _ ->\n exit(1)\n end\n catch\n # The exit is caught here:\n :exit, _ ->\n :exit_b\n end\n\n This means the VM no longer needs to keep the stacktrace once inside\n an else clause and so tail recursion is possible when using a `try`\n with a tail call as the final call inside an else clause. The same\n is true for rescue and catch clauses.\n\n ## Variable handling\n\n Since an expression inside `try` may not have been evaluated\n due to an exception, any variable created inside `try` cannot\n be accessed externally. For instance:\n\n try do\n x = 1\n do_something_that_may_fail(same_arg)\n :ok\n catch\n _, _ -> :failed\n end\n\n x #=> unbound variable `x`\n\n In the example above, `x` cannot be accessed since it was defined\n inside the `try` clause. A common practice to address this issue\n is to return the variables defined inside `try`:\n\n x =\n try do\n x = 1\n do_something_that_may_fail(same_arg)\n x\n catch\n _, _ -> :failed\n end\n\n \"\"\"\n defmacro try(args)\n\n @doc \"\"\"\n Checks if there is a message matching the given clauses\n in the current process mailbox.\n\n In case there is no such message, the current process hangs\n until a message arrives or waits until a given timeout value.\n\n ## Examples\n\n receive do\n { :selector, i, value } when is_integer(i) ->\n value\n value when is_atom(value) ->\n value\n _ ->\n IO.puts :stderr, \"Unexpected message received\"\n end\n\n An optional after clause can be given in case the message was not\n received after the specified period of time:\n\n receive do\n { :selector, i, value } when is_integer(i) ->\n value\n value when is_atom(value) ->\n value\n _ ->\n IO.puts :stderr, \"Unexpected message received\"\n after\n 5000 ->\n IO.puts :stderr, \"No message in 5 seconds\"\n end\n\n The `after` clause can be specified even if there are no match clauses.\n There are two special cases for the timeout value given to `after`\n\n * `:infinity` - The process should wait indefinitely for a matching\n message, this is the same as not using a timeout.\n\n * 0 - if there is no matching message in the mailbox, the timeout\n will occur immediately.\n\n ## Variables handling\n\n The `receive` special form handles variables exactly as the `case`\n special macro. For more information, check the docs for `case\/2`.\n \"\"\"\n defmacro receive(args)\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"653bf090a14c07adb5d05b25cf10043ffe71651c","subject":"Fix typos in Kernel.SpecialForms doc (#8731)","message":"Fix typos in Kernel.SpecialForms doc (#8731)\n\n","repos":"kelvinst\/elixir,michalmuskala\/elixir,lexmag\/elixir,joshprice\/elixir,pedrosnk\/elixir,elixir-lang\/elixir,kelvinst\/elixir,pedrosnk\/elixir,lexmag\/elixir,ggcampinho\/elixir,kimshrier\/elixir,kimshrier\/elixir,ggcampinho\/elixir","old_file":"lib\/elixir\/lib\/kernel\/special_forms.ex","new_file":"lib\/elixir\/lib\/kernel\/special_forms.ex","new_contents":"defmodule Kernel.SpecialForms do\n @moduledoc \"\"\"\n Special forms are the basic building blocks of Elixir, and therefore\n cannot be overridden by the developer.\n\n We define them in this module. Some of these forms are lexical (like\n `alias\/2`, `case\/2`, etc.). The macros `{}\/1` and `<<>>\/1` are also special\n forms used to define tuple and binary data structures respectively.\n\n This module also documents macros that return information about Elixir's\n compilation environment, such as (`__ENV__\/0`, `__MODULE__\/0`, `__DIR__\/0` and `__CALLER__\/0`).\n\n Finally, it also documents two special forms, `__block__\/1` and\n `__aliases__\/1`, which are not intended to be called directly by the\n developer but they appear in quoted contents since they are essential\n in Elixir's constructs.\n \"\"\"\n\n defmacrop error!(args) do\n quote do\n _ = unquote(args)\n\n message =\n \"Elixir's special forms are expanded by the compiler and must not be invoked directly\"\n\n :erlang.error(RuntimeError.exception(message))\n end\n end\n\n @doc \"\"\"\n Creates a tuple.\n\n More information about the tuple data type and about functions to manipulate\n tuples can be found in the `Tuple` module; some functions for working with\n tuples are also available in `Kernel` (such as `Kernel.elem\/2` or\n `Kernel.tuple_size\/1`).\n\n ## AST representation\n\n Only two-item tuples are considered literals in Elixir and return themselves\n when quoted. Therefore, all other tuples are represented in the AST as calls to\n the `:{}` special form.\n\n iex> quote do\n ...> {1, 2}\n ...> end\n {1, 2}\n\n iex> quote do\n ...> {1, 2, 3}\n ...> end\n {:{}, [], [1, 2, 3]}\n\n \"\"\"\n defmacro unquote(:{})(args), do: error!([args])\n\n @doc \"\"\"\n Creates a map.\n\n See the `Map` module for more information about maps, their syntax, and ways to\n access and manipulate them.\n\n ## AST representation\n\n Regardless of whether `=>` or the keyword syntax is used, key-value pairs in\n maps are always represented internally as a list of two-element tuples for\n simplicity:\n\n iex> quote do\n ...> %{\"a\" => :b, c: :d}\n ...> end\n {:%{}, [], [{\"a\", :b}, {:c, :d}]}\n\n \"\"\"\n defmacro unquote(:%{})(args), do: error!([args])\n\n @doc \"\"\"\n Matches on or builds a struct.\n\n A struct is a tagged map that allows developers to provide\n default values for keys, tags to be used in polymorphic\n dispatches and compile time assertions.\n\n Structs are usually defined with the `Kernel.defstruct\/1` macro:\n\n defmodule User do\n defstruct name: \"john\", age: 27\n end\n\n Now a struct can be created as follows:\n\n %User{}\n\n Underneath a struct is just a map with a `:__struct__` key\n pointing to the `User` module:\n\n %User{} == %{__struct__: User, name: \"john\", age: 27}\n\n The struct fields can be given when building the struct:\n\n %User{age: 31}\n #=> %{__struct__: User, name: \"john\", age: 31}\n\n Or also on pattern matching to extract values out:\n\n %User{age: age} = user\n\n An update operation specific for structs is also available:\n\n %User{user | age: 28}\n\n The advantage of structs is that they validate that the given\n keys are part of the defined struct. The example below will fail\n because there is no key `:full_name` in the `User` struct:\n\n %User{full_name: \"john doe\"}\n\n The syntax above will guarantee the given keys are valid at\n compilation time and it will guarantee at runtime the given\n argument is a struct, failing with `BadStructError` otherwise.\n\n Although structs are maps, by default structs do not implement\n any of the protocols implemented for maps. Check\n `Kernel.defprotocol\/2` for more information on how structs\n can be used with protocols for polymorphic dispatch. Also\n see `Kernel.struct\/2` and `Kernel.struct!\/2` for examples on\n how to create and update structs dynamically.\n\n ## Pattern matching on struct names\n\n Besides allowing pattern matching on struct fields, such as:\n\n %User{age: age} = user\n\n Structs also allow pattern matching on the struct name:\n\n %struct_name{} = user\n struct_name #=> User\n\n You can also assign the struct name to `_` when you want to\n check if something is a struct but you are not interested in\n its name:\n\n %_{} = user\n\n \"\"\"\n defmacro unquote(:%)(struct, map), do: error!([struct, map])\n\n @doc \"\"\"\n Defines a new bitstring.\n\n ## Examples\n\n iex> <<1, 2, 3>>\n <<1, 2, 3>>\n\n ## Types\n\n A bitstring is made of many segments and each segment has a\n type. There are 9 types used in bitstrings:\n\n - `integer`\n - `float`\n - `bits` (alias for `bitstring`)\n - `bitstring`\n - `binary`\n - `bytes` (alias for `binary`)\n - `utf8`\n - `utf16`\n - `utf32`\n\n When no type is specified, the default is `integer`:\n\n iex> <<1, 2, 3>>\n <<1, 2, 3>>\n\n Elixir also accepts by default the segment to be a literal\n string or a literal charlist, which are by default expanded to integers:\n\n iex> <<0, \"foo\">>\n <<0, 102, 111, 111>>\n\n Variables or any other type need to be explicitly tagged:\n\n iex> rest = \"oo\"\n iex> <<102, rest>>\n ** (ArgumentError) argument error\n\n We can solve this by explicitly tagging it as `binary`:\n\n iex> rest = \"oo\"\n iex> <<102, rest::binary>>\n \"foo\"\n\n The `utf8`, `utf16`, and `utf32` types are for Unicode codepoints. They\n can also be applied to literal strings and charlists:\n\n iex> <<\"foo\"::utf16>>\n <<0, 102, 0, 111, 0, 111>>\n iex> <<\"foo\"::utf32>>\n <<0, 0, 0, 102, 0, 0, 0, 111, 0, 0, 0, 111>>\n\n ## Options\n\n Many options can be given by using `-` as separator. Order is\n arbitrary, so the following are all equivalent:\n\n <<102::integer-native, rest::binary>>\n <<102::native-integer, rest::binary>>\n <<102::unsigned-big-integer, rest::binary>>\n <<102::unsigned-big-integer-size(8), rest::binary>>\n <<102::unsigned-big-integer-8, rest::binary>>\n <<102::8-integer-big-unsigned, rest::binary>>\n <<102, rest::binary>>\n\n ### Unit and Size\n\n The length of the match is equal to the `unit` (a number of bits) times the\n `size` (the number of repeated segments of length `unit`).\n\n Type | Default Unit\n --------- | ------------\n `integer` | 1 bit\n `float` | 1 bit\n `binary` | 8 bits\n\n Sizes for types are a bit more nuanced. The default size for integers is 8.\n\n For floats, it is 64. For floats, `size * unit` must result in 32 or 64,\n corresponding to [IEEE 754](https:\/\/en.wikipedia.org\/wiki\/IEEE_floating_point)\n binary32 and binary64, respectively.\n\n For binaries, the default is the size of the binary. Only the last binary in a\n match can use the default size. All others must have their size specified\n explicitly, even if the match is unambiguous. For example:\n\n iex> <> = <<\"Frank the Walrus\">>\n \"Frank the Walrus\"\n iex> {name, species}\n {\"Frank\", \"Walrus\"}\n\n The size can be a variable:\n\n iex> name_size = 5\n iex> <> = <<\"Frank the Walrus\">>\n iex> {name, species}\n {\"Frank\", \"Walrus\"}\n\n And the variable can be defined in the match itself (prior to its use):\n\n iex> <> = <<5, \"Frank the Walrus\">>\n iex> {name, species}\n {\"Frank\", \"Walrus\"}\n\n However, the size cannot be defined in the match outside the binary\/bitstring match:\n\n {name_size, <>} = {5, <<\"Frank the Walrus\">>}\n ** (CompileError): undefined variable \"name_size\" in bitstring segment\n\n Failing to specify the size for the non-last causes compilation to fail:\n\n <> = <<\"Frank the Walrus\">>\n ** (CompileError): a binary field without size is only allowed at the end of a binary pattern\n\n #### Shortcut Syntax\n\n Size and unit can also be specified using a syntax shortcut\n when passing integer values:\n\n iex> x = 1\n iex> <> == <>\n true\n iex> <> == <>\n true\n\n This syntax reflects the fact the effective size is given by\n multiplying the size by the unit.\n\n ### Modifiers\n\n Some types have associated modifiers to clear up ambiguity in byte\n representation.\n\n Modifier | Relevant Type(s)\n -------------------- | ----------------\n `signed` | `integer`\n `unsigned` (default) | `integer`\n `little` | `integer`, `float`, `utf16`, `utf32`\n `big` (default) | `integer`, `float`, `utf16`, `utf32`\n `native` | `integer`, `utf16`, `utf32`\n\n ### Sign\n\n Integers can be `signed` or `unsigned`, defaulting to `unsigned`.\n\n iex> <> = <<-100>>\n <<156>>\n iex> int\n 156\n iex> <> = <<-100>>\n <<156>>\n iex> int\n -100\n\n `signed` and `unsigned` are only used for matching binaries (see below) and\n are only used for integers.\n\n iex> <<-100::signed, _rest::binary>> = <<-100, \"foo\">>\n <<156, 102, 111, 111>>\n\n ### Endianness\n\n Elixir has three options for endianness: `big`, `little`, and `native`.\n The default is `big`:\n\n iex> <> = <<0, 1>>\n <<0, 1>>\n iex> number\n 256\n iex> <> = <<0, 1>>\n <<0, 1>>\n iex> number\n 1\n\n `native` is determined by the VM at startup and will depend on the\n host operating system.\n\n ## Binary\/Bitstring Matching\n\n Binary matching is a powerful feature in Elixir that is useful for extracting\n information from binaries as well as pattern matching.\n\n Binary matching can be used by itself to extract information from binaries:\n\n iex> <<\"Hello, \", place::binary>> = \"Hello, World\"\n \"Hello, World\"\n iex> place\n \"World\"\n\n Or as a part of function definitions to pattern match:\n\n defmodule ImageTyper do\n @png_signature <<137::size(8), 80::size(8), 78::size(8), 71::size(8),\n 13::size(8), 10::size(8), 26::size(8), 10::size(8)>>\n @jpg_signature <<255::size(8), 216::size(8)>>\n\n def type(<<@png_signature, rest::binary>>), do: :png\n def type(<<@jpg_signature, rest::binary>>), do: :jpg\n def type(_), do: :unknown\n end\n\n ### Performance & Optimizations\n\n The Erlang compiler can provide a number of optimizations on binary creation\n and matching. To see optimization output, set the `bin_opt_info` compiler\n option:\n\n ERL_COMPILER_OPTIONS=bin_opt_info mix compile\n\n To learn more about specific optimizations and performance considerations,\n check out\n [Erlang's Efficiency Guide on handling binaries](http:\/\/www.erlang.org\/doc\/efficiency_guide\/binaryhandling.html).\n \"\"\"\n defmacro unquote(:<<>>)(args), do: error!([args])\n\n @doc \"\"\"\n Defines a remote call, a call to an anonymous function, or an alias.\n\n The dot (`.`) in Elixir can be used for remote calls:\n\n iex> String.downcase(\"FOO\")\n \"foo\"\n\n In this example above, we have used `.` to invoke `downcase` in the\n `String` module, passing `\"FOO\"` as argument.\n\n The dot may be used to invoke anonymous functions too:\n\n iex> (fn n -> n end).(7)\n 7\n\n in which case there is a function on the left hand side.\n\n We can also use the dot for creating aliases:\n\n iex> Hello.World\n Hello.World\n\n This time, we have joined two aliases, defining the final alias\n `Hello.World`.\n\n ## Syntax\n\n The right side of `.` may be a word starting with an uppercase letter, which represents\n an alias, a word starting with lowercase or underscore, any valid language\n operator or any name wrapped in single- or double-quotes. Those are all valid\n examples:\n\n iex> Kernel.Sample\n Kernel.Sample\n\n iex> Kernel.length([1, 2, 3])\n 3\n\n iex> Kernel.+(1, 2)\n 3\n\n iex> Kernel.\"+\"(1, 2)\n 3\n\n Wrapping the function name in single- or double-quotes is always a\n remote call. Therefore `Kernel.\"Foo\"` will attempt to call the function \"Foo\"\n and not return the alias `Kernel.Foo`. This is done by design as module names\n are more strict than function names.\n\n When the dot is used to invoke an anonymous function there is only one\n operand, but it is still written using a postfix notation:\n\n iex> negate = fn n -> -n end\n iex> negate.(7)\n -7\n\n ## Quoted expression\n\n When `.` is used, the quoted expression may take two distinct\n forms. When the right side starts with a lowercase letter (or\n underscore):\n\n iex> quote do\n ...> String.downcase(\"FOO\")\n ...> end\n {{:., [], [{:__aliases__, [alias: false], [:String]}, :downcase]}, [], [\"FOO\"]}\n\n Notice we have an inner tuple, containing the atom `:.` representing\n the dot as first element:\n\n {:., [], [{:__aliases__, [alias: false], [:String]}, :downcase]}\n\n This tuple follows the general quoted expression structure in Elixir,\n with the name as first argument, some keyword list as metadata as second,\n and the list of arguments as third. In this case, the arguments are the\n alias `String` and the atom `:downcase`. The second argument in a remote call\n is **always** an atom.\n\n In the case of calls to anonymous functions, the inner tuple with the dot\n special form has only one argument, reflecting the fact that the operator is\n unary:\n\n iex> quote do\n ...> negate.(0)\n ...> end\n {{:., [], [{:negate, [], __MODULE__}]}, [], [0]}\n\n When the right side is an alias (i.e. starts with uppercase), we get instead:\n\n iex> quote do\n ...> Hello.World\n ...> end\n {:__aliases__, [alias: false], [:Hello, :World]}\n\n We go into more details about aliases in the `__aliases__\/1` special form\n documentation.\n\n ## Unquoting\n\n We can also use unquote to generate a remote call in a quoted expression:\n\n iex> x = :downcase\n iex> quote do\n ...> String.unquote(x)(\"FOO\")\n ...> end\n {{:., [], [{:__aliases__, [alias: false], [:String]}, :downcase]}, [], [\"FOO\"]}\n\n Similar to `Kernel.\"FUNCTION_NAME\"`, `unquote(x)` will always generate a remote call,\n independent of the value of `x`. To generate an alias via the quoted expression,\n one needs to rely on `Module.concat\/2`:\n\n iex> x = Sample\n iex> quote do\n ...> Module.concat(String, unquote(x))\n ...> end\n {{:., [], [{:__aliases__, [alias: false], [:Module]}, :concat]}, [],\n [{:__aliases__, [alias: false], [:String]}, Sample]}\n\n \"\"\"\n defmacro unquote(:.)(left, right), do: error!([left, right])\n\n @doc \"\"\"\n `alias\/2` is used to setup aliases, often useful with modules' names.\n\n ## Examples\n\n `alias\/2` can be used to set up an alias for any module:\n\n defmodule Math do\n alias MyKeyword, as: Keyword\n end\n\n In the example above, we have set up `MyKeyword` to be aliased\n as `Keyword`. So now, any reference to `Keyword` will be\n automatically replaced by `MyKeyword`.\n\n In case one wants to access the original `Keyword`, it can be done\n by accessing `Elixir`:\n\n Keyword.values #=> uses MyKeyword.values\n Elixir.Keyword.values #=> uses Keyword.values\n\n Notice that calling `alias` without the `:as` option automatically\n sets an alias based on the last part of the module. For example:\n\n alias Foo.Bar.Baz\n\n Is the same as:\n\n alias Foo.Bar.Baz, as: Baz\n\n We can also alias multiple modules in one line:\n\n alias Foo.{Bar, Baz, Biz}\n\n Is the same as:\n\n alias Foo.Bar\n alias Foo.Baz\n alias Foo.Biz\n\n ## Lexical scope\n\n `import\/2`, `require\/2` and `alias\/2` are called directives and all\n have lexical scope. This means you can set up aliases inside\n specific functions and it won't affect the overall scope.\n\n ## Warnings\n\n If you alias a module and you don't use the alias, Elixir is\n going to issue a warning implying the alias is not being used.\n\n In case the alias is generated automatically by a macro,\n Elixir won't emit any warnings though, since the alias\n was not explicitly defined.\n\n Both warning behaviours could be changed by explicitly\n setting the `:warn` option to `true` or `false`.\n\n \"\"\"\n defmacro alias(module, opts), do: error!([module, opts])\n\n @doc \"\"\"\n Requires a module in order to use its macros.\n\n ## Examples\n\n Public functions in modules are globally available, but in order to use\n macros, you need to opt-in by requiring the module they are defined in.\n\n Let's suppose you created your own `if\/2` implementation in the module\n `MyMacros`. If you want to invoke it, you need to first explicitly\n require the `MyMacros`:\n\n defmodule Math do\n require MyMacros\n MyMacros.if do_something, it_works\n end\n\n An attempt to call a macro that was not loaded will raise an error.\n\n ## Alias shortcut\n\n `require\/2` also accepts `:as` as an option so it automatically sets\n up an alias. Please check `alias\/2` for more information.\n\n \"\"\"\n defmacro require(module, opts), do: error!([module, opts])\n\n @doc \"\"\"\n Imports functions and macros from other modules.\n\n `import\/2` allows one to easily access functions or macros from\n other modules without using the qualified name.\n\n ## Examples\n\n If you are using several functions from a given module, you can\n import those functions and reference them as local functions,\n for example:\n\n iex> import List\n iex> flatten([1, [2], 3])\n [1, 2, 3]\n\n ## Selector\n\n By default, Elixir imports functions and macros from the given\n module, except the ones starting with underscore (which are\n usually callbacks):\n\n import List\n\n A developer can filter to import only macros or functions via\n the only option:\n\n import List, only: :functions\n import List, only: :macros\n\n Alternatively, Elixir allows a developer to pass pairs of\n name\/arities to `:only` or `:except` as a fine grained control\n on what to import (or not):\n\n import List, only: [flatten: 1]\n import String, except: [split: 2]\n\n Notice that calling `except` is always exclusive on a previously\n declared `import\/2`. If there is no previous import, then it applies\n to all functions and macros in the module. For example:\n\n import List, only: [flatten: 1, keyfind: 4]\n import List, except: [flatten: 1]\n\n After the two import calls above, only `List.keyfind\/4` will be\n imported.\n\n ## Underscore functions\n\n By default functions starting with `_` are not imported. If you really want\n to import a function starting with `_` you must explicitly include it in the\n `:only` selector.\n\n import File.Stream, only: [__build__: 3]\n\n ## Lexical scope\n\n It is important to notice that `import\/2` is lexical. This means you\n can import specific macros inside specific functions:\n\n defmodule Math do\n def some_function do\n # 1) Disable \"if\/2\" from Kernel\n import Kernel, except: [if: 2]\n\n # 2) Require the new \"if\/2\" macro from MyMacros\n import MyMacros\n\n # 3) Use the new macro\n if do_something, it_works\n end\n end\n\n In the example above, we imported macros from `MyMacros`,\n replacing the original `if\/2` implementation by our own\n within that specific function. All other functions in that\n module will still be able to use the original one.\n\n ## Warnings\n\n If you import a module and you don't use any of the imported\n functions or macros from this module, Elixir is going to issue\n a warning implying the import is not being used.\n\n In case the import is generated automatically by a macro,\n Elixir won't emit any warnings though, since the import\n was not explicitly defined.\n\n Both warning behaviours could be changed by explicitly\n setting the `:warn` option to `true` or `false`.\n\n ## Ambiguous function\/macro names\n\n If two modules `A` and `B` are imported and they both contain\n a `foo` function with an arity of `1`, an error is only emitted\n if an ambiguous call to `foo\/1` is actually made; that is, the\n errors are emitted lazily, not eagerly.\n \"\"\"\n defmacro import(module, opts), do: error!([module, opts])\n\n @doc \"\"\"\n Returns the current environment information as a `Macro.Env` struct.\n\n In the environment you can access the current filename,\n line numbers, set up aliases, the current function and others.\n \"\"\"\n defmacro __ENV__, do: error!([])\n\n @doc \"\"\"\n Returns the current module name as an atom or `nil` otherwise.\n\n Although the module can be accessed in the `__ENV__\/0`, this macro\n is a convenient shortcut.\n \"\"\"\n defmacro __MODULE__, do: error!([])\n\n @doc \"\"\"\n Returns the absolute path of the directory of the current file as a binary.\n\n Although the directory can be accessed as `Path.dirname(__ENV__.file)`,\n this macro is a convenient shortcut.\n \"\"\"\n defmacro __DIR__, do: error!([])\n\n @doc \"\"\"\n Returns the current calling environment as a `Macro.Env` struct.\n\n In the environment you can access the filename, line numbers,\n set up aliases, the function and others.\n \"\"\"\n defmacro __CALLER__, do: error!([])\n\n @doc \"\"\"\n Returns the stacktrace for the currently handled exception.\n\n It is available only in the `catch` and `rescue` clauses of `try\/1`\n expressions.\n\n To retrieve the stacktrace of the current process, use\n `Process.info(self(), :current_stacktrace)` instead.\n \"\"\"\n defmacro __STACKTRACE__, do: error!([])\n\n @doc \"\"\"\n Accesses an already bound variable in match clauses. Also known as the pin operator.\n\n ## Examples\n\n Elixir allows variables to be rebound via static single assignment:\n\n iex> x = 1\n iex> x = x + 1\n iex> x\n 2\n\n However, in some situations, it is useful to match against an existing\n value, instead of rebinding. This can be done with the `^` special form,\n colloquially known as the pin operator:\n\n iex> x = 1\n iex> ^x = List.first([1])\n iex> ^x = List.first([2])\n ** (MatchError) no match of right hand side value: 2\n\n Note that `^x` always refers to the value of `x` prior to the match. The\n following example will match:\n\n iex> x = 0\n iex> {x, ^x} = {1, 0}\n iex> x\n 1\n\n \"\"\"\n defmacro ^var, do: error!([var])\n\n @doc \"\"\"\n Matches the value on the right against the pattern on the left.\n \"\"\"\n defmacro left = right, do: error!([left, right])\n\n @doc \"\"\"\n Used by types and bitstrings to specify types.\n\n This operator is used in two distinct occasions in Elixir.\n It is used in typespecs to specify the type of a variable,\n function or of a type itself:\n\n @type number :: integer | float\n @spec add(number, number) :: number\n\n It may also be used in bit strings to specify the type\n of a given bit segment:\n\n <> = bits\n\n Read the documentation on the `Typespec` page and\n `<<>>\/1` for more information on typespecs and\n bitstrings respectively.\n \"\"\"\n defmacro left :: right, do: error!([left, right])\n\n @doc ~S\"\"\"\n Gets the representation of any expression.\n\n ## Examples\n\n iex> quote do\n ...> sum(1, 2, 3)\n ...> end\n {:sum, [], [1, 2, 3]}\n\n ## Elixir's AST (Abstract Syntax Tree)\n\n Any Elixir code can be represented using Elixir data structures.\n The building block of Elixir macros is a tuple with three elements,\n for example:\n\n {:sum, [], [1, 2, 3]}\n\n The tuple above represents a function call to `sum` passing 1, 2 and\n 3 as arguments. The tuple elements are:\n\n * The first element of the tuple is always an atom or\n another tuple in the same representation.\n\n * The second element of the tuple represents metadata.\n\n * The third element of the tuple are the arguments for the\n function call. The third argument may be an atom, which is\n usually a variable (or a local call).\n\n Besides the tuple described above, Elixir has a few literals that\n are also part of its AST. Those literals return themselves when\n quoted. They are:\n\n :sum #=> Atoms\n 1 #=> Integers\n 2.0 #=> Floats\n [1, 2] #=> Lists\n \"strings\" #=> Strings\n {key, value} #=> Tuples with two elements\n\n Any other value, such as a map or a four-element tuple, must be escaped\n (`Macro.escape\/1`) before being introduced into an AST.\n\n ## Options\n\n * `:unquote` - when `false`, disables unquoting. This means any `unquote`\n call will be kept as is in the AST, instead of replaced by the `unquote`\n arguments. For example:\n\n iex> quote do\n ...> unquote(\"hello\")\n ...> end\n \"hello\"\n\n iex> quote unquote: false do\n ...> unquote(\"hello\")\n ...> end\n {:unquote, [], [\"hello\"]}\n\n * `:location` - when set to `:keep`, keeps the current line and file from\n quote. Read the Stacktrace information section below for more\n information.\n\n * `:line` - sets the quoted expressions to have the given line.\n\n * `:generated` - marks the given chunk as generated so it does not emit warnings.\n Currently it only works on special forms (for example, you can annotate a `case`\n but not an `if`).\n\n * `:context` - sets the resolution context.\n\n * `:bind_quoted` - passes a binding to the macro. Whenever a binding is\n given, `unquote\/1` is automatically disabled.\n\n ## Quote and macros\n\n `quote\/2` is commonly used with macros for code generation. As an exercise,\n let's define a macro that multiplies a number by itself (squared). In practice,\n there is no reason to define such as a macro (and it would actually be\n seen as a bad practice), but it is simple enough that it allows us to focus\n on the important aspects of quotes and macros:\n\n defmodule Math do\n defmacro squared(x) do\n quote do\n unquote(x) * unquote(x)\n end\n end\n end\n\n We can invoke it as:\n\n import Math\n IO.puts \"Got #{squared(5)}\"\n\n At first, there is nothing in this example that actually reveals it is a\n macro. But what is happening is that, at compilation time, `squared(5)`\n becomes `5 * 5`. The argument `5` is duplicated in the produced code, we\n can see this behaviour in practice though because our macro actually has\n a bug:\n\n import Math\n my_number = fn ->\n IO.puts \"Returning 5\"\n 5\n end\n IO.puts \"Got #{squared(my_number.())}\"\n\n The example above will print:\n\n Returning 5\n Returning 5\n Got 25\n\n Notice how \"Returning 5\" was printed twice, instead of just once. This is\n because a macro receives an expression and not a value (which is what we\n would expect in a regular function). This means that:\n\n squared(my_number.())\n\n Actually expands to:\n\n my_number.() * my_number.()\n\n Which invokes the function twice, explaining why we get the printed value\n twice! In the majority of the cases, this is actually unexpected behaviour,\n and that's why one of the first things you need to keep in mind when it\n comes to macros is to **not unquote the same value more than once**.\n\n Let's fix our macro:\n\n defmodule Math do\n defmacro squared(x) do\n quote do\n x = unquote(x)\n x * x\n end\n end\n end\n\n Now invoking `squared(my_number.())` as before will print the value just\n once.\n\n In fact, this pattern is so common that most of the times you will want\n to use the `bind_quoted` option with `quote\/2`:\n\n defmodule Math do\n defmacro squared(x) do\n quote bind_quoted: [x: x] do\n x * x\n end\n end\n end\n\n `:bind_quoted` will translate to the same code as the example above.\n `:bind_quoted` can be used in many cases and is seen as good practice,\n not only because it helps prevent us from running into common mistakes, but also\n because it allows us to leverage other tools exposed by macros, such as\n unquote fragments discussed in some sections below.\n\n Before we finish this brief introduction, you will notice that, even though\n we defined a variable `x` inside our quote:\n\n quote do\n x = unquote(x)\n x * x\n end\n\n When we call:\n\n import Math\n squared(5)\n x #=> ** (CompileError) undefined variable x or undefined function x\/0\n\n We can see that `x` did not leak to the user context. This happens\n because Elixir macros are hygienic, a topic we will discuss at length\n in the next sections as well.\n\n ## Hygiene in variables\n\n Consider the following example:\n\n defmodule Hygiene do\n defmacro no_interference do\n quote do\n a = 1\n end\n end\n end\n\n require Hygiene\n\n a = 10\n Hygiene.no_interference\n a #=> 10\n\n In the example above, `a` returns 10 even if the macro\n is apparently setting it to 1 because variables defined\n in the macro do not affect the context the macro is executed in.\n If you want to set or get a variable in the caller's context, you\n can do it with the help of the `var!` macro:\n\n defmodule NoHygiene do\n defmacro interference do\n quote do\n var!(a) = 1\n end\n end\n end\n\n require NoHygiene\n\n a = 10\n NoHygiene.interference\n a #=> 1\n\n You cannot even access variables defined in the same module unless\n you explicitly give it a context:\n\n defmodule Hygiene do\n defmacro write do\n quote do\n a = 1\n end\n end\n\n defmacro read do\n quote do\n a\n end\n end\n end\n\n Hygiene.write\n Hygiene.read\n #=> ** (RuntimeError) undefined variable a or undefined function a\/0\n\n For such, you can explicitly pass the current module scope as\n argument:\n\n defmodule ContextHygiene do\n defmacro write do\n quote do\n var!(a, ContextHygiene) = 1\n end\n end\n\n defmacro read do\n quote do\n var!(a, ContextHygiene)\n end\n end\n end\n\n ContextHygiene.write\n ContextHygiene.read\n #=> 1\n\n ## Hygiene in aliases\n\n Aliases inside quote are hygienic by default.\n Consider the following example:\n\n defmodule Hygiene do\n alias Map, as: M\n\n defmacro no_interference do\n quote do\n M.new\n end\n end\n end\n\n require Hygiene\n Hygiene.no_interference #=> %{}\n\n Notice that, even though the alias `M` is not available\n in the context the macro is expanded, the code above works\n because `M` still expands to `Map`.\n\n Similarly, even if we defined an alias with the same name\n before invoking a macro, it won't affect the macro's result:\n\n defmodule Hygiene do\n alias Map, as: M\n\n defmacro no_interference do\n quote do\n M.new\n end\n end\n end\n\n require Hygiene\n alias SomethingElse, as: M\n Hygiene.no_interference #=> %{}\n\n In some cases, you want to access an alias or a module defined\n in the caller. For such, you can use the `alias!` macro:\n\n defmodule Hygiene do\n # This will expand to Elixir.Nested.hello\n defmacro no_interference do\n quote do\n Nested.hello\n end\n end\n\n # This will expand to Nested.hello for\n # whatever is Nested in the caller\n defmacro interference do\n quote do\n alias!(Nested).hello\n end\n end\n end\n\n defmodule Parent do\n defmodule Nested do\n def hello, do: \"world\"\n end\n\n require Hygiene\n Hygiene.no_interference\n #=> ** (UndefinedFunctionError) ...\n\n Hygiene.interference\n #=> \"world\"\n end\n\n ## Hygiene in imports\n\n Similar to aliases, imports in Elixir are hygienic. Consider the\n following code:\n\n defmodule Hygiene do\n defmacrop get_length do\n quote do\n length([1, 2, 3])\n end\n end\n\n def return_length do\n import Kernel, except: [length: 1]\n get_length\n end\n end\n\n Hygiene.return_length #=> 3\n\n Notice how `Hygiene.return_length\/0` returns `3` even though the `Kernel.length\/1`\n function is not imported. In fact, even if `return_length\/0`\n imported a function with the same name and arity from another\n module, it wouldn't affect the function result:\n\n def return_length do\n import String, only: [length: 1]\n get_length\n end\n\n Calling this new `return_length\/0` will still return `3` as result.\n\n Elixir is smart enough to delay the resolution to the latest\n possible moment. So, if you call `length([1, 2, 3])` inside quote,\n but no `length\/1` function is available, it is then expanded in\n the caller:\n\n defmodule Lazy do\n defmacrop get_length do\n import Kernel, except: [length: 1]\n\n quote do\n length(\"hello\")\n end\n end\n\n def return_length do\n import Kernel, except: [length: 1]\n import String, only: [length: 1]\n get_length\n end\n end\n\n Lazy.return_length #=> 5\n\n ## Stacktrace information\n\n When defining functions via macros, developers have the option of\n choosing if runtime errors will be reported from the caller or from\n inside the quote. Let's see an example:\n\n # adder.ex\n defmodule Adder do\n @doc \"Defines a function that adds two numbers\"\n defmacro defadd do\n quote location: :keep do\n def add(a, b), do: a + b\n end\n end\n end\n\n # sample.ex\n defmodule Sample do\n import Adder\n defadd\n end\n\n require Sample\n Sample.add(:one, :two)\n #=> ** (ArithmeticError) bad argument in arithmetic expression\n #=> adder.ex:5: Sample.add\/2\n\n When using `location: :keep` and invalid arguments are given to\n `Sample.add\/2`, the stacktrace information will point to the file\n and line inside the quote. Without `location: :keep`, the error is\n reported to where `defadd` was invoked. `location: :keep` affects\n only definitions inside the quote.\n\n ## Binding and unquote fragments\n\n Elixir quote\/unquote mechanisms provides a functionality called\n unquote fragments. Unquote fragments provide an easy way to generate\n functions on the fly. Consider this example:\n\n kv = [foo: 1, bar: 2]\n Enum.each kv, fn {k, v} ->\n def unquote(k)(), do: unquote(v)\n end\n\n In the example above, we have generated the functions `foo\/0` and\n `bar\/0` dynamically. Now, imagine that, we want to convert this\n functionality into a macro:\n\n defmacro defkv(kv) do\n Enum.map kv, fn {k, v} ->\n quote do\n def unquote(k)(), do: unquote(v)\n end\n end\n end\n\n We can invoke this macro as:\n\n defkv [foo: 1, bar: 2]\n\n However, we can't invoke it as follows:\n\n kv = [foo: 1, bar: 2]\n defkv kv\n\n This is because the macro is expecting its arguments to be a\n keyword list at **compilation** time. Since in the example above\n we are passing the representation of the variable `kv`, our\n code fails.\n\n This is actually a common pitfall when developing macros. We are\n assuming a particular shape in the macro. We can work around it\n by unquoting the variable inside the quoted expression:\n\n defmacro defkv(kv) do\n quote do\n Enum.each unquote(kv), fn {k, v} ->\n def unquote(k)(), do: unquote(v)\n end\n end\n end\n\n If you try to run our new macro, you will notice it won't\n even compile, complaining that the variables `k` and `v`\n do not exist. This is because of the ambiguity: `unquote(k)`\n can either be an unquote fragment, as previously, or a regular\n unquote as in `unquote(kv)`.\n\n One solution to this problem is to disable unquoting in the\n macro, however, doing that would make it impossible to inject the\n `kv` representation into the tree. That's when the `:bind_quoted`\n option comes to the rescue (again!). By using `:bind_quoted`, we\n can automatically disable unquoting while still injecting the\n desired variables into the tree:\n\n defmacro defkv(kv) do\n quote bind_quoted: [kv: kv] do\n Enum.each kv, fn {k, v} ->\n def unquote(k)(), do: unquote(v)\n end\n end\n end\n\n In fact, the `:bind_quoted` option is recommended every time\n one desires to inject a value into the quote.\n \"\"\"\n defmacro quote(opts, block), do: error!([opts, block])\n\n @doc \"\"\"\n Unquotes the given expression inside a quoted expression.\n\n This function expects a valid Elixir AST, also known as\n quoted expression, as argument. If you would like to `unquote`\n any value, such as a map or a four-element tuple, you should\n call `Macro.escape\/1` before unquoting.\n\n ## Examples\n\n Imagine the situation you have a quoted expression and\n you want to inject it inside some quote. The first attempt\n would be:\n\n value =\n quote do\n 13\n end\n\n quote do\n sum(1, value, 3)\n end\n\n Which would then return:\n\n {:sum, [], [1, {:value, [], Elixir}, 3]}\n\n Which is not the expected result. For this, we use `unquote`:\n\n iex> value =\n ...> quote do\n ...> 13\n ...> end\n iex> quote do\n ...> sum(1, unquote(value), 3)\n ...> end\n {:sum, [], [1, 13, 3]}\n\n If you want to unquote a value that is not a quoted expression,\n such as a map, you need to call `Macro.escape\/1` before:\n\n iex> value = %{foo: :bar}\n iex> quote do\n ...> process_map(unquote(Macro.escape(value)))\n ...> end\n {:process_map, [], [{:%{}, [], [foo: :bar]}]}\n\n If you forget to escape it, Elixir will raise an error\n when compiling the code.\n \"\"\"\n defmacro unquote(:unquote)(expr), do: error!([expr])\n\n @doc \"\"\"\n Unquotes the given list expanding its arguments.\n\n Similar to `unquote\/1`.\n\n ## Examples\n\n iex> values = [2, 3, 4]\n iex> quote do\n ...> sum(1, unquote_splicing(values), 5)\n ...> end\n {:sum, [], [1, 2, 3, 4, 5]}\n\n \"\"\"\n defmacro unquote(:unquote_splicing)(expr), do: error!([expr])\n\n @doc ~S\"\"\"\n Comprehensions allow you to quickly build a data structure from\n an enumerable or a bitstring.\n\n Let's start with an example:\n\n iex> for n <- [1, 2, 3, 4], do: n * 2\n [2, 4, 6, 8]\n\n A comprehension accepts many generators and filters. Enumerable\n generators are defined using `<-`:\n\n # A list generator:\n iex> for n <- [1, 2, 3, 4], do: n * 2\n [2, 4, 6, 8]\n\n # A comprehension with two generators\n iex> for x <- [1, 2], y <- [2, 3], do: x * y\n [2, 3, 4, 6]\n\n Filters can also be given:\n\n # A comprehension with a generator and a filter\n iex> for n <- [1, 2, 3, 4, 5, 6], rem(n, 2) == 0, do: n\n [2, 4, 6]\n\n Generators can also be used to filter as it removes any value\n that doesn't match the pattern on the left side of `<-`:\n\n iex> users = [user: \"john\", admin: \"meg\", guest: \"barbara\"]\n iex> for {type, name} when type != :guest <- users do\n ...> String.upcase(name)\n ...> end\n [\"JOHN\", \"MEG\"]\n\n Bitstring generators are also supported and are very useful when you\n need to organize bitstring streams:\n\n iex> pixels = <<213, 45, 132, 64, 76, 32, 76, 0, 0, 234, 32, 15>>\n iex> for <>, do: {r, g, b}\n [{213, 45, 132}, {64, 76, 32}, {76, 0, 0}, {234, 32, 15}]\n\n Variable assignments inside the comprehension, be it in generators,\n filters or inside the block, are not reflected outside of the\n comprehension.\n\n ## The `:into` and `:uniq` options\n\n In the examples above, the result returned by the comprehension was\n always a list. The returned result can be configured by passing an\n `:into` option, that accepts any structure as long as it implements\n the `Collectable` protocol.\n\n For example, we can use bitstring generators with the `:into` option\n to easily remove all spaces in a string:\n\n iex> for <>, c != ?\\s, into: \"\", do: <>\n \"helloworld\"\n\n The `IO` module provides streams, that are both `Enumerable` and\n `Collectable`, here is an upcase echo server using comprehensions:\n\n for line <- IO.stream(:stdio, :line), into: IO.stream(:stdio, :line) do\n String.upcase(line)\n end\n\n Similarly, `uniq: true` can also be given to comprehensions to guarantee\n the results are only added to the collection if they were not returned\n before. For example:\n\n iex> for x <- [1, 1, 2, 3], uniq: true, do: x * 2\n [2, 4, 6]\n\n iex> for <>, uniq: true, into: \"\", do: <>\n \"ABC\"\n\n ## The `:reduce` option\n\n While the `:into` option allows us to customize the comprehension behaviour\n to a given data type, such as putting all of the values inside a map or inside\n a binary, it is not always enough.\n\n For example, imagine that you have a binary with letters where you want to\n count how many times each lowercase letter happens, ignoring all uppercase\n ones. For instance, for the string `\"AbCabCABc\"`, we want to return the map\n `%{\"a\" => 1, \"b\" => 2, \"c\" => 1}`.\n\n If we were to use `:into`, we would need a data type that computes the\n frequency of each element it holds. While there is no such data type in\n Elixir, you could implement one yourself.\n\n A simpler option would be to use comprehensions for the mapping and\n filtering of letters, and then we invoke `Enum.reduce\/3` to build a map,\n for example:\n\n iex> letters = for <>, x in ?a..?z, do: <>\n iex> Enum.reduce(letters, %{}, fn x, acc -> Map.update(acc, x, 1, & &1 + 1) end)\n %{\"a\" => 1, \"b\" => 2, \"c\" => 1}\n\n While the above is straight-forward, it has the downside of traversing the\n data at least twice. If you are expecting long strings as inputs, this can\n be quite expensive.\n\n Luckily, comprehensions also support the `:reduce` option, which would allow\n us to fuse both steps above into a single step:\n\n iex> for <>, x in ?a..?z, reduce: %{} do\n ...> acc -> Map.update(acc, <>, 1, & &1 + 1)\n ...> end\n %{\"a\" => 1, \"b\" => 2, \"c\" => 1}\n\n When the `:reduce` key is given, its value is used as the initial accumulator\n and the `do` block must be changed to use `->` clauses, where the left side\n of `->` receives the accumulated value of the previous iteration and the\n expression on the right side must return the new accumulator value. Once there are no more\n elements, the final accumulated value is returned. If there are no elements\n at all, then the initial accumulator value is returned.\n \"\"\"\n defmacro for(args), do: error!([args])\n\n @doc \"\"\"\n Used to combine matching clauses.\n\n Let's start with an example:\n\n iex> opts = %{width: 10, height: 15}\n iex> with {:ok, width} <- Map.fetch(opts, :width),\n ...> {:ok, height} <- Map.fetch(opts, :height) do\n ...> {:ok, width * height}\n ...> end\n {:ok, 150}\n\n If all clauses match, the `do` block is executed, returning its result.\n Otherwise the chain is aborted and the non-matched value is returned:\n\n iex> opts = %{width: 10}\n iex> with {:ok, width} <- Map.fetch(opts, :width),\n ...> {:ok, height} <- Map.fetch(opts, :height) do\n ...> {:ok, width * height}\n ...> end\n :error\n\n Guards can be used in patterns as well:\n\n iex> users = %{\"melany\" => \"guest\", \"bob\" => :admin}\n iex> with {:ok, role} when not is_binary(role) <- Map.fetch(users, \"bob\") do\n ...> {:ok, to_string(role)}\n ...> end\n {:ok, \"admin\"}\n\n As in `for\/1`, variables bound inside `with\/1` won't leak.\n Expressions without `<-` may also be used in clauses. For instance,\n you can perform regular matches with the `=` operator:\n\n iex> width = nil\n iex> opts = %{width: 10, height: 15}\n iex> with {:ok, width} <- Map.fetch(opts, :width),\n ...> double_width = width * 2,\n ...> {:ok, height} <- Map.fetch(opts, :height) do\n ...> {:ok, double_width * height}\n ...> end\n {:ok, 300}\n iex> width\n nil\n\n The behaviour of any expression in a clause is the same as outside.\n For example, `=` will raise a `MatchError` instead of returning the\n non-matched value:\n\n with :foo = :bar, do: :ok\n #=> ** (MatchError) no match of right hand side value: :bar\n\n As with any other function or macro call in Elixir, explicit parens can\n also be used around the arguments before the `do`\/`end` block:\n\n iex> opts = %{width: 10, height: 15}\n iex> with(\n ...> {:ok, width} <- Map.fetch(opts, :width),\n ...> {:ok, height} <- Map.fetch(opts, :height)\n ...> ) do\n ...> {:ok, width * height}\n ...> end\n {:ok, 150}\n\n The choice between parens and no parens is a matter of preference.\n\n An `else` option can be given to modify what is being returned from\n `with` in the case of a failed match:\n\n iex> opts = %{width: 10}\n iex> with {:ok, width} <- Map.fetch(opts, :width),\n ...> {:ok, height} <- Map.fetch(opts, :height) do\n ...> {:ok, width * height}\n ...> else\n ...> :error ->\n ...> {:error, :wrong_data}\n ...> end\n {:error, :wrong_data}\n\n If an `else` block is used and there are no matching clauses, a `WithClauseError`\n exception is raised.\n \"\"\"\n defmacro with(args), do: error!([args])\n\n @doc \"\"\"\n Defines an anonymous function.\n\n ## Examples\n\n iex> add = fn a, b -> a + b end\n iex> add.(1, 2)\n 3\n\n Anonymous functions can also have multiple clauses. All clauses\n should expect the same number of arguments:\n\n iex> negate = fn\n ...> true -> false\n ...> false -> true\n ...> end\n iex> negate.(false)\n true\n\n \"\"\"\n defmacro unquote(:fn)(clauses), do: error!([clauses])\n\n @doc \"\"\"\n Internal special form for block expressions.\n\n This is the special form used whenever we have a block\n of expressions in Elixir. This special form is private\n and should not be invoked directly:\n\n iex> quote do\n ...> 1\n ...> 2\n ...> 3\n ...> end\n {:__block__, [], [1, 2, 3]}\n\n \"\"\"\n defmacro unquote(:__block__)(args), do: error!([args])\n\n @doc \"\"\"\n Captures or creates an anonymous function.\n\n ## Capture\n\n The capture operator is most commonly used to capture a\n function with given name and arity from a module:\n\n iex> fun = &Kernel.is_atom\/1\n iex> fun.(:atom)\n true\n iex> fun.(\"string\")\n false\n\n In the example above, we captured `Kernel.is_atom\/1` as an\n anonymous function and then invoked it.\n\n The capture operator can also be used to capture local functions,\n including private ones, and imported functions by omitting the\n module name:\n\n &local_function\/1\n\n ## Anonymous functions\n\n The capture operator can also be used to partially apply\n functions, where `&1`, `&2` and so on can be used as value\n placeholders. For example:\n\n iex> double = &(&1 * 2)\n iex> double.(2)\n 4\n\n In other words, `&(&1 * 2)` is equivalent to `fn x -> x * 2 end`.\n\n We can partially apply a remote function with placeholder:\n\n iex> take_five = &Enum.take(&1, 5)\n iex> take_five.(1..10)\n [1, 2, 3, 4, 5]\n\n Another example while using an imported or local function:\n\n iex> first_elem = &elem(&1, 0)\n iex> first_elem.({0, 1})\n 0\n\n The `&` operator can be used with more complex expressions:\n\n iex> fun = &(&1 + &2 + &3)\n iex> fun.(1, 2, 3)\n 6\n\n As well as with lists and tuples:\n\n iex> fun = &{&1, &2}\n iex> fun.(1, 2)\n {1, 2}\n\n iex> fun = &[&1 | &2]\n iex> fun.(1, [2, 3])\n [1, 2, 3]\n\n The only restrictions when creating anonymous functions is that at\n least one placeholder must be present, i.e. it must contain at least\n `&1`, and that block expressions are not supported:\n\n # No placeholder, fails to compile.\n &(:foo)\n\n # Block expression, fails to compile.\n &(&1; &2)\n\n \"\"\"\n defmacro unquote(:&)(expr), do: error!([expr])\n\n @doc \"\"\"\n Internal special form to hold aliases information.\n\n It is usually compiled to an atom:\n\n iex> quote do\n ...> Foo.Bar\n ...> end\n {:__aliases__, [alias: false], [:Foo, :Bar]}\n\n Elixir represents `Foo.Bar` as `__aliases__` so calls can be\n unambiguously identified by the operator `:.`. For example:\n\n iex> quote do\n ...> Foo.bar\n ...> end\n {{:., [], [{:__aliases__, [alias: false], [:Foo]}, :bar]}, [], []}\n\n Whenever an expression iterator sees a `:.` as the tuple key,\n it can be sure that it represents a call and the second argument\n in the list is an atom.\n\n On the other hand, aliases holds some properties:\n\n 1. The head element of aliases can be any term that must expand to\n an atom at compilation time.\n\n 2. The tail elements of aliases are guaranteed to always be atoms.\n\n 3. When the head element of aliases is the atom `:Elixir`, no expansion happens.\n\n \"\"\"\n defmacro unquote(:__aliases__)(args), do: error!([args])\n\n @doc \"\"\"\n Calls the overridden function when overriding it with `Kernel.defoverridable\/1`.\n\n See `Kernel.defoverridable\/1` for more information and documentation.\n \"\"\"\n defmacro super(args), do: error!([args])\n\n @doc ~S\"\"\"\n Matches the given expression against the given clauses.\n\n ## Examples\n\n case thing do\n {:selector, i, value} when is_integer(i) ->\n value\n value ->\n value\n end\n\n In the example above, we match `thing` against each clause \"head\"\n and execute the clause \"body\" corresponding to the first clause\n that matches.\n\n If no clause matches, an error is raised.\n For this reason, it may be necessary to add a final catch-all clause (like `_`)\n which will always match.\n\n x = 10\n\n case x do\n 0 ->\n \"This clause won't match\"\n _ ->\n \"This clause would match any value (x = #{x})\"\n end\n #=> \"This clause would match any value (x = 10)\"\n\n ## Variables handling\n\n Notice that variables bound in a clause \"head\" do not leak to the\n outer context:\n\n case data do\n {:ok, value} -> value\n :error -> nil\n end\n\n value #=> unbound variable value\n\n However, variables explicitly bound in the clause \"body\" are\n accessible from the outer context:\n\n value = 7\n\n case lucky? do\n false -> value = 13\n true -> true\n end\n\n value #=> 7 or 13\n\n In the example above, value is going to be `7` or `13` depending on\n the value of `lucky?`. In case `value` has no previous value before\n case, clauses that do not explicitly bind a value have the variable\n bound to `nil`.\n\n If you want to pattern match against an existing variable,\n you need to use the `^\/1` operator:\n\n x = 1\n\n case 10 do\n ^x -> \"Won't match\"\n _ -> \"Will match\"\n end\n #=> \"Will match\"\n\n \"\"\"\n defmacro case(condition, clauses), do: error!([condition, clauses])\n\n @doc \"\"\"\n Evaluates the expression corresponding to the first clause that\n evaluates to a truthy value.\n\n cond do\n hd([1, 2, 3]) ->\n \"1 is considered as true\"\n end\n #=> \"1 is considered as true\"\n\n Raises an error if all conditions evaluate to `nil` or `false`.\n For this reason, it may be necessary to add a final always-truthy condition\n (anything non-`false` and non-`nil`), which will always match.\n\n ## Examples\n\n cond do\n 1 + 1 == 1 ->\n \"This will never match\"\n 2 * 2 != 4 ->\n \"Nor this\"\n true ->\n \"This will\"\n end\n #=> \"This will\"\n\n \"\"\"\n defmacro cond(clauses), do: error!([clauses])\n\n @doc ~S\"\"\"\n Evaluates the given expressions and handles any error, exit,\n or throw that may have happened.\n\n ## Examples\n\n try do\n do_something_that_may_fail(some_arg)\n rescue\n ArgumentError ->\n IO.puts \"Invalid argument given\"\n catch\n value ->\n IO.puts \"Caught #{inspect(value)}\"\n else\n value ->\n IO.puts \"Success! The result was #{inspect(value)}\"\n after\n IO.puts \"This is printed regardless if it failed or succeed\"\n end\n\n The `rescue` clause is used to handle exceptions while the `catch`\n clause can be used to catch thrown values and exits.\n The `else` clause can be used to control flow based on the result of\n the expression. `catch`, `rescue`, and `else` clauses work based on\n pattern matching (similar to the `case` special form).\n\n Calls inside `try\/1` are not tail recursive since the VM needs to keep\n the stacktrace in case an exception happens. To retrieve the stacktrace,\n access `__STACKTRACE__\/0` inside the `rescue` or `catch` clause.\n\n ## `rescue` clauses\n\n Besides relying on pattern matching, `rescue` clauses provide some\n conveniences around exceptions that allow one to rescue an\n exception by its name. All the following formats are valid patterns\n in `rescue` clauses:\n\n # Rescue a single exception without binding the exception\n # to a variable\n try do\n UndefinedModule.undefined_function\n rescue\n UndefinedFunctionError -> nil\n end\n\n # Rescue any of the given exception without binding\n try do\n UndefinedModule.undefined_function\n rescue\n [UndefinedFunctionError, ArgumentError] -> nil\n end\n\n # Rescue and bind the exception to the variable \"x\"\n try do\n UndefinedModule.undefined_function\n rescue\n x in [UndefinedFunctionError] -> nil\n end\n\n # Rescue all kinds of exceptions and bind the rescued exception\n # to the variable \"x\"\n try do\n UndefinedModule.undefined_function\n rescue\n x -> nil\n end\n\n ### Erlang errors\n\n Erlang errors are transformed into Elixir ones when rescuing:\n\n try do\n :erlang.error(:badarg)\n rescue\n ArgumentError -> :ok\n end\n #=> :ok\n\n The most common Erlang errors will be transformed into their\n Elixir counterpart. Those which are not will be transformed\n into the more generic `ErlangError`:\n\n try do\n :erlang.error(:unknown)\n rescue\n ErlangError -> :ok\n end\n #=> :ok\n\n In fact, `ErlangError` can be used to rescue any error that is\n not a proper Elixir error. For example, it can be used to rescue\n the earlier `:badarg` error too, prior to transformation:\n\n try do\n :erlang.error(:badarg)\n rescue\n ErlangError -> :ok\n end\n #=> :ok\n\n ## `catch` clauses\n\n The `catch` clause can be used to catch thrown values, exits, and errors.\n\n ### Catching thrown values\n\n `catch` can be used to catch values thrown by `Kernel.throw\/1`:\n\n try do\n throw(:some_value)\n catch\n thrown_value ->\n IO.puts \"A value was thrown: #{inspect(thrown_value)}\"\n end\n\n ### Catching values of any kind\n\n The `catch` clause also supports catching exits and errors. To do that, it\n allows matching on both the *kind* of the caught value as well as the value\n itself:\n\n try do\n exit(:shutdown)\n catch\n :exit, value\n IO.puts \"Exited with value #{inspect(value)}\"\n end\n\n try do\n exit(:shutdown)\n catch\n kind, value when kind in [:exit, :throw] ->\n IO.puts \"Caught exit or throw with value #{inspect(value)}\"\n end\n\n The `catch` clause also supports `:error` alongside `:exit` and `:throw` as\n in Erlang, although this is commonly avoided in favor of `raise`\/`rescue` control\n mechanisms. One reason for this is that when catching `:error`, the error is\n not automatically transformed into an Elixir error:\n\n try do\n :erlang.error(:badarg)\n catch\n :error, :badarg -> :ok\n end\n #=> :ok\n\n ## `after` clauses\n\n An `after` clause allows you to define cleanup logic that will be invoked both\n when the block of code passed to `try\/1` succeeds and also when an error is raised. Note\n that the process will exit as usual when receiving an exit signal that causes\n it to exit abruptly and so the `after` clause is not guaranteed to be executed.\n Luckily, most resources in Elixir (such as open files, ETS tables, ports, sockets,\n and so on) are linked to or monitor the owning process and will automatically clean\n themselves up if that process exits.\n\n File.write!(\"tmp\/story.txt\", \"Hello, World\")\n try do\n do_something_with(\"tmp\/story.txt\")\n after\n File.rm(\"tmp\/story.txt\")\n end\n\n ## `else` clauses\n\n `else` clauses allow the result of the body passed to `try\/1` to be pattern\n matched on:\n\n x = 2\n try do\n 1 \/ x\n rescue\n ArithmeticError ->\n :infinity\n else\n y when y < 1 and y > -1 ->\n :small\n _ ->\n :large\n end\n\n If an `else` clause is not present and no exceptions are raised,\n the result of the expression will be returned:\n\n x = 1\n ^x =\n try do\n 1 \/ x\n rescue\n ArithmeticError ->\n :infinity\n end\n\n However, when an `else` clause is present but the result of the expression\n does not match any of the patterns then an exception will be raised. This\n exception will not be caught by a `catch` or `rescue` in the same `try`:\n\n x = 1\n try do\n try do\n 1 \/ x\n rescue\n # The TryClauseError cannot be rescued here:\n TryClauseError ->\n :error_a\n else\n 0 ->\n :small\n end\n rescue\n # The TryClauseError is rescued here:\n TryClauseError ->\n :error_b\n end\n\n Similarly, an exception inside an `else` clause is not caught or rescued\n inside the same `try`:\n\n try do\n try do\n nil\n catch\n # The exit(1) call below can not be caught here:\n :exit, _ ->\n :exit_a\n else\n _ ->\n exit(1)\n end\n catch\n # The exit is caught here:\n :exit, _ ->\n :exit_b\n end\n\n This means the VM no longer needs to keep the stacktrace once inside\n an `else` clause and so tail recursion is possible when using a `try`\n with a tail call as the final call inside an `else` clause. The same\n is true for `rescue` and `catch` clauses.\n\n Only the result of the tried expression falls down to the `else` clause.\n If the `try` ends up in the `rescue` or `catch` clauses, their result\n will not fall down to `else`:\n\n try do\n throw(:catch_this)\n catch\n :throw, :catch_this ->\n :it_was_caught\n else\n # :it_was_caught will not fall down to this \"else\" clause.\n other ->\n {:else, other}\n end\n\n ## Variable handling\n\n Since an expression inside `try` may not have been evaluated\n due to an exception, any variable created inside `try` cannot\n be accessed externally. For instance:\n\n try do\n x = 1\n do_something_that_may_fail(same_arg)\n :ok\n catch\n _, _ -> :failed\n end\n\n x #=> unbound variable \"x\"\n\n In the example above, `x` cannot be accessed since it was defined\n inside the `try` clause. A common practice to address this issue\n is to return the variables defined inside `try`:\n\n x =\n try do\n x = 1\n do_something_that_may_fail(same_arg)\n x\n catch\n _, _ -> :failed\n end\n\n \"\"\"\n defmacro try(args), do: error!([args])\n\n @doc \"\"\"\n Checks if there is a message matching the given clauses\n in the current process mailbox.\n\n In case there is no such message, the current process hangs\n until a message arrives or waits until a given timeout value.\n\n ## Examples\n\n receive do\n {:selector, number, name} when is_integer(number) ->\n name\n name when is_atom(name) ->\n name\n _ ->\n IO.puts :stderr, \"Unexpected message received\"\n end\n\n An optional `after` clause can be given in case the message was not\n received after the given timeout period, specified in milliseconds:\n\n receive do\n {:selector, number, name} when is_integer(number) ->\n name\n name when is_atom(name) ->\n name\n _ ->\n IO.puts :stderr, \"Unexpected message received\"\n after\n 5000 ->\n IO.puts :stderr, \"No message in 5 seconds\"\n end\n\n The `after` clause can be specified even if there are no match clauses.\n The timeout value given to `after` can be any expression evaluating to\n one of the allowed values:\n\n * `:infinity` - the process should wait indefinitely for a matching\n message, this is the same as not using the after clause\n\n * `0` - if there is no matching message in the mailbox, the timeout\n will occur immediately\n\n * positive integer smaller than or equal to `4_294_967_295` (`0xFFFFFFFF`\n in hexadecimal notation) - it should be possible to represent the timeout\n value as an unsigned 32-bit integer.\n\n ## Variables handling\n\n The `receive\/1` special form handles variables exactly as the `case\/2`\n special macro. For more information, check the docs for `case\/2`.\n \"\"\"\n defmacro receive(args), do: error!([args])\nend\n","old_contents":"defmodule Kernel.SpecialForms do\n @moduledoc \"\"\"\n Special forms are the basic building blocks of Elixir, and therefore\n cannot be overridden by the developer.\n\n We define them in this module. Some of these forms are lexical (like\n `alias\/2`, `case\/2`, etc.). The macros `{}\/1` and `<<>>\/1` are also special\n forms used to define tuple and binary data structures respectively.\n\n This module also documents macros that return information about Elixir's\n compilation environment, such as (`__ENV__\/0`, `__MODULE__\/0`, `__DIR__\/0` and `__CALLER__\/0`).\n\n Finally, it also documents two special forms, `__block__\/1` and\n `__aliases__\/1`, which are not intended to be called directly by the\n developer but they appear in quoted contents since they are essential\n in Elixir's constructs.\n \"\"\"\n\n defmacrop error!(args) do\n quote do\n _ = unquote(args)\n\n message =\n \"Elixir's special forms are expanded by the compiler and must not be invoked directly\"\n\n :erlang.error(RuntimeError.exception(message))\n end\n end\n\n @doc \"\"\"\n Creates a tuple.\n\n More information about the tuple data type and about functions to manipulate\n tuples can be found in the `Tuple` module; some functions for working with\n tuples are also available in `Kernel` (such as `Kernel.elem\/2` or\n `Kernel.tuple_size\/1`).\n\n ## AST representation\n\n Only two-item tuples are considered literals in Elixir and return themselves\n when quoted. Therefore, all other tuples are represented in the AST as calls to\n the `:{}` special form.\n\n iex> quote do\n ...> {1, 2}\n ...> end\n {1, 2}\n\n iex> quote do\n ...> {1, 2, 3}\n ...> end\n {:{}, [], [1, 2, 3]}\n\n \"\"\"\n defmacro unquote(:{})(args), do: error!([args])\n\n @doc \"\"\"\n Creates a map.\n\n See the `Map` module for more information about maps, their syntax, and ways to\n access and manipulate them.\n\n ## AST representation\n\n Regardless of whether `=>` or the keyword syntax is used, key-value pairs in\n maps are always represented internally as a list of two-element tuples for\n simplicity:\n\n iex> quote do\n ...> %{\"a\" => :b, c: :d}\n ...> end\n {:%{}, [], [{\"a\", :b}, {:c, :d}]}\n\n \"\"\"\n defmacro unquote(:%{})(args), do: error!([args])\n\n @doc \"\"\"\n Matches on or builds a struct.\n\n A struct is a tagged map that allows developers to provide\n default values for keys, tags to be used in polymorphic\n dispatches and compile time assertions.\n\n Structs are usually defined with the `Kernel.defstruct\/1` macro:\n\n defmodule User do\n defstruct name: \"john\", age: 27\n end\n\n Now a struct can be created as follows:\n\n %User{}\n\n Underneath a struct is just a map with a `:__struct__` key\n pointing to the `User` module:\n\n %User{} == %{__struct__: User, name: \"john\", age: 27}\n\n The struct fields can be given when building the struct:\n\n %User{age: 31}\n #=> %{__struct__: User, name: \"john\", age: 31}\n\n Or also on pattern matching to extract values out:\n\n %User{age: age} = user\n\n An update operation specific for structs is also available:\n\n %User{user | age: 28}\n\n The advantage of structs is that they validate that the given\n keys are part of the defined struct. The example below will fail\n because there is no key `:full_name` in the `User` struct:\n\n %User{full_name: \"john doe\"}\n\n The syntax above will guarantee the given keys are valid at\n compilation time and it will guarantee at runtime the given\n argument is a struct, failing with `BadStructError` otherwise.\n\n Although structs are maps, by default structs do not implement\n any of the protocols implemented for maps. Check\n `Kernel.defprotocol\/2` for more information on how structs\n can be used with protocols for polymorphic dispatch. Also\n see `Kernel.struct\/2` and `Kernel.struct!\/2` for examples on\n how to create and update structs dynamically.\n\n ## Pattern matching on struct names\n\n Besides allowing pattern matching on struct fields, such as:\n\n %User{age: age} = user\n\n Structs also allow pattern matching on the struct name:\n\n %struct_name{} = user\n struct_name #=> User\n\n You can also assign the struct name to `_` when you want to\n check if something is a struct but you are not interested in\n its name:\n\n %_{} = user\n\n \"\"\"\n defmacro unquote(:%)(struct, map), do: error!([struct, map])\n\n @doc \"\"\"\n Defines a new bitstring.\n\n ## Examples\n\n iex> <<1, 2, 3>>\n <<1, 2, 3>>\n\n ## Types\n\n A bitstring is made of many segments and each segment has a\n type. There are 9 types used in bitstrings:\n\n - `integer`\n - `float`\n - `bits` (alias for `bitstring`)\n - `bitstring`\n - `binary`\n - `bytes` (alias for `binary`)\n - `utf8`\n - `utf16`\n - `utf32`\n\n When no type is specified, the default is `integer`:\n\n iex> <<1, 2, 3>>\n <<1, 2, 3>>\n\n Elixir also accepts by default the segment to be a literal\n string or a literal charlist, which are by default expanded to integers:\n\n iex> <<0, \"foo\">>\n <<0, 102, 111, 111>>\n\n Variables or any other type need to be explicitly tagged:\n\n iex> rest = \"oo\"\n iex> <<102, rest>>\n ** (ArgumentError) argument error\n\n We can solve this by explicitly tagging it as `binary`:\n\n iex> rest = \"oo\"\n iex> <<102, rest::binary>>\n \"foo\"\n\n The `utf8`, `utf16`, and `utf32` types are for Unicode codepoints. They\n can also be applied to literal strings and charlists:\n\n iex> <<\"foo\"::utf16>>\n <<0, 102, 0, 111, 0, 111>>\n iex> <<\"foo\"::utf32>>\n <<0, 0, 0, 102, 0, 0, 0, 111, 0, 0, 0, 111>>\n\n ## Options\n\n Many options can be given by using `-` as separator. Order is\n arbitrary, so the following are all equivalent:\n\n <<102::integer-native, rest::binary>>\n <<102::native-integer, rest::binary>>\n <<102::unsigned-big-integer, rest::binary>>\n <<102::unsigned-big-integer-size(8), rest::binary>>\n <<102::unsigned-big-integer-8, rest::binary>>\n <<102::8-integer-big-unsigned, rest::binary>>\n <<102, rest::binary>>\n\n ### Unit and Size\n\n The length of the match is equal to the `unit` (a number of bits) times the\n `size` (the number of repeated segments of length `unit`).\n\n Type | Default Unit\n --------- | ------------\n `integer` | 1 bit\n `float` | 1 bit\n `binary` | 8 bits\n\n Sizes for types are a bit more nuanced. The default size for integers is 8.\n\n For floats, it is 64. For floats, `size * unit` must result in 32 or 64,\n corresponding to [IEEE 754](https:\/\/en.wikipedia.org\/wiki\/IEEE_floating_point)\n binary32 and binary64, respectively.\n\n For binaries, the default is the size of the binary. Only the last binary in a\n match can use the default size. All others must have their size specified\n explicitly, even if the match is unambiguous. For example:\n\n iex> <> = <<\"Frank the Walrus\">>\n \"Frank the Walrus\"\n iex> {name, species}\n {\"Frank\", \"Walrus\"}\n\n The size can be a variable:\n\n iex> name_size = 5\n iex> <> = <<\"Frank the Walrus\">>\n iex> {name, species}\n {\"Frank\", \"Walrus\"}\n\n And the variable can be defined in the match itself (prior to its use):\n\n iex> <> = <<5, \"Frank the Walrus\">>\n iex> {name, species}\n {\"Frank\", \"Walrus\"}\n\n However, the size cannot be defined in the match outside the binary\/bitstring match:\n\n {name_size, <>} = {5, <<\"Frank the Walrus\">>}\n ** (CompileError): undefined variable \"name_size\" in bitstring segment\n\n Failing to specify the size for the non-last causes compilation to fail:\n\n <> = <<\"Frank the Walrus\">>\n ** (CompileError): a binary field without size is only allowed at the end of a binary pattern\n\n #### Shortcut Syntax\n\n Size and unit can also be specified using a syntax shortcut\n when passing integer values:\n\n iex> x = 1\n iex> <> == <>\n true\n iex> <> == <>\n true\n\n This syntax reflects the fact the effective size is given by\n multiplying the size by the unit.\n\n ### Modifiers\n\n Some types have associated modifiers to clear up ambiguity in byte\n representation.\n\n Modifier | Relevant Type(s)\n -------------------- | ----------------\n `signed` | `integer`\n `unsigned` (default) | `integer`\n `little` | `integer`, `float`, `utf16`, `utf32`\n `big` (default) | `integer`, `float`, `utf16`, `utf32`\n `native` | `integer`, `utf16`, `utf32`\n\n ### Sign\n\n Integers can be `signed` or `unsigned`, defaulting to `unsigned`.\n\n iex> <> = <<-100>>\n <<156>>\n iex> int\n 156\n iex> <> = <<-100>>\n <<156>>\n iex> int\n -100\n\n `signed` and `unsigned` are only used for matching binaries (see below) and\n are only used for integers.\n\n iex> <<-100::signed, _rest::binary>> = <<-100, \"foo\">>\n <<156, 102, 111, 111>>\n\n ### Endianness\n\n Elixir has three options for endianness: `big`, `little`, and `native`.\n The default is `big`:\n\n iex> <> = <<0, 1>>\n <<0, 1>>\n iex> number\n 256\n iex> <> = <<0, 1>>\n <<0, 1>>\n iex> number\n 1\n\n `native` is determined by the VM at startup and will depend on the\n host operating system.\n\n ## Binary\/Bitstring Matching\n\n Binary matching is a powerful feature in Elixir that is useful for extracting\n information from binaries as well as pattern matching.\n\n Binary matching can be used by itself to extract information from binaries:\n\n iex> <<\"Hello, \", place::binary>> = \"Hello, World\"\n \"Hello, World\"\n iex> place\n \"World\"\n\n Or as a part of function definitions to pattern match:\n\n defmodule ImageTyper do\n @png_signature <<137::size(8), 80::size(8), 78::size(8), 71::size(8),\n 13::size(8), 10::size(8), 26::size(8), 10::size(8)>>\n @jpg_signature <<255::size(8), 216::size(8)>>\n\n def type(<<@png_signature, rest::binary>>), do: :png\n def type(<<@jpg_signature, rest::binary>>), do: :jpg\n def type(_), do :unknown\n end\n\n ### Performance & Optimizations\n\n The Erlang compiler can provide a number of optimizations on binary creation\n and matching. To see optimization output, set the `bin_opt_info` compiler\n option:\n\n ERL_COMPILER_OPTIONS=bin_opt_info mix compile\n\n To learn more about specific optimizations and performance considerations,\n check out\n [Erlang's Efficiency Guide on handling binaries](http:\/\/www.erlang.org\/doc\/efficiency_guide\/binaryhandling.html).\n \"\"\"\n defmacro unquote(:<<>>)(args), do: error!([args])\n\n @doc \"\"\"\n Defines a remote call, a call to an anonymous function, or an alias.\n\n The dot (`.`) in Elixir can be used for remote calls:\n\n iex> String.downcase(\"FOO\")\n \"foo\"\n\n In this example above, we have used `.` to invoke `downcase` in the\n `String` module, passing `\"FOO\"` as argument.\n\n The dot may be used to invoke anonymous functions too:\n\n iex> (fn n -> n end).(7)\n 7\n\n in which case there is a function on the left hand side.\n\n We can also use the dot for creating aliases:\n\n iex> Hello.World\n Hello.World\n\n This time, we have joined two aliases, defining the final alias\n `Hello.World`.\n\n ## Syntax\n\n The right side of `.` may be a word starting with an uppercase letter, which represents\n an alias, a word starting with lowercase or underscore, any valid language\n operator or any name wrapped in single- or double-quotes. Those are all valid\n examples:\n\n iex> Kernel.Sample\n Kernel.Sample\n\n iex> Kernel.length([1, 2, 3])\n 3\n\n iex> Kernel.+(1, 2)\n 3\n\n iex> Kernel.\"+\"(1, 2)\n 3\n\n Wrapping the function name in single- or double-quotes is always a\n remote call. Therefore `Kernel.\"Foo\"` will attempt to call the function \"Foo\"\n and not return the alias `Kernel.Foo`. This is done by design as module names\n are more strict than function names.\n\n When the dot is used to invoke an anonymous function there is only one\n operand, but it is still written using a postfix notation:\n\n iex> negate = fn n -> -n end\n iex> negate.(7)\n -7\n\n ## Quoted expression\n\n When `.` is used, the quoted expression may take two distinct\n forms. When the right side starts with a lowercase letter (or\n underscore):\n\n iex> quote do\n ...> String.downcase(\"FOO\")\n ...> end\n {{:., [], [{:__aliases__, [alias: false], [:String]}, :downcase]}, [], [\"FOO\"]}\n\n Notice we have an inner tuple, containing the atom `:.` representing\n the dot as first element:\n\n {:., [], [{:__aliases__, [alias: false], [:String]}, :downcase]}\n\n This tuple follows the general quoted expression structure in Elixir,\n with the name as first argument, some keyword list as metadata as second,\n and the list of arguments as third. In this case, the arguments are the\n alias `String` and the atom `:downcase`. The second argument in a remote call\n is **always** an atom.\n\n In the case of calls to anonymous functions, the inner tuple with the dot\n special form has only one argument, reflecting the fact that the operator is\n unary:\n\n iex> quote do\n ...> negate.(0)\n ...> end\n {{:., [], [{:negate, [], __MODULE__}]}, [], [0]}\n\n When the right side is an alias (i.e. starts with uppercase), we get instead:\n\n iex> quote do\n ...> Hello.World\n ...> end\n {:__aliases__, [alias: false], [:Hello, :World]}\n\n We go into more details about aliases in the `__aliases__\/1` special form\n documentation.\n\n ## Unquoting\n\n We can also use unquote to generate a remote call in a quoted expression:\n\n iex> x = :downcase\n iex> quote do\n ...> String.unquote(x)(\"FOO\")\n ...> end\n {{:., [], [{:__aliases__, [alias: false], [:String]}, :downcase]}, [], [\"FOO\"]}\n\n Similar to `Kernel.\"FUNCTION_NAME\"`, `unquote(x)` will always generate a remote call,\n independent of the value of `x`. To generate an alias via the quoted expression,\n one needs to rely on `Module.concat\/2`:\n\n iex> x = Sample\n iex> quote do\n ...> Module.concat(String, unquote(x))\n ...> end\n {{:., [], [{:__aliases__, [alias: false], [:Module]}, :concat]}, [],\n [{:__aliases__, [alias: false], [:String]}, Sample]}\n\n \"\"\"\n defmacro unquote(:.)(left, right), do: error!([left, right])\n\n @doc \"\"\"\n `alias\/2` is used to setup aliases, often useful with modules names.\n\n ## Examples\n\n `alias\/2` can be used to setup an alias for any module:\n\n defmodule Math do\n alias MyKeyword, as: Keyword\n end\n\n In the example above, we have set up `MyKeyword` to be aliased\n as `Keyword`. So now, any reference to `Keyword` will be\n automatically replaced by `MyKeyword`.\n\n In case one wants to access the original `Keyword`, it can be done\n by accessing `Elixir`:\n\n Keyword.values #=> uses MyKeyword.values\n Elixir.Keyword.values #=> uses Keyword.values\n\n Notice that calling `alias` without the `:as` option automatically\n sets an alias based on the last part of the module. For example:\n\n alias Foo.Bar.Baz\n\n Is the same as:\n\n alias Foo.Bar.Baz, as: Baz\n\n We can also alias multiple modules in one line:\n\n alias Foo.{Bar, Baz, Biz}\n\n Is the same as:\n\n alias Foo.Bar\n alias Foo.Baz\n alias Foo.Biz\n\n ## Lexical scope\n\n `import\/2`, `require\/2` and `alias\/2` are called directives and all\n have lexical scope. This means you can set up aliases inside\n specific functions and it won't affect the overall scope.\n\n ## Warnings\n\n If you alias a module and you don't use the alias, Elixir is\n going to issue a warning implying the alias is not being used.\n\n In case the alias is generated automatically by a macro,\n Elixir won't emit any warnings though, since the alias\n was not explicitly defined.\n\n Both warning behaviours could be changed by explicitly\n setting the `:warn` option to `true` or `false`.\n \"\"\"\n defmacro alias(module, opts), do: error!([module, opts])\n\n @doc \"\"\"\n Requires a module in order to use its macros.\n\n ## Examples\n\n Public functions in modules are globally available, but in order to use\n macros, you need to opt-in by requiring the module they are defined in.\n\n Let's suppose you created your own `if\/2` implementation in the module\n `MyMacros`. If you want to invoke it, you need to first explicitly\n require the `MyMacros`:\n\n defmodule Math do\n require MyMacros\n MyMacros.if do_something, it_works\n end\n\n An attempt to call a macro that was not loaded will raise an error.\n\n ## Alias shortcut\n\n `require\/2` also accepts `:as` as an option so it automatically sets\n up an alias. Please check `alias\/2` for more information.\n\n \"\"\"\n defmacro require(module, opts), do: error!([module, opts])\n\n @doc \"\"\"\n Imports functions and macros from other modules.\n\n `import\/2` allows one to easily access functions or macros from\n others modules without using the qualified name.\n\n ## Examples\n\n If you are using several functions from a given module, you can\n import those functions and reference them as local functions,\n for example:\n\n iex> import List\n iex> flatten([1, [2], 3])\n [1, 2, 3]\n\n ## Selector\n\n By default, Elixir imports functions and macros from the given\n module, except the ones starting with underscore (which are\n usually callbacks):\n\n import List\n\n A developer can filter to import only macros or functions via\n the only option:\n\n import List, only: :functions\n import List, only: :macros\n\n Alternatively, Elixir allows a developer to pass pairs of\n name\/arities to `:only` or `:except` as a fine grained control\n on what to import (or not):\n\n import List, only: [flatten: 1]\n import String, except: [split: 2]\n\n Notice that calling `except` is always exclusive on a previously\n declared `import\/2`. If there is no previous import, then it applies\n to all functions and macros in the module. For example:\n\n import List, only: [flatten: 1, keyfind: 4]\n import List, except: [flatten: 1]\n\n After the two import calls above, only `List.keyfind\/4` will be\n imported.\n\n ## Underscore functions\n\n By default functions starting with `_` are not imported. If you really want\n to import a function starting with `_` you must explicitly include it in the\n `:only` selector.\n\n import File.Stream, only: [__build__: 3]\n\n ## Lexical scope\n\n It is important to notice that `import\/2` is lexical. This means you\n can import specific macros inside specific functions:\n\n defmodule Math do\n def some_function do\n # 1) Disable \"if\/2\" from Kernel\n import Kernel, except: [if: 2]\n\n # 2) Require the new \"if\/2\" macro from MyMacros\n import MyMacros\n\n # 3) Use the new macro\n if do_something, it_works\n end\n end\n\n In the example above, we imported macros from `MyMacros`,\n replacing the original `if\/2` implementation by our own\n within that specific function. All other functions in that\n module will still be able to use the original one.\n\n ## Warnings\n\n If you import a module and you don't use any of the imported\n functions or macros from this module, Elixir is going to issue\n a warning implying the import is not being used.\n\n In case the import is generated automatically by a macro,\n Elixir won't emit any warnings though, since the import\n was not explicitly defined.\n\n Both warning behaviours could be changed by explicitly\n setting the `:warn` option to `true` or `false`.\n\n ## Ambiguous function\/macro names\n\n If two modules `A` and `B` are imported and they both contain\n a `foo` function with an arity of `1`, an error is only emitted\n if an ambiguous call to `foo\/1` is actually made; that is, the\n errors are emitted lazily, not eagerly.\n \"\"\"\n defmacro import(module, opts), do: error!([module, opts])\n\n @doc \"\"\"\n Returns the current environment information as a `Macro.Env` struct.\n\n In the environment you can access the current filename,\n line numbers, set up aliases, the current function and others.\n \"\"\"\n defmacro __ENV__, do: error!([])\n\n @doc \"\"\"\n Returns the current module name as an atom or `nil` otherwise.\n\n Although the module can be accessed in the `__ENV__\/0`, this macro\n is a convenient shortcut.\n \"\"\"\n defmacro __MODULE__, do: error!([])\n\n @doc \"\"\"\n Returns the absolute path of the directory of the current file as a binary.\n\n Although the directory can be accessed as `Path.dirname(__ENV__.file)`,\n this macro is a convenient shortcut.\n \"\"\"\n defmacro __DIR__, do: error!([])\n\n @doc \"\"\"\n Returns the current calling environment as a `Macro.Env` struct.\n\n In the environment you can access the filename, line numbers,\n set up aliases, the function and others.\n \"\"\"\n defmacro __CALLER__, do: error!([])\n\n @doc \"\"\"\n Returns the stacktrace for the currently handled exception.\n\n It is available only in the `catch` and `rescue` clauses of `try\/1`\n expressions.\n\n To retrieve the stacktrace of the current process, use\n `Process.info(self(), :current_stacktrace)` instead.\n \"\"\"\n defmacro __STACKTRACE__, do: error!([])\n\n @doc \"\"\"\n Accesses an already bound variable in match clauses. Also known as the pin operator.\n\n ## Examples\n\n Elixir allows variables to be rebound via static single assignment:\n\n iex> x = 1\n iex> x = x + 1\n iex> x\n 2\n\n However, in some situations, it is useful to match against an existing\n value, instead of rebinding. This can be done with the `^` special form,\n colloquially known as the pin operator:\n\n iex> x = 1\n iex> ^x = List.first([1])\n iex> ^x = List.first([2])\n ** (MatchError) no match of right hand side value: 2\n\n Note that `^x` always refers to the value of `x` prior to the match. The\n following example will match:\n\n iex> x = 0\n iex> {x, ^x} = {1, 0}\n iex> x\n 1\n\n \"\"\"\n defmacro ^var, do: error!([var])\n\n @doc \"\"\"\n Matches the value on the right against the pattern on the left.\n \"\"\"\n defmacro left = right, do: error!([left, right])\n\n @doc \"\"\"\n Used by types and bitstrings to specify types.\n\n This operator is used in two distinct occasions in Elixir.\n It is used in typespecs to specify the type of a variable,\n function or of a type itself:\n\n @type number :: integer | float\n @spec add(number, number) :: number\n\n It may also be used in bit strings to specify the type\n of a given bit segment:\n\n <> = bits\n\n Read the documentation on the `Typespec` page and\n `<<>>\/1` for more information on typespecs and\n bitstrings respectively.\n \"\"\"\n defmacro left :: right, do: error!([left, right])\n\n @doc ~S\"\"\"\n Gets the representation of any expression.\n\n ## Examples\n\n iex> quote do\n ...> sum(1, 2, 3)\n ...> end\n {:sum, [], [1, 2, 3]}\n\n ## Elixir's AST (Abstract Syntax Tree)\n\n Any Elixir code can be represented using Elixir data structures.\n The building block of Elixir macros is a tuple with three elements,\n for example:\n\n {:sum, [], [1, 2, 3]}\n\n The tuple above represents a function call to `sum` passing 1, 2 and\n 3 as arguments. The tuple elements are:\n\n * The first element of the tuple is always an atom or\n another tuple in the same representation.\n\n * The second element of the tuple represents metadata.\n\n * The third element of the tuple are the arguments for the\n function call. The third argument may be an atom, which is\n usually a variable (or a local call).\n\n Besides the tuple described above, Elixir has a few literals that\n are also part of its AST. Those literals return themselves when\n quoted. They are:\n\n :sum #=> Atoms\n 1 #=> Integers\n 2.0 #=> Floats\n [1, 2] #=> Lists\n \"strings\" #=> Strings\n {key, value} #=> Tuples with two elements\n\n Any other value, such as a map or a four-element tuple, must be escaped\n (`Macro.escape\/1`) before being introduced into an AST.\n\n ## Options\n\n * `:unquote` - when `false`, disables unquoting. This means any `unquote`\n call will be kept as is in the AST, instead of replaced by the `unquote`\n arguments. For example:\n\n iex> quote do\n ...> unquote(\"hello\")\n ...> end\n \"hello\"\n\n iex> quote unquote: false do\n ...> unquote(\"hello\")\n ...> end\n {:unquote, [], [\"hello\"]}\n\n * `:location` - when set to `:keep`, keeps the current line and file from\n quote. Read the Stacktrace information section below for more\n information.\n\n * `:line` - sets the quoted expressions to have the given line.\n\n * `:generated` - marks the given chunk as generated so it does not emit warnings.\n Currently it only works on special forms (for example, you can annotate a `case`\n but not an `if`).\n\n * `:context` - sets the resolution context.\n\n * `:bind_quoted` - passes a binding to the macro. Whenever a binding is\n given, `unquote\/1` is automatically disabled.\n\n ## Quote and macros\n\n `quote\/2` is commonly used with macros for code generation. As an exercise,\n let's define a macro that multiplies a number by itself (squared). In practice,\n there is no reason to define such as a macro (and it would actually be\n seen as a bad practice), but it is simple enough that it allows us to focus\n on the important aspects of quotes and macros:\n\n defmodule Math do\n defmacro squared(x) do\n quote do\n unquote(x) * unquote(x)\n end\n end\n end\n\n We can invoke it as:\n\n import Math\n IO.puts \"Got #{squared(5)}\"\n\n At first, there is nothing in this example that actually reveals it is a\n macro. But what is happening is that, at compilation time, `squared(5)`\n becomes `5 * 5`. The argument `5` is duplicated in the produced code, we\n can see this behaviour in practice though because our macro actually has\n a bug:\n\n import Math\n my_number = fn ->\n IO.puts \"Returning 5\"\n 5\n end\n IO.puts \"Got #{squared(my_number.())}\"\n\n The example above will print:\n\n Returning 5\n Returning 5\n Got 25\n\n Notice how \"Returning 5\" was printed twice, instead of just once. This is\n because a macro receives an expression and not a value (which is what we\n would expect in a regular function). This means that:\n\n squared(my_number.())\n\n Actually expands to:\n\n my_number.() * my_number.()\n\n Which invokes the function twice, explaining why we get the printed value\n twice! In the majority of the cases, this is actually unexpected behaviour,\n and that's why one of the first things you need to keep in mind when it\n comes to macros is to **not unquote the same value more than once**.\n\n Let's fix our macro:\n\n defmodule Math do\n defmacro squared(x) do\n quote do\n x = unquote(x)\n x * x\n end\n end\n end\n\n Now invoking `squared(my_number.())` as before will print the value just\n once.\n\n In fact, this pattern is so common that most of the times you will want\n to use the `bind_quoted` option with `quote\/2`:\n\n defmodule Math do\n defmacro squared(x) do\n quote bind_quoted: [x: x] do\n x * x\n end\n end\n end\n\n `:bind_quoted` will translate to the same code as the example above.\n `:bind_quoted` can be used in many cases and is seen as good practice,\n not only because it helps prevent us from running into common mistakes, but also\n because it allows us to leverage other tools exposed by macros, such as\n unquote fragments discussed in some sections below.\n\n Before we finish this brief introduction, you will notice that, even though\n we defined a variable `x` inside our quote:\n\n quote do\n x = unquote(x)\n x * x\n end\n\n When we call:\n\n import Math\n squared(5)\n x #=> ** (CompileError) undefined variable x or undefined function x\/0\n\n We can see that `x` did not leak to the user context. This happens\n because Elixir macros are hygienic, a topic we will discuss at length\n in the next sections as well.\n\n ## Hygiene in variables\n\n Consider the following example:\n\n defmodule Hygiene do\n defmacro no_interference do\n quote do\n a = 1\n end\n end\n end\n\n require Hygiene\n\n a = 10\n Hygiene.no_interference\n a #=> 10\n\n In the example above, `a` returns 10 even if the macro\n is apparently setting it to 1 because variables defined\n in the macro do not affect the context the macro is executed in.\n If you want to set or get a variable in the caller's context, you\n can do it with the help of the `var!` macro:\n\n defmodule NoHygiene do\n defmacro interference do\n quote do\n var!(a) = 1\n end\n end\n end\n\n require NoHygiene\n\n a = 10\n NoHygiene.interference\n a #=> 1\n\n You cannot even access variables defined in the same module unless\n you explicitly give it a context:\n\n defmodule Hygiene do\n defmacro write do\n quote do\n a = 1\n end\n end\n\n defmacro read do\n quote do\n a\n end\n end\n end\n\n Hygiene.write\n Hygiene.read\n #=> ** (RuntimeError) undefined variable a or undefined function a\/0\n\n For such, you can explicitly pass the current module scope as\n argument:\n\n defmodule ContextHygiene do\n defmacro write do\n quote do\n var!(a, ContextHygiene) = 1\n end\n end\n\n defmacro read do\n quote do\n var!(a, ContextHygiene)\n end\n end\n end\n\n ContextHygiene.write\n ContextHygiene.read\n #=> 1\n\n ## Hygiene in aliases\n\n Aliases inside quote are hygienic by default.\n Consider the following example:\n\n defmodule Hygiene do\n alias Map, as: M\n\n defmacro no_interference do\n quote do\n M.new\n end\n end\n end\n\n require Hygiene\n Hygiene.no_interference #=> %{}\n\n Notice that, even though the alias `M` is not available\n in the context the macro is expanded, the code above works\n because `M` still expands to `Map`.\n\n Similarly, even if we defined an alias with the same name\n before invoking a macro, it won't affect the macro's result:\n\n defmodule Hygiene do\n alias Map, as: M\n\n defmacro no_interference do\n quote do\n M.new\n end\n end\n end\n\n require Hygiene\n alias SomethingElse, as: M\n Hygiene.no_interference #=> %{}\n\n In some cases, you want to access an alias or a module defined\n in the caller. For such, you can use the `alias!` macro:\n\n defmodule Hygiene do\n # This will expand to Elixir.Nested.hello\n defmacro no_interference do\n quote do\n Nested.hello\n end\n end\n\n # This will expand to Nested.hello for\n # whatever is Nested in the caller\n defmacro interference do\n quote do\n alias!(Nested).hello\n end\n end\n end\n\n defmodule Parent do\n defmodule Nested do\n def hello, do: \"world\"\n end\n\n require Hygiene\n Hygiene.no_interference\n #=> ** (UndefinedFunctionError) ...\n\n Hygiene.interference\n #=> \"world\"\n end\n\n ## Hygiene in imports\n\n Similar to aliases, imports in Elixir are hygienic. Consider the\n following code:\n\n defmodule Hygiene do\n defmacrop get_length do\n quote do\n length([1, 2, 3])\n end\n end\n\n def return_length do\n import Kernel, except: [length: 1]\n get_length\n end\n end\n\n Hygiene.return_length #=> 3\n\n Notice how `Hygiene.return_length\/0` returns `3` even though the `Kernel.length\/1`\n function is not imported. In fact, even if `return_length\/0`\n imported a function with the same name and arity from another\n module, it wouldn't affect the function result:\n\n def return_length do\n import String, only: [length: 1]\n get_length\n end\n\n Calling this new `return_length\/0` will still return `3` as result.\n\n Elixir is smart enough to delay the resolution to the latest\n possible moment. So, if you call `length([1, 2, 3])` inside quote,\n but no `length\/1` function is available, it is then expanded in\n the caller:\n\n defmodule Lazy do\n defmacrop get_length do\n import Kernel, except: [length: 1]\n\n quote do\n length(\"hello\")\n end\n end\n\n def return_length do\n import Kernel, except: [length: 1]\n import String, only: [length: 1]\n get_length\n end\n end\n\n Lazy.return_length #=> 5\n\n ## Stacktrace information\n\n When defining functions via macros, developers have the option of\n choosing if runtime errors will be reported from the caller or from\n inside the quote. Let's see an example:\n\n # adder.ex\n defmodule Adder do\n @doc \"Defines a function that adds two numbers\"\n defmacro defadd do\n quote location: :keep do\n def add(a, b), do: a + b\n end\n end\n end\n\n # sample.ex\n defmodule Sample do\n import Adder\n defadd\n end\n\n require Sample\n Sample.add(:one, :two)\n #=> ** (ArithmeticError) bad argument in arithmetic expression\n #=> adder.ex:5: Sample.add\/2\n\n When using `location: :keep` and invalid arguments are given to\n `Sample.add\/2`, the stacktrace information will point to the file\n and line inside the quote. Without `location: :keep`, the error is\n reported to where `defadd` was invoked. `location: :keep` affects\n only definitions inside the quote.\n\n ## Binding and unquote fragments\n\n Elixir quote\/unquote mechanisms provides a functionality called\n unquote fragments. Unquote fragments provide an easy way to generate\n functions on the fly. Consider this example:\n\n kv = [foo: 1, bar: 2]\n Enum.each kv, fn {k, v} ->\n def unquote(k)(), do: unquote(v)\n end\n\n In the example above, we have generated the functions `foo\/0` and\n `bar\/0` dynamically. Now, imagine that, we want to convert this\n functionality into a macro:\n\n defmacro defkv(kv) do\n Enum.map kv, fn {k, v} ->\n quote do\n def unquote(k)(), do: unquote(v)\n end\n end\n end\n\n We can invoke this macro as:\n\n defkv [foo: 1, bar: 2]\n\n However, we can't invoke it as follows:\n\n kv = [foo: 1, bar: 2]\n defkv kv\n\n This is because the macro is expecting its arguments to be a\n keyword list at **compilation** time. Since in the example above\n we are passing the representation of the variable `kv`, our\n code fails.\n\n This is actually a common pitfall when developing macros. We are\n assuming a particular shape in the macro. We can work around it\n by unquoting the variable inside the quoted expression:\n\n defmacro defkv(kv) do\n quote do\n Enum.each unquote(kv), fn {k, v} ->\n def unquote(k)(), do: unquote(v)\n end\n end\n end\n\n If you try to run our new macro, you will notice it won't\n even compile, complaining that the variables `k` and `v`\n do not exist. This is because of the ambiguity: `unquote(k)`\n can either be an unquote fragment, as previously, or a regular\n unquote as in `unquote(kv)`.\n\n One solution to this problem is to disable unquoting in the\n macro, however, doing that would make it impossible to inject the\n `kv` representation into the tree. That's when the `:bind_quoted`\n option comes to the rescue (again!). By using `:bind_quoted`, we\n can automatically disable unquoting while still injecting the\n desired variables into the tree:\n\n defmacro defkv(kv) do\n quote bind_quoted: [kv: kv] do\n Enum.each kv, fn {k, v} ->\n def unquote(k)(), do: unquote(v)\n end\n end\n end\n\n In fact, the `:bind_quoted` option is recommended every time\n one desires to inject a value into the quote.\n \"\"\"\n defmacro quote(opts, block), do: error!([opts, block])\n\n @doc \"\"\"\n Unquotes the given expression inside a quoted expression.\n\n This function expects a valid Elixir AST, also known as\n quoted expression, as argument. If you would like to `unquote`\n any value, such as a map or a four-element tuple, you should\n call `Macro.escape\/1` before unquoting.\n\n ## Examples\n\n Imagine the situation you have a quoted expression and\n you want to inject it inside some quote. The first attempt\n would be:\n\n value =\n quote do\n 13\n end\n\n quote do\n sum(1, value, 3)\n end\n\n Which would then return:\n\n {:sum, [], [1, {:value, [], Elixir}, 3]}\n\n Which is not the expected result. For this, we use `unquote`:\n\n iex> value =\n ...> quote do\n ...> 13\n ...> end\n iex> quote do\n ...> sum(1, unquote(value), 3)\n ...> end\n {:sum, [], [1, 13, 3]}\n\n If you want to unquote a value that is not a quoted expression,\n such as a map, you need to call `Macro.escape\/1` before:\n\n iex> value = %{foo: :bar}\n iex> quote do\n ...> process_map(unquote(Macro.escape(value)))\n ...> end\n {:process_map, [], [{:%{}, [], [foo: :bar]}]}\n\n If you forget to escape it, Elixir will raise an error\n when compiling the code.\n \"\"\"\n defmacro unquote(:unquote)(expr), do: error!([expr])\n\n @doc \"\"\"\n Unquotes the given list expanding its arguments.\n\n Similar to `unquote\/1`.\n\n ## Examples\n\n iex> values = [2, 3, 4]\n iex> quote do\n ...> sum(1, unquote_splicing(values), 5)\n ...> end\n {:sum, [], [1, 2, 3, 4, 5]}\n\n \"\"\"\n defmacro unquote(:unquote_splicing)(expr), do: error!([expr])\n\n @doc ~S\"\"\"\n Comprehensions allow you to quickly build a data structure from\n an enumerable or a bitstring.\n\n Let's start with an example:\n\n iex> for n <- [1, 2, 3, 4], do: n * 2\n [2, 4, 6, 8]\n\n A comprehension accepts many generators and filters. Enumerable\n generators are defined using `<-`:\n\n # A list generator:\n iex> for n <- [1, 2, 3, 4], do: n * 2\n [2, 4, 6, 8]\n\n # A comprehension with two generators\n iex> for x <- [1, 2], y <- [2, 3], do: x * y\n [2, 3, 4, 6]\n\n Filters can also be given:\n\n # A comprehension with a generator and a filter\n iex> for n <- [1, 2, 3, 4, 5, 6], rem(n, 2) == 0, do: n\n [2, 4, 6]\n\n Generators can also be used to filter as it removes any value\n that doesn't match the pattern on the left side of `<-`:\n\n iex> users = [user: \"john\", admin: \"meg\", guest: \"barbara\"]\n iex> for {type, name} when type != :guest <- users do\n ...> String.upcase(name)\n ...> end\n [\"JOHN\", \"MEG\"]\n\n Bitstring generators are also supported and are very useful when you\n need to organize bitstring streams:\n\n iex> pixels = <<213, 45, 132, 64, 76, 32, 76, 0, 0, 234, 32, 15>>\n iex> for <>, do: {r, g, b}\n [{213, 45, 132}, {64, 76, 32}, {76, 0, 0}, {234, 32, 15}]\n\n Variable assignments inside the comprehension, be it in generators,\n filters or inside the block, are not reflected outside of the\n comprehension.\n\n ## The `:into` and `:uniq` options\n\n In the examples above, the result returned by the comprehension was\n always a list. The returned result can be configured by passing an\n `:into` option, that accepts any structure as long as it implements\n the `Collectable` protocol.\n\n For example, we can use bitstring generators with the `:into` option\n to easily remove all spaces in a string:\n\n iex> for <>, c != ?\\s, into: \"\", do: <>\n \"helloworld\"\n\n The `IO` module provides streams, that are both `Enumerable` and\n `Collectable`, here is an upcase echo server using comprehensions:\n\n for line <- IO.stream(:stdio, :line), into: IO.stream(:stdio, :line) do\n String.upcase(line)\n end\n\n Similarly, `uniq: true` can also be given to comprehensions to guarantee\n the results are only added to the collection if they were not returned\n before. For example:\n\n iex> for x <- [1, 1, 2, 3], uniq: true, do: x * 2\n [2, 4, 6]\n\n iex> for <>, uniq: true, into: \"\", do: <>\n \"ABC\"\n\n ## The `:reduce` option\n\n While the `:into` option allows us to customize the comprehension behaviour\n to a given data type, such as putting all of the values inside a map or inside\n a binary, it is not always enough.\n\n For example, imagine that you have a binary with letters where you want to\n count how many times each lowercase letter happens, ignoring all uppercase\n ones. For instance, for the string `\"AbCabCABc\"`, we want to return the map\n `%{\"a\" => 1, \"b\" => 2, \"c\" => 1}`.\n\n If we were to use `:into`, we would need a data type that computes the\n frequency of each element it holds. While there is no such data type in\n Elixir, you could implement one yourself.\n\n A simpler option would be to use comprehensions for the mapping and\n filtering of letters, and then we invoke `Enum.reduce\/3` to build a map,\n for example:\n\n iex> letters = for <>, x in ?a..?z, do: <>\n iex> Enum.reduce(letters, %{}, fn x, acc -> Map.update(acc, x, 1, & &1 + 1) end)\n %{\"a\" => 1, \"b\" => 2, \"c\" => 1}\n\n While the above is straight-forward, it has the downside of traversing the\n data at least twice. If you are expecting long strings as inputs, this can\n be quite expensive.\n\n Luckily, comprehensions also support the `:reduce` option, which would allow\n us to fuse both steps above into a single step:\n\n iex> for <>, x in ?a..?z, reduce: %{} do\n ...> acc -> Map.update(acc, <>, 1, & &1 + 1)\n ...> end\n %{\"a\" => 1, \"b\" => 2, \"c\" => 1}\n\n When the `:reduce` key is given, its value is used as the initial accumulator\n and the `do` block must be changed to use `->` clauses, where the left side\n of `->` receives the accumulated value of the previous iteration and the\n expression on the right side must return the new accumulator value. Once there are no more\n elements, the final accumulated value is returned. If there are no elements\n at all, then the initial accumulator value is returned.\n \"\"\"\n defmacro for(args), do: error!([args])\n\n @doc \"\"\"\n Used to combine matching clauses.\n\n Let's start with an example:\n\n iex> opts = %{width: 10, height: 15}\n iex> with {:ok, width} <- Map.fetch(opts, :width),\n ...> {:ok, height} <- Map.fetch(opts, :height) do\n ...> {:ok, width * height}\n ...> end\n {:ok, 150}\n\n If all clauses match, the `do` block is executed, returning its result.\n Otherwise the chain is aborted and the non-matched value is returned:\n\n iex> opts = %{width: 10}\n iex> with {:ok, width} <- Map.fetch(opts, :width),\n ...> {:ok, height} <- Map.fetch(opts, :height) do\n ...> {:ok, width * height}\n ...> end\n :error\n\n Guards can be used in patterns as well:\n\n iex> users = %{\"melany\" => \"guest\", \"bob\" => :admin}\n iex> with {:ok, role} when not is_binary(role) <- Map.fetch(users, \"bob\") do\n ...> {:ok, to_string(role)}\n ...> end\n {:ok, \"admin\"}\n\n As in `for\/1`, variables bound inside `with\/1` won't leak.\n Expressions without `<-` may also be used in clauses. For instance,\n you can perform regular matches with the `=` operator:\n\n iex> width = nil\n iex> opts = %{width: 10, height: 15}\n iex> with {:ok, width} <- Map.fetch(opts, :width),\n ...> double_width = width * 2,\n ...> {:ok, height} <- Map.fetch(opts, :height) do\n ...> {:ok, double_width * height}\n ...> end\n {:ok, 300}\n iex> width\n nil\n\n The behaviour of any expression in a clause is the same as outside.\n For example, `=` will raise a `MatchError` instead of returning the\n non-matched value:\n\n with :foo = :bar, do: :ok\n #=> ** (MatchError) no match of right hand side value: :bar\n\n As with any other function or macro call in Elixir, explicit parens can\n also be used around the arguments before the `do`\/`end` block:\n\n iex> opts = %{width: 10, height: 15}\n iex> with(\n ...> {:ok, width} <- Map.fetch(opts, :width),\n ...> {:ok, height} <- Map.fetch(opts, :height)\n ...> ) do\n ...> {:ok, width * height}\n ...> end\n {:ok, 150}\n\n The choice between parens and no parens is a matter of preference.\n\n An `else` option can be given to modify what is being returned from\n `with` in the case of a failed match:\n\n iex> opts = %{width: 10}\n iex> with {:ok, width} <- Map.fetch(opts, :width),\n ...> {:ok, height} <- Map.fetch(opts, :height) do\n ...> {:ok, width * height}\n ...> else\n ...> :error ->\n ...> {:error, :wrong_data}\n ...> end\n {:error, :wrong_data}\n\n If an `else` block is used and there are no matching clauses, a `WithClauseError`\n exception is raised.\n \"\"\"\n defmacro with(args), do: error!([args])\n\n @doc \"\"\"\n Defines an anonymous function.\n\n ## Examples\n\n iex> add = fn a, b -> a + b end\n iex> add.(1, 2)\n 3\n\n Anonymous functions can also have multiple clauses. All clauses\n should expect the same number of arguments:\n\n iex> negate = fn\n ...> true -> false\n ...> false -> true\n ...> end\n iex> negate.(false)\n true\n\n \"\"\"\n defmacro unquote(:fn)(clauses), do: error!([clauses])\n\n @doc \"\"\"\n Internal special form for block expressions.\n\n This is the special form used whenever we have a block\n of expressions in Elixir. This special form is private\n and should not be invoked directly:\n\n iex> quote do\n ...> 1\n ...> 2\n ...> 3\n ...> end\n {:__block__, [], [1, 2, 3]}\n\n \"\"\"\n defmacro unquote(:__block__)(args), do: error!([args])\n\n @doc \"\"\"\n Captures or creates an anonymous function.\n\n ## Capture\n\n The capture operator is most commonly used to capture a\n function with given name and arity from a module:\n\n iex> fun = &Kernel.is_atom\/1\n iex> fun.(:atom)\n true\n iex> fun.(\"string\")\n false\n\n In the example above, we captured `Kernel.is_atom\/1` as an\n anonymous function and then invoked it.\n\n The capture operator can also be used to capture local functions,\n including private ones, and imported functions by omitting the\n module name:\n\n &local_function\/1\n\n ## Anonymous functions\n\n The capture operator can also be used to partially apply\n functions, where `&1`, `&2` and so on can be used as value\n placeholders. For example:\n\n iex> double = &(&1 * 2)\n iex> double.(2)\n 4\n\n In other words, `&(&1 * 2)` is equivalent to `fn x -> x * 2 end`.\n\n We can partially apply a remote function with placeholder:\n\n iex> take_five = &Enum.take(&1, 5)\n iex> take_five.(1..10)\n [1, 2, 3, 4, 5]\n\n Another example while using an imported or local function:\n\n iex> first_elem = &elem(&1, 0)\n iex> first_elem.({0, 1})\n 0\n\n The `&` operator can be used with more complex expressions:\n\n iex> fun = &(&1 + &2 + &3)\n iex> fun.(1, 2, 3)\n 6\n\n As well as with lists and tuples:\n\n iex> fun = &{&1, &2}\n iex> fun.(1, 2)\n {1, 2}\n\n iex> fun = &[&1 | &2]\n iex> fun.(1, [2, 3])\n [1, 2, 3]\n\n The only restrictions when creating anonymous functions is that at\n least one placeholder must be present, i.e. it must contain at least\n `&1`, and that block expressions are not supported:\n\n # No placeholder, fails to compile.\n &(:foo)\n\n # Block expression, fails to compile.\n &(&1; &2)\n\n \"\"\"\n defmacro unquote(:&)(expr), do: error!([expr])\n\n @doc \"\"\"\n Internal special form to hold aliases information.\n\n It is usually compiled to an atom:\n\n iex> quote do\n ...> Foo.Bar\n ...> end\n {:__aliases__, [alias: false], [:Foo, :Bar]}\n\n Elixir represents `Foo.Bar` as `__aliases__` so calls can be\n unambiguously identified by the operator `:.`. For example:\n\n iex> quote do\n ...> Foo.bar\n ...> end\n {{:., [], [{:__aliases__, [alias: false], [:Foo]}, :bar]}, [], []}\n\n Whenever an expression iterator sees a `:.` as the tuple key,\n it can be sure that it represents a call and the second argument\n in the list is an atom.\n\n On the other hand, aliases holds some properties:\n\n 1. The head element of aliases can be any term that must expand to\n an atom at compilation time.\n\n 2. The tail elements of aliases are guaranteed to always be atoms.\n\n 3. When the head element of aliases is the atom `:Elixir`, no expansion happens.\n\n \"\"\"\n defmacro unquote(:__aliases__)(args), do: error!([args])\n\n @doc \"\"\"\n Calls the overridden function when overriding it with `Kernel.defoverridable\/1`.\n\n See `Kernel.defoverridable\/1` for more information and documentation.\n \"\"\"\n defmacro super(args), do: error!([args])\n\n @doc ~S\"\"\"\n Matches the given expression against the given clauses.\n\n ## Examples\n\n case thing do\n {:selector, i, value} when is_integer(i) ->\n value\n value ->\n value\n end\n\n In the example above, we match `thing` against each clause \"head\"\n and execute the clause \"body\" corresponding to the first clause\n that matches.\n\n If no clause matches, an error is raised.\n For this reason, it may be necessary to add a final catch-all clause (like `_`)\n which will always match.\n\n x = 10\n\n case x do\n 0 ->\n \"This clause won't match\"\n _ ->\n \"This clause would match any value (x = #{x})\"\n end\n #=> \"This clause would match any value (x = 10)\"\n\n ## Variables handling\n\n Notice that variables bound in a clause \"head\" do not leak to the\n outer context:\n\n case data do\n {:ok, value} -> value\n :error -> nil\n end\n\n value #=> unbound variable value\n\n However, variables explicitly bound in the clause \"body\" are\n accessible from the outer context:\n\n value = 7\n\n case lucky? do\n false -> value = 13\n true -> true\n end\n\n value #=> 7 or 13\n\n In the example above, value is going to be `7` or `13` depending on\n the value of `lucky?`. In case `value` has no previous value before\n case, clauses that do not explicitly bind a value have the variable\n bound to `nil`.\n\n If you want to pattern match against an existing variable,\n you need to use the `^\/1` operator:\n\n x = 1\n\n case 10 do\n ^x -> \"Won't match\"\n _ -> \"Will match\"\n end\n #=> \"Will match\"\n\n \"\"\"\n defmacro case(condition, clauses), do: error!([condition, clauses])\n\n @doc \"\"\"\n Evaluates the expression corresponding to the first clause that\n evaluates to a truthy value.\n\n cond do\n hd([1, 2, 3]) ->\n \"1 is considered as true\"\n end\n #=> \"1 is considered as true\"\n\n Raises an error if all conditions evaluate to `nil` or `false`.\n For this reason, it may be necessary to add a final always-truthy condition\n (anything non-`false` and non-`nil`), which will always match.\n\n ## Examples\n\n cond do\n 1 + 1 == 1 ->\n \"This will never match\"\n 2 * 2 != 4 ->\n \"Nor this\"\n true ->\n \"This will\"\n end\n #=> \"This will\"\n\n \"\"\"\n defmacro cond(clauses), do: error!([clauses])\n\n @doc ~S\"\"\"\n Evaluates the given expressions and handles any error, exit,\n or throw that may have happened.\n\n ## Examples\n\n try do\n do_something_that_may_fail(some_arg)\n rescue\n ArgumentError ->\n IO.puts \"Invalid argument given\"\n catch\n value ->\n IO.puts \"Caught #{inspect(value)}\"\n else\n value ->\n IO.puts \"Success! The result was #{inspect(value)}\"\n after\n IO.puts \"This is printed regardless if it failed or succeed\"\n end\n\n The `rescue` clause is used to handle exceptions while the `catch`\n clause can be used to catch thrown values and exits.\n The `else` clause can be used to control flow based on the result of\n the expression. `catch`, `rescue`, and `else` clauses work based on\n pattern matching (similar to the `case` special form).\n\n Calls inside `try\/1` are not tail recursive since the VM needs to keep\n the stacktrace in case an exception happens. To retrieve the stacktrace,\n access `__STACKTRACE__\/0` inside the `rescue` or `catch` clause.\n\n ## `rescue` clauses\n\n Besides relying on pattern matching, `rescue` clauses provide some\n conveniences around exceptions that allow one to rescue an\n exception by its name. All the following formats are valid patterns\n in `rescue` clauses:\n\n # Rescue a single exception without binding the exception\n # to a variable\n try do\n UndefinedModule.undefined_function\n rescue\n UndefinedFunctionError -> nil\n end\n\n # Rescue any of the given exception without binding\n try do\n UndefinedModule.undefined_function\n rescue\n [UndefinedFunctionError, ArgumentError] -> nil\n end\n\n # Rescue and bind the exception to the variable \"x\"\n try do\n UndefinedModule.undefined_function\n rescue\n x in [UndefinedFunctionError] -> nil\n end\n\n # Rescue all kinds of exceptions and bind the rescued exception\n # to the variable \"x\"\n try do\n UndefinedModule.undefined_function\n rescue\n x -> nil\n end\n\n ### Erlang errors\n\n Erlang errors are transformed into Elixir ones when rescuing:\n\n try do\n :erlang.error(:badarg)\n rescue\n ArgumentError -> :ok\n end\n #=> :ok\n\n The most common Erlang errors will be transformed into their\n Elixir counterpart. Those which are not will be transformed\n into the more generic `ErlangError`:\n\n try do\n :erlang.error(:unknown)\n rescue\n ErlangError -> :ok\n end\n #=> :ok\n\n In fact, `ErlangError` can be used to rescue any error that is\n not a proper Elixir error. For example, it can be used to rescue\n the earlier `:badarg` error too, prior to transformation:\n\n try do\n :erlang.error(:badarg)\n rescue\n ErlangError -> :ok\n end\n #=> :ok\n\n ## `catch` clauses\n\n The `catch` clause can be used to catch thrown values, exits, and errors.\n\n ### Catching thrown values\n\n `catch` can be used to catch values thrown by `Kernel.throw\/1`:\n\n try do\n throw(:some_value)\n catch\n thrown_value ->\n IO.puts \"A value was thrown: #{inspect(thrown_value)}\"\n end\n\n ### Catching values of any kind\n\n The `catch` clause also supports catching exits and errors. To do that, it\n allows matching on both the *kind* of the caught value as well as the value\n itself:\n\n try do\n exit(:shutdown)\n catch\n :exit, value\n IO.puts \"Exited with value #{inspect(value)}\"\n end\n\n try do\n exit(:shutdown)\n catch\n kind, value when kind in [:exit, :throw] ->\n IO.puts \"Caught exit or throw with value #{inspect(value)}\"\n end\n\n The `catch` clause also supports `:error` alongside `:exit` and `:throw` as\n in Erlang, although this is commonly avoided in favor of `raise`\/`rescue` control\n mechanisms. One reason for this is that when catching `:error`, the error is\n not automatically transformed into an Elixir error:\n\n try do\n :erlang.error(:badarg)\n catch\n :error, :badarg -> :ok\n end\n #=> :ok\n\n ## `after` clauses\n\n An `after` clause allows you to define cleanup logic that will be invoked both\n when the block of code passed to `try\/1` succeeds and also when an error is raised. Note\n that the process will exit as usual when receiving an exit signal that causes\n it to exit abruptly and so the `after` clause is not guaranteed to be executed.\n Luckily, most resources in Elixir (such as open files, ETS tables, ports, sockets,\n and so on) are linked to or monitor the owning process and will automatically clean\n themselves up if that process exits.\n\n File.write!(\"tmp\/story.txt\", \"Hello, World\")\n try do\n do_something_with(\"tmp\/story.txt\")\n after\n File.rm(\"tmp\/story.txt\")\n end\n\n ## `else` clauses\n\n `else` clauses allow the result of the body passed to `try\/1` to be pattern\n matched on:\n\n x = 2\n try do\n 1 \/ x\n rescue\n ArithmeticError ->\n :infinity\n else\n y when y < 1 and y > -1 ->\n :small\n _ ->\n :large\n end\n\n If an `else` clause is not present and no exceptions are raised,\n the result of the expression will be returned:\n\n x = 1\n ^x =\n try do\n 1 \/ x\n rescue\n ArithmeticError ->\n :infinity\n end\n\n However, when an `else` clause is present but the result of the expression\n does not match any of the patterns then an exception will be raised. This\n exception will not be caught by a `catch` or `rescue` in the same `try`:\n\n x = 1\n try do\n try do\n 1 \/ x\n rescue\n # The TryClauseError cannot be rescued here:\n TryClauseError ->\n :error_a\n else\n 0 ->\n :small\n end\n rescue\n # The TryClauseError is rescued here:\n TryClauseError ->\n :error_b\n end\n\n Similarly, an exception inside an `else` clause is not caught or rescued\n inside the same `try`:\n\n try do\n try do\n nil\n catch\n # The exit(1) call below can not be caught here:\n :exit, _ ->\n :exit_a\n else\n _ ->\n exit(1)\n end\n catch\n # The exit is caught here:\n :exit, _ ->\n :exit_b\n end\n\n This means the VM no longer needs to keep the stacktrace once inside\n an `else` clause and so tail recursion is possible when using a `try`\n with a tail call as the final call inside an `else` clause. The same\n is true for `rescue` and `catch` clauses.\n\n Only the result of the tried expression falls down to the `else` clause.\n If the `try` ends up in the `rescue` or `catch` clauses, their result\n will not fall down to `else`:\n\n try do\n throw(:catch_this)\n catch\n :throw, :catch_this ->\n :it_was_caught\n else\n # :it_was_caught will not fall down to this \"else\" clause.\n other ->\n {:else, other}\n end\n\n ## Variable handling\n\n Since an expression inside `try` may not have been evaluated\n due to an exception, any variable created inside `try` cannot\n be accessed externally. For instance:\n\n try do\n x = 1\n do_something_that_may_fail(same_arg)\n :ok\n catch\n _, _ -> :failed\n end\n\n x #=> unbound variable \"x\"\n\n In the example above, `x` cannot be accessed since it was defined\n inside the `try` clause. A common practice to address this issue\n is to return the variables defined inside `try`:\n\n x =\n try do\n x = 1\n do_something_that_may_fail(same_arg)\n x\n catch\n _, _ -> :failed\n end\n\n \"\"\"\n defmacro try(args), do: error!([args])\n\n @doc \"\"\"\n Checks if there is a message matching the given clauses\n in the current process mailbox.\n\n In case there is no such message, the current process hangs\n until a message arrives or waits until a given timeout value.\n\n ## Examples\n\n receive do\n {:selector, number, name} when is_integer(number) ->\n name\n name when is_atom(name) ->\n name\n _ ->\n IO.puts :stderr, \"Unexpected message received\"\n end\n\n An optional `after` clause can be given in case the message was not\n received after the given timeout period, specified in milliseconds:\n\n receive do\n {:selector, number, name} when is_integer(number) ->\n name\n name when is_atom(name) ->\n name\n _ ->\n IO.puts :stderr, \"Unexpected message received\"\n after\n 5000 ->\n IO.puts :stderr, \"No message in 5 seconds\"\n end\n\n The `after` clause can be specified even if there are no match clauses.\n The timeout value given to `after` can be any expression evaluating to\n one of the allowed values:\n\n * `:infinity` - the process should wait indefinitely for a matching\n message, this is the same as not using the after clause\n\n * `0` - if there is no matching message in the mailbox, the timeout\n will occur immediately\n\n * positive integer smaller than or equal to `4_294_967_295` (`0xFFFFFFFF`\n in hexadecimal notation) - it should be possible to represent the timeout\n value as an unsigned 32-bit integer.\n\n ## Variables handling\n\n The `receive\/1` special form handles variables exactly as the `case\/2`\n special macro. For more information, check the docs for `case\/2`.\n \"\"\"\n defmacro receive(args), do: error!([args])\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"44bcc00fcec4d75c6baf151c064a899b968f3d63","subject":"Remove tests since utf-8 names on env variables are poorly supported depending on the OS and ERTS","message":"Remove tests since utf-8 names on env variables are poorly supported depending on the OS and ERTS\n","repos":"antipax\/elixir,joshprice\/elixir,gfvcastro\/elixir,ggcampinho\/elixir,antipax\/elixir,pedrosnk\/elixir,beedub\/elixir,lexmag\/elixir,kelvinst\/elixir,ggcampinho\/elixir,lexmag\/elixir,michalmuskala\/elixir,kimshrier\/elixir,pedrosnk\/elixir,gfvcastro\/elixir,kelvinst\/elixir,elixir-lang\/elixir,kimshrier\/elixir,beedub\/elixir","old_file":"lib\/elixir\/test\/elixir\/system_test.exs","new_file":"lib\/elixir\/test\/elixir\/system_test.exs","new_contents":"Code.require_file \"..\/test_helper.exs\", __FILE__\n\nrequire :os, as: OS\n\ndefmodule SystemTest do\n use ExUnit.Case, async: true\n import PathHelpers\n\n test :build_info do\n assert not nil?(System.build_info[:version])\n assert not nil?(System.build_info[:tag])\n assert not nil?(System.build_info[:date])\n end\n\n test :argv do\n list = elixir('-e \"IO.inspect System.argv\" -- -o opt arg1 arg2 --long-opt 10')\n { args, _ } = Code.eval list, []\n assert args == [\"-o\", \"opt\", \"arg1\", \"arg2\", \"--long-opt\", \"10\"]\n end\n\n test :at_exit do\n output = elixir('-e \"System.at_exit(fn x -> IO.inspect x end)\"')\n assert output == '0\\n'\n end\n\n test :env do\n assert System.get_env(\"SYSTEM_ELIXIR_ENV_TEST_VAR\") == nil\n System.put_env('SYSTEM_ELIXIR_ENV_TEST_VAR', 'SAMPLE')\n assert System.get_env(\"SYSTEM_ELIXIR_ENV_TEST_VAR\") == \"SAMPLE\"\n end\n\n test :cmd do\n assert is_binary(System.cmd \"binary\")\n assert is_list(System.cmd 'binary')\n end\n\n test :find_executable_with_binary do\n assert System.find_executable(\"erl\")\n assert is_binary System.find_executable(\"erl\")\n assert !System.find_executable(\"does-not-really-exist-from-elixir\")\n end\n\n test :find_executable_with_list do\n assert System.find_executable('erl')\n assert is_list System.find_executable('erl')\n assert !System.find_executable('does-not-really-exist-from-elixir')\n end\nend","old_contents":"Code.require_file \"..\/test_helper.exs\", __FILE__\n\nrequire :os, as: OS\n\ndefmodule SystemTest do\n use ExUnit.Case, async: true\n import PathHelpers\n\n test :build_info do\n assert not nil?(System.build_info[:version])\n assert not nil?(System.build_info[:tag])\n assert not nil?(System.build_info[:date])\n end\n\n test :argv do\n list = elixir('-e \"IO.inspect System.argv\" -- -o opt arg1 arg2 --long-opt 10')\n { args, _ } = Code.eval list, []\n assert args == [\"-o\", \"opt\", \"arg1\", \"arg2\", \"--long-opt\", \"10\"]\n end\n\n test :at_exit do\n output = elixir('-e \"System.at_exit(fn x -> IO.inspect x end)\"')\n assert output == '0\\n'\n end\n\n test :env do\n assert System.get_env(\"SYSTEM_ELIXIR_ENV_TEST_VAR\") == nil\n System.put_env('SYSTEM_ELIXIR_ENV_TEST_VAR', 'SAMPLE')\n assert System.get_env(\"SYSTEM_ELIXIR_ENV_TEST_VAR\") == \"SAMPLE\"\n end\n\n test :env_utf8 do\n assert System.get_env(\"SYSTEM_ELIXIR_UTF_TEST_VAR\") == nil\n System.put_env(\"SYSTEM_ELIXIR_UTF_TEST_VAR\", \"ol\u00e9\")\n assert length(:os.getenv(\"SYSTEM_ELIXIR_UTF_TEST_VAR\")) == 3\n assert System.get_env(\"SYSTEM_ELIXIR_UTF_TEST_VAR\") == \"ol\u00e9\"\n end\n\n test :cmd do\n assert is_binary(System.cmd \"binary\")\n assert is_list(System.cmd 'binary')\n end\n\n test :find_executable_with_binary do\n assert System.find_executable(\"erl\")\n assert is_binary System.find_executable(\"erl\")\n assert !System.find_executable(\"does-not-really-exist-from-elixir\")\n end\n\n test :find_executable_with_list do\n assert System.find_executable('erl')\n assert is_list System.find_executable('erl')\n assert !System.find_executable('does-not-really-exist-from-elixir')\n end\nend","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"0e2a38dc96485cd449dff1247c3e7c2d6b7db93a","subject":"Simplify code","message":"Simplify code\n","repos":"thbar\/elixir-playground","old_file":"lib\/day_03_01.ex","new_file":"lib\/day_03_01.ex","new_contents":"defmodule AdventOfCode2018.Day0301 do\n @regexp ~r\/^#(?\\d+) @ (?\\d+),(?\\d+): (?\\d+)x(?\\d+)$\/\n \n @doc ~S\"\"\"\n iex> AdventOfCode2018.Day0301.interpret(\"#1 @ 1,3: 4x4\")\n %{id: 1, x: 1, y: 3, w: 4, h: 4}\n iex> AdventOfCode2018.Day0301.interpret(\"#123 @ 2,10: 6x7\")\n %{id: 123, x: 2, y: 10, w: 6, h: 7}\n \"\"\"\n def interpret(input) do\n Regex.named_captures(@regexp, input)\n |> Enum.map(fn {k,v}->{String.to_atom(k),String.to_integer(v)} end)\n |> Map.new\n end\n \n def build_pixels(%{id: id, x: x, y: y, w: w, h: h}) do\n for i <- (0..w-1), j <- (0..h-1),\n do: %{x: x + i, y: y + j} \n end\n \n # We store all the \"pixels\" in a map to count them later\n def mark(box = %{id: id}, map) do\n build_pixels(box)\n |> Enum.reduce(map, fn(p, acc) -> \n Map.put(acc, p, Map.get(acc, p, []) ++ [id])\n end)\n end\n\n # Input is analysed line by line, then we build a map of all the pixels\n # drawn by each box\n def build_map(input) do\n input\n |> String.splitter(\"\\n\", trim: true)\n |> Stream.map(&String.trim\/1)\n |> Stream.map(&(interpret(&1)))\n end\n \n def mark_map(map) do\n Enum.reduce(map, Map.new, &mark\/2)\n end\n \n # here we finally we count all the pixels drawn more than once.\n def count_overlap(input) do\n input\n |> build_map\n |> mark_map\n |> Enum.filter(fn({_, ids}) -> Enum.count(ids) > 1 end)\n |> Enum.count\n end\n \n def find_non_overlapping(input) do\n map = input\n |> build_map\n \n all_ids = Enum.reduce(map, MapSet.new, fn(p, acc) ->\n MapSet.put(acc, p.id)\n end)\n\n overlapping_ids = map\n |> mark_map\n |> Enum.filter(fn({_coords, ids}) -> Enum.count(ids) > 1 end)\n |> Enum.map((fn({_coords, ids}) -> ids end))\n |> List.flatten\n |> Enum.uniq\n\n MapSet.difference(all_ids, MapSet.new(overlapping_ids))\n |> Enum.to_list\n end\nend","old_contents":"defmodule AdventOfCode2018.Day0301 do\n @regexp ~r\/^#(?\\d+) @ (?\\d+),(?\\d+): (?\\d+)x(?\\d+)$\/\n \n @doc ~S\"\"\"\n iex> AdventOfCode2018.Day0301.interpret(\"#1 @ 1,3: 4x4\")\n %{id: 1, x: 1, y: 3, w: 4, h: 4}\n iex> AdventOfCode2018.Day0301.interpret(\"#123 @ 2,10: 6x7\")\n %{id: 123, x: 2, y: 10, w: 6, h: 7}\n \"\"\"\n def interpret(input) do\n Regex.named_captures(@regexp, input)\n |> Enum.map(fn {k,v}->{String.to_atom(k),String.to_integer(v)} end)\n |> Map.new\n end\n \n def build_pixels(%{id: id, x: x, y: y, w: w, h: h}) do\n for i <- (0..w-1), j <- (0..h-1),\n do: %{x: x + i, y: y + j} \n end\n \n # We store all the \"pixels\" in a map to count them later\n def mark(box = %{id: id}, map) do\n build_pixels(box)\n |> Enum.reduce(map, fn(p, acc) -> \n Map.put(acc, p, Map.get(acc, p, []) ++ [id])\n end)\n end\n\n # Input is analysed line by line, then we build a map of all the pixels\n # drawn by each box\n def build_map(input) do\n input\n |> String.splitter(\"\\n\", trim: true)\n |> Stream.map(&String.trim\/1)\n |> Stream.map(&(interpret(&1)))\n end\n \n def mark_map(map) do\n Enum.reduce(map, Map.new, &mark\/2)\n end\n \n # here we finally we count all the pixels drawn more than once.\n def count_overlap(input) do\n input\n |> build_map\n |> mark_map\n |> Enum.reduce(0, fn({_, ids}, acc) ->\n if Enum.count(ids) > 1 do acc + 1 else acc end\n end)\n end\n \n def find_non_overlapping(input) do\n map = input\n |> build_map\n \n all_ids = Enum.reduce(map, MapSet.new, fn(p, acc) ->\n MapSet.put(acc, p.id)\n end)\n\n overlapping_ids = map\n |> mark_map\n |> Enum.filter(fn({_coords, ids}) -> Enum.count(ids) > 1 end)\n |> Enum.map((fn({_coords, ids}) -> ids end))\n |> List.flatten\n |> Enum.uniq\n\n MapSet.difference(all_ids, MapSet.new(overlapping_ids))\n |> Enum.to_list\n end\nend","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"373b4a6a178315522066bb7ab2488d056653ba2e","subject":"Applied `mix format` to the Mixfile.","message":"Applied `mix format` to the Mixfile.\n","repos":"bendiken\/templates,bendiken\/templates,bendiken\/templates,bendiken\/templates,bendiken\/templates,bendiken\/templates","old_file":"elixir\/mix.exs","new_file":"elixir\/mix.exs","new_contents":"defmodule Foobar.Mixfile do\n use Mix.Project\n\n @name \"Foobar\"\n @version File.read!(\"VERSION\") |> String.strip()\n @github \"https:\/\/github.com\/bendiken\/foobar\"\n @bitbucket \"https:\/\/bitbucket.org\/bendiken\/foobar\"\n @homepage @github\n\n def project do\n [\n app: :foobar,\n version: @version,\n elixir: \"~> 1.4\",\n compilers: Mix.compilers(),\n build_embedded: Mix.env() == :prod,\n start_permanent: Mix.env() == :prod,\n name: @name,\n source_url: @github,\n homepage_url: @homepage,\n description: description(),\n aliases: aliases(),\n deps: deps(),\n package: package(),\n docs: [source_ref: @version, main: \"readme\", extras: [\"README.md\"]],\n test_coverage: [tool: ExCoveralls],\n preferred_cli_env: [\n coveralls: :test,\n \"coveralls.detail\": :test,\n \"coveralls.post\": :test,\n \"coveralls.html\": :test\n ]\n ]\n end\n\n def application do\n # mod: {Foobar, []},\n [extra_applications: [:logger]]\n end\n\n defp package do\n [\n files: ~w(lib priv src mix.exs CHANGES.md README.md UNLICENSE VERSION),\n maintainers: [\"Arto Bendiken\"],\n licenses: [\"Public Domain\"],\n links: %{\"GitHub\" => @github, \"Bitbucket\" => @bitbucket}\n ]\n end\n\n defp description do\n \"\"\"\n Foobar is a template for Elixir projects.\n \"\"\"\n end\n\n defp deps do\n [\n {:credo, \">= 0.0.0\", only: [:dev, :test]},\n {:dialyxir, \">= 0.0.0\", only: [:dev, :test]},\n {:earmark, \">= 0.0.0\", only: :dev},\n {:ex_doc, \">= 0.0.0\", only: :dev},\n {:excoveralls, \">= 0.0.0\", only: :test}\n ]\n end\n\n defp aliases do\n []\n end\nend\n","old_contents":"defmodule Foobar.Mixfile do\n use Mix.Project\n\n @name \"Foobar\"\n @version File.read!(\"VERSION\") |> String.strip\n @github \"https:\/\/github.com\/bendiken\/foobar\"\n @bitbucket \"https:\/\/bitbucket.org\/bendiken\/foobar\"\n @homepage @github\n\n def project do\n [app: :foobar,\n version: @version,\n elixir: \"~> 1.4\",\n compilers: Mix.compilers,\n build_embedded: Mix.env == :prod,\n start_permanent: Mix.env == :prod,\n name: @name,\n source_url: @github,\n homepage_url: @homepage,\n description: description(),\n aliases: aliases(),\n deps: deps(),\n package: package(),\n docs: [source_ref: @version, main: \"readme\", extras: [\"README.md\"]],\n test_coverage: [tool: ExCoveralls],\n preferred_cli_env: [\n \"coveralls\": :test,\n \"coveralls.detail\": :test,\n \"coveralls.post\": :test,\n \"coveralls.html\": :test,\n ]]\n end\n\n def application do\n [#mod: {Foobar, []},\n extra_applications: [:logger]]\n end\n\n defp package do\n [files: ~w(lib priv src mix.exs CHANGES.md README.md UNLICENSE VERSION),\n maintainers: [\"Arto Bendiken\"],\n licenses: [\"Public Domain\"],\n links: %{\"GitHub\" => @github, \"Bitbucket\" => @bitbucket}]\n end\n\n defp description do\n \"\"\"\n Foobar is a template for Elixir projects.\n \"\"\"\n end\n\n defp deps do\n [{:credo, \">= 0.0.0\", only: [:dev, :test]},\n {:dialyxir, \">= 0.0.0\", only: [:dev, :test]},\n {:earmark, \">= 0.0.0\", only: :dev},\n {:ex_doc, \">= 0.0.0\", only: :dev},\n {:excoveralls, \">= 0.0.0\", only: :test}]\n end\n\n defp aliases do\n []\n end\nend\n","returncode":0,"stderr":"","license":"unlicense","lang":"Elixir"} {"commit":"dff3d1813bd736c9ceb9e7befc175b0192632c50","subject":"Expand includes after compiling EEx pages","message":"Expand includes after compiling EEx pages\n","repos":"Dalgona\/Serum","old_file":"lib\/serum\/build\/file_processor\/page.ex","new_file":"lib\/serum\/build\/file_processor\/page.ex","new_contents":"defmodule Serum.Build.FileProcessor.Page do\n @moduledoc false\n\n import Serum.IOProxy, only: [put_msg: 2]\n alias Serum.Markdown\n alias Serum.Page\n alias Serum.Plugin\n alias Serum.Project\n alias Serum.Renderer\n alias Serum.Result\n alias Serum.Template\n alias Serum.Template.Compiler, as: TC\n\n @spec preprocess_pages([Serum.File.t()], Project.t()) :: Result.t({[Page.t()], [map()]})\n def preprocess_pages(files, proj) do\n put_msg(:info, \"Processing page files...\")\n\n result =\n files\n |> Task.async_stream(&preprocess_page(&1, proj))\n |> Enum.map(&elem(&1, 1))\n |> Result.aggregate_values(:file_processor)\n\n case result do\n {:ok, pages} ->\n sorted_pages = Enum.sort(pages, &(&1.order < &2.order))\n\n {:ok, {sorted_pages, Enum.map(sorted_pages, &Page.compact\/1)}}\n\n {:error, _} = error ->\n error\n end\n end\n\n @spec preprocess_page(Serum.File.t(), Project.t()) :: Result.t(Page.t())\n defp preprocess_page(file, proj) do\n import Serum.HeaderParser\n\n opts = [\n title: :string,\n label: :string,\n group: :string,\n order: :integer,\n template: :string\n ]\n\n required = [:title]\n\n with {:ok, %{in_data: data} = file2} <- Plugin.processing_page(file),\n {:ok, {header, extras, rest}} <- parse_header(data, opts, required) do\n header = Map.put(header, :label, header[:label] || header.title)\n page = Page.new(file2.src, {header, extras}, rest, proj)\n\n {:ok, page}\n else\n {:invalid, message} -> {:error, {message, file.src, 0}}\n {:error, _} = plugin_error -> plugin_error\n end\n end\n\n @spec process_pages([Page.t()], Project.t()) :: Result.t([Page.t()])\n def process_pages(pages, proj) do\n pages\n |> Task.async_stream(&process_page(&1, proj))\n |> Enum.map(&elem(&1, 1))\n |> Result.aggregate_values(:file_processor)\n |> case do\n {:ok, pages} -> Plugin.processed_pages(pages)\n {:error, _} = error -> error\n end\n end\n\n @spec process_page(Page.t(), Project.t()) :: Result.t(Page.t())\n defp process_page(page, proj) do\n case do_process_page(page, proj) do\n {:ok, page} -> Plugin.processed_page(page)\n {:error, _} = error -> error\n end\n end\n\n @spec do_process_page(Page.t(), Project.t()) :: Result.t(Page.t())\n defp do_process_page(page, proj)\n\n defp do_process_page(%Page{type: \".md\"} = page, proj) do\n {:ok, %Page{page | data: Markdown.to_html(page.data, proj)}}\n end\n\n defp do_process_page(%Page{type: \".html\"} = page, _proj) do\n {:ok, page}\n end\n\n defp do_process_page(%Page{type: \".html.eex\"} = page, _proj) do\n with {:ok, ast} <- TC.compile_string(page.data),\n template = Template.new(ast, page.file, :template, page.file),\n {:ok, new_template} <- TC.Include.expand(template),\n {:ok, html} <- Renderer.render_fragment(new_template, []) do\n {:ok, %Page{page | data: html}}\n else\n {:ct_error, msg, line} -> {:error, {msg, page.file, line}}\n {:error, _} = error -> error\n end\n end\nend\n","old_contents":"defmodule Serum.Build.FileProcessor.Page do\n @moduledoc false\n\n import Serum.IOProxy, only: [put_msg: 2]\n alias Serum.Markdown\n alias Serum.Page\n alias Serum.Plugin\n alias Serum.Project\n alias Serum.Renderer\n alias Serum.Result\n alias Serum.Template\n alias Serum.Template.Compiler, as: TC\n\n @spec preprocess_pages([Serum.File.t()], Project.t()) :: Result.t({[Page.t()], [map()]})\n def preprocess_pages(files, proj) do\n put_msg(:info, \"Processing page files...\")\n\n result =\n files\n |> Task.async_stream(&preprocess_page(&1, proj))\n |> Enum.map(&elem(&1, 1))\n |> Result.aggregate_values(:file_processor)\n\n case result do\n {:ok, pages} ->\n sorted_pages = Enum.sort(pages, &(&1.order < &2.order))\n\n {:ok, {sorted_pages, Enum.map(sorted_pages, &Page.compact\/1)}}\n\n {:error, _} = error ->\n error\n end\n end\n\n @spec preprocess_page(Serum.File.t(), Project.t()) :: Result.t(Page.t())\n defp preprocess_page(file, proj) do\n import Serum.HeaderParser\n\n opts = [\n title: :string,\n label: :string,\n group: :string,\n order: :integer,\n template: :string\n ]\n\n required = [:title]\n\n with {:ok, %{in_data: data} = file2} <- Plugin.processing_page(file),\n {:ok, {header, extras, rest}} <- parse_header(data, opts, required) do\n header = Map.put(header, :label, header[:label] || header.title)\n page = Page.new(file2.src, {header, extras}, rest, proj)\n\n {:ok, page}\n else\n {:invalid, message} -> {:error, {message, file.src, 0}}\n {:error, _} = plugin_error -> plugin_error\n end\n end\n\n @spec process_pages([Page.t()], Project.t()) :: Result.t([Page.t()])\n def process_pages(pages, proj) do\n pages\n |> Task.async_stream(&process_page(&1, proj))\n |> Enum.map(&elem(&1, 1))\n |> Result.aggregate_values(:file_processor)\n |> case do\n {:ok, pages} -> Plugin.processed_pages(pages)\n {:error, _} = error -> error\n end\n end\n\n @spec process_page(Page.t(), Project.t()) :: Result.t(Page.t())\n defp process_page(page, proj) do\n case do_process_page(page, proj) do\n {:ok, page} -> Plugin.processed_page(page)\n {:error, _} = error -> error\n end\n end\n\n @spec do_process_page(Page.t(), Project.t()) :: Result.t(Page.t())\n defp do_process_page(page, proj)\n\n defp do_process_page(%Page{type: \".md\"} = page, proj) do\n {:ok, %Page{page | data: Markdown.to_html(page.data, proj)}}\n end\n\n defp do_process_page(%Page{type: \".html\"} = page, _proj) do\n {:ok, page}\n end\n\n defp do_process_page(%Page{type: \".html.eex\"} = page, _proj) do\n with {:ok, ast} <- TC.compile_string(page.data),\n template = Template.new(ast, page.file, :template, page.file),\n {:ok, html} <- Renderer.render_fragment(template, []) do\n {:ok, %Page{page | data: html}}\n else\n {:ct_error, msg, line} -> {:error, {msg, page.file, line}}\n {:error, _} = error -> error\n end\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"ed40cd54928fc0544690922caceb76d6b65a6e9a","subject":"Remove unused file","message":"Remove unused file\n","repos":"Dalgona\/Serum","old_file":"lib\/serum\/build_pass1\/index_builder.ex","new_file":"lib\/serum\/build_pass1\/index_builder.ex","new_contents":"","old_contents":"defmodule Serum.BuildPass1.IndexBuilder do\n alias Serum.Build\n alias Serum.Error\n alias Serum.Tag\n\n @type state :: Build.state\n\n @spec run(Build.mode, state) :: Error.result(Tag.t)\n\n def run(_mode, state) do\n tags =\n state.post_info\n |> Enum.reduce(MapSet.new(), fn info, acc ->\n MapSet.union acc, MapSet.new(info.tags)\n end)\n |> MapSet.to_list\n {:ok, tags}\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"3ecfa74bc3c263094c751a3c9b3bf3b4de372412","subject":"Remove log","message":"Remove log\n","repos":"elixir-web\/weber,mozillo\/weber,mozillo\/weber,elixir-web\/weber","old_file":"lib\/weber\/i18n\/localization_manager.ex","new_file":"lib\/weber\/i18n\/localization_manager.ex","new_contents":"defmodule Weber.Localization.LocalizationManager do\n \n use GenServer.Behaviour\n \n defrecord LocalizationConfig,\n config: nil,\n default_locale: nil\n\n def start_link(config) do\n :gen_server.start_link({:local, :localization_manager}, __MODULE__, [config], [])\n end\n\n def init([config]) do\n :gen_server.cast(:erlang.self(), :load_localization_files)\n { :ok, LocalizationConfig.new config: config}\n end\n\n def handle_cast(:load_localization_files, state) do\n case :lists.keyfind(:localization, 1, state.config) do\n false -> \n {:stop, :normal, state}\n\n {:localization, localization_config} ->\n {:ok, project_path} = File.cwd()\n {_, default_locale} = :lists.keyfind(:default_locale, 1, localization_config)\n {_, use_locales} = :lists.keyfind(:use_locales, 1, localization_config)\n\n use_locales = Enum.map(use_locales, fn(l) -> atom_to_binary(l) <> \".json\" end)\n\n case File.ls(project_path <> \"\/deps\/weber\/lib\/weber\/i18n\/localization\/locale\") do\n {:ok, localization_files} ->\n Enum.each(localization_files, fn (file) ->\n case :lists.member(file, use_locales) do\n true ->\n case File.read(project_path <> \"\/deps\/weber\/lib\/weber\/i18n\/localization\/locale\/\" <> file) do\n {:ok, data} -> Weber.Localization.Locale.start_link(binary_to_atom(file), data) \n _ -> :ok\n end\n false ->\n :ok\n end\n end)\n _ -> :ok\n end\n \n case File.ls(project_path <> \"\/lang\") do\n {:ok, translation_files} ->\n Enum.each(translation_files, fn (file) ->\n {:ok, translation_file_data} = File.read(project_path <> \"\/lang\/\" <> file)\n case translation_file_data do\n <<>> -> :ok\n _ -> Weber.Translation.Translate.start_link(binary_to_atom(file), translation_file_data)\n end\n end)\n _ -> :ok\n end\n \n {:noreply, LocalizationConfig.new config: state.config, default_locale: default_locale}\n end\n end\n\n def handle_cast({:set_current_locale, locale}, state) do\n {:noreply, LocalizationConfig.new config: state.config, default_locale: locale <> \".json\"}\n end\n\n def handle_call(:get_current_locale, _from, state) do\n {:reply, :lists.nth(1, String.split(state.default_locale, \".\")), state}\n end\n\nend","old_contents":"defmodule Weber.Localization.LocalizationManager do\n \n use GenServer.Behaviour\n \n defrecord LocalizationConfig,\n config: nil,\n default_locale: nil\n\n def start_link(config) do\n :gen_server.start_link({:local, :localization_manager}, __MODULE__, [config], [])\n end\n\n def init([config]) do\n :gen_server.cast(:erlang.self(), :load_localization_files)\n { :ok, LocalizationConfig.new config: config}\n end\n\n def handle_cast(:load_localization_files, state) do\n case :lists.keyfind(:localization, 1, state.config) do\n false -> \n {:stop, :normal, state}\n\n {:localization, localization_config} ->\n {:ok, project_path} = File.cwd()\n {_, default_locale} = :lists.keyfind(:default_locale, 1, localization_config)\n {_, use_locales} = :lists.keyfind(:use_locales, 1, localization_config)\n\n use_locales = Enum.map(use_locales, fn(l) -> atom_to_binary(l) <> \".json\" end)\n \n case File.ls(project_path <> \"\/deps\/weber\/lib\/weber\/i18n\/localization\/locale\") do\n {:ok, localization_files} ->\n Enum.each(localization_files, fn (file) ->\n case :lists.member(file, use_locales) do\n true ->\n :io.format(\"~p~n\", [File.read(project_path <> \"\/deps\/weber\/lib\/weber\/i18n\/localization\/locale\/\" <> file)])\n case File.read(project_path <> \"\/deps\/weber\/lib\/weber\/i18n\/localization\/locale\/\" <> file) do\n {:ok, data} -> Weber.Localization.Locale.start_link(binary_to_atom(file), data) \n _ -> :ok\n end\n false ->\n :ok\n end\n end)\n _ -> :ok\n end\n \n case File.ls(project_path <> \"\/lang\") do\n {:ok, translation_files} ->\n Enum.each(translation_files, fn (file) ->\n {:ok, translation_file_data} = File.read(project_path <> \"\/lang\/\" <> file)\n case translation_file_data do\n <<>> -> :ok\n _ -> Weber.Translation.Translate.start_link(binary_to_atom(file), translation_file_data)\n end\n end)\n _ -> :ok\n end\n \n {:noreply, LocalizationConfig.new config: state.config, default_locale: default_locale}\n end\n end\n\n def handle_cast({:set_current_locale, locale}, state) do\n {:noreply, LocalizationConfig.new config: state.config, default_locale: locale <> \".json\"}\n end\n\n def handle_call(:get_current_locale, _from, state) do\n {:reply, :lists.nth(1, String.split(state.default_locale, \".\")), state}\n end\n\nend","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"6304a761b6cc4ad4f1a7e31b8fbbd5cb46a05633","subject":"Remove command option in favor of shell scripts","message":"Remove command option in favor of shell scripts\n","repos":"rentpath\/rprel","old_file":"lib\/rprel\/cli.ex","new_file":"lib\/rprel\/cli.ex","new_contents":"defmodule Rprel.CLI do\n @invalid_repo_name_msg \"You must provide a full repo name.\"\n def invalid_repo_name_msg, do: @invalid_repo_name_msg\n\n @invalid_commit_msg \"You must provide a commit sha.\"\n def invalid_commit_msg, do: @invalid_commit_msg\n\n @invalid_version_msg \"You must provide a version number.\"\n def invalid_version_msg, do: @invalid_version_msg\n\n @invalid_files_msg \"You must provide at least one valid file.\"\n def invalid_files_msg, do: @invalid_files_msg\n\n @invalid_token_msg \"You must provide a valid GitHub authentication token.\"\n def invalid_token_msg, do: @invalid_token_msg\n\n @release_already_exists_msg \"A release for that version already exists. Please use a different version.\"\n def release_already_exists_msg, do: @release_already_exists_msg\n\n @unspecified_error_msg \"An unknown error has occurred.\"\n def unspecified_error_msg, do: @unspecified_error_msg\n\n def main(argv) do\n {_result, message} = do_main(argv)\n if message, do: IO.puts(message)\n end\n\n def do_main(argv) do\n {opts, args, _invalid_opts} = OptionParser.parse_head(argv, strict: [help: :boolean, version: :boolean], aliases: [h: :help, v: :version])\n case args do\n [\"help\" | cmd] -> help(cmd)\n [\"build\" | build_argv] -> build(build_argv)\n [\"release\" | release_argv] -> release(release_argv)\n _ -> handle_other_commands(opts)\n end\n end\n\n def help(cmd) do\n case cmd do\n [\"build\"] -> {:ok, build_help_text}\n [\"release\"] -> {:ok, release_help_text}\n _ -> {:error, \"No help topic for '#{cmd}'\"}\n end\n end\n\n def build(build_argv) do\n {build_opts, _build_args, _invalid_opts} = OptionParser.parse(build_argv, strict: [help: :boolean, archive_command: :string, build_number: :string, commit: :string, path: :string], aliases: [h: :help, a: :archive_command])\n cond do\n build_opts[:help] -> {:ok, build_help_text}\n true -> Rprel.Build.create(build_opts)\n end\n end\n\n def release(release_argv) do\n {release_opts, release_args, _invalid_opts} = OptionParser.parse(release_argv, strict: [help: :boolean, token: :string, commit: :string, repo: :string, version: :string], aliases: [h: :help, t: :token, c: :commit, r: :repo, v: :version])\n cond do\n release_opts[:help] -> {:ok, release_help_text}\n true -> release_opts |> update_with_release_env_vars |> do_release(release_args)\n end\n end\n\n def handle_other_commands(opts) do\n cond do\n opts[:help] -> {:ok, help_text}\n opts[:version] -> {:ok, Rprel.version}\n true -> {:ok, help_text}\n end\n end\n\n defp do_release(opts, args) do\n release = %Rprel.GithubRelease{name: opts[:repo], version: opts[:version], commit: opts[:commit]}\n case Rprel.ReleaseCreator.create(release, args, [token: opts[:token]]) do\n {:error, :invalid_auth_token} -> {:error, @invalid_token_msg}\n {:error, :invalid_repo_name} -> {:error, @invalid_repo_name_msg}\n {:error, :missing_commit} -> {:error, @invalid_commit_msg}\n {:error, :missing_version} -> {:error, @invalid_version_msg}\n {:error, :missing_files} -> {:error, @invalid_files_msg}\n {:error, :release_already_exists} -> {:error, @release_already_exists_msg}\n {:error, :unspecified_error} -> {:error, @unspecified_error_msg}\n {:ok, _} -> {:ok, \"\"}\n end\n end\n\n defp update_with_release_env_vars(opts) do\n opts\n |> Keyword.put_new(:token, System.get_env(\"GITHUB_AUTH_TOKEN\"))\n |> Keyword.put_new(:commit, System.get_env(\"RELEASE_COMMIT\"))\n |> Keyword.put_new(:repo, System.get_env(\"RELEASE_REPO\"))\n |> Keyword.put_new(:version, System.get_env(\"RELEASE_VERSION\"))\n end\n\n def help_text do\n ~s\"\"\"\n NAME:\n rprel - Build and create releases\n USAGE:\n rprel [global options] command [command options] [arguments...]\n VERSION:\n #{Rprel.version}\n AUTHOR(S):\n Tyler Long\n Colin Rymer\n COMMANDS:\n build\n help\n release\n GLOBAL OPTIONS:\n --help, -h show help\n --version, -v print the version\n COPYRIGHT:\n 2016\n \"\"\"\n end\n\n def build_help_text do\n ~s\"\"\"\n NAME:\n rprel build - Builds a release artifact\n\n USAGE:\n rprel build [command options] [arguments...]\n\n OPTIONS:\n --archive-command ARCHIVE_CMD, -a ARCHIVE_CMD\n The ARCHIVE_CMD to run during the artifact packaging phase. If no command\n is provided and a Makefile exists with an `archive` target, `make archive`\n will be run, otherwise, the source provided will be packaged into a\n gzipped tarball.\n --build-number NUMBER\n The NUMBER used by the CI service to identify the build` [$BUILD_NUMBER]\n --commit SHA\n The SHA of the build (default: `git rev-parse --verify HEAD`) [$GIT_COMMIT]\n --path PATH\n The path to tar and gzip (default: current working directory )\n \"\"\"\n end\n\n def release_help_text do\n ~s\"\"\"\n NAME:\n rprel release - Creates GitHub release and upload artifacts\n\n USAGE:\n rprel release [command options] [arguments...]\n\n OPTIONS:\n --token TOKEN, -t TOKEN\n The GitHub authentication TOKEN [$GITHUB_AUTH_TOKEN]\n --commit SHA, -c SHA\n The commit SHA that will be used to create the release [$RELEASE_COMMIT]\n --repo OWNER\/REPO, -r OWNER\/REPO\n The full repo name, OWNER\/REPO, where the release will be created [$RELEASE_REPO]\n --version VERSION, -v VERSION\n The release VERSION [$RELEASE_VERSION]\n \"\"\"\n end\nend\n","old_contents":"defmodule Rprel.CLI do\n @invalid_repo_name_msg \"You must provide a full repo name.\"\n def invalid_repo_name_msg, do: @invalid_repo_name_msg\n\n @invalid_commit_msg \"You must provide a commit sha.\"\n def invalid_commit_msg, do: @invalid_commit_msg\n\n @invalid_version_msg \"You must provide a version number.\"\n def invalid_version_msg, do: @invalid_version_msg\n\n @invalid_files_msg \"You must provide at least one valid file.\"\n def invalid_files_msg, do: @invalid_files_msg\n\n @invalid_token_msg \"You must provide a valid GitHub authentication token.\"\n def invalid_token_msg, do: @invalid_token_msg\n\n @release_already_exists_msg \"A release for that version already exists. Please use a different version.\"\n def release_already_exists_msg, do: @release_already_exists_msg\n\n @unspecified_error_msg \"An unknown error has occurred.\"\n def unspecified_error_msg, do: @unspecified_error_msg\n\n def main(argv) do\n {_result, message} = do_main(argv)\n if message, do: IO.puts(message)\n end\n\n def do_main(argv) do\n {opts, args, _invalid_opts} = OptionParser.parse_head(argv, strict: [help: :boolean, version: :boolean], aliases: [h: :help, v: :version])\n case args do\n [\"help\" | cmd] -> help(cmd)\n [\"build\" | build_argv] -> build(build_argv)\n [\"release\" | release_argv] -> release(release_argv)\n _ -> handle_other_commands(opts)\n end\n end\n\n def help(cmd) do\n case cmd do\n [\"build\"] -> {:ok, build_help_text}\n [\"release\"] -> {:ok, release_help_text}\n _ -> {:error, \"No help topic for '#{cmd}'\"}\n end\n end\n\n def build(build_argv) do\n {build_opts, _build_args, _invalid_opts} = OptionParser.parse(build_argv, strict: [help: :boolean, command: :string, archive_command: :string, build_number: :string, commit: :string, path: :string], aliases: [h: :help, c: :command, a: :archive_command])\n cond do\n build_opts[:help] -> {:ok, build_help_text}\n true -> Rprel.Build.create(build_opts)\n end\n end\n\n def release(release_argv) do\n {release_opts, release_args, _invalid_opts} = OptionParser.parse(release_argv, strict: [help: :boolean, token: :string, commit: :string, repo: :string, version: :string], aliases: [h: :help, t: :token, c: :commit, r: :repo, v: :version])\n cond do\n release_opts[:help] -> {:ok, release_help_text}\n true -> release_opts |> update_with_release_env_vars |> do_release(release_args)\n end\n end\n\n def handle_other_commands(opts) do\n cond do\n opts[:help] -> {:ok, help_text}\n opts[:version] -> {:ok, Rprel.version}\n true -> {:ok, help_text}\n end\n end\n\n defp do_release(opts, args) do\n release = %Rprel.GithubRelease{name: opts[:repo], version: opts[:version], commit: opts[:commit]}\n case Rprel.ReleaseCreator.create(release, args, [token: opts[:token]]) do\n {:error, :invalid_auth_token} -> {:error, @invalid_token_msg}\n {:error, :invalid_repo_name} -> {:error, @invalid_repo_name_msg}\n {:error, :missing_commit} -> {:error, @invalid_commit_msg}\n {:error, :missing_version} -> {:error, @invalid_version_msg}\n {:error, :missing_files} -> {:error, @invalid_files_msg}\n {:error, :release_already_exists} -> {:error, @release_already_exists_msg}\n {:error, :unspecified_error} -> {:error, @unspecified_error_msg}\n {:ok, _} -> {:ok, \"\"}\n end\n end\n\n defp update_with_release_env_vars(opts) do\n opts\n |> Keyword.put_new(:token, System.get_env(\"GITHUB_AUTH_TOKEN\"))\n |> Keyword.put_new(:commit, System.get_env(\"RELEASE_COMMIT\"))\n |> Keyword.put_new(:repo, System.get_env(\"RELEASE_REPO\"))\n |> Keyword.put_new(:version, System.get_env(\"RELEASE_VERSION\"))\n end\n\n def help_text do\n ~s\"\"\"\n NAME:\n rprel - Build and create releases\n USAGE:\n rprel [global options] command [command options] [arguments...]\n VERSION:\n #{Rprel.version}\n AUTHOR(S):\n Tyler Long\n Colin Rymer\n COMMANDS:\n build\n help\n release\n GLOBAL OPTIONS:\n --help, -h show help\n --version, -v print the version\n COPYRIGHT:\n 2016\n \"\"\"\n end\n\n def build_help_text do\n ~s\"\"\"\n NAME:\n rprel build - Builds a release artifact\n\n USAGE:\n rprel build [command options] [arguments...]\n\n OPTIONS:\n --command CMD, -c CMD\n The CMD to run during the building of the artifact. If no command is\n provided and a Makefile is present, rprel will run `make build` if `build`\n is a valid Make target, otherwise falling back to just `make`. If no `CMD`\n is provided and there is no Makefile, nothing will be done during the\n build phase.\n --archive-command ARCHIVE_CMD, -a ARCHIVE_CMD\n The ARCHIVE_CMD to run during the artifact packaging phase. If no command\n is provided and a Makefile exists with an `archive` target, `make archive`\n will be run, otherwise, the source provided will be packaged into a\n gzipped tarball.\n --build-number NUMBER\n The NUMBER used by the CI service to identify the build` [$BUILD_NUMBER]\n --commit SHA\n The SHA of the build (default: `git rev-parse --verify HEAD`) [$GIT_COMMIT]\n --path PATH\n The path to tar and gzip (default: current working directory )\n \"\"\"\n end\n\n def release_help_text do\n ~s\"\"\"\n NAME:\n rprel release - Creates GitHub release and upload artifacts\n\n USAGE:\n rprel release [command options] [arguments...]\n\n OPTIONS:\n --token TOKEN, -t TOKEN\n The GitHub authentication TOKEN [$GITHUB_AUTH_TOKEN]\n --commit SHA, -c SHA\n The commit SHA that will be used to create the release [$RELEASE_COMMIT]\n --repo OWNER\/REPO, -r OWNER\/REPO\n The full repo name, OWNER\/REPO, where the release will be created [$RELEASE_REPO]\n --version VERSION, -v VERSION\n The release VERSION [$RELEASE_VERSION]\n \"\"\"\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"92bb3817ad66c6d7e5cf84b7d165baed3dee44e5","subject":"fix warnings","message":"fix warnings\n","repos":"ello\/apex,ello\/apex,ello\/apex","old_file":"apps\/ello_v2\/web\/controllers\/post_controller.ex","new_file":"apps\/ello_v2\/web\/controllers\/post_controller.ex","new_contents":"defmodule Ello.V2.PostController do\n use Ello.V2.Web, :controller\n alias Ello.Core.{Content, Content.Post}\n alias Ello.Events\n alias Ello.Events.CountPostView\n\n def show(conn, params) do\n with %Post{} = post <- load_post(conn, params),\n true <- owned_by_user(post, params) do\n track_post_view(conn, post)\n render(conn, post: post)\n else\n _ -> send_resp(conn, 404, \"\")\n end\n end\n\n defp load_post(conn, %{\"id\" => id_or_slug}) do\n Content.post(id_or_slug,\n conn.assigns[:current_user],\n conn.assigns[:allow_nsfw],\n conn.assigns[:allow_nudity]\n )\n end\n\n defp track_post_view(%{assigns: assigns}, post) do\n current_user_id = case assigns[:current_user] do\n %{id: id} -> id\n _ -> nil\n end\n\n event = %CountPostView{\n post_ids: [post.id],\n current_user_id: current_user_id,\n stream_kind: \"post\",\n }\n Events.publish(event)\n end\n\n defp owned_by_user(post, %{\"user_id\" => \"~\" <> username}),\n do: post.author.username == username\n defp owned_by_user(post, %{\"user_id\" => user_id}),\n do: \"#{post.author.id}\" == user_id\n defp owned_by_user(_, _), do: true\n\nend\n","old_contents":"defmodule Ello.V2.PostController do\n use Ello.V2.Web, :controller\n alias Ello.Core.{Content, Content.Post}\n alias Ello.Events\n alias Ello.Events.CountPostView\n\n def show(conn, params) do\n with %Post{} = post <- load_post(conn, params),\n true <- owned_by_user(post, params) do\n track_post_view(conn, post)\n render(conn, post: post)\n else\n _ -> send_resp(conn, 404, \"\")\n end\n end\n\n defp load_post(conn, %{\"id\" => id_or_slug}) do\n Content.post(id_or_slug,\n conn.assigns[:current_user],\n conn.assigns[:allow_nsfw],\n conn.assigns[:allow_nudity]\n )\n end\n\n defp track_post_view(%{assigns: assigns} = conn, post) do\n current_user_id = case assigns[:current_user] do\n %{id: id} -> id\n _ -> nil\n end\n\n event = %CountPostView{\n post_ids: [post.id],\n current_user_id: current_user_id,\n stream_kind: \"post\",\n }\n Ello.Events.publish(event)\n end\n\n defp owned_by_user(post, %{\"user_id\" => \"~\" <> username}),\n do: post.author.username == username\n defp owned_by_user(post, %{\"user_id\" => user_id}),\n do: \"#{post.author.id}\" == user_id\n defp owned_by_user(_, _), do: true\n\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"ad4e7f1dcd4695379c1cb792cd1741f88c9e6376","subject":"Error fix for themes directory resolve","message":"Error fix for themes directory resolve\n","repos":"cyberdot\/dnevnik,cyberdot\/dnevnik","old_file":"lib\/dnevnik\/theme.ex","new_file":"lib\/dnevnik\/theme.ex","new_contents":"defmodule Dnevnik.Theme do\n alias Dnevnik.{Config, Errors, Utils.Git, Utils.IO}\n \n def init do\n File.mkdir \"#{Config.content_directory}\/themes\"\n File.cp_r IO.resolve(\"themes\"), \"#{Config.content_directory}\/themes\"\n end\n \n def ensure, do: Config.data |> Map.get(:theme) |> String.split(\"\/\") |> _ensure \n \n def current, do: Config.data|> Map.get(:theme) |> String.split(\"\/\") |> _current\n defp _current([local]), do: local\n defp _current([_user, repo]), do: repo\n defp _current(url), do: url |> Enum.reverse |> hd |> String.replace(\"\\.git\", \"\")\n\n defp _ensure([local]), do: ensure_local(File.dir?(\"#{Config.content_directory}\/themes\/#{local}\"), local)\n defp _ensure([user, repo]), do: ensure_github(File.dir?(\"#{Config.content_directory}\/themes\/#{repo}\"), user, repo)\n defp _ensure(url), do: ensure_url(url)\n\n defp ensure_local(true, _theme), do: true\n defp ensure_local(false, theme), do: raise(Errors.ThemeNotFound, {:local, theme})\n \n defp ensure_github(true, _user, _repo), do: true\n defp ensure_github(false, user, repo), do: \"https:\/\/github.com\/#{user}\/#{repo}.git\" |> Git.clone \n\n defp ensure_url(url) do\n repo = url\n |> Enum.reverse\n |> hd\n |> String.replace(\"\\.git\", \"\")\n\n _ensure_url(File.dir?(\"#{Config.content_directory}\/themes\/#{repo}\"), Enum.join(url, \"\/\"))\n end\n\n def _ensure_url(true, _url), do: true\n def _ensure_url(false, url), do: url |> Git.clone\n\nend\n","old_contents":"defmodule Dnevnik.Theme do\n alias Dnevnik.{Config, Errors, Utils.Git, Utils.IO}\n \n def init do\n File.mkdir \"#{Config.content_directory}\/themes\"\n File.cp_r IO.resolve \"themes\", \"#{Config.content_directory}\/themes\"\n end\n \n def ensure, do: Config.data |> Map.get(:theme) |> String.split(\"\/\") |> _ensure \n \n def current, do: Config.data|> Map.get(:theme) |> String.split(\"\/\") |> _current\n defp _current([local]), do: local\n defp _current([_user, repo]), do: repo\n defp _current(url), do: url |> Enum.reverse |> hd |> String.replace(\"\\.git\", \"\")\n\n defp _ensure([local]), do: ensure_local(File.dir?(\"#{Config.content_directory}\/themes\/#{local}\"), local)\n defp _ensure([user, repo]), do: ensure_github(File.dir?(\"#{Config.content_directory}\/themes\/#{repo}\"), user, repo)\n defp _ensure(url), do: ensure_url(url)\n\n defp ensure_local(true, _theme), do: true\n defp ensure_local(false, theme), do: raise(Errors.ThemeNotFound, {:local, theme})\n \n defp ensure_github(true, _user, _repo), do: true\n defp ensure_github(false, user, repo), do: \"https:\/\/github.com\/#{user}\/#{repo}.git\" |> Git.clone \n\n defp ensure_url(url) do\n repo = url\n |> Enum.reverse\n |> hd\n |> String.replace(\"\\.git\", \"\")\n\n _ensure_url(File.dir?(\"#{Config.content_directory}\/themes\/#{repo}\"), Enum.join(url, \"\/\"))\n end\n\n def _ensure_url(true, _url), do: true\n def _ensure_url(false, url), do: url |> Git.clone\n\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"e12b2b4a9c1324a3a2680dbae4718c87d5470194","subject":"Update Shell.error, Shell.raise to consider --quiet arg","message":"Update Shell.error, Shell.raise to consider --quiet arg\n","repos":"capbash\/doex","old_file":"lib\/doex\/io\/shell.ex","new_file":"lib\/doex\/io\/shell.ex","new_contents":"defmodule Doex.Io.Shell do\n\n def cmd(\"doex\") do\n if has_mix?() do\n \"mix doex\"\n else\n \"doex\"\n end\n end\n def cmd(raw_cmd) do\n if has_mix?() do\n String.replace(raw_cmd, \"doex \", \"mix doex.\")\n else\n raw_cmd\n end\n end\n\n def info(raw_msg, args \\\\ %{}) do\n case parse(raw_msg, args) do\n {:quiet, msg} -> msg\n {:ok, msg} -> if has_mix?() do\n Mix.shell.info(msg)\n else\n IO.puts(msg)\n end\n end\n end\n\n def inspect(data, %{quiet: true_or_false}), do: true_or_false |> _inspect(data)\n def inspect(data, args), do: Enum.member?(args, \"--quiet\") |> _inspect(data)\n\n defp _inspect(false, data), do: IO.inspect(data)\n defp _inspect(true, data), do: data\n\n def error(raw_msg, args \\\\ %{}) do\n case parse(raw_msg, args) do\n {:quiet, msg} -> msg\n {:ok, msg} -> if has_mix?() do\n Mix.shell.error(msg)\n else\n IO.puts(msg)\n end\n end\n end\n\n def raise(raw_msg, args \\\\ %{}) do\n case parse(raw_msg, args) do\n {:quiet, msg} -> msg\n {:ok, msg} -> if has_mix?() do\n Mix.raise(msg)\n else\n Kernel.raise(msg)\n end\n end\n end\n\n def newline, do: info \"\"\n\n defp has_mix?, do: function_exported?(Mix, :shell, 1)\n\n defp parse(msg, args), do: _parse(msg |> clean, args)\n defp _parse(msg, %{quiet: true}), do: {:quiet, msg}\n defp _parse(msg, args) when is_list(args) do\n if Enum.member?(args, \"--quiet\") do\n {:quiet, msg}\n else\n {:ok, msg}\n end\n end\n defp _parse(msg, _), do: {:ok, msg}\n defp clean(msg) when is_binary(msg), do: msg\n defp clean(msg), do: \"#{msg}\"\n\nend","old_contents":"defmodule Doex.Io.Shell do\n\n def cmd(\"doex\") do\n if has_mix?() do\n \"mix doex\"\n else\n \"doex\"\n end\n end\n def cmd(raw_cmd) do\n if has_mix?() do\n String.replace(raw_cmd, \"doex \", \"mix doex.\")\n else\n raw_cmd\n end\n end\n\n def info(_msg, %{quiet: true}), do: nil\n def info(msg, args) when is_list(args) do\n if Enum.member?(args, \"--quiet\") do\n nil\n else\n info(msg)\n end\n end\n def info(msg, _), do: info(msg)\n def info(msg) when is_binary(msg) do\n if has_mix?() do\n Mix.shell.info(msg)\n else\n IO.puts(msg)\n end\n end\n def info(msg), do: info(\"#{msg}\")\n\n def inspect(data, %{quiet: true_or_false}), do: true_or_false |> _inspect(data)\n def inspect(data, args), do: Enum.member?(args, \"--quiet\") |> _inspect(data)\n\n defp _inspect(false, data), do: IO.inspect(data)\n defp _inspect(true, data), do: data\n\n def error(msg) do\n if has_mix?() do\n Mix.shell.error(msg)\n else\n IO.puts(msg)\n end\n end\n\n def raise(msg) do\n if has_mix?() do\n Mix.raise(msg)\n else\n Kernel.raise(msg)\n end\n end\n\n def newline, do: info \"\"\n\n defp has_mix?, do: function_exported?(Mix, :shell, 1)\nend","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"91bf3cc66f3e52872180da3dc1d22df8cb1cfd46","subject":"Using Kernel.ParallelRequire.files to load in files for macros now","message":"Using Kernel.ParallelRequire.files to load in files for macros now\n","repos":"bryanjos\/elixirscript,elixirscript\/elixirscript","old_file":"lib\/elixir_script.ex","new_file":"lib\/elixir_script.ex","new_contents":"defmodule ElixirScript do\n alias ESTree.Tools.Builder\n alias ESTree.Tools.Generator\n alias ElixirScript.Translator.Utils\n alias ElixirScript.Translator.ModuleCollector\n alias ElixirScript.Compiler.Cache\n alias ElixirScript.Compiler.Output\n require Logger\n\n @moduledoc \"\"\"\n Translates Elixir into JavaScript.\n\n All compile functions return a list of\n transpiled javascript code or a tuple consisting of\n the file name for the code and the transpiled javascript code.\n\n All compile functions also take an optional opts parameter\n that controls transpiler output.\n\n Available options are:\n * `:include_path` - a boolean controlling whether to return just the JavaScript code\n or a tuple of the file name and the JavaScript code\n * `:root` - a binary path prepended to the path of the standard lib imports if needed\n * `:env` - a Macro.env struct to use. This is most useful when using macros. Make sure that the\n env has the macros imported or required.\n * `:core_path` - The es6 import path used to import the elixirscript core.\n When using this option, the Elixir.js file is not exported\n * `:full_build` - For compile_path, tells the compiler to perform a full build instead of incremental one\n * `:output` - option to tell compiler how to output data\n * `nil`: Return as list\n * `:stdout`: Write to standard out\n * `path (string)`: Write to specified path\n \"\"\"\n\n defmacro __using__(_) do\n quote do\n import Kernel, only: [&&: 2, use: 2, use: 1]\n import ElixirScript.Kernel\n require ElixirScript.JS, as: JS\n require ElixirScript.Html, as: Html\n require ElixirScript.VDom, as: VDom\n end\n end\n\n # This is the serialized state of the ElixirScript.State module containing references to the standard library\n @external_resource stdlib_state_path = Path.join([__DIR__, \"elixir_script\", \"translator\", \"stdlib_state.bin\"])\n @stdlib_state File.read(stdlib_state_path)\n @lib_path Application.get_env(:elixir_script, :lib_path)\n\n @doc \"\"\"\n Compiles the given Elixir code string\n \"\"\"\n @spec compile(binary, Map.t) :: [binary | {binary, binary} | :ok]\n def compile(elixir_code, opts \\\\ %{}) do\n elixir_code\n |> Code.string_to_quoted!\n |> compile_quoted(opts)\n end\n\n @doc \"\"\"\n Compiles the given Elixir code in quoted form\n \"\"\"\n @spec compile_quoted(Macro.t, Map.t) :: [binary | {binary, binary} | :ok]\n def compile_quoted(quoted, opts \\\\ %{}) do\n { code, _ } = do_compile(opts, [quoted], get_stdlib_state, [])\n Output.out(quoted, code, build_compiler_options(opts))\n end\n\n @doc \"\"\"\n Compiles the elixir files found at the given path\n \"\"\"\n @spec compile_path(binary, Map.t) :: [binary | {binary, binary} | :ok]\n def compile_path(path, opts \\\\ %{}) do\n\n {expanded_path, loaded_modules} = case File.dir?(path) do\n true ->\n process_path(path)\n false ->\n {[path], []}\n end\n\n opts = build_compiler_options(opts)\n\n compiler_cache = get_compiler_cache(path, opts)\n\n new_file_stats = Cache.build_file_stats(expanded_path)\n\n changed_files = Cache.get_changed_files(compiler_cache.input_files, new_file_stats)\n |> Enum.map(fn {file, state} -> file end)\n\n code = Enum.map(changed_files, &file_to_quoted\/1)\n\n { code, new_state } = do_compile(opts, code, compiler_cache.state, loaded_modules)\n compiler_cache = %{compiler_cache | input_files: new_file_stats, state: new_state }\n\n Cache.write(path, compiler_cache)\n Output.out(path, code, opts)\n end\n\n defp process_path(path) do\n path = Path.join(path, \"**\/*.{ex,exs,exjs}\") |> Path.wildcard\n {exjs, ex} = Enum.partition(path, fn(x) ->\n case Path.extname(x) do\n ext when ext in [\".ex\", \".exs\"] ->\n false\n _ ->\n true\n end\n end)\n\n ex = Kernel.ParallelRequire.files(ex)\n {exjs, ex}\n end\n\n defp get_stdlib_state() do\n case @stdlib_state do\n {:ok, data} ->\n data\n {:error, _} ->\n raise RuntimeError, message: \"Standard Library state not found. Please run `mix std_lib`\"\n end\n end\n\n defp get_compiler_cache(path, opts) do\n if Map.get(opts, :full_build) or empty?(opts.output) do\n Cache.delete(path)\n Cache.new(get_stdlib_state)\n else\n case Cache.get(path) do\n nil ->\n Cache.new(get_stdlib_state)\n x ->\n %{ x | full_build?: false }\n end\n end\n end\n\n defp empty?(path) when is_binary(path) do\n case File.ls(path) do\n {:ok, []} ->\n true\n {:error, _} ->\n true\n _ ->\n false\n end\n end\n\n defp empty?(_) do\n true\n end\n\n @doc false\n def compile_std_lib() do\n compile_std_lib(Path.join([File.cwd!, \"priv\"]))\n end\n\n @doc false\n def compile_std_lib(output_path) do\n compiler_opts = build_compiler_options(%{std_lib: true, include_path: true, output: output_path})\n libs_path = Path.join([__DIR__, \"elixir_script\", \"prelude\", \"**\", \"*.ex\"])\n\n code = Path.wildcard(libs_path)\n |> Enum.filter(fn(path) ->\n !String.contains?(path, [\"v_dom.ex\", \"html.ex\"])\n end)\n |> Enum.map(&file_to_quoted\/1)\n\n ElixirScript.Translator.State.start_link(compiler_opts, [])\n\n code\n |> Enum.map(&update_quoted(&1))\n |> ModuleCollector.process_modules\n\n code = create_code(compiler_opts, ElixirScript.Translator.State.get)\n |> Enum.filter(fn({path, _}) -> !String.contains?(path, \"ElixirScript.Temp.js\") end)\n\n new_std_state = ElixirScript.Translator.State.serialize()\n ElixirScript.Translator.State.stop\n\n File.write!(File.cwd!() <> \"\/lib\/elixir_script\/translator\/stdlib_state.bin\", new_std_state)\n Output.out(libs_path, code, compiler_opts)\n end\n\n defp do_compile(opts, quoted_code_list, state, loaded_modules) do\n compiler_opts = build_compiler_options(opts)\n\n ElixirScript.Translator.State.start_link(compiler_opts, loaded_modules)\n ElixirScript.Translator.State.deserialize(state, loaded_modules)\n\n quoted_code_list\n |> Enum.map(&update_quoted(&1))\n |> ModuleCollector.process_modules\n\n code = create_code(compiler_opts, ElixirScript.Translator.State.get)\n new_state = ElixirScript.Translator.State.serialize()\n ElixirScript.Translator.State.stop\n\n { code, new_state }\n end\n\n defp build_compiler_options(opts) do\n default_options = Map.new\n |> Map.put(:include_path, false)\n |> Map.put(:root, nil)\n |> Map.put(:env, custom_env)\n |> Map.put(:import_standard_libs, true)\n |> Map.put(:core_path, \"Elixir\")\n |> Map.put(:full_build, false)\n |> Map.put(:output, nil)\n\n Map.merge(default_options, opts)\n end\n\n defp file_to_quoted(file) do\n file\n |> File.read!\n |> Code.string_to_quoted!\n end\n\n defp update_quoted(quoted) do\n Macro.prewalk(quoted, fn\n ({name, context, parms}) ->\n if context[:import] == Kernel do\n context = Keyword.update!(context, :import, fn(_) -> ElixirScript.Kernel end)\n end\n\n {name, context, parms}\n (x) ->\n x\n end)\n end\n\n @doc false\n def custom_env() do\n __using__([])\n __ENV__\n end\n\n defp create_code(compiler_opts, state) do\n\n parent = self\n\n Map.values(state.modules)\n |> Enum.reject(fn(ast) ->\n not ast.name in state.added_modules\n end)\n |> Enum.map(fn ast ->\n spawn_link fn ->\n env = ElixirScript.Translator.Env.module_env(ast.name, Utils.name_to_js_file_name(ast.name) <> \".js\", state.compiler_opts.env)\n\n module = case ast.type do\n :module ->\n ElixirScript.Translator.Module.make_module(ast.name, ast.body, env)\n :protocol ->\n ElixirScript.Translator.Protocol.make(ast.name, ast.functions, env)\n :protocol_implementation ->\n ElixirScript.Translator.Protocol.Implementation.make(ast.name, ast.impl_type, ast.body, env)\n end\n\n\n result = javascript_ast_to_code(module)\n\n send parent, { self, result }\n end\n end)\n |> Enum.map(fn pid ->\n receive do\n {^pid, result} -> result\n end\n end)\n end\n\n @doc false\n def update_protocols(compiler_output, compiler_opts) do\n Enum.reduce(compiler_output, %{}, fn\n {file, code}, state ->\n case String.split(file, \".DefImpl.\") do\n [protocol, impl] ->\n protocol = String.split(protocol, \"\/\") |> List.last |> String.to_atom\n impl = String.replace(impl, \".js\", \"\") |> String.to_atom\n Map.put(state, protocol, Map.get(state, protocol, []) ++ [impl])\n [_] ->\n state\n end\n _, state ->\n state\n end)\n |> do_make_defimpl(compiler_opts)\n end\n\n @doc false\n def update_protocols_in_path(compiler_output, compiler_opts, output_path) do\n Enum.reduce(compiler_output, %{}, fn {file, code}, state ->\n case String.split(file, \".DefImpl.\") do\n [protocol, _] ->\n protocol = String.split(protocol, \"\/\") |> List.last\n protocol_impls = find_protocols_implementations_in_path(output_path, protocol)\n protocol = String.to_atom(protocol)\n Map.put(state, protocol, Map.get(state, protocol, []) ++ protocol_impls)\n [_] ->\n state\n end\n end)\n |> do_make_defimpl(compiler_opts)\n end\n\n defp do_make_defimpl(protocols, compiler_opts) do\n Enum.map(protocols, fn {protocol, implementations} ->\n ElixirScript.Translator.Protocol.make_defimpl(protocol, Enum.uniq(implementations), compiler_opts)\n end)\n |> Enum.map(fn(module) ->\n javascript_ast_to_code(module)\n end)\n end\n\n defp find_protocols_implementations_in_path(path, protocol_prefix) do\n Path.join([path, protocol_prefix <> \".DefImpl*.js\"])\n |> Path.wildcard\n |> Enum.filter(fn path -> !String.ends_with?(path, \"DefImpl.js\") end)\n |> Enum.map(fn impl ->\n Path.basename(impl)\n |> String.split(\".DefImpl.\")\n |> List.last\n |> String.replace(\".js\", \"\")\n |> String.to_atom end)\n end\n\n @doc \"\"\"\n Copies the javascript that makes up the ElixirScript stdlib\n to the specified location\n \"\"\"\n def copy_stdlib_to_destination(destination) do\n Enum.each(Path.wildcard(Path.join([operating_path, \"*.js\"])), fn(path) ->\n base = Path.basename(path)\n File.cp!(path, Path.join([destination, base]))\n end)\n end\n\n defp javascript_ast_to_code(module) do\n path = Utils.name_to_js_file_name(module.name) <> \".js\"\n js_ast = Builder.program(module.body)\n\n js_code = js_ast\n |> prepare_js_ast\n |> Generator.generate\n\n { path, js_code }\n end\n\n defp prepare_js_ast(js_ast) do\n js_ast = case js_ast do\n modules when is_list(modules) ->\n modules\n |> Enum.reduce([], &(&2 ++ &1.body))\n |> Builder.program\n %ElixirScript.Translator.Group{ body: body } ->\n Builder.program(body)\n %ElixirScript.Translator.Empty{ } ->\n Builder.program([])\n _ ->\n js_ast\n end\n\n js_ast\n end\n\n #Gets path to js files whether the mix project is available\n #or when used as an escript\n defp operating_path do\n case @lib_path do\n nil ->\n try do\n Mix.Project.build_path <> \"\/lib\/elixir_script\/priv\"\n rescue\n UndefinedFunctionError ->\n split_path = Path.split(Application.app_dir(:elixirscript))\n replaced_path = List.delete_at(split_path, length(split_path) - 1)\n replaced_path = List.delete_at(replaced_path, length(replaced_path) - 1)\n Path.join(replaced_path)\n end\n lib_path ->\n lib_path\n end\n end\n\nend\n","old_contents":"defmodule ElixirScript do\n alias ESTree.Tools.Builder\n alias ESTree.Tools.Generator\n alias ElixirScript.Translator.Utils\n alias ElixirScript.Translator.ModuleCollector\n alias ElixirScript.Compiler.Cache\n alias ElixirScript.Compiler.Output\n require Logger\n\n @moduledoc \"\"\"\n Translates Elixir into JavaScript.\n\n All compile functions return a list of\n transpiled javascript code or a tuple consisting of\n the file name for the code and the transpiled javascript code.\n\n All compile functions also take an optional opts parameter\n that controls transpiler output.\n\n Available options are:\n * `:include_path` - a boolean controlling whether to return just the JavaScript code\n or a tuple of the file name and the JavaScript code\n * `:root` - a binary path prepended to the path of the standard lib imports if needed\n * `:env` - a Macro.env struct to use. This is most useful when using macros. Make sure that the\n env has the macros imported or required.\n * `:core_path` - The es6 import path used to import the elixirscript core.\n When using this option, the Elixir.js file is not exported\n * `:full_build` - For compile_path, tells the compiler to perform a full build instead of incremental one\n * `:output` - option to tell compiler how to output data\n * `nil`: Return as list\n * `:stdout`: Write to standard out\n * `path (string)`: Write to specified path\n \"\"\"\n\n defmacro __using__(_) do\n quote do\n import Kernel, only: [&&: 2, use: 2, use: 1]\n import ElixirScript.Kernel\n require ElixirScript.JS, as: JS\n require ElixirScript.Html, as: Html\n require ElixirScript.VDom, as: VDom\n end\n end\n\n # This is the serialized state of the ElixirScript.State module containing references to the standard library\n @external_resource stdlib_state_path = Path.join([__DIR__, \"elixir_script\", \"translator\", \"stdlib_state.bin\"])\n @stdlib_state File.read(stdlib_state_path)\n @lib_path Application.get_env(:elixir_script, :lib_path)\n\n @doc \"\"\"\n Compiles the given Elixir code string\n \"\"\"\n @spec compile(binary, Map.t) :: [binary | {binary, binary} | :ok]\n def compile(elixir_code, opts \\\\ %{}) do\n elixir_code\n |> Code.string_to_quoted!\n |> compile_quoted(opts)\n end\n\n @doc \"\"\"\n Compiles the given Elixir code in quoted form\n \"\"\"\n @spec compile_quoted(Macro.t, Map.t) :: [binary | {binary, binary} | :ok]\n def compile_quoted(quoted, opts \\\\ %{}) do\n { code, _ } = do_compile(opts, [quoted], get_stdlib_state, [])\n Output.out(quoted, code, build_compiler_options(opts))\n end\n\n @doc \"\"\"\n Compiles the elixir files found at the given path\n \"\"\"\n @spec compile_path(binary, Map.t) :: [binary | {binary, binary} | :ok]\n def compile_path(path, opts \\\\ %{}) do\n\n {expanded_path, loaded_modules} = case File.dir?(path) do\n true ->\n process_path(path)\n false ->\n {[path], []}\n end\n\n opts = build_compiler_options(opts)\n\n compiler_cache = get_compiler_cache(path, opts)\n\n new_file_stats = Cache.build_file_stats(expanded_path)\n\n changed_files = Cache.get_changed_files(compiler_cache.input_files, new_file_stats)\n |> Enum.map(fn {file, state} -> file end)\n\n code = Enum.map(changed_files, &file_to_quoted\/1)\n\n { code, new_state } = do_compile(opts, code, compiler_cache.state, loaded_modules)\n compiler_cache = %{compiler_cache | input_files: new_file_stats, state: new_state }\n\n Cache.write(path, compiler_cache)\n Output.out(path, code, opts)\n end\n\n defp process_path(path) do\n path = Path.join(path, \"**\/*.{ex,exs,exjs}\") |> Path.wildcard\n {exjs, ex} = Enum.partition(path, fn(x) ->\n case Path.extname(x) do\n ext when ext in [\".ex\", \".exs\"] ->\n false\n _ ->\n true\n end\n end)\n\n ex = Enum.flat_map(ex, fn(x) -> Code.load_file(x) end)\n |> Enum.map(fn({module, _}) -> module end)\n\n {exjs, ex}\n end\n\n defp get_stdlib_state() do\n case @stdlib_state do\n {:ok, data} ->\n data\n {:error, _} ->\n raise RuntimeError, message: \"Standard Library state not found. Please run `mix std_lib`\"\n end\n end\n\n defp get_compiler_cache(path, opts) do\n if Map.get(opts, :full_build) or empty?(opts.output) do\n Cache.delete(path)\n Cache.new(get_stdlib_state)\n else\n case Cache.get(path) do\n nil ->\n Cache.new(get_stdlib_state)\n x ->\n %{ x | full_build?: false }\n end\n end\n end\n\n defp empty?(path) when is_binary(path) do\n case File.ls(path) do\n {:ok, []} ->\n true\n {:error, _} ->\n true\n _ ->\n false\n end\n end\n\n defp empty?(_) do\n true\n end\n\n @doc false\n def compile_std_lib() do\n compile_std_lib(Path.join([File.cwd!, \"priv\"]))\n end\n\n @doc false\n def compile_std_lib(output_path) do\n compiler_opts = build_compiler_options(%{std_lib: true, include_path: true, output: output_path})\n libs_path = Path.join([__DIR__, \"elixir_script\", \"prelude\", \"**\", \"*.ex\"])\n\n code = Path.wildcard(libs_path)\n |> Enum.filter(fn(path) ->\n !String.contains?(path, [\"v_dom.ex\", \"html.ex\"])\n end)\n |> Enum.map(&file_to_quoted\/1)\n\n ElixirScript.Translator.State.start_link(compiler_opts, [])\n\n code\n |> Enum.map(&update_quoted(&1))\n |> ModuleCollector.process_modules\n\n code = create_code(compiler_opts, ElixirScript.Translator.State.get)\n |> Enum.filter(fn({path, _}) -> !String.contains?(path, \"ElixirScript.Temp.js\") end)\n\n new_std_state = ElixirScript.Translator.State.serialize()\n ElixirScript.Translator.State.stop\n\n File.write!(File.cwd!() <> \"\/lib\/elixir_script\/translator\/stdlib_state.bin\", new_std_state)\n Output.out(libs_path, code, compiler_opts)\n end\n\n defp do_compile(opts, quoted_code_list, state, loaded_modules) do\n compiler_opts = build_compiler_options(opts)\n\n ElixirScript.Translator.State.start_link(compiler_opts, loaded_modules)\n ElixirScript.Translator.State.deserialize(state, loaded_modules)\n\n quoted_code_list\n |> Enum.map(&update_quoted(&1))\n |> ModuleCollector.process_modules\n\n code = create_code(compiler_opts, ElixirScript.Translator.State.get)\n new_state = ElixirScript.Translator.State.serialize()\n ElixirScript.Translator.State.stop\n\n { code, new_state }\n end\n\n defp build_compiler_options(opts) do\n default_options = Map.new\n |> Map.put(:include_path, false)\n |> Map.put(:root, nil)\n |> Map.put(:env, custom_env)\n |> Map.put(:import_standard_libs, true)\n |> Map.put(:core_path, \"Elixir\")\n |> Map.put(:full_build, false)\n |> Map.put(:output, nil)\n\n Map.merge(default_options, opts)\n end\n\n defp file_to_quoted(file) do\n file\n |> File.read!\n |> Code.string_to_quoted!\n end\n\n defp update_quoted(quoted) do\n Macro.prewalk(quoted, fn\n ({name, context, parms}) ->\n if context[:import] == Kernel do\n context = Keyword.update!(context, :import, fn(_) -> ElixirScript.Kernel end)\n end\n\n {name, context, parms}\n (x) ->\n x\n end)\n end\n\n @doc false\n def custom_env() do\n __using__([])\n __ENV__\n end\n\n defp create_code(compiler_opts, state) do\n\n parent = self\n\n Map.values(state.modules)\n |> Enum.reject(fn(ast) ->\n not ast.name in state.added_modules\n end)\n |> Enum.map(fn ast ->\n spawn_link fn ->\n env = ElixirScript.Translator.Env.module_env(ast.name, Utils.name_to_js_file_name(ast.name) <> \".js\", state.compiler_opts.env)\n\n module = case ast.type do\n :module ->\n ElixirScript.Translator.Module.make_module(ast.name, ast.body, env)\n :protocol ->\n ElixirScript.Translator.Protocol.make(ast.name, ast.functions, env)\n :protocol_implementation ->\n ElixirScript.Translator.Protocol.Implementation.make(ast.name, ast.impl_type, ast.body, env)\n end\n\n\n result = javascript_ast_to_code(module)\n\n send parent, { self, result }\n end\n end)\n |> Enum.map(fn pid ->\n receive do\n {^pid, result} -> result\n end\n end)\n end\n\n @doc false\n def update_protocols(compiler_output, compiler_opts) do\n Enum.reduce(compiler_output, %{}, fn\n {file, code}, state ->\n case String.split(file, \".DefImpl.\") do\n [protocol, impl] ->\n protocol = String.split(protocol, \"\/\") |> List.last |> String.to_atom\n impl = String.replace(impl, \".js\", \"\") |> String.to_atom\n Map.put(state, protocol, Map.get(state, protocol, []) ++ [impl])\n [_] ->\n state\n end\n _, state ->\n state\n end)\n |> do_make_defimpl(compiler_opts)\n end\n\n @doc false\n def update_protocols_in_path(compiler_output, compiler_opts, output_path) do\n Enum.reduce(compiler_output, %{}, fn {file, code}, state ->\n case String.split(file, \".DefImpl.\") do\n [protocol, _] ->\n protocol = String.split(protocol, \"\/\") |> List.last\n protocol_impls = find_protocols_implementations_in_path(output_path, protocol)\n protocol = String.to_atom(protocol)\n Map.put(state, protocol, Map.get(state, protocol, []) ++ protocol_impls)\n [_] ->\n state\n end\n end)\n |> do_make_defimpl(compiler_opts)\n end\n\n defp do_make_defimpl(protocols, compiler_opts) do\n Enum.map(protocols, fn {protocol, implementations} ->\n ElixirScript.Translator.Protocol.make_defimpl(protocol, Enum.uniq(implementations), compiler_opts)\n end)\n |> Enum.map(fn(module) ->\n javascript_ast_to_code(module)\n end)\n end\n\n defp find_protocols_implementations_in_path(path, protocol_prefix) do\n Path.join([path, protocol_prefix <> \".DefImpl*.js\"])\n |> Path.wildcard\n |> Enum.filter(fn path -> !String.ends_with?(path, \"DefImpl.js\") end)\n |> Enum.map(fn impl ->\n Path.basename(impl)\n |> String.split(\".DefImpl.\")\n |> List.last\n |> String.replace(\".js\", \"\")\n |> String.to_atom end)\n end\n\n @doc \"\"\"\n Copies the javascript that makes up the ElixirScript stdlib\n to the specified location\n \"\"\"\n def copy_stdlib_to_destination(destination) do\n Enum.each(Path.wildcard(Path.join([operating_path, \"*.js\"])), fn(path) ->\n base = Path.basename(path)\n File.cp!(path, Path.join([destination, base]))\n end)\n end\n\n defp javascript_ast_to_code(module) do\n path = Utils.name_to_js_file_name(module.name) <> \".js\"\n js_ast = Builder.program(module.body)\n\n js_code = js_ast\n |> prepare_js_ast\n |> Generator.generate\n\n { path, js_code }\n end\n\n defp prepare_js_ast(js_ast) do\n js_ast = case js_ast do\n modules when is_list(modules) ->\n modules\n |> Enum.reduce([], &(&2 ++ &1.body))\n |> Builder.program\n %ElixirScript.Translator.Group{ body: body } ->\n Builder.program(body)\n %ElixirScript.Translator.Empty{ } ->\n Builder.program([])\n _ ->\n js_ast\n end\n\n js_ast\n end\n\n #Gets path to js files whether the mix project is available\n #or when used as an escript\n defp operating_path do\n case @lib_path do\n nil ->\n try do\n Mix.Project.build_path <> \"\/lib\/elixir_script\/priv\"\n rescue\n UndefinedFunctionError ->\n split_path = Path.split(Application.app_dir(:elixirscript))\n replaced_path = List.delete_at(split_path, length(split_path) - 1)\n replaced_path = List.delete_at(replaced_path, length(replaced_path) - 1)\n Path.join(replaced_path)\n end\n lib_path ->\n lib_path\n end\n end\n\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"a5bdf127d9054fe927c2e4acb569a3a7d79af363","subject":"Expand column responses after coalescing them","message":"Expand column responses after coalescing them\n","repos":"rozap\/exsoda","old_file":"lib\/exsoda\/writer.ex","new_file":"lib\/exsoda\/writer.ex","new_contents":"defmodule Exsoda.Writer do\n alias Exsoda.Http\n\n defmodule CreateColumn do\n defstruct name: nil,\n dataTypeName: nil,\n fourfour: nil,\n properties: %{} # description, fieldName\n end\n\n defmodule CreateColumns do\n defstruct columns: []\n end\n\n defmodule CreateView do\n defstruct name: nil,\n properties: %{}\n end\n\n defmodule UpdateView do\n defstruct fourfour: nil,\n properties: %{}\n end\n\n defmodule Upsert do\n defstruct fourfour: nil,\n mode: nil,\n rows: []\n end\n\n defmodule Write do\n defstruct opts: %{},\n operations: []\n end\n\n defmodule Publish do\n defstruct fourfour: nil\n end\n\n defmodule Permission do\n defstruct fourfour: nil,\n mode: nil\n end\n\n defmodule PrepareDraftForImport do\n defstruct fourfour: nil\n end\n\n def write(options \\\\ []) do\n %Write{\n opts: Http.options(options)\n }\n end\n\n def create(%Write{} = w, name, properties) do\n operation = %CreateView{name: name, properties: properties}\n %{ w | operations: [operation | w.operations] }\n end\n\n def update(%Write{} = w, fourfour, properties) do\n operation = %UpdateView{fourfour: fourfour, properties: properties}\n %{ w | operations: [operation | w.operations] }\n end\n\n def create_column(%Write{} = w, fourfour, name, type, properties) do\n operation = %CreateColumn{name: name, dataTypeName: type, fourfour: fourfour, properties: properties}\n %{ w | operations: [operation | w.operations] }\n end\n\n # a row looks like: {fieldName: value, fieldName: value}\n def upsert(%Write{} = w, fourfour, rows) do\n operation = %Upsert{fourfour: fourfour, rows: rows, mode: :append}\n %{ w | operations: [operation | w.operations] }\n end\n\n def replace(%Write{} = w, fourfour, rows) do\n operation = %Upsert{fourfour: fourfour, rows: rows, mode: :replace}\n %{ w | operations: [operation | w.operations] }\n end\n\n def publish(%Write{} = w, fourfour) do\n operation = %Publish{fourfour: fourfour}\n %{ w | operations: [operation | w.operations]}\n end\n\n def permission(%Write{} = w, fourfour, :public) do\n operation = %Permission{fourfour: fourfour, mode: \"public.read\"}\n %{ w | operations: [operation | w.operations]}\n end\n\n def permission(%Write{} = w, fourfour, :private) do\n operation = %Permission{fourfour: fourfour, mode: \"private\"}\n %{ w | operations: [operation | w.operations]}\n end\n\n def prepare_draft_for_import(%Write{} = w, fourfour) do\n operation = %PrepareDraftForImport{fourfour: fourfour}\n %{ w | operations: [operation | w.operations]}\n end\n\n defp do_run(%CreateView{} = cv, w) do\n data = Map.merge(cv.properties, %{name: cv.name})\n with {:ok, json} <- Poison.encode(data) do\n Http.post(\"\/views.json\", w, json)\n end\n end\n\n defp do_run(%UpdateView{} = uv, w) do\n with {:ok, json} <- Poison.encode(uv.properties) do\n Http.put(\"\/views\/#{uv.fourfour}.json\", w, json)\n end\n end\n\n defp do_run(%CreateColumn{} = cc, w) do\n data = merge_column(cc)\n\n with {:ok, json} <- Poison.encode(data) do\n Http.post(\"\/views\/#{cc.fourfour}\/columns\", w, json)\n end\n end\n\n defp do_run(%CreateColumns{columns: ccs}, w) do\n data = %{\"columns\" => Enum.map(ccs, &merge_column\/1)}\n\n with {:ok, json} <- Poison.encode(data) do\n case Http.post(\"\/views\/#{hd(ccs).fourfour}\/columns?method=multiCreate\", w, json) do\n {:ok, list} -> Enum.map(list, fn result -> {:ok, result} end)\n {:error, _} = err -> Enum.map(ccs, fn _ -> err end)\n end\n end\n end\n\n defp do_run(%Upsert{rows: rows} = u, w) when is_list(rows) do\n with {:ok, json} <- Poison.encode(rows) do\n case u.mode do\n :append -> Http.post(\"\/id\/#{u.fourfour}.json\", w, json)\n :replace -> Http.put(\"\/id\/#{u.fourfour}.json\", w, json)\n end\n end\n end\n defp do_run(%Upsert{rows: rows} = u, w) do\n with_commas = Stream.transform(rows, false, fn\n row, false -> {[Poison.encode!(row)], true}\n row, true -> {[\",\\n\" <> Poison.encode!(row)], true}\n end)\n\n json_stream = Stream.concat(\n [\"[\"],\n with_commas\n )\n |> Stream.concat([\"]\"])\n\n case u.mode do\n :append -> Http.post(\"\/id\/#{u.fourfour}.json\", w, {:stream, json_stream})\n :replace -> Http.put(\"\/id\/#{u.fourfour}.json\", w, {:stream, json_stream})\n end\n end\n\n defp do_run(%Publish{fourfour: fourfour}, w) do\n with {:ok, json} <- Poison.encode(%{}) do\n Http.post(\"\/views\/#{fourfour}\/publication\", w, json)\n end\n end\n\n defp do_run(%Permission{fourfour: fourfour, mode: mode}, w) do\n with {:ok, json} <- Poison.encode(mode) do\n Http.put(\"\/views\/#{fourfour}?method=setPermission\", w, json)\n end\n end\n\n defp do_run(%PrepareDraftForImport{fourfour: fourfour}, w) do\n with {:ok, json} <- Poison.encode(%{}) do\n Http.patch(\"\/views\/#{fourfour}?method=prepareDraftForImport\", w, json)\n end\n end\n\n defp merge_column(%CreateColumn{} = cc), do: Map.take(cc, [:dataTypeName, :name]) |> Map.merge(cc.properties)\n\n defp collapse_column_create([]), do: []\n defp collapse_column_create([%CreateColumn{fourfour: fourfour} = cc | ccs]) do\n {ccs, remainder} = Enum.split_while(ccs, fn\n %CreateColumn{fourfour: ^fourfour} -> true\n _ -> false\n end)\n [%CreateColumns{columns: [cc | ccs]} | collapse_column_create(remainder)]\n end\n defp collapse_column_create([h | t]), do: [h | collapse_column_create(t)]\n\n def run(%Write{} = w) do\n w.operations\n |> Enum.reverse\n |> collapse_column_create\n |> Enum.reduce_while([], fn op, acc ->\n Enum.reduce_while(List.wrap(do_run(op, w)), {:cont, acc}, fn result, {_, acc} ->\n case result do\n {:error, _} = err -> {:halt, {:halt, [err | acc]}}\n {:ok, _} = ok -> {:cont, {:cont, [ok | acc]}}\n end\n end)\n end)\n |> Enum.reverse\n end\nend\n","old_contents":"defmodule Exsoda.Writer do\n alias Exsoda.Http\n\n defmodule CreateColumn do\n defstruct name: nil,\n dataTypeName: nil,\n fourfour: nil,\n properties: %{} # description, fieldName\n end\n\n defmodule CreateColumns do\n defstruct columns: []\n end\n\n defmodule CreateView do\n defstruct name: nil,\n properties: %{}\n end\n\n defmodule UpdateView do\n defstruct fourfour: nil,\n properties: %{}\n end\n\n defmodule Upsert do\n defstruct fourfour: nil,\n mode: nil,\n rows: []\n end\n\n defmodule Write do\n defstruct opts: %{},\n operations: []\n end\n\n defmodule Publish do\n defstruct fourfour: nil\n end\n\n defmodule Permission do\n defstruct fourfour: nil,\n mode: nil\n end\n\n defmodule PrepareDraftForImport do\n defstruct fourfour: nil\n end\n\n def write(options \\\\ []) do\n %Write{\n opts: Http.options(options)\n }\n end\n\n def create(%Write{} = w, name, properties) do\n operation = %CreateView{name: name, properties: properties}\n %{ w | operations: [operation | w.operations] }\n end\n\n def update(%Write{} = w, fourfour, properties) do\n operation = %UpdateView{fourfour: fourfour, properties: properties}\n %{ w | operations: [operation | w.operations] }\n end\n\n def create_column(%Write{} = w, fourfour, name, type, properties) do\n operation = %CreateColumn{name: name, dataTypeName: type, fourfour: fourfour, properties: properties}\n %{ w | operations: [operation | w.operations] }\n end\n\n # a row looks like: {fieldName: value, fieldName: value}\n def upsert(%Write{} = w, fourfour, rows) do\n operation = %Upsert{fourfour: fourfour, rows: rows, mode: :append}\n %{ w | operations: [operation | w.operations] }\n end\n\n def replace(%Write{} = w, fourfour, rows) do\n operation = %Upsert{fourfour: fourfour, rows: rows, mode: :replace}\n %{ w | operations: [operation | w.operations] }\n end\n\n def publish(%Write{} = w, fourfour) do\n operation = %Publish{fourfour: fourfour}\n %{ w | operations: [operation | w.operations]}\n end\n\n def permission(%Write{} = w, fourfour, :public) do\n operation = %Permission{fourfour: fourfour, mode: \"public.read\"}\n %{ w | operations: [operation | w.operations]}\n end\n\n def permission(%Write{} = w, fourfour, :private) do\n operation = %Permission{fourfour: fourfour, mode: \"private\"}\n %{ w | operations: [operation | w.operations]}\n end\n\n def prepare_draft_for_import(%Write{} = w, fourfour) do\n operation = %PrepareDraftForImport{fourfour: fourfour}\n %{ w | operations: [operation | w.operations]}\n end\n\n defp do_run(%CreateView{} = cv, w) do\n data = Map.merge(cv.properties, %{name: cv.name})\n with {:ok, json} <- Poison.encode(data) do\n Http.post(\"\/views.json\", w, json)\n end\n end\n\n defp do_run(%UpdateView{} = uv, w) do\n with {:ok, json} <- Poison.encode(uv.properties) do\n Http.put(\"\/views\/#{uv.fourfour}.json\", w, json)\n end\n end\n\n defp do_run(%CreateColumn{} = cc, w) do\n data = merge_column(cc)\n\n with {:ok, json} <- Poison.encode(data) do\n Http.post(\"\/views\/#{cc.fourfour}\/columns\", w, json)\n end\n end\n\n defp do_run(%CreateColumns{columns: ccs}, w) do\n data = %{\"columns\" => Enum.map(ccs, &merge_column\/1)}\n\n with {:ok, json} <- Poison.encode(data) do\n Http.post(\"\/views\/#{hd(ccs).fourfour}\/columns?method=multiCreate\", w, json)\n end\n end\n\n defp do_run(%Upsert{rows: rows} = u, w) when is_list(rows) do\n with {:ok, json} <- Poison.encode(rows) do\n case u.mode do\n :append -> Http.post(\"\/id\/#{u.fourfour}.json\", w, json)\n :replace -> Http.put(\"\/id\/#{u.fourfour}.json\", w, json)\n end\n end\n end\n defp do_run(%Upsert{rows: rows} = u, w) do\n with_commas = Stream.transform(rows, false, fn\n row, false -> {[Poison.encode!(row)], true}\n row, true -> {[\",\\n\" <> Poison.encode!(row)], true}\n end)\n\n json_stream = Stream.concat(\n [\"[\"],\n with_commas\n )\n |> Stream.concat([\"]\"])\n\n case u.mode do\n :append -> Http.post(\"\/id\/#{u.fourfour}.json\", w, {:stream, json_stream})\n :replace -> Http.put(\"\/id\/#{u.fourfour}.json\", w, {:stream, json_stream})\n end\n end\n\n defp do_run(%Publish{fourfour: fourfour}, w) do\n with {:ok, json} <- Poison.encode(%{}) do\n Http.post(\"\/views\/#{fourfour}\/publication\", w, json)\n end\n end\n\n defp do_run(%Permission{fourfour: fourfour, mode: mode}, w) do\n with {:ok, json} <- Poison.encode(mode) do\n Http.put(\"\/views\/#{fourfour}?method=setPermission\", w, json)\n end\n end\n\n defp do_run(%PrepareDraftForImport{fourfour: fourfour}, w) do\n with {:ok, json} <- Poison.encode(%{}) do\n Http.patch(\"\/views\/#{fourfour}?method=prepareDraftForImport\", w, json)\n end\n end\n\n defp merge_column(%CreateColumn{} = cc), do: Map.take(cc, [:dataTypeName, :name]) |> Map.merge(cc.properties)\n\n defp collapse_column_create([]), do: []\n defp collapse_column_create([%CreateColumn{fourfour: fourfour} = cc | ccs]) do\n {ccs, remainder} = Enum.split_while(ccs, fn\n %CreateColumn{fourfour: ^fourfour} -> true\n _ -> false\n end)\n [%CreateColumns{columns: [cc | ccs]} | collapse_column_create(remainder)]\n end\n defp collapse_column_create([h | t]), do: [h | collapse_column_create(t)]\n\n def run(%Write{} = w) do\n Enum.reduce_while(collapse_column_create(Enum.reverse(w.operations)), [], fn op, acc ->\n case do_run(op, w) do\n {:error, _} = err -> {:halt, [err | acc]}\n {:ok, _} = ok -> {:cont, [ok | acc]}\n end\n end)\n |> Enum.reverse\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"9d3cb7159af61587aa2f4ed47fe7a7a996ec1323","subject":"Replace metadata with module attributes","message":"Replace metadata with module attributes\n","repos":"nekova\/metainvestigator","old_file":"lib\/metainspector.ex","new_file":"lib\/metainspector.ex","new_contents":"defmodule MetaInspector.Meta do\n defstruct og_title: [], og_type: [], og_url: [], og_image: []\n @type t :: %__MODULE__{og_title: list, og_type: list, og_url: list, og_image: list}\nend\n\ndefmodule MetaInspector do\n defstruct status: nil, title: nil, best_title: nil, best_image: nil, meta: %{}\n @type t :: %__MODULE__{status: integer, title: String.t, best_title: String.t, best_image: String.t, meta: MetaInspector.Meta.t}\n\n @metadata [\"title\", \"type\", \"image\", \"url\"]\n\n @spec new(String.t) :: __MODULE__.t\n def new(url) do\n case HTTPoison.get(url) do\n {:ok, %HTTPoison.Response{status_code: 200, body: body}} ->\n {:ok, fetch(body)}\n {:error, %HTTPoison.Error{reason: reason}} ->\n {:error, reason}\n end\n end\n\n def new!(url) do\n case new(url) do\n {:ok, response} ->\n response\n {:error, reason} ->\n reason\n end\n end\n\n def fetch(body) do\n body = body |> to_utf8\n %__MODULE__{status: 200, title: title(body), best_title: best_title(body), best_image: best_image(body), meta: meta(body)}\n end\n\n def status(response) do\n response.status_code\n end\n\n @spec title(String.t) :: String.t\n def title(body) do\n body\n |> Floki.find(\"head title\")\n |> Floki.text\n end\n\n @spec best_title(String.t) :: String.t\n def best_title(body) do\n og_title = og_title(body) |> to_string\n title = title(body)\n case og_title >= title do\n true -> og_title\n false -> title\n end\n end\n\n @spec best_image(String.t) :: String.t\n def best_image(body) do\n og_image(body)\n |> List.first\n end\n\n for meta <- @metadata do\n def unquote(:\"og_#{meta}\")(body), do: meta_tag_by(body, unquote(meta))\n end\n\n @spec meta_tag_by(String.t, String.t) :: [String.t]\n defp meta_tag_by(body, attribute) when attribute in @metadata do\n Floki.find(body, \"[property=\\\"og:#{attribute}\\\"]\")\n |> Floki.attribute(\"content\")\n end\n\n defp meta(body) do\n %__MODULE__.Meta{og_title: og_title(body), og_type: og_type(body), og_url: og_url(body), og_image: og_image(body)}\n end\n\n def to_utf8(body) do\n case String.valid?(body) do\n true -> body\n false -> decode_to_utf8(body)\n end\n end\n\n def decode_to_utf8(body) do\n Mbcs.start\n str = :erlang.binary_to_list(body)\n \"#{Mbcs.decode!(str, :cp932, return: :list)}\"\n end\nend\n","old_contents":"defmodule MetaInspector.Meta do\n defstruct og_title: [], og_type: [], og_url: [], og_image: []\n @type t :: %__MODULE__{og_title: list, og_type: list, og_url: list, og_image: list}\nend\n\ndefmodule MetaInspector do\n defstruct status: nil, title: nil, best_title: nil, best_image: nil, meta: %{}\n @type t :: %__MODULE__{status: integer, title: String.t, best_title: String.t, best_image: String.t, meta: MetaInspector.Meta.t}\n\n @spec new(String.t) :: __MODULE__.t\n def new(url) do\n case HTTPoison.get(url) do\n {:ok, %HTTPoison.Response{status_code: 200, body: body}} ->\n {:ok, fetch(body)}\n {:error, %HTTPoison.Error{reason: reason}} ->\n {:error, reason}\n end\n end\n\n def new!(url) do\n case new(url) do\n {:ok, response} ->\n response\n {:error, reason} ->\n reason\n end\n end\n\n def fetch(body) do\n body = body |> to_utf8\n %__MODULE__{status: 200, title: title(body), best_title: best_title(body), best_image: best_image(body), meta: meta(body)}\n end\n\n def status(response) do\n response.status_code\n end\n\n @spec title(String.t) :: String.t\n def title(body) do\n body\n |> Floki.find(\"head title\")\n |> Floki.text\n end\n\n @spec best_title(String.t) :: String.t\n def best_title(body) do\n og_title = og_title(body) |> to_string\n title = title(body)\n case og_title >= title do\n true -> og_title\n false -> title\n end\n end\n\n @spec best_image(String.t) :: String.t\n def best_image(body) do\n og_image(body)\n |> List.first\n end\n\n metadata = [\"title\", \"type\", \"image\", \"url\"]\n for meta <- metadata do\n def unquote(:\"og_#{meta}\")(body), do: meta_tag_by(body, unquote(meta))\n end\n\n @spec meta_tag_by(String.t, String.t) :: [String.t]\n defp meta_tag_by(body, attribute) when attribute in [\"title\", \"image\", \"type\", \"url\"] do\n Floki.find(body, \"[property=\\\"og:#{attribute}\\\"]\")\n |> Floki.attribute(\"content\")\n end\n\n defp meta(body) do\n %__MODULE__.Meta{og_title: og_title(body), og_type: og_type(body), og_url: og_url(body), og_image: og_image(body)}\n end\n\n def to_utf8(body) do\n case String.valid?(body) do\n true -> body\n false -> decode_to_utf8(body)\n end\n end\n\n def decode_to_utf8(body) do\n Mbcs.start\n str = :erlang.binary_to_list(body)\n \"#{Mbcs.decode!(str, :cp932, return: :list)}\"\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"f3a0a52c10bfaf9f1491927eff7a77dabdb7ce92","subject":"Add examples for disjoint? and subset?","message":"Add examples for disjoint? and subset?\n","repos":"joshprice\/elixir,pedrosnk\/elixir,kimshrier\/elixir,michalmuskala\/elixir,antipax\/elixir,lexmag\/elixir,kelvinst\/elixir,pedrosnk\/elixir,kelvinst\/elixir,gfvcastro\/elixir,ggcampinho\/elixir,beedub\/elixir,antipax\/elixir,ggcampinho\/elixir,beedub\/elixir,lexmag\/elixir,gfvcastro\/elixir,elixir-lang\/elixir,kimshrier\/elixir","old_file":"lib\/elixir\/lib\/set.ex","new_file":"lib\/elixir\/lib\/set.ex","new_contents":"defmodule Set do\n # The ordered record contains a single bucket.\n @ordered_threshold 8\n\n defrecordp :ordered,\n size: 0,\n bucket: []\n\n # The bucketed record contains a series of buckets.\n @expand_load 5\n @contract_load 2\n @node_bitmap 0b111\n @node_shift 3\n @node_size 8\n @node_template :erlang.make_tuple(@node_size, [])\n\n defrecordp :trie,\n size: 0,\n depth: 0,\n expand_on: @node_size * @expand_load,\n contract_on: @contract_load,\n root: @node_template\n\n import Bitwise\n\n @compile { :inline, bucket_hash: 1, bucket_index: 1, bucket_nth_index: 2, bucket_next: 1 }\n\n @doc \"\"\"\n Creates a new empty set.\n \"\"\"\n def new() do\n ordered()\n end\n\n @doc \"\"\"\n Creates a new set from the given enumerable.\n\n ## Examples\n\n iex> Set.new [1, 1, 2, 3, 3] |> Set.to_list\n [1,2,3]\n\n \"\"\"\n def new(members) do\n Enum.reduce members, ordered(), fn member, set ->\n put(set, member)\n end\n end\n\n @doc \"\"\"\n Returns a set combining the two input sets.\n\n ## Examples\n\n iex> Set.union(Set.new([1,2]), Set.new([2,3,4])) |> Set.to_list\n [1,2,3,4]\n\n \"\"\"\n def union(set1, set2) when is_record(set1, Set) and is_record(set2, Set) and elem(set1, 1) < elem(set2, 1) do\n set_fold set1, set2, fn v1, acc ->\n put(acc, v1)\n end\n end\n\n def union(set1, set2) when is_record(set1, Set) and is_record(set2, Set) do\n set_fold set2, set1, fn v, acc ->\n put(acc, v)\n end\n end\n\n @doc \"\"\"\n Returns a set containing only members in common between the two input sets.\n\n ## Examples\n\n iex> Set.intersection(Set.new([1,2]), Set.new([2,3,4])) |> Set.to_list\n [2]\n\n \"\"\"\n def intersection(set1, set2) when is_record(set1, Set) and is_record(set2, Set) do\n set_intersect(set1, set2)\n end\n\n @doc \"\"\"\n Returns a set that is the first set without members of the second set.\n\n ## Examples\n\n iex> Set.difference(Set.new([1,2]), Set.new([2,3,4])) |> Set.to_list\n [1]\n\n \"\"\"\n def difference(set1, set2) when is_record(set1, Set) and is_record(set2, Set) do\n set_difference(set1, set2)\n end\n\n @doc \"\"\"\n Checks if the set has the given value.\n \"\"\"\n def member?(set, member) when is_record(set, Set) do\n case set_get(set, member) do\n ^member -> true\n _ -> false\n end\n end\n\n @doc \"\"\"\n Returns an empty set.\n \"\"\"\n def empty(_) do\n ordered()\n end\n\n @doc \"\"\"\n Returns the set size.\n \"\"\"\n def size(set) do\n elem(set, 1)\n end\n\n @doc \"\"\"\n Converts a set to a list.\n \"\"\"\n def to_list(ordered(bucket: bucket)) do\n bucket\n end\n\n def to_list(set) do\n set_fold(set, [], [&1|&2]) |> :lists.reverse\n end\n\n @doc \"\"\"\n Puts the given value into the set if it does not already contain it.\n \"\"\"\n def put(set, member) do\n { set, _ } = set_put(set, { :put, member })\n set\n end\n\n @doc \"\"\"\n Deletes a value from the set.\n \"\"\"\n def delete(set, member) do\n { set, _, _ } = set_delete(set, member)\n set\n end\n\n @doc \"\"\"\n Checks if two sets are equal\n \"\"\"\n def equal?(set1, set2) do\n size = elem(set1, 1)\n case elem(set2, 1) do\n ^size ->\n set_equal?(set1, set2)\n _ ->\n false\n end\n end\n\n @doc \"\"\"\n Checks if set1's members are all contained in set2.\n\n ## Examples\n\n iex> Set.subset?(Set.new([1, 2]), Set.new([1, 2, 3]))\n true\n iex> Set.subset?(Set.new([1, 2, 3]), Set.new([1, 2]))\n false\n \"\"\"\n def subset?(set1, set2) do\n set_equal?(set1, set2)\n end\n\n @doc \"\"\"\n Checks if set1 and set2 have no members in common.\n\n ## Examples\n\n iex> Set.disjoint?(Set.new([1, 2]), Set.new([3, 4]))\n true\n iex> Set.disjoint?(Set.new([1, 2]), Set.new([2, 3]))\n false\n\n \"\"\"\n def disjoint?(set1, set2) do\n set_disjoint?(set1, set2)\n end\n\n def reduce(ordered(bucket: bucket), acc, fun) do\n :lists.foldl(fun, acc, bucket)\n end\n\n def reduce(trie() = set, acc, fun) do\n set_fold(set, acc, fun)\n end\n\n ## Set-wide functions\n\n defp set_intersect(ordered(bucket: bucket1), ordered(bucket: bucket2)) do\n { new_bucket, size } = bucket_intersect(bucket1, bucket2)\n ordered(bucket: new_bucket, size: size)\n end\n\n defp set_intersect(trie(size: size1) = set1, trie(size: size2) = set2) when size1 > size2 do\n set_intersect(set2, set1)\n end\n\n defp set_intersect(trie(root: root, depth: depth, size: size) = set1, set2) do\n set_fold set2, ordered(), fn m, acc ->\n if member?(set1, m) do\n put acc, m\n else\n acc\n end\n end\n end\n\n defp set_difference(ordered(bucket: bucket1, size: size), ordered(bucket: bucket2)) do\n { new, count } = bucket_difference(bucket1, bucket2)\n ordered(bucket: new, size: size - count)\n end\n\n defp set_difference(trie(size: size1) = set1, set2) do\n set_fold set2, set1, fn m, acc ->\n delete(acc, m)\n end\n end\n\n defp set_put(ordered(size: @ordered_threshold, bucket: bucket), member) do\n root = node_relocate(bucket, 0)\n set_put(trie(size: @ordered_threshold, root: root), member)\n end\n\n defp set_put(ordered(size: size, bucket: bucket) = set, member) do\n { new, count } = bucket_put(bucket, member)\n { ordered(set, size: size + count, bucket: new), count }\n end\n\n defp set_put(trie(root: root, depth: depth, size: size, expand_on: size, contract_on: contract_on) = set, member) do\n root = node_expand(root, depth, depth + 1)\n set = trie(set, root: root, depth: depth + 1,\n expand_on: size * @node_size, contract_on: contract_on * @node_size)\n set_put(set, member)\n end\n\n defp set_put(trie(root: root, size: size, depth: depth) = set, { :put, member }) do\n pos = bucket_hash(member)\n { root, count } = node_put(root, depth, pos, {:put, member})\n { trie(set, size: size + count, root: root), count }\n end\n\n defp set_get(ordered(bucket: bucket), member) do\n bucket_get(bucket, member)\n end\n\n defp set_get(trie(root: root, depth: depth), member) do\n bucket_get(node_bucket(root, depth, bucket_hash(member)), member)\n end\n\n defp set_delete(ordered(bucket: bucket, size: size) = set, member) do\n case bucket_delete(bucket, member) do\n { _, value, 0 } ->\n { set, value, 0 }\n { new_bucket, value, -1 } ->\n { ordered(set, size: size - 1, bucket: new_bucket), value, -1 }\n end\n end\n\n defp set_delete(trie(root: root, size: size, depth: depth) = set, member) do\n pos = bucket_hash(member)\n case node_delete(root, depth, pos, member) do\n { _, value, 0 } ->\n { set, value, 0 }\n { root, value, -1 } ->\n { if depth > 0 and trie(set, :contract_on) == size do\n root = node_contract(root, depth)\n trie(set,\n root: root,\n size: size - 1,\n depth: depth - 1,\n contract_on: div(size, @node_size),\n expand_on: div(trie(set, :expand_on), @node_size))\n else\n trie(set, size: size - 1, root: root)\n end, member, -1 }\n end\n end\n\n defp set_equal?(set1, set2) do\n try do\n reduce(set1, true, fn member, acc ->\n case member?(set2, member) do\n true -> acc\n _ -> throw(:error)\n end\n end)\n catch\n :error -> false\n end\n end\n\n defp set_disjoint?(set1, set2) do\n try do\n reduce(set1, true, fn member, acc ->\n case member?(set2, member) do\n false -> acc\n _ -> throw(:error)\n end\n end)\n catch\n :error -> false\n end\n end\n\n defp set_fold(ordered(bucket: bucket), acc, fun) do\n bucket_fold(bucket, acc, fun)\n end\n\n defp set_fold(trie(root: root, depth: depth), acc, fun) do\n node_fold(root, depth, acc, fun, @node_size)\n end\n\n ## Bucket helpers\n\n defp bucket_intersect([m | bucket1], [m | bucket2]) do\n { new, count } = bucket_intersect(bucket1, bucket2)\n { [m | new], count + 1 }\n end\n\n defp bucket_intersect([m1 | _] = bucket1, [m2 | bucket2]) when m1 > m2 do\n bucket_intersect(bucket1, bucket2)\n end\n\n defp bucket_intersect([_ | bucket1], bucket2) do\n bucket_intersect(bucket1, bucket2)\n end\n\n defp bucket_intersect([], _) do\n { [], 0 }\n end\n\n defp bucket_intersect(_, []) do\n { [], 0 }\n end\n\n defp bucket_difference([m | bucket1], [m | bucket2]) do\n { new, count } = bucket_difference(bucket1, bucket2)\n { new, count + 1 }\n end\n\n defp bucket_difference([m1 | bucket1], [m2 | _] = bucket2) when m1 < m2 do\n { new, count } = bucket_difference(bucket1, bucket2)\n { [m1 | new], count }\n end\n\n defp bucket_difference([m1 | _]= bucket1, [m2 | bucket2]) when m1 > m2 do\n bucket_difference(bucket1, bucket2)\n end\n\n defp bucket_difference([], bucket) do\n { [], 0 }\n end\n\n defp bucket_difference(bucket, []) do\n { bucket, 0 }\n end\n\n defp bucket_put([m|_]=bucket, { :put, member }) when m > member do\n { [member|bucket], 1 }\n end\n\n defp bucket_put([member|bucket], { :put, member }) do\n { [member|bucket], 0 }\n end\n\n defp bucket_put([e|bucket], member) do\n { rest, count } = bucket_put(bucket, member)\n { [e|rest], count }\n end\n\n defp bucket_put([], { :put, member }) do\n { [member], 1 }\n end\n\n defp bucket_put!([m|_]=bucket, member) when m > member, do: [member|bucket]\n defp bucket_put!([member|bucket], member), do: [member|bucket]\n defp bucket_put!([e|bucket], member), do: [e|bucket_put!(bucket, member)]\n defp bucket_put!([], member), do: [member]\n\n # Deletes a key from the bucket\n defp bucket_delete([m,_|_]=bucket, member) when m > member do\n { bucket, nil, 0 }\n end\n\n defp bucket_delete([member|bucket], member) do\n { bucket, member, -1 }\n end\n\n defp bucket_delete([e|bucket], member) do\n { rest, value, count } = bucket_delete(bucket, member)\n { [e|rest], value, count }\n end\n\n defp bucket_delete([], _member) do\n { [], nil, 0 }\n end\n\n defp bucket_get([member|bucket], member) do\n member\n end\n\n defp bucket_get([member|bucket], candidate) when candidate > member do\n bucket_get(bucket, candidate)\n end\n\n defp bucket_get(_, member) do\n nil\n end\n\n defp bucket_fold(bucket, acc, fun) do\n :lists.foldl(fun, acc, bucket)\n end\n\n defp bucket_hash(key) do\n :erlang.phash2(key)\n end\n\n defp bucket_nth_index(hash, n) do\n (hash >>> (@node_shift * n)) &&& @node_bitmap\n end\n\n defp bucket_index(hash) do\n hash &&& @node_bitmap\n end\n\n defp bucket_next(hash) do\n hash >>> @node_shift\n end\n\n # Node helpers\n\n # Gets a bucket from the node\n defp node_bucket(node, 0, hash) do\n elem(node, bucket_index(hash))\n end\n\n defp node_bucket(node, depth, hash) do\n child = elem(node, bucket_index(hash))\n node_bucket(child, depth - 1, bucket_next(hash))\n end\n\n defp node_put(node, 0, hash, member) do\n pos = bucket_index(hash)\n { new, count } = bucket_put(elem(node, pos), member)\n { set_elem(node, pos, new), count }\n end\n\n defp node_put(node, depth, hash, member) do\n pos = bucket_index(hash)\n { new, count } = node_put(elem(node, pos), depth - 1, bucket_next(hash), member)\n { set_elem(node, pos, new), count }\n end\n\n # Deletes a key from the bucket\n defp node_delete(node, 0, hash, member) do\n pos = bucket_index(hash)\n case bucket_delete(elem(node, pos), member) do\n { _, value, 0 } -> { node, value, 0 }\n { new, value, -1 } -> { set_elem(node, pos, new), value, -1 }\n end\n end\n\n defp node_delete(node, depth, hash, member) do\n pos = bucket_index(hash)\n case node_delete(elem(node, pos), depth - 1, bucket_next(hash), member) do\n { _, value, 0 } -> { node, value, 0 }\n { new, value, -1 } -> { set_elem(node, pos, new), value, -1 }\n end\n end\n\n defp node_fold(bucket, -1, acc, fun, _) do\n bucket_fold(bucket, acc, fun)\n end\n\n defp node_fold(node, depth, acc, fun, count) when count >= 1 do\n acc = node_fold(:erlang.element(count, node), depth - 1, acc, fun, @node_size)\n node_fold(node, depth, acc, fun, count - 1)\n end\n\n defp node_fold(_node, _, acc, _fun, 0) do\n acc\n end\n\n defp node_relocate(node \/\/ @node_template, bucket, n) do\n :lists.foldl fn member, acc ->\n pos = member |> bucket_hash() |> bucket_nth_index(n)\n set_elem(acc, pos, bucket_put!(elem(acc, pos), member))\n end, node, bucket\n end\n\n # Node resizing\n defp node_expand({ b1, b2, b3, b4, b5, b6, b7, b8 }, 0, n) do\n { node_relocate(b1, n), node_relocate(b2, n), node_relocate(b3, n),\n node_relocate(b4, n), node_relocate(b5, n), node_relocate(b6, n),\n node_relocate(b7, n), node_relocate(b8, n) }\n end\n\n defp node_expand({ b1, b2, b3, b4, b5, b6, b7, b8 }, depth, n) do\n depth = depth - 1\n { node_expand(b1, depth, n), node_expand(b2, depth, n), node_expand(b3, depth, n),\n node_expand(b4, depth, n), node_expand(b5, depth, n), node_expand(b6, depth, n),\n node_expand(b7, depth, n), node_expand(b8, depth, n) }\n end\n\n defp node_contract({ b1, b2, b3, b4, b5, b6, b7, b8 }, depth) when depth > 0 do\n depth = depth - 1\n { node_contract(b1, depth), node_contract(b2, depth), node_contract(b3, depth),\n node_contract(b4, depth), node_contract(b5, depth), node_contract(b6, depth),\n node_contract(b7, depth), node_contract(b8, depth) }\n end\n\n defp node_contract({ b1, b2, b3, b4, b5, b6, b7, b8 }, 0) do\n b1 |> each_contract(b2) |> each_contract(b3) |> each_contract(b4)\n |> each_contract(b5) |> each_contract(b6) |> each_contract(b7)\n |> each_contract(b8)\n end\n\n defp each_contract([m1|acc], [m2|_]=bucket) when m1 < m2, do: [m1|each_contract(acc, bucket)]\n defp each_contract(acc, [m|bucket]), do: [m|each_contract(acc, bucket)]\n defp each_contract([], bucket), do: bucket\n defp each_contract(acc, []), do: acc\n\nend\n\ndefimpl Enumerable, for: Set do\n def reduce(set, acc, fun), do: Set.reduce(set, acc, fun)\n def member?(set, v), do: Set.member?(set, v)\n def member?(_set, _), do: false\n def count(set), do: Set.size(set)\nend\n\ndefimpl Binary.Inspect, for: Set do\n import Kernel, except: [inspect: 2]\n\n def inspect(set, opts) do\n \"#Set<\" <> Kernel.inspect(Set.to_list(set), opts) <> \">\"\n end\nend","old_contents":"defmodule Set do\n # The ordered record contains a single bucket.\n @ordered_threshold 8\n\n defrecordp :ordered,\n size: 0,\n bucket: []\n\n # The bucketed record contains a series of buckets.\n @expand_load 5\n @contract_load 2\n @node_bitmap 0b111\n @node_shift 3\n @node_size 8\n @node_template :erlang.make_tuple(@node_size, [])\n\n defrecordp :trie,\n size: 0,\n depth: 0,\n expand_on: @node_size * @expand_load,\n contract_on: @contract_load,\n root: @node_template\n\n import Bitwise\n\n @compile { :inline, bucket_hash: 1, bucket_index: 1, bucket_nth_index: 2, bucket_next: 1 }\n\n @doc \"\"\"\n Creates a new empty set.\n \"\"\"\n def new() do\n ordered()\n end\n\n @doc \"\"\"\n Creates a new set from the given enumerable.\n\n ## Examples\n\n iex> Set.new [1, 1, 2, 3, 3] |> Set.to_list\n [1,2,3]\n\n \"\"\"\n def new(members) do\n Enum.reduce members, ordered(), fn member, set ->\n put(set, member)\n end\n end\n\n @doc \"\"\"\n Returns a set combining the two input sets.\n\n ## Examples\n\n iex> Set.union(Set.new([1,2]), Set.new([2,3,4])) |> Set.to_list\n [1,2,3,4]\n\n \"\"\"\n def union(set1, set2) when is_record(set1, Set) and is_record(set2, Set) and elem(set1, 1) < elem(set2, 1) do\n set_fold set1, set2, fn v1, acc ->\n put(acc, v1)\n end\n end\n\n def union(set1, set2) when is_record(set1, Set) and is_record(set2, Set) do\n set_fold set2, set1, fn v, acc ->\n put(acc, v)\n end\n end\n\n @doc \"\"\"\n Returns a set containing only members in common between the two input sets.\n\n ## Examples\n\n iex> Set.intersection(Set.new([1,2]), Set.new([2,3,4])) |> Set.to_list\n [2]\n\n \"\"\"\n def intersection(set1, set2) when is_record(set1, Set) and is_record(set2, Set) do\n set_intersect(set1, set2)\n end\n\n @doc \"\"\"\n Returns a set that is the first set without members of the second set.\n\n ## Examples\n\n iex> Set.difference(Set.new([1,2]), Set.new([2,3,4])) |> Set.to_list\n [1]\n\n \"\"\"\n def difference(set1, set2) when is_record(set1, Set) and is_record(set2, Set) do\n set_difference(set1, set2)\n end\n\n @doc \"\"\"\n Checks if the set has the given value.\n \"\"\"\n def member?(set, member) when is_record(set, Set) do\n case set_get(set, member) do\n ^member -> true\n _ -> false\n end\n end\n\n @doc \"\"\"\n Returns an empty set.\n \"\"\"\n def empty(_) do\n ordered()\n end\n\n @doc \"\"\"\n Returns the set size.\n \"\"\"\n def size(set) do\n elem(set, 1)\n end\n\n @doc \"\"\"\n Converts a set to a list.\n \"\"\"\n def to_list(ordered(bucket: bucket)) do\n bucket\n end\n\n def to_list(set) do\n set_fold(set, [], [&1|&2]) |> :lists.reverse\n end\n\n @doc \"\"\"\n Puts the given value into the set if it does not already contain it.\n \"\"\"\n def put(set, member) do\n { set, _ } = set_put(set, { :put, member })\n set\n end\n\n @doc \"\"\"\n Deletes a value from the set.\n \"\"\"\n def delete(set, member) do\n { set, _, _ } = set_delete(set, member)\n set\n end\n\n @doc \"\"\"\n Checks if two sets are equal\n \"\"\"\n def equal?(set1, set2) do\n size = elem(set1, 1)\n case elem(set2, 1) do\n ^size ->\n set_equal?(set1, set2)\n _ ->\n false\n end\n end\n\n @doc \"\"\"\n Checks if set1's members are all contained in set2.\n \"\"\"\n def subset?(set1, set2) do\n set_equal?(set1, set2)\n end\n\n @doc \"\"\"\n Checks if set1 and set2 have no members in common.\n \"\"\"\n def disjoint?(set1, set2) do\n set_disjoint?(set1, set2)\n end\n\n def reduce(ordered(bucket: bucket), acc, fun) do\n :lists.foldl(fun, acc, bucket)\n end\n\n def reduce(trie() = set, acc, fun) do\n set_fold(set, acc, fun)\n end\n\n ## Set-wide functions\n\n defp set_intersect(ordered(bucket: bucket1), ordered(bucket: bucket2)) do\n { new_bucket, size } = bucket_intersect(bucket1, bucket2)\n ordered(bucket: new_bucket, size: size)\n end\n\n defp set_intersect(trie(size: size1) = set1, trie(size: size2) = set2) when size1 > size2 do\n set_intersect(set2, set1)\n end\n\n defp set_intersect(trie(root: root, depth: depth, size: size) = set1, set2) do\n set_fold set2, ordered(), fn m, acc ->\n if member?(set1, m) do\n put acc, m\n else\n acc\n end\n end\n end\n\n defp set_difference(ordered(bucket: bucket1, size: size), ordered(bucket: bucket2)) do\n { new, count } = bucket_difference(bucket1, bucket2)\n ordered(bucket: new, size: size - count)\n end\n\n defp set_difference(trie(size: size1) = set1, set2) do\n set_fold set2, set1, fn m, acc ->\n delete(acc, m)\n end\n end\n\n defp set_put(ordered(size: @ordered_threshold, bucket: bucket), member) do\n root = node_relocate(bucket, 0)\n set_put(trie(size: @ordered_threshold, root: root), member)\n end\n\n defp set_put(ordered(size: size, bucket: bucket) = set, member) do\n { new, count } = bucket_put(bucket, member)\n { ordered(set, size: size + count, bucket: new), count }\n end\n\n defp set_put(trie(root: root, depth: depth, size: size, expand_on: size, contract_on: contract_on) = set, member) do\n root = node_expand(root, depth, depth + 1)\n set = trie(set, root: root, depth: depth + 1,\n expand_on: size * @node_size, contract_on: contract_on * @node_size)\n set_put(set, member)\n end\n\n defp set_put(trie(root: root, size: size, depth: depth) = set, { :put, member }) do\n pos = bucket_hash(member)\n { root, count } = node_put(root, depth, pos, {:put, member})\n { trie(set, size: size + count, root: root), count }\n end\n\n defp set_get(ordered(bucket: bucket), member) do\n bucket_get(bucket, member)\n end\n\n defp set_get(trie(root: root, depth: depth), member) do\n bucket_get(node_bucket(root, depth, bucket_hash(member)), member)\n end\n\n defp set_delete(ordered(bucket: bucket, size: size) = set, member) do\n case bucket_delete(bucket, member) do\n { _, value, 0 } ->\n { set, value, 0 }\n { new_bucket, value, -1 } ->\n { ordered(set, size: size - 1, bucket: new_bucket), value, -1 }\n end\n end\n\n defp set_delete(trie(root: root, size: size, depth: depth) = set, member) do\n pos = bucket_hash(member)\n case node_delete(root, depth, pos, member) do\n { _, value, 0 } ->\n { set, value, 0 }\n { root, value, -1 } ->\n { if depth > 0 and trie(set, :contract_on) == size do\n root = node_contract(root, depth)\n trie(set,\n root: root,\n size: size - 1,\n depth: depth - 1,\n contract_on: div(size, @node_size),\n expand_on: div(trie(set, :expand_on), @node_size))\n else\n trie(set, size: size - 1, root: root)\n end, member, -1 }\n end\n end\n\n defp set_equal?(set1, set2) do\n try do\n reduce(set1, true, fn member, acc ->\n case member?(set2, member) do\n true -> acc\n _ -> throw(:error)\n end\n end)\n catch\n :error -> false\n end\n end\n\n defp set_disjoint?(set1, set2) do\n try do\n reduce(set1, true, fn member, acc ->\n case member?(set2, member) do\n false -> acc\n _ -> throw(:error)\n end\n end)\n catch\n :error -> false\n end\n end\n\n defp set_fold(ordered(bucket: bucket), acc, fun) do\n bucket_fold(bucket, acc, fun)\n end\n\n defp set_fold(trie(root: root, depth: depth), acc, fun) do\n node_fold(root, depth, acc, fun, @node_size)\n end\n\n ## Bucket helpers\n\n defp bucket_intersect([m | bucket1], [m | bucket2]) do\n { new, count } = bucket_intersect(bucket1, bucket2)\n { [m | new], count + 1 }\n end\n\n defp bucket_intersect([m1 | _] = bucket1, [m2 | bucket2]) when m1 > m2 do\n bucket_intersect(bucket1, bucket2)\n end\n\n defp bucket_intersect([_ | bucket1], bucket2) do\n bucket_intersect(bucket1, bucket2)\n end\n\n defp bucket_intersect([], _) do\n { [], 0 }\n end\n\n defp bucket_intersect(_, []) do\n { [], 0 }\n end\n\n defp bucket_difference([m | bucket1], [m | bucket2]) do\n { new, count } = bucket_difference(bucket1, bucket2)\n { new, count + 1 }\n end\n\n defp bucket_difference([m1 | bucket1], [m2 | _] = bucket2) when m1 < m2 do\n { new, count } = bucket_difference(bucket1, bucket2)\n { [m1 | new], count }\n end\n\n defp bucket_difference([m1 | _]= bucket1, [m2 | bucket2]) when m1 > m2 do\n bucket_difference(bucket1, bucket2)\n end\n\n defp bucket_difference([], bucket) do\n { [], 0 }\n end\n\n defp bucket_difference(bucket, []) do\n { bucket, 0 }\n end\n\n defp bucket_put([m|_]=bucket, { :put, member }) when m > member do\n { [member|bucket], 1 }\n end\n\n defp bucket_put([member|bucket], { :put, member }) do\n { [member|bucket], 0 }\n end\n\n defp bucket_put([e|bucket], member) do\n { rest, count } = bucket_put(bucket, member)\n { [e|rest], count }\n end\n\n defp bucket_put([], { :put, member }) do\n { [member], 1 }\n end\n\n defp bucket_put!([m|_]=bucket, member) when m > member, do: [member|bucket]\n defp bucket_put!([member|bucket], member), do: [member|bucket]\n defp bucket_put!([e|bucket], member), do: [e|bucket_put!(bucket, member)]\n defp bucket_put!([], member), do: [member]\n\n # Deletes a key from the bucket\n defp bucket_delete([m,_|_]=bucket, member) when m > member do\n { bucket, nil, 0 }\n end\n\n defp bucket_delete([member|bucket], member) do\n { bucket, member, -1 }\n end\n\n defp bucket_delete([e|bucket], member) do\n { rest, value, count } = bucket_delete(bucket, member)\n { [e|rest], value, count }\n end\n\n defp bucket_delete([], _member) do\n { [], nil, 0 }\n end\n\n defp bucket_get([member|bucket], member) do\n member\n end\n\n defp bucket_get([member|bucket], candidate) when candidate > member do\n bucket_get(bucket, candidate)\n end\n\n defp bucket_get(_, member) do\n nil\n end\n\n defp bucket_fold(bucket, acc, fun) do\n :lists.foldl(fun, acc, bucket)\n end\n\n defp bucket_hash(key) do\n :erlang.phash2(key)\n end\n\n defp bucket_nth_index(hash, n) do\n (hash >>> (@node_shift * n)) &&& @node_bitmap\n end\n\n defp bucket_index(hash) do\n hash &&& @node_bitmap\n end\n\n defp bucket_next(hash) do\n hash >>> @node_shift\n end\n\n # Node helpers\n\n # Gets a bucket from the node\n defp node_bucket(node, 0, hash) do\n elem(node, bucket_index(hash))\n end\n\n defp node_bucket(node, depth, hash) do\n child = elem(node, bucket_index(hash))\n node_bucket(child, depth - 1, bucket_next(hash))\n end\n\n defp node_put(node, 0, hash, member) do\n pos = bucket_index(hash)\n { new, count } = bucket_put(elem(node, pos), member)\n { set_elem(node, pos, new), count }\n end\n\n defp node_put(node, depth, hash, member) do\n pos = bucket_index(hash)\n { new, count } = node_put(elem(node, pos), depth - 1, bucket_next(hash), member)\n { set_elem(node, pos, new), count }\n end\n\n # Deletes a key from the bucket\n defp node_delete(node, 0, hash, member) do\n pos = bucket_index(hash)\n case bucket_delete(elem(node, pos), member) do\n { _, value, 0 } -> { node, value, 0 }\n { new, value, -1 } -> { set_elem(node, pos, new), value, -1 }\n end\n end\n\n defp node_delete(node, depth, hash, member) do\n pos = bucket_index(hash)\n case node_delete(elem(node, pos), depth - 1, bucket_next(hash), member) do\n { _, value, 0 } -> { node, value, 0 }\n { new, value, -1 } -> { set_elem(node, pos, new), value, -1 }\n end\n end\n\n defp node_fold(bucket, -1, acc, fun, _) do\n bucket_fold(bucket, acc, fun)\n end\n\n defp node_fold(node, depth, acc, fun, count) when count >= 1 do\n acc = node_fold(:erlang.element(count, node), depth - 1, acc, fun, @node_size)\n node_fold(node, depth, acc, fun, count - 1)\n end\n\n defp node_fold(_node, _, acc, _fun, 0) do\n acc\n end\n\n defp node_relocate(node \/\/ @node_template, bucket, n) do\n :lists.foldl fn member, acc ->\n pos = member |> bucket_hash() |> bucket_nth_index(n)\n set_elem(acc, pos, bucket_put!(elem(acc, pos), member))\n end, node, bucket\n end\n\n # Node resizing\n defp node_expand({ b1, b2, b3, b4, b5, b6, b7, b8 }, 0, n) do\n { node_relocate(b1, n), node_relocate(b2, n), node_relocate(b3, n),\n node_relocate(b4, n), node_relocate(b5, n), node_relocate(b6, n),\n node_relocate(b7, n), node_relocate(b8, n) }\n end\n\n defp node_expand({ b1, b2, b3, b4, b5, b6, b7, b8 }, depth, n) do\n depth = depth - 1\n { node_expand(b1, depth, n), node_expand(b2, depth, n), node_expand(b3, depth, n),\n node_expand(b4, depth, n), node_expand(b5, depth, n), node_expand(b6, depth, n),\n node_expand(b7, depth, n), node_expand(b8, depth, n) }\n end\n\n defp node_contract({ b1, b2, b3, b4, b5, b6, b7, b8 }, depth) when depth > 0 do\n depth = depth - 1\n { node_contract(b1, depth), node_contract(b2, depth), node_contract(b3, depth),\n node_contract(b4, depth), node_contract(b5, depth), node_contract(b6, depth),\n node_contract(b7, depth), node_contract(b8, depth) }\n end\n\n defp node_contract({ b1, b2, b3, b4, b5, b6, b7, b8 }, 0) do\n b1 |> each_contract(b2) |> each_contract(b3) |> each_contract(b4)\n |> each_contract(b5) |> each_contract(b6) |> each_contract(b7)\n |> each_contract(b8)\n end\n\n defp each_contract([m1|acc], [m2|_]=bucket) when m1 < m2, do: [m1|each_contract(acc, bucket)]\n defp each_contract(acc, [m|bucket]), do: [m|each_contract(acc, bucket)]\n defp each_contract([], bucket), do: bucket\n defp each_contract(acc, []), do: acc\n\nend\n\ndefimpl Enumerable, for: Set do\n def reduce(set, acc, fun), do: Set.reduce(set, acc, fun)\n def member?(set, v), do: Set.member?(set, v)\n def member?(_set, _), do: false\n def count(set), do: Set.size(set)\nend\n\ndefimpl Binary.Inspect, for: Set do\n import Kernel, except: [inspect: 2]\n\n def inspect(set, opts) do\n \"#Set<\" <> Kernel.inspect(Set.to_list(set), opts) <> \">\"\n end\nend","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"1a8e430ab926cc9808c1277471b267939a7228a2","subject":"Add output for mix load task.","message":"Add output for mix load task.\n","repos":"supernintendo\/moongate,supernintendo\/moongate,supernintendo\/moongate,supernintendo\/moongate,supernintendo\/moongate","old_file":"lib\/mix\/tasks\/load.ex","new_file":"lib\/mix\/tasks\/load.ex","new_contents":"defmodule Mix.Tasks.Moongate.Load do\n @shortdoc \"Load a world.\"\n use Mix.Task\n\n def run(args = []) do\n IO.puts(\n IO.chardata_to_string(\n IO.ANSI.format_fragment(\n [:red, \"Please provide a world name.\" <> IO.ANSI.reset], true)))\n IO.puts \"\"\n IO.puts world_list\n end\n\n def run(args) do\n defaults = %{\n db: \"localhost\/moongate\",\n db_user: {\"moongate\", \"moongate\"}\n }\n world = hd(args)\n {:ok, config} = Peon.from_file(\"priv\/worlds\/#{world}\/moongate.peon\")\n prepared = defaults |> Map.merge(config)\n {username, password} = prepared.db_user\n result = \"#{world}\\n#{username}:#{password}@#{prepared.db}\"\n {:ok, file} = File.open(\"user\", [:write])\n IO.binwrite(file, result)\n Mix.Tasks.Clean.run([])\n\n IO.puts(\n IO.chardata_to_string(\n [\"Loaded world \"] ++\n IO.ANSI.format_fragment(\n [:blue, \"#{world}\" <> IO.ANSI.reset <> \".\"], true)))\n end\n\n defp world_list do\n IO.chardata_to_string([\"The worlds you can load are: \"] ++\n IO.ANSI.format_fragment(\n [:cyan, \"#{world_dirs}\" <> IO.ANSI.reset], true))\n end\n\n defp world_dirs do\n {:ok, ls} = File.ls(\"priv\/worlds\")\n ls\n |> Enum.filter(&(File.dir?(\"priv\/worlds\/#{&1}\")))\n |> Enum.join(\" \")\n end\nend\n","old_contents":"defmodule Mix.Tasks.Moongate.Load do\n @shortdoc \"Load a world.\"\n use Mix.Task\n\n def run(args = []) do\n IO.puts(\n IO.chardata_to_string(\n IO.ANSI.format_fragment(\n [:red, \"Please provide a world name.\" <> IO.ANSI.reset], true)))\n IO.puts \"\"\n IO.puts world_list\n end\n\n def run(args) do\n defaults = %{\n db: \"localhost\/moongate\",\n db_user: {\"moongate\", \"moongate\"}\n }\n world = hd(args)\n {:ok, config} = Peon.from_file(\"priv\/worlds\/#{world}\/moongate.peon\")\n prepared = defaults |> Map.merge(config)\n {username, password} = prepared.db_user\n result = \"#{world}\\n#{username}:#{password}@#{prepared.db}\"\n {:ok, file} = File.open(\"user\", [:write])\n IO.binwrite(file, result)\n Mix.Tasks.Clean.run([])\n end\n\n defp world_list do\n IO.chardata_to_string([\"The worlds you can load are: \"] ++\n IO.ANSI.format_fragment(\n [:cyan, \"#{world_dirs}\" <> IO.ANSI.reset], true))\n end\n\n defp world_dirs do\n {:ok, ls} = File.ls(\"priv\/worlds\")\n ls\n |> Enum.filter(&(File.dir?(\"priv\/worlds\/#{&1}\")))\n |> Enum.join(\" \")\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"365749971674b2cc7650a28d034109edddc93478","subject":"Typo fix in live_reload patterns","message":"Typo fix in live_reload patterns\n","repos":"hashrocket\/tilex,hashrocket\/tilex,hashrocket\/tilex","old_file":"config\/dev.exs","new_file":"config\/dev.exs","new_contents":"use Mix.Config\n\n# For development, we disable any cache and enable\n# debugging and code reloading.\n#\n# The watchers configuration can be used to run external\n# watchers to your application. For example, we use it\n# with brunch.io to recompile .js and .css sources.\nconfig :tilex, TilexWeb.Endpoint,\n http: [port: System.get_env(\"PORT\") || 4000],\n debug_errors: true,\n code_reloader: true,\n check_origin: false,\n watchers: [\n node: [\n \"node_modules\/brunch\/bin\/brunch\",\n \"watch\",\n \"--stdin\",\n cd: Path.expand(\"..\/assets\", __DIR__)\n ]\n ]\n\n# Watch static and templates for browser reloading.\nconfig :tilex, TilexWeb.Endpoint,\n live_reload: [\n patterns: [\n ~r{priv\/static\/.*(js|css|png|jpeg|jpg|gif|svg)$},\n ~r{priv\/gettext\/.*(po)$},\n ~r{lib\/tilex_web\/views\/.*(ex)$},\n ~r{lib\/tilex_web\/templates\/.*(eex)$}\n ]\n ]\n\n# Do not include metadata nor timestamps in development logs\nconfig :logger, :console, format: \"[$level] $message\\n\"\n\n# Set a higher stacktrace during development. Avoid configuring such\n# in production as building large stacktraces may be expensive.\nconfig :phoenix, :stacktrace_depth, 20\n\n# Configure your database\nconfig :tilex, Tilex.Repo,\n adapter: Ecto.Adapters.Postgres,\n url: System.get_env(\"DATABASE_URL\"),\n database: \"tilex_dev\",\n hostname: \"localhost\",\n pool_size: 10\n\nconfig :tilex, :page_size, 50\nconfig :tilex, :cors_origin, \"http:\/\/localhost:3000\"\nconfig :tilex, :default_twitter_handle, \"hashrocket\"\n\nconfig :tilex, :request_tracking, true\n","old_contents":"use Mix.Config\n\n# For development, we disable any cache and enable\n# debugging and code reloading.\n#\n# The watchers configuration can be used to run external\n# watchers to your application. For example, we use it\n# with brunch.io to recompile .js and .css sources.\nconfig :tilex, TilexWeb.Endpoint,\n http: [port: System.get_env(\"PORT\") || 4000],\n debug_errors: true,\n code_reloader: true,\n check_origin: false,\n watchers: [\n node: [\n \"node_modules\/brunch\/bin\/brunch\",\n \"watch\",\n \"--stdin\",\n cd: Path.expand(\"..\/assets\", __DIR__)\n ]\n ]\n\n# Watch static and templates for browser reloading.\nconfig :tilex, TilexWeb.Endpoint,\n live_reload: [\n patterns: [\n ~r{priv\/static\/.*(js|css|png|jpeg|jpg|gif|svg)$},\n ~r{priv\/gettext\/.*(po)$},\n ~r{lib\/tilex\/web\/views\/.*(ex)$},\n ~r{lib\/tilex\/web\/templates\/.*(eex)$}\n ]\n ]\n\n# Do not include metadata nor timestamps in development logs\nconfig :logger, :console, format: \"[$level] $message\\n\"\n\n# Set a higher stacktrace during development. Avoid configuring such\n# in production as building large stacktraces may be expensive.\nconfig :phoenix, :stacktrace_depth, 20\n\n# Configure your database\nconfig :tilex, Tilex.Repo,\n adapter: Ecto.Adapters.Postgres,\n url: System.get_env(\"DATABASE_URL\"),\n database: \"tilex_dev\",\n hostname: \"localhost\",\n pool_size: 10\n\nconfig :tilex, :page_size, 50\nconfig :tilex, :cors_origin, \"http:\/\/localhost:3000\"\nconfig :tilex, :default_twitter_handle, \"hashrocket\"\n\nconfig :tilex, :request_tracking, true\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"5e1b711b22158c359c30fcdb6a746732ba0fdb50","subject":"Fix merge mistake","message":"Fix merge mistake\n","repos":"bors-ng\/bors-ng,bors-ng\/bors-ng,bors-ng\/bors-ng","old_file":"lib\/worker\/batcher.ex","new_file":"lib\/worker\/batcher.ex","new_contents":"require Logger\n\ndefmodule BorsNG.Worker.Batcher do\n @moduledoc \"\"\"\n A \"Batcher\" manages the backlog of batches a project has.\n It implements this set of rules:\n\n * When a patch is reviewed (\"r+'ed\"),\n it gets added to the project's non-running batch.\n If no such batch exists, it creates it.\n * After a short delay, if there is no currently running batch,\n the project's non-running batch is started.\n * The project's CI is occasionally polled,\n if a batch is currently running.\n After polling, the completion logic is run.\n * If a notification related to the underlying CI is received,\n the completion logic is run.\n * When the completion logic is run, the batch is either\n bisected (if it failed and there are two or more patches in it),\n blocked (if it failed and there is only one patch in it),\n pushed to master (if it passed),\n or (if there are still CI jobs with no results) it is left alone.\n \"\"\"\n\n use GenServer\n alias BorsNG.Worker.Batcher\n alias BorsNG.Database.Repo\n alias BorsNG.Database.Batch\n alias BorsNG.Database.BatchState\n alias BorsNG.Database.Patch\n alias BorsNG.Database.Project\n alias BorsNG.Database.Status\n alias BorsNG.Database.LinkPatchBatch\n alias BorsNG.GitHub\n alias BorsNG.Endpoint\n import BorsNG.Router.Helpers\n import Ecto.Query\n\n # Every half-hour\n @poll_period 30 * 60 * 1000\n\n # Public API\n\n def start_link(project_id) do\n GenServer.start_link(__MODULE__, project_id)\n end\n\n def reviewed(pid, patch_id, reviewer) when is_integer(patch_id) do\n GenServer.cast(pid, {:reviewed, patch_id, reviewer})\n end\n\n def set_priority(pid, patch_id, priority) when is_integer(patch_id) do\n GenServer.call(pid, {:set_priority, patch_id, priority})\n end\n\n def status(pid, stat) do\n GenServer.cast(pid, {:status, stat})\n end\n\n def poll(pid) do\n send(pid, {:poll, :once})\n end\n\n def cancel(pid, patch_id) when is_integer(patch_id) do\n GenServer.cast(pid, {:cancel, patch_id})\n end\n\n def cancel_all(pid) do\n GenServer.cast(pid, {:cancel_all})\n end\n\n # Server callbacks\n\n def init(project_id) do\n Process.send_after(\n self(),\n {:poll, :repeat},\n trunc(@poll_period * :rand.uniform(2) * 0.5))\n {:ok, project_id}\n end\n\n def handle_cast(args, project_id) do\n do_handle_cast(args, project_id)\n {:noreply, project_id}\n end\n\n def handle_call({:set_priority, patch_id, priority}, _from, project_id) do\n case Repo.get(Patch, patch_id) do\n nil -> nil\n %{priority: ^priority} -> nil\n patch ->\n patch.id\n |> Batch.all_for_patch(:incomplete)\n |> Repo.one()\n |> raise_batch_priority(priority)\n patch\n |> Patch.changeset(%{priority: priority})\n |> Repo.update!()\n end\n\n {:reply, :ok, project_id}\n end\n\n def do_handle_cast({:reviewed, patch_id, reviewer}, project_id) do\n case Repo.get(Patch.all(:awaiting_review), patch_id) do\n nil ->\n # Patch exists (otherwise, no ID), but is not awaiting review\n patch = Repo.get!(Patch, patch_id)\n project = Repo.get!(Project, patch.project_id)\n project\n |> get_repo_conn()\n |> send_message([patch], :already_running_review)\n patch ->\n # Patch exists and is awaiting review\n # This will cause the PR to start after the patch's scheduled delay\n project = Repo.get!(Project, patch.project_id)\n repo_conn = get_repo_conn(project)\n case patch_preflight(repo_conn, patch) do\n :ok ->\n {batch, is_new_batch} = get_new_batch(\n project_id,\n patch.into_branch,\n patch.priority\n )\n %LinkPatchBatch{}\n |> LinkPatchBatch.changeset(%{\n batch_id: batch.id,\n patch_id: patch.id,\n reviewer: reviewer})\n |> Repo.insert!()\n if is_new_batch do\n put_incomplete_on_hold(get_repo_conn(project), batch)\n end\n poll_after_delay(project)\n send_status(repo_conn, batch.id, [patch], :waiting)\n {:error, message} ->\n send_message(repo_conn, [patch], {:preflight, message})\n end\n end\n end\n\n def do_handle_cast({:status, {commit, identifier, state, url}}, project_id) do\n project_id\n |> Batch.get_assoc_by_commit(commit)\n |> Repo.all()\n |> case do\n [batch] ->\n batch.id\n |> Status.get_for_batch(identifier)\n |> Repo.update_all([set: [state: state, url: url, identifier: identifier]])\n if batch.state == :running do\n maybe_complete_batch(batch)\n end\n [] -> :ok\n end\n end\n\n def do_handle_cast({:cancel, patch_id}, _project_id) do\n patch_id\n |> Batch.all_for_patch(:incomplete)\n |> Repo.one()\n |> cancel_patch(patch_id)\n end\n\n def do_handle_cast({:cancel_all}, project_id) do\n waiting = project_id\n |> Batch.all_for_project(:waiting)\n |> Repo.all()\n Enum.each(waiting, &Repo.delete!\/1)\n running = project_id\n |> Batch.all_for_project(:running)\n |> Repo.all()\n Enum.map(running, &Batch.changeset(&1, %{state: :canceled}))\n |> Enum.each(&Repo.update!\/1)\n repo_conn = Project\n |> Repo.get!(project_id)\n |> get_repo_conn()\n Enum.each(running, &send_status(repo_conn, &1, :canceled))\n Enum.each(waiting, &send_status(repo_conn, &1, :canceled))\n end\n\n def handle_info({:poll, repetition}, project_id) do\n if repetition != :once do\n Process.send_after(self(), {:poll, repetition}, @poll_period)\n end\n case poll_(project_id) do\n :stop ->\n {:stop, :normal, project_id}\n :again ->\n {:noreply, project_id}\n end\n end\n\n # Private implementation details\n\n defp poll_(project_id) do\n project = Repo.get(Project, project_id)\n incomplete = project_id\n |> Batch.all_for_project(:incomplete)\n |> Repo.all()\n incomplete\n |> Enum.map(&%Batch{&1 | project: project})\n |> sort_batches()\n |> poll_batches()\n if Enum.empty?(incomplete) do\n :stop\n else\n :again\n end\n end\n\n def sort_batches(batches) do\n sorted_batches = Enum.sort_by(batches, &{\n -BatchState.numberize(&1.state),\n -&1.priority,\n &1.last_polled\n })\n new_batches = Enum.dedup_by(sorted_batches, &(&1.id))\n state = if new_batches != [] and hd(new_batches).state == :running do\n :running\n else\n Enum.each(new_batches, fn batch -> :waiting = batch.state end)\n :waiting\n end\n {state, new_batches}\n end\n\n defp poll_batches({:waiting, batches}) do\n case Enum.filter(batches, &Batch.next_poll_is_past\/1) do\n [] -> :ok\n [batch | _] -> start_waiting_batch(batch)\n end\n end\n\n defp poll_batches({:running, batches}) do\n batch = hd(batches)\n cond do\n Batch.timeout_is_past(batch) ->\n timeout_batch(batch)\n Batch.next_poll_is_past(batch) ->\n poll_running_batch(batch)\n true -> :ok\n end\n end\n\n defp start_waiting_batch(batch) do\n project = batch.project\n repo_conn = get_repo_conn(project)\n patch_links = Repo.all(LinkPatchBatch.from_batch(batch.id))\n |> Enum.sort_by(&(&1.patch.pr_xref))\n stmp = \"#{project.staging_branch}.tmp\"\n\n base = GitHub.get_branch!(\n repo_conn,\n batch.into_branch)\n tbase = %{\n tree: base.tree,\n commit: GitHub.synthesize_commit!(\n repo_conn,\n %{\n branch: stmp,\n tree: base.tree,\n parents: [base.commit],\n commit_message: \"[ci skip][skip ci][skip netlify]\",\n committer: nil})}\n do_merge_patch = fn %{patch: patch}, branch ->\n case branch do\n :conflict -> :conflict\n :canceled -> :canceled\n _ -> GitHub.merge_branch!(\n repo_conn,\n %{\n from: patch.commit,\n to: stmp,\n commit_message: \"[ci skip][skip ci][skip netlify] -bors-staging-tmp-#{patch.pr_xref}\"})\n end\n end\n\n merge = Enum.reduce(patch_links, tbase, do_merge_patch)\n {status, commit} = start_waiting_merged_batch(\n batch,\n patch_links,\n base,\n merge)\n now = DateTime.to_unix(DateTime.utc_now(), :second)\n\n GitHub.delete_branch!(repo_conn, stmp)\n send_status(repo_conn, batch, status)\n batch\n |> Batch.changeset(%{state: status, commit: commit, last_polled: now})\n |> Repo.update!()\n\n Project.ping!(batch.project_id)\n status\n end\n\n defp start_waiting_merged_batch(_batch, [], _, _) do\n {:canceled, nil}\n end\n\n defp start_waiting_merged_batch(batch, patch_links, base, %{tree: tree}) do\n repo_conn = get_repo_conn(batch.project)\n patches = Enum.map(patch_links, &(&1.patch))\n\n repo_conn\n |> Batcher.GetBorsToml.get(\"#{batch.project.staging_branch}.tmp\")\n |> case do\n {:ok, toml} ->\n parents = if toml.use_squash_merge do\n stmp = \"#{batch.project.staging_branch}.tmp2\"\n GitHub.force_push!(repo_conn, base.commit, stmp)\n\n new_head = Enum.reduce(patch_links, base.commit, fn patch_link, prev_head ->\n\n Logger.debug(\"Patch Link #{inspect(patch_link)}\")\n Logger.debug(\"Patch #{inspect(patch_link.patch)}\")\n\n {:ok, commits} = GitHub.get_pr_commits(repo_conn, patch_link.patch.pr_xref)\n {:ok, pr} = GitHub.get_pr(repo_conn, patch_link.patch.pr_xref)\n\n {token, _} = repo_conn\n user = GitHub.get_user_by_login!(token, pr.user.login)\n\n Logger.debug(\"PR #{inspect(pr)}\")\n Logger.debug(\"User #{inspect(user)}\")\n\n # If a user doesn't have a public email address in their GH profile\n # then get the email from the first commit to the PR\n user_email = if user.email != nil do\n user.email\n else\n Enum.at(commits, 0).author_email\n end\n\n # The head sha is the final commit in the PR.\n source_sha = pr.head_sha\n Logger.info(\"Staging branch #{stmp}\")\n Logger.info(\"Commit sha #{source_sha}\")\n\n # Create a merge commit for each PR\n # because each PR is merged on top of each other in stmp, we can verify against any merge conflicts\n merge_commit = GitHub.merge_branch!(repo_conn,\n %{\n from: source_sha,\n to: stmp,\n commit_message: \"[ci skip][skip ci][skip netlify] -bors-staging-tmp-#{source_sha}\"}\n )\n\n Logger.info(\"Merge Commit #{inspect(merge_commit)}\")\n\n Logger.info(\"Previous Head #{inspect(prev_head)}\")\n # Then compress the merge commit into tree into a single commit\n # appent it to the previous commit\n # Because the merges are iterative the contain *only* the changes from the PR vs the previous PR(or head)\n cpt = GitHub.create_commit!(\n repo_conn,\n %{\n tree: merge_commit.tree,\n parents: [prev_head],\n commit_message: \"#{pr.title} (##{pr.number})\\n#{pr.body}\",\n committer: %{name: user.login, email: user_email}})\n\n Logger.info(\"Commit Sha #{inspect(cpt)}\")\n cpt\n\n end)\n GitHub.delete_branch!(repo_conn, stmp)\n [new_head]\n else\n parents = [base.commit | Enum.map(patch_links, &(&1.patch.commit))]\n parents\n end\n\n head = if toml.use_squash_merge do\n # This will avoid creating a merge commit, which is important since it will prevent\n # bors from polluting th git blame history with it's own name\n head = Enum.at(parents, 0)\n GitHub.force_push!(repo_conn, head, batch.project.staging_branch)\n head\n else\n commit_message = Batcher.Message.generate_commit_message(\n patch_links,\n toml.cut_body_after,\n gather_co_authors(batch, patch_links))\n GitHub.synthesize_commit!(\n repo_conn,\n %{\n branch: batch.project.staging_branch,\n tree: tree,\n parents: parents,\n commit_message: commit_message,\n committer: toml.committer})\n end\n\n setup_statuses(batch, toml)\n {:running, head}\n {:error, message} ->\n message = Batcher.Message.generate_bors_toml_error(message)\n send_message(repo_conn, patches, {:config, message})\n {:error, nil}\n end\n end\n\n defp start_waiting_merged_batch(batch, patch_links, _base, :conflict) do\n repo_conn = get_repo_conn(batch.project)\n patches = Enum.map(patch_links, &(&1.patch))\n state = bisect(patch_links, batch)\n send_message(repo_conn, patches, {:conflict, state})\n {:conflict, nil}\n end\n\n def gather_co_authors(batch, patch_links) do\n repo_conn = get_repo_conn(batch.project)\n patch_links\n |> Enum.map(&(&1.patch.pr_xref))\n |> Enum.flat_map(&GitHub.get_pr_commits!(repo_conn, &1))\n |> Enum.map(&(\"#{&1.author_name} <#{&1.author_email}>\"))\n |> Enum.uniq\n end\n\n defp setup_statuses(batch, toml) do\n toml.status\n |> Enum.map(&%Status{\n batch_id: batch.id,\n identifier: &1,\n url: nil,\n state: :running})\n |> Enum.each(&Repo.insert!\/1)\n now = DateTime.to_unix(DateTime.utc_now(), :second)\n batch\n |> Batch.changeset(%{timeout_at: now + toml.timeout_sec})\n |> Repo.update!()\n end\n\n defp poll_running_batch(batch) do\n batch.project\n |> get_repo_conn()\n |> GitHub.get_commit_status!(batch.commit)\n |> Enum.each(fn {identifier, state} ->\n batch.id\n |> Status.get_for_batch(identifier)\n |> Repo.update_all([set: [state: state, identifier: identifier]])\n end)\n maybe_complete_batch(batch)\n end\n\n defp maybe_complete_batch(batch) do\n statuses = Repo.all(Status.all_for_batch(batch.id))\n status = Batcher.State.summary_database_statuses(statuses)\n now = DateTime.to_unix(DateTime.utc_now(), :second)\n if status != :running do\n batch.project\n |> get_repo_conn()\n |> send_status(batch, status)\n Project.ping!(batch.project_id)\n complete_batch(status, batch, statuses)\n end\n batch\n |> Batch.changeset(%{state: status, last_polled: now})\n |> Repo.update!()\n if status != :running do\n poll_(batch.project_id)\n end\n end\n\n @spec complete_batch(Status.state, Batch.t, [Status.t]) :: :ok\n defp complete_batch(:ok, batch, statuses) do\n project = batch.project\n repo_conn = get_repo_conn(project)\n {res,toml} = case Batcher.GetBorsToml.get(repo_conn, \"#{batch.project.staging_branch}\") do\n {:error, :fetch_failed} -> Batcher.GetBorsToml.get(repo_conn, \"#{batch.project.staging_branch}.tmp\")\n {:ok, x} -> {:ok, x}\n end\n\n {:ok, _} = push_with_retry(\n repo_conn,\n batch.commit,\n batch.into_branch)\n\n patches = batch.id\n |> Patch.all_for_batch()\n |> Repo.all()\n\n if toml.use_squash_merge do\n Enum.each(patches, fn patch ->\n pr = GitHub.get_pr!(repo_conn, patch.pr_xref)\n pr = %BorsNG.GitHub.Pr{pr | state: :closed, title: \"[Merged by Bors] - #{pr.title}\"}\n pr = GitHub.update_pr!(repo_conn, pr)\n GitHub.post_comment!(repo_conn, patch.pr_xref, \"# Pull request successfully merged into master.\")\n end)\n end\n\n send_message(repo_conn, patches, {:succeeded, statuses})\n end\n\n defp complete_batch(:error, batch, statuses) do\n project = batch.project\n repo_conn = get_repo_conn(project)\n erred = Enum.filter(statuses, &(&1.state == :error))\n patch_links = batch.id\n |> LinkPatchBatch.from_batch()\n |> Repo.all()\n patches = Enum.map(patch_links, &(&1.patch))\n state = bisect(patch_links, batch)\n send_message(repo_conn, patches, {state, erred})\n end\n\n # A delay has been observed between Bors sending the Status change\n # and GitHub allowing a Status-bearing commit to be pushed to master.\n # As a workaround, retry with exponential backoff.\n # This should retry *nine times*, by the way.\n defp push_with_retry(repo_conn, commit, into_branch, timeout \\\\ 1) do\n Process.sleep(timeout)\n result = GitHub.push(\n repo_conn,\n commit,\n into_branch)\n case result do\n {:ok, _} -> result\n _ when timeout >= 512 -> result\n _ -> push_with_retry(repo_conn, commit, into_branch, timeout * 2)\n end\n end\n\n defp timeout_batch(batch) do\n project = batch.project\n patch_links = batch.id\n |> LinkPatchBatch.from_batch()\n |> Repo.all()\n patches = Enum.map(patch_links, &(&1.patch))\n state = bisect(patch_links, batch)\n project\n |> get_repo_conn()\n |> send_message(patches, {:timeout, state})\n batch\n |> Batch.changeset(%{state: :error})\n |> Repo.update!()\n Project.ping!(project.id)\n project\n |> get_repo_conn()\n |> send_status(batch, :timeout)\n end\n\n defp cancel_patch(nil, _), do: :ok\n\n defp cancel_patch(batch, patch_id) do\n cancel_patch(batch, patch_id, batch.state)\n Project.ping!(batch.project_id)\n end\n\n defp cancel_patch(batch, patch_id, :running) do\n project = batch.project\n patch_links = batch.id\n |> LinkPatchBatch.from_batch()\n |> Repo.all()\n patches = Enum.map(patch_links, &(&1.patch))\n state = case tl(patch_links) do\n [] -> :failed\n _ -> :retrying\n end\n batch\n |> Batch.changeset(%{state: :canceled})\n |> Repo.update!()\n repo_conn = get_repo_conn(project)\n if state == :retrying do\n uncanceled_patch_links = Enum.filter(\n patch_links,\n &(&1.patch_id != patch_id))\n clone_batch(uncanceled_patch_links, project.id, batch.into_branch)\n canceled_patches = Enum.filter(\n patches,\n &(&1.id == patch_id))\n uncanceled_patches = Enum.filter(\n patches,\n &(&1.id != patch_id))\n send_message(repo_conn, canceled_patches, {:canceled, :failed})\n send_message(repo_conn, uncanceled_patches, {:canceled, :retrying})\n else\n send_message(repo_conn, patches, {:canceled, :failed})\n end\n send_status(repo_conn, batch, :canceled)\n end\n\n defp cancel_patch(batch, patch_id, _state) do\n project = batch.project\n LinkPatchBatch\n |> Repo.get_by!(batch_id: batch.id, patch_id: patch_id)\n |> Repo.delete!()\n if Batch.is_empty(batch.id, Repo) do\n Repo.delete!(batch)\n end\n patch = Repo.get!(Patch, patch_id)\n repo_conn = get_repo_conn(project)\n send_status(repo_conn, batch.id, [patch], :canceled)\n send_message(repo_conn, [patch], {:canceled, :failed})\n end\n\n defp bisect(patch_links, %Batch{project: project, into_branch: into}) do\n count = Enum.count(patch_links)\n if count > 1 do\n {lo, hi} = Enum.split(patch_links, div(count, 2))\n clone_batch(lo, project.id, into)\n clone_batch(hi, project.id, into)\n poll_after_delay(project)\n :retrying\n else\n :failed\n end\n end\n\n defp patch_preflight(repo_conn, patch) do\n if Patch.ci_skip?(patch) do\n {:error, :ci_skip}\n else\n toml = Batcher.GetBorsToml.get(\n repo_conn,\n patch.commit)\n patch_preflight(repo_conn, patch, toml)\n end\n end\n\n defp patch_preflight(_repo_conn, _patch, {:error, _}) do\n :ok\n end\n\n defp patch_preflight(repo_conn, patch, {:ok, toml}) do\n passed_label = repo_conn\n |> GitHub.get_labels!(patch.pr_xref)\n |> MapSet.new()\n |> MapSet.disjoint?(MapSet.new(toml.block_labels))\n passed_status = repo_conn\n |> GitHub.get_commit_status!(patch.commit)\n |> Enum.filter(fn {_, status} -> status != :ok end)\n |> Enum.map(fn {context, _} -> context end)\n |> MapSet.new()\n |> MapSet.disjoint?(MapSet.new(toml.pr_status))\n passed_review = repo_conn\n |> GitHub.get_reviews!(patch.pr_xref)\n |> reviews_status(toml)\n case {passed_label, passed_status, passed_review} do\n {true, true, :sufficient} -> :ok\n {false, _, _} -> {:error, :blocked_labels}\n {_, false, _} -> {:error, :pr_status}\n {_, _, :insufficient} -> {:error, :insufficient_approvals}\n {_, _, :failed} -> {:error, :blocked_review}\n end\n end\n\n @spec reviews_status(map, Batcher.BorsToml.t) :: :sufficient | :failed | :insufficient\n defp reviews_status(reviews, toml) do\n %{\"CHANGES_REQUESTED\" => failed, \"APPROVED\" => approvals} = reviews\n review_required? = is_integer(toml.required_approvals)\n approvals_needed = review_required? && toml.required_approvals || 0\n approved? = approvals >= approvals_needed\n failed? = failed > 0\n cond do\n # NOTE: A way to disable the code reviewing behaviour was requested on #587.\n # As such, we only apply the reviewing rules if, on bors, the config\n # `required_approvals` is present and an integer.\n not review_required? ->\n :sufficient\n failed? ->\n :failed\n approved? ->\n :sufficient\n review_required? ->\n :insufficient\n end\n end\n\n defp clone_batch(patch_links, project_id, into_branch) do\n batch = Repo.insert!(Batch.new(project_id, into_branch))\n patch_links\n |> Enum.map(&%{\n batch_id: batch.id,\n patch_id: &1.patch_id,\n reviewer: &1.reviewer})\n |> Enum.map(&LinkPatchBatch.changeset(%LinkPatchBatch{}, &1))\n |> Enum.each(&Repo.insert!\/1)\n batch\n end\n\n def get_new_batch(project_id, into_branch, priority) do\n Batch\n |> where([b], b.project_id == ^project_id)\n |> where([b], b.state == ^(:waiting))\n |> where([b], b.into_branch == ^into_branch)\n |> where([b], b.priority == ^priority)\n |> order_by([b], [desc: b.updated_at])\n |> limit(1)\n |> Repo.all()\n |> case do\n [batch] -> {batch, false}\n _ -> {Repo.insert!(Batch.new(project_id, into_branch, priority)), true}\n end\n end\n\n defp raise_batch_priority(%Batch{priority: old_priority} = batch, priority) when old_priority < priority do\n project = Repo.get!(Project, batch.project_id)\n batch = batch\n |> Batch.changeset_raise_priority(%{priority: priority})\n |> Repo.update!()\n put_incomplete_on_hold(get_repo_conn(project), batch)\n end\n defp raise_batch_priority(_, _) do\n :ok\n end\n\n defp send_message(repo_conn, patches, message) do\n body = Batcher.Message.generate_message(message)\n Enum.each(patches, &GitHub.post_comment!(\n repo_conn,\n &1.pr_xref,\n body))\n end\n\n defp send_status(\n repo_conn,\n %Batch{id: id, commit: commit, project_id: project_id},\n message\n ) do\n patches = id\n |> Patch.all_for_batch()\n |> Repo.all()\n send_status(repo_conn, id, patches, message)\n unless is_nil commit do\n {msg, status} = Batcher.Message.generate_status(message)\n repo_conn\n |> GitHub.post_commit_status!({\n commit,\n status,\n msg,\n project_url(Endpoint, :log, project_id) <> \"#batch-#{id}\"})\n end\n end\n defp send_status(repo_conn, batch_id, patches, message) do\n {msg, status} = Batcher.Message.generate_status(message)\n Enum.each(patches, &GitHub.post_commit_status!(\n repo_conn,\n {\n &1.commit,\n status,\n msg,\n project_url(Endpoint, :log, &1.project_id) <> \"#batch-#{batch_id}\"}))\n end\n\n @spec get_repo_conn(%Project{}) :: {{:installation, number}, number}\n defp get_repo_conn(project) do\n Project.installation_connection(project.repo_xref, Repo)\n end\n\n defp put_incomplete_on_hold(repo_conn, batch) do\n batches = batch.project_id\n |> Batch.all_for_project(:running)\n |> where([b], b.id != ^batch.id and b.priority < ^batch.priority)\n |> Repo.all()\n\n ids = Enum.map(batches, &(&1.id))\n\n Status\n |> where([s], s.batch_id in ^ids)\n |> Repo.delete_all()\n\n \n Enum.each(batches, &send_status(repo_conn, &1, :delayed))\n Batch\n |> where([b], b.id in ^ids)\n |> Repo.update_all(set: [state: :waiting])\n end\n\n defp poll_after_delay(project) do\n poll_at = (project.batch_delay_sec + 1) * 1000\n Process.send_after(self(), {:poll, :once}, poll_at)\n end\nend\n","old_contents":"require Logger\n\ndefmodule BorsNG.Worker.Batcher do\n @moduledoc \"\"\"\n A \"Batcher\" manages the backlog of batches a project has.\n It implements this set of rules:\n\n * When a patch is reviewed (\"r+'ed\"),\n it gets added to the project's non-running batch.\n If no such batch exists, it creates it.\n * After a short delay, if there is no currently running batch,\n the project's non-running batch is started.\n * The project's CI is occasionally polled,\n if a batch is currently running.\n After polling, the completion logic is run.\n * If a notification related to the underlying CI is received,\n the completion logic is run.\n * When the completion logic is run, the batch is either\n bisected (if it failed and there are two or more patches in it),\n blocked (if it failed and there is only one patch in it),\n pushed to master (if it passed),\n or (if there are still CI jobs with no results) it is left alone.\n \"\"\"\n\n use GenServer\n alias BorsNG.Worker.Batcher\n alias BorsNG.Database.Repo\n alias BorsNG.Database.Batch\n alias BorsNG.Database.BatchState\n alias BorsNG.Database.Patch\n alias BorsNG.Database.Project\n alias BorsNG.Database.Status\n alias BorsNG.Database.LinkPatchBatch\n alias BorsNG.GitHub\n alias BorsNG.Endpoint\n import BorsNG.Router.Helpers\n import Ecto.Query\n\n # Every half-hour\n @poll_period 30 * 60 * 1000\n\n # Public API\n\n def start_link(project_id) do\n GenServer.start_link(__MODULE__, project_id)\n end\n\n def reviewed(pid, patch_id, reviewer) when is_integer(patch_id) do\n GenServer.cast(pid, {:reviewed, patch_id, reviewer})\n end\n\n def set_priority(pid, patch_id, priority) when is_integer(patch_id) do\n GenServer.call(pid, {:set_priority, patch_id, priority})\n end\n\n def status(pid, stat) do\n GenServer.cast(pid, {:status, stat})\n end\n\n def poll(pid) do\n send(pid, {:poll, :once})\n end\n\n def cancel(pid, patch_id) when is_integer(patch_id) do\n GenServer.cast(pid, {:cancel, patch_id})\n end\n\n def cancel_all(pid) do\n GenServer.cast(pid, {:cancel_all})\n end\n\n # Server callbacks\n\n def init(project_id) do\n Process.send_after(\n self(),\n {:poll, :repeat},\n trunc(@poll_period * :rand.uniform(2) * 0.5))\n {:ok, project_id}\n end\n\n def handle_cast(args, project_id) do\n do_handle_cast(args, project_id)\n {:noreply, project_id}\n end\n\n def handle_call({:set_priority, patch_id, priority}, _from, project_id) do\n case Repo.get(Patch, patch_id) do\n nil -> nil\n %{priority: ^priority} -> nil\n patch ->\n patch.id\n |> Batch.all_for_patch(:incomplete)\n |> Repo.one()\n |> raise_batch_priority(priority)\n patch\n |> Patch.changeset(%{priority: priority})\n |> Repo.update!()\n end\n\n {:reply, :ok, project_id}\n end\n\n def do_handle_cast({:reviewed, patch_id, reviewer}, project_id) do\n case Repo.get(Patch.all(:awaiting_review), patch_id) do\n nil ->\n # Patch exists (otherwise, no ID), but is not awaiting review\n patch = Repo.get!(Patch, patch_id)\n project = Repo.get!(Project, patch.project_id)\n project\n |> get_repo_conn()\n |> send_message([patch], :already_running_review)\n patch ->\n # Patch exists and is awaiting review\n # This will cause the PR to start after the patch's scheduled delay\n project = Repo.get!(Project, patch.project_id)\n repo_conn = get_repo_conn(project)\n case patch_preflight(repo_conn, patch) do\n :ok ->\n {batch, is_new_batch} = get_new_batch(\n project_id,\n patch.into_branch,\n patch.priority\n )\n %LinkPatchBatch{}\n |> LinkPatchBatch.changeset(%{\n batch_id: batch.id,\n patch_id: patch.id,\n reviewer: reviewer})\n |> Repo.insert!()\n if is_new_batch do\n put_incomplete_on_hold(get_repo_conn(project), batch)\n end\n poll_after_delay(project)\n send_status(repo_conn, batch.id, [patch], :waiting)\n {:error, message} ->\n send_message(repo_conn, [patch], {:preflight, message})\n end\n end\n end\n\n def do_handle_cast({:status, {commit, identifier, state, url}}, project_id) do\n project_id\n |> Batch.get_assoc_by_commit(commit)\n |> Repo.all()\n |> case do\n [batch] ->\n batch.id\n |> Status.get_for_batch(identifier)\n |> Repo.update_all([set: [state: state, url: url, identifier: identifier]])\n if batch.state == :running do\n maybe_complete_batch(batch)\n end\n [] -> :ok\n end\n end\n\n def do_handle_cast({:cancel, patch_id}, _project_id) do\n patch_id\n |> Batch.all_for_patch(:incomplete)\n |> Repo.one()\n |> cancel_patch(patch_id)\n end\n\n def do_handle_cast({:cancel_all}, project_id) do\n waiting = project_id\n |> Batch.all_for_project(:waiting)\n |> Repo.all()\n Enum.each(waiting, &Repo.delete!\/1)\n running = project_id\n |> Batch.all_for_project(:running)\n |> Repo.all()\n Enum.map(running, &Batch.changeset(&1, %{state: :canceled}))\n |> Enum.each(&Repo.update!\/1)\n repo_conn = Project\n |> Repo.get!(project_id)\n |> get_repo_conn()\n Enum.each(running, &send_status(repo_conn, &1, :canceled))\n Enum.each(waiting, &send_status(repo_conn, &1, :canceled))\n end\n\n def handle_info({:poll, repetition}, project_id) do\n if repetition != :once do\n Process.send_after(self(), {:poll, repetition}, @poll_period)\n end\n case poll_(project_id) do\n :stop ->\n {:stop, :normal, project_id}\n :again ->\n {:noreply, project_id}\n end\n end\n\n # Private implementation details\n\n defp poll_(project_id) do\n project = Repo.get(Project, project_id)\n incomplete = project_id\n |> Batch.all_for_project(:incomplete)\n |> Repo.all()\n incomplete\n |> Enum.map(&%Batch{&1 | project: project})\n |> sort_batches()\n |> poll_batches()\n if Enum.empty?(incomplete) do\n :stop\n else\n :again\n end\n end\n\n def sort_batches(batches) do\n sorted_batches = Enum.sort_by(batches, &{\n -BatchState.numberize(&1.state),\n -&1.priority,\n &1.last_polled\n })\n new_batches = Enum.dedup_by(sorted_batches, &(&1.id))\n state = if new_batches != [] and hd(new_batches).state == :running do\n :running\n else\n Enum.each(new_batches, fn batch -> :waiting = batch.state end)\n :waiting\n end\n {state, new_batches}\n end\n\n defp poll_batches({:waiting, batches}) do\n case Enum.filter(batches, &Batch.next_poll_is_past\/1) do\n [] -> :ok\n [batch | _] -> start_waiting_batch(batch)\n end\n end\n\n defp poll_batches({:running, batches}) do\n batch = hd(batches)\n cond do\n Batch.timeout_is_past(batch) ->\n timeout_batch(batch)\n Batch.next_poll_is_past(batch) ->\n poll_running_batch(batch)\n true -> :ok\n end\n end\n\n defp start_waiting_batch(batch) do\n project = batch.project\n repo_conn = get_repo_conn(project)\n patch_links = Repo.all(LinkPatchBatch.from_batch(batch.id))\n |> Enum.sort_by(&(&1.patch.pr_xref))\n stmp = \"#{project.staging_branch}.tmp\"\n\n base = GitHub.get_branch!(\n repo_conn,\n batch.into_branch)\n tbase = %{\n tree: base.tree,\n commit: GitHub.synthesize_commit!(\n repo_conn,\n %{\n branch: stmp,\n tree: base.tree,\n parents: [base.commit],\n commit_message: \"[ci skip][skip ci][skip netlify]\",\n committer: nil})}\n do_merge_patch = fn %{patch: patch}, branch ->\n case branch do\n :conflict -> :conflict\n :canceled -> :canceled\n _ -> GitHub.merge_branch!(\n repo_conn,\n %{\n from: patch.commit,\n to: stmp,\n commit_message: \"[ci skip][skip ci][skip netlify] -bors-staging-tmp-#{patch.pr_xref}\"})\n end\n end\n\n merge = Enum.reduce(patch_links, tbase, do_merge_patch)\n {status, commit} = start_waiting_merged_batch(\n batch,\n patch_links,\n base,\n merge)\n now = DateTime.to_unix(DateTime.utc_now(), :second)\n\n GitHub.delete_branch!(repo_conn, stmp)\n send_status(repo_conn, batch, status)\n batch\n |> Batch.changeset(%{state: status, commit: commit, last_polled: now})\n |> Repo.update!()\n\n stmp = \"#{batch.project.staging_branch}.tmp2\"\n GitHub.force_push!(repo_conn, base.commit, stmp)\n\n new_head = Enum.reduce(patch_links, base.commit, fn patch_link, prev_head ->\n\n Logger.debug(\"Patch Link #{inspect(patch_link)}\")\n Logger.debug(\"Patch #{inspect(patch_link.patch)}\")\n\n {:ok, commits} = GitHub.get_pr_commits(repo_conn, patch_link.patch.pr_xref)\n {:ok, pr} = GitHub.get_pr(repo_conn, patch_link.patch.pr_xref)\n\n {token, _} = repo_conn\n user = GitHub.get_user_by_login!(token, pr.user.login)\n\n Logger.debug(\"PR #{inspect(pr)}\")\n Logger.debug(\"User #{inspect(user)}\")\n\n # If a user doesn't have a public email address in their GH profile\n # then get the email from the first commit to the PR\n user_email = if user.email != nil do\n user.email\n else\n Enum.at(commits, 0).author_email\n end\n\n # The head sha is the final commit in the PR.\n source_sha = pr.head_sha\n Logger.info(\"Staging branch #{stmp}\")\n Logger.info(\"Commit sha #{source_sha}\")\n\n # Create a merge commit for each PR\n # because each PR is merged on top of each other in stmp, we can verify against any merge conflicts\n merge_commit = GitHub.merge_branch!(repo_conn,\n %{\n from: source_sha,\n to: stmp,\n commit_message: \"[ci skip][skip ci][skip netlify] -bors-staging-tmp-#{source_sha}\"}\n )\n\n Logger.info(\"Merge Commit #{inspect(merge_commit)}\")\n\n Logger.info(\"Previous Head #{inspect(prev_head)}\")\n # Then compress the merge commit into tree into a single commit\n # appent it to the previous commit\n # Because the merges are iterative the contain *only* the changes from the PR vs the previous PR(or head)\n cpt = GitHub.create_commit!(\n repo_conn,\n %{\n tree: merge_commit.tree,\n parents: [prev_head],\n commit_message: \"#{pr.title} (##{pr.number})\\n#{pr.body}\",\n committer: %{name: user.login, email: user_email}})\n\n Logger.info(\"Commit Sha #{inspect(cpt)}\")\n cpt\n\n end)\n GitHub.delete_branch!(repo_conn, stmp)\n [new_head]\n else\n parents = [base.commit | Enum.map(patch_links, &(&1.patch.commit))]\n parents\n end\n commit_message = Batcher.Message.generate_commit_message(\n patch_links,\n toml.cut_body_after,\n gather_co_authors(batch, patch_links))\n\n head = if toml.use_squash_merge do\n head = Enum.at(parents, 0)\n GitHub.force_push!(repo_conn, head, batch.project.staging_branch)\n head\n else\n GitHub.synthesize_commit!(\n repo_conn,\n %{\n branch: batch.project.staging_branch,\n tree: tree,\n parents: parents,\n commit_message: commit_message,\n committer: toml.committer})\n end\n \n setup_statuses(batch, toml)\n {:running, head}\n {:error, message} ->\n message = Batcher.Message.generate_bors_toml_error(message)\n send_message(repo_conn, patches, {:config, message})\n {:error, nil}\n end\n end\n\n defp start_waiting_merged_batch(batch, patch_links, _base, :conflict) do\n repo_conn = get_repo_conn(batch.project)\n patches = Enum.map(patch_links, &(&1.patch))\n state = bisect(patch_links, batch)\n send_message(repo_conn, patches, {:conflict, state})\n {:conflict, nil}\n end\n\n def gather_co_authors(batch, patch_links) do\n repo_conn = get_repo_conn(batch.project)\n patch_links\n |> Enum.map(&(&1.patch.pr_xref))\n |> Enum.flat_map(&GitHub.get_pr_commits!(repo_conn, &1))\n |> Enum.map(&(\"#{&1.author_name} <#{&1.author_email}>\"))\n |> Enum.uniq\n end\n\n defp setup_statuses(batch, toml) do\n toml.status\n |> Enum.map(&%Status{\n batch_id: batch.id,\n identifier: &1,\n url: nil,\n state: :running})\n |> Enum.each(&Repo.insert!\/1)\n now = DateTime.to_unix(DateTime.utc_now(), :second)\n batch\n |> Batch.changeset(%{timeout_at: now + toml.timeout_sec})\n |> Repo.update!()\n end\n\n defp poll_running_batch(batch) do\n batch.project\n |> get_repo_conn()\n |> GitHub.get_commit_status!(batch.commit)\n |> Enum.each(fn {identifier, state} ->\n batch.id\n |> Status.get_for_batch(identifier)\n |> Repo.update_all([set: [state: state, identifier: identifier]])\n end)\n maybe_complete_batch(batch)\n end\n\n defp maybe_complete_batch(batch) do\n statuses = Repo.all(Status.all_for_batch(batch.id))\n status = Batcher.State.summary_database_statuses(statuses)\n now = DateTime.to_unix(DateTime.utc_now(), :second)\n if status != :running do\n batch.project\n |> get_repo_conn()\n |> send_status(batch, status)\n Project.ping!(batch.project_id)\n complete_batch(status, batch, statuses)\n end\n batch\n |> Batch.changeset(%{state: status, last_polled: now})\n |> Repo.update!()\n if status != :running do\n poll_(batch.project_id)\n end\n end\n\n @spec complete_batch(Status.state, Batch.t, [Status.t]) :: :ok\n defp complete_batch(:ok, batch, statuses) do\n project = batch.project\n repo_conn = get_repo_conn(project)\n {res,toml} = case Batcher.GetBorsToml.get(repo_conn, \"#{batch.project.staging_branch}\") do\n {:error, :fetch_failed} -> Batcher.GetBorsToml.get(repo_conn, \"#{batch.project.staging_branch}.tmp\")\n {:ok, x} -> {:ok, x}\n end\n\n {:ok, _} = push_with_retry(\n repo_conn,\n batch.commit,\n batch.into_branch)\n\n patches = batch.id\n |> Patch.all_for_batch()\n |> Repo.all()\n\n if toml.use_squash_merge do\n Enum.each(patches, fn patch ->\n pr = GitHub.get_pr!(repo_conn, patch.pr_xref)\n pr = %BorsNG.GitHub.Pr{pr | state: :closed, title: \"[Merged by Bors] - #{pr.title}\"}\n pr = GitHub.update_pr!(repo_conn, pr)\n GitHub.post_comment!(repo_conn, patch.pr_xref, \"# Pull request successfully merged into master.\")\n end)\n end\n\n send_message(repo_conn, patches, {:succeeded, statuses})\n end\n\n defp complete_batch(:error, batch, statuses) do\n project = batch.project\n repo_conn = get_repo_conn(project)\n erred = Enum.filter(statuses, &(&1.state == :error))\n patch_links = batch.id\n |> LinkPatchBatch.from_batch()\n |> Repo.all()\n patches = Enum.map(patch_links, &(&1.patch))\n state = bisect(patch_links, batch)\n send_message(repo_conn, patches, {state, erred})\n end\n\n # A delay has been observed between Bors sending the Status change\n # and GitHub allowing a Status-bearing commit to be pushed to master.\n # As a workaround, retry with exponential backoff.\n # This should retry *nine times*, by the way.\n defp push_with_retry(repo_conn, commit, into_branch, timeout \\\\ 1) do\n Process.sleep(timeout)\n result = GitHub.push(\n repo_conn,\n commit,\n into_branch)\n case result do\n {:ok, _} -> result\n _ when timeout >= 512 -> result\n _ -> push_with_retry(repo_conn, commit, into_branch, timeout * 2)\n end\n end\n\n defp timeout_batch(batch) do\n project = batch.project\n patch_links = batch.id\n |> LinkPatchBatch.from_batch()\n |> Repo.all()\n patches = Enum.map(patch_links, &(&1.patch))\n state = bisect(patch_links, batch)\n project\n |> get_repo_conn()\n |> send_message(patches, {:timeout, state})\n batch\n |> Batch.changeset(%{state: :error})\n |> Repo.update!()\n Project.ping!(project.id)\n project\n |> get_repo_conn()\n |> send_status(batch, :timeout)\n end\n\n defp cancel_patch(nil, _), do: :ok\n\n defp cancel_patch(batch, patch_id) do\n cancel_patch(batch, patch_id, batch.state)\n Project.ping!(batch.project_id)\n end\n\n defp cancel_patch(batch, patch_id, :running) do\n project = batch.project\n patch_links = batch.id\n |> LinkPatchBatch.from_batch()\n |> Repo.all()\n patches = Enum.map(patch_links, &(&1.patch))\n state = case tl(patch_links) do\n [] -> :failed\n _ -> :retrying\n end\n batch\n |> Batch.changeset(%{state: :canceled})\n |> Repo.update!()\n repo_conn = get_repo_conn(project)\n if state == :retrying do\n uncanceled_patch_links = Enum.filter(\n patch_links,\n &(&1.patch_id != patch_id))\n clone_batch(uncanceled_patch_links, project.id, batch.into_branch)\n canceled_patches = Enum.filter(\n patches,\n &(&1.id == patch_id))\n uncanceled_patches = Enum.filter(\n patches,\n &(&1.id != patch_id))\n send_message(repo_conn, canceled_patches, {:canceled, :failed})\n send_message(repo_conn, uncanceled_patches, {:canceled, :retrying})\n else\n send_message(repo_conn, patches, {:canceled, :failed})\n end\n send_status(repo_conn, batch, :canceled)\n end\n\n defp cancel_patch(batch, patch_id, _state) do\n project = batch.project\n LinkPatchBatch\n |> Repo.get_by!(batch_id: batch.id, patch_id: patch_id)\n |> Repo.delete!()\n if Batch.is_empty(batch.id, Repo) do\n Repo.delete!(batch)\n end\n patch = Repo.get!(Patch, patch_id)\n repo_conn = get_repo_conn(project)\n send_status(repo_conn, batch.id, [patch], :canceled)\n send_message(repo_conn, [patch], {:canceled, :failed})\n end\n\n defp bisect(patch_links, %Batch{project: project, into_branch: into}) do\n count = Enum.count(patch_links)\n if count > 1 do\n {lo, hi} = Enum.split(patch_links, div(count, 2))\n clone_batch(lo, project.id, into)\n clone_batch(hi, project.id, into)\n poll_after_delay(project)\n :retrying\n else\n :failed\n end\n end\n\n defp patch_preflight(repo_conn, patch) do\n if Patch.ci_skip?(patch) do\n {:error, :ci_skip}\n else\n toml = Batcher.GetBorsToml.get(\n repo_conn,\n patch.commit)\n patch_preflight(repo_conn, patch, toml)\n end\n end\n\n defp patch_preflight(_repo_conn, _patch, {:error, _}) do\n :ok\n end\n\n defp patch_preflight(repo_conn, patch, {:ok, toml}) do\n passed_label = repo_conn\n |> GitHub.get_labels!(patch.pr_xref)\n |> MapSet.new()\n |> MapSet.disjoint?(MapSet.new(toml.block_labels))\n passed_status = repo_conn\n |> GitHub.get_commit_status!(patch.commit)\n |> Enum.filter(fn {_, status} -> status != :ok end)\n |> Enum.map(fn {context, _} -> context end)\n |> MapSet.new()\n |> MapSet.disjoint?(MapSet.new(toml.pr_status))\n passed_review = repo_conn\n |> GitHub.get_reviews!(patch.pr_xref)\n |> reviews_status(toml)\n case {passed_label, passed_status, passed_review} do\n {true, true, :sufficient} -> :ok\n {false, _, _} -> {:error, :blocked_labels}\n {_, false, _} -> {:error, :pr_status}\n {_, _, :insufficient} -> {:error, :insufficient_approvals}\n {_, _, :failed} -> {:error, :blocked_review}\n end\n end\n\n @spec reviews_status(map, Batcher.BorsToml.t) :: :sufficient | :failed | :insufficient\n defp reviews_status(reviews, toml) do\n %{\"CHANGES_REQUESTED\" => failed, \"APPROVED\" => approvals} = reviews\n review_required? = is_integer(toml.required_approvals)\n approvals_needed = review_required? && toml.required_approvals || 0\n approved? = approvals >= approvals_needed\n failed? = failed > 0\n cond do\n # NOTE: A way to disable the code reviewing behaviour was requested on #587.\n # As such, we only apply the reviewing rules if, on bors, the config\n # `required_approvals` is present and an integer.\n not review_required? ->\n :sufficient\n failed? ->\n :failed\n approved? ->\n :sufficient\n review_required? ->\n :insufficient\n end\n end\n\n defp clone_batch(patch_links, project_id, into_branch) do\n batch = Repo.insert!(Batch.new(project_id, into_branch))\n patch_links\n |> Enum.map(&%{\n batch_id: batch.id,\n patch_id: &1.patch_id,\n reviewer: &1.reviewer})\n |> Enum.map(&LinkPatchBatch.changeset(%LinkPatchBatch{}, &1))\n |> Enum.each(&Repo.insert!\/1)\n batch\n end\n\n def get_new_batch(project_id, into_branch, priority) do\n Batch\n |> where([b], b.project_id == ^project_id)\n |> where([b], b.state == ^(:waiting))\n |> where([b], b.into_branch == ^into_branch)\n |> where([b], b.priority == ^priority)\n |> order_by([b], [desc: b.updated_at])\n |> limit(1)\n |> Repo.all()\n |> case do\n [batch] -> {batch, false}\n _ -> {Repo.insert!(Batch.new(project_id, into_branch, priority)), true}\n end\n end\n\n defp raise_batch_priority(%Batch{priority: old_priority} = batch, priority) when old_priority < priority do\n project = Repo.get!(Project, batch.project_id)\n batch = batch\n |> Batch.changeset_raise_priority(%{priority: priority})\n |> Repo.update!()\n put_incomplete_on_hold(get_repo_conn(project), batch)\n end\n defp raise_batch_priority(_, _) do\n :ok\n end\n\n defp send_message(repo_conn, patches, message) do\n body = Batcher.Message.generate_message(message)\n Enum.each(patches, &GitHub.post_comment!(\n repo_conn,\n &1.pr_xref,\n body))\n end\n\n defp send_status(\n repo_conn,\n %Batch{id: id, commit: commit, project_id: project_id},\n message\n ) do\n patches = id\n |> Patch.all_for_batch()\n |> Repo.all()\n send_status(repo_conn, id, patches, message)\n unless is_nil commit do\n {msg, status} = Batcher.Message.generate_status(message)\n repo_conn\n |> GitHub.post_commit_status!({\n commit,\n status,\n msg,\n project_url(Endpoint, :log, project_id) <> \"#batch-#{id}\"})\n end\n end\n defp send_status(repo_conn, batch_id, patches, message) do\n {msg, status} = Batcher.Message.generate_status(message)\n Enum.each(patches, &GitHub.post_commit_status!(\n repo_conn,\n {\n &1.commit,\n status,\n msg,\n project_url(Endpoint, :log, &1.project_id) <> \"#batch-#{batch_id}\"}))\n end\n\n @spec get_repo_conn(%Project{}) :: {{:installation, number}, number}\n defp get_repo_conn(project) do\n Project.installation_connection(project.repo_xref, Repo)\n end\n\n defp put_incomplete_on_hold(repo_conn, batch) do\n batches = batch.project_id\n |> Batch.all_for_project(:running)\n |> where([b], b.id != ^batch.id and b.priority < ^batch.priority)\n |> Repo.all()\n\n ids = Enum.map(batches, &(&1.id))\n\n Status\n |> where([s], s.batch_id in ^ids)\n |> Repo.delete_all()\n\n \n Enum.each(batches, &send_status(repo_conn, &1, :delayed))\n Batch\n |> where([b], b.id in ^ids)\n |> Repo.update_all(set: [state: :waiting])\n end\n\n defp poll_after_delay(project) do\n poll_at = (project.batch_delay_sec + 1) * 1000\n Process.send_after(self(), {:poll, :once}, poll_at)\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"19d788e8a77a60e3aa459967419cdb71cc8359ac","subject":"Change test example in lib\/bamboo\/test.ex from MyApp.EmailsTest to MyApp.EmailTest","message":"Change test example in lib\/bamboo\/test.ex from MyApp.EmailsTest to MyApp.EmailTest\n","repos":"alekseenko\/bamboo,thoughtbot\/bamboo","old_file":"lib\/bamboo\/test.ex","new_file":"lib\/bamboo\/test.ex","new_contents":"defmodule Bamboo.Test do\n import ExUnit.Assertions\n\n @moduledoc \"\"\"\n Helpers for testing email delivery\n\n Use these helpers with Bamboo.TestAdapter to test email delivery. Typically\n you'll want to **unit test emails first**. Then in integration tests use\n helpers from this module to test whether that email was delivered.\n\n ## Note on sending from other processes\n\n If you are sending emails from another process (for example, from inside a\n Task or GenServer) you may need to use shared mode when using\n `Bamboo.Test`. See the docs `__using__\/1` for an example.\n\n For most scenarios you will not need shared mode.\n\n ## In your config\n\n # Typically in config\/test.exs\n config :my_app, MyApp.Mailer,\n adapter: Bamboo.TestAdapter\n\n ## Unit test\n\n You don't need any special functions to unit test emails.\n\n defmodule MyApp.EmailTest do\n use ExUnit.Case\n\n test \"welcome email\" do\n user = %User{name: \"John\", email: \"person@example.com\"}\n\n email = MyApp.Email.welcome_email(user)\n\n assert email.to == user\n assert email.subject == \"This is your welcome email\"\n assert email.html_body =~ \"Welcome to the app\"\n end\n end\n\n ## Integration test\n\n defmodule MyApp.Email do\n import Bamboo.Email\n\n def welcome_email(user) do\n new_email(\n from: \"me@app.com\",\n to: user,\n subject: \"Welcome!\",\n text_body: \"Welcome to the app\",\n html_body: \"Welcome to the app<\/strong>\"\n )\n end\n end\n\n defmodule MyApp.EmailDeliveryTest do\n use ExUnit.Case\n use Bamboo.Test\n\n test \"sends welcome email\" do\n user = %User{...}\n email = MyApp.Email.welcome_email(user)\n\n email |> MyApp.Mailer.deliver_now\n\n # Works with deliver_now and deliver_later\n assert_delivered_email email\n end\n end\n \"\"\"\n\n @doc \"\"\"\n Imports Bamboo.Test and Bamboo.Formatter.format_email_address\/2\n\n `Bamboo.Test` and the `Bamboo.TestAdapter` work by sending a message to the\n current process when an email is delivered. The process mailbox is then\n checked when using the assertion helpers like `assert_delivered_email\/1`.\n\n Sometimes emails don't show up when asserting because you may deliver an email\n from a _different_ process than the test process. When that happens, turn on\n shared mode. This will tell `Bamboo.TestAdapter` to always send to the test process.\n This means that you cannot use shared mode with async tests.\n\n ## Try to use this version first\n\n use Bamboo.Test\n\n ## And if you are delivering from another process, set `shared: true`\n\n use Bamboo.Test, shared: true\n\n Common scenarios for delivering mail from a different process are when you\n send from inside of a Task, GenServer, or are running acceptance tests with a\n headless browser like phantomjs.\n \"\"\"\n defmacro __using__(shared: true) do\n quote do\n setup tags do\n if tags[:async] do\n raise \"\"\"\n you cannot use Bamboo.Test shared mode with async tests.\n\n There are a few options, the 1st is the easiest:\n\n 1) Set your test to [async: false].\n 2) If you are delivering emails from another process (for example,\n delivering from within Task.async or Process.spawn), try using\n Mailer.deliver_later. If you use Mailer.deliver_later without\n spawning another process you can use Bamboo.Test with [async:\n true] and without the shared mode.\n 3) If you are writing an acceptance test that requires shared mode,\n try using a controller test instead. Then see if the test works\n without shared mode.\n \"\"\"\n else\n Application.put_env(:bamboo, :shared_test_process, self())\n end\n\n :ok\n end\n\n import Bamboo.Formatter, only: [format_email_address: 2]\n import Bamboo.Test\n end\n end\n\n defmacro __using__(_opts) do\n quote do\n setup tags do\n Application.delete_env(:bamboo, :shared_test_process)\n\n :ok\n end\n\n import Bamboo.Formatter, only: [format_email_address: 2]\n import Bamboo.Test\n end\n end\n\n @doc \"\"\"\n Checks whether an email was delivered.\n\n Must be used with the `Bamboo.TestAdapter` or this will never pass. In case you\n are delivering from another process, the assertion waits up to 100ms before\n failing. Typically if an email is successfully delivered the assertion will\n pass instantly, so test suites will remain fast.\n\n ## Examples\n\n email = Bamboo.Email.new_email(subject: \"something\")\n email |> MyApp.Mailer.deliver\n assert_delivered_email(email) # Will pass\n\n unsent_email = Bamboo.Email.new_email(subject: \"something else\")\n assert_delivered_email(unsent_email) # Will fail\n \"\"\"\n defmacro assert_delivered_email(email) do\n quote do\n import ExUnit.Assertions\n email = Bamboo.Test.normalize_for_testing(unquote(email))\n assert_receive({:delivered_email, ^email}, 100, Bamboo.Test.flunk_with_email_list(email))\n end\n end\n\n @doc \"\"\"\n Check whether an email's params are equal to the ones provided.\n\n Must be used with the `Bamboo.TestAdapter` or this will never pass. In case you\n are delivering from another process, the assertion waits up to 100ms before\n failing. Typically if an email is successfully delivered the assertion will\n pass instantly, so test suites will remain fast.\n\n ## Examples\n\n email = Bamboo.Email.new_email(subject: \"something\")\n email |> MyApp.Mailer.deliver\n assert_email_delivered_with(subject: \"something\") # Will pass\n\n unsent_email = Bamboo.Email.new_email(subject: \"something else\")\n assert_email_delivered_with(subject: \"something else\") # Will fail\n\n You can also pass a regex to match portions of an email.\n\n ## Example\n\n email = new_email(text_body: \"I love coffee\")\n assert_email_delivered_with(email, text_body: ~r\/love\/) # Will pass\n assert_email_delivered_with(email, text_body: ~r\/like\/) # Will fail\n \"\"\"\n defmacro assert_email_delivered_with(email_params) do\n quote bind_quoted: [email_params: email_params] do\n import ExUnit.Assertions\n assert_receive({:delivered_email, email}, 100, Bamboo.Test.flunk_no_emails_received)\n\n recieved_email_params = email |> Map.from_struct\n assert Enum.all?(email_params, fn({k, v}) -> do_match(recieved_email_params[k], v) end),\n Bamboo.Test.flunk_attributes_do_not_match(email_params, recieved_email_params)\n end\n end\n\n @doc false\n def do_match(value1, value2 = %Regex{}) do\n Regex.match?(value2, value1)\n end\n\n @doc false\n def do_match(value1, value2) do\n value1 == value2\n end\n\n @doc false\n def flunk_with_email_list(email) do\n if Enum.empty?(delivered_emails()) do\n flunk_no_emails_received()\n else\n flunk \"\"\"\n There were no matching emails.\n\n No emails matched:\n\n #{inspect email}\n\n Delivered emails:\n\n #{delivered_emails_as_list()}\n \"\"\"\n end\n end\n\n @doc false\n def flunk_no_emails_received do\n flunk \"\"\"\n There were 0 emails delivered to this process.\n\n If you expected an email to be sent, try these ideas:\n\n 1) Make sure you call deliver_now\/1 or deliver_later\/1 to deliver the email\n 2) Make sure you are using the Bamboo.TestAdapter\n 3) Use shared mode with Bamboo.Test. This will allow Bamboo.Test\n to work across processes: use Bamboo.Test, shared: :true\n 4) If you are writing an acceptance test through a headless browser, use\n shared mode as described in option 3.\n \"\"\"\n end\n\n @doc false\n def flunk_attributes_do_not_match(params_given, params_received) do\n \"\"\"\n The parameters given do not match.\n\n Parameters given:\n\n #{inspect params_given}\n\n Email recieved:\n\n #{inspect params_received}\n \"\"\"\n end\n\n defp delivered_emails do\n {:messages, messages} = Process.info(self(), :messages)\n\n for {:delivered_email, _} = email_message <- messages do\n email_message\n end\n end\n\n defp delivered_emails_as_list do\n delivered_emails() |> add_asterisk |> Enum.join(\"\\n\")\n end\n\n defp add_asterisk(emails) do\n Enum.map(emails, &\" * #{inspect &1}\")\n end\n\n @doc \"\"\"\n Checks that no emails were sent.\n\n If `Bamboo.Test` is used with shared mode, you must also configure a timeout\n in your test config.\n\n # Set this in your config, typically in config\/test.exs\n config :bamboo, :refute_timeout, 10\n\n The value you set is up to you. Lower values will result in faster tests,\n but may incorrectly pass if an email is delivered *after* the timeout. Often\n times 1ms is enough.\n \"\"\"\n def assert_no_emails_delivered do\n receive do\n {:delivered_email, email} -> flunk_with_unexpected_email(email)\n after\n refute_timeout() -> true\n end\n end\n\n @doc false\n def assert_no_emails_sent do\n raise \"assert_no_emails_sent\/0 has been renamed to assert_no_emails_delivered\/0\"\n end\n\n defp flunk_with_unexpected_email(email) do\n flunk \"\"\"\n Unexpectedly delivered an email when expected none to be delivered.\n\n Delivered email:\n\n #{inspect email}\n \"\"\"\n end\n\n @doc \"\"\"\n Ensures a particular email was not sent\n\n Same as `assert_delivered_email\/0`, except it checks that a particular email\n was not sent.\n\n If `Bamboo.Test` is used with shared mode, you must also configure a timeout\n in your test config.\n\n # Set this in your config, typically in config\/test.exs\n config :bamboo, :refute_timeout, 10\n\n The value you set is up to you. Lower values will result in faster tests,\n but may incorrectly pass if an email is delivered *after* the timeout. Often\n times 1ms is enough.\n \"\"\"\n def refute_delivered_email(%Bamboo.Email{} = email) do\n email = normalize_for_testing(email)\n\n receive do\n {:delivered_email, ^email} -> flunk_with_unexpected_matching_email(email)\n after\n refute_timeout() -> true\n end\n end\n\n defp flunk_with_unexpected_matching_email(email) do\n flunk \"\"\"\n Unexpectedly delivered a matching email.\n\n Matched email that was delivered:\n\n #{inspect email}\n \"\"\"\n end\n\n defp refute_timeout do\n if using_shared_mode?() do\n Application.get_env(:bamboo, :refute_timeout) || raise \"\"\"\n When using shared mode with Bamboo.Test, you must set a timeout. This\n is because an email can be delivered after the assertion is called.\n\n # Set this in your config, typically in config\/test.exs\n config :bamboo, :refute_timeout, 10\n\n The value you set is up to you. Lower values will result in faster tests,\n but may incorrectly pass if an email is delivered *after* the timeout.\n \"\"\"\n else\n 0\n end\n end\n\n defp using_shared_mode? do\n !!Application.get_env(:bamboo, :shared_test_process)\n end\n\n @doc false\n def normalize_for_testing(email) do\n email\n |> Bamboo.Mailer.normalize_addresses\n |> Bamboo.TestAdapter.clean_assigns\n end\nend\n","old_contents":"defmodule Bamboo.Test do\n import ExUnit.Assertions\n\n @moduledoc \"\"\"\n Helpers for testing email delivery\n\n Use these helpers with Bamboo.TestAdapter to test email delivery. Typically\n you'll want to **unit test emails first**. Then in integration tests use\n helpers from this module to test whether that email was delivered.\n\n ## Note on sending from other processes\n\n If you are sending emails from another process (for example, from inside a\n Task or GenServer) you may need to use shared mode when using\n `Bamboo.Test`. See the docs `__using__\/1` for an example.\n\n For most scenarios you will not need shared mode.\n\n ## In your config\n\n # Typically in config\/test.exs\n config :my_app, MyApp.Mailer,\n adapter: Bamboo.TestAdapter\n\n ## Unit test\n\n You don't need any special functions to unit test emails.\n\n defmodule MyApp.EmailsTest do\n use ExUnit.Case\n\n test \"welcome email\" do\n user = %User{name: \"John\", email: \"person@example.com\"}\n\n email = MyApp.Email.welcome_email(user)\n\n assert email.to == user\n assert email.subject == \"This is your welcome email\"\n assert email.html_body =~ \"Welcome to the app\"\n end\n end\n\n ## Integration test\n\n defmodule MyApp.Email do\n import Bamboo.Email\n\n def welcome_email(user) do\n new_email(\n from: \"me@app.com\",\n to: user,\n subject: \"Welcome!\",\n text_body: \"Welcome to the app\",\n html_body: \"Welcome to the app<\/strong>\"\n )\n end\n end\n\n defmodule MyApp.EmailDeliveryTest do\n use ExUnit.Case\n use Bamboo.Test\n\n test \"sends welcome email\" do\n user = %User{...}\n email = MyApp.Email.welcome_email(user)\n\n email |> MyApp.Mailer.deliver_now\n\n # Works with deliver_now and deliver_later\n assert_delivered_email email\n end\n end\n \"\"\"\n\n @doc \"\"\"\n Imports Bamboo.Test and Bamboo.Formatter.format_email_address\/2\n\n `Bamboo.Test` and the `Bamboo.TestAdapter` work by sending a message to the\n current process when an email is delivered. The process mailbox is then\n checked when using the assertion helpers like `assert_delivered_email\/1`.\n\n Sometimes emails don't show up when asserting because you may deliver an email\n from a _different_ process than the test process. When that happens, turn on\n shared mode. This will tell `Bamboo.TestAdapter` to always send to the test process.\n This means that you cannot use shared mode with async tests.\n\n ## Try to use this version first\n\n use Bamboo.Test\n\n ## And if you are delivering from another process, set `shared: true`\n\n use Bamboo.Test, shared: true\n\n Common scenarios for delivering mail from a different process are when you\n send from inside of a Task, GenServer, or are running acceptance tests with a\n headless browser like phantomjs.\n \"\"\"\n defmacro __using__(shared: true) do\n quote do\n setup tags do\n if tags[:async] do\n raise \"\"\"\n you cannot use Bamboo.Test shared mode with async tests.\n\n There are a few options, the 1st is the easiest:\n\n 1) Set your test to [async: false].\n 2) If you are delivering emails from another process (for example,\n delivering from within Task.async or Process.spawn), try using\n Mailer.deliver_later. If you use Mailer.deliver_later without\n spawning another process you can use Bamboo.Test with [async:\n true] and without the shared mode.\n 3) If you are writing an acceptance test that requires shared mode,\n try using a controller test instead. Then see if the test works\n without shared mode.\n \"\"\"\n else\n Application.put_env(:bamboo, :shared_test_process, self())\n end\n\n :ok\n end\n\n import Bamboo.Formatter, only: [format_email_address: 2]\n import Bamboo.Test\n end\n end\n\n defmacro __using__(_opts) do\n quote do\n setup tags do\n Application.delete_env(:bamboo, :shared_test_process)\n\n :ok\n end\n\n import Bamboo.Formatter, only: [format_email_address: 2]\n import Bamboo.Test\n end\n end\n\n @doc \"\"\"\n Checks whether an email was delivered.\n\n Must be used with the `Bamboo.TestAdapter` or this will never pass. In case you\n are delivering from another process, the assertion waits up to 100ms before\n failing. Typically if an email is successfully delivered the assertion will\n pass instantly, so test suites will remain fast.\n\n ## Examples\n\n email = Bamboo.Email.new_email(subject: \"something\")\n email |> MyApp.Mailer.deliver\n assert_delivered_email(email) # Will pass\n\n unsent_email = Bamboo.Email.new_email(subject: \"something else\")\n assert_delivered_email(unsent_email) # Will fail\n \"\"\"\n defmacro assert_delivered_email(email) do\n quote do\n import ExUnit.Assertions\n email = Bamboo.Test.normalize_for_testing(unquote(email))\n assert_receive({:delivered_email, ^email}, 100, Bamboo.Test.flunk_with_email_list(email))\n end\n end\n\n @doc \"\"\"\n Check whether an email's params are equal to the ones provided.\n\n Must be used with the `Bamboo.TestAdapter` or this will never pass. In case you\n are delivering from another process, the assertion waits up to 100ms before\n failing. Typically if an email is successfully delivered the assertion will\n pass instantly, so test suites will remain fast.\n\n ## Examples\n\n email = Bamboo.Email.new_email(subject: \"something\")\n email |> MyApp.Mailer.deliver\n assert_email_delivered_with(subject: \"something\") # Will pass\n\n unsent_email = Bamboo.Email.new_email(subject: \"something else\")\n assert_email_delivered_with(subject: \"something else\") # Will fail\n\n You can also pass a regex to match portions of an email.\n\n ## Example\n\n email = new_email(text_body: \"I love coffee\")\n assert_email_delivered_with(email, text_body: ~r\/love\/) # Will pass\n assert_email_delivered_with(email, text_body: ~r\/like\/) # Will fail\n \"\"\"\n defmacro assert_email_delivered_with(email_params) do\n quote bind_quoted: [email_params: email_params] do\n import ExUnit.Assertions\n assert_receive({:delivered_email, email}, 100, Bamboo.Test.flunk_no_emails_received)\n\n recieved_email_params = email |> Map.from_struct\n assert Enum.all?(email_params, fn({k, v}) -> do_match(recieved_email_params[k], v) end),\n Bamboo.Test.flunk_attributes_do_not_match(email_params, recieved_email_params)\n end\n end\n\n @doc false\n def do_match(value1, value2 = %Regex{}) do\n Regex.match?(value2, value1)\n end\n\n @doc false\n def do_match(value1, value2) do\n value1 == value2\n end\n\n @doc false\n def flunk_with_email_list(email) do\n if Enum.empty?(delivered_emails()) do\n flunk_no_emails_received()\n else\n flunk \"\"\"\n There were no matching emails.\n\n No emails matched:\n\n #{inspect email}\n\n Delivered emails:\n\n #{delivered_emails_as_list()}\n \"\"\"\n end\n end\n\n @doc false\n def flunk_no_emails_received do\n flunk \"\"\"\n There were 0 emails delivered to this process.\n\n If you expected an email to be sent, try these ideas:\n\n 1) Make sure you call deliver_now\/1 or deliver_later\/1 to deliver the email\n 2) Make sure you are using the Bamboo.TestAdapter\n 3) Use shared mode with Bamboo.Test. This will allow Bamboo.Test\n to work across processes: use Bamboo.Test, shared: :true\n 4) If you are writing an acceptance test through a headless browser, use\n shared mode as described in option 3.\n \"\"\"\n end\n\n @doc false\n def flunk_attributes_do_not_match(params_given, params_received) do\n \"\"\"\n The parameters given do not match.\n\n Parameters given:\n\n #{inspect params_given}\n\n Email recieved:\n\n #{inspect params_received}\n \"\"\"\n end\n\n defp delivered_emails do\n {:messages, messages} = Process.info(self(), :messages)\n\n for {:delivered_email, _} = email_message <- messages do\n email_message\n end\n end\n\n defp delivered_emails_as_list do\n delivered_emails() |> add_asterisk |> Enum.join(\"\\n\")\n end\n\n defp add_asterisk(emails) do\n Enum.map(emails, &\" * #{inspect &1}\")\n end\n\n @doc \"\"\"\n Checks that no emails were sent.\n\n If `Bamboo.Test` is used with shared mode, you must also configure a timeout\n in your test config.\n\n # Set this in your config, typically in config\/test.exs\n config :bamboo, :refute_timeout, 10\n\n The value you set is up to you. Lower values will result in faster tests,\n but may incorrectly pass if an email is delivered *after* the timeout. Often\n times 1ms is enough.\n \"\"\"\n def assert_no_emails_delivered do\n receive do\n {:delivered_email, email} -> flunk_with_unexpected_email(email)\n after\n refute_timeout() -> true\n end\n end\n\n @doc false\n def assert_no_emails_sent do\n raise \"assert_no_emails_sent\/0 has been renamed to assert_no_emails_delivered\/0\"\n end\n\n defp flunk_with_unexpected_email(email) do\n flunk \"\"\"\n Unexpectedly delivered an email when expected none to be delivered.\n\n Delivered email:\n\n #{inspect email}\n \"\"\"\n end\n\n @doc \"\"\"\n Ensures a particular email was not sent\n\n Same as `assert_delivered_email\/0`, except it checks that a particular email\n was not sent.\n\n If `Bamboo.Test` is used with shared mode, you must also configure a timeout\n in your test config.\n\n # Set this in your config, typically in config\/test.exs\n config :bamboo, :refute_timeout, 10\n\n The value you set is up to you. Lower values will result in faster tests,\n but may incorrectly pass if an email is delivered *after* the timeout. Often\n times 1ms is enough.\n \"\"\"\n def refute_delivered_email(%Bamboo.Email{} = email) do\n email = normalize_for_testing(email)\n\n receive do\n {:delivered_email, ^email} -> flunk_with_unexpected_matching_email(email)\n after\n refute_timeout() -> true\n end\n end\n\n defp flunk_with_unexpected_matching_email(email) do\n flunk \"\"\"\n Unexpectedly delivered a matching email.\n\n Matched email that was delivered:\n\n #{inspect email}\n \"\"\"\n end\n\n defp refute_timeout do\n if using_shared_mode?() do\n Application.get_env(:bamboo, :refute_timeout) || raise \"\"\"\n When using shared mode with Bamboo.Test, you must set a timeout. This\n is because an email can be delivered after the assertion is called.\n\n # Set this in your config, typically in config\/test.exs\n config :bamboo, :refute_timeout, 10\n\n The value you set is up to you. Lower values will result in faster tests,\n but may incorrectly pass if an email is delivered *after* the timeout.\n \"\"\"\n else\n 0\n end\n end\n\n defp using_shared_mode? do\n !!Application.get_env(:bamboo, :shared_test_process)\n end\n\n @doc false\n def normalize_for_testing(email) do\n email\n |> Bamboo.Mailer.normalize_addresses\n |> Bamboo.TestAdapter.clean_assigns\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"8fefea928555d6dd89a3c74bfe3ea8dce5aecaa1","subject":"Only consider this year's workshops for the participant limit","message":"Only consider this year's workshops for the participant limit\n","repos":"portosummerofcode\/psc-api","old_file":"lib\/api\/accounts\/user.ex","new_file":"lib\/api\/accounts\/user.ex","new_contents":"defmodule Api.Accounts.User do\n use Ecto.Schema\n import Ecto.Changeset\n\n alias Api.Repo\n alias Api.{Workshops.Workshop, Workshops.Attendance}\n alias Api.{Teams.Invite, Teams.Membership}\n alias Api.AICompetition.Bot\n alias Comeonin.Bcrypt\n\n @valid_attrs ~w(\n email\n name\n password\n birthday\n employment_status\n college\n company\n github_handle\n twitter_handle\n linkedin_url\n bio\n tshirt_size\n pwd_recovery_token\n pwd_recovery_token_expiration\n )a\n\n @admin_attrs @valid_attrs ++ ~w(\n role\n )a\n\n @required_attrs ~w(\n email\n )a\n\n @primary_key {:id, :binary_id, autogenerate: true}\n @foreign_key_type :binary_id\n schema \"users\" do\n field :email, :string\n field :name, :string\n field :password_hash, :string\n field :birthday, :date\n field :employment_status, :string\n field :college, :string\n field :company, :string\n field :github_handle, :string\n field :twitter_handle, :string\n field :linkedin_url, :string\n field :bio, :string\n field :role, :string, default: \"participant\"\n field :tshirt_size, :string\n field :pwd_recovery_token, :string\n field :pwd_recovery_token_expiration, :utc_datetime, default: nil\n\n timestamps()\n\n # Virtual fields\n field :password, :string, virtual: true\n\n # Associations\n has_many :invites, Invite, foreign_key: :host_id, on_delete: :delete_all\n has_many :invitations, Invite, foreign_key: :invitee_id, on_delete: :delete_all\n has_many :memberships, Membership, foreign_key: :user_id, on_delete: :delete_all\n has_many :teams, through: [:memberships, :team]\n has_many :ai_competition_bots, Bot\n\n many_to_many :workshops, Workshop, join_through: Attendance, on_delete: :delete_all\n end\n\n def changeset(struct, params \\\\ %{}), do: _cs(struct, params, @valid_attrs)\n def participant_changeset(struct, params \\\\ %{}), do: _cs(struct, params, @valid_attrs)\n def admin_changeset(struct, params \\\\ %{}), do: _cs(struct, params, @admin_attrs)\n defp _cs(struct, params, attrs) do\n struct\n |> cast(params, attrs)\n |> validate_required(@required_attrs)\n |> validate_length(:email, min: 1, max: 255)\n |> validate_format(:email, ~r\/@\/)\n |> unique_constraint(:email)\n |> unique_constraint(:password_recovery_token)\n end\n\n def registration_changeset(struct, params \\\\ %{}) do\n struct\n |> changeset(params)\n |> validate_required(~w(password)a)\n |> validate_length(:password, min: 6)\n |> hash_password\n end\n\n defp hash_password(%{valid?: false} = changeset), do: changeset\n defp hash_password(%{valid?: true} = changeset) do\n hashed_password =\n changeset\n |> get_field(:password)\n |> Bcrypt.hashpwsalt()\n\n changeset\n |> put_change(:password_hash, hashed_password)\n end\n\n # gravatar hash\n def gravatar_hash(%{email: email}),\n do: :crypto.hash(:md5, String.trim(email)) |> Base.encode16(case: :lower)\n\n def display_name(%{name: name, email: email}) do\n name || (email |> String.split(\"@\") |> Enum.at(0))\n end\n\n def can_apply_to_workshops(user) do\n user = Repo.preload(user, [:workshops, :teams])\n\n (Enum.any?(\n user.teams, fn team -> team.applied == true &&\n end) && Enum.count(user.workshops, fn(w) -> w.year == DateTime.utc_now.year end) < 2) || true\n end\n\n def can_apply_to_hackathon(user) do\n user = Repo.preload(user, :workshops)\n\n Enum.count(user.workshops, fn(w) -> w.year == DateTime.utc_now.year end) <= 2\n end\n\n # generate password recovery token\n def generate_token(length \\\\ 32) do\n :crypto.strong_rand_bytes(length)\n |> Base.url_encode64\n |> binary_part(0, length)\n end\n\n def calculate_token_expiration do\n :erlang.universaltime\n |> :calendar.datetime_to_gregorian_seconds\n |> Kernel.+(30 * 60)\n |> DateTime.from_unix!\n end\n\n # def able_to_vote(at \\\\ nil) do\n # at = at || DateTime.utc_now\n\n # from(\n # u in User,\n # left_join: tm in assoc(u, :teams),\n # left_join: t in assoc(tm, :team),\n # where: u.role == \"participant\",\n # where: is_nil(t.disqualified_at) or t.disqualified_at > ^at,\n # )\n # end\nend\n","old_contents":"defmodule Api.Accounts.User do\n use Ecto.Schema\n import Ecto.Changeset\n\n alias Api.Repo\n alias Api.{Workshops.Workshop, Workshops.Attendance}\n alias Api.{Teams.Invite, Teams.Membership}\n alias Api.AICompetition.Bot\n alias Comeonin.Bcrypt\n\n @valid_attrs ~w(\n email\n name\n password\n birthday\n employment_status\n college\n company\n github_handle\n twitter_handle\n linkedin_url\n bio\n tshirt_size\n pwd_recovery_token\n pwd_recovery_token_expiration\n )a\n\n @admin_attrs @valid_attrs ++ ~w(\n role\n )a\n\n @required_attrs ~w(\n email\n )a\n\n @primary_key {:id, :binary_id, autogenerate: true}\n @foreign_key_type :binary_id\n schema \"users\" do\n field :email, :string\n field :name, :string\n field :password_hash, :string\n field :birthday, :date\n field :employment_status, :string\n field :college, :string\n field :company, :string\n field :github_handle, :string\n field :twitter_handle, :string\n field :linkedin_url, :string\n field :bio, :string\n field :role, :string, default: \"participant\"\n field :tshirt_size, :string\n field :pwd_recovery_token, :string\n field :pwd_recovery_token_expiration, :utc_datetime, default: nil\n\n timestamps()\n\n # Virtual fields\n field :password, :string, virtual: true\n\n # Associations\n has_many :invites, Invite, foreign_key: :host_id, on_delete: :delete_all\n has_many :invitations, Invite, foreign_key: :invitee_id, on_delete: :delete_all\n has_many :memberships, Membership, foreign_key: :user_id, on_delete: :delete_all\n has_many :teams, through: [:memberships, :team]\n has_many :ai_competition_bots, Bot\n\n many_to_many :workshops, Workshop, join_through: Attendance, on_delete: :delete_all\n end\n\n def changeset(struct, params \\\\ %{}), do: _cs(struct, params, @valid_attrs)\n def participant_changeset(struct, params \\\\ %{}), do: _cs(struct, params, @valid_attrs)\n def admin_changeset(struct, params \\\\ %{}), do: _cs(struct, params, @admin_attrs)\n defp _cs(struct, params, attrs) do\n struct\n |> cast(params, attrs)\n |> validate_required(@required_attrs)\n |> validate_length(:email, min: 1, max: 255)\n |> validate_format(:email, ~r\/@\/)\n |> unique_constraint(:email)\n |> unique_constraint(:password_recovery_token)\n end\n\n def registration_changeset(struct, params \\\\ %{}) do\n struct\n |> changeset(params)\n |> validate_required(~w(password)a)\n |> validate_length(:password, min: 6)\n |> hash_password\n end\n\n defp hash_password(%{valid?: false} = changeset), do: changeset\n defp hash_password(%{valid?: true} = changeset) do\n hashed_password =\n changeset\n |> get_field(:password)\n |> Bcrypt.hashpwsalt()\n\n changeset\n |> put_change(:password_hash, hashed_password)\n end\n\n # gravatar hash\n def gravatar_hash(%{email: email}),\n do: :crypto.hash(:md5, String.trim(email)) |> Base.encode16(case: :lower)\n\n def display_name(%{name: name, email: email}) do\n name || (email |> String.split(\"@\") |> Enum.at(0))\n end\n\n def can_apply_to_workshops(user) do\n user = Repo.preload(user, [:workshops, :teams])\n\n (Enum.any?(\n user.teams, fn team -> team.applied == true\n end) && Enum.count(user.workshops) < 2) || true\n end\n\n def can_apply_to_hackathon(user) do\n user = Repo.preload(user, :workshops)\n\n Enum.count(user.workshops) <= 2\n end\n\n # generate password recovery token\n def generate_token(length \\\\ 32) do\n :crypto.strong_rand_bytes(length)\n |> Base.url_encode64\n |> binary_part(0, length)\n end\n\n def calculate_token_expiration do\n :erlang.universaltime\n |> :calendar.datetime_to_gregorian_seconds\n |> Kernel.+(30 * 60)\n |> DateTime.from_unix!\n end\n\n # def able_to_vote(at \\\\ nil) do\n # at = at || DateTime.utc_now\n\n # from(\n # u in User,\n # left_join: tm in assoc(u, :teams),\n # left_join: t in assoc(tm, :team),\n # where: u.role == \"participant\",\n # where: is_nil(t.disqualified_at) or t.disqualified_at > ^at,\n # )\n # end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"4ce2195c626212440ba4d7b4f8714d3c2054b159","subject":"fix: Previous version bumps should not trigger minor changes","message":"fix: Previous version bumps should not trigger minor changes\n\n","repos":"googleapis\/elixir-google-api,googleapis\/elixir-google-api,googleapis\/elixir-google-api","old_file":"lib\/google_apis\/change_analyzer.ex","new_file":"lib\/google_apis\/change_analyzer.ex","new_contents":"# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\ndefmodule GoogleApis.ChangeAnalyzer do\n @moduledoc \"\"\"\n Analyzes the current git diff and determines what kind of changes have been\n made. This information can be used to determine what type of version bump\n should accompany the change.\n \"\"\"\n\n alias GoogleApis.ApiConfig\n\n require Logger\n\n @doc \"\"\"\n Analyzes the git diff for the given API, and determines whether any of the\n changes are actual significant changes as opposed to documentation, comment,\n or formatting.\n \"\"\"\n def has_significant_changes?(api_config) do\n dir = ApiConfig.library_directory(api_config)\n {only_modified, files} = check_git_status(dir)\n if only_modified do\n Enum.any?(files, &file_has_significant_changes?\/1)\n else\n true\n end\n end\n\n defp check_git_status(dir) do\n case System.cmd(\"git\", [\"status\", \"--porcelain\"]) do\n {results, 0} ->\n results\n |> String.split(\"\\n\", trim: true)\n |> Enum.reduce({true, []}, fn\n (_, {false, _}) ->\n {false, []}\n (line, {true, files}) ->\n case Regex.run(~r{^ M (\\S+)}, line) do\n [_, file] ->\n if String.starts_with?(Path.expand(file), dir) do\n {true, [file | files]}\n else\n {true, files}\n end\n nil ->\n {false, []}\n end\n end)\n _ ->\n Logger.error(\"Change analyzer: git status failed!\")\n {false, []}\n end\n end\n\n @elixir_source_extensions [\".ex\", \".exs\"]\n @non_significant_files [\"synth.metadata\", \"README.md\"]\n\n defp file_has_significant_changes?(file) do\n cond do\n Enum.member?(@elixir_source_extensions, Path.extname(file)) ->\n elixir_file_has_significant_changes?(file)\n Enum.member?(@non_significant_files, Path.basename(file)) ->\n false\n true ->\n true\n end\n end\n\n defp elixir_file_has_significant_changes?(file) do\n with {old_content, 0} <- System.cmd(\"git\", [\"show\", \"HEAD:#{file}\"]),\n {:ok, new_content} <- File.read(file) do\n elixir_content_has_significant_changes?(old_content, new_content, file)\n else\n {:error, _} ->\n Logger.error(\"Change analyzer: could not read file #{file}\")\n true\n _ ->\n Logger.error(\"Change analyzer: git show failed for file #{file}\")\n true\n end\n end\n\n defp elixir_content_has_significant_changes?(old_content, new_content, file) do\n with {:old, {:ok, old_ast}} <- {:old, Code.string_to_quoted(old_content)},\n {:new, {:ok, new_ast}} <- {:new, Code.string_to_quoted(new_content)} do\n elixir_ast_has_significant_changes?(old_ast, new_ast, Path.basename(file))\n else\n {:old, _} ->\n Logger.error(\"Change analyzer: parse of pre-change #{file} failed!\")\n true\n {:new, _} ->\n Logger.error(\"Change analyzer: parse of post-change #{file} failed!\")\n true\n end\n end\n\n defp elixir_ast_has_significant_changes?(old_ast, new_ast, basename) do\n strip_trivial_ast(old_ast, basename) != strip_trivial_ast(new_ast, basename)\n end\n\n defp strip_trivial_ast({:@, _, [{:doc, _, [str]}]}, _) when is_binary(str) do\n {:@, [], [{:doc, [], [\".\"]}]}\n end\n\n defp strip_trivial_ast({:@, _, [{:moduledoc, _, [str]}]}, _) when is_binary(str) do\n {:@, [], [{:moduledoc, [], [\".\"]}]}\n end\n\n defp strip_trivial_ast({:@, _, [{:version, _, [str]}]}, \"mix.exs\") when is_binary(str) do\n {:@, [], [{:version, [], [\".\"]}]}\n end\n\n defp strip_trivial_ast({name, _, args}, basename) do\n {strip_trivial_ast(name, basename), [], strip_trivial_ast(args, basename)}\n end\n\n defp strip_trivial_ast(list, basename) when is_list(list) do\n Enum.map(list, &(strip_trivial_ast(&1, basename)))\n end\n\n defp strip_trivial_ast({key, value}, basename) do\n {strip_trivial_ast(key, basename), strip_trivial_ast(value, basename)}\n end\n\n defp strip_trivial_ast(term, _) do\n term\n end\nend\n","old_contents":"# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\ndefmodule GoogleApis.ChangeAnalyzer do\n @moduledoc \"\"\"\n Analyzes the current git diff and determines what kind of changes have been\n made. This information can be used to determine what type of version bump\n should accompany the change.\n \"\"\"\n\n alias GoogleApis.ApiConfig\n\n require Logger\n\n @doc \"\"\"\n Analyzes the git diff for the given API, and determines whether any of the\n changes are actual significant changes as opposed to documentation, comment,\n or formatting.\n \"\"\"\n def has_significant_changes?(api_config) do\n dir = ApiConfig.library_directory(api_config)\n {only_modified, files} = check_git_status(dir)\n if only_modified do\n Enum.any?(files, &file_has_significant_changes?\/1)\n else\n true\n end\n end\n\n defp check_git_status(dir) do\n case System.cmd(\"git\", [\"status\", \"--porcelain\"]) do\n {results, 0} ->\n results\n |> String.split(\"\\n\", trim: true)\n |> Enum.reduce({true, []}, fn\n (_, {false, _}) ->\n {false, []}\n (line, {true, files}) ->\n case Regex.run(~r{^ M (\\S+)}, line) do\n [_, file] ->\n if String.starts_with?(Path.expand(file), dir) do\n {true, [file | files]}\n else\n {true, files}\n end\n nil ->\n {false, []}\n end\n end)\n _ ->\n Logger.error(\"Change analyzer: git status failed!\")\n {false, []}\n end\n end\n\n @elixir_source_extensions [\".ex\", \".exs\"]\n @non_significant_files [\"synth.metadata\", \"README.md\"]\n\n defp file_has_significant_changes?(file) do\n cond do\n Enum.member?(@elixir_source_extensions, Path.extname(file)) ->\n elixir_file_has_significant_changes?(file)\n Enum.member?(@non_significant_files, Path.basename(file)) ->\n false\n true ->\n true\n end\n end\n\n defp elixir_file_has_significant_changes?(file) do\n with {old_content, 0} <- System.cmd(\"git\", [\"show\", \"HEAD:#{file}\"]),\n {:ok, new_content} <- File.read(file) do\n elixir_content_has_significant_changes?(old_content, new_content, file)\n else\n {:error, _} ->\n Logger.error(\"Change analyzer: could not read file #{file}\")\n true\n _ ->\n Logger.error(\"Change analyzer: git show failed for file #{file}\")\n true\n end\n end\n\n defp elixir_content_has_significant_changes?(old_content, new_content, file) do\n with {:old, {:ok, old_ast}} <- {:old, Code.string_to_quoted(old_content)},\n {:new, {:ok, new_ast}} <- {:new, Code.string_to_quoted(new_content)} do\n elixir_ast_has_significant_changes?(old_ast, new_ast)\n else\n {:old, _} ->\n Logger.error(\"Change analyzer: parse of pre-change #{file} failed!\")\n true\n {:new, _} ->\n Logger.error(\"Change analyzer: parse of post-change #{file} failed!\")\n true\n end\n end\n\n defp elixir_ast_has_significant_changes?(old_ast, new_ast) do\n strip_trivial_ast(old_ast) != strip_trivial_ast(new_ast)\n end\n\n defp strip_trivial_ast({:@, _, [{:doc, _, [str]}]}) when is_binary(str) do\n {:@, [], [{:doc, [], [\".\"]}]}\n end\n\n defp strip_trivial_ast({:@, _, [{:moduledoc, _, [str]}]}) when is_binary(str) do\n {:@, [], [{:moduledoc, [], [\".\"]}]}\n end\n\n defp strip_trivial_ast({name, _, args}) do\n {strip_trivial_ast(name), [], strip_trivial_ast(args)}\n end\n\n defp strip_trivial_ast(list) when is_list(list) do\n Enum.map(list, &strip_trivial_ast\/1)\n end\n\n defp strip_trivial_ast({key, value}) do\n {strip_trivial_ast(key), strip_trivial_ast(value)}\n end\n\n defp strip_trivial_ast(term) do\n term\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"1c8aeda0cb1d1bf23372fff40376f898e0f427b7","subject":"Add head for GenServer.whereis\/1 to match spec","message":"Add head for GenServer.whereis\/1 to match spec\n","repos":"ggcampinho\/elixir,lexmag\/elixir,gfvcastro\/elixir,beedub\/elixir,kelvinst\/elixir,antipax\/elixir,kelvinst\/elixir,joshprice\/elixir,kimshrier\/elixir,gfvcastro\/elixir,michalmuskala\/elixir,pedrosnk\/elixir,ggcampinho\/elixir,lexmag\/elixir,kimshrier\/elixir,elixir-lang\/elixir,beedub\/elixir,pedrosnk\/elixir,antipax\/elixir","old_file":"lib\/elixir\/lib\/gen_server.ex","new_file":"lib\/elixir\/lib\/gen_server.ex","new_contents":"defmodule GenServer do\n @moduledoc \"\"\"\n A behaviour module for implementing the server of a client-server relation.\n\n A GenServer is a process like any other Elixir process and it can be used\n to keep state, execute code asynchronously and so on. The advantage of using\n a generic server process (GenServer) implemented using this module is that it\n will have a standard set of interface functions and include functionality for\n tracing and error reporting. It will also fit into a supervision tree.\n\n ## Example\n\n The GenServer behaviour abstracts the common client-server interaction.\n Developers are only required to implement the callbacks and functionality they are\n interested in.\n\n Let's start with a code example and then explore the available callbacks.\n Imagine we want a GenServer that works like a stack, allowing us to push\n and pop items:\n\n defmodule Stack do\n use GenServer\n\n # Callbacks\n\n def handle_call(:pop, _from, [h | t]) do\n {:reply, h, t}\n end\n\n def handle_cast({:push, item}, state) do\n {:noreply, [item | state]}\n end\n end\n\n # Start the server\n {:ok, pid} = GenServer.start_link(Stack, [:hello])\n\n # This is the client\n GenServer.call(pid, :pop)\n #=> :hello\n\n GenServer.cast(pid, {:push, :world})\n #=> :ok\n\n GenServer.call(pid, :pop)\n #=> :world\n\n We start our `Stack` by calling `start_link\/3`, passing the module\n with the server implementation and its initial argument (a list\n representing the stack containing the item `:hello`). We can primarily\n interact with the server by sending two types of messages. **call**\n messages expect a reply from the server (and are therefore synchronous)\n while **cast** messages do not.\n\n Every time you do a `GenServer.call\/3`, the client will send a message\n that must be handled by the `c:handle_call\/3` callback in the GenServer.\n A `cast\/2` message must be handled by `c:handle_cast\/2`.\n\n ## Callbacks\n\n There are 6 callbacks required to be implemented in a `GenServer`. By\n adding `use GenServer` to your module, Elixir will automatically define\n all 6 callbacks for you, leaving it up to you to implement the ones\n you want to customize.\n\n ## Name Registration\n\n Both `start_link\/3` and `start\/3` support the `GenServer` to register\n a name on start via the `:name` option. Registered names are also\n automatically cleaned up on termination. The supported values are:\n\n * an atom - the GenServer is registered locally with the given name\n using `Process.register\/2`.\n\n * `{:global, term}`- the GenServer is registered globally with the given\n term using the functions in the [`:global` module](http:\/\/www.erlang.org\/doc\/man\/global.html).\n\n * `{:via, module, term}` - the GenServer is registered with the given\n mechanism and name. The `:via` option expects a module that exports\n `register_name\/2`, `unregister_name\/1`, `whereis_name\/1` and `send\/2`.\n One such example is the [`:global` module](http:\/\/www.erlang.org\/doc\/man\/global.html) which uses these functions\n for keeping the list of names of processes and their associated PIDs\n that are available globally for a network of Elixir nodes. Elixir also\n ships with a local, decentralized and scalable registry called `Registry`\n for locally storing names that are generated dynamically.\n\n For example, we could start and register our `Stack` server locally as follows:\n\n # Start the server and register it locally with name MyStack\n {:ok, _} = GenServer.start_link(Stack, [:hello], name: MyStack)\n\n # Now messages can be sent directly to MyStack\n GenServer.call(MyStack, :pop) #=> :hello\n\n Once the server is started, the remaining functions in this module (`call\/3`,\n `cast\/2`, and friends) will also accept an atom, or any `:global` or `:via`\n tuples. In general, the following formats are supported:\n\n * a `pid`\n * an `atom` if the server is locally registered\n * `{atom, node}` if the server is locally registered at another node\n * `{:global, term}` if the server is globally registered\n * `{:via, module, name}` if the server is registered through an alternative\n registry\n\n If there is an interest to register dynamic names locally, do not use\n atoms, as atoms are never garbage collected and therefore dynamically\n generated atoms won't be garbage collected. For such cases, you can\n set up your own local registry by using the `Registry` module.\n\n ## Client \/ Server APIs\n\n Although in the example above we have used `GenServer.start_link\/3` and\n friends to directly start and communicate with the server, most of the\n time we don't call the `GenServer` functions directly. Instead, we wrap\n the calls in new functions representing the public API of the server.\n\n Here is a better implementation of our Stack module:\n\n defmodule Stack do\n use GenServer\n\n # Client\n\n def start_link(default) do\n GenServer.start_link(__MODULE__, default)\n end\n\n def push(pid, item) do\n GenServer.cast(pid, {:push, item})\n end\n\n def pop(pid) do\n GenServer.call(pid, :pop)\n end\n\n # Server (callbacks)\n\n def handle_call(:pop, _from, [h | t]) do\n {:reply, h, t}\n end\n\n def handle_call(request, from, state) do\n # Call the default implementation from GenServer\n super(request, from, state)\n end\n\n def handle_cast({:push, item}, state) do\n {:noreply, [item | state]}\n end\n\n def handle_cast(request, state) do\n super(request, state)\n end\n end\n\n In practice, it is common to have both server and client functions in\n the same module. If the server and\/or client implementations are growing\n complex, you may want to have them in different modules.\n\n ## Receiving \"regular\" messages\n\n The goal of a `GenServer` is to abstract the \"receive\" loop for developers,\n automatically handling system messages, support code change, synchronous\n calls and more. Therefore, you should never call your own \"receive\" inside\n the GenServer callbacks as doing so will cause the GenServer to misbehave.\n\n Besides the synchronous and asynchronous communication provided by `call\/3`\n and `cast\/2`, \"regular\" messages sent by functions such `Kernel.send\/2`,\n `Process.send_after\/4` and similar, can be handled inside the `c:handle_info\/2`\n callback.\n\n `c:handle_info\/2` can be used in many situations, such as handling monitor\n DOWN messages sent by `Process.monitor\/1`. Another use case for `c:handle_info\/2`\n is to perform periodic work, with the help of `Process.send_after\/4`:\n\n defmodule MyApp.Periodically do\n use GenServer\n\n def start_link do\n GenServer.start_link(__MODULE__, %{})\n end\n\n def init(state) do\n schedule_work() # Schedule work to be performed on start\n {:ok, state}\n end\n\n def handle_info(:work, state) do\n # Do the desired work here\n schedule_work() # Reschedule once more\n {:noreply, state}\n end\n\n defp schedule_work() do\n Process.send_after(self(), :work, 2 * 60 * 60 * 1000) # In 2 hours\n end\n end\n\n ## Debugging with the :sys module\n\n GenServers, as [special processes](http:\/\/erlang.org\/doc\/design_principles\/spec_proc.html),\n can be debugged using the [`:sys` module](http:\/\/www.erlang.org\/doc\/man\/sys.html). Through various hooks, this module\n allows developers to introspect the state of the process and trace\n system events that happen during its execution, such as received messages,\n sent replies and state changes.\n\n Let's explore the basic functions from the [`:sys` module](http:\/\/www.erlang.org\/doc\/man\/sys.html) used for debugging:\n\n * [`:sys.get_state\/2`](http:\/\/erlang.org\/doc\/man\/sys.html#get_state-2) -\n allows retrieval of the state of the process. In the case of\n a GenServer process, it will be the callback module state, as\n passed into the callback functions as last argument.\n * [`:sys.get_status\/2`](http:\/\/erlang.org\/doc\/man\/sys.html#get_status-2) -\n allows retrieval of the status of the process. This status includes\n the process dictionary, if the process is running or is suspended,\n the parent PID, the debugger state, and the state of the behaviour module,\n which includes the callback module state (as returned by `:sys.get_state\/2`).\n It's possible to change how this status is represented by defining\n the optional `c:GenServer.format_status\/2` callback.\n * [`:sys.trace\/3`](http:\/\/erlang.org\/doc\/man\/sys.html#trace-3) -\n prints all the system events to `:stdio`.\n * [`:sys.statistics\/3`](http:\/\/erlang.org\/doc\/man\/sys.html#statistics-3) -\n manages collection of process statistics.\n * [`:sys.no_debug\/2`](http:\/\/erlang.org\/doc\/man\/sys.html#no_debug-2) -\n turns off all debug handlers for the given process. It is very important\n to switch off debugging once we're done. Excessive debug handlers or\n those that should be turned off, but weren't, can seriously damage\n the performance of the system.\n * [`:sys.suspend\/2`](http:\/\/erlang.org\/doc\/man\/sys.html#suspend-2) - allows\n to suspend a process so that it only replies to system messages but no\n other messages. A suspended process can be reactivated via\n [`:sys.resume\/2`](http:\/\/erlang.org\/doc\/man\/sys.html#resume-2).\n\n Let's see how we could use those functions for debugging the stack server\n we defined earlier.\n\n iex> {:ok, pid} = Stack.start_link([])\n iex> :sys.statistics(pid, true) # turn on collecting process statistics\n iex> :sys.trace(pid, true) # turn on event printing\n iex> Stack.push(pid, 1)\n *DBG* <0.122.0> got cast {push,1}\n *DBG* <0.122.0> new state [1]\n :ok\n iex> :sys.get_state(pid)\n [1]\n iex> Stack.pop(pid)\n *DBG* <0.122.0> got call pop from <0.80.0>\n *DBG* <0.122.0> sent 1 to <0.80.0>, new state []\n 1\n iex> :sys.statistics(pid, :get)\n {:ok,\n [start_time: {{2016, 7, 16}, {12, 29, 41}},\n current_time: {{2016, 7, 16}, {12, 29, 50}},\n reductions: 117, messages_in: 2, messages_out: 0]}\n iex> :sys.no_debug(pid) # turn off all debug handlers\n :ok\n iex> :sys.get_status(pid)\n {:status, #PID<0.122.0>, {:module, :gen_server},\n [[\"$initial_call\": {Stack, :init, 1}, # pdict\n \"$ancestors\": [#PID<0.80.0>, #PID<0.51.0>]],\n :running, # :running | :suspended\n #PID<0.80.0>, # parent\n [], # debugger state\n [header: 'Status for generic server <0.122.0>', # module status\n data: [{'Status', :running}, {'Parent', #PID<0.80.0>},\n {'Logged events', []}], data: [{'State', [1]}]]]}\n\n ## Learn more\n\n If you wish to find out more about gen servers, the Elixir Getting Started\n guide provides a tutorial-like introduction. The documentation and links\n in Erlang can also provide extra insight.\n\n * [GenServer \u2013 Elixir's Getting Started Guide](http:\/\/elixir-lang.org\/getting-started\/mix-otp\/genserver.html)\n * [`:gen_server` module documentation](http:\/\/www.erlang.org\/doc\/man\/gen_server.html)\n * [gen_server Behaviour \u2013 OTP Design Principles](http:\/\/www.erlang.org\/doc\/design_principles\/gen_server_concepts.html)\n * [Clients and Servers \u2013 Learn You Some Erlang for Great Good!](http:\/\/learnyousomeerlang.com\/clients-and-servers)\n \"\"\"\n\n @doc \"\"\"\n Invoked when the server is started. `start_link\/3` or `start\/3` will\n block until it returns.\n\n `args` is the argument term (second argument) passed to `start_link\/3`.\n\n Returning `{:ok, state}` will cause `start_link\/3` to return\n `{:ok, pid}` and the process to enter its loop.\n\n Returning `{:ok, state, timeout}` is similar to `{:ok, state}`\n except `handle_info(:timeout, state)` will be called after `timeout`\n milliseconds if no messages are received within the timeout.\n\n Returning `{:ok, state, :hibernate}` is similar to\n `{:ok, state}` except the process is hibernated before entering the loop. See\n `c:handle_call\/3` for more information on hibernation.\n\n Returning `:ignore` will cause `start_link\/3` to return `:ignore` and the\n process will exit normally without entering the loop or calling `c:terminate\/2`.\n If used when part of a supervision tree the parent supervisor will not fail\n to start nor immediately try to restart the `GenServer`. The remainder of the\n supervision tree will be (re)started and so the `GenServer` should not be\n required by other processes. It can be started later with\n `Supervisor.restart_child\/2` as the child specification is saved in the parent\n supervisor. The main use cases for this are:\n\n * The `GenServer` is disabled by configuration but might be enabled later.\n * An error occurred and it will be handled by a different mechanism than the\n `Supervisor`. Likely this approach involves calling `Supervisor.restart_child\/2`\n after a delay to attempt a restart.\n\n Returning `{:stop, reason}` will cause `start_link\/3` to return\n `{:error, reason}` and the process to exit with reason `reason` without\n entering the loop or calling `c:terminate\/2`.\n \"\"\"\n @callback init(args :: term) ::\n {:ok, state} |\n {:ok, state, timeout | :hibernate} |\n :ignore |\n {:stop, reason :: any} when state: any\n\n @doc \"\"\"\n Invoked to handle synchronous `call\/3` messages. `call\/3` will block until a\n reply is received (unless the call times out or nodes are disconnected).\n\n `request` is the request message sent by a `call\/3`, `from` is a 2-tuple\n containing the caller's PID and a term that uniquely identifies the call, and\n `state` is the current state of the `GenServer`.\n\n Returning `{:reply, reply, new_state}` sends the response `reply` to the\n caller and continues the loop with new state `new_state`.\n\n Returning `{:reply, reply, new_state, timeout}` is similar to\n `{:reply, reply, new_state}` except `handle_info(:timeout, new_state)` will be\n called after `timeout` milliseconds if no messages are received.\n\n Returning `{:reply, reply, new_state, :hibernate}` is similar to\n `{:reply, reply, new_state}` except the process is hibernated and will\n continue the loop once a message is in its message queue. If a message is\n already in the message queue this will be immediately. Hibernating a\n `GenServer` causes garbage collection and leaves a continuous heap that\n minimises the memory used by the process.\n\n Hibernating should not be used aggressively as too much time could be spent\n garbage collecting. Normally it should only be used when a message is not\n expected soon and minimising the memory of the process is shown to be\n beneficial.\n\n Returning `{:noreply, new_state}` does not send a response to the caller and\n continues the loop with new state `new_state`. The response must be sent with\n `reply\/2`.\n\n There are three main use cases for not replying using the return value:\n\n * To reply before returning from the callback because the response is known\n before calling a slow function.\n * To reply after returning from the callback because the response is not yet\n available.\n * To reply from another process, such as a task.\n\n When replying from another process the `GenServer` should exit if the other\n process exits without replying as the caller will be blocking awaiting a\n reply.\n\n Returning `{:noreply, new_state, timeout | :hibernate}` is similar to\n `{:noreply, new_state}` except a timeout or hibernation occurs as with a\n `:reply` tuple.\n\n Returning `{:stop, reason, reply, new_state}` stops the loop and `c:terminate\/2`\n is called with reason `reason` and state `new_state`. Then the `reply` is sent\n as the response to call and the process exits with reason `reason`.\n\n Returning `{:stop, reason, new_state}` is similar to\n `{:stop, reason, reply, new_state}` except a reply is not sent.\n\n If this callback is not implemented, the default implementation by\n `use GenServer` will return `{:stop, {:bad_call, request}, state}`.\n \"\"\"\n @callback handle_call(request :: term, from, state :: term) ::\n {:reply, reply, new_state} |\n {:reply, reply, new_state, timeout | :hibernate} |\n {:noreply, new_state} |\n {:noreply, new_state, timeout | :hibernate} |\n {:stop, reason, reply, new_state} |\n {:stop, reason, new_state} when reply: term, new_state: term, reason: term\n\n @doc \"\"\"\n Invoked to handle asynchronous `cast\/2` messages.\n\n `request` is the request message sent by a `cast\/2` and `state` is the current\n state of the `GenServer`.\n\n Returning `{:noreply, new_state}` continues the loop with new state `new_state`.\n\n Returning `{:noreply, new_state, timeout}` is similar to\n `{:noreply, new_state}` except `handle_info(:timeout, new_state)` will be\n called after `timeout` milliseconds if no messages are received.\n\n Returning `{:noreply, new_state, :hibernate}` is similar to\n `{:noreply, new_state}` except the process is hibernated before continuing the\n loop. See `c:handle_call\/3` for more information.\n\n Returning `{:stop, reason, new_state}` stops the loop and `c:terminate\/2` is\n called with the reason `reason` and state `new_state`. The process exits with\n reason `reason`.\n\n If this callback is not implemented, the default implementation by\n `use GenServer` will return `{:stop, {:bad_cast, request}, state}`.\n \"\"\"\n @callback handle_cast(request :: term, state :: term) ::\n {:noreply, new_state} |\n {:noreply, new_state, timeout | :hibernate} |\n {:stop, reason :: term, new_state} when new_state: term\n\n @doc \"\"\"\n Invoked to handle all other messages.\n\n `msg` is the message and `state` is the current state of the `GenServer`. When\n a timeout occurs the message is `:timeout`.\n\n Return values are the same as `c:handle_cast\/2`.\n\n If this callback is not implemented, the default implementation by\n `use GenServer` will return `{:noreply, state}`.\n \"\"\"\n @callback handle_info(msg :: :timeout | term, state :: term) ::\n {:noreply, new_state} |\n {:noreply, new_state, timeout | :hibernate} |\n {:stop, reason :: term, new_state} when new_state: term\n\n @doc \"\"\"\n Invoked when the server is about to exit. It should do any cleanup required.\n\n `reason` is exit reason and `state` is the current state of the `GenServer`.\n The return value is ignored.\n\n `c:terminate\/2` is called if a callback (except `c:init\/1`) does one of the\n following:\n\n * returns a `:stop` tuple\n * raises\n * calls `Kernel.exit\/1`\n * returns an invalid value\n * the `GenServer` traps exits (using `Process.flag\/2`) *and* the parent\n process sends an exit signal\n\n If part of a supervision tree, a `GenServer`'s `Supervisor` will send an exit\n signal when shutting it down. The exit signal is based on the shutdown\n strategy in the child's specification. If it is `:brutal_kill` the `GenServer`\n is killed and so `c:terminate\/2` is not called. However if it is a timeout the\n `Supervisor` will send the exit signal `:shutdown` and the `GenServer` will\n have the duration of the timeout to call `c:terminate\/2` - if the process is\n still alive after the timeout it is killed.\n\n If the `GenServer` receives an exit signal (that is not `:normal`) from any\n process when it is not trapping exits it will exit abruptly with the same\n reason and so not call `c:terminate\/2`. Note that a process does *NOT* trap\n exits by default and an exit signal is sent when a linked process exits or its\n node is disconnected.\n\n Therefore it is not guaranteed that `c:terminate\/2` is called when a `GenServer`\n exits. For such reasons, we usually recommend important clean-up rules to\n happen in separated processes either by use of monitoring or by links\n themselves. For example if the `GenServer` controls a `port` (e.g.\n `:gen_tcp.socket`) or `t:File.io_device\/0`, they will be closed on receiving a\n `GenServer`'s exit signal and do not need to be closed in `c:terminate\/2`.\n\n If `reason` is not `:normal`, `:shutdown`, nor `{:shutdown, term}` an error is\n logged.\n \"\"\"\n @callback terminate(reason, state :: term) ::\n term when reason: :normal | :shutdown | {:shutdown, term} | term\n\n @doc \"\"\"\n Invoked to change the state of the `GenServer` when a different version of a\n module is loaded (hot code swapping) and the state's term structure should be\n changed.\n\n `old_vsn` is the previous version of the module (defined by the `@vsn`\n attribute) when upgrading. When downgrading the previous version is wrapped in\n a 2-tuple with first element `:down`. `state` is the current state of the\n `GenServer` and `extra` is any extra data required to change the state.\n\n Returning `{:ok, new_state}` changes the state to `new_state` and the code\n change is successful.\n\n Returning `{:error, reason}` fails the code change with reason `reason` and\n the state remains as the previous state.\n\n If `c:code_change\/3` raises the code change fails and the loop will continue\n with its previous state. Therefore this callback does not usually contain side effects.\n \"\"\"\n @callback code_change(old_vsn, state :: term, extra :: term) ::\n {:ok, new_state :: term} |\n {:error, reason :: term} when old_vsn: term | {:down, term}\n\n @doc \"\"\"\n Invoked in some cases to retrieve a formatted version of the `GenServer` status.\n\n This callback can be useful to control the *appearance* of the status of the\n `GenServer`. For example, it can be used to return a compact representation of\n the `GenServer`'s state to avoid having large state terms printed.\n\n * one of `:sys.get_status\/1` or `:sys.get_status\/2` is invoked to get the\n status of the `GenServer`; in such cases, `reason` is `:normal`\n\n * the `GenServer` terminates abnormally and logs an error; in such cases,\n `reason` is `:terminate`\n\n `pdict_and_state` is a two-elements list `[pdict, state]` where `pdict` is a\n list of `{key, value}` tuples representing the current process dictionary of\n the `GenServer` and `state` is the current state of the `GenServer`.\n \"\"\"\n @callback format_status(reason, pdict_and_state :: list) ::\n term when reason: :normal | :terminate\n\n @optional_callbacks format_status: 2\n\n @typedoc \"Return values of `start*` functions\"\n @type on_start :: {:ok, pid} | :ignore | {:error, {:already_started, pid} | term}\n\n @typedoc \"The GenServer name\"\n @type name :: atom | {:global, term} | {:via, module, term}\n\n @typedoc \"Options used by the `start*` functions\"\n @type options :: [option]\n\n @typedoc \"Option values used by the `start*` functions\"\n @type option :: {:debug, debug} |\n {:name, name} |\n {:timeout, timeout} |\n {:spawn_opt, Process.spawn_opt}\n\n @typedoc \"Debug options supported by the `start*` functions\"\n @type debug :: [:trace | :log | :statistics | {:log_to_file, Path.t}]\n\n @typedoc \"The server reference\"\n @type server :: pid | name | {atom, node}\n\n @typedoc \"\"\"\n Tuple describing the client of a call request.\n\n `pid` is the PID of the caller and `tag` is a unique term used to identify the\n call.\n \"\"\"\n @type from :: {pid, tag :: term}\n\n @doc false\n defmacro __using__(_) do\n quote location: :keep do\n @behaviour GenServer\n\n @doc false\n def init(args) do\n {:ok, args}\n end\n\n @doc false\n def handle_call(msg, _from, state) do\n proc =\n case Process.info(self(), :registered_name) do\n {_, []} -> self()\n {_, name} -> name\n end\n\n # We do this to trick Dialyzer to not complain about non-local returns.\n case :erlang.phash2(1, 1) do\n 0 -> raise \"attempted to call GenServer #{inspect proc} but no handle_call\/3 clause was provided\"\n 1 -> {:stop, {:bad_call, msg}, state}\n end\n end\n\n @doc false\n def handle_info(msg, state) do\n proc =\n case Process.info(self(), :registered_name) do\n {_, []} -> self()\n {_, name} -> name\n end\n :error_logger.error_msg('~p ~p received unexpected message in handle_info\/2: ~p~n',\n [__MODULE__, proc, msg])\n {:noreply, state}\n end\n\n @doc false\n def handle_cast(msg, state) do\n proc =\n case Process.info(self(), :registered_name) do\n {_, []} -> self()\n {_, name} -> name\n end\n\n # We do this to trick Dialyzer to not complain about non-local returns.\n case :erlang.phash2(1, 1) do\n 0 -> raise \"attempted to cast GenServer #{inspect proc} but no handle_cast\/2 clause was provided\"\n 1 -> {:stop, {:bad_cast, msg}, state}\n end\n end\n\n @doc false\n def terminate(_reason, _state) do\n :ok\n end\n\n @doc false\n def code_change(_old, state, _extra) do\n {:ok, state}\n end\n\n defoverridable [init: 1, handle_call: 3, handle_info: 2,\n handle_cast: 2, terminate: 2, code_change: 3]\n end\n end\n\n @doc \"\"\"\n Starts a `GenServer` process linked to the current process.\n\n This is often used to start the `GenServer` as part of a supervision tree.\n\n Once the server is started, the `c:init\/1` function of the given `module` is\n called with `args` as its arguments to initialize the server. To ensure a\n synchronized start-up procedure, this function does not return until `c:init\/1`\n has returned.\n\n Note that a `GenServer` started with `start_link\/3` is linked to the\n parent process and will exit in case of crashes from the parent. The GenServer\n will also exit due to the `:normal` reasons in case it is configured to trap\n exits in the `c:init\/1` callback.\n\n ## Options\n\n * `:name` - used for name registration as described in the \"Name\n registration\" section of the module documentation\n\n * `:timeout` - if present, the server is allowed to spend the given amount of\n milliseconds initializing or it will be terminated and the start function\n will return `{:error, :timeout}`\n\n * `:debug` - if present, the corresponding function in the [`:sys` module](http:\/\/www.erlang.org\/doc\/man\/sys.html) is invoked\n\n * `:spawn_opt` - if present, its value is passed as options to the\n underlying process as in `Process.spawn\/4`\n\n ## Return values\n\n If the server is successfully created and initialized, this function returns\n `{:ok, pid}`, where `pid` is the PID of the server. If a process with the\n specified server name already exists, this function returns\n `{:error, {:already_started, pid}}` with the PID of that process.\n\n If the `c:init\/1` callback fails with `reason`, this function returns\n `{:error, reason}`. Otherwise, if it returns `{:stop, reason}`\n or `:ignore`, the process is terminated and this function returns\n `{:error, reason}` or `:ignore`, respectively.\n \"\"\"\n @spec start_link(module, any, options) :: on_start\n def start_link(module, args, options \\\\ []) when is_atom(module) and is_list(options) do\n do_start(:link, module, args, options)\n end\n\n @doc \"\"\"\n Starts a `GenServer` process without links (outside of a supervision tree).\n\n See `start_link\/3` for more information.\n \"\"\"\n @spec start(module, any, options) :: on_start\n def start(module, args, options \\\\ []) when is_atom(module) and is_list(options) do\n do_start(:nolink, module, args, options)\n end\n\n defp do_start(link, module, args, options) do\n case Keyword.pop(options, :name) do\n {nil, opts} ->\n :gen.start(:gen_server, link, module, args, opts)\n {atom, opts} when is_atom(atom) ->\n :gen.start(:gen_server, link, {:local, atom}, module, args, opts)\n {{:global, _term} = tuple, opts} ->\n :gen.start(:gen_server, link, tuple, module, args, opts)\n {{:via, via_module, _term} = tuple, opts} when is_atom(via_module) ->\n :gen.start(:gen_server, link, tuple, module, args, opts)\n other ->\n raise ArgumentError, \"\"\"\n expected :name option to be one of:\n\n * nil\n * atom\n * {:global, term}\n * {:via, module, term}\n\n Got: #{inspect(other)}\n \"\"\"\n end\n end\n\n @doc \"\"\"\n Synchronously stops the server with the given `reason`.\n\n The `c:terminate\/2` callback of the given `server` will be invoked before\n exiting. This function returns `:ok` if the server terminates with the\n given reason; if it terminates with another reason, the call exits.\n\n This function keeps OTP semantics regarding error reporting.\n If the reason is any other than `:normal`, `:shutdown` or\n `{:shutdown, _}`, an error report is logged.\n \"\"\"\n @spec stop(server, reason :: term, timeout) :: :ok\n def stop(server, reason \\\\ :normal, timeout \\\\ :infinity) do\n :gen.stop(server, reason, timeout)\n end\n\n @doc \"\"\"\n Makes a synchronous call to the `server` and waits for its reply.\n\n The client sends the given `request` to the server and waits until a reply\n arrives or a timeout occurs. `c:handle_call\/3` will be called on the server\n to handle the request.\n\n `server` can be any of the values described in the \"Name registration\"\n section of the documentation for this module.\n\n ## Timeouts\n\n `timeout` is an integer greater than zero which specifies how many\n milliseconds to wait for a reply, or the atom `:infinity` to wait\n indefinitely. The default value is `5000`. If no reply is received within\n the specified time, the function call fails and the caller exits. If the\n caller catches the failure and continues running, and the server is just late\n with the reply, it may arrive at any time later into the caller's message\n queue. The caller must in this case be prepared for this and discard any such\n garbage messages that are two-element tuples with a reference as the first\n element.\n \"\"\"\n @spec call(server, term, timeout) :: term\n def call(server, request, timeout \\\\ 5000) do\n case whereis(server) do\n nil ->\n exit({:noproc, {__MODULE__, :call, [server, request, timeout]}})\n pid when pid == self() ->\n exit({:calling_self, {__MODULE__, :call, [server, request, timeout]}})\n pid ->\n try do\n :gen.call(pid, :\"$gen_call\", request, timeout)\n catch\n :exit, reason ->\n exit({reason, {__MODULE__, :call, [server, request, timeout]}})\n else\n {:ok, res} -> res\n end\n end\n end\n\n @doc \"\"\"\n Sends an asynchronous request to the `server`.\n\n This function always returns `:ok` regardless of whether\n the destination `server` (or node) exists. Therefore it\n is unknown whether the destination `server` successfully\n handled the message.\n\n `c:handle_cast\/2` will be called on the server to handle\n the request. In case the `server` is on a node which is\n not yet connected to the caller one, the call is going to\n block until a connection happens. This is different than\n the behaviour in OTP's `:gen_server` where the message\n is sent by another process in this case, which could cause\n messages to other nodes to arrive out of order.\n \"\"\"\n @spec cast(server, term) :: :ok\n def cast(server, request)\n\n def cast({:global, name}, request) do\n try do\n :global.send(name, cast_msg(request))\n :ok\n catch\n _, _ -> :ok\n end\n end\n\n def cast({:via, mod, name}, request) do\n try do\n mod.send(name, cast_msg(request))\n :ok\n catch\n _, _ -> :ok\n end\n end\n\n def cast({name, node}, request) when is_atom(name) and is_atom(node),\n do: do_send({name, node}, cast_msg(request))\n\n def cast(dest, request) when is_atom(dest) or is_pid(dest),\n do: do_send(dest, cast_msg(request))\n\n @doc \"\"\"\n Casts all servers locally registered as `name` at the specified nodes.\n\n This function returns immediately and ignores nodes that do not exist, or where the\n server name does not exist.\n\n See `multi_call\/4` for more information.\n \"\"\"\n @spec abcast([node], name :: atom, term) :: :abcast\n def abcast(nodes \\\\ [node() | Node.list()], name, request) when is_list(nodes) and is_atom(name) do\n msg = cast_msg(request)\n _ = for node <- nodes, do: do_send({name, node}, msg)\n :abcast\n end\n\n defp cast_msg(req) do\n {:\"$gen_cast\", req}\n end\n\n defp do_send(dest, msg) do\n try do\n send(dest, msg)\n :ok\n catch\n _, _ -> :ok\n end\n end\n\n @doc \"\"\"\n Calls all servers locally registered as `name` at the specified `nodes`.\n\n First, the `request` is sent to every node in `nodes`; then, the caller waits\n for the replies. This function returns a two-element tuple `{replies,\n bad_nodes}` where:\n\n * `replies` - is a list of `{node, reply}` tuples where `node` is the node\n that replied and `reply` is its reply\n * `bad_nodes` - is a list of nodes that either did not exist or where a\n server with the given `name` did not exist or did not reply\n\n `nodes` is a list of node names to which the request is sent. The default\n value is the list of all known nodes (including this node).\n\n To avoid that late answers (after the timeout) pollute the caller's message\n queue, a middleman process is used to do the actual calls. Late answers will\n then be discarded when they arrive to a terminated process.\n\n ## Examples\n\n Assuming the `Stack` GenServer mentioned in the docs for the `GenServer`\n module is registered as `Stack` in the `:\"foo@my-machine\"` and\n `:\"bar@my-machine\"` nodes:\n\n GenServer.multi_call(Stack, :pop)\n #=> {[{:\"foo@my-machine\", :hello}, {:\"bar@my-machine\", :world}], []}\n\n \"\"\"\n @spec multi_call([node], name :: atom, term, timeout) ::\n {replies :: [{node, term}], bad_nodes :: [node]}\n def multi_call(nodes \\\\ [node() | Node.list()], name, request, timeout \\\\ :infinity) do\n :gen_server.multi_call(nodes, name, request, timeout)\n end\n\n @doc \"\"\"\n Replies to a client.\n\n This function can be used to explicitly send a reply to a client that called\n `call\/3` or `multi_call\/4` when the reply cannot be specified in the return\n value of `c:handle_call\/3`.\n\n `client` must be the `from` argument (the second argument) accepted by\n `c:handle_call\/3` callbacks. `reply` is an arbitrary term which will be given\n back to the client as the return value of the call.\n\n Note that `reply\/2` can be called from any process, not just the GenServer\n that originally received the call (as long as that GenServer communicated the\n `from` argument somehow).\n\n This function always returns `:ok`.\n\n ## Examples\n\n def handle_call(:reply_in_one_second, from, state) do\n Process.send_after(self(), {:reply, from}, 1_000)\n {:noreply, state}\n end\n\n def handle_info({:reply, from}, state) do\n GenServer.reply(from, :one_second_has_passed)\n {:noreply, state}\n end\n\n \"\"\"\n @spec reply(from, term) :: :ok\n def reply(client, reply)\n\n def reply({to, tag}, reply) when is_pid(to) do\n try do\n send(to, {tag, reply})\n :ok\n catch\n _, _ -> :ok\n end\n end\n\n @doc \"\"\"\n Returns the `pid` or `{name, node}` of a GenServer process, or `nil` if\n no process is associated with the given `server`.\n\n ## Examples\n\n For example, to lookup a server process, monitor it and send a cast to it:\n\n process = GenServer.whereis(server)\n monitor = Process.monitor(process)\n GenServer.cast(process, :hello)\n\n \"\"\"\n @spec whereis(server) :: pid | {atom, node} | nil\n def whereis(server)\n\n def whereis(pid) when is_pid(pid), do: pid\n def whereis(name) when is_atom(name) do\n Process.whereis(name)\n end\n def whereis({:global, name}) do\n case :global.whereis_name(name) do\n pid when is_pid(pid) -> pid\n :undefined -> nil\n end\n end\n def whereis({:via, mod, name}) do\n case apply(mod, :whereis_name, [name]) do\n pid when is_pid(pid) -> pid\n :undefined -> nil\n end\n end\n def whereis({name, local}) when is_atom(name) and local == node() do\n Process.whereis(name)\n end\n def whereis({name, node} = server) when is_atom(name) and is_atom(node) do\n server\n end\nend\n","old_contents":"defmodule GenServer do\n @moduledoc \"\"\"\n A behaviour module for implementing the server of a client-server relation.\n\n A GenServer is a process like any other Elixir process and it can be used\n to keep state, execute code asynchronously and so on. The advantage of using\n a generic server process (GenServer) implemented using this module is that it\n will have a standard set of interface functions and include functionality for\n tracing and error reporting. It will also fit into a supervision tree.\n\n ## Example\n\n The GenServer behaviour abstracts the common client-server interaction.\n Developers are only required to implement the callbacks and functionality they are\n interested in.\n\n Let's start with a code example and then explore the available callbacks.\n Imagine we want a GenServer that works like a stack, allowing us to push\n and pop items:\n\n defmodule Stack do\n use GenServer\n\n # Callbacks\n\n def handle_call(:pop, _from, [h | t]) do\n {:reply, h, t}\n end\n\n def handle_cast({:push, item}, state) do\n {:noreply, [item | state]}\n end\n end\n\n # Start the server\n {:ok, pid} = GenServer.start_link(Stack, [:hello])\n\n # This is the client\n GenServer.call(pid, :pop)\n #=> :hello\n\n GenServer.cast(pid, {:push, :world})\n #=> :ok\n\n GenServer.call(pid, :pop)\n #=> :world\n\n We start our `Stack` by calling `start_link\/3`, passing the module\n with the server implementation and its initial argument (a list\n representing the stack containing the item `:hello`). We can primarily\n interact with the server by sending two types of messages. **call**\n messages expect a reply from the server (and are therefore synchronous)\n while **cast** messages do not.\n\n Every time you do a `GenServer.call\/3`, the client will send a message\n that must be handled by the `c:handle_call\/3` callback in the GenServer.\n A `cast\/2` message must be handled by `c:handle_cast\/2`.\n\n ## Callbacks\n\n There are 6 callbacks required to be implemented in a `GenServer`. By\n adding `use GenServer` to your module, Elixir will automatically define\n all 6 callbacks for you, leaving it up to you to implement the ones\n you want to customize.\n\n ## Name Registration\n\n Both `start_link\/3` and `start\/3` support the `GenServer` to register\n a name on start via the `:name` option. Registered names are also\n automatically cleaned up on termination. The supported values are:\n\n * an atom - the GenServer is registered locally with the given name\n using `Process.register\/2`.\n\n * `{:global, term}`- the GenServer is registered globally with the given\n term using the functions in the [`:global` module](http:\/\/www.erlang.org\/doc\/man\/global.html).\n\n * `{:via, module, term}` - the GenServer is registered with the given\n mechanism and name. The `:via` option expects a module that exports\n `register_name\/2`, `unregister_name\/1`, `whereis_name\/1` and `send\/2`.\n One such example is the [`:global` module](http:\/\/www.erlang.org\/doc\/man\/global.html) which uses these functions\n for keeping the list of names of processes and their associated PIDs\n that are available globally for a network of Elixir nodes. Elixir also\n ships with a local, decentralized and scalable registry called `Registry`\n for locally storing names that are generated dynamically.\n\n For example, we could start and register our `Stack` server locally as follows:\n\n # Start the server and register it locally with name MyStack\n {:ok, _} = GenServer.start_link(Stack, [:hello], name: MyStack)\n\n # Now messages can be sent directly to MyStack\n GenServer.call(MyStack, :pop) #=> :hello\n\n Once the server is started, the remaining functions in this module (`call\/3`,\n `cast\/2`, and friends) will also accept an atom, or any `:global` or `:via`\n tuples. In general, the following formats are supported:\n\n * a `pid`\n * an `atom` if the server is locally registered\n * `{atom, node}` if the server is locally registered at another node\n * `{:global, term}` if the server is globally registered\n * `{:via, module, name}` if the server is registered through an alternative\n registry\n\n If there is an interest to register dynamic names locally, do not use\n atoms, as atoms are never garbage collected and therefore dynamically\n generated atoms won't be garbage collected. For such cases, you can\n set up your own local registry by using the `Registry` module.\n\n ## Client \/ Server APIs\n\n Although in the example above we have used `GenServer.start_link\/3` and\n friends to directly start and communicate with the server, most of the\n time we don't call the `GenServer` functions directly. Instead, we wrap\n the calls in new functions representing the public API of the server.\n\n Here is a better implementation of our Stack module:\n\n defmodule Stack do\n use GenServer\n\n # Client\n\n def start_link(default) do\n GenServer.start_link(__MODULE__, default)\n end\n\n def push(pid, item) do\n GenServer.cast(pid, {:push, item})\n end\n\n def pop(pid) do\n GenServer.call(pid, :pop)\n end\n\n # Server (callbacks)\n\n def handle_call(:pop, _from, [h | t]) do\n {:reply, h, t}\n end\n\n def handle_call(request, from, state) do\n # Call the default implementation from GenServer\n super(request, from, state)\n end\n\n def handle_cast({:push, item}, state) do\n {:noreply, [item | state]}\n end\n\n def handle_cast(request, state) do\n super(request, state)\n end\n end\n\n In practice, it is common to have both server and client functions in\n the same module. If the server and\/or client implementations are growing\n complex, you may want to have them in different modules.\n\n ## Receiving \"regular\" messages\n\n The goal of a `GenServer` is to abstract the \"receive\" loop for developers,\n automatically handling system messages, support code change, synchronous\n calls and more. Therefore, you should never call your own \"receive\" inside\n the GenServer callbacks as doing so will cause the GenServer to misbehave.\n\n Besides the synchronous and asynchronous communication provided by `call\/3`\n and `cast\/2`, \"regular\" messages sent by functions such `Kernel.send\/2`,\n `Process.send_after\/4` and similar, can be handled inside the `c:handle_info\/2`\n callback.\n\n `c:handle_info\/2` can be used in many situations, such as handling monitor\n DOWN messages sent by `Process.monitor\/1`. Another use case for `c:handle_info\/2`\n is to perform periodic work, with the help of `Process.send_after\/4`:\n\n defmodule MyApp.Periodically do\n use GenServer\n\n def start_link do\n GenServer.start_link(__MODULE__, %{})\n end\n\n def init(state) do\n schedule_work() # Schedule work to be performed on start\n {:ok, state}\n end\n\n def handle_info(:work, state) do\n # Do the desired work here\n schedule_work() # Reschedule once more\n {:noreply, state}\n end\n\n defp schedule_work() do\n Process.send_after(self(), :work, 2 * 60 * 60 * 1000) # In 2 hours\n end\n end\n\n ## Debugging with the :sys module\n\n GenServers, as [special processes](http:\/\/erlang.org\/doc\/design_principles\/spec_proc.html),\n can be debugged using the [`:sys` module](http:\/\/www.erlang.org\/doc\/man\/sys.html). Through various hooks, this module\n allows developers to introspect the state of the process and trace\n system events that happen during its execution, such as received messages,\n sent replies and state changes.\n\n Let's explore the basic functions from the [`:sys` module](http:\/\/www.erlang.org\/doc\/man\/sys.html) used for debugging:\n\n * [`:sys.get_state\/2`](http:\/\/erlang.org\/doc\/man\/sys.html#get_state-2) -\n allows retrieval of the state of the process. In the case of\n a GenServer process, it will be the callback module state, as\n passed into the callback functions as last argument.\n * [`:sys.get_status\/2`](http:\/\/erlang.org\/doc\/man\/sys.html#get_status-2) -\n allows retrieval of the status of the process. This status includes\n the process dictionary, if the process is running or is suspended,\n the parent PID, the debugger state, and the state of the behaviour module,\n which includes the callback module state (as returned by `:sys.get_state\/2`).\n It's possible to change how this status is represented by defining\n the optional `c:GenServer.format_status\/2` callback.\n * [`:sys.trace\/3`](http:\/\/erlang.org\/doc\/man\/sys.html#trace-3) -\n prints all the system events to `:stdio`.\n * [`:sys.statistics\/3`](http:\/\/erlang.org\/doc\/man\/sys.html#statistics-3) -\n manages collection of process statistics.\n * [`:sys.no_debug\/2`](http:\/\/erlang.org\/doc\/man\/sys.html#no_debug-2) -\n turns off all debug handlers for the given process. It is very important\n to switch off debugging once we're done. Excessive debug handlers or\n those that should be turned off, but weren't, can seriously damage\n the performance of the system.\n * [`:sys.suspend\/2`](http:\/\/erlang.org\/doc\/man\/sys.html#suspend-2) - allows\n to suspend a process so that it only replies to system messages but no\n other messages. A suspended process can be reactivated via\n [`:sys.resume\/2`](http:\/\/erlang.org\/doc\/man\/sys.html#resume-2).\n\n Let's see how we could use those functions for debugging the stack server\n we defined earlier.\n\n iex> {:ok, pid} = Stack.start_link([])\n iex> :sys.statistics(pid, true) # turn on collecting process statistics\n iex> :sys.trace(pid, true) # turn on event printing\n iex> Stack.push(pid, 1)\n *DBG* <0.122.0> got cast {push,1}\n *DBG* <0.122.0> new state [1]\n :ok\n iex> :sys.get_state(pid)\n [1]\n iex> Stack.pop(pid)\n *DBG* <0.122.0> got call pop from <0.80.0>\n *DBG* <0.122.0> sent 1 to <0.80.0>, new state []\n 1\n iex> :sys.statistics(pid, :get)\n {:ok,\n [start_time: {{2016, 7, 16}, {12, 29, 41}},\n current_time: {{2016, 7, 16}, {12, 29, 50}},\n reductions: 117, messages_in: 2, messages_out: 0]}\n iex> :sys.no_debug(pid) # turn off all debug handlers\n :ok\n iex> :sys.get_status(pid)\n {:status, #PID<0.122.0>, {:module, :gen_server},\n [[\"$initial_call\": {Stack, :init, 1}, # pdict\n \"$ancestors\": [#PID<0.80.0>, #PID<0.51.0>]],\n :running, # :running | :suspended\n #PID<0.80.0>, # parent\n [], # debugger state\n [header: 'Status for generic server <0.122.0>', # module status\n data: [{'Status', :running}, {'Parent', #PID<0.80.0>},\n {'Logged events', []}], data: [{'State', [1]}]]]}\n\n ## Learn more\n\n If you wish to find out more about gen servers, the Elixir Getting Started\n guide provides a tutorial-like introduction. The documentation and links\n in Erlang can also provide extra insight.\n\n * [GenServer \u2013 Elixir's Getting Started Guide](http:\/\/elixir-lang.org\/getting-started\/mix-otp\/genserver.html)\n * [`:gen_server` module documentation](http:\/\/www.erlang.org\/doc\/man\/gen_server.html)\n * [gen_server Behaviour \u2013 OTP Design Principles](http:\/\/www.erlang.org\/doc\/design_principles\/gen_server_concepts.html)\n * [Clients and Servers \u2013 Learn You Some Erlang for Great Good!](http:\/\/learnyousomeerlang.com\/clients-and-servers)\n \"\"\"\n\n @doc \"\"\"\n Invoked when the server is started. `start_link\/3` or `start\/3` will\n block until it returns.\n\n `args` is the argument term (second argument) passed to `start_link\/3`.\n\n Returning `{:ok, state}` will cause `start_link\/3` to return\n `{:ok, pid}` and the process to enter its loop.\n\n Returning `{:ok, state, timeout}` is similar to `{:ok, state}`\n except `handle_info(:timeout, state)` will be called after `timeout`\n milliseconds if no messages are received within the timeout.\n\n Returning `{:ok, state, :hibernate}` is similar to\n `{:ok, state}` except the process is hibernated before entering the loop. See\n `c:handle_call\/3` for more information on hibernation.\n\n Returning `:ignore` will cause `start_link\/3` to return `:ignore` and the\n process will exit normally without entering the loop or calling `c:terminate\/2`.\n If used when part of a supervision tree the parent supervisor will not fail\n to start nor immediately try to restart the `GenServer`. The remainder of the\n supervision tree will be (re)started and so the `GenServer` should not be\n required by other processes. It can be started later with\n `Supervisor.restart_child\/2` as the child specification is saved in the parent\n supervisor. The main use cases for this are:\n\n * The `GenServer` is disabled by configuration but might be enabled later.\n * An error occurred and it will be handled by a different mechanism than the\n `Supervisor`. Likely this approach involves calling `Supervisor.restart_child\/2`\n after a delay to attempt a restart.\n\n Returning `{:stop, reason}` will cause `start_link\/3` to return\n `{:error, reason}` and the process to exit with reason `reason` without\n entering the loop or calling `c:terminate\/2`.\n \"\"\"\n @callback init(args :: term) ::\n {:ok, state} |\n {:ok, state, timeout | :hibernate} |\n :ignore |\n {:stop, reason :: any} when state: any\n\n @doc \"\"\"\n Invoked to handle synchronous `call\/3` messages. `call\/3` will block until a\n reply is received (unless the call times out or nodes are disconnected).\n\n `request` is the request message sent by a `call\/3`, `from` is a 2-tuple\n containing the caller's PID and a term that uniquely identifies the call, and\n `state` is the current state of the `GenServer`.\n\n Returning `{:reply, reply, new_state}` sends the response `reply` to the\n caller and continues the loop with new state `new_state`.\n\n Returning `{:reply, reply, new_state, timeout}` is similar to\n `{:reply, reply, new_state}` except `handle_info(:timeout, new_state)` will be\n called after `timeout` milliseconds if no messages are received.\n\n Returning `{:reply, reply, new_state, :hibernate}` is similar to\n `{:reply, reply, new_state}` except the process is hibernated and will\n continue the loop once a message is in its message queue. If a message is\n already in the message queue this will be immediately. Hibernating a\n `GenServer` causes garbage collection and leaves a continuous heap that\n minimises the memory used by the process.\n\n Hibernating should not be used aggressively as too much time could be spent\n garbage collecting. Normally it should only be used when a message is not\n expected soon and minimising the memory of the process is shown to be\n beneficial.\n\n Returning `{:noreply, new_state}` does not send a response to the caller and\n continues the loop with new state `new_state`. The response must be sent with\n `reply\/2`.\n\n There are three main use cases for not replying using the return value:\n\n * To reply before returning from the callback because the response is known\n before calling a slow function.\n * To reply after returning from the callback because the response is not yet\n available.\n * To reply from another process, such as a task.\n\n When replying from another process the `GenServer` should exit if the other\n process exits without replying as the caller will be blocking awaiting a\n reply.\n\n Returning `{:noreply, new_state, timeout | :hibernate}` is similar to\n `{:noreply, new_state}` except a timeout or hibernation occurs as with a\n `:reply` tuple.\n\n Returning `{:stop, reason, reply, new_state}` stops the loop and `c:terminate\/2`\n is called with reason `reason` and state `new_state`. Then the `reply` is sent\n as the response to call and the process exits with reason `reason`.\n\n Returning `{:stop, reason, new_state}` is similar to\n `{:stop, reason, reply, new_state}` except a reply is not sent.\n\n If this callback is not implemented, the default implementation by\n `use GenServer` will return `{:stop, {:bad_call, request}, state}`.\n \"\"\"\n @callback handle_call(request :: term, from, state :: term) ::\n {:reply, reply, new_state} |\n {:reply, reply, new_state, timeout | :hibernate} |\n {:noreply, new_state} |\n {:noreply, new_state, timeout | :hibernate} |\n {:stop, reason, reply, new_state} |\n {:stop, reason, new_state} when reply: term, new_state: term, reason: term\n\n @doc \"\"\"\n Invoked to handle asynchronous `cast\/2` messages.\n\n `request` is the request message sent by a `cast\/2` and `state` is the current\n state of the `GenServer`.\n\n Returning `{:noreply, new_state}` continues the loop with new state `new_state`.\n\n Returning `{:noreply, new_state, timeout}` is similar to\n `{:noreply, new_state}` except `handle_info(:timeout, new_state)` will be\n called after `timeout` milliseconds if no messages are received.\n\n Returning `{:noreply, new_state, :hibernate}` is similar to\n `{:noreply, new_state}` except the process is hibernated before continuing the\n loop. See `c:handle_call\/3` for more information.\n\n Returning `{:stop, reason, new_state}` stops the loop and `c:terminate\/2` is\n called with the reason `reason` and state `new_state`. The process exits with\n reason `reason`.\n\n If this callback is not implemented, the default implementation by\n `use GenServer` will return `{:stop, {:bad_cast, request}, state}`.\n \"\"\"\n @callback handle_cast(request :: term, state :: term) ::\n {:noreply, new_state} |\n {:noreply, new_state, timeout | :hibernate} |\n {:stop, reason :: term, new_state} when new_state: term\n\n @doc \"\"\"\n Invoked to handle all other messages.\n\n `msg` is the message and `state` is the current state of the `GenServer`. When\n a timeout occurs the message is `:timeout`.\n\n Return values are the same as `c:handle_cast\/2`.\n\n If this callback is not implemented, the default implementation by\n `use GenServer` will return `{:noreply, state}`.\n \"\"\"\n @callback handle_info(msg :: :timeout | term, state :: term) ::\n {:noreply, new_state} |\n {:noreply, new_state, timeout | :hibernate} |\n {:stop, reason :: term, new_state} when new_state: term\n\n @doc \"\"\"\n Invoked when the server is about to exit. It should do any cleanup required.\n\n `reason` is exit reason and `state` is the current state of the `GenServer`.\n The return value is ignored.\n\n `c:terminate\/2` is called if a callback (except `c:init\/1`) does one of the\n following:\n\n * returns a `:stop` tuple\n * raises\n * calls `Kernel.exit\/1`\n * returns an invalid value\n * the `GenServer` traps exits (using `Process.flag\/2`) *and* the parent\n process sends an exit signal\n\n If part of a supervision tree, a `GenServer`'s `Supervisor` will send an exit\n signal when shutting it down. The exit signal is based on the shutdown\n strategy in the child's specification. If it is `:brutal_kill` the `GenServer`\n is killed and so `c:terminate\/2` is not called. However if it is a timeout the\n `Supervisor` will send the exit signal `:shutdown` and the `GenServer` will\n have the duration of the timeout to call `c:terminate\/2` - if the process is\n still alive after the timeout it is killed.\n\n If the `GenServer` receives an exit signal (that is not `:normal`) from any\n process when it is not trapping exits it will exit abruptly with the same\n reason and so not call `c:terminate\/2`. Note that a process does *NOT* trap\n exits by default and an exit signal is sent when a linked process exits or its\n node is disconnected.\n\n Therefore it is not guaranteed that `c:terminate\/2` is called when a `GenServer`\n exits. For such reasons, we usually recommend important clean-up rules to\n happen in separated processes either by use of monitoring or by links\n themselves. For example if the `GenServer` controls a `port` (e.g.\n `:gen_tcp.socket`) or `t:File.io_device\/0`, they will be closed on receiving a\n `GenServer`'s exit signal and do not need to be closed in `c:terminate\/2`.\n\n If `reason` is not `:normal`, `:shutdown`, nor `{:shutdown, term}` an error is\n logged.\n \"\"\"\n @callback terminate(reason, state :: term) ::\n term when reason: :normal | :shutdown | {:shutdown, term} | term\n\n @doc \"\"\"\n Invoked to change the state of the `GenServer` when a different version of a\n module is loaded (hot code swapping) and the state's term structure should be\n changed.\n\n `old_vsn` is the previous version of the module (defined by the `@vsn`\n attribute) when upgrading. When downgrading the previous version is wrapped in\n a 2-tuple with first element `:down`. `state` is the current state of the\n `GenServer` and `extra` is any extra data required to change the state.\n\n Returning `{:ok, new_state}` changes the state to `new_state` and the code\n change is successful.\n\n Returning `{:error, reason}` fails the code change with reason `reason` and\n the state remains as the previous state.\n\n If `c:code_change\/3` raises the code change fails and the loop will continue\n with its previous state. Therefore this callback does not usually contain side effects.\n \"\"\"\n @callback code_change(old_vsn, state :: term, extra :: term) ::\n {:ok, new_state :: term} |\n {:error, reason :: term} when old_vsn: term | {:down, term}\n\n @doc \"\"\"\n Invoked in some cases to retrieve a formatted version of the `GenServer` status.\n\n This callback can be useful to control the *appearance* of the status of the\n `GenServer`. For example, it can be used to return a compact representation of\n the `GenServer`'s state to avoid having large state terms printed.\n\n * one of `:sys.get_status\/1` or `:sys.get_status\/2` is invoked to get the\n status of the `GenServer`; in such cases, `reason` is `:normal`\n\n * the `GenServer` terminates abnormally and logs an error; in such cases,\n `reason` is `:terminate`\n\n `pdict_and_state` is a two-elements list `[pdict, state]` where `pdict` is a\n list of `{key, value}` tuples representing the current process dictionary of\n the `GenServer` and `state` is the current state of the `GenServer`.\n \"\"\"\n @callback format_status(reason, pdict_and_state :: list) ::\n term when reason: :normal | :terminate\n\n @optional_callbacks format_status: 2\n\n @typedoc \"Return values of `start*` functions\"\n @type on_start :: {:ok, pid} | :ignore | {:error, {:already_started, pid} | term}\n\n @typedoc \"The GenServer name\"\n @type name :: atom | {:global, term} | {:via, module, term}\n\n @typedoc \"Options used by the `start*` functions\"\n @type options :: [option]\n\n @typedoc \"Option values used by the `start*` functions\"\n @type option :: {:debug, debug} |\n {:name, name} |\n {:timeout, timeout} |\n {:spawn_opt, Process.spawn_opt}\n\n @typedoc \"Debug options supported by the `start*` functions\"\n @type debug :: [:trace | :log | :statistics | {:log_to_file, Path.t}]\n\n @typedoc \"The server reference\"\n @type server :: pid | name | {atom, node}\n\n @typedoc \"\"\"\n Tuple describing the client of a call request.\n\n `pid` is the PID of the caller and `tag` is a unique term used to identify the\n call.\n \"\"\"\n @type from :: {pid, tag :: term}\n\n @doc false\n defmacro __using__(_) do\n quote location: :keep do\n @behaviour GenServer\n\n @doc false\n def init(args) do\n {:ok, args}\n end\n\n @doc false\n def handle_call(msg, _from, state) do\n proc =\n case Process.info(self(), :registered_name) do\n {_, []} -> self()\n {_, name} -> name\n end\n\n # We do this to trick Dialyzer to not complain about non-local returns.\n case :erlang.phash2(1, 1) do\n 0 -> raise \"attempted to call GenServer #{inspect proc} but no handle_call\/3 clause was provided\"\n 1 -> {:stop, {:bad_call, msg}, state}\n end\n end\n\n @doc false\n def handle_info(msg, state) do\n proc =\n case Process.info(self(), :registered_name) do\n {_, []} -> self()\n {_, name} -> name\n end\n :error_logger.error_msg('~p ~p received unexpected message in handle_info\/2: ~p~n',\n [__MODULE__, proc, msg])\n {:noreply, state}\n end\n\n @doc false\n def handle_cast(msg, state) do\n proc =\n case Process.info(self(), :registered_name) do\n {_, []} -> self()\n {_, name} -> name\n end\n\n # We do this to trick Dialyzer to not complain about non-local returns.\n case :erlang.phash2(1, 1) do\n 0 -> raise \"attempted to cast GenServer #{inspect proc} but no handle_cast\/2 clause was provided\"\n 1 -> {:stop, {:bad_cast, msg}, state}\n end\n end\n\n @doc false\n def terminate(_reason, _state) do\n :ok\n end\n\n @doc false\n def code_change(_old, state, _extra) do\n {:ok, state}\n end\n\n defoverridable [init: 1, handle_call: 3, handle_info: 2,\n handle_cast: 2, terminate: 2, code_change: 3]\n end\n end\n\n @doc \"\"\"\n Starts a `GenServer` process linked to the current process.\n\n This is often used to start the `GenServer` as part of a supervision tree.\n\n Once the server is started, the `c:init\/1` function of the given `module` is\n called with `args` as its arguments to initialize the server. To ensure a\n synchronized start-up procedure, this function does not return until `c:init\/1`\n has returned.\n\n Note that a `GenServer` started with `start_link\/3` is linked to the\n parent process and will exit in case of crashes from the parent. The GenServer\n will also exit due to the `:normal` reasons in case it is configured to trap\n exits in the `c:init\/1` callback.\n\n ## Options\n\n * `:name` - used for name registration as described in the \"Name\n registration\" section of the module documentation\n\n * `:timeout` - if present, the server is allowed to spend the given amount of\n milliseconds initializing or it will be terminated and the start function\n will return `{:error, :timeout}`\n\n * `:debug` - if present, the corresponding function in the [`:sys` module](http:\/\/www.erlang.org\/doc\/man\/sys.html) is invoked\n\n * `:spawn_opt` - if present, its value is passed as options to the\n underlying process as in `Process.spawn\/4`\n\n ## Return values\n\n If the server is successfully created and initialized, this function returns\n `{:ok, pid}`, where `pid` is the PID of the server. If a process with the\n specified server name already exists, this function returns\n `{:error, {:already_started, pid}}` with the PID of that process.\n\n If the `c:init\/1` callback fails with `reason`, this function returns\n `{:error, reason}`. Otherwise, if it returns `{:stop, reason}`\n or `:ignore`, the process is terminated and this function returns\n `{:error, reason}` or `:ignore`, respectively.\n \"\"\"\n @spec start_link(module, any, options) :: on_start\n def start_link(module, args, options \\\\ []) when is_atom(module) and is_list(options) do\n do_start(:link, module, args, options)\n end\n\n @doc \"\"\"\n Starts a `GenServer` process without links (outside of a supervision tree).\n\n See `start_link\/3` for more information.\n \"\"\"\n @spec start(module, any, options) :: on_start\n def start(module, args, options \\\\ []) when is_atom(module) and is_list(options) do\n do_start(:nolink, module, args, options)\n end\n\n defp do_start(link, module, args, options) do\n case Keyword.pop(options, :name) do\n {nil, opts} ->\n :gen.start(:gen_server, link, module, args, opts)\n {atom, opts} when is_atom(atom) ->\n :gen.start(:gen_server, link, {:local, atom}, module, args, opts)\n {{:global, _term} = tuple, opts} ->\n :gen.start(:gen_server, link, tuple, module, args, opts)\n {{:via, via_module, _term} = tuple, opts} when is_atom(via_module) ->\n :gen.start(:gen_server, link, tuple, module, args, opts)\n other ->\n raise ArgumentError, \"\"\"\n expected :name option to be one of:\n\n * nil\n * atom\n * {:global, term}\n * {:via, module, term}\n\n Got: #{inspect(other)}\n \"\"\"\n end\n end\n\n @doc \"\"\"\n Synchronously stops the server with the given `reason`.\n\n The `c:terminate\/2` callback of the given `server` will be invoked before\n exiting. This function returns `:ok` if the server terminates with the\n given reason; if it terminates with another reason, the call exits.\n\n This function keeps OTP semantics regarding error reporting.\n If the reason is any other than `:normal`, `:shutdown` or\n `{:shutdown, _}`, an error report is logged.\n \"\"\"\n @spec stop(server, reason :: term, timeout) :: :ok\n def stop(server, reason \\\\ :normal, timeout \\\\ :infinity) do\n :gen.stop(server, reason, timeout)\n end\n\n @doc \"\"\"\n Makes a synchronous call to the `server` and waits for its reply.\n\n The client sends the given `request` to the server and waits until a reply\n arrives or a timeout occurs. `c:handle_call\/3` will be called on the server\n to handle the request.\n\n `server` can be any of the values described in the \"Name registration\"\n section of the documentation for this module.\n\n ## Timeouts\n\n `timeout` is an integer greater than zero which specifies how many\n milliseconds to wait for a reply, or the atom `:infinity` to wait\n indefinitely. The default value is `5000`. If no reply is received within\n the specified time, the function call fails and the caller exits. If the\n caller catches the failure and continues running, and the server is just late\n with the reply, it may arrive at any time later into the caller's message\n queue. The caller must in this case be prepared for this and discard any such\n garbage messages that are two-element tuples with a reference as the first\n element.\n \"\"\"\n @spec call(server, term, timeout) :: term\n def call(server, request, timeout \\\\ 5000) do\n case whereis(server) do\n nil ->\n exit({:noproc, {__MODULE__, :call, [server, request, timeout]}})\n pid when pid == self() ->\n exit({:calling_self, {__MODULE__, :call, [server, request, timeout]}})\n pid ->\n try do\n :gen.call(pid, :\"$gen_call\", request, timeout)\n catch\n :exit, reason ->\n exit({reason, {__MODULE__, :call, [server, request, timeout]}})\n else\n {:ok, res} -> res\n end\n end\n end\n\n @doc \"\"\"\n Sends an asynchronous request to the `server`.\n\n This function always returns `:ok` regardless of whether\n the destination `server` (or node) exists. Therefore it\n is unknown whether the destination `server` successfully\n handled the message.\n\n `c:handle_cast\/2` will be called on the server to handle\n the request. In case the `server` is on a node which is\n not yet connected to the caller one, the call is going to\n block until a connection happens. This is different than\n the behaviour in OTP's `:gen_server` where the message\n is sent by another process in this case, which could cause\n messages to other nodes to arrive out of order.\n \"\"\"\n @spec cast(server, term) :: :ok\n def cast(server, request)\n\n def cast({:global, name}, request) do\n try do\n :global.send(name, cast_msg(request))\n :ok\n catch\n _, _ -> :ok\n end\n end\n\n def cast({:via, mod, name}, request) do\n try do\n mod.send(name, cast_msg(request))\n :ok\n catch\n _, _ -> :ok\n end\n end\n\n def cast({name, node}, request) when is_atom(name) and is_atom(node),\n do: do_send({name, node}, cast_msg(request))\n\n def cast(dest, request) when is_atom(dest) or is_pid(dest),\n do: do_send(dest, cast_msg(request))\n\n @doc \"\"\"\n Casts all servers locally registered as `name` at the specified nodes.\n\n This function returns immediately and ignores nodes that do not exist, or where the\n server name does not exist.\n\n See `multi_call\/4` for more information.\n \"\"\"\n @spec abcast([node], name :: atom, term) :: :abcast\n def abcast(nodes \\\\ [node() | Node.list()], name, request) when is_list(nodes) and is_atom(name) do\n msg = cast_msg(request)\n _ = for node <- nodes, do: do_send({name, node}, msg)\n :abcast\n end\n\n defp cast_msg(req) do\n {:\"$gen_cast\", req}\n end\n\n defp do_send(dest, msg) do\n try do\n send(dest, msg)\n :ok\n catch\n _, _ -> :ok\n end\n end\n\n @doc \"\"\"\n Calls all servers locally registered as `name` at the specified `nodes`.\n\n First, the `request` is sent to every node in `nodes`; then, the caller waits\n for the replies. This function returns a two-element tuple `{replies,\n bad_nodes}` where:\n\n * `replies` - is a list of `{node, reply}` tuples where `node` is the node\n that replied and `reply` is its reply\n * `bad_nodes` - is a list of nodes that either did not exist or where a\n server with the given `name` did not exist or did not reply\n\n `nodes` is a list of node names to which the request is sent. The default\n value is the list of all known nodes (including this node).\n\n To avoid that late answers (after the timeout) pollute the caller's message\n queue, a middleman process is used to do the actual calls. Late answers will\n then be discarded when they arrive to a terminated process.\n\n ## Examples\n\n Assuming the `Stack` GenServer mentioned in the docs for the `GenServer`\n module is registered as `Stack` in the `:\"foo@my-machine\"` and\n `:\"bar@my-machine\"` nodes:\n\n GenServer.multi_call(Stack, :pop)\n #=> {[{:\"foo@my-machine\", :hello}, {:\"bar@my-machine\", :world}], []}\n\n \"\"\"\n @spec multi_call([node], name :: atom, term, timeout) ::\n {replies :: [{node, term}], bad_nodes :: [node]}\n def multi_call(nodes \\\\ [node() | Node.list()], name, request, timeout \\\\ :infinity) do\n :gen_server.multi_call(nodes, name, request, timeout)\n end\n\n @doc \"\"\"\n Replies to a client.\n\n This function can be used to explicitly send a reply to a client that called\n `call\/3` or `multi_call\/4` when the reply cannot be specified in the return\n value of `c:handle_call\/3`.\n\n `client` must be the `from` argument (the second argument) accepted by\n `c:handle_call\/3` callbacks. `reply` is an arbitrary term which will be given\n back to the client as the return value of the call.\n\n Note that `reply\/2` can be called from any process, not just the GenServer\n that originally received the call (as long as that GenServer communicated the\n `from` argument somehow).\n\n This function always returns `:ok`.\n\n ## Examples\n\n def handle_call(:reply_in_one_second, from, state) do\n Process.send_after(self(), {:reply, from}, 1_000)\n {:noreply, state}\n end\n\n def handle_info({:reply, from}, state) do\n GenServer.reply(from, :one_second_has_passed)\n {:noreply, state}\n end\n\n \"\"\"\n @spec reply(from, term) :: :ok\n def reply(client, reply)\n\n def reply({to, tag}, reply) when is_pid(to) do\n try do\n send(to, {tag, reply})\n :ok\n catch\n _, _ -> :ok\n end\n end\n\n @doc \"\"\"\n Returns the `pid` or `{name, node}` of a GenServer process, or `nil` if\n no process is associated with the given name.\n\n ## Examples\n\n For example, to lookup a server process, monitor it and send a cast to it:\n\n process = GenServer.whereis(server)\n monitor = Process.monitor(process)\n GenServer.cast(process, :hello)\n\n \"\"\"\n @spec whereis(server) :: pid | {atom, node} | nil\n def whereis(pid) when is_pid(pid), do: pid\n def whereis(name) when is_atom(name) do\n Process.whereis(name)\n end\n def whereis({:global, name}) do\n case :global.whereis_name(name) do\n pid when is_pid(pid) -> pid\n :undefined -> nil\n end\n end\n def whereis({:via, mod, name}) do\n case apply(mod, :whereis_name, [name]) do\n pid when is_pid(pid) -> pid\n :undefined -> nil\n end\n end\n def whereis({name, local}) when is_atom(name) and local == node() do\n Process.whereis(name)\n end\n def whereis({name, node} = server) when is_atom(name) and is_atom(node) do\n server\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"27e9486b4775017681804c2359e7e25b0ac2e775","subject":"Fix typos in GenServer @moduledoc (#7525)","message":"Fix typos in GenServer @moduledoc (#7525)\n\n","repos":"pedrosnk\/elixir,michalmuskala\/elixir,ggcampinho\/elixir,ggcampinho\/elixir,lexmag\/elixir,pedrosnk\/elixir,kimshrier\/elixir,lexmag\/elixir,kelvinst\/elixir,kimshrier\/elixir,joshprice\/elixir,kelvinst\/elixir,elixir-lang\/elixir","old_file":"lib\/elixir\/lib\/gen_server.ex","new_file":"lib\/elixir\/lib\/gen_server.ex","new_contents":"defmodule GenServer do\n @moduledoc \"\"\"\n A behaviour module for implementing the server of a client-server relation.\n\n A GenServer is a process like any other Elixir process and it can be used\n to keep state, execute code asynchronously and so on. The advantage of using\n a generic server process (GenServer) implemented using this module is that it\n will have a standard set of interface functions and include functionality for\n tracing and error reporting. It will also fit into a supervision tree.\n\n ## Example\n\n The GenServer behaviour abstracts the common client-server interaction.\n Developers are only required to implement the callbacks and functionality\n they are interested in.\n\n Let's start with a code example and then explore the available callbacks.\n Imagine we want a GenServer that works like a stack, allowing us to push\n and pop items:\n\n defmodule Stack do\n use GenServer\n\n # Callbacks\n\n def handle_call(:pop, _from, [h | t]) do\n {:reply, h, t}\n end\n\n def handle_cast({:push, item}, state) do\n {:noreply, [item | state]}\n end\n end\n\n # Start the server\n {:ok, pid} = GenServer.start_link(Stack, [:hello])\n\n # This is the client\n GenServer.call(pid, :pop)\n #=> :hello\n\n GenServer.cast(pid, {:push, :world})\n #=> :ok\n\n GenServer.call(pid, :pop)\n #=> :world\n\n We start our `Stack` by calling `start_link\/2`, passing the module\n with the server implementation and its initial argument (a list\n representing the stack containing the item `:hello`). We can primarily\n interact with the server by sending two types of messages. **call**\n messages expect a reply from the server (and are therefore synchronous)\n while **cast** messages do not.\n\n Every time you do a `GenServer.call\/3`, the client will send a message\n that must be handled by the `c:handle_call\/3` callback in the GenServer.\n A `cast\/2` message must be handled by `c:handle_cast\/2`.\n\n ## use GenServer and callbacks\n\n There are 6 callbacks required to be implemented in a `GenServer`. By\n adding `use GenServer` to your module, Elixir will automatically define\n all 6 callbacks for you, leaving it up to you to implement the ones\n you want to customize.\n\n `use GenServer` also defines a `child_spec\/1` function, allowing the\n defined module to be put under a supervision tree. The generated\n `child_spec\/1` can be customized with the following options:\n\n * `:id` - the child specification id, defaults to the current module\n * `:start` - how to start the child process (defaults to calling `__MODULE__.start_link\/1`)\n * `:restart` - when the child should be restarted, defaults to `:permanent`\n * `:shutdown` - how to shut down the child\n\n For example:\n\n use GenServer, restart: :transient, shutdown: 10_000\n\n See the `Supervisor` docs for more information.\n\n ## Name registration\n\n Both `start_link\/3` and `start\/3` support the `GenServer` to register\n a name on start via the `:name` option. Registered names are also\n automatically cleaned up on termination. The supported values are:\n\n * an atom - the GenServer is registered locally with the given name\n using `Process.register\/2`.\n\n * `{:global, term}` - the GenServer is registered globally with the given\n term using the functions in the [`:global` module](http:\/\/www.erlang.org\/doc\/man\/global.html).\n\n * `{:via, module, term}` - the GenServer is registered with the given\n mechanism and name. The `:via` option expects a module that exports\n `register_name\/2`, `unregister_name\/1`, `whereis_name\/1` and `send\/2`.\n One such example is the [`:global` module](http:\/\/www.erlang.org\/doc\/man\/global.html) which uses these functions\n for keeping the list of names of processes and their associated PIDs\n that are available globally for a network of Elixir nodes. Elixir also\n ships with a local, decentralized and scalable registry called `Registry`\n for locally storing names that are generated dynamically.\n\n For example, we could start and register our `Stack` server locally as follows:\n\n # Start the server and register it locally with name MyStack\n {:ok, _} = GenServer.start_link(Stack, [:hello], name: MyStack)\n\n # Now messages can be sent directly to MyStack\n GenServer.call(MyStack, :pop) #=> :hello\n\n Once the server is started, the remaining functions in this module (`call\/3`,\n `cast\/2`, and friends) will also accept an atom, or any `:global` or `:via`\n tuples. In general, the following formats are supported:\n\n * a `pid`\n * an `atom` if the server is locally registered\n * `{atom, node}` if the server is locally registered at another node\n * `{:global, term}` if the server is globally registered\n * `{:via, module, name}` if the server is registered through an alternative\n registry\n\n If there is an interest to register dynamic names locally, do not use\n atoms, as atoms are never garbage collected and therefore dynamically\n generated atoms won't be garbage collected. For such cases, you can\n set up your own local registry by using the `Registry` module.\n\n ## Client \/ Server APIs\n\n Although in the example above we have used `GenServer.start_link\/3` and\n friends to directly start and communicate with the server, most of the\n time we don't call the `GenServer` functions directly. Instead, we wrap\n the calls in new functions representing the public API of the server.\n\n Here is a better implementation of our Stack module:\n\n defmodule Stack do\n use GenServer\n\n # Client\n\n def start_link(default) do\n GenServer.start_link(__MODULE__, default)\n end\n\n def push(pid, item) do\n GenServer.cast(pid, {:push, item})\n end\n\n def pop(pid) do\n GenServer.call(pid, :pop)\n end\n\n # Server (callbacks)\n\n def handle_call(:pop, _from, [h | t]) do\n {:reply, h, t}\n end\n\n def handle_call(request, from, state) do\n # Call the default implementation from GenServer\n super(request, from, state)\n end\n\n def handle_cast({:push, item}, state) do\n {:noreply, [item | state]}\n end\n\n def handle_cast(request, state) do\n super(request, state)\n end\n end\n\n In practice, it is common to have both server and client functions in\n the same module. If the server and\/or client implementations are growing\n complex, you may want to have them in different modules.\n\n ## Receiving \"regular\" messages\n\n The goal of a `GenServer` is to abstract the \"receive\" loop for developers,\n automatically handling system messages, support code change, synchronous\n calls and more. Therefore, you should never call your own \"receive\" inside\n the GenServer callbacks as doing so will cause the GenServer to misbehave.\n\n Besides the synchronous and asynchronous communication provided by `call\/3`\n and `cast\/2`, \"regular\" messages sent by functions such as `Kernel.send\/2`,\n `Process.send_after\/4` and similar, can be handled inside the `c:handle_info\/2`\n callback.\n\n `c:handle_info\/2` can be used in many situations, such as handling monitor\n DOWN messages sent by `Process.monitor\/1`. Another use case for `c:handle_info\/2`\n is to perform periodic work, with the help of `Process.send_after\/4`:\n\n defmodule MyApp.Periodically do\n use GenServer\n\n def start_link do\n GenServer.start_link(__MODULE__, %{})\n end\n\n def init(state) do\n schedule_work() # Schedule work to be performed on start\n {:ok, state}\n end\n\n def handle_info(:work, state) do\n # Do the desired work here\n schedule_work() # Reschedule once more\n {:noreply, state}\n end\n\n defp schedule_work() do\n Process.send_after(self(), :work, 2 * 60 * 60 * 1000) # In 2 hours\n end\n end\n\n ## Debugging with the :sys module\n\n GenServers, as [special processes](http:\/\/erlang.org\/doc\/design_principles\/spec_proc.html),\n can be debugged using the [`:sys` module](http:\/\/www.erlang.org\/doc\/man\/sys.html). Through various hooks, this module\n allows developers to introspect the state of the process and trace\n system events that happen during its execution, such as received messages,\n sent replies and state changes.\n\n Let's explore the basic functions from the\n [`:sys` module](http:\/\/www.erlang.org\/doc\/man\/sys.html) used for debugging:\n\n * `:sys.get_state\/2` - allows retrieval of the state of the process.\n In the case of a GenServer process, it will be the callback module state,\n as passed into the callback functions as last argument.\n * `:sys.get_status\/2` - allows retrieval of the status of the process.\n This status includes the process dictionary, if the process is running\n or is suspended, the parent PID, the debugger state, and the state of\n the behaviour module, which includes the callback module state\n (as returned by `:sys.get_state\/2`). It's possible to change how this\n status is represented by defining the optional `c:GenServer.format_status\/2`\n callback.\n * `:sys.trace\/3` - prints all the system events to `:stdio`.\n * `:sys.statistics\/3` - manages collection of process statistics.\n * `:sys.no_debug\/2` - turns off all debug handlers for the given process.\n It is very important to switch off debugging once we're done. Excessive\n debug handlers or those that should be turned off, but weren't, can\n seriously damage the performance of the system.\n * `:sys.suspend\/2` - allows to suspend a process so that it only\n replies to system messages but no other messages. A suspended process\n can be reactivated via `:sys.resume\/2`.\n\n Let's see how we could use those functions for debugging the stack server\n we defined earlier.\n\n iex> {:ok, pid} = Stack.start_link([])\n iex> :sys.statistics(pid, true) # turn on collecting process statistics\n iex> :sys.trace(pid, true) # turn on event printing\n iex> Stack.push(pid, 1)\n *DBG* <0.122.0> got cast {push,1}\n *DBG* <0.122.0> new state [1]\n :ok\n iex> :sys.get_state(pid)\n [1]\n iex> Stack.pop(pid)\n *DBG* <0.122.0> got call pop from <0.80.0>\n *DBG* <0.122.0> sent 1 to <0.80.0>, new state []\n 1\n iex> :sys.statistics(pid, :get)\n {:ok,\n [start_time: {{2016, 7, 16}, {12, 29, 41}},\n current_time: {{2016, 7, 16}, {12, 29, 50}},\n reductions: 117, messages_in: 2, messages_out: 0]}\n iex> :sys.no_debug(pid) # turn off all debug handlers\n :ok\n iex> :sys.get_status(pid)\n {:status, #PID<0.122.0>, {:module, :gen_server},\n [[\"$initial_call\": {Stack, :init, 1}, # pdict\n \"$ancestors\": [#PID<0.80.0>, #PID<0.51.0>]],\n :running, # :running | :suspended\n #PID<0.80.0>, # parent\n [], # debugger state\n [header: 'Status for generic server <0.122.0>', # module status\n data: [{'Status', :running}, {'Parent', #PID<0.80.0>},\n {'Logged events', []}], data: [{'State', [1]}]]]}\n\n ## Learn more\n\n If you wish to find out more about GenServers, the Elixir Getting Started\n guide provides a tutorial-like introduction. The documentation and links\n in Erlang can also provide extra insight.\n\n * [GenServer \u2013 Elixir's Getting Started Guide](http:\/\/elixir-lang.org\/getting-started\/mix-otp\/genserver.html)\n * [`:gen_server` module documentation](http:\/\/www.erlang.org\/doc\/man\/gen_server.html)\n * [gen_server Behaviour \u2013 OTP Design Principles](http:\/\/www.erlang.org\/doc\/design_principles\/gen_server_concepts.html)\n * [Clients and Servers \u2013 Learn You Some Erlang for Great Good!](http:\/\/learnyousomeerlang.com\/clients-and-servers)\n \"\"\"\n\n @doc \"\"\"\n Invoked when the server is started. `start_link\/3` or `start\/3` will\n block until it returns.\n\n `args` is the argument term (second argument) passed to `start_link\/3`.\n\n Returning `{:ok, state}` will cause `start_link\/3` to return\n `{:ok, pid}` and the process to enter its loop.\n\n Returning `{:ok, state, timeout}` is similar to `{:ok, state}`\n except `handle_info(:timeout, state)` will be called after `timeout`\n milliseconds if no messages are received within the timeout.\n\n Returning `{:ok, state, :hibernate}` is similar to\n `{:ok, state}` except the process is hibernated before entering the loop. See\n `c:handle_call\/3` for more information on hibernation.\n\n Returning `:ignore` will cause `start_link\/3` to return `:ignore` and the\n process will exit normally without entering the loop or calling `c:terminate\/2`.\n If used when part of a supervision tree the parent supervisor will not fail\n to start nor immediately try to restart the `GenServer`. The remainder of the\n supervision tree will be (re)started and so the `GenServer` should not be\n required by other processes. It can be started later with\n `Supervisor.restart_child\/2` as the child specification is saved in the parent\n supervisor. The main use cases for this are:\n\n * The `GenServer` is disabled by configuration but might be enabled later.\n * An error occurred and it will be handled by a different mechanism than the\n `Supervisor`. Likely this approach involves calling `Supervisor.restart_child\/2`\n after a delay to attempt a restart.\n\n Returning `{:stop, reason}` will cause `start_link\/3` to return\n `{:error, reason}` and the process to exit with reason `reason` without\n entering the loop or calling `c:terminate\/2`.\n \"\"\"\n @callback init(args :: term) ::\n {:ok, state}\n | {:ok, state, timeout | :hibernate}\n | :ignore\n | {:stop, reason :: any}\n when state: any\n\n @doc \"\"\"\n Invoked to handle synchronous `call\/3` messages. `call\/3` will block until a\n reply is received (unless the call times out or nodes are disconnected).\n\n `request` is the request message sent by a `call\/3`, `from` is a 2-tuple\n containing the caller's PID and a term that uniquely identifies the call, and\n `state` is the current state of the `GenServer`.\n\n Returning `{:reply, reply, new_state}` sends the response `reply` to the\n caller and continues the loop with new state `new_state`.\n\n Returning `{:reply, reply, new_state, timeout}` is similar to\n `{:reply, reply, new_state}` except `handle_info(:timeout, new_state)` will be\n called after `timeout` milliseconds if no messages are received.\n\n Returning `{:reply, reply, new_state, :hibernate}` is similar to\n `{:reply, reply, new_state}` except the process is hibernated and will\n continue the loop once a message is in its message queue. If a message is\n already in the message queue this will be immediately. Hibernating a\n `GenServer` causes garbage collection and leaves a continuous heap that\n minimises the memory used by the process.\n\n Hibernating should not be used aggressively as too much time could be spent\n garbage collecting. Normally it should only be used when a message is not\n expected soon and minimising the memory of the process is shown to be\n beneficial.\n\n Returning `{:noreply, new_state}` does not send a response to the caller and\n continues the loop with new state `new_state`. The response must be sent with\n `reply\/2`.\n\n There are three main use cases for not replying using the return value:\n\n * To reply before returning from the callback because the response is known\n before calling a slow function.\n * To reply after returning from the callback because the response is not yet\n available.\n * To reply from another process, such as a task.\n\n When replying from another process the `GenServer` should exit if the other\n process exits without replying as the caller will be blocking awaiting a\n reply.\n\n Returning `{:noreply, new_state, timeout | :hibernate}` is similar to\n `{:noreply, new_state}` except a timeout or hibernation occurs as with a\n `:reply` tuple.\n\n Returning `{:stop, reason, reply, new_state}` stops the loop and `c:terminate\/2`\n is called with reason `reason` and state `new_state`. Then the `reply` is sent\n as the response to call and the process exits with reason `reason`.\n\n Returning `{:stop, reason, new_state}` is similar to\n `{:stop, reason, reply, new_state}` except a reply is not sent.\n\n If this callback is not implemented, the default implementation by\n `use GenServer` will fail with a `RuntimeError` exception with a message:\n attempted to call `GenServer` but no `handle_call\/3` clause was provided.\n \"\"\"\n @callback handle_call(request :: term, from, state :: term) ::\n {:reply, reply, new_state}\n | {:reply, reply, new_state, timeout | :hibernate}\n | {:noreply, new_state}\n | {:noreply, new_state, timeout | :hibernate}\n | {:stop, reason, reply, new_state}\n | {:stop, reason, new_state}\n when reply: term, new_state: term, reason: term\n\n @doc \"\"\"\n Invoked to handle asynchronous `cast\/2` messages.\n\n `request` is the request message sent by a `cast\/2` and `state` is the current\n state of the `GenServer`.\n\n Returning `{:noreply, new_state}` continues the loop with new state `new_state`.\n\n Returning `{:noreply, new_state, timeout}` is similar to\n `{:noreply, new_state}` except `handle_info(:timeout, new_state)` will be\n called after `timeout` milliseconds if no messages are received.\n\n Returning `{:noreply, new_state, :hibernate}` is similar to\n `{:noreply, new_state}` except the process is hibernated before continuing the\n loop. See `c:handle_call\/3` for more information.\n\n Returning `{:stop, reason, new_state}` stops the loop and `c:terminate\/2` is\n called with the reason `reason` and state `new_state`. The process exits with\n reason `reason`.\n\n If this callback is not implemented, the default implementation by\n `use GenServer` will fail with a `RuntimeError` exception with a message:\n attempted to call `GenServer` but no `handle_cast\/2` clause was provided.\n \"\"\"\n @callback handle_cast(request :: term, state :: term) ::\n {:noreply, new_state}\n | {:noreply, new_state, timeout | :hibernate}\n | {:stop, reason :: term, new_state}\n when new_state: term\n\n @doc \"\"\"\n Invoked to handle all other messages.\n\n `msg` is the message and `state` is the current state of the `GenServer`. When\n a timeout occurs the message is `:timeout`.\n\n Return values are the same as `c:handle_cast\/2`.\n\n If this callback is not implemented, the default implementation by\n `use GenServer` will return `{:noreply, state}`.\n \"\"\"\n @callback handle_info(msg :: :timeout | term, state :: term) ::\n {:noreply, new_state}\n | {:noreply, new_state, timeout | :hibernate}\n | {:stop, reason :: term, new_state}\n when new_state: term\n\n @doc \"\"\"\n Invoked when the server is about to exit. It should do any cleanup required.\n\n `reason` is exit reason and `state` is the current state of the `GenServer`.\n The return value is ignored.\n\n `c:terminate\/2` is called if a callback (except `c:init\/1`) does one of the\n following:\n\n * returns a `:stop` tuple\n * raises\n * calls `Kernel.exit\/1`\n * returns an invalid value\n * the `GenServer` traps exits (using `Process.flag\/2`) *and* the parent\n process sends an exit signal\n\n If part of a supervision tree, a `GenServer`'s `Supervisor` will send an exit\n signal when shutting it down. The exit signal is based on the shutdown\n strategy in the child's specification. If it is `:brutal_kill` the `GenServer`\n is killed and so `c:terminate\/2` is not called. However if it is a timeout the\n `Supervisor` will send the exit signal `:shutdown` and the `GenServer` will\n have the duration of the timeout to call `c:terminate\/2` - if the process is\n still alive after the timeout it is killed.\n\n If the `GenServer` receives an exit signal (that is not `:normal`) from any\n process when it is not trapping exits it will exit abruptly with the same\n reason and so not call `c:terminate\/2`. Note that a process does *NOT* trap\n exits by default and an exit signal is sent when a linked process exits or its\n node is disconnected.\n\n Therefore it is not guaranteed that `c:terminate\/2` is called when a `GenServer`\n exits. For such reasons, we usually recommend important clean-up rules to\n happen in separated processes either by use of monitoring or by links\n themselves. For example if the `GenServer` controls a `port` (e.g.\n `:gen_tcp.socket`) or `t:File.io_device\/0`, they will be closed on receiving a\n `GenServer`'s exit signal and do not need to be closed in `c:terminate\/2`.\n\n If `reason` is not `:normal`, `:shutdown`, nor `{:shutdown, term}` an error is\n logged.\n \"\"\"\n @callback terminate(reason, state :: term) :: term\n when reason: :normal | :shutdown | {:shutdown, term}\n\n @doc \"\"\"\n Invoked to change the state of the `GenServer` when a different version of a\n module is loaded (hot code swapping) and the state's term structure should be\n changed.\n\n `old_vsn` is the previous version of the module (defined by the `@vsn`\n attribute) when upgrading. When downgrading the previous version is wrapped in\n a 2-tuple with first element `:down`. `state` is the current state of the\n `GenServer` and `extra` is any extra data required to change the state.\n\n Returning `{:ok, new_state}` changes the state to `new_state` and the code\n change is successful.\n\n Returning `{:error, reason}` fails the code change with reason `reason` and\n the state remains as the previous state.\n\n If `c:code_change\/3` raises the code change fails and the loop will continue\n with its previous state. Therefore this callback does not usually contain side effects.\n \"\"\"\n @callback code_change(old_vsn, state :: term, extra :: term) ::\n {:ok, new_state :: term}\n | {:error, reason :: term}\n | {:down, term}\n when old_vsn: term\n\n @doc \"\"\"\n Invoked in some cases to retrieve a formatted version of the `GenServer` status.\n\n This callback can be useful to control the *appearance* of the status of the\n `GenServer`. For example, it can be used to return a compact representation of\n the `GenServer`'s state to avoid having large state terms printed.\n\n * one of `:sys.get_status\/1` or `:sys.get_status\/2` is invoked to get the\n status of the `GenServer`; in such cases, `reason` is `:normal`\n\n * the `GenServer` terminates abnormally and logs an error; in such cases,\n `reason` is `:terminate`\n\n `pdict_and_state` is a two-elements list `[pdict, state]` where `pdict` is a\n list of `{key, value}` tuples representing the current process dictionary of\n the `GenServer` and `state` is the current state of the `GenServer`.\n \"\"\"\n @callback format_status(reason, pdict_and_state :: list) :: term\n when reason: :normal | :terminate\n\n @optional_callbacks format_status: 2\n\n @typedoc \"Return values of `start*` functions\"\n @type on_start :: {:ok, pid} | :ignore | {:error, {:already_started, pid} | term}\n\n @typedoc \"The GenServer name\"\n @type name :: atom | {:global, term} | {:via, module, term}\n\n @typedoc \"Options used by the `start*` functions\"\n @type options :: [option]\n\n @typedoc \"Option values used by the `start*` functions\"\n @type option ::\n {:debug, debug}\n | {:name, name}\n | {:timeout, timeout}\n | {:spawn_opt, Process.spawn_opt()}\n\n @typedoc \"Debug options supported by the `start*` functions\"\n @type debug :: [:trace | :log | :statistics | {:log_to_file, Path.t()}]\n\n @typedoc \"The server reference\"\n @type server :: pid | name | {atom, node}\n\n @typedoc \"\"\"\n Tuple describing the client of a call request.\n\n `pid` is the PID of the caller and `tag` is a unique term used to identify the\n call.\n \"\"\"\n @type from :: {pid, tag :: term}\n\n @doc false\n defmacro __using__(opts) do\n quote location: :keep, bind_quoted: [opts: opts] do\n @behaviour GenServer\n\n @doc \"\"\"\n Returns a specification to start this module under a supervisor.\n\n See `Supervisor`.\n \"\"\"\n def child_spec(arg) do\n default = %{\n id: __MODULE__,\n start: {__MODULE__, :start_link, [arg]}\n }\n\n Supervisor.child_spec(default, unquote(Macro.escape(opts)))\n end\n\n defoverridable child_spec: 1\n\n # TODO: Remove this on Elixir v2.0\n @before_compile GenServer\n\n @doc false\n def handle_call(msg, _from, state) do\n proc =\n case Process.info(self(), :registered_name) do\n {_, []} -> self()\n {_, name} -> name\n end\n\n # We do this to trick Dialyzer to not complain about non-local returns.\n case :erlang.phash2(1, 1) do\n 0 ->\n raise \"attempted to call GenServer #{inspect(proc)} but no handle_call\/3 clause was provided\"\n\n 1 ->\n {:stop, {:bad_call, msg}, state}\n end\n end\n\n @doc false\n def handle_info(msg, state) do\n proc =\n case Process.info(self(), :registered_name) do\n {_, []} -> self()\n {_, name} -> name\n end\n\n pattern = '~p ~p received unexpected message in handle_info\/2: ~p~n'\n :error_logger.error_msg(pattern, [__MODULE__, proc, msg])\n {:noreply, state}\n end\n\n @doc false\n def handle_cast(msg, state) do\n proc =\n case Process.info(self(), :registered_name) do\n {_, []} -> self()\n {_, name} -> name\n end\n\n # We do this to trick Dialyzer to not complain about non-local returns.\n case :erlang.phash2(1, 1) do\n 0 ->\n raise \"attempted to cast GenServer #{inspect(proc)} but no handle_cast\/2 clause was provided\"\n\n 1 ->\n {:stop, {:bad_cast, msg}, state}\n end\n end\n\n @doc false\n def terminate(_reason, _state) do\n :ok\n end\n\n @doc false\n def code_change(_old, state, _extra) do\n {:ok, state}\n end\n\n defoverridable GenServer\n end\n end\n\n defmacro __before_compile__(env) do\n unless Module.defines?(env.module, {:init, 1}) do\n message = \"\"\"\n function init\/1 required by behaviour GenServer is not implemented \\\n (in module #{inspect(env.module)}).\n\n We will inject a default implementation for now:\n\n def init(args) do\n {:ok, args}\n end\n\n But you want to define your own implementation that converts the \\\n arguments given to GenServer.start_link\/3 to the server state\n \"\"\"\n\n :elixir_errors.warn(env.line, env.file, message)\n\n quote do\n @doc false\n def init(args) do\n {:ok, args}\n end\n\n defoverridable init: 1\n end\n end\n end\n\n @doc \"\"\"\n Starts a `GenServer` process linked to the current process.\n\n This is often used to start the `GenServer` as part of a supervision tree.\n\n Once the server is started, the `c:init\/1` function of the given `module` is\n called with `args` as its arguments to initialize the server. To ensure a\n synchronized start-up procedure, this function does not return until `c:init\/1`\n has returned.\n\n Note that a `GenServer` started with `start_link\/3` is linked to the\n parent process and will exit in case of crashes from the parent. The GenServer\n will also exit due to the `:normal` reasons in case it is configured to trap\n exits in the `c:init\/1` callback.\n\n ## Options\n\n * `:name` - used for name registration as described in the \"Name\n registration\" section of the module documentation\n\n * `:timeout` - if present, the server is allowed to spend the given number of\n milliseconds initializing or it will be terminated and the start function\n will return `{:error, :timeout}`\n\n * `:debug` - if present, the corresponding function in the [`:sys` module](http:\/\/www.erlang.org\/doc\/man\/sys.html) is invoked\n\n * `:spawn_opt` - if present, its value is passed as options to the\n underlying process as in `Process.spawn\/4`\n\n ## Return values\n\n If the server is successfully created and initialized, this function returns\n `{:ok, pid}`, where `pid` is the PID of the server. If a process with the\n specified server name already exists, this function returns\n `{:error, {:already_started, pid}}` with the PID of that process.\n\n If the `c:init\/1` callback fails with `reason`, this function returns\n `{:error, reason}`. Otherwise, if it returns `{:stop, reason}`\n or `:ignore`, the process is terminated and this function returns\n `{:error, reason}` or `:ignore`, respectively.\n \"\"\"\n @spec start_link(module, any, options) :: on_start\n def start_link(module, args, options \\\\ []) when is_atom(module) and is_list(options) do\n do_start(:link, module, args, options)\n end\n\n @doc \"\"\"\n Starts a `GenServer` process without links (outside of a supervision tree).\n\n See `start_link\/3` for more information.\n \"\"\"\n @spec start(module, any, options) :: on_start\n def start(module, args, options \\\\ []) when is_atom(module) and is_list(options) do\n do_start(:nolink, module, args, options)\n end\n\n defp do_start(link, module, args, options) do\n case Keyword.pop(options, :name) do\n {nil, opts} ->\n :gen.start(:gen_server, link, module, args, opts)\n\n {atom, opts} when is_atom(atom) ->\n :gen.start(:gen_server, link, {:local, atom}, module, args, opts)\n\n {{:global, _term} = tuple, opts} ->\n :gen.start(:gen_server, link, tuple, module, args, opts)\n\n {{:via, via_module, _term} = tuple, opts} when is_atom(via_module) ->\n :gen.start(:gen_server, link, tuple, module, args, opts)\n\n {other, _} ->\n raise ArgumentError, \"\"\"\n expected :name option to be one of:\n\n * nil\n * atom\n * {:global, term}\n * {:via, module, term}\n\n Got: #{inspect(other)}\n \"\"\"\n end\n end\n\n @doc \"\"\"\n Synchronously stops the server with the given `reason`.\n\n The `c:terminate\/2` callback of the given `server` will be invoked before\n exiting. This function returns `:ok` if the server terminates with the\n given reason; if it terminates with another reason, the call exits.\n\n This function keeps OTP semantics regarding error reporting.\n If the reason is any other than `:normal`, `:shutdown` or\n `{:shutdown, _}`, an error report is logged.\n \"\"\"\n @spec stop(server, reason :: term, timeout) :: :ok\n def stop(server, reason \\\\ :normal, timeout \\\\ :infinity) do\n case whereis(server) do\n nil ->\n exit({:noproc, {__MODULE__, :stop, [server, reason, timeout]}})\n\n pid when pid == self() ->\n exit({:calling_self, {__MODULE__, :stop, [server, reason, timeout]}})\n\n pid ->\n try do\n :proc_lib.stop(pid, reason, timeout)\n catch\n :exit, err ->\n exit({err, {__MODULE__, :stop, [server, reason, timeout]}})\n end\n end\n end\n\n @doc \"\"\"\n Makes a synchronous call to the `server` and waits for its reply.\n\n The client sends the given `request` to the server and waits until a reply\n arrives or a timeout occurs. `c:handle_call\/3` will be called on the server\n to handle the request.\n\n `server` can be any of the values described in the \"Name registration\"\n section of the documentation for this module.\n\n ## Timeouts\n\n `timeout` is an integer greater than zero which specifies how many\n milliseconds to wait for a reply, or the atom `:infinity` to wait\n indefinitely. The default value is `5000`. If no reply is received within\n the specified time, the function call fails and the caller exits. If the\n caller catches the failure and continues running, and the server is just late\n with the reply, it may arrive at any time later into the caller's message\n queue. The caller must in this case be prepared for this and discard any such\n garbage messages that are two-element tuples with a reference as the first\n element.\n \"\"\"\n @spec call(server, term, timeout) :: term\n def call(server, request, timeout \\\\ 5000) do\n case whereis(server) do\n nil ->\n exit({:noproc, {__MODULE__, :call, [server, request, timeout]}})\n\n pid when pid == self() ->\n exit({:calling_self, {__MODULE__, :call, [server, request, timeout]}})\n\n pid ->\n try do\n :gen.call(pid, :\"$gen_call\", request, timeout)\n catch\n :exit, reason ->\n exit({reason, {__MODULE__, :call, [server, request, timeout]}})\n else\n {:ok, res} -> res\n end\n end\n end\n\n @doc \"\"\"\n Sends an asynchronous request to the `server`.\n\n This function always returns `:ok` regardless of whether\n the destination `server` (or node) exists. Therefore it\n is unknown whether the destination `server` successfully\n handled the message.\n\n `c:handle_cast\/2` will be called on the server to handle\n the request. In case the `server` is on a node which is\n not yet connected to the caller one, the call is going to\n block until a connection happens. This is different than\n the behaviour in OTP's `:gen_server` where the message\n is sent by another process in this case, which could cause\n messages to other nodes to arrive out of order.\n \"\"\"\n @spec cast(server, term) :: :ok\n def cast(server, request)\n\n def cast({:global, name}, request) do\n try do\n :global.send(name, cast_msg(request))\n :ok\n catch\n _, _ -> :ok\n end\n end\n\n def cast({:via, mod, name}, request) do\n try do\n mod.send(name, cast_msg(request))\n :ok\n catch\n _, _ -> :ok\n end\n end\n\n def cast({name, node}, request) when is_atom(name) and is_atom(node),\n do: do_send({name, node}, cast_msg(request))\n\n def cast(dest, request) when is_atom(dest) or is_pid(dest), do: do_send(dest, cast_msg(request))\n\n @doc \"\"\"\n Casts all servers locally registered as `name` at the specified nodes.\n\n This function returns immediately and ignores nodes that do not exist, or where the\n server name does not exist.\n\n See `multi_call\/4` for more information.\n \"\"\"\n @spec abcast([node], name :: atom, term) :: :abcast\n def abcast(nodes \\\\ [node() | Node.list()], name, request)\n when is_list(nodes) and is_atom(name) do\n msg = cast_msg(request)\n _ = for node <- nodes, do: do_send({name, node}, msg)\n :abcast\n end\n\n defp cast_msg(req) do\n {:\"$gen_cast\", req}\n end\n\n defp do_send(dest, msg) do\n try do\n send(dest, msg)\n :ok\n catch\n _, _ -> :ok\n end\n end\n\n @doc \"\"\"\n Calls all servers locally registered as `name` at the specified `nodes`.\n\n First, the `request` is sent to every node in `nodes`; then, the caller waits\n for the replies. This function returns a two-element tuple `{replies,\n bad_nodes}` where:\n\n * `replies` - is a list of `{node, reply}` tuples where `node` is the node\n that replied and `reply` is its reply\n * `bad_nodes` - is a list of nodes that either did not exist or where a\n server with the given `name` did not exist or did not reply\n\n `nodes` is a list of node names to which the request is sent. The default\n value is the list of all known nodes (including this node).\n\n To avoid that late answers (after the timeout) pollute the caller's message\n queue, a middleman process is used to do the actual calls. Late answers will\n then be discarded when they arrive to a terminated process.\n\n ## Examples\n\n Assuming the `Stack` GenServer mentioned in the docs for the `GenServer`\n module is registered as `Stack` in the `:\"foo@my-machine\"` and\n `:\"bar@my-machine\"` nodes:\n\n GenServer.multi_call(Stack, :pop)\n #=> {[{:\"foo@my-machine\", :hello}, {:\"bar@my-machine\", :world}], []}\n\n \"\"\"\n @spec multi_call([node], name :: atom, term, timeout) ::\n {replies :: [{node, term}], bad_nodes :: [node]}\n def multi_call(nodes \\\\ [node() | Node.list()], name, request, timeout \\\\ :infinity) do\n :gen_server.multi_call(nodes, name, request, timeout)\n end\n\n @doc \"\"\"\n Replies to a client.\n\n This function can be used to explicitly send a reply to a client that called\n `call\/3` or `multi_call\/4` when the reply cannot be specified in the return\n value of `c:handle_call\/3`.\n\n `client` must be the `from` argument (the second argument) accepted by\n `c:handle_call\/3` callbacks. `reply` is an arbitrary term which will be given\n back to the client as the return value of the call.\n\n Note that `reply\/2` can be called from any process, not just the GenServer\n that originally received the call (as long as that GenServer communicated the\n `from` argument somehow).\n\n This function always returns `:ok`.\n\n ## Examples\n\n def handle_call(:reply_in_one_second, from, state) do\n Process.send_after(self(), {:reply, from}, 1_000)\n {:noreply, state}\n end\n\n def handle_info({:reply, from}, state) do\n GenServer.reply(from, :one_second_has_passed)\n {:noreply, state}\n end\n\n \"\"\"\n @spec reply(from, term) :: :ok\n def reply(client, reply)\n\n def reply({to, tag}, reply) when is_pid(to) do\n try do\n send(to, {tag, reply})\n :ok\n catch\n _, _ -> :ok\n end\n end\n\n @doc \"\"\"\n Returns the `pid` or `{name, node}` of a GenServer process, or `nil` if\n no process is associated with the given `server`.\n\n ## Examples\n\n For example, to lookup a server process, monitor it and send a cast to it:\n\n process = GenServer.whereis(server)\n monitor = Process.monitor(process)\n GenServer.cast(process, :hello)\n\n \"\"\"\n @spec whereis(server) :: pid | {atom, node} | nil\n def whereis(server)\n\n def whereis(pid) when is_pid(pid), do: pid\n\n def whereis(name) when is_atom(name) do\n Process.whereis(name)\n end\n\n def whereis({:global, name}) do\n case :global.whereis_name(name) do\n pid when is_pid(pid) -> pid\n :undefined -> nil\n end\n end\n\n def whereis({:via, mod, name}) do\n case apply(mod, :whereis_name, [name]) do\n pid when is_pid(pid) -> pid\n :undefined -> nil\n end\n end\n\n def whereis({name, local}) when is_atom(name) and local == node() do\n Process.whereis(name)\n end\n\n def whereis({name, node} = server) when is_atom(name) and is_atom(node) do\n server\n end\nend\n","old_contents":"defmodule GenServer do\n @moduledoc \"\"\"\n A behaviour module for implementing the server of a client-server relation.\n\n A GenServer is a process like any other Elixir process and it can be used\n to keep state, execute code asynchronously and so on. The advantage of using\n a generic server process (GenServer) implemented using this module is that it\n will have a standard set of interface functions and include functionality for\n tracing and error reporting. It will also fit into a supervision tree.\n\n ## Example\n\n The GenServer behaviour abstracts the common client-server interaction.\n Developers are only required to implement the callbacks and functionality\n they are interested in.\n\n Let's start with a code example and then explore the available callbacks.\n Imagine we want a GenServer that works like a stack, allowing us to push\n and pop items:\n\n defmodule Stack do\n use GenServer\n\n # Callbacks\n\n def handle_call(:pop, _from, [h | t]) do\n {:reply, h, t}\n end\n\n def handle_cast({:push, item}, state) do\n {:noreply, [item | state]}\n end\n end\n\n # Start the server\n {:ok, pid} = GenServer.start_link(Stack, [:hello])\n\n # This is the client\n GenServer.call(pid, :pop)\n #=> :hello\n\n GenServer.cast(pid, {:push, :world})\n #=> :ok\n\n GenServer.call(pid, :pop)\n #=> :world\n\n We start our `Stack` by calling `start_link\/2`, passing the module\n with the server implementation and its initial argument (a list\n representing the stack containing the item `:hello`). We can primarily\n interact with the server by sending two types of messages. **call**\n messages expect a reply from the server (and are therefore synchronous)\n while **cast** messages do not.\n\n Every time you do a `GenServer.call\/3`, the client will send a message\n that must be handled by the `c:handle_call\/3` callback in the GenServer.\n A `cast\/2` message must be handled by `c:handle_cast\/2`.\n\n ## use GenServer and callbacks\n\n There are 6 callbacks required to be implemented in a `GenServer`. By\n adding `use GenServer` to your module, Elixir will automatically define\n all 6 callbacks for you, leaving it up to you to implement the ones\n you want to customize.\n\n `use GenServer` also defines a `child_spec\/1` function, allowing the\n defined module to be put under a supervision tree. The generated\n `child_spec\/1` can be customized with the following options:\n\n * `:id` - the child specification id, defaults to the current module\n * `:start` - how to start the child process (defaults to calling `__MODULE__.start_link\/1`)\n * `:restart` - when the child should be restarted, defaults to `:permanent`\n * `:shutdown` - how to shut down the child\n\n For example:\n\n use GenServer, restart: :transient, shutdown: 10_000\n\n See the `Supervisor` docs for more information.\n\n ## Name registration\n\n Both `start_link\/3` and `start\/3` support the `GenServer` to register\n a name on start via the `:name` option. Registered names are also\n automatically cleaned up on termination. The supported values are:\n\n * an atom - the GenServer is registered locally with the given name\n using `Process.register\/2`.\n\n * `{:global, term}`- the GenServer is registered globally with the given\n term using the functions in the [`:global` module](http:\/\/www.erlang.org\/doc\/man\/global.html).\n\n * `{:via, module, term}` - the GenServer is registered with the given\n mechanism and name. The `:via` option expects a module that exports\n `register_name\/2`, `unregister_name\/1`, `whereis_name\/1` and `send\/2`.\n One such example is the [`:global` module](http:\/\/www.erlang.org\/doc\/man\/global.html) which uses these functions\n for keeping the list of names of processes and their associated PIDs\n that are available globally for a network of Elixir nodes. Elixir also\n ships with a local, decentralized and scalable registry called `Registry`\n for locally storing names that are generated dynamically.\n\n For example, we could start and register our `Stack` server locally as follows:\n\n # Start the server and register it locally with name MyStack\n {:ok, _} = GenServer.start_link(Stack, [:hello], name: MyStack)\n\n # Now messages can be sent directly to MyStack\n GenServer.call(MyStack, :pop) #=> :hello\n\n Once the server is started, the remaining functions in this module (`call\/3`,\n `cast\/2`, and friends) will also accept an atom, or any `:global` or `:via`\n tuples. In general, the following formats are supported:\n\n * a `pid`\n * an `atom` if the server is locally registered\n * `{atom, node}` if the server is locally registered at another node\n * `{:global, term}` if the server is globally registered\n * `{:via, module, name}` if the server is registered through an alternative\n registry\n\n If there is an interest to register dynamic names locally, do not use\n atoms, as atoms are never garbage collected and therefore dynamically\n generated atoms won't be garbage collected. For such cases, you can\n set up your own local registry by using the `Registry` module.\n\n ## Client \/ Server APIs\n\n Although in the example above we have used `GenServer.start_link\/3` and\n friends to directly start and communicate with the server, most of the\n time we don't call the `GenServer` functions directly. Instead, we wrap\n the calls in new functions representing the public API of the server.\n\n Here is a better implementation of our Stack module:\n\n defmodule Stack do\n use GenServer\n\n # Client\n\n def start_link(default) do\n GenServer.start_link(__MODULE__, default)\n end\n\n def push(pid, item) do\n GenServer.cast(pid, {:push, item})\n end\n\n def pop(pid) do\n GenServer.call(pid, :pop)\n end\n\n # Server (callbacks)\n\n def handle_call(:pop, _from, [h | t]) do\n {:reply, h, t}\n end\n\n def handle_call(request, from, state) do\n # Call the default implementation from GenServer\n super(request, from, state)\n end\n\n def handle_cast({:push, item}, state) do\n {:noreply, [item | state]}\n end\n\n def handle_cast(request, state) do\n super(request, state)\n end\n end\n\n In practice, it is common to have both server and client functions in\n the same module. If the server and\/or client implementations are growing\n complex, you may want to have them in different modules.\n\n ## Receiving \"regular\" messages\n\n The goal of a `GenServer` is to abstract the \"receive\" loop for developers,\n automatically handling system messages, support code change, synchronous\n calls and more. Therefore, you should never call your own \"receive\" inside\n the GenServer callbacks as doing so will cause the GenServer to misbehave.\n\n Besides the synchronous and asynchronous communication provided by `call\/3`\n and `cast\/2`, \"regular\" messages sent by functions such `Kernel.send\/2`,\n `Process.send_after\/4` and similar, can be handled inside the `c:handle_info\/2`\n callback.\n\n `c:handle_info\/2` can be used in many situations, such as handling monitor\n DOWN messages sent by `Process.monitor\/1`. Another use case for `c:handle_info\/2`\n is to perform periodic work, with the help of `Process.send_after\/4`:\n\n defmodule MyApp.Periodically do\n use GenServer\n\n def start_link do\n GenServer.start_link(__MODULE__, %{})\n end\n\n def init(state) do\n schedule_work() # Schedule work to be performed on start\n {:ok, state}\n end\n\n def handle_info(:work, state) do\n # Do the desired work here\n schedule_work() # Reschedule once more\n {:noreply, state}\n end\n\n defp schedule_work() do\n Process.send_after(self(), :work, 2 * 60 * 60 * 1000) # In 2 hours\n end\n end\n\n ## Debugging with the :sys module\n\n GenServers, as [special processes](http:\/\/erlang.org\/doc\/design_principles\/spec_proc.html),\n can be debugged using the [`:sys` module](http:\/\/www.erlang.org\/doc\/man\/sys.html). Through various hooks, this module\n allows developers to introspect the state of the process and trace\n system events that happen during its execution, such as received messages,\n sent replies and state changes.\n\n Let's explore the basic functions from the\n [`:sys` module](http:\/\/www.erlang.org\/doc\/man\/sys.html) used for debugging:\n\n * `:sys.get_state\/2` - allows retrieval of the state of the process.\n In the case of a GenServer process, it will be the callback module state,\n as passed into the callback functions as last argument.\n * `:sys.get_status\/2` - allows retrieval of the status of the process.\n This status includes the process dictionary, if the process is running\n or is suspended, the parent PID, the debugger state, and the state of\n the behaviour module, which includes the callback module state\n (as returned by `:sys.get_state\/2`). It's possible to change how this\n status is represented by defining the optional `c:GenServer.format_status\/2`\n callback.\n * `:sys.trace\/3` - prints all the system events to `:stdio`.\n * `:sys.statistics\/3` - manages collection of process statistics.\n * `:sys.no_debug\/2` - turns off all debug handlers for the given process.\n It is very important to switch off debugging once we're done. Excessive\n debug handlers or those that should be turned off, but weren't, can\n seriously damage the performance of the system.\n * `:sys.suspend\/2` - allows to suspend a process so that it only\n replies to system messages but no other messages. A suspended process\n can be reactivated via `:sys.resume\/2`.\n\n Let's see how we could use those functions for debugging the stack server\n we defined earlier.\n\n iex> {:ok, pid} = Stack.start_link([])\n iex> :sys.statistics(pid, true) # turn on collecting process statistics\n iex> :sys.trace(pid, true) # turn on event printing\n iex> Stack.push(pid, 1)\n *DBG* <0.122.0> got cast {push,1}\n *DBG* <0.122.0> new state [1]\n :ok\n iex> :sys.get_state(pid)\n [1]\n iex> Stack.pop(pid)\n *DBG* <0.122.0> got call pop from <0.80.0>\n *DBG* <0.122.0> sent 1 to <0.80.0>, new state []\n 1\n iex> :sys.statistics(pid, :get)\n {:ok,\n [start_time: {{2016, 7, 16}, {12, 29, 41}},\n current_time: {{2016, 7, 16}, {12, 29, 50}},\n reductions: 117, messages_in: 2, messages_out: 0]}\n iex> :sys.no_debug(pid) # turn off all debug handlers\n :ok\n iex> :sys.get_status(pid)\n {:status, #PID<0.122.0>, {:module, :gen_server},\n [[\"$initial_call\": {Stack, :init, 1}, # pdict\n \"$ancestors\": [#PID<0.80.0>, #PID<0.51.0>]],\n :running, # :running | :suspended\n #PID<0.80.0>, # parent\n [], # debugger state\n [header: 'Status for generic server <0.122.0>', # module status\n data: [{'Status', :running}, {'Parent', #PID<0.80.0>},\n {'Logged events', []}], data: [{'State', [1]}]]]}\n\n ## Learn more\n\n If you wish to find out more about GenServers, the Elixir Getting Started\n guide provides a tutorial-like introduction. The documentation and links\n in Erlang can also provide extra insight.\n\n * [GenServer \u2013 Elixir's Getting Started Guide](http:\/\/elixir-lang.org\/getting-started\/mix-otp\/genserver.html)\n * [`:gen_server` module documentation](http:\/\/www.erlang.org\/doc\/man\/gen_server.html)\n * [gen_server Behaviour \u2013 OTP Design Principles](http:\/\/www.erlang.org\/doc\/design_principles\/gen_server_concepts.html)\n * [Clients and Servers \u2013 Learn You Some Erlang for Great Good!](http:\/\/learnyousomeerlang.com\/clients-and-servers)\n \"\"\"\n\n @doc \"\"\"\n Invoked when the server is started. `start_link\/3` or `start\/3` will\n block until it returns.\n\n `args` is the argument term (second argument) passed to `start_link\/3`.\n\n Returning `{:ok, state}` will cause `start_link\/3` to return\n `{:ok, pid}` and the process to enter its loop.\n\n Returning `{:ok, state, timeout}` is similar to `{:ok, state}`\n except `handle_info(:timeout, state)` will be called after `timeout`\n milliseconds if no messages are received within the timeout.\n\n Returning `{:ok, state, :hibernate}` is similar to\n `{:ok, state}` except the process is hibernated before entering the loop. See\n `c:handle_call\/3` for more information on hibernation.\n\n Returning `:ignore` will cause `start_link\/3` to return `:ignore` and the\n process will exit normally without entering the loop or calling `c:terminate\/2`.\n If used when part of a supervision tree the parent supervisor will not fail\n to start nor immediately try to restart the `GenServer`. The remainder of the\n supervision tree will be (re)started and so the `GenServer` should not be\n required by other processes. It can be started later with\n `Supervisor.restart_child\/2` as the child specification is saved in the parent\n supervisor. The main use cases for this are:\n\n * The `GenServer` is disabled by configuration but might be enabled later.\n * An error occurred and it will be handled by a different mechanism than the\n `Supervisor`. Likely this approach involves calling `Supervisor.restart_child\/2`\n after a delay to attempt a restart.\n\n Returning `{:stop, reason}` will cause `start_link\/3` to return\n `{:error, reason}` and the process to exit with reason `reason` without\n entering the loop or calling `c:terminate\/2`.\n \"\"\"\n @callback init(args :: term) ::\n {:ok, state}\n | {:ok, state, timeout | :hibernate}\n | :ignore\n | {:stop, reason :: any}\n when state: any\n\n @doc \"\"\"\n Invoked to handle synchronous `call\/3` messages. `call\/3` will block until a\n reply is received (unless the call times out or nodes are disconnected).\n\n `request` is the request message sent by a `call\/3`, `from` is a 2-tuple\n containing the caller's PID and a term that uniquely identifies the call, and\n `state` is the current state of the `GenServer`.\n\n Returning `{:reply, reply, new_state}` sends the response `reply` to the\n caller and continues the loop with new state `new_state`.\n\n Returning `{:reply, reply, new_state, timeout}` is similar to\n `{:reply, reply, new_state}` except `handle_info(:timeout, new_state)` will be\n called after `timeout` milliseconds if no messages are received.\n\n Returning `{:reply, reply, new_state, :hibernate}` is similar to\n `{:reply, reply, new_state}` except the process is hibernated and will\n continue the loop once a message is in its message queue. If a message is\n already in the message queue this will be immediately. Hibernating a\n `GenServer` causes garbage collection and leaves a continuous heap that\n minimises the memory used by the process.\n\n Hibernating should not be used aggressively as too much time could be spent\n garbage collecting. Normally it should only be used when a message is not\n expected soon and minimising the memory of the process is shown to be\n beneficial.\n\n Returning `{:noreply, new_state}` does not send a response to the caller and\n continues the loop with new state `new_state`. The response must be sent with\n `reply\/2`.\n\n There are three main use cases for not replying using the return value:\n\n * To reply before returning from the callback because the response is known\n before calling a slow function.\n * To reply after returning from the callback because the response is not yet\n available.\n * To reply from another process, such as a task.\n\n When replying from another process the `GenServer` should exit if the other\n process exits without replying as the caller will be blocking awaiting a\n reply.\n\n Returning `{:noreply, new_state, timeout | :hibernate}` is similar to\n `{:noreply, new_state}` except a timeout or hibernation occurs as with a\n `:reply` tuple.\n\n Returning `{:stop, reason, reply, new_state}` stops the loop and `c:terminate\/2`\n is called with reason `reason` and state `new_state`. Then the `reply` is sent\n as the response to call and the process exits with reason `reason`.\n\n Returning `{:stop, reason, new_state}` is similar to\n `{:stop, reason, reply, new_state}` except a reply is not sent.\n\n If this callback is not implemented, the default implementation by\n `use GenServer` will fail with a `RuntimeError` exception with a message:\n attempted to call `GenServer` but no `handle_call\/3` clause was provided.\n \"\"\"\n @callback handle_call(request :: term, from, state :: term) ::\n {:reply, reply, new_state}\n | {:reply, reply, new_state, timeout | :hibernate}\n | {:noreply, new_state}\n | {:noreply, new_state, timeout | :hibernate}\n | {:stop, reason, reply, new_state}\n | {:stop, reason, new_state}\n when reply: term, new_state: term, reason: term\n\n @doc \"\"\"\n Invoked to handle asynchronous `cast\/2` messages.\n\n `request` is the request message sent by a `cast\/2` and `state` is the current\n state of the `GenServer`.\n\n Returning `{:noreply, new_state}` continues the loop with new state `new_state`.\n\n Returning `{:noreply, new_state, timeout}` is similar to\n `{:noreply, new_state}` except `handle_info(:timeout, new_state)` will be\n called after `timeout` milliseconds if no messages are received.\n\n Returning `{:noreply, new_state, :hibernate}` is similar to\n `{:noreply, new_state}` except the process is hibernated before continuing the\n loop. See `c:handle_call\/3` for more information.\n\n Returning `{:stop, reason, new_state}` stops the loop and `c:terminate\/2` is\n called with the reason `reason` and state `new_state`. The process exits with\n reason `reason`.\n\n If this callback is not implemented, the default implementation by\n `use GenServer` will fail with a `RuntimeError` exception with a message:\n attempted to call `GenServer` but no `handle_cast\/2` clause was provided.\n \"\"\"\n @callback handle_cast(request :: term, state :: term) ::\n {:noreply, new_state}\n | {:noreply, new_state, timeout | :hibernate}\n | {:stop, reason :: term, new_state}\n when new_state: term\n\n @doc \"\"\"\n Invoked to handle all other messages.\n\n `msg` is the message and `state` is the current state of the `GenServer`. When\n a timeout occurs the message is `:timeout`.\n\n Return values are the same as `c:handle_cast\/2`.\n\n If this callback is not implemented, the default implementation by\n `use GenServer` will return `{:noreply, state}`.\n \"\"\"\n @callback handle_info(msg :: :timeout | term, state :: term) ::\n {:noreply, new_state}\n | {:noreply, new_state, timeout | :hibernate}\n | {:stop, reason :: term, new_state}\n when new_state: term\n\n @doc \"\"\"\n Invoked when the server is about to exit. It should do any cleanup required.\n\n `reason` is exit reason and `state` is the current state of the `GenServer`.\n The return value is ignored.\n\n `c:terminate\/2` is called if a callback (except `c:init\/1`) does one of the\n following:\n\n * returns a `:stop` tuple\n * raises\n * calls `Kernel.exit\/1`\n * returns an invalid value\n * the `GenServer` traps exits (using `Process.flag\/2`) *and* the parent\n process sends an exit signal\n\n If part of a supervision tree, a `GenServer`'s `Supervisor` will send an exit\n signal when shutting it down. The exit signal is based on the shutdown\n strategy in the child's specification. If it is `:brutal_kill` the `GenServer`\n is killed and so `c:terminate\/2` is not called. However if it is a timeout the\n `Supervisor` will send the exit signal `:shutdown` and the `GenServer` will\n have the duration of the timeout to call `c:terminate\/2` - if the process is\n still alive after the timeout it is killed.\n\n If the `GenServer` receives an exit signal (that is not `:normal`) from any\n process when it is not trapping exits it will exit abruptly with the same\n reason and so not call `c:terminate\/2`. Note that a process does *NOT* trap\n exits by default and an exit signal is sent when a linked process exits or its\n node is disconnected.\n\n Therefore it is not guaranteed that `c:terminate\/2` is called when a `GenServer`\n exits. For such reasons, we usually recommend important clean-up rules to\n happen in separated processes either by use of monitoring or by links\n themselves. For example if the `GenServer` controls a `port` (e.g.\n `:gen_tcp.socket`) or `t:File.io_device\/0`, they will be closed on receiving a\n `GenServer`'s exit signal and do not need to be closed in `c:terminate\/2`.\n\n If `reason` is not `:normal`, `:shutdown`, nor `{:shutdown, term}` an error is\n logged.\n \"\"\"\n @callback terminate(reason, state :: term) :: term\n when reason: :normal | :shutdown | {:shutdown, term}\n\n @doc \"\"\"\n Invoked to change the state of the `GenServer` when a different version of a\n module is loaded (hot code swapping) and the state's term structure should be\n changed.\n\n `old_vsn` is the previous version of the module (defined by the `@vsn`\n attribute) when upgrading. When downgrading the previous version is wrapped in\n a 2-tuple with first element `:down`. `state` is the current state of the\n `GenServer` and `extra` is any extra data required to change the state.\n\n Returning `{:ok, new_state}` changes the state to `new_state` and the code\n change is successful.\n\n Returning `{:error, reason}` fails the code change with reason `reason` and\n the state remains as the previous state.\n\n If `c:code_change\/3` raises the code change fails and the loop will continue\n with its previous state. Therefore this callback does not usually contain side effects.\n \"\"\"\n @callback code_change(old_vsn, state :: term, extra :: term) ::\n {:ok, new_state :: term}\n | {:error, reason :: term}\n | {:down, term}\n when old_vsn: term\n\n @doc \"\"\"\n Invoked in some cases to retrieve a formatted version of the `GenServer` status.\n\n This callback can be useful to control the *appearance* of the status of the\n `GenServer`. For example, it can be used to return a compact representation of\n the `GenServer`'s state to avoid having large state terms printed.\n\n * one of `:sys.get_status\/1` or `:sys.get_status\/2` is invoked to get the\n status of the `GenServer`; in such cases, `reason` is `:normal`\n\n * the `GenServer` terminates abnormally and logs an error; in such cases,\n `reason` is `:terminate`\n\n `pdict_and_state` is a two-elements list `[pdict, state]` where `pdict` is a\n list of `{key, value}` tuples representing the current process dictionary of\n the `GenServer` and `state` is the current state of the `GenServer`.\n \"\"\"\n @callback format_status(reason, pdict_and_state :: list) :: term\n when reason: :normal | :terminate\n\n @optional_callbacks format_status: 2\n\n @typedoc \"Return values of `start*` functions\"\n @type on_start :: {:ok, pid} | :ignore | {:error, {:already_started, pid} | term}\n\n @typedoc \"The GenServer name\"\n @type name :: atom | {:global, term} | {:via, module, term}\n\n @typedoc \"Options used by the `start*` functions\"\n @type options :: [option]\n\n @typedoc \"Option values used by the `start*` functions\"\n @type option ::\n {:debug, debug}\n | {:name, name}\n | {:timeout, timeout}\n | {:spawn_opt, Process.spawn_opt()}\n\n @typedoc \"Debug options supported by the `start*` functions\"\n @type debug :: [:trace | :log | :statistics | {:log_to_file, Path.t()}]\n\n @typedoc \"The server reference\"\n @type server :: pid | name | {atom, node}\n\n @typedoc \"\"\"\n Tuple describing the client of a call request.\n\n `pid` is the PID of the caller and `tag` is a unique term used to identify the\n call.\n \"\"\"\n @type from :: {pid, tag :: term}\n\n @doc false\n defmacro __using__(opts) do\n quote location: :keep, bind_quoted: [opts: opts] do\n @behaviour GenServer\n\n @doc \"\"\"\n Returns a specification to start this module under a supervisor.\n\n See `Supervisor`.\n \"\"\"\n def child_spec(arg) do\n default = %{\n id: __MODULE__,\n start: {__MODULE__, :start_link, [arg]}\n }\n\n Supervisor.child_spec(default, unquote(Macro.escape(opts)))\n end\n\n defoverridable child_spec: 1\n\n # TODO: Remove this on Elixir v2.0\n @before_compile GenServer\n\n @doc false\n def handle_call(msg, _from, state) do\n proc =\n case Process.info(self(), :registered_name) do\n {_, []} -> self()\n {_, name} -> name\n end\n\n # We do this to trick Dialyzer to not complain about non-local returns.\n case :erlang.phash2(1, 1) do\n 0 ->\n raise \"attempted to call GenServer #{inspect(proc)} but no handle_call\/3 clause was provided\"\n\n 1 ->\n {:stop, {:bad_call, msg}, state}\n end\n end\n\n @doc false\n def handle_info(msg, state) do\n proc =\n case Process.info(self(), :registered_name) do\n {_, []} -> self()\n {_, name} -> name\n end\n\n pattern = '~p ~p received unexpected message in handle_info\/2: ~p~n'\n :error_logger.error_msg(pattern, [__MODULE__, proc, msg])\n {:noreply, state}\n end\n\n @doc false\n def handle_cast(msg, state) do\n proc =\n case Process.info(self(), :registered_name) do\n {_, []} -> self()\n {_, name} -> name\n end\n\n # We do this to trick Dialyzer to not complain about non-local returns.\n case :erlang.phash2(1, 1) do\n 0 ->\n raise \"attempted to cast GenServer #{inspect(proc)} but no handle_cast\/2 clause was provided\"\n\n 1 ->\n {:stop, {:bad_cast, msg}, state}\n end\n end\n\n @doc false\n def terminate(_reason, _state) do\n :ok\n end\n\n @doc false\n def code_change(_old, state, _extra) do\n {:ok, state}\n end\n\n defoverridable GenServer\n end\n end\n\n defmacro __before_compile__(env) do\n unless Module.defines?(env.module, {:init, 1}) do\n message = \"\"\"\n function init\/1 required by behaviour GenServer is not implemented \\\n (in module #{inspect(env.module)}).\n\n We will inject a default implementation for now:\n\n def init(args) do\n {:ok, args}\n end\n\n But you want to define your own implementation that converts the \\\n arguments given to GenServer.start_link\/3 to the server state\n \"\"\"\n\n :elixir_errors.warn(env.line, env.file, message)\n\n quote do\n @doc false\n def init(args) do\n {:ok, args}\n end\n\n defoverridable init: 1\n end\n end\n end\n\n @doc \"\"\"\n Starts a `GenServer` process linked to the current process.\n\n This is often used to start the `GenServer` as part of a supervision tree.\n\n Once the server is started, the `c:init\/1` function of the given `module` is\n called with `args` as its arguments to initialize the server. To ensure a\n synchronized start-up procedure, this function does not return until `c:init\/1`\n has returned.\n\n Note that a `GenServer` started with `start_link\/3` is linked to the\n parent process and will exit in case of crashes from the parent. The GenServer\n will also exit due to the `:normal` reasons in case it is configured to trap\n exits in the `c:init\/1` callback.\n\n ## Options\n\n * `:name` - used for name registration as described in the \"Name\n registration\" section of the module documentation\n\n * `:timeout` - if present, the server is allowed to spend the given number of\n milliseconds initializing or it will be terminated and the start function\n will return `{:error, :timeout}`\n\n * `:debug` - if present, the corresponding function in the [`:sys` module](http:\/\/www.erlang.org\/doc\/man\/sys.html) is invoked\n\n * `:spawn_opt` - if present, its value is passed as options to the\n underlying process as in `Process.spawn\/4`\n\n ## Return values\n\n If the server is successfully created and initialized, this function returns\n `{:ok, pid}`, where `pid` is the PID of the server. If a process with the\n specified server name already exists, this function returns\n `{:error, {:already_started, pid}}` with the PID of that process.\n\n If the `c:init\/1` callback fails with `reason`, this function returns\n `{:error, reason}`. Otherwise, if it returns `{:stop, reason}`\n or `:ignore`, the process is terminated and this function returns\n `{:error, reason}` or `:ignore`, respectively.\n \"\"\"\n @spec start_link(module, any, options) :: on_start\n def start_link(module, args, options \\\\ []) when is_atom(module) and is_list(options) do\n do_start(:link, module, args, options)\n end\n\n @doc \"\"\"\n Starts a `GenServer` process without links (outside of a supervision tree).\n\n See `start_link\/3` for more information.\n \"\"\"\n @spec start(module, any, options) :: on_start\n def start(module, args, options \\\\ []) when is_atom(module) and is_list(options) do\n do_start(:nolink, module, args, options)\n end\n\n defp do_start(link, module, args, options) do\n case Keyword.pop(options, :name) do\n {nil, opts} ->\n :gen.start(:gen_server, link, module, args, opts)\n\n {atom, opts} when is_atom(atom) ->\n :gen.start(:gen_server, link, {:local, atom}, module, args, opts)\n\n {{:global, _term} = tuple, opts} ->\n :gen.start(:gen_server, link, tuple, module, args, opts)\n\n {{:via, via_module, _term} = tuple, opts} when is_atom(via_module) ->\n :gen.start(:gen_server, link, tuple, module, args, opts)\n\n {other, _} ->\n raise ArgumentError, \"\"\"\n expected :name option to be one of:\n\n * nil\n * atom\n * {:global, term}\n * {:via, module, term}\n\n Got: #{inspect(other)}\n \"\"\"\n end\n end\n\n @doc \"\"\"\n Synchronously stops the server with the given `reason`.\n\n The `c:terminate\/2` callback of the given `server` will be invoked before\n exiting. This function returns `:ok` if the server terminates with the\n given reason; if it terminates with another reason, the call exits.\n\n This function keeps OTP semantics regarding error reporting.\n If the reason is any other than `:normal`, `:shutdown` or\n `{:shutdown, _}`, an error report is logged.\n \"\"\"\n @spec stop(server, reason :: term, timeout) :: :ok\n def stop(server, reason \\\\ :normal, timeout \\\\ :infinity) do\n case whereis(server) do\n nil ->\n exit({:noproc, {__MODULE__, :stop, [server, reason, timeout]}})\n\n pid when pid == self() ->\n exit({:calling_self, {__MODULE__, :stop, [server, reason, timeout]}})\n\n pid ->\n try do\n :proc_lib.stop(pid, reason, timeout)\n catch\n :exit, err ->\n exit({err, {__MODULE__, :stop, [server, reason, timeout]}})\n end\n end\n end\n\n @doc \"\"\"\n Makes a synchronous call to the `server` and waits for its reply.\n\n The client sends the given `request` to the server and waits until a reply\n arrives or a timeout occurs. `c:handle_call\/3` will be called on the server\n to handle the request.\n\n `server` can be any of the values described in the \"Name registration\"\n section of the documentation for this module.\n\n ## Timeouts\n\n `timeout` is an integer greater than zero which specifies how many\n milliseconds to wait for a reply, or the atom `:infinity` to wait\n indefinitely. The default value is `5000`. If no reply is received within\n the specified time, the function call fails and the caller exits. If the\n caller catches the failure and continues running, and the server is just late\n with the reply, it may arrive at any time later into the caller's message\n queue. The caller must in this case be prepared for this and discard any such\n garbage messages that are two-element tuples with a reference as the first\n element.\n \"\"\"\n @spec call(server, term, timeout) :: term\n def call(server, request, timeout \\\\ 5000) do\n case whereis(server) do\n nil ->\n exit({:noproc, {__MODULE__, :call, [server, request, timeout]}})\n\n pid when pid == self() ->\n exit({:calling_self, {__MODULE__, :call, [server, request, timeout]}})\n\n pid ->\n try do\n :gen.call(pid, :\"$gen_call\", request, timeout)\n catch\n :exit, reason ->\n exit({reason, {__MODULE__, :call, [server, request, timeout]}})\n else\n {:ok, res} -> res\n end\n end\n end\n\n @doc \"\"\"\n Sends an asynchronous request to the `server`.\n\n This function always returns `:ok` regardless of whether\n the destination `server` (or node) exists. Therefore it\n is unknown whether the destination `server` successfully\n handled the message.\n\n `c:handle_cast\/2` will be called on the server to handle\n the request. In case the `server` is on a node which is\n not yet connected to the caller one, the call is going to\n block until a connection happens. This is different than\n the behaviour in OTP's `:gen_server` where the message\n is sent by another process in this case, which could cause\n messages to other nodes to arrive out of order.\n \"\"\"\n @spec cast(server, term) :: :ok\n def cast(server, request)\n\n def cast({:global, name}, request) do\n try do\n :global.send(name, cast_msg(request))\n :ok\n catch\n _, _ -> :ok\n end\n end\n\n def cast({:via, mod, name}, request) do\n try do\n mod.send(name, cast_msg(request))\n :ok\n catch\n _, _ -> :ok\n end\n end\n\n def cast({name, node}, request) when is_atom(name) and is_atom(node),\n do: do_send({name, node}, cast_msg(request))\n\n def cast(dest, request) when is_atom(dest) or is_pid(dest), do: do_send(dest, cast_msg(request))\n\n @doc \"\"\"\n Casts all servers locally registered as `name` at the specified nodes.\n\n This function returns immediately and ignores nodes that do not exist, or where the\n server name does not exist.\n\n See `multi_call\/4` for more information.\n \"\"\"\n @spec abcast([node], name :: atom, term) :: :abcast\n def abcast(nodes \\\\ [node() | Node.list()], name, request)\n when is_list(nodes) and is_atom(name) do\n msg = cast_msg(request)\n _ = for node <- nodes, do: do_send({name, node}, msg)\n :abcast\n end\n\n defp cast_msg(req) do\n {:\"$gen_cast\", req}\n end\n\n defp do_send(dest, msg) do\n try do\n send(dest, msg)\n :ok\n catch\n _, _ -> :ok\n end\n end\n\n @doc \"\"\"\n Calls all servers locally registered as `name` at the specified `nodes`.\n\n First, the `request` is sent to every node in `nodes`; then, the caller waits\n for the replies. This function returns a two-element tuple `{replies,\n bad_nodes}` where:\n\n * `replies` - is a list of `{node, reply}` tuples where `node` is the node\n that replied and `reply` is its reply\n * `bad_nodes` - is a list of nodes that either did not exist or where a\n server with the given `name` did not exist or did not reply\n\n `nodes` is a list of node names to which the request is sent. The default\n value is the list of all known nodes (including this node).\n\n To avoid that late answers (after the timeout) pollute the caller's message\n queue, a middleman process is used to do the actual calls. Late answers will\n then be discarded when they arrive to a terminated process.\n\n ## Examples\n\n Assuming the `Stack` GenServer mentioned in the docs for the `GenServer`\n module is registered as `Stack` in the `:\"foo@my-machine\"` and\n `:\"bar@my-machine\"` nodes:\n\n GenServer.multi_call(Stack, :pop)\n #=> {[{:\"foo@my-machine\", :hello}, {:\"bar@my-machine\", :world}], []}\n\n \"\"\"\n @spec multi_call([node], name :: atom, term, timeout) ::\n {replies :: [{node, term}], bad_nodes :: [node]}\n def multi_call(nodes \\\\ [node() | Node.list()], name, request, timeout \\\\ :infinity) do\n :gen_server.multi_call(nodes, name, request, timeout)\n end\n\n @doc \"\"\"\n Replies to a client.\n\n This function can be used to explicitly send a reply to a client that called\n `call\/3` or `multi_call\/4` when the reply cannot be specified in the return\n value of `c:handle_call\/3`.\n\n `client` must be the `from` argument (the second argument) accepted by\n `c:handle_call\/3` callbacks. `reply` is an arbitrary term which will be given\n back to the client as the return value of the call.\n\n Note that `reply\/2` can be called from any process, not just the GenServer\n that originally received the call (as long as that GenServer communicated the\n `from` argument somehow).\n\n This function always returns `:ok`.\n\n ## Examples\n\n def handle_call(:reply_in_one_second, from, state) do\n Process.send_after(self(), {:reply, from}, 1_000)\n {:noreply, state}\n end\n\n def handle_info({:reply, from}, state) do\n GenServer.reply(from, :one_second_has_passed)\n {:noreply, state}\n end\n\n \"\"\"\n @spec reply(from, term) :: :ok\n def reply(client, reply)\n\n def reply({to, tag}, reply) when is_pid(to) do\n try do\n send(to, {tag, reply})\n :ok\n catch\n _, _ -> :ok\n end\n end\n\n @doc \"\"\"\n Returns the `pid` or `{name, node}` of a GenServer process, or `nil` if\n no process is associated with the given `server`.\n\n ## Examples\n\n For example, to lookup a server process, monitor it and send a cast to it:\n\n process = GenServer.whereis(server)\n monitor = Process.monitor(process)\n GenServer.cast(process, :hello)\n\n \"\"\"\n @spec whereis(server) :: pid | {atom, node} | nil\n def whereis(server)\n\n def whereis(pid) when is_pid(pid), do: pid\n\n def whereis(name) when is_atom(name) do\n Process.whereis(name)\n end\n\n def whereis({:global, name}) do\n case :global.whereis_name(name) do\n pid when is_pid(pid) -> pid\n :undefined -> nil\n end\n end\n\n def whereis({:via, mod, name}) do\n case apply(mod, :whereis_name, [name]) do\n pid when is_pid(pid) -> pid\n :undefined -> nil\n end\n end\n\n def whereis({name, local}) when is_atom(name) and local == node() do\n Process.whereis(name)\n end\n\n def whereis({name, node} = server) when is_atom(name) and is_atom(node) do\n server\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"353eafb259954d080cb595cc599a1634471cca88","subject":"Consistently halt with 1 on standalone options","message":"Consistently halt with 1 on standalone options\n","repos":"joshprice\/elixir,michalmuskala\/elixir,elixir-lang\/elixir","old_file":"lib\/elixir\/lib\/kernel\/cli.ex","new_file":"lib\/elixir\/lib\/kernel\/cli.ex","new_contents":"defmodule Kernel.CLI do\n @moduledoc false\n\n @compile {:no_warn_undefined, [Logger, IEx]}\n\n @blank_config %{\n commands: [],\n output: \".\",\n compile: [],\n no_halt: false,\n compiler_options: [],\n errors: [],\n pa: [],\n pz: [],\n verbose_compile: false,\n profile: nil\n }\n\n @standalone_opts [\"-h\", \"--help\", \"--short-version\"]\n\n @doc \"\"\"\n This is the API invoked by Elixir boot process.\n \"\"\"\n def main(argv) do\n argv = for arg <- argv, do: IO.chardata_to_string(arg)\n\n {config, argv} = parse_argv(argv)\n System.argv(argv)\n System.no_halt(config.no_halt)\n\n fun = fn _ ->\n errors = process_commands(config)\n\n if errors != [] do\n Enum.each(errors, &IO.puts(:stderr, &1))\n System.halt(1)\n end\n end\n\n run(fun)\n end\n\n @doc \"\"\"\n Runs the given function by catching any failure\n and printing them to stdout. `at_exit` hooks are\n also invoked before exiting.\n\n This function is used by Elixir's CLI and also\n by escripts generated by Elixir.\n \"\"\"\n def run(fun) do\n {ok_or_shutdown, status} = exec_fun(fun, {:ok, 0})\n\n if ok_or_shutdown == :shutdown or not System.no_halt() do\n {_, status} = at_exit({ok_or_shutdown, status})\n\n # Ensure Logger messages are flushed before halting\n case :erlang.whereis(Logger) do\n pid when is_pid(pid) -> Logger.flush()\n _ -> :ok\n end\n\n System.halt(status)\n end\n end\n\n @doc \"\"\"\n Parses the CLI arguments. Made public for testing.\n \"\"\"\n def parse_argv(argv) do\n parse_argv(argv, @blank_config)\n end\n\n @doc \"\"\"\n Process CLI commands. Made public for testing.\n \"\"\"\n def process_commands(config) do\n results = Enum.map(Enum.reverse(config.commands), &process_command(&1, config))\n errors = for {:error, msg} <- results, do: msg\n Enum.reverse(config.errors, errors)\n end\n\n @doc \"\"\"\n Shared helper for error formatting on CLI tools.\n \"\"\"\n def format_error(kind, reason, stacktrace) do\n {blamed, stacktrace} = Exception.blame(kind, reason, stacktrace)\n\n iodata =\n case blamed do\n %FunctionClauseError{} ->\n formatted = Exception.format_banner(kind, reason, stacktrace)\n padded_blame = pad(FunctionClauseError.blame(blamed, &inspect\/1, &blame_match\/1))\n [formatted, padded_blame]\n\n _ ->\n Exception.format_banner(kind, blamed, stacktrace)\n end\n\n [iodata, ?\\n, Exception.format_stacktrace(prune_stacktrace(stacktrace))]\n end\n\n @doc \"\"\"\n Function invoked across nodes for `--rpc-eval`.\n \"\"\"\n def rpc_eval(expr) do\n wrapper(fn -> Code.eval_string(expr) end)\n catch\n kind, reason -> {kind, reason, __STACKTRACE__}\n end\n\n ## Helpers\n\n defp at_exit(res) do\n hooks = :elixir_config.get_and_put(:at_exit, [])\n res = Enum.reduce(hooks, res, &exec_fun\/2)\n if hooks == [], do: res, else: at_exit(res)\n end\n\n defp exec_fun(fun, res) when is_function(fun, 1) and is_tuple(res) do\n parent = self()\n\n {pid, ref} =\n spawn_monitor(fn ->\n try do\n fun.(elem(res, 1))\n catch\n :exit, {:shutdown, int} when is_integer(int) ->\n send(parent, {self(), {:shutdown, int}})\n exit({:shutdown, int})\n\n :exit, reason\n when reason == :normal\n when reason == :shutdown\n when tuple_size(reason) == 2 and elem(reason, 0) == :shutdown ->\n send(parent, {self(), {:shutdown, 0}})\n exit(reason)\n\n kind, reason ->\n print_error(kind, reason, __STACKTRACE__)\n send(parent, {self(), {:shutdown, 1}})\n exit(to_exit(kind, reason, __STACKTRACE__))\n else\n _ ->\n send(parent, {self(), res})\n end\n end)\n\n receive do\n {^pid, res} ->\n :erlang.demonitor(ref, [:flush])\n res\n\n {:DOWN, ^ref, _, _, other} ->\n print_error({:EXIT, pid}, other, [])\n {:shutdown, 1}\n end\n end\n\n defp to_exit(:throw, reason, stack), do: {{:nocatch, reason}, stack}\n defp to_exit(:error, reason, stack), do: {reason, stack}\n defp to_exit(:exit, reason, _stack), do: reason\n\n defp shared_option?(list, config, callback) do\n case parse_shared(list, config) do\n {[h | hs], _} when h == hd(list) ->\n new_config = %{config | errors: [\"#{h} : Unknown option\" | config.errors]}\n callback.(hs, new_config)\n\n {new_list, new_config} ->\n callback.(new_list, new_config)\n end\n end\n\n ## Error handling\n\n defp print_error(kind, reason, stacktrace) do\n IO.write(:stderr, format_error(kind, reason, stacktrace))\n end\n\n defp blame_match(%{match?: true, node: node}), do: blame_ansi(:normal, \"+\", node)\n defp blame_match(%{match?: false, node: node}), do: blame_ansi(:red, \"-\", node)\n\n defp blame_ansi(color, no_ansi, node) do\n if IO.ANSI.enabled?() do\n [color | Macro.to_string(node)]\n |> IO.ANSI.format(true)\n |> IO.iodata_to_binary()\n else\n no_ansi <> Macro.to_string(node) <> no_ansi\n end\n end\n\n defp pad(string) do\n \" \" <> String.replace(string, \"\\n\", \"\\n \")\n end\n\n @elixir_internals [:elixir, :elixir_aliases, :elixir_expand, :elixir_compiler, :elixir_module] ++\n [:elixir_clauses, :elixir_lexical, :elixir_def, :elixir_map, :elixir_locals] ++\n [:elixir_erl, :elixir_erl_clauses, :elixir_erl_compiler, :elixir_erl_pass] ++\n [Kernel.ErrorHandler, Module.ParallelChecker]\n\n defp prune_stacktrace([{mod, _, _, _} | t]) when mod in @elixir_internals do\n prune_stacktrace(t)\n end\n\n defp prune_stacktrace([{__MODULE__, :wrapper, 1, _} | _]) do\n []\n end\n\n defp prune_stacktrace([h | t]) do\n [h | prune_stacktrace(t)]\n end\n\n defp prune_stacktrace([]) do\n []\n end\n\n # Parse shared options\n\n defp halt_standalone(opt) do\n IO.puts(:stderr, \"#{opt} : Standalone options can't be combined with other options\")\n System.halt(1)\n end\n\n defp parse_shared([opt | _], _config) when opt in @standalone_opts do\n halt_standalone(opt)\n end\n\n defp parse_shared([opt | t], _config) when opt in [\"-v\", \"--version\"] do\n if function_exported?(IEx, :started?, 0) and IEx.started?() do\n IO.puts(\"IEx \" <> System.build_info()[:build])\n else\n IO.puts(:erlang.system_info(:system_version))\n IO.puts(\"Elixir \" <> System.build_info()[:build])\n end\n\n if t != [] do\n halt_standalone(opt)\n else\n System.halt(0)\n end\n end\n\n defp parse_shared([\"-pa\", h | t], config) do\n paths = expand_code_path(h)\n Enum.each(paths, &:code.add_patha\/1)\n parse_shared(t, %{config | pa: config.pa ++ paths})\n end\n\n defp parse_shared([\"-pz\", h | t], config) do\n paths = expand_code_path(h)\n Enum.each(paths, &:code.add_pathz\/1)\n parse_shared(t, %{config | pz: config.pz ++ paths})\n end\n\n defp parse_shared([\"--app\", h | t], config) do\n parse_shared(t, %{config | commands: [{:app, h} | config.commands]})\n end\n\n defp parse_shared([\"--no-halt\" | t], config) do\n parse_shared(t, %{config | no_halt: true})\n end\n\n defp parse_shared([\"-e\", h | t], config) do\n parse_shared(t, %{config | commands: [{:eval, h} | config.commands]})\n end\n\n defp parse_shared([\"--eval\", h | t], config) do\n parse_shared(t, %{config | commands: [{:eval, h} | config.commands]})\n end\n\n defp parse_shared([\"--rpc-eval\", node, h | t], config) do\n node = append_hostname(node)\n parse_shared(t, %{config | commands: [{:rpc_eval, node, h} | config.commands]})\n end\n\n defp parse_shared([\"-r\", h | t], config) do\n parse_shared(t, %{config | commands: [{:require, h} | config.commands]})\n end\n\n defp parse_shared([\"-pr\", h | t], config) do\n parse_shared(t, %{config | commands: [{:parallel_require, h} | config.commands]})\n end\n\n defp parse_shared(list, config) do\n {list, config}\n end\n\n defp append_hostname(node) do\n case :string.find(node, \"@\") do\n :nomatch -> node <> :string.find(Atom.to_string(node()), \"@\")\n _ -> node\n end\n end\n\n defp expand_code_path(path) do\n path = Path.expand(path)\n\n case Path.wildcard(path) do\n [] -> [to_charlist(path)]\n list -> Enum.map(list, &to_charlist\/1)\n end\n end\n\n # Process init options\n\n defp parse_argv([\"--\" | t], config) do\n {config, t}\n end\n\n defp parse_argv([\"+elixirc\" | t], config) do\n parse_compiler(t, config)\n end\n\n defp parse_argv([\"+iex\" | t], config) do\n parse_iex(t, config)\n end\n\n defp parse_argv([\"-S\", h | t], config) do\n {%{config | commands: [{:script, h} | config.commands]}, t}\n end\n\n defp parse_argv([h | t] = list, config) do\n case h do\n \"-\" <> _ ->\n shared_option?(list, config, &parse_argv(&1, &2))\n\n _ ->\n if List.keymember?(config.commands, :eval, 0) do\n {config, list}\n else\n {%{config | commands: [{:file, h} | config.commands]}, t}\n end\n end\n end\n\n defp parse_argv([], config) do\n {config, []}\n end\n\n # Parse compiler options\n\n defp parse_compiler([\"--\" | t], config) do\n {config, t}\n end\n\n defp parse_compiler([\"-o\", h | t], config) do\n parse_compiler(t, %{config | output: h})\n end\n\n defp parse_compiler([\"--no-docs\" | t], config) do\n parse_compiler(t, %{config | compiler_options: [{:docs, false} | config.compiler_options]})\n end\n\n defp parse_compiler([\"--no-debug-info\" | t], config) do\n compiler_options = [{:debug_info, false} | config.compiler_options]\n parse_compiler(t, %{config | compiler_options: compiler_options})\n end\n\n defp parse_compiler([\"--ignore-module-conflict\" | t], config) do\n compiler_options = [{:ignore_module_conflict, true} | config.compiler_options]\n parse_compiler(t, %{config | compiler_options: compiler_options})\n end\n\n defp parse_compiler([\"--warnings-as-errors\" | t], config) do\n compiler_options = [{:warnings_as_errors, true} | config.compiler_options]\n parse_compiler(t, %{config | compiler_options: compiler_options})\n end\n\n defp parse_compiler([\"--verbose\" | t], config) do\n parse_compiler(t, %{config | verbose_compile: true})\n end\n\n # Private compiler options\n\n defp parse_compiler([\"--profile\", \"time\" | t], config) do\n parse_compiler(t, %{config | profile: :time})\n end\n\n defp parse_compiler([h | t] = list, config) do\n case h do\n \"-\" <> _ ->\n shared_option?(list, config, &parse_compiler(&1, &2))\n\n _ ->\n pattern = if File.dir?(h), do: \"#{h}\/**\/*.ex\", else: h\n parse_compiler(t, %{config | compile: [pattern | config.compile]})\n end\n end\n\n defp parse_compiler([], config) do\n {%{config | commands: [{:compile, config.compile} | config.commands]}, []}\n end\n\n # Parse IEx options\n\n defp parse_iex([\"--\" | t], config) do\n {config, t}\n end\n\n # This clause is here so that Kernel.CLI does not\n # error out with \"unknown option\"\n defp parse_iex([\"--dot-iex\", _ | t], config) do\n parse_iex(t, config)\n end\n\n defp parse_iex([opt, _ | t], config) when opt in [\"--remsh\"] do\n parse_iex(t, config)\n end\n\n defp parse_iex([\"-S\", h | t], config) do\n {%{config | commands: [{:script, h} | config.commands]}, t}\n end\n\n defp parse_iex([h | t] = list, config) do\n case h do\n \"-\" <> _ -> shared_option?(list, config, &parse_iex(&1, &2))\n _ -> {%{config | commands: [{:file, h} | config.commands]}, t}\n end\n end\n\n defp parse_iex([], config) do\n {config, []}\n end\n\n # Process commands\n\n defp process_command({:cookie, h}, _config) do\n if Node.alive?() do\n wrapper(fn -> Node.set_cookie(String.to_atom(h)) end)\n else\n {:error, \"--cookie : Cannot set cookie if the node is not alive (set --name or --sname)\"}\n end\n end\n\n defp process_command({:eval, expr}, _config) when is_binary(expr) do\n wrapper(fn -> Code.eval_string(expr, []) end)\n end\n\n defp process_command({:rpc_eval, node, expr}, _config) when is_binary(expr) do\n case :rpc.call(String.to_atom(node), __MODULE__, :rpc_eval, [expr]) do\n :ok -> :ok\n {:badrpc, {:EXIT, exit}} -> Process.exit(self(), exit)\n {:badrpc, reason} -> {:error, \"--rpc-eval : RPC failed with reason #{inspect(reason)}\"}\n {kind, error, stack} -> :erlang.raise(kind, error, stack)\n end\n end\n\n defp process_command({:app, app}, _config) when is_binary(app) do\n case Application.ensure_all_started(String.to_atom(app)) do\n {:error, {app, reason}} ->\n msg = \"--app : Could not start application #{app}: \" <> Application.format_error(reason)\n {:error, msg}\n\n {:ok, _} ->\n :ok\n end\n end\n\n defp process_command({:script, file}, _config) when is_binary(file) do\n if exec = find_elixir_executable(file) do\n wrapper(fn -> Code.require_file(exec) end)\n else\n {:error, \"-S : Could not find executable #{file}\"}\n end\n end\n\n defp process_command({:file, file}, _config) when is_binary(file) do\n if File.regular?(file) do\n wrapper(fn -> Code.require_file(file) end)\n else\n {:error, \"No file named #{file}\"}\n end\n end\n\n defp process_command({:require, pattern}, _config) when is_binary(pattern) do\n files = filter_patterns(pattern)\n\n if files != [] do\n wrapper(fn -> Enum.map(files, &Code.require_file(&1)) end)\n else\n {:error, \"-r : No files matched pattern #{pattern}\"}\n end\n end\n\n defp process_command({:parallel_require, pattern}, _config) when is_binary(pattern) do\n files = filter_patterns(pattern)\n\n if files != [] do\n wrapper(fn ->\n case Kernel.ParallelCompiler.require(files) do\n {:ok, _, _} -> :ok\n {:error, _, _} -> exit({:shutdown, 1})\n end\n end)\n else\n {:error, \"-pr : No files matched pattern #{pattern}\"}\n end\n end\n\n defp process_command({:compile, patterns}, config) do\n # If ensuring the dir returns an error no files will be found.\n _ = :filelib.ensure_dir(:filename.join(config.output, \".\"))\n\n case filter_multiple_patterns(patterns) do\n {:ok, []} ->\n {:error, \"No files matched provided patterns\"}\n\n {:ok, files} ->\n wrapper(fn ->\n Code.compiler_options(config.compiler_options)\n\n verbose_opts =\n if config.verbose_compile do\n [each_file: &IO.puts(\"Compiling #{Path.relative_to_cwd(&1)}\")]\n else\n [\n each_long_compilation:\n &IO.puts(\"Compiling #{Path.relative_to_cwd(&1)} (it's taking more than 10s)\")\n ]\n end\n\n profile_opts =\n if config.profile do\n [profile: config.profile]\n else\n []\n end\n\n opts = verbose_opts ++ profile_opts\n\n case Kernel.ParallelCompiler.compile_to_path(files, config.output, opts) do\n {:ok, _, _} -> :ok\n {:error, _, _} -> exit({:shutdown, 1})\n end\n end)\n\n {:missing, missing} ->\n {:error, \"No files matched pattern(s) #{Enum.join(missing, \",\")}\"}\n end\n end\n\n defp filter_patterns(pattern) do\n pattern\n |> Path.expand()\n |> Path.wildcard()\n |> :lists.usort()\n |> Enum.filter(&File.regular?\/1)\n end\n\n defp filter_multiple_patterns(patterns) do\n {files, missing} =\n Enum.reduce(patterns, {[], []}, fn pattern, {files, missing} ->\n case filter_patterns(pattern) do\n [] -> {files, [pattern | missing]}\n match -> {match ++ files, missing}\n end\n end)\n\n case missing do\n [] -> {:ok, :lists.usort(files)}\n _ -> {:missing, :lists.usort(missing)}\n end\n end\n\n defp wrapper(fun) do\n _ = fun.()\n :ok\n end\n\n defp find_elixir_executable(file) do\n if exec = System.find_executable(file) do\n # If we are on Windows, the executable is going to be\n # a .bat file that must be in the same directory as\n # the actual Elixir executable.\n case :os.type() do\n {:win32, _} ->\n base = Path.rootname(exec)\n if File.regular?(base), do: base, else: exec\n\n _ ->\n exec\n end\n end\n end\nend\n","old_contents":"defmodule Kernel.CLI do\n @moduledoc false\n\n @compile {:no_warn_undefined, [Logger, IEx]}\n\n @blank_config %{\n commands: [],\n output: \".\",\n compile: [],\n no_halt: false,\n compiler_options: [],\n errors: [],\n pa: [],\n pz: [],\n verbose_compile: false,\n profile: nil\n }\n\n @standalone_opts [\"-h\", \"--help\", \"--short-version\"]\n\n @doc \"\"\"\n This is the API invoked by Elixir boot process.\n \"\"\"\n def main(argv) do\n argv = for arg <- argv, do: IO.chardata_to_string(arg)\n\n {config, argv} = parse_argv(argv)\n System.argv(argv)\n System.no_halt(config.no_halt)\n\n fun = fn _ ->\n errors = process_commands(config)\n\n if errors != [] do\n Enum.each(errors, &IO.puts(:stderr, &1))\n System.halt(1)\n end\n end\n\n run(fun)\n end\n\n @doc \"\"\"\n Runs the given function by catching any failure\n and printing them to stdout. `at_exit` hooks are\n also invoked before exiting.\n\n This function is used by Elixir's CLI and also\n by escripts generated by Elixir.\n \"\"\"\n def run(fun) do\n {ok_or_shutdown, status} = exec_fun(fun, {:ok, 0})\n\n if ok_or_shutdown == :shutdown or not System.no_halt() do\n {_, status} = at_exit({ok_or_shutdown, status})\n\n # Ensure Logger messages are flushed before halting\n case :erlang.whereis(Logger) do\n pid when is_pid(pid) -> Logger.flush()\n _ -> :ok\n end\n\n System.halt(status)\n end\n end\n\n @doc \"\"\"\n Parses the CLI arguments. Made public for testing.\n \"\"\"\n def parse_argv(argv) do\n parse_argv(argv, @blank_config)\n end\n\n @doc \"\"\"\n Process CLI commands. Made public for testing.\n \"\"\"\n def process_commands(config) do\n results = Enum.map(Enum.reverse(config.commands), &process_command(&1, config))\n errors = for {:error, msg} <- results, do: msg\n Enum.reverse(config.errors, errors)\n end\n\n @doc \"\"\"\n Shared helper for error formatting on CLI tools.\n \"\"\"\n def format_error(kind, reason, stacktrace) do\n {blamed, stacktrace} = Exception.blame(kind, reason, stacktrace)\n\n iodata =\n case blamed do\n %FunctionClauseError{} ->\n formatted = Exception.format_banner(kind, reason, stacktrace)\n padded_blame = pad(FunctionClauseError.blame(blamed, &inspect\/1, &blame_match\/1))\n [formatted, padded_blame]\n\n _ ->\n Exception.format_banner(kind, blamed, stacktrace)\n end\n\n [iodata, ?\\n, Exception.format_stacktrace(prune_stacktrace(stacktrace))]\n end\n\n @doc \"\"\"\n Function invoked across nodes for `--rpc-eval`.\n \"\"\"\n def rpc_eval(expr) do\n wrapper(fn -> Code.eval_string(expr) end)\n catch\n kind, reason -> {kind, reason, __STACKTRACE__}\n end\n\n ## Helpers\n\n defp at_exit(res) do\n hooks = :elixir_config.get_and_put(:at_exit, [])\n res = Enum.reduce(hooks, res, &exec_fun\/2)\n if hooks == [], do: res, else: at_exit(res)\n end\n\n defp exec_fun(fun, res) when is_function(fun, 1) and is_tuple(res) do\n parent = self()\n\n {pid, ref} =\n spawn_monitor(fn ->\n try do\n fun.(elem(res, 1))\n catch\n :exit, {:shutdown, int} when is_integer(int) ->\n send(parent, {self(), {:shutdown, int}})\n exit({:shutdown, int})\n\n :exit, reason\n when reason == :normal\n when reason == :shutdown\n when tuple_size(reason) == 2 and elem(reason, 0) == :shutdown ->\n send(parent, {self(), {:shutdown, 0}})\n exit(reason)\n\n kind, reason ->\n print_error(kind, reason, __STACKTRACE__)\n send(parent, {self(), {:shutdown, 1}})\n exit(to_exit(kind, reason, __STACKTRACE__))\n else\n _ ->\n send(parent, {self(), res})\n end\n end)\n\n receive do\n {^pid, res} ->\n :erlang.demonitor(ref, [:flush])\n res\n\n {:DOWN, ^ref, _, _, other} ->\n print_error({:EXIT, pid}, other, [])\n {:shutdown, 1}\n end\n end\n\n defp to_exit(:throw, reason, stack), do: {{:nocatch, reason}, stack}\n defp to_exit(:error, reason, stack), do: {reason, stack}\n defp to_exit(:exit, reason, _stack), do: reason\n\n defp shared_option?(list, config, callback) do\n case parse_shared(list, config) do\n {[h | hs], _} when h == hd(list) ->\n new_config = %{config | errors: [\"#{h} : Unknown option\" | config.errors]}\n callback.(hs, new_config)\n\n {new_list, new_config} ->\n callback.(new_list, new_config)\n end\n end\n\n ## Error handling\n\n defp print_error(kind, reason, stacktrace) do\n IO.write(:stderr, format_error(kind, reason, stacktrace))\n end\n\n defp blame_match(%{match?: true, node: node}), do: blame_ansi(:normal, \"+\", node)\n defp blame_match(%{match?: false, node: node}), do: blame_ansi(:red, \"-\", node)\n\n defp blame_ansi(color, no_ansi, node) do\n if IO.ANSI.enabled?() do\n [color | Macro.to_string(node)]\n |> IO.ANSI.format(true)\n |> IO.iodata_to_binary()\n else\n no_ansi <> Macro.to_string(node) <> no_ansi\n end\n end\n\n defp pad(string) do\n \" \" <> String.replace(string, \"\\n\", \"\\n \")\n end\n\n @elixir_internals [:elixir, :elixir_aliases, :elixir_expand, :elixir_compiler, :elixir_module] ++\n [:elixir_clauses, :elixir_lexical, :elixir_def, :elixir_map, :elixir_locals] ++\n [:elixir_erl, :elixir_erl_clauses, :elixir_erl_compiler, :elixir_erl_pass] ++\n [Kernel.ErrorHandler, Module.ParallelChecker]\n\n defp prune_stacktrace([{mod, _, _, _} | t]) when mod in @elixir_internals do\n prune_stacktrace(t)\n end\n\n defp prune_stacktrace([{__MODULE__, :wrapper, 1, _} | _]) do\n []\n end\n\n defp prune_stacktrace([h | t]) do\n [h | prune_stacktrace(t)]\n end\n\n defp prune_stacktrace([]) do\n []\n end\n\n # Parse shared options\n\n defp warn_standalone(opt) do\n IO.puts(:stderr, \"#{opt} : Standalone options can't be combined with other options\")\n end\n\n defp parse_shared([opt | _], _config) when opt in @standalone_opts do\n warn_standalone(opt)\n System.halt(1)\n end\n\n defp parse_shared([opt | t], _config) when opt in [\"-v\", \"--version\"] do\n if function_exported?(IEx, :started?, 0) and IEx.started?() do\n IO.puts(\"IEx \" <> System.build_info()[:build])\n else\n IO.puts(:erlang.system_info(:system_version))\n IO.puts(\"Elixir \" <> System.build_info()[:build])\n end\n\n t != [] && warn_standalone(opt)\n System.halt(0)\n end\n\n defp parse_shared([\"-pa\", h | t], config) do\n paths = expand_code_path(h)\n Enum.each(paths, &:code.add_patha\/1)\n parse_shared(t, %{config | pa: config.pa ++ paths})\n end\n\n defp parse_shared([\"-pz\", h | t], config) do\n paths = expand_code_path(h)\n Enum.each(paths, &:code.add_pathz\/1)\n parse_shared(t, %{config | pz: config.pz ++ paths})\n end\n\n defp parse_shared([\"--app\", h | t], config) do\n parse_shared(t, %{config | commands: [{:app, h} | config.commands]})\n end\n\n defp parse_shared([\"--no-halt\" | t], config) do\n parse_shared(t, %{config | no_halt: true})\n end\n\n defp parse_shared([\"-e\", h | t], config) do\n parse_shared(t, %{config | commands: [{:eval, h} | config.commands]})\n end\n\n defp parse_shared([\"--eval\", h | t], config) do\n parse_shared(t, %{config | commands: [{:eval, h} | config.commands]})\n end\n\n defp parse_shared([\"--rpc-eval\", node, h | t], config) do\n node = append_hostname(node)\n parse_shared(t, %{config | commands: [{:rpc_eval, node, h} | config.commands]})\n end\n\n defp parse_shared([\"-r\", h | t], config) do\n parse_shared(t, %{config | commands: [{:require, h} | config.commands]})\n end\n\n defp parse_shared([\"-pr\", h | t], config) do\n parse_shared(t, %{config | commands: [{:parallel_require, h} | config.commands]})\n end\n\n defp parse_shared(list, config) do\n {list, config}\n end\n\n defp append_hostname(node) do\n case :string.find(node, \"@\") do\n :nomatch -> node <> :string.find(Atom.to_string(node()), \"@\")\n _ -> node\n end\n end\n\n defp expand_code_path(path) do\n path = Path.expand(path)\n\n case Path.wildcard(path) do\n [] -> [to_charlist(path)]\n list -> Enum.map(list, &to_charlist\/1)\n end\n end\n\n # Process init options\n\n defp parse_argv([\"--\" | t], config) do\n {config, t}\n end\n\n defp parse_argv([\"+elixirc\" | t], config) do\n parse_compiler(t, config)\n end\n\n defp parse_argv([\"+iex\" | t], config) do\n parse_iex(t, config)\n end\n\n defp parse_argv([\"-S\", h | t], config) do\n {%{config | commands: [{:script, h} | config.commands]}, t}\n end\n\n defp parse_argv([h | t] = list, config) do\n case h do\n \"-\" <> _ ->\n shared_option?(list, config, &parse_argv(&1, &2))\n\n _ ->\n if List.keymember?(config.commands, :eval, 0) do\n {config, list}\n else\n {%{config | commands: [{:file, h} | config.commands]}, t}\n end\n end\n end\n\n defp parse_argv([], config) do\n {config, []}\n end\n\n # Parse compiler options\n\n defp parse_compiler([\"--\" | t], config) do\n {config, t}\n end\n\n defp parse_compiler([\"-o\", h | t], config) do\n parse_compiler(t, %{config | output: h})\n end\n\n defp parse_compiler([\"--no-docs\" | t], config) do\n parse_compiler(t, %{config | compiler_options: [{:docs, false} | config.compiler_options]})\n end\n\n defp parse_compiler([\"--no-debug-info\" | t], config) do\n compiler_options = [{:debug_info, false} | config.compiler_options]\n parse_compiler(t, %{config | compiler_options: compiler_options})\n end\n\n defp parse_compiler([\"--ignore-module-conflict\" | t], config) do\n compiler_options = [{:ignore_module_conflict, true} | config.compiler_options]\n parse_compiler(t, %{config | compiler_options: compiler_options})\n end\n\n defp parse_compiler([\"--warnings-as-errors\" | t], config) do\n compiler_options = [{:warnings_as_errors, true} | config.compiler_options]\n parse_compiler(t, %{config | compiler_options: compiler_options})\n end\n\n defp parse_compiler([\"--verbose\" | t], config) do\n parse_compiler(t, %{config | verbose_compile: true})\n end\n\n # Private compiler options\n\n defp parse_compiler([\"--profile\", \"time\" | t], config) do\n parse_compiler(t, %{config | profile: :time})\n end\n\n defp parse_compiler([h | t] = list, config) do\n case h do\n \"-\" <> _ ->\n shared_option?(list, config, &parse_compiler(&1, &2))\n\n _ ->\n pattern = if File.dir?(h), do: \"#{h}\/**\/*.ex\", else: h\n parse_compiler(t, %{config | compile: [pattern | config.compile]})\n end\n end\n\n defp parse_compiler([], config) do\n {%{config | commands: [{:compile, config.compile} | config.commands]}, []}\n end\n\n # Parse IEx options\n\n defp parse_iex([\"--\" | t], config) do\n {config, t}\n end\n\n # This clause is here so that Kernel.CLI does not\n # error out with \"unknown option\"\n defp parse_iex([\"--dot-iex\", _ | t], config) do\n parse_iex(t, config)\n end\n\n defp parse_iex([opt, _ | t], config) when opt in [\"--remsh\"] do\n parse_iex(t, config)\n end\n\n defp parse_iex([\"-S\", h | t], config) do\n {%{config | commands: [{:script, h} | config.commands]}, t}\n end\n\n defp parse_iex([h | t] = list, config) do\n case h do\n \"-\" <> _ -> shared_option?(list, config, &parse_iex(&1, &2))\n _ -> {%{config | commands: [{:file, h} | config.commands]}, t}\n end\n end\n\n defp parse_iex([], config) do\n {config, []}\n end\n\n # Process commands\n\n defp process_command({:cookie, h}, _config) do\n if Node.alive?() do\n wrapper(fn -> Node.set_cookie(String.to_atom(h)) end)\n else\n {:error, \"--cookie : Cannot set cookie if the node is not alive (set --name or --sname)\"}\n end\n end\n\n defp process_command({:eval, expr}, _config) when is_binary(expr) do\n wrapper(fn -> Code.eval_string(expr, []) end)\n end\n\n defp process_command({:rpc_eval, node, expr}, _config) when is_binary(expr) do\n case :rpc.call(String.to_atom(node), __MODULE__, :rpc_eval, [expr]) do\n :ok -> :ok\n {:badrpc, {:EXIT, exit}} -> Process.exit(self(), exit)\n {:badrpc, reason} -> {:error, \"--rpc-eval : RPC failed with reason #{inspect(reason)}\"}\n {kind, error, stack} -> :erlang.raise(kind, error, stack)\n end\n end\n\n defp process_command({:app, app}, _config) when is_binary(app) do\n case Application.ensure_all_started(String.to_atom(app)) do\n {:error, {app, reason}} ->\n msg = \"--app : Could not start application #{app}: \" <> Application.format_error(reason)\n {:error, msg}\n\n {:ok, _} ->\n :ok\n end\n end\n\n defp process_command({:script, file}, _config) when is_binary(file) do\n if exec = find_elixir_executable(file) do\n wrapper(fn -> Code.require_file(exec) end)\n else\n {:error, \"-S : Could not find executable #{file}\"}\n end\n end\n\n defp process_command({:file, file}, _config) when is_binary(file) do\n if File.regular?(file) do\n wrapper(fn -> Code.require_file(file) end)\n else\n {:error, \"No file named #{file}\"}\n end\n end\n\n defp process_command({:require, pattern}, _config) when is_binary(pattern) do\n files = filter_patterns(pattern)\n\n if files != [] do\n wrapper(fn -> Enum.map(files, &Code.require_file(&1)) end)\n else\n {:error, \"-r : No files matched pattern #{pattern}\"}\n end\n end\n\n defp process_command({:parallel_require, pattern}, _config) when is_binary(pattern) do\n files = filter_patterns(pattern)\n\n if files != [] do\n wrapper(fn ->\n case Kernel.ParallelCompiler.require(files) do\n {:ok, _, _} -> :ok\n {:error, _, _} -> exit({:shutdown, 1})\n end\n end)\n else\n {:error, \"-pr : No files matched pattern #{pattern}\"}\n end\n end\n\n defp process_command({:compile, patterns}, config) do\n # If ensuring the dir returns an error no files will be found.\n _ = :filelib.ensure_dir(:filename.join(config.output, \".\"))\n\n case filter_multiple_patterns(patterns) do\n {:ok, []} ->\n {:error, \"No files matched provided patterns\"}\n\n {:ok, files} ->\n wrapper(fn ->\n Code.compiler_options(config.compiler_options)\n\n verbose_opts =\n if config.verbose_compile do\n [each_file: &IO.puts(\"Compiling #{Path.relative_to_cwd(&1)}\")]\n else\n [\n each_long_compilation:\n &IO.puts(\"Compiling #{Path.relative_to_cwd(&1)} (it's taking more than 10s)\")\n ]\n end\n\n profile_opts =\n if config.profile do\n [profile: config.profile]\n else\n []\n end\n\n opts = verbose_opts ++ profile_opts\n\n case Kernel.ParallelCompiler.compile_to_path(files, config.output, opts) do\n {:ok, _, _} -> :ok\n {:error, _, _} -> exit({:shutdown, 1})\n end\n end)\n\n {:missing, missing} ->\n {:error, \"No files matched pattern(s) #{Enum.join(missing, \",\")}\"}\n end\n end\n\n defp filter_patterns(pattern) do\n pattern\n |> Path.expand()\n |> Path.wildcard()\n |> :lists.usort()\n |> Enum.filter(&File.regular?\/1)\n end\n\n defp filter_multiple_patterns(patterns) do\n {files, missing} =\n Enum.reduce(patterns, {[], []}, fn pattern, {files, missing} ->\n case filter_patterns(pattern) do\n [] -> {files, [pattern | missing]}\n match -> {match ++ files, missing}\n end\n end)\n\n case missing do\n [] -> {:ok, :lists.usort(files)}\n _ -> {:missing, :lists.usort(missing)}\n end\n end\n\n defp wrapper(fun) do\n _ = fun.()\n :ok\n end\n\n defp find_elixir_executable(file) do\n if exec = System.find_executable(file) do\n # If we are on Windows, the executable is going to be\n # a .bat file that must be in the same directory as\n # the actual Elixir executable.\n case :os.type() do\n {:win32, _} ->\n base = Path.rootname(exec)\n if File.regular?(base), do: base, else: exec\n\n _ ->\n exec\n end\n end\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"ffe66ff54f93cef232994dfbd4c765bb0b0aca3b","subject":"Fixed all credo warnings","message":"Fixed all credo warnings\n","repos":"rrrene\/credo,rrrene\/credo","old_file":"lib\/credo\/check.ex","new_file":"lib\/credo\/check.ex","new_contents":"defmodule Credo.Check do\n @base_priority_map %{ignore: -100, low: -10, normal: 1, high: +10, higher: +20}\n @base_category_exit_status_map %{\n consistency: 1,\n design: 2,\n readability: 4,\n refactor: 8,\n warning: 16,\n }\n\n @type t :: module\n\n defmacro __using__(opts) do\n quote do\n @behaviour Credo.Check\n\n alias Credo.Check\n alias Credo.Issue\n alias Credo.IssueMeta\n alias Credo.Priority\n alias Credo.Severity\n alias Credo.SourceFile\n alias Credo.Check.CodeHelper\n alias Credo.Check.Params\n alias Credo.CLI.ExitStatus\n\n def base_priority do\n unquote(to_priority(opts[:base_priority]))\n end\n\n def category do\n default = unquote(category_body(opts[:category]))\n default || :unknown\n end\n\n def run_on_all? do\n unquote(run_on_all_body(opts[:run_on_all]))\n end\n\n def explanation do\n Check.explanation_for(@explanation, :check)\n end\n\n def explanation_for_params do\n Check.explanation_for(@explanation, :params)\n end\n\n def format_issue(issue_meta, opts) do\n Check.format_issue(issue_meta, opts, category(), base_priority(), __MODULE__)\n end\n end\n end\n\n alias Credo.Check\n alias Credo.Issue\n alias Credo.IssueMeta\n alias Credo.Priority\n alias Credo.Severity\n alias Credo.SourceFile\n alias Credo.Check.CodeHelper\n\n @doc \"\"\"\n Returns the base priority for the check.\n \"\"\"\n @callback base_priority() :: integer\n\n @doc \"\"\"\n Returns the category for the check.\n \"\"\"\n @callback category() :: atom\n\n @callback run(source_file :: Credo.SourceFile.t, params :: Keyword.t) :: List.t\n\n @callback run_on_all?() :: boolean\n\n @callback explanation() :: String.t\n\n @callback explanation_for_params() :: Keyword.t\n\n @callback format_issue(issue_meta :: IssueMeta, opts :: Keyword.t) :: Issue.t\n\n def explanation_for(nil, _) do\n nil\n end\n def explanation_for(keywords, key) do\n keywords[key]\n end\n\n @doc \"\"\"\n format_issue takes an issue_meta and returns an issue.\n The resulting issue can be made more explicit by passing the following\n options to `format_issue\/2`:\n\n - `:priority` Sets the issue's priority.\n - `:trigger` Sets the issue's trigger.\n - `:line_no` Sets the issue's line number.\n Tries to find `column` if `:trigger` is supplied.\n - `:column` Sets the issue's column.\n - `:exit_status` Sets the issue's exit_status.\n - `:severity` Sets the issue's severity.\n \"\"\"\n def format_issue(issue_meta, opts, issue_category, issue_base_priority, check) do\n source_file = IssueMeta.source_file(issue_meta)\n params = IssueMeta.params(issue_meta)\n priority =\n case params[:priority] do\n nil -> issue_base_priority\n val -> val |> Check.to_priority\n end\n exit_status =\n case params[:exit_status] do\n nil -> issue_category |> Check.to_exit_status\n val -> val |> Check.to_exit_status\n end\n\n line_no = opts[:line_no]\n trigger = opts[:trigger]\n column = opts[:column]\n severity = opts[:severity] || Severity.default_value\n\n %Issue{\n priority: priority,\n filename: source_file.filename,\n message: opts[:message],\n trigger: trigger,\n line_no: line_no,\n column: column,\n severity: severity,\n exit_status: exit_status\n }\n |> add_line_no_options(line_no, source_file)\n |> add_custom_column(trigger, line_no, column, source_file)\n |> add_check_and_category(check, issue_category)\n end\n\n defp add_check_and_category(issue, check, issue_category) do\n %Issue{\n issue |\n check: check,\n category: issue_category\n }\n end\n\n defp add_custom_column(issue, trigger, line_no, column, source_file) do\n if trigger && line_no && !column do\n %Issue{\n issue |\n column: SourceFile.column(source_file, line_no, trigger)\n }\n else\n issue\n end\n end\n\n defp add_line_no_options(issue, line_no, source_file) do\n if line_no do\n {_def, scope} = CodeHelper.scope_for(source_file, line: line_no)\n %Issue{\n issue |\n priority: issue.priority + priority_for(source_file, scope),\n scope: scope\n }\n else\n issue\n end\n end\n\n defp priority_for(source_file, scope) do\n scope_prio_map = Priority.scope_priorities(source_file)\n scope_prio_map[scope] || 0\n end\n\n\n\n defp category_body(nil) do\n quote do\n value =\n __MODULE__\n |> Module.split\n |> Enum.at(2)\n (value || :unknown)\n |> to_string\n |> String.downcase\n |> String.to_atom\n end\n end\n defp category_body(value), do: value\n\n @doc \"Converts a given category to a priority\"\n def to_priority(nil), do: 0\n def to_priority(atom) when is_atom(atom) do\n @base_priority_map[atom]\n end\n def to_priority(value), do: value\n\n @doc \"Converts a given category to an exit status\"\n def to_exit_status(nil), do: 0\n def to_exit_status(atom) when is_atom(atom) do\n @base_category_exit_status_map[atom]\n |> to_exit_status\n end\n def to_exit_status(value), do: value\n\n defp run_on_all_body(true), do: true\n defp run_on_all_body(_), do: false\nend\n","old_contents":"defmodule Credo.Check do\n @base_priority_map %{ignore: -100, low: -10, normal: 1, high: +10, higher: +20}\n @base_category_exit_status_map %{\n consistency: 1,\n design: 2,\n readability: 4,\n refactor: 8,\n warning: 16,\n }\n\n @type t :: module\n\n defmacro __using__(opts) do\n quote do\n @behaviour Credo.Check\n\n alias Credo.Check\n alias Credo.Issue\n alias Credo.IssueMeta\n alias Credo.Priority\n alias Credo.Severity\n alias Credo.SourceFile\n alias Credo.Check.CodeHelper\n alias Credo.Check.Params\n alias Credo.CLI.ExitStatus\n\n def base_priority do\n unquote(to_priority(opts[:base_priority]))\n end\n\n def category do\n default = unquote(category_body(opts[:category]))\n default || :unknown\n end\n\n def run_on_all? do\n unquote(run_on_all_body(opts[:run_on_all]))\n end\n\n def explanation do\n Check.explanation_for(@explanation, :check)\n end\n\n def explanation_for_params do\n Check.explanation_for(@explanation, :params)\n end\n\n def format_issue(issue_meta, opts) do\n Check.format_issue(issue_meta, opts, category(), base_priority(), __MODULE__)\n end\n end\n end\n\n alias Credo.Check\n alias Credo.Issue\n alias Credo.IssueMeta\n alias Credo.Priority\n alias Credo.Severity\n alias Credo.SourceFile\n alias Credo.Check.CodeHelper\n\n @doc \"\"\"\n Returns the base priority for the check.\n \"\"\"\n @callback base_priority() :: integer\n\n @doc \"\"\"\n Returns the category for the check.\n \"\"\"\n @callback category() :: atom\n\n @callback run(source_file :: Credo.SourceFile.t, params :: Keyword.t) :: List.t\n\n @callback run_on_all?() :: boolean\n\n @callback explanation() :: String.t\n\n @callback explanation_for_params() :: Keyword.t\n\n @callback format_issue(issue_meta :: IssueMeta, opts :: Keyword.t) :: Issue.t\n\n def explanation_for(nil, _) do\n nil\n end\n def explanation_for(keywords, key) do\n keywords[key]\n end\n\n @doc \"\"\"\n format_issue takes an issue_meta and returns an issue.\n The resulting issue can be made more explicit by passing the following\n options to `format_issue\/2`:\n\n - `:priority` Sets the issue's priority.\n - `:trigger` Sets the issue's trigger.\n - `:line_no` Sets the issue's line number.\n Tries to find `column` if `:trigger` is supplied.\n - `:column` Sets the issue's column.\n - `:exit_status` Sets the issue's exit_status.\n - `:severity` Sets the issue's severity.\n \"\"\"\n def format_issue(issue_meta, opts, category, base_priority, check) do\n source_file = IssueMeta.source_file(issue_meta)\n params = IssueMeta.params(issue_meta)\n priority =\n case params[:priority] do\n nil -> base_priority\n val -> val |> Check.to_priority\n end\n exit_status =\n case params[:exit_status] do\n nil -> category |> Check.to_exit_status\n val -> val |> Check.to_exit_status\n end\n\n line_no = opts[:line_no]\n trigger = opts[:trigger]\n column = opts[:column]\n severity = opts[:severity] || Severity.default_value\n\n %Issue{\n priority: priority,\n filename: source_file.filename,\n message: opts[:message],\n trigger: trigger,\n line_no: line_no,\n column: column,\n severity: severity,\n exit_status: exit_status\n }\n |> add_line_no_options(line_no, source_file)\n |> add_custom_column(trigger, line_no, column, source_file)\n |> add_check_and_category(check, category)\n end\n\n defp add_check_and_category(issue, check, category) do\n %Issue{\n issue |\n check: check,\n category: category\n }\n end\n\n defp add_custom_column(issue, trigger, line_no, column, source_file) do\n if trigger && line_no && !column do\n %Issue{\n issue |\n column: SourceFile.column(source_file, line_no, trigger)\n }\n else\n issue\n end\n end\n\n defp add_line_no_options(issue, line_no, source_file) do\n if line_no do\n {_def, scope} = CodeHelper.scope_for(source_file, line: line_no)\n %Issue{\n issue |\n priority: issue.priority + priority_for(source_file, scope),\n scope: scope\n }\n else\n issue\n end\n end\n\n defp priority_for(source_file, scope) do\n scope_prio_map = Priority.scope_priorities(source_file)\n scope_prio_map[scope] || 0\n end\n\n\n\n defp category_body(nil) do\n quote do\n value =\n __MODULE__\n |> Module.split\n |> Enum.at(2)\n (value || :unknown)\n |> to_string\n |> String.downcase\n |> String.to_atom\n end\n end\n defp category_body(value), do: value\n\n @doc \"Converts a given category to a priority\"\n def to_priority(nil), do: 0\n def to_priority(atom) when is_atom(atom) do\n @base_priority_map[atom]\n end\n def to_priority(value), do: value\n\n @doc \"Converts a given category to an exit status\"\n def to_exit_status(nil), do: 0\n def to_exit_status(atom) when is_atom(atom) do\n @base_category_exit_status_map[atom]\n |> to_exit_status\n end\n def to_exit_status(value), do: value\n\n defp run_on_all_body(true), do: true\n defp run_on_all_body(_), do: false\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"d8f1a5d6b653c14ae44c6eacdbc8e9df7006d284","subject":"Fix logic in get_in docs (#10704)","message":"Fix logic in get_in docs (#10704)\n\n","repos":"kelvinst\/elixir,ggcampinho\/elixir,ggcampinho\/elixir,michalmuskala\/elixir,elixir-lang\/elixir,kelvinst\/elixir,joshprice\/elixir,kimshrier\/elixir,pedrosnk\/elixir,kimshrier\/elixir,pedrosnk\/elixir","old_file":"lib\/elixir\/lib\/kernel.ex","new_file":"lib\/elixir\/lib\/kernel.ex","new_contents":"# Use elixir_bootstrap module to be able to bootstrap Kernel.\n# The bootstrap module provides simpler implementations of the\n# functions removed, simple enough to bootstrap.\nimport Kernel,\n except: [@: 1, defmodule: 2, def: 1, def: 2, defp: 2, defmacro: 1, defmacro: 2, defmacrop: 2]\n\nimport :elixir_bootstrap\n\ndefmodule Kernel do\n @moduledoc \"\"\"\n `Kernel` is Elixir's default environment.\n\n It mainly consists of:\n\n * basic language primitives, such as arithmetic operators, spawning of processes,\n data type handling, and others\n * macros for control-flow and defining new functionality (modules, functions, and the like)\n * guard checks for augmenting pattern matching\n\n You can invoke `Kernel` functions and macros anywhere in Elixir code\n without the use of the `Kernel.` prefix since they have all been\n automatically imported. For example, in IEx, you can call:\n\n iex> is_number(13)\n true\n\n If you don't want to import a function or macro from `Kernel`, use the `:except`\n option and then list the function\/macro by arity:\n\n import Kernel, except: [if: 2, unless: 2]\n\n See `Kernel.SpecialForms.import\/2` for more information on importing.\n\n Elixir also has special forms that are always imported and\n cannot be skipped. These are described in `Kernel.SpecialForms`.\n\n ## The standard library\n\n `Kernel` provides the basic capabilities the Elixir standard library\n is built on top of. It is recommended to explore the standard library\n for advanced functionality. Here are the main groups of modules in the\n standard library (this list is not a complete reference, see the\n documentation sidebar for all entries).\n\n ### Built-in types\n\n The following modules handle Elixir built-in data types:\n\n * `Atom` - literal constants with a name (`true`, `false`, and `nil` are atoms)\n * `Float` - numbers with floating point precision\n * `Function` - a reference to code chunk, created with the `fn\/1` special form\n * `Integer` - whole numbers (not fractions)\n * `List` - collections of a variable number of elements (linked lists)\n * `Map` - collections of key-value pairs\n * `Process` - light-weight threads of execution\n * `Port` - mechanisms to interact with the external world\n * `Tuple` - collections of a fixed number of elements\n\n There are two data types without an accompanying module:\n\n * Bitstring - a sequence of bits, created with `Kernel.SpecialForms.<<>>\/1`.\n When the number of bits is divisible by 8, they are called binaries and can\n be manipulated with Erlang's `:binary` module\n * Reference - a unique value in the runtime system, created with `make_ref\/0`\n\n ### Data types\n\n Elixir also provides other data types that are built on top of the types\n listed above. Some of them are:\n\n * `Date` - `year-month-day` structs in a given calendar\n * `DateTime` - date and time with time zone in a given calendar\n * `Exception` - data raised from errors and unexpected scenarios\n * `MapSet` - unordered collections of unique elements\n * `NaiveDateTime` - date and time without time zone in a given calendar\n * `Keyword` - lists of two-element tuples, often representing optional values\n * `Range` - inclusive ranges between two integers\n * `Regex` - regular expressions\n * `String` - UTF-8 encoded binaries representing characters\n * `Time` - `hour:minute:second` structs in a given calendar\n * `URI` - representation of URIs that identify resources\n * `Version` - representation of versions and requirements\n\n ### System modules\n\n Modules that interface with the underlying system, such as:\n\n * `IO` - handles input and output\n * `File` - interacts with the underlying file system\n * `Path` - manipulates file system paths\n * `System` - reads and writes system information\n\n ### Protocols\n\n Protocols add polymorphic dispatch to Elixir. They are contracts\n implementable by data types. See `Protocol` for more information on\n protocols. Elixir provides the following protocols in the standard library:\n\n * `Collectable` - collects data into a data type\n * `Enumerable` - handles collections in Elixir. The `Enum` module\n provides eager functions for working with collections, the `Stream`\n module provides lazy functions\n * `Inspect` - converts data types into their programming language\n representation\n * `List.Chars` - converts data types to their outside world\n representation as charlists (non-programming based)\n * `String.Chars` - converts data types to their outside world\n representation as strings (non-programming based)\n\n ### Process-based and application-centric functionality\n\n The following modules build on top of processes to provide concurrency,\n fault-tolerance, and more.\n\n * `Agent` - a process that encapsulates mutable state\n * `Application` - functions for starting, stopping and configuring\n applications\n * `GenServer` - a generic client-server API\n * `Registry` - a key-value process-based storage\n * `Supervisor` - a process that is responsible for starting,\n supervising and shutting down other processes\n * `Task` - a process that performs computations\n * `Task.Supervisor` - a supervisor for managing tasks exclusively\n\n ### Supporting documents\n\n Elixir documentation also includes supporting documents under the\n \"Pages\" section. Those are:\n\n * [Compatibility and Deprecations](compatibility-and-deprecations.md) - lists\n compatibility between every Elixir version and Erlang\/OTP, release schema;\n lists all deprecated functions, when they were deprecated and alternatives\n * [Library Guidelines](library-guidelines.md) - general guidelines, anti-patterns,\n and rules for those writing libraries\n * [Naming Conventions](naming-conventions.md) - naming conventions for Elixir code\n * [Operators](operators.md) - lists all Elixir operators and their precedences\n * [Patterns and Guards](patterns-and-guards.md) - an introduction to patterns,\n guards, and extensions\n * [Syntax Reference](syntax-reference.md) - the language syntax reference\n * [Typespecs](typespecs.md)- types and function specifications, including list of types\n * [Unicode Syntax](unicode-syntax.md) - outlines Elixir support for Unicode\n * [Writing Documentation](writing-documentation.md) - guidelines for writing\n documentation in Elixir\n\n ## Guards\n\n This module includes the built-in guards used by Elixir developers.\n They are a predefined set of functions and macros that augment pattern\n matching, typically invoked after the `when` operator. For example:\n\n def drive(%User{age: age}) when age >= 16 do\n ...\n end\n\n The clause above will only be invoked if the user's age is more than\n or equal to 16. Guards also support joining multiple conditions with\n `and` and `or`. The whole guard is true if all guard expressions will\n evaluate to `true`. A more complete introduction to guards is available\n [in the \"Patterns and Guards\" page](patterns-and-guards.md).\n\n ## Structural comparison\n\n The comparison functions in this module perform structural comparison.\n This means structures are compared based on their representation and\n not on their semantic value. This is specially important for functions\n that are meant to provide ordering, such as `>\/2`, `<\/2`, `>=\/2`,\n `<=\/2`, `min\/2`, and `max\/2`. For example:\n\n ~D[2017-03-31] > ~D[2017-04-01]\n\n will return `true` because structural comparison compares the `:day`\n field before `:month` or `:year`. Therefore, when comparing structs,\n you often use the `compare\/2` function made available by the structs\n modules themselves:\n\n iex> Date.compare(~D[2017-03-31], ~D[2017-04-01])\n :lt\n\n Alternatively, you can use the functions in the `Enum` module to\n sort or compute a maximum\/minimum:\n\n iex> Enum.sort([~D[2017-03-31], ~D[2017-04-01]], Date)\n [~D[2017-03-31], ~D[2017-04-01]]\n iex> Enum.max([~D[2017-03-31], ~D[2017-04-01]], Date)\n ~D[2017-04-01]\n\n ## Truthy and falsy values\n\n Besides the booleans `true` and `false`, Elixir has the\n concept of a \"truthy\" or \"falsy\" value.\n\n * a value is truthy when it is neither `false` nor `nil`\n * a value is falsy when it is either `false` or `nil`\n\n Elixir has functions, like `and\/2`, that *only* work with\n booleans, but also functions that work with these\n truthy\/falsy values, like `&&\/2` and `!\/1`.\n\n ### Examples\n\n We can check the truthiness of a value by using the `!\/1`\n function twice.\n\n Truthy values:\n\n iex> !!true\n true\n iex> !!5\n true\n iex> !![1,2]\n true\n iex> !!\"foo\"\n true\n\n Falsy values (of which there are exactly two):\n\n iex> !!false\n false\n iex> !!nil\n false\n\n ## Inlining\n\n Some of the functions described in this module are inlined by\n the Elixir compiler into their Erlang counterparts in the\n [`:erlang` module](http:\/\/www.erlang.org\/doc\/man\/erlang.html).\n Those functions are called BIFs (built-in internal functions)\n in Erlang-land and they exhibit interesting properties, as some\n of them are allowed in guards and others are used for compiler\n optimizations.\n\n Most of the inlined functions can be seen in effect when\n capturing the function:\n\n iex> &Kernel.is_atom\/1\n &:erlang.is_atom\/1\n\n Those functions will be explicitly marked in their docs as\n \"inlined by the compiler\".\n \"\"\"\n\n # We need this check only for bootstrap purposes.\n # Once Kernel is loaded and we recompile, it is a no-op.\n @compile {:inline, bootstrapped?: 1}\n case :code.ensure_loaded(Kernel) do\n {:module, _} ->\n defp bootstrapped?(_), do: true\n\n {:error, _} ->\n defp bootstrapped?(module), do: :code.ensure_loaded(module) == {:module, module}\n end\n\n ## Delegations to Erlang with inlining (macros)\n\n @doc \"\"\"\n Returns an integer or float which is the arithmetical absolute value of `number`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> abs(-3.33)\n 3.33\n\n iex> abs(-3)\n 3\n\n \"\"\"\n @doc guard: true\n @spec abs(number) :: number\n def abs(number) do\n :erlang.abs(number)\n end\n\n @doc \"\"\"\n Invokes the given anonymous function `fun` with the list of\n arguments `args`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> apply(fn x -> x * 2 end, [2])\n 4\n\n \"\"\"\n @spec apply(fun, [any]) :: any\n def apply(fun, args) do\n :erlang.apply(fun, args)\n end\n\n @doc \"\"\"\n Invokes the given function from `module` with the list of\n arguments `args`.\n\n `apply\/3` is used to invoke functions where the module, function\n name or arguments are defined dynamically at runtime. For this\n reason, you can't invoke macros using `apply\/3`, only functions.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> apply(Enum, :reverse, [[1, 2, 3]])\n [3, 2, 1]\n\n \"\"\"\n @spec apply(module, function_name :: atom, [any]) :: any\n def apply(module, function_name, args) do\n :erlang.apply(module, function_name, args)\n end\n\n @doc \"\"\"\n Extracts the part of the binary starting at `start` with length `length`.\n Binaries are zero-indexed.\n\n If `start` or `length` reference in any way outside the binary, an\n `ArgumentError` exception is raised.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> binary_part(\"foo\", 1, 2)\n \"oo\"\n\n A negative `length` can be used to extract bytes that come *before* the byte\n at `start`:\n\n iex> binary_part(\"Hello\", 5, -3)\n \"llo\"\n\n An `ArgumentError` is raised when the length is outside of the binary:\n\n binary_part(\"Hello\", 0, 10)\n ** (ArgumentError) argument error\n\n \"\"\"\n @doc guard: true\n @spec binary_part(binary, non_neg_integer, integer) :: binary\n def binary_part(binary, start, length) do\n :erlang.binary_part(binary, start, length)\n end\n\n @doc \"\"\"\n Returns an integer which is the size in bits of `bitstring`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> bit_size(<<433::16, 3::3>>)\n 19\n\n iex> bit_size(<<1, 2, 3>>)\n 24\n\n \"\"\"\n @doc guard: true\n @spec bit_size(bitstring) :: non_neg_integer\n def bit_size(bitstring) do\n :erlang.bit_size(bitstring)\n end\n\n @doc \"\"\"\n Returns the number of bytes needed to contain `bitstring`.\n\n That is, if the number of bits in `bitstring` is not divisible by 8, the\n resulting number of bytes will be rounded up (by excess). This operation\n happens in constant time.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> byte_size(<<433::16, 3::3>>)\n 3\n\n iex> byte_size(<<1, 2, 3>>)\n 3\n\n \"\"\"\n @doc guard: true\n @spec byte_size(bitstring) :: non_neg_integer\n def byte_size(bitstring) do\n :erlang.byte_size(bitstring)\n end\n\n @doc \"\"\"\n Returns the smallest integer greater than or equal to `number`.\n\n If you want to perform ceil operation on other decimal places,\n use `Float.ceil\/2` instead.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc since: \"1.8.0\", guard: true\n @spec ceil(number) :: integer\n def ceil(number) do\n :erlang.ceil(number)\n end\n\n @doc \"\"\"\n Performs an integer division.\n\n Raises an `ArithmeticError` exception if one of the arguments is not an\n integer, or when the `divisor` is `0`.\n\n `div\/2` performs *truncated* integer division. This means that\n the result is always rounded towards zero.\n\n If you want to perform floored integer division (rounding towards negative infinity),\n use `Integer.floor_div\/2` instead.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n div(5, 2)\n #=> 2\n\n div(6, -4)\n #=> -1\n\n div(-99, 2)\n #=> -49\n\n div(100, 0)\n ** (ArithmeticError) bad argument in arithmetic expression\n\n \"\"\"\n @doc guard: true\n @spec div(integer, neg_integer | pos_integer) :: integer\n def div(dividend, divisor) do\n :erlang.div(dividend, divisor)\n end\n\n @doc \"\"\"\n Stops the execution of the calling process with the given reason.\n\n Since evaluating this function causes the process to terminate,\n it has no return value.\n\n Inlined by the compiler.\n\n ## Examples\n\n When a process reaches its end, by default it exits with\n reason `:normal`. You can also call `exit\/1` explicitly if you\n want to terminate a process but not signal any failure:\n\n exit(:normal)\n\n In case something goes wrong, you can also use `exit\/1` with\n a different reason:\n\n exit(:seems_bad)\n\n If the exit reason is not `:normal`, all the processes linked to the process\n that exited will crash (unless they are trapping exits).\n\n ## OTP exits\n\n Exits are used by the OTP to determine if a process exited abnormally\n or not. The following exits are considered \"normal\":\n\n * `exit(:normal)`\n * `exit(:shutdown)`\n * `exit({:shutdown, term})`\n\n Exiting with any other reason is considered abnormal and treated\n as a crash. This means the default supervisor behaviour kicks in,\n error reports are emitted, and so forth.\n\n This behaviour is relied on in many different places. For example,\n `ExUnit` uses `exit(:shutdown)` when exiting the test process to\n signal linked processes, supervision trees and so on to politely\n shut down too.\n\n ## CLI exits\n\n Building on top of the exit signals mentioned above, if the\n process started by the command line exits with any of the three\n reasons above, its exit is considered normal and the Operating\n System process will exit with status 0.\n\n It is, however, possible to customize the operating system exit\n signal by invoking:\n\n exit({:shutdown, integer})\n\n This will cause the operating system process to exit with the status given by\n `integer` while signaling all linked Erlang processes to politely\n shut down.\n\n Any other exit reason will cause the operating system process to exit with\n status `1` and linked Erlang processes to crash.\n \"\"\"\n @spec exit(term) :: no_return\n def exit(reason) do\n :erlang.exit(reason)\n end\n\n @doc \"\"\"\n Returns the largest integer smaller than or equal to `number`.\n\n If you want to perform floor operation on other decimal places,\n use `Float.floor\/2` instead.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc since: \"1.8.0\", guard: true\n @spec floor(number) :: integer\n def floor(number) do\n :erlang.floor(number)\n end\n\n @doc \"\"\"\n Returns the head of a list. Raises `ArgumentError` if the list is empty.\n\n It works with improper lists.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n hd([1, 2, 3, 4])\n #=> 1\n\n hd([])\n ** (ArgumentError) argument error\n\n hd([1 | 2])\n #=> 1\n\n \"\"\"\n @doc guard: true\n @spec hd(nonempty_maybe_improper_list(elem, any)) :: elem when elem: term\n def hd(list) do\n :erlang.hd(list)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is an atom; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_atom(term) :: boolean\n def is_atom(term) do\n :erlang.is_atom(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a binary; otherwise returns `false`.\n\n A binary always contains a complete number of bytes.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> is_binary(\"foo\")\n true\n iex> is_binary(<<1::3>>)\n false\n\n \"\"\"\n @doc guard: true\n @spec is_binary(term) :: boolean\n def is_binary(term) do\n :erlang.is_binary(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a bitstring (including a binary); otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> is_bitstring(\"foo\")\n true\n iex> is_bitstring(<<1::3>>)\n true\n\n \"\"\"\n @doc guard: true\n @spec is_bitstring(term) :: boolean\n def is_bitstring(term) do\n :erlang.is_bitstring(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is either the atom `true` or the atom `false` (i.e.,\n a boolean); otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_boolean(term) :: boolean\n def is_boolean(term) do\n :erlang.is_boolean(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a floating-point number; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_float(term) :: boolean\n def is_float(term) do\n :erlang.is_float(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a function; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_function(term) :: boolean\n def is_function(term) do\n :erlang.is_function(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a function that can be applied with `arity` number of arguments;\n otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> is_function(fn x -> x * 2 end, 1)\n true\n iex> is_function(fn x -> x * 2 end, 2)\n false\n\n \"\"\"\n @doc guard: true\n @spec is_function(term, non_neg_integer) :: boolean\n def is_function(term, arity) do\n :erlang.is_function(term, arity)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is an integer; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_integer(term) :: boolean\n def is_integer(term) do\n :erlang.is_integer(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a list with zero or more elements; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_list(term) :: boolean\n def is_list(term) do\n :erlang.is_list(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is either an integer or a floating-point number;\n otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_number(term) :: boolean\n def is_number(term) do\n :erlang.is_number(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a PID (process identifier); otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_pid(term) :: boolean\n def is_pid(term) do\n :erlang.is_pid(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a port identifier; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_port(term) :: boolean\n def is_port(term) do\n :erlang.is_port(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a reference; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_reference(term) :: boolean\n def is_reference(term) do\n :erlang.is_reference(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a tuple; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_tuple(term) :: boolean\n def is_tuple(term) do\n :erlang.is_tuple(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a map; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_map(term) :: boolean\n def is_map(term) do\n :erlang.is_map(term)\n end\n\n @doc \"\"\"\n Returns `true` if `key` is a key in `map`; otherwise returns `false`.\n\n It raises `BadMapError` if the first element is not a map.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true, since: \"1.10.0\"\n @spec is_map_key(map, term) :: boolean\n def is_map_key(map, key) do\n :erlang.is_map_key(key, map)\n end\n\n @doc \"\"\"\n Returns the length of `list`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> length([1, 2, 3, 4, 5, 6, 7, 8, 9])\n 9\n\n \"\"\"\n @doc guard: true\n @spec length(list) :: non_neg_integer\n def length(list) do\n :erlang.length(list)\n end\n\n @doc \"\"\"\n Returns an almost unique reference.\n\n The returned reference will re-occur after approximately 2^82 calls;\n therefore it is unique enough for practical purposes.\n\n Inlined by the compiler.\n\n ## Examples\n\n make_ref()\n #=> #Reference<0.0.0.135>\n\n \"\"\"\n @spec make_ref() :: reference\n def make_ref() do\n :erlang.make_ref()\n end\n\n @doc \"\"\"\n Returns the size of a map.\n\n The size of a map is the number of key-value pairs that the map contains.\n\n This operation happens in constant time.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> map_size(%{a: \"foo\", b: \"bar\"})\n 2\n\n \"\"\"\n @doc guard: true\n @spec map_size(map) :: non_neg_integer\n def map_size(map) do\n :erlang.map_size(map)\n end\n\n @doc \"\"\"\n Returns the biggest of the two given terms according to\n their structural comparison.\n\n If the terms compare equal, the first one is returned.\n\n This performs a structural comparison where all Elixir\n terms can be compared with each other. See the [\"Structural\n comparison\" section](#module-structural-comparison) section\n for more information.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> max(1, 2)\n 2\n iex> max(:a, :b)\n :b\n\n \"\"\"\n @spec max(first, second) :: first | second when first: term, second: term\n def max(first, second) do\n :erlang.max(first, second)\n end\n\n @doc \"\"\"\n Returns the smallest of the two given terms according to\n their structural comparison.\n\n If the terms compare equal, the first one is returned.\n\n This performs a structural comparison where all Elixir\n terms can be compared with each other. See the [\"Structural\n comparison\" section](#module-structural-comparison) section\n for more information.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> min(1, 2)\n 1\n iex> min(\"foo\", \"bar\")\n \"bar\"\n\n \"\"\"\n @spec min(first, second) :: first | second when first: term, second: term\n def min(first, second) do\n :erlang.min(first, second)\n end\n\n @doc \"\"\"\n Returns an atom representing the name of the local node.\n If the node is not alive, `:nonode@nohost` is returned instead.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec node() :: node\n def node do\n :erlang.node()\n end\n\n @doc \"\"\"\n Returns the node where the given argument is located.\n The argument can be a PID, a reference, or a port.\n If the local node is not alive, `:nonode@nohost` is returned.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec node(pid | reference | port) :: node\n def node(arg) do\n :erlang.node(arg)\n end\n\n @doc \"\"\"\n Computes the remainder of an integer division.\n\n `rem\/2` uses truncated division, which means that\n the result will always have the sign of the `dividend`.\n\n Raises an `ArithmeticError` exception if one of the arguments is not an\n integer, or when the `divisor` is `0`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> rem(5, 2)\n 1\n iex> rem(6, -4)\n 2\n\n \"\"\"\n @doc guard: true\n @spec rem(integer, neg_integer | pos_integer) :: integer\n def rem(dividend, divisor) do\n :erlang.rem(dividend, divisor)\n end\n\n @doc \"\"\"\n Rounds a number to the nearest integer.\n\n If the number is equidistant to the two nearest integers, rounds away from zero.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> round(5.6)\n 6\n\n iex> round(5.2)\n 5\n\n iex> round(-9.9)\n -10\n\n iex> round(-9)\n -9\n\n iex> round(2.5)\n 3\n\n iex> round(-2.5)\n -3\n\n \"\"\"\n @doc guard: true\n @spec round(number) :: integer\n def round(number) do\n :erlang.round(number)\n end\n\n @doc \"\"\"\n Sends a message to the given `dest` and returns the message.\n\n `dest` may be a remote or local PID, a local port, a locally\n registered name, or a tuple in the form of `{registered_name, node}` for a\n registered name at another node.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> send(self(), :hello)\n :hello\n\n \"\"\"\n @spec send(dest :: Process.dest(), message) :: message when message: any\n def send(dest, message) do\n :erlang.send(dest, message)\n end\n\n @doc \"\"\"\n Returns the PID (process identifier) of the calling process.\n\n Allowed in guard clauses. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec self() :: pid\n def self() do\n :erlang.self()\n end\n\n @doc \"\"\"\n Spawns the given function and returns its PID.\n\n Typically developers do not use the `spawn` functions, instead they use\n abstractions such as `Task`, `GenServer` and `Agent`, built on top of\n `spawn`, that spawns processes with more conveniences in terms of\n introspection and debugging.\n\n Check the `Process` module for more process-related functions.\n\n The anonymous function receives 0 arguments, and may return any value.\n\n Inlined by the compiler.\n\n ## Examples\n\n current = self()\n child = spawn(fn -> send(current, {self(), 1 + 2}) end)\n\n receive do\n {^child, 3} -> IO.puts(\"Received 3 back\")\n end\n\n \"\"\"\n @spec spawn((() -> any)) :: pid\n def spawn(fun) do\n :erlang.spawn(fun)\n end\n\n @doc \"\"\"\n Spawns the given function `fun` from the given `module` passing it the given\n `args` and returns its PID.\n\n Typically developers do not use the `spawn` functions, instead they use\n abstractions such as `Task`, `GenServer` and `Agent`, built on top of\n `spawn`, that spawns processes with more conveniences in terms of\n introspection and debugging.\n\n Check the `Process` module for more process-related functions.\n\n Inlined by the compiler.\n\n ## Examples\n\n spawn(SomeModule, :function, [1, 2, 3])\n\n \"\"\"\n @spec spawn(module, atom, list) :: pid\n def spawn(module, fun, args) do\n :erlang.spawn(module, fun, args)\n end\n\n @doc \"\"\"\n Spawns the given function, links it to the current process, and returns its PID.\n\n Typically developers do not use the `spawn` functions, instead they use\n abstractions such as `Task`, `GenServer` and `Agent`, built on top of\n `spawn`, that spawns processes with more conveniences in terms of\n introspection and debugging.\n\n Check the `Process` module for more process-related functions. For more\n information on linking, check `Process.link\/1`.\n\n The anonymous function receives 0 arguments, and may return any value.\n\n Inlined by the compiler.\n\n ## Examples\n\n current = self()\n child = spawn_link(fn -> send(current, {self(), 1 + 2}) end)\n\n receive do\n {^child, 3} -> IO.puts(\"Received 3 back\")\n end\n\n \"\"\"\n @spec spawn_link((() -> any)) :: pid\n def spawn_link(fun) do\n :erlang.spawn_link(fun)\n end\n\n @doc \"\"\"\n Spawns the given function `fun` from the given `module` passing it the given\n `args`, links it to the current process, and returns its PID.\n\n Typically developers do not use the `spawn` functions, instead they use\n abstractions such as `Task`, `GenServer` and `Agent`, built on top of\n `spawn`, that spawns processes with more conveniences in terms of\n introspection and debugging.\n\n Check the `Process` module for more process-related functions. For more\n information on linking, check `Process.link\/1`.\n\n Inlined by the compiler.\n\n ## Examples\n\n spawn_link(SomeModule, :function, [1, 2, 3])\n\n \"\"\"\n @spec spawn_link(module, atom, list) :: pid\n def spawn_link(module, fun, args) do\n :erlang.spawn_link(module, fun, args)\n end\n\n @doc \"\"\"\n Spawns the given function, monitors it and returns its PID\n and monitoring reference.\n\n Typically developers do not use the `spawn` functions, instead they use\n abstractions such as `Task`, `GenServer` and `Agent`, built on top of\n `spawn`, that spawns processes with more conveniences in terms of\n introspection and debugging.\n\n Check the `Process` module for more process-related functions.\n\n The anonymous function receives 0 arguments, and may return any value.\n\n Inlined by the compiler.\n\n ## Examples\n\n current = self()\n spawn_monitor(fn -> send(current, {self(), 1 + 2}) end)\n\n \"\"\"\n @spec spawn_monitor((() -> any)) :: {pid, reference}\n def spawn_monitor(fun) do\n :erlang.spawn_monitor(fun)\n end\n\n @doc \"\"\"\n Spawns the given module and function passing the given args,\n monitors it and returns its PID and monitoring reference.\n\n Typically developers do not use the `spawn` functions, instead they use\n abstractions such as `Task`, `GenServer` and `Agent`, built on top of\n `spawn`, that spawns processes with more conveniences in terms of\n introspection and debugging.\n\n Check the `Process` module for more process-related functions.\n\n Inlined by the compiler.\n\n ## Examples\n\n spawn_monitor(SomeModule, :function, [1, 2, 3])\n\n \"\"\"\n @spec spawn_monitor(module, atom, list) :: {pid, reference}\n def spawn_monitor(module, fun, args) do\n :erlang.spawn_monitor(module, fun, args)\n end\n\n @doc \"\"\"\n Pipes `value` to the given `fun` and returns the `value` itself.\n\n Useful for running synchronous side effects in a pipeline.\n\n ## Examples\n\n iex> tap(1, fn x -> x + 1 end)\n 1\n\n Most commonly, this is used in pipelines. For example,\n let's suppose you want to inspect part of a data structure.\n You could write:\n\n %{a: 1}\n |> Map.update!(:a, & &1 + 2)\n |> tap(&IO.inspect(&1.a))\n |> Map.update!(:a, & &1 * 2)\n\n \"\"\"\n @doc since: \"1.12.0\"\n defmacro tap(value, fun) do\n quote bind_quoted: [fun: fun, value: value] do\n fun.(value)\n value\n end\n end\n\n @doc \"\"\"\n A non-local return from a function.\n\n Check `Kernel.SpecialForms.try\/1` for more information.\n\n Inlined by the compiler.\n \"\"\"\n @spec throw(term) :: no_return\n def throw(term) do\n :erlang.throw(term)\n end\n\n @doc \"\"\"\n Returns the tail of a list. Raises `ArgumentError` if the list is empty.\n\n It works with improper lists.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n tl([1, 2, 3, :go])\n #=> [2, 3, :go]\n\n tl([])\n ** (ArgumentError) argument error\n\n tl([:one])\n #=> []\n\n tl([:a, :b | :c])\n #=> [:b | :c]\n\n tl([:a | %{b: 1}])\n #=> %{b: 1}\n\n \"\"\"\n @doc guard: true\n @spec tl(nonempty_maybe_improper_list(elem, tail)) :: maybe_improper_list(elem, tail) | tail\n when elem: term, tail: term\n def tl(list) do\n :erlang.tl(list)\n end\n\n @doc \"\"\"\n Returns the integer part of `number`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> trunc(5.4)\n 5\n\n iex> trunc(-5.99)\n -5\n\n iex> trunc(-5)\n -5\n\n \"\"\"\n @doc guard: true\n @spec trunc(number) :: integer\n def trunc(number) do\n :erlang.trunc(number)\n end\n\n @doc \"\"\"\n Returns the size of a tuple.\n\n This operation happens in constant time.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> tuple_size({:a, :b, :c})\n 3\n\n \"\"\"\n @doc guard: true\n @spec tuple_size(tuple) :: non_neg_integer\n def tuple_size(tuple) do\n :erlang.tuple_size(tuple)\n end\n\n @doc \"\"\"\n Arithmetic addition operator.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 + 2\n 3\n\n \"\"\"\n @doc guard: true\n @spec integer + integer :: integer\n @spec float + float :: float\n @spec integer + float :: float\n @spec float + integer :: float\n def left + right do\n :erlang.+(left, right)\n end\n\n @doc \"\"\"\n Arithmetic subtraction operator.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 - 2\n -1\n\n \"\"\"\n @doc guard: true\n @spec integer - integer :: integer\n @spec float - float :: float\n @spec integer - float :: float\n @spec float - integer :: float\n def left - right do\n :erlang.-(left, right)\n end\n\n @doc \"\"\"\n Arithmetic positive unary operator.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> +1\n 1\n\n \"\"\"\n @doc guard: true\n @spec +integer :: integer\n @spec +float :: float\n def +value do\n :erlang.+(value)\n end\n\n @doc \"\"\"\n Arithmetic negative unary operator.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> -2\n -2\n\n \"\"\"\n @doc guard: true\n @spec -0 :: 0\n @spec -pos_integer :: neg_integer\n @spec -neg_integer :: pos_integer\n @spec -float :: float\n def -value do\n :erlang.-(value)\n end\n\n @doc \"\"\"\n Arithmetic multiplication operator.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 * 2\n 2\n\n \"\"\"\n @doc guard: true\n @spec integer * integer :: integer\n @spec float * float :: float\n @spec integer * float :: float\n @spec float * integer :: float\n def left * right do\n :erlang.*(left, right)\n end\n\n @doc \"\"\"\n Arithmetic division operator.\n\n The result is always a float. Use `div\/2` and `rem\/2` if you want\n an integer division or the remainder.\n\n Raises `ArithmeticError` if `right` is 0 or 0.0.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n 1 \/ 2\n #=> 0.5\n\n -3.0 \/ 2.0\n #=> -1.5\n\n 5 \/ 1\n #=> 5.0\n\n 7 \/ 0\n ** (ArithmeticError) bad argument in arithmetic expression\n\n \"\"\"\n @doc guard: true\n @spec number \/ number :: float\n def left \/ right do\n :erlang.\/(left, right)\n end\n\n @doc \"\"\"\n List concatenation operator. Concatenates a proper list and a term, returning a list.\n\n The complexity of `a ++ b` is proportional to `length(a)`, so avoid repeatedly\n appending to lists of arbitrary length, for example, `list ++ [element]`.\n Instead, consider prepending via `[element | rest]` and then reversing.\n\n If the `right` operand is not a proper list, it returns an improper list.\n If the `left` operand is not a proper list, it raises `ArgumentError`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> [1] ++ [2, 3]\n [1, 2, 3]\n\n iex> 'foo' ++ 'bar'\n 'foobar'\n\n # returns an improper list\n iex> [1] ++ 2\n [1 | 2]\n\n # returns a proper list\n iex> [1] ++ [2]\n [1, 2]\n\n # improper list on the right will return an improper list\n iex> [1] ++ [2 | 3]\n [1, 2 | 3]\n\n \"\"\"\n @spec list ++ term :: maybe_improper_list\n def left ++ right do\n :erlang.++(left, right)\n end\n\n @doc \"\"\"\n List subtraction operator. Removes the first occurrence of an element on the left list\n for each element on the right.\n\n Before Erlang\/OTP 22, the complexity of `a -- b` was proportional to\n `length(a) * length(b)`, meaning that it would be very slow if\n both `a` and `b` were long lists. In such cases, consider\n converting each list to a `MapSet` and using `MapSet.difference\/2`.\n\n As of Erlang\/OTP 22, this operation is significantly faster even if both\n lists are very long, and using `--\/2` is usually faster and uses less\n memory than using the `MapSet`-based alternative mentioned above.\n See also the [Erlang efficiency\n guide](https:\/\/erlang.org\/doc\/efficiency_guide\/retired_myths.html).\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> [1, 2, 3] -- [1, 2]\n [3]\n\n iex> [1, 2, 3, 2, 1] -- [1, 2, 2]\n [3, 1]\n\n The `--\/2` operator is right associative, meaning:\n\n iex> [1, 2, 3] -- [2] -- [3]\n [1, 3]\n\n As it is equivalent to:\n\n iex> [1, 2, 3] -- ([2] -- [3])\n [1, 3]\n\n \"\"\"\n @spec list -- list :: list\n def left -- right do\n :erlang.--(left, right)\n end\n\n @doc \"\"\"\n Strictly boolean \"not\" operator.\n\n `value` must be a boolean; if it's not, an `ArgumentError` exception is raised.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> not false\n true\n\n \"\"\"\n @doc guard: true\n @spec not true :: false\n @spec not false :: true\n def not value do\n :erlang.not(value)\n end\n\n @doc \"\"\"\n Less-than operator.\n\n Returns `true` if `left` is less than `right`.\n\n This performs a structural comparison where all Elixir\n terms can be compared with each other. See the [\"Structural\n comparison\" section](#module-structural-comparison) section\n for more information.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 < 2\n true\n\n \"\"\"\n @doc guard: true\n @spec term < term :: boolean\n def left < right do\n :erlang.<(left, right)\n end\n\n @doc \"\"\"\n Greater-than operator.\n\n Returns `true` if `left` is more than `right`.\n\n This performs a structural comparison where all Elixir\n terms can be compared with each other. See the [\"Structural\n comparison\" section](#module-structural-comparison) section\n for more information.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 > 2\n false\n\n \"\"\"\n @doc guard: true\n @spec term > term :: boolean\n def left > right do\n :erlang.>(left, right)\n end\n\n @doc \"\"\"\n Less-than or equal to operator.\n\n Returns `true` if `left` is less than or equal to `right`.\n\n This performs a structural comparison where all Elixir\n terms can be compared with each other. See the [\"Structural\n comparison\" section](#module-structural-comparison) section\n for more information.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 <= 2\n true\n\n \"\"\"\n @doc guard: true\n @spec term <= term :: boolean\n def left <= right do\n :erlang.\"=<\"(left, right)\n end\n\n @doc \"\"\"\n Greater-than or equal to operator.\n\n Returns `true` if `left` is more than or equal to `right`.\n\n This performs a structural comparison where all Elixir\n terms can be compared with each other. See the [\"Structural\n comparison\" section](#module-structural-comparison) section\n for more information.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 >= 2\n false\n\n \"\"\"\n @doc guard: true\n @spec term >= term :: boolean\n def left >= right do\n :erlang.>=(left, right)\n end\n\n @doc \"\"\"\n Equal to operator. Returns `true` if the two terms are equal.\n\n This operator considers 1 and 1.0 to be equal. For stricter\n semantics, use `===\/2` instead.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 == 2\n false\n\n iex> 1 == 1.0\n true\n\n \"\"\"\n @doc guard: true\n @spec term == term :: boolean\n def left == right do\n :erlang.==(left, right)\n end\n\n @doc \"\"\"\n Not equal to operator.\n\n Returns `true` if the two terms are not equal.\n\n This operator considers 1 and 1.0 to be equal. For match\n comparison, use `!==\/2` instead.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 != 2\n true\n\n iex> 1 != 1.0\n false\n\n \"\"\"\n @doc guard: true\n @spec term != term :: boolean\n def left != right do\n :erlang.\"\/=\"(left, right)\n end\n\n @doc \"\"\"\n Strictly equal to operator.\n\n Returns `true` if the two terms are exactly equal.\n\n The terms are only considered to be exactly equal if they\n have the same value and are of the same type. For example,\n `1 == 1.0` returns `true`, but since they are of different\n types, `1 === 1.0` returns `false`.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 === 2\n false\n\n iex> 1 === 1.0\n false\n\n \"\"\"\n @doc guard: true\n @spec term === term :: boolean\n def left === right do\n :erlang.\"=:=\"(left, right)\n end\n\n @doc \"\"\"\n Strictly not equal to operator.\n\n Returns `true` if the two terms are not exactly equal.\n See `===\/2` for a definition of what is considered \"exactly equal\".\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 !== 2\n true\n\n iex> 1 !== 1.0\n true\n\n \"\"\"\n @doc guard: true\n @spec term !== term :: boolean\n def left !== right do\n :erlang.\"=\/=\"(left, right)\n end\n\n @doc \"\"\"\n Gets the element at the zero-based `index` in `tuple`.\n\n It raises `ArgumentError` when index is negative or it is out of range of the tuple elements.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n tuple = {:foo, :bar, 3}\n elem(tuple, 1)\n #=> :bar\n\n elem({}, 0)\n ** (ArgumentError) argument error\n\n elem({:foo, :bar}, 2)\n ** (ArgumentError) argument error\n\n \"\"\"\n @doc guard: true\n @spec elem(tuple, non_neg_integer) :: term\n def elem(tuple, index) do\n :erlang.element(index + 1, tuple)\n end\n\n @doc \"\"\"\n Puts `value` at the given zero-based `index` in `tuple`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> tuple = {:foo, :bar, 3}\n iex> put_elem(tuple, 0, :baz)\n {:baz, :bar, 3}\n\n \"\"\"\n @spec put_elem(tuple, non_neg_integer, term) :: tuple\n def put_elem(tuple, index, value) do\n :erlang.setelement(index + 1, tuple, value)\n end\n\n ## Implemented in Elixir\n\n defp optimize_boolean({:case, meta, args}) do\n {:case, [{:optimize_boolean, true} | meta], args}\n end\n\n @doc \"\"\"\n Strictly boolean \"or\" operator.\n\n If `left` is `true`, returns `true`; otherwise returns `right`.\n\n Requires only the `left` operand to be a boolean since it short-circuits.\n If the `left` operand is not a boolean, a `BadBooleanError` exception is\n raised.\n\n Allowed in guard tests.\n\n ## Examples\n\n iex> true or false\n true\n\n iex> false or 42\n 42\n\n iex> 42 or false\n ** (BadBooleanError) expected a boolean on left-side of \"or\", got: 42\n\n \"\"\"\n @doc guard: true\n defmacro left or right do\n case __CALLER__.context do\n nil -> build_boolean_check(:or, left, true, right)\n :match -> invalid_match!(:or)\n :guard -> quote(do: :erlang.orelse(unquote(left), unquote(right)))\n end\n end\n\n @doc \"\"\"\n Strictly boolean \"and\" operator.\n\n If `left` is `false`, returns `false`; otherwise returns `right`.\n\n Requires only the `left` operand to be a boolean since it short-circuits. If\n the `left` operand is not a boolean, a `BadBooleanError` exception is raised.\n\n Allowed in guard tests.\n\n ## Examples\n\n iex> true and false\n false\n\n iex> true and \"yay!\"\n \"yay!\"\n\n iex> \"yay!\" and true\n ** (BadBooleanError) expected a boolean on left-side of \"and\", got: \"yay!\"\n\n \"\"\"\n @doc guard: true\n defmacro left and right do\n case __CALLER__.context do\n nil -> build_boolean_check(:and, left, right, false)\n :match -> invalid_match!(:and)\n :guard -> quote(do: :erlang.andalso(unquote(left), unquote(right)))\n end\n end\n\n defp build_boolean_check(operator, check, true_clause, false_clause) do\n optimize_boolean(\n quote do\n case unquote(check) do\n false -> unquote(false_clause)\n true -> unquote(true_clause)\n other -> :erlang.error({:badbool, unquote(operator), other})\n end\n end\n )\n end\n\n @doc \"\"\"\n Boolean \"not\" operator.\n\n Receives any value (not just booleans) and returns `true` if `value`\n is `false` or `nil`; returns `false` otherwise.\n\n Not allowed in guard clauses.\n\n ## Examples\n\n iex> !Enum.empty?([])\n false\n\n iex> !List.first([])\n true\n\n \"\"\"\n defmacro !value\n\n defmacro !{:!, _, [value]} do\n assert_no_match_or_guard_scope(__CALLER__.context, \"!\")\n\n optimize_boolean(\n quote do\n case unquote(value) do\n x when :\"Elixir.Kernel\".in(x, [false, nil]) -> false\n _ -> true\n end\n end\n )\n end\n\n defmacro !value do\n assert_no_match_or_guard_scope(__CALLER__.context, \"!\")\n\n optimize_boolean(\n quote do\n case unquote(value) do\n x when :\"Elixir.Kernel\".in(x, [false, nil]) -> true\n _ -> false\n end\n end\n )\n end\n\n @doc \"\"\"\n Binary concatenation operator. Concatenates two binaries.\n\n ## Examples\n\n iex> \"foo\" <> \"bar\"\n \"foobar\"\n\n The `<>\/2` operator can also be used in pattern matching (and guard clauses) as\n long as the left argument is a literal binary:\n\n iex> \"foo\" <> x = \"foobar\"\n iex> x\n \"bar\"\n\n `x <> \"bar\" = \"foobar\"` would have resulted in a `CompileError` exception.\n\n \"\"\"\n defmacro left <> right do\n concats = extract_concatenations({:<>, [], [left, right]}, __CALLER__)\n quote(do: <>)\n end\n\n # Extracts concatenations in order to optimize many\n # concatenations into one single clause.\n defp extract_concatenations({:<>, _, [left, right]}, caller) do\n [wrap_concatenation(left, :left, caller) | extract_concatenations(right, caller)]\n end\n\n defp extract_concatenations(other, caller) do\n [wrap_concatenation(other, :right, caller)]\n end\n\n defp wrap_concatenation(binary, _side, _caller) when is_binary(binary) do\n binary\n end\n\n defp wrap_concatenation(literal, _side, _caller)\n when is_list(literal) or is_atom(literal) or is_integer(literal) or is_float(literal) do\n :erlang.error(\n ArgumentError.exception(\n \"expected binary argument in <> operator but got: #{Macro.to_string(literal)}\"\n )\n )\n end\n\n defp wrap_concatenation(other, side, caller) do\n expanded = expand_concat_argument(other, side, caller)\n {:\"::\", [], [expanded, {:binary, [], nil}]}\n end\n\n defp expand_concat_argument(arg, :left, %{context: :match} = caller) do\n expanded_arg =\n case bootstrapped?(Macro) do\n true -> Macro.expand(arg, caller)\n false -> arg\n end\n\n case expanded_arg do\n {var, _, nil} when is_atom(var) ->\n invalid_concat_left_argument_error(Atom.to_string(var))\n\n {:^, _, [{var, _, nil}]} when is_atom(var) ->\n invalid_concat_left_argument_error(\"^#{Atom.to_string(var)}\")\n\n _ ->\n expanded_arg\n end\n end\n\n defp expand_concat_argument(arg, _, _) do\n arg\n end\n\n defp invalid_concat_left_argument_error(arg) do\n :erlang.error(\n ArgumentError.exception(\n \"the left argument of <> operator inside a match should always be a literal \" <>\n \"binary because its size can't be verified. Got: #{arg}\"\n )\n )\n end\n\n @doc \"\"\"\n Raises an exception.\n\n If `message` is a string, it raises a `RuntimeError` exception with it.\n\n If `message` is an atom, it just calls `raise\/2` with the atom as the first\n argument and `[]` as the second one.\n\n If `message` is an exception struct, it is raised as is.\n\n If `message` is anything else, `raise` will fail with an `ArgumentError`\n exception.\n\n ## Examples\n\n iex> raise \"oops\"\n ** (RuntimeError) oops\n\n try do\n 1 + :foo\n rescue\n x in [ArithmeticError] ->\n IO.puts(\"that was expected\")\n raise x\n end\n\n \"\"\"\n defmacro raise(message) do\n # Try to figure out the type at compilation time\n # to avoid dead code and make Dialyzer happy.\n message =\n case not is_binary(message) and bootstrapped?(Macro) do\n true -> Macro.expand(message, __CALLER__)\n false -> message\n end\n\n case message do\n message when is_binary(message) ->\n quote do\n :erlang.error(RuntimeError.exception(unquote(message)))\n end\n\n {:<<>>, _, _} = message ->\n quote do\n :erlang.error(RuntimeError.exception(unquote(message)))\n end\n\n alias when is_atom(alias) ->\n quote do\n :erlang.error(unquote(alias).exception([]))\n end\n\n _ ->\n quote do\n :erlang.error(Kernel.Utils.raise(unquote(message)))\n end\n end\n end\n\n @doc \"\"\"\n Raises an exception.\n\n Calls the `exception\/1` function on the given argument (which has to be a\n module name like `ArgumentError` or `RuntimeError`) passing `attributes`\n in order to retrieve the exception struct.\n\n Any module that contains a call to the `defexception\/1` macro automatically\n implements the `c:Exception.exception\/1` callback expected by `raise\/2`.\n For more information, see `defexception\/1`.\n\n ## Examples\n\n iex> raise(ArgumentError, \"Sample\")\n ** (ArgumentError) Sample\n\n \"\"\"\n defmacro raise(exception, attributes) do\n quote do\n :erlang.error(unquote(exception).exception(unquote(attributes)))\n end\n end\n\n @doc \"\"\"\n Raises an exception preserving a previous stacktrace.\n\n Works like `raise\/1` but does not generate a new stacktrace.\n\n Note that `__STACKTRACE__` can be used inside catch\/rescue\n to retrieve the current stacktrace.\n\n ## Examples\n\n try do\n raise \"oops\"\n rescue\n exception ->\n reraise exception, __STACKTRACE__\n end\n\n \"\"\"\n defmacro reraise(message, stacktrace) do\n # Try to figure out the type at compilation time\n # to avoid dead code and make Dialyzer happy.\n case Macro.expand(message, __CALLER__) do\n message when is_binary(message) ->\n quote do\n :erlang.error(\n :erlang.raise(:error, RuntimeError.exception(unquote(message)), unquote(stacktrace))\n )\n end\n\n {:<<>>, _, _} = message ->\n quote do\n :erlang.error(\n :erlang.raise(:error, RuntimeError.exception(unquote(message)), unquote(stacktrace))\n )\n end\n\n alias when is_atom(alias) ->\n quote do\n :erlang.error(:erlang.raise(:error, unquote(alias).exception([]), unquote(stacktrace)))\n end\n\n message ->\n quote do\n :erlang.error(\n :erlang.raise(:error, Kernel.Utils.raise(unquote(message)), unquote(stacktrace))\n )\n end\n end\n end\n\n @doc \"\"\"\n Raises an exception preserving a previous stacktrace.\n\n `reraise\/3` works like `reraise\/2`, except it passes arguments to the\n `exception\/1` function as explained in `raise\/2`.\n\n ## Examples\n\n try do\n raise \"oops\"\n rescue\n exception ->\n reraise WrapperError, [exception: exception], __STACKTRACE__\n end\n\n \"\"\"\n defmacro reraise(exception, attributes, stacktrace) do\n quote do\n :erlang.raise(\n :error,\n unquote(exception).exception(unquote(attributes)),\n unquote(stacktrace)\n )\n end\n end\n\n @doc \"\"\"\n Text-based match operator. Matches the term on the `left`\n against the regular expression or string on the `right`.\n\n If `right` is a regular expression, returns `true` if `left` matches right.\n\n If `right` is a string, returns `true` if `left` contains `right`.\n\n ## Examples\n\n iex> \"abcd\" =~ ~r\/c(d)\/\n true\n\n iex> \"abcd\" =~ ~r\/e\/\n false\n\n iex> \"abcd\" =~ ~r\/\/\n true\n\n iex> \"abcd\" =~ \"bc\"\n true\n\n iex> \"abcd\" =~ \"ad\"\n false\n\n iex> \"abcd\" =~ \"abcd\"\n true\n\n iex> \"abcd\" =~ \"\"\n true\n\n \"\"\"\n @spec String.t() =~ (String.t() | Regex.t()) :: boolean\n def left =~ \"\" when is_binary(left), do: true\n\n def left =~ right when is_binary(left) and is_binary(right) do\n :binary.match(left, right) != :nomatch\n end\n\n def left =~ right when is_binary(left) do\n Regex.match?(right, left)\n end\n\n @doc ~S\"\"\"\n Inspects the given argument according to the `Inspect` protocol.\n The second argument is a keyword list with options to control\n inspection.\n\n ## Options\n\n `inspect\/2` accepts a list of options that are internally\n translated to an `Inspect.Opts` struct. Check the docs for\n `Inspect.Opts` to see the supported options.\n\n ## Examples\n\n iex> inspect(:foo)\n \":foo\"\n\n iex> inspect([1, 2, 3, 4, 5], limit: 3)\n \"[1, 2, 3, ...]\"\n\n iex> inspect([1, 2, 3], pretty: true, width: 0)\n \"[1,\\n 2,\\n 3]\"\n\n iex> inspect(\"ol\u00e1\" <> <<0>>)\n \"<<111, 108, 195, 161, 0>>\"\n\n iex> inspect(\"ol\u00e1\" <> <<0>>, binaries: :as_strings)\n \"\\\"ol\u00e1\\\\0\\\"\"\n\n iex> inspect(\"ol\u00e1\", binaries: :as_binaries)\n \"<<111, 108, 195, 161>>\"\n\n iex> inspect('bar')\n \"'bar'\"\n\n iex> inspect([0 | 'bar'])\n \"[0, 98, 97, 114]\"\n\n iex> inspect(100, base: :octal)\n \"0o144\"\n\n iex> inspect(100, base: :hex)\n \"0x64\"\n\n Note that the `Inspect` protocol does not necessarily return a valid\n representation of an Elixir term. In such cases, the inspected result\n must start with `#`. For example, inspecting a function will return:\n\n inspect(fn a, b -> a + b end)\n #=> #Function<...>\n\n The `Inspect` protocol can be derived to hide certain fields\n from structs, so they don't show up in logs, inspects and similar.\n See the \"Deriving\" section of the documentation of the `Inspect`\n protocol for more information.\n \"\"\"\n @spec inspect(Inspect.t(), keyword) :: String.t()\n def inspect(term, opts \\\\ []) when is_list(opts) do\n opts = struct(Inspect.Opts, opts)\n\n limit =\n case opts.pretty do\n true -> opts.width\n false -> :infinity\n end\n\n doc = Inspect.Algebra.group(Inspect.Algebra.to_doc(term, opts))\n IO.iodata_to_binary(Inspect.Algebra.format(doc, limit))\n end\n\n @doc \"\"\"\n Creates and updates a struct.\n\n The `struct` argument may be an atom (which defines `defstruct`)\n or a `struct` itself. The second argument is any `Enumerable` that\n emits two-element tuples (key-value pairs) during enumeration.\n\n Keys in the `Enumerable` that don't exist in the struct are automatically\n discarded. Note that keys must be atoms, as only atoms are allowed when\n defining a struct. If keys in the `Enumerable` are duplicated, the last\n entry will be taken (same behaviour as `Map.new\/1`).\n\n This function is useful for dynamically creating and updating structs, as\n well as for converting maps to structs; in the latter case, just inserting\n the appropriate `:__struct__` field into the map may not be enough and\n `struct\/2` should be used instead.\n\n ## Examples\n\n defmodule User do\n defstruct name: \"john\"\n end\n\n struct(User)\n #=> %User{name: \"john\"}\n\n opts = [name: \"meg\"]\n user = struct(User, opts)\n #=> %User{name: \"meg\"}\n\n struct(user, unknown: \"value\")\n #=> %User{name: \"meg\"}\n\n struct(User, %{name: \"meg\"})\n #=> %User{name: \"meg\"}\n\n # String keys are ignored\n struct(User, %{\"name\" => \"meg\"})\n #=> %User{name: \"john\"}\n\n \"\"\"\n @spec struct(module | struct, Enum.t()) :: struct\n def struct(struct, fields \\\\ []) do\n struct(struct, fields, fn\n {:__struct__, _val}, acc ->\n acc\n\n {key, val}, acc ->\n case acc do\n %{^key => _} -> %{acc | key => val}\n _ -> acc\n end\n end)\n end\n\n @doc \"\"\"\n Similar to `struct\/2` but checks for key validity.\n\n The function `struct!\/2` emulates the compile time behaviour\n of structs. This means that:\n\n * when building a struct, as in `struct!(SomeStruct, key: :value)`,\n it is equivalent to `%SomeStruct{key: :value}` and therefore this\n function will check if every given key-value belongs to the struct.\n If the struct is enforcing any key via `@enforce_keys`, those will\n be enforced as well;\n\n * when updating a struct, as in `struct!(%SomeStruct{}, key: :value)`,\n it is equivalent to `%SomeStruct{struct | key: :value}` and therefore this\n function will check if every given key-value belongs to the struct.\n However, updating structs does not enforce keys, as keys are enforced\n only when building;\n\n \"\"\"\n @spec struct!(module | struct, Enum.t()) :: struct\n def struct!(struct, fields \\\\ [])\n\n def struct!(struct, fields) when is_atom(struct) do\n validate_struct!(struct.__struct__(fields), struct, 1)\n end\n\n def struct!(struct, fields) when is_map(struct) do\n struct(struct, fields, fn\n {:__struct__, _}, acc ->\n acc\n\n {key, val}, acc ->\n Map.replace!(acc, key, val)\n end)\n end\n\n defp struct(struct, [], _fun) when is_atom(struct) do\n validate_struct!(struct.__struct__(), struct, 0)\n end\n\n defp struct(struct, fields, fun) when is_atom(struct) do\n struct(validate_struct!(struct.__struct__(), struct, 0), fields, fun)\n end\n\n defp struct(%_{} = struct, [], _fun) do\n struct\n end\n\n defp struct(%_{} = struct, fields, fun) do\n Enum.reduce(fields, struct, fun)\n end\n\n defp validate_struct!(%{__struct__: module} = struct, module, _arity) do\n struct\n end\n\n defp validate_struct!(%{__struct__: struct_name}, module, arity) when is_atom(struct_name) do\n error_message =\n \"expected struct name returned by #{inspect(module)}.__struct__\/#{arity} to be \" <>\n \"#{inspect(module)}, got: #{inspect(struct_name)}\"\n\n :erlang.error(ArgumentError.exception(error_message))\n end\n\n defp validate_struct!(expr, module, arity) do\n error_message =\n \"expected #{inspect(module)}.__struct__\/#{arity} to return a map with a :__struct__ \" <>\n \"key that holds the name of the struct (atom), got: #{inspect(expr)}\"\n\n :erlang.error(ArgumentError.exception(error_message))\n end\n\n @doc \"\"\"\n Returns true if `term` is a struct; otherwise returns `false`.\n\n Allowed in guard tests.\n\n ## Examples\n\n iex> is_struct(URI.parse(\"\/\"))\n true\n\n iex> is_struct(%{})\n false\n\n \"\"\"\n @doc since: \"1.10.0\", guard: true\n defmacro is_struct(term) do\n case __CALLER__.context do\n nil ->\n quote do\n case unquote(term) do\n %_{} -> true\n _ -> false\n end\n end\n\n :match ->\n invalid_match!(:is_struct)\n\n :guard ->\n quote do\n is_map(unquote(term)) and :erlang.is_map_key(:__struct__, unquote(term)) and\n is_atom(:erlang.map_get(:__struct__, unquote(term)))\n end\n end\n end\n\n @doc \"\"\"\n Returns true if `term` is a struct of `name`; otherwise returns `false`.\n\n Allowed in guard tests.\n\n ## Examples\n\n iex> is_struct(URI.parse(\"\/\"), URI)\n true\n\n iex> is_struct(URI.parse(\"\/\"), Macro.Env)\n false\n\n \"\"\"\n @doc since: \"1.11.0\", guard: true\n defmacro is_struct(term, name) do\n case __CALLER__.context do\n nil ->\n quote do\n case unquote(name) do\n name when is_atom(name) ->\n case unquote(term) do\n %{__struct__: ^name} -> true\n _ -> false\n end\n\n _ ->\n raise ArgumentError\n end\n end\n\n :match ->\n invalid_match!(:is_struct)\n\n :guard ->\n quote do\n is_map(unquote(term)) and\n (is_atom(unquote(name)) or :fail) and\n :erlang.is_map_key(:__struct__, unquote(term)) and\n :erlang.map_get(:__struct__, unquote(term)) == unquote(name)\n end\n end\n end\n\n @doc \"\"\"\n Returns true if `term` is an exception; otherwise returns `false`.\n\n Allowed in guard tests.\n\n ## Examples\n\n iex> is_exception(%RuntimeError{})\n true\n\n iex> is_exception(%{})\n false\n\n \"\"\"\n @doc since: \"1.11.0\", guard: true\n defmacro is_exception(term) do\n case __CALLER__.context do\n nil ->\n quote do\n case unquote(term) do\n %_{__exception__: true} -> true\n _ -> false\n end\n end\n\n :match ->\n invalid_match!(:is_exception)\n\n :guard ->\n quote do\n is_map(unquote(term)) and :erlang.is_map_key(:__struct__, unquote(term)) and\n is_atom(:erlang.map_get(:__struct__, unquote(term))) and\n :erlang.is_map_key(:__exception__, unquote(term)) and\n :erlang.map_get(:__exception__, unquote(term)) == true\n end\n end\n end\n\n @doc \"\"\"\n Returns true if `term` is an exception of `name`; otherwise returns `false`.\n\n Allowed in guard tests.\n\n ## Examples\n\n iex> is_exception(%RuntimeError{}, RuntimeError)\n true\n\n iex> is_exception(%RuntimeError{}, Macro.Env)\n false\n\n \"\"\"\n @doc since: \"1.11.0\", guard: true\n defmacro is_exception(term, name) do\n case __CALLER__.context do\n nil ->\n quote do\n case unquote(name) do\n name when is_atom(name) ->\n case unquote(term) do\n %{__struct__: ^name, __exception__: true} -> true\n _ -> false\n end\n\n _ ->\n raise ArgumentError\n end\n end\n\n :match ->\n invalid_match!(:is_exception)\n\n :guard ->\n quote do\n is_map(unquote(term)) and\n (is_atom(unquote(name)) or :fail) and\n :erlang.is_map_key(:__struct__, unquote(term)) and\n :erlang.map_get(:__struct__, unquote(term)) == unquote(name) and\n :erlang.is_map_key(:__exception__, unquote(term)) and\n :erlang.map_get(:__exception__, unquote(term)) == true\n end\n end\n end\n\n @doc \"\"\"\n Pipes `value` into the given `fun`.\n\n In other words, it invokes `fun` with `value` as argument.\n This is most commonly used in pipelines, allowing you\n to pipe a value to a function outside of its first argument.\n\n ### Examples\n\n iex> 1 |> then(fn x -> x * 2 end)\n 2\n \"\"\"\n @doc since: \"1.12.0\"\n defmacro then(value, fun) do\n quote do\n unquote(fun).(unquote(value))\n end\n end\n\n @doc \"\"\"\n Gets a value from a nested structure.\n\n Uses the `Access` module to traverse the structures\n according to the given `keys`, unless the `key` is a\n function, which is detailed in a later section.\n\n ## Examples\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> get_in(users, [\"john\", :age])\n 27\n\n In case any of the keys returns `nil`, `nil` will be returned:\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> get_in(users, [\"unknown\", :age])\n nil\n\n Note that `get_in` exists mostly for convenience and parity with\n functionality found in `put_in` and `update_in`. Given Elixir\n provides pattern matching, it can often be more expressive for\n deep data traversal, for example:\n\n case users do\n %{\"unknown\" => %{age: age}} -> age\n _ -> default_value\n end\n\n ## Functions as keys\n\n If a key is a function, the function will be invoked passing three\n arguments:\n\n * the operation (`:get`)\n * the data to be accessed\n * a function to be invoked next\n\n This means `get_in\/2` can be extended to provide custom lookups.\n In the example below, we use a function to get all the maps inside\n a list:\n\n iex> users = [%{name: \"john\", age: 27}, %{name: \"meg\", age: 23}]\n iex> all = fn :get, data, next -> Enum.map(data, next) end\n iex> get_in(users, [all, :age])\n [27, 23]\n\n If the previous value before invoking the function is `nil`,\n the function *will* receive `nil` as a value and must handle it\n accordingly.\n\n The `Access` module ships with many convenience accessor functions,\n like the `all` anonymous function defined above. See `Access.all\/0`,\n `Access.key\/2`, and others as examples.\n\n ## Working with structs\n\n By default, structs do not implement the `Access` behaviour required\n by this function. Therefore, you can't do this:\n\n get_in(some_struct, [:some_key, :nested_key])\n\n The good news is that structs have predefined shape. Therefore,\n you can write instead:\n\n some_struct.some_key.nested_key\n\n If, by any chance, `some_key` can return nil, you can always\n fallback to pattern matching to provide nested struct handling:\n\n case some_struct do\n %{some_key: %{nested_key: value}} -> value\n %{} -> nil\n end\n\n \"\"\"\n @spec get_in(Access.t(), nonempty_list(term)) :: term\n def get_in(data, keys)\n\n def get_in(data, [h]) when is_function(h), do: h.(:get, data, & &1)\n def get_in(data, [h | t]) when is_function(h), do: h.(:get, data, &get_in(&1, t))\n\n def get_in(nil, [_]), do: nil\n def get_in(nil, [_ | t]), do: get_in(nil, t)\n\n def get_in(data, [h]), do: Access.get(data, h)\n def get_in(data, [h | t]), do: get_in(Access.get(data, h), t)\n\n @doc \"\"\"\n Puts a value in a nested structure.\n\n Uses the `Access` module to traverse the structures\n according to the given `keys`, unless the `key` is a\n function. If the key is a function, it will be invoked\n as specified in `get_and_update_in\/3`.\n\n ## Examples\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> put_in(users, [\"john\", :age], 28)\n %{\"john\" => %{age: 28}, \"meg\" => %{age: 23}}\n\n In case any of the entries in the middle returns `nil`,\n an error will be raised when trying to access it next.\n \"\"\"\n @spec put_in(Access.t(), nonempty_list(term), term) :: Access.t()\n def put_in(data, [_ | _] = keys, value) do\n elem(get_and_update_in(data, keys, fn _ -> {nil, value} end), 1)\n end\n\n @doc \"\"\"\n Updates a key in a nested structure.\n\n Uses the `Access` module to traverse the structures\n according to the given `keys`, unless the `key` is a\n function. If the key is a function, it will be invoked\n as specified in `get_and_update_in\/3`.\n\n `data` is a nested structure (that is, a map, keyword\n list, or struct that implements the `Access` behaviour).\n The `fun` argument receives the value of `key` (or `nil`\n if `key` is not present) and the result replaces the value\n in the structure.\n\n ## Examples\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> update_in(users, [\"john\", :age], &(&1 + 1))\n %{\"john\" => %{age: 28}, \"meg\" => %{age: 23}}\n\n In case any of the entries in the middle returns `nil`,\n an error will be raised when trying to access it next.\n \"\"\"\n @spec update_in(Access.t(), nonempty_list(term), (term -> term)) :: Access.t()\n def update_in(data, [_ | _] = keys, fun) when is_function(fun) do\n elem(get_and_update_in(data, keys, fn x -> {nil, fun.(x)} end), 1)\n end\n\n @doc \"\"\"\n Gets a value and updates a nested structure.\n\n `data` is a nested structure (that is, a map, keyword\n list, or struct that implements the `Access` behaviour).\n\n The `fun` argument receives the value of `key` (or `nil` if `key`\n is not present) and must return one of the following values:\n\n * a two-element tuple `{get_value, new_value}`. In this case,\n `get_value` is the retrieved value which can possibly be operated on before\n being returned. `new_value` is the new value to be stored under `key`.\n\n * `:pop`, which implies that the current value under `key`\n should be removed from the structure and returned.\n\n This function uses the `Access` module to traverse the structures\n according to the given `keys`, unless the `key` is a function,\n which is detailed in a later section.\n\n ## Examples\n\n This function is useful when there is a need to retrieve the current\n value (or something calculated in function of the current value) and\n update it at the same time. For example, it could be used to read the\n current age of a user while increasing it by one in one pass:\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> get_and_update_in(users, [\"john\", :age], &{&1, &1 + 1})\n {27, %{\"john\" => %{age: 28}, \"meg\" => %{age: 23}}}\n\n ## Functions as keys\n\n If a key is a function, the function will be invoked passing three\n arguments:\n\n * the operation (`:get_and_update`)\n * the data to be accessed\n * a function to be invoked next\n\n This means `get_and_update_in\/3` can be extended to provide custom\n lookups. The downside is that functions cannot be stored as keys\n in the accessed data structures.\n\n When one of the keys is a function, the function is invoked.\n In the example below, we use a function to get and increment all\n ages inside a list:\n\n iex> users = [%{name: \"john\", age: 27}, %{name: \"meg\", age: 23}]\n iex> all = fn :get_and_update, data, next ->\n ...> data |> Enum.map(next) |> Enum.unzip()\n ...> end\n iex> get_and_update_in(users, [all, :age], &{&1, &1 + 1})\n {[27, 23], [%{name: \"john\", age: 28}, %{name: \"meg\", age: 24}]}\n\n If the previous value before invoking the function is `nil`,\n the function *will* receive `nil` as a value and must handle it\n accordingly (be it by failing or providing a sane default).\n\n The `Access` module ships with many convenience accessor functions,\n like the `all` anonymous function defined above. See `Access.all\/0`,\n `Access.key\/2`, and others as examples.\n \"\"\"\n @spec get_and_update_in(\n structure :: Access.t(),\n keys,\n (term -> {get_value, update_value} | :pop)\n ) :: {get_value, structure :: Access.t()}\n when keys: nonempty_list(any),\n get_value: var,\n update_value: term\n def get_and_update_in(data, keys, fun)\n\n def get_and_update_in(data, [head], fun) when is_function(head, 3),\n do: head.(:get_and_update, data, fun)\n\n def get_and_update_in(data, [head | tail], fun) when is_function(head, 3),\n do: head.(:get_and_update, data, &get_and_update_in(&1, tail, fun))\n\n def get_and_update_in(data, [head], fun) when is_function(fun, 1),\n do: Access.get_and_update(data, head, fun)\n\n def get_and_update_in(data, [head | tail], fun) when is_function(fun, 1),\n do: Access.get_and_update(data, head, &get_and_update_in(&1, tail, fun))\n\n @doc \"\"\"\n Pops a key from the given nested structure.\n\n Uses the `Access` protocol to traverse the structures\n according to the given `keys`, unless the `key` is a\n function. If the key is a function, it will be invoked\n as specified in `get_and_update_in\/3`.\n\n ## Examples\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> pop_in(users, [\"john\", :age])\n {27, %{\"john\" => %{}, \"meg\" => %{age: 23}}}\n\n In case any entry returns `nil`, its key will be removed\n and the deletion will be considered a success.\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> pop_in(users, [\"jane\", :age])\n {nil, %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}}\n\n \"\"\"\n @spec pop_in(data, nonempty_list(Access.get_and_update_fun(term, data) | term)) :: {term, data}\n when data: Access.container()\n def pop_in(data, keys)\n\n def pop_in(nil, [key | _]) do\n raise ArgumentError, \"could not pop key #{inspect(key)} on a nil value\"\n end\n\n def pop_in(data, [_ | _] = keys) do\n pop_in_data(data, keys)\n end\n\n defp pop_in_data(nil, [_ | _]), do: :pop\n\n defp pop_in_data(data, [fun]) when is_function(fun),\n do: fun.(:get_and_update, data, fn _ -> :pop end)\n\n defp pop_in_data(data, [fun | tail]) when is_function(fun),\n do: fun.(:get_and_update, data, &pop_in_data(&1, tail))\n\n defp pop_in_data(data, [key]), do: Access.pop(data, key)\n\n defp pop_in_data(data, [key | tail]),\n do: Access.get_and_update(data, key, &pop_in_data(&1, tail))\n\n @doc \"\"\"\n Puts a value in a nested structure via the given `path`.\n\n This is similar to `put_in\/3`, except the path is extracted via\n a macro rather than passing a list. For example:\n\n put_in(opts[:foo][:bar], :baz)\n\n Is equivalent to:\n\n put_in(opts, [:foo, :bar], :baz)\n\n This also works with nested structs and the `struct.path.to.value` way to specify\n paths:\n\n put_in(struct.foo.bar, :baz)\n\n Note that in order for this macro to work, the complete path must always\n be visible by this macro. For more information about the supported path\n expressions, please check `get_and_update_in\/2` docs.\n\n ## Examples\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> put_in(users[\"john\"][:age], 28)\n %{\"john\" => %{age: 28}, \"meg\" => %{age: 23}}\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> put_in(users[\"john\"].age, 28)\n %{\"john\" => %{age: 28}, \"meg\" => %{age: 23}}\n\n \"\"\"\n defmacro put_in(path, value) do\n case unnest(path, [], true, \"put_in\/2\") do\n {[h | t], true} ->\n nest_update_in(h, t, quote(do: fn _ -> unquote(value) end))\n\n {[h | t], false} ->\n expr = nest_get_and_update_in(h, t, quote(do: fn _ -> {nil, unquote(value)} end))\n quote(do: :erlang.element(2, unquote(expr)))\n end\n end\n\n @doc \"\"\"\n Pops a key from the nested structure via the given `path`.\n\n This is similar to `pop_in\/2`, except the path is extracted via\n a macro rather than passing a list. For example:\n\n pop_in(opts[:foo][:bar])\n\n Is equivalent to:\n\n pop_in(opts, [:foo, :bar])\n\n Note that in order for this macro to work, the complete path must always\n be visible by this macro. For more information about the supported path\n expressions, please check `get_and_update_in\/2` docs.\n\n ## Examples\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> pop_in(users[\"john\"][:age])\n {27, %{\"john\" => %{}, \"meg\" => %{age: 23}}}\n\n iex> users = %{john: %{age: 27}, meg: %{age: 23}}\n iex> pop_in(users.john[:age])\n {27, %{john: %{}, meg: %{age: 23}}}\n\n In case any entry returns `nil`, its key will be removed\n and the deletion will be considered a success.\n \"\"\"\n defmacro pop_in(path) do\n {[h | t], _} = unnest(path, [], true, \"pop_in\/1\")\n nest_pop_in(:map, h, t)\n end\n\n @doc \"\"\"\n Updates a nested structure via the given `path`.\n\n This is similar to `update_in\/3`, except the path is extracted via\n a macro rather than passing a list. For example:\n\n update_in(opts[:foo][:bar], &(&1 + 1))\n\n Is equivalent to:\n\n update_in(opts, [:foo, :bar], &(&1 + 1))\n\n This also works with nested structs and the `struct.path.to.value` way to specify\n paths:\n\n update_in(struct.foo.bar, &(&1 + 1))\n\n Note that in order for this macro to work, the complete path must always\n be visible by this macro. For more information about the supported path\n expressions, please check `get_and_update_in\/2` docs.\n\n ## Examples\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> update_in(users[\"john\"][:age], &(&1 + 1))\n %{\"john\" => %{age: 28}, \"meg\" => %{age: 23}}\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> update_in(users[\"john\"].age, &(&1 + 1))\n %{\"john\" => %{age: 28}, \"meg\" => %{age: 23}}\n\n \"\"\"\n defmacro update_in(path, fun) do\n case unnest(path, [], true, \"update_in\/2\") do\n {[h | t], true} ->\n nest_update_in(h, t, fun)\n\n {[h | t], false} ->\n expr = nest_get_and_update_in(h, t, quote(do: fn x -> {nil, unquote(fun).(x)} end))\n quote(do: :erlang.element(2, unquote(expr)))\n end\n end\n\n @doc \"\"\"\n Gets a value and updates a nested data structure via the given `path`.\n\n This is similar to `get_and_update_in\/3`, except the path is extracted\n via a macro rather than passing a list. For example:\n\n get_and_update_in(opts[:foo][:bar], &{&1, &1 + 1})\n\n Is equivalent to:\n\n get_and_update_in(opts, [:foo, :bar], &{&1, &1 + 1})\n\n This also works with nested structs and the `struct.path.to.value` way to specify\n paths:\n\n get_and_update_in(struct.foo.bar, &{&1, &1 + 1})\n\n Note that in order for this macro to work, the complete path must always\n be visible by this macro. See the \"Paths\" section below.\n\n ## Examples\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> get_and_update_in(users[\"john\"].age, &{&1, &1 + 1})\n {27, %{\"john\" => %{age: 28}, \"meg\" => %{age: 23}}}\n\n ## Paths\n\n A path may start with a variable, local or remote call, and must be\n followed by one or more:\n\n * `foo[bar]` - accesses the key `bar` in `foo`; in case `foo` is nil,\n `nil` is returned\n\n * `foo.bar` - accesses a map\/struct field; in case the field is not\n present, an error is raised\n\n Here are some valid paths:\n\n users[\"john\"][:age]\n users[\"john\"].age\n User.all()[\"john\"].age\n all_users()[\"john\"].age\n\n Here are some invalid ones:\n\n # Does a remote call after the initial value\n users[\"john\"].do_something(arg1, arg2)\n\n # Does not access any key or field\n users\n\n \"\"\"\n defmacro get_and_update_in(path, fun) do\n {[h | t], _} = unnest(path, [], true, \"get_and_update_in\/2\")\n nest_get_and_update_in(h, t, fun)\n end\n\n defp nest_update_in([], fun), do: fun\n\n defp nest_update_in(list, fun) do\n quote do\n fn x -> unquote(nest_update_in(quote(do: x), list, fun)) end\n end\n end\n\n defp nest_update_in(h, [{:map, key} | t], fun) do\n quote do\n Map.update!(unquote(h), unquote(key), unquote(nest_update_in(t, fun)))\n end\n end\n\n defp nest_get_and_update_in([], fun), do: fun\n\n defp nest_get_and_update_in(list, fun) do\n quote do\n fn x -> unquote(nest_get_and_update_in(quote(do: x), list, fun)) end\n end\n end\n\n defp nest_get_and_update_in(h, [{:access, key} | t], fun) do\n quote do\n Access.get_and_update(unquote(h), unquote(key), unquote(nest_get_and_update_in(t, fun)))\n end\n end\n\n defp nest_get_and_update_in(h, [{:map, key} | t], fun) do\n quote do\n Map.get_and_update!(unquote(h), unquote(key), unquote(nest_get_and_update_in(t, fun)))\n end\n end\n\n defp nest_pop_in(kind, list) do\n quote do\n fn x -> unquote(nest_pop_in(kind, quote(do: x), list)) end\n end\n end\n\n defp nest_pop_in(:map, h, [{:access, key}]) do\n quote do\n case unquote(h) do\n nil -> {nil, nil}\n h -> Access.pop(h, unquote(key))\n end\n end\n end\n\n defp nest_pop_in(_, _, [{:map, key}]) do\n raise ArgumentError,\n \"cannot use pop_in when the last segment is a map\/struct field. \" <>\n \"This would effectively remove the field #{inspect(key)} from the map\/struct\"\n end\n\n defp nest_pop_in(_, h, [{:map, key} | t]) do\n quote do\n Map.get_and_update!(unquote(h), unquote(key), unquote(nest_pop_in(:map, t)))\n end\n end\n\n defp nest_pop_in(_, h, [{:access, key}]) do\n quote do\n case unquote(h) do\n nil -> :pop\n h -> Access.pop(h, unquote(key))\n end\n end\n end\n\n defp nest_pop_in(_, h, [{:access, key} | t]) do\n quote do\n Access.get_and_update(unquote(h), unquote(key), unquote(nest_pop_in(:access, t)))\n end\n end\n\n defp unnest({{:., _, [Access, :get]}, _, [expr, key]}, acc, _all_map?, kind) do\n unnest(expr, [{:access, key} | acc], false, kind)\n end\n\n defp unnest({{:., _, [expr, key]}, _, []}, acc, all_map?, kind)\n when is_tuple(expr) and :erlang.element(1, expr) != :__aliases__ and\n :erlang.element(1, expr) != :__MODULE__ do\n unnest(expr, [{:map, key} | acc], all_map?, kind)\n end\n\n defp unnest(other, [], _all_map?, kind) do\n raise ArgumentError,\n \"expected expression given to #{kind} to access at least one element, \" <>\n \"got: #{Macro.to_string(other)}\"\n end\n\n defp unnest(other, acc, all_map?, kind) do\n case proper_start?(other) do\n true ->\n {[other | acc], all_map?}\n\n false ->\n raise ArgumentError,\n \"expression given to #{kind} must start with a variable, local or remote call \" <>\n \"and be followed by an element access, got: #{Macro.to_string(other)}\"\n end\n end\n\n defp proper_start?({{:., _, [expr, _]}, _, _args})\n when is_atom(expr)\n when :erlang.element(1, expr) == :__aliases__\n when :erlang.element(1, expr) == :__MODULE__,\n do: true\n\n defp proper_start?({atom, _, _args})\n when is_atom(atom),\n do: true\n\n defp proper_start?(other), do: not is_tuple(other)\n\n @doc \"\"\"\n Converts the argument to a string according to the\n `String.Chars` protocol.\n\n This is the function invoked when there is string interpolation.\n\n ## Examples\n\n iex> to_string(:foo)\n \"foo\"\n\n \"\"\"\n defmacro to_string(term) do\n quote(do: :\"Elixir.String.Chars\".to_string(unquote(term)))\n end\n\n @doc \"\"\"\n Converts the given term to a charlist according to the `List.Chars` protocol.\n\n ## Examples\n\n iex> to_charlist(:foo)\n 'foo'\n\n \"\"\"\n defmacro to_charlist(term) do\n quote(do: List.Chars.to_charlist(unquote(term)))\n end\n\n @doc \"\"\"\n Returns `true` if `term` is `nil`, `false` otherwise.\n\n Allowed in guard clauses.\n\n ## Examples\n\n iex> is_nil(1)\n false\n\n iex> is_nil(nil)\n true\n\n \"\"\"\n @doc guard: true\n defmacro is_nil(term) do\n quote(do: unquote(term) == nil)\n end\n\n @doc \"\"\"\n A convenience macro that checks if the right side (an expression) matches the\n left side (a pattern).\n\n ## Examples\n\n iex> match?(1, 1)\n true\n\n iex> match?({1, _}, {1, 2})\n true\n\n iex> map = %{a: 1, b: 2}\n iex> match?(%{a: _}, map)\n true\n\n iex> a = 1\n iex> match?(^a, 1)\n true\n\n `match?\/2` is very useful when filtering or finding a value in an enumerable:\n\n iex> list = [a: 1, b: 2, a: 3]\n iex> Enum.filter(list, &match?({:a, _}, &1))\n [a: 1, a: 3]\n\n Guard clauses can also be given to the match:\n\n iex> list = [a: 1, b: 2, a: 3]\n iex> Enum.filter(list, &match?({:a, x} when x < 2, &1))\n [a: 1]\n\n However, variables assigned in the match will not be available\n outside of the function call (unlike regular pattern matching with the `=`\n operator):\n\n iex> match?(_x, 1)\n true\n iex> binding()\n []\n\n \"\"\"\n defmacro match?(pattern, expr) do\n success =\n quote do\n unquote(pattern) -> true\n end\n\n failure =\n quote generated: true do\n _ -> false\n end\n\n {:case, [], [expr, [do: success ++ failure]]}\n end\n\n @doc \"\"\"\n Module attribute unary operator. Reads and writes attributes in the current module.\n\n The canonical example for attributes is annotating that a module\n implements an OTP behaviour, such as `GenServer`:\n\n defmodule MyServer do\n @behaviour GenServer\n # ... callbacks ...\n end\n\n By default Elixir supports all the module attributes supported by Erlang, but\n custom attributes can be used as well:\n\n defmodule MyServer do\n @my_data 13\n IO.inspect(@my_data)\n #=> 13\n end\n\n Unlike Erlang, such attributes are not stored in the module by default since\n it is common in Elixir to use custom attributes to store temporary data that\n will be available at compile-time. Custom attributes may be configured to\n behave closer to Erlang by using `Module.register_attribute\/3`.\n\n Finally, note that attributes can also be read inside functions:\n\n defmodule MyServer do\n @my_data 11\n def first_data, do: @my_data\n @my_data 13\n def second_data, do: @my_data\n end\n\n MyServer.first_data()\n #=> 11\n\n MyServer.second_data()\n #=> 13\n\n It is important to note that reading an attribute takes a snapshot of\n its current value. In other words, the value is read at compilation\n time and not at runtime. Check the `Module` module for other functions\n to manipulate module attributes.\n \"\"\"\n defmacro @expr\n\n defmacro @{:__aliases__, _meta, _args} do\n raise ArgumentError, \"module attributes set via @ cannot start with an uppercase letter\"\n end\n\n defmacro @{name, meta, args} do\n assert_module_scope(__CALLER__, :@, 1)\n function? = __CALLER__.function != nil\n\n cond do\n # Check for Macro as it is compiled later than Kernel\n not bootstrapped?(Macro) ->\n nil\n\n not function? and __CALLER__.context == :match ->\n raise ArgumentError,\n \"\"\"\n invalid write attribute syntax. If you want to define an attribute, don't do this:\n\n @foo = :value\n\n Instead, do this:\n\n @foo :value\n \"\"\"\n\n # Typespecs attributes are currently special cased by the compiler\n is_list(args) and typespec?(name) ->\n case bootstrapped?(Kernel.Typespec) do\n false ->\n :ok\n\n true ->\n pos = :elixir_locals.cache_env(__CALLER__)\n %{line: line, file: file, module: module} = __CALLER__\n\n quote do\n Kernel.Typespec.deftypespec(\n unquote(name),\n unquote(Macro.escape(hd(args), unquote: true)),\n unquote(line),\n unquote(file),\n unquote(module),\n unquote(pos)\n )\n end\n end\n\n true ->\n do_at(args, meta, name, function?, __CALLER__)\n end\n end\n\n # @attribute(value)\n defp do_at([arg], meta, name, function?, env) do\n line =\n case :lists.keymember(:context, 1, meta) do\n true -> nil\n false -> env.line\n end\n\n cond do\n function? ->\n raise ArgumentError, \"cannot set attribute @#{name} inside function\/macro\"\n\n name == :behavior ->\n warn_message = \"@behavior attribute is not supported, please use @behaviour instead\"\n IO.warn(warn_message, Macro.Env.stacktrace(env))\n\n :lists.member(name, [:moduledoc, :typedoc, :doc]) ->\n arg = {env.line, arg}\n\n quote do\n Module.__put_attribute__(__MODULE__, unquote(name), unquote(arg), unquote(line))\n end\n\n true ->\n quote do\n Module.__put_attribute__(__MODULE__, unquote(name), unquote(arg), unquote(line))\n end\n end\n end\n\n # @attribute()\n defp do_at([], meta, name, function?, env) do\n IO.warn(\n \"the @#{name}() notation (with parenthesis) is deprecated, please use @#{name} (without parenthesis) instead\",\n Macro.Env.stacktrace(env)\n )\n\n do_at(nil, meta, name, function?, env)\n end\n\n # @attribute\n defp do_at(args, _meta, name, function?, env) when is_atom(args) do\n line = env.line\n doc_attr? = :lists.member(name, [:moduledoc, :typedoc, :doc])\n\n case function? do\n true ->\n value =\n case Module.__get_attribute__(env.module, name, line) do\n {_, doc} when doc_attr? -> doc\n other -> other\n end\n\n try do\n :elixir_quote.escape(value, :default, false)\n rescue\n ex in [ArgumentError] ->\n raise ArgumentError,\n \"cannot inject attribute @#{name} into function\/macro because \" <>\n Exception.message(ex)\n end\n\n false when doc_attr? ->\n quote do\n case Module.__get_attribute__(__MODULE__, unquote(name), unquote(line)) do\n {_, doc} -> doc\n other -> other\n end\n end\n\n false ->\n quote do\n Module.__get_attribute__(__MODULE__, unquote(name), unquote(line))\n end\n end\n end\n\n # Error cases\n defp do_at([{call, meta, ctx_or_args}, [{:do, _} | _] = kw], _meta, name, _function?, _env) do\n args =\n case is_atom(ctx_or_args) do\n true -> []\n false -> ctx_or_args\n end\n\n code = \"\\n@#{name} (#{Macro.to_string({call, meta, args ++ [kw]})})\"\n\n raise ArgumentError, \"\"\"\n expected 0 or 1 argument for @#{name}, got 2.\n\n It seems you are trying to use the do-syntax with @module attributes \\\n but the do-block is binding to the attribute name. You probably want \\\n to wrap the argument value in parentheses, like this:\n #{String.replace(code, \"\\n\", \"\\n \")}\n \"\"\"\n end\n\n defp do_at(args, _meta, name, _function?, _env) do\n raise ArgumentError, \"expected 0 or 1 argument for @#{name}, got: #{length(args)}\"\n end\n\n defp typespec?(:type), do: true\n defp typespec?(:typep), do: true\n defp typespec?(:opaque), do: true\n defp typespec?(:spec), do: true\n defp typespec?(:callback), do: true\n defp typespec?(:macrocallback), do: true\n defp typespec?(_), do: false\n\n @doc \"\"\"\n Returns the binding for the given context as a keyword list.\n\n In the returned result, keys are variable names and values are the\n corresponding variable values.\n\n If the given `context` is `nil` (by default it is), the binding for the\n current context is returned.\n\n ## Examples\n\n iex> x = 1\n iex> binding()\n [x: 1]\n iex> x = 2\n iex> binding()\n [x: 2]\n\n iex> binding(:foo)\n []\n iex> var!(x, :foo) = 1\n 1\n iex> binding(:foo)\n [x: 1]\n\n \"\"\"\n defmacro binding(context \\\\ nil) do\n in_match? = Macro.Env.in_match?(__CALLER__)\n\n bindings =\n for {v, c} <- Macro.Env.vars(__CALLER__), c == context do\n {v, wrap_binding(in_match?, {v, [generated: true], c})}\n end\n\n :lists.sort(bindings)\n end\n\n defp wrap_binding(true, var) do\n quote(do: ^unquote(var))\n end\n\n defp wrap_binding(_, var) do\n var\n end\n\n @doc \"\"\"\n Provides an `if\/2` macro.\n\n This macro expects the first argument to be a condition and the second\n argument to be a keyword list.\n\n ## One-liner examples\n\n if(foo, do: bar)\n\n In the example above, `bar` will be returned if `foo` evaluates to\n a truthy value (neither `false` nor `nil`). Otherwise, `nil` will be\n returned.\n\n An `else` option can be given to specify the opposite:\n\n if(foo, do: bar, else: baz)\n\n ## Blocks examples\n\n It's also possible to pass a block to the `if\/2` macro. The first\n example above would be translated to:\n\n if foo do\n bar\n end\n\n Note that `do\/end` become delimiters. The second example would\n translate to:\n\n if foo do\n bar\n else\n baz\n end\n\n In order to compare more than two clauses, the `cond\/1` macro has to be used.\n \"\"\"\n defmacro if(condition, clauses) do\n build_if(condition, clauses)\n end\n\n defp build_if(condition, do: do_clause) do\n build_if(condition, do: do_clause, else: nil)\n end\n\n defp build_if(condition, do: do_clause, else: else_clause) do\n optimize_boolean(\n quote do\n case unquote(condition) do\n x when :\"Elixir.Kernel\".in(x, [false, nil]) -> unquote(else_clause)\n _ -> unquote(do_clause)\n end\n end\n )\n end\n\n defp build_if(_condition, _arguments) do\n raise ArgumentError,\n \"invalid or duplicate keys for if, only \\\"do\\\" and an optional \\\"else\\\" are permitted\"\n end\n\n @doc \"\"\"\n Provides an `unless` macro.\n\n This macro evaluates and returns the `do` block passed in as the second\n argument if `condition` evaluates to a falsy value (`false` or `nil`).\n Otherwise, it returns the value of the `else` block if present or `nil` if not.\n\n See also `if\/2`.\n\n ## Examples\n\n iex> unless(Enum.empty?([]), do: \"Hello\")\n nil\n\n iex> unless(Enum.empty?([1, 2, 3]), do: \"Hello\")\n \"Hello\"\n\n iex> unless Enum.sum([2, 2]) == 5 do\n ...> \"Math still works\"\n ...> else\n ...> \"Math is broken\"\n ...> end\n \"Math still works\"\n\n \"\"\"\n defmacro unless(condition, clauses) do\n build_unless(condition, clauses)\n end\n\n defp build_unless(condition, do: do_clause) do\n build_unless(condition, do: do_clause, else: nil)\n end\n\n defp build_unless(condition, do: do_clause, else: else_clause) do\n quote do\n if(unquote(condition), do: unquote(else_clause), else: unquote(do_clause))\n end\n end\n\n defp build_unless(_condition, _arguments) do\n raise ArgumentError,\n \"invalid or duplicate keys for unless, \" <>\n \"only \\\"do\\\" and an optional \\\"else\\\" are permitted\"\n end\n\n @doc \"\"\"\n Destructures two lists, assigning each term in the\n right one to the matching term in the left one.\n\n Unlike pattern matching via `=`, if the sizes of the left\n and right lists don't match, destructuring simply stops\n instead of raising an error.\n\n ## Examples\n\n iex> destructure([x, y, z], [1, 2, 3, 4, 5])\n iex> {x, y, z}\n {1, 2, 3}\n\n In the example above, even though the right list has more entries than the\n left one, destructuring works fine. If the right list is smaller, the\n remaining elements are simply set to `nil`:\n\n iex> destructure([x, y, z], [1])\n iex> {x, y, z}\n {1, nil, nil}\n\n The left-hand side supports any expression you would use\n on the left-hand side of a match:\n\n x = 1\n destructure([^x, y, z], [1, 2, 3])\n\n The example above will only work if `x` matches the first value in the right\n list. Otherwise, it will raise a `MatchError` (like the `=` operator would\n do).\n \"\"\"\n defmacro destructure(left, right) when is_list(left) do\n quote do\n unquote(left) = Kernel.Utils.destructure(unquote(right), unquote(length(left)))\n end\n end\n\n @doc \"\"\"\n Range creation operator. Returns a range with the specified `first` and `last` integers.\n\n If last is larger than first, the range will be increasing from\n first to last. If first is larger than last, the range will be\n decreasing from first to last. If first is equal to last, the range\n will contain one element, which is the number itself.\n\n ## Examples\n\n iex> 0 in 1..3\n false\n\n iex> 1 in 1..3\n true\n\n iex> 2 in 1..3\n true\n\n iex> 3 in 1..3\n true\n\n \"\"\"\n defmacro first..last do\n case bootstrapped?(Macro) do\n true ->\n first = Macro.expand(first, __CALLER__)\n last = Macro.expand(last, __CALLER__)\n range(__CALLER__.context, first, last)\n\n false ->\n range(__CALLER__.context, first, last)\n end\n end\n\n defp range(_context, first, last) when is_integer(first) and is_integer(last) do\n {:%{}, [], [__struct__: Elixir.Range, first: first, last: last]}\n end\n\n defp range(_context, first, last)\n when is_float(first) or is_float(last) or is_atom(first) or is_atom(last) or\n is_binary(first) or is_binary(last) or is_list(first) or is_list(last) do\n raise ArgumentError,\n \"ranges (first..last) expect both sides to be integers, \" <>\n \"got: #{Macro.to_string({:.., [], [first, last]})}\"\n end\n\n defp range(nil, first, last) do\n quote(do: Elixir.Range.new(unquote(first), unquote(last)))\n end\n\n defp range(_, first, last) do\n {:%{}, [], [__struct__: Elixir.Range, first: first, last: last]}\n end\n\n @doc \"\"\"\n Boolean \"and\" operator.\n\n Provides a short-circuit operator that evaluates and returns\n the second expression only if the first one evaluates to a truthy value\n (neither `false` nor `nil`). Returns the first expression\n otherwise.\n\n Not allowed in guard clauses.\n\n ## Examples\n\n iex> Enum.empty?([]) && Enum.empty?([])\n true\n\n iex> List.first([]) && true\n nil\n\n iex> Enum.empty?([]) && List.first([1])\n 1\n\n iex> false && throw(:bad)\n false\n\n Note that, unlike `and\/2`, this operator accepts any expression\n as the first argument, not only booleans.\n \"\"\"\n defmacro left && right do\n assert_no_match_or_guard_scope(__CALLER__.context, \"&&\")\n\n quote do\n case unquote(left) do\n x when :\"Elixir.Kernel\".in(x, [false, nil]) ->\n x\n\n _ ->\n unquote(right)\n end\n end\n end\n\n @doc \"\"\"\n Boolean \"or\" operator.\n\n Provides a short-circuit operator that evaluates and returns the second\n expression only if the first one does not evaluate to a truthy value (that is,\n it is either `nil` or `false`). Returns the first expression otherwise.\n\n Not allowed in guard clauses.\n\n ## Examples\n\n iex> Enum.empty?([1]) || Enum.empty?([1])\n false\n\n iex> List.first([]) || true\n true\n\n iex> Enum.empty?([1]) || 1\n 1\n\n iex> Enum.empty?([]) || throw(:bad)\n true\n\n Note that, unlike `or\/2`, this operator accepts any expression\n as the first argument, not only booleans.\n \"\"\"\n defmacro left || right do\n assert_no_match_or_guard_scope(__CALLER__.context, \"||\")\n\n quote do\n case unquote(left) do\n x when :\"Elixir.Kernel\".in(x, [false, nil]) ->\n unquote(right)\n\n x ->\n x\n end\n end\n end\n\n @doc \"\"\"\n Pipe operator.\n\n This operator introduces the expression on the left-hand side as\n the first argument to the function call on the right-hand side.\n\n ## Examples\n\n iex> [1, [2], 3] |> List.flatten()\n [1, 2, 3]\n\n The example above is the same as calling `List.flatten([1, [2], 3])`.\n\n The `|>` operator is mostly useful when there is a desire to execute a series\n of operations resembling a pipeline:\n\n iex> [1, [2], 3] |> List.flatten() |> Enum.map(fn x -> x * 2 end)\n [2, 4, 6]\n\n In the example above, the list `[1, [2], 3]` is passed as the first argument\n to the `List.flatten\/1` function, then the flattened list is passed as the\n first argument to the `Enum.map\/2` function which doubles each element of the\n list.\n\n In other words, the expression above simply translates to:\n\n Enum.map(List.flatten([1, [2], 3]), fn x -> x * 2 end)\n\n ## Pitfalls\n\n There are two common pitfalls when using the pipe operator.\n\n The first one is related to operator precedence. For example,\n the following expression:\n\n String.graphemes \"Hello\" |> Enum.reverse\n\n Translates to:\n\n String.graphemes(\"Hello\" |> Enum.reverse())\n\n which results in an error as the `Enumerable` protocol is not defined\n for binaries. Adding explicit parentheses resolves the ambiguity:\n\n String.graphemes(\"Hello\") |> Enum.reverse()\n\n Or, even better:\n\n \"Hello\" |> String.graphemes() |> Enum.reverse()\n\n The second limitation is that Elixir always pipes to a function\n call. Therefore, to pipe into an anonymous function, you need to\n invoke it:\n\n some_fun = &Regex.replace(~r\/l\/, &1, \"L\")\n \"Hello\" |> some_fun.()\n\n Alternatively, you can use `then\/2` for the same effect:\n\n some_fun = &Regex.replace(~r\/l\/, &1, \"L\")\n \"Hello\" |> then(some_fun)\n\n `then\/2` is most commonly used when you want to pipe to a function\n but the value is expected outside of the first argument, such as\n above. By replacing `some_fun` by its value, we get:\n\n \"Hello\" |> then(&Regex.replace(~r\/l\/,&1, \"L\"))\n\n \"\"\"\n defmacro left |> right do\n [{h, _} | t] = Macro.unpipe({:|>, [], [left, right]})\n\n fun = fn {x, pos}, acc ->\n Macro.pipe(acc, x, pos)\n end\n\n :lists.foldl(fun, h, t)\n end\n\n @doc \"\"\"\n Returns `true` if `module` is loaded and contains a\n public `function` with the given `arity`, otherwise `false`.\n\n Note that this function does not load the module in case\n it is not loaded. Check `Code.ensure_loaded\/1` for more\n information.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> function_exported?(Enum, :map, 2)\n true\n\n iex> function_exported?(Enum, :map, 10)\n false\n\n iex> function_exported?(List, :to_string, 1)\n true\n \"\"\"\n @spec function_exported?(module, atom, arity) :: boolean\n def function_exported?(module, function, arity) do\n :erlang.function_exported(module, function, arity)\n end\n\n @doc \"\"\"\n Returns `true` if `module` is loaded and contains a\n public `macro` with the given `arity`, otherwise `false`.\n\n Note that this function does not load the module in case\n it is not loaded. Check `Code.ensure_loaded\/1` for more\n information.\n\n If `module` is an Erlang module (as opposed to an Elixir module), this\n function always returns `false`.\n\n ## Examples\n\n iex> macro_exported?(Kernel, :use, 2)\n true\n\n iex> macro_exported?(:erlang, :abs, 1)\n false\n\n \"\"\"\n @spec macro_exported?(module, atom, arity) :: boolean\n def macro_exported?(module, macro, arity)\n when is_atom(module) and is_atom(macro) and is_integer(arity) and\n (arity >= 0 and arity <= 255) do\n function_exported?(module, :__info__, 1) and\n :lists.member({macro, arity}, module.__info__(:macros))\n end\n\n @doc \"\"\"\n Membership operator. Checks if the element on the left-hand side is a member of the\n collection on the right-hand side.\n\n ## Examples\n\n iex> x = 1\n iex> x in [1, 2, 3]\n true\n\n This operator (which is a macro) simply translates to a call to\n `Enum.member?\/2`. The example above would translate to:\n\n Enum.member?([1, 2, 3], x)\n\n Elixir also supports `left not in right`, which evaluates to\n `not(left in right)`:\n\n iex> x = 1\n iex> x not in [1, 2, 3]\n false\n\n ## Guards\n\n The `in\/2` operator (as well as `not in`) can be used in guard clauses as\n long as the right-hand side is a range or a list. In such cases, Elixir will\n expand the operator to a valid guard expression. For example:\n\n when x in [1, 2, 3]\n\n translates to:\n\n when x === 1 or x === 2 or x === 3\n\n When using ranges:\n\n when x in 1..3\n\n translates to:\n\n when is_integer(x) and x >= 1 and x <= 3\n\n Note that only integers can be considered inside a range by `in`.\n\n ### AST considerations\n\n `left not in right` is parsed by the compiler into the AST:\n\n {:not, _, [{:in, _, [left, right]}]}\n\n This is the same AST as `not(left in right)`.\n\n Additionally, `Macro.to_string\/2` will translate all occurrences of\n this AST to `left not in right`.\n \"\"\"\n @doc guard: true\n defmacro left in right do\n in_body? = __CALLER__.context == nil\n\n expand =\n case bootstrapped?(Macro) do\n true -> &Macro.expand(&1, __CALLER__)\n false -> & &1\n end\n\n case expand.(right) do\n [] when not in_body? ->\n false\n\n [] ->\n quote do\n _ = unquote(left)\n false\n end\n\n [head | tail] = list when not in_body? ->\n in_list(left, head, tail, expand, list, in_body?)\n\n [_ | _] = list when in_body? ->\n case ensure_evaled(list, {0, []}, expand) do\n {[head | tail], {_, []}} ->\n in_var(in_body?, left, &in_list(&1, head, tail, expand, list, in_body?))\n\n {[head | tail], {_, vars_values}} ->\n {vars, values} = :lists.unzip(:lists.reverse(vars_values))\n is_in_list = &in_list(&1, head, tail, expand, list, in_body?)\n\n quote do\n {unquote_splicing(vars)} = {unquote_splicing(values)}\n unquote(in_var(in_body?, left, is_in_list))\n end\n end\n\n {:%{}, _meta, [__struct__: Elixir.Range, first: first, last: last]} ->\n in_var(in_body?, left, &in_range(&1, expand.(first), expand.(last)))\n\n right when in_body? ->\n quote(do: Elixir.Enum.member?(unquote(right), unquote(left)))\n\n %{__struct__: Elixir.Range, first: _, last: _} ->\n raise ArgumentError, \"non-literal range in guard should be escaped with Macro.escape\/2\"\n\n right ->\n raise_on_invalid_args_in_2(right)\n end\n end\n\n defp raise_on_invalid_args_in_2(right) do\n raise ArgumentError, <<\n \"invalid right argument for operator \\\"in\\\", it expects a compile-time proper list \",\n \"or compile-time range on the right side when used in guard expressions, got: \",\n Macro.to_string(right)::binary\n >>\n end\n\n defp in_var(false, ast, fun), do: fun.(ast)\n\n defp in_var(true, {atom, _, context} = var, fun) when is_atom(atom) and is_atom(context),\n do: fun.(var)\n\n defp in_var(true, ast, fun) do\n quote do\n var = unquote(ast)\n unquote(fun.(quote(do: var)))\n end\n end\n\n # Called as ensure_evaled(list, {0, []}). Note acc is reversed.\n defp ensure_evaled(list, acc, expand) do\n fun = fn\n {:|, meta, [head, tail]}, acc ->\n {head, acc} = ensure_evaled_element(head, acc)\n {tail, acc} = ensure_evaled_tail(expand.(tail), acc, expand)\n {{:|, meta, [head, tail]}, acc}\n\n elem, acc ->\n ensure_evaled_element(elem, acc)\n end\n\n :lists.mapfoldl(fun, acc, list)\n end\n\n defp ensure_evaled_element(elem, acc)\n when is_number(elem) or is_atom(elem) or is_binary(elem) do\n {elem, acc}\n end\n\n defp ensure_evaled_element(elem, acc) do\n ensure_evaled_var(elem, acc)\n end\n\n defp ensure_evaled_tail(elem, acc, expand) when is_list(elem) do\n ensure_evaled(elem, acc, expand)\n end\n\n defp ensure_evaled_tail(elem, acc, _expand) do\n ensure_evaled_var(elem, acc)\n end\n\n defp ensure_evaled_var(elem, {index, ast}) do\n var = {String.to_atom(\"arg\" <> Integer.to_string(index + 1)), [], __MODULE__}\n {var, {index + 1, [{var, elem} | ast]}}\n end\n\n defp in_range(left, first, last) do\n case is_integer(first) and is_integer(last) do\n true ->\n in_range_literal(left, first, last)\n\n false ->\n quote do\n :erlang.is_integer(unquote(left)) and :erlang.is_integer(unquote(first)) and\n :erlang.is_integer(unquote(last)) and\n ((:erlang.\"=<\"(unquote(first), unquote(last)) and\n unquote(increasing_compare(left, first, last))) or\n (:erlang.<(unquote(last), unquote(first)) and\n unquote(decreasing_compare(left, first, last))))\n end\n end\n end\n\n defp in_range_literal(left, first, first) do\n quote do\n :erlang.\"=:=\"(unquote(left), unquote(first))\n end\n end\n\n defp in_range_literal(left, first, last) when first < last do\n quote do\n :erlang.andalso(\n :erlang.is_integer(unquote(left)),\n unquote(increasing_compare(left, first, last))\n )\n end\n end\n\n defp in_range_literal(left, first, last) do\n quote do\n :erlang.andalso(\n :erlang.is_integer(unquote(left)),\n unquote(decreasing_compare(left, first, last))\n )\n end\n end\n\n defp in_list(left, head, tail, expand, right, in_body?) do\n [head | tail] = :lists.map(&comp(left, &1, expand, right, in_body?), [head | tail])\n :lists.foldl("e(do: :erlang.orelse(unquote(&2), unquote(&1))), head, tail)\n end\n\n defp comp(left, {:|, _, [head, tail]}, expand, right, in_body?) do\n case expand.(tail) do\n [] ->\n quote(do: :erlang.\"=:=\"(unquote(left), unquote(head)))\n\n [tail_head | tail] ->\n quote do\n :erlang.orelse(\n :erlang.\"=:=\"(unquote(left), unquote(head)),\n unquote(in_list(left, tail_head, tail, expand, right, in_body?))\n )\n end\n\n tail when in_body? ->\n quote do\n :erlang.orelse(\n :erlang.\"=:=\"(unquote(left), unquote(head)),\n :lists.member(unquote(left), unquote(tail))\n )\n end\n\n _ ->\n raise_on_invalid_args_in_2(right)\n end\n end\n\n defp comp(left, right, _expand, _right, _in_body?) do\n quote(do: :erlang.\"=:=\"(unquote(left), unquote(right)))\n end\n\n defp increasing_compare(var, first, last) do\n quote do\n :erlang.andalso(\n :erlang.>=(unquote(var), unquote(first)),\n :erlang.\"=<\"(unquote(var), unquote(last))\n )\n end\n end\n\n defp decreasing_compare(var, first, last) do\n quote do\n :erlang.andalso(\n :erlang.\"=<\"(unquote(var), unquote(first)),\n :erlang.>=(unquote(var), unquote(last))\n )\n end\n end\n\n @doc \"\"\"\n Marks that the given variable should not be hygienized.\n\n This macro expects a variable and it is typically invoked\n inside `Kernel.SpecialForms.quote\/2` to mark that a variable\n should not be hygienized. See `Kernel.SpecialForms.quote\/2`\n for more information.\n\n ## Examples\n\n iex> Kernel.var!(example) = 1\n 1\n iex> Kernel.var!(example)\n 1\n\n \"\"\"\n defmacro var!(var, context \\\\ nil)\n\n defmacro var!({name, meta, atom}, context) when is_atom(name) and is_atom(atom) do\n # Remove counter and force them to be vars\n meta = :lists.keydelete(:counter, 1, meta)\n meta = :lists.keystore(:var, 1, meta, {:var, true})\n\n case Macro.expand(context, __CALLER__) do\n context when is_atom(context) ->\n {name, meta, context}\n\n other ->\n raise ArgumentError,\n \"expected var! context to expand to an atom, got: #{Macro.to_string(other)}\"\n end\n end\n\n defmacro var!(other, _context) do\n raise ArgumentError, \"expected a variable to be given to var!, got: #{Macro.to_string(other)}\"\n end\n\n @doc \"\"\"\n When used inside quoting, marks that the given alias should not\n be hygienized. This means the alias will be expanded when\n the macro is expanded.\n\n Check `Kernel.SpecialForms.quote\/2` for more information.\n \"\"\"\n defmacro alias!(alias) when is_atom(alias) do\n alias\n end\n\n defmacro alias!({:__aliases__, meta, args}) do\n # Simply remove the alias metadata from the node\n # so it does not affect expansion.\n {:__aliases__, :lists.keydelete(:alias, 1, meta), args}\n end\n\n ## Definitions implemented in Elixir\n\n @doc ~S\"\"\"\n Defines a module given by name with the given contents.\n\n This macro defines a module with the given `alias` as its name and with the\n given contents. It returns a tuple with four elements:\n\n * `:module`\n * the module name\n * the binary contents of the module\n * the result of evaluating the contents block\n\n ## Examples\n\n defmodule Number do\n def one, do: 1\n def two, do: 2\n end\n #=> {:module, Number, <<70, 79, 82, ...>>, {:two, 0}}\n\n Number.one()\n #=> 1\n\n Number.two()\n #=> 2\n\n ## Nesting\n\n Nesting a module inside another module affects the name of the nested module:\n\n defmodule Foo do\n defmodule Bar do\n end\n end\n\n In the example above, two modules - `Foo` and `Foo.Bar` - are created.\n When nesting, Elixir automatically creates an alias to the inner module,\n allowing the second module `Foo.Bar` to be accessed as `Bar` in the same\n lexical scope where it's defined (the `Foo` module). This only happens\n if the nested module is defined via an alias.\n\n If the `Foo.Bar` module is moved somewhere else, the references to `Bar` in\n the `Foo` module need to be updated to the fully-qualified name (`Foo.Bar`) or\n an alias has to be explicitly set in the `Foo` module with the help of\n `Kernel.SpecialForms.alias\/2`.\n\n defmodule Foo.Bar do\n # code\n end\n\n defmodule Foo do\n alias Foo.Bar\n # code here can refer to \"Foo.Bar\" as just \"Bar\"\n end\n\n ## Dynamic names\n\n Elixir module names can be dynamically generated. This is very\n useful when working with macros. For instance, one could write:\n\n defmodule String.to_atom(\"Foo#{1}\") do\n # contents ...\n end\n\n Elixir will accept any module name as long as the expression passed as the\n first argument to `defmodule\/2` evaluates to an atom.\n Note that, when a dynamic name is used, Elixir won't nest the name under\n the current module nor automatically set up an alias.\n\n ## Reserved module names\n\n If you attempt to define a module that already exists, you will get a\n warning saying that a module has been redefined.\n\n There are some modules that Elixir does not currently implement but it\n may be implement in the future. Those modules are reserved and defining\n them will result in a compilation error:\n\n defmodule Any do\n # code\n end\n ** (CompileError) iex:1: module Any is reserved and cannot be defined\n\n Elixir reserves the following module names: `Elixir`, `Any`, `BitString`,\n `PID`, and `Reference`.\n \"\"\"\n defmacro defmodule(alias, do_block)\n\n defmacro defmodule(alias, do: block) do\n env = __CALLER__\n boot? = bootstrapped?(Macro)\n\n expanded =\n case boot? do\n true -> Macro.expand(alias, env)\n false -> alias\n end\n\n {expanded, with_alias} =\n case boot? and is_atom(expanded) do\n true ->\n # Expand the module considering the current environment\/nesting\n {full, old, new} = expand_module(alias, expanded, env)\n meta = [defined: full, context: env.module] ++ alias_meta(alias)\n {full, {:alias, meta, [old, [as: new, warn: false]]}}\n\n false ->\n {expanded, nil}\n end\n\n # We do this so that the block is not tail-call optimized and stacktraces\n # are not messed up. Basically, we just insert something between the return\n # value of the block and what is returned by defmodule. Using just \":ok\" or\n # similar doesn't work because it's likely optimized away by the compiler.\n block =\n quote do\n result = unquote(block)\n :elixir_utils.noop()\n result\n end\n\n escaped =\n case env do\n %{function: nil, lexical_tracker: pid} when is_pid(pid) ->\n integer = Kernel.LexicalTracker.write_cache(pid, block)\n quote(do: Kernel.LexicalTracker.read_cache(unquote(pid), unquote(integer)))\n\n %{} ->\n :elixir_quote.escape(block, :default, false)\n end\n\n module_vars = :lists.map(&module_var\/1, :maps.keys(elem(env.current_vars, 0)))\n\n quote do\n unquote(with_alias)\n :elixir_module.compile(unquote(expanded), unquote(escaped), unquote(module_vars), __ENV__)\n end\n end\n\n defp alias_meta({:__aliases__, meta, _}), do: meta\n defp alias_meta(_), do: []\n\n # defmodule Elixir.Alias\n defp expand_module({:__aliases__, _, [:\"Elixir\", _ | _]}, module, _env),\n do: {module, module, nil}\n\n # defmodule Alias in root\n defp expand_module({:__aliases__, _, _}, module, %{module: nil}),\n do: {module, module, nil}\n\n # defmodule Alias nested\n defp expand_module({:__aliases__, _, [h | t]}, _module, env) when is_atom(h) do\n module = :elixir_aliases.concat([env.module, h])\n alias = String.to_atom(\"Elixir.\" <> Atom.to_string(h))\n\n case t do\n [] -> {module, module, alias}\n _ -> {String.to_atom(Enum.join([module | t], \".\")), module, alias}\n end\n end\n\n # defmodule _\n defp expand_module(_raw, module, _env) do\n {module, module, nil}\n end\n\n defp module_var({name, kind}) when is_atom(kind), do: {name, [generated: true], kind}\n defp module_var({name, kind}), do: {name, [counter: kind, generated: true], nil}\n\n @doc ~S\"\"\"\n Defines a public function with the given name and body.\n\n ## Examples\n\n defmodule Foo do\n def bar, do: :baz\n end\n\n Foo.bar()\n #=> :baz\n\n A function that expects arguments can be defined as follows:\n\n defmodule Foo do\n def sum(a, b) do\n a + b\n end\n end\n\n In the example above, a `sum\/2` function is defined; this function receives\n two arguments and returns their sum.\n\n ## Default arguments\n\n `\\\\` is used to specify a default value for a parameter of a function. For\n example:\n\n defmodule MyMath do\n def multiply_by(number, factor \\\\ 2) do\n number * factor\n end\n end\n\n MyMath.multiply_by(4, 3)\n #=> 12\n\n MyMath.multiply_by(4)\n #=> 8\n\n The compiler translates this into multiple functions with different arities,\n here `MyMath.multiply_by\/1` and `MyMath.multiply_by\/2`, that represent cases when\n arguments for parameters with default values are passed or not passed.\n\n When defining a function with default arguments as well as multiple\n explicitly declared clauses, you must write a function head that declares the\n defaults. For example:\n\n defmodule MyString do\n def join(string1, string2 \\\\ nil, separator \\\\ \" \")\n\n def join(string1, nil, _separator) do\n string1\n end\n\n def join(string1, string2, separator) do\n string1 <> separator <> string2\n end\n end\n\n Note that `\\\\` can't be used with anonymous functions because they\n can only have a sole arity.\n\n ### Keyword lists with default arguments\n\n Functions containing many arguments can benefit from using `Keyword`\n lists to group and pass attributes as a single value.\n\n defmodule MyConfiguration do\n @default_opts [storage: \"local\"]\n\n def configure(resource, opts \\\\ []) do\n opts = Keyword.merge(@default_opts, opts)\n storage = opts[:storage]\n # ...\n end\n end\n\n The difference between using `Map` and `Keyword` to store many\n arguments is `Keyword`'s keys:\n\n * must be atoms\n * can be given more than once\n * ordered, as specified by the developer\n\n ## Function and variable names\n\n Function and variable names have the following syntax:\n A _lowercase ASCII letter_ or an _underscore_, followed by any number of\n _lowercase or uppercase ASCII letters_, _numbers_, or _underscores_.\n Optionally they can end in either an _exclamation mark_ or a _question mark_.\n\n For variables, any identifier starting with an underscore should indicate an\n unused variable. For example:\n\n def foo(bar) do\n []\n end\n #=> warning: variable bar is unused\n\n def foo(_bar) do\n []\n end\n #=> no warning\n\n def foo(_bar) do\n _bar\n end\n #=> warning: the underscored variable \"_bar\" is used after being set\n\n ## `rescue`\/`catch`\/`after`\/`else`\n\n Function bodies support `rescue`, `catch`, `after`, and `else` as `Kernel.SpecialForms.try\/1`\n does (known as \"implicit try\"). For example, the following two functions are equivalent:\n\n def convert(number) do\n try do\n String.to_integer(number)\n rescue\n e in ArgumentError -> {:error, e.message}\n end\n end\n\n def convert(number) do\n String.to_integer(number)\n rescue\n e in ArgumentError -> {:error, e.message}\n end\n\n \"\"\"\n defmacro def(call, expr \\\\ nil) do\n define(:def, call, expr, __CALLER__)\n end\n\n @doc \"\"\"\n Defines a private function with the given name and body.\n\n Private functions are only accessible from within the module in which they are\n defined. Trying to access a private function from outside the module it's\n defined in results in an `UndefinedFunctionError` exception.\n\n Check `def\/2` for more information.\n\n ## Examples\n\n defmodule Foo do\n def bar do\n sum(1, 2)\n end\n\n defp sum(a, b), do: a + b\n end\n\n Foo.bar()\n #=> 3\n\n Foo.sum(1, 2)\n ** (UndefinedFunctionError) undefined function Foo.sum\/2\n\n \"\"\"\n defmacro defp(call, expr \\\\ nil) do\n define(:defp, call, expr, __CALLER__)\n end\n\n @doc \"\"\"\n Defines a public macro with the given name and body.\n\n Macros must be defined before its usage.\n\n Check `def\/2` for rules on naming and default arguments.\n\n ## Examples\n\n defmodule MyLogic do\n defmacro unless(expr, opts) do\n quote do\n if !unquote(expr), unquote(opts)\n end\n end\n end\n\n require MyLogic\n\n MyLogic.unless false do\n IO.puts(\"It works\")\n end\n\n \"\"\"\n defmacro defmacro(call, expr \\\\ nil) do\n define(:defmacro, call, expr, __CALLER__)\n end\n\n @doc \"\"\"\n Defines a private macro with the given name and body.\n\n Private macros are only accessible from the same module in which they are\n defined.\n\n Private macros must be defined before its usage.\n\n Check `defmacro\/2` for more information, and check `def\/2` for rules on\n naming and default arguments.\n\n \"\"\"\n defmacro defmacrop(call, expr \\\\ nil) do\n define(:defmacrop, call, expr, __CALLER__)\n end\n\n defp define(kind, call, expr, env) do\n module = assert_module_scope(env, kind, 2)\n assert_no_function_scope(env, kind, 2)\n\n unquoted_call = :elixir_quote.has_unquotes(call)\n unquoted_expr = :elixir_quote.has_unquotes(expr)\n escaped_call = :elixir_quote.escape(call, :default, true)\n\n escaped_expr =\n case unquoted_expr do\n true ->\n :elixir_quote.escape(expr, :default, true)\n\n false ->\n key = :erlang.unique_integer()\n :elixir_module.write_cache(module, key, expr)\n quote(do: :elixir_module.read_cache(unquote(module), unquote(key)))\n end\n\n # Do not check clauses if any expression was unquoted\n check_clauses = not (unquoted_expr or unquoted_call)\n pos = :elixir_locals.cache_env(env)\n\n quote do\n :elixir_def.store_definition(\n unquote(kind),\n unquote(check_clauses),\n unquote(escaped_call),\n unquote(escaped_expr),\n unquote(pos)\n )\n end\n end\n\n @doc \"\"\"\n Defines a struct.\n\n A struct is a tagged map that allows developers to provide\n default values for keys, tags to be used in polymorphic\n dispatches and compile time assertions.\n\n To define a struct, a developer must define both `__struct__\/0` and\n `__struct__\/1` functions. `defstruct\/1` is a convenience macro which\n defines such functions with some conveniences.\n\n For more information about structs, please check `Kernel.SpecialForms.%\/2`.\n\n ## Examples\n\n defmodule User do\n defstruct name: nil, age: nil\n end\n\n Struct fields are evaluated at compile-time, which allows\n them to be dynamic. In the example below, `10 + 11` is\n evaluated at compile-time and the age field is stored\n with value `21`:\n\n defmodule User do\n defstruct name: nil, age: 10 + 11\n end\n\n The `fields` argument is usually a keyword list with field names\n as atom keys and default values as corresponding values. `defstruct\/1`\n also supports a list of atoms as its argument: in that case, the atoms\n in the list will be used as the struct's field names and they will all\n default to `nil`.\n\n defmodule Post do\n defstruct [:title, :content, :author]\n end\n\n ## Deriving\n\n Although structs are maps, by default structs do not implement\n any of the protocols implemented for maps. For example, attempting\n to use a protocol with the `User` struct leads to an error:\n\n john = %User{name: \"John\"}\n MyProtocol.call(john)\n ** (Protocol.UndefinedError) protocol MyProtocol not implemented for %User{...}\n\n `defstruct\/1`, however, allows protocol implementations to be\n *derived*. This can be done by defining a `@derive` attribute as a\n list before invoking `defstruct\/1`:\n\n defmodule User do\n @derive [MyProtocol]\n defstruct name: nil, age: 10 + 11\n end\n\n MyProtocol.call(john) # it works!\n\n For each protocol in the `@derive` list, Elixir will assert the protocol has\n been implemented for `Any`. If the `Any` implementation defines a\n `__deriving__\/3` callback, the callback will be invoked and it should define\n the implementation module. Otherwise an implementation that simply points to\n the `Any` implementation is automatically derived. For more information on\n the `__deriving__\/3` callback, see `Protocol.derive\/3`.\n\n ## Enforcing keys\n\n When building a struct, Elixir will automatically guarantee all keys\n belongs to the struct:\n\n %User{name: \"john\", unknown: :key}\n ** (KeyError) key :unknown not found in: %User{age: 21, name: nil}\n\n Elixir also allows developers to enforce certain keys must always be\n given when building the struct:\n\n defmodule User do\n @enforce_keys [:name]\n defstruct name: nil, age: 10 + 11\n end\n\n Now trying to build a struct without the name key will fail:\n\n %User{age: 21}\n ** (ArgumentError) the following keys must also be given when building struct User: [:name]\n\n Keep in mind `@enforce_keys` is a simple compile-time guarantee\n to aid developers when building structs. It is not enforced on\n updates and it does not provide any sort of value-validation.\n\n ## Types\n\n It is recommended to define types for structs. By convention such type\n is called `t`. To define a struct inside a type, the struct literal syntax\n is used:\n\n defmodule User do\n defstruct name: \"John\", age: 25\n @type t :: %__MODULE__{name: String.t(), age: non_neg_integer}\n end\n\n It is recommended to only use the struct syntax when defining the struct's\n type. When referring to another struct it's better to use `User.t` instead of\n `%User{}`.\n\n The types of the struct fields that are not included in `%User{}` default to\n `term()` (see `t:term\/0`).\n\n Structs whose internal structure is private to the local module (pattern\n matching them or directly accessing their fields should not be allowed) should\n use the `@opaque` attribute. Structs whose internal structure is public should\n use `@type`.\n \"\"\"\n defmacro defstruct(fields) do\n builder =\n case bootstrapped?(Enum) do\n true ->\n quote do\n case @enforce_keys do\n [] ->\n def __struct__(kv) do\n Enum.reduce(kv, @__struct__, fn {key, val}, map ->\n Map.replace!(map, key, val)\n end)\n end\n\n _ ->\n def __struct__(kv) do\n {map, keys} =\n Enum.reduce(kv, {@__struct__, @enforce_keys}, fn {key, val}, {map, keys} ->\n {Map.replace!(map, key, val), List.delete(keys, key)}\n end)\n\n case keys do\n [] ->\n map\n\n _ ->\n raise ArgumentError,\n \"the following keys must also be given when building \" <>\n \"struct #{inspect(__MODULE__)}: #{inspect(keys)}\"\n end\n end\n end\n end\n\n false ->\n quote do\n _ = @enforce_keys\n\n def __struct__(kv) do\n :lists.foldl(fn {key, val}, acc -> Map.replace!(acc, key, val) end, @__struct__, kv)\n end\n end\n end\n\n quote do\n if Module.has_attribute?(__MODULE__, :__struct__) do\n raise ArgumentError,\n \"defstruct has already been called for \" <>\n \"#{Kernel.inspect(__MODULE__)}, defstruct can only be called once per module\"\n end\n\n {struct, keys, derive} = Kernel.Utils.defstruct(__MODULE__, unquote(fields))\n @__struct__ struct\n @enforce_keys keys\n\n case derive do\n [] -> :ok\n _ -> Protocol.__derive__(derive, __MODULE__, __ENV__)\n end\n\n def __struct__() do\n @__struct__\n end\n\n unquote(builder)\n Kernel.Utils.announce_struct(__MODULE__)\n struct\n end\n end\n\n @doc ~S\"\"\"\n Defines an exception.\n\n Exceptions are structs backed by a module that implements\n the `Exception` behaviour. The `Exception` behaviour requires\n two functions to be implemented:\n\n * [`exception\/1`](`c:Exception.exception\/1`) - receives the arguments given to `raise\/2`\n and returns the exception struct. The default implementation\n accepts either a set of keyword arguments that is merged into\n the struct or a string to be used as the exception's message.\n\n * [`message\/1`](`c:Exception.message\/1`) - receives the exception struct and must return its\n message. Most commonly exceptions have a message field which\n by default is accessed by this function. However, if an exception\n does not have a message field, this function must be explicitly\n implemented.\n\n Since exceptions are structs, the API supported by `defstruct\/1`\n is also available in `defexception\/1`.\n\n ## Raising exceptions\n\n The most common way to raise an exception is via `raise\/2`:\n\n defmodule MyAppError do\n defexception [:message]\n end\n\n value = [:hello]\n\n raise MyAppError,\n message: \"did not get what was expected, got: #{inspect(value)}\"\n\n In many cases it is more convenient to pass the expected value to\n `raise\/2` and generate the message in the `c:Exception.exception\/1` callback:\n\n defmodule MyAppError do\n defexception [:message]\n\n @impl true\n def exception(value) do\n msg = \"did not get what was expected, got: #{inspect(value)}\"\n %MyAppError{message: msg}\n end\n end\n\n raise MyAppError, value\n\n The example above shows the preferred strategy for customizing\n exception messages.\n \"\"\"\n defmacro defexception(fields) do\n quote bind_quoted: [fields: fields] do\n @behaviour Exception\n struct = defstruct([__exception__: true] ++ fields)\n\n if Map.has_key?(struct, :message) do\n @impl true\n def message(exception) do\n exception.message\n end\n\n defoverridable message: 1\n\n @impl true\n def exception(msg) when Kernel.is_binary(msg) do\n exception(message: msg)\n end\n end\n\n # Calls to Kernel functions must be fully-qualified to ensure\n # reproducible builds; otherwise, this macro will generate ASTs\n # with different metadata (:import, :context) depending on if\n # it is the bootstrapped version or not.\n # TODO: Change the implementation on v2.0 to simply call Kernel.struct!\/2\n @impl true\n def exception(args) when Kernel.is_list(args) do\n struct = __struct__()\n {valid, invalid} = Enum.split_with(args, fn {k, _} -> Map.has_key?(struct, k) end)\n\n case invalid do\n [] ->\n :ok\n\n _ ->\n IO.warn(\n \"the following fields are unknown when raising \" <>\n \"#{Kernel.inspect(__MODULE__)}: #{Kernel.inspect(invalid)}. \" <>\n \"Please make sure to only give known fields when raising \" <>\n \"or redefine #{Kernel.inspect(__MODULE__)}.exception\/1 to \" <>\n \"discard unknown fields. Future Elixir versions will raise on \" <>\n \"unknown fields given to raise\/2\"\n )\n end\n\n Kernel.struct!(struct, valid)\n end\n\n defoverridable exception: 1\n end\n end\n\n @doc \"\"\"\n Defines a protocol.\n\n See the `Protocol` module for more information.\n \"\"\"\n defmacro defprotocol(name, do_block)\n\n defmacro defprotocol(name, do: block) do\n Protocol.__protocol__(name, do: block)\n end\n\n @doc \"\"\"\n Defines an implementation for the given protocol.\n\n See the `Protocol` module for more information.\n \"\"\"\n defmacro defimpl(name, opts, do_block \\\\ []) do\n merged = Keyword.merge(opts, do_block)\n merged = Keyword.put_new(merged, :for, __CALLER__.module)\n\n if Keyword.fetch!(merged, :for) == nil do\n raise ArgumentError, \"defimpl\/3 expects a :for option when declared outside a module\"\n end\n\n Protocol.__impl__(name, merged)\n end\n\n @doc \"\"\"\n Makes the given functions in the current module overridable.\n\n An overridable function is lazily defined, allowing a developer to override\n it.\n\n Macros cannot be overridden as functions and vice-versa.\n\n ## Example\n\n defmodule DefaultMod do\n defmacro __using__(_opts) do\n quote do\n def test(x, y) do\n x + y\n end\n\n defoverridable test: 2\n end\n end\n end\n\n defmodule InheritMod do\n use DefaultMod\n\n def test(x, y) do\n x * y + super(x, y)\n end\n end\n\n As seen as in the example above, `super` can be used to call the default\n implementation.\n\n If `@behaviour` has been defined, `defoverridable` can also be called with a\n module as an argument. All implemented callbacks from the behaviour above the\n call to `defoverridable` will be marked as overridable.\n\n ## Example\n\n defmodule Behaviour do\n @callback foo :: any\n end\n\n defmodule DefaultMod do\n defmacro __using__(_opts) do\n quote do\n @behaviour Behaviour\n\n def foo do\n \"Override me\"\n end\n\n defoverridable Behaviour\n end\n end\n end\n\n defmodule InheritMod do\n use DefaultMod\n\n def foo do\n \"Overridden\"\n end\n end\n\n \"\"\"\n defmacro defoverridable(keywords_or_behaviour) do\n quote do\n Module.make_overridable(__MODULE__, unquote(keywords_or_behaviour))\n end\n end\n\n @doc \"\"\"\n Generates a macro suitable for use in guard expressions.\n\n It raises at compile time if the definition uses expressions that aren't\n allowed in guards, and otherwise creates a macro that can be used both inside\n or outside guards.\n\n Note the convention in Elixir is to name functions\/macros allowed in\n guards with the `is_` prefix, such as `is_list\/1`. If, however, the\n function\/macro returns a boolean and is not allowed in guards, it should\n have no prefix and end with a question mark, such as `Keyword.keyword?\/1`.\n\n ## Example\n\n defmodule Integer.Guards do\n defguard is_even(value) when is_integer(value) and rem(value, 2) == 0\n end\n\n defmodule Collatz do\n @moduledoc \"Tools for working with the Collatz sequence.\"\n import Integer.Guards\n\n @doc \"Determines the number of steps `n` takes to reach `1`.\"\n # If this function never converges, please let me know what `n` you used.\n def converge(n) when n > 0, do: step(n, 0)\n\n defp step(1, step_count) do\n step_count\n end\n\n defp step(n, step_count) when is_even(n) do\n step(div(n, 2), step_count + 1)\n end\n\n defp step(n, step_count) do\n step(3 * n + 1, step_count + 1)\n end\n end\n\n \"\"\"\n @doc since: \"1.6.0\"\n @spec defguard(Macro.t()) :: Macro.t()\n defmacro defguard(guard) do\n define_guard(:defmacro, guard, __CALLER__)\n end\n\n @doc \"\"\"\n Generates a private macro suitable for use in guard expressions.\n\n It raises at compile time if the definition uses expressions that aren't\n allowed in guards, and otherwise creates a private macro that can be used\n both inside or outside guards in the current module.\n\n Similar to `defmacrop\/2`, `defguardp\/1` must be defined before its use\n in the current module.\n \"\"\"\n @doc since: \"1.6.0\"\n @spec defguardp(Macro.t()) :: Macro.t()\n defmacro defguardp(guard) do\n define_guard(:defmacrop, guard, __CALLER__)\n end\n\n defp define_guard(kind, guard, env) do\n case :elixir_utils.extract_guards(guard) do\n {call, [_, _ | _]} ->\n raise ArgumentError,\n \"invalid syntax in defguard #{Macro.to_string(call)}, \" <>\n \"only a single when clause is allowed\"\n\n {call, impls} ->\n case Macro.decompose_call(call) do\n {_name, args} ->\n validate_variable_only_args!(call, args)\n\n macro_definition =\n case impls do\n [] ->\n define(kind, call, nil, env)\n\n [guard] ->\n quoted =\n quote do\n require Kernel.Utils\n Kernel.Utils.defguard(unquote(args), unquote(guard))\n end\n\n define(kind, call, [do: quoted], env)\n end\n\n quote do\n @doc guard: true\n unquote(macro_definition)\n end\n\n _invalid_definition ->\n raise ArgumentError, \"invalid syntax in defguard #{Macro.to_string(call)}\"\n end\n end\n end\n\n defp validate_variable_only_args!(call, args) do\n Enum.each(args, fn\n {ref, _meta, context} when is_atom(ref) and is_atom(context) ->\n :ok\n\n {:\\\\, _m1, [{ref, _m2, context}, _default]} when is_atom(ref) and is_atom(context) ->\n :ok\n\n _match ->\n raise ArgumentError, \"invalid syntax in defguard #{Macro.to_string(call)}\"\n end)\n end\n\n @doc \"\"\"\n Uses the given module in the current context.\n\n When calling:\n\n use MyModule, some: :options\n\n the `__using__\/1` macro from the `MyModule` module is invoked with the second\n argument passed to `use` as its argument. Since `__using__\/1` is a macro, all\n the usual macro rules apply, and its return value should be quoted code\n that is then inserted where `use\/2` is called.\n\n ## Examples\n\n For example, to write test cases using the `ExUnit` framework provided\n with Elixir, a developer should `use` the `ExUnit.Case` module:\n\n defmodule AssertionTest do\n use ExUnit.Case, async: true\n\n test \"always pass\" do\n assert true\n end\n end\n\n In this example, Elixir will call the `__using__\/1` macro in the\n `ExUnit.Case` module with the keyword list `[async: true]` as its\n argument.\n\n In other words, `use\/2` translates to:\n\n defmodule AssertionTest do\n require ExUnit.Case\n ExUnit.Case.__using__(async: true)\n\n test \"always pass\" do\n assert true\n end\n end\n\n where `ExUnit.Case` defines the `__using__\/1` macro:\n\n defmodule ExUnit.Case do\n defmacro __using__(opts) do\n # do something with opts\n quote do\n # return some code to inject in the caller\n end\n end\n end\n\n ## Best practices\n\n `__using__\/1` is typically used when there is a need to set some state (via\n module attributes) or callbacks (like `@before_compile`, see the documentation\n for `Module` for more information) into the caller.\n\n `__using__\/1` may also be used to alias, require, or import functionality\n from different modules:\n\n defmodule MyModule do\n defmacro __using__(_opts) do\n quote do\n import MyModule.Foo\n import MyModule.Bar\n import MyModule.Baz\n\n alias MyModule.Repo\n end\n end\n end\n\n However, do not provide `__using__\/1` if all it does is to import,\n alias or require the module itself. For example, avoid this:\n\n defmodule MyModule do\n defmacro __using__(_opts) do\n quote do\n import MyModule\n end\n end\n end\n\n In such cases, developers should instead import or alias the module\n directly, so that they can customize those as they wish,\n without the indirection behind `use\/2`.\n\n Finally, developers should also avoid defining functions inside\n the `__using__\/1` callback, unless those functions are the default\n implementation of a previously defined `@callback` or are functions\n meant to be overridden (see `defoverridable\/1`). Even in these cases,\n defining functions should be seen as a \"last resort\".\n\n In case you want to provide some existing functionality to the user module,\n please define it in a module which will be imported accordingly; for example,\n `ExUnit.Case` doesn't define the `test\/3` macro in the module that calls\n `use ExUnit.Case`, but it defines `ExUnit.Case.test\/3` and just imports that\n into the caller when used.\n \"\"\"\n defmacro use(module, opts \\\\ []) do\n calls =\n Enum.map(expand_aliases(module, __CALLER__), fn\n expanded when is_atom(expanded) ->\n quote do\n require unquote(expanded)\n unquote(expanded).__using__(unquote(opts))\n end\n\n _otherwise ->\n raise ArgumentError,\n \"invalid arguments for use, \" <>\n \"expected a compile time atom or alias, got: #{Macro.to_string(module)}\"\n end)\n\n quote(do: (unquote_splicing(calls)))\n end\n\n defp expand_aliases({{:., _, [base, :{}]}, _, refs}, env) do\n base = Macro.expand(base, env)\n\n Enum.map(refs, fn\n {:__aliases__, _, ref} ->\n Module.concat([base | ref])\n\n ref when is_atom(ref) ->\n Module.concat(base, ref)\n\n other ->\n other\n end)\n end\n\n defp expand_aliases(module, env) do\n [Macro.expand(module, env)]\n end\n\n @doc \"\"\"\n Defines a function that delegates to another module.\n\n Functions defined with `defdelegate\/2` are public and can be invoked from\n outside the module they're defined in, as if they were defined using `def\/2`.\n Therefore, `defdelegate\/2` is about extending the current module's public API.\n If what you want is to invoke a function defined in another module without\n using its full module name, then use `alias\/2` to shorten the module name or use\n `import\/2` to be able to invoke the function without the module name altogether.\n\n Delegation only works with functions; delegating macros is not supported.\n\n Check `def\/2` for rules on naming and default arguments.\n\n ## Options\n\n * `:to` - the module to dispatch to.\n\n * `:as` - the function to call on the target given in `:to`.\n This parameter is optional and defaults to the name being\n delegated (`funs`).\n\n ## Examples\n\n defmodule MyList do\n defdelegate reverse(list), to: Enum\n defdelegate other_reverse(list), to: Enum, as: :reverse\n end\n\n MyList.reverse([1, 2, 3])\n #=> [3, 2, 1]\n\n MyList.other_reverse([1, 2, 3])\n #=> [3, 2, 1]\n\n \"\"\"\n defmacro defdelegate(funs, opts) do\n funs = Macro.escape(funs, unquote: true)\n\n # don't add compile-time dependency on :to\n opts =\n with true <- is_list(opts),\n {:ok, target} <- Keyword.fetch(opts, :to),\n {:__aliases__, _, _} <- target do\n target = Macro.expand(target, %{__CALLER__ | function: {:__info__, 1}})\n Keyword.replace!(opts, :to, target)\n else\n _ ->\n opts\n end\n\n quote bind_quoted: [funs: funs, opts: opts] do\n target =\n Keyword.get(opts, :to) || raise ArgumentError, \"expected to: to be given as argument\"\n\n if is_list(funs) do\n IO.warn(\n \"passing a list to Kernel.defdelegate\/2 is deprecated, please define each delegate separately\",\n Macro.Env.stacktrace(__ENV__)\n )\n end\n\n if Keyword.has_key?(opts, :append_first) do\n IO.warn(\n \"Kernel.defdelegate\/2 :append_first option is deprecated\",\n Macro.Env.stacktrace(__ENV__)\n )\n end\n\n for fun <- List.wrap(funs) do\n {name, args, as, as_args} = Kernel.Utils.defdelegate(fun, opts)\n\n @doc delegate_to: {target, as, :erlang.length(as_args)}\n\n # Build the call AST by hand so it doesn't get a\n # context and it warns on things like missing @impl\n def unquote({name, [line: __ENV__.line], args}) do\n unquote(target).unquote(as)(unquote_splicing(as_args))\n end\n end\n end\n end\n\n ## Sigils\n\n @doc ~S\"\"\"\n Handles the sigil `~S` for strings.\n\n It returns a string without interpolations and without escape\n characters, except for the escaping of the closing sigil character\n itself.\n\n ## Examples\n\n iex> ~S(foo)\n \"foo\"\n iex> ~S(f#{o}o)\n \"f\\#{o}o\"\n iex> ~S(\\o\/)\n \"\\\\o\/\"\n\n However, if you want to re-use the sigil character itself on\n the string, you need to escape it:\n\n iex> ~S((\\))\n \"()\"\n\n \"\"\"\n defmacro sigil_S(term, modifiers)\n defmacro sigil_S({:<<>>, _, [binary]}, []) when is_binary(binary), do: binary\n\n @doc ~S\"\"\"\n Handles the sigil `~s` for strings.\n\n It returns a string as if it was a double quoted string, unescaping characters\n and replacing interpolations.\n\n ## Examples\n\n iex> ~s(foo)\n \"foo\"\n\n iex> ~s(f#{:o}o)\n \"foo\"\n\n iex> ~s(f\\#{:o}o)\n \"f\\#{:o}o\"\n\n \"\"\"\n defmacro sigil_s(term, modifiers)\n\n defmacro sigil_s({:<<>>, _, [piece]}, []) when is_binary(piece) do\n :elixir_interpolation.unescape_chars(piece)\n end\n\n defmacro sigil_s({:<<>>, line, pieces}, []) do\n {:<<>>, line, unescape_tokens(pieces)}\n end\n\n @doc ~S\"\"\"\n Handles the sigil `~C` for charlists.\n\n It returns a charlist without interpolations and without escape\n characters, except for the escaping of the closing sigil character\n itself.\n\n ## Examples\n\n iex> ~C(foo)\n 'foo'\n\n iex> ~C(f#{o}o)\n 'f\\#{o}o'\n\n \"\"\"\n defmacro sigil_C(term, modifiers)\n\n defmacro sigil_C({:<<>>, _meta, [string]}, []) when is_binary(string) do\n String.to_charlist(string)\n end\n\n @doc ~S\"\"\"\n Handles the sigil `~c` for charlists.\n\n It returns a charlist as if it was a single quoted string, unescaping\n characters and replacing interpolations.\n\n ## Examples\n\n iex> ~c(foo)\n 'foo'\n\n iex> ~c(f#{:o}o)\n 'foo'\n\n iex> ~c(f\\#{:o}o)\n 'f\\#{:o}o'\n\n \"\"\"\n defmacro sigil_c(term, modifiers)\n\n # We can skip the runtime conversion if we are\n # creating a binary made solely of series of chars.\n defmacro sigil_c({:<<>>, _meta, [string]}, []) when is_binary(string) do\n String.to_charlist(:elixir_interpolation.unescape_chars(string))\n end\n\n defmacro sigil_c({:<<>>, _meta, pieces}, []) do\n quote(do: List.to_charlist(unquote(unescape_list_tokens(pieces))))\n end\n\n @doc \"\"\"\n Handles the sigil `~r` for regular expressions.\n\n It returns a regular expression pattern, unescaping characters and replacing\n interpolations.\n\n More information on regular expressions can be found in the `Regex` module.\n\n ## Examples\n\n iex> Regex.match?(~r(foo), \"foo\")\n true\n\n iex> Regex.match?(~r\/a#{:b}c\/, \"abc\")\n true\n\n \"\"\"\n defmacro sigil_r(term, modifiers)\n\n defmacro sigil_r({:<<>>, _meta, [string]}, options) when is_binary(string) do\n binary = :elixir_interpolation.unescape_chars(string, &Regex.unescape_map\/1)\n regex = Regex.compile!(binary, :binary.list_to_bin(options))\n Macro.escape(regex)\n end\n\n defmacro sigil_r({:<<>>, meta, pieces}, options) do\n binary = {:<<>>, meta, unescape_tokens(pieces, &Regex.unescape_map\/1)}\n quote(do: Regex.compile!(unquote(binary), unquote(:binary.list_to_bin(options))))\n end\n\n @doc ~S\"\"\"\n Handles the sigil `~R` for regular expressions.\n\n It returns a regular expression pattern without interpolations and\n without escape characters. Note it still supports escape of Regex\n tokens (such as escaping `+` or `?`) and it also requires you to\n escape the closing sigil character itself if it appears on the Regex.\n\n More information on regexes can be found in the `Regex` module.\n\n ## Examples\n\n iex> Regex.match?(~R(f#{1,3}o), \"f#o\")\n true\n\n \"\"\"\n defmacro sigil_R(term, modifiers)\n\n defmacro sigil_R({:<<>>, _meta, [string]}, options) when is_binary(string) do\n regex = Regex.compile!(string, :binary.list_to_bin(options))\n Macro.escape(regex)\n end\n\n @doc ~S\"\"\"\n Handles the sigil `~D` for dates.\n\n By default, this sigil uses the built-in `Calendar.ISO`, which\n requires dates to be written in the ISO8601 format:\n\n ~D[yyyy-mm-dd]\n\n such as:\n\n ~D[2015-01-13]\n\n If you are using alternative calendars, any representation can\n be used as long as you follow the representation by a single space\n and the calendar name:\n\n ~D[SOME-REPRESENTATION My.Alternative.Calendar]\n\n The lower case `~d` variant does not exist as interpolation\n and escape characters are not useful for date sigils.\n\n More information on dates can be found in the `Date` module.\n\n ## Examples\n\n iex> ~D[2015-01-13]\n ~D[2015-01-13]\n\n \"\"\"\n defmacro sigil_D(date_string, modifiers)\n\n defmacro sigil_D({:<<>>, _, [string]}, []) do\n {{:ok, {year, month, day}}, calendar} = parse_with_calendar!(string, :parse_date, \"Date\")\n to_calendar_struct(Date, calendar: calendar, year: year, month: month, day: day)\n end\n\n @doc ~S\"\"\"\n Handles the sigil `~T` for times.\n\n By default, this sigil uses the built-in `Calendar.ISO`, which\n requires times to be written in the ISO8601 format:\n\n ~T[hh:mm:ss]\n ~T[hh:mm:ss.ssssss]\n\n such as:\n\n ~T[13:00:07]\n ~T[13:00:07.123]\n\n If you are using alternative calendars, any representation can\n be used as long as you follow the representation by a single space\n and the calendar name:\n\n ~T[SOME-REPRESENTATION My.Alternative.Calendar]\n\n The lower case `~t` variant does not exist as interpolation\n and escape characters are not useful for time sigils.\n\n More information on times can be found in the `Time` module.\n\n ## Examples\n\n iex> ~T[13:00:07]\n ~T[13:00:07]\n iex> ~T[13:00:07.001]\n ~T[13:00:07.001]\n\n \"\"\"\n defmacro sigil_T(time_string, modifiers)\n\n defmacro sigil_T({:<<>>, _, [string]}, []) do\n {{:ok, {hour, minute, second, microsecond}}, calendar} =\n parse_with_calendar!(string, :parse_time, \"Time\")\n\n to_calendar_struct(Time,\n calendar: calendar,\n hour: hour,\n minute: minute,\n second: second,\n microsecond: microsecond\n )\n end\n\n @doc ~S\"\"\"\n Handles the sigil `~N` for naive date times.\n\n By default, this sigil uses the built-in `Calendar.ISO`, which\n requires naive date times to be written in the ISO8601 format:\n\n ~N[yyyy-mm-dd hh:mm:ss]\n ~N[yyyy-mm-dd hh:mm:ss.ssssss]\n ~N[yyyy-mm-ddThh:mm:ss.ssssss]\n\n such as:\n\n ~N[2015-01-13 13:00:07]\n ~N[2015-01-13T13:00:07.123]\n\n If you are using alternative calendars, any representation can\n be used as long as you follow the representation by a single space\n and the calendar name:\n\n ~N[SOME-REPRESENTATION My.Alternative.Calendar]\n\n The lower case `~n` variant does not exist as interpolation\n and escape characters are not useful for date time sigils.\n\n More information on naive date times can be found in the\n `NaiveDateTime` module.\n\n ## Examples\n\n iex> ~N[2015-01-13 13:00:07]\n ~N[2015-01-13 13:00:07]\n iex> ~N[2015-01-13T13:00:07.001]\n ~N[2015-01-13 13:00:07.001]\n\n \"\"\"\n defmacro sigil_N(naive_datetime_string, modifiers)\n\n defmacro sigil_N({:<<>>, _, [string]}, []) do\n {{:ok, {year, month, day, hour, minute, second, microsecond}}, calendar} =\n parse_with_calendar!(string, :parse_naive_datetime, \"NaiveDateTime\")\n\n to_calendar_struct(NaiveDateTime,\n calendar: calendar,\n year: year,\n month: month,\n day: day,\n hour: hour,\n minute: minute,\n second: second,\n microsecond: microsecond\n )\n end\n\n @doc ~S\"\"\"\n Handles the sigil `~U` to create a UTC `DateTime`.\n\n By default, this sigil uses the built-in `Calendar.ISO`, which\n requires UTC date times to be written in the ISO8601 format:\n\n ~U[yyyy-mm-dd hh:mm:ssZ]\n ~U[yyyy-mm-dd hh:mm:ss.ssssssZ]\n ~U[yyyy-mm-ddThh:mm:ss.ssssss+00:00]\n\n such as:\n\n ~U[2015-01-13 13:00:07Z]\n ~U[2015-01-13T13:00:07.123+00:00]\n\n If you are using alternative calendars, any representation can\n be used as long as you follow the representation by a single space\n and the calendar name:\n\n ~U[SOME-REPRESENTATION My.Alternative.Calendar]\n\n The given `datetime_string` must include \"Z\" or \"00:00\" offset\n which marks it as UTC, otherwise an error is raised.\n\n The lower case `~u` variant does not exist as interpolation\n and escape characters are not useful for date time sigils.\n\n More information on date times can be found in the `DateTime` module.\n\n ## Examples\n\n iex> ~U[2015-01-13 13:00:07Z]\n ~U[2015-01-13 13:00:07Z]\n iex> ~U[2015-01-13T13:00:07.001+00:00]\n ~U[2015-01-13 13:00:07.001Z]\n\n \"\"\"\n @doc since: \"1.9.0\"\n defmacro sigil_U(datetime_string, modifiers)\n\n defmacro sigil_U({:<<>>, _, [string]}, []) do\n {{:ok, {year, month, day, hour, minute, second, microsecond}, offset}, calendar} =\n parse_with_calendar!(string, :parse_utc_datetime, \"UTC DateTime\")\n\n if offset != 0 do\n raise ArgumentError,\n \"cannot parse #{inspect(string)} as UTC DateTime for #{inspect(calendar)}, reason: :non_utc_offset\"\n end\n\n to_calendar_struct(DateTime,\n calendar: calendar,\n year: year,\n month: month,\n day: day,\n hour: hour,\n minute: minute,\n second: second,\n microsecond: microsecond,\n time_zone: \"Etc\/UTC\",\n zone_abbr: \"UTC\",\n utc_offset: 0,\n std_offset: 0\n )\n end\n\n defp parse_with_calendar!(string, fun, context) do\n {calendar, string} = extract_calendar(string)\n result = apply(calendar, fun, [string])\n {maybe_raise!(result, calendar, context, string), calendar}\n end\n\n defp extract_calendar(string) do\n case :binary.split(string, \" \", [:global]) do\n [_] -> {Calendar.ISO, string}\n parts -> maybe_atomize_calendar(List.last(parts), string)\n end\n end\n\n defp maybe_atomize_calendar(<> = last_part, string)\n when alias >= ?A and alias <= ?Z do\n string = binary_part(string, 0, byte_size(string) - byte_size(last_part) - 1)\n {String.to_atom(\"Elixir.\" <> last_part), string}\n end\n\n defp maybe_atomize_calendar(_last_part, string) do\n {Calendar.ISO, string}\n end\n\n defp maybe_raise!({:error, reason}, calendar, type, string) do\n raise ArgumentError,\n \"cannot parse #{inspect(string)} as #{type} for #{inspect(calendar)}, \" <>\n \"reason: #{inspect(reason)}\"\n end\n\n defp maybe_raise!(other, _calendar, _type, _string), do: other\n\n defp to_calendar_struct(type, fields) do\n quote do\n %{unquote_splicing([__struct__: type] ++ fields)}\n end\n end\n\n @doc ~S\"\"\"\n Handles the sigil `~w` for list of words.\n\n It returns a list of \"words\" split by whitespace. Character unescaping and\n interpolation happens for each word.\n\n ## Modifiers\n\n * `s`: words in the list are strings (default)\n * `a`: words in the list are atoms\n * `c`: words in the list are charlists\n\n ## Examples\n\n iex> ~w(foo #{:bar} baz)\n [\"foo\", \"bar\", \"baz\"]\n\n iex> ~w(foo #{\" bar baz \"})\n [\"foo\", \"bar\", \"baz\"]\n\n iex> ~w(--source test\/enum_test.exs)\n [\"--source\", \"test\/enum_test.exs\"]\n\n iex> ~w(foo bar baz)a\n [:foo, :bar, :baz]\n\n \"\"\"\n defmacro sigil_w(term, modifiers)\n\n defmacro sigil_w({:<<>>, _meta, [string]}, modifiers) when is_binary(string) do\n split_words(:elixir_interpolation.unescape_chars(string), modifiers, __CALLER__)\n end\n\n defmacro sigil_w({:<<>>, meta, pieces}, modifiers) do\n binary = {:<<>>, meta, unescape_tokens(pieces)}\n split_words(binary, modifiers, __CALLER__)\n end\n\n @doc ~S\"\"\"\n Handles the sigil `~W` for list of words.\n\n It returns a list of \"words\" split by whitespace without interpolations\n and without escape characters, except for the escaping of the closing\n sigil character itself.\n\n ## Modifiers\n\n * `s`: words in the list are strings (default)\n * `a`: words in the list are atoms\n * `c`: words in the list are charlists\n\n ## Examples\n\n iex> ~W(foo #{bar} baz)\n [\"foo\", \"\\#{bar}\", \"baz\"]\n\n \"\"\"\n defmacro sigil_W(term, modifiers)\n\n defmacro sigil_W({:<<>>, _meta, [string]}, modifiers) when is_binary(string) do\n split_words(string, modifiers, __CALLER__)\n end\n\n defp split_words(string, [], caller) do\n split_words(string, [?s], caller)\n end\n\n defp split_words(string, [mod], caller)\n when mod == ?s or mod == ?a or mod == ?c do\n case is_binary(string) do\n true ->\n parts = String.split(string)\n\n parts_with_trailing_comma =\n :lists.filter(&(byte_size(&1) > 1 and :binary.last(&1) == ?,), parts)\n\n if parts_with_trailing_comma != [] do\n stacktrace = Macro.Env.stacktrace(caller)\n\n IO.warn(\n \"the sigils ~w\/~W do not allow trailing commas at the end of each word. \" <>\n \"If the comma is necessary, define a regular list with [...], otherwise remove the comma.\",\n stacktrace\n )\n end\n\n case mod do\n ?s -> parts\n ?a -> :lists.map(&String.to_atom\/1, parts)\n ?c -> :lists.map(&String.to_charlist\/1, parts)\n end\n\n false ->\n parts = quote(do: String.split(unquote(string)))\n\n case mod do\n ?s -> parts\n ?a -> quote(do: :lists.map(&String.to_atom\/1, unquote(parts)))\n ?c -> quote(do: :lists.map(&String.to_charlist\/1, unquote(parts)))\n end\n end\n end\n\n defp split_words(_string, _mods, _caller) do\n raise ArgumentError, \"modifier must be one of: s, a, c\"\n end\n\n ## Shared functions\n\n defp assert_module_scope(env, fun, arity) do\n case env.module do\n nil -> raise ArgumentError, \"cannot invoke #{fun}\/#{arity} outside module\"\n mod -> mod\n end\n end\n\n defp assert_no_function_scope(env, fun, arity) do\n case env.function do\n nil -> :ok\n _ -> raise ArgumentError, \"cannot invoke #{fun}\/#{arity} inside function\/macro\"\n end\n end\n\n defp assert_no_match_or_guard_scope(context, exp) do\n case context do\n :match ->\n invalid_match!(exp)\n\n :guard ->\n raise ArgumentError,\n \"invalid expression in guard, #{exp} is not allowed in guards. \" <>\n \"To learn more about guards, visit: https:\/\/hexdocs.pm\/elixir\/patterns-and-guards.html\"\n\n _ ->\n :ok\n end\n end\n\n defp invalid_match!(exp) do\n raise ArgumentError,\n \"invalid expression in match, #{exp} is not allowed in patterns \" <>\n \"such as function clauses, case clauses or on the left side of the = operator\"\n end\n\n # Helper to handle the :ok | :error tuple returned from :elixir_interpolation.unescape_tokens\n defp unescape_tokens(tokens) do\n case :elixir_interpolation.unescape_tokens(tokens) do\n {:ok, unescaped_tokens} -> unescaped_tokens\n {:error, reason} -> raise ArgumentError, to_string(reason)\n end\n end\n\n defp unescape_tokens(tokens, unescape_map) do\n case :elixir_interpolation.unescape_tokens(tokens, unescape_map) do\n {:ok, unescaped_tokens} -> unescaped_tokens\n {:error, reason} -> raise ArgumentError, to_string(reason)\n end\n end\n\n defp unescape_list_tokens(tokens) do\n escape = fn\n {:\"::\", _, [expr, _]} -> expr\n binary when is_binary(binary) -> :elixir_interpolation.unescape_chars(binary)\n end\n\n :lists.map(escape, tokens)\n end\n\n @doc false\n defmacro to_char_list(arg) do\n IO.warn(\n \"Kernel.to_char_list\/1 is deprecated, use Kernel.to_charlist\/1 instead\",\n Macro.Env.stacktrace(__CALLER__)\n )\n\n quote(do: Kernel.to_charlist(unquote(arg)))\n end\nend\n","old_contents":"# Use elixir_bootstrap module to be able to bootstrap Kernel.\n# The bootstrap module provides simpler implementations of the\n# functions removed, simple enough to bootstrap.\nimport Kernel,\n except: [@: 1, defmodule: 2, def: 1, def: 2, defp: 2, defmacro: 1, defmacro: 2, defmacrop: 2]\n\nimport :elixir_bootstrap\n\ndefmodule Kernel do\n @moduledoc \"\"\"\n `Kernel` is Elixir's default environment.\n\n It mainly consists of:\n\n * basic language primitives, such as arithmetic operators, spawning of processes,\n data type handling, and others\n * macros for control-flow and defining new functionality (modules, functions, and the like)\n * guard checks for augmenting pattern matching\n\n You can invoke `Kernel` functions and macros anywhere in Elixir code\n without the use of the `Kernel.` prefix since they have all been\n automatically imported. For example, in IEx, you can call:\n\n iex> is_number(13)\n true\n\n If you don't want to import a function or macro from `Kernel`, use the `:except`\n option and then list the function\/macro by arity:\n\n import Kernel, except: [if: 2, unless: 2]\n\n See `Kernel.SpecialForms.import\/2` for more information on importing.\n\n Elixir also has special forms that are always imported and\n cannot be skipped. These are described in `Kernel.SpecialForms`.\n\n ## The standard library\n\n `Kernel` provides the basic capabilities the Elixir standard library\n is built on top of. It is recommended to explore the standard library\n for advanced functionality. Here are the main groups of modules in the\n standard library (this list is not a complete reference, see the\n documentation sidebar for all entries).\n\n ### Built-in types\n\n The following modules handle Elixir built-in data types:\n\n * `Atom` - literal constants with a name (`true`, `false`, and `nil` are atoms)\n * `Float` - numbers with floating point precision\n * `Function` - a reference to code chunk, created with the `fn\/1` special form\n * `Integer` - whole numbers (not fractions)\n * `List` - collections of a variable number of elements (linked lists)\n * `Map` - collections of key-value pairs\n * `Process` - light-weight threads of execution\n * `Port` - mechanisms to interact with the external world\n * `Tuple` - collections of a fixed number of elements\n\n There are two data types without an accompanying module:\n\n * Bitstring - a sequence of bits, created with `Kernel.SpecialForms.<<>>\/1`.\n When the number of bits is divisible by 8, they are called binaries and can\n be manipulated with Erlang's `:binary` module\n * Reference - a unique value in the runtime system, created with `make_ref\/0`\n\n ### Data types\n\n Elixir also provides other data types that are built on top of the types\n listed above. Some of them are:\n\n * `Date` - `year-month-day` structs in a given calendar\n * `DateTime` - date and time with time zone in a given calendar\n * `Exception` - data raised from errors and unexpected scenarios\n * `MapSet` - unordered collections of unique elements\n * `NaiveDateTime` - date and time without time zone in a given calendar\n * `Keyword` - lists of two-element tuples, often representing optional values\n * `Range` - inclusive ranges between two integers\n * `Regex` - regular expressions\n * `String` - UTF-8 encoded binaries representing characters\n * `Time` - `hour:minute:second` structs in a given calendar\n * `URI` - representation of URIs that identify resources\n * `Version` - representation of versions and requirements\n\n ### System modules\n\n Modules that interface with the underlying system, such as:\n\n * `IO` - handles input and output\n * `File` - interacts with the underlying file system\n * `Path` - manipulates file system paths\n * `System` - reads and writes system information\n\n ### Protocols\n\n Protocols add polymorphic dispatch to Elixir. They are contracts\n implementable by data types. See `Protocol` for more information on\n protocols. Elixir provides the following protocols in the standard library:\n\n * `Collectable` - collects data into a data type\n * `Enumerable` - handles collections in Elixir. The `Enum` module\n provides eager functions for working with collections, the `Stream`\n module provides lazy functions\n * `Inspect` - converts data types into their programming language\n representation\n * `List.Chars` - converts data types to their outside world\n representation as charlists (non-programming based)\n * `String.Chars` - converts data types to their outside world\n representation as strings (non-programming based)\n\n ### Process-based and application-centric functionality\n\n The following modules build on top of processes to provide concurrency,\n fault-tolerance, and more.\n\n * `Agent` - a process that encapsulates mutable state\n * `Application` - functions for starting, stopping and configuring\n applications\n * `GenServer` - a generic client-server API\n * `Registry` - a key-value process-based storage\n * `Supervisor` - a process that is responsible for starting,\n supervising and shutting down other processes\n * `Task` - a process that performs computations\n * `Task.Supervisor` - a supervisor for managing tasks exclusively\n\n ### Supporting documents\n\n Elixir documentation also includes supporting documents under the\n \"Pages\" section. Those are:\n\n * [Compatibility and Deprecations](compatibility-and-deprecations.md) - lists\n compatibility between every Elixir version and Erlang\/OTP, release schema;\n lists all deprecated functions, when they were deprecated and alternatives\n * [Library Guidelines](library-guidelines.md) - general guidelines, anti-patterns,\n and rules for those writing libraries\n * [Naming Conventions](naming-conventions.md) - naming conventions for Elixir code\n * [Operators](operators.md) - lists all Elixir operators and their precedences\n * [Patterns and Guards](patterns-and-guards.md) - an introduction to patterns,\n guards, and extensions\n * [Syntax Reference](syntax-reference.md) - the language syntax reference\n * [Typespecs](typespecs.md)- types and function specifications, including list of types\n * [Unicode Syntax](unicode-syntax.md) - outlines Elixir support for Unicode\n * [Writing Documentation](writing-documentation.md) - guidelines for writing\n documentation in Elixir\n\n ## Guards\n\n This module includes the built-in guards used by Elixir developers.\n They are a predefined set of functions and macros that augment pattern\n matching, typically invoked after the `when` operator. For example:\n\n def drive(%User{age: age}) when age >= 16 do\n ...\n end\n\n The clause above will only be invoked if the user's age is more than\n or equal to 16. Guards also support joining multiple conditions with\n `and` and `or`. The whole guard is true if all guard expressions will\n evaluate to `true`. A more complete introduction to guards is available\n [in the \"Patterns and Guards\" page](patterns-and-guards.md).\n\n ## Structural comparison\n\n The comparison functions in this module perform structural comparison.\n This means structures are compared based on their representation and\n not on their semantic value. This is specially important for functions\n that are meant to provide ordering, such as `>\/2`, `<\/2`, `>=\/2`,\n `<=\/2`, `min\/2`, and `max\/2`. For example:\n\n ~D[2017-03-31] > ~D[2017-04-01]\n\n will return `true` because structural comparison compares the `:day`\n field before `:month` or `:year`. Therefore, when comparing structs,\n you often use the `compare\/2` function made available by the structs\n modules themselves:\n\n iex> Date.compare(~D[2017-03-31], ~D[2017-04-01])\n :lt\n\n Alternatively, you can use the functions in the `Enum` module to\n sort or compute a maximum\/minimum:\n\n iex> Enum.sort([~D[2017-03-31], ~D[2017-04-01]], Date)\n [~D[2017-03-31], ~D[2017-04-01]]\n iex> Enum.max([~D[2017-03-31], ~D[2017-04-01]], Date)\n ~D[2017-04-01]\n\n ## Truthy and falsy values\n\n Besides the booleans `true` and `false`, Elixir has the\n concept of a \"truthy\" or \"falsy\" value.\n\n * a value is truthy when it is neither `false` nor `nil`\n * a value is falsy when it is either `false` or `nil`\n\n Elixir has functions, like `and\/2`, that *only* work with\n booleans, but also functions that work with these\n truthy\/falsy values, like `&&\/2` and `!\/1`.\n\n ### Examples\n\n We can check the truthiness of a value by using the `!\/1`\n function twice.\n\n Truthy values:\n\n iex> !!true\n true\n iex> !!5\n true\n iex> !![1,2]\n true\n iex> !!\"foo\"\n true\n\n Falsy values (of which there are exactly two):\n\n iex> !!false\n false\n iex> !!nil\n false\n\n ## Inlining\n\n Some of the functions described in this module are inlined by\n the Elixir compiler into their Erlang counterparts in the\n [`:erlang` module](http:\/\/www.erlang.org\/doc\/man\/erlang.html).\n Those functions are called BIFs (built-in internal functions)\n in Erlang-land and they exhibit interesting properties, as some\n of them are allowed in guards and others are used for compiler\n optimizations.\n\n Most of the inlined functions can be seen in effect when\n capturing the function:\n\n iex> &Kernel.is_atom\/1\n &:erlang.is_atom\/1\n\n Those functions will be explicitly marked in their docs as\n \"inlined by the compiler\".\n \"\"\"\n\n # We need this check only for bootstrap purposes.\n # Once Kernel is loaded and we recompile, it is a no-op.\n @compile {:inline, bootstrapped?: 1}\n case :code.ensure_loaded(Kernel) do\n {:module, _} ->\n defp bootstrapped?(_), do: true\n\n {:error, _} ->\n defp bootstrapped?(module), do: :code.ensure_loaded(module) == {:module, module}\n end\n\n ## Delegations to Erlang with inlining (macros)\n\n @doc \"\"\"\n Returns an integer or float which is the arithmetical absolute value of `number`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> abs(-3.33)\n 3.33\n\n iex> abs(-3)\n 3\n\n \"\"\"\n @doc guard: true\n @spec abs(number) :: number\n def abs(number) do\n :erlang.abs(number)\n end\n\n @doc \"\"\"\n Invokes the given anonymous function `fun` with the list of\n arguments `args`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> apply(fn x -> x * 2 end, [2])\n 4\n\n \"\"\"\n @spec apply(fun, [any]) :: any\n def apply(fun, args) do\n :erlang.apply(fun, args)\n end\n\n @doc \"\"\"\n Invokes the given function from `module` with the list of\n arguments `args`.\n\n `apply\/3` is used to invoke functions where the module, function\n name or arguments are defined dynamically at runtime. For this\n reason, you can't invoke macros using `apply\/3`, only functions.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> apply(Enum, :reverse, [[1, 2, 3]])\n [3, 2, 1]\n\n \"\"\"\n @spec apply(module, function_name :: atom, [any]) :: any\n def apply(module, function_name, args) do\n :erlang.apply(module, function_name, args)\n end\n\n @doc \"\"\"\n Extracts the part of the binary starting at `start` with length `length`.\n Binaries are zero-indexed.\n\n If `start` or `length` reference in any way outside the binary, an\n `ArgumentError` exception is raised.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> binary_part(\"foo\", 1, 2)\n \"oo\"\n\n A negative `length` can be used to extract bytes that come *before* the byte\n at `start`:\n\n iex> binary_part(\"Hello\", 5, -3)\n \"llo\"\n\n An `ArgumentError` is raised when the length is outside of the binary:\n\n binary_part(\"Hello\", 0, 10)\n ** (ArgumentError) argument error\n\n \"\"\"\n @doc guard: true\n @spec binary_part(binary, non_neg_integer, integer) :: binary\n def binary_part(binary, start, length) do\n :erlang.binary_part(binary, start, length)\n end\n\n @doc \"\"\"\n Returns an integer which is the size in bits of `bitstring`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> bit_size(<<433::16, 3::3>>)\n 19\n\n iex> bit_size(<<1, 2, 3>>)\n 24\n\n \"\"\"\n @doc guard: true\n @spec bit_size(bitstring) :: non_neg_integer\n def bit_size(bitstring) do\n :erlang.bit_size(bitstring)\n end\n\n @doc \"\"\"\n Returns the number of bytes needed to contain `bitstring`.\n\n That is, if the number of bits in `bitstring` is not divisible by 8, the\n resulting number of bytes will be rounded up (by excess). This operation\n happens in constant time.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> byte_size(<<433::16, 3::3>>)\n 3\n\n iex> byte_size(<<1, 2, 3>>)\n 3\n\n \"\"\"\n @doc guard: true\n @spec byte_size(bitstring) :: non_neg_integer\n def byte_size(bitstring) do\n :erlang.byte_size(bitstring)\n end\n\n @doc \"\"\"\n Returns the smallest integer greater than or equal to `number`.\n\n If you want to perform ceil operation on other decimal places,\n use `Float.ceil\/2` instead.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc since: \"1.8.0\", guard: true\n @spec ceil(number) :: integer\n def ceil(number) do\n :erlang.ceil(number)\n end\n\n @doc \"\"\"\n Performs an integer division.\n\n Raises an `ArithmeticError` exception if one of the arguments is not an\n integer, or when the `divisor` is `0`.\n\n `div\/2` performs *truncated* integer division. This means that\n the result is always rounded towards zero.\n\n If you want to perform floored integer division (rounding towards negative infinity),\n use `Integer.floor_div\/2` instead.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n div(5, 2)\n #=> 2\n\n div(6, -4)\n #=> -1\n\n div(-99, 2)\n #=> -49\n\n div(100, 0)\n ** (ArithmeticError) bad argument in arithmetic expression\n\n \"\"\"\n @doc guard: true\n @spec div(integer, neg_integer | pos_integer) :: integer\n def div(dividend, divisor) do\n :erlang.div(dividend, divisor)\n end\n\n @doc \"\"\"\n Stops the execution of the calling process with the given reason.\n\n Since evaluating this function causes the process to terminate,\n it has no return value.\n\n Inlined by the compiler.\n\n ## Examples\n\n When a process reaches its end, by default it exits with\n reason `:normal`. You can also call `exit\/1` explicitly if you\n want to terminate a process but not signal any failure:\n\n exit(:normal)\n\n In case something goes wrong, you can also use `exit\/1` with\n a different reason:\n\n exit(:seems_bad)\n\n If the exit reason is not `:normal`, all the processes linked to the process\n that exited will crash (unless they are trapping exits).\n\n ## OTP exits\n\n Exits are used by the OTP to determine if a process exited abnormally\n or not. The following exits are considered \"normal\":\n\n * `exit(:normal)`\n * `exit(:shutdown)`\n * `exit({:shutdown, term})`\n\n Exiting with any other reason is considered abnormal and treated\n as a crash. This means the default supervisor behaviour kicks in,\n error reports are emitted, and so forth.\n\n This behaviour is relied on in many different places. For example,\n `ExUnit` uses `exit(:shutdown)` when exiting the test process to\n signal linked processes, supervision trees and so on to politely\n shut down too.\n\n ## CLI exits\n\n Building on top of the exit signals mentioned above, if the\n process started by the command line exits with any of the three\n reasons above, its exit is considered normal and the Operating\n System process will exit with status 0.\n\n It is, however, possible to customize the operating system exit\n signal by invoking:\n\n exit({:shutdown, integer})\n\n This will cause the operating system process to exit with the status given by\n `integer` while signaling all linked Erlang processes to politely\n shut down.\n\n Any other exit reason will cause the operating system process to exit with\n status `1` and linked Erlang processes to crash.\n \"\"\"\n @spec exit(term) :: no_return\n def exit(reason) do\n :erlang.exit(reason)\n end\n\n @doc \"\"\"\n Returns the largest integer smaller than or equal to `number`.\n\n If you want to perform floor operation on other decimal places,\n use `Float.floor\/2` instead.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc since: \"1.8.0\", guard: true\n @spec floor(number) :: integer\n def floor(number) do\n :erlang.floor(number)\n end\n\n @doc \"\"\"\n Returns the head of a list. Raises `ArgumentError` if the list is empty.\n\n It works with improper lists.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n hd([1, 2, 3, 4])\n #=> 1\n\n hd([])\n ** (ArgumentError) argument error\n\n hd([1 | 2])\n #=> 1\n\n \"\"\"\n @doc guard: true\n @spec hd(nonempty_maybe_improper_list(elem, any)) :: elem when elem: term\n def hd(list) do\n :erlang.hd(list)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is an atom; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_atom(term) :: boolean\n def is_atom(term) do\n :erlang.is_atom(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a binary; otherwise returns `false`.\n\n A binary always contains a complete number of bytes.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> is_binary(\"foo\")\n true\n iex> is_binary(<<1::3>>)\n false\n\n \"\"\"\n @doc guard: true\n @spec is_binary(term) :: boolean\n def is_binary(term) do\n :erlang.is_binary(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a bitstring (including a binary); otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> is_bitstring(\"foo\")\n true\n iex> is_bitstring(<<1::3>>)\n true\n\n \"\"\"\n @doc guard: true\n @spec is_bitstring(term) :: boolean\n def is_bitstring(term) do\n :erlang.is_bitstring(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is either the atom `true` or the atom `false` (i.e.,\n a boolean); otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_boolean(term) :: boolean\n def is_boolean(term) do\n :erlang.is_boolean(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a floating-point number; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_float(term) :: boolean\n def is_float(term) do\n :erlang.is_float(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a function; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_function(term) :: boolean\n def is_function(term) do\n :erlang.is_function(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a function that can be applied with `arity` number of arguments;\n otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> is_function(fn x -> x * 2 end, 1)\n true\n iex> is_function(fn x -> x * 2 end, 2)\n false\n\n \"\"\"\n @doc guard: true\n @spec is_function(term, non_neg_integer) :: boolean\n def is_function(term, arity) do\n :erlang.is_function(term, arity)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is an integer; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_integer(term) :: boolean\n def is_integer(term) do\n :erlang.is_integer(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a list with zero or more elements; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_list(term) :: boolean\n def is_list(term) do\n :erlang.is_list(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is either an integer or a floating-point number;\n otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_number(term) :: boolean\n def is_number(term) do\n :erlang.is_number(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a PID (process identifier); otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_pid(term) :: boolean\n def is_pid(term) do\n :erlang.is_pid(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a port identifier; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_port(term) :: boolean\n def is_port(term) do\n :erlang.is_port(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a reference; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_reference(term) :: boolean\n def is_reference(term) do\n :erlang.is_reference(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a tuple; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_tuple(term) :: boolean\n def is_tuple(term) do\n :erlang.is_tuple(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a map; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec is_map(term) :: boolean\n def is_map(term) do\n :erlang.is_map(term)\n end\n\n @doc \"\"\"\n Returns `true` if `key` is a key in `map`; otherwise returns `false`.\n\n It raises `BadMapError` if the first element is not a map.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true, since: \"1.10.0\"\n @spec is_map_key(map, term) :: boolean\n def is_map_key(map, key) do\n :erlang.is_map_key(key, map)\n end\n\n @doc \"\"\"\n Returns the length of `list`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> length([1, 2, 3, 4, 5, 6, 7, 8, 9])\n 9\n\n \"\"\"\n @doc guard: true\n @spec length(list) :: non_neg_integer\n def length(list) do\n :erlang.length(list)\n end\n\n @doc \"\"\"\n Returns an almost unique reference.\n\n The returned reference will re-occur after approximately 2^82 calls;\n therefore it is unique enough for practical purposes.\n\n Inlined by the compiler.\n\n ## Examples\n\n make_ref()\n #=> #Reference<0.0.0.135>\n\n \"\"\"\n @spec make_ref() :: reference\n def make_ref() do\n :erlang.make_ref()\n end\n\n @doc \"\"\"\n Returns the size of a map.\n\n The size of a map is the number of key-value pairs that the map contains.\n\n This operation happens in constant time.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> map_size(%{a: \"foo\", b: \"bar\"})\n 2\n\n \"\"\"\n @doc guard: true\n @spec map_size(map) :: non_neg_integer\n def map_size(map) do\n :erlang.map_size(map)\n end\n\n @doc \"\"\"\n Returns the biggest of the two given terms according to\n their structural comparison.\n\n If the terms compare equal, the first one is returned.\n\n This performs a structural comparison where all Elixir\n terms can be compared with each other. See the [\"Structural\n comparison\" section](#module-structural-comparison) section\n for more information.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> max(1, 2)\n 2\n iex> max(:a, :b)\n :b\n\n \"\"\"\n @spec max(first, second) :: first | second when first: term, second: term\n def max(first, second) do\n :erlang.max(first, second)\n end\n\n @doc \"\"\"\n Returns the smallest of the two given terms according to\n their structural comparison.\n\n If the terms compare equal, the first one is returned.\n\n This performs a structural comparison where all Elixir\n terms can be compared with each other. See the [\"Structural\n comparison\" section](#module-structural-comparison) section\n for more information.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> min(1, 2)\n 1\n iex> min(\"foo\", \"bar\")\n \"bar\"\n\n \"\"\"\n @spec min(first, second) :: first | second when first: term, second: term\n def min(first, second) do\n :erlang.min(first, second)\n end\n\n @doc \"\"\"\n Returns an atom representing the name of the local node.\n If the node is not alive, `:nonode@nohost` is returned instead.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec node() :: node\n def node do\n :erlang.node()\n end\n\n @doc \"\"\"\n Returns the node where the given argument is located.\n The argument can be a PID, a reference, or a port.\n If the local node is not alive, `:nonode@nohost` is returned.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec node(pid | reference | port) :: node\n def node(arg) do\n :erlang.node(arg)\n end\n\n @doc \"\"\"\n Computes the remainder of an integer division.\n\n `rem\/2` uses truncated division, which means that\n the result will always have the sign of the `dividend`.\n\n Raises an `ArithmeticError` exception if one of the arguments is not an\n integer, or when the `divisor` is `0`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> rem(5, 2)\n 1\n iex> rem(6, -4)\n 2\n\n \"\"\"\n @doc guard: true\n @spec rem(integer, neg_integer | pos_integer) :: integer\n def rem(dividend, divisor) do\n :erlang.rem(dividend, divisor)\n end\n\n @doc \"\"\"\n Rounds a number to the nearest integer.\n\n If the number is equidistant to the two nearest integers, rounds away from zero.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> round(5.6)\n 6\n\n iex> round(5.2)\n 5\n\n iex> round(-9.9)\n -10\n\n iex> round(-9)\n -9\n\n iex> round(2.5)\n 3\n\n iex> round(-2.5)\n -3\n\n \"\"\"\n @doc guard: true\n @spec round(number) :: integer\n def round(number) do\n :erlang.round(number)\n end\n\n @doc \"\"\"\n Sends a message to the given `dest` and returns the message.\n\n `dest` may be a remote or local PID, a local port, a locally\n registered name, or a tuple in the form of `{registered_name, node}` for a\n registered name at another node.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> send(self(), :hello)\n :hello\n\n \"\"\"\n @spec send(dest :: Process.dest(), message) :: message when message: any\n def send(dest, message) do\n :erlang.send(dest, message)\n end\n\n @doc \"\"\"\n Returns the PID (process identifier) of the calling process.\n\n Allowed in guard clauses. Inlined by the compiler.\n \"\"\"\n @doc guard: true\n @spec self() :: pid\n def self() do\n :erlang.self()\n end\n\n @doc \"\"\"\n Spawns the given function and returns its PID.\n\n Typically developers do not use the `spawn` functions, instead they use\n abstractions such as `Task`, `GenServer` and `Agent`, built on top of\n `spawn`, that spawns processes with more conveniences in terms of\n introspection and debugging.\n\n Check the `Process` module for more process-related functions.\n\n The anonymous function receives 0 arguments, and may return any value.\n\n Inlined by the compiler.\n\n ## Examples\n\n current = self()\n child = spawn(fn -> send(current, {self(), 1 + 2}) end)\n\n receive do\n {^child, 3} -> IO.puts(\"Received 3 back\")\n end\n\n \"\"\"\n @spec spawn((() -> any)) :: pid\n def spawn(fun) do\n :erlang.spawn(fun)\n end\n\n @doc \"\"\"\n Spawns the given function `fun` from the given `module` passing it the given\n `args` and returns its PID.\n\n Typically developers do not use the `spawn` functions, instead they use\n abstractions such as `Task`, `GenServer` and `Agent`, built on top of\n `spawn`, that spawns processes with more conveniences in terms of\n introspection and debugging.\n\n Check the `Process` module for more process-related functions.\n\n Inlined by the compiler.\n\n ## Examples\n\n spawn(SomeModule, :function, [1, 2, 3])\n\n \"\"\"\n @spec spawn(module, atom, list) :: pid\n def spawn(module, fun, args) do\n :erlang.spawn(module, fun, args)\n end\n\n @doc \"\"\"\n Spawns the given function, links it to the current process, and returns its PID.\n\n Typically developers do not use the `spawn` functions, instead they use\n abstractions such as `Task`, `GenServer` and `Agent`, built on top of\n `spawn`, that spawns processes with more conveniences in terms of\n introspection and debugging.\n\n Check the `Process` module for more process-related functions. For more\n information on linking, check `Process.link\/1`.\n\n The anonymous function receives 0 arguments, and may return any value.\n\n Inlined by the compiler.\n\n ## Examples\n\n current = self()\n child = spawn_link(fn -> send(current, {self(), 1 + 2}) end)\n\n receive do\n {^child, 3} -> IO.puts(\"Received 3 back\")\n end\n\n \"\"\"\n @spec spawn_link((() -> any)) :: pid\n def spawn_link(fun) do\n :erlang.spawn_link(fun)\n end\n\n @doc \"\"\"\n Spawns the given function `fun` from the given `module` passing it the given\n `args`, links it to the current process, and returns its PID.\n\n Typically developers do not use the `spawn` functions, instead they use\n abstractions such as `Task`, `GenServer` and `Agent`, built on top of\n `spawn`, that spawns processes with more conveniences in terms of\n introspection and debugging.\n\n Check the `Process` module for more process-related functions. For more\n information on linking, check `Process.link\/1`.\n\n Inlined by the compiler.\n\n ## Examples\n\n spawn_link(SomeModule, :function, [1, 2, 3])\n\n \"\"\"\n @spec spawn_link(module, atom, list) :: pid\n def spawn_link(module, fun, args) do\n :erlang.spawn_link(module, fun, args)\n end\n\n @doc \"\"\"\n Spawns the given function, monitors it and returns its PID\n and monitoring reference.\n\n Typically developers do not use the `spawn` functions, instead they use\n abstractions such as `Task`, `GenServer` and `Agent`, built on top of\n `spawn`, that spawns processes with more conveniences in terms of\n introspection and debugging.\n\n Check the `Process` module for more process-related functions.\n\n The anonymous function receives 0 arguments, and may return any value.\n\n Inlined by the compiler.\n\n ## Examples\n\n current = self()\n spawn_monitor(fn -> send(current, {self(), 1 + 2}) end)\n\n \"\"\"\n @spec spawn_monitor((() -> any)) :: {pid, reference}\n def spawn_monitor(fun) do\n :erlang.spawn_monitor(fun)\n end\n\n @doc \"\"\"\n Spawns the given module and function passing the given args,\n monitors it and returns its PID and monitoring reference.\n\n Typically developers do not use the `spawn` functions, instead they use\n abstractions such as `Task`, `GenServer` and `Agent`, built on top of\n `spawn`, that spawns processes with more conveniences in terms of\n introspection and debugging.\n\n Check the `Process` module for more process-related functions.\n\n Inlined by the compiler.\n\n ## Examples\n\n spawn_monitor(SomeModule, :function, [1, 2, 3])\n\n \"\"\"\n @spec spawn_monitor(module, atom, list) :: {pid, reference}\n def spawn_monitor(module, fun, args) do\n :erlang.spawn_monitor(module, fun, args)\n end\n\n @doc \"\"\"\n Pipes `value` to the given `fun` and returns the `value` itself.\n\n Useful for running synchronous side effects in a pipeline.\n\n ## Examples\n\n iex> tap(1, fn x -> x + 1 end)\n 1\n\n Most commonly, this is used in pipelines. For example,\n let's suppose you want to inspect part of a data structure.\n You could write:\n\n %{a: 1}\n |> Map.update!(:a, & &1 + 2)\n |> tap(&IO.inspect(&1.a))\n |> Map.update!(:a, & &1 * 2)\n\n \"\"\"\n @doc since: \"1.12.0\"\n defmacro tap(value, fun) do\n quote bind_quoted: [fun: fun, value: value] do\n fun.(value)\n value\n end\n end\n\n @doc \"\"\"\n A non-local return from a function.\n\n Check `Kernel.SpecialForms.try\/1` for more information.\n\n Inlined by the compiler.\n \"\"\"\n @spec throw(term) :: no_return\n def throw(term) do\n :erlang.throw(term)\n end\n\n @doc \"\"\"\n Returns the tail of a list. Raises `ArgumentError` if the list is empty.\n\n It works with improper lists.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n tl([1, 2, 3, :go])\n #=> [2, 3, :go]\n\n tl([])\n ** (ArgumentError) argument error\n\n tl([:one])\n #=> []\n\n tl([:a, :b | :c])\n #=> [:b | :c]\n\n tl([:a | %{b: 1}])\n #=> %{b: 1}\n\n \"\"\"\n @doc guard: true\n @spec tl(nonempty_maybe_improper_list(elem, tail)) :: maybe_improper_list(elem, tail) | tail\n when elem: term, tail: term\n def tl(list) do\n :erlang.tl(list)\n end\n\n @doc \"\"\"\n Returns the integer part of `number`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> trunc(5.4)\n 5\n\n iex> trunc(-5.99)\n -5\n\n iex> trunc(-5)\n -5\n\n \"\"\"\n @doc guard: true\n @spec trunc(number) :: integer\n def trunc(number) do\n :erlang.trunc(number)\n end\n\n @doc \"\"\"\n Returns the size of a tuple.\n\n This operation happens in constant time.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> tuple_size({:a, :b, :c})\n 3\n\n \"\"\"\n @doc guard: true\n @spec tuple_size(tuple) :: non_neg_integer\n def tuple_size(tuple) do\n :erlang.tuple_size(tuple)\n end\n\n @doc \"\"\"\n Arithmetic addition operator.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 + 2\n 3\n\n \"\"\"\n @doc guard: true\n @spec integer + integer :: integer\n @spec float + float :: float\n @spec integer + float :: float\n @spec float + integer :: float\n def left + right do\n :erlang.+(left, right)\n end\n\n @doc \"\"\"\n Arithmetic subtraction operator.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 - 2\n -1\n\n \"\"\"\n @doc guard: true\n @spec integer - integer :: integer\n @spec float - float :: float\n @spec integer - float :: float\n @spec float - integer :: float\n def left - right do\n :erlang.-(left, right)\n end\n\n @doc \"\"\"\n Arithmetic positive unary operator.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> +1\n 1\n\n \"\"\"\n @doc guard: true\n @spec +integer :: integer\n @spec +float :: float\n def +value do\n :erlang.+(value)\n end\n\n @doc \"\"\"\n Arithmetic negative unary operator.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> -2\n -2\n\n \"\"\"\n @doc guard: true\n @spec -0 :: 0\n @spec -pos_integer :: neg_integer\n @spec -neg_integer :: pos_integer\n @spec -float :: float\n def -value do\n :erlang.-(value)\n end\n\n @doc \"\"\"\n Arithmetic multiplication operator.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 * 2\n 2\n\n \"\"\"\n @doc guard: true\n @spec integer * integer :: integer\n @spec float * float :: float\n @spec integer * float :: float\n @spec float * integer :: float\n def left * right do\n :erlang.*(left, right)\n end\n\n @doc \"\"\"\n Arithmetic division operator.\n\n The result is always a float. Use `div\/2` and `rem\/2` if you want\n an integer division or the remainder.\n\n Raises `ArithmeticError` if `right` is 0 or 0.0.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n 1 \/ 2\n #=> 0.5\n\n -3.0 \/ 2.0\n #=> -1.5\n\n 5 \/ 1\n #=> 5.0\n\n 7 \/ 0\n ** (ArithmeticError) bad argument in arithmetic expression\n\n \"\"\"\n @doc guard: true\n @spec number \/ number :: float\n def left \/ right do\n :erlang.\/(left, right)\n end\n\n @doc \"\"\"\n List concatenation operator. Concatenates a proper list and a term, returning a list.\n\n The complexity of `a ++ b` is proportional to `length(a)`, so avoid repeatedly\n appending to lists of arbitrary length, for example, `list ++ [element]`.\n Instead, consider prepending via `[element | rest]` and then reversing.\n\n If the `right` operand is not a proper list, it returns an improper list.\n If the `left` operand is not a proper list, it raises `ArgumentError`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> [1] ++ [2, 3]\n [1, 2, 3]\n\n iex> 'foo' ++ 'bar'\n 'foobar'\n\n # returns an improper list\n iex> [1] ++ 2\n [1 | 2]\n\n # returns a proper list\n iex> [1] ++ [2]\n [1, 2]\n\n # improper list on the right will return an improper list\n iex> [1] ++ [2 | 3]\n [1, 2 | 3]\n\n \"\"\"\n @spec list ++ term :: maybe_improper_list\n def left ++ right do\n :erlang.++(left, right)\n end\n\n @doc \"\"\"\n List subtraction operator. Removes the first occurrence of an element on the left list\n for each element on the right.\n\n Before Erlang\/OTP 22, the complexity of `a -- b` was proportional to\n `length(a) * length(b)`, meaning that it would be very slow if\n both `a` and `b` were long lists. In such cases, consider\n converting each list to a `MapSet` and using `MapSet.difference\/2`.\n\n As of Erlang\/OTP 22, this operation is significantly faster even if both\n lists are very long, and using `--\/2` is usually faster and uses less\n memory than using the `MapSet`-based alternative mentioned above.\n See also the [Erlang efficiency\n guide](https:\/\/erlang.org\/doc\/efficiency_guide\/retired_myths.html).\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> [1, 2, 3] -- [1, 2]\n [3]\n\n iex> [1, 2, 3, 2, 1] -- [1, 2, 2]\n [3, 1]\n\n The `--\/2` operator is right associative, meaning:\n\n iex> [1, 2, 3] -- [2] -- [3]\n [1, 3]\n\n As it is equivalent to:\n\n iex> [1, 2, 3] -- ([2] -- [3])\n [1, 3]\n\n \"\"\"\n @spec list -- list :: list\n def left -- right do\n :erlang.--(left, right)\n end\n\n @doc \"\"\"\n Strictly boolean \"not\" operator.\n\n `value` must be a boolean; if it's not, an `ArgumentError` exception is raised.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> not false\n true\n\n \"\"\"\n @doc guard: true\n @spec not true :: false\n @spec not false :: true\n def not value do\n :erlang.not(value)\n end\n\n @doc \"\"\"\n Less-than operator.\n\n Returns `true` if `left` is less than `right`.\n\n This performs a structural comparison where all Elixir\n terms can be compared with each other. See the [\"Structural\n comparison\" section](#module-structural-comparison) section\n for more information.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 < 2\n true\n\n \"\"\"\n @doc guard: true\n @spec term < term :: boolean\n def left < right do\n :erlang.<(left, right)\n end\n\n @doc \"\"\"\n Greater-than operator.\n\n Returns `true` if `left` is more than `right`.\n\n This performs a structural comparison where all Elixir\n terms can be compared with each other. See the [\"Structural\n comparison\" section](#module-structural-comparison) section\n for more information.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 > 2\n false\n\n \"\"\"\n @doc guard: true\n @spec term > term :: boolean\n def left > right do\n :erlang.>(left, right)\n end\n\n @doc \"\"\"\n Less-than or equal to operator.\n\n Returns `true` if `left` is less than or equal to `right`.\n\n This performs a structural comparison where all Elixir\n terms can be compared with each other. See the [\"Structural\n comparison\" section](#module-structural-comparison) section\n for more information.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 <= 2\n true\n\n \"\"\"\n @doc guard: true\n @spec term <= term :: boolean\n def left <= right do\n :erlang.\"=<\"(left, right)\n end\n\n @doc \"\"\"\n Greater-than or equal to operator.\n\n Returns `true` if `left` is more than or equal to `right`.\n\n This performs a structural comparison where all Elixir\n terms can be compared with each other. See the [\"Structural\n comparison\" section](#module-structural-comparison) section\n for more information.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 >= 2\n false\n\n \"\"\"\n @doc guard: true\n @spec term >= term :: boolean\n def left >= right do\n :erlang.>=(left, right)\n end\n\n @doc \"\"\"\n Equal to operator. Returns `true` if the two terms are equal.\n\n This operator considers 1 and 1.0 to be equal. For stricter\n semantics, use `===\/2` instead.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 == 2\n false\n\n iex> 1 == 1.0\n true\n\n \"\"\"\n @doc guard: true\n @spec term == term :: boolean\n def left == right do\n :erlang.==(left, right)\n end\n\n @doc \"\"\"\n Not equal to operator.\n\n Returns `true` if the two terms are not equal.\n\n This operator considers 1 and 1.0 to be equal. For match\n comparison, use `!==\/2` instead.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 != 2\n true\n\n iex> 1 != 1.0\n false\n\n \"\"\"\n @doc guard: true\n @spec term != term :: boolean\n def left != right do\n :erlang.\"\/=\"(left, right)\n end\n\n @doc \"\"\"\n Strictly equal to operator.\n\n Returns `true` if the two terms are exactly equal.\n\n The terms are only considered to be exactly equal if they\n have the same value and are of the same type. For example,\n `1 == 1.0` returns `true`, but since they are of different\n types, `1 === 1.0` returns `false`.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 === 2\n false\n\n iex> 1 === 1.0\n false\n\n \"\"\"\n @doc guard: true\n @spec term === term :: boolean\n def left === right do\n :erlang.\"=:=\"(left, right)\n end\n\n @doc \"\"\"\n Strictly not equal to operator.\n\n Returns `true` if the two terms are not exactly equal.\n See `===\/2` for a definition of what is considered \"exactly equal\".\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 !== 2\n true\n\n iex> 1 !== 1.0\n true\n\n \"\"\"\n @doc guard: true\n @spec term !== term :: boolean\n def left !== right do\n :erlang.\"=\/=\"(left, right)\n end\n\n @doc \"\"\"\n Gets the element at the zero-based `index` in `tuple`.\n\n It raises `ArgumentError` when index is negative or it is out of range of the tuple elements.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n tuple = {:foo, :bar, 3}\n elem(tuple, 1)\n #=> :bar\n\n elem({}, 0)\n ** (ArgumentError) argument error\n\n elem({:foo, :bar}, 2)\n ** (ArgumentError) argument error\n\n \"\"\"\n @doc guard: true\n @spec elem(tuple, non_neg_integer) :: term\n def elem(tuple, index) do\n :erlang.element(index + 1, tuple)\n end\n\n @doc \"\"\"\n Puts `value` at the given zero-based `index` in `tuple`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> tuple = {:foo, :bar, 3}\n iex> put_elem(tuple, 0, :baz)\n {:baz, :bar, 3}\n\n \"\"\"\n @spec put_elem(tuple, non_neg_integer, term) :: tuple\n def put_elem(tuple, index, value) do\n :erlang.setelement(index + 1, tuple, value)\n end\n\n ## Implemented in Elixir\n\n defp optimize_boolean({:case, meta, args}) do\n {:case, [{:optimize_boolean, true} | meta], args}\n end\n\n @doc \"\"\"\n Strictly boolean \"or\" operator.\n\n If `left` is `true`, returns `true`; otherwise returns `right`.\n\n Requires only the `left` operand to be a boolean since it short-circuits.\n If the `left` operand is not a boolean, a `BadBooleanError` exception is\n raised.\n\n Allowed in guard tests.\n\n ## Examples\n\n iex> true or false\n true\n\n iex> false or 42\n 42\n\n iex> 42 or false\n ** (BadBooleanError) expected a boolean on left-side of \"or\", got: 42\n\n \"\"\"\n @doc guard: true\n defmacro left or right do\n case __CALLER__.context do\n nil -> build_boolean_check(:or, left, true, right)\n :match -> invalid_match!(:or)\n :guard -> quote(do: :erlang.orelse(unquote(left), unquote(right)))\n end\n end\n\n @doc \"\"\"\n Strictly boolean \"and\" operator.\n\n If `left` is `false`, returns `false`; otherwise returns `right`.\n\n Requires only the `left` operand to be a boolean since it short-circuits. If\n the `left` operand is not a boolean, a `BadBooleanError` exception is raised.\n\n Allowed in guard tests.\n\n ## Examples\n\n iex> true and false\n false\n\n iex> true and \"yay!\"\n \"yay!\"\n\n iex> \"yay!\" and true\n ** (BadBooleanError) expected a boolean on left-side of \"and\", got: \"yay!\"\n\n \"\"\"\n @doc guard: true\n defmacro left and right do\n case __CALLER__.context do\n nil -> build_boolean_check(:and, left, right, false)\n :match -> invalid_match!(:and)\n :guard -> quote(do: :erlang.andalso(unquote(left), unquote(right)))\n end\n end\n\n defp build_boolean_check(operator, check, true_clause, false_clause) do\n optimize_boolean(\n quote do\n case unquote(check) do\n false -> unquote(false_clause)\n true -> unquote(true_clause)\n other -> :erlang.error({:badbool, unquote(operator), other})\n end\n end\n )\n end\n\n @doc \"\"\"\n Boolean \"not\" operator.\n\n Receives any value (not just booleans) and returns `true` if `value`\n is `false` or `nil`; returns `false` otherwise.\n\n Not allowed in guard clauses.\n\n ## Examples\n\n iex> !Enum.empty?([])\n false\n\n iex> !List.first([])\n true\n\n \"\"\"\n defmacro !value\n\n defmacro !{:!, _, [value]} do\n assert_no_match_or_guard_scope(__CALLER__.context, \"!\")\n\n optimize_boolean(\n quote do\n case unquote(value) do\n x when :\"Elixir.Kernel\".in(x, [false, nil]) -> false\n _ -> true\n end\n end\n )\n end\n\n defmacro !value do\n assert_no_match_or_guard_scope(__CALLER__.context, \"!\")\n\n optimize_boolean(\n quote do\n case unquote(value) do\n x when :\"Elixir.Kernel\".in(x, [false, nil]) -> true\n _ -> false\n end\n end\n )\n end\n\n @doc \"\"\"\n Binary concatenation operator. Concatenates two binaries.\n\n ## Examples\n\n iex> \"foo\" <> \"bar\"\n \"foobar\"\n\n The `<>\/2` operator can also be used in pattern matching (and guard clauses) as\n long as the left argument is a literal binary:\n\n iex> \"foo\" <> x = \"foobar\"\n iex> x\n \"bar\"\n\n `x <> \"bar\" = \"foobar\"` would have resulted in a `CompileError` exception.\n\n \"\"\"\n defmacro left <> right do\n concats = extract_concatenations({:<>, [], [left, right]}, __CALLER__)\n quote(do: <>)\n end\n\n # Extracts concatenations in order to optimize many\n # concatenations into one single clause.\n defp extract_concatenations({:<>, _, [left, right]}, caller) do\n [wrap_concatenation(left, :left, caller) | extract_concatenations(right, caller)]\n end\n\n defp extract_concatenations(other, caller) do\n [wrap_concatenation(other, :right, caller)]\n end\n\n defp wrap_concatenation(binary, _side, _caller) when is_binary(binary) do\n binary\n end\n\n defp wrap_concatenation(literal, _side, _caller)\n when is_list(literal) or is_atom(literal) or is_integer(literal) or is_float(literal) do\n :erlang.error(\n ArgumentError.exception(\n \"expected binary argument in <> operator but got: #{Macro.to_string(literal)}\"\n )\n )\n end\n\n defp wrap_concatenation(other, side, caller) do\n expanded = expand_concat_argument(other, side, caller)\n {:\"::\", [], [expanded, {:binary, [], nil}]}\n end\n\n defp expand_concat_argument(arg, :left, %{context: :match} = caller) do\n expanded_arg =\n case bootstrapped?(Macro) do\n true -> Macro.expand(arg, caller)\n false -> arg\n end\n\n case expanded_arg do\n {var, _, nil} when is_atom(var) ->\n invalid_concat_left_argument_error(Atom.to_string(var))\n\n {:^, _, [{var, _, nil}]} when is_atom(var) ->\n invalid_concat_left_argument_error(\"^#{Atom.to_string(var)}\")\n\n _ ->\n expanded_arg\n end\n end\n\n defp expand_concat_argument(arg, _, _) do\n arg\n end\n\n defp invalid_concat_left_argument_error(arg) do\n :erlang.error(\n ArgumentError.exception(\n \"the left argument of <> operator inside a match should always be a literal \" <>\n \"binary because its size can't be verified. Got: #{arg}\"\n )\n )\n end\n\n @doc \"\"\"\n Raises an exception.\n\n If `message` is a string, it raises a `RuntimeError` exception with it.\n\n If `message` is an atom, it just calls `raise\/2` with the atom as the first\n argument and `[]` as the second one.\n\n If `message` is an exception struct, it is raised as is.\n\n If `message` is anything else, `raise` will fail with an `ArgumentError`\n exception.\n\n ## Examples\n\n iex> raise \"oops\"\n ** (RuntimeError) oops\n\n try do\n 1 + :foo\n rescue\n x in [ArithmeticError] ->\n IO.puts(\"that was expected\")\n raise x\n end\n\n \"\"\"\n defmacro raise(message) do\n # Try to figure out the type at compilation time\n # to avoid dead code and make Dialyzer happy.\n message =\n case not is_binary(message) and bootstrapped?(Macro) do\n true -> Macro.expand(message, __CALLER__)\n false -> message\n end\n\n case message do\n message when is_binary(message) ->\n quote do\n :erlang.error(RuntimeError.exception(unquote(message)))\n end\n\n {:<<>>, _, _} = message ->\n quote do\n :erlang.error(RuntimeError.exception(unquote(message)))\n end\n\n alias when is_atom(alias) ->\n quote do\n :erlang.error(unquote(alias).exception([]))\n end\n\n _ ->\n quote do\n :erlang.error(Kernel.Utils.raise(unquote(message)))\n end\n end\n end\n\n @doc \"\"\"\n Raises an exception.\n\n Calls the `exception\/1` function on the given argument (which has to be a\n module name like `ArgumentError` or `RuntimeError`) passing `attributes`\n in order to retrieve the exception struct.\n\n Any module that contains a call to the `defexception\/1` macro automatically\n implements the `c:Exception.exception\/1` callback expected by `raise\/2`.\n For more information, see `defexception\/1`.\n\n ## Examples\n\n iex> raise(ArgumentError, \"Sample\")\n ** (ArgumentError) Sample\n\n \"\"\"\n defmacro raise(exception, attributes) do\n quote do\n :erlang.error(unquote(exception).exception(unquote(attributes)))\n end\n end\n\n @doc \"\"\"\n Raises an exception preserving a previous stacktrace.\n\n Works like `raise\/1` but does not generate a new stacktrace.\n\n Note that `__STACKTRACE__` can be used inside catch\/rescue\n to retrieve the current stacktrace.\n\n ## Examples\n\n try do\n raise \"oops\"\n rescue\n exception ->\n reraise exception, __STACKTRACE__\n end\n\n \"\"\"\n defmacro reraise(message, stacktrace) do\n # Try to figure out the type at compilation time\n # to avoid dead code and make Dialyzer happy.\n case Macro.expand(message, __CALLER__) do\n message when is_binary(message) ->\n quote do\n :erlang.error(\n :erlang.raise(:error, RuntimeError.exception(unquote(message)), unquote(stacktrace))\n )\n end\n\n {:<<>>, _, _} = message ->\n quote do\n :erlang.error(\n :erlang.raise(:error, RuntimeError.exception(unquote(message)), unquote(stacktrace))\n )\n end\n\n alias when is_atom(alias) ->\n quote do\n :erlang.error(:erlang.raise(:error, unquote(alias).exception([]), unquote(stacktrace)))\n end\n\n message ->\n quote do\n :erlang.error(\n :erlang.raise(:error, Kernel.Utils.raise(unquote(message)), unquote(stacktrace))\n )\n end\n end\n end\n\n @doc \"\"\"\n Raises an exception preserving a previous stacktrace.\n\n `reraise\/3` works like `reraise\/2`, except it passes arguments to the\n `exception\/1` function as explained in `raise\/2`.\n\n ## Examples\n\n try do\n raise \"oops\"\n rescue\n exception ->\n reraise WrapperError, [exception: exception], __STACKTRACE__\n end\n\n \"\"\"\n defmacro reraise(exception, attributes, stacktrace) do\n quote do\n :erlang.raise(\n :error,\n unquote(exception).exception(unquote(attributes)),\n unquote(stacktrace)\n )\n end\n end\n\n @doc \"\"\"\n Text-based match operator. Matches the term on the `left`\n against the regular expression or string on the `right`.\n\n If `right` is a regular expression, returns `true` if `left` matches right.\n\n If `right` is a string, returns `true` if `left` contains `right`.\n\n ## Examples\n\n iex> \"abcd\" =~ ~r\/c(d)\/\n true\n\n iex> \"abcd\" =~ ~r\/e\/\n false\n\n iex> \"abcd\" =~ ~r\/\/\n true\n\n iex> \"abcd\" =~ \"bc\"\n true\n\n iex> \"abcd\" =~ \"ad\"\n false\n\n iex> \"abcd\" =~ \"abcd\"\n true\n\n iex> \"abcd\" =~ \"\"\n true\n\n \"\"\"\n @spec String.t() =~ (String.t() | Regex.t()) :: boolean\n def left =~ \"\" when is_binary(left), do: true\n\n def left =~ right when is_binary(left) and is_binary(right) do\n :binary.match(left, right) != :nomatch\n end\n\n def left =~ right when is_binary(left) do\n Regex.match?(right, left)\n end\n\n @doc ~S\"\"\"\n Inspects the given argument according to the `Inspect` protocol.\n The second argument is a keyword list with options to control\n inspection.\n\n ## Options\n\n `inspect\/2` accepts a list of options that are internally\n translated to an `Inspect.Opts` struct. Check the docs for\n `Inspect.Opts` to see the supported options.\n\n ## Examples\n\n iex> inspect(:foo)\n \":foo\"\n\n iex> inspect([1, 2, 3, 4, 5], limit: 3)\n \"[1, 2, 3, ...]\"\n\n iex> inspect([1, 2, 3], pretty: true, width: 0)\n \"[1,\\n 2,\\n 3]\"\n\n iex> inspect(\"ol\u00e1\" <> <<0>>)\n \"<<111, 108, 195, 161, 0>>\"\n\n iex> inspect(\"ol\u00e1\" <> <<0>>, binaries: :as_strings)\n \"\\\"ol\u00e1\\\\0\\\"\"\n\n iex> inspect(\"ol\u00e1\", binaries: :as_binaries)\n \"<<111, 108, 195, 161>>\"\n\n iex> inspect('bar')\n \"'bar'\"\n\n iex> inspect([0 | 'bar'])\n \"[0, 98, 97, 114]\"\n\n iex> inspect(100, base: :octal)\n \"0o144\"\n\n iex> inspect(100, base: :hex)\n \"0x64\"\n\n Note that the `Inspect` protocol does not necessarily return a valid\n representation of an Elixir term. In such cases, the inspected result\n must start with `#`. For example, inspecting a function will return:\n\n inspect(fn a, b -> a + b end)\n #=> #Function<...>\n\n The `Inspect` protocol can be derived to hide certain fields\n from structs, so they don't show up in logs, inspects and similar.\n See the \"Deriving\" section of the documentation of the `Inspect`\n protocol for more information.\n \"\"\"\n @spec inspect(Inspect.t(), keyword) :: String.t()\n def inspect(term, opts \\\\ []) when is_list(opts) do\n opts = struct(Inspect.Opts, opts)\n\n limit =\n case opts.pretty do\n true -> opts.width\n false -> :infinity\n end\n\n doc = Inspect.Algebra.group(Inspect.Algebra.to_doc(term, opts))\n IO.iodata_to_binary(Inspect.Algebra.format(doc, limit))\n end\n\n @doc \"\"\"\n Creates and updates a struct.\n\n The `struct` argument may be an atom (which defines `defstruct`)\n or a `struct` itself. The second argument is any `Enumerable` that\n emits two-element tuples (key-value pairs) during enumeration.\n\n Keys in the `Enumerable` that don't exist in the struct are automatically\n discarded. Note that keys must be atoms, as only atoms are allowed when\n defining a struct. If keys in the `Enumerable` are duplicated, the last\n entry will be taken (same behaviour as `Map.new\/1`).\n\n This function is useful for dynamically creating and updating structs, as\n well as for converting maps to structs; in the latter case, just inserting\n the appropriate `:__struct__` field into the map may not be enough and\n `struct\/2` should be used instead.\n\n ## Examples\n\n defmodule User do\n defstruct name: \"john\"\n end\n\n struct(User)\n #=> %User{name: \"john\"}\n\n opts = [name: \"meg\"]\n user = struct(User, opts)\n #=> %User{name: \"meg\"}\n\n struct(user, unknown: \"value\")\n #=> %User{name: \"meg\"}\n\n struct(User, %{name: \"meg\"})\n #=> %User{name: \"meg\"}\n\n # String keys are ignored\n struct(User, %{\"name\" => \"meg\"})\n #=> %User{name: \"john\"}\n\n \"\"\"\n @spec struct(module | struct, Enum.t()) :: struct\n def struct(struct, fields \\\\ []) do\n struct(struct, fields, fn\n {:__struct__, _val}, acc ->\n acc\n\n {key, val}, acc ->\n case acc do\n %{^key => _} -> %{acc | key => val}\n _ -> acc\n end\n end)\n end\n\n @doc \"\"\"\n Similar to `struct\/2` but checks for key validity.\n\n The function `struct!\/2` emulates the compile time behaviour\n of structs. This means that:\n\n * when building a struct, as in `struct!(SomeStruct, key: :value)`,\n it is equivalent to `%SomeStruct{key: :value}` and therefore this\n function will check if every given key-value belongs to the struct.\n If the struct is enforcing any key via `@enforce_keys`, those will\n be enforced as well;\n\n * when updating a struct, as in `struct!(%SomeStruct{}, key: :value)`,\n it is equivalent to `%SomeStruct{struct | key: :value}` and therefore this\n function will check if every given key-value belongs to the struct.\n However, updating structs does not enforce keys, as keys are enforced\n only when building;\n\n \"\"\"\n @spec struct!(module | struct, Enum.t()) :: struct\n def struct!(struct, fields \\\\ [])\n\n def struct!(struct, fields) when is_atom(struct) do\n validate_struct!(struct.__struct__(fields), struct, 1)\n end\n\n def struct!(struct, fields) when is_map(struct) do\n struct(struct, fields, fn\n {:__struct__, _}, acc ->\n acc\n\n {key, val}, acc ->\n Map.replace!(acc, key, val)\n end)\n end\n\n defp struct(struct, [], _fun) when is_atom(struct) do\n validate_struct!(struct.__struct__(), struct, 0)\n end\n\n defp struct(struct, fields, fun) when is_atom(struct) do\n struct(validate_struct!(struct.__struct__(), struct, 0), fields, fun)\n end\n\n defp struct(%_{} = struct, [], _fun) do\n struct\n end\n\n defp struct(%_{} = struct, fields, fun) do\n Enum.reduce(fields, struct, fun)\n end\n\n defp validate_struct!(%{__struct__: module} = struct, module, _arity) do\n struct\n end\n\n defp validate_struct!(%{__struct__: struct_name}, module, arity) when is_atom(struct_name) do\n error_message =\n \"expected struct name returned by #{inspect(module)}.__struct__\/#{arity} to be \" <>\n \"#{inspect(module)}, got: #{inspect(struct_name)}\"\n\n :erlang.error(ArgumentError.exception(error_message))\n end\n\n defp validate_struct!(expr, module, arity) do\n error_message =\n \"expected #{inspect(module)}.__struct__\/#{arity} to return a map with a :__struct__ \" <>\n \"key that holds the name of the struct (atom), got: #{inspect(expr)}\"\n\n :erlang.error(ArgumentError.exception(error_message))\n end\n\n @doc \"\"\"\n Returns true if `term` is a struct; otherwise returns `false`.\n\n Allowed in guard tests.\n\n ## Examples\n\n iex> is_struct(URI.parse(\"\/\"))\n true\n\n iex> is_struct(%{})\n false\n\n \"\"\"\n @doc since: \"1.10.0\", guard: true\n defmacro is_struct(term) do\n case __CALLER__.context do\n nil ->\n quote do\n case unquote(term) do\n %_{} -> true\n _ -> false\n end\n end\n\n :match ->\n invalid_match!(:is_struct)\n\n :guard ->\n quote do\n is_map(unquote(term)) and :erlang.is_map_key(:__struct__, unquote(term)) and\n is_atom(:erlang.map_get(:__struct__, unquote(term)))\n end\n end\n end\n\n @doc \"\"\"\n Returns true if `term` is a struct of `name`; otherwise returns `false`.\n\n Allowed in guard tests.\n\n ## Examples\n\n iex> is_struct(URI.parse(\"\/\"), URI)\n true\n\n iex> is_struct(URI.parse(\"\/\"), Macro.Env)\n false\n\n \"\"\"\n @doc since: \"1.11.0\", guard: true\n defmacro is_struct(term, name) do\n case __CALLER__.context do\n nil ->\n quote do\n case unquote(name) do\n name when is_atom(name) ->\n case unquote(term) do\n %{__struct__: ^name} -> true\n _ -> false\n end\n\n _ ->\n raise ArgumentError\n end\n end\n\n :match ->\n invalid_match!(:is_struct)\n\n :guard ->\n quote do\n is_map(unquote(term)) and\n (is_atom(unquote(name)) or :fail) and\n :erlang.is_map_key(:__struct__, unquote(term)) and\n :erlang.map_get(:__struct__, unquote(term)) == unquote(name)\n end\n end\n end\n\n @doc \"\"\"\n Returns true if `term` is an exception; otherwise returns `false`.\n\n Allowed in guard tests.\n\n ## Examples\n\n iex> is_exception(%RuntimeError{})\n true\n\n iex> is_exception(%{})\n false\n\n \"\"\"\n @doc since: \"1.11.0\", guard: true\n defmacro is_exception(term) do\n case __CALLER__.context do\n nil ->\n quote do\n case unquote(term) do\n %_{__exception__: true} -> true\n _ -> false\n end\n end\n\n :match ->\n invalid_match!(:is_exception)\n\n :guard ->\n quote do\n is_map(unquote(term)) and :erlang.is_map_key(:__struct__, unquote(term)) and\n is_atom(:erlang.map_get(:__struct__, unquote(term))) and\n :erlang.is_map_key(:__exception__, unquote(term)) and\n :erlang.map_get(:__exception__, unquote(term)) == true\n end\n end\n end\n\n @doc \"\"\"\n Returns true if `term` is an exception of `name`; otherwise returns `false`.\n\n Allowed in guard tests.\n\n ## Examples\n\n iex> is_exception(%RuntimeError{}, RuntimeError)\n true\n\n iex> is_exception(%RuntimeError{}, Macro.Env)\n false\n\n \"\"\"\n @doc since: \"1.11.0\", guard: true\n defmacro is_exception(term, name) do\n case __CALLER__.context do\n nil ->\n quote do\n case unquote(name) do\n name when is_atom(name) ->\n case unquote(term) do\n %{__struct__: ^name, __exception__: true} -> true\n _ -> false\n end\n\n _ ->\n raise ArgumentError\n end\n end\n\n :match ->\n invalid_match!(:is_exception)\n\n :guard ->\n quote do\n is_map(unquote(term)) and\n (is_atom(unquote(name)) or :fail) and\n :erlang.is_map_key(:__struct__, unquote(term)) and\n :erlang.map_get(:__struct__, unquote(term)) == unquote(name) and\n :erlang.is_map_key(:__exception__, unquote(term)) and\n :erlang.map_get(:__exception__, unquote(term)) == true\n end\n end\n end\n\n @doc \"\"\"\n Pipes `value` into the given `fun`.\n\n In other words, it invokes `fun` with `value` as argument.\n This is most commonly used in pipelines, allowing you\n to pipe a value to a function outside of its first argument.\n\n ### Examples\n\n iex> 1 |> then(fn x -> x * 2 end)\n 2\n \"\"\"\n @doc since: \"1.12.0\"\n defmacro then(value, fun) do\n quote do\n unquote(fun).(unquote(value))\n end\n end\n\n @doc \"\"\"\n Gets a value from a nested structure.\n\n Uses the `Access` module to traverse the structures\n according to the given `keys`, unless the `key` is a\n function, which is detailed in a later section.\n\n ## Examples\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> get_in(users, [\"john\", :age])\n 27\n\n In case any of the keys returns `nil`, `nil` will be returned:\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> get_in(users, [\"unknown\", :age])\n nil\n\n Note that `get_in` exists mostly for convenience and parity with\n functionality found in `put_in` and `update_in`. Given Elixir\n provides pattern matching, it can often be more expressive for\n deep data traversal, for example:\n\n case users do\n %{\"unknown\" => %{age: age}} -> age\n _ -> default_value\n end\n\n ## Functions as keys\n\n If a key is a function, the function will be invoked passing three\n arguments:\n\n * the operation (`:get`)\n * the data to be accessed\n * a function to be invoked next\n\n This means `get_in\/2` can be extended to provide custom lookups.\n In the example below, we use a function to get all the maps inside\n a list:\n\n iex> users = [%{name: \"john\", age: 27}, %{name: \"meg\", age: 23}]\n iex> all = fn :get, data, next -> Enum.map(data, next) end\n iex> get_in(users, [all, :age])\n [27, 23]\n\n If the previous value before invoking the function is `nil`,\n the function *will* receive `nil` as a value and must handle it\n accordingly.\n\n The `Access` module ships with many convenience accessor functions,\n like the `all` anonymous function defined above. See `Access.all\/0`,\n `Access.key\/2`, and others as examples.\n\n ## Working with structs\n\n By default, structs do implement the `Access` behaviour required\n by this function. Therefore, you can't do this:\n\n get_in(some_struct, [:some_key, :nested_key])\n\n The good news is that structs have predefined shape. Therefore,\n you can write instead:\n\n some_struct.some_key.nested_key\n\n If, by any chance, `some_key` can return nil, you can always\n fallback to pattern matching to provide nested struct handling:\n\n case some_struct do\n %{some_key: %{nested_key: value}} -> value\n %{} -> nil\n end\n\n \"\"\"\n @spec get_in(Access.t(), nonempty_list(term)) :: term\n def get_in(data, keys)\n\n def get_in(data, [h]) when is_function(h), do: h.(:get, data, & &1)\n def get_in(data, [h | t]) when is_function(h), do: h.(:get, data, &get_in(&1, t))\n\n def get_in(nil, [_]), do: nil\n def get_in(nil, [_ | t]), do: get_in(nil, t)\n\n def get_in(data, [h]), do: Access.get(data, h)\n def get_in(data, [h | t]), do: get_in(Access.get(data, h), t)\n\n @doc \"\"\"\n Puts a value in a nested structure.\n\n Uses the `Access` module to traverse the structures\n according to the given `keys`, unless the `key` is a\n function. If the key is a function, it will be invoked\n as specified in `get_and_update_in\/3`.\n\n ## Examples\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> put_in(users, [\"john\", :age], 28)\n %{\"john\" => %{age: 28}, \"meg\" => %{age: 23}}\n\n In case any of the entries in the middle returns `nil`,\n an error will be raised when trying to access it next.\n \"\"\"\n @spec put_in(Access.t(), nonempty_list(term), term) :: Access.t()\n def put_in(data, [_ | _] = keys, value) do\n elem(get_and_update_in(data, keys, fn _ -> {nil, value} end), 1)\n end\n\n @doc \"\"\"\n Updates a key in a nested structure.\n\n Uses the `Access` module to traverse the structures\n according to the given `keys`, unless the `key` is a\n function. If the key is a function, it will be invoked\n as specified in `get_and_update_in\/3`.\n\n `data` is a nested structure (that is, a map, keyword\n list, or struct that implements the `Access` behaviour).\n The `fun` argument receives the value of `key` (or `nil`\n if `key` is not present) and the result replaces the value\n in the structure.\n\n ## Examples\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> update_in(users, [\"john\", :age], &(&1 + 1))\n %{\"john\" => %{age: 28}, \"meg\" => %{age: 23}}\n\n In case any of the entries in the middle returns `nil`,\n an error will be raised when trying to access it next.\n \"\"\"\n @spec update_in(Access.t(), nonempty_list(term), (term -> term)) :: Access.t()\n def update_in(data, [_ | _] = keys, fun) when is_function(fun) do\n elem(get_and_update_in(data, keys, fn x -> {nil, fun.(x)} end), 1)\n end\n\n @doc \"\"\"\n Gets a value and updates a nested structure.\n\n `data` is a nested structure (that is, a map, keyword\n list, or struct that implements the `Access` behaviour).\n\n The `fun` argument receives the value of `key` (or `nil` if `key`\n is not present) and must return one of the following values:\n\n * a two-element tuple `{get_value, new_value}`. In this case,\n `get_value` is the retrieved value which can possibly be operated on before\n being returned. `new_value` is the new value to be stored under `key`.\n\n * `:pop`, which implies that the current value under `key`\n should be removed from the structure and returned.\n\n This function uses the `Access` module to traverse the structures\n according to the given `keys`, unless the `key` is a function,\n which is detailed in a later section.\n\n ## Examples\n\n This function is useful when there is a need to retrieve the current\n value (or something calculated in function of the current value) and\n update it at the same time. For example, it could be used to read the\n current age of a user while increasing it by one in one pass:\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> get_and_update_in(users, [\"john\", :age], &{&1, &1 + 1})\n {27, %{\"john\" => %{age: 28}, \"meg\" => %{age: 23}}}\n\n ## Functions as keys\n\n If a key is a function, the function will be invoked passing three\n arguments:\n\n * the operation (`:get_and_update`)\n * the data to be accessed\n * a function to be invoked next\n\n This means `get_and_update_in\/3` can be extended to provide custom\n lookups. The downside is that functions cannot be stored as keys\n in the accessed data structures.\n\n When one of the keys is a function, the function is invoked.\n In the example below, we use a function to get and increment all\n ages inside a list:\n\n iex> users = [%{name: \"john\", age: 27}, %{name: \"meg\", age: 23}]\n iex> all = fn :get_and_update, data, next ->\n ...> data |> Enum.map(next) |> Enum.unzip()\n ...> end\n iex> get_and_update_in(users, [all, :age], &{&1, &1 + 1})\n {[27, 23], [%{name: \"john\", age: 28}, %{name: \"meg\", age: 24}]}\n\n If the previous value before invoking the function is `nil`,\n the function *will* receive `nil` as a value and must handle it\n accordingly (be it by failing or providing a sane default).\n\n The `Access` module ships with many convenience accessor functions,\n like the `all` anonymous function defined above. See `Access.all\/0`,\n `Access.key\/2`, and others as examples.\n \"\"\"\n @spec get_and_update_in(\n structure :: Access.t(),\n keys,\n (term -> {get_value, update_value} | :pop)\n ) :: {get_value, structure :: Access.t()}\n when keys: nonempty_list(any),\n get_value: var,\n update_value: term\n def get_and_update_in(data, keys, fun)\n\n def get_and_update_in(data, [head], fun) when is_function(head, 3),\n do: head.(:get_and_update, data, fun)\n\n def get_and_update_in(data, [head | tail], fun) when is_function(head, 3),\n do: head.(:get_and_update, data, &get_and_update_in(&1, tail, fun))\n\n def get_and_update_in(data, [head], fun) when is_function(fun, 1),\n do: Access.get_and_update(data, head, fun)\n\n def get_and_update_in(data, [head | tail], fun) when is_function(fun, 1),\n do: Access.get_and_update(data, head, &get_and_update_in(&1, tail, fun))\n\n @doc \"\"\"\n Pops a key from the given nested structure.\n\n Uses the `Access` protocol to traverse the structures\n according to the given `keys`, unless the `key` is a\n function. If the key is a function, it will be invoked\n as specified in `get_and_update_in\/3`.\n\n ## Examples\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> pop_in(users, [\"john\", :age])\n {27, %{\"john\" => %{}, \"meg\" => %{age: 23}}}\n\n In case any entry returns `nil`, its key will be removed\n and the deletion will be considered a success.\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> pop_in(users, [\"jane\", :age])\n {nil, %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}}\n\n \"\"\"\n @spec pop_in(data, nonempty_list(Access.get_and_update_fun(term, data) | term)) :: {term, data}\n when data: Access.container()\n def pop_in(data, keys)\n\n def pop_in(nil, [key | _]) do\n raise ArgumentError, \"could not pop key #{inspect(key)} on a nil value\"\n end\n\n def pop_in(data, [_ | _] = keys) do\n pop_in_data(data, keys)\n end\n\n defp pop_in_data(nil, [_ | _]), do: :pop\n\n defp pop_in_data(data, [fun]) when is_function(fun),\n do: fun.(:get_and_update, data, fn _ -> :pop end)\n\n defp pop_in_data(data, [fun | tail]) when is_function(fun),\n do: fun.(:get_and_update, data, &pop_in_data(&1, tail))\n\n defp pop_in_data(data, [key]), do: Access.pop(data, key)\n\n defp pop_in_data(data, [key | tail]),\n do: Access.get_and_update(data, key, &pop_in_data(&1, tail))\n\n @doc \"\"\"\n Puts a value in a nested structure via the given `path`.\n\n This is similar to `put_in\/3`, except the path is extracted via\n a macro rather than passing a list. For example:\n\n put_in(opts[:foo][:bar], :baz)\n\n Is equivalent to:\n\n put_in(opts, [:foo, :bar], :baz)\n\n This also works with nested structs and the `struct.path.to.value` way to specify\n paths:\n\n put_in(struct.foo.bar, :baz)\n\n Note that in order for this macro to work, the complete path must always\n be visible by this macro. For more information about the supported path\n expressions, please check `get_and_update_in\/2` docs.\n\n ## Examples\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> put_in(users[\"john\"][:age], 28)\n %{\"john\" => %{age: 28}, \"meg\" => %{age: 23}}\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> put_in(users[\"john\"].age, 28)\n %{\"john\" => %{age: 28}, \"meg\" => %{age: 23}}\n\n \"\"\"\n defmacro put_in(path, value) do\n case unnest(path, [], true, \"put_in\/2\") do\n {[h | t], true} ->\n nest_update_in(h, t, quote(do: fn _ -> unquote(value) end))\n\n {[h | t], false} ->\n expr = nest_get_and_update_in(h, t, quote(do: fn _ -> {nil, unquote(value)} end))\n quote(do: :erlang.element(2, unquote(expr)))\n end\n end\n\n @doc \"\"\"\n Pops a key from the nested structure via the given `path`.\n\n This is similar to `pop_in\/2`, except the path is extracted via\n a macro rather than passing a list. For example:\n\n pop_in(opts[:foo][:bar])\n\n Is equivalent to:\n\n pop_in(opts, [:foo, :bar])\n\n Note that in order for this macro to work, the complete path must always\n be visible by this macro. For more information about the supported path\n expressions, please check `get_and_update_in\/2` docs.\n\n ## Examples\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> pop_in(users[\"john\"][:age])\n {27, %{\"john\" => %{}, \"meg\" => %{age: 23}}}\n\n iex> users = %{john: %{age: 27}, meg: %{age: 23}}\n iex> pop_in(users.john[:age])\n {27, %{john: %{}, meg: %{age: 23}}}\n\n In case any entry returns `nil`, its key will be removed\n and the deletion will be considered a success.\n \"\"\"\n defmacro pop_in(path) do\n {[h | t], _} = unnest(path, [], true, \"pop_in\/1\")\n nest_pop_in(:map, h, t)\n end\n\n @doc \"\"\"\n Updates a nested structure via the given `path`.\n\n This is similar to `update_in\/3`, except the path is extracted via\n a macro rather than passing a list. For example:\n\n update_in(opts[:foo][:bar], &(&1 + 1))\n\n Is equivalent to:\n\n update_in(opts, [:foo, :bar], &(&1 + 1))\n\n This also works with nested structs and the `struct.path.to.value` way to specify\n paths:\n\n update_in(struct.foo.bar, &(&1 + 1))\n\n Note that in order for this macro to work, the complete path must always\n be visible by this macro. For more information about the supported path\n expressions, please check `get_and_update_in\/2` docs.\n\n ## Examples\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> update_in(users[\"john\"][:age], &(&1 + 1))\n %{\"john\" => %{age: 28}, \"meg\" => %{age: 23}}\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> update_in(users[\"john\"].age, &(&1 + 1))\n %{\"john\" => %{age: 28}, \"meg\" => %{age: 23}}\n\n \"\"\"\n defmacro update_in(path, fun) do\n case unnest(path, [], true, \"update_in\/2\") do\n {[h | t], true} ->\n nest_update_in(h, t, fun)\n\n {[h | t], false} ->\n expr = nest_get_and_update_in(h, t, quote(do: fn x -> {nil, unquote(fun).(x)} end))\n quote(do: :erlang.element(2, unquote(expr)))\n end\n end\n\n @doc \"\"\"\n Gets a value and updates a nested data structure via the given `path`.\n\n This is similar to `get_and_update_in\/3`, except the path is extracted\n via a macro rather than passing a list. For example:\n\n get_and_update_in(opts[:foo][:bar], &{&1, &1 + 1})\n\n Is equivalent to:\n\n get_and_update_in(opts, [:foo, :bar], &{&1, &1 + 1})\n\n This also works with nested structs and the `struct.path.to.value` way to specify\n paths:\n\n get_and_update_in(struct.foo.bar, &{&1, &1 + 1})\n\n Note that in order for this macro to work, the complete path must always\n be visible by this macro. See the \"Paths\" section below.\n\n ## Examples\n\n iex> users = %{\"john\" => %{age: 27}, \"meg\" => %{age: 23}}\n iex> get_and_update_in(users[\"john\"].age, &{&1, &1 + 1})\n {27, %{\"john\" => %{age: 28}, \"meg\" => %{age: 23}}}\n\n ## Paths\n\n A path may start with a variable, local or remote call, and must be\n followed by one or more:\n\n * `foo[bar]` - accesses the key `bar` in `foo`; in case `foo` is nil,\n `nil` is returned\n\n * `foo.bar` - accesses a map\/struct field; in case the field is not\n present, an error is raised\n\n Here are some valid paths:\n\n users[\"john\"][:age]\n users[\"john\"].age\n User.all()[\"john\"].age\n all_users()[\"john\"].age\n\n Here are some invalid ones:\n\n # Does a remote call after the initial value\n users[\"john\"].do_something(arg1, arg2)\n\n # Does not access any key or field\n users\n\n \"\"\"\n defmacro get_and_update_in(path, fun) do\n {[h | t], _} = unnest(path, [], true, \"get_and_update_in\/2\")\n nest_get_and_update_in(h, t, fun)\n end\n\n defp nest_update_in([], fun), do: fun\n\n defp nest_update_in(list, fun) do\n quote do\n fn x -> unquote(nest_update_in(quote(do: x), list, fun)) end\n end\n end\n\n defp nest_update_in(h, [{:map, key} | t], fun) do\n quote do\n Map.update!(unquote(h), unquote(key), unquote(nest_update_in(t, fun)))\n end\n end\n\n defp nest_get_and_update_in([], fun), do: fun\n\n defp nest_get_and_update_in(list, fun) do\n quote do\n fn x -> unquote(nest_get_and_update_in(quote(do: x), list, fun)) end\n end\n end\n\n defp nest_get_and_update_in(h, [{:access, key} | t], fun) do\n quote do\n Access.get_and_update(unquote(h), unquote(key), unquote(nest_get_and_update_in(t, fun)))\n end\n end\n\n defp nest_get_and_update_in(h, [{:map, key} | t], fun) do\n quote do\n Map.get_and_update!(unquote(h), unquote(key), unquote(nest_get_and_update_in(t, fun)))\n end\n end\n\n defp nest_pop_in(kind, list) do\n quote do\n fn x -> unquote(nest_pop_in(kind, quote(do: x), list)) end\n end\n end\n\n defp nest_pop_in(:map, h, [{:access, key}]) do\n quote do\n case unquote(h) do\n nil -> {nil, nil}\n h -> Access.pop(h, unquote(key))\n end\n end\n end\n\n defp nest_pop_in(_, _, [{:map, key}]) do\n raise ArgumentError,\n \"cannot use pop_in when the last segment is a map\/struct field. \" <>\n \"This would effectively remove the field #{inspect(key)} from the map\/struct\"\n end\n\n defp nest_pop_in(_, h, [{:map, key} | t]) do\n quote do\n Map.get_and_update!(unquote(h), unquote(key), unquote(nest_pop_in(:map, t)))\n end\n end\n\n defp nest_pop_in(_, h, [{:access, key}]) do\n quote do\n case unquote(h) do\n nil -> :pop\n h -> Access.pop(h, unquote(key))\n end\n end\n end\n\n defp nest_pop_in(_, h, [{:access, key} | t]) do\n quote do\n Access.get_and_update(unquote(h), unquote(key), unquote(nest_pop_in(:access, t)))\n end\n end\n\n defp unnest({{:., _, [Access, :get]}, _, [expr, key]}, acc, _all_map?, kind) do\n unnest(expr, [{:access, key} | acc], false, kind)\n end\n\n defp unnest({{:., _, [expr, key]}, _, []}, acc, all_map?, kind)\n when is_tuple(expr) and :erlang.element(1, expr) != :__aliases__ and\n :erlang.element(1, expr) != :__MODULE__ do\n unnest(expr, [{:map, key} | acc], all_map?, kind)\n end\n\n defp unnest(other, [], _all_map?, kind) do\n raise ArgumentError,\n \"expected expression given to #{kind} to access at least one element, \" <>\n \"got: #{Macro.to_string(other)}\"\n end\n\n defp unnest(other, acc, all_map?, kind) do\n case proper_start?(other) do\n true ->\n {[other | acc], all_map?}\n\n false ->\n raise ArgumentError,\n \"expression given to #{kind} must start with a variable, local or remote call \" <>\n \"and be followed by an element access, got: #{Macro.to_string(other)}\"\n end\n end\n\n defp proper_start?({{:., _, [expr, _]}, _, _args})\n when is_atom(expr)\n when :erlang.element(1, expr) == :__aliases__\n when :erlang.element(1, expr) == :__MODULE__,\n do: true\n\n defp proper_start?({atom, _, _args})\n when is_atom(atom),\n do: true\n\n defp proper_start?(other), do: not is_tuple(other)\n\n @doc \"\"\"\n Converts the argument to a string according to the\n `String.Chars` protocol.\n\n This is the function invoked when there is string interpolation.\n\n ## Examples\n\n iex> to_string(:foo)\n \"foo\"\n\n \"\"\"\n defmacro to_string(term) do\n quote(do: :\"Elixir.String.Chars\".to_string(unquote(term)))\n end\n\n @doc \"\"\"\n Converts the given term to a charlist according to the `List.Chars` protocol.\n\n ## Examples\n\n iex> to_charlist(:foo)\n 'foo'\n\n \"\"\"\n defmacro to_charlist(term) do\n quote(do: List.Chars.to_charlist(unquote(term)))\n end\n\n @doc \"\"\"\n Returns `true` if `term` is `nil`, `false` otherwise.\n\n Allowed in guard clauses.\n\n ## Examples\n\n iex> is_nil(1)\n false\n\n iex> is_nil(nil)\n true\n\n \"\"\"\n @doc guard: true\n defmacro is_nil(term) do\n quote(do: unquote(term) == nil)\n end\n\n @doc \"\"\"\n A convenience macro that checks if the right side (an expression) matches the\n left side (a pattern).\n\n ## Examples\n\n iex> match?(1, 1)\n true\n\n iex> match?({1, _}, {1, 2})\n true\n\n iex> map = %{a: 1, b: 2}\n iex> match?(%{a: _}, map)\n true\n\n iex> a = 1\n iex> match?(^a, 1)\n true\n\n `match?\/2` is very useful when filtering or finding a value in an enumerable:\n\n iex> list = [a: 1, b: 2, a: 3]\n iex> Enum.filter(list, &match?({:a, _}, &1))\n [a: 1, a: 3]\n\n Guard clauses can also be given to the match:\n\n iex> list = [a: 1, b: 2, a: 3]\n iex> Enum.filter(list, &match?({:a, x} when x < 2, &1))\n [a: 1]\n\n However, variables assigned in the match will not be available\n outside of the function call (unlike regular pattern matching with the `=`\n operator):\n\n iex> match?(_x, 1)\n true\n iex> binding()\n []\n\n \"\"\"\n defmacro match?(pattern, expr) do\n success =\n quote do\n unquote(pattern) -> true\n end\n\n failure =\n quote generated: true do\n _ -> false\n end\n\n {:case, [], [expr, [do: success ++ failure]]}\n end\n\n @doc \"\"\"\n Module attribute unary operator. Reads and writes attributes in the current module.\n\n The canonical example for attributes is annotating that a module\n implements an OTP behaviour, such as `GenServer`:\n\n defmodule MyServer do\n @behaviour GenServer\n # ... callbacks ...\n end\n\n By default Elixir supports all the module attributes supported by Erlang, but\n custom attributes can be used as well:\n\n defmodule MyServer do\n @my_data 13\n IO.inspect(@my_data)\n #=> 13\n end\n\n Unlike Erlang, such attributes are not stored in the module by default since\n it is common in Elixir to use custom attributes to store temporary data that\n will be available at compile-time. Custom attributes may be configured to\n behave closer to Erlang by using `Module.register_attribute\/3`.\n\n Finally, note that attributes can also be read inside functions:\n\n defmodule MyServer do\n @my_data 11\n def first_data, do: @my_data\n @my_data 13\n def second_data, do: @my_data\n end\n\n MyServer.first_data()\n #=> 11\n\n MyServer.second_data()\n #=> 13\n\n It is important to note that reading an attribute takes a snapshot of\n its current value. In other words, the value is read at compilation\n time and not at runtime. Check the `Module` module for other functions\n to manipulate module attributes.\n \"\"\"\n defmacro @expr\n\n defmacro @{:__aliases__, _meta, _args} do\n raise ArgumentError, \"module attributes set via @ cannot start with an uppercase letter\"\n end\n\n defmacro @{name, meta, args} do\n assert_module_scope(__CALLER__, :@, 1)\n function? = __CALLER__.function != nil\n\n cond do\n # Check for Macro as it is compiled later than Kernel\n not bootstrapped?(Macro) ->\n nil\n\n not function? and __CALLER__.context == :match ->\n raise ArgumentError,\n \"\"\"\n invalid write attribute syntax. If you want to define an attribute, don't do this:\n\n @foo = :value\n\n Instead, do this:\n\n @foo :value\n \"\"\"\n\n # Typespecs attributes are currently special cased by the compiler\n is_list(args) and typespec?(name) ->\n case bootstrapped?(Kernel.Typespec) do\n false ->\n :ok\n\n true ->\n pos = :elixir_locals.cache_env(__CALLER__)\n %{line: line, file: file, module: module} = __CALLER__\n\n quote do\n Kernel.Typespec.deftypespec(\n unquote(name),\n unquote(Macro.escape(hd(args), unquote: true)),\n unquote(line),\n unquote(file),\n unquote(module),\n unquote(pos)\n )\n end\n end\n\n true ->\n do_at(args, meta, name, function?, __CALLER__)\n end\n end\n\n # @attribute(value)\n defp do_at([arg], meta, name, function?, env) do\n line =\n case :lists.keymember(:context, 1, meta) do\n true -> nil\n false -> env.line\n end\n\n cond do\n function? ->\n raise ArgumentError, \"cannot set attribute @#{name} inside function\/macro\"\n\n name == :behavior ->\n warn_message = \"@behavior attribute is not supported, please use @behaviour instead\"\n IO.warn(warn_message, Macro.Env.stacktrace(env))\n\n :lists.member(name, [:moduledoc, :typedoc, :doc]) ->\n arg = {env.line, arg}\n\n quote do\n Module.__put_attribute__(__MODULE__, unquote(name), unquote(arg), unquote(line))\n end\n\n true ->\n quote do\n Module.__put_attribute__(__MODULE__, unquote(name), unquote(arg), unquote(line))\n end\n end\n end\n\n # @attribute()\n defp do_at([], meta, name, function?, env) do\n IO.warn(\n \"the @#{name}() notation (with parenthesis) is deprecated, please use @#{name} (without parenthesis) instead\",\n Macro.Env.stacktrace(env)\n )\n\n do_at(nil, meta, name, function?, env)\n end\n\n # @attribute\n defp do_at(args, _meta, name, function?, env) when is_atom(args) do\n line = env.line\n doc_attr? = :lists.member(name, [:moduledoc, :typedoc, :doc])\n\n case function? do\n true ->\n value =\n case Module.__get_attribute__(env.module, name, line) do\n {_, doc} when doc_attr? -> doc\n other -> other\n end\n\n try do\n :elixir_quote.escape(value, :default, false)\n rescue\n ex in [ArgumentError] ->\n raise ArgumentError,\n \"cannot inject attribute @#{name} into function\/macro because \" <>\n Exception.message(ex)\n end\n\n false when doc_attr? ->\n quote do\n case Module.__get_attribute__(__MODULE__, unquote(name), unquote(line)) do\n {_, doc} -> doc\n other -> other\n end\n end\n\n false ->\n quote do\n Module.__get_attribute__(__MODULE__, unquote(name), unquote(line))\n end\n end\n end\n\n # Error cases\n defp do_at([{call, meta, ctx_or_args}, [{:do, _} | _] = kw], _meta, name, _function?, _env) do\n args =\n case is_atom(ctx_or_args) do\n true -> []\n false -> ctx_or_args\n end\n\n code = \"\\n@#{name} (#{Macro.to_string({call, meta, args ++ [kw]})})\"\n\n raise ArgumentError, \"\"\"\n expected 0 or 1 argument for @#{name}, got 2.\n\n It seems you are trying to use the do-syntax with @module attributes \\\n but the do-block is binding to the attribute name. You probably want \\\n to wrap the argument value in parentheses, like this:\n #{String.replace(code, \"\\n\", \"\\n \")}\n \"\"\"\n end\n\n defp do_at(args, _meta, name, _function?, _env) do\n raise ArgumentError, \"expected 0 or 1 argument for @#{name}, got: #{length(args)}\"\n end\n\n defp typespec?(:type), do: true\n defp typespec?(:typep), do: true\n defp typespec?(:opaque), do: true\n defp typespec?(:spec), do: true\n defp typespec?(:callback), do: true\n defp typespec?(:macrocallback), do: true\n defp typespec?(_), do: false\n\n @doc \"\"\"\n Returns the binding for the given context as a keyword list.\n\n In the returned result, keys are variable names and values are the\n corresponding variable values.\n\n If the given `context` is `nil` (by default it is), the binding for the\n current context is returned.\n\n ## Examples\n\n iex> x = 1\n iex> binding()\n [x: 1]\n iex> x = 2\n iex> binding()\n [x: 2]\n\n iex> binding(:foo)\n []\n iex> var!(x, :foo) = 1\n 1\n iex> binding(:foo)\n [x: 1]\n\n \"\"\"\n defmacro binding(context \\\\ nil) do\n in_match? = Macro.Env.in_match?(__CALLER__)\n\n bindings =\n for {v, c} <- Macro.Env.vars(__CALLER__), c == context do\n {v, wrap_binding(in_match?, {v, [generated: true], c})}\n end\n\n :lists.sort(bindings)\n end\n\n defp wrap_binding(true, var) do\n quote(do: ^unquote(var))\n end\n\n defp wrap_binding(_, var) do\n var\n end\n\n @doc \"\"\"\n Provides an `if\/2` macro.\n\n This macro expects the first argument to be a condition and the second\n argument to be a keyword list.\n\n ## One-liner examples\n\n if(foo, do: bar)\n\n In the example above, `bar` will be returned if `foo` evaluates to\n a truthy value (neither `false` nor `nil`). Otherwise, `nil` will be\n returned.\n\n An `else` option can be given to specify the opposite:\n\n if(foo, do: bar, else: baz)\n\n ## Blocks examples\n\n It's also possible to pass a block to the `if\/2` macro. The first\n example above would be translated to:\n\n if foo do\n bar\n end\n\n Note that `do\/end` become delimiters. The second example would\n translate to:\n\n if foo do\n bar\n else\n baz\n end\n\n In order to compare more than two clauses, the `cond\/1` macro has to be used.\n \"\"\"\n defmacro if(condition, clauses) do\n build_if(condition, clauses)\n end\n\n defp build_if(condition, do: do_clause) do\n build_if(condition, do: do_clause, else: nil)\n end\n\n defp build_if(condition, do: do_clause, else: else_clause) do\n optimize_boolean(\n quote do\n case unquote(condition) do\n x when :\"Elixir.Kernel\".in(x, [false, nil]) -> unquote(else_clause)\n _ -> unquote(do_clause)\n end\n end\n )\n end\n\n defp build_if(_condition, _arguments) do\n raise ArgumentError,\n \"invalid or duplicate keys for if, only \\\"do\\\" and an optional \\\"else\\\" are permitted\"\n end\n\n @doc \"\"\"\n Provides an `unless` macro.\n\n This macro evaluates and returns the `do` block passed in as the second\n argument if `condition` evaluates to a falsy value (`false` or `nil`).\n Otherwise, it returns the value of the `else` block if present or `nil` if not.\n\n See also `if\/2`.\n\n ## Examples\n\n iex> unless(Enum.empty?([]), do: \"Hello\")\n nil\n\n iex> unless(Enum.empty?([1, 2, 3]), do: \"Hello\")\n \"Hello\"\n\n iex> unless Enum.sum([2, 2]) == 5 do\n ...> \"Math still works\"\n ...> else\n ...> \"Math is broken\"\n ...> end\n \"Math still works\"\n\n \"\"\"\n defmacro unless(condition, clauses) do\n build_unless(condition, clauses)\n end\n\n defp build_unless(condition, do: do_clause) do\n build_unless(condition, do: do_clause, else: nil)\n end\n\n defp build_unless(condition, do: do_clause, else: else_clause) do\n quote do\n if(unquote(condition), do: unquote(else_clause), else: unquote(do_clause))\n end\n end\n\n defp build_unless(_condition, _arguments) do\n raise ArgumentError,\n \"invalid or duplicate keys for unless, \" <>\n \"only \\\"do\\\" and an optional \\\"else\\\" are permitted\"\n end\n\n @doc \"\"\"\n Destructures two lists, assigning each term in the\n right one to the matching term in the left one.\n\n Unlike pattern matching via `=`, if the sizes of the left\n and right lists don't match, destructuring simply stops\n instead of raising an error.\n\n ## Examples\n\n iex> destructure([x, y, z], [1, 2, 3, 4, 5])\n iex> {x, y, z}\n {1, 2, 3}\n\n In the example above, even though the right list has more entries than the\n left one, destructuring works fine. If the right list is smaller, the\n remaining elements are simply set to `nil`:\n\n iex> destructure([x, y, z], [1])\n iex> {x, y, z}\n {1, nil, nil}\n\n The left-hand side supports any expression you would use\n on the left-hand side of a match:\n\n x = 1\n destructure([^x, y, z], [1, 2, 3])\n\n The example above will only work if `x` matches the first value in the right\n list. Otherwise, it will raise a `MatchError` (like the `=` operator would\n do).\n \"\"\"\n defmacro destructure(left, right) when is_list(left) do\n quote do\n unquote(left) = Kernel.Utils.destructure(unquote(right), unquote(length(left)))\n end\n end\n\n @doc \"\"\"\n Range creation operator. Returns a range with the specified `first` and `last` integers.\n\n If last is larger than first, the range will be increasing from\n first to last. If first is larger than last, the range will be\n decreasing from first to last. If first is equal to last, the range\n will contain one element, which is the number itself.\n\n ## Examples\n\n iex> 0 in 1..3\n false\n\n iex> 1 in 1..3\n true\n\n iex> 2 in 1..3\n true\n\n iex> 3 in 1..3\n true\n\n \"\"\"\n defmacro first..last do\n case bootstrapped?(Macro) do\n true ->\n first = Macro.expand(first, __CALLER__)\n last = Macro.expand(last, __CALLER__)\n range(__CALLER__.context, first, last)\n\n false ->\n range(__CALLER__.context, first, last)\n end\n end\n\n defp range(_context, first, last) when is_integer(first) and is_integer(last) do\n {:%{}, [], [__struct__: Elixir.Range, first: first, last: last]}\n end\n\n defp range(_context, first, last)\n when is_float(first) or is_float(last) or is_atom(first) or is_atom(last) or\n is_binary(first) or is_binary(last) or is_list(first) or is_list(last) do\n raise ArgumentError,\n \"ranges (first..last) expect both sides to be integers, \" <>\n \"got: #{Macro.to_string({:.., [], [first, last]})}\"\n end\n\n defp range(nil, first, last) do\n quote(do: Elixir.Range.new(unquote(first), unquote(last)))\n end\n\n defp range(_, first, last) do\n {:%{}, [], [__struct__: Elixir.Range, first: first, last: last]}\n end\n\n @doc \"\"\"\n Boolean \"and\" operator.\n\n Provides a short-circuit operator that evaluates and returns\n the second expression only if the first one evaluates to a truthy value\n (neither `false` nor `nil`). Returns the first expression\n otherwise.\n\n Not allowed in guard clauses.\n\n ## Examples\n\n iex> Enum.empty?([]) && Enum.empty?([])\n true\n\n iex> List.first([]) && true\n nil\n\n iex> Enum.empty?([]) && List.first([1])\n 1\n\n iex> false && throw(:bad)\n false\n\n Note that, unlike `and\/2`, this operator accepts any expression\n as the first argument, not only booleans.\n \"\"\"\n defmacro left && right do\n assert_no_match_or_guard_scope(__CALLER__.context, \"&&\")\n\n quote do\n case unquote(left) do\n x when :\"Elixir.Kernel\".in(x, [false, nil]) ->\n x\n\n _ ->\n unquote(right)\n end\n end\n end\n\n @doc \"\"\"\n Boolean \"or\" operator.\n\n Provides a short-circuit operator that evaluates and returns the second\n expression only if the first one does not evaluate to a truthy value (that is,\n it is either `nil` or `false`). Returns the first expression otherwise.\n\n Not allowed in guard clauses.\n\n ## Examples\n\n iex> Enum.empty?([1]) || Enum.empty?([1])\n false\n\n iex> List.first([]) || true\n true\n\n iex> Enum.empty?([1]) || 1\n 1\n\n iex> Enum.empty?([]) || throw(:bad)\n true\n\n Note that, unlike `or\/2`, this operator accepts any expression\n as the first argument, not only booleans.\n \"\"\"\n defmacro left || right do\n assert_no_match_or_guard_scope(__CALLER__.context, \"||\")\n\n quote do\n case unquote(left) do\n x when :\"Elixir.Kernel\".in(x, [false, nil]) ->\n unquote(right)\n\n x ->\n x\n end\n end\n end\n\n @doc \"\"\"\n Pipe operator.\n\n This operator introduces the expression on the left-hand side as\n the first argument to the function call on the right-hand side.\n\n ## Examples\n\n iex> [1, [2], 3] |> List.flatten()\n [1, 2, 3]\n\n The example above is the same as calling `List.flatten([1, [2], 3])`.\n\n The `|>` operator is mostly useful when there is a desire to execute a series\n of operations resembling a pipeline:\n\n iex> [1, [2], 3] |> List.flatten() |> Enum.map(fn x -> x * 2 end)\n [2, 4, 6]\n\n In the example above, the list `[1, [2], 3]` is passed as the first argument\n to the `List.flatten\/1` function, then the flattened list is passed as the\n first argument to the `Enum.map\/2` function which doubles each element of the\n list.\n\n In other words, the expression above simply translates to:\n\n Enum.map(List.flatten([1, [2], 3]), fn x -> x * 2 end)\n\n ## Pitfalls\n\n There are two common pitfalls when using the pipe operator.\n\n The first one is related to operator precedence. For example,\n the following expression:\n\n String.graphemes \"Hello\" |> Enum.reverse\n\n Translates to:\n\n String.graphemes(\"Hello\" |> Enum.reverse())\n\n which results in an error as the `Enumerable` protocol is not defined\n for binaries. Adding explicit parentheses resolves the ambiguity:\n\n String.graphemes(\"Hello\") |> Enum.reverse()\n\n Or, even better:\n\n \"Hello\" |> String.graphemes() |> Enum.reverse()\n\n The second limitation is that Elixir always pipes to a function\n call. Therefore, to pipe into an anonymous function, you need to\n invoke it:\n\n some_fun = &Regex.replace(~r\/l\/, &1, \"L\")\n \"Hello\" |> some_fun.()\n\n Alternatively, you can use `then\/2` for the same effect:\n\n some_fun = &Regex.replace(~r\/l\/, &1, \"L\")\n \"Hello\" |> then(some_fun)\n\n `then\/2` is most commonly used when you want to pipe to a function\n but the value is expected outside of the first argument, such as\n above. By replacing `some_fun` by its value, we get:\n\n \"Hello\" |> then(&Regex.replace(~r\/l\/,&1, \"L\"))\n\n \"\"\"\n defmacro left |> right do\n [{h, _} | t] = Macro.unpipe({:|>, [], [left, right]})\n\n fun = fn {x, pos}, acc ->\n Macro.pipe(acc, x, pos)\n end\n\n :lists.foldl(fun, h, t)\n end\n\n @doc \"\"\"\n Returns `true` if `module` is loaded and contains a\n public `function` with the given `arity`, otherwise `false`.\n\n Note that this function does not load the module in case\n it is not loaded. Check `Code.ensure_loaded\/1` for more\n information.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> function_exported?(Enum, :map, 2)\n true\n\n iex> function_exported?(Enum, :map, 10)\n false\n\n iex> function_exported?(List, :to_string, 1)\n true\n \"\"\"\n @spec function_exported?(module, atom, arity) :: boolean\n def function_exported?(module, function, arity) do\n :erlang.function_exported(module, function, arity)\n end\n\n @doc \"\"\"\n Returns `true` if `module` is loaded and contains a\n public `macro` with the given `arity`, otherwise `false`.\n\n Note that this function does not load the module in case\n it is not loaded. Check `Code.ensure_loaded\/1` for more\n information.\n\n If `module` is an Erlang module (as opposed to an Elixir module), this\n function always returns `false`.\n\n ## Examples\n\n iex> macro_exported?(Kernel, :use, 2)\n true\n\n iex> macro_exported?(:erlang, :abs, 1)\n false\n\n \"\"\"\n @spec macro_exported?(module, atom, arity) :: boolean\n def macro_exported?(module, macro, arity)\n when is_atom(module) and is_atom(macro) and is_integer(arity) and\n (arity >= 0 and arity <= 255) do\n function_exported?(module, :__info__, 1) and\n :lists.member({macro, arity}, module.__info__(:macros))\n end\n\n @doc \"\"\"\n Membership operator. Checks if the element on the left-hand side is a member of the\n collection on the right-hand side.\n\n ## Examples\n\n iex> x = 1\n iex> x in [1, 2, 3]\n true\n\n This operator (which is a macro) simply translates to a call to\n `Enum.member?\/2`. The example above would translate to:\n\n Enum.member?([1, 2, 3], x)\n\n Elixir also supports `left not in right`, which evaluates to\n `not(left in right)`:\n\n iex> x = 1\n iex> x not in [1, 2, 3]\n false\n\n ## Guards\n\n The `in\/2` operator (as well as `not in`) can be used in guard clauses as\n long as the right-hand side is a range or a list. In such cases, Elixir will\n expand the operator to a valid guard expression. For example:\n\n when x in [1, 2, 3]\n\n translates to:\n\n when x === 1 or x === 2 or x === 3\n\n When using ranges:\n\n when x in 1..3\n\n translates to:\n\n when is_integer(x) and x >= 1 and x <= 3\n\n Note that only integers can be considered inside a range by `in`.\n\n ### AST considerations\n\n `left not in right` is parsed by the compiler into the AST:\n\n {:not, _, [{:in, _, [left, right]}]}\n\n This is the same AST as `not(left in right)`.\n\n Additionally, `Macro.to_string\/2` will translate all occurrences of\n this AST to `left not in right`.\n \"\"\"\n @doc guard: true\n defmacro left in right do\n in_body? = __CALLER__.context == nil\n\n expand =\n case bootstrapped?(Macro) do\n true -> &Macro.expand(&1, __CALLER__)\n false -> & &1\n end\n\n case expand.(right) do\n [] when not in_body? ->\n false\n\n [] ->\n quote do\n _ = unquote(left)\n false\n end\n\n [head | tail] = list when not in_body? ->\n in_list(left, head, tail, expand, list, in_body?)\n\n [_ | _] = list when in_body? ->\n case ensure_evaled(list, {0, []}, expand) do\n {[head | tail], {_, []}} ->\n in_var(in_body?, left, &in_list(&1, head, tail, expand, list, in_body?))\n\n {[head | tail], {_, vars_values}} ->\n {vars, values} = :lists.unzip(:lists.reverse(vars_values))\n is_in_list = &in_list(&1, head, tail, expand, list, in_body?)\n\n quote do\n {unquote_splicing(vars)} = {unquote_splicing(values)}\n unquote(in_var(in_body?, left, is_in_list))\n end\n end\n\n {:%{}, _meta, [__struct__: Elixir.Range, first: first, last: last]} ->\n in_var(in_body?, left, &in_range(&1, expand.(first), expand.(last)))\n\n right when in_body? ->\n quote(do: Elixir.Enum.member?(unquote(right), unquote(left)))\n\n %{__struct__: Elixir.Range, first: _, last: _} ->\n raise ArgumentError, \"non-literal range in guard should be escaped with Macro.escape\/2\"\n\n right ->\n raise_on_invalid_args_in_2(right)\n end\n end\n\n defp raise_on_invalid_args_in_2(right) do\n raise ArgumentError, <<\n \"invalid right argument for operator \\\"in\\\", it expects a compile-time proper list \",\n \"or compile-time range on the right side when used in guard expressions, got: \",\n Macro.to_string(right)::binary\n >>\n end\n\n defp in_var(false, ast, fun), do: fun.(ast)\n\n defp in_var(true, {atom, _, context} = var, fun) when is_atom(atom) and is_atom(context),\n do: fun.(var)\n\n defp in_var(true, ast, fun) do\n quote do\n var = unquote(ast)\n unquote(fun.(quote(do: var)))\n end\n end\n\n # Called as ensure_evaled(list, {0, []}). Note acc is reversed.\n defp ensure_evaled(list, acc, expand) do\n fun = fn\n {:|, meta, [head, tail]}, acc ->\n {head, acc} = ensure_evaled_element(head, acc)\n {tail, acc} = ensure_evaled_tail(expand.(tail), acc, expand)\n {{:|, meta, [head, tail]}, acc}\n\n elem, acc ->\n ensure_evaled_element(elem, acc)\n end\n\n :lists.mapfoldl(fun, acc, list)\n end\n\n defp ensure_evaled_element(elem, acc)\n when is_number(elem) or is_atom(elem) or is_binary(elem) do\n {elem, acc}\n end\n\n defp ensure_evaled_element(elem, acc) do\n ensure_evaled_var(elem, acc)\n end\n\n defp ensure_evaled_tail(elem, acc, expand) when is_list(elem) do\n ensure_evaled(elem, acc, expand)\n end\n\n defp ensure_evaled_tail(elem, acc, _expand) do\n ensure_evaled_var(elem, acc)\n end\n\n defp ensure_evaled_var(elem, {index, ast}) do\n var = {String.to_atom(\"arg\" <> Integer.to_string(index + 1)), [], __MODULE__}\n {var, {index + 1, [{var, elem} | ast]}}\n end\n\n defp in_range(left, first, last) do\n case is_integer(first) and is_integer(last) do\n true ->\n in_range_literal(left, first, last)\n\n false ->\n quote do\n :erlang.is_integer(unquote(left)) and :erlang.is_integer(unquote(first)) and\n :erlang.is_integer(unquote(last)) and\n ((:erlang.\"=<\"(unquote(first), unquote(last)) and\n unquote(increasing_compare(left, first, last))) or\n (:erlang.<(unquote(last), unquote(first)) and\n unquote(decreasing_compare(left, first, last))))\n end\n end\n end\n\n defp in_range_literal(left, first, first) do\n quote do\n :erlang.\"=:=\"(unquote(left), unquote(first))\n end\n end\n\n defp in_range_literal(left, first, last) when first < last do\n quote do\n :erlang.andalso(\n :erlang.is_integer(unquote(left)),\n unquote(increasing_compare(left, first, last))\n )\n end\n end\n\n defp in_range_literal(left, first, last) do\n quote do\n :erlang.andalso(\n :erlang.is_integer(unquote(left)),\n unquote(decreasing_compare(left, first, last))\n )\n end\n end\n\n defp in_list(left, head, tail, expand, right, in_body?) do\n [head | tail] = :lists.map(&comp(left, &1, expand, right, in_body?), [head | tail])\n :lists.foldl("e(do: :erlang.orelse(unquote(&2), unquote(&1))), head, tail)\n end\n\n defp comp(left, {:|, _, [head, tail]}, expand, right, in_body?) do\n case expand.(tail) do\n [] ->\n quote(do: :erlang.\"=:=\"(unquote(left), unquote(head)))\n\n [tail_head | tail] ->\n quote do\n :erlang.orelse(\n :erlang.\"=:=\"(unquote(left), unquote(head)),\n unquote(in_list(left, tail_head, tail, expand, right, in_body?))\n )\n end\n\n tail when in_body? ->\n quote do\n :erlang.orelse(\n :erlang.\"=:=\"(unquote(left), unquote(head)),\n :lists.member(unquote(left), unquote(tail))\n )\n end\n\n _ ->\n raise_on_invalid_args_in_2(right)\n end\n end\n\n defp comp(left, right, _expand, _right, _in_body?) do\n quote(do: :erlang.\"=:=\"(unquote(left), unquote(right)))\n end\n\n defp increasing_compare(var, first, last) do\n quote do\n :erlang.andalso(\n :erlang.>=(unquote(var), unquote(first)),\n :erlang.\"=<\"(unquote(var), unquote(last))\n )\n end\n end\n\n defp decreasing_compare(var, first, last) do\n quote do\n :erlang.andalso(\n :erlang.\"=<\"(unquote(var), unquote(first)),\n :erlang.>=(unquote(var), unquote(last))\n )\n end\n end\n\n @doc \"\"\"\n Marks that the given variable should not be hygienized.\n\n This macro expects a variable and it is typically invoked\n inside `Kernel.SpecialForms.quote\/2` to mark that a variable\n should not be hygienized. See `Kernel.SpecialForms.quote\/2`\n for more information.\n\n ## Examples\n\n iex> Kernel.var!(example) = 1\n 1\n iex> Kernel.var!(example)\n 1\n\n \"\"\"\n defmacro var!(var, context \\\\ nil)\n\n defmacro var!({name, meta, atom}, context) when is_atom(name) and is_atom(atom) do\n # Remove counter and force them to be vars\n meta = :lists.keydelete(:counter, 1, meta)\n meta = :lists.keystore(:var, 1, meta, {:var, true})\n\n case Macro.expand(context, __CALLER__) do\n context when is_atom(context) ->\n {name, meta, context}\n\n other ->\n raise ArgumentError,\n \"expected var! context to expand to an atom, got: #{Macro.to_string(other)}\"\n end\n end\n\n defmacro var!(other, _context) do\n raise ArgumentError, \"expected a variable to be given to var!, got: #{Macro.to_string(other)}\"\n end\n\n @doc \"\"\"\n When used inside quoting, marks that the given alias should not\n be hygienized. This means the alias will be expanded when\n the macro is expanded.\n\n Check `Kernel.SpecialForms.quote\/2` for more information.\n \"\"\"\n defmacro alias!(alias) when is_atom(alias) do\n alias\n end\n\n defmacro alias!({:__aliases__, meta, args}) do\n # Simply remove the alias metadata from the node\n # so it does not affect expansion.\n {:__aliases__, :lists.keydelete(:alias, 1, meta), args}\n end\n\n ## Definitions implemented in Elixir\n\n @doc ~S\"\"\"\n Defines a module given by name with the given contents.\n\n This macro defines a module with the given `alias` as its name and with the\n given contents. It returns a tuple with four elements:\n\n * `:module`\n * the module name\n * the binary contents of the module\n * the result of evaluating the contents block\n\n ## Examples\n\n defmodule Number do\n def one, do: 1\n def two, do: 2\n end\n #=> {:module, Number, <<70, 79, 82, ...>>, {:two, 0}}\n\n Number.one()\n #=> 1\n\n Number.two()\n #=> 2\n\n ## Nesting\n\n Nesting a module inside another module affects the name of the nested module:\n\n defmodule Foo do\n defmodule Bar do\n end\n end\n\n In the example above, two modules - `Foo` and `Foo.Bar` - are created.\n When nesting, Elixir automatically creates an alias to the inner module,\n allowing the second module `Foo.Bar` to be accessed as `Bar` in the same\n lexical scope where it's defined (the `Foo` module). This only happens\n if the nested module is defined via an alias.\n\n If the `Foo.Bar` module is moved somewhere else, the references to `Bar` in\n the `Foo` module need to be updated to the fully-qualified name (`Foo.Bar`) or\n an alias has to be explicitly set in the `Foo` module with the help of\n `Kernel.SpecialForms.alias\/2`.\n\n defmodule Foo.Bar do\n # code\n end\n\n defmodule Foo do\n alias Foo.Bar\n # code here can refer to \"Foo.Bar\" as just \"Bar\"\n end\n\n ## Dynamic names\n\n Elixir module names can be dynamically generated. This is very\n useful when working with macros. For instance, one could write:\n\n defmodule String.to_atom(\"Foo#{1}\") do\n # contents ...\n end\n\n Elixir will accept any module name as long as the expression passed as the\n first argument to `defmodule\/2` evaluates to an atom.\n Note that, when a dynamic name is used, Elixir won't nest the name under\n the current module nor automatically set up an alias.\n\n ## Reserved module names\n\n If you attempt to define a module that already exists, you will get a\n warning saying that a module has been redefined.\n\n There are some modules that Elixir does not currently implement but it\n may be implement in the future. Those modules are reserved and defining\n them will result in a compilation error:\n\n defmodule Any do\n # code\n end\n ** (CompileError) iex:1: module Any is reserved and cannot be defined\n\n Elixir reserves the following module names: `Elixir`, `Any`, `BitString`,\n `PID`, and `Reference`.\n \"\"\"\n defmacro defmodule(alias, do_block)\n\n defmacro defmodule(alias, do: block) do\n env = __CALLER__\n boot? = bootstrapped?(Macro)\n\n expanded =\n case boot? do\n true -> Macro.expand(alias, env)\n false -> alias\n end\n\n {expanded, with_alias} =\n case boot? and is_atom(expanded) do\n true ->\n # Expand the module considering the current environment\/nesting\n {full, old, new} = expand_module(alias, expanded, env)\n meta = [defined: full, context: env.module] ++ alias_meta(alias)\n {full, {:alias, meta, [old, [as: new, warn: false]]}}\n\n false ->\n {expanded, nil}\n end\n\n # We do this so that the block is not tail-call optimized and stacktraces\n # are not messed up. Basically, we just insert something between the return\n # value of the block and what is returned by defmodule. Using just \":ok\" or\n # similar doesn't work because it's likely optimized away by the compiler.\n block =\n quote do\n result = unquote(block)\n :elixir_utils.noop()\n result\n end\n\n escaped =\n case env do\n %{function: nil, lexical_tracker: pid} when is_pid(pid) ->\n integer = Kernel.LexicalTracker.write_cache(pid, block)\n quote(do: Kernel.LexicalTracker.read_cache(unquote(pid), unquote(integer)))\n\n %{} ->\n :elixir_quote.escape(block, :default, false)\n end\n\n module_vars = :lists.map(&module_var\/1, :maps.keys(elem(env.current_vars, 0)))\n\n quote do\n unquote(with_alias)\n :elixir_module.compile(unquote(expanded), unquote(escaped), unquote(module_vars), __ENV__)\n end\n end\n\n defp alias_meta({:__aliases__, meta, _}), do: meta\n defp alias_meta(_), do: []\n\n # defmodule Elixir.Alias\n defp expand_module({:__aliases__, _, [:\"Elixir\", _ | _]}, module, _env),\n do: {module, module, nil}\n\n # defmodule Alias in root\n defp expand_module({:__aliases__, _, _}, module, %{module: nil}),\n do: {module, module, nil}\n\n # defmodule Alias nested\n defp expand_module({:__aliases__, _, [h | t]}, _module, env) when is_atom(h) do\n module = :elixir_aliases.concat([env.module, h])\n alias = String.to_atom(\"Elixir.\" <> Atom.to_string(h))\n\n case t do\n [] -> {module, module, alias}\n _ -> {String.to_atom(Enum.join([module | t], \".\")), module, alias}\n end\n end\n\n # defmodule _\n defp expand_module(_raw, module, _env) do\n {module, module, nil}\n end\n\n defp module_var({name, kind}) when is_atom(kind), do: {name, [generated: true], kind}\n defp module_var({name, kind}), do: {name, [counter: kind, generated: true], nil}\n\n @doc ~S\"\"\"\n Defines a public function with the given name and body.\n\n ## Examples\n\n defmodule Foo do\n def bar, do: :baz\n end\n\n Foo.bar()\n #=> :baz\n\n A function that expects arguments can be defined as follows:\n\n defmodule Foo do\n def sum(a, b) do\n a + b\n end\n end\n\n In the example above, a `sum\/2` function is defined; this function receives\n two arguments and returns their sum.\n\n ## Default arguments\n\n `\\\\` is used to specify a default value for a parameter of a function. For\n example:\n\n defmodule MyMath do\n def multiply_by(number, factor \\\\ 2) do\n number * factor\n end\n end\n\n MyMath.multiply_by(4, 3)\n #=> 12\n\n MyMath.multiply_by(4)\n #=> 8\n\n The compiler translates this into multiple functions with different arities,\n here `MyMath.multiply_by\/1` and `MyMath.multiply_by\/2`, that represent cases when\n arguments for parameters with default values are passed or not passed.\n\n When defining a function with default arguments as well as multiple\n explicitly declared clauses, you must write a function head that declares the\n defaults. For example:\n\n defmodule MyString do\n def join(string1, string2 \\\\ nil, separator \\\\ \" \")\n\n def join(string1, nil, _separator) do\n string1\n end\n\n def join(string1, string2, separator) do\n string1 <> separator <> string2\n end\n end\n\n Note that `\\\\` can't be used with anonymous functions because they\n can only have a sole arity.\n\n ### Keyword lists with default arguments\n\n Functions containing many arguments can benefit from using `Keyword`\n lists to group and pass attributes as a single value.\n\n defmodule MyConfiguration do\n @default_opts [storage: \"local\"]\n\n def configure(resource, opts \\\\ []) do\n opts = Keyword.merge(@default_opts, opts)\n storage = opts[:storage]\n # ...\n end\n end\n\n The difference between using `Map` and `Keyword` to store many\n arguments is `Keyword`'s keys:\n\n * must be atoms\n * can be given more than once\n * ordered, as specified by the developer\n\n ## Function and variable names\n\n Function and variable names have the following syntax:\n A _lowercase ASCII letter_ or an _underscore_, followed by any number of\n _lowercase or uppercase ASCII letters_, _numbers_, or _underscores_.\n Optionally they can end in either an _exclamation mark_ or a _question mark_.\n\n For variables, any identifier starting with an underscore should indicate an\n unused variable. For example:\n\n def foo(bar) do\n []\n end\n #=> warning: variable bar is unused\n\n def foo(_bar) do\n []\n end\n #=> no warning\n\n def foo(_bar) do\n _bar\n end\n #=> warning: the underscored variable \"_bar\" is used after being set\n\n ## `rescue`\/`catch`\/`after`\/`else`\n\n Function bodies support `rescue`, `catch`, `after`, and `else` as `Kernel.SpecialForms.try\/1`\n does (known as \"implicit try\"). For example, the following two functions are equivalent:\n\n def convert(number) do\n try do\n String.to_integer(number)\n rescue\n e in ArgumentError -> {:error, e.message}\n end\n end\n\n def convert(number) do\n String.to_integer(number)\n rescue\n e in ArgumentError -> {:error, e.message}\n end\n\n \"\"\"\n defmacro def(call, expr \\\\ nil) do\n define(:def, call, expr, __CALLER__)\n end\n\n @doc \"\"\"\n Defines a private function with the given name and body.\n\n Private functions are only accessible from within the module in which they are\n defined. Trying to access a private function from outside the module it's\n defined in results in an `UndefinedFunctionError` exception.\n\n Check `def\/2` for more information.\n\n ## Examples\n\n defmodule Foo do\n def bar do\n sum(1, 2)\n end\n\n defp sum(a, b), do: a + b\n end\n\n Foo.bar()\n #=> 3\n\n Foo.sum(1, 2)\n ** (UndefinedFunctionError) undefined function Foo.sum\/2\n\n \"\"\"\n defmacro defp(call, expr \\\\ nil) do\n define(:defp, call, expr, __CALLER__)\n end\n\n @doc \"\"\"\n Defines a public macro with the given name and body.\n\n Macros must be defined before its usage.\n\n Check `def\/2` for rules on naming and default arguments.\n\n ## Examples\n\n defmodule MyLogic do\n defmacro unless(expr, opts) do\n quote do\n if !unquote(expr), unquote(opts)\n end\n end\n end\n\n require MyLogic\n\n MyLogic.unless false do\n IO.puts(\"It works\")\n end\n\n \"\"\"\n defmacro defmacro(call, expr \\\\ nil) do\n define(:defmacro, call, expr, __CALLER__)\n end\n\n @doc \"\"\"\n Defines a private macro with the given name and body.\n\n Private macros are only accessible from the same module in which they are\n defined.\n\n Private macros must be defined before its usage.\n\n Check `defmacro\/2` for more information, and check `def\/2` for rules on\n naming and default arguments.\n\n \"\"\"\n defmacro defmacrop(call, expr \\\\ nil) do\n define(:defmacrop, call, expr, __CALLER__)\n end\n\n defp define(kind, call, expr, env) do\n module = assert_module_scope(env, kind, 2)\n assert_no_function_scope(env, kind, 2)\n\n unquoted_call = :elixir_quote.has_unquotes(call)\n unquoted_expr = :elixir_quote.has_unquotes(expr)\n escaped_call = :elixir_quote.escape(call, :default, true)\n\n escaped_expr =\n case unquoted_expr do\n true ->\n :elixir_quote.escape(expr, :default, true)\n\n false ->\n key = :erlang.unique_integer()\n :elixir_module.write_cache(module, key, expr)\n quote(do: :elixir_module.read_cache(unquote(module), unquote(key)))\n end\n\n # Do not check clauses if any expression was unquoted\n check_clauses = not (unquoted_expr or unquoted_call)\n pos = :elixir_locals.cache_env(env)\n\n quote do\n :elixir_def.store_definition(\n unquote(kind),\n unquote(check_clauses),\n unquote(escaped_call),\n unquote(escaped_expr),\n unquote(pos)\n )\n end\n end\n\n @doc \"\"\"\n Defines a struct.\n\n A struct is a tagged map that allows developers to provide\n default values for keys, tags to be used in polymorphic\n dispatches and compile time assertions.\n\n To define a struct, a developer must define both `__struct__\/0` and\n `__struct__\/1` functions. `defstruct\/1` is a convenience macro which\n defines such functions with some conveniences.\n\n For more information about structs, please check `Kernel.SpecialForms.%\/2`.\n\n ## Examples\n\n defmodule User do\n defstruct name: nil, age: nil\n end\n\n Struct fields are evaluated at compile-time, which allows\n them to be dynamic. In the example below, `10 + 11` is\n evaluated at compile-time and the age field is stored\n with value `21`:\n\n defmodule User do\n defstruct name: nil, age: 10 + 11\n end\n\n The `fields` argument is usually a keyword list with field names\n as atom keys and default values as corresponding values. `defstruct\/1`\n also supports a list of atoms as its argument: in that case, the atoms\n in the list will be used as the struct's field names and they will all\n default to `nil`.\n\n defmodule Post do\n defstruct [:title, :content, :author]\n end\n\n ## Deriving\n\n Although structs are maps, by default structs do not implement\n any of the protocols implemented for maps. For example, attempting\n to use a protocol with the `User` struct leads to an error:\n\n john = %User{name: \"John\"}\n MyProtocol.call(john)\n ** (Protocol.UndefinedError) protocol MyProtocol not implemented for %User{...}\n\n `defstruct\/1`, however, allows protocol implementations to be\n *derived*. This can be done by defining a `@derive` attribute as a\n list before invoking `defstruct\/1`:\n\n defmodule User do\n @derive [MyProtocol]\n defstruct name: nil, age: 10 + 11\n end\n\n MyProtocol.call(john) # it works!\n\n For each protocol in the `@derive` list, Elixir will assert the protocol has\n been implemented for `Any`. If the `Any` implementation defines a\n `__deriving__\/3` callback, the callback will be invoked and it should define\n the implementation module. Otherwise an implementation that simply points to\n the `Any` implementation is automatically derived. For more information on\n the `__deriving__\/3` callback, see `Protocol.derive\/3`.\n\n ## Enforcing keys\n\n When building a struct, Elixir will automatically guarantee all keys\n belongs to the struct:\n\n %User{name: \"john\", unknown: :key}\n ** (KeyError) key :unknown not found in: %User{age: 21, name: nil}\n\n Elixir also allows developers to enforce certain keys must always be\n given when building the struct:\n\n defmodule User do\n @enforce_keys [:name]\n defstruct name: nil, age: 10 + 11\n end\n\n Now trying to build a struct without the name key will fail:\n\n %User{age: 21}\n ** (ArgumentError) the following keys must also be given when building struct User: [:name]\n\n Keep in mind `@enforce_keys` is a simple compile-time guarantee\n to aid developers when building structs. It is not enforced on\n updates and it does not provide any sort of value-validation.\n\n ## Types\n\n It is recommended to define types for structs. By convention such type\n is called `t`. To define a struct inside a type, the struct literal syntax\n is used:\n\n defmodule User do\n defstruct name: \"John\", age: 25\n @type t :: %__MODULE__{name: String.t(), age: non_neg_integer}\n end\n\n It is recommended to only use the struct syntax when defining the struct's\n type. When referring to another struct it's better to use `User.t` instead of\n `%User{}`.\n\n The types of the struct fields that are not included in `%User{}` default to\n `term()` (see `t:term\/0`).\n\n Structs whose internal structure is private to the local module (pattern\n matching them or directly accessing their fields should not be allowed) should\n use the `@opaque` attribute. Structs whose internal structure is public should\n use `@type`.\n \"\"\"\n defmacro defstruct(fields) do\n builder =\n case bootstrapped?(Enum) do\n true ->\n quote do\n case @enforce_keys do\n [] ->\n def __struct__(kv) do\n Enum.reduce(kv, @__struct__, fn {key, val}, map ->\n Map.replace!(map, key, val)\n end)\n end\n\n _ ->\n def __struct__(kv) do\n {map, keys} =\n Enum.reduce(kv, {@__struct__, @enforce_keys}, fn {key, val}, {map, keys} ->\n {Map.replace!(map, key, val), List.delete(keys, key)}\n end)\n\n case keys do\n [] ->\n map\n\n _ ->\n raise ArgumentError,\n \"the following keys must also be given when building \" <>\n \"struct #{inspect(__MODULE__)}: #{inspect(keys)}\"\n end\n end\n end\n end\n\n false ->\n quote do\n _ = @enforce_keys\n\n def __struct__(kv) do\n :lists.foldl(fn {key, val}, acc -> Map.replace!(acc, key, val) end, @__struct__, kv)\n end\n end\n end\n\n quote do\n if Module.has_attribute?(__MODULE__, :__struct__) do\n raise ArgumentError,\n \"defstruct has already been called for \" <>\n \"#{Kernel.inspect(__MODULE__)}, defstruct can only be called once per module\"\n end\n\n {struct, keys, derive} = Kernel.Utils.defstruct(__MODULE__, unquote(fields))\n @__struct__ struct\n @enforce_keys keys\n\n case derive do\n [] -> :ok\n _ -> Protocol.__derive__(derive, __MODULE__, __ENV__)\n end\n\n def __struct__() do\n @__struct__\n end\n\n unquote(builder)\n Kernel.Utils.announce_struct(__MODULE__)\n struct\n end\n end\n\n @doc ~S\"\"\"\n Defines an exception.\n\n Exceptions are structs backed by a module that implements\n the `Exception` behaviour. The `Exception` behaviour requires\n two functions to be implemented:\n\n * [`exception\/1`](`c:Exception.exception\/1`) - receives the arguments given to `raise\/2`\n and returns the exception struct. The default implementation\n accepts either a set of keyword arguments that is merged into\n the struct or a string to be used as the exception's message.\n\n * [`message\/1`](`c:Exception.message\/1`) - receives the exception struct and must return its\n message. Most commonly exceptions have a message field which\n by default is accessed by this function. However, if an exception\n does not have a message field, this function must be explicitly\n implemented.\n\n Since exceptions are structs, the API supported by `defstruct\/1`\n is also available in `defexception\/1`.\n\n ## Raising exceptions\n\n The most common way to raise an exception is via `raise\/2`:\n\n defmodule MyAppError do\n defexception [:message]\n end\n\n value = [:hello]\n\n raise MyAppError,\n message: \"did not get what was expected, got: #{inspect(value)}\"\n\n In many cases it is more convenient to pass the expected value to\n `raise\/2` and generate the message in the `c:Exception.exception\/1` callback:\n\n defmodule MyAppError do\n defexception [:message]\n\n @impl true\n def exception(value) do\n msg = \"did not get what was expected, got: #{inspect(value)}\"\n %MyAppError{message: msg}\n end\n end\n\n raise MyAppError, value\n\n The example above shows the preferred strategy for customizing\n exception messages.\n \"\"\"\n defmacro defexception(fields) do\n quote bind_quoted: [fields: fields] do\n @behaviour Exception\n struct = defstruct([__exception__: true] ++ fields)\n\n if Map.has_key?(struct, :message) do\n @impl true\n def message(exception) do\n exception.message\n end\n\n defoverridable message: 1\n\n @impl true\n def exception(msg) when Kernel.is_binary(msg) do\n exception(message: msg)\n end\n end\n\n # Calls to Kernel functions must be fully-qualified to ensure\n # reproducible builds; otherwise, this macro will generate ASTs\n # with different metadata (:import, :context) depending on if\n # it is the bootstrapped version or not.\n # TODO: Change the implementation on v2.0 to simply call Kernel.struct!\/2\n @impl true\n def exception(args) when Kernel.is_list(args) do\n struct = __struct__()\n {valid, invalid} = Enum.split_with(args, fn {k, _} -> Map.has_key?(struct, k) end)\n\n case invalid do\n [] ->\n :ok\n\n _ ->\n IO.warn(\n \"the following fields are unknown when raising \" <>\n \"#{Kernel.inspect(__MODULE__)}: #{Kernel.inspect(invalid)}. \" <>\n \"Please make sure to only give known fields when raising \" <>\n \"or redefine #{Kernel.inspect(__MODULE__)}.exception\/1 to \" <>\n \"discard unknown fields. Future Elixir versions will raise on \" <>\n \"unknown fields given to raise\/2\"\n )\n end\n\n Kernel.struct!(struct, valid)\n end\n\n defoverridable exception: 1\n end\n end\n\n @doc \"\"\"\n Defines a protocol.\n\n See the `Protocol` module for more information.\n \"\"\"\n defmacro defprotocol(name, do_block)\n\n defmacro defprotocol(name, do: block) do\n Protocol.__protocol__(name, do: block)\n end\n\n @doc \"\"\"\n Defines an implementation for the given protocol.\n\n See the `Protocol` module for more information.\n \"\"\"\n defmacro defimpl(name, opts, do_block \\\\ []) do\n merged = Keyword.merge(opts, do_block)\n merged = Keyword.put_new(merged, :for, __CALLER__.module)\n\n if Keyword.fetch!(merged, :for) == nil do\n raise ArgumentError, \"defimpl\/3 expects a :for option when declared outside a module\"\n end\n\n Protocol.__impl__(name, merged)\n end\n\n @doc \"\"\"\n Makes the given functions in the current module overridable.\n\n An overridable function is lazily defined, allowing a developer to override\n it.\n\n Macros cannot be overridden as functions and vice-versa.\n\n ## Example\n\n defmodule DefaultMod do\n defmacro __using__(_opts) do\n quote do\n def test(x, y) do\n x + y\n end\n\n defoverridable test: 2\n end\n end\n end\n\n defmodule InheritMod do\n use DefaultMod\n\n def test(x, y) do\n x * y + super(x, y)\n end\n end\n\n As seen as in the example above, `super` can be used to call the default\n implementation.\n\n If `@behaviour` has been defined, `defoverridable` can also be called with a\n module as an argument. All implemented callbacks from the behaviour above the\n call to `defoverridable` will be marked as overridable.\n\n ## Example\n\n defmodule Behaviour do\n @callback foo :: any\n end\n\n defmodule DefaultMod do\n defmacro __using__(_opts) do\n quote do\n @behaviour Behaviour\n\n def foo do\n \"Override me\"\n end\n\n defoverridable Behaviour\n end\n end\n end\n\n defmodule InheritMod do\n use DefaultMod\n\n def foo do\n \"Overridden\"\n end\n end\n\n \"\"\"\n defmacro defoverridable(keywords_or_behaviour) do\n quote do\n Module.make_overridable(__MODULE__, unquote(keywords_or_behaviour))\n end\n end\n\n @doc \"\"\"\n Generates a macro suitable for use in guard expressions.\n\n It raises at compile time if the definition uses expressions that aren't\n allowed in guards, and otherwise creates a macro that can be used both inside\n or outside guards.\n\n Note the convention in Elixir is to name functions\/macros allowed in\n guards with the `is_` prefix, such as `is_list\/1`. If, however, the\n function\/macro returns a boolean and is not allowed in guards, it should\n have no prefix and end with a question mark, such as `Keyword.keyword?\/1`.\n\n ## Example\n\n defmodule Integer.Guards do\n defguard is_even(value) when is_integer(value) and rem(value, 2) == 0\n end\n\n defmodule Collatz do\n @moduledoc \"Tools for working with the Collatz sequence.\"\n import Integer.Guards\n\n @doc \"Determines the number of steps `n` takes to reach `1`.\"\n # If this function never converges, please let me know what `n` you used.\n def converge(n) when n > 0, do: step(n, 0)\n\n defp step(1, step_count) do\n step_count\n end\n\n defp step(n, step_count) when is_even(n) do\n step(div(n, 2), step_count + 1)\n end\n\n defp step(n, step_count) do\n step(3 * n + 1, step_count + 1)\n end\n end\n\n \"\"\"\n @doc since: \"1.6.0\"\n @spec defguard(Macro.t()) :: Macro.t()\n defmacro defguard(guard) do\n define_guard(:defmacro, guard, __CALLER__)\n end\n\n @doc \"\"\"\n Generates a private macro suitable for use in guard expressions.\n\n It raises at compile time if the definition uses expressions that aren't\n allowed in guards, and otherwise creates a private macro that can be used\n both inside or outside guards in the current module.\n\n Similar to `defmacrop\/2`, `defguardp\/1` must be defined before its use\n in the current module.\n \"\"\"\n @doc since: \"1.6.0\"\n @spec defguardp(Macro.t()) :: Macro.t()\n defmacro defguardp(guard) do\n define_guard(:defmacrop, guard, __CALLER__)\n end\n\n defp define_guard(kind, guard, env) do\n case :elixir_utils.extract_guards(guard) do\n {call, [_, _ | _]} ->\n raise ArgumentError,\n \"invalid syntax in defguard #{Macro.to_string(call)}, \" <>\n \"only a single when clause is allowed\"\n\n {call, impls} ->\n case Macro.decompose_call(call) do\n {_name, args} ->\n validate_variable_only_args!(call, args)\n\n macro_definition =\n case impls do\n [] ->\n define(kind, call, nil, env)\n\n [guard] ->\n quoted =\n quote do\n require Kernel.Utils\n Kernel.Utils.defguard(unquote(args), unquote(guard))\n end\n\n define(kind, call, [do: quoted], env)\n end\n\n quote do\n @doc guard: true\n unquote(macro_definition)\n end\n\n _invalid_definition ->\n raise ArgumentError, \"invalid syntax in defguard #{Macro.to_string(call)}\"\n end\n end\n end\n\n defp validate_variable_only_args!(call, args) do\n Enum.each(args, fn\n {ref, _meta, context} when is_atom(ref) and is_atom(context) ->\n :ok\n\n {:\\\\, _m1, [{ref, _m2, context}, _default]} when is_atom(ref) and is_atom(context) ->\n :ok\n\n _match ->\n raise ArgumentError, \"invalid syntax in defguard #{Macro.to_string(call)}\"\n end)\n end\n\n @doc \"\"\"\n Uses the given module in the current context.\n\n When calling:\n\n use MyModule, some: :options\n\n the `__using__\/1` macro from the `MyModule` module is invoked with the second\n argument passed to `use` as its argument. Since `__using__\/1` is a macro, all\n the usual macro rules apply, and its return value should be quoted code\n that is then inserted where `use\/2` is called.\n\n ## Examples\n\n For example, to write test cases using the `ExUnit` framework provided\n with Elixir, a developer should `use` the `ExUnit.Case` module:\n\n defmodule AssertionTest do\n use ExUnit.Case, async: true\n\n test \"always pass\" do\n assert true\n end\n end\n\n In this example, Elixir will call the `__using__\/1` macro in the\n `ExUnit.Case` module with the keyword list `[async: true]` as its\n argument.\n\n In other words, `use\/2` translates to:\n\n defmodule AssertionTest do\n require ExUnit.Case\n ExUnit.Case.__using__(async: true)\n\n test \"always pass\" do\n assert true\n end\n end\n\n where `ExUnit.Case` defines the `__using__\/1` macro:\n\n defmodule ExUnit.Case do\n defmacro __using__(opts) do\n # do something with opts\n quote do\n # return some code to inject in the caller\n end\n end\n end\n\n ## Best practices\n\n `__using__\/1` is typically used when there is a need to set some state (via\n module attributes) or callbacks (like `@before_compile`, see the documentation\n for `Module` for more information) into the caller.\n\n `__using__\/1` may also be used to alias, require, or import functionality\n from different modules:\n\n defmodule MyModule do\n defmacro __using__(_opts) do\n quote do\n import MyModule.Foo\n import MyModule.Bar\n import MyModule.Baz\n\n alias MyModule.Repo\n end\n end\n end\n\n However, do not provide `__using__\/1` if all it does is to import,\n alias or require the module itself. For example, avoid this:\n\n defmodule MyModule do\n defmacro __using__(_opts) do\n quote do\n import MyModule\n end\n end\n end\n\n In such cases, developers should instead import or alias the module\n directly, so that they can customize those as they wish,\n without the indirection behind `use\/2`.\n\n Finally, developers should also avoid defining functions inside\n the `__using__\/1` callback, unless those functions are the default\n implementation of a previously defined `@callback` or are functions\n meant to be overridden (see `defoverridable\/1`). Even in these cases,\n defining functions should be seen as a \"last resort\".\n\n In case you want to provide some existing functionality to the user module,\n please define it in a module which will be imported accordingly; for example,\n `ExUnit.Case` doesn't define the `test\/3` macro in the module that calls\n `use ExUnit.Case`, but it defines `ExUnit.Case.test\/3` and just imports that\n into the caller when used.\n \"\"\"\n defmacro use(module, opts \\\\ []) do\n calls =\n Enum.map(expand_aliases(module, __CALLER__), fn\n expanded when is_atom(expanded) ->\n quote do\n require unquote(expanded)\n unquote(expanded).__using__(unquote(opts))\n end\n\n _otherwise ->\n raise ArgumentError,\n \"invalid arguments for use, \" <>\n \"expected a compile time atom or alias, got: #{Macro.to_string(module)}\"\n end)\n\n quote(do: (unquote_splicing(calls)))\n end\n\n defp expand_aliases({{:., _, [base, :{}]}, _, refs}, env) do\n base = Macro.expand(base, env)\n\n Enum.map(refs, fn\n {:__aliases__, _, ref} ->\n Module.concat([base | ref])\n\n ref when is_atom(ref) ->\n Module.concat(base, ref)\n\n other ->\n other\n end)\n end\n\n defp expand_aliases(module, env) do\n [Macro.expand(module, env)]\n end\n\n @doc \"\"\"\n Defines a function that delegates to another module.\n\n Functions defined with `defdelegate\/2` are public and can be invoked from\n outside the module they're defined in, as if they were defined using `def\/2`.\n Therefore, `defdelegate\/2` is about extending the current module's public API.\n If what you want is to invoke a function defined in another module without\n using its full module name, then use `alias\/2` to shorten the module name or use\n `import\/2` to be able to invoke the function without the module name altogether.\n\n Delegation only works with functions; delegating macros is not supported.\n\n Check `def\/2` for rules on naming and default arguments.\n\n ## Options\n\n * `:to` - the module to dispatch to.\n\n * `:as` - the function to call on the target given in `:to`.\n This parameter is optional and defaults to the name being\n delegated (`funs`).\n\n ## Examples\n\n defmodule MyList do\n defdelegate reverse(list), to: Enum\n defdelegate other_reverse(list), to: Enum, as: :reverse\n end\n\n MyList.reverse([1, 2, 3])\n #=> [3, 2, 1]\n\n MyList.other_reverse([1, 2, 3])\n #=> [3, 2, 1]\n\n \"\"\"\n defmacro defdelegate(funs, opts) do\n funs = Macro.escape(funs, unquote: true)\n\n # don't add compile-time dependency on :to\n opts =\n with true <- is_list(opts),\n {:ok, target} <- Keyword.fetch(opts, :to),\n {:__aliases__, _, _} <- target do\n target = Macro.expand(target, %{__CALLER__ | function: {:__info__, 1}})\n Keyword.replace!(opts, :to, target)\n else\n _ ->\n opts\n end\n\n quote bind_quoted: [funs: funs, opts: opts] do\n target =\n Keyword.get(opts, :to) || raise ArgumentError, \"expected to: to be given as argument\"\n\n if is_list(funs) do\n IO.warn(\n \"passing a list to Kernel.defdelegate\/2 is deprecated, please define each delegate separately\",\n Macro.Env.stacktrace(__ENV__)\n )\n end\n\n if Keyword.has_key?(opts, :append_first) do\n IO.warn(\n \"Kernel.defdelegate\/2 :append_first option is deprecated\",\n Macro.Env.stacktrace(__ENV__)\n )\n end\n\n for fun <- List.wrap(funs) do\n {name, args, as, as_args} = Kernel.Utils.defdelegate(fun, opts)\n\n @doc delegate_to: {target, as, :erlang.length(as_args)}\n\n # Build the call AST by hand so it doesn't get a\n # context and it warns on things like missing @impl\n def unquote({name, [line: __ENV__.line], args}) do\n unquote(target).unquote(as)(unquote_splicing(as_args))\n end\n end\n end\n end\n\n ## Sigils\n\n @doc ~S\"\"\"\n Handles the sigil `~S` for strings.\n\n It returns a string without interpolations and without escape\n characters, except for the escaping of the closing sigil character\n itself.\n\n ## Examples\n\n iex> ~S(foo)\n \"foo\"\n iex> ~S(f#{o}o)\n \"f\\#{o}o\"\n iex> ~S(\\o\/)\n \"\\\\o\/\"\n\n However, if you want to re-use the sigil character itself on\n the string, you need to escape it:\n\n iex> ~S((\\))\n \"()\"\n\n \"\"\"\n defmacro sigil_S(term, modifiers)\n defmacro sigil_S({:<<>>, _, [binary]}, []) when is_binary(binary), do: binary\n\n @doc ~S\"\"\"\n Handles the sigil `~s` for strings.\n\n It returns a string as if it was a double quoted string, unescaping characters\n and replacing interpolations.\n\n ## Examples\n\n iex> ~s(foo)\n \"foo\"\n\n iex> ~s(f#{:o}o)\n \"foo\"\n\n iex> ~s(f\\#{:o}o)\n \"f\\#{:o}o\"\n\n \"\"\"\n defmacro sigil_s(term, modifiers)\n\n defmacro sigil_s({:<<>>, _, [piece]}, []) when is_binary(piece) do\n :elixir_interpolation.unescape_chars(piece)\n end\n\n defmacro sigil_s({:<<>>, line, pieces}, []) do\n {:<<>>, line, unescape_tokens(pieces)}\n end\n\n @doc ~S\"\"\"\n Handles the sigil `~C` for charlists.\n\n It returns a charlist without interpolations and without escape\n characters, except for the escaping of the closing sigil character\n itself.\n\n ## Examples\n\n iex> ~C(foo)\n 'foo'\n\n iex> ~C(f#{o}o)\n 'f\\#{o}o'\n\n \"\"\"\n defmacro sigil_C(term, modifiers)\n\n defmacro sigil_C({:<<>>, _meta, [string]}, []) when is_binary(string) do\n String.to_charlist(string)\n end\n\n @doc ~S\"\"\"\n Handles the sigil `~c` for charlists.\n\n It returns a charlist as if it was a single quoted string, unescaping\n characters and replacing interpolations.\n\n ## Examples\n\n iex> ~c(foo)\n 'foo'\n\n iex> ~c(f#{:o}o)\n 'foo'\n\n iex> ~c(f\\#{:o}o)\n 'f\\#{:o}o'\n\n \"\"\"\n defmacro sigil_c(term, modifiers)\n\n # We can skip the runtime conversion if we are\n # creating a binary made solely of series of chars.\n defmacro sigil_c({:<<>>, _meta, [string]}, []) when is_binary(string) do\n String.to_charlist(:elixir_interpolation.unescape_chars(string))\n end\n\n defmacro sigil_c({:<<>>, _meta, pieces}, []) do\n quote(do: List.to_charlist(unquote(unescape_list_tokens(pieces))))\n end\n\n @doc \"\"\"\n Handles the sigil `~r` for regular expressions.\n\n It returns a regular expression pattern, unescaping characters and replacing\n interpolations.\n\n More information on regular expressions can be found in the `Regex` module.\n\n ## Examples\n\n iex> Regex.match?(~r(foo), \"foo\")\n true\n\n iex> Regex.match?(~r\/a#{:b}c\/, \"abc\")\n true\n\n \"\"\"\n defmacro sigil_r(term, modifiers)\n\n defmacro sigil_r({:<<>>, _meta, [string]}, options) when is_binary(string) do\n binary = :elixir_interpolation.unescape_chars(string, &Regex.unescape_map\/1)\n regex = Regex.compile!(binary, :binary.list_to_bin(options))\n Macro.escape(regex)\n end\n\n defmacro sigil_r({:<<>>, meta, pieces}, options) do\n binary = {:<<>>, meta, unescape_tokens(pieces, &Regex.unescape_map\/1)}\n quote(do: Regex.compile!(unquote(binary), unquote(:binary.list_to_bin(options))))\n end\n\n @doc ~S\"\"\"\n Handles the sigil `~R` for regular expressions.\n\n It returns a regular expression pattern without interpolations and\n without escape characters. Note it still supports escape of Regex\n tokens (such as escaping `+` or `?`) and it also requires you to\n escape the closing sigil character itself if it appears on the Regex.\n\n More information on regexes can be found in the `Regex` module.\n\n ## Examples\n\n iex> Regex.match?(~R(f#{1,3}o), \"f#o\")\n true\n\n \"\"\"\n defmacro sigil_R(term, modifiers)\n\n defmacro sigil_R({:<<>>, _meta, [string]}, options) when is_binary(string) do\n regex = Regex.compile!(string, :binary.list_to_bin(options))\n Macro.escape(regex)\n end\n\n @doc ~S\"\"\"\n Handles the sigil `~D` for dates.\n\n By default, this sigil uses the built-in `Calendar.ISO`, which\n requires dates to be written in the ISO8601 format:\n\n ~D[yyyy-mm-dd]\n\n such as:\n\n ~D[2015-01-13]\n\n If you are using alternative calendars, any representation can\n be used as long as you follow the representation by a single space\n and the calendar name:\n\n ~D[SOME-REPRESENTATION My.Alternative.Calendar]\n\n The lower case `~d` variant does not exist as interpolation\n and escape characters are not useful for date sigils.\n\n More information on dates can be found in the `Date` module.\n\n ## Examples\n\n iex> ~D[2015-01-13]\n ~D[2015-01-13]\n\n \"\"\"\n defmacro sigil_D(date_string, modifiers)\n\n defmacro sigil_D({:<<>>, _, [string]}, []) do\n {{:ok, {year, month, day}}, calendar} = parse_with_calendar!(string, :parse_date, \"Date\")\n to_calendar_struct(Date, calendar: calendar, year: year, month: month, day: day)\n end\n\n @doc ~S\"\"\"\n Handles the sigil `~T` for times.\n\n By default, this sigil uses the built-in `Calendar.ISO`, which\n requires times to be written in the ISO8601 format:\n\n ~T[hh:mm:ss]\n ~T[hh:mm:ss.ssssss]\n\n such as:\n\n ~T[13:00:07]\n ~T[13:00:07.123]\n\n If you are using alternative calendars, any representation can\n be used as long as you follow the representation by a single space\n and the calendar name:\n\n ~T[SOME-REPRESENTATION My.Alternative.Calendar]\n\n The lower case `~t` variant does not exist as interpolation\n and escape characters are not useful for time sigils.\n\n More information on times can be found in the `Time` module.\n\n ## Examples\n\n iex> ~T[13:00:07]\n ~T[13:00:07]\n iex> ~T[13:00:07.001]\n ~T[13:00:07.001]\n\n \"\"\"\n defmacro sigil_T(time_string, modifiers)\n\n defmacro sigil_T({:<<>>, _, [string]}, []) do\n {{:ok, {hour, minute, second, microsecond}}, calendar} =\n parse_with_calendar!(string, :parse_time, \"Time\")\n\n to_calendar_struct(Time,\n calendar: calendar,\n hour: hour,\n minute: minute,\n second: second,\n microsecond: microsecond\n )\n end\n\n @doc ~S\"\"\"\n Handles the sigil `~N` for naive date times.\n\n By default, this sigil uses the built-in `Calendar.ISO`, which\n requires naive date times to be written in the ISO8601 format:\n\n ~N[yyyy-mm-dd hh:mm:ss]\n ~N[yyyy-mm-dd hh:mm:ss.ssssss]\n ~N[yyyy-mm-ddThh:mm:ss.ssssss]\n\n such as:\n\n ~N[2015-01-13 13:00:07]\n ~N[2015-01-13T13:00:07.123]\n\n If you are using alternative calendars, any representation can\n be used as long as you follow the representation by a single space\n and the calendar name:\n\n ~N[SOME-REPRESENTATION My.Alternative.Calendar]\n\n The lower case `~n` variant does not exist as interpolation\n and escape characters are not useful for date time sigils.\n\n More information on naive date times can be found in the\n `NaiveDateTime` module.\n\n ## Examples\n\n iex> ~N[2015-01-13 13:00:07]\n ~N[2015-01-13 13:00:07]\n iex> ~N[2015-01-13T13:00:07.001]\n ~N[2015-01-13 13:00:07.001]\n\n \"\"\"\n defmacro sigil_N(naive_datetime_string, modifiers)\n\n defmacro sigil_N({:<<>>, _, [string]}, []) do\n {{:ok, {year, month, day, hour, minute, second, microsecond}}, calendar} =\n parse_with_calendar!(string, :parse_naive_datetime, \"NaiveDateTime\")\n\n to_calendar_struct(NaiveDateTime,\n calendar: calendar,\n year: year,\n month: month,\n day: day,\n hour: hour,\n minute: minute,\n second: second,\n microsecond: microsecond\n )\n end\n\n @doc ~S\"\"\"\n Handles the sigil `~U` to create a UTC `DateTime`.\n\n By default, this sigil uses the built-in `Calendar.ISO`, which\n requires UTC date times to be written in the ISO8601 format:\n\n ~U[yyyy-mm-dd hh:mm:ssZ]\n ~U[yyyy-mm-dd hh:mm:ss.ssssssZ]\n ~U[yyyy-mm-ddThh:mm:ss.ssssss+00:00]\n\n such as:\n\n ~U[2015-01-13 13:00:07Z]\n ~U[2015-01-13T13:00:07.123+00:00]\n\n If you are using alternative calendars, any representation can\n be used as long as you follow the representation by a single space\n and the calendar name:\n\n ~U[SOME-REPRESENTATION My.Alternative.Calendar]\n\n The given `datetime_string` must include \"Z\" or \"00:00\" offset\n which marks it as UTC, otherwise an error is raised.\n\n The lower case `~u` variant does not exist as interpolation\n and escape characters are not useful for date time sigils.\n\n More information on date times can be found in the `DateTime` module.\n\n ## Examples\n\n iex> ~U[2015-01-13 13:00:07Z]\n ~U[2015-01-13 13:00:07Z]\n iex> ~U[2015-01-13T13:00:07.001+00:00]\n ~U[2015-01-13 13:00:07.001Z]\n\n \"\"\"\n @doc since: \"1.9.0\"\n defmacro sigil_U(datetime_string, modifiers)\n\n defmacro sigil_U({:<<>>, _, [string]}, []) do\n {{:ok, {year, month, day, hour, minute, second, microsecond}, offset}, calendar} =\n parse_with_calendar!(string, :parse_utc_datetime, \"UTC DateTime\")\n\n if offset != 0 do\n raise ArgumentError,\n \"cannot parse #{inspect(string)} as UTC DateTime for #{inspect(calendar)}, reason: :non_utc_offset\"\n end\n\n to_calendar_struct(DateTime,\n calendar: calendar,\n year: year,\n month: month,\n day: day,\n hour: hour,\n minute: minute,\n second: second,\n microsecond: microsecond,\n time_zone: \"Etc\/UTC\",\n zone_abbr: \"UTC\",\n utc_offset: 0,\n std_offset: 0\n )\n end\n\n defp parse_with_calendar!(string, fun, context) do\n {calendar, string} = extract_calendar(string)\n result = apply(calendar, fun, [string])\n {maybe_raise!(result, calendar, context, string), calendar}\n end\n\n defp extract_calendar(string) do\n case :binary.split(string, \" \", [:global]) do\n [_] -> {Calendar.ISO, string}\n parts -> maybe_atomize_calendar(List.last(parts), string)\n end\n end\n\n defp maybe_atomize_calendar(<> = last_part, string)\n when alias >= ?A and alias <= ?Z do\n string = binary_part(string, 0, byte_size(string) - byte_size(last_part) - 1)\n {String.to_atom(\"Elixir.\" <> last_part), string}\n end\n\n defp maybe_atomize_calendar(_last_part, string) do\n {Calendar.ISO, string}\n end\n\n defp maybe_raise!({:error, reason}, calendar, type, string) do\n raise ArgumentError,\n \"cannot parse #{inspect(string)} as #{type} for #{inspect(calendar)}, \" <>\n \"reason: #{inspect(reason)}\"\n end\n\n defp maybe_raise!(other, _calendar, _type, _string), do: other\n\n defp to_calendar_struct(type, fields) do\n quote do\n %{unquote_splicing([__struct__: type] ++ fields)}\n end\n end\n\n @doc ~S\"\"\"\n Handles the sigil `~w` for list of words.\n\n It returns a list of \"words\" split by whitespace. Character unescaping and\n interpolation happens for each word.\n\n ## Modifiers\n\n * `s`: words in the list are strings (default)\n * `a`: words in the list are atoms\n * `c`: words in the list are charlists\n\n ## Examples\n\n iex> ~w(foo #{:bar} baz)\n [\"foo\", \"bar\", \"baz\"]\n\n iex> ~w(foo #{\" bar baz \"})\n [\"foo\", \"bar\", \"baz\"]\n\n iex> ~w(--source test\/enum_test.exs)\n [\"--source\", \"test\/enum_test.exs\"]\n\n iex> ~w(foo bar baz)a\n [:foo, :bar, :baz]\n\n \"\"\"\n defmacro sigil_w(term, modifiers)\n\n defmacro sigil_w({:<<>>, _meta, [string]}, modifiers) when is_binary(string) do\n split_words(:elixir_interpolation.unescape_chars(string), modifiers, __CALLER__)\n end\n\n defmacro sigil_w({:<<>>, meta, pieces}, modifiers) do\n binary = {:<<>>, meta, unescape_tokens(pieces)}\n split_words(binary, modifiers, __CALLER__)\n end\n\n @doc ~S\"\"\"\n Handles the sigil `~W` for list of words.\n\n It returns a list of \"words\" split by whitespace without interpolations\n and without escape characters, except for the escaping of the closing\n sigil character itself.\n\n ## Modifiers\n\n * `s`: words in the list are strings (default)\n * `a`: words in the list are atoms\n * `c`: words in the list are charlists\n\n ## Examples\n\n iex> ~W(foo #{bar} baz)\n [\"foo\", \"\\#{bar}\", \"baz\"]\n\n \"\"\"\n defmacro sigil_W(term, modifiers)\n\n defmacro sigil_W({:<<>>, _meta, [string]}, modifiers) when is_binary(string) do\n split_words(string, modifiers, __CALLER__)\n end\n\n defp split_words(string, [], caller) do\n split_words(string, [?s], caller)\n end\n\n defp split_words(string, [mod], caller)\n when mod == ?s or mod == ?a or mod == ?c do\n case is_binary(string) do\n true ->\n parts = String.split(string)\n\n parts_with_trailing_comma =\n :lists.filter(&(byte_size(&1) > 1 and :binary.last(&1) == ?,), parts)\n\n if parts_with_trailing_comma != [] do\n stacktrace = Macro.Env.stacktrace(caller)\n\n IO.warn(\n \"the sigils ~w\/~W do not allow trailing commas at the end of each word. \" <>\n \"If the comma is necessary, define a regular list with [...], otherwise remove the comma.\",\n stacktrace\n )\n end\n\n case mod do\n ?s -> parts\n ?a -> :lists.map(&String.to_atom\/1, parts)\n ?c -> :lists.map(&String.to_charlist\/1, parts)\n end\n\n false ->\n parts = quote(do: String.split(unquote(string)))\n\n case mod do\n ?s -> parts\n ?a -> quote(do: :lists.map(&String.to_atom\/1, unquote(parts)))\n ?c -> quote(do: :lists.map(&String.to_charlist\/1, unquote(parts)))\n end\n end\n end\n\n defp split_words(_string, _mods, _caller) do\n raise ArgumentError, \"modifier must be one of: s, a, c\"\n end\n\n ## Shared functions\n\n defp assert_module_scope(env, fun, arity) do\n case env.module do\n nil -> raise ArgumentError, \"cannot invoke #{fun}\/#{arity} outside module\"\n mod -> mod\n end\n end\n\n defp assert_no_function_scope(env, fun, arity) do\n case env.function do\n nil -> :ok\n _ -> raise ArgumentError, \"cannot invoke #{fun}\/#{arity} inside function\/macro\"\n end\n end\n\n defp assert_no_match_or_guard_scope(context, exp) do\n case context do\n :match ->\n invalid_match!(exp)\n\n :guard ->\n raise ArgumentError,\n \"invalid expression in guard, #{exp} is not allowed in guards. \" <>\n \"To learn more about guards, visit: https:\/\/hexdocs.pm\/elixir\/patterns-and-guards.html\"\n\n _ ->\n :ok\n end\n end\n\n defp invalid_match!(exp) do\n raise ArgumentError,\n \"invalid expression in match, #{exp} is not allowed in patterns \" <>\n \"such as function clauses, case clauses or on the left side of the = operator\"\n end\n\n # Helper to handle the :ok | :error tuple returned from :elixir_interpolation.unescape_tokens\n defp unescape_tokens(tokens) do\n case :elixir_interpolation.unescape_tokens(tokens) do\n {:ok, unescaped_tokens} -> unescaped_tokens\n {:error, reason} -> raise ArgumentError, to_string(reason)\n end\n end\n\n defp unescape_tokens(tokens, unescape_map) do\n case :elixir_interpolation.unescape_tokens(tokens, unescape_map) do\n {:ok, unescaped_tokens} -> unescaped_tokens\n {:error, reason} -> raise ArgumentError, to_string(reason)\n end\n end\n\n defp unescape_list_tokens(tokens) do\n escape = fn\n {:\"::\", _, [expr, _]} -> expr\n binary when is_binary(binary) -> :elixir_interpolation.unescape_chars(binary)\n end\n\n :lists.map(escape, tokens)\n end\n\n @doc false\n defmacro to_char_list(arg) do\n IO.warn(\n \"Kernel.to_char_list\/1 is deprecated, use Kernel.to_charlist\/1 instead\",\n Macro.Env.stacktrace(__CALLER__)\n )\n\n quote(do: Kernel.to_charlist(unquote(arg)))\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"ed9862ea91536e33e2b712e2509e4bed73373d9f","subject":"First deprecate types in struct fields","message":"First deprecate types in struct fields\n","repos":"joshprice\/elixir,ggcampinho\/elixir,beedub\/elixir,gfvcastro\/elixir,gfvcastro\/elixir,antipax\/elixir,kelvinst\/elixir,pedrosnk\/elixir,elixir-lang\/elixir,michalmuskala\/elixir,antipax\/elixir,beedub\/elixir,kimshrier\/elixir,pedrosnk\/elixir,kelvinst\/elixir,kimshrier\/elixir,lexmag\/elixir,ggcampinho\/elixir,lexmag\/elixir","old_file":"lib\/elixir\/lib\/kernel.ex","new_file":"lib\/elixir\/lib\/kernel.ex","new_contents":"# Use elixir_bootstrap module to be able to bootstrap Kernel.\n# The bootstrap module provides simpler implementations of the\n# functions removed, simple enough to bootstrap.\nimport Kernel, except: [@: 1, defmodule: 2, def: 1, def: 2, defp: 2,\n defmacro: 1, defmacro: 2, defmacrop: 2]\nimport :elixir_bootstrap\n\ndefmodule Kernel do\n @moduledoc \"\"\"\n `Kernel` provides the default macros and functions\n Elixir imports into your environment. These macros and functions\n can be skipped or cherry-picked via the `import` macro. For\n instance, if you want to tell Elixir not to import the `if`\n macro, you can do:\n\n import Kernel, except: [if: 2]\n\n Elixir also has special forms that are always imported and\n cannot be skipped. These are described in `Kernel.SpecialForms`.\n\n Some of the functions described in this module are inlined by\n the Elixir compiler into their Erlang counterparts in the `:erlang`\n module. Those functions are called BIFs (builtin internal functions)\n in Erlang-land and they exhibit interesting properties, as some of\n them are allowed in guards and others are used for compiler\n optimizations.\n\n Most of the inlined functions can be seen in effect when capturing\n the function:\n\n iex> &Kernel.is_atom\/1\n &:erlang.is_atom\/1\n\n Those functions will be explicitly marked in their docs as\n \"inlined by the compiler\".\n \"\"\"\n\n ## Delegations to Erlang with inlining (macros)\n\n @doc \"\"\"\n Returns an integer or float which is the arithmetical absolute value of `number`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> abs(-3.33)\n 3.33\n\n iex> abs(-3)\n 3\n\n \"\"\"\n @spec abs(number) :: number\n def abs(number) do\n :erlang.abs(number)\n end\n\n @doc \"\"\"\n Invokes the given `fun` with the array of arguments `args`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> apply(fn x -> x * 2 end, [2])\n 4\n\n \"\"\"\n @spec apply(fun, [any]) :: any\n def apply(fun, args) do\n :erlang.apply(fun, args)\n end\n\n @doc \"\"\"\n Invokes the given `fun` from `module` with the array of arguments `args`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> apply(Enum, :reverse, [[1, 2, 3]])\n [3,2,1]\n\n \"\"\"\n @spec apply(module, atom, [any]) :: any\n def apply(module, fun, args) do\n :erlang.apply(module, fun, args)\n end\n\n @doc \"\"\"\n Extracts the part of the binary starting at `start` with length `length`.\n Binaries are zero-indexed.\n\n If start or length references in any way outside the binary, an\n `ArgumentError` exception is raised.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> binary_part(\"foo\", 1, 2)\n \"oo\"\n\n A negative length can be used to extract bytes at the end of a binary:\n\n iex> binary_part(\"foo\", 3, -1)\n \"o\"\n\n \"\"\"\n @spec binary_part(binary, pos_integer, integer) :: binary\n def binary_part(binary, start, length) do\n :erlang.binary_part(binary, start, length)\n end\n\n @doc \"\"\"\n Returns an integer which is the size in bits of `bitstring`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> bit_size(<<433::16, 3::3>>)\n 19\n\n iex> bit_size(<<1, 2, 3>>)\n 24\n\n \"\"\"\n @spec bit_size(bitstring) :: non_neg_integer\n def bit_size(bitstring) do\n :erlang.bit_size(bitstring)\n end\n\n @doc \"\"\"\n Returns the number of bytes needed to contain `bitstring`.\n\n That is, if the number of bits in `bitstring` is not divisible by 8,\n the resulting number of bytes will be rounded up. This operation\n happens in constant time.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> byte_size(<<433::16, 3::3>>)\n 3\n\n iex> byte_size(<<1, 2, 3>>)\n 3\n\n \"\"\"\n @spec byte_size(bitstring) :: non_neg_integer\n def byte_size(bitstring) do\n :erlang.byte_size(bitstring)\n end\n\n @doc \"\"\"\n Performs an integer division.\n\n Raises an error if one of the arguments is not an integer.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> div(5, 2)\n 2\n\n \"\"\"\n @spec div(integer, integer) :: integer\n def div(left, right) do\n :erlang.div(left, right)\n end\n\n @doc \"\"\"\n Stops the execution of the calling process with the given reason.\n\n Since evaluating this function causes the process to terminate,\n it has no return value.\n\n Inlined by the compiler.\n\n ## Examples\n\n exit(:normal)\n exit(:seems_bad)\n\n \"\"\"\n @spec exit(term) :: no_return\n def exit(reason) do\n :erlang.exit(reason)\n end\n\n @doc \"\"\"\n Returns the head of a list, raises `badarg` if the list is empty.\n\n Inlined by the compiler.\n \"\"\"\n @spec hd(list) :: term\n def hd(list) do\n :erlang.hd(list)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is an atom; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_atom(term) :: boolean\n def is_atom(term) do\n :erlang.is_atom(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a binary; otherwise returns `false`.\n\n A binary always contains a complete number of bytes.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_binary(term) :: boolean\n def is_binary(term) do\n :erlang.is_binary(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a bitstring (including a binary); otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_bitstring(term) :: boolean\n def is_bitstring(term) do\n :erlang.is_bitstring(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is either the atom `true` or the atom `false` (i.e. a boolean);\n otherwise returns false.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_boolean(term) :: boolean\n def is_boolean(term) do\n :erlang.is_boolean(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a floating point number; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_float(term) :: boolean\n def is_float(term) do\n :erlang.is_float(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a function; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_function(term) :: boolean\n def is_function(term) do\n :erlang.is_function(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a function that can be applied with `arity` number of arguments;\n otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_function(term, non_neg_integer) :: boolean\n def is_function(term, arity) do\n :erlang.is_function(term, arity)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is an integer; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_integer(term) :: boolean\n def is_integer(term) do\n :erlang.is_integer(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a list with zero or more elements; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_list(term) :: boolean\n def is_list(term) do\n :erlang.is_list(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is either an integer or a floating point number;\n otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_number(term) :: boolean\n def is_number(term) do\n :erlang.is_number(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a pid (process identifier); otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_pid(term) :: boolean\n def is_pid(term) do\n :erlang.is_pid(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a port identifier; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_port(term) :: boolean\n def is_port(term) do\n :erlang.is_port(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a reference; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_reference(term) :: boolean\n def is_reference(term) do\n :erlang.is_reference(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a tuple; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_tuple(term) :: boolean\n def is_tuple(term) do\n :erlang.is_tuple(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a map; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_map(term) :: boolean\n def is_map(term) do\n :erlang.is_map(term)\n end\n\n @doc \"\"\"\n Returns the length of `list`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> length([1, 2, 3, 4, 5, 6, 7, 8, 9])\n 9\n\n \"\"\"\n @spec length(list) :: non_neg_integer\n def length(list) do\n :erlang.length(list)\n end\n\n @doc \"\"\"\n Returns an almost unique reference.\n\n The returned reference will re-occur after approximately 2^82 calls;\n therefore it is unique enough for practical purposes.\n\n Inlined by the compiler.\n\n ## Examples\n\n make_ref() #=> #Reference<0.0.0.135>\n\n \"\"\"\n @spec make_ref() :: reference\n def make_ref() do\n :erlang.make_ref()\n end\n\n @doc \"\"\"\n Returns the size of a map.\n\n This operation happens in constant time.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec map_size(map) :: non_neg_integer\n def map_size(map) do\n :erlang.map_size(map)\n end\n\n @doc \"\"\"\n Return the biggest of the two given terms according to\n Erlang's term ordering. If the terms compare equal, the\n first one is returned.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> max(1, 2)\n 2\n\n \"\"\"\n @spec max(term, term) :: term\n def max(first, second) do\n :erlang.max(first, second)\n end\n\n @doc \"\"\"\n Return the smallest of the two given terms according to\n Erlang's term ordering. If the terms compare equal, the\n first one is returned.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> min(1, 2)\n 1\n\n \"\"\"\n @spec min(term, term) :: term\n def min(first, second) do\n :erlang.min(first, second)\n end\n\n @doc \"\"\"\n Returns an atom representing the name of the local node.\n If the node is not alive, `:nonode@nohost` is returned instead.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec node() :: node\n def node do\n :erlang.node\n end\n\n @doc \"\"\"\n Returns the node where the given argument is located.\n The argument can be a pid, a reference, or a port.\n If the local node is not alive, `nonode@nohost` is returned.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec node(pid|reference|port) :: node\n def node(arg) do\n :erlang.node(arg)\n end\n\n @doc \"\"\"\n Calculates the remainder of an integer division.\n\n Raises an error if one of the arguments is not an integer.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> rem(5, 2)\n 1\n\n \"\"\"\n @spec rem(integer, integer) :: integer\n def rem(left, right) do\n :erlang.rem(left, right)\n end\n\n @doc \"\"\"\n Returns an integer by rounding the given number.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> round(5.5)\n 6\n\n \"\"\"\n @spec round(number) :: integer\n def round(number) do\n :erlang.round(number)\n end\n\n @doc \"\"\"\n Sends a message to the given `dest` and returns the message.\n\n `dest` may be a remote or local pid, a (local) port, a locally\n registered name, or a tuple `{registered_name, node}` for a registered\n name at another node.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> send self(), :hello\n :hello\n\n \"\"\"\n @spec send(dest :: pid | port | atom | {atom, node}, msg) :: msg when msg: any\n def send(dest, msg) do\n :erlang.send(dest, msg)\n end\n\n @doc \"\"\"\n Returns the pid (process identifier) of the calling process.\n\n Allowed in guard clauses. Inlined by the compiler.\n \"\"\"\n @spec self() :: pid\n def self() do\n :erlang.self()\n end\n\n @doc \"\"\"\n Spawns the given function and returns its pid.\n\n Check the modules `Process` and `Node` for other functions\n to handle processes, including spawning functions in nodes.\n\n Inlined by the compiler.\n\n ## Examples\n\n current = Kernel.self\n child = spawn(fn -> send current, {Kernel.self, 1 + 2} end)\n\n receive do\n {^child, 3} -> IO.puts \"Received 3 back\"\n end\n\n \"\"\"\n @spec spawn((() -> any)) :: pid\n def spawn(fun) do\n :erlang.spawn(fun)\n end\n\n @doc \"\"\"\n Spawns the given module and function passing the given args\n and returns its pid.\n\n Check the modules `Process` and `Node` for other functions\n to handle processes, including spawning functions in nodes.\n\n Inlined by the compiler.\n\n ## Examples\n\n spawn(SomeModule, :function, [1, 2, 3])\n\n \"\"\"\n @spec spawn(module, atom, list) :: pid\n def spawn(module, fun, args) do\n :erlang.spawn(module, fun, args)\n end\n\n @doc \"\"\"\n Spawns the given function, links it to the current process and returns its pid.\n\n Check the modules `Process` and `Node` for other functions\n to handle processes, including spawning functions in nodes.\n\n Inlined by the compiler.\n\n ## Examples\n\n current = Kernel.self\n child = spawn_link(fn -> send current, {Kernel.self, 1 + 2} end)\n\n receive do\n {^child, 3} -> IO.puts \"Received 3 back\"\n end\n\n \"\"\"\n @spec spawn_link((() -> any)) :: pid\n def spawn_link(fun) do\n :erlang.spawn_link(fun)\n end\n\n @doc \"\"\"\n Spawns the given module and function passing the given args,\n links it to the current process and returns its pid.\n\n Check the modules `Process` and `Node` for other functions\n to handle processes, including spawning functions in nodes.\n\n Inlined by the compiler.\n\n ## Examples\n\n spawn_link(SomeModule, :function, [1, 2, 3])\n\n \"\"\"\n @spec spawn_link(module, atom, list) :: pid\n def spawn_link(module, fun, args) do\n :erlang.spawn_link(module, fun, args)\n end\n\n @doc \"\"\"\n Spawns the given function, monitors it and returns its pid\n and monitoring reference.\n\n Check the modules `Process` and `Node` for other functions\n to handle processes, including spawning functions in nodes.\n\n Inlined by the compiler.\n\n ## Examples\n\n current = Kernel.self\n spawn_monitor(fn -> send current, {Kernel.self, 1 + 2} end)\n\n \"\"\"\n @spec spawn_monitor((() -> any)) :: {pid, reference}\n def spawn_monitor(fun) do\n :erlang.spawn_monitor(fun)\n end\n\n @doc \"\"\"\n Spawns the given module and function passing the given args,\n monitors it and returns its pid and monitoring reference.\n\n Check the modules `Process` and `Node` for other functions\n to handle processes, including spawning functions in nodes.\n\n Inlined by the compiler.\n\n ## Examples\n\n spawn_monitor(SomeModule, :function, [1, 2, 3])\n\n \"\"\"\n @spec spawn_monitor(module, atom, list) :: {pid, reference}\n def spawn_monitor(module, fun, args) do\n :erlang.spawn_monitor(module, fun, args)\n end\n\n @doc \"\"\"\n A non-local return from a function. Check `Kernel.SpecialForms.try\/1` for more information.\n\n Inlined by the compiler.\n \"\"\"\n @spec throw(term) :: no_return\n def throw(term) do\n :erlang.throw(term)\n end\n\n @doc \"\"\"\n Returns the tail of a list. Raises `ArgumentError` if the list is empty.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec tl(maybe_improper_list) :: maybe_improper_list\n def tl(list) do\n :erlang.tl(list)\n end\n\n @doc \"\"\"\n Returns an integer by truncating the given number.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> trunc(5.5)\n 5\n\n \"\"\"\n @spec trunc(number) :: integer\n def trunc(number) do\n :erlang.trunc(number)\n end\n\n @doc \"\"\"\n Returns the size of a tuple.\n\n This operation happens in constant time.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec tuple_size(tuple) :: non_neg_integer\n def tuple_size(tuple) do\n :erlang.tuple_size(tuple)\n end\n\n @doc \"\"\"\n Arithmetic plus.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 + 2\n 3\n\n \"\"\"\n @spec (number + number) :: number\n def left + right do\n :erlang.+(left, right)\n end\n\n @doc \"\"\"\n Arithmetic minus.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 - 2\n -1\n\n \"\"\"\n @spec (number - number) :: number\n def left - right do\n :erlang.-(left, right)\n end\n\n @doc \"\"\"\n Arithmetic unary plus.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> +1\n 1\n\n \"\"\"\n @spec (+number) :: number\n def (+value) do\n :erlang.+(value)\n end\n\n @doc \"\"\"\n Arithmetic unary minus.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> -2\n -2\n\n \"\"\"\n @spec (-number) :: number\n def (-value) do\n :erlang.-(value)\n end\n\n @doc \"\"\"\n Arithmetic multiplication.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 * 2\n 2\n\n \"\"\"\n @spec (number * number) :: number\n def left * right do\n :erlang.*(left, right)\n end\n\n @doc \"\"\"\n Arithmetic division.\n\n The result is always a float. Use `div` and `rem` if you want\n a natural division or the remainder.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 \/ 2\n 0.5\n\n iex> 2 \/ 1\n 2.0\n\n \"\"\"\n @spec (number \/ number) :: float\n def left \/ right do\n :erlang.\/(left, right)\n end\n\n @doc \"\"\"\n Concatenates two lists.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> [1] ++ [2, 3]\n [1,2,3]\n\n iex> 'foo' ++ 'bar'\n 'foobar'\n\n \"\"\"\n @spec (list ++ term) :: maybe_improper_list\n def left ++ right do\n :erlang.++(left, right)\n end\n\n @doc \"\"\"\n Removes the first occurrence of an item on the left\n for each item on the right.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> [1, 2, 3] -- [1, 2]\n [3]\n\n iex> [1, 2, 3, 2, 1] -- [1, 2, 2]\n [3,1]\n\n \"\"\"\n @spec (list -- list) :: list\n def left -- right do\n :erlang.--(left, right)\n end\n\n @doc false\n def left xor right do\n :erlang.xor(left, right)\n end\n\n @doc \"\"\"\n Boolean not. Argument must be a boolean.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> not false\n true\n\n \"\"\"\n @spec not(boolean) :: boolean\n def not(arg) do\n :erlang.not(arg)\n end\n\n @doc \"\"\"\n Returns `true` if left is less than right.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 < 2\n true\n\n \"\"\"\n @spec (term < term) :: boolean\n def left < right do\n :erlang.<(left, right)\n end\n\n @doc \"\"\"\n Returns `true` if left is more than right.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 > 2\n false\n\n \"\"\"\n @spec (term > term) :: boolean\n def left > right do\n :erlang.>(left, right)\n end\n\n @doc \"\"\"\n Returns `true` if left is less than or equal to right.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 <= 2\n true\n\n \"\"\"\n @spec (term <= term) :: boolean\n def left <= right do\n :erlang.\"=<\"(left, right)\n end\n\n @doc \"\"\"\n Returns `true` if left is more than or equal to right.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 >= 2\n false\n\n \"\"\"\n @spec (term >= term) :: boolean\n def left >= right do\n :erlang.>=(left, right)\n end\n\n @doc \"\"\"\n Returns `true` if the two items are equal.\n\n This operator considers 1 and 1.0 to be equal. For match\n semantics, use `===` instead.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 == 2\n false\n\n iex> 1 == 1.0\n true\n\n \"\"\"\n @spec (term == term) :: boolean\n def left == right do\n :erlang.==(left, right)\n end\n\n @doc \"\"\"\n Returns `true` if the two items are not equal.\n\n This operator considers 1 and 1.0 to be equal. For match\n comparison, use `!==` instead.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 != 2\n true\n\n iex> 1 != 1.0\n false\n\n \"\"\"\n @spec (term != term) :: boolean\n def left != right do\n :erlang.\"\/=\"(left, right)\n end\n\n @doc \"\"\"\n Returns `true` if the two items are match.\n\n This operator gives the same semantics as the one existing in\n pattern matching, i.e., `1` and `1.0` are equal, but they do\n not match.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 === 2\n false\n\n iex> 1 === 1.0\n false\n\n \"\"\"\n @spec (term === term) :: boolean\n def left === right do\n :erlang.\"=:=\"(left, right)\n end\n\n @doc \"\"\"\n Returns `true` if the two items do not match.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 !== 2\n true\n\n iex> 1 !== 1.0\n true\n\n \"\"\"\n @spec (term !== term) :: boolean\n def left !== right do\n :erlang.\"=\/=\"(left, right)\n end\n\n @doc \"\"\"\n Get the element at the zero-based `index` in `tuple`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Example\n\n iex> tuple = {:foo, :bar, 3}\n iex> elem(tuple, 1)\n :bar\n\n \"\"\"\n @spec elem(tuple, non_neg_integer) :: term\n def elem(tuple, index) do\n :erlang.element(index + 1, tuple)\n end\n\n @doc \"\"\"\n Puts the element in `tuple` at the zero-based `index` to the given `value`.\n\n Inlined by the compiler.\n\n ## Example\n\n iex> tuple = {:foo, :bar, 3}\n iex> put_elem(tuple, 0, :baz)\n {:baz, :bar, 3}\n\n \"\"\"\n @spec put_elem(tuple, non_neg_integer, term) :: tuple\n def put_elem(tuple, index, value) do\n :erlang.setelement(index + 1, tuple, value)\n end\n\n ## Implemented in Elixir\n\n @doc \"\"\"\n Boolean or. Requires only the first argument to be a\n boolean since it short-circuits.\n\n Allowed in guard tests.\n\n ## Examples\n\n iex> true or false\n true\n\n \"\"\"\n defmacro left or right do\n quote do: __op__(:orelse, unquote(left), unquote(right))\n end\n\n @doc \"\"\"\n Boolean and. Requires only the first argument to be a\n boolean since it short-circuits.\n\n Allowed in guard tests.\n\n ## Examples\n\n iex> true and false\n false\n\n \"\"\"\n defmacro left and right do\n quote do: __op__(:andalso, unquote(left), unquote(right))\n end\n\n @doc \"\"\"\n Receives any argument and returns `true` if it is `false`\n or `nil`. Returns `false` otherwise. Not allowed in guard\n clauses.\n\n ## Examples\n\n iex> !Enum.empty?([])\n false\n\n iex> !List.first([])\n true\n\n \"\"\"\n defmacro !(arg)\n\n defmacro !({:!, _, [arg]}) do\n optimize_boolean(quote do\n case unquote(arg) do\n x when x in [false, nil] -> false\n _ -> true\n end\n end)\n end\n\n defmacro !(arg) do\n optimize_boolean(quote do\n case unquote(arg) do\n x when x in [false, nil] -> true\n _ -> false\n end\n end)\n end\n\n @doc \"\"\"\n Concatenates two binaries.\n\n ## Examples\n\n iex> \"foo\" <> \"bar\"\n \"foobar\"\n\n The `<>` operator can also be used in guard clauses as\n long as the first part is a literal binary:\n\n iex> \"foo\" <> x = \"foobar\"\n iex> x\n \"bar\"\n\n \"\"\"\n defmacro left <> right do\n concats = extract_concatenations({:<>, [], [left, right]})\n quote do: << unquote_splicing(concats) >>\n end\n\n # Extracts concatenations in order to optimize many\n # concatenations into one single clause.\n defp extract_concatenations({:<>, _, [left, right]}) do\n [wrap_concatenation(left)|extract_concatenations(right)]\n end\n\n defp extract_concatenations(other) do\n [wrap_concatenation(other)]\n end\n\n defp wrap_concatenation(binary) when is_binary(binary) do\n binary\n end\n\n defp wrap_concatenation(other) do\n {:::, [], [other, {:binary, [], nil}]}\n end\n\n @doc \"\"\"\n Raises an exception.\n\n If the argument is a binary, it raises `RuntimeError`\n using the given argument as message.\n\n If an atom, it will become a call to `raise(atom, [])`.\n\n If anything else, it will just raise the given exception.\n\n ## Examples\n\n raise \"Given values do not match\"\n\n try do\n 1 + :foo\n rescue\n x in [ArithmeticError] ->\n IO.puts \"that was expected\"\n raise x\n end\n\n \"\"\"\n defmacro raise(msg) do\n # Try to figure out the type at compilation time\n # to avoid dead code and make dialyzer happy.\n msg = case not is_binary(msg) and bootstraped?(Macro) do\n true -> Macro.expand(msg, __CALLER__)\n false -> msg\n end\n\n case msg do\n msg when is_binary(msg) ->\n quote do\n :erlang.error RuntimeError.exception(unquote(msg))\n end\n {:<<>>, _, _} = msg ->\n quote do\n :erlang.error RuntimeError.exception(unquote(msg))\n end\n alias when is_atom(alias) ->\n quote do\n :erlang.error unquote(alias).exception([])\n end\n _ ->\n quote do\n case unquote(msg) do\n msg when is_binary(msg) ->\n :erlang.error RuntimeError.exception(msg)\n atom when is_atom(atom) ->\n :erlang.error atom.exception([])\n %{__struct__: struct, __exception__: true} = other when is_atom(struct) ->\n :erlang.error other\n end\n end\n end\n end\n\n @doc \"\"\"\n Raises an exception.\n\n Calls `.exception` on the given argument passing\n the attributes in order to retrieve the appropriate exception\n structure.\n\n Any module defined via `defexception\/1` automatically\n implements `exception(attrs)` callback expected by `raise\/2`.\n\n ## Examples\n\n iex> raise(ArgumentError, message: \"Sample\")\n ** (ArgumentError) Sample\n\n \"\"\"\n defmacro raise(exception, attrs) do\n quote do\n :erlang.error unquote(exception).exception(unquote(attrs))\n end\n end\n\n @doc \"\"\"\n Raises an exception preserving a previous stacktrace.\n\n Works like `raise\/1` but does not generate a new stacktrace.\n\n Notice that `System.stacktrace` returns the stacktrace\n of the last exception. That said, it is common to assign\n the stacktrace as the first expression inside a `rescue`\n clause as any other exception potentially raised (and\n rescued) in between the rescue clause and the raise call\n may change the `System.stacktrace` value.\n\n ## Examples\n\n try do\n raise \"Oops\"\n rescue\n exception ->\n stacktrace = System.stacktrace\n if Exception.message(exception) == \"Oops\" do\n reraise exception, stacktrace\n end\n end\n \"\"\"\n defmacro reraise(msg, stacktrace) do\n # Try to figure out the type at compilation time\n # to avoid dead code and make dialyzer happy.\n\n case Macro.expand(msg, __CALLER__) do\n msg when is_binary(msg) ->\n quote do\n :erlang.raise :error, RuntimeError.exception(unquote(msg)), unquote(stacktrace)\n end\n {:<<>>, _, _} = msg ->\n quote do\n :erlang.raise :error, RuntimeError.exception(unquote(msg)), unquote(stacktrace)\n end\n alias when is_atom(alias) ->\n quote do\n :erlang.raise :error, unquote(alias).exception([]), unquote(stacktrace)\n end\n msg ->\n quote do\n stacktrace = unquote(stacktrace)\n case unquote(msg) do\n msg when is_binary(msg) ->\n :erlang.raise :error, RuntimeError.exception(msg), stacktrace\n atom when is_atom(atom) ->\n :erlang.raise :error, atom.exception([]), stacktrace\n %{__struct__: struct, __exception__: true} = other when is_atom(struct) ->\n :erlang.raise :error, other, stacktrace\n end\n end\n end\n end\n\n @doc \"\"\"\n Raises an exception preserving a previous stacktrace.\n\n Works like `raise\/2` but does not generate a new stacktrace.\n\n See `reraise\/2` for more details.\n\n ## Examples\n\n try do\n raise \"Oops\"\n rescue\n exception ->\n stacktrace = System.stacktrace\n reraise WrapperError, [exception: exception], stacktrace\n end\n \"\"\"\n defmacro reraise(exception, attrs, stacktrace) do\n quote do\n :erlang.raise :error, unquote(exception).exception(unquote(attrs)), unquote(stacktrace)\n end\n end\n\n @doc \"\"\"\n Matches the term on the left against the regular expression or string on the\n right. Returns true if `left` matches `right` (if it's a regular expression)\n or contains `right` (if it's a string).\n\n ## Examples\n\n iex> \"abcd\" =~ ~r\/c(d)\/\n true\n\n iex> \"abcd\" =~ ~r\/e\/\n false\n\n iex> \"abcd\" =~ \"bc\"\n true\n\n iex> \"abcd\" =~ \"ad\"\n false\n\n \"\"\"\n def left =~ right when is_binary(left) and is_binary(right) do\n :binary.match(left, right) != :nomatch\n end\n\n def left =~ right when is_binary(left) do\n Regex.match?(right, left)\n end\n\n @doc ~S\"\"\"\n Inspect the given argument according to the `Inspect` protocol.\n The second argument is a keywords list with options to control\n inspection.\n\n ## Options\n\n `inspect\/2` accepts a list of options that are internally\n translated to an `Inspect.Opts` struct. Check the docs for\n `Inspect.Opts` to see the supported options.\n\n ## Examples\n\n iex> inspect(:foo)\n \":foo\"\n\n iex> inspect [1, 2, 3, 4, 5], limit: 3\n \"[1, 2, 3, ...]\"\n\n iex> inspect(\"jos\u00e9\" <> <<0>>)\n \"<<106, 111, 115, 195, 169, 0>>\"\n\n iex> inspect(\"jos\u00e9\" <> <<0>>, binaries: :as_strings)\n \"\\\"jos\u00e9\\\\000\\\"\"\n\n iex> inspect(\"jos\u00e9\", binaries: :as_binaries)\n \"<<106, 111, 115, 195, 169>>\"\n\n Note that the inspect protocol does not necessarily return a valid\n representation of an Elixir term. In such cases, the inspected result\n must start with `#`. For example, inspecting a function will return:\n\n inspect fn a, b -> a + b end\n #=> #Function<...>\n\n \"\"\"\n @spec inspect(Inspect.t, Keyword.t) :: String.t\n def inspect(arg, opts \\\\ []) when is_list(opts) do\n opts = struct(Inspect.Opts, opts)\n limit = case opts.pretty do\n true -> opts.width\n false -> :infinity\n end\n Inspect.Algebra.pretty(Inspect.Algebra.to_doc(arg, opts), limit)\n end\n\n @doc \"\"\"\n Creates and updates structs.\n\n The struct argument may be an atom (which defines `defstruct`)\n or a struct itself. The second argument is any Enumerable that\n emits two-item tuples (key-value) during enumeration.\n\n If one of the keys in the Enumerable does not exist in the struct,\n they are automatically discarded.\n\n This function is useful for dynamically creating and updating\n structs.\n\n ## Example\n\n defmodule User do\n defstruct name: \"jose\"\n end\n\n struct(User)\n #=> %User{name: \"jose\"}\n\n opts = [name: \"eric\"]\n user = struct(User, opts)\n #=> %User{name: \"eric\"}\n\n struct(user, unknown: \"value\")\n #=> %User{name: \"eric\"}\n\n \"\"\"\n @spec struct(module | map, Enum.t) :: map\n def struct(struct, kv \\\\ [])\n\n def struct(struct, []) when is_atom(struct) or is_tuple(struct) do\n apply(struct, :__struct__, [])\n end\n\n def struct(struct, kv) when is_atom(struct) or is_tuple(struct) do\n struct(apply(struct, :__struct__, []), kv)\n end\n\n def struct(%{__struct__: _} = struct, kv) do\n Enum.reduce(kv, struct, fn {k, v}, acc ->\n case :maps.is_key(k, acc) and k != :__struct__ do\n true -> :maps.put(k, v, acc)\n false -> acc\n end\n end)\n end\n\n @doc \"\"\"\n Gets a value from a nested structure.\n\n Uses the `Access` protocol to traverse the structures\n according to the given `keys`, unless the `key` is a\n function.\n\n If a key is a function, the function will be invoked\n passing three arguments, the operation (`:get`), the\n data to be accessed, and a function to be invoked next.\n\n This means `get_in\/2` can be extended to provide\n custom lookups. The downside is that functions cannot be\n stored as keys in the accessed data structures.\n\n ## Examples\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> get_in(users, [\"jos\u00e9\", :age])\n 27\n\n In case any of entries in the middle returns `nil`, `nil` will be returned\n as per the Access protocol:\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> get_in(users, [\"unknown\", :age])\n nil\n\n When one of the keys is a function, the function is invoked.\n In the example below, we use a function to get all the maps\n inside a list:\n\n iex> users = [%{name: \"jos\u00e9\", age: 27}, %{name: \"eric\", age: 23}]\n iex> all = fn :get, data, next -> Enum.map(data, next) end\n iex> get_in(users, [all, :age])\n [27, 23]\n\n If the previous value before invoking the function is nil,\n the function *will* receive nil as a value and must handle it\n accordingly.\n \"\"\"\n @spec get_in(Access.t, nonempty_list(term)) :: term\n def get_in(data, keys)\n\n def get_in(data, [h]) when is_function(h),\n do: h.(:get, data, &(&1))\n def get_in(data, [h|t]) when is_function(h),\n do: h.(:get, data, &get_in(&1, t))\n\n def get_in(nil, [_]),\n do: nil\n def get_in(nil, [_|t]),\n do: get_in(nil, t)\n\n def get_in(data, [h]),\n do: Access.get(data, h)\n def get_in(data, [h|t]),\n do: get_in(Access.get(data, h), t)\n\n @doc \"\"\"\n Puts a value in a nested structure.\n\n Uses the `Access` protocol to traverse the structures\n according to the given `keys`, unless the `key` is a\n function. If the key is a function, it will be invoked\n as specified in `get_and_update_in\/3`.\n\n ## Examples\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> put_in(users, [\"jos\u00e9\", :age], 28)\n %{\"jos\u00e9\" => %{age: 28}, \"eric\" => %{age: 23}}\n\n In case any of entries in the middle returns `nil`,\n an error will be raised when trying to access it next.\n \"\"\"\n @spec put_in(Access.t, nonempty_list(term), term) :: Access.t\n def put_in(data, keys, value) do\n elem(get_and_update_in(data, keys, fn _ -> {nil, value} end), 1)\n end\n\n @doc \"\"\"\n Updates a key in a nested structure.\n\n Uses the `Access` protocol to traverse the structures\n according to the given `keys`, unless the `key` is a\n function. If the key is a function, it will be invoked\n as specified in `get_and_update_in\/3`.\n\n ## Examples\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> update_in(users, [\"jos\u00e9\", :age], &(&1 + 1))\n %{\"jos\u00e9\" => %{age: 28}, \"eric\" => %{age: 23}}\n\n In case any of entries in the middle returns `nil`,\n an error will be raised when trying to access it next.\n \"\"\"\n @spec update_in(Access.t, nonempty_list(term), (term -> term)) :: Access.t\n def update_in(data, keys, fun) do\n elem(get_and_update_in(data, keys, fn x -> {nil, fun.(x)} end), 1)\n end\n\n @doc \"\"\"\n Gets a value and updates a nested structure.\n\n It expects a tuple to be returned, containing the value\n retrieved and the update one.\n\n Uses the `Access` protocol to traverse the structures\n according to the given `keys`, unless the `key` is a\n function.\n\n If a key is a function, the function will be invoked\n passing three arguments, the operation (`:get_and_update`),\n the data to be accessed, and a function to be invoked next.\n\n This means `get_and_update_in\/3` can be extended to provide\n custom lookups. The downside is that functions cannot be stored\n as keys in the accessed data structures.\n\n ## Examples\n\n This function is useful when there is a need to retrieve the current\n value (or something calculated in function of the current value) and\n update it at the same time. For example, it could be used to increase\n the age of a user by one and return the previous age in one pass:\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> get_and_update_in(users, [\"jos\u00e9\", :age], &{&1, &1 + 1})\n {27, %{\"jos\u00e9\" => %{age: 28}, \"eric\" => %{age: 23}}}\n\n When one of the keys is a function, the function is invoked.\n In the example below, we use a function to get and increment all\n ages inside a list:\n\n iex> users = [%{name: \"jos\u00e9\", age: 27}, %{name: \"eric\", age: 23}]\n iex> all = fn :get_and_update, data, next ->\n ...> Enum.map(data, next) |> List.unzip() |> List.to_tuple()\n ...> end\n iex> get_and_update_in(users, [all, :age], &{&1, &1 + 1})\n {[27, 23], [%{name: \"jos\u00e9\", age: 28}, %{name: \"eric\", age: 24}]}\n\n If the previous value before invoking the function is nil,\n the function *will* receive `nil` as a value and must handle it\n accordingly (be it by failing or providing a sane default).\n \"\"\"\n @spec get_and_update_in(Access.t, nonempty_list(term),\n (term -> {get, term})) :: {get, Access.t} when get: var\n def get_and_update_in(data, keys, fun)\n\n def get_and_update_in(data, [h], fun) when is_function(h),\n do: h.(:get_and_update, data, fun)\n def get_and_update_in(data, [h|t], fun) when is_function(h),\n do: h.(:get_and_update, data, &get_and_update_in(&1, t, fun))\n\n def get_and_update_in(data, [h], fun),\n do: Access.get_and_update(data, h, fun)\n def get_and_update_in(data, [h|t], fun),\n do: Access.get_and_update(data, h, &get_and_update_in(&1, t, fun))\n\n @doc \"\"\"\n Puts a value in a nested structure via the given `path`.\n\n This is similar to `put_in\/3`, except the path is extracted via\n a macro rather than passing a list. For example:\n\n put_in(opts[:foo][:bar], :baz)\n\n Is equivalent to:\n\n put_in(opts, [:foo, :bar], :baz)\n\n Note that in order for this macro to work, the complete path must always\n be visible by this macro. For more information about the supported path\n expressions, please check `get_and_update_in\/2` docs.\n\n ## Examples\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> put_in(users[\"jos\u00e9\"][:age], 28)\n %{\"jos\u00e9\" => %{age: 28}, \"eric\" => %{age: 23}}\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> put_in(users[\"jos\u00e9\"].age, 28)\n %{\"jos\u00e9\" => %{age: 28}, \"eric\" => %{age: 23}}\n\n \"\"\"\n defmacro put_in(path, value) do\n [h|t] = unnest(path, [], \"put_in\/2\")\n expr = nest_get_and_update_in(h, t, quote(do: fn _ -> {nil, unquote(value)} end))\n quote do: :erlang.element(2, unquote(expr))\n end\n\n @doc \"\"\"\n Updates a nested structure via the given `path`.\n\n This is similar to `update_in\/3`, except the path is extracted via\n a macro rather than passing a list. For example:\n\n update_in(opts[:foo][:bar], &(&1 + 1))\n\n Is equivalent to:\n\n update_in(opts, [:foo, :bar], &(&1 + 1))\n\n Note that in order for this macro to work, the complete path must always\n be visible by this macro. For more information about the supported path\n expressions, please check `get_and_update_in\/2` docs.\n\n ## Examples\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> update_in(users[\"jos\u00e9\"][:age], &(&1 + 1))\n %{\"jos\u00e9\" => %{age: 28}, \"eric\" => %{age: 23}}\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> update_in(users[\"jos\u00e9\"].age, &(&1 + 1))\n %{\"jos\u00e9\" => %{age: 28}, \"eric\" => %{age: 23}}\n\n \"\"\"\n defmacro update_in(path, fun) do\n [h|t] = unnest(path, [], \"update_in\/2\")\n expr = nest_get_and_update_in(h, t, quote(do: fn x -> {nil, unquote(fun).(x)} end))\n quote do: :erlang.element(2, unquote(expr))\n end\n\n @doc \"\"\"\n Gets a value and updates a nested data structure via the given `path`.\n\n This is similar to `get_and_update_in\/3`, except the path is extracted\n via a macro rather than passing a list. For example:\n\n get_and_update_in(opts[:foo][:bar], &{&1, &1 + 1})\n\n Is equivalent to:\n\n get_and_update_in(opts, [:foo, :bar], &{&1, &1 + 1})\n\n Note that in order for this macro to work, the complete path must always\n be visible by this macro. See the Paths section below.\n\n ## Examples\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> get_and_update_in(users[\"jos\u00e9\"].age, &{&1, &1 + 1})\n {27, %{\"jos\u00e9\" => %{age: 28}, \"eric\" => %{age: 23}}}\n\n ## Paths\n\n A path may start with a variable, local or remote call, and must be\n followed by one or more:\n\n * `foo[bar]` - access a field; in case an intermediate field is not\n present or returns nil, an empty map is used\n\n * `foo.bar` - access a map\/struct field; in case the field is not\n present, an error is raised\n\n Here are some valid paths:\n\n users[\"jos\u00e9\"][:age]\n users[\"jos\u00e9\"].age\n User.all[\"jos\u00e9\"].age\n all_users()[\"jos\u00e9\"].age\n\n Here are some invalid ones:\n\n # Does a remote call after the initial value\n users[\"jos\u00e9\"].do_something(arg1, arg2)\n\n # Does not access any field\n users\n\n \"\"\"\n defmacro get_and_update_in(path, fun) do\n [h|t] = unnest(path, [], \"get_and_update_in\/2\")\n nest_get_and_update_in(h, t, fun)\n end\n\n defp nest_get_and_update_in([], fun), do: fun\n defp nest_get_and_update_in(list, fun) do\n quote do\n fn x -> unquote(nest_get_and_update_in(quote(do: x), list, fun)) end\n end\n end\n\n defp nest_get_and_update_in(h, [{:access, key}|t], fun) do\n quote do\n Access.get_and_update(\n case(unquote(h), do: (nil -> %{}; o -> o)),\n unquote(key),\n unquote(nest_get_and_update_in(t, fun))\n )\n end\n end\n\n defp nest_get_and_update_in(h, [{:map, key}|t], fun) do\n quote do\n Access.Map.get_and_update!(unquote(h), unquote(key), unquote(nest_get_and_update_in(t, fun)))\n end\n end\n\n defp unnest({{:., _, [Access, :get]}, _, [expr, key]}, acc, kind) do\n unnest(expr, [{:access, key}|acc], kind)\n end\n\n defp unnest({{:., _, [expr, key]}, _, []}, acc, kind)\n when is_tuple(expr) and elem(expr, 0) != :__aliases__ and elem(expr, 0) != :__MODULE__ do\n unnest(expr, [{:map, key}|acc], kind)\n end\n\n defp unnest(other, [], kind) do\n raise ArgumentError,\n \"expected expression given to #{kind} to access at least one element, got: #{Macro.to_string other}\"\n end\n\n defp unnest(other, acc, kind) do\n case proper_start?(other) do\n true -> [other|acc]\n false ->\n raise ArgumentError,\n \"expression given to #{kind} must start with a variable, local or remote call \" <>\n \"and be followed by an element access, got: #{Macro.to_string other}\"\n end\n end\n\n defp proper_start?({{:., _, [expr, _]}, _, _args})\n when is_atom(expr)\n when elem(expr, 0) == :__aliases__\n when elem(expr, 0) == :__MODULE__, do: true\n\n defp proper_start?({atom, _, _args})\n when is_atom(atom), do: true\n\n defp proper_start?(other),\n do: not is_tuple(other)\n\n @doc \"\"\"\n Converts the argument to a string according to the\n `String.Chars` protocol.\n\n This is the function invoked when there is string interpolation.\n\n ## Examples\n\n iex> to_string(:foo)\n \"foo\"\n\n \"\"\"\n # If it is a binary at compilation time, simply return it.\n defmacro to_string(arg) when is_binary(arg), do: arg\n\n defmacro to_string(arg) do\n quote do: String.Chars.to_string(unquote(arg))\n end\n\n @doc \"\"\"\n Convert the argument to a list according to the List.Chars protocol.\n\n ## Examples\n\n iex> to_char_list(:foo)\n 'foo'\n\n \"\"\"\n defmacro to_char_list(arg) do\n quote do: List.Chars.to_char_list(unquote(arg))\n end\n\n @doc \"\"\"\n Checks if the given argument is nil or not.\n Allowed in guard clauses.\n\n ## Examples\n\n iex> nil?(1)\n false\n\n iex> nil?(nil)\n true\n\n \"\"\"\n defmacro nil?(x) do\n quote do: unquote(x) == nil\n end\n\n @doc \"\"\"\n A convenient macro that checks if the right side matches\n the left side. The left side is allowed to be a match pattern.\n\n ## Examples\n\n iex> match?(1, 1)\n true\n\n iex> match?(1, 2)\n false\n\n iex> match?({1, _}, {1, 2})\n true\n\n Match can also be used to filter or find a value in an enumerable:\n\n list = [{:a, 1}, {:b, 2}, {:a, 3}]\n Enum.filter list, &match?({:a, _}, &1)\n\n Guard clauses can also be given to the match:\n\n list = [{:a, 1}, {:b, 2}, {:a, 3}]\n Enum.filter list, &match?({:a, x} when x < 2, &1)\n\n However, variables assigned in the match will not be available\n outside of the function call:\n\n iex> match?(x, 1)\n true\n\n iex> binding([:x]) == []\n true\n\n \"\"\"\n defmacro match?(pattern, expr)\n\n # Special case underscore since it always matches\n defmacro match?({:_, _, atom}, _right) when is_atom(atom) do\n true\n end\n\n defmacro match?(left, right) do\n quote do\n case unquote(right) do\n unquote(left) ->\n true\n _ ->\n false\n end\n end\n end\n\n @doc \"\"\"\n Read and write attributes of th current module.\n\n The canonical example for attributes is annotating that a module\n implements the OTP behaviour called `gen_server`:\n\n defmodule MyServer do\n @behaviour :gen_server\n # ... callbacks ...\n end\n\n By default Elixir supports all Erlang module attributes, but any developer\n can also add custom attributes:\n\n defmodule MyServer do\n @my_data 13\n IO.inspect @my_data #=> 13\n end\n\n Unlike Erlang, such attributes are not stored in the module by\n default since it is common in Elixir to use such attributes to store\n temporary data. A developer can configure an attribute to behave closer\n to Erlang by calling `Module.register_attribute\/3`.\n\n Finally, notice that attributes can also be read inside functions:\n\n defmodule MyServer do\n @my_data 11\n def first_data, do: @my_data\n @my_data 13\n def second_data, do: @my_data\n end\n\n MyServer.first_data #=> 11\n MyServer.second_data #=> 13\n\n It is important to note that reading an attribute takes a snapshot of\n its current value. In other words, the value is read at compilation\n time and not at runtime. Check the module `Module` for other functions\n to manipulate module attributes.\n \"\"\"\n defmacro @(expr)\n\n # Typespecs attributes are special cased by the compiler so far\n defmacro @({name, _, args}) do\n # Check for Macro as it is compiled later than Module\n case bootstraped?(Module) do\n false -> nil\n true ->\n assert_module_scope(__CALLER__, :@, 1)\n function? = __CALLER__.function != nil\n\n case is_list(args) and length(args) == 1 and typespec(name) do\n false ->\n case name == :typedoc and not bootstraped?(Kernel.Typespec) do\n true -> nil\n false -> do_at(args, name, function?, __CALLER__)\n end\n macro ->\n case bootstraped?(Kernel.Typespec) do\n false -> nil\n true -> quote do: Kernel.Typespec.unquote(macro)(unquote(hd(args)))\n end\n end\n end\n end\n\n # @attribute value\n defp do_at([arg], name, function?, env) do\n case function? do\n true ->\n raise ArgumentError, \"cannot dynamically set attribute @#{name} inside function\"\n false ->\n case name do\n :behavior ->\n :elixir_errors.warn warn_info(env_stacktrace(env)),\n \"@behavior attribute is not supported, please use @behaviour instead\"\n _ ->\n :ok\n end\n\n quote do: Module.put_attribute(__MODULE__, unquote(name), unquote(arg))\n end\n end\n\n # @attribute or @attribute()\n defp do_at(args, name, function?, env) when is_atom(args) or args == [] do\n stack = env_stacktrace(env)\n\n case function? do\n true ->\n attr = Module.get_attribute(env.module, name, stack)\n :erlang.element(1, :elixir_quote.escape(attr, false))\n false ->\n escaped = case stack do\n [] -> []\n _ -> Macro.escape(stack)\n end\n quote do: Module.get_attribute(__MODULE__, unquote(name), unquote(escaped))\n end\n end\n\n # All other cases\n defp do_at(args, name, _function?, _env) do\n raise ArgumentError, \"expected 0 or 1 argument for @#{name}, got: #{length(args)}\"\n end\n\n defp warn_info([entry|_]) do\n opts = elem(entry, tuple_size(entry) - 1)\n Exception.format_file_line(Keyword.get(opts, :file), Keyword.get(opts, :line)) <> \" \"\n end\n\n defp warn_info([]) do\n \"\"\n end\n\n defp typespec(:type), do: :deftype\n defp typespec(:typep), do: :deftypep\n defp typespec(:opaque), do: :defopaque\n defp typespec(:spec), do: :defspec\n defp typespec(:callback), do: :defcallback\n defp typespec(_), do: false\n\n @doc \"\"\"\n Returns the binding as a keyword list where the variable name\n is the key and the variable value is the value.\n\n ## Examples\n\n iex> x = 1\n iex> binding()\n [x: 1]\n iex> x = 2\n iex> binding()\n [x: 2]\n\n \"\"\"\n defmacro binding() do\n do_binding(nil, nil, __CALLER__.vars, Macro.Env.in_match?(__CALLER__))\n end\n\n @doc \"\"\"\n Receives a list of atoms at compilation time and returns the\n binding of the given variables as a keyword list where the\n variable name is the key and the variable value is the value.\n\n In case a variable in the list does not exist in the binding,\n it is not included in the returned result.\n\n ## Examples\n\n iex> x = 1\n iex> binding([:x, :y])\n [x: 1]\n\n \"\"\"\n defmacro binding(list) when is_list(list) do\n do_binding(list, nil, __CALLER__.vars, Macro.Env.in_match?(__CALLER__))\n end\n\n defmacro binding(context) when is_atom(context) do\n do_binding(nil, context, __CALLER__.vars, Macro.Env.in_match?(__CALLER__))\n end\n\n @doc \"\"\"\n Receives a list of atoms at compilation time and returns the\n binding of the given variables in the given context as a keyword\n list where the variable name is the key and the variable value\n is the value.\n\n In case a variable in the list does not exist in the binding,\n it is not included in the returned result.\n\n ## Examples\n\n iex> var!(x, :foo) = 1\n iex> binding([:x, :y])\n []\n iex> binding([:x, :y], :foo)\n [x: 1]\n\n \"\"\"\n defmacro binding(list, context) when is_list(list) and is_atom(context) do\n do_binding(list, context, __CALLER__.vars, Macro.Env.in_match?(__CALLER__))\n end\n\n defp do_binding(list, context, vars, in_match) do\n for {v, c} <- vars, c == context, list == nil or :lists.member(v, list) do\n {v, wrap_binding(in_match, {v, [], c})}\n end\n end\n\n defp wrap_binding(true, var) do\n quote do: ^(unquote(var))\n end\n\n defp wrap_binding(_, var) do\n var\n end\n\n @doc \"\"\"\n Provides an `if` macro. This macro expects the first argument to\n be a condition and the rest are keyword arguments.\n\n ## One-liner examples\n\n if(foo, do: bar)\n\n In the example above, `bar` will be returned if `foo` evaluates to\n `true` (i.e. it is neither `false` nor `nil`). Otherwise, `nil` will be returned.\n\n An `else` option can be given to specify the opposite:\n\n if(foo, do: bar, else: baz)\n\n ## Blocks examples\n\n Elixir also allows you to pass a block to the `if` macro. The first\n example above would be translated to:\n\n if foo do\n bar\n end\n\n Notice that `do\/end` becomes delimiters. The second example would\n then translate to:\n\n if foo do\n bar\n else\n baz\n end\n\n If you want to compare more than two clauses, you can use the `cond\/1`\n macro.\n \"\"\"\n defmacro if(condition, clauses) do\n do_clause = Keyword.get(clauses, :do, nil)\n else_clause = Keyword.get(clauses, :else, nil)\n\n optimize_boolean(quote do\n case unquote(condition) do\n x when x in [false, nil] -> unquote(else_clause)\n _ -> unquote(do_clause)\n end\n end)\n end\n\n @doc \"\"\"\n Evaluates and returns the do-block passed in as a second argument\n unless clause evaluates to true.\n Returns nil otherwise.\n See also `if`.\n\n ## Examples\n\n iex> unless(Enum.empty?([]), do: \"Hello\")\n nil\n\n iex> unless(Enum.empty?([1,2,3]), do: \"Hello\")\n \"Hello\"\n\n \"\"\"\n defmacro unless(clause, options) do\n do_clause = Keyword.get(options, :do, nil)\n else_clause = Keyword.get(options, :else, nil)\n quote do\n if(unquote(clause), do: unquote(else_clause), else: unquote(do_clause))\n end\n end\n\n @doc \"\"\"\n Allows you to destructure two lists, assigning each term in the right to the\n matching term in the left. Unlike pattern matching via `=`, if the sizes of\n the left and right lists don't match, destructuring simply stops instead of\n raising an error.\n\n ## Examples\n\n iex> destructure([x, y, z], [1, 2, 3, 4, 5])\n iex> {x, y, z}\n {1, 2, 3}\n\n Notice in the example above, even though the right\n size has more entries than the left, destructuring works\n fine. If the right size is smaller, the remaining items\n are simply assigned to nil:\n\n iex> destructure([x, y, z], [1])\n iex> {x, y, z}\n {1, nil, nil}\n\n The left side supports any expression you would use\n on the left side of a match:\n\n x = 1\n destructure([^x, y, z], [1, 2, 3])\n\n The example above will only work if x matches\n the first value from the right side. Otherwise,\n it will raise a CaseClauseError.\n \"\"\"\n defmacro destructure(left, right) when is_list(left) do\n Enum.reduce left, right, fn item, acc ->\n {:case, meta, args} =\n quote do\n case unquote(acc) do\n [unquote(item)|t] ->\n t\n other when other == [] or other == nil ->\n unquote(item) = nil\n end\n end\n {:case, [{:export_head,true}|meta], args}\n end\n end\n\n @doc \"\"\"\n Returns a range with the specified start and end.\n Includes both ends.\n\n ## Examples\n\n iex> 0 in 1..3\n false\n\n iex> 1 in 1..3\n true\n\n iex> 2 in 1..3\n true\n\n iex> 3 in 1..3\n true\n\n \"\"\"\n defmacro first .. last do\n {:%{}, [], [__struct__: Elixir.Range, first: first, last: last]}\n end\n\n @doc \"\"\"\n Provides a short-circuit operator that evaluates and returns\n the second expression only if the first one evaluates to true\n (i.e. it is not nil nor false). Returns the first expression\n otherwise.\n\n ## Examples\n\n iex> Enum.empty?([]) && Enum.empty?([])\n true\n\n iex> List.first([]) && true\n nil\n\n iex> Enum.empty?([]) && List.first([1])\n 1\n\n iex> false && throw(:bad)\n false\n\n Notice that, unlike Erlang's `and` operator,\n this operator accepts any expression as an argument,\n not only booleans, however it is not allowed in guards.\n \"\"\"\n defmacro left && right do\n quote do\n case unquote(left) do\n x when x in [false, nil] ->\n x\n _ ->\n unquote(right)\n end\n end\n end\n\n @doc \"\"\"\n Provides a short-circuit operator that evaluates and returns the second\n expression only if the first one does not evaluate to true (i.e. it\n is either nil or false). Returns the first expression otherwise.\n\n ## Examples\n\n iex> Enum.empty?([1]) || Enum.empty?([1])\n false\n\n iex> List.first([]) || true\n true\n\n iex> Enum.empty?([1]) || 1\n 1\n\n iex> Enum.empty?([]) || throw(:bad)\n true\n\n Notice that, unlike Erlang's `or` operator,\n this operator accepts any expression as an argument,\n not only booleans, however it is not allowed in guards.\n \"\"\"\n defmacro left || right do\n quote do\n case unquote(left) do\n x when x in [false, nil] ->\n unquote(right)\n x ->\n x\n end\n end\n end\n\n @doc \"\"\"\n `|>` is the pipe operator.\n\n This operator introduces the expression on the left as\n the first argument to the function call on the right.\n\n ## Examples\n\n iex> [1, [2], 3] |> List.flatten()\n [1, 2, 3]\n\n The example above is the same as calling `List.flatten([1, [2], 3])`,\n i.e. the argument on the left side of `|>` is introduced as the first\n argument of the function call on the right side.\n\n This pattern is mostly useful when there is a desire to execute\n a bunch of operations, resembling a pipeline:\n\n iex> [1, [2], 3] |> List.flatten |> Enum.map(fn x -> x * 2 end)\n [2, 4, 6]\n\n The example above will pass the list to `List.flatten\/1`, then get\n the flattened list and pass to `Enum.map\/2`, which will multiply\n each entry in the list per two.\n\n In other words, the expression above simply translates to:\n\n Enum.map(List.flatten([1, [2], 3]), fn x -> x * 2 end)\n\n Beware of operator precedence when using the pipe operator.\n For example, the following expression:\n\n String.graphemes \"Hello\" |> Enum.reverse\n\n Translates to:\n\n String.graphemes(\"Hello\" |> Enum.reverse)\n\n Which will result in an error as Enumerable protocol is not defined\n for binaries. Adding explicit parenthesis resolves the ambiguity:\n\n String.graphemes(\"Hello\") |> Enum.reverse\n\n Or, even better:\n\n \"Hello\" |> String.graphemes |> Enum.reverse\n\n \"\"\"\n defmacro left |> right do\n [{h, _}|t] = Macro.unpipe({:|>, [], [left, right]})\n :lists.foldl fn {x, pos}, acc -> Macro.pipe(acc, x, pos) end, h, t\n end\n\n @doc \"\"\"\n Returns true if the `module` is loaded and contains a\n public `function` with the given `arity`, otherwise false.\n\n Notice that this function does not load the module in case\n it is not loaded. Check `Code.ensure_loaded\/1` for more\n information.\n \"\"\"\n @spec function_exported?(atom | tuple, atom, integer) :: boolean\n def function_exported?(module, function, arity) do\n :erlang.function_exported(module, function, arity)\n end\n\n @doc \"\"\"\n Returns true if the `module` is loaded and contains a\n public `macro` with the given `arity`, otherwise false.\n\n Notice that this function does not load the module in case\n it is not loaded. Check `Code.ensure_loaded\/1` for more\n information.\n \"\"\"\n @spec macro_exported?(atom, atom, integer) :: boolean\n def macro_exported?(module, macro, arity) do\n case :code.is_loaded(module) do\n {:file, _} -> :lists.member({macro, arity}, module.__info__(:macros))\n _ -> false\n end\n end\n\n @doc \"\"\"\n Access the given element using the qualifier according\n to the `Access` protocol. All calls in the form `foo[bar]`\n are translated to `access(foo, bar)`.\n\n The usage of this protocol is to access a raw value in a\n keyword list.\n\n iex> sample = [a: 1, b: 2, c: 3]\n iex> sample[:b]\n 2\n\n \"\"\"\n\n @doc \"\"\"\n Checks if the element on the left side is member of the\n collection on the right side.\n\n ## Examples\n\n iex> x = 1\n iex> x in [1, 2, 3]\n true\n\n This macro simply translates the expression above to:\n\n Enum.member?([1,2,3], x)\n\n ## Guards\n\n The `in` operator can be used on guard clauses as long as the\n right side is a range or a list. Elixir will then expand the\n operator to a valid guard expression. For example:\n\n when x in [1,2,3]\n\n Translates to:\n\n when x === 1 or x === 2 or x === 3\n\n When using ranges:\n\n when x in 1..3\n\n Translates to:\n\n when x >= 1 and x <= 3\n\n \"\"\"\n defmacro left in right do\n cache = (__CALLER__.context == nil)\n\n right = case bootstraped?(Macro) do\n true -> Macro.expand(right, __CALLER__)\n false -> right\n end\n\n case right do\n _ when cache ->\n quote do: Elixir.Enum.member?(unquote(right), unquote(left))\n [] ->\n false\n [h|t] ->\n :lists.foldr(fn x, acc ->\n quote do\n unquote(comp(left, x)) or unquote(acc)\n end\n end, comp(left, h), t)\n {:%{}, [], [__struct__: Elixir.Range, first: first, last: last]} ->\n in_range(left, Macro.expand(first, __CALLER__), Macro.expand(last, __CALLER__))\n _ ->\n raise ArgumentError, <<\"invalid args for operator in, it expects a compile time list \",\n \"or range on the right side when used in guard expressions, got: \",\n Macro.to_string(right) :: binary>>\n end\n end\n\n defp in_range(left, first, last) do\n case opt_in?(first) and opt_in?(last) do\n true ->\n case first <= last do\n true -> increasing_compare(left, first, last)\n false -> decreasing_compare(left, first, last)\n end\n false ->\n quote do\n (:erlang.\"=<\"(unquote(first), unquote(last)) and\n unquote(increasing_compare(left, first, last)))\n or\n (:erlang.\"<\"(unquote(last), unquote(first)) and\n unquote(decreasing_compare(left, first, last)))\n end\n end\n end\n\n defp opt_in?(x), do: is_integer(x) or is_float(x) or is_atom(x)\n\n defp comp(left, right) do\n quote(do: :erlang.\"=:=\"(unquote(left), unquote(right)))\n end\n\n defp increasing_compare(var, first, last) do\n quote do\n :erlang.\">=\"(unquote(var), unquote(first)) and\n :erlang.\"=<\"(unquote(var), unquote(last))\n end\n end\n\n defp decreasing_compare(var, first, last) do\n quote do\n :erlang.\"=<\"(unquote(var), unquote(first)) and\n :erlang.\">=\"(unquote(var), unquote(last))\n end\n end\n\n @doc \"\"\"\n When used inside quoting, marks that the variable should\n not be hygienized. The argument can be either a variable\n unquoted or in standard tuple form `{name, meta, context}`.\n\n Check `Kernel.SpecialForms.quote\/2` for more information.\n \"\"\"\n defmacro var!(var, context \\\\ nil)\n\n defmacro var!({name, meta, atom}, context) when is_atom(name) and is_atom(atom) do\n do_var!(name, meta, context, __CALLER__)\n end\n\n defmacro var!(x, _context) do\n raise ArgumentError, \"expected a var to be given to var!, got: #{Macro.to_string(x)}\"\n end\n\n defp do_var!(name, meta, context, env) do\n # Remove counter and force them to be vars\n meta = :lists.keydelete(:counter, 1, meta)\n meta = :lists.keystore(:var, 1, meta, {:var, true})\n\n case Macro.expand(context, env) do\n x when is_atom(x) ->\n {name, meta, x}\n x ->\n raise ArgumentError, \"expected var! context to expand to an atom, got: #{Macro.to_string(x)}\"\n end\n end\n\n @doc \"\"\"\n When used inside quoting, marks that the alias should not\n be hygienezed. This means the alias will be expanded when\n the macro is expanded.\n\n Check `Kernel.SpecialForms.quote\/2` for more information.\n \"\"\"\n defmacro alias!(alias)\n\n defmacro alias!(alias) when is_atom(alias) do\n alias\n end\n\n defmacro alias!({:__aliases__, meta, args}) do\n # Simply remove the alias metadata from the node\n # so it does not affect expansion.\n {:__aliases__, :lists.keydelete(:alias, 1, meta), args}\n end\n\n ## Definitions implemented in Elixir\n\n @doc ~S\"\"\"\n Defines a module given by name with the given contents.\n\n It returns the module name, the module binary and the\n block contents result.\n\n ## Examples\n\n iex> defmodule Foo do\n ...> def bar, do: :baz\n ...> end\n iex> Foo.bar\n :baz\n\n ## Nesting\n\n Nesting a module inside another module affects its name:\n\n defmodule Foo do\n defmodule Bar do\n end\n end\n\n In the example above, two modules `Foo` and `Foo.Bar` are created.\n When nesting, Elixir automatically creates an alias, allowing the\n second module `Foo.Bar` to be accessed as `Bar` in the same lexical\n scope.\n\n This means that, if the module `Bar` is moved to another file,\n the references to `Bar` needs to be updated or an alias needs to\n be explicitly set with the help of `Kernel.SpecialForms.alias\/2`.\n\n ## Dynamic names\n\n Elixir module names can be dynamically generated. This is very\n useful for macros. For instance, one could write:\n\n defmodule String.to_atom(\"Foo#{1}\") do\n # contents ...\n end\n\n Elixir will accept any module name as long as the expression\n returns an atom. Note that, when a dynamic name is used, Elixir\n won't nest the name under the current module nor automatically\n set up an alias.\n \"\"\"\n defmacro defmodule(alias, do: block) do\n env = __CALLER__\n boot? = bootstraped?(Macro)\n\n expanded =\n case boot? do\n true -> Macro.expand(alias, env)\n false -> alias\n end\n\n {expanded, with_alias} =\n case boot? and is_atom(expanded) do\n true ->\n # Expand the module considering the current environment\/nesting\n full = expand_module(alias, expanded, env)\n\n # Generate the alias for this module definition\n {new, old} = module_nesting(env.module, full)\n meta = [defined: full, context: true] ++ alias_meta(alias)\n\n {full, {:alias, meta, [old, [as: new, warn: false]]}}\n false ->\n {expanded, nil}\n end\n\n {escaped, _} = :elixir_quote.escape(block, false)\n module_vars = module_vars(env.vars, 0)\n\n quote do\n unquote(with_alias)\n :elixir_module.compile(unquote(expanded), unquote(escaped),\n unquote(module_vars), __ENV__)\n end\n end\n\n defp alias_meta({:__aliases__, meta, _}), do: meta\n defp alias_meta(_), do: []\n\n # defmodule :foo\n defp expand_module(raw, _module, _env) when is_atom(raw),\n do: raw\n\n # defmodule Elixir.Alias\n defp expand_module({:__aliases__, _, [:Elixir|t]}, module, _env) when t != [],\n do: module\n\n # defmodule Alias in root\n defp expand_module({:__aliases__, _, _}, module, %{module: nil}),\n do: module\n\n # defmodule Alias nested\n defp expand_module({:__aliases__, _, t}, _module, env),\n do: :elixir_aliases.concat([env.module|t])\n\n # defmodule _\n defp expand_module(_raw, module, env),\n do: :elixir_aliases.concat([env.module, module])\n\n # quote vars to be injected into the module definition\n defp module_vars([{key, kind}|vars], counter) do\n var =\n case is_atom(kind) do\n true -> {key, [], kind}\n false -> {key, [counter: kind], nil}\n end\n\n under = String.to_atom(<<\"_@\", :erlang.integer_to_binary(counter)::binary>>)\n args = [key, kind, under, var]\n [{:{}, [], args}|module_vars(vars, counter+1)]\n end\n\n defp module_vars([], _counter) do\n []\n end\n\n # Gets two modules names and return an alias\n # which can be passed down to the alias directive\n # and it will create a proper shortcut representing\n # the given nesting.\n #\n # Examples:\n #\n # module_nesting('Elixir.Foo.Bar', 'Elixir.Foo.Bar.Baz.Bat')\n # {'Elixir.Baz', 'Elixir.Foo.Bar.Baz'}\n #\n # In case there is no nesting\/no module:\n #\n # module_nesting(nil, 'Elixir.Foo.Bar.Baz.Bat')\n # {false, 'Elixir.Foo.Bar.Baz.Bat'}\n #\n defp module_nesting(nil, full),\n do: {false, full}\n\n defp module_nesting(prefix, full) do\n case split_module(prefix) do\n [] -> {false, full}\n prefix -> module_nesting(prefix, split_module(full), [], full)\n end\n end\n\n defp module_nesting([x|t1], [x|t2], acc, full),\n do: module_nesting(t1, t2, [x|acc], full)\n defp module_nesting([], [h|_], acc, _full),\n do: {String.to_atom(<<\"Elixir.\", h::binary>>),\n :elixir_aliases.concat(:lists.reverse([h|acc]))}\n defp module_nesting(_, _, _acc, full),\n do: {false, full}\n\n defp split_module(atom) do\n case :binary.split(Atom.to_string(atom), \".\", [:global]) do\n [\"Elixir\"|t] -> t\n _ -> []\n end\n end\n\n @doc \"\"\"\n Defines a function with the given name and contents.\n\n ## Examples\n\n defmodule Foo do\n def bar, do: :baz\n end\n\n Foo.bar #=> :baz\n\n A function that expects arguments can be defined as follow:\n\n defmodule Foo do\n def sum(a, b) do\n a + b\n end\n end\n\n In the example above, we defined a function `sum` that receives\n two arguments and sums them.\n\n \"\"\"\n defmacro def(call, expr \\\\ nil) do\n define(:def, call, expr, __CALLER__)\n end\n\n @doc \"\"\"\n Defines a function that is private. Private functions are\n only accessible from within the module in which they are defined.\n\n Check `def\/2` for more information\n\n ## Examples\n\n defmodule Foo do\n def bar do\n sum(1, 2)\n end\n\n defp sum(a, b), do: a + b\n end\n\n In the example above, `sum` is private and accessing it\n through `Foo.sum` will raise an error.\n \"\"\"\n defmacro defp(call, expr \\\\ nil) do\n define(:defp, call, expr, __CALLER__)\n end\n\n @doc \"\"\"\n Defines a macro with the given name and contents.\n\n ## Examples\n\n defmodule MyLogic do\n defmacro unless(expr, opts) do\n quote do\n if !unquote(expr), unquote(opts)\n end\n end\n end\n\n require MyLogic\n MyLogic.unless false do\n IO.puts \"It works\"\n end\n\n \"\"\"\n defmacro defmacro(call, expr \\\\ nil) do\n define(:defmacro, call, expr, __CALLER__)\n end\n\n @doc \"\"\"\n Defines a macro that is private. Private macros are\n only accessible from the same module in which they are defined.\n\n Check `defmacro\/2` for more information\n \"\"\"\n defmacro defmacrop(call, expr \\\\ nil) do\n define(:defmacrop, call, expr, __CALLER__)\n end\n\n defp define(kind, call, expr, env) do\n assert_module_scope(env, kind, 2)\n assert_no_function_scope(env, kind, 2)\n line = env.line\n\n {call, uc} = :elixir_quote.escape(call, true)\n {expr, ue} = :elixir_quote.escape(expr, true)\n\n # Do not check clauses if any expression was unquoted\n check_clauses = not(ue or uc)\n pos = :elixir_locals.cache_env(env)\n\n quote do\n :elixir_def.store_definition(unquote(line), unquote(kind), unquote(check_clauses),\n unquote(call), unquote(expr), unquote(pos))\n end\n end\n\n @doc \"\"\"\n Defines a struct for the current module.\n\n A struct is a tagged map that allows developers to provide\n default values for keys, tags to be used in polymorphic\n dispatches and compile time assertions.\n\n To define a struct, a developer needs to only define\n a function named `__struct__\/0` that returns a map with the\n structs field. This macro is a convenience for defining such\n function, with the addition of a type `t` and deriving\n conveniences.\n\n For more information about structs, please check\n `Kernel.SpecialForms.%\/2`.\n\n ## Examples\n\n defmodule User do\n defstruct name: nil, age: nil\n end\n\n Struct fields are evaluated at definition time, which allows\n them to be dynamic. In the example below, `10 + 11` will be\n evaluated at compilation time and the age field will be stored\n with value `21`:\n\n defmodule User do\n defstruct name: nil, age: 10 + 11\n end\n\n ## Deriving\n\n Although structs are maps, by default structs do not implement\n any of the protocols implemented for maps. For example, if you\n attempt to use the access protocol with the User struct, it\n will lead to an error:\n\n %User{}[:age]\n ** (Protocol.UndefinedError) protocol Access not implemented for %User{...}\n\n However, `defstruct\/2` allows implementation for protocols to\n derived by defining a `@derive` attribute as a list before `defstruct\/2`\n is invoked:\n\n defmodule User do\n @derive [Access]\n defstruct name: nil, age: 10 + 11\n end\n\n %User{}[:age] #=> 21\n\n For each protocol given to `@derive`, Elixir will assert there is an\n implementation of that protocol for maps and check if the map\n implementation defines a `__deriving__\/3` callback. If so, the callback\n is invoked, otherwise an implementation that simply points to the map\n one is automatically derived.\n\n ## Types\n\n It is recommended to define types for structs, by convention this type\n is called `t`. To define a struct in a type the struct literal syntax\n is used:\n\n defmodule User do\n defstruct name: \"Jos\u00e9\", age: 25\n @type t :: %User{name: String.t, age: integer}\n end\n\n It is recommended to only use the struct syntax when defining the struct's\n type. When referring to another struct use `User.t`, not `%User{}`. Fields\n in the struct not included in the type defaults to `term`.\n\n Private structs that are not used outside its module should use the private\n type attribute `@typep`. Public structs whose internal structure is private\n to the local module (you are not allowed to pattern match it or directly\n access fields) should use the `@opaque` attribute. Structs whose internal\n structure is public should use `@type`.\n \"\"\"\n defmacro defstruct(fields) do\n {fields, types} = split_fields_and_types(fields)\n\n types =\n case types do\n true ->\n stacktrace = Exception.format_stacktrace(Macro.Env.stacktrace(__CALLER__))\n IO.write :stderr, \"warning: passing types to struct fields with :: is deprecated, \" <>\n \"please define a type explicitly instead\\n#{stacktrace}\"\n quote do\n unless Kernel.Typespec.defines_type?(__MODULE__, :t, 0) do\n @type t :: %{__struct__: __MODULE__}\n end\n end\n false ->\n :ok\n end\n\n fields =\n quote bind_quoted: [fields: fields] do\n fields = :lists.map(fn\n {key, _} = pair when is_atom(key) -> pair\n key when is_atom(key) -> {key, nil}\n other -> raise ArgumentError, \"struct field names must be atoms, got: #{inspect other}\"\n end, fields)\n\n @struct :maps.put(:__struct__, __MODULE__, :maps.from_list(fields))\n\n case Module.get_attribute(__MODULE__, :derive) do\n [] ->\n :ok\n derive ->\n Protocol.__derive__(derive, __MODULE__, __ENV__)\n end\n\n @spec __struct__() :: %__MODULE__{}\n def __struct__() do\n @struct\n end\n end\n\n quote do\n unquote(fields)\n unquote(types)\n fields\n end\n end\n\n defp split_fields_and_types(kv) do\n case Keyword.keyword?(kv) do\n true -> split_fields_and_types(kv, [], false)\n false -> {kv, false}\n end\n end\n\n defp split_fields_and_types([{field, {:::, _, [default, _]}}|t], fields, _types) do\n split_fields_and_types(t, [{field, default}|fields], true)\n end\n\n defp split_fields_and_types([{field, default}|t], fields, types) do\n split_fields_and_types(t, [{field, default}|fields], types)\n end\n\n defp split_fields_and_types([field|t], fields, types) do\n split_fields_and_types(t, [field|fields], types)\n end\n\n defp split_fields_and_types([], fields, types) do\n {:lists.reverse(fields), types}\n end\n\n @doc ~S\"\"\"\n Defines an exception.\n\n Exceptions are structs backed by a module that implements\n the Exception behaviour. The Exception behaviour requires\n two functions to be implemented:\n\n * `exception\/1` - that receives the arguments given to `raise\/2`\n and returns the exception struct. The default implementation\n accepts a set of keyword arguments that is merged into the\n struct.\n\n * `message\/1` - receives the exception struct and must return its\n message. Most commonly exceptions have a message field which\n by default is accessed by this function. However, if your exception\n does not have a message field, this function must be explicitly\n implemented.\n\n Since exceptions are structs, all the API supported by `defstruct\/1`\n is also available in `defexception\/1`.\n\n ## Raising exceptions\n\n The most common way to raise an exception is via the `raise\/2`\n function:\n\n defmodule MyAppError do\n defexception [:message]\n end\n\n raise MyAppError,\n message: \"did not get what was expected, got: #{inspect value}\"\n\n In many cases it is more convenient to pass the expected value to\n `raise` and generate the message in the `exception\/1` callback:\n\n defmodule MyAppError do\n defexception [:message]\n\n def exception(value) do\n msg = \"did not get what was expected, got: #{inspect value}\"\n %MyAppError{message: msg}\n end\n end\n\n raise MyAppError, value\n\n The example above is the preferred mechanism for customizing\n exception messages.\n \"\"\"\n defmacro defexception(fields) do\n fields = case is_list(fields) do\n true -> [{:__exception__, true}|fields]\n false -> quote(do: [{:__exception__, true}] ++ unquote(fields))\n end\n\n quote do\n @behaviour Exception\n fields = defstruct unquote(fields)\n\n @spec exception(Keyword.t) :: Exception.t\n def exception(args) when is_list(args) do\n Kernel.struct(__struct__, args)\n end\n\n defoverridable exception: 1\n\n if Keyword.has_key?(fields, :message) do\n @spec message(Exception.t) :: String.t\n def message(exception) do\n exception.message\n end\n\n defoverridable message: 1\n end\n end\n end\n\n @doc \"\"\"\n Defines a protocol.\n\n A protocol specifies an API that should be defined by its\n implementations.\n\n ## Examples\n\n In Elixir, only `false` and `nil` are considered falsy values.\n Everything else evaluates to true in `if` clauses. Depending\n on the application, it may be important to specify a `blank?`\n protocol that returns a boolean for other data types that should\n be considered `blank?`. For instance, an empty list or an empty\n binary could be considered blanks.\n\n We could implement this protocol as follow:\n\n defprotocol Blank do\n @doc \"Returns true if data is considered blank\/empty\"\n def blank?(data)\n end\n\n Now that the protocol is defined, we can implement it. We need\n to implement the protocol for each Elixir type. For example:\n\n # Integers are never blank\n defimpl Blank, for: Integer do\n def blank?(number), do: false\n end\n\n # Just empty list is blank\n defimpl Blank, for: List do\n def blank?([]), do: true\n def blank?(_), do: false\n end\n\n # Just the atoms false and nil are blank\n defimpl Blank, for: Atom do\n def blank?(false), do: true\n def blank?(nil), do: true\n def blank?(_), do: false\n end\n\n And we would have to define the implementation for all types.\n The supported types available are:\n\n * Structs (see below)\n * `Tuple`\n * `Atom`\n * `List`\n * `BitString`\n * `Integer`\n * `Float`\n * `Function`\n * `PID`\n * `Map`\n * `Port`\n * `Reference`\n * `Any` (see below)\n\n ## Protocols + Structs\n\n The real benefit of protocols comes when mixed with structs.\n For instance, Elixir ships with many data types implemented as\n structs, like `HashDict` and `HashSet`. We can implement the\n `Blank` protocol for those types as well:\n\n defimpl Blank, for: [HashDict, HashSet] do\n def blank?(enum_like), do: Enum.empty?(enum_like)\n end\n\n If a protocol is not found for a given type, it will fallback to\n `Any`.\n\n ## Fallback to any\n\n In some cases, it may be convenient to provide a default\n implementation for all types. This can be achieved by\n setting `@fallback_to_any` to `true` in the protocol\n definition:\n\n defprotocol Blank do\n @fallback_to_any true\n def blank?(data)\n end\n\n Which can now be implemented as:\n\n defimpl Blank, for: Any do\n def blank?(_), do: true\n end\n\n One may wonder why such fallback is not true by default.\n\n It is two-fold: first, the majority of protocols cannot\n implement an action in a generic way for all types. In fact,\n providing a default implementation may be harmful, because users\n may rely on the default implementation instead of providing a\n specialized one.\n\n Second, falling back to `Any` adds an extra lookup to all types,\n which is unnecessary overhead unless an implementation for Any is\n required.\n\n ## Types\n\n Defining a protocol automatically defines a type named `t`, which\n can be used as:\n\n @spec present?(Blank.t) :: boolean\n def present?(blank) do\n not Blank.blank?(blank)\n end\n\n The `@spec` above expresses that all types allowed to implement the\n given protocol are valid argument types for the given function.\n\n ## Reflection\n\n Any protocol module contains three extra functions:\n\n\n * `__protocol__\/1` - returns the protocol name when `:name` is given, and a\n keyword list with the protocol functions when `:functions` is given\n\n * `impl_for\/1` - receives a structure and returns the module that\n implements the protocol for the structure, `nil` otherwise\n\n * `impl_for!\/1` - same as above but raises an error if an implementation is\n not found\n\n ## Consolidation\n\n In order to cope with code loading in development, protocols in\n Elixir provide a slow implementation of protocol dispatching specific\n to development.\n\n In order to speed up dispatching in production environments, where\n all implementations are known up-front, Elixir provides a feature\n called protocol consolidation. For this reason, all protocols are\n compiled with `debug_info` set to true, regardless of the option\n set by `elixirc` compiler. The debug info though may be removed\n after consolidation.\n\n For more information on how to apply protocol consolidation to\n a given project, please check the functions in the `Protocol`\n module or the `mix compile.protocols` task.\n \"\"\"\n defmacro defprotocol(name, do: block) do\n Protocol.__protocol__(name, do: block)\n end\n\n @doc \"\"\"\n Defines an implementation for the given protocol. See\n `defprotocol\/2` for examples.\n\n Inside an implementation, the name of the protocol can be accessed\n via `@protocol` and the current target as `@for`.\n \"\"\"\n defmacro defimpl(name, opts, do_block \\\\ []) do\n merged = Keyword.merge(opts, do_block)\n merged = Keyword.put_new(merged, :for, __CALLER__.module)\n Protocol.__impl__(name, merged)\n end\n\n @doc \"\"\"\n Makes the given functions in the current module overridable. An overridable\n function is lazily defined, allowing a developer to customize it.\n\n ## Example\n\n defmodule DefaultMod do\n defmacro __using__(_opts) do\n quote do\n def test(x, y) do\n x + y\n end\n\n defoverridable [test: 2]\n end\n end\n end\n\n defmodule InheritMod do\n use DefaultMod\n\n def test(x, y) do\n x * y + super(x, y)\n end\n end\n\n As seen as in the example `super` can be used to call the default\n implementation.\n \"\"\"\n defmacro defoverridable(tuples) do\n quote do\n Module.make_overridable(__MODULE__, unquote(tuples))\n end\n end\n\n @doc \"\"\"\n `use` is a simple mechanism for using a given module into\n the current context.\n\n ## Examples\n\n For example, in order to write tests using the ExUnit framework,\n a developer should use the `ExUnit.Case` module:\n\n defmodule AssertionTest do\n use ExUnit.Case, async: true\n\n test \"always pass\" do\n assert true\n end\n end\n\n By calling `use`, a hook called `__using__` will be invoked in\n `ExUnit.Case` which will then do the proper setup.\n\n Simply put, `use` is simply a translation to:\n\n defmodule AssertionTest do\n require ExUnit.Case\n ExUnit.Case.__using__([async: true])\n\n test \"always pass\" do\n assert true\n end\n end\n\n \"\"\"\n defmacro use(module, opts \\\\ []) do\n expanded = Macro.expand(module, __CALLER__)\n\n case is_atom(expanded) do\n false ->\n raise ArgumentError, \"invalid arguments for use, expected an atom or alias as argument\"\n true ->\n quote do\n require unquote(expanded)\n unquote(expanded).__using__(unquote(opts))\n end\n end\n end\n\n @doc \"\"\"\n Defines the given functions in the current module that will\n delegate to the given `target`. Functions defined with\n `defdelegate` are public and are allowed to be invoked\n from external. If you find yourself wishing to define a\n delegation as private, you should likely use import\n instead.\n\n Delegation only works with functions, delegating to macros\n is not supported.\n\n ## Options\n\n * `:to` - the expression to delegate to. Any expression\n is allowed and its results will be calculated on runtime.\n\n * `:as` - the function to call on the target given in `:to`.\n This parameter is optional and defaults to the name being\n delegated.\n\n * `:append_first` - if true, when delegated, first argument\n passed to the delegate will be relocated to the end of the\n arguments when dispatched to the target.\n\n The motivation behind this is because Elixir normalizes\n the \"handle\" as a first argument and some Erlang modules\n expect it as last argument.\n\n ## Examples\n\n defmodule MyList do\n defdelegate reverse(list), to: :lists\n defdelegate [reverse(list), map(callback, list)], to: :lists\n defdelegate other_reverse(list), to: :lists, as: :reverse\n end\n\n MyList.reverse([1, 2, 3])\n #=> [3,2,1]\n\n MyList.other_reverse([1, 2, 3])\n #=> [3,2,1]\n\n \"\"\"\n defmacro defdelegate(funs, opts) do\n funs = Macro.escape(funs, unquote: true)\n quote bind_quoted: [funs: funs, opts: opts] do\n target = Keyword.get(opts, :to) ||\n raise ArgumentError, \"Expected to: to be given as argument\"\n\n append_first = Keyword.get(opts, :append_first, false)\n\n for fun <- List.wrap(funs) do\n {name, args} =\n case Macro.decompose_call(fun) do\n {_, _} = pair -> pair\n _ -> raise ArgumentError, \"invalid syntax in defdelegate #{Macro.to_string(fun)}\"\n end\n\n actual_args =\n case append_first and args != [] do\n true -> tl(args) ++ [hd(args)]\n false -> args\n end\n\n fun = Keyword.get(opts, :as, name)\n\n def unquote(name)(unquote_splicing(args)) do\n unquote(target).unquote(fun)(unquote_splicing(actual_args))\n end\n end\n end\n end\n\n ## Sigils\n\n @doc \"\"\"\n Handles the sigil ~S. It simply returns a string\n without escaping characters and without interpolations.\n\n ## Examples\n\n iex> ~S(foo)\n \"foo\"\n\n iex> ~S(f\\#{o}o)\n \"f\\\\\\#{o}o\"\n\n \"\"\"\n defmacro sigil_S(string, []) do\n string\n end\n\n @doc \"\"\"\n Handles the sigil ~s. It returns a string as if it was double quoted\n string, unescaping characters and replacing interpolations.\n\n ## Examples\n\n iex> ~s(foo)\n \"foo\"\n\n iex> ~s(f\\#{:o}o)\n \"foo\"\n\n \"\"\"\n defmacro sigil_s({:<<>>, line, pieces}, []) do\n {:<<>>, line, Macro.unescape_tokens(pieces)}\n end\n\n @doc \"\"\"\n Handles the sigil ~C. It simply returns a char list\n without escaping characters and without interpolations.\n\n ## Examples\n\n iex> ~C(foo)\n 'foo'\n\n iex> ~C(f\\#{o}o)\n 'f\\\\\\#{o}o'\n\n \"\"\"\n defmacro sigil_C({:<<>>, _line, [string]}, []) when is_binary(string) do\n String.to_char_list(string)\n end\n\n @doc \"\"\"\n Handles the sigil ~c. It returns a char list as if it were a single\n quoted string, unescaping characters and replacing interpolations.\n\n ## Examples\n\n iex> ~c(foo)\n 'foo'\n\n iex> ~c(f\\#{:o}o)\n 'foo'\n\n \"\"\"\n\n # We can skip the runtime conversion if we are\n # creating a binary made solely of series of chars.\n defmacro sigil_c({:<<>>, _line, [string]}, []) when is_binary(string) do\n String.to_char_list(Macro.unescape_string(string))\n end\n\n defmacro sigil_c({:<<>>, line, pieces}, []) do\n binary = {:<<>>, line, Macro.unescape_tokens(pieces)}\n quote do: String.to_char_list(unquote(binary))\n end\n\n @doc \"\"\"\n Handles the sigil ~r. It returns a Regex pattern.\n\n ## Examples\n\n iex> Regex.match?(~r(foo), \"foo\")\n true\n\n \"\"\"\n defmacro sigil_r({:<<>>, _line, [string]}, options) when is_binary(string) do\n binary = Macro.unescape_string(string, fn(x) -> Regex.unescape_map(x) end)\n regex = Regex.compile!(binary, :binary.list_to_bin(options))\n Macro.escape(regex)\n end\n\n defmacro sigil_r({:<<>>, line, pieces}, options) do\n binary = {:<<>>, line, Macro.unescape_tokens(pieces, fn(x) -> Regex.unescape_map(x) end)}\n quote do: Regex.compile!(unquote(binary), unquote(:binary.list_to_bin(options)))\n end\n\n @doc \"\"\"\n Handles the sigil ~R. It returns a Regex pattern without escaping\n nor interpreting interpolations.\n\n ## Examples\n\n iex> Regex.match?(~R(f\\#{1,3}o), \"f\\#o\")\n true\n\n \"\"\"\n defmacro sigil_R({:<<>>, _line, [string]}, options) when is_binary(string) do\n regex = Regex.compile!(string, :binary.list_to_bin(options))\n Macro.escape(regex)\n end\n\n @doc \"\"\"\n Handles the sigil ~w. It returns a list of \"words\" split by whitespace.\n\n ## Modifiers\n\n * `s`: strings (default)\n * `a`: atoms\n * `c`: char lists\n\n ## Examples\n\n iex> ~w(foo \\#{:bar} baz)\n [\"foo\", \"bar\", \"baz\"]\n\n iex> ~w(--source test\/enum_test.exs)\n [\"--source\", \"test\/enum_test.exs\"]\n\n iex> ~w(foo bar baz)a\n [:foo, :bar, :baz]\n\n \"\"\"\n\n defmacro sigil_w({:<<>>, _line, [string]}, modifiers) when is_binary(string) do\n split_words(Macro.unescape_string(string), modifiers)\n end\n\n defmacro sigil_w({:<<>>, line, pieces}, modifiers) do\n binary = {:<<>>, line, Macro.unescape_tokens(pieces)}\n split_words(binary, modifiers)\n end\n\n @doc \"\"\"\n Handles the sigil ~W. It returns a list of \"words\" split by whitespace\n without escaping nor interpreting interpolations.\n\n ## Modifiers\n\n * `s`: strings (default)\n * `a`: atoms\n * `c`: char lists\n\n ## Examples\n\n iex> ~W(foo \\#{bar} baz)\n [\"foo\", \"\\\\\\#{bar}\", \"baz\"]\n\n \"\"\"\n defmacro sigil_W({:<<>>, _line, [string]}, modifiers) when is_binary(string) do\n split_words(string, modifiers)\n end\n\n defp split_words(\"\", _modifiers), do: []\n\n defp split_words(string, modifiers) do\n mod =\n case modifiers do\n [] -> ?s\n [mod] when mod == ?s or mod == ?a or mod == ?c -> mod\n _else -> raise ArgumentError, \"modifier must be one of: s, a, c\"\n end\n\n case is_binary(string) do\n true ->\n case mod do\n ?s -> String.split(string)\n ?a -> for p <- String.split(string), do: String.to_atom(p)\n ?c -> for p <- String.split(string), do: String.to_char_list(p)\n end\n false ->\n case mod do\n ?s -> quote do: String.split(unquote(string))\n ?a -> quote do: for(p <- String.split(unquote(string)), do: String.to_atom(p))\n ?c -> quote do: for(p <- String.split(unquote(string)), do: String.to_char_list(p))\n end\n end\n end\n\n ## Shared functions\n\n defp optimize_boolean({:case, meta, args}) do\n {:case, [{:optimize_boolean, true}|meta], args}\n end\n\n # We need this check only for bootstrap purposes.\n # Once Kernel is loaded and we recompile, it is a no-op.\n case :code.ensure_loaded(Kernel) do\n {:module, _} ->\n defp bootstraped?(_), do: true\n {:error, _} ->\n defp bootstraped?(module), do: :code.ensure_loaded(module) == {:module, module}\n end\n\n defp assert_module_scope(env, fun, arity) do\n case env.module do\n nil -> raise ArgumentError, \"cannot invoke #{fun}\/#{arity} outside module\"\n _ -> :ok\n end\n end\n\n defp assert_no_function_scope(env, fun, arity) do\n case env.function do\n nil -> :ok\n _ -> raise ArgumentError, \"cannot invoke #{fun}\/#{arity} inside function\/macro\"\n end\n end\n\n defp env_stacktrace(env) do\n case bootstraped?(Path) do\n true -> Macro.Env.stacktrace(env)\n false -> []\n end\n end\nend\n","old_contents":"# Use elixir_bootstrap module to be able to bootstrap Kernel.\n# The bootstrap module provides simpler implementations of the\n# functions removed, simple enough to bootstrap.\nimport Kernel, except: [@: 1, defmodule: 2, def: 1, def: 2, defp: 2,\n defmacro: 1, defmacro: 2, defmacrop: 2]\nimport :elixir_bootstrap\n\ndefmodule Kernel do\n @moduledoc \"\"\"\n `Kernel` provides the default macros and functions\n Elixir imports into your environment. These macros and functions\n can be skipped or cherry-picked via the `import` macro. For\n instance, if you want to tell Elixir not to import the `if`\n macro, you can do:\n\n import Kernel, except: [if: 2]\n\n Elixir also has special forms that are always imported and\n cannot be skipped. These are described in `Kernel.SpecialForms`.\n\n Some of the functions described in this module are inlined by\n the Elixir compiler into their Erlang counterparts in the `:erlang`\n module. Those functions are called BIFs (builtin internal functions)\n in Erlang-land and they exhibit interesting properties, as some of\n them are allowed in guards and others are used for compiler\n optimizations.\n\n Most of the inlined functions can be seen in effect when capturing\n the function:\n\n iex> &Kernel.is_atom\/1\n &:erlang.is_atom\/1\n\n Those functions will be explicitly marked in their docs as\n \"inlined by the compiler\".\n \"\"\"\n\n ## Delegations to Erlang with inlining (macros)\n\n @doc \"\"\"\n Returns an integer or float which is the arithmetical absolute value of `number`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> abs(-3.33)\n 3.33\n\n iex> abs(-3)\n 3\n\n \"\"\"\n @spec abs(number) :: number\n def abs(number) do\n :erlang.abs(number)\n end\n\n @doc \"\"\"\n Invokes the given `fun` with the array of arguments `args`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> apply(fn x -> x * 2 end, [2])\n 4\n\n \"\"\"\n @spec apply(fun, [any]) :: any\n def apply(fun, args) do\n :erlang.apply(fun, args)\n end\n\n @doc \"\"\"\n Invokes the given `fun` from `module` with the array of arguments `args`.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> apply(Enum, :reverse, [[1, 2, 3]])\n [3,2,1]\n\n \"\"\"\n @spec apply(module, atom, [any]) :: any\n def apply(module, fun, args) do\n :erlang.apply(module, fun, args)\n end\n\n @doc \"\"\"\n Extracts the part of the binary starting at `start` with length `length`.\n Binaries are zero-indexed.\n\n If start or length references in any way outside the binary, an\n `ArgumentError` exception is raised.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> binary_part(\"foo\", 1, 2)\n \"oo\"\n\n A negative length can be used to extract bytes at the end of a binary:\n\n iex> binary_part(\"foo\", 3, -1)\n \"o\"\n\n \"\"\"\n @spec binary_part(binary, pos_integer, integer) :: binary\n def binary_part(binary, start, length) do\n :erlang.binary_part(binary, start, length)\n end\n\n @doc \"\"\"\n Returns an integer which is the size in bits of `bitstring`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> bit_size(<<433::16, 3::3>>)\n 19\n\n iex> bit_size(<<1, 2, 3>>)\n 24\n\n \"\"\"\n @spec bit_size(bitstring) :: non_neg_integer\n def bit_size(bitstring) do\n :erlang.bit_size(bitstring)\n end\n\n @doc \"\"\"\n Returns the number of bytes needed to contain `bitstring`.\n\n That is, if the number of bits in `bitstring` is not divisible by 8,\n the resulting number of bytes will be rounded up. This operation\n happens in constant time.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> byte_size(<<433::16, 3::3>>)\n 3\n\n iex> byte_size(<<1, 2, 3>>)\n 3\n\n \"\"\"\n @spec byte_size(bitstring) :: non_neg_integer\n def byte_size(bitstring) do\n :erlang.byte_size(bitstring)\n end\n\n @doc \"\"\"\n Performs an integer division.\n\n Raises an error if one of the arguments is not an integer.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> div(5, 2)\n 2\n\n \"\"\"\n @spec div(integer, integer) :: integer\n def div(left, right) do\n :erlang.div(left, right)\n end\n\n @doc \"\"\"\n Stops the execution of the calling process with the given reason.\n\n Since evaluating this function causes the process to terminate,\n it has no return value.\n\n Inlined by the compiler.\n\n ## Examples\n\n exit(:normal)\n exit(:seems_bad)\n\n \"\"\"\n @spec exit(term) :: no_return\n def exit(reason) do\n :erlang.exit(reason)\n end\n\n @doc \"\"\"\n Returns the head of a list, raises `badarg` if the list is empty.\n\n Inlined by the compiler.\n \"\"\"\n @spec hd(list) :: term\n def hd(list) do\n :erlang.hd(list)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is an atom; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_atom(term) :: boolean\n def is_atom(term) do\n :erlang.is_atom(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a binary; otherwise returns `false`.\n\n A binary always contains a complete number of bytes.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_binary(term) :: boolean\n def is_binary(term) do\n :erlang.is_binary(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a bitstring (including a binary); otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_bitstring(term) :: boolean\n def is_bitstring(term) do\n :erlang.is_bitstring(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is either the atom `true` or the atom `false` (i.e. a boolean);\n otherwise returns false.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_boolean(term) :: boolean\n def is_boolean(term) do\n :erlang.is_boolean(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a floating point number; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_float(term) :: boolean\n def is_float(term) do\n :erlang.is_float(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a function; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_function(term) :: boolean\n def is_function(term) do\n :erlang.is_function(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a function that can be applied with `arity` number of arguments;\n otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_function(term, non_neg_integer) :: boolean\n def is_function(term, arity) do\n :erlang.is_function(term, arity)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is an integer; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_integer(term) :: boolean\n def is_integer(term) do\n :erlang.is_integer(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a list with zero or more elements; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_list(term) :: boolean\n def is_list(term) do\n :erlang.is_list(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is either an integer or a floating point number;\n otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_number(term) :: boolean\n def is_number(term) do\n :erlang.is_number(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a pid (process identifier); otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_pid(term) :: boolean\n def is_pid(term) do\n :erlang.is_pid(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a port identifier; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_port(term) :: boolean\n def is_port(term) do\n :erlang.is_port(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a reference; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_reference(term) :: boolean\n def is_reference(term) do\n :erlang.is_reference(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a tuple; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_tuple(term) :: boolean\n def is_tuple(term) do\n :erlang.is_tuple(term)\n end\n\n @doc \"\"\"\n Returns `true` if `term` is a map; otherwise returns `false`.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec is_map(term) :: boolean\n def is_map(term) do\n :erlang.is_map(term)\n end\n\n @doc \"\"\"\n Returns the length of `list`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> length([1, 2, 3, 4, 5, 6, 7, 8, 9])\n 9\n\n \"\"\"\n @spec length(list) :: non_neg_integer\n def length(list) do\n :erlang.length(list)\n end\n\n @doc \"\"\"\n Returns an almost unique reference.\n\n The returned reference will re-occur after approximately 2^82 calls;\n therefore it is unique enough for practical purposes.\n\n Inlined by the compiler.\n\n ## Examples\n\n make_ref() #=> #Reference<0.0.0.135>\n\n \"\"\"\n @spec make_ref() :: reference\n def make_ref() do\n :erlang.make_ref()\n end\n\n @doc \"\"\"\n Returns the size of a map.\n\n This operation happens in constant time.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec map_size(map) :: non_neg_integer\n def map_size(map) do\n :erlang.map_size(map)\n end\n\n @doc \"\"\"\n Return the biggest of the two given terms according to\n Erlang's term ordering. If the terms compare equal, the\n first one is returned.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> max(1, 2)\n 2\n\n \"\"\"\n @spec max(term, term) :: term\n def max(first, second) do\n :erlang.max(first, second)\n end\n\n @doc \"\"\"\n Return the smallest of the two given terms according to\n Erlang's term ordering. If the terms compare equal, the\n first one is returned.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> min(1, 2)\n 1\n\n \"\"\"\n @spec min(term, term) :: term\n def min(first, second) do\n :erlang.min(first, second)\n end\n\n @doc \"\"\"\n Returns an atom representing the name of the local node.\n If the node is not alive, `:nonode@nohost` is returned instead.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec node() :: node\n def node do\n :erlang.node\n end\n\n @doc \"\"\"\n Returns the node where the given argument is located.\n The argument can be a pid, a reference, or a port.\n If the local node is not alive, `nonode@nohost` is returned.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec node(pid|reference|port) :: node\n def node(arg) do\n :erlang.node(arg)\n end\n\n @doc \"\"\"\n Calculates the remainder of an integer division.\n\n Raises an error if one of the arguments is not an integer.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> rem(5, 2)\n 1\n\n \"\"\"\n @spec rem(integer, integer) :: integer\n def rem(left, right) do\n :erlang.rem(left, right)\n end\n\n @doc \"\"\"\n Returns an integer by rounding the given number.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> round(5.5)\n 6\n\n \"\"\"\n @spec round(number) :: integer\n def round(number) do\n :erlang.round(number)\n end\n\n @doc \"\"\"\n Sends a message to the given `dest` and returns the message.\n\n `dest` may be a remote or local pid, a (local) port, a locally\n registered name, or a tuple `{registered_name, node}` for a registered\n name at another node.\n\n Inlined by the compiler.\n\n ## Examples\n\n iex> send self(), :hello\n :hello\n\n \"\"\"\n @spec send(dest :: pid | port | atom | {atom, node}, msg) :: msg when msg: any\n def send(dest, msg) do\n :erlang.send(dest, msg)\n end\n\n @doc \"\"\"\n Returns the pid (process identifier) of the calling process.\n\n Allowed in guard clauses. Inlined by the compiler.\n \"\"\"\n @spec self() :: pid\n def self() do\n :erlang.self()\n end\n\n @doc \"\"\"\n Spawns the given function and returns its pid.\n\n Check the modules `Process` and `Node` for other functions\n to handle processes, including spawning functions in nodes.\n\n Inlined by the compiler.\n\n ## Examples\n\n current = Kernel.self\n child = spawn(fn -> send current, {Kernel.self, 1 + 2} end)\n\n receive do\n {^child, 3} -> IO.puts \"Received 3 back\"\n end\n\n \"\"\"\n @spec spawn((() -> any)) :: pid\n def spawn(fun) do\n :erlang.spawn(fun)\n end\n\n @doc \"\"\"\n Spawns the given module and function passing the given args\n and returns its pid.\n\n Check the modules `Process` and `Node` for other functions\n to handle processes, including spawning functions in nodes.\n\n Inlined by the compiler.\n\n ## Examples\n\n spawn(SomeModule, :function, [1, 2, 3])\n\n \"\"\"\n @spec spawn(module, atom, list) :: pid\n def spawn(module, fun, args) do\n :erlang.spawn(module, fun, args)\n end\n\n @doc \"\"\"\n Spawns the given function, links it to the current process and returns its pid.\n\n Check the modules `Process` and `Node` for other functions\n to handle processes, including spawning functions in nodes.\n\n Inlined by the compiler.\n\n ## Examples\n\n current = Kernel.self\n child = spawn_link(fn -> send current, {Kernel.self, 1 + 2} end)\n\n receive do\n {^child, 3} -> IO.puts \"Received 3 back\"\n end\n\n \"\"\"\n @spec spawn_link((() -> any)) :: pid\n def spawn_link(fun) do\n :erlang.spawn_link(fun)\n end\n\n @doc \"\"\"\n Spawns the given module and function passing the given args,\n links it to the current process and returns its pid.\n\n Check the modules `Process` and `Node` for other functions\n to handle processes, including spawning functions in nodes.\n\n Inlined by the compiler.\n\n ## Examples\n\n spawn_link(SomeModule, :function, [1, 2, 3])\n\n \"\"\"\n @spec spawn_link(module, atom, list) :: pid\n def spawn_link(module, fun, args) do\n :erlang.spawn_link(module, fun, args)\n end\n\n @doc \"\"\"\n Spawns the given function, monitors it and returns its pid\n and monitoring reference.\n\n Check the modules `Process` and `Node` for other functions\n to handle processes, including spawning functions in nodes.\n\n Inlined by the compiler.\n\n ## Examples\n\n current = Kernel.self\n spawn_monitor(fn -> send current, {Kernel.self, 1 + 2} end)\n\n \"\"\"\n @spec spawn_monitor((() -> any)) :: {pid, reference}\n def spawn_monitor(fun) do\n :erlang.spawn_monitor(fun)\n end\n\n @doc \"\"\"\n Spawns the given module and function passing the given args,\n monitors it and returns its pid and monitoring reference.\n\n Check the modules `Process` and `Node` for other functions\n to handle processes, including spawning functions in nodes.\n\n Inlined by the compiler.\n\n ## Examples\n\n spawn_monitor(SomeModule, :function, [1, 2, 3])\n\n \"\"\"\n @spec spawn_monitor(module, atom, list) :: {pid, reference}\n def spawn_monitor(module, fun, args) do\n :erlang.spawn_monitor(module, fun, args)\n end\n\n @doc \"\"\"\n A non-local return from a function. Check `Kernel.SpecialForms.try\/1` for more information.\n\n Inlined by the compiler.\n \"\"\"\n @spec throw(term) :: no_return\n def throw(term) do\n :erlang.throw(term)\n end\n\n @doc \"\"\"\n Returns the tail of a list. Raises `ArgumentError` if the list is empty.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec tl(maybe_improper_list) :: maybe_improper_list\n def tl(list) do\n :erlang.tl(list)\n end\n\n @doc \"\"\"\n Returns an integer by truncating the given number.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> trunc(5.5)\n 5\n\n \"\"\"\n @spec trunc(number) :: integer\n def trunc(number) do\n :erlang.trunc(number)\n end\n\n @doc \"\"\"\n Returns the size of a tuple.\n\n This operation happens in constant time.\n\n Allowed in guard tests. Inlined by the compiler.\n \"\"\"\n @spec tuple_size(tuple) :: non_neg_integer\n def tuple_size(tuple) do\n :erlang.tuple_size(tuple)\n end\n\n @doc \"\"\"\n Arithmetic plus.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 + 2\n 3\n\n \"\"\"\n @spec (number + number) :: number\n def left + right do\n :erlang.+(left, right)\n end\n\n @doc \"\"\"\n Arithmetic minus.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 - 2\n -1\n\n \"\"\"\n @spec (number - number) :: number\n def left - right do\n :erlang.-(left, right)\n end\n\n @doc \"\"\"\n Arithmetic unary plus.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> +1\n 1\n\n \"\"\"\n @spec (+number) :: number\n def (+value) do\n :erlang.+(value)\n end\n\n @doc \"\"\"\n Arithmetic unary minus.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> -2\n -2\n\n \"\"\"\n @spec (-number) :: number\n def (-value) do\n :erlang.-(value)\n end\n\n @doc \"\"\"\n Arithmetic multiplication.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 * 2\n 2\n\n \"\"\"\n @spec (number * number) :: number\n def left * right do\n :erlang.*(left, right)\n end\n\n @doc \"\"\"\n Arithmetic division.\n\n The result is always a float. Use `div` and `rem` if you want\n a natural division or the remainder.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 \/ 2\n 0.5\n\n iex> 2 \/ 1\n 2.0\n\n \"\"\"\n @spec (number \/ number) :: float\n def left \/ right do\n :erlang.\/(left, right)\n end\n\n @doc \"\"\"\n Concatenates two lists.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> [1] ++ [2, 3]\n [1,2,3]\n\n iex> 'foo' ++ 'bar'\n 'foobar'\n\n \"\"\"\n @spec (list ++ term) :: maybe_improper_list\n def left ++ right do\n :erlang.++(left, right)\n end\n\n @doc \"\"\"\n Removes the first occurrence of an item on the left\n for each item on the right.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> [1, 2, 3] -- [1, 2]\n [3]\n\n iex> [1, 2, 3, 2, 1] -- [1, 2, 2]\n [3,1]\n\n \"\"\"\n @spec (list -- list) :: list\n def left -- right do\n :erlang.--(left, right)\n end\n\n @doc false\n def left xor right do\n :erlang.xor(left, right)\n end\n\n @doc \"\"\"\n Boolean not. Argument must be a boolean.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> not false\n true\n\n \"\"\"\n @spec not(boolean) :: boolean\n def not(arg) do\n :erlang.not(arg)\n end\n\n @doc \"\"\"\n Returns `true` if left is less than right.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 < 2\n true\n\n \"\"\"\n @spec (term < term) :: boolean\n def left < right do\n :erlang.<(left, right)\n end\n\n @doc \"\"\"\n Returns `true` if left is more than right.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 > 2\n false\n\n \"\"\"\n @spec (term > term) :: boolean\n def left > right do\n :erlang.>(left, right)\n end\n\n @doc \"\"\"\n Returns `true` if left is less than or equal to right.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 <= 2\n true\n\n \"\"\"\n @spec (term <= term) :: boolean\n def left <= right do\n :erlang.\"=<\"(left, right)\n end\n\n @doc \"\"\"\n Returns `true` if left is more than or equal to right.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 >= 2\n false\n\n \"\"\"\n @spec (term >= term) :: boolean\n def left >= right do\n :erlang.>=(left, right)\n end\n\n @doc \"\"\"\n Returns `true` if the two items are equal.\n\n This operator considers 1 and 1.0 to be equal. For match\n semantics, use `===` instead.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 == 2\n false\n\n iex> 1 == 1.0\n true\n\n \"\"\"\n @spec (term == term) :: boolean\n def left == right do\n :erlang.==(left, right)\n end\n\n @doc \"\"\"\n Returns `true` if the two items are not equal.\n\n This operator considers 1 and 1.0 to be equal. For match\n comparison, use `!==` instead.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 != 2\n true\n\n iex> 1 != 1.0\n false\n\n \"\"\"\n @spec (term != term) :: boolean\n def left != right do\n :erlang.\"\/=\"(left, right)\n end\n\n @doc \"\"\"\n Returns `true` if the two items are match.\n\n This operator gives the same semantics as the one existing in\n pattern matching, i.e., `1` and `1.0` are equal, but they do\n not match.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 === 2\n false\n\n iex> 1 === 1.0\n false\n\n \"\"\"\n @spec (term === term) :: boolean\n def left === right do\n :erlang.\"=:=\"(left, right)\n end\n\n @doc \"\"\"\n Returns `true` if the two items do not match.\n\n All terms in Elixir can be compared with each other.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Examples\n\n iex> 1 !== 2\n true\n\n iex> 1 !== 1.0\n true\n\n \"\"\"\n @spec (term !== term) :: boolean\n def left !== right do\n :erlang.\"=\/=\"(left, right)\n end\n\n @doc \"\"\"\n Get the element at the zero-based `index` in `tuple`.\n\n Allowed in guard tests. Inlined by the compiler.\n\n ## Example\n\n iex> tuple = {:foo, :bar, 3}\n iex> elem(tuple, 1)\n :bar\n\n \"\"\"\n @spec elem(tuple, non_neg_integer) :: term\n def elem(tuple, index) do\n :erlang.element(index + 1, tuple)\n end\n\n @doc \"\"\"\n Puts the element in `tuple` at the zero-based `index` to the given `value`.\n\n Inlined by the compiler.\n\n ## Example\n\n iex> tuple = {:foo, :bar, 3}\n iex> put_elem(tuple, 0, :baz)\n {:baz, :bar, 3}\n\n \"\"\"\n @spec put_elem(tuple, non_neg_integer, term) :: tuple\n def put_elem(tuple, index, value) do\n :erlang.setelement(index + 1, tuple, value)\n end\n\n ## Implemented in Elixir\n\n @doc \"\"\"\n Boolean or. Requires only the first argument to be a\n boolean since it short-circuits.\n\n Allowed in guard tests.\n\n ## Examples\n\n iex> true or false\n true\n\n \"\"\"\n defmacro left or right do\n quote do: __op__(:orelse, unquote(left), unquote(right))\n end\n\n @doc \"\"\"\n Boolean and. Requires only the first argument to be a\n boolean since it short-circuits.\n\n Allowed in guard tests.\n\n ## Examples\n\n iex> true and false\n false\n\n \"\"\"\n defmacro left and right do\n quote do: __op__(:andalso, unquote(left), unquote(right))\n end\n\n @doc \"\"\"\n Receives any argument and returns `true` if it is `false`\n or `nil`. Returns `false` otherwise. Not allowed in guard\n clauses.\n\n ## Examples\n\n iex> !Enum.empty?([])\n false\n\n iex> !List.first([])\n true\n\n \"\"\"\n defmacro !(arg)\n\n defmacro !({:!, _, [arg]}) do\n optimize_boolean(quote do\n case unquote(arg) do\n x when x in [false, nil] -> false\n _ -> true\n end\n end)\n end\n\n defmacro !(arg) do\n optimize_boolean(quote do\n case unquote(arg) do\n x when x in [false, nil] -> true\n _ -> false\n end\n end)\n end\n\n @doc \"\"\"\n Concatenates two binaries.\n\n ## Examples\n\n iex> \"foo\" <> \"bar\"\n \"foobar\"\n\n The `<>` operator can also be used in guard clauses as\n long as the first part is a literal binary:\n\n iex> \"foo\" <> x = \"foobar\"\n iex> x\n \"bar\"\n\n \"\"\"\n defmacro left <> right do\n concats = extract_concatenations({:<>, [], [left, right]})\n quote do: << unquote_splicing(concats) >>\n end\n\n # Extracts concatenations in order to optimize many\n # concatenations into one single clause.\n defp extract_concatenations({:<>, _, [left, right]}) do\n [wrap_concatenation(left)|extract_concatenations(right)]\n end\n\n defp extract_concatenations(other) do\n [wrap_concatenation(other)]\n end\n\n defp wrap_concatenation(binary) when is_binary(binary) do\n binary\n end\n\n defp wrap_concatenation(other) do\n {:::, [], [other, {:binary, [], nil}]}\n end\n\n @doc \"\"\"\n Raises an exception.\n\n If the argument is a binary, it raises `RuntimeError`\n using the given argument as message.\n\n If an atom, it will become a call to `raise(atom, [])`.\n\n If anything else, it will just raise the given exception.\n\n ## Examples\n\n raise \"Given values do not match\"\n\n try do\n 1 + :foo\n rescue\n x in [ArithmeticError] ->\n IO.puts \"that was expected\"\n raise x\n end\n\n \"\"\"\n defmacro raise(msg) do\n # Try to figure out the type at compilation time\n # to avoid dead code and make dialyzer happy.\n msg = case not is_binary(msg) and bootstraped?(Macro) do\n true -> Macro.expand(msg, __CALLER__)\n false -> msg\n end\n\n case msg do\n msg when is_binary(msg) ->\n quote do\n :erlang.error RuntimeError.exception(unquote(msg))\n end\n {:<<>>, _, _} = msg ->\n quote do\n :erlang.error RuntimeError.exception(unquote(msg))\n end\n alias when is_atom(alias) ->\n quote do\n :erlang.error unquote(alias).exception([])\n end\n _ ->\n quote do\n case unquote(msg) do\n msg when is_binary(msg) ->\n :erlang.error RuntimeError.exception(msg)\n atom when is_atom(atom) ->\n :erlang.error atom.exception([])\n %{__struct__: struct, __exception__: true} = other when is_atom(struct) ->\n :erlang.error other\n end\n end\n end\n end\n\n @doc \"\"\"\n Raises an exception.\n\n Calls `.exception` on the given argument passing\n the attributes in order to retrieve the appropriate exception\n structure.\n\n Any module defined via `defexception\/1` automatically\n implements `exception(attrs)` callback expected by `raise\/2`.\n\n ## Examples\n\n iex> raise(ArgumentError, message: \"Sample\")\n ** (ArgumentError) Sample\n\n \"\"\"\n defmacro raise(exception, attrs) do\n quote do\n :erlang.error unquote(exception).exception(unquote(attrs))\n end\n end\n\n @doc \"\"\"\n Raises an exception preserving a previous stacktrace.\n\n Works like `raise\/1` but does not generate a new stacktrace.\n\n Notice that `System.stacktrace` returns the stacktrace\n of the last exception. That said, it is common to assign\n the stacktrace as the first expression inside a `rescue`\n clause as any other exception potentially raised (and\n rescued) in between the rescue clause and the raise call\n may change the `System.stacktrace` value.\n\n ## Examples\n\n try do\n raise \"Oops\"\n rescue\n exception ->\n stacktrace = System.stacktrace\n if Exception.message(exception) == \"Oops\" do\n reraise exception, stacktrace\n end\n end\n \"\"\"\n defmacro reraise(msg, stacktrace) do\n # Try to figure out the type at compilation time\n # to avoid dead code and make dialyzer happy.\n\n case Macro.expand(msg, __CALLER__) do\n msg when is_binary(msg) ->\n quote do\n :erlang.raise :error, RuntimeError.exception(unquote(msg)), unquote(stacktrace)\n end\n {:<<>>, _, _} = msg ->\n quote do\n :erlang.raise :error, RuntimeError.exception(unquote(msg)), unquote(stacktrace)\n end\n alias when is_atom(alias) ->\n quote do\n :erlang.raise :error, unquote(alias).exception([]), unquote(stacktrace)\n end\n msg ->\n quote do\n stacktrace = unquote(stacktrace)\n case unquote(msg) do\n msg when is_binary(msg) ->\n :erlang.raise :error, RuntimeError.exception(msg), stacktrace\n atom when is_atom(atom) ->\n :erlang.raise :error, atom.exception([]), stacktrace\n %{__struct__: struct, __exception__: true} = other when is_atom(struct) ->\n :erlang.raise :error, other, stacktrace\n end\n end\n end\n end\n\n @doc \"\"\"\n Raises an exception preserving a previous stacktrace.\n\n Works like `raise\/2` but does not generate a new stacktrace.\n\n See `reraise\/2` for more details.\n\n ## Examples\n\n try do\n raise \"Oops\"\n rescue\n exception ->\n stacktrace = System.stacktrace\n reraise WrapperError, [exception: exception], stacktrace\n end\n \"\"\"\n defmacro reraise(exception, attrs, stacktrace) do\n quote do\n :erlang.raise :error, unquote(exception).exception(unquote(attrs)), unquote(stacktrace)\n end\n end\n\n @doc \"\"\"\n Matches the term on the left against the regular expression or string on the\n right. Returns true if `left` matches `right` (if it's a regular expression)\n or contains `right` (if it's a string).\n\n ## Examples\n\n iex> \"abcd\" =~ ~r\/c(d)\/\n true\n\n iex> \"abcd\" =~ ~r\/e\/\n false\n\n iex> \"abcd\" =~ \"bc\"\n true\n\n iex> \"abcd\" =~ \"ad\"\n false\n\n \"\"\"\n def left =~ right when is_binary(left) and is_binary(right) do\n :binary.match(left, right) != :nomatch\n end\n\n def left =~ right when is_binary(left) do\n Regex.match?(right, left)\n end\n\n @doc ~S\"\"\"\n Inspect the given argument according to the `Inspect` protocol.\n The second argument is a keywords list with options to control\n inspection.\n\n ## Options\n\n `inspect\/2` accepts a list of options that are internally\n translated to an `Inspect.Opts` struct. Check the docs for\n `Inspect.Opts` to see the supported options.\n\n ## Examples\n\n iex> inspect(:foo)\n \":foo\"\n\n iex> inspect [1, 2, 3, 4, 5], limit: 3\n \"[1, 2, 3, ...]\"\n\n iex> inspect(\"jos\u00e9\" <> <<0>>)\n \"<<106, 111, 115, 195, 169, 0>>\"\n\n iex> inspect(\"jos\u00e9\" <> <<0>>, binaries: :as_strings)\n \"\\\"jos\u00e9\\\\000\\\"\"\n\n iex> inspect(\"jos\u00e9\", binaries: :as_binaries)\n \"<<106, 111, 115, 195, 169>>\"\n\n Note that the inspect protocol does not necessarily return a valid\n representation of an Elixir term. In such cases, the inspected result\n must start with `#`. For example, inspecting a function will return:\n\n inspect fn a, b -> a + b end\n #=> #Function<...>\n\n \"\"\"\n @spec inspect(Inspect.t, Keyword.t) :: String.t\n def inspect(arg, opts \\\\ []) when is_list(opts) do\n opts = struct(Inspect.Opts, opts)\n limit = case opts.pretty do\n true -> opts.width\n false -> :infinity\n end\n Inspect.Algebra.pretty(Inspect.Algebra.to_doc(arg, opts), limit)\n end\n\n @doc \"\"\"\n Creates and updates structs.\n\n The struct argument may be an atom (which defines `defstruct`)\n or a struct itself. The second argument is any Enumerable that\n emits two-item tuples (key-value) during enumeration.\n\n If one of the keys in the Enumerable does not exist in the struct,\n they are automatically discarded.\n\n This function is useful for dynamically creating and updating\n structs.\n\n ## Example\n\n defmodule User do\n defstruct name: \"jose\"\n end\n\n struct(User)\n #=> %User{name: \"jose\"}\n\n opts = [name: \"eric\"]\n user = struct(User, opts)\n #=> %User{name: \"eric\"}\n\n struct(user, unknown: \"value\")\n #=> %User{name: \"eric\"}\n\n \"\"\"\n @spec struct(module | map, Enum.t) :: map\n def struct(struct, kv \\\\ [])\n\n def struct(struct, []) when is_atom(struct) or is_tuple(struct) do\n apply(struct, :__struct__, [])\n end\n\n def struct(struct, kv) when is_atom(struct) or is_tuple(struct) do\n struct(apply(struct, :__struct__, []), kv)\n end\n\n def struct(%{__struct__: _} = struct, kv) do\n Enum.reduce(kv, struct, fn {k, v}, acc ->\n case :maps.is_key(k, acc) and k != :__struct__ do\n true -> :maps.put(k, v, acc)\n false -> acc\n end\n end)\n end\n\n @doc \"\"\"\n Gets a value from a nested structure.\n\n Uses the `Access` protocol to traverse the structures\n according to the given `keys`, unless the `key` is a\n function.\n\n If a key is a function, the function will be invoked\n passing three arguments, the operation (`:get`), the\n data to be accessed, and a function to be invoked next.\n\n This means `get_in\/2` can be extended to provide\n custom lookups. The downside is that functions cannot be\n stored as keys in the accessed data structures.\n\n ## Examples\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> get_in(users, [\"jos\u00e9\", :age])\n 27\n\n In case any of entries in the middle returns `nil`, `nil` will be returned\n as per the Access protocol:\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> get_in(users, [\"unknown\", :age])\n nil\n\n When one of the keys is a function, the function is invoked.\n In the example below, we use a function to get all the maps\n inside a list:\n\n iex> users = [%{name: \"jos\u00e9\", age: 27}, %{name: \"eric\", age: 23}]\n iex> all = fn :get, data, next -> Enum.map(data, next) end\n iex> get_in(users, [all, :age])\n [27, 23]\n\n If the previous value before invoking the function is nil,\n the function *will* receive nil as a value and must handle it\n accordingly.\n \"\"\"\n @spec get_in(Access.t, nonempty_list(term)) :: term\n def get_in(data, keys)\n\n def get_in(data, [h]) when is_function(h),\n do: h.(:get, data, &(&1))\n def get_in(data, [h|t]) when is_function(h),\n do: h.(:get, data, &get_in(&1, t))\n\n def get_in(nil, [_]),\n do: nil\n def get_in(nil, [_|t]),\n do: get_in(nil, t)\n\n def get_in(data, [h]),\n do: Access.get(data, h)\n def get_in(data, [h|t]),\n do: get_in(Access.get(data, h), t)\n\n @doc \"\"\"\n Puts a value in a nested structure.\n\n Uses the `Access` protocol to traverse the structures\n according to the given `keys`, unless the `key` is a\n function. If the key is a function, it will be invoked\n as specified in `get_and_update_in\/3`.\n\n ## Examples\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> put_in(users, [\"jos\u00e9\", :age], 28)\n %{\"jos\u00e9\" => %{age: 28}, \"eric\" => %{age: 23}}\n\n In case any of entries in the middle returns `nil`,\n an error will be raised when trying to access it next.\n \"\"\"\n @spec put_in(Access.t, nonempty_list(term), term) :: Access.t\n def put_in(data, keys, value) do\n elem(get_and_update_in(data, keys, fn _ -> {nil, value} end), 1)\n end\n\n @doc \"\"\"\n Updates a key in a nested structure.\n\n Uses the `Access` protocol to traverse the structures\n according to the given `keys`, unless the `key` is a\n function. If the key is a function, it will be invoked\n as specified in `get_and_update_in\/3`.\n\n ## Examples\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> update_in(users, [\"jos\u00e9\", :age], &(&1 + 1))\n %{\"jos\u00e9\" => %{age: 28}, \"eric\" => %{age: 23}}\n\n In case any of entries in the middle returns `nil`,\n an error will be raised when trying to access it next.\n \"\"\"\n @spec update_in(Access.t, nonempty_list(term), (term -> term)) :: Access.t\n def update_in(data, keys, fun) do\n elem(get_and_update_in(data, keys, fn x -> {nil, fun.(x)} end), 1)\n end\n\n @doc \"\"\"\n Gets a value and updates a nested structure.\n\n It expects a tuple to be returned, containing the value\n retrieved and the update one.\n\n Uses the `Access` protocol to traverse the structures\n according to the given `keys`, unless the `key` is a\n function.\n\n If a key is a function, the function will be invoked\n passing three arguments, the operation (`:get_and_update`),\n the data to be accessed, and a function to be invoked next.\n\n This means `get_and_update_in\/3` can be extended to provide\n custom lookups. The downside is that functions cannot be stored\n as keys in the accessed data structures.\n\n ## Examples\n\n This function is useful when there is a need to retrieve the current\n value (or something calculated in function of the current value) and\n update it at the same time. For example, it could be used to increase\n the age of a user by one and return the previous age in one pass:\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> get_and_update_in(users, [\"jos\u00e9\", :age], &{&1, &1 + 1})\n {27, %{\"jos\u00e9\" => %{age: 28}, \"eric\" => %{age: 23}}}\n\n When one of the keys is a function, the function is invoked.\n In the example below, we use a function to get and increment all\n ages inside a list:\n\n iex> users = [%{name: \"jos\u00e9\", age: 27}, %{name: \"eric\", age: 23}]\n iex> all = fn :get_and_update, data, next ->\n ...> Enum.map(data, next) |> List.unzip() |> List.to_tuple()\n ...> end\n iex> get_and_update_in(users, [all, :age], &{&1, &1 + 1})\n {[27, 23], [%{name: \"jos\u00e9\", age: 28}, %{name: \"eric\", age: 24}]}\n\n If the previous value before invoking the function is nil,\n the function *will* receive `nil` as a value and must handle it\n accordingly (be it by failing or providing a sane default).\n \"\"\"\n @spec get_and_update_in(Access.t, nonempty_list(term),\n (term -> {get, term})) :: {get, Access.t} when get: var\n def get_and_update_in(data, keys, fun)\n\n def get_and_update_in(data, [h], fun) when is_function(h),\n do: h.(:get_and_update, data, fun)\n def get_and_update_in(data, [h|t], fun) when is_function(h),\n do: h.(:get_and_update, data, &get_and_update_in(&1, t, fun))\n\n def get_and_update_in(data, [h], fun),\n do: Access.get_and_update(data, h, fun)\n def get_and_update_in(data, [h|t], fun),\n do: Access.get_and_update(data, h, &get_and_update_in(&1, t, fun))\n\n @doc \"\"\"\n Puts a value in a nested structure via the given `path`.\n\n This is similar to `put_in\/3`, except the path is extracted via\n a macro rather than passing a list. For example:\n\n put_in(opts[:foo][:bar], :baz)\n\n Is equivalent to:\n\n put_in(opts, [:foo, :bar], :baz)\n\n Note that in order for this macro to work, the complete path must always\n be visible by this macro. For more information about the supported path\n expressions, please check `get_and_update_in\/2` docs.\n\n ## Examples\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> put_in(users[\"jos\u00e9\"][:age], 28)\n %{\"jos\u00e9\" => %{age: 28}, \"eric\" => %{age: 23}}\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> put_in(users[\"jos\u00e9\"].age, 28)\n %{\"jos\u00e9\" => %{age: 28}, \"eric\" => %{age: 23}}\n\n \"\"\"\n defmacro put_in(path, value) do\n [h|t] = unnest(path, [], \"put_in\/2\")\n expr = nest_get_and_update_in(h, t, quote(do: fn _ -> {nil, unquote(value)} end))\n quote do: :erlang.element(2, unquote(expr))\n end\n\n @doc \"\"\"\n Updates a nested structure via the given `path`.\n\n This is similar to `update_in\/3`, except the path is extracted via\n a macro rather than passing a list. For example:\n\n update_in(opts[:foo][:bar], &(&1 + 1))\n\n Is equivalent to:\n\n update_in(opts, [:foo, :bar], &(&1 + 1))\n\n Note that in order for this macro to work, the complete path must always\n be visible by this macro. For more information about the supported path\n expressions, please check `get_and_update_in\/2` docs.\n\n ## Examples\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> update_in(users[\"jos\u00e9\"][:age], &(&1 + 1))\n %{\"jos\u00e9\" => %{age: 28}, \"eric\" => %{age: 23}}\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> update_in(users[\"jos\u00e9\"].age, &(&1 + 1))\n %{\"jos\u00e9\" => %{age: 28}, \"eric\" => %{age: 23}}\n\n \"\"\"\n defmacro update_in(path, fun) do\n [h|t] = unnest(path, [], \"update_in\/2\")\n expr = nest_get_and_update_in(h, t, quote(do: fn x -> {nil, unquote(fun).(x)} end))\n quote do: :erlang.element(2, unquote(expr))\n end\n\n @doc \"\"\"\n Gets a value and updates a nested data structure via the given `path`.\n\n This is similar to `get_and_update_in\/3`, except the path is extracted\n via a macro rather than passing a list. For example:\n\n get_and_update_in(opts[:foo][:bar], &{&1, &1 + 1})\n\n Is equivalent to:\n\n get_and_update_in(opts, [:foo, :bar], &{&1, &1 + 1})\n\n Note that in order for this macro to work, the complete path must always\n be visible by this macro. See the Paths section below.\n\n ## Examples\n\n iex> users = %{\"jos\u00e9\" => %{age: 27}, \"eric\" => %{age: 23}}\n iex> get_and_update_in(users[\"jos\u00e9\"].age, &{&1, &1 + 1})\n {27, %{\"jos\u00e9\" => %{age: 28}, \"eric\" => %{age: 23}}}\n\n ## Paths\n\n A path may start with a variable, local or remote call, and must be\n followed by one or more:\n\n * `foo[bar]` - access a field; in case an intermediate field is not\n present or returns nil, an empty map is used\n\n * `foo.bar` - access a map\/struct field; in case the field is not\n present, an error is raised\n\n Here are some valid paths:\n\n users[\"jos\u00e9\"][:age]\n users[\"jos\u00e9\"].age\n User.all[\"jos\u00e9\"].age\n all_users()[\"jos\u00e9\"].age\n\n Here are some invalid ones:\n\n # Does a remote call after the initial value\n users[\"jos\u00e9\"].do_something(arg1, arg2)\n\n # Does not access any field\n users\n\n \"\"\"\n defmacro get_and_update_in(path, fun) do\n [h|t] = unnest(path, [], \"get_and_update_in\/2\")\n nest_get_and_update_in(h, t, fun)\n end\n\n defp nest_get_and_update_in([], fun), do: fun\n defp nest_get_and_update_in(list, fun) do\n quote do\n fn x -> unquote(nest_get_and_update_in(quote(do: x), list, fun)) end\n end\n end\n\n defp nest_get_and_update_in(h, [{:access, key}|t], fun) do\n quote do\n Access.get_and_update(\n case(unquote(h), do: (nil -> %{}; o -> o)),\n unquote(key),\n unquote(nest_get_and_update_in(t, fun))\n )\n end\n end\n\n defp nest_get_and_update_in(h, [{:map, key}|t], fun) do\n quote do\n Access.Map.get_and_update!(unquote(h), unquote(key), unquote(nest_get_and_update_in(t, fun)))\n end\n end\n\n defp unnest({{:., _, [Access, :get]}, _, [expr, key]}, acc, kind) do\n unnest(expr, [{:access, key}|acc], kind)\n end\n\n defp unnest({{:., _, [expr, key]}, _, []}, acc, kind)\n when is_tuple(expr) and elem(expr, 0) != :__aliases__ and elem(expr, 0) != :__MODULE__ do\n unnest(expr, [{:map, key}|acc], kind)\n end\n\n defp unnest(other, [], kind) do\n raise ArgumentError,\n \"expected expression given to #{kind} to access at least one element, got: #{Macro.to_string other}\"\n end\n\n defp unnest(other, acc, kind) do\n case proper_start?(other) do\n true -> [other|acc]\n false ->\n raise ArgumentError,\n \"expression given to #{kind} must start with a variable, local or remote call \" <>\n \"and be followed by an element access, got: #{Macro.to_string other}\"\n end\n end\n\n defp proper_start?({{:., _, [expr, _]}, _, _args})\n when is_atom(expr)\n when elem(expr, 0) == :__aliases__\n when elem(expr, 0) == :__MODULE__, do: true\n\n defp proper_start?({atom, _, _args})\n when is_atom(atom), do: true\n\n defp proper_start?(other),\n do: not is_tuple(other)\n\n @doc \"\"\"\n Converts the argument to a string according to the\n `String.Chars` protocol.\n\n This is the function invoked when there is string interpolation.\n\n ## Examples\n\n iex> to_string(:foo)\n \"foo\"\n\n \"\"\"\n # If it is a binary at compilation time, simply return it.\n defmacro to_string(arg) when is_binary(arg), do: arg\n\n defmacro to_string(arg) do\n quote do: String.Chars.to_string(unquote(arg))\n end\n\n @doc \"\"\"\n Convert the argument to a list according to the List.Chars protocol.\n\n ## Examples\n\n iex> to_char_list(:foo)\n 'foo'\n\n \"\"\"\n defmacro to_char_list(arg) do\n quote do: List.Chars.to_char_list(unquote(arg))\n end\n\n @doc \"\"\"\n Checks if the given argument is nil or not.\n Allowed in guard clauses.\n\n ## Examples\n\n iex> nil?(1)\n false\n\n iex> nil?(nil)\n true\n\n \"\"\"\n defmacro nil?(x) do\n quote do: unquote(x) == nil\n end\n\n @doc \"\"\"\n A convenient macro that checks if the right side matches\n the left side. The left side is allowed to be a match pattern.\n\n ## Examples\n\n iex> match?(1, 1)\n true\n\n iex> match?(1, 2)\n false\n\n iex> match?({1, _}, {1, 2})\n true\n\n Match can also be used to filter or find a value in an enumerable:\n\n list = [{:a, 1}, {:b, 2}, {:a, 3}]\n Enum.filter list, &match?({:a, _}, &1)\n\n Guard clauses can also be given to the match:\n\n list = [{:a, 1}, {:b, 2}, {:a, 3}]\n Enum.filter list, &match?({:a, x} when x < 2, &1)\n\n However, variables assigned in the match will not be available\n outside of the function call:\n\n iex> match?(x, 1)\n true\n\n iex> binding([:x]) == []\n true\n\n \"\"\"\n defmacro match?(pattern, expr)\n\n # Special case underscore since it always matches\n defmacro match?({:_, _, atom}, _right) when is_atom(atom) do\n true\n end\n\n defmacro match?(left, right) do\n quote do\n case unquote(right) do\n unquote(left) ->\n true\n _ ->\n false\n end\n end\n end\n\n @doc \"\"\"\n Read and write attributes of th current module.\n\n The canonical example for attributes is annotating that a module\n implements the OTP behaviour called `gen_server`:\n\n defmodule MyServer do\n @behaviour :gen_server\n # ... callbacks ...\n end\n\n By default Elixir supports all Erlang module attributes, but any developer\n can also add custom attributes:\n\n defmodule MyServer do\n @my_data 13\n IO.inspect @my_data #=> 13\n end\n\n Unlike Erlang, such attributes are not stored in the module by\n default since it is common in Elixir to use such attributes to store\n temporary data. A developer can configure an attribute to behave closer\n to Erlang by calling `Module.register_attribute\/3`.\n\n Finally, notice that attributes can also be read inside functions:\n\n defmodule MyServer do\n @my_data 11\n def first_data, do: @my_data\n @my_data 13\n def second_data, do: @my_data\n end\n\n MyServer.first_data #=> 11\n MyServer.second_data #=> 13\n\n It is important to note that reading an attribute takes a snapshot of\n its current value. In other words, the value is read at compilation\n time and not at runtime. Check the module `Module` for other functions\n to manipulate module attributes.\n \"\"\"\n defmacro @(expr)\n\n # Typespecs attributes are special cased by the compiler so far\n defmacro @({name, _, args}) do\n # Check for Macro as it is compiled later than Module\n case bootstraped?(Module) do\n false -> nil\n true ->\n assert_module_scope(__CALLER__, :@, 1)\n function? = __CALLER__.function != nil\n\n case is_list(args) and length(args) == 1 and typespec(name) do\n false ->\n case name == :typedoc and not bootstraped?(Kernel.Typespec) do\n true -> nil\n false -> do_at(args, name, function?, __CALLER__)\n end\n macro ->\n case bootstraped?(Kernel.Typespec) do\n false -> nil\n true -> quote do: Kernel.Typespec.unquote(macro)(unquote(hd(args)))\n end\n end\n end\n end\n\n # @attribute value\n defp do_at([arg], name, function?, env) do\n case function? do\n true ->\n raise ArgumentError, \"cannot dynamically set attribute @#{name} inside function\"\n false ->\n case name do\n :behavior ->\n :elixir_errors.warn warn_info(env_stacktrace(env)),\n \"@behavior attribute is not supported, please use @behaviour instead\"\n _ ->\n :ok\n end\n\n quote do: Module.put_attribute(__MODULE__, unquote(name), unquote(arg))\n end\n end\n\n # @attribute or @attribute()\n defp do_at(args, name, function?, env) when is_atom(args) or args == [] do\n stack = env_stacktrace(env)\n\n case function? do\n true ->\n attr = Module.get_attribute(env.module, name, stack)\n :erlang.element(1, :elixir_quote.escape(attr, false))\n false ->\n escaped = case stack do\n [] -> []\n _ -> Macro.escape(stack)\n end\n quote do: Module.get_attribute(__MODULE__, unquote(name), unquote(escaped))\n end\n end\n\n # All other cases\n defp do_at(args, name, _function?, _env) do\n raise ArgumentError, \"expected 0 or 1 argument for @#{name}, got: #{length(args)}\"\n end\n\n defp warn_info([entry|_]) do\n opts = elem(entry, tuple_size(entry) - 1)\n Exception.format_file_line(Keyword.get(opts, :file), Keyword.get(opts, :line)) <> \" \"\n end\n\n defp warn_info([]) do\n \"\"\n end\n\n defp typespec(:type), do: :deftype\n defp typespec(:typep), do: :deftypep\n defp typespec(:opaque), do: :defopaque\n defp typespec(:spec), do: :defspec\n defp typespec(:callback), do: :defcallback\n defp typespec(_), do: false\n\n @doc \"\"\"\n Returns the binding as a keyword list where the variable name\n is the key and the variable value is the value.\n\n ## Examples\n\n iex> x = 1\n iex> binding()\n [x: 1]\n iex> x = 2\n iex> binding()\n [x: 2]\n\n \"\"\"\n defmacro binding() do\n do_binding(nil, nil, __CALLER__.vars, Macro.Env.in_match?(__CALLER__))\n end\n\n @doc \"\"\"\n Receives a list of atoms at compilation time and returns the\n binding of the given variables as a keyword list where the\n variable name is the key and the variable value is the value.\n\n In case a variable in the list does not exist in the binding,\n it is not included in the returned result.\n\n ## Examples\n\n iex> x = 1\n iex> binding([:x, :y])\n [x: 1]\n\n \"\"\"\n defmacro binding(list) when is_list(list) do\n do_binding(list, nil, __CALLER__.vars, Macro.Env.in_match?(__CALLER__))\n end\n\n defmacro binding(context) when is_atom(context) do\n do_binding(nil, context, __CALLER__.vars, Macro.Env.in_match?(__CALLER__))\n end\n\n @doc \"\"\"\n Receives a list of atoms at compilation time and returns the\n binding of the given variables in the given context as a keyword\n list where the variable name is the key and the variable value\n is the value.\n\n In case a variable in the list does not exist in the binding,\n it is not included in the returned result.\n\n ## Examples\n\n iex> var!(x, :foo) = 1\n iex> binding([:x, :y])\n []\n iex> binding([:x, :y], :foo)\n [x: 1]\n\n \"\"\"\n defmacro binding(list, context) when is_list(list) and is_atom(context) do\n do_binding(list, context, __CALLER__.vars, Macro.Env.in_match?(__CALLER__))\n end\n\n defp do_binding(list, context, vars, in_match) do\n for {v, c} <- vars, c == context, list == nil or :lists.member(v, list) do\n {v, wrap_binding(in_match, {v, [], c})}\n end\n end\n\n defp wrap_binding(true, var) do\n quote do: ^(unquote(var))\n end\n\n defp wrap_binding(_, var) do\n var\n end\n\n @doc \"\"\"\n Provides an `if` macro. This macro expects the first argument to\n be a condition and the rest are keyword arguments.\n\n ## One-liner examples\n\n if(foo, do: bar)\n\n In the example above, `bar` will be returned if `foo` evaluates to\n `true` (i.e. it is neither `false` nor `nil`). Otherwise, `nil` will be returned.\n\n An `else` option can be given to specify the opposite:\n\n if(foo, do: bar, else: baz)\n\n ## Blocks examples\n\n Elixir also allows you to pass a block to the `if` macro. The first\n example above would be translated to:\n\n if foo do\n bar\n end\n\n Notice that `do\/end` becomes delimiters. The second example would\n then translate to:\n\n if foo do\n bar\n else\n baz\n end\n\n If you want to compare more than two clauses, you can use the `cond\/1`\n macro.\n \"\"\"\n defmacro if(condition, clauses) do\n do_clause = Keyword.get(clauses, :do, nil)\n else_clause = Keyword.get(clauses, :else, nil)\n\n optimize_boolean(quote do\n case unquote(condition) do\n x when x in [false, nil] -> unquote(else_clause)\n _ -> unquote(do_clause)\n end\n end)\n end\n\n @doc \"\"\"\n Evaluates and returns the do-block passed in as a second argument\n unless clause evaluates to true.\n Returns nil otherwise.\n See also `if`.\n\n ## Examples\n\n iex> unless(Enum.empty?([]), do: \"Hello\")\n nil\n\n iex> unless(Enum.empty?([1,2,3]), do: \"Hello\")\n \"Hello\"\n\n \"\"\"\n defmacro unless(clause, options) do\n do_clause = Keyword.get(options, :do, nil)\n else_clause = Keyword.get(options, :else, nil)\n quote do\n if(unquote(clause), do: unquote(else_clause), else: unquote(do_clause))\n end\n end\n\n @doc \"\"\"\n Allows you to destructure two lists, assigning each term in the right to the\n matching term in the left. Unlike pattern matching via `=`, if the sizes of\n the left and right lists don't match, destructuring simply stops instead of\n raising an error.\n\n ## Examples\n\n iex> destructure([x, y, z], [1, 2, 3, 4, 5])\n iex> {x, y, z}\n {1, 2, 3}\n\n Notice in the example above, even though the right\n size has more entries than the left, destructuring works\n fine. If the right size is smaller, the remaining items\n are simply assigned to nil:\n\n iex> destructure([x, y, z], [1])\n iex> {x, y, z}\n {1, nil, nil}\n\n The left side supports any expression you would use\n on the left side of a match:\n\n x = 1\n destructure([^x, y, z], [1, 2, 3])\n\n The example above will only work if x matches\n the first value from the right side. Otherwise,\n it will raise a CaseClauseError.\n \"\"\"\n defmacro destructure(left, right) when is_list(left) do\n Enum.reduce left, right, fn item, acc ->\n {:case, meta, args} =\n quote do\n case unquote(acc) do\n [unquote(item)|t] ->\n t\n other when other == [] or other == nil ->\n unquote(item) = nil\n end\n end\n {:case, [{:export_head,true}|meta], args}\n end\n end\n\n @doc \"\"\"\n Returns a range with the specified start and end.\n Includes both ends.\n\n ## Examples\n\n iex> 0 in 1..3\n false\n\n iex> 1 in 1..3\n true\n\n iex> 2 in 1..3\n true\n\n iex> 3 in 1..3\n true\n\n \"\"\"\n defmacro first .. last do\n {:%{}, [], [__struct__: Elixir.Range, first: first, last: last]}\n end\n\n @doc \"\"\"\n Provides a short-circuit operator that evaluates and returns\n the second expression only if the first one evaluates to true\n (i.e. it is not nil nor false). Returns the first expression\n otherwise.\n\n ## Examples\n\n iex> Enum.empty?([]) && Enum.empty?([])\n true\n\n iex> List.first([]) && true\n nil\n\n iex> Enum.empty?([]) && List.first([1])\n 1\n\n iex> false && throw(:bad)\n false\n\n Notice that, unlike Erlang's `and` operator,\n this operator accepts any expression as an argument,\n not only booleans, however it is not allowed in guards.\n \"\"\"\n defmacro left && right do\n quote do\n case unquote(left) do\n x when x in [false, nil] ->\n x\n _ ->\n unquote(right)\n end\n end\n end\n\n @doc \"\"\"\n Provides a short-circuit operator that evaluates and returns the second\n expression only if the first one does not evaluate to true (i.e. it\n is either nil or false). Returns the first expression otherwise.\n\n ## Examples\n\n iex> Enum.empty?([1]) || Enum.empty?([1])\n false\n\n iex> List.first([]) || true\n true\n\n iex> Enum.empty?([1]) || 1\n 1\n\n iex> Enum.empty?([]) || throw(:bad)\n true\n\n Notice that, unlike Erlang's `or` operator,\n this operator accepts any expression as an argument,\n not only booleans, however it is not allowed in guards.\n \"\"\"\n defmacro left || right do\n quote do\n case unquote(left) do\n x when x in [false, nil] ->\n unquote(right)\n x ->\n x\n end\n end\n end\n\n @doc \"\"\"\n `|>` is the pipe operator.\n\n This operator introduces the expression on the left as\n the first argument to the function call on the right.\n\n ## Examples\n\n iex> [1, [2], 3] |> List.flatten()\n [1, 2, 3]\n\n The example above is the same as calling `List.flatten([1, [2], 3])`,\n i.e. the argument on the left side of `|>` is introduced as the first\n argument of the function call on the right side.\n\n This pattern is mostly useful when there is a desire to execute\n a bunch of operations, resembling a pipeline:\n\n iex> [1, [2], 3] |> List.flatten |> Enum.map(fn x -> x * 2 end)\n [2, 4, 6]\n\n The example above will pass the list to `List.flatten\/1`, then get\n the flattened list and pass to `Enum.map\/2`, which will multiply\n each entry in the list per two.\n\n In other words, the expression above simply translates to:\n\n Enum.map(List.flatten([1, [2], 3]), fn x -> x * 2 end)\n\n Beware of operator precedence when using the pipe operator.\n For example, the following expression:\n\n String.graphemes \"Hello\" |> Enum.reverse\n\n Translates to:\n\n String.graphemes(\"Hello\" |> Enum.reverse)\n\n Which will result in an error as Enumerable protocol is not defined\n for binaries. Adding explicit parenthesis resolves the ambiguity:\n\n String.graphemes(\"Hello\") |> Enum.reverse\n\n Or, even better:\n\n \"Hello\" |> String.graphemes |> Enum.reverse\n\n \"\"\"\n defmacro left |> right do\n [{h, _}|t] = Macro.unpipe({:|>, [], [left, right]})\n :lists.foldl fn {x, pos}, acc -> Macro.pipe(acc, x, pos) end, h, t\n end\n\n @doc \"\"\"\n Returns true if the `module` is loaded and contains a\n public `function` with the given `arity`, otherwise false.\n\n Notice that this function does not load the module in case\n it is not loaded. Check `Code.ensure_loaded\/1` for more\n information.\n \"\"\"\n @spec function_exported?(atom | tuple, atom, integer) :: boolean\n def function_exported?(module, function, arity) do\n :erlang.function_exported(module, function, arity)\n end\n\n @doc \"\"\"\n Returns true if the `module` is loaded and contains a\n public `macro` with the given `arity`, otherwise false.\n\n Notice that this function does not load the module in case\n it is not loaded. Check `Code.ensure_loaded\/1` for more\n information.\n \"\"\"\n @spec macro_exported?(atom, atom, integer) :: boolean\n def macro_exported?(module, macro, arity) do\n case :code.is_loaded(module) do\n {:file, _} -> :lists.member({macro, arity}, module.__info__(:macros))\n _ -> false\n end\n end\n\n @doc \"\"\"\n Access the given element using the qualifier according\n to the `Access` protocol. All calls in the form `foo[bar]`\n are translated to `access(foo, bar)`.\n\n The usage of this protocol is to access a raw value in a\n keyword list.\n\n iex> sample = [a: 1, b: 2, c: 3]\n iex> sample[:b]\n 2\n\n \"\"\"\n\n @doc \"\"\"\n Checks if the element on the left side is member of the\n collection on the right side.\n\n ## Examples\n\n iex> x = 1\n iex> x in [1, 2, 3]\n true\n\n This macro simply translates the expression above to:\n\n Enum.member?([1,2,3], x)\n\n ## Guards\n\n The `in` operator can be used on guard clauses as long as the\n right side is a range or a list. Elixir will then expand the\n operator to a valid guard expression. For example:\n\n when x in [1,2,3]\n\n Translates to:\n\n when x === 1 or x === 2 or x === 3\n\n When using ranges:\n\n when x in 1..3\n\n Translates to:\n\n when x >= 1 and x <= 3\n\n \"\"\"\n defmacro left in right do\n cache = (__CALLER__.context == nil)\n\n right = case bootstraped?(Macro) do\n true -> Macro.expand(right, __CALLER__)\n false -> right\n end\n\n case right do\n _ when cache ->\n quote do: Elixir.Enum.member?(unquote(right), unquote(left))\n [] ->\n false\n [h|t] ->\n :lists.foldr(fn x, acc ->\n quote do\n unquote(comp(left, x)) or unquote(acc)\n end\n end, comp(left, h), t)\n {:%{}, [], [__struct__: Elixir.Range, first: first, last: last]} ->\n in_range(left, Macro.expand(first, __CALLER__), Macro.expand(last, __CALLER__))\n _ ->\n raise ArgumentError, <<\"invalid args for operator in, it expects a compile time list \",\n \"or range on the right side when used in guard expressions, got: \",\n Macro.to_string(right) :: binary>>\n end\n end\n\n defp in_range(left, first, last) do\n case opt_in?(first) and opt_in?(last) do\n true ->\n case first <= last do\n true -> increasing_compare(left, first, last)\n false -> decreasing_compare(left, first, last)\n end\n false ->\n quote do\n (:erlang.\"=<\"(unquote(first), unquote(last)) and\n unquote(increasing_compare(left, first, last)))\n or\n (:erlang.\"<\"(unquote(last), unquote(first)) and\n unquote(decreasing_compare(left, first, last)))\n end\n end\n end\n\n defp opt_in?(x), do: is_integer(x) or is_float(x) or is_atom(x)\n\n defp comp(left, right) do\n quote(do: :erlang.\"=:=\"(unquote(left), unquote(right)))\n end\n\n defp increasing_compare(var, first, last) do\n quote do\n :erlang.\">=\"(unquote(var), unquote(first)) and\n :erlang.\"=<\"(unquote(var), unquote(last))\n end\n end\n\n defp decreasing_compare(var, first, last) do\n quote do\n :erlang.\"=<\"(unquote(var), unquote(first)) and\n :erlang.\">=\"(unquote(var), unquote(last))\n end\n end\n\n @doc \"\"\"\n When used inside quoting, marks that the variable should\n not be hygienized. The argument can be either a variable\n unquoted or in standard tuple form `{name, meta, context}`.\n\n Check `Kernel.SpecialForms.quote\/2` for more information.\n \"\"\"\n defmacro var!(var, context \\\\ nil)\n\n defmacro var!({name, meta, atom}, context) when is_atom(name) and is_atom(atom) do\n do_var!(name, meta, context, __CALLER__)\n end\n\n defmacro var!(x, _context) do\n raise ArgumentError, \"expected a var to be given to var!, got: #{Macro.to_string(x)}\"\n end\n\n defp do_var!(name, meta, context, env) do\n # Remove counter and force them to be vars\n meta = :lists.keydelete(:counter, 1, meta)\n meta = :lists.keystore(:var, 1, meta, {:var, true})\n\n case Macro.expand(context, env) do\n x when is_atom(x) ->\n {name, meta, x}\n x ->\n raise ArgumentError, \"expected var! context to expand to an atom, got: #{Macro.to_string(x)}\"\n end\n end\n\n @doc \"\"\"\n When used inside quoting, marks that the alias should not\n be hygienezed. This means the alias will be expanded when\n the macro is expanded.\n\n Check `Kernel.SpecialForms.quote\/2` for more information.\n \"\"\"\n defmacro alias!(alias)\n\n defmacro alias!(alias) when is_atom(alias) do\n alias\n end\n\n defmacro alias!({:__aliases__, meta, args}) do\n # Simply remove the alias metadata from the node\n # so it does not affect expansion.\n {:__aliases__, :lists.keydelete(:alias, 1, meta), args}\n end\n\n ## Definitions implemented in Elixir\n\n @doc ~S\"\"\"\n Defines a module given by name with the given contents.\n\n It returns the module name, the module binary and the\n block contents result.\n\n ## Examples\n\n iex> defmodule Foo do\n ...> def bar, do: :baz\n ...> end\n iex> Foo.bar\n :baz\n\n ## Nesting\n\n Nesting a module inside another module affects its name:\n\n defmodule Foo do\n defmodule Bar do\n end\n end\n\n In the example above, two modules `Foo` and `Foo.Bar` are created.\n When nesting, Elixir automatically creates an alias, allowing the\n second module `Foo.Bar` to be accessed as `Bar` in the same lexical\n scope.\n\n This means that, if the module `Bar` is moved to another file,\n the references to `Bar` needs to be updated or an alias needs to\n be explicitly set with the help of `Kernel.SpecialForms.alias\/2`.\n\n ## Dynamic names\n\n Elixir module names can be dynamically generated. This is very\n useful for macros. For instance, one could write:\n\n defmodule String.to_atom(\"Foo#{1}\") do\n # contents ...\n end\n\n Elixir will accept any module name as long as the expression\n returns an atom. Note that, when a dynamic name is used, Elixir\n won't nest the name under the current module nor automatically\n set up an alias.\n \"\"\"\n defmacro defmodule(alias, do: block) do\n env = __CALLER__\n boot? = bootstraped?(Macro)\n\n expanded =\n case boot? do\n true -> Macro.expand(alias, env)\n false -> alias\n end\n\n {expanded, with_alias} =\n case boot? and is_atom(expanded) do\n true ->\n # Expand the module considering the current environment\/nesting\n full = expand_module(alias, expanded, env)\n\n # Generate the alias for this module definition\n {new, old} = module_nesting(env.module, full)\n meta = [defined: full, context: true] ++ alias_meta(alias)\n\n {full, {:alias, meta, [old, [as: new, warn: false]]}}\n false ->\n {expanded, nil}\n end\n\n {escaped, _} = :elixir_quote.escape(block, false)\n module_vars = module_vars(env.vars, 0)\n\n quote do\n unquote(with_alias)\n :elixir_module.compile(unquote(expanded), unquote(escaped),\n unquote(module_vars), __ENV__)\n end\n end\n\n defp alias_meta({:__aliases__, meta, _}), do: meta\n defp alias_meta(_), do: []\n\n # defmodule :foo\n defp expand_module(raw, _module, _env) when is_atom(raw),\n do: raw\n\n # defmodule Elixir.Alias\n defp expand_module({:__aliases__, _, [:Elixir|t]}, module, _env) when t != [],\n do: module\n\n # defmodule Alias in root\n defp expand_module({:__aliases__, _, _}, module, %{module: nil}),\n do: module\n\n # defmodule Alias nested\n defp expand_module({:__aliases__, _, t}, _module, env),\n do: :elixir_aliases.concat([env.module|t])\n\n # defmodule _\n defp expand_module(_raw, module, env),\n do: :elixir_aliases.concat([env.module, module])\n\n # quote vars to be injected into the module definition\n defp module_vars([{key, kind}|vars], counter) do\n var =\n case is_atom(kind) do\n true -> {key, [], kind}\n false -> {key, [counter: kind], nil}\n end\n\n under = String.to_atom(<<\"_@\", :erlang.integer_to_binary(counter)::binary>>)\n args = [key, kind, under, var]\n [{:{}, [], args}|module_vars(vars, counter+1)]\n end\n\n defp module_vars([], _counter) do\n []\n end\n\n # Gets two modules names and return an alias\n # which can be passed down to the alias directive\n # and it will create a proper shortcut representing\n # the given nesting.\n #\n # Examples:\n #\n # module_nesting('Elixir.Foo.Bar', 'Elixir.Foo.Bar.Baz.Bat')\n # {'Elixir.Baz', 'Elixir.Foo.Bar.Baz'}\n #\n # In case there is no nesting\/no module:\n #\n # module_nesting(nil, 'Elixir.Foo.Bar.Baz.Bat')\n # {false, 'Elixir.Foo.Bar.Baz.Bat'}\n #\n defp module_nesting(nil, full),\n do: {false, full}\n\n defp module_nesting(prefix, full) do\n case split_module(prefix) do\n [] -> {false, full}\n prefix -> module_nesting(prefix, split_module(full), [], full)\n end\n end\n\n defp module_nesting([x|t1], [x|t2], acc, full),\n do: module_nesting(t1, t2, [x|acc], full)\n defp module_nesting([], [h|_], acc, _full),\n do: {String.to_atom(<<\"Elixir.\", h::binary>>),\n :elixir_aliases.concat(:lists.reverse([h|acc]))}\n defp module_nesting(_, _, _acc, full),\n do: {false, full}\n\n defp split_module(atom) do\n case :binary.split(Atom.to_string(atom), \".\", [:global]) do\n [\"Elixir\"|t] -> t\n _ -> []\n end\n end\n\n @doc \"\"\"\n Defines a function with the given name and contents.\n\n ## Examples\n\n defmodule Foo do\n def bar, do: :baz\n end\n\n Foo.bar #=> :baz\n\n A function that expects arguments can be defined as follow:\n\n defmodule Foo do\n def sum(a, b) do\n a + b\n end\n end\n\n In the example above, we defined a function `sum` that receives\n two arguments and sums them.\n\n \"\"\"\n defmacro def(call, expr \\\\ nil) do\n define(:def, call, expr, __CALLER__)\n end\n\n @doc \"\"\"\n Defines a function that is private. Private functions are\n only accessible from within the module in which they are defined.\n\n Check `def\/2` for more information\n\n ## Examples\n\n defmodule Foo do\n def bar do\n sum(1, 2)\n end\n\n defp sum(a, b), do: a + b\n end\n\n In the example above, `sum` is private and accessing it\n through `Foo.sum` will raise an error.\n \"\"\"\n defmacro defp(call, expr \\\\ nil) do\n define(:defp, call, expr, __CALLER__)\n end\n\n @doc \"\"\"\n Defines a macro with the given name and contents.\n\n ## Examples\n\n defmodule MyLogic do\n defmacro unless(expr, opts) do\n quote do\n if !unquote(expr), unquote(opts)\n end\n end\n end\n\n require MyLogic\n MyLogic.unless false do\n IO.puts \"It works\"\n end\n\n \"\"\"\n defmacro defmacro(call, expr \\\\ nil) do\n define(:defmacro, call, expr, __CALLER__)\n end\n\n @doc \"\"\"\n Defines a macro that is private. Private macros are\n only accessible from the same module in which they are defined.\n\n Check `defmacro\/2` for more information\n \"\"\"\n defmacro defmacrop(call, expr \\\\ nil) do\n define(:defmacrop, call, expr, __CALLER__)\n end\n\n defp define(kind, call, expr, env) do\n assert_module_scope(env, kind, 2)\n assert_no_function_scope(env, kind, 2)\n line = env.line\n\n {call, uc} = :elixir_quote.escape(call, true)\n {expr, ue} = :elixir_quote.escape(expr, true)\n\n # Do not check clauses if any expression was unquoted\n check_clauses = not(ue or uc)\n pos = :elixir_locals.cache_env(env)\n\n quote do\n :elixir_def.store_definition(unquote(line), unquote(kind), unquote(check_clauses),\n unquote(call), unquote(expr), unquote(pos))\n end\n end\n\n @doc \"\"\"\n Defines a struct for the current module.\n\n A struct is a tagged map that allows developers to provide\n default values for keys, tags to be used in polymorphic\n dispatches and compile time assertions.\n\n To define a struct, a developer needs to only define\n a function named `__struct__\/0` that returns a map with the\n structs field. This macro is a convenience for defining such\n function, with the addition of a type `t` and deriving\n conveniences.\n\n For more information about structs, please check\n `Kernel.SpecialForms.%\/2`.\n\n ## Examples\n\n defmodule User do\n defstruct name: nil, age: nil\n end\n\n Struct fields are evaluated at definition time, which allows\n them to be dynamic. In the example below, `10 + 11` will be\n evaluated at compilation time and the age field will be stored\n with value `21`:\n\n defmodule User do\n defstruct name: nil, age: 10 + 11\n end\n\n ## Deriving\n\n Although structs are maps, by default structs do not implement\n any of the protocols implemented for maps. For example, if you\n attempt to use the access protocol with the User struct, it\n will lead to an error:\n\n %User{}[:age]\n ** (Protocol.UndefinedError) protocol Access not implemented for %User{...}\n\n However, `defstruct\/2` allows implementation for protocols to\n derived by defining a `@derive` attribute as a list before `defstruct\/2`\n is invoked:\n\n defmodule User do\n @derive [Access]\n defstruct name: nil, age: 10 + 11\n end\n\n %User{}[:age] #=> 21\n\n For each protocol given to `@derive`, Elixir will assert there is an\n implementation of that protocol for maps and check if the map\n implementation defines a `__deriving__\/3` callback. If so, the callback\n is invoked, otherwise an implementation that simply points to the map\n one is automatically derived.\n\n ## Types\n\n It is recommended to define types for structs, by convention this type\n is called `t`. To define a struct in a type the struct literal syntax\n is used:\n\n defmodule User do\n defstruct name: \"Jos\u00e9\", age: 25\n @type t :: %User{name: String.t, age: integer}\n end\n\n It is recommended to only use the struct syntax when defining the struct's\n type. When referring to another struct use `User.t`, not `%User{}`. Fields\n in the struct not included in the type defaults to `term`.\n\n Private structs that are not used outside its module should use the private\n type attribute `@typep`. Public structs whose internal structure is private\n to the local module (you are not allowed to pattern match it or directly\n access fields) should use the `@opaque` attribute. Structs whose internal\n structure is public should use `@type`.\n \"\"\"\n defmacro defstruct(kv) do\n fields =\n quote bind_quoted: [fields: kv] do\n fields = :lists.map(fn\n {key, _} = pair when is_atom(key) -> pair\n key when is_atom(key) -> {key, nil}\n other -> raise ArgumentError, \"struct field names must be atoms, got: #{inspect other}\"\n end, fields)\n\n @struct :maps.put(:__struct__, __MODULE__, :maps.from_list(fields))\n\n case Module.get_attribute(__MODULE__, :derive) do\n [] ->\n :ok\n derive ->\n Protocol.__derive__(derive, __MODULE__, __ENV__)\n end\n\n @spec __struct__() :: %__MODULE__{}\n def __struct__() do\n @struct\n end\n end\n\n quote do\n unquote(fields)\n fields\n end\n end\n\n @doc ~S\"\"\"\n Defines an exception.\n\n Exceptions are structs backed by a module that implements\n the Exception behaviour. The Exception behaviour requires\n two functions to be implemented:\n\n * `exception\/1` - that receives the arguments given to `raise\/2`\n and returns the exception struct. The default implementation\n accepts a set of keyword arguments that is merged into the\n struct.\n\n * `message\/1` - receives the exception struct and must return its\n message. Most commonly exceptions have a message field which\n by default is accessed by this function. However, if your exception\n does not have a message field, this function must be explicitly\n implemented.\n\n Since exceptions are structs, all the API supported by `defstruct\/1`\n is also available in `defexception\/1`.\n\n ## Raising exceptions\n\n The most common way to raise an exception is via the `raise\/2`\n function:\n\n defmodule MyAppError do\n defexception [:message]\n end\n\n raise MyAppError,\n message: \"did not get what was expected, got: #{inspect value}\"\n\n In many cases it is more convenient to pass the expected value to\n `raise` and generate the message in the `exception\/1` callback:\n\n defmodule MyAppError do\n defexception [:message]\n\n def exception(value) do\n msg = \"did not get what was expected, got: #{inspect value}\"\n %MyAppError{message: msg}\n end\n end\n\n raise MyAppError, value\n\n The example above is the preferred mechanism for customizing\n exception messages.\n \"\"\"\n defmacro defexception(fields) do\n fields = case is_list(fields) do\n true -> [{:__exception__, true}|fields]\n false -> quote(do: [{:__exception__, true}] ++ unquote(fields))\n end\n\n quote do\n @behaviour Exception\n fields = defstruct unquote(fields)\n\n @spec exception(Keyword.t) :: Exception.t\n def exception(args) when is_list(args) do\n Kernel.struct(__struct__, args)\n end\n\n defoverridable exception: 1\n\n if Keyword.has_key?(fields, :message) do\n @spec message(Exception.t) :: String.t\n def message(exception) do\n exception.message\n end\n\n defoverridable message: 1\n end\n end\n end\n\n @doc \"\"\"\n Defines a protocol.\n\n A protocol specifies an API that should be defined by its\n implementations.\n\n ## Examples\n\n In Elixir, only `false` and `nil` are considered falsy values.\n Everything else evaluates to true in `if` clauses. Depending\n on the application, it may be important to specify a `blank?`\n protocol that returns a boolean for other data types that should\n be considered `blank?`. For instance, an empty list or an empty\n binary could be considered blanks.\n\n We could implement this protocol as follow:\n\n defprotocol Blank do\n @doc \"Returns true if data is considered blank\/empty\"\n def blank?(data)\n end\n\n Now that the protocol is defined, we can implement it. We need\n to implement the protocol for each Elixir type. For example:\n\n # Integers are never blank\n defimpl Blank, for: Integer do\n def blank?(number), do: false\n end\n\n # Just empty list is blank\n defimpl Blank, for: List do\n def blank?([]), do: true\n def blank?(_), do: false\n end\n\n # Just the atoms false and nil are blank\n defimpl Blank, for: Atom do\n def blank?(false), do: true\n def blank?(nil), do: true\n def blank?(_), do: false\n end\n\n And we would have to define the implementation for all types.\n The supported types available are:\n\n * Structs (see below)\n * `Tuple`\n * `Atom`\n * `List`\n * `BitString`\n * `Integer`\n * `Float`\n * `Function`\n * `PID`\n * `Map`\n * `Port`\n * `Reference`\n * `Any` (see below)\n\n ## Protocols + Structs\n\n The real benefit of protocols comes when mixed with structs.\n For instance, Elixir ships with many data types implemented as\n structs, like `HashDict` and `HashSet`. We can implement the\n `Blank` protocol for those types as well:\n\n defimpl Blank, for: [HashDict, HashSet] do\n def blank?(enum_like), do: Enum.empty?(enum_like)\n end\n\n If a protocol is not found for a given type, it will fallback to\n `Any`.\n\n ## Fallback to any\n\n In some cases, it may be convenient to provide a default\n implementation for all types. This can be achieved by\n setting `@fallback_to_any` to `true` in the protocol\n definition:\n\n defprotocol Blank do\n @fallback_to_any true\n def blank?(data)\n end\n\n Which can now be implemented as:\n\n defimpl Blank, for: Any do\n def blank?(_), do: true\n end\n\n One may wonder why such fallback is not true by default.\n\n It is two-fold: first, the majority of protocols cannot\n implement an action in a generic way for all types. In fact,\n providing a default implementation may be harmful, because users\n may rely on the default implementation instead of providing a\n specialized one.\n\n Second, falling back to `Any` adds an extra lookup to all types,\n which is unnecessary overhead unless an implementation for Any is\n required.\n\n ## Types\n\n Defining a protocol automatically defines a type named `t`, which\n can be used as:\n\n @spec present?(Blank.t) :: boolean\n def present?(blank) do\n not Blank.blank?(blank)\n end\n\n The `@spec` above expresses that all types allowed to implement the\n given protocol are valid argument types for the given function.\n\n ## Reflection\n\n Any protocol module contains three extra functions:\n\n\n * `__protocol__\/1` - returns the protocol name when `:name` is given, and a\n keyword list with the protocol functions when `:functions` is given\n\n * `impl_for\/1` - receives a structure and returns the module that\n implements the protocol for the structure, `nil` otherwise\n\n * `impl_for!\/1` - same as above but raises an error if an implementation is\n not found\n\n ## Consolidation\n\n In order to cope with code loading in development, protocols in\n Elixir provide a slow implementation of protocol dispatching specific\n to development.\n\n In order to speed up dispatching in production environments, where\n all implementations are known up-front, Elixir provides a feature\n called protocol consolidation. For this reason, all protocols are\n compiled with `debug_info` set to true, regardless of the option\n set by `elixirc` compiler. The debug info though may be removed\n after consolidation.\n\n For more information on how to apply protocol consolidation to\n a given project, please check the functions in the `Protocol`\n module or the `mix compile.protocols` task.\n \"\"\"\n defmacro defprotocol(name, do: block) do\n Protocol.__protocol__(name, do: block)\n end\n\n @doc \"\"\"\n Defines an implementation for the given protocol. See\n `defprotocol\/2` for examples.\n\n Inside an implementation, the name of the protocol can be accessed\n via `@protocol` and the current target as `@for`.\n \"\"\"\n defmacro defimpl(name, opts, do_block \\\\ []) do\n merged = Keyword.merge(opts, do_block)\n merged = Keyword.put_new(merged, :for, __CALLER__.module)\n Protocol.__impl__(name, merged)\n end\n\n @doc \"\"\"\n Makes the given functions in the current module overridable. An overridable\n function is lazily defined, allowing a developer to customize it.\n\n ## Example\n\n defmodule DefaultMod do\n defmacro __using__(_opts) do\n quote do\n def test(x, y) do\n x + y\n end\n\n defoverridable [test: 2]\n end\n end\n end\n\n defmodule InheritMod do\n use DefaultMod\n\n def test(x, y) do\n x * y + super(x, y)\n end\n end\n\n As seen as in the example `super` can be used to call the default\n implementation.\n \"\"\"\n defmacro defoverridable(tuples) do\n quote do\n Module.make_overridable(__MODULE__, unquote(tuples))\n end\n end\n\n @doc \"\"\"\n `use` is a simple mechanism for using a given module into\n the current context.\n\n ## Examples\n\n For example, in order to write tests using the ExUnit framework,\n a developer should use the `ExUnit.Case` module:\n\n defmodule AssertionTest do\n use ExUnit.Case, async: true\n\n test \"always pass\" do\n assert true\n end\n end\n\n By calling `use`, a hook called `__using__` will be invoked in\n `ExUnit.Case` which will then do the proper setup.\n\n Simply put, `use` is simply a translation to:\n\n defmodule AssertionTest do\n require ExUnit.Case\n ExUnit.Case.__using__([async: true])\n\n test \"always pass\" do\n assert true\n end\n end\n\n \"\"\"\n defmacro use(module, opts \\\\ []) do\n expanded = Macro.expand(module, __CALLER__)\n\n case is_atom(expanded) do\n false ->\n raise ArgumentError, \"invalid arguments for use, expected an atom or alias as argument\"\n true ->\n quote do\n require unquote(expanded)\n unquote(expanded).__using__(unquote(opts))\n end\n end\n end\n\n @doc \"\"\"\n Defines the given functions in the current module that will\n delegate to the given `target`. Functions defined with\n `defdelegate` are public and are allowed to be invoked\n from external. If you find yourself wishing to define a\n delegation as private, you should likely use import\n instead.\n\n Delegation only works with functions, delegating to macros\n is not supported.\n\n ## Options\n\n * `:to` - the expression to delegate to. Any expression\n is allowed and its results will be calculated on runtime.\n\n * `:as` - the function to call on the target given in `:to`.\n This parameter is optional and defaults to the name being\n delegated.\n\n * `:append_first` - if true, when delegated, first argument\n passed to the delegate will be relocated to the end of the\n arguments when dispatched to the target.\n\n The motivation behind this is because Elixir normalizes\n the \"handle\" as a first argument and some Erlang modules\n expect it as last argument.\n\n ## Examples\n\n defmodule MyList do\n defdelegate reverse(list), to: :lists\n defdelegate [reverse(list), map(callback, list)], to: :lists\n defdelegate other_reverse(list), to: :lists, as: :reverse\n end\n\n MyList.reverse([1, 2, 3])\n #=> [3,2,1]\n\n MyList.other_reverse([1, 2, 3])\n #=> [3,2,1]\n\n \"\"\"\n defmacro defdelegate(funs, opts) do\n funs = Macro.escape(funs, unquote: true)\n quote bind_quoted: [funs: funs, opts: opts] do\n target = Keyword.get(opts, :to) ||\n raise ArgumentError, \"Expected to: to be given as argument\"\n\n append_first = Keyword.get(opts, :append_first, false)\n\n for fun <- List.wrap(funs) do\n {name, args} =\n case Macro.decompose_call(fun) do\n {_, _} = pair -> pair\n _ -> raise ArgumentError, \"invalid syntax in defdelegate #{Macro.to_string(fun)}\"\n end\n\n actual_args =\n case append_first and args != [] do\n true -> tl(args) ++ [hd(args)]\n false -> args\n end\n\n fun = Keyword.get(opts, :as, name)\n\n def unquote(name)(unquote_splicing(args)) do\n unquote(target).unquote(fun)(unquote_splicing(actual_args))\n end\n end\n end\n end\n\n ## Sigils\n\n @doc \"\"\"\n Handles the sigil ~S. It simply returns a string\n without escaping characters and without interpolations.\n\n ## Examples\n\n iex> ~S(foo)\n \"foo\"\n\n iex> ~S(f\\#{o}o)\n \"f\\\\\\#{o}o\"\n\n \"\"\"\n defmacro sigil_S(string, []) do\n string\n end\n\n @doc \"\"\"\n Handles the sigil ~s. It returns a string as if it was double quoted\n string, unescaping characters and replacing interpolations.\n\n ## Examples\n\n iex> ~s(foo)\n \"foo\"\n\n iex> ~s(f\\#{:o}o)\n \"foo\"\n\n \"\"\"\n defmacro sigil_s({:<<>>, line, pieces}, []) do\n {:<<>>, line, Macro.unescape_tokens(pieces)}\n end\n\n @doc \"\"\"\n Handles the sigil ~C. It simply returns a char list\n without escaping characters and without interpolations.\n\n ## Examples\n\n iex> ~C(foo)\n 'foo'\n\n iex> ~C(f\\#{o}o)\n 'f\\\\\\#{o}o'\n\n \"\"\"\n defmacro sigil_C({:<<>>, _line, [string]}, []) when is_binary(string) do\n String.to_char_list(string)\n end\n\n @doc \"\"\"\n Handles the sigil ~c. It returns a char list as if it were a single\n quoted string, unescaping characters and replacing interpolations.\n\n ## Examples\n\n iex> ~c(foo)\n 'foo'\n\n iex> ~c(f\\#{:o}o)\n 'foo'\n\n \"\"\"\n\n # We can skip the runtime conversion if we are\n # creating a binary made solely of series of chars.\n defmacro sigil_c({:<<>>, _line, [string]}, []) when is_binary(string) do\n String.to_char_list(Macro.unescape_string(string))\n end\n\n defmacro sigil_c({:<<>>, line, pieces}, []) do\n binary = {:<<>>, line, Macro.unescape_tokens(pieces)}\n quote do: String.to_char_list(unquote(binary))\n end\n\n @doc \"\"\"\n Handles the sigil ~r. It returns a Regex pattern.\n\n ## Examples\n\n iex> Regex.match?(~r(foo), \"foo\")\n true\n\n \"\"\"\n defmacro sigil_r({:<<>>, _line, [string]}, options) when is_binary(string) do\n binary = Macro.unescape_string(string, fn(x) -> Regex.unescape_map(x) end)\n regex = Regex.compile!(binary, :binary.list_to_bin(options))\n Macro.escape(regex)\n end\n\n defmacro sigil_r({:<<>>, line, pieces}, options) do\n binary = {:<<>>, line, Macro.unescape_tokens(pieces, fn(x) -> Regex.unescape_map(x) end)}\n quote do: Regex.compile!(unquote(binary), unquote(:binary.list_to_bin(options)))\n end\n\n @doc \"\"\"\n Handles the sigil ~R. It returns a Regex pattern without escaping\n nor interpreting interpolations.\n\n ## Examples\n\n iex> Regex.match?(~R(f\\#{1,3}o), \"f\\#o\")\n true\n\n \"\"\"\n defmacro sigil_R({:<<>>, _line, [string]}, options) when is_binary(string) do\n regex = Regex.compile!(string, :binary.list_to_bin(options))\n Macro.escape(regex)\n end\n\n @doc \"\"\"\n Handles the sigil ~w. It returns a list of \"words\" split by whitespace.\n\n ## Modifiers\n\n * `s`: strings (default)\n * `a`: atoms\n * `c`: char lists\n\n ## Examples\n\n iex> ~w(foo \\#{:bar} baz)\n [\"foo\", \"bar\", \"baz\"]\n\n iex> ~w(--source test\/enum_test.exs)\n [\"--source\", \"test\/enum_test.exs\"]\n\n iex> ~w(foo bar baz)a\n [:foo, :bar, :baz]\n\n \"\"\"\n\n defmacro sigil_w({:<<>>, _line, [string]}, modifiers) when is_binary(string) do\n split_words(Macro.unescape_string(string), modifiers)\n end\n\n defmacro sigil_w({:<<>>, line, pieces}, modifiers) do\n binary = {:<<>>, line, Macro.unescape_tokens(pieces)}\n split_words(binary, modifiers)\n end\n\n @doc \"\"\"\n Handles the sigil ~W. It returns a list of \"words\" split by whitespace\n without escaping nor interpreting interpolations.\n\n ## Modifiers\n\n * `s`: strings (default)\n * `a`: atoms\n * `c`: char lists\n\n ## Examples\n\n iex> ~W(foo \\#{bar} baz)\n [\"foo\", \"\\\\\\#{bar}\", \"baz\"]\n\n \"\"\"\n defmacro sigil_W({:<<>>, _line, [string]}, modifiers) when is_binary(string) do\n split_words(string, modifiers)\n end\n\n defp split_words(\"\", _modifiers), do: []\n\n defp split_words(string, modifiers) do\n mod =\n case modifiers do\n [] -> ?s\n [mod] when mod == ?s or mod == ?a or mod == ?c -> mod\n _else -> raise ArgumentError, \"modifier must be one of: s, a, c\"\n end\n\n case is_binary(string) do\n true ->\n case mod do\n ?s -> String.split(string)\n ?a -> for p <- String.split(string), do: String.to_atom(p)\n ?c -> for p <- String.split(string), do: String.to_char_list(p)\n end\n false ->\n case mod do\n ?s -> quote do: String.split(unquote(string))\n ?a -> quote do: for(p <- String.split(unquote(string)), do: String.to_atom(p))\n ?c -> quote do: for(p <- String.split(unquote(string)), do: String.to_char_list(p))\n end\n end\n end\n\n ## Shared functions\n\n defp optimize_boolean({:case, meta, args}) do\n {:case, [{:optimize_boolean, true}|meta], args}\n end\n\n # We need this check only for bootstrap purposes.\n # Once Kernel is loaded and we recompile, it is a no-op.\n case :code.ensure_loaded(Kernel) do\n {:module, _} ->\n defp bootstraped?(_), do: true\n {:error, _} ->\n defp bootstraped?(module), do: :code.ensure_loaded(module) == {:module, module}\n end\n\n defp assert_module_scope(env, fun, arity) do\n case env.module do\n nil -> raise ArgumentError, \"cannot invoke #{fun}\/#{arity} outside module\"\n _ -> :ok\n end\n end\n\n defp assert_no_function_scope(env, fun, arity) do\n case env.function do\n nil -> :ok\n _ -> raise ArgumentError, \"cannot invoke #{fun}\/#{arity} inside function\/macro\"\n end\n end\n\n defp env_stacktrace(env) do\n case bootstraped?(Path) do\n true -> Macro.Env.stacktrace(env)\n false -> []\n end\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"5724277da214bf0de82b62fd94891c3f96930813","subject":"Remove appologies.","message":"Remove appologies.\n","repos":"FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os,FarmBot\/farmbot_os","old_file":"lib\/farmbot\/debug_log.ex","new_file":"lib\/farmbot\/debug_log.ex","new_contents":"defmodule Farmbot.DebugLog do\n @moduledoc \"\"\"\n Provides a `debug_log\/1` function.\n \"\"\"\n\n def color(:NC), do: \"\\e[0m\"\n def color(:WHITE), do: \"\\e[1;37m\"\n def color(:BLACK), do: \"\\e[0;30m\"\n def color(:BLUE), do: \"\\e[0;34m\"\n def color(:LIGHT_BLUE), do: \"\\e[1;34m\"\n def color(:GREEN), do: \"\\e[0;32m\"\n def color(:LIGHT_GREEN), do: \"\\e[1;32m\"\n def color(:CYAN), do: \"\\e[0;36m\"\n def color(:LIGHT_CYAN), do: \"\\e[1;36m\"\n def color(:RED), do: \"\\e[0;31m\"\n def color(:LIGHT_RED), do: \"\\e[1;31m\"\n def color(:PURPLE), do: \"\\e[0;35m\"\n def color(:LIGHT_PURPLE), do: \"\\e[1;35m\"\n def color(:BROWN), do: \"\\e[0;33m\"\n def color(:YELLOW), do: \"\\e[1;33m\"\n def color(:GRAY), do: \"\\e[0;30m\"\n def color(:LIGHT_GRAY), do: \"\\e[0;37m\"\n\n @doc \"\"\"\n enables the `debug_log\/1` function.\n \"\"\"\n defmacro __using__(opts) do\n color = Keyword.get(opts, :color)\n name = Keyword.get(opts, :name)\n quote do\n\n if unquote(name) do\n defp get_module, do: unquote(name)\n else\n defp get_module, do: __MODULE__ |> Module.split() |> List.last\n end\n\n if unquote(color) do\n defp debug_log(str) do\n GenEvent.notify(Farmbot.DebugLog,\n {get_module(), {unquote(color), str}})\n end\n else\n defp debug_log(str) do\n GenEvent.notify Farmbot.DebugLog, {Farmbot.DebugLog, {:BLUE, str}}\n end\n end # if color\n\n end # quote\n end # defmacro\n\n defmodule Handler do\n @moduledoc \"\"\"\n Handler for DebugLogger\n \"\"\"\n use GenEvent\n\n @doc false\n defdelegate color(color), to: Farmbot.DebugLog\n\n def init(state), do: {:ok, state}\n\n def handle_event(_, :all), do: {:ok, :all}\n\n def handle_event({module, {color, str}}, state) when is_binary(str) do\n filter_me? = Map.get(state, module)\n unless filter_me? do\n IO.puts \"#{color(color)} [#{module}]#{color(:NC)} #{str}\"\n end\n {:ok, state}\n end\n\n def handle_call({:filter, :all}, _state) do\n {:ok, :all}\n end\n\n def handle_call({:filter, module}, state) do\n {:ok, :ok, Map.put(state, module, :filterme)}\n end\n\n def handle_call({:unfilter, module}, state) do\n if state == :all do\n {:ok, :error, state}\n else\n {:ok, :ok, Map.delete(state, module)}\n end\n end\n end\n\n @doc \"\"\"\n Start the Debug Logger\n \"\"\"\n def start_link do\n {:ok, pid} = GenEvent.start_link(name: __MODULE__)\n :ok = GenEvent.add_handler(pid, Handler, %{})\n {:ok, pid}\n end\n\n @doc \"\"\"\n Filter a module from the handler.\n \"\"\"\n def filter(module) do\n GenEvent.call(__MODULE__, Handler, {:filter, module})\n end\n\n @doc \"\"\"\n Unfilter a module from the handler.\n \"\"\"\n def unfilter(module) do\n GenEvent.call(__MODULE__, Handler, {:unfilter, module})\n end\nend # defmodule\n","old_contents":"defmodule Farmbot.DebugLog do\n @moduledoc \"\"\"\n Provides a `debug_log\/1` function.\n \"\"\"\n\n def color(:NC), do: \"\\e[0m\"\n def color(:WHITE), do: \"\\e[1;37m\"\n def color(:BLACK), do: \"\\e[0;30m\"\n def color(:BLUE), do: \"\\e[0;34m\"\n def color(:LIGHT_BLUE), do: \"\\e[1;34m\"\n def color(:GREEN), do: \"\\e[0;32m\"\n def color(:LIGHT_GREEN), do: \"\\e[1;32m\"\n def color(:CYAN), do: \"\\e[0;36m\"\n def color(:LIGHT_CYAN), do: \"\\e[1;36m\"\n def color(:RED), do: \"\\e[0;31m\"\n def color(:LIGHT_RED), do: \"\\e[1;31m\"\n def color(:PURPLE), do: \"\\e[0;35m\"\n def color(:LIGHT_PURPLE), do: \"\\e[1;35m\"\n def color(:BROWN), do: \"\\e[0;33m\"\n def color(:YELLOW), do: \"\\e[1;33m\"\n def color(:GRAY), do: \"\\e[0;30m\"\n def color(:LIGHT_GRAY), do: \"\\e[0;37m\"\n\n @doc \"\"\"\n enables the `debug_log\/1` function.\n \"\"\"\n defmacro __using__(opts) do\n color = Keyword.get(opts, :color)\n name = Keyword.get(opts, :name)\n quote do\n\n if unquote(name) do\n defp get_module, do: unquote(name)\n else\n defp get_module, do: __MODULE__ |> Module.split() |> List.last\n end\n\n if unquote(color) do\n defp debug_log(str) do\n GenEvent.notify(Farmbot.DebugLog,\n {get_module(), {unquote(color), str}})\n end\n else\n defp debug_log(str) do\n IO.puts \"Stubbed out. Sorry. - RC\"\n # GenEvent.notify Farmbot.DebugLog, {Farmbot.DebugLog, {:BLUE, str}}\n end\n end # if color\n\n end # quote\n end # defmacro\n\n defmodule Handler do\n @moduledoc \"\"\"\n Handler for DebugLogger\n \"\"\"\n use GenEvent\n\n @doc false\n defdelegate color(color), to: Farmbot.DebugLog\n\n def init(state), do: {:ok, state}\n\n def handle_event(_, :all), do: {:ok, :all}\n\n def handle_event({module, {color, str}}, state) when is_binary(str) do\n filter_me? = Map.get(state, module)\n unless filter_me? do\n IO.puts \"#{color(color)} [#{module}]#{color(:NC)} #{str}\"\n end\n {:ok, state}\n end\n\n def handle_call({:filter, :all}, _state) do\n {:ok, :all}\n end\n\n def handle_call({:filter, module}, state) do\n {:ok, :ok, Map.put(state, module, :filterme)}\n end\n\n def handle_call({:unfilter, module}, state) do\n if state == :all do\n {:ok, :error, state}\n else\n {:ok, :ok, Map.delete(state, module)}\n end\n end\n end\n\n @doc \"\"\"\n Start the Debug Logger\n \"\"\"\n def start_link do\n {:ok, pid} = GenEvent.start_link(name: __MODULE__)\n :ok = GenEvent.add_handler(pid, Handler, %{})\n {:ok, pid}\n end\n\n @doc \"\"\"\n Filter a module from the handler.\n \"\"\"\n def filter(module) do\n GenEvent.call(__MODULE__, Handler, {:filter, module})\n end\n\n @doc \"\"\"\n Unfilter a module from the handler.\n \"\"\"\n def unfilter(module) do\n GenEvent.call(__MODULE__, Handler, {:unfilter, module})\n end\nend # defmodule\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"d7df6d20a7ebcff9b642f715d8e113d88a041aa3","subject":"Fix pruning IEx stacktraces too aggressively","message":"Fix pruning IEx stacktraces too aggressively\n","repos":"kelvinst\/elixir,antipax\/elixir,kimshrier\/elixir,pedrosnk\/elixir,beedub\/elixir,joshprice\/elixir,gfvcastro\/elixir,ggcampinho\/elixir,kimshrier\/elixir,beedub\/elixir,lexmag\/elixir,michalmuskala\/elixir,elixir-lang\/elixir,antipax\/elixir,kelvinst\/elixir,lexmag\/elixir,ggcampinho\/elixir,pedrosnk\/elixir,gfvcastro\/elixir","old_file":"lib\/iex\/lib\/iex\/evaluator.ex","new_file":"lib\/iex\/lib\/iex\/evaluator.ex","new_contents":"defmodule IEx.Evaluator do\n @moduledoc false\n\n @doc \"\"\"\n Eval loop for an IEx session. Its responsibilities include:\n\n * loading of .iex files\n * evaluating code\n * trapping exceptions in the code being evaluated\n * keeping expression history\n\n \"\"\"\n def start(server, leader) do\n IEx.History.init\n old_leader = Process.group_leader\n old_flag = Process.flag(:trap_exit, true)\n Process.group_leader(self, leader)\n\n try do\n loop(server)\n after\n IEx.History.reset\n Process.group_leader(self, old_leader)\n Process.flag(:trap_exit, old_flag)\n end\n end\n\n defp loop(server) do\n receive do\n {:eval, ^server, code, config} ->\n send server, {:evaled, self, eval(code, config)}\n loop(server)\n {:done, ^server} ->\n IEx.History.reset\n :ok\n\n {:EXIT, _other, :normal} ->\n loop(server)\n {:EXIT, other, reason} ->\n print_exit(other, reason)\n loop(server)\n end\n end\n\n @doc \"\"\"\n Locates and loads an .iex.exs file from one of predefined locations.\n Returns the new config.\n \"\"\"\n def load_dot_iex(config, path \\\\ nil) do\n candidates = if path do\n [path]\n else\n Enum.map [\".iex.exs\", \"~\/.iex.exs\"], &Path.expand\/1\n end\n\n path = Enum.find candidates, &File.regular?\/1\n\n if nil?(path) do\n config\n else\n eval_dot_iex(config, path)\n end\n end\n\n defp eval_dot_iex(config, path) do\n try do\n code = File.read!(path)\n env = :elixir.env_for_eval(config.env, file: path)\n\n # Evaluate the contents in the same environment server_loop will run in\n {_result, binding, env, _scope} =\n :elixir.eval(List.from_char_data!(code), config.binding, env)\n\n %{config | binding: binding, env: :elixir.env_for_eval(env, file: \"iex\")}\n catch\n kind, error ->\n print_error(kind, error, System.stacktrace)\n System.halt(1)\n end\n end\n\n # Instead of doing just `:elixir.eval`, we first parse the expression to see\n # if it's well formed. If parsing succeeds, we evaluate the AST as usual.\n #\n # If parsing fails, this might be a TokenMissingError which we treat in\n # a special way (to allow for continuation of an expression on the next\n # line in IEx). In case of any other error, we let :elixir_translator\n # to re-raise it.\n #\n # Returns updated config.\n #\n # The first two clauses provide support for the break-trigger allowing to\n # break out from a pending incomplete expression. See\n # https:\/\/github.com\/elixir-lang\/elixir\/issues\/1089 for discussion.\n @break_trigger '#iex:break\\n'\n\n defp eval(code, config) do\n try do\n do_eval(List.from_char_data!(code), config)\n catch\n kind, error ->\n print_error(kind, error, System.stacktrace)\n %{config | cache: ''}\n end\n end\n\n defp do_eval(@break_trigger, config=%IEx.Config{cache: ''}) do\n config\n end\n\n defp do_eval(@break_trigger, config) do\n :elixir_errors.parse_error(config.counter, \"iex\", \"incomplete expression\", \"\")\n end\n\n defp do_eval(latest_input, config) do\n code = config.cache ++ latest_input\n line = config.counter\n\n case Code.string_to_quoted(code, [line: line, file: \"iex\"]) do\n {:ok, forms} ->\n {result, new_binding, env, scope} =\n :elixir.eval_forms(forms, config.binding, config.env, config.scope)\n unless result == IEx.dont_display_result, do: io_put result\n update_history(line, code, result)\n %{config | env: env,\n cache: '',\n scope: scope,\n binding: new_binding,\n counter: config.counter + 1}\n {:error, {line, error, token}} ->\n if token == \"\" do\n # Update config.cache so that IEx continues to add new input to\n # the unfinished expression in `code`\n %{config | cache: code}\n else\n # Encountered malformed expression\n :elixir_errors.parse_error(line, \"iex\", error, token)\n end\n end\n end\n\n defp update_history(counter, cache, result) do\n IEx.History.append({counter, cache, result}, counter, IEx.Options.get(:history_size))\n end\n\n defp io_put(result) do\n IO.puts :stdio, IEx.color(:eval_result, inspect(result, inspect_opts))\n end\n\n defp io_error(result) do\n IO.puts :stdio, IEx.color(:eval_error, result)\n end\n\n defp inspect_opts do\n [width: IEx.width] ++ IEx.Options.get(:inspect)\n end\n\n ## Error handling\n\n defp print_error(:error, exception, stacktrace) do\n {exception, stacktrace} = normalize_exception(exception, stacktrace)\n print_stacktrace stacktrace, fn ->\n \"** (#{inspect exception.__record__(:name)}) #{exception.message}\"\n end\n end\n\n defp print_error(kind, reason, stacktrace) do\n print_stacktrace stacktrace, fn ->\n \"** (#{kind}) #{inspect(reason)}\"\n end\n end\n\n defp print_exit(pid, reason) do\n io_error \"** (EXIT from #{inspect pid}) #{inspect(reason)}\"\n end\n\n defp normalize_exception(:undef, [{IEx.Helpers, fun, arity, _}|t]) do\n {RuntimeError[message: \"undefined function: #{format_function(fun, arity)}\"], t}\n end\n\n defp normalize_exception(exception, stacktrace) do\n {Exception.normalize(:error, exception), stacktrace}\n end\n\n defp format_function(fun, arity) do\n cond do\n is_list(arity) ->\n \"#{fun}\/#{length(arity)}\"\n true ->\n \"#{fun}\/#{arity}\"\n end\n end\n\n defp print_stacktrace(trace, callback) do\n try do\n io_error callback.()\n case prune_stacktrace(trace) do\n [] -> :ok\n other -> IO.puts(format_stacktrace(other))\n end\n catch\n type, detail ->\n io_error \"** (IEx.Error) #{type} when printing exception message and stacktrace: #{inspect detail, records: false}\"\n end\n end\n\n defp prune_stacktrace(stacktrace) do\n stacktrace\n |> Enum.reverse()\n |> Enum.drop_while(&(elem(&1, 0) == __MODULE__))\n |> Enum.drop_while(&(elem(&1, 0) == :elixir))\n |> Enum.drop_while(&(elem(&1, 0) in [:erl_eval, :eval_bits]))\n |> Enum.reverse()\n end\n\n @doc false\n def format_stacktrace(trace) do\n entries =\n for entry <- trace do\n split_entry(Exception.format_stacktrace_entry(entry))\n end\n\n width = Enum.reduce entries, 0, fn {app, _}, acc ->\n max(String.length(app), acc)\n end\n\n \" \" <> Enum.map_join(entries, \"\\n \", &format_entry(&1, width))\n end\n\n defp split_entry(entry) do\n case entry do\n \"(\" <> _ ->\n case :binary.split(entry, \") \") do\n [left, right] -> {left <> \")\", right}\n _ -> {\"\", entry}\n end\n _ ->\n {\"\", entry}\n end\n end\n\n defp format_entry({app, info}, width) do\n app = String.rjust(app, width)\n \"#{IEx.color(:stack_app, app)} #{IEx.color(:stack_info, info)}\"\n end\nend\n","old_contents":"defmodule IEx.Evaluator do\n @moduledoc false\n\n @doc \"\"\"\n Eval loop for an IEx session. Its responsibilities include:\n\n * loading of .iex files\n * evaluating code\n * trapping exceptions in the code being evaluated\n * keeping expression history\n\n \"\"\"\n def start(server, leader) do\n IEx.History.init\n old_leader = Process.group_leader\n old_flag = Process.flag(:trap_exit, true)\n Process.group_leader(self, leader)\n\n try do\n loop(server)\n after\n IEx.History.reset\n Process.group_leader(self, old_leader)\n Process.flag(:trap_exit, old_flag)\n end\n end\n\n defp loop(server) do\n receive do\n {:eval, ^server, code, config} ->\n send server, {:evaled, self, eval(code, config)}\n loop(server)\n {:done, ^server} ->\n IEx.History.reset\n :ok\n\n {:EXIT, _other, :normal} ->\n loop(server)\n {:EXIT, other, reason} ->\n print_exit(other, reason)\n loop(server)\n end\n end\n\n @doc \"\"\"\n Locates and loads an .iex.exs file from one of predefined locations.\n Returns the new config.\n \"\"\"\n def load_dot_iex(config, path \\\\ nil) do\n candidates = if path do\n [path]\n else\n Enum.map [\".iex.exs\", \"~\/.iex.exs\"], &Path.expand\/1\n end\n\n path = Enum.find candidates, &File.regular?\/1\n\n if nil?(path) do\n config\n else\n eval_dot_iex(config, path)\n end\n end\n\n defp eval_dot_iex(config, path) do\n try do\n code = File.read!(path)\n env = :elixir.env_for_eval(config.env, file: path)\n\n # Evaluate the contents in the same environment server_loop will run in\n {_result, binding, env, _scope} =\n :elixir.eval(List.from_char_data!(code), config.binding, env)\n\n %{config | binding: binding, env: :elixir.env_for_eval(env, file: \"iex\")}\n catch\n kind, error ->\n print_error(kind, error, System.stacktrace)\n System.halt(1)\n end\n end\n\n # Instead of doing just `:elixir.eval`, we first parse the expression to see\n # if it's well formed. If parsing succeeds, we evaluate the AST as usual.\n #\n # If parsing fails, this might be a TokenMissingError which we treat in\n # a special way (to allow for continuation of an expression on the next\n # line in IEx). In case of any other error, we let :elixir_translator\n # to re-raise it.\n #\n # Returns updated config.\n #\n # The first two clauses provide support for the break-trigger allowing to\n # break out from a pending incomplete expression. See\n # https:\/\/github.com\/elixir-lang\/elixir\/issues\/1089 for discussion.\n @break_trigger '#iex:break\\n'\n\n defp eval(code, config) do\n try do\n do_eval(List.from_char_data!(code), config)\n catch\n kind, error ->\n print_error(kind, error, System.stacktrace)\n %{config | cache: ''}\n end\n end\n\n defp do_eval(@break_trigger, config=%IEx.Config{cache: ''}) do\n config\n end\n\n defp do_eval(@break_trigger, config) do\n :elixir_errors.parse_error(config.counter, \"iex\", \"incomplete expression\", \"\")\n end\n\n defp do_eval(latest_input, config) do\n code = config.cache ++ latest_input\n line = config.counter\n\n case Code.string_to_quoted(code, [line: line, file: \"iex\"]) do\n {:ok, forms} ->\n {result, new_binding, env, scope} =\n :elixir.eval_forms(forms, config.binding, config.env, config.scope)\n unless result == IEx.dont_display_result, do: io_put result\n update_history(line, code, result)\n %{config | env: env,\n cache: '',\n scope: scope,\n binding: new_binding,\n counter: config.counter + 1}\n {:error, {line, error, token}} ->\n if token == \"\" do\n # Update config.cache so that IEx continues to add new input to\n # the unfinished expression in `code`\n %{config | cache: code}\n else\n # Encountered malformed expression\n :elixir_errors.parse_error(line, \"iex\", error, token)\n end\n end\n end\n\n defp update_history(counter, cache, result) do\n IEx.History.append({counter, cache, result}, counter, IEx.Options.get(:history_size))\n end\n\n defp io_put(result) do\n IO.puts :stdio, IEx.color(:eval_result, inspect(result, inspect_opts))\n end\n\n defp io_error(result) do\n IO.puts :stdio, IEx.color(:eval_error, result)\n end\n\n defp inspect_opts do\n [width: IEx.width] ++ IEx.Options.get(:inspect)\n end\n\n ## Error handling\n\n defp print_error(:error, exception, stacktrace) do\n {exception, stacktrace} = normalize_exception(exception, stacktrace)\n print_stacktrace stacktrace, fn ->\n \"** (#{inspect exception.__record__(:name)}) #{exception.message}\"\n end\n end\n\n defp print_error(kind, reason, stacktrace) do\n print_stacktrace stacktrace, fn ->\n \"** (#{kind}) #{inspect(reason)}\"\n end\n end\n\n defp print_exit(pid, reason) do\n io_error \"** (EXIT from #{inspect pid}) #{inspect(reason)}\"\n end\n\n defp normalize_exception(:undef, [{IEx.Helpers, fun, arity, _}|t]) do\n {RuntimeError[message: \"undefined function: #{format_function(fun, arity)}\"], t}\n end\n\n defp normalize_exception(exception, stacktrace) do\n {Exception.normalize(:error, exception), stacktrace}\n end\n\n defp format_function(fun, arity) do\n cond do\n is_list(arity) ->\n \"#{fun}\/#{length(arity)}\"\n true ->\n \"#{fun}\/#{arity}\"\n end\n end\n\n defp print_stacktrace(trace, callback) do\n try do\n io_error callback.()\n case prune_stacktrace(trace) do\n [] -> :ok\n other -> IO.puts(format_stacktrace(other))\n end\n catch\n type, detail ->\n io_error \"** (IEx.Error) #{type} when printing exception message and stacktrace: #{inspect detail, records: false}\"\n end\n end\n\n defp prune_stacktrace([{:erl_eval, _, _, _}|_]), do: []\n defp prune_stacktrace([{__MODULE__, _, _, _}|_]), do: []\n defp prune_stacktrace([h|t]), do: [h|prune_stacktrace(t)]\n defp prune_stacktrace([]), do: []\n\n @doc false\n def format_stacktrace(trace) do\n entries =\n for entry <- trace do\n split_entry(Exception.format_stacktrace_entry(entry))\n end\n\n width = Enum.reduce entries, 0, fn {app, _}, acc ->\n max(String.length(app), acc)\n end\n\n \" \" <> Enum.map_join(entries, \"\\n \", &format_entry(&1, width))\n end\n\n defp split_entry(entry) do\n case entry do\n \"(\" <> _ ->\n case :binary.split(entry, \") \") do\n [left, right] -> {left <> \")\", right}\n _ -> {\"\", entry}\n end\n _ ->\n {\"\", entry}\n end\n end\n\n defp format_entry({app, info}, width) do\n app = String.rjust(app, width)\n \"#{IEx.color(:stack_app, app)} #{IEx.color(:stack_info, info)}\"\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"1f57c74412ccec450a28432f2685d33658bf9e45","subject":"fix proxy","message":"fix proxy\n","repos":"KazuCocoa\/http_proxy","old_file":"lib\/http_proxy\/handle.ex","new_file":"lib\/http_proxy\/handle.ex","new_contents":"defmodule HttpProxy.Handle do\n @moduledoc \"\"\"\n Handle every http request to outside of the server.\n \"\"\"\n\n use Plug.Builder\n import Plug.Conn\n require Logger\n\n alias HttpProxy.Play.Data, as: Data\n alias HttpProxy.Record.Response, as: Record\n alias HttpProxy.Play.Response, as: Play\n\n @default_schemes [:http, :https]\n\n plug Plug.Logger\n plug :dispatch\n\n # Same as Plug.Conn https:\/\/github.com\/elixir-lang\/plug\/blob\/576c04c2cba778f1ac9ca28aa71c50efa1046b50\/lib\/plug\/conn.ex#L125\n @type t :: %Plug.Conn{}\n\n @type param :: binary | [param]\n\n @doc \"\"\"\n Start Cowboy http process with localhost and arbitrary port.\n Clients access to local Cowboy process with HTTP potocol.\n \"\"\"\n @spec start_link([binary]) :: pid\n def start_link([proxy, module_name]) do\n Logger.info \"Running Proxy with Cowboy on http:\/\/localhost:#{proxy.port} named #{module_name}\"\n Plug.Adapters.Cowboy.http(__MODULE__, [], [port: proxy.port, ref: String.to_atom(module_name)])\n end\n\n @doc \"\"\"\n Dispatch connection and Play\/Record http\/https requests.\n \"\"\"\n @spec dispatch(t, param) :: t\n def dispatch(conn, _opts) do\n {:ok, client} = String.downcase(conn.method)\n |> String.to_atom\n |> :hackney.request(uri(conn), conn.req_headers, :stream, [])\n conn\n |> write_proxy(client)\n |> read_proxy(client)\n end\n\n @spec uri(t) :: String.t\n def uri(conn) do\n base = gen_path conn, target_proxy(conn)\n case conn.query_string do\n \"\" -> base\n query_string -> ~s(#{base}?#{query_string})\n end\n end\n\n @doc ~S\"\"\"\n Get proxy defined in config\/config.exs\n\n ## Example\n\n iex> HttpProxy.Handle.proxies\n [%{port: 8080, to: \"http:\/\/google.com\"}, %{port: 8081, to: \"http:\/\/neko.com\"}]\n \"\"\"\n @spec proxies() :: []\n def proxies do\n Application.get_env :http_proxy, :proxies, nil\n end\n\n @doc ~S\"\"\"\n Get schemes which is defined as deault.\n\n ## Example\n\n iex> HttpProxy.Handle.schemes\n [:http, :https]\n \"\"\"\n @spec schemes() :: []\n def schemes do\n @default_schemes\n end\n\n defp write_proxy(conn, client) do\n case read_body(conn, []) do\n {:ok, body, conn} ->\n :hackney.send_body client, body\n conn\n {:more, body, conn} ->\n :hackney.send_body client, body\n write_proxy conn, client\n end\n end\n\n defp read_proxy(conn, client) do\n {:ok, status, headers, client} = :hackney.start_response client\n {:ok, body} = :hackney.body client\n\n headers = List.keydelete headers, \"Transfer-Encoding\", 0\n\n cond do\n Record.record? && Play.play? ->\n raise ArgumentError, \"Can't set record and play at the same time.\"\n Play.play? ->\n %{conn | resp_headers: headers}\n |> play_conn\n Record.record? ->\n %{conn | resp_headers: headers}\n |> send_resp(status, body)\n |> Record.record\n true ->\n %{conn | resp_headers: headers}\n |> send_resp(status, body)\n end\n end\n\n defp play_conn(conn) do\n key = String.downcase(conn.method) <> \"_\" <> Integer.to_string(conn.port) <> conn.request_path\n\n # TODO: do matching with string ot regex\n # \u3053\u3053\u3067\u30d1\u30bf\u30fc\u30f3\u30de\u30c3\u30c1\u304b\u3001\u5b8c\u5168\u4e00\u81f4\u3067path\u3092\u632f\u308a\u5206\u3051\u308b\n case Keyword.get(%Data{}.responses, String.to_atom(key)) do\n {_, resp} ->\n res_json = Map.fetch!(resp, \"response\")\n response = [\n \"body\": Map.fetch!(res_json, \"body\"),\n \"cookies\": Map.to_list(Map.fetch!(res_json, \"cookies\")),\n \"headers\": Map.to_list(Map.fetch!(res_json, \"headers\"))\n |> List.insert_at(0, {\"Date\", conn.resp_headers[\"Date\"]}),\n \"status_code\": Map.fetch!(res_json, \"status_code\")\n ]\n\n conn = %{conn | resp_body: response[:body] }\n conn = %{conn | resp_cookies: response[:cookies] }\n conn = %{conn | status: response[:status_code] }\n conn = %{conn | resp_headers: response[:headers] }\n nil ->\n conn = %{conn | resp_body: \"not found nil play_conn case<\/html>\" }\n conn = %{conn | status: 404 }\n conn = %{conn | resp_cookies: [] }\n conn = %{conn | resp_headers: [] }\n end\n\n send_resp conn, conn.status, conn.resp_body\n end\n\n defp gen_path(conn, proxy) when proxy == nil do\n case conn.scheme do\n s when s in @default_schemes ->\n uri = %URI{}\n %URI{uri | scheme: Atom.to_string(conn.scheme), host: conn.host, path: conn.request_path}\n |> URI.to_string\n _ ->\n raise ArgumentError, \"no scheme\"\n end\n end\n defp gen_path(conn, proxy) do\n uri = URI.parse proxy.to\n %URI{uri | path: conn.request_path}\n |> URI.to_string\n end\n\n defp target_proxy(conn) do\n Enum.reduce(proxies, [], fn proxy, acc ->\n cond do\n proxy.port == conn.port ->\n [proxy | acc]\n true ->\n acc\n end\n end)\n |> Enum.at(0)\n end\nend\n","old_contents":"defmodule HttpProxy.Handle do\n @moduledoc \"\"\"\n Handle every http request to outside of the server.\n \"\"\"\n\n use Plug.Builder\n import Plug.Conn\n require Logger\n\n alias HttpProxy.Play.Data, as: Data\n alias HttpProxy.Record.Response, as: Record\n alias HttpProxy.Play.Response, as: Play\n\n @default_schemes [:http, :https]\n\n plug Plug.Logger\n plug :dispatch\n\n # Same as Plug.Conn https:\/\/github.com\/elixir-lang\/plug\/blob\/576c04c2cba778f1ac9ca28aa71c50efa1046b50\/lib\/plug\/conn.ex#L125\n @type t :: %Plug.Conn{}\n\n @type param :: binary | [param]\n\n @doc \"\"\"\n Start Cowboy http process with localhost and arbitrary port.\n Clients access to local Cowboy process with HTTP potocol.\n \"\"\"\n @spec start_link([binary]) :: pid\n def start_link([proxy, module_name]) do\n Logger.info \"Running Proxy with Cowboy on http:\/\/localhost:#{proxy.port} named #{module_name}\"\n Plug.Adapters.Cowboy.http(__MODULE__, [], [port: proxy.port, ref: String.to_atom(module_name)])\n end\n\n @doc \"\"\"\n Dispatch connection and Play\/Record http\/https requests.\n \"\"\"\n @spec dispatch(t, param) :: t\n def dispatch(conn, _opts) do\n {:ok, client} = String.downcase(conn.method)\n |> String.to_atom\n |> :hackney.request(uri(conn), conn.req_headers, :stream, [])\n conn\n |> write_proxy(client)\n |> read_proxy(client)\n end\n\n @spec uri(t) :: String.t\n def uri(conn) do\n base = gen_path conn, target_proxy(conn)\n case conn.query_string do\n \"\" -> base\n query_string -> ~s(#{base}?#{query_string})\n end\n end\n\n @doc ~S\"\"\"\n Get proxy defined in config\/config.exs\n\n ## Example\n\n iex> HttpProxy.Handle.proxies\n [%{port: 8080, to: \"http:\/\/google.com\"}, %{port: 8081, to: \"http:\/\/neko.com\"}]\n \"\"\"\n @spec proxies() :: []\n def proxies do\n Application.get_env :http_proxy, :proxies, nil\n end\n\n @doc ~S\"\"\"\n Get schemes which is defined as deault.\n\n ## Example\n\n iex> HttpProxy.Handle.schemes\n [:http, :https]\n \"\"\"\n @spec schemes() :: []\n def schemes do\n @default_schemes\n end\n\n defp write_proxy(conn, client) do\n case read_body(conn, []) do\n {:ok, body, conn} ->\n :hackney.send_body client, body\n conn\n {:more, body, conn} ->\n :hackney.send_body client, body\n write_proxy conn, client\n end\n end\n\n defp read_proxy(conn, client) do\n {:ok, status, headers, client} = :hackney.start_response client\n {:ok, body} = :hackney.body client\n\n headers = List.keydelete headers, \"Transfer-Encoding\", 0\n\n cond do\n Record.record? && Play.play? ->\n raise ArgumentError, \"Can't set record and play at the same time.\"\n Play.play? ->\n %{conn | resp_headers: headers}\n |> play_conn\n Record.record? ->\n %{conn | resp_headers: headers}\n |> send_resp(status, body)\n |> Record.record\n true ->\n conn\n end\n end\n\n defp play_conn(conn) do\n key = String.downcase(conn.method) <> \"_\" <> Integer.to_string(conn.port) <> conn.request_path\n\n # TODO: do matching with string ot regex\n # \u3053\u3053\u3067\u30d1\u30bf\u30fc\u30f3\u30de\u30c3\u30c1\u304b\u3001\u5b8c\u5168\u4e00\u81f4\u3067path\u3092\u632f\u308a\u5206\u3051\u308b\n case Keyword.get(%Data{}.responses, String.to_atom(key)) do\n {_, resp} ->\n res_json = Map.fetch!(resp, \"response\")\n response = [\n \"body\": Map.fetch!(res_json, \"body\"),\n \"cookies\": Map.to_list(Map.fetch!(res_json, \"cookies\")),\n \"headers\": Map.to_list(Map.fetch!(res_json, \"headers\"))\n |> List.insert_at(0, {\"Date\", conn.resp_headers[\"Date\"]}),\n \"status_code\": Map.fetch!(res_json, \"status_code\")\n ]\n\n conn = %{conn | resp_body: response[:body] }\n conn = %{conn | resp_cookies: response[:cookies] }\n conn = %{conn | status: response[:status_code] }\n conn = %{conn | resp_headers: response[:headers] }\n nil ->\n conn = %{conn | resp_body: \"not found nil play_conn case<\/html>\" }\n conn = %{conn | status: 404 }\n conn = %{conn | resp_cookies: [] }\n conn = %{conn | resp_headers: [] }\n end\n\n send_resp conn, conn.status, conn.resp_body\n end\n\n defp gen_path(conn, proxy) when proxy == nil do\n case conn.scheme do\n s when s in @default_schemes ->\n uri = %URI{}\n %URI{uri | scheme: Atom.to_string(conn.scheme), host: conn.host, path: conn.request_path}\n |> URI.to_string\n _ ->\n raise ArgumentError, \"no scheme\"\n end\n end\n defp gen_path(conn, proxy) do\n uri = URI.parse proxy.to\n %URI{uri | path: conn.request_path}\n |> URI.to_string\n end\n\n defp target_proxy(conn) do\n Enum.reduce(proxies, [], fn proxy, acc ->\n cond do\n proxy.port == conn.port ->\n [proxy | acc]\n true ->\n acc\n end\n end)\n |> Enum.at(0)\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"df207b9c37dcc127d16aa76fa39bb7430cf029f0","subject":"Enable gzip on statics. Fix #44","message":"Enable gzip on statics. Fix #44","repos":"Nagasaki45\/krihelinator,Nagasaki45\/krihelinator,Nagasaki45\/krihelinator,Nagasaki45\/krihelinator","old_file":"lib\/krihelinator\/endpoint.ex","new_file":"lib\/krihelinator\/endpoint.ex","new_contents":"defmodule Krihelinator.Endpoint do\n use Phoenix.Endpoint, otp_app: :krihelinator\n\n socket \"\/socket\", Krihelinator.UserSocket\n\n # Serve at \"\/\" the static files from \"priv\/static\" directory.\n #\n # You should set gzip to true if you are running phoenix.digest\n # when deploying your static files in production.\n plug Plug.Static,\n at: \"\/\", from: :krihelinator, gzip: true,\n only: ~w(css fonts images js favicon.ico robots.txt)\n\n # Code reloading can be explicitly enabled under the\n # :code_reloader configuration of your endpoint.\n if code_reloading? do\n socket \"\/phoenix\/live_reload\/socket\", Phoenix.LiveReloader.Socket\n plug Phoenix.LiveReloader\n plug Phoenix.CodeReloader\n end\n\n plug Plug.RequestId\n plug Plug.Logger\n\n plug Plug.Parsers,\n parsers: [:urlencoded, :multipart, :json],\n pass: [\"*\/*\"],\n json_decoder: Poison\n\n plug Plug.MethodOverride\n plug Plug.Head\n\n # The session will be stored in the cookie and signed,\n # this means its contents can be read but not tampered with.\n # Set :encryption_salt if you would also like to encrypt it.\n plug Plug.Session,\n store: :cookie,\n key: \"_krihelinator_key\",\n signing_salt: \"lZoUI4Gb\"\n\n plug Krihelinator.Router\nend\n","old_contents":"defmodule Krihelinator.Endpoint do\n use Phoenix.Endpoint, otp_app: :krihelinator\n\n socket \"\/socket\", Krihelinator.UserSocket\n\n # Serve at \"\/\" the static files from \"priv\/static\" directory.\n #\n # You should set gzip to true if you are running phoenix.digest\n # when deploying your static files in production.\n plug Plug.Static,\n at: \"\/\", from: :krihelinator, gzip: false,\n only: ~w(css fonts images js favicon.ico robots.txt)\n\n # Code reloading can be explicitly enabled under the\n # :code_reloader configuration of your endpoint.\n if code_reloading? do\n socket \"\/phoenix\/live_reload\/socket\", Phoenix.LiveReloader.Socket\n plug Phoenix.LiveReloader\n plug Phoenix.CodeReloader\n end\n\n plug Plug.RequestId\n plug Plug.Logger\n\n plug Plug.Parsers,\n parsers: [:urlencoded, :multipart, :json],\n pass: [\"*\/*\"],\n json_decoder: Poison\n\n plug Plug.MethodOverride\n plug Plug.Head\n\n # The session will be stored in the cookie and signed,\n # this means its contents can be read but not tampered with.\n # Set :encryption_salt if you would also like to encrypt it.\n plug Plug.Session,\n store: :cookie,\n key: \"_krihelinator_key\",\n signing_salt: \"lZoUI4Gb\"\n\n plug Krihelinator.Router\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"a95dd5b493a9d10e670a96191d84461e4b76c2ae","subject":"Add some comments to MarcoPolo.Connection","message":"Add some comments to MarcoPolo.Connection\n\nI commented what each field in the connection's state does. You can\nnever be too explicit.\n","repos":"MyMedsAndMe\/marco_polo","old_file":"lib\/marco_polo\/connection.ex","new_file":"lib\/marco_polo\/connection.ex","new_contents":"defmodule MarcoPolo.Connection do\n @moduledoc false\n\n use Connection\n\n require Logger\n\n alias MarcoPolo.Connection.Auth\n alias MarcoPolo.Protocol\n alias MarcoPolo.Document\n alias MarcoPolo.Error\n\n @socket_opts [:binary, active: false, packet: :raw]\n\n @timeout 5000\n\n @initial_state %{\n # The TCP socket to the OrientDB server\n socket: nil,\n # The session id for the session held by this genserver\n session_id: nil,\n # The queue of commands sent to the server\n queue: :queue.new,\n # The schema of the OrientDB database (if we're connected to a db)\n schema: nil,\n # The tail of binary data from parsing\n tail: \"\",\n # A monothonically increasing transaction id (must be unique per session)\n transaction_id: 1,\n # The options used to start this genserver\n opts: nil,\n }\n\n ## Client code.\n\n @doc \"\"\"\n Starts the current `Connection`. If the (successful) connection is to a\n database, fetch the schema.\n \"\"\"\n @spec start_link(Keyword.t) :: GenServer.on_start\n def start_link(opts) do\n # The first `opts` is the value to pass to the `init\/1` callback, the second\n # one is the list of options being passed to `Connection.start_link` (e.g.,\n # `:name` or `:timeout`).\n case Connection.start_link(__MODULE__, opts, opts) do\n {:error, _} = err ->\n err\n {:ok, pid} = res ->\n maybe_fetch_schema(pid, opts)\n res\n end\n end\n\n @doc \"\"\"\n Shuts down the connection (asynchronously since it's a cast).\n \"\"\"\n @spec stop(pid) :: :ok\n def stop(pid) do\n Connection.cast(pid, :stop)\n end\n\n @doc \"\"\"\n Performs the operation identified by `op_name` with the connection on\n `pid`. `args` is the list of arguments to pass to the operation.\n \"\"\"\n @spec operation(pid, atom, [Protocol.encodable_term], Keyword.t) ::\n {:ok, term} | {:error, term}\n def operation(pid, op_name, args, opts) do\n Connection.call(pid, {:operation, op_name, args}, opts[:timeout] || @timeout)\n end\n\n @doc \"\"\"\n Does what `operation\/3` does but expects no response from OrientDB and always\n returns `:ok`.\n \"\"\"\n @spec no_response_operation(pid, atom, [Protocol.encodable_term]) :: :ok\n def no_response_operation(pid, op_name, args) do\n Connection.cast(pid, {:operation, op_name, args})\n end\n\n @doc \"\"\"\n Fetch the schema and store it into the state.\n\n Always returns `:ok` without waiting for the schema to be fetched.\n \"\"\"\n @spec fetch_schema(pid) :: :ok\n def fetch_schema(pid) do\n Connection.call(pid, :fetch_schema)\n end\n\n defp maybe_fetch_schema(pid, opts) do\n case Keyword.get(opts, :connection) do\n {:db, _, _} -> fetch_schema(pid)\n _ -> nil\n end\n end\n\n ## Callbacks.\n\n @doc false\n def init(opts) do\n s = Dict.merge(@initial_state, opts: opts)\n {:connect, :init, s}\n end\n\n @doc false\n def connect(_info, s) do\n {host, port, socket_opts, timeout} = tcp_connection_opts(s)\n\n case :gen_tcp.connect(host, port, socket_opts, timeout) do\n {:ok, socket} ->\n s = %{s | socket: socket}\n setup_socket_buffers(socket)\n\n case Auth.connect(s) do\n {:ok, s} ->\n :inet.setopts(socket, active: :once)\n {:ok, s}\n {:error, error, s} ->\n {:stop, error, s}\n {:tcp_error, reason, s} ->\n {:stop, reason, s}\n end\n {:error, reason} ->\n Logger.error \"OrientDB TCP connect error (#{host}:#{port}): #{:inet.format_error(reason)}\"\n {:stop, reason, s}\n end\n end\n\n @doc false\n def disconnect(:stop, %{socket: nil} = s) do\n {:stop, :normal, s}\n end\n\n def disconnect(:stop, %{socket: socket} = s) do\n :gen_tcp.close(socket)\n {:stop, :normal, %{s | socket: nil}}\n end\n\n def disconnect(error, s) do\n # We only care about {from, _} tuples, ignoring queued stuff like\n # :fetch_schema.\n for {from, _operation} <- :queue.to_list(s.queue) do\n Connection.reply(from, error)\n end\n\n # Backoff 0 to churn through all commands in mailbox before reconnecting,\n # https:\/\/github.com\/ericmj\/mongodb\/blob\/a2dba1dfc089960d87364c2c43892f3061a93924\/lib\/mongo\/connection.ex#L210\n {:backoff, 0, %{s | socket: nil, queue: :queue.new, transaction_id: 1}}\n end\n\n @doc false\n # No socket means there's no TCP connection, we can return an error to the\n # client.\n def handle_call(_call, _from, %{socket: nil} = s) do\n {:reply, {:error, :closed}, s}\n end\n\n # We have to handle the :tx_commit operation differently as we have to keep\n # track of the transaction id, which is kept in the state of this genserver\n # (we also have to update this id).\n def handle_call({:operation, :tx_commit, [:transaction_id|args]}, from, s) do\n {id, s} = next_transaction_id(s)\n handle_call({:operation, :tx_commit, [id|args]}, from, s)\n end\n\n def handle_call({:operation, op_name, args}, from, %{session_id: sid} = s) do\n check_op_is_allowed!(s, op_name)\n\n req = Protocol.encode_op(op_name, [sid|args])\n s\n |> enqueue({from, op_name})\n |> send_noreply(req)\n end\n\n def handle_call(:fetch_schema, from, %{session_id: sid} = s) do\n check_op_is_allowed!(s, :record_load)\n\n args = [sid, {:short, 0}, {:long, 1}, \"*:-1\", true, false]\n req = Protocol.encode_op(:record_load, args)\n\n s\n |> enqueue({:fetch_schema, from})\n |> send_noreply(req)\n end\n\n @doc false\n def handle_cast({:operation, op_name, args}, %{session_id: sid} = s) do\n check_op_is_allowed!(s, op_name)\n\n req = Protocol.encode_op(op_name, [sid|args])\n send_noreply(s, req)\n end\n\n def handle_cast(:stop, s) do\n {:disconnect, :stop, s}\n end\n\n @doc false\n def handle_info({:tcp, socket, msg}, %{socket: socket} = s) do\n :inet.setopts(socket, active: :once)\n s = dequeue_and_parse_resp(s, :queue.out(s.queue), s.tail <> msg)\n {:noreply, s}\n end\n\n def handle_info({:tcp_closed, socket}, %{socket: socket} = s) do\n {:disconnect, {:error, :closed}, s}\n end\n\n # Helper functions.\n\n defp tcp_connection_opts(%{opts: opts} = _state) do\n socket_opts = @socket_opts ++ (opts[:socket_opts] || [])\n {to_char_list(opts[:host]), opts[:port], socket_opts, opts[:timeout] || @timeout}\n end\n\n defp parse_schema(%Document{fields: %{\"globalProperties\" => properties}}) do\n global_properties =\n for %Document{fields: %{\"name\" => name, \"type\" => type, \"id\" => id}} <- properties,\n into: HashDict.new() do\n {id, {name, type}}\n end\n\n %{global_properties: global_properties}\n end\n\n defp setup_socket_buffers(socket) do\n {:ok, [sndbuf: sndbuf, recbuf: recbuf, buffer: buffer]} =\n :inet.getopts(socket, [:sndbuf, :recbuf, :buffer])\n\n buffer = buffer |> max(sndbuf) |> max(recbuf)\n :ok = :inet.setopts(socket, [buffer: buffer])\n end\n\n defp send_noreply(%{socket: socket} = s, req) do\n case :gen_tcp.send(socket, req) do\n :ok ->\n {:noreply, s}\n {:error, _reason} = error ->\n {:disconnect, error, s}\n end\n end\n\n defp enqueue(s, what) do\n update_in s.queue, &:queue.in(what, &1)\n end\n\n defp dequeue_and_parse_resp(s, {{:value, {:fetch_schema, from}}, new_queue}, data) do\n sid = s.session_id\n\n case Protocol.parse_resp(:record_load, data, s.schema) do\n :incomplete ->\n %{s | tail: data}\n {^sid, {:error, _}, _rest} ->\n raise \"couldn't fetch schema\"\n {^sid, {:ok, {schema, _linked_records}}, rest} ->\n schema = parse_schema(schema)\n Connection.reply(from, schema)\n %{s | schema: schema, tail: rest, queue: new_queue}\n end\n end\n\n defp dequeue_and_parse_resp(s, {{:value, {from, op_name}}, new_queue}, data) do\n sid = s.session_id\n\n case Protocol.parse_resp(op_name, data, s.schema) do\n :incomplete ->\n %{s | tail: data}\n {^sid, resp, rest} ->\n Connection.reply(from, resp)\n %{s | tail: rest, queue: new_queue}\n end\n end\n\n defp check_op_is_allowed!(%{opts: opts}, operation) do\n do_check_op_is_allowed!(Keyword.fetch!(opts, :connection), operation)\n end\n\n @server_ops ~w(\n shutdown\n db_create\n db_exist\n db_drop\n )a\n\n @db_ops ~w(\n db_close\n db_size\n db_countrecords\n db_reload\n record_load\n record_load_if_version_not_latest\n record_create\n record_update\n record_delete\n command\n tx_commit\n )a\n\n defp do_check_op_is_allowed!({:db, _, _}, op) when not op in @db_ops do\n raise Error, \"must be connected to the server (not a db) to perform operation #{op}\"\n end\n\n defp do_check_op_is_allowed!(:server, op) when not op in @server_ops do\n raise Error, \"must be connected to a database to perform operation #{op}\"\n end\n\n defp do_check_op_is_allowed!(_, _) do\n nil\n end\n\n defp next_transaction_id(s) do\n get_and_update_in(s.transaction_id, &{&1, &1 + 1})\n end\nend\n","old_contents":"defmodule MarcoPolo.Connection do\n @moduledoc false\n\n use Connection\n\n require Logger\n\n alias MarcoPolo.Connection.Auth\n alias MarcoPolo.Protocol\n alias MarcoPolo.Document\n alias MarcoPolo.Error\n\n @socket_opts [:binary, active: false, packet: :raw]\n\n @timeout 5000\n\n @initial_state %{\n socket: nil,\n session_id: nil,\n queue: :queue.new,\n schema: nil,\n tail: \"\",\n transaction_id: 1,\n }\n\n ## Client code.\n\n @doc \"\"\"\n Starts the current `Connection`. If the (successful) connection is to a\n database, fetch the schema.\n \"\"\"\n @spec start_link(Keyword.t) :: GenServer.on_start\n def start_link(opts) do\n # The first `opts` is the value to pass to the `init\/1` callback, the second\n # one is the list of options being passed to `Connection.start_link` (e.g.,\n # `:name` or `:timeout`).\n case Connection.start_link(__MODULE__, opts, opts) do\n {:error, _} = err ->\n err\n {:ok, pid} = res ->\n maybe_fetch_schema(pid, opts)\n res\n end\n end\n\n @doc \"\"\"\n Shuts down the connection (asynchronously since it's a cast).\n \"\"\"\n @spec stop(pid) :: :ok\n def stop(pid) do\n Connection.cast(pid, :stop)\n end\n\n @doc \"\"\"\n Performs the operation identified by `op_name` with the connection on\n `pid`. `args` is the list of arguments to pass to the operation.\n \"\"\"\n @spec operation(pid, atom, [Protocol.encodable_term], Keyword.t) ::\n {:ok, term} | {:error, term}\n def operation(pid, op_name, args, opts) do\n Connection.call(pid, {:operation, op_name, args}, opts[:timeout] || @timeout)\n end\n\n @doc \"\"\"\n Does what `operation\/3` does but expects no response from OrientDB and always\n returns `:ok`.\n \"\"\"\n @spec no_response_operation(pid, atom, [Protocol.encodable_term]) :: :ok\n def no_response_operation(pid, op_name, args) do\n Connection.cast(pid, {:operation, op_name, args})\n end\n\n @doc \"\"\"\n Fetch the schema and store it into the state.\n\n Always returns `:ok` without waiting for the schema to be fetched.\n \"\"\"\n @spec fetch_schema(pid) :: :ok\n def fetch_schema(pid) do\n Connection.call(pid, :fetch_schema)\n end\n\n defp maybe_fetch_schema(pid, opts) do\n case Keyword.get(opts, :connection) do\n {:db, _, _} -> fetch_schema(pid)\n _ -> nil\n end\n end\n\n ## Callbacks.\n\n @doc false\n def init(opts) do\n s = Dict.merge(@initial_state, opts: opts)\n {:connect, :init, s}\n end\n\n @doc false\n def connect(_info, s) do\n {host, port, socket_opts, timeout} = tcp_connection_opts(s)\n\n case :gen_tcp.connect(host, port, socket_opts, timeout) do\n {:ok, socket} ->\n s = %{s | socket: socket}\n setup_socket_buffers(socket)\n\n case Auth.connect(s) do\n {:ok, s} ->\n :inet.setopts(socket, active: :once)\n {:ok, s}\n {:error, error, s} ->\n {:stop, error, s}\n {:tcp_error, reason, s} ->\n {:stop, reason, s}\n end\n {:error, reason} ->\n Logger.error \"OrientDB TCP connect error (#{host}:#{port}): #{:inet.format_error(reason)}\"\n {:stop, reason, s}\n end\n end\n\n @doc false\n def disconnect(:stop, %{socket: nil} = s) do\n {:stop, :normal, s}\n end\n\n def disconnect(:stop, %{socket: socket} = s) do\n :gen_tcp.close(socket)\n {:stop, :normal, %{s | socket: nil}}\n end\n\n def disconnect(error, s) do\n # We only care about {from, _} tuples, ignoring queued stuff like\n # :fetch_schema.\n for {from, _operation} <- :queue.to_list(s.queue) do\n Connection.reply(from, error)\n end\n\n # Backoff 0 to churn through all commands in mailbox before reconnecting,\n # https:\/\/github.com\/ericmj\/mongodb\/blob\/a2dba1dfc089960d87364c2c43892f3061a93924\/lib\/mongo\/connection.ex#L210\n {:backoff, 0, %{s | socket: nil, queue: :queue.new, transaction_id: 1}}\n end\n\n @doc false\n # No socket means there's no TCP connection, we can return an error to the\n # client.\n def handle_call(_call, _from, %{socket: nil} = s) do\n {:reply, {:error, :closed}, s}\n end\n\n # We have to handle the :tx_commit operation differently as we have to keep\n # track of the transaction id, which is kept in the state of this genserver\n # (we also have to update this id).\n def handle_call({:operation, :tx_commit, [:transaction_id|args]}, from, s) do\n {id, s} = next_transaction_id(s)\n handle_call({:operation, :tx_commit, [id|args]}, from, s)\n end\n\n def handle_call({:operation, op_name, args}, from, %{session_id: sid} = s) do\n check_op_is_allowed!(s, op_name)\n\n req = Protocol.encode_op(op_name, [sid|args])\n s\n |> enqueue({from, op_name})\n |> send_noreply(req)\n end\n\n def handle_call(:fetch_schema, from, %{session_id: sid} = s) do\n check_op_is_allowed!(s, :record_load)\n\n args = [sid, {:short, 0}, {:long, 1}, \"*:-1\", true, false]\n req = Protocol.encode_op(:record_load, args)\n\n s\n |> enqueue({:fetch_schema, from})\n |> send_noreply(req)\n end\n\n @doc false\n def handle_cast({:operation, op_name, args}, %{session_id: sid} = s) do\n check_op_is_allowed!(s, op_name)\n\n req = Protocol.encode_op(op_name, [sid|args])\n send_noreply(s, req)\n end\n\n def handle_cast(:stop, s) do\n {:disconnect, :stop, s}\n end\n\n @doc false\n def handle_info({:tcp, socket, msg}, %{socket: socket} = s) do\n :inet.setopts(socket, active: :once)\n s = dequeue_and_parse_resp(s, :queue.out(s.queue), s.tail <> msg)\n {:noreply, s}\n end\n\n def handle_info({:tcp_closed, socket}, %{socket: socket} = s) do\n {:disconnect, {:error, :closed}, s}\n end\n\n # Helper functions.\n\n defp tcp_connection_opts(%{opts: opts} = _state) do\n socket_opts = @socket_opts ++ (opts[:socket_opts] || [])\n {to_char_list(opts[:host]), opts[:port], socket_opts, opts[:timeout] || @timeout}\n end\n\n defp parse_schema(%Document{fields: %{\"globalProperties\" => properties}}) do\n global_properties =\n for %Document{fields: %{\"name\" => name, \"type\" => type, \"id\" => id}} <- properties,\n into: HashDict.new() do\n {id, {name, type}}\n end\n\n %{global_properties: global_properties}\n end\n\n defp setup_socket_buffers(socket) do\n {:ok, [sndbuf: sndbuf, recbuf: recbuf, buffer: buffer]} =\n :inet.getopts(socket, [:sndbuf, :recbuf, :buffer])\n\n buffer = buffer |> max(sndbuf) |> max(recbuf)\n :ok = :inet.setopts(socket, [buffer: buffer])\n end\n\n defp send_noreply(%{socket: socket} = s, req) do\n case :gen_tcp.send(socket, req) do\n :ok ->\n {:noreply, s}\n {:error, _reason} = error ->\n {:disconnect, error, s}\n end\n end\n\n defp enqueue(s, what) do\n update_in s.queue, &:queue.in(what, &1)\n end\n\n defp dequeue_and_parse_resp(s, {{:value, {:fetch_schema, from}}, new_queue}, data) do\n sid = s.session_id\n\n case Protocol.parse_resp(:record_load, data, s.schema) do\n :incomplete ->\n %{s | tail: data}\n {^sid, {:error, _}, _rest} ->\n raise \"couldn't fetch schema\"\n {^sid, {:ok, {schema, _linked_records}}, rest} ->\n schema = parse_schema(schema)\n Connection.reply(from, schema)\n %{s | schema: schema, tail: rest, queue: new_queue}\n end\n end\n\n defp dequeue_and_parse_resp(s, {{:value, {from, op_name}}, new_queue}, data) do\n sid = s.session_id\n\n case Protocol.parse_resp(op_name, data, s.schema) do\n :incomplete ->\n %{s | tail: data}\n {^sid, resp, rest} ->\n Connection.reply(from, resp)\n %{s | tail: rest, queue: new_queue}\n end\n end\n\n defp check_op_is_allowed!(%{opts: opts}, operation) do\n do_check_op_is_allowed!(Keyword.fetch!(opts, :connection), operation)\n end\n\n @server_ops ~w(\n shutdown\n db_create\n db_exist\n db_drop\n )a\n\n @db_ops ~w(\n db_close\n db_size\n db_countrecords\n db_reload\n record_load\n record_load_if_version_not_latest\n record_create\n record_update\n record_delete\n command\n tx_commit\n )a\n\n defp do_check_op_is_allowed!({:db, _, _}, op) when not op in @db_ops do\n raise Error, \"must be connected to the server (not a db) to perform operation #{op}\"\n end\n\n defp do_check_op_is_allowed!(:server, op) when not op in @server_ops do\n raise Error, \"must be connected to a database to perform operation #{op}\"\n end\n\n defp do_check_op_is_allowed!(_, _) do\n nil\n end\n\n defp next_transaction_id(s) do\n get_and_update_in(s.transaction_id, &{&1, &1 + 1})\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"49d8534c0c2005a2d2f8c2f71bc31c87cd08ed34","subject":"Refactor the response handling in MarcoPolo.Connection","message":"Refactor the response handling in MarcoPolo.Connection\n","repos":"linearregression\/marco_polo,MyMedsAndMe\/marco_polo","old_file":"lib\/marco_polo\/connection.ex","new_file":"lib\/marco_polo\/connection.ex","new_contents":"defmodule MarcoPolo.Connection do\n @moduledoc false\n\n use Connection\n\n require Logger\n\n alias MarcoPolo.Connection.Auth\n alias MarcoPolo.Protocol\n alias MarcoPolo.Document\n alias MarcoPolo.Error\n\n @socket_opts [:binary, active: false, packet: :raw]\n\n @initial_state %{socket: nil,\n session_id: nil,\n queue: :queue.new,\n schema: nil,\n tail: \"\"}\n\n ## Client code.\n\n def start_link(opts) do\n case Connection.start_link(__MODULE__, opts) do\n {:error, _} = err ->\n err\n {:ok, pid} = res ->\n maybe_fetch_schema(pid, opts)\n res\n end\n end\n\n def operation(pid, op_name, args) do\n Connection.call(pid, {:operation, op_name, args})\n end\n\n def fetch_schema(pid) do\n Connection.cast(pid, :fetch_schema)\n end\n\n defp maybe_fetch_schema(pid, opts) do\n case Keyword.get(opts, :connection) do\n {:db, _, _} -> fetch_schema(pid)\n _ -> nil\n end\n end\n\n ## Callbacks.\n\n @doc false\n def init(opts) do\n s = Dict.merge(@initial_state, opts: opts)\n {:connect, :init, s}\n end\n\n @doc false\n def connect(_info, s) do\n {host, port, socket_opts} = tcp_connection_opts(s)\n\n case :gen_tcp.connect(host, port, socket_opts) do\n {:ok, socket} ->\n s = %{s | socket: socket}\n setup_socket_buffers(socket)\n\n case Auth.connect(s) do\n {:ok, s} ->\n :inet.setopts(socket, active: :once)\n {:ok, s}\n {:error, error, s} ->\n {:stop, error, s}\n {:tcp_error, reason, s} ->\n {:stop, reason, s}\n end\n {:error, reason} ->\n Logger.error \"OrientDB TCP connect error (#{host}:#{port}): #{:inet.format_error(reason)}\"\n {:stop, reason, s}\n end\n end\n\n @doc false\n def disconnect(error, s) do\n # We only care about {from, _} tuples, ignoring queued stuff like\n # :fetch_schema.\n for {from, _operation} <- :queue.to_list(s.queue) do\n Connection.reply(from, error)\n end\n\n # Backoff 0 to churn through all commands in mailbox before reconnecting,\n # https:\/\/github.com\/ericmj\/mongodb\/blob\/a2dba1dfc089960d87364c2c43892f3061a93924\/lib\/mongo\/connection.ex#L210\n {:backoff, 0, %{s | socket: nil, queue: :queue.new}}\n end\n\n @doc false\n def handle_call(call, from, s)\n\n # No socket means there's no TCP connection, we can return an error to the\n # client.\n def handle_call(_call, _from, %{socket: nil} = s) do\n {:reply, {:error, :closed}, s}\n end\n\n def handle_call({:operation, op_name, args}, from, s) do\n req = Protocol.encode_op(op_name, [sid|args])\n send_noreply_enqueueing(s, req, {from, op_name})\n end\n\n @doc false\n def handle_cast(:fetch_schema, s) do\n args = [sid, {:short, 0}, {:long, 1}, \"*:-1\", true, false]\n req = Protocol.encode_op(:record_load, args)\n\n send_noreply_enqueueing(s, req, :fetch_schema)\n end\n\n @doc false\n def handle_info(msg, state)\n\n def handle_info({:tcp, socket, msg}, %{session_id: sid, socket: socket} = s) do\n :inet.setopts(socket, active: :once)\n s = dequeue_and_parse_resp(s, :queue.out(s.queue), s.tail <> msg)\n {:noreply, s}\n end\n\n def handle_info({:tcp_closed, socket}, %{socket: socket} = s) do\n {:disconnect, {:error, :closed}, s}\n end\n\n # Helper functions.\n\n defp tcp_connection_opts(%{opts: opts} = _state) do\n socket_opts = @socket_opts ++ (opts[:socket_opts] || [])\n {to_char_list(opts[:host]), opts[:port], socket_opts}\n end\n\n defp parse_schema(%Document{fields: %{\"globalProperties\" => properties}}) do\n global_properties =\n for %Document{fields: %{\"name\" => name, \"type\" => type, \"id\" => id}} <- properties,\n into: HashDict.new() do\n {id, {name, type}}\n end\n\n %{global_properties: global_properties}\n end\n\n defp setup_socket_buffers(socket) do\n {:ok, [sndbuf: sndbuf, recbuf: recbuf]} = :inet.getopts(socket, [:sndbuf, :recbuf])\n :ok = :inet.setopts(socket, [buffer: max(sndbuf, recbuf)])\n end\n\n defp send_noreply_enqueueing(%{socket: socket} = s, req, to_enqueue) do\n case :gen_tcp.send(socket, req) do\n :ok ->\n {:noreply, enqueue(s, to_enqueue)}\n {:error, _reason} = error ->\n {:disconnect, error, s}\n end\n end\n\n defp enqueue(s, what) do\n update_in s.queue, &:queue.in(what, &1)\n end\n\n defp dequeue_and_parse_resp(s, {{:value, :fetch_schema}, new_queue}, data) do\n sid = s.session_id\n\n case Protocol.parse_resp(:record_load, data, s.schema) do\n :incomplete ->\n %{s | tail: data}\n {:error, %Error{}, _} ->\n raise \"couldn't fetch schema\"\n {:ok, ^sid, [resp], rest} ->\n %{s | schema: parse_schema(resp), tail: rest, queue: new_queue}\n end\n end\n\n defp dequeue_and_parse_resp(s, {{:value, {from, op_name}}, new_queue}, data) do\n sid = s.session_id\n\n case Protocol.parse_resp(op_name, data, s.schema) do\n :incomplete ->\n %{s | tail: data}\n {:unknown_property_id, rest} ->\n Connection.reply(from, {:error, :unknown_property_id})\n %{s | tail: rest}\n {:error, error, rest} ->\n Connection.reply(from, {:error, error})\n %{s | tail: rest, queue: new_queue}\n {:ok, ^sid, resp, rest} ->\n Connection.reply(from, {:ok, resp})\n %{s | tail: rest, queue: new_queue}\n end\n end\nend\n","old_contents":"defmodule MarcoPolo.Connection do\n @moduledoc false\n\n use Connection\n\n require Logger\n\n alias MarcoPolo.Connection.Auth\n alias MarcoPolo.Protocol\n alias MarcoPolo.Document\n alias MarcoPolo.Error\n\n @socket_opts [:binary, active: false, packet: :raw]\n\n @initial_state %{socket: nil,\n session_id: nil,\n queue: :queue.new,\n schema: nil,\n tail: \"\"}\n\n ## Client code.\n\n def start_link(opts) do\n case Connection.start_link(__MODULE__, opts) do\n {:error, _} = err ->\n err\n {:ok, pid} = res ->\n maybe_fetch_schema(pid, opts)\n res\n end\n end\n\n def operation(pid, op_name, args) do\n Connection.call(pid, {:operation, op_name, args})\n end\n\n def fetch_schema(pid) do\n Connection.cast(pid, :fetch_schema)\n end\n\n defp maybe_fetch_schema(pid, opts) do\n case Keyword.get(opts, :connection) do\n {:db, _, _} -> fetch_schema(pid)\n _ -> nil\n end\n end\n\n ## Callbacks.\n\n @doc false\n def init(opts) do\n s = Dict.merge(@initial_state, opts: opts)\n {:connect, :init, s}\n end\n\n @doc false\n def connect(_info, s) do\n {host, port, socket_opts} = tcp_connection_opts(s)\n\n case :gen_tcp.connect(host, port, socket_opts) do\n {:ok, socket} ->\n s = %{s | socket: socket}\n setup_socket_buffers(socket)\n\n case Auth.connect(s) do\n {:ok, s} ->\n :inet.setopts(socket, active: :once)\n {:ok, s}\n {:error, error, s} ->\n {:stop, error, s}\n {:tcp_error, reason, s} ->\n {:stop, reason, s}\n end\n {:error, reason} ->\n Logger.error \"OrientDB TCP connect error (#{host}:#{port}): #{:inet.format_error(reason)}\"\n {:stop, reason, s}\n end\n end\n\n @doc false\n def disconnect(error, s) do\n # We only care about {_, from} tuples, ignoring queued stuff like\n # :fetch_schema.\n for {_operation, from} <- :queue.to_list(s.queue) do\n Connection.reply(from, error)\n end\n\n # Backoff 0 to churn through all commands in mailbox before reconnecting,\n # https:\/\/github.com\/ericmj\/mongodb\/blob\/a2dba1dfc089960d87364c2c43892f3061a93924\/lib\/mongo\/connection.ex#L210\n {:backoff, 0, %{s | socket: nil, queue: :queue.new}}\n end\n\n @doc false\n def handle_call(call, from, s)\n\n # No socket means there's no TCP connection, we can return an error to the\n # client.\n def handle_call(_call, _from, %{socket: nil} = s) do\n {:reply, {:error, :closed}, s}\n end\n\n def handle_call({:operation, op_name, args}, from, %{session_id: sid} = s) do\n req = Protocol.encode_op(op_name, [sid|args])\n send_noreply_enqueueing(s, req, {from, op_name})\n end\n\n @doc false\n def handle_cast(:fetch_schema, %{session_id: sid} = s) do\n args = [sid, {:short, 0}, {:long, 1}, \"*:-1\", true, false]\n req = Protocol.encode_op(:record_load, args)\n\n send_noreply_enqueueing(s, req, :fetch_schema)\n end\n\n @doc false\n def handle_info(msg, state)\n\n def handle_info({:tcp, socket, msg}, %{session_id: sid, socket: socket} = s) do\n :inet.setopts(socket, active: :once)\n data = s.tail <> msg\n\n s =\n case :queue.out(s.queue) do\n {{:value, :fetch_schema}, new_queue} ->\n case Protocol.parse_resp(:record_load, data, s.schema) do\n :incomplete ->\n %{s | tail: data}\n {:error, %Error{}, _} ->\n raise \"couldn't fetch schema\"\n {:ok, ^sid, [resp], rest} ->\n %{s | schema: parse_schema(resp), tail: rest, queue: new_queue}\n end\n {{:value, {from, op_name}}, new_queue} ->\n case Protocol.parse_resp(op_name, data, s.schema) do\n :incomplete ->\n %{s | tail: data}\n {:unknown_property_id, rest} ->\n Connection.reply(from, {:error, :unknown_property_id})\n %{s | tail: rest}\n {:error, error, rest} ->\n Connection.reply(from, {:error, error})\n %{s | tail: rest, queue: new_queue}\n {:ok, ^sid, resp, rest} ->\n Connection.reply(from, {:ok, resp})\n %{s | tail: rest, queue: new_queue}\n end\n end\n\n {:noreply, s}\n end\n\n def handle_info({:tcp_closed, socket}, %{socket: socket} = s) do\n {:disconnect, {:error, :closed}, s}\n end\n\n # Helper functions.\n\n defp tcp_connection_opts(%{opts: opts} = _state) do\n socket_opts = @socket_opts ++ (opts[:socket_opts] || [])\n {to_char_list(opts[:host]), opts[:port], socket_opts}\n end\n\n defp parse_schema(%Document{fields: %{\"globalProperties\" => properties}}) do\n global_properties =\n for %Document{fields: %{\"name\" => name, \"type\" => type, \"id\" => id}} <- properties,\n into: HashDict.new() do\n {id, {name, type}}\n end\n\n %{global_properties: global_properties}\n end\n\n defp setup_socket_buffers(socket) do\n {:ok, [sndbuf: sndbuf, recbuf: recbuf]} = :inet.getopts(socket, [:sndbuf, :recbuf])\n :ok = :inet.setopts(socket, [buffer: max(sndbuf, recbuf)])\n end\n\n defp send_noreply_enqueueing(%{socket: socket} = s, req, to_enqueue) do\n case :gen_tcp.send(socket, req) do\n :ok ->\n {:noreply, enqueue(s, to_enqueue)}\n {:error, _reason} = error ->\n {:disconnect, error, s}\n end\n end\n\n defp enqueue(s, what) do\n update_in s.queue, &:queue.in(what, &1)\n end\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"092376f849dc66fe67521a83a48364d1dc196b94","subject":"Generate `*_url` helpers with domain and scheme (protocol)","message":"Generate `*_url` helpers with domain and scheme (protocol)\n","repos":"gjaldon\/phoenix,nshafer\/phoenix,yonglehou\/phoenix,ahmetabdi\/phoenix,Joe-noh\/phoenix,manukall\/phoenix,andrewvy\/phoenix,wsmoak\/phoenix,elliotcm\/phoenix,Rumel\/phoenix,jamilabreu\/phoenix,Eventacular\/phoenix,evax\/phoenix,eksperimental\/phoenix,DavidAlphaFox\/phoenix,vic\/phoenix,kholbekj\/phoenix,Dahoon\/phoenix,rafbgarcia\/phoenix,ybur-yug\/phoenix,yoavlt\/phoenix,mobileoverlord\/phoenix,lono-devices\/phoenix,keathley\/phoenix,JHKennedy4\/phoenix,xtity\/simple_phoenix,andrewvy\/phoenix,nshafer\/phoenix,jwarwick\/phoenix,milafrerichs\/phoenix,foxnewsnetwork\/phoenix,mschae\/phoenix,trarbr\/phoenix,mvidaurre\/phoenix,kidaa\/phoenix,esbullington\/phoenix-1,wicliff\/phoenix,optikfluffel\/phoenix,optikfluffel\/phoenix,jeffweiss\/phoenix,bsmr-erlang\/phoenix,beni55\/phoenix,omotenko\/phoenix_auth,iStefo\/phoenix,bsodmike\/phoenix,jamilabreu\/phoenix,michalmuskala\/phoenix,linearregression\/phoenix,Kosmas\/phoenix,trarbr\/phoenix,ericmj\/phoenix,0x00evil\/phoenix,seejee\/phoenix,ephe-meral\/phoenix,Rumel\/phoenix,stevedomin\/phoenix,bsmr-erlang\/phoenix,pap\/phoenix,switchflip\/phoenix,robomc\/phoenix,ACPK\/phoenix,vic\/phoenix,begleynk\/phoenix,tony612\/phoenix,Smulligan85\/phoenix,doomspork\/phoenix,fbjork\/phoenix,Smulligan85\/phoenix,keathley\/phoenix,romul\/phoenix,manukall\/phoenix,ephe-meral\/phoenix,jasond-s\/phoenix,optikfluffel\/phoenix,phoenixframework\/phoenix,scrogson\/phoenix,CD1212\/phoenix,sadiqmmm\/phoenix,marcioj\/phoenix,eksperimental\/phoenix,paulcsmith\/phoenix,kevinold\/phoenix,bitgamma\/phoenix,StevenNunez\/phoenix,VictorZeng\/phoenix,doron2402\/phoenix,arthurcolle\/phoenix,rafbgarcia\/phoenix,rafbgarcia\/phoenix,Gazler\/phoenix,mschae\/phoenix,dmarkow\/phoenix,sdnorm\/phoenix,CultivateHQ\/phoenix,cas27\/phoenix,greyhwndz\/phoenix,mitchellhenke\/phoenix,kyledecot\/phoenix,mobileoverlord\/phoenix,seejee\/phoenix,brucify\/phoenix,hotvulcan\/phoenix,robhurring\/phoenix,phoenixframework\/phoenix,Gazler\/phoenix,Kosmas\/phoenix,michalmuskala\/phoenix,jeffkreeftmeijer\/phoenix,SmartCasual\/phoenix,ybur-yug\/phoenix,daytonn\/phoenix,y-yagi\/phoenix,stevedomin\/phoenix,cas27\/phoenix,nshafer\/phoenix,pap\/phoenix,evax\/phoenix,Ben-Evolently\/phoenix,justnoxx\/phoenix,KazuCocoa\/phoenix,ugisozols\/phoenix,FND\/phoenix,GabrielNicolasAvellaneda\/phoenix,omotenko\/phoenix_auth,nicrioux\/phoenix,jxs\/phoenix,gjaldon\/phoenix,korobkov\/phoenix,mvidaurre\/phoenix,korobkov\/phoenix,dmarkow\/phoenix,rodrigues\/phoenix,CultivateHQ\/phoenix,0x00evil\/phoenix,Fluxuous\/phoenix,iStefo\/phoenix,henrik\/phoenix,safi\/phoenix,Joe-noh\/phoenix,thegrubbsian\/phoenix,hsavit1\/phoenix,DavidAlphaFox\/phoenix,javimolla\/phoenix,stefania11\/phoenix,phoenixframework\/phoenix,lono-devices\/phoenix,nickgartmann\/phoenix,lancehalvorsen\/phoenix,maxnordlund\/phoenix,jwarwick\/phoenix,wsmoak\/phoenix,lancehalvorsen\/phoenix,ericmj\/phoenix,iguberman\/phoenix,bdtomlin\/phoenix,rodrigues\/phoenix,0x00evil\/phoenix,mitchellhenke\/phoenix","old_file":"lib\/phoenix\/router\/mapper.ex","new_file":"lib\/phoenix\/router\/mapper.ex","new_contents":"defmodule Phoenix.Router.Mapper do\n alias Phoenix.Router.Path\n alias Phoenix.Controller\n alias Phoenix.Router.ResourcesContext\n alias Phoenix.Router.ScopeContext\n alias Phoenix.Router.Errors\n alias Phoenix.Router.Mapper\n\n @actions [:index, :edit, :show, :new, :create, :update, :destroy]\n\n @moduledoc \"\"\"\n Adds Macros for Route match definitions. All routes are\n compiled to pattern matched def match() definitions for fast\n and efficient lookup by the VM.\n\n # Examples\n\n defmodule Router do\n use Phoenix.Router, port: 4000\n\n get \"pages\/:page\", PagesController, :show, as: :page\n resources \"users\", UsersController\n end\n\n Compiles to\n\n get \"pages\/:page\", PagesController, :show, as: :page\n\n -> defmatch({:get, \"pages\/:page\", PagesController, :show, [as: :page]})\n defroute_aliases({:get, \"pages\/:page\", PagesController, :show, [as: :page]})\n\n --> def(match(conn, :get, [\"pages\", page])) do\n conn = conn.params(Dict.merge(conn.params(), [{\"page\", page}]))\n apply(PagesController, :show, [conn])\n end\n\n The resources macro accepts flags to limit which resources are generated. Passing\n a list of actions through either :only or :except will prevent building all the\n routes\n\n # Examples\n\n defmodule Router do\n use Phoenix.Router, port: 4000\n\n resources \"pages\", Controllers.Pages, only: [ :show ]\n resources \"users\", Controllers.Users, except: [ :destroy ]\n end\n\n Generated Routes\n\n page GET pages\/:id Elixir.Controllers.Pages#show\n\n users GET users Elixir.Controllers.Users#new\n new_user GET users\/new Elixir.Controllers.Users#new\n edit_user GET users\/:id\/edit Elixir.Controllers.Users#edit\n user GET users\/:id Elixir.Controllers.Users#show\n\n POST users Elixir.Controllers.Users#create\n PUT users\/:id Elixir.Controllers.Users#update\n PATCH users\/:id Elixir.Controllers.Users#update\n \"\"\"\n\n defmacro __using__(_options) do\n quote do\n Module.register_attribute __MODULE__, :routes, accumulate: true,\n persist: false\n import unquote(__MODULE__)\n @before_compile unquote(__MODULE__)\n end\n end\n\n defmacro __before_compile__(env) do\n routes = Enum.reverse(Module.get_attribute(env.module, :routes))\n routes_ast = Enum.reduce routes, nil, fn route, acc ->\n quote do\n defmatch(unquote(route))\n defroute_aliases(unquote(route))\n unquote(acc)\n end\n end\n\n quote do\n def __routes__, do: Enum.reverse(@routes)\n unquote(routes_ast)\n def match(conn, method, path), do: Controller.not_found(conn, method, path)\n end\n end\n\n defmacro defmatch({http_method, path, controller, action, _options}) do\n path_args = Path.matched_arg_list_with_ast_bindings(path)\n params_list_with_bindings = Path.params_with_ast_bindings(path)\n\n quote do\n def unquote(:match)(conn, unquote(http_method), unquote(path_args)) do\n conn = %{conn | params: Dict.merge(conn.params, unquote(params_list_with_bindings)) }\n\n apply(unquote(controller), unquote(action), [conn])\n end\n end\n end\n\n defmacro defroute_aliases({_http_method, path, _controller, _action, options}) do\n alias_name = options[:as]\n if alias_name do\n quote do\n def unquote(binary_to_atom \"#{alias_name}_path\")(params \\\\ []) do\n Path.build(unquote(path), params)\n end\n def unquote(binary_to_atom \"#{alias_name}_url\")(params \\\\ []) do\n config = Phoenix.Config.for(__MODULE__).router\n domain = config[:domain]\n scheme = if config[:ssl], do: \"https\", else: \"http\"\n\n Path.build(unquote(path), params)\n |> Path.build_url(domain, scheme)\n end\n end\n end\n end\n\n defmacro get(path, controller, action, options \\\\ []) do\n add_route(:get, path, controller, action, options)\n end\n\n defmacro post(path, controller, action, options \\\\ []) do\n add_route(:post, path, controller, action, options)\n end\n\n defmacro put(path, controller, action, options \\\\ []) do\n add_route(:put, path, controller, action, options)\n end\n\n defmacro patch(path, controller, action, options \\\\ []) do\n add_route(:patch, path, controller, action, options)\n end\n\n defmacro delete(path, controller, action, options \\\\ []) do\n add_route(:delete, path, controller, action, options)\n end\n\n defp add_route(verb, path, controller, action, options) do\n quote bind_quoted: [verb: verb,\n path: path,\n controller: controller,\n action: action,\n options: options] do\n\n Errors.ensure_valid_path!(path)\n current_path = ResourcesContext.current_path(path, __MODULE__)\n {scoped_path, scoped_controller, scoped_helper} = ScopeContext.current_scope(current_path,\n controller,\n options[:as],\n __MODULE__)\n opts = Dict.merge(options, as: scoped_helper)\n\n @routes {verb, scoped_path, scoped_controller, action, opts}\n end\n end\n\n defmacro resources(resource, controller, opts, do: nested_context) do\n add_resources resource, controller, opts, do: nested_context\n end\n defmacro resources(resource, controller, do: nested_context) do\n add_resources resource, controller, [], do: nested_context\n end\n defmacro resources(resource, controller, opts) do\n add_resources resource, controller, opts, do: nil\n end\n defmacro resources(resource, controller) do\n add_resources resource, controller, [], do: nil\n end\n defp add_resources(resource, controller, options, do: nested_context) do\n quote unquote: true, bind_quoted: [options: options,\n resource: resource,\n controller: controller] do\n\n actions = Mapper.extract_actions_from_options(options)\n Enum.each actions, fn action ->\n current_alias = ResourcesContext.current_alias(action, resource, __MODULE__)\n opts = [as: current_alias]\n case action do\n :index -> get \"\/#{resource}\", controller, :index, opts\n :show -> get \"\/#{resource}\/:id\", controller, :show, opts\n :new -> get \"\/#{resource}\/new\", controller, :new, opts\n :edit -> get \"\/#{resource}\/:id\/edit\", controller, :edit, opts\n :create -> post \"\/#{resource}\", controller, :create, opts\n :destroy -> delete \"\/#{resource}\/:id\", controller, :destroy, opts\n :update ->\n put \"\/#{resource}\/:id\", controller, :update, []\n patch \"\/#{resource}\/:id\", controller, :update, []\n end\n end\n\n ResourcesContext.push(resource, __MODULE__)\n unquote(nested_context)\n ResourcesContext.pop(__MODULE__)\n end\n end\n\n defmacro scope(params, do: nested_context) do\n path = Keyword.get(params, :path)\n controller_alias = Keyword.get(params, :alias)\n helper = Keyword.get(params, :helper)\n\n quote unquote: true, bind_quoted: [path: path,\n controller_alias: controller_alias,\n helper: helper] do\n\n ScopeContext.push({path, controller_alias, helper}, __MODULE__)\n unquote(nested_context)\n ScopeContext.pop(__MODULE__)\n end\n end\n\n def extract_actions_from_options(opts) do\n Keyword.get(opts, :only) || (@actions -- Keyword.get(opts, :except, []))\n end\nend\n","old_contents":"defmodule Phoenix.Router.Mapper do\n alias Phoenix.Router.Path\n alias Phoenix.Controller\n alias Phoenix.Router.ResourcesContext\n alias Phoenix.Router.ScopeContext\n alias Phoenix.Router.Errors\n alias Phoenix.Router.Mapper\n\n @actions [:index, :edit, :show, :new, :create, :update, :destroy]\n\n @moduledoc \"\"\"\n Adds Macros for Route match definitions. All routes are\n compiled to pattern matched def match() definitions for fast\n and efficient lookup by the VM.\n\n # Examples\n\n defmodule Router do\n use Phoenix.Router, port: 4000\n\n get \"pages\/:page\", PagesController, :show, as: :page\n resources \"users\", UsersController\n end\n\n Compiles to\n\n get \"pages\/:page\", PagesController, :show, as: :page\n\n -> defmatch({:get, \"pages\/:page\", PagesController, :show, [as: :page]})\n defroute_aliases({:get, \"pages\/:page\", PagesController, :show, [as: :page]})\n\n --> def(match(conn, :get, [\"pages\", page])) do\n conn = conn.params(Dict.merge(conn.params(), [{\"page\", page}]))\n apply(PagesController, :show, [conn])\n end\n\n The resources macro accepts flags to limit which resources are generated. Passing\n a list of actions through either :only or :except will prevent building all the\n routes\n\n # Examples\n\n defmodule Router do\n use Phoenix.Router, port: 4000\n\n resources \"pages\", Controllers.Pages, only: [ :show ]\n resources \"users\", Controllers.Users, except: [ :destroy ]\n end\n\n Generated Routes\n\n page GET pages\/:id Elixir.Controllers.Pages#show\n\n users GET users Elixir.Controllers.Users#new\n new_user GET users\/new Elixir.Controllers.Users#new\n edit_user GET users\/:id\/edit Elixir.Controllers.Users#edit\n user GET users\/:id Elixir.Controllers.Users#show\n\n POST users Elixir.Controllers.Users#create\n PUT users\/:id Elixir.Controllers.Users#update\n PATCH users\/:id Elixir.Controllers.Users#update\n \"\"\"\n\n defmacro __using__(_options) do\n quote do\n Module.register_attribute __MODULE__, :routes, accumulate: true,\n persist: false\n import unquote(__MODULE__)\n @before_compile unquote(__MODULE__)\n end\n end\n\n defmacro __before_compile__(env) do\n routes = Enum.reverse(Module.get_attribute(env.module, :routes))\n routes_ast = Enum.reduce routes, nil, fn route, acc ->\n quote do\n defmatch(unquote(route))\n defroute_aliases(unquote(route))\n unquote(acc)\n end\n end\n\n quote do\n def __routes__, do: Enum.reverse(@routes)\n unquote(routes_ast)\n def match(conn, method, path), do: Controller.not_found(conn, method, path)\n end\n end\n\n defmacro defmatch({http_method, path, controller, action, _options}) do\n path_args = Path.matched_arg_list_with_ast_bindings(path)\n params_list_with_bindings = Path.params_with_ast_bindings(path)\n\n quote do\n def unquote(:match)(conn, unquote(http_method), unquote(path_args)) do\n conn = %{conn | params: Dict.merge(conn.params, unquote(params_list_with_bindings)) }\n\n apply(unquote(controller), unquote(action), [conn])\n end\n end\n end\n\n defmacro defroute_aliases({_http_method, path, _controller, _action, options}) do\n alias_name = options[:as]\n if alias_name do\n quote do\n def unquote(binary_to_atom \"#{alias_name}_path\")(params \\\\ []) do\n Path.build(unquote(path), params)\n end\n # TODO: use config based domain for URL\n def unquote(binary_to_atom \"#{alias_name}_url\")(params \\\\ []) do\n Path.build(unquote(path), params)\n end\n end\n end\n end\n\n defmacro get(path, controller, action, options \\\\ []) do\n add_route(:get, path, controller, action, options)\n end\n\n defmacro post(path, controller, action, options \\\\ []) do\n add_route(:post, path, controller, action, options)\n end\n\n defmacro put(path, controller, action, options \\\\ []) do\n add_route(:put, path, controller, action, options)\n end\n\n defmacro patch(path, controller, action, options \\\\ []) do\n add_route(:patch, path, controller, action, options)\n end\n\n defmacro delete(path, controller, action, options \\\\ []) do\n add_route(:delete, path, controller, action, options)\n end\n\n defp add_route(verb, path, controller, action, options) do\n quote bind_quoted: [verb: verb,\n path: path,\n controller: controller,\n action: action,\n options: options] do\n\n Errors.ensure_valid_path!(path)\n current_path = ResourcesContext.current_path(path, __MODULE__)\n {scoped_path, scoped_controller, scoped_helper} = ScopeContext.current_scope(current_path,\n controller,\n options[:as],\n __MODULE__)\n opts = Dict.merge(options, as: scoped_helper)\n\n @routes {verb, scoped_path, scoped_controller, action, opts}\n end\n end\n\n defmacro resources(resource, controller, opts, do: nested_context) do\n add_resources resource, controller, opts, do: nested_context\n end\n defmacro resources(resource, controller, do: nested_context) do\n add_resources resource, controller, [], do: nested_context\n end\n defmacro resources(resource, controller, opts) do\n add_resources resource, controller, opts, do: nil\n end\n defmacro resources(resource, controller) do\n add_resources resource, controller, [], do: nil\n end\n defp add_resources(resource, controller, options, do: nested_context) do\n quote unquote: true, bind_quoted: [options: options,\n resource: resource,\n controller: controller] do\n\n actions = Mapper.extract_actions_from_options(options)\n Enum.each actions, fn action ->\n current_alias = ResourcesContext.current_alias(action, resource, __MODULE__)\n opts = [as: current_alias]\n case action do\n :index -> get \"\/#{resource}\", controller, :index, opts\n :show -> get \"\/#{resource}\/:id\", controller, :show, opts\n :new -> get \"\/#{resource}\/new\", controller, :new, opts\n :edit -> get \"\/#{resource}\/:id\/edit\", controller, :edit, opts\n :create -> post \"\/#{resource}\", controller, :create, opts\n :destroy -> delete \"\/#{resource}\/:id\", controller, :destroy, opts\n :update ->\n put \"\/#{resource}\/:id\", controller, :update, []\n patch \"\/#{resource}\/:id\", controller, :update, []\n end\n end\n\n ResourcesContext.push(resource, __MODULE__)\n unquote(nested_context)\n ResourcesContext.pop(__MODULE__)\n end\n end\n\n defmacro scope(params, do: nested_context) do\n path = Keyword.get(params, :path)\n controller_alias = Keyword.get(params, :alias)\n helper = Keyword.get(params, :helper)\n\n quote unquote: true, bind_quoted: [path: path,\n controller_alias: controller_alias,\n helper: helper] do\n\n ScopeContext.push({path, controller_alias, helper}, __MODULE__)\n unquote(nested_context)\n ScopeContext.pop(__MODULE__)\n end\n end\n\n def extract_actions_from_options(opts) do\n Keyword.get(opts, :only) || (@actions -- Keyword.get(opts, :except, []))\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"831d4fb8f04ed333cf9cb6fe39057cb7156c748f","subject":"Fix type in logger.ex doc sample (#8096)","message":"Fix type in logger.ex doc sample (#8096)\n\n","repos":"lexmag\/elixir,ggcampinho\/elixir,michalmuskala\/elixir,joshprice\/elixir,pedrosnk\/elixir,kimshrier\/elixir,elixir-lang\/elixir,kelvinst\/elixir,kelvinst\/elixir,lexmag\/elixir,ggcampinho\/elixir,pedrosnk\/elixir,kimshrier\/elixir","old_file":"lib\/logger\/lib\/logger.ex","new_file":"lib\/logger\/lib\/logger.ex","new_contents":"defmodule Logger do\n @moduledoc ~S\"\"\"\n A logger for Elixir applications.\n\n It includes many features:\n\n * Provides debug, info, warn, and error levels.\n\n * Supports multiple backends which are automatically\n supervised when plugged into `Logger`.\n\n * Formats and truncates messages on the client\n to avoid clogging `Logger` backends.\n\n * Alternates between sync and async modes to remain\n performant when required but also apply backpressure\n when under stress.\n\n * Plugs into Erlang's [`:logger`](http:\/\/erlang.org\/doc\/man\/logger.html)\n (from Erlang\/OTP 21) to convert terms to Elixir syntax or wraps\n Erlang's [`:error_logger`](http:\/\/erlang.org\/doc\/man\/error_logger.html)\n in earlier Erlang\/OTP versions to prevent it from overflowing.\n\n Logging is useful for tracking when an event of interest happens in your\n system. For example, it may be helpful to log whenever a user is deleted.\n\n def delete_user(user) do\n Logger.info \"Deleting user from the system: #{inspect(user)}\"\n # ...\n end\n\n The `Logger.info\/2` macro emits the provided message at the `:info`\n level. Note the arguments given to `info\/2` will only be evaluated\n if a message is logged. For instance, if the Logger level is\n set to `:warn`, `:info` messages are never logged and therefore the\n arguments given above won't even be executed.\n\n There are additional macros for other levels.\n\n Logger also allows log commands to be removed altogether via the\n `:compile_time_purge_matching` option (see below).\n\n For dynamically logging messages, see `bare_log\/3`. But note that\n `bare_log\/3` always evaluates its arguments (unless the argument\n is an anonymous function).\n\n ## Levels\n\n The supported levels are:\n\n * `:debug` - for debug-related messages\n * `:info` - for information of any kind\n * `:warn` - for warnings\n * `:error` - for errors\n\n ## Configuration\n\n `Logger` supports a wide range of configurations.\n\n This configuration is split in three categories:\n\n * Application configuration - must be set before the `:logger`\n application is started\n\n * Runtime configuration - can be set before the `:logger`\n application is started, but may be changed during runtime\n\n * Erlang configuration - options that handle integration with\n Erlang's logging facilities\n\n ### Application configuration\n\n The following configuration must be set via config files (such as\n `config\/config.exs`) before the `:logger` application is started.\n\n * `:backends` - the backends to be used. Defaults to `[:console]`.\n See the \"Backends\" section for more information.\n\n * `:compile_time_application` - sets the `:application` metadata value\n to the configured value at compilation time. This configuration is\n usually only useful for build tools to automatically add the\n application to the metadata for `Logger.debug\/2`, `Logger.info\/2`, etc.\n style of calls.\n\n * `:compile_time_purge_matching` - purges *at compilation time* all calls\n that match the given conditions. This means that `Logger` calls with\n level lower than this option will be completely removed at compile time,\n accruing no overhead at runtime. This configuration expects a list of\n keyword lists. Each keyword list contains a metadata key and the matching\n value that should be purged. A special key named `:level_lower_than` can\n be used to purge all messages with a lower logger level. Remember that\n if you want to purge log calls from a dependency, the dependency must be\n recompiled.\n\n For example, to configure the `:backends` and purge all calls that happen\n at compile time with level lower than `:info` in a `config\/config.exs` file:\n\n config :logger,\n backends: [:console],\n compile_time_purge_matching: [\n [level_lower_than: :info]\n ]\n\n If you want to purge all log calls from an application named `:foo` and only\n keep errors from `Bar.foo\/3`, you can set up two different matches:\n\n config :logger,\n compile_time_purge_matching: [\n [application: :foo],\n [module: Bar, function: \"foo\/3\", level_lower_than: :error]\n ]\n\n ### Runtime Configuration\n\n All configuration below can be set via config files (such as\n `config\/config.exs`) but also changed dynamically during runtime via\n `Logger.configure\/1`.\n\n * `:level` - the logging level. Attempting to log any message\n with severity less than the configured level will simply\n cause the message to be ignored. Keep in mind that each backend\n may have its specific level, too.\n\n * `:utc_log` - when `true`, uses UTC in logs. By default it uses\n local time (i.e., it defaults to `false`).\n\n * `:truncate` - the maximum message size to be logged (in bytes).\n Defaults to 8192 bytes. Note this configuration is approximate.\n Truncated messages will have `\" (truncated)\"` at the end.\n The atom `:infinity` can be passed to disable this behavior.\n\n * `:sync_threshold` - if the `Logger` manager has more than\n `:sync_threshold` messages in its queue, `Logger` will change\n to *sync mode*, to apply backpressure to the clients.\n `Logger` will return to *async mode* once the number of messages\n in the queue is reduced to `sync_threshold * 0.75` messages.\n Defaults to 20 messages. `:sync_threshold` can be set to `0` to force *sync mode*.\n\n * `:discard_threshold` - if the `Logger` manager has more than\n `:discard_threshold` messages in its queue, `Logger` will change\n to *discard mode* and messages will be discarded directly in the\n clients. `Logger` will return to *sync mode* once the number of\n messages in the queue is reduced to `discard_threshold * 0.75`\n messages. Defaults to 500 messages.\n\n * `:translator_inspect_opts` - when translating OTP reports and\n errors, the last message and state must be inspected in the\n error reports. This configuration allow developers to change\n how much and how the data should be inspected.\n\n For example, to configure the `:level` and `:truncate` options in a\n `config\/config.exs` file:\n\n config :logger,\n level: :warn,\n truncate: 4096\n\n ### Error logger configuration\n\n The following configuration applies to `Logger`'s wrapper around\n Erlang's logging functionalities. All the configurations below must\n be set before the `:logger` application starts.\n\n * `:handle_otp_reports` - redirects OTP reports to `Logger` so\n they are formatted in Elixir terms. This effectively disables\n Erlang standard logger. Defaults to `true`.\n\n * `:handle_sasl_reports` - redirects supervisor, crash and\n progress reports to `Logger` so they are formatted in Elixir\n terms. Your application must guarantee `:sasl` is started before\n `:logger`. This means you may see some initial reports written\n in Erlang syntax until the Logger application kicks in.\n Defaults to `false`.\n\n From Erlang\/OTP 21, `:handle_sasl_reports` only has an effect if\n `:handle_otp_reports` is true.\n\n The following configurations apply only for Erlang\/OTP 20 and earlier:\n\n * `:discard_threshold_for_error_logger` - if `:error_logger` has more than\n `discard_threshold` messages in its inbox, messages will be dropped\n until the message queue goes down to `discard_threshold * 0.75`\n entries. The threshold will be checked once again after 10% of threshold\n messages are processed, to avoid messages from being constantly dropped.\n For example, if the threshold is 500 (the default) and the inbox has\n 600 messages, 225 messages will dropped, bringing the inbox down to\n 375 (0.75 * threshold) entries and 50 (0.1 * threshold) messages will\n be processed before the threshold is checked once again.\n\n For example, to configure `Logger` to redirect all Erlang messages using a\n `config\/config.exs` file:\n\n config :logger,\n handle_otp_reports: true,\n handle_sasl_reports: true\n\n Furthermore, `Logger` allows messages sent by Erlang to be translated\n into an Elixir format via translators. Translators can be added at any\n time with the `add_translator\/1` and `remove_translator\/1` APIs. Check\n `Logger.Translator` for more information.\n\n ## Backends\n\n `Logger` supports different backends where log messages are written to.\n\n The available backends by default are:\n\n * `:console` - logs messages to the console (enabled by default)\n\n Developers may also implement their own backends, an option that\n is explored in more detail below.\n\n The initial backends are loaded via the `:backends` configuration,\n which must be set before the `:logger` application is started.\n\n ### Console backend\n\n The console backend logs messages by printing them to the console. It supports\n the following options:\n\n * `:level` - the level to be logged by this backend.\n Note that messages are filtered by the general\n `:level` configuration for the `:logger` application first.\n\n * `:format` - the format message used to print logs.\n Defaults to: `\"\\n$time $metadata[$level] $levelpad$message\\n\"`.\n It may also be a `{module, function}` tuple that is invoked\n with the log level, the message, the current timestamp and\n the metadata.\n\n * `:metadata` - the metadata to be printed by `$metadata`.\n Defaults to an empty list (no metadata).\n Setting `:metadata` to `:all` prints all metadata. See\n the \"Metadata\" section for more information.\n\n * `:colors` - a keyword list of coloring options.\n\n * `:device` - the device to log error messages to. Defaults to\n `:user` but can be changed to something else such as `:standard_error`.\n\n * `:max_buffer` - maximum events to buffer while waiting\n for a confirmation from the IO device (default: 32).\n Once the buffer is full, the backend will block until\n a confirmation is received.\n\n The supported keys in the `:colors` keyword list are:\n\n * `:enabled` - boolean value that allows for switching the\n coloring on and off. Defaults to: `IO.ANSI.enabled?\/0`\n\n * `:debug` - color for debug messages. Defaults to: `:cyan`\n\n * `:info` - color for info messages. Defaults to: `:normal`\n\n * `:warn` - color for warn messages. Defaults to: `:yellow`\n\n * `:error` - color for error messages. Defaults to: `:red`\n\n See the `IO.ANSI` module for a list of colors and attributes.\n\n Here is an example of how to configure the `:console` backend in a\n `config\/config.exs` file:\n\n config :logger, :console,\n format: \"\\n$time $metadata[$level] $levelpad$message\\n\",\n metadata: [:user_id]\n\n ## Metadata\n\n In addition to the keys provided by the user via `Logger.metadata\/1`,\n the following extra keys are available to the `:metadata` list:\n\n * `:application` - the current application\n\n * `:module` - the current module\n\n * `:function` - the current function\n\n * `:file` - the current file\n\n * `:line` - the current line\n\n * `:pid` - the current process identifier\n\n * `:crash_reason` - a two-element tuple with the throw\/error\/exit reason\n as first argument and the stacktrace as second. A throw will always be\n `{:nocatch, term}`. An error is always an `Exception` struct. All other\n entries are exits. The console backend ignores this metadata by default\n but it can be useful to other backends, such as the ones that report\n errors to third-party services\n\n * `:initial_call` - the initial call that started the process\n\n * `:registered_name` - the process registered name as an atom\n\n Note that all metadata is optional and may not always be available.\n The `:module`, `:function`, `:line`, and similar metadata are automatically\n included when using `Logger` macros. `Logger.bare_log\/3` does not include\n any metadata beyond the `:pid` by default. Other metadata, such as\n `:crash_reason`, `:initial_call`, and `:registered_name` are extracted\n from Erlang\/OTP crash reports and available only in those cases.\n\n ### Custom formatting\n\n The console backend allows you to customize the format of your log messages\n with the `:format` option.\n\n You may set `:format` to either a string or a `{module, function}` tuple if\n you wish to provide your own format function. Here is an example of how to\n configure the `:console` backend in a `config\/config.exs` file:\n\n config :logger, :console,\n format: {MyConsoleLogger, :format}\n\n And here is an example of how you can define `MyConsoleLogger.format\/4` from the\n above configuration:\n\n defmodule MyConsoleLogger do\n def format(level, message, timestamp, metadata) do\n # Custom formatting logic...\n end\n end\n\n It is extremely important that **the formatting function does not fail**, as\n it will bring that particular logger instance down, causing your system to\n temporarily lose messages. If necessary, wrap the function in a `rescue` and\n log a default message instead:\n\n defmodule MyConsoleLogger do\n def format(level, message, timestamp, metadata) do\n # Custom formatting logic...\n rescue\n _ -> \"could not format: #{inspect({level, message, metadata})}\"\n end\n end\n\n The `{module, function}` will be invoked with four arguments:\n\n * the log level: an atom\n * the message: this is usually chardata, but in some cases it may not be.\n Since the formatting function should *never* fail, you need to prepare for\n the message being anything (and do something like the `rescue` in the example\n above)\n * the current timestamp: a term of type `t:Logger.Formatter.time\/0`\n * the metadata: a keyword list\n\n You can read more about formatting in `Logger.Formatter`.\n\n ### Custom backends\n\n Any developer can create their own `Logger` backend.\n Since `Logger` is an event manager powered by `:gen_event`,\n writing a new backend is a matter of creating an event\n handler, as described in the [`:gen_event`](http:\/\/erlang.org\/doc\/man\/gen_event.html)\n documentation.\n\n From now on, we will be using the term \"event handler\" to refer\n to your custom backend, as we head into implementation details.\n\n Once the `:logger` application starts, it installs all event handlers listed under\n the `:backends` configuration into the `Logger` event manager. The event\n manager and all added event handlers are automatically supervised by `Logger`.\n\n Once initialized, the handler should be designed to handle events\n in the following format:\n\n {level, group_leader, {Logger, message, timestamp, metadata}} | :flush\n\n where:\n\n * `level` is one of `:debug`, `:info`, `:warn`, or `:error`, as previously\n described\n * `group_leader` is the group leader of the process which logged the message\n * `{Logger, message, timestamp, metadata}` is a tuple containing information\n about the logged message:\n * the first element is always the atom `Logger`\n * `message` is the actual message (as chardata)\n * `timestamp` is the timestamp for when the message was logged, as a\n `{{year, month, day}, {hour, minute, second, millisecond}}` tuple\n * `metadata` is a keyword list of metadata used when logging the message\n\n It is recommended that handlers ignore messages where\n the group leader is in a different node than the one where\n the handler is installed. For example:\n\n def handle_event({_level, gl, {Logger, _, _, _}}, state)\n when node(gl) != node() do\n {:ok, state}\n end\n\n In the case of the event `:flush` handlers should flush any pending data. This\n event is triggered by `flush\/0`.\n\n Furthermore, backends can be configured via the\n `configure_backend\/2` function which requires event handlers\n to handle calls of the following format:\n\n {:configure, options}\n\n where `options` is a keyword list. The result of the call is\n the result returned by `configure_backend\/2`. The recommended\n return value for successful configuration is `:ok`.\n\n It is recommended that backends support at least the following\n configuration options:\n\n * `:level` - the logging level for that backend\n * `:format` - the logging format for that backend\n * `:metadata` - the metadata to include in that backend\n\n Check the implementation for `Logger.Backends.Console`, for\n examples on how to handle the recommendations in this section\n and how to process the existing options.\n \"\"\"\n\n @type backend :: :gen_event.handler()\n @type message :: IO.chardata() | String.Chars.t()\n @type level :: :error | :info | :warn | :debug\n @type metadata :: keyword()\n @levels [:error, :info, :warn, :debug]\n\n @metadata :logger_metadata\n @compile {:inline, __metadata__: 0}\n\n defp __metadata__ do\n Process.get(@metadata) || {true, []}\n end\n\n @doc \"\"\"\n Alters the current process metadata according the given keyword list.\n\n This function will merge the given keyword list into the existing metadata,\n with the exception of setting a key to `nil`, which will remove that key\n from the metadata.\n \"\"\"\n @spec metadata(metadata) :: :ok\n def metadata(keyword) do\n {enabled?, metadata} = __metadata__()\n Process.put(@metadata, {enabled?, into_metadata(keyword, metadata)})\n :ok\n end\n\n defp into_metadata([], metadata), do: metadata\n defp into_metadata(keyword, metadata), do: into_metadata(keyword, [], metadata)\n\n defp into_metadata([{key, nil} | keyword], prepend, metadata) do\n into_metadata(keyword, prepend, :lists.keydelete(key, 1, metadata))\n end\n\n defp into_metadata([{key, _} = pair | keyword], prepend, metadata) do\n into_metadata(keyword, [pair | prepend], :lists.keydelete(key, 1, metadata))\n end\n\n defp into_metadata([], prepend, metadata) do\n prepend ++ metadata\n end\n\n @doc \"\"\"\n Reads the current process metadata.\n \"\"\"\n @spec metadata() :: metadata\n def metadata() do\n __metadata__() |> elem(1)\n end\n\n @doc \"\"\"\n Resets the current process metadata to the given keyword list.\n \"\"\"\n @spec reset_metadata(metadata) :: :ok\n def reset_metadata(keywords \\\\ []) do\n {enabled?, _metadata} = __metadata__()\n Process.put(@metadata, {enabled?, []})\n metadata(keywords)\n end\n\n @doc \"\"\"\n Enables logging for the current process.\n\n Currently the only accepted PID is `self()`.\n \"\"\"\n @spec enable(pid) :: :ok\n def enable(pid) when pid == self() do\n Process.put(@metadata, {true, metadata()})\n :ok\n end\n\n @doc \"\"\"\n Disables logging for the current process.\n\n Currently the only accepted PID is `self()`.\n \"\"\"\n @spec disable(pid) :: :ok\n def disable(pid) when pid == self() do\n Process.put(@metadata, {false, metadata()})\n :ok\n end\n\n @doc \"\"\"\n Retrieves the `Logger` level.\n\n The `Logger` level can be changed via `configure\/1`.\n \"\"\"\n @spec level() :: level\n def level() do\n %{level: level} = Logger.Config.__data__()\n level\n end\n\n @doc \"\"\"\n Compares log levels.\n\n Receives two log levels and compares the `left` level\n against the `right` level and returns:\n\n * `:lt` if `left` is less than `right`\n * `:eq` if `left` and `right` are equal\n * `:gt` if `left` is greater than `right`\n\n ## Examples\n\n iex> Logger.compare_levels(:debug, :warn)\n :lt\n iex> Logger.compare_levels(:error, :info)\n :gt\n\n \"\"\"\n @spec compare_levels(level, level) :: :lt | :eq | :gt\n def compare_levels(level, level) do\n :eq\n end\n\n def compare_levels(left, right) do\n if level_to_number(left) > level_to_number(right), do: :gt, else: :lt\n end\n\n defp level_to_number(:debug), do: 0\n defp level_to_number(:info), do: 1\n defp level_to_number(:warn), do: 2\n defp level_to_number(:error), do: 3\n\n @doc \"\"\"\n Configures the logger.\n\n See the \"Runtime Configuration\" section in the `Logger` module\n documentation for the available options.\n \"\"\"\n @valid_options [\n :compile_time_application,\n :compile_time_purge_level,\n :compile_time_purge_matching,\n :sync_threshold,\n :truncate,\n :level,\n :utc_log,\n :discard_threshold,\n :translator_inspect_opts\n ]\n @spec configure(keyword) :: :ok\n def configure(options) do\n Logger.Config.configure(Keyword.take(options, @valid_options))\n end\n\n @doc \"\"\"\n Flushes the logger.\n\n This guarantees all messages sent to `Logger` prior to this call will\n be processed. This is useful for testing and it should not be called\n in production code.\n \"\"\"\n @spec flush :: :ok\n def flush do\n _ = Process.whereis(:error_logger) && :gen_event.which_handlers(:error_logger)\n :gen_event.sync_notify(Logger, :flush)\n end\n\n @doc \"\"\"\n Adds a new backend.\n\n ## Options\n\n * `:flush` - when `true`, guarantees all messages currently sent\n to `Logger` are processed before the backend is added\n\n \"\"\"\n @spec add_backend(atom, keyword) :: Supervisor.on_start_child()\n def add_backend(backend, opts \\\\ []) do\n _ = if opts[:flush], do: flush()\n\n case Logger.WatcherSupervisor.watch(Logger, Logger.Config.translate_backend(backend), backend) do\n {:ok, _} = ok ->\n Logger.Config.add_backend(backend)\n ok\n\n {:error, {:already_started, _pid}} ->\n {:error, :already_present}\n\n {:error, _} = error ->\n error\n end\n end\n\n @doc \"\"\"\n Removes a backend.\n\n ## Options\n\n * `:flush` - when `true`, guarantees all messages currently sent\n to `Logger` are processed before the backend is removed\n\n \"\"\"\n @spec remove_backend(atom, keyword) :: :ok | {:error, term}\n def remove_backend(backend, opts \\\\ []) do\n _ = if opts[:flush], do: flush()\n Logger.Config.remove_backend(backend)\n Logger.WatcherSupervisor.unwatch(Logger, Logger.Config.translate_backend(backend))\n end\n\n @doc \"\"\"\n Adds a new translator.\n \"\"\"\n @spec add_translator({module, function :: atom}) :: :ok\n def add_translator({mod, fun} = translator) when is_atom(mod) and is_atom(fun) do\n Logger.Config.add_translator(translator)\n end\n\n @doc \"\"\"\n Removes a translator.\n \"\"\"\n @spec remove_translator({module, function :: atom}) :: :ok\n def remove_translator({mod, fun} = translator) when is_atom(mod) and is_atom(fun) do\n Logger.Config.remove_translator(translator)\n end\n\n @doc \"\"\"\n Configures the given backend.\n\n The backend needs to be started and running in order to\n be configured at runtime.\n \"\"\"\n @spec configure_backend(backend, keyword) :: term\n def configure_backend(backend, options) when is_list(options) do\n :gen_event.call(Logger, Logger.Config.translate_backend(backend), {:configure, options})\n end\n\n @doc \"\"\"\n Logs a message dynamically.\n\n Opposite to `log\/3`, `debug\/2`, `info\/2`, and friends, the arguments\n given to `bare_log\/3` are always evaluated. However, you can pass\n anonymous functions to `bare_log\/3` and they will only be evaluated\n if there is something to be logged.\n \"\"\"\n @spec bare_log(level, message | (() -> message | {message, keyword}), keyword) ::\n :ok | {:error, :noproc} | {:error, term}\n def bare_log(level, chardata_or_fun, metadata \\\\ []) do\n case __should_log__(level) do\n :error -> :ok\n info -> __do_log__(info, chardata_or_fun, metadata)\n end\n end\n\n @doc false\n def __should_log__(level) when level in @levels do\n case __metadata__() do\n {true, pdict} ->\n %{mode: mode, level: min_level} = config = Logger.Config.__data__()\n\n if compare_levels(level, min_level) != :lt and mode != :discard do\n {level, config, pdict}\n else\n :error\n end\n\n {false, _} ->\n :error\n end\n end\n\n @doc false\n def __do_log__({level, config, pdict}, chardata_or_fun, metadata) when is_list(metadata) do\n %{utc_log: utc_log?, truncate: truncate, mode: mode} = config\n metadata = [pid: self()] ++ into_metadata(metadata, pdict)\n\n case normalize_message(chardata_or_fun, metadata) do\n {message, metadata} ->\n tuple = {Logger, truncate(message, truncate), Logger.Utils.timestamp(utc_log?), metadata}\n\n try do\n notify(mode, {level, Process.group_leader(), tuple})\n :ok\n rescue\n ArgumentError -> {:error, :noproc}\n catch\n :exit, reason -> {:error, reason}\n end\n\n :skip ->\n :ok\n end\n end\n\n @doc \"\"\"\n Logs a warning message.\n\n Returns `:ok` or an `{:error, reason}` tuple.\n\n ## Examples\n\n Logger.warn \"knob turned too far to the right\"\n Logger.warn fn -> \"dynamically calculated warning\" end\n Logger.warn fn -> {\"dynamically calculated warning\", [additional: :metadata]} end\n\n \"\"\"\n defmacro warn(chardata_or_fun, metadata \\\\ []) do\n maybe_log(:warn, chardata_or_fun, metadata, __CALLER__)\n end\n\n @doc \"\"\"\n Logs an info message.\n\n Returns `:ok` or an `{:error, reason}` tuple.\n\n ## Examples\n\n Logger.info \"mission accomplished\"\n Logger.info fn -> \"dynamically calculated info\" end\n Logger.info fn -> {\"dynamically calculated info\", [additional: :metadata]} end\n\n \"\"\"\n defmacro info(chardata_or_fun, metadata \\\\ []) do\n maybe_log(:info, chardata_or_fun, metadata, __CALLER__)\n end\n\n @doc \"\"\"\n Logs an error message.\n\n Returns `:ok` or an `{:error, reason}` tuple.\n\n ## Examples\n\n Logger.error \"oops\"\n Logger.error fn -> \"dynamically calculated error\" end\n Logger.error fn -> {\"dynamically calculated error\", [additional: :metadata]} end\n\n \"\"\"\n defmacro error(chardata_or_fun, metadata \\\\ []) do\n maybe_log(:error, chardata_or_fun, metadata, __CALLER__)\n end\n\n @doc \"\"\"\n Logs a debug message.\n\n Returns `:ok` or an `{:error, reason}` tuple.\n\n ## Examples\n\n Logger.debug \"hello?\"\n Logger.debug fn -> \"dynamically calculated debug\" end\n Logger.debug fn -> {\"dynamically calculated debug\", [additional: :metadata]} end\n\n \"\"\"\n defmacro debug(chardata_or_fun, metadata \\\\ []) do\n maybe_log(:debug, chardata_or_fun, metadata, __CALLER__)\n end\n\n @doc \"\"\"\n Logs a message with the given `level`.\n\n Returns `:ok` or an `{:error, reason}` tuple.\n\n The macros `debug\/2`, `warn\/2`, `info\/2`, and `error\/2` are\n preferred over this macro as they can automatically eliminate\n the call to `Logger` altogether at compile time if desired\n (see the documentation for the `Logger` module).\n \"\"\"\n defmacro log(level, chardata_or_fun, metadata \\\\ []) do\n macro_log(level, chardata_or_fun, metadata, __CALLER__)\n end\n\n defp macro_log(level, data, metadata, caller) do\n %{module: module, function: fun, file: file, line: line} = caller\n\n caller =\n compile_time_application_and_file(file) ++\n [module: module, function: form_fa(fun), line: line]\n\n {compile_metadata, quoted_metadata} =\n if Keyword.keyword?(metadata) do\n metadata = Keyword.merge(caller, metadata)\n {metadata, metadata}\n else\n {metadata,\n quote do\n Keyword.merge(unquote(caller), unquote(metadata))\n end}\n end\n\n compile_level = if is_atom(level), do: level, else: :error\n\n if compile_time_purge_matching?(compile_level, compile_metadata) do\n no_log(data, quoted_metadata)\n else\n quote do\n case Logger.__should_log__(unquote(level)) do\n :error -> :ok\n info -> Logger.__do_log__(info, unquote(data), unquote(quoted_metadata))\n end\n end\n end\n end\n\n defp compile_time_application_and_file(file) do\n if app = Application.get_env(:logger, :compile_time_application) do\n [application: app, file: Path.relative_to_cwd(file)]\n else\n [file: file]\n end\n end\n\n defp compile_time_purge_matching?(level, compile_metadata) do\n matching = Application.get_env(:logger, :compile_time_purge_matching, [])\n\n Enum.any?(matching, fn filter ->\n Enum.all?(filter, fn\n {:level_lower_than, min_level} ->\n compare_levels(level, min_level) == :lt\n\n {k, v} when is_atom(k) ->\n Keyword.fetch(compile_metadata, k) == {:ok, v}\n\n _ ->\n raise \"expected :compile_time_purge_matching to be a list of keyword lists, \" <>\n \"got: #{inspect(matching)}\"\n end)\n end)\n end\n\n # TODO: Either deprecate compile_time_purge_level in favor of\n # compile_time_purge_matching or document it again on 1.9 based\n # on feedback\n defp maybe_log(level, data, metadata, caller) do\n min_level = Application.get_env(:logger, :compile_time_purge_level, :debug)\n\n if compare_levels(level, min_level) != :lt do\n macro_log(level, data, metadata, caller)\n else\n no_log(data, metadata)\n end\n end\n\n defp no_log(data, metadata) do\n # We wrap the contents in an anonymous function\n # to avoid unused variable warnings.\n quote do\n _ = fn -> {unquote(data), unquote(metadata)} end\n :ok\n end\n end\n\n defp normalize_message(fun, metadata) when is_function(fun, 0) do\n case fun.() do\n {message, fun_metadata} -> {message, into_metadata(fun_metadata, metadata)}\n :skip -> :skip\n message -> {message, metadata}\n end\n end\n\n defp normalize_message(message, metadata) do\n {message, metadata}\n end\n\n defp truncate(data, n) when is_list(data) or is_binary(data), do: Logger.Utils.truncate(data, n)\n defp truncate(data, n), do: Logger.Utils.truncate(to_string(data), n)\n\n defp form_fa({name, arity}) do\n Atom.to_string(name) <> \"\/\" <> Integer.to_string(arity)\n end\n\n defp form_fa(nil), do: nil\n\n defp notify(:sync, msg), do: :gen_event.sync_notify(Logger, msg)\n defp notify(:async, msg), do: :gen_event.notify(Logger, msg)\nend\n","old_contents":"defmodule Logger do\n @moduledoc ~S\"\"\"\n A logger for Elixir applications.\n\n It includes many features:\n\n * Provides debug, info, warn, and error levels.\n\n * Supports multiple backends which are automatically\n supervised when plugged into `Logger`.\n\n * Formats and truncates messages on the client\n to avoid clogging `Logger` backends.\n\n * Alternates between sync and async modes to remain\n performant when required but also apply backpressure\n when under stress.\n\n * Plugs into Erlang's [`:logger`](http:\/\/erlang.org\/doc\/man\/logger.html)\n (from Erlang\/OTP 21) to convert terms to Elixir syntax or wraps\n Erlang's [`:error_logger`](http:\/\/erlang.org\/doc\/man\/error_logger.html)\n in earlier Erlang\/OTP versions to prevent it from overflowing.\n\n Logging is useful for tracking when an event of interest happens in your\n system. For example, it may be helpful to log whenever a user is deleted.\n\n def delete_user(user) do\n Logger.info \"Deleting user from the system: #{inspect(user)}\"\n # ...\n end\n\n The `Logger.info\/2` macro emits the provided message at the `:info`\n level. Note the arguments given to `info\/2` will only be evaluated\n if a message is logged. For instance, if the Logger level is\n set to `:warn`, `:info` messages are never logged and therefore the\n arguments given above won't even be executed.\n\n There are additional macros for other levels.\n\n Logger also allows log commands to be removed altogether via the\n `:compile_time_purge_matching` option (see below).\n\n For dynamically logging messages, see `bare_log\/3`. But note that\n `bare_log\/3` always evaluates its arguments (unless the argument\n is an anonymous function).\n\n ## Levels\n\n The supported levels are:\n\n * `:debug` - for debug-related messages\n * `:info` - for information of any kind\n * `:warn` - for warnings\n * `:error` - for errors\n\n ## Configuration\n\n `Logger` supports a wide range of configurations.\n\n This configuration is split in three categories:\n\n * Application configuration - must be set before the `:logger`\n application is started\n\n * Runtime configuration - can be set before the `:logger`\n application is started, but may be changed during runtime\n\n * Erlang configuration - options that handle integration with\n Erlang's logging facilities\n\n ### Application configuration\n\n The following configuration must be set via config files (such as\n `config\/config.exs`) before the `:logger` application is started.\n\n * `:backends` - the backends to be used. Defaults to `[:console]`.\n See the \"Backends\" section for more information.\n\n * `:compile_time_application` - sets the `:application` metadata value\n to the configured value at compilation time. This configuration is\n usually only useful for build tools to automatically add the\n application to the metadata for `Logger.debug\/2`, `Logger.info\/2`, etc.\n style of calls.\n\n * `:compile_time_purge_matching` - purges *at compilation time* all calls\n that match the given conditions. This means that `Logger` calls with\n level lower than this option will be completely removed at compile time,\n accruing no overhead at runtime. This configuration expects a list of\n keyword lists. Each keyword list contains a metadata key and the matching\n value that should be purged. A special key named `:level_lower_than` can\n be used to purge all messages with a lower logger level. Remember that\n if you want to purge log calls from a dependency, the dependency must be\n recompiled.\n\n For example, to configure the `:backends` and purge all calls that happen\n at compile time with level lower than `:info` in a `config\/config.exs` file:\n\n config :logger,\n backends: [:console],\n compile_time_purge_matching: [\n [level_lower_than: :info]\n ]\n\n If you want to purge all log calls from an application named `:foo` and only\n keep errors from `Bar.foo\/3`, you can set up two different matches:\n\n config :logger,\n compile_time_purge_matching: [\n [application: :foo],\n [module: Bar, function: \"foo\/3\", level_lower_than: :error]\n ]\n\n ### Runtime Configuration\n\n All configuration below can be set via config files (such as\n `config\/config.exs`) but also changed dynamically during runtime via\n `Logger.configure\/1`.\n\n * `:level` - the logging level. Attempting to log any message\n with severity less than the configured level will simply\n cause the message to be ignored. Keep in mind that each backend\n may have its specific level, too.\n\n * `:utc_log` - when `true`, uses UTC in logs. By default it uses\n local time (i.e., it defaults to `false`).\n\n * `:truncate` - the maximum message size to be logged (in bytes).\n Defaults to 8192 bytes. Note this configuration is approximate.\n Truncated messages will have `\" (truncated)\"` at the end.\n The atom `:infinity` can be passed to disable this behavior.\n\n * `:sync_threshold` - if the `Logger` manager has more than\n `:sync_threshold` messages in its queue, `Logger` will change\n to *sync mode*, to apply backpressure to the clients.\n `Logger` will return to *async mode* once the number of messages\n in the queue is reduced to `sync_threshold * 0.75` messages.\n Defaults to 20 messages. `:sync_threshold` can be set to `0` to force *sync mode*.\n\n * `:discard_threshold` - if the `Logger` manager has more than\n `:discard_threshold` messages in its queue, `Logger` will change\n to *discard mode* and messages will be discarded directly in the\n clients. `Logger` will return to *sync mode* once the number of\n messages in the queue is reduced to `discard_threshold * 0.75`\n messages. Defaults to 500 messages.\n\n * `:translator_inspect_opts` - when translating OTP reports and\n errors, the last message and state must be inspected in the\n error reports. This configuration allow developers to change\n how much and how the data should be inspected.\n\n For example, to configure the `:level` and `:truncate` options in a\n `config\/config.exs` file:\n\n config :logger,\n level: :warn,\n truncate: 4096\n\n ### Error logger configuration\n\n The following configuration applies to `Logger`'s wrapper around\n Erlang's logging functionalities. All the configurations below must\n be set before the `:logger` application starts.\n\n * `:handle_otp_reports` - redirects OTP reports to `Logger` so\n they are formatted in Elixir terms. This effectively disables\n Erlang standard logger. Defaults to `true`.\n\n * `:handle_sasl_reports` - redirects supervisor, crash and\n progress reports to `Logger` so they are formatted in Elixir\n terms. Your application must guarantee `:sasl` is started before\n `:logger`. This means you may see some initial reports written\n in Erlang syntax until the Logger application kicks in.\n Defaults to `false`.\n\n From Erlang\/OTP 21, `:handle_sasl_reports` only has an effect if\n `:handle_otp_reports` is true.\n\n The following configurations apply only for Erlang\/OTP 20 and earlier:\n\n * `:discard_threshold_for_error_logger` - if `:error_logger` has more than\n `discard_threshold` messages in its inbox, messages will be dropped\n until the message queue goes down to `discard_threshold * 0.75`\n entries. The threshold will be checked once again after 10% of threshold\n messages are processed, to avoid messages from being constantly dropped.\n For example, if the threshold is 500 (the default) and the inbox has\n 600 messages, 225 messages will dropped, bringing the inbox down to\n 375 (0.75 * threshold) entries and 50 (0.1 * threshold) messages will\n be processed before the threshold is checked once again.\n\n For example, to configure `Logger` to redirect all Erlang messages using a\n `config\/config.exs` file:\n\n config :logger,\n handle_otp_reports: true,\n handle_sasl_reports: true\n\n Furthermore, `Logger` allows messages sent by Erlang to be translated\n into an Elixir format via translators. Translators can be added at any\n time with the `add_translator\/1` and `remove_translator\/1` APIs. Check\n `Logger.Translator` for more information.\n\n ## Backends\n\n `Logger` supports different backends where log messages are written to.\n\n The available backends by default are:\n\n * `:console` - logs messages to the console (enabled by default)\n\n Developers may also implement their own backends, an option that\n is explored in more detail below.\n\n The initial backends are loaded via the `:backends` configuration,\n which must be set before the `:logger` application is started.\n\n ### Console backend\n\n The console backend logs messages by printing them to the console. It supports\n the following options:\n\n * `:level` - the level to be logged by this backend.\n Note that messages are filtered by the general\n `:level` configuration for the `:logger` application first.\n\n * `:format` - the format message used to print logs.\n Defaults to: `\"\\n$time $metadata[$level] $levelpad$message\\n\"`.\n It may also be a `{module, function}` tuple that is invoked\n with the log level, the message, the current timestamp and\n the metadata.\n\n * `:metadata` - the metadata to be printed by `$metadata`.\n Defaults to an empty list (no metadata).\n Setting `:metadata` to `:all` prints all metadata. See\n the \"Metadata\" section for more information.\n\n * `:colors` - a keyword list of coloring options.\n\n * `:device` - the device to log error messages to. Defaults to\n `:user` but can be changed to something else such as `:standard_error`.\n\n * `:max_buffer` - maximum events to buffer while waiting\n for a confirmation from the IO device (default: 32).\n Once the buffer is full, the backend will block until\n a confirmation is received.\n\n The supported keys in the `:colors` keyword list are:\n\n * `:enabled` - boolean value that allows for switching the\n coloring on and off. Defaults to: `IO.ANSI.enabled?\/0`\n\n * `:debug` - color for debug messages. Defaults to: `:cyan`\n\n * `:info` - color for info messages. Defaults to: `:normal`\n\n * `:warn` - color for warn messages. Defaults to: `:yellow`\n\n * `:error` - color for error messages. Defaults to: `:red`\n\n See the `IO.ANSI` module for a list of colors and attributes.\n\n Here is an example of how to configure the `:console` backend in a\n `config\/config.exs` file:\n\n config :logger, :console,\n format: \"\\n$time $metadata[$level] $levelpad$message\\n\",\n metadata: [:user_id]\n\n ## Metadata\n\n In addition to the keys provided by the user via `Logger.metadata\/1`,\n the following extra keys are available to the `:metadata` list:\n\n * `:application` - the current application\n\n * `:module` - the current module\n\n * `:function` - the current function\n\n * `:file` - the current file\n\n * `:line` - the current line\n\n * `:pid` - the current process identifier\n\n * `:crash_reason` - a two-element tuple with the throw\/error\/exit reason\n as first argument and the stacktrace as second. A throw will always be\n `{:nocatch, term}`. An error is always an `Exception` struct. All other\n entries are exits. The console backend ignores this metadata by default\n but it can be useful to other backends, such as the ones that report\n errors to third-party services\n\n * `:initial_call` - the initial call that started the process\n\n * `:registered_name` - the process registered name as an atom\n\n Note that all metadata is optional and may not always be available.\n The `:module`, `:function`, `:line`, and similar metadata are automatically\n included when using `Logger` macros. `Logger.bare_log\/3` does not include\n any metadata beyond the `:pid` by default. Other metadata, such as\n `:crash_reason`, `:initial_call`, and `:registered_name` are extracted\n from Erlang\/OTP crash reports and available only in those cases.\n\n ### Custom formatting\n\n The console backend allows you to customize the format of your log messages\n with the `:format` option.\n\n You may set `:format` to either a string or a `{module, function}` tuple if\n you wish to provide your own format function. Here is an example of how to\n configure the `:console` backend in a `config\/config.exs` file:\n\n config :logger, :console,\n format: {MyConsoleLogger, :format}\n\n And here is an example of how you can define `MyConsoleLogger.format\/4` from the\n above configuration:\n\n defmodule MyConsoleLogger do\n def format(level, message, timestamp, metadata) do\n # Custom formatting logic...\n end\n end\n\n It is extremely important that **the formatting function does not fail**, as\n it will bring that particular logger instance down, causing your system to\n temporarily lose messages. If necessary, wrap the function in a `rescue` and\n log a default message instead:\n\n defmodule MyConsoleLogger do\n def format(level, message, timestamp, metadata) do\n # Custom formatting logic...\n rescue\n _ -> \"could not format: #{inspect({level, message, metadata}})\"\n end\n end\n\n The `{module, function}` will be invoked with four arguments:\n\n * the log level: an atom\n * the message: this is usually chardata, but in some cases it may not be.\n Since the formatting function should *never* fail, you need to prepare for\n the message being anything (and do something like the `rescue` in the example\n above)\n * the current timestamp: a term of type `t:Logger.Formatter.time\/0`\n * the metadata: a keyword list\n\n You can read more about formatting in `Logger.Formatter`.\n\n ### Custom backends\n\n Any developer can create their own `Logger` backend.\n Since `Logger` is an event manager powered by `:gen_event`,\n writing a new backend is a matter of creating an event\n handler, as described in the [`:gen_event`](http:\/\/erlang.org\/doc\/man\/gen_event.html)\n documentation.\n\n From now on, we will be using the term \"event handler\" to refer\n to your custom backend, as we head into implementation details.\n\n Once the `:logger` application starts, it installs all event handlers listed under\n the `:backends` configuration into the `Logger` event manager. The event\n manager and all added event handlers are automatically supervised by `Logger`.\n\n Once initialized, the handler should be designed to handle events\n in the following format:\n\n {level, group_leader, {Logger, message, timestamp, metadata}} | :flush\n\n where:\n\n * `level` is one of `:debug`, `:info`, `:warn`, or `:error`, as previously\n described\n * `group_leader` is the group leader of the process which logged the message\n * `{Logger, message, timestamp, metadata}` is a tuple containing information\n about the logged message:\n * the first element is always the atom `Logger`\n * `message` is the actual message (as chardata)\n * `timestamp` is the timestamp for when the message was logged, as a\n `{{year, month, day}, {hour, minute, second, millisecond}}` tuple\n * `metadata` is a keyword list of metadata used when logging the message\n\n It is recommended that handlers ignore messages where\n the group leader is in a different node than the one where\n the handler is installed. For example:\n\n def handle_event({_level, gl, {Logger, _, _, _}}, state)\n when node(gl) != node() do\n {:ok, state}\n end\n\n In the case of the event `:flush` handlers should flush any pending data. This\n event is triggered by `flush\/0`.\n\n Furthermore, backends can be configured via the\n `configure_backend\/2` function which requires event handlers\n to handle calls of the following format:\n\n {:configure, options}\n\n where `options` is a keyword list. The result of the call is\n the result returned by `configure_backend\/2`. The recommended\n return value for successful configuration is `:ok`.\n\n It is recommended that backends support at least the following\n configuration options:\n\n * `:level` - the logging level for that backend\n * `:format` - the logging format for that backend\n * `:metadata` - the metadata to include in that backend\n\n Check the implementation for `Logger.Backends.Console`, for\n examples on how to handle the recommendations in this section\n and how to process the existing options.\n \"\"\"\n\n @type backend :: :gen_event.handler()\n @type message :: IO.chardata() | String.Chars.t()\n @type level :: :error | :info | :warn | :debug\n @type metadata :: keyword()\n @levels [:error, :info, :warn, :debug]\n\n @metadata :logger_metadata\n @compile {:inline, __metadata__: 0}\n\n defp __metadata__ do\n Process.get(@metadata) || {true, []}\n end\n\n @doc \"\"\"\n Alters the current process metadata according the given keyword list.\n\n This function will merge the given keyword list into the existing metadata,\n with the exception of setting a key to `nil`, which will remove that key\n from the metadata.\n \"\"\"\n @spec metadata(metadata) :: :ok\n def metadata(keyword) do\n {enabled?, metadata} = __metadata__()\n Process.put(@metadata, {enabled?, into_metadata(keyword, metadata)})\n :ok\n end\n\n defp into_metadata([], metadata), do: metadata\n defp into_metadata(keyword, metadata), do: into_metadata(keyword, [], metadata)\n\n defp into_metadata([{key, nil} | keyword], prepend, metadata) do\n into_metadata(keyword, prepend, :lists.keydelete(key, 1, metadata))\n end\n\n defp into_metadata([{key, _} = pair | keyword], prepend, metadata) do\n into_metadata(keyword, [pair | prepend], :lists.keydelete(key, 1, metadata))\n end\n\n defp into_metadata([], prepend, metadata) do\n prepend ++ metadata\n end\n\n @doc \"\"\"\n Reads the current process metadata.\n \"\"\"\n @spec metadata() :: metadata\n def metadata() do\n __metadata__() |> elem(1)\n end\n\n @doc \"\"\"\n Resets the current process metadata to the given keyword list.\n \"\"\"\n @spec reset_metadata(metadata) :: :ok\n def reset_metadata(keywords \\\\ []) do\n {enabled?, _metadata} = __metadata__()\n Process.put(@metadata, {enabled?, []})\n metadata(keywords)\n end\n\n @doc \"\"\"\n Enables logging for the current process.\n\n Currently the only accepted PID is `self()`.\n \"\"\"\n @spec enable(pid) :: :ok\n def enable(pid) when pid == self() do\n Process.put(@metadata, {true, metadata()})\n :ok\n end\n\n @doc \"\"\"\n Disables logging for the current process.\n\n Currently the only accepted PID is `self()`.\n \"\"\"\n @spec disable(pid) :: :ok\n def disable(pid) when pid == self() do\n Process.put(@metadata, {false, metadata()})\n :ok\n end\n\n @doc \"\"\"\n Retrieves the `Logger` level.\n\n The `Logger` level can be changed via `configure\/1`.\n \"\"\"\n @spec level() :: level\n def level() do\n %{level: level} = Logger.Config.__data__()\n level\n end\n\n @doc \"\"\"\n Compares log levels.\n\n Receives two log levels and compares the `left` level\n against the `right` level and returns:\n\n * `:lt` if `left` is less than `right`\n * `:eq` if `left` and `right` are equal\n * `:gt` if `left` is greater than `right`\n\n ## Examples\n\n iex> Logger.compare_levels(:debug, :warn)\n :lt\n iex> Logger.compare_levels(:error, :info)\n :gt\n\n \"\"\"\n @spec compare_levels(level, level) :: :lt | :eq | :gt\n def compare_levels(level, level) do\n :eq\n end\n\n def compare_levels(left, right) do\n if level_to_number(left) > level_to_number(right), do: :gt, else: :lt\n end\n\n defp level_to_number(:debug), do: 0\n defp level_to_number(:info), do: 1\n defp level_to_number(:warn), do: 2\n defp level_to_number(:error), do: 3\n\n @doc \"\"\"\n Configures the logger.\n\n See the \"Runtime Configuration\" section in the `Logger` module\n documentation for the available options.\n \"\"\"\n @valid_options [\n :compile_time_application,\n :compile_time_purge_level,\n :compile_time_purge_matching,\n :sync_threshold,\n :truncate,\n :level,\n :utc_log,\n :discard_threshold,\n :translator_inspect_opts\n ]\n @spec configure(keyword) :: :ok\n def configure(options) do\n Logger.Config.configure(Keyword.take(options, @valid_options))\n end\n\n @doc \"\"\"\n Flushes the logger.\n\n This guarantees all messages sent to `Logger` prior to this call will\n be processed. This is useful for testing and it should not be called\n in production code.\n \"\"\"\n @spec flush :: :ok\n def flush do\n _ = Process.whereis(:error_logger) && :gen_event.which_handlers(:error_logger)\n :gen_event.sync_notify(Logger, :flush)\n end\n\n @doc \"\"\"\n Adds a new backend.\n\n ## Options\n\n * `:flush` - when `true`, guarantees all messages currently sent\n to `Logger` are processed before the backend is added\n\n \"\"\"\n @spec add_backend(atom, keyword) :: Supervisor.on_start_child()\n def add_backend(backend, opts \\\\ []) do\n _ = if opts[:flush], do: flush()\n\n case Logger.WatcherSupervisor.watch(Logger, Logger.Config.translate_backend(backend), backend) do\n {:ok, _} = ok ->\n Logger.Config.add_backend(backend)\n ok\n\n {:error, {:already_started, _pid}} ->\n {:error, :already_present}\n\n {:error, _} = error ->\n error\n end\n end\n\n @doc \"\"\"\n Removes a backend.\n\n ## Options\n\n * `:flush` - when `true`, guarantees all messages currently sent\n to `Logger` are processed before the backend is removed\n\n \"\"\"\n @spec remove_backend(atom, keyword) :: :ok | {:error, term}\n def remove_backend(backend, opts \\\\ []) do\n _ = if opts[:flush], do: flush()\n Logger.Config.remove_backend(backend)\n Logger.WatcherSupervisor.unwatch(Logger, Logger.Config.translate_backend(backend))\n end\n\n @doc \"\"\"\n Adds a new translator.\n \"\"\"\n @spec add_translator({module, function :: atom}) :: :ok\n def add_translator({mod, fun} = translator) when is_atom(mod) and is_atom(fun) do\n Logger.Config.add_translator(translator)\n end\n\n @doc \"\"\"\n Removes a translator.\n \"\"\"\n @spec remove_translator({module, function :: atom}) :: :ok\n def remove_translator({mod, fun} = translator) when is_atom(mod) and is_atom(fun) do\n Logger.Config.remove_translator(translator)\n end\n\n @doc \"\"\"\n Configures the given backend.\n\n The backend needs to be started and running in order to\n be configured at runtime.\n \"\"\"\n @spec configure_backend(backend, keyword) :: term\n def configure_backend(backend, options) when is_list(options) do\n :gen_event.call(Logger, Logger.Config.translate_backend(backend), {:configure, options})\n end\n\n @doc \"\"\"\n Logs a message dynamically.\n\n Opposite to `log\/3`, `debug\/2`, `info\/2`, and friends, the arguments\n given to `bare_log\/3` are always evaluated. However, you can pass\n anonymous functions to `bare_log\/3` and they will only be evaluated\n if there is something to be logged.\n \"\"\"\n @spec bare_log(level, message | (() -> message | {message, keyword}), keyword) ::\n :ok | {:error, :noproc} | {:error, term}\n def bare_log(level, chardata_or_fun, metadata \\\\ []) do\n case __should_log__(level) do\n :error -> :ok\n info -> __do_log__(info, chardata_or_fun, metadata)\n end\n end\n\n @doc false\n def __should_log__(level) when level in @levels do\n case __metadata__() do\n {true, pdict} ->\n %{mode: mode, level: min_level} = config = Logger.Config.__data__()\n\n if compare_levels(level, min_level) != :lt and mode != :discard do\n {level, config, pdict}\n else\n :error\n end\n\n {false, _} ->\n :error\n end\n end\n\n @doc false\n def __do_log__({level, config, pdict}, chardata_or_fun, metadata) when is_list(metadata) do\n %{utc_log: utc_log?, truncate: truncate, mode: mode} = config\n metadata = [pid: self()] ++ into_metadata(metadata, pdict)\n\n case normalize_message(chardata_or_fun, metadata) do\n {message, metadata} ->\n tuple = {Logger, truncate(message, truncate), Logger.Utils.timestamp(utc_log?), metadata}\n\n try do\n notify(mode, {level, Process.group_leader(), tuple})\n :ok\n rescue\n ArgumentError -> {:error, :noproc}\n catch\n :exit, reason -> {:error, reason}\n end\n\n :skip ->\n :ok\n end\n end\n\n @doc \"\"\"\n Logs a warning message.\n\n Returns `:ok` or an `{:error, reason}` tuple.\n\n ## Examples\n\n Logger.warn \"knob turned too far to the right\"\n Logger.warn fn -> \"dynamically calculated warning\" end\n Logger.warn fn -> {\"dynamically calculated warning\", [additional: :metadata]} end\n\n \"\"\"\n defmacro warn(chardata_or_fun, metadata \\\\ []) do\n maybe_log(:warn, chardata_or_fun, metadata, __CALLER__)\n end\n\n @doc \"\"\"\n Logs an info message.\n\n Returns `:ok` or an `{:error, reason}` tuple.\n\n ## Examples\n\n Logger.info \"mission accomplished\"\n Logger.info fn -> \"dynamically calculated info\" end\n Logger.info fn -> {\"dynamically calculated info\", [additional: :metadata]} end\n\n \"\"\"\n defmacro info(chardata_or_fun, metadata \\\\ []) do\n maybe_log(:info, chardata_or_fun, metadata, __CALLER__)\n end\n\n @doc \"\"\"\n Logs an error message.\n\n Returns `:ok` or an `{:error, reason}` tuple.\n\n ## Examples\n\n Logger.error \"oops\"\n Logger.error fn -> \"dynamically calculated error\" end\n Logger.error fn -> {\"dynamically calculated error\", [additional: :metadata]} end\n\n \"\"\"\n defmacro error(chardata_or_fun, metadata \\\\ []) do\n maybe_log(:error, chardata_or_fun, metadata, __CALLER__)\n end\n\n @doc \"\"\"\n Logs a debug message.\n\n Returns `:ok` or an `{:error, reason}` tuple.\n\n ## Examples\n\n Logger.debug \"hello?\"\n Logger.debug fn -> \"dynamically calculated debug\" end\n Logger.debug fn -> {\"dynamically calculated debug\", [additional: :metadata]} end\n\n \"\"\"\n defmacro debug(chardata_or_fun, metadata \\\\ []) do\n maybe_log(:debug, chardata_or_fun, metadata, __CALLER__)\n end\n\n @doc \"\"\"\n Logs a message with the given `level`.\n\n Returns `:ok` or an `{:error, reason}` tuple.\n\n The macros `debug\/2`, `warn\/2`, `info\/2`, and `error\/2` are\n preferred over this macro as they can automatically eliminate\n the call to `Logger` altogether at compile time if desired\n (see the documentation for the `Logger` module).\n \"\"\"\n defmacro log(level, chardata_or_fun, metadata \\\\ []) do\n macro_log(level, chardata_or_fun, metadata, __CALLER__)\n end\n\n defp macro_log(level, data, metadata, caller) do\n %{module: module, function: fun, file: file, line: line} = caller\n\n caller =\n compile_time_application_and_file(file) ++\n [module: module, function: form_fa(fun), line: line]\n\n {compile_metadata, quoted_metadata} =\n if Keyword.keyword?(metadata) do\n metadata = Keyword.merge(caller, metadata)\n {metadata, metadata}\n else\n {metadata,\n quote do\n Keyword.merge(unquote(caller), unquote(metadata))\n end}\n end\n\n compile_level = if is_atom(level), do: level, else: :error\n\n if compile_time_purge_matching?(compile_level, compile_metadata) do\n no_log(data, quoted_metadata)\n else\n quote do\n case Logger.__should_log__(unquote(level)) do\n :error -> :ok\n info -> Logger.__do_log__(info, unquote(data), unquote(quoted_metadata))\n end\n end\n end\n end\n\n defp compile_time_application_and_file(file) do\n if app = Application.get_env(:logger, :compile_time_application) do\n [application: app, file: Path.relative_to_cwd(file)]\n else\n [file: file]\n end\n end\n\n defp compile_time_purge_matching?(level, compile_metadata) do\n matching = Application.get_env(:logger, :compile_time_purge_matching, [])\n\n Enum.any?(matching, fn filter ->\n Enum.all?(filter, fn\n {:level_lower_than, min_level} ->\n compare_levels(level, min_level) == :lt\n\n {k, v} when is_atom(k) ->\n Keyword.fetch(compile_metadata, k) == {:ok, v}\n\n _ ->\n raise \"expected :compile_time_purge_matching to be a list of keyword lists, \" <>\n \"got: #{inspect(matching)}\"\n end)\n end)\n end\n\n # TODO: Either deprecate compile_time_purge_level in favor of\n # compile_time_purge_matching or document it again on 1.9 based\n # on feedback\n defp maybe_log(level, data, metadata, caller) do\n min_level = Application.get_env(:logger, :compile_time_purge_level, :debug)\n\n if compare_levels(level, min_level) != :lt do\n macro_log(level, data, metadata, caller)\n else\n no_log(data, metadata)\n end\n end\n\n defp no_log(data, metadata) do\n # We wrap the contents in an anonymous function\n # to avoid unused variable warnings.\n quote do\n _ = fn -> {unquote(data), unquote(metadata)} end\n :ok\n end\n end\n\n defp normalize_message(fun, metadata) when is_function(fun, 0) do\n case fun.() do\n {message, fun_metadata} -> {message, into_metadata(fun_metadata, metadata)}\n :skip -> :skip\n message -> {message, metadata}\n end\n end\n\n defp normalize_message(message, metadata) do\n {message, metadata}\n end\n\n defp truncate(data, n) when is_list(data) or is_binary(data), do: Logger.Utils.truncate(data, n)\n defp truncate(data, n), do: Logger.Utils.truncate(to_string(data), n)\n\n defp form_fa({name, arity}) do\n Atom.to_string(name) <> \"\/\" <> Integer.to_string(arity)\n end\n\n defp form_fa(nil), do: nil\n\n defp notify(:sync, msg), do: :gen_event.sync_notify(Logger, msg)\n defp notify(:async, msg), do: :gen_event.notify(Logger, msg)\nend\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Elixir"} {"commit":"ca5a40d3f3762a3ec57e1ff821144b17764a8be5","subject":"observer task first attempt on production","message":"observer task first attempt on production\n","repos":"rubencaro\/bottler","old_file":"lib\/mix\/tasks\/bottler.ex","new_file":"lib\/mix\/tasks\/bottler.ex","new_contents":"require Bottler.Helpers, as: H\nalias Bottler, as: B\n\ndefmodule Mix.Tasks.Deploy do\n\n @moduledoc \"\"\"\n Build a release file, ship it to remote servers, install it, and restart\n the app. No hot code swap for now.\n\n Use like `mix deploy`.\n\n `prod` environment is used by default. Use like\n `MIX_ENV=other_env mix deploy` to force it to `other_env`.\n \"\"\"\n\n use Mix.Task\n\n def run(_args) do\n H.set_prod_environment\n c = H.read_and_validate_config\n :ok = B.release c\n {:ok, _} = B.ship c\n {:ok, _} = B.install c\n {:ok, _} = B.restart c\n :ok\n end\n\nend\n\ndefmodule Mix.Tasks.Bottler.Release do\n\n @moduledoc \"\"\"\n Build a release file. Use like `mix bottler.release`.\n\n `prod` environment is used by default. Use like\n `MIX_ENV=other_env mix bottler.release` to force it to `other_env`.\n \"\"\"\n\n use Mix.Task\n\n def run(_args) do\n H.set_prod_environment\n c = H.read_and_validate_config\n :ok = B.release c\n :ok\n end\n\nend\n\ndefmodule Mix.Tasks.Bottler.Ship do\n\n @moduledoc \"\"\"\n Ship a release file to configured remote servers.\n Use like `mix bottler.ship`.\n\n `prod` environment is used by default. Use like\n `MIX_ENV=other_env mix bottler.ship` to force it to `other_env`.\n \"\"\"\n\n use Mix.Task\n\n def run(_args) do\n H.set_prod_environment\n c = H.read_and_validate_config\n {:ok, _} = B.ship c\n :ok\n end\n\nend\n\ndefmodule Mix.Tasks.Bottler.Install do\n\n @moduledoc \"\"\"\n Install a shipped file on configured remote servers.\n Use like `mix bottler.install`.\n\n `prod` environment is used by default. Use like\n `MIX_ENV=other_env mix bottler.install` to force it to `other_env`.\n \"\"\"\n\n use Mix.Task\n\n def run(_args) do\n H.set_prod_environment\n c = H.read_and_validate_config\n {:ok, _} = B.install c\n :ok\n end\n\nend\n\ndefmodule Mix.Tasks.Bottler.Restart do\n\n @moduledoc \"\"\"\n Touch `tmp\/restart` on configured remote servers.\n That expects to have `Harakiri` or similar software reacting to that.\n Use like `mix bottler.restart`.\n\n `prod` environment is used by default. Use like\n `MIX_ENV=other_env mix bottler.restart` to force it to `other_env`.\n \"\"\"\n\n use Mix.Task\n\n def run(_args) do\n H.set_prod_environment\n c = H.read_and_validate_config\n {:ok, _} = B.restart c\n :ok\n end\n\nend\n\ndefmodule Mix.Tasks.Bottler.Rollback do\n\n @moduledoc \"\"\"\n Simply move the _current_ link to the previous release and restart to\n apply. It's quite faster than to deploy a previous release, that is\n also possible.\n\n Be careful because the _previous release_ may be different on each server.\n It's up to you to keep all your servers rollback-able (yeah).\n\n Use like `mix bottler.rollback`.\n\n `prod` environment is used by default. Use like\n `MIX_ENV=other_env mix bottler.rollback` to force it to `other_env`.\n \"\"\"\n\n use Mix.Task\n\n def run(_args) do\n H.set_prod_environment\n c = H.read_and_validate_config\n {:ok, _} = B.rollback c\n :ok\n end\n\nend\n\ndefmodule Mix.Tasks.Bottler.HelperScripts do\n\n @moduledoc \"\"\"\n This generates some helper scripts using project's current config\n information, such as target servers. You can run this task repeatedly to\n force regeneration of these scripts to reflect config changes.\n\n Generated scripts are located under `\/.bottler\/scripts` (configurable\n via `scripts_folder`). It will also generate links to those scripts on a\n configurable folder to add them to your system PATH. The configuration param\n is `script_links_folder`. Its default value is `~\/local\/bin`.\n\n Use like `mix bottler.helper_scripts`.\n\n The generated scripts' list is short by now:\n\n * A `_` script for each target server configured. That script\n will open an SSH session with this server. When you want to access one of your\n production servers, the one that is called `daisy42`, for the project called\n `motion`, then you can invoke `motion_daisy42` on any terminal and it will\n open up an SSH shell for you.\n \"\"\"\n\n use Mix.Task\n\n def run(_args) do\n H.set_prod_environment\n c = H.read_and_validate_config\n :ok = B.helper_scripts c\n :ok\n end\n\nend\n\ndefmodule Mix.Tasks.Bottler.Observer do\n use Mix.Task\n\n def run(args) do\n args |> inspect |> IO.puts\n\n name = args |> List.first |> String.to_existing_atom\n\n H.set_prod_environment\n c = H.read_and_validate_config\n c |> inspect |> IO.puts\n \n ip = c[:servers][name][:ip]\n port = get_port(c, ip)\n\n # auto closing tunnel\n :os.cmd('killall epmd') # free distributed erlang port\n cmd = \"ssh -f -L 4369:localhost:4369 -L #{port}:localhost:#{port} #{c[:remote_user]}@#{ip} sleep 30;\" |> to_char_list\n IO.puts \"Opening tunnel: #{cmd}\"\n :os.cmd(cmd) |> to_string |> IO.puts\n\n # observer\n IO.puts \"Starting observer...\"\n cmd = \"elixir --name observerunique@127.0.0.1 --cookie monikako --no-halt #{__DIR__}\/..\/..\/..\/lib\/mix\/scripts\/observer.exs\" |> to_char_list\n IO.puts cmd\n :os.cmd(cmd) |> to_string |> IO.puts\n\n IO.puts \"Done\"\n end\n\n defp get_port(c, ip) do\n cmd = \"ssh #{c[:remote_user]}@#{ip} \\\"source \/home\/#{c[:remote_user]}\/.bash_profile && epmd -names\\\" | grep dean | cut -d \\\" \\\" -f 5\"\n :os.cmd(cmd |> to_char_list) |> to_string |> String.strip(?\\n)\n end\nend\n","old_contents":"require Bottler.Helpers, as: H\nalias Bottler, as: B\n\ndefmodule Mix.Tasks.Deploy do\n\n @moduledoc \"\"\"\n Build a release file, ship it to remote servers, install it, and restart\n the app. No hot code swap for now.\n\n Use like `mix deploy`.\n\n `prod` environment is used by default. Use like\n `MIX_ENV=other_env mix deploy` to force it to `other_env`.\n \"\"\"\n\n use Mix.Task\n\n def run(_args) do\n H.set_prod_environment\n c = H.read_and_validate_config\n :ok = B.release c\n {:ok, _} = B.ship c\n {:ok, _} = B.install c\n {:ok, _} = B.restart c\n :ok\n end\n\nend\n\ndefmodule Mix.Tasks.Bottler.Release do\n\n @moduledoc \"\"\"\n Build a release file. Use like `mix bottler.release`.\n\n `prod` environment is used by default. Use like\n `MIX_ENV=other_env mix bottler.release` to force it to `other_env`.\n \"\"\"\n\n use Mix.Task\n\n def run(_args) do\n H.set_prod_environment\n c = H.read_and_validate_config\n :ok = B.release c\n :ok\n end\n\nend\n\ndefmodule Mix.Tasks.Bottler.Ship do\n\n @moduledoc \"\"\"\n Ship a release file to configured remote servers.\n Use like `mix bottler.ship`.\n\n `prod` environment is used by default. Use like\n `MIX_ENV=other_env mix bottler.ship` to force it to `other_env`.\n \"\"\"\n\n use Mix.Task\n\n def run(_args) do\n H.set_prod_environment\n c = H.read_and_validate_config\n {:ok, _} = B.ship c\n :ok\n end\n\nend\n\ndefmodule Mix.Tasks.Bottler.Install do\n\n @moduledoc \"\"\"\n Install a shipped file on configured remote servers.\n Use like `mix bottler.install`.\n\n `prod` environment is used by default. Use like\n `MIX_ENV=other_env mix bottler.install` to force it to `other_env`.\n \"\"\"\n\n use Mix.Task\n\n def run(_args) do\n H.set_prod_environment\n c = H.read_and_validate_config\n {:ok, _} = B.install c\n :ok\n end\n\nend\n\ndefmodule Mix.Tasks.Bottler.Restart do\n\n @moduledoc \"\"\"\n Touch `tmp\/restart` on configured remote servers.\n That expects to have `Harakiri` or similar software reacting to that.\n Use like `mix bottler.restart`.\n\n `prod` environment is used by default. Use like\n `MIX_ENV=other_env mix bottler.restart` to force it to `other_env`.\n \"\"\"\n\n use Mix.Task\n\n def run(_args) do\n H.set_prod_environment\n c = H.read_and_validate_config\n {:ok, _} = B.restart c\n :ok\n end\n\nend\n\ndefmodule Mix.Tasks.Bottler.Rollback do\n\n @moduledoc \"\"\"\n Simply move the _current_ link to the previous release and restart to\n apply. It's quite faster than to deploy a previous release, that is\n also possible.\n\n Be careful because the _previous release_ may be different on each server.\n It's up to you to keep all your servers rollback-able (yeah).\n\n Use like `mix bottler.rollback`.\n\n `prod` environment is used by default. Use like\n `MIX_ENV=other_env mix bottler.rollback` to force it to `other_env`.\n \"\"\"\n\n use Mix.Task\n\n def run(_args) do\n H.set_prod_environment\n c = H.read_and_validate_config\n {:ok, _} = B.rollback c\n :ok\n end\n\nend\n\ndefmodule Mix.Tasks.Bottler.HelperScripts do\n\n @moduledoc \"\"\"\n This generates some helper scripts using project's current config\n information, such as target servers. You can run this task repeatedly to\n force regeneration of these scripts to reflect config changes.\n\n Generated scripts are located under `\/.bottler\/scripts` (configurable\n via `scripts_folder`). It will also generate links to those scripts on a\n configurable folder to add them to your system PATH. The configuration param\n is `script_links_folder`. Its default value is `~\/local\/bin`.\n\n Use like `mix bottler.helper_scripts`.\n\n The generated scripts' list is short by now:\n\n * A `_` script for each target server configured. That script\n will open an SSH session with this server. When you want to access one of your\n production servers, the one that is called `daisy42`, for the project called\n `motion`, then you can invoke `motion_daisy42` on any terminal and it will\n open up an SSH shell for you.\n \"\"\"\n\n use Mix.Task\n\n def run(_args) do\n H.set_prod_environment\n c = H.read_and_validate_config\n :ok = B.helper_scripts c\n :ok\n end\n\nend\n\ndefmodule Mix.Tasks.Bottler.Observer do\n use Mix.Task\n\n def run(args) do\n args |> inspect |> IO.puts\n\n name = args |> List.first |> String.to_existing_atom\n\n H.set_prod_environment\n c = H.read_and_validate_config\n c |> inspect |> IO.puts\n port = get_port(c, args)\n IO.puts port\n\n ip = c[:servers][name][:ip]\n\n # auto closing tunnel\n :os.cmd('killall epmd') # free distributed erlang port\n cmd = \"ssh -f -L 4369:localhost:4369 -L #{port}:localhost:#{port} #{c[:remote_user]}@#{ip} sleep 30;\" |> to_char_list\n IO.puts cmd\n :os.cmd(cmd) |> to_string |> IO.puts\n IO.puts \"Tunnel is open.\"\n\n # observer\n IO.puts \"Starting observer...\"\n cmd = \"elixir --name observerunique@127.0.0.1 --cookie monikako --no-halt lib\/mix\/scripts\/observer.exs\" |> to_char_list\n IO.puts cmd\n :os.cmd(cmd) |> to_string |> IO.puts\n\n IO.puts \"Done\"\n end\n\n defp get_port(c, args) do\n # cmd = \"ssh #{c[:remote_user]}@#{args |> List.first} \\\"source \/home\/#{c[:remote_user]}\/.bash_profile && epmd -names\\\" | grep dean | cut -d \\\" \\\" -f 5\"\n cmd = \"ssh epdp@#{args |> List.first} \\\"source \/home\/epdp\/.bash_profile && epmd -names\\\" | grep dean | cut -d \\\" \\\" -f 5\"\n :os.cmd(cmd |> to_char_list) |> to_string |> String.strip(?\\n)\n end\nend\n","returncode":0,"stderr":"","license":"mit","lang":"Elixir"} {"commit":"ed3d39167542fa594746e7297372405c08b6d9ba","subject":"Fix typo.","message":"Fix typo.","repos":"KazuCocoa\/phoenix_html,phoenixframework\/phoenix_html,henrik\/phoenix_html,felipesere\/phoenix_html,drapergeek\/phoenix_html,mgwidmann\/phoenix_html","old_file":"lib\/phoenix_html\/form.ex","new_file":"lib\/phoenix_html\/form.ex","new_contents":"defmodule Phoenix.HTML.Form do\n @moduledoc ~S\"\"\"\n Helpers related to producing HTML forms.\n\n The functions in this module can be used in three\n distinct scenario:\n\n * with model data - when information to populate\n the form comes from a model\n\n * with connection data - when a form is created based\n on the information in the connection (aka `Plug.Conn`)\n\n * without form data - when the functions are used directly,\n outside of a form\n\n We will explore all three scenarios below.\n\n ## With model data\n\n The entry point for defining forms in Phoenix is with\n the `form_for\/4` function. For this example, we will\n use `Ecto.Changeset`, which integrate nicely with Phoenix\n forms via the `phoenix_ecto` package.\n\n Imagine you have the following action in your controller:\n\n def new(conn, _params) do\n changeset = User.changeset(%User{})\n render conn, \"new.html\", changeset: changeset\n end\n\n where `User.changeset\/2` is defined as follows:\n\n def changeset(user, params \\\\ nil) do\n cast(user, params)\n end\n\n Now a `@changeset` assign is available in views which we\n can pass to the form:\n\n <%= form_for @changeset, user_path(@conn, :create), fn f -> %>\n