Документ взят из кэша поисковой машины. Адрес оригинального документа : http://www.stsci.edu/spst/UnixTransition/doc/difference_prd_files.py
Дата изменения: Fri Feb 28 14:46:09 2014
Дата индексирования: Sat Mar 1 22:18:06 2014
Кодировка:

Поисковые слова: п п п п п п п п п п п п п п п п п п п
#!/usr/bin/env python
#MODULE build_prd_files
#
#***********************************************************************
"""

**PURPOSE** --

This script compares a new PRD file with a reference PRD file.
It uses the gnu diff utility for the difference.

python difference_prd_files.py

where:
branch name = OPS or SM4

**DEVELOPER** --
R. Kantor

**MODIFICATION HISTORY** --

o Initial implementation 3/30/04 RK
o Updated 4/15/04 KWC - Removed from build_PRD_file.py.
"""
#***********************************************************************
import os, string, sys

__version__ = " 4/15/04"

class difference_prd_file:

def __init__(self):
""" Constructor.
"""
self.new_PRD_file = None
self.ref_PRD_file = None
self.dif_lis = []

def find_ref_file (self, branch_name):
""" Find the reference PRD file to compare against.
"""
# Determine if this is Operational or a Servicing Mission PRD file.
if (string.upper(branch_name) == "OPS"):
ref_env = "PDB"
elif (string.upper(branch_name) != None):
ref_env = "SMDB"
else:
ref_env = None
print " *** Error - Must select OPS or SM4 library."
print " Can't difference installed file with:", \
self.new_PRD_file
return

# Determine which directory the reference PRD files are in.
ref_PRD_dir = os.getenv(string.upper(ref_env))
if (ref_PRD_dir == None):
print " *** Error - Can't find environment variable for PRD", \
" directory:", ref_env
print " Can't difference installed file with:", \
self.new_PRD_file
return

# Determine if the reference file exists.
ref_PRD_file = os.path.join(ref_PRD_dir,self.new_PRD_file)
if (os.path.isfile(ref_PRD_file) == 0):
print " *** Error - Unable to locate reference PRD file:", \
ref_PRD_file

self.ref_PRD_file = ref_PRD_file

def strip_numbers (self, infile, outfile):
""" Create new file without line numbers. Lines will have 74 columns.
"""
input = open(infile, "r")

newlines = []
for line in input.readlines():
new_line = "%s\n" % line[:74]
newlines.append(new_line)
input.close()

output = open(outfile, "w")
for line in newlines:
output.write(line)
output.close()

def capture_cmd (self, cmd):
""" Replacement for os.system that gets stdout and stderr
"""
cmd_data = []

# Spawn a child process to execute the command and capture all its
# output.
cin,cout,cerr = os.popen3(cmd)

# Store the response.
line = cout.readline()
while line:
cmd_data.append(line)
line = cout.readline()

# Store any errors.
line = cerr.readline()
while line:
cmd_data.append(line)
line = cerr.readline()

#Close the pipe.
cin.close ()
cout.close ()
cerr.close ()

# Return the response.
return cmd_data

def get_diff (self):
""" Returns a data list of the difference.
"""
return self.dif_lis

def write_dif (self):
""" Writes the results of the file difference to disk.
"""
# Get the file name to create the difference file name.
file_type,ext = os.path.splitext(os.path.basename(self.new_PRD_file))

results_file = file_type + ".dif"

if (len(self.dif_lis) > 0):
output = open(results_file, "w")
output.writelines(self.dif_lis)
output.close()

def compare_file(self):
""" Compare the new file with the old file.
"""
self.dif_lis = []

# Strip the numbers off the reference PRD file.
no_number_old_file = "old_" + os.path.basename(self.ref_PRD_file)
self.strip_numbers(self.ref_PRD_file, no_number_old_file)

# Strip the numbers off the new PRD file.
no_number_new_file = "new_" + os.path.basename(self.new_PRD_file)
self.strip_numbers(self.new_PRD_file, no_number_new_file)

cmd = "gdiff -y --width=80 --suppress " + no_number_new_file + " "
cmd += no_number_old_file

print "\nDifferencing the new file with the installed file"
print "Line numbers have been stripped from both files"
print "The results of the differencing (which may be blank) follow:\n"

# Difference the files.
self.dif_lis = self.capture_cmd(cmd)
sys.stdout.flush()

# Display the results.
if (len(self.dif_lis) > 0):
self.write_dif()
sys.stdout.writelines(self.dif_lis)

def compare_install_file(self, file_name, branch_name):
""" Compare the new file with the installed file.
"""
self.new_PRD_file = file_name
if (self.new_PRD_file == None):
return

# Check if the new file exists.
if (os.path.isfile(self.new_PRD_file) != 1):
print " *** Error - Unable to locate new PRD file:", \
self.new_PRD_file
return

# Find the location of the reference PRD file.
self.find_ref_file(branch_name)

# Do the difference.
if (self.ref_PRD_file != None):
self.compare_file()

def compare_PRD_files(self, new_file_name, old_file_name):
""" Compare the new file with the installed file.
"""
self.new_PRD_file = new_file_name
self.ref_PRD_file = old_file_name

if ((self.new_PRD_file == None) or (self.ref_PRD_file == None)):
return

# Check if the new file exists.
if (os.path.isfile(self.new_PRD_file) != 1):
print " *** Error - Unable to locate new PRD file:", \
self.new_PRD_file
return

# Check if the old file exists.
if (os.path.isfile(self.ref_PRD_file) != 1):
print " *** Error - Unable to locate old PRD file:", \
self.ref_PRD_file
return

# Do the difference.
self.compare_file()


# -------------- Run time interface ------------------------------------
import spst_getopt, glob

def run (file_name, branch_name=None, old_file=None, *args):
""" Compare a new PRD file with a reference PRD file.
This uses the gnu diff utility for the difference.

Usage:
do difference_prd_files -PRD_lib=
-old_file=
where:
file name = New PRD file name.

run options:
-PRD_lib = Difference new file against
OPS or SM4 reference file.
-old_file = Difference new file against
old file.

"""

if (not file_name):
# Spew out the usage and quit when no initial directory
# is provided.
print run.__doc__
return

allowed_options = ['PRD_lib=', 'old_file=']
try:
options, parms = spst_getopt.spst_getopt(sys.argv, allowed_options)
except Exception,e:
e = '%s\n%s' %(e,run.__doc__)
raise IOError(e)

branch_name = None
if '-PRD_lib' in options.keys():
branch_name = options['-PRD_lib']

old_file = None
if '-old_file' in options.keys():
old_file = options['-old_file']

if ((branch_name == None) and (old_file == None)):
# Spew out the usage and quit when no comparision file
# is provided.
print run.__doc__
return

diff_util = difference_prd_file()

# Handle a single file.
if (os.path.isfile(file_name)):
new_file_list = [file_name]
else:
# Handle a list of files.
new_file_list = glob.glob (file_name)

if (len(new_file_list) == 0):
print " *** Error - Unable to find file:", file_name
else:
for new_file in new_file_list:
if (branch_name != None):
# Compare against installed reference PRD file.
diff_util.compare_install_file(new_file, branch_name)
elif (old_file != None):
# If just a directory given then append the new file name to it.
if os.path.isdir(old_file):
ref_file = os.path.join(old_file,os.path.basename(new_file))
else:
ref_file = old_file

# Compare against user specified file.
diff_util.compare_PRD_files(new_file, ref_file)

if __name__ == '__main__':

if (len(sys.argv) <= 2):
print run.__doc__
sys.exit(1)

file_name = sys.argv[1]
allowed_options = ['PRD_lib=', 'old_file=']
try:
options, parms = spst_getopt.spst_getopt(sys.argv, allowed_options)
except Exception,e:
e = '%s\n%s' %(e,run.__doc__)
raise IOError(e)

branch_name = None
if '-PRD_lib' in options.keys():
branch_name = options['-PRD_lib']

old_file = None
if '-old_file' in options.keys():
old_file = options['-old_file']

if ((branch_name == None) and (old_file == None)):
# Spew out the usage and quit when no comparision file
# is provided.
print run.__doc__
sys.exit(1)

diff_util = difference_prd_file()

# Handle a single file.
if (os.path.isfile(file_name)):
new_file_list = [file_name]
else:
# Handle a list of files.
new_file_list = glob.glob (file_name)

if (len(new_file_list) == 0):
print " *** Error - Unable to find file:", file_name
else:
for new_file in new_file_list:
if (branch_name != None):
# Compare against installed reference PRD file.
diff_util.compare_install_file(new_file, branch_name)
elif (old_file != None):
# If just a directory given then append the new file name to it.
if os.path.isdir(old_file):
ref_file = os.path.join(old_file,os.path.basename(new_file))
else:
ref_file = old_file

# Compare against user specified file.
diff_util.compare_PRD_files(new_file, ref_file)