From 07a018ba5ecdef5319097834141d1f0e98d7f32a Mon Sep 17 00:00:00 2001 From: Gofannon Date: Sun, 12 May 2019 15:59:22 +0200 Subject: [PATCH] Add helper "ynh_smart_mktemp" --- scripts/_common.sh | 46 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/scripts/_common.sh b/scripts/_common.sh index bb04a03..d98beaf 100644 --- a/scripts/_common.sh +++ b/scripts/_common.sh @@ -10,4 +10,48 @@ ynh_delete_file_checksum () { local checksum_setting_name=checksum_${1//[\/ ]/_} # Replace all '/' and ' ' by '_' ynh_app_setting_delete $app $checksum_setting_name -} \ No newline at end of file +} + + + + + + + + +# Check available space before creating a temp directory. +# +# usage: ynh_smart_mktemp --min_size="Min size" +# +# | arg: -s, --min_size= - Minimal size needed for the temporary directory, in Mb +ynh_smart_mktemp () { + # Declare an array to define the options of this helper. + declare -Ar args_array=( [s]=min_size= ) + local min_size + # Manage arguments with getopts + ynh_handle_getopts_args "$@" + + min_size="${min_size:-300}" + # Transform the minimum size from megabytes to kilobytes + min_size=$(( $min_size * 1024 )) + + # Check if there's enough free space in a directory + is_there_enough_space () { + local free_space=$(df --output=avail "$1" | sed 1d) + test $free_space -ge $min_size + } + + if is_there_enough_space /tmp; then + local tmpdir=/tmp + elif is_there_enough_space /var; then + local tmpdir=/var + elif is_there_enough_space /; then + local tmpdir=/ + elif is_there_enough_space /home; then + local tmpdir=/home + else + ynh_die "Insufficient free space to continue..." + fi + + echo "$(sudo mktemp --directory --tmpdir="$tmpdir")" +}