def index(request): if request.method == "POST": print "=" * 100 print request print "=" * 1000 afile = request.FILES['file1'] #Check if file is PDF and Convert to text using method defined below # if afile[-3:]=='pdf': # afile = convert_pdf_to_txt(afile) print afile.name, afile.read() instance = Tuple(file1=request.FILES['file1'], file2=request.FILES['file2']) instance.save() print str(instance.file1)[1:], str(instance.file2) file1 = str(instance.file1)[2:] file2 = str(instance.file2)[2:] dire = str(settings.MEDIA_ROOT) #Used to truncate strings ccod1 = open(dire + file1).read().split('\n') if len(ccod1) >= 100: ccod1 = ccod1[:100] ccod2 = open(dire + file2).read().split('\n') if len(ccod2) >= 100: ccod2 = ccod2[:100] datastuff = process_it(file1, file2, dire) # ddifference = difference(file1, file2, dire) # data1 = open(dire+file1).read() # data2 = open(dire+file2).read() sMatcher = SequenceMatcher(None, ccod1, ccod2) fileRatio = sMatcher.ratio() * 100 matchingBlocks = sMatcher.get_matching_blocks() HtmlDiff().__init__() differenze = HtmlDiff().make_file(ccod1, ccod2) ccod1.insert(0, '') ccod2.insert(0, '') print datastuff[0][2] return render( request, 'ComparedResult\\ComparedResult.html', { 'diff': differenze, 'mblocks': matchingBlocks, 'ratio': fileRatio, 'code1': ccod1, 'code2': ccod2, 'ccode1': ["", datastuff[1][1]], 'ccode2': ["", datastuff[1][2]], 'assembly1': ["", datastuff[0][1]], 'assembly2': ["", datastuff[0][2]] }) return render( request, 'ComparedResult\\ComparedResult.html', { 'ccode1': [ "", '''<div><mark>.def __main; .scl 2; .type 32; .endef</mark><br>.LC0:<br>.ascii "Hello world\\0"<br>.text<br>.globl main<br>.def main; .scl 2; .type 32; .endef<br>.seh_proc main<br>main:<br>pushq %rbp<br>.seh_pushreg %rbp<br>movq %rsp, %rbp<br>.seh_setframe %rbp, 0<br>subq $32, %rsp<br>.seh_stackalloc 32<br>.seh_endprologue<br>call __main<br>leaq .LC0(%rip), %rcx<br>call puts<br>movl $0, %eax<br>addq $32, %rsp<br><mark>popq %rbp</mark><br><mark>ret</mark><br><mark>.seh_endproc</mark><br><mark>.def puts; .scl 2; .type 32; .endef</mark><br></div> ''' ] })
def diff_text(text1, text2): """Generates a HTML diff table. """ text1 = text1 if text1 is not None else '' text2 = text2 if text2 is not None else '' if text1 == text2: return None lines1 = text1.split('\n') lines2 = text2.split('\n') # create a diff table with 3 lines of context table = HtmlDiff().make_table(lines1, lines2, context=True, numlines=3) # clean the table a bit (remove unneeded columns, fix styling, etc.) table = table. \ replace(' ', ' '). \ replace(' nowrap="nowrap"', ''). \ replace('rules="groups"', ''). \ replace( '<colgroup></colgroup> <colgroup></colgroup> ' + '<colgroup></colgroup>', '<colgroup></colgroup> <colgroup>') table = TABLE_CLEANUP_REGEX.sub('', table) return table
def installer_diff(request): form = DiffInstallerForm() diff_table = None installer_1_id = request.GET.get('installer_1') installer_2_id = request.GET.get('installer_2') installer_1 = None installer_2 = None if installer_1_id and installer_2_id: installer_1 = get_object_or_404(Installer, id=installer_1_id) installer_2 = get_object_or_404(Installer, id=installer_2_id) i1_lines = installer_1.content.split('\n') i2_lines = installer_2.content.split('\n') diff = HtmlDiff(tabsize=2, wrapcolumn=64) diff_table = diff.make_table(i1_lines, i2_lines) return render( request, 'installers/diff.html', { 'form': form, 'diff_table': diff_table, 'installer_1': installer_1, 'installer_2': installer_2 })
def PromptUserToAcceptDiff(old_text, new_text, prompt): """Displays a difference in two strings (old and new file contents) to the user and asks whether the new version is acceptable. Args: old_text: A string containing old file contents. new_text: A string containing new file contents. prompt: Text that should be displayed to the user, asking whether the new file contents should be accepted. Returns: True is user accepted the changes or there were no changes, False otherwise. """ logging.info('Computing diff...') if old_text == new_text: logging.info('No changes detected') return True html_diff = HtmlDiff(wrapcolumn=80).make_file(old_text.splitlines(), new_text.splitlines(), fromdesc='Original', todesc='Updated', context=True, numlines=5) temp = NamedTemporaryFile(suffix='.html', delete=False) try: temp.write(html_diff) temp.close() # Close the file so the browser process can access it. webbrowser.open('file://' + temp.name) print prompt response = raw_input('(Y/n): ').strip().lower() finally: temp.close() # May be called on already closed file. os.remove(temp.name) return response == 'y' or response == ''
def create_diff(csv1, csv2, diff_output_file, context, numlines): """creates a html source code file with diff details context, set to True for contextual differences (defaults to False which shows full differences i.e. the whole file. Lines that have changes and also those that don't have any changes). numlines, number of context lines. When context is set to True, controls number of lines(extra lines) displayed before and after the lines where the changes have been made. When context is False, controls the number of lines to place the "next" link anchors before the next change in the diff html file (so click of "next" link jumps to just before the change). It basically is used to position the "next" anchor tag a particular number of lines before the change. """ html_diff = HtmlDiff() try: with open(csv1, 'r', encoding="ISO-8859-1") as file1, \ open(csv2, 'r', encoding="ISO-8859-1") as file2, \ open(diff_output_file, 'w') as file3: diff_lines = html_diff.make_file(file1, file2, context=context, numlines=numlines) file3.writelines(diff_lines) return True except IOError as e: print(e, ": in create diff") return IOError
def run(self): with open(self.options['left']) as left: left_lines = left.readlines() with open(self.options['right']) as right: right_lines = right.readlines() diff = HtmlDiff() return [nodes.raw('', diff.make_table(left_lines, right_lines), format='html')]
def diff(request, group, snipName, changeId=None): snip = get_object_or_404(WikiSnip, group=group, name=snipName) if not snip.has_view_permission(): raise PermissionDenied() changeEnd = get_object_or_404( WikiSnipChange, snip=snip, pk=changeId, ) args = { 'snip': snip, 'snipName': snipName, } try: changeStart = snip.wikisnipchange_set.filter( edited__lt=changeEnd.edited, ).order_by('-edited')[0] args['prev_change'] = changeStart except IndexError: changeStart = None diffTable = ugettext("This is the first change.") try: next_change = snip.wikisnipchange_set.filter( edited__gt=changeEnd.edited, ).order_by('edited')[0] args['next_change'] = next_change except IndexError: pass if changeStart: htmlDiff = HtmlDiff(wrapcolumn=50, ) from sphene.community.templatetags.sph_extras import sph_date, sph_user_displayname desc = ugettext('%(date)s by %(editor)s') if snip.has_edit_permission(): desc += ' / <a href="%(editversionlink)s">' + ugettext( 'Edit this version') + '</a>' fromdesc = desc % { 'date': sph_date(changeStart.edited), 'editor': sph_user_displayname(changeStart.editor), 'editversionlink': changeStart.get_absolute_editurl() }, todesc = desc % { 'date': sph_date(changeEnd.edited), 'editor': sph_user_displayname(changeEnd.editor), 'editversionlink': changeEnd.get_absolute_editurl() }, diffTable = htmlDiff.make_table( changeStart.body.splitlines(1), changeEnd.body.splitlines(1), fromdesc=fromdesc, todesc=todesc, context=True, ) args['diffTable'] = mark_safe(diffTable) args['fromchange'] = changeStart args['tochange'] = changeEnd return render_to_response('sphene/sphwiki/diff.html', args, context_instance=RequestContext(request))
def email_changes(zone, prev_addrs, curr_addrs, subject, server, fromaddr, toaddr, test=False): bindformat = format_records_for_email(curr_addrs) prev_addrs = ' '.join(prev_addrs) curr_addrs = ' '.join(curr_addrs) prev = sorted([s for s in prev_addrs.split() if 'ip' in s]) curr = sorted([s for s in curr_addrs.split() if 'ip' in s]) diff = HtmlDiff() table = diff.make_table( fromlines=prev, tolines=curr, fromdesc='Old records', todesc='New records' ) header = '<h1>Diff</h1>' html = _email_style + bindformat + header + table html = MIMEText(html, 'html') msg_template = MIMEMultipart('alternative') msg_template['Subject'] = subject.format(zone=zone) email = msg_template email.attach(html) try: mailserver = smtplib.SMTP() mailserver.connect(server) mailserver.sendmail(fromaddr, toaddr, email.as_string()) except Exception as err: print('Email failed: ' + str(err)) with open('result.html', 'w+') as mailfile: mailfile.write(html.as_string()) if test: return bindformat
def default_content_diff(self, obj): return mark_safe(HtmlDiff().make_table( obj.original_default_content.split('\n')[:-1], obj.default_content.split('\n')[:-1], fromdesc=_('original default content'), todesc=_('current default content'), )) if obj.default_content_changed else '-'
def compare_files(self, param, param1): """ 对比两个word文档,并生成差异性报告 :param param: :param param1: :return: """ file1 = Document(param) file2 = Document(param1) # 分别获取段落内容 content1 = '' content2 = '' for paragraph in file1.paragraphs: if "" == paragraph.text.strip(): continue content1 += paragraph.text + '\n' for paragraph in file2.paragraphs: if "" == paragraph.text.strip(): continue content2 += paragraph.text + '\n' # 如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。 print("第二个文档数据如下:\n", content1.splitlines(keepends=False)) print("第一个文档数据如下:\n", content1.splitlines(keepends=False)) diff_html = HtmlDiff(wrapcolumn=100).make_file(content1.split("\n"), content2.split("\n")) with codecs.open('./diff_result.html', 'w', encoding='utf-8') as f: f.write(diff_html)
def change(self, id): from .models.changes import Change change = Change.query.get(id) previous = (Change.query.filter( Change.created_at < change.created_at).filter( Change.cve == change.cve).order_by( Change.created_at.desc()).first()) if previous: previous_json = previous.json else: previous_json = {} differ = HtmlDiff(wrapcolumn=100) diff = differ.make_table( json.dumps(previous_json, sort_keys=True, indent=2).split("\n"), json.dumps(change.json, sort_keys=True, indent=2).split("\n"), "Old", "New", ) return self.render("/admin/change.html", change=change, previous=previous, diff=diff)
def html_diff(old_as_text, new_as_text): # {{{1 """ returns a utf8 string containing the code of a html table showing differences of the utf8 parameters """ old_as_text = old_as_text.splitlines() new_as_text = new_as_text.splitlines() table = HtmlDiff(tabsize=4).make_table(old_as_text, new_as_text) return table.replace(' ', ' ').replace(' nowrap="nowrap"', '')
def pytest_runtest_makereport(item, call): outcome = yield report = outcome.get_result() extra = getattr(report, "extra", []) if report.when == "call" and report.outcome != "skipped": props = {k: v for k, v in report.user_properties} if "compare" in props: required, obtained = props["compare"] html_content = """ <button class="copy-button" onclick="this.nextElementSibling.select();document.execCommand('copy');this.textContent = 'Copied!';">Copy obtained output to clipboard</button> <textarea class="hidden-textarea" readonly>{}</textarea> """.format(escape(obtained)) actual = obtained.split("\n") htmldiff = HtmlDiff(2) html_content += '<h4>Diffs</h4><div class="diffs">' html_content += "<hr>".join( htmldiff.make_table( expected.split("\n"), actual, fromdesc="expected", todesc="actual", context=True, ) for expected in required) html_content += "</div>" extra.append(pytest_html.extras.html(html_content)) report.extra = extra
def main(args): """Generate diff.html file""" if not args.filename: """ print(args.file[0].name) file1 = args.file[0].name.split('/')[-1].split('.')[0] file2 = args.file[1].name.split('/')[-1].split('.')[0] filename = "diff_%s_X_%s.html" % (file1, file2) """ date_now = datetime.now() filename = 'Diff from {0:%Y}-{0:%m}-{0:%d} {0:%H}-{0:%M}-{0:%S}.html' filename = filename.format(date_now) elif not args.filename.endswith(".html"): filename = args.filename = args.filename + ".html" else: filename = args.filename with open(filename, 'w+') as output_file: first_file, second_file = args.file[0], args.file[1] diff = HtmlDiff().make_file( fromlines=first_file, tolines=second_file, fromdesc=first_file.name.split('/')[-1], todesc=second_file.name.split('/')[-1]) custom = CustomHTML() diff = custom.new_html(html=diff, args=args) output_file.write(diff) for file_open in args.file: file_open.close() print("Successful diff!\nFile: {}".format(filename))
def to_html(self, filename: str) -> None: source = self.source.splitlines(keepends=True) target = self.target.splitlines(keepends=True) diff = HtmlDiff().make_file(source, target) with open(filename, mode='w') as fd: fd.write(diff)
def main(file1, file2): d1 = read(file1) d2 = read(file2) differ = Differ() d = differ.compare(d1, d2) hd = HtmlDiff().make_file() sys.stdout.writelines(d)
def create_html_diff(from_text: str, to_text: str, from_description: str, to_description: str, *, numlines: int = 3) -> Optional[str]: """Calculate the difference between the two texts and render it as HTML. If the texts to compare are equal, `None` is returned. """ from_text = _fallback_if_none(from_text) to_text = _fallback_if_none(to_text) if from_text == to_text: return None from_lines = from_text.split('\n') to_lines = to_text.split('\n') return HtmlDiff().make_table(from_lines, to_lines, from_description, to_description, context=True, numlines=numlines)
def body_change(self): previous_commit = self.previous_commit if not previous_commit: return self.body HtmlDiff._file_template = ( """<style type="text/css">%(styles)s</style>%(table)s""" ) HtmlDiff._table_template = """ <table class="diff"> <tbody>%(data_rows)s</tbody> </table> """ HtmlDiff._styles = """ table.diff {font-family:Courier; border:medium;} .diff_header {color:#99a3a4} td.diff_header {text-align:center} .diff tbody{display: block;} .diff_next {background-color:#c0c0c0;display:none} .diff_add {background-color:#aaffaa} .diff_chg {background-color:#ffff77} .diff_sub {background-color:#ffaaaa} .diff [nowrap]{word-break: break-word;white-space: normal;width: 50%;} """ return HtmlDiff().make_file( previous_commit.body.splitlines(), self.body.splitlines() )
def changed_content_diff(self, obj): return mark_safe(HtmlDiff().make_table( obj.default_content.splitlines(), obj.changed_content.splitlines(), fromdesc=_('default content'), todesc=_('changed content'), )) if obj.changed_content else '-'
def diff( left: NDLElement, right: NDLElement, cls: Optional[Type[JSONEncoder]] = None, sorters: LIST_SORTERS = None, normalizers: NORMALIZERS = None, max_col_width: Optional[int] = 20, ) -> DiffResult: """ Show the difference of two objects. Unix like diff results. :param left: Test object :param right: Expected object :param cls: JSON Encoder if any fields aren't JSON encodable. :param sorters: Sorters for list elements. :param normalizers: Normalizers for leaf elements. :param max_col_width: Maximum column width of diff output. :return: True if match. """ if normalizers: normalizers = ( normalizers if isinstance(normalizers, list) else [normalizers] ) sorted_left = Sorter.sorted(left, sorters=sorters, normalizers=normalizers) sorted_right = Sorter.sorted(right, sorters=sorters, normalizers=normalizers) differ = HtmlDiff() result = differ.make_file( json.dumps(sorted_left, indent=2, cls=cls).split("\n"), json.dumps(sorted_right, indent=2, cls=cls).split("\n"), ) match, support = Formatter(max_col_width=max_col_width).format(result) return DiffResult(match, support)
def body_change(self): previous_body = self.previous_commit if previous_body == self.body or not previous_body: previous_body = "" else: previous_body = previous_body.body return HtmlDiff().make_file(previous_body.splitlines(), self.body.splitlines())
def diff_text(text1, text2="", title1="", title2=""): txt1 = text1.splitlines(1) txt2 = text2.splitlines(1) d = HtmlDiff() result = d.make_file(txt1, txt2, title1, title2, context=True) return result
def wip_tests(self, events:"modified_pyfiles") -> plugin.Task: """ Run tests marked with @wip tag. """ pytest_path = self.config.get(self._section_name, "pytest_path") tests_path = self.config.get(self._section_name, "tests_path") wip_mark = self.config.get(self._section_name, "wip_mark") last_wip_status = None status_change_filename = None status_change_differences = None while True: event = yield from events.get() self.log.critical("Event received in plugin `pytest`") yield from self.hub.put(self.new_event(key="wip_tests_status", status="running")) with tempfile.NamedTemporaryFile(mode="r", encoding="utf-8") as logfile: exitcode, stdout, stderr = yield from execute( pytest_path, "-r", "fesxX", "-v", "-m", wip_mark, "--result-log", logfile.name, tests_path) details = self.parse_result_file(logfile.file.read()) if exitcode == 0: status = "passed" else: status = "failed" yield from self.hub.put(self.new_event(key="wip_tests_status", status=status)) new_content = event.content or "" if last_wip_status != exitcode: old_content = self.modified_files.get(event.key, "") status_change_filename = event.key status_change_differences = HtmlDiff().make_table( old_content.splitlines(), new_content.splitlines(), context=True) last_wip_status = exitcode self.modified_files[event.key] = new_content success = (exitcode == 0) state = self.new_state(key="wip_tests", success=success, filename=status_change_filename, differences=status_change_differences, status=status, details=details, task='wip_tests' ) yield from self.hub.put(state)
def gedcom_compare(gedcom1,gedcom2): filename1 = gedcom_utils.gedcom_fullname(gedcom1) filename2 = gedcom_utils.gedcom_fullname(gedcom2) lines1 = gedcom_utils.read_gedcom(filename1) lines2 = gedcom_utils.read_gedcom(filename2) difftable = HtmlDiff().make_file(lines1, lines2, context=True, numlines=2, fromdesc=gedcom1, todesc=gedcom2) rsp = dict(diff=difftable) return jsonify(rsp)
def make_diff(old, new): """ Render in HTML the diff between two texts """ df = HtmlDiff() old_lines = old.splitlines(1) new_lines = new.splitlines(1) html = df.make_table(old_lines, new_lines, context=True) html = html.replace(' nowrap="nowrap"','') return html
def diff_table(rawinfo, newinfo): ''' Generate the difference as the table format. :param rawinfo: :param newinfo: :return: ''' return HtmlDiff.make_table(HtmlDiff(), rawinfo.split('\n'), newinfo.split('\n'), context=True, numlines=1)
def diff_html(html_dict, base_ip, other_ip): """ Uses difflib to construct a table that is the difference between the base and all of the other returned html """ diff = HtmlDiff(wrapcolumn=60) return diff.make_table( fromlines=html_dict[base_ip].splitlines(), tolines=html_dict[other_ip].splitlines(), )
async def start(self, ctx): self.add_component('detector', ChangeDetectorComponent) self.add_component('mailer', backend='smtp') await super().start(ctx) diff = HtmlDiff() async for event in ctx.detector.changed.stream_events(): difference = diff.make_file(event.old_lines, event.new_lines, context=True) await ctx.mailer.create_and_deliver( subject='Change detected in %s' % event.source.url, html_body=difference) logger.info('Sent notification email')
def compare_file(file1, file2): lines1 = get_file_content(file1) lines2 = get_file_content(file2) # 找出差异输出到result(str) html_diff = HtmlDiff() result = html_diff.make_file(lines1, lines2) # 将差异写入html文件 with open("comparison.html", "w", encoding="utf8") as f: f.write(result)
async def run(self, ctx): diff = HtmlDiff() async with aclosing(ctx.detector.changed.stream_events()) as stream: async for event in stream: difference = diff.make_file(event.old_lines, event.new_lines, context=True) await ctx.mailer.create_and_deliver( subject='Change detected in %s' % event.source.url, html_body=difference) logger.info('Sent notification email')