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

The following are top voted examples for showing how to use org.eclipse.jgit.lib.PersonIdent. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: centraldogma   File: GitRepository.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 2
Project: gitplex-mit   File: GitUtils.java   View source code 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 3
Project: gitplex-mit   File: LogCommit.java   View source code 6 votes vote down vote up
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);
}
 
Example 4
Project: gmds   File: Commands.java   View source code 6 votes vote down vote up
/**
 * 
 * @param commitBuilder
 * @param treeId
 * @param repo
 * @return
 * @throws UnsupportedEncodingException
 * @throws IOException 
 */
public static ObjectId commit(CommitBuilder commitBuilder, ObjectId treeId, Repository repo) throws UnsupportedEncodingException, IOException {
    commitBuilder.setTreeId(treeId);
    commitBuilder.setMessage(System.currentTimeMillis() + ": My commit!\n");
    PersonIdent person = new PersonIdent("Alex", "[email protected]");
    commitBuilder.setAuthor(person);
    commitBuilder.setCommitter(person);

    commitBuilder.build();

    ObjectInserter commitInserter = repo.newObjectInserter();
    ObjectId commitId = commitInserter.insert(commitBuilder);
    commitInserter.flush();

    updateMasterRecord(repo, commitId);

    System.out.println("Commit Object ID: " + commitId.getName());

    return commitId;
}
 
Example 5
Project: pdi-git-plugin   File: UIGit.java   View source code 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
Project: pdi-git-plugin   File: UIGitTest.java   View source code 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 7
Project: fabric8-forge   File: RepositoryResource.java   View source code 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 8
Project: cwlviewer   File: GitService.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 9
Project: app-runner-router   File: AppRepo.java   View source code 6 votes vote down vote up
public static AppRepo create(String name, File originDir) {
    try {
        InitCommand initCommand = Git.init();
        initCommand.setDirectory(originDir);
        Git origin = initCommand.call();

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

        return new AppRepo(name, originDir, origin);
    } catch (Exception e) {
        throw new RuntimeException("Error while creating git repo", e);
    }
}
 
Example 10
Project: app-runner   File: SystemTest.java   View source code 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 11
Project: app-runner   File: GitCommitTest.java   View source code 6 votes vote down vote up
@Test
public void returnsCurrentCommitForNonEmptyRepos() throws Exception {
    Git git = emptyRepo();
    FileRepository repository = (FileRepository) git.getRepository();
    File dir = repository.getDirectory();
    FileUtils.writeStringToFile(new File(dir, "file1"), "Hello", "UTF-8");
    git.add().addFilepattern(".").call();
    git.commit().setMessage("Initial commit")
        .setAuthor(new PersonIdent("Author Test", "[email protected]"))
        .call();

    FileUtils.writeStringToFile(new File(dir, "file2"), "Hello too", "UTF-8");
    git.add().addFilepattern(".").call();
    git.commit().setMessage("Second commit")
        .setAuthor(new PersonIdent("Second contributor", "[email protected]"))
        .call();

    JSONObject actual = GitCommit.fromHEAD(git).toJSON();
    JSONAssert.assertEquals("{" +
        "author: 'Second contributor', message: 'Second commit'" +
        "}", actual, JSONCompareMode.LENIENT);

    assertThat(actual.getLong("date"), Matchers.greaterThanOrEqualTo(System.currentTimeMillis() - 1000));
    assertThat(actual.getString("id"), actual.getString("id").length(), is("3688d7063d2d647e3989d62d9770d0dfd0ce3c25".length()));

}
 
Example 12
Project: app-runner   File: AppRepo.java   View source code 6 votes vote down vote up
public static AppRepo create(String name) {
    try {
        File originDir = copySampleAppToTempDir(name);

        InitCommand initCommand = Git.init();
        initCommand.setDirectory(originDir);
        Git origin = initCommand.call();

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

        return new AppRepo(name, originDir, origin);
    } catch (Exception e) {
        throw new RuntimeException("Error while creating git repo", e);
    }
}
 
Example 13
Project: mdw   File: VersionControlGit.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 14
Project: gerrit   File: AbstractChangeUpdate.java   View source code 6 votes vote down vote up
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);
}
 
Example 15
Project: gerrit   File: ConsistencyCheckerIT.java   View source code 6 votes vote down vote up
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();
}
 
Example 16
Project: gerrit   File: AllProjectsCreator.java   View source code 6 votes vote down vote up
@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);
}
 
Example 17
Project: gerrit   File: RobotCommentUpdate.java   View source code 6 votes vote down vote up
@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);
}
 
Example 18
Project: rtc2gitcli   File: GitMigrator.java   View source code 6 votes vote down vote up
void initialize(Properties props) {
	properties = props;
	commentTranslator = new CommitCommentTranslator(props);
	defaultIdent = new PersonIdent(props.getProperty("user.name", "RTC 2 git"),
			props.getProperty("user.email", "[email protected]"));
	parseElements(props.getProperty("ignore.file.extensions", ""), ignoredFileExtensions);
	// update window cache config
	WindowCacheConfig cfg = getWindowCacheConfig();
	cfg.setPackedGitOpenFiles(
			(int) parseConfigValue(props.getProperty("packedgitopenfiles"), cfg.getPackedGitOpenFiles()));
	cfg.setPackedGitLimit(parseConfigValue(props.getProperty("packedgitlimit"), cfg.getPackedGitLimit()));
	cfg.setPackedGitWindowSize(
			(int) parseConfigValue(props.getProperty("packedgitwindowsize"), cfg.getPackedGitWindowSize()));
	cfg.setPackedGitMMAP(Boolean.parseBoolean(props.getProperty("packedgitmmap")));
	cfg.setDeltaBaseCacheLimit(
			(int) parseConfigValue(props.getProperty("deltabasecachelimit"), cfg.getDeltaBaseCacheLimit()));
	long sft = parseConfigValue(props.getProperty("streamfilethreshold"), cfg.getStreamFileThreshold());
	cfg.setStreamFileThreshold(getMaxFileThresholdValue(sft, Runtime.getRuntime().maxMemory()));
}
 
Example 19
Project: gerrit   File: GroupsIT.java   View source code 6 votes vote down vote up
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);
  }
}
 
Example 20
Project: fabric8-devops   File: GitHelpers.java   View source code 6 votes vote down vote up
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;
}
 
Example 21
Project: gerrit   File: ChangeField.java   View source code 6 votes vote down vote up
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());
}
 
Example 22
Project: fabric8-devops   File: GitBuildConfigProcessor.java   View source code 6 votes vote down vote up
protected void doPull(File gitFolder, CredentialsProvider cp, String branch, PersonIdent personIdent, UserDetails userDetails) {
    try {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(gitFolder)
                .readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();

        Git git = new Git(repository);

        File projectFolder = repository.getDirectory();

        StoredConfig config = repository.getConfig();
        String url = config.getString("remote", userDetails.getRemote(), "url");
        if (Strings.isNullOrBlank(url)) {
            LOG.warn("No remote repository url for " + branch + " defined for the git repository at " + projectFolder.getCanonicalPath() + " so cannot pull");
            //return;
        }
        String mergeUrl = config.getString("branch", branch, "merge");
        if (Strings.isNullOrBlank(mergeUrl)) {
            LOG.warn("No merge spec for branch." + branch + ".merge in the git repository at " + projectFolder.getCanonicalPath() + " so not doing a pull");
            //return;
        }

        LOG.debug("Performing a pull in git repository " + projectFolder.getCanonicalPath() + " on remote URL: " + url);
        PullCommand pull = git.pull();
        GitHelpers.configureCommand(pull, userDetails);
        pull.setRebase(true).call();
    } catch (Throwable e) {
        LOG.error("Failed to pull from the remote git repo with credentials " + cp + " due: " + e.getMessage() + ". This exception is ignored.", e);
    }
}
 
Example 23
Project: fitnesse-git-plugin   File: GitFileVersionsController.java   View source code 6 votes vote down vote up
@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;
}
 
Example 24
Project: gerrit   File: ChangeNotesParser.java   View source code 6 votes vote down vote up
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());
    }
  }
}
 
Example 25
Project: gerrit   File: PostGpgKeys.java   View source code 6 votes vote down vote up
@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;
}
 
Example 26
Project: gerrit   File: GroupsUpdate.java   View source code 6 votes vote down vote up
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;
}
 
Example 27
Project: gerrit   File: IdentifiedUser.java   View source code 6 votes vote down vote up
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);
}
 
Example 28
Project: gerrit   File: PushOneCommit.java   View source code 6 votes vote down vote up
@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);
}
 
Example 29
Project: gerrit   File: PushOneCommit.java   View source code 6 votes vote down vote up
@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);
}
 
Example 30
Project: gerrit   File: PushOneCommit.java   View source code 6 votes vote down vote up
@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);
}
 
Example 31
Project: gerrit   File: ChangeNotesParserTest.java   View source code 6 votes vote down vote up
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;
  }
}
 
Example 32
Project: gerrit   File: ExternalIdsUpdate.java   View source code 6 votes vote down vote up
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);
}
 
Example 33
Project: gerrit   File: NotesBranchUtil.java   View source code 6 votes vote down vote up
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();
  }
}
 
Example 34
Project: gerrit   File: AccountsUpdate.java   View source code 6 votes vote down vote up
@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;
}
 
Example 35
Project: gerrit   File: CreateChangeIT.java   View source code 6 votes vote down vote up
@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);
  }
}
 
Example 36
Project: gerrit   File: EventFactory.java   View source code 6 votes vote down vote up
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;
}
 
Example 37
Project: forweaver2.0   File: GitInfo.java   View source code 5 votes vote down vote up
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;
}
 
Example 38
Project: incubator-netbeans   File: GitRevisionInfo.java   View source code 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 39
Project: incubator-netbeans   File: CommitCommand.java   View source code 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 40
Project: incubator-netbeans   File: GitBlameResult.java   View source code 5 votes vote down vote up
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));
        }
    }
}