Beispiel #1
0
  /**
   * This will create or refresh the working copy. If the working copy cannot be pulled cleanly this
   * method will fail.
   *
   * @param gitRepositoryUri remote git repository URI string
   * @return git
   * @throws GitAPIException
   * @throws IOException
   * @throws URISyntaxException
   */
  private Git getGit(final String gitRepositoryUri)
      throws GitAPIException, IOException, URISyntaxException {
    final Git cachedGit = gitCache.get(gitRepositoryUri);
    if (cachedGit != null) {
      return cachedGit;
    }
    final File gitDir =
        File.createTempFile(
            gitRepositoryUri.replaceAll("[^A-Za-z]", "_"), "wagon-git"); // $NON-NLS-1$
    gitDir.delete();
    gitDir.mkdir();

    credentialsProvider =
        new UsernamePasswordCredentialsProvider(
            getAuthenticationInfo().getUserName(),
            getAuthenticationInfo().getPassword() == null
                ? "" //$NON-NLS-1$
                : getAuthenticationInfo().getPassword());
    final Git git =
        Git.cloneRepository()
            .setURI(gitRepositoryUri)
            .setCredentialsProvider(credentialsProvider)
            .setBranch(gitUri.getBranchName())
            .setDirectory(gitDir)
            .call();
    if (!gitUri.getBranchName().equals(git.getRepository().getBranch())) {
      LOG.log(Level.INFO, "missingbranch", gitUri.getBranchName());
      final RefUpdate refUpdate =
          git.getRepository().getRefDatabase().newUpdate(Constants.HEAD, true);
      refUpdate.setForceUpdate(true);
      refUpdate.link("refs/heads/" + gitUri.getBranchName()); // $NON-NLS-1$
    }
    gitCache.put(gitRepositoryUri, git);
    return git;
  }
  @Test
  public void finishHotfixMasterIsTagged() throws Exception {
    Git git = RepoUtil.createRepositoryWithMasterAndTag(newDir());
    JGitFlowInitCommand initCommand = new JGitFlowInitCommand();
    JGitFlow flow = initCommand.setDirectory(git.getRepository().getWorkTree()).call();

    flow.hotfixStart("1.1").call();

    // Make sure we move away from master on a hotfix branch
    // This is important to validate JGITFFLOW-14

    // create a new commit
    File junkFile = new File(git.getRepository().getWorkTree(), "junk.txt");
    FileUtils.writeStringToFile(junkFile, "I am junk");
    git.add().addFilepattern(junkFile.getName()).call();
    git.commit().setMessage("committing junk file").call();

    flow.hotfixFinish("1.1").setNoTag(false).call();

    // we should be on develop branch
    assertEquals(flow.getDevelopBranchName(), git.getRepository().getBranch());

    // There should be a tag reference
    Ref hotfixTagRef = git.getRepository().getTags().get(flow.getVersionTagPrefix() + "1.1");

    assertNotNull(hotfixTagRef);

    RevTag hotfixTag = new RevWalk(git.getRepository()).parseTag(hotfixTagRef.getObjectId());

    assertNotNull(hotfixTag);

    // Check that latest tag has moved
    assertFalse(getTaggedCommit(git, "1.1").equals(getTaggedCommit(git, "1.0")));
  }
  @Test(expected = BranchOutOfDateException.class)
  public void finishHotfixMasterBehindRemoteWithFetch() throws Exception {
    Git git = null;
    Git remoteGit = null;
    remoteGit = RepoUtil.createRepositoryWithMasterAndTag(newDir());

    git =
        Git.cloneRepository()
            .setDirectory(newDir())
            .setURI("file://" + remoteGit.getRepository().getWorkTree().getPath())
            .call();

    JGitFlowInitCommand initCommand = new JGitFlowInitCommand();
    JGitFlow flow = initCommand.setDirectory(git.getRepository().getWorkTree()).call();

    flow.hotfixStart("1.1").call();

    // do a commit to the remote develop branch
    remoteGit.checkout().setName(flow.getDevelopBranchName());
    File junkFile = new File(remoteGit.getRepository().getWorkTree(), "junk.txt");
    FileUtils.writeStringToFile(junkFile, "I am junk");
    remoteGit.add().addFilepattern(junkFile.getName()).call();
    remoteGit.commit().setMessage("adding junk file").call();

    flow.hotfixFinish("1.1").setFetch(true).call();
  }
Beispiel #4
0
  @SuppressWarnings("unchecked")
  void analyzeForkTree(ForkEntry fe) throws Exception {

    RevWalk walk = null;

    String gitDirPath =
        GitWorks.gits_out_dir
            + GitWorks.getSafeName(fe)
            + ((GitWorks.bare == true) ? ".git" : "/.git");
    String treeDirPath = GitWorks.trees_out_dir + GitWorks.getSafeName(fe);

    try {
      // with git.init() it is not possible to specify a different tree path!!
      // git = Git.init().setBare(bare).setDirectory(new File(gitDirPath)).call();
      git = Git.wrap(createRepo(treeDirPath, gitDirPath));
      //    System.out.println(printRepoInfo());

      if (GitWorks.anew) {
        addRemotes(git, fe, Integer.MAX_VALUE);
      }

      name = GitWorks.getSafeName(fe);
      id = fe.getRetrievalTimestamp();
      if (allBranches == null) buildBranchesMap(fe.howManyForks());

      walk = new RevWalk(git.getRepository());

      if (allCommits == null) {
        init();
        getCommitsInB(walk, false);
        tailor();
      }
      getCommitsInB(walk, true);
      getCommitsInR(walk, false);
      getCommitsInR(walk, true);
      getCommitsNotInR(walk);

      authOfComInB = computePersonFreq(comInB);
      authOfComOnlyInB = computePersonFreq(comOnlyInB);
      authOfComInF = computePersonFreq(comInF);
      authOfComOnlyInF = computePersonFreq(comOnlyInF);
      authOfComNotInF = computePersonFreq(comNotInF);

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (walk != null) {
        walk.dispose();
        walk.release();
        walk = null;
      }
      if (git != null) {
        git.getRepository().close();
        git = null;
      }
      System.gc();
    }
  }
  @Test
  public void finishHotfixWithNewCommitAndReleaseBranch() throws Exception {
    Git git = RepoUtil.createRepositoryWithMasterAndTag(newDir());
    JGitFlowInitCommand initCommand = new JGitFlowInitCommand();
    JGitFlow flow = initCommand.setDirectory(git.getRepository().getWorkTree()).call();

    flow.releaseStart("1.1").call();

    String releaseName = "release/1.1";

    flow.git().checkout().setName("master").call();

    flow.hotfixStart("1.1.1").call();

    // create a new commit
    File junkFile = new File(git.getRepository().getWorkTree(), "junk.txt");
    FileUtils.writeStringToFile(junkFile, "I am junk");
    git.add().addFilepattern(junkFile.getName()).call();
    RevCommit commit = git.commit().setMessage("committing junk file").call();

    // make sure develop doesn't report our commit yet
    assertFalse(GitHelper.isMergedInto(git, commit, flow.getDevelopBranchName()));

    // make sure release doesn't report our commit yet
    assertFalse(GitHelper.isMergedInto(git, commit, releaseName));

    // try to finish
    flow.hotfixFinish("1.1.1").setKeepBranch(false).call();

    // we should be on develop branch
    assertEquals(flow.getDevelopBranchName(), git.getRepository().getBranch());

    // hotfix branch should be gone
    Ref ref2check = git.getRepository().getRef(flow.getHotfixBranchPrefix() + "1.1.1");
    assertNull(ref2check);

    // the develop branch should have our commit
    assertTrue(GitHelper.isMergedInto(git, commit, flow.getDevelopBranchName()));

    // since fast-forward is suppressed the latest commit on develop should be a merge commit with 2
    // parents
    assertEquals(2, GitHelper.getLatestCommit(git, flow.getDevelopBranchName()).getParentCount());

    // the master branch should have our commit
    assertTrue(GitHelper.isMergedInto(git, commit, getTaggedCommit(git, "1.1.1")));

    // since fast-forward is suppressed the latest commit on master should be a merge commit with 2
    // parents
    assertEquals(2, GitHelper.getLatestCommit(git, getTaggedCommit(git, "1.1.1")).getParentCount());

    // the release branch should have our commit
    assertTrue(GitHelper.isMergedInto(git, commit, releaseName));

    // since fast-forward is suppressed the latest commit on the release branch should be a merge
    // commit with 2 parents
    assertEquals(2, GitHelper.getLatestCommit(git, releaseName).getParentCount());
  }
Beispiel #6
0
 // print some structural info about the git repo
 String printRepoInfo() {
   String out = "Current GIT_DIR : " + git.getRepository().getDirectory().getAbsolutePath() + "\n";
   StoredConfig config = git.getRepository().getConfig();
   Set<String> sections = config.getSections();
   Set<String> subsections;
   out += "This repository has " + sections.size() + " sections:\n";
   for (String s : sections) {
     out += s + " : <";
     subsections = config.getSubsections(s);
     for (String ss : subsections) out += ss + "  ";
     out += ">\n";
   }
   return out;
 }
  @Test(expected = DirtyWorkingTreeException.class)
  public void finishHotfixWithUnStagedFile() throws Exception {
    Git git = RepoUtil.createRepositoryWithMasterAndTag(newDir());
    JGitFlowInitCommand initCommand = new JGitFlowInitCommand();
    JGitFlow flow = initCommand.setDirectory(git.getRepository().getWorkTree()).call();

    flow.hotfixStart("1.1").call();

    // create a new file
    File junkFile = new File(git.getRepository().getWorkTree(), "junk.txt");
    FileUtils.writeStringToFile(junkFile, "I am junk");

    // try to finish
    flow.hotfixFinish("1.1").call();
  }
Beispiel #8
0
 protected String defaultObjectId(Git git, String objectId) {
   if (objectId == null || objectId.trim().length() == 0) {
     RevCommit commit = CommitUtils.getHead(git.getRepository());
     objectId = commit.getName();
   }
   return objectId;
 }
Beispiel #9
0
  protected List<CommitInfo> doHistory(
      Git git, String branch, String objectId, String path, int limit) {
    Repository r = git.getRepository();

    CommitFinder finder = new CommitFinder(r);
    CommitListFilter block = new CommitListFilter();
    if (Strings.isNotBlank(path)) {
      finder.setFilter(PathFilterUtils.and(path));
    }
    finder.setFilter(block);

    if (limit > 0) {
      finder.setFilter(new CommitLimitFilter(100).setStop(true));
    }
    if (Strings.isNotBlank(objectId)) {
      finder.findFrom(objectId);
    } else {
      if (Strings.isNotBlank(branch)) {
        RevCommit base = CommitUtils.getBase(r, branch);
        finder.findFrom(base);
      } else {
        finder.find();
      }
    }
    List<RevCommit> commits = block.getCommits();
    List<CommitInfo> results = new ArrayList<CommitInfo>();
    for (RevCommit entry : commits) {
      CommitInfo commitInfo = createCommitInfo(entry);
      results.add(commitInfo);
    }
    return results;
  }
Beispiel #10
0
 private void close(Git git) {
   // really close the repository
   // decrement the use counter to 0
   for (int i = 0; i < 2; i++) {
     git.getRepository().close();
   }
 }
Beispiel #11
0
 public BranchCollector(Git git) {
   this.git = git;
   this.repository = git.getRepository();
   if (masterRef == null) {
     this.masterRef = this.findMasterRef();
   }
 }
Beispiel #12
0
 public static List<File> getNotIgnoredFilesOfRepo(File directory) throws GitException {
   Git git = openRepository(directory);
   Repository repo = null;
   repo = git.getRepository();
   List<File> foundFiles = new ArrayList<>();
   TreeWalk treeWalk = null;
   try {
     treeWalk = new TreeWalk(repo);
     FileTreeIterator tree = new FileTreeIterator(repo);
     treeWalk.addTree(tree);
     treeWalk.setRecursive(false);
     while (treeWalk.next()) {
       WorkingTreeIterator iterator = treeWalk.getTree(0, WorkingTreeIterator.class);
       if (!iterator.isEntryIgnored())
         if (treeWalk.isSubtree()) {
           treeWalk.enterSubtree();
         } else {
           File file = new File(directory, treeWalk.getPathString());
           foundFiles.add(file);
         }
     }
   } catch (IOException e) {
     throw new GitException("Listing of non-ignored files in " + directory + " failed", e);
   } finally {
     if (treeWalk != null) treeWalk.close();
   }
   return foundFiles;
 }
Beispiel #13
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());
  }
Beispiel #14
0
  protected void createAndCheckoutBranch()
      throws MojoExecutionException, IOException, GitAPIException {
    if (Strings.isNullOrBlank(oldBranchName)) {
      // lets find the previous branch
      List<String> branches =
          new ArrayList<String>(RepositoryUtils.getBranches(git.getRepository()));
      int size = branches.size();
      if (size > 0) {
        String last = branches.get(size - 1);
        int idx = last.lastIndexOf('/');
        if (idx > 0) {
          oldBranchName = last.substring(idx + 1);
          getLog().info("Using previous branch: " + oldBranchName);
        }
      }
    }
    if (Strings.isNullOrBlank(oldBranchName)) {
      oldBranchName = "master";
      getLog().warn("Could not deduce the old branch so setting it to: " + oldBranchName);
    }
    checkoutBranch(git, oldBranchName);
    getLog().info("Creating branch " + branchName + " in " + getGitBuildPathDescription());

    createOrCheckoutBranch(git, branchName, remoteName);
    checkoutBranch(git, branchName);
  }
Beispiel #15
0
 protected void configureBranch(String branch) {
   // lets update the merge config
   if (Strings.isNotBlank(branch) && hasRemoteRepo()) {
     StoredConfig config = git.getRepository().getConfig();
     if (Strings.isNullOrBlank(config.getString("branch", branch, "remote"))
         || Strings.isNullOrBlank(config.getString("branch", branch, "merge"))) {
       config.setString("branch", branch, "remote", remoteName);
       config.setString("branch", branch, "merge", "refs/heads/" + branch);
       try {
         config.save();
       } catch (IOException e) {
         getLog()
             .error(
                 "Failed to save the git configuration into "
                     + new File(buildDir, ".git")
                     + " with branch "
                     + branch
                     + " on remote repo: "
                     + gitUrl
                     + " due: "
                     + e.getMessage()
                     + ". This exception is ignored.",
                 e);
       }
     }
   }
 }
Beispiel #16
0
 @Override
 public String getContent(String objectId, String blobPath) {
   objectId = defaultObjectId(objectId);
   Repository r = git.getRepository();
   RevCommit commit = JGitUtils.getCommit(r, objectId);
   return JGitUtils.getStringContent(r, commit.getTree(), blobPath, encodings);
 }
Beispiel #17
0
  private IStatus doClone() {
    try {
      File cloneFolder = new File(clone.getContentLocation().getPath());
      if (!cloneFolder.exists()) {
        cloneFolder.mkdir();
      }
      CloneCommand cc = Git.cloneRepository();
      cc.setBare(false);
      cc.setCredentialsProvider(credentials);
      cc.setDirectory(cloneFolder);
      cc.setRemote(Constants.DEFAULT_REMOTE_NAME);
      cc.setURI(clone.getUrl());
      Git git = cc.call();

      // Configure the clone, see Bug 337820
      setMessage(NLS.bind("Configuring {0}...", clone.getUrl()));
      GitCloneHandlerV1.doConfigureClone(git, user);
      git.getRepository().close();
    } catch (IOException e) {
      return new Status(IStatus.ERROR, GitActivator.PI_GIT, "Error cloning git repository", e);
    } catch (CoreException e) {
      return e.getStatus();
    } catch (GitAPIException e) {
      return getGitAPIExceptionStatus(e, "Error cloning git repository");
    } catch (JGitInternalException e) {
      return getJGitInternalExceptionStatus(e, "Error cloning git repository");
    } catch (Exception e) {
      return new Status(IStatus.ERROR, GitActivator.PI_GIT, "Error cloning git repository", e);
    }
    return Status.OK_STATUS;
  }
Beispiel #18
0
  private void completeUndo(Git git) {
    try {
      if (isUndo(git)) {
        git.checkout().setName("master").call();
        git.merge()
            .setStrategy(MergeStrategy.THEIRS)
            .include(git.getRepository().resolve("undo"))
            .setCommit(true)
            .call();
        git.branchDelete().setBranchNames("undo").call();
      }
    } catch (RuntimeException ex) {

    } catch (CheckoutConflictException e) {
      throw new RuntimeException(e);
    } catch (RefAlreadyExistsException e) {
      throw new RuntimeException(e);
    } catch (IOException e) {
      throw new RuntimeException(e);
    } catch (InvalidRefNameException e) {
      throw new RuntimeException(e);
    } catch (RefNotFoundException e) {
      throw new RuntimeException(e);
    } catch (GitAPIException e) {
      throw new RuntimeException(e);
    }
  }
  @Test
  public void testGetCloneAndPull() throws Exception {
    // see bug 339254
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = getWorkspaceId(workspaceLocation);

    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath =
        new Path("file").append(project.getString(ProtocolConstants.KEY_ID)).makeAbsolute();
    String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

    // get clones for workspace
    WebRequest request = listGitClonesRequest(workspaceId, null);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject clones = new JSONObject(response.getText());
    JSONArray clonesArray = clones.getJSONArray(ProtocolConstants.KEY_CHILDREN);
    assertEquals(1, clonesArray.length());

    Git git = new Git(getRepositoryForContentLocation(contentLocation));
    // TODO: replace with RESTful API when ready, see bug 339114
    PullResult pullResult = git.pull().call();
    assertEquals(pullResult.getMergeResult().getMergeStatus(), MergeStatus.ALREADY_UP_TO_DATE);
    assertEquals(RepositoryState.SAFE, git.getRepository().getRepositoryState());
  }
  @Before
  public void setUp() throws Exception {
    sfb = new ZKServerFactoryBean();
    delete(sfb.getDataDir());
    delete(sfb.getDataLogDir());
    sfb.afterPropertiesSet();

    CuratorFrameworkFactory.Builder builder =
        CuratorFrameworkFactory.builder()
            .connectString("localhost:" + sfb.getClientPortAddress().getPort())
            .retryPolicy(new RetryOneTime(1000))
            .connectionTimeoutMs(360000);

    curator = builder.build();
    curator.start();
    curator.getZookeeperClient().blockUntilConnectedOrTimedOut();

    // setup a local and remote git repo
    basedir = System.getProperty("basedir", ".");
    File root = new File(basedir + "/target/git").getCanonicalFile();
    delete(root);

    new File(root, "remote").mkdirs();
    remote = Git.init().setDirectory(new File(root, "remote")).call();
    remote.commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call();
    String remoteUrl = "file://" + new File(root, "remote").getCanonicalPath();

    new File(root, "local").mkdirs();
    git = Git.init().setDirectory(new File(root, "local")).call();
    git.commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call();
    StoredConfig config = git.getRepository().getConfig();
    config.setString("remote", "origin", "url", remoteUrl);
    config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
    config.save();

    DefaultRuntimeProperties sysprops = new DefaultRuntimeProperties();
    sysprops.setProperty(SystemProperties.KARAF_DATA, "target/data");
    FabricGitServiceImpl gitService = new FabricGitServiceImpl();
    gitService.bindRuntimeProperties(sysprops);
    gitService.activate();
    gitService.setGitForTesting(git);

    DataStoreTemplateRegistry registrationHandler = new DataStoreTemplateRegistry();
    registrationHandler.activateComponent();

    dataStore = new CachingGitDataStore();
    dataStore.bindCurator(curator);
    dataStore.bindGitService(gitService);
    dataStore.bindRegistrationHandler(registrationHandler);
    dataStore.bindRuntimeProperties(sysprops);
    dataStore.bindConfigurer(
        new Configurer() {
          @Override
          public <T> void configure(Map<String, ?> configuration, T target) throws Exception {}
        });
    Map<String, String> datastoreProperties = new HashMap<String, String>();
    datastoreProperties.put(GitDataStore.GIT_REMOTE_URL, remoteUrl);
    dataStore.activate(datastoreProperties);
  }
Beispiel #21
0
 /**
  * This will get the file object for the given resource relative to the {@link Git} specified for
  * the connection. It will handle resources where it jumps up past the parent folder.
  *
  * @param resourceName resource name.
  * @return file used for the resourse.
  * @throws IOException
  * @throws GitAPIException
  * @throws URISyntaxException
  */
 private File getFileForResource(final String resourceName)
     throws GitAPIException, IOException, URISyntaxException {
   // /foo/bar/foo.git + ../bar.git == /foo/bar/bar.git + /
   // /foo/bar/foo.git + ../bar.git/abc == /foo/bar/bar.git + /abc
   final GitUri resolved = gitUri.resolve(resourceName);
   final Git resourceGit = getGit(resolved.getGitRepositoryUri());
   return new File(resourceGit.getRepository().getWorkTree(), resolved.getResource());
 }
Beispiel #22
0
  @Override
  public List<CommitInfo> log(
      String objectId,
      final String path,
      int limit,
      int pageOffset,
      boolean showRemoteRefs,
      int itemsPerPage) {

    try {
      if (itemsPerPage <= 1) {
        itemsPerPage = 50;
      }
      boolean pageResults = limit <= 0;
      Repository r = git.getRepository();

      // TODO not sure if this is the right String we should use for the sub module stuff...
      String repositoryName = getConfigDirectory().getPath();

      objectId = defaultObjectId(objectId);

      final Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(r, showRemoteRefs);
      List<RevCommit> commits;
      if (pageResults) {
        // Paging result set
        commits = JGitUtils.getRevLog(r, objectId, pageOffset * itemsPerPage, itemsPerPage);
      } else {
        // Fixed size result set
        commits = JGitUtils.getRevLog(r, objectId, 0, limit);
      }

      List<CommitInfo> answer = new ArrayList<CommitInfo>();
      for (RevCommit entry : commits) {
        final Date date = JGitUtils.getCommitDate(entry);
        String author = entry.getAuthorIdent().getName();
        boolean merge = entry.getParentCount() > 1;

        // short message
        String shortMessage = entry.getShortMessage();
        String trimmedMessage = shortMessage;
        if (allRefs.containsKey(entry.getId())) {
          trimmedMessage = StringUtils.trimString(shortMessage, Constants.LEN_SHORTLOG_REFS);
        } else {
          trimmedMessage = StringUtils.trimString(shortMessage, Constants.LEN_SHORTLOG);
        }

        String name = entry.getName();
        String commitHash = getShortCommitHash(name);
        answer.add(
            new CommitInfo(
                commitHash, name, "log", author, date, merge, trimmedMessage, shortMessage));
      }
      return answer;
    } catch (Exception e) {
      throw new RuntimeIOException(e);
    }
  }
Beispiel #23
0
  /**
   * Initialize a new git repository.
   *
   * @param dir The directory in which to create a new .git/ folder and repository.
   */
  public static Git init(final DirectoryResource dir) throws IOException {
    FileResource<?> gitDir = dir.getChildDirectory(".git").reify(FileResource.class);
    gitDir.mkdirs();

    RepositoryBuilder db =
        new RepositoryBuilder().setGitDir(gitDir.getUnderlyingResourceObject()).setup();
    Git git = new Git(db.build());
    git.getRepository().create();
    return git;
  }
  @Test
  public void finishHotfix() throws Exception {
    Git git = RepoUtil.createRepositoryWithMasterAndTag(newDir());
    JGitFlowInitCommand initCommand = new JGitFlowInitCommand();
    JGitFlow flow = initCommand.setDirectory(git.getRepository().getWorkTree()).call();

    flow.hotfixStart("1.1").call();

    assertEquals(flow.getHotfixBranchPrefix() + "1.1", git.getRepository().getBranch());

    flow.hotfixFinish("1.1").call();

    // we should be on develop branch
    assertEquals(flow.getDevelopBranchName(), git.getRepository().getBranch());

    // release branch should be gone
    Ref ref2check = git.getRepository().getRef(flow.getHotfixBranchPrefix() + "1.1");
    assertNull(ref2check);
  }
  @Test
  public void finishHotfixWithMultipleCommits() throws Exception {
    Git git = RepoUtil.createRepositoryWithMasterAndTag(newDir());
    JGitFlowInitCommand initCommand = new JGitFlowInitCommand();
    JGitFlow flow = initCommand.setDirectory(git.getRepository().getWorkTree()).call();

    flow.hotfixStart("1.1").call();

    // create a new commit
    File junkFile = new File(git.getRepository().getWorkTree(), "junk.txt");
    FileUtils.writeStringToFile(junkFile, "I am junk");
    git.add().addFilepattern(junkFile.getName()).call();
    RevCommit commit = git.commit().setMessage("committing junk file").call();

    // create second commit
    File junkFile2 = new File(git.getRepository().getWorkTree(), "junk2.txt");
    FileUtils.writeStringToFile(junkFile2, "I am junk, and so are you");
    git.add().addFilepattern(junkFile2.getName()).call();
    RevCommit commit2 = git.commit().setMessage("updating junk file").call();

    // make sure develop doesn't have our commits yet
    assertFalse(GitHelper.isMergedInto(git, commit, flow.getDevelopBranchName()));
    assertFalse(GitHelper.isMergedInto(git, commit2, flow.getDevelopBranchName()));

    // try to finish
    flow.hotfixFinish("1.1").call();

    // we should be on develop branch
    assertEquals(flow.getDevelopBranchName(), git.getRepository().getBranch());

    // release branch should be gone
    Ref ref2check = git.getRepository().getRef(flow.getHotfixBranchPrefix() + "1.1");
    assertNull(ref2check);

    // the develop branch should have both of our commits now
    assertTrue(GitHelper.isMergedInto(git, commit, flow.getDevelopBranchName()));
    assertTrue(GitHelper.isMergedInto(git, commit2, flow.getDevelopBranchName()));

    // the master branch should have both of our commits now
    assertTrue(GitHelper.isMergedInto(git, commit, getTaggedCommit(git, "1.1")));
    assertTrue(GitHelper.isMergedInto(git, commit2, getTaggedCommit(git, "1.1")));
  }
Beispiel #26
0
  public static Iterable<RevCommit> getLogForBranch(final Git repo, String branchName)
      throws GitAPIException, IOException {
    String oldBranch = repo.getRepository().getBranch();
    repo.checkout().setName(branchName).call();

    Iterable<RevCommit> commits = repo.log().call();

    repo.checkout().setName(oldBranch).call();

    return commits;
  }
 public static boolean clone(String URL, String localpaths) throws IOException, GitAPIException {
   File localPath = new File(localpaths);
   if (!localPath.exists()) localPath.mkdir();
   try {
     Git result = Git.cloneRepository().setURI(URL).setDirectory(localPath).call();
     result.getRepository().close();
     return true;
   } catch (Exception e) {
     return false;
   }
 }
Beispiel #28
0
 private static String getRemoteOfUrl(File directory, String url) throws GitException {
   Git git = openRepository(directory);
   StoredConfig config = git.getRepository().getConfig();
   Set<String> remotes = config.getSubsections("remote");
   for (String remote : remotes) {
     String remoteUrl = config.getString("remote", remote, "url");
     if (remoteUrl.equals(url)) {
       return remote;
     }
   }
   return null;
 }
Beispiel #29
0
 /**
  * Returns true if the remote git url is defined or the local git repo has a remote url defined
  */
 protected boolean hasRemoteRepo() {
   if (Strings.isNotBlank(gitUrl)) {
     return true;
   }
   Repository repository = git.getRepository();
   StoredConfig config = repository.getConfig();
   String url = config.getString("remote", remoteName, "url");
   if (Strings.isNotBlank(url)) {
     return true;
   }
   return false;
 }
  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");
  }