Refine a complete diff down to its useful information
@param  {Object} diff Too much information about a diff
@return {Object}      Just enough information about a diff
962996
function extractDiffData(diff) {
  print(['Extract diff for ', clc.yellow.bold(`${diff.user}/${diff.repo}#${diff.number}`), clc.white.italic(` (${diff.title})`)], debug);
  return {
    user: diff.user,
    repo: diff.repo,
    title: diff.title,
    number: diff.number,
    link: diff.link,
    createdAt: diff.createdAt,
    updatedAt: diff.updatedAt,
    labels: diff.labels,
    aheadBy: diff.ahead_by,
    behindBy: diff.behind_by,
    status: diff.status,
    totalCommits: diff.total_commits,
    author: {
      login: diff.merge_base_commit.author ? diff.merge_base_commit.author.login : 'Unknown',
      avatarUrl: diff.merge_base_commit.author ? diff.merge_base_commit.author.avatar_url : '',
    },
    files: diff.files.map((file) => {
      return {
        filename: file.filename,
        status: file.status,
        additions: file.additions,
        deletions: file.deletions,
        changes: file.changes,
        patch: analyzePatch(file.patch || '')
      };
    })
  };
}
884518
def diff(self, old, new, rel_path=None):
        
        full_url_or_path = self.__url_or_path
        if rel_path is not None:
            full_url_or_path += '/' + rel_path
        diff_result = self.run_command(
            'diff',
            ['--old', '{0}@{1}'.format(full_url_or_path, old),
             '--new', '{0}@{1}'.format(full_url_or_path, new)],
            do_combine=True)
        file_to_diff = {}
        for non_empty_diff in filter(None, diff_result.decode('utf8').split('Index: ')):
            split_diff = non_empty_diff.split('==')
            file_to_diff[split_diff[0].strip().strip('/')] = split_diff[-1].strip('=').strip()
        diff_summaries = self.diff_summary(old, new, rel_path)
        for diff_summary in diff_summaries:
            diff_summary['diff'] = \
                file_to_diff[diff_summary['path'].split(full_url_or_path)[-1].strip('/')]
        return diff_summaries
260143
function diff(a, b, shallow, isOwn) {

            if (a === b) {
                return equalObj(a);
            }

            var diffValue = {};
            var equal = true;

            for (var key in a) {
                if ((!isOwn && key in b) || (isOwn && typeof b != 'undefined' && b.hasOwnProperty(key))) {
                    if (a[key] === b[key]) {
                        diffValue[key] = equalObj(a[key]);
                    } else {
                        if (!shallow && isValidAttr(a[key], b[key])) {
                            var valueDiff = diff(a[key], b[key], shallow, isOwn);
                            if (valueDiff.changed == 'equal') {
                                diffValue[key] = equalObj(a[key]);
                            } else {
                                equal = false;
                                diffValue[key] = valueDiff;
                            }
                        } else {
                            equal = false;
                            diffValue[key] = {
                                changed: 'primitive change',
                                removed: a[key],
                                added: b[key]
                            }
                        }
                    }
                } else {
                    equal = false;
                    diffValue[key] = {
                        changed: 'removed',
                        value: a[key]
                    }
                }
            }

            for (key in b) {
                if ((!isOwn && !(key in a)) || (isOwn && typeof a != 'undefined' && !a.hasOwnProperty(key))) {
                    equal = false;
                    diffValue[key] = {
                        changed: 'added',
                        value: b[key]
                    }
                }
            }

            if (equal) {
                return equalObj(a);
            } else {
                return {
                    changed: 'object change',
                    value: diffValue
                }
            }
        }
482243
function convertDiff (diff) {
  var converted = []
  var index = 0

  for (var i = 0; i < diff.length; i += 1) {
    var change = diff[i]

    if (!change.added && !change.removed) {
      index += change.items.length
      continue
    }

    var next = diff[i + 1]
    if (next && change.removed && next.added) {
      var changeLen = change.items.length
      var nextLen = next.items.length
      var len = Math.min(changeLen, nextLen)
      converted.push({
        items: next.items.slice(0, len),
        index: index,
        added: true,
        removed: true
      })

      index += len

      if (changeLen < nextLen) {
        converted.push({
          items: next.items.slice(len),
          index: index,
          added: true,
          removed: false
        })
        index += nextLen - len
      } else if (nextLen < changeLen) {
        converted.push({
          items: change.items.slice(len),
          index: index,
          added: false,
          removed: true
        })
      }

      i += 1
      continue
    }

    converted.push({
      items: change.items.slice(),
      index: index,
      added: change.added,
      removed: change.removed
    })

    if (change.added) {
      index += change.items.length
    }
  }

  return converted
}
8775
def _make_diff(old, new, both):
    
    # make a copy of old topology to avoid tampering with it
    diff_edges = new.copy()
    not_different = [tuple(edge) for edge in both]
    diff_edges.remove_edges_from(not_different)
    # repeat operation with nodes
    diff_nodes = new.copy()
    not_different = []
    for new_node in new.nodes():
        if new_node in old.nodes():
            not_different.append(new_node)
    diff_nodes.remove_nodes_from(not_different)
    # return tuple with modified graphs
    # one for nodes and one for links
    return diff_nodes, diff_edges
551844
function inlineDiff (actual, expected, formatAdd, formatRem) {
  var result = diff.diffWordsWithSpace(actual, expected)
    .map(function (line, idx) {
      if (line.added) { return formatLinesWith(formatAdd, line.value) }
      return line.removed
        ? formatLinesWith(formatRem, line.value)
        : line.value
    })
    .join('')

  var lines = result.split('\n')
  if (lines.length > 4) {
    result = lines
      .map(function (line, idx) {
        return lpad(idx + 1, String(lines.length).length) + ' | ' + line
      })
      .join('\n')
  }

  return formatRem('actual') + ' ' + formatAdd('expected') + '\n\n' + result
}
567567
function diffDataProps(props, oldProps) {
  if (oldProps === null) {
    return 'oldProps is null, initial diff';
  }

  // Support optional app defined comparison of data
  const {dataComparator} = props;
  if (dataComparator) {
    if (!dataComparator(props.data, oldProps.data)) {
      return 'Data comparator detected a change';
    }
    // Otherwise, do a shallow equal on props
  } else if (props.data !== oldProps.data) {
    return 'A new data container was supplied';
  }

  return null;
}
800050
function getDiffForPR(pr) {
  print(['Get diff for PR ', clc.yellow.bold(`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`)], debug);
  return new Promise((resolve) => {
    github.repos.compareCommits({
      user: pr.head.user.login,
      repo: pr.head.repo.name,
      head: pr.head.ref,
      base: pr.base.ref
    }, (err, diff) => {
      if (err && debug) {
        print(['Error fetching diffs for PR ', clc.red.bold`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`], debug);
      }
      diff.user = pr.head.user.login;
      diff.repo = pr.head.repo.name;
      diff.title = pr.title;
      diff.number = pr.number;
      diff.link = pr._links.html.href;
      diff.createdAt = pr.created_at;
      diff.createdAt = pr.updated_at;
      diff.labels = pr.labels;
      return resolve(extractDiffData(diff));
    });
  });
}
642322
function analyzeDiff (diff, sha, conf) {
  var options = _.merge({
    "onProgress": function onProgress (err, result, todo) {
      if (err) {
        console.error("[Github-Todos] Error", err);
      } else if (result && result.type === "comment") {
        console.log("[Github-Todos] Added comment to issue #%s (%s) - %s", result.issue, result.title, result.url);
      } else if (result && result.type === "issue") {
        console.log("[Github-Todos] Created issue #%s (%s) - %s", result.number, result.title, result.url);
      } else if (!result) {
        console.log("[Github-Todos] Skipped - \"%s\"", todo.title);
      } else {
        console.error("[Github-Todos] Unknown result", result);
      }
      if (result && result.url && conf["open-url"]) {
        open(result.url);
      }
    }
  }, conf);

  function done (/* injectedIssues */) {
    if (process.env.DRY_RUN) {
      console.error("[Github-Todos] Dry Run: Aborting git push");
      process.exit(123);
    } else {
      console.log("[Github-Todos] OK.");
    }
  }

  return todos.fromDiff(conf.repo, diff, sha, options).spread(function (results, todos) {
    if (!conf["inject-issue"]) {
      return false;
    }

    console.log("[Github-Todos] Injecting issue numbers to files…");

    return git.dirty().then(null, function (err) {
      // Ignore error but warn user
      if (process.env.DEBUG) {
        console.error(err.stack || err);
      }
      console.error("[Github-Todos] Warning: could not check if repository is dirty");
      return false;
    }).then(function (dirty) {
      var injects = generateInjects(todos, results);

      if (process.env.DRY_RUN) {
        throw new Error("Simulated execution (DRY_RUN set)");
      }

      return stash(dirty)()
        .then(injectIssues(injects))
        .then(add)
        .then(commit)
        .then(unstash(dirty))
        .then(null, function (err) {
          console.error("[Github-Todos] Warning: failed injecting issues, you may need to do it manually in following files:");
          console.error("[Github-Todos] %s", err);
          _.each(injects, function (inject) {
            console.log("[Github-Todos]  * %s, line %s: Issue #%s", inject.file, inject.line, inject.issue);
          });
        });
    });
  }).then(done);
}
406172
def checkdiff(a,b,sp=True):
  ''
  if sp: a=splitpreserve(a); b=splitpreserve(b)
  res=applydiff(a,rediff(a,b))
  if sp: res=''.join(res)
  return res
969505
def diff_a_thing(thing, opt):
    """"""
    changed = thing.diff()
    if changed == ADD:
        print("%s %s" % (maybe_colored("+", "green", opt), str(thing)))
    elif changed == DEL:
        print("%s %s" % (maybe_colored("-", "red", opt), str(thing)))
    elif changed == CHANGED:
        print("%s %s" % (maybe_colored("~", "yellow", opt), str(thing)))
    elif changed == OVERWRITE:
        print("%s %s" % (maybe_colored("+", "yellow", opt), str(thing)))
    elif changed == CONFLICT:
        print("%s %s" % (maybe_colored("!", "red", opt), str(thing)))

    if changed != OVERWRITE and changed != NOOP:
        maybe_details(thing, opt)
541381
def is_diff(self):
        """"""
        if not isinstance(self.details, dict):
            return False

        for key in ['additions', 'updates', 'deletions']:
            if self.details.get(key, None):
                return True

        return False
1075184
function prettifyDiffObj(diff) {
    const obj = {
        kind: undefined,
        path: undefined,
        expect: undefined,
        actual: undefined,
        index: undefined,
        item: undefined,
    };
    if (diff.kind) {
        switch (diff.kind) {
            case 'N':
                obj.kind = 'New';
                break;
            case 'D':
                obj.kind = 'Missing';
                break;
            case 'E':
                obj.kind = 'Changed';
                break;
            case 'A':
                obj.kind = 'Array Canged';
                break;
        }
    }
    if (diff.path) {
        let path = diff.path[0];
        for (let i = 1; i < diff.path.length; i++) {
            path += `/${diff.path[i]}`;
        }
        obj.path = path;
    }
    if (typeof diff.lhs !== 'undefined') {
        obj.expect = diff.lhs;
    }
    if (typeof diff.rhs !== 'undefined') {
        obj.actual = diff.rhs;
    }
    if (diff.index) {
        obj.index = diff.index;
    }
    if (diff.item) {
        obj.item = prettifyDiffObj(diff.item);
    }
    return obj;
}
539529
def diff(self, a_ref, target=None, b_ref=None):
    
    result = {}
    diff_dct = self.scm.get_diff_trees(a_ref, b_ref=b_ref)
    result[DIFF_A_REF] = diff_dct[DIFF_A_REF]
    result[DIFF_B_REF] = diff_dct[DIFF_B_REF]
    if diff_dct[DIFF_EQUAL]:
        result[DIFF_EQUAL] = True
        return result
    result[DIFF_LIST] = []
    diff_outs = _get_diff_outs(self, diff_dct)
    if target is None:
        result[DIFF_LIST] = [
            _diff_royal(self, path, diff_outs[path]) for path in diff_outs
        ]
    elif target in diff_outs:
        result[DIFF_LIST] = [_diff_royal(self, target, diff_outs[target])]
    else:
        msg = "Have not found file/directory '{}' in the commits"
        raise FileNotInCommitError(msg.format(target))
    return result
713932
def diff(self):
        """"""

        if not self.present:
            if self.existing:
                return DEL

            return NOOP

        is_diff = NOOP
        if self.present and self.existing:
            a_obj = self.config.copy()
            if self.config and diff_dict(a_obj, self.existing, True):
                is_diff = CHANGED

            if self.description != self.existing.get('description'):
                is_diff = CONFLICT

        elif self.present and not self.existing:
            is_diff = ADD

        return is_diff
918150
def diff_cleanupEfficiency(self, diffs):
    
    changes = False
    equalities = []  # Stack of indices where equalities are found.
    lastEquality = None  # Always equal to diffs[equalities[-1]][1]
    pointer = 0  # Index of current position.
    pre_ins = False  # Is there an insertion operation before the last equality.
    pre_del = False  # Is there a deletion operation before the last equality.
    post_ins = False  # Is there an insertion operation after the last equality.
    post_del = False  # Is there a deletion operation after the last equality.
    while pointer < len(diffs):
      if diffs[pointer][0] == self.DIFF_EQUAL:  # Equality found.
        if (len(diffs[pointer][1]) < self.Diff_EditCost and
            (post_ins or post_del)):
          # Candidate found.
          equalities.append(pointer)
          pre_ins = post_ins
          pre_del = post_del
          lastEquality = diffs[pointer][1]
        else:
          # Not a candidate, and can never become one.
          equalities = []
          lastEquality = None

        post_ins = post_del = False
      else:  # An insertion or deletion.
        if diffs[pointer][0] == self.DIFF_DELETE:
          post_del = True
        else:
          post_ins = True

        # Five types to be split:
        # <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
        # <ins>A</ins>X<ins>C</ins><del>D</del>
        # <ins>A</ins><del>B</del>X<ins>C</ins>
        # <ins>A</del>X<ins>C</ins><del>D</del>
        # <ins>A</ins><del>B</del>X<del>C</del>

        if lastEquality and ((pre_ins and pre_del and post_ins and post_del) or
                             ((len(lastEquality) < self.Diff_EditCost / 2) and
                              (pre_ins + pre_del + post_ins + post_del) == 3)):
          # Duplicate record.
          diffs.insert(equalities[-1], (self.DIFF_DELETE, lastEquality))
          # Change second copy to insert.
          diffs[equalities[-1] + 1] = (self.DIFF_INSERT,
              diffs[equalities[-1] + 1][1])
          equalities.pop()  # Throw away the equality we just deleted.
          lastEquality = None
          if pre_ins and pre_del:
            # No changes made which could affect previous entry, keep going.
            post_ins = post_del = True
            equalities = []
          else:
            if len(equalities):
              equalities.pop()  # Throw away the previous equality.
            if len(equalities):
              pointer = equalities[-1]
            else:
              pointer = -1
            post_ins = post_del = False
          changes = True
      pointer += 1

    if changes:
      self.diff_cleanupMerge(diffs)
657872
function deepDiff(a, b, r, reversible) {
	_.each(a, function(v, k) {
	  // already checked this or equal...
	  if (r.hasOwnProperty(k) || b[k] === v) return;
	  // but what if it returns an empty object? still attach?
	  r[k] = _.isObject(v) ? _.diff(v, b[k], reversible) : v;
	});
}