class RepositoryBuildLauncher {

  @VisibleForTesting
  CommitInfo calculateCommitInfoForBuild(
      GitInfo gitInfo,
      RepositoryBuild queuedBuild,
      Optional<RepositoryBuild> previousBuild) throws IOException, NonRetryableBuildException {
    LOG.info("Trying to fetch current sha for branch {}/{}", gitInfo.getRepository(), gitInfo.getBranch());

    final GHRepository repository;
    try {
      repository = gitHubHelper.repositoryFor(gitInfo);
    } catch (FileNotFoundException e) {
      throw new NonRetryableBuildException("Couldn't find repository " + gitInfo.getFullRepositoryName(), e);
    }

    Optional<Commit> lastCommitInPreviousBuild = getCommitFromRepositoryBuild(previousBuild);

    // Inter project builds re-build the project using the commit of the last build if available
    // otherwise we fall back to using the newest commit available
    if (queuedBuild.getBuildTrigger().getType() == INTER_PROJECT && lastCommitInPreviousBuild.isPresent()) {
      return new CommitInfo(lastCommitInPreviousBuild.get(), lastCommitInPreviousBuild, ImmutableList.of(), false);
    }

    // Resolve newest sha
    Optional<String> sha = gitHubHelper.shaFor(repository, gitInfo);
    if (!sha.isPresent()) {
      String message = String.format("Couldn't find branch %s for repository %s", gitInfo.getBranch(), gitInfo.getFullRepositoryName());
      throw new NonRetryableBuildException(message);
    } else {
      LOG.info("Found sha {} for branch {}/{}", sha.get(), gitInfo.getRepository(), gitInfo.getBranch());

      Commit currentCommit = gitHubHelper.toCommit(repository.getCommit(sha.get()));
      return gitHubHelper.commitInfoFor(repository, currentCommit, lastCommitInPreviousBuild);
    }
  }

  @Inject public  RepositoryBuildLauncher(RepositoryBuildService repositoryBuildService,
                                 BranchService branchService,
                                 ModuleService moduleService,
                                 DependenciesService dependenciesService,
                                 ModuleDiscoveryService moduleDiscoveryService,
                                 ModuleDiscoveryHandler moduleDiscoveryHandler,
                                 GitHubHelper gitHubHelper);

}