-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpermute_aliases.sh
executable file
·65 lines (56 loc) · 1.75 KB
/
permute_aliases.sh
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
#!/usr/bin/env bash
# Prints all unique permutation of a given program as bash alias commands to stdout. Ideal for generation of "make" or "git" aliases.
# Usage:
# $ ./permute_aliases.sh <program> > ${XDG_CONFIG_HOME:-$HOME/.config}/shell/aliases_<program>
# source the generated file in you bash configuration file(s), like $(source aliases_<program>)
# or add it directly like
# $ ./permute_aliases.sh <program> >> ~/.bashrc
# TODO don't use globals...
declare -A permutations
# In subject, swap subject[a_pos] with subject[b_pos].
_swap() {
local subject="$1"
local a_pos="$2"
local b_pos="$3"
local a="${subject:${a_pos}:1}"
local b="${subject:${b_pos}:1}"
a_pos=$((a_pos + 1))
b_pos=$((b_pos + 1))
local permuted="$(echo "$subject" | sed -e "s/./${b}/${a_pos}" | sed -e "s/./${a}/${b_pos}")"
echo "$permuted"
}
# Save a given permutation to global permutations array.
_save_permutation() {
local program="$1"
local permutation="$2"
if [ "$permuted" != "$program" ]; then
if [[ ! ${permutations["${permutation}"]} ]]; then
permutations+=(["${permutation}"]="${permutation}")
fi
fi
}
_permutate() {
local program="$1"
local subject="$2"
local pos="$3"
local i="$pos"
for ((; $i < ${#subject}; i++)); do
local permuted=$(_swap "$subject" "$pos" "$i")
_save_permutation "$program" "$permuted"
_permutate "$program" "$permuted" $((pos+1))
done
}
# Generate permutation aliases recursively.
permutate() {
local program="$1"
_permutate "$program" "$program" 0
}
if [ "$#" -ne "1" ]; then
echo "One argument expected: string to permute." 1>&2
exit 1
else
program="$1"
echo "# Below follows all unique permutation aliases of \"${program}\", generated by \"${0##*/}\"."
permutate "$program"
printf "alias %s='$program'\n" "${permutations[@]}"
fi