Java源码示例:com.intellij.openapi.compiler.CompileContext

示例1
@Override
public boolean execute(CompileContext context) {
    if(context.getMessageCount(CompilerMessageCategory.ERROR) > 0) {
        RoboVmPlugin.logError(context.getProject(), "Can't compile application due to previous compilation errors");
        return false;
    }

    RunConfiguration c = context.getCompileScope().getUserData(CompileStepBeforeRun.RUN_CONFIGURATION);
    if(c == null || !(c instanceof RoboVmRunConfiguration)) {
        CreateIpaAction.IpaConfig ipaConfig = context.getCompileScope().getUserData(CreateIpaAction.IPA_CONFIG_KEY);
        if(ipaConfig != null) {
            return compileForIpa(context, ipaConfig);
        } else {
            return true;
        }
    } else {
        return compileForRunConfiguration(context, (RoboVmRunConfiguration)c);
    }
}
 
示例2
public void actionPerformed(final AnActionEvent e) {
    final CreateIpaDialog dialog = new CreateIpaDialog(e.getProject());
    dialog.show();
    if(dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) {
        // create IPA
        IpaConfig ipaConfig = dialog.getIpaConfig();
        CompileScope scope = CompilerManager.getInstance(e.getProject()).createModuleCompileScope(ipaConfig.module, true);
        scope.putUserData(IPA_CONFIG_KEY, ipaConfig);
        CompilerManager.getInstance(e.getProject()).compile(scope, new CompileStatusNotification() {
            @Override
            public void finished(boolean aborted, int errors, int warnings, CompileContext compileContext) {
                RoboVmPlugin.logInfo(e.getProject(), "IPA creation complete, %d errors, %d warnings", errors, warnings);
            }
        });
    }
}
 
示例3
private void refactor(String currentStepText, String newStepText, TransactionId contextTransaction, CompileContext context, RefactorStatusCallback refactorStatusCallback) {
    refactorStatusCallback.onStatusChange("Refactoring...");
    Module module = GaugeUtil.moduleForPsiElement(file);
    TransactionGuard.getInstance().submitTransaction(() -> {
    }, contextTransaction, () -> {
        Api.PerformRefactoringResponse response = null;
        FileDocumentManager.getInstance().saveAllDocuments();
        FileDocumentManager.getInstance().saveDocumentAsIs(editor.getDocument());
        GaugeService gaugeService = Gauge.getGaugeService(module, true);
        try {
            response = gaugeService.getGaugeConnection().sendPerformRefactoringRequest(currentStepText, newStepText);
        } catch (Exception e) {
            refactorStatusCallback.onFinish(new RefactoringStatus(false, String.format("Could not execute refactor command: %s", e.toString())));
            return;
        }
        new UndoHandler(response.getFilesChangedList(), module.getProject(), "Refactoring").handle();
        if (!response.getSuccess()) {
            showMessage(response, context, refactorStatusCallback);
            return;
        }
        refactorStatusCallback.onFinish(new RefactoringStatus(true));
    });
}
 
示例4
private static void addErrorToContext(String error, CompileContext context,
                                      String errorRoot)
{
    // TODO: Add a button to the Haxe module settings to control whether we always open the window or not.
    if (context.getUserData(messageWindowAutoOpened) == null) {
        openCompilerMessagesWindow(context);
        context.putUserData(messageWindowAutoOpened, "yes");
    }

    final HaxeCompilerError compilerError = HaxeCompilerError.create
        (errorRoot,
         error,
         !ApplicationManager.getApplication().isUnitTestMode());
    

    if (null != compilerError) {
        String path = compilerError.getPath();
        context.addMessage
            (compilerError.getCategory(),
             compilerError.getErrorMessage(),
             path == null ? null : VfsUtilCore.pathToUrl(compilerError.getPath()),
             compilerError.getLine(),
             compilerError.getColumn());
    }
}
 
示例5
@Nonnull
public static Pair<InputStream, Long> getArchiveEntryInputStream(VirtualFile sourceFile, final CompileContext context) throws IOException {
  final String fullPath = sourceFile.getPath();
  final int jarEnd = fullPath.indexOf(ArchiveFileSystem.ARCHIVE_SEPARATOR);
  LOG.assertTrue(jarEnd != -1, fullPath);
  String pathInJar = fullPath.substring(jarEnd + ArchiveFileSystem.ARCHIVE_SEPARATOR.length());
  String jarPath = fullPath.substring(0, jarEnd);
  final ZipFile jarFile = new ZipFile(new File(FileUtil.toSystemDependentName(jarPath)));
  final ZipEntry entry = jarFile.getEntry(pathInJar);
  if (entry == null) {
    context.addMessage(CompilerMessageCategory.ERROR, "Cannot extract '" + pathInJar + "' from '" + jarFile.getName() + "': entry not found", null, -1, -1);
    return Pair.empty();
  }

  BufferedInputStream bufferedInputStream = new BufferedInputStream(jarFile.getInputStream(entry)) {
    @Override
    public void close() throws IOException {
      super.close();
      jarFile.close();
    }
  };
  return Pair.<InputStream, Long>create(bufferedInputStream, entry.getSize());
}
 
示例6
public static VirtualFile getSourceRoot(CompileContext context, Module module, VirtualFile file) {
  final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(module.getProject()).getFileIndex();
  final VirtualFile root = fileIndex.getSourceRootForFile(file);
  if (root != null) {
    return root;
  }
  // try to find among roots of generated files.
  final VirtualFile[] sourceRoots = context.getSourceRoots(module);
  for (final VirtualFile sourceRoot : sourceRoots) {
    if (fileIndex.isInSourceContent(sourceRoot)) {
      continue; // skip content source roots, need only roots for generated files
    }
    if (VfsUtil.isAncestor(sourceRoot, file, false)) {
      return sourceRoot;
    }
  }
  return null;
}
 
示例7
public static Map<Module, List<VirtualFile>> buildModuleToFilesMap(final CompileContext context, final List<VirtualFile> files) {
  //assertion: all files are different
  final Map<Module, List<VirtualFile>> map = new THashMap<Module, List<VirtualFile>>();
  ApplicationManager.getApplication().runReadAction(new Runnable() {
    public void run() {
      for (VirtualFile file : files) {
        final Module module = context.getModuleByFile(file);

        if (module == null) {
          continue; // looks like file invalidated
        }

        List<VirtualFile> moduleFiles = map.get(module);
        if (moduleFiles == null) {
          moduleFiles = new ArrayList<VirtualFile>();
          map.put(module, moduleFiles);
        }
        moduleFiles.add(file);
      }
    }
  });
  return map;
}
 
示例8
@Override
public void run() {
    compilerManager.make(
        moduleScope,
        new CompileStatusNotification() {
            public void finished(boolean aborted, int errors, int warnings, CompileContext compileContext) {
            getResponse().set(!aborted && errors == 0);
            }
        }
    );
}
 
示例9
private void showMessage(Api.PerformRefactoringResponse response, CompileContext context, RefactorStatusCallback refactorStatusCallback) {
    refactorStatusCallback.onFinish(new RefactoringStatus(false, "Please fix all errors before refactoring."));
    for (String error : response.getErrorsList()) {
        GaugeError gaugeError = GaugeError.getInstance(error);
        if (gaugeError != null) {
            context.addMessage(CompilerMessageCategory.ERROR, gaugeError.getMessage(), Paths.get(gaugeError.getFileName()).toUri().toString(), gaugeError.getLineNumber(), -1);
        } else {
            context.addMessage(CompilerMessageCategory.ERROR, error, null, -1, -1);
        }
    }
}
 
示例10
@Override
public boolean execute(CompileContext context) {
  if (haxeCompiler == null) {
    haxeCompiler = new HaxeCompiler();
  }
  
  FileProcessingCompiler.ProcessingItem[] processingItems = haxeCompiler.getProcessingItems(context);
  haxeCompiler.process(context, processingItems);
  return true;
}
 
示例11
/**
 * Add errors to the compile context.
 *
 * @param context
 * @param errorRoot
 * @param errors
 */
public static void fillContext(CompileContext context, String errorRoot,
                               String[] errors)
{
    for (String error : errors) {
        addErrorToContext(error, context, errorRoot);
    }
}
 
示例12
private static void openCompilerMessagesWindow(final CompileContext context) {
    // Force the compile window open.  We should probably have a configuration button
    // on the compile gui page to force it open or not.
    if (!isHeadless()) {
        ApplicationManager.getApplication().invokeLater(new Runnable() {
            public void run() {
                // This was lifted from intellij-community/java/compiler/impl/src/com/intellij/compiler/progress/CompilerTask.java
                final ToolWindow tw = ToolWindowManager.getInstance(context.getProject()).getToolWindow(ToolWindowId.MESSAGES_WINDOW);
                if (tw != null) {
                    tw.activate(null, false);
                }
            }
        });
    }
}
 
示例13
public abstract void collectFiles(CompileContext context,
TranslatingCompiler compiler,
Iterator<VirtualFile> scopeSrcIterator,
boolean forceCompile,
boolean isRebuild,
Collection<VirtualFile> toCompile,
Collection<Trinity<File, String, Boolean>> toDelete);
 
示例14
public ArtifactsProcessingItemsBuilderContext(CompileContext compileContext) {
  myCompileContext = compileContext;
  myItemsBySource = new HashMap<VirtualFile, ArtifactCompilerCompileItem>();
  mySourceByOutput = new HashMap<String, VirtualFile>();
  myJarByPath = new HashMap<String, ArchivePackageInfo>();
  myPrintToLog = ArtifactsCompilerInstance.FULL_LOG.isDebugEnabled();
}
 
示例15
public static void addChangedArtifact(final CompileContext context, Artifact artifact) {
  Set<Artifact> artifacts = context.getUserData(CHANGED_ARTIFACTS);
  if (artifacts == null) {
    artifacts = new THashSet<Artifact>();
    context.putUserData(CHANGED_ARTIFACTS, artifacts);
  }
  artifacts.add(artifact);
}
 
示例16
public static void addWrittenPaths(final CompileContext context, Set<String> writtenPaths) {
  Set<String> paths = context.getUserData(WRITTEN_PATHS_KEY);
  if (paths == null) {
    paths = new THashSet<String>();
    context.putUserData(WRITTEN_PATHS_KEY, paths);
  }
  paths.addAll(writtenPaths);
}
 
示例17
@RequiredUIAccess
@Override
protected void doAction(DataContext dataContext, final Project project) {
  CompilerManager.getInstance(project).rebuild(new CompileStatusNotification() {
    @Override
    public void finished(boolean aborted, int errors, int warnings, final CompileContext compileContext) {
      if (aborted) return;

      String text = getTemplatePresentation().getText();
      LocalHistory.getInstance().putSystemLabel(project, errors == 0
                                     ? CompilerBundle.message("rebuild.lvcs.label.no.errors", text)
                                     : CompilerBundle.message("rebuild.lvcs.label.with.errors", text));
    }
  });
}
 
示例18
public ArchivesBuilder(@Nonnull Set<ArchivePackageInfo> archivesToBuild, @Nonnull FileFilter fileFilter, @Nonnull CompileContext context) {
  DependentArchivesEvaluator evaluator = new DependentArchivesEvaluator();
  for (ArchivePackageInfo archivePackageInfo : archivesToBuild) {
    evaluator.addArchiveWithDependencies(archivePackageInfo);
  }
  myArchivesToBuild = evaluator.getArchivePackageInfos();
  myFileFilter = fileFilter;
  myContext = context;
}
 
示例19
public static <T extends Throwable> void runInContext(CompileContext context, String title, ThrowableRunnable<T> action) throws T {
  if (title != null) {
    context.getProgressIndicator().pushState();
    context.getProgressIndicator().setText(title);
  }
  try {
    action.run();
  }
  finally {
    if (title != null) {
      context.getProgressIndicator().popState();
    }
  }
}
 
示例20
public GenericCompilerRunner(CompileContext context, boolean forceCompile, boolean onlyCheckStatus, final GenericCompiler[] compilers) {
  myContext = context;
  myForceCompile = forceCompile;
  myOnlyCheckStatus = onlyCheckStatus;
  myCompilers = compilers;
  myProject = myContext.getProject();
}
 
示例21
@Override
public void compile(CompileContext context, Chunk<Module> moduleChunk, VirtualFile[] files, OutputSink sink) {
  try {
    context.addMessage(CompilerMessageCategory.WARNING, "my warning", null, -1, -1);
    Thread.sleep(5000L);
  }
  catch (InterruptedException e) {
    e.printStackTrace();
  }

  if (myAddError) {
    context.addMessage(CompilerMessageCategory.ERROR, "my error", null, -1, -1);
  }
  myAddError = !myAddError;
}
 
示例22
private void executeMakeInUIThread(final VirtualFileEvent event) {
    if(project.isInitialized() && !project.isDisposed() && project.isOpen()) {
        final CompilerManager compilerManager = CompilerManager.getInstance(project);
        if(!compilerManager.isCompilationActive() &&
            !compilerManager.isExcludedFromCompilation(event.getFile()) // &&
        ) {
            // Check first if there are no errors in the code
            CodeSmellDetector codeSmellDetector = CodeSmellDetector.getInstance(project);
            boolean isOk = true;
            if(codeSmellDetector != null) {
                List<CodeSmellInfo> codeSmellInfoList = codeSmellDetector.findCodeSmells(Arrays.asList(event.getFile()));
                for(CodeSmellInfo codeSmellInfo: codeSmellInfoList) {
                    if(codeSmellInfo.getSeverity() == HighlightSeverity.ERROR) {
                        isOk = false;
                        break;
                    }
                }
            }
            if(isOk) {
                // Changed file found in module. Make it.
                final ToolWindow tw = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.MESSAGES_WINDOW);
                final boolean isShown = tw != null && tw.isVisible();
                compilerManager.compile(
                    new VirtualFile[]{event.getFile()},
                    new CompileStatusNotification() {
                        @Override
                        public void finished(boolean b, int i, int i1, CompileContext compileContext) {
                            if (tw != null && tw.isVisible()) {
                                // Close / Hide the Build Message Window after we did the build if it wasn't shown
                                if(!isShown) {
                                    tw.hide(null);
                                }
                            }
                        }
                    }
                );
            } else {
                MessageManager messageManager = ComponentProvider.getComponent(project, MessageManager.class);
                if(messageManager != null) {
                    messageManager.sendErrorNotification(
                        "server.update.file.change.with.error",
                        event.getFile()
                    );
                }
            }
        }
    }
}
 
示例23
private boolean compileForIpa(CompileContext context, final CreateIpaAction.IpaConfig ipaConfig) {
    try {
        ProgressIndicator progress = context.getProgressIndicator();
        context.getProgressIndicator().pushState();
        RoboVmPlugin.focusToolWindow(context.getProject());
        progress.setText("Creating IPA");

        RoboVmPlugin.logInfo(context.getProject(), "Creating package in " + ipaConfig.getDestinationDir().getAbsolutePath() + " ...");

        Config.Builder builder = new Config.Builder();
        builder.logger(RoboVmPlugin.getLogger(context.getProject()));
        File moduleBaseDir = new File(ModuleRootManager.getInstance(ipaConfig.getModule()).getContentRoots()[0].getPath());

        // load the robovm.xml file
        loadConfig(context.getProject(), builder, moduleBaseDir, false);
        builder.os(OS.ios);
        builder.archs(ipaConfig.getArchs());
        builder.installDir(ipaConfig.getDestinationDir());
        builder.iosSignIdentity(SigningIdentity.find(SigningIdentity.list(), ipaConfig.getSigningIdentity()));
        if (ipaConfig.getProvisioningProfile() != null) {
            builder.iosProvisioningProfile(ProvisioningProfile.find(ProvisioningProfile.list(), ipaConfig.getProvisioningProfile()));
        }
        configureClassAndSourcepaths(context, builder, ipaConfig.getModule());
        builder.home(RoboVmPlugin.getRoboVmHome());
        Config config = builder.build();

        progress.setFraction(0.5);

        AppCompiler compiler = new AppCompiler(config);
        RoboVmCompilerThread thread = new RoboVmCompilerThread(compiler, progress) {
            protected void doCompile() throws Exception {
                compiler.build();
                compiler.archive();
            }
        };
        thread.compile();

        if(progress.isCanceled()) {
            RoboVmPlugin.logInfo(context.getProject(), "Build canceled");
            return false;
        }

        progress.setFraction(1);
        RoboVmPlugin.logInfo(context.getProject(), "Package successfully created in " + ipaConfig.getDestinationDir().getAbsolutePath());
    } catch(Throwable t) {
        RoboVmPlugin.logErrorThrowable(context.getProject(), "Couldn't create IPA", t, false);
        return false;
    } finally {
        context.getProgressIndicator().popState();
    }
    return true;
}
 
示例24
public void onBuildStarted(@Nonnull Artifact artifact, @Nonnull CompileContext compileContext) {
}
 
示例25
public void onBuildFinished(@Nonnull Artifact artifact, @Nonnull CompileContext compileContext) {
}
 
示例26
public static void copyFile(@Nonnull final File fromFile,
                     @Nonnull final File toFile,
                     @Nonnull CompileContext context,
                     @Nullable Set<String> writtenPaths,
                     @Nullable FileFilter fileFilter) throws IOException {
  if (fileFilter != null && !fileFilter.accept(fromFile)) {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Skipping " + fromFile.getAbsolutePath() + ": it wasn't accepted by filter " + fileFilter);
    }
    return;
  }
  checkPathDoNotNavigatesUpFromFile(fromFile);
  checkPathDoNotNavigatesUpFromFile(toFile);
  if (fromFile.isDirectory()) {
    final File[] fromFiles = fromFile.listFiles();
    toFile.mkdirs();
    for (File file : fromFiles) {
      copyFile(file, new File(toFile, file.getName()), context, writtenPaths, fileFilter);
    }
    return;
  }
  if (toFile.isDirectory()) {
    context.addMessage(CompilerMessageCategory.ERROR,
                       CompilerBundle.message("message.text.destination.is.directory", createCopyErrorMessage(fromFile, toFile)), null, -1, -1);
    return;
  }
  if (FileUtil.filesEqual(fromFile, toFile) || writtenPaths != null && !writtenPaths.add(toFile.getPath())) {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Skipping " + fromFile.getAbsolutePath() + ": " + toFile.getAbsolutePath() + " is already written");
    }
    return;
  }
  if (!FileUtil.isFilePathAcceptable(toFile, fileFilter)) {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Skipping " + fromFile.getAbsolutePath() + ": " + toFile.getAbsolutePath() + " wasn't accepted by filter " + fileFilter);
    }
    return;
  }
  context.getProgressIndicator().setText("Copying files");
  context.getProgressIndicator().setText2(fromFile.getPath());
  try {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Copy file '" + fromFile + "' to '"+toFile+"'");
    }
    if (toFile.exists() && !SystemInfo.isFileSystemCaseSensitive) {
      File canonicalFile = toFile.getCanonicalFile();
      if (!canonicalFile.getAbsolutePath().equals(toFile.getAbsolutePath())) {
        FileUtil.delete(toFile);
      }
    }
    FileUtil.copy(fromFile, toFile);
  }
  catch (IOException e) {
    context.addMessage(CompilerMessageCategory.ERROR, createCopyErrorMessage(fromFile, toFile) + ": "+ ExceptionUtil.getThrowableText(e), null, -1, -1);
  }
}
 
示例27
public abstract void update(CompileContext context,
@Nullable String outputRoot,
Collection<TranslatingCompiler.OutputItem> successfullyCompiled,
VirtualFile[] filesToRecompile) throws IOException;
 
示例28
@Nonnull
public abstract GenericCompilerInstance<?, ? extends CompileItem<Key, SourceState, OutputState>, Key, SourceState, OutputState> createInstance(@Nonnull CompileContext context);
 
示例29
protected GenericCompilerInstance(CompileContext context) {
  myContext = context;
}
 
示例30
public CompileContext getCompileContext() {
  return myCompileContext;
}