DEV Community

Cover image for Printing Git Tree

Printing Git Tree

unfor19 profile image Meir Gabay ・2 min read

From time to time I need to print my git project's tree, so I can share it in the docs, or just go through it quickly to make sure it makes sense.

The required applications for the task

  • git - we'll use it to find out which files and directories are committed in the current branch
  • tree - a recursive directory listing program that produces a depth indented listing of files. We'll use it to print beautifully the output of git

Getting Committed Files And Directories

The following command will recursively go through all the files and directories that were committed in the current git HEAD and print their names only.

$ git ls-tree HEAD -r --name-only

... # omitted for brevity
Enter fullscreen mode Exit fullscreen mode

The output above is the exact output we need for tree.

Printing Git Tree

Now, it's time to pipe the git ls-tree output to tree. We'll be using the --fromfile flag

--fromfile Reads a directory listing from a file rather than the file-system. Paths provided on the command line are files to read from rather than directories to search. The dot (.) directory indicates that tree should read paths from standard input.

$ git ls-tree -r --name-only HEAD | tree --fromfile

|-- .dockerignore
|-- .github
|   `-- workflows
|       |-- docker-latest.yml
|       `-- release.yml
|-- .gitignore
|-- Dockerfile
|-- pyproject.toml
|-- requirements.txt
|-- scripts
|   |--
|   `--
|-- setup.cfg
|-- src
|   `-- appy
|       |--
|       |--
|       |-- assets
|       |   |--
|       |   `-- meirg-logo.jpg
|       |-- core
|       |   |--
|       |   `--
|       `-- utils
|           |--
|           |--
|           `--
|-- tests
|   |--
|   |--
|   `--
`-- version

9 directories, 27 files
Enter fullscreen mode Exit fullscreen mode

How beautiful is that? :)

Creating An Alias

I don't really remember this command, I've just set it as an alias in $HOME/bash_aliases, here are the lines that I've added

treegit_func(){ git ls-tree -r --name-only HEAD | tree --fromfile; }
alias treegit=treegit_func
Enter fullscreen mode Exit fullscreen mode

Now I can simply run in the terminal treegit and print the committed files and directories of the current HEAD, beautifully.

$ treegit

# Same output as before
Enter fullscreen mode Exit fullscreen mode

Final Words

The examples in this blog post were done on this git repository - unfor19/python-project

I hope you find it useful, feel free to start a discussion, or ask questions below.

Discussion (0)

Forem Open with the Forem app