#!/usr/bin/python3

# update-code-analysis-tags -- update Lintian data about code-analysis tags
#
# Copyright © 2011, 2012, 2013 Jakub Wilk
#
# This program is free software.  It is distributed under the terms of the GNU
# General Public License as published by the Free Software Foundation; either
# version 2 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, you can find it on the World Wide Web at
# http://www.gnu.org/copyleft/gpl.html, or write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

import ast
import os

import deb822

import misc

def extract_tags(node):
    for child in ast.iter_child_nodes(node):
        for t in extract_tags(child):
            yield t
    if (
        isinstance(node, ast.Call) and
        isinstance(node.func, ast.Name) and
        node.func.id == 'tag' and
        node.args and
        isinstance(node.args[0], ast.Str)
    ):
        yield node.args[0].s

def main():
    os.chdir(misc.root)
    filename = 'helpers/python/code-analysis'
    with open(filename, 'r') as file:
        contents = file.read()
        node = ast.parse(contents, filename=filename)
        tags = set(extract_tags(node))
    old_tags = {}
    first = True
    with open('checks/python/code-analysis.desc', 'r', encoding='UTF-8') as file:
        for para in deb822.Deb822.iter_paragraphs(file):
            if first:
                first_para = para
            else:
                old_tags[para['tag']] = para
            first = False
    first = True
    with open('checks/python/code-analysis.desc', 'w', encoding='UTF-8') as file:
        file.write(str(first_para))
        for tag in sorted(tags):
            try:
                para = old_tags[tag]
            except LookupError:
                para = deb822.Deb822()
                para['Tag'] = tag
                para['Severity'] = 'wishlist'
                para['Certainty'] = 'wild-guess'
                para['Experimental'] = 'yes'
            file.write('\n')
            file.write(str(para))
            first = False

if __name__ == '__main__':
    main()

# Local Variables:
# indent-tabs-mode: nil
# End:
# vim: syntax=python sw=4 sts=4 sr et
