Source

reviewanywhere / say-thanks

Full commit
#!/usr/bin/env python
import re
import urllib
import urllib2
from os import path

def read_config_file(file, config=None):
    """ Read a file-like thanksrc file into (optional) dictionary 'config' and
        return 'config'. """
    if config is None:
        config = {}

    comment_re = re.compile("#.*")
    lineno = 0
    for line in file.xreadlines():
        lineno += 1
        line = comment_re.sub("", line)
        line = line.strip()
        if not line: continue

        if ':' not in line:
            raise Exception("Reading %r: malformed line %d: %r"
                            %(file.name, lineno, line))

        (key, val) = [ part.strip() for part in line.split(":", 1) ]
        config[key] = val

    return config

def post_thanks(thanksd_url, app_name, comments):
    values = {
        'app_name': app_name,
        'comments': comments,
    }

    data = urllib.urlencode(values)
    target_url = thanksd_url.rstrip("/") + "/" + app_name + "/new"
    response = urllib2.urlopen(target_url, data)
    return response.read()

def get_comment(config):
    message = """
        This script lets you say 'thanks' to the author of %(app-name)s.
        Let them know you appreciate it by leaving a short message, and (if
        you'd like) your email/website/Twitter/Identica/GPG key fingerprint or
        something else to put an identity to your kudos.
        Finish your message by leaving a couple of blank lines.
        And... Thanks! """ %(config)
    # Strip the leading whitespace from the message
    message = "\n".join([ line.strip() for line in message.splitlines() ])
    print message

    # Now Read the comments...
    comment = []
    while True:
        try:
            line = raw_input()
        except EOFError:
            # Breaking on an EOF
            break

        comment.append(line)

        # Check if the last two lines, stripped of whitespace,
        # were blank...
        if [ c.strip() for c in comment[-2:] ] == [ '', '' ]:
            # ... and break if they were
            break

    return "".join(comment)

def run():
    app_config = path.join(path.dirname(__file__), ".thanksrc")
    config = read_config_file(open(app_config))
    comment = get_comment(config)
    print "Sending in the message..."
    print post_thanks(config['thanksd-url'], config['app-name'], comment)

if __name__ == '__main__':
    run()