Skip to content

Commit

Permalink
restructure code
Browse files Browse the repository at this point in the history
  • Loading branch information
tusharmath committed Apr 16, 2024
1 parent c6a30ad commit 79aef83
Show file tree
Hide file tree
Showing 6 changed files with 105 additions and 62 deletions.
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.

4 changes: 3 additions & 1 deletion tailcall-prettier/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@ edition = "2021"

[dependencies]
anyhow = "1.0.82"
strum_macros = "0.26.2"
lazy_static = "1.4.0"
strum_macros = "0.26.2"
tokio.workspace = true
75 changes: 14 additions & 61 deletions tailcall-prettier/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,72 +1,25 @@
use std::io::Write;
use std::process::{Command, Stdio};

use anyhow::{anyhow, Result};

#[derive(strum_macros::Display)]
pub enum Parser {
Gql,
Yml,
Json,
Md,
Ts,
Js,
}

impl Parser {
pub fn detect(path: &str) -> Result<Self> {
let ext = path
.split('.')
.last()
.ok_or(anyhow!("No file extension found"))?
.to_lowercase();
match ext.as_str() {
"gql" | "graphql" => Ok(Parser::Gql),
"yml" | "yaml" => Ok(Parser::Yml),
"json" => Ok(Parser::Json),
"md" => Ok(Parser::Md),
"ts" => Ok(Parser::Ts),
"js" => Ok(Parser::Js),
_ => Err(anyhow!("Unsupported file type")),
}
}
}

fn get_command() -> Command {
if cfg!(target_os = "windows") {
Command::new("prettier.cmd")
} else {
Command::new("prettier")
}
use std::sync::Arc;
mod parser;
mod prettier;
use anyhow::Result;
pub use parser::Parser;
use prettier::Prettier;

lazy_static::lazy_static! {
static ref PRETTIER: Arc<Prettier> = Arc::new(Prettier::new());
}

pub fn format<T: AsRef<str>>(source: T, parser: Parser) -> Result<String> {
let mut child = get_command()
.arg("--stdin-filepath")
.arg(format!("file.{}", parser))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?;

if let Some(ref mut stdin) = child.stdin {
stdin.write_all(source.as_ref().as_bytes())?;
}

let output = child.wait_with_output()?;
if output.status.success() {
Ok(String::from_utf8(output.stdout)?)
} else {
Err(anyhow!("Prettier formatting failed"))
}
pub async fn format<T: AsRef<str>>(source: T, parser: Parser) -> Result<String> {
PRETTIER.format(source.as_ref().to_string(), parser).await
}

#[cfg(test)]
mod tests {
use crate::{format, Parser};

#[test]
fn test_js() -> anyhow::Result<()> {
let prettier = format("const x={a:3};", Parser::Js)?;
#[tokio::test]
async fn test_js() -> anyhow::Result<()> {
let prettier = format("const x={a:3};", Parser::Js).await?;
assert_eq!("const x = {a: 3}\n", prettier);
Ok(())
}
Expand Down
30 changes: 30 additions & 0 deletions tailcall-prettier/src/parser.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use anyhow::{anyhow, Result};

#[derive(strum_macros::Display)]
pub enum Parser {
Gql,
Yml,
Json,
Md,
Ts,
Js,
}

impl Parser {
pub fn detect(path: &str) -> Result<Self> {
let ext = path
.split('.')
.last()
.ok_or(anyhow!("No file extension found"))?
.to_lowercase();
match ext.as_str() {
"gql" | "graphql" => Ok(Parser::Gql),
"yml" | "yaml" => Ok(Parser::Yml),
"json" => Ok(Parser::Json),
"md" => Ok(Parser::Md),
"ts" => Ok(Parser::Ts),
"js" => Ok(Parser::Js),
_ => Err(anyhow!("Unsupported file type")),

Check warning on line 27 in tailcall-prettier/src/parser.rs

View check run for this annotation

Codecov / codecov/patch

tailcall-prettier/src/parser.rs#L25-L27

Added lines #L25 - L27 were not covered by tests
}
}
}
54 changes: 54 additions & 0 deletions tailcall-prettier/src/prettier.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
use std::io::Write;
use std::process::{Command, Stdio};

use anyhow::{anyhow, Result};

pub use super::Parser;

pub struct Prettier {
runtime: tokio::runtime::Runtime,
}

impl Prettier {
pub fn new() -> Prettier {
let runtime = tokio::runtime::Builder::new_multi_thread()
.max_blocking_threads(1024)
.build()
.unwrap();

Self { runtime }
}

pub async fn format(&self, source: String, parser: Parser) -> Result<String> {
self.runtime
.spawn_blocking(move || {
let mut command = command();
let mut child = command
.arg("--stdin-filepath")
.arg(format!("file.{}", parser))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?;

if let Some(ref mut stdin) = child.stdin {
stdin.write_all(source.as_bytes())?;
}

Check warning on line 35 in tailcall-prettier/src/prettier.rs

View check run for this annotation

Codecov / codecov/patch

tailcall-prettier/src/prettier.rs#L35

Added line #L35 was not covered by tests

let output = child.wait_with_output()?;
if output.status.success() {
Ok(String::from_utf8(output.stdout)?)
} else {
Err(anyhow!("Prettier formatting failed"))

Check warning on line 41 in tailcall-prettier/src/prettier.rs

View check run for this annotation

Codecov / codecov/patch

tailcall-prettier/src/prettier.rs#L41

Added line #L41 was not covered by tests
}
})
.await?
}
}

fn command() -> Command {
if cfg!(target_os = "windows") {
Command::new("prettier.cmd")

Check warning on line 50 in tailcall-prettier/src/prettier.rs

View check run for this annotation

Codecov / codecov/patch

tailcall-prettier/src/prettier.rs#L50

Added line #L50 was not covered by tests
} else {
Command::new("prettier")
}
}
2 changes: 2 additions & 0 deletions tests/execution_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -895,12 +895,14 @@ async fn assert_spec(spec: ExecutionSpec, opentelemetry: &InMemoryTelemetry) {
identity,
tailcall_prettier::Parser::detect(path_str.as_str()).unwrap(),
)
.await
.unwrap();

let content = tailcall_prettier::format(
content,
tailcall_prettier::Parser::detect(path_str.as_str()).unwrap(),
)
.await
.unwrap();

pretty_assertions::assert_eq!(
Expand Down

0 comments on commit 79aef83

Please sign in to comment.