List of usage examples for org.eclipse.jgit.lib Repository getDirectory
public File getDirectory()
From source file:io.jenkins.blueocean.blueocean_git_pipeline.GitCacheCloneReadSaveRequest.java
License:Open Source License
private @Nonnull Git getActiveRepository(Repository repository) throws IOException { try {//from ww w .j a v a 2 s. c o m // Clone the bare repository File cloneDir = File.createTempFile("clone", ""); if (cloneDir.exists()) { if (cloneDir.isDirectory()) { FileUtils.deleteDirectory(cloneDir); } else { if (!cloneDir.delete()) { throw new ServiceException.UnexpectedErrorException("Unable to delete repository clone"); } } } if (!cloneDir.mkdirs()) { throw new ServiceException.UnexpectedErrorException("Unable to create repository clone directory"); } String url = repository.getConfig().getString("remote", "origin", "url"); Git gitClient = Git.cloneRepository().setCloneAllBranches(false) .setProgressMonitor(new CloneProgressMonitor(url)) .setURI(repository.getDirectory().getCanonicalPath()).setDirectory(cloneDir).call(); RemoteRemoveCommand remove = gitClient.remoteRemove(); remove.setName("origin"); remove.call(); RemoteAddCommand add = gitClient.remoteAdd(); add.setName("origin"); add.setUri(new URIish(gitSource.getRemote())); add.call(); if (GitUtils.isSshUrl(gitSource.getRemote())) { // Get committer info and credentials User user = User.current(); if (user == null) { throw new ServiceException.UnauthorizedException("Not authenticated"); } BasicSSHUserPrivateKey privateKey = UserSSHKeyManager.getOrCreate(user); // Make sure up-to-date and credentials work GitUtils.fetch(repository, privateKey); } else { FetchCommand fetch = gitClient.fetch(); fetch.call(); } if (!StringUtils.isEmpty(sourceBranch) && !sourceBranch.equals(branch)) { CheckoutCommand checkout = gitClient.checkout(); checkout.setStartPoint("origin/" + sourceBranch); checkout.setName(sourceBranch); checkout.setCreateBranch(true); // to create a new local branch checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK); checkout.call(); checkout = gitClient.checkout(); checkout.setName(branch); checkout.setCreateBranch(true); // this *should* be a new branch checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK); checkout.call(); } else { CheckoutCommand checkout = gitClient.checkout(); checkout.setStartPoint("origin/" + branch); checkout.setName(branch); checkout.setCreateBranch(true); // to create a new local branch checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK); checkout.call(); } return gitClient; } catch (GitAPIException | URISyntaxException ex) { throw new ServiceException.UnexpectedErrorException("Unable to get working repository directory", ex); } }
From source file:jbyoshi.gitupdate.GitUpdate.java
License:Apache License
private static void update(Repository repo, Task root) { File dir = repo.getDirectory(); if (dir.getName().equals(Constants.DOT_GIT)) { dir = dir.getParentFile();/*from www. j ava 2s .c o m*/ } try { dir = dir.toPath().toRealPath().toFile(); } catch (IOException e) { dir = dir.toPath().normalize().toFile(); } if (!updated.add(dir)) { return; } List<String> failures = new ArrayList<>(); try { if (SubmoduleWalk.containsGitModulesFile(repo)) { try (SubmoduleWalk submodules = SubmoduleWalk.forIndex(repo)) { while (submodules.next()) { if (submodules.getRepository() == null) { failures.add("Submodule " + submodules.getDirectory().getName() + " - does not exist"); } else { update(submodules.getRepository(), root); } } } } } catch (IOException e) { e.printStackTrace(); } Task repoTask = root.newChild(dir.getName()); for (String error : failures) { repoTask.report.newChild(error).error(); } try (Git git = Git.wrap(repo)) { for (Processor processor : processors) { try { processor.registerTasks(repo, git, repoTask); } catch (Exception e) { e.printStackTrace(); } } } }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.agent.UpdaterImpl.java
License:Apache License
private void addSubmoduleUsernames(@NotNull File repositoryDir, @NotNull Config gitModules) throws IOException, ConfigInvalidException, VcsException { if (!myPluginConfig.isUseMainRepoUserForSubmodules()) return;//from w ww .j a va 2 s.c o m Loggers.VCS.info("Update submodules credentials"); AuthSettings auth = myRoot.getAuthSettings(); final String userName = auth.getUserName(); if (userName == null) { Loggers.VCS.info("Username is not specified in the main VCS root settings, skip updating credentials"); return; } Repository r = new RepositoryBuilder().setBare().setGitDir(getGitDir(repositoryDir)).build(); StoredConfig gitConfig = r.getConfig(); Set<String> submodules = gitModules.getSubsections("submodule"); if (submodules.isEmpty()) { Loggers.VCS.info("No submodule sections found in " + new File(repositoryDir, ".gitmodules").getCanonicalPath() + ", skip updating credentials"); return; } File modulesDir = new File(r.getDirectory(), Constants.MODULES); for (String submoduleName : submodules) { String url = gitModules.getString("submodule", submoduleName, "url"); Loggers.VCS.info("Update credentials for submodule with url " + url); if (url == null || !isRequireAuth(url)) { Loggers.VCS.info("Url " + url + " does not require authentication, skip updating credentials"); continue; } try { URIish uri = new URIish(url); String updatedUrl = uri.setUser(userName).toASCIIString(); gitConfig.setString("submodule", submoduleName, "url", updatedUrl); String submodulePath = gitModules.getString("submodule", submoduleName, "path"); if (submodulePath != null && myPluginConfig.isUpdateSubmoduleOriginUrl()) { File submoduleDir = new File(modulesDir, submodulePath); if (submoduleDir.isDirectory() && new File(submoduleDir, Constants.CONFIG).isFile()) updateOriginUrl(submoduleDir, updatedUrl); } Loggers.VCS.debug("Submodule url " + url + " changed to " + updatedUrl); } catch (URISyntaxException e) { Loggers.VCS.warn("Error while parsing an url " + url + ", skip updating submodule credentials", e); } catch (Exception e) { Loggers.VCS.warn("Error while updating the '" + submoduleName + "' submodule url", e); } } gitConfig.save(); }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.AutoCloseRepositoryCache.java
License:Apache License
/** * Releases the repository acquired via {@link #add} or {@link #get} method. * Decrements an openCounter for the repository and if it reaches 0 repository * is closed and removed from the cache. Does nothing if repository is not * present found in the cache.// w w w . j av a2s. c o m * @param db repository to release */ synchronized void release(@NotNull Repository db) { RepositoryCache.FileKey key = RepositoryCache.FileKey.exact(db.getDirectory(), FS.DETECTED); CachedRepository cachedRepository = myRepositories.get(key); if (cachedRepository != null && cachedRepository.getRepository() == db && cachedRepository.dec() == 0) { myRepositories.remove(key); db.close(); } }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.CommitLoaderImpl.java
License:Apache License
public void fetch(@NotNull Repository db, @NotNull URIish fetchURI, @NotNull Collection<RefSpec> refspecs, @NotNull FetchSettings settings) throws IOException, VcsException { File repositoryDir = db.getDirectory(); assert repositoryDir != null : "Non-local repository"; Lock rmLock = myRepositoryManager.getRmLock(repositoryDir).readLock(); rmLock.lock();/*from w w w . j a va2 s. c om*/ try { final long start = System.currentTimeMillis(); synchronized (myRepositoryManager.getWriteLock(repositoryDir)) { final long finish = System.currentTimeMillis(); Map<String, Ref> oldRefs = new HashMap<String, Ref>(db.getAllRefs()); PERFORMANCE_LOG.debug("[waitForWriteLock] repository: " + repositoryDir.getAbsolutePath() + ", took " + (finish - start) + "ms"); myFetchCommand.fetch(db, fetchURI, refspecs, settings); Map<String, Ref> newRefs = new HashMap<String, Ref>(db.getAllRefs()); myMapFullPath.invalidateRevisionsCache(db, oldRefs, newRefs); } } finally { rmLock.unlock(); } }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.CommitLoaderImpl.java
License:Apache License
@NotNull public RevCommit getCommit(@NotNull Repository repository, @NotNull ObjectId commitId) throws IOException { final long start = System.currentTimeMillis(); RevWalk walk = new RevWalk(repository); try {// w ww . jav a2 s . co m return walk.parseCommit(commitId); } finally { walk.release(); final long finish = System.currentTimeMillis(); if (PERFORMANCE_LOG.isDebugEnabled()) { PERFORMANCE_LOG .debug("[RevWalk.parseCommit] repository=" + repository.getDirectory().getAbsolutePath() + ", commit=" + commitId.name() + ", took: " + (finish - start) + "ms"); } } }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.FetchCommandImpl.java
License:Apache License
@NotNull private List<Ref> findLockedRefs(@NotNull Repository db) { File refsDir = new File(db.getDirectory(), org.eclipse.jgit.lib.Constants.R_REFS); List<String> lockFiles = new ArrayList<>(); //listFilesRecursively always uses / as a separator, we get valid ref names on all OSes FileUtil.listFilesRecursively(refsDir, "refs/", false, Integer.MAX_VALUE, f -> f.isDirectory() || f.isFile() && f.getName().endsWith(".lock"), lockFiles); Map<String, Ref> allRefs = db.getAllRefs(); List<Ref> result = new ArrayList<>(); for (String lock : lockFiles) { String refName = lock.substring(0, lock.length() - ".lock".length()); Ref ref = allRefs.get(refName); if (ref != null) result.add(ref);/* ww w .ja v a2s .c o m*/ } return result; }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.FetchCommandImpl.java
License:Apache License
private void unlockRef(Repository db, Ref ref) throws IOException, InterruptedException { File refFile = new File(db.getDirectory(), ref.getName()); File refLockFile = new File(db.getDirectory(), ref.getName() + ".lock"); LockFile lock = new LockFile(refFile, FS.DETECTED); try {// w w w . j a va 2s . c o m if (!lock.lock()) { LOG.warn("Cannot lock the ref " + ref.getName() + ", will wait and try again"); Thread.sleep(5000); if (lock.lock()) { LOG.warn("Successfully lock the ref " + ref.getName()); } else { if (FileUtil.delete(refLockFile)) { LOG.warn("Remove ref lock " + refLockFile.getAbsolutePath()); } else { LOG.warn("Cannot remove ref lock " + refLockFile.getAbsolutePath() + ", fetch will probably fail. Please remove lock manually."); } } } } finally { lock.unlock(); } }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.FetchCommandImpl.java
License:Apache License
private void fetchInSeparateProcess(@NotNull Repository repository, @NotNull URIish uri, @NotNull Collection<RefSpec> specs, @NotNull FetchSettings settings) throws VcsException { final long fetchStart = System.currentTimeMillis(); final String debugInfo = getDebugInfo(repository, uri, specs); File gitPropertiesFile = null; File teamcityPrivateKey = null; try {//from ww w . jav a2 s .c om GeneralCommandLine cl = createFetcherCommandLine(repository, uri); if (LOG.isDebugEnabled()) LOG.debug("Start fetch process for " + debugInfo); File threadDump = getThreadDumpFile(repository); gitPropertiesFile = myFetcherProperties.getPropertiesFile(); FetcherEventHandler processEventHandler = new FetcherEventHandler(debugInfo); teamcityPrivateKey = getTeamCityPrivateKey(settings.getAuthSettings()); AuthSettings preparedSettings = settings.getAuthSettings(); if (teamcityPrivateKey != null) { Map<String, String> properties = settings.getAuthSettings().toMap(); properties.put(Constants.AUTH_METHOD, AuthenticationMethod.PRIVATE_KEY_FILE.name()); properties.put(Constants.PRIVATE_KEY_PATH, teamcityPrivateKey.getAbsolutePath()); preparedSettings = new AuthSettings(properties, settings.getAuthSettings().getRoot()); } byte[] fetchProcessInput = getFetchProcessInputBytes(preparedSettings, repository.getDirectory(), uri, specs, threadDump, gitPropertiesFile); ByteArrayOutputStream stdoutBuffer = settings.createStdoutBuffer(); ByteArrayOutputStream stderrBuffer = new ByteArrayOutputStream(); settings.getProgress().reportProgress("git fetch " + uri); ExecResult result = SimpleCommandLineProcessRunner.runCommandSecure(cl, cl.getCommandLineString(), fetchProcessInput, processEventHandler, stdoutBuffer, stderrBuffer); if (PERFORMANCE_LOG.isDebugEnabled()) PERFORMANCE_LOG.debug("[fetch in separate process] root=" + debugInfo + ", took " + (System.currentTimeMillis() - fetchStart) + "ms"); VcsException commandError = CommandLineUtil.getCommandLineError("git fetch", result); if (commandError != null) { if (isOutOfMemoryError(result)) LOG.warn("There is not enough memory for git fetch, teamcity.git.fetch.process.max.memory=" + myConfig.getFetchProcessMaxMemory() + ", try to increase it."); if (isTimeout(result)) logTimeout(debugInfo, threadDump); clean(repository); throw commandError; } if (result.getStderr().length() > 0) { LOG.warn("Error output produced by git fetch:\n" + result.getStderr()); } LOG.debug("Fetch process output:\n" + result.getStdout()); } finally { settings.getProgress().reportProgress("git fetch " + uri + " finished"); if (teamcityPrivateKey != null) FileUtil.delete(teamcityPrivateKey); if (gitPropertiesFile != null) FileUtil.delete(gitPropertiesFile); } }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.FetchCommandImpl.java
License:Apache License
private File getMonitoringDir(@NotNull Repository repository) { return new File(repository.getDirectory(), myConfig.getMonitoringDirName()); }