// Extract extracts a tar file into disk
973223
func (r *tarReader) Extract(fileName string, noOverride bool) error {
	fileInfo, err := os.Lstat(fileName)
	if err != nil && !os.IsNotExist(err) {
		return err
	}

	// If the `fileName` already exists on disk and it is a file
	// we try to delete it in order to create a new one unless
	// `noOverride` is set to true
	if err == nil && !fileInfo.IsDir() {
		if noOverride {
			return nil
		}

		if err := os.Remove(fileName); err != nil {
			return err
		}
	}

	// header.Mode is in linux format, we have to convert it to os.FileMode
	// to be compatible to other platforms.
	headerInfo := r.header.FileInfo()

	switch r.header.Typeflag {
	case tar.TypeDir:
		if err := os.Mkdir(fileName, headerInfo.Mode()); err != nil && !os.IsExist(err) {
			return err
		}
	case tar.TypeReg, tar.TypeRegA:
		if err := createFile(fileName, headerInfo.Mode(), r.reader); err != nil {
			return err
		}
	case tar.TypeSymlink:
		if err := os.Symlink(r.header.Linkname, fileName); err != nil {
			return err
		}
	default:
		return fmt.Errorf("Unhandled tar header type %d", r.header.Typeflag)
	}

	return nil
}
772821
func (e *Extractor) Tar(ctx context.Context, body io.Reader, location string, rename Renamer) error {
	files := []file{}
	links := []link{}
	symlinks := []link{}

	// We make the first pass creating the directory structure, or we could end up
	// attempting to create a file where there's no folder
	tr := tar.NewReader(body)
	for {
		select {
		case <-ctx.Done():
			return errors.New("interrupted")
		default:
		}

		header, err := tr.Next()
		if err == io.EOF {
			break
		}

		if err != nil {
			return errors.Annotatef(err, "Read tar stream")
		}

		path := header.Name
		if rename != nil {
			path = rename(path)
		}

		if path == "" {
			continue
		}

		path = filepath.Join(location, path)
		info := header.FileInfo()

		switch header.Typeflag {
		case tar.TypeDir:
			if err := e.FS.MkdirAll(path, info.Mode()); err != nil {
				return errors.Annotatef(err, "Create directory %s", path)
			}
		case tar.TypeReg, tar.TypeRegA:
			var data bytes.Buffer
			if _, err := copyCancel(ctx, &data, tr); err != nil {
				return errors.Annotatef(err, "Read contents of file %s", path)
			}
			files = append(files, file{Path: path, Mode: info.Mode(), Data: data})
		case tar.TypeLink:
			name := header.Linkname
			if rename != nil {
				name = rename(name)
			}

			name = filepath.Join(location, name)
			links = append(links, link{Path: path, Name: name})
		case tar.TypeSymlink:
			symlinks = append(symlinks, link{Path: path, Name: header.Linkname})
		}
	}

	// Now we make another pass creating the files and links
	for i := range files {
		if err := e.copy(ctx, files[i].Path, files[i].Mode, &files[i].Data); err != nil {
			return errors.Annotatef(err, "Create file %s", files[i].Path)
		}
	}

	for i := range links {
		select {
		case <-ctx.Done():
			return errors.New("interrupted")
		default:
		}
		if err := e.FS.Link(links[i].Name, links[i].Path); err != nil {
			return errors.Annotatef(err, "Create link %s", links[i].Path)
		}
	}

	for i := range symlinks {
		select {
		case <-ctx.Done():
			return errors.New("interrupted")
		default:
		}
		if err := e.FS.Symlink(symlinks[i].Name, symlinks[i].Path); err != nil {
			return errors.Annotatef(err, "Create link %s", symlinks[i].Path)
		}
	}
	return nil
}
1032300
func extractFile(f *tar.Header, tr *tar.Reader, destPath string) error {
	filePath := path.Join(destPath, f.Name)
	os.MkdirAll(path.Dir(filePath), os.ModePerm)

	fw, err := os.Create(filePath)
	if err != nil {
		return err
	}
	defer fw.Close()

	if _, err = io.Copy(fw, tr); err != nil {
		return err
	}

	// Skip symbolic links.
	if f.FileInfo().Mode()&os.ModeSymlink != 0 {
		return nil
	}
	// Set back file information.
	if err = os.Chtimes(filePath, f.FileInfo().ModTime(), f.FileInfo().ModTime()); err != nil {
		return err
	}
	return os.Chmod(filePath, f.FileInfo().Mode())
}
114095
func extractFile(tr *tar.Reader, target string, hdr *tar.Header, overwrite bool, editor FilePermissionsEditor) error {
	p := filepath.Join(target, hdr.Name)
	fi := hdr.FileInfo()
	typ := hdr.Typeflag
	if overwrite {
		info, err := os.Lstat(p)
		switch {
		case os.IsNotExist(err):
		case err == nil:
			// If the old and new paths are both dirs do nothing or
			// RemoveAll will remove all dir's contents
			if !info.IsDir() || typ != tar.TypeDir {
				err := os.RemoveAll(p)
				if err != nil {
					return err
				}
			}
		default:
			return err
		}
	}

	// Create parent dir if it doesn't exist
	if err := os.MkdirAll(filepath.Dir(p), DEFAULT_DIR_MODE); err != nil {
		return err
	}
	switch {
	case typ == tar.TypeReg || typ == tar.TypeRegA:
		f, err := os.OpenFile(p, os.O_CREATE|os.O_RDWR, fi.Mode())
		if err != nil {
			return err
		}
		_, err = io.Copy(f, tr)
		if err != nil {
			f.Close()
			return err
		}
		f.Close()
	case typ == tar.TypeDir:
		if err := os.MkdirAll(p, fi.Mode()); err != nil {
			return err
		}
		dir, err := os.Open(p)
		if err != nil {
			return err
		}
		if err := dir.Chmod(fi.Mode()); err != nil {
			dir.Close()
			return err
		}
		dir.Close()
	case typ == tar.TypeLink:
		dest := filepath.Join(target, hdr.Linkname)
		if err := os.Link(dest, p); err != nil {
			return err
		}
	case typ == tar.TypeSymlink:
		if err := os.Symlink(hdr.Linkname, p); err != nil {
			return err
		}
	case typ == tar.TypeChar:
		dev := device.Makedev(uint(hdr.Devmajor), uint(hdr.Devminor))
		mode := uint32(fi.Mode()) | syscall.S_IFCHR
		if err := syscall.Mknod(p, mode, int(dev)); err != nil {
			return err
		}
	case typ == tar.TypeBlock:
		dev := device.Makedev(uint(hdr.Devmajor), uint(hdr.Devminor))
		mode := uint32(fi.Mode()) | syscall.S_IFBLK
		if err := syscall.Mknod(p, mode, int(dev)); err != nil {
			return err
		}
	case typ == tar.TypeFifo:
		if err := syscall.Mkfifo(p, uint32(fi.Mode())); err != nil {
			return err
		}
	case typ == tar.TypeXGlobalHeader:
		return nil
	// TODO(jonboulle): implement other modes
	default:
		return fmt.Errorf("unsupported type: %v", typ)
	}

	if editor != nil {
		if err := editor(p, hdr.Uid, hdr.Gid, hdr.Typeflag, fi, hdr.Xattrs); err != nil {
			return err
		}
	}

	// Restore entry atime and mtime.
	// Use special function LUtimesNano not available on go's syscall package because we
	// have to restore symlink's times and not the referenced file times.
	ts := HdrToTimespec(hdr)
	if hdr.Typeflag != tar.TypeSymlink {
		if err := syscall.UtimesNano(p, ts); err != nil {
			return err
		}
	} else {
		if err := fileutil.LUtimesNano(p, ts); err != nil && err != ErrNotSupportedPlatform {
			return err
		}
	}

	return nil
}
998184
func Extract(source, target, destination string) error {
	eIface, err := ByExtension(source)
	if err != nil {
		return err
	}
	e, ok := eIface.(Extractor)
	if !ok {
		return fmt.Errorf("format specified by source filename is not an extractor format: %s (%T)", source, eIface)
	}
	return e.Extract(source, target, destination)
}
966253
func Extract(f io.ReadSeeker) (string, error) {
	fileMode := os.FileMode(0755)

	tr, err := specaci.NewCompressedTarReader(f)
	if err != nil {
		return "", err
	}
	defer tr.Close()

	// Extract archive to temporary directory
	dir, err := ioutil.TempDir("", "")
	if err != nil {
		return "", err
	}
	aciLogger.WithField("directory", dir).Debugf(
		"Extracting archive to temporary directory")
	for {
		hdr, err := tr.Reader.Next()
		if err == io.EOF {
			break
		}
		if err != nil {
			return "", fmt.Errorf("%v\n%v", ErrNext, err)
		}
		file := filepath.Join(dir, hdr.Name)

		switch hdr.Typeflag {
		case tar.TypeReg:
			w, err := os.Create(file)
			if err != nil {
				return "", fmt.Errorf("%v: %v\n%v", ErrCreatingFile, file, err)
			}
			_, err = io.Copy(w, tr)
			if err != nil {
				w.Close()
				return "", fmt.Errorf("%v: %v\n%v", ErrCopyingFile, file, err)
			}
			w.Close()
			err = os.Chmod(file, fileMode)
			if err != nil {
				return "", fmt.Errorf("%v: %v\n%v", ErrChmod, file, err)
			}
		case tar.TypeDir:
			err = os.MkdirAll(file, fileMode)
			if err != nil {
				return "", fmt.Errorf("%v: %v\n%v", ErrMkdirAll, file, err)
			}
		case tar.TypeSymlink:
			err := os.Symlink(
				filepath.Join(dir, filepath.Dir(hdr.Name), hdr.Linkname),
				filepath.Join(dir, hdr.Name))
			if err != nil {
				return "", fmt.Errorf("%v: name: %v Linkname: %v \n%v",
					ErrCreatingSymLink, hdr.Name, hdr.Linkname, err)
			}
		default:
			return "", fmt.Errorf("%v (type: %d): %v", ErrUntar, hdr.Typeflag, hdr.Name)
		}
	}
	return dir, nil
}
700343
func ExtractZip(zipfile, destDir string) error {
	r, err := zip.OpenReader(zipfile)
	if err != nil {
		return err
	}
	defer r.Close()

	for _, f := range r.File {
		path := filepath.Join(destDir, filepath.Clean(f.Name))

		rc, err := f.Open()
		if err != nil {
			return err
		}

		if f.FileInfo().IsDir() {
			err = os.MkdirAll(path, f.Mode())
		} else {
			err = writeToFile(rc, path, f.Mode())
		}

		rc.Close()
		if err != nil {
			return err
		}
	}

	return nil
}
695991
func (l *SchemaList) Extract(v interface{}) error {
	switch val := v.(type) {
	case []interface{}:
		*l = make([]*Schema, len(val))
		var s *Schema
		for i, d := range val {
			m, ok := d.(map[string]interface{})
			if !ok {
				return errors.Wrap(
					errInvalidType("map[string]interface{}", d),
					"failed to extract schema list",
				)
			}
			if err := extractSingleSchema(&s, m); err != nil {
				return errors.Wrap(err, "failed to extract schema list")
			}
			(*l)[i] = s
		}
		return nil
	case map[string]interface{}:
		var s *Schema
		if err := extractSingleSchema(&s, val); err != nil {
			return errors.Wrap(err, "failed to extract schema list")
		}
		*l = []*Schema{s}
		return nil
	default:
		return errors.Wrap(
			errInvalidType("[]*Schema or *Schema", v),
			"failed to extract schema list",
		)
	}
}
1022297
func (mr *MockExtractorMockRecorder) Extract(arg0 interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Extract", reflect.TypeOf((*MockExtractor)(nil).Extract), arg0)
}
1171423
func extract(buf []byte, name string) []byte {
	extractRE := regexp.MustCompile(`\s+` + name + `.+?{`)
	buf = buf[extractRE.FindIndex(buf)[0]:]
	return buf[:endRE.FindIndex(buf)[1]]
}
103381
func extract(str string) (name string, num int, rest string, ok bool) {
	if len(str) < 2 || str[0] != '$' {
		return
	}
	brace := false
	if str[1] == '{' {
		brace = true
		str = str[2:]
	} else {
		str = str[1:]
	}
	i := 0
	for i < len(str) {
		rune, size := utf8.DecodeRuneInString(str[i:])
		if !unicode.IsLetter(rune) && !unicode.IsDigit(rune) && rune != '_' {
			break
		}
		i += size
	}
	if i == 0 {
		// empty name is not okay
		return
	}
	name = str[:i]
	if brace {
		if i >= len(str) || str[i] != '}' {
			// missing closing brace
			return
		}
		i++
	}

	// Parse number.
	num = 0
	for i := 0; i < len(name); i++ {
		if name[i] < '0' || '9' < name[i] || num >= 1e8 {
			num = -1
			break
		}
		num = num*10 + int(name[i]) - '0'
	}
	// Disallow leading zeros.
	if name[0] == '0' && len(name) > 1 {
		num = -1
	}

	rest = str[i:]
	ok = true
	return
}
1172784
func ExtractQuery(opts ...interface{}) *opt.QueryOption {
	for _, o := range opts {
		if v, ok := o.(*opt.QueryOption); ok {
			return v
		}
	}
	return nil
}
522711
func (i *Image) Extract(top, left, width, height int) ([]byte, error) {
	options := Options{
		Top:        top,
		Left:       left,
		AreaWidth:  width,
		AreaHeight: height,
	}

	if top == 0 && left == 0 {
		options.Top = -1
	}

	return i.Process(options)
}
358410
func (z *ZipArchive) ExtractTo(destPath string, entries ...string) (err error) {
	return z.ExtractToFunc(destPath, defaultExtractFunc, entries...)
}
811913
func extractTar(r io.Reader, dir string) error {
	first := true // true if we are on the first entry of tarball
	tr := tar.NewReader(r)
	for {
		hdr, err := tr.Next()
		if err == io.EOF {
			// end of tar archive
			break
		}
		if err != nil {
			return err
		}

		// Check if the same kite version is installed before
		if first {
			first = false
			kiteName := strings.TrimSuffix(hdr.Name, ".kite/")

			installed, err := isInstalled(kiteName)
			if err != nil {
				return err
			}

			if installed {
				return fmt.Errorf("Already installed: %s", kiteName)
			}
		}

		path := filepath.Join(dir, hdr.Name)

		if hdr.FileInfo().IsDir() {
			os.MkdirAll(path, 0700)
		} else {
			mode := 0600
			if isBinaryFile(hdr.Name) {
				mode = 0700
			}

			f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(mode))
			if err != nil {
				return err
			}

			if _, err := io.Copy(f, tr); err != nil {
				return err
			}
		}
	}
	return nil
}
1215601
func (s *Schema) Extract(m map[string]interface{}) error {
	if pdebug.Enabled {
		g := pdebug.IPrintf("START Schema.Extract")
		defer g.IRelease("END Schema.Extract")
	}

	var err error

	if err = extractString(&s.ID, m, "id"); err != nil {
		return errors.Wrapf(err, "failed to extract 'id'")
	}

	if err = extractString(&s.Title, m, "title"); err != nil {
		return errors.Wrap(err, "failed to extract 'title'")
	}

	if err = extractString(&s.Description, m, "description"); err != nil {
		return errors.Wrap(err, "failed to extract 'description'")
	}

	if err = extractStringList(&s.Required, m, "required"); err != nil {
		return errors.Wrap(err, "failed to extract 'required'")
	}

	if err = extractJSPointer(&s.SchemaRef, m, "$schema"); err != nil {
		return errors.Wrap(err, "failed to extract '$schema'")
	}

	if err = extractJSPointer(&s.Reference, m, "$ref"); err != nil {
		return errors.Wrap(err, "failed to extract '$ref'")
	}

	if err = extractFormat(&s.Format, m, "format"); err != nil {
		return errors.Wrap(err, "failed to extract 'format'")
	}

	if err = extractInterfaceList(&s.Enum, m, "enum"); err != nil {
		return errors.Wrap(err, "failed to extract 'enum'")
	}

	if err = extractInterface(&s.Default, m, "default"); err != nil {
		return errors.Wrap(err, "failed to extract 'default'")
	}

	if err = extractType(&s.Type, m, "type"); err != nil {
		return errors.Wrap(err, "failed to extract 'type'")
	}

	if s.Definitions, err = extractSchemaMap(m, "definitions"); err != nil {
		return errors.Wrap(err, "failed to extract 'definitions'")
	}

	if err = extractItems(&s.Items, m, "items"); err != nil {
		return errors.Wrap(err, "failed to extract 'items'")
	}

	if err = extractRegexp(&s.Pattern, m, "pattern"); err != nil {
		return errors.Wrap(err, "failed to extract 'patterns'")
	}

	if extractInt(&s.MinLength, m, "minLength"); err != nil {
		return errors.Wrap(err, "failed to extract 'minLength'")
	}

	if extractInt(&s.MaxLength, m, "maxLength"); err != nil {
		return errors.Wrap(err, "failed to extract 'maxLength'")
	}

	if extractInt(&s.MinItems, m, "minItems"); err != nil {
		return errors.Wrap(err, "failed to extract 'minItems'")
	}

	if extractInt(&s.MaxItems, m, "maxItems"); err != nil {
		return errors.Wrap(err, "failed to extract 'maxItems'")
	}

	if err = extractBool(&s.UniqueItems, m, "uniqueItems", false); err != nil {
		return errors.Wrap(err, "failed to extract 'uniqueItems'")
	}

	if err = extractInt(&s.MaxProperties, m, "maxProperties"); err != nil {
		return errors.Wrap(err, "failed to extract 'maxProperties'")
	}

	if err = extractInt(&s.MinProperties, m, "minProperties"); err != nil {
		return errors.Wrap(err, "failed to extract 'minProperties'")
	}

	if err = extractNumber(&s.Minimum, m, "minimum"); err != nil {
		return errors.Wrap(err, "failed to extract 'minimum'")
	}

	if err = extractBool(&s.ExclusiveMinimum, m, "exclusiveMinimum", false); err != nil {
		return errors.Wrap(err, "failed to extract 'exclusiveMinimum'")
	}

	if err = extractNumber(&s.Maximum, m, "maximum"); err != nil {
		return errors.Wrap(err, "failed to extract 'maximum'")
	}

	if err = extractBool(&s.ExclusiveMaximum, m, "exclusiveMaximum", false); err != nil {
		return errors.Wrap(err, "failed to extract 'exclusiveMaximum'")
	}

	if err = extractNumber(&s.MultipleOf, m, "multipleOf"); err != nil {
		return errors.Wrap(err, "failed to extract 'multipleOf'")
	}

	if s.Properties, err = extractSchemaMap(m, "properties"); err != nil {
		return errors.Wrap(err, "failed to extract 'properties'")
	}

	if err = extractDependecies(&s.Dependencies, m, "dependencies"); err != nil {
		return errors.Wrap(err, "failed to extract 'dependencies'")
	}

	if _, ok := m["additionalItems"]; !ok {
		// doesn't exist. it's an empty schema
		s.AdditionalItems = &AdditionalItems{}
	} else {
		var b Bool
		if err = extractBool(&b, m, "additionalItems", true); err == nil {
			if b.Bool() {
				s.AdditionalItems = &AdditionalItems{}
			}
		} else {
			// Oh, it's not a boolean?
			var apSchema *Schema
			if err = extractSchema(&apSchema, m, "additionalItems"); err != nil {
				return errors.Wrap(err, "failed to extract 'additionalItems'")
			}
			s.AdditionalItems = &AdditionalItems{apSchema}
		}
	}

	if _, ok := m["additionalProperties"]; !ok {
		// doesn't exist. it's an empty schema
		s.AdditionalProperties = &AdditionalProperties{}
	} else {
		var b Bool
		if err = extractBool(&b, m, "additionalProperties", true); err == nil {
			if b.Bool() {
				s.AdditionalProperties = &AdditionalProperties{}
			}
		} else {
			// Oh, it's not a boolean?
			var apSchema *Schema
			if err = extractSchema(&apSchema, m, "additionalProperties"); err != nil {
				return errors.Wrap(err, "failed to extract 'additionalProperties'")
			}
			s.AdditionalProperties = &AdditionalProperties{apSchema}
		}
	}

	if s.PatternProperties, err = extractRegexpToSchemaMap(m, "patternProperties"); err != nil {
		return errors.Wrap(err, "failed to extract 'patternProperties'")
	}

	if err = s.AllOf.extractIfPresent(m, "allOf"); err != nil {
		return errors.Wrap(err, "failed to extract 'allOf'")
	}

	if err = s.AnyOf.extractIfPresent(m, "anyOf"); err != nil {
		return errors.Wrap(err, "failed to extract 'anyOf'")
	}

	if err = s.OneOf.extractIfPresent(m, "oneOf"); err != nil {
		return errors.Wrap(err, "failed to extract 'oneOf'")
	}

	if err = extractSchema(&s.Not, m, "not"); err != nil {
		return errors.Wrap(err, "failed to extract 'not'")
	}

	s.applyParentSchema()

	s.Extras = make(map[string]interface{})
	for k, v := range m {
		switch k {
		case "id", "title", "description", "required", "$schema", "$ref", "format", "enum", "default", "type", "definitions", "items", "pattern", "minLength", "maxLength", "minItems", "maxItems", "uniqueItems", "maxProperties", "minProperties", "minimum", "exclusiveMinimum", "maximum", "exclusiveMaximum", "multipleOf", "properties", "dependencies", "additionalItems", "additionalProperties", "patternProperties", "allOf", "anyOf", "oneOf", "not":
			continue
		}
		if pdebug.Enabled {
			pdebug.Printf("Extracting extra field '%s'", k)
		}
		s.Extras[k] = v
	}

	if pdebug.Enabled {
		pdebug.Printf("Successfully extracted schema")
	}

	return nil
}
3330
func Extract(reader io.Reader, dest string) error {
	tarReader := tar.NewReader(reader)

	for {
		header, err := tarReader.Next()

		if err == io.EOF {
			break
		}

		if err != nil {
			return err
		}

		if header.Name == "." {
			continue
		}

		err = extract(tarReader, header, dest)
		if err != nil {
			return err
		}
	}

	return nil
}