private Set<String> getRelativePaths(String[] paths) {
   final Set<String> set = new THashSet<String>();
   final String basePath = myProject.getBaseDir().getPath();
   for (String path : paths) {
     set.add(
         StringUtil.trimStart(
             StringUtil.trimStart(FileUtil.toSystemIndependentName(path), basePath), "/"));
   }
   return set;
 }
  @com.intellij.testFramework.Parameterized.Parameters(name = "{0}")
  public static List<Object[]> params(Class<?> klass) throws Throwable {
    final LightPlatformCodeInsightTestCase testCase =
        (LightPlatformCodeInsightTestCase) klass.newInstance();
    if (!(testCase instanceof FileBasedTestCaseHelper)) {
      fail("Parameterized test should implement FileBasedTestCaseHelper");
    }

    try {
      PathManagerEx.replaceLookupStrategy(klass, com.intellij.testFramework.Parameterized.class);
    } catch (IllegalArgumentException ignore) {
      // allow to run out of idea project
    }

    final FileBasedTestCaseHelper fileBasedTestCase = (FileBasedTestCaseHelper) testCase;
    String testDataPath = testCase.getTestDataPath();

    File testDir = null;
    if (fileBasedTestCase instanceof FileBasedTestCaseHelperEx) {
      testDir =
          new File(
              testDataPath, ((FileBasedTestCaseHelperEx) fileBasedTestCase).getRelativeBasePath());
    } else {
      final TestDataPath annotation = klass.getAnnotation(TestDataPath.class);
      if (annotation == null) {
        fail(
            "TestCase should implement com.intellij.testFramework.FileBasedTestCaseHelperEx or be annotated with com.intellij.testFramework.TestDataPath");
      } else {
        final String trimmedRoot =
            StringUtil.trimStart(
                StringUtil.trimStart(annotation.value(), "$CONTENT_ROOT"), "$PROJECT_ROOT");
        final String lastPathComponent = new File(testDataPath).getName();
        final int idx = trimmedRoot.indexOf(lastPathComponent);
        testDataPath =
            testDataPath.replace(File.separatorChar, '/')
                + (idx > 0 ? trimmedRoot.substring(idx + lastPathComponent.length()) : trimmedRoot);
        testDir = new File(testDataPath);
      }
    }

    final File[] files = testDir.listFiles();

    if (files == null) {
      fail("Test files not found in " + testDir.getPath());
    }

    final List<Object[]> result = new ArrayList<Object[]>();
    for (File file : files) {
      final String fileSuffix = fileBasedTestCase.getFileSuffix(file.getName());
      if (fileSuffix != null) {
        result.add(new Object[] {fileSuffix, testDataPath});
      }
    }
    return result;
  }
  private static void assertOrder(PsiJavaFile file, @NonNls String... expectedOrder) {
    PsiImportStatementBase[] statements = file.getImportList().getAllImportStatements();

    assertEquals(expectedOrder.length, statements.length);
    for (int i = 0; i < statements.length; i++) {
      PsiImportStatementBase statement = statements[i];
      String text = StringUtil.trimEnd(StringUtil.trimStart(statement.getText(), "import "), ";");
      assertEquals(expectedOrder[i], text);
    }
  }
Ejemplo n.º 4
0
 public static String getTestName(String name, boolean lowercaseFirstLetter) {
   if (name == null) {
     return "";
   }
   name = StringUtil.trimStart(name, "test");
   if (StringUtil.isEmpty(name)) {
     return "";
   }
   return lowercaseFirstLetter(name, lowercaseFirstLetter);
 }
 @Override
 public String getName() {
   final String fieldName = myField.name();
   if (isOuterLocalVariableValue()
       && NodeRendererSettings.getInstance()
           .getClassRenderer()
           .SHOW_VAL_FIELDS_AS_LOCAL_VARIABLES) {
     return StringUtil.trimStart(fieldName, OUTER_LOCAL_VAR_FIELD_PREFIX);
   }
   return fieldName;
 }
Ejemplo n.º 6
0
  public static boolean processElementsByRelativePath(
      @NotNull final CompositePackagingElement<?> parent,
      @NotNull String relativePath,
      @NotNull final PackagingElementResolvingContext context,
      @NotNull final ArtifactType artifactType,
      @NotNull PackagingElementPath parentPath,
      @NotNull final PackagingElementProcessor<PackagingElement<?>> processor) {
    relativePath = StringUtil.trimStart(relativePath, "/");
    if (relativePath.length() == 0) {
      return true;
    }

    int i = relativePath.indexOf('/');
    final String firstName = i != -1 ? relativePath.substring(0, i) : relativePath;
    final String tail = i != -1 ? relativePath.substring(i + 1) : "";

    return processElementsWithSubstitutions(
        parent.getChildren(),
        context,
        artifactType,
        parentPath.appendComposite(parent),
        new PackagingElementProcessor<PackagingElement<?>>() {
          @Override
          public boolean process(
              @NotNull PackagingElement<?> element, @NotNull PackagingElementPath path) {
            boolean process = false;
            if (element instanceof CompositePackagingElement
                && firstName.equals(((CompositePackagingElement<?>) element).getName())) {
              process = true;
            } else if (element instanceof FileCopyPackagingElement) {
              final FileCopyPackagingElement fileCopy = (FileCopyPackagingElement) element;
              if (firstName.equals(fileCopy.getOutputFileName())) {
                process = true;
              }
            }

            if (process) {
              if (tail.length() == 0) {
                if (!processor.process(element, path)) return false;
              } else if (element instanceof CompositePackagingElement<?>) {
                return processElementsByRelativePath(
                    (CompositePackagingElement) element,
                    tail,
                    context,
                    artifactType,
                    path,
                    processor);
              }
            }
            return true;
          }
        });
  }
 private static String suggestNewName(Project project, PsiVariable variable) {
   // new name should not conflict with another variable at the variable declaration level and
   // usage level
   String name = variable.getName();
   // trim last digit to suggest variable names like i1,i2, i3...
   if (name.length() > 1 && Character.isDigit(name.charAt(name.length() - 1))) {
     name = name.substring(0, name.length() - 1);
   }
   name = "final" + StringUtil.capitalize(StringUtil.trimStart(name, "final"));
   return JavaCodeStyleManager.getInstance(project)
       .suggestUniqueVariableName(name, variable, true);
 }
  @Nullable
  public static List<String> findTestDataFiles(@NotNull DataContext context) {
    final PsiMethod method = findTargetMethod(context);
    if (method == null) {
      return null;
    }
    final String name = method.getName();

    if (name.startsWith("test")) {
      String testDataPath =
          TestDataLineMarkerProvider.getTestDataBasePath(method.getContainingClass());
      final TestDataReferenceCollector collector =
          new TestDataReferenceCollector(testDataPath, name.substring(4));
      return collector.collectTestDataReferences(method);
    }

    final Location<?> location = Location.DATA_KEY.getData(context);
    if (location instanceof PsiMemberParameterizedLocation) {
      PsiClass containingClass = ((PsiMemberParameterizedLocation) location).getContainingClass();
      if (containingClass == null) {
        containingClass =
            PsiTreeUtil.getParentOfType(location.getPsiElement(), PsiClass.class, false);
      }
      if (containingClass != null) {
        final PsiAnnotation annotation =
            AnnotationUtil.findAnnotationInHierarchy(
                containingClass, Collections.singleton(JUnitUtil.RUN_WITH));
        if (annotation != null) {
          final PsiAnnotationMemberValue memberValue = annotation.findAttributeValue("value");
          if (memberValue instanceof PsiClassObjectAccessExpression) {
            final PsiTypeElement operand =
                ((PsiClassObjectAccessExpression) memberValue).getOperand();
            if (operand.getType().equalsToText(Parameterized.class.getName())) {
              final String testDataPath =
                  TestDataLineMarkerProvider.getTestDataBasePath(containingClass);
              final String paramSetName =
                  ((PsiMemberParameterizedLocation) location).getParamSetName();
              final String baseFileName =
                  StringUtil.trimEnd(StringUtil.trimStart(paramSetName, "["), "]");
              final ProjectFileIndex fileIndex =
                  ProjectRootManager.getInstance(containingClass.getProject()).getFileIndex();
              return TestDataGuessByExistingFilesUtil.suggestTestDataFiles(
                  fileIndex, baseFileName, testDataPath, containingClass);
            }
          }
        }
      }
    }

    return null;
  }
Ejemplo n.º 9
0
  @Nullable
  private static String getSingleLineDocCommentsText(final @NotNull PsiComment[] comments) {
    StringBuilder buf = null;

    for (PsiComment comment : comments) {
      if (comment.getNode().getElementType() == DartTokenTypesSets.SINGLE_LINE_DOC_COMMENT) {
        if (buf == null) {
          buf = new StringBuilder();
        } else {
          buf.append('\n');
        }

        final String text = comment.getText();
        if (text.startsWith(SINGLE_LINE_DOC_COMMENT + " ")) {
          buf.append(StringUtil.trimStart(text, SINGLE_LINE_DOC_COMMENT + " "));
        } else {
          buf.append(StringUtil.trimStart(text, SINGLE_LINE_DOC_COMMENT));
        }
      }
    }

    return buf == null ? null : buf.toString();
  }
 // minimum sequence of text replacement operations for each host range
 // result[i] == null means no change
 // result[i] == "" means delete
 // result[i] == string means replace
 public String[] calculateMinEditSequence(String newText) {
   synchronized (myLock) {
     String[] result = new String[myShreds.size()];
     String hostText = myDelegate.getText();
     calculateMinEditSequence(hostText, newText, result, 0, result.length - 1);
     for (int i = 0; i < result.length; i++) {
       String change = result[i];
       if (change == null) continue;
       String prefix = myShreds.get(i).getPrefix();
       String suffix = myShreds.get(i).getSuffix();
       assert change.startsWith(prefix) : change + "/" + prefix;
       assert change.endsWith(suffix) : change + "/" + suffix;
       result[i] = StringUtil.trimEnd(StringUtil.trimStart(change, prefix), suffix);
     }
     return result;
   }
 }
Ejemplo n.º 11
0
  @SuppressWarnings("UseOfSystemOutOrSystemErr")
  private static synchronized void printOrder(Loader loader, String url, Resource resource) {
    if (!ourDumpOrder) return;
    if (!ourOrderedUrls.add(url)) return;

    String home = FileUtil.toSystemIndependentName(PathManager.getHomePath());
    try {
      ourOrderSize += resource.getContentLength();
    } catch (IOException e) {
      e.printStackTrace(System.out);
    }

    if (ourOrder == null) {
      final File orderFile = new File(PathManager.getBinPath() + File.separator + "order.txt");
      try {
        if (!FileUtil.ensureCanCreateFile(orderFile)) return;
        ourOrder = new PrintStream(new FileOutputStream(orderFile, true));
        ShutDownTracker.getInstance()
            .registerShutdownTask(
                new Runnable() {
                  public void run() {
                    ourOrder.close();
                    System.out.println(ourOrderSize);
                  }
                });
      } catch (IOException e) {
        return;
      }
    }

    if (ourOrder != null) {
      String jarURL = FileUtil.toSystemIndependentName(loader.getBaseURL().getFile());
      jarURL = StringUtil.trimStart(jarURL, "file:/");
      if (jarURL.startsWith(home)) {
        jarURL = jarURL.replaceFirst(home, "");
        jarURL = StringUtil.trimEnd(jarURL, "!/");
        ourOrder.println(url + ":" + jarURL);
      }
    }
  }
Ejemplo n.º 12
0
  private static void checkStructure(final SliceNode root, @NonNls String dataExpected) {
    List<SliceNode> actualNodes = new ArrayList<SliceNode>((Collection) root.getChildren());
    Collections.sort(actualNodes, SliceTreeBuilder.SLICE_NODE_COMPARATOR);

    Object[] actualStrings =
        ContainerUtil.map2Array(
            actualNodes,
            new Function<SliceNode, Object>() {
              @Override
              public Object fun(SliceNode node) {
                return node.toString();
              }
            });

    String[] childrenExpected =
        dataExpected.length() == 0 ? ArrayUtil.EMPTY_STRING_ARRAY : dataExpected.split("\n");
    String curChildren = "";
    String curNode = null;
    int iactual = 0;
    for (int iexp = 0; iexp <= childrenExpected.length; iexp++) {
      String e = iexp == childrenExpected.length ? null : childrenExpected[iexp];
      boolean isTopLevel = e == null || e.charAt(0) != ' ';
      if (isTopLevel) {
        if (curNode != null) {
          assertTrue(iactual < actualStrings.length);
          Object actual = actualStrings[iactual];
          assertEquals(curNode, actual);
          checkStructure(actualNodes.get(iactual), curChildren);
          iactual++;
        }

        curNode = e;
        curChildren = "";
      } else {
        curChildren += StringUtil.trimStart(e, "  ") + "\n";
      }
    }
    assertEquals(actualNodes.size(), iactual);
  }
 @Override
 public PsiExpression getDescriptorEvaluation(DebuggerContext context) throws EvaluateException {
   PsiElementFactory elementFactory = JavaPsiFacade.getInstance(myProject).getElementFactory();
   String fieldName;
   if (isStatic()) {
     String typeName = myField.declaringType().name().replace('$', '.');
     typeName =
         DebuggerTreeNodeExpression.normalize(
             typeName, PositionUtil.getContextElement(context), myProject);
     fieldName = typeName + "." + getName();
   } else {
     //noinspection HardCodedStringLiteral
     fieldName =
         isOuterLocalVariableValue()
             ? StringUtil.trimStart(getName(), OUTER_LOCAL_VAR_FIELD_PREFIX)
             : "this." + getName();
   }
   try {
     return elementFactory.createExpressionFromText(fieldName, null);
   } catch (IncorrectOperationException e) {
     throw new EvaluateException(DebuggerBundle.message("error.invalid.field.name", getName()), e);
   }
 }
  @Override
  protected void addModuleLibrary(
      JpsModule rootModel,
      Element element,
      boolean exported,
      String libName,
      String url,
      String srcUrl,
      ExpandMacroToPathMap macroMap) {
    final JpsLibrary jpsLibrary = rootModel.addModuleLibrary(libName, JpsJavaLibraryType.INSTANCE);
    final JpsDependenciesList dependenciesList = rootModel.getDependenciesList();
    final JpsLibraryDependency dependency = dependenciesList.addLibraryDependency(jpsLibrary);
    url = StringUtil.trimStart(url, "file://");
    final String linked = expandLinkedResourcesPath(url, macroMap);
    if (linked != null) {
      url = pathToUrl(linked);
    } else {
      url = expandEclipsePath2Url(rootModel, url);
    }
    LOG.debug("loading " + rootModel.getName() + ": adding module library " + libName + ": " + url);
    jpsLibrary.addRoot(url, JpsOrderRootType.COMPILED);

    setLibraryEntryExported(dependency, exported);
  }
Ejemplo n.º 15
0
 @NotNull
 public static String toAbsolute(@NotNull VirtualFile root, @NotNull String relativePath) {
   return StringUtil.trimEnd(root.getPath(), "/") + "/" + StringUtil.trimStart(relativePath, "/");
 }
 public NamedPackageSetReference(String name) {
   myName = StringUtil.trimStart(name, "$");
 }
Ejemplo n.º 17
0
  public static List<VirtualFile> findSourceFilesByOutputPath(
      CompositePackagingElement<?> parent,
      final String outputPath,
      final PackagingElementResolvingContext context,
      final ArtifactType artifactType) {
    final String path = StringUtil.trimStart(outputPath, "/");
    if (path.length() == 0) {
      return Collections.emptyList();
    }

    int i = path.indexOf('/');
    final String firstName = i != -1 ? path.substring(0, i) : path;
    final String tail = i != -1 ? path.substring(i + 1) : "";

    final List<VirtualFile> result = new SmartList<VirtualFile>();
    processElementsWithSubstitutions(
        parent.getChildren(),
        context,
        artifactType,
        PackagingElementPath.EMPTY,
        new PackagingElementProcessor<PackagingElement<?>>() {
          @Override
          public boolean process(
              @NotNull PackagingElement<?> element, @NotNull PackagingElementPath elementPath) {
            // todo[nik] replace by method findSourceFile() in PackagingElement
            if (element instanceof CompositePackagingElement) {
              final CompositePackagingElement<?> compositeElement =
                  (CompositePackagingElement<?>) element;
              if (firstName.equals(compositeElement.getName())) {
                result.addAll(
                    findSourceFilesByOutputPath(compositeElement, tail, context, artifactType));
              }
            } else if (element instanceof FileCopyPackagingElement) {
              final FileCopyPackagingElement fileCopyElement = (FileCopyPackagingElement) element;
              if (firstName.equals(fileCopyElement.getOutputFileName()) && tail.length() == 0) {
                ContainerUtil.addIfNotNull(fileCopyElement.findFile(), result);
              }
            } else if (element instanceof DirectoryCopyPackagingElement
                || element instanceof ExtractedDirectoryPackagingElement) {
              final VirtualFile sourceRoot =
                  ((FileOrDirectoryCopyPackagingElement<?>) element).findFile();
              if (sourceRoot != null) {
                ContainerUtil.addIfNotNull(sourceRoot.findFileByRelativePath(path), result);
              }
            } else if (element instanceof ModuleOutputPackagingElement) {
              final CompilerConfiguration compilerConfiguration =
                  CompilerConfiguration.getInstance(context.getProject());
              for (VirtualFile sourceRoot :
                  ((ModuleOutputPackagingElement) element).getSourceRoots(context)) {
                final VirtualFile sourceFile = sourceRoot.findFileByRelativePath(path);
                if (sourceFile != null && compilerConfiguration.isResourceFile(sourceFile)) {
                  result.add(sourceFile);
                }
              }
            }
            return true;
          }
        });

    return result;
  }
 protected String getProjectName() {
   return StringUtil.decapitalize(StringUtil.trimStart(getName(), "test"));
 }