<commit_before># Copyright (c) 2014-present PlatformIO <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from email.utils import parsedate_tz
from math import ceil
from os.path import getsize, join
from sys import getfilesystemencoding, version_info
from time import mktime

import click
import requests

from platformio import util
from platformio.exception import (FDSHASumMismatch, FDSizeMismatch,
                                  FDUnrecognizedStatusCode)


class FileDownloader(object):

    CHUNK_SIZE = 1024

    def __init__(self, url, dest_dir=None):
        self._request = None
        # make connection
        self._request = requests.get(
            url,
            stream=True,
            headers=util.get_request_defheaders(),
            verify=version_info >= (2, 7, 9))
        if self._request.status_code != 200:
            raise FDUnrecognizedStatusCode(self._request.status_code, url)

        disposition = self._request.headers.get("content-disposition")
        if disposition and "filename=" in disposition:
            self._fname = disposition[
                disposition.index("filename=") + 9:].replace('"', "").replace(
                    "'", "")
            self._fname = self._fname.encode("utf8")
        else:
            self._fname = [p for p in url.split("/") if p][-1]

        self._progressbar = None
        self._destination = self._fname
        if dest_dir:
            self.set_destination(
                join(dest_dir.decode(getfilesystemencoding()), self._fname))

    def set_destination(self, destination):
        self._destination = destination

    def get_filepath(self):
        return self._destination

    def get_lmtime(self):
        return self._request.headers.get("last-modified")

    def get_size(self):
        if "content-length" not in self._request.headers:
            return -1
        return int(self._request.headers['content-length'])

    def start(self, with_progress=True):
        label = "Downloading"
        itercontent = self._request.iter_content(chunk_size=self.CHUNK_SIZE)
        f = open(self._destination, "wb")
        try:
            if not with_progress or self.get_size() == -1:
                click.echo("%s..." % label)
                for chunk in itercontent:
                    if chunk:
                        f.write(chunk)
            else:
                chunks = int(ceil(self.get_size() / float(self.CHUNK_SIZE)))
                with click.progressbar(length=chunks, label=label) as pb:
                    for _ in pb:
                        f.write(next(itercontent))
        except IOError as e:
            if with_progress:<commit_msg>Reinit download session when IOError<commit_after># Copyright (c) 2014-present PlatformIO <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from email.utils import parsedate_tz
from math import ceil
from os.path import getsize, join
from sys import getfilesystemencoding, version_info
from time import mktime

import click
import requests

from platformio import util
from platformio.exception import (FDSHASumMismatch, FDSizeMismatch,
                                  FDUnrecognizedStatusCode)


class FileDownloader(object):

    CHUNK_SIZE = 1024

    def __init__(self, url, dest_dir=None):
        self.url = url
        self._request = self.init_request()

        disposition = self._request.headers.get("content-disposition")
        if disposition and "filename=" in disposition:
            self._fname = disposition[
                disposition.index("filename=") + 9:].replace('"', "").replace(
                    "'", "")
            self._fname = self._fname.encode("utf8")
        else:
            self._fname = [p for p in url.split("/") if p][-1]

        self._destination = self._fname
        if dest_dir:
            self.set_destination(
                join(dest_dir.decode(getfilesystemencoding()), self._fname))

    def init_request(self):
        r = requests.get(
            self.url,
            stream=True,
            headers=util.get_request_defheaders(),
            verify=version_info >= (2, 7, 9))
        if r.status_code != 200:
            raise FDUnrecognizedStatusCode(r.status_code, self.url)
        return r

    def set_destination(self, destination):
        self._destination = destination

    def get_filepath(self):
        return self._destination

    def get_lmtime(self):
        return self._request.headers.get("last-modified")

    def get_size(self):
        if "content-length" not in self._request.headers:
            return -1
        return int(self._request.headers['content-length'])

    def start(self, with_progress=True):
        label = "Downloading"
        itercontent = self._request.iter_content(chunk_size=self.CHUNK_SIZE)
        f = open(self._destination, "wb")
        try:
            if not with_progress or self.get_size() == -1:
                click.echo("%s..." % label)
                for chunk in itercontent:
                    if chunk:
                        f.write(chunk)
            else:
                chunks = int(ceil(self.get_size() / float(self.CHUNK_SIZE)))
                with click.progressbar(length=chunks, label=label) as pb:
                    for _ in pb:
                        f.write(next(itercontent))
        except IOError as e:
            if with_progress:
                # reinitialize request
                self._request = self.init_request()
{'fraction_non_alphanumeric': 0.09306654257794322, 'fraction_numerical': 0.007135101597642315, 'mean_word_length': 2.2814249363867685, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 7, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2066090', 'n_tokens_mistral': 1778, 'n_tokens_neox': 1698, 'n_words': 507}