11#! /usr/bin/env bash
22
3- : ${ GIT_DIR: = $(git rev-parse --git-dir)}
3+ GIT_DIR=$( git rev-parse --git-dir 2> /dev/null )
44
55function show_contents {
66 local file=" ${2/# ~/ $HOME } "
@@ -11,18 +11,41 @@ function show_contents {
1111 fi
1212}
1313
14+ function cd_to_git_root {
15+ local error_level=" $1 "
16+
17+ if ! git rev-parse --git-dir & > /dev/null; then
18+ if [ " $error_level " = ' --warn' ]; then
19+ echo " Warning: Not currently in a Git repository" >&2
20+ elif [ " $error_level " = ' --error' ]; then
21+ echo " Error: Not currently in a Git repository" >&2
22+ exit 1
23+ fi
24+ fi
25+
26+ local result=
27+ if result=$( git rev-parse --show-toplevel 2> /dev/null) ; then
28+ cd " $result " || exit
29+ fi
30+ }
31+
1432function global_ignore() {
15- git config --global core.excludesFile || \
16- ([ -n " $XDG_CONFIG_HOME " ] && echo " $XDG_CONFIG_HOME /git/ignore" ) || \
17- echo " $HOME /.config/git/ignore"
33+ if ! git config --global core.excludesFile 2> /dev/null; then
34+ if [ -f " $HOME /.gitignore" ]; then
35+ echo " $HOME /.gitignore"
36+ else
37+ echo " ${XDG_CONFIG_HOME:- $HOME / .config} /git/ignore"
38+ fi
39+ fi
1840}
1941
2042function show_global {
2143 show_contents Global " $( global_ignore) "
2244}
2345
2446function add_global {
25- local global_gitignore=" $( global_ignore) "
47+ local global_gitignore
48+ global_gitignore=" $( global_ignore) "
2649 if [ -z " $global_gitignore " ]; then
2750 echo " Can't find global .gitignore."
2851 echo " "
@@ -34,22 +57,22 @@ function add_global {
3457}
3558
3659function show_local {
37- cd " $( git root ) "
60+ cd_to_git_root --warn
3861 show_contents Local .gitignore
3962}
4063
4164function add_local {
42- cd " $( git root ) "
65+ cd_to_git_root --warn
4366 add_patterns .gitignore " $@ "
4467}
4568
4669function show_private {
47- cd " $( git root ) "
70+ cd_to_git_root --error
4871 show_contents Private " ${GIT_DIR} /info/exclude"
4972}
5073
5174function add_private {
52- cd " $( git root ) "
75+ cd_to_git_root --error
5376 test -d " ${GIT_DIR} /info" || mkdir -p " ${GIT_DIR} /info"
5477 add_patterns " ${GIT_DIR} /info/exclude" " $@ "
5578}
0 commit comments