@Before
  public void setup() throws Exception {
    client = mock(IClient.class);
    server = mock(IServer.class);
    repository = mock(P4JavaPerforceRepository.class);
    baseDir = new File("src/test/resources");
    fileSpecsToAdd = new ArrayList<IFileSpec>();
    fileSpecsAdded = new ArrayList<IFileSpec>();
    scmFilesAdded = new ArrayList<ScmFile>();
    parameters = new CommandParameters();
    files = new ArrayList<File>();
    addCommand = new P4JavaPerforceAddCommand();
    scmFileSet = mock(ScmFileSet.class);

    // P4Java Repository
    when(repository.getPerforceServer()).thenReturn(server);
    when(repository.getWorkspace(server, baseDir)).thenReturn(client);
    when(server.getCurrentClient()).thenReturn(client);
    when(repository.transformFiles(files)).thenReturn(fileSpecsToAdd);
    when(repository.transformFileSpec(fileSpecsAdded)).thenReturn(scmFilesAdded);

    // SCM File Set
    when(scmFileSet.getBasedir()).thenReturn(baseDir);
    when(scmFileSet.getFileList()).thenReturn(files);

    parameters.setString(CommandParameter.BINARY, "false");
    parameters.setString(CommandParameter.MESSAGE, "Hi.");
  }
  /** {@inheritDoc} */
  protected ScmResult executeAddCommand(
      ScmProviderRepository repository, ScmFileSet fileSet, String message, boolean binary)
      throws ScmException {
    Commandline cl = new Commandline();
    cl.setExecutable(accurevExecutable);
    cl.setWorkingDirectory(fileSet.getBasedir().getPath());
    cl.addArguments(new String[] {"add"});
    ArrayList params = new ArrayList();
    AccuRevScmProvider.appendHostToParamsIfNeeded(
        (AccuRevScmProviderRepository) repository, params);
    cl.addArguments((String[]) params.toArray(new String[params.size()]));

    cl.addArguments(makeFileArgs(fileSet.getFileList()));

    final List filesAdded = new ArrayList();
    final CommandLineUtils.StringStreamConsumer stdout =
        new CommandLineUtils.StringStreamConsumer();
    try {
      if (0
          != CommandLineUtils.executeCommandLine(
              cl, new AddCommandStreamConsumer(stdout, filesAdded), stdout)) {
        return new AddScmResult(cl.toString(), null, stdout.getOutput(), false);
      }
    } catch (CommandLineException e) {
      throw new ScmRepositoryException("Cannot exeucute add command", e);
    }
    return new AddScmResult(cl.toString(), filesAdded);
  }
  /** {@inheritDoc} */
  protected ScmResult executeEditCommand(ScmProviderRepository repository, ScmFileSet fileSet)
      throws ScmException {
    if (getLogger().isDebugEnabled()) {
      getLogger().debug("executing edit command...");
    }

    SynergyScmProviderRepository repo = (SynergyScmProviderRepository) repository;

    if (getLogger().isDebugEnabled()) {
      getLogger().debug("basedir: " + fileSet.getBasedir());
    }

    String ccmAddr = SynergyUtil.start(getLogger(), repo.getUser(), repo.getPassword(), null);

    try {
      String projectSpec =
          SynergyUtil.getWorkingProject(
              getLogger(), repo.getProjectSpec(), repo.getUser(), ccmAddr);
      File waPath = SynergyUtil.getWorkArea(getLogger(), projectSpec, ccmAddr);
      File sourcePath = new File(waPath, repo.getProjectName());
      if (projectSpec == null) {
        throw new ScmException("You should checkout project first");
      }
      int taskNum =
          SynergyUtil.createTask(
              getLogger(),
              "Maven SCM Synergy provider: edit command for project " + repo.getProjectSpec(),
              repo.getProjectRelease(),
              true,
              ccmAddr);
      if (getLogger().isInfoEnabled()) {
        getLogger().info("Task " + taskNum + " was created to perform checkout.");
      }
      for (Iterator i = fileSet.getFileList().iterator(); i.hasNext(); ) {
        File f = (File) i.next();
        File dest = f;
        File source = new File(sourcePath, SynergyUtil.removePrefix(fileSet.getBasedir(), f));
        List list = new LinkedList();
        list.add(source);
        SynergyUtil.checkoutFiles(getLogger(), list, ccmAddr);
        if (!source.equals(dest)) {
          if (getLogger().isDebugEnabled()) {
            getLogger().debug("Copy file [" + source + "] to expected folder [" + dest + "].");
          }
          try {
            FileUtils.copyFile(source, dest);
          } catch (IOException e) {
            throw new ScmException("Unable to copy file from Work Area", e);
          }
        }
      }
    } finally {
      SynergyUtil.stop(getLogger(), ccmAddr);
    }

    return new EditScmResult("", fileSet.getFileList());
  }
Example #4
0
  /** {@inheritDoc} */
  protected ExportScmResult executeExportCommand(
      ScmProviderRepository repo, ScmFileSet fileSet, ScmVersion version, String outputDirectory)
      throws ScmException {

    if (outputDirectory == null) {
      outputDirectory = fileSet.getBasedir().getAbsolutePath();
    }

    SvnScmProviderRepository repository = (SvnScmProviderRepository) repo;

    String url = repository.getUrl();

    if (version != null && StringUtils.isNotEmpty(version.getName())) {
      if (version instanceof ScmTag) {
        url = SvnTagBranchUtils.resolveTagUrl(repository, (ScmTag) version);
      } else if (version instanceof ScmBranch) {
        url = SvnTagBranchUtils.resolveBranchUrl(repository, (ScmBranch) version);
      }
    }

    url = SvnCommandUtils.fixUrl(url, repository.getUser());

    Commandline cl =
        createCommandLine(
            (SvnScmProviderRepository) repo, fileSet.getBasedir(), version, url, outputDirectory);

    SvnUpdateConsumer consumer = new SvnUpdateConsumer(getLogger(), fileSet.getBasedir());

    CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();

    if (getLogger().isInfoEnabled()) {
      getLogger().info("Executing: " + SvnCommandLineUtils.cryptPassword(cl));
      if (cl.getWorkingDirectory() != null) {
        getLogger().info("Working directory: " + cl.getWorkingDirectory().getAbsolutePath());
      }
    }

    int exitCode;

    try {
      exitCode = SvnCommandLineUtils.execute(cl, consumer, stderr, getLogger());
    } catch (CommandLineException ex) {
      throw new ScmException("Error while executing command.", ex);
    }

    if (exitCode != 0) {
      return new ExportScmResult(
          cl.toString(), "The svn command failed.", stderr.getOutput(), false);
    }

    return new ExportScmResultWithRevision(
        cl.toString(), consumer.getUpdatedFiles(), String.valueOf(consumer.getRevision()));
  }
  public static Commandline createCommandLine(
      PerforceScmProviderRepository repo, File workingDirectory, ScmFileSet files) {
    Commandline command = PerforceScmProvider.createP4Command(repo, workingDirectory);

    command.createArg().setValue("edit");

    try {
      String candir = workingDirectory.getCanonicalPath();
      List fs = files.getFileList();
      for (int i = 0; i < fs.size(); i++) {
        File file = (File) fs.get(i);
        // I want to use relative paths to add files to make testing
        // simpler.
        // Otherwise the absolute path will be different on everyone's
        // machine
        // and testing will be a little more painful.
        String canfile = file.getCanonicalPath();
        if (canfile.startsWith(candir)) {
          canfile = canfile.substring(candir.length() + 1);
        }
        command.createArg().setValue(canfile);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return command;
  }
  /** {@inheritDoc} */
  protected ScmResult executeEditCommand(ScmProviderRepository repo, ScmFileSet files)
      throws ScmException {
    Commandline cl =
        createCommandLine((PerforceScmProviderRepository) repo, files.getBasedir(), files);
    PerforceEditConsumer consumer = new PerforceEditConsumer();
    try {
      if (getLogger().isDebugEnabled()) {
        getLogger().debug(PerforceScmProvider.clean("Executing " + cl.toString()));
      }

      CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer();
      int exitCode = CommandLineUtils.executeCommandLine(cl, consumer, err);

      if (exitCode != 0) {
        String cmdLine = CommandLineUtils.toString(cl.getCommandline());

        StringBuffer msg = new StringBuffer("Exit code: " + exitCode + " - " + err.getOutput());
        msg.append('\n');
        msg.append("Command line was:" + cmdLine);

        throw new CommandLineException(msg.toString());
      }
    } catch (CommandLineException e) {
      if (getLogger().isErrorEnabled()) {
        getLogger().error("CommandLineException " + e.getMessage(), e);
      }
    }

    if (consumer.isSuccess()) {
      return new EditScmResult(cl.toString(), consumer.getEdits());
    }

    return new EditScmResult(
        cl.toString(), "Unable to edit file(s)", consumer.getErrorMessage(), false);
  }
 /** {@inheritDoc} */
 @Override
 protected ScmResult executeCommand(
     ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters parameters)
     throws ScmException {
   return executeLockCommand(
       repository, fileSet.getBasedir(), parameters.getString(CommandParameter.FILE));
 }
  @Override
  public BlameScmResult executeBlameCommand(
      ScmProviderRepository repo, ScmFileSet workingDirectory, String filename)
      throws ScmException {
    Commandline cl = new Commandline();
    cl.setWorkingDirectory(workingDirectory.getBasedir());
    cl.setExecutable(EXECUTABLE);
    cl.createArg().setValue(filename);

    TfsBlameConsumer consumer = new TfsBlameConsumer(getLogger());
    CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();

    try {
      int exitCode = CommandLineUtils.executeCommandLine(cl, consumer, stderr);

      if (exitCode != 0) {
        return new BlameScmResult(
            cl.toString(),
            "The "
                + EXECUTABLE
                + " command failed. Did you install https://github.com/SonarCommunity/sonar-tfs ?",
            stderr.getOutput(),
            false);
      }
    } catch (CommandLineException ex) {
      throw new ScmException("Error while executing command.", ex);
    }

    return new BlameScmResult(cl.toString(), consumer.getLines());
  }
Example #9
0
  protected MkdirScmResult executeMkdirCommand(
      ScmProviderRepository repository, ScmFileSet fileSet, String message, boolean createInLocal)
      throws ScmException {
    LocalScmProviderRepository repo = (LocalScmProviderRepository) repository;
    List<ScmFile> createdDirs = new ArrayList<ScmFile>();

    // create/commit the directory directly in the repository
    if (!createInLocal) {
      File file = (File) fileSet.getFileList().get(0);
      File modulePath = new File(repo.getRoot(), repo.getModule());
      File dir = new File(modulePath, file.getName());

      if (dir.exists()) {
        return new MkdirScmResult(
            null, "Directory already exists!", "Directory already exists.", false);
      } else {
        if (getLogger().isInfoEnabled()) {
          getLogger().info("Creating directory in '" + modulePath.getAbsolutePath() + "'");
        }

        FileUtils.mkdir(dir.getAbsolutePath());
        createdDirs.add(new ScmFile(dir.getPath(), ScmFileStatus.ADDED));
      }
    } else {
      // add the directory, but not commit
      LocalAddCommand addCmd = new LocalAddCommand();
      addCmd.setLogger(getLogger());

      CommandParameters parameters = new CommandParameters();
      parameters.setString(CommandParameter.MESSAGE, message);
      parameters.setString(CommandParameter.BINARY, "false");

      String path = ((File) fileSet.getFileList().get(0)).getPath();
      if (repo.isFileAdded(path)) {
        return new MkdirScmResult(
            null, "Directory already exists!", "Directory already exists.", false);
      }

      AddScmResult result = (AddScmResult) addCmd.execute(repository, fileSet, parameters);
      createdDirs.addAll(result.getAddedFiles());
    }

    return new MkdirScmResult(null, createdDirs);
  }
Example #10
0
  protected ScmResult executeTagCommand(
      ScmProviderRepository r, ScmFileSet f, String tag, ScmTagParameters scmTagParameters)
      throws ScmException {
    TfsCommand command = createCommand(r, f, tag, scmTagParameters);

    StringStreamConsumer out = new StringStreamConsumer();
    ErrorStreamConsumer err = new ErrorStreamConsumer();

    int status = command.execute(out, err);
    if (status != 0 || err.hasBeenFed()) {
      return new TagScmResult(
          command.getCommandString(),
          "Error code for TFS label command - " + status,
          err.getOutput(),
          false);
    }
    List<ScmFile> files = new ArrayList<ScmFile>(f.getFileList().size());
    for (File file : f.getFileList()) {
      files.add(new ScmFile(file.getPath(), ScmFileStatus.TAGGED));
    }
    return new TagScmResult(command.getCommandString(), files);
  }
  /** {@inheritDoc} */
  protected ScmResult executeAddCommand(
      ScmProviderRepository repository, ScmFileSet fileSet, String message, boolean binary)
      throws ScmException {
    LocalScmProviderRepository localRepo = (LocalScmProviderRepository) repository;

    File[] files = fileSet.getFiles();
    List fileList = new ArrayList();
    for (int i = 0; i < files.length; i++) {
      String path = files[i].getPath().replace('\\', '/');
      localRepo.addFile(path);
      fileList.add(new ScmFile(path, ScmFileStatus.ADDED));
    }

    // TODO: Also, ensure it is tested from the update test
    return new AddScmResult(null, fileList);
  }
 /** {@inheritDoc} */
 @Override
 public CheckInScmResult executeCheckInCommand(
     ScmProviderRepository repository, ScmFileSet fileSet, String message, ScmVersion scmVersion)
     throws ScmException {
   getLogger()
       .info(
           "Attempting to check-in updates from sandbox "
               + fileSet.getBasedir().getAbsolutePath());
   IntegrityScmProviderRepository iRepo = (IntegrityScmProviderRepository) repository;
   Sandbox siSandbox = iRepo.getSandbox();
   List<ScmFile> changedFiles = siSandbox.checkInUpdates(message);
   if (siSandbox.getOverallCheckInSuccess()) {
     return new CheckInScmResult("si ci/drop", changedFiles);
   } else {
     return new CheckInScmResult(
         changedFiles,
         new ScmResult("si ci/drop", "There was a problem updating the repository", "", false));
   }
 }
 /** {@inheritDoc} */
 @Override
 public UpdateScmResult executeUpdateCommand(
     ScmProviderRepository repository, ScmFileSet fileSet, ScmVersion scmVersion)
     throws ScmException {
   getLogger()
       .info("Attempting to synchronize sandbox in " + fileSet.getBasedir().getAbsolutePath());
   List<ScmFile> updatedFiles = new ArrayList<ScmFile>();
   IntegrityScmProviderRepository iRepo = (IntegrityScmProviderRepository) repository;
   Sandbox siSandbox = iRepo.getSandbox();
   try {
     // Make sure we've got a valid sandbox, otherwise create it...
     if (siSandbox.create()) {
       Response res = siSandbox.resync();
       // Lets capture what we got from running this resync
       WorkItemIterator wit = res.getWorkItems();
       while (wit.hasNext()) {
         WorkItem wi = wit.next();
         if (wi.getModelType().equals(SIModelTypeName.MEMBER)) {
           Result message = wi.getResult();
           getLogger()
               .debug(wi.getDisplayId() + " " + (null != message ? message.getMessage() : ""));
           if (null != message && message.getMessage().length() > 0) {
             updatedFiles.add(
                 new ScmFile(
                     wi.getDisplayId(),
                     message.getMessage().equalsIgnoreCase("removed")
                         ? ScmFileStatus.DELETED
                         : ScmFileStatus.UPDATED));
           }
         }
       }
       return new UpdateScmResult(res.getCommandString(), updatedFiles);
     } else {
       return new UpdateScmResult("si resync", "Failed to synchronize workspace", "", false);
     }
   } catch (APIException aex) {
     ExceptionHandler eh = new ExceptionHandler(aex);
     getLogger().error("MKS API Exception: " + eh.getMessage());
     getLogger().info(eh.getCommand() + " exited with return code " + eh.getExitCode());
     return new UpdateScmResult(
         eh.getCommand(), eh.getMessage(), "Exit Code: " + eh.getExitCode(), false);
   }
 }