scop / bash-completion

Programmable completion functions for bash
GNU General Public License v2.0
2.95k stars 381 forks source link

Enable .java Filename Completion for java Command #1196

Closed jiri-pejchal closed 5 months ago

jiri-pejchal commented 6 months ago

Description

Enhance the bash completion scripts for the java command to complete filenames with the .java extension.

This enhancement is necessary to support:

which allows the java launcher to run a program supplied as a single file of Java source code:

java HelloWorld.java
jiri-pejchal commented 6 months ago

The completion could be further improved by having the completion suggest only .java files that contain the method main, which serves as the entry point for program execution.

Files without the main method cannot be launched with the java command.

Perhaps complete on .java files with content matching void main.

Following the implementation of JEP 477, the main method could appear in any of the following forms:

static void main(String[] args) {
  println("Hello, World!");
 }
static void main() {
  println("Hello, World!");
}
void main(String[] args) {
  println("Hello, World!");
}
void main() {
  println("Hello, World!");
}

I don't know if it is feasible or how it could be implemented.

akinomyoga commented 6 months ago

I don't know if it is feasible or how it could be implemented.

To perform that robustly, we would need a compiler or, at least, a Java parser. If the java command (or any associated tool) itself can list the files that contain the proper main function, we can use that.

One might think it could be possible to detect the main function by matching a fixed string, but it's not robust. That can mistakenly hit an unrelated string in a code comment, or it might miss the actual main function by a tiny style difference. I'm not sure if we should add the completions that can produce wrong results randomly at a small probability, because the users would learn to believe the list generated by bash-completion, which would tell a lie at a small probability and cause a mistake. [Note: Of course, it is not random in a strict sense, but it's non-trivial to explain to the users in what situations the completion fails or succeeds.]. That said, such a native implementation would probably work in most cases. This would be a matter of the preferences of the maintainer.