List of usage examples for org.eclipse.jgit.lib Repository updateRef
@NonNull public RefUpdate updateRef(String ref) throws IOException
From source file:com.gitblit.utils.RefLogUtils.java
License:Apache License
/** * Updates the reflog with the received commands. * * @param user/*from ww w . j a va2 s . com*/ * @param repository * @param commands * @return true, if the update was successful */ public static boolean updateRefLog(UserModel user, Repository repository, Collection<ReceiveCommand> commands) { // only track branches and tags List<ReceiveCommand> filteredCommands = new ArrayList<ReceiveCommand>(); for (ReceiveCommand cmd : commands) { if (!cmd.getRefName().startsWith(Constants.R_HEADS) && !cmd.getRefName().startsWith(Constants.R_TAGS)) { continue; } filteredCommands.add(cmd); } if (filteredCommands.isEmpty()) { // nothing to log return true; } RefModel reflogBranch = getRefLogBranch(repository); if (reflogBranch == null) { JGitUtils.createOrphanBranch(repository, GB_REFLOG, null); } boolean success = false; String message = "push"; try { ObjectId headId = repository.resolve(GB_REFLOG + "^{commit}"); ObjectInserter odi = repository.newObjectInserter(); try { // Create the in-memory index of the reflog log entry DirCache index = createIndex(repository, headId, commands); ObjectId indexTreeId = index.writeTree(odi); PersonIdent ident; if (UserModel.ANONYMOUS.equals(user)) { // anonymous push ident = new PersonIdent(user.username + "/" + user.username, user.username); } else { // construct real pushing account ident = new PersonIdent(MessageFormat.format("{0}/{1}", user.getDisplayName(), user.username), user.emailAddress == null ? user.username : user.emailAddress); } // Create a commit object CommitBuilder commit = new CommitBuilder(); commit.setAuthor(ident); commit.setCommitter(ident); commit.setEncoding(Constants.ENCODING); commit.setMessage(message); commit.setParentId(headId); commit.setTreeId(indexTreeId); // Insert the commit into the repository ObjectId commitId = odi.insert(commit); odi.flush(); RevWalk revWalk = new RevWalk(repository); try { RevCommit revCommit = revWalk.parseCommit(commitId); RefUpdate ru = repository.updateRef(GB_REFLOG); ru.setNewObjectId(commitId); ru.setExpectedOldObjectId(headId); ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false); Result rc = ru.forceUpdate(); switch (rc) { case NEW: case FORCED: case FAST_FORWARD: success = true; break; case REJECTED: case LOCK_FAILURE: throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc); default: throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, GB_REFLOG, commitId.toString(), rc)); } } finally { revWalk.close(); } } finally { odi.close(); } } catch (Throwable t) { error(t, repository, "Failed to commit reflog entry to {0}"); } return success; }
From source file:com.gitblit.wicket.pages.NewRepositoryPage.java
License:Apache License
/** * Prepare the initial commit for the repository. * * @param repository// w w w .j a v a 2s. co m * @param addReadme * @param gitignore * @param addGitFlow * @return true if an initial commit was created */ protected boolean initialCommit(RepositoryModel repository, boolean addReadme, String gitignore, boolean addGitFlow) { boolean initialCommit = addReadme || !StringUtils.isEmpty(gitignore) || addGitFlow; if (!initialCommit) { return false; } // build an initial commit boolean success = false; Repository db = app().repositories().getRepository(repositoryModel.name); ObjectInserter odi = db.newObjectInserter(); try { UserModel user = GitBlitWebSession.get().getUser(); String email = Optional.fromNullable(user.emailAddress).or(user.username + "@" + "gitblit"); PersonIdent author = new PersonIdent(user.getDisplayName(), email); DirCache newIndex = DirCache.newInCore(); DirCacheBuilder indexBuilder = newIndex.builder(); if (addReadme) { // insert a README String title = StringUtils.stripDotGit(StringUtils.getLastPathElement(repositoryModel.name)); String description = repositoryModel.description == null ? "" : repositoryModel.description; String readme = String.format("## %s\n\n%s\n\n", title, description); byte[] bytes = readme.getBytes(Constants.ENCODING); DirCacheEntry entry = new DirCacheEntry("README.md"); entry.setLength(bytes.length); entry.setLastModified(System.currentTimeMillis()); entry.setFileMode(FileMode.REGULAR_FILE); entry.setObjectId(odi.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, bytes)); indexBuilder.add(entry); } if (!StringUtils.isEmpty(gitignore)) { // insert a .gitignore file File dir = app().runtime().getFileOrFolder(Keys.git.gitignoreFolder, "${baseFolder}/gitignore"); File file = new File(dir, gitignore + ".gitignore"); if (file.exists() && file.length() > 0) { byte[] bytes = FileUtils.readContent(file); if (!ArrayUtils.isEmpty(bytes)) { DirCacheEntry entry = new DirCacheEntry(".gitignore"); entry.setLength(bytes.length); entry.setLastModified(System.currentTimeMillis()); entry.setFileMode(FileMode.REGULAR_FILE); entry.setObjectId(odi.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, bytes)); indexBuilder.add(entry); } } } if (addGitFlow) { // insert a .gitflow file Config config = new Config(); config.setString("gitflow", null, "masterBranch", Constants.MASTER); config.setString("gitflow", null, "developBranch", Constants.DEVELOP); config.setString("gitflow", null, "featureBranchPrefix", "feature/"); config.setString("gitflow", null, "releaseBranchPrefix", "release/"); config.setString("gitflow", null, "hotfixBranchPrefix", "hotfix/"); config.setString("gitflow", null, "supportBranchPrefix", "support/"); config.setString("gitflow", null, "versionTagPrefix", ""); byte[] bytes = config.toText().getBytes(Constants.ENCODING); DirCacheEntry entry = new DirCacheEntry(".gitflow"); entry.setLength(bytes.length); entry.setLastModified(System.currentTimeMillis()); entry.setFileMode(FileMode.REGULAR_FILE); entry.setObjectId(odi.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, bytes)); indexBuilder.add(entry); } indexBuilder.finish(); if (newIndex.getEntryCount() == 0) { // nothing to commit return false; } ObjectId treeId = newIndex.writeTree(odi); // Create a commit object CommitBuilder commit = new CommitBuilder(); commit.setAuthor(author); commit.setCommitter(author); commit.setEncoding(Constants.ENCODING); commit.setMessage("Initial commit"); commit.setTreeId(treeId); // Insert the commit into the repository ObjectId commitId = odi.insert(commit); odi.flush(); // set the branch refs RevWalk revWalk = new RevWalk(db); try { // set the master branch RevCommit revCommit = revWalk.parseCommit(commitId); RefUpdate masterRef = db.updateRef(Constants.R_MASTER); masterRef.setNewObjectId(commitId); masterRef.setRefLogMessage("commit: " + revCommit.getShortMessage(), false); Result masterRC = masterRef.update(); switch (masterRC) { case NEW: success = true; break; default: success = false; } if (addGitFlow) { // set the develop branch for git-flow RefUpdate developRef = db.updateRef(Constants.R_DEVELOP); developRef.setNewObjectId(commitId); developRef.setRefLogMessage("commit: " + revCommit.getShortMessage(), false); Result developRC = developRef.update(); switch (developRC) { case NEW: success = true; break; default: success = false; } } } finally { revWalk.close(); } } catch (UnsupportedEncodingException e) { logger().error(null, e); } catch (IOException e) { logger().error(null, e); } finally { odi.close(); db.close(); } return success; }
From source file:com.google.appraise.eclipse.core.client.git.JgitUtils.java
License:Open Source License
/** * Updates the given ref to the new commit. *///w ww .jav a2 s .c o m public static RefUpdate updateRef(Repository repo, ObjectId newObjectId, ObjectId expectedOldObjectId, String refName) throws IOException { RefUpdate refUpdate = repo.updateRef(refName); refUpdate.setNewObjectId(newObjectId); if (expectedOldObjectId == null) { refUpdate.setExpectedOldObjectId(ObjectId.zeroId()); } else { refUpdate.setExpectedOldObjectId(expectedOldObjectId); } return refUpdate; }
From source file:com.google.gerrit.httpd.rpc.project.AddBranch.java
License:Apache License
@Override public ListBranchesResult call() throws NoSuchProjectException, InvalidNameException, InvalidRevisionException, IOException, BranchCreationNotAllowedException { final ProjectControl projectControl = projectControlFactory.controlFor(projectName); String refname = branchName;// w w w . java2 s. co m while (refname.startsWith("/")) { refname = refname.substring(1); } if (!refname.startsWith(Constants.R_REFS)) { refname = Constants.R_HEADS + refname; } if (!Repository.isValidRefName(refname)) { throw new InvalidNameException(); } if (refname.startsWith(ReceiveCommits.NEW_CHANGE)) { throw new BranchCreationNotAllowedException(ReceiveCommits.NEW_CHANGE); } final Branch.NameKey name = new Branch.NameKey(projectName, refname); final RefControl refControl = projectControl.controlForRef(name); final Repository repo = repoManager.openRepository(projectName); try { final ObjectId revid = parseStartingRevision(repo); final RevWalk rw = verifyConnected(repo, revid); RevObject object = rw.parseAny(revid); if (refname.startsWith(Constants.R_HEADS)) { // Ensure that what we start the branch from is a commit. If we // were given a tag, deference to the commit instead. // try { object = rw.parseCommit(object); } catch (IncorrectObjectTypeException notCommit) { throw new IllegalStateException(startingRevision + " not a commit"); } } if (!refControl.canCreate(rw, object)) { throw new IllegalStateException("Cannot create " + refname); } try { final RefUpdate u = repo.updateRef(refname); u.setExpectedOldObjectId(ObjectId.zeroId()); u.setNewObjectId(object.copy()); u.setRefLogIdent(identifiedUser.newRefLogIdent()); u.setRefLogMessage("created via web from " + startingRevision, false); final RefUpdate.Result result = u.update(rw); switch (result) { case FAST_FORWARD: case NEW: case NO_CHANGE: replication.scheduleUpdate(name.getParentKey(), refname); hooks.doRefUpdatedHook(name, u, identifiedUser.getAccount()); break; default: { throw new IOException(result.name()); } } } catch (IOException err) { log.error("Cannot create branch " + name, err); throw err; } } finally { repo.close(); } return listBranchesFactory.create(projectName).call(); }
From source file:com.google.gerrit.httpd.rpc.project.DeleteBranches.java
License:Apache License
@Override public Set<Branch.NameKey> call() throws NoSuchProjectException, RepositoryNotFoundException { final ProjectControl projectControl = projectControlFactory.controlFor(projectName); for (Branch.NameKey k : toRemove) { if (!projectName.equals(k.getParentKey())) { throw new IllegalArgumentException("All keys must be from same project"); }//from ww w . j av a 2 s. com if (!projectControl.controlForRef(k).canDelete()) { throw new IllegalStateException("Cannot delete " + k.getShortName()); } } final Set<Branch.NameKey> deleted = new HashSet<Branch.NameKey>(); final Repository r = repoManager.openRepository(projectName); try { for (final Branch.NameKey branchKey : toRemove) { final String refname = branchKey.get(); final RefUpdate.Result result; final RefUpdate u; try { u = r.updateRef(refname); u.setForceUpdate(true); result = u.delete(); } catch (IOException e) { log.error("Cannot delete " + branchKey, e); continue; } switch (result) { case NEW: case NO_CHANGE: case FAST_FORWARD: case FORCED: deleted.add(branchKey); replication.scheduleUpdate(projectName, refname); hooks.doRefUpdatedHook(branchKey, u, identifiedUser.getAccount()); break; case REJECTED_CURRENT_BRANCH: log.warn("Cannot delete " + branchKey + ": " + result.name()); break; default: log.error("Cannot delete " + branchKey + ": " + result.name()); break; } } } finally { r.close(); } return deleted; }
From source file:com.google.gerrit.pgm.init.AllProjectsConfig.java
License:Apache License
private void updateRef(Repository repo, PersonIdent ident, ObjectId newRevision, String refLogMsg) throws IOException { RefUpdate ru = repo.updateRef(getRefName()); ru.setRefLogIdent(ident);/*from ww w . j a va 2s. c o m*/ ru.setNewObjectId(newRevision); ru.setExpectedOldObjectId(revision); ru.setRefLogMessage(refLogMsg, false); RefUpdate.Result r = ru.update(); switch (r) { case FAST_FORWARD: case NEW: case NO_CHANGE: break; default: throw new IOException("Failed to update " + getRefName() + " of " + project + ": " + r.name()); } }
From source file:com.google.gerrit.pgm.init.api.VersionedMetaDataOnInit.java
License:Apache License
private void updateRef(Repository repo, PersonIdent ident, ObjectId newRevision, String refLogMsg) throws IOException { RefUpdate ru = repo.updateRef(getRefName()); ru.setRefLogIdent(ident);// ww w . j a v a2 s. c o m ru.setNewObjectId(newRevision); ru.setExpectedOldObjectId(revision); ru.setRefLogMessage(refLogMsg, false); RefUpdate.Result r = ru.update(); switch (r) { case FAST_FORWARD: case NEW: case NO_CHANGE: break; case FORCED: case IO_FAILURE: case LOCK_FAILURE: case NOT_ATTEMPTED: case REJECTED: case REJECTED_CURRENT_BRANCH: case RENAMED: default: throw new IOException("Failed to update " + getRefName() + " of " + project + ": " + r.name()); } }
From source file:com.google.gerrit.server.account.AccountsUpdate.java
License:Apache License
public static void createUserBranch(Repository repo, ObjectInserter oi, PersonIdent committerIdent, PersonIdent authorIdent, Account account) throws IOException { ObjectId id = createInitialEmptyCommit(oi, committerIdent, authorIdent, account.getRegisteredOn()); String refName = RefNames.refsUsers(account.getId()); RefUpdate ru = repo.updateRef(refName); ru.setExpectedOldObjectId(ObjectId.zeroId()); ru.setNewObjectId(id);/*ww w . j a v a 2 s . c o m*/ ru.setForceUpdate(true); ru.setRefLogIdent(committerIdent); ru.setRefLogMessage("Create Account", true); Result result = ru.update(); if (result != Result.NEW) { throw new IOException(String.format("Failed to update ref %s: %s", refName, result.name())); } }
From source file:com.google.gerrit.server.account.AccountsUpdate.java
License:Apache License
public static void deleteUserBranch(Repository repo, PersonIdent refLogIdent, Account.Id accountId) throws IOException { String refName = RefNames.refsUsers(accountId); Ref ref = repo.exactRef(refName); if (ref == null) { return;//from ww w . ja va2 s.co m } RefUpdate ru = repo.updateRef(refName); ru.setExpectedOldObjectId(ref.getObjectId()); ru.setNewObjectId(ObjectId.zeroId()); ru.setForceUpdate(true); ru.setRefLogIdent(refLogIdent); ru.setRefLogMessage("Delete Account", true); Result result = ru.delete(); if (result != Result.FORCED) { throw new IOException(String.format("Failed to delete ref %s: %s", refName, result.name())); } }
From source file:com.google.gerrit.server.account.externalids.ExternalIdsUpdate.java
License:Apache License
/** Commits updates to the external IDs. */ public static ObjectId commit(Repository repo, RevWalk rw, ObjectInserter ins, ObjectId rev, NoteMap noteMap, String commitMessage, PersonIdent committerIdent, PersonIdent authorIdent) throws IOException { CommitBuilder cb = new CommitBuilder(); cb.setMessage(commitMessage);/*ww w . ja v a2s .c o m*/ cb.setTreeId(noteMap.writeTree(ins)); cb.setAuthor(authorIdent); cb.setCommitter(committerIdent); if (!rev.equals(ObjectId.zeroId())) { cb.setParentId(rev); } else { cb.setParentIds(); // Ref is currently nonexistent, commit has no parents. } if (cb.getTreeId() == null) { if (rev.equals(ObjectId.zeroId())) { cb.setTreeId(emptyTree(ins)); // No parent, assume empty tree. } else { RevCommit p = rw.parseCommit(rev); cb.setTreeId(p.getTree()); // Copy tree from parent. } } ObjectId commitId = ins.insert(cb); ins.flush(); RefUpdate u = repo.updateRef(RefNames.REFS_EXTERNAL_IDS); u.setRefLogIdent(committerIdent); u.setRefLogMessage("Update external IDs", false); u.setExpectedOldObjectId(rev); u.setNewObjectId(commitId); RefUpdate.Result res = u.update(); switch (res) { case NEW: case FAST_FORWARD: case NO_CHANGE: case RENAMED: case FORCED: break; case LOCK_FAILURE: throw new LockFailureException("Updating external IDs failed with " + res); case IO_FAILURE: case NOT_ATTEMPTED: case REJECTED: case REJECTED_CURRENT_BRANCH: default: throw new IOException("Updating external IDs failed with " + res); } return rw.parseCommit(commitId); }