예제 #1
4
 /**
  * Fix up the repository set up to our policy.
  */
 private void setupRepository(GHRepository r) throws IOException {
     r.setEmailServiceHook(POST_COMMIT_HOOK_EMAIL);
     r.enableIssueTracker(false);
     r.enableWiki(false);
     r.createHook(IrcBotImpl.IRC_HOOK_NAME,
             IrcBotImpl.IRC_HOOK_CONFIG, (Collection<GHEvent>) null,
             true);
 }
예제 #2
0
 /** Gets all the open pull requests in this organizataion. */
 public List<GHPullRequest> getPullRequests() throws IOException {
   List<GHPullRequest> all = new ArrayList<GHPullRequest>();
   for (GHRepository r : getRepositoriesWithOpenPullRequests()) {
     all.addAll(r.getPullRequests(GHIssueState.OPEN));
   }
   return all;
 }
예제 #3
0
	public DynamicProject createNewProject(GHRepository githubRepository) {
		try {
			new GithubRepositoryService(githubRepository).linkProjectToCi();

			OrganizationContainer folder = this.organizationRepository.getOrCreateContainer(githubRepository.getOwner().getLogin());
			String projectName = githubRepository.getName();
			DynamicProject project = folder.createProject(DynamicProject.class, projectName);

			project.setDescription(format("<a href=\"%s\">%s</a>", githubRepository.getUrl(), githubRepository.getUrl()));
			project.setConcurrentBuild(true);
			if (StringUtils.isNotEmpty(SetupConfig.get().getLabel())) {
				project.setAssignedLabel(Jenkins.getInstance().getLabel(SetupConfig.get().getLabel()));
			}
			project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("BRANCH", "master")));
			project.addProperty(new GithubRepoProperty(githubRepository.getUrl()));

			project.getPublishersList().add(new DotCiNotifier());
			project.save();
			folder.addItem(project);
			folder.save();
			return project;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
 public void run() throws Exception {
   GitHub gh = GitHub.connect();
   GHOrganization org = gh.getOrganization("jenkinsci");
   for (GHRepository r : org.listRepositories()) {
     // as a roll out, only do this for 60% of the repositories
     if (r.getName().hashCode() % 10 < 6 && !r.getName().equals("jenkins")) greet(r);
   }
 }
 private GHRepository mockGHRepository(String ownerName, String name) throws IOException {
   GHRepository ghRepository = PowerMockito.mock(GHRepository.class);
   GHUser ghUser = PowerMockito.mock(GHUser.class);
   PowerMockito.when(ghUser.getLogin()).thenReturn(ownerName);
   PowerMockito.when(ghRepository.getOwner()).thenReturn(ghUser);
   PowerMockito.when(ghRepository.getName()).thenReturn(name);
   return ghRepository;
 }
예제 #6
0
    /**
     * @param newName
     *      If not null, rename a epository after a fork.
     */
    private void forkGitHub(String channel, String owner, String repo, String newName) {
        try {
            sendMessage(channel, "Forking "+repo);

            GitHub github = GitHub.connect();
            GHUser user = github.getUser(owner);
            if (user==null) {
                sendMessage(channel,"No such user: "******"No such repository: "+repo);
                return;
            }

            GHOrganization org = github.getOrganization("jenkinsci");
            GHRepository r;
            try {
                r = orig.forkTo(org);
            } catch (IOException e) {
                // we started seeing 500 errors, presumably due to time out.
                // give it a bit of time, and see if the repository is there
                System.out.println("GitHub reported that it failed to fork "+owner+"/"+repo+". But we aren't trusting");
                Thread.sleep(3000);
                r = org.getRepository(repo);
                if (r==null)
                    throw e;
            }
            if (newName!=null)
                r.renameTo(newName);

            // GitHub adds a lot of teams to this repo by default, which we don't want
            Set<GHTeam> legacyTeams = r.getTeams();

            GHTeam t = getOrCreateRepoLocalTeam(org, r);
            t.add(user);    // the user immediately joins this team

            // the Everyone group gets access to this new repository, too.
            GHTeam everyone = org.getTeams().get("Everyone");
            everyone.add(r);

            setupRepository(r);

            sendMessage(channel, "Created https://github.com/jenkinsci/" + (newName != null ? newName : repo));

            // remove all the existing teams
            for (GHTeam team : legacyTeams)
                team.remove(r);

        } catch (InterruptedException e) {
            sendMessage(channel,"Failed to fork a repository: "+e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            sendMessage(channel,"Failed to fork a repository: "+e.getMessage());
            e.printStackTrace();
        }
    }
 private void mockGithubRepositoryWithCollaborators(
     GitHub mockGithub, String name, boolean isPrivate, List<String> collaboratorNames)
     throws IOException {
   GHRepository ghRepository = PowerMockito.mock(GHRepository.class);
   PowerMockito.when(mockGithub.getRepository(name)).thenReturn(ghRepository);
   PowerMockito.when(ghRepository.isPrivate()).thenReturn(isPrivate);
   Set<String> names = new HashSet(collaboratorNames);
   PowerMockito.when(ghRepository.getCollaboratorNames()).thenReturn(names);
 }
예제 #8
0
 /** Creates a new team and assigns the repositories. */
 public GHTeam createTeam(String name, Permission p, Collection<GHRepository> repositories)
     throws IOException {
   Requester post = new Requester(root).with("name", name).with("permission", p);
   List<String> repo_names = new ArrayList<String>();
   for (GHRepository r : repositories) {
     repo_names.add(r.getName());
   }
   post.with("repo_names", repo_names);
   return post.method("POST").to("/orgs/" + login + "/teams", GHTeam.class).wrapUp(this);
 }
예제 #9
0
 /**
  * List up repositories that has some open pull requests.
  *
  * <p>This used to be an efficient method that didn't involve traversing every repository, but now
  * it doesn't do any optimization.
  */
 public List<GHRepository> getRepositoriesWithOpenPullRequests() throws IOException {
   List<GHRepository> r = new ArrayList<GHRepository>();
   for (GHRepository repository : listRepositories()) {
     repository.wrap(root);
     List<GHPullRequest> pullRequests = repository.getPullRequests(GHIssueState.OPEN);
     if (pullRequests.size() > 0) {
       r.add(repository);
     }
   }
   return r;
 }
예제 #10
0
 /** Creates a new team and assigns the repositories. */
 public GHTeam createTeam(String name, Permission p, Collection<GHRepository> repositories)
     throws IOException {
   Poster post =
       new Poster(root)
           .withCredential()
           .with("team[name]", name)
           .with("team[permission]", p.name().toLowerCase());
   for (GHRepository r : repositories) {
     post.with("team[repo_names][]", r.getOwnerName() + '/' + r.getName());
   }
   return post.to("/organizations/" + login + "/teams", JsonTeam.class).wrap(this);
 }
예제 #11
0
 private boolean hookExist() throws IOException {
   GHRepository ghRepository = getGitHubRepo();
   for (GHHook h : ghRepository.getHooks()) {
     if (!"web".equals(h.getName())) {
       continue;
     }
     if (!getHookUrl().equals(h.getConfig().get("url"))) {
       continue;
     }
     return true;
   }
   return false;
 }
  // 2. Get branch/commit hash for the source repo - the actual source code
  @Test
  public void existsInGit() throws IOException {
    final String repo = "binrepo-devex";
    //  final String repo = "search_raptor_binary";
    String githubUrl = "https://github.scm.corp.ebay.com/api/v3/";
    String accessToken = "1cf7d9792235b8592eda18bd7dcc2de37f99b3bc";
    // String accessToken = "5d8e186b08062ca405ab25d489fca9823c2a7136";

    GitHub gitHub = GitHub.connectUsingOAuth(githubUrl, accessToken);

    String login = gitHub.getMyself().getLogin();
    System.out.println(login);

    GHRepository repository = gitHub.getMyself().getRepository(repo);
    if (repository != null) {
      System.out.println(repository.getDescription());
      Map<String, GHBranch> branches = repository.getBranches();
      for (String branch : branches.keySet()) {
        System.out.println(branch);

        GHBranch ghBranch = branches.get(branch);

        System.out.println(
            "Repository URL = "
                + repository.getUrl()
                + " Branch = "
                + ghBranch.getName()
                + " Commit Hash = "
                + ghBranch.getSHA1());
      }

      PagedIterable<GHCommit> commits = repository.listCommits();
      for (GHCommit commit : commits) {
        List<GHCommit.File> commitFiles = commit.getFiles();
        for (GHCommit.File commitFile : commitFiles) {
          System.out.println(commitFile.getFileName() + commitFile.getRawUrl());
        }
        System.out.println(
            commit.getSHA1()
                + " NumFiles = "
                + commit.getFiles().size()
                + " Committer = "
                + commit.getCommitter().getName()); // + commit.getLastStatus().getDescription());
      }

      GHBranch test2 = branches.get("test2");
      test2.getRoot();
    }
  }
예제 #13
0
 public boolean createHook() {
   if (ghRepository == null) {
     logger.log(
         Level.INFO,
         "Repository not available, cannot set pull request hook for repository {0}",
         reponame);
     return false;
   }
   try {
     if (hookExist()) {
       return true;
     }
     Map<String, String> config = new HashMap<String, String>();
     String secret = getSecret();
     config.put("url", new URL(getHookUrl()).toExternalForm());
     config.put("insecure_ssl", "1");
     if (secret != "") {
       config.put("secret", secret);
     }
     ghRepository.createHook("web", config, HOOK_EVENTS, true);
     return true;
   } catch (IOException ex) {
     logger.log(
         Level.SEVERE,
         "Couldn''t create web hook for repository {0}. Does the user (from global configuration) have admin rights to the repository?",
         reponame);
     return false;
   }
 }
  private void createCommitStatus(
      AbstractBuild<?, ?> build,
      TaskListener listener,
      String message,
      GHRepository repo,
      GHCommitState state)
      throws GhprcCommitStatusException {
    GhprcCause cause = Ghprc.getCause(build);

    String sha1 = cause.getCommit();
    String url = Jenkins.getInstance().getRootUrl() + build.getUrl();
    if (!StringUtils.isEmpty(statusUrl)) {
      url = Ghprc.replaceMacros(build, listener, statusUrl);
    }
    String context = Util.fixEmpty(commitStatusContext);
    context = Ghprc.replaceMacros(build, listener, context);

    listener
        .getLogger()
        .println(
            String.format(
                "Setting status of %s to %s with url %s and message: '%s'",
                sha1, state, url, message));
    if (context != null) {
      listener.getLogger().println(String.format("Using context: " + context));
    }
    try {
      repo.createCommitStatus(sha1, state, url, message, context);
    } catch (IOException e) {
      throw new GhprcCommitStatusException(e, state, message, cause.getPullID());
    }
  }
  public void onBuildTriggered(GhprcTrigger trigger, GhprcPullRequest pr, GHRepository ghRepository)
      throws GhprcCommitStatusException {
    StringBuilder sb = new StringBuilder();
    GHCommitState state = GHCommitState.PENDING;

    AbstractProject<?, ?> project = trigger.getActualProject();

    String context = Util.fixEmpty(commitStatusContext);
    context = Ghprc.replaceMacros(project, context);

    if (!StringUtils.isEmpty(triggeredStatus)) {
      sb.append(Ghprc.replaceMacros(project, triggeredStatus));
    } else {
      sb.append("Build triggered.");
      if (pr.isMergeable()) {
        sb.append(" sha1 is merged.");
      } else {
        sb.append(" sha1 is original commit.");
      }
    }

    String url = Ghprc.replaceMacros(project, statusUrl);

    String message = sb.toString();
    try {
      ghRepository.createCommitStatus(pr.getHead(), state, url, message, context);
    } catch (IOException e) {
      throw new GhprcCommitStatusException(e, state, message, pr.getId());
    }
  }
예제 #16
0
    private void createGitHubRepository(String channel, String name, String collaborator) {
        try {
            GitHub github = GitHub.connect();
            GHOrganization org = github.getOrganization("jenkinsci");
            GHRepository r = org.createRepository(name, "", "", "Everyone", true);
            setupRepository(r);

            GHTeam t = getOrCreateRepoLocalTeam(org, r);
            if (collaborator!=null)
                t.add(github.getUser(collaborator));

            sendMessage(channel,"New github repository created at "+r.getUrl());
        } catch (IOException e) {
            sendMessage(channel,"Failed to create a repository: "+e.getMessage());
            e.printStackTrace();
        }
    }
예제 #17
0
  public void check() {
    if (!initGhRepository()) {
      return;
    }

    if (helper.isProjectDisabled()) {
      logger.log(Level.FINE, "Project is disabled, not checking github state");
      return;
    }

    List<GHPullRequest> openPulls;
    try {
      openPulls = ghRepository.getPullRequests(GHIssueState.OPEN);
    } catch (IOException ex) {
      logger.log(Level.SEVERE, "Could not retrieve open pull requests.", ex);
      return;
    }

    ConcurrentMap<Integer, GhprbPullRequest> pulls = helper.getTrigger().getPulls();

    Set<Integer> closedPulls = new HashSet<Integer>(pulls.keySet());

    for (GHPullRequest pr : openPulls) {
      if (pr.getHead() == null) {
        try {
          pr = ghRepository.getPullRequest(pr.getNumber());
        } catch (IOException ex) {
          logger.log(Level.SEVERE, "Could not retrieve pr " + pr.getNumber(), ex);
          return;
        }
      }
      try {
        check(pr);
      } catch (IOException ex) {
        logger.log(Level.SEVERE, "Could not retrieve pr " + pr.getNumber(), ex);
        return;
      }
      closedPulls.remove(pr.getNumber());
    }

    // remove closed pulls so we don't check them again
    for (Integer id : closedPulls) {
      pulls.remove(id);
    }
  }
 private Set<GhprbRepository> getRepos(GHRepository repo) throws IOException {
   try {
     return getRepos(repo.getOwner().getLogin() + "/" + repo.getName());
   } catch (Exception ex) {
     logger.log(Level.WARNING, "Can't get a valid owner for repo");
     // this normally happens due to missing "login" field in the owner of the repo
     // when the repo is inside of an organisation account. The only field which doesn't
     // rely on the owner.login (which would throw a null pointer exception) is the "html_url"
     // field. So we try to parse the owner out of that here until github fixes his api
     String repoUrl = repo.getUrl();
     if (repoUrl.endsWith("/")) { // strip off trailing slash if any
       repoUrl = repoUrl.substring(0, repoUrl.length() - 2);
     }
     int slashIndex = repoUrl.lastIndexOf('/');
     String owner = repoUrl.substring(slashIndex + 1);
     logger.log(Level.INFO, "Parsed {0} from {1}", new Object[] {owner, repoUrl});
     return getRepos(owner + "/" + repo.getName());
   }
 }
예제 #19
0
 /**
  * Creates a repository local team, and grants access to the repository.
  */
 private GHTeam getOrCreateRepoLocalTeam(GHOrganization org, GHRepository r) throws IOException {
     String teamName = r.getName() + " Developers";
     GHTeam t = org.getTeams().get(teamName);
     if (t==null) {
         t = org.createTeam(teamName, Permission.ADMIN, r);
     } else {
         t.add(r);
     }
     return t;
 }
예제 #20
0
파일: Test3.java 프로젝트: broose/PieceOf
  public static void main(String[] args) throws IOException {
    GitHub github = GitHub.connectUsingOAuth(""); // deleted
    repo = github.getRepository(username + "/new-repository-1");
    content = repo.getFileContent("test-folder-2/data.txt");

    byte[] bytes = new byte[100];
    URL website = new URL(content.getDownloadUrl());
    ReadableByteChannel rbc = Channels.newChannel(website.openStream());
    FileOutputStream fos = new FileOutputStream(localFile);
    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
  }
예제 #21
0
  private static boolean syncIssue(final GHRepository rep, final int issueId, final String body) {
    try {
      GHIssue issue = rep.getIssue(issueId);
      issue.setBody(body);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
    }

    return false;
  }
예제 #22
0
 private boolean createJenkinsHook(GHRepository repo, URL url) {
   try {
     repo.createHook(
         "jenkins",
         Collections.singletonMap("jenkins_hook_url", url.toExternalForm()),
         null,
         true);
     return true;
   } catch (IOException e) {
     throw new GHException("Failed to update jenkins hooks", e);
   }
 }
  private GHHook createWebHook(String webhookUrl) throws IOException {
    final GitHubRepositoryName gitHubRepoName = GitHubRepositoryName.create(gitHubRepositoryUrl);
    for (GHRepository repo : gitHubRepoName.resolve()) {
      // check if the webhook already exists
      for (GHHook hook : repo.getHooks()) {
        if ("web".equals(hook.getName()) && webhookUrl.equals(hook.getConfig().get("url"))) {
          LOGGER.info(
              MessageFormat.format(
                  "Webhook {0} already exists for {1}", webhookUrl, gitHubRepositoryUrl));
          return hook;
        }
      }
      try {
        Map<String, String> config = new HashMap<String, String>();
        config.put("url", webhookUrl);
        config.put("insecure_ssl", "1");
        GHHook hook = repo.createHook("web", config, WEBHOOK_EVENTS, true);
        LOGGER.info(
            MessageFormat.format(
                "Webhook {0} is added to GitHub repository {1}", webhookUrl, gitHubRepositoryUrl));

        return hook;
      } catch (IOException e) {
        LOGGER.log(
            Level.FINEST,
            MessageFormat.format(
                "Failed to add webhook {0} to GitHub repository {1}",
                webhookUrl, gitHubRepositoryUrl),
            e);
      }
    }
    LOGGER.warning(
        MessageFormat.format(
            "Cannot add webhook {0} to GitHub repository {1}. "
                + "Make sure that you specified a valid GitHub credential for GitHub project {1} in Jenkins "
                + "configuration.",
            webhookUrl, gitHubRepositoryUrl));

    return null;
  }
 /** Does this repository match the repository referenced in the given {@link GHCommitPointer}? */
 public boolean matches(GHRepository repo) throws IOException {
   return userName.equals(repo.getOwner().getLogin()) // TODO: use getOwnerName
       && repositoryName.equals(repo.getName())
       && host.equals(new URL(repo.getUrl()).getHost());
 }
 protected void greet(GHRepository r) throws IOException {
   for (GHPullRequest pr : r.listPullRequests(GHIssueState.OPEN)) {
     greet(pr);
   }
 }
예제 #26
0
  public void createBinaryRepository() throws IOException, GitException, MapServiceException {
    // check whether "binary repository" exists
    if (isBinaryRepositoryAvailable()) throw new GitException("Repository already exists");

    // find the name of the "source repository"
    // String sourceRepoName = getRepositoryName();

    // find where ".git" folder is found
    File f = sourceRepository.getDirectory();
    File sourceRepoFolder = f.getParentFile();

    String sourceRepoFolderName = f.getParentFile().getName();

    // calculate binary repository folder
    File parent = f.getParentFile().getParentFile();
    File binaryRepoFolder = new File(parent, ("." + sourceRepoFolderName));

    // create binary repository folder
    FileUtils.mkdir(binaryRepoFolder, true);

    // initialize "git" repository
    InitCommand initCmd = Git.init();
    initCmd.setDirectory(binaryRepoFolder);
    Git binaryRepo = null;
    try {
      System.out.println("initializing bare repository");
      binaryRepo = initCmd.call();
    } catch (GitAPIException e) {
      throw new GitException("unable to initialize repository", e);
    }

    System.out.println("adding readme.md file");
    createReadMeFile(binaryRepoFolder);

    // get "status"
    StatusCommand statusC = binaryRepo.status();
    Collection<String> toadd = GitUtils.getFilesToStage(statusC);

    // add "readme" file to staging
    if (toadd.size() > 0) {
      AddCommand add = binaryRepo.add();
      for (String file : toadd) {
        add.addFilepattern(file);
      }
      try {
        add.call();
        CommitCommand commit = binaryRepo.commit();
        commit.setMessage("initial commit");
        System.out.println("performing first commit");
        commit.call();
      } catch (NoFilepatternException e) {
        throw new GitException("unable to add file(s)", e);
      } catch (GitAPIException e) {
        throw new GitException("Unable to add or commit", e);
      }
    }

    // Calculate the remote url for binary repository
    String remoteUrl = calculateBinaryRepositoryUrl();

    // TODO: check whether the remote exists, if not create it, else fail
    GitHub github = new GitHubClient().getGithub();
    GHOrganization githubOrg = github.getOrganization("Binary");
    GHRepository repository = githubOrg.getRepository(GitUtils.getRepositoryName(remoteUrl));

    if (repository == null) {

      System.out.println("creating remote repository : " + remoteUrl);
      GHRepository repo =
          githubOrg.createRepository(
              GitUtils.getRepositoryName(remoteUrl),
              "Binary repository",
              "https://github.scm.corp.ebay.com",
              "Owners",
              true);

      System.out.println(repo.getUrl() + " created successfully ");

    } else {
      // fail, it shouldn't come here
    }

    // add "remote" repository
    StoredConfig config = binaryRepo.getRepository().getConfig();
    config.setString("remote", "origin", "url", remoteUrl);
    System.out.println("adding remote origin " + remoteUrl);
    config.save();

    // get "status"
    StatusCommand stat = binaryRepo.status();
    Collection<String> filesToAdd = GitUtils.getFilesToStage(stat);

    // add files to "staging"
    if (filesToAdd.size() > 0) {
      AddCommand addCmd = binaryRepo.add();
      for (String file : filesToAdd) {
        addCmd.addFilepattern(file);
      }
      try {
        addCmd.call();
      } catch (NoFilepatternException e) {
        throw new GitException("unable to add files", e);
      } catch (GitAPIException e) {
        throw new GitException("unable to add files", e);
      }
    }

    // commit
    System.out.println("commiting the files");
    CommitCommand commit = binaryRepo.commit();
    // add the 'source' repository git-url, commit-id and branch
    commit.setMessage("adding readme.md file");

    try {
      commit.call();
    } catch (NoHeadException e) {
      throw new GitException("unable to commit", e);
    } catch (NoMessageException e) {
      throw new GitException("unable to commit", e);
    } catch (UnmergedPathsException e) {
      throw new GitException("unable to commit", e);
    } catch (ConcurrentRefUpdateException e) {
      throw new GitException("unable to commit", e);
    } catch (WrongRepositoryStateException e) {
      throw new GitException("unable to commit", e);
    } catch (GitAPIException e) {
      throw new GitException("unable to commit", e);
    }

    // push
    System.out.println("pushing to remote");
    PushCommand push = binaryRepo.push();
    try {
      push.call();
    } catch (InvalidRemoteException e) {
      throw new GitException("unable to push", e);
    } catch (TransportException e) {
      throw new GitException("unable to push", e);
    } catch (GitAPIException e) {
      throw new GitException("unable to push", e);
    }

    // read the branch from "source" repository
    String branchname = sourceRepository.getBranch();

    // create a "branch"
    if (!branchname.toLowerCase().equals("master")) {
      CreateBranchCommand branchCmd = binaryRepo.branchCreate();
      branchCmd.setName(branchname);
      try {
        // create branch
        branchCmd.call();

        // checkout the branch
        CheckoutCommand checkout = binaryRepo.checkout();
        checkout.setName(branchname);
        checkout.call();
      } catch (RefAlreadyExistsException e) {
        throw new GitException("unable to create a branch", e);
      } catch (RefNotFoundException e) {
        throw new GitException("unable to create a branch", e);
      } catch (InvalidRefNameException e) {
        throw new GitException("unable to create a branch", e);
      } catch (GitAPIException e) {
        throw new GitException("unable to create a branch", e);
      }
    }

    // find the "localobr" folders and exclude them during copy
    List<String> excludes = new ArrayList<String>();
    Collection<File> excludeFiles =
        FileUtil.findDirectoriesThatEndWith(sourceRepoFolder, "localobr");
    for (File file : excludeFiles) {
      excludes.add(file.getCanonicalPath());
    }

    // copy the classes
    System.out.println("copying binary files");
    copyBinaryFolders("target", excludes, binaryRepoFolder);

    // get "status"
    StatusCommand statusCmd = binaryRepo.status();
    Collection<String> tobeAdded = GitUtils.getFilesToStage(statusCmd);

    // add files to "staging"
    if (tobeAdded.size() > 0) {
      AddCommand addCmd = binaryRepo.add();
      for (String file : tobeAdded) {
        addCmd.addFilepattern(file);
      }
      try {
        addCmd.call();
      } catch (NoFilepatternException e) {
        throw new GitException("unable to add files", e);
      } catch (GitAPIException e) {
        throw new GitException("unable to add files", e);
      }
    }

    // commit
    System.out.println("commiting the files");
    CommitCommand commit1 = binaryRepo.commit();
    commit1.setMessage("saving the files");

    try {
      commit1.call();
    } catch (NoHeadException e) {
      throw new GitException("unable to commit", e);
    } catch (NoMessageException e) {
      throw new GitException("unable to commit", e);
    } catch (UnmergedPathsException e) {
      throw new GitException("unable to commit", e);
    } catch (ConcurrentRefUpdateException e) {
      throw new GitException("unable to commit", e);
    } catch (WrongRepositoryStateException e) {
      throw new GitException("unable to commit", e);
    } catch (GitAPIException e) {
      throw new GitException("unable to commit", e);
    }

    // push
    System.out.println("pushing to remote");
    PushCommand pushCmd = binaryRepo.push();
    try {
      pushCmd.call();
    } catch (InvalidRemoteException e) {
      throw new GitException("unable to push", e);
    } catch (TransportException e) {
      throw new GitException("unable to push", e);
    } catch (GitAPIException e) {
      throw new GitException("unable to push", e);
    }

    final String repoUrl = getSourceRemoteUrl();
    // branchName was computed above
    final org.eclipse.jgit.lib.Repository repo =
        new org.eclipse.jgit.storage.file.FileRepository(f);
    final RevWalk revWalk = new RevWalk(repo);
    final ObjectId resolve = repo.resolve(Constants.HEAD);
    final RevCommit commitRev = revWalk.parseCommit(resolve);
    final String commitHash = commitRev.getName();

    Git git = Git.open(binaryRepoFolder);
    final RevCommit binRepoResolveCommitRev;
    try {
      binRepoResolveCommitRev = git.log().call().iterator().next();
    } catch (NoHeadException e) {
      throw new GitException("No head found for repo", e);
    } catch (GitAPIException e) {
      throw new GitException("No head found for repo", e);
    }
    final String binRepoResolveCommitHash = binRepoResolveCommitRev.getName();
    final String binRepoBranchName = git.getRepository().getBranch();

    System.out.println("Update Bin Repo Service with the new changes - POST new object to service");
    final BinRepoBranchCommitDO binRepoBranchCommitDO =
        newInstance(
            repoUrl,
            branchname,
            commitHash,
            remoteUrl,
            binRepoBranchName,
            binRepoResolveCommitHash);
    final WebResource resource = client.resource(getUrlForPost());

    BinRepoBranchCommitDO postedDO = null;
    try {
      postedDO =
          resource
              .accept(MediaType.APPLICATION_XML)
              .post(BinRepoBranchCommitDO.class, binRepoBranchCommitDO);
      System.out.println("Posted Object = " + postedDO.toString());
    } catch (UniformInterfaceException e) {
      int statusCode = e.getResponse().getClientResponseStatus().getStatusCode();
      System.out.println("status code: " + statusCode);
      throw new MapServiceException("Unable to register the commit details", e);
    }

    // System.out.println(postedDO != null ? postedDO.toString() : "postedDO was null");
    System.out.println("updated the map service");
  }
예제 #27
0
	public boolean projectExists(GHRepository repository) throws IOException {
		OrganizationContainer folder = this.organizationRepository.getOrganizationContainer(repository.getOwner().getLogin());
		return folder != null && folder.getItem(repository.getName()) != null;
	}
예제 #28
0
 @Override
 protected boolean isDefault(GHRepository githubRepository) {
   return "go".equalsIgnoreCase(githubRepository.getLanguage());
 }
  public PullRequestBuildHandler(AbstractProject<?, ?> project, boolean newTrigger)
      throws IOException {
    this.project = project;

    final GithubProjectProperty property = project.getProperty(GithubProjectProperty.class);

    if (property == null
        || property.getProjectUrl() == null
        || StringUtils.isBlank(property.getProjectUrl().baseUrl())) {

      throw new IOException(
          MessageFormat.format(
              "GitHub project URL must be specified for project {0}", project.getFullName()));
    }

    String gitHubProjectUrl = property.getProjectUrl().baseUrl().trim();
    GitHubRepositoryName gitHubRepoName = GitHubRepositoryName.create(gitHubProjectUrl);
    if (gitHubRepoName == null) {
      throw new IOException(
          MessageFormat.format("Invalid GitHub project URL specified: {0}", gitHubProjectUrl));
    }

    GHRepository repo = gitHubRepoName.resolveOne();
    if (repo == null) {
      LOGGER.severe(
          MessageFormat.format(
              "Cannot connect to {0}. Please check your registered GitHub credentials",
              gitHubRepoName));

      gitHubRepositoryUrl = gitHubProjectUrl;
    } else {
      gitHubRepositoryUrl = repo.getHtmlUrl().toString();
    }
    if (!gitHubRepositoryUrl.endsWith("/")) {
      gitHubRepositoryUrl += '/';
    }

    PullRequestBuildTrigger trigger = project.getTrigger(PullRequestBuildTrigger.class);
    triggerPhrasePattern = Pattern.compile(trigger.getTriggerPhrase(), Pattern.CASE_INSENSITIVE);
    if (StringUtils.isNotBlank(trigger.getWhitelist())) {
      Set<String> entries = new HashSet<String>();
      for (String entry : trigger.getWhitelist().split(",")) {
        if (StringUtils.isNotBlank(entry)) {
          entries.add(entry);
        }
      }
      if (!entries.isEmpty()) {
        whitelist = entries;
      }
    }

    if (newTrigger) {
      configureGit(gitHubRepoName, trigger);

      // The construction of webhook URL requires Jenkins root URL which might be null if it is not
      // manually
      // configured and it is retrieved in a separate thread without request context. So the webhook
      // URL is first
      // retrieved here.
      PullRequestBuildTrigger.DescriptorImpl descriptor =
          (PullRequestBuildTrigger.DescriptorImpl)
              Jenkins.getInstance().getDescriptor(PullRequestBuildTrigger.class);

      final String webhookUrl =
          StringUtils.isBlank(descriptor.getWebHookExternalUrl())
              ? descriptor.getWebHookUrl()
              : descriptor.getWebHookExternalUrl();

      if (webhookUrl == null) {
        LOGGER.warning(
            MessageFormat.format(
                "Cannot add webhook to GitHub repository {0}. "
                    + "Please configure Jenkins URL or Webhook External URL for {1}",
                gitHubRepositoryUrl, descriptor.getDisplayName()));

      } else {
        LOGGER.info(
            MessageFormat.format(
                "Adding webhook {0} to GitHub repository {1}", webhookUrl, gitHubRepositoryUrl));

        sequentialExecutionQueue.execute(
            new Runnable() {

              public void run() {
                try {
                  createWebHook(webhookUrl);
                } catch (Throwable ex) {
                  LOGGER.log(
                      Level.SEVERE,
                      MessageFormat.format(
                          "Error adding webhook to GitHub repository {0}", gitHubRepositoryUrl),
                      ex);
                }
              }
            });
      }
    }
  }