For the manual approach, git provides a shell script to generate the env var __git_ps1 for this very purpose.[1]
[1]: https://git-scm.com/book/id/v2/Appendix-A%3A-Git-in-Other-En...
[1]: https://git-scm.com/book/id/v2/Appendix-A%3A-Git-in-Other-En...