Skip to content

Offline, privacy-first grammar checker. Fast, open-source, Rust-powered

feat(cli): allow `forms` subcommand to accept multiple arguments (#2996)

Abhishek Deshmukh66bf00b63419
diff --git a/harper-cli/src/main.rs b/harper-cli/src/main.rs
index 44e4a2d75..b568c308c 100644
--- a/harper-cli/src/main.rs
+++ b/harper-cli/src/main.rs
@@ -128,7 +128,10 @@ enum Args {
brief: bool,
},
/// Get all the forms of a word using the affixes.
- Forms { line: String },
+ Forms {
+ #[arg(num_args = 1..)]
+ lines: Vec<String>,
+ },
/// Emit a decompressed, line-separated list of the words in Harper's dictionary.
Words,
/// Summarize a lint record
@@ -210,7 +213,7 @@ enum Args {
/// As long as there's either an open or hyphenated spelling.
Compounds,
/// Emit a decompressed, line-separated list of the words in Harper's dictionary
- /// which occur in more than one lettercase variant.
+ /// which occur in more than one lettercase variant.
CaseVariants,
/// Emit a list of each noun phrase contained within the input
NominalPhrases {
@@ -436,65 +439,72 @@ fn main() -> anyhow::Result<()> {
Ok(())
}
- Args::Forms { line } => {
- let (word, annot) = line_to_parts(&line);
+ Args::Forms { lines } => {
+ for (i, line) in lines.iter().enumerate() {
+ if i > 0 {
+ println!();
+ }
- let curated_word_list = include_str!("../../harper-core/dictionary.dict");
- let dict_lines = curated_word_list.split('\n');
+ let (word, annot) = line_to_parts(line);
- let mut entry_in_dict = None;
+ let curated_word_list = include_str!("../../harper-core/dictionary.dict");
+ let dict_lines = curated_word_list.split('\n');
- // Check if the word is contained in the list.
- for dict_line in dict_lines {
- let (dict_word, dict_annot) = line_to_parts(dict_line);
+ let mut entry_in_dict = None;
- if dict_word == word {
- entry_in_dict = Some((dict_word, dict_annot));
- break;
- }
- }
+ // Check if the word is contained in the list.
+ for dict_line in dict_lines {
+ let (dict_word, dict_annot) = line_to_parts(dict_line);
- let summary = match &entry_in_dict {
- Some((dict_word, dict_annot)) => {
- let mut status_summary = if dict_annot.is_empty() {
- format!("'{dict_word}' is already in the dictionary but not annotated.")
- } else {
- format!(
- "'{dict_word}' is already in the dictionary with annotation `{dict_annot}`."
- )
- };
+ if dict_word == word {
+ entry_in_dict = Some((dict_word, dict_annot));
+ break;
+ }
+ }
- if !annot.is_empty() {
- if annot.as_str() != dict_annot.as_str() {
- status_summary
- .push_str("\n Your annotations differ from the dictionary.\n");
+ let summary = match &entry_in_dict {
+ Some((dict_word, dict_annot)) => {
+ let mut status_summary = if dict_annot.is_empty() {
+ format!("'{dict_word}' is already in the dictionary but not annotated.")
} else {
- status_summary
- .push_str("\n Your annotations are the same as the dictionary.\n");
+ format!(
+ "'{dict_word}' is already in the dictionary with annotation `{dict_annot}`."
+ )
+ };
+
+ if !annot.is_empty() {
+ if annot.as_str() != dict_annot.as_str() {
+ status_summary
+ .push_str("\n Your annotations differ from the dictionary.\n");
+ } else {
+ status_summary.push_str(
+ "\n Your annotations are the same as the dictionary.\n",
+ );
+ }
}
+
+ status_summary
}
+ None => format!("'{word}' is not in the dictionary yet."),
+ };
- status_summary
- }
- None => format!("'{word}' is not in the dictionary yet."),
- };
+ println!("{summary}");
- println!("{summary}");
-
- if let Some((dict_word, dict_annot)) = &entry_in_dict {
- println!("Old, from the dictionary:");
- print_word_derivations(dict_word, dict_annot, &FstDictionary::curated());
- };
+ if let Some((dict_word, dict_annot)) = &entry_in_dict {
+ println!("Old, from the dictionary:");
+ print_word_derivations(dict_word, dict_annot, &FstDictionary::curated());
+ };
- if !annot.is_empty() {
- let rune_words = format!("1\n{line}");
- let dict = MutableDictionary::from_rune_files(
- &rune_words,
- include_str!("../../harper-core/annotations.json"),
- )?;
+ if !annot.is_empty() {
+ let rune_words = format!("1\n{line}");
+ let dict = MutableDictionary::from_rune_files(
+ &rune_words,
+ include_str!("../../harper-core/annotations.json"),
+ )?;
- println!("New, from you:");
- print_word_derivations(&word, &annot, &dict);
+ println!("New, from you:");
+ print_word_derivations(&word, &annot, &dict);
+ }
}
Ok(())
diff --git a/justfile b/justfile
index 06d4726a8..33edcca1d 100644
--- a/justfile
+++ b/justfile
@@ -74,7 +74,7 @@ build-wasm:
# Build `harper.js` with all size optimizations available.
alias build-harper-js := build-harperjs
-build-harperjs: build-wasm
+build-harperjs: build-wasm
#!/usr/bin/env bash
set -eo pipefail
@@ -130,7 +130,7 @@ dev-wp: build-harperjs
cd "{{justfile_directory()}}/packages/wordpress-plugin"
pnpm install
pnpm wp-now start &
- pnpm start
+ pnpm start
# Build the WordPress plugin
alias build-wordpress := build-wp
@@ -156,7 +156,7 @@ dev-web: build-harperjs build-lint-framework build-components build-harper-edito
build-web: build-harperjs build-lint-framework build-components build-harper-editor
#!/usr/bin/env bash
set -eo pipefail
-
+
cd "{{justfile_directory()}}/packages/web"
pnpm install
pnpm build
@@ -229,7 +229,7 @@ build-desktop-macos-unsigned: build-harperjs build-lint-framework build-componen
build-obsidian: build-harperjs
#!/usr/bin/env bash
set -eo pipefail
-
+
cd "{{justfile_directory()}}/packages/obsidian-plugin"
max_bundle_size_bytes=$((30 * 1024 * 1024))
@@ -255,10 +255,10 @@ alias build-chrome-extension := build-chrome-plugin
build-chrome-plugin: build-harperjs build-lint-framework build-components
#!/usr/bin/env bash
set -eo pipefail
-
+
cd "{{justfile_directory()}}/packages/chrome-plugin"
- pnpm install
+ pnpm install
pnpm zip-for-chrome
# Start a development server for the Chrome extension.
@@ -267,10 +267,10 @@ alias dev-chrome-extension := dev-chrome-plugin
dev-chrome-plugin: build-harperjs build-lint-framework build-components
#!/usr/bin/env bash
set -eo pipefail
-
+
cd "{{justfile_directory()}}/packages/chrome-plugin"
- pnpm install
+ pnpm install
pnpm dev
# Build the Firefox extension.
@@ -279,10 +279,10 @@ alias build-firefox-extension := build-firefox-plugin
build-firefox-plugin: build-harperjs build-lint-framework build-components
#!/usr/bin/env bash
set -eo pipefail
-
+
cd "{{justfile_directory()}}/packages/chrome-plugin"
- pnpm install
+ pnpm install
pnpm zip-for-firefox
alias test-chrome := test-chrome-plugin
@@ -316,7 +316,7 @@ test-firefox-plugin: build-firefox-plugin
if [[ "$(uname)" == "Linux" ]] && [[ -z "$DISPLAY" ]]; then
xvfb-run --auto-servernum pnpm test --project firefox
else
- pnpm test --project firefox
+ pnpm test --project firefox
fi
# Run VSCode plugin unit and integration tests.
@@ -452,7 +452,7 @@ check-js: build-harperjs build-lint-framework build-components build-harper-edit
setup: build-harperjs test-harperjs test-vscode build-web build-wp build-obsidian build-chrome-plugin
# Perform full format and type checking, build all projects and run all tests. Run this before pushing your code.
-precommit: check test build-harperjs build-obsidian build-web build-wp build-firefox-plugin build-chrome-plugin
+precommit: check test build-harperjs build-obsidian build-web build-wp build-firefox-plugin build-chrome-plugin
#!/usr/bin/env bash
set -eo pipefail
@@ -461,14 +461,14 @@ precommit: check test build-harperjs build-obsidian build-web build-wp build-fir
# Install `harper-cli` and `harper-ls` to your machine via `cargo`
install:
- cargo install --path harper-ls --locked
- cargo install --path harper-cli --locked
+ cargo install --path harper-ls --locked
+ cargo install --path harper-cli --locked
# Run `harper-cli` on the Harper repository
dogfood:
#!/usr/bin/env bash
cargo build --release
-
+
if command -v fd &> /dev/null; then
# Use fd if available (faster and more user-friendly)
fd_cmd() { fd -e rs; }
@@ -507,7 +507,7 @@ spans file:
alias add-noun := addnoun
addnoun noun:
#!/usr/bin/env bash
- DICT_FILE=./harper-core/dictionary.dict
+ DICT_FILE=./harper-core/dictionary.dict
cat $DICT_FILE | grep "^{{noun}}/"
@@ -559,14 +559,14 @@ get-metadata-brief *words:
cargo run --bin harper-cli -- metadata --brief {{words}}
# Get all the forms of a word using the affixes.
-get-forms word:
- cargo run --bin harper-cli -- forms {{word}}
+get-forms +words:
+ cargo run --bin harper-cli -- forms {{words}}
# Get a random sample of words from Harper's dictionary and list all forms of each.
sample-forms count:
#!/usr/bin/env bash
set -eo pipefail
- DICT_FILE=./harper-core/dictionary.dict
+ DICT_FILE=./harper-core/dictionary.dict
# USER_DICT_FILE="$HOME/.config/harper-ls/dictionary.txt"
if [ "{{count}}" -eq 0 ]; then
@@ -574,7 +574,7 @@ sample-forms count:
fi
total_lines=$(wc -l < $DICT_FILE)
-
+
# Cross-platform random line selection
if command -v shuf >/dev/null 2>&1; then
words=$(shuf -n "{{count}}" "$DICT_FILE")
@@ -586,7 +586,7 @@ sample-forms count:
echo "Error: Neither 'shuf' nor 'jot' found. Cannot generate random words." >&2
exit 1
fi
-
+
cargo run --bin harper-cli -- forms $words
bump-versions: update-vscode-linters
@@ -634,7 +634,7 @@ bump-versions: update-vscode-linters
# Enter an infinite loop of property testing until a bug is found.
fuzz:
#!/usr/bin/env bash
-
+
while true
do
QUICKCHECK_TESTS=100000 cargo test
@@ -665,7 +665,7 @@ print-annotations:
...affixesData.affixes || {},
...affixesData.properties || {}
};
-
+
// Calculate the maximum description length for alignment
const entries = Object.entries(allEntries);
const maxDescLength = entries.reduce((max, [flag, fields]) => {
@@ -673,7 +673,7 @@ print-annotations:
const lineLength = flag.length + 2 + description.length; // flag + ': ' + description
return Math.max(max, lineLength);
}, 0);
-
+
entries.sort((a, b) => a[0].localeCompare(b[0])).forEach(([flag, fields]) => {
const description = fields['#'] || '';
const comment = fields['//'] || null;
@@ -683,24 +683,24 @@ print-annotations:
console.log(line + (comment ? `${padding}// ${comment}` : ''));
}
});
-
- console.log('Available letters for new flags:', [...Array.from({length: 26}, (_, i) =>
+
+ console.log('Available letters for new flags:', [...Array.from({length: 26}, (_, i) =>
[String.fromCharCode(65 + i), String.fromCharCode(97 + i)]
).flat()].filter(letter => !Object.keys(allEntries).includes(letter)).sort().join(' '));
- console.log('Available digits for new flags:', [...Array.from({length: 10}, (_, i) =>
+ console.log('Available digits for new flags:', [...Array.from({length: 10}, (_, i) =>
String(i)
)].filter(digit => !Object.keys(allEntries).includes(digit)).sort().join(' '));
console.log('Available symbols for new flags:',
[...Array.from('!"#$%&\'()*+,-./:;<=>?@\[\\\]\^_`{|}~')]
.filter(symbol => !Object.keys(allEntries).includes(symbol)).sort().join(' '));
- console.log('Available Latin-1 characters for new flags:');
+ console.log('Available Latin-1 characters for new flags:');
[...Array.from({length: 256-160}, (_, i) => String.fromCharCode(160 + i))]
.filter(char => !Object.keys(allEntries).includes(char) && char.charCodeAt(0) !== 160 && char.charCodeAt(0) !== 173)
.sort()
.join(' ')
.match(/.{1,64}/g)
.forEach(line => console.log(' ' + line));
-
+
# Get the most recent changes to the curated dictionary. Includes an optional argument to specify the number of commits to look back. Defaults to 1.
newest-dict-changes *numCommits:
#! /usr/bin/env node
@@ -818,21 +818,21 @@ suggest-annotation input:
...affixesData.affixes || {},
...affixesData.properties || {}
};
-
+
// Get all used flags
const usedFlags = new Set(Object.keys(allEntries));
-
+
// Process input string and check both cases
const input = '{{input}}';
const normalizedInput = input.replace(/\s/g, '');
const uniqueChars = [...new Set(normalizedInput.toUpperCase() + normalizedInput.toLowerCase())];
-
+
console.log(`Checking input: "${input}"\n${'='.repeat(50)}`);
-
+
// Check each character in input
const availableChars = [...new Set(uniqueChars)]
.filter(char => !usedFlags.has(char));
-
+
if (availableChars.length > 0) {
console.log(`These characters of "${input}" are available to use for new annotations:`);
availableChars.forEach(char => console.log(` '${char}' (${char.charCodeAt(0)})`));
@@ -841,7 +841,7 @@ suggest-annotation input:
const renamable = Object.entries(allEntries)
.filter(([flag, entry]) => entry.rename_ok && inputChars.has(flag))
.sort((a, b) => a[0].localeCompare(b[0]));
-
+
if (renamable.length > 0) {
console.log(`None of the characters of "${input}" are available to use for new annotations, but these ones are OK to be moved to make way for new annotations:`);
renamable.forEach(([flag, entry]) => {