Perform diff on two iterables containing lines from two files, and return
    the diff as as string. Lines are normalized to str types to avoid issues
    with unicode on PY2.
329626
def get_diff(a, b, *args, **kwargs):
    '''
    
    '''
    encoding = ('utf-8', 'latin-1', __salt_system_encoding__)
    # Late import to avoid circular import
    import salt.utils.data
    return ''.join(
        difflib.unified_diff(
            salt.utils.data.decode_list(a, encoding=encoding),
            salt.utils.data.decode_list(b, encoding=encoding),
            *args, **kwargs
        )
    )
1357960
def difference(a: Iterable[Any], b: Container[Any]) -> List[Any]:
    
    d = []
    for item in a:
        if item not in b:
            d.append(item)
    return d
797550
def parse_udiff(diff, patterns=None, parent='.'):
    """"""
    # For each file of the diff, the entry key is the filename,
    # and the value is a set of row numbers to consider.
    rv = {}
    path = nrows = None
    for line in diff.splitlines():
        if nrows:
            if line[:1] != '-':
                nrows -= 1
            continue
        if line[:3] == '@@ ':
            hunk_match = HUNK_REGEX.match(line)
            (row, nrows) = [int(g or '1') for g in hunk_match.groups()]
            rv[path].update(range(row, row + nrows))
        elif line[:3] == '+++':
            path = line[4:].split('\t', 1)[0]
            if path[:2] == 'b/':
                path = path[2:]
            rv[path] = set()
    return dict([(os.path.join(parent, path), rows)
                 for (path, rows) in rv.items()
                 if rows and filename_match(path, patterns)])
1098563
def compare_files(path1, path2):
    # type: (str, str) -> List[str]
    
    diff = difflib.ndiff(open(path1).readlines(), open(path2).readlines())
    return [x for x in diff if x[0] in ['-', '+', '?']]
174197
def diff(a, b):
        
        delta = diff(a, b)
        if not a:
            return delta
        for item in delta:
            if isinstance(a[item], list):
                if delta[item] == []:
                    delta[item] = {JSONUtils.DIFF_DELETE : a[item]}
                elif isinstance(delta[item], dict):
                    for key in delta[item].keys():
                        if str(key) == JSONUtils.DIFF_DELETE:
                            delta_upd = {JSONUtils.DIFF_DELETE : []}
                            for i in delta[item][key]:
                                delta_upd[JSONUtils.DIFF_DELETE].append(a[item][i])
                                delta[item] = delta_upd
        return delta
286721
function(diff) {
	var ret = [];

	diff.push({ value: '', lines: [] });  // Append an empty value to make cleanup easier

	// Formats a given set of lines for printing as context lines in a patch
	function contextLines(lines) {
		return lines.map(function(entry) { return ' ' + entry; });
	}

	var oldRangeStart = 0;
	var newRangeStart = 0;
	var curRange = [];
	var oldLine = 1;
	var newLine = 1;

	for (var i = 0; i < diff.length; i++) {
		var current = diff[i];
		var lines = current.lines || current.value.replace(/\n$/, '').split('\n');
		current.lines = lines;

		if (current.added || current.removed) {
			// If we have previous context, start with that
			if (!oldRangeStart) {
				var prev = diff[i - 1];
				oldRangeStart = oldLine;
				newRangeStart = newLine;

				if (prev) {
					curRange = contextLines(prev.lines.slice(-4));
					oldRangeStart -= curRange.length;
					newRangeStart -= curRange.length;
				}
			}

			// Output our changes
			curRange.push.apply(curRange, lines.map(function(entry) {
				return (current.added ? '+' : '-') + entry;
			}));

			// Track the updated file position
			if (current.added) {
				newLine += lines.length;
			} else {
				oldLine += lines.length;
			}
		} else {
			// Identical context lines. Track line changes
			if (oldRangeStart) {
				// Close out any changes that have been output (or join overlapping)
				if (lines.length <= 8 && i < diff.length - 2) {
					// Overlapping
					curRange.push.apply(curRange, contextLines(lines));
				} else {
					// end the range and output
					var contextSize = Math.min(lines.length, 4);
					ret.push(
						'@@ -' + oldRangeStart + ',' + (oldLine - oldRangeStart + contextSize)
						+ ' +' + newRangeStart + ',' + (newLine - newRangeStart + contextSize)
						+ ' @@');
					ret.push.apply(ret, curRange);
					ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));

					oldRangeStart = 0;
					newRangeStart = 0;
					curRange = [];
				}
			}
			oldLine += lines.length;
			newLine += lines.length;
		}
	}

	return ret.join('\n') + '\n';
}
1345713
def diff_texts(left, right, diff_options=None, formatter=None):
    """"""
    return _diff(etree.fromstring, left, right,
                 diff_options=diff_options, formatter=formatter)
1104633
def get_diff_text(old, new, filename):
    """"""
    newline = '\n'
    diff = difflib.unified_diff(
        old, new,
        'original/' + filename,
        'fixed/' + filename,
        lineterm=newline)

    text = ''
    for line in diff:
        text += line

        # Work around missing newline (http://bugs.python.org/issue2142).
        if text and not line.endswith(newline):
            text += newline + r'\ No newline at end of file' + newline

    return text
541459
def diff(path_from, path_to, ignore_empty = False):
  
  fh_from = open(path_from, 'rb')
  fh_to = open(path_to, 'rb')
  diffs = file_diff(fh_from, fh_to, ignore_empty)
  fh_to.close()
  fh_from.close()
  return diffs
263734
def diff_analysis(using):
    
    python_analysis = collect_analysis(using)
    es_analysis = existing_analysis(using)
    return compare_dicts(es_analysis, python_analysis)
976410
def _diff(text_0, text_1):
    """"""
    diff = difflib.ndiff(text_0.splitlines(), text_1.splitlines())
    return _diff_removed_lines(diff)
478333
def _diff(self, dir1, dir2):
        

        self._dcmp = self._compare(dir1, dir2)

        if self._dcmp.left_only:
            self.log('Only in %s' % dir1)
            for x in sorted(self._dcmp.left_only):
                self.log('>> %s' % x)
            self.log('')

        if self._dcmp.right_only:
            self.log('Only in %s' % dir2)
            for x in sorted(self._dcmp.right_only):
                self.log('<< %s' % x)
            self.log('')

        if self._dcmp.common:
            self.log('Common to %s and %s' % (self._dir1, self._dir2))
            for x in sorted(self._dcmp.common):
                self.log('-- %s' % x)
        else:
            self.log('No common files or sub-directories!')
696253
def diff_missed_lines(self, filename):
        
        line_changed = []
        for line in self.file_source(filename):
            if line.status is not None:
                is_new = not line.status
                line_changed.append((line.number, is_new))
        return line_changed
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
592882
function diff($from_lines, $to_lines)
    {
        array_walk($from_lines, array('Text_Diff', 'trimNewlines'));
        array_walk($to_lines, array('Text_Diff', 'trimNewlines'));

        $temp_dir = Text_Diff::_getTempDir();

        // Execute gnu diff or similar to get a standard diff file.
        $from_file = tempnam($temp_dir, 'Text_Diff');
        $to_file = tempnam($temp_dir, 'Text_Diff');
        $fp = fopen($from_file, 'w');
        fwrite($fp, implode("\n", $from_lines));
        fclose($fp);
        $fp = fopen($to_file, 'w');
        fwrite($fp, implode("\n", $to_lines));
        fclose($fp);
        $diff = shell_exec($this->_diffCommand . ' ' . $from_file . ' ' . $to_file);
        unlink($from_file);
        unlink($to_file);

        if (is_null($diff)) {
            // No changes were made
            return array(new Text_Diff_Op_copy($from_lines));
        }

        $from_line_no = 1;
        $to_line_no = 1;
        $edits = array();

        // Get changed lines by parsing something like:
        // 0a1,2
        // 1,2c4,6
        // 1,5d6
        preg_match_all('#^(\d+)(?:,(\d+))?([adc])(\d+)(?:,(\d+))?$#m', $diff,
            $matches, PREG_SET_ORDER);

        foreach ($matches as $match) {
            if (!isset($match[5])) {
                // This paren is not set every time (see regex).
                $match[5] = false;
            }

            if ($match[3] == 'a') {
                $from_line_no--;
            }

            if ($match[3] == 'd') {
                $to_line_no--;
            }

            if ($from_line_no < $match[1] || $to_line_no < $match[4]) {
                // copied lines
                assert($match[1] - $from_line_no == $match[4] - $to_line_no);
                array_push($edits,
                    new Text_Diff_Op_copy(
                        $this->_getLines($from_lines, $from_line_no, $match[1] - 1),
                        $this->_getLines($to_lines, $to_line_no, $match[4] - 1)));
            }

            switch ($match[3]) {
            case 'd':
                // deleted lines
                array_push($edits,
                    new Text_Diff_Op_delete(
                        $this->_getLines($from_lines, $from_line_no, $match[2])));
                $to_line_no++;
                break;

            case 'c':
                // changed lines
                array_push($edits,
                    new Text_Diff_Op_change(
                        $this->_getLines($from_lines, $from_line_no, $match[2]),
                        $this->_getLines($to_lines, $to_line_no, $match[5])));
                break;

            case 'a':
                // added lines
                array_push($edits,
                    new Text_Diff_Op_add(
                        $this->_getLines($to_lines, $to_line_no, $match[5])));
                $from_line_no++;
                break;
            }
        }

        if (!empty($from_lines)) {
            // Some lines might still be pending. Add them as copied
            array_push($edits,
                new Text_Diff_Op_copy(
                    $this->_getLines($from_lines, $from_line_no,
                                     $from_line_no + count($from_lines) - 1),
                    $this->_getLines($to_lines, $to_line_no,
                                     $to_line_no + count($to_lines) - 1)));
        }

        return $edits;
    }
305651
def run_diff(self):
        
        files = tuple(self.files)
        # Use same header as more.
        header, footer = (termcolor.colored("{0}\n{{}}\n{0}\n".format(
            ":" * 14), "cyan"), "\n") if len(files) > 1 else ("", "")

        for file in files:
            print(header.format(file), end="")
            try:
                results = self._check(file)
            except Error as e:
                termcolor.cprint(e.msg, "yellow", file=sys.stderr)
                continue

            # Display results
            if results.diffs:
                print()
                print(*self.diff(results.original, results.styled), sep="\n")
                print()
                conjunction = "And"
            else:
                termcolor.cprint("Looks good!", "green")
                conjunction = "But"

            if results.diffs:
                for type, c in sorted(self._warn_chars):
                    color, verb = ("on_green", "insert") if type == "+" else ("on_red", "delete")
                    termcolor.cprint(c, None, color, end="")
                    termcolor.cprint(" means that you should {} a {}.".format(
                        verb, "newline" if c == "\\n" else "tab"), "yellow")

            if results.comment_ratio < results.COMMENT_MIN:
                termcolor.cprint("{} consider adding more comments!".format(conjunction), "yellow")

            if (results.comment_ratio < results.COMMENT_MIN or self._warn_chars) and results.diffs:
                print()
231717
def raw_diff(self):
        
        udiff_copy = self.copy_iterator()
        if self.__format == 'gitdiff':
            udiff_copy = self._parse_gitdiff(udiff_copy)
        return u''.join(udiff_copy)