Example #1
0
 /**
  * Returns a map of installed packages to the respective version number.
  *
  * @param lockFile the pubspec.lock file
  * @return Map<String,String> Map<packageName,versionNumber>
  */
 public static Map<String, String> getPackageVersionMap(IResource lockFile) {
   try {
     return getPackageVersionMap(IFileUtilities.getContents((IFile) lockFile));
   } catch (CoreException exception) {
     DartCore.logError(exception);
   } catch (IOException exception) {
     DartCore.logError(exception);
   }
   return null;
 }
Example #2
0
 public final void runSafe() {
   try {
     run();
   } catch (Exception e) {
     // Don't log here... let caller determine what to do
     handleException(e);
   } catch (LinkageError e) {
     DartCore.logError(e);
     handleException(e);
   } catch (AssertionError e) {
     DartCore.logError(e);
     handleException(e);
   }
 }
  private boolean runPubServe(DartLaunchConfigWrapper wrapper) {

    stdOut = new StringBuilder();
    stdError = new StringBuilder();
    IResource resource = wrapper.getApplicationResource();
    console.printSeparator("Starting pub serve : " + resource.getProject().getName());

    workingDir = DartCore.getApplicationDirectory(resource);

    List<String> args = buildPubServeCommand();
    String dirName = getPubserveRootDir(workingDir, resource);
    if (dirName != null) {
      args.add(getPubserveRootDir(workingDir, resource));
    }
    ProcessBuilder builder = new ProcessBuilder();
    builder.command(args);

    builder.directory(workingDir.getLocation().toFile());

    try {
      process = builder.start();
    } catch (IOException e) {
      DartCore.logError(e);
      return false;
    }

    Thread stdoutThread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                copyStream(process.getInputStream(), stdOut, true);
              }
            });
    stdoutThread.start();

    Thread stderrThread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                copyStream(process.getErrorStream(), stdError, true);
              }
            });
    stderrThread.start();

    while (!isTerminated() && !stdOut.toString().contains(LOCAL_HOST_ADDR)) {
      try {
        Thread.sleep(200);
      } catch (Exception exception) {

      }
    }

    if (isTerminated()) {
      return false;
    }
    currentLaunch = wrapper;
    return true;
  }
Example #4
0
  /** Parse a single file and report the errors/warnings */
  static DartUnit parse(
      AnalysisServer server, File libraryFile, LibrarySource librarySource, File sourceFile) {
    ErrorListener errorListener = new ErrorListener(server);
    DartSource source = new UrlDartSource(sourceFile, librarySource);

    String sourceCode = null;
    try {
      sourceCode = FileUtilities.getContents(sourceFile);
    } catch (IOException e) {
      errorListener.onError(newIoError(source, e));
    }

    DartUnit dartUnit = null;
    if (sourceCode != null) {
      try {
        DartParser parser = new DartParser(source, sourceCode, errorListener);
        dartUnit = parser.parseUnit(source);
      } catch (Throwable e) {
        DartCore.logError("Exception while parsing " + sourceFile.getPath(), e);
        errorListener.onError(newParseFailure(source, e));
      }
    }

    errorListener.notifyParsed(libraryFile, sourceFile, dartUnit);
    return dartUnit != null ? dartUnit : new DartUnit(source, false);
  }
Example #5
0
 @Override
 public Void visitImportDirective(DartImportDirective node) {
   DartLibrary library = compilationUnit.getLibrary();
   try {
     if (Objects.equal(compilationUnit, library.getDefiningCompilationUnit())) {
       DartImport[] imports = library.getImports();
       for (DartImport imprt : imports) {
         // on URI of library - return defining Unit of imported Library
         SourceRange uriRange = imprt.getUriRange();
         if (SourceRangeUtils.contains(uriRange, startOffset)) {
           resolvedElement = null;
           foundElement = imprt.getLibrary().getDefiningCompilationUnit();
           wordRegion = new Region(uriRange.getOffset(), uriRange.getLength());
           candidateRegion = new Region(0, 0);
           throw new DartElementFoundException();
         }
         // on #import directive - return DartImport element
         SourceRange sourceRange = imprt.getSourceRange();
         if (SourceRangeUtils.contains(sourceRange, startOffset)) {
           resolvedElement = null;
           foundElement = imprt;
           wordRegion = new Region(sourceRange.getOffset(), sourceRange.getLength());
           candidateRegion = new Region(sourceRange.getOffset(), sourceRange.getLength());
           throw new DartElementFoundException();
         }
       }
     }
   } catch (DartModelException e) {
     DartCore.logError("Cannot access imports of " + library.getElementName(), e);
   }
   return super.visitImportDirective(node);
 }
 /** Initialize this index with information from the user libraries. */
 private boolean indexUserLibraries() {
   boolean librariesIndexed = true;
   try {
     AnalysisServer analysisServer = PackageLibraryManagerProvider.getDefaultAnalysisServer();
     SavedContext savedContext = analysisServer.getSavedContext();
     DartModel model = DartCore.create(ResourcesPlugin.getWorkspace().getRoot());
     for (DartProject project : model.getDartProjects()) {
       for (DartLibrary library : project.getDartLibraries()) {
         CompilationUnit compilationUnit = library.getDefiningCompilationUnit();
         if (compilationUnit == null) {
           continue;
         }
         IResource libraryResource = compilationUnit.getResource();
         if (libraryResource == null) {
           continue;
         }
         IPath libraryLocation = libraryResource.getLocation();
         if (libraryLocation == null) {
           continue;
         }
         File libraryFile = libraryLocation.toFile();
         savedContext.resolve(libraryFile, null);
       }
     }
   } catch (Exception exception) {
     librariesIndexed = false;
     DartCore.logError("Could not index user libraries", exception);
   }
   return librariesIndexed;
 }
  /**
   * Process the given resource within the context of the given working set in order to record the
   * data and relationships found within the resource.
   */
  public void indexResource(File libraryFile, File sourceFile, DartUnit dartUnit)
      throws DartModelException {

    // Get the LibrarySource

    LibrarySource librarySource = dartUnit.getLibrary().getSource();

    // Get the DartLibrary

    DartLibraryImpl library;
    IResource resource = ResourceUtil.getResource(libraryFile);
    if (resource == null) {
      library = new DartLibraryImpl(librarySource);
    } else {
      DartElement element = DartCore.create(resource);
      if (element instanceof CompilationUnitImpl) {
        element = ((CompilationUnitImpl) element).getLibrary();
      }
      if (!(element instanceof DartLibrary)) {
        DartCore.logError("Expected library to be associated with " + libraryFile);
        return;
      }
      library = (DartLibraryImpl) element;
    }

    // Get the CompilationUnit

    DartSource unitSource = (DartSource) dartUnit.getSourceInfo().getSource();
    CompilationUnit compilationUnit;
    IResource res = ResourceUtil.getResource(sourceFile);
    if (res != null) {
      DefaultWorkingCopyOwner workingCopy = DefaultWorkingCopyOwner.getInstance();
      compilationUnit = new CompilationUnitImpl(library, (IFile) res, workingCopy);
    } else {
      String relPath = unitSource.getRelativePath();
      compilationUnit = new ExternalCompilationUnitImpl(library, relPath, unitSource);
    }

    URI unitUri = unitSource.getUri();
    Resource indexerResource;
    if (PackageLibraryManager.isDartUri(unitUri)) {
      indexerResource =
          new Resource(
              ResourceFactory.composeResourceId(
                  librarySource.getUri().toString(), unitUri.toString()));
    } else if (PackageLibraryManager.isPackageUri(unitUri)) {
      indexerResource =
          new Resource(
              ResourceFactory.composeResourceId(
                  libraryFile.toURI().toString(), sourceFile.toURI().toString()));
    } else {
      indexerResource = ResourceFactory.getResource(compilationUnit);
    }

    // Queue the resource to be indexed

    indexResource(indexerResource, libraryFile, compilationUnit, dartUnit);
  }
 @Override
 public void run() {
   for (IFile file : files) {
     try {
       format(file, new NullProgressMonitor());
     } catch (Exception e) {
       DartCore.logError(e);
     }
   }
 }
 /**
  * Initialize this index from the given file.
  *
  * @param indexFile the file from which this index is to be initialized
  * @return <code>true</code> if the index was correctly initialized
  */
 private boolean initializeIndexFrom(File indexFile) {
   if (indexFile == null) {
     if (DartCoreDebug.TRACE_INDEX_STATISTICS) {
       DartCore.logInformation("Index file was null");
     }
     return false;
   } else if (!indexFile.exists()) {
     if (DartCoreDebug.TRACE_INDEX_STATISTICS) {
       DartCore.logInformation("Index file " + indexFile.getAbsolutePath() + " does not exist");
     }
     return false;
   }
   if (DartCoreDebug.TRACE_INDEX_STATISTICS) {
     DartCore.logInformation(
         "About to initialize the index from file "
             + indexFile.getAbsolutePath()
             + " (size = "
             + indexFile.getTotalSpace()
             + " bytes)");
   }
   try {
     boolean wasRead = readIndexFrom(indexFile);
     if (DartCoreDebug.TRACE_INDEX_STATISTICS) {
       logIndexStats("After initializing the index from file " + indexFile.getAbsolutePath());
     }
     synchronized (indexStore) {
       return wasRead && indexStore.getResourceCount() > 0;
     }
   } catch (Exception exception) {
     DartCore.logError("Could not read index file " + indexFile.getAbsolutePath(), exception);
   }
   if (DartCoreDebug.TRACE_INDEX_STATISTICS) {
     logIndexStats("Deleting corrupted index file " + indexFile.getAbsolutePath());
   }
   try {
     indexFile.delete();
   } catch (Exception exception) {
     DartCore.logError(
         "Could not delete corrupt index file " + indexFile.getAbsolutePath(), exception);
   }
   return false;
 }
Example #10
0
 /**
  * Write the contents of this index to the given file.
  *
  * @param indexFile the file to which this index will be written
  * @throws IOException if the index could not be written to the given file
  */
 private void writeIndexTo(File indexFile) {
   boolean successfullyWritten = true;
   ObjectOutputStream output = null;
   try {
     output = new ObjectOutputStream(new FileOutputStream(indexFile));
     long startTime = System.currentTimeMillis();
     writeIndex(output);
     if (DartCoreDebug.PERF_INDEX) {
       long endTime = System.currentTimeMillis();
       DartCore.logInformation("Writing the index took " + (endTime - startTime) + " ms");
     }
   } catch (IOException exception) {
     successfullyWritten = false;
     DartCore.logError(
         "Could not write index file: \"" + indexFile.getAbsolutePath() + "\"", exception);
   } finally {
     if (output != null) {
       try {
         output.flush();
       } catch (IOException exception) {
         successfullyWritten = false;
         DartCore.logError(
             "Could not flush index file after write: \"" + indexFile.getAbsolutePath() + "\"",
             exception);
       }
       try {
         output.close();
       } catch (IOException exception) {
         successfullyWritten = false;
         DartCore.logError(
             "Could not close index file after write: \"" + indexFile.getAbsolutePath() + "\"",
             exception);
       }
     }
   }
   if (!successfullyWritten) {
     if (!indexFile.delete()) {
       DartCore.logError(
           "Could not delete corrupted index file: \"" + indexFile.getAbsolutePath() + "\"");
     }
   }
 }
  @Override
  protected IStatus run(IProgressMonitor monitor) {
    IStatus status = DartSdkManager.getManager().upgrade(monitor);

    if (!status.isOK()) {
      if (status.getException() != null) {
        DartCore.logError(status.getException());
      }
    }

    return status;
  }
Example #12
0
 /**
  * Answer the absolute file for the specified URI
  *
  * @return the file or <code>null</code> if unknown
  */
 static File toFile(AnalysisServer server, URI uri) {
   String scheme = uri.getScheme();
   if (scheme == null || "file".equals(scheme)) {
     File file = new File(uri.getPath());
     if (file.isAbsolute()) {
       return file;
     }
     DartCore.logError("Non absolute path: " + file);
     return null;
   }
   if (SystemLibraryManager.isDartUri(uri)) {
     URI resolveUri = server.getLibraryManager().resolveDartUri(uri);
     if (resolveUri == null) {
       DartCore.logError("Failed to resolve: " + uri);
       return null;
     }
     return new File(resolveUri.getPath());
   }
   DartCore.logError("Unknown library scheme : " + uri);
   return null;
 }
Example #13
0
 @Override
 public Void visitIdentifier(DartIdentifier node) {
   if (foundElement == null) {
     int start = node.getSourceInfo().getOffset();
     int length = node.getSourceInfo().getLength();
     int end = start + length;
     if (start <= startOffset && endOffset <= end) {
       wordRegion = new Region(start, length);
       Element targetElement = DartAstUtilities.getElement(node, includeDeclarations);
       if (targetElement == null) {
         foundElement = null;
       } else {
         if (targetElement instanceof VariableElement) {
           VariableElement variableElement = (VariableElement) targetElement;
           resolvedElement = variableElement;
           if (variableElement.getKind() == ElementKind.PARAMETER
               || variableElement.getKind() == ElementKind.VARIABLE) {
             foundElement =
                 BindingUtils.getDartElement(compilationUnit.getLibrary(), variableElement);
             candidateRegion =
                 new Region(
                     variableElement.getNameLocation().getOffset(),
                     variableElement.getNameLocation().getLength());
           } else {
             foundElement = null;
           }
         } else {
           findElementFor(targetElement);
           // Import prefix is resolved into LibraryElement, so it is correct that corresponding
           // DartElement is DartLibrary, but this is not what we (and user) wants, because
           // it looses information. We want DartImport, it gives both DartLibrary and name.
           if (foundElement instanceof DartLibrary) {
             try {
               DartImport[] imports = compilationUnit.getLibrary().getImports();
               for (DartImport imprt : imports) {
                 if (Objects.equal(imprt.getLibrary(), foundElement)
                     && Objects.equal(imprt.getPrefix(), node.getName())) {
                   foundElement = imprt;
                   SourceRange range = imprt.getNameRange();
                   candidateRegion = new Region(range.getOffset(), range.getLength());
                 }
               }
             } catch (DartModelException e) {
               DartCore.logError("Cannot resolve import " + foundElement.getElementName(), e);
             }
           }
         }
       }
       throw new DartElementFoundException();
     }
   }
   return null;
 }
Example #14
0
  /**
   * Given a simple name for a javascript file, return the SourceMapping object that can map that
   * back to it's source Dart file. This methods differs from {@link
   * #getCachedSourceMappingPath(IPath)} in that it knows where on disk the named javascript file
   * might live.
   *
   * @param jsFileName
   * @return
   */
  private Object /* SourceMapping */ getCachedSourceMapping(String jsFileName) {
    try {
      IPath outputLocation = getMainDartProject().getOutputLocation();

      IPath sourceMapPath = outputLocation.append(jsFileName + ".map");

      return getCachedSourceMappingPath(sourceMapPath);
    } catch (DartModelException exception) {
      DartCore.logError(exception);

      return null;
    }
  }
Example #15
0
  /**
   * Return a yaml string for the given {@link PubYamlObject}
   *
   * @param pubYamlObject bean for pubspec
   * @return String
   */
  public static String buildYamlString(PubYamlObject pubYamlObject) {

    try {
      SkipEmptyRepresenter repr = new SkipEmptyRepresenter();
      repr.setPropertyUtils(new UnsortedPropertyUtils());
      Yaml yaml = new Yaml(repr);
      String yamlString = yaml.dumpAsMap(pubYamlObject);
      return yamlString;
    } catch (Exception e) {
      DartCore.logError(e);
      return null;
    }
  }
 @Override
 public LibraryElement getLibraryElement(IFile file) {
   ResourceMap map = getResourceMap(file);
   Source source = map.getSource(file);
   if (source != null) {
     try {
       return map.getContext().computeLibraryElement(source);
     } catch (AnalysisException e) {
       DartCore.logError("Failed to compute library element: " + file, e);
     }
   }
   return null;
 }
Example #17
0
 /**
  * Initialize this index with information from the bundled libraries.
  *
  * @return <code>true</code> if the bundled libraries were successfully indexed
  */
 private boolean indexBundledLibraries() {
   boolean librariesIndexed = true;
   long startTime = System.currentTimeMillis();
   PackageLibraryManager libraryManager = PackageLibraryManagerProvider.getPackageLibraryManager();
   ArrayList<String> librarySpecs = new ArrayList<String>(libraryManager.getAllLibrarySpecs());
   if (librarySpecs.remove("dart:html")) {
     librarySpecs.add("dart:html");
   }
   AnalysisServer analysisServer = PackageLibraryManagerProvider.getDefaultAnalysisServer();
   analysisServer.reanalyze();
   SavedContext savedContext = analysisServer.getSavedContext();
   for (String urlSpec : librarySpecs) {
     try {
       URI libraryUri = new URI(urlSpec);
       File libraryFile = new File(libraryManager.resolveDartUri(libraryUri));
       savedContext.resolve(libraryFile, null);
     } catch (URISyntaxException exception) {
       librariesIndexed = false;
       DartCore.logError(
           "Invalid URI returned from the system library manager: \"" + urlSpec + "\"", exception);
     } catch (Exception exception) {
       librariesIndexed = false;
       DartCore.logError("Could not index bundled libraries", exception);
     }
   }
   if (DartCoreDebug.PERF_INDEX) {
     long endTime = System.currentTimeMillis();
     DartCore.logInformation(
         "Initializing the index with information from bundled libraries took "
             + (endTime - startTime)
             + " ms ("
             + initIndexingTime
             + " ms indexing)");
   }
   return librariesIndexed;
 }
Example #18
0
  protected void processHtml(IFile file) {
    try {
      MarkerUtilities.deleteMarkers(file);

      XmlDocument document =
          new HtmlParser(Files.toString(file.getLocation().toFile(), Charsets.UTF_8)).parse();

      validate(document, file);
    } catch (CoreException e) {
      DartCore.logError(e);
    } catch (IOException ioe) {

    }

    HtmlAnalyzeHelper.analyze(file);
  }
Example #19
0
 /**
  * Return a list of names of the dependencies specified in the pubspec
  *
  * @param contents String contents of pubspec.yaml
  * @return List<String> names of the packages specified as dependencies
  */
 @SuppressWarnings("unchecked")
 public static List<String> getNamesOfDependencies(String contents) {
   Map<String, Object> map = null;
   try {
     map = parsePubspecYamlToMap(contents);
   } catch (ScannerException e) {
     DartCore.logError(e);
   }
   if (map != null) {
     Map<String, Object> dependecies =
         (Map<String, Object>) map.get(PubspecConstants.DEPENDENCIES);
     if (dependecies != null && !dependecies.isEmpty()) {
       return new ArrayList<String>(dependecies.keySet());
     }
   }
   return null;
 }
 private void copyStream(InputStream in, StringBuilder stringBuilder, boolean toConsole) {
   byte[] buffer = new byte[2048];
   try {
     int count = in.read(buffer);
     while (count != -1) {
       if (count > 0) {
         String str = new String(buffer, 0, count);
         stringBuilder.append(str);
         if (toConsole) {
           console.print(str);
         }
       }
       count = in.read(buffer);
     }
     in.close();
   } catch (IOException ioe) {
     DartCore.logError(ioe);
   }
 }
  /**
   * Returns the name of the directory containing the given resource that can be used as root by pub
   * serve. Pub serve uses the directories that are siblings to the pubspec as root.
   *
   * @param container - directory which contains the pubspec.yaml
   * @param resource - the resource to launch
   * @return
   */
  private String getPubserveRootDir(IContainer container, IResource resource) {

    try {
      IResource[] folders = container.members();
      for (IResource folder : folders) {
        if (folder instanceof IFolder
            && !(folder.getName().equals(DartCore.PACKAGES_DIRECTORY_NAME)
                || folder.getName().equals(DartCore.BUILD_DIRECTORY_NAME))) {
          if (resource.getFullPath().toString().startsWith(folder.getFullPath().toString())) {
            return folder.getName();
          }
        }
      }
    } catch (CoreException e) {
      DartCore.logError(e);
    }

    return null;
  }
 /**
  * Send a serve directory command to the current pub serve
  *
  * @param resource
  * @return
  */
 private boolean serveDirectory(IResource resource) {
   CountDownLatch latch = new CountDownLatch(1);
   final boolean[] done = new boolean[1];
   done[0] = false;
   try {
     pubConnection
         .getCommands()
         .serveDirectory(
             getPubserveRootDir(workingDir, resource), new ServeDirectoryCallback(latch, done));
   } catch (IOException e) {
     DartCore.logError(e);
   }
   try {
     latch.await(3000, TimeUnit.MILLISECONDS);
   } catch (InterruptedException e) {
     // do nothing
   }
   return done[0];
 }
Example #23
0
  /**
   * Given a path for a javascript file, return the SourceMapping object that can map that back to
   * it's source Dart file.
   *
   * @param sourceMapPath
   * @return
   */
  private Object /* SourceMapping */ getCachedSourceMappingPath(IPath sourceMapPath) {
    if (sourceMappingCache.containsKey(sourceMapPath)) {
      return sourceMappingCache.get(sourceMapPath);
    } else {
      try {
        String fileContents = getContentsOf(sourceMapPath);

        // long start = System.currentTimeMillis();

        //        SourceMapping mapping = SourceMapConsumerFactory.parse(fileContents,
        //            new SourceMapSupplier() {
        //              @Override
        //              public String getSourceMap(String url) throws IOException {
        //                return getSourceMapContentsAt(url);
        //              }
        //            });
        //
        //        //System.out.println(sourceMapPath.lastSegment() + " parse time: "
        //        //    + (System.currentTimeMillis() - start) + "ms");
        //
        //        sourceMappingCache.put(sourceMapPath, mapping);
        //
        //        return mapping;
        //      } catch (SourceMapParseException exception) {
        //        DartCore.logError(exception);

        return null;
      } catch (FileNotFoundException exception) {
        // This is an expected error - no need to log the exception.

        return null;
      } catch (IOException exception) {
        DartCore.logError(exception);

        return null;
      }
    }
  }
Example #24
0
 /**
  * Read the contents of this index from the given file.
  *
  * @param indexFile the file from which this index will be read
  * @return {@code true} if the file was correctly read
  * @throws IOException if the index could not be read from the given file
  */
 private boolean readIndexFrom(File indexFile) throws IOException {
   ObjectInputStream input = null;
   try {
     input = new ObjectInputStream(new FileInputStream(indexFile));
     long startTime = System.currentTimeMillis();
     boolean wasRead = readIndex(input);
     if (DartCoreDebug.PERF_INDEX) {
       long endTime = System.currentTimeMillis();
       DartCore.logInformation("Reading the index took " + (endTime - startTime) + " ms");
     }
     return wasRead;
   } finally {
     if (input != null) {
       try {
         input.close();
       } catch (IOException exception) {
         DartCore.logError(
             "Could not close index file after read: \"" + indexFile.getAbsolutePath() + "\"",
             exception);
       }
     }
   }
 }
Example #25
0
  /**
   * Returns a map of installed packages to the respective version number.
   *
   * @param lockFileContents string contents of pubspec.lock file
   * @return Map<String,String> Map<packageName,versionNumber>
   */
  @SuppressWarnings("unchecked")
  public static Map<String, String> getPackageVersionMap(String lockFileContents) {

    Map<String, String> versionMap = new HashMap<String, String>();
    Map<String, Object> map = null;
    try {
      map = PubYamlUtils.parsePubspecYamlToMap(lockFileContents);
    } catch (ScannerException e) {
      DartCore.logError(e);
    }
    if (map != null) {
      Map<String, Object> packagesMap = (Map<String, Object>) map.get("packages");
      if (packagesMap != null) {
        for (String key : packagesMap.keySet()) {
          Map<String, Object> attrMap = (Map<String, Object>) packagesMap.get(key);
          String version = (String) attrMap.get(PubspecConstants.VERSION);
          if (version != null) {
            versionMap.put(key, version);
          }
        }
      }
    }
    return versionMap;
  }
Example #26
0
 public void shutdown() {
   synchronized (indexStore) {
     if (DartCoreDebug.TRACE_INDEX_STATISTICS) {
       logIndexStats("In shutdown, before writing the index");
     }
     if (hasBeenInitialized) {
       if (hasPendingClear()) {
         try {
           if (DartCoreDebug.TRACE_INDEX_STATISTICS) {
             DartCore.logInformation("In shutdown, deleting the index file");
           }
           getIndexFile().delete();
         } catch (Exception exception) {
           DartCore.logError("Could not delete the index file", exception);
         }
       } else {
         writeIndexTo(getIndexFile());
         if (DartCoreDebug.TRACE_INDEX_STATISTICS) {
           logIndexStats("In shutdown, after writing the index");
         }
       }
     }
   }
 }
Example #27
0
  /**
   * Resolve the specified library and any imported libraries that have not already been resolved.
   *
   * @return a map of newly resolved libraries
   */
  static Map<URI, LibraryUnit> resolve(
      AnalysisServer server,
      Library library,
      Map<URI, LibraryUnit> resolvedLibs,
      Map<URI, DartUnit> parsedUnits) {
    ErrorListener errorListener = new ErrorListener(server);

    File libraryFile = library.getFile();
    LibrarySource librarySource = library.getLibrarySource();
    provider.clearCachedArtifacts();

    Map<URI, LibraryUnit> newlyResolved = null;
    try {
      newlyResolved =
          DartCompiler.analyzeLibraries(
              librarySource, resolvedLibs, parsedUnits, config, provider, errorListener);
    } catch (IOException e) {
      errorListener.onError(newIoError(librarySource, e));
    } catch (Throwable e) {
      DartCore.logError("Exception while resolving " + libraryFile.getPath(), e);
      DartCompilationError error =
          new DartCompilationError(
              librarySource, AnalysisErrorCode.RESOLUTION_FAILURE, e.getMessage());
      error.setSource(librarySource);
      errorListener.onError(error);
    }

    if (newlyResolved != null) {
      notifyParsedDuringResolve(server, parsedUnits, newlyResolved.values(), errorListener);
      errorListener.notifyResolved(newlyResolved);
    } else {
      newlyResolved = new HashMap<URI, LibraryUnit>();
      newlyResolved.put(libraryFile.toURI(), new LibraryUnit(librarySource));
    }
    return newlyResolved;
  }
Example #28
0
  /**
   * Runs the pub command.
   *
   * @return the result of running the pub command
   */
  public IStatus runSilent(IProgressMonitor monitor) {
    try {
      // Build the process description to run pub
      DartSdk sdk = DartSdkManager.getManager().getSdk();
      File pubFile = sdk.getPubExecutable();

      ProcessBuilder builder = new ProcessBuilder();
      builder.directory(container.getLocation().toFile());
      builder.redirectErrorStream(true);

      List<String> args = new ArrayList<String>();
      if (DartCore.isMac()) {
        args.add("/bin/bash");
        args.add("--login");
        args.add("-c");
        args.add("\"" + pubFile.getAbsolutePath() + "\"" + " " + command);
      } else {
        args.add(pubFile.getAbsolutePath());
        args.add(command);
      }
      builder.command(args);

      // Run the pub command as an external process.
      ProcessRunner runner = newProcessRunner(builder);

      try {
        runner.runSync(monitor);
      } catch (IOException e) {
        String message = NLS.bind(PubMessages.RunPubJob_failed, command, e.toString());
        return new Status(IStatus.CANCEL, DartCore.PLUGIN_ID, message, e);
      }

      StringBuilder stringBuilder = new StringBuilder();

      if (!runner.getStdOut().isEmpty()) {
        stringBuilder.append(runner.getStdOut().trim() + "\n"); // $NON-NLS-1$
      }

      int exitCode = runner.getExitCode();

      if (exitCode != 0) {
        String output = "[" + exitCode + "] " + stringBuilder.toString();
        String message = NLS.bind(PubMessages.RunPubJob_failed, command, output);
        return new Status(IStatus.ERROR, DartCore.PLUGIN_ID, message);
      }

      try {
        // Refresh the Eclipse resources
        container.refreshLocal(IResource.DEPTH_INFINITE, monitor);
      } catch (CoreException e) {
        // Log the exception and move on
        DartCore.logError("Exception refreshing " + container, e);
      }

      return new Status(IStatus.OK, DartCore.PLUGIN_ID, stringBuilder.toString());
    } catch (OperationCanceledException exception) {
      String message = NLS.bind(PubMessages.RunPubJob_canceled, command);
      return new Status(IStatus.CANCEL, DartCore.PLUGIN_ID, message, exception);
    } finally {
      monitor.done();
    }
  }
Example #29
0
  /** Map from the source language to the target language (Dart to Javascript). */
  public SourceLocation mapDartToJavascript(IFile file, int line) {
    // given the file, find the dart element
    DartElement dartElement = DartCore.create(file);

    if (dartElement == null) {
      return SourceLocation.UNKNOWN_LOCATION;
    }

    // given that, find the dart application / library
    DartLibraryImpl dartLibrary = (DartLibraryImpl) dartElement.getAncestor(DartLibrary.class);

    if (dartLibrary == null) {
      return SourceLocation.UNKNOWN_LOCATION;
    }

    try {
      // [out/DartAppFileName.app.js.map]

      IPath outputLocation = getMainDartProject().getOutputLocation();

      List<LibraryConfigurationFileImpl> libraryConfigurationFiles =
          dartLibrary.getChildrenOfType(LibraryConfigurationFileImpl.class);

      //      if (libraryConfigurationFiles.size() > 0) {
      //        String libraryName = libraryConfigurationFiles.get(0).getFile().getName();
      //
      //        IPath sourceMapPath = outputLocation.append(libraryName + ".js.map");
      //
      //        SourceMapping mapping = getCachedSourceMappingPath(sourceMapPath);
      //
      //        if (mapping != null && mapping instanceof SourceMappingReversable) {
      //          SourceMappingReversable revMapping = (SourceMappingReversable) mapping;
      //
      //          String sourcePath = findMatchingSourcePath(file, revMapping);
      //
      //          if (sourcePath != null) {
      //            Collection<OriginalMapping> mappings = revMapping.getReverseMapping(sourcePath,
      // line, 1);
      //
      //            // TODO(devoncarew): We need to handle the case where there are more then one
      // mappings
      //            // returned; this will probably involve setting one breakpoint per mapping. More
      // then
      //            // one mapping ==> something like a function that's been inlined into multiple
      // places.
      //            if (mappings.size() > 0) {
      //              OriginalMapping map = mappings.iterator().next();
      //
      //              String fileName = map.getOriginalFile();
      //              int lineNumber = map.getLineNumber();
      //
      //              return new SourceLocation(new Path(fileName), lineNumber);
      //            }
      //          }
      //        }
      //      }
    } catch (DartModelException exception) {
      DartCore.logError(exception);
    }

    return SourceLocation.UNKNOWN_LOCATION;
  }
  /**
   * Creates a new project resource.
   *
   * @param name the project name
   * @param newProjectHandle the project handle
   * @param projectType the type of project
   * @param location the location
   * @param runnableContext a context for executing the creation operation
   * @param shell the shell (for UI context)
   * @return the created project resource, or <code>null</code> if the project was not created
   */
  public static IProject createNewProject(
      String name,
      final IProject newProjectHandle,
      final ProjectType projectType,
      URI location,
      final IRunnableContext runnableContext,
      final Shell shell) {

    final IProjectDescription description = createProjectDescription(newProjectHandle, location);

    // create the new project operation
    IRunnableWithProgress op =
        new IRunnableWithProgress() {
          @Override
          public void run(IProgressMonitor monitor) throws InvocationTargetException {
            CreateProjectOperation op =
                new CreateProjectOperation(description, ResourceMessages.NewProject_windowTitle);
            try {
              IStatus status = op.execute(monitor, WorkspaceUndoUtil.getUIInfoAdapter(shell));

              if (status.isOK() && projectType != ProjectType.NONE) {
                createProjectContent(newProjectHandle, projectType);
              }
            } catch (ExecutionException e) {
              throw new InvocationTargetException(e);
            } catch (CoreException e) {
              throw new InvocationTargetException(e);
            }
          }
        };

    try {
      runnableContext.run(true, true, op);
    } catch (InterruptedException e) {
      return null;
    } catch (InvocationTargetException e) {
      Throwable t = e.getTargetException();
      if (t instanceof ExecutionException && t.getCause() instanceof CoreException) {
        CoreException cause = (CoreException) t.getCause();
        StatusAdapter status;
        if (cause.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) {
          status =
              new StatusAdapter(
                  StatusUtil.newStatus(
                      IStatus.WARNING,
                      NLS.bind(
                          ResourceMessages.NewProject_caseVariantExistsError,
                          newProjectHandle.getName()),
                      cause));
        } else {
          status =
              new StatusAdapter(
                  StatusUtil.newStatus(
                      cause.getStatus().getSeverity(),
                      ResourceMessages.NewProject_errorMessage,
                      cause));
        }
        status.setProperty(
            IStatusAdapterConstants.TITLE_PROPERTY, ResourceMessages.NewProject_errorMessage);
        StatusManager.getManager().handle(status, StatusManager.BLOCK);
      } else {
        StatusAdapter status =
            new StatusAdapter(
                new Status(
                    IStatus.WARNING,
                    IDEWorkbenchPlugin.IDE_WORKBENCH,
                    0,
                    NLS.bind(ResourceMessages.NewProject_internalError, t.getMessage()),
                    t));
        status.setProperty(
            IStatusAdapterConstants.TITLE_PROPERTY, ResourceMessages.NewProject_errorMessage);
        StatusManager.getManager().handle(status, StatusManager.LOG | StatusManager.BLOCK);
      }
      return null;
    }
    try {
      IProjectUtilities.configurePackagesFilter(newProjectHandle);
    } catch (CoreException e) {
      DartCore.logError("Could not set package filter on folder " + newProjectHandle.getName(), e);
    }

    return newProjectHandle;
  }