// Extract expands the ACI file to a temporary directory, returning
// the directory path where the ACI was expanded or an error
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
}
1055104
func (tz *TzArchive) ExtractTo(destPath string, entries ...string) (err error) {
	return tz.ExtractToFunc(destPath, defaultExtractFunc, entries...)
}
470380
func (o *ExtractOptions) extractCommand(command string) error {
	// Available targets is treated as a GA API and may not be changed without backwards
	// compatibility of at least N-2 releases.
	availableTargets := []extractTarget{
		{
			OS:      "darwin",
			Command: "oc",
			Mapping: extract.Mapping{Image: "cli-artifacts", From: "usr/share/openshift/mac/oc"},

			LinkTo:        []string{"kubectl"},
			Readme:        readmeCLIUnix,
			ArchiveFormat: "openshift-client-mac-%s.tar.gz",
		},
		{
			OS:      "linux",
			Command: "oc",
			Mapping: extract.Mapping{Image: "cli", From: "usr/bin/oc"},

			LinkTo:        []string{"kubectl"},
			Readme:        readmeCLIUnix,
			ArchiveFormat: "openshift-client-linux-%s.tar.gz",
		},
		{
			OS:      "windows",
			Command: "oc",
			Mapping: extract.Mapping{Image: "cli-artifacts", From: "usr/share/openshift/windows/oc.exe"},

			Readme:        readmeCLIWindows,
			ArchiveFormat: "openshift-client-windows-%s.zip",
			AsZip:         true,
		},
		{
			OS:      "darwin",
			Command: "openshift-install",
			Mapping: extract.Mapping{Image: "installer-artifacts", From: "usr/share/openshift/mac/openshift-install"},

			Readme:             readmeInstallUnix,
			InjectReleaseImage: true,
			ArchiveFormat:      "openshift-install-mac-%s.tar.gz",
		},
		{
			OS:      "linux",
			Command: "openshift-install",
			Mapping: extract.Mapping{Image: "installer", From: "usr/bin/openshift-install"},

			Readme:             readmeInstallUnix,
			InjectReleaseImage: true,
			ArchiveFormat:      "openshift-install-linux-%s.tar.gz",
		},
	}

	currentOS := runtime.GOOS
	if len(o.CommandOperatingSystem) > 0 {
		currentOS = o.CommandOperatingSystem
	}
	if currentOS == "mac" {
		currentOS = "darwin"
	}

	// select the subset of targets based on command line input
	var willArchive bool
	var targets []extractTarget
	if len(command) > 0 {
		hasCommand := false
		for _, target := range availableTargets {
			if target.Command != command {
				continue
			}
			hasCommand = true
			if target.OS == currentOS || currentOS == "*" {
				targets = []extractTarget{target}
				break
			}
		}
		if len(targets) == 0 {
			if hasCommand {
				return fmt.Errorf("command %q does not support the operating system %q", o.Command, currentOS)
			}
			return fmt.Errorf("the supported commands are 'oc' and 'openshift-install'")
		}
	} else {
		willArchive = true
		targets = availableTargets
		for i := range targets {
			targets[i].AsArchive = true
			targets[i].AsZip = targets[i].OS == "windows"
		}
	}

	var hashFn = sha256.New
	var signer *openpgp.Entity
	if willArchive && len(o.SigningKey) > 0 {
		key, err := ioutil.ReadFile(o.SigningKey)
		if err != nil {
			return err
		}
		keyring, err := openpgp.ReadArmoredKeyRing(bytes.NewBuffer(key))
		if err != nil {
			return err
		}
		for _, key := range keyring {
			if !key.PrivateKey.CanSign() {
				continue
			}
			fmt.Fprintf(o.Out, "Enter password for private key: ")
			password, err := terminal.ReadPassword(int(syscall.Stdin))
			fmt.Fprintln(o.Out)
			if err != nil {
				return err
			}
			if err := key.PrivateKey.Decrypt(password); err != nil {
				return fmt.Errorf("unable to decrypt signing key: %v", err)
			}
			for i, subkey := range key.Subkeys {
				if err := subkey.PrivateKey.Decrypt(password); err != nil {
					return fmt.Errorf("unable to decrypt signing subkey %d: %v", i, err)
				}
			}
			signer = key
			break
		}
		if signer == nil {
			return fmt.Errorf("no private key exists in %s capable of signing the output", o.SigningKey)
		}
	}

	// load the release image
	dir := o.Directory
	infoOptions := NewInfoOptions(o.IOStreams)
	release, err := infoOptions.LoadReleaseInfo(o.From, false)
	if err != nil {
		return err
	}
	releaseName := release.PreferredName()
	refExact := release.ImageRef
	refExact.Tag = ""
	refExact.ID = release.Digest.String()
	exactReleaseImage := refExact.String()

	// resolve target image references to their pull specs
	missing := sets.NewString()
	var validTargets []extractTarget
	for _, target := range targets {
		if currentOS != "*" && target.OS != currentOS {
			klog.V(2).Infof("Skipping %s, does not match current OS %s", target.ArchiveFormat, target.OS)
			continue
		}
		spec, err := findImageSpec(release.References, target.Mapping.Image, o.From)
		if err != nil {
			missing.Insert(target.Mapping.Image)
			continue
		}
		klog.V(2).Infof("Will extract %s from %s", target.Mapping.From, spec)
		ref, err := imagereference.Parse(spec)
		if err != nil {
			return err
		}
		target.Mapping.Image = spec
		target.Mapping.ImageRef = ref
		if target.AsArchive {
			willArchive = true
			target.Mapping.Name = fmt.Sprintf(target.ArchiveFormat, releaseName)
			target.Mapping.To = filepath.Join(dir, target.Mapping.Name)
		} else {
			target.Mapping.To = filepath.Join(dir, filepath.Base(target.Mapping.From))
			target.Mapping.Name = fmt.Sprintf("%s-%s", target.OS, target.Command)
		}
		validTargets = append(validTargets, target)
	}

	if len(validTargets) == 0 {
		if len(missing) == 1 {
			return fmt.Errorf("the image %q containing the desired command is not available", missing.List()[0])
		}
		return fmt.Errorf("some required images are missing: %s", strings.Join(missing.List(), ", "))
	}
	if len(missing) > 0 {
		fmt.Fprintf(o.ErrOut, "warning: Some commands can not be extracted due to missing images: %s\n", strings.Join(missing.List(), ", "))
	}

	// will extract in parallel
	opts := extract.NewOptions(genericclioptions.IOStreams{Out: o.Out, ErrOut: o.ErrOut})
	opts.ParallelOptions = o.ParallelOptions
	opts.SecurityOptions = o.SecurityOptions
	opts.OnlyFiles = true

	// create the mapping lookup of the valid targets
	var extractLock sync.Mutex
	targetsByName := make(map[string]extractTarget)
	for _, target := range validTargets {
		targetsByName[target.Mapping.Name] = target
		opts.Mappings = append(opts.Mappings, target.Mapping)
	}
	hashByTargetName := make(map[string]string)

	// ensure to is a directory
	if err := os.MkdirAll(dir, 0777); err != nil {
		return err
	}

	// as each layer is extracted, take the output binary and write it to disk
	opts.TarEntryCallback = func(hdr *tar.Header, layer extract.LayerInfo, r io.Reader) (bool, error) {
		// ensure we don't process the same mapping twice due to programmer error
		target, ok := func() (extractTarget, bool) {
			extractLock.Lock()
			defer extractLock.Unlock()
			target, ok := targetsByName[layer.Mapping.Name]
			return target, ok
		}()
		if !ok {
			return false, fmt.Errorf("unable to find target with mapping name %s", layer.Mapping.Name)
		}

		// open the file
		f, err := os.OpenFile(layer.Mapping.To, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0755)
		if err != nil {
			return false, err
		}

		// if we need to write an archive, wrap the file appropriately to create a single
		// entry
		var w io.Writer = f

		bw := bufio.NewWriterSize(w, 16*1024)
		w = bw

		var hash hash.Hash
		closeFn := func() error { return nil }
		if target.AsArchive {
			text := strings.Replace(target.Readme, `\u0060`, "`", -1)
			hash = hashFn()
			w = io.MultiWriter(hash, w)
			if target.AsZip {
				klog.V(2).Infof("Writing %s as a ZIP archive %s", hdr.Name, layer.Mapping.To)
				zw := zip.NewWriter(w)

				if len(text) > 0 {
					text = strings.Replace(text, "\n", "\r\n", -1)
					zh := &zip.FileHeader{
						Method:             zip.Deflate,
						Name:               "README.md",
						UncompressedSize64: uint64(len(text)),
						Modified:           hdr.ModTime,
					}
					zh.SetMode(os.FileMode(0755))

					fw, err := zw.CreateHeader(zh)
					if err != nil {
						return false, err
					}
					if _, err := fmt.Fprintf(fw, text); err != nil {
						return false, err
					}
				}

				zh := &zip.FileHeader{
					Method:             zip.Deflate,
					Name:               hdr.Name,
					UncompressedSize64: uint64(hdr.Size),
					Modified:           hdr.ModTime,
				}
				zh.SetMode(os.FileMode(0755))

				fw, err := zw.CreateHeader(zh)
				if err != nil {
					return false, err
				}

				w = fw
				closeFn = func() error { return zw.Close() }

			} else {
				klog.V(2).Infof("Writing %s as a tar.gz archive %s", hdr.Name, layer.Mapping.To)
				gw, err := gzip.NewWriterLevel(w, 3)
				if err != nil {
					return false, err
				}
				tw := tar.NewWriter(gw)

				if len(text) > 0 {
					if err := tw.WriteHeader(&tar.Header{
						Name:     "README.md",
						Mode:     int64(os.FileMode(0644).Perm()),
						Size:     int64(len(text)),
						Typeflag: tar.TypeReg,
						ModTime:  hdr.ModTime,
					}); err != nil {
						return false, err
					}
					if _, err := fmt.Fprintf(tw, text); err != nil {
						return false, err
					}
				}

				if err := tw.WriteHeader(&tar.Header{
					Name:     hdr.Name,
					Mode:     int64(os.FileMode(0755).Perm()),
					Size:     hdr.Size,
					Typeflag: tar.TypeReg,
					ModTime:  hdr.ModTime,
				}); err != nil {
					return false, err
				}

				w = tw
				closeFn = func() error {
					for _, link := range target.LinkTo {
						if err := tw.WriteHeader(&tar.Header{
							Name:     link,
							Mode:     int64(os.FileMode(0755).Perm()),
							Size:     0,
							Typeflag: tar.TypeLink,
							ModTime:  hdr.ModTime,
							Linkname: hdr.Name,
						}); err != nil {
							return err
						}
					}
					if err := tw.Close(); err != nil {
						return err
					}
					return gw.Close()
				}
			}
		}

		// copy the input to disk
		if target.InjectReleaseImage {
			var matched bool
			matched, err = copyAndReplaceReleaseImage(w, r, 4*1024, exactReleaseImage)
			if !matched {
				fmt.Fprintf(o.ErrOut, "warning: Unable to replace release image location into %s, installer will not be locked to the correct image\n", target.TargetName)
			}
		} else {
			_, err = io.Copy(w, r)
		}
		if err != nil {
			closeFn()
			f.Close()
			os.Remove(f.Name())
			return false, err
		}

		// ensure the file is written to disk
		if err := closeFn(); err != nil {
			return false, err
		}
		if err := bw.Flush(); err != nil {
			return false, err
		}
		if err := f.Close(); err != nil {
			return false, err
		}
		if err := os.Chtimes(f.Name(), hdr.ModTime, hdr.ModTime); err != nil {
			klog.V(2).Infof("Unable to set extracted file modification time: %v", err)
		}

		func() {
			extractLock.Lock()
			defer extractLock.Unlock()
			delete(targetsByName, layer.Mapping.Name)
			if hash != nil {
				hashByTargetName[layer.Mapping.To] = hex.EncodeToString(hash.Sum(nil))
			}
		}()

		return false, nil
	}
	if err := opts.Run(); err != nil {
		return err
	}

	if willArchive {
		buf := &bytes.Buffer{}
		fmt.Fprintf(buf, heredoc.Doc(`
			Client tools for OpenShift
			--------------------------
			
			These archives contain the client tooling for [OpenShift](https://docs.openshift.com).

			To verify the contents of this directory, use the 'gpg' and 'shasum' tools to
			ensure the archives you have downloaded match those published from this location.
			
			The openshift-install binary has been preconfigured to install the following release:

			---
			
		`))
		if err := describeReleaseInfo(buf, release, false, true, false); err != nil {
			return err
		}
		filename := "release.txt"
		if err := ioutil.WriteFile(filepath.Join(dir, filename), buf.Bytes(), 0644); err != nil {
			return err
		}
		hash := hashFn()
		hash.Write(buf.Bytes())
		hashByTargetName[filename] = hex.EncodeToString(hash.Sum(nil))
	}

	// write a checksum of the tar files to disk as sha256sum.txt.asc
	if len(hashByTargetName) > 0 {
		var keys []string
		for k := range hashByTargetName {
			keys = append(keys, k)
		}
		sort.Strings(keys)
		var lines []string
		for _, k := range keys {
			hash := hashByTargetName[k]
			lines = append(lines, fmt.Sprintf("%s  %s", hash, filepath.Base(k)))
		}
		// ensure a trailing newline
		if len(lines[len(lines)-1]) != 0 {
			lines = append(lines, "")
		}
		// write the content manifest
		data := []byte(strings.Join(lines, "\n"))
		filename := "sha256sum.txt"
		if err := ioutil.WriteFile(filepath.Join(dir, filename), data, 0644); err != nil {
			return fmt.Errorf("unable to write checksum file: %v", err)
		}
		// sign the content manifest
		if signer != nil {
			buf := &bytes.Buffer{}
			if err := openpgp.ArmoredDetachSign(buf, signer, bytes.NewBuffer(data), nil); err != nil {
				return fmt.Errorf("unable to sign the sha256sum.txt file: %v", err)
			}
			if err := ioutil.WriteFile(filepath.Join(dir, filename+".asc"), buf.Bytes(), 0644); err != nil {
				return fmt.Errorf("unable to write signed manifest: %v", err)
			}
		}
	}

	// if we did not process some targets, report that to the user and error if necessary
	if len(targetsByName) > 0 {
		var missing []string
		for _, target := range targetsByName {
			missing = append(missing, target.Mapping.From)
		}
		sort.Strings(missing)
		if len(missing) == 1 {
			return fmt.Errorf("image did not contain %s", missing[0])
		}
		return fmt.Errorf("unable to find multiple files: %s", strings.Join(missing, ", "))
	}

	return nil
}
194522
func (t Tracer) Extract(format interface{}, carrier interface{}) (ctx opentracing.SpanContext, err error) {
	defer func() {
		if r := recover(); r != nil {
			// TODO annotate this error type
			err = ErrContractViolation{r}
		}
	}()

	if format == opentracing.Binary {
		// carrier is guaranteed to be an io.Reader by contract
		r := carrier.(io.Reader)
		packet, err := ioutil.ReadAll(r)
		if err != nil {
			return nil, err
		}

		sample := ssf.SSFSpan{}
		err = proto.Unmarshal(packet, &sample)
		if err != nil {
			return nil, err
		}

		resource := sample.Tags[ResourceKey]

		trace := &Trace{
			TraceID:  sample.TraceId,
			SpanID:   sample.Id,
			Resource: resource,
		}

		return trace.context(), nil
	}

	if tm, ok := carrier.(opentracing.TextMapReader); ok {
		// carrier is guaranteed to be an opentracing.TextMapReader by contract
		// TODO support other TextMapReader implementations
		var traceID int64
		var spanID int64
		for _, headers := range HeaderFormats {

			base := 10
			if headers.numFormat == hexadecimal {
				base = 16
			}

			traceID, _ = strconv.ParseInt(textMapReaderGet(tm, headers.TraceID), base, 64)
			spanID, _ = strconv.ParseInt(textMapReaderGet(tm, headers.SpanID), base, 64)

			if traceID != 0 && spanID != 0 {
				break
			}
		}
		if traceID == 0 && spanID == 0 {
			return nil, errors.New("error parsing fields from TextMapReader")
		}

		trace := &Trace{
			TraceID:  traceID,
			SpanID:   spanID,
			Resource: textMapReaderGet(tm, ResourceKey),
		}

		return trace.context(), nil
	}

	return nil, opentracing.ErrUnsupportedFormat
}
935836
func (r *Rar) Extract(source, target, destination string) error {
	// target refers to a path inside the archive, which should be clean also
	target = path.Clean(target)

	// if the target ends up being a directory, then
	// we will continue walking and extracting files
	// until we are no longer within that directory
	var targetDirPath string

	return r.Walk(source, func(f File) error {
		th, ok := f.Header.(*rardecode.FileHeader)
		if !ok {
			return fmt.Errorf("expected header to be *rardecode.FileHeader but was %T", f.Header)
		}

		// importantly, cleaning the path strips tailing slash,
		// which must be appended to folders within the archive
		name := path.Clean(th.Name)
		if f.IsDir() && target == name {
			targetDirPath = path.Dir(name)
		}

		if within(target, th.Name) {
			// either this is the exact file we want, or is
			// in the directory we want to extract

			// build the filename we will extract to
			end, err := filepath.Rel(targetDirPath, th.Name)
			if err != nil {
				return fmt.Errorf("relativizing paths: %v", err)
			}
			joined := filepath.Join(destination, end)

			err = r.unrarFile(f, joined)
			if err != nil {
				return fmt.Errorf("extracting file %s: %v", th.Name, err)
			}

			// if our target was not a directory, stop walk
			if targetDirPath == "" {
				return ErrStopWalk
			}
		} else if targetDirPath != "" {
			// finished walking the entire directory
			return ErrStopWalk
		}

		return nil
	})
}
937033
func (p *WebHookPlugin) Extract(buildCfg *buildv1.BuildConfig, trigger *buildv1.WebHookTrigger, req *http.Request) (revision *buildv1.SourceRevision, envvars []corev1.EnvVar, dockerStrategyOptions *buildv1.DockerStrategyOptions, proceed bool, err error) {
	klog.V(4).Infof("Verifying build request for BuildConfig %s/%s", buildCfg.Namespace, buildCfg.Name)
	if err = verifyRequest(req); err != nil {
		return revision, envvars, dockerStrategyOptions, false, err
	}

	contentType := req.Header.Get("Content-Type")
	if len(contentType) != 0 {
		contentType, _, err = mime.ParseMediaType(contentType)
		if err != nil {
			return revision, envvars, dockerStrategyOptions, false, errors.NewBadRequest(fmt.Sprintf("error parsing Content-Type: %s", err))
		}
	}

	if req.Body == nil {
		return revision, envvars, dockerStrategyOptions, true, nil
	}

	if contentType != "application/json" && contentType != "application/yaml" {
		warning := webhook.NewWarning("invalid Content-Type on payload, ignoring payload and continuing with build")
		return revision, envvars, dockerStrategyOptions, true, warning
	}

	body, err := ioutil.ReadAll(req.Body)
	if err != nil {
		return revision, envvars, dockerStrategyOptions, false, errors.NewBadRequest(err.Error())
	}

	if len(body) == 0 {
		return revision, envvars, dockerStrategyOptions, true, nil
	}

	internalData := &buildapi.GenericWebHookEvent{}
	versionedData := &buildv1.GenericWebHookEvent{}
	if contentType == "application/yaml" {
		body, err = yaml.ToJSON(body)
		if err != nil {
			warning := webhook.NewWarning(fmt.Sprintf("error converting payload to json: %v, ignoring payload and continuing with build", err))
			return revision, envvars, dockerStrategyOptions, true, warning
		}
	}
	if err = json.Unmarshal(body, &versionedData); err != nil {
		warning := webhook.NewWarning(fmt.Sprintf("error unmarshalling payload: %v, ignoring payload and continuing with build", err))
		return revision, envvars, dockerStrategyOptions, true, warning
	}
	if err := legacyscheme.Scheme.Convert(versionedData, internalData, nil); err != nil {
		return revision, envvars, dockerStrategyOptions, false, errors.NewBadRequest(err.Error())
	}

	if len(versionedData.Env) > 0 && trigger.AllowEnv {
		envvars = versionedData.Env
	}
	if internalData.DockerStrategyOptions != nil {
		dockerStrategyOptions = versionedData.DockerStrategyOptions
	}
	if buildCfg.Spec.Source.Git == nil {
		// everything below here is specific to git-based builds
		return revision, envvars, dockerStrategyOptions, true, nil
	}
	if internalData.Git == nil {
		warning := webhook.NewWarning("no git information found in payload, ignoring and continuing with build")
		return revision, envvars, dockerStrategyOptions, true, warning
	}

	if internalData.Git.Refs != nil {
		for _, ref := range versionedData.Git.Refs {
			if webhook.GitRefMatches(ref.Ref, webhook.DefaultConfigRef, &buildCfg.Spec.Source) {
				revision = &buildv1.SourceRevision{
					Git: &ref.GitSourceRevision,
				}
				return revision, envvars, dockerStrategyOptions, true, nil
			}
		}
		warning := webhook.NewWarning(fmt.Sprintf("skipping build. None of the supplied refs matched %q", buildCfg.Spec.Source.Git.Ref))
		return revision, envvars, dockerStrategyOptions, false, warning
	}
	if !webhook.GitRefMatches(internalData.Git.Ref, webhook.DefaultConfigRef, &buildCfg.Spec.Source) {
		warning := webhook.NewWarning(fmt.Sprintf("skipping build. Branch reference from %q does not match configuration", internalData.Git.Ref))
		return revision, envvars, dockerStrategyOptions, false, warning
	}
	revision = &buildv1.SourceRevision{
		Git: &versionedData.Git.GitSourceRevision,
	}
	return revision, envvars, dockerStrategyOptions, true, nil
}
73825
func (txz *TarXz) Extract(source, target, destination string) error {
	txz.wrapReader()
	return txz.Tar.Extract(source, target, destination)
}
894239
func (tgz *TarGz) Extract(source, target, destination string) error {
	tgz.wrapReader()
	return tgz.Tar.Extract(source, target, destination)
}
587746
func (tz *TzArchive) ExtractToFunc(destPath string, fn cae.HookFunc, entries ...string) (err error) {
	destPath = strings.Replace(destPath, "\\", "/", -1)
	isHasEntry := len(entries) > 0
	if Verbose {
		fmt.Println("Extracting " + tz.FileName + "...")
	}
	os.MkdirAll(destPath, os.ModePerm)

	// Copy post-added files.
	for _, f := range tz.files {
		if !cae.IsExist(f.absPath) {
			continue
		}

		relPath := path.Join(destPath, f.Name)
		os.MkdirAll(path.Dir(relPath), os.ModePerm)
		if err := cae.Copy(relPath, f.absPath); err != nil {
			return err
		}
	}

	tr, f, err := openFile(tz.FileName)
	if err != nil {
		return err
	}
	defer f.Close()

	for {
		h, err := tr.Next()
		if err == io.EOF {
			break
		} else if err != nil {
			return err
		}

		h.Name = strings.Replace(h.Name, "\\", "/", -1)

		// Directory.
		if h.Typeflag == tar.TypeDir {
			if isHasEntry {
				if cae.IsEntry(h.Name, entries) {
					if err = fn(h.Name, h.FileInfo()); err != nil {
						continue
					}
					os.MkdirAll(path.Join(destPath, h.Name), os.ModePerm)
				}
				continue
			}
			if err = fn(h.Name, h.FileInfo()); err != nil {
				continue
			}
			os.MkdirAll(path.Join(destPath, h.Name), os.ModePerm)
			continue
		}

		// File.
		if isHasEntry {
			if cae.IsEntry(h.Name, entries) {
				if err = fn(h.Name, h.FileInfo()); err != nil {
					continue
				}
				err = extractFile(h, tr, destPath)
			}
		} else {
			if err = fn(h.Name, h.FileInfo()); err != nil {
				continue
			}
			err = extractFile(h, tr, destPath)
		}
		if err != nil {
			return err
		}
	}
	return nil
}
12101
func (t *Tracing) Extract(format interface{}, carrier interface{}) (opentracing.SpanContext, error) {
	return t.tracer.Extract(format, carrier)
}
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
}
730033
func Extract(ctx context.Context) *logrus.Entry {
	l, ok := ctx.Value(ctxLoggerKey).(*ctxLogger)
	if !ok || l == nil {
		return logrus.NewEntry(nullLogger)
	}

	fields := logrus.Fields{}

	// Add grpc_ctxtags tags metadata until now.
	tags := grpc_ctxtags.Extract(ctx)
	for k, v := range tags.Values() {
		fields[k] = v
	}

	// Add logrus fields added until now.
	for k, v := range l.fields {
		fields[k] = v
	}

	return l.logger.WithFields(fields)
}
564564
func extractScript(p *Provisioner) (string, error) {
	temp, err := tmp.File("powershell-provisioner")
	if err != nil {
		return "", err
	}
	defer temp.Close()
	writer := bufio.NewWriter(temp)
	for _, command := range p.config.Inline {
		log.Printf("Found command: %s", command)
		if _, err := writer.WriteString(command + "\n"); err != nil {
			return "", fmt.Errorf("Error preparing powershell script: %s", err)
		}
	}

	if err := writer.Flush(); err != nil {
		return "", fmt.Errorf("Error preparing powershell script: %s", err)
	}

	return temp.Name(), nil
}
824272
func ExtractToFunc(srcPath, destPath string, fn cae.HookFunc, entries ...string) (err error) {
	z, err := Open(srcPath)
	if err != nil {
		return err
	}
	defer z.Close()
	return z.ExtractToFunc(destPath, fn, entries...)
}
556512
func Extract(img image.Image, c Channel) *image.Gray {
	if c < 0 || 3 < c {
		panic(fmt.Sprintf("channel index '%v' out of bounds. Red: 0, Green: 1, Blue: 2, Alpha: 3", c))
	}

	src := clone.AsRGBA(img)
	bounds := src.Bounds()
	srcW, srcH := bounds.Dx(), bounds.Dy()

	if bounds.Empty() {
		return &image.Gray{}
	}

	dst := image.NewGray(bounds)

	parallel.Line(srcH, func(start, end int) {
		for y := start; y < end; y++ {
			for x := 0; x < srcW; x++ {
				srcPos := y*src.Stride + x*4
				dstPos := y*dst.Stride + x

				dst.Pix[dstPos] = src.Pix[srcPos+int(c)]
			}
		}
	})

	return dst
}
738206
func ExtractTo(srcPath, destPath string, entries ...string) (err error) {
	tz, err := Open(srcPath)
	if err != nil {
		return err
	}
	defer tz.Close()
	return tz.ExtractToFunc(destPath, defaultExtractFunc, entries...)
}
308990
func Extract(ctx context.Context) *zap.Logger {
	l, ok := ctx.Value(ctxMarkerKey).(*ctxLogger)
	if !ok || l == nil {
		return nullLogger
	}
	// Add grpc_ctxtags tags metadata until now.
	fields := TagsToFields(ctx)
	// Add zap fields added until now.
	fields = append(fields, l.fields...)
	return l.logger.With(fields...)
}