Skip to content

Commit

Permalink
Add adding entries to crontab
Browse files Browse the repository at this point in the history
  • Loading branch information
norm committed Sep 12, 2021
1 parent d5303ce commit f6981fc
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 1 deletion.
5 changes: 5 additions & 0 deletions documentation/kitfile.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,8 @@ Available commands are:

Copies a file found at _SOURCE_ to _DESTINATION_. If _MODE_ is specified,
the file has that mode applied (any valid arguments to `chmod`).

* cron_entry _MN_ _HR_ _DOM_ _MON_ _DOW_ _CMD_

Add an entry to the crontab, creating one if necessary. The arguments are
described in more detail in the manual: run `man 5 crontab`.
36 changes: 35 additions & 1 deletion kitout.sh
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ function process_kitfile {
)
read command argument <<<"$line"
case "$command" in
\#|'') : ;;
\#*|'') : ;;
echo) output "$argument" ;;
debug) debug_output "$argument" ;;
section) section "$argument" ;;
Expand All @@ -128,6 +128,8 @@ function process_kitfile {
brewfile) brewfile "$argument" ;;
install) install_file $argument ;;

cron_entry) add_to_crontab "$argument" ;;

*) error "Unknown command: '$command'" ;;
esac
done
Expand Down Expand Up @@ -246,4 +248,36 @@ function install_file {
fi
}

function add_to_crontab {
local line="$*"
local tab="$(mktemp '/tmp/kitout.crontab.XXXXX')"
local email search

if ! crontab -l > "$tab" 2>/dev/null; then
email=$( git config user.email )
[ -z "$email" ] && email='crontab@example.com'

cat << EOF | sed -e 's/^ *//' > "$tab"
MAILTO=$email
PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
#mn hr dom mon dow cmd
EOF
action 'initialising crontab'
fi

search=$(
echo "$line" \
| sed -e 's/\*/\\*/g' -e 's/ */ */g'
)
debug "search='$search'"

if ! grep -q "$search" "$tab"; then
echo "$line" >> "$tab"
action "added '$line' to crontab"
fi

crontab "$tab"
}

main "$@"
25 changes: 25 additions & 0 deletions tests/cron.bats
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#!/usr/bin/env bash

yellow=$'\e'[33m
reset=$'\e'[0m
TEMP_CRON=$( mktemp '/tmp/crontab.original.XXXXX' )

@test cron_entry {
skip "Triggers a security prompt, run manually"

if crontab -l > $TEMP_CRON; then
crontab /dev/null
fi

run ./kitout.sh tests/cron.kitfile
echo "$output"

[ $status -eq 0 ]
[ "${lines[0]}" == "${yellow}=== added '* * * * * sleep 1' to crontab${reset}" ]

if [ "$(stat -f'%z' $TEMP_CRON)" -gt 0 ]; then
crontab $TEMP_CRON
else
crontab /dev/null
fi
}
2 changes: 2 additions & 0 deletions tests/cron.kitfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#mn hr dom mon dow cmd
cron_entry * * * * * sleep 1

0 comments on commit f6981fc

Please sign in to comment.