Skip to content

Commit

Permalink
feat: short commit hash (#2), fix file name typo
Browse files Browse the repository at this point in the history
  • Loading branch information
Kneemund committed Oct 5, 2024
1 parent 28696a8 commit 299c289
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,21 @@ pub struct GitHubRepositoryFilePreview {
raw_content: String,
}

fn get_short_reference(reference: &str) -> &str {
if reference.len() == 40 && reference.chars().all(|c| c.is_ascii_hexdigit()) {
&reference[..7]
} else {
reference
}
}

impl GitHubRepositoryFilePreview {
pub async fn new(message_url: Url) -> Result<Self, Box<dyn Error + Send + Sync>> {
let path_segments: Vec<&str> = message_url.path_segments().unwrap().collect();

let (author, repository, branch, urlencoded_path) = match path_segments.as_slice() {
[author, repository, "blob" | "blame", branch, urlencoded_path @ ..] => {
(author, repository, branch, urlencoded_path.join("/"))
let (author, repository, reference, urlencoded_path) = match path_segments.as_slice() {
[author, repository, "blob" | "blame", reference, urlencoded_path @ ..] => {
(author, repository, reference, urlencoded_path.join("/"))
}
_ => return Err("Malformed GitHub repository URL.".into()),
};
Expand All @@ -34,16 +42,18 @@ impl GitHubRepositoryFilePreview {
.push("/")
.push_bold_safe(repository.to_owned())
.push(" (on ")
.push_safe(branch.to_owned())
.push_safe(get_short_reference(reference))
.push_line(")")
.push_line_safe(path.as_ref())
.build();

let mut raw_url = Url::parse("https://raw.githubusercontent.com/").unwrap();
raw_url
.path_segments_mut()
.unwrap()
.extend(&[author, repository, branch, path.as_ref()]);
raw_url.path_segments_mut().unwrap().extend(&[
author,
repository,
reference,
path.as_ref(),
]);

let file_name = message_url
.path_segments()
Expand Down
4 changes: 2 additions & 2 deletions src/bot/file_preview/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ use serenity::prelude::*;
use crate::HTTP_CLIENT;

use self::gist::GistFilePreview;
use self::github_repositoriy_file::GitHubRepositoryFilePreview;
use self::github_repository_file::GitHubRepositoryFilePreview;

mod gist;
mod github_repositoriy_file;
mod github_repository_file;

static GITHUB_REPOSITORY_FILE_URL_REGEX: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"https://github\.com(?:/[^/\s]+){2}/(?:blob|blame)(?:/[^/\s]+)+#(?:[^/\s]*L[^/\s]*)+").unwrap()
Expand Down

0 comments on commit 299c289

Please sign in to comment.