D4no0

D4no0

Credo rule to dissallow calls to specific functions

I have a project currently that I want to ban calls to some functions. Currently, all of those functions are either from a library or standard elixir library.

Since I have already a credo pipeline running, I was wondering if it would be possible to define a custom rule for this, or maybe there is already an existing rule for this (I could not find it).

Has anyone managed to do this successfully?

Marked As Solved

sodapopcan

sodapopcan

I made one to ban assign/2. then is next :slight_smile:

defmodule GelaSkins.Credo.NoCallsToAssign2 do
  @moduledoc """
  Checks that `Phoenix.LiveView.assign/2` can't be called.
  """

  # you can configure the basics of your check via the `use Credo.Check` call
  use Credo.Check,
    base_priority: :high,
    category: :custom,
    exit_status: 0,
    explanations: [
      check: """
      Always use `assign/3` in favour of `assign/2`.

      This forces a pipeline when using multiple assigns.  The advantage here is
      that assigns may be added, removed, and re-ordered easily (no commas to deal
      with) making diffs nicer.  It also means you must explicitly name the
      parameters accepted by LiveComponents.  You cannot simply do
      `assign(socket, assigns)`.
      """
    ]

  @doc false
  @impl true
  def run(%SourceFile{} = source_file, params \\ []) do
    # IssueMeta helps us pass down both the source_file and params of a check
    # run to the lower levels where issues are created, formatted and returned
    issue_meta = IssueMeta.for(source_file, params)

    # Finally, we can run our custom made analysis.
    # In this example, we look for lines in source code matching our regex:
    Credo.Code.prewalk(source_file, &traverse(&1, &2, [], issue_meta))
  end

  defp traverse({:|>, _, [{:socket, _, _}, {:assign, meta, [_]}]} = ast, issues, [], issue_meta) do
    {ast, issues ++ [issue_for(:assign, meta[:line], issue_meta)]}
  end

  defp traverse({:assign, meta, [{:socket, _, _}, [_]]} = ast, issues, [], issue_meta) do
    {ast, issues ++ [issue_for(:assign, meta[:line], issue_meta)]}
  end

  defp traverse(ast, issues, _, _issue_meta) do
    {ast, issues}
  end

  defp issue_for(trigger, line_no, issue_meta) do
    format_issue(
      issue_meta,
      message: "Only use assign/3",
      line_no: line_no,
      trigger: trigger
    )
  end
end

It also checks for a single pipe into assign. I can’t remember why I did this instead of using the existing credo rule but I assume it’s because sometimes I’m ok with single pipes. This was a while ago.

Also Liked

sodapopcan

sodapopcan

I’d say it’s definitely fine to do all of them in a single check. Certainly less code. I think the only advantage in using multiple checks is giving more details about why specific functions are banned per error as opposed to just a big “don’t a or b or c or d” but if you aren’t distributing it then one big one is fine.

Rereading this a perhaps slightly clearer way to write the check would be:

  defp traverse({:assign, meta, [args, [_]]} = ast, issues, [], issue_meta)
       when elem(args, 0) == :socket and len(args) == 3 do
    {ast, issues ++ [issue_for(:assign, meta[:line], issue_meta)]}
  end

EDIT: I royally hecked up my refactor there—it made no sense as I was using elem on a list and && in a guard :grimacing: :sweat_smile: Fixed it, but now it’s only maybe marginally better.

EDIT 2: I should really stop answering questions first thing in the morning. I re-edited it, not that is really matters :upside_down_face: I also realized the way I had it there it’s possible to get around the rule by not calling the socket variable socket, so perhaps you don’t even want to check for that. Ok, I’m really done now (probably, lol).

sodapopcan

sodapopcan

@D4no0 is talking about outright banning functions everywhere. This is certainly a linting concern. Boundary is used to describe application boundaries, what we’re talking about in this thread is stylistic choices of what functions can be used.

krasenyp

krasenyp

I haven’t seen such rule and don’t know how to implement it but I’m curious about your use case as I too want to do something similar. In my case it’s related to capability-based development.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement