2016-03-23 81 views
0

我有以下的搖籃代碼:如何在Gradle Ant任務中重構通用代碼?

ant.jdiff(destdir: outputDir) { 
    old(name: "platform-${oldVersion}") { 
    oldVersionRoot.eachDirMatch({ dir -> 
     new File("${dir}/src").exists() 
    }) { dir -> 
     dirset(dir: "${dir}/src") 
    } 
    } 

    'new'(name: "platform-${currentVersion}") { 
    currentVersionRoot.eachDirMatch({ dir -> 
     new File("${dir}/src").exists() 
    }) { dir -> 
     dirset(dir: "${dir}/src") 
    } 
    } 
} 

我已經試過:

final getSrcDirSets = { root -> 
    final result = [] 

    root.eachDirMatch({ dir -> 
    new File("${dir}/src").exists() 
    }) { dir -> 
    result.append(dirset(dir: "${dir}/src")) 
    } 

    result 
} 

ant.jdiff(destdir: outputDir) { 
    old(name: "example-${oldVersion}") { 
    getSrcDirSets(oldVersionRoot) 
    } 

    'new'(name: "example-${currentVersion}") { 
    getSrcDirSets(currentVersionRoot) 
    } 
} 

但導致以下錯誤:

Caused by: org.gradle.api.internal.MissingMethodException: Could not find method old() for arguments [{name=example-1.2.3}, build_at5jtticx[email protected]26f75d38] on task ':jdiff'. 

如何通用代碼被重構到一個單獨的功能?

回答

0

的一種方式,雖然不是很理想,因爲DefaultAntBuilder的所有實例都受到影響,是通過Groovy中的monkeypatching:

ant.metaClass.jDiff_getSrcDirSets = { root -> 
    root.eachDirMatch({ dir -> 
    new File("${dir}/src").exists() 
    }) { dir -> 
    dirset(dir: "${dir}/src") 
    } 
} 

ant.property(name: "JDIFF_HOME", value: jdiffHome) 
ant.jdiff(
    destdir: outputDir, 
    verbose: 'off', 
    stats: 'on', 
    docchanges: 'off', 
    source: '1.8') { 
    old(name: "${project.name}-${oldVersion}") { 
    jDiff_getSrcDirSets(oldVersionRoot) 
    } 

    'new'(name: "${project.name}-${currentVersion}") { 
    jDiff_getSrcDirSets(currentVersionRoot) 
    } 
}