Java 获取文件、修改内容并使用JGit提交
我正在尝试编写代码,可以从存储库中获取文件内容,对文件内容进行一些更改,然后写回文件并提交 我能够获取内容,但不知道如何将内容写入同一个文件 这是我正在使用的代码Java 获取文件、修改内容并使用JGit提交,java,git,git-commit,jgit,Java,Git,Git Commit,Jgit,我正在尝试编写代码,可以从存储库中获取文件内容,对文件内容进行一些更改,然后写回文件并提交 我能够获取内容,但不知道如何将内容写入同一个文件 这是我正在使用的代码 public void test() { String filename = "test.txt"; Repository repository = openRepository(); try { ObjectId lastCommitId = repository.resolve(Consta
public void test() {
String filename = "test.txt";
Repository repository = openRepository();
try {
ObjectId lastCommitId = repository.resolve(Constants.HEAD);
RevWalk revWalk = new RevWalk(repository);
RevCommit commit = revWalk.parseCommit(lastCommitId);
// and using commit's tree find the path
RevTree tree = commit.getTree();
// Here i was able to get data using reader
ObjectReader reader = repository.newObjectReader();
ObjectInserter writer = repository.newObjectInserter();
String data = null;
try {
commitNewData(filename, "Hello");
} catch (GitAPIException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
reader.release();
}
revWalk.dispose();
repository.close();
} catch (RevisionSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AmbiguousObjectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IncorrectObjectTypeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Repository openRepository(){
try{
Repository repository = new FileRepository("c:\\gitest\\.git");
return repository;
}catch(Exception e){
}
return null;
}
public void commitNewData(String filename, String data) throws IOException, ConcurrentRefUpdateException {
Repository repository = openRepository();
ObjectInserter inserter = repository.newObjectInserter();
PrincipalID principal = new PrincipalID("me@test.com");
PersonIdent author = new PersonIdent(principal.getLocalID(), principal.getID());
PersonIdent committer = new PersonIdent("Sample Data", "raviteja.bellam@msci.com");
try {
// get head commit
ObjectId lastCommitId = repository.resolve(Constants.HEAD + "^{commit}");
// Get bytes
byte[] bytes = data.getBytes(Charset.forName("UTF-8"));
System.out.printf("Data: %s", data);
// Create new object hash
ObjectId resultObjectId = inserter.insert(Constants.OBJ_BLOB, bytes);
System.out.printf("BlobId: %s", resultObjectId.toString());
// create tree
TreeFormatter treeFormatter = new TreeFormatter();
treeFormatter.append(filename, FileMode.REGULAR_FILE, resultObjectId);
// add existing entries to the tree
addExistingEntriesToTree(repository, lastCommitId, treeFormatter);
ObjectId treeId = treeFormatter.insertTo(inserter);
System.out.printf("TreeId: %s", treeId.toString());
// insert tree to the commit
CommitBuilder builder = new CommitBuilder();
builder.setParentId(lastCommitId);
builder.setCommitter(committer);
builder.setAuthor(author);
builder.setTreeId(treeId);
builder.setMessage(String.format("Updated %s", filename));
ObjectId commitId = null;
// insert commit
try{
commitId = inserter.insert(builder);
}catch(Exception e){
System.out.println(e);
}
System.out.printf("CommitId: %s", commitId.toString());
// update the ref
RevWalk rw = new RevWalk(repository);
RevCommit revCommit = rw.parseCommit(commitId);
RefUpdate ru = repository.updateRef(Constants.HEAD);
ru.setNewObjectId(commitId);
ru.setRefLogMessage(String.format("commit: %s", revCommit.getShortMessage()), false);
ru.setExpectedOldObjectId(lastCommitId);
RefUpdate.Result rc = ru.forceUpdate();
RepositoryState state = repository.getRepositoryState();
switch (rc) {
case NEW:
case FORCED:
case FAST_FORWARD: {
if (state == RepositoryState.MERGING_RESOLVED) {
// Commit was successful. Now delete the files
// used for merge commits
repository.writeMergeCommitMsg(null);
repository.writeMergeHeads(null);
} else if (state == RepositoryState.CHERRY_PICKING_RESOLVED) {
repository.writeMergeCommitMsg(null);
repository.writeCherryPickHead(null);
} else if (state == RepositoryState.REVERTING_RESOLVED) {
repository.writeMergeCommitMsg(null);
repository.writeRevertHead(null);
}
break;
//return revCommit;
}
case REJECTED:
case LOCK_FAILURE:
throw new ConcurrentRefUpdateException(
JGitText.get().couldNotLockHEAD, ru.getRef(),
rc);
default:
throw new JGitInternalException(MessageFormat.format(
JGitText.get().updatingRefFailed,
Constants.HEAD, commitId.toString(), rc));
}
inserter.flush();
} finally {
inserter.release();
}
}
protected void addExistingEntriesToTree(Repository repository, ObjectId lastCommitId, TreeFormatter treeFormatter) throws IOException {
RevWalk revWalk = new RevWalk(repository);
// get last commit
RevCommit commit = revWalk.parseCommit(lastCommitId);
// get it's tree
RevTree tree = commit.getTree();
// now walk the tree
TreeWalk treeWalk = new TreeWalk(repository);
treeWalk.addTree(tree);
//treeWalk.setRecursive(true);
while (treeWalk.next()) {
treeFormatter.append(treeWalk.getNameString(), treeWalk.getFileMode(0), treeWalk.getObjectId(0));
}
}
我正在尝试签出我的文件:
Repository repository = new FileRepository("c:\\Users\\gitest\\.git");
Git git = new Git(repository);
CheckoutCommand checkout = git.checkout();
//checkout.addPath("test.txt");
checkout.setName("master");
//checkout.setName("test.txt");
Ref ref = checkout.call();
在Git中修改文件的指定方法是将提交签出到工作目录,更改文件,然后将其添加到索引并提交更改 在JGit中,大致如下所示:
Git git = new Git( repository );
git.checkout().setName( <commit-id> ).call(); // likely already done
// modify file
git.add().addFilepattern( "/repo-relative/path/to/file" ).call();
git.commit().setMessage( "Modify file" ).call();
Git-Git=新的Git(存储库);
git.checkout().setName().call();//可能已经做了
//修改文件
git.add().addFilepattern(“/repo-relative/path/to/file”).call();
git.commit().setMessage(“修改文件”).call();
如果这不是您想要的,并且您确实知道自己在做什么,那么您可以使用较低级别的JGit API来编写提交对象。你好,Herrmann,谢谢您的回复。我在上面编辑了我的代码,试图使用较低级别的JGITAPI调用。Git状态显示文件已更新,但当我打开文件时,没有任何更改。你能告诉我我在哪里吗wrong@user3833055为什么在Git中执行操作的普通方式(即签出、修改、提交)不适合您?@Herrmann我无法签出我的文件。我有一个特定的文件,我需要修改并提交回回购。我试图使用我在上面添加的代码。@Hermann上面的代码实际上是有效的,它将数据复制到存储库中,当我从该文件中读取数据时,我能够看到修改过的内容,但当我在存储库中检查该文件时,它显示的是旧版本