Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in

How to Compare fields of 2 jira projects using Groovy Script

Vinay January 21, 2025 edited

I am struggling with groovy script which can compare all fields of 2 project and create a confluence page with findings .
I am new to groovy script , so this i got from GPT.

Code :


import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.fields.FieldManager
//import org.apache.poi.ss.usermodel.*
//import org.apache.poi.xssf.usermodel.XSSFWorkbook
import java.io.File
import java.io.FileOutputStream
import com.atlassian.sal.api.net.Request
import com.atlassian.applinks.api.ApplicationLink
import com.atlassian.applinks.api.ApplicationLinkService

// Configuration
def projectKey1 = "PROJECT1" // Replace with the first project's key
def projectKey2 = "PROJECT2" // Replace with the second project's key
def createConfluencePage = true // Set to true to create a Confluence page
def confluenceSpaceKey = "SPACE" // Confluence space key (if enabled)
def confluencePageTitle = "Jira Fields Comparison of  ${projectKey1} vs ${projectKey2}" // Confluence page title

// Get project objects
def projectManager = ComponentAccessor.getProjectManager()
def project1 = projectManager.getProjectByCurrentKey(projectKey1)
def project2 = projectManager.getProjectByCurrentKey(projectKey2)

if (!project1 || !project2) {
    throw new IllegalArgumentException("Invalid project keys provided!")
}

// Get field manager
def fieldManager = ComponentAccessor.getFieldManager()

// Retrieve all fields for comparison

def fieldsProject1 = fieldManager.getAvailableFields(project1)
def fieldsProject2 = fieldManager.getAvailableFields(project2)

// Compare fields
def fieldComparison = []
fieldsProject1.each { field1 ->
    def matchingField = fieldsProject2.find { field2 -> field2.getId() == field1.getId() }
    fieldComparison << [
        field1.getName(),
        field1.getFieldType(),
        matchingField ? "Yes" : "No",
        matchingField ? matchingField.getFieldType() : "N/A"
    ]
}

// Generate Confluence page
def generateConfluencePage = {
    // Get application link to Confluence
    def appLinkService = ComponentAccessor.getComponent(ApplicationLinkService)
    def confluenceLink = appLinkService.getPrimaryApplicationLink("confluence")
    if (!confluenceLink) {
        throw new IllegalStateException("No Confluence application link configured!")
    }

    // Prepare table data
    def tableContent = fieldComparison.collect { row ->
        "| ${row[0]} | ${row[1]} | ${row[2]} | ${row[3]} |"
    }.join("\n")
    def confluenceContent = """
        h1. Jira Fields Comparison: ${projectKey1} vs ${projectKey2}

        || Field Name (Project 1) || Field Type (Project 1) || Exists in Project 2? || Field Type (Project 2) ||
        ${tableContent}
    """

    // Send a request to create a Confluence page
    def authenticatedRequestFactory = confluenceLink.createAuthenticatedRequestFactory()
    authenticatedRequestFactory
        .createRequest(Request.MethodType.POST, "/rest/api/content")
        .addHeader("Content-Type", "application/json")
        .setRequestBody("""{
            "type": "page",
            "title": "${confluencePageTitle}",
            "space": {"key": "${confluenceSpaceKey}"},
            "body": {
                "storage": {
                    "value": "${confluenceContent}",
                    "representation": "wiki"
                }
            }
        }""")
        .execute({ response ->
            if (response.statusCode == 200 || response.statusCode == 201) {
                println "Confluence page created successfully!"
            } else {
                println "Failed to create Confluence page: ${response.statusCode} - ${response.responseBodyAsString}"
            }
        })
}

// Execute the chosen output
if (createConfluencePage) {
    generateConfluencePage()
} else {
    generateExcelFile()
}

0 answers

Suggest an answer

Log in or Sign up to answer
DEPLOYMENT TYPE
CLOUD
PRODUCT PLAN
STANDARD
TAGS
atlassian, team '25, conference, certifications, bootcamps, training experience, anaheim ca,

Want to make the most of Team ‘25?

Spend the day sharpening your skills in Atlassian Cloud Organization Admin or Jira Administration, then take the exam onsite. Already ready? Take one - or more - of 12 different certification exams while you’re in Anaheim at Team' 25.

Learn more
AUG Leaders

Upcoming Jira Events