Ejemplo n.º 1
1
  private void writeNewVersion(Document document) throws IOException, GitAPIException {
    final File docDir = getDirForDoc(document.getId());
    Git git = null;
    if (!docDir.exists()) {
      docDir.mkdirs();
      git = new InitCommand().setDirectory(docDir).call();
    } else {
      git = Git.open(docDir);
      completeUndo(git);
    }

    File outputFile = new File(docDir, "document.xml");
    FileOutputStream fos = new FileOutputStream(outputFile);
    try {
      document.serialize(fos);
    } catch (XMLStreamException e) {
      throw new RuntimeException(e);
    } finally {
      fos.close();
    }
    git.add().addFilepattern("document.xml").call();
    git.commit()
        .setCommitter("transmog", "*****@*****.**")
        .setMessage("Updated through application.")
        .call();
  }
Ejemplo n.º 2
0
  @Test
  public void dontPackHEAD_bare() throws Exception {
    BranchBuilder bb = tr.branch("refs/heads/side");
    bb.commit().add("A", "A").add("B", "B").create();
    RevCommit second = bb.commit().add("A", "A2").add("B", "B2").create();

    // Convert the repo to be bare
    FileBasedConfig cfg = repo.getConfig();
    cfg.setBoolean(
        ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_BARE, true);
    cfg.save();
    Git git = Git.open(repo.getDirectory());
    repo = (FileRepository) git.getRepository();

    // check for the unborn branch master. HEAD should point to master and
    // master doesn't exist.
    assertEquals(repo.exactRef("HEAD").getTarget().getName(), "refs/heads/master");
    assertNull(repo.exactRef("HEAD").getTarget().getObjectId());
    gc.packRefs();
    assertSame(repo.exactRef("HEAD").getStorage(), Storage.LOOSE);
    assertEquals(repo.exactRef("HEAD").getTarget().getName(), "refs/heads/master");
    assertNull(repo.exactRef("HEAD").getTarget().getObjectId());

    // check for non-detached HEAD
    repo.updateRef(Constants.HEAD).link("refs/heads/side");
    gc.packRefs();
    assertSame(repo.exactRef("HEAD").getStorage(), Storage.LOOSE);
    assertEquals(repo.exactRef("HEAD").getTarget().getObjectId(), second.getId());
  }
Ejemplo n.º 3
0
 private static Git openRepository(File directory) throws GitException {
   try {
     return Git.open(directory);
   } catch (IOException e) {
     throw new GitException("Cannot open repository " + directory, e);
   }
 }
Ejemplo n.º 4
0
  @Test
  public void testPushToNonBareRepository() throws Exception {
    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/git/working/jgit", url));
    clone.setDirectory(jgit2Folder);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password));
    close(clone.call());
    assertTrue(true);

    Git git = Git.open(jgit2Folder);
    File file = new File(jgit2Folder, "NONBARE");
    OutputStreamWriter os =
        new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    BufferedWriter w = new BufferedWriter(os);
    w.write("// " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    git.commit().setMessage("test commit followed by push to non-bare repository").call();
    try {
      git.push().setPushAll().call();
      assertTrue(false);
    } catch (Exception e) {
      assertTrue(e.getCause().getMessage().contains("git-receive-pack not permitted"));
    }
    close(git);
  }
Ejemplo n.º 5
0
 public Document undoLastChange(Document document) {
   try {
     final File docDir = getDirForDoc(document.getId());
     if (!docDir.exists()) {
       return null;
     } else {
       Git git = Git.open(docDir);
       Iterator<RevCommit> it = git.log().setMaxCount(2).call().iterator();
       if (it.hasNext()) {
         final RevCommit c = it.next(); // current version
       }
       if (it.hasNext()) {
         RevCommit c = it.next(); // previous version
         if (isUndo(git)) {
           git.reset().setMode(ResetCommand.ResetType.HARD).setRef("HEAD~1").call();
         } else {
           git.branchCreate().setName("undo").setStartPoint(c).call();
           git.checkout().setName("undo").call();
         }
         return getDocument(document.getId());
       }
       return null;
     }
   } catch (IOException e) {
     throw new RuntimeException(e);
   } catch (NoHeadException e) {
     throw new RuntimeException(e);
   } catch (GitAPIException e) {
     throw new RuntimeException(e);
   }
 }
Ejemplo n.º 6
0
  @Override
  public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {
      String localPath = args[0].getStringValue();
      if (!(localPath.endsWith("/"))) localPath += File.separator;

      //	        Repository localRepo = new FileRepository(localPath + ".git");
      //	        Git git = new Git(localRepo);

      Git git = Git.open(new Resource(localPath), FS);

      MemTreeBuilder builder = context.getDocumentBuilder();

      AttributesImpl attribs = new AttributesImpl();
      attribs.addAttribute(NAMESPACE_URI, "local-path", PREFIX + ":local-path", "CDATA", localPath);

      int nodeNr = builder.startElement(LOG_ELEMENT, attribs);

      for (RevCommit commit : git.log().call()) {
        //                commit.getParentCount();
        //                commit.getParents();

        attribs = new AttributesImpl();
        attribs.addAttribute(NAMESPACE_URI, "id", PREFIX + ":id", "CDATA", commit.name());

        attribs.addAttribute(
            NAMESPACE_URI,
            "time",
            PREFIX + ":time",
            "CDATA",
            String.valueOf(commit.getCommitTime()));

        builder.startElement(COMMIT_ELEMENT, attribs);

        PersonIdent authorIdent = commit.getAuthorIdent();
        builder.startElement(AUTHOR_ELEMENT, null);
        builder.startElement(AUTHOR_NAME_ELEMENT, null);
        builder.characters(authorIdent.getName());
        builder.endElement();
        builder.startElement(AUTHOR_EMAIL_ELEMENT, null);
        builder.characters(authorIdent.getEmailAddress());
        builder.endElement();
        builder.endElement();

        builder.startElement(MESSAGE_ELEMENT, null);
        builder.characters(commit.getFullMessage());
        builder.endElement();

        builder.endElement();
      }

      builder.endElement();

      return builder.getDocument().getNode(nodeNr);
    } catch (Throwable e) {
      throw new XPathException(this, Module.EXGIT001, e);
    }
  }
Ejemplo n.º 7
0
  @Test
  public void testGitPgm() throws Exception {
    Path targetParent = detectTargetFolder().getParent();
    Path serverDir = getTempTargetRelativeFile(getClass().getSimpleName());

    //
    // TODO: the GitpgmCommandFactory is kept in the test tree
    // TODO: because it's quite limited for now
    //

    try (SshServer sshd = setupTestServer()) {
      sshd.setSubsystemFactories(Arrays.<NamedFactory<Command>>asList(new SftpSubsystemFactory()));
      sshd.setCommandFactory(
          new GitPgmCommandFactory(Utils.resolveRelativeRemotePath(targetParent, serverDir)));
      sshd.start();

      int port = sshd.getPort();
      try {
        Utils.deleteRecursive(serverDir);

        try (SshClient client = setupTestClient()) {
          client.start();

          try (ClientSession session =
              client
                  .connect(getCurrentTestName(), SshdSocketAddress.LOCALHOST_IP, port)
                  .verify(7L, TimeUnit.SECONDS)
                  .getSession()) {
            session.addPasswordIdentity(getCurrentTestName());
            session.auth().verify(5L, TimeUnit.SECONDS);

            Path repo = serverDir.resolve(getCurrentTestName());
            Git.init().setDirectory(repo.toFile()).call();
            Git git = Git.open(repo.toFile());
            git.commit()
                .setMessage("First Commit")
                .setCommitter(getCurrentTestName(), "*****@*****.**")
                .call();

            Path readmeFile = Files.createFile(repo.resolve("readme.txt"));
            String commandPrefix = "git --git-dir " + repo.getFileName();
            execute(session, commandPrefix + " add " + readmeFile.getFileName());
            execute(session, commandPrefix + " commit -m \"readme\"");
          } finally {
            client.stop();
          }
        }
      } finally {
        sshd.stop();
      }
    }
  }
Ejemplo n.º 8
0
 private Git openOrInit(File repo) throws IOException {
   try {
     return Git.open(repo);
   } catch (RepositoryNotFoundException e) {
     try {
       Git git = Git.init().setDirectory(repo).call();
       git.commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call();
       return git;
     } catch (GitAPIException ex) {
       throw new IOException(ex);
     }
   }
 }
Ejemplo n.º 9
0
 @Test
 public void testAnonymousPush() throws Exception {
   Git git = Git.open(ticgitFolder);
   File file = new File(ticgitFolder, "TODO");
   OutputStreamWriter os =
       new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
   BufferedWriter w = new BufferedWriter(os);
   w.write("// hellol中文 " + new Date().toString() + "\n");
   w.close();
   git.add().addFilepattern(file.getName()).call();
   git.commit().setMessage("test commit").call();
   git.push().setPushAll().call();
   close(git);
 }
Ejemplo n.º 10
0
 @Override
 public Git get() throws IOException {
   File localRepo = new File(DEFAULT_LOCAL_LOCATION);
   if (!localRepo.exists() && !localRepo.mkdirs()) {
     throw new IOException("Failed to create local repository");
   }
   try {
     return Git.open(localRepo);
   } catch (RepositoryNotFoundException e) {
     try {
       Git git = Git.init().setDirectory(localRepo).call();
       git.commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call();
       return git;
     } catch (GitAPIException ex) {
       throw new IOException(ex);
     }
   }
 }
Ejemplo n.º 11
0
  @Test
  public void testRemote() throws Exception {

    File binaryRepoFolder = new File("D:\\dev\\rgiroti_search_raptor\\.search_raptor");
    Git git = Git.open(binaryRepoFolder);
    final Iterable<RevCommit> revCommits = git.log().call();
    for (RevCommit revCommit : revCommits) {
      System.out.println(
          revCommit.getName() + revCommit.getFullMessage() + revCommit.getCommitTime());
    }

    // final org.eclipse.jgit.lib.Repository binRepo = new
    // org.eclipse.jgit.storage.file.FileRepository(binaryRepoFolder);
    // final RevWalk binRepoRevWalk = new RevWalk(binRepo);

    // final ObjectId binRepoResolve = binRepo.resolve(Constants.HEAD);
    // final RevCommit binRepoResolveCommitRev = git.log().call().iterator().next();
    // final String binRepoResolveCommitHash = binRepoResolveCommitRev.getName();

    // final String binRepoBranchname = git.getRepository().getBranch();
  }
Ejemplo n.º 12
0
  @Test
  public void testSubfolderPush() throws Exception {
    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/git/test/jgit.git", url));
    clone.setDirectory(jgitFolder);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password));
    close(clone.call());
    assertTrue(true);

    Git git = Git.open(jgitFolder);
    File file = new File(jgitFolder, "TODO");
    OutputStreamWriter os =
        new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    BufferedWriter w = new BufferedWriter(os);
    w.write("// " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    git.commit().setMessage("test commit").call();
    git.push().setPushAll().call();
    close(git);
  }
Ejemplo n.º 13
0
  // 2. Get branch/commit hash for the source repo - the actual source code
  @Test
  public void existsIn2() throws IOException {
    final String repo = "binrepo-devex";
    //  final String repo = "search_raptor_binary";
    // String githubUrl = "https://github.scm.corp.ebay.com/api/v3";
    // String accessToken = "1cf7d9792235b8592eda18bd7dcc2de37f99b3bc";

    final String path = "D:\\dev\\devex\\.binrepo-devex\\.git";

    File gitDir = new File(path);
    org.eclipse.jgit.lib.Repository repository =
        new org.eclipse.jgit.storage.file.FileRepository(gitDir);
    String branch = repository.getBranch();
    System.out.println("Branch=" + branch);
    final Map<String, Ref> allRefs = repository.getAllRefs();
    for (String s : allRefs.keySet()) {
      System.out.println("Here" + s);
    }

    RevWalk revWalk = new RevWalk(repository);
    ObjectId resolve = repository.resolve(Constants.HEAD);
    RevCommit commitRev = revWalk.parseCommit(resolve);
    String commitHash = commitRev.getName();
    System.out.println(commitHash + "\t" + commitRev.getFullMessage());

    Git binaryRepo = Git.open(gitDir);

    final ListBranchCommand listBranchCommand = binaryRepo.branchList();
    System.out.println(listBranchCommand.getRepository().getFullBranch());
    // get "status"
    final StatusCommand statusCommand = binaryRepo.status();
    Collection<String> toadd = GitUtils.getFilesToStage(statusCommand);
    for (String s : toadd) {
      System.out.println("To be added:" + s);
    }

    // add files to "staging"
    if (toadd.size() > 0) {
      AddCommand addCmd = binaryRepo.add();
      for (String file : toadd) {
        addCmd.addFilepattern(file);
      }

      try {
        addCmd.call();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    final StoredConfig config = repository.getConfig();
    String url = config.getString("remote", "origin", "url");
    if (url != null) {
      System.out.println("Origin comes from " + url);
    }

    // commit
    final CommitCommand commit = binaryRepo.commit();
    String msg = "Saving Repo:%s Branch:%s CommitHash:%s Time:%s";
    final String formattedMsg = String.format(msg, repo, branch, commitHash, new Date().toString());
    commit.setMessage(formattedMsg);
    try {
      commit.call();
    } catch (Exception e) {
      e.printStackTrace();
    }

    // push to origin now
    final PushCommand push = binaryRepo.push();
    final String remote = push.getRemote();
    System.out.println("Remote to push to:'" + remote + "'");
    try {
      push.call();
    } catch (Exception e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }
  }
Ejemplo n.º 14
0
  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);
  }
Ejemplo n.º 15
0
  public String getProjectVersion(File repoDir) throws IOException, GitAPIException {
    Git git = Git.open(repoDir);
    Repository repo = git.getRepository();

    // Find base commit between current branch and "master":
    String branch = repo.getBranch();
    RevCommit base = CommitUtils.getBase(repo, "master", branch);
    CommitCountFilter count = new CommitCountFilter();
    CommitFinder finder = new CommitFinder(repo).setFilter(count);
    finder.findBetween(branch, base);
    long commitsSinceBase = count.getCount();

    // Find tags in "master" before base commit:
    RevWalk rw = new RevWalk(repo);
    rw.markStart(base);
    rw.setRetainBody(false);
    Ref master = repo.getRef("master");
    List<Ref> masterAsList = Arrays.asList(master);
    List<Ref> tags = git.tagList().call();
    Map<RevCommit, Ref> masterTags = new HashMap<RevCommit, Ref>();
    for (Ref tag : tags) {
      tag = repo.peel(tag);
      ObjectId commitID = tag.getPeeledObjectId();
      if (commitID == null) continue;
      RevCommit commit = rw.parseCommit(commitID);
      // Only remember tags reachable from "master":
      if (!RevWalkUtils.findBranchesReachableFrom(commit, rw, masterAsList).isEmpty()) {
        masterTags.put(commit, tag);
      }
    }

    // Find the shortest distance in commits between base tag in "master":
    long commitsBetweenBaseAndTag = Long.MAX_VALUE;
    String tagName = "";
    for (RevCommit tagCommit : masterTags.keySet()) {
      count.reset();
      finder.findBetween(base, tagCommit);
      if (count.getCount() < commitsBetweenBaseAndTag) {
        commitsBetweenBaseAndTag = count.getCount();
        tagName = masterTags.get(tagCommit).getName();
      }
    }
    if (commitsBetweenBaseAndTag == Long.MAX_VALUE) {
      // If no tag, get total number of commits:
      commitsBetweenBaseAndTag = repo.getRefDatabase().getRefs("").size();
    }
    long commitsSinceLastMasterTag = commitsSinceBase + commitsBetweenBaseAndTag;

    // Construct version string:
    String version = branch.equals("master") ? "" : (branch + "-");
    if (tagName.startsWith("refs/tags/")) {
      tagName = tagName.substring("refs/tags/".length());
    }
    // v1.1 -> 1.1
    if (tagName.matches("v\\d+.*")) {
      tagName = tagName.substring(1);
    }
    if (tagName.isEmpty()) {
      version = "0";
    }
    version += tagName + ((!tagonly) ? "." + commitsSinceLastMasterTag : "");

    return version;
  }
 /*
  * (non-Javadoc)
  *
  * @see nl.minicom.gitolite.manager.git.GitManager#open()
  */
 @Override
 public void open() throws IOException {
   git = Git.open(workingDirectory);
 }
Ejemplo n.º 17
0
  public void updateBinaryRepository() throws IOException, GitException, MapServiceException {

    // 1. Check if repository exists remotely [email protected]/Binary/Repo_Binary.git
    // find the name of the "source repository"
    final String repoUrl = getSourceRemoteUrl();

    // find where ".git" folder is found
    // SourceRepository = D:\dev\devex\binrepo-devex
    // BinaryRepository = D:\dev\devex\.binrepo-devex
    final File srcRepoDir = sourceRepository.getDirectory();
    final File sourceDir = srcRepoDir.getParentFile();

    final String sourceRepoFolder = srcRepoDir.getParentFile().getCanonicalPath();

    final File parent = srcRepoDir.getParentFile().getParentFile();
    final File binaryRepoDir = new File(parent, "." + srcRepoDir.getParentFile().getName());
    System.out.println(
        "SourceRepository = "
            + sourceRepoFolder
            + "\nBinaryRepository = "
            + binaryRepoDir.getCanonicalPath());

    // 2. Get branch/commit hash for the source repo - the actual source code
    final org.eclipse.jgit.lib.Repository repository =
        new org.eclipse.jgit.storage.file.FileRepository(srcRepoDir);
    final String branch = repository.getBranch();

    final RevWalk revWalk = new RevWalk(repository);
    final ObjectId resolve = repository.resolve(Constants.HEAD);
    final RevCommit commit = revWalk.parseCommit(resolve);
    String commitHash = commit.getName();
    System.out.println("CommitHash:" + commitHash + "\tMessage:" + commit.getFullMessage());

    // 3. Call the BinRepo service and check if a corresponding BinRepo entry exists
    final String url =
        getUrlForFindByRepoBranchCommit()
            + "repourl="
            + URLEncoder.encode(repoUrl, UTF_8)
            + "&branch="
            + URLEncoder.encode(branch, UTF_8)
            + "&commitid="
            + URLEncoder.encode(commitHash, UTF_8);
    System.out.println("svc url : " + url);

    WebResource webResource = client.resource(url);

    boolean noContent = false;
    BinRepoBranchCommitDO binRepoBranchCommitDO1 = null;

    try {
      binRepoBranchCommitDO1 =
          webResource.accept(MediaType.APPLICATION_JSON).get(BinRepoBranchCommitDO.class);
    } catch (UniformInterfaceException e) {
      int statusCode = e.getResponse().getClientResponseStatus().getStatusCode();
      System.out.println("Service Status Code : " + statusCode);
      noContent =
          (statusCode == 204 || statusCode == 404); // HTTP 204 is NO CONTENT which is ok for us
    } catch (Exception e) { // Catch-all to deal with network problems etc.
      e.printStackTrace();
    }

    System.out.println(
        binRepoBranchCommitDO1 != null
            ? binRepoBranchCommitDO1.toString()
            : "Resource not found on server");

    // 4. If not copy all the target folders from the source repo to the binary repo - root to root
    // copy of artifacts
    if (noContent) {
      System.out.println(
          "Source Directory:'"
              + sourceDir.getCanonicalPath()
              + "' Destination Directory:'"
              + binaryRepoDir.getCanonicalPath()
              + "'");
      FileUtil.copyBinaries(sourceDir, binaryRepoDir);
    }

    // 5. Call git status to get the delta (Use StatusCommand and refine it)
    Git binaryRepo;
    try {
      binaryRepo = Git.open(binaryRepoDir);
    } catch (IOException e) {
      throw new GitException("Unable to open repository" + binaryRepoDir, e);
    }

    // get "status"
    final StatusCommand statusCommand = binaryRepo.status();
    // TODO: RGIROTI Ask Nambi if we should actually filter this to only add .class files and
    // nothing else
    Collection<String> filesToStage = GitUtils.getFilesToStage(statusCommand);
    /*for (String file : filesToStage) {
        System.out.println("File to be added:" + file);
    }*/

    // add files to "staging" - if there is nothing to stage none of the other operations make any
    // sense at all
    if (filesToStage.size() > 0) {
      final AddCommand addCmd = binaryRepo.add();
      for (String file : filesToStage) {
        addCmd.addFilepattern(file);
      }
      final String[] filesArr = filesToStage.toArray(new String[filesToStage.size()]);
      final String files = StringUtils.join(filesArr, ",");
      try {
        addCmd.call();
      } catch (Exception e) {
        throw new GitException("Unable to add files to repository" + files, e);
      }

      // 6. Commit the changes to local and call push after that (use JGit API for this)
      // 6a. COmmit message should use format "Saving url:branch:commit:UTC time"
      // commit
      final CommitCommand commitCommand = binaryRepo.commit();
      String msg = "Saving Repo:%s Branch:%s CommitHash:%s Time:%s";
      final String formattedMsg =
          String.format(msg, repoUrl, branch, commitHash, new Date().toString());
      commitCommand.setMessage(formattedMsg);
      String commitHashBinRepo;
      try {
        final RevCommit call = commitCommand.call();
        commitHashBinRepo = call.getName();
      } catch (Exception e) {
        throw new GitException("Unable to read commit hash from commit command", e);
      }

      // push to origin now
      final PushCommand push = binaryRepo.push();
      final String remote = push.getRemote();
      final String remoteBranch = push.getRepository().getBranch();
      System.out.println("Remote to push to:'" + remote + "'");
      try {
        push.call();
      } catch (Exception e) {
        throw new GitException("Unable to push to remote", e);
      }

      // Calculate the remote url for binary repository
      String binRepoUrl = calculateBinaryRepositoryUrl();

      // 7. Call the BinRepo service and create a new entity for this change - repoUrl, branch, and
      // commit
      System.out.println(
          "Update Bin Repo Service with the new changes - POST new object to service");
      final BinRepoBranchCommitDO binRepoBranchCommitDO =
          newInstance(repoUrl, branch, commitHash, binRepoUrl, remoteBranch, commitHashBinRepo);
      webResource = client.resource(getUrlForPost());

      BinRepoBranchCommitDO postedDO = null;
      try {
        postedDO =
            webResource
                .accept(MediaType.APPLICATION_XML)
                .post(BinRepoBranchCommitDO.class, binRepoBranchCommitDO);
      } catch (UniformInterfaceException e) {
        int statusCode = e.getResponse().getClientResponseStatus().getStatusCode();
        System.out.println("status code: " + statusCode);
        throw new MapServiceException("Unable to register the commit details in update binrepo", e);
      }
      System.out.println(postedDO != null ? postedDO.toString() : "Post failed");
    }
  }
Ejemplo n.º 18
0
  public void createBinaryRepository() throws IOException, GitException, MapServiceException {
    // check whether "binary repository" exists
    if (isBinaryRepositoryAvailable()) throw new GitException("Repository already exists");

    // find the name of the "source repository"
    // String sourceRepoName = getRepositoryName();

    // find where ".git" folder is found
    File f = sourceRepository.getDirectory();
    File sourceRepoFolder = f.getParentFile();

    String sourceRepoFolderName = f.getParentFile().getName();

    // calculate binary repository folder
    File parent = f.getParentFile().getParentFile();
    File binaryRepoFolder = new File(parent, ("." + sourceRepoFolderName));

    // create binary repository folder
    FileUtils.mkdir(binaryRepoFolder, true);

    // initialize "git" repository
    InitCommand initCmd = Git.init();
    initCmd.setDirectory(binaryRepoFolder);
    Git binaryRepo = null;
    try {
      System.out.println("initializing bare repository");
      binaryRepo = initCmd.call();
    } catch (GitAPIException e) {
      throw new GitException("unable to initialize repository", e);
    }

    System.out.println("adding readme.md file");
    createReadMeFile(binaryRepoFolder);

    // get "status"
    StatusCommand statusC = binaryRepo.status();
    Collection<String> toadd = GitUtils.getFilesToStage(statusC);

    // add "readme" file to staging
    if (toadd.size() > 0) {
      AddCommand add = binaryRepo.add();
      for (String file : toadd) {
        add.addFilepattern(file);
      }
      try {
        add.call();
        CommitCommand commit = binaryRepo.commit();
        commit.setMessage("initial commit");
        System.out.println("performing first commit");
        commit.call();
      } catch (NoFilepatternException e) {
        throw new GitException("unable to add file(s)", e);
      } catch (GitAPIException e) {
        throw new GitException("Unable to add or commit", e);
      }
    }

    // Calculate the remote url for binary repository
    String remoteUrl = calculateBinaryRepositoryUrl();

    // TODO: check whether the remote exists, if not create it, else fail
    GitHub github = new GitHubClient().getGithub();
    GHOrganization githubOrg = github.getOrganization("Binary");
    GHRepository repository = githubOrg.getRepository(GitUtils.getRepositoryName(remoteUrl));

    if (repository == null) {

      System.out.println("creating remote repository : " + remoteUrl);
      GHRepository repo =
          githubOrg.createRepository(
              GitUtils.getRepositoryName(remoteUrl),
              "Binary repository",
              "https://github.scm.corp.ebay.com",
              "Owners",
              true);

      System.out.println(repo.getUrl() + " created successfully ");

    } else {
      // fail, it shouldn't come here
    }

    // add "remote" repository
    StoredConfig config = binaryRepo.getRepository().getConfig();
    config.setString("remote", "origin", "url", remoteUrl);
    System.out.println("adding remote origin " + remoteUrl);
    config.save();

    // get "status"
    StatusCommand stat = binaryRepo.status();
    Collection<String> filesToAdd = GitUtils.getFilesToStage(stat);

    // add files to "staging"
    if (filesToAdd.size() > 0) {
      AddCommand addCmd = binaryRepo.add();
      for (String file : filesToAdd) {
        addCmd.addFilepattern(file);
      }
      try {
        addCmd.call();
      } catch (NoFilepatternException e) {
        throw new GitException("unable to add files", e);
      } catch (GitAPIException e) {
        throw new GitException("unable to add files", e);
      }
    }

    // commit
    System.out.println("commiting the files");
    CommitCommand commit = binaryRepo.commit();
    // add the 'source' repository git-url, commit-id and branch
    commit.setMessage("adding readme.md file");

    try {
      commit.call();
    } catch (NoHeadException e) {
      throw new GitException("unable to commit", e);
    } catch (NoMessageException e) {
      throw new GitException("unable to commit", e);
    } catch (UnmergedPathsException e) {
      throw new GitException("unable to commit", e);
    } catch (ConcurrentRefUpdateException e) {
      throw new GitException("unable to commit", e);
    } catch (WrongRepositoryStateException e) {
      throw new GitException("unable to commit", e);
    } catch (GitAPIException e) {
      throw new GitException("unable to commit", e);
    }

    // push
    System.out.println("pushing to remote");
    PushCommand push = binaryRepo.push();
    try {
      push.call();
    } catch (InvalidRemoteException e) {
      throw new GitException("unable to push", e);
    } catch (TransportException e) {
      throw new GitException("unable to push", e);
    } catch (GitAPIException e) {
      throw new GitException("unable to push", e);
    }

    // read the branch from "source" repository
    String branchname = sourceRepository.getBranch();

    // create a "branch"
    if (!branchname.toLowerCase().equals("master")) {
      CreateBranchCommand branchCmd = binaryRepo.branchCreate();
      branchCmd.setName(branchname);
      try {
        // create branch
        branchCmd.call();

        // checkout the branch
        CheckoutCommand checkout = binaryRepo.checkout();
        checkout.setName(branchname);
        checkout.call();
      } catch (RefAlreadyExistsException e) {
        throw new GitException("unable to create a branch", e);
      } catch (RefNotFoundException e) {
        throw new GitException("unable to create a branch", e);
      } catch (InvalidRefNameException e) {
        throw new GitException("unable to create a branch", e);
      } catch (GitAPIException e) {
        throw new GitException("unable to create a branch", e);
      }
    }

    // find the "localobr" folders and exclude them during copy
    List<String> excludes = new ArrayList<String>();
    Collection<File> excludeFiles =
        FileUtil.findDirectoriesThatEndWith(sourceRepoFolder, "localobr");
    for (File file : excludeFiles) {
      excludes.add(file.getCanonicalPath());
    }

    // copy the classes
    System.out.println("copying binary files");
    copyBinaryFolders("target", excludes, binaryRepoFolder);

    // get "status"
    StatusCommand statusCmd = binaryRepo.status();
    Collection<String> tobeAdded = GitUtils.getFilesToStage(statusCmd);

    // add files to "staging"
    if (tobeAdded.size() > 0) {
      AddCommand addCmd = binaryRepo.add();
      for (String file : tobeAdded) {
        addCmd.addFilepattern(file);
      }
      try {
        addCmd.call();
      } catch (NoFilepatternException e) {
        throw new GitException("unable to add files", e);
      } catch (GitAPIException e) {
        throw new GitException("unable to add files", e);
      }
    }

    // commit
    System.out.println("commiting the files");
    CommitCommand commit1 = binaryRepo.commit();
    commit1.setMessage("saving the files");

    try {
      commit1.call();
    } catch (NoHeadException e) {
      throw new GitException("unable to commit", e);
    } catch (NoMessageException e) {
      throw new GitException("unable to commit", e);
    } catch (UnmergedPathsException e) {
      throw new GitException("unable to commit", e);
    } catch (ConcurrentRefUpdateException e) {
      throw new GitException("unable to commit", e);
    } catch (WrongRepositoryStateException e) {
      throw new GitException("unable to commit", e);
    } catch (GitAPIException e) {
      throw new GitException("unable to commit", e);
    }

    // push
    System.out.println("pushing to remote");
    PushCommand pushCmd = binaryRepo.push();
    try {
      pushCmd.call();
    } catch (InvalidRemoteException e) {
      throw new GitException("unable to push", e);
    } catch (TransportException e) {
      throw new GitException("unable to push", e);
    } catch (GitAPIException e) {
      throw new GitException("unable to push", e);
    }

    final String repoUrl = getSourceRemoteUrl();
    // branchName was computed above
    final org.eclipse.jgit.lib.Repository repo =
        new org.eclipse.jgit.storage.file.FileRepository(f);
    final RevWalk revWalk = new RevWalk(repo);
    final ObjectId resolve = repo.resolve(Constants.HEAD);
    final RevCommit commitRev = revWalk.parseCommit(resolve);
    final String commitHash = commitRev.getName();

    Git git = Git.open(binaryRepoFolder);
    final RevCommit binRepoResolveCommitRev;
    try {
      binRepoResolveCommitRev = git.log().call().iterator().next();
    } catch (NoHeadException e) {
      throw new GitException("No head found for repo", e);
    } catch (GitAPIException e) {
      throw new GitException("No head found for repo", e);
    }
    final String binRepoResolveCommitHash = binRepoResolveCommitRev.getName();
    final String binRepoBranchName = git.getRepository().getBranch();

    System.out.println("Update Bin Repo Service with the new changes - POST new object to service");
    final BinRepoBranchCommitDO binRepoBranchCommitDO =
        newInstance(
            repoUrl,
            branchname,
            commitHash,
            remoteUrl,
            binRepoBranchName,
            binRepoResolveCommitHash);
    final WebResource resource = client.resource(getUrlForPost());

    BinRepoBranchCommitDO postedDO = null;
    try {
      postedDO =
          resource
              .accept(MediaType.APPLICATION_XML)
              .post(BinRepoBranchCommitDO.class, binRepoBranchCommitDO);
      System.out.println("Posted Object = " + postedDO.toString());
    } catch (UniformInterfaceException e) {
      int statusCode = e.getResponse().getClientResponseStatus().getStatusCode();
      System.out.println("status code: " + statusCode);
      throw new MapServiceException("Unable to register the commit details", e);
    }

    // System.out.println(postedDO != null ? postedDO.toString() : "postedDO was null");
    System.out.println("updated the map service");
  }
Ejemplo n.º 19
0
  static Git makeOpen() throws Exception {

    return Git.open(FILE);
  }
Ejemplo n.º 20
0
    /**
     * Gets the status of this file.
     *
     * @return status of this file.
     */
    public TextArea getStatus() {
      TextArea area = null;
      try {
        Path repoPath = this.getHost().repository;
        Git git = Git.open(repoPath.toFile());

        //
        // I would like to use absolutePath, but that seems to barf when
        // we try to relativize this if a full path is not given.
        //
        Path relativePath = repoPath.relativize(Paths.get(this.file.getPath()));

        Status status = git.status().addPath(relativePath.toString()).call();
        if (logger.isDebugEnabled()) {
          logger.debug(this.file.getAbsolutePath());
          logger.debug("Added: " + status.getAdded());
          logger.debug("Changed: " + status.getChanged());
          logger.debug("Conflicting: " + status.getConflicting());
          logger.debug("Missing: " + status.getMissing());
          logger.debug("Modified: " + status.getModified());
          logger.debug("Removed: " + status.getRemoved());
          logger.debug("Uncommitted: " + status.getUncommittedChanges());
          logger.debug("Untracked: " + status.getUntracked());
          logger.debug("Untracked folders; " + status.getUntrackedFolders());
        }
        //
        // Are we a file or directory?
        //
        StringBuffer buffer = new StringBuffer();
        int length = 0;
        if (this.file.isFile()) {
          if (status.getAdded().contains(relativePath.toString())) {
            buffer.append("Added" + "\n");
            length++;
          }
          if (status.getChanged().contains(relativePath.toString())) {
            buffer.append("Changed" + "\n");
            length++;
          }
          if (status.getConflicting().contains(relativePath.toString())) {
            buffer.append("Conflicting" + "\n");
            length++;
          }
          if (status.getMissing().contains(relativePath.toString())) {
            buffer.append("Missing" + "\n");
            length++;
          }
          if (status.getModified().contains(relativePath.toString())) {
            buffer.append("Modified" + "\n");
            length++;
          }
          if (status.getRemoved().contains(relativePath.toString())) {
            buffer.append("Removed" + "\n");
            length++;
          }
          if (status.getUncommittedChanges().contains(relativePath.toString())) {
            buffer.append("Uncommitted" + "\n");
            length++;
          }
          if (status.getUntracked().contains(relativePath.toString())) {
            buffer.append("Untracked (New)" + "\n");
            length++;
          }
          if (status.getUntrackedFolders().contains(relativePath.toString())) {
            buffer.append("Untracked Folders (New)" + "\n");
            length++;
          }
        } else if (this.file.isDirectory()) {
          if (status.getUntracked().size() > 0) {
            buffer.append("Untracked (New)" + "\n");
            length++;
          }
          if (status.getUntrackedFolders().size() > 0) {
            buffer.append("Untracked Folders (New)" + "\n");
            length++;
          }
        }
        if (length > 0) {
          area = new TextArea();
          area.setValue(buffer.toString().trim());
          area.setWidth("100.0%");
          area.setRows(length);
          area.setReadOnly(true);
        }
      } catch (IOException | NoWorkTreeException | GitAPIException e) {
        logger.error(e);
      }
      return area;
    }