Skip to content

Commit e68b8f0

Browse files
committed
Use /raw/ rather than /blob/ URLs for images
1 parent 9da11a4 commit e68b8f0

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

src/render.rs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use ammonia::{Builder, UrlRelative};
22
use comrak;
33
use htmlescape::encode_minimal;
44
use std::borrow::Cow;
5+
use std::path::Path;
56
use url::Url;
67

78
use util::CargoResult;
@@ -119,6 +120,16 @@ impl<'a> MarkdownRenderer<'a> {
119120
None
120121
});
121122

123+
fn is_media_url(url: &str) -> bool {
124+
Path::new(url)
125+
.extension()
126+
.and_then(|e| e.to_str())
127+
.map_or(false, |e| match e {
128+
"png" | "svg" | "jpg" | "jpeg" | "gif" | "mp4" | "webm" | "ogg" => true,
129+
_ => false,
130+
})
131+
}
132+
122133
let relative_url_sanitizer = constrain_closure(move |url| {
123134
// sanitizer_base_url is Some(String); use it to fix the relative URL.
124135
if url.starts_with('#') {
@@ -133,7 +144,13 @@ impl<'a> MarkdownRenderer<'a> {
133144
let offset = new_url.len() - 5;
134145
new_url.drain(offset..offset + 4);
135146
}
136-
new_url += "blob/master";
147+
// Assumes GitHub's URL scheme. GitHub renders text and markdown
148+
// better in the "blob" view, but images need to be served raw.
149+
new_url += if is_media_url(url) {
150+
"raw/master"
151+
} else {
152+
"blob/master"
153+
};
137154
if !url.starts_with('/') {
138155
new_url.push('/');
139156
}
@@ -310,6 +327,7 @@ mod tests {
310327
fn relative_links() {
311328
let absolute = "[hi](/hi)";
312329
let relative = "[there](there)";
330+
let image = "![alt](img.png)";
313331

314332
for host in &["github.com", "gitlab.com", "bitbucket.org"] {
315333
for (&extra_slash, &dot_git) in [true, false].iter().zip(&[true, false]) {
@@ -337,6 +355,15 @@ mod tests {
337355
host
338356
)
339357
);
358+
359+
let result = markdown_to_html(image, Some(&url)).unwrap();
360+
assert_eq!(
361+
result,
362+
format!(
363+
"<p><img src=\"https://{}/rust-lang/test/raw/master/img.png\" alt=\"alt\"></p>\n",
364+
host
365+
)
366+
);
340367
}
341368
}
342369

0 commit comments

Comments
 (0)