// Diff returns the ResourceDiff for a resource given its state and
// configuration.
342225
func (b *ResourceBuilder) Diff(
	s *terraform.InstanceState,
	c *terraform.ResourceConfig) (*terraform.InstanceDiff, error) {
	attrs := make(map[string]*terraform.ResourceAttrDiff)

	// We require a new resource if the ID is empty. Or, later, we set
	// this to true if any configuration changed that triggers a new resource.
	requiresNew := s.ID == ""

	// Flatten the raw and processed configuration
	flatRaw := flatmap.Flatten(c.Raw)
	flatConfig := flatmap.Flatten(c.Config)

	for ak, at := range b.Attrs {
		// Keep track of all the keys we saw in the raw structure
		// so that we can prune our attributes later.
		seenKeys := make([]string, 0)

		// Go through and find the added/changed keys in flatRaw
		for k, v := range flatRaw {
			// Find only the attributes that match our prefix
			if !strings.HasPrefix(k, ak) {
				continue
			}

			// Track that we saw this key
			seenKeys = append(seenKeys, k)

			// We keep track of this in case we have a pre-processor
			// so that we can store the original value still.
			originalV := v

			// If this key is in the cleaned config, then use that value
			// because it'll have its variables properly interpolated
			if cleanV, ok := flatConfig[k]; ok && cleanV != config.UnknownVariableValue {
				v = cleanV
				originalV = v

				// If we have a pre-processor for this, run it.
				if pp, ok := b.PreProcess[k]; ok {
					v = pp(v)
				}
			}

			oldV, ok := s.Attributes[k]

			// If there is an old value and they're the same, no change
			if ok && oldV == v {
				continue
			}

			// Record the change
			attrs[k] = &terraform.ResourceAttrDiff{
				Old:      oldV,
				New:      v,
				NewExtra: originalV,
				Type:     terraform.DiffAttrInput,
			}

			// If this requires a new resource, record that and flag our
			// boolean.
			if at == AttrTypeCreate {
				attrs[k].RequiresNew = true
				requiresNew = true
			}
		}

		// Find all the keys that are in our attributes right now that
		// we also care about.
		matchingKeys := make(map[string]struct{})
		for k, _ := range s.Attributes {
			// Find only the attributes that match our prefix
			if !strings.HasPrefix(k, ak) {
				continue
			}

			// If this key is computed, then we don't ever delete it
			comp := false
			for _, ck := range b.ComputedAttrs {
				if ck == k {
					comp = true
					break
				}

				// If the key is prefixed with the computed key, don't
				// mark it for delete, ever.
				if strings.HasPrefix(k, ck+".") {
					comp = true
					break
				}
			}
			if comp {
				continue
			}

			matchingKeys[k] = struct{}{}
		}

		// Delete the keys we saw in the configuration from the keys
		// that are currently set.
		for _, k := range seenKeys {
			delete(matchingKeys, k)
		}
		for k, _ := range matchingKeys {
			attrs[k] = &terraform.ResourceAttrDiff{
				Old:        s.Attributes[k],
				NewRemoved: true,
				Type:       terraform.DiffAttrInput,
			}
		}
	}

	// If we require a new resource, then process all the attributes
	// that will be changing due to the creation of the resource.
	if requiresNew {
		for _, k := range b.ComputedAttrs {
			if _, ok := attrs[k]; ok {
				continue
			}

			old := s.Attributes[k]
			attrs[k] = &terraform.ResourceAttrDiff{
				Old:         old,
				NewComputed: true,
				Type:        terraform.DiffAttrOutput,
			}
		}
	}

	// If we're changing anything, then mark the updated
	// attributes.
	if len(attrs) > 0 {
		for _, k := range b.ComputedAttrsUpdate {
			if _, ok := attrs[k]; ok {
				continue
			}

			old := s.Attributes[k]
			attrs[k] = &terraform.ResourceAttrDiff{
				Old:         old,
				NewComputed: true,
				Type:        terraform.DiffAttrOutput,
			}
		}
	}

	// Build our resulting diff if we had attributes change
	var result *terraform.InstanceDiff
	if len(attrs) > 0 {
		result = &terraform.InstanceDiff{
			Attributes: attrs,
		}
	}

	return result, nil
}
1205336
func Compare(a, b interface{}) Diff {
	mapA := map[string]interface{}{}
	mapB := map[string]interface{}{}

	jsonA, _ := json.Marshal(a)
	jsonB, _ := json.Marshal(b)

	json.Unmarshal(jsonA, &mapA)
	json.Unmarshal(jsonB, &mapB)

	return compareStringMaps(mapA, mapB)
}
700505
func (d *Driver) DiffSize(id, parent string) (size int64, err error) {
	rPId, err := d.resolveID(parent)
	if err != nil {
		return
	}

	changes, err := d.Changes(id, rPId)
	if err != nil {
		return
	}

	layerFs, err := d.Get(id, "")
	if err != nil {
		return
	}
	defer d.Put(id)

	return archive.ChangesSize(layerFs.Path(), changes), nil
}
336361
func (sdw *SplitDiffWorker) diff(ctx context.Context) error {
	sdw.SetState(WorkerStateDiff)

	sdw.wr.Logger().Infof("Gathering schema information...")
	wg := sync.WaitGroup{}
	rec := &concurrency.AllErrorRecorder{}
	wg.Add(1)
	go func() {
		var err error
		shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout)
		sdw.destinationSchemaDefinition, err = sdw.wr.GetSchema(
			shortCtx, sdw.destinationAlias, nil /* tables */, sdw.excludeTables, false /* includeViews */)
		cancel()
		if err != nil {
			sdw.markAsWillFail(rec, err)
		}
		sdw.wr.Logger().Infof("Got schema from destination %v", sdw.destinationAlias)
		wg.Done()
	}()
	wg.Add(1)
	go func() {
		var err error
		shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout)
		sdw.sourceSchemaDefinition, err = sdw.wr.GetSchema(
			shortCtx, sdw.sourceAlias, nil /* tables */, sdw.excludeTables, false /* includeViews */)
		cancel()
		if err != nil {
			sdw.markAsWillFail(rec, err)
		}
		sdw.wr.Logger().Infof("Got schema from source %v", sdw.sourceAlias)
		wg.Done()
	}()

	wg.Wait()
	if rec.HasErrors() {
		return rec.Error()
	}

	sdw.wr.Logger().Infof("Diffing the schema...")
	rec = &concurrency.AllErrorRecorder{}
	tmutils.DiffSchema("destination", sdw.destinationSchemaDefinition, "source", sdw.sourceSchemaDefinition, rec)
	if rec.HasErrors() {
		sdw.wr.Logger().Warningf("Different schemas: %v", rec.Error().Error())
	} else {
		sdw.wr.Logger().Infof("Schema match, good.")
	}

	// read the vschema if needed
	var keyspaceSchema *vindexes.KeyspaceSchema
	if *useV3ReshardingMode {
		kschema, err := sdw.wr.TopoServer().GetVSchema(ctx, sdw.keyspace)
		if err != nil {
			return vterrors.Wrapf(err, "cannot load VSchema for keyspace %v", sdw.keyspace)
		}
		if kschema == nil {
			return vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "no VSchema for keyspace %v", sdw.keyspace)
		}

		keyspaceSchema, err = vindexes.BuildKeyspaceSchema(kschema, sdw.keyspace)
		if err != nil {
			return vterrors.Wrapf(err, "cannot build vschema for keyspace %v", sdw.keyspace)
		}
	}

	// Compute the overlap keyrange. Later, we'll compare it with
	// source or destination keyrange. If it matches either,
	// we'll just ask for all the data. If the overlap is a subset,
	// we'll filter.
	overlap, err := key.KeyRangesOverlap(sdw.shardInfo.KeyRange, sdw.sourceShard.KeyRange)
	if err != nil {
		return vterrors.Wrap(err, "Source shard doesn't overlap with destination")
	}

	// run the diffs, 8 at a time
	sdw.wr.Logger().Infof("Running the diffs...")
	sem := sync2.NewSemaphore(sdw.parallelDiffsCount, 0)
	tableDefinitions := sdw.destinationSchemaDefinition.TableDefinitions

	// sort tables by size
	// if there are large deltas between table sizes then it's more efficient to start working on the large tables first
	sort.Slice(tableDefinitions, func(i, j int) bool { return tableDefinitions[i].DataLength > tableDefinitions[j].DataLength })

	// use a channel to make sure tables are diffed in order
	tableChan := make(chan *tabletmanagerdatapb.TableDefinition, len(tableDefinitions))
	for _, tableDefinition := range tableDefinitions {
		tableChan <- tableDefinition
	}

	// start as many goroutines as there are tables to diff
	for range tableDefinitions {
		wg.Add(1)
		go func() {
			defer wg.Done()
			// use the semaphore to limit the number of tables that are diffed in parallel
			sem.Acquire()
			defer sem.Release()

			// grab the table to process out of the channel
			tableDefinition := <-tableChan

			sdw.wr.Logger().Infof("Starting the diff on table %v", tableDefinition.Name)

			// On the source, see if we need a full scan
			// or a filtered scan.
			var sourceQueryResultReader *QueryResultReader
			if key.KeyRangeEqual(overlap, sdw.sourceShard.KeyRange) {
				sourceQueryResultReader, err = TableScan(ctx, sdw.wr.Logger(), sdw.wr.TopoServer(), sdw.sourceAlias, tableDefinition)
			} else {
				sourceQueryResultReader, err = TableScanByKeyRange(ctx, sdw.wr.Logger(), sdw.wr.TopoServer(), sdw.sourceAlias, tableDefinition, overlap, keyspaceSchema, sdw.keyspaceInfo.ShardingColumnName, sdw.keyspaceInfo.ShardingColumnType)
			}
			if err != nil {
				newErr := vterrors.Wrap(err, "TableScan(ByKeyRange?)(source) failed")
				sdw.markAsWillFail(rec, newErr)
				sdw.wr.Logger().Error(newErr)
				return
			}
			defer sourceQueryResultReader.Close(ctx)

			// On the destination, see if we need a full scan
			// or a filtered scan.
			var destinationQueryResultReader *QueryResultReader
			if key.KeyRangeEqual(overlap, sdw.shardInfo.KeyRange) {
				destinationQueryResultReader, err = TableScan(ctx, sdw.wr.Logger(), sdw.wr.TopoServer(), sdw.destinationAlias, tableDefinition)
			} else {
				destinationQueryResultReader, err = TableScanByKeyRange(ctx, sdw.wr.Logger(), sdw.wr.TopoServer(), sdw.destinationAlias, tableDefinition, overlap, keyspaceSchema, sdw.keyspaceInfo.ShardingColumnName, sdw.keyspaceInfo.ShardingColumnType)
			}
			if err != nil {
				newErr := vterrors.Wrap(err, "TableScan(ByKeyRange?)(destination) failed")
				sdw.markAsWillFail(rec, newErr)
				sdw.wr.Logger().Error(newErr)
				return
			}
			defer destinationQueryResultReader.Close(ctx)

			// Create the row differ.
			differ, err := NewRowDiffer(sourceQueryResultReader, destinationQueryResultReader, tableDefinition)
			if err != nil {
				newErr := vterrors.Wrap(err, "NewRowDiffer() failed")
				sdw.markAsWillFail(rec, newErr)
				sdw.wr.Logger().Error(newErr)
				return
			}

			// And run the diff.
			report, err := differ.Go(sdw.wr.Logger())
			if err != nil {
				newErr := vterrors.Wrapf(err, "Differ.Go failed")
				sdw.markAsWillFail(rec, newErr)
				sdw.wr.Logger().Error(newErr)
			} else {
				if report.HasDifferences() {
					err := vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "table %v has differences: %v", tableDefinition.Name, report.String())
					sdw.markAsWillFail(rec, err)
					sdw.wr.Logger().Warningf(err.Error())
				} else {
					sdw.wr.Logger().Infof("Table %v checks out (%v rows processed, %v qps)", tableDefinition.Name, report.processedRows, report.processingQPS)
				}
			}
		}()
	}

	// grab the table to process out of the channel
	wg.Wait()

	return rec.Error()
}
539676
func (rule *Rule) Diff(other *Rule) []string {
	result := []string{}

	if rule.Kind != other.Kind {
		result = append(result, fmt.Sprintf("Kind: %s | %s", rule.Kind.String(), other.Kind.String()))
	}

	if rule.Prelude != other.Prelude {
		result = append(result, fmt.Sprintf("Prelude: \"%s\" | \"%s\"", rule.Prelude, other.Prelude))
	}

	if rule.Name != other.Name {
		result = append(result, fmt.Sprintf("Name: \"%s\" | \"%s\"", rule.Name, other.Name))
	}

	if len(rule.Selectors) != len(other.Selectors) {
		result = append(result, fmt.Sprintf("Selectors: %v | %v", strings.Join(rule.Selectors, ", "), strings.Join(other.Selectors, ", ")))
	} else {
		for i, sel := range rule.Selectors {
			if sel != other.Selectors[i] {
				result = append(result, fmt.Sprintf("Selector: \"%s\" | \"%s\"", sel, other.Selectors[i]))
			}
		}
	}

	if len(rule.Declarations) != len(other.Declarations) {
		result = append(result, fmt.Sprintf("Declarations Nb: %d | %d", len(rule.Declarations), len(other.Declarations)))
	} else {
		for i, decl := range rule.Declarations {
			if !decl.Equal(other.Declarations[i]) {
				result = append(result, fmt.Sprintf("Declaration: \"%s\" | \"%s\"", decl.String(), other.Declarations[i].String()))
			}
		}
	}

	if len(rule.Rules) != len(other.Rules) {
		result = append(result, fmt.Sprintf("Rules Nb: %d | %d", len(rule.Rules), len(other.Rules)))
	} else {

		for i, rule := range rule.Rules {
			if !rule.Equal(other.Rules[i]) {
				result = append(result, fmt.Sprintf("Rule: \"%s\" | \"%s\"", rule.String(), other.Rules[i].String()))
			}
		}
	}

	return result
}
228197
func ObjectDiff(a, b interface{}) string {
	ab, err := json.Marshal(a)
	if err != nil {
		panic(fmt.Sprintf("a: %v", err))
	}
	bb, err := json.Marshal(b)
	if err != nil {
		panic(fmt.Sprintf("b: %v", err))
	}
	return StringDiff(string(ab), string(bb))
}
1205338
func (d *Driver) DiffSize(id, parent string) (size int64, err error) {
	if useNaiveDiff(d.home) || !d.isParent(id, parent) {
		return d.naiveDiff.DiffSize(id, parent)
	}
	return directory.Size(context.TODO(), d.getDiffPath(id))
}
83590
func (s VarSet) Diff(vs VarSet) VarSet {
	r := VarSet{}
	for v := range s {
		if !vs.Contains(v) {
			r.Add(v)
		}
	}
	return r
}
558233
func (msdw *MultiSplitDiffWorker) diff(ctx context.Context) error {
	msdw.SetState(WorkerStateDiff)

	destinationSchemaDefinitions, sourceSchemaDefinition, err := msdw.gatherSchemaInfo(ctx)
	if err != nil {
		return err
	}
	err = msdw.diffSchemaInformation(ctx, destinationSchemaDefinitions, sourceSchemaDefinition)
	if err != nil {
		return err
	}

	// read the vschema if needed
	var keyspaceSchema *vindexes.KeyspaceSchema
	if *useV3ReshardingMode {
		keyspaceSchema, err = msdw.loadVSchema(ctx)
		if err != nil {
			return err
		}
	}

	msdw.wr.Logger().Infof("running the diffs...")
	tableDefinitions := sourceSchemaDefinition.TableDefinitions
	rec := &concurrency.AllErrorRecorder{}

	// sort tables by size
	// if there are large deltas between table sizes then it's more efficient to start working on the large tables first
	sort.Slice(tableDefinitions, func(i, j int) bool { return tableDefinitions[i].DataLength > tableDefinitions[j].DataLength })
	tableChan := make(chan *tabletmanagerdatapb.TableDefinition, len(tableDefinitions))
	for _, tableDefinition := range tableDefinitions {
		tableChan <- tableDefinition
	}
	close(tableChan)

	consumers := sync.WaitGroup{}
	// start as many goroutines we want parallel diffs running
	for i := 0; i < msdw.parallelDiffsCount; i++ {
		scanners := msdw.scanners[i]
		if scanners.sourceScanner == nil || scanners.destinationScanner == nil {
			return vterrors.Errorf(vtrpc.Code_INTERNAL, "should not be nil [%v] OR [%v]", scanners.sourceScanner, scanners.destinationScanner)
		}

		consumers.Add(1)
		go msdw.tableDiffingConsumer(ctx, &consumers, tableChan, rec, keyspaceSchema, scanners.sourceScanner, scanners.destinationScanner)
	}

	// wait for all consumers to wrap up their work
	consumers.Wait()

	return rec.Error()
}
702020
func (p *PullRequestsService) Diff() (diff io.ReadCloser, result *Result) {
	return p.client.getBody(p.URL, diffMediaType)
}
1139040
func (s *ChangesService) GetDiff(changeID, revisionID, fileID string, opt *DiffOptions) (*DiffInfo, *Response, error) {
	u := fmt.Sprintf("changes/%s/revisions/%s/files/%s/diff", changeID, revisionID, url.PathEscape(fileID))

	u, err := addOptions(u, opt)
	if err != nil {
		return nil, nil, err
	}

	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	v := new(DiffInfo)
	resp, err := s.client.Do(req, v)
	if err != nil {
		return nil, resp, err
	}

	return v, resp, err
}
544833
func Diff(left, right []byte) error {
	lf, err := ioutil.TempFile("/tmp", "actual-file-")
	if err != nil {
		return err
	}
	defer lf.Close()
	defer os.Remove(lf.Name())

	rf, err := ioutil.TempFile("/tmp", "expected-file-")
	if err != nil {
		return err
	}
	defer rf.Close()
	defer os.Remove(rf.Name())

	_, err = lf.Write(left)
	if err != nil {
		return err
	}
	lf.Close()

	_, err = rf.Write(right)
	if err != nil {
		return err
	}
	rf.Close()

	cmd := exec.Command("/usr/bin/diff", "-u", lf.Name(), rf.Name())
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Run()

	return nil
}
421771
func (d *Driver) Diff(id, parent string) (archive.Archive, error) {
	return archive.TarWithOptions(path.Join(virtPath, id), &archive.TarOptions{
		Compression:     archive.Uncompressed,
		ExcludePatterns: []string{archive.WhiteoutMetaPrefix + "*", "!" + archive.WhiteoutOpaqueDir},
	})
}
481703
func (a *Driver) Diff(id, parent string) (io.ReadCloser, error) {
	if !a.isParent(id, parent) {
		return a.naiveDiff.Diff(id, parent)
	}

	// AUFS doesn't need the parent layer to produce a diff.
	return archive.TarWithOptions(path.Join(a.rootPath(), "diff", id), &archive.TarOptions{
		Compression:     archive.Uncompressed,
		ExcludePatterns: []string{archive.WhiteoutMetaPrefix + "*", "!" + archive.WhiteoutOpaqueDir},
		UIDMaps:         a.uidMaps,
		GIDMaps:         a.gidMaps,
	})
}
1254763
func (d *ResourceDiff) setDiff(key string, new interface{}, computed bool) error {
	if err := d.clear(key); err != nil {
		return err
	}

	if err := d.newWriter.WriteField(strings.Split(key, "."), new, computed); err != nil {
		return fmt.Errorf("Cannot set new diff value for key %s: %s", key, err)
	}

	d.updatedKeys[key] = true

	return nil
}
1153889
func (m *MockContainerAPIClient) ContainerDiff(ctx context.Context, container string) ([]containerpkg.ContainerChangeResponseItem, error) {
	ret := m.ctrl.Call(m, "ContainerDiff", ctx, container)
	ret0, _ := ret[0].([]containerpkg.ContainerChangeResponseItem)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
1145274
func (d *Differ) Diff(obj Object, printer Printer) error {
	if err := d.From.Print(obj, printer); err != nil {
		return err
	}
	if err := d.To.Print(obj, printer); err != nil {
		return err
	}
	return nil
}