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: complete format support #4818

Merged
merged 5 commits into from
Apr 10, 2024
Merged
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
2 changes: 2 additions & 0 deletions Cargo.lock

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

37 changes: 30 additions & 7 deletions prisma-fmt/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ mod validate;
use log::*;
use lsp_types::{Position, Range};
use psl::parser_database::ast;
use schema_file_input::SchemaFileInput;

/// The API is modelled on an LSP [completion
/// request](https://github.com/microsoft/language-server-protocol/blob/gh-pages/_specifications/specification-3-16.md#textDocument_completion).
Expand Down Expand Up @@ -45,27 +46,49 @@ pub fn code_actions(schema: String, params: &str) -> String {
}

/// The two parameters are:
/// - The Prisma schema to reformat, as a string.
/// - The [`SchemaFileInput`] to reformat, as a string.
/// - An LSP
/// [DocumentFormattingParams](https://github.com/microsoft/language-server-protocol/blob/gh-pages/_specifications/specification-3-16.md#textDocument_formatting) object, as JSON.
///
/// The function returns the formatted schema, as a string.
/// If the schema or any of the provided parameters is invalid, the function returns the original schema.
/// This function never panics.
///
/// Of the DocumentFormattingParams, we only take into account tabSize, at the moment.
pub fn format(schema: &str, params: &str) -> String {
pub fn format(datamodel: String, params: &str) -> String {
let schema: SchemaFileInput = match serde_json::from_str(&datamodel) {
Ok(params) => params,
Err(_) => {
return datamodel;
}
};

let params: lsp_types::DocumentFormattingParams = match serde_json::from_str(params) {
Ok(params) => params,
Err(err) => {
warn!("Error parsing DocumentFormattingParams params: {}", err);
return schema.to_owned();
Err(_) => {
return datamodel;
}
};

psl::reformat(schema, params.options.tab_size as usize).unwrap_or_else(|| schema.to_owned())
let indent_width = params.options.tab_size as usize;

match schema {
jkomyno marked this conversation as resolved.
Show resolved Hide resolved
SchemaFileInput::Single(single) => psl::reformat(&single, indent_width).unwrap_or(datamodel),
SchemaFileInput::Multiple(multiple) => {
let result = psl::reformat_multiple(multiple, indent_width);
serde_json::to_string(&result).unwrap_or(datamodel)
}
}
}

pub fn lint(schema: String) -> String {
lint::run(&schema)
let schema: SchemaFileInput = match serde_json::from_str(&schema) {
Ok(params) => params,
Err(serde_err) => {
panic!("Failed to deserialize SchemaFileInput: {serde_err}");
}
};
lint::run(schema)
}

/// Function that throws a human-friendly error message when the schema is invalid, following the JSON formatting
Expand Down
59 changes: 52 additions & 7 deletions prisma-fmt/src/lint.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use psl::diagnostics::{DatamodelError, DatamodelWarning};

use crate::schema_file_input::SchemaFileInput;

#[derive(serde::Serialize)]
pub struct MiniError {
start: usize,
Expand All @@ -8,8 +10,11 @@ pub struct MiniError {
is_warning: bool,
}

pub(crate) fn run(schema: &str) -> String {
let schema = psl::validate(schema.into());
pub(crate) fn run(schema: SchemaFileInput) -> String {
let schema = match schema {
SchemaFileInput::Single(file) => psl::validate(file.into()),
SchemaFileInput::Multiple(files) => psl::validate_multi_file(files),
};
let diagnostics = &schema.diagnostics;

let mut mini_errors: Vec<MiniError> = diagnostics
Expand Down Expand Up @@ -45,19 +50,20 @@ fn print_diagnostics(diagnostics: Vec<MiniError>) -> String {

#[cfg(test)]
mod tests {
use super::SchemaFileInput;
use expect_test::expect;
use indoc::indoc;

fn lint(s: &str) -> String {
let result = super::run(s);
fn lint(schema: SchemaFileInput) -> String {
let result = super::run(schema);
let value: serde_json::Value = serde_json::from_str(&result).unwrap();

serde_json::to_string_pretty(&value).unwrap()
}

#[test]
fn deprecated_preview_features_should_give_a_warning() {
let dml = indoc! {r#"
fn single_deprecated_preview_features_should_give_a_warning() {
let schema = indoc! {r#"
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
Expand All @@ -72,6 +78,45 @@ mod tests {
id String @id
}
"#};
let datamodel = SchemaFileInput::Single(schema.to_string());

let expected = expect![[r#"
[
{
"start": 149,
"end": 163,
"text": "Preview feature \"createMany\" is deprecated. The functionality can be used without specifying it as a preview feature.",
"is_warning": true
}
]"#]];

expected.assert_eq(&lint(datamodel));
}

#[test]
fn multi_deprecated_preview_features_should_give_a_warning() {
let schema1 = indoc! {r#"
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

generator client {
provider = "prisma-client-js"
previewFeatures = ["createMany"]
}
"#};

let schema2 = indoc! {r#"
model A {
id String @id
}
"#};

let datamodel = SchemaFileInput::Multiple(vec![
("schema1.prisma".to_string(), schema1.into()),
("schema2.prisma".to_string(), schema2.into()),
]);

let expected = expect![[r#"
[
Expand All @@ -83,6 +128,6 @@ mod tests {
}
]"#]];

expected.assert_eq(&lint(dml));
expected.assert_eq(&lint(datamodel));
}
}
6 changes: 3 additions & 3 deletions prisma-fmt/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
mod actions;
mod format;
mod lint;
// mod lint;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Changes to main.rs are necessary to let prisma-fmt compile.
I commented out the prisma-fmt lint command keeping in mind that, with https://github.com/prisma/team-orm/issues/1100, we will soon get rid of prisma-fmt's binary anyway

mod native;
mod preview;

Expand Down Expand Up @@ -30,7 +30,7 @@ pub struct FormatOpts {
/// Prisma Datamodel v2 formatter
pub enum FmtOpts {
/// Specifies linter mode
Lint,
// Lint,
/// Specifies format mode
Format(FormatOpts),
/// Specifies Native Types mode
Expand All @@ -46,7 +46,7 @@ pub enum FmtOpts {
fn main() {
match FmtOpts::from_args() {
FmtOpts::DebugPanic => panic!("This is the debugPanic artificial panic"),
FmtOpts::Lint => plug(lint::run),
// FmtOpts::Lint => plug(lint::run),
FmtOpts::Format(opts) => format::run(opts),
FmtOpts::NativeTypes => plug(native::run),
FmtOpts::ReferentialActions => plug(actions::run),
Expand Down
7 changes: 2 additions & 5 deletions prisma-fmt/src/schema_file_input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,14 @@ use serde::Deserialize;
#[serde(untagged)]
pub(crate) enum SchemaFileInput {
Single(String),
Multiple(Vec<(String, String)>),
Multiple(Vec<(String, SourceFile)>),
}

impl From<SchemaFileInput> for Vec<(String, SourceFile)> {
fn from(value: SchemaFileInput) -> Self {
match value {
SchemaFileInput::Single(content) => vec![("schema.prisma".to_owned(), content.into())],
SchemaFileInput::Multiple(file_list) => file_list
.into_iter()
.map(|(filename, content)| (filename, content.into()))
.collect(),
SchemaFileInput::Multiple(file_list) => file_list,
}
}
}
2 changes: 1 addition & 1 deletion prisma-schema-wasm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ fn register_panic_hook() {
#[wasm_bindgen]
pub fn format(schema: String, params: String) -> String {
register_panic_hook();
prisma_fmt::format(&schema, &params)
prisma_fmt::format(schema, &params)
}

/// Docs: https://prisma.github.io/prisma-engines/doc/prisma_fmt/fn.get_config.html
Expand Down
2 changes: 2 additions & 0 deletions psl/schema-ast/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ diagnostics = { path = "../diagnostics" }

pest = "2.1.3"
pest_derive = "2.1.0"
serde.workspace = true
serde_json.workspace = true
12 changes: 12 additions & 0 deletions psl/schema-ast/src/source_file.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
use std::sync::Arc;

use serde::{Deserialize, Deserializer};

/// A Prisma schema document.
#[derive(Debug, Clone)]
pub struct SourceFile {
contents: Contents,
}

impl<'de> Deserialize<'de> for SourceFile {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s: String = serde::de::Deserialize::deserialize(deserializer)?;
Ok(s.into())
}
}
Comment on lines +11 to +19
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This allows deriving Multiple(Vec<(String, SourceFile)>) from Vec<(String, String)> within the following:

#[derive(Deserialize, Debug)]
#[serde(untagged)]
pub(crate) enum SchemaFileInput {
    Single(String),
    Multiple(Vec<(String, SourceFile)>),
}

It also highlights that SourceFile is created from a String.

Copy link
Contributor

Choose a reason for hiding this comment

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

Nice!
Wouldn't putting #[serde(transparent)] over SourceFile do the same?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Afaik it wouldn't be the same, as SourceFile is essentially a newtype over a Contents field, not a String field


impl Default for SourceFile {
fn default() -> Self {
Self {
Expand Down