Beispiel #1
0
 @Override
 public PsiElement setName(@NotNull String newName) throws IncorrectOperationException {
   final String oldName = FileUtil.getNameWithoutExtension(getName());
   final PsiElement result = super.setName(newName);
   final HaxeClass haxeClass = HaxeResolveUtil.findComponentDeclaration(this, oldName);
   if (haxeClass != null) {
     haxeClass.setName(FileUtil.getNameWithoutExtension(newName));
   }
   return result;
 }
  public void removeCoverageSuite(final CoverageSuite suite) {
    final String fileName = suite.getCoverageDataFileName();

    boolean deleteTraces = suite.isTracingEnabled();
    if (!FileUtil.isAncestor(PathManager.getSystemPath(), fileName, false)) {
      String message = "Would you like to delete file \'" + fileName + "\' ";
      if (deleteTraces) {
        message +=
            "and traces directory \'"
                + FileUtil.getNameWithoutExtension(new File(fileName))
                + "\' ";
      }
      message += "on disk?";
      if (Messages.showYesNoDialog(
              myProject, message, CommonBundle.getWarningTitle(), Messages.getWarningIcon())
          == Messages.YES) {
        deleteCachedCoverage(fileName, deleteTraces);
      }
    } else {
      deleteCachedCoverage(fileName, deleteTraces);
    }

    myCoverageSuites.remove(suite);
    if (myCurrentSuitesBundle != null && myCurrentSuitesBundle.contains(suite)) {
      CoverageSuite[] suites = myCurrentSuitesBundle.getSuites();
      suites = ArrayUtil.remove(suites, suite);
      chooseSuitesBundle(suites.length > 0 ? new CoverageSuitesBundle(suites) : null);
    }
  }
  @NotNull
  private static Map<Module, String> collectJpsPluginModules(@NotNull Module module) {
    XmlFile pluginXml = PluginModuleType.getPluginXml(module);
    if (pluginXml == null) return Collections.emptyMap();

    DomFileElement<IdeaPlugin> fileElement =
        DomManager.getDomManager(module.getProject()).getFileElement(pluginXml, IdeaPlugin.class);
    if (fileElement == null) return Collections.emptyMap();

    Map<Module, String> jpsPluginToOutputPath = new HashMap<Module, String>();
    IdeaPlugin plugin = fileElement.getRootElement();
    List<Extensions> extensions = plugin.getExtensions();
    for (Extensions extensionGroup : extensions) {
      XmlTag extensionsTag = extensionGroup.getXmlTag();
      String defaultExtensionNs = extensionsTag.getAttributeValue("defaultExtensionNs");
      for (XmlTag tag : extensionsTag.getSubTags()) {
        String name = tag.getLocalName();
        String qualifiedName = defaultExtensionNs != null ? defaultExtensionNs + "." + name : name;
        if (CompileServerPlugin.EP_NAME.getName().equals(qualifiedName)) {
          String classpath = tag.getAttributeValue("classpath");
          if (classpath != null) {
            for (String path : StringUtil.split(classpath, ";")) {
              String moduleName = FileUtil.getNameWithoutExtension(PathUtil.getFileName(path));
              Module jpsModule =
                  ModuleManager.getInstance(module.getProject()).findModuleByName(moduleName);
              if (jpsModule != null) {
                jpsPluginToOutputPath.put(jpsModule, path);
              }
            }
          }
        }
      }
    }
    return jpsPluginToOutputPath;
  }
  private static BundleManifest readProperties(PsiFile propertiesFile) {
    try {
      UTF8Properties properties = new UTF8Properties();
      properties.load(new StringReader(propertiesFile.getText()));
      Map<String, String> map = ContainerUtil.newHashMap();
      for (Object key : properties.keySet()) {
        String name = key.toString();
        map.put(name, properties.getProperty(name));
      }
      if (map.get(Constants.BUNDLE_SYMBOLICNAME) == null) {
        VirtualFile file = propertiesFile.getVirtualFile();
        if (file != null) {
          if (!BndProjectImporter.BND_FILE.equals(file.getName())) {
            map.put(
                Constants.BUNDLE_SYMBOLICNAME, FileUtil.getNameWithoutExtension(file.getName()));
          } else if (file.getParent() != null) {
            map.put(Constants.BUNDLE_SYMBOLICNAME, file.getParent().getName());
          }
        }
      }
      return new BundleManifest(map, propertiesFile);
    } catch (IOException ignored) {
    } catch (InvalidVirtualFileAccessException ignored) {
    }

    return null;
  }
  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));
  }
  protected void doTest(String xmlPath) throws IOException {
    File txtFile = new File(FileUtil.getNameWithoutExtension(xmlPath) + ".txt");

    ModuleScriptData result =
        ModuleXmlParser.parseModuleScript(
            xmlPath,
            new MessageCollector() {
              @Override
              public void report(
                  @NotNull CompilerMessageSeverity severity,
                  @NotNull String message,
                  @NotNull CompilerMessageLocation location) {
                throw new AssertionError(
                    MessageRenderer.PLAIN_FULL_PATHS.render(severity, message, location));
              }
            });

    StringBuilder sb = new StringBuilder();
    for (Module module : result.getModules()) {
      sb.append(moduleToString(module)).append("\n");
    }

    String actual = sb.toString();

    if (!txtFile.exists()) {
      FileUtil.writeToFile(txtFile, actual);
      fail("Expected data file does not exist. A new file created: " + txtFile);
    }

    JetTestUtils.assertEqualsToFile(txtFile, actual);
  }
Beispiel #7
0
  protected void unzip(String pathToFile, String outputFolder) {
    System.out.println("Start unzipping: " + pathToFile + " to " + outputFolder);
    String pathToUnzip;
    if (outputFolder.equals(pathManager.getPlatformFolderInAndroidSdk())) {
      pathToUnzip = outputFolder;
    } else {
      pathToUnzip = outputFolder + "/" + FileUtil.getNameWithoutExtension(new File(pathToFile));
    }
    if (new File(pathToUnzip).listFiles() != null) {
      System.out.println("File was already unzipped: " + pathToFile);
      return;
    }
    try {
      byte[] buf = new byte[1024];
      ZipInputStream zipinputstream = null;
      ZipEntry zipentry;
      zipinputstream = new ZipInputStream(new FileInputStream(pathToFile));

      zipentry = zipinputstream.getNextEntry();
      try {
        while (zipentry != null) {
          String entryName = zipentry.getName();
          int n;
          File outputFile = new File(outputFolder + "/" + entryName);

          if (zipentry.isDirectory()) {
            outputFile.mkdirs();
            zipinputstream.closeEntry();
            zipentry = zipinputstream.getNextEntry();
            continue;
          } else {
            File parentFile = outputFile.getParentFile();
            if (parentFile != null && !parentFile.exists()) {
              parentFile.mkdirs();
            }
            outputFile.createNewFile();
          }

          FileOutputStream fileoutputstream = new FileOutputStream(outputFile);
          try {
            while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
              fileoutputstream.write(buf, 0, n);
            }
          } finally {
            fileoutputstream.close();
          }
          zipinputstream.closeEntry();
          zipentry = zipinputstream.getNextEntry();
        }

        zipinputstream.close();
      } catch (IOException e) {
        System.err.println("Entry name: " + zipentry.getName());
        e.printStackTrace();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println("Finish unzipping: " + pathToFile + " to " + outputFolder);
  }
  @NotNull
  private static File copyJarFileWithoutEntry(
      @NotNull File jarPath, @NotNull String... entriesToDelete) {
    try {
      File outputFile =
          new File(
              jarPath.getParentFile(), FileUtil.getNameWithoutExtension(jarPath) + "-after.jar");
      Set<String> toDelete = SetsKt.setOf(entriesToDelete);

      @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
      JarFile jar = new JarFile(jarPath);
      ZipOutputStream output =
          new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));
      try {
        for (Enumeration<JarEntry> enumeration = jar.entries(); enumeration.hasMoreElements(); ) {
          JarEntry jarEntry = enumeration.nextElement();
          if (toDelete.contains(jarEntry.getName())) {
            continue;
          }
          output.putNextEntry(jarEntry);
          output.write(FileUtil.loadBytes(jar.getInputStream(jarEntry)));
          output.closeEntry();
        }
      } finally {
        output.close();
        jar.close();
      }

      return outputFile;
    } catch (IOException e) {
      throw ExceptionUtilsKt.rethrow(e);
    }
  }
  protected void doTest(@NotNull String path) throws Exception {
    File mainFile = new File(path);
    String mainFileName = FileUtil.getNameWithoutExtension(mainFile);
    IntentionAction intentionAction = createIntention(mainFile);
    List<String> sourceFilePaths = new ArrayList<String>();
    File parentDir = mainFile.getParentFile();
    extraFileLoop:
    //noinspection ForLoopThatDoesntUseLoopVariable
    for (int i = 1; true; i++) {
      for (String extension : EXTENSIONS) {
        File extraFile = new File(parentDir, mainFileName + "." + i + extension);
        if (extraFile.exists()) {
          sourceFilePaths.add(extraFile.getPath());
          continue extraFileLoop;
        }
      }
      break;
    }
    sourceFilePaths.add(path);

    Map<String, PsiFile> pathToFile =
        ContainerUtil.newMapFromKeys(
            sourceFilePaths.iterator(),
            new Convertor<String, PsiFile>() {
              @Override
              public PsiFile convert(String path) {
                try {
                  configureByFile(path);
                } catch (Exception e) {
                  throw new RuntimeException(e);
                }
                return myFile;
              }
            });

    String fileText = FileUtil.loadFile(mainFile, true);

    String minJavaVersion =
        InTextDirectivesUtils.findStringWithPrefixes(fileText, "// MIN_JAVA_VERSION: ");
    if (minJavaVersion != null && !SystemInfo.isJavaVersionAtLeast(minJavaVersion)) return;

    boolean isWithRuntime =
        InTextDirectivesUtils.findStringWithPrefixes(fileText, "// WITH_RUNTIME") != null;

    try {
      if (isWithRuntime) {
        ConfigLibraryUtil.configureKotlinRuntime(getModule(), getFullJavaJDK());
      }

      DirectiveBasedActionUtils.checkForUnexpectedErrors((JetFile) getFile());

      doTestFor(pathToFile, intentionAction, fileText);
    } finally {
      if (isWithRuntime) {
        ConfigLibraryUtil.unConfigureKotlinRuntime(getModule(), getTestProjectJdk());
      }
    }
  }
 private static void createTestHelper(@NotNull Project project, PsiDirectory projectDir) {
   final FileTemplate template =
       FileTemplateManager.getInstance(project)
           .getInternalTemplate(FileUtil.getNameWithoutExtension(EduNames.TEST_HELPER));
   try {
     FileTemplateUtil.createFromTemplate(template, EduNames.TEST_HELPER, null, projectDir);
   } catch (Exception ignored) {
   }
 }
 private JpsModule loadModule(String path) {
   final File file = new File(path);
   String name = FileUtil.getNameWithoutExtension(file);
   final Element moduleRoot = loadRootElement(file);
   final String typeId = moduleRoot.getAttributeValue("type");
   final JpsModule module =
       JpsElementFactory.getInstance().createModule(name, getModuleType(typeId));
   JpsModuleLoader.loadRootModel(module, findComponent(moduleRoot, "NewModuleRootManager"));
   return module;
 }
  public static void removeDuplicatingClasses(
      final Module module,
      @NotNull final String packageName,
      @NotNull String className,
      @Nullable File classFile,
      String sourceRootPath) {
    if (sourceRootPath == null) {
      return;
    }
    VirtualFile sourceRoot = LocalFileSystem.getInstance().findFileByPath(sourceRootPath);
    if (sourceRoot == null) {
      return;
    }
    final Project project = module.getProject();
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
    final String interfaceQualifiedName = packageName + '.' + className;
    PsiClass[] classes =
        facade.findClasses(interfaceQualifiedName, GlobalSearchScope.moduleScope(module));
    final ProjectFileIndex projectFileIndex =
        ProjectRootManager.getInstance(project).getFileIndex();
    for (PsiClass c : classes) {
      PsiFile psiFile = c.getContainingFile();
      if (className.equals(FileUtil.getNameWithoutExtension(psiFile.getName()))) {
        VirtualFile virtualFile = psiFile.getVirtualFile();
        if (virtualFile != null
            && projectFileIndex.getSourceRootForFile(virtualFile) == sourceRoot) {
          final String path = virtualFile.getPath();
          File f = new File(path);

          try {
            f = f.getCanonicalFile();
            classFile = classFile != null ? classFile.getCanonicalFile() : null;
            if (f != null && !f.equals(classFile) && f.exists()) {
              if (f.delete()) {
                virtualFile.refresh(true, false);
              } else {
                ApplicationManager.getApplication()
                    .invokeLater(
                        new Runnable() {
                          public void run() {
                            Messages.showErrorDialog(
                                project, "Can't delete file " + path, CommonBundle.getErrorTitle());
                          }
                        },
                        project.getDisposed());
              }
            }
          } catch (IOException e) {
            LOG.info(e);
          }
        }
      }
    }
  }
 @NotNull
 @Override
 public Map<String, Void> map(@NotNull FileContent inputData) {
   final VirtualFile file = inputData.getFile();
   final String name = file.getName();
   if (PyNames.INIT_DOT_PY.equals(name)) {
     final VirtualFile parent = file.getParent();
     if (parent != null && parent.isDirectory()) {
       return Collections.singletonMap(parent.getName(), null);
     }
   } else {
     return Collections.singletonMap(FileUtil.getNameWithoutExtension(name), null);
   }
   return Collections.emptyMap();
 }
    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;
    }
 @Nullable
 private static PsiFile findPyFileInDir(PsiDirectory dir, String referencedName) {
   PsiFile file = dir.findFile(referencedName + PyNames.DOT_PY);
   if (file == null) {
     final List<FileNameMatcher> associations =
         FileTypeManager.getInstance().getAssociations(PythonFileType.INSTANCE);
     for (FileNameMatcher association : associations) {
       if (association instanceof ExtensionFileNameMatcher) {
         file =
             dir.findFile(
                 referencedName + "." + ((ExtensionFileNameMatcher) association).getExtension());
         if (file != null) break;
       }
     }
   }
   if (file != null && FileUtil.getNameWithoutExtension(file.getName()).equals(referencedName)) {
     return file;
   }
   return null;
 }
  private ShelvedBinaryFile shelveBinaryFile(final Change change) throws IOException {
    final ContentRevision beforeRevision = change.getBeforeRevision();
    final ContentRevision afterRevision = change.getAfterRevision();
    File beforeFile = beforeRevision == null ? null : beforeRevision.getFile().getIOFile();
    File afterFile = afterRevision == null ? null : afterRevision.getFile().getIOFile();
    String shelvedPath = null;
    if (afterFile != null) {
      String shelvedName = FileUtil.getNameWithoutExtension(afterFile.getName());
      String shelvedExt = FileUtil.getExtension(afterFile.getName());
      File shelvedFile =
          FileUtil.findSequentNonexistentFile(
              myFileProcessor.getBaseIODir(), shelvedName, shelvedExt);

      myFileProcessor.saveFile(afterRevision.getFile().getIOFile(), shelvedFile);

      shelvedPath = shelvedFile.getPath();
    }
    String beforePath = ChangesUtil.getProjectRelativePath(myProject, beforeFile);
    String afterPath = ChangesUtil.getProjectRelativePath(myProject, afterFile);
    return new ShelvedBinaryFile(beforePath, afterPath, shelvedPath);
  }
  @NotNull
  private static AbstractGradleDependency buildDependency(
      @NotNull GradleModule ownerModule,
      @NotNull IdeaSingleEntryLibraryDependency dependency,
      @NotNull GradleProject intellijProject)
      throws IllegalStateException {
    File binaryPath = dependency.getFile();
    if (binaryPath == null) {
      throw new IllegalStateException(
          String.format(
              "Can't parse external library dependency '%s'. Reason: it doesn't specify path to the binaries",
              dependency));
    }

    // Gradle API doesn't provide library name at the moment.
    GradleLibrary library = new GradleLibrary(FileUtil.getNameWithoutExtension(binaryPath));
    library.addPath(LibraryPathType.BINARY, binaryPath.getAbsolutePath());

    File sourcePath = dependency.getSource();
    if (sourcePath != null) {
      library.addPath(LibraryPathType.SOURCE, sourcePath.getAbsolutePath());
    }

    File javadocPath = dependency.getJavadoc();
    if (javadocPath != null) {
      library.addPath(LibraryPathType.DOC, javadocPath.getAbsolutePath());
    }

    if (!intellijProject.addLibrary(library)) {
      for (GradleLibrary registeredLibrary : intellijProject.getLibraries()) {
        if (registeredLibrary.equals(library)) {
          return new GradleLibraryDependency(ownerModule, registeredLibrary);
        }
      }
    }

    return new GradleLibraryDependency(ownerModule, library);
  }
 private static String readProjectName(String path) {
   final File file = new File(path);
   if (file.isDirectory()) {
     final File nameFile =
         new File(new File(path, Project.DIRECTORY_STORE_FOLDER), ProjectImpl.NAME_FILE);
     if (nameFile.exists()) {
       try {
         final BufferedReader in =
             new BufferedReader(new InputStreamReader(new FileInputStream(nameFile), "UTF-8"));
         try {
           final String name = in.readLine();
           if (name != null && name.length() > 0) return name.trim();
         } finally {
           in.close();
         }
       } catch (IOException ignored) {
       }
     }
     return file.getName();
   } else {
     return FileUtil.getNameWithoutExtension(file.getName());
   }
 }
Beispiel #19
0
 @NotNull
 public static File replaceExtension(@NotNull File file, @Nullable String newExtension) {
   return new File(
       file.getParentFile(),
       FileUtil.getNameWithoutExtension(file) + (newExtension == null ? "" : "." + newExtension));
 }
 private static boolean isXmlFile(File file) {
   return file.isFile() && FileUtil.getNameWithoutExtension(file).equalsIgnoreCase("xml");
 }
 private File getTracesDirectory(final String fileName) {
   return new File(
       new File(fileName).getParentFile(), FileUtil.getNameWithoutExtension(new File(fileName)));
 }
 @Override
 public String inferBinaryName(Location location, JavaFileObject file) {
   return FileUtil.getNameWithoutExtension(new File(file.getName()).getName());
 }