#!/usr/bin/python3

#	anti-cppcheck : utility for processing reports with static analysis
#	Copyright (C) 2019-2024 Alexey Appolonov
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

import argparse
import anticppcheck.machinery as machinery
from anticppcheck.common import argparser
from anticppcheck.common import PrintExamples

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Parsing the arguments

argparser.add_argument(
	'-s', '--selection', metavar='MESSAGE_ID', type=int, nargs='+',
	help='IDs of interested types of messages')
args = argparser.parse_args()

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Usage examples

EXAMPLES = [(
	'Find messages of type 10 and 15 (numbered that way in a given comments '
	'file) produced by cppcheck for herodotos and stored in a given dir and '
	'it\'s subdirs',
	'--type herodotos --analyzer cppcheck --path DIR_WITH_REPORTS '
	'--comments COMMENTS_FILE_NAME --selection 10 15'
	)]

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

if __name__ == '__main__':

	# Printing the usage examples
	if args.examples:
		PrintExamples(__file__, EXAMPLES)
		exit(0)

	# Checking required arguments
	if any(not arg for arg in \
			(args.selection, args.type, args.analyzer, args.path)):
		argparser.error('--type, --analyzer, --path and --selection '
			'are required')

	# Creating the machine that instantly parses a given report file(s)
	#	and a given comments file and holds the data for later requests
	try:
		machine = machinery.Machine(args.type,
			args.analyzer,
			args.path,
			args.comments,
			args.selection)
	except Exception as e:
		print('Error: ' + str(e))
		exit(1)

	# Selecting all the interested messages and then printing them one by one
	for report_path, report in machine.reports.items():
		for entry in report:
			src_path = ''
			for field in ('path', 'path1', 'path2'):
				src_path = entry.get(field, '')
				if src_path:
					break
			print(report_path + ': '
				'[' + src_path + ']'
				'[' + entry.get('message', '') + ']')

	exit(0)
