Computes the relative location of a file with respect to a root directory.
@param rootDirectory a directory
@param subFile a file contained (directly or indirectly) in the directory
@return a non-null string
182887
public static String computeFileRelativeLocation( File rootDirectory, File subFile ) {

		String rootPath = rootDirectory.getAbsolutePath();
		String subPath = subFile.getAbsolutePath();
		if(  ! subPath.startsWith( rootPath ))
			throw new IllegalArgumentException( "The sub-file must be contained in the directory." );

		if(  rootDirectory.equals( subFile ))
			throw new IllegalArgumentException( "The sub-file must be different than the directory." );

		return subPath.substring( rootPath.length() + 1 ).replace( '\\', '/' );
	}
1324246
private void addSubDirectory(Path root, Path filePath) throws IOException {
        String listener = getListenerRootPath(root);

        List<String> listeners = mSubDirectories.get(listener);

        if (listeners != null) {
            if (mSubDirectories.get(listener).contains(filePath.toAbsolutePath())) {
                return;
            } else {
                mSubDirectories.get(listener).add(filePath.toString());
            }

            try {
                watchDir(filePath.toFile());
            } catch (IOException e) {
                throw new IOException("Could not watch the subdirectories.", e);
            }
        }
    }
1164373
private String getStoredBundlePath(String rootDir, String bundleName) {
		if (bundleName.indexOf('/') != -1) {
			bundleName = bundleName.replace('/', File.separatorChar);
		}

		if (!bundleName.startsWith(File.separator)) {
			rootDir += File.separator;
		}

		return rootDir + PathNormalizer.escapeToPhysicalPath(bundleName);
	}
1020486
def _get_subdirectory(cls, location):
        """"""
        # find the repo root
        git_dir = cls.run_command(['rev-parse', '--git-dir'],
                                  show_stdout=False, cwd=location).strip()
        if not os.path.isabs(git_dir):
            git_dir = os.path.join(location, git_dir)
        root_dir = os.path.join(git_dir, '..')
        # find setup.py
        orig_location = location
        while not os.path.exists(os.path.join(location, 'setup.py')):
            last_location = location
            location = os.path.dirname(location)
            if location == last_location:
                # We've traversed up to the root of the filesystem without
                # finding setup.py
                logger.warning(
                    "Could not find setup.py for directory %s (tried all "
                    "parent directories)",
                    orig_location,
                )
                return None
        # relative path of setup.py to repo root
        if samefile(root_dir, location):
            return None
        return os.path.relpath(location, root_dir)
1037606
@OverrideOnDemand
  protected boolean recurseIntoDirectory (@Nonnull final File aDirectory)
  {
    return m_aRecursionFilter == null || m_aRecursionFilter.test (aDirectory);
  }
475750
public File getDir(String subDir) {
		File dir = new File(getDir(), subDir);
		dir.mkdirs();
		return dir;
	}
1333453
def get_subfolder(txt):
    
    root_folder = os.sep + 'aikif' + os.sep
    ndx = txt.find(root_folder, 1)
    return txt[ndx:].replace('__init__.py', '')
406957
static public void scanRoot(File root,
                                Set<String> suffixes,
                                List<String> excludes,
                                List<String> includes,
                                Map<String,Source> foundFiles,
                                Map<String,Module> foundModules,
                                final Module currentModule,
                                boolean permitSourcesWithoutPackage,
                                boolean inGensrc,
                                boolean inLinksrc)
                                        throws IOException, ProblemException {

        if (root == null)
            return;

        FileSystem fs = root.toPath().getFileSystem();

        if (includes.isEmpty()) {
            includes = Collections.singletonList("**");
        }

        List<PathMatcher> includeMatchers = createPathMatchers(fs, includes);
        List<PathMatcher> excludeMatchers = createPathMatchers(fs, excludes);

        Files.walkFileTree(root.toPath(), new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

                Path relToRoot = root.toPath().relativize(file);

                if (includeMatchers.stream().anyMatch(im -> im.matches(relToRoot))
                        && excludeMatchers.stream().noneMatch(em -> em.matches(relToRoot))
                        && suffixes.contains(Util.fileSuffix(file))) {

                    // TODO: Test this.
                    Source existing = foundFiles.get(file);
                    if (existing != null) {
                        throw new IOException("You have already added the file "+file+" from "+existing.file().getPath());
                    }
                    existing = currentModule.lookupSource(file.toString());
                    if (existing != null) {

                            // Oups, the source is already added, could be ok, could be not, lets check.
                            if (inLinksrc) {
                                // So we are collecting sources for linking only.
                                if (existing.isLinkedOnly()) {
                                    // Ouch, this one is also for linking only. Bad.
                                    throw new IOException("You have already added the link only file " + file + " from " + existing.file().getPath());
                                }
                                // Ok, the existing source is to be compiled. Thus this link only is redundant
                                // since all compiled are also linked to. Continue to the next source.
                                // But we need to add the source, so that it will be visible to linking,
                                // if not the multi core compile will fail because a JavaCompiler cannot
                                // find the necessary dependencies for its part of the source.
                                foundFiles.put(file.toString(), existing);
                            } else {
                                // We are looking for sources to compile, if we find an existing to be compiled
                                // source with the same name, it is an internal error, since we must
                                // find the sources to be compiled before we find the sources to be linked to.
                                throw new IOException("Internal error: Double add of file " + file + " from " + existing.file().getPath());
                            }

                    } else {

                        //////////////////////////////////////////////////////////////
                        // Add source
                        Source s = new Source(currentModule, file.toString(), file.toFile());
                        if (inGensrc) {
                            s.markAsGenerated();
                        }
                        if (inLinksrc) {
                            s.markAsLinkedOnly();
                        }
                        String pkg = packageOfJavaFile(root.toPath(), file);
                        pkg = currentModule.name() + ":" + pkg;
                        foundFiles.put(file.toString(), s);
                        currentModule.addSource(pkg, s);
                        //////////////////////////////////////////////////////////////
                    }
                }

                return FileVisitResult.CONTINUE;
            }
        });
    }
1083499
function subModulePath(subModule, node_modules) {
  var index = subModule.indexOf("/");
  var length = subModule.length;
  if (index <= 0 || index + 1 == length) {
    return null;
  }
  var module = subModule.substring(0, index);
  var relative = subModule.substring(index + 1, length);

  var moduleDirectory = path.join(node_modules, module);
  var filePath = path.join(moduleDirectory, relative);
  return realRequirPath(filePath);
}
78311
private boolean subModuleExists(File dir) {
        if (isSlotDirectory(dir)) {
            return true;
        } else {
            File[] children = dir.listFiles(File::isDirectory);
            for (File child : children) {
                if (subModuleExists(child)) {
                    return true;
                }
            }
        }

        return false;
    }
284666
private static Collection<? extends URL> doFindPathMatchingFileResources(final URL rootDirResource, final String subPattern) {

        File rootFile = null;
        final Set<URL> rets = new LinkedHashSet<URL>();

        try {
            rootFile = new File(rootDirResource.toURI());
        } catch (final URISyntaxException e) {
            LOGGER.log(Level.ERROR, "cat not resolve the rootFile", e);
            throw new RuntimeException("cat not resolve the rootFile", e);
        }
        String fullPattern = StringUtils.replace(rootFile.getAbsolutePath(), File.separator, "/");

        if (!subPattern.startsWith("/")) {
            fullPattern += "/";
        }
        final String filePattern = fullPattern + StringUtils.replace(subPattern, File.separator, "/");

        @SuppressWarnings("unchecked") final Collection<File> files = FileUtils.listFiles(rootFile, new IOFileFilter() {
            @Override
            public boolean accept(final File dir, final String name) {
                return true;
            }

            @Override
            public boolean accept(final File file) {

                if (file.isDirectory()) {
                    return false;
                }
                if (AntPathMatcher.match(filePattern, StringUtils.replace(file.getAbsolutePath(), File.separator, "/"))) {
                    return true;
                }
                return false;
            }
        }, TrueFileFilter.INSTANCE);

        try {
            for (File file : files) {
                rets.add(file.toURI().toURL());
            }
        } catch (final Exception e) {
            LOGGER.log(Level.ERROR, "convert file to URL error", e);
            throw new RuntimeException("convert file to URL error", e);
        }

        return rets;
    }
772000
public File getDirectory(String targetProject, String targetPackage)
      throws ShellException {
    // targetProject is interpreted as a directory that must exist
    //
    // targetPackage is interpreted as a sub directory, but in package
    // format (with dots instead of slashes). The sub directory will be
    // created
    // if it does not already exist

    File project = new File(targetProject);
    if (!project.isDirectory()) {
      throw new ShellException(getString("Warning.9", //$NON-NLS-1$
          targetProject));
    }

    StringBuilder sb = new StringBuilder();
    StringTokenizer st = new StringTokenizer(targetPackage, "."); //$NON-NLS-1$
    while (st.hasMoreTokens()) {
      sb.append(st.nextToken());
      sb.append(File.separatorChar);
    }

    File directory = new File(project, sb.toString());
    if (!directory.isDirectory()) {
      boolean rc = directory.mkdirs();
      if (!rc) {
        throw new ShellException(getString("Warning.10", //$NON-NLS-1$
            directory.getAbsolutePath()));
      }
    }

    return directory;
  }
1012757
protected List<String> getFileLocationsFromSubsystemContent(String subsystemContent) {
        String sc = subsystemContent + ",";
        List<String> files = new ArrayList<String>();
        boolean isFile = false;
        String location = null;
        int strLen = sc.length();
        boolean quoted = false;
        for (int i = 0, pos = 0; i < strLen; i++) {
            char c = sc.charAt(i);
            if (!quoted && (c == ';' || c == ',')) {
                String str = sc.substring(pos, i);
                pos = i + 1;
                if (logger.isLoggable(Level.FINE)) {
                    logger.fine("element : " + str);
                }
                if (str.contains(":=")) {
                    if (getKey(str).equals(HDR_ATTR_LOCATION)) {
                        location = getValue(str);
                    }
                } else if (str.contains("=")) {
                    if (getKey(str).equals(HDR_ATTR_TYPE) && getValue(str).equals(HDR_ATTR_VALUE_FILE)) {
                        isFile = true;
                    }
                }
                if (c == ',') { // the delimiter of each subsystem content.
                    if (isFile && location != null) {
                        if (logger.isLoggable(Level.FINE)) {
                            logger.fine("location : " + location);
                        }
                        files.add(location);
                    }
                    location = null;
                    isFile = false;
                }
            } else if (c == '\"') {
                quoted = !quoted;
            }
        }
        return files;
    }
283816
public static boolean recursiveDelete (final File pFile) {
        if (pFile.isDirectory()) {
            for (final File child : pFile.listFiles()) {
                if (!recursiveDelete(child)) { return false; }
            }
        }
        return pFile.delete();
    }
733697
public static String getCategoryPath(String rootPath, String baseFolder) throws Exception {

        String base;
        if (rootPath.startsWith(CmsCategoryService.CENTRALIZED_REPOSITORY)) {
            base = CmsCategoryService.CENTRALIZED_REPOSITORY;
        } else {
            base = baseFolder;
            if (!base.endsWith("/")) {
                base += "/";
            }
            if (!base.startsWith("/")) {
                base = "/" + base;
            }
            int pos = rootPath.indexOf(base);
            if (pos < 0) {
                throw new Exception("Invalid category location \"" + rootPath + "\".");
            }
            base = rootPath.substring(0, pos + base.length());
        }
        return rootPath.substring(base.length());
    }
672849
function(root, path) {
				if (path.indexOf(this.SEPARATOR) === 0) {
					root = this.rootNode;
					path = path.substring(1);
				} else {
					if (!root) {
						if (!this.currentDirectory) {
							/* no node to resolve the path in terms of */
							return null;
						}
						root = this.currentDirectory;
					}
				}
				var segments = path.substring(0, path.lastIndexOf(this.SEPARATOR)).split(this.SEPARATOR);
				var result = root;
				for (var i = 0; i < segments.length; i++) {
					if (segments[i].length > 0) {
						result = this.getChild(result, segments[i]);
						if (!result || !result.Directory) {
							/* non-existent directory */
							return null;
						}
					}
				}

				/*
				 * If the full path represents a directory then initiate the
				 * retrieval of its full node info and children.
				 */
				var lastSegment = path.substring(path.lastIndexOf(this.SEPARATOR) + 1);
				var child = this.getChild(result, lastSegment);
				if (child) {
					this._retrieveNode(child);
				}

				if (!result.Children) {
					this._retrieveNode(result);
				}
				return result;
			}
405833
def filename_for(self, subpath):
        
        try:
            filename = self.readme_for(subpath)
            return os.path.relpath(filename, self.root_directory)
        except ReadmeNotFoundError:
            return None