JetBrains/intellij-community · error · IncorrectOperationException

Cannot create package '{0}' in source folder {1}

Error message

Cannot create package '{0}' in source folder {1}

What it means

CommonJavaRefactoringUtil.qNameToCreateInSourceRoot throws IncorrectOperationException when the target package's qualified name is not reachable beneath the package that the given source root directory already declares. canCreateInSourceRoot requires targetQName to start with sourceRootPackage (with a '.' boundary); otherwise the refactoring cannot compute a relative path and aborts with this message, which names the target package and the source folder URL.

Source

Thrown at java/java-impl/src/com/intellij/util/CommonJavaRefactoringUtil.java:205

    if (initializerType == null) {
      return initializer;
    }
    LOG.assertTrue(initializerType instanceof PsiArrayType);
    PsiElementFactory factory = JavaPsiFacade.getElementFactory(initializer.getProject());
    PsiNewExpression result =
      (PsiNewExpression)factory.createExpressionFromText("new " + initializerType.getPresentableText() + "{}", null);
    result = (PsiNewExpression)CodeStyleManager.getInstance(initializer.getProject()).reformat(result);
    PsiArrayInitializerExpression arrayInitializer = result.getArrayInitializer();
    LOG.assertTrue(arrayInitializer != null);
    arrayInitializer.replace(initializer);
    return result;
  }

  public static String qNameToCreateInSourceRoot(PackageWrapper aPackage, VirtualFile sourceRoot) {
    String targetQName = aPackage.getQualifiedName();
    String sourceRootPackage = PackageIndex.getInstance(aPackage.getManager().getProject()).getPackageNameByDirectory(sourceRoot);
    if (!canCreateInSourceRoot(sourceRootPackage, targetQName)) {
      throw new IncorrectOperationException(
        "Cannot create package '" + targetQName + "' in source folder " + sourceRoot.getPresentableUrl());
    }
    String result = targetQName.substring(sourceRootPackage.length());
    if (StringUtil.startsWithChar(result, '.')) result = result.substring(1);  // remove initial '.'
    return result;
  }

  public static boolean canCreateInSourceRoot(String sourceRootPackage, String targetQName) {
    if (sourceRootPackage == null || !targetQName.startsWith(sourceRootPackage)) return false;
    if (sourceRootPackage.isEmpty() || targetQName.length() == sourceRootPackage.length()) return true;
    return targetQName.charAt(sourceRootPackage.length()) == '.';
  }

  public static @Nullable PsiDirectory findPackageDirectoryInSourceRoot(PackageWrapper aPackage, VirtualFile sourceRoot) {
    final PsiDirectory[] directories = aPackage.getDirectories();
    for (PsiDirectory directory : directories) {
      if (VfsUtilCore.isAncestor(sourceRoot, directory.getVirtualFile(), false)) {
        return directory;

View on GitHub (pinned to be881553f2)

Solutions

  1. Check the package declaration of files directly in the chosen source root — a stray package-info.java or class with a package statement forces sourceRootPackage to a non-prefix value; move or fix it.
  2. Pick a source root whose existing package structure is consistent with the target package.
  3. Fix the module configuration so the marked source root corresponds to the actual package root (no extra package-info at root level).
  4. If calling the API directly, pre-check with CommonJavaRefactoringUtil.canCreateInSourceRoot(sourceRootPackage, targetQName) and skip or choose another root when it returns false.

Example fix

// before:
String rel = CommonJavaRefactoringUtil.qNameToCreateInSourceRoot(pkg, sourceRoot);

// after:
String rootPkg = PackageIndex.getInstance(project).getPackageNameByDirectory(sourceRoot);
if (!CommonJavaRefactoringUtil.canCreateInSourceRoot(rootPkg, pkg.getQualifiedName())) {
  sourceRoot = chooseCleanSourceRoot(pkg); // or report to user
}
String rel = CommonJavaRefactoringUtil.qNameToCreateInSourceRoot(pkg, sourceRoot);
Defensive patterns

Strategy: validation

Validate before calling

String rootPkg = PackageIndex.getInstance(project).getPackageNameByDirectory(sourceRoot);
if (!CommonJavaRefactoringUtil.canCreateInSourceRoot(rootPkg, targetQName)) {
  // choose a different source root or report; do not call qNameToCreateInSourceRoot
}

Try / catch

try { CommonJavaRefactoringUtil.qNameToCreateInSourceRoot(pkg, sourceRoot); } catch (IncorrectOperationException e) { /* package not creatable under this root: pick another root */ }

Prevention

When it happens

Trigger: Calling qNameToCreateInSourceRoot(PackageWrapper, VirtualFile) during move/rename of a class or package where the destination source root already has a package-info/package prefix that is not a prefix of the target package — e.g. moving 'com.foo.Bar' into a source root whose root directory declares package 'org.other'.

Common situations: Source roots misconfigured so the root directory contains classes with a package statement that mismatches the directory layout; moving packages into a source root that already has unrelated top-level packages plus a package-info; multi-root projects (generated/test/root per-module roots) where the wrong root is selected; directory named 'com/foo' but containing files with a different package declaration.

Related errors


AI-assisted analysis of JetBrains/intellij-community@be881553f2 (2026-08-14). Data as JSON: /api/errors/497fe62d32dfe7e1. Report an issue: GitHub.