/*
appLoaderOpts: object
.signal: boolean
.parentFolder: string fully qualified path to folder
.appFiles: array of string: fully qualified paths to files
.apps: object key: app identifier, value: AppEntity
483764
function AppLoader(appLoaderOpts, errEmitter) {
	this.load = load

	function load(cb) { // load data from parent process and all app Files
		var isError
		var cbCounter = 3
		var parentApps = {}
		var appFileApps = {}
		var launchBrowser

		parentloader.load(parentDataReceiver)
		appfileloader.loadAppFiles(appLoaderOpts.appFiles, fileDataReceiver)
		doneLoading()

		function parentDataReceiver(err, result) {
			if (result) {
				if (result.appMap) parentApps = result.appMap
				if (result.time) appLoaderOpts.launchTime = result.time
			}
			doneLoading(err)
		}

		function fileDataReceiver(err, appConfigs) {
			if (!err) appFileApps = appConfigs
			doneLoading(err)
		}

		function doneLoading(err) {
			if (!err) {
				if (!--cbCounter) updateAppEntity()
			} else if (!isError) {
				isError = true
				cb(err)
			}
		}

		/*
		appFileApps: the apps we should have
		parentApps: the apps that are currently running
		appLoaderOpts.apps: the apps frontend has configured

		app structure in config file json:
		key: app Name
		.id: optional string default derived from App name: app id
		.state: optional string default run: state on Node God launch, any of 'run', 'debug', 'stop'
		.folder: optional string folder: app launch folder default app id, absolute path or relative to Node God's parent folder
		.start: optional array of string: launch command and arguments for app, default ['node', .folder + '/app']
		.debug: optional array of string: debug launch command and arguments for app, default ['node', '--debug-brk', .folder + '/app']
		.watchFiles: optional string or regexp or array of those, default none: file to watch for app restart
		.watchCopy: optional object default none: key: destination path, value: source path
		- paths to file or folder, relative to .folder
		.signal boolean default from Node God settings: whether process accepts SIGUSR2 signal
		*/
		function updateAppEntity() {

			var feApps = {} // key: app id configured in frontend
			for (var appId in appLoaderOpts.apps) feApps[appId] = true

			var pApps = {} // key: app id that parent process has running
			for (var appId in parentApps) pApps[appId] = true
			for (var appId in appFileApps) { // create or update front end AppEntity instances
				var o = getAppConfig(appFileApps[appId], appId)
				if (!feApps[o.id]) appLoaderOpts.apps[o.id] = new appentity.AppEntity(o, parentApps[o.id]) // app is new to frontend
					.on('data', appLoaderOpts.appListener)
					.on('error', getErrorListener(o.id))
				else appLoaderOpts.apps[o.id].update(o)
				delete feApps[o.id]
				delete pApps[o.id]
			}

			for (var appId in feApps) { // close front end apps
				var appEntity = appLoaderOpts[o.id]
				delete appLoaderOpts[o.id]
				appEntity.close()
				appEntity.removeAllListener()
				delete pApps[o.id]
			}

			for (var appId in pApps) { // kill spurious patent process apps
				// TODO
			}

			if (launchBrowser) {
				appLoaderOpts.launchedBrowser = true
				haraldutil.browseTo(launchBrowser)
			}

			cb()
		}

		function getErrorListener(appId) {
			return listener

			function listener(err) {
				errEmitter.emit('error', new Error(appId + ': ' + err.message))
			}
		}

		function getAppConfig(fileApp, appId) {
			var o = {
				id: appId,
				name: fileApp.name,
			}

			o.state = states[fileApp.state || 0] ||  states[0]

			o.folder = path.resolve(appLoaderOpts.parentFolder, String(fileApp.folder || o.id)) // absolute path

			o.start = Array.isArray(fileApp.start) ? fileApp.start.map(makeString) :
				['node', path.join(o.folder, 'app')]

			o.debug = Array.isArray(fileApp.debug) ? fileApp.debug.map(makeString) :
				['node', '--debug-brk', path.join(o.folder, 'app')]

			o.watchFiles = typeof fileApp.watchFiles === 'string' || fileApp.watchFiles instanceof RegExp ? [fileApp.watchFiles] :
				Array.isArray(fileApp.watchFiles) ? fileApp.watchFiles.map(makeStringOrRegExp) :
				[]

			o.watchFileExclude = Array.isArray(fileApp.watchFileExclude) ? fileApp.watchFileExclude.map(makeString) :
				[]

			o.watchCopy = {}
			for (var dest in fileApp.watchCopy)
				o.watchCopy[
					path.resolve(o.folder, String(dest))] =
					path.resolve(o.folder, String(fileApp.watchCopy[dest]))

			o.signal = fileApp.signal != null ? !!fileApp.signal : appLoaderOpts.signal

			if (fileApp.launchBrowser && !appLoaderOpts.launchedBrowser) launchBrowser = fileApp.launchBrowser

			return o
		}

		function makeString(v) {
			return String(v)
		}

		function makeStringOrRegExp(v) {
			return v instanceof RegExp ? v : String(v)
		}
	}
}
1203446
function getEntitlementFiles(preferences) {
    const files = [];
    const entitlements = path.join(
      preferences.projectRoot,
      "platforms",
      "ios",
      preferences.projectName,
      "Resources",
      `${preferences.projectName}.entitlements`
    );
    files.push(
      path.join(
        preferences.projectRoot,
        "platforms",
        "ios",
        preferences.projectName,
        `${preferences.projectName}.entitlements`
      )
    );
    files.push(entitlements);

    for (let i = 0; i < BUILD_TYPES.length; i++) {
      const buildType = BUILD_TYPES[i];
      const plist = path.join(
        preferences.projectRoot,
        "platforms",
        "ios",
        preferences.projectName,
        `Entitlements-${buildType}.plist`
      );
      files.push(plist);
    }

    return files;
  }
945799
function parseFilepath(path) {
  if (path === undefined) {
    return {filename: null, list: []};
  }

  var list = path.split('/'),
      isDir = (path[path.length - 1] === '/') || (list[list.length - 1].indexOf('.') === -1);

  return {
    filename: isDir ? null : list.pop(),
    list: list
  };
}
728004
function parseFromDir(dir) {
  if (!dir) {
    throw new Error('The app directory must be passed to read JSON files.');
  }
  if (!FileUtils.doesDirectoryExist(dir)) {
    throw new Error(`The passed directory '${dir}' must exist and must be a directory to read JSON files.`);
  }
  const entityDir = `${dir}/.jhipster`;
  if (!FileUtils.doesDirectoryExist(entityDir)) {
    throw new Error(`'${entityDir}' must exist as a directory.`);
  }
  const entities = {};
  const files = fs.readdirSync(entityDir);
  files.forEach(file => {
    if (file.endsWith('.json')) {
      const entityName = file.slice(0, file.length - 5);
      try {
        entities[entityName] = JSONFileReader.readEntityJSON(`${entityDir}/${file}`);
      } catch (error) {
        // Not an entity file, not adding
      }
    }
  });
  const jdl = convertServerOptionsToJDL(JSONFileReader.readEntityJSON(`${dir}/.yo-rc.json`)['generator-jhipster']);
  convertEntitiesToJDL(entities, jdl);
  return jdl;
}
7940
function parseChildInputpaths(build) {
  function parse(build) {
    let inputpaths = [];

    build.forEach(build => {
      inputpaths = inputpaths.concat(build.inputpaths, build.builds ? parse(build.builds) : []);
    });

    return inputpaths;
  }

  build.childInputpaths = parse(build.builds);
}
1044528
function importFolderItem(item, parentId) {
  return {
    parentId,
    _id: `__GRP_${requestGroupCount++}__`,
    _type: 'request_group',
    name: item.name || `Folder {requestGroupCount}`,
    description: item.description || '',
  };
}
1061102
function (classpath) {
            var apps = this._appenders;

            if (classpath) {
                apps = [];
                for (var i = 0; i < this._appenders.length; i++) {
                    if (this._appenders[i].$classpath == classpath) {
                        apps.push(this._appenders[i]);
                    }
                }
            }

            return apps;
        }
251451
function pnodeParents (pnode) {
        if (!pnode.valid) return undefined
        var parentPaths = parents(pnode.path),
        list            = []
        for (var i = 0; i < parentPaths.length; i++) list.push( ptree(parentPaths[i]) )
        return list
    }
1017156
function(folderPath, callback, level) {
        level = level || 1;
        if (typeof callback !== 'function') {
            throw 'The callback argument must be a valid function.';
        }

        var treeTraversed = _promise.deferred();
        var dirContentsReady = _promise.deferred();

        function _rejectTraversal() {
            treeTraversed.reject(folderPath);
        };

        // Attempt to read the contents of the folder.
        _fs.readdir(folderPath, dirContentsReady.getResolver());

        // Handler to handle when the folder contents are ready.
        dirContentsReady.success(function(data) {
            // Create a resolver that will complete the promise after all
            // items have been processed.
            var resolver = treeTraversed.getMultiStepResolver(data.length);

            // The contents of the folder have been read. Process them.
            data.forEach(function(item) {
                var itemStats = _promise.deferred();
                var itemPath = _path.join(folderPath, item);

                _fs.lstat(itemPath, itemStats.getResolver());

                itemStats.success(function(data) {
                    if (data.isDirectory()) {
                        // Let the listener know that we found an item.
                        callback(itemPath, level, true);

                        // Traverse the child folder, and only mark this
                        // activity as completed once the child is finished.
                        mod.traverse(itemPath, callback, level + 1)
                            .success(resolver.stepComplete)
                            .fail(resolver.reject);
                    } else {
                        // Let the listener know that we found an item.
                        callback(itemPath, level, false);

                        // Nothing to wait for. Mark the step as completed.
                        resolver.stepComplete();
                    }

                    //Could not get child item stats. Traversal failed.
                }).fail(_rejectTraversal);
            });

            // Could not read child items. Traversal failed.
        }).fail(_rejectTraversal);

        return treeTraversed.promise();
    }
1172751
function getAppDir() {
    var fileRepo = args._[1] ? path.resolve(args._[1]) : undefined;
    return fileRepo && fs.existsSync(fileRepo) ? fileRepo : 0;
}
1375000
def path_parents(path, root = nil)
      root = "#{root}#{File::SEPARATOR}" if root
      parents = []

      loop do
        parent = File.dirname(path)
        break if parent == path
        break if root && !path.start_with?(root)
        parents << path = parent
      end

      parents
    end
300363
function loadMappings(rootDir, paths) {
        var mappings = {}, i, j, fullPath, fileNames, fileName, path, name, val;

        if (!paths) {
            return mappings;
        }

        for (i = 0; i < paths.length; i++) {
            path = paths[i];
            fullPath = rootDir + '/' + path;

            // if the directory doesn't exist, then skip to the next loop iteration
            if (!fs.existsSync(p.normalize(fullPath))) {
                continue;
            }

            // loop through all files in this folder
            fileNames = fs.readdirSync(p.normalize(fullPath));

            for (j = 0; j < fileNames.length; j++) {
                fileName = fileNames[j];

                // if it is a javascript file and it DOES NOT end in .service.js, then save the mapping
                if (utils.isJavaScript(fileName) && !fileName.match(/^.*\.service\.js$/)) {
                    name = utils.getCamelCase(fileName);
                    val = utils.getModulePath(path, fileName);
                    mappings[name] = val;
                    mappings[name.substring(0, 1).toUpperCase() + name.substring(1)] = val;  // store PascalCase as well
                }

                // else if we are dealing with a directory, recurse down into the folder
                else if (fs.lstatSync(p.join(fullPath, fileName)).isDirectory()) {
                    _.extend(mappings, this.loadMappings(rootDir, [path + '/' + fileName]));
                }
            }
        }

        return mappings;
    }
56710
private Path getYarnFilesDir(final ApplicationId appId) throws IOException {
		final FileSystem fileSystem = FileSystem.get(yarnConfiguration);
		final Path homeDir = fileSystem.getHomeDirectory();
		return new Path(homeDir, ".flink/" + appId + '/');
	}
558837
function isAppDir_p(dirPath) {
      var deferred = Q.defer();
      fs.exists(dirPath, function(exists) {
        if (!exists)
          deferred.resolve({
            exists: false, 
            isApp: false, 
            isRmd: false, 
            index: false
          });
        else {
          deferred.resolve(
            Q.nfcall(fs.readdir, dirPath)
            .then(
              function(entries) {
                var app = _.find(entries, function(entry) {
                  return /^server\.r$/i.test(entry);
                });
                var singleApp = _.find(entries, function(entry) {
                  return /^app\.r$/i.test(entry);
                });
                var rmd = _.find(entries, function(entry) {
                  return /\.rmd$/i.test(entry);
                });
                var indexRmd = _.find(entries, function(entry) {
                  if (/^index\.rmd$/i.test(entry)){
                    return entry;
                  }
                  return false;
                });
                var indexHtm = _.find(entries, function(entry) {
                  if (/index\.htm(l)?$/i.test(entry)){
                    return entry;
                  }
                  return false;
                });

                // Give priority to an Rmd index, the fall back to an html index
                return {
                  exists: true, 
                  isApp: (!!app || !!singleApp), 
                  isRmd: !!rmd, 
                  indexType: indexRmd ? 'rmd' : indexHtm ? 'html' : null,
                  indexPath: indexRmd || indexHtm
                };
              },
              function(err) {
                if (err.code == 'ENOTDIR') {
                  return {
                    exists: false, 
                    isApp: false, 
                    isRmd: false, 
                    indexType: null
                  };
                }
                else {
                  logger.error('Error reading dir: ' + err.message);
                  return {
                    exists: true, 
                    isApp: false, 
                    isRmd: false, 
                    indexType: null
                  };
                }
              }
            )
          );
        }
      });

      return deferred.promise;
    }
665639
function(app) {
  return {
    compose: getComposeFiles(app),
    project: app.name,
    opts: {
      app: app
    }
  };
}
1314139
def app_controllers_recursive(path)
      invalid_entries = ['..', '.', 'concerns']

      (Dir.entries(path) - invalid_entries).each do |entry|
        if File.directory?(path + entry)
          app_controllers_recursive(path + entry + '/')
        elsif File.extname(entry) == '.rb'
          parent_directory = File.dirname(path + entry).split(/\//).last

          container = if parent_directory == 'controllers'
            'default'
          else
            parent_directory
          end

          @controllers[container.to_sym] ||= []

          unless File.basename(path + entry, '.*') == 'application_controller'
            @controllers[container.to_sym] << File.basename(path + entry, '.*')
          end
        end
      end
      @controllers
    end
865559
function (folder) {
		var elems = getFolderElements( folder ),
			result = {};

		// files
		elems.files.forEach( function (route) {
			// get object name
			var fileName = path.basename( route, '.json' );
			// assign object data from file
			result[ fileName ] = getData.file( route );
		});

		// no namesake folders
		elems.folders.forEach( function (route) {
			// get object name
			var fileName = path.basename( route );
			// assign data from folder
			result[ fileName ] = extend( result[ fileName ] || {}, getData.folder( route ));
		});

		return result;
	}