org.eclipse.jgit.lib.Repository Java Examples

The following examples show how to use org.eclipse.jgit.lib.Repository. 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: CheckoutIndexCommand.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void run() throws GitException {
    Repository repository = getRepository();
    DirCache cache = null;
    try {
        // cache must be locked because checkout index may modify its entries
        cache = repository.lockDirCache();
        DirCacheBuilder builder = cache.builder();
        if (cache.getEntryCount() > 0) {
            builder.keep(0, cache.getEntryCount());
        }
        builder.finish();
        new CheckoutIndex(repository, cache, roots, recursively, listener, monitor, true).checkout();
        // cache must be saved to disk because checkout index may modify its entries
        builder.commit();
    } catch (IOException ex) {
        throw new GitException(ex);
    } finally {
        if (cache != null) {
            cache.unlock();
        }
    }
}
 
Example #2
Source File: GitDiffHandlerV1.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
private boolean handleMultiPartGet(HttpServletRequest request, HttpServletResponse response, Repository db, String scope, String pattern) throws Exception {
	String boundary = createBoundaryString();
	response.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$
	response.setHeader(ProtocolConstants.HEADER_CONTENT_TYPE, "multipart/related; boundary=\"" + boundary + '"'); //$NON-NLS-1$
	OutputStream outputStream = response.getOutputStream();
	Writer out = new OutputStreamWriter(outputStream);
	try {
		out.write("--" + boundary + EOL); //$NON-NLS-1$
		out.write(ProtocolConstants.HEADER_CONTENT_TYPE + ": " + ProtocolConstants.CONTENT_TYPE_JSON + EOL + EOL); //$NON-NLS-1$
		out.flush();
		JSONObject getURIs = new Diff(getURI(request), db).toJSON();
		JsonURIUnqualificationStrategy.ALL.run(request, getURIs);

		out.write(getURIs.toString());
		out.write(EOL + "--" + boundary + EOL); //$NON-NLS-1$
		out.write(ProtocolConstants.HEADER_CONTENT_TYPE + ": plain/text" + EOL + EOL); //$NON-NLS-1$
		out.flush();
		handleGetDiff(request, response, db, scope, pattern, outputStream);
		out.write(EOL);
		out.flush();
	} finally {
		IOUtilities.safeClose(out);
	}
	return true;
}
 
Example #3
Source File: RebaseCommand.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private GitRebaseResult createResult (RebaseResult res) {
    String currHead;
    Repository repository = getRepository();
    try {
        currHead = repository.resolve(Constants.HEAD).name();
    } catch (IOException ex) {
        currHead = Constants.HEAD;
    }
    List<File> conflicts;
    if (res.getStatus() == RebaseResult.Status.STOPPED) {
        conflicts = getConflicts(res.getCurrentCommit());
    } else {
        conflicts = Collections.<File>emptyList();
    }
    return getClassFactory().createRebaseResult(res, conflicts, getFailures(res), currHead);
}
 
Example #4
Source File: AppraiseReviewTaskActivationListener.java    From git-appraise-eclipse with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Asks the user if they want to switch to the review branch, and performs
 * the switch if so.
 */
private void promptSwitchToReviewBranch(TaskRepository taskRepository, String reviewBranch) {
  MessageDialog dialog = new MessageDialog(null, "Appraise Review", null,
      "Do you want to switch to the review branch (" + reviewBranch + ")", MessageDialog.QUESTION,
      new String[] {"Yes", "No"}, 0);
  int result = dialog.open();
  if (result == 0) {
    Repository repo = AppraisePluginUtils.getGitRepoForRepository(taskRepository);
    try (Git git = new Git(repo)) {
      previousBranch = repo.getFullBranch();
      git.checkout().setName(reviewBranch).call();
    } catch (RefNotFoundException rnfe) {
      MessageDialog alert = new MessageDialog(null, "Oops", null,
          "Branch " + reviewBranch + " not found", MessageDialog.INFORMATION, new String[] {"OK"}, 0);
      alert.open();
    } catch (Exception e) {
      AppraiseUiPlugin.logError("Unable to switch to review branch: " + reviewBranch, e);
    }
  }
}
 
Example #5
Source File: GitContentRepositoryHelper.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
public String commitFile(Repository repo, String site, String path, String comment, PersonIdent user) {
    String commitId = null;
    String gitPath = getGitPath(path);
    Status status;

    try (Git git = new Git(repo)) {
        status = git.status().addPath(gitPath).call();

        // TODO: SJ: Below needs more thought and refactoring to detect issues with git repo and report them
        if (status.hasUncommittedChanges() || !status.isClean()) {
            RevCommit commit;
            commit = git.commit().setOnly(gitPath).setAuthor(user).setCommitter(user).setMessage(comment).call();
            commitId = commit.getName();
        }

        git.close();
    } catch (GitAPIException e) {
        logger.error("error adding and committing file to git: site: " + site + " path: " + path, e);
    }

    return commitId;
}
 
Example #6
Source File: XdocPublisher.java    From contribution with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Publish release notes.
 *
 * @throws IOException if problem with access to files appears.
 * @throws GitAPIException for problems with jgit.
 */
public void publish() throws IOException, GitAPIException {
    changeLocalRepoXdoc();
    final FileRepositoryBuilder builder = new FileRepositoryBuilder();
    final File localRepo = new File(localRepoPath);
    final Repository repo = builder.findGitDir(localRepo).readEnvironment().build();
    final Git git = new Git(repo);
    git.add()
        .addFilepattern(PATH_TO_XDOC_IN_REPO)
        .call();
    git.commit()
        .setMessage(String.format(Locale.ENGLISH, COMMIT_MESSAGE_TEMPLATE, releaseNumber))
        .call();
    if (doPush) {
        final CredentialsProvider credentialsProvider =
            new UsernamePasswordCredentialsProvider(authToken, "");
        git.push()
            .setCredentialsProvider(credentialsProvider)
            .call();
    }
}
 
Example #7
Source File: RepositoryManagementServiceInternalImpl.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean removeRemote(String siteId, String remoteName) throws CryptoException {
    logger.debug("Remove remote " + remoteName + " from the sandbox repo for the site " + siteId);
    GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration);
    Repository repo = helper.getRepository(siteId, SANDBOX);
    try (Git git = new Git(repo)) {
        RemoteRemoveCommand remoteRemoveCommand = git.remoteRemove();
        remoteRemoveCommand.setName(remoteName);
        remoteRemoveCommand.call();

    } catch (GitAPIException e) {
        logger.error("Failed to remove remote " + remoteName + " for site " + siteId, e);
        return false;
    }

    logger.debug("Remove remote record from database for remote " + remoteName + " and site " + siteId);
    Map<String, String> params = new HashMap<String, String>();
    params.put("siteId", siteId);
    params.put("remoteName", remoteName);
    remoteRepositoryDao.deleteRemoteRepository(params);

    return true;
}
 
Example #8
Source File: UpdaterGenerator.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Execute git pull command on the given repository.
 * It populates an ArrayList with all the updated files.
 * @param localPath The path where the project is.
 * @return Returns true if you should update plugins, false otherwise.
 */
private boolean gitPull(File localPath) {
    try {
        Repository localRepo = new FileRepository(localPath.getAbsolutePath() + "/.git");
        git = new Git(localRepo);
        
        
        
        if(populateDiff()){
            PullCommand pullCmd = git.pull();
            pullCmd.call();
            return true;
        }
        else{
            return false;
        }
        
    } catch (GitAPIException | IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

    return true;
}
 
Example #9
Source File: Build.java    From onedev with MIT License 6 votes vote down vote up
public Collection<RevCommit> getCommits(@Nullable Build.Status sincePrevStatus) {
	if (commitsCache == null) 
		commitsCache = new HashMap<>();
	if (!commitsCache.containsKey(sincePrevStatus)) {
		Collection<RevCommit> commits = new ArrayList<>();
		Build prevBuild = getStreamPrevious(sincePrevStatus);
		if (prevBuild != null) {
			Repository repository = project.getRepository();
			try (RevWalk revWalk = new RevWalk(repository)) {
				revWalk.markStart(revWalk.parseCommit(ObjectId.fromString(getCommitHash())));
				revWalk.markUninteresting(revWalk.parseCommit(prevBuild.getCommitId()));

				RevCommit commit;
				while ((commit = revWalk.next()) != null) 
					commits.add(commit);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		} 
		commitsCache.put(sincePrevStatus, commits);
	}
	return commitsCache.get(sincePrevStatus);
}
 
Example #10
Source File: GitContentRepository.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
@Override
public long getContentSize(final String site, final String path) {
    Repository repo = helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX);
    try {
        RevTree tree = helper.getTreeForLastCommit(repo);
        try (TreeWalk tw = TreeWalk.forPath(repo, helper.getGitPath(path), tree)) {
            if (tw != null && tw.getObjectId(0) != null) {
                ObjectId id = tw.getObjectId(0);
                ObjectLoader objectLoader = repo.open(id);
                return objectLoader.getSize();
            }
        }
    } catch (IOException e) {
        logger.error("Error while getting content for file at site: " + site + " path: " + path, e);
    }
    return -1L;
}
 
Example #11
Source File: UpdaterGenerator.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Populate all the files to update, if the system should update.
 */
private void populateDiff() {
    try {
        git.fetch().call();
        Repository repo = git.getRepository();
        ObjectId fetchHead = repo.resolve("FETCH_HEAD^{tree}");
        ObjectId head = repo.resolve("HEAD^{tree}");
        
        ObjectReader reader = repo.newObjectReader();
        CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
        oldTreeIter.reset(reader, head);
        CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
        newTreeIter.reset(reader, fetchHead);
        List<DiffEntry> diffs = git.diff().setShowNameAndStatusOnly(true)
                .setNewTree(newTreeIter)
                .setOldTree(oldTreeIter)
                .call();
        
        pluginsToUpdate = new ArrayList<PluginToUpdate>();
        
        checkDiffEmpty(diffs);
        
    } catch (GitAPIException | IOException ex) {
        Logger.getLogger(UpdaterGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example #12
Source File: JGitUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static void persistUser (File root, GitUser author) throws GitException {
    Repository repository = getRepository(root);
    if (repository != null) {
        try {
            StoredConfig config = repository.getConfig();
            config.setString("user", null, "name", author.getName()); //NOI18N
            config.setString("user", null, "email", author.getEmailAddress()); //NOI18N
            try {
                config.save();
                FileUtil.refreshFor(new File(GitUtils.getGitFolderForRoot(root), "config"));
            } catch (IOException ex) {
                throw new GitException(ex);
            }
        } finally {
            repository.close();
        }
    }
}
 
Example #13
Source File: GitContentRepositoryHelper.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Create a site git repository from scratch (Sandbox and Published)
 * @param site
 * @return true if successful, false otherwise
 */
public boolean createSiteGitRepo(String site, String sandboxBranch) {
    boolean toReturn;
    Repository sandboxRepo = null;

    // Build a path for the site/sandbox
    Path siteSandboxPath = buildRepoPath(GitRepositories.SANDBOX, site);

    // Create Sandbox
    sandboxRepo = createGitRepository(siteSandboxPath);

    toReturn = (sandboxRepo != null);

    if (toReturn) {
        checkoutSandboxBranch(site, sandboxRepo, sandboxBranch);
        sandboxes.put(site, sandboxRepo);
    }

    return toReturn;
}
 
Example #14
Source File: Build.java    From onedev with MIT License 6 votes vote down vote up
/**
 * Get fixed issue numbers
 * 
 */
public Collection<Long> getFixedIssueNumbers() {
	if (fixedIssueNumbers == null) {
		fixedIssueNumbers = new HashSet<>();
		Build prevBuild = getStreamPrevious(null);
		if (prevBuild != null) {
			Repository repository = project.getRepository();
			try (RevWalk revWalk = new RevWalk(repository)) {
				revWalk.markStart(revWalk.parseCommit(ObjectId.fromString(getCommitHash())));
				revWalk.markUninteresting(revWalk.parseCommit(prevBuild.getCommitId()));

				RevCommit commit;
				while ((commit = revWalk.next()) != null) 
					fixedIssueNumbers.addAll(IssueUtils.parseFixedIssueNumbers(commit.getFullMessage()));
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		} 
	}
	return fixedIssueNumbers;
}
 
Example #15
Source File: GitRepositoryHelper.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Opens a git repository
 *
 * @param repositoryPath path to repository to open (including .git)
 * @return repository object if successful
 * @throws IOException
 */
public Repository openRepository(Path repositoryPath) throws IOException {
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder
            .setGitDir(repositoryPath.toFile())
            .readEnvironment()
            .findGitDir()
            .build();
    return repository;
}
 
Example #16
Source File: RepoSemanticVersions.java    From gradle-gitsemver with Apache License 2.0 5 votes vote down vote up
public static Repository getRepo(String repoLocation)
       throws NoWorkTreeException, IOException, GitAPIException {
    Repository repo;
    try {
        repo = new FileRepositoryBuilder().readEnvironment()
                .findGitDir(new File(repoLocation)).build();
    } catch (IllegalArgumentException iae) {
        throw new SemverGitflowPlugin.VersionApplicationException(
                "Project is not in a Git repository. Cannot use semver versioning in a non repository.",
                iae);
    }
    return repo;
}
 
Example #17
Source File: GitRepositoryConfig.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@NotNull
public static GitRepository createRepository(@NotNull LocalContext context, @Nullable LfsStorage lfsStorage, @NotNull Repository git, @NotNull GitPusher pusher, @NotNull Set<String> branches, boolean renameDetection) throws IOException {
  final LockStorage lockStorage;
  if (lfsStorage != null) {
    context.add(LfsStorage.class, lfsStorage);
    lockStorage = lfsStorage;
  } else {
    lockStorage = new LocalLockManager(LocalLockManager.getPersistentStorage(context));
  }

  final GitFilters filters = new GitFilters(context, lfsStorage);
  return new GitRepository(context, git, pusher, branches, renameDetection, lockStorage, filters);
}
 
Example #18
Source File: LogCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void markBranchFlags (Map<String, GitBranch> allBranches, RevWalk walk, Map<RevFlag, List<GitBranch>> branchFlags) {
    int i = 1;
    Set<String> usedFlags = new HashSet<>();
    Repository repository = getRepository();
    for (Map.Entry<String, GitBranch> e : allBranches.entrySet()) {
        if (! GitBranch.NO_BRANCH.equals(e.getKey())) {
            String flagId = e.getValue().getId();
            if (usedFlags.contains(flagId)) {
                for (Map.Entry<RevFlag, List<GitBranch>> e2 : branchFlags.entrySet()) {
                    if (e2.getKey().toString().equals(flagId)) {
                        e2.getValue().add(e.getValue());
                    }
                }
            } else {
                usedFlags.add(flagId);
                if (i < 25) {
                    i = i + 1;
                    RevFlag flag = walk.newFlag(flagId);
                    List<GitBranch> branches = new ArrayList<>(allBranches.size());
                    branches.add(e.getValue());
                    branchFlags.put(flag, branches);
                    try {
                        RevCommit branchHeadCommit = walk.parseCommit(repository.resolve(e.getValue().getId()));
                        branchHeadCommit.add(flag);
                        branchHeadCommit.carry(flag);
                        walk.markStart(branchHeadCommit);
                    } catch (IOException ex) {
                        LOG.log(Level.INFO, null, ex);
                    }
                } else {
                    LOG.log(Level.WARNING, "Out of available flags for branches: {0}", allBranches.size()); //NOI18N
                    break;
                }
            }
        }
    }
    walk.carry(branchFlags.keySet());
}
 
Example #19
Source File: CreateAndDeleteTag.java    From tutorials with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException, GitAPIException {
    // prepare test-repository
    try (Repository repository = Helper.openJGitRepository()) {
        try (Git git = new Git(repository)) {
            // remove the tag before creating it
            git.tagDelete().setTags("tag_for_testing").call();

            // set it on the current HEAD
            Ref tag = git.tag().setName("tag_for_testing").call();
            System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory());

            // remove the tag again
            git.tagDelete().setTags("tag_for_testing").call();

            // read some other commit and set the tag on it
            ObjectId id = repository.resolve("HEAD^");
            try (RevWalk walk = new RevWalk(repository)) {
                RevCommit commit = walk.parseCommit(id);
                tag = git.tag().setObjectId(commit).setName("tag_for_testing").call();
                System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory());

                // remove the tag again
                git.tagDelete().setTags("tag_for_testing").call();

                // create an annotated tag
                tag = git.tag().setName("tag_for_testing").setAnnotated(true).call();
                System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory());

                // remove the tag again
                git.tagDelete().setTags("tag_for_testing").call();

                walk.dispose();
            }
        }
    }
}
 
Example #20
Source File: SetUpstreamBranchCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    
    try {
        Ref ref = repository.findRef(trackedBranchName);
        if (ref == null) {
            throw new GitException(MessageFormat.format(Utils.getBundle(SetUpstreamBranchCommand.class)
                    .getString("MSG_Error_UpdateTracking_InvalidReference"), trackedBranchName)); //NOI18N)
        }
        String remote = null;
        String branchName = ref.getName();
        StoredConfig config = repository.getConfig();
        if (branchName.startsWith(Constants.R_REMOTES)) {
            String[] elements = branchName.split("/", 4);
            remote = elements[2];
            if (config.getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION).contains(remote)) {
                branchName = Constants.R_HEADS + elements[3];
                setupRebaseFlag(repository);
            } else {
                // remote not yet set
                remote = null;
            }
        }
        if (remote == null) {
            remote = "."; //NOI18N
        }
        config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, localBranchName,
                ConfigConstants.CONFIG_KEY_REMOTE, remote);
        config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, localBranchName,
                ConfigConstants.CONFIG_KEY_MERGE, branchName);
        config.save();
    } catch (IOException ex) {
        throw new GitException(ex);
    }
    ListBranchCommand branchCmd = new ListBranchCommand(repository, getClassFactory(), false, new DelegatingGitProgressMonitor(monitor));
    branchCmd.run();
    Map<String, GitBranch> branches = branchCmd.getBranches();
    branch = branches.get(localBranchName);
}
 
Example #21
Source File: WorkerTest.java    From github-bucket with ISC License 5 votes vote down vote up
public WorkerTest() {
    URIish fetchUrl = new URIish();
    SyncableRepository pushRepository = mock(SyncableRepository.class);

    when(config.getFetchUrl()).thenReturn(fetchUrl);
    when(config.getPushRepository()).thenReturn(pushRepository);

    ObjectDatabase database = mock(ObjectDatabase.class);
    when(database.exists()).thenReturn(false);
    Repository repository = mock(Repository.class);
    when(repository.getObjectDatabase()).thenReturn(database);
    when(config.getWorkingFileRepository()).thenReturn(repository);

    uut = new Worker(config);
}
 
Example #22
Source File: GitContentRepositoryHelper.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
public boolean deleteSiteGitRepo(String site) {
    boolean toReturn;

    // Get the Sandbox Path
    Path siteSandboxPath = buildRepoPath(GitRepositories.SANDBOX, site);
    // Get parent of that (since every site has two repos: Sandbox and Published)
    Path sitePath = siteSandboxPath.getParent();
    // Get a file handle to the parent and delete it
    File siteFolder = sitePath.toFile();

    try {
        Repository sboxRepo = sandboxes.get(site);
        if (sboxRepo != null) {
            sboxRepo.close();
            sandboxes.remove(site);
            RepositoryCache.close(sboxRepo);
            sboxRepo = null;
        }
        Repository pubRepo = published.get(site);
        if (pubRepo != null) {
            pubRepo.close();
            published.remove(site);
            RepositoryCache.close(pubRepo);
            pubRepo = null;
        }
        FileUtils.deleteDirectory(siteFolder);

        toReturn = true;

        logger.debug("Deleted site: " + site + " at path: " + sitePath);
    } catch (IOException e) {
        logger.error("Failed to delete site: " + site + " at path: " + sitePath + " exception " +
                e.toString());
        toReturn = false;
    }

    return toReturn;
}
 
Example #23
Source File: GitBasedArtifactRepository.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
public static boolean addRemote(Repository repository, String remoteUrl) {

        boolean remoteAdded = false;

        StoredConfig config = repository.getConfig();
        config.setString(GitDeploymentSynchronizerConstants.REMOTE,
                GitDeploymentSynchronizerConstants.ORIGIN,
                GitDeploymentSynchronizerConstants.URL,
                remoteUrl);

        config.setString(GitDeploymentSynchronizerConstants.REMOTE,
                GitDeploymentSynchronizerConstants.ORIGIN,
                GitDeploymentSynchronizerConstants.FETCH,
                GitDeploymentSynchronizerConstants.FETCH_LOCATION);

        config.setString(GitDeploymentSynchronizerConstants.BRANCH,
                GitDeploymentSynchronizerConstants.MASTER,
                GitDeploymentSynchronizerConstants.REMOTE,
                GitDeploymentSynchronizerConstants.ORIGIN);

        config.setString(GitDeploymentSynchronizerConstants.BRANCH,
                GitDeploymentSynchronizerConstants.MASTER,
                GitDeploymentSynchronizerConstants.MERGE,
                GitDeploymentSynchronizerConstants.GIT_REFS_HEADS_MASTER);

        try {
            config.save();
            remoteAdded = true;

        } catch (IOException e) {
            log.error("Error in adding remote origin " + remoteUrl + " for local repository " +
                    repository.toString(), e);
        }

        return remoteAdded;
    }
 
Example #24
Source File: StatusCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Map<String, DiffEntry> detectRenames (Repository repository, DirCache cache, ObjectId commitId) {
    List<DiffEntry> entries;
    try(TreeWalk treeWalk = new TreeWalk(repository);) {
        treeWalk.setRecursive(true);
        treeWalk.reset();
        if (commitId != null) {
            treeWalk.addTree(new RevWalk(repository).parseTree(commitId));
        } else {
            treeWalk.addTree(new EmptyTreeIterator());
        }
        // Index
        treeWalk.addTree(new DirCacheIterator(cache));
        treeWalk.setFilter(TreeFilter.ANY_DIFF);
        entries = DiffEntry.scan(treeWalk);
        RenameDetector d = new RenameDetector(repository);
        d.addAll(entries);
        entries = d.compute();
    } catch (IOException ex) {
        entries = Collections.<DiffEntry>emptyList();
    }
    Map<String, DiffEntry> renames = new HashMap<>();
    for (DiffEntry e : entries) {
        if (e.getChangeType().equals(DiffEntry.ChangeType.COPY) || e.getChangeType().equals(DiffEntry.ChangeType.RENAME)) {
            renames.put(e.getNewPath(), e);
        }
    }
    return renames;
}
 
Example #25
Source File: CherryPickCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private GitRevisionInfo getCurrentHead () {
    GitRevisionInfo currHead;
    Repository repository = getRepository();
    try {
        currHead = getClassFactory().createRevisionInfo(Utils.findCommit(repository, Constants.HEAD), repository);
    } catch (GitException ex) {
        currHead = null;
    }
    return currHead;
}
 
Example #26
Source File: BugFinderFactory.java    From SZZUnleashed with MIT License 5 votes vote down vote up
public static BugIntroducerFinder getFinder(Repository repo, Issues issues) {
  Configuration conf = Configuration.getInstance();
  switch (conf.getBugFinder()) {
    case SIMPLE:
      return new SimpleBugIntroducerFinder(
          issues, repo, conf.getDepth(), conf.getPartialFixPattern());
    case DISTANCE:
      return new DistanceIntroducerFinder(repo, conf.getDiffCustomContext());
  }

  return null;
}
 
Example #27
Source File: GitUtils.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private static PersonIdent buildPersonIdent(final Repository repo, final String name, final String email,
        final TimeZone timeZone, final Date when) {
    final TimeZone tz = timeZone == null ? TimeZone.getDefault() : timeZone;

    if (name != null) {
        if (when != null) {
            return new PersonIdent(name, email, when, tz);
        } else {
            return new PersonIdent(name, email);
        }
    }
    return new PersonIdent(repo);
}
 
Example #28
Source File: UpToDateTask.java    From ant-git-tasks with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute() throws BuildException {
        Repository repo = git.getRepository();

        FileTreeIterator workingTreeIterator = new FileTreeIterator(repo);

        try {
                IndexDiff diff = new IndexDiff(repo, Constants.HEAD, workingTreeIterator);
                diff.diff();

                Status status = new Status(diff);

                if (!status.isClean()) {
                        if (modificationExistProperty != null) {
                                getProject().setProperty(modificationExistProperty, "true");
                        }

                        if (isFailOnError()) {
                                StringBuilder msg = new StringBuilder();
                                msg.append("The Git tree was modified.");
                                msg.append("\n").append("Changed:").append(status.getChanged());
                                msg.append("\n").append("Added:").append(status.getAdded());
                                msg.append("\n").append("Modified:").append(status.getModified());
                                msg.append("\n").append("Missing:").append(status.getMissing());
                                msg.append("\n").append("Removed:").append(status.getRemoved());
                                msg.append("\n").append("Untracked:").append(status.getUntracked());

                                throw new GitBuildException(String.format(STATUS_NOT_CLEAN_TEMPLATE, msg.toString()));
                        }
                } else {
                        log(MESSAGE_UPTODATE_SUCCESS);
                }
        } catch (IOException ioe) {
                throw new GitBuildException(MESSAGE_UPTODATE_FAILED, ioe);
        }

}
 
Example #29
Source File: GitUtil.java    From vertx-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve the git commitId hash
 *
 * @param repository - the Git repository from where the latest commit will be retrieved
 * @return String of Git commit hash
 * @throws GitAPIException - any Git exception that might occur while getting commitId
 */
public static String getGitCommitId(Repository repository) throws GitAPIException {
    try {
        if (repository != null) {
            Iterable<RevCommit> logs = new Git(repository).log().call();
            for (RevCommit rev : logs) {
                return rev.getName();
            }
        }
    } finally {

    }
    return null;
}
 
Example #30
Source File: GitCloneHandler.java    From ice with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * This private method is used to import existing projects into the project
 * explorer.
 * 
 * @param repository
 * @param sets
 */
protected void importProjects(final Repository repository, final IWorkingSet[] sets) {
	String repoName = Activator.getDefault().getRepositoryUtil().getRepositoryName(repository);
	Job importJob = new WorkspaceJob(MessageFormat.format(UIText.GitCloneWizard_jobImportProjects, repoName)) {

		@Override
		public IStatus runInWorkspace(IProgressMonitor monitor) {
			List<File> files = new ArrayList<File>();
			ProjectUtil.findProjectFiles(files, repository.getWorkTree(), true, monitor);
			if (files.isEmpty()) {
				return Status.OK_STATUS;
			}

			Set<ProjectRecord> projectRecords = new LinkedHashSet<ProjectRecord>();
			for (File file : files) {
				projectRecords.add(new ProjectRecord(file));
			}
			try {
				ProjectUtils.createProjects(projectRecords, sets, monitor);
			} catch (InvocationTargetException | InterruptedException e) {
				Activator.logError(e.getLocalizedMessage(), e);
			}

			return Status.OK_STATUS;
		}
	};
	importJob.schedule();
}