Open a IO session to use within a CLI

Hello
I’m building a command line tool with elixir.

And I’m looking for way to allow the user write on the terminal as much as they want and them get that content from the terminal.

I seen IO.read(:stdio, :line) but once you hit \n it will stop

You can also pass an integer saying how many characters you want to read but if I set that to a high number is there any way to close IO and get the output?

Are there any bindings with the terminal that I can use with Elixir.

I hope my question makes any sense.

Thanks!

How do you want to know if the user has finished typing? A common way to decide that he has finished was by typing an end command followed by enter, so why not do it today as well?

def read_undtil_end(acc \\ [])
def read_until_end(["end\n"|acc]), do: acc |> Enum.reverse |> Enum.join
def read_until_end(acc), do:  read_until_end([IO.read(:line)|acc])

This example is missing propper errorhandling

2 Likes

Thank you @NobbZ I’m getting used to the functional and recursive way of working with Elixir.

I will try this.

@NobbZ also regarding testing I’m having some issues, the CLI as for the username using gets have you found a simple way for mocking or having a work around. I have ExUnit.CaptureIO but I think is not going to work

Nevermind I found the solution here Testing recursive IO prompt

1 Like