最近做項目用git向github推送時,總是出現大於100M的文件導致push失敗,每次都要手動找到大於100M的文件,然後修改.gitattributes,用git-fls 上傳,很麻煩,所以就用Java寫了一個自動檢測Git倉庫中大於100M的文件,並將其添加到.gitattributes的程序,代碼如下所示。使用時只需要將main函數中的gitRepositoryDir路徑改爲自己倉庫的路徑即可。另外修改.gitattributes文件的方法是註釋了的,還是建議手動添加,不然出問題很麻煩;自動添加只要去掉下面這行的註釋,也可以根據自己需要修改appendContext()方法。注意,如果可能出現大於100M的文件,一定要在commit之前就檢測一下!!!!
// appendContext(path,context);//這是修改.gitattributes文件的方法
完整代碼如下:
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class GitCheck {
public static void main(String[] args) throws FileNotFoundException {
File gitRepositoryDir = new File("D:\\Repository");//修改成自己的倉庫目錄即可
checkGitFiles(gitRepositoryDir,gitRepositoryDir.getAbsolutePath());
}
public static void checkGitFiles(File fileDir,String baseFileString) throws FileNotFoundException {// 操作文件
if (!fileDir.exists()) {
throw new FileNotFoundException("倉庫路徑不存在");
}
File[] files = fileDir.listFiles();
if (files != null) {// 判斷是否還有子目錄
for (int i = 0; i < files.length; i++) {
if (files[i].isFile() && files[i].length() >= 100 * 1024 *1024) {// 判斷是文件,且大小大於100M(github大文件上傳限制爲100M)
File file = files[i];
List<String> list = new ArrayList<>();//獲取文件的相對路徑
while(!file.getAbsolutePath().equals(baseFileString)){
list.add(file.getName());
file = file.getParentFile();
}
StringBuilder sb = new StringBuilder();
for(int j = list.size() - 1;j >= 0;j --){
sb.append("/" + list.get(j));
}
System.out.println(sb);//打印相對路徑
String path = baseFileString + "\\.gitattributes"; //.gitattributes文件路徑
String context = sb.toString() + " filter=lfs diff=lfs merge=lfs -text";//構建寫入.gitattributes文件的字符串
// appendContext(path,context);//慎用,還是根據打印出的字符串手動添加!!!!!
} else {
if(!files[i].getName().equals(".git"))//忽略倉庫目錄
checkGitFiles(files[i],baseFileString);// 遞歸調用,直到所有的文件都沒有了子目錄
}
}
}
}
//向文件追加內容方法
public static void appendContext(String path,String appendContext ) {
FileWriter fw = null;
try {
//如果文件存在,則追加內容;如果文件不存在,則創建文件
File f = new File(path);
fw = new FileWriter(f, true);
} catch (IOException e) {
e.printStackTrace();
}
PrintWriter pw = new PrintWriter(fw);
pw.println(appendContext);
pw.flush();
try {
fw.flush();
pw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}