Skip to content

refactor: use more iterator and named format args #1

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

Merged
merged 8 commits into from
Nov 27, 2023
Merged
Show file tree
Hide file tree
Changes from 5 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
43 changes: 22 additions & 21 deletions src/format_text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,22 @@ use anyhow::Result;
use jsonc_parser::CollectOptions;
use jsonc_parser::ParseOptions;

const COLLECT_OPTIONS: CollectOptions = CollectOptions {
comments: false,
tokens: false,
};

const PARSE_OPTIONS: ParseOptions = ParseOptions {
allow_comments: true,
allow_loose_object_property_names: true,
allow_trailing_commas: true,
};

pub fn format_text(
input_text: &str,
format_with_host: impl FnMut(&Path, String) -> Result<Option<String>>,
) -> Result<Option<String>> {
let parse_result = jsonc_parser::parse_to_ast(
input_text,
&CollectOptions {
comments: false,
tokens: false,
},
&ParseOptions {
allow_comments: true,
allow_loose_object_property_names: true,
allow_trailing_commas: true,
},
)?;
let parse_result = jsonc_parser::parse_to_ast(input_text, &COLLECT_OPTIONS, &PARSE_OPTIONS)?;
let Some(root_value) = parse_result.value else {
return Ok(None);
};
Expand All @@ -39,13 +39,13 @@ fn format_root(
let root_obj = root_value.as_object()?;
let maybe_default_language = get_metadata_language(root_obj);
let cells = root_value.as_object()?.get_array("cells")?;
let mut text_changes = Vec::new();
for element in &cells.elements {
let maybe_text_change = get_cell_text_change(input_text, element, maybe_default_language, &mut format_with_host);
if let Some(text_change) = maybe_text_change {
text_changes.push(text_change);
}
}

let text_changes: Vec<TextChange> = cells
.elements
.iter()
.filter_map(|element| get_cell_text_change(input_text, element, maybe_default_language, &mut format_with_host))
.collect();

if text_changes.is_empty() {
None
} else {
Expand Down Expand Up @@ -105,6 +105,7 @@ fn analyze_code_block<'a>(cell: &jsonc_parser::ast::Object<'a>, file_text: &'a s
}
strings.push(&string_lit.value);
}

let mut text = String::with_capacity(strings.iter().map(|s| s.len()).sum::<usize>());
for string in strings {
text.push_str(string);
Expand Down Expand Up @@ -137,7 +138,7 @@ fn build_json_text(formatted_text: &str, indent_text: &str) -> String {
if is_last_line {
Cow::Borrowed(line)
} else {
Cow::Owned(format!("{}\n", line))
Cow::Owned(format!("{line}\n"))
}
.as_ref(),
)
Expand Down Expand Up @@ -183,7 +184,7 @@ fn language_to_path(language: &str) -> Option<PathBuf> {
"yaml" => Some("yml"),
_ => None,
};
ext.map(|ext| PathBuf::from(format!("code_block.{}", ext)))
ext.map(|ext| PathBuf::from(format!("code_block.{ext}")))
}

fn get_indent_text(file_text: &str, start_pos: usize) -> &str {
Expand Down
30 changes: 15 additions & 15 deletions src/text_changes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,27 +32,27 @@ pub fn apply_text_changes(source: &str, mut changes: Vec<TextChange>) -> String
let mut last_index = 0;
let mut final_text = String::new();

for (i, change) in changes.iter().enumerate() {
if change.range.start > change.range.end {
for (i, TextChange { range, new_text, .. }) in changes.iter().enumerate() {
if range.start > range.end {
panic!(
"Text change had start index {} greater than end index {}.\n\n{:?}",
change.range.start,
change.range.end,
&changes[0..i + 1],
"Text change had start index {start} greater than end index {end}.\n\n{changes:?}",
start = range.start,
end = range.end,
changes = &changes[0..i + 1],
)
}
if change.range.start < last_index {
if range.start < last_index {
panic!(
"Text changes were overlapping. Past index was {}, but new change had index {}.\n\n{:?}",
last_index,
change.range.start,
&changes[0..i + 1]
"Text changes were overlapping. Past index was {past}, but new change had index {new}.\n\n{changes:?}",
past = last_index,
new = range.start,
changes = &changes[0..i + 1]
);
} else if change.range.start > last_index && last_index < source.len() {
final_text.push_str(&source[last_index..std::cmp::min(source.len(), change.range.start)]);
} else if range.start > last_index && last_index < source.len() {
final_text.push_str(&source[last_index..std::cmp::min(source.len(), range.start)]);
}
final_text.push_str(&change.new_text);
last_index = change.range.end;
final_text.push_str(new_text);
last_index = range.end;
}

if last_index < source.len() {
Expand Down
5 changes: 1 addition & 4 deletions src/wasm_plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,7 @@ impl SyncPluginHandler<Configuration> for JupyterPluginHandler {
version: version.clone(),
config_key: "jupyter".to_string(),
help_url: "https://dprint.dev/plugins/jupyter".to_string(),
config_schema_url: format!(
"https://plugins.dprint.dev/dprint/dprint-plugin-jupyter/{}/schema.json",
version
),
config_schema_url: format!("https://plugins.dprint.dev/dprint/dprint-plugin-jupyter/{version}/schema.json"),
update_url: Some("https://plugins.dprint.dev/dprint/dprint-plugin-jupyter/latest.json".to_string()),
},
file_matching: FileMatchingInfo {
Expand Down
6 changes: 3 additions & 3 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,19 +31,19 @@ fn test_specs() {
|path, text| {
if path.ends_with("code_block.py") {
if !text.ends_with("_python") {
Ok(Some(format!("{}_python", text)))
Ok(Some(format!("{text}_python")))
} else {
Ok(None)
}
} else if path.ends_with("code_block.md") {
if !text.ends_with("_markdown") {
Ok(Some(format!("{}_markdown", text)))
Ok(Some(format!("{text}_markdown")))
} else {
Ok(None)
}
} else if path.ends_with("code_block.ts") {
if !text.ends_with("_typescript") {
Ok(Some(format!("{}_typescript", text)))
Ok(Some(format!("{text}_typescript")))
} else {
Ok(None)
}
Expand Down