Skip to content

Instantly share code, notes, and snippets.

@bew
Created April 10, 2020 02:07
Show Gist options
  • Select an option

  • Save bew/3a824eda77f1cd5ae69fa2e5daed2d78 to your computer and use it in GitHub Desktop.

Select an option

Save bew/3a824eda77f1cd5ae69fa2e5daed2d78 to your computer and use it in GitHub Desktop.
My first Nix semi-complex-expr! Show files with type in a directory
# Used docs:
#
# Builtins reference (not exaustive): https://nixos.org/nix/manual/#ssec-builtins
#
# nixpkgs in lib/attrsets.nix: (all functions for manipulating attributes sets)
# https://github.com/NixOS/nixpkgs/blob/c7e0e9ed5abd0043e50ee371129fcb8640264fc4/lib/attrsets.nix
#
# nixpkgs in lib/lists.nix: (all functions for manipulating lists)
# https://github.com/NixOS/nixpkgs/blob/6ff181331874fa1004ef187d97367bd762dc8c46/lib/lists.nix#L1
dirPath:
with builtins;
let
lib = (import <nixpkgs> {}).lib;
# type: set of 'filename = filetype;'
dirContent = readDir dirPath;
# type: list of '{name = filename; type = filetype;}'
filesInfo = lib.mapAttrsToList (k: v: {name = k; type = v;}) dirContent;
fileTypeToChar = fileType:
let
mapping = {
directory = "d";
symlink = "l";
regular = "f";
};
in mapping.${fileType} or "?";
traceFileInfo = {type, name}: ret:
trace "${fileTypeToChar type} '${name}'" ret;
traceFileInfoAndReturnTrue = info: traceFileInfo info true;
results = map traceFileInfoAndReturnTrue filesInfo;
in lib.count (x: x) results
$ nix eval '(import ./show-dir.nix) "/"'
trace: l 'bin'
trace: d 'boot'
trace: d 'data'
trace: d 'dev'
trace: d 'etc'
trace: d 'fix'
trace: d 'home'
trace: l 'lib'
trace: l 'lib64'
trace: d 'lost+found'
trace: d 'mnt'
trace: d 'nas'
trace: d 'nix'
trace: d 'opt'
trace: d 'proc'
trace: d 'root'
trace: d 'run'
trace: l 'sbin'
trace: d 'srv'
trace: d 'sys'
trace: l 't'
trace: d 'tmp'
trace: d 'usr'
trace: d 'var'
24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment