Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add preamble-future-date lint for last-call-deadline validation #120

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion eipw-lint/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ regex = "1.11.0"
serde_json = "1.0.128"
serde = { version = "1.0.164", features = [ "derive" ] }
url = "2.5.2"
chrono = { version = "0.4.38", default-features = false }
chrono = { version = "0.4.38", default-features = false, features = ["clock"] }
educe = { version = "0.6.0", default-features = false, features = [ "Debug" ] }
tokio = { optional = true, version = "1.40.0", features = [ "macros" ] }
scraper = { version = "0.20.0", default-features = false }
Expand Down
4 changes: 4 additions & 0 deletions eipw-lint/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,10 @@ pub fn default_lints_enum() -> impl Iterator<Item = (&'static str, DefaultLint<&
"preamble-date-last-call-deadline",
PreambleDate { name: preamble::Date("last-call-deadline") },
),
(
"preamble-future-date",
PreambleFutureDate { name: preamble::FutureDate("last-call-deadline") },
),
(
"preamble-req-category",
PreambleRequiredIfEq(preamble::RequiredIfEq {
Expand Down
8 changes: 8 additions & 0 deletions eipw-lint/src/lints/known_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ pub enum DefaultLint<S> {
PreambleDate {
name: preamble::Date<S>,
},
PreambleFutureDate {
name: preamble::FutureDate<S>,
},
PreambleFileName(preamble::FileName<S>),
PreambleLength(preamble::Length<S>),
PreambleList {
Expand Down Expand Up @@ -87,6 +90,7 @@ where
match self {
Self::PreambleAuthor { name } => Box::new(name),
Self::PreambleDate { name } => Box::new(name),
Self::PreambleFutureDate { name } => Box::new(name),
Self::PreambleFileName(l) => Box::new(l),
Self::PreambleLength(l) => Box::new(l),
Self::PreambleList { name } => Box::new(name),
Expand Down Expand Up @@ -128,6 +132,7 @@ where
match self {
Self::PreambleAuthor { name } => name,
Self::PreambleDate { name } => name,
Self::PreambleFutureDate { name } => name,
Self::PreambleFileName(l) => l,
Self::PreambleLength(l) => l,
Self::PreambleList { name } => name,
Expand Down Expand Up @@ -173,6 +178,9 @@ where
Self::PreambleDate { name } => DefaultLint::PreambleDate {
name: preamble::Date(name.0.as_ref()),
},
Self::PreambleFutureDate { name } => DefaultLint::PreambleFutureDate {
name: preamble::FutureDate(name.0.as_ref()),
},
Self::PreambleFileName(l) => DefaultLint::PreambleFileName(preamble::FileName {
name: l.name.as_ref(),
format: l.format.as_ref(),
Expand Down
2 changes: 2 additions & 0 deletions eipw-lint/src/lints/preamble.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
pub mod author;
pub mod date;
pub mod file_name;
pub mod future_date;
pub mod length;
pub mod list;
pub mod no_duplicates;
Expand All @@ -25,6 +26,7 @@ pub mod url;
pub use self::author::Author;
pub use self::date::Date;
pub use self::file_name::FileName;
pub use self::future_date::FutureDate;
pub use self::length::Length;
pub use self::list::List;
pub use self::no_duplicates::NoDuplicates;
Expand Down
112 changes: 112 additions & 0 deletions eipw-lint/src/lints/preamble/future_date.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/*
* Copyright 2023 The EIP.WTF Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

eipw is released under the MPL, not apache.

*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

use eipw_snippets::Snippet;
use chrono::{NaiveDate, Utc};

use crate::{
lints::{Context, Error, FetchContext, Lint},
LevelExt, SnippetExt,
};

use serde::{Deserialize, Serialize};
use std::fmt::{Debug, Display};

/// Validates that the `last-call-deadline` in an EIP preamble is a future date
/// when the EIP status is "Last Call".
///
/// According to EIP-1, the `last-call-deadline` field is only required when status
/// is "Last Call", and it must be in ISO 8601 date format (YYYY-MM-DD). The date
/// must be in the future or today, as it represents when the last call period ends.
///
/// Example valid preamble:
/// ```yaml
/// status: Last Call
/// last-call-deadline: 2024-12-31 # Must be today or a future date
/// ```
///
/// The lint will raise an error if:
/// - The date is in the past
/// - The date format is invalid (not YYYY-MM-DD)
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(transparent)]
pub struct FutureDate<S>(pub S);

impl<S> Lint for FutureDate<S>
where
S: Debug + Display + AsRef<str>,
{
fn find_resources(&self, _ctx: &FetchContext<'_>) -> Result<(), Error> {
Ok(())
}

fn lint<'a>(&self, slug: &'a str, ctx: &Context<'a, '_>) -> Result<(), Error> {
// Only check if status is "Last Call"
let status = match ctx.preamble().by_name("status") {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When possible, I prefer keeping lints small and single purpose. Here, I think it would be simpler if—instead of checking for a particular status—you only enforce that the date is in the future if and only if the field is present.

Then preamble-req-last-call-deadline, preamble-date-last-call-deadline, and this lint will all work together.

None => return Ok(()),
Some(s) => s.value().trim(),
};

if status != "Last Call" {
return Ok(());
}

// Get the deadline field
let field = match ctx.preamble().by_name(self.0.as_ref()) {
None => return Ok(()),
Some(s) => s,
};

let value = field.value().trim();

// Parse the date
let date = match NaiveDate::parse_from_str(value, "%Y-%m-%d") {
Ok(d) => d,
Err(_) => return Ok(()), // Let the Date lint handle invalid dates
};

// Get today's date
let today = Utc::now().date_naive();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This might be overly strict. If someone in, for example, Eastern Time (so UTC-5) submits near midnight, this would annoyingly fail for them. Can we do like... UTC-12 or something? I'm not 100% sure how timezones work.


// Check if date is in the future or today
if date < today {
let label = format!(
"preamble header `{}` must be today or a future date (today is {})",
self.0,
today.format("%Y-%m-%d")
);

let name_count = field.name().len();
let value_count = field.value().len();

ctx.report(
ctx.annotation_level().title(&label).id(slug).snippet(
Snippet::source(field.source())
.fold(false)
.line_start(field.line_start())
.origin_opt(ctx.origin())
.annotation(
ctx.annotation_level()
.span_utf8(field.source(), name_count + 2, value_count)
.label("must be today or a future date"),
),
),
)?;
}

Ok(())
}
}
99 changes: 99 additions & 0 deletions eipw-lint/tests/lint_preamble_future_date.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/

use eipw_lint::lints::preamble::FutureDate;
use eipw_lint::reporters::Text;
use eipw_lint::Linter;

#[tokio::test]
async fn past_date() {
let src = r#"---
status: Last Call
last-call-deadline: 2023-12-12
---
hello world"#;

let reports = Linter::<Text<String>>::default()
.clear_lints()
.deny("preamble-future-date", FutureDate("last-call-deadline"))
.check_slice(None, src)
.run()
.await
.unwrap()
.into_inner();

assert_eq!(
reports,
r#"error[preamble-future-date]: preamble header `last-call-deadline` must be today or a future date (today is 2024-12-12)
|
3 | last-call-deadline: 2023-12-12
| ^^^^^^^^^^ must be today or a future date
|
"#,
);
}

#[tokio::test]
async fn today_date() {
let src = r#"---
status: Last Call
last-call-deadline: 2024-12-12
---
hello world"#;

let reports = Linter::<Text<String>>::default()
.clear_lints()
.deny("preamble-future-date", FutureDate("last-call-deadline"))
.check_slice(None, src)
.run()
.await
.unwrap()
.into_inner();

// Today's date should be valid
assert_eq!(reports, "");
}

#[tokio::test]
async fn future_date() {
let src = r#"---
status: Last Call
last-call-deadline: 2025-12-12
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will fail while I am alive. Can we do like 3000-12-12?

---
hello world"#;

let reports = Linter::<Text<String>>::default()
.clear_lints()
.deny("preamble-future-date", FutureDate("last-call-deadline"))
.check_slice(None, src)
.run()
.await
.unwrap()
.into_inner();

assert_eq!(reports, "");
}

#[tokio::test]
async fn not_last_call() {
let src = r#"---
status: Draft
last-call-deadline: 2023-12-12
---
hello world"#;

let reports = Linter::<Text<String>>::default()
.clear_lints()
.deny("preamble-future-date", FutureDate("last-call-deadline"))
.check_slice(None, src)
.run()
.await
.unwrap()
.into_inner();

// Should not error when status is not Last Call, even with past date
assert_eq!(reports, "");
}