org.eclipse.jgit.lib.RefUpdate Java Examples

The following examples show how to use org.eclipse.jgit.lib.RefUpdate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GitRepositoryTest.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
private static void testDoUpdateRef(String ref, ObjectId commitId, boolean tagExists) throws Exception {
    final org.eclipse.jgit.lib.Repository jGitRepo = mock(org.eclipse.jgit.lib.Repository.class);
    final RevWalk revWalk = mock(RevWalk.class);
    final RefUpdate refUpdate = mock(RefUpdate.class);

    lenient().when(jGitRepo.exactRef(ref)).thenReturn(tagExists ? mock(Ref.class) : null);
    lenient().when(jGitRepo.updateRef(ref)).thenReturn(refUpdate);

    lenient().when(refUpdate.update(revWalk)).thenReturn(RefUpdate.Result.NEW);
    GitRepository.doRefUpdate(jGitRepo, revWalk, ref, commitId);

    when(refUpdate.update(revWalk)).thenReturn(RefUpdate.Result.FAST_FORWARD);
    GitRepository.doRefUpdate(jGitRepo, revWalk, ref, commitId);

    when(refUpdate.update(revWalk)).thenReturn(RefUpdate.Result.LOCK_FAILURE);
    assertThatThrownBy(() -> GitRepository.doRefUpdate(jGitRepo, revWalk, ref, commitId))
            .isInstanceOf(StorageException.class);
}
 
Example #2
Source File: GitUtils.java    From onedev with MIT License 6 votes vote down vote up
public static void deleteRef(RefUpdate refUpdate) {
	try {
		refUpdate.setForceUpdate(true);
		RefUpdate.Result result = refUpdate.delete();
        if (result == RefUpdate.Result.LOCK_FAILURE
        		&& refUpdate.getExpectedOldObjectId() != null
        		&& !refUpdate.getExpectedOldObjectId().equals(refUpdate.getOldObjectId())) {
        	throw new ObsoleteCommitException(refUpdate.getOldObjectId());
        } else if (result != RefUpdate.Result.FAST_FORWARD && result != RefUpdate.Result.FORCED
        		&& result != RefUpdate.Result.NEW && result != RefUpdate.Result.NO_CHANGE) {
        	throw new RefUpdateException(result);
        } 
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #3
Source File: GitRepository.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static void doRefUpdate(org.eclipse.jgit.lib.Repository jGitRepository, RevWalk revWalk,
                        String ref, ObjectId commitId) throws IOException {

    if (ref.startsWith(Constants.R_TAGS)) {
        final Ref oldRef = jGitRepository.exactRef(ref);
        if (oldRef != null) {
            throw new StorageException("tag ref exists already: " + ref);
        }
    }

    final RefUpdate refUpdate = jGitRepository.updateRef(ref);
    refUpdate.setNewObjectId(commitId);

    final Result res = refUpdate.update(revWalk);
    switch (res) {
        case NEW:
        case FAST_FORWARD:
            // Expected
            break;
        default:
            throw new StorageException("unexpected refUpdate state: " + res);
    }
}
 
Example #4
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public void prune(RemoteConfig repository) throws GitException {
    try (Repository gitRepo = getRepository()) {
        String remote = repository.getName();
        String prefix = "refs/remotes/" + remote + "/";

        Set<String> branches = listRemoteBranches(remote);

        for (Ref r : new ArrayList<>(gitRepo.getAllRefs().values())) {
            if (r.getName().startsWith(prefix) && !branches.contains(r.getName())) {
                // delete this ref
                RefUpdate update = gitRepo.updateRef(r.getName());
                update.setRefLogMessage("remote branch pruned", false);
                update.setForceUpdate(true);
                update.delete();
            }
        }
    } catch (URISyntaxException | IOException e) {
        throw new GitException(e);
    }
}
 
Example #5
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
   @Override
   public void deleteRef(String refName) throws GitException, InterruptedException {
refName = refName.replace(' ', '_');
try (Repository repo = getRepository()) {
    RefUpdate refUpdate = repo.updateRef(refName);
    // Required, even though this is a forced delete.
    refUpdate.setNewObjectId(repo.exactRef(Constants.HEAD).getObjectId());
    refUpdate.setForceUpdate(true);
    switch (refUpdate.delete()) {
    case NOT_ATTEMPTED:
    case LOCK_FAILURE:
    case REJECTED:
    case REJECTED_CURRENT_BRANCH:
    case IO_FAILURE:
    case RENAMED:
	throw new GitException("Could not delete " + refName);
    }
} catch (IOException e) {
    throw new GitException("Could not delete " + refName, e);
}
   }
 
Example #6
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
   @Override
   public void ref(String refName) throws GitException, InterruptedException {
refName = refName.replace(' ', '_');
try (Repository repo = getRepository()) {
    RefUpdate refUpdate = repo.updateRef(refName);
    refUpdate.setNewObjectId(repo.exactRef(Constants.HEAD).getObjectId());
    switch (refUpdate.forceUpdate()) {
    case NOT_ATTEMPTED:
    case LOCK_FAILURE:
    case REJECTED:
    case REJECTED_CURRENT_BRANCH:
    case IO_FAILURE:
    case RENAMED:
	throw new GitException("Could not update " + refName + " to HEAD");
    }
} catch (IOException e) {
    throw new GitException("Could not update " + refName + " to HEAD", e);
}
   }
 
Example #7
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
private void doCheckoutWithResetAndRetryAndCleanBranch(String branch, String ref) throws GitException {
    try (Repository repo = getRepository()) {
        RefUpdate refUpdate = repo.updateRef(R_HEADS + branch);
        refUpdate.setNewObjectId(repo.resolve(ref));
        switch (refUpdate.forceUpdate()) {
        case NOT_ATTEMPTED:
        case LOCK_FAILURE:
        case REJECTED:
        case REJECTED_CURRENT_BRANCH:
        case IO_FAILURE:
        case RENAMED:
            throw new GitException("Could not update " + branch + " to " + ref);
        }

        doCheckoutWithResetAndRetry(branch);
    } catch (IOException e) {
        throw new GitException("Could not checkout " + branch +  " with start point " + ref, e);
    }
}
 
Example #8
Source File: GitPushEmbedded.java    From git-as-svn with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean push(@NotNull Repository repository, @NotNull ObjectId ReceiveId, @NotNull String branch, @NotNull User userInfo) throws SVNException, IOException {
  final RefUpdate refUpdate = repository.updateRef(branch);
  refUpdate.getOldObjectId();
  refUpdate.setNewObjectId(ReceiveId);
  runReceiveHook(repository, refUpdate, SVNErrorCode.REPOS_HOOK_FAILURE, "pre-receive", userInfo);
  runUpdateHook(repository, refUpdate, "update", userInfo);
  final RefUpdate.Result result = refUpdate.update();
  switch (result) {
    case REJECTED:
    case LOCK_FAILURE:
      return false;
    case NEW:
    case FAST_FORWARD:
      runReceiveHook(repository, refUpdate, SVNErrorCode.REPOS_POST_COMMIT_HOOK_FAILED, "post-receive", userInfo);
      return true;
    default:
      log.error("Unexpected push error: {}", result);
      throw new SVNException(SVNErrorMessage.create(SVNErrorCode.IO_WRITE_ERROR, result.name()));
  }
}
 
Example #9
Source File: DeleteTagCommand.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    Ref currentRef = repository.getTags().get(tagName);
    if (currentRef == null) {
        throw new GitException.MissingObjectException(tagName, GitObjectType.TAG);
    }
    String fullName = currentRef.getName();
    try {
        RefUpdate update = repository.updateRef(fullName);
        update.setRefLogMessage("tag deleted", false);
        update.setForceUpdate(true);
        Result deleteResult = update.delete();

        switch (deleteResult) {
            case IO_FAILURE:
            case LOCK_FAILURE:
            case REJECTED:
                throw new GitException.RefUpdateException("Cannot delete tag " + tagName, GitRefUpdateResult.valueOf(deleteResult.name()));
        }
    } catch (IOException ex) {
        throw new GitException(ex);
    }
    
}
 
Example #10
Source File: GitPushEmbedded.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
private void runUpdateHook(@NotNull Repository repository, @NotNull RefUpdate refUpdate, @NotNull String hook, @NotNull User userInfo) throws SVNException {
  runHook(repository, SVNErrorCode.REPOS_HOOK_FAILURE, hook, userInfo, processBuilder -> {
    processBuilder.command().addAll(Arrays.asList(
        refUpdate.getName(),
        getObjectId(refUpdate.getOldObjectId()),
        getObjectId(refUpdate.getNewObjectId())
    ));
    return processBuilder.start();
  });
}
 
Example #11
Source File: RefUpdateValidator.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
public static void validate(RefUpdate.Result result) {
  switch(result) {
    case REJECTED_CURRENT_BRANCH:
      throw new RefUpdateRejectedCurrentBranchException(result.name());
    case REJECTED:
      throw new RefUpdateRejectedException(result.name());
    case LOCK_FAILURE:
      throw new RefUpdateLockFailureException(result.name());
    case IO_FAILURE:
      throw new RefUpdateIOFailureException(result.name());
  }
}
 
Example #12
Source File: JgitUtils.java    From git-appraise-eclipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Updates the given ref to the new commit.
 */
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;
}
 
Example #13
Source File: GitNoteWriter.java    From git-appraise-eclipse with Eclipse Public License 1.0 5 votes vote down vote up
private void updateRef() throws IOException, InterruptedException, RuntimeException,
                                MissingObjectException, IncorrectObjectTypeException,
                                CorruptObjectException {
  if (baseCommit != null && oursCommit.getTree().equals(baseCommit.getTree())) {
    // If the trees are identical, there is no change in the notes.
    // Avoid saving this commit as it has no new information.
    return;
  }

  int remainingLockFailureCalls = JgitUtils.MAX_LOCK_FAILURE_CALLS;
  RefUpdate refUpdate = JgitUtils.updateRef(repo, oursCommit, baseCommit, ref);

  for (;;) {
    Result result = refUpdate.update();

    if (result == Result.LOCK_FAILURE) {
      if (--remainingLockFailureCalls > 0) {
        Thread.sleep(JgitUtils.SLEEP_ON_LOCK_FAILURE_MS);
      } else {
        throw new RuntimeException("Failed to lock the ref: " + ref);
      }

    } else if (result == Result.REJECTED) {
      RevCommit theirsCommit = revWalk.parseCommit(refUpdate.getOldObjectId());
      NoteMap theirs = NoteMap.read(revWalk.getObjectReader(), theirsCommit);
      NoteMapMerger merger = new NoteMapMerger(repo);
      NoteMap merged = merger.merge(base, ours, theirs);
      RevCommit mergeCommit =
          createCommit(merged, author, "Merged note records\n", theirsCommit, oursCommit);
      refUpdate = JgitUtils.updateRef(repo, mergeCommit, theirsCommit, ref);
      remainingLockFailureCalls = JgitUtils.MAX_LOCK_FAILURE_CALLS;

    } else if (result == Result.IO_FAILURE) {
      throw new RuntimeException("Couldn't create notes because of IO_FAILURE");
    } else {
      break;
    }
  }
}
 
Example #14
Source File: RefUpdateValidator.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
public static void validate(RefUpdate.Result result) {
  switch(result) {
    case REJECTED_CURRENT_BRANCH:
      throw new RefUpdateRejectedCurrentBranchException(result.name());
    case REJECTED:
      throw new RefUpdateRejectedException(result.name());
    case LOCK_FAILURE:
      throw new RefUpdateLockFailureException(result.name());
    case IO_FAILURE:
      throw new RefUpdateIOFailureException(result.name());
  }
}
 
Example #15
Source File: GitPushEmbedded.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
private void runReceiveHook(@NotNull Repository repository, @NotNull RefUpdate refUpdate, @NotNull SVNErrorCode svnErrorCode, @NotNull String hook, @NotNull User userInfo) throws SVNException {
  runHook(repository, svnErrorCode, hook, userInfo, processBuilder -> {
    final Process process = processBuilder.start();
    try (Writer stdin = new OutputStreamWriter(process.getOutputStream(), StandardCharsets.UTF_8)) {
      stdin.write(getObjectId(refUpdate.getOldObjectId()));
      stdin.write(' ');
      stdin.write(getObjectId(refUpdate.getNewObjectId()));
      stdin.write(' ');
      stdin.write(refUpdate.getName());
      stdin.write('\n');
    }
    return process;
  });
}
 
Example #16
Source File: RepoMerger.java    From git-merge-repos with Apache License 2.0 5 votes vote down vote up
private MergedRef mergeBranch(String branch) throws IOException {

		Map<SubtreeConfig, ObjectId> resolvedRefs = resolveRefs(
				"refs/heads/original/", branch);

		Map<SubtreeConfig, RevCommit> parentCommits = new LinkedHashMap<>();
		try (RevWalk revWalk = new RevWalk(repository)) {
			for (SubtreeConfig config : subtreeConfigs) {
				ObjectId objectId = resolvedRefs.get(config);
				if (objectId != null) {
					RevCommit commit = revWalk.parseCommit(objectId);
					parentCommits.put(config, commit);
				}
			}
		}

		MergedRef mergedRef = getMergedRef("branch", branch, parentCommits.keySet());

		ObjectId mergeCommit = new SubtreeMerger(repository).createMergeCommit(parentCommits,
				mergedRef.getMessage());

		RefUpdate refUpdate = repository.updateRef("refs/heads/" + branch);
		refUpdate.setNewObjectId(mergeCommit);
		refUpdate.update();

		return mergedRef;
	}
 
Example #17
Source File: GitTaskUtils.java    From ant-git-tasks with Apache License 2.0 5 votes vote down vote up
/**
 * Check references updates for any errors
 *
 * @param errorPrefix The error prefix for any error message
 * @param refUpdates A collection of tracking references updates
 */
public static void validateTrackingRefUpdates(String errorPrefix, Collection<TrackingRefUpdate> refUpdates) {
        for (TrackingRefUpdate refUpdate : refUpdates) {
                RefUpdate.Result result = refUpdate.getResult();

                if (result == RefUpdate.Result.IO_FAILURE ||
                    result == RefUpdate.Result.LOCK_FAILURE ||
                    result == RefUpdate.Result.REJECTED ||
                    result == RefUpdate.Result.REJECTED_CURRENT_BRANCH ) {
                        throw new BuildException(String.format("%s - Status '%s'", errorPrefix, result.name()));
                }
        }
}
 
Example #18
Source File: RepoMerger.java    From git-merge-repos with Apache License 2.0 5 votes vote down vote up
private void deleteOriginalRefs() throws IOException {
	try (RevWalk revWalk = new RevWalk(repository)) {
		Collection<Ref> refs = new ArrayList<>();
		RefDatabase refDatabase = repository.getRefDatabase();
		Map<String, Ref> originalBranches = refDatabase.getRefs("refs/heads/original/");
		Map<String, Ref> originalTags = refDatabase.getRefs("refs/tags/original/");
		refs.addAll(originalBranches.values());
		refs.addAll(originalTags.values());
		for (Ref originalRef : refs) {
			RefUpdate refUpdate = repository.updateRef(originalRef.getName());
			refUpdate.setForceUpdate(true);
			refUpdate.delete(revWalk);
		}
	}
}
 
Example #19
Source File: GitUtils.java    From onedev with MIT License 5 votes vote down vote up
public static RefUpdate getRefUpdate(Repository repository, String refName) {
	try {
		return repository.updateRef(refName);
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #20
Source File: GitTransportUpdate.java    From netbeans with Apache License 2.0 5 votes vote down vote up
GitTransportUpdate (URIish uri, TrackingRefUpdate update) {
    this.localName = stripRefs(update.getLocalName());
    this.remoteName = stripRefs(update.getRemoteName());
    this.oldObjectId = update.getOldObjectId() == null || ObjectId.zeroId().equals(update.getOldObjectId()) ? null : update.getOldObjectId().getName();
    this.newObjectId = update.getNewObjectId() == null || ObjectId.zeroId().equals(update.getNewObjectId()) ? null : update.getNewObjectId().getName();
    this.result = GitRefUpdateResult.valueOf((update.getResult() == null 
            ? RefUpdate.Result.NOT_ATTEMPTED 
            : update.getResult()).name());
    this.uri = uri.toString();
    this.type = getType(update.getLocalName());
}
 
Example #21
Source File: AbstractGitTest.java    From onedev with MIT License 5 votes vote down vote up
protected void updateRef(String refName, String newValue, @Nullable String oldValue) {
	try {
		RefUpdate update = git.getRepository().updateRef(refName);
		update.setNewObjectId(git.getRepository().resolve(newValue));
		if (oldValue != null)
			update.setExpectedOldObjectId(git.getRepository().resolve(oldValue));
		update.setRefLogIdent(user);
		update.setRefLogMessage("update ref", false);
		GitUtils.updateRef(update);
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #22
Source File: MergePreview.java    From onedev with MIT License 5 votes vote down vote up
public void syncRef(PullRequest request) {
	Project project = request.getTargetProject();
	ObjectId mergedId = getMergeCommitHash()!=null? ObjectId.fromString(getMergeCommitHash()): null;
	RefUpdate refUpdate = GitUtils.getRefUpdate(project.getRepository(), request.getMergeRef());
	if (mergedId != null && !mergedId.equals((project.getObjectId(request.getMergeRef(), false)))) {
		refUpdate.setNewObjectId(mergedId);
		GitUtils.updateRef(refUpdate);
	} else if (mergeCommitHash == null && project.getObjectId(request.getMergeRef(), false) != null) {
		GitUtils.deleteRef(refUpdate);
	}		
}
 
Example #23
Source File: GitUtils.java    From onedev with MIT License 5 votes vote down vote up
public static void linkRef(RefUpdate refUpdate, String target) {
	try {
		RefUpdate.Result result = refUpdate.link(target);
		if (result != RefUpdate.Result.FORCED && result != RefUpdate.Result.NEW && result != RefUpdate.Result.NO_CHANGE)
			throw new RefUpdateException(result);
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #24
Source File: GitUtils.java    From onedev with MIT License 5 votes vote down vote up
public static void updateRef(RefUpdate refUpdate) {
	try {
		RefUpdate.Result result = refUpdate.forceUpdate();
        if (result == RefUpdate.Result.LOCK_FAILURE 
        		&& refUpdate.getExpectedOldObjectId() != null 
        		&& !refUpdate.getExpectedOldObjectId().equals(refUpdate.getOldObjectId())) {
        	throw new ObsoleteCommitException(refUpdate.getOldObjectId());
        } else if (result != RefUpdate.Result.FAST_FORWARD && result != RefUpdate.Result.FORCED
        		&& result != RefUpdate.Result.NEW && result != RefUpdate.Result.NO_CHANGE) {
        	throw new RefUpdateException(result);
        } 
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #25
Source File: GitBareRepoReadSaveRequest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Override
void save() throws IOException {
    invokeOnScm(new GitSCMFileSystem.FSFunction<Void>() {
        @Override
        public Void invoke(Repository repo) throws IOException, InterruptedException {
            String localBranchRef = LOCAL_REF_BASE + sourceBranch;

            ObjectId branchHead = repo.resolve(localBranchRef);

            try {
                // Get committer info
                User user = User.current();
                if (user == null) {
                    throw new ServiceException.UnauthorizedException("Not authenticated");
                }
                String mailAddress = MailAddressResolver.resolve(user);

                if(mailAddress == null) {
                    mailAddress = user.getId() + "@email-address-not-set";
                }

                StandardCredentials credential = getCredential();

                // Make sure up-to-date and credentials work
                GitUtils.fetch(repo, credential);

                GitUtils.commit(repo, localBranchRef, filePath, contents, user.getId(), mailAddress, commitMessage, TimeZone.getDefault(), new Date());

                GitUtils.push(gitSource.getRemote(), repo, credential, localBranchRef, REMOTE_REF_BASE + branch);
                return null;
            } finally {
                // always roll back to undo our local changes
                try {
                    if (branchHead != null) { // branchHead may be null if this was an empty repo
                        RefUpdate rollback = repo.updateRef(localBranchRef);
                        rollback.setNewObjectId(branchHead);
                        rollback.forceUpdate();
                    }
                } catch(Exception ex) {
                    log.log(Level.SEVERE, "Unable to roll back repo after save failure", ex);
                }
            }
        }
    });
}
 
Example #26
Source File: GitRepository.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new Git-backed repository.
 *
 * @param repoDir the location of this repository
 * @param format the repository format
 * @param repositoryWorker the {@link Executor} which will perform the blocking repository operations
 * @param creationTimeMillis the creation time
 * @param author the user who initiated the creation of this repository
 *
 * @throws StorageException if failed to create a new repository
 */
GitRepository(Project parent, File repoDir, GitRepositoryFormat format, Executor repositoryWorker,
              long creationTimeMillis, Author author, @Nullable RepositoryCache cache) {

    this.parent = requireNonNull(parent, "parent");
    name = requireNonNull(repoDir, "repoDir").getName();
    this.repositoryWorker = requireNonNull(repositoryWorker, "repositoryWorker");
    this.format = requireNonNull(format, "format");
    this.cache = cache;

    requireNonNull(author, "author");

    final RepositoryBuilder repositoryBuilder = new RepositoryBuilder().setGitDir(repoDir).setBare();
    boolean success = false;
    try {
        // Create an empty repository with format version 0 first.
        try (org.eclipse.jgit.lib.Repository initRepo = repositoryBuilder.build()) {
            if (exist(repoDir)) {
                throw new StorageException(
                        "failed to create a repository at: " + repoDir + " (exists already)");
            }

            initRepo.create(true);

            final StoredConfig config = initRepo.getConfig();
            if (format == GitRepositoryFormat.V1) {
                // Update the repository settings to upgrade to format version 1 and reftree.
                config.setInt(CONFIG_CORE_SECTION, null, CONFIG_KEY_REPO_FORMAT_VERSION, 1);
            }

            // Disable hidden files, symlinks and file modes we do not use.
            config.setEnum(CONFIG_CORE_SECTION, null, CONFIG_KEY_HIDEDOTFILES, HideDotFiles.FALSE);
            config.setBoolean(CONFIG_CORE_SECTION, null, CONFIG_KEY_SYMLINKS, false);
            config.setBoolean(CONFIG_CORE_SECTION, null, CONFIG_KEY_FILEMODE, false);

            // Disable GPG signing.
            config.setBoolean(CONFIG_COMMIT_SECTION, null, CONFIG_KEY_GPGSIGN, false);

            // Set the diff algorithm.
            config.setString(CONFIG_DIFF_SECTION, null, CONFIG_KEY_ALGORITHM, "histogram");

            // Disable rename detection which we do not use.
            config.setBoolean(CONFIG_DIFF_SECTION, null, CONFIG_KEY_RENAMES, false);

            config.save();
        }

        // Re-open the repository with the updated settings and format version.
        jGitRepository = new RepositoryBuilder().setGitDir(repoDir).build();

        // Initialize the master branch.
        final RefUpdate head = jGitRepository.updateRef(Constants.HEAD);
        head.disableRefLog();
        head.link(Constants.R_HEADS + Constants.MASTER);

        // Initialize the commit ID database.
        commitIdDatabase = new CommitIdDatabase(jGitRepository);

        // Insert the initial commit into the master branch.
        commit0(null, Revision.INIT, creationTimeMillis, author,
                "Create a new repository", "", Markup.PLAINTEXT,
                Collections.emptyList(), true);

        headRevision = Revision.INIT;
        success = true;
    } catch (IOException e) {
        throw new StorageException("failed to create a repository at: " + repoDir, e);
    } finally {
        if (!success) {
            internalClose();
            // Failed to create a repository. Remove any cruft so that it is not loaded on the next run.
            deleteCruft(repoDir);
        }
    }
}
 
Example #27
Source File: GitEnumsStateTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testUpdateResult () {
    for (RefUpdate.Result result : RefUpdate.Result.values()) {
        assertNotNull(GitRefUpdateResult.valueOf(result.name()));
    }
}
 
Example #28
Source File: PullRequest.java    From onedev with MIT License 4 votes vote down vote up
public void writeMergeRef() {
	RefUpdate refUpdate = GitUtils.getRefUpdate(getTargetProject().getRepository(), getMergeRef());
	refUpdate.setNewObjectId(ObjectId.fromString(getLastMergePreview().getMergeCommitHash()));
	GitUtils.updateRef(refUpdate);
}
 
Example #29
Source File: PullRequest.java    From onedev with MIT License 4 votes vote down vote up
public void writeHeadRef() {
	RefUpdate refUpdate = GitUtils.getRefUpdate(getTargetProject().getRepository(), getHeadRef());
	refUpdate.setNewObjectId(ObjectId.fromString(getLatestUpdate().getHeadCommitHash()));
	GitUtils.updateRef(refUpdate);
}
 
Example #30
Source File: PullRequest.java    From onedev with MIT License 4 votes vote down vote up
public void writeBaseRef() {
	RefUpdate refUpdate = GitUtils.getRefUpdate(getTargetProject().getRepository(), getBaseRef());
	refUpdate.setNewObjectId(ObjectId.fromString(getBaseCommitHash()));
	GitUtils.updateRef(refUpdate);
}