157

In my Githubs repos documentation I want to represent a directory tree structure like this:

enter image description here

Is there a way to do that with Github flavoured markdown, besides just creating it with ascii art?

So basically like this question, but I'm wondering if there is a github specific solution.

2

20 Answers 20

207

I got resolver the problem in this way:

  1. Insert command tree in bash.

Example

enter image description here

  1. Create a README.md in github repository and copy bash result
  2. Insert in .md file within markdown code

Example

enter image description here 4. See the output and be happy =) enter image description here

2
  • 4
    Here's an example you can copy, I found this on github Nov 19, 2018 at 4:24
  • 3
    Note that in some cases, using "```bash ... ```" will highlight some of the words. Instead, you can use the "pre" tag: "<pre> ... </pre>". Jun 2, 2020 at 8:08
76

I wrote a small script that does the trick:

#!/bin/bash

#File: tree-md

tree=$(tree -tf --noreport -I '*~' --charset ascii $1 |
       sed -e 's/| \+/  /g' -e 's/[|`]-\+/ */g' -e 's:\(* \)\(\(.*/\)\([^/]\+\)\):\1[\4](\2):g')

printf "# Project tree\n\n${tree}"

Example:

Original tree command:

$ tree
.
├── dir1
│   ├── file11.ext
│   └── file12.ext
├── dir2
│   ├── file21.ext
│   ├── file22.ext
│   └── file23.ext
├── dir3
├── file_in_root.ext
└── README.md

3 directories, 7 files

Markdown tree command:

$ ./tree-md .
# Project tree

.
 * [tree-md](./tree-md)
 * [dir2](./dir2)
   * [file21.ext](./dir2/file21.ext)
   * [file22.ext](./dir2/file22.ext)
   * [file23.ext](./dir2/file23.ext)
 * [dir1](./dir1)
   * [file11.ext](./dir1/file11.ext)
   * [file12.ext](./dir1/file12.ext)
 * [file_in_root.ext](./file_in_root.ext)
 * [README.md](./README.md)
 * [dir3](./dir3)

Rendered result:

(Links are not visible in Stackoverflow...)

Project tree
  • tree-md
  • dir2
    • file21.ext
    • file22.ext
    • file23.ext
  • dir1
    • file11.ext
    • file12.ext
  • file_in_root.ext
  • README.md
  • dir3
7
  • Such a great idea! Keeping my minutes in git and now I can update the README TOC easily. Thank you! Did you think to make it more configurable? Oct 26, 2016 at 0:09
  • 1
    Also, suggest this nodejs package by @michalbe github.com/michalbe/md-file-tree Nov 24, 2016 at 22:29
  • Is there a way to limit the tree depth ?
    – Sami-L
    Jul 27, 2018 at 11:57
  • 2
    This didn't work for mac.!! I used brew install tree to install tree. Jul 20, 2019 at 16:10
  • Dude... this is lovely Oct 9, 2019 at 16:54
36

Not directly, no. You'd have to hand create it and put it in yourself. Assuming you are using a *nix box locally and are using utf, then tree will generate it nicely (I believe that is what generated the example you used above).

Assuming you mean the readme.md as the documentation target, then I think the only way you could automate it would be a git pre-commit hook that ran tree and embedded it into your readme file. You'd want to do a diff to make sure you only updated the readme if the output changed.

Otoh if you are maintaining seperate docs via github pages, then what you could do, is switch to using jekyll (or another generator) locally and pushing the static pages yourself. Then you could potentially implement the changes you want either as a plugin / shell script* / manual changes (if they won't vary much), or use the same method as above.

*If you integrate it into a commit hook, you can avoid adding any extra steps to changing your pages.

6
  • 1
    Thanks for the answer, but that is not what I meant. I meant to ask if there is a way to represent a directory tree in your readme (with nesting etc.) not generate it. I've edited the question for clarity.
    – user1694077
    Jun 2, 2014 at 8:49
  • As in one with links such as the sort you'd get in apache if you don't have an index.html? Jun 2, 2014 at 8:50
  • No, what I mean is if there is an easy way to generate something like this: imgur.com/OHfWdLk in your readme.
    – user1694077
    Jun 2, 2014 at 8:54
  • 3
    On a Mac, you can install the tree command with Homebrew, i.e. brew install tree. Then from the directory I wanted to represent I ran tree . >> tree.txt and then copied and edited the text in my README.md file. Did exactly what I needed!
    – morphatic
    Dec 24, 2018 at 1:31
  • 2
    Why this answer is accepted? There are many good utility available to do this. Please don't do this manual. Check out this. github.com/michalbe/md-file-tree Jul 23, 2019 at 1:59
24

Here is a useful git alias that works for me.

git config --global alias.tree '! git ls-tree --full-name --name-only -t -r HEAD | sed -e "s/[^-][^\/]*\//   |/g" -e "s/|\([^ ]\)/|-- \1/"'

Here is the output of git tree

jonavon@XPS13:~/projects/roman-numerals$ git tree
.gitignore
pom.xml
src
   |-- main
   |   |-- java
   |   |   |-- com
   |   |   |   |-- foxguardsolutions
   |   |   |   |   |-- jonavon
   |   |   |   |   |   |-- AbstractFile.java
   |   |   |   |   |   |-- roman
   |   |   |   |   |   |   |-- Main.java
   |   |   |   |   |   |   |-- Numeral.java
   |   |   |   |   |   |   |-- RomanNumberInputFile.java
   |   |   |   |   |   |   |-- RomanNumeralToDecimalEvaluator.java
   |-- test
   |   |-- java
   |   |   |-- com
   |   |   |   |-- foxguardsolutions
   |   |   |   |   |-- jonavon
   |   |   |   |   |   |-- roman
   |   |   |   |   |   |   |-- InterpretSteps.java
   |   |   |   |   |   |   |-- RunCukesTest.java
   |   |-- resources
   |   |   |-- com
   |   |   |   |-- foxguardsolutions
   |   |   |   |   |-- jonavon
   |   |   |   |   |   |-- roman
   |   |   |   |   |   |   |-- Interpret.feature
   |   |   |-- sample-input.txt

The comparable tree command

jonavon@XPS13:~/projects/roman-numerals$ tree -n
.
├── pom.xml
├── src
│   ├── main
│   │   └── java
│   │       └── com
│   │           └── foxguardsolutions
│   │               └── jonavon
│   │                   ├── AbstractFile.java
│   │                   └── roman
│   │                       ├── Main.java
│   │                       ├── Numeral.java
│   │                       ├── RomanNumberInputFile.java
│   │                       └── RomanNumeralToDecimalEvaluator.java
│   └── test
│       ├── java
│       │   └── com
│       │       └── foxguardsolutions
│       │           └── jonavon
│       │               └── roman
│       │                   ├── InterpretSteps.java
│       │                   └── RunCukesTest.java
│       └── resources
│           ├── com
│           │   └── foxguardsolutions
│           │       └── jonavon
│           │           └── roman
│           │               └── Interpret.feature
│           └── sample-input.txt
└── target
    ├── classes
    │   └── com
    │       └── foxguardsolutions
    │           └── jonavon
    │               ├── AbstractFile.class
    │               └── roman
    │                   ├── Main.class
    │                   ├── Numeral.class
    │                   ├── RomanNumberInputFile.class
    │                   └── RomanNumeralToDecimalEvaluator.class
    ├── generated-sources
    │   └── annotations
    └── maven-status
        └── maven-compiler-plugin
            └── compile
                └── default-compile
                    ├── createdFiles.lst
                    └── inputFiles.lst

30 directories, 17 files

Clearly tree has better output, but I like this way because it only shows the relevant source files and not the .git directory and compiled binaries.

19

I made a node module to automate this task: mddir

Usage

node mddir "../relative/path/"

To install: npm install mddir -g

To generate markdown for current directory: mddir

To generate for any absolute path: mddir /absolute/path

To generate for a relative path: mddir ~/Documents/whatever.

The md file gets generated in your working directory.

Currently ignores node_modules, and .git folders.

Troubleshooting

If you receive the error 'node\r: No such file or directory', the issue is that your operating system uses different line endings and mddir can't parse them without you explicitly setting the line ending style to Unix. This usually affects Windows, but also some versions of Linux. Setting line endings to Unix style has to be performed within the mddir npm global bin folder.

Line endings fix

Get npm bin folder path with:

npm config get prefix

Cd into that folder

brew install dos2unix

dos2unix lib/node_modules/mddir/src/mddir.js

This converts line endings to Unix instead of Dos

Then run as normal with: node mddir "../relative/path/".

Example generated markdown file structure 'directoryList.md'

    |-- .bowerrc
    |-- .jshintrc
    |-- .jshintrc2
    |-- Gruntfile.js
    |-- README.md
    |-- bower.json
    |-- karma.conf.js
    |-- package.json
    |-- app
        |-- app.js
        |-- db.js
        |-- directoryList.md
        |-- index.html
        |-- mddir.js
        |-- routing.js
        |-- server.js
        |-- _api
            |-- api.groups.js
            |-- api.posts.js
            |-- api.users.js
            |-- api.widgets.js
        |-- _components
            |-- directives
                |-- directives.module.js
                |-- vendor
                    |-- directive.draganddrop.js
            |-- helpers
                |-- helpers.module.js
                |-- proprietary
                    |-- factory.actionDispatcher.js
            |-- services
                |-- services.cardTemplates.js
                |-- services.cards.js
                |-- services.groups.js
                |-- services.posts.js
                |-- services.users.js
                |-- services.widgets.js
        |-- _mocks
            |-- mocks.groups.js
            |-- mocks.posts.js
            |-- mocks.users.js
            |-- mocks.widgets.js
2
  • Thanks for the node package. A couple of comments 1) is there an option to get the output just as text instead of as JSON. I had to further parse the JSON output before I could paste it into markdown. 2) Is there a way to make it so you don't have to run it from the node_modules/mddir/src/ directory? For instance I'd like to run node ~./src > dir-struct.txt from my project directory and paste the contents of dir-struct.txt directly into my markdown.
    – wilblack
    May 16, 2017 at 16:20
  • on windows u can use the "tree" command, and i betcha u can find one for linux too
    – user7111260
    Apr 10, 2021 at 14:00
14

The best way to do this is to surround your tree in the triple backticks to denote a code block. For more info, see the markdown docs: http://daringfireball.net/projects/markdown/syntax#code

1
  • 2
    Different from what the OP asked but exactly the tip I needed. Thanks!
    – Mike Ellis
    Aug 13, 2016 at 21:08
13

In Linux the tree command can be used to list all the files/dirs under the directory.

If someone just wants to list directories and not files, use the -d option:

$ tree -d

data
├── cats_vs_dogs
│   ├── test_cat_dog
│   ├── testing
│   │   ├── cats
│   │   └── dogs
│   └── training
│       ├── cats
│       └── dogs
└── PetImages
    ├── Cat
    └── Dog

Copy the output and wrap it into 3 backticks ``` in the markdown file.

0
8

None of the above solution worked for me completely on my mac.

The best solution I found this is to use the utility created here.

https://github.com/michalbe/md-file-tree

Once you have installed the utility npm install md-file-tree -g then you can simply run to get all files tree

md-file-tree . > README.md
2
  • I have to say, this is the best tool. Thank you!
    – dorinand
    Sep 9, 2021 at 21:45
  • 1
    Was googling a while to find such tool. works perfectly and as expected. Thanks for sharing!
    – Naofumi
    Oct 18, 2022 at 16:04
7

Yes there is a way, In your readme.md file just copy & paste the tree you have generated in between three of back quotes like as if you are writing a code in markdown, it will work. Please see the below attachment. ``` your tree ```

enter image description here

1
  • 2
    If anyone's wondering, here's the vscode extension: link Dec 30, 2021 at 13:32
6

You can also check this tree-extended package. It can be used as a command line app by using node >= 6.x.

It is very similar to tree but also has the option of configuring the max deep in the tree, that is one of the awful things of it. Also you can filter by using .gitignore file.

enter image description here


UPDATE

You can also use this VsCode plugin (tree-extended-vscode) it is easier to use and you can do it from the VSCode's visual interface and just pass the arguments over there.

1
  • 1
    note to others: To convert something like this to markdown, just include the three backticks.
    – user45254
    Sep 5, 2018 at 2:41
3

You can use <pre> tags as I did in one of my projects.

1
  • How is this different than what the OP mentioned? Aug 24, 2017 at 7:54
3

Insert command tree in bash.

Also, there is a DOS comnand "tree". You can displays directory paths and files in each subdirectory with command:

tree /F

https://web.csulb.edu/~murdock/tree.html

2

Simple tree command will do the job. For example: tree -o readme.md will print the tree structure of your current working directory and write it to readme.md. Then open readme.md file in one of text editor like Sublime and wrap its content within a pair of triple backticks (```).

FYI: you might have to brew install tree in OSX if it's not already installed. In Linux and Windows it should just work fine. Also in windows you might have to replace hyphen with forward slash.

I hope this helps.

2

For those who want a quick solution:

There is a way to get a output to the console similar to the output from tree, by typing the following command into your terminal:

ls -R YOURFOLDER | grep ':$' | sed -e 's/:$//' -e 's/[^\/]*\//|  /g' -e 's/|  \([^|]\)/|–– \1/g' 

This alternative is mentioned in this documentation: https://wiki.ubuntuusers.de/tree/

Then the output can be copied and encapsuled inside a .md file with code block back tics, like mentioned in Jonathas B.C.'s answer.

But be aware that it also outputs all node modules folders in a node project. And in tree you can do something like

tree -I node_modules

to exlude the node modules folder.

1
  • I like this solution as it only outputs folders - which is what I want in my README.
    – djm
    Aug 12, 2022 at 9:03
1

If you are working on windows write tree /f inside the directory you want to achieve that in command prompt. This should do your job. you can copy and paste the output on markdown surrounded my triple back ticks i.e. '''{tree structure here}'''

1

One easier way I found is to use ASCII Tree Generator online free tool https://ascii-tree-generator.com/. Once you create your directory tree with this nice tool, you can paste the tree into your Markdown file surrounded by backticks (```). And here is the result:

my-app/
├─ node_modules/
├─ public/
│  ├─ favicon.ico
│  ├─ index.html
│  ├─ robots.txt
├─ src/
│  ├─ index.css
│  ├─ index.js
├─ .gitignore
├─ package.json
├─ README.md

If you need more info about code syntax in Markdown, please check out this page https://www.markdownguide.org/basic-syntax/#code.

Hope that helps !

0

I just like to generate it with UTF-8 and link it to every file and folder to navigate really easily. Please take a look at the example here.

The denerated markdown file

1
  • Instead if voting it down. Tell me what additional information do you need. You can generate a markdown however you like. I do it with my own personal library, but my preference may be different than yours. Dec 5, 2018 at 13:32
0

This python module (I am the author) generates directory-trees dynamically based on a specific tag added to the project's files.

For example, inserting in a file a comment line like the following:

# [treesource] the file description

Will generate an entry for this file in the generate tree. The tree, by default, shows only the files that have been tagged.

A generated tree looks like this:

$ python -m treesource
.
├── example_folder\
│   ├── first_subfolder\ (a documented folder)
│   │   ├── sub-sub1\
│   │   │   └── file3.sh (this is file 3)
│   │   ├── sub-sub2\
│   │   │   └── file4.cpp (this is file 4)
│   │   └── random_file.rdm (a documented file)
│   ├── second_subfolder\ (a documented folder with no documented files)
│   ├── a_text_file.txt (a text file)
│   ├── my_javascript.js (this is file 1)
│   └── test.py (a python script)
└── README.md (The main readme)

and can directly be exported in makdown format:

.
├── example_folder\
│ ├── first_subfolder\ a documented folder
│ │ ├── sub-sub1\
│ │ │ └── file3.sh this is file 3
│ │ ├── sub-sub2\
│ │ │ └── file4.cpp this is file 4
│ │ └── random_file.rdm a documented file
│ ├── second_subfolder\ a documented folder with no documented files
│ ├── a_text_file.txt a text file
│ ├── my_javascript.js this is file 1
│ └── test.py a python script
└── README.md The main readme\

0

it works in my MAC.


➜  examle-web git:(develop) ✗ tree src -d -L 1
src
├── api
├── assets
├── biz
├── constants
├── hooks
├── layout
├── queries
├── routes
├── store
├── themes
├── types
├── ui-component
├── utils
├── views
└── zustands

0

I have written a simple python code, which can give you the best result exactly what you want. Output sample :

Your_code
    ├── .github/
    │   ├── ISSUE_TEMPLATE/
    │   │   ├── bug_report.md
    │   │   └── feature_request.md
    │   └── workflows/
    │       ├── greet-contributors.yml
    │       └── python-publish.yml
    ├── Applications/
    │   ├── Alarm/
    │   │   ├── alarmtiming.py
    │   │   └── audio.wav
    │   ├── Audio Visualization Tool/
    │   │   ├── README.md
    │   │   └── source-code.py
    │   ├── Birthday Reminder/
    │   │   ├── README.md
    │   │   └── source-code.py
    │   ├── CSPRNG/
    │   │   ├── CSPRNG_1/
    │   │   │   ├── FreshProject.py
    │   │   │   └── GETdata.py
    │   │   ├── CSPRNG_2/
    │   │   │   ├── FreshProject1.py
    │   │   │   └── recordAudio.py
    │   │   ├── CSPRNG_3/
    │   │   │   └── FreshProject2.py
    │   │   ├── CSPRNG_4/
    │   │   │   └── FreshProject3.py
    │   │   └── README.md
    │   ├── Calendar/
    │   │   └── calendar.py
    │   ├── Extract mp3 from mp4/
    │   │   ├── README.md
    │   │   ├── source-code.py
    │   │   └── source-code.pyw
    │   ├── Link Shortener and Extractor/
    │   │   ├── README.md
    │   │   └── source-code.py
    │   ├── Merge Multiple PDF/
    │   │   ├── README.md
    │   │   └── source-code.py
    │   ├── Noscreensaver/
    │   │   ├── Readme.md
    │   │   └── noscreensaver.py
    │   ├── Object Detection/
    │   │   └── ObjectDetection.py.txt
    │   ├── Paint/
    │   │   └── paint.py
    │   ├── Password Protech PDF/
    │   │   ├── README.md
    │   │   └── source-code.py
    │   ├── README.md
    │   ├── Random Password Generator/
    │   │   ├── README.md
    │   │   ├── random pass.py
    │   │   └── source-code.py
    │   ├── ScreenShot/
    │   │   └── screenshot.py
    │   ├── Search Engine/
    │   │   └── wikipediasearch.py
    │   ├── Terminal Tricks/
    │   │   ├── README.md
    │   │   ├── source-code-color.py
    │   │   └── source-code-funky.py
    │   ├── Voice Recorder/
    │   │   ├── README.md
    │   │   └── source-code.py
    │   ├── Windows Notification/
    │   │   ├── README.md
    │   │   ├── jokes-desktop-notifier.py
    │   │   ├── source-code-custom.py
    │   │   └── source-code-timer.py
    │   ├── audiobook/
    │   │   ├── audiobook.py
    │   │   └── book.txt
    │   └── pong_game/
    │       ├── __pycache__/
    │       │   ├── ball.cpython-310.pyc
    │       │   ├── paddle.cpython-310.pyc
    │       │   └── scoreboard.cpython-310.pyc
    │       ├── ball.py
    │       ├── main.py
    │       ├── paddle.py
    │       ├── scoreboard.py
    │       └── tempCodeRunnerFile.py
    ├── CODE_OF_CONDUCT.md
    ├── CONTRIBUTING.md
    ├── LICENSE
    ├── README.md
    └── passpdf.py

Find the code below :

import os

def generate_tree_structure(root_dir, output_file, indent="    "):
    with open(output_file, 'w') as readme:
        generate_tree(root_dir, readme, indent)


def generate_tree(directory, readme, indent):
    items = os.listdir(directory)
    items.sort()  # Sort items to ensure consistent order

    for i, item in enumerate(items):
        item_path = os.path.join(directory, item)
        is_last_item = i == len(items) - 1

        if os.path.isdir(item_path):
            readme.write(f"{indent}{'└── ' if is_last_item else '├── '}{item}/\n")
            next_indent = indent + ("    " if is_last_item else "│   ")
            generate_tree(item_path, readme, next_indent)
        elif os.path.isfile(item_path):
            readme.write(f"{indent}{'└── ' if is_last_item else '├── '}{item}\n")


if __name__ == '__main__':
    project_folder = '/Users/buddha/my_project/'
    readme_file = 'project_structure3.txt'

    generate_tree_structure(project_folder, readme_file)
    print(f"Project structure generated and saved in '{readme_file}'.")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.