Package com.tek42.perforce.model

Examples of com.tek42.perforce.model.User


   * @return
   * @throws PerforceException
   */
  public Workspace getWorkspace(String ws_name, String stream_name) throws PerforceException {
    WorkspaceBuilder builder = new WorkspaceBuilder();
    Workspace workspace;
    if (stream_name != null && !stream_name.equals("")) {
        workspace = builder.build(getPerforceResponse(builder.getBuildCmd(getP4Exe(), ws_name, stream_name)));
    }
    else {
        workspace = builder.build(getPerforceResponse(builder.getBuildCmd(getP4Exe(), ws_name)));
View Full Code Here


        try {
            // keep projectPath local so any modifications for slaves don't get saved
            String effectiveProjectPath= getEffectiveProjectPath(build,
                    build.getProject(), build.getBuiltOn(), log, depot);

            Workspace p4workspace = getPerforceWorkspace(build.getProject(), effectiveProjectPath, depot, build.getBuiltOn(), build, launcher, workspace, listener, false);

            boolean dirtyWorkspace = p4workspace.isDirty();
            saveWorkspaceIfDirty(depot, p4workspace, log);

            //Wipe/clean workspace
            String p4config;
            WipeWorkspaceExcludeFilter wipeFilter;
            try {
                p4config = MacroStringHelper.substituteParameters("${P4CONFIG}", this, build, null);
                wipeFilter = new WipeWorkspaceExcludeFilter(".p4config",p4config);
            } catch (ParameterSubstitutionException ex) {
                wipeFilter = new WipeWorkspaceExcludeFilter();
            }
                   
            if (wipeBeforeBuild || quickCleanBeforeBuild) {
                long cleanStartTime = System.currentTimeMillis();
                if (wipeRepoBeforeBuild) {
                    log.println("Clear workspace includes .repository ...");                   
                } else {
                    log.println("Note: .repository directory in workspace (if exists) is skipped during clean.");
                    wipeFilter.exclude(".repository");
                }
                if (wipeBeforeBuild) {
                    log.println("Wiping workspace...");
                    List<FilePath> workspaceDirs = workspace.list(wipeFilter);
                    for (FilePath dir : workspaceDirs) {
                        dir.deleteRecursive();
                    }
                    log.println("Wiped workspace.");
                    forceSync = true;
                }
                if (quickCleanBeforeBuild) {
                    QuickCleaner quickCleaner = new QuickCleaner(depot.getExecutable(), depot.getP4Ticket(), launcher, depot, workspace, wipeFilter);
                    log.println("Quickly cleaning workspace...");
                    quickCleaner.doClean();
                    log.println("Workspace is clean.");
                    if (restoreChangedDeletedFiles) {
                        log.println("Restoring changed and deleted files...");
                        quickCleaner.doRestore();
                        log.println("Files restored.");
                    }
                }
                long cleanEndTime = System.currentTimeMillis();
                long cleanDuration = cleanEndTime - cleanStartTime;

                log.println("Clean complete, took " + cleanDuration + " ms");
            }
           
            // In case of a stream depot, we want Perforce to handle the client views. So let's re-initialize
            // the p4workspace object if it was changed since the last build. Also, populate projectPath with
            // the current view from Perforce. We need it for labeling.
            if (useStreamDepot) {
                if (dirtyWorkspace) {
                    // Support for concurrent builds
                    String p4Client = getConcurrentClientName(workspace, getEffectiveClientName(build, null));
                    p4workspace = depot.getWorkspaces().getWorkspace(p4Client, p4Stream);
                }
                effectiveProjectPath = p4workspace.getTrimmedViewsAsString();
            }
            // If we're not managing the view, populate the projectPath with the current view from perforce
            // This is both for convenience, and so the labeling mechanism can operate correctly
            if (!updateView) {
                effectiveProjectPath = p4workspace.getTrimmedViewsAsString();
            }

            String p4WorkspacePath = "//" + p4workspace.getName() + "/...";
            int lastChange = getLastChange((Run)build.getPreviousBuild());
            log.println("Last build changeset: " + lastChange);

            // Determine changeset number
            int newestChange = lastChange;

            List<Changelist> changes;
            if (p4Label != null && !p4Label.trim().isEmpty()) {
                newestChange = depot.getChanges().getHighestLabelChangeNumber(p4workspace, p4Label.trim(), p4WorkspacePath);
            } else {
                if (p4UpstreamProject != null && p4UpstreamProject.length() > 0) {
                    log.println("Using last successful or unstable build of upstream project " + p4UpstreamProject);
                    Job job = Hudson.getInstance().getItemByFullName(p4UpstreamProject, Job.class);
                    if (job == null) {
                        throw new AbortException(
                                "Configured upstream job does not exist anymore: " + p4UpstreamProject + ". Please update your job configuration.");
                    }
                    Run upStreamRun = job.getLastSuccessfulBuild();
                    int lastUpStreamChange = getLastChangeNoFirstChange(upStreamRun);
                    if (lastUpStreamChange > 0) {
                        log.println("Using P4 revision " + lastUpStreamChange + " from upstream project " + p4UpstreamProject);
                        newestChange = lastUpStreamChange;
                    } else {
                        log.println("No P4 revision found in upstream project " + p4UpstreamProject);
                        throw new AbortException(
                                "Configured upstream job has not been run yet: " + p4UpstreamProject + ". Please run it once befor launching a new build.");
                    }
                } else
                if (p4Counter != null && !updateCounterValue) {
                    //use a counter
                    String counterName;
                    counterName = MacroStringHelper.substituteParameters(this.p4Counter, this, build, null);
                    Counter counter = depot.getCounters().getCounter(counterName);
                    newestChange = counter.getValue();
                } else {
                    //use the latest submitted change from workspace, or depot
                    try {
                        List<Integer> workspaceChanges = depot.getChanges().getChangeNumbers(p4WorkspacePath, 0, 1);
                        if (workspaceChanges != null && workspaceChanges.size() > 0) {
                            newestChange = workspaceChanges.get(0);
                        } else {
                            List<Integer> depotChanges = depot.getChanges().getChangeNumbers("//...", 0, 1);
                            if (depotChanges != null && depotChanges.size() > 0) {
                                newestChange = depotChanges.get(0);
                            }
                        }
                    } catch (PerforceException e) {
                        //fall back onto 'change' counter value
                        log.println("Failed to get last submitted changeset in the view, falling back to change counter. Error was: " + e.getMessage());
                        Counter counter = depot.getCounters().getCounter("change");
                        newestChange = counter.getValue();
                    }
                }
            }

            // Set newestChange down to the next available changeset if we're building one change at a time
            if (oneChangelistOnly && build.getPreviousBuild() != null
                    && lastChange > 0 && newestChange > lastChange) {
                List<Integer> workspaceChanges = depot.getChanges().getChangeNumbersInRange(
                        p4workspace, lastChange+1, newestChange, viewMask, showIntegChanges);
                for (int i = workspaceChanges.size()-1; i >= 0; --i) {
                    int changeNumber = workspaceChanges.get(i);
                    Changelist changelist = depot.getChanges().getChangelist(changeNumber, fileLimit);
                    if (!isChangelistExcluded(changelist, build.getProject(), build.getBuiltOn(), p4workspace.getViewsAsString(), log)) {
                        newestChange = changeNumber;
                        break;
                    }
                    log.println("Changelist "+changeNumber+" is composed of file(s) and/or user(s) that are excluded.");
                }
View Full Code Here

            } else {
                depot = getDepot(buildNode.createLauncher(listener),buildNode.getRootPath(),project,null, buildNode);
                logger.println("Using node: " + buildNode.getDisplayName());
            }

            Workspace p4workspace = getPerforceWorkspace(project, getEffectiveProjectPath(null, project, buildNode, logger, depot), depot, buildNode, null, launcher, workspace, listener, true);
            saveWorkspaceIfDirty(depot, p4workspace, logger);

            int lastChangeNumber = baseline.getRevision();
            SCMRevisionState repositoryState = getCurrentDepotRevisionState(p4workspace, project, buildNode, depot, logger, lastChangeNumber);
View Full Code Here

        depot.setClient(effectiveP4Client);
        String effectiveP4Stream = MacroStringHelper.substituteParameters(this.p4Stream, this, build, project, buildNode, null);

        // Get the clientspec (workspace) from perforce
        Workspace p4workspace = depot.getWorkspaces().getWorkspace(effectiveP4Client, effectiveP4Stream);
        assert p4workspace != null;
        boolean creatingNewWorkspace = p4workspace.isNew();

        // If the client workspace doesn't exist, and we're not managing the clients,
        // Then terminate the build with an error
        if (!createWorkspace && creatingNewWorkspace) {
            log.println("*** Perforce client workspace '" + effectiveP4Client +"' doesn't exist.");
            log.println("*** Please create it, or allow Jenkins to manage clients on it's own.");
            log.println("*** If the client name mentioned above is not what you expected, ");
            log.println("*** check your 'Client name format for slaves' advanced config option.");
            throw new AbortException("Error accessing perforce workspace.");
        }

        // Ensure that the clientspec (workspace) name is set correctly
        // TODO Examine why this would be necessary.

        p4workspace.setName(effectiveP4Client);

        // Set the workspace options according to the configuration
        if (projectOptions != null)
            p4workspace.setOptions(projectOptions);

        // Set the line ending option according to the configuration
        if (lineEndValue != null && getAllLineEndChoices().contains(lineEndValue)) {
            p4workspace.setLineEnd(lineEndValue);
        }

        if (clientOwner != null && !clientOwner.trim().isEmpty()) {
            p4workspace.setOwner(clientOwner);
        }

        // Ensure that the root is appropriate (it might be wrong if the user
        // created it, or if we previously built on another node).

        // Both launcher and workspace can be null if requiresWorkspaceForPolling returns true
        // So provide 'reasonable' default values.
        boolean isunix = true;
        if (launcher != null)
            isunix = launcher.isUnix();

        String localPath = unescapeP4String(p4workspace.getRoot());

        if (workspace != null)
            localPath = getLocalPathName(workspace, isunix);
        else if (localPath.trim().equals(""))
            localPath = project.getRootDir().getAbsolutePath();
        localPath = escapeP4String(localPath);

        if (!localPath.equals(p4workspace.getRoot()) && !dontChangeRoot && !dontUpdateClient) {
            log.println("Changing P4 Client Root to: " + localPath);
            forceSync = true;
            p4workspace.setRoot(localPath);
        }

        if (updateView || creatingNewWorkspace) {
            // Switch to another stream view if necessary
            if (useStreamDepot) {
                p4workspace.setStream(effectiveP4Stream);
            }
            // If necessary, rewrite the views field in the clientspec. Also, clear the stream.
            // TODO If dontRenameClient==false, and updateView==false, user
            // has a lot of work to do to maintain the clientspecs.  Seems like
            // we could copy from a master clientspec to the slaves.
            else {
                p4workspace.setStream("");
                if (useClientSpec) {
                    projectPath = getEffectiveProjectPathFromFile(build, project, buildNode, log, depot);
                }
                List<String> mappingPairs = parseProjectPath(projectPath, effectiveP4Client, log);
                if (!equalsProjectPath(mappingPairs, p4workspace.getViews())) {
                    log.println("Changing P4 Client View from:\n" + p4workspace.getViewsAsString());
                    log.println("Changing P4 Client View to: ");
                    p4workspace.clearViews();
                    for (int i = 0; i < mappingPairs.size(); ) {
                        String depotPath = mappingPairs.get(i++);
                        String clientPath = mappingPairs.get(i++);
                        p4workspace.addView(" " + depotPath + " " + clientPath);
                        log.println("  " + depotPath + " " + clientPath);
                    }
                }
            }
        }
        // Clean host field so the client can be used on other slaves
        // such as those operating with the workspace on a network share
        p4workspace.setHost("");

        // NOTE: The workspace is not saved.
        return p4workspace;
    }
View Full Code Here

       
        try {
            Depot depot = getDepot(launcher, workspace, project, null, node);
            final String effectiveProjectPath = MacroStringHelper.substituteParameters(
                    projectPath, this, project, node, null);
            Workspace p4workspace = getPerforceWorkspace(
                project,
                effectiveProjectPath,
                depot,
                node,
                null,
View Full Code Here

                return FormValidation.ok();

            Depot depot = getDepotFromRequest(req);
            if (depot != null) {
                try {
                    Counters counters = depot.getCounters();
                    Counter p4Counter = counters.getCounter(counter);
                    // try setting the counter back to the same value to verify permissions
                    counters.saveCounter(p4Counter);
                } catch (PerforceException e) {
                    return FormValidation.error(
                            "Error accessing perforce while checking counter: " + e.getLocalizedMessage());
                }
            }
View Full Code Here

    // TODO Handle the case where p4Label is set.
    private boolean wouldSyncChangeWorkspace(AbstractProject project, Depot depot,
            PrintStream logger) throws IOException, InterruptedException, PerforceException {

        Workspaces workspaces = depot.getWorkspaces();
        String result = workspaces.syncDryRun().toString();

        if (result.startsWith("File(s) up-to-date.")) {
            logger.println("Workspace up-to-date.");
            return false;
        } else {
View Full Code Here

  private Status status;
  private Groups groups;
  private Counters counters;

  public Depot() {
    this(new DefaultExecutorFactory());
  }
View Full Code Here

   * Returns the output created by "p4 info"
   *
   * @return The string output of p4 info
   */
  public String info() throws Exception {
    Executor p4 = getExecFactory().newExecutor();
    String cmd[] = { getExecutable(), "info" };
    p4.exec(cmd);
    StringBuilder sb = new StringBuilder();
    String line;
    while((line = p4.getReader().readLine()) != null) {
      sb.append(line + "\n");
    }
    return sb.toString();
  }
View Full Code Here

    boolean attemptLogin = true;

    //StringBuilder response = new StringBuilder();
    do {
      int mesgIndex = -1;//, count = 0;
      Executor p4 = depot.getExecFactory().newExecutor();
      String debugCmd = "";
      try {
        String cmds[] = getExtraParams(builder.getSaveCmd(getP4Exe(), object));

        // for exception reporting...
        for(String cm : cmds) {
          debugCmd += cm + " ";
        }

        // back to our regularly scheduled programming...
        p4.exec(cmds);
        BufferedReader reader = p4.getReader();

        // Maintain a log of what was sent to p4 on std input
        final StringBuilder log = new StringBuilder();

        // Conditional use of std input for saving the perforce entity
        if(builder.requiresStandardInput()) {
          BufferedWriter writer = p4.getWriter();
          Writer fwriter = new FilterWriter(writer) {
            public void write(String str) throws IOException {
              log.append(str);
              out.write(str);
            }
          };
          builder.save(object, fwriter);
          fwriter.flush();
          fwriter.close();
        }

        String line;
                StringBuilder error = new StringBuilder();
                StringBuilder info = new StringBuilder();
        int exitCode = 0;

        while((line = reader.readLine()) != null) {

          // Check for authentication errors...
            if (mesgIndex == -1)
                mesgIndex = checkAuthnErrors(line);

            if (mesgIndex != -1) {
                error.append(line);

            } else if(line.startsWith("error")) {
            if(!line.trim().equals("") && (line.indexOf("up-to-date") < 0) && (line.indexOf("no file(s) to resolve") < 0)) {
              error.append(line.substring(6));
            }

          } else if(line.startsWith("exit")) {
            exitCode = Integer.parseInt(line.substring(line.indexOf(" ") + 1, line.length()));

          } else {
            if(line.indexOf(":") > -1)
              info.append(line.substring(line.indexOf(":")));
            else
              info.append(line);
          }
        }
        reader.close();

        loop = false;
        // If we failed to execute because of an authentication issue, try a p4 login.
        if(mesgIndex == 1 || mesgIndex == 2 || mesgIndex == 6 || mesgIndex == 9) {
            if (attemptLogin) {
                      // password is unset means that perforce isn't using the environment var P4PASSWD
                      // Instead it is using tickets. We must attempt to login via p4 login, then
                      // retry this cmd.
                      p4.close();
                            trustIfSSL();
                      login();
                      loop = true;
                      attemptLogin = false;
                      mesgIndex = -1; // cancel this error for now
                      continue;
            }
        }
       
        if(mesgIndex != -1 || exitCode != 0) {
          if(error.length() != 0) {
              error.append("\nFor Command: ").append(debugCmd);
              if (log.length() > 0) {
                  error.append("\nWith Data:\n===================\n");
                  error.append(log);
                            error.append("\n===================\n");
              }
                        throw new PerforceException(error.toString());
          }
          throw new PerforceException(info.toString());
        }

      } catch(IOException e) {
        throw new PerforceException("Failed to open connection to perforce", e);
      } finally {
                                try{
                                    p4.getWriter().close();
                                } catch (IOException e) {
                                    //failed to close pipe, but we can't do much about that
                                }
                                try{
                                    p4.getReader().close();
                                } catch (IOException e) {
                                    //failed to close pipe, but we can't do much about that
                                }
        p4.close();
      }
    } while(loop);
  }
View Full Code Here

TOP

Related Classes of com.tek42.perforce.model.User

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.