Skip to content
This repository was archived by the owner on Oct 16, 2024. It is now read-only.

Commit 70a0a72

Browse files
authored
Merge pull request #27 from bartosh/master
Ported to Python3. Fixes #14
2 parents 7a9e2b1 + 433495d commit 70a0a72

19 files changed

+183
-104
lines changed

.travis.yml

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,13 @@ language: python
22
python:
33
- "2.6"
44
- "2.7"
5-
# bmap-tools don't support 3.x yet, thus disable.
6-
# pypy 2.x currently also disabled, until testing fixed.
7-
# - "3.2"
8-
# - "3.3"
9-
# - "3.4"
10-
# - "3.5"
11-
# - "3.5-dev" # 3.5 development branch
12-
# - "nightly" # currently points to 3.6-dev
5+
- "3.3"
6+
- "3.4"
7+
- "3.5"
8+
- "3.6"
9+
- "3.7-dev" # 3.7 development branch
10+
- "nightly" # currently points to 3.6-dev
11+
# pypy 2.x currently disabled, until testing fixed.
1312
# - "pypy"
1413
# - "pypy3"
1514
# command to install dependencies

bmaptools/BmapCopy.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -61,16 +61,21 @@
6161
import sys
6262
import hashlib
6363
import logging
64-
import Queue
65-
import thread
6664
import datetime
65+
if sys.version[0] == '2':
66+
import Queue
67+
import thread
68+
else:
69+
import queue as Queue
70+
import _thread as thread
71+
6772
from xml.etree import ElementTree
6873
from bmaptools.BmapHelpers import human_size
6974

7075
_log = logging.getLogger(__name__) # pylint: disable=C0103
7176

7277
# The highest supported bmap format version
73-
SUPPORTED_BMAP_VERSION = 2
78+
SUPPORTED_BMAP_VERSION = "2.0"
7479

7580

7681
class Error(Exception):
@@ -208,7 +213,7 @@ def __init__(self, image, dest, bmap=None, image_size=None):
208213
if image_size:
209214
self._set_image_size(image_size)
210215

211-
self._batch_blocks = self._batch_bytes / self.block_size
216+
self._batch_blocks = self._batch_bytes // self.block_size
212217

213218
def set_progress_indicator(self, file_obj, format_string):
214219
"""
@@ -241,8 +246,7 @@ def _set_image_size(self, image_size):
241246

242247
self.image_size = image_size
243248
self.image_size_human = human_size(image_size)
244-
self.blocks_cnt = self.image_size + self.block_size - 1
245-
self.blocks_cnt /= self.block_size
249+
self.blocks_cnt = (self.image_size + self.block_size - 1) // self.block_size
246250

247251
if self.mapped_cnt is None:
248252
self.mapped_cnt = self.blocks_cnt
@@ -264,10 +268,10 @@ def _verify_bmap_checksum(self):
264268
mapped_bmap = mmap.mmap(self._f_bmap.fileno(), 0,
265269
access=mmap.ACCESS_COPY)
266270

267-
chksum_pos = mapped_bmap.find(correct_chksum)
271+
chksum_pos = mapped_bmap.find(correct_chksum.encode())
268272
assert chksum_pos != -1
269273

270-
mapped_bmap[chksum_pos:chksum_pos + self._cs_len] = '0' * self._cs_len
274+
mapped_bmap[chksum_pos:chksum_pos + self._cs_len] = b'0' * self._cs_len
271275

272276
hash_obj = hashlib.new(self._cs_type)
273277
hash_obj.update(mapped_bmap)
@@ -305,7 +309,7 @@ def _parse_bmap(self):
305309
# Make sure we support this version
306310
self.bmap_version_major = int(self.bmap_version.split('.', 1)[0])
307311
self.bmap_version_minor = int(self.bmap_version.split('.', 1)[1])
308-
if self.bmap_version_major > SUPPORTED_BMAP_VERSION:
312+
if self.bmap_version_major > int(SUPPORTED_BMAP_VERSION.split('.', 1)[0]):
309313
raise Error("only bmap format version up to %d is supported, "
310314
"version %d is not supported"
311315
% (SUPPORTED_BMAP_VERSION, self.bmap_version_major))
@@ -320,7 +324,7 @@ def _parse_bmap(self):
320324
self.mapped_size_human = human_size(self.mapped_size)
321325
self.mapped_percent = (self.mapped_cnt * 100.0) / self.blocks_cnt
322326

323-
blocks_cnt = (self.image_size + self.block_size - 1) / self.block_size
327+
blocks_cnt = (self.image_size + self.block_size - 1) // self.block_size
324328
if self.blocks_cnt != blocks_cnt:
325329
raise Error("Inconsistent bmap - image size does not match "
326330
"blocks count (%d bytes != %d blocks * %d bytes)"
@@ -514,7 +518,7 @@ def _get_data(self, verify):
514518
if verify and chksum:
515519
hash_obj.update(buf)
516520

517-
blocks = (len(buf) + self.block_size - 1) / self.block_size
521+
blocks = (len(buf) + self.block_size - 1) // self.block_size
518522
_log.debug("queueing %d blocks, queue length is %d" %
519523
(blocks, self._batch_queue.qsize()))
520524

@@ -577,7 +581,7 @@ def copy(self, sync=True, verify=True):
577581
# The reader thread encountered an error and passed us the
578582
# exception.
579583
exc_info = batch[1]
580-
raise exc_info[0], exc_info[1], exc_info[2]
584+
raise exc_info[1].with_traceback(exc_info[2])
581585

582586
(start, end, buf) = batch[1:4]
583587

@@ -664,7 +668,7 @@ def __init__(self, image, dest, bmap=None, image_size=None):
664668
# Call the base class constructor first
665669
BmapCopy.__init__(self, image, dest, bmap, image_size)
666670

667-
self._dest_fsync_watermark = (6 * 1024 * 1024) / self.block_size
671+
self._dest_fsync_watermark = (6 * 1024 * 1024) // self.block_size
668672

669673
self._sysfs_base = None
670674
self._sysfs_scheduler_path = None

bmaptools/BmapCreate.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ def _bmap_file_end(self):
282282

283283
self._f_bmap.seek(0)
284284
hash_obj = hashlib.new(self._cs_type)
285-
hash_obj.update(self._f_bmap.read())
285+
hash_obj.update(self._f_bmap.read().encode())
286286
chksum = hash_obj.hexdigest()
287287
self._f_bmap.seek(self._chksum_pos)
288288
self._f_bmap.write("%s" % chksum)

bmaptools/CLI.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -451,7 +451,7 @@ def copy_command(args):
451451

452452
# Print the progress indicator while copying
453453
if not args.quiet and not args.debug and \
454-
os.isatty(sys.stderr.fileno()) and os.isatty(sys.stdout.fileno()):
454+
sys.stderr.isatty() and sys.stdout.isatty():
455455
writer.set_progress_indicator(sys.stderr, "bmaptool: info: %d%% copied")
456456

457457
start_time = time.time()
@@ -491,7 +491,7 @@ def copy_command(args):
491491
raise SystemExit(1)
492492

493493
copying_time = time.time() - start_time
494-
copying_speed = writer.mapped_size / copying_time
494+
copying_speed = writer.mapped_size // copying_time
495495
log.info("copying time: %s, copying speed %s/sec"
496496
% (BmapHelpers.human_time(copying_time),
497497
BmapHelpers.human_size(copying_speed)))
@@ -720,12 +720,12 @@ def main():
720720
log.info("The contents of /proc/meminfo:")
721721
with open('/proc/meminfo', 'rt') as file_obj:
722722
for line in file_obj:
723-
print line,
723+
print(line.strip())
724724

725725
log.info("The contents of /proc/self/status:")
726726
with open('/proc/self/status', 'rt') as file_obj:
727727
for line in file_obj:
728-
print line,
728+
print(line.strip())
729729

730730
if __name__ == "__main__":
731731
sys.exit(main())

bmaptools/Filemap.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,7 @@ def __init__(self, image):
8585
raise Error("cannot get block size for '%s': %s"
8686
% (self._image_path, err))
8787

88-
self.blocks_cnt = self.image_size + self.block_size - 1
89-
self.blocks_cnt /= self.block_size
88+
self.blocks_cnt = (self.image_size + self.block_size - 1) // self.block_size
9089

9190
try:
9291
self._f_image.flush()
@@ -247,7 +246,7 @@ def block_is_mapped(self, block):
247246
if offs == -1:
248247
result = False
249248
else:
250-
result = (offs / self.block_size == block)
249+
result = (offs // self.block_size == block)
251250

252251
_log.debug("FilemapSeek: block_is_mapped(%d) returns %s"
253252
% (block, result))
@@ -279,8 +278,8 @@ def _get_ranges(self, start, count, whence1, whence2):
279278
if end > limit:
280279
end = limit
281280

282-
start_blk = start / self.block_size
283-
end_blk = end / self.block_size - 1
281+
start_blk = start // self.block_size
282+
end_blk = end // self.block_size - 1
284283
_log.debug("FilemapSeek: yielding range (%d, %d)"
285284
% (start_blk, end_blk))
286285
yield (start_blk, end_blk)
@@ -345,7 +344,7 @@ def __init__(self, image):
345344

346345
# Calculate how many 'struct fiemap_extent' elements fit the buffer
347346
self._buf_size -= _FIEMAP_SIZE
348-
self._fiemap_extent_cnt = self._buf_size / _FIEMAP_EXTENT_SIZE
347+
self._fiemap_extent_cnt = self._buf_size // _FIEMAP_EXTENT_SIZE
349348
assert self._fiemap_extent_cnt > 0
350349
self._buf_size = self._fiemap_extent_cnt * _FIEMAP_EXTENT_SIZE
351350
self._buf_size += _FIEMAP_SIZE
@@ -450,11 +449,11 @@ def _do_get_mapped_ranges(self, start, count):
450449
# Start of the extent
451450
extent_start = fiemap_extent[0]
452451
# Starting block number of the extent
453-
extent_block = extent_start / self.block_size
452+
extent_block = extent_start // self.block_size
454453
# Length of the extent
455454
extent_len = fiemap_extent[2]
456455
# Count of blocks in the extent
457-
extent_count = extent_len / self.block_size
456+
extent_count = extent_len // self.block_size
458457

459458
# Extent length and offset have to be block-aligned
460459
assert extent_start % self.block_size == 0
@@ -476,7 +475,7 @@ def get_mapped_ranges(self, start, count):
476475
_log.debug("FilemapFiemap: get_mapped_ranges(%d, %d(%d))"
477476
% (start, count, start + count - 1))
478477
iterator = self._do_get_mapped_ranges(start, count)
479-
first_prev, last_prev = iterator.next()
478+
first_prev, last_prev = next(iterator)
480479

481480
for first, last in iterator:
482481
if last_prev == first - 1:

bmaptools/TransRead.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,11 @@
2626

2727
import os
2828
import errno
29-
import urlparse
29+
import sys
30+
if sys.version[0] == '2':
31+
import urlparse
32+
else:
33+
import urllib.parse as urlparse
3034
import logging
3135
import threading
3236
import subprocess
@@ -376,7 +380,7 @@ def is_tar_lz4(name):
376380
else:
377381
args = decompressor + " " + args
378382

379-
if type(self._f_objs[-1]) == file:
383+
if hasattr(self._f_objs[-1], 'fileno'):
380384
child_stdin = self._f_objs[-1].fileno()
381385
else:
382386
child_stdin = subprocess.PIPE
@@ -487,10 +491,15 @@ def _print_warning(timeout):
487491
"proxy configured correctly? Keep trying ..." %
488492
timeout)
489493

490-
import urllib2
491-
import httplib
492494
import socket
493495

496+
if sys.version[0] == '2':
497+
import httplib
498+
import urllib2
499+
else:
500+
import http.client as httplib
501+
import urllib.request as urllib2
502+
494503
parsed_url = urlparse.urlparse(url)
495504

496505
if parsed_url.scheme == "ssh":
@@ -535,7 +544,7 @@ def _print_warning(timeout):
535544
try:
536545
f_obj = opener.open(url, timeout=timeout)
537546
# Handling the timeout case in Python 2.7
538-
except socket.timeout, err:
547+
except socket.timeout as err:
539548
if timeout is not None:
540549
_print_warning(timeout)
541550
else:

setup.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,5 +34,9 @@ def get_version():
3434
"can be copied or flashed a lot faster with bmaptool "
3535
"than with traditional tools like \"dd\" or \"cp\". See "
3636
"source.tizen.org/documentation/reference/bmaptool for "
37-
"more information."
37+
"more information.",
38+
classifiers=[
39+
"Programming Language :: Python :: 2.7",
40+
"Programming Language :: Python :: 3"
41+
]
3842
)

tests/helpers.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
import random
2828
import itertools
2929
import hashlib
30+
import struct
3031
import sys
3132
import os
3233
from bmaptools import BmapHelpers, BmapCopy, TransRead
@@ -43,7 +44,7 @@ def _create_random_sparse_file(file_obj, size):
4344

4445
file_obj.truncate(size)
4546
block_size = BmapHelpers.get_block_size(file_obj)
46-
blocks_cnt = (size + block_size - 1) / block_size
47+
blocks_cnt = (size + block_size - 1) // block_size
4748

4849
def process_block(block):
4950
"""
@@ -60,17 +61,16 @@ def process_block(block):
6061
write = random.randint(1, block_size - seek)
6162
assert seek + write <= block_size
6263
file_obj.seek(block * block_size + seek)
63-
file_obj.write(chr(random.getrandbits(8)) * write)
64-
64+
file_obj.write(struct.pack("=B", random.getrandbits(8)) * write)
6565
return map_the_block
6666

6767
mapped = []
6868
unmapped = []
69-
iterator = xrange(0, blocks_cnt)
69+
iterator = range(0, blocks_cnt)
7070
for was_mapped, group in itertools.groupby(iterator, process_block):
7171
# Start of a mapped region or a hole. Find the last element in the
7272
# group.
73-
first = group.next()
73+
first = next(group)
7474
last = first
7575
for last in group:
7676
pass
@@ -98,7 +98,8 @@ def _create_random_file(file_obj, size):
9898
if written + chunk_size > size:
9999
chunk_size = size - written
100100

101-
file_obj.write(chr(random.getrandbits(8)) * chunk_size)
101+
file_obj.write(struct.pack("=B", random.getrandbits(8)) * chunk_size)
102+
102103
written += chunk_size
103104

104105
file_obj.flush()
@@ -161,13 +162,13 @@ def generate_test_files(max_size=4 * 1024 * 1024, directory=None, delete=True):
161162
file_obj.close()
162163

163164
# And 10 holes of random size
164-
for i in xrange(10):
165+
for i in range(10):
165166
size = random.randint(1, max_size)
166167
file_obj = tempfile.NamedTemporaryFile("wb+", suffix=".img",
167168
delete=delete, dir=directory,
168169
prefix="rand_hole_%d_" % i)
169170
file_obj.truncate(size)
170-
blocks_cnt = (size + block_size - 1) / block_size
171+
blocks_cnt = (size + block_size - 1) // block_size
171172
yield (file_obj, size, [], [(0, blocks_cnt - 1)])
172173
file_obj.close()
173174

@@ -200,7 +201,7 @@ def generate_test_files(max_size=4 * 1024 * 1024, directory=None, delete=True):
200201
file_obj.close()
201202

202203
# And 10 files of random size
203-
for i in xrange(10):
204+
for i in range(10):
204205
size = random.randint(1, max_size)
205206
file_obj = tempfile.NamedTemporaryFile("wb+", suffix=".img",
206207
delete=delete, dir=directory,
@@ -246,13 +247,13 @@ def generate_test_files(max_size=4 * 1024 * 1024, directory=None, delete=True):
246247
file_obj.close()
247248

248249
# And 10 mapped files of random size
249-
for i in xrange(10):
250+
for i in range(10):
250251
size = random.randint(1, max_size)
251252
file_obj = tempfile.NamedTemporaryFile("wb+", suffix=".img",
252253
delete=delete, dir=directory,
253254
prefix="rand_mapped_%d_" % i)
254255
_create_random_file(file_obj, size)
255-
blocks_cnt = (size + block_size - 1) / block_size
256+
blocks_cnt = (size + block_size - 1) // block_size
256257
yield (file_obj, size, [(0, blocks_cnt - 1)], [])
257258
file_obj.close()
258259

@@ -282,16 +283,15 @@ def copy_and_verify_image(image, dest, bmap, image_chksum, image_size):
282283
"""
283284

284285
f_image = TransRead.TransRead(image)
285-
f_dest = open(dest, "w+")
286+
f_dest = open(dest, "w+b")
286287
if (bmap):
287288
f_bmap = open(bmap, "r")
288289
else:
289290
f_bmap = None
290291

291292
writer = BmapCopy.BmapCopy(f_image, f_dest, f_bmap, image_size)
292293
# Randomly decide whether we want the progress bar or not
293-
if bool(random.getrandbits(1)) and hasattr(sys.stdout, 'fileno') and \
294-
os.isatty(sys.stdout.fileno()):
294+
if bool(random.getrandbits(1)) and sys.stdout.isatty():
295295
writer.set_progress_indicator(sys.stdout, None)
296296
writer.copy(bool(random.getrandbits(1)), bool(random.getrandbits(1)))
297297

0 commit comments

Comments
 (0)