<?php
/**
 * Tweeter.php - an SVN post-commit hook script to post SVN commits to twitter.
 * 
 * Requires the following (aka tested with and will likely fail if not present):
 *  - a linux environment
 *  - PHP 5 CLI
 *  - a working svn install
 *  - a twitter account
 *  - curl installed
 * 
 * LICENSE: This is free software. Use it, modify it, sell it, do whatever 
 * you want with it. We offer no guarantee it will work and no support, but 
 * we hope you find some use for it.
 * 
 * USAGE: Call it from your post-commit script like so:
 *   [path-to-php5-cli] [path-to-tweeter.php] "${REPOS}" "${REV}"
 * 
 * Don't forget to replace TWITTER_USERNAME and TWITTER_PASS with your
 * proper username and password below.
 * 
 * @author Steve Lounsbury <steve@76design.com>
 * @link http://76design.com
 */

ini_set('display_errors', 1);
error_reporting(E_ALL | E_STRICT);

define('CMD_SVNLOOK_INFO', 'svnlook info %s -r %s');
define('CMD_SVNLOOK_CHANGED', 'svnlook changed %s -r %s');
define('CMD_CURL_TWITTER', 'curl -u TWITTER_USERNAME:TWIITER_PASS -d status="%s" http://twitter.com/statuses/update.xml');

$svn = $argv[1];
$rev = $argv[2];

$details = array();
$changed = array();

exec(sprintf(CMD_SVNLOOK_INFO, $svn, $rev), $details);
exec(sprintf(CMD_SVNLOOK_CHANGED, $svn, $rev), $changed);

// First line of the changed files should give us
// which project is being committed.
// Format is:
// U   [project]/trunk/[file]

$all_changed = $changed;
$first_changed = $changed[0];

$changed = $changed[0];
$changed = preg_split('/\s+/', $changed);
$changed = $first_changed = $changed[1];
$changed = explode('/', $changed);
$changed = $changed[0];

// Output of svnlook info is formatted like this:
// author
// date
// length of message
// message
$author = array_shift($details);
$date = array_shift($details);
$length = array_shift($details);


$date = preg_split('/\s+/', $date);
$date = $date[0] . ' ' . $date[1];


$message = implode("\n", $details);
$tweet = "r$rev $changed [$author] \n";
if ($length > (144 - strlen($tweet))) {
        $message = substr($message, 0, 140 - strlen($tweet)) . '...';
}

$tweet .= $message;

exec(sprintf(CMD_CURL_TWITTER, $tweet));

