예제 #1
0
 public static void addMappingIfSubRoot(
     @NotNull Project project, @NotNull String newRepositoryPath, @NotNull String vcsName) {
   if (project.getBasePath() != null
       && FileUtil.isAncestor(project.getBasePath(), newRepositoryPath, true)) {
     ProjectLevelVcsManager manager = ProjectLevelVcsManager.getInstance(project);
     manager.setDirectoryMappings(
         VcsUtil.addMapping(manager.getDirectoryMappings(), newRepositoryPath, vcsName));
   }
 }
  @Override
  public void setupRootModel(final ModifiableRootModel modifiableRootModel)
      throws ConfigurationException {
    String contentEntryPath = getContentEntryPath();
    if (StringUtil.isEmpty(contentEntryPath)) {
      return;
    }
    File contentRootDir = new File(contentEntryPath);
    FileUtilRt.createDirectory(contentRootDir);
    LocalFileSystem fileSystem = LocalFileSystem.getInstance();
    VirtualFile modelContentRootDir = fileSystem.refreshAndFindFileByIoFile(contentRootDir);
    if (modelContentRootDir == null) {
      return;
    }

    modifiableRootModel.addContentEntry(modelContentRootDir);
    modifiableRootModel.inheritSdk();

    final Project project = modifiableRootModel.getProject();

    setupGradleBuildFile(modelContentRootDir);
    setupGradleSettingsFile(modelContentRootDir, modifiableRootModel);

    if (myWizardContext.isCreatingNewProject()) {
      String externalProjectPath = FileUtil.toCanonicalPath(project.getBasePath());
      getExternalProjectSettings().setExternalProjectPath(externalProjectPath);
      AbstractExternalSystemSettings settings =
          ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID);
      //noinspection unchecked
      settings.linkProject(getExternalProjectSettings());
    } else {
      FileDocumentManager.getInstance().saveAllDocuments();
      ExternalSystemUtil.refreshProjects(project, GradleConstants.SYSTEM_ID, false);
    }
  }
 public void testEmbeddedRebar() throws Exception {
   final Project createdProject = doTest(null);
   if (SystemInfo.isWindows) return;
   assertEquals(
       createdProject.getBasePath() + "/rebar",
       RebarSettings.getInstance(createdProject).getRebarPath());
 }
예제 #4
0
        @Override
        public void caretPositionChanged(CaretEvent event) {

          if (project.isDisposed()) {
            return;
          }

          VirtualFile file =
              FileDocumentManager.getInstance().getFile(event.getEditor().getDocument());

          // Make sure file exists
          if (file == null) {
            return;
          }

          // Make sure file is in the project
          if (!ProjectFileIndex.SERVICE.getInstance(project).isInSource(file)) {
            return;
          }

          int offset = event.getEditor().logicalPositionToOffset(event.getNewPosition());

          // Get path relative to project root (e.g. src/Sample.java)
          Path basePath = Paths.get(project.getBasePath());
          Path absoluteFilePath = Paths.get(file.getPath());
          String relativeFilePath = basePath.relativize(absoluteFilePath).toString();

          CursorMovement cursorMovement = new CursorMovement(-1, relativeFilePath, offset);

          for (EditorEvent editorEvent : events) {
            editorEvent.sendCursorMovement(cursorMovement);
          }
        }
 @Override
 public WorkspaceConfig get() {
   SimpleWorkspaceConfig _xblockexpression = null;
   {
     ProjectManager _instance = ProjectManager.getInstance();
     Project[] _openProjects = _instance.getOpenProjects();
     final Project project =
         IterableExtensions.<Project>head(
             ((Iterable<Project>) Conversions.doWrapArray(_openProjects)));
     String _basePath = project.getBasePath();
     final SimpleWorkspaceConfig result = new SimpleWorkspaceConfig(_basePath);
     ModuleManager _instance_1 = ModuleManager.getInstance(project);
     Module[] _modules = _instance_1.getModules();
     final Procedure1<Module> _function =
         new Procedure1<Module>() {
           @Override
           public void apply(final Module m) {
             IdeaModuleConfig _ideaModuleConfig =
                 new IdeaModuleConfig(m, IdeaWorkspaceConfigProvider.this.outputConfigurations);
             result.addProjectConfig(_ideaModuleConfig);
           }
         };
     IterableExtensions.<Module>forEach(
         ((Iterable<Module>) Conversions.doWrapArray(_modules)), _function);
     _xblockexpression = result;
   }
   return _xblockexpression;
 }
  private void updateCourse() {
    if (myCourse == null) {
      return;
    }
    final File resourceDirectory = new File(myCourse.getCourseDirectory());
    if (!resourceDirectory.exists()) {
      return;
    }
    final File[] files = resourceDirectory.listFiles();
    if (files == null) return;
    for (File file : files) {
      if (file.getName().equals(StudyNames.TEST_HELPER)) {
        copyFile(file, new File(myProject.getBasePath(), StudyNames.TEST_HELPER));
      }
      if (file.getName().startsWith(StudyNames.LESSON)) {
        final File[] tasks = file.listFiles();
        if (tasks == null) continue;
        for (File task : tasks) {
          final File taskDescr = new File(task, StudyNames.TASK_HTML);
          final File taskTests = new File(task, StudyNames.TASK_TESTS);
          copyFile(
              taskDescr,
              new File(
                  new File(new File(myProject.getBasePath(), file.getName()), task.getName()),
                  StudyNames.TASK_HTML));
          copyFile(
              taskTests,
              new File(
                  new File(new File(myProject.getBasePath(), file.getName()), task.getName()),
                  StudyNames.TASK_TESTS));
        }
      }
    }

    final Notification notification =
        new Notification(
            "Update.course",
            "Course update",
            "Current course is synchronized",
            NotificationType.INFORMATION);
    notification.notify(myProject);
  }
예제 #7
0
        @Override
        public void beforeDocumentChange(DocumentEvent event) {

          if (project.isDisposed()) {
            return;
          }

          if (!isListening) {
            System.out.println("Ignoring change.");
            return;
          }

          VirtualFile file = FileDocumentManager.getInstance().getFile(event.getDocument());

          // Make sure file exists
          if (file == null) {
            return;
          }

          // Make sure file is in the project
          if (!ProjectFileIndex.SERVICE.getInstance(project).isInSource(file)) {
            return;
          }

          String dummyIdentifier = "IntellijIdeaRulezzz";

          if (!event.getNewFragment().toString().contains(dummyIdentifier)) {
            if (!event.isWholeTextReplaced()) {

              // Get path relative to project root (e.g. src/Sample.java)
              Path basePath = Paths.get(project.getBasePath());
              Path absoluteFilePath = Paths.get(file.getPath());
              String relativeFilePath = basePath.relativize(absoluteFilePath).toString();

              String documentText = event.getDocument().getText();
              String oldFragment = event.getOldFragment().toString();
              String newFragment = event.getNewFragment().toString();
              int offset = event.getOffset();

              IOPatcher patcher = new IOPatcher();
              LinkedList<Patch> patches =
                  patcher.makePatchAsList(documentText, oldFragment, newFragment, offset);

              UserEdit edit = new UserEdit(0, relativeFilePath, patches);

              for (EditorEvent editorEvent : events) {
                editorEvent.sendChange(edit);
              }
            }
          }
        }
  @Before
  public void setUp() throws Throwable {
    IdeaTestApplication.getInstance();

    myTestName = createTestName();
    myProjectFixture =
        IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(myTestName).getFixture();

    edt(
        new ThrowableRunnable<Exception>() {
          @Override
          public void run() throws Exception {
            myProjectFixture.setUp();
          }
        });

    myProject = myProjectFixture.getProject();

    myProjectRoot = myProject.getBasePath();
    myProjectDir = myProject.getBaseDir();
    myTestRoot = myProjectRoot;

    myGit = ServiceManager.getService(myProject, Git.class);
    mySettings = GitVcsSettings.getInstance(myProject);
    mySettings.getAppSettings().setPathToGit(GitExecutor.PathHolder.GIT_EXECUTABLE);

    // dynamic overriding is used instead of making it in plugin.xml,
    // because MockVcsHelper is not ready to be a full featured implementation for all tests.
    myVcsHelper =
        GitTestUtil.overrideService(myProject, AbstractVcsHelper.class, MockVcsHelper.class);
    myChangeListManager = ChangeListManagerImpl.getInstanceImpl(myProject);
    myNotificator = (TestVcsNotifier) ServiceManager.getService(myProject, VcsNotifier.class);
    myVcs = GitVcs.getInstance(myProject);
    myRepositoryManager = GitUtil.getRepositoryManager(myProject);

    virtualCommits = new GitTestVirtualCommitsHolder();
    myAsyncTasks = new ArrayList<>();

    cd(myProjectRoot);
    myRepository = GitTestUtil.createRepository(myProject, myProjectRoot);

    ProjectLevelVcsManagerImpl vcsManager =
        (ProjectLevelVcsManagerImpl) ProjectLevelVcsManager.getInstance(myProject);
    AbstractVcs vcs = vcsManager.findVcsByName("Git");
    Assert.assertEquals(1, vcsManager.getRootsUnderVcs(vcs).length);

    GitTestUtil.assumeSupportedGitVersion(myVcs);
    LOG.info(getStartTestMarker());
  }
 private static String replacePlaceHolders(String template, Project project) {
   String processedTemplate = template;
   String projectName = "";
   String projectBaseDir = "";
   String projectBaseDirName = "";
   if (null != project) {
     projectName = project.getName();
     projectBaseDir = project.getBasePath();
     projectBaseDirName = project.getBaseDir().getName();
   }
   processedTemplate = processedTemplate.replace(PROJECT_NAME.getVariableName(), projectName);
   processedTemplate =
       processedTemplate.replace(PROJECT_BASE_DIR_NAME.getVariableName(), projectBaseDirName);
   processedTemplate =
       processedTemplate.replace(PROJECT_BASE_DIR.getVariableName(), projectBaseDir);
   return processedTemplate;
 }
  // null means we were unable to get roots, so do not check access
  @Nullable
  @TestOnly
  private static Set<String> allowedRoots() {
    if (insideGettingRoots) return null;

    Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
    if (openProjects.length == 0) return null;

    final Set<String> allowed = new THashSet<String>();
    allowed.add(FileUtil.toSystemIndependentName(PathManager.getHomePath()));

    try {
      URL outUrl = Application.class.getResource("/");
      String output = new File(outUrl.toURI()).getParentFile().getParentFile().getPath();
      allowed.add(FileUtil.toSystemIndependentName(output));
    } catch (URISyntaxException ignored) {
    }

    allowed.add(FileUtil.toSystemIndependentName(SystemProperties.getJavaHome()));
    allowed.add(
        FileUtil.toSystemIndependentName(new File(FileUtil.getTempDirectory()).getParent()));
    allowed.add(FileUtil.toSystemIndependentName(System.getProperty("java.io.tmpdir")));
    allowed.add(FileUtil.toSystemIndependentName(SystemProperties.getUserHome()));

    for (Project project : openProjects) {
      if (!project.isInitialized()) {
        return null; // all is allowed
      }
      for (VirtualFile root : ProjectRootManager.getInstance(project).getContentRoots()) {
        allowed.add(root.getPath());
      }
      for (VirtualFile root : getAllRoots(project)) {
        allowed.add(StringUtil.trimEnd(root.getPath(), JarFileSystem.JAR_SEPARATOR));
      }
      String location = project.getBasePath();
      assert location != null : project;
      allowed.add(FileUtil.toSystemIndependentName(location));
    }

    allowed.addAll(ourAdditionalRoots);

    return allowed;
  }
 public void checkWorkingDirectoryExist(
     CommonProgramRunConfigurationParameters configuration, Project project, Module module)
     throws RuntimeConfigurationWarning {
   final String workingDir = getWorkingDir(configuration, project, module);
   if (workingDir == null) {
     throw new RuntimeConfigurationWarning(
         "Working directory is null for "
             + "project '"
             + project.getName()
             + "' ("
             + project.getBasePath()
             + ")"
             + ", module '"
             + module.getName()
             + "' ("
             + module.getModuleFilePath()
             + ")");
   }
   if (!new File(workingDir).exists()) {
     throw new RuntimeConfigurationWarning("Working directory '" + workingDir + "' doesn't exist");
   }
 }
  private static boolean hasJSLibraryMappingToOldDartSdkGlobalLib(final @NotNull Project project) {
    /*
        Mapping to old 'Dart SDK' global lib is removed when ScriptingLibraryManager is loaded if 'Dart SDK' lib does not exist. That's why we use hacky way.
        One more bonus is that it works even if JavaScript plugin is disabled and in IntelliJ IDEA Community Edition

        <?xml version="1.0" encoding="UTF-8"?>
        <project version="4">
          <component name="JavaScriptLibraryMappings">
            <file url="PROJECT" libraries="{Dart SDK}" />
            <excludedPredefinedLibrary name="HTML5 / EcmaScript 5" />
          </component>
        </project>
    */
    final File jsLibraryMappingsFile =
        new File(project.getBasePath() + "/.idea/jsLibraryMappings.xml");
    if (jsLibraryMappingsFile.isFile()) {
      try {
        final Document document = JDOMUtil.loadDocument(jsLibraryMappingsFile);
        final Element rootElement = document.getRootElement();
        for (final Element componentElement : rootElement.getChildren("component")) {
          if ("JavaScriptLibraryMappings".equals(componentElement.getAttributeValue("name"))) {
            for (final Element fileElement : componentElement.getChildren("file")) {
              if ("PROJECT".equals(fileElement.getAttributeValue("url"))
                  && "{Dart SDK}".equals(fileElement.getAttributeValue("libraries"))) {
                return true;
              }
            }
          }
        }
      } catch (Throwable ignore) {
        /* unlucky */
      }
    }

    return false;
  }
 public ErlangConsoleRunConfigurationForm(@NotNull Project project, @Nullable Module module) {
   myInitialModule = module;
   myModuleComboBox.setEnabled(true);
   addFileChooser("Choose Working Directory", myWorkingDirPathField, project);
   myWorkingDirPathField.setText(project.getBasePath());
 }
예제 #14
0
 public void actionPerformed(
     AnActionEvent actionEvent, Project project, FloobitsPlugin plugin, ContextImpl context) {
   final String project_path = project.getBasePath();
   FloobitsPlugin.getInstance(project).context.shareProject(false, project_path);
 }
예제 #15
0
 private PsiFile getMetaFile(Project project) {
   VirtualFile metaFile =
       LocalFileSystem.getInstance()
           .findFileByPath(project.getBasePath() + File.separatorChar + ".phpstorm.meta.php");
   return metaFile != null ? PsiManager.getInstance(project).findFile(metaFile) : null;
 }
  private void executeTest(String className, String testMethodName, String dunitPath) {
    String testPath = className + "." + testMethodName;
    final String workingDirectory = project.getBasePath();
    //            final String testFile = configuration.getDFile().getCanonicalPath();

    final String dubPath = ToolKey.DUB_KEY.getPath(project);
    if (dubPath == null || dubPath.isEmpty()) {
      Notifications.Bus.notify(
          new Notification(
              "Dunit Test Runner",
              "Dub path must be specified",
              "Dub executable path is empty"
                  + "<br/><a href='configureDLanguageTools'>Configure</a>",
              NotificationType.WARNING,
              new DToolsNotificationListener(project)),
          project);
      return;
    }

    GeneralCommandLine commandLine = new GeneralCommandLine();
    commandLine.setWorkDirectory(workingDirectory);
    commandLine.setExePath(dubPath);
    ParametersList parametersList = commandLine.getParametersList();
    parametersList.addParametersString("--");
    parametersList.addParametersString("-v");
    parametersList.addParametersString("--filter");
    parametersList.addParametersString(testPath + "$"); // regex to locate exact test

    final StringBuilder builder = new StringBuilder();
    try {
      OSProcessHandler process = new OSProcessHandler(commandLine.createProcess());
      process.addProcessListener(
          new ProcessAdapter() {
            @Override
            public void onTextAvailable(ProcessEvent event, Key outputType) {
              builder.append(event.getText());
            }
          });

      process.startNotify();
      process.waitFor();

    } catch (ExecutionException e) {
      e.printStackTrace();
    }

    String result = builder.toString();
    // call either finished(success) or failed
    String successPatternString = ".*OK:.*";
    Pattern successPattern = Pattern.compile(successPatternString);
    Matcher successMatcher = successPattern.matcher(result);

    if (successMatcher.find()) {
      testFinished(className, testMethodName, 0);
      testStdOut(className, testMethodName, result);
    } else if (result.contains("FAILURE:")) {
      testFailed(className, testMethodName, 0, "Failed", result);
    } else if (result.contains("SKIP:")) {
      testIgnored(className, testMethodName);
      testStdOut(className, testMethodName, result);
    } else {
      testFailed(className, testMethodName, 0, "Failed for unknown reasons", result);
    }
  }
 private boolean isUnderOrAboveProjectDir(@NotNull String mapping) {
   String projectDir = ObjectUtils.assertNotNull(myProject.getBasePath());
   return mapping.equals(VcsDirectoryMapping.PROJECT_CONSTANT)
       || FileUtil.isAncestor(projectDir, mapping, false)
       || FileUtil.isAncestor(mapping, projectDir, false);
 }
 public static <K, V> ID<K, V> generateIndexId(final String indexName, final Project project) {
   return ID.create(
       String.format(
           "compilerOutputIndex.%s.%d", indexName, Math.abs(project.getBasePath().hashCode())));
 }