Skip to content

Commit

Permalink
fix: add --lang aliases (#544)
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex-ley-scrub authored Oct 23, 2024
1 parent 835c1e5 commit e5d3023
Show file tree
Hide file tree
Showing 2 changed files with 162 additions and 9 deletions.
92 changes: 92 additions & 0 deletions crates/cli_bin/tests/apply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2821,6 +2821,98 @@ def renamed(name):
Ok(())
}

/// simple stdin example from documentation
#[test]
fn apply_stdin_simple() -> Result<()> {
let (_temp_dir, fixture_dir) = get_fixture("limit_files", false)?;

let input_file = r#"console.log(hello)"#;
let expected_output = r#"console.log(goodbye)"#;

let mut cmd = get_test_cmd()?;
cmd.arg("apply")
.arg("`hello` => `goodbye`")
.arg("--stdin")
.arg("--lang")
.arg("js")
.current_dir(&fixture_dir);

cmd.write_stdin(String::from_utf8(input_file.into())?);

let result = cmd.output()?;

let stderr = String::from_utf8(result.stderr)?;
println!("stderr: {:?}", stderr);
let stdout = String::from_utf8(result.stdout)?;
println!("stdout: {:?}", stdout);

assert!(result.status.success(), "Command should have succeeded");
assert!(stdout.contains(expected_output));

Ok(())
}

/// simple stdin example from documentation, but using a language alias
#[test]
fn apply_stdin_with_lang_alias() -> Result<()> {
let (_temp_dir, fixture_dir) = get_fixture("limit_files", false)?;

let input_file = r#"console.log(hello)"#;
let expected_output = r#"console.log(goodbye)"#;

let mut cmd = get_test_cmd()?;
cmd.arg("apply")
.arg("`hello` => `goodbye`")
.arg("--stdin")
.arg("--lang")
.arg("javascript")
.current_dir(&fixture_dir);

cmd.write_stdin(String::from_utf8(input_file.into())?);

let result = cmd.output()?;

let stderr = String::from_utf8(result.stderr)?;
println!("stderr: {:?}", stderr);
let stdout = String::from_utf8(result.stdout)?;
println!("stdout: {:?}", stdout);

assert!(result.status.success(), "Command should have succeeded");
assert!(stdout.contains(expected_output));

Ok(())
}

/// simple stdin example from documentation, but using a language alias
#[test]
fn apply_stdin_with_invalid_lang_alias() -> Result<()> {
let (_temp_dir, fixture_dir) = get_fixture("limit_files", false)?;

let input_file = r#"console.log(hello)"#;

let mut cmd = get_test_cmd()?;
cmd.arg("apply")
.arg("`hello` => `goodbye`")
.arg("--stdin")
.arg("--lang")
.arg("markdowninline")
.current_dir(&fixture_dir);

cmd.write_stdin(String::from_utf8(input_file.into())?);

let result = cmd.output()?;

let stderr = String::from_utf8(result.stderr)?;
println!("stderr: {:?}", stderr);
let stdout = String::from_utf8(result.stdout)?;
println!("stdout: {:?}", stdout);

assert!(!result.status.success(), "Command should have failed");
assert!(stderr.contains("markdowninline"));

Ok(())
}

/// Ban multiple stdin paths
#[test]
fn apply_stdin_two_paths() -> Result<()> {
Expand Down
79 changes: 70 additions & 9 deletions crates/language/src/target_language.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ use crate::{
yaml::Yaml,
};
use anyhow::Result;
use clap::builder::PossibleValue;
use clap::ValueEnum;
use grit_util::Order;
use grit_util::{Ast, AstNode, ByteRange, CodeRange, Language, Parser, SnippetTree};
Expand All @@ -45,16 +46,12 @@ use std::path::PathBuf;
#[cfg(feature = "finder")]
use std::str::FromStr;

#[derive(ValueEnum, Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[clap(rename_all = "lower")]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PatternLanguage {
#[value(skip)]
JavaScript,
#[value(skip)]
TypeScript,
#[default]
#[value(name = "js")]
#[serde(rename = "js")]
Tsx,
Html,
Expand All @@ -63,9 +60,7 @@ pub enum PatternLanguage {
Java,
CSharp,
Python,
#[value(name = "markdown")]
MarkdownBlock,
#[value(skip)]
MarkdownInline,
Go,
Rust,
Expand All @@ -78,7 +73,6 @@ pub enum PatternLanguage {
Toml,
Php,
PhpOnly,
#[value(skip)]
Universal,
}

Expand Down Expand Up @@ -118,6 +112,46 @@ impl From<&TargetLanguage> for PatternLanguage {
}
}

// see: https://github.com/clap-rs/clap/issues/4416
impl ValueEnum for PatternLanguage {
// we need to implement the skip variants here ourselves now
fn value_variants<'a>() -> &'a [Self] {
&[
Self::Tsx,
Self::Html,
Self::Css,
Self::Json,
Self::Java,
Self::CSharp,
Self::Python,
Self::MarkdownBlock,
Self::Go,
Self::Rust,
Self::Ruby,
Self::Solidity,
Self::Hcl,
Self::Yaml,
Self::Sql,
Self::Vue,
Self::Toml,
Self::Php,
Self::PhpOnly,
]
}

// we need to implement the lowercase/rename transformations here ourselves now
// but we use fmt / .to_string() to do so
fn to_possible_value<'a>(&self) -> Option<PossibleValue> {
// needed to convert String to &'static str
let lang_name: &'static str = Box::leak(self.to_string().into_boxed_str());
Some(
PossibleValue::new(lang_name)
.aliases(self.get_file_extensions())
.aliases(self.get_lang_aliases()),
)
}
}

impl PatternLanguage {
pub fn from_tree(tree: &Tree) -> Option<Self> {
let root = tree.root_node();
Expand Down Expand Up @@ -174,7 +208,7 @@ impl PatternLanguage {
}

pub fn from_string(name: &str, flavor: Option<&str>) -> Option<Self> {
match name {
let lang = match name {
"js" => match flavor {
Some("jsx") => Some(Self::Tsx),
Some("flow") => Some(Self::Tsx),
Expand Down Expand Up @@ -211,6 +245,33 @@ impl PatternLanguage {
},
"universal" => Some(Self::Universal),
_ => None,
};
if let Some(lang) = lang {
return Some(lang);
}
if let Some(lang) = Self::from_extension(name) {
return Some(lang);
}
let name = name.to_lowercase();
for lang in PatternLanguage::enumerate() {
for alias in lang.get_lang_aliases() {
if *alias == name {
return Some(lang);
}
}
}
None
}

// https://github.com/getgrit/gritql/issues/445
// add any more language aliases here
fn get_lang_aliases(&self) -> &'static [&'static str] {
match self {
PatternLanguage::JavaScript => &["javascript"],
PatternLanguage::TypeScript => &["typescript"],
PatternLanguage::Tsx => &["javascript", "typescript", "flow"],
PatternLanguage::Sql => &["mysql", "postgresql"],
_ => &[],
}
}

Expand Down

0 comments on commit e5d3023

Please sign in to comment.