Minimal code to add a Mantis note with an external script

General discussion of Mantis.

Moderators: Developer, Contributor

Post Reply
kbrannen

Minimal code to add a Mantis note with an external script

Post by kbrannen »

For anyone else who looking for the minimal code to add a note with an external script (talk to the plugin), I'll volunteer this as I was unable to find it anywhere else. The Mantis Wiki has something a little more complicated (checkin.php), but in searching for words with the title string, I came up empty. So I hope this helps others in the future. I did this in Perl as I'll need to build on it to add a LOT more stuff to it, but it could be done in about any language that offers regular expressions.

Code: Select all

#!/usr/bin/perl
#
# Usage:
#   echo "12345: Fixed...git commit KEY" | ssh mantis_svr 'cd $mantis_svr_dir/htdocs/scripts; perl checkin.pl"
#   You have to be in the mantis dir or the php part won't work as it can't find "core.php".
#   1 ticket number per checkin.
#
# History:
#   based on: MantisBT's checkin.php

use strict;
use warnings;

# Define our search patterns, we'll use the first that matches;
# reorder to suit your needs
my @search_patterns = (
        q/^(\d{4,8})\b/,        # If leading number of 4-8 digits, assume it's a Mantis number
        q/\bM#?(\d+)\b/,        # Else, it's only a Mantis number if we have M or M# in front of the number
        );

# Get our username so the note is attributed to us
my $username = $ENV{USER};
print "user is $username\n";

# Get checkin comment from STDIN
$/ = undef;
my $commit_msg = <>;

# Search for a ticket number
my $ticket_id;
foreach my $regex (@search_patterns)
{
        if ($commit_msg =~ m/$regex/)
        {
                $ticket_id = $1;
                print "found ticket id $ticket_id\n";
                last;
        }
}

# If no ticket number found, then no work to do.
if (!$ticket_id)
{
        print "Commit message does not reference any tickets.\n";
        exit(0);
}

# Create the comment ... **LOTS** more code to go here...
my $note = "This is a generated note...\n$commit_msg";

# Create a PHP script to talk to Mantis
my $php_code = qq%
<?php
global \$g_bypass_headers;
\$g_bypass_headers = 1;
require_once( dirname( dirname( __FILE__ ) ) . DIRECTORY_SEPARATOR . 'core.php' );
if( !auth_attempt_script_login( "$username" ) ) { echo "Unable to login\\n"; exit( 1 ); }
helper_call_custom_function( 'checkin', array( $ticket_id, "$note", '', '', false ) );
exit( 0 );
%;

# Talk to Mantis...
open(PIPE,"|/usr/bin/php") or die "cannot open pipe to php\n";
print PIPE $php_code;
close(PIPE);
print "php exit status was $?, ($!)\n" if ($?);

exit($?);
HTH,
Kevin
Post Reply