@Override 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 GitVersionControl(Path path) throws IOException { try { // Cribbed from Git.open, but with findGitDir rather than setGitDir // and extracting the location. FS fs = FS.DETECTED; RepositoryCache.FileKey key = RepositoryCache.FileKey.lenient(path.toFile(), fs); RepositoryBuilder builder = new RepositoryBuilder() .setFS(fs) .findGitDir(key.getFile()) .setMustExist(true); repositoryRoot = Paths.get(builder.getGitDir().getAbsolutePath()).getParent(); repo = new Git(builder.build()); checkMergeDriver(repositoryRoot); } catch (RuntimeException ex) { throw new IOException(ex); } }
/** * @param gitConfigFolder e.g. /your/project/root/.git * * @return Returns last commit's UUID, "nocommit" if there are no commits and returns null if an exception occured */ public static String getLastCommitUuid( String gitConfigFolder ) throws MojoExecutionException { try { Repository repo = new RepositoryBuilder().setGitDir( new File( gitConfigFolder ) ).readEnvironment().findGitDir() .build(); RevWalk walk = new RevWalk( repo ); ObjectId head = repo.resolve( "HEAD" ); if ( head != null ) { RevCommit lastCommit = walk.parseCommit( head ); return lastCommit.getId().getName(); } else { return "nocommit"; } } catch ( Exception e ) { throw new MojoExecutionException( "Error trying to get the last git commit uuid", e ); } }
/** {@inheritDoc} */ @Deprecated public boolean isBareRepository(String GIT_DIR) throws GitException, InterruptedException { Repository repo = null; boolean isBare = false; if (GIT_DIR == null) { throw new GitException("Not a git repository"); // Compatible with CliGitAPIImpl } try { if (isBlank(GIT_DIR) || !(new File(GIT_DIR)).isAbsolute()) { if ((new File(workspace, ".git")).exists()) { repo = getRepository(); } else { repo = new RepositoryBuilder().setGitDir(workspace).build(); } } else { repo = new RepositoryBuilder().setGitDir(new File(GIT_DIR)).build(); } isBare = repo.isBare(); } catch (IOException ioe) { throw new GitException(ioe); } finally { if (repo != null) repo.close(); } return isBare; }
private static boolean exist(File repoDir) { try { RepositoryBuilder repositoryBuilder = new RepositoryBuilder().setGitDir(repoDir); org.eclipse.jgit.lib.Repository repository = repositoryBuilder.build(); if (repository.getConfig() instanceof FileBasedConfig) { return ((FileBasedConfig) repository.getConfig()).getFile().exists(); } return repository.getDirectory().exists(); } catch (IOException e) { throw new StorageException("failed to check if repository exists at " + repoDir, e); } }
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 static Repository open(File folder) throws IOException { RepositoryBuilder builder = new RepositoryBuilder(); return builder .setGitDir(new File(folder, ".git")) .readEnvironment() .findGitDir() .build(); }
private List<Repository> findRegisteredRepositories() { final RepositoryUtil util = Activator.getDefault().getRepositoryUtil(); final List<String> repositoryFolders = util.getConfiguredRepositories(); final List<Repository> repositories = new ArrayList<Repository>(); for (final String repositoryFolder : repositoryFolders) { final File folder = new File(repositoryFolder); if (!folder.exists() || !folder.isDirectory()) { continue; } if (!folder.getName().equals(Constants.DOT_GIT) || !FileKey.isGitRepository(folder, FS.DETECTED)) { continue; } final RepositoryBuilder rb = new RepositoryBuilder().setGitDir(folder).setMustExist(true); try { repositories.add(rb.build()); } catch (final Exception e) { log.error("Error loading Git repository " + repositoryFolder, e); //$NON-NLS-1$ continue; } } return repositories; }
private void loadRegisteredRepositories() { repositoryMap = new TreeMap<String, Repository>(); final List<String> repositoryFolders = Activator.getDefault().getRepositoryUtil().getConfiguredRepositories(); for (final String repositoryFolder : repositoryFolders) { final File folder = new File(repositoryFolder); if (!folder.exists() || !folder.isDirectory()) { continue; } if (!folder.getName().equals(Constants.DOT_GIT) || !FileKey.isGitRepository(folder, FS.DETECTED)) { continue; } final RepositoryBuilder rb = new RepositoryBuilder().setGitDir(folder).setMustExist(true); try { final Repository repo = rb.build(); final StoredConfig repositoryConfig = repo.getConfig(); final Set<String> remotes = repositoryConfig.getSubsections(REMOTES_SECTION_NAME); for (final String remoteName : remotes) { final String remoteURL = repositoryConfig.getString(REMOTES_SECTION_NAME, remoteName, URL_VALUE_NAME); repositoryMap.put(remoteURL, repo); } } catch (final Exception e) { log.error("Error loading local Git repository " + repositoryFolder, e); //$NON-NLS-1$ continue; } } }
/** * Function used to treat pack object, it load the data from each object of * the pack to create the original object when the object is recreate it * store the object into the git object index * * @author Sylvain * * @param pathPack * the path of the pack file * @throws IOException * @throws DataFormatException */ public static void makePack(String pathPack) throws IOException, DataFormatException { String[] path = pathPack.split(osBarre + ".git" + osBarre); RepositoryBuilder builder = new RepositoryBuilder(); builder.setMustExist(true); builder.setGitDir(new File(path[0] + osBarre + ".git" + osBarre)); Repository repository = builder.build(); for (MutableEntry mutableEntry : new PackFile(new File(pathPack), 0)) { GitObject obj = null; String sha1 = mutableEntry.toObjectId().name(); ObjectId id = repository.resolve(sha1); ObjectLoader loader = repository.open(id); switch (loader.getType()) { case Constants.OBJ_BLOB: obj = new GitBlob(loader.getSize(), sha1, "", loader.getCachedBytes()); break; case Constants.OBJ_COMMIT: obj = new GitCommit(loader.getSize(), sha1, new String(loader.getCachedBytes())); break; case Constants.OBJ_TREE: obj = new GitTree(loader.getSize(), sha1, loader.getBytes()); break; case Constants.OBJ_TAG: obj = new GitTag(loader.getSize(), sha1, new String(loader.getCachedBytes())); break; default: break; } GitObjectsIndex.getInstance().put(mutableEntry.toObjectId().name(), obj); } }
@Override public String revisionId(Path path) { RepositoryBuilder builder = getVerifiedRepositoryBuilder(path); try { return builder.build().exactRef("HEAD").getObjectId().getName(); } catch (IOException e) { throw new IllegalStateException("I/O error while getting revision ID for path: " + path, e); } }
static RepositoryBuilder getVerifiedRepositoryBuilder(Path basedir) { RepositoryBuilder builder = new RepositoryBuilder() .findGitDir(basedir.toFile()) .setMustExist(true); if (builder.getGitDir() == null) { throw MessageException.of("Not inside a Git work tree: " + basedir); } return builder; }
public GitUtil(File f) { try { File workspace = findWorkspaceRoot(f); if (workspace==null) { throw new IllegalStateException("Does not appear to be a Git workspace: "+f.getCanonicalPath()); } Repository r = new RepositoryBuilder().setWorkTree(findWorkspaceRoot(f)).build(); git = new Git(r); } catch (IOException e) { throw new AstException(e); } }
public Git load() throws IOException { try (Repository repository = new RepositoryBuilder().findGitDir(this.sourceDirectory).build()) { Git.Head head = getHead(repository); String branch = getBranch(repository); List<Git.Remote> remotes = getRemotes(repository); return new Git(repository.getWorkTree(), head, branch, remotes); } }
/** * @param gitConfigFolder e.g. /your/project/root/.git * * @return Returns git config remote.origin.url field of the repository located at gitConfigFolder */ public static String getGitRemoteUrl( String gitConfigFolder ) throws MojoExecutionException { try { Repository repo = new RepositoryBuilder().setGitDir( new File( gitConfigFolder ) ).readEnvironment().findGitDir() .build(); Config config = repo.getConfig(); return config.getString( "remote", "origin", "url" ); } catch ( Exception e ) { throw new MojoExecutionException( "Error trying to get remote origin url of git repository", e ); } }
@Override public final void execute() { try { try { Repository repository = new RepositoryBuilder(). readEnvironment(). findGitDir(getDirectory()). build(); git = new Git(repository); } catch (IOException ioe) { String errorMsg = "Specified path (%s) doesn't seem to be a git repository."; throw new BuildException(String.format(errorMsg, getDirectory().getAbsolutePath()), ioe); } doExecute(); } catch (GitBuildException e) { log(e, Project.MSG_ERR); if (failOnError) { throw new BuildException(e); } } finally { if (git != null) { git.getRepository().close(); } } }
/** * getRepository. * * @return a {@link org.eclipse.jgit.lib.Repository} object. * @throws hudson.plugins.git.GitException if underlying git operation fails. */ @NonNull public Repository getRepository() throws GitException { try { return new RepositoryBuilder().setWorkTree(workspace).build(); } catch (IOException e) { throw new GitException(e); } }
/** {@inheritDoc} */ @Deprecated public void setRemoteUrl(String name, String url, String GIT_DIR) throws GitException, InterruptedException { try (Repository repo = new RepositoryBuilder().setGitDir(new File(GIT_DIR)).build()) { StoredConfig config = repo.getConfig(); config.setString("remote", name, "url", url); config.save(); } catch (IOException ioe) { throw new GitException(ioe); } }
private StoredConfig getConfig(String GIT_DIR) throws GitException { try (Repository repo = isBlank(GIT_DIR) ? getRepository() : new RepositoryBuilder().setWorkTree(new File(GIT_DIR)).build()) { return repo.getConfig(); } catch (IOException ioe) { throw new GitException(ioe); } }
/** * Returns the {@link org.eclipse.jgit.lib.Repository} used by this git instance. * * @return a {@link org.eclipse.jgit.lib.Repository} object. * @throws hudson.plugins.git.GitException if underlying git operation fails. */ @NonNull public Repository getRepository() throws GitException { try { return new RepositoryBuilder().setWorkTree(workspace).build(); } catch (IOException e) { throw new GitException(e); } }
public RepoMerger(String outputRepositoryPath, List<SubtreeConfig> subtreeConfigs) throws IOException { this.subtreeConfigs = subtreeConfigs; File file = new File(outputRepositoryPath); repository = new RepositoryBuilder().setWorkTree(file).build(); if (!repository.getDirectory().exists()) { repository.create(); } }
/** * Creates a new Git-backed repository. * * @param repoDir the location of this repository * @param format the repository format * @param repositoryWorker the {@link Executor} which will perform the blocking repository operations * @param creationTimeMillis the creation time * @param author the user who initiated the creation of this repository * * @throws StorageException if failed to create a new repository */ GitRepository(Project parent, File repoDir, GitRepositoryFormat format, Executor repositoryWorker, long creationTimeMillis, Author author) { this.parent = requireNonNull(parent, "parent"); name = requireNonNull(repoDir, "repoDir").getName(); this.repositoryWorker = requireNonNull(repositoryWorker, "repositoryWorker"); this.format = requireNonNull(format, "format"); requireNonNull(author, "author"); final RepositoryBuilder repositoryBuilder = new RepositoryBuilder().setGitDir(repoDir).setBare(); boolean success = false; try { // Create an empty repository with format version 0 first. try (org.eclipse.jgit.lib.Repository initRepo = repositoryBuilder.build()) { if (exist(repoDir)) { throw new StorageException( "failed to create a repository at: " + repoDir + " (exists already)"); } initRepo.create(true); final StoredConfig config = initRepo.getConfig(); if (format == GitRepositoryFormat.V1) { // Update the repository settings to upgrade to format version 1 and reftree. config.setInt(CONFIG_CORE_SECTION, null, CONFIG_KEY_REPO_FORMAT_VERSION, 1); } // Disable hidden files, symlinks and file modes we do not use. config.setEnum(CONFIG_CORE_SECTION, null, CONFIG_KEY_HIDEDOTFILES, HideDotFiles.FALSE); config.setBoolean(CONFIG_CORE_SECTION, null, CONFIG_KEY_SYMLINKS, false); config.setBoolean(CONFIG_CORE_SECTION, null, CONFIG_KEY_FILEMODE, false); // Set the diff algorithm. config.setString(CONFIG_DIFF_SECTION, null, CONFIG_KEY_ALGORITHM, "histogram"); // Disable rename detection which we do not use. config.setBoolean(CONFIG_DIFF_SECTION, null, CONFIG_KEY_RENAMES, false); config.save(); } // Re-open the repository with the updated settings and format version. jGitRepository = new RepositoryBuilder().setGitDir(repoDir).build(); // Initialize the master branch. final RefUpdate head = jGitRepository.updateRef(Constants.HEAD); head.disableRefLog(); head.link(Constants.R_HEADS + Constants.MASTER); // Initialize the commit ID database. commitIdDatabase = new CommitIdDatabase(jGitRepository); // Insert the initial commit into the master branch. commit0(null, Revision.INIT, creationTimeMillis, author, "Create a new repository", "", Markup.PLAINTEXT, Collections.emptyList(), true); headRevision = Revision.INIT; success = true; } catch (IOException e) { throw new StorageException("failed to create a repository at: " + repoDir, e); } finally { if (!success) { close(); // Failed to create a repository. Remove any cruft so that it is not loaded on the next run. deleteCruft(repoDir); } } }
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; }
@Override 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 { logger.info("Cloning {} ...", cloneUrl); 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; }
public List<TagWrapper> process(File repoRoot) throws IOException { try (Repository repository = new RepositoryBuilder().findGitDir(repoRoot).build()) { return process(repository); } }
private void openRepository() { File testRepositoryBaseDir = getTestRepositoryBaseDir(); try { FileSystemManager manager = VFS.getManager(); if (repositoryPath.startsWith(CLASSPATH_PREFIX)) { String res = "res:" + repositoryPath.substring(CLASSPATH_PREFIX.length()); FileObject packFileObject = manager.resolveFile(res); try { FileObject zipFileSystem = manager .createFileSystem(packFileObject); try { FileObject targetDir = manager .toFileObject(testRepositoryBaseDir); targetDir.delete(Selectors.SELECT_ALL); targetDir.copyFrom(zipFileSystem, Selectors.SELECT_ALL); testRepositoryBaseDir = resolveRepositoryDirectory(testRepositoryBaseDir); } finally { zipFileSystem.close(); } } finally { packFileObject.close(); } } else { throw new UnsupportedOperationException( "GitRepository.value() must be a classpath:... resource"); } RepositoryBuilder repositoryBuilder = new RepositoryBuilder(); repositoryBuilder.readEnvironment(); repositoryBuilder.findGitDir(testRepositoryBaseDir); Repository repository = repositoryBuilder.build(); git = new Git(repository); } catch (Exception e) { throw new RuntimeException(e); } }
@Override public boolean supports(File baseDir) { RepositoryBuilder builder = new RepositoryBuilder().findGitDir(baseDir); return builder.getGitDir() != null; }
@Override public Path relativePathFromScmRoot(Path path) { RepositoryBuilder builder = getVerifiedRepositoryBuilder(path); return builder.getGitDir().toPath().getParent().relativize(path); }