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() print diff.make_table(left_lines, right_lines) return [nodes.raw('', diff.make_table(left_lines, right_lines), format='html')]
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() print diff.make_table(left_lines, right_lines) 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 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 make_diff(old, new): 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 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 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 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(), )
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 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 command_autoconvert(self): dry = self.is_dry_run() from digipal_text.models import TextContentXML, TextAnnotation from digipal_text.views import viewer before = ur'' after = ur'' total = 0 converted = 0 for tcx in TextContentXML.objects.filter( text_content__type__slug='transcription').order_by('id'): total += 1 content = tcx.content if not content: continue tcx.convert() if content != tcx.content: converted += 1 text_name = u'#%s: %s [length diff = %s]' % ( tcx.id, tcx, abs(len(content) - len(tcx.content))) print text_name before += u'\n\n' before += text_name before += u'\n\n' before += content.replace('\r', '\n') after += u'\n\n' after += text_name after += u'\n\n' after += tcx.content.replace('\r', '\n') if 0: html = '' from difflib import HtmlDiff diff = HtmlDiff(tabsize=2) d = diff.make_table([content], [tcx.content]) html += u'<h2>%s</h2>' % text_name html += d if not dry: tcx.save() #break #tcx.save() dputils.write_file('before.txt', before) dputils.write_file('after.txt', after) print '%s converted out of %s texts' % (converted, total) if dry: print 'DRY RUN: no data was changed in the database.'
def htmldiff(string1, string2): txt1 = str(string1).splitlines() txt2 = str(string2).splitlines() diff = HtmlDiff(tabsize=4, wrapcolumn=80) result = diff.make_table(txt1, txt2, context=True, numlines=2) if '<td> No Differences Found </td>' in result: return _('<p>Pas de changements.</p>') else: return format_html('<div class="diff_delta">{}</div>', mark_safe(result))
def _gen_diff_html(from_title, from_lines, to_title, to_lines): """Compare two strings and string of HTML code with the output. :param from_title: Title of the left content to compare. :param from_lines: List of lines to compare. :param to_title: Title of the right content to compare. :param to_lines: List of lines to compare. :return: String of HTML code with the comparison output. """ html_template = """<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Diff {from_title} vs. {to_title}</title> <style type="text/css"> table {{font-family:Courier; border:medium}} .diff_header {{background-color:#e0e0e0; padding:0px 10px}} td.diff_header {{text-align:right}} .diff_next {{background-color:#c0c0c0; padding:0px 10px}} .diff_add {{background-color:#aaffaa}} .diff_chg {{background-color:#ffff77}} .diff_sub {{background-color:#ffaaaa}} </style> </head> <body> <table> <tr><td><table> <tr><th>Colors</th></tr> <tr><td class="diff_add">Added</td></tr> <tr><td class="diff_chg">Changed</td></tr> <tr><td class="diff_sub">Deleted</td></tr> </table></td><td><table> <tr><th>Links<th></tr> <tr><td>(f)irst change</td></tr> <tr><td>(n)ext change</td></tr> <tr><td>(t)op</td></tr> </table></td><td><table> <tr><th>Files<th></tr> <tr><td>Left: {from_title}</td></tr> <tr><td>Right: {to_title}</td></tr> </table></td></tr> </table> {diff_table} </body> </html>""" differ = HtmlDiff() filled_template = html_template.format( from_title=from_title, to_title=to_title, diff_table=differ.make_table(from_lines, to_lines), ) return filled_template
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 article_diff(request, title): article = get_object_or_404(Article, title=title) from_id = int(request.GET['from']) to_id = int(request.GET['to']) from_version = article.versions.get(number=from_id) to_version = article.versions.get(number=to_id) differ = HtmlDiff() from_body = from_version.body.raw.split('\n') to_body = to_version.body.raw.split('\n') table = differ.make_table(from_body, to_body) return render_to_response('markupwiki/article_diff.html', {'article': article, 'table':table, 'from': from_id, 'to':to_id}, context_instance=RequestContext(request))
def get_comparison(self) -> Dict[str, str]: """ Get a comparison object for use in sending emails. We have the name (key) -> HTML diff table (value). """ diff = HtmlDiff(tabsize=4, wrapcolumn=80) return { name: (diff.make_table(v['cached_content'].split('\n'), v['current_content'].split('\n'), context=True), v['url']) for name, v in self.entries.items() if v['cached_content'] is not None and v['current_content'] is not None and v['cached_content'] != v['current_content'] }
def archives(version, name, ext = None): archives = {os.path.basename(f): app.config['FILE_DECODER'][ext if ext else 'json'](open(f, 'r')) for f in glob.iglob(os.path.join(app.config['DATA_FOLDER_PATH'], 'archive', '{}.{}'.format(name, ext if ext else 'json'), '*'))} if ext: return archives # compute diff from one to another htmldiff = HtmlDiff() archives = {} last_time = 0 last_lines = [] d = os.path.join(app.config['DATA_FOLDER_PATH'], 'archive', '{}.{}'.format(name, 'json'), '*') for path in sorted(glob.iglob(d)): with open(path, 'r') as f: lines = json.dumps(json.load(f), indent = 4, separators = (',', ': '), sort_keys = True).split("\n") time = int(os.path.basename(path)) archives[time] = htmldiff.make_table(last_lines, lines, fromdesc=datetime.fromtimestamp(last_time), todesc=datetime.fromtimestamp(time)) last_time, last_lines = time, lines return render_template('archives.html', name = name, archives = archives)
def htmldiff(string1, string2): try: txt1 = string1.decode('utf-8').splitlines() # string1 is an empty SafeText from template except AttributeError: txt1 = string1.splitlines() try: txt2 = string2.decode('utf-8').splitlines() except AttributeError: txt2 = string2.splitlines() diff = HtmlDiff(tabsize=4, wrapcolumn=80) result = diff.make_table(txt1, txt2, context=True, numlines=2) if 'No Differences Found' in result: return format_html('<p>{}</p>', _('Pas de changements.')) else: return format_html('<div class="diff_delta">{}</div>', mark_safe(result))
def htmldiff(string1, string2): try: txt1 = string1.decode("utf-8").splitlines() # string1 is an empty SafeText from template except AttributeError: txt1 = string1.splitlines() try: txt2 = string2.decode("utf-8").splitlines() except AttributeError: txt2 = string2.splitlines() diff = HtmlDiff(tabsize=4) result = diff.make_table(txt1, txt2, context=True, numlines=2) if "No Differences Found" in result: return format_html("<p>{}</p>", _("Pas de changements.")) else: # the diff.make_table() replaces all spaces by non-breakable ones, which prevent line breaks: r = mark_safe(result.replace('<td nowrap="nowrap">', "<td>").replace(" ", " ")) return format_html('<div class="diff_delta">{}</div>', r)
def compare(request, rev1, rev2): page1 = get_object_or_404(Page, rev=rev1) page2 = get_object_or_404(Page, rev=rev2) # We only compare two pages if they have the same UID! if page1.uid != page2.uid: raise Http404 diffengine = HtmlDiff(tabsize=4, wrapcolumn=65) htmldiff = diffengine.make_table( fromlines=page1.content.split("\n"), tolines=page2.content.split("\n"), fromdesc=page1.name, todesc=page2.name, context=False, ) return render_to_response( settings.TEMPLATE_DIR + "compare.html", {"page1": page1, "page2": page2, "htmldiff": htmldiff, "base_site": settings.BASE_SITE}, context_instance=RequestContext(request), )
def diff(project, branch, filename): if current_user.username != get_branch_owner(project, branch): flash(_('You are not the owner of this branch'), 'error') return redirect(url_for('.view', project=project, branch=branch, filename='index.html')) merging = get_merging(project, branch) if not merging: flash(_('You are not merging'), 'error') return redirect(url_for('.view', project=project, branch=branch, filename='index.html')) #menu = menu_bar(project, branch) differ = HtmlDiff() filename, file_extension = os.path.splitext(filename) branch_source_path = join('repos', project, branch, 'source', filename + '.rst') new = string.split(load_file(branch_source_path), '\n') git_api = get_git(project, branch) if git_api.ls_tree('-r', '--name-only', branch, filename + file_extension) != '': old = string.split(git_api.show(branch + ':' + filename + file_extension), '\n') else: old = '' diff = differ.make_table(new, old) diff = string.replace(diff, 'nowrap="nowrap"', '') return render_template('diff.html', other=merging['branch'], diff=diff, filename=filename + file_extension)
def compare_orgs_task(job): job.status = 'Comparing' job.save() try: org_left = job.sorted_orgs()[0] org_right = job.sorted_orgs()[1] # Map of name to component component_type_map = {} component_map = {} # Create a list of the left component type names left_components = [] for component_type in org_left.sorted_component_types(): left_components.append(component_type.name) component_type_map['left' + component_type.name] = component_type # Append components for component in component_type.sorted_components(): left_components.append(component_type.name + '***' + component.name) component_map['left' + component_type.name + '***' + component.name] = component # Create a list of the right component type names right_components = [] for component_type in org_right.sorted_component_types(): right_components.append(component_type.name) component_type_map['right' + component_type.name] = component_type for component in component_type.sorted_components(): right_components.append(component_type.name + '***' + component.name) component_map['right' + component_type.name + '***' + component.name] = component # Start the unique list all_components_unique = list(left_components) # Add all right components that aren't in the list for component_type in right_components: if component_type not in all_components_unique: all_components_unique.append(component_type) # Sort alphabetically all_components_unique.sort() order_counter = 0 # Start to build the HTML for the table for row_value in all_components_unique: order_counter = order_counter + 1 component_result = ComponentListUnique() component_result.job = job component_result.order = order_counter component_result.save() # save now as we need ID # Generating HTML here to speed up page load performance on the front end row_html = '' if row_value in left_components and row_value not in right_components: if '***' not in row_value: row_html += '<tr class="type type_' + component_type_map[ 'left' + row_value].name + '">' row_html += '<td>' + component_type_map[ 'left' + row_value].name + '</td>' row_html += '<td></td>' row_html += '</tr>' else: row_html += '<tr class="component danger component_' + component_map[ 'left' + row_value].component_type.name + '">' row_html += '<td id="' + str( component_map['left' + row_value].id ) + '">' + component_map['left' + row_value].name + '</td>' row_html += '<td id="' + str( component_map['left' + row_value].id) + '"></td>' row_html += '</tr>' elif row_value not in left_components and row_value in right_components: if '***' not in row_value: row_html += '<tr class="type type_' + component_type_map[ 'right' + row_value].name + '">' row_html += '<td></td>' row_html += '<td>' + component_type_map[ 'right' + row_value].name + '</td>' row_html += '</tr>' else: row_html += '<tr class="component danger component_' + component_map[ 'right' + row_value].component_type.name + '">' row_html += '<td id="' + str( component_map['right' + row_value].id) + '"></td>' row_html += '<td id="' + str( component_map['right' + row_value].id) + '">' + component_map[ 'right' + row_value].name + '</td>' row_html += '</tr>' elif row_value in left_components and row_value in right_components: if '***' not in row_value: row_html += '<tr class="type type_' + component_type_map[ 'left' + row_value].name + '">' row_html += '<td>' + component_type_map[ 'left' + row_value].name + '</td>' row_html += '<td>' + component_type_map[ 'right' + row_value].name + '</td>' row_html += '</tr>' else: # If diff exists if component_map['left' + row_value].content != component_map[ 'right' + row_value].content: # Content for comparison left_content = component_map[ 'left' + row_value].content.split('\n') right_content = component_map[ 'right' + row_value].content.split('\n') # Instantiate Python diff tool diff_tool = HtmlDiff() # If contextual diff, compare results differently if job.contextual_diff: component_result.diff_html = diff_tool.make_table( left_content, right_content, context=True, numlines=7) # Otherwise, no contextual diff required else: component_result.diff_html = diff_tool.make_table( left_content, right_content) row_html += '<tr class="component warning component_' + component_map[ 'left' + row_value].component_type.name + '">' row_html += '<td id="' + str( component_result.id ) + '" class="diff">' + component_map[ 'left' + row_value].name + '</td>' row_html += '<td id="' + str( component_result.id ) + '" class="diff">' + component_map[ 'right' + row_value].name + '</td>' row_html += '</tr>' else: row_html += '<tr class="component success component_' + component_map[ 'left' + row_value].component_type.name + '">' row_html += '<td id="' + str( component_map['left' + row_value].id ) + '" class="both_same">' + component_map[ 'left' + row_value].name + '</td>' row_html += '<td id="' + str( component_map['right' + row_value].id ) + '" class="both_same">' + component_map[ 'right' + row_value].name + '</td>' row_html += '</tr>' component_result.row_html = row_html component_result.save() job.status = 'Finished' email_body = 'Your Org compare job is complete:\n' email_body += settings.APP_URL + '/compare_result/' + str( job.random_id) email_body += '\n\nYour result will be deleted after one day in order to avoid storing any metadata.' email_subject = 'Your Salesforce Org Compare results are ready.' except Exception as error: job.status = 'Error' job.error = error job.error_stacktrace = traceback.format_exc() send_error_email(job, error) job.finished_date = datetime.datetime.now() job.save() if job.email_result and job.status == 'Finished': send_mail(email_subject, email_body, settings.DEFAULT_FROM_EMAIL, [job.email], fail_silently=True)
def compare_orgs_task(job): job.status = 'Comparing' job.save() try: org_left = job.sorted_orgs()[0] org_right = job.sorted_orgs()[1] # Map of name to component component_type_map = {} component_map = {} # Create a list of the left component type names left_components = [] for component_type in org_left.sorted_component_types(): left_components.append(component_type.name) component_type_map['left' + component_type.name] = component_type # Append components for component in component_type.sorted_components(): left_components.append(component_type.name + '***' + component.name) component_map['left' + component_type.name + '***' + component.name] = component # Create a list of the right component type names right_components = [] for component_type in org_right.sorted_component_types(): right_components.append(component_type.name) component_type_map['right' + component_type.name] = component_type for component in component_type.sorted_components(): right_components.append(component_type.name + '***' + component.name) component_map['right' + component_type.name + '***' + component.name] = component # Start the unique list all_components_unique = list(left_components) # Add all right components that aren't in the list for component_type in right_components: if component_type not in all_components_unique: all_components_unique.append(component_type) # Sort alphabetically all_components_unique.sort() order_counter = 0 # Start to build the HTML for the table for row_value in all_components_unique: order_counter = order_counter + 1 component_result = ComponentListUnique() component_result.job = job component_result.order = order_counter component_result.save() # save now as we need ID # Generating HTML here to speed up page load performance on the front end row_html = '' if row_value in left_components and row_value not in right_components: if '***' not in row_value: row_html += '<tr class="type type_' + component_type_map[ 'left' + row_value].name + '">' row_html += '<td>' + component_type_map[ 'left' + row_value].name + '</td>' row_html += '<td></td>' row_html += '</tr>' else: row_html += '<tr class="component danger component_' + component_map[ 'left' + row_value].component_type.name + '">' row_html += '<td id="' + str( component_map['left' + row_value].id ) + '">' + component_map['left' + row_value].name + '</td>' row_html += '<td id="' + str( component_map['left' + row_value].id) + '"></td>' row_html += '</tr>' elif row_value not in left_components and row_value in right_components: if '***' not in row_value: row_html += '<tr class="type type_' + component_type_map[ 'right' + row_value].name + '">' row_html += '<td></td>' row_html += '<td>' + component_type_map[ 'right' + row_value].name + '</td>' row_html += '</tr>' else: row_html += '<tr class="component danger component_' + component_map[ 'right' + row_value].component_type.name + '">' row_html += '<td id="' + str( component_map['right' + row_value].id) + '"></td>' row_html += '<td id="' + str( component_map['right' + row_value].id) + '">' + component_map[ 'right' + row_value].name + '</td>' row_html += '</tr>' elif row_value in left_components and row_value in right_components: if '***' not in row_value: row_html += '<tr class="type type_' + component_type_map[ 'left' + row_value].name + '">' row_html += '<td>' + component_type_map[ 'left' + row_value].name + '</td>' row_html += '<td>' + component_type_map[ 'right' + row_value].name + '</td>' row_html += '</tr>' else: # If diff exists if component_map['left' + row_value].content != component_map[ 'right' + row_value].content: diff_tool = HtmlDiff() component_result.diff_html = diff_tool.make_table( component_map['left' + row_value].content.split('\n'), component_map['right' + row_value].content.split('\n')) row_html += '<tr class="component warning component_' + component_map[ 'left' + row_value].component_type.name + '">' row_html += '<td id="' + str( component_result.id ) + '" class="diff">' + component_map[ 'left' + row_value].name + '</td>' row_html += '<td id="' + str( component_result.id ) + '" class="diff">' + component_map[ 'right' + row_value].name + '</td>' row_html += '</tr>' else: row_html += '<tr class="component success component_' + component_map[ 'left' + row_value].component_type.name + '">' row_html += '<td id="' + str( component_map['left' + row_value].id ) + '" class="both_same">' + component_map[ 'left' + row_value].name + '</td>' row_html += '<td id="' + str( component_map['right' + row_value].id ) + '" class="both_same">' + component_map[ 'right' + row_value].name + '</td>' row_html += '</tr>' component_result.row_html = row_html component_result.save() job.status = 'Finished' email_body = 'Your Org compare job is complete:\n' email_body += 'https://sforgcompare.herokuapp.com/compare_result/' + str( job.random_id) email_body += '\n\nYour result will be deleted after one day in order to avoid storing any metadata.' email_subject = 'Your Salesforce Org Compare results are ready.' except Exception as error: job.status = 'Error' job.error = error send_error_email(job, error) job.finished_date = datetime.datetime.now() job.save() if job.email_result and job.status == 'Finished': #send_mail('Your Org Compare Results', email_body, '*****@*****.**', [job.email], fail_silently=False) message = PMMail(api_key=os.environ.get('POSTMARK_API_KEY'), subject=email_subject, sender="*****@*****.**", to=job.email, text_body=email_body, tag="orgcompareemail") message.send()
def approving(version, name, ext, timestamp): form = forms.ApprovingForm() approving_path, approving_ext, _ = find_approving(name, ext if ext else form.ext.data, timestamp) if not os.path.exists(approving_path): if ext: return 'There is no data at this endpoint.', NOT_FOUND return render_template('error.html', code = NOT_FOUND, message = message), NOT_FOUND with open(approving_path, 'r') as a: approving = app.config['FILE_DECODER'][approving_ext](a) current_path, current_ext = find_current(name, approving_ext) with open(current_path, 'r') as c: current = app.config['FILE_DECODER'][current_ext](c) if request.method == 'POST': if request.remote_addr in approving['approvers']: return 'You have already approved this data', BAD_REQUEST approving['approvers'].append(request.remote_addr) # not regressive validation form.data = JSONTextAreaField() form.data.validators.append(NotRegressive(current)) if form.validate_on_submit(): # update approving with open(approving_path, 'w') as a: app.config['FILE_ENCODER'][approving_ext](approving, a) archive_path, archive_ext, archive_timestamp = find_archive(name, ext, timestamp) # check if the approving version has more approvers than the current version if len(approving['approvers']) > len(current['approvers']): with open(current_path, 'w') as c, open(archive_path, 'w')as a: # write to archive and replace current app.config['FILE_ENCODER'][archive_ext](approving, a) app.config['FILE_ENCODER'][current_ext](approving, c) # remove approving os.remove(approving_path) return redirect(url_for('current', name = name, ext = ext)) elif ext: return {field.name: field.errors for field in form}, BAD_REQUEST if ext: return approving # compute the delta between approved and current htmldiff = HtmlDiff() approving_lines = json.dumps(approving, indent = 4).splitlines() current_lines = json.dumps(current, indent = 4).splitlines() diff = htmldiff.make_table(fromlines = current_lines, tolines = approving_lines) return render_template('approving.html', name = name, approving = approving, timestamp = timestamp, diff = diff, current = current, form = form)
def compare_orgs_task(job): job.status = 'Comparing' job.save() try: org_left = job.sorted_orgs()[0] org_right = job.sorted_orgs()[1] # Map of name to component component_type_map = {} component_map = {} # Create a list of the left component type names left_components = [] for component_type in org_left.sorted_component_types(): left_components.append(component_type.name) component_type_map['left' + component_type.name] = component_type # Append components for component in component_type.sorted_components(): left_components.append(component_type.name + '***' + component.name) component_map['left' + component_type.name + '***' + component.name] = component # Create a list of the right component type names right_components = [] for component_type in org_right.sorted_component_types(): right_components.append(component_type.name) component_type_map['right' + component_type.name] = component_type for component in component_type.sorted_components(): right_components.append(component_type.name + '***' + component.name) component_map['right' + component_type.name + '***' + component.name] = component # Start the unique list all_components_unique = list(left_components) # Add all right components that aren't in the list for component_type in right_components: if component_type not in all_components_unique: all_components_unique.append(component_type) # Sort alphabetically all_components_unique.sort() order_counter = 0 # Start to build the HTML for the table for row_value in all_components_unique: order_counter = order_counter + 1 component_result = ComponentListUnique() component_result.job = job component_result.order = order_counter component_result.save() # save now as we need ID # Generating HTML here to speed up page load performance on the front end row_html = '' if row_value in left_components and row_value not in right_components: if '***' not in row_value: row_html += '<tr class="type type_' + component_type_map['left' + row_value].name + '">' row_html += '<td>' + component_type_map['left' + row_value].name + '</td>' row_html += '<td></td>' row_html += '</tr>' else: row_html += '<tr class="component danger component_' + component_map['left' + row_value].component_type.name + '">' row_html += '<td id="' + str(component_map['left' + row_value].id) + '">' + component_map['left' + row_value].name + '</td>' row_html += '<td id="' + str(component_map['left' + row_value].id) + '"></td>' row_html += '</tr>' elif row_value not in left_components and row_value in right_components: if '***' not in row_value: row_html += '<tr class="type type_' + component_type_map['right' + row_value].name + '">' row_html += '<td></td>' row_html += '<td>' + component_type_map['right' + row_value].name + '</td>' row_html += '</tr>' else: row_html += '<tr class="component danger component_' + component_map['right' + row_value].component_type.name + '">' row_html += '<td id="' + str(component_map['right' + row_value].id) + '"></td>' row_html += '<td id="' + str(component_map['right' + row_value].id) + '">' + component_map['right' + row_value].name + '</td>' row_html += '</tr>' elif row_value in left_components and row_value in right_components: if '***' not in row_value: row_html += '<tr class="type type_' + component_type_map['left' + row_value].name + '">' row_html += '<td>' + component_type_map['left' + row_value].name + '</td>' row_html += '<td>' + component_type_map['right' + row_value].name + '</td>' row_html += '</tr>' else: # If diff exists if component_map['left' + row_value].content != component_map['right' + row_value].content: diff_tool = HtmlDiff() component_result.diff_html = diff_tool.make_table(component_map['left' + row_value].content.split('\n'), component_map['right' + row_value].content.split('\n')) row_html += '<tr class="component warning component_' + component_map['left' + row_value].component_type.name + '">' row_html += '<td id="' + str(component_result.id) + '" class="diff">' + component_map['left' + row_value].name + '</td>' row_html += '<td id="' + str(component_result.id) + '" class="diff">' + component_map['right' + row_value].name + '</td>' row_html += '</tr>' else: row_html += '<tr class="component success component_' + component_map['left' + row_value].component_type.name + '">' row_html += '<td id="' + str(component_map['left' + row_value].id) + '" class="both_same">' + component_map['left' + row_value].name + '</td>' row_html += '<td id="' + str(component_map['right' + row_value].id) + '" class="both_same">' + component_map['right' + row_value].name + '</td>' row_html += '</tr>' component_result.row_html = row_html component_result.save() job.status = 'Finished' email_body = 'Your Org compare job is complete:\n' email_body += 'https://sforgcompare.herokuapp.com/compare_result/' + str(job.random_id) email_body += '\n\nYour result will be deleted after one day in order to avoid storing any metadata.' email_subject = 'Your Salesforce Org Compare results are ready.' except Exception as error: job.status = 'Error' job.error = error send_error_email(job, error) job.finished_date = datetime.datetime.now() job.save() if job.email_result and job.status == 'Finished': #send_mail('Your Org Compare Results', email_body, '*****@*****.**', [job.email], fail_silently=False) message = PMMail(api_key = os.environ.get('POSTMARK_API_KEY'), subject = email_subject, sender = "*****@*****.**", to = job.email, text_body = email_body, tag = "orgcompareemail") message.send()
def diff_table(content_from, content_to): """Creates an HTML diff of the passed in content_from and content_to.""" html_diff = HtmlDiff(wrapcolumn=DIFF_WRAP_COLUMN) diff = html_diff.make_table(content_from.splitlines(), content_to.splitlines(), context=True) return jinja2.Markup(diff)
def diff_table(rawinfo, newinfo): return HtmlDiff.make_table(HtmlDiff(), rawinfo.split('\n'), newinfo.split('\n'), context=True, numlines=1)
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, 'games/installer-diff.html', { 'form': form, 'diff_table': diff_table, 'installer_1': installer_1, 'installer_2': installer_2 })