下面列出了java.nio.channels.IllegalSelectorException#org.eclipse.jgit.lib.PersonIdent 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
}
@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();
}
}
@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 ) );
}
@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());
}
}
@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);
}
}
@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();");
}
});
}
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;
}
/**
* 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);
}
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);
}
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);
}
@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");
}
}
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);
}
@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("{")));
}
@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());
}
@Override
public boolean commit( String authorName, String message ) {
PersonIdent author = RawParseUtils.parsePersonIdent( authorName );
// Set the local time
PersonIdent author2 = new PersonIdent( author.getName(), author.getEmailAddress(),
SystemReader.getInstance().getCurrentTime(),
SystemReader.getInstance().getTimezone( SystemReader.getInstance().getCurrentTime() ) );
try {
git.commit().setAuthor( author2 ).setMessage( message ).call();
return true;
} catch ( Exception e ) {
showMessageBox( BaseMessages.getString( PKG, "Dialog.Error" ), e.getMessage() );
return false;
}
}
@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());
}
@Test
public void testCommit_3args() throws Exception {
final ObjectId commitA = commitOneFile();
final String authorName = randomName();
final String authorEmail = randomEmail(authorName);
gitClient.setAuthor(new PersonIdent(authorName, authorEmail));
final String committerName = randomName();
final String committerEmail = randomEmail(committerName);
gitClient.setCommitter(new PersonIdent(committerName, committerEmail));
final String expectedCommitMessage = "This is commit B's expected message";
final ObjectId commitB = commitOneFile(expectedCommitMessage);
assertLogContains(commitA, commitB, " ", expectedCommitMessage);
assertAuthor(commitA, commitB, authorName, authorEmail);
assertCommitter(commitA, commitB, committerName, committerEmail);
}
private String toString(PersonIdent author) {
final StringBuilder a = new StringBuilder();
a.append("Author: "); //$NON-NLS-1$
a.append(author.getName());
a.append(" <"); //$NON-NLS-1$
a.append(author.getEmailAddress());
a.append(">\n"); //$NON-NLS-1$
a.append("Date: "); //$NON-NLS-1$
a.append(dateFormatter.formatDate(author));
a.append("\n"); //$NON-NLS-1$
return a.toString();
}
@Nullable
public static ObjectId rebase(Repository repository, ObjectId source, ObjectId target, PersonIdent committer) {
try ( RevWalk revWalk = new RevWalk(repository);
ObjectInserter inserter = repository.newObjectInserter();) {
RevCommit sourceCommit = revWalk.parseCommit(source);
RevCommit targetCommit = revWalk.parseCommit(target);
revWalk.setRevFilter(RevFilter.NO_MERGES);
List<RevCommit> commits = RevWalkUtils.find(revWalk, sourceCommit, targetCommit);
Collections.reverse(commits);
RevCommit headCommit = targetCommit;
for (RevCommit commit: commits) {
ResolveMerger merger = (ResolveMerger) MergeStrategy.RECURSIVE.newMerger(repository, true);
merger.setBase(commit.getParent(0));
if (merger.merge(headCommit, commit)) {
if (!headCommit.getTree().getId().equals(merger.getResultTreeId())) {
if (!commit.getTree().getId().equals(merger.getResultTreeId())
|| !commit.getParent(0).equals(headCommit)) {
CommitBuilder commitBuilder = new CommitBuilder();
commitBuilder.setAuthor(commit.getAuthorIdent());
commitBuilder.setCommitter(committer);
commitBuilder.setParentId(headCommit);
commitBuilder.setMessage(commit.getFullMessage());
commitBuilder.setTreeId(merger.getResultTreeId());
headCommit = revWalk.parseCommit(inserter.insert(commitBuilder));
} else {
headCommit = commit;
}
}
} else {
return null;
}
}
inserter.flush();
return headCommit.copy();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Nullable
public static ObjectId merge(Repository repository, ObjectId targetCommitId, ObjectId sourceCommitId,
boolean squash, PersonIdent committer, PersonIdent author, String commitMessage,
boolean useOursOnConflict) {
boolean prevUseOursOnConflict = UseOursOnConflict.get();
UseOursOnConflict.set(useOursOnConflict);
try ( RevWalk revWalk = new RevWalk(repository);
ObjectInserter inserter = repository.newObjectInserter();) {
RevCommit sourceCommit = revWalk.parseCommit(sourceCommitId);
RevCommit targetCommit = revWalk.parseCommit(targetCommitId);
Merger merger = MergeStrategy.RECURSIVE.newMerger(repository, true);
if (merger.merge(targetCommit, sourceCommit)) {
CommitBuilder mergedCommit = new CommitBuilder();
mergedCommit.setAuthor(author);
mergedCommit.setCommitter(committer);
if (squash)
mergedCommit.setParentId(targetCommit);
else
mergedCommit.setParentIds(targetCommit, sourceCommit);
mergedCommit.setMessage(commitMessage);
mergedCommit.setTreeId(merger.getResultTreeId());
ObjectId mergedCommitId = inserter.insert(mergedCommit);
inserter.flush();
return mergedCommitId;
} else {
return null;
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
UseOursOnConflict.set(prevUseOursOnConflict);
}
}
/**
* Return the author identity as a jgit PersonIdent
*
* @param author author
* @return author user as a PersonIdent
*/
public PersonIdent getAuthorIdent(String author) throws ServiceLayerException, UserNotFoundException {
User user = userServiceInternal.getUserByIdOrUsername(-1, author);
PersonIdent currentUserIdent =
new PersonIdent(user.getFirstName() + " " + user.getLastName(), user.getEmail());
return currentUserIdent;
}
@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());
}
@Test
public void testCommit_String() throws Exception {
final ObjectId commitA = commitOneFile();
final String name = randomName();
final String email = randomEmail(name);
gitClient.setAuthor(new PersonIdent(name, email));
final String expectedCommitMessage = "This is commit B's expected message";
final ObjectId commitB = commitOneFile(expectedCommitMessage);
assertLogContains(commitA, commitB, " ", expectedCommitMessage);
}
public GitCommit(String hash, @Nullable List<String> parentHashes, @Nullable PersonIdent committer,
@Nullable PersonIdent author, @Nullable Date commitDate, @Nullable String subject,
@Nullable String body, @Nullable List<FileChange> fileChanges) {
this.hash = hash;
this.parentHashes = parentHashes;
this.committer = committer;
this.author = author;
this.commitDate = commitDate;
this.subject = subject;
this.body = body;
this.fileChanges = fileChanges;
}
@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());
}
@Sessional
@Override
public User find(PersonIdent person) {
if (StringUtils.isNotBlank(person.getEmailAddress()))
return findByEmail(person.getEmailAddress());
else
return null;
}
/**
* @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();
}
}
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()));
}
}
@Override
public String getRevDate() {
PersonIdent authorIdent = revCommit.getAuthorIdent();
Date authorDate = authorIdent.getWhen();
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
return ft.format(authorDate);
}
@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);
}
}