This commit is contained in:
40
src/http_convert/highlighter.py
Normal file
40
src/http_convert/highlighter.py
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
from rich.syntax import Syntax
|
||||||
|
from rich.console import Console
|
||||||
|
from io import StringIO
|
||||||
|
|
||||||
|
|
||||||
|
class SyntaxHighlighter:
|
||||||
|
THEMES = {
|
||||||
|
"curl": "bash",
|
||||||
|
"httpie": "bash",
|
||||||
|
"fetch": "javascript",
|
||||||
|
"axios": "javascript",
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def highlight(code: str, format: str) -> str:
|
||||||
|
theme = SyntaxHighlighter.THEMES.get(format.lower(), "bash")
|
||||||
|
|
||||||
|
try:
|
||||||
|
syntax = Syntax(code, theme, word_wrap=True)
|
||||||
|
console = Console(file=StringIO(), force_terminal=True, width=120)
|
||||||
|
console.print(syntax)
|
||||||
|
return console.file.getvalue()
|
||||||
|
except Exception:
|
||||||
|
return code
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def highlight_curl(code: str) -> str:
|
||||||
|
return SyntaxHighlighter.highlight(code, "curl")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def highlight_httpie(code: str) -> str:
|
||||||
|
return SyntaxHighlighter.highlight(code, "httpie")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def highlight_fetch(code: str) -> str:
|
||||||
|
return SyntaxHighlighter.highlight(code, "fetch")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def highlight_axios(code: str) -> str:
|
||||||
|
return SyntaxHighlighter.highlight(code, "axios")
|
||||||
Reference in New Issue
Block a user