#!/usr/bin/python

"""$Id: demo.py 988 2008-03-12 18:22:48Z sa3ruby $"""

__author__ = "Sam Ruby <http://intertwingly.net/> and Mark Pilgrim <http://diveintomark.org/>"
__version__ = "$Revision: 988 $"
__copyright__ = "Copyright (c) 2002 Sam Ruby and Mark Pilgrim"

import getopt
import feedvalidator
import sys
import os
import urllib
import urllib2
import urlparse

def run():
  # arg 1 is URL to validate
  link = sys.argv[1:] and sys.argv[1] or 'http://www.intertwingly.net/blog/index.atom'
  link = urlparse.urljoin('file:' + urllib.pathname2url(os.getcwd()) + '/', link)
  try:
    link = link.decode('utf-8').encode('idna')
  except:
    pass
  print 'Validating %s' % link

  curdir = os.path.abspath(os.path.dirname(sys.argv[0]))
  basedir = urlparse.urljoin('file:' + curdir, ".")

  try:
    if link.startswith(basedir):
      events = feedvalidator.validateStream(urllib.urlopen(link), firstOccurrenceOnly=1,base=link.replace(basedir,"http://www.feedvalidator.org/"))['loggedEvents']
    else:
      events = feedvalidator.validateURL(link, firstOccurrenceOnly=1)['loggedEvents']
  except feedvalidator.logging.ValidationFailure, vf:
    events = [vf.event]

  # (optional) arg 2 is compatibility level
  # "A" is most basic level
  # "AA" mimics online validator
  # "AAA" is experimental; these rules WILL change or disappear in future versions
  from feedvalidator import compatibility
  filter = sys.argv[2:] and sys.argv[2] or "AA"
  filterFunc = getattr(compatibility, filter)
  events = filterFunc(events)

  from feedvalidator.formatter.text_plain import Formatter
  output = Formatter(events)
  if output:
      print "\n".join(output)
      sys.exit(1)
  else:
      print "No errors or warnings"

def main():
    short_opts = "hV"
    long_opts = ["help", "version"]
    try:
        opts, args = getopt.getopt(sys.argv[1:], short_opts, long_opts)
    except getopt.GetoptError, error:
        sys.stderr.write("error: %s\n\n" % error)
        sys.stderr.write("Try `%s --help` for more information.\n" % sys.argv[0])
        sys.exit(1)
    for opt, value in opts:
        if opt in ("-h", "--help"):
            sys.stdout.write("""Usage: feedvalidator [OPTION] [FEED] [LEVEL]

Validate a feed as RSS, Atom or KML. The feed can be a local or remote URI.

The optional level argument can be one of the following:

  A    basic level only
  AA   mimic the online validator (default)
  AAA  experimental, these rules will change or disappear in future versions

The exit status is 0 for success or 1 for failure.

Options:

  -h, --help     display a short help message and exit
  -V, --version  display version information and exit

Report bugs using the `reportbug` command.
"""
)
            sys.exit(0)
        if opt in ("-V", "--version"):
            sys.stdout.write("""feedvalidator - Feed Validator 0~svn1022

Copyright 2002, Sam Ruby and Mark Pilgrim

Licensed under an MIT variant free software license.

Written by Sam Ruby and Mark Pilgrim.
""")
            sys.exit(0)
    run()

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        pass
