// imports returns true if the current file imports the specified package path.
969024
func (f *file) imports(importPath string) bool {
	all := astutil.Imports(f.fset, f.f)
	for _, p := range all {
		for _, i := range p {
			uq, err := strconv.Unquote(i.Path.Value)
			if err == nil && importPath == uq {
				return true
			}
		}
	}
	return false
}
1026385
func New(currentpkg string) Importer {
	return &imports{
		currentpkg: currentpkg,
		imp:        make(map[string]string),
	}
}
1066735
func addImports(imports map[string]string, decl ast.Decl, srcDir string) {
	genDecl, ok := decl.(*ast.GenDecl)
	if !ok {
		return
	}

	if genDecl.Tok != token.IMPORT {
		return
	}

	for _, spec := range genDecl.Specs {
		importSpec := spec.(*ast.ImportSpec)
		var pkgAlias string
		if importSpec.Name != nil {
			pkgAlias = importSpec.Name.Name
			if pkgAlias == "_" {
				continue
			}
		}
		quotedPath := importSpec.Path.Value           // e.g. "\"sample/app/models\""
		fullPath := quotedPath[1 : len(quotedPath)-1] // Remove the quotes

		// If the package was not aliased (common case), we have to import it
		// to see what the package name is.
		// TODO: Can improve performance here a lot:
		// 1. Do not import everything over and over again.  Keep a cache.
		// 2. Exempt the standard library; their directories always match the package name.
		// 3. Can use build.FindOnly and then use parser.ParseDir with mode PackageClauseOnly
		if pkgAlias == "" {
			utils.Logger.Debug("Reading from build", "path", fullPath, "srcPath", srcDir, "gopath", build.Default.GOPATH)
			pkg, err := build.Import(fullPath, srcDir, 0)
			if err != nil {
				// We expect this to happen for apps using reverse routing (since we
				// have not yet generated the routes).  Don't log that.
				if !strings.HasSuffix(fullPath, "/app/routes") {
					utils.Logger.Error("Could not find import:", "path", fullPath, "srcPath", srcDir, "error", err)
				}
				continue
			} else {
				utils.Logger.Debug("Found package in dir", "dir", pkg.Dir, "name", pkg.ImportPath)
			}
			pkgAlias = pkg.Name
		}

		imports[pkgAlias] = fullPath
	}
}
1354823
func (b *Builder) importPackage(dir string, userRequested bool) (*tc.Package, error) {
	klog.V(5).Infof("importPackage %s", dir)
	var pkgPath = importPathString(dir)

	// Get the canonical path if we can.
	if buildPkg := b.buildPackages[dir]; buildPkg != nil {
		canonicalPackage := canonicalizeImportPath(buildPkg.ImportPath)
		klog.V(5).Infof("importPackage %s, canonical path is %s", dir, canonicalPackage)
		pkgPath = canonicalPackage
	}

	// If we have not seen this before, process it now.
	ignoreError := false
	if _, found := b.parsed[pkgPath]; !found {
		// Ignore errors in paths that we're importing solely because
		// they're referenced by other packages.
		ignoreError = true

		// Add it.
		if err := b.addDir(dir, userRequested); err != nil {
			return nil, err
		}

		// Get the canonical path now that it has been added.
		if buildPkg := b.buildPackages[dir]; buildPkg != nil {
			canonicalPackage := canonicalizeImportPath(buildPkg.ImportPath)
			klog.V(5).Infof("importPackage %s, canonical path is %s", dir, canonicalPackage)
			pkgPath = canonicalPackage
		}
	}

	// If it was previously known, just check that the user-requestedness hasn't
	// changed.
	b.userRequested[pkgPath] = userRequested || b.userRequested[pkgPath]

	// Run the type checker.  We may end up doing this to pkgs that are already
	// done, or are in the queue to be done later, but it will short-circuit,
	// and we can't miss pkgs that are only depended on.
	pkg, err := b.typeCheckPackage(pkgPath)
	if err != nil {
		switch {
		case ignoreError && pkg != nil:
			klog.V(2).Infof("type checking encountered some issues in %q, but ignoring.\n", pkgPath)
		case !ignoreError && pkg != nil:
			klog.V(2).Infof("type checking encountered some errors in %q\n", pkgPath)
			return nil, err
		default:
			return nil, err
		}
	}

	return pkg, nil
}
1302635
func (pkg *Package) Imports() map[string]bool {
	im := make(map[string]bool)
	for _, intf := range pkg.Interfaces {
		intf.addImports(im)
	}
	return im
}
423181
func (ctx *Context) addFileImports(pathname, gopath string) (*Package, error) {
	dir, filenameExt := filepath.Split(pathname)
	importPath := pathos.FileTrimPrefix(dir, gopath)
	importPath = pathos.SlashToImportPath(importPath)
	importPath = strings.Trim(importPath, "/")

	if !strings.HasSuffix(pathname, ".go") {
		return nil, nil
	}
	// No need to add the same file more than once.
	for _, pkg := range ctx.Package {
		if !pathos.FileStringEquals(pkg.Dir, dir) {
			continue
		}
		for _, f := range pkg.Files {
			if pathos.FileStringEquals(f.Path, pathname) {
				return nil, nil
			}
		}
		for _, f := range pkg.ignoreFile {
			if pathos.FileStringEquals(f, filenameExt) {
				return nil, nil
			}
		}
	}
	// Ignore error here and continue on best effort.
	f, _ := parser.ParseFile(token.NewFileSet(), pathname, nil, parser.ImportsOnly|parser.ParseComments)
	if f == nil {
		return nil, nil
	}
	pkgNameNormalized := strings.TrimSuffix(f.Name.Name, "_test")

	// Files with package name "documentation" should be ignored, per go build tool.
	if pkgNameNormalized == "documentation" {
		return nil, nil
	}

	tags, _, err := ctx.getFileTags(pathname, f)
	if err != nil {
		return nil, err
	}
	// If file has "// +build ignore", can mix package main with normal package.
	// For now, just ignore ignored packages.
	if tags.IgnoreItem() {
		return nil, nil
	}

	pkg, found := ctx.Package[importPath]
	if !found {
		status := Status{
			Type:     TypePackage,
			Location: LocationUnknown,
			Presence: PresenceFound,
		}
		if pkgNameNormalized == "main" {
			status.Type = TypeProgram
		}
		pkg = ctx.setPackage(dir, importPath, importPath, gopath, status)
		ctx.Package[importPath] = pkg
	}
	if pkg.Status.Location != LocationLocal {
		if tags.IgnoreItem(ctx.ignoreTag...) {
			pkg.ignoreFile = append(pkg.ignoreFile, filenameExt)
			return pkg, nil
		}
		// package excluded if non-local && same name or sub-package of an excluded package
		for _, exclude := range ctx.excludePackage {
			if importPath == exclude || strings.HasPrefix(importPath, exclude+"/") {
				pkg.Status.Presence = PresenceExcluded
			}
		}
	}
	pf := &File{
		Package: pkg,
		Path:    pathname,
		Imports: make([]string, len(f.Imports)),
	}
	pkg.Files = append(pkg.Files, pf)
	for i := range f.Imports {
		imp := f.Imports[i].Path.Value
		imp, err = strconv.Unquote(imp)
		if err != nil {
			// Best effort only.
			continue
		}
		if strings.HasPrefix(imp, "./") {
			imp = path.Join(importPath, imp)
		}
		pf.Imports[i] = imp
		if pkg.Status.Presence != PresenceExcluded { // do not add package imports if it was explicitly excluded
			_, err = ctx.addSingleImport(pkg.Dir, imp, pkg.IncludeTree)
			if err != nil {
				return pkg, err
			}
		}
	}

	// Record any import comment for file.
	var ic *ast.Comment
	if f.Name != nil {
		pos := f.Name.Pos()
	big:
		// Find the next comment after the package name.
		for _, cblock := range f.Comments {
			for _, c := range cblock.List {
				if c.Pos() > pos {
					ic = c
					break big
				}
			}
		}
	}
	if ic != nil {
		// If it starts with the import text, assume it is the import comment.
		if index := strings.Index(ic.Text, " import "); index > 0 && index < 5 {
			q := strings.TrimSpace(ic.Text[index+len(" import "):])
			pf.ImportComment, err = strconv.Unquote(q)
			if err != nil {
				pf.ImportComment = q
			}
		}
	}

	return pkg, nil
}
776836
func vendorlessImportPath(ipath string, currentPackagePath string) (string, bool) {
	split := strings.Split(ipath, "vendor/")
	// no vendor in path
	if len(split) == 1 {
		return ipath, true
	}
	// this import path does not belong to the current package
	if currentPackagePath != "" && !strings.Contains(currentPackagePath, split[0]) {
		return "", false
	}
	// Devendorize for use in import statement.
	if i := strings.LastIndex(ipath, "/vendor/"); i >= 0 {
		return ipath[i+len("/vendor/"):], true
	}
	if strings.HasPrefix(ipath, "vendor/") {
		return ipath[len("vendor/"):], true
	}
	return ipath, true
}
488147
func (g Generator) Imports() map[string]string {
	imports := imports.New(g.Package())
	for _, m := range g.Methods() {
		s := m.signature()
		imports.AddImportsFrom(s.Params())
		imports.AddImportsFrom(s.Results())
	}
	return imports.Imports()
}
932178
func (importer *MemoryImporter) Import(importedFrom, importedPath string) (contents Contents, foundAt string, err error) {
	if content, ok := importer.Data[importedPath]; ok {
		return content, importedPath, nil
	}
	return Contents{}, "", fmt.Errorf("import not available %v", importedPath)
}
115311
func (cmd *ImportCommand) importPath(ctx context.Context, fieldType string, useColumnKeys, useRowKeys bool, path string) error {
	// If fieldType is `int`, treat the import data as values to be range-encoded.
	if fieldType == pilosa.FieldTypeInt {
		return cmd.bufferValues(ctx, useColumnKeys, path)
	}
	return cmd.bufferBits(ctx, useColumnKeys, useRowKeys, path)
}
1191092
func (bi *blockImporter) Import() chan *importResults {
	// Start up the read and process handling goroutines.  This setup allows
	// blocks to be read from disk in parallel while being processed.
	bi.wg.Add(2)
	go bi.readHandler()
	go bi.processHandler()

	// Wait for the import to finish in a separate goroutine and signal
	// the status handler when done.
	go func() {
		bi.wg.Wait()
		bi.doneChan <- true
	}()

	// Start the status handler and return the result channel that it will
	// send the results on when the import is done.
	resultChan := make(chan *importResults)
	go bi.statusHandler(resultChan)
	return resultChan
}
186265
func DefineImport(e *vm.Env) {
	e.Define("import", func(source string) *vm.Env {
		methods, ok := Packages[source]
		if !ok {
			panic(fmt.Sprintf("package '%s' not found", source))
		}
		var err error
		pack := e.NewPackage(source)
		for methodName, methodValue := range methods {
			err = pack.Define(methodName, methodValue)
			if err != nil {
				panic(fmt.Sprintf("import Define error: %v", err))
			}
		}
		types, ok := PackageTypes[source]
		if ok {
			for typeName, typeValue := range types {
				err = pack.DefineType(typeName, typeValue)
				if err != nil {
					panic(fmt.Sprintf("import DefineType error: %v", err))
				}
			}
		}
		return pack
	})
}
587374
func getAllDeps(importPath string, cmds []string) []string {
	subpackagePrefix := importPath + "/"

	var depsSlice []string
	for _, useAllFiles := range []bool{false, true} {
		printLoadingError := func(path string, err error) {
			if err != nil && !useAllFiles {
				// Lots of errors because of UseAllFiles.
				log.Printf("error loading package %s: %s", path, err)
			}
		}

		deps := map[string]struct{}{}
		roots := map[string]struct{}{
			importPath: {},
		}

		// Add the command packages. Note that external command packages are
		// considered dependencies.
		for _, pkg := range cmds {
			roots[pkg] = struct{}{}

			if !strings.HasPrefix(pkg, subpackagePrefix) {
				deps[pkg] = struct{}{}
			}
		}

		buildContext := build.Default
		buildContext.CgoEnabled = true
		buildContext.UseAllFiles = useAllFiles

		// Add the subpackages.
		for path := range buildutil.ExpandPatterns(&buildContext, []string{subpackagePrefix + "..."}) {
			_, err := buildContext.Import(path, "", 0)
			if _, ok := err.(*build.NoGoError); ok {
				continue
			}
			printLoadingError(path, err)
			roots[path] = struct{}{}
		}

		var addTransitiveClosure func(string)
		addTransitiveClosure = func(path string) {
			pkg, err := buildContext.Import(path, "", 0)
			printLoadingError(path, err)

			importPaths := append([]string(nil), pkg.Imports...)
			if _, ok := roots[path]; ok {
				importPaths = append(importPaths, pkg.TestImports...)
				importPaths = append(importPaths, pkg.XTestImports...)
			}

			for _, path := range importPaths {
				if path == "C" {
					continue // "C" is fake
				}

				// Resolve the import path relative to the importing package.
				if bp2, _ := buildContext.Import(path, pkg.Dir, build.FindOnly); bp2 != nil {
					path = bp2.ImportPath
				}

				// Exclude our roots. Note that commands are special-cased above.
				if _, ok := roots[path]; ok {
					continue
				}
				slash := strings.IndexByte(path, '/')
				stdLib := slash == -1 || strings.IndexByte(path[:slash], '.') == -1
				// Exclude the standard library.
				if stdLib {
					continue
				}
				if _, ok := deps[path]; !ok {
					deps[path] = struct{}{}
					addTransitiveClosure(path)
				}
			}
		}

		for path := range roots {
			addTransitiveClosure(path)
		}
		addTransitiveClosure(importPath)

		depsSlice = append(depsSlice, setToSlice(deps)...)
	}

	return depsSlice
}
925622
func (s *LDBStore) Import(in io.Reader) (int64, error) {
	tr := tar.NewReader(in)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	countC := make(chan int64)
	errC := make(chan error)
	var count int64
	go func() {
		for {
			hdr, err := tr.Next()
			if err == io.EOF {
				break
			} else if err != nil {
				select {
				case errC <- err:
				case <-ctx.Done():
				}
			}

			if len(hdr.Name) != 64 {
				log.Warn("ignoring non-chunk file", "name", hdr.Name)
				continue
			}

			keybytes, err := hex.DecodeString(hdr.Name)
			if err != nil {
				log.Warn("ignoring invalid chunk file", "name", hdr.Name, "err", err)
				continue
			}

			data, err := ioutil.ReadAll(tr)
			if err != nil {
				select {
				case errC <- err:
				case <-ctx.Done():
				}
			}
			key := Address(keybytes)
			chunk := NewChunk(key, data[32:])

			go func() {
				select {
				case errC <- s.Put(ctx, chunk):
				case <-ctx.Done():
				}
			}()

			count++
		}
		countC <- count
	}()

	// wait for all chunks to be stored
	i := int64(0)
	var total int64
	for {
		select {
		case err := <-errC:
			if err != nil {
				return count, err
			}
			i++
		case total = <-countC:
		case <-ctx.Done():
			return i, ctx.Err()
		}
		if total > 0 && i == total {
			return total, nil
		}
	}
}
1274868
func (imp *Importer) Import(src video.Source, subdir string, clips []*video.Clip) *Status {
	updates := imp.init(clips)
	defer func() {
		imp.m.Lock()
		defer imp.m.Unlock()
		imp.updates = nil
	}()
	for _, clip := range clips {
		result := Result{
			Clip:  clip,
			Start: time.Now(),
		}
		var clipWritten int64
		for _, file := range clip.Paths {
			var fileWritten int64
			fileWritten, result.Error = imp.copy(src, subdir, file, updates)
			clipWritten += fileWritten
			if result.Error != nil {
				imp.status.BytesTotal -= clip.TotalSize - clipWritten
				break
			}
		}
		result.End = time.Now()
		imp.ncopied += clipWritten
		imp.elapsed += result.End.Sub(result.Start)
		imp.status.ETA = result.End.Add(estimateTime(imp.status.BytesTotal-imp.status.BytesCopied, imp.ncopied, imp.elapsed))
		imp.status.Pending = imp.status.Pending[1:]
		imp.status.Results = append(imp.status.Results, result)
		select {
		case updates <- imp.newStatus():
		default:
		}
	}
	imp.status.Active = false
	return imp.newStatus()
}
878391
func (b *Builder) addFile(pkgPath importPathString, path string, src []byte, userRequested bool) error {
	for _, p := range b.parsed[pkgPath] {
		if path == p.name {
			klog.V(5).Infof("addFile %s %s already parsed, skipping", pkgPath, path)
			return nil
		}
	}
	klog.V(6).Infof("addFile %s %s", pkgPath, path)
	p, err := parser.ParseFile(b.fset, path, src, parser.DeclarationErrors|parser.ParseComments)
	if err != nil {
		return err
	}

	// This is redundant with addDir, but some tests call AddFileForTest, which
	// call into here without calling addDir.
	b.userRequested[pkgPath] = userRequested || b.userRequested[pkgPath]

	b.parsed[pkgPath] = append(b.parsed[pkgPath], parsedFile{path, p})
	for _, c := range p.Comments {
		position := b.fset.Position(c.End())
		b.endLineToCommentGroup[fileLine{position.Filename, position.Line}] = c
	}

	// We have to get the packages from this specific file, in case the
	// user added individual files instead of entire directories.
	if b.importGraph[pkgPath] == nil {
		b.importGraph[pkgPath] = map[string]struct{}{}
	}
	for _, im := range p.Imports {
		importedPath := strings.Trim(im.Path.Value, `"`)
		b.importGraph[pkgPath][importedPath] = struct{}{}
	}
	return nil
}
831068
func importSorted(imports map[string]string) []Import {
	names := make([]string, 0, len(imports))
	for n := range imports {
		names = append(names, n)
	}
	sort.Strings(names)
	result := make([]Import, len(names))
	for i, n := range names {
		result[i] = Import{n, imports[n]}
	}
	return result
}