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 = ""; } }
@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(); } } }); }
@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(); } } }
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; }
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; }
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(); }
@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); } }
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))); }
/** * * @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()); } } }
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; }
@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); } }
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()); } }
@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); } }
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); } }
@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(); }
@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(); } } }
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(); } }
/** * 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); }
/** * 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); } }
/** * 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; }
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; }
@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; } }
@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); }
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()); } }
public static Repository open(File folder) throws IOException { RepositoryBuilder builder = new RepositoryBuilder(); return builder .setGitDir(new File(folder, ".git")) .readEnvironment() .findGitDir() .build(); }
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; }
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); } }
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)); }
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); }
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; }
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; }
/** * @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; }
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); } }
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; }
/** * * @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; }
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); } }
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(); }
@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(); }