Groovy 展平Gradle中文件树的第一个目录

Groovy 展平Gradle中文件树的第一个目录,groovy,gradle,Groovy,Gradle,我正在写一个任务,将tarball提取到目录中。我不能控制这个柏油球的内容 tarball包含一个目录,其中包含我真正关心的所有文件。我想从那个目录中取出所有内容,并将其复制到我的目的地 例如: /root/subdir /root/subdir/file1 /root/file2 期望的: /subdir /subdir/file1 /file2 以下是我迄今为止尝试过的方法,但这似乎是一种非常愚蠢的方法: copy { eachFile { def segment

我正在写一个任务,将tarball提取到目录中。我不能控制这个柏油球的内容

tarball包含一个目录,其中包含我真正关心的所有文件。我想从那个目录中取出所有内容,并将其复制到我的目的地

例如:

/root/subdir
/root/subdir/file1
/root/file2
期望的:

/subdir
/subdir/file1
/file2
以下是我迄今为止尝试过的方法,但这似乎是一种非常愚蠢的方法:

copy {
    eachFile {
        def segments = it.getRelativePath().getSegments() as List
        it.setPath(segments.tail().join("/"))
        return it
    }
    from tarTree(resources.gzip('mytarfile.tar.gz'))
    into destinationDir
}
对于每个文件,我获取其路径的元素,删除第一个,用
/
连接它,然后将其设置为文件的路径。这就行了……有点。问题在于,这会导致以下结构:

/root/subdir
/root/subdir/file1
/root/file2
/subdir
/subdir/file1
/file2

作为任务的最后一个操作,我可以自己删除根目录,但我觉得应该有一种更简单的方法来完成此操作。

好的,唯一的方法是解压缩zip、tar、tgz文件:(

有一个悬而未决的问题 请投赞成票

在此之前,解决方案不是很漂亮,但也不是那么难。在下面的示例中,我假设您希望从只包含apache tomcat zip文件的“tomcat”配置中删除“apache tomcat XYZ”根目录

def unpackDir = "$buildDir/tmp/apache.tomcat.unpack"
task unpack(type: Copy) {
    from configurations.tomcat.collect {
        zipTree(it).matching {
            // these would be global items I might want to exclude
            exclude '**/EMPTY.txt'
            exclude '**/examples/**', '**/work/**'
        }
    }
    into unpackDir
}

def mainFiles = copySpec {
    from {
        // use of a closure here defers evaluation until execution time
        // It might not be clear, but this next line "moves down" 
        // one directory and makes everything work
        "${unpackDir}/apache-tomcat-7.0.59"
    }
    // these excludes are only made up for an example
    // you would only use/need these here if you were going to have
    // multiple such copySpec's. Otherwise, define everything in the
    // global unpack above.
    exclude '**/webapps/**'
    exclude '**/lib/**'
}

task createBetterPackage(type: Zip) {
    baseName 'apache-tomcat'
    with mainFiles
}
createBetterPackage.dependsOn(unpack)

使用groovy的语法,我们可以使用正则表达式来消除第一个路径段:

task myCopyTask(type: Copy) {
    eachFile {
        path -= ~/^.+?\//
    }
    from tarTree(resources.gzip('mytarfile.tar.gz'))
    into destinationDir

    includeEmptyDirs = false // ignore empty directories
}

是的,这基本上就是我最终解决它的方式。感谢您找到了一个至少要引用的问题。要改名顶级目录:
eachFile{path=path.replaceFirst(/^.+?\/,“NEW\u NAME/”)}