////////////////////////////////////////////////////////////////////////////////
// Site root path resolution.
// findSiteRoot returns a directory R such as R/.cipd exists and p is inside
// R or p is R. Returns empty string if no such directory.
497327
func findSiteRoot(p string) string {
	for {
		if isSiteRoot(p) {
			return p
		}
		// Dir returns "/" (or C:\\) when it encounters the root directory. It is
		// the only case when Dir(...) return value ends with separator.
		parent := filepath.Dir(p)
		if parent[len(parent)-1] == filepath.Separator {
			// It is possible disk root has .cipd directory, check it.
			if isSiteRoot(parent) {
				return parent
			}
			return ""
		}
		p = parent
	}
}
232927
func matchFind(ctx *findContext, fileContent contentMessage) (match bool) {
	match = true
	prefixPath := ctx.targetURL
	// Add separator only if targetURL doesn't already have separator.
	if !strings.HasPrefix(prefixPath, string(ctx.clnt.GetURL().Separator)) {
		prefixPath = ctx.targetURL + string(ctx.clnt.GetURL().Separator)
	}
	// Trim the prefix such that we will apply file path matching techniques
	// on path excluding the starting prefix.
	path := strings.TrimPrefix(fileContent.Key, prefixPath)
	if match && ctx.ignorePattern != "" {
		match = !pathMatch(ctx.ignorePattern, path)
	}
	if match && ctx.namePattern != "" {
		match = nameMatch(ctx.namePattern, path)
	}
	if match && ctx.pathPattern != "" {
		match = pathMatch(ctx.pathPattern, path)
	}
	if match && ctx.regexPattern != "" {
		match = regexMatch(ctx.regexPattern, path)
	}
	if match && ctx.olderThan != "" {
		match = !isOlder(fileContent.Time, ctx.olderThan)
	}
	if match && ctx.newerThan != "" {
		match = !isNewer(fileContent.Time, ctx.newerThan)
	}
	if match && ctx.largerSize > 0 {
		match = int64(ctx.largerSize) < fileContent.Size
	}
	if match && ctx.smallerSize > 0 {
		match = int64(ctx.smallerSize) > fileContent.Size
	}
	return match
}
516171
func FindSrcPaths(appImportPath, revelImportPath string, packageResolver func(pkgName string) error) (appSourcePath, revelSourcePath string, err error) {
	var (
		gopaths = filepath.SplitList(build.Default.GOPATH)
		goroot  = build.Default.GOROOT
	)

	if len(gopaths) == 0 {
		err = errors.New("GOPATH environment variable is not set. " +
			"Please refer to http://golang.org/doc/code.html to configure your Go environment.")
		return
	}

	if ContainsString(gopaths, goroot) {
		err = fmt.Errorf("GOPATH (%s) must not include your GOROOT (%s). "+
			"Please refer to http://golang.org/doc/code.html to configure your Go environment. ",
			build.Default.GOPATH, goroot)
		return

	}

	appPkgDir := ""
	appPkgSrcDir := ""
	if len(appImportPath)>0 {
		Logger.Info("Seeking app package","app",appImportPath)
		appPkg, err := build.Import(appImportPath, "", build.FindOnly)
		if err != nil {
			err = fmt.Errorf("Failed to import " + appImportPath + " with error %s", err.Error())
			return "","",err
		}
		appPkgDir,appPkgSrcDir =appPkg.Dir, appPkg.SrcRoot
	}
	Logger.Info("Seeking remote package","using",appImportPath, "remote",revelImportPath)
	revelPkg, err := build.Default.Import(revelImportPath, appPkgDir, build.FindOnly)
	if err != nil {
		Logger.Info("Resolved called Seeking remote package","using",appImportPath, "remote",revelImportPath)
		packageResolver(revelImportPath)
		revelPkg, err = build.Import(revelImportPath, appPkgDir, build.FindOnly)
		if err != nil {
			err = fmt.Errorf("Failed to find Revel with error: %s", err.Error())
			return
		}
	}

	revelSourcePath, appSourcePath = revelPkg.Dir[:len(revelPkg.Dir)-len(revelImportPath)], appPkgSrcDir
	return
}
271090
func findPackage(packageName string) string {
	if packageName == "" {
		return ""
	}

	for _, srcPath := range srcPaths {
		packagePath := filepath.Join(srcPath, packageName)
		if exists(packagePath) {
			return packagePath
		}
	}

	return ""
}
884872
func Find(root string, pattern *regexp.Regexp) (paths []string) {
	if Exists(root) {
		filepath.Walk(root, func(path string, info os.FileInfo, e error) error {
			if pattern.MatchString(path) {
				paths = append(paths, info.Name())
			}
			return e
		})
	}
	return
}
653938
func (num Number) Find(path Ref) (Value, error) {
	if len(path) == 0 {
		return num, nil
	}
	return nil, fmt.Errorf("find: not found")
}
270226
func (d *Dir) Lookup(ctx context.Context, req *fuse.LookupRequest, resp *fuse.LookupResponse) (node fs.Node, err error) {
	ctx = d.folder.fs.config.MaybeStartTrace(ctx, "Dir.Lookup",
		fmt.Sprintf("%s %s", d.node.GetBasename(), req.Name))
	defer func() { d.folder.fs.config.MaybeFinishTrace(ctx, err) }()

	d.folder.fs.vlog.CLogf(ctx, libkb.VLog1, "Dir Lookup %s", req.Name)
	defer func() { err = d.folder.processError(ctx, libkbfs.ReadMode, err) }()

	// This fits in situation 1 as described in libkbfs/delayed_cancellation.go
	err = libcontext.EnableDelayedCancellationWithGracePeriod(
		ctx, d.folder.fs.config.DelayedCancellationGracePeriod())
	if err != nil {
		return nil, err
	}

	specialNode := handleTLFSpecialFile(
		req.Name, d.folder, &resp.EntryValid)
	if specialNode != nil {
		return specialNode, nil
	}

	// Check if this is a per-file metainformation file, if so
	// return the corresponding SpecialReadFile.
	if strings.HasPrefix(req.Name, libfs.FileInfoPrefix) {
		name := req.Name[len(libfs.FileInfoPrefix):]
		return NewFileInfoFile(d.folder.fs, d.node, name, &resp.EntryValid), nil
	}

	newNode, de, err := d.folder.fs.config.KBFSOps().Lookup(ctx, d.node, req.Name)
	if err != nil {
		if _, ok := err.(idutil.NoSuchNameError); ok {
			return nil, fuse.ENOENT
		}
		return nil, err
	}

	// No libkbfs calls after this point!
	d.folder.nodesMu.Lock()
	defer d.folder.nodesMu.Unlock()

	// newNode can be nil even without errors when the KBFS direntry
	// is of a type that doesn't get its own node (is fully contained
	// in the directory); Symlink does this.
	if newNode != nil {
		if n, ok := d.folder.nodes[newNode.GetID()]; ok {
			return n, nil
		}

		newNode.FillCacheDuration(&resp.EntryValid)
	}

	switch de.Type {
	default:
		return nil, fmt.Errorf("unhandled entry type: %v", de.Type)

	case data.File, data.Exec:
		child := d.makeFile(newNode)
		d.folder.nodes[newNode.GetID()] = child
		return child, nil

	case data.Dir:
		child := newDir(d.folder, newNode)
		d.folder.nodes[newNode.GetID()] = child
		return child, nil

	case data.Sym:
		// Give each symlink instance a unique inode.  We don't get
		// enough information about remote renames of syminks to be
		// able to attach a constant inode to a given symlink.
		child := &Symlink{
			parent: d,
			name:   req.Name,
			inode:  d.folder.fs.assignInode(),
		}
		// A Symlink is never included in Folder.nodes, as it doesn't
		// have a libkbfs.Node to keep track of renames.
		return child, nil
	}
}
340996
func (dir *Directory) lookup(path string) *Directory {
	d := splitPath(dir.Path)
	p := splitPath(path)
	i := 0
	for i < len(d) {
		if i >= len(p) || d[i] != p[i] {
			return nil
		}
		i++
	}
	for dir != nil && i < len(p) {
		dir = dir.lookupLocal(p[i])
		i++
	}
	return dir
}
973970
func GetIntelRdtPath(id string) (string, error) {
	rootPath, err := getIntelRdtRoot()
	if err != nil {
		return "", err
	}

	path := filepath.Join(rootPath, id)
	return path, nil
}
761933
func (oc *ObjectComprehension) Find(path Ref) (Value, error) {
	if len(path) == 0 {
		return oc, nil
	}
	return nil, fmt.Errorf("find: not found")
}
785990
func (ctx *Context) findImportDir(relative, importPath string) (dir, gopath string, err error) {
	if importPath == "builtin" || importPath == "unsafe" || importPath == "C" {
		return filepath.Join(ctx.Goroot, importPath), ctx.Goroot, nil
	}
	if len(relative) != 0 {
		rel := relative
		for {
			look := filepath.Join(rel, ctx.VendorDiscoverFolder, importPath)
			nextRel := filepath.Join(rel, "..")
			if rel == nextRel {
				break
			}
			rel = nextRel
			fi, err := os.Stat(look)
			if os.IsNotExist(err) {
				continue
			}
			if err != nil {
				continue
			}
			if !fi.IsDir() {
				continue
			}
			for _, gopath = range ctx.GopathList {
				if pathos.FileHasPrefix(look, gopath) {
					hasGo, err := hasGoFileInFolder(look)
					if err != nil {
						return "", "", err
					}
					if hasGo {
						return look, gopath, nil
					}
				}
			}
		}

	}
	for _, gopath = range ctx.GopathList {
		dir := filepath.Join(gopath, importPath)
		fi, err := os.Stat(dir)
		if os.IsNotExist(err) {
			continue
		}
		if fi == nil {
			continue
		}
		if !fi.IsDir() {
			continue
		}

		return dir, gopath, nil
	}
	return "", "", ErrNotInGOPATH{importPath}
}
82820
func resolveDirPlaceholder(p *helpers.PathSpec, placeholder string) (cacheDir string, isResource bool, err error) {
	switch strings.ToLower(placeholder) {
	case ":resourcedir":
		return "", true, nil
	case ":cachedir":
		d, err := helpers.GetCacheDir(p.Fs.Source, p.Cfg)
		return d, false, err
	case ":project":
		return filepath.Base(p.WorkingDir), false, nil
	}

	return "", false, errors.Errorf("%q is not a valid placeholder (valid values are :cacheDir or :resourceDir)", placeholder)
}
507692
func findIntelRdtMountpointDir() (string, error) {
	f, err := os.Open("/proc/self/mountinfo")
	if err != nil {
		return "", err
	}
	defer f.Close()

	s := bufio.NewScanner(f)
	for s.Scan() {
		text := s.Text()
		fields := strings.Split(text, " ")
		// Safe as mountinfo encodes mountpoints with spaces as \040.
		index := strings.Index(text, " - ")
		postSeparatorFields := strings.Fields(text[index+3:])
		numPostFields := len(postSeparatorFields)

		// This is an error as we can't detect if the mount is for "Intel RDT"
		if numPostFields == 0 {
			return "", fmt.Errorf("Found no fields post '-' in %q", text)
		}

		if postSeparatorFields[0] == "resctrl" {
			// Check that the mount is properly formatted.
			if numPostFields < 3 {
				return "", fmt.Errorf("Error found less than 3 fields post '-' in %q", text)
			}

			// Check if MBA Software Controller is enabled through mount option "-o mba_MBps"
			if strings.Contains(postSeparatorFields[2], "mba_MBps") {
				isMbaScEnabled = true
			}

			return fields[4], nil
		}
	}
	if err := s.Err(); err != nil {
		return "", err
	}

	return "", NewNotFoundError("Intel RDT")
}
49269
func FindCWD() (string, error) {
	serverFile, err := filepath.Abs(os.Args[0])

	if err != nil {
		return "", fmt.Errorf("can't get absolute path for executable: %v", err)
	}

	path := filepath.Dir(serverFile)
	realFile, err := filepath.EvalSymlinks(serverFile)

	if err != nil {
		if _, err = os.Stat(serverFile + ".exe"); err == nil {
			realFile = filepath.Clean(serverFile + ".exe")
		}
	}

	if err == nil && realFile != serverFile {
		path = filepath.Dir(realFile)
	}

	return path, nil
}
207761
func (r Routefinder) Lookup(path string) (string, map[string]string) {
	// Dump any query string
	normalizedPath := strings.SplitN(path, "?", 2)[0]

	// Check key against regex'es
	for _, template := range r {
		// Get the prefix of the regex and test it
		if !strings.HasPrefix(normalizedPath, template.prefix) {
			continue
		}

		// Is the prefix == the whole thing? Then a match == win
		if !template.hasVars && normalizedPath == template.name {
			return template.name, map[string]string{}
		}

		// Check key against regexes
		if !template.re.MatchString(normalizedPath) {
			continue
		}

		subMatchNames := template.re.SubexpNames()
		subMatchValues := template.re.FindStringSubmatch(normalizedPath)

		meta := make(map[string]string, len(subMatchNames))

		for j := 1; j < len(subMatchNames); j++ {
			meta[subMatchNames[j]] = subMatchValues[j]
		}

		templateName := template.name

		// If the template ends with /... and we extracted __TRAILING__, transplant it back
		if trailing, ok := meta["__TRAILING__"]; ok && strings.HasSuffix(template.name, "/...") {
			templateName = templateName[:len(templateName)-3] + trailing
			delete(meta, "__TRAILING__")
		}

		if _, ok := meta["__DISCARD__"]; ok && strings.HasSuffix(template.name, "/???") {
			delete(meta, "__DISCARD__")
		}

		return templateName, meta
	}

	return "", map[string]string{}
}
1051386
function find () {
  const serialPath = this.paths.linux.serial;
  const readLink = (file, filePath) => (
    new Promise((resolve, reject) => {
      fs.readlink(filePath, (error, link) => {
        if (error) {
          reject(error);
        } else {
          resolve({
            'info': file.replace(/\_/g, ' '),
            'port': path.resolve(serialPath, link)
          });
        }
      });
    })
  );
  const readDir = (directory) => (
    new Promise((resolve, reject) => {
      fs.readdir(directory, (error, files) => {
        if (error) {
          reject(error);
        } else {
          resolve(files);
        }
      });
    })
  );

  return new Promise(async (resolve, reject) => {
    try {
      const files = await readDir(this.paths.linux.serial);

      if (!files.length) {
        // Resolve if the directory is empty
        resolve([]);
      }

      let promises = [];
      files.forEach((file) => {
        const filePath = path.join(serialPath, file);
        promises.push(readLink(file, filePath));
      });

      // Wait for all promisses to be resolved
      this.ports = await Promise.all(promises);

      resolve(this.ports);
    } catch (error) {
      reject(error);
    }
  });
}
725907
func (finder PackageFinder) Root() string {
	if finder.root == "" {
		return os.Getenv("GOPATH")
	}
	return finder.root
}