From a89aaec1fbe1d7f501f58d9ea7a92feebda70e17 Mon Sep 17 00:00:00 2001 From: ByteDream Date: Thu, 3 Jun 2021 01:21:17 +0200 Subject: [PATCH] Added java-beautifier --- README.md | 1 + java-beautifier/README.md | 40 ++++++++++++++++++++++++++++++ java-beautifier/java-beautifier.py | 30 ++++++++++++++++++++++ 3 files changed, 71 insertions(+) create mode 100644 java-beautifier/README.md create mode 100755 java-beautifier/java-beautifier.py diff --git a/README.md b/README.md index fde8d7b..ebaf8b4 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ This repository contains some (linux) scripts I am using to simplify my daily wo - [Merge pdf files together](/merge-pdf) - [Rename files random](/randomize-filename) - [Rename files based on their MD5 hashsum](/hashify-filename) +- [Beautify java source code](/java-beautifier) If you want to use any of the (bash!) scripts globaly, see [pathify](/pathify) diff --git a/java-beautifier/README.md b/java-beautifier/README.md new file mode 100644 index 0000000..a33e097 --- /dev/null +++ b/java-beautifier/README.md @@ -0,0 +1,40 @@ +## Java beautifier + +Makes java code look like it should. + +#### Usage + +Beautifies a java file. + +`./java-beautifier.py ` + +#### Example + +1. Create `Main.java` with the content + ```java + public class Main { + + public static void main(String[] args) { + System.out.println("I'm so beautiful"); + } + + public static class UnnecessarySubClass { + public static void unnecessaryVoid() { + System.out.println("Hello, i'm unnecessary"); + } + } + + } + ``` + +2. Beautify the file: `./java-beautifier.py Main.java` + +3. Look at the beautiful output + ```java + public class Main { + public static void main(String[] args) { + System.out.println("I'm so beautiful"); } + public static class UnnecessarySubClass { + public static void unnecessaryVoid() { + System.out.println("Hello, i'm unnecessary"); }}} + ``` diff --git a/java-beautifier/java-beautifier.py b/java-beautifier/java-beautifier.py new file mode 100755 index 0000000..a754240 --- /dev/null +++ b/java-beautifier/java-beautifier.py @@ -0,0 +1,30 @@ +#!/usr/bin/python3 + +import sys + +if __name__ == '__main__': + file = sys.argv[-1] + + lenght = 0 + content = [] + new_content = [] + + for line in open(file, 'r'): + line = line.strip() + if line: + if len(line) > lenght: + lenght = len(line) + content.append(line) + + lenght = lenght + 2 + + for i, line in enumerate(content): + if line and line[-1] in ('{', '}'): + if len(line.strip()) == 1 and i != 0: + new_content[-1] += ' ' * (lenght - len(new_content[-1]) - 1) + line[-1] + else: + new_content.append(line[:-1] + (' ' * (lenght - len(line))) + line[-1]) + else: + new_content.append(line) + + sys.stdout.write('\n'.join(new_content))