org.eclipse.jgit.internal.storage.file.FileRepository Java Examples

The following examples show how to use org.eclipse.jgit.internal.storage.file.FileRepository. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UpdaterGenerator.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Execute git pull command on the given repository.
 * It populates an ArrayList with all the updated files.
 * @param localPath The path where the project is.
 * @return Returns true if you should update plugins, false otherwise.
 */
private boolean gitPull(File localPath) {
    try {
        Repository localRepo = new FileRepository(localPath.getAbsolutePath() + "/.git");
        git = new Git(localRepo);
        
        populateDiff();
        
        if(!pluginsToUpdate.isEmpty()){
            PullCommand pullCmd = git.pull();
            pullCmd.call();
            return true;
        }
        else{
            return false;
        }
        
    } catch (GitAPIException | IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

    return true;
}
 
Example #2
Source File: OldGitNotebookRepo.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Override
public void init(ZeppelinConfiguration conf) throws IOException {
  //TODO(zjffdu), it is weird that I can not call super.init directly here, as it would cause
  //AbstractMethodError
  this.conf = conf;
  setNotebookDirectory(conf.getNotebookDir());

  localPath = getRootDir().getName().getPath();
  LOG.info("Opening a git repo at '{}'", localPath);
  Repository localRepo = new FileRepository(Joiner.on(File.separator).join(localPath, ".git"));
  if (!localRepo.getDirectory().exists()) {
    LOG.info("Git repo {} does not exist, creating a new one", localRepo.getDirectory());
    localRepo.create();
  }
  git = new Git(localRepo);
}
 
Example #3
Source File: GitNotebookRepo.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Override
public void init(ZeppelinConfiguration conf) throws IOException {
  //TODO(zjffdu), it is weird that I can not call super.init directly here, as it would cause
  //AbstractMethodError
  this.conf = conf;
  setNotebookDirectory(conf.getNotebookDir());

  LOGGER.info("Opening a git repo at '{}'", this.rootNotebookFolder);
  Repository localRepo = new FileRepository(Joiner.on(File.separator)
      .join(this.rootNotebookFolder, ".git"));
  if (!localRepo.getDirectory().exists()) {
    LOGGER.info("Git repo {} does not exist, creating a new one", localRepo.getDirectory());
    localRepo.create();
  }
  git = new Git(localRepo);
}
 
Example #4
Source File: RemoteRepoMock.java    From gitflow-incremental-builder with MIT License 6 votes vote down vote up
public RemoteRepoMock(File baseFolder, boolean bare, TestServerType testServerType) throws IOException {
    this.repoFolder = new File(baseFolder, "tmp/remote");

    if (bare) {
        repoFolder.mkdirs();
    } else {
        unpackTemplateProject();
    }

    try {
        git = new Git(new FileRepository(new File(repoFolder, ".git")));
    } catch (IOException | RuntimeException e) {
        close();
        throw e;
    }

    testServer = testServerType.buildServer();
    repoUri = testServer.start(git.getRepository());
}
 
Example #5
Source File: LocalRepoMock.java    From gitflow-incremental-builder with MIT License 6 votes vote down vote up
public LocalRepoMock(File baseFolder, TestServerType remoteRepoServerType) throws IOException, URISyntaxException, GitAPIException {
    this.baseFolder = new File(baseFolder.getAbsolutePath(), "tmp/repo/");
    new UnZipper().act(templateProjectZip, this.baseFolder);

    remoteRepo = remoteRepoServerType != null ? new RemoteRepoMock(baseFolder, remoteRepoServerType) : null;
    git = new Git(new FileRepository(new File(this.baseFolder, ".git")));

    if (remoteRepoServerType != null) {
        try {
            configureRemote(git, remoteRepo.repoUri.toString());
        } catch (IOException | URISyntaxException | GitAPIException | RuntimeException e) {
            close();
            throw e;
        }
    }
}
 
Example #6
Source File: LambdaConfig.java    From github-bucket with ISC License 6 votes vote down vote up
private LambdaConfig() {
    try (InputStream is = getClass().getClassLoader().getResourceAsStream("env.properties")) {
        this.props.load(is);
        this.repository = new FileRepository(new File(System.getProperty("java.io.tmpdir"), "s3"));
    }
    catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
    overwriteWithSystemProperty(ENV_BRANCH);
    overwriteWithSystemProperty(ENV_BUCKET);
    overwriteWithSystemProperty(ENV_GITHUB);

    this.remote = new Remote(Constants.DEFAULT_REMOTE_NAME);
    this.branch = new Branch(props.getProperty(ENV_BRANCH, Constants.MASTER));
    this.authentication = new SecureShellAuthentication(new Bucket(props.getProperty(ENV_BUCKET)), client);
}
 
Example #7
Source File: JGitOperator.java    From verigreen with Apache License 2.0 6 votes vote down vote up
public JGitOperator(String repositoryPath, String gitUser, String gitPassword) {

try {
          // need to verify repo was created successfully - this is not enough
	/*if(!repositoryPath.contains("\\.git") && !repositoryPath.equals("."))
	{
		repositoryPath=repositoryPath.concat("\\.git");
	}*/
          _repo = new FileRepository(repositoryPath);
          _git = new Git(_repo);
          if(gitUser != null)
              _cp  = new UsernamePasswordCredentialsProvider(gitUser, gitPassword);
          } catch (IOException e) {
          throw new RuntimeException(String.format(
                  "Failed creating git repository for path [%s]",
                  repositoryPath), e);
          }
      }
 
Example #8
Source File: PluginRepoResolver.java    From flow-platform-x with Apache License 2.0 6 votes vote down vote up
@Override
public Repository open(HttpServletRequest req, String name) throws RepositoryNotFoundException {
    try {
        Plugin plugin = pluginService.get(name);
        File gitDir = Paths.get(pluginService.getDir(plugin).toString(), ".git").toFile();
        return new FileRepository(gitDir);
    } catch (NotFoundException | IOException e) {
        throw new RepositoryNotFoundException("Repository " + name + "does not exist");
    }
}
 
Example #9
Source File: UpdaterGenerator.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Execute git pull command on the given repository.
 * It populates an ArrayList with all the updated files.
 * @param localPath The path where the project is.
 * @return Returns true if you should update plugins, false otherwise.
 */
private boolean gitPull(File localPath) {
    try {
        Repository localRepo = new FileRepository(localPath.getAbsolutePath() + "/.git");
        git = new Git(localRepo);
        
        
        
        if(populateDiff()){
            PullCommand pullCmd = git.pull();
            pullCmd.call();
            return true;
        }
        else{
            return false;
        }
        
    } catch (GitAPIException | IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

    return true;
}
 
Example #10
Source File: GitManager.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String getCurrentRevision(VcsRepository repository) throws Exception {
	Git git = new Git(new FileRepository("tmp-ls")); // FIXME
	Collection<Ref> refs = git.lsRemote().setRemote(repository.getUrl()).call();
	
	String headId = null;
	for (Ref ref : refs) {
		if ("HEAD".equals(ref.getName())) {
			headId = ref.getObjectId().getName();
		}
	}
	
	git.close();
	
	return headId;
}
 
Example #11
Source File: LambdaConfig.java    From github-bucket with ISC License 6 votes vote down vote up
private LambdaConfig() {
    try (InputStream is = getClass().getClassLoader().getResourceAsStream("env.properties")) {
        this.props.load(is);
        this.repository = new FileRepository(new File(System.getProperty("java.io.tmpdir"), "s3"));
    }
    catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
    overwriteWithSystemProperty(ENV_BRANCH);
    overwriteWithSystemProperty(ENV_BUCKET);
    overwriteWithSystemProperty(ENV_GITHUB);

    this.remote = new Remote(Constants.DEFAULT_REMOTE_NAME);
    this.branch = new Branch(props.getProperty(ENV_BRANCH, Constants.MASTER));
    this.authentication = new SecureShellAuthentication(new Bucket(props.getProperty(ENV_BUCKET)), client);
}
 
Example #12
Source File: ConfigOption.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Retrieves local config without any base config.
 */
private FileBasedConfig getLocalConfig() throws IOException {
	// TODO: remove usage of internal type
	if (db instanceof FileRepository) {
		FileRepository fr = (FileRepository) db;
		FileBasedConfig config = new FileBasedConfig(fr.getConfig().getFile(), FS.detect());
		try {
			config.load();
		} catch (ConfigInvalidException e) {
			throw new IOException(e);
		}
		return config;
	} else {
		throw new IllegalArgumentException("Repository is not file based.");
	}
}
 
Example #13
Source File: JGitWrapper.java    From mOrgAnd with GNU General Public License v2.0 5 votes vote down vote up
private Git initGitRepo(ProgressMonitor monitor) throws Exception {
    if (new File(localPath).exists() == false)
        createNewRepo(monitor);

    FileRepository fileRepository = new FileRepository(localPath + "/.git");
    return new Git(fileRepository);
}
 
Example #14
Source File: RepositoryUtils.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
public static void garbageCollect(FileRepository repo) throws IOException {
  try {
    new GC(repo).gc();
  } catch(ParseException e) {
    throw new IllegalStateException(e);
  }
}
 
Example #15
Source File: GitSubmodules.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
public GitSubmodules(@NotNull Path basePath, @NotNull Collection<String> paths) throws IOException {
  for (String path : paths) {
    final Path file = ConfigHelper.joinPath(basePath, path);
    if (!Files.exists(file))
      throw new FileNotFoundException(file.toString());

    log.info("Linked repository path: {}", file);
    repositories.add(new FileRepository(file.toFile()));
  }
}
 
Example #16
Source File: Utils.java    From usergrid with Apache License 2.0 5 votes vote down vote up
/**
 * @param gitConfigFolder e.g. /your/project/root/.git
 *
 * @return Returns true if 'git status' has modified files inside the 'Changes to be committed' section
 */
public static boolean isCommitNecessary( String gitConfigFolder ) throws MojoExecutionException {
    try {
        Repository repo = new FileRepository( gitConfigFolder );
        Git git = new Git( repo );

        Status status = git.status().call();
        Set<String> modified = status.getModified();

        return ( modified.size() != 0 );
    }
    catch ( Exception e ) {
        throw new MojoExecutionException( "Error trying to find out if git commit is needed", e );
    }
}
 
Example #17
Source File: GitRepository.java    From APDE with GNU General Public License v2.0 5 votes vote down vote up
public void open() {
    try {
        git = new Git(new FileRepository(getGitDir()));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #18
Source File: RepositoryUtils.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
public static void garbageCollect(Repository repo) throws IOException {
  if(repo instanceof FileRepository)
    garbageCollect((FileRepository) repo);
  else if(repo instanceof DfsRepository)
    garbageCollect((DfsRepository) repo);
  else
    throw new UnsupportedOperationException("Unsupported repository: " + repo.getClass().getName());
}
 
Example #19
Source File: RepositoryUtils.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
public static void garbageCollect(Repository repo) throws IOException {
  if(repo instanceof FileRepository)
    garbageCollect((FileRepository) repo);
  else if(repo instanceof DfsRepository)
    garbageCollect((DfsRepository) repo);
  else
    throw new UnsupportedOperationException("Unsupported repository: " + repo.getClass().getName());
}
 
Example #20
Source File: GitRepositoryConfig.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@NotNull
private Repository createGit(@NotNull LocalContext context, @NotNull Path fullPath) throws IOException {
  if (!Files.exists(fullPath)) {
    log.info("[{}]: storage {} not found, create mode: {}", context.getName(), fullPath, createMode);
    return createMode.createRepository(fullPath, branches);
  }
  log.info("[{}]: using existing storage {}", context.getName(), fullPath);
  return new FileRepository(fullPath.toFile());
}
 
Example #21
Source File: RepositoryUtils.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
public static void garbageCollect(FileRepository repo) throws IOException {
  try {
    new GC(repo).gc();
  } catch(ParseException e) {
    throw new IllegalStateException(e);
  }
}
 
Example #22
Source File: GitClientTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void testAutocreateFailsOnMultipleMatchingOrigins() throws Exception {
    File repoRootTemp = tempFolder.newFolder();
    GitClient gitClientTemp = Git.with(TaskListener.NULL, new EnvVars()).in(repoRootTemp).using(gitImplName).getClient();
    gitClientTemp.init();
    FilePath gitClientFilePath = gitClientTemp.getWorkTree();
    FilePath gitClientTempFile = gitClientFilePath.createTextTempFile("aPre", ".txt", "file contents");
    gitClientTemp.add(".");
    gitClientTemp.commit("Added " + gitClientTempFile.toURI().toString());
    gitClient.clone_().url("file://" + repoRootTemp.getPath()).execute();
    final URIish remote = new URIish(Constants.DEFAULT_REMOTE_NAME);

    try ( // add second remote
          FileRepository repo = new FileRepository(new File(repoRoot, ".git"))) {
        StoredConfig config = repo.getConfig();
        config.setString("remote", "upstream", "url", "file://" + repoRootTemp.getPath());
        config.setString("remote", "upstream", "fetch", "+refs/heads/*:refs/remotes/upstream/*");
        config.save();
    }

    // fill both remote branches
    List<RefSpec> refspecs = Collections.singletonList(new RefSpec(
            "refs/heads/*:refs/remotes/origin/*"));
    gitClient.fetch_().from(remote, refspecs).execute();
    refspecs = Collections.singletonList(new RefSpec(
            "refs/heads/*:refs/remotes/upstream/*"));
    gitClient.fetch_().from(remote, refspecs).execute();

    // checkout will fail
    try {
        gitClient.checkout().ref(Constants.MASTER).execute();
    } catch (GitException e) {
        // expected
        Set<String> refNames = gitClient.getRefNames("refs/heads/");
        assertFalse("RefNames will not contain master", refNames.contains("refs/heads/master"));
    }

}
 
Example #23
Source File: JGitEnvironmentRepositorySslTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setup() throws Exception {
	URL repoUrl = JGitEnvironmentRepositorySslTests.class
			.getResource("/test1-config-repo/git");
	Repository repo = new FileRepository(new File(repoUrl.toURI()));
	server = new SimpleHttpServer(repo, true);
	server.start();
}
 
Example #24
Source File: GitControl.java    From juneau with Apache License 2.0 5 votes vote down vote up
public GitControl(String localPath, String remotePath) throws IOException {
	this.localPath = localPath;
	this.remotePath = remotePath;
	this.localRepo = new FileRepository(localPath + "/.git");
	cp = new UsernamePasswordCredentialsProvider(this.name, this.password);
	git = new Git(localRepo);
}
 
Example #25
Source File: GitJobUtils.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Calls pack refs for a given repository
 * 
 * @param Repository
 *            the git repository
 */
public static void packRefs(Repository repo, ProgressMonitor monitor) {
	if (repo != null && repo instanceof FileRepository) {
		GC gc = new GC(((FileRepository) repo));
		gc.setProgressMonitor(monitor);
		try {
			gc.packRefs();
		} catch (IOException ex) {
			// ignore IOException since packing is an optimization (not essential for the callers doClone/doFetch) 
		}
	}
}
 
Example #26
Source File: MicroGitSync.java    From nh-micro with Apache License 2.0 5 votes vote down vote up
public void reset() throws Exception{
	logger.debug("begin git sync loop");
       File file = new File(localPath);
       if(!file.exists()){
           logger.debug("rep not exist");
       }
       String localRepo=localPath+"/.git";
       Git git = new Git(new FileRepository(localRepo));
       git.reset().setMode(ResetType.HARD).call();
       logger.debug("end git sync loop");
}
 
Example #27
Source File: PluginRepoResolver.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
@Override
public Repository open(HttpServletRequest req, String name) throws RepositoryNotFoundException {
    try {
        Plugin plugin = pluginService.get(name);
        File gitDir = Paths.get(pluginService.getDir(plugin).toString(), ".git").toFile();
        return new FileRepository(gitDir);
    } catch (NotFoundException | IOException e) {
        throw new RepositoryNotFoundException("Repository " + name + "does not exist");
    }
}
 
Example #28
Source File: MdeTechnologyRepoAuthorCounter.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private int count(String repoLocation) {	
		HashSet<String> repoAuthorsSet = new HashSet<String>();
		
		try {
			Repository repo = new FileRepository(new File(repoLocation).getCanonicalPath());
			
			// get a list of all known heads, tags, remotes, ...
            Collection<Ref> allRefs = repo.getAllRefs().values();

            // a RevWalk allows to walk over commits based on some filtering that is defined
            try (RevWalk revWalk = new RevWalk( repo )) {
                for( Ref ref : allRefs ) {
                    revWalk.markStart( revWalk.parseCommit( ref.getObjectId() ));
                }
//                System.out.println("Walking all commits starting with " + allRefs.size() + " refs: " + allRefs);
                for( RevCommit commit : revWalk ) {
                	repoAuthorsSet.add(commit.getAuthorIdent().getEmailAddress());
                }
            }
		
		} catch (IOException e) {
			System.err.println("\n" + "[" + workflow.getName() + "] " + "Failed to count repository authors. Wrong cloned repository location?");
			e.printStackTrace();
		}	 
		
		return repoAuthorsSet.size();
	}
 
Example #29
Source File: MdeTechnologyRepoAuthorCounter.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private int count(String repoLocation) {	
		HashSet<String> repoAuthorsSet = new HashSet<String>();
		
		try {
			Repository repo = new FileRepository(new File(repoLocation).getCanonicalPath());
			
			// get a list of all known heads, tags, remotes, ...
            Collection<Ref> allRefs = repo.getAllRefs().values();

            // a RevWalk allows to walk over commits based on some filtering that is defined
            try (RevWalk revWalk = new RevWalk( repo )) {
                for( Ref ref : allRefs ) {
                    revWalk.markStart( revWalk.parseCommit( ref.getObjectId() ));
                }
//                System.out.println("Walking all commits starting with " + allRefs.size() + " refs: " + allRefs);
                for( RevCommit commit : revWalk ) {
                	repoAuthorsSet.add(commit.getAuthorIdent().getEmailAddress());
                }
            }
		
		} catch (IOException e) {
			System.err.println("\n" + "[" + workflow.getName() + "] " + "Failed to count repository authors. Wrong cloned repository location?");
			e.printStackTrace();
		}	 
		
		return repoAuthorsSet.size();
	}
 
Example #30
Source File: RepositorySearcher.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private void countAuthors(RepositoryClone repositoryClone, AnalysisResult res) {

		// getOrCreateResult(repositoryClone, ext).fileCount = fileCount;
		// XXX NB: since authors are not linked to technologies yet, assume they all
		// contribute to all technologies found in the files of the repo

		Set<String> repoAuthorsSet = new HashSet<>();

		//

		try {
			FileRepository repo = new FileRepository(new File(repositoryClone.path + "/.git").getCanonicalPath());

			// get a list of all known heads, tags, remotes, ...
			@SuppressWarnings("deprecation")
			Collection<Ref> allRefs = repo.getAllRefs().values();

			// a RevWalk allows to walk over commits based on some filtering that is defined
			try (RevWalk revWalk = new RevWalk(repo)) {
				for (Ref ref : allRefs) {
					revWalk.markStart(revWalk.parseCommit(ref.getObjectId()));
				}
				System.out.println("Walking all commits starting with " + allRefs.size() + " refs: " + allRefs);
				for (RevCommit commit : revWalk) {
					repoAuthorsSet.add(commit.getAuthorIdent().getEmailAddress());
				}
			}

		} catch (IOException e) {
			System.err.println("\n" + "[" + workflow.getName() + "] "
					+ "Failed to count repository authors. Wrong cloned repository location?");
			e.printStackTrace();
		}

		//

		res.authorCount = repoAuthorsSet.size();

	}