Beispiel #1
0
  private <T> void readModuleDescriptorsFromFile(
      IFile file,
      Set<IFile> excludes,
      List<T> result,
      boolean refreshFiles,
      DescriptorReader<T> reader) {
    if (!needProcess(file, excludes)) return;
    if (refreshFiles) {
      FileSystem.getInstance().refresh(file);
    }

    if (file.getName().endsWith(JAR)) {
      IFile jarRoot = FileSystem.getInstance().getFileByPath(file.getPath() + JAR_SEPARATOR);
      if (jarRoot != null) {
        readModuleDescriptorsFromFolder(jarRoot, excludes, result, refreshFiles, reader);
      }
    } else {
      if (!isModuleFile(file)) return;
      ModuleDescriptor moduleDescriptor = loadDescriptorOnly_internal(file, excludes);
      if (moduleDescriptor != null) {
        T descriptor = reader.read(new ModuleHandle(file, moduleDescriptor));
        if (descriptor != null) {
          result.add(descriptor);
        }
      }
    }
  }
Beispiel #2
0
 public ModuleDescriptor loadModuleDescriptor(IFile file) {
   try {
     String filePath = file.getPath();
     if (filePath.endsWith(SLASH_META_INF_MODULE_XML)) {
       DeploymentDescriptor deploymentDescriptor =
           DeploymentDescriptorPersistence.loadDeploymentDescriptor(file);
       ModuleDescriptor result = null;
       IFile realDescriptorFile = getRealDescriptorFile(filePath, deploymentDescriptor);
       if (realDescriptorFile != null) {
         result = loadModuleDescriptor(realDescriptorFile);
       }
       // TODO create module without sources
       if (result != null) {
         result.setDeploymentDescriptor(deploymentDescriptor);
         // TODO fix stubs
       }
       return result;
     } else {
       return DescriptorIOFacade.getInstance().fromFileType(file).readFromFile(file);
     }
   } catch (Exception t) {
     LOG.error("Fail to load module from descriptor " + file.getPath(), t);
     return null;
   }
 }
Beispiel #3
0
 protected void readModules(FileMPSProject.ProjectDescriptor projDesc) {
   myErrors = null;
   //  load solutions
   Set<ModuleReference> existingModules = getModuleReferences();
   for (Path modulePath : projDesc.getModules()) {
     String path = modulePath.getPath();
     IFile descriptorFile = FileSystem.getInstance().getFileByPath(path);
     if (descriptorFile.exists()) {
       ModuleDescriptor descriptor =
           ModulesMiner.getInstance().loadModuleDescriptor(descriptorFile);
       if (descriptor != null) {
         ModulesMiner.ModuleHandle moduleHandle =
             new ModulesMiner.ModuleHandle(descriptorFile, descriptor);
         IModule m = ModuleRepositoryFacade.createModule(moduleHandle, this);
         ModuleReference moduleReference = m.getModuleReference();
         if (!(existingModules.remove(moduleReference))) {
           super.addModule(moduleReference);
         }
       } else {
         error("Can't load module from " + descriptorFile.getPath() + " Unknown file type.");
       }
     } else {
       error("Can't load module from " + descriptorFile.getPath() + " File doesn't exist.");
     }
   }
   for (ModuleReference ref : existingModules) {
     super.removeModule(ref);
   }
 }
  @Override
  public void findTargets(
      TargetKind kind,
      Collection<SModel> scope,
      Consumer<NavigationTarget> consumer,
      Consumer<SModel> processedConsumer) {
    final ID<Integer, List<SNodeDescriptor>> indexName = RootNodeNameIndex.NAME;
    final FileBasedIndex fileBasedIndex = FileBasedIndex.getInstance();

    for (SModel sm : scope) {
      if (sm instanceof EditableSModel && ((EditableSModel) sm).isChanged()) {
        continue;
      }

      DataSource source = sm.getSource();
      if (!(source instanceof FileDataSource)) {
        continue;
      }

      IFile modelFile = ((FileDataSource) source).getFile();
      String ext = FileUtil.getExtension(modelFile.getName());
      if (ext == null
          || modelFile.isDirectory()
          || !(supportedExtensions.contains(ext.toLowerCase()))) {
        continue;
      }

      VirtualFile vf = VirtualFileUtils.getVirtualFile(modelFile);
      if (vf == null) continue; // e.g. model was deleted

      int fileId = FileBasedIndex.getFileId(vf);
      ConcreteFilesGlobalSearchScope fileScope =
          new ConcreteFilesGlobalSearchScope(Collections.singleton(vf));
      List<List<SNodeDescriptor>> descriptors =
          fileBasedIndex.getValues(indexName, fileId, fileScope);
      if (descriptors.isEmpty()) continue;

      boolean needToLoad = false;
      for (NavigationTarget snd : descriptors.get(0)) {
        PropertyConstraintsDescriptor descriptor =
            ConceptRegistry.getInstance()
                .getConstraintsDescriptor(snd.getConcept().getQualifiedName())
                .getProperty(SNodeUtil.property_INamedConcept_name);
        if (descriptor instanceof BasePropertyConstraintsDescriptor
            && !((BasePropertyConstraintsDescriptor) descriptor).isGetterDefault()) {
          needToLoad = true;
          break;
        }
      }

      if (!needToLoad) {
        for (SNodeDescriptor desc : descriptors.get(0)) {
          consumer.consume(desc);
        }
        processedConsumer.consume(sm);
      }
    }
  }
Beispiel #5
0
  @Override
  public List<String> getErrors() {
    List<String> errors = new ArrayList<String>();
    Throwable loadException = myModule.getModuleDescriptor().getLoadException();
    if (loadException != null) {
      errors.add("Couldn't load module: " + loadException.getMessage());
      return errors;
    }

    ModuleDescriptor descriptor = myModule.getModuleDescriptor();
    // null?

    for (Dependency dep : descriptor.getDependencies()) {
      SModuleReference moduleRef = dep.getModuleRef();
      if (MPSModuleRepository.getInstance().getModule(moduleRef) == null) {
        errors.add("Can't find dependency: " + moduleRef.getModuleName());
      }
    }
    for (SModuleReference reference : descriptor.getUsedLanguages()) {
      if (ModuleRepositoryFacade.getInstance().getModule(reference, Language.class) == null) {
        errors.add("Can't find used language: " + reference.getModuleName());
      }
    }
    for (SModuleReference reference : descriptor.getUsedDevkits()) {
      if (MPSModuleRepository.getInstance().getModule(reference) == null) {
        errors.add("Can't find used devkit: " + reference.getModuleName());
      }
    }

    if (descriptor.getSourcePaths() != null && !myModule.isPackaged()) {
      for (String sourcePath : descriptor.getSourcePaths()) {
        IFile file = FileSystem.getInstance().getFileByPath(sourcePath);
        if (file == null || !file.exists()) {
          errors.add("Can't find source path: " + sourcePath);
        }
      }
    }
    if (descriptor.getAdditionalJavaStubPaths() != null) {
      for (String path : descriptor.getAdditionalJavaStubPaths()) {
        IFile file = FileSystem.getInstance().getFileByPath(path);
        if (file == null || !file.exists()) {
          if (new File(path).exists()) {
            errors.add("Idea VFS is not up-to-date. Can't find library: " + path);
          } else {
            errors.add("Can't find library: " + path);
          }
        }
      }
    }

    // todo: =(
    if (!(myModule instanceof Generator)) {
      errors.addAll(validateDependenciesOnGenerators());
    }

    return errors;
  }
  /*package*/ Solution createNewSolution(final IFile solutionDescriptorFile) {
    MPSProject mpsProject = myThis.getProject();

    // Prepare files
    File dir = new File(solutionDescriptorFile.getAbsolutePath()).getParentFile();
    if (!(dir.exists())) {
      dir.mkdirs();
    }
    String solutionFileName = solutionDescriptorFile.getName();
    String solutionName = solutionFileName.substring(0, solutionFileName.length() - 4);

    // Create
    // RE-2448
    ModelRoot modelRoot = new ModelRoot();
    modelRoot.setPrefix("");
    modelRoot.setPath(solutionDescriptorFile.getParent().getAbsolutePath());
    final Solution solution =
        Solution.createStubSolution(solutionName, solutionDescriptorFile, mpsProject, modelRoot);

    SolutionDescriptor solutionDescriptor = solution.getModuleDescriptor();
    solutionDescriptor.setCompileInMPS(myThis.getCompileInMPS());

    // Add SWC file to the classpath
    ModelRoot stubModelEntry = new ModelRoot();
    stubModelEntry.setPath(myThis.getSourcesPath());
    stubModelEntry.setManager(LanguageID.AS_MANAGER);
    solutionDescriptor.getStubModelEntries().add(stubModelEntry);

    // Add languages refs
    solutionDescriptor
        .getUsedLanguages()
        .add(ModuleReference.fromString(Languages.ACTION_SCRIPT_INTERNAL));
    solutionDescriptor
        .getUsedLanguages()
        .add(ModuleReference.fromString(Languages.ACTION_SCRIPT_LOGGING));
    solutionDescriptor
        .getUsedLanguages()
        .add(ModuleReference.fromString(Languages.ACTION_SCRIPT_ASSETS));

    // Add playerglobal reference
    Dependency playerGlobalDependency = new Dependency();
    playerGlobalDependency.setModuleRef(ModuleReference.fromString(PLAYERGLOBAL_SWC));
    solutionDescriptor.getDependencies().add(playerGlobalDependency);

    // Save the solution descriptor
    ModelAccess.instance()
        .writeFilesInEDT(
            new Runnable() {
              public void run() {
                solution.save();
              }
            });
    mpsProject.addProjectModule(solution);

    return solution;
  }
Beispiel #7
0
 @Override
 public String compute() {
   TreeFileChooser chooser = new TreeFileChooser();
   chooser.setMode(TreeFileChooser.MODE_DIRECTORIES);
   IFile result = chooser.showDialog();
   if (result == null) {
     return null;
   }
   return result.getPath();
 }
Beispiel #8
0
  private void processExcludes(
      @NotNull IFile descriptorFile, ModuleDescriptor descriptor, Set<IFile> excludes) {
    if (descriptor == null || descriptorFile.isReadOnly()) {
      return;
    }

    for (String p : descriptor.getSourcePaths()) {
      excludes.add(FileSystem.getInstance().getFileByPath(p));
    }

    IFile genPath = ProjectPathUtil.getGeneratorOutputPath(descriptorFile.getParent(), descriptor);
    if (genPath != null) {
      excludes.add(genPath);
      if (!descriptorFile.isReadOnly()) {
        FileSystem.getInstance().getFileByPath(FileGenerationUtil.getCachesPath(genPath.getPath()));
      }
    }

    IFile testsGenPath = ProjectPathUtil.getGeneratorTestsOutputPath(descriptorFile, descriptor);
    if (testsGenPath != null) {
      excludes.add(testsGenPath);
      if (!descriptorFile.isReadOnly()) {
        FileSystem.getInstance()
            .getFileByPath(FileGenerationUtil.getCachesPath(testsGenPath.getPath()));
      }
    }

    for (ModelRootDescriptor rootDescriptor : descriptor.getModelRootDescriptors()) {
      ModelRoot root = rootDescriptor.getRoot();
      if (root == null
          || root.getManager() != null && root.getManager() != LanguageID.JAVA_MANAGER) {
        continue;
      }

      excludes.add(FileSystem.getInstance().getFileByPath(root.getPath()));
    }

    IFile classesGen = ProjectPathUtil.getClassesGenFolder(descriptorFile.getParent(), false);
    if (classesGen != null) {
      excludes.add(classesGen);
    }

    // todo: specify what kind of descriptor can be input for this method
    if (descriptor instanceof LanguageDescriptor) {
      IFile generatorClassesGen =
          ProjectPathUtil.getClassesGenFolder(descriptorFile.getParent(), true);
      if (generatorClassesGen != null) {
        excludes.add(generatorClassesGen);
      }
    }

    for (String entry : descriptor.getAdditionalJavaStubPaths()) {
      excludes.add(FileSystem.getInstance().getFileByPath(entry));
    }
  }
Beispiel #9
0
 public void doExecute(@NotNull final AnActionEvent event, final Map<String, Object> _params) {
   try {
     IModule module = ((SModelDescriptor) MapSequence.fromMap(_params).get("model")).getModule();
     TreeFileChooser treeFileChooser = new TreeFileChooser();
     treeFileChooser.setDirectoriesAreAlwaysVisible(true);
     treeFileChooser.setMode(TreeFileChooser.MODE_DIRECTORIES);
     final SModel sModel =
         ((SModelDescriptor) MapSequence.fromMap(_params).get("model")).getSModel();
     treeFileChooser.setFileFilter(
         new IFileFilter() {
           public boolean accept(IFile file) {
             return JavaCompiler.checkBaseModelMatchesSourceDirectory(
                 sModel, new File(file.getPath()));
           }
         });
     String generatorOutputPath = module.getGeneratorOutputPath();
     File initial = null;
     File output = new File(generatorOutputPath);
     if (output.exists()) {
       initial = output;
       File sourceRoot = new File(initial.getParentFile(), "source");
       if (!(sourceRoot.exists())) {
         sourceRoot = new File(initial.getParentFile(), "src");
       }
       initial = sourceRoot;
       if (sourceRoot.exists()) {
         File modelSource = new File(sourceRoot, NameUtil.pathFromNamespace(sModel.getLongName()));
         if (modelSource.exists()) {
           initial = modelSource;
         }
       }
     }
     if (initial != null) {
       treeFileChooser.setInitialFile(
           FileSystem.getInstance().getFileByPath(initial.getAbsolutePath()));
     }
     IFile result =
         treeFileChooser.showDialog(((Frame) MapSequence.fromMap(_params).get("frame")));
     if (result != null) {
       JavaCompiler javaCompiler =
           new JavaCompiler(
               ((IOperationContext) MapSequence.fromMap(_params).get("context")),
               module,
               new File(result.getPath()),
               false,
               sModel);
       javaCompiler.compile();
     }
   } catch (Throwable t) {
     if (log.isErrorEnabled()) {
       log.error("User's action execute method failed. Action:" + "GetModelContentsFromSource", t);
     }
   }
 }
Beispiel #10
0
  protected final void collectModels(
      IFile dir,
      String package_,
      String relativePath,
      Map<String, String> options,
      Collection<SModel> models) {
    if (FileSystem.getInstance().isFileIgnored(dir.getName())) return;
    if (!dir.isDirectory()) return;

    List<IFile> files = dir.getChildren();
    options.put(ModelFactory.OPTION_PACKAGE, package_);
    for (IFile file : files) {
      String fileName = file.getName();
      String extension = FileUtil.getExtension(fileName);

      if (extension == null) continue;
      ModelFactory modelFactory = PersistenceFacade.getInstance().getModelFactory(extension);
      if (modelFactory == null || file.isDirectory()) continue;

      FileDataSource source = new FileDataSource(file, this);
      options.put(ModelFactory.OPTION_RELPATH, combinePath(relativePath, fileName));
      String fileNameWE = FileUtil.getNameWithoutExtension(fileName);
      options.put(
          ModelFactory.OPTION_MODELNAME,
          package_ != null
              ? (package_.isEmpty() ? fileNameWE : package_ + "." + fileNameWE)
              : null);
      try {
        SModel model = modelFactory.load(source, Collections.unmodifiableMap(options));
        ((SModelBase) model).setModelRoot(this);
        models.add(model);
      } catch (UnsupportedDataSourceException ex) {
        /* model factory registration problem: ignore */
      }
    }

    options.put(ModelFactory.OPTION_RELPATH, relativePath);
    for (FolderModelFactory factory : PersistenceRegistry.getInstance().getFolderModelFactories()) {
      for (DataSource dataSource : factory.createDataSources(this, dir)) {
        SModel model = factory.load(dataSource, Collections.unmodifiableMap(options));
        ((SModelBase) model).setModelRoot(this);
        models.add(model);
      }
    }

    for (IFile childDir : files) {
      if (childDir.isDirectory()) {
        String name = childDir.getName();
        String innerPackage =
            package_ != null && JavaNameUtil.isJavaIdentifier(name)
                ? (package_.isEmpty() ? name : package_ + "." + name)
                : null;
        String innerPath = combinePath(relativePath, name);
        collectModels(childDir, innerPackage, innerPath, options, models);
      }
    }
  }
Beispiel #11
0
 public Path compute() {
   TreeFileChooser chooser = new TreeFileChooser();
   chooser.setExtensionFileFilter(
       MPSExtentions.DOT_LANGUAGE,
       MPSExtentions.DOT_SOLUTION,
       MPSExtentions.DOT_LIBRARY,
       MPSExtentions.DOT_DEVKIT);
   IFile file = chooser.showDialog(myOwner.getMainComponent());
   if (file == null) {
     return null;
   }
   return new Path(file.getPath());
 }
Beispiel #12
0
 @Override
 public void update(ProgressMonitor monitor, @NotNull FileSystemEvent event) {
   assertCanChange();
   for (IFile file : event.getRemoved()) {
     if (file.equals(myDescriptorFile)) {
       ModuleRepositoryFacade.getInstance().unregisterModule(this);
       return;
     }
   }
   for (IFile file : event.getChanged()) {
     if (file.equals(myDescriptorFile)) {
       SModuleOperations.reloadFromDisk(this);
       return;
     }
   }
 }
Beispiel #13
0
 private static IFile getRefactoringsFile(IFile modelFile) {
   String modelPath = modelFile.getPath();
   String refactoringsPath =
       modelPath.substring(0, modelPath.length() - MPSExtentions.DOT_MODEL.length())
           + MPSExtentions.DOT_REFACTORINGS;
   return FileSystem.getInstance().getFileByPath(refactoringsPath);
 }
Beispiel #14
0
  public static void save(IFile modelFile, StructureModificationLog log) {
    IFile refactoringsFile = getRefactoringsFile(modelFile);
    refactoringsFile.createNewFile();

    Document document = new HistoryWriter().saveHistory(log);
    if (refactoringsFile.isReadOnly()) {
      LOG.error("Can't write to " + refactoringsFile.getPath());
      return;
    }

    try {
      JDOMUtil.writeDocument(document, refactoringsFile);
    } catch (IOException e) {
      LOG.error("Error in file " + refactoringsFile, e);
    }
  }
Beispiel #15
0
 private SNode convertLanguage(LanguageDescriptor source) {
   SNode result =
       SConceptOperations.createNewNode("jetbrains.mps.lang.project.structure.Language", null);
   result.setId(SNodeId.fromString("~root"));
   SModelOperations.addRootNode(myModel, result);
   fill(result, source);
   SPropertyOperations.set(result, "doNotGenerateAdapters", "" + source.isDoNotGenerateAdapters());
   SPropertyOperations.set(result, "genPath", source.getGenPath());
   SPropertyOperations.set(result, "languagePath", myFile.getPath());
   for (SModelReference ref : source.getAccessoryModels()) {
     SLinkOperations.getTargets(result, "accessoryModels", true).add(convert(ref));
   }
   for (GeneratorDescriptor descriptor : source.getGenerators()) {
     SLinkOperations.getTargets(result, "generator", true).add(convert(descriptor));
   }
   for (ModuleReference ref : source.getExtendedLanguages()) {
     SLinkOperations.getTargets(result, "extendedLanguages", true).add(convert(ref));
   }
   for (Dependency dep : source.getRuntimeModules()) {
     SLinkOperations.getTargets(result, "runtimeModules", true).add(convert(dep));
   }
   for (ModelRoot entry : source.getRuntimeStubModels()) {
     SLinkOperations.getTargets(result, "runtimeStubModels", true).add(convert(entry));
   }
   for (StubSolution sol : source.getStubSolutions()) {
     SLinkOperations.getTargets(result, "stubSolutions", true).add(convert(sol));
   }
   collectModels(result, source);
   return result;
 }
Beispiel #16
0
 @Override
 public int hashCode() {
   int result = file.hashCode();
   result = 31 * result + (parent != null ? parent.hashCode() : 0);
   result = 31 * result + (isHidden ? 1 : 0);
   return result;
 }
Beispiel #17
0
 protected AbstractModule(@Nullable IFile descriptorFile) {
   myDescriptorFile = descriptorFile;
   if (descriptorFile != null) {
     myFileSystem = descriptorFile.getFileSystem();
   } else {
     myFileSystem = getFSSingleton();
   }
 }
Beispiel #18
0
 @Nullable
 public static IFile getRealDescriptorFile(
     String filePath, DeploymentDescriptor deploymentDescriptor) {
   if (deploymentDescriptor.getSourcesJar() != null) {
     IFile moduleJar =
         FileSystem.getInstance()
             .getFileByPath(
                 filePath.substring(0, filePath.length() - SLASH_META_INF_MODULE_XML.length()));
     IFile sourcesJar = moduleJar.getParent().getDescendant(deploymentDescriptor.getSourcesJar());
     if (sourcesJar.exists() && deploymentDescriptor.getDescriptorFile() != null) {
       return FileSystem.getInstance()
           .getFileByPath(
               sourcesJar.getPath() + "!/module/" + deploymentDescriptor.getDescriptorFile());
     }
   }
   return null;
 }
Beispiel #19
0
  @Override
  public void rename(String newModelName, boolean changeFile) {
    assertCanChange();

    SModelReference oldName = getReference();
    fireBeforeModelRenamed(new SModelRenamedEvent(this, oldName.getModelName(), newModelName));

    // TODO update SModelId (if it contains modelName)
    // if(getReference().getModelId().getModelName() != null) { }
    SModelReference newModelReference =
        PersistenceFacade.getInstance()
            .createModelReference(
                getReference().getModuleReference(), getReference().getModelId(), newModelName);

    fireBeforeModelRenamed(newModelReference);
    changeModelReference(newModelReference);

    if (!changeFile) {
      save();
    } else {
      if (changeFile && !(getSource() instanceof FileDataSource)) {
        throw new UnsupportedOperationException("cannot change model file on non-file data source");
      }

      IFile oldFile = ((FileDataSource) getSource()).getFile();
      ModelRoot root = ModelRootUtil.getModelRoot(this);
      if (root instanceof DefaultModelRoot) {
        DefaultModelRoot defaultModelRoot = (DefaultModelRoot) root;
        String sourceRoot = null;
        for (String sr : defaultModelRoot.getFiles(FileBasedModelRoot.SOURCE_ROOTS)) {
          if (oldFile.getPath().startsWith(sr)) {
            // using the same sourceRoot
            sourceRoot = sr;
            break;
          }
        }
        try {
          IFile newFile =
              defaultModelRoot
                  .createSource(
                      newModelName,
                      FileUtil.getExtension(oldFile.getName()),
                      sourceRoot,
                      new HashMap<String, String>())
                  .getFile();
          newFile.getParent().mkdirs();
          newFile.createNewFile();
          changeModelFile(newFile);
          save();
          oldFile.delete();
        } catch (IOException e) {
          LOG.error("cannot rename " + getModelName() + ": " + e.getMessage());
          save();
        }
      }
    }

    fireModelRenamed(new SModelRenamedEvent(this, oldName.getModelName(), newModelName));
    fireModelRenamed(oldName);
  }
Beispiel #20
0
 public static ModuleDescriptor loadModuleDescriptor(
     IFile moduleDescriptorFile,
     TemplateQueryContext genContext,
     SNode originalModule,
     ModuleChecker.Reporter reporter) {
   MacroHelper helper =
       new ModuleLoaderUtils.ModuleMacroHelper(
           moduleDescriptorFile.getParent(), genContext, originalModule, reporter);
   String path = moduleDescriptorFile.getPath();
   if (path.endsWith(MPSExtentions.DOT_LANGUAGE)) {
     return LanguageDescriptorPersistence.loadLanguageDescriptor(moduleDescriptorFile, helper);
   } else if (path.endsWith(MPSExtentions.DOT_SOLUTION)) {
     return SolutionDescriptorPersistence.loadSolutionDescriptor(moduleDescriptorFile, helper);
   } else if (path.endsWith(MPSExtentions.DOT_DEVKIT)) {
     return DevkitDescriptorPersistence.loadDevKitDescriptor(moduleDescriptorFile);
   }
   throw new RuntimeException("unknown file type: " + moduleDescriptorFile.getName());
 }
Beispiel #21
0
 public static StructureModificationLog load(IFile modelFile) {
   IFile refactoringsFile = getRefactoringsFile(modelFile);
   if (!refactoringsFile.exists()) return null;
   try {
     HistoryReaderHandler handler = new HistoryReaderHandler();
     JDOMUtil.createSAXParser().parse(JDOMUtil.loadSource(refactoringsFile), handler);
     return handler.getResult();
   } catch (SAXParseException e) {
     LOG.warning(refactoringsFile.getPath() + " line " + e.getLineNumber());
   } catch (IOException e) {
     LOG.error(e);
   } catch (SAXException e) {
     LOG.error(e);
   } catch (ParserConfigurationException e) {
     LOG.error(e);
   }
   return null;
 }
Beispiel #22
0
  @Override
  public void scheduleUpdateForWrittenFiles(Iterable<IFile> writtenFiles) {
    final List<IFile> newFiles = new ArrayList<IFile>();
    final List<IFile> updatedFiles = new ArrayList<IFile>();
    for (IFile file : writtenFiles) {
      if (file.exists()) {
        updatedFiles.add(file);
      } else {
        newFiles.add(file);
      }
    }
    ApplicationManager.getApplication()
        .invokeLater(
            new IdeaWriteAction(
                new Runnable() {
                  @Override
                  public void run() {
                    // Recreate files using VFS
                    for (IFile file : newFiles) {
                      OutputStream out = null;
                      try {
                        // No need to close InputStream: it will be closed by loadFromStream()
                        byte[] content =
                            StreamUtil.loadFromStream(new FileInputStream(file.getPath()));

                        out = file.openOutputStream();
                        out.write(content);
                      } catch (IOException e) {
                        LOG.error(null, e);
                      } finally {
                        FileUtil.closeFileSafe(out);
                      }
                    }

                    // Refresh added files
                    for (IFile file : updatedFiles) {
                      FileSystem.getInstance().refresh(file);
                    }
                  }
                }));
  }
Beispiel #23
0
 private ModuleDescriptor loadDescriptorOnly_internal(IFile descriptorFile, Set<IFile> excludes) {
   try {
     ModuleDescriptor descriptor = loadModuleDescriptor(descriptorFile);
     if (descriptor != null) {
       processExcludes(descriptorFile, descriptor, excludes);
     }
     return descriptor;
   } catch (Exception t) {
     LOG.error("Fail to load module from descriptor " + descriptorFile.getPath(), t);
   }
   return null;
 }
Beispiel #24
0
 private SNode convertSolution(SolutionDescriptor source) {
   SNode result =
       SConceptOperations.createNewNode("jetbrains.mps.lang.project.structure.Solution", null);
   result.setId(SNodeId.fromString("~root"));
   SModelOperations.addRootNode(myModel, result);
   fill(result, source);
   SPropertyOperations.set(result, "dontLoadClasses", "" + source.isDontLoadClasses());
   SPropertyOperations.set(result, "outputPath", source.getOutputPath());
   SPropertyOperations.set(result, "solutionPath", myFile.getPath());
   collectModels(result, source);
   return result;
 }
Beispiel #25
0
  /**
   * Convert path from sources module descriptor for using on distribution /classes && /classes_gen
   * converts to bundle home path
   *
   * @param originalPath Original path from sources module descriptor
   * @return Converted path, null if path meaningless on packaged module
   */
  @Nullable
  private String convertPath(
      String originalPath,
      IFile bundleHome,
      IFile sourcesDescriptorFile,
      ModuleDescriptor descriptor) {
    MacroHelper macroHelper = MacrosFactory.forModuleFile(sourcesDescriptorFile);

    String canonicalPath = FileUtil.getCanonicalPath(originalPath).toLowerCase();

    // /classes && /classes_gen hack
    String suffix = descriptor.getCompileInMPS() ? CLASSES_GEN : CLASSES;
    if (canonicalPath.endsWith(suffix)) {
      // MacrosFactory based on original descriptor file because we use original descriptor file for
      // ModuleDescriptor reading, so all paths expanded to original descriptor file
      String classes = macroHelper.expandPath("${module}/" + suffix);
      if (FileUtil.getCanonicalPath(classes).equalsIgnoreCase(canonicalPath)) {
        return bundleHome.getPath();
      }
    } else if (FileUtil.getCanonicalPath(bundleHome.getPath()).equalsIgnoreCase(canonicalPath)) {
      return bundleHome.getPath();
    }

    // ${mps_home}/lib
    String mpsHomeLibPath =
        FileUtil.getCanonicalPath(PathManager.getHomePath() + File.separator + "lib").toLowerCase();
    if (canonicalPath.startsWith(mpsHomeLibPath)) {
      return canonicalPath;
    }

    // we used to keep originalPath if it has a macro not known to MPS here.
    // However, the check has been deprecated in 2012 and thus removed. I'm not 100% sure what
    // 'meaningless' in the contract of the method means. Of course, unknown macros make no sense
    // for us
    // and thus null is legitimate answer, OTOH, custom macros might have a lot of meaning to
    // someone else.
    //
    // ignore paths starts from ${module}/${project} etc
    return null;
  }
Beispiel #26
0
  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    SLibrary library = (SLibrary) o;

    if (isHidden != library.isHidden) return false;
    if (parent != null ? !parent.equals(library.parent) : library.parent != null) return false;
    if (!file.equals(library.file)) return false;

    return true;
  }
  private Set<SModel> getModels(IFile dir, String pkg) {

    Set<SModel> models = SetSequence.fromSet(new HashSet<SModel>());

    MultiStreamDataSource dataSource = newDataSource(dir);
    boolean thereAreJavaFiles = dataSource.getAvailableStreams().iterator().hasNext();

    if (thereAreJavaFiles) {
      SModelReference modelRef = Util.makeModelReference(pkg, getModule());
      // it can be a default package
      if (modelRef != null) {
        JavaSourceStubModelDescriptor model =
            new JavaSourceStubModelDescriptor(modelRef, dataSource, pkg);
        SetSequence.fromSet(models).addElement(model);

        SetSequence.fromSet(myDataSources).addElement(dataSource);
      }
    }

    // should be one line: dir.getChildren().where cannot be entered...
    Iterable<IFile> children = dir.getChildren();
    Iterable<IFile> subDirs =
        Sequence.fromIterable(children)
            .where(
                new IWhereFilter<IFile>() {
                  public boolean accept(IFile it) {
                    return it.isDirectory();
                  }
                });

    for (IFile subDir : Sequence.fromIterable(subDirs)) {
      String subPkg = (pkg.equals("") ? subDir.getName() : pkg + "." + subDir.getName());
      Set<SModel> set = getModels(subDir, subPkg);
      SetSequence.fromSet(models).addSequence(SetSequence.fromSet(set));
    }

    return models;
  }
Beispiel #28
0
  public void rename(@NotNull String newName) {
    SModuleReference oldRef = getModuleReference();
    renameModels(getModuleName(), newName, true);

    save(); // see MPS-18743, need to save before setting descriptor

    ModuleDescriptor descriptor = getModuleDescriptor();
    if (myDescriptorFile != null) {
      // fixme AP: this looks awful -- I agree; the right way is to have IFile something immutable
      // fixme or just work in <code>WatchedRoots</code> by IFile (not by String) and listen for
      // rename
      myFileSystem.removeListener(this);
      myDescriptorFile.rename(newName + "." + FileUtil.getExtension(myDescriptorFile.getName()));
      myFileSystem.addListener(this);
    }

    if (descriptor != null) {
      descriptor.setNamespace(newName);
      setModuleDescriptor(descriptor);
    }

    fireModuleRenamed(oldRef);
  }
Beispiel #29
0
  private <T> void readModuleDescriptors(
      IFile file,
      Set<IFile> excludes,
      List<T> result,
      boolean refreshFiles,
      DescriptorReader<T> reader) {
    if (!needProcess(file, excludes)) return;
    if (refreshFiles) {
      FileSystem.getInstance().refresh(file);
    }

    if (file.isDirectory()) {
      readModuleDescriptorsFromFolder(file, excludes, result, refreshFiles, reader);
    } else {
      readModuleDescriptorsFromFile(file, excludes, result, refreshFiles, reader);
    }
  }
Beispiel #30
0
  public void changeModelFile(IFile newModelFile) {
    assertCanChange();
    if (!(getSource() instanceof FileDataSource)) {
      throw new UnsupportedOperationException("cannot change model file on non-file data source");
    }

    FileDataSource source = (FileDataSource) getSource();
    if (source.getFile().getPath().equals(newModelFile.getPath())) return;

    IFile oldFile = source.getFile();
    jetbrains.mps.smodel.SModel model = getSModel();
    fireBeforeModelFileChanged(
        new SModelFileChangedEvent(model.getModelDescriptor(), oldFile, newModelFile));
    source.setFile(newModelFile);
    updateTimestamp();
    fireModelFileChanged(
        new SModelFileChangedEvent(model.getModelDescriptor(), oldFile, newModelFile));
  }