Skip to content

Commit

Permalink
Merge pull request #213 from fls-bioinformatics-core/utils-convert_si…
Browse files Browse the repository at this point in the history
…ze_to_bytes

bcftbx/utils: new function 'convert_size_to_bytes'
  • Loading branch information
pjbriggs committed Jul 10, 2023
2 parents 2110765 + 68d4371 commit 199d9ef
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
14 changes: 14 additions & 0 deletions bcftbx/test/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -801,6 +801,20 @@ def test_bytes_to_tb(self):
self.assertEqual("0.0T",format_file_size(195035136,units='T'))
self.assertEqual("0.2T",format_file_size(171798691900,units='T'))

class TestConvertSizeToBytes(unittest.TestCase):
"""
Unit tests for converting file sizes to bytes
"""
def test_convert_size_to_bytes(self):
"""
convert_size_to_bytes: handle different inputs
"""
self.assertEqual(convert_size_to_bytes('4.0K'),4096)
self.assertEqual(convert_size_to_bytes('4.0M'),4194304)
self.assertEqual(convert_size_to_bytes('4.0G'),4294967296)
self.assertEqual(convert_size_to_bytes('4.0T'),4398046511104)
self.assertEqual(convert_size_to_bytes('4T'),4398046511104)

class ExampleDirLinks(ExampleDirSpiders):
"""Extended example dir for testing symbolic link handling
Expand Down
27 changes: 25 additions & 2 deletions bcftbx/utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# utils.py: utility classes and functions shared between BCF codes
# Copyright (C) University of Manchester 2013-2020 Peter Briggs
# Copyright (C) University of Manchester 2013-2023 Peter Briggs
#
########################################################################
#
Expand Down Expand Up @@ -31,6 +31,7 @@
chmod
touch
format_file_size
convert_size_to_bytes
commonprefix
is_gzipped_file
rootname
Expand Down Expand Up @@ -91,6 +92,7 @@
import datetime
import re
import socket
import math
from builtins import range

#######################################################################
Expand Down Expand Up @@ -716,7 +718,28 @@ def format_file_size(fsize,units=None):
else:
break
return "%.1f%s" % (fsize,unit)


def convert_size_to_bytes(size):
"""
Converts a human-readable size specification to bytes
Given an arbitary human-readable file size (e.g.
'4.0K', '186M', '1.5G'), returns the equivalent size
in bytes.
Arguments:
size (str): size specification string
Returns:
Integer: size expressed as number of bytes.
"""
try:
return int(str(size))
except ValueError:
units = str(size)[-1].upper()
p = "KMGTP".index(units) + 1
return int(float(str(size)[:-1])) * int(math.pow(1024,p))

def commonprefix(path1,path2):
"""Determine common prefix path for path1 and path2
Expand Down

0 comments on commit 199d9ef

Please sign in to comment.