Source

TimeStampMod / TimestampMod.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
# begin Extension Help Text:
'''Automatically store and retrieve file modification times.'''
# end help text
#==============================================================================
# TimestampMod.py - Automatically save and restore the modification times of files
File_Version = '0.2.2'	# Version number definition
# --> !!BETA RELEASE!!! <--
# Copyright 2011-2012 Nathan Durnan <nedmech@gmail.com>
#
# Based on timestamp extension by Friedrich Kastner-Masilko <face@snoopie.at>
# This extension differs from the original in that the original only managed
#	the timestamps of files that had been manually added to the tracking file.
# The default behaviour of this extension instead manages the timestamps of
#	ALL files under version control AUTOMATICALLY.  The purpose of this is to
#	minimize the fears of those who are new to Version Control concepts and
#	make the process of updating between changesets "feel" more like native
#	OS file copy methods (preserving file modification times).
#
# This software may be used and distributed according to the terms
# of the GNU General Public License, incorporated herein by reference.
#------------------------------------------------------------------------------
# Summary: This is an extension written for Mercurial/TortoiseHG that allows
#	the original modification times of files under version control to be
#	recorded and restored during commit, update, revert, etc. operations.
#
# Development information:
#	Mercurial Version:	1.8.3 - 2.1.1 (from TortoiseHg package)
#	Python Version:		2.6.6 (from TortoiseHg package)
#	TortoiseHg Version: 2.0.4 - 2.3.1
#==============================================================================

#==============================================================================
# Import Modules
#------------------------------------------------------------------------------
import sys	#requied for debugging/exception info.
import os	#required for filesystem access methods.
import time	#required for time functions.
import json	#use JSON format for storing timestamp data in file.
import inspect	#required for getting path/name of current code module.
from mercurial import localrepo	#required for creating a pseudo-pre-commit hook.
from mercurial import match as matchmod	#required for "match" object in commit wrapper.
from mercurial import cmdutil	#required for working with "Revert" command methods.
from mercurial import commands	#required for working with "Revert" command methods.
#_ end of imported modules_____________________________________________________

#==============================================================================
# Global Objects
#------------------------------------------------------------------------------
File_TimestampRecords = '.hgtimestamp'
LastPlaceholder = 'TimestampMod_LastRecord'
TimeStamp_dict = dict()
#_ end of global objects ______________________________________________________



#==============================================================================
# uisetup Callback Configuration
#------------------------------------------------------------------------------
# NOTES: Called when the extension is first loaded and receives a ui object.  
#	This is the FIRST callback that is executed when intializing this extension.
#==============================================================================
def uisetup(ui):
	'''Initialize UI-Level Callback'''
	ui.debug('* Loading TimestampMod uisetup\n')
	ui.setconfig("hooks", "post-status.TimestampMod", Hook_Post_Status)
	# Hook_Pre_Commit is depreciated in favor of Wrap_Commit method
	#	(Wrap_Commit works with both native Mercurial and TortoiseHg.)
	'''ui.setconfig("hooks", "pre-commit.TimestampMod", Hook_Pre_Commit)'''
	#NOTE: the post-merge, post-resolve, and post-revert hooks are not picked up 
	#  by TortoiseHg.  When using this extension with TortoiseHg, these hooks 
	#  must be manually added to the "mercurial.ini" configuration file.  
	#  Use the following format:
	#    [hooks]
	#    post-merge.TimestampMod = python:{path-to-TimestampMod.py}:Hook_Post_Merge
	#    post-resolve.TimestampMod = python:{path-to-TimestampMod.py}:Hook_Post_Resolve
	#    post-revert.TimestampMod = python:{path-to-TimestampMod.py}:Hook_Post_Revert
	ui.setconfig("hooks", "post-merge.TimestampMod", Hook_Post_Merge)
	ui.setconfig("hooks", "post-resolve.TimestampMod", Hook_Post_Resolve)
	ui.setconfig("hooks", "post-revert.TimestampMod", Hook_Post_Revert)
#_ end of uisetup _____________________________________________________________


#==============================================================================
# extsetup Callback Configuration
#------------------------------------------------------------------------------
# NOTES: Called after all the extension have been initially loaded.
#	This is the SECOND callback that is executed when intializing this extension.
#	It can be used to access other extensions that this one may depend on.
#==============================================================================
def extsetup(ui):
	'''Initialize Extension-Level Callback'''
	ui.debug('* Loading TimestampMod extsetup\n')
	pass
#_ end of extsetup ____________________________________________________________


#==============================================================================
# reposetup Callback Configuration
#------------------------------------------------------------------------------
# NOTES: Called after the main Mercurial repository initialization.
#	This is the LAST callback that is executed when intializing this extension.
#	It can be used to setup any local state the extension might need.
#==============================================================================
def reposetup(ui, repo):
	'''Initialize Repository-Level Callback'''
	ui.debug('* Loading TimestampMod reposetup\n')
	ui.setconfig("hooks", "update.TimestampMod", Hook_Update)
	if not hasattr(localrepo.localrepository, "timestamp_origcommit"):
		'''This is a "dirty" method of wrapping the commit event so
		pre-commit actions are executed.  Normal pre-commit hooks and
		extension.wrapcommand() methods failed to work with the version
		of TortoiseHg used for development.  Ideally, this will be 
		revised to a cleaner method in the future.'''
		localrepo.localrepository.timestamp_origcommit = localrepo.localrepository.commit
		localrepo.localrepository.commit = Wrap_Commit
#_ end of reposetup ___________________________________________________________


#==============================================================================
# Wrap_Commit Function Definition
#------------------------------------------------------------------------------
# Summary: Intercept the commit event to update the timestamp record file, and
#	make sure the record file gets included in the commit.
# NOTES: This is a "dirty" method of wrapping the commit event so pre-commit 
#	actions are executed.  Normal pre-commit hooks and extensions.wrapcommand()
#	 methods failed to work with the version of TortoiseHg used for development .  
#	Ideally, this will be revised to a cleaner method in the future.
#==============================================================================
def Wrap_Commit(repo, text="", user=None, date=None, match=None, force=False, editor=False, extra={}):
	repo.ui.note('TimestampMod|Wrap_Commit accessed!\n')
	#Check for a merge-commit. 
	#  Don't run timestamp code on merge.
	if (len(repo.parents()) > 1):
		repo.ui.status('TimestampMod|Wrap_Commit aborted - Merge in progress\n')
	else:
		# Make sure the match object is created.
		if not match:
			repo.ui.debug('Empty match: Must create!\n')
			match = matchmod.always(repo.root, '') #create an empty match object
		else:
			pass
		# End of check for non-existent match object.
		myList_Match = list()
		myList_Match = match.files() #don't add timestamp file here, it will be added later.
		timestamp_mod(repo.ui, repo, **dict({'save': True, 'restore': None, 'match': myList_Match}))
		# Make sure record file is part of repository and commit. 
		if not (File_TimestampRecords in repo.dirstate):
			repo.ui.debug('Wrap_Commit: ', File_TimestampRecords, ' not in repo.dirstate  Adding...\n')
			repo[None].add([File_TimestampRecords]) #same method used for adding '.hgtags' file in localrepo.py
		#end of check for record file in repository.
		#Update match fileset for use under TortoiseHg.
		#  TortoiseHg doesn't seem to catch the updated file
		#  unless it is manually added to the match fileset.
		if (File_TimestampRecords in match.files()):
			# Don't need to do anything if record file already in commit.
			repo.ui.debug('Wrap_Commit: ', File_TimestampRecords, ' already in match\n')
			pass
		else:
			# Add the record file to the match object.
			match.files().append(File_TimestampRecords)
		# end of check for record file.
		repo.ui.debug('Match Files: ', str(match.files()), '\n')
	#end of check for merge-commit.
	repo.ui.note('TimestampMod|Wrap_Commit finished!\n')
	return repo.timestamp_origcommit(text, user, date, match, force, editor, extra)
#_ end of Wrap_Commit _________________________________________________________


#==============================================================================
# Hook Function Definitions
#------------------------------------------------------------------------------
# Summary: These functions are intended to be triggered by the hooks defined
#	either by Mercurial or in the configuration files.
# NOTES: The pre-** hooks are the only ones that does not function properly
#	under the TortoiseHg GUI.  All the hooks work from command-line.
#==============================================================================
# Hook_Pre_Commit is depreciated in favor of Wrap_Commit method
#	(Wrap_Commit works with both native Mercurial and TortoiseHg.)
'''def Hook_Pre_Commit(repo, **kwargs):
	repo.ui.note("Pre-Commit Hook accessed!\n")
	repo.ui.debug('kwargs = ',kwargs, "\n")
	timestamp_mod(repo.ui, repo, **dict({'save': True, 'restore': None}))
	kwargs['pats'].append(File_TimestampRecords)
''' # Hook_Pre_Commit is depreciated
def Hook_Post_Status(repo, **kwargs):
	repo.ui.note("TimestampMod|Post-Status Hook accessed!\n")
	timestamp_mod(repo.ui, repo, **dict({'save': None, 'restore': None}))

def Hook_Update(repo, **kwargs):
	repo.ui.note("TimestampMod|Hook_Update accessed!\n")
	if (len(repo.parents()) > 1):
		repo.ui.status('TimestampMod|Hook_Update aborted - Merge in progress\n')
	else:
		timestamp_mod(repo.ui, repo, **dict({'save': None, 'restore': True}))
	#end of check for merging.

def Hook_Post_Merge(repo, **kwargs):
	repo.ui.note("TimestampMod|Post-Merge Hook accessed!\n")
	#repo.ui.debug("Post-Merge:kwargs = \n", str(kwargs), '\n')
	myPreview = False #starting value
	if ('opts' in kwargs):
		if ('preview' in kwargs['opts']):
			myPreview = kwargs['opts']['preview']
		#end of check for 'preview' option.
	#end of check for 'opts' keyword.
	if not myPreview:
		#only update timestamps if not just a preview.
		timestamp_mod(repo.ui, repo, **dict({'save': None, 'restore': True}))
	#check for preview option.

def Hook_Post_Resolve(repo, **kwargs):
	repo.ui.note("TimestampMod|Post-Resolve Hook accessed!\n")
	#repo.ui.debug("Post-Resolve:kwargs = \n", str(kwargs), '\n')
	myResolveAll = False #starting value
	if ('opts' in kwargs):
		if ('all' in kwargs['opts']):
			myResolveAll = kwargs['opts']['all']
		#end of check for 'preview' option.
	#end of check for 'opts' keyword.
	if (myResolveAll or (File_TimestampRecords in str(kwargs['pats']))):
		#Only re-apply timestamps if the timestamp file is the one being resolved.
		repo.ui.status("Resolved timestamp file - Reapplying timestamps!\n")
		timestamp_mod(repo.ui, repo, **dict({'save': None, 'restore': True}))
	#end of check for timestamp file resolve.

def Hook_Post_Revert(repo, **kwargs):
	'''NOTE: TortoiseHg Incompatibility Issue!
	The Post-Revert hook does not work correctly for most of the Revert 
	commands from TortoiseHg (version 2.2.2 at the time of implementaion).
	The hook simply does not fire from the methods used within TortoiseHg.
	This issue has been brought to the attention of the TortoiseHg team and
	is on their list of items that need fixed:
	https://bitbucket.org/tortoisehg/thg/issue/1347/add-support-for-pre-and-post-hooks
	'''
	repo.ui.note("TimestampMod|Post-Revert Hook accessed!\n")
	repo.ui.debug("-----\nPost-Revert:kwargs = \n", str(kwargs), "\n-----\n")
	bDryRun = False #starting value
	bAll = False #starting value
	listExclude = list()
	if ('opts' in kwargs):
		bDryRun = kwargs['opts'].get('dry_run', False)
		bAll = kwargs['opts'].get('all', False)
		listExclude = kwargs['opts'].get('exclude', list())
		if kwargs['opts'].get('date'):
			#Don't bother to check for rev-spec. 
			# Original command would've failed and not 
			# gotten here if both date and rev were spec'd.
			kwargs['opts']['rev'] = cmdutil.finddate(repo.ui, repo, kwargs['opts']['date'])
		#end of check for date specified.
	#end of check for 'opts' keyword.
	#Create a temporary copy of the timestamp file from the source revision.
	commands.cat(repo.ui, repo, 
		File_TimestampRecords, File_TimestampRecords, 
		**dict({'rev':kwargs['opts']['rev'], 'output':'%s.revert'}))
	#Create dictionary entries for items that were reverted.
	if bAll:
		_get_RepoFileList(repo, list(), TimeStamp_dict)
		for myFile in listExclude:
			if myFile in TimeStamp_dict:
				del TimeStamp_dict[myFile]
			#end of check for file in dictionary.
		#loop through exclude filter
	else: #only specific files have been reverted.
		TimeStamp_dict.clear()
		for myFile in kwargs['pats']:
			myFileName = str(myFile).strip()
			TimeStamp_dict[myFileName] = -1
		#end of loop through pattern list
	#end of check for 'all' flag
	# Retrieve existing timestamps from the record file.
	myErr = _read_TimestampJSONRecords(repo, (File_TimestampRecords + '.revert'), TimeStamp_dict)
	if (not bDryRun):
		if not myErr:
			_restore_Timestamps(repo, TimeStamp_dict)
		#end of check for file-read error.
	#end of check for dry-run operation.
	#Delete temporary timestamp file
	try:
		os.unlink(repo.wjoin(File_TimestampRecords + '.revert'))
	except:
		repo.ui.status("Post-Revert: error deleting timestamp file!\n")
	#end of deleting temporary timestamp file.
#_ end of Hook Functions ______________________________________________________


#==============================================================================
# timestamp_mod 
#------------------------------------------------------------------------------
# Summary: save or restore file modification times.
#
#==============================================================================
def timestamp_mod(ui, repo, **kwargs):
	'''Save or restore file modification times.'''
	ui.note("Executing timestamp_mod function\n")
	# Retrieve Repository file list contents.
	myChangedList = list()
	myDroppedList = list()
	myMatchList = list()
	if ('match' in kwargs):
		ui.debug("-----\nmatch: ", str(kwargs['match']), "\n")
		myMatchList = kwargs['match']
	else:
		ui.debug("-----\nmatch argument not specified\n")
	# end of check for match argument'''
	# Build initial file lists from the repository contents.
	myChangedList, myDroppedList = _get_RepoFileList(repo, myMatchList, TimeStamp_dict)
	# Retrieve existing timestamps from the record file.
	myErr = _read_TimestampJSONRecords(repo, File_TimestampRecords, TimeStamp_dict)
	
	# Check for command optional argument
	if kwargs['save']:
		_save_TimestampsJSON(repo, File_TimestampRecords, myChangedList, myDroppedList, TimeStamp_dict)
	elif not myErr:	# Only evaluate Restore or Display if file was read.
		if kwargs['restore']:
			_restore_Timestamps(repo, TimeStamp_dict)
		else:
			_display_Timestamps(repo, TimeStamp_dict)
		# end of check options (Restore/Display)
	else:
		repo.ui.debug('Timestamp_Mod can not continue without ', File_TimestampRecords, ' file! \n')
	# end of check options
#_ end of timestamp_mod _______________________________________________________


#==============================================================================
# Command Table Definition
#------------------------------------------------------------------------------
# (NOTE: Keep this after command definitions.  cmdtable contents 
#		 must be defined after the commands/functions referenced!)
#==============================================================================
cmdtable = {
	"timestamp_mod":
		(timestamp_mod, 
			[('s', 'save', None, ('save modification times')),
			('r', 'restore', None, ('restore modification times'))
			], 
			('hg timestamp_mod [-s | -r] \n' +
				'\n' + inspect.getfile(inspect.currentframe()) +
				'\n  ' + '(Version ' + File_Version + ')')
		) #end of timestamp_mod
}
#_ end of cmdtable ____________________________________________________________



#==============================================================================
# _get_fileModTime() Function Definition
#------------------------------------------------------------------------------
# Summary: Return a UTC timestamp value for the specified file's modified time.
#==============================================================================
def _get_fileModTime(repo, IN_FileName):
	'''Retrieve the Modification Timestamp for the specified file.'''
	repo.ui.debug('get_mtime: ')
	myFilePath = repo.wjoin(IN_FileName)
	try:
		myModTime = float(os.stat(myFilePath).st_mtime)
		repo.ui.debug(time.strftime("%Y.%m.%d %H:%M:%S", time.localtime(myModTime)), " \t", IN_FileName, "\n")
		return myModTime
	except:
		repo.ui.warn('*** TimestampMod: Get File Stat failed for ', IN_FileName, '!\n')
		repo.ui.debug('*** Exception: ', str(sys.exc_info()), '  ***\n')
		return -1
	# end of file stat access.
#_ end of _get_fileModTime ____________________________________________________



#==============================================================================
# _set_fileModTime() Function Definition
#------------------------------------------------------------------------------
# Summary: Set the UTC timestamp value for the specified file's modified time.
#==============================================================================
def _set_fileModTime(repo, IN_FileName, IN_ModTime):
	'''Assign the Modification Timestamp for the specified file.'''
	repo.ui.debug('set_mtime: ')
	myFilePath = repo.wjoin(IN_FileName)
	try:
		myFileStat = os.stat(myFilePath)
		os.utime(myFilePath, (myFileStat.st_atime, type(myFileStat.st_mtime)(IN_ModTime)))
		repo.ui.debug(time.strftime("%Y.%m.%d %H:%M:%S", time.localtime(IN_ModTime)), " \t", IN_FileName, "\n")
	except:
		repo.ui.warn('*** TimestampMod: Set File Stat failed for ', IN_FileName, '! ***\n')
		repo.ui.debug('*** Exception: ', str(sys.exc_info()), '  ***\n')
	# end of file stat access.
#_ end of _set_fileModTime ____________________________________________________



#==============================================================================
# _get_RepoFileList Function Definition
#------------------------------------------------------------------------------
# Summary: Build lists of the files in the Working Directory from the Repository
#	Status entries.  Add active files (clean/added/modified) to the global 
#	dictionary collection, andreturn lists containing changed files (added/
#	modified) and dropped files(removed/deleted).  
# NOTE: This function will CLEAR the contents of the global dictionary collection
#	and rebuild it from scratch.
#==============================================================================
def _get_RepoFileList(repo, IN_ListMatch, OUT_TimeStamp_dict):
	'''Build lists of files from the repository status contents.'''
	repo.ui.debug('______\nGenerating file list from repo...\n------\n')
	# Establish category lists from repository status.
	modified, added, removed, deleted, unknown, ignored, clean = repo.status(ignored=True, clean=True, unknown=True)
	myChanged = IN_ListMatch + modified + added
	myDropped = removed + deleted
	myFiles = myChanged + clean
	# Rebuild global dictionary collection
	OUT_TimeStamp_dict.clear() # Be sure to start with a clean collection.
	for myFile in myFiles:
		if myFile not in myDropped:
			#Only add non-dropped files to the list, even if they are part of the match list.
			myFileName = str(myFile).strip()
			OUT_TimeStamp_dict[myFileName] = -1	# initialize dictionary entry
			repo.ui.debug('Tracking:  ', myFileName, '\n')
		# end of check for droppped files.
	# end of loop through repo files.
	myReturnList = myChanged, myDropped
	return myReturnList
#_ end of _get_RepoFileList ___________________________________________________



#==============================================================================
# _read_TimestampRecords Function Definition
#------------------------------------------------------------------------------
# Summary: Read in the data from the Timestamp Record File and assign the 
#	timestamps to their corresponding entries in the global file dictionary
#	collection object.
# NOTES:
# * This method is to be kept in tact in order to be able to deal with the
#   original CSV timestamp file format that may have been recorded and commited
#   using previous versions of this extension.  DO NOT LOSE this functionality!
#==============================================================================
def _read_TimestampRecords(repo, IN_TimestampFileName, INOUT_TimeStamp_dict):
	'''Read data from Timestamp Record File.'''
	myTimeStampRecordsFile = ''
	try:
		myTimeStampRecordsFile = open(repo.wjoin(IN_TimestampFileName), 'r')
		repo.ui.debug('______\nRetrieving 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 ', 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 _read_TimestampRecords ______________________________________________



#==============================================================================
# _read_TimestampJSONRecords Function Definition
#------------------------------------------------------------------------------
# Summary: Read in the data from the Timestamp JSON Record File and assign the 
#	timestamps to their corresponding entries in the global file dictionary
#	collection object.
# NOTES:
# * This method will fall back to use the previous CSV file read method if it
#   can not read the file as JSON data.
#==============================================================================
def _read_TimestampJSONRecords(repo, IN_TimestampFileName, INOUT_TimeStamp_dict):
	'''Read data from Timestamp JSON Record File.'''
	myTimeStampJSONFile = ''
	myErr = False #initialize as boolean
	try:
		myTimeStampJSONFile = open(repo.wjoin(IN_TimestampFileName), 'r')
		repo.ui.debug('______\nRetrieving timestamps from JSON record file:\n------\n')
		try:
			myData = json.load(myTimeStampJSONFile)
			# 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():
					#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 entry in dictionary.
								f_fileModTime = -1 # use explicitly invalid value if none found.
								myWarn = True
								repo.ui.warn('WARNING: Missing timestamp definition for ', 
									str(s_fileName), ': ', str(obj_fileData), '\n')
						else: # Error - not a recognized data type.
							f_fileModTime = -1 # use explicitly invalid value if none found.
							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 (myWarnCount >= len(myData['FileData'])):
					repo.ui.debug('ERROR: Could not read any JSON 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 data
			# 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
			myTimeStampJSONFile.close()
			if myErr: #error return 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)
		# end of reading record file.
		return myErr
	except: #report errors
		repo.ui.warn('*** Error accessing ', 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 _read_TimestampJSONRecords ______________________________________________


#==============================================================================
# _save_TimestampsJSON Function Definition
#------------------------------------------------------------------------------
# Summary: Save File Modified Timestamp data for files in the global dictionary
#	collection to a JSON-formatted record file in the repository root directory.  
#	New values for timestamps will be retrieved for files that have changed or 
#	are missing timestamp records in the first place.
# NOTES:
# * Many thanks to BitBucket user lboehler (https://bitbucket.org/lboehler) for
#	suggesting using the SORTED list to build the timestamp file.  This really 
#	should have been obvious, but I completely overlooked it!  
# * The JSON file will be built manually instead of using the built-in JSON 
#	methods.  This is because the dict object in Python can no be sorted well
#	enough to generate a repeatable JSON file with the data in the same order
#	all the time.  Maybe when Mercurial starts using Python 2.7+, the newer 
#	OrderedDict object type may be able to be used here.
#==============================================================================
def _save_TimestampsJSON(repo, IN_TimestampFileName, IN_ChangedList, IN_DroppedList, INOUT_TimeStamp_dict):
	'''Save File Modification Timestamps to JSON record file.'''
	repo.ui.note('______\nSaving timestamps to JSON file...\n------\n')
	# Remove the record file from the list.
	#	It causes confusion and difficulty during merge.
	if IN_TimestampFileName in INOUT_TimeStamp_dict:
		del INOUT_TimeStamp_dict[IN_TimestampFileName]
	# end of check for record file.
	myTimeStampJSONFile = open(repo.wjoin(IN_TimestampFileName), 'w')
	# Record version data for the file.
	myTimeStampJSONFile.write('{\n"Version": "' + File_Version + '",\n"FileData":{\n')
	# Make sure to use a sorted dictionary for the file data:
	for s_fileName in sorted(INOUT_TimeStamp_dict.keys(), key=str.lower):
		f_fileModTime = INOUT_TimeStamp_dict[s_fileName]
		if (s_fileName in IN_ChangedList) or (f_fileModTime<=0):
			f_fileModTime = INOUT_TimeStamp_dict[s_fileName] = _get_fileModTime(repo, s_fileName)
		# end of update timestamps for changed items or missing timestamps.
		if (s_fileName in IN_DroppedList) or (f_fileModTime<=0):
			repo.ui.debug('...removing record of dropped file, or file with missing timestamp (', s_fileName, ')\n')
			del INOUT_TimeStamp_dict[s_fileName]
		else:	#timestamp is valid
			myTimeStampJSONFile.write('"%s": {"timestamp": %s},\n' % (s_fileName, f_fileModTime))
		# end of check for non-existing files or timestamps.
	# end of loop through dictionary items.
	# Add one last record to wrap up the JSON formatting.
	myTimeStampJSONFile.write('"' + LastPlaceholder + '": {"timestamp": 0}\n}\n}')
	# Make sure to close the file!
	myTimeStampJSONFile.close()
#_ end of _save_TimestampsJSON ____________________________________________________


#==============================================================================
# _restore_Timestamps Function Definition
#------------------------------------------------------------------------------
# Summary: Restore the File Modification Timestamp property for files in the
#	global dictionary collection.  
# NOTE: This presumes that the dictionary has been initialized and the original
#	timestamp data has already been read into the dictionary.
#==============================================================================
def _restore_Timestamps(repo, IN_TimeStamp_dict):
	'''Restore File Modification Timestamps from record file.'''
	repo.ui.note('______\nRestoring timestamps...\n------\n')
	for s_fileName, f_fileModTime in IN_TimeStamp_dict.items():
		# Check for valid timestamp.
		if (f_fileModTime>0):
			# Valid timestamp detected!
			# Restore file timestamp.
			_set_fileModTime(repo, s_fileName, f_fileModTime)
		else:
			# No valid timestamp recorded, skip this file.
			repo.ui.debug(s_fileName, ' - skipped - no timestamp recorded\n')
		# end of check for valid timestamp.
	# end of loop through dictionary items.
#_ end of _restore_Timestamps _________________________________________________



#==============================================================================
# _display_Timestamps Function Definition
#------------------------------------------------------------------------------
# Summary: Default action.  Display the File Modification Timestamp property for
#	files in the global dictionary collection.  
# NOTE: This presumes that the dictionary has been initialized and the original
#	timestamp data has already been read into the dictionary.
#==============================================================================
def _display_Timestamps(repo, myTimeStamp_dict):
	'''Display File Timestamps currently recorded.'''
	repo.ui.note('______\nDisplaying timestamps...\n------\n')
	for s_fileName, f_fileModTime in myTimeStamp_dict.items():
		# Check for valid timestamp
		if (f_fileModTime>0):
			# Valid timestamp detected!
			# Display timestamp using local time adjustment.
			repo.ui.status(time.strftime("%Y.%m.%d %H:%M:%S", time.localtime(f_fileModTime)), " \t", s_fileName, "\n")
		else:
			# No valid timestamp recorded, skip this file.
			repo.ui.debug(s_fileName, ' - skipped - no timestamp recorded\n')
		# end of check for valid timestamp.
	# end of loop through dictionary items.
#_ end of _display_Timestamps _________________________________________________