#!python
# gir2rst - Create Sphinx documentation from GIR files
# Copyright (C) 2012 Matthias Vogelgesang
#
# 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 sys
import re
import argparse
import gir2rst
import gir2rst.formatter


def log_error(s):
    print >> sys.stderr, s

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Generate Sphinx \
            documentation from GObject Introspection GIR files.')

    parser.add_argument('--version', action='version', version='gir2rst %s' %
            gir2rst.__version__)
    parser.add_argument('-t', type=str, metavar='TITLE',
            help="override the title [available variables: #version \
                    (escape with '\\')]")
    parser.add_argument('-o', type=str, metavar='FILE',
            help='write to FILE or stdout if omitted')
    parser.add_argument('input', nargs='*', help='.gir input files')

    if len(sys.argv) == 1:
        parser.print_usage()
        sys.exit()

    args = parser.parse_args()

    title = None
    if args.t:
        title = re.sub(r'([^\\])#version', r'\1%(version)s', args.t)

    if args.o and len(args.input) > 1:
        log_error("Warning: %s will be overwritten for each input" % (args.o))

    stream = open(args.o, 'w') if args.o else sys.stdout

    try:
        for filename in args.input:
            formatter = gir2rst.formatter.RstCFormatter(filename, stream,
                    title)
            formatter.write_rst()
    except IOError:
        parser.print_usage()
