use std::ops::Range;
use url::Url;
use super::reference::{ReferenceRecognizer, valid_identifier};
mod parse;
use parse::{authority, linear_identifier, relative_address};
pub struct IssueLinkContext<'a> {
app_origin: &'a str,
organisation_id: &'a str,
references: &'a ReferenceRecognizer,
linear_workspace: Option<&'a str>,
}
impl<'a> IssueLinkContext<'a> {
pub fn new(
app_origin: &'a str,
organisation_id: &'a str,
references: &'a ReferenceRecognizer,
) -> Self {
Self {
app_origin,
organisation_id,
references,
linear_workspace: None,
}
}
pub fn with_linear_workspace(mut self, workspace: &'a str) -> Self {
self.linear_workspace = (!workspace.is_empty()).then_some(workspace);
self
}
pub fn flattens(&self, url: &str) -> bool {
nett_path(url, self.app_origin).is_some_and(|path| {
!app_identifier(&path).is_some_and(valid_identifier)
|| organisation_matches(url, self.organisation_id)
})
}
}
pub fn issue_link_identifier(url: &str, context: &IssueLinkContext<'_>) -> Option<String> {
let identifier = link_identifier(url, context)?;
context
.references
.recognises(&identifier)
.then_some(identifier)
}
pub fn relative_issue_addresses(text: &str) -> Vec<(Range<usize>, &str)> {
text.match_indices("/issues/")
.filter_map(|(start, _)| relative_address(text, start))
.collect()
}
fn nett_path(url: &str, app_origin: &str) -> Option<String> {
if url.starts_with('/') && !url.starts_with("//") {
return Some(url.split(['?', '#']).next().unwrap_or_default().into());
}
let authority = authority(url)?;
let target = Url::parse(url).ok()?;
let app = Url::parse(app_origin).ok()?;
(matches!(target.scheme(), "http" | "https")
&& target.origin() == app.origin()
&& !authority.contains('@')
&& target.username().is_empty()
&& target.password().is_none())
.then(|| target.path().to_owned())
}
fn link_identifier(url: &str, context: &IssueLinkContext<'_>) -> Option<String> {
if let Some(path) = nett_path(url, context.app_origin) {
let identifier = app_identifier(&path)?;
return organisation_matches(url, context.organisation_id).then(|| identifier.to_owned());
}
linear_identifier(url, context.linear_workspace?)
}
fn app_identifier(path: &str) -> Option<&str> {
let identifier = path.strip_prefix("/issues/")?;
let identifier = identifier.strip_suffix('/').unwrap_or(identifier);
(!identifier.contains('/')).then_some(identifier)
}
fn organisation_matches(url: &str, organisation_id: &str) -> bool {
let before_fragment = url.split('#').next().unwrap_or_default();
let query = before_fragment
.split_once('?')
.map_or("", |(_, query)| query);
url::form_urlencoded::parse(query.as_bytes())
.filter(|(name, _)| name == "orgId")
.all(|(_, value)| value.eq_ignore_ascii_case(organisation_id))
}