gh-htmlpreview 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gh_htmlpreview/__init__.py +18 -0
- gh_htmlpreview/__main__.py +3 -0
- gh_htmlpreview/browser.py +87 -0
- gh_htmlpreview/cli.py +148 -0
- gh_htmlpreview/exceptions.py +6 -0
- gh_htmlpreview/github.py +214 -0
- gh_htmlpreview/server.py +345 -0
- gh_htmlpreview/urls.py +40 -0
- gh_htmlpreview-0.1.0.dist-info/METADATA +191 -0
- gh_htmlpreview-0.1.0.dist-info/RECORD +13 -0
- gh_htmlpreview-0.1.0.dist-info/WHEEL +4 -0
- gh_htmlpreview-0.1.0.dist-info/entry_points.txt +3 -0
- gh_htmlpreview-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import importlib.metadata
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import tomllib
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _version() -> str:
|
|
7
|
+
# Source checkout, as run by the gh extension
|
|
8
|
+
pyproject = Path(__file__).resolve().parents[2] / "pyproject.toml"
|
|
9
|
+
if pyproject.is_file():
|
|
10
|
+
project = tomllib.loads(pyproject.read_text(encoding="utf-8")).get("project", {})
|
|
11
|
+
if project.get("name") == "gh-htmlpreview":
|
|
12
|
+
return project["version"]
|
|
13
|
+
return importlib.metadata.version("gh-htmlpreview")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
__version__ = _version()
|
|
17
|
+
|
|
18
|
+
__all__ = ["__version__"]
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
from collections.abc import Callable, Mapping
|
|
2
|
+
import os
|
|
3
|
+
import shlex
|
|
4
|
+
import subprocess
|
|
5
|
+
import sys
|
|
6
|
+
import threading
|
|
7
|
+
from typing import Protocol
|
|
8
|
+
from urllib.parse import urlsplit
|
|
9
|
+
import webbrowser
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Process(Protocol):
|
|
13
|
+
def wait(self) -> int: ...
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class LaunchError(Exception):
|
|
17
|
+
"""The browser couldn't be launched."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def skip_reason(
|
|
21
|
+
url: str, env: Mapping[str, str] = os.environ, platform: str = sys.platform
|
|
22
|
+
) -> str | None:
|
|
23
|
+
"""Explain why the default browser shouldn't be opened, or return None if it should."""
|
|
24
|
+
if env.get("SSH_CONNECTION") or env.get("SSH_TTY"):
|
|
25
|
+
port = urlsplit(url).port
|
|
26
|
+
return (
|
|
27
|
+
"Not opening a browser in an SSH session. To view it from your machine, forward "
|
|
28
|
+
f"the port with 'ssh -L {port}:127.0.0.1:{port} HOST' and open the URL above. "
|
|
29
|
+
"Use -p to keep the same port."
|
|
30
|
+
)
|
|
31
|
+
if platform.startswith("linux") and not (env.get("DISPLAY") or env.get("WAYLAND_DISPLAY")):
|
|
32
|
+
return "Not opening a browser because neither DISPLAY nor WAYLAND_DISPLAY is set."
|
|
33
|
+
return None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _gh_config_browser(run: Callable[..., subprocess.CompletedProcess[str]]) -> str | None:
|
|
37
|
+
try:
|
|
38
|
+
result = run(
|
|
39
|
+
["gh", "config", "get", "browser"], capture_output=True, text=True, timeout=10
|
|
40
|
+
)
|
|
41
|
+
except (OSError, subprocess.SubprocessError):
|
|
42
|
+
return None
|
|
43
|
+
if result.returncode != 0:
|
|
44
|
+
return None
|
|
45
|
+
return result.stdout.strip() or None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def resolve_launcher(
|
|
49
|
+
env: Mapping[str, str] = os.environ,
|
|
50
|
+
run: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
|
|
51
|
+
) -> str | None:
|
|
52
|
+
"""Find the browser command the way gh does: GH_BROWSER, gh's browser config, BROWSER."""
|
|
53
|
+
if launcher := env.get("GH_BROWSER", "").strip():
|
|
54
|
+
return launcher
|
|
55
|
+
if launcher := _gh_config_browser(run):
|
|
56
|
+
return launcher
|
|
57
|
+
return env.get("BROWSER", "").strip() or None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def open_url(
|
|
61
|
+
url: str,
|
|
62
|
+
launcher: str | None,
|
|
63
|
+
popen: Callable[..., Process] = subprocess.Popen,
|
|
64
|
+
default: Callable[[str], bool] = webbrowser.open,
|
|
65
|
+
) -> None:
|
|
66
|
+
"""Open the URL with a browser command, or the system default browser if it's None.
|
|
67
|
+
|
|
68
|
+
A browser command is started without waiting for it to exit.
|
|
69
|
+
"""
|
|
70
|
+
if launcher is None:
|
|
71
|
+
try:
|
|
72
|
+
opened = default(url)
|
|
73
|
+
except webbrowser.Error as e:
|
|
74
|
+
raise LaunchError(f"Couldn't open the default browser: {e}.") from e
|
|
75
|
+
if not opened:
|
|
76
|
+
raise LaunchError("No default browser found.")
|
|
77
|
+
return
|
|
78
|
+
try:
|
|
79
|
+
args = shlex.split(launcher)
|
|
80
|
+
except ValueError as e:
|
|
81
|
+
raise LaunchError(f"Couldn't parse browser command {launcher!r}: {e}.") from e
|
|
82
|
+
try:
|
|
83
|
+
# A new session keeps Ctrl-C in the terminal from reaching the browser.
|
|
84
|
+
process = popen([*args, url], stdin=subprocess.DEVNULL, start_new_session=True)
|
|
85
|
+
except OSError as e:
|
|
86
|
+
raise LaunchError(f"Couldn't run browser command {launcher!r}: {e.strerror or e}.") from e
|
|
87
|
+
threading.Thread(target=process.wait, daemon=True).start()
|
gh_htmlpreview/cli.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
from collections.abc import Sequence
|
|
3
|
+
from datetime import timedelta
|
|
4
|
+
from functools import partial
|
|
5
|
+
import re
|
|
6
|
+
import sys
|
|
7
|
+
from typing import NoReturn
|
|
8
|
+
|
|
9
|
+
from gh_htmlpreview import __version__, browser, github, urls
|
|
10
|
+
from gh_htmlpreview.exceptions import NotFound, UpstreamError
|
|
11
|
+
from gh_htmlpreview.server import HOST, PreviewServer
|
|
12
|
+
|
|
13
|
+
_NUMBER = r"\d+(?:\.\d+)?"
|
|
14
|
+
_DURATION_PART = re.compile(rf"({_NUMBER})([smh])")
|
|
15
|
+
_DURATION_PATTERN = re.compile(rf"(?:{_NUMBER}[smh])+|{_NUMBER}")
|
|
16
|
+
_UNIT_SECONDS = {"s": 1, "m": 60, "h": 3600}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def parse_duration(value: str) -> float:
|
|
20
|
+
"""Parse a duration like '90s', '10m', '1h30m' or '600' into seconds."""
|
|
21
|
+
text = value.strip()
|
|
22
|
+
if _DURATION_PATTERN.fullmatch(text) is None:
|
|
23
|
+
raise argparse.ArgumentTypeError(
|
|
24
|
+
f"Unable to parse {value!r} as a duration. Use numbers with units s, m or h, such "
|
|
25
|
+
"as '90s', '10m' or '1h30m', or a number of seconds without a unit."
|
|
26
|
+
)
|
|
27
|
+
parts = _DURATION_PART.findall(text)
|
|
28
|
+
if parts:
|
|
29
|
+
seconds = sum(float(number) * _UNIT_SECONDS[unit] for number, unit in parts)
|
|
30
|
+
else:
|
|
31
|
+
seconds = float(text)
|
|
32
|
+
if seconds <= 0:
|
|
33
|
+
raise argparse.ArgumentTypeError(f"Duration must be positive, got {value!r}.")
|
|
34
|
+
try:
|
|
35
|
+
timedelta(seconds=seconds)
|
|
36
|
+
except OverflowError:
|
|
37
|
+
raise argparse.ArgumentTypeError(f"Duration is too long, got {value!r}.") from None
|
|
38
|
+
return seconds
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _port(value: str) -> int:
|
|
42
|
+
try:
|
|
43
|
+
port = int(value)
|
|
44
|
+
except ValueError:
|
|
45
|
+
raise argparse.ArgumentTypeError(f"Port must be an integer, got {value!r}.") from None
|
|
46
|
+
if not 0 <= port <= 65535:
|
|
47
|
+
raise argparse.ArgumentTypeError(f"Port must be between 0 and 65535, got {port}.")
|
|
48
|
+
return port
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _parser(prog: str) -> argparse.ArgumentParser:
|
|
52
|
+
parser = argparse.ArgumentParser(
|
|
53
|
+
prog=prog,
|
|
54
|
+
allow_abbrev=False,
|
|
55
|
+
description="Preview an HTML file from a GitHub repository in your browser.",
|
|
56
|
+
)
|
|
57
|
+
parser.add_argument("url", metavar="URL", help="GitHub URL of the file to preview.")
|
|
58
|
+
parser.add_argument(
|
|
59
|
+
"-t",
|
|
60
|
+
"--timeout",
|
|
61
|
+
default="30m",
|
|
62
|
+
type=parse_duration,
|
|
63
|
+
metavar="DURATION",
|
|
64
|
+
help=(
|
|
65
|
+
"Time to keep the server alive after the most recent request, such as '90s', '10m' "
|
|
66
|
+
"or '1h30m'. A number without a unit is seconds. (default: %(default)s)"
|
|
67
|
+
),
|
|
68
|
+
)
|
|
69
|
+
parser.add_argument(
|
|
70
|
+
"-p",
|
|
71
|
+
"--port",
|
|
72
|
+
default=0,
|
|
73
|
+
type=_port,
|
|
74
|
+
help="Port to use. (default: 0, chosen by the operating system)",
|
|
75
|
+
)
|
|
76
|
+
parser.add_argument(
|
|
77
|
+
"-n",
|
|
78
|
+
"--no-browser",
|
|
79
|
+
action="store_true",
|
|
80
|
+
help="Print the URL without opening a browser.",
|
|
81
|
+
)
|
|
82
|
+
parser.add_argument(
|
|
83
|
+
"--version", action="version", version=__version__, help="Show version and exit."
|
|
84
|
+
)
|
|
85
|
+
return parser
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def open_browser(url: str) -> None:
|
|
89
|
+
"""Open the URL with the configured browser command, or the default browser unless
|
|
90
|
+
there's a reason not to. Failures are reported only.
|
|
91
|
+
"""
|
|
92
|
+
launcher = browser.resolve_launcher()
|
|
93
|
+
if launcher is None and (reason := browser.skip_reason(url)) is not None:
|
|
94
|
+
print(reason, flush=True)
|
|
95
|
+
return
|
|
96
|
+
try:
|
|
97
|
+
browser.open_url(url, launcher)
|
|
98
|
+
except browser.LaunchError as e:
|
|
99
|
+
print(e, file=sys.stderr, flush=True)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def main(argv: Sequence[str] | None = None, prog: str = "gh-htmlpreview") -> None:
|
|
103
|
+
"""Run the gh-htmlpreview command-line program."""
|
|
104
|
+
parser = _parser(prog)
|
|
105
|
+
args = parser.parse_args(argv)
|
|
106
|
+
try:
|
|
107
|
+
file_url = urls.parse(args.url)
|
|
108
|
+
except ValueError as e:
|
|
109
|
+
forms = "\n".join(f" {form}" for form in urls.ACCEPTED_FORMS)
|
|
110
|
+
parser.error(f"argument URL: {e}\nAccepted forms:\n{forms}")
|
|
111
|
+
|
|
112
|
+
def fail(message: str) -> NoReturn:
|
|
113
|
+
print(f"{prog}: error: {message}", file=sys.stderr)
|
|
114
|
+
sys.exit(1)
|
|
115
|
+
|
|
116
|
+
owner, repo = file_url.owner, file_url.repo
|
|
117
|
+
try:
|
|
118
|
+
client = github.Client(github.resolve_token())
|
|
119
|
+
sha, path = client.resolve(owner, repo, file_url.segments)
|
|
120
|
+
target = client.fetch(owner, repo, sha, path)
|
|
121
|
+
except (NotFound, UpstreamError) as e:
|
|
122
|
+
fail(str(e))
|
|
123
|
+
except KeyboardInterrupt:
|
|
124
|
+
sys.exit(130)
|
|
125
|
+
|
|
126
|
+
repo_commit = f"{owner}/{repo}@{sha[:7]}"
|
|
127
|
+
try:
|
|
128
|
+
server = PreviewServer(
|
|
129
|
+
partial(client.fetch, owner, repo, sha),
|
|
130
|
+
path,
|
|
131
|
+
repo_commit,
|
|
132
|
+
port=args.port,
|
|
133
|
+
seed={path: target},
|
|
134
|
+
)
|
|
135
|
+
except OSError as e:
|
|
136
|
+
fail(f"Couldn't bind to {HOST}:{args.port}: {e.strerror or e}")
|
|
137
|
+
|
|
138
|
+
timeout = timedelta(seconds=args.timeout)
|
|
139
|
+
with server:
|
|
140
|
+
print(f"Serving {repo_commit}:{path} at {server.url}")
|
|
141
|
+
print(f"Shutting down after {timeout} without requests. Press Ctrl-C to stop.", flush=True)
|
|
142
|
+
try:
|
|
143
|
+
if not args.no_browser:
|
|
144
|
+
open_browser(server.url)
|
|
145
|
+
server.serve_until_idle(args.timeout)
|
|
146
|
+
print(f"No requests for {timeout}. Stopped.")
|
|
147
|
+
except KeyboardInterrupt:
|
|
148
|
+
print(" Stopped.")
|
gh_htmlpreview/github.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from email.message import Message
|
|
4
|
+
import http.client
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import subprocess
|
|
9
|
+
from typing import Protocol
|
|
10
|
+
import urllib.error
|
|
11
|
+
from urllib.parse import quote, urlsplit
|
|
12
|
+
import urllib.request
|
|
13
|
+
|
|
14
|
+
from gh_htmlpreview import __version__
|
|
15
|
+
from gh_htmlpreview.exceptions import NotFound, UpstreamError
|
|
16
|
+
|
|
17
|
+
API_URL = "https://api.github.com"
|
|
18
|
+
RAW_URL = "https://raw.githubusercontent.com"
|
|
19
|
+
TIMEOUT_SECONDS = 30
|
|
20
|
+
|
|
21
|
+
_SHA_PATTERN = re.compile(r"[0-9a-f]{40}")
|
|
22
|
+
_QUALIFIED_REF_PREFIXES = (("refs", "heads"), ("refs", "tags"))
|
|
23
|
+
_AUTH_HINT = "If it's a private repository, run 'gh auth login' or set GH_TOKEN."
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Response(Protocol):
|
|
27
|
+
@property
|
|
28
|
+
def headers(self) -> Message: ...
|
|
29
|
+
|
|
30
|
+
def read(self) -> bytes: ...
|
|
31
|
+
|
|
32
|
+
def close(self) -> None: ...
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class _SameHostAuthRedirectHandler(urllib.request.HTTPRedirectHandler):
|
|
36
|
+
"""Keeps the Authorization header on a redirect only if it stays on the same HTTPS host."""
|
|
37
|
+
|
|
38
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
39
|
+
new = super().redirect_request(req, fp, code, msg, headers, newurl)
|
|
40
|
+
auth = req.get_header("Authorization")
|
|
41
|
+
if new is not None and auth is not None:
|
|
42
|
+
old_parts, new_parts = urlsplit(req.full_url), urlsplit(new.full_url)
|
|
43
|
+
if new_parts.scheme == "https" and new_parts.netloc == old_parts.netloc:
|
|
44
|
+
new.add_unredirected_header("Authorization", auth)
|
|
45
|
+
return new
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class Token:
|
|
50
|
+
value: str
|
|
51
|
+
source: str
|
|
52
|
+
"""Where the token came from, for error messages."""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def resolve_token(
|
|
56
|
+
env: Mapping[str, str] = os.environ,
|
|
57
|
+
run: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
|
|
58
|
+
) -> Token | None:
|
|
59
|
+
"""Find a GitHub token from the environment or the GitHub CLI."""
|
|
60
|
+
for name in ("GH_TOKEN", "GITHUB_TOKEN"):
|
|
61
|
+
value = env.get(name, "").strip()
|
|
62
|
+
if value:
|
|
63
|
+
return Token(value, name)
|
|
64
|
+
try:
|
|
65
|
+
result = run(
|
|
66
|
+
["gh", "auth", "token", "--hostname", "github.com"],
|
|
67
|
+
capture_output=True,
|
|
68
|
+
text=True,
|
|
69
|
+
timeout=10,
|
|
70
|
+
)
|
|
71
|
+
except (OSError, subprocess.SubprocessError):
|
|
72
|
+
return None
|
|
73
|
+
if result.returncode != 0:
|
|
74
|
+
return None
|
|
75
|
+
value = result.stdout.strip()
|
|
76
|
+
return Token(value, "gh auth") if value else None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _quote_path(segments: Sequence[str]) -> str:
|
|
80
|
+
return "/".join(quote(s, safe="") for s in segments)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _error_detail(error: urllib.error.HTTPError) -> str | None:
|
|
84
|
+
"""The message from GitHub's JSON error body, if there is one."""
|
|
85
|
+
try:
|
|
86
|
+
body = json.loads(error.read(65536))
|
|
87
|
+
except (OSError, http.client.HTTPException, ValueError):
|
|
88
|
+
return None
|
|
89
|
+
if isinstance(body, dict) and isinstance(body.get("message"), str):
|
|
90
|
+
return body["message"].strip() or None
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class Client:
|
|
95
|
+
"""Resolves refs and fetches files from GitHub.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
token: Token to authenticate with. Without one, files come from raw.githubusercontent.com.
|
|
99
|
+
transport: Handler that sends requests in place of urllib's HTTP handlers.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
def __init__(self, token: Token | None, transport: urllib.request.BaseHandler | None = None):
|
|
103
|
+
self.token = token
|
|
104
|
+
handlers: list[urllib.request.BaseHandler] = [_SameHostAuthRedirectHandler()]
|
|
105
|
+
if transport is not None:
|
|
106
|
+
handlers.append(transport)
|
|
107
|
+
self._opener = urllib.request.build_opener(*handlers)
|
|
108
|
+
|
|
109
|
+
def resolve(self, owner: str, repo: str, segments: Sequence[str]) -> tuple[str, str]:
|
|
110
|
+
"""Split segments into a ref and a file path, and resolve the ref to a commit SHA.
|
|
111
|
+
|
|
112
|
+
Returns the commit SHA and the file path.
|
|
113
|
+
"""
|
|
114
|
+
start = 3 if tuple(segments[:2]) in _QUALIFIED_REF_PREFIXES else 1
|
|
115
|
+
for end in range(start, len(segments)):
|
|
116
|
+
ref = segments[:end]
|
|
117
|
+
url = f"{API_URL}/repos/{_quote_path([owner, repo])}/commits/{_quote_path(ref)}"
|
|
118
|
+
try:
|
|
119
|
+
body = self._get(url, accept="application/vnd.github.sha")
|
|
120
|
+
except urllib.error.HTTPError as e:
|
|
121
|
+
if e.code == 422:
|
|
122
|
+
continue
|
|
123
|
+
if e.code == 404:
|
|
124
|
+
if self.token is None:
|
|
125
|
+
message = f"Repository {owner}/{repo} not found. {_AUTH_HINT}"
|
|
126
|
+
else:
|
|
127
|
+
message = (
|
|
128
|
+
f"Repository {owner}/{repo} not found, or the token from "
|
|
129
|
+
f"{self.token.source} can't access it."
|
|
130
|
+
)
|
|
131
|
+
raise NotFound(message) from None
|
|
132
|
+
raise UpstreamError(self._describe_http_error(e, url)) from None
|
|
133
|
+
sha = body.decode("ascii", errors="replace").strip()
|
|
134
|
+
if not _SHA_PATTERN.fullmatch(sha):
|
|
135
|
+
raise UpstreamError(f"Unexpected response from {url}: {sha[:100]!r}")
|
|
136
|
+
# The commits API also matches SHA prefixes. Only full SHAs are accepted as refs.
|
|
137
|
+
if end == 1 and 4 <= len(ref[0]) < 40 and sha.startswith(ref[0].lower()):
|
|
138
|
+
continue
|
|
139
|
+
return sha, "/".join(segments[end:])
|
|
140
|
+
raise NotFound(
|
|
141
|
+
f"No branch, tag or commit in {owner}/{repo} matches the start of "
|
|
142
|
+
f"{'/'.join(segments)!r}."
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
def fetch(self, owner: str, repo: str, sha: str, path: str) -> bytes:
|
|
146
|
+
"""Fetch a file's contents at a commit."""
|
|
147
|
+
segments = [s for s in path.split("/") if s]
|
|
148
|
+
if not segments or any(s in (".", "..") for s in segments):
|
|
149
|
+
raise NotFound(f"Invalid file path {path!r}.")
|
|
150
|
+
if self.token is not None:
|
|
151
|
+
url = (
|
|
152
|
+
f"{API_URL}/repos/{_quote_path([owner, repo])}/contents/{_quote_path(segments)}"
|
|
153
|
+
f"?ref={quote(sha, safe='')}"
|
|
154
|
+
)
|
|
155
|
+
accept = "application/vnd.github.raw+json"
|
|
156
|
+
else:
|
|
157
|
+
url = f"{RAW_URL}/{_quote_path([owner, repo, sha, *segments])}"
|
|
158
|
+
accept = "*/*"
|
|
159
|
+
try:
|
|
160
|
+
response = self._open(url, accept=accept)
|
|
161
|
+
except urllib.error.HTTPError as e:
|
|
162
|
+
if e.code == 404:
|
|
163
|
+
raise NotFound(f"{path} not found in {owner}/{repo} at {sha[:7]}.") from None
|
|
164
|
+
raise UpstreamError(self._describe_http_error(e, url)) from None
|
|
165
|
+
try:
|
|
166
|
+
# The contents API returns a JSON listing for a directory.
|
|
167
|
+
if response.headers.get_content_type() == "application/json":
|
|
168
|
+
raise NotFound(f"{path} is a directory in {owner}/{repo}, not a file.")
|
|
169
|
+
return self._read(response, url)
|
|
170
|
+
finally:
|
|
171
|
+
response.close()
|
|
172
|
+
|
|
173
|
+
def _get(self, url: str, accept: str) -> bytes:
|
|
174
|
+
response = self._open(url, accept=accept)
|
|
175
|
+
try:
|
|
176
|
+
return self._read(response, url)
|
|
177
|
+
finally:
|
|
178
|
+
response.close()
|
|
179
|
+
|
|
180
|
+
def _open(self, url: str, accept: str) -> Response:
|
|
181
|
+
request = urllib.request.Request(url)
|
|
182
|
+
request.add_header("Accept", accept)
|
|
183
|
+
request.add_header("User-Agent", f"gh-htmlpreview/{__version__}")
|
|
184
|
+
if url.startswith(f"{API_URL}/"):
|
|
185
|
+
request.add_header("X-GitHub-Api-Version", "2022-11-28")
|
|
186
|
+
if self.token is not None:
|
|
187
|
+
request.add_unredirected_header("Authorization", f"Bearer {self.token.value}")
|
|
188
|
+
try:
|
|
189
|
+
return self._opener.open(request, timeout=TIMEOUT_SECONDS)
|
|
190
|
+
except urllib.error.HTTPError:
|
|
191
|
+
raise
|
|
192
|
+
except (OSError, http.client.HTTPException) as e:
|
|
193
|
+
raise UpstreamError(f"Couldn't connect to {urlsplit(url).netloc}: {e}") from None
|
|
194
|
+
|
|
195
|
+
def _read(self, response: Response, url: str) -> bytes:
|
|
196
|
+
try:
|
|
197
|
+
return response.read()
|
|
198
|
+
except (OSError, http.client.HTTPException) as e:
|
|
199
|
+
raise UpstreamError(f"Couldn't read response from {url}: {e}") from None
|
|
200
|
+
|
|
201
|
+
def _describe_http_error(self, error: urllib.error.HTTPError, url: str) -> str:
|
|
202
|
+
headers = error.headers
|
|
203
|
+
if error.code in (403, 429) and headers is not None:
|
|
204
|
+
if headers.get("x-ratelimit-remaining") == "0" or headers.get("retry-after"):
|
|
205
|
+
message = "GitHub rate limit exceeded."
|
|
206
|
+
if self.token is None:
|
|
207
|
+
message += " Run 'gh auth login' or set GH_TOKEN for a higher limit."
|
|
208
|
+
return message
|
|
209
|
+
detail = _error_detail(error)
|
|
210
|
+
if error.code == 401 and self.token is not None:
|
|
211
|
+
message = f"GitHub rejected the token from {self.token.source}"
|
|
212
|
+
else:
|
|
213
|
+
message = f"GitHub returned HTTP {error.code} for {url}"
|
|
214
|
+
return f"{message}: {detail}" if detail else message
|
gh_htmlpreview/server.py
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
from collections.abc import Callable, Generator, Mapping
|
|
2
|
+
from contextlib import contextmanager
|
|
3
|
+
import errno
|
|
4
|
+
import html
|
|
5
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
6
|
+
import mimetypes
|
|
7
|
+
import posixpath
|
|
8
|
+
import socket
|
|
9
|
+
import socketserver
|
|
10
|
+
import sys
|
|
11
|
+
import threading
|
|
12
|
+
import time
|
|
13
|
+
from urllib.parse import quote, unquote
|
|
14
|
+
|
|
15
|
+
from gh_htmlpreview import __version__
|
|
16
|
+
from gh_htmlpreview.exceptions import NotFound, UpstreamError
|
|
17
|
+
|
|
18
|
+
Source = Callable[[str], bytes]
|
|
19
|
+
"""Returns the contents of a file by its repository path. Raises NotFound or UpstreamError."""
|
|
20
|
+
|
|
21
|
+
HOST = "127.0.0.1"
|
|
22
|
+
|
|
23
|
+
_ADDRESS_IN_USE = tuple(
|
|
24
|
+
code
|
|
25
|
+
for name in ("EADDRINUSE", "WSAEADDRINUSE")
|
|
26
|
+
if (code := getattr(errno, name, None)) is not None
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
_CONTROL_CHARS = {c: f"\\x{c:02x}" for c in (*range(0x20), *range(0x7F, 0xA0))} | {0x5C: "\\\\"}
|
|
30
|
+
|
|
31
|
+
MIME_OVERRIDES = {
|
|
32
|
+
".html": "text/html",
|
|
33
|
+
".htm": "text/html",
|
|
34
|
+
".js": "text/javascript",
|
|
35
|
+
".mjs": "text/javascript",
|
|
36
|
+
".css": "text/css",
|
|
37
|
+
".json": "application/json",
|
|
38
|
+
".svg": "image/svg+xml",
|
|
39
|
+
".wasm": "application/wasm",
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def content_type(path: str) -> str:
|
|
44
|
+
ext = posixpath.splitext(path)[1].lower()
|
|
45
|
+
if ext in MIME_OVERRIDES:
|
|
46
|
+
mime_type = MIME_OVERRIDES[ext]
|
|
47
|
+
else:
|
|
48
|
+
mime_type, encoding = mimetypes.guess_type(path, strict=False)
|
|
49
|
+
# A compressed file, such as data.json.gz, would need a Content-Encoding.
|
|
50
|
+
if mime_type is None or encoding is not None:
|
|
51
|
+
return "application/octet-stream"
|
|
52
|
+
if mime_type.startswith("text/"):
|
|
53
|
+
return f"{mime_type}; charset=utf-8"
|
|
54
|
+
return mime_type
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def normalize_path(request_path: str) -> str | None:
|
|
58
|
+
"""Map a request path to a repository path. Returns None if it escapes the root."""
|
|
59
|
+
path = unquote(request_path.split("?", 1)[0].split("#", 1)[0])
|
|
60
|
+
segments: list[str] = []
|
|
61
|
+
for segment in path.split("/"):
|
|
62
|
+
if segment in ("", "."):
|
|
63
|
+
continue
|
|
64
|
+
if segment == "..":
|
|
65
|
+
if not segments:
|
|
66
|
+
return None
|
|
67
|
+
segments.pop()
|
|
68
|
+
else:
|
|
69
|
+
segments.append(segment)
|
|
70
|
+
if path.endswith("/") or path.split("/")[-1] in (".", ".."):
|
|
71
|
+
segments.append("index.html")
|
|
72
|
+
return "/".join(segments)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def not_found_page(target_path: str, repo_commit: str) -> str:
|
|
76
|
+
link = f'<a href="/{quote(target_path)}"><code>{html.escape(target_path)}</code></a>'
|
|
77
|
+
return (
|
|
78
|
+
"<!doctype html>\n"
|
|
79
|
+
"<title>Not found</title>\n"
|
|
80
|
+
"<h1>Not found</h1>\n"
|
|
81
|
+
f"<p>This server is previewing {link} from <code>{html.escape(repo_commit)}</code>.</p>\n"
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _prepare_socket(sock: socket.socket) -> None:
|
|
86
|
+
# On Windows, SO_REUSEADDR allows binding a port that another socket is listening on.
|
|
87
|
+
if sys.platform == "win32":
|
|
88
|
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
|
|
89
|
+
else:
|
|
90
|
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _check_port_free(port: int) -> None:
|
|
94
|
+
"""Raise the bind error if another socket holds the port on an address that receives
|
|
95
|
+
127.0.0.1 traffic. Each probe binds a throwaway socket and closes it without listening.
|
|
96
|
+
"""
|
|
97
|
+
for family, address in (
|
|
98
|
+
(socket.AF_INET, HOST),
|
|
99
|
+
(socket.AF_INET, "0.0.0.0"),
|
|
100
|
+
(socket.AF_INET6, "::"),
|
|
101
|
+
):
|
|
102
|
+
try:
|
|
103
|
+
sock = socket.socket(family, socket.SOCK_STREAM)
|
|
104
|
+
except OSError:
|
|
105
|
+
continue # Address family not supported
|
|
106
|
+
with sock:
|
|
107
|
+
_prepare_socket(sock)
|
|
108
|
+
if family == socket.AF_INET6:
|
|
109
|
+
# Dual-stack, to detect dual-stack listeners. Windows defaults to IPv6-only.
|
|
110
|
+
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
|
|
111
|
+
try:
|
|
112
|
+
sock.bind((address, port))
|
|
113
|
+
except OSError as e:
|
|
114
|
+
if e.errno in _ADDRESS_IN_USE:
|
|
115
|
+
raise
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class _NotFoundEntry:
|
|
119
|
+
pass
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class _Cache:
|
|
123
|
+
"""Caches a source's files and misses. Upstream errors aren't cached."""
|
|
124
|
+
|
|
125
|
+
def __init__(self, source: Source, seed: Mapping[str, bytes]):
|
|
126
|
+
self._source = source
|
|
127
|
+
self._entries: dict[str, bytes | _NotFoundEntry] = dict(seed)
|
|
128
|
+
self._lock = threading.Lock()
|
|
129
|
+
|
|
130
|
+
def get(self, path: str) -> bytes:
|
|
131
|
+
with self._lock:
|
|
132
|
+
entry = self._entries.get(path)
|
|
133
|
+
if entry is None:
|
|
134
|
+
try:
|
|
135
|
+
entry = self._source(path)
|
|
136
|
+
except NotFound:
|
|
137
|
+
entry = _NotFoundEntry()
|
|
138
|
+
with self._lock:
|
|
139
|
+
self._entries[path] = entry
|
|
140
|
+
if isinstance(entry, _NotFoundEntry):
|
|
141
|
+
raise NotFound(path)
|
|
142
|
+
return entry
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class _Handler(BaseHTTPRequestHandler):
|
|
146
|
+
server_version = f"gh-htmlpreview/{__version__}"
|
|
147
|
+
sys_version = ""
|
|
148
|
+
timeout = 60
|
|
149
|
+
|
|
150
|
+
def do_GET(self):
|
|
151
|
+
if self._check_request():
|
|
152
|
+
with self._server()._track_request():
|
|
153
|
+
self._serve(head=False)
|
|
154
|
+
|
|
155
|
+
def do_HEAD(self):
|
|
156
|
+
if self._check_request(head=True):
|
|
157
|
+
with self._server()._track_request():
|
|
158
|
+
self._serve(head=True)
|
|
159
|
+
|
|
160
|
+
def _method_not_allowed(self):
|
|
161
|
+
if self._check_request():
|
|
162
|
+
self._send_text(405, "Method not allowed.", extra_headers={"Allow": "GET, HEAD"})
|
|
163
|
+
|
|
164
|
+
do_POST = do_PUT = do_DELETE = do_PATCH = do_OPTIONS = _method_not_allowed
|
|
165
|
+
|
|
166
|
+
def end_headers(self):
|
|
167
|
+
self.send_header("Cache-Control", "no-store")
|
|
168
|
+
self.send_header("Cross-Origin-Resource-Policy", "same-origin")
|
|
169
|
+
self.send_header("Content-Security-Policy", "frame-ancestors 'self'")
|
|
170
|
+
self.send_header("X-Content-Type-Options", "nosniff")
|
|
171
|
+
super().end_headers()
|
|
172
|
+
|
|
173
|
+
def log_message(self, format, *args):
|
|
174
|
+
# Same as BaseHTTPRequestHandler on Python 3.12+, which escapes control characters
|
|
175
|
+
message = (format % args).translate(_CONTROL_CHARS)
|
|
176
|
+
sys.stderr.write(
|
|
177
|
+
f"{self.address_string()} - - [{self.log_date_time_string()}] {message}\n"
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
def _server(self) -> "PreviewServer":
|
|
181
|
+
assert isinstance(self.server, PreviewServer)
|
|
182
|
+
return self.server
|
|
183
|
+
|
|
184
|
+
def _check_request(self, head: bool = False) -> bool:
|
|
185
|
+
"""Send an error and return False if the request must be refused."""
|
|
186
|
+
port = self._server().port
|
|
187
|
+
# Clients leave out the default port.
|
|
188
|
+
allowed_hosts = (f"{HOST}:{port}", HOST) if port == 80 else (f"{HOST}:{port}",)
|
|
189
|
+
if self.headers.get("Host") not in allowed_hosts:
|
|
190
|
+
path = self.path if self.path.startswith("/") else "/"
|
|
191
|
+
self._send_text(
|
|
192
|
+
403, f"Forbidden host. Open http://{HOST}:{port}{path} instead.", head=head
|
|
193
|
+
)
|
|
194
|
+
return False
|
|
195
|
+
# Browsers send "none" for navigations the user started, such as opening the URL.
|
|
196
|
+
if self.headers.get("Sec-Fetch-Site", "none") not in ("same-origin", "none"):
|
|
197
|
+
self._send_text(403, "Requests from other sites aren't allowed.", head=head)
|
|
198
|
+
return False
|
|
199
|
+
if self.headers.get("Service-Worker") == "script":
|
|
200
|
+
self.log_message("Blocked service worker registration: %s", self.path)
|
|
201
|
+
self._send_text(403, "Service workers aren't allowed.", head=head)
|
|
202
|
+
return False
|
|
203
|
+
if not self.path.startswith("/"):
|
|
204
|
+
self._send_text(400, "Bad request.", head=head)
|
|
205
|
+
return False
|
|
206
|
+
return True
|
|
207
|
+
|
|
208
|
+
def _serve(self, head: bool) -> None:
|
|
209
|
+
server = self._server()
|
|
210
|
+
path = normalize_path(self.path)
|
|
211
|
+
if path is None:
|
|
212
|
+
self._send_not_found(head)
|
|
213
|
+
return
|
|
214
|
+
try:
|
|
215
|
+
body = server.cache.get(path)
|
|
216
|
+
except NotFound:
|
|
217
|
+
self._send_not_found(head)
|
|
218
|
+
return
|
|
219
|
+
except UpstreamError as e:
|
|
220
|
+
self.log_message("Error fetching %s: %s", path, e)
|
|
221
|
+
self._send_text(502, f"Error fetching {path} from GitHub.", head=head)
|
|
222
|
+
return
|
|
223
|
+
self.send_response(200)
|
|
224
|
+
self.send_header("Content-Type", content_type(path))
|
|
225
|
+
self.send_header("Content-Length", str(len(body)))
|
|
226
|
+
self.end_headers()
|
|
227
|
+
if not head:
|
|
228
|
+
self.wfile.write(body)
|
|
229
|
+
|
|
230
|
+
def _send_not_found(self, head: bool) -> None:
|
|
231
|
+
server = self._server()
|
|
232
|
+
page = not_found_page(server.target_path, server.repo_commit)
|
|
233
|
+
self._send(404, page.encode(), "text/html; charset=utf-8", head=head)
|
|
234
|
+
|
|
235
|
+
def _send_text(
|
|
236
|
+
self,
|
|
237
|
+
code: int,
|
|
238
|
+
text: str,
|
|
239
|
+
head: bool = False,
|
|
240
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
241
|
+
) -> None:
|
|
242
|
+
body = f"{text}\n".encode()
|
|
243
|
+
self._send(code, body, "text/plain; charset=utf-8", head, extra_headers)
|
|
244
|
+
|
|
245
|
+
def _send(
|
|
246
|
+
self,
|
|
247
|
+
code: int,
|
|
248
|
+
body: bytes,
|
|
249
|
+
media_type: str,
|
|
250
|
+
head: bool = False,
|
|
251
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
252
|
+
) -> None:
|
|
253
|
+
self.send_response(code)
|
|
254
|
+
self.send_header("Content-Type", media_type)
|
|
255
|
+
self.send_header("Content-Length", str(len(body)))
|
|
256
|
+
for name, value in (extra_headers or {}).items():
|
|
257
|
+
self.send_header(name, value)
|
|
258
|
+
self.end_headers()
|
|
259
|
+
if not head:
|
|
260
|
+
self.wfile.write(body)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
class PreviewServer(ThreadingHTTPServer):
|
|
264
|
+
"""Serves a repository's files from a source on 127.0.0.1, and shuts down when idle.
|
|
265
|
+
|
|
266
|
+
Args:
|
|
267
|
+
source: Returns a file's contents by repository path.
|
|
268
|
+
target_path: Repository path of the file being previewed.
|
|
269
|
+
repo_commit: Repository and commit being served, such as "owner/repo@abc1234".
|
|
270
|
+
port: Port to bind to. 0 uses a port chosen by the operating system.
|
|
271
|
+
seed: Files already fetched, by repository path.
|
|
272
|
+
"""
|
|
273
|
+
|
|
274
|
+
allow_reuse_address = False # _prepare_socket sets this per platform
|
|
275
|
+
|
|
276
|
+
def __init__(
|
|
277
|
+
self,
|
|
278
|
+
source: Source,
|
|
279
|
+
target_path: str,
|
|
280
|
+
repo_commit: str,
|
|
281
|
+
port: int = 0,
|
|
282
|
+
seed: Mapping[str, bytes] | None = None,
|
|
283
|
+
):
|
|
284
|
+
self.target_path = target_path
|
|
285
|
+
self.repo_commit = repo_commit
|
|
286
|
+
self.cache = _Cache(source, seed or {})
|
|
287
|
+
self._lock = threading.Lock()
|
|
288
|
+
self._in_flight = 0
|
|
289
|
+
self._last_activity = time.monotonic()
|
|
290
|
+
super().__init__((HOST, port), _Handler)
|
|
291
|
+
|
|
292
|
+
def server_bind(self):
|
|
293
|
+
_prepare_socket(self.socket)
|
|
294
|
+
# Probes run before the real bind. On Linux, they'd conflict with this socket after it.
|
|
295
|
+
if self.server_address[1] != 0:
|
|
296
|
+
_check_port_free(int(self.server_address[1]))
|
|
297
|
+
# Skips HTTPServer.server_bind, whose reverse DNS lookup for server_name can hang.
|
|
298
|
+
socketserver.TCPServer.server_bind(self)
|
|
299
|
+
self.server_name = HOST
|
|
300
|
+
self.server_port = self.port
|
|
301
|
+
|
|
302
|
+
@property
|
|
303
|
+
def port(self) -> int:
|
|
304
|
+
return int(self.server_address[1])
|
|
305
|
+
|
|
306
|
+
@property
|
|
307
|
+
def url(self) -> str:
|
|
308
|
+
"""URL of the file being previewed."""
|
|
309
|
+
return f"http://{HOST}:{self.port}/{quote(self.target_path)}"
|
|
310
|
+
|
|
311
|
+
@contextmanager
|
|
312
|
+
def _track_request(self) -> Generator[None, None, None]:
|
|
313
|
+
"""Mark a request as in progress. The server doesn't count as idle while any request
|
|
314
|
+
is in progress, and the idle time restarts when the last one finishes.
|
|
315
|
+
"""
|
|
316
|
+
with self._lock:
|
|
317
|
+
self._in_flight += 1
|
|
318
|
+
self._last_activity = time.monotonic()
|
|
319
|
+
try:
|
|
320
|
+
yield
|
|
321
|
+
finally:
|
|
322
|
+
with self._lock:
|
|
323
|
+
self._in_flight -= 1
|
|
324
|
+
self._last_activity = time.monotonic()
|
|
325
|
+
|
|
326
|
+
def _idle_seconds(self) -> float:
|
|
327
|
+
with self._lock:
|
|
328
|
+
if self._in_flight:
|
|
329
|
+
return 0.0
|
|
330
|
+
return time.monotonic() - self._last_activity
|
|
331
|
+
|
|
332
|
+
def serve_until_idle(self, idle_timeout: float) -> None:
|
|
333
|
+
"""Serve requests until no request has been in progress for `idle_timeout` seconds.
|
|
334
|
+
The server is shut down on return, including when interrupted by an exception such
|
|
335
|
+
as `KeyboardInterrupt`.
|
|
336
|
+
"""
|
|
337
|
+
with self._lock:
|
|
338
|
+
self._last_activity = time.monotonic()
|
|
339
|
+
threading.Thread(target=self.serve_forever, args=(0.1,), daemon=True).start()
|
|
340
|
+
try:
|
|
341
|
+
# Short sleeps keep KeyboardInterrupt responsive on all platforms.
|
|
342
|
+
while (idle := self._idle_seconds()) < idle_timeout:
|
|
343
|
+
time.sleep(min(0.5, idle_timeout - idle))
|
|
344
|
+
finally:
|
|
345
|
+
self.shutdown()
|
gh_htmlpreview/urls.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from urllib.parse import unquote, urlsplit
|
|
3
|
+
|
|
4
|
+
ACCEPTED_FORMS = (
|
|
5
|
+
"https://github.com/{owner}/{repo}/blob/{ref}/{path}",
|
|
6
|
+
"https://github.com/{owner}/{repo}/raw/{ref}/{path}",
|
|
7
|
+
"https://raw.githubusercontent.com/{owner}/{repo}/{ref}/{path}",
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class FileURL:
|
|
13
|
+
"""A file in a GitHub repository. The ref and the file path are still combined in
|
|
14
|
+
segments, because a ref can contain '/'."""
|
|
15
|
+
|
|
16
|
+
owner: str
|
|
17
|
+
repo: str
|
|
18
|
+
segments: tuple[str, ...]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def parse(url: str) -> FileURL:
|
|
22
|
+
"""Parse a GitHub URL to a file. Raises ValueError for unsupported URLs."""
|
|
23
|
+
parts = urlsplit(url.strip())
|
|
24
|
+
host = parts.netloc.lower()
|
|
25
|
+
if parts.scheme.lower() not in ("https", "http"):
|
|
26
|
+
raise ValueError(f"Unsupported URL: {url!r}")
|
|
27
|
+
segments = [s for s in unquote(parts.path).split("/") if s]
|
|
28
|
+
if any(s in (".", "..") for s in segments):
|
|
29
|
+
raise ValueError(f"Unsupported URL: {url!r}")
|
|
30
|
+
|
|
31
|
+
if host == "github.com" and len(segments) >= 3 and segments[2] in ("blob", "raw"):
|
|
32
|
+
owner, repo, _, *rest = segments
|
|
33
|
+
elif host == "raw.githubusercontent.com" and len(segments) >= 2:
|
|
34
|
+
owner, repo, *rest = segments
|
|
35
|
+
else:
|
|
36
|
+
raise ValueError(f"Unsupported URL: {url!r}")
|
|
37
|
+
|
|
38
|
+
if len(rest) < 2:
|
|
39
|
+
raise ValueError(f"URL doesn't include both a ref and a file path: {url!r}")
|
|
40
|
+
return FileURL(owner=owner, repo=repo, segments=tuple(rest))
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gh-htmlpreview
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Preview HTML files from GitHub repositories in your browser.
|
|
5
|
+
Keywords: github,gh-extension,html,preview
|
|
6
|
+
Author: Jay Qi
|
|
7
|
+
Author-email: Jay Qi <jayqi@users.noreply.github.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
19
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
|
|
20
|
+
Classifier: Topic :: Utilities
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Project-URL: Homepage, https://github.com/jayqi/gh-htmlpreview
|
|
23
|
+
Project-URL: Repository, https://github.com/jayqi/gh-htmlpreview
|
|
24
|
+
Project-URL: Changelog, https://github.com/jayqi/gh-htmlpreview/blob/main/CHANGELOG.md
|
|
25
|
+
Project-URL: Issues, https://github.com/jayqi/gh-htmlpreview/issues
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# gh-htmlpreview
|
|
29
|
+
|
|
30
|
+
[](https://github.com/jayqi/gh-htmlpreview/actions/workflows/tests.yml?query=branch%3Amain)
|
|
31
|
+
|
|
32
|
+
A GitHub CLI extension or a standalone Python CLI tool for serving a preview of an HTML file from a GitHub repository. Pass a URL for a file in a GitHub repository, and it will open your browser to a local HTTP server that serves the file and its relative assets (CSS, JavaScript, images, etc.). You can also follow links to other pages in the repository. All files are handled in memory, so no need to download files or clean them up afterwards. It can authenticate with GitHub to work with either public or private repos.
|
|
33
|
+
|
|
34
|
+
Handy for browsing things like:
|
|
35
|
+
|
|
36
|
+
- Static sites and built docs, especially in private repos
|
|
37
|
+
- Notebook and report exports from [Jupyter](https://jupyter.org/), [marimo](https://marimo.io/), [Quarto](https://quarto.org/), or [R Markdown](https://rmarkdown.rstudio.com/)
|
|
38
|
+
- Interactive charts exported to HTML, from libraries like [Plotly](https://plotly.com/), [Bokeh](https://bokeh.org/), or [Altair](https://altair-viz.github.io/)
|
|
39
|
+
- HTML prototypes and LLM-generated artifacts
|
|
40
|
+
|
|
41
|
+
> [!IMPORTANT]
|
|
42
|
+
> **Security:** The previewed page's JavaScript runs in your browser like any website's. Only preview pages from repositories you trust as much as a website you'd visit. See the [Security](#security) section for additional discussion.
|
|
43
|
+
|
|
44
|
+
> [!NOTE]
|
|
45
|
+
> What this tool does is similar to [htmlpreview.github.io](https://htmlpreview.github.io/), but it runs locally and can authenticate with your GitHub CLI login or a token. It does not route content through a third-party website, and it works for private repos. We are not affiliated in any way with htmlpreview.github.io.
|
|
46
|
+
|
|
47
|
+
## Installation
|
|
48
|
+
|
|
49
|
+
### As a GitHub CLI extension
|
|
50
|
+
|
|
51
|
+
With the [GitHub CLI](https://cli.github.com/) installed, run:
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
gh extension install jayqi/gh-htmlpreview
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The extension needs [uv](https://docs.astral.sh/uv/) or Python 3.11 or newer on your `PATH`. With uv, it finds or downloads a suitable Python itself.
|
|
58
|
+
|
|
59
|
+
The extension tracks the `main` branch; update it with `gh extension upgrade htmlpreview`. To stay on a release instead, install with `--pin`, such as `--pin v0.1.0`.
|
|
60
|
+
|
|
61
|
+
### As a standalone CLI tool
|
|
62
|
+
|
|
63
|
+
As a Python package from PyPI, with uv:
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
uvx gh-htmlpreview URL
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
or installed as a tool:
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
uv tool install gh-htmlpreview
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
It has no dependencies beyond the Python standard library.
|
|
76
|
+
|
|
77
|
+
## Usage
|
|
78
|
+
|
|
79
|
+
Copy the URL of an HTML file from GitHub and pass it in:
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
gh htmlpreview https://github.com/jayqi/gh-htmlpreview/blob/main/demo/index.html
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
```text
|
|
86
|
+
Serving jayqi/gh-htmlpreview@a64dfb7:demo/index.html at http://127.0.0.1:53817/demo/index.html
|
|
87
|
+
Shutting down after 0:30:00 without requests. Press Ctrl-C to stop.
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
The branch or tag is resolved to a commit when it starts, and every file in the session comes from that commit. The server stops after an idle timeout without requests (by default 30 minutes, configurable with `-t`/`--timeout`), or when you press Ctrl-C.
|
|
91
|
+
|
|
92
|
+
A private repository works the same way once you're signed in to the GitHub CLI:
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
gh auth login
|
|
96
|
+
gh htmlpreview https://github.com/my-org/private-repo/blob/main/reports/summary.html
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Branch names containing `/` work too:
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
gh htmlpreview https://github.com/my-org/my-repo/blob/feature/new-report/docs/report.html
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
To use the standalone Python CLI installed from PyPI, the command is `gh-htmlpreview` instead of `gh htmlpreview`.
|
|
106
|
+
|
|
107
|
+
For a shorter command, set a gh alias:
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
gh alias set hp htmlpreview
|
|
111
|
+
gh hp https://github.com/jayqi/gh-htmlpreview/blob/main/demo/index.html
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### Accepted URL formats
|
|
115
|
+
|
|
116
|
+
- `https://github.com/{owner}/{repo}/blob/{ref}/{path}`
|
|
117
|
+
- `https://github.com/{owner}/{repo}/raw/{ref}/{path}`
|
|
118
|
+
- `https://raw.githubusercontent.com/{owner}/{repo}/{ref}/{path}`
|
|
119
|
+
|
|
120
|
+
`{ref}` can be a branch, a tag, or a full commit SHA, as in GitHub's permalinks.
|
|
121
|
+
|
|
122
|
+
### Links between pages
|
|
123
|
+
|
|
124
|
+
The whole repository at that commit is servable from the HTTP server's root, so relative links (`../index.html`) and root-relative links (`/docs/other.html`) resolve the way they would on GitHub Pages serving from the repository root. Following links from the previewed page to other HTML files in the repository works as a result, but it's best effort: a link to a directory needs a trailing slash (`articles/`) to serve its `index.html`.
|
|
125
|
+
|
|
126
|
+
Root-relative links assume the site's root is the repository's root. A site built into a subdirectory, such as `site/` or `docs/_build/html/`, works only if its links are relative. Links that leave off both the trailing slash and `.html` (`/about`) won't resolve.
|
|
127
|
+
|
|
128
|
+
### Authentication
|
|
129
|
+
|
|
130
|
+
This tool authenticates with any GitHub token that can read the repository, such as the one from `gh auth login` or a personal access token. It checks token sources in the following order:
|
|
131
|
+
|
|
132
|
+
1. The `GH_TOKEN` environment variable
|
|
133
|
+
2. The `GITHUB_TOKEN` environment variable
|
|
134
|
+
3. `gh auth token`, if the GitHub CLI is installed and signed in
|
|
135
|
+
|
|
136
|
+
If you create a personal access token for this, a fine-grained token needs the "Contents: Read-only" permission, and a classic token needs the `repo` scope for private repositories.
|
|
137
|
+
|
|
138
|
+
Without a token, public repositories still work. Files come from `raw.githubusercontent.com`, and only resolving the branch, tag, or commit uses the GitHub API, which allows 60 unauthenticated requests per hour.
|
|
139
|
+
|
|
140
|
+
### Opening the browser
|
|
141
|
+
|
|
142
|
+
The tool will automatically open your browser to the served page. You can configure a browser command, and the configuration source follows the GitHub CLI's behavior with the following order:
|
|
143
|
+
|
|
144
|
+
- The `GH_BROWSER` environment variable
|
|
145
|
+
- `gh config get browser`
|
|
146
|
+
- The `BROWSER` environment variable
|
|
147
|
+
- Your system's default browser
|
|
148
|
+
|
|
149
|
+
Use `-n`/`--no-browser` to print the URL without opening a browser.
|
|
150
|
+
|
|
151
|
+
In an SSH session, or on Linux without a display, the default browser isn't opened. Over SSH, it prints the port-forwarding command to run on your own machine, such as `ssh -L 53817:127.0.0.1:53817 HOST`. Forward to the same port number and open the printed URL as is, with `127.0.0.1` rather than `localhost`, or the server refuses the request. You can use `-p`/`--port` to specify a port in order to keep the same port between sessions.
|
|
152
|
+
|
|
153
|
+
## Security
|
|
154
|
+
|
|
155
|
+
The previewed page's JavaScript runs in your browser like any website's. **Only preview pages from repositories you trust as much as a website you'd visit.** Because browsers don't separate cookies by port, that JavaScript can read and set cookies of other apps served on `127.0.0.1`, other than HttpOnly ones. Storage the page leaves behind, such as `localStorage`, can also be seen by later web applications served at the same port.
|
|
156
|
+
|
|
157
|
+
This tool takes the following security precautions:
|
|
158
|
+
|
|
159
|
+
- The server listens on `127.0.0.1` only. It does not listen on `0.0.0.0`, which would allow other devices to connect.
|
|
160
|
+
- Requests must have the `Host` header `127.0.0.1:{port}`, which blocks DNS-rebinding attacks from reading repository content through the server. It also refuses `localhost`, in order to keep the cookies of other apps running on `localhost` isolated from the previewed page.
|
|
161
|
+
- There is an idle timeout after which the server is shut down. By default, it is 30 minutes.
|
|
162
|
+
- Requests from other sites are refused, based on the `Sec-Fetch-Site` header that browsers send. This includes other apps served on `127.0.0.1`.
|
|
163
|
+
- JavaScript service workers can't be registered, so a previewed page can't leave code behind that intercepts something else served on that port later.
|
|
164
|
+
- A session serves one repository at one commit. It does not mix commits or serve files across repositories.
|
|
165
|
+
- Your auth token is only sent to GitHub and is not accessible to the browser.
|
|
166
|
+
|
|
167
|
+
## Limitations
|
|
168
|
+
|
|
169
|
+
- Only works for github.com. GitHub Enterprise Server is not supported.
|
|
170
|
+
- Git LFS files are served as their pointer files and not the files themselves.
|
|
171
|
+
|
|
172
|
+
## CLI help
|
|
173
|
+
|
|
174
|
+
```text
|
|
175
|
+
usage: gh htmlpreview [-h] [-t DURATION] [-p PORT] [-n] [--version] URL
|
|
176
|
+
|
|
177
|
+
Preview an HTML file from a GitHub repository in your browser.
|
|
178
|
+
|
|
179
|
+
positional arguments:
|
|
180
|
+
URL GitHub URL of the file to preview.
|
|
181
|
+
|
|
182
|
+
options:
|
|
183
|
+
-h, --help show this help message and exit
|
|
184
|
+
-t, --timeout DURATION
|
|
185
|
+
Time to keep the server alive after the most recent request,
|
|
186
|
+
such as '90s', '10m' or '1h30m'. A number without a unit is
|
|
187
|
+
seconds. (default: 30m)
|
|
188
|
+
-p, --port PORT Port to use. (default: 0, chosen by the operating system)
|
|
189
|
+
-n, --no-browser Print the URL without opening a browser.
|
|
190
|
+
--version Show version and exit.
|
|
191
|
+
```
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
gh_htmlpreview/__init__.py,sha256=Qm4qwWuohb1sgG0InKlnv2RhboKvkJrHo5mdMEmrNpQ,530
|
|
2
|
+
gh_htmlpreview/__main__.py,sha256=y7SVLrGOTk96eztW4Fa989nG-Mfwi3eUeUDtSzsONkU,75
|
|
3
|
+
gh_htmlpreview/browser.py,sha256=6nccg0Qa7kPU5FRkgJzaufsV-cqjvl8E6NwaALuzvWU,3072
|
|
4
|
+
gh_htmlpreview/cli.py,sha256=DZwQPJQ5eXVUOpXtLfkbpsXPmKhqCASd4Q_4h1vlhZk,5115
|
|
5
|
+
gh_htmlpreview/exceptions.py,sha256=A4AsZA5RqdiCUs674Z9Te_lGrRZ0gQOhicS14QZ-JpA,191
|
|
6
|
+
gh_htmlpreview/github.py,sha256=tphK-l8jOBmTJcKm1re2BKhnpu4u3Uytq4Vfqwq9deI,8736
|
|
7
|
+
gh_htmlpreview/server.py,sha256=hSR6PQPVkK3r65ehVMKNfkfDYcKmBx9-hPi_IEcTU-0,12371
|
|
8
|
+
gh_htmlpreview/urls.py,sha256=RnnJXSVuFpeCauaTCnKKcA0MxJ4N6CLbfoXvY96xY3o,1447
|
|
9
|
+
gh_htmlpreview-0.1.0.dist-info/licenses/LICENSE,sha256=WJpT1XJOygof1raMfGZEZNNQCya1DJJ1pWRyntVjd2o,1063
|
|
10
|
+
gh_htmlpreview-0.1.0.dist-info/WHEEL,sha256=-gI5GRFdiNNn2CFz-ptlExISMINC-k8bFxeojAlHbrM,81
|
|
11
|
+
gh_htmlpreview-0.1.0.dist-info/entry_points.txt,sha256=rw3P7AzaL-0pFNextITB2ttNfi-kBXZ-IPxs7WiAJ8Q,60
|
|
12
|
+
gh_htmlpreview-0.1.0.dist-info/METADATA,sha256=iGXrkOsvx9o05nrKXslBqRl1Ah7CXYPCFkpO7BQf0UA,9929
|
|
13
|
+
gh_htmlpreview-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jay Qi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|