aboutsummaryrefslogtreecommitdiff
path: root/.local/bin/new
blob: 2de7ecdf7d381debbbb055454a2bdd8601ed1b56 (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
#! /usr/bin/env sh

main()
{
	# Handle opts
	opts "$@"
	shift "$OPTS"
	unset OPTS

	# Show help
	[ "$OPT_HELP_ONLY" ] && usage && exit 0

	if [ -d "$1" ]
	then
		printf "A directory already exists at %s\n" "$1" >&2
		exit 1
	fi

	if [ -f "$1" ]
	then
		printf "A file already exists at %s\n" "$1" >&2
		exit 1
	fi

	if [ -z "$TYPE" ]
	then
		# TODO: Calculate type from extension
		TYPE=
	fi

	if [ ! -f "$XDG_TEMPLATES_DIR/$TYPE" ]
	then
		printf "No template for %s\n" "$TYPE" >&2
		touch "$1"
		return 0
	fi

	cp -- "$XDG_TEMPLATES_DIR/$TYPE" "$1"
}

opts()
{
	OPTS=0

	while getopts ":ht:" opt
	do
		case "$opt" in
			h) OPT_HELP_ONLY=1 OPTS=$((OPTS + 1)) ;;
			t) TYPE=$OPTARG OPTS=$((OPTS + 2)) ;;
			*)
				printf "Invalid option passed: %s\n" "$OPTARG" >&2
				;;
		esac
	done

	unset opt
}

usage()
{
	cat <<EOF
Usage:
	$(basename "$0") -h
	$(basename "$0") [-t TYPE] <LOCATION>

Create a new file from a template, found in the \$XDG_TEMPLATES_DIR directory.

Options:
	-h  Show this help text and exit.
	-t  Specify the template type to use.
EOF
}

main "$@"