public List<Workspace> call() throws Exception {
    final Server server = createServer();
    final MockableVersionControlClient vcc = server.getVersionControlClient();
    final TaskListener listener = server.getListener();
    final PrintStream logger = listener.getLogger();

    final String listWorkspacesMessage = String.format(ListingWorkspacesTemplate, server.getUrl());
    logger.println(listWorkspacesMessage);

    final com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace[] sdkWorkspaces =
        vcc.queryWorkspaces(
            null, null, Util.fixEmpty(computer), WorkspacePermissions.NONE_OR_NOT_SUPPORTED);

    final List<Workspace> result = new ArrayList<Workspace>(sdkWorkspaces.length);
    for (final com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace sdkWorkspace :
        sdkWorkspaces) {
      final String name = sdkWorkspace.getName();
      final String computer = sdkWorkspace.getComputer();
      final String ownerName = sdkWorkspace.getOwnerName();
      final String comment = Util.fixNull(sdkWorkspace.getComment());

      final Workspace workspace = new Workspace(name, computer, ownerName, comment);
      result.add(workspace);
    }

    log(result, logger);

    return result;
  }
 /** {@inheritDoc} */
 @Override
 protected SCMRevision retrieve(String unparsedRevision, TaskListener listener)
     throws IOException, InterruptedException {
   try {
     listener.getLogger().println("Opening connection to " + remoteBase);
     SVNURL repoURL = SVNURL.parseURIEncoded(remoteBase);
     SVNRepositoryView repository = openSession(repoURL);
     String repoPath =
         SubversionSCM.DescriptorImpl.getRelativePath(repoURL, repository.getRepository());
     String base;
     long revision;
     Matcher pathAtRev = Pattern.compile("(.+)@(\\d+)").matcher(unparsedRevision);
     if (pathAtRev.matches()) {
       base = pathAtRev.group(1);
       revision = Long.parseLong(pathAtRev.group(2));
     } else {
       base = unparsedRevision;
       revision = -1;
     }
     String path = SVNPathUtil.append(repoPath, base);
     long resolvedRevision = repository.getNode(path, -1).getRevision();
     if (resolvedRevision == -1) {
       listener.getLogger().println("Could not find " + path);
       return null;
     }
     return new SCMRevisionImpl(new SCMHead(base), revision == -1 ? resolvedRevision : revision);
   } catch (SVNException e) {
     throw new IOException(e);
   }
 }
示例#3
0
  /**
   * Fetch information from a particular remote repository. Attempt to fetch from submodules, if
   * they exist in the local WC
   *
   * @param git
   * @param listener
   * @param remoteRepository
   * @throws
   */
  private void fetchFrom(
      IGitAPI git, File workspace, TaskListener listener, RemoteConfig remoteRepository) {
    try {
      listener.getLogger().println("Fetching from " + remoteRepository.getName());
      git.fetch(remoteRepository);

      List<IndexEntry> submodules = new GitUtils(listener, git).getSubmodules("HEAD");

      for (IndexEntry submodule : submodules) {
        try {
          RemoteConfig submoduleRemoteRepository =
              getSubmoduleRepository(remoteRepository, submodule.getFile());

          File subdir = new File(workspace, submodule.getFile());
          IGitAPI subGit =
              new GitAPI(git.getGitExe(), new FilePath(subdir), listener, git.getEnvironment());

          subGit.fetch(submoduleRemoteRepository);
        } catch (Exception ex) {
          listener.error(
              "Problem fetching from "
                  + remoteRepository.getName()
                  + " - could be unavailable. Continuing anyway");
        }
      }
    } catch (GitException ex) {
      listener.error(
          "Problem fetching from "
              + remoteRepository.getName()
              + " / "
              + remoteRepository.getName()
              + " - could be unavailable. Continuing anyway");
    }
  }
 /** {@inheritDoc} */
 public void addIdentity(String privateKey, final String passphrase, String comment)
     throws IOException {
   if (!SecurityUtils.isBouncyCastleRegistered()) {
     throw new IllegalStateException("BouncyCastle must be registered as a JCE provider");
   }
   try {
     PEMReader r =
         new PEMReader(
             new StringReader(privateKey),
             passphrase == null
                 ? null
                 : new PasswordFinder() {
                   public char[] getPassword() {
                     return passphrase.toCharArray();
                   }
                 });
     try {
       Object o = r.readObject();
       if (o instanceof KeyPair) {
         agent.getAgent().addIdentity((KeyPair) o, comment);
       }
     } finally {
       r.close();
     }
   } catch (Exception e) {
     listener.getLogger().println(Messages.SSHAgentBuildWrapper_UnableToReadKey(e.getMessage()));
     e.printStackTrace(listener.getLogger());
   }
 }
 @Override
 protected void launch(EC2Computer computer, TaskListener listener, Instance inst)
     throws AmazonClientException, IOException, InterruptedException {
   int processedTime = 0;
   JIException exception = null;
   // TODO 自動生成されたメソッド・スタブ
   this.host = getHostName(computer);
   while (TIMEOUT > processedTime) {
     try {
       wmiLaunch(computer, listener);
       return;
     } catch (JIException e) {
       listener.getLogger().println("Waiting for DCOM to come up. Sleeping " + WAIT);
       Thread.sleep(WAIT * 1000);
       processedTime += WAIT * 1000;
       exception = e;
     }
   }
   // if not return, then print error.
   if (exception.getErrorCode() == 5) {
     // access denied error
     exception.printStackTrace(
         listener.error(Messages.ManagedWindowsServiceLauncher_AccessDenied()));
   } else {
     exception.printStackTrace(listener.error(exception.getMessage()));
   }
 }
  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());
    }
  }
示例#7
0
 private void listenerWarnOrError(TaskListener listener, String message) {
   if (allowEmptyArchive) {
     listener.getLogger().println(String.format("WARN: %s", message));
   } else {
     listener.error(message);
   }
 }
  /** {@inheritDoc} */
  @NonNull
  @Override
  protected void retrieve(@NonNull final SCMHeadObserver observer, @NonNull TaskListener listener)
      throws IOException {
    SVNRepositoryView repository = null;
    try {
      listener.getLogger().println("Opening conection to " + remoteBase);
      SVNURL repoURL = SVNURL.parseURIEncoded(remoteBase);
      repository = openSession(repoURL);

      String repoPath =
          SubversionSCM.DescriptorImpl.getRelativePath(repoURL, repository.getRepository());
      List<String> prefix = Collections.emptyList();
      fetch(
          listener,
          repository,
          -1,
          repoPath,
          toPaths(splitCludes(includes)),
          prefix,
          prefix,
          toPaths(splitCludes(excludes)),
          getCriteria(),
          observer);
    } catch (SVNException e) {
      e.printStackTrace(listener.error("Could not communicate with Subversion server"));
      throw new IOException(e);
    } finally {
      closeSession(repository);
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see hudson.FilePath.FileCallable#invoke(java.io.File,
   *      hudson.remoting.VirtualChannel)
   */
  public Boolean invoke(File workspace, VirtualChannel channel) throws IOException {

    File localCheckoutPath = new File(workspace, destinationpath);
    StarTeamConnection connection =
        new StarTeamConnection(
            hostname, port, user, passwd, projectname, viewname, foldername, config);
    try {
      connection.initialize();
    } catch (StarTeamSCMException e) {
      listener.getLogger().println(e.getLocalizedMessage());
      connection.close();
      return false;
    }

    StarTeamChangeSet changeSet = null;
    try {
      changeSet =
          connection.computeChangeSet(
              connection.getRootFolder(),
              localCheckoutPath,
              historicFilePoints,
              listener.getLogger());
    } catch (StarTeamSCMException e) {
      e.printStackTrace(listener.getLogger());
    }
    connection.close();
    if (changeSet != null && changeSet.hasChanges()) {
      return true;
    }
    return false;
  }
示例#10
0
文件: SU.java 项目: Chi721/jenkins
    VirtualChannel start(TaskListener listener, String rootPassword)
        throws IOException, InterruptedException {
      final int uid = LIBC.geteuid();

      if (uid == 0) // already running as root
      return newLocalChannel();

      String javaExe = System.getProperty("java.home") + "/bin/java";
      File slaveJar = Which.jarFile(Launcher.class);

      ArgumentListBuilder args = new ArgumentListBuilder().add(javaExe);
      if (slaveJar.isFile()) args.add("-jar").add(slaveJar);
      else // in production code this never happens, but during debugging this is convenientud
      args.add("-cp").add(slaveJar).add(hudson.remoting.Launcher.class.getName());

      if (rootPassword == null) {
        // try sudo, in the hope that the user has the permission to do so without password
        return new LocalLauncher(listener)
            .launchChannel(
                args.prepend(sudoExe()).toCommandArray(),
                listener.getLogger(),
                null,
                Collections.<String, String>emptyMap());
      } else {
        // try sudo with the given password. Also run in pfexec so that we can elevate the
        // privileges
        Process proc = sudoWithPass(args);
        return Channels.forProcess(
            args.toStringWithQuote(), Computer.threadPoolForRemoting, proc, listener.getLogger());
      }
    }
示例#11
0
  public void setBuildOpts(Workspace workspace) throws AbortException {

    ClientHelper p4 = new ClientHelper(credential, listener, client);

    try {
      // setup the client workspace to use for the build.
      if (!p4.setClient(workspace)) {
        String err = "Undefined workspace: " + workspace.getFullName();
        logger.severe(err);
        listener.error(err);
        throw new AbortException(err);
      }

      // fetch and calculate change to sync to or review to unshelve.
      status = getStatus(workspace);
      head = p4.getClientHead();
      review = getReview(workspace);
      buildChange = getBuildChange(workspace);

    } catch (Exception e) {
      String err = "Unable to setup workspace: " + e;
      logger.severe(err);
      listener.error(err);
      throw new AbortException(err);
    } finally {
      p4.disconnect();
    }
  }
  @Override
  public void run() {
    ReviewInput reviewInput = createReview();

    String reviewEndpoint = resolveEndpointURL();

    HttpPost httpPost = createHttpPostEntity(reviewInput, reviewEndpoint);

    if (httpPost == null) {
      return;
    }

    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient
        .getCredentialsProvider()
        .setCredentials(
            new AuthScope(null, -1),
            new UsernamePasswordCredentials(
                config.getGerritHttpUserName(), config.getGerritHttpPassword()));
    try {
      HttpResponse httpResponse = httpclient.execute(httpPost);
      String response = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");
      listener.getLogger().print(response);
      if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        listener.error(httpResponse.getStatusLine().getReasonPhrase());
      }
    } catch (Exception e) {
      listener.error("Failed to submit result", e);
    }
  }
  @Override
  public void perform(Run build, FilePath workspace, Launcher launcher, TaskListener listener)
      throws InterruptedException, IOException {
    listener.getLogger().println(Messages.JUnitResultArchiver_Recording());

    final String testResults = build.getEnvironment(listener).expand(this.testResults);

    TestResult result = parse(testResults, build, workspace, launcher, listener);

    synchronized (build) {
      // TODO can the build argument be omitted now, or is it used prior to the call to addAction?
      TestResultAction action = build.getAction(TestResultAction.class);
      boolean appending;
      if (action == null) {
        appending = false;
        action = new TestResultAction(build, result, listener);
      } else {
        appending = true;
        result.freeze(action);
        action.mergeResult(result, listener);
      }
      action.setHealthScaleFactor(getHealthScaleFactor()); // overwrites previous value if appending
      if (result.isEmpty()) {
        if (build.getResult() == Result.FAILURE) {
          // most likely a build failed before it gets to the test phase.
          // don't report confusing error message.
          return;
        }
        if (this.allowEmptyResults) {
          // User allow empty results
          listener.getLogger().println(Messages.JUnitResultArchiver_ResultIsEmpty());
          return;
        }
        // most likely a configuration error in the job - e.g. false pattern to match the JUnit
        // result files
        throw new AbortException(Messages.JUnitResultArchiver_ResultIsEmpty());
      }

      // TODO: Move into JUnitParser [BUG 3123310]
      List<Data> data = action.getData();
      if (testDataPublishers != null) {
        for (TestDataPublisher tdp : testDataPublishers) {
          Data d = tdp.contributeTestData(build, workspace, launcher, listener, result);
          if (d != null) {
            data.add(d);
          }
        }
      }

      if (appending) {
        build.save();
      } else {
        build.addAction(action);
      }

      if (action.getResult().getFailCount() > 0) build.setResult(Result.UNSTABLE);
    }
  }
示例#14
0
  @Override
  public void perform(Run<?, ?> build, FilePath ws, Launcher launcher, TaskListener listener)
      throws InterruptedException {
    if (artifacts.length() == 0) {
      listener.error(Messages.ArtifactArchiver_NoIncludes());
      build.setResult(Result.FAILURE);
      return;
    }

    if (onlyIfSuccessful
        && build.getResult() != null
        && build.getResult().isWorseThan(Result.UNSTABLE)) {
      listener.getLogger().println(Messages.ArtifactArchiver_SkipBecauseOnlyIfSuccessful());
      return;
    }

    listener.getLogger().println(Messages.ArtifactArchiver_ARCHIVING_ARTIFACTS());
    try {
      String artifacts = build.getEnvironment(listener).expand(this.artifacts);

      Map<String, String> files =
          ws.act(new ListFiles(artifacts, excludes, defaultExcludes, caseSensitive));
      if (!files.isEmpty()) {
        build
            .pickArtifactManager()
            .archive(ws, launcher, BuildListenerAdapter.wrap(listener), files);
        if (fingerprint) {
          new Fingerprinter(artifacts).perform(build, ws, launcher, listener);
        }
      } else {
        Result result = build.getResult();
        if (result != null && result.isBetterOrEqualTo(Result.UNSTABLE)) {
          // If the build failed, don't complain that there was no matching artifact.
          // The build probably didn't even get to the point where it produces artifacts.
          listenerWarnOrError(listener, Messages.ArtifactArchiver_NoMatchFound(artifacts));
          String msg = null;
          try {
            msg =
                ws.validateAntFileMask(
                    artifacts, FilePath.VALIDATE_ANT_FILE_MASK_BOUND, caseSensitive);
          } catch (Exception e) {
            listenerWarnOrError(listener, e.getMessage());
          }
          if (msg != null) listenerWarnOrError(listener, msg);
        }
        if (!allowEmptyArchive) {
          build.setResult(Result.FAILURE);
        }
        return;
      }
    } catch (IOException e) {
      Util.displayIOException(e, listener);
      e.printStackTrace(listener.error(Messages.ArtifactArchiver_FailedToArchive(artifacts)));
      build.setResult(Result.FAILURE);
      return;
    }
  }
示例#15
0
 public String call() throws IOException {
   File home = new File(mvnHome);
   if (MavenProcessFactory.debug) listener.getLogger().println("Using mvnHome: " + mvnHome);
   File bootDir = new File(home, "boot");
   File[] classworlds = bootDir.listFiles(CLASSWORLDS_FILTER);
   if (classworlds == null || classworlds.length == 0) {
     listener.error(Messages.MavenProcessFactory_ClassWorldsNotFound(home));
     throw new RunnerAbortedException();
   }
   return classworlds[0].getAbsolutePath();
 }
    private void install(Computer c, TaskListener listener) {
        try {
            final List<SlaveRestarter> restarters = new ArrayList<SlaveRestarter>(SlaveRestarter.all());

            VirtualChannel ch = c.getChannel();
            if (ch==null) return;  // defensive check

            List<SlaveRestarter> effective = ch.call(new Callable<List<SlaveRestarter>, IOException>() {
                public List<SlaveRestarter> call() throws IOException {
                    Engine e = Engine.current();
                    if (e == null) return null;    // not running under Engine

                    try {
                        Engine.class.getMethod("addListener", EngineListener.class);
                    } catch (NoSuchMethodException _) {
                        return null;    // running with older version of remoting that doesn't support adding listener
                    }

                    // filter out ones that doesn't apply
                    for (Iterator<SlaveRestarter> itr = restarters.iterator(); itr.hasNext(); ) {
                        SlaveRestarter r =  itr.next();
                        if (!r.canWork())
                            itr.remove();
                    }

                    e.addListener(new EngineListenerAdapter() {
                        @Override
                        public void onDisconnect() {
                            try {
                                for (SlaveRestarter r : restarters) {
                                    try {
                                        LOGGER.info("Restarting slave via "+r);
                                        r.restart();
                                    } catch (Exception x) {
                                        LOGGER.log(SEVERE, "Failed to restart slave with "+r, x);
                                    }
                                }
                            } finally {
                                // if we move on to the reconnection without restart,
                                // don't let the current implementations kick in when the slave loses connection again
                                restarters.clear();
                            }
                        }
                    });

                    return restarters;
                }
            });

            listener.getLogger().println("Effective SlaveRestarter on " + c.getDisplayName() + ": " + effective);
        } catch (Throwable e) {
            e.printStackTrace(listener.error("Failed to install restarter"));
        }
    }
示例#17
0
  /** Performs tagging. */
  public void perform(String tagName, TaskListener listener) {
    File destdir = null;
    try {
      destdir = Util.createTempDir();

      // unzip the archive
      listener
          .getLogger()
          .println(hudson.scm.cvs.Messages.CVSSCM_ExpandingWorkspaceArchive(destdir));
      Expand e = new Expand();
      e.setProject(new org.apache.tools.ant.Project());
      e.setDest(destdir);
      e.setSrc(CVSSCM.getArchiveFile(build));
      e.setTaskType("unzip");
      e.execute();

      // run cvs tag command
      listener.getLogger().println(hudson.scm.cvs.Messages.CVSSCM_TaggingWorkspace());
      for (ModuleLocation moduleLocation : scmInstance.getModuleLocations()) {
        @SuppressWarnings("unchecked")
        ModuleLocation parametrizedLocation =
            new ParametrizedModuleLocationImpl(moduleLocation, build.getBuildVariables());
        for (String module : parametrizedLocation.getNormalizedModules()) {
          if (!createTag(
              tagName,
              listener,
              destdir,
              parametrizedLocation.getLocalDir(),
              module,
              scmInstance.isFlatten())) {
            return;
          }
        }
      }

      // completed successfully
      onTagCompleted(tagName);
      build.save();
    } catch (Throwable e) {
      e.printStackTrace(listener.fatalError(e.getMessage()));
    } finally {
      try {
        if (destdir != null) {
          listener.getLogger().println("cleaning up " + destdir);
          Util.deleteRecursive(destdir);
        }
      } catch (IOException e) {
        e.printStackTrace(listener.fatalError(e.getMessage()));
      }
    }
  }
示例#18
0
 @Override
 public void decorateCloneCommand(
     GitSCM scm, Run<?, ?> build, GitClient git, TaskListener listener, CloneCommand cmd)
     throws IOException, InterruptedException, GitException {
   if (shallow) {
     listener.getLogger().println("Using shallow clone");
     cmd.shallow();
   }
   if (noTags) {
     listener.getLogger().println("Avoid fetching tags");
     cmd.tags(false);
   }
   cmd.timeout(timeout);
   cmd.reference(build.getEnvironment(listener).expand(reference));
 }
示例#19
0
  /**
   * **************************************************
   *
   * <p>private int joinWithPossibleTimeout(ProcStarter proc, final TaskListener listener,
   * StringBuffer strBuf, AbstractBuild currentBuild) throws IOException, InterruptedException
   *
   * <p>**************************************************
   */
  protected int joinWithPossibleTimeout(
      ProcStarter proc,
      final TaskListener listener,
      StringBuffer strBuf,
      AbstractBuild currentBuild,
      String stringToHide)
      throws IOException, InterruptedException {
    boolean useTimeout = configuration.isUseTimeout();
    long timeoutValue = configuration.getTimeoutValue();

    int result = -1;

    try {
      PipedInputStream pis = null;
      if (strBuf != null) {
        PipedOutputStream pos = new PipedOutputStream();
        pis = new PipedInputStream(pos, 1000000);
        proc = proc.stdout(pos);
      }

      hudson.Proc procStarted = proc.start();
      if (useTimeout) {
        result = procStarted.joinWithTimeout(timeoutValue, TimeUnit.SECONDS, listener);
      } else {
        result = procStarted.join();
      }

      if (strBuf != null) {
        byte[] stdoutDataArr = new byte[pis.available()];
        pis.read(stdoutDataArr, 0, stdoutDataArr.length);
        String stdoutStr = new String(stdoutDataArr);
        if (stringToHide != null) {
          stdoutStr = stdoutStr.replaceAll(stringToHide, "****");
        }
        strBuf.append(stdoutStr);
        PrintStream output = listener.getLogger();
        output.println(stdoutStr);
      }
    } catch (InterruptedException e) {
      throw e;
    } catch (Exception e) {
      if (listener != null) {
        listener.error("Exception caught in joinWithPossibleTimeout: " + e);
      }
    }

    return result;
  } // End: joinWithPossibleTimeout(...)
  private GroovyShell createEngine(AbstractBuild<?, ?> build, TaskListener listener) {

    ClassLoader cl = Jenkins.getInstance().getPluginManager().uberClassLoader;
    ScriptSandbox sandbox = null;
    CompilerConfiguration cc = new CompilerConfiguration();
    cc.addCompilationCustomizers(
        new ImportCustomizer()
            .addStarImports("jenkins", "jenkins.model", "hudson", "hudson.model"));

    ExtendedEmailPublisher publisher =
        build.getProject().getPublishersList().get(ExtendedEmailPublisher.class);
    if (publisher.getDescriptor().isSecurityEnabled()) {
      cc.addCompilationCustomizers(new SandboxTransformer());
      sandbox = new ScriptSandbox();
    }

    Binding binding = new Binding();
    binding.setVariable("build", build);
    binding.setVariable("project", build.getParent());
    binding.setVariable("rooturl", publisher.getDescriptor().getHudsonUrl());
    binding.setVariable("out", listener.getLogger());

    GroovyShell shell = new GroovyShell(cl, binding, cc);

    if (sandbox != null) {
      sandbox.register();
    }

    return shell;
  }
 public Object invoke(File ws, VirtualChannel channel) throws IOException, InterruptedException {
   File workingCopy = new File(ws, location.getLocalDir()).getCanonicalFile();
   try {
     SVNURL svnUrl = SVNURL.parseURIEncoded(tagUrl);
     ISVNAuthenticationManager sam = SVNWCUtil.createDefaultAuthenticationManager();
     sam.setAuthenticationProvider(authProvider);
     SVNCopyClient copyClient = new SVNCopyClient(sam, null);
     buildListener.getLogger().println("[RELEASE] Creating subversion tag: " + tagUrl);
     SVNCopySource source =
         new SVNCopySource(SVNRevision.WORKING, SVNRevision.WORKING, workingCopy);
     SVNCommitInfo commitInfo =
         copyClient.doCopy(
             new SVNCopySource[] {source},
             svnUrl,
             false,
             true,
             true,
             commitMessage,
             new SVNProperties());
     SVNErrorMessage errorMessage = commitInfo.getErrorMessage();
     if (errorMessage != null) {
       throw new IOException("Failed to create tag: " + errorMessage.getFullMessage());
     }
     return null;
   } catch (SVNException e) {
     throw new IOException("Subversion tag creation failed: " + e.getMessage());
   }
 }
 public Object invoke(File ws, VirtualChannel channel) throws IOException, InterruptedException {
   File workingCopy = new File(ws, location.getLocalDir()).getCanonicalFile();
   try {
     ISVNAuthenticationManager sam = SVNWCUtil.createDefaultAuthenticationManager();
     sam.setAuthenticationProvider(authProvider);
     SVNCommitClient commitClient = new SVNCommitClient(sam, null);
     buildListener.getLogger().println("[RELEASE] " + commitMessage);
     debuggingLogger.fine(String.format("Committing working copy: '%s'", workingCopy));
     SVNCommitInfo commitInfo =
         commitClient.doCommit(
             new File[] {workingCopy},
             true,
             commitMessage,
             null,
             null,
             true,
             true,
             SVNDepth.INFINITY);
     SVNErrorMessage errorMessage = commitInfo.getErrorMessage();
     if (errorMessage != null) {
       throw new IOException("Failed to commit working copy: " + errorMessage.getFullMessage());
     }
     return null;
   } catch (SVNException e) {
     throw new IOException(e.getMessage());
   }
 }
示例#23
0
  private boolean createTag(
      String tagName,
      TaskListener listener,
      File destdir,
      String moduleLocalDir,
      String module,
      boolean isFlatten)
      throws IOException, InterruptedException {
    FilePath path =
        (isFlatten
            ? new FilePath(destdir).child(module)
            : new FilePath(destdir).child(moduleLocalDir).child(module));
    boolean isDir = path.isDirectory();

    ArgumentListBuilder cmd = new ArgumentListBuilder();
    cmd.add(scmInstance.getDescriptor().getCvsExeOrDefault(), "tag");
    if (isDir) {
      cmd.add("-R");
    }
    cmd.add(tagName);
    if (!isDir) {
      cmd.add(path.getName());
      path = path.getParent();
    }

    if (!scmInstance.run(new Launcher.LocalLauncher(listener), cmd, listener, path)) {
      listener.getLogger().println(Messages.CVSSCM_TaggingFailed());
      return false;
    }
    return true;
  }
示例#24
0
  /** Runs the command and captures the output. */
  public String popen(
      FilePath repository, TaskListener listener, boolean useTimeout, ArgumentListBuilder args)
      throws IOException, InterruptedException {
    args = seed().add(args.toCommandArray());

    ByteArrayOutputStream rev = new ByteArrayOutputStream();
    if (MercurialSCM.joinWithPossibleTimeout(
            l(args).pwd(repository).stdout(rev), useTimeout, listener)
        == 0) {
      return rev.toString();
    } else {
      listener.error("Failed to run " + args.toStringWithQuote());
      listener.getLogger().write(rev.toByteArray());
      throw new AbortException();
    }
  }
  public void onBuildComplete(AbstractBuild<?, ?> build, TaskListener listener, GHRepository repo)
      throws GhprcCommitStatusException {

    GHCommitState state = Ghprc.getState(build);

    StringBuilder sb = new StringBuilder();

    if (completedStatus == null || completedStatus.isEmpty()) {
      sb.append("Build finished.");
    } else {
      for (GhprcBuildResultMessage buildStatus : completedStatus) {
        sb.append(buildStatus.postBuildComment(build, listener));
      }
    }

    sb.append(" ");
    GhprcTrigger trigger = Ghprc.extractTrigger(build);
    if (trigger == null) {
      listener.getLogger().println("Unable to get pull request builder trigger!!");
    } else {
      JobConfiguration jobConfiguration =
          JobConfiguration.builder()
              .printStackTrace(trigger.isDisplayBuildErrorsOnDownstreamBuilds())
              .build();

      GhprcBuildManager buildManager =
          GhprcBuildManagerFactoryUtil.getBuildManager(build, jobConfiguration);
      sb.append(buildManager.getOneLineTestResults());
    }

    createCommitStatus(build, listener, sb.toString(), repo, state);
  }
  protected void makeCombination(Map<IndexEntry, Revision> settings) {
    // Assume we are checked out
    String name = "combine-" + tid + "-" + (idx++);
    git.branch(name);
    git.checkout(name);

    String commit = "Hudson generated combination of:\n";

    for (IndexEntry submodule : settings.keySet()) {
      Revision branch = settings.get(submodule);
      commit += "  " + submodule.getFile() + " " + branch.toString() + "\n";
    }

    listener.getLogger().print(commit);

    for (IndexEntry submodule : settings.keySet()) {
      Revision branch = settings.get(submodule);
      File subdir = new File(workspace, submodule.getFile());
      IGitAPI subGit =
          new GitAPI(git.getGitExe(), new FilePath(subdir), listener, git.getEnvironment());

      subGit.checkout(branch.sha1.name());
      git.add(submodule.file);
    }

    git.commit(commit);
  }
示例#27
0
  /**
   * **************************************************
   *
   * <p>private Map<String, JazzChangeSet> accept(Collection<String> changeSets) throws IOException,
   * InterruptedException {
   *
   * <p>**************************************************
   */
  private Map<String, JazzChangeSet> accept(Collection<String> changeSets)
      throws IOException, InterruptedException {
    // output to console.
    PrintStream output = listener.getLogger();
    output.println("  RTC SCM - Jazz Client: Accept...");
    String version =
        getVersion(); // TODO The version should be checked when configuring the Jazz Executable

    String[] streams = configuration.getStreamNames();
    Map<String, JazzChangeSet> returnObject = new LinkedHashMap<String, JazzChangeSet>();

    for (int i = 0; i < streams.length; i++) {
      configuration.setStreamIndex(i);
      AcceptCommand cmd =
          new AcceptCommand(configuration, changeSets, version, listener, jazzExecutable);
      Map<String, JazzChangeSet> acceptResults = execute(cmd);
      // for debugging
      /*
         output.println("DEBUG: results of calling accept...");
         for (String key : acceptResults.keySet()) {
      output.println("DEBUG: accept key = " + key + ": " + acceptResults.get(key).toStringDetails());
         }
         */

      returnObject.putAll(acceptResults);
    }

    return returnObject;
  }
示例#28
0
  /**
   * An attempt to generate at least semi-useful EnvVars for polling calls, based on previous build.
   * Cribbed from various places.
   */
  public static EnvVars getPollEnvironment(
      AbstractProject p, FilePath ws, Launcher launcher, TaskListener listener)
      throws IOException, InterruptedException {
    EnvVars env;

    AbstractBuild b = (AbstractBuild) p.getLastBuild();

    if (b != null) {
      Node lastBuiltOn = b.getBuiltOn();

      if (lastBuiltOn != null) {
        env = lastBuiltOn.toComputer().getEnvironment().overrideAll(b.getCharacteristicEnvVars());
      } else {
        env = new EnvVars(System.getenv());
      }

      String rootUrl = Hudson.getInstance().getRootUrl();
      if (rootUrl != null) {
        env.put("HUDSON_URL", rootUrl);
        env.put("BUILD_URL", rootUrl + b.getUrl());
        env.put("JOB_URL", rootUrl + p.getUrl());
      }

      if (!env.containsKey("HUDSON_HOME")) {
        env.put("HUDSON_HOME", Hudson.getInstance().getRootDir().getPath());
      }

      if (ws != null) {
        env.put("WORKSPACE", ws.getRemote());
      }

      p.getScm().buildEnvVars(b, env);

      StreamBuildListener buildListener =
          new StreamBuildListener((OutputStream) listener.getLogger());

      for (NodeProperty nodeProperty : Hudson.getInstance().getGlobalNodeProperties()) {
        Environment environment = nodeProperty.setUp(b, launcher, (BuildListener) buildListener);
        if (environment != null) {
          environment.buildEnvVars(env);
        }
      }

      if (lastBuiltOn != null) {
        for (NodeProperty nodeProperty : lastBuiltOn.getNodeProperties()) {
          Environment environment = nodeProperty.setUp(b, launcher, buildListener);
          if (environment != null) {
            environment.buildEnvVars(env);
          }
        }
      }

      EnvVars.resolve(env);
    } else {
      env = new EnvVars(System.getenv());
    }

    return env;
  }
示例#29
0
 protected void perform(TaskListener listener) {
   for (Map.Entry<AbstractBuild, String> e : tagSet.entrySet()) {
     TagAction ta = e.getKey().getAction(TagAction.class);
     if (ta == null) {
       listener.error(e.getKey() + " doesn't have CVS tag associated with it. Skipping");
       continue;
     }
     listener.getLogger().println(Messages.CVSSCM_TagginXasY(e.getKey(), e.getValue()));
     try {
       e.getKey().keepLog();
     } catch (IOException x) {
       x.printStackTrace(listener.error(Messages.CVSSCM_FailedToMarkForKeep(e.getKey())));
     }
     ta.perform(e.getValue(), listener);
     listener.getLogger().println();
   }
 }
 private String getWspFilter(AbstractBuild<?, ?> build, TaskListener listener) {
   try {
     return TokenMacro.expandAll(build, listener, getWspFilter());
   } catch (Exception e) {
     listener.error("failed to expand tokens in: %s%n", getWspFilter());
   }
   return getWspFilter();
 }