Commits

Nathan Durnan committed 3306e9e

_read_TimestampJSONRecords: simplify try-except blocks to reduce nesting.

  • Participants
  • Parent commits 631b4ea
  • Branches development

Comments (0)

Files changed (2)

 "Tests/BBI38_EmptyUpdate_Test.bat": {"timestamp": 1341604677.09},
 "Tests/TimestampMod_BBI37_Test.bat": {"timestamp": 1341343207.95},
 "TimeStampMod.png": {"timestamp": 1305052883.0},
-"TimestampMod.py": {"timestamp": 1342028367.91},
+"TimestampMod.py": {"timestamp": 1342029612.95},
 "TimeStampMod.xmind": {"timestamp": 1306451621.66},
 "TimestampMod_LastRecord": {"timestamp": 0}
 }
 #_ end of _get_RepoFileList __________________________________________________
 
 
-
 #=============================================================================
 # _read_TimestampRecords Function Definition
 #-----------------------------------------------------------------------------
 	myTimeStampRecordsFile = ''
 	try:
 		myTimeStampRecordsFile = open(repo.wjoin(IN_TimestampFileName), 'r')
-		repo.ui.debug(
-			'______\n', 
-			'Retrieving timestamps from record file:\n', 
-			'------\n'
-			)
-		for myLine in myTimeStampRecordsFile.readlines():
-			# Read the data from the line. 
-			# (CSV format: [FileName],[ModificationTime])
-			try:
-				myFileName, myModTime = myLine.strip().split(',')
-				#Only import data for entries already in local dictionary.
-				if myFileName in INOUT_TimeStamp_dict:
-					#Make sure incoming data is properly formatted.
-					INOUT_TimeStamp_dict[str(myFileName)] = float(myModTime)
-					repo.ui.debug(
-						'UTC: ', myModTime, 
-						'\t: ', myFileName, '\n'
-						)
-				# end of check file exists in dictionary.
-			except:
-				repo.ui.debug('Invalid data on line: ', myLine)
-			# end of read data from line.
-		# end of readlines from record file.
-		myTimeStampRecordsFile.close()
-		return False 	# no return flag as successful.
 	except:
 		repo.ui.warn(
 			'*** Error accessing ', 
 			)
 		repo.ui.debug('*** Exception: ', str(sys.exc_info()), '  ***\n')
 		return True	# set return flag on error.
-	# end of accessing record file.
+	# end of opening record file.
+	repo.ui.debug(
+		'______\n', 
+		'Retrieving timestamps from record file:\n', 
+		'------\n'
+		)
+	for myLine in myTimeStampRecordsFile.readlines():
+		# Read the data from the line. 
+		# (CSV format: [FileName],[ModificationTime])
+		try:
+			myFileName, myModTime = myLine.strip().split(',')
+			#Only import data for entries already in local dictionary.
+			if myFileName in INOUT_TimeStamp_dict:
+				#Make sure incoming data is properly formatted.
+				INOUT_TimeStamp_dict[str(myFileName)] = float(myModTime)
+				repo.ui.debug(
+					'UTC: ', myModTime, 
+					'\t: ', myFileName, '\n'
+					)
+			# end of check file exists in dictionary.
+		except:
+			repo.ui.debug('Invalid data on line: ', myLine)
+		# end of read data from line.
+	# end of readlines from record file.
+	myTimeStampRecordsFile.close()
+	return False 	# no return flag as successful.
 #_ end of _read_TimestampRecords _____________________________________________
 
 
-
 #=============================================================================
 # _read_TimestampJSONRecords Function Definition
 #-----------------------------------------------------------------------------
 		# If restoring, nothing more can be done without the file data.
 		return True
 	# end of check for existing file
+	# Open timestamp record file.
 	try:
 		myTimeStampJSONFile = open(repo.wjoin(IN_TimestampFileName), 'rb')
-		repo.ui.debug(
-			'______\n', 
-			'Retrieving timestamps from JSON record file:\n', 
-			'------\n'
-			)
-		try:
-			# Read in file content into local string.
-			s_Content = myTimeStampJSONFile.read()
-			myTimeStampJSONFile.close()
-			openedEncoding = None
-			encodingList = list((
-				'utf_8', 
-				sys.getfilesystemencoding(), 
-				'ascii'
-				))
-			for testEncoding in encodingList:
-				repo.ui.debug('testEncoding = ', testEncoding, '\n')
-				try:
-					myData =json.loads(unicode(s_Content, testEncoding))
-				except:
-					#move on to check next encoding.
-					continue
-				else:
-					openedEncoding = testEncoding
-					#valid encoding found, no need to try others.
-					break
-				# end of load attempt.
-			# end of loop through encoding list.
-			if not openedEncoding: 
-				#openedEncoding not detected - try older version.
-				# Try opening as a pre-v0.2.0 CSV file insted:
-				repo.ui.warn(
-					'Opening ', 
-						IN_TimestampFileName, 
-						' as CSV file\n'
-						)
-				myErr = _read_TimestampRecords(
-					repo, 
-					IN_TimestampFileName, 
-					INOUT_TimeStamp_dict
-					)
-				return myErr
-			# Check for version and object data:
-			if ('FileData' in myData):
-				if (LastPlaceholder in myData['FileData']):
-					#Don't import placeholder into local dictionary.
-					del myData['FileData'][LastPlaceholder]
-				myWarnCount = 0 #initialize counter.
-				for s_fileName, obj_fileData in myData['FileData'].items():
-					# Convert s_fileName encode (unicode) 
-					# to sys.getfilesystemencoding()
-					s_fileName = s_fileName.encode(sys.getfilesystemencoding())
-					#Only import data for entries already in local dictionary.
-					if s_fileName in INOUT_TimeStamp_dict:
-						myWarn = False #initialize warning flag for each item.
-						#Make sure incoming data is properly formatted.
-						if isinstance(obj_fileData, float):
-							# Keep this section for compatibility 
-							# with v0.2.1 timestamp file.
-							f_fileModTime = float(obj_fileData)
-							#myErr = False 	# no return flag as successful.
-						elif isinstance(obj_fileData, dict):
-							# As of v0.2.2, file data is stored within
-							# a dict object for future extensibility.
-							if ('timestamp' in obj_fileData):
-								f_fileModTime = float(obj_fileData['timestamp'])
-								#myErr = False 	# no return flag as successful.
-							else: # Error - missing timestamp in dictionary.
-								# use explicitly invalid value if none found.
-								f_fileModTime = -1 
-								myWarn = True
-								repo.ui.warn(
-									'WARNING: ', 
-									'Missing timestamp definition for ', 
-									str(s_fileName), ': ', 
-									str(obj_fileData), '\n'
-									)
-						else: # Error - not a recognized data type.
-							# use explicitly invalid value if none found.
-							f_fileModTime = -1 
-							myWarn = True
-							repo.ui.warn(
-								'WARNING: Undefined data for ', 
-								str(s_fileName), ': ', 
-								str(type(obj_fileData)), 
-								' = [', str(obj_fileData), ']\n'
-								)
-						# end of check for data type
-						if not myWarn:
-							INOUT_TimeStamp_dict[str(s_fileName)] = \
-								f_fileModTime
-							repo.ui.debug(
-								'UTC: ', str(f_fileModTime), 
-								'\t: ', str(s_fileName), '\n'
-								)
-						else:
-							myWarnCount += 1 # increment count of problem reads.
-						# end of check for per-item warning.
-					# end of check file exists in dictionary.
-				# end of loop through items.
-				if (len(myData['FileData']) <= 0):
-					# This is not an error condition.
-					# Likely just an empty working directory.
-					repo.ui.debug(
-						IN_TimestampFileName, 
-						' contains no file records', 
-						' - Working Directory is empty?\n'
-						)
-				elif (myWarnCount >= len(myData['FileData'])):
-					repo.ui.debug(
-						'ERROR: Could not read file data from ', 
-						IN_TimestampFileName, '\n'
-						)
-					myErr = True	# Error - could not find JSON data
-				# end of check warning count.
-			else: # JSON file data is not present
-				repo.ui.debug(
-					IN_TimestampFileName, 
-					' does not have JSON file data.\n'
-					)
-				myErr = True	# Error - could not find JSON FileData records
-			# end of check for file data.
-		except: # report errors
-			repo.ui.debug('Error loading JSON file\n')
-			repo.ui.debug(
-				'*** Exception: ', 
-				str(sys.exc_info()), '  ***\n'
-				)
-			myErr = True	# Error - problem loading JSON file.
-		finally: #cleanup clause
-			pass
-		# end of reading record file.
-		return myErr
 	except: #report errors
 		repo.ui.warn(
-			'*** Error accessing ', 
+			'*** Error opening ', 
 			IN_TimestampFileName, 
 			' file! ***\n'
 			)
 		repo.ui.debug('*** Exception: ', str(sys.exc_info()), '  ***\n')
 		return True	# set return flag on error.
-	# end of accessing record file.
+	# end of opening record file.
+	repo.ui.debug(
+		'______\n', 
+		'Retrieving timestamps from JSON record file:\n', 
+		'------\n'
+		)
+	# Read in file content into local string.
+	s_Content = myTimeStampJSONFile.read()
+	myTimeStampJSONFile.close()
+	# Attempt to load JSON data with correct encoding.
+	openedEncoding = None
+	encodingList = list(('utf_8', sys.getfilesystemencoding(), 'ascii'))
+	for testEncoding in encodingList:
+		repo.ui.debug('testEncoding = ', testEncoding, '\n')
+		try:
+			myData = json.loads(unicode(s_Content, testEncoding))
+		except:
+			repo.ui.debug( \
+				'*** ', testEncoding, ' Exception: \n', \
+				str(sys.exc_info()), '\n***\n')
+			#move on to check next encoding.
+			continue
+		else:
+			openedEncoding = testEncoding
+			#valid encoding found, no need to try others.
+			break
+		# end of load attempt.
+	# end of loop through encoding list.
+	if not openedEncoding: 
+		# No encoding could be determined - Treat as failure.
+		# Allow error checking to try opening as CSV file.
+		repo.ui.debug('Failed to open as JSON file with available Encoding.\n')
+		# Try opening as a pre-v0.2.0 CSV file insted:
+		repo.ui.warn(
+			'Attempting to open ', 
+				IN_TimestampFileName, 
+				' as CSV file\n'
+				)
+		return _read_TimestampRecords(
+			repo, 
+			IN_TimestampFileName, 
+			INOUT_TimeStamp_dict
+			)
+	# Check for version and object data:
+	if ('FileData' in myData):
+		if (LastPlaceholder in myData['FileData']):
+			#Don't import placeholder into local dictionary.
+			del myData['FileData'][LastPlaceholder]
+		myWarnCount = 0 #initialize counter.
+		for s_fileName, obj_fileData in myData['FileData'].items():
+			# Convert s_fileName encode (unicode) 
+			# to sys.getfilesystemencoding()
+			s_fileName = s_fileName.encode(sys.getfilesystemencoding())
+			#Only import data for entries already in local dictionary.
+			if s_fileName in INOUT_TimeStamp_dict:
+				myWarn = False #initialize warning flag for each item.
+				#Make sure incoming data is properly formatted.
+				if isinstance(obj_fileData, float):
+					# Keep this section for compatibility 
+					# with v0.2.1 timestamp file.
+					f_fileModTime = float(obj_fileData)
+					#myErr = False 	# no return flag as successful.
+				elif isinstance(obj_fileData, dict):
+					# As of v0.2.2, file data is stored within
+					# a dict object for future extensibility.
+					if ('timestamp' in obj_fileData):
+						f_fileModTime = float(obj_fileData['timestamp'])
+						#myErr = False 	# no return flag as successful.
+					else: # Error - missing timestamp in dictionary.
+						# use explicitly invalid value if none found.
+						f_fileModTime = -1 
+						myWarn = True
+						repo.ui.warn(
+							'WARNING: ', 
+							'Missing timestamp definition for ', 
+							str(s_fileName), ': ', 
+							str(obj_fileData), '\n'
+							)
+				else: # Error - not a recognized data type.
+					# use explicitly invalid value if none found.
+					f_fileModTime = -1 
+					myWarn = True
+					repo.ui.warn(
+						'WARNING: Undefined data for ', 
+						str(s_fileName), ': ', 
+						str(type(obj_fileData)), 
+						' = [', str(obj_fileData), ']\n'
+						)
+				# end of check for data type
+				if not myWarn:
+					INOUT_TimeStamp_dict[str(s_fileName)] = \
+						f_fileModTime
+					repo.ui.debug(
+						'UTC: ', str(f_fileModTime), 
+						'\t: ', str(s_fileName), '\n'
+						)
+				else:
+					myWarnCount += 1 # increment count of problem reads.
+				# end of check for per-item warning.
+			# end of check file exists in dictionary.
+		# end of loop through items.
+		if (len(myData['FileData']) <= 0):
+			# This is not an error condition.
+			# Likely just an empty working directory.
+			repo.ui.debug(
+				IN_TimestampFileName, 
+				' contains no file records', 
+				' - Working Directory is empty?\n'
+				)
+		elif (myWarnCount >= len(myData['FileData'])):
+			repo.ui.debug(
+				'ERROR: Could not read file data from ', 
+				IN_TimestampFileName, '\n'
+				)
+			myErr = True	# Error - could not find JSON data
+		# end of check warning count.
+	else: # JSON file data is not present
+		repo.ui.debug(
+			IN_TimestampFileName, 
+			' does not have JSON file data.\n'
+			)
+		myErr = True	# Error - could not find JSON FileData records
+	# end of check for file data.
+	if myErr: #error return detected
+		repo.ui.warn('Failed to read JSON file.\n')
+	# end of final error check
+	return myErr
 #_ end of _read_TimestampJSONRecords _________________________________________
 
 
 #_ end of _restore_Timestamps ________________________________________________
 
 
-
 #=============================================================================
 # _display_Timestamps Function Definition
 #-----------------------------------------------------------------------------