bb51dc731e4025375f6769ebe43c3e4134808cbb
[bash-notes.git] / SOURCE / CORE / git.sh
1 # check if GITCLIENT has been set or set it to the output of hostname
2 if [ -z "$GITCLIENT" ]; then
3 GITCLIENT=$( hostname )
4 fi
5 # returns true if the argument provided directory is a git repository
6 is_git_repo() {
7 DIR=$1
8 if [[ -d $DIR ]]; then
9 cd $DIR
10 if git rev-parse 2>/dev/null; then
11 true
12 else
13 false
14 fi
15 fi
16 }
17
18 # sync local repository to remote
19 # accepts -f parameter to skip last sync check
20 gitsync() {
21 FORCE=$1
22 if [[ $USEGIT && -n $GITREMOTE ]]; then
23 [ $PLAIN == false ] && echo "Syncing notes with git on remote \"$GITREMOTE\""
24 NOWSYNC=$(date +%s)
25 if [[ $FORCE == "-f" ]]; then
26 $JQ --arg n "$NOWSYNC" '.git["lastpull"] = $n' "$DB" > $TMPDB
27 mv $TMPDB $DB
28 cd $BASEDIR
29 $GIT pull
30 else
31 # LASTSYNC is the last time we synced to the remote, or 0 if it's the first time.
32 LASTSYNC=$($JQ -r '.git["lastpull"] // 0' "$DB")
33 SYNCDIFF=$(( ${NOWSYNC} - ${LASTSYNC} ))
34 if (( $SYNCDIFF > $GITSYNCDELAY )); then
35 #more than our delay time has passed. We can sync again.
36 $JQ --arg n "$NOWSYNC" '.git["lastpull"] = $n' "$DB" > $TMPDB
37 mv $TMPDB $DB
38 cd $BASEDIR
39 $GIT pull
40 else
41 # Last synced less than $GITSYNCDELAY seconds ago. We shall wait
42 [ $PLAIN == false ] && echo "Last synced less than $GITSYNCDELAY seconds ago. We shall wait"
43 fi
44 fi
45 else
46 # no git, so we just keep going
47 true
48 fi
49 }
50
51 # add note to git and push it to remote
52 gitadd() {
53 if [[ $USEGIT && -n $GITREMOTE ]]; then
54 [ $PLAIN == false ] && echo "Adding note to remote \"$GITREMOTE\""
55 cd $BASEDIR
56 $GIT add .
57 $GIT commit -m "$(basename $0) - adding note from ${GITCLIENT}"
58 $GIT push origin master
59 else
60 # no git, so we just keep going
61 true
62 fi
63 }
64
65 # check for USEGIT and subsequent variables
66 if [[ $USEGIT && -n $GITREMOTE ]]; then
67 # GIT is a go.
68 if ! is_git_repo $BASEDIR; then
69 # initializing git repository
70 cd $BASEDIR
71 $GIT init
72 echo "adding all files to git"
73 $GIT add .
74 $GIT commit -m "$(basename $0) - initial commit from ${GITCLIENT}"
75 $GIT remote add origin $GITREMOTE
76 $GIT push -u origin master
77 fi
78 elif [[ $USEGIT && -z $GITREMOTE ]]; then
79 echo "GITREMOTE variable not set. reverting USEGIT to false"
80 USEGIT=false
81 fi
82