View Source Xfile (xfile v0.1.0)

Xfile contains augmentations of the built-in File module, such as supporting streams, recursion, and programmatic filtering.

Link to this section Summary

Functions

As Xfile.ls/2, but returns raw results on success or raises on :error.

Like File.ls/1, this returns the list of files in the given directory, but it makes available some useful options to support recursive listing and filtering results programmatically.

Link to this section Functions

Link to this function

ls!(directory, opts \\ [])

View Source
@spec ls!(directory :: Path.t(), opts :: Keyword.t()) :: Enumerable.t() | none()

As Xfile.ls/2, but returns raw results on success or raises on :error.

Link to this function

ls(directory, opts \\ [])

View Source
@spec ls(directory :: Path.t(), opts :: Keyword.t()) ::
  {:ok, Enumerable.t()} | {:error, any()}

Like File.ls/1, this returns the list of files in the given directory, but it makes available some useful options to support recursive listing and filtering results programmatically.

Stream

Unlike File.ls/1, Xfile.ls/2 returns its result as a Stream, so you must remember to convert it to a list via Enum.to_list/1 if you are not lazily evaluating its result.

options

Options

  • :recursive indicates whether the directory and its subdirectories should be recursively searched. This can be expressed either as a simple boolean or as a positive integer indicating the maximum depth (where false is equivalent to 0 and would list only the contents of the given directory). Default: true

  • :filter can be either a regular expression to be used with String.match?/2 OR an arity 1 function that receives the full file path and returns a boolean value. If the filter operation returns true, the file will be included in the output. Any other output will cause the file to be filtered from the output. Optional.

examples

Examples

Use a regular expression to return only .txt files:

iex> {:ok, stream} = Xfile.ls("path/to/files", filter: ~r/\.txt$/)
{:ok, #Function<59.58486609/2 in Stream.transform/3>}
iex> Enum.to_list(stream)
[
  "path/to/files/a.txt",
  "path/to/files/b.txt",
  "path/to/files/subdir/c.txt"
]

Use a function to apply more complex logic to filter the results:

iex> {:ok, stream} = Xfile.ls("mydir", filter: fn x ->
  stat = File.stat!(x)
  stat.size > 1024
end)
{:ok, #Function<59.58486609/2 in Stream.transform/3>}
iex> Enum.to_list(stream)
[
  "mydir/big-file",
  "mydir/big-file2",
  # ...
]

Limit the depth of the recursion to the given directory and its subdirectories, but no further:

iex> {:ok, stream} = Xfile.ls("top/dir", recursive: 1)
{:ok, #Function<59.58486609/2 in Stream.transform/3>}
iex> Enum.to_list(stream)
[
  "top/dir/a",
  "top/dir/b",
  # ...
  "top/dir/sub1/x",
  "top/dir/sub1/y"
]