def get_diff_html(feedstock_path, remote_org): repo = GitRepo(feedstock_path) diff_cf_text = repo.diff(f'{remote_org}/master', 'recipe') diff_origin_text = repo.diff('origin/master', 'recipe') formatter = HtmlFormatter(cssclass='diff') diff_cf_html = highlight(diff_cf_text, DiffLexer(), formatter) diff_origin_html = highlight(diff_origin_text, DiffLexer(), formatter) return diff_cf_html, diff_origin_html
def show_diff(request, sha=None, parent_sha=None, wiki=None, path=None): dajax = Dajax() if not sha or not wiki: return dajax.json() # Retrieve git repository try: w = Wiki.objects.get(slug=wiki) except Wiki.DoesNotExist: return dajax.json() if parent_sha and path: diff = w.repo.git.diff(parent_sha, sha, '--', path.encode('utf-8')).decode('utf-8') elif parent_sha and not path: diff = w.repo.git.diff(parent_sha, sha).decode('utf-8') elif not parent_sha and path: diff = w.repo.git.diff(sha, '--', path.encode('utf-8')).decode('utf-8') else: diff = w.repo.git.diff(sha).decode('utf-8') dajax.assign('#diff', 'innerHTML', highlight(diff, DiffLexer(), HtmlFormatter(cssclass='codehilite'))) return dajax.json()
def show(result: list) -> int: ''' Show test results :param result: List of result objects :return: Error code ''' # TODO gui show Error = 0 for name, res in result: print(f"{basename(name)}: ", end="") if isinstance(res, Exception) or isinstance(res, str): print(f"{res}") Error |= 1 elif hasattr(res, "send"): print(f"Output differs") if all((os.isatty(1), highlight, DiffLexer, TerminalFormatter, os.getenv("TERM"), os.getenv("TERM") != "dumb")): print(highlight("".join(res), DiffLexer(), TerminalFormatter())) else: sys.stdout.writelines(res) Error |= 2 else: print("OK") print() return Error
def diff_data(version, version_old): """Function to display pretty version of our data""" # Convert the data to sorted, indented JSON json_data1 = json.loads(version.serialized_data) response1 = json.dumps(json_data1, sort_keys=True, indent=2) if version_old: json_data2 = json.loads(version_old.serialized_data) response2 = json.dumps(json_data2, sort_keys=True, indent=2) else: response2 = "[]" response = difflib.unified_diff(response2.splitlines(), response1.splitlines()) response = "\n".join(response) # Get the Pygments formatter formatter = HtmlFormatter(style="colorful") # Highlight the data response = highlight(response, DiffLexer(), formatter) # Get the stylesheet style = "<style>" + formatter.get_style_defs() + "</style><br>" # Safe the output return mark_safe(style + response)
def log(request, name, path='/', rev=None): resp, r, rc = check_acl(request, name, path) if resp is not None: return resp o = svn.LOG(r, rev, limit=-1) e = o.log.logentry rc.author = get_author(getattr(e, 'author', '')) rc.mtime = parse_datetime(str(e.date)) rc.msg = unicode(e.msg) paths = e.paths if type(paths) != list: paths = [paths] cfiles = [] for p in e.paths: path = {'dir':p['kind'] == 'dir' and True or False, 'action':p['action'], 'name':unicode(p)} cfiles.append(path) rc.cfiles = cfiles rc.rev = rev content = svn.DIFF(r, rev) if content is not None and len(content) > 0: hf = HtmlFormatter(encoding='utf8') rc.content_style = hf.get_style_defs('.highlight') rc.content = highlight(safe_esc(force_unicode(content)), DiffLexer(), hf) return send_response(request, 'repos/view_log.html')
def view_diff(self, request, object_id, mode="u", r1=None, r2=None): o = get_object_or_404(Object.get_object_class(self.repo), id=int(object_id)) if not o.has_access(request.user): return self.response_forbidden("Access denied") if request.POST: r1 = request.POST.get("r1", r1) r2 = request.POST.get("r2", r2) if r1 and r2: rev1 = o.find_revision(r1) rev2 = o.find_revision(r2) if mode == "2": d1 = o.get_revision(rev1) d2 = o.get_revision(rev2) d = difflib.HtmlDiff() diff = d.make_table(d1.splitlines(), d2.splitlines()) diff = diff.replace("rules=\"groups\"", "rules=\"none\"", 1) # Use no colgroup rules else: diff = o.diff(rev1, rev2) diff = unicode(diff, "utf8") diff = highlight(diff, DiffLexer(), NOCHtmlFormatter()) # Highlight diff return self.render(request, "diff.html", { "o": o, "diff": diff, "r1": r1, "r2": r2, "mode": mode }) else: return self.response_redirect_to_object(o)
def get_diff(request, entity_id, r1, r2): entity = get_object_or_404(Entity, id=entity_id) diff = entity.metadata.get_diff(r1, r2) formatter = HtmlFormatter(linenos=True) html = HTML_WRAPPER % (entity_id, u'%s:%s' % (r1, r2), highlight(diff, DiffLexer(), formatter)) return HttpResponse(html.encode(settings.DEFAULT_CHARSET))
def send_main_email(self): if not self.get_needs_main_email(): return extra = self.get_project_extra() if extra: extra = "/" + extra else: extra = "" subject = "[" + projectshort + extra + "] " + self.get_subject() html_body = None body = self.get_body() if len(body) < MAX_HTML_BODY_SIZE: try: if self.get_format_body_html(): html_body = highlight( body, DiffLexer(encoding='latin1'), HtmlFormatter(full=True, noclasses=True, nobackground=True, encoding='latin1')) except UnicodeDecodeError: html_body = None self.mailer.send(subject, body, html_body)
def render_diff(content): lexer = DiffLexer() content = content.replace("\ No newline at end of file\n", "") html = highlight( content, lexer, HtmlFormatter(linenos=True, lineanchors='L', anchorlinenos=True)) return html
def highlighted(self): from django.utils.safestring import mark_safe from pygments import highlight from pygments.formatters import HtmlFormatter from pygments.lexers import DiffLexer return mark_safe(highlight(self.text, DiffLexer(), HtmlFormatter()))
def get(self, request, *args, **kwargs): deploy_id = kwargs["deploy"] headers = {'authorization': request.session.get('tsuru_token')} url = "{0}/deploys/{1}".format(settings.TSURU_HOST, deploy_id) response = requests.get(url, headers=headers) context = {"deploy": response.json()} format = HtmlFormatter() diff_output = highlight(context["deploy"]["Diff"], DiffLexer(), format) context["deploy"]["Diff"] = diff_output return TemplateResponse(request, "deploys/deploy_details.html", context)
def __get_files_to_diff(self): """ """ groups = self.__get_lst_files() diffs_content = [ highlight(bloc, DiffLexer(), HtmlFormatter(cssclass=u'source', style=u'colorful')) for bloc in re.split(u"\n*diff -r [a-z0-9]{8,20} [^\n]+\n", self.raw_diff) if bloc.strip() ] return dict(zip(groups, diffs_content))
def _html_version(diff_output, method='udiff'): """Convert the given diff output to HTML if needed.""" with io.StringIO() as diff_f: diff_f.writelines(diff_output) diff_output = diff_f.getvalue() if diff_output: diff_html = (highlight( diff_output, DiffLexer(), HtmlFormatter( full=True)) if method == 'udiff' else diff_output) else: diff_html = None return diff_html
def diff(self): cmd = "cd %s && git diff %s^1..%s" % (self.branch.project.root, self.name, self.name) diff = Popen(cmd, shell=True, stdout=PIPE).stdout.read() diff = diff.decode("utf8", "ignore") from pygments import highlight from pygments.lexers import DiffLexer from pygments.formatters import HtmlFormatter from jinja2 import Markup return Markup(highlight(diff, DiffLexer(), HtmlFormatter()))
def _print_output(self, output1, output2): output1 = output1.splitlines(1) output2 = output2.splitlines(1) diff = ''.join(difflib.unified_diff(output1, output2)) print print 'Diff....' print print highlight(diff, DiffLexer(), Formatter()) return diff
def main(args=None): args = prepare_parser().parse_args(args=args) commands = parse_file(args.infile) errors = check_commands(commands, no_expected_means_empty_out=args.empty, raise_error=args.raise_error) if not errors: print("Everything looks ok!!") return 0 for error in errors: print(highlight(error, DiffLexer(), Terminal256Formatter())) return 1
def diff_view(request, domain, id): result = get_object_or_404(Result, id=id, domain=domain) context = {} html_formatter = HtmlFormatter(linenos=True, lineanchors='L', linespans='L', anchorlinenos=True) context['code'] = highlight(diff_table(result.before, result.after), DiffLexer(), html_formatter) context['domain'] = domain context['result'] = result context['pygments_css'] = html_formatter.get_style_defs('.highlight') return render(request, 'analyzer/diff_view.html', context)
def diff(self): """ Show changes to be written to the file. (diff between the current and the new config.) """ # Split new and existing content in lines current_content = self.current_content.splitlines(1) new_content = self.content.splitlines(1) # Call difflib diff = ''.join(difflib.unified_diff(current_content, new_content)) print highlight(diff, DiffLexer(), Formatter()) return diff
def item_description(self, item): entity = item['entity'] current = item['revision']['versionid'] formatter = HtmlFormatter(linenos=True, outencoding=settings.DEFAULT_CHARSET) if 'previous' in item['revision']: previous = item['revision']['previous'] diff = entity.metadata.get_diff(previous, current) html = highlight(diff, DiffLexer(), formatter) else: xml = entity.metadata.get_revision(current) html = highlight(xml, XmlLexer(), formatter) return html
def diff(request, name, revN, revM, path='/'): resp, r, rc = check_acl(request, name, path) if resp is not None: return resp content = svn.DIFF(r, revN, revM) if content is not None and len(content) > 0: hf = HtmlFormatter(encoding='utf8') rc.content_style = hf.get_style_defs('.highlight') rc.content = highlight(safe_esc(force_unicode(content)), DiffLexer(), hf) rc.revN = revN rc.revM = revM return send_response(request, 'repos/view_diff.html')
def test(docstr, fname): fmt = compute_new_doc(docstr, fname) dold = docstr.splitlines() dnew = fmt.splitlines() diffs = list( difflib.unified_diff(dold, dnew, n=100, fromfile=fname, tofile=fname), ) if diffs: from pygments import highlight from pygments.lexers import DiffLexer from pygments.formatters import TerminalFormatter code = "\n".join(w(diffs)) hldiff = highlight(code, DiffLexer(), TerminalFormatter()) print(indent(hldiff, " | ", predicate=lambda x: True))
def prepare(self): super(Patch, self).prepare() self.package = self.kwds['package'] self.subpackage_of = self.kwds.get('subpackage_of') self.patch = self.kwds['patch'] self.branch = self.kwds['branch'] if self.subpackage_of: main_package = self.subpackage_of else: main_package = self.package repo = FedoraGitRepo(main_package, branch=self.branch) diff = repo.get_patch(self.patch) if self.diffstat: self.diffstat = repo.get_diffstat(self.patch) self.text = highlight(diff, DiffLexer(), HtmlFormatter(full=True, nobackground=True)) self.changelog = repo.get_patch_changelog(self.patch)
def get_context_data(self, *args, **kwargs): deploy_id = kwargs['deploy'] context = super(DeployInfo, self).get_context_data(*args, **kwargs) url = '{}/deploys/{}'.format(settings.TSURU_HOST, deploy_id) response = requests.get(url, headers=self.authorization) context['deploy'] = response.json() diff = context['deploy'].get('Diff') if diff and diff != u'The deployment must have at least two commits for the diff.': format = HtmlFormatter() diff = highlight(diff, DiffLexer(), format) else: diff = None context['deploy']['Diff'] = diff return context
def print_diff(path: Path, old: TextDocument, new: TextDocument) -> None: """Print ``black --diff`` style output for the changes""" relative_path = path.resolve().relative_to(Path.cwd()).as_posix() diff = "\n".join( line.rstrip("\n") for line in unified_diff( old.lines, new.lines, relative_path, relative_path)) if sys.stdout.isatty(): try: from pygments import highlight from pygments.formatters import TerminalFormatter from pygments.lexers import DiffLexer except ImportError: print(diff) else: print(highlight(diff, DiffLexer(), TerminalFormatter())) else: print(diff)
def _style_diff(self, diff): """Return a syntax-highlighted version of the diff. Args: diff (bytes): The raw diff content. Returns: django.utils.safestring.SafeText: The syntax-highlighted HTML. """ # NOTE: Django wraps the contents in a <p>, but browsers will # be sad about that, because it contains a <pre>. Chrome, # for instance, will move it out into its own node. Be # consistent and just make that happen for them. return format_html( '</p>{0}<p>', mark_safe(highlight(diff, DiffLexer(), HtmlFormatter())))
def diffmenu(outputfile, diffout): print "[Continue, Abort, View, Replace?] ", response = sys.stdin.readline() rchar = response[0].upper() if rchar == 'C': return elif rchar == 'A': sys.exit(-1) elif rchar == 'V': print highlight(diffout, DiffLexer(), TerminalFormatter(bg="dark")) diffmenu(outputfile, diffout) elif rchar == 'R': dest = 'expected/' + outputfile copy(outputfile, dest) else: print "Please enter a valid option: ", diffmenu(sourcefile, diffout)
def get_context_data(self, **kwargs): deploy_id = kwargs["deploy"] url = "{}/deploys/{}".format(settings.TSURU_HOST, deploy_id) response = requests.get(url, headers=self.authorization) if response.status_code > 399: raise Http404("Deploy does not exist") context = {"deploy": response.json()} diff = context["deploy"].get("Diff") if diff and diff != u'The deployment must have at least two commits for the diff.': format = HtmlFormatter() diff = highlight(diff, DiffLexer(), format) else: diff = None context["deploy"]["Diff"] = diff return context
def get_diff_html(snapshots): html = '' for new, old in zip(snapshots, snapshots[1:]): old_date = '{} ({})'.format(old[0].replace(microsecond=0), humanize.naturaltime(old[0])) new_date = '{} ({})'.format(new[0].replace(microsecond=0), humanize.naturaltime(new[0])) diff_text = '\n'.join( difflib.unified_diff( old[1], new[1], fromfiledate=old_date, tofiledate=new_date, n=5, lineterm='', )) html += highlight(diff_text, DiffLexer(), HtmlFormatter()) return html
def get(self, first_rev, second_rev): before = self.db.get(self.table_name, first_rev) after = self.db.get(self.table_name, second_rev) if not (before and after): raise NotFound() if before["date"] > after[ "date"]: # Check whether the before was created after the after raise BadRequest() if before["id"] == after["id"]: # The same revision has been requested raise BadRequest() before_text = before["post"]["rst"] after_text = after["post"]["rst"] if not before_text.endswith("\n"): before_text += "\n" if not after_text.endswith("\n"): after_text += "\n" before_text = before_text.splitlines(keepends=True) after_text = after_text.splitlines(keepends=True) if not before["slug"] == after["slug"]: raise BadRequest() # The revisions are not from the same post diff = difflib.unified_diff(before_text, after_text, fromfile=f"{first_rev}.rst", tofile=f"{second_rev}.rst") diff = "".join(diff) diff = highlight(diff, DiffLexer(), HtmlFormatter()) return self.render("wiki/compare_revision.html", title=after["post"]["title"], page=before["slug"], diff=diff, slug=before["slug"], can_edit=self.is_staff())
def _handle_metadata_post(request, form, return_view): if form.is_valid(): if request.is_ajax(): # validation of metadata and diff calculation diff = form.get_diff() html = highlight(diff, DiffLexer(), HtmlFormatter(linenos=True)) return HttpResponse(html.encode(settings.DEFAULT_CHARSET)) else: # after validation and when user has added the commit message if 'button_clicked' in request.POST and request.POST[ 'button_clicked'] != '': action = request.POST['button_clicked'] else: action = None form.save(action) messages.success(request, _get_success_message(action)) return_url = reverse(return_view, args=(form.entity.id, )) return HttpResponseRedirect(return_url) else: messages.error(request, _('Please correct the errors indicated below')) if request.is_ajax(): sorted_errors = {} for field, errors in form.errors.items(): sorted_error_list = [] for error in errors: if ':ERROR:' in error or ':FATAL:' in error: sorted_error_list.insert(0, error) else: sorted_error_list.append(error) sorted_errors[field] = sorted_error_list content = render_to_string( 'entity/validation_errors.html', { 'errors': sorted_errors, }, context_instance=RequestContext(request)) return HttpResponseBadRequest(content)