Skip to content

Commit

Permalink
Merge pull request #8 from fufexan/lints
Browse files Browse the repository at this point in the history
chore: apply clippy lints
  • Loading branch information
NotAShelf authored Jul 21, 2024
2 parents 344c9ba + e65bfa9 commit fc87440
Show file tree
Hide file tree
Showing 11 changed files with 110 additions and 120 deletions.
4 changes: 2 additions & 2 deletions src/clipboard.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use arboard::Clipboard;

pub fn copy_to_clipboard(text: &str) -> Result<(), arboard::Error> {
pub fn copy(text: &str) -> Result<(), arboard::Error> {
let mut clipboard = Clipboard::new()?;
clipboard.set_text(text)
}

pub fn get_from_clipboard() -> Result<String, arboard::Error> {
pub fn get() -> Result<String, arboard::Error> {
let mut clipboard = Clipboard::new()?;
clipboard.get_text()
}
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ fn main() {

// start tray service
match start_tray_service() {
Ok(_) => println!("Tray service started successfully."),
Err(e) => eprintln!("Failed to start the tray service: {}", e),
Ok(()) => println!("Tray service started successfully."),
Err(e) => eprintln!("Failed to start the tray service: {e}"),
}

// keep the main thread alive
Expand Down
9 changes: 3 additions & 6 deletions src/pkexec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,15 @@ use std::path::PathBuf;
use which::which;
use whoami::username;

pub fn get_pkexec_path() -> PathBuf {
match which("pkexec") {
Ok(path) => path,
Err(_) => panic!("pkexec not found in PATH"),
}
pub fn get_path() -> PathBuf {
which("pkexec").unwrap_or_else(|_| panic!("pkexec not found in PATH"))
}

// We don't need to elevate privileges if we're using the Tray service
// as the root user. This shouldn't really happen, but it's possible
// depending on how Tailran is ran.
pub fn should_elevate_perms() -> bool {
let parent_user = username().to_string();
let parent_user = username();

if parent_user.eq("root") {
return false;
Expand Down
36 changes: 18 additions & 18 deletions src/svg/renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,25 @@ use resvg::{

const SVG_DATA: &str = include_str!("assets/tailscale.svg");

pub struct ResvgRenderer {
pub struct Resvg {
options: Options,
transform: Transform,
font_db: fontdb::Database,
}

impl ResvgRenderer {
pub fn to_icon(&mut self, svg_str: &str) -> Icon {
impl Resvg {
#[allow(clippy::cast_sign_loss)]
#[allow(clippy::cast_possible_truncation)]
pub fn to_icon(&self, svg_str: &str) -> Icon {
let rtree = Tree::from_str(svg_str, &self.options, &self.font_db).unwrap_or_else(|e| {
panic!("Failed to parse SVG: {}", e);
panic!("Failed to parse SVG: {e}");
});

let size = rtree.size();
let width = size.width() as u32;
let height = size.height() as u32;

let mut pixmap =
Pixmap::new(size.width().round() as u32, size.height().round() as u32).unwrap();
let mut pixmap = Pixmap::new(width, height).unwrap();

resvg::render(&rtree, self.transform, &mut pixmap.as_mut());

Expand All @@ -33,28 +36,25 @@ impl ResvgRenderer {
.collect();

Icon {
width: size.width().round() as i32,
height: size.height().round() as i32,
width: size.width() as i32,
height: size.height() as i32,
data: argb_data,
}
}

pub fn load_icon(enabled: bool) -> Vec<Icon> {
let mut renderer = ResvgRenderer {
let renderer = Self {
options: Options::default(),
transform: Transform::default(),
font_db: fontdb::Database::new(),
};

match enabled {
true => {
log::debug!("icon: Tailscale is enabled");
vec![renderer.to_icon(&SVG_DATA)]
}
false => {
log::debug!("icon: Tailscale is not enabled");
vec![renderer.to_icon(&SVG_DATA.replace("1.0", "0.4"))]
}
if enabled {
log::debug!("icon: Tailscale is enabled");
vec![renderer.to_icon(SVG_DATA)]
} else {
log::debug!("icon: Tailscale is not enabled");
vec![renderer.to_icon(&SVG_DATA.replace("1.0", "0.4"))]
}
}
}
9 changes: 0 additions & 9 deletions src/tailscale/dns.rs

This file was deleted.

1 change: 0 additions & 1 deletion src/tailscale/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
pub mod dns;
pub mod peer;
pub mod status;
pub mod utils;
15 changes: 7 additions & 8 deletions src/tailscale/peer.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
use crate::clipboard::{copy_to_clipboard, get_from_clipboard};
use log::{error, info};
use crate::clipboard::{copy, get};
use notify_rust::Notification;

pub fn check_peer_ip(peer_ip: &str) {
if peer_ip.is_empty() {
error!("No peer IP.")
log::error!("No peer IP.");
} else {
info!("Peer IP: {}", peer_ip);
log::info!("Peer IP: {peer_ip}");
}
}

Expand All @@ -17,21 +16,21 @@ pub fn copy_peer_ip(
) -> Result<(), Box<dyn std::error::Error>> {
check_peer_ip(peer_ip);

copy_to_clipboard(peer_ip)?;
copy(peer_ip)?;

// Get IP from clipboard to verify
let clip_ip = get_from_clipboard()?;
let clip_ip = get()?;

// Create summary for host/peer
let summary = format!("Copied {} IP address", if host { "host" } else { "peer" });

// log success
info!("{} {} to the clipboard", summary, clip_ip);
log::info!("{summary} {clip_ip} to the clipboard");

// send a notification through dbus
Notification::new()
.summary(&summary)
.body(&notif_body)
.body(notif_body)
.icon("tailscale")
.show()?;

Expand Down
18 changes: 9 additions & 9 deletions src/tailscale/status.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::tailscale::dns;
use crate::tailscale::utils;
use crate::tailscale::utils::{Machine, User};
use crate::tray::menu::Context;
use serde::{Deserialize, Serialize};
Expand All @@ -22,23 +22,23 @@ pub struct Status {
user: HashMap<String, User>,
}

pub fn get_status() -> Result<Status, Box<dyn std::error::Error>> {
let status_json = get_status_json()?;
pub fn get() -> Result<Status, Box<dyn std::error::Error>> {
let status_json = get_json()?;
let mut status: Status = serde_json::from_str(&status_json)?;
let dnssuffix = status.magic_dnssuffix.to_owned();
let dnssuffix = &status.magic_dnssuffix;
status.tailscale_up = matches!(status.backend_state.as_str(), "Running");

dns::dns_or_quote_hostname(&mut status.this_machine, &dnssuffix);
utils::set_display_name(&mut status.this_machine, dnssuffix);
status
.peers
.values_mut()
.for_each(|m| dns::dns_or_quote_hostname(m, &dnssuffix));
.for_each(|m| utils::set_display_name(m, dnssuffix));

Ok(status)
}

pub fn get_current_status() -> Result<Context, Box<dyn std::error::Error>> {
let status = get_status()?;
pub fn get_current() -> Result<Context, Box<dyn std::error::Error>> {
let status = get()?;
let pkexec = which("pkexec")?;

Ok(Context {
Expand All @@ -48,7 +48,7 @@ pub fn get_current_status() -> Result<Context, Box<dyn std::error::Error>> {
})
}

pub fn get_status_json() -> Result<String, Box<dyn std::error::Error>> {
pub fn get_json() -> Result<String, Box<dyn std::error::Error>> {
let output = Command::new("tailscale")
.arg("status")
.arg("--json")
Expand Down
79 changes: 42 additions & 37 deletions src/tailscale/utils.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
collections::HashSet,
fmt::{Display, Formatter},
};

Expand All @@ -12,15 +12,15 @@ pub enum PeerKind {

impl Default for PeerKind {
fn default() -> Self {
PeerKind::HostName("default".to_owned())
Self::HostName("default".to_owned())
}
}

impl Display for PeerKind {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match &self {
PeerKind::DNSName(d) => write!(f, "{d}"),
PeerKind::HostName(h) => write!(f, "{h}"),
Self::DNSName(d) => write!(f, "{d}"),
Self::HostName(h) => write!(f, "{h}"),
}
}
}
Expand Down Expand Up @@ -62,50 +62,55 @@ pub fn has_suffix(name: &str, suffix: &str) -> bool {
pub fn trim_suffix(name: &str, suffix: &str) -> String {
let mut new_name = name;
if has_suffix(name, suffix) {
new_name = new_name.trim_end_matches('.');
let suffix = suffix.trim_start_matches('.').trim_end_matches('.');
new_name = new_name.trim_end_matches('.');
new_name = new_name.trim_end_matches(suffix);
}
new_name.trim_end_matches('.').to_string()
}

pub fn sanitize_hostname(hostname: &str) -> String {
const MAX_LABEL_LEN: usize = 63;
let mut sb = "".to_string();
const MAX_LABEL_LENGTH: usize = 63;

// Trim suffixes
let hostname = hostname
.trim_end_matches(".local")
.trim_end_matches(".localdomain")
.trim_end_matches(".lan");
let mut start = 0;
let mut end = hostname.len();
if end > MAX_LABEL_LEN {
end = MAX_LABEL_LEN;
}
let mut chars = hostname.chars();
while start < end {
if chars.nth(start).unwrap().is_alphanumeric() {
break;
}
start += 1;
}
while start < end {
if chars.nth(end - 1).unwrap().is_alphanumeric() {
break;
}
end -= 1;
}
let seperators: HashMap<char, bool> =
HashMap::from([(' ', true), ('.', true), ('@', true), ('_', true)]);

let mut chars = hostname.chars();
for i in start..end - 1 {
let boundary = (i == start) || (i == end - 1);
let chari = chars.nth(i).unwrap();
if !boundary && seperators[&chari] {
sb.push('-');
} else if chari.is_alphanumeric() || chari == '-' {
sb.push(chari.to_ascii_lowercase())
}
// Find the first/last alphanumeric characters
let start = hostname.find(|c: char| c.is_alphanumeric()).unwrap_or(0);
let end = hostname
.rfind(|c: char| c.is_alphanumeric())
.map_or(0, |e| e + 1);

let separators: HashSet<char> = [' ', '.', '@', '_'].into();

let mut sanitized: String = hostname[start..end]
.chars()
.enumerate()
.map(|(index, char)| {
let boundary = (index == 0) || (index == end - start - 1);
if !boundary && separators.contains(&char) {
'-'
} else if char.is_alphanumeric() || char == '-' {
char.to_ascii_lowercase()
} else {
char
}
})
.collect();

sanitized.truncate(MAX_LABEL_LENGTH);
sanitized
}

pub fn set_display_name(m: &mut Machine, dns_suffix: &str) {
let dns_name = trim_suffix(&m.dns_name, dns_suffix);

if dns_name.is_empty() {
m.display_name = PeerKind::DNSName(sanitize_hostname(&m.hostname));
} else {
m.display_name = PeerKind::HostName(dns_name);
}
sb
}
Loading

0 comments on commit fc87440

Please sign in to comment.