Snippets

Adaptavist Find Disabled User Repositories

Created by Jamie Echlin
package examples.stash

import com.atlassian.sal.api.component.ComponentLocator
import com.atlassian.sal.api.transaction.TransactionCallback
import com.atlassian.sal.api.transaction.TransactionTemplate
import com.atlassian.stash.internal.hibernate.SwappableSessionFactory
import com.atlassian.stash.repository.Repository
import com.atlassian.stash.repository.RepositoryService
import com.atlassian.stash.user.UserService
import com.atlassian.stash.util.Page
import com.atlassian.stash.util.PageProvider
import com.atlassian.stash.util.PageRequest
import com.atlassian.stash.util.PagedIterable
import com.onresolve.scriptrunner.runner.ScriptRunnerImpl

// Change to *false* to actually delete the repositories
def preview = true

def userService = ComponentLocator.getComponent(UserService)
def repositoryService = ComponentLocator.getComponent(RepositoryService)

def reposToDelete = []

def txTemplate = ScriptRunnerImpl.getPluginComponent("txTemplate") as TransactionTemplate
txTemplate.execute(new TransactionCallback() {
    @Override
    Object doInTransaction() {
        def session = ComponentLocator.getComponent(SwappableSessionFactory).getWrappedObject().getCurrentSession()
        session.createQuery("select p.name from InternalProject p where project_type = 1").list().each { String slug ->

            def username = slug.replace("~", "")
            def stashUser = userService.getUserByName(username)

            // check the user exists and is active
            if (!stashUser || !stashUser.active) {
                new PagedIterable<Repository>(new PageProvider<Repository>() {
                    @Override
                    Page<Repository> get(PageRequest pageRequest) {
                        repositoryService.findByProjectKey(slug, pageRequest) as Page<Repository>
                    }
                }, 10).each { repo ->
                    reposToDelete << repo
                    if (! preview) {
                        repositoryService.delete(repo)
                    }
                }
            }
        }
    }
})

(preview ? "Will delete" : "Have deleted") + " the following repos: ${reposToDelete}"

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.