Skip to content

Commit

Permalink
add functions to check whether a dir is empty or not
Browse files Browse the repository at this point in the history
  • Loading branch information
georglauterbach committed Aug 28, 2024
1 parent 8a715ff commit d728a69
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 1 deletion.
33 changes: 32 additions & 1 deletion modules/utils.sh
Original file line number Diff line number Diff line change
Expand Up @@ -325,5 +325,36 @@ function is_in_path() {
#
# $1 :: executable to check
function is_not_in_path() {
! is_in_path "${1:?}"
! is_in_path "${1}"
}

# ### Check Whether a Directory is Empty
#
# This function checks whether a directory
# contains files or other directories, and
# returns false if so.
#
# #### Arguments
#
# $1 :: directory to check
function dir_is_empty() {
parameter_is_not_empty "${1}" || {
log 'error' 'No name for an executable provided'
return 1
}

[[ -n $(find "${1}" -maxdepth 0 -empty) ]]
}

# ### Check Whether a Directory is Not Empty
#
# This function checks whether a directory
# contains files or other directories, and
# returns true if so.
#
# #### Arguments
#
# $1 :: directory to check
function dir_is_not_empty() {
! dir_is_empty "${1}"
}
38 changes: 38 additions & 0 deletions tests/40-utils.bats
Original file line number Diff line number Diff line change
Expand Up @@ -410,3 +410,41 @@ function setup() { source load 'log' 'utils' ; }
run is_not_in_path ls
assert_failure
}

@test "dir is empty or not works correctly" {
local TEST_DIR='/tmp/.libbash_tests/test_dir'
rm -rf "${TEST_DIR}"
mkdir -p "${TEST_DIR}"

run dir_is_empty "${TEST_DIR}"
assert_success

run dir_is_not_empty "${TEST_DIR}"
assert_failure

touch "${TEST_DIR}/test_file"

run dir_is_empty "${TEST_DIR}"
assert_failure

run dir_is_not_empty "${TEST_DIR}"
assert_success

rm "${TEST_DIR}/test_file"
mkdir "${TEST_DIR}/test_dir_2"

run dir_is_empty "${TEST_DIR}"
assert_failure

run dir_is_not_empty "${TEST_DIR}"
assert_success

rmdir "${TEST_DIR}/test_dir_2"
touch "${TEST_DIR}/.hidden_file"

run dir_is_empty "${TEST_DIR}"
assert_failure

run dir_is_not_empty "${TEST_DIR}"
assert_success
}

0 comments on commit d728a69

Please sign in to comment.