コード例 #1
0
ファイル: GitUtil.java プロジェクト: jccastrejon/exschema
  /**
   * Obtain the Git respository that contains the specified project. The repository can either be in
   * the project's directory or in its hierarchy.
   *
   * @param project
   * @return
   * @throws IOException
   */
  private static Git getGitRepository(final IJavaProject project) throws IOException {
    Git returnValue;
    File gitDirectory;
    File currentDirectory;
    Repository repository;
    FileRepositoryBuilder repositoryBuilder;

    // Check whether the project or one of its ancestors hosts a Git
    // repository
    returnValue = null;
    if (project.getProject().getRawLocation() != null) {
      repositoryBuilder = new FileRepositoryBuilder();
      currentDirectory = project.getProject().getRawLocation().toFile();
      repository =
          repositoryBuilder.setGitDir(currentDirectory).readEnvironment().findGitDir().build();
      while (currentDirectory != null) {
        gitDirectory = new File(currentDirectory, ".git");
        if (gitDirectory.exists()) {
          repositoryBuilder = new FileRepositoryBuilder();
          repository =
              repositoryBuilder.setGitDir(gitDirectory).readEnvironment().findGitDir().build();
          break;
        } else {
          currentDirectory = currentDirectory.getParentFile();
        }
      }

      // If possible, reference the Git repository
      if (repository != null) {
        returnValue = new Git(repository);
      }
    }

    return returnValue;
  }
コード例 #2
0
  @Override
  public void open(String repositoryPath) {

    FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
    try {
      repository =
          repositoryBuilder
              .setGitDir(new File(repositoryPath))
              .readEnvironment() // read git environment variables
              .findGitDir()
              .build();
    } catch (IOException e) {
      throw new VisMinerAPIException(e.getMessage(), e);
    }

    git = new Git(repository);
    revWalk = new RevWalk(repository);
    treeWalk = new TreeWalk(repository);
    reader = repository.newObjectReader();

    processBuilder = new ProcessBuilder();
    processBuilder.directory(new File(repository.getDirectory().toString()));

    commands = Arrays.asList("git", "log", "--numstat", "--oneline", "--max-count=1", "");

    this.repositoryPath = repository.getWorkTree().getAbsolutePath();
  }
コード例 #3
0
  /** Clones or pulls the remote repository and returns the directory with the checkout */
  public void cloneOrPull(final String repo, final CredentialsProvider credentials)
      throws Exception {
    if (!localRepo.exists() && !localRepo.mkdirs()) {
      throw new IOException("Failed to create local repository");
    }
    File gitDir = new File(localRepo, ".git");
    if (!gitDir.exists()) {
      LOG.info("Cloning remote repo " + repo);
      CloneCommand command =
          Git.cloneRepository()
              .setCredentialsProvider(credentials)
              .setURI(repo)
              .setDirectory(localRepo)
              .setRemote(remoteName);
      git = command.call();
    } else {
      FileRepositoryBuilder builder = new FileRepositoryBuilder();
      Repository repository =
          builder
              .setGitDir(gitDir)
              .readEnvironment() // scan environment GIT_* variables
              .findGitDir() // scan up the file system tree
              .build();

      git = new Git(repository);

      // update the remote repo just in case
      StoredConfig config = repository.getConfig();
      config.setString("remote", remoteName, "url", repo);
      config.setString(
          "remote", remoteName, "fetch", "+refs/heads/*:refs/remotes/" + remoteName + "/*");

      String branch = "master";
      config.setString("branch", branch, "remote", remoteName);
      config.setString("branch", branch, "merge", "refs/heads/" + branch);

      try {
        config.save();
      } catch (IOException e) {
        LOG.error(
            "Failed to save the git configuration to "
                + localRepo
                + " with remote repo: "
                + repo
                + ". "
                + e,
            e);
      }

      // now pull
      LOG.info("Pulling from remote repo " + repo);
      git.pull().setCredentialsProvider(credentials).setRebase(true).call();
    }
  }
コード例 #4
0
  public static void main(final String[] args) throws Exception {

    logger.debug("init");

    final FileRepositoryBuilder builder = new FileRepositoryBuilder();
    builder.setGitDir(FILE);
    builder.readEnvironment();
    builder.findGitDir();

    final Repository repo = builder.build();

    // logger.debug("branch=" + repo.getBranch());
    // logger.debug("state=" + repo.getRepositoryState());

    switch (repo.getRepositoryState()) {
      case BARE:
        break;
      case SAFE:
        break;
      default:
        logger.error("wrong state");
    }

    final Git git = make();
    logger.debug("state=" + git.getRepository().getRepositoryState());

    // git.checkout().setName(Constants.MASTER).call();
    // git.pull().setTimeout(10).call();

    git.fetch().call();

    git.checkout().setName("current-config").call();

    // runClone();

    // final Git git = Git.open(FILE);
    // final StatusCommand status = git.status();
    // final Status result = status.call();
    // logger.debug("result=" + result);

    // final Git git = new Git(repo);

    // final RevCommit commit =
    // git.commit().setMessage("test commit").call();

    // final RevTag tag = git.tag().setName("test_tag").call();

    // logger.debug("branch=" + repo.getBranch());
    // logger.debug("state=" + repo.getRepositoryState());

    logger.debug("done");
  }
コード例 #5
0
  public JGitFlowSemver(File dir, GitflowVersioningConfiguration conf) throws IOException {
    this.dir = dir;
    this.conf = conf;

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    repository =
        builder
            .setGitDir(dir)
            .readEnvironment() // scan environment GIT_* variables
            .findGitDir() // scan up the file system tree
            .build();
    this.git = Git.wrap(repository);
  }
コード例 #6
0
ファイル: GitFacade.java プロジェクト: AlanFoster/hawtio
  public void initialiseGitRepo() throws IOException, GitAPIException {
    File confDir = getConfigDirectory();
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    File gitDir = new File(confDir, ".git");
    if (!gitDir.exists()) {
      InitCommand initCommand = Git.init();
      initCommand.setDirectory(confDir);
      git = initCommand.call();
    } else {
      Repository repository =
          builder
              .setGitDir(gitDir)
              .readEnvironment() // scan environment GIT_* variables
              .findGitDir() // scan up the file system tree
              .build();

      git = new Git(repository);
    }
  }
コード例 #7
0
ファイル: Santra.java プロジェクト: otavanopisto/santra
  private void reload(String botName) throws IOException, GitAPIException {
    log.info("Starting bot reload");
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository =
        builder.setGitDir(new File(arguments.getBasePath() + "/.git")).readEnvironment().build();
    log.info("Starting repository update");
    Git git = new Git(repository);
    git.reset().setMode(ResetCommand.ResetType.HARD).call();
    log.info("Reset complete");
    git.clean().call();
    log.info("Clean compete");
    git.fetch().call();
    log.info("Fetch complete");
    git.pull().call();
    log.info("Repository update finished");

    initBot(botName);
    log.info("Bot reloaded");
  }
コード例 #8
0
ファイル: EmailSender.java プロジェクト: soninob/verigreen
 public String getCommitMessage(String commitId) {
   String commitMessage = null;
   try {
     FileRepositoryBuilder builder = new FileRepositoryBuilder();
     String repoPath = VerigreenNeededLogic.properties.getProperty("git.repositoryLocation");
     Repository repo = builder.setGitDir(new File(repoPath)).setMustExist(true).build();
     Git git = new Git(repo);
     Iterable<RevCommit> log = git.log().call();
     Iterator<RevCommit> iterator = log.iterator();
     while (commitMessage == null && iterator.hasNext()) {
       RevCommit rev = iterator.next();
       String commit = rev.getName().substring(0, 7);
       if (commit.equals(commitId)) {
         commitMessage = rev.getFullMessage();
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return commitMessage;
 }
コード例 #9
0
ファイル: GitMiner.java プロジェクト: pombredanne/GitWorks
  // import a git repo in jgit data structures or create a new one
  private Repository createRepo(String repoDir, String gitDir) throws IOException {

    File gd = new File(gitDir);
    File rd = new File(repoDir);
    if (GitWorks.anew) {
      if (rd.exists()) FileUtils.delete(rd, FileUtils.RECURSIVE);
      if (!GitWorks.bare) rd.mkdirs();
      if (gd.exists()) FileUtils.delete(gd, FileUtils.RECURSIVE);
      gd.mkdirs();
    }
    FileRepositoryBuilder frb = new FileRepositoryBuilder();
    if (!GitWorks.bare) frb.setWorkTree(rd);
    Repository repository =
        frb.setGitDir(gd)
            .readEnvironment() // scan environment GIT_* variables
            .findGitDir() // scan up the file system tree
            .setMustExist(!GitWorks.anew)
            .build();
    if (GitWorks.anew) repository.create(GitWorks.bare);

    return repository;
  }
コード例 #10
0
ファイル: GitDiff.java プロジェクト: JuniorHu/JiraTest
  public String getDiffText(String str) {
    int filenubs = 0;
    int lines = 0;
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    File gitDir = new File("F:/work/demo-rio/.git");
    Repository repository = null;
    try {
      if (git == null) {
        git = Git.open(gitDir);
      }
    } catch (Exception e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    try {
      String cid = str;
      repository = builder.setGitDir(gitDir).readEnvironment().findGitDir().build();
      RevWalk walk = new RevWalk(repository);
      ObjectId objId = ObjectId.fromString(cid);
      RevCommit commit = walk.parseCommit(objId);
      System.out.println(commit.getFullMessage());

      TreeWalk tw = new TreeWalk(repository);

      RevCommit[] parent_commits = commit.getParents();
      if (parent_commits.length == 0) {
        throw new Exception("当前只有一个版本");
      }

      ObjectId objId2 = parent_commits[0].toObjectId();
      RevCommit paren_commit = walk.parseCommit(objId2);
      tw.addTree(paren_commit.getTree());
      tw.addTree(commit.getTree());
      tw.setRecursive(true);

      ByteArrayOutputStream out = new ByteArrayOutputStream();
      DiffFormatter df = new DiffFormatter(out);
      df.setRepository(git.getRepository());
      RenameDetector rd = new RenameDetector(repository);
      rd.addAll(DiffEntry.scan(tw));
      List<DiffEntry> diffEntries = rd.compute();
      if (diffEntries != null || diffEntries.size() != 0) {

        Iterator<DiffEntry> iterator = new ArrayList<DiffEntry>(diffEntries).iterator();
        DiffEntry diffEntry = null;
        while (iterator.hasNext()) {
          diffEntry = iterator.next();
          String changeType = diffEntry.getChangeType().toString();
          String type = "";
          if (changeType.equals("DELETE")) {
            type = ConfigUtil.getFileType(diffEntry.getOldPath());
            filenubs++;
            System.out.println(diffEntry.getOldPath());
          } else {
            type = ConfigUtil.getFileType(diffEntry.getNewPath());
            filenubs++;
            System.out.println(diffEntry.getNewPath());
          }
          // 检查文件的后缀
          // System.out.println(type);
          if (fileTypes.contains(type)) {
            df.format(diffEntry);
            String diffText = out.toString("UTF-8");
            lines += scanDiffText(diffText);
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return filenubs + "&" + lines;
    // System.out.println("the changed file nubs: "+ filenubs);
    // System.out.println("the changed linr nubs: "+ lines);
  }
コード例 #11
0
ファイル: CreateBranchMojo.java プロジェクト: jensaug/fabric8
  protected void initGitRepo() throws MojoExecutionException, IOException, GitAPIException {
    buildDir.mkdirs();
    File gitDir = new File(buildDir, ".git");
    if (!gitDir.exists()) {
      String repo = gitUrl;
      if (Strings.isNotBlank(repo)) {
        getLog()
            .info(
                "Cloning git repo "
                    + repo
                    + " into directory "
                    + getGitBuildPathDescription()
                    + " cloneAllBranches: "
                    + cloneAll);
        CloneCommand command =
            Git.cloneRepository()
                .setCloneAllBranches(cloneAll)
                .setURI(repo)
                .setDirectory(buildDir)
                .setRemote(remoteName);
        // .setCredentialsProvider(getCredentials()).
        try {
          git = command.call();
          return;
        } catch (Throwable e) {
          getLog().error("Failed to command remote repo " + repo + " due: " + e.getMessage(), e);
          // lets just use an empty repo instead
        }
      } else {
        InitCommand initCommand = Git.init();
        initCommand.setDirectory(buildDir);
        git = initCommand.call();
        getLog()
            .info("Initialised an empty git configuration repo at " + getGitBuildPathDescription());

        // lets add a dummy file
        File readMe = new File(buildDir, "ReadMe.md");
        getLog().info("Generating " + readMe);
        Files.writeToFile(
            readMe,
            "fabric8 git repository created by fabric8-maven-plugin at " + new Date(),
            Charset.forName("UTF-8"));
        git.add().addFilepattern("ReadMe.md").call();
        commit("Initial commit");
      }
      String branch = git.getRepository().getBranch();
      configureBranch(branch);
    } else {
      getLog().info("Reusing existing git repository at " + getGitBuildPathDescription());

      FileRepositoryBuilder builder = new FileRepositoryBuilder();
      Repository repository =
          builder
              .setGitDir(gitDir)
              .readEnvironment() // scan environment GIT_* variables
              .findGitDir() // scan up the file system tree
              .build();

      git = new Git(repository);
      if (pullOnStartup) {
        doPull();
      } else {
        getLog().info("git pull from remote config repo on startup is disabled");
      }
    }
  }