summarylogtreecommitdiffstats
path: root/swaycwd
blob: 5585b6b12925b26fb000c4a09b8f70db7a01d1d9 (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
#!/usr/bin/env bash

fallback="$HOME"

# taken from https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash
! PARSED=$(getopt --options="h?f:" --longoptions="fallback:,help" --name "$0" -- "$@")
if [[ ${PIPESTATUS[0]} -ne 0 ]]; then
    # e.g. return value is 1
    #  then getopt has complained about wrong arguments to stdout
    exit 2
fi

# helptext 
usage="$(basename $0) [-h] [-f=/fallback/directory] 

Get Current Working Directory for program under cursor in sway. 

Options: 
 -h, --help     Print this help text
 -f, --fallback Set directory to print when error occured (defaults to $HOME)"

# parse args
eval set -- "$PARSED"

while true; do
	case "$1" in 
	-f|--fallback) 
		fallback="$2"
		shift 2
		;;
	-h|--help)
		echo "$usage"
		exit 0
		;;
	--)
		break
		;;
	*) 
		echo "argparse error"
		exit 1
		;;
	esac
done

# get parent pid of program under cursor
pid=$(swaymsg -t get_tree | jq '.. | select(.type?) | select(.type=="con") | select(.focused==true).pid')
ppid=$(pgrep --newest --parent ${pid})

# get cwd from proc dir
location=$(readlink /proc/${ppid}/cwd)

if [ "$?" -ne 0 ]; then 
	# just print out fallback dir on error
	echo $fallback
	exit 0
fi 

# find out if the path points to /proc dir
# use fallback in that case
echo $location | grep -q /proc && echo $fallback || echo $location