コード例 #1
0
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      try {
        SAXTransformerFactory transformerFactory =
            (SAXTransformerFactory) TransformerFactory.newInstance();
        TransformerHandler handler = transformerFactory.newTransformerHandler();
        handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
        handler
            .getTransformer()
            .setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        final String configurationNameIncludedDate =
            PathUtil.suggestFileName(myConfiguration.getName())
                + " - "
                + new SimpleDateFormat(HISTORY_DATE_FORMAT).format(new Date());

        myOutputFile =
            new File(
                AbstractImportTestsAction.getTestHistoryRoot(myProject),
                configurationNameIncludedDate + ".xml");
        FileUtilRt.createParentDirs(myOutputFile);
        handler.setResult(new StreamResult(new FileWriter(myOutputFile)));
        final SMTestProxy.SMRootTestProxy root = myRoot;
        final RunConfiguration configuration = myConfiguration;
        if (root != null && configuration != null) {
          TestResultsXmlFormatter.execute(root, configuration, myConsoleProperties, handler);
        }
      } catch (ProcessCanceledException e) {
        throw e;
      } catch (Exception e) {
        LOG.info("Export to history failed", e);
      }
    }
コード例 #2
0
 /** Adds new CLASSES entries found in sys.path. */
 private static boolean addNewSysPathEntries(
     @NotNull Sdk sdk, @NotNull SdkModificator modificator, @NotNull List<String> sysPath) {
   final List<VirtualFile> oldRoots =
       Arrays.asList(sdk.getRootProvider().getFiles(OrderRootType.CLASSES));
   PythonSdkAdditionalData additionalData =
       sdk.getSdkAdditionalData() instanceof PythonSdkAdditionalData
           ? (PythonSdkAdditionalData) sdk.getSdkAdditionalData()
           : null;
   List<String> newRoots = new ArrayList<String>();
   for (String root : sysPath) {
     if (new File(root).exists()
         && !FileUtilRt.extensionEquals(root, "egg-info")
         && (additionalData == null || !wasOldRoot(root, additionalData.getExcludedPathFiles()))
         && !wasOldRoot(root, oldRoots)) {
       newRoots.add(root);
     }
   }
   if (!newRoots.isEmpty()) {
     for (String root : newRoots) {
       PythonSdkType.addSdkRoot(modificator, root);
     }
     return true;
   }
   return false;
 }
コード例 #3
0
  public static Map<String, String> pluginIdToPathMap() {
    final boolean containsIdeaProjectFolder =
        new File(pluginsRootPath() + "/" + DIRECTORY_STORE_FOLDER).exists();

    File[] files =
        new File(pluginsRootPath())
            .listFiles(
                new FileFilter() {
                  @SuppressWarnings("SimplifiableIfStatement")
                  @Override
                  public boolean accept(@NotNull File file) {
                    if (containsIdeaProjectFolder
                        && file.getName().equals(DEFAULT_IDEA_OUTPUT_FOLDER)) return false;
                    if (file.getName().equals(DIRECTORY_STORE_FOLDER)) return false;
                    return file.isDirectory();
                  }
                });
    if (files == null) return new HashMap<String, String>();

    HashMap<String, String> result = new HashMap<String, String>();
    for (File file : files) {
      result.put(file.getName(), FileUtilRt.toSystemIndependentName(file.getAbsolutePath()));
    }
    return result;
  }
コード例 #4
0
  public static List<Pair<String, Integer>> getFileNames(@NotNull String file) {
    final boolean dark = UIUtil.isUnderDarcula();
    final boolean retina = UIUtil.isRetina();
    if (retina || dark) {
      List<Pair<String, Integer>> answer = new ArrayList<Pair<String, Integer>>(4);

      final String name = FileUtil.getNameWithoutExtension(file);
      final String ext = FileUtilRt.getExtension(file);
      if (dark && retina) {
        answer.add(Pair.create(name + "@2x_dark." + ext, 2));
      }

      if (dark) {
        answer.add(Pair.create(name + "_dark." + ext, 1));
      }

      if (retina) {
        answer.add(Pair.create(name + "@2x." + ext, 2));
      }

      answer.add(Pair.create(file, 1));

      return answer;
    }

    return Collections.singletonList(Pair.create(file, 1));
  }
コード例 #5
0
  @Override
  public void setupRootModel(final ModifiableRootModel modifiableRootModel)
      throws ConfigurationException {
    String contentEntryPath = getContentEntryPath();
    if (StringUtil.isEmpty(contentEntryPath)) {
      return;
    }
    File contentRootDir = new File(contentEntryPath);
    FileUtilRt.createDirectory(contentRootDir);
    LocalFileSystem fileSystem = LocalFileSystem.getInstance();
    VirtualFile modelContentRootDir = fileSystem.refreshAndFindFileByIoFile(contentRootDir);
    if (modelContentRootDir == null) {
      return;
    }

    modifiableRootModel.addContentEntry(modelContentRootDir);
    modifiableRootModel.inheritSdk();

    final Project project = modifiableRootModel.getProject();

    setupGradleBuildFile(modelContentRootDir);
    setupGradleSettingsFile(modelContentRootDir, modifiableRootModel);

    if (myWizardContext.isCreatingNewProject()) {
      String externalProjectPath = FileUtil.toCanonicalPath(project.getBasePath());
      getExternalProjectSettings().setExternalProjectPath(externalProjectPath);
      AbstractExternalSystemSettings settings =
          ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID);
      //noinspection unchecked
      settings.linkProject(getExternalProjectSettings());
    } else {
      FileDocumentManager.getInstance().saveAllDocuments();
      ExternalSystemUtil.refreshProjects(project, GradleConstants.SYSTEM_ID, false);
    }
  }
コード例 #6
0
 @Nullable
 private static VirtualFile getExternalProjectConfigFile(
     @NotNull String parent, @NotNull String fileName) {
   File file = new File(parent, fileName);
   FileUtilRt.createIfNotExists(file);
   return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
 }
コード例 #7
0
  @Override
  protected void setUp() throws Exception {
    super.setUp();
    myFilesToDelete.add(new File(FileUtilRt.getTempDirectory()));
    if (ourTestCase != null) {
      String message =
          "Previous test "
              + ourTestCase
              + " hasn't called tearDown(). Probably overridden without super call.";
      ourTestCase = null;
      fail(message);
    }
    IdeaLogger.ourErrorsOccurred = null;

    LOG.info(getClass().getName() + ".setUp()");

    initApplication();

    myEditorListenerTracker = new EditorListenerTracker();
    myThreadTracker = new ThreadTracker();

    setUpProject();

    storeSettings();
    ourTestCase = this;
    if (myProject != null) {
      ProjectManagerEx.getInstanceEx().openTestProject(myProject);
      CodeStyleSettingsManager.getInstance(myProject).setTemporarySettings(new CodeStyleSettings());
      InjectedLanguageManagerImpl.pushInjectors(getProject());
    }

    DocumentCommitThread.getInstance().clearQueue();
    UIUtil.dispatchAllInvocationEvents();
  }
 /**
  * Configure test from data file. Data file is usual java, xml or whatever file that needs to be
  * tested except it has &lt;caret&gt; marker where caret should be placed when file is loaded in
  * editor and &lt;selection&gt;&lt;/selection&gt; denoting selection bounds.
  *
  * @param filePath - relative path from %IDEA_INSTALLATION_HOME%/testData/
  */
 protected void configureByFile(@TestDataFile @NonNls @NotNull String filePath) {
   try {
     final File ioFile = new File(getTestDataPath() + filePath);
     String fileText = FileUtilRt.loadFile(ioFile, CharsetToolkit.UTF8, true);
     configureFromFileText(ioFile.getName(), fileText);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
コード例 #9
0
 public static File createTempDir(@NonNls final String prefix, final boolean refresh)
     throws IOException {
   final File tempDirectory =
       FileUtilRt.createTempDirectory(TEST_DIR_PREFIX + prefix, null, false);
   myFilesToDelete.add(tempDirectory);
   if (refresh) {
     getVirtualFile(tempDirectory);
   }
   return tempDirectory;
 }
コード例 #10
0
 private boolean validateFile(final Document doc) {
   try {
     return _selectedFile != null
         && _selectedFile.isFile()
         && _selectedFile.canRead()
         && "xml".equalsIgnoreCase(FileUtilRt.getExtension(_selectedFile.getAbsolutePath()))
         && !doc.getText(0, doc.getLength()).trim().isEmpty();
   } catch (final BadLocationException ignore) {
     return false;
   }
 }
コード例 #11
0
ファイル: BytecodeCompiler.java プロジェクト: kazhida/kotlin
  private CompilerConfiguration createConfiguration(
      @Nullable String stdlib,
      @Nullable String[] classpath,
      @Nullable String[] externalAnnotationsPath,
      @NotNull String[] sourceRoots,
      boolean enableInline,
      boolean enableOptimization) {
    KotlinPaths paths = getKotlinPathsForAntTask();
    CompilerConfiguration configuration = new CompilerConfiguration();
    configuration.addAll(CLASSPATH_KEY, PathUtil.getJdkClassesRoots());
    if ((stdlib != null) && (stdlib.trim().length() > 0)) {
      configuration.add(CLASSPATH_KEY, new File(stdlib));
    } else {
      File path = paths.getRuntimePath();
      if (path.exists()) {
        configuration.add(CLASSPATH_KEY, path);
      }
    }
    if ((classpath != null) && (classpath.length > 0)) {
      for (String path : classpath) {
        configuration.add(CLASSPATH_KEY, new File(path));
      }
    }
    if ((externalAnnotationsPath != null) && (externalAnnotationsPath.length > 0)) {
      for (String path : externalAnnotationsPath) {
        configuration.add(ANNOTATIONS_PATH_KEY, new File(path));
      }
    }
    File jdkAnnotationsPath = paths.getJdkAnnotationsPath();
    if (jdkAnnotationsPath.exists()) {
      configuration.add(ANNOTATIONS_PATH_KEY, jdkAnnotationsPath);
    }

    configuration.addAll(CommonConfigurationKeys.SOURCE_ROOTS_KEY, Arrays.asList(sourceRoots));
    for (String sourceRoot : sourceRoots) {
      File file = new File(sourceRoot);
      if (!file.isFile() || !"kt".equals(FileUtilRt.getExtension(file.getName()))) {
        configuration.add(JVMConfigurationKeys.CLASSPATH_KEY, file);
      }
    }
    configuration.put(
        CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY,
        MessageCollectorPlainTextToStream.PLAIN_TEXT_TO_SYSTEM_ERR);

    configuration.put(ENABLE_INLINE, enableInline);
    configuration.put(ENABLE_OPTIMIZATION, enableOptimization);

    // lets register any compiler plugins
    configuration.addAll(CLIConfigurationKeys.COMPILER_PLUGINS, getCompilerPlugins());
    return configuration;
  }
コード例 #12
0
  @Override
  public void setupRootModel(ModifiableRootModel model) throws ConfigurationException {
    String contentPath = getContentEntryPath();
    if (StringUtil.isEmpty(contentPath)) {
      return;
    }
    File contentRootDir = new File(contentPath);
    FileUtilRt.createDirectory(contentRootDir);
    LocalFileSystem fileSystem = LocalFileSystem.getInstance();
    VirtualFile vContentRootDir = fileSystem.refreshAndFindFileByIoFile(contentRootDir);
    if (vContentRootDir == null) {
      return;
    }

    model.addContentEntry(vContentRootDir);

    VirtualFile configFile = getExternalProjectConfigFile(vContentRootDir);
    if (configFile != null && myTemplateConfigName != null) {
      FileTemplateManager manager = FileTemplateManager.getInstance();
      FileTemplate template = manager.getInternalTemplate(myTemplateConfigName);
      try {
        VfsUtil.saveText(configFile, template.getText());
      } catch (IOException e) {
        LOG.warn(
            String.format(
                "Unexpected exception on applying template %s config",
                myExternalSystemId.getReadableName()),
            e);
        throw new ConfigurationException(
            e.getMessage(),
            String.format(
                "Can't apply %s template config text", myExternalSystemId.getReadableName()));
      }
    }

    AbstractExternalSystemSettings settings =
        ExternalSystemApiUtil.getSettings(model.getProject(), myExternalSystemId);
    S externalProjectSettings = createSettings();
    if (myExternalProjectSettingsControl != null) {
      String errorMessage = myExternalProjectSettingsControl.apply(externalProjectSettings);
      myExternalProjectSettingsControl.disposeUIResources();
      if (errorMessage != null) {
        throw new ConfigurationException(errorMessage);
      }
    }
    //noinspection unchecked
    settings.linkProject(externalProjectSettings);
  }
 @NotNull
 @Override
 public Map<String, String> getAvailableSystemLibraries() {
   Map<String, String> map = new TreeMap<String, String>();
   File[] directoriesForLibraries = getFilesForLibraries();
   for (File childFile : directoriesForLibraries) {
     if (!FileUtilRt.getExtension(childFile.getName()).equals("dll")) {
       continue;
     }
     Couple<String> info = parseLibrary(childFile);
     if (info == null) {
       continue;
     }
     map.put(info.getFirst(), info.getSecond());
   }
   return map;
 }
コード例 #14
0
    public static ImageDescList create(
        @NotNull String file,
        @Nullable Class cls,
        boolean dark,
        boolean retina,
        boolean allowFloatScaling) {
      ImageDescList vars = new ImageDescList();
      if (retina || dark) {
        final String name = FileUtil.getNameWithoutExtension(file);
        final String ext = FileUtilRt.getExtension(file);

        float scale = calcScaleFactor(allowFloatScaling);

        // TODO: allow SVG images to freely scale on Retina

        if (Registry.is("ide.svg.icon") && dark) {
          vars.add(
              new ImageDesc(
                  name + "_dark.svg", cls, UIUtil.isRetina() ? 2f : scale, ImageDesc.Type.SVG));
        }

        if (Registry.is("ide.svg.icon")) {
          vars.add(
              new ImageDesc(
                  name + ".svg", cls, UIUtil.isRetina() ? 2f : scale, ImageDesc.Type.SVG));
        }

        if (dark && retina) {
          vars.add(new ImageDesc(name + "@2x_dark." + ext, cls, 2f, ImageDesc.Type.PNG));
        }

        if (dark) {
          vars.add(new ImageDesc(name + "_dark." + ext, cls, 1f, ImageDesc.Type.PNG));
        }

        if (retina) {
          vars.add(new ImageDesc(name + "@2x." + ext, cls, 2f, ImageDesc.Type.PNG));
        }
      }
      vars.add(new ImageDesc(file, cls, 1f, ImageDesc.Type.PNG, true));
      return vars;
    }
コード例 #15
0
 @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
 private static Control[] loadControls() {
   Document document;
   try {
     // use temporary bytes stream because otherwise inputStreamSkippingBOM will fail
     // on ZipFileInputStream used in jar files
     final InputStream stream = HTMLControls.class.getResourceAsStream("HtmlControls.xml");
     final byte[] bytes = FileUtilRt.loadBytes(stream);
     stream.close();
     final UnsyncByteArrayInputStream bytesStream = new UnsyncByteArrayInputStream(bytes);
     document = JDOMUtil.loadDocument(CharsetToolkit.inputStreamSkippingBOM(bytesStream));
     bytesStream.close();
   } catch (Exception e) {
     LOG.error(e);
     return new Control[0];
   }
   if (!document.getRootElement().getName().equals("htmlControls")) {
     LOG.error("HTMLControls storage is broken");
     return new Control[0];
   }
   return XmlSerializer.deserialize(document, Control[].class);
 }
コード例 #16
0
  @NotNull
  public static Project createProject(@NotNull String path, String creationPlace) {
    String fileName = PathUtilRt.getFileName(path);
    String projectName = FileUtilRt.getNameWithoutExtension(fileName);
    VirtualFile projectBase =
        LocalFileSystem.getInstance()
            .findFileByPath(
                FileUtil.toSystemIndependentName(
                    fileName.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION)
                        ? PathUtilRt.getParentPath(path)
                        : path));
    if (projectBase != null) {
      // must be leftovers from the previous test run
      for (VirtualFile file : ((NewVirtualFile) projectBase).iterInDbChildren()) {
        delete(file);
      }
    }

    try {
      Project project =
          ProjectManagerEx.getInstanceEx().newProject(projectName, path, false, false);
      assert project != null;

      project.putUserData(CREATION_PLACE, creationPlace);
      return project;
    } catch (TooManyProjectLeakedException e) {
      StringBuilder leakers = new StringBuilder();
      leakers.append("Too many projects leaked: \n");
      for (Project project : e.getLeakedProjects()) {
        String presentableString = getCreationPlace(project);
        leakers.append(presentableString);
        leakers.append("\n");
      }

      fail(leakers.toString());
      return null;
    }
  }
コード例 #17
0
  @Nullable
  public T findAssociatedFileType(@NotNull @NonNls CharSequence fileName) {
    if (!myExactFileNameMappings.isEmpty()) {
      T t = myExactFileNameMappings.get(fileName);
      if (t != null) return t;
    }

    if (!myExactFileNameAnyCaseMappings
        .isEmpty()) { // even hash lookup with case insensitive hasher is costly for isIgnored
                      // checks during compile
      T t = myExactFileNameAnyCaseMappings.get(fileName);
      if (t != null) return t;
    }

    //noinspection ForLoopReplaceableByForEach
    for (int i = 0; i < myMatchingMappings.size(); i++) {
      final Pair<FileNameMatcher, T> mapping = myMatchingMappings.get(i);
      if (FileNameMatcherEx.acceptsCharSequence(mapping.getFirst(), fileName))
        return mapping.getSecond();
    }

    return myExtensionMappings.get(FileUtilRt.getExtension(fileName));
  }
コード例 #18
0
  // please keep an implementation in sync with [junit-rt] ProcessBuilder.createProcess()
  @NotNull
  public static List<String> toCommandLine(
      @NotNull String command, @NotNull List<String> parameters, @NotNull Platform platform) {
    List<String> commandLine = ContainerUtil.newArrayListWithExpectedSize(parameters.size() + 1);

    commandLine.add(FileUtilRt.toSystemDependentName(command, platform.fileSeparator));

    boolean isWindows = platform == Platform.WINDOWS;
    boolean winShell =
        isWindows
            && ("cmd".equalsIgnoreCase(command) || "cmd.exe".equalsIgnoreCase(command))
            && parameters.size() > 1
            && "/c".equalsIgnoreCase(parameters.get(0));

    for (String parameter : parameters) {
      if (isWindows) {
        if (parameter.contains("\"")) {
          parameter = StringUtil.replace(parameter, "\"", "\\\"");
        } else if (parameter.isEmpty()) {
          parameter = "\"\"";
        }
      }

      if (winShell && StringUtil.containsAnyChar(parameter, WIN_SHELL_SPECIALS)) {
        parameter = quote(parameter, SPECIAL_QUOTE);
      }

      if (isQuoted(parameter, SPECIAL_QUOTE)) {
        parameter = quote(parameter.substring(1, parameter.length() - 1), '"');
      }

      commandLine.add(parameter);
    }

    return commandLine;
  }
コード例 #19
0
 public static String pluginsRootPath() {
   return FileUtilRt.toSystemIndependentName(PathManager.getPluginsPath() + "/live-plugins");
 }
コード例 #20
0
 // When file is renamed so that extension changes then language dialect might change and thus
 // psiFile should be invalidated
 private static boolean languageDialectChanged(final PsiFile newPsiFile, String oldFileName) {
   return newPsiFile != null
       && !FileUtilRt.extensionEquals(oldFileName, FileUtilRt.getExtension(newPsiFile.getName()));
 }
コード例 #21
0
 private void setModuleFilePath(String newFilePath) {
   ClasspathStorage.modulePathChanged(ModuleImpl.this, newFilePath);
   getMainStorage(ModuleImpl.this).setFile(null, new File(newFilePath));
   ComponentsPackage.getStateStore(ModuleImpl.this)
       .setPath(FileUtilRt.toSystemIndependentName(newFilePath));
 }
コード例 #22
0
 protected String getFileName(String newName) {
   if (getDefaultExtension() == null || FileUtilRt.getExtension(newName).length() > 0) {
     return newName;
   }
   return newName + "." + getDefaultExtension();
 }