~skiqqy/q

ref: ddd2ed1afc463d2fe9074639694b3eb1fa26c628 q/q -rwxr-xr-x 7.9 KiB
ddd2ed1aStephen Cochrane Added helper funcs 3 months ago
                                                                                
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
#!/bin/bash

# Dont change these
declare -A commands

# Commands the user can run, and its help info
commands[pop]="pop [n|all]\nPop nth (defaults to 1) item from the stack."
commands[push]="push [n]\nPush into the stack with priority n (defaults to highest)."
commands[peek]="peek [n|all]\nLook at the first n (defaults to 1) items from the stack."
commands[grep]="grep PATTERN\nSearch for notes matching PATTERN."
commands[dmenu]="dmenu\nView the stack in dmenu, to exit hit esc twice"
commands[clean]="clean\nReset the stack and ID's."
commands[ed]="ed id\nEdit the note at id."
commands[help]="q help\nShows helpful information."
commands[list]="list\nShows all available commands."
commands[tree]="tree\nShows all available stacks."
commands[server]="server [options]\nStart a q server."
commands[sync]="sync [ pull | push ] [options]\nPull/ Push current stack to q server."

usage()
{
	cat << EOF

  >>
 |  |
  <<\\

The simple stack based bug tracker

Usage: q [options] [COMMAND] [ARGS...]

options
-------
-h        Shows this message.
-d NAME   Set q directory (default $HOME/.q).
-q NAME   Specify the name of a stack to operate on (default is q).

Commands
--------
$ q list

help
----
$ q help [command]

Written by skiqqy.
EOF
	exit "$1"
}

# Parse argument for stack manipulation, and print the start index.
readstack()
{
	case "$1" in
		[0-9]* | '')
			l=${1:-1}
			;;
		all)
			l=$(wc -l "$q" | cut -d" " -f 1)
			;;
		*)
			echo "Invalid argument"
			return 1
			;;
	esac
	echo "$l"
}

# See: q help pop
qpop()
{
	n=$(readstack "$1") || return 1
	stay=$(($(wc -l "$q" | cut -d" " -f 1)-n))
	[ "$stay" -lt 0 ] && return

	qpeek "$n"
	head -"$stay" "$q" > "$qdir/qt"
	mv "$qdir/qt" "$q"
}

# See: q help peek
qpeek()
{
	l=$(readstack "$1") || return 1
	mapfile lines < <(tail -"$l" "$q")
	len=$((${#lines[@]}-1))
	[ "$l" -gt "$len" ] && l="$((len+1))"

	for ((i=len; i>=0; i--))
	do
		unpack "${lines[i]}"
		[ "$((i-1))" -gt "$((len-l))" ] && echo
	done
	return 0 # last test can evaluate to non zero. We want peek to always return 0
}

# See: q help push
qpush()
{
	prio=${1:-$(tail -1 "$qdir/q" | cut -d"$delim" -f3)}
	[ -z "$prio" ] && prio=0
	if [[ ! "$prio" =~ ^[0-9]+$ ]] || [[ ! "$prio" -ge 0 ]] > /dev/null
	then
		>&1 echo "Priority must be an int in [0,inf)"
		return 1
	fi

	read -rp "Title: " title
	write_desc
	desc="$(tr_desc)"

	if [ "$prio" = "$(tail -1 "$q" | cut -d"$delim" -f3)" ] # If max prio, simply put on top of stack.
	then
		echo "$title$delim$id$delim$prio$delim$desc" >> "$q"
		echo "$((++id))" > "$qdir/id"
		return
	fi

	t=0
	while IFS="$delim" read -r i i p i
	do
		if [ "$prio" -ge "$p" ]
		then
			[ "$prio" -eq "$p" ] && ((t++))
			break
		fi
		((t++))
	done < "$q"

	l=$(($(wc -l "$q" | cut -d" " -f 1)-t)) # Calculate the amount of items below the item to be inserted.

	{
		head -"$t" "$q"
		echo "$title$delim$id$delim$prio$delim$desc"
		tail -"$l" "$q"
	} > "$qdir/qt"
	mv "$qdir/qt" "$q"

	echo "$((++id))" > "$qdir/id"
}

# See: q help ed
qed()
{
	line=$(grep -E ".*$delim$1$delim" "$q")

	if [ -z "$line" ]
	then
		echo "Invalid ID"
		return 1
	fi

	unpack "$line" && echo

	# Todo, use a text editor to edit note
	read -rp "Title (empty to skip): " t
	read -rp "Priority (empty to skip): " p
	read -rp "Desc (empty to skip): " d

	title=${t:-"$title"}
	prio=${p:-"$prio"}
	desc=${d:-"$desc"}

	if [[ ! "$prio" =~ ^[0-9]+$ ]] || [[ ! "$prio" -ge 0 ]] > /dev/null
	then
		>&1 echo "Priority must be an int "
		return 1
	fi
	
	sed -i "/.*$delim$1$delim.*/d" "$q" # TODO: maybe use ed to preserve symlinks
	id=$1 && printf '%s\n%s\n' "$title" "$desc" | qpush "$prio" # Update the stack
}

# See: q help grep
qgrep()
{
	[ -z "$1" ] && return
	while read -r line
	do
		unpack "$line" && echo
	done < <(grep -E "$1" "$q" | tac) # Preserve order

	# Remove the last printed newline
	printf "\033[1A"
	printf '\b'
}

# See: q help dmenu
qdmenu()
{
	[ ! "$(command -v dmenu)" ] && { printf 'This command requires dmenu\n'; return 1; }

	# Event loop to browse the stack
	while data=$(tac "$q" | cut -d: -f1,2 | sed -E 's|(.*):(.*)|ID\2 -> \1|g') && \
		select=$(dmenu -l "$(echo "$data" | wc -l | cut -d " " -f 1)" <<< "$data")
	do
		id=$(sed -E 's|ID(.*) ->.*|\1|g' <<< "$select")
		grep -E ".*$delim$id$delim" "$q" | cut -d "$delim" -f4 | dmenu -l 1
	done
	return 0 # Force clean exit code.
}

# See: q help clean
qclean()
{
	read -rp "Confirm delete stack? Y/N: " input
	if [[ ! $input =~ ^(y|Y)(es|ES)?$ ]]
	then
		echo "Aborted"
		return
	fi
	rm "$qdir/"{q,id}
}

# Write a description in your editor
write_desc()
{
	> "$qdir/buffer" # Clear the buffer
	$EDITOR "$qdir/buffer"
}

# Translates a description, and prints the result to stdout
tr_desc()
{
	tr '\n' "$delim" < "$qdir/buffer" | sed "s|$delim|\\\n|g" # Replace newlines with \n
}

# Read a string and split it into vars
parse()
{
	title=$(echo "$1" | cut -d "$delim" -f1)
	id=$(echo "$1"    | cut -d "$delim" -f2)
	prio=$(echo "$1"  | cut -d "$delim" -f3)
	desc=$(echo "$1"  | cut -d "$delim" -f4)
}

# Print an item from the stack nicely
unpack()
{
	parse "$1"
	printf 'Title: %s\nID: %s\nPriority: %s\n%b\n' "$title" "$id" "$prio" "$desc"
}

qhelp()
{
	[ "$#" -eq 0 ] && usage 0
	if [ -n "${commands[$1]}" ]
	then
		printf 'Usage: %b\n' "${commands[$1]}"
	else
		printf 'Unknown Command.\n'
	fi
}

qlist()
{
	list=${!commands[*]}
	printf "Commands\n--------\n\n%b\n\nSee, q help <command>\n" "${list// /\\n}"
}

qtree()
{
	[ ! "$(command -v tree)" ] && { printf 'This command requires tree\n'; return 1; }
	printf 'Stacks\n'
	tree -I id --noreport "$qdir" | tail -n +2
}

qserver()
{
	local spath
	spath="$HOME/.local/lib"
	mkdir -p "$spath"
	[ ! -d "$spath/kept-folder" ] && git clone "https://git.sr.ht/~skiqqy/kept-folder" "$spath/kept-folder"
	if [ ! -f "$qdir/config" ]
	then
		printf 'Generated config file in %s, please complete and then restart server\n.' "$qdir/config"
		cat << EOF > "$qdir/config"
nic=nickname
privkey=key
domain=http://0.0.0.0:5000/
EOF
	return
	fi

	pushd "$spath/kept-folder" > /dev/null || return 1
		printf 'Server Directory: %s\n\n' "$PWD"
		./main.sh "$@"
	popd > /dev/null || return 1
}

qsync()
{
	if [ "$1" = push ]
	then
		upload "$q"
	elif [ "$1" = pull ]
	then
		download "$q"
	fi
}

# Upload a file
# Usage: upload FILE
upload() {
	[ -z "$domain" ] && . "$qdir/config"
	route="$domain/upload/note"
	content=$(cat "$1")
	fname=$(basename "$1")
	curl -s -X POST -F "nic=$nic" -F "key=$privkey" -F "fname=$fname" -F "content=$content" "$route" > /dev/null
}

# Download a file
# Usage: download FILE
download() {
	[ ! -d "$qdir/syc" ] && mkdir -p "$qdir/sync"
	[ -z "$domain" ] && . "$qdir/config"
	route="$domain/download/note"
	fname=$(basename "$1")
	ret="$(curl -s -X POST -F "nic=$nic" -F "key=$privkey" -F "fname=$fname" "$route")"

	code=$(echo "$ret" | jq '.status')
	if [ -n "$code" ]  && [ "$code" -eq 0 ]
	then
		data=$(echo "$ret" | jq '.data')
		fname=$(echo "$data" | jq '.fname')
		content=$(echo "$data" | jq '.content')

		fname=$(sq "$fname")
		content=$(sq "$content")

		echo -en "$content" > "$qdir/$fname"
		echo "Sync for <$1> completed."
	else
		echo "Sync for <$1> failed."
		return 1
	fi
}

sq () {
	sed -e 's/^"//' -e 's/"$//' <<< "$1"
}

main()
{
	default=qpeek # Default command
	qdir="$HOME/.q" # Default location
	q="q" # Default Stack Name
	nic=
	privkey=
	domain=
	delim="$(echo -e '\x1f')"

	while getopts "hd:q:" opt
	do
		case "$opt" in
			h)
				usage 0
				;;
			d)
				qdir="$OPTARG"
				;;
			q)
				if [ "$OPTARG" = id ] || [ "$OPTARG" = config ]
				then
					printf 'q cannot be set to %s, aborting.\n' "$OPTARG"
					exit 1
				fi
				q="$OPTARG"
				;;
			*)
				usage 1
				;;
		esac
	done

	shift $((OPTIND-1)) # Get rid of the parsed arguments

	# Final init
	mkdir -p "$qdir"
	touch "$qdir/id"
	id=$(head -1 "$qdir/id")
	id=${id:-0}
	q="$qdir/$q"
	touch "$qdir/q" "$q"

	command="$1"
	shift 1

	if [ -z "$command" ]
	then
		$default
	elif [ -n "${commands[$command]}" ]
	then
		q"$command" "$@" # If the user can invoke the command, run it directly
	else
		usage 1
	fi
}

main "$@"