How to archive some dependencies in specific way inside tar task?

I am writing a task, which packages application along with dependencies from ‘packaged’ configuration. Some of those dependencies need to be packaged in a certain way, e.g. dependencyA’s contents must be first unpacked and dependencyB should be inside a ‘dependencyB’ directory within the archive. Anything else i just included in the main archive, although this may change later. Any ideas on how to achieve that?

I’ve tried the following:

project.tasks.create('packageApplication', Tar) {
    from {
        project.configurations['packaged'].collect {
            if (it.name.startsWith('dependencyA')) {
                project.tarTree(it)
            } else if (it.name.startsWith('dependencyB') {
                //How to set destination directory for this dependency?
                it
            } else {
                it
            }
        }
    }
}

I probably need separate from closures for these, but was wandering if anyone knows a nice way of achieving this only iterating through packaged dependencies once.

Thanks

I would reverse the nesting logic of your task like this:

project.tasks.create('packageApplication', Tar) {
    project.configurations['packaged'].each { dep ->
            if (dep.name.startsWith('dependencyA')) {
                from {
                     project.tarTree(dep)
                }
            } else if (dep.name.startsWith('dependencyB') {
                into('subdir') {
                    from {
                         project.tarTree(dep)
                    }
                }
            } else {
                from {
                    dep
                }
            }
     }
}

I already tried something like this, but I get the error:

Caused by: org.gradle.api.InvalidUserDataException: Cannot change dependencies of configuration ‘:packaged’ after it has been resolved.

I think this is because now I’m accessing dependencies during the configuration phase, whereas with my previous approach they are being accessed during execution phase because everything is wrapped inside from closure.