Java Code Examples for org.eclipse.jgit.lib.Repository

The following are top voted examples for showing how to use org.eclipse.jgit.lib.Repository. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: BlameCommand.java   Source Code and License 7 votes vote down vote up
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    org.eclipse.jgit.api.BlameCommand cmd = new Git(repository).blame();
    cmd.setFilePath(Utils.getRelativePath(getRepository().getWorkTree(), file));
    if (revision != null) {
        cmd.setStartCommit(Utils.findCommit(repository, revision));
    } else if (repository.getConfig().get(WorkingTreeOptions.KEY).getAutoCRLF() != CoreConfig.AutoCRLF.FALSE) {
        // work-around for autocrlf
        cmd.setTextComparator(new AutoCRLFComparator());
    }
    cmd.setFollowFileRenames(true);
    try {
        BlameResult cmdResult = cmd.call();
        if (cmdResult != null) {
            result = getClassFactory().createBlameResult(cmdResult, repository);
        }
    } catch (GitAPIException ex) {
        throw new GitException(ex);
    }
}
 
Example 2
Project: yacy_grid_mcp   File: GitTool.java   Source Code and License 6 votes vote down vote up
public GitTool() {
    File gitWorkDir = new File(".");
    try {
        Git git = Git.open(gitWorkDir);
        Iterable<RevCommit> commits = git.log().all().call();
        Repository repo = git.getRepository();
        branch = repo.getBranch();
        RevCommit latestCommit = commits.iterator().next();
        name = latestCommit.getName();
        message = latestCommit.getFullMessage();
    } catch (Throwable e) {
        name = "";
        message = "";
        branch = "";
    }
}
 
Example 3
Project: gitplex-mit   File: DefaultProjectManager.java   Source Code and License 6 votes vote down vote up
@Transactional
  @Override
  public void delete(Project project) {
  	Query query = getSession().createQuery("update Project set forkedFrom=null where forkedFrom=:forkedFrom");
  	query.setParameter("forkedFrom", project);
  	query.executeUpdate();

  	dao.remove(project);

  	dao.doAfterCommit(new Runnable() {

	@Override
	public void run() {
		synchronized (repositoryCache) {
   			Repository repository = repositoryCache.remove(project.getId());
   			if (repository != null) 
   				repository.close();
   		}
		
	}
	
});
  }
 
Example 4
Project: xm-ms-config   File: JGitRepository.java   Source Code and License 6 votes vote down vote up
@SneakyThrows
protected void pull() {
    try (
            Repository db = createRepository();
            Git git = Git.wrap(db);
    ) {
        String branchName = gitProperties.getBranchName();
        try {
            git.checkout().setName(branchName).call();
            git.pull().setCredentialsProvider(createCredentialsProvider()).call();
        } catch (RefNotFoundException e) {
            log.info("Branch {} not found in local repository", branchName);
            git.fetch().setCredentialsProvider(createCredentialsProvider()).call();
            git.checkout()
                    .setCreateBranch(true)
                    .setName(branchName)
                    .setUpstreamMode(TRACK)
                    .setStartPoint(DEFAULT_REMOTE_NAME + "/" + branchName).
                    call();
            git.pull().setCredentialsProvider(createCredentialsProvider()).call();
        }
    }
}
 
Example 5
Project: RefDiff   File: GitServiceImpl.java   Source Code and License 6 votes vote down vote up
public RevWalk createAllRevsWalk(Repository repository, String branch) throws Exception {
	List<ObjectId> currentRemoteRefs = new ArrayList<ObjectId>(); 
	for (Ref ref : repository.getAllRefs().values()) {
		String refName = ref.getName();
		if (refName.startsWith(REMOTE_REFS_PREFIX)) {
			if (branch == null || refName.endsWith("/" + branch)) {
				currentRemoteRefs.add(ref.getObjectId());
			}
		}
	}
	
	RevWalk walk = new RevWalk(repository);
	for (ObjectId newRef : currentRemoteRefs) {
		walk.markStart(walk.parseCommit(newRef));
	}
	walk.setRevFilter(commitsFilter);
	return walk;
}
 
Example 6
Project: gmds   File: Commands.java   Source Code and License 6 votes vote down vote up
/**
 * 
 * @param commitBuilder
 * @param treeId
 * @param repo
 * @return
 * @throws UnsupportedEncodingException
 * @throws IOException 
 */
public static ObjectId commit(CommitBuilder commitBuilder, ObjectId treeId, Repository repo) throws UnsupportedEncodingException, IOException {
    commitBuilder.setTreeId(treeId);
    commitBuilder.setMessage(System.currentTimeMillis() + ": My commit!\n");
    PersonIdent person = new PersonIdent("Alex", "[email protected]");
    commitBuilder.setAuthor(person);
    commitBuilder.setCommitter(person);

    commitBuilder.build();

    ObjectInserter commitInserter = repo.newObjectInserter();
    ObjectId commitId = commitInserter.insert(commitBuilder);
    commitInserter.flush();

    updateMasterRecord(repo, commitId);

    System.out.println("Commit Object ID: " + commitId.getName());

    return commitId;
}
 
Example 7
Project: RefDiff   File: GitHelper.java   Source Code and License 6 votes vote down vote up
public RevWalk fetchAndCreateNewRevsWalk(Repository repository, String branch) throws Exception {
	List<ObjectId> currentRemoteRefs = new ArrayList<ObjectId>();
	for (Ref ref : repository.getAllRefs().values()) {
		String refName = ref.getName();
		if (refName.startsWith(REMOTE_REFS_PREFIX)) {
			currentRemoteRefs.add(ref.getObjectId());
		}
	}
	
	List<TrackingRefUpdate> newRemoteRefs = this.fetch(repository);
	
	RevWalk walk = new RevWalk(repository);
	for (TrackingRefUpdate newRef : newRemoteRefs) {
		if (branch == null || newRef.getLocalName().endsWith("/" + branch)) {
			walk.markStart(walk.parseCommit(newRef.getNewObjectId()));
		}
	}
	for (ObjectId oldRef : currentRemoteRefs) {
		walk.markUninteresting(walk.parseCommit(oldRef));
	}
	walk.setRevFilter(commitsFilter);
	return walk;
}
 
Example 8
Project: incubator-netbeans   File: AbstractGitTestCase.java   Source Code and License 6 votes vote down vote up
protected static void assertDirCacheEntry (Repository repository, File workDir, Collection<File> files) throws IOException {
    DirCache cache = repository.lockDirCache();
    for (File f : files) {
        String relativePath = Utils.getRelativePath(workDir, f);
        DirCacheEntry e = cache.getEntry(relativePath);
        assertNotNull(e);
        assertEquals(relativePath, e.getPathString());
        if (f.lastModified() != e.getLastModified()) {
            assertEquals((f.lastModified() / 1000) * 1000, (e.getLastModified() / 1000) * 1000);
        }
        try (InputStream in = new FileInputStream(f)) {
            assertEquals(e.getObjectId(), repository.newObjectInserter().idFor(Constants.OBJ_BLOB, f.length(), in));
        }
        if (e.getLength() == 0 && f.length() != 0) {
            assertTrue(e.isSmudged());
        } else {
            assertEquals(f.length(), e.getLength());
        }
    }
    cache.unlock();
}
 
Example 9
Project: RefDiff   File: GitServiceImpl.java   Source Code and License 6 votes vote down vote up
public RevWalk fetchAndCreateNewRevsWalk(Repository repository, String branch) throws Exception {
	List<ObjectId> currentRemoteRefs = new ArrayList<ObjectId>(); 
	for (Ref ref : repository.getAllRefs().values()) {
		String refName = ref.getName();
		if (refName.startsWith(REMOTE_REFS_PREFIX)) {
			currentRemoteRefs.add(ref.getObjectId());
		}
	}
	
	List<TrackingRefUpdate> newRemoteRefs = this.fetch(repository);
	
	RevWalk walk = new RevWalk(repository);
	for (TrackingRefUpdate newRef : newRemoteRefs) {
		if (branch == null || newRef.getLocalName().endsWith("/" + branch)) {
			walk.markStart(walk.parseCommit(newRef.getNewObjectId()));
		}
	}
	for (ObjectId oldRef : currentRemoteRefs) {
		walk.markUninteresting(walk.parseCommit(oldRef));
	}
	walk.setRevFilter(commitsFilter);
	return walk;
}
 
Example 10
Project: incubator-netbeans   File: UnignoreTest.java   Source Code and License 6 votes vote down vote up
public void test199443_GlobalIgnoreFile () throws Exception {
    File f = new File(new File(workDir, "nbproject"), "file");
    f.getParentFile().mkdirs();
    f.createNewFile();
    File ignoreFile = new File(workDir.getParentFile(), "globalignore");
    write(ignoreFile, "nbproject");
    Repository repo = getRepository(getLocalGitRepository());
    StoredConfig cfg = repo.getConfig();
    cfg.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_EXCLUDESFILE, ignoreFile.getAbsolutePath());
    cfg.save();
    GitClient client = getClient(workDir);
    assertEquals(Status.STATUS_IGNORED, client.getStatus(new File[] { f }, NULL_PROGRESS_MONITOR).get(f).getStatusIndexWC());
    
    assertEquals(new File(workDir, Constants.GITIGNORE_FILENAME), client.unignore(new File[] { f }, NULL_PROGRESS_MONITOR)[0]);
    
    write(new File(workDir, Constants.GITIGNORE_FILENAME), "/nbproject/file");
    assertEquals(new File(workDir, Constants.GITIGNORE_FILENAME), client.unignore(new File[] { f }, NULL_PROGRESS_MONITOR)[0]);
    assertEquals("!/nbproject/file", read(new File(workDir, Constants.GITIGNORE_FILENAME)));
}
 
Example 11
Project: gmds   File: Commands.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @param repo
 * @param objectId
 * @throws IOException
 */
public static void updateMasterRecord(Repository repo, ObjectId objectId) throws IOException {

    RefUpdate refUpdate = repo.updateRef(Constants.HEAD);
    refUpdate.setNewObjectId(objectId);
    final RefUpdate.Result result = refUpdate.forceUpdate();

    switch (result) {
        case NEW:
            System.out.println("New commit!\n");
            break;
        case FORCED:
            System.out.println("Forced change commit!\n");
            break;
        default: {
            System.out.println(result.name());
        }
    }
}
 
Example 12
Project: smart-testing   File: EmbeddedHttpGitServer.java   Source Code and License 6 votes vote down vote up
private GitServlet createGitServlet() {
    final GitServlet gitServlet = new GitServlet();
    gitServlet.setRepositoryResolver((req, name) -> {
        String trimmedName = name.endsWith(SUFFIX) ? name.substring(0, name.length() - SUFFIX.length()) : name;
        trimmedName = trimmedName.substring(trimmedName.lastIndexOf('/') + 1);
        if (repositories.containsKey(trimmedName)) {
            final LazilyLoadedRepository lazilyLoadedRepository = repositories.get(trimmedName);
            synchronized (gitServlet) {
                lazilyLoadedRepository.cloneRepository();
                final Repository repository = lazilyLoadedRepository.get();
                enableInsecureReceiving(repository);
                repository.incrementOpen();
                return repository;
            }
        } else {
            throw new RepositoryNotFoundException("Repository " + name + "does not exist");
        }
    });
    gitServlet.addReceivePackFilter(new AfterReceivePackResetFilter(repositories.values()));
    return gitServlet;
}
 
Example 13
Project: incubator-netbeans   File: RemoveRemoteCommand.java   Source Code and License 6 votes vote down vote up
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    StoredConfig config = repository.getConfig();
    config.unsetSection(ConfigConstants.CONFIG_REMOTE_SECTION, remote);
    Set<String> subSections = config.getSubsections(ConfigConstants.CONFIG_BRANCH_SECTION);
    for (String subSection : subSections) {
        if (remote.equals(config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, subSection, ConfigConstants.CONFIG_KEY_REMOTE))) {
            config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, subSection, ConfigConstants.CONFIG_KEY_REMOTE);
            config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, subSection, ConfigConstants.CONFIG_KEY_MERGE);
        }
    }
    try {
        config.save();
    } catch (IOException ex) {
        throw new GitException(ex);
    }
}
 
Example 14
Project: incubator-netbeans   File: CleanCommand.java   Source Code and License 6 votes vote down vote up
private void deleteIfUnversioned(DirCache cache, String path, WorkingTreeIterator f, Repository repository, TreeWalk treeWalk) throws IOException, NoWorkTreeException {
    if (cache.getEntry(path) == null &&  // not in index 
        !f.isEntryIgnored() &&             // not ignored
        !Utils.isFromNested(f.getEntryFileMode().getBits()))
    {            
        File file = new File(repository.getWorkTree().getAbsolutePath() + File.separator + path);                        
        if(file.isDirectory()) {
            String[] s = file.list();
            if(s != null && s.length > 0) { // XXX is there no better way to find out if empty?
                // not empty
                return; 
            }
        }
        file.delete();
        listener.notifyFile(file, treeWalk.getPathString());
    }
}
 
Example 15
Project: incubator-netbeans   File: SubmoduleStatusCommand.java   Source Code and License 6 votes vote down vote up
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    File workTree = repository.getWorkTree();
    org.eclipse.jgit.api.SubmoduleStatusCommand cmd = new Git(repository).submoduleStatus();
    for (String path : Utils.getRelativePaths(workTree, roots)) {
        cmd.addPath(path);
    }
    try {
        Map<String, SubmoduleStatus> result = cmd.call();
        GitClassFactory fac = getClassFactory();
        for (Map.Entry<String, SubmoduleStatus> e : result.entrySet()) {
            File root = new File(workTree, e.getKey());
            statuses.put(root, fac.createSubmoduleStatus(e.getValue(), root));
        }
    } catch (GitAPIException | JGitInternalException ex) {
        throw new GitException(ex);
    }
}
 
Example 16
Project: RefDiff   File: GitHistoryStructuralDiffAnalyzer.java   Source Code and License 6 votes vote down vote up
public void detectAtCommit(Repository repository, String commitId, StructuralDiffHandler handler) {
	File metadataFolder = repository.getDirectory();
	File projectFolder = metadataFolder.getParentFile();
	GitService gitService = new GitServiceImpl();
	//RevWalk walk = new RevWalk(repository);
	try (RevWalk walk = new RevWalk(repository)) {
		RevCommit commit = walk.parseCommit(repository.resolve(commitId));
		if (commit.getParentCount() == 1) {
		    walk.parseCommit(commit.getParent(0));
		    this.detectRefactorings(gitService, repository, handler, projectFolder, commit);
		}
	} catch (Exception e) {
	    logger.warn(String.format("Ignored revision %s due to error", commitId), e);
	    handler.handleException(commitId, e);
       }
}
 
Example 17
Project: oxygen-git-plugin   File: GitTestBase.java   Source Code and License 6 votes vote down vote up
@Override
protected void tearDown() throws Exception {
  super.tearDown();
  
  // Wait for JGit threads to finish up work.
  flushAWT();
  
  // Only one repository is open at a given time.
  GitAccess.getInstance().close();
  
  for (Repository repository : loadedRepos) {
    // Remove the file system resources.
    try {
      String absolutePath = repository.getWorkTree().getAbsolutePath();
      File dirToDelete = new File(absolutePath);
      FileUtils.deleteDirectory(dirToDelete);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  
  GitAccess.getInstance().cleanUp();
}
 
Example 18
Project: flow-platform   File: SyncServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void load() {
    final List<Repository> gitRepos = gitService.repos();
    repos = new HashSet<>(gitRepos.size());

    for (Repository repo : gitRepos) {
        try {
            List<String> tags = JGitUtil.tags(repo);
            String gitRepoName = repo.getDirectory().getName();

            // git repo needs tags
            if (tags.isEmpty()) {
                LOGGER.warn("Git repo '%s' cannot be synced since missing tag", gitRepoName);
                continue;
            }

            gitRepoName = StringUtil.trimEnd(gitRepoName, ".git");
            repos.add(new SyncRepo(gitRepoName, tags.get(0)));
        } catch (GitException e) {
            LOGGER.warn(e.getMessage());
        } finally {
            repo.close();
        }
    }
}
 
Example 19
Project: RefDiff   File: GitHistoryStructuralDiffAnalyzer.java   Source Code and License 5 votes vote down vote up
public void fetchAndDetectNew(Repository repository, final StructuralDiffHandler handler) throws Exception {
	GitService gitService = new GitServiceImpl() {
		@Override
		public boolean isCommitAnalyzed(String sha1) {
			return handler.skipCommit(sha1);
		}
	};
	RevWalk walk = gitService.fetchAndCreateNewRevsWalk(repository);
	try {
		detect(gitService, repository, handler, walk.iterator());
	} finally {
		walk.dispose();
	}
}
 
Example 20
Project: oxygen-git-plugin   File: GitTestBase.java   Source Code and License 5 votes vote down vote up
/**
 * Binds the local repository to the remote one.
 * 
 * @param localRepository The local repository.
 * @param remoteRepo The remote repository.
 * 
 * @throws NoRepositorySelected
 * @throws URISyntaxException
 * @throws MalformedURLException
 * @throws IOException
 */
protected void bindLocalToRemote(Repository localRepository, Repository remoteRepo)
    throws NoRepositorySelected, URISyntaxException, MalformedURLException, IOException {
  
  StoredConfig config = localRepository.getConfig();
  RemoteConfig remoteConfig = new RemoteConfig(config, "origin");
  URIish uri = new URIish(remoteRepo.getDirectory().toURI().toURL());
  remoteConfig.addURI(uri);
  RefSpec spec = new RefSpec("+refs/heads/*:refs/remotes/origin/*");
  remoteConfig.addFetchRefSpec(spec);
  remoteConfig.update(config);
  config.save();
  
  remoteRepos.add(remoteRepo);
}
 
Example 21
Project: smart-testing   File: EmbeddedHttpGitServer.java   Source Code and License 5 votes vote down vote up
/**
 * To allow performing push operations from the cloned repository to remote (served by this server) let's
 * skip authorization for HTTP.
 */
private void enableInsecureReceiving(Repository repository) {
    final StoredConfig config = repository.getConfig();
    config.setBoolean("http", null, "receivepack", true);
    try {
        config.save();
    } catch (IOException e) {
        throw new RuntimeException("Unable to save http.receivepack=true config", e);
    }
}
 
Example 22
Project: n4js   File: WorkspaceRepositoriesProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the set of repositories that are currently associated with workspace projects.
 */
public Set<Repository> getWorkspaceRepositories() {
	knownRepositories = getWorkspaceProjects().stream()
			.filter(p -> p.isOpen()) // do not include project mapping for closed projects
			.map(GitProjectData::get) // get project data for project
			.filter(Objects::nonNull) // filter null project data (no project associated or not yet initialized)
			.map(WorkspaceRepositoriesProvider::getOfProjectData) // get mapping for project
			.map(RepositoryMapping::getRepository) // get repository of mapping
			.collect(Collectors.toSet()); // return set of distinct repositories

	return knownRepositories;
}
 
Example 23
Project: incubator-netbeans   File: JGitUtils.java   Source Code and License 5 votes vote down vote up
public static RepositoryInfo.PushMode getPushMode (File root) {
    Repository repository = getRepository(root);
    if (repository != null) {
        try {
            String val = repository.getConfig().getString("push", null, "default"); //NOI18N
            if ("upstream".equals(val)) { //NOI18N
                return PushMode.UPSTREAM;
            }
        } finally {
            repository.close();
        }
    }
    return PushMode.ASK;
}
 
Example 24
Project: RefDiff   File: GitServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public RevCommit resolveCommit(Repository repository, String commitId) throws Exception {
    ObjectId oid = repository.resolve(commitId);
    if (oid == null) {
        return null;
    }
    try (RevWalk rw = new RevWalk(repository)) {
        return rw.parseCommit(oid);
    } catch (MissingObjectException e) {
    	return null;
    }
   }
 
Example 25
Project: flow-platform   File: JGitUtilTest.java   Source Code and License 5 votes vote down vote up
@Test
public void should_init_git_with_bare() throws Throwable {
    File gitDir = folder.newFolder("hello.git");
    JGitUtil.init(gitDir.toPath(), true);
    Assert.assertTrue(gitDir.exists());

    Repository repo = JGitUtil.getRepo(gitDir.toPath());
    Assert.assertNotNull(repo);
}
 
Example 26
Project: flow-platform   File: JGitUtil.java   Source Code and License 5 votes vote down vote up
public static Repository getRepo(Path path) throws GitException {
    try (Git git = Git.open(path.toFile())) {
        return git.getRepository();
    } catch (IOException e) {
        throw new GitException(e.getMessage());
    }
}
 
Example 27
Project: RefDiff   File: Example1.java   Source Code and License 5 votes vote down vote up
public static Repository open(File folder) throws IOException {
	RepositoryBuilder builder = new RepositoryBuilder();
	return builder
		.setGitDir(new File(folder, ".git"))
		.readEnvironment()
		.findGitDir()
		.build();
}
 
Example 28
Project: incubator-netbeans   File: IgnoreUnignoreCommand.java   Source Code and License 5 votes vote down vote up
private File getGlobalExcludeFile () {
    Repository repository = getRepository();
    String path = repository.getConfig().get(CoreConfig.KEY).getExcludesFile();
    File excludesfile = null;
    FS fs = repository.getFS();
    if (path != null) {
        if (path.startsWith("~/")) {
            excludesfile = fs.resolve(fs.userHome(), path.substring(2));
        } else {
            excludesfile = fs.resolve(null, path);
        }
    }
    return excludesfile;
}
 
Example 29
Project: RefDiff   File: TestPerformance.java   Source Code and License 5 votes vote down vote up
private void process(String fullName, String branch, String folder, ProcessCommitFn processCommitFn) {
    GitService gitService = new GitServiceImpl();
    try (
        Repository repository = gitService.cloneIfNotExists(folder, "https://github.com/" + fullName + ".git");
        RevWalk walk = gitService.createAllRevsWalk(repository, branch);) {

        DbRepository dbRepository = repositoryDao.findOneByFullName(fullName);
        if (dbRepository == null) {
            dbRepository = repositoryDao.save(new DbRepository(fullName));
        }
        for (RevCommit commit : walk) {
            LocalDateTime ldt = LocalDateTime.ofEpochSecond(commit.getCommitTime(), 0, ZoneOffset.UTC);
            int parentsCount = commit.getParents().length;
            if (ldt.isAfter(LocalDateTime.of(2017, 1, 1, 0, 0)) && parentsCount == 1) {
                String sha1 = commit.getId().getName();
                DbCommit dbCommit = commitDao.findOneByRepositoryAndSha1(dbRepository, sha1);
                if (dbCommit == null) {
                    dbCommit = commitDao.save(new DbCommit(dbRepository, sha1));
                }
                if (dbCommit.getAffectedFiles() == null) {
                    List<String> javaFiles = new ArrayList<>();
                    Map<String, String> renamed = new HashMap<>();
                    gitService.fileTreeDiff(repository, commit, javaFiles, javaFiles, renamed, false);
                    Set<String> distinctFiles = new HashSet<>(javaFiles);
                    dbCommit.setAffectedFiles(distinctFiles.size());
                    commitDao.save(dbCommit);
                }
                processCommitFn.processCommit(repository, commit, dbCommit);
            }
        }
        gitService.checkout(repository, branch);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}
 
Example 30
Project: incubator-netbeans   File: SubmoduleInitializeCommand.java   Source Code and License 5 votes vote down vote up
public SubmoduleInitializeCommand (Repository repository, GitClassFactory classFactory,
        File[] roots, ProgressMonitor monitor) {
    super(repository, classFactory, monitor);
    this.roots = roots;
    this.statusCmd = new SubmoduleStatusCommand(repository,
                getClassFactory(), roots, new DelegatingGitProgressMonitor(monitor));
}
 
Example 31
Project: github-bucket   File: RepositoryS3.java   Source Code and License 5 votes vote down vote up
public RepositoryS3(Bucket bucket, Repository repository, AmazonS3 s3, Branch branch) {
    this.s3 = s3;
    this.bucket = bucket;
    this.repository = repository;
    this.branch = branch;
    this.uri = new URIish().setScheme("amazon-s3").setHost(bucket.getName()).setPath(Constants.DOT_GIT);
}
 
Example 32
Project: RefDiff   File: GitHelper.java   Source Code and License 5 votes vote down vote up
public Repository openRepository(String repositoryPath) throws Exception {
	File folder = new File(repositoryPath);
	Repository repository;
	if (folder.exists()) {
		RepositoryBuilder builder = new RepositoryBuilder();
		repository = builder
			.setGitDir(new File(folder, ".git"))
			.readEnvironment()
			.findGitDir()
			.build();
	} else {
		throw new FileNotFoundException(repositoryPath);
	}
	return repository;
}
 
Example 33
Project: incubator-netbeans   File: CheckoutIndexCommand.java   Source Code and License 5 votes vote down vote up
public CheckoutIndexCommand (Repository repository, GitClassFactory gitFactory, File[] roots, boolean recursively, ProgressMonitor monitor, FileListener listener) {
    super(repository, gitFactory, monitor);
    this.roots = roots;
    this.listener = listener;
    this.monitor = monitor;
    this.recursively = recursively;
}
 
Example 34
Project: oxygen-git-plugin   File: ChangesPanel.java   Source Code and License 5 votes vote down vote up
/**
 * @return the current repository or <code>null</code> if there's no repository selected.
 */
private Repository getCurrentRepository() {
  Repository repo = null;
  try {
    repo = GitAccess.getInstance().getRepository();
   } catch (NoRepositorySelected e) {
     if (logger.isDebugEnabled()) {
       logger.debug(e, e);
     }
   }
  return repo;
}
 
Example 35
Project: incubator-netbeans   File: SetUpstreamBranchCommand.java   Source Code and License 5 votes vote down vote up
private void setupRebaseFlag (Repository repository) throws IOException {
    StoredConfig config = repository.getConfig();
    String autosetupRebase = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION,
            null, ConfigConstants.CONFIG_KEY_AUTOSETUPREBASE);
    boolean rebase = ConfigConstants.CONFIG_KEY_ALWAYS.equals(autosetupRebase)
            || ConfigConstants.CONFIG_KEY_REMOTE.equals(autosetupRebase);
    if (rebase) {
        config.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, localBranchName,
                ConfigConstants.CONFIG_KEY_REBASE, rebase);
    }
}
 
Example 36
Project: incubator-netbeans   File: CherryPickCommand.java   Source Code and License 5 votes vote down vote up
private List<GitRevisionInfo> toCommits (List<Ref> cherryPickedRefs) {
    List<GitRevisionInfo> commits = new ArrayList<>(cherryPickedRefs.size());
    Repository repository = getRepository();
    RevWalk walk = new RevWalk(repository);
    for (Ref ref : cherryPickedRefs) {
        try {
            commits.add(getClassFactory().createRevisionInfo(Utils.findCommit(repository,
                    ref.getLeaf().getObjectId(), walk), repository));
        } catch (GitException ex) {
            Logger.getLogger(CherryPickCommand.class.getName()).log(Level.INFO, null, ex);
        }
    }
    return commits;
}
 
Example 37
Project: gmds   File: Commands.java   Source Code and License 5 votes vote down vote up
/**
     *
     * @param repo
     * @param blobId
     * @return
     * @throws LargeObjectException
     * @throws IOException
     */
    public static byte[] getObjectFromRepo(Repository repo, ObjectId blobId) throws LargeObjectException, IOException {
        ObjectReader objectReader = repo.newObjectReader();
        ObjectLoader objectLoader = objectReader.open(blobId);
//        int type = objectLoader.getType(); // Constants.OBJ_BLOB
        byte[] bytes = objectLoader.getBytes();

        return bytes;
    }
 
Example 38
Project: incubator-netbeans   File: CherryPickCommand.java   Source Code and License 5 votes vote down vote up
private void writeTodoFile (Repository repository, List<RebaseTodoLine> steps) throws IOException {
    File f = new File(repository.getDirectory(), SEQUENCER);
    if (f.canWrite()) {
        RebaseTodoFile todoFile = new RebaseTodoFile(repository);
        todoFile.writeRebaseTodoFile(SEQUENCER + File.separator + SEQUENCER_TODO, steps, false);
    }
}
 
Example 39
Project: incubator-netbeans   File: CherryPickCommand.java   Source Code and License 5 votes vote down vote up
private List<RebaseTodoLine> readTodoFile (Repository repository) throws IOException {
    String path = SEQUENCER + File.separator + SEQUENCER_TODO;
    File f = new File(repository.getDirectory(), path);
    if (f.canRead()) {
        RebaseTodoFile todoFile = new RebaseTodoFile(repository);
        return todoFile.readRebaseTodo(SEQUENCER + File.separator + SEQUENCER_TODO, true);
    }
    return Collections.<RebaseTodoLine>emptyList();
}
 
Example 40
Project: smart-testing   File: GitServerClassLevelRuleTest.java   Source Code and License 5 votes vote down vote up
@Test
public void should_clone_second_repository_using_http_call_and_custom_port_through_rule() throws Exception {
    // when
    gitCloner = new GitCloner("http://localhost:6655/launchpad");
    final Repository repository = gitCloner.cloneRepositoryToTempFolder();

    // then
    assertThat(new File(repository.getDirectory().getParent(), "config.yaml")).exists();
}
 
Example 41
Project: incubator-netbeans   File: CherryPickCommand.java   Source Code and License 5 votes vote down vote up
@Override
public ThreeWayMerger newMerger (Repository db, boolean inCore) {
    return new RecursiveMerger(db, inCore) {
        protected boolean mergeTreeWalk (TreeWalk treeWalk, boolean ignoreConflicts)
                throws IOException {
            boolean ok = true;
            boolean hasWorkingTreeIterator = tw.getTreeCount() > T_FILE;
            while (treeWalk.next()) {
                if (!processEntry(
                        treeWalk.getTree(T_BASE, CanonicalTreeParser.class),
                        treeWalk.getTree(T_OURS, CanonicalTreeParser.class),
                        treeWalk.getTree(T_THEIRS, CanonicalTreeParser.class),
                        treeWalk.getTree(T_INDEX, DirCacheBuildIterator.class),
                        hasWorkingTreeIterator ? treeWalk.getTree(T_FILE,
                                        WorkingTreeIterator.class) : null, ignoreConflicts)) {
                    ok = false;
                }
                if (treeWalk.isSubtree() && enterSubtree) {
                    treeWalk.enterSubtree();
                }
            }
            if (!ok) {
                cleanUp();
            }
            return ok;
        }
    };
}
 
Example 42
Project: RefDiff   File: RefDiffExample.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    RefDiff refDiff = new RefDiff();
    GitService gitService = new GitServiceImpl(); 
    try (Repository repository = gitService.cloneIfNotExists("C:/tmp/clojure", "https://github.com/refdiff-data/clojure.git")) {
        List<SDRefactoring> refactorings = refDiff.detectAtCommit(repository, "17217a1");
        for (SDRefactoring refactoring : refactorings) {
            System.out.println(refactoring.toString());
        }
    }
}
 
Example 43
Project: oxygen-git-plugin   File: GitAccess.java   Source Code and License 5 votes vote down vote up
/**
 * Finds the base commit from the last local commit and the remote commit
 * 
 * @param branchInfo Current branch info or <code>null</code> if unknown.
 * 
 * @return the base commit
 */
public ObjectId getBaseCommit(BranchInfo branchInfo) {
  if (branchInfo == null) {
    branchInfo = getBranchInfo();
  }
	Repository repository = git.getRepository();
	RevWalk walk = new RevWalk(repository);
	ObjectId localCommit = null;
	ObjectId remoteCommit = null;
	ObjectId baseCommit = null;
	try {
		remoteCommit = repository.resolve("origin/" + branchInfo.getBranchName() + "^{commit}");
		localCommit = repository.resolve("HEAD^{commit}");
		if (remoteCommit != null && localCommit != null) {
			RevCommit base = getCommonAncestor(walk, walk.parseCommit(localCommit), walk.parseCommit(remoteCommit));
			if (base != null) {
				baseCommit = base.toObjectId();
			}
		}
	} catch (IOException e) {
		if (logger.isDebugEnabled()) {
			logger.debug(e, e);
		}
	}
	walk.close();
	return baseCommit;
}
 
Example 44
Project: incubator-netbeans   File: StashSaveCommand.java   Source Code and License 5 votes vote down vote up
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    try {
        StashCreateCommand cmd = new Git(repository).stashCreate()
                .setIncludeUntracked(includeUntracked)
                .setWorkingDirectoryMessage(message);
        RevCommit commit = cmd.call();
        this.stash = getClassFactory().createRevisionInfo(commit, repository);
    } catch (GitAPIException ex) {
        throw new GitException(ex);
    }
}
 
Example 45
Project: oxygen-git-plugin   File: TreeViewTest.java   Source Code and License 5 votes vote down vote up
/**
 * <p><b>Description:</b> stage / unstage folder.</p>
 * <p><b>Bug ID:</b> EXM-40615</p>
 *
 * @author sorin_carbunaru
 *
 * @throws Exception
 */
public void testStageUnstage_Folder() throws Exception {
  String localTestRepository = "target/test-resources/testStageUnstage_Folder_local";
  String remoteTestRepository = "target/test-resources/testStageUnstage_Folder_remote";
  
  // Create a new test file.
  new File(localTestRepository).mkdirs();
  new File(localTestRepository + "/folder").mkdirs();
  File file = new File(localTestRepository + "/folder/test.txt");
  file.createNewFile();
  
  // Create repositories
  Repository remoteRepo = createRepository(remoteTestRepository);
  Repository localRepo = createRepository(localTestRepository);
  // Bind the local repository to the remote one.
  bindLocalToRemote(localRepo , remoteRepo);
  
  // The newly created file is present in the model.
  assertTreeModels("UNTRACKED, folder/test.txt", "");

  //---------------
  // Stage.
  //---------------
  change(true, "folder");
  assertTreeModels("", "ADD, folder/test.txt");

  //---------------
  // Back to unStaged
  //---------------
  change(false, "folder");
  assertTreeModels("UNTRACKED, folder/test.txt", "");
}
 
Example 46
Project: RefDiff   File: GitHistoryStructuralDiffAnalyzer.java   Source Code and License 5 votes vote down vote up
public void detectAll(Repository repository, String branch, final StructuralDiffHandler handler) throws Exception {
	GitService gitService = new GitServiceImpl() {
		@Override
		public boolean isCommitAnalyzed(String sha1) {
			return handler.skipCommit(sha1);
		}
	};
	RevWalk walk = gitService.createAllRevsWalk(repository, branch);
	try {
		detect(gitService, repository, handler, walk.iterator());
	} finally {
		walk.dispose();
	}
}
 
Example 47
Project: incubator-netbeans   File: SubmoduleUpdateCommand.java   Source Code and License 5 votes vote down vote up
public SubmoduleUpdateCommand (Repository repository, GitClassFactory classFactory,
        File[] roots, ProgressMonitor monitor) {
    super(repository, classFactory, "origin", monitor);
    this.monitor = monitor;
    this.roots = roots;
    this.statusCmd = new SubmoduleStatusCommand(repository,
                getClassFactory(), roots, new DelegatingGitProgressMonitor(monitor));
}
 
Example 48
Project: RefDiff   File: RunCalibration.java   Source Code and License 5 votes vote down vote up
private RefactoringSet runRefDiff(String project, String commit) throws Exception {
	RefactoringSet rs = new RefactoringSet(project, commit);
	
	String basePath = "C:/tmp/";
	String repoFolder = project.substring(project.lastIndexOf('/') + 1, project.lastIndexOf('.'));
	String checkoutFolder = repoFolder + "-" + commit.substring(0, 7) + "/";
	String checkoutFolderV0 = basePath + "v0/" + checkoutFolder;
	String checkoutFolderV1 = basePath + "v1/" + checkoutFolder;
	
	GitHelper gitHelper = new GitHelper();
	try (
		Repository repo = gitHelper.openRepository(basePath + repoFolder);
		RevWalk rw = new RevWalk(repo)) {
		
		RevCommit revCommit = rw.parseCommit(repo.resolve(commit));
		rw.parseCommit(revCommit.getParent(0));
		
		List<String> filesV0 = new ArrayList<>();
		List<String> filesV1 = new ArrayList<>();
		Map<String, String> renamedFilesHint = new HashMap<>();
		
		gitHelper.fileTreeDiff(repo, revCommit, filesV0, filesV1, renamedFilesHint, false);
		
		System.out.println(String.format("Computing diff for %s %s", project, commit));
		RastDiff diff = comparator.compare(getSourceFiles(checkoutFolderV0, filesV0), getSourceFiles(checkoutFolderV1, filesV1));
		
		for (Relationship rel : diff.getRelationships()) {
			RelationshipType relType = rel.getType();
			String nodeType = rel.getNodeAfter().getType();
			Optional<RefactoringType> refType = getRefactoringType(relType, nodeType);
			if (refType.isPresent()) {
				String keyN1 = JavaParser.getKey(rel.getNodeBefore());
				String keyN2 = JavaParser.getKey(rel.getNodeAfter());
				rs.add(refType.get(), keyN1, keyN2);
			}
		}
	}
	
	return rs;
}
 
Example 49
Project: incubator-netbeans   File: CheckoutIndex.java   Source Code and License 5 votes vote down vote up
public CheckoutIndex (Repository repository, DirCache cache, File[] roots, boolean recursively, FileListener listener, ProgressMonitor monitor, boolean checkContent) {
    this.repository = repository;
    this.cache = cache;
    this.roots = roots;
    this.listener = listener;
    this.monitor = monitor;
    this.checkContent = checkContent;
    this.recursively = recursively;
}
 
Example 50
Project: incubator-netbeans   File: RevertCommand.java   Source Code and License 5 votes vote down vote up
public RevertCommand (Repository repository, GitClassFactory gitFactory, String revision, String message, boolean commit, ProgressMonitor monitor) {
    super(repository, gitFactory, monitor);
    this.monitor = monitor;
    this.revisionStr = revision;
    this.message = message;
    this.commit = commit;
}
 
Example 51
Project: gitplex-mit   File: DepthWalk.java   Source Code and License 5 votes vote down vote up
/**
 * @param repo Repository to walk
 * @param depth Maximum depth to return
 */
public RevWalk(Repository repo, int depth) {
	super(repo);

	this.depth = depth;
	this.UNSHALLOW = newFlag("UNSHALLOW"); //$NON-NLS-1$
	this.REINTERESTING = newFlag("REINTERESTING"); //$NON-NLS-1$
}
 
Example 52
Project: gitplex-mit   File: GitUtils.java   Source Code and License 5 votes vote down vote up
/**
   * @return
   * 			merge base of specified commits, or <tt>null</tt> if two commits do not have related history. In this 
   * 			case, these two commits can not be merged
   */
  @Nullable
  public static ObjectId getMergeBase(Repository repository, ObjectId commit1, ObjectId commit2) {
try (RevWalk revWalk = new RevWalk(repository)) {
	revWalk.setRevFilter(RevFilter.MERGE_BASE);
	
	revWalk.markStart(revWalk.parseCommit(commit1));
	revWalk.markStart(revWalk.parseCommit(commit2));
	RevCommit mergeBase = revWalk.next();
	return mergeBase!=null?mergeBase.copy():null;
} catch (IOException e) {
	throw new RuntimeException(e);
} 			
  }
 
Example 53
Project: incubator-netbeans   File: CatCommand.java   Source Code and License 5 votes vote down vote up
public CatCommand (Repository repository, GitClassFactory gitFactory, File file, int stage, OutputStream out, ProgressMonitor monitor) {
    super(repository, gitFactory, monitor);
    this.file = file;
    this.revision = null;
    this.os = out;
    this.monitor = monitor;
    this.fromRevision = false;
    this.stage = stage;
}
 
Example 54
Project: incubator-netbeans   File: ExportCommitCommand.java   Source Code and License 5 votes vote down vote up
public ExportCommitCommand (Repository repository, GitClassFactory gitFactory, String revisionStr, OutputStream out, ProgressMonitor monitor, FileListener listener) {
    super(repository, gitFactory, monitor);
    this.monitor = monitor;
    this.listener = listener;
    this.out = out;
    this.revisionStr = revisionStr;
}
 
Example 55
Project: cf-mta-deploy-service   File: GitRepoCloner.java   Source Code and License 5 votes vote down vote up
public void cloneRepo(final String gitUri, final Path repoDir) throws InvalidRemoteException, GitAPIException, IOException {
    if (Files.exists(repoDir)) {
        LOGGER.debug("Deleting left-over repo dir" + repoDir.toAbsolutePath().toString());
        com.sap.cloud.lm.sl.cf.core.util.FileUtils.deleteDirectory(repoDir);
    }

    configureGitSslValidation();
    if (shoudlUseToken(gitServiceUrlString, gitUri)) {
        cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, token));
    }
    if (refName != null && !refName.isEmpty()) {
        String fullRefName = refName.startsWith("refs/") ? refName : "refs/heads/" + refName;
        cloneCommand.setBranchesToClone(Arrays.asList(new String[] { fullRefName }));
        cloneCommand.setBranch(fullRefName);
    }
    cloneCommand.setTimeout(290);
    cloneCommand.setDirectory(repoDir.toAbsolutePath().toFile());
    cloneCommand.setURI(gitUri);
    LOGGER.debug(
        MessageFormat.format("cloning repo with url {0} in repo dir {1} ref '{2}'", gitUri, repoDir.toAbsolutePath().toString()));
    try (Git callInstance = cloneCommand.call()) {
        Repository repo = callInstance.getRepository();
        repo.close();
    } catch (TransportException e) {
        Throwable cause1 = e.getCause();
        if (cause1 != null && cause1.getCause() instanceof SSLHandshakeException) {
            throw new SLException(cause1.getCause(), "Failed to establish ssl connection"); // NOSONAR
        }
        throw e;
    }
}
 
Example 56
Project: gmds   File: Commands.java   Source Code and License 5 votes vote down vote up
/**
 * 
 * @param repo
 * @param lastCommitId
 * @return
 * @throws LargeObjectException
 * @throws IOException 
 */
public static ObjectId getLastCommitTreeId(Repository repo, ObjectId lastCommitId) throws LargeObjectException, IOException {

    if (lastCommitId == null) {
        return null;
    } else {
        ObjectReader objectReader = repo.newObjectReader();
        ObjectLoader objectLoader = objectReader.open(lastCommitId);
        RevCommit oldCommit = RevCommit.parse(objectLoader.getBytes());

        return oldCommit.getTree().getId();
    }
}
 
Example 57
Project: incubator-netbeans   File: LogCommand.java   Source Code and License 5 votes vote down vote up
public LogCommand (Repository repository, GitClassFactory gitFactory, SearchCriteria criteria,
        boolean fetchBranchInfo, ProgressMonitor monitor, RevisionInfoListener listener) {
    super(repository, gitFactory, monitor);
    this.monitor = monitor;
    this.listener = listener;
    this.criteria = criteria;
    this.fetchBranchInfo = fetchBranchInfo;
    this.revision = null;
    this.revisions = new LinkedList<>();
}
 
Example 58
Project: RefDiff   File: GitHelper.java   Source Code and License 4 votes vote down vote up
public Repository cloneIfNotExists(String projectPath, String cloneUrl/* , String branch */) throws Exception {
	File folder = new File(projectPath);
	Repository repository;
	if (folder.exists()) {
		RepositoryBuilder builder = new RepositoryBuilder();
		repository = builder
			.setGitDir(new File(folder, ".git"))
			.readEnvironment()
			.findGitDir()
			.build();
		
		// logger.info("Project {} is already cloned, current branch is {}", cloneUrl, repository.getBranch());
		
	} else {
		Git git = Git.cloneRepository()
			.setDirectory(folder)
			.setURI(cloneUrl)
			.setCloneAllBranches(true)
			.call();
		repository = git.getRepository();
		// logger.info("Done cloning {}, current branch is {}", cloneUrl, repository.getBranch());
	}
	
	// if (branch != null && !repository.getBranch().equals(branch)) {
	// Git git = new Git(repository);
	//
	// String localBranch = "refs/heads/" + branch;
	// List<Ref> refs = git.branchList().call();
	// boolean branchExists = false;
	// for (Ref ref : refs) {
	// if (ref.getName().equals(localBranch)) {
	// branchExists = true;
	// }
	// }
	//
	// if (branchExists) {
	// git.checkout()
	// .setName(branch)
	// .call();
	// } else {
	// git.checkout()
	// .setCreateBranch(true)
	// .setName(branch)
	// .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
	// .setStartPoint("origin/" + branch)
	// .call();
	// }
	//
	// logger.info("Project {} switched to {}", cloneUrl, repository.getBranch());
	// }
	return repository;
}
 
Example 59
Project: gitplex-mit   File: Project.java   Source Code and License 4 votes vote down vote up
public Repository getRepository() {
	if (repository == null) {
		repository = GitPlex.getInstance(ProjectManager.class).getRepository(this);
	}
	return repository;
}
 
Example 60
Project: incubator-netbeans   File: GitCommand.java   Source Code and License 4 votes vote down vote up
protected GitCommand (Repository repository, GitClassFactory gitFactory, ProgressMonitor monitor) {
    this.repository = repository;
    this.gitFactory = gitFactory;
    this.monitor = monitor;
}