2012-10-16 70 views
3

我正在嘗試編寫一些自定義NAnt任務來執行某些基於文件的操作。其中一個非常有用的功能是能夠在其中一個輸入文件上運行<expandproperties>篩選器。編寫能夠使用過濾器的自定義NAnt任務

爲了保持適當的通用任務,我只想啓用對<filterchain>元素的支持(類似於<copy>任務的工作方式)。

我一直在使用<copy>任務的源代碼來指導我,但是我一直在寫入任務時遇到內部方法。我知道我可以使用反射來打破封裝,但我不願意這樣做。

有沒有人知道任何有用的文章,或有任何這方面的經驗?

回答

1

我開始着手創建一個帶有TextReader的私有Filter子類(基本上在NAnt源中重新創建PhysicalTextReader)。但是我意識到,實際上,有通過過濾器鏈讀取文件更簡單的方法:

[TaskName("mytask")] 
public class MyTask : Task 
{ 
    /// <summary> 
    /// Chain of filters used to alter the input file's content as it is read. 
    /// </summary> 
    [BuildElement("filterchain")] 
    public FilterChain Filters { get; set; } 

    /// <summary> 
    /// The input file. 
    /// </summary> 
    [TaskAttribute("input")] 
    public FileInfo InputFile { get; set; } 

    protected override void ExecuteTask() 
    { 
     Log(FileUtils.ReadFile(InputFile.FullName, Filters, null)); 
    } 
} 

然後你就可以準確地使用你所期望的:

<mytask input="foo.txt"> 
    <filterchain> 
     <expandproperties /> 
    </filterchain> 
</mytask>