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