org.eclipse.jgit.lib.PersonIdent - java examples

Here are the examples of the java api org.eclipse.jgit.lib.PersonIdent taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

155 Examples 7

19 View Complete Implementation : NoteDbUtil.java
Copyright Apache License 2.0
Author : GerritCodeReview
/**
 * Returns an AccountId for the given email address.
 */
public static Optional<Account.Id> parseIdent(PersonIdent ident) {
    String email = ident.getEmailAddress();
    int at = email.indexOf('@');
    if (at >= 0) {
        Integer id = Ints.tryParse(email.substring(0, at));
        if (id != null) {
            return Optional.of(Account.id(id));
        }
    }
    return Optional.empty();
}

19 View Complete Implementation : CommitValidators.java
Copyright Apache License 2.0
Author : GerritCodeReview
private static CommitValidationMessage invalidEmail(String type, PersonIdent who, IdentifiedUser currentUser, UrlFormatter urlFormatter) {
    StringBuilder sb = new StringBuilder();
    sb.append("email address ").append(who.getEmailAddress()).append(" is not registered in your account, and you lack 'forge ").append(type).append("' permission.\n");
    if (currentUser.getEmailAddresses().isEmpty()) {
        sb.append("You have not registered any email addresses.\n");
    } else {
        sb.append("The following addresses are currently registered:\n");
        for (String address : currentUser.getEmailAddresses()) {
            sb.append("   ").append(address).append("\n");
        }
    }
    if (urlFormatter.getSettingsUrl("").isPresent()) {
        sb.append("To register an email address, visit:\n").append(urlFormatter.getSettingsUrl("EmailAddresses").get()).append("\n\n");
    }
    return new CommitValidationMessage(sb.toString(), Type.ERROR);
}

19 View Complete Implementation : AuditLogFormatter.java
Copyright Apache License 2.0
Author : GerritCodeReview
/**
 * Creates a parsable {@code PersonIdent} for commits which are used as an audit log.
 *
 * <p>See {@link #getParsableAuthorIdent(Account, PersonIdent)} for further details.
 *
 * @param accountId the ID of the account of the user who should be represented
 * @param personIdent a {@code PersonIdent} which provides the timestamp for the created {@code
 *     PersonIdent}
 * @return a {@code PersonIdent} which can be used for the author of a commit
 */
public PersonIdent getParsableAuthorIdent(Account.Id accountId, PersonIdent personIdent) {
    String accountName = getAccountName(accountId);
    return getParsableAuthorIdent(accountName, accountId, personIdent);
}

19 View Complete Implementation : ChangeNotesParser.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void parseSubmitRecords(List<String> lines) throws ConfigInvalidException {
    SubmitRecord rec = null;
    for (String line : lines) {
        int c = line.indexOf(": ");
        if (c < 0) {
            rec = new SubmitRecord();
            submitRecords.add(rec);
            int s = line.indexOf(' ');
            String statusStr = s >= 0 ? line.substring(0, s) : line;
            rec.status = Enums.getIfPresent(SubmitRecord.Status.clreplaced, statusStr).orNull();
            checkFooter(rec.status != null, FOOTER_SUBMITTED_WITH, line);
            if (s >= 0) {
                rec.errorMessage = line.substring(s);
            }
        } else {
            checkFooter(rec != null, FOOTER_SUBMITTED_WITH, line);
            SubmitRecord.Label label = new SubmitRecord.Label();
            if (rec.labels == null) {
                rec.labels = new ArrayList<>();
            }
            rec.labels.add(label);
            label.status = Enums.getIfPresent(SubmitRecord.Label.Status.clreplaced, line.substring(0, c)).orNull();
            checkFooter(label.status != null, FOOTER_SUBMITTED_WITH, line);
            int c2 = line.indexOf(": ", c + 2);
            if (c2 >= 0) {
                label.label = line.substring(c + 2, c2);
                PersonIdent ident = RawParseUtils.parsePersonIdent(line.substring(c2 + 2));
                checkFooter(ident != null, FOOTER_SUBMITTED_WITH, line);
                label.appliedBy = parseIdent(ident);
            } else {
                label.label = line.substring(c + 2);
            }
        }
    }
}

19 View Complete Implementation : AbstractQueryAccountsTest.java
Copyright Apache License 2.0
Author : GerritCodeReview
// reindex permissions are tested by {@link Accounreplaced#reindexPermissions}
@Test
public void reindex() throws Exception {
    AccountInfo user1 = newAccountWithFullName("tester", "Test Usre");
    // update account without reindex so that account index is stale
    Account.Id accountId = Account.id(user1._accountId);
    String newName = "Test User";
    try (Repository repo = repoManager.openRepository(allUsers)) {
        MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsers, repo);
        PersonIdent ident = serverIdent.get();
        md.getCommitBuilder().setAuthor(ident);
        md.getCommitBuilder().setCommitter(ident);
        new AccountConfig(accountId, allUsers, repo).load().setAccountUpdate(InternalAccountUpdate.builder().setFullName(newName).build()).commit(md);
    }
    replacedertQuery("name:" + quote(user1.name), user1);
    replacedertQuery("name:" + quote(newName));
    gApi.accounts().id(user1.username).index();
    replacedertQuery("name:" + quote(user1.name));
    replacedertQuery("name:" + quote(newName), user1);
}

19 View Complete Implementation : ChangeNotesParser.java
Copyright Apache License 2.0
Author : GerritCodeReview
private Account.Id parseIdent(ChangeNotesCommit commit) throws ConfigInvalidException {
    // Check if the author name/email is the same as the committer name/email,
    // i.e. was the server ident at the time this commit was made.
    PersonIdent a = commit.getAuthorIdent();
    PersonIdent c = commit.getCommitterIdent();
    if (a.getName().equals(c.getName()) && a.getEmailAddress().equals(c.getEmailAddress())) {
        return null;
    }
    return parseIdent(commit.getAuthorIdent());
}

19 View Complete Implementation : ChangeNotesParser.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void parsereplacedigneeUpdates(Timestamp ts, ChangeNotesCommit commit) throws ConfigInvalidException {
    String replacedigneeValue = parseOneFooter(commit, FOOTER_replacedIGNEE);
    if (replacedigneeValue != null) {
        Optional<Account.Id> parsedreplacedignee;
        if (replacedigneeValue.equals("")) {
            // Empty footer found, replacedignee deleted
            parsedreplacedignee = Optional.empty();
        } else {
            PersonIdent ident = RawParseUtils.parsePersonIdent(replacedigneeValue);
            parsedreplacedignee = Optional.ofNullable(parseIdent(ident));
        }
        replacedigneeUpdates.add(replacedigneeStatusUpdate.create(ts, ownerId, parsedreplacedignee));
    }
}

19 View Complete Implementation : MergeOneOp.java
Copyright Apache License 2.0
Author : GerritCodeReview
@Override
public void updateRepoImpl(RepoContext ctx) throws IntegrationException, IOException {
    PersonIdent caller = ctx.getIdentifiedUser().newCommitterIdent(args.serverIdent.getWhen(), args.serverIdent.getTimeZone());
    if (args.mergeTip.getCurrentTip() == null) {
        throw new IllegalStateException("cannot merge commit " + toMerge.name() + " onto a null tip; expected at least one fast-forward prior to" + " this operation");
    }
    CodeReviewCommit merged = args.mergeUtil.mergeOneCommit(caller, args.serverIdent, args.rw, ctx.getInserter(), ctx.getRepoView().getConfig(), args.destBranch, args.mergeTip.getCurrentTip(), toMerge);
    if (args.project.is(BooleanProjectConfig.REJECT_EMPTY_COMMIT) && merged.getTree().equals(merged.getParent(0).getTree())) {
        toMerge.setStatusCode(EMPTY_COMMIT);
        return;
    }
    args.mergeTip.moveTipTo(amendGitlink(merged), toMerge);
}

18 View Complete Implementation : NotesBranchUtil.java
Copyright Apache License 2.0
Author : GerritCodeReview
/**
 * Create a new commit in the {@code notesBranch} by updating existing or creating new notes from
 * the {@code notes} map.
 *
 * <p>Does not retry in the case of lock failure; callers may use {@link
 * com.google.gerrit.server.update.RetryHelper}.
 *
 * @param notes map of notes
 * @param notesBranch notes branch to update
 * @param commitAuthor author of the commit in the notes branch
 * @param commitMessage for the commit in the notes branch
 * @throws LockFailureException if committing the notes failed due to a lock failure on the notes
 *     branch
 * @throws IOException if committing the notes failed for any other reason
 */
public final void commitAllNotes(NoteMap notes, String notesBranch, PersonIdent commitAuthor, String commitMessage) throws IOException {
    this.overwrite = true;
    commitNotes(notes, notesBranch, commitAuthor, commitMessage);
}

18 View Complete Implementation : ExternalIDCacheLoaderTest.java
Copyright Apache License 2.0
Author : GerritCodeReview
private ObjectId performExternalIdUpdate(Consumer<ExternalIdNotes> update) throws Exception {
    try (Repository repo = repoManager.openRepository(ALL_USERS)) {
        PersonIdent updater = new PersonIdent("Foo bar", "[email protected]");
        ExternalIdNotes extIdNotes = ExternalIdNotes.loadNoCacheUpdate(ALL_USERS, repo);
        update.accept(extIdNotes);
        try (MetaDataUpdate metaDataUpdate = new MetaDataUpdate(GitReferenceUpdated.DISABLED, null, repo)) {
            metaDataUpdate.getCommitBuilder().setAuthor(updater);
            metaDataUpdate.getCommitBuilder().setCommitter(updater);
            return extIdNotes.commit(metaDataUpdate).getId();
        }
    }
}

18 View Complete Implementation : ChangeEditIT.java
Copyright Apache License 2.0
Author : GerritCodeReview
private String newChange2(PersonIdent ident) throws Exception {
    PushOneCommit push = pushFactory.create(ident, testRepo, PushOneCommit.SUBJECT, FILE_NAME, new String(CONTENT_OLD, UTF_8));
    return push.rm("refs/for/master").getChangeId();
}

18 View Complete Implementation : EventFactory.java
Copyright Apache License 2.0
Author : gerrit-review
/**
 * Create an AuthorAttribute for the given person ident suitable for serialization to JSON.
 *
 * @param ident
 * @return object suitable for serialization to JSON
 */
public AccountAttribute asAccountAttribute(PersonIdent ident) {
    AccountAttribute who = new AccountAttribute();
    who.name = ident.getName();
    who.email = ident.getEmailAddress();
    return who;
}

18 View Complete Implementation : ChangeNotesParser.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void parseReviewer(Timestamp ts, ReviewerStateInternal state, String line) throws ConfigInvalidException {
    PersonIdent ident = RawParseUtils.parsePersonIdent(line);
    if (ident == null) {
        throw invalidFooter(state.getFooterKey(), line);
    }
    Account.Id accountId = parseIdent(ident);
    reviewerUpdates.add(ReviewerStatusUpdate.create(ts, ownerId, accountId, state));
    if (!reviewers.containsRow(accountId)) {
        reviewers.put(accountId, state, ts);
    }
}

18 View Complete Implementation : ChangeField.java
Copyright Apache License 2.0
Author : GerritCodeReview
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());
}

18 View Complete Implementation : AccountsUpdate.java
Copyright Apache License 2.0
Author : GerritCodeReview
private static PersonIdent createPersonIdent(PersonIdent serverIdent, Optional<IdentifiedUser> user) {
    if (!user.isPresent()) {
        return serverIdent;
    }
    return user.get().newCommitterIdent(serverIdent.getWhen(), serverIdent.getTimeZone());
}

18 View Complete Implementation : ChangeField.java
Copyright Apache License 2.0
Author : gerrit-review
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());
}

18 View Complete Implementation : GroupsOnInit.java
Copyright Apache License 2.0
Author : GerritCodeReview
private MetaDataUpdate createMetaDataUpdate(Repository repository, PersonIdent personIdent) {
    MetaDataUpdate metaDataUpdate = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsers, repository);
    metaDataUpdate.getCommitBuilder().setAuthor(personIdent);
    metaDataUpdate.getCommitBuilder().setCommitter(personIdent);
    return metaDataUpdate;
}

18 View Complete Implementation : EventFactory.java
Copyright Apache License 2.0
Author : GerritCodeReview
/**
 * Create an AuthorAttribute for the given person ident suitable for serialization to JSON.
 *
 * @param ident
 * @return object suitable for serialization to JSON
 */
public AccountAttribute asAccountAttribute(PersonIdent ident) {
    AccountAttribute who = new AccountAttribute();
    who.name = ident.getName();
    who.email = ident.getEmailAddress();
    return who;
}

18 View Complete Implementation : AbstractGroupTest.java
Copyright Apache License 2.0
Author : GerritCodeReview
protected MetaDataUpdate createMetaDataUpdate(PersonIdent authorIdent) {
    MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsersName, allUsersRepo);
    md.getCommitBuilder().setAuthor(authorIdent);
    // Committer is always the server idenreplacedy.
    md.getCommitBuilder().setCommitter(serverIdent);
    return md;
}

18 View Complete Implementation : ConsistencyCheckerIT.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void addNoteDbCommit(Change.Id id, String commitMessage) throws Exception {
    PersonIdent committer = serverIdent.get();
    PersonIdent author = noteUtil.newIdent(getAccount(admin.id()), committer.getWhen(), committer);
    serverSideTestRepo.branch(RefNames.changeMetaRef(id)).commit().author(author).committer(committer).message(commitMessage).create();
}

18 View Complete Implementation : Schema_162.java
Copyright Apache License 2.0
Author : gerrit-review
public clreplaced Schema_162 extends SchemaVersion {

    private final GitRepositoryManager repoManager;

    private final AllProjectsName allProjectsName;

    private final AllUsersName allUsersName;

    private final PersonIdent serverUser;

    @Inject
    Schema_162(Provider<Schema_161> prior, GitRepositoryManager repoManager, AllProjectsName allProjectsName, AllUsersName allUsersName, @GerritPersonIdent PersonIdent serverUser) {
        super(prior);
        this.repoManager = repoManager;
        this.allProjectsName = allProjectsName;
        this.allUsersName = allUsersName;
        this.serverUser = serverUser;
    }

    @Override
    protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException {
        try (Repository git = repoManager.openRepository(allUsersName);
            MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsersName, git)) {
            ProjectConfig cfg = ProjectConfig.read(md);
            if (allProjectsName.equals(cfg.getProject().getParent(allProjectsName))) {
                return;
            }
            cfg.getProject().setParentName(allProjectsName);
            md.getCommitBuilder().setAuthor(serverUser);
            md.getCommitBuilder().setCommitter(serverUser);
            md.setMessage(String.format("Make %s inherit from %s", allUsersName.get(), allProjectsName.get()));
            cfg.commit(md);
        } catch (ConfigInvalidException | IOException ex) {
            throw new OrmException(ex);
        }
    }
}

18 View Complete Implementation : ChangeNotesParser.java
Copyright Apache License 2.0
Author : GerritCodeReview
private Account.Id parseIdent(PersonIdent ident) throws ConfigInvalidException {
    return NoteDbUtil.parseIdent(ident).orElseThrow(() -> parseException("cannot retrieve account id: %s", ident.getEmailAddress()));
}

18 View Complete Implementation : MergeUtil.java
Copyright Apache License 2.0
Author : gerrit-review
public CodeReviewCommit mergeOneCommit(PersonIdent author, PersonIdent committer, CodeReviewRevWalk rw, ObjectInserter inserter, Config repoConfig, Branch.NameKey destBranch, CodeReviewCommit mergeTip, CodeReviewCommit n) throws IntegrationException {
    ThreeWayMerger m = newThreeWayMerger(inserter, repoConfig);
    try {
        if (m.merge(new AnyObjectId[] { mergeTip, n })) {
            return writeMergeCommit(author, committer, rw, inserter, destBranch, mergeTip, m.getResultTreeId(), n);
        }
        failed(rw, mergeTip, n, CommitMergeStatus.PATH_CONFLICT);
    } catch (NoMergeBaseException e) {
        try {
            failed(rw, mergeTip, n, getCommitMergeStatus(e.getReason()));
        } catch (IOException e2) {
            throw new IntegrationException("Cannot merge " + n.name(), e);
        }
    } catch (IOException e) {
        throw new IntegrationException("Cannot merge " + n.name(), e);
    }
    return mergeTip;
}

18 View Complete Implementation : GroupTestUtil.java
Copyright Apache License 2.0
Author : GerritCodeReview
public static void updateGroupFile(GitRepositoryManager repoManager, AllUsersName allUsersName, PersonIdent serverIdent, String refName, String fileName, String content) throws Exception {
    try (Repository repo = repoManager.openRepository(allUsersName)) {
        updateGroupFile(repo, serverIdent, refName, fileName, content);
    }
}

18 View Complete Implementation : NotesBranchUtil.java
Copyright Apache License 2.0
Author : gerrit-review
/**
 * Create a new commit in the {@code notesBranch} by updating existing or creating new notes from
 * the {@code notes} map.
 *
 * <p>Does not retry in the case of lock failure; callers may use {@link
 * com.google.gerrit.server.update.RetryHelper}.
 *
 * @param notes map of notes
 * @param notesBranch notes branch to update
 * @param commitAuthor author of the commit in the notes branch
 * @param commitMessage for the commit in the notes branch
 * @throws LockFailureException if committing the notes failed due to a lock failure on the notes
 *     branch
 * @throws IOException if committing the notes failed for any other reason
 */
public final void commitAllNotes(NoteMap notes, String notesBranch, PersonIdent commitAuthor, String commitMessage) throws IOException {
    this.overwrite = true;
    commitNotes(notes, notesBranch, commitAuthor, commitMessage);
}

18 View Complete Implementation : ChangeNotesParser.java
Copyright Apache License 2.0
Author : gerrit-review
private void parsereplacedignee(ChangeNotesCommit commit) throws ConfigInvalidException {
    if (pastreplacedignees == null) {
        pastreplacedignees = Lists.newArrayList();
    }
    String replacedigneeValue = parseOneFooter(commit, FOOTER_replacedIGNEE);
    if (replacedigneeValue != null) {
        Optional<Account.Id> parsedreplacedignee;
        if (replacedigneeValue.equals("")) {
            // Empty footer found, replacedignee deleted
            parsedreplacedignee = Optional.empty();
        } else {
            PersonIdent ident = RawParseUtils.parsePersonIdent(replacedigneeValue);
            parsedreplacedignee = Optional.ofNullable(noteUtil.parseIdent(ident, id));
        }
        if (replacedignee == null) {
            replacedignee = parsedreplacedignee;
        }
        if (parsedreplacedignee.isPresent()) {
            pastreplacedignees.add(parsedreplacedignee.get());
        }
    }
}

18 View Complete Implementation : ChangeNotesParser.java
Copyright Apache License 2.0
Author : gerrit-review
private PatchSetApproval parseRemoveApproval(PatchSet.Id psId, Account.Id committerId, Account.Id realAccountId, Timestamp ts, String line) throws ConfigInvalidException {
    // See comments in parseAddApproval about the various users involved.
    Account.Id effectiveAccountId;
    String label;
    int s = line.indexOf(' ');
    if (s > 0) {
        label = line.substring(1, s);
        PersonIdent ident = RawParseUtils.parsePersonIdent(line.substring(s + 1));
        checkFooter(ident != null, FOOTER_LABEL, line);
        effectiveAccountId = noteUtil.parseIdent(ident, id);
    } else {
        label = line.substring(1);
        effectiveAccountId = committerId;
    }
    try {
        LabelType.checkNameInternal(label);
    } catch (IllegalArgumentException e) {
        ConfigInvalidException pe = parseException("invalid %s: %s", FOOTER_LABEL, line);
        pe.initCause(e);
        throw pe;
    }
    // Store an actual 0-vote approval in the map for a removed approval, for
    // several reasons:
    // - This is closer to the ReviewDb representation, which leads to less
    // confusion and special-casing of NoteDb.
    // - More importantly, ApprovalCopier needs an actual approval in order to
    // block copying an earlier approval over a later delete.
    PatchSetApproval remove = new PatchSetApproval(new PatchSetApproval.Key(psId, effectiveAccountId, new LabelId(label)), (short) 0, ts);
    if (!Objects.equals(realAccountId, committerId)) {
        remove.setRealAccountId(realAccountId);
    }
    ApprovalKey k = ApprovalKey.create(psId, effectiveAccountId, label);
    if (!approvals.containsKey(k)) {
        approvals.put(k, remove);
    }
    return remove;
}

17 View Complete Implementation : ChangeEditIT.java
Copyright Apache License 2.0
Author : GerritCodeReview
private String newChange(PersonIdent ident) throws Exception {
    PushOneCommit push = pushFactory.create(ident, testRepo, PushOneCommit.SUBJECT, FILE_NAME, new String(CONTENT_OLD, UTF_8));
    return push.to("refs/for/master").getChangeId();
}

17 View Complete Implementation : AbstractChangeUpdate.java
Copyright Apache License 2.0
Author : GerritCodeReview
private static PersonIdent ident(ChangeNoteUtil noteUtil, PersonIdent serverIdent, CurrentUser u, Date when) {
    checkUserType(u);
    if (u instanceof IdentifiedUser) {
        return noteUtil.newIdent(u.asIdentifiedUser().getAccount(), when, serverIdent);
    } else if (u instanceof InternalUser) {
        return serverIdent;
    }
    throw new IllegalStateException();
}

17 View Complete Implementation : GetBlame.java
Copyright Apache License 2.0
Author : GerritCodeReview
private static BlameInfo toBlameInfo(RevCommit commit, PersonIdent sourceAuthor) {
    BlameInfo blameInfo = new BlameInfo();
    blameInfo.author = sourceAuthor.getName();
    blameInfo.id = commit.getName();
    blameInfo.commitMsg = commit.getFullMessage();
    blameInfo.time = commit.getCommitTime();
    return blameInfo;
}

17 View Complete Implementation : GitUtil.java
Copyright Apache License 2.0
Author : GerritCodeReview
public static Ref updateAnnotatedTag(TestRepository<?> testRepo, String name, PersonIdent tagger) throws GitAPIException {
    TagCommand tc = testRepo.git().tag().setName(name);
    return tc.setAnnotated(true).setMessage(name).setTagger(tagger).setForceUpdate(true).call();
}

17 View Complete Implementation : GitUtil.java
Copyright Apache License 2.0
Author : GerritCodeReview
public static Ref createAnnotatedTag(TestRepository<?> testRepo, String name, PersonIdent tagger) throws GitAPIException {
    TagCommand cmd = testRepo.git().tag().setName(name).setAnnotated(true).setMessage(name).setTagger(tagger);
    return cmd.call();
}

17 View Complete Implementation : AuditLogFormatter.java
Copyright Apache License 2.0
Author : GerritCodeReview
/**
 * Creates a parsable {@code PersonIdent} for commits which are used as an audit log.
 *
 * <p><em>Parsable</em> means that we can unambiguously identify the original account when being
 * presented with a {@code PersonIdent} of a commit.
 *
 * <p>We typically use the initiator of an action as the author of the commit when using those
 * commits as an audit log. That's something which has to be specified by a caller of this method
 * as this clreplaced doesn't create any commits itself.
 *
 * @param account the {@code Account} of the user who should be represented
 * @param personIdent a {@code PersonIdent} which provides the timestamp for the created {@code
 *     PersonIdent}
 * @return a {@code PersonIdent} which can be used for the author of a commit
 */
public PersonIdent getParsableAuthorIdent(Account account, PersonIdent personIdent) {
    return getParsableAuthorIdent(account.getName(), account.id(), personIdent);
}

17 View Complete Implementation : MergeUtil.java
Copyright Apache License 2.0
Author : GerritCodeReview
public CodeReviewCommit mergeOneCommit(PersonIdent author, PersonIdent committer, CodeReviewRevWalk rw, ObjectInserter inserter, Config repoConfig, BranchNameKey destBranch, CodeReviewCommit mergeTip, CodeReviewCommit n) throws IntegrationException, InvalidMergeStrategyException {
    ThreeWayMerger m = newThreeWayMerger(inserter, repoConfig);
    try {
        if (m.merge(mergeTip, n)) {
            return writeMergeCommit(author, committer, rw, inserter, destBranch, mergeTip, m.getResultTreeId(), n);
        }
        failed(rw, mergeTip, n, CommitMergeStatus.PATH_CONFLICT);
    } catch (NoMergeBaseException e) {
        try {
            failed(rw, mergeTip, n, getCommitMergeStatus(e.getReason()));
        } catch (IOException e2) {
            throw new IntegrationException("Cannot merge " + n.name(), e);
        }
    } catch (IOException e) {
        throw new IntegrationException("Cannot merge " + n.name(), e);
    }
    return mergeTip;
}

17 View Complete Implementation : ChangeEditIT.java
Copyright Apache License 2.0
Author : GerritCodeReview
private String amendChange(PersonIdent ident, String changeId) throws Exception {
    PushOneCommit push = pushFactory.create(ident, testRepo, PushOneCommit.SUBJECT, FILE_NAME2, new String(CONTENT_NEW2, UTF_8), changeId);
    return push.to("refs/for/master").getChangeId();
}

17 View Complete Implementation : ProjectConfigSchemaUpdate.java
Copyright Apache License 2.0
Author : GerritCodeReview
public void save(PersonIdent personIdent, String commitMessage) {
    if (!updated) {
        return;
    }
    update.getCommitBuilder().setAuthor(personIdent);
    update.getCommitBuilder().setCommitter(personIdent);
    update.setMessage(commitMessage);
    try {
        commit(update);
    } catch (IOException e) {
        throw new StorageException(e);
    }
}

17 View Complete Implementation : GroupsUpdate.java
Copyright Apache License 2.0
Author : GerritCodeReview
private static PersonIdent createPersonIdent(PersonIdent ident, IdentifiedUser user) {
    return user.newCommitterIdent(ident.getWhen(), ident.getTimeZone());
}

17 View Complete Implementation : ChangeNotesParser.java
Copyright Apache License 2.0
Author : GerritCodeReview
private PatchSetApproval.Builder parseRemoveApproval(PatchSet.Id psId, Account.Id committerId, Account.Id realAccountId, Timestamp ts, String line) throws ConfigInvalidException {
    // See comments in parseAddApproval about the various users involved.
    Account.Id effectiveAccountId;
    String label;
    int s = line.indexOf(' ');
    if (s > 0) {
        label = line.substring(1, s);
        PersonIdent ident = RawParseUtils.parsePersonIdent(line.substring(s + 1));
        checkFooter(ident != null, FOOTER_LABEL, line);
        effectiveAccountId = parseIdent(ident);
    } else {
        label = line.substring(1);
        effectiveAccountId = committerId;
    }
    try {
        LabelType.checkNameInternal(label);
    } catch (IllegalArgumentException e) {
        ConfigInvalidException pe = parseException("invalid %s: %s", FOOTER_LABEL, line);
        pe.initCause(e);
        throw pe;
    }
    // Store an actual 0-vote approval in the map for a removed approval, because ApprovalCopier
    // needs an actual approval in order to block copying an earlier approval over a later delete.
    PatchSetApproval.Builder remove = PatchSetApproval.builder().key(PatchSetApproval.key(psId, effectiveAccountId, LabelId.create(label))).value(0).granted(ts);
    if (!Objects.equals(realAccountId, committerId)) {
        remove.realAccountId(realAccountId);
    }
    approvals.putIfAbsent(remove.key(), remove);
    return remove;
}

17 View Complete Implementation : ProjectConfigSchemaUpdate.java
Copyright Apache License 2.0
Author : gerrit-review
public void save(PersonIdent personIdent, String commitMessage) throws OrmException {
    if (!updated) {
        return;
    }
    update.getCommitBuilder().setAuthor(personIdent);
    update.getCommitBuilder().setCommitter(personIdent);
    update.setMessage(commitMessage);
    try {
        commit(update);
    } catch (IOException e) {
        throw new OrmException(e);
    }
}

16 View Complete Implementation : AccountIndexerIT.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void updateAccountWithoutCacheOrIndex(Account.Id accountId, InternalAccountUpdate accountUpdate) throws IOException, ConfigInvalidException {
    try (Repository allUsersRepo = repoManager.openRepository(allUsersName);
        MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsersName, allUsersRepo)) {
        PersonIdent ident = serverIdent.get();
        md.getCommitBuilder().setAuthor(ident);
        md.getCommitBuilder().setCommitter(ident);
        AccountConfig accountConfig = new AccountConfig(accountId, allUsersName, allUsersRepo).load();
        accountConfig.setAccountUpdate(accountUpdate);
        accountConfig.commit(md);
    }
}

16 View Complete Implementation : CreateChange.java
Copyright Apache License 2.0
Author : GerritCodeReview
private static RevCommit newCommit(ObjectInserter oi, RevWalk rw, PersonIdent authorIdent, RevCommit mergeTip, String commitMessage) throws IOException {
    logger.atFine().log("Creating empty commit");
    CommitBuilder commit = new CommitBuilder();
    if (mergeTip == null) {
        commit.setTreeId(emptyTreeId(oi));
    } else {
        commit.setTreeId(mergeTip.getTree().getId());
        commit.setParentId(mergeTip);
    }
    commit.setAuthor(authorIdent);
    commit.setCommitter(authorIdent);
    commit.setMessage(commitMessage);
    return rw.parseCommit(insert(oi, commit));
}

16 View Complete Implementation : CreateChange.java
Copyright Apache License 2.0
Author : GerritCodeReview
private RevCommit newMergeCommit(Repository repo, ObjectInserter oi, RevWalk rw, ProjectState projectState, RevCommit mergeTip, MergeInput merge, PersonIdent authorIdent, String commitMessage) throws RestApiException, IOException {
    logger.atFine().log("Creating merge commit: source = %s, strategy = %s", merge.source, merge.strategy);
    if (Strings.isNullOrEmpty(merge.source)) {
        throw new BadRequestException("merge.source must be non-empty");
    }
    RevCommit sourceCommit = MergeUtil.resolveCommit(repo, rw, merge.source);
    if (merge.sourceBranch != null) {
        Ref ref = repo.findRef(merge.sourceBranch);
        logger.atFine().log("checking visibility for branch %s", merge.sourceBranch);
        if (ref == null || !commits.canRead(projectState, repo, sourceCommit, ref)) {
            throw new BadRequestException("do not have read permission for: " + merge.source);
        }
    } else if (!commits.canRead(projectState, repo, sourceCommit)) {
        throw new BadRequestException("do not have read permission for: " + merge.source);
    }
    MergeUtil mergeUtil = mergeUtilFactory.create(projectState);
    // default merge strategy from project settings
    String mergeStrategy = firstNonNull(Strings.emptyToNull(merge.strategy), mergeUtil.mergeStrategyName());
    logger.atFine().log("merge strategy = %s", mergeStrategy);
    try {
        return MergeUtil.createMergeCommit(oi, repo.getConfig(), mergeTip, sourceCommit, mergeStrategy, authorIdent, commitMessage, rw);
    } catch (NoMergeBaseException e) {
        throw new ResourceConflictException(String.format("Cannot create merge commit: %s", e.getMessage()), e);
    }
}

16 View Complete Implementation : GroupNameNotesTest.java
Copyright Apache License 2.0
Author : GerritCodeReview
@Test
public void updateGroupNamesWithEmptyCollectionClearsAllNotes() throws Exception {
    GroupReference g1 = newGroup("a");
    GroupReference g2 = newGroup("b");
    PersonIdent ident = newPersonIdent();
    updateAllGroups(ident, g1, g2);
    replacedertThat(GroupNameNotes.loadAllGroups(repo)).containsExactly(g1, g2);
    updateAllGroups(ident);
    replacedertThat(GroupNameNotes.loadAllGroups(repo)).isEmpty();
    ImmutableList<CommitInfo> log = log();
    replacedertThat(log).hreplacedize(2);
    replacedertThat(log.get(1)).message().isEqualTo("Store 0 group names");
}

16 View Complete Implementation : PublicKeyCheckerTest.java
Copyright Apache License 2.0
Author : GerritCodeReview
private void save() throws Exception {
    PersonIdent ident = new PersonIdent("A U Thor", "[email protected]");
    CommitBuilder cb = new CommitBuilder();
    cb.setAuthor(ident);
    cb.setCommitter(ident);
    RefUpdate.Result result = store.save(cb);
    switch(result) {
        case NEW:
        case FAST_FORWARD:
        case FORCED:
            break;
        case IO_FAILURE:
        case LOCK_FAILURE:
        case NOT_ATTEMPTED:
        case NO_CHANGE:
        case REJECTED:
        case REJECTED_CURRENT_BRANCH:
        case RENAMED:
        case REJECTED_MISSING_OBJECT:
        case REJECTED_OTHER_REASON:
        default:
            throw new replacedertionError(result);
    }
}

16 View Complete Implementation : ExternalIdsOnInit.java
Copyright Apache License 2.0
Author : GerritCodeReview
public synchronized void insert(String commitMessage, Collection<ExternalId> extIds) throws IOException, ConfigInvalidException {
    File path = getPath();
    if (path != null) {
        try (Repository allUsersRepo = new FileRepository(path)) {
            ExternalIdNotes extIdNotes = ExternalIdNotes.loadNoCacheUpdate(allUsers, allUsersRepo);
            extIdNotes.insert(extIds);
            try (MetaDataUpdate metaDataUpdate = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsers, allUsersRepo)) {
                PersonIdent serverIdent = new GerritPersonIdentProvider(flags.cfg).get();
                metaDataUpdate.getCommitBuilder().setAuthor(serverIdent);
                metaDataUpdate.getCommitBuilder().setCommitter(serverIdent);
                metaDataUpdate.getCommitBuilder().setMessage(commitMessage);
                extIdNotes.commit(metaDataUpdate);
            }
        }
    }
}

16 View Complete Implementation : CreateChange.java
Copyright Apache License 2.0
Author : gerrit-review
private RevCommit newMergeCommit(Repository repo, ObjectInserter oi, RevWalk rw, ProjectState projectState, RevCommit mergeTip, MergeInput merge, PersonIdent authorIdent, String commitMessage) throws RestApiException, IOException {
    if (Strings.isNullOrEmpty(merge.source)) {
        throw new BadRequestException("merge.source must be non-empty");
    }
    RevCommit sourceCommit = MergeUtil.resolveCommit(repo, rw, merge.source);
    if (!commits.canRead(projectState, repo, sourceCommit)) {
        throw new BadRequestException("do not have read permission for: " + merge.source);
    }
    MergeUtil mergeUtil = mergeUtilFactory.create(projectState);
    // default merge strategy from project settings
    String mergeStrategy = MoreObjects.firstNonNull(Strings.emptyToNull(merge.strategy), mergeUtil.mergeStrategyName());
    return MergeUtil.createMergeCommit(oi, repo.getConfig(), mergeTip, sourceCommit, mergeStrategy, authorIdent, commitMessage, rw);
}

16 View Complete Implementation : NotesBranchUtil.java
Copyright Apache License 2.0
Author : GerritCodeReview
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();
    }
}

16 View Complete Implementation : GroupNameNotesTest.java
Copyright Apache License 2.0
Author : GerritCodeReview
@Test
public void updateGroupNames() throws Exception {
    GroupReference g1 = newGroup("a");
    GroupReference g2 = newGroup("b");
    PersonIdent ident = newPersonIdent();
    updateAllGroups(ident, g1, g2);
    ImmutableList<CommitInfo> log = log();
    replacedertThat(log).hreplacedize(1);
    replacedertThat(log.get(0)).parents().isEmpty();
    replacedertThat(log.get(0)).message().isEqualTo("Store 2 group names");
    replacedertThat(log.get(0)).author().matches(ident);
    replacedertThat(log.get(0)).committer().matches(ident);
    replacedertThat(GroupNameNotes.loadAllGroups(repo)).containsExactly(g1, g2);
    // Updating the same set of names is a no-op.
    String commit = log.get(0).commit;
    updateAllGroups(newPersonIdent(), g1, g2);
    log = log();
    replacedertThat(log).hreplacedize(1);
    replacedertThat(log.get(0)).commit().isEqualTo(commit);
}

16 View Complete Implementation : ChangeNotesParser.java
Copyright Apache License 2.0
Author : GerritCodeReview
private PatchSetApproval.Builder parseAddApproval(PatchSet.Id psId, Account.Id committerId, Account.Id realAccountId, Timestamp ts, String line) throws ConfigInvalidException {
    // There are potentially 3 accounts involved here:
    // 1. The account from the commit, which is the effective IdentifiedUser
    // that produced the update.
    // 2. The account in the label footer itself, which is used during submit
    // to copy other users' labels to a new patch set.
    // 3. The account in the Real-user footer, indicating that the whole
    // update operation was executed by this user on behalf of the effective
    // user.
    Account.Id effectiveAccountId;
    String labelVoteStr;
    int s = line.indexOf(' ');
    if (s > 0) {
        // Account in the label line (2) becomes the effective ID of the
        // approval. If there is a real user (3) different from the commit user
        // (2), we actually don't store that anywhere in this case; it's more
        // important to record that the real user (3) actually initiated submit.
        labelVoteStr = line.substring(0, s);
        PersonIdent ident = RawParseUtils.parsePersonIdent(line.substring(s + 1));
        checkFooter(ident != null, FOOTER_LABEL, line);
        effectiveAccountId = parseIdent(ident);
    } else {
        labelVoteStr = line;
        effectiveAccountId = committerId;
    }
    LabelVote l;
    try {
        l = LabelVote.parseWithEquals(labelVoteStr);
    } catch (IllegalArgumentException e) {
        ConfigInvalidException pe = parseException("invalid %s: %s", FOOTER_LABEL, line);
        pe.initCause(e);
        throw pe;
    }
    PatchSetApproval.Builder psa = PatchSetApproval.builder().key(PatchSetApproval.key(psId, effectiveAccountId, LabelId.create(l.label()))).value(l.value()).granted(ts).tag(Optional.ofNullable(tag));
    if (!Objects.equals(realAccountId, committerId)) {
        psa.realAccountId(realAccountId);
    }
    approvals.putIfAbsent(psa.key(), psa);
    return psa;
}

16 View Complete Implementation : ExternalIdTestUtil.java
Copyright Apache License 2.0
Author : GerritCodeReview
public static String insertExternalIdWithInvalidConfig(Repository repo, RevWalk rw, PersonIdent ident, String externalId) throws IOException {
    return insertExternalId(repo, rw, ident, (ins, noteMap) -> {
        ObjectId noteId = ExternalId.Key.parse(externalId).sha1();
        byte[] raw = "bad-config".getBytes(UTF_8);
        ObjectId dataBlob = ins.insert(OBJ_BLOB, raw);
        noteMap.set(noteId, dataBlob);
        return noteId;
    });
}