1# -*- coding: utf-8 -*- 2# Copyright 2019 The Chromium OS Authors. All rights reserved. 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5 6"""Utilities for operations on files.""" 7 8from __future__ import print_function 9 10import errno 11import os 12import shutil 13 14from cros_utils import command_executer 15 16 17class FileUtils(object): 18 """Utilities for operations on files.""" 19 _instance = None 20 DRY_RUN = False 21 22 @classmethod 23 def Configure(cls, dry_run): 24 cls.DRY_RUN = dry_run 25 26 def __new__(cls, *args, **kwargs): 27 if not cls._instance: 28 if cls.DRY_RUN: 29 cls._instance = super(FileUtils, cls).__new__(MockFileUtils, *args, 30 **kwargs) 31 else: 32 cls._instance = super(FileUtils, cls).__new__(cls, *args, **kwargs) 33 return cls._instance 34 35 def Md5File(self, filename, log_level='verbose', _block_size=2**10): 36 command = 'md5sum %s' % filename 37 ce = command_executer.GetCommandExecuter(log_level=log_level) 38 ret, out, _ = ce.RunCommandWOutput(command) 39 if ret: 40 raise RuntimeError('Could not run md5sum on: %s' % filename) 41 42 return out.strip().split()[0] 43 44 def CanonicalizeChromeOSRoot(self, chromeos_root): 45 chromeos_root = os.path.expanduser(chromeos_root) 46 if os.path.isdir(os.path.join(chromeos_root, 'chromite')): 47 return chromeos_root 48 else: 49 return None 50 51 def ChromeOSRootFromImage(self, chromeos_image): 52 chromeos_root = os.path.join( 53 os.path.dirname(chromeos_image), '../../../../..') 54 return self.CanonicalizeChromeOSRoot(chromeos_root) 55 56 def MkDirP(self, path): 57 try: 58 os.makedirs(path) 59 except OSError as exc: 60 if exc.errno == errno.EEXIST: 61 pass 62 else: 63 raise 64 65 def RmDir(self, path): 66 shutil.rmtree(path, ignore_errors=True) 67 68 def WriteFile(self, path, contents): 69 with open(path, 'w', encoding='utf-8') as f: 70 f.write(contents) 71 72 73class MockFileUtils(FileUtils): 74 """Mock class for file utilities.""" 75 76 def Md5File(self, filename, log_level='verbose', _block_size=2**10): 77 return 'd41d8cd98f00b204e9800998ecf8427e' 78 79 def CanonicalizeChromeOSRoot(self, chromeos_root): 80 return '/tmp/chromeos_root' 81 82 def ChromeOSRootFromImage(self, chromeos_image): 83 return '/tmp/chromeos_root' 84 85 def RmDir(self, path): 86 pass 87 88 def MkDirP(self, path): 89 pass 90 91 def WriteFile(self, path, contents): 92 pass 93