Skip to content

Commit

Permalink
Some misc improvements
Browse files Browse the repository at this point in the history
* Remove more redundant code

* Check for any conflict before installation

* Add a check if terminal supportd ansi escapes

* Improve COLUMN detection in posix scripts

* Add a pure posix version of _bytes_to_human

* Fix an edge case in _json_value function
  • Loading branch information
Akianonymus committed Aug 9, 2020
1 parent 53797c8 commit 65480d7
Show file tree
Hide file tree
Showing 7 changed files with 109 additions and 106 deletions.
18 changes: 9 additions & 9 deletions bash/common-utils.bash
Original file line number Diff line number Diff line change
Expand Up @@ -49,20 +49,19 @@ _check_debug() {
set -x && PS4='-> '
_print_center() { { [[ $# = 3 ]] && printf "%s\n" "${2}"; } || { printf "%s%s\n" "${2}" "${3}"; }; }
_clear_line() { :; } && _newline() { :; }
CURL_PROGRESS="-s" && export CURL_PROGRESS
else
if [[ -z ${QUIET} ]]; then
if _is_terminal; then
if _support_ansi_escapes; then
# This refreshes the interactive shell so we can use the ${COLUMNS} variable in the _print_center function.
shopt -s checkwinsize && (: && :)
if [[ ${COLUMNS} -lt 45 ]]; then
_print_center() { { [[ $# = 3 ]] && printf "%s\n" "[ ${2} ]"; } || { printf "%s\n" "[ ${2}${3} ]"; }; }
else
trap 'shopt -s checkwinsize; (:;:)' SIGWINCH
fi
EXTRA_LOG="_print_center"
CURL_PROGRESS="-#" EXTRA_LOG="_print_center" CURL_PROGRESS_EXTRA="-#"
export CURL_PROGRESS EXTRA_LOG CURL_PROGRESS_EXTRA
else
CURL_PROGRESS="-s" && export CURL_PROGRESS
_print_center() { { [[ $# = 3 ]] && printf "%s\n" "[ ${2} ]"; } || { printf "%s\n" "[ ${2}${3} ]"; }; }
_clear_line() { :; }
fi
Expand Down Expand Up @@ -227,14 +226,14 @@ _get_latest_sha() {
}

###################################################
# Check if script running in a terminal
# Check if script terminal supports ansi escapes
# Globals: 1 variable
# TERM
# Arguments: None
# Result: return 1 or 0
###################################################
_is_terminal() {
[[ -t 1 || -z ${TERM} ]] && return 0 || return 1
_support_ansi_escapes() {
{ [[ -t 2 && -n ${TERM} && ${TERM} =~ (xterm|rxvt|urxvt|linux|vt) ]] && return 0; } || return 1
}

###################################################
Expand All @@ -251,10 +250,11 @@ _is_terminal() {
# Result: print extracted value
###################################################
_json_value() {
declare num _tmp
declare num _tmp no_of_lines
{ [[ ${2} -gt 0 ]] && no_of_lines="${2}"; } || :
{ [[ ${3} -gt 0 ]] && num="${3}"; } || { [[ ${3} != all ]] && num=1; }
_tmp="$(grep -o "\"${1}\"\:.*" ${no_of_lines:+-m ${no_of_lines}})" || return 1
# shellcheck disable=SC2086
_tmp="$(grep -o "\"${1}\"\:.*" ${no_of_lines:+-m} ${no_of_lines})" || return 1
printf "%s\n" "${_tmp}" | sed -e "s/.*\"""${1}""\"://" -e 's/[",]*$//' -e 's/["]*$//' -e 's/[,]*$//' -e "s/^ //" -e 's/^"//' -n -e "${num}"p || :
}

Expand Down
12 changes: 6 additions & 6 deletions bash/drive-utils.bash
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ _drive_info() {
"${EXTRA_LOG}" "justify" "Fetching info.." "-" 1>&2
search_response="$(curl --compressed "${CURL_PROGRESS_EXTRA}" \
-H "Authorization: Bearer ${token}" \
"${API_URL}/drive/${API_VERSION}/files/${folder_id}?fields=${fetch}&supportsAllDrives=true" || :)" && "${CURL_PROGRESS_EXTRA_CLEAR:-:}" 1 1>&2
"${API_URL}/drive/${API_VERSION}/files/${folder_id}?fields=${fetch}&supportsAllDrives=true" || :)" && _clear_line 1 1>&2
_clear_line 1 1>&2

printf "%b" "${search_response:+${search_response}\n}"
Expand Down Expand Up @@ -86,7 +86,7 @@ _check_existing_file() {

search_response="$(curl --compressed "${CURL_PROGRESS_EXTRA}" \
-H "Authorization: Bearer ${token}" \
"${API_URL}/drive/${API_VERSION}/files?q=${query}&fields=files(id,name,mimeType)&supportsAllDrives=true" || :)" && "${CURL_PROGRESS_EXTRA_CLEAR:-:}" 1 1>&2
"${API_URL}/drive/${API_VERSION}/files?q=${query}&fields=files(id,name,mimeType)&supportsAllDrives=true" || :)" && _clear_line 1 1>&2
_clear_line 1 1>&2

{ _json_value id 1 1 <<< "${search_response}" 2> /dev/null 1>&2 && printf "%s\n" "${search_response}"; } || return 1
Expand Down Expand Up @@ -116,7 +116,7 @@ _create_directory() {

search_response="$(curl --compressed "${CURL_PROGRESS_EXTRA}" \
-H "Authorization: Bearer ${token}" \
"${API_URL}/drive/${API_VERSION}/files?q=${query}&fields=files(id)&supportsAllDrives=true" || :)" && "${CURL_PROGRESS_EXTRA_CLEAR:-:}" 1 1>&2
"${API_URL}/drive/${API_VERSION}/files?q=${query}&fields=files(id)&supportsAllDrives=true" || :)" && _clear_line 1 1>&2

if ! folder_id="$(printf "%s\n" "${search_response}" | _json_value id 1 1)"; then
declare create_folder_post_data create_folder_response
Expand All @@ -126,7 +126,7 @@ _create_directory() {
-H "Authorization: Bearer ${token}" \
-H "Content-Type: application/json; charset=UTF-8" \
-d "${create_folder_post_data}" \
"${API_URL}/drive/${API_VERSION}/files?fields=id&supportsAllDrives=true" || :)" && "${CURL_PROGRESS_EXTRA_CLEAR:-:}" 1 1>&2
"${API_URL}/drive/${API_VERSION}/files?fields=id&supportsAllDrives=true" || :)" && _clear_line 1 1>&2
fi
_clear_line 1 1>&2

Expand All @@ -148,7 +148,7 @@ _generate_upload_link() {
-H "X-Upload-Content-Length: ${inputsize}" \
-d "$postdata" \
"${url}" \
-D - || :)" && "${CURL_PROGRESS_EXTRA_CLEAR:-:}" 1 1>&2
-D - || :)" && _clear_line 1 1>&2
_clear_line 1 1>&2

uploadlink="$(read -r firstline <<< "${uploadlink/*[L,l]ocation: /}" && printf "%s\n" "${firstline//$'\r'/}")"
Expand Down Expand Up @@ -508,7 +508,7 @@ _share_id() {
-H "Authorization: Bearer ${token}" \
-H "Content-Type: application/json; charset=UTF-8" \
-d "${share_post_data}" \
"${API_URL}/drive/${API_VERSION}/files/${id}/permissions" || :)" && "${CURL_PROGRESS_EXTRA_CLEAR:-:}" 1
"${API_URL}/drive/${API_VERSION}/files/${id}/permissions" || :)" && _clear_line 1 1>&2
_clear_line 1 1>&2

{ _json_value id 1 1 <<< "${share_response}" 2> /dev/null 1>&2 && return 0; } ||
Expand Down
44 changes: 15 additions & 29 deletions bash/upload.bash
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ Options:\n
--info - Show detailed info, only if script is installed system wide.\n
-U | --uninstall - Uninstall script, remove related files.\n
-D | --debug - Display script command trace.\n
-h | --help - Display usage instructions.\n"
-h | --help - Display this message.\n"
exit 0
}

Expand Down Expand Up @@ -129,7 +129,7 @@ _setup_arguments() {
unset FIRST_INPUT FOLDER_INPUT FOLDERNAME LOCAL_INPUT_ARRAY ID_INPUT_ARRAY
unset PARALLEL NO_OF_PARALLEL_JOBS SHARE SHARE_EMAIL OVERWRITE SKIP_DUPLICATES SKIP_SUBDIRS ROOTDIR QUIET
unset VERBOSE VERBOSE_PROGRESS DEBUG LOG_FILE_ID CURL_SPEED RETRY
CURL_PROGRESS="-#" EXTRA_LOG=":" && unset CURL_PROGRESS_EXTRA CURL_PROGRESS_EXTRA_CLEAR
CURL_PROGRESS="-s" EXTRA_LOG=":" CURL_PROGRESS_EXTRA="-s"
INFO_PATH="${HOME}/.google-drive-upload" INFO_FILE="${INFO_PATH}/google-drive-upload.info"
[[ -f "${INFO_PATH}/google-drive-upload.configpath" ]] && CONFIG="$(< "${INFO_PATH}/google-drive-upload.configpath")"
CONFIG="${CONFIG:-${HOME}/.googledrive.conf}"
Expand Down Expand Up @@ -243,7 +243,7 @@ _setup_arguments() {
--hide) HIDE_INFO=":" ;;
-q | --quiet) QUIET="_print_center_quiet" ;;
-v | --verbose) VERBOSE="true" ;;
-V | --verbose-progress) VERBOSE_PROGRESS="true" && CURL_PROGRESS="" ;;
-V | --verbose-progress) VERBOSE_PROGRESS="true" ;;
--skip-internet-check) SKIP_INTERNET_CHECK=":" ;;
'') shorthelp ;;
*) # Check if user meant it to be a flag
Expand All @@ -262,16 +262,13 @@ _setup_arguments() {
shift
done

# Get foldername, prioritise the input given by -C/--create-dir option.
FOLDERNAME="${FOLDERNAME:-${FOLDER_INPUT}}"

[[ -n ${VERBOSE_PROGRESS:+${VERBOSE}} ]] && unset "${VERBOSE}"
_check_debug

[[ -n ${VERBOSE_PROGRESS} ]] && unset VERBOSE && CURL_PROGRESS=""
[[ -n ${QUIET} ]] && CURL_PROGRESS="-s"

_check_debug

{ [[ ${CURL_PROGRESS} = "-#" ]] && CURL_PROGRESS_EXTRA="-#" && CURL_PROGRESS_EXTRA_CLEAR="_clear_line"; } || CURL_PROGRESS_EXTRA="-s"
# Get foldername, prioritise the input given by -C/--create-dir option.
FOLDERNAME="${FOLDERNAME:-${FOLDER_INPUT}}"

unset Aseen && declare -A Aseen
for input in "${LOCAL_INPUT_ARRAY[@]}"; do
Expand All @@ -288,19 +285,6 @@ _setup_arguments() {
return 0
}

###################################################
# Setup Temporary file name for writing, uses mktemp, current dir as fallback
# Used in parallel folder uploads progress
# Globals: 1 variable
# PWD ( optional )
# Arguments: None
# Result: read description
###################################################
_setup_tempfile() {
{ type -p mktemp 2> /dev/null 1>&2 && TMPFILE="$(mktemp -u)"; } || TMPFILE="${PWD}/$(printf "%(%s)T\\n" "-1").LOG"
return 0
}

###################################################
# Check Oauth credentials and create/update config file
# Client ID, Client Secret, Refesh Token and Access Token
Expand All @@ -317,7 +301,7 @@ _check_credentials() {
[[ -r ${CONFIG} ]] &&
. "${CONFIG}" && [[ -n ${UPDATE_DEFAULT_CONFIG} ]] && printf "%s\n" "${CONFIG}" >| "${INFO_PATH}/google-drive-upload.configpath"

! _is_terminal && [[ -z ${CLIENT_ID:+${CLIENT_SECRET:+${REFRESH_TOKEN}}} ]] && {
! [[ -t 1 ]] && [[ -z ${CLIENT_ID:+${CLIENT_SECRET:+${REFRESH_TOKEN}}} ]] && {
printf "%s\n" "Error: Script is not running in a terminal, cannot ask for credentials."
printf "%s\n" "Add in config manually if terminal is not accessible. CLIENT_ID, CLIENT_SECRET and REFRESH_TOKEN is required." && return 1
}
Expand Down Expand Up @@ -464,7 +448,7 @@ _setup_workspace() {
# UPLOAD_STATUS, COLUMNS, API_URL, API_VERSION, LOG_FILE_ID
# FILE_ID, FILE_LINK, FINAL_ID_INPUT_ARRAY ( array )
# PARALLEL_UPLOAD, QUIET, NO_OF_PARALLEL_JOBS, TMPFILE
# Functions - _print_center, _clear_line, _newline, _is_terminal, _print_center_quiet
# Functions - _print_center, _clear_line, _newline, _support_ansi_escapes, _print_center_quiet
# _upload_file, _share_id, _is_terminal, _dirname,
# _create_directory, _json_value, _url_encode, _check_existing_file, _bytes_to_human
# _clone_file
Expand All @@ -475,7 +459,7 @@ _process_arguments() {
export API_URL API_VERSION ACCESS_TOKEN LOG_FILE_ID OVERWRITE UPLOAD_MODE SKIP_DUPLICATES CURL_SPEED RETRY UTILS_FOLDER \
QUIET VERBOSE VERBOSE_PROGRESS CURL_PROGRESS CURL_PROGRESS_EXTRA CURL_PROGRESS_EXTRA_CLEAR COLUMNS EXTRA_LOG PARALLEL_UPLOAD

export -f _bytes_to_human _dirname _json_value _url_encode _is_terminal _newline _print_center_quiet _print_center _clear_line \
export -f _bytes_to_human _dirname _json_value _url_encode _support_ansi_escapes _newline _print_center_quiet _print_center _clear_line \
_check_existing_file _upload_file _upload_file_main _clone_file _collect_file_info _generate_upload_link _upload_file_from_uri _full_upload \
_normal_logging_upload _error_logging_upload _log_upload_session _remove_upload_session _upload_folder _share_id _gen_final_list

Expand All @@ -484,7 +468,7 @@ _process_arguments() {
"${SHARE:-:}" "${1:-}" "${ACCESS_TOKEN}" "${SHARE_EMAIL}"
[[ -z ${HIDE_INFO} ]] &&
_print_center "justify" "DriveLink" "${SHARE:+ (SHARED)}" "-" &&
_is_terminal && [[ ${COLUMNS} -gt 45 ]] && _print_center "normal" "↓ ↓ ↓" ' ' &&
_support_ansi_escapes && [[ ${COLUMNS} -gt 45 ]] && _print_center "normal" "↓ ↓ ↓" ' ' &&
_print_center "normal" "https://drive.google.com/open?id=${1:-}" " "
return 0
}
Expand Down Expand Up @@ -634,15 +618,17 @@ _process_arguments() {
main() {
[[ $# = 0 ]] && _short_help

UTILS_FOLDER="${UTILS_FOLDER:-$(pwd)}"
UTILS_FOLDER="${UTILS_FOLDER:-${PWD}}"
{ . "${UTILS_FOLDER}"/common-utils.bash && . "${UTILS_FOLDER}"/drive-utils.bash; } || { printf "Error: Unable to source util files.\n" && exit 1; }

_check_bash_version && set -o errexit -o noclobber -o pipefail

_setup_arguments "${@}"
"${SKIP_INTERNET_CHECK:-_check_internet}"

[[ -n ${PARALLEL_UPLOAD} ]] && _setup_tempfile
[[ -n ${PARALLEL_UPLOAD} ]] && {
{ command -v mktemp 2> /dev/null && TMPFILE="$(mktemp -u)"; } || TMPFILE="${PWD}/$(printf "%(%s)T\\n" "-1").LOG"
}

_cleanup() {
{
Expand Down
46 changes: 31 additions & 15 deletions install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,16 @@ _check_debug() {
if [ -n "${DEBUG}" ]; then
_print_center() { { [ $# = 3 ] && printf "%s\n" "${2}"; } || { printf "%s%s\n" "${2}" "${3}"; }; }
_clear_line() { :; } && _newline() { :; }
set -x && PS4='-> '
set -x
else
if [ -z "${QUIET}" ]; then
if _is_terminal; then
if ! COLUMNS="$(_get_columns_size)" || [ "${COLUMNS:-0}" -lt 45 ]; then
# check if running in terminal and support ansi escape sequences
case "${TERM}" in
xterm* | rxvt* | urxvt* | linux* | vt*) ansi_escapes="true" ;;
esac
if [ -t 2 ] && [ -n "${ansi_escapes}" ]; then
! COLUMNS="$(_get_columns_size)" || [ "${COLUMNS:-0}" -lt 45 ] 2> /dev/null &&
_print_center() { { [ $# = 3 ] && printf "%s\n" "[ ${2} ]"; } || { printf "%s\n" "[ ${2}${3} ]"; }; }
fi
else
_print_center() { { [ $# = 3 ] && printf "%s\n" "[ ${2} ]"; } || { printf "%s\n" "[ ${2}${3} ]"; }; }
_clear_line() { :; }
Expand Down Expand Up @@ -185,10 +188,10 @@ _dirname() {
# use bash or zsh or stty or tput
###################################################
_get_columns_size() {
{ command -v bash 2> /dev/null 1>&2 && bash -c 'shopt -s checkwinsize && (: && :); printf "%s\n" "${COLUMNS}" 2>&1'; } ||
zsh -c 'printf "%s\n" "${COLUMNS}" 2>&1' 2> /dev/null ||
{ _tmp="$(stty size)" && printf "%s\n" "${_tmp##* }" 2> /dev/null; } ||
tput cols 2> /dev/null ||
{ command -v bash 1>| /dev/null && bash -c 'shopt -s checkwinsize && (: && :); printf "%s\n" "${COLUMNS}" 2>&1'; } ||
{ command -v zsh 1>| /dev/null && zsh -c 'printf "%s\n" "${COLUMNS}"'; } ||
{ command -v stty 1>| /dev/null && _tmp="$(stty size)" && printf "%s\n" "${_tmp##* }"; } ||
{ command -v tput 1>| /dev/null && tput cols; } ||
return 1
}

Expand Down Expand Up @@ -667,19 +670,32 @@ main() {

_variables && _setup_arguments "${@}"

_check_existing_command() {
if command -v "${COMMAND_NAME}" 2> /dev/null 1>&2; then
if grep -q COMMAND_NAME "${INFO_PATH}"/google-drive-upload.info 2> /dev/null 1>&2; then
return 0
else
printf "%s\n" "Error: Cannot validate existing installation, make sure no other program is installed as ${COMMAND_NAME}."
printf "%s\n" "You can use -c / --cmd flag to specify custom command name."
printf "%s\n" "Otherwise uninstall the ${COMMAND_NAME} command manually and run this script again."
exit 1
fi
else
return 1
fi
}

if [ -n "${UNINSTALL}" ]; then
{ command -v "${COMMAND_NAME}" 2> /dev/null 1>&2 && _uninstall; } || {
_print_center "justify" "google-drive-upload is not installed." "="
{ _check_existing_command && _uninstall; } || {
"${QUIET:-_print_center}" "justify" "google-drive-upload is not installed." "="
exit 0
}
else
"${SKIP_INTERNET_CHECK:-_check_internet}"
if command -v "${COMMAND_NAME}" 2> /dev/null 1>&2; then
INSTALL_PATH="$(_dirname "$(command -v "${COMMAND_NAME}")")"
_start update
else
{ _check_existing_command && INSTALL_PATH="$(_dirname "$(command -v "${COMMAND_NAME}")")" &&
_start update; } || {
_start install
fi
}
fi

return 0
Expand Down

0 comments on commit 65480d7

Please sign in to comment.