Tuesday, 18 September 2012

Uploading attachments to Jira using Jira4r

Today I found myself needing to make a ruby script that would update a file and upload it to an issue as an attachment in Jira.
I found the SOAP API method to do this in Jira's documentation, but I didn't find a suitable mapping in the Jira4r docs.
I found this comment on the Jira4r page, the only  reference to the API's addBase64EncodedAttachmentsToIssue method. Also found some forum posts of people with the same issue and that comment was the only found solution.
So if you need to upload stuff to Jira, follow the instructions in that comment, you'll find the file to edit at "[GEM_PATH]/gems/jira4r-0.3.0/lib/jira4r/v2/jira_soap_service_driver.rb"
The end result I got in my file for it to work was this, worked for my task.

The usage is quite simple, the test example on the page linked shows well how to use it, I'm just going to paste here to keep it "in record".
The only difference between what I did and what's on the example is that I used the base64 standard lib for encoding while he uses Array#pack('m') which results on the same thing.


#!/usr/bin/env ruby
$LOAD_PATH << './lib'
gem('soap4r')
gem('jira4r')
require 'jira4r'
require 'base64'
require 'cgi'
jiraBaseUrl      = "http://localhost:8080"
jiraUsername     = "automated-user"
jiraPassword     = "Thbmahws,"
escapedPassword  = CGI::escape(jiraPassword)
jira = Jira4R::JiraTool.new(2, jiraBaseUrl)
jira.login(jiraUsername, jiraPassword)
newFilepath = "H:\\edisc\\Tst\\Printed\\Test.eml"
fileName = newFilepath.split('\').last
issue = Jira4R::V2::RemoteIssue.new
issue.project = "ED"
issue.type = "1"
issue.summary = "This is a test"
issue.description = newFilepath
returnedIssue = jira.createIssue(issue)

filedata = File.open(newFilename, "rb") { |f| f.read }
attachmentData = filedata.pack("m")
jira.addBase64EncodedAttachmentsToIssue(returnedIssue.key.to_s, fileName, attachmentData)