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
.dockerignore
.github/workflows/docker-latest.yml
... # omitted for brevity
tests/test_img_to_ascii.py
version
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
|-- MANIFEST.in
|-- README.md
|-- main.py
|-- pyproject.toml
|-- requirements.txt
|-- scripts
| |-- gh_create_release.sh
| `-- version_validation.sh
|-- setup.cfg
|-- setup.py
|-- src
| `-- appy
| |-- __init__.py
| |-- __main__.py
| |-- assets
| | |-- __init__.py
| | `-- meirg-logo.jpg
| |-- core
| | |-- __init__.py
| | `-- app.py
| `-- utils
| |-- __init__.py
| |-- img_ascii.py
| `-- message.py
|-- tests
| |-- test_api.py
| |-- test_greet.py
| `-- test_img_to_ascii.py
`-- version
9 directories, 27 files
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
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
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.
Top comments (0)