-
Notifications
You must be signed in to change notification settings - Fork 1
/
generate
85 lines (66 loc) · 1.73 KB
/
generate
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
#!/usr/bin/env bash
TARGET=$1
SLUG=$2
usage() {
cat << EOF
link.bsmnt.pro — a serverless & minimalist URL shortener that doesn't try to do too much.
Usage:
./generate <url to redirect> <slug>
Example:
./generate https://github.com/basement-works github
-- will redirect /github to https://github.com/basement-works
./generate https://github.com/basement-works/link.bsmnt.pro
-- will redirect /<auto-generated> to https://github.com/basement-works/link.bsmnt.pro
Notes:
Auto-generated slug can only be used if you have openssl(1) installed on your machine.
EOF
}
check_openssl_installed() {
if ! command -v openssl &> /dev/null; then
echo
echo " In order to use auto-generated slug, you need to have openssl(1) installed on your machine."
exit 1
fi
}
generate_slug() {
SLUG=$(openssl rand -hex 3)
}
slug_exists() {
if [ -f "links/$SLUG.$FORMAT" ]; then
echo
echo "/$SLUG already exists. Please choose another."
echo
exit 1
fi
}
create_redirect_file() {
cat <<EOF > "links/$SLUG.$FORMAT"
---
target: $TARGET
---
EOF
}
commit_redirect() {
git add "links/$SLUG.$FORMAT"
git commit -m "feat: create /$SLUG" -m "url target is $TARGET" > /dev/null 2>&1
}
if [ -z "$TARGET" ]; then
usage
exit 1
fi
if [ -z "$SLUG" ]; then
check_openssl_installed
generate_slug
fi
# Ask the user for the file format
echo "Choose the file format (md/mdx):"
read -r FORMAT
if [[ "$FORMAT" != "md" && "$FORMAT" != "mdx" ]]; then
echo "Invalid format. Please choose either 'md' or 'mdx'."
exit 1
fi
slug_exists
create_redirect_file
commit_redirect
echo
echo " 🤘 Successfully created redirect from /$SLUG to $TARGET."