예제 #1
0
 @Before
 public void createGitRepository() throws IOException, InterruptedException {
   tempAllocator = new TemporaryDirectoryAllocator();
   testGitDir = tempAllocator.allocate();
   TaskListener listener = StreamTaskListener.fromStderr();
   testGitClient = Git.with(listener, new EnvVars()).in(testGitDir).getClient();
   testGitClient.init();
 }
예제 #2
0
  public TestGitRepo(String name, File tmpDir, TaskListener listener)
      throws IOException, InterruptedException {
    this.name = name;
    this.listener = listener;

    envVars = new EnvVars();

    gitDir = tmpDir;
    User john = User.get(johnDoe.getName(), true);
    UserProperty johnsMailerProperty = new Mailer.UserProperty(johnDoe.getEmailAddress());
    john.addProperty(johnsMailerProperty);

    User jane = User.get(janeDoe.getName(), true);
    UserProperty janesMailerProperty = new Mailer.UserProperty(janeDoe.getEmailAddress());
    jane.addProperty(janesMailerProperty);

    // initialize the git interface.
    gitDirPath = new FilePath(gitDir);
    git = Git.with(listener, envVars).in(gitDir).getClient();

    // finally: initialize the repo
    git.init();
  }
예제 #3
0
 @CheckForNull
 @Override
 protected SCMRevision retrieve(@NonNull SCMHead head, @NonNull TaskListener listener)
     throws IOException, InterruptedException {
   String cacheEntry = getCacheEntry();
   Lock cacheLock = getCacheLock(cacheEntry);
   cacheLock.lock();
   try {
     File cacheDir = getCacheDir(cacheEntry);
     Git git =
         Git.with(listener, new EnvVars(System.getenv()))
             .in(cacheDir)
             .using(GitTool.getDefaultInstallation().getGitExe());
     GitClient client = git.getClient();
     client.addDefaultCredentials(getCredentials());
     if (!client.hasGitRepo()) {
       listener.getLogger().println("Creating git repository in " + cacheDir);
       client.init();
     }
     String remoteName = getRemoteName();
     listener.getLogger().println("Setting " + remoteName + " to " + getRemote());
     client.setRemoteUrl(remoteName, getRemote());
     listener.getLogger().println("Fetching " + remoteName + "...");
     List<RefSpec> refSpecs = getRefSpecs();
     client.fetch(remoteName, refSpecs.toArray(new RefSpec[refSpecs.size()]));
     // we don't prune remotes here, as we just want one head's revision
     for (Branch b : client.getRemoteBranches()) {
       String branchName = StringUtils.removeStart(b.getName(), remoteName + "/");
       if (branchName.equals(head.getName())) {
         return new SCMRevisionImpl(head, b.getSHA1String());
       }
     }
     return null;
   } finally {
     cacheLock.unlock();
   }
 }
  public Map<String, String> generateContents(AbstractProject<?, ?> project, GitSCM git)
      throws IOException, InterruptedException {

    Map<String, String> paramList = new LinkedHashMap<String, String>();
    // for (AbstractProject<?,?> project :
    // Hudson.getInstance().getItems(AbstractProject.class)) {
    if (project.getSomeWorkspace() == null) {
      this.errorMessage = "noWorkspace";
    }

    EnvVars environment = null;

    try {
      environment = project.getSomeBuildWithWorkspace().getEnvironment(TaskListener.NULL);
    } catch (Exception e) {
    }

    for (RemoteConfig repository : git.getRepositories()) {
      LOGGER.log(
          Level.INFO,
          "generateContents contenttype " + type + " RemoteConfig " + repository.getURIs());
      for (URIish remoteURL : repository.getURIs()) {
        GitClient newgit =
            git.createClient(
                TaskListener.NULL, environment, new Run(project) {}, project.getSomeWorkspace());
        FilePath wsDir = null;
        if (project.getSomeBuildWithWorkspace() != null) {
          wsDir = project.getSomeBuildWithWorkspace().getWorkspace();
          if (wsDir == null || !wsDir.exists()) {
            LOGGER.log(
                Level.WARNING, "generateContents create wsDir " + wsDir + " for " + remoteURL);
            wsDir.mkdirs();
            if (!wsDir.exists()) {
              LOGGER.log(Level.SEVERE, "generateContents wsDir.mkdirs() failed.");
              String errMsg = "!Failed To Create Workspace";
              return Collections.singletonMap(errMsg, errMsg);
            }
            newgit.init();
            newgit.clone(remoteURL.toASCIIString(), "origin", false, null);
            LOGGER.log(Level.INFO, "generateContents clone done");
          }
        } else {
          // probably our first build. We cannot yet fill in any
          // values.
          LOGGER.log(Level.INFO, "getSomeBuildWithWorkspace is null");
          String errMsg = "!No workspace. Please build the project at least once";
          return Collections.singletonMap(errMsg, errMsg);
        }

        long time = -System.currentTimeMillis();
        FetchCommand fetch = newgit.fetch_().from(remoteURL, repository.getFetchRefSpecs());
        fetch.execute();
        LOGGER.finest("Took " + (time + System.currentTimeMillis()) + "ms to fetch");
        if (type.equalsIgnoreCase(PARAMETER_TYPE_REVISION)) {
          List<ObjectId> oid;

          if (this.branch != null && !this.branch.isEmpty()) {
            oid = newgit.revList(this.branch);
          } else {
            oid = newgit.revListAll();
          }

          for (ObjectId noid : oid) {
            Revision r = new Revision(noid);
            paramList.put(r.getSha1String(), prettyRevisionInfo(newgit, r));
          }
        }
        if (type.equalsIgnoreCase(PARAMETER_TYPE_TAG)
            || type.equalsIgnoreCase(PARAMETER_TYPE_TAG_BRANCH)) {

          Set<String> tagSet = newgit.getTagNames(tagFilter);
          ArrayList<String> orderedTagNames;

          if (this.getSortMode().getIsSorting()) {
            orderedTagNames = sortByName(tagSet);
            if (this.getSortMode().getIsDescending()) Collections.reverse(orderedTagNames);
          } else {
            orderedTagNames = new ArrayList<String>(tagSet);
          }

          for (String tagName : orderedTagNames) {
            paramList.put(tagName, tagName);
          }
        }
        if (type.equalsIgnoreCase(PARAMETER_TYPE_BRANCH)
            || type.equalsIgnoreCase(PARAMETER_TYPE_TAG_BRANCH)) {
          time = -System.currentTimeMillis();
          Set<String> branchSet = new HashSet<String>();
          final boolean wildcard = "*".equals(branchfilter);
          for (Branch branch : newgit.getRemoteBranches()) {
            // It'd be nice if we could filter on remote branches via the GitClient,
            // but that's not an option.
            final String branchName = branch.getName();
            if (wildcard || branchName.matches(branchfilter)) {
              branchSet.add(branchName);
            }
          }
          LOGGER.finest("Took " + (time + System.currentTimeMillis()) + "ms to fetch branches");

          time = -System.currentTimeMillis();
          List<String> orderedBranchNames;
          if (this.getSortMode().getIsSorting()) {
            orderedBranchNames = sortByName(branchSet);
            if (this.getSortMode().getIsDescending()) Collections.reverse(orderedBranchNames);
          } else {
            orderedBranchNames = new ArrayList<String>(branchSet);
          }

          for (String branchName : orderedBranchNames) {
            paramList.put(branchName, branchName);
          }
          LOGGER.finest(
              "Took " + (time + System.currentTimeMillis()) + "ms to sort and add to param list.");
        }
      }
      break;
    }
    return paramList;
  }
예제 #5
0
  @NonNull
  @Override
  protected void retrieve(@NonNull final SCMHeadObserver observer, @NonNull TaskListener listener)
      throws IOException, InterruptedException {
    String cacheEntry = getCacheEntry();
    Lock cacheLock = getCacheLock(cacheEntry);
    cacheLock.lock();
    try {
      File cacheDir = getCacheDir(cacheEntry);
      Git git =
          Git.with(listener, new EnvVars(System.getenv()))
              .in(cacheDir)
              .using(GitTool.getDefaultInstallation().getGitExe());
      GitClient client = git.getClient();
      client.addDefaultCredentials(getCredentials());
      if (!client.hasGitRepo()) {
        listener.getLogger().println("Creating git repository in " + cacheDir);
        client.init();
      }
      String remoteName = getRemoteName();
      listener.getLogger().println("Setting " + remoteName + " to " + getRemote());
      client.setRemoteUrl(remoteName, getRemote());
      listener.getLogger().println("Fetching " + remoteName + "...");
      List<RefSpec> refSpecs = getRefSpecs();
      client.fetch(remoteName, refSpecs.toArray(new RefSpec[refSpecs.size()]));
      listener.getLogger().println("Pruning stale remotes...");
      final Repository repository = client.getRepository();
      try {
        client.prune(new RemoteConfig(repository.getConfig(), remoteName));
      } catch (UnsupportedOperationException e) {
        e.printStackTrace(listener.error("Could not prune stale remotes"));
      } catch (URISyntaxException e) {
        e.printStackTrace(listener.error("Could not prune stale remotes"));
      }
      listener.getLogger().println("Getting remote branches...");
      SCMSourceCriteria branchCriteria = getCriteria();
      RevWalk walk = new RevWalk(repository);
      try {
        walk.setRetainBody(false);
        for (Branch b : client.getRemoteBranches()) {
          if (!b.getName().startsWith(remoteName + "/")) {
            continue;
          }
          final String branchName = StringUtils.removeStart(b.getName(), remoteName + "/");
          listener.getLogger().println("Checking branch " + branchName);
          if (isExcluded(branchName)) {
            continue;
          }
          if (branchCriteria != null) {
            RevCommit commit = walk.parseCommit(b.getSHA1());
            final long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime());
            final RevTree tree = commit.getTree();
            SCMSourceCriteria.Probe probe =
                new SCMSourceCriteria.Probe() {
                  @Override
                  public String name() {
                    return branchName;
                  }

                  @Override
                  public long lastModified() {
                    return lastModified;
                  }

                  @Override
                  public boolean exists(@NonNull String path) throws IOException {
                    TreeWalk tw = TreeWalk.forPath(repository, path, tree);
                    try {
                      return tw != null;
                    } finally {
                      if (tw != null) {
                        tw.release();
                      }
                    }
                  }
                };
            if (branchCriteria.isHead(probe, listener)) {
              listener.getLogger().println("Met criteria");
            } else {
              listener.getLogger().println("Does not meet criteria");
              continue;
            }
          }
          SCMHead head = new SCMHead(branchName);
          SCMRevision hash = new SCMRevisionImpl(head, b.getSHA1String());
          observer.observe(head, hash);
          if (!observer.isObserving()) {
            return;
          }
        }
      } finally {
        walk.dispose();
      }

      listener.getLogger().println("Done.");
    } finally {
      cacheLock.unlock();
    }
  }