aboutsummaryrefslogtreecommitdiff
path: root/bash/10-board.bash
blob: 67c7da75d01dedfcd0416563ea56cd46e3ac0aff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#!/bin/bash

# config in ~/.files.config

if [ ! "$BB_ENABLE" = "yes" ]; then
	return
fi

[ ! -d "$BB_HIST_DIR" ] && mkdir -p "$BB_HIST_DIR"

# Public var, not config
BB_SHORTCUT=()

# format
# NUM EPOCH PATH

# add ssh targets

function cd {
	local BB_PWD
	local BB_GREP_RET
	local BB_NUM BB_DATE BB_DIR

	builtin cd "$@" || return $?
	[ -f "$BB_DIR/history" ] || touch "$BB_HIST_DIR/history"
	BB_PWD="$(pwd)"

	[ "${BB_PWD%%/}" = "${HOME%%/}" ] && return

	BB_GREP_RET=$(grep -P "^\d+ \d+ \Q$BB_PWD\E$" "$BB_HIST_DIR/history")
	read -r BB_NUM BB_DATE BB_DIR <<< "$BB_GREP_RET"
	if [ -n "$BB_NUM" ]; then
		BB_NUM=$((BB_NUM+1))
		perl -p -i -e "s|^\d+ \d+ \Q$BB_PWD\E$|$BB_NUM $(date +%s) $BB_PWD|g" \
			"$BB_HIST_DIR/history"
	else
		echo "1 $(date +%s) $BB_PWD" >> "$BB_HIST_DIR/history"
	fi
}

function bashboard {
	local BB_NUM BB_DATE BB_DIR
	local line
	local cnt

	[ -f "$BB_HIST_DIR/history" ] || return

	BB_SHORTCUT=()

	cnt=0
	while read -r line; do
		local DIR BNAME DNAME
		read -r BB_NUM BB_DATE BB_DIR <<< "$line"

		DIR="${BB_DIR##"$HOME"}"
		DIR="${DIR##"/"}"
		BNAME="$(basename "$DIR")"
		DNAME="$(dirname "$DIR")"

		if [ "$DNAME" = "." ]; then
			DNAME=""
		else
			DNAME="$DNAME/"
		fi

		printf "[$cnt] $DNAME$BB_COLOR_HIGHLIGHT$BNAME$BB_COLOR_RESET\n"

		BB_SHORTCUT+=("$BB_DIR")

		cnt=$((cnt+1))
	done <<< "$(sort -nr "$BB_HIST_DIR/history" | head -n $BB_LIST_LEN)"

	# TODO recently used
}

function bb {
	if [ $# -eq 0 ]; then
		bashboard
		return
	fi

	cd "${BB_SHORTCUT[$1]}" || return
}

function bb_prune {
	# Older than...
	# Folder exists?
	# shorten list
	local COUNT FILEDATE FILEPATH COMP
	COMP=$(date -d "-${BB_PRUNE_DAYS}days" +%s)

	echo -n > "$BB_HIST_DIR/history.new"

	while read -r COUNT FILEDATE FILEPATH; do
		[ $FILEDATE -ge $COMP ] && echo "$COUNT $FILEDATE $FILEPATH" >> "$BB_HIST_DIR/history.new"
	done < "$BB_HIST_DIR/history"

	mv "$BB_HIST_DIR/history.new" "$BB_HIST_DIR/history"
}

bashboard