git4idea.repo.GitRepository Java Examples

The following examples show how to use git4idea.repo.GitRepository. 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: InfoCacheGateway.java    From GitToolBox with Apache License 2.0 6 votes vote down vote up
private RepoStatusRemote createRemoteStatus(@NotNull GitRepository repository, @NotNull GitLocalBranch localBranch) {
  GitToolBoxConfigPrj config = ProjectConfig.get(project);
  GitRemoteBranch trackedBranch = localBranch.findTrackedBranch(repository);
  GitRemoteBranch parentBranch = null;
  GitRepoInfo repoInfo = repository.getInfo();
  ReferencePointForStatusType type = config.getReferencePointForStatus().getType();
  if (type == ReferencePointForStatusType.TRACKED_REMOTE_BRANCH) {
    parentBranch = trackedBranch;
  } else if (type == ReferencePointForStatusType.SELECTED_PARENT_BRANCH) {
    parentBranch = findRemoteParent(repository, config.getReferencePointForStatus().getName()).orElse(null);
  } else if (type == ReferencePointForStatusType.AUTOMATIC) {
    parentBranch = getRemoteBranchFromActiveTask(repository).orElse(trackedBranch);
  }

  Hash parentHash = repoInfo.getRemoteBranchesWithHashes()
                        .get(parentBranch);
  return new RepoStatusRemote(trackedBranch, parentBranch, parentHash);
}
 
Example #2
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 #3
Source File: CreatePullRequestForm.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
/**
 * This should only be called from the UI thread anyway, adding synchronized keyword
 * just in case
 */
public synchronized void populateDiffPane(@NotNull final Project project,
                                          @NotNull final GitRepository gitRepository,
                                          @NotNull final String sourceBranchBeingCompared,
                                          @NotNull final String targetBranchBeingCompared,
                                          @NotNull final GitCommitCompareInfo myCompareInfo) {
    final GitRemoteBranch gitRemoteBranch = this.getSelectedRemoteBranch();
    final String currBranch = this.sourceBranch.getText();

    if (gitRemoteBranch != null && StringUtils.equals(gitRemoteBranch.getName(), targetBranchBeingCompared)
            && StringUtils.isNotEmpty(currBranch) && StringUtils.equals(currBranch, sourceBranchBeingCompared)) {

        this.quickDiffPane.removeAll();

        JComponent myDiffPanel = createDiffPaneBrowser(project, myCompareInfo);
        this.quickDiffPane.addTab(TfPluginBundle.message(TfPluginBundle.KEY_CREATE_PR_CHANGES_PANE_TITLE),
                AllIcons.Actions.Diff, myDiffPanel);

        JComponent myCommitsPanel = createCommitsListPane(project, gitRepository, myCompareInfo);
        this.quickDiffPane.addTab(TfPluginBundle.message(TfPluginBundle.KEY_CREATE_PR_COMMITS_PANE_TITLE),
                AllIcons.Actions.Commit, myCommitsPanel);
    }
}
 
Example #4
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 #5
Source File: InfoCacheGateway.java    From GitToolBox with Apache License 2.0 6 votes vote down vote up
private Optional<GitRemoteBranch> findRemoteParent(@NotNull GitRepository repository,
                                                   @NotNull String referencePointName) {
  if (referencePointName.contains("/")) {
    Optional<GitRemoteBranch> maybeRemoteBranch = repository.getBranches()
              .getRemoteBranches()
              .stream()
              .filter(remoteBranch -> remoteBranch
                                          .getNameForLocalOperations()
                                          .equals(referencePointName))
              .findFirst();
    return maybeRemoteBranch.isPresent() ? maybeRemoteBranch : findRemoteParentByLocalName(repository,
        referencePointName);
  } else {
    return findRemoteParentByLocalName(repository, referencePointName);
  }
}
 
Example #6
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 #7
Source File: IncrementalBlameCalculator.java    From GitToolBox with Apache License 2.0 6 votes vote down vote up
@Nullable
private RevisionDataProvider annotateImpl(@NotNull GitRepository repository,
                                          @NotNull VirtualFile file,
                                          @NotNull VcsRevisionNumber revision) {
  GitLineHandler handler = prepareLineHandler(repository, file, revision);
  IncrementalBlameBuilder builder = new IncrementalBlameBuilder();
  handler.addLineListener(builder);

  log.debug("Will run blame: ", handler);

  GitCommandResult result = gateway.runCommand(handler);
  if (result.success()) {
    List<CommitInfo> lineInfos = builder.buildLineInfos();
    if (log.isTraceEnabled()) {
      log.trace("Blame for " + file + " is:\n" + dumpBlame(lineInfos));
    }
    return new BlameRevisionDataProvider(lineInfos, file, revision);
  } else if (!result.cancelled()) {
    log.warn("Blame failed:\n" + result.getErrorOutputAsJoinedString());
  }
  return null;
}
 
Example #8
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 #9
Source File: EventContextHelperTest.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
@Test
public void testSetGetRepository() {
    GitRepository repo = Mockito.mock(GitRepository.class);
    // Test the precondition that project is not in the map
    final Map<String, Object> map = EventContextHelper.createContext(null);
    Assert.assertNotNull(map);
    Assert.assertFalse(map.containsKey(EventContextHelper.CONTEXT_REPOSITORY));
    // Add project and make sure it exists
    EventContextHelper.setRepository(map, repo);
    Assert.assertEquals(repo, map.get(EventContextHelper.CONTEXT_REPOSITORY));
    // Make sure that the getRepository method returns the exact same value
    GitRepository repo2 = EventContextHelper.getRepository(map);
    Assert.assertEquals(repo, repo2);
    // Remove project and make sure it is removed
    EventContextHelper.setRepository(map, null);
    Assert.assertFalse(map.containsKey(EventContextHelper.CONTEXT_REPOSITORY));
    // Repeat removal - make sure this doesn't change anything
    EventContextHelper.setRepository(map, null);
    Assert.assertFalse(map.containsKey(EventContextHelper.CONTEXT_REPOSITORY));
}
 
Example #10
Source File: BehindTracker.java    From GitToolBox with Apache License 2.0 6 votes vote down vote up
private void onStateChangeUnsafe(@NotNull GitRepository repository, @NotNull RepoInfo info) {
  RepoInfo previousInfo = state.put(repository, info);
  if (log.isDebugEnabled()) {
    GtRepository repo = gateway.getGtRepository(repository);
    log.debug("Info update [", repo.getName(), "]: ", previousInfo, " > ", info);
  }
  ChangeType changeType = detectChangeType(previousInfo, info);
  if (changeType == ChangeType.FETCHED) {
    BehindStatus status = null;
    if (previousInfo == null) {
      status = calculateBehindStatus(info, count -> BehindStatus.create(count.behind));
    } else if (info.maybeCount().isPresent()) {
      status = calculateBehindStatus(info, count -> calculateBehindStatus(previousInfo, count));
    }
    if (status != null) {
      pendingChanges.put(repository, new PendingChange(status, changeType));
    }
  } else if (changeType != ChangeType.NONE) {
    pendingChanges.remove(repository);
  }
}
 
Example #11
Source File: BehindTracker.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
void showChangeNotification() {
  if (gateway.isNotificationEnabled()) {
    ImmutableMap<GitRepository, PendingChange> changes = drainChanges();
    log.debug("Show notification for ", changes.size(), " repositories");
    showNotification(changes);
  }
}
 
Example #12
Source File: CacheSourcesSubscriber.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
void onDirMappingChanged() {
  log.debug("Dir mappings changed");
  GitRepositoryManager gitManager = GitRepositoryManager.getInstance(project);
  ImmutableList<GitRepository> repositories = ImmutableList.copyOf(gitManager.getRepositories());
  dirMappingAwares.forEach(aware -> aware.updatedRepoList(repositories));
  log.debug("Dir mappings change notification done");
}
 
Example #13
Source File: GtRepositoryManager.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
@Override
public void repositoryChanged(@NotNull GitRepository repository) {
  VirtualFile gitDir = GitUtil.findGitDir(repository.getRoot());
  Optional.ofNullable(gitDir)
      .map(dir -> dir.findChild("config"))
      .map(VfsUtilCore::virtualToIoFile)
      .map(GtConfig::load)
      .ifPresent(config -> configs.put(repository, config));
}
 
Example #14
Source File: GtUtil.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
@Nullable
@CalledInAwt
public static GitRepository getCurrentRepositoryQuick(@NotNull Project project) {
  GitRepositoryManager repositoryManager = GitUtil.getRepositoryManager(project);
  String recentRootPath = GitVcsSettings.getInstance(project).getRecentRootPath();
  return DvcsUtil.guessCurrentRepositoryQuick(project, repositoryManager, recentRootPath);
}
 
Example #15
Source File: CompletionServiceImpl.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
@Override
@NotNull
public Collection<GitRepository> getAffected() {
  CompletionScopeProvider scopeProvider = getScopeProvider();
  Collection<File> affectedFiles = scopeProvider.getAffectedFiles();
  log.debug("Get affected files: ", affectedFiles);
  Collection<GitRepository> affectedRepositories = findAffectedRepositories(affectedFiles);
  log.debug("Get affected repositories: ", affectedRepositories);
  return affectedRepositories;
}
 
Example #16
Source File: VirtualFileRepoCacheImpl.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
@Override
public void updatedRepoList(ImmutableList<GitRepository> repositories) {
  RepoListUpdate update = buildUpdate(repositories);
  rebuildRootsCache(update);
  purgeDirsCache(update);

  updateNotifications(update);
}
 
Example #17
Source File: RootActions.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
private void addPerRepositoryActions() {
  Collection<GitRepository> repositories = GitUtil.getRepositories(project);
  repositories = GtUtil.sort(repositories);
  List<GitRepository> repos = repositories.stream().filter(GtUtil::hasRemotes).collect(Collectors.toList());
  if (hasRepositories(repos)) {
    addSeparator(ResBundle.message("statusBar.status.menu.repositories.title"));
    if (repos.size() == 1) {
      GitRepository repo = repos.get(0);
      addAll(StatusBarActions.actionsFor(repo));
    } else if (repos.size() > 1) {
      addAll(repos.stream().map(RepositoryActions::new).collect(Collectors.toList()));
    }
  }
}
 
Example #18
Source File: RepositoryLocator.java    From GitLink with MIT License 5 votes vote down vote up
@NotNull
public Repository locate(@NotNull final VirtualFile file) throws RepositoryNotFoundException {
    LocalFilePath path = new LocalFilePath(file.getPath(), file.isDirectory());
    GitRepository repository = GitUtil.getRepositoryManager(project).getRepositoryForFileQuick(path);

    if (repository == null) {
        throw new RepositoryNotFoundException();
    }

    Preferences preferences = Preferences.getInstance(project);

    return new Repository(repository, preferences.getDefaultBranch(), preferences.remoteName);
}
 
Example #19
Source File: InfoCacheGateway.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
private Optional<GitRemoteBranch> getRemoteBranchFromActiveTask(@NotNull GitRepository repository) {
  TaskManager manager = TaskManager.getManager(project);
  if (manager == null) {
    return Optional.empty();
  }
  LocalTask activeTask = manager.getActiveTask();
  return activeTask.getBranches(true)
             .stream()
             .filter(branchInfo -> Objects.equals(repository.getPresentableUrl(), branchInfo.repository))
             .findFirst()
             .map(branchInfo -> branchInfo.name)
             .map(repository::getBranchTrackInfo)
             .map(GitBranchTrackInfo::getRemoteBranch);
}
 
Example #20
Source File: ProjectViewDecorator.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
private void doDecorate(ProjectViewNode<?> node, PresentationData presentation, Metrics metrics) {
  Timer repoForLatency = metrics.timer("decorate-repo-for");
  GitRepository repo = repoForLatency.timeSupplier(() -> repoFinder.getRepoFor(node));
  if (repo != null) {
    Timer applyLatency = metrics.timer("decorate-apply");
    applyLatency.time(() -> applyDecoration(node.getProject(), repo, node, presentation));
  }
}
 
Example #21
Source File: VirtualFileRepoCacheImplTest.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
@Test
void getRepoForDirShouldReturnSameRepositoryForDirInRootIfCalledMoreThanOnce() {
  setupRepo();

  MockVirtualFile dirInRoot = createDir(repositoryRoot, "dirInRoot");
  GitRepository repo1 = cache.getRepoForDir(dirInRoot);
  GitRepository repo2 = cache.getRepoForDir(dirInRoot);
  assertThat(repo1).isEqualTo(repo2);
}
 
Example #22
Source File: StatusToolTip.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
private void prepareMultiRepoTooltip(StringBand infoPart, Collection<GitRepository> repositories) {
  PerRepoInfoCache cache = PerRepoInfoCache.getInstance(project);
  Map<GitRepository, String> statuses = new LinkedHashMap<>();
  final AtomicReference<GitRepository> currentRepo = new AtomicReference<>();
  for (GitRepository repository : GtUtil.sort(repositories)) {
    cache.getInfo(repository).maybeCount().map(StatusText::format).ifPresent(statusText -> {
      if (repository.equals(currentRepository)) {
        currentRepo.set(repository);
      }
      statuses.put(repository, statusText);
    });
  }
  if (!statuses.isEmpty()) {
    if (infoPart.length() > 0) {
      infoPart.append(Html.HRX);
    }
    infoPart.append(
        statuses.entrySet().stream().map(e -> {
          String repoStatus = GitUIUtil.bold(GtUtil.name(e.getKey())) + ": " + e.getValue();
          if (Objects.equals(e.getKey(), currentRepo.get())) {
            repoStatus = Html.underline(repoStatus);
          }
          return repoStatus;
        }).collect(Collectors.joining(Html.BRX))
    );
  }
}
 
Example #23
Source File: IncrementalBlameCalculator.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
private GitLineHandler prepareLineHandler(@NotNull GitRepository repository, @NotNull VirtualFile file,
                                          @NotNull VcsRevisionNumber revisionNumber) {
  GitLineHandler handler = gateway.createLineHandler(repository);
  handler.setStdoutSuppressed(true);
  handler.addParameters("--incremental", "-l", "-t", "-w", "--encoding=UTF-8", revisionNumber.asString());
  handler.endOptions();
  handler.addRelativePaths(GtUtil.localFilePath(file));
  return handler;
}
 
Example #24
Source File: NodeDecorationBase.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
public NodeDecorationBase(@NotNull NodeDecorationUi ui,
                          @NotNull GitRepository repo,
                          @NotNull RepoInfo repoInfo,
                          @NotNull ExtendedRepoInfo extendedRepoInfo) {
  this.ui = ui;
  this.repo = repo;
  this.repoInfo = repoInfo;
  this.extendedRepoInfo = extendedRepoInfo;
}
 
Example #25
Source File: VirtualFileRepoCacheImpl.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public GitRepository getRepoForDir(@NotNull VirtualFile dir) {
  Preconditions.checkArgument(dir.isDirectory(), "%s is not a dir", dir);
  try {
    return dirsCache.get(dir).repository;
  } catch (ExecutionException e) {
    log.warn("Cannot compute repo for dir: " + dir, e);
    return null;
  }
}
 
Example #26
Source File: DiffCompareInfoProviderTest.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    gitUtilWrapperMock = Mockito.mock(DiffCompareInfoProvider.GitUtilWrapper.class);

    projectMock = Mockito.mock(Project.class);

    gitRepositoryMock = Mockito.mock(GitRepository.class);
    fileMock = Mockito.mock(VirtualFile.class);
    when(gitRepositoryMock.getRoot()).thenReturn(fileMock);

    underTest = new DiffCompareInfoProvider();
    underTest.setUtilWrapper(gitUtilWrapperMock);
}
 
Example #27
Source File: OpenCommitInBrowserAction.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
@Override
public void update(@NotNull final AnActionEvent anActionEvent) {

    final Presentation presentation = anActionEvent.getPresentation();

    final Project project = anActionEvent.getData(CommonDataKeys.PROJECT);
    final VcsLog log = anActionEvent.getData(VcsLogDataKeys.VCS_LOG);
    if (project == null || project.isDisposed() || log == null) {
        presentation.setEnabledAndVisible(false);
        return;
    }

    final List<VcsFullCommitDetails> commits = log.getSelectedDetails();
    if (commits.size() == 0) {
        presentation.setEnabledAndVisible(false);
        return;
    }

    final VcsFullCommitDetails commit = commits.get(0);

    final GitRepository repository = GitUtil.getRepositoryManager(project).getRepositoryForRootQuick(commit.getRoot());

    if (repository == null || !TfGitHelper.isTfGitRepository(repository)) {
        presentation.setEnabledAndVisible(false);
        return;
    } else if (commits.size() > 1) {
        // only one for now, leave it visible as a breadcrumb
        presentation.setVisible(true);
        presentation.setEnabled(false);
        return;
    }

    presentation.setEnabledAndVisible(true);
}
 
Example #28
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 #29
Source File: AutoFetchSchedule.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
private boolean updatedSomeTimeAgo(@NotNull GitRepository repository, long now) {
  long lastFetch = getLastFetch(repository).get();
  if (lastFetch == 0) {
    return true;
  } else {
    long elapsedSinceUpdateMillis = now - lastFetch;
    return elapsedSinceUpdateMillis > BRANCH_SWITCH_GRACE_PERIOD.toMillis();
  }
}
 
Example #30
Source File: ProjectRepoEventManager.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
private void triggerServerEvents(final String sender, final Project project, final GitRepository repository) {
    ArgumentHelper.checkNotEmptyString(sender, "sender");
    ArgumentHelper.checkNotNull(project, "project");

    final Map<String, Object> context = EventContextHelper.createContext(sender);
    EventContextHelper.setProject(context, project);
    if (repository != null) {
        EventContextHelper.setRepository(context, repository);
    }

    // Fire all events
    ServerEventManager.getInstance().triggerAllEvents(context);
}