Skip to content

Commit

Permalink
Fix and add tests for the dehumanize function
Browse files Browse the repository at this point in the history
  • Loading branch information
Arturo Pie committed Oct 3, 2019
1 parent bd5fbab commit 0ae78f3
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 8 deletions.
9 changes: 1 addition & 8 deletions packer/linux/conf/bin/bk-check-disk-space.sh
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,7 @@ set -euo pipefail
# or 500M, or a percentage like 5%
# min inodes must be a number, default to 250,000

# Converts human-readable units like 1.43K and 120.3M to bytes
dehumanize() {
awk '/[0-9][bB]?$/ {printf "%u\n", $1*1024}
/[tT][bB]?$/ {printf "%u\n", $1*(1024*1024*1024)}
/[gG][bB]?$/ {printf "%u\n", $1*(1024*1024)}
/[mM][bB]?$/ {printf "%u\n", $1*(1024)}
/[kK][bB]?$/ {printf "%u\n", $1*1}' <<< "$1"
}
. "$(dirname "$0")"/dehumanize.sh

min_available=${1:-5G}
docker_dir="/var/lib/docker/"
Expand Down
39 changes: 39 additions & 0 deletions packer/linux/conf/bin/dehumanize-test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#!/bin/bash
set -o pipefail

. "$(dirname "$0")"/dehumanize.sh

test_without_unit(){
assertEquals 45 $(dehumanize 45)
}

test_bytes(){
assertEquals 45 $(dehumanize 45b)
assertEquals 45 $(dehumanize 45B)
}

test_kilobytes(){
assertEquals 46080 $(dehumanize 45kb)
assertEquals 46080 $(dehumanize 45KB)
}

test_megabytes(){
assertEquals 47185920 $(dehumanize 45mb)
assertEquals 47185920 $(dehumanize 45MB)
}

test_gigabytes(){
assertEquals 48318382080 $(dehumanize 45gb)
assertEquals 48318382080 $(dehumanize 45GB)
}

test_terabytes(){
assertEquals 49478023249920 $(dehumanize 45tb)
assertEquals 49478023249920 $(dehumanize 45TB)
}

test_using_decimals(){
assertEquals 1610612736 $(dehumanize 1.5gb)
}

. shunit2
10 changes: 10 additions & 0 deletions packer/linux/conf/bin/dehumanize.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/usr/bin/env bash

# Converts human-readable units like 1.43K and 120.3M to bytes
dehumanize() {
awk '/[0-9][bB]?$/ {printf "%u\n", $1*1}
/[tT][bB]?$/ {printf "%u\n", $1*(1024*1024*1024*1024)}
/[gG][bB]?$/ {printf "%u\n", $1*(1024*1024*1024)}
/[mM][bB]?$/ {printf "%u\n", $1*(1024*1024)}
/[kK][bB]?$/ {printf "%u\n", $1*1024}' <<< "$1"
}

0 comments on commit 0ae78f3

Please sign in to comment.