Resolve the root folder containing for node_modules
since gitbook can be used as a library and dependency can be flattened.

@return {String} folderPath
186456
function locateRootFolder() {
    var firstDefaultPlugin = DEFAULT_PLUGINS.first();
    var pluginPath = resolve.sync(firstDefaultPlugin.getNpmID() + '/package.json', {
        basedir: __dirname
    });
    var nodeModules = path.resolve(pluginPath, '../../..');

    return nodeModules;
}
330518
function findModulePath(moduleName, currentState) {
    const cwd = currentState.get('cwd');

    if (currentState.get('global')) {
        return path.join(cwd, moduleName);
    }

    // Module._nodeModulePaths does not include some places the node module resolver searches, such as
    // the global prefix or other special directories. This is desirable because if a module is missing
    // in the project directory we want to be sure to report it as missing.
    // We can't use require.resolve because it fails if the module doesn't have an entry point.
    const nodeModulesPaths = Module._nodeModulePaths(cwd);
    const possibleModulePaths = nodeModulesPaths.map(x => path.join(x, moduleName));
    const modulePath = possibleModulePaths.find(pathExists.sync);

    // if no existing path was found, return the first tried path anyway
    return modulePath || path.join(cwd, moduleName);
}
802587
@Override
    public String getRootFolderId() {
        if (rootNodeId == null) {
            Document layout = getUserLayoutDOM();

            Element rootNode =
                    this.xpathOperations.evaluate("//layout/folder", layout, XPathConstants.NODE);
            if (rootNode == null
                    || !rootNode.getAttribute(Constants.ATT_TYPE)
                            .equals(Constants.ROOT_FOLDER_ID)) {
                LOG.error(
                        "Unable to locate root node in layout of "
                                + owner.getUserName()
                                + ". Resetting corrupted layout.");
                resetLayout((String) null);

                rootNode =
                        this.xpathOperations.evaluate(
                                "//layout/folder", layout, XPathConstants.NODE);
                if (rootNode == null
                        || !rootNode.getAttribute(Constants.ATT_TYPE)
                                .equals(Constants.ROOT_FOLDER_ID)) {
                    throw new PortalException(
                            "Corrupted layout detected for "
                                    + owner.getUserName()
                                    + " and resetting layout failed.");
                }
            }
            rootNodeId = rootNode.getAttribute("ID");
        }
        return rootNodeId;
    }
77896
function findFilesToPackage(dir, callback) {
    var cwd = process.cwd();
    process.chdir(dir);

    var gitls = spawn('git', ['ls-files']),
        // This gets the full path to each file in each submodule
        subls = spawn('git', ['submodule', 'foreach', 'for file in `git ls-files`; do echo "$path/$file"; done']);
        // List all node_modules
        modls = spawn('find', ['node_modules']);


    var mainFileList = '';
    gitls.stdout.on('data', function (data) {
        mainFileList += data;
    });
    gitls.on('exit', returnFileList);

    var subFileList = '';
    subls.stdout.on('data', function (data) {
        subFileList += data;
    });
    subls.on('exit', returnFileList);
    
    var modFileList = '';
    modls.stdout.on('data', function (data) {
        modFileList += data;
    });
    modls.on('exit', returnFileList);

    var lsCount = 0;
    function returnFileList(code) {
        lsCount++;
        if (lsCount < 3) {
            return;
        }
        process.chdir(cwd);

        // Convert \n separated list of filenames into a sorted array
        var fileList = (mainFileList.trim() + '\n' + subFileList.trim() + '\n' + modFileList.trim()).split('\n').filter(function(file) {
            // Ignore entering submodule messages
            if (file.indexOf('Entering ') === 0) {
                return;
            }

            // Ignore hidden and backup files
            if (file.split('/').pop()[0] == '.' || file[file.length - 1] == '~') {
                return;
            }

            // Submodules appear in ls-files but aren't files. Skip them
            if (fs.statSync(path.join(dir, file)).isDirectory()) {
                return;
            }

            
            return file;
        }).sort();

        callback(fileList);
    }

}
1158410
function fileToPackage(d) {
  debug(d);
  if (d.startsWith('packages/node_modules/')) {
    d = d.replace('packages/node_modules/', '');
    d = d.split('/');
    if (d[0].startsWith('@')) {
      return d.slice(0, 2).join('/');
    }

    return d[0];
  }

  if (d.startsWith('docs') || d.startsWith('documentation') || d.startsWith('.github') || d.endsWith('.md')) {
    return 'docs';
  }

  return 'tooling';
}
780568
function resolvePath(path, options, callback) {
        if (!callback) {
            callback = options;
            options = {};
        }
        
        var alreadyRooted = options.alreadyRooted;
        var checkSymlinks = options.checkSymlinks === undefined 
            ? true : options.checkSymlinks;
        var isHome        = false;
        
        if (checkSymlinks === undefined)
            checkSymlinks = true;
        if (path.substr(0, 2) == "~/") {
            isHome = true;
            path = process.env.HOME + path.substr(1);
        }
        else if (!alreadyRooted) 
            path = join(root, path);

        if (checkSymlinks && fsOptions.checkSymlinks && !alreadyRooted) 
            fs.realpath(path, check);
        else check(null, path);

        function check(err, path) {
            if (err) return callback(err);
            
            if (!options.nocheck) {
                if (!(path === base || path.substr(0, root.length) === root)
                  && !isHome) {
                    err = new Error("EACCESS: '" + path + "' not in '" + root + "'");
                    err.code = "EACCESS";
                    return callback(err);
                }
            }
            callback(null, path);
        }
    }
1025147
function getRoot(cwd, filename, smap) {
    var relativePath = path.relative(cwd, filename);

    var segments = relativePath.split('node_modules');

    var sourceRoot = smap.getProperty('sourceRoot') || '/source/' + relativePath;

    if (segments.length <= 1) {
        return sourceRoot;
    } else {
        return sourceRoot
            .replace(/^\/source\//, '/source/' + pathToPackage());
    }

    // it works, somehow ¯\_(ツ)_/¯
    function pathToPackage() {
        var upToNodeModules = segments
            .slice(0, -1)
            .concat('/')
            .join('node_modules');

        var packageName = segments[segments.length - 1]
            .split('/', 2)[1]
            + '/';

        return upToNodeModules + packageName;
    }
}
550521
function resolvePathname(to) {
  var from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';

  var toParts = to && to.split('/') || [];
  var fromParts = from && from.split('/') || [];

  var isToAbs = to && isAbsolute(to);
  var isFromAbs = from && isAbsolute(from);
  var mustEndAbs = isToAbs || isFromAbs;

  if (to && isAbsolute(to)) {
    // to is absolute
    fromParts = toParts;
  } else if (toParts.length) {
    // to is relative, drop the filename
    fromParts.pop();
    fromParts = fromParts.concat(toParts);
  }

  if (!fromParts.length) { return '/'; }

  var hasTrailingSlash = void 0;
  if (fromParts.length) {
    var last = fromParts[fromParts.length - 1];
    hasTrailingSlash = last === '.' || last === '..' || last === '';
  } else {
    hasTrailingSlash = false;
  }

  var up = 0;
  for (var i = fromParts.length; i >= 0; i--) {
    var part = fromParts[i];

    if (part === '.') {
      spliceOne(fromParts, i);
    } else if (part === '..') {
      spliceOne(fromParts, i);
      up++;
    } else if (up) {
      spliceOne(fromParts, i);
      up--;
    }
  }

  if (!mustEndAbs) { for (; up--; up) {
    fromParts.unshift('..');
  } }if (mustEndAbs && fromParts[0] !== '' && (!fromParts[0] || !isAbsolute(fromParts[0]))) { fromParts.unshift(''); }

  var result = fromParts.join('/');

  if (hasTrailingSlash && result.substr(-1) !== '/') { result += '/'; }

  return result;
}
234723
function pkgPath(pkg) {
    pkg = pkg.pkg || pkg;
    var pkgPath = npmResolve(pkg, { basedir:opts.basedir, paths:builtins } );
    if (!pkgPath) throw new Error('cannot resolve module ' + pkg);
    return pkgPath;
  }
806666
function getRootPath (p) {
  p = path.normalize(path.resolve(p)).split(path.sep)
  if (p.length > 0) return p[0]
  return null
}
1020304
function initBook(rootFolder) {
    var extension = '.md';

    return fs.mkdirp(rootFolder)

    // Parse the summary and readme
    .then(function() {
        var fs = createNodeFS(rootFolder);
        var book = Book.createForFS(fs);

        return Parse.parseReadme(book)

        // Setup default readme if doesn't found one
        .fail(function() {
            var readmeFile = File.createWithFilepath('README' + extension);
            var readme = Readme.create(readmeFile);
            return book.setReadme(readme);
        });
    })
    .then(Parse.parseSummary)

    .then(function(book) {
        var logger = book.getLogger();
        var summary = book.getSummary();
        var summaryFile = summary.getFile();
        var summaryFilename = summaryFile.getPath() || ('SUMMARY' + extension);

        var articles = summary.getArticlesAsList();

        // Write pages
        return Promise.forEach(articles, function(article) {
            var articlePath = article.getPath();
            var filePath = articlePath? path.join(rootFolder, articlePath) : null;
            if (!filePath) {
                return;
            }

            return fs.assertFile(filePath, function() {
                return fs.ensureFile(filePath)
                .then(function() {
                    logger.info.ln('create', article.getPath());
                    return fs.writeFile(filePath, '# ' + article.getTitle() + '\n\n');
                });
            });
        })

        // Write summary
        .then(function() {
            var filePath = path.join(rootFolder, summaryFilename);

            return fs.ensureFile(filePath)
            .then(function() {
                logger.info.ln('create ' + path.basename(filePath));
                return fs.writeFile(filePath, summary.toText(extension));
            });
        })

        // Log end
        .then(function() {
            logger.info.ln('initialization is finished');
        });
    });
}
478694
function findRoot() {

  let rootPath;

  try {
    rootPath = glob.sync('../**/Drupal.php', {ignore: ['../vendor/**', '../node_modules/**']});
  } catch (err) {
    throw new Error('No Drupal root found.');
  }

  // If we found no results for Drupal.php..then bomb out.
  if (rootPath.length === 0) {
    throw new Error('No Drupal root found.');
  }

  // Glob returns an array, even though we've only got one item.
  rootPath = rootPath[0];

  const filePathParts = rootPath.split(path.sep);
  const coreDirPosition = filePathParts.indexOf('core');

  // If we found a Drupal.php file, but no core directory..then bomb out.
  if (coreDirPosition === -1) {
    throw new Error('No Drupal root found.');
  }

  return filePathParts.slice(0, coreDirPosition).join(path.sep);

}
802996
private File resolveBasedir() throws IOException {
    String path = null;

    if (project != null) {
      File file = project.getBasedir();
      if (file != null) {
        path = file.getAbsolutePath();
      }
    }

    if (path == null) {
      path = session.getExecutionRootDirectory();
    }

    if (path == null) {
      path = System.getProperty("user.dir");
    }

    return new File(path).getCanonicalFile();
  }
205697
function getProjectRootDirectory() {
  // From the current directory, check if parent directories have a package.json file and if it contains
  // a reference to the @myrmex/core node_module
  let cwd = process.cwd();
  let packageJson;
  let found = false;

  do {
    try {
      packageJson = require(path.join(cwd, 'package.json'));
      if ((packageJson.dependencies && packageJson.dependencies['@myrmex/core'])
        || (packageJson.devDependencies && packageJson.devDependencies['@myrmex/core'])) {
        found = true;
      } else {
        cwd = path.dirname(cwd);
      }
    } catch (e) {
      cwd = path.dirname(cwd);
    }
  } while (cwd !== path.dirname(cwd) && !found);
  if (found) {
    return cwd;
  }
  return false;
}
167625
function(root) {
    var files;
    var ignored = ['node_modules/', 'bower_components/', 'dist/', 'tmp/', 'blueprints/'];
    files = walkSync(root).filter(function(file){
      return !ignored.map(function(i){
        return file.indexOf(i) !== -1;
      }).reduce(function(total,value){
        // if we have a true value, then don't include
        return total ? total : (value ? value : total);
      });
    });
    return {
      js: filterByExt(files,'.js'),
      hbs: filterByExt(files,'.hbs')
    };
  }
952454
function cleanFolder(root) {
    if (!fs.existsSync(root)) return fsUtils.mkdirp(root);

    return listFiles(root, {
        ignoreFiles: [],
        ignoreRules: [
            // Skip Git and SVN stuff
            '.git/',
            '.svn/'
        ]
    })
    .then(function(files) {
        var d = Q.defer();

        _.reduce(files, function(prev, file, i) {
            return prev.then(function() {
                var _file = path.join(root, file);

                d.notify({
                    i: i+1,
                    count: files.length,
                    file: _file
                });
                return fsUtils.remove(_file);
            });
        }, Q())
        .then(function() {
            d.resolve();
        }, function(err) {
            d.reject(err);
        });

        return d.promise;
    });
}
803199
function walkTree(dirPath) {
    let filesindir = [];
    return new Promise((res, rej) => {
        if (dirPath.match(/node_modules|.git|bower|LICENCE|tree.json/)) {
            rej([]);
        }

        const relative = `${dirPath}/`,
            readPath = dirPath === '.' ? ROOT + '/' : dirPath + '/';

        readdir(path.resolve(readPath))
            .then(files => {
                files.map(async(i) => {
                    let file;
                    if (fs.statSync(path.join(relative, i)).isDirectory()) {
                        file = {
                            name: i,
                            type: 'dir',
                            path: `${relative}${i}`,
                            files: {}
                        }
                    } else {
                        file = {
                            id: id,
                            name: i,
                            type: 'file',
                            path: `${relative}${i}`,
                            imports: [],
                            exports: []
                        }
                        AllFiles[id++] = file;
                    }
                    filesindir.push(file);
                })
                res(filesindir);
            })
            .catch(err => {
                console.error(err);
                rej([]);
            })
    })
}