Ejemplo n.º 1
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);
      }
    }
  }
Ejemplo n.º 2
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);
        }
      }
    }
  }
Ejemplo n.º 3
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);
  }
  @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);
      }
    }
  }
  /*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;
  }
Ejemplo n.º 6
0
  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;
  }
Ejemplo n.º 7
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());
 }
Ejemplo n.º 8
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);
  }
Ejemplo n.º 9
0
 private boolean needProcess(IFile file, Set<IFile> excludes) {
   return !FileSystem.getInstance().isFileIgnored(file.getName()) && !excludes.contains(file);
 }
Ejemplo n.º 10
0
  private <T> MultiMap<SModel, T> findCandidates(
      Collection<SModel> models,
      Set<T> elems,
      Consumer<SModel> processedModels,
      Function<T, UsageEntry> id) {
    // get all files in scope
    final ManyToManyMap<SModel, VirtualFile> scopeFiles = new ManyToManyMap<SModel, VirtualFile>();
    for (final SModel sm : models) {
      if (sm instanceof EditableSModel && ((EditableSModel) sm).isChanged()) {
        continue;
      }

      DataSource source = sm.getSource();
      // these are data sources this participant knows about
      if (!(source instanceof FileDataSource || source instanceof FilePerRootDataSource)) {
        continue;
      }

      /*
      This is a tmp fix for MPS-24151. See the issue to learn about the correct fix
       */
      if (!(sm instanceof DefaultSModelDescriptor)) {
        continue;
      }

      Collection<IFile> modelFiles = getDataSourceFiles(source);
      for (IFile modelFile : modelFiles) {
        String ext = FileUtil.getExtension(modelFile.getName());
        if (ext == null || modelFile.isDirectory()) {
          continue;
        }

        VirtualFile vf = VirtualFileUtils.getOrCreateVirtualFile(modelFile);
        if (vf == null) {
          LogManager.getLogger(MPSModelsFastFindSupport.class)
              .warn(
                  String.format(
                      "Model %s: virtual file not found for model file. Model file: %s",
                      sm.getName(), modelFile.getPath()));
          continue;
        }
        processedModels.consume(sm);
        scopeFiles.addLink(sm, vf);
      }
    }

    // filter files with usages
    ConcreteFilesGlobalSearchScope allFiles =
        new ConcreteFilesGlobalSearchScope(scopeFiles.getSecond());
    // process indexes
    MultiMap<SModel, T> result = new SetBasedMultiMap<SModel, T>();
    for (T elem : elems) {
      UsageEntry entry = id.apply(elem);

      Collection<VirtualFile> matchingFiles;

      try {
        matchingFiles = MPSModelsIndexer.getContainingFiles(entry, allFiles);
      } catch (ProcessCanceledException ce) {
        matchingFiles = Collections.emptyList();
      }

      // back-transform
      for (VirtualFile file : matchingFiles) {
        for (SModel m : scopeFiles.getBySecond(file)) {
          result.putValue(m, elem);
        }
      }
    }
    return result;
  }