13

Is there a way to make tree not show files that are ignored in .gitignore?

  • 2
    If you really want to consider all possible ignored files, try to parse the output of git ls-files. – Franklin Yu Jun 22 '16 at 7:31
3

This might help: list git ignored files in an almost-compatible way for tree filter:

function tree-git-ignore {
    # tree respecting gitignore

    local ignored=$(git ls-files -ci --others --directory --exclude-standard)
    local ignored_filter=$(echo "$ignored" \
                    | egrep -v "^#.*$|^[[:space:]]*$" \
                    | sed 's~^/~~' \
                    | sed 's~/$~~' \
                    | tr "\\n" "|")
    tree --prune -I ".git|${ignored_filter: : -1}" "$@"
}
7

Tree supports the -I flag.

-I pattern
   Do not list those files that match the wild-card pattern.

Tree supports a single pattern which will exclude all files/directories that match it.

Git's ignore files are a bit more complicated:

Exclusion can come from multiple files, $HOME/.config/git/ignore, the output of git config --get core.excludesfile, .gitignore (per directory), ~/.gitignore, and more (see man gitignore).

Another problem is the patterns that tree supports differs from what git does (as noted by @Brad Urani).

But we can get close-ish ...

tree -I "$(grep -hvE '^$|^#' {~/,,$(git rev-parse --show-toplevel)/}.gitignore|sed 's:/$::'|tr \\n '\|')"

Or as a function:

function gtree {
    git_ignore_files=("$(git config --get core.excludesfile)" .gitignore ~/.gitignore)
    ignore_pattern="$(grep -hvE '^$|^#' "${git_ignore_files[@]}" 2>/dev/null|sed 's:/$::'|tr '\n' '\|')"
    if git status &> /dev/null && [[ -n "${ignore_pattern}" ]]; then
      tree -I "${ignore_pattern}" "${@}"
    else 
      tree "${@}"
    fi
}
  • Nice! Am I correct that the fact that this is not removing comment lines from .gitignore will cause problems? – Brad Urani Jun 22 '16 at 5:56
  • I guess it's also not going to respect .gitignore files outside the home dir 🤔 – Brad Urani Jun 22 '16 at 6:23
  • @BradUrani - i've updated my answer to use git commands to try find the file. What that returns will depend on what setting you have. – DarkHeart Jun 22 '16 at 7:18
  • This isn't working for me, I think because my ~/.gitignore is a symlink. I've been trying to find a way to rely on git to tell me what's ignored, but all my efforts to find the right combination keep running into difficulties or ambiguous situations. – Brad Urani Jun 22 '16 at 21:31
  • Also it looks like tree -I does respect all the globbing options that .gitignore does which makes me think there's no perfect solution. Best approximation I came up with last night is echo "node_modules|tmp|_build" > ~/.treeignore and tree -I "$(cat ~/.treeignore)" – Brad Urani Jun 22 '16 at 21:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.