git4idea.repo.GitRemote Java Examples

The following examples show how to use git4idea.repo.GitRemote. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GitTagsPusher.java    From GitToolBox with Apache License 2.0 6 votes vote down vote up
@NotNull
public GtPushResult push(@NotNull TagsPushSpec pushSpec) {
  Preconditions.checkNotNull(pushSpec);
  GitRepository repository = GitUtil.getRepositoryManager(project).getRepositoryForRoot(pushSpec.gitRoot());
  if (repository == null) {
    return GtPushResult.error("Path " + pushSpec.gitRoot().getPath() + " is not a Git root");
  }
  Optional<GitBranchTrackInfo> trackInfo = Optional.ofNullable(GitUtil.getTrackInfoForCurrentBranch(repository));
  if (trackInfo.isPresent()) {
    GitRemote remote = trackInfo.get().getRemote();
    Optional<String> url = Optional.ofNullable(remote.getFirstUrl());
    if (url.isPresent()) {
      return push(pushSpec, repository, remote, url.get());
    } else {
      return GtPushResult.error(ResBundle.message("message.no.remote.url", remote.getName()));
    }
  } else {
    return GtPushResult.error(ResBundle.message("message.cannot.push.without.tracking"));
  }
}
 
Example #2
Source File: CreatePullRequestModelTest.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
@Before
public void setUp() {
    projectMock = Mockito.mock(Project.class);
    gitRepositoryMock = Mockito.mock(GitRepository.class);
    diffProviderMock = Mockito.mock(DiffCompareInfoProvider.class);
    observerMock = Mockito.mock(Observer.class);
    applicationProviderMock = Mockito.mock(CreatePullRequestModel.ApplicationProvider.class);
    currentBranch = PRGitObjectMockHelper.createLocalBranch("local");

    tfsRemote = new GitRemote("origin", Collections.singletonList("https://mytest.visualstudio.com/DefaultCollection/_git/testrepo"),
            Collections.singletonList("https://pushurl"), Collections.emptyList(), Collections.emptyList());

    when(diffProviderMock.getEmptyDiff(gitRepositoryMock)).thenCallRealMethod();
    when(gitRepositoryMock.getRemotes()).thenReturn(Collections.singletonList(tfsRemote));

    mockGitRepoBranches(currentBranch);
}
 
Example #3
Source File: TfGitHttpAuthDataProviderTest.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
@Test
public void testAuthDataWithTwoRemotesDifferentOrganizations() {
    GitRemote gitRemote1 = Mockito.mock(GitRemote.class);
    when(gitRemote1.getFirstUrl()).thenReturn("https://dev.azure.com/username1/myproject1/_git/myproject1");

    GitRemote gitRemote2 = Mockito.mock(GitRemote.class);
    when(gitRemote2.getFirstUrl()).thenReturn("https://dev.azure.com/username2/myproject2/_git/myproject2");

    when(TfGitHelper.getTfGitRemotes(any(Project.class))).thenReturn(Arrays.asList(gitRemote1, gitRemote2));

    AuthData result = authDataProvider.getAuthData(project, "https://dev.azure.com");

    assertNull(result);

    verifyStatic();
    AzureDevOpsNotifications.showManageRemoteUrlsNotification(
            project,
            "dev.azure.com");
}
 
Example #4
Source File: OpenCommitInBrowserAction.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull final AnActionEvent anActionEvent) {
    final Project project = anActionEvent.getRequiredData(CommonDataKeys.PROJECT);
    final VcsFullCommitDetails commit = anActionEvent.getRequiredData(VcsLogDataKeys.VCS_LOG).getSelectedDetails().get(0);

    final GitRepository gitRepository = GitUtil.getRepositoryManager(project).getRepositoryForRootQuick(commit.getRoot());
    if (gitRepository == null)
        return;

    final GitRemote remote = TfGitHelper.getTfGitRemote(gitRepository);

    // guard for null so findbugs doesn't complain
    if (remote == null) {
        return;
    }

    final String remoteUrl = remote.getFirstUrl();
    if (remoteUrl == null) {
        return;
    }

    final URI urlToBrowseTo = UrlHelper.getCommitURI(remoteUrl, commit.getId().toString());
    logger.info("Browsing to url " + urlToBrowseTo.getPath());
    BrowserUtil.browse(urlToBrowseTo);
}
 
Example #5
Source File: CreatePullRequestModelTest.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
@Test
public void targetDropDownOnlyShowsTfRemoteBranches() {
    GitRemoteBranch first = PRGitObjectMockHelper.createRemoteBranch("origin/test1", tfsRemote);
    GitRemoteBranch second = PRGitObjectMockHelper.createRemoteBranch("origin/test2", tfsRemote);
    GitRemoteBranch master = PRGitObjectMockHelper.createRemoteBranch("origin/master", tfsRemote);

    // two remotes, non tfs repo should be filtered out
    GitRemote nonTfsRemote = new GitRemote("origin", Collections.singletonList("https://mytest.notvso.com/git/testrepo"),
            Collections.singletonList("https://pushurl"), Collections.emptyList(), Collections.emptyList());

    when(gitRepositoryMock.getRemotes()).thenReturn(Arrays.asList(tfsRemote, nonTfsRemote));
    GitRemoteBranch nonTfsMaster = PRGitObjectMockHelper.createRemoteBranch("other/master", nonTfsRemote);
    mockGitRepoBranches(currentBranch, first, second, master, nonTfsMaster);
    underTest = new CreatePullRequestModel(projectMock, gitRepositoryMock);

    // nonTfsMaster should be filtered out
    assertEquals(3, underTest.getRemoteBranchDropdownModel().getSize());
    for (int i = 0; i < underTest.getRemoteBranchDropdownModel().getSize(); ++i) {
        assertNotEquals(nonTfsMaster, underTest.getRemoteBranchDropdownModel().getElementAt(i));
    }
}
 
Example #6
Source File: GitTagsPusher.java    From GitToolBox with Apache License 2.0 6 votes vote down vote up
private GtPushResult push(final TagsPushSpec pushSpec, final GitRepository repository,
                          final GitRemote remote, final String url) {
  final GitLineHandlerListener progressListener = GitStandardProgressAnalyzer.createListener(progressIndicator);
  final GitPushRejectedDetector rejectedDetector = new GitPushRejectedDetector();
  GitCommandResult result = Git.getInstance().runCommand(() -> {
    final GitLineHandler h = new GitLineHandler(repository.getProject(), repository.getRoot(),
        GitCommand.PUSH);
    h.setUrl(url);
    h.setSilent(false);
    h.setStdoutSuppressed(false);
    h.addLineListener(progressListener);
    h.addLineListener(rejectedDetector);
    h.addParameters("--progress");
    h.addParameters(remote.getName());
    h.addParameters(pushSpec.specs());
    return h;
  });
  if (rejectedDetector.rejected()) {
    return GtPushResult.reject(rejectedDetector.getRejectedBranches());
  } else {
    return translate(result);
  }
}
 
Example #7
Source File: TfGitHelper.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
/**
 * This method for now assumes the default branch name is master
 * <p/>
 * If there is no master, return the first branch on the list or null for empty list
 * <p/>
 * We should get the default branch from TF if necessary, but that's a server call
 */
@Nullable
public static GitRemoteBranch getDefaultBranch(@NotNull final List<GitRemoteBranch> remoteBranches, @NotNull final Collection<GitRemote> tfGitRemotes) {
    if (remoteBranches.isEmpty() || tfGitRemotes.isEmpty()) {
        return null;
    }

    final GitRemote firstTfRemote = tfGitRemotes.iterator().next();

    final String masterBranchName = String.format(MASTER_BRANCH_PATTERN, firstTfRemote.getName());
    for (GitRemoteBranch remoteBranch : remoteBranches) {
        if (remoteBranch.getName().equals(masterBranchName)) {
            return remoteBranch;
        }
    }

    return remoteBranches.get(0);
}
 
Example #8
Source File: TfGitHelper.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
private static boolean isTfGitRemote(final GitRemote gitRemote) {
    if (gitRemote == null) {
        return false;
    }

    final String remoteUrl = gitRemote.getFirstUrl();
    if (remoteUrl != null
        && (remoteUrl.contains(".visualstudio.com/")
            || remoteUrl.contains(".azure.com/")
            || remoteUrl.contains(".tfsallin.net/")
            || remoteUrl.contains(".vsallin.net/")
            || remoteUrl.contains(".vsts.io/")
            || remoteUrl.contains(".vsts.me/")
            || remoteUrl.contains("codeapp.ms/")
            || remoteUrl.contains("codedev.ms/")
            || remoteUrl.contains("/_git/"))) {
        // TODO: once we have the connections cached, we should rework this to also query those for better OnPrem detection.
        return true;
    }
    return false;
}
 
Example #9
Source File: TfGitHelper.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
public static GitRemote getTfGitRemote(@NotNull final GitRepository gitRepository) {
    if (gitRepository == null) {
        throw new IllegalArgumentException();
    }
    GitRemote first = null;
    for (GitRemote gitRemote : gitRepository.getRemotes()) {
        if (isTfGitRemote(gitRemote)) {
            if (gitRemote.getName().equals("origin")) {
                return gitRemote;
            } else if (first == null) {
                first = gitRemote;
            }
        }
    }
    return first;
}
 
Example #10
Source File: GitlabUrlUtil.java    From IDEA-GitLab-Integration with MIT License 5 votes vote down vote up
@Nullable
public static String findRemoteUrl(@NotNull GitRepository repository) {
    List<String> remotes = new ArrayList<String>();
    for (GitRemote remote : repository.getRemotes()) {
        if (remote.getName().equals("origin")) {
            return remote.getFirstUrl();
        }
    }
    return null;
}
 
Example #11
Source File: CreatePullRequestModel.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
private ListenableFuture<Pair<String, GitCommandResult>> doPushCommits(@NotNull final GitRepository gitRepository,
                                                                       @NotNull final GitLocalBranch localBranch,
                                                                       @NotNull final GitRemote gitRemote,
                                                                       @NotNull final ProgressIndicator indicator) {
    // just set the result without going off to another thread, we should already be in a background task
    SettableFuture<Pair<String, GitCommandResult>> pushResult
            = SettableFuture.<Pair<String, GitCommandResult>>create();

    indicator.setText(TfPluginBundle.message(TfPluginBundle.KEY_CREATE_PR_PUSH_TITLE));
    final Git git = ServiceManager.getService(Git.class);

    final GitRemoteBranch trackingBranch = localBranch.findTrackedBranch(gitRepository);

    final String createdBranchNameOnServer;
    final StringBuilder pushSpec = new StringBuilder(localBranch.getName());
    if (trackingBranch != null && trackingBranch.getRemote().equals(gitRemote)) {
        // if the tracking branch is on the same remote, we should update that
        pushSpec.append(":").append(trackingBranch.getNameForRemoteOperations());
        createdBranchNameOnServer = trackingBranch.getNameForRemoteOperations();
    } else {
        createdBranchNameOnServer = localBranch.getName();
    }

    final String fetchUrl = getFetchUrl(gitRemote);
    final String pushSpecStr = pushSpec.toString();
    final String gitRemoteName = gitRemote.getName();
    logger.debug("Pushing {} to {}: {}", pushSpecStr, gitRemoteName, fetchUrl);
    final GitCommandResult result
            = git.push(gitRepository, gitRemoteName, fetchUrl, pushSpecStr, true);

    if (result.success()) {
        pushResult.set(Pair.create(createdBranchNameOnServer, result));
    } else {
        final String errMsg = result.getErrorOutputAsJoinedString();
        pushResult.setException(new GitExecutionException(errMsg, null));
    }

    return pushResult;
}
 
Example #12
Source File: CreateBranchModelTest.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
private static void mockRemoteBranch(GitRemoteBranch branch, GitRemote remote, String shortBranchName) {
    String remoteName = remote.getName();
    String branchName = remoteName + "/" + shortBranchName;
    String fullBranchName = "refs/remotes/" + branchName;
    when(branch.getRemote()).thenReturn(remote);
    when(branch.getName()).thenReturn(branchName);
    when(branch.getFullName()).thenReturn(fullBranchName);
}
 
Example #13
Source File: TfGitHelper.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
public static String getTfGitRemoteUrl(@NotNull final GitRepository gitRepository) {
    final GitRemote gitRemote = getTfGitRemote(gitRepository);
    if (gitRemote != null) {
        return gitRemote.getFirstUrl();
    }
    return null;
}
 
Example #14
Source File: OpenFileInBrowserAction.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
@Override
public void actionPerformed(final AnActionEvent anActionEvent) {
    final Project project = anActionEvent.getRequiredData(CommonDataKeys.PROJECT);
    final VirtualFile virtualFile = anActionEvent.getRequiredData(CommonDataKeys.VIRTUAL_FILE);

    final GitRepositoryManager manager = GitUtil.getRepositoryManager(project);
    final GitRepository gitRepository = manager.getRepositoryForFileQuick(virtualFile);
    if (gitRepository == null)
        return;

    final GitRemote gitRemote = TfGitHelper.getTfGitRemote(gitRepository);

    // guard for null so findbugs doesn't complain
    if (gitRemote == null || gitRepository.getRoot() == null) {
        return;
    }

    final String rootPath = gitRepository.getRoot().getPath();
    final String path = virtualFile.getPath();
    final String relativePath = path.substring(rootPath.length());

    String gitRemoteBranchName = StringUtils.EMPTY;
    final GitLocalBranch gitLocalBranch = gitRepository.getCurrentBranch();
    if (gitLocalBranch != null) {
        final GitRemoteBranch gitRemoteBranch = gitLocalBranch.findTrackedBranch(gitRepository);
        if (gitRemoteBranch != null) {
            gitRemoteBranchName = gitRemoteBranch.getNameForRemoteOperations();
        }
    }

    final URI urlToBrowseTo = UrlHelper.getFileURI(gitRemote.getFirstUrl(), encodeVirtualFilePath(relativePath), gitRemoteBranchName);
    logger.info("Browsing to url " + urlToBrowseTo.getPath());
    BrowserUtil.browse(urlToBrowseTo);
}
 
Example #15
Source File: RemoteTest.java    From GitLink with MIT License 5 votes vote down vote up
@Test(expected = RemoteException.class)
public void testDoesThrowWhenRemoteUrlNotFound() throws RemoteException
{
    GitRemote gitRemote = mock(GitRemote.class);

    when(gitRemote.getName()).thenReturn("");
    when(gitRemote.getFirstUrl()).thenReturn(null);

    Remote remote = new Remote(gitRemote);

    remote.url();
}
 
Example #16
Source File: TfGitHttpAuthDataProviderTest.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
@Test
public void testAuthDataWithOneRemote() {
    GitRemote gitRemote = PowerMockito.mock(GitRemote.class);
    when(gitRemote.getFirstUrl()).thenReturn("https://dev.azure.com/username/myproject/_git/myproject");
    when(TfGitHelper.getTfGitRemotes(any(Project.class))).thenReturn(Collections.singleton(gitRemote));

    AuthData result = authDataProvider.getAuthData(project, "https://dev.azure.com");

    assertAuthenticationInfoEquals(authenticationInfo, result);
}
 
Example #17
Source File: TfGitHttpAuthDataProviderTest.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
@Test
public void testAuthDataWithTwoRemotesSameOrganization() {
    GitRemote gitRemote1 = Mockito.mock(GitRemote.class);
    when(gitRemote1.getFirstUrl()).thenReturn("https://dev.azure.com/username/myproject1/_git/myproject1");

    GitRemote gitRemote2 = Mockito.mock(GitRemote.class);
    when(gitRemote2.getFirstUrl()).thenReturn("https://dev.azure.com/username/myproject2/_git/myproject2");

    when(TfGitHelper.getTfGitRemotes(any(Project.class))).thenReturn(Arrays.asList(gitRemote1, gitRemote2));

    AuthData result = authDataProvider.getAuthData(project, "https://dev.azure.com");

    assertAuthenticationInfoEquals(authenticationInfo, result);
}
 
Example #18
Source File: RemoteTest.java    From GitLink with MIT License 5 votes vote down vote up
@Test
@UseDataProvider("urlProvider")
public void testReturnsExpectedUrl(String url, String expected) throws RemoteException
{
    GitRemote gitRemote = mock(GitRemote.class);

    when(gitRemote.getFirstUrl()).thenReturn(url);

    Remote remote = new Remote(gitRemote);

    assertEquals(expected, remote.url().toString());
}
 
Example #19
Source File: PRGitObjectMockHelper.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
public static GitRemoteBranch createRemoteBranch(final String name, final GitRemote remote) {
    GitRemoteBranch branch = mock(GitRemoteBranch.class);
    when(branch.getName()).thenReturn("refs/remotes/" + name);
    when(branch.getFullName()).thenReturn(name);
    when(branch.isRemote()).thenReturn(true);
    when(branch.getRemote()).thenReturn(remote);
    when(branch.getNameForLocalOperations()).thenReturn(name);
    when(branch.getNameForRemoteOperations()).thenReturn(name);
    return branch;
}
 
Example #20
Source File: GitLabOpenInBrowserAction.java    From IDEA-GitLab-Integration with MIT License 5 votes vote down vote up
public RemoteSelectedAction(@NotNull Project project, @NotNull GitRepository repository, @Nullable Editor editor,
                            @NotNull GitRemote remote, @NotNull String rootPath, @NotNull String path) {
    super(remote.getName());
    this.project = project;
    this.repository = repository;
    this.editor = editor;
    this.remote = remote;
    this.rootPath = rootPath;
    this.path = path;
}
 
Example #21
Source File: GitLabOpenInBrowserAction.java    From IDEA-GitLab-Integration with MIT License 4 votes vote down vote up
@Override
public void actionPerformed(final AnActionEvent e) {
    final Project project = e.getData(PlatformDataKeys.PROJECT);
    final VirtualFile virtualFile = e.getData(PlatformDataKeys.VIRTUAL_FILE);
    final Editor editor = e.getData(PlatformDataKeys.EDITOR);
    if (virtualFile == null || project == null || project.isDisposed()) {
        return;
    }

    GitRepositoryManager manager = GitUtil.getRepositoryManager(project);
    final GitRepository repository = manager.getRepositoryForFile(virtualFile);
    if (repository == null) {
        StringBuilder details = new StringBuilder("file: " + virtualFile.getPresentableUrl() + "; Git repositories: ");
        for (GitRepository repo : manager.getRepositories()) {
            details.append(repo.getPresentableUrl()).append("; ");
        }
        showError(project, CANNOT_OPEN_IN_BROWSER, "Can't find git repository", details.toString());
        return;
    }

    final String rootPath = repository.getRoot().getPath();
    final String path = virtualFile.getPath();

    List<AnAction> remoteSelectedActions = new ArrayList<AnAction>();

    for (GitRemote remote : repository.getRemotes()) {
        remoteSelectedActions.add(new RemoteSelectedAction(project, repository, editor, remote, rootPath, path));
    }

    if (remoteSelectedActions.size() > 1) {
        DefaultActionGroup remotesActionGroup = new DefaultActionGroup();
        remotesActionGroup.addAll(remoteSelectedActions);
        DataContext dataContext = e.getDataContext();
        final ListPopup popup = JBPopupFactory.getInstance().createActionGroupPopup(
                        "Select remote",
                        remotesActionGroup,
                        dataContext,
                        JBPopupFactory.ActionSelectionAid.SPEEDSEARCH,
                        true);

        popup.showInBestPositionFor(dataContext);
    } else if (remoteSelectedActions.size() == 1) {
        remoteSelectedActions.get(0).actionPerformed(null);
    } else {
        showError(project, CANNOT_OPEN_IN_BROWSER, "Can't find gitlab remote");
    }
}
 
Example #22
Source File: VcsHelper.java    From azure-devops-intellij with MIT License 4 votes vote down vote up
/**
 * This method creates a RepositoryContext object from the local project context.
 * It works for TF Git or TFVC repositories. Any other type of repo will return null.
 *
 * @param project
 * @return
 */
public static RepositoryContext getRepositoryContext(final Project project) {
    ArgumentHelper.checkNotNull(project, "project");
    try {
        final String projectRootFolder = project.getBasePath();

        // Check the manager first since that's where we cache these things
        //TODO this cache doesn't include the current branch info that could have changed. We should probably only cache stuff for TFVC
        RepositoryContext context = RepositoryContextManager.getInstance().get(projectRootFolder);
        if (context != null) {
            logger.info("getRepositoryContext: cache hit: " + projectRootFolder);
            return context;
        }
        logger.info("getRepositoryContext: cache miss: " + projectRootFolder);

        final ProjectLevelVcsManager projectLevelVcsManager = ProjectLevelVcsManager.getInstance(project);
        // Check for Git, then TFVC
        if (projectLevelVcsManager.checkVcsIsActive(GitVcs.NAME)) {
            // It's Git, so get the repository and remote url to create the context from
            final GitRepository repository = getGitRepository(project);
            if (repository != null && TfGitHelper.isTfGitRepository(repository)) {
                final GitRemote gitRemote = TfGitHelper.getTfGitRemote(repository);
                final String gitRemoteUrl = Objects.requireNonNull(gitRemote.getFirstUrl());
                // TODO: Fix this HACK. There doesn't seem to be a clear way to get the full name of the current branch
                final String branch = GIT_BRANCH_PREFIX + GitBranchUtil.getDisplayableBranchText(repository);
                context = RepositoryContext.createGitContext(projectRootFolder, repository.getRoot().getName(), branch, URI.create(gitRemoteUrl));
            }
        } else if (projectLevelVcsManager.checkVcsIsActive(TFSVcs.TFVC_NAME)) {
            final Workspace workspace = CommandUtils.getPartialWorkspace(project, false);
            if (workspace != null) {
                final String projectName = getTeamProjectFromTfvcServerPath(
                        workspace.getMappings().size() > 0 ? workspace.getMappings().get(0).getServerPath() : null);
                context = RepositoryContext.createTfvcContext(projectRootFolder, workspace.getName(), projectName, workspace.getServerUri());
            }
        }

        if (context != null) {
            RepositoryContextManager.getInstance().add(context);
            return context;
        }
    } catch (Throwable t) {
        // Don't let errors bubble out here, just return null if something goes wrong
        logger.warn("Unable to get repository context for the project.", t);
    }

    logger.info("getRepositoryContext: We couldn't determine the VCS provider, so returning null.");
    return null;
}
 
Example #23
Source File: StatusBarManagerTest.java    From azure-devops-intellij with MIT License 4 votes vote down vote up
@Before
public void setupLocalTests() {
    MockitoAnnotations.initMocks(this);
    buildStatusLookupOperation = new MyBuildStatusLookupOperation();

    PowerMockito.mockStatic(WindowManager.class);
    when(WindowManager.getInstance()).thenReturn(windowManager);
    when(windowManager.getStatusBar(any(Project.class))).thenReturn(statusBar);
    when(statusBar.getWidget(anyString()))
            .thenReturn(null) // First time return null
            .thenReturn(new BuildWidget()); // All other calls should return something other than null
    doNothing().when(statusBar).addWidget(any(StatusBarWidget.class));
    doNothing().when(statusBar).updateWidget(anyString());

    PowerMockito.mockStatic(ProjectManager.class);
    when(ProjectManager.getInstance()).thenReturn(projectManager);
    when(projectManager.getOpenProjects()).thenReturn(new Project[]{project});

    PowerMockito.mockStatic(VcsHelper.class);
    when(VcsHelper.getRepositoryContext(any(Project.class)))
            .thenReturn(
                    RepositoryContext.createGitContext(
                            "/root/one",
                            "repo1",
                            "branch1",
                            URI.create("http://repoUrl1")));

    PowerMockito.mockStatic(GitBranchUtil.class);
    when(GitBranchUtil.getCurrentRepository(any(Project.class))).thenReturn(gitRepository);
    when(GitBranchUtil.getDisplayableBranchText(any(GitRepository.class))).thenReturn("branch");

    when(applicationNamesInfo.getProductName()).thenReturn("IDEA");
    PowerMockito.mockStatic(ApplicationNamesInfo.class);
    when(ApplicationNamesInfo.getInstance()).thenReturn(applicationNamesInfo);

    when(gitRepository.getRemotes()).thenReturn(Collections.singletonList(
            new GitRemote("origin", Collections.singletonList("https://test.visualstudio.com/"),
                    Collections.singletonList("https://test.visualstudio.com/"),
                    Collections.singletonList("https://test.visualstudio.com/"),
                    Collections.singletonList("https://test.visualstudio.com/"))));

    PowerMockito.mockStatic(OperationFactory.class);
    when(OperationFactory.createBuildStatusLookupOperation(any(RepositoryContext.class), anyBoolean())).thenReturn(buildStatusLookupOperation);
}
 
Example #24
Source File: Remote.java    From GitLink with MIT License 4 votes vote down vote up
public Remote(@NotNull final GitRemote remote) {
    this.remote = remote;
}
 
Example #25
Source File: CreatePullRequestModel.java    From azure-devops-intellij with MIT License 4 votes vote down vote up
private String getFetchUrl(@NotNull final GitRemote gitRemote) {
    return gitRemote.getFirstUrl();
}
 
Example #26
Source File: ImportPageModelImpl.java    From azure-devops-intellij with MIT License 4 votes vote down vote up
private boolean setupRemoteOnLocalRepo(final Project project, final GitRepository localRepository,
                                       final com.microsoft.alm.sourcecontrol.webapi.model.GitRepository remoteRepository,
                                       final ServerContext localContext, final ProgressIndicator indicator) {
    //get remotes on local repository
    indicator.setText(TfPluginBundle.message(TfPluginBundle.KEY_IMPORT_GIT_REMOTE));
    final Collection<GitRemote> gitRemotes = localRepository.getRemotes();
    final List<String> remoteParams = new ArrayList<String>();

    if (!gitRemotes.isEmpty()) {
        for (GitRemote remote : gitRemotes) {
            if (StringUtils.equalsIgnoreCase(remote.getName(), REMOTE_ORIGIN)) {
                //remote named origin exits, ask user if they want to overwrite it and proceed or cancel
                IdeaHelper.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        final boolean replaceOrigin = IdeaHelper.showConfirmationDialog(project,
                                TfPluginBundle.message(TfPluginBundle.KEY_IMPORT_ORIGIN_EXISTS),
                                TfPluginBundle.message(TfPluginBundle.KEY_IMPORT_DIALOG_TITLE),
                                Icons.VSLogoSmall,
                                TfPluginBundle.message(TfPluginBundle.KEY_IMPORT_UPDATE_ORIGIN),
                                TfPluginBundle.message(TfPluginBundle.KEY_IMPORT_CANCEL));
                        if (replaceOrigin) {
                            remoteParams.add("set-url");
                        }
                    }
                }, true, indicator.getModalityState());
                if (remoteParams.size() == 0) {
                    //user chose to cancel import
                    logger.warn("setupRemoteOnLocalRepo: User chose to cancel import for project: {}, local repo: {}",
                            project.getName(), localRepository.getGitDir().getUrl());
                    notifyImportError(project, TfPluginBundle.message(TfPluginBundle.KEY_IMPORT_CANCELED));
                    return false;
                }
                break;
            }
        }
    }

    final String remoteGitUrl = UrlHelper.getCmdLineFriendlyUrl(remoteRepository.getRemoteUrl());
    //update remotes on local repository
    final GitSimpleHandler hRemote = new GitSimpleHandler(project, localRepository.getRoot(), GitCommand.REMOTE);
    hRemote.setSilent(true);
    if (remoteParams.size() == 1) {
        hRemote.addParameters(remoteParams.get(0), REMOTE_ORIGIN, remoteGitUrl);
    } else {
        hRemote.addParameters("add", REMOTE_ORIGIN, remoteGitUrl);
    }

    GitHandlerUtil.runInCurrentThread(hRemote, null, true, TfPluginBundle.message(TfPluginBundle.KEY_IMPORT_GIT_REMOTE));
    if (hRemote.getExitCode() != 0) {
        logger.error("setupRemoteOnLocalRepo: git remote failed for project: {}, local repo: {}, error: {}, output: {}",
                project.getName(), localRepository.getRoot().getUrl(), hRemote.getStderr(), hRemote.getStdout());
        notifyImportError(project,
                TfPluginBundle.message(TfPluginBundle.KEY_IMPORT_GIT_REMOTE_ERROR, remoteGitUrl, hRemote.getStderr()));
        return false;
    }
    return true;
}
 
Example #27
Source File: TfGitHttpAuthDataProvider.java    From azure-devops-intellij with MIT License 4 votes vote down vote up
@Nullable
@Override
public AuthData getAuthData(@NotNull Project project, @NotNull String url) {
    logger.info("getAuthData: processing URL {}", url);

    URI remoteUri = URI.create(url);
    String host = remoteUri.getHost();
    if (UrlHelper.isOrganizationHost(host)) {
        logger.info("getAuthData: is Azure DevOps host: {}", host);

        // For azure.com hosts (mainly for dev.azure.com), we need to check if the organization name could be
        // determined from the URL passed from Git. Sometimes, when using the Git repositories created in Visual
        // Studio, the organization name may be omitted from the authority part.
        //
        // Usually, a proper Git remote URL for dev.azure.com looks like this:
        // https://{organization}@dev.azure.com/{organization}/{repo}/_git/{repo}
        //
        // The reason for that is simple: when authenticating the user, Git will only pass the authority part (i.e.
        // https://{organization}@dev.azure.com) to the askpass program (and IDEA implements the askpass protocol
        // for Git), so, without the "{organization}@" part in the URL authority, it would be impossible to know in
        // which organization we should authenticate.
        //
        // If we're in the situation when we use dev.azure.com and the organization name is unknown from the
        // authority part of the URL, we may guess the organization by analyzing the Git remotes in the current
        // project.
        if (!Strings.isNullOrEmpty(remoteUri.getUserInfo())) {
            logger.info("getAuthData: URL has authentication info");
            return getAuthData(url);
        }

        Collection<GitRemote> remotes = TfGitHelper.getTfGitRemotes(project);
        List<String> organizationsFromRemotes = remotes.stream()
                .map(GitRemote::getFirstUrl)
                .filter(Objects::nonNull)
                .map(URI::create)
                .filter(uri -> host.equals(uri.getHost()))
                .map(UrlHelper::getAccountFromOrganizationUri)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
        if (organizationsFromRemotes.size() == 0) {
            logger.info("getAuthData: no Azure DevOps organizations detected");
            return null; // we cannot authenticate without knowing the organization
        }

        if (organizationsFromRemotes.size() > 1) {
            // If there's more that one Azure-like Git remote, then we have no information on which remote to use,
            // so we only could fail with notification.
            logger.info("getAuthData: more than one Azure DevOps organizations detected: {}", organizationsFromRemotes);
            AzureDevOpsNotifications.showManageRemoteUrlsNotification(project, host);
            return null;
        }

        String organizationName = organizationsFromRemotes.get(0);

        try {
            url = appendOrganizationInfo(url, organizationName);
        } catch (URISyntaxException e) {
            logger.warn("Error when parsing URL \"" + url + "\"", e);
        }
    }

    return getAuthData(url);
}
 
Example #28
Source File: TfGitHelper.java    From azure-devops-intellij with MIT License 4 votes vote down vote up
/**
 * This method gets the TFGit remote name for the GitRemote and then forms the remote branch name
 * @param branchName the local branch name without any prefix (refs/heads/)
 * @return returns the remote branch name like origin/branchName
 */
public static String getRemoteBranchName(GitRemote remote, String branchName) {
    ArgumentHelper.checkNotNull(remote, "remote");
    ArgumentHelper.checkNotEmptyString(branchName, "branchName");
    return remote.getName() + "/" + branchName;
}
 
Example #29
Source File: TfGitHelper.java    From azure-devops-intellij with MIT License 4 votes vote down vote up
public static Collection<GitRemote> getTfGitRemotes(@NotNull final GitRepository gitRepository) {
    assert gitRepository != null;
    Collection<GitRemote> gitRemotes = gitRepository.getRemotes();

    return Collections2.filter(gitRemotes, TfGitHelper::isTfGitRemote);
}
 
Example #30
Source File: TfGitHelper.java    From azure-devops-intellij with MIT License 4 votes vote down vote up
@NotNull
public static Collection<GitRemote> getTfGitRemotes(@NotNull Project project) {
    List<GitRepository> repositories = GitUtil.getRepositoryManager(project).getRepositories();
    return repositories.stream().flatMap(r -> getTfGitRemotes(r).stream()).collect(Collectors.toList());
}