{"record":{"id":"497fe62d32dfe7e1","repo":"JetBrains/intellij-community","slug":"cannot-create-package-0-in-source-folder-1","errorCode":null,"errorMessage":"Cannot create package '{0}' in source folder {1}","messagePattern":"Cannot create package '(.+?)' in source folder (.+?)","errorType":"exception","errorClass":"IncorrectOperationException","httpStatus":null,"severity":"error","filePath":"java/java-impl/src/com/intellij/util/CommonJavaRefactoringUtil.java","lineNumber":205,"sourceCode":"    if (initializerType == null) {\n      return initializer;\n    }\n    LOG.assertTrue(initializerType instanceof PsiArrayType);\n    PsiElementFactory factory = JavaPsiFacade.getElementFactory(initializer.getProject());\n    PsiNewExpression result =\n      (PsiNewExpression)factory.createExpressionFromText(\"new \" + initializerType.getPresentableText() + \"{}\", null);\n    result = (PsiNewExpression)CodeStyleManager.getInstance(initializer.getProject()).reformat(result);\n    PsiArrayInitializerExpression arrayInitializer = result.getArrayInitializer();\n    LOG.assertTrue(arrayInitializer != null);\n    arrayInitializer.replace(initializer);\n    return result;\n  }\n\n  public static String qNameToCreateInSourceRoot(PackageWrapper aPackage, VirtualFile sourceRoot) {\n    String targetQName = aPackage.getQualifiedName();\n    String sourceRootPackage = PackageIndex.getInstance(aPackage.getManager().getProject()).getPackageNameByDirectory(sourceRoot);\n    if (!canCreateInSourceRoot(sourceRootPackage, targetQName)) {\n      throw new IncorrectOperationException(\n        \"Cannot create package '\" + targetQName + \"' in source folder \" + sourceRoot.getPresentableUrl());\n    }\n    String result = targetQName.substring(sourceRootPackage.length());\n    if (StringUtil.startsWithChar(result, '.')) result = result.substring(1);  // remove initial '.'\n    return result;\n  }\n\n  public static boolean canCreateInSourceRoot(String sourceRootPackage, String targetQName) {\n    if (sourceRootPackage == null || !targetQName.startsWith(sourceRootPackage)) return false;\n    if (sourceRootPackage.isEmpty() || targetQName.length() == sourceRootPackage.length()) return true;\n    return targetQName.charAt(sourceRootPackage.length()) == '.';\n  }\n\n  public static @Nullable PsiDirectory findPackageDirectoryInSourceRoot(PackageWrapper aPackage, VirtualFile sourceRoot) {\n    final PsiDirectory[] directories = aPackage.getDirectories();\n    for (PsiDirectory directory : directories) {\n      if (VfsUtilCore.isAncestor(sourceRoot, directory.getVirtualFile(), false)) {\n        return directory;","sourceCodeStart":187,"sourceCodeEnd":223,"githubUrl":"https://github.com/JetBrains/intellij-community/blob/be881553f2a76ac8b4ea53950d93f0de78295c19/java/java-impl/src/com/intellij/util/CommonJavaRefactoringUtil.java#L187-L223","documentation":"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.","triggerScenarios":"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'.","commonSituations":"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.","solutions":["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.","Pick a source root whose existing package structure is consistent with the target package.","Fix the module configuration so the marked source root corresponds to the actual package root (no extra package-info at root level).","If calling the API directly, pre-check with CommonJavaRefactoringUtil.canCreateInSourceRoot(sourceRootPackage, targetQName) and skip or choose another root when it returns false."],"exampleFix":"// before:\nString rel = CommonJavaRefactoringUtil.qNameToCreateInSourceRoot(pkg, sourceRoot);\n\n// after:\nString rootPkg = PackageIndex.getInstance(project).getPackageNameByDirectory(sourceRoot);\nif (!CommonJavaRefactoringUtil.canCreateInSourceRoot(rootPkg, pkg.getQualifiedName())) {\n  sourceRoot = chooseCleanSourceRoot(pkg); // or report to user\n}\nString rel = CommonJavaRefactoringUtil.qNameToCreateInSourceRoot(pkg, sourceRoot);","handlingStrategy":"validation","validationCode":"String rootPkg = PackageIndex.getInstance(project).getPackageNameByDirectory(sourceRoot);\nif (!CommonJavaRefactoringUtil.canCreateInSourceRoot(rootPkg, targetQName)) {\n  // choose a different source root or report; do not call qNameToCreateInSourceRoot\n}","typeGuard":null,"tryCatchPattern":"try { CommonJavaRefactoringUtil.qNameToCreateInSourceRoot(pkg, sourceRoot); } catch (IncorrectOperationException e) { /* package not creatable under this root: pick another root */ }","preventionTips":["Always pre-check with canCreateInSourceRoot; it exists exactly for this guard.","Keep source roots free of root-level package-info/stray package declarations.","Validate that directory layout and package statements agree before batch moves."],"tags":["java","intellij","refactoring","package","source-root","psi"],"backgroundTag":null,"analyzedSha":"be881553f2a76ac8b4ea53950d93f0de78295c19","analyzedAt":"2026-08-14T14:13:06.425Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}