Java Code Examples for org.eclipse.jgit.lib.Constants

The following examples show how to use org.eclipse.jgit.lib.Constants. These examples are extracted from open source projects. 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 Project: hop   Source File: UIGit.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void revertPath( String path ) {
  try {
    // Delete added files
    Status status = git.status().addPath( path ).call();
    if ( status.getUntracked().size() != 0 || status.getAdded().size() != 0 ) {
      resetPath( path );
      org.apache.commons.io.FileUtils.deleteQuietly( new File( directory, path ) );
    }

    /*
     * This is a work-around to discard changes of conflicting files
     * Git CLI `git checkout -- conflicted.txt` discards the changes, but jgit does not
     */
    git.add().addFilepattern( path ).call();

    git.checkout().setStartPoint( Constants.HEAD ).addPath( path ).call();
    org.apache.commons.io.FileUtils.deleteQuietly( new File( directory, path + ".ours" ) );
    org.apache.commons.io.FileUtils.deleteQuietly( new File( directory, path + ".theirs" ) );
  } catch ( Exception e ) {
    showMessageBox( BaseMessages.getString( PKG, "Dialog.Error" ), e.getMessage() );
  }
}
 
Example 2
Source Project: orion.server   Source File: Branch.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@PropertyDescription(name = GitConstants.KEY_REMOTE)
private JSONArray getRemotes() throws URISyntaxException, JSONException, IOException, CoreException {
	String branchName = Repository.shortenRefName(ref.getName());
	String remoteName = getConfig().getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REMOTE);
	List<RemoteConfig> remoteConfigs = RemoteConfig.getAllRemoteConfigs(getConfig());
	ArrayList<JSONObject> remotes = new ArrayList<JSONObject>();
	for (RemoteConfig remoteConfig : remoteConfigs) {
		if (!remoteConfig.getFetchRefSpecs().isEmpty()) {
			Remote r = new Remote(cloneLocation, db, remoteConfig.getName());
			r.setNewBranch(branchName);
			// Ensure that the remote tracking branch is the first in the list.
			// Insert at the beginning of the list as well when the remote tracking branch is not set but the branch has been pushed to the remote
			if (remoteConfig.getName().equals(remoteName) || (remoteName == null && db.resolve(Constants.R_REMOTES + remoteConfig.getName() + "/" + branchName) != null)) {
				remotes.add(0, r.toJSON());
			} else {
				remotes.add(r.toJSON());
			}
		}
	}
	JSONArray result = new JSONArray();
	for (JSONObject remote : remotes) {
		result.put(remote);
	}
	return result;
}
 
Example 3
Source Project: jgitver   Source File: Scenarios.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Merges commit with id given as parameter with current branch using given FastForwardMode.
 * @param sourceId the application identifier to use as merge source
 * @param id the application identifier to use to store the git commitID of merge commit
 * @param mode the non null fast forward strategy to use for the merge
 * @return the builder itself to continue building the scenario
 */
public ScenarioBuilder merge(String sourceId, String id, MergeCommand.FastForwardMode mode) {
    try {
        ObjectId other = scenario.getCommits().get(sourceId);
        ObjectId head = repository.resolve(Constants.HEAD);
        String nameOfHead = scenario.nameOf(head);
        MergeResult rc = git.merge()
                .setFastForward(mode)
                .setMessage(String.format("%s :: merge %s into %s", id, sourceId, nameOfHead))
                .include(other)
                .call();
        scenario.getCommits().put(id, rc.getNewHead());
    } catch (Exception ex) {
        throw new IllegalStateException(String.format("error merging %s", id), ex);
    }
    return this;
}
 
Example 4
Source Project: netbeans   Source File: CatTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testCatRemoved () throws Exception {
    File f = new File(workDir, "removed");
    copyFile(getGoldenFile(), f);
    assertFile(getGoldenFile(), f);
    add(f);
    commit(f);

    GitClient client = getClient(workDir);
    String revision = new Git(repository).log().call().iterator().next().getId().getName();

    // remove and commit
    client.remove(new File[] { f }, false, NULL_PROGRESS_MONITOR);
    commit(f);
    assertTrue(client.catFile(f, revision, new FileOutputStream(f), NULL_PROGRESS_MONITOR));
    assertFile(f, getGoldenFile());

    assertFalse(client.catFile(f, Constants.HEAD, new FileOutputStream(f), NULL_PROGRESS_MONITOR));
}
 
Example 5
Source Project: rewrite   Source File: Change.java    License: Apache License 2.0 6 votes vote down vote up
InMemoryDiffEntry(Path filePath, @Nullable Path relativeTo, String oldSource, String newSource) {
    this.changeType = ChangeType.MODIFY;

    var relativePath = relativeTo == null ? filePath : relativeTo.relativize(filePath);
    this.oldPath = relativePath.toString();
    this.newPath = relativePath.toString();

    try {
        this.repo = new InMemoryRepository.Builder().build();

        var inserter = repo.getObjectDatabase().newInserter();
        oldId = inserter.insert(Constants.OBJ_BLOB, oldSource.getBytes()).abbreviate(40);
        newId = inserter.insert(Constants.OBJ_BLOB, newSource.getBytes()).abbreviate(40);
        inserter.flush();

        oldMode = FileMode.REGULAR_FILE;
        newMode = FileMode.REGULAR_FILE;
        repo.close();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 6
Source Project: netbeans   Source File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
public static GitBranch getTrackedBranch (Config config, String branchName, Map<String, GitBranch> allBranches) {
    String remoteName = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REMOTE);
    String trackedBranchName = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_MERGE);
    if (trackedBranchName != null) {
        if (trackedBranchName.startsWith(Constants.R_HEADS)) {
            trackedBranchName = trackedBranchName.substring(Constants.R_HEADS.length());
        } else if (trackedBranchName.startsWith(Constants.R_REMOTES)) {
            trackedBranchName = trackedBranchName.substring(Constants.R_REMOTES.length());
        }
    }
    if (trackedBranchName == null) {
        return null;
    } else {
        if (remoteName != null && ".".equals(remoteName)) { //NOI18N
            remoteName = ""; //NOI18N
        } else {
            remoteName = remoteName + "/"; //NOI18N
        }
        return allBranches.get(remoteName + trackedBranchName);
    }
}
 
Example 7
Source Project: netbeans   Source File: CheckoutTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testCheckoutRevisionAddRemoveFile () throws Exception {
    File file = new File(workDir, "file");
    write(file, "initial");
    File[] files = new File[] { file };
    add(files);
    GitClient client = getClient(workDir);
    GitRevisionInfo info = client.commit(files, "initial", null, null, NULL_PROGRESS_MONITOR);
    client.createBranch(BRANCH, info.getRevision(), NULL_PROGRESS_MONITOR);
    client.checkoutRevision(BRANCH, true, NULL_PROGRESS_MONITOR);
    
    remove(false, file);
    commit(files);
    
    // test checkout
    // the file is added to WT
    client.checkoutRevision(Constants.MASTER, true, NULL_PROGRESS_MONITOR);
    assertTrue(file.exists());
    Map<File, GitStatus> statuses = client.getStatus(new File[] { workDir }, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, file, true, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, false);
    
    // the file is removed from WT
    client.checkoutRevision(BRANCH, true, NULL_PROGRESS_MONITOR);
    assertFalse(file.exists());
    statuses = client.getStatus(new File[] { workDir }, NULL_PROGRESS_MONITOR);
    assertNull(statuses.get(file));
}
 
Example 8
Source Project: onedev   Source File: BitmappedReachabilityChecker.java    License: MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public final boolean include(RevWalk walker, RevCommit cmit) {
	Bitmap commitBitmap;

	if (reached.contains(cmit)) {
		// already seen or included
		dontFollow(cmit);
		return false;
	}

	if ((commitBitmap = repoBitmaps.getBitmap(cmit)) != null) {
		reached.or(commitBitmap);
		// Emit the commit because there are new contents in the bitmap
		// but don't follow parents (they are already in the bitmap)
		dontFollow(cmit);
		return true;
	}

	// No bitmaps, keep going
	reached.addObject(cmit, Constants.OBJ_COMMIT);
	return true;
}
 
Example 9
Source Project: onedev   Source File: RevisionSelector.java    License: MIT License 6 votes vote down vote up
public RevisionSelector(String id, IModel<Project> projectModel, @Nullable String revision, boolean canCreateRef) {
	super(id);
	
	Preconditions.checkArgument(revision!=null || !canCreateRef);

	this.projectModel = projectModel;
	this.revision = revision;		
	if (canCreateRef) {
		Project project = projectModel.getObject();
		canCreateBranch = SecurityUtils.canCreateBranch(project, Constants.R_HEADS);						
		canCreateTag = SecurityUtils.canCreateTag(project, Constants.R_TAGS);						
	} else {
		canCreateBranch = false;
		canCreateTag = false;
	}
	if (revision != null) {
		Ref ref = projectModel.getObject().getRef(revision);
		branchesActive = ref == null || GitUtils.ref2tag(ref.getName()) == null;
	} else {
		branchesActive = true;
	}
	
	refs = findRefs();
}
 
Example 10
Source Project: netbeans   Source File: PullTest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    workDir = getWorkingDirectory();
    repository = getRepository(getLocalGitRepository());
    
    otherWT = new File(workDir.getParentFile(), "repo2");
    GitClient client = getClient(otherWT);
    client.init(NULL_PROGRESS_MONITOR);
    f = new File(otherWT, "f");
    write(f, "init");
    f2 = new File(otherWT, "f2");
    write(f2, "init");
    client.add(new File[] { f, f2 }, NULL_PROGRESS_MONITOR);
    masterInfo = client.commit(new File[] { f, f2 }, "init commit", null, null, NULL_PROGRESS_MONITOR);
    branch = client.createBranch(BRANCH_NAME, Constants.MASTER, NULL_PROGRESS_MONITOR);
    RemoteConfig cfg = new RemoteConfig(repository.getConfig(), "origin");
    cfg.addURI(new URIish(otherWT.toURI().toURL().toString()));
    cfg.update(repository.getConfig());
    repository.getConfig().save();
}
 
Example 11
Source Project: orion.server   Source File: GitRemoteTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testGetOrigin() throws Exception {
	createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
	IPath[] clonePaths = createTestProjects(workspaceLocation);

	for (IPath clonePath : clonePaths) {
		// clone a  repo
		JSONObject clone = clone(clonePath);
		String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
		String gitRemoteUri = clone.getString(GitConstants.KEY_REMOTE);
		JSONObject remoteBranch = getRemoteBranch(gitRemoteUri, 1, 0, Constants.MASTER);
		assertNotNull(remoteBranch);

		// get project/folder metadata
		WebRequest request = getGetRequest(cloneContentLocation);
		WebResponse response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
		JSONObject folder = new JSONObject(response.getText());

		// check if Git locations are in place
		JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
		assertEquals(gitRemoteUri, gitSection.getString(GitConstants.KEY_REMOTE));
	}
}
 
Example 12
Source Project: onedev   Source File: Project.java    License: MIT License 6 votes vote down vote up
public RevCommit getLastCommit() {
	if (lastCommitHolder == null) {
		RevCommit lastCommit = null;
		try {
			for (Ref ref: getRepository().getRefDatabase().getRefsByPrefix(Constants.R_HEADS)) {
				RevCommit commit = getRevCommit(ref.getObjectId(), false);
				if (commit != null) {
					if (lastCommit != null) {
						if (commit.getCommitTime() > lastCommit.getCommitTime())
							lastCommit = commit;
					} else {
						lastCommit = commit;
					}
				}
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		lastCommitHolder = Optional.fromNullable(lastCommit);
	}
	return lastCommitHolder.orNull();
}
 
Example 13
Source Project: git-as-svn   Source File: GitDeltaConsumer.java    License: GNU General Public License v2.0 6 votes vote down vote up
boolean migrateFilter(@NotNull GitFilter filter) throws IOException {
  if (newFilter == null || objectId == null) {
    throw new IllegalStateException("Original object ID defined, but original Filter is not defined");
  }
  final GitObject<ObjectId> beforeId = objectId;
  if (!newFilter.equals(filter)) {
    final Repository repo = writer.getBranch().getRepository().getGit();

    try (TemporaryOutputStream content = new TemporaryOutputStream()) {
      try (InputStream inputStream = newFilter.inputStream(objectId);
           OutputStream outputStream = filter.outputStream(new UncloseableOutputStream(content), user)) {
        IOUtils.copy(inputStream, outputStream);
      }
      try (InputStream inputStream = content.toInputStream()) {
        objectId = new GitObject<>(repo, writer.getInserter().insert(Constants.OBJ_BLOB, content.size(), inputStream));
        newFilter = filter;
      }
    }
  }
  return !beforeId.equals(objectId);
}
 
Example 14
Source Project: git-client-plugin   Source File: GitClientTest.java    License: 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 15
Source Project: netbeans   Source File: IgnoreTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testIgnoreFolderNoNegationRemoval_NestedIgnoreFile () throws Exception {
    File f = new File(new File(new File(workDir, "sf1"), "sf2"), "folder");
    f.mkdirs();
    File gitIgnore = new File(f.getParentFile().getParentFile(), Constants.DOT_GIT_IGNORE);
    write(gitIgnore, "\n/sf2/folder/\n!/sf2/folder");
    File[] ignores = getClient(workDir).ignore(new File[] { f }, NULL_PROGRESS_MONITOR);
    assertTrue(gitIgnore.exists());
    assertEquals("\n!/sf2/folder\n/sf2/folder/", read(gitIgnore));
    assertFalse(new File(workDir, Constants.DOT_GIT_IGNORE).exists());
    assertEquals(Arrays.asList(gitIgnore), Arrays.asList(ignores));
}
 
Example 16
Source Project: orion.server   Source File: Index.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public ObjectStream toObjectStream() throws IOException {
	DirCache cache = db.readDirCache();
	DirCacheEntry entry = cache.getEntry(pattern);
	if (entry == null) {
		return null;
	}
	try {
		ObjectId blobId = entry.getObjectId();
		return db.open(blobId, Constants.OBJ_BLOB).openStream();
	} catch (MissingObjectException e) {
		return null;
	}
}
 
Example 17
Source Project: celerio   Source File: GITStatusCrawler.java    License: Apache License 2.0 5 votes vote down vote up
private static RevTree getTree(Repository repository) throws IOException {
    ObjectId lastCommitId = repository.resolve(Constants.HEAD);

    // a RevWalk allows to walk over commits based on some filtering
    RevWalk revWalk = new RevWalk(repository);
    RevCommit commit = revWalk.parseCommit(lastCommitId);

    // and using commit's tree find the path
    RevTree tree = commit.getTree();
    return tree;
}
 
Example 18
Source Project: git-client-plugin   Source File: GitClientTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testgetRemoteSymbolicReferences_with_matching_pattern_old_git() throws Exception {
    assumeFalse(CLI_GIT_SUPPORTS_SYMREF);
    assumeThat(gitImplName, is("git"));
    commitOneFile("A-Single-File-Commit");
    assertThat(gitClient.getRemoteSymbolicReferences(repoRoot.getAbsolutePath(), Constants.HEAD).keySet(), hasSize(0));
}
 
Example 19
Source Project: hop   Source File: UIGit.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String getBranch() {
  try {
    Ref head = git.getRepository().exactRef( Constants.HEAD );
    String branch = git.getRepository().getBranch();
    if ( head.getLeaf().getName().equals( Constants.HEAD ) ) { // if detached
      return Constants.HEAD + " detached at " + branch.substring( 0, 7 );
    } else {
      return branch;
    }
  } catch ( Exception e ) {
    return "";
  }
}
 
Example 20
Source Project: orion.server   Source File: GitTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
protected void createRepository() throws IOException, GitAPIException, CoreException {
	IPath randomLocation = createTempDir();
	gitDir = randomLocation.toFile();
	randomLocation = randomLocation.addTrailingSeparator().append(Constants.DOT_GIT);
	File dotGitDir = randomLocation.toFile().getCanonicalFile();
	db = FileRepositoryBuilder.create(dotGitDir);
	toClose.add(db);
	assertFalse(dotGitDir.exists());
	db.create(false /* non bare */);

	testFile = new File(gitDir, "test.txt");
	testFile.createNewFile();
	createFile(testFile.toURI(), "test");
	File folder = new File(gitDir, "folder");
	folder.mkdir();
	File folderFile = new File(folder, "folder.txt");
	folderFile.createNewFile();
	createFile(folderFile.toURI(), "folder");

	Git git = Git.wrap(db);
	git.add().addFilepattern(".").call();
	git.commit().setMessage("Initial commit").call();

	// The system settings on eclipse.org was changed to receive.denyNonFastForward=true, see bug 343150.
	// Imitate the same setup when running tests locally, see bug 371881.
	StoredConfig cfg = db.getConfig();
	cfg.setBoolean("receive", null, "denyNonFastforwards", true);
	cfg.save();
}
 
Example 21
Source Project: hop   Source File: UIGit.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean rollback( String name ) {
  if ( hasUncommittedChanges() ) {
    showMessageBox( BaseMessages.getString( PKG, "Dialog.Error" ),
      BaseMessages.getString( PKG, "Git.Dialog.UncommittedChanges.Message" ) );
    return false;
  }
  String commit = resolve( Constants.HEAD ).getName();
  RevertCommand cmd = git.revert();
  for ( int i = 0; i < getRevisions().size(); i++ ) {
    String commitId = getRevisions().get( i ).getRevisionId();
    /*
     * Revert commits from HEAD to the specified commit in reverse order.
     */
    cmd.include( resolve( commitId ) );
    if ( commitId.equals( name ) ) {
      break;
    }
  }
  try {
    cmd.call();
    git.reset().setRef( commit ).call();
    return true;
  } catch ( Exception e ) {
    showMessageBox( BaseMessages.getString( PKG, "Dialog.Error" ), e.getMessage() );
  }
  return false;
}
 
Example 22
Source Project: hop   Source File: UIGit.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String getShortenedName( String name, String type ) {
  if ( name.length() == Constants.OBJECT_ID_STRING_LENGTH ) {
    return name.substring( 0, 7 );
  } else {
    return Repository.shortenRefName( name );
  }
}
 
Example 23
Source Project: ParallelGit   Source File: GfsCommitAfterMergeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void commitAfterConflictingMerge_resultCommitShouldHaveOneParent() throws IOException {
  writeToCache("/test_file.txt", "THEIR VERSION");
  commitToBranch(THEIRS);
  Gfs.merge(gfs).source(THEIRS).execute();
  MergeNote note = gfs.getStatusProvider().mergeNote();
  write(gfs.getPath("/test_file.txt"), Constants.encodeASCII("COMBINED VERSION"));
  RevCommit commit = Gfs.commit(gfs).execute().getCommit();

  assertNotNull(note);
  assertNotNull(commit);
  assertEquals(note.getSource(), commit.getParent(1));
}
 
Example 24
Source Project: proctor   Source File: GitProctor.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public Map<String, List<Revision>> getAllHistories() throws StoreException {
    final Repository repository = git.getRepository();
    try {
        final ObjectId head = repository.resolve(Constants.HEAD);
        final GitHistoryParser historyParser =
                GitHistoryParser.fromRepository(git.getRepository(), getTestDefinitionsDirectory());
        return historyParser.parseFromHead(head);
    } catch (final IOException e) {
        throw new StoreException("Could not get history " + getGitCore().getRefName(), e);
    }
}
 
Example 25
Source Project: git-as-svn   Source File: ACLTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void emptyDeny() {
  final ACL acl = new ACL(Collections.emptyMap(), Collections.emptyMap());

  Assert.assertFalse(acl.canRead(Bob, Constants.MASTER, "/"));
  Assert.assertFalse(acl.canRead(User.getAnonymous(), Constants.MASTER, "/"));
}
 
Example 26
Source Project: netbeans   Source File: MergeTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testMergeNoChange () throws Exception {
    File f = new File(workDir, "file");
    write(f, "init");
    add(f);
    commit(f);
    
    GitClient client = getClient(workDir);
    GitBranch branch = client.createBranch(BRANCH_NAME, Constants.MASTER, NULL_PROGRESS_MONITOR);
    
    GitMergeResult result = client.merge(BRANCH_NAME, NULL_PROGRESS_MONITOR);
    assertEquals(MergeStatus.ALREADY_UP_TO_DATE, result.getMergeStatus());
    result = client.merge(branch.getId(), NULL_PROGRESS_MONITOR);
    assertEquals(MergeStatus.ALREADY_UP_TO_DATE, result.getMergeStatus());
}
 
Example 27
Source Project: centraldogma   Source File: GitRepository.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void apply(DirCacheEntry ent) {
    try {
        ent.setObjectId(inserter.insert(Constants.OBJ_BLOB, text.getBytes(UTF_8)));
        ent.setFileMode(FileMode.REGULAR_FILE);
    } catch (IOException e) {
        throw new StorageException("failed to create a new text blob", e);
    }
}
 
Example 28
Source Project: gitlab-branch-source-plugin   Source File: GitLabPushSCMEvent.java    License: MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String descriptionFor(SCMSource source) {
    String ref = getPayload().getRef();
    ref = ref.startsWith(Constants.R_HEADS) ? ref.substring(Constants.R_HEADS.length()) : ref;
    return "Push event to branch " + ref;
}
 
Example 29
@Before
public void createDirectoriesAndFiles() throws Exception {
    root = new File("target", "standalone").toPath();
    Files.createDirectories(root);
    File baseDir = root.toAbsolutePath().toFile();
    File gitDir = new File(baseDir, Constants.DOT_GIT);
    if (!gitDir.exists()) {
        try (Git git = Git.init().setDirectory(baseDir).setGitDir(gitDir).call()) {
            git.commit().setMessage("Repository initialized").call();
        }
    }
    repository = new FileRepositoryBuilder().setWorkTree(baseDir).setGitDir(gitDir).setup().build();
}
 
Example 30
Source Project: heroku-maven-plugin   Source File: GitUtils.java    License: MIT License 5 votes vote down vote up
public static Optional<String> getHeadCommitHash(Path projectDirectory) throws IOException {
    try {
        Git git = Git.open(projectDirectory.toFile());
        ObjectId objectId = git.getRepository().resolve(Constants.HEAD);
        return Optional.of(objectId.getName());

    } catch (RepositoryNotFoundException e) {
        return Optional.empty();
    }
}