From 49960b257dec1d1c4f49c17a03f39fac64b20d5f Mon Sep 17 00:00:00 2001 From: Ivan Kravets Date: Thu, 28 May 2020 16:07:02 +0300 Subject: [PATCH] Implement fs.calculate_file_hashsum --- platformio/downloader.py | 17 ++++------------- platformio/fs.py | 13 +++++++++++++ 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/platformio/downloader.py b/platformio/downloader.py index 21f5477b..ccbc5b36 100644 --- a/platformio/downloader.py +++ b/platformio/downloader.py @@ -12,7 +12,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -import hashlib import io import math import sys @@ -23,7 +22,7 @@ from time import mktime import click import requests -from platformio import app, util +from platformio import app, fs, util from platformio.exception import ( FDSHASumMismatch, FDSizeMismatch, @@ -103,17 +102,9 @@ class FileDownloader(object): raise FDSizeMismatch(_dlsize, self._fname, self.get_size()) if not sha1: return None - - checksum = hashlib.sha1() - with io.open(self._destination, "rb", buffering=0) as fp: - while True: - chunk = fp.read(io.DEFAULT_BUFFER_SIZE) - if not chunk: - break - checksum.update(chunk) - - if sha1.lower() != checksum.hexdigest().lower(): - raise FDSHASumMismatch(checksum.hexdigest(), self._fname, sha1) + checksum = fs.calculate_file_hashsum("sha1", self._destination) + if sha1.lower() != checksum.lower(): + raise FDSHASumMismatch(checksum, self._fname, sha1) return True def _preserve_filemtime(self, lmdate): diff --git a/platformio/fs.py b/platformio/fs.py index 5122c882..7a592746 100644 --- a/platformio/fs.py +++ b/platformio/fs.py @@ -12,6 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. +import hashlib +import io import json import os import re @@ -72,6 +74,17 @@ def format_filesize(filesize): return "%d%sB" % ((base * filesize / unit), suffix) +def calculate_file_hashsum(algorithm, path): + h = hashlib.new(algorithm) + with io.open(path, "rb", buffering=0) as fp: + while True: + chunk = fp.read(io.DEFAULT_BUFFER_SIZE) + if not chunk: + break + h.update(chunk) + return h.hexdigest() + + def ensure_udev_rules(): from platformio.util import get_systype # pylint: disable=import-outside-toplevel