private static Commit toCommit(RevCommit revCommit) { final Author author; final PersonIdent committerIdent = revCommit.getCommitterIdent(); if (committerIdent == null) { author = Author.UNKNOWN; } else { author = new Author(committerIdent.getName(), committerIdent.getEmailAddress()); } long when = committerIdent.getWhen().getTime(); try { return CommitUtil.newCommit(author, when, revCommit.getFullMessage()); } catch (Exception e) { throw new StorageException("failed to create a Commit", e); } }
public LogCommit build() { PersonIdent committer; if (StringUtils.isNotBlank(committerName) && StringUtils.isNotBlank(committerEmail) && committerDate != null) { committer = GitUtils.newPersonIdent(committerName, committerEmail, committerDate); } else { committer = null; } PersonIdent author; if (StringUtils.isNotBlank(authorName) && StringUtils.isNotBlank(authorEmail) && authorDate != null) { author = GitUtils.newPersonIdent(authorName, authorEmail, authorDate); } else { author = null; } return new LogCommit(hash, committer, author, parentHashes, changedFiles); }
@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(); } }
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); }
/** * Gets a set of authors for a path in a given repository * @param repo The git repository * @param path The path to get commits for * @return An iterable of commits * @throws GitAPIException Any API errors which may occur * @throws URISyntaxException Error constructing mailto link */ public Set<HashableAgent> getAuthors(Git repo, String path) throws GitAPIException, URISyntaxException { Iterable<RevCommit> logs = repo.log().addPath(path).call(); Set<HashableAgent> fileAuthors = new HashSet<>(); for (RevCommit rev : logs) { // Use author first with backup of committer PersonIdent author = rev.getAuthorIdent(); if (author == null) { author = rev.getCommitterIdent(); } // Create a new agent and add as much detail as possible if (author != null) { HashableAgent newAgent = new HashableAgent(); String name = author.getName(); if (name != null && name.length() > 0) { newAgent.setName(author.getName()); } String email = author.getEmailAddress(); if (email != null && email.length() > 0) { newAgent.setUri(new URI("mailto:" + author.getEmailAddress())); } fileAuthors.add(newAgent); } } return fileAuthors; }
/** * Does not fetch. */ public CommitInfo getCommitInfo(String path) throws Exception { Iterator<RevCommit> revCommits = git.log().addPath(path).setMaxCount(1).call().iterator(); if (revCommits.hasNext()) { RevCommit revCommit = revCommits.next(); CommitInfo commitInfo = new CommitInfo(revCommit.getId().name()); PersonIdent committerIdent = revCommit.getCommitterIdent(); commitInfo.setCommitter(committerIdent.getName()); commitInfo.setEmail(committerIdent.getEmailAddress()); if ((commitInfo.getCommitter() == null || commitInfo.getCommitter().isEmpty()) && commitInfo.getEmail() != null) commitInfo.setCommitter(commitInfo.getEmail()); commitInfo.setDate(committerIdent.getWhen()); commitInfo.setMessage(revCommit.getShortMessage()); return commitInfo; } return null; }
protected AbstractChangeUpdate( Config cfg, NotesMigration migration, ChangeNotes notes, CurrentUser user, PersonIdent serverIdent, String anonymousCowardName, ChangeNoteUtil noteUtil, Date when) { this.migration = migration; this.noteUtil = noteUtil; this.serverIdent = new PersonIdent(serverIdent, when); this.anonymousCowardName = anonymousCowardName; this.notes = notes; this.change = notes.getChange(); this.accountId = accountId(user); Account.Id realAccountId = accountId(user.getRealUser()); this.realAccountId = realAccountId != null ? realAccountId : accountId; this.authorIdent = ident(noteUtil, serverIdent, anonymousCowardName, user, when); this.when = when; this.readOnlySkewMs = NoteDbChangeState.getReadOnlySkew(cfg); }
private void addNoteDbCommit(Change.Id id, String commitMessage) throws Exception { if (!notesMigration.commitChangeWrites()) { return; } PersonIdent committer = serverIdent.get(); PersonIdent author = noteUtil.newIdent( accountCache.get(admin.getId()).getAccount(), committer.getWhen(), committer, anonymousCowardName); testRepo .branch(RefNames.changeMetaRef(id)) .commit() .author(author) .committer(committer) .message(commitMessage) .create(); }
@Inject AllProjectsCreator( GitRepositoryManager mgr, AllProjectsName allProjectsName, SystemGroupBackend systemGroupBackend, @GerritPersonIdent PersonIdent serverUser, NotesMigration notesMigration) { this.mgr = mgr; this.allProjectsName = allProjectsName; this.serverUser = serverUser; this.notesMigration = notesMigration; this.anonymous = systemGroupBackend.getGroup(ANONYMOUS_USERS); this.registered = systemGroupBackend.getGroup(REGISTERED_USERS); this.owners = systemGroupBackend.getGroup(PROJECT_OWNERS); }
@AssistedInject private RobotCommentUpdate( @GerritServerConfig Config cfg, @GerritPersonIdent PersonIdent serverIdent, @AnonymousCowardName String anonymousCowardName, NotesMigration migration, ChangeNoteUtil noteUtil, @Assisted Change change, @Assisted("effective") Account.Id accountId, @Assisted("real") Account.Id realAccountId, @Assisted PersonIdent authorIdent, @Assisted Date when) { super( cfg, migration, noteUtil, serverIdent, anonymousCowardName, null, change, accountId, realAccountId, authorIdent, when); }
private void createGroupBranch(Project.NameKey project, String ref) throws IOException { try (Repository r = repoManager.openRepository(project); ObjectInserter oi = r.newObjectInserter(); RevWalk rw = new RevWalk(r)) { ObjectId emptyTree = oi.insert(Constants.OBJ_TREE, new byte[] {}); PersonIdent ident = new PersonIdent(serverIdent.get(), TimeUtil.nowTs()); CommitBuilder cb = new CommitBuilder(); cb.setTreeId(emptyTree); cb.setCommitter(ident); cb.setAuthor(ident); cb.setMessage("Create group"); ObjectId emptyCommit = oi.insert(cb); oi.flush(); RefUpdate updateRef = r.updateRef(ref); updateRef.setExpectedOldObjectId(ObjectId.zeroId()); updateRef.setNewObjectId(emptyCommit); assertThat(updateRef.update(rw)).isEqualTo(RefUpdate.Result.NEW); } }
public static RevCommit doCommitAndPush(Git git, String message, UserDetails userDetails, PersonIdent author, String branch, String origin, boolean pushOnCommit) throws GitAPIException { CommitCommand commit = git.commit().setAll(true).setMessage(message); if (author != null) { commit = commit.setAuthor(author); } RevCommit answer = commit.call(); if (LOG.isDebugEnabled()) { LOG.debug("Committed " + answer.getId() + " " + answer.getFullMessage()); } if (pushOnCommit) { PushCommand push = git.push(); configureCommand(push, userDetails); Iterable<PushResult> results = push.setRemote(origin).call(); for (PushResult result : results) { if (LOG.isDebugEnabled()) { LOG.debug("Pushed " + result.getMessages() + " " + result.getURI() + " branch: " + branch + " updates: " + toString(result.getRemoteUpdates())); } } } return answer; }
private static Set<String> getNameAndEmail(PersonIdent person) { if (person == null) { return ImmutableSet.of(); } String name = person.getName().toLowerCase(Locale.US); String email = person.getEmailAddress().toLowerCase(Locale.US); StringBuilder nameEmailBuilder = new StringBuilder(); PersonIdent.appendSanitized(nameEmailBuilder, name); nameEmailBuilder.append(" <"); PersonIdent.appendSanitized(nameEmailBuilder, email); nameEmailBuilder.append('>'); return ImmutableSet.of(name, email, nameEmailBuilder.toString()); }
@Override public FileVersion[] getRevisionData(String label, File... files) { // Workaround for CachingPage if (label == null) { return persistence.getRevisionData(null, files); } RevCommit revCommit; Repository repository = getRepository(files[0]); FileVersion[] versions = new FileVersion[files.length]; try { ObjectId rev = repository.resolve(label); RevWalk walk = new RevWalk(repository); revCommit = walk.parseCommit(rev); PersonIdent author = revCommit.getAuthorIdent(); int counter = 0; for (File file : files) { String path = getPath(file, repository); byte[] content = getRepositoryContent(repository, revCommit, path); versions[counter++] = new GitFileVersion(file, content, author.getName(), author.getWhen()); } } catch (IOException e) { throw new RuntimeException("Unable to get data for revision " + label, e); } return versions; }
private void parseAssignee(ChangeNotesCommit commit) throws ConfigInvalidException { if (pastAssignees == null) { pastAssignees = Lists.newArrayList(); } String assigneeValue = parseOneFooter(commit, FOOTER_ASSIGNEE); if (assigneeValue != null) { Optional<Account.Id> parsedAssignee; if (assigneeValue.equals("")) { // Empty footer found, assignee deleted parsedAssignee = Optional.empty(); } else { PersonIdent ident = RawParseUtils.parsePersonIdent(assigneeValue); parsedAssignee = Optional.ofNullable(noteUtil.parseIdent(ident, id)); } if (assignee == null) { assignee = parsedAssignee; } if (parsedAssignee.isPresent()) { pastAssignees.add(parsedAssignee.get()); } } }
@Inject PostGpgKeys( @GerritPersonIdent Provider<PersonIdent> serverIdent, Provider<CurrentUser> self, Provider<PublicKeyStore> storeProvider, GerritPublicKeyChecker.Factory checkerFactory, AddKeySender.Factory addKeyFactory, Provider<InternalAccountQuery> accountQueryProvider, ExternalIds externalIds, ExternalIdsUpdate.User externalIdsUpdateFactory) { this.serverIdent = serverIdent; this.self = self; this.storeProvider = storeProvider; this.checkerFactory = checkerFactory; this.addKeyFactory = addKeyFactory; this.accountQueryProvider = accountQueryProvider; this.externalIds = externalIds; this.externalIdsUpdateFactory = externalIdsUpdateFactory; }
private static MetaDataUpdateFactory getMetaDataUpdateFactory( MetaDataUpdate.User metaDataUpdateUserFactory, MetaDataUpdate.Server metaDataUpdateServerFactory, @Nullable IdentifiedUser currentUser, PersonIdent serverIdent, String serverId, String anonymousCowardName) { return currentUser != null ? projectName -> { MetaDataUpdate metaDataUpdate = metaDataUpdateUserFactory.create(projectName, currentUser); PersonIdent authorIdent = getAuditLogAuthorIdent( currentUser.getAccount(), serverIdent, serverId, anonymousCowardName); metaDataUpdate.getCommitBuilder().setAuthor(authorIdent); return metaDataUpdate; } : metaDataUpdateServerFactory::create; }
public PersonIdent newRefLogIdent(Date when, TimeZone tz) { final Account ua = getAccount(); String name = ua.getFullName(); if (name == null || name.isEmpty()) { name = ua.getPreferredEmail(); } if (name == null || name.isEmpty()) { name = anonymousCowardName; } String user = getUserName(); if (user == null) { user = ""; } user = user + "|account-" + ua.getId().toString(); return new PersonIdent(name, user + "@" + guessHost(), when, tz); }
@AssistedInject PushOneCommit( ChangeNotes.Factory notesFactory, ApprovalsUtil approvalsUtil, Provider<InternalChangeQuery> queryProvider, NotesMigration notesMigration, @Assisted ReviewDb db, @Assisted PersonIdent i, @Assisted TestRepository<?> testRepo) throws Exception { this( notesFactory, approvalsUtil, queryProvider, notesMigration, db, i, testRepo, SUBJECT, FILE_NAME, FILE_CONTENT); }
@AssistedInject PushOneCommit( ChangeNotes.Factory notesFactory, ApprovalsUtil approvalsUtil, Provider<InternalChangeQuery> queryProvider, NotesMigration notesMigration, @Assisted ReviewDb db, @Assisted PersonIdent i, @Assisted TestRepository<?> testRepo, @Assisted("changeId") String changeId) throws Exception { this( notesFactory, approvalsUtil, queryProvider, notesMigration, db, i, testRepo, SUBJECT, FILE_NAME, FILE_CONTENT, changeId); }
@AssistedInject PushOneCommit( ChangeNotes.Factory notesFactory, ApprovalsUtil approvalsUtil, Provider<InternalChangeQuery> queryProvider, NotesMigration notesMigration, @Assisted ReviewDb db, @Assisted PersonIdent i, @Assisted TestRepository<?> testRepo, @Assisted String subject, @Assisted Map<String, String> files) throws Exception { this( notesFactory, approvalsUtil, queryProvider, notesMigration, db, i, testRepo, subject, files, null); }
private RevCommit writeCommit(String body, PersonIdent author, boolean initWorkInProgress) throws Exception { Change change = newChange(initWorkInProgress); ChangeNotes notes = newNotes(change).load(); try (ObjectInserter ins = testRepo.getRepository().newObjectInserter()) { CommitBuilder cb = new CommitBuilder(); cb.setParentId(notes.getRevision()); cb.setAuthor(author); cb.setCommitter(new PersonIdent(serverIdent, author.getWhen())); cb.setTreeId(testRepo.tree()); cb.setMessage(body); ObjectId id = ins.insert(cb); ins.flush(); RevCommit commit = walk.parseCommit(id); walk.parseBody(commit); return commit; } }
private ExternalIdsUpdate( GitRepositoryManager repoManager, @Nullable AccountCache accountCache, AllUsersName allUsersName, MetricMaker metricMaker, ExternalIds externalIds, ExternalIdCache externalIdCache, PersonIdent committerIdent, PersonIdent authorIdent, @Nullable IdentifiedUser currentUser, GitReferenceUpdated gitRefUpdated) { this( repoManager, accountCache, allUsersName, metricMaker, externalIds, externalIdCache, committerIdent, authorIdent, currentUser, gitRefUpdated, Runnables.doNothing(), RETRYER); }
private void commitNotes( NoteMap notes, String notesBranch, PersonIdent commitAuthor, String commitMessage) throws LockFailureException, IOException { try { revWalk = new RevWalk(db); reader = db.newObjectReader(); loadBase(notesBranch); if (overwrite) { addAllNotes(notes); } else { addNewNotes(notes); } if (base != null) { oursCommit = createCommit(ours, commitAuthor, commitMessage, baseCommit); } else { oursCommit = createCommit(ours, commitAuthor, commitMessage); } updateRef(notesBranch); } finally { revWalk.close(); reader.close(); } }
@Inject public User( GitRepositoryManager repoManager, GitReferenceUpdated gitRefUpdated, AllUsersName allUsersName, OutgoingEmailValidator emailValidator, @GerritPersonIdent Provider<PersonIdent> serverIdent, Provider<IdentifiedUser> identifiedUser, Provider<MetaDataUpdate.User> metaDataUpdateUserFactory) { this.repoManager = repoManager; this.gitRefUpdated = gitRefUpdated; this.allUsersName = allUsersName; this.serverIdent = serverIdent; this.emailValidator = emailValidator; this.identifiedUser = identifiedUser; this.metaDataUpdateUserFactory = metaDataUpdateUserFactory; }
@Test public void noteDbCommit() throws Exception { assume().that(notesMigration.readChanges()).isTrue(); ChangeInfo c = assertCreateSucceeds(newChangeInput(ChangeStatus.NEW)); try (Repository repo = repoManager.openRepository(project); RevWalk rw = new RevWalk(repo)) { RevCommit commit = rw.parseCommit(repo.exactRef(changeMetaRef(new Change.Id(c._number))).getObjectId()); assertThat(commit.getShortMessage()).isEqualTo("Create change"); PersonIdent expectedAuthor = changeNoteUtil.newIdent( accountCache.get(admin.id).getAccount(), c.created, serverIdent.get(), AnonymousCowardNameProvider.DEFAULT); assertThat(commit.getAuthorIdent()).isEqualTo(expectedAuthor); assertThat(commit.getCommitterIdent()) .isEqualTo(new PersonIdent(serverIdent.get(), c.created)); assertThat(commit.getParentCount()).isEqualTo(0); } }
private UserIdentity toUserIdentity(PersonIdent who) throws IOException, OrmException { UserIdentity u = new UserIdentity(); u.setName(who.getName()); u.setEmail(who.getEmailAddress()); u.setDate(new Timestamp(who.getWhen().getTime())); u.setTimeZone(who.getTimeZoneOffset()); // If only one account has access to this email address, select it // as the identity of the user. // Set<Account.Id> a = emails.getAccountFor(u.getEmail()); if (a.size() == 1) { u.setAccount(a.iterator().next()); } return u; }
private Map<String, Set<String>> mergeIdentities( Collection<PersonIdent> persons) { Map<String, Set<String>> namesToEmails = new TreeMap<String, Set<String>>( caseInsensitveComparator); namesToEmails.putAll(RepositoryUtils.mapNamesToEmails(persons)); Map<String, Set<String>> emailsToNames = RepositoryUtils .mapEmailsToNames(persons); for (Entry<String, Set<String>> entry : emailsToNames.entrySet()) for (String name : entry.getValue()) namesToEmails.get(name).add(entry.getKey()); Object[] nameEntries = namesToEmails.entrySet().toArray(); for (int i = 0; i < nameEntries.length; i++) { @SuppressWarnings("unchecked") Entry<String, Set<String>> curr = (Entry<String, Set<String>>) nameEntries[i]; if (curr == null) continue; for (int j = 0; j < nameEntries.length; j++) { if (i == j) continue; for (String email : curr.getValue().toArray( new String[curr.getValue().size()])) { @SuppressWarnings("unchecked") Entry<String, Set<String>> other = (Entry<String, Set<String>>) nameEntries[j]; if (other == null) continue; if (other.getValue().contains(email)) { curr.getValue().addAll(other.getValue()); namesToEmails.remove(other.getKey()); nameEntries[j] = null; } } } } return namesToEmails; }
/** * @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())); } }
GitBlameResult (BlameResult result, Repository repository) { this.lineCount = result.getResultContents().size(); this.lineDetails = new GitLineDetails[lineCount]; Map<String, File> cachedFiles = new HashMap<String, File>(lineCount); this.blamedFile = getFile(cachedFiles, result.getResultPath(), repository.getWorkTree()); Map<RevCommit, GitRevisionInfo> cachedRevisions = new HashMap<RevCommit, GitRevisionInfo>(lineCount); Map<PersonIdent, GitUser> cachedUsers = new HashMap<PersonIdent, GitUser>(lineCount * 2); for (int i = 0; i < lineCount; ++i) { RevCommit commit = result.getSourceCommit(i); if (commit == null) { lineDetails[i] = null; } else { GitRevisionInfo revInfo = cachedRevisions.get(commit); if (revInfo == null) { revInfo = new GitRevisionInfo(commit, repository); cachedRevisions.put(commit, revInfo); } GitUser author = getUser(cachedUsers, result.getSourceAuthor(i)); GitUser committer = getUser(cachedUsers, result.getSourceCommitter(i)); File sourceFile = getFile(cachedFiles, result.getSourcePath(i), repository.getWorkTree()); String content = result.getResultContents().getString(i); lineDetails[i] = new GitLineDetails(content, revInfo, author, committer, sourceFile, result.getSourceLine(i)); } } }
private GitUser getUser (Map<PersonIdent, GitUser> cached, PersonIdent ident) { GitUser user = cached.get(ident); if (user == null) { user = GitClassFactoryImpl.getInstance().createUser(ident); cached.put(ident, user); } return user; }