Skip to main content
Example scripts
arrow icon
To homepage
Confluence
Cloud icon
Cloud

Bulk convert migrated built-in macros

Created 8 month(s) ago, Updated 27 day(s) ago
App in script
ScriptRunner For Confluence
ScriptRunner For Confluence
by Adaptavist
Compatibility
compatibility bullet
Confluence
Language |
groovy
import com.atlassian.confluence.rest.clientv2.model.Space
import com.atlassian.confluence.rest.clientv2.model.PageBulk

def spaceKeys = "ds,ds1" // Replace the spaceKeys to your own value
def spaces = fetchSpacesByKeys(spaceKeys)
spaces.each { space ->
    def pages = fetchPagesBySpaceId(space.id)
    pages.each { page ->
        def storage = page.body.storage.value
        def currentVersion = page.version.number as Integer
        def newContent = replaceAcName(storage)
        if (newContent == storage) {
            return
        }

        def response = put("/wiki/api/v2/pages/${page.id}")
                .header("Content-Type", "application/json")
                .body([
                        id: page.id,
                        status: "current",
                        title: page.title,
                        body: [
                                representation: "storage",
                                value: newContent,
                        ],
                        version: [
                                number: currentVersion + 1
                        ]
                ]).asObject(Map)
        if (response.status != 200) {
            throw new RuntimeException("Failed to convert migrated macros.")
        }
        logger.info("Page '${page.title}' has been updated.")
    }
}

def replaceAcName(String storage) {
    def SEARCH = ["ac:name=\"add-label\"", "ac:name=\"choose-label\"", "ac:name=\"page-info\""]
    def REPLACEMENT = ["ac:name=\"sr-add-labels-macro\"", "ac:name=\"sr-choose-label-macro\"", "ac:name=\"sr-page-info-macro\""]
    def modifiedStorage = storage
    SEARCH.eachWithIndex { acName, index ->
        modifiedStorage = modifiedStorage.replace(acName, REPLACEMENT[index])
    }
    modifiedStorage
}

List<PageBulk> fetchPagesBySpaceId(spaceId) {
    def pages = (List) get("/wiki/api/v2/spaces/${spaceId}/pages?body-format=storage").asObject(Map).body.results
    if (!pages) {
        throw new RuntimeException("Failed to fetch pages or no pages found.")
    }
    pages
}

List<Space> fetchSpacesByKeys(spaceKeys) {
    def spaces = (List) get("/wiki/api/v2/spaces?keys=${spaceKeys}").asObject(Map).body.results
    if (!spaces) {
        throw new RuntimeException("Failed to fetch spaces or no spaces found.")
    }
    spaces
}
Having an issue with this script?
Report it here