""" Output file objects for generator. """
import difflib
import os
import time
import subprocess
import sys
from idl_log import ErrOut, InfoOut, WarnOut
from idl_option import GetOption, Option, ParseOptions
from stat import *
Option('diff', 'Generate a DIFF when saving the file.')
class IDLOutFile(object):
def __init__(self, filename, always_write = False, create_dir = True):
self.filename = filename
self.always_write = always_write
self.create_dir = create_dir
self.outlist = []
self.open = True
def IsEquivalent_(self, oldtext):
if not oldtext: return False
oldlines = oldtext.split('\n')
curlines = (''.join(self.outlist)).split('\n')
if len(oldlines) != len(curlines):
return False
for index in range(len(oldlines)):
oldline = oldlines[index]
curline = curlines[index]
if oldline == curline: continue
curwords = curline.split()
oldwords = oldline.split()
if len(curwords) != len(oldwords):
return False
if curwords[0] not in ['*', '/*', '//']:
return False
if len(curwords) > 4 and curwords[1] == 'Copyright':
if curwords[4:] == oldwords[4:]: continue
if curwords[1] == 'From':
if curwords[0:4] == oldwords[0:4]: continue
if index > 0:
two_line_oldwords = oldlines[index - 1].split() + oldwords[1:]
two_line_curwords = curlines[index - 1].split() + curwords[1:]
if len(two_line_curwords) > 8 and two_line_curwords[1] == 'From':
if two_line_curwords[0:4] == two_line_oldwords[0:4]: continue
return False
return True
def Filename(self):
return self.filename
def Write(self, string):
if not self.open:
raise RuntimeError('Could not write to closed file %s.' % self.filename)
self.outlist.append(string)
def ClangFormat(self):
clang_format = subprocess.Popen(['clang-format', '-style=Chromium'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
new_output = clang_format.communicate("".join(self.outlist))[0]
self.outlist = [new_output]
def Close(self):
filename = os.path.realpath(self.filename)
self.open = False
outtext = ''.join(self.outlist)
oldtext = ''
if not self.always_write:
if os.path.isfile(filename):
with open(filename, 'r', encoding='utf-8') as fin:
oldtext = fin.read()
if self.IsEquivalent_(oldtext):
if GetOption('verbose'):
InfoOut.Log('Output %s unchanged.' % self.filename)
return False
if GetOption('diff'):
for line in difflib.unified_diff(oldtext.split('\n'), outtext.split('\n'),
'OLD ' + self.filename,
'NEW ' + self.filename,
n=1, lineterm=''):
ErrOut.Log(line)
try:
basepath, leafname = os.path.split(filename)
if basepath and not os.path.isdir(basepath) and self.create_dir:
InfoOut.Log('Creating directory: %s\n' % basepath)
os.makedirs(basepath)
if not GetOption('test'):
with open(filename, 'w', newline='\n', encoding='utf=8') as fout:
fout.write(outtext)
InfoOut.Log('Output %s written.' % self.filename)
return True
except IOError as e:
ErrOut.Log("I/O error(%d): %s" % (e.errno, e.strerror))
except:
ErrOut.Log("Unexpected error: %s" % sys.exc_info()[0])
raise
return False
def TestFile(name, stringlist, force, update):
errors = 0
if os.path.exists(name):
old_time = os.stat(filename)[ST_MTIME]
else:
old_time = 'NONE'
out = IDLOutFile(filename, force)
for item in stringlist:
out.Write(item)
time.sleep(2)
wrote = out.Close()
cur_time = os.stat(filename)[ST_MTIME]
if update:
if not wrote:
ErrOut.Log('Failed to write output %s.' % filename)
return 1
if cur_time == old_time:
ErrOut.Log('Failed to update timestamp for %s.' % filename)
return 1
else:
if wrote:
ErrOut.Log('Should not have writen output %s.' % filename)
return 1
if cur_time != old_time:
ErrOut.Log('Should not have modified timestamp for %s.' % filename)
return 1
return 0
def main():
errors = 0
stringlist = ['Test', 'Testing\n', 'Test']
filename = 'outtest.txt'
errors += TestFile(filename, stringlist, force=True, update=True)
errors += TestFile(filename, stringlist, force=False, update=False)
errors += TestFile(filename, stringlist + ['X'], force=False, update=True)
os.remove(filename)
if not errors: InfoOut.Log('All tests pass.')
return errors
if __name__ == '__main__':
sys.exit(main())