2016-06-30 72 views
2

當使用設置有非法字符一個分支名(概述here),像這樣:JGit支持逃生分支名稱

git.checkout().setName("......my:bad:branch:name") 

它生成一個低級別的git的錯誤。

理想情況下,我可以避免直接在我的代碼中編碼這些無效字符。 JGit是否有任何功能來轉義/替換/去除無效字符?

+0

@RüdigerHerrmann我結束了備案與jgit功能請求,[#497123]( https://bugs.eclipse.org/bugs/show_bug.cgi?id=497123),引用你的答案。 –

回答

1

更新2017年1月27日:由於this commit有一個靜態方法Repository::normalizeBranchName()逃脫給定的字符串,形成一個有效的裁判的名字並返回。這些更改將隨JGit v4.7發佈。

對於早期版本的JGit,名稱必須手動轉義。

With Repository::isValidRefName()您可以確定給定的字符串是否爲有效的Git ref名稱。 documentation for git check-ref-format詳細描述了有效的參考名稱必須符合的規則。

我正在使用以下劃線(可能有一些不準確)替換所有可疑人物的一個項目這個方法:

String DOT_LOCK = ".lock"; 
String REPLACEMENT = "_"; 

String escapeRefName(String refName) { 
    String result = refName; 
    if(result.endsWith(DOT_LOCK)) { 
    result = result.substring(0, result.length() - DOT_LOCK.length()); 
    } 
    result = result.replace(" ", REPLACEMENT); 
    result = result.replace("\\", REPLACEMENT); 
    result = result.replace("/", REPLACEMENT); 
    result = result.replace("^", REPLACEMENT); 
    result = result.replace("@", REPLACEMENT); 
    result = result.replace("{", REPLACEMENT); 
    result = result.replace("}", REPLACEMENT); 
    result = result.replace("~", REPLACEMENT); 
    result = result.replace("*", REPLACEMENT); 
    result = result.replace("?", REPLACEMENT); 
    result = result.replace(":", REPLACEMENT); 
    result = result.replace("[", REPLACEMENT); 
    result = result.replace(".", REPLACEMENT); 
    result = result.replace("\u007F", REPLACEMENT); 
    return result; 
}