Assessing Confluence DC Page Templates for Macro Usage

The task was to determine which Confluence page templates were using a given macro, without resorting to doing it by hand.

The most obvious way to do this is to parse the body of the template as text, and use regex to look for macro references.  Here’s an example of some code that does this:

import com.atlassian.confluence.pages.templates.PageTemplateManager
import com.atlassian.sal.api.component.ComponentLocator

PageTemplateManager pageTemplateManager = ComponentLocator.getComponent(PageTemplateManager.class);
def templates = pageTemplateManager.getGlobalPageTemplates()

def structuredMacroPattern = /<ac:structured-macro ac:name="multiexcerpt-include".*?<\/ac:structured-macro>/

templates.each{template -> 
   
    String templateContents = pageTemplateManager.getPageTemplate(template.name,null).getContent();
     def macroMatcher = templateContents.toString() =~ structuredMacroPattern
     if(macroMatcher){
         log.warn(template.title)
     }
}

So what is it doing?  It first returns a list of global templates.  It then iterates through the template objects, using the title of the template to return the body contents. 

Finally, it compares the contents of the body against a regex statement we provided, that includes the name of the macro we want to assess.

One idea for expanding on this would be to fetch a list of all of the user macros in the system, and then return a reporting indicating which templates used which macros.

 

Leave a Reply

Your email address will not be published. Required fields are marked *