Example usage for org.eclipse.jgit.lib Constants FETCH_HEAD

List of usage examples for org.eclipse.jgit.lib Constants FETCH_HEAD

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Constants FETCH_HEAD.

Prototype

String FETCH_HEAD

To view the source code for org.eclipse.jgit.lib Constants FETCH_HEAD.

Click Source Link

Document

Special name for the "FETCH_HEAD" symbolic-ref.

Usage

From source file:com.gitblit.FederationPullExecutor.java

License:Apache License

/**
 * Mirrors a repository and, optionally, the server's users, and/or
 * configuration settings from a origin Gitblit instance.
 * /*from  w w  w. ja  v a  2s.c o  m*/
 * @param registration
 * @throws Exception
 */
private void pull(FederationModel registration) throws Exception {
    Map<String, RepositoryModel> repositories = FederationUtils.getRepositories(registration, true);
    String registrationFolder = registration.folder.toLowerCase().trim();
    // confirm valid characters in server alias
    Character c = StringUtils.findInvalidCharacter(registrationFolder);
    if (c != null) {
        logger.error(MessageFormat.format(
                "Illegal character ''{0}'' in folder name ''{1}'' of federation registration {2}!", c,
                registrationFolder, registration.name));
        return;
    }
    File repositoriesFolder = new File(GitBlit.getString(Keys.git.repositoriesFolder, "git"));
    File registrationFolderFile = new File(repositoriesFolder, registrationFolder);
    registrationFolderFile.mkdirs();

    // Clone/Pull the repository
    for (Map.Entry<String, RepositoryModel> entry : repositories.entrySet()) {
        String cloneUrl = entry.getKey();
        RepositoryModel repository = entry.getValue();
        if (!repository.hasCommits) {
            logger.warn(MessageFormat.format(
                    "Skipping federated repository {0} from {1} @ {2}. Repository is EMPTY.", repository.name,
                    registration.name, registration.url));
            registration.updateStatus(repository, FederationPullStatus.SKIPPED);
            continue;
        }

        // Determine local repository name
        String repositoryName;
        if (StringUtils.isEmpty(registrationFolder)) {
            repositoryName = repository.name;
        } else {
            repositoryName = registrationFolder + "/" + repository.name;
        }

        if (registration.bare) {
            // bare repository, ensure .git suffix
            if (!repositoryName.toLowerCase().endsWith(DOT_GIT_EXT)) {
                repositoryName += DOT_GIT_EXT;
            }
        } else {
            // normal repository, strip .git suffix
            if (repositoryName.toLowerCase().endsWith(DOT_GIT_EXT)) {
                repositoryName = repositoryName.substring(0, repositoryName.indexOf(DOT_GIT_EXT));
            }
        }

        // confirm that the origin of any pre-existing repository matches
        // the clone url
        String fetchHead = null;
        Repository existingRepository = GitBlit.self().getRepository(repositoryName);
        if (existingRepository != null) {
            StoredConfig config = existingRepository.getConfig();
            config.load();
            String origin = config.getString("remote", "origin", "url");
            RevCommit commit = JGitUtils.getCommit(existingRepository,
                    org.eclipse.jgit.lib.Constants.FETCH_HEAD);
            if (commit != null) {
                fetchHead = commit.getName();
            }
            existingRepository.close();
            if (!origin.startsWith(registration.url)) {
                logger.warn(MessageFormat.format(
                        "Skipping federated repository {0} from {1} @ {2}. Origin does not match, consider EXCLUDING.",
                        repository.name, registration.name, registration.url));
                registration.updateStatus(repository, FederationPullStatus.SKIPPED);
                continue;
            }
        }

        // clone/pull this repository
        CredentialsProvider credentials = new UsernamePasswordCredentialsProvider(Constants.FEDERATION_USER,
                registration.token);
        logger.info(MessageFormat.format("Pulling federated repository {0} from {1} @ {2}", repository.name,
                registration.name, registration.url));

        CloneResult result = JGitUtils.cloneRepository(registrationFolderFile, repository.name, cloneUrl,
                registration.bare, credentials);
        Repository r = GitBlit.self().getRepository(repositoryName);
        RepositoryModel rm = GitBlit.self().getRepositoryModel(repositoryName);
        repository.isFrozen = registration.mirror;
        if (result.createdRepository) {
            // default local settings
            repository.federationStrategy = FederationStrategy.EXCLUDE;
            repository.isFrozen = registration.mirror;
            repository.showRemoteBranches = !registration.mirror;
            logger.info(MessageFormat.format("     cloning {0}", repository.name));
            registration.updateStatus(repository, FederationPullStatus.MIRRORED);
        } else {
            // fetch and update
            boolean fetched = false;
            RevCommit commit = JGitUtils.getCommit(r, org.eclipse.jgit.lib.Constants.FETCH_HEAD);
            String newFetchHead = commit.getName();
            fetched = fetchHead == null || !fetchHead.equals(newFetchHead);

            if (registration.mirror) {
                // mirror
                if (fetched) {
                    // update local branches to match the remote tracking branches
                    for (RefModel ref : JGitUtils.getRemoteBranches(r, false, -1)) {
                        if (ref.displayName.startsWith("origin/")) {
                            String branch = org.eclipse.jgit.lib.Constants.R_HEADS
                                    + ref.displayName.substring(ref.displayName.indexOf('/') + 1);
                            String hash = ref.getReferencedObjectId().getName();

                            JGitUtils.setBranchRef(r, branch, hash);
                            logger.info(MessageFormat.format("     resetting {0} of {1} to {2}", branch,
                                    repository.name, hash));
                        }
                    }

                    String newHead;
                    if (StringUtils.isEmpty(repository.HEAD)) {
                        newHead = newFetchHead;
                    } else {
                        newHead = repository.HEAD;
                    }
                    JGitUtils.setHEADtoRef(r, newHead);
                    logger.info(MessageFormat.format("     resetting HEAD of {0} to {1}", repository.name,
                            newHead));
                    registration.updateStatus(repository, FederationPullStatus.MIRRORED);
                } else {
                    // indicate no commits pulled
                    registration.updateStatus(repository, FederationPullStatus.NOCHANGE);
                }
            } else {
                // non-mirror
                if (fetched) {
                    // indicate commits pulled to origin/master
                    registration.updateStatus(repository, FederationPullStatus.PULLED);
                } else {
                    // indicate no commits pulled
                    registration.updateStatus(repository, FederationPullStatus.NOCHANGE);
                }
            }

            // preserve local settings
            repository.isFrozen = rm.isFrozen;
            repository.federationStrategy = rm.federationStrategy;

            // merge federation sets
            Set<String> federationSets = new HashSet<String>();
            if (rm.federationSets != null) {
                federationSets.addAll(rm.federationSets);
            }
            if (repository.federationSets != null) {
                federationSets.addAll(repository.federationSets);
            }
            repository.federationSets = new ArrayList<String>(federationSets);

            // merge indexed branches
            Set<String> indexedBranches = new HashSet<String>();
            if (rm.indexedBranches != null) {
                indexedBranches.addAll(rm.indexedBranches);
            }
            if (repository.indexedBranches != null) {
                indexedBranches.addAll(repository.indexedBranches);
            }
            repository.indexedBranches = new ArrayList<String>(indexedBranches);

        }
        // only repositories that are actually _cloned_ from the origin
        // Gitblit repository are marked as federated. If the origin
        // is from somewhere else, these repositories are not considered
        // "federated" repositories.
        repository.isFederated = cloneUrl.startsWith(registration.url);

        GitBlit.self().updateConfiguration(r, repository);
        r.close();
    }

    IUserService userService = null;

    try {
        // Pull USERS
        // TeamModels are automatically pulled because they are contained
        // within the UserModel. The UserService creates unknown teams
        // and updates existing teams.
        Collection<UserModel> users = FederationUtils.getUsers(registration);
        if (users != null && users.size() > 0) {
            File realmFile = new File(registrationFolderFile, registration.name + "_users.conf");
            realmFile.delete();
            userService = new ConfigUserService(realmFile);
            for (UserModel user : users) {
                userService.updateUserModel(user.username, user);

                // merge the origin permissions and origin accounts into
                // the user accounts of this Gitblit instance
                if (registration.mergeAccounts) {
                    // reparent all repository permissions if the local
                    // repositories are stored within subfolders
                    if (!StringUtils.isEmpty(registrationFolder)) {
                        List<String> permissions = new ArrayList<String>(user.repositories);
                        user.repositories.clear();
                        for (String permission : permissions) {
                            user.addRepository(registrationFolder + "/" + permission);
                        }
                    }

                    // insert new user or update local user
                    UserModel localUser = GitBlit.self().getUserModel(user.username);
                    if (localUser == null) {
                        // create new local user
                        GitBlit.self().updateUserModel(user.username, user, true);
                    } else {
                        // update repository permissions of local user
                        for (String repository : user.repositories) {
                            localUser.addRepository(repository);
                        }
                        localUser.password = user.password;
                        localUser.canAdmin = user.canAdmin;
                        GitBlit.self().updateUserModel(localUser.username, localUser, false);
                    }

                    for (String teamname : GitBlit.self().getAllTeamnames()) {
                        TeamModel team = GitBlit.self().getTeamModel(teamname);
                        if (user.isTeamMember(teamname) && !team.hasUser(user.username)) {
                            // new team member
                            team.addUser(user.username);
                            GitBlit.self().updateTeamModel(teamname, team, false);
                        } else if (!user.isTeamMember(teamname) && team.hasUser(user.username)) {
                            // remove team member
                            team.removeUser(user.username);
                            GitBlit.self().updateTeamModel(teamname, team, false);
                        }

                        // update team repositories
                        TeamModel remoteTeam = user.getTeam(teamname);
                        if (remoteTeam != null && !ArrayUtils.isEmpty(remoteTeam.repositories)) {
                            int before = team.repositories.size();
                            team.addRepositories(remoteTeam.repositories);
                            int after = team.repositories.size();
                            if (after > before) {
                                // repository count changed, update
                                GitBlit.self().updateTeamModel(teamname, team, false);
                            }
                        }
                    }
                }
            }
        }
    } catch (ForbiddenException e) {
        // ignore forbidden exceptions
    } catch (IOException e) {
        logger.warn(MessageFormat.format("Failed to retrieve USERS from federated gitblit ({0} @ {1})",
                registration.name, registration.url), e);
    }

    try {
        // Pull TEAMS
        // We explicitly pull these even though they are embedded in
        // UserModels because it is possible to use teams to specify
        // mailing lists or push scripts without specifying users.
        if (userService != null) {
            Collection<TeamModel> teams = FederationUtils.getTeams(registration);
            if (teams != null && teams.size() > 0) {
                for (TeamModel team : teams) {
                    userService.updateTeamModel(team);
                }
            }
        }
    } catch (ForbiddenException e) {
        // ignore forbidden exceptions
    } catch (IOException e) {
        logger.warn(MessageFormat.format("Failed to retrieve TEAMS from federated gitblit ({0} @ {1})",
                registration.name, registration.url), e);
    }

    try {
        // Pull SETTINGS
        Map<String, String> settings = FederationUtils.getSettings(registration);
        if (settings != null && settings.size() > 0) {
            Properties properties = new Properties();
            properties.putAll(settings);
            FileOutputStream os = new FileOutputStream(
                    new File(registrationFolderFile, registration.name + "_" + Constants.PROPERTIES_FILE));
            properties.store(os, null);
            os.close();
        }
    } catch (ForbiddenException e) {
        // ignore forbidden exceptions
    } catch (IOException e) {
        logger.warn(MessageFormat.format("Failed to retrieve SETTINGS from federated gitblit ({0} @ {1})",
                registration.name, registration.url), e);
    }

    try {
        // Pull SCRIPTS
        Map<String, String> scripts = FederationUtils.getScripts(registration);
        if (scripts != null && scripts.size() > 0) {
            for (Map.Entry<String, String> script : scripts.entrySet()) {
                String scriptName = script.getKey();
                if (scriptName.endsWith(".groovy")) {
                    scriptName = scriptName.substring(0, scriptName.indexOf(".groovy"));
                }
                File file = new File(registrationFolderFile, registration.name + "_" + scriptName + ".groovy");
                FileUtils.writeContent(file, script.getValue());
            }
        }
    } catch (ForbiddenException e) {
        // ignore forbidden exceptions
    } catch (IOException e) {
        logger.warn(MessageFormat.format("Failed to retrieve SCRIPTS from federated gitblit ({0} @ {1})",
                registration.name, registration.url), e);
    }
}

From source file:com.microsoft.gittf.core.tasks.FetchTask.java

License:Open Source License

private boolean writeFetchHead(final ObjectId commitID, final int changesetID) throws IOException {
    Ref fetchHeadRef = repository.getRef(Constants.FETCH_HEAD);
    boolean referencesEqual = fetchHeadRef == null ? false : fetchHeadRef.getObjectId().equals(commitID);

    if (referencesEqual) {
        return false;
    }/* w w w  .j av  a2s . co m*/

    final File refFile = new File(repository.getDirectory(), Constants.FETCH_HEAD);
    final LockFile lockFile = new LockFile(refFile, repository.getFS());

    if (lockFile.lock()) {
        try {
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(lockFile.getOutputStream(), Charset.forName("UTF-8"))); //$NON-NLS-1$

            try {
                writer.append(MessageFormat.format("{0}\t\t{1}", commitID.getName(), //$NON-NLS-1$
                        Messages.formatString("FetchTask.RefLogFormat", //$NON-NLS-1$
                                Integer.toString(changesetID))));
            } finally {
                writer.close();
            }

            lockFile.commit();
        } finally {
            lockFile.unlock();
        }
    }

    return true;
}

From source file:com.microsoft.gittf.core.tasks.FetchTaskTest.java

License:Open Source License

@Test
public void testFetchShallow() throws Exception {
    URI projectCollectionURI = new URI("http://fakeCollection:8080/tfs/DefaultCollection"); //$NON-NLS-1$
    String tfsPath = "$/project"; //$NON-NLS-1$
    String gitRepositoryPath = Util.getRepositoryFile(getName()).getAbsolutePath();

    final MockVersionControlService mockVersionControlService = new MockVersionControlService();

    mockVersionControlService.AddFile("$/project/folder/file0.txt", 1); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file0.txt", 1); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file0.txt", 1); //$NON-NLS-1$

    mockVersionControlService.AddFile("$/project/folder/file1.txt", 2); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file1.txt", 2); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file1.txt", 2); //$NON-NLS-1$

    mockVersionControlService.AddFile("$/project/folder/file2.txt", 3); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file2.txt", 3); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file2.txt", 3); //$NON-NLS-1$

    Calendar date = Calendar.getInstance();
    date.set(2012, 11, 12, 18, 15);//from w ww . j  av a2  s .  c  o  m

    MockChangesetProperties changesetProperties = new MockChangesetProperties("ownerDisplayName", //$NON-NLS-1$
            "ownerName", //$NON-NLS-1$
            "committerDisplayName", //$NON-NLS-1$
            "committerName", //$NON-NLS-1$
            "comment", //$NON-NLS-1$
            date);
    mockVersionControlService.updateChangesetInformation(changesetProperties, 3);

    final Repository repository = RepositoryUtil.createNewRepository(gitRepositoryPath, false);

    CloneTask cloneTask = new CloneTask(projectCollectionURI, mockVersionControlService, tfsPath, repository);
    TaskStatus cloneTaskStatus = cloneTask.run(new NullTaskProgressMonitor());

    // Verify task completed without errors
    assertTrue(cloneTaskStatus.isOK());

    // Update some files
    mockVersionControlService.AddFile("$/project/folder/file1.txt", 4); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file1.txt", 4); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file1.txt", 4); //$NON-NLS-1$

    MockChangesetProperties changesetProperties2 = new MockChangesetProperties("ownerDisplayName4", //$NON-NLS-1$
            "ownerName4", //$NON-NLS-1$
            "committerDisplayName4", //$NON-NLS-1$
            "committerName4", //$NON-NLS-1$
            "comment4", //$NON-NLS-1$
            date);
    mockVersionControlService.updateChangesetInformation(changesetProperties2, 4);

    FetchTask fetchTask = new FetchTask(repository, mockVersionControlService);
    TaskStatus fetchTaskStatus = fetchTask.run(new NullTaskProgressMonitor());

    // Verify task completed without errors
    assertTrue(fetchTaskStatus.isOK());

    // Verify the commit fetched
    Ref fetchHeadRef = repository.getRef(Constants.FETCH_HEAD);
    Ref headRef = repository.getRef(Constants.HEAD);

    assertNotNull(fetchHeadRef);
    assertNotNull(headRef);

    ObjectId fetchHeadCommitID = fetchHeadRef.getObjectId();
    ObjectId headCommitID = headRef.getObjectId();

    RevWalk revWalk = new RevWalk(repository);
    RevCommit fetchedCommit = revWalk.parseCommit(fetchHeadCommitID);
    RevCommit headCommit = revWalk.parseCommit(headCommitID);

    assertEquals(fetchedCommit.getFullMessage(), "comment4"); //$NON-NLS-1$

    PersonIdent ownwer = fetchedCommit.getAuthorIdent();
    assertEquals(ownwer.getEmailAddress(), "ownerName4"); //$NON-NLS-1$
    assertEquals(ownwer.getName(), "ownerDisplayName4"); //$NON-NLS-1$

    PersonIdent committer = fetchedCommit.getCommitterIdent();
    assertEquals(committer.getEmailAddress(), "committerName4"); //$NON-NLS-1$
    assertEquals(committer.getName(), "committerDisplayName4"); //$NON-NLS-1$

    // Verify the file content
    TreeWalk treeWalk = new TreeWalk(repository);
    treeWalk.setRecursive(true);

    treeWalk.addTree(headCommit.getTree());
    treeWalk.addTree(fetchedCommit.getTree());

    treeWalk.setFilter(TreeFilter.ANY_DIFF);

    int count = 0;
    while (treeWalk.next()) {
        ObjectId fileObjectId = treeWalk.getObjectId(1);
        byte[] fileContent = repository.getObjectDatabase().open(fileObjectId, OBJ_BLOB).getBytes();

        switch (count) {
        case 0:
            assertTrue(mockVersionControlService.verifyFileContent(fileContent, "$/project/folder/file1.txt", //$NON-NLS-1$
                    4));
            break;
        case 2:
            assertTrue(mockVersionControlService.verifyFileContent(fileContent, "$/project/folder2/file1.txt", //$NON-NLS-1$
                    4));
            break;
        case 1:
            assertTrue(mockVersionControlService.verifyFileContent(fileContent,
                    "$/project/folder/nestedFolder/file1.txt", //$NON-NLS-1$
                    4));
            break;
        }

        count++;
    }

    Git git = new Git(repository);

    // Verify the tags
    List<Ref> tags = git.tagList().call();
    assertEquals(2, tags.size());
}

From source file:com.microsoft.gittf.core.tasks.FetchTaskTest.java

License:Open Source License

@Test
public void testFetchDeep() throws Exception {
    URI projectCollectionURI = new URI("http://fakeCollection:8080/tfs/DefaultCollection"); //$NON-NLS-1$
    String tfsPath = "$/project"; //$NON-NLS-1$
    String gitRepositoryPath = Util.getRepositoryFile(getName()).getAbsolutePath();

    final MockVersionControlService mockVersionControlService = new MockVersionControlService();

    mockVersionControlService.AddFile("$/project/folder/file0.txt", 1); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file0.txt", 1); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file0.txt", 1); //$NON-NLS-1$

    mockVersionControlService.AddFile("$/project/folder/file1.txt", 2); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file1.txt", 2); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file1.txt", 2); //$NON-NLS-1$

    mockVersionControlService.AddFile("$/project/folder/file2.txt", 3); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file2.txt", 3); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file2.txt", 3); //$NON-NLS-1$

    Calendar date = Calendar.getInstance();
    date.set(2012, 11, 12, 18, 15);/* w  w w . jav  a  2s . c o m*/

    MockChangesetProperties changesetProperties = new MockChangesetProperties("ownerDisplayName", //$NON-NLS-1$
            "ownerName", //$NON-NLS-1$
            "committerDisplayName", //$NON-NLS-1$
            "committerName", //$NON-NLS-1$
            "comment", //$NON-NLS-1$
            date);
    mockVersionControlService.updateChangesetInformation(changesetProperties, 3);

    final Repository repository = RepositoryUtil.createNewRepository(gitRepositoryPath, false);

    CloneTask cloneTask = new CloneTask(projectCollectionURI, mockVersionControlService, tfsPath, repository);
    TaskStatus cloneTaskStatus = cloneTask.run(new NullTaskProgressMonitor());

    // Verify task completed without errors
    assertTrue(cloneTaskStatus.isOK());

    // Update some files
    mockVersionControlService.AddFile("$/project/folder/file1.txt", 4); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file1.txt", 4); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file1.txt", 4); //$NON-NLS-1$

    MockChangesetProperties changesetProperties2 = new MockChangesetProperties("ownerDisplayName4", //$NON-NLS-1$
            "ownerName4", //$NON-NLS-1$
            "committerDisplayName4", //$NON-NLS-1$
            "committerName4", //$NON-NLS-1$
            "comment4", //$NON-NLS-1$
            date);
    mockVersionControlService.updateChangesetInformation(changesetProperties2, 4);

    mockVersionControlService.AddFile("$/project/folder/file1.txt", 5); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file1.txt", 5); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file1.txt", 5); //$NON-NLS-1$

    MockChangesetProperties changesetProperties3 = new MockChangesetProperties("ownerDisplayName5", //$NON-NLS-1$
            "ownerName5", //$NON-NLS-1$
            "committerDisplayName5", //$NON-NLS-1$
            "committerName5", //$NON-NLS-1$
            "comment5", //$NON-NLS-1$
            date);
    mockVersionControlService.updateChangesetInformation(changesetProperties3, 5);

    FetchTask fetchTask = new FetchTask(repository, mockVersionControlService);
    fetchTask.setDeep(true);
    TaskStatus fetchTaskStatus = fetchTask.run(new NullTaskProgressMonitor());

    // Verify task completed without errors
    assertTrue(fetchTaskStatus.isOK());

    // Retrieve commits
    Ref fetchHeadRef = repository.getRef(Constants.FETCH_HEAD);
    Ref headRef = repository.getRef(Constants.HEAD);

    assertNotNull(fetchHeadRef);
    assertNotNull(headRef);

    ObjectId fetchHeadCommitID = fetchHeadRef.getObjectId();
    ObjectId headCommitID = headRef.getObjectId();

    RevWalk revWalk = new RevWalk(repository);
    RevCommit fetchedCommit = revWalk.parseCommit(fetchHeadCommitID);
    RevCommit headCommit = revWalk.parseCommit(headCommitID);

    assertEquals(fetchedCommit.getParentCount(), 1);

    RevCommit intermediateCommit = revWalk.parseCommit(fetchedCommit.getParent(0).getId());

    // Verify intermediateCommit
    assertEquals(intermediateCommit.getFullMessage(), "comment4"); //$NON-NLS-1$

    PersonIdent ownwer = intermediateCommit.getAuthorIdent();
    assertEquals(ownwer.getEmailAddress(), "ownerName4"); //$NON-NLS-1$
    assertEquals(ownwer.getName(), "ownerDisplayName4"); //$NON-NLS-1$

    PersonIdent committer = intermediateCommit.getCommitterIdent();
    assertEquals(committer.getEmailAddress(), "committerName4"); //$NON-NLS-1$
    assertEquals(committer.getName(), "committerDisplayName4"); //$NON-NLS-1$

    // Verify fetch_head commit
    assertEquals(fetchedCommit.getFullMessage(), "comment5"); //$NON-NLS-1$

    ownwer = fetchedCommit.getAuthorIdent();
    assertEquals(ownwer.getEmailAddress(), "ownerName5"); //$NON-NLS-1$
    assertEquals(ownwer.getName(), "ownerDisplayName5"); //$NON-NLS-1$

    committer = fetchedCommit.getCommitterIdent();
    assertEquals(committer.getEmailAddress(), "committerName5"); //$NON-NLS-1$
    assertEquals(committer.getName(), "committerDisplayName5"); //$NON-NLS-1$

    // Verify the file content
    TreeWalk treeWalk = new TreeWalk(repository);
    treeWalk.setRecursive(true);

    treeWalk.addTree(headCommit.getTree());
    treeWalk.addTree(intermediateCommit.getTree());

    treeWalk.setFilter(TreeFilter.ANY_DIFF);

    int count = 0;
    while (treeWalk.next()) {
        ObjectId fileObjectId = treeWalk.getObjectId(1);
        byte[] fileContent = repository.getObjectDatabase().open(fileObjectId, OBJ_BLOB).getBytes();

        switch (count) {
        case 0:
            assertTrue(mockVersionControlService.verifyFileContent(fileContent, "$/project/folder/file1.txt", //$NON-NLS-1$
                    4));
            break;
        case 2:
            assertTrue(mockVersionControlService.verifyFileContent(fileContent, "$/project/folder2/file1.txt", //$NON-NLS-1$
                    4));
            break;
        case 1:
            assertTrue(mockVersionControlService.verifyFileContent(fileContent,
                    "$/project/folder/nestedFolder/file1.txt", //$NON-NLS-1$
                    4));
            break;
        }

        count++;
    }

    treeWalk.reset();
    treeWalk.setRecursive(true);

    treeWalk.addTree(headCommit.getTree());
    treeWalk.addTree(fetchedCommit.getTree());

    treeWalk.setFilter(TreeFilter.ANY_DIFF);

    count = 0;
    while (treeWalk.next()) {
        ObjectId fileObjectId = treeWalk.getObjectId(1);
        byte[] fileContent = repository.getObjectDatabase().open(fileObjectId, OBJ_BLOB).getBytes();

        switch (count) {
        case 0:
            assertTrue(mockVersionControlService.verifyFileContent(fileContent, "$/project/folder/file1.txt", //$NON-NLS-1$
                    5));
            break;
        case 2:
            assertTrue(mockVersionControlService.verifyFileContent(fileContent, "$/project/folder2/file1.txt", //$NON-NLS-1$
                    5));
            break;
        case 1:
            assertTrue(mockVersionControlService.verifyFileContent(fileContent,
                    "$/project/folder/nestedFolder/file1.txt", //$NON-NLS-1$
                    5));
            break;
        }

        count++;
    }

    Git git = new Git(repository);

    // Verify the tags
    List<Ref> tags = git.tagList().call();
    assertEquals(3, tags.size());
}

From source file:org.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public void fetch(FetchRequest request) throws GitException, UnauthorizedException {
    String remoteName = request.getRemote();
    String remoteUri;//from w  ww  . j  ava  2s  .c o m
    try {
        List<RefSpec> fetchRefSpecs;
        List<String> refSpec = request.getRefSpec();
        if (!refSpec.isEmpty()) {
            fetchRefSpecs = new ArrayList<>(refSpec.size());
            for (String refSpecItem : refSpec) {
                RefSpec fetchRefSpec = (refSpecItem.indexOf(':') < 0) //
                        ? new RefSpec(Constants.R_HEADS + refSpecItem + ":") //
                        : new RefSpec(refSpecItem);
                fetchRefSpecs.add(fetchRefSpec);
            }
        } else {
            fetchRefSpecs = Collections.emptyList();
        }

        FetchCommand fetchCommand = getGit().fetch();

        // If this an unknown remote with no refspecs given, put HEAD
        // (otherwise JGit fails)
        if (remoteName != null && refSpec.isEmpty()) {
            boolean found = false;
            List<Remote> configRemotes = remoteList(newDto(RemoteListRequest.class));
            for (Remote configRemote : configRemotes) {
                if (remoteName.equals(configRemote.getName())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                fetchRefSpecs = Collections
                        .singletonList(new RefSpec(Constants.HEAD + ":" + Constants.FETCH_HEAD));
            }
        }

        if (remoteName == null) {
            remoteName = Constants.DEFAULT_REMOTE_NAME;
        }
        fetchCommand.setRemote(remoteName);
        remoteUri = getRepository().getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName,
                ConfigConstants.CONFIG_KEY_URL);
        fetchCommand.setRefSpecs(fetchRefSpecs);

        int timeout = request.getTimeout();
        if (timeout > 0) {
            fetchCommand.setTimeout(timeout);
        }
        fetchCommand.setRemoveDeletedRefs(request.isRemoveDeletedRefs());

        executeRemoteCommand(remoteUri, fetchCommand);
    } catch (GitException | GitAPIException exception) {
        String errorMessage;
        if (exception.getMessage().contains("Invalid remote: ")) {
            errorMessage = ERROR_NO_REMOTE_REPOSITORY;
        } else if ("Nothing to fetch.".equals(exception.getMessage())) {
            return;
        } else {
            errorMessage = exception.getMessage();
        }
        throw new GitException(errorMessage, exception);
    }
}

From source file:org.eclipse.egit.ui.internal.fetch.FetchGerritChangePage.java

License:Open Source License

boolean doFetch() {
    try {//www . ja v  a 2  s. co  m
        final RefSpec spec = new RefSpec().setSource(refText.getText()).setDestination(Constants.FETCH_HEAD);
        final String uri = uriCombo.getText();
        final boolean doCheckout = checkout.getSelection();
        final boolean doCreateTag = createTag.getSelection();
        final boolean doCreateBranch = createBranch.getSelection();
        final boolean doActivateAdditionalRefs = (checkout.getSelection() || dontCheckout.getSelection())
                && activateAdditionalRefs.getSelection();
        final String textForTag = tagText.getText();
        final String textForBranch = branchText.getText();

        getWizard().getContainer().run(true, true, new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                int totalWork = 1;
                if (doCheckout)
                    totalWork++;
                if (doCreateTag || doCreateBranch)
                    totalWork++;
                monitor.beginTask(UIText.FetchGerritChangePage_GetChangeTaskName, totalWork);

                try {
                    RevCommit commit = fetchChange(uri, spec, monitor);

                    if (doCreateTag) {
                        createTag(spec, textForTag, commit, monitor);
                    }
                    if (doCreateBranch) {
                        createBranch(textForBranch, commit, monitor);
                    }
                    if (doCheckout || doCreateTag) {
                        checkout(commit, monitor);
                    }
                    if (doActivateAdditionalRefs) {
                        activateAdditionalRefs();
                    }
                    storeLastUsedUri(uri);
                } catch (RuntimeException e) {
                    throw e;
                } catch (Exception e) {
                    throw new InvocationTargetException(e);
                } finally {
                    monitor.done();
                }
            }
        });
    } catch (InvocationTargetException e) {
        Activator.handleError(e.getCause().getMessage(), e.getCause(), true);
        return false;
    } catch (InterruptedException e) {
        // just return
    }
    return true;
}

From source file:org.eclipse.egit.ui.internal.GitLabels.java

License:Open Source License

/**
 * @param ref/* w  ww.  j a v  a  2 s .  c  o  m*/
 * @return a description of the ref, or null if the ref does not have a
 *         description
 */
public static String getRefDescription(Ref ref) {
    String name = ref.getName();
    if (name.equals(Constants.HEAD)) {
        if (ref.isSymbolic())
            return UIText.GitLabelProvider_RefDescriptionHeadSymbolic;
        else
            return UIText.GitLabelProvider_RefDescriptionHead;
    } else if (name.equals(Constants.ORIG_HEAD))
        return UIText.GitLabelProvider_RefDescriptionOrigHead;
    else if (name.equals(Constants.FETCH_HEAD))
        return UIText.GitLabelProvider_RefDescriptionFetchHead;
    else if (name.equals(Constants.R_STASH))
        return UIText.GitLabelProvider_RefDescriptionStash;
    else
        return null;
}

From source file:org.jenkinsci.git.FetchOperation.java

License:Open Source License

public RevCommit call() throws IOException {
    FetchCommand fetch = Git.wrap(gitRepo).fetch();
    fetch.setRemote(repo.getUri());//from w w  w . ja v  a 2 s .co  m
    fetch.setRefSpecs(new RefSpec(repo.getBranch()));
    if (monitor != null)
        fetch.setProgressMonitor(monitor);
    try {
        fetch.call();
        return CommitUtils.getRef(gitRepo, Constants.FETCH_HEAD);
    } catch (GitException e) {
        throw new IOException(e);
    } catch (JGitInternalException e) {
        throw new IOException(e);
    } catch (InvalidRemoteException e) {
        throw new IOException(e);
    }
}

From source file:uk.ac.cam.UROP.twentyfourteen.database.GitDb.java

/**
 * Retrieve the SHA that is at the head of the repository (based on all
 * fetched commits)//w w  w. j a va  2 s. com
 *
 * @return String of sha id
 */
public String getHeadSha() {
    String result = null;

    try {
        ObjectId fetchHead = gitHandle.getRepository().resolve(Constants.FETCH_HEAD);
        if (null != fetchHead) {
            result = fetchHead.getName();
        } else {
            log.warn("Problem fetching head from remote. Providing local head instead.");
            result = gitHandle.getRepository().resolve(Constants.HEAD).getName();
        }

    } catch (RevisionSyntaxException | IOException e) {
        e.printStackTrace();
        log.error("Error getting the head from the repository.");
    }
    return result;
}