org.eclipse.jgit.lib.PersonIdent Java Examples

The following examples show how to use org.eclipse.jgit.lib.PersonIdent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProjectContribsPage.java    From onedev with MIT License 6 votes vote down vote up
@Override
protected void onInitialize() {
	super.onInitialize();
	if (getProject().getDefaultBranch() != null)
		add(new Label("note", "Contributions to " + getProject().getDefaultBranch() + " branch, excluding merge commits"));
	else
		add(new WebMarkupContainer("note").setVisible(false));
	add(new WebMarkupContainer(USER_CARD_ID).setOutputMarkupId(true));
	add(userCardBehavior = new AbstractPostAjaxBehavior() {
		
		@Override
		protected void respond(AjaxRequestTarget target) {
			String name = RequestCycle.get().getRequest().getPostParameters()
					.getParameterValue("name").toString();
			String emailAddress = RequestCycle.get().getRequest().getPostParameters()
					.getParameterValue("emailAddress").toString();
			PersonIdent author = new PersonIdent(name, emailAddress);
			Component userCard = new PersonCardPanel(USER_CARD_ID, author, "Author");
			userCard.setOutputMarkupId(true);
			replace(userCard);
			target.add(userCard);
			target.appendJavaScript("onedev.server.stats.contribs.onUserCardAvailable();");
		}
		
	});
}
 
Example #2
Source File: GitCommit.java    From onedev with MIT License 6 votes vote down vote up
public GitCommit build() {
	PersonIdent committer;
	if (StringUtils.isNotBlank(committerName) || StringUtils.isNotBlank(committerEmail))
		committer = GitUtils.newPersonIdent(committerName, committerEmail, committerDate);
	else 
		committer = null;

	PersonIdent author;
	if (StringUtils.isNotBlank(authorName) || StringUtils.isNotBlank(authorEmail)) 
		author = GitUtils.newPersonIdent(authorName, authorEmail, authorDate);
	else
		author = null;

	if (subject != null)
		subject = subject.trim();
	
	if (body != null) 
		body = body.trim();
	
	return new GitCommit(hash, parentHashes, committer, author, commitDate, 
			subject, body, fileChanges);
}
 
Example #3
Source File: RemotingTest.java    From git-client-plugin with MIT License 6 votes vote down vote up
@Override
public Void call() throws IOException {
    try {
        git.init();
        git.getWorkTree().child("foo").touch(0);
        git.add("foo");
        PersonIdent alice = new PersonIdent("alice", "[email protected]");
        git.setAuthor(alice);
        git.setCommitter(alice);
        git.commit("committing changes");

        FilePath ws = git.withRepository(new RepositoryCallableImpl());
        assertEquals(ws, git.getWorkTree());

        return null;
    } catch (InterruptedException e) {
        throw new Error(e);
    }
}
 
Example #4
Source File: SubtreeMerger.java    From git-merge-repos with Apache License 2.0 6 votes vote down vote up
public ObjectId createMergeCommit(Map<SubtreeConfig, RevCommit> parentCommits, String message)
		throws IOException {
	PersonIdent latestIdent = getLatestPersonIdent(parentCommits.values());
	DirCache treeDirCache = createTreeDirCache(parentCommits, message);
	List<? extends ObjectId> parentIds = new ArrayList<>(parentCommits.values());
	try (ObjectInserter inserter = repository.newObjectInserter()) {
		ObjectId treeId = treeDirCache.writeTree(inserter);

		PersonIdent repositoryUser = new PersonIdent(repository);
		PersonIdent ident = new PersonIdent(repositoryUser, latestIdent.getWhen().getTime(),
				latestIdent.getTimeZoneOffset());
		CommitBuilder commitBuilder = new CommitBuilder();
		commitBuilder.setTreeId(treeId);
		commitBuilder.setAuthor(ident);
		commitBuilder.setCommitter(ident);
		commitBuilder.setMessage(message);
		commitBuilder.setParentIds(parentIds);
		ObjectId mergeCommit = inserter.insert(commitBuilder);
		inserter.flush();
		return mergeCommit;
	}
}
 
Example #5
Source File: UIGit.java    From hop with Apache License 2.0 6 votes vote down vote up
@Override
public String getAuthorName( String commitId ) {
  if ( commitId.equals( IVCS.WORKINGTREE ) ) {
    Config config = git.getRepository().getConfig();
    return config.get( UserConfig.KEY ).getAuthorName()
        + " <" + config.get( UserConfig.KEY ).getAuthorEmail() + ">";
  } else {
    RevCommit commit = resolve( commitId );
    PersonIdent author = commit.getAuthorIdent();
    final StringBuilder r = new StringBuilder();
    r.append( author.getName() );
    r.append( " <" ); //$NON-NLS-1$
    r.append( author.getEmailAddress() );
    r.append( ">" ); //$NON-NLS-1$
    return r.toString();
  }
}
 
Example #6
Source File: GitSCM.java    From repositoryminer with Apache License 2.0 6 votes vote down vote up
private Commit processCommit(RevCommit revCommit) {
	PersonIdent author = revCommit.getAuthorIdent();
	PersonIdent committer = revCommit.getCommitterIdent();

	Developer myAuthor = new Developer(author.getName(), author.getEmailAddress());
	Developer myCommitter = new Developer(committer.getName(), committer.getEmailAddress());

	List<String> parents = new ArrayList<String>();
	for (RevCommit parent : revCommit.getParents()) {
		parents.add(parent.getName());
	}

	List<Change> changes = null;
	try {
		changes = getChangesForCommitedFiles(revCommit.getName());
	} catch (IOException e) {
		close();
		throw new RepositoryMinerException(e);
	}

	return new Commit(null, revCommit.getName(), myAuthor, myCommitter, revCommit.getFullMessage().trim(), changes,
			parents, author.getWhen(), committer.getWhen(), (parents.size() > 1), null);
}
 
Example #7
Source File: UIGitTest.java    From hop with Apache License 2.0 6 votes vote down vote up
@Test
public void testCommit() throws Exception {
  assertFalse( uiGit.hasStagedFiles() );

  writeTrashFile( "Test.txt", "Hello world" );
  uiGit.add( "Test.txt" );
  PersonIdent author = new PersonIdent( "author", "[email protected]" );
  String message = "Initial commit";

  assertTrue( uiGit.hasStagedFiles() );

  uiGit.commit( author.toExternalString(), message );
  String commitId = uiGit.getCommitId( Constants.HEAD );

  assertTrue( uiGit.isClean() );
  assertTrue( author.toExternalString().contains( uiGit.getAuthorName( commitId ) ) );
  assertEquals( message, uiGit.getCommitMessage( commitId ) );
}
 
Example #8
Source File: CreateTagAction.java    From onedev with MIT License 6 votes vote down vote up
@Override
public void execute(Build build) {
	PersonIdent tagIdent = OneDev.getInstance(UserManager.class).getSystem().asPerson();
	Project project = build.getProject();
	String tagName = getTagName();

	CreateTagAction instance = new CreateTagAction();
	instance.setTagName(tagName);
	if (project.getBuildSetting().isActionAuthorized(build, instance)) {
		Ref tagRef = project.getTagRef(tagName);
		if (tagRef != null) {
			OneDev.getInstance(ProjectManager.class).deleteTag(project, tagName);
			project.createTag(tagName, build.getCommitHash(), tagIdent, getTagMessage());
		} else {
			project.createTag(tagName, build.getCommitHash(), tagIdent, getTagMessage());
		}
	} else {
		throw new OneException("Creating tag '" + tagName + "' is not allowed in this build");
	}
}
 
Example #9
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
public CommitInfo createCommitInfo(RevCommit entry) {
    final Date date = GitUtils.getCommitDate(entry);
    PersonIdent authorIdent = entry.getAuthorIdent();
    String author = null;
    String name = null;
    String email = null;
    String avatarUrl = null;
    if (authorIdent != null) {
        author = authorIdent.getName();
        name = authorIdent.getName();
        email = authorIdent.getEmailAddress();

        // lets try default the avatar
        if (Strings.isNotBlank(email)) {
            avatarUrl = getAvatarUrl(email);
        }
    }
    boolean merge = entry.getParentCount() > 1;
    String shortMessage = entry.getShortMessage();
    String sha = entry.getName();
    return new CommitInfo(sha, author, name, email, avatarUrl, date, merge, shortMessage);
}
 
Example #10
Source File: DefaultAvatarManager.java    From onedev with MIT License 6 votes vote down vote up
@Sessional
@Override
public String getAvatarUrl(PersonIdent personIdent) {
	if (StringUtils.isBlank(personIdent.getEmailAddress())) {
		if (personIdent.getName().equals(OneDev.NAME)) 
			return AVATARS_BASE_URL + "onedev.png";
		else  
			return AVATARS_BASE_URL + "user.png";
	} else {
		User user = userManager.findByEmail(personIdent.getEmailAddress());
		if (user != null) {
			File uploadedFile = getUploaded(user);
			if (uploadedFile.exists())
				return AVATARS_BASE_URL + "uploaded/users/" + user.getId() + ".jpg?version=" + uploadedFile.lastModified();
		}
		if (settingManager.getSystemSetting().isGravatarEnabled())
			return Gravatar.getURL(personIdent.getEmailAddress(), GRAVATAR_SIZE);
		else 
			return generateAvatar(personIdent.getName(), personIdent.getEmailAddress());
	}
}
 
Example #11
Source File: GitUtils.java    From onedev with MIT License 6 votes vote down vote up
/**
 * Parse the raw user information into PersonIdent object, the raw information
 * should be in format <code>[name] [<email>] [epoch timezone]</code>, for 
 * example:
 * 
 * Jacob Thornton <[email protected]> 1328060294 -0800
 * 
 * @param raw
 * @return
 */
public static @Nullable PersonIdent parsePersonIdent(String raw) {
	if (Strings.isNullOrEmpty(raw))
		return null;
	
	int pos1 = raw.indexOf('<');
	if (pos1 <= 0)
		throw new IllegalArgumentException("Raw " + raw);
	
	String name = raw.substring(0, pos1 - 1);
	
	int pos2 = raw.indexOf('>');
	if (pos2 <= 0)
		throw new IllegalArgumentException("Raw " + raw);
	
	String time = raw.substring(pos2 + 1).trim();
	Date when = parseRawDate(time);
	
	String email = raw.substring(pos1 + 1, pos2 - 1);
	
	return newPersonIdent(name, email, when);
}
 
Example #12
Source File: SystemTest.java    From app-runner with MIT License 6 votes vote down vote up
@Test
public void pushingAnEmptyRepoIsRejected() throws Exception {
    File dir = Photocopier.folderForSampleProject("empty-project");
    InitCommand initCommand = Git.init();
    initCommand.setDirectory(dir);
    Git origin = initCommand.call();

    ContentResponse resp = restClient.createApp(dir.toURI().toString(), "empty-project");
    assertThat(resp, equalTo(501, containsString("No suitable runner found for this app")));

    Photocopier.copySampleAppToDir("maven", dir);
    origin.add().addFilepattern(".").call();
    origin.commit().setMessage("Initial commit")
        .setAuthor(new PersonIdent("Author Test", "[email protected]"))
        .call();

    resp = restClient.createApp(dir.toURI().toString(), "empty-project");
    assertThat(resp, equalTo(201, containsString("empty-project")));
    assertThat(new JSONObject(resp.getContentAsString()).get("name"), Matchers.equalTo("empty-project"));
    assertThat(restClient.deleteApp("empty-project"), equalTo(200, containsString("{")));
}
 
Example #13
Source File: GitUtils.java    From jphp with Apache License 2.0 6 votes vote down vote up
public static ArrayMemory valueOf(RevCommit value) {
    ArrayMemory memory = valueOf((RevObject) value);

    memory.refOfIndex("commitTime").assign(value.getCommitTime());
    memory.refOfIndex("encoding").assign(value.getEncodingName());
    memory.refOfIndex("shortMessage").assign(value.getShortMessage());
    memory.refOfIndex("fullMessage").assign(value.getFullMessage());
    
    ArrayMemory parents = new ArrayMemory();
    for (RevCommit revCommit : value.getParents()) {
        parents.add(valueOf((RevObject)revCommit));
    }

    memory.refOfIndex("parents").assign(parents);

    PersonIdent authorIdent = value.getAuthorIdent();
    memory.refOfIndex("author").assign(authorIdent == null ? Memory.NULL : valueOf(authorIdent));

    PersonIdent committerIdent = value.getCommitterIdent();
    memory.refOfIndex("committer").assign(committerIdent == null ? Memory.NULL : valueOf(committerIdent));

    return memory;
}
 
Example #14
Source File: GitRepositoryHelper.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Return the author identity as a jgit PersonIdent
 *
 * @param user author
 * @return author user as a PersonIdent
 */
public PersonIdent getAuthorIdent(User user) throws ServiceLayerException, UserNotFoundException {
    PersonIdent currentUserIdent =
            new PersonIdent(user.getFirstName() + " " + user.getLastName(), user.getEmail());

    return currentUserIdent;
}
 
Example #15
Source File: GfsCommitTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void commitWithAuthor_theResultCommitShouldHaveTheSpecifiedAuthor() throws IOException {
  writeSomethingToGfs();
  PersonIdent author = new PersonIdent("test_author_name", "[email protected]");
  Result result = Gfs.commit(gfs).author(author).execute();
  assertEquals(author, result.getCommit().getAuthorIdent());
}
 
Example #16
Source File: RepositoryUtilsConfigTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void setDefaultCommitter_newPersonIdentInstanceShouldHaveTheSpecifiedUserNameAndEmail() throws IOException {
  String name = "test_user";
  String email = "[email protected]";
  RepositoryUtils.setDefaultCommitter(name, email, repo);
  PersonIdent actual = new PersonIdent(repo);
  assertEquals(name, actual.getName());
  assertEquals(email, actual.getEmailAddress());
}
 
Example #17
Source File: GitClientTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void testSetAuthor_PersonIdent() throws Exception {
    final ObjectId commitA = commitOneFile();
    final String name = randomName();
    final String email = randomEmail(name);
    gitClient.setAuthor(new PersonIdent(name, email));
    final ObjectId commitB = commitOneFile();
    assertAuthor(commitA, commitB, name, email);
}
 
Example #18
Source File: GfsCommitTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void commitWithAuthorAndCommitter_theResultCommitShouldHaveTheSpecifiedAuthorAndCommitter() throws IOException {
  writeSomethingToGfs();
  PersonIdent author = new PersonIdent("test_author_name", "[email protected]");
  PersonIdent committer = new PersonIdent("test_committer_name", "[email protected]");
  Result result = Gfs.commit(gfs).committer(committer).author(author).execute();
  RevCommit resultCommit = result.getCommit();
  assertEquals(author, resultCommit.getAuthorIdent());
  assertEquals(committer, resultCommit.getCommitterIdent());
}
 
Example #19
Source File: GfsCommitTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void commitWithAuthorAndCommitter_theResultCommitShouldHaveTheSpecifiedAuthorAndCommitter() throws IOException {
  writeSomethingToGfs();
  PersonIdent author = new PersonIdent("test_author_name", "[email protected]");
  PersonIdent committer = new PersonIdent("test_committer_name", "[email protected]");
  Result result = Gfs.commit(gfs).committer(committer).author(author).execute();
  RevCommit resultCommit = result.getCommit();
  assertEquals(author, resultCommit.getAuthorIdent());
  assertEquals(committer, resultCommit.getCommitterIdent());
}
 
Example #20
Source File: GfsCommitTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void commitWithCommitterOnly_theResultCommitAuthorShouldDefaultToBeTheSameAsTheSpecifiedCommitter() throws IOException {
  writeSomethingToGfs();
  PersonIdent committer = new PersonIdent("test_committer_name", "[email protected]");
  Result result = Gfs.commit(gfs).committer(committer).execute();
  assertEquals(committer, result.getCommit().getAuthorIdent());
}
 
Example #21
Source File: GfsCommitTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void commitWithCommitter_theResultCommitShouldHaveTheSpecifiedCommitter() throws IOException {
  writeSomethingToGfs();
  PersonIdent committer = new PersonIdent("test_committer_name", "[email protected]");
  Result result = Gfs.commit(gfs).committer(committer).execute();
  assertEquals(committer, result.getCommit().getCommitterIdent());
}
 
Example #22
Source File: GitUtils.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private static PersonIdent buildPersonIdent(final Repository repo, final String name, final String email,
        final TimeZone timeZone, final Date when) {
    final TimeZone tz = timeZone == null ? TimeZone.getDefault() : timeZone;

    if (name != null) {
        if (when != null) {
            return new PersonIdent(name, email, when, tz);
        } else {
            return new PersonIdent(name, email);
        }
    }
    return new PersonIdent(repo);
}
 
Example #23
Source File: GitAPI.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
public void commit(String message, PersonIdent author, PersonIdent committer) throws GitException, InterruptedException {
    if (Git.USE_CLI) {
        super.setAuthor(author);
        super.setCommitter(committer);
        super.commit(message);
    } else {
        jgit.setAuthor(author);
        jgit.setCommitter(committer);
        jgit.commit(message);
    }
}
 
Example #24
Source File: GitStashHandlerV1.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected boolean handlePost(RequestInfo requestInfo) throws ServletException {

	JSONObject requestPayload = requestInfo.getJSONRequest();
	HttpServletRequest request = requestInfo.request;
	HttpServletResponse response = requestInfo.response;
	Repository db = requestInfo.db;

	String indexMessage = requestPayload.optString(GitConstants.KEY_STASH_INDEX_MESSAGE);
	String workingDirectoryMessage = requestPayload.optString(GitConstants.KEY_STASH_WORKING_DIRECTORY_MESSAGE);
	boolean includeUntracked = requestPayload.optBoolean(GitConstants.KEY_STASH_INCLUDE_UNTRACKED, false);

	try {

		Git git = Git.wrap(db);
		StashCreateCommand stashCreate = git.stashCreate();
		stashCreate.setPerson(new PersonIdent(db));
		stashCreate.setIncludeUntracked(includeUntracked);

		if (!indexMessage.isEmpty())
			stashCreate.setIndexMessage(indexMessage);

		if (!workingDirectoryMessage.isEmpty())
			stashCreate.setWorkingDirectoryMessage(workingDirectoryMessage);

		stashCreate.call();
		return true;

	} catch (Exception ex) {
		String msg = "An error occured for stash command.";
		return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex));
	}
}
 
Example #25
Source File: RepositoryManagementServiceInternalImpl.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean commitResolution(String siteId, String commitMessage) throws CryptoException, ServiceLayerException {
    GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration);
    Repository repo = helper.getRepository(siteId, SANDBOX);
    logger.debug("Commit resolution for merge conflict for site " + siteId);
    try (Git git = new Git(repo)) {
        Status status = git.status().call();

        logger.debug("Add all uncommitted changes/files");
        AddCommand addCommand = git.add();
        for (String uncommited : status.getUncommittedChanges()) {
            addCommand.addFilepattern(uncommited);
        }
        addCommand.call();
        logger.debug("Commit changes");
        CommitCommand commitCommand = git.commit();
        String userName = securityService.getCurrentUser();
        User user = userServiceInternal.getUserByIdOrUsername(-1, userName);
        PersonIdent personIdent = helper.getAuthorIdent(user);
        String prologue = studioConfiguration.getProperty(REPO_COMMIT_MESSAGE_PROLOGUE);
        String postscript = studioConfiguration.getProperty(REPO_COMMIT_MESSAGE_POSTSCRIPT);

        StringBuilder sbMessage = new StringBuilder();
        if (StringUtils.isNotEmpty(prologue)) {
            sbMessage.append(prologue).append("\n\n");
        }
        sbMessage.append(commitMessage);
        if (StringUtils.isNotEmpty(postscript)) {
            sbMessage.append("\n\n").append(postscript);
        }
        commitCommand.setCommitter(personIdent).setAuthor(personIdent).setMessage(sbMessage.toString()).call();
        return true;
    } catch (GitAPIException | UserNotFoundException | ServiceLayerException e) {
        logger.error("Error while committing conflict resolution for site " + siteId, e);
        throw new ServiceLayerException("Error while committing conflict resolution for site " + siteId, e);
    }
}
 
Example #26
Source File: CommitGit.java    From coming with MIT License 5 votes vote down vote up
@Override
public String getRevDate() {
	PersonIdent authorIdent = revCommit.getAuthorIdent();
	Date authorDate = authorIdent.getWhen();
	SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
	return ft.format(authorDate);
}
 
Example #27
Source File: CommitCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void transferTimestamp (org.eclipse.jgit.api.CommitCommand commit, RevCommit lastCommit) {
    PersonIdent lastAuthor = lastCommit.getAuthorIdent();
    if (lastAuthor != null) {
        PersonIdent author = commit.getAuthor();
        commit.setAuthor(lastAuthor.getTimeZone() == null
                ? new PersonIdent(author, lastAuthor.getWhen())
                : new PersonIdent(author, lastAuthor.getWhen(), lastAuthor.getTimeZone()));
    }
}
 
Example #28
Source File: GitRevisionInfo.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * @return time this commit was created in milliseconds.
 */
public long getCommitTime () {
    // must be indeed author, that complies with CLI
    // committer time is different after rebase
    PersonIdent author = revCommit.getAuthorIdent();
    if (author == null) {
        return (long) revCommit.getCommitTime() * 1000;
    } else {
        return author.getWhen().getTime();
    }
}
 
Example #29
Source File: GfsCreateStashTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void stashWithCommitter_bothWorkingDirectoryCommitAndIndexCommitShouldBeCommittedByTheSpecifiedCommitter() throws IOException {
  writeSomethingToGfs();
  PersonIdent committer = somePersonIdent();
  RevCommit workDirCommit = createStash(gfs).committer(committer).execute().getCommit();
  assertEquals(committer, workDirCommit.getCommitterIdent());
  RevCommit indexCommit = CommitUtils.getCommit(workDirCommit.getParent(1), repo);
  assertEquals(committer, workDirCommit.getCommitterIdent());
  assertEquals(committer, indexCommit.getCommitterIdent());
}
 
Example #30
Source File: CommitUtilsCreateCommitTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void createCommit_theResultCommitShouldHaveTheInputCommitter() throws IOException {
  writeSomethingToCache();
  PersonIdent expectedCommitter = new PersonIdent("test_user", "[email protected]");
  RevCommit commit = CommitUtils.createCommit(someCommitMessage(), cache, expectedCommitter, null, repo);
  assertEquals(expectedCommitter, commit.getCommitterIdent());
}