// rewriteTar interprets an pipe reader as a tar reader and rewrites the
// headers so they can get written to the outfile.
420795
func rewriteTar(prefix string, tarWriter *tar.Writer, r *io.PipeReader) error {
	defer r.Close()
	tarReader := tar.NewReader(r)

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

		// Rewrite the header to include the prefix
		header.Name = filepath.Join(prefix, header.Name)
		if err := tarWriter.WriteHeader(header); err != nil {
			return err
		}
		if _, err := io.Copy(tarWriter, tarReader); err != nil {
			return err
		}
	}

	return nil
}
1210782
func ImportTar(ctx context.Context, r io.Reader, ds ipld.DAGService) (*dag.ProtoNode, error) {
	tr := tar.NewReader(r)

	root := new(dag.ProtoNode)
	root.SetData([]byte("ipfs/tar"))

	e := dagutils.NewDagEditor(root, ds)

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

		header := new(dag.ProtoNode)

		headerBytes, err := marshalHeader(h)
		if err != nil {
			return nil, err
		}

		header.SetData(headerBytes)

		if h.Size > 0 {
			spl := chunker.NewRabin(tr, uint64(chunker.DefaultBlockSize))
			nd, err := importer.BuildDagFromReader(ds, spl)
			if err != nil {
				return nil, err
			}

			err = header.AddNodeLink("data", nd)
			if err != nil {
				return nil, err
			}
		}

		err = ds.Add(ctx, header)
		if err != nil {
			return nil, err
		}

		path := escapePath(h.Name)
		err = e.InsertNodeAtPath(context.Background(), path, header, func() *dag.ProtoNode { return new(dag.ProtoNode) })
		if err != nil {
			return nil, err
		}
	}

	return e.Finalize(ctx, ds)
}
172560
func (t *stiTar) ExtractTarStream(dir string, reader io.Reader) error {
	tarReader := tar.NewReader(reader)
	return t.ExtractTarStreamFromTarReader(dir, tarReader, nil)
}
747734
func writeNestedTarHeader(tw *tar.Writer, parts []string, existing map[string]struct{}, hdr tar.Header) error {
	for i := range parts {
		componentDir := path.Join(parts[:i+1]...)
		if _, ok := existing[componentDir]; ok {
			continue
		}
		existing[componentDir] = struct{}{}
		hdr.Name = componentDir
		if err := tw.WriteHeader(&hdr); err != nil {
			return err
		}
	}
	return nil
}
1252917
func untar(input io.Reader, dst, src string, dir bool) error {
	tarR := tar.NewReader(input)
	done := false
	dirHdrs := []*tar.Header{}
	now := time.Now()
	for {
		hdr, err := tarR.Next()
		if err == io.EOF {
			if !done {
				// Empty archive
				return fmt.Errorf("empty archive: %s", src)
			}

			break
		}
		if err != nil {
			return err
		}

		if hdr.Typeflag == tar.TypeXGlobalHeader || hdr.Typeflag == tar.TypeXHeader {
			// don't unpack extended headers as files
			continue
		}

		path := dst
		if dir {
			// Disallow parent traversal
			if containsDotDot(hdr.Name) {
				return fmt.Errorf("entry contains '..': %s", hdr.Name)
			}

			path = filepath.Join(path, hdr.Name)
		}

		if hdr.FileInfo().IsDir() {
			if !dir {
				return fmt.Errorf("expected a single file: %s", src)
			}

			// A directory, just make the directory and continue unarchiving...
			if err := os.MkdirAll(path, 0755); err != nil {
				return err
			}

			// Record the directory information so that we may set its attributes
			// after all files have been extracted
			dirHdrs = append(dirHdrs, hdr)

			continue
		} else {
			// There is no ordering guarantee that a file in a directory is
			// listed before the directory
			dstPath := filepath.Dir(path)

			// Check that the directory exists, otherwise create it
			if _, err := os.Stat(dstPath); os.IsNotExist(err) {
				if err := os.MkdirAll(dstPath, 0755); err != nil {
					return err
				}
			}
		}

		// We have a file. If we already decoded, then it is an error
		if !dir && done {
			return fmt.Errorf("expected a single file, got multiple: %s", src)
		}

		// Mark that we're done so future in single file mode errors
		done = true

		// Open the file for writing
		dstF, err := os.Create(path)
		if err != nil {
			return err
		}
		_, err = io.Copy(dstF, tarR)
		dstF.Close()
		if err != nil {
			return err
		}

		// Chmod the file
		if err := os.Chmod(path, hdr.FileInfo().Mode()); err != nil {
			return err
		}

		// Set the access and modification time if valid, otherwise default to current time
		aTime := now
		mTime := now
		if hdr.AccessTime.Unix() > 0 {
			aTime = hdr.AccessTime
		}
		if hdr.ModTime.Unix() > 0 {
			mTime = hdr.ModTime
		}
		if err := os.Chtimes(path, aTime, mTime); err != nil {
			return err
		}
	}

	// Perform a final pass over extracted directories to update metadata
	for _, dirHdr := range dirHdrs {
		path := filepath.Join(dst, dirHdr.Name)
		// Chmod the directory since they might be created before we know the mode flags
		if err := os.Chmod(path, dirHdr.FileInfo().Mode()); err != nil {
			return err
		}
		// Set the mtime/atime attributes since they would have been changed during extraction
		aTime := now
		mTime := now
		if dirHdr.AccessTime.Unix() > 0 {
			aTime = dirHdr.AccessTime
		}
		if dirHdr.ModTime.Unix() > 0 {
			mTime = dirHdr.ModTime
		}
		if err := os.Chtimes(path, aTime, mTime); err != nil {
			return err
		}
	}

	return nil
}
327607
func (rule *suffixTtlRule) Rewrite(ctx context.Context, state request.Request) Result {
	if strings.HasSuffix(state.Name(), rule.Suffix) {
		return RewriteDone
	}
	return RewriteIgnored
}
834952
func (s *Spec) rewriteIdent(pkg *Package) error {
	for _, node := range pkg.Files {
		ast.Inspect(node, func(n ast.Node) bool {
			switch x := n.(type) {
			case *ast.Ident:
				if x.Obj == nil || x.Obj.Kind != ast.Typ {
					return false
				}
				to, ok := s.TypeMap[x.Name]
				if !ok {
					return false
				}
				x.Name = to.Expr

				for _, im := range to.Import {
					astutil.AddImport(pkg.FileSet, node, im)
				}
				return false
			}
			return true
		})
	}
	return nil
}
1323697
func (api *Client) AddStar(channel string, item ItemRef) error {
	return api.AddStarContext(context.Background(), channel, item)
}
784691
func rewriteFile(pattern, replace ast.Expr, p *ast.File) *ast.File {
	cmap := ast.NewCommentMap(fileSet, p, p.Comments)
	m := make(map[string]reflect.Value)
	pat := reflect.ValueOf(pattern)
	repl := reflect.ValueOf(replace)

	var rewriteVal func(val reflect.Value) reflect.Value
	rewriteVal = func(val reflect.Value) reflect.Value {
		// don't bother if val is invalid to start with
		if !val.IsValid() {
			return reflect.Value{}
		}
		for k := range m {
			delete(m, k)
		}
		val = apply(rewriteVal, val)
		if match(m, pat, val) {
			val = subst(m, repl, reflect.ValueOf(val.Interface().(ast.Node).Pos()))
		}
		return val
	}

	r := apply(rewriteVal, reflect.ValueOf(p)).Interface().(*ast.File)
	r.Comments = cmap.Filter(r).Comments() // recreate comments list
	return r
}
357671
func (archiver *Archiver) CopyWithTar(src, dst string) error {
	srcSt, err := os.Stat(src)
	if err != nil {
		return err
	}
	if !srcSt.IsDir() {
		return archiver.CopyFileWithTar(src, dst)
	}
	// Create dst, copy src's content into it
	logrus.Debugf("Creating dest directory: %s", dst)
	if err := system.MkdirAll(dst, 0755); err != nil {
		return err
	}
	logrus.Debugf("Calling TarUntar(%s, %s)", src, dst)
	return archiver.TarUntar(src, dst)
}
1086840
func (r *Rewriter) Rewrite(opt *RewriteOptions) ([]byte, error) {
	// First, obtain a list of commits to rewrite.
	commits, err := r.commitsToMigrate(opt)
	if err != nil {
		return nil, err
	}

	var perc *tasklog.PercentageTask
	if opt.UpdateRefs {
		perc = r.l.Percentage("migrate: Rewriting commits", uint64(len(commits)))
	} else {
		perc = r.l.Percentage("migrate: Examining commits", uint64(len(commits)))
	}

	var vPerc *tasklog.PercentageTask
	if opt.Verbose {
		vPerc = perc
	}

	var objectMapFile *os.File
	if len(opt.ObjectMapFilePath) > 0 {
		objectMapFile, err = os.OpenFile(opt.ObjectMapFilePath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
		if err != nil {
			return nil, fmt.Errorf("Could not create object map file: %v", err)
		}
		defer objectMapFile.Close()
	}

	// Keep track of the last commit that we rewrote. Callers often want
	// this so that they can perform a git-update-ref(1).
	var tip []byte
	for _, oid := range commits {
		// Load the original commit to access the data necessary in
		// order to rewrite it.
		original, err := r.db.Commit(oid)
		if err != nil {
			return nil, err
		}

		// Rewrite the tree given at that commit.
		rewrittenTree, err := r.rewriteTree(oid, original.TreeID, "", opt.blobFn(), opt.treePreFn(), opt.treeFn(), vPerc)
		if err != nil {
			return nil, err
		}

		// Create a new list of parents from the original commit to
		// point at the rewritten parents in order to create a
		// topologically equivalent DAG.
		//
		// This operation is safe since we are visiting the commits in
		// reverse topological order and therefore have seen all parents
		// before children (in other words, r.uncacheCommit(...) will
		// always return a value, if the prospective parent is a part of
		// the migration).
		rewrittenParents := make([][]byte, 0, len(original.ParentIDs))
		for _, originalParent := range original.ParentIDs {
			rewrittenParent, ok := r.uncacheCommit(originalParent)
			if !ok {
				// If we haven't seen the parent before, this
				// means that we're doing a partial migration
				// and the parent that we're looking for isn't
				// included.
				//
				// Use the original parent to properly link
				// history across the migration boundary.
				rewrittenParent = originalParent
			}

			rewrittenParents = append(rewrittenParents, rewrittenParent)
		}

		// Construct a new commit using the original header information,
		// but the rewritten set of parents as well as root tree.
		rewrittenCommit := &gitobj.Commit{
			Author:       original.Author,
			Committer:    original.Committer,
			ExtraHeaders: original.ExtraHeaders,
			Message:      original.Message,

			ParentIDs: rewrittenParents,
			TreeID:    rewrittenTree,
		}

		var newSha []byte

		if original.Equal(rewrittenCommit) {
			newSha = make([]byte, len(oid))
			copy(newSha, oid)
		} else {
			newSha, err = r.db.WriteCommit(rewrittenCommit)
			if err != nil {
				return nil, err
			}
			if objectMapFile != nil {
				if _, err := fmt.Fprintf(objectMapFile, "%x,%x\n", oid, newSha); err != nil {
					return nil, err
				}
			}
		}

		// Cache that commit so that we can reassign children of this
		// commit.
		r.cacheCommit(oid, newSha)

		// Increment the percentage displayed in the terminal.
		perc.Count(1)

		// Move the tip forward.
		tip = newSha
	}

	if opt.UpdateRefs {
		refs, err := r.refsToMigrate()
		if err != nil {
			return nil, errors.Wrap(err, "could not find refs to update")
		}

		root, _ := r.db.Root()

		updater := &refUpdater{
			CacheFn: r.uncacheCommit,
			Logger:  r.l,
			Refs:    refs,
			Root:    root,

			db: r.db,
		}

		if err := updater.UpdateRefs(); err != nil {
			return nil, errors.Wrap(err, "could not update refs")
		}
	}

	return tip, err
}
974591
func (mb *configManifestBuilder) emptyTar(ctx context.Context) (digest.Digest, error) {
	if mb.emptyTarDigest != "" {
		// Already put an empty tar
		return mb.emptyTarDigest, nil
	}

	descriptor, err := mb.bs.Stat(ctx, digestSHA256GzippedEmptyTar)
	switch err {
	case nil:
		mb.emptyTarDigest = descriptor.Digest
		return descriptor.Digest, nil
	case distribution.ErrBlobUnknown:
		// nop
	default:
		return "", err
	}

	// Add gzipped empty tar to the blob store
	descriptor, err = mb.bs.Put(ctx, "", gzippedEmptyTar)
	if err != nil {
		return "", err
	}

	mb.emptyTarDigest = descriptor.Digest

	return descriptor.Digest, nil
}
783611
func (_m *RequesterVariadic) MultiWriteToFile(filename string, w ...io.Writer) string {
	_va := make([]interface{}, len(w))
	for _i := range w {
		_va[_i] = w[_i]
	}
	var _ca []interface{}
	_ca = append(_ca, filename)
	_ca = append(_ca, _va...)
	ret := _m.Called(_ca...)

	var r0 string
	if rf, ok := ret.Get(0).(func(string, ...io.Writer) string); ok {
		r0 = rf(filename, w...)
	} else {
		r0 = ret.Get(0).(string)
	}

	return r0
}
207560
func (rule *classRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result {
	if rule.fromClass > 0 && rule.toClass > 0 {
		if r.Question[0].Qclass == rule.fromClass {
			r.Question[0].Qclass = rule.toClass
			return RewriteDone
		}
	}
	return RewriteIgnored
}
242665
func (m *rewrite) rewrite() (string, error) {

	var err error

	if m.sel.Where != nil {
		m.result.Where = m.sel.Where
		m.result.Where.Expr, err = m.walkNode(m.sel.Where.Expr)
		if err != nil {
			return "", err
		}
	}

	// Evaluate the Select columns make sure we can pass them down or polyfill
	err = m.walkSelectList()
	if err != nil {
		u.Warnf("Could Not evaluate Columns/Aggs %s %v", m.sel.Columns.String(), err)
		return "", err
	}
	m.result.From = m.sel.From

	if len(m.sel.GroupBy) > 0 {
		err = m.walkGroupBy()
		if err != nil {
			u.Warnf("Could Not evaluate GroupBys %s %v", m.sel.GroupBy.String(), err)
			return "", err
		}
	}

	if len(m.sel.OrderBy) > 0 {
		// this should be same right?
		m.result.OrderBy = m.sel.OrderBy
	}

	return m.result.String(), nil
}
630646
func rewriteOpts(e dockeropts.Editor, cfgFile string, args string) (restartNeeded bool, err error) {
	in, err := ioutil.ReadFile(cfgFile)
	if err != nil {
		return false, fmt.Errorf("error reading %s: %v", cfgFile, err)
	}

	out, err := e.ChangeOpts(string(in), args)
	if err != nil {
		return false, fmt.Errorf("error updating settings at %s: %v", cfgFile, err)
	}

	// check if existing config file needs an update
	if ok, _ := util.PathExists(cfgFile); ok {
		existing, err := ioutil.ReadFile(cfgFile)
		if err != nil {
			return false, fmt.Errorf("error reading %s: %v", cfgFile, err)
		}

		// no need to update config or restart service if goal config is already there
		if string(existing) == out {
			return false, nil
		}
	}

	if err := ioutil.WriteFile(cfgFile, []byte(out), 0644); err != nil {
		return false, fmt.Errorf("error writing to %s: %v", cfgFile, err)
	}
	return true, nil
}
324758
func Untar(dest string, r io.Reader) error {
	if exists(dest) {
		return errors.Errorf("%q must not exist", dest)
	}
	parent, _ := filepath.Split(dest)
	tmpdir, err := ioutil.TempDir(parent, ".untar")
	if err != nil {
		return err
	}

	if err := untar(tmpdir, r); err != nil {
		os.RemoveAll(tmpdir)
		return err
	}

	if err := os.Rename(tmpdir, dest); err != nil {
		os.RemoveAll(tmpdir)
		return err
	}
	return nil
}