Skip to content

Commit

Permalink
Change hidden!() color to purple
Browse files Browse the repository at this point in the history
Changed the `hidden!()` log color to purple as orange is not part of the
ANSI standard, and using a fixed color code to represent it could result
in poor legibility in some terminals.

Changed comment styling to always use single-line annotations (`//`) for
text and multi-line ones (`/* */`) for disabled code blocks, increasing
clarity and preventing the https://github.com/stkb/Rewrap extension from
accidentally breaking "commented-out" code.
  • Loading branch information
subreme committed Nov 26, 2021
1 parent 0cdabdc commit 1c8262c
Show file tree
Hide file tree
Showing 5 changed files with 178 additions and 263 deletions.
18 changes: 4 additions & 14 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -424,8 +424,7 @@ pub struct Settings {
// the URL to a product's variant, so the only unique link to each
// variant is the Add To Cart one (which is therefore always
// included).
// pub atc: Option<bool>,

/* pub atc: Option<bool>, */
// Although I was planning to include the option to select whether
// to include the item price or not, I decided to "strip users of
// this power" as I couldn't figure out a way to make the embeds
Expand Down Expand Up @@ -533,7 +532,7 @@ pub struct Channel {
// to identically named channels, however the `name` is only used
// for logging and debugging purposes, and the ID wasn't ever used,
// so it was removed.
// pub id: u64,
/* pub id: u64, */
pub url: String,
#[serde(default)]
pub settings: Alt<Settings>,
Expand Down Expand Up @@ -561,16 +560,7 @@ pub struct ChannelHM {
// would be used instead of the key to it as the channel name,
// however I decided against it. Users are still allowed to include
// they field if they choose to, but its value will be ignored.

// // While this alternative struct could be removed entirely if the
// // `name` field were made optional in the original version, as it is
// // here, I decided to require it instead, so that debugging (and
// // configuring the monitor) doesn't become ridiculously hard.

// // In this struct, users all allowed to include a `name` field in
// // the struct contained by a `HashMap` if they want to, bypassing
// // the limitation cause by the type not allowing duplicate keys.
// pub name: Option<String>,
/* pub name: Option<String>, */
pub url: String,
#[serde(default)]
pub settings: Alt<Settings>,
Expand Down Expand Up @@ -668,7 +658,7 @@ impl IntoIterator for VecMap<Event, Event> {
if let VecMap::Vec(events) = self {
events.into_iter()
} else if let VecMap::Map(eventhms) = self {
// events.values().collect::<Vec<Event>>().into_iter()
/* events.values().collect::<Vec<Event>>().into_iter() */

let mut events = Vec::with_capacity(eventhms.len());

Expand Down
58 changes: 28 additions & 30 deletions src/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,6 @@ macro_rules! log {
// This macro also shouldn't be called outside this file, as it's
// implemented in the other macros to save logs to a file.
#[macro_export]
/*
// It should only save logs if it isn't called from during tests, as
// those logs would not be useful and could be confusing.
#[cfg(not(test))]
*/
macro_rules! file {
// While they weren't included for `log!()`, the parentheses around
// the curly brackets are necessary in this macro as the `Write`
Expand All @@ -40,34 +35,29 @@ macro_rules! file {
// trait was already declared, it would be imported twice, causing
// the code not to compile.
($($arg:tt)*) => ({
// Traits must be explicitly imported using `use`.
use std::io::Write;

if let Ok(mut file) = std::fs::OpenOptions::new()
.write(true)
.create(true)
.append(true)
.open("shopify-monitor.log")
{
let _ = std::write!(
file,
"[{}] {}\n",
chrono::Local::now().format("%F %T%.3f"),
std::format_args!($($arg)*)
);
// It should only save logs if it isn't called from during tests, as
// those logs would not be useful and could be confusing.
#[cfg(not(test))] {
// Traits must be explicitly imported using `use`.
use std::io::Write;

if let Ok(mut file) = std::fs::OpenOptions::new()
.write(true)
.create(true)
.append(true)
.open("shopify-monitor.log")
{
let _ = std::write!(
file,
"[{}] {}\n",
chrono::Local::now().format("%F %T%.3f"),
std::format_args!($($arg)*)
);
}
}
});
}

/*
// While a test is running, it shouldn't do anything.
#[macro_export]
#[cfg(test)]
macro_rules! file {
($($arg:tt)*) => {};
}
*/

// The other macros take a string literal and some optional parameters,
// allowing them to be called in the same way as `println!()`. Its
// arguments are then styled differently in each macro, as each type of
Expand Down Expand Up @@ -165,7 +155,15 @@ macro_rules! hidden {
use colored::Colorize;

let msg = std::format_args!($($arg)*).to_string();
crate::log!(msg.black().truecolor(255, 165, 0));

// While the program originally used a custom orange
// (#FFAA00) as the color isn't "built-in" to the terminal,
// it was switched to purple so that it can be automatically
// adjusted to be visible regardless of the platform the
// monitor is run on.
/* crate::log!(msg.truecolor(255, 170, 0)); */

crate::log!(msg.purple());
}

crate::file!("[HIDDEN] {}", std::format_args!($($arg)*));
Expand Down
126 changes: 39 additions & 87 deletions src/monitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ pub async fn run(stores: Vec<Store>) {
// `/products.json`, so it has to be added to the
// website's URL to get the link to it.
let req = client.get(
// format!("{}/products.json?limit=100",
/* format!("{}/products.json?limit=100", */
format!("{}/products.json",
&store.url.clone().trim_end_matches('/')
))
Expand All @@ -65,20 +65,11 @@ pub async fn run(stores: Vec<Store>) {
.header("sec-fetch-dest", "document")
.header("accept-language", "en-US,en;q=0.9")

// .header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
// .header("accept-language", "en-US,en;q=0.9")
// .header("sec-fetch-dest", "document")
// .header("sec-fetch-mode", "navigate")
// .header("sec-fetch-site", "none")
// .header("sec-fetch-user", "?1")
// .header("sec-gpc", "1")
// .header("upgrade-insecure-requests", "1")

.send()
.await;

if let Ok(res) = req {
// hidden!("Fetched {}! Status: {}!", res.url(), res.status());
/* hidden!("Fetched {}! Status: {}!", res.url(), res.status()); */

if res.status() == 200 {
// In this case, a webhook saying the password
Expand Down Expand Up @@ -190,7 +181,7 @@ pub async fn run(stores: Vec<Store>) {
)
)
{
// hidden!("Product {} Updated At: {}", curr.id, curr.updated_at);
/* hidden!("Product {} Updated At: {}", curr.id, curr.updated_at); */

hidden!("{}/product/{} restocked!", store.url, curr.id);
success!("{}: `{}` restocked!", store.name, curr.title);
Expand Down Expand Up @@ -233,11 +224,11 @@ pub async fn run(stores: Vec<Store>) {
store_logo: store.logo.clone()
}));

// hidden!("Pushed a webhook for product {}!", curr.id);
/* hidden!("Pushed a webhook for product {}!", curr.id); */
}
}

// hidden!("Sending webhooks for `{}`!", curr.id);
/* hidden!("Sending webhooks for `{}`!", curr.id); */

let length = webhooks.len();

Expand Down Expand Up @@ -388,30 +379,6 @@ pub async fn run(stores: Vec<Store>) {
join_all(tasks).await;
}

// This function was scrapped s it raised several issues.
// // I initially wrote this function because the compiler wouldn't allow me to
// // return a value to the `default!()` macro, instead of for the whole
// // function, as setting values with conditionals becomes "weirder"
// // inside nested `if` statements. I changed it not to `.await` the
// // webhook tasks as that required the function to be asynchronous, and
// // the compiler warned that moving Futures isn't thread-safe.
// async fn log_webhooks(length: usize) {
// // The purpose of this conditional statement is to allow for the
// // use of the correct form of a noun in a log message.
// let s: String = if length == 1 {
// // // I'm using `\0`, a null character, instead of an empty
// // // character as the latter doesn't exist.
// // // https://stackoverflow.com/questions/3670505/why-is-there-no-char-empty-like-string-empty
// // '\0'
// "".into()
// } else {
// // 's'
// "s".into()
// };

// default!("Sending {} webhook{}...", length, s);
// }

pub fn minimal_products(current_products: Arc<Vec<Product>>) -> Option<Vec<MinimalProduct>> {
Some({
let mut products = vec![];
Expand All @@ -421,7 +388,7 @@ pub fn minimal_products(current_products: Arc<Vec<Product>>) -> Option<Vec<Minim
variants.push(MinimalVariant {
id: variant.id,
available: variant.available,
// updated_at: variant.updated_at.clone(),
/* updated_at: variant.updated_at.clone(), */
});
}
products.push(MinimalProduct {
Expand Down Expand Up @@ -512,41 +479,18 @@ pub fn available_product(
"?".into()
};

// let image = if let Some(img) = curr.images.get(0) {
// Some(img.src.clone())
// } else {
// None
// };
/*
let image = if let Some(img) = curr.images.get(0) {
Some(img.src.clone())
} else {
None
};
*/

let image = curr.images.get(0).map(|img| img.src.clone());

for variant in curr.variants.iter() {
if variant.available {
// These conditional statement used to check whether the
// variant was previously unavailable, however it was
// removed, as explained earlier.

// if let Some(p) = &prev {
// if let Some(v) = p.iter().find(|v| v.id == variant.id) {
// if !v.available {
// variants.push(AvailableVariant {
// name: variant.title.clone(),
// id: variant.id,
// });
// }
// } else {
// variants.push(AvailableVariant {
// name: variant.title.clone(),
// id: variant.id,
// });
// }
// } else {
// variants.push(AvailableVariant {
// name: variant.title.clone(),
// id: variant.id,
// });
// }

variants.push(AvailableVariant {
// Some websites have very weird variant names.
// UNDEFEATED, for example, prefixes their "sizes" with
Expand All @@ -557,14 +501,20 @@ pub fn available_product(
// almost all of these strange names can be "normalized".
name: variant
.title
.chars() // The string is split into characters.
.collect::<Vec<char>>() // The split is transformed into a vector.
.iter() // The program can now iterate through each char.
// The string is split into characters.
.chars()
// The split is transformed into a vector.
.collect::<Vec<char>>()
// The program can now iterate through each char.
.iter()
// "Invalid" characters are removed.
.filter(|c| c.is_alphanumeric() || c.is_whitespace() || c == &&'.')
.collect::<String>() // The filtered characters are collected into a string.
.trim() // Leading and trailing whitespace is removed.
.into(), // The returned `&str` is converted to a `String`.
// The filtered characters are collected into a string.
.collect::<String>()
// Leading and trailing whitespace is removed.
.trim()
// The returned `&str` is converted to a `String`.
.into(),
id: variant.id,
});
}
Expand All @@ -586,15 +536,15 @@ pub fn available_product(
// while the two functions' role is to construct the embeds, as they
// will differ between item and password-related notifications.
async fn request(url: String, msg: Arc<Message>) {
// hidden!("`request()` started!");
/* hidden!("`request()` started!"); */

loop {
let status = webhook::send(url.clone(), msg.clone()).await;

// hidden!("Webhook Status: {:?}!", status);
/* hidden!("Webhook Status: {:?}!", status); */

if status == Status::Success {
// hidden!("Successfully sent webhook to {}!", url);
/* hidden!("Successfully sent webhook to {}!", url); */
break;
}

Expand Down Expand Up @@ -624,7 +574,7 @@ pub struct ItemSettings {
avatar: Option<String>,
color: Option<u32>,
sizes: bool,
// atc: Option<bool>,
/* atc: Option<bool>, */
thumbnail: bool,
image: bool,
footer_text: Option<String>,
Expand All @@ -639,7 +589,7 @@ pub struct ItemSettings {
// `product()` and `Product`, because the `Product` name is already used
// by `crate::products::Product`, which is named after `products.json`.
async fn item(settings: ItemSettings) {
// hidden!("`item()` started for {}!", product.name.clone());
/* hidden!("`item()` started for {}!", product.name.clone()); */

let embed = Embed {
title: Some(settings.product.name.clone()),
Expand All @@ -651,13 +601,15 @@ async fn item(settings: ItemSettings) {
color: settings.color,
fields: {
let quantity = if settings.sizes {
// let len = 3 + product.variants.len();
/*
let len = 3 + product.variants.len();
// if len % 3 == 2 {
// len + 4
// }
if len % 3 == 2 {
len + 4
}
// len + 3
len + 3
*/

// Since the checks for the number of variants (above
// this comment) were removed, the number of fields
Expand Down Expand Up @@ -698,7 +650,7 @@ async fn item(settings: ItemSettings) {
value: settings.product.price.clone(),
});

// hidden!("{} has {} updated variants!", settings.product.name, settings.product.variants.len());
/* hidden!("{} has {} updated variants!", settings.product.name, settings.product.variants.len()); */

if settings.sizes {
for variant in (*settings.product.variants).iter() {
Expand Down Expand Up @@ -789,7 +741,7 @@ async fn item(settings: ItemSettings) {
avatar_url: settings.avatar.clone(),
});

// hidden!("Calling `request()` for {}!", product.name.clone());
/* hidden!("Calling `request()` for {}!", product.name.clone()); */

request(settings.url, msg).await;
}
Expand Down
Loading

0 comments on commit 1c8262c

Please sign in to comment.