commit fbfe9d6edf615c7993f2bc7d721ed88ade6faead Author: Dan Ballard Date: Wed May 20 14:44:58 2020 -0700 copy qmlfmt over from cwtch.im/ui/cmd/qmlfmt diff --git a/README.md b/README.md new file mode 100644 index 0000000..7416d12 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# qmlfmt + +`qmlfmt` in place edits the qml files specified on the command line applying fixed 4 space indent rules to them. This simple tool is aimed at projects working with QML but not using QT Creator so not benefiting from it's auto formating. diff --git a/qmlfmt.go b/qmlfmt.go new file mode 100644 index 0000000..ac109ad --- /dev/null +++ b/qmlfmt.go @@ -0,0 +1,91 @@ +package main + +import ( + "bufio" + "log" + "os" + "strings" +) + +const ( + indent = " " +) + +func main() { + if len(os.Args) < 2 { + log.Fatal("Required argument(s): filename(s)") + } + + for _, filename := range os.Args[1:] { + processFile(filename) + } + +} + +func processFile(filename string) { + file, err := os.Open(filename) + if err != nil { + log.Fatalf("Could not read file %v: %v\n", filename, err) + } + + scanner := bufio.NewScanner(file) + var lines []string + + for scanner.Scan() { + lines = append(lines, scanner.Text()) + } + + file.Close() + + file, err = os.Create(filename) + defer file.Close() + if err != nil { + log.Fatalf("Could not write to file %v: %v\n", filename, err) + } + + indentCount := 0 + inMultiLineComment := false + + for ln, line := range lines { + + singleCommentPos := strings.Index(line, "//") + multiLineCommentStartPos := strings.Index(line, "/*") + multiLineCommentEndPos := strings.Index(line, "*/") + + openPos := strings.Index(line, "{") + closePos := strings.Index(line, "}") + + if !inMultiLineComment && closePos > -1 && (openPos == -1 || openPos > closePos) && (singleCommentPos == -1 || closePos < singleCommentPos) && + (multiLineCommentStartPos == -1 || closePos < multiLineCommentStartPos) && + (multiLineCommentEndPos == -1 || closePos > multiLineCommentEndPos) { + indentCount-- + } + + trimedLine := strings.Trim(line, " \t") + if trimedLine == "" { + file.Write([]byte("\n")) + } else { + if indentCount < 0 { + log.Fatalf("indent Count negative in %v at line %v\n", filename, ln) + } + + file.Write([]byte(strings.Repeat(indent, indentCount) + trimedLine + "\n")) + } + + if !inMultiLineComment && openPos > -1 && (closePos == -1 || openPos > closePos) && (singleCommentPos == -1 || openPos < singleCommentPos) && + (multiLineCommentStartPos == -1 || openPos < multiLineCommentStartPos) && + (multiLineCommentEndPos == -1 || openPos > multiLineCommentEndPos) { + indentCount++ + } + + if multiLineCommentStartPos > -1 { + inMultiLineComment = true + } + + if multiLineCommentEndPos > -1 { + inMultiLineComment = false + } + + } + +}