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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #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: 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 #13
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 #14
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 #15
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 #16
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();
}
 
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: 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 #19
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 #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: 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 #22
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 #23
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 #24
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 #25
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void deleteBranch(String name) throws GitException {
    try (Repository repo = getRepository()) {
        git(repo).branchDelete().setForce(true).setBranchNames(name).call();
    } catch (GitAPIException e) {
        throw new GitException(e);
    }
}
 
Example #26
Source File: CommitAll.java    From tutorials with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException, GitAPIException {
    // prepare a new test-repository
    try (Repository repository = Helper.createNewRepository()) {
        try (Git git = new Git(repository)) {
            // create the file
            File myfile = new File(repository.getDirectory().getParent(), "testfile");
            if(!myfile.createNewFile()) {
                throw new IOException("Could not create file " + myfile);
            }

            // Stage all files in the repo including new files
            git.add().addFilepattern(".").call();

            // and then commit the changes.
            git.commit()
                    .setMessage("Commit all changes including additions")
                    .call();

            try(PrintWriter writer = new PrintWriter(myfile)) {
                writer.append("Hello, world!");
            }

            // Stage all changed files, omitting new files, and commit with one command
            git.commit()
                    .setAll(true)
                    .setMessage("Commit changes to all files")
                    .call();


            System.out.println("Committed all changes to repository at " + repository.getDirectory());
        }
    }
}
 
Example #27
Source File: GitUtils.java    From onedev with MIT License 5 votes vote down vote up
@Nullable
  public static ObjectId merge(Repository repository, ObjectId targetCommitId, ObjectId sourceCommitId, 
  		boolean squash, PersonIdent committer, PersonIdent author, String commitMessage, 
  		boolean useOursOnConflict) {
  	boolean prevUseOursOnConflict = UseOursOnConflict.get();
  	UseOursOnConflict.set(useOursOnConflict);
  	try (	RevWalk revWalk = new RevWalk(repository);
  			ObjectInserter inserter = repository.newObjectInserter();) {
  		RevCommit sourceCommit = revWalk.parseCommit(sourceCommitId);
  		RevCommit targetCommit = revWalk.parseCommit(targetCommitId);
  		Merger merger = MergeStrategy.RECURSIVE.newMerger(repository, true);
  		if (merger.merge(targetCommit, sourceCommit)) {
        CommitBuilder mergedCommit = new CommitBuilder();
        mergedCommit.setAuthor(author);
        mergedCommit.setCommitter(committer);
        if (squash)
        	mergedCommit.setParentId(targetCommit);
        else
        	mergedCommit.setParentIds(targetCommit, sourceCommit);
        mergedCommit.setMessage(commitMessage);
        mergedCommit.setTreeId(merger.getResultTreeId());
        ObjectId mergedCommitId = inserter.insert(mergedCommit);
        inserter.flush();
        return mergedCommitId;
  		} else {
  			return null;
  		}
  	} catch (IOException e) {
  		throw new RuntimeException(e);
} finally {
	UseOursOnConflict.set(prevUseOursOnConflict);
}
  }
 
Example #28
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Deprecated
@Override
public void merge(String refSpec) throws GitException, InterruptedException {
    try (Repository repo = getRepository()) {
        merge(repo.resolve(refSpec));
    } catch (IOException e) {
        throw new GitException(e);
    }
}
 
Example #29
Source File: GitIndexHandlerV1.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private boolean handleGet(HttpServletRequest request, HttpServletResponse response, Repository db, String pattern) throws CoreException, IOException,
		ServletException {
	Index index = new Index(null /* not needed */, db, pattern);
	ObjectStream stream = index.toObjectStream();
	if (stream == null) {
		String msg = NLS.bind("{0} not found in index", pattern); //$NON-NLS-1$
		if ("true".equals(request.getHeader("read-if-exists"))) {
			return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.WARNING, 204, msg, null)); 
		}
		return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.OK, HttpServletResponse.SC_NOT_FOUND, msg, null));
	}
	response.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$
	IOUtilities.pipe(stream, response.getOutputStream(), true, false);
	return true;
}
 
Example #30
Source File: GitServiceImpl.java    From RefactoringMiner with MIT License 5 votes vote down vote up
public void checkout2(Repository repository, String commitId) throws Exception {
    logger.info("Checking out {} {} ...", repository.getDirectory().getParent().toString(), commitId);
	File workingDir = repository.getDirectory().getParentFile();
	String output = ExternalProcess.execute(workingDir, "git", "checkout", commitId);
	if (output.startsWith("fatal")) {
	    throw new RuntimeException("git error " + output);
	}
}