1# Utility functions used in conf.py 2# 3# Copyright 2017 Espressif Systems (Shanghai) PTE LTD 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http:#www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16 17from __future__ import unicode_literals 18 19import os 20import shutil 21import sys 22from io import open 23 24try: 25 import urllib.request 26 _urlretrieve = urllib.request.urlretrieve 27except ImportError: 28 # Python 2 fallback 29 import urllib 30 _urlretrieve = urllib.urlretrieve 31 32 33def files_equal(path_1, path_2): 34 if not os.path.exists(path_1) or not os.path.exists(path_2): 35 return False 36 file_1_contents = '' 37 with open(path_1, 'r', encoding='utf-8') as f_1: 38 file_1_contents = f_1.read() 39 file_2_contents = '' 40 with open(path_2, 'r', encoding='utf-8') as f_2: 41 file_2_contents = f_2.read() 42 return file_1_contents == file_2_contents 43 44 45def copy_file_if_modified(src_file_path, dst_file_path): 46 if not files_equal(src_file_path, dst_file_path): 47 dst_dir_name = os.path.dirname(dst_file_path) 48 if not os.path.isdir(dst_dir_name): 49 os.makedirs(dst_dir_name) 50 shutil.copy(src_file_path, dst_file_path) 51 52 53def copy_if_modified(src_path, dst_path): 54 if os.path.isfile(src_path): 55 copy_file_if_modified(src_path, dst_path) 56 return 57 58 src_path_len = len(src_path) 59 for root, dirs, files in os.walk(src_path): 60 for src_file_name in files: 61 src_file_path = os.path.join(root, src_file_name) 62 dst_file_path = os.path.join(dst_path + root[src_path_len:], src_file_name) 63 copy_file_if_modified(src_file_path, dst_file_path) 64 65 66def download_file_if_missing(from_url, to_path): 67 filename_with_path = to_path + '/' + os.path.basename(from_url) 68 exists = os.path.isfile(filename_with_path) 69 if exists: 70 print("The file '%s' already exists" % (filename_with_path)) 71 else: 72 tmp_file, header = _urlretrieve(from_url) 73 with open(filename_with_path, 'wb') as fobj: 74 with open(tmp_file, 'rb') as tmp: 75 fobj.write(tmp.read()) 76 77 78def call_with_python(cmd): 79 # using sys.executable ensures that the scripts are called with the same Python interpreter 80 if os.system('{} {}'.format(sys.executable, cmd)) != 0: 81 raise RuntimeError('{} failed'.format(cmd)) 82