1
0

format_code.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package nginx
  2. import (
  3. "bufio"
  4. "github.com/emirpasic/gods/stacks/linkedliststack"
  5. "strings"
  6. )
  7. func fmtCode(content string) (fmtContent string) {
  8. fmtContent = fmtCodeWithIndent(content, 0)
  9. return
  10. }
  11. func fmtCodeWithIndent(content string, indent int) (fmtContent string) {
  12. /*
  13. Format content
  14. 1. TrimSpace for each line
  15. 2. use stack to count how many \t should add
  16. */
  17. stack := linkedliststack.New()
  18. scanner := bufio.NewScanner(strings.NewReader(content))
  19. for scanner.Scan() {
  20. text := scanner.Text()
  21. text = strings.TrimSpace(text)
  22. before := stack.Size()
  23. for _, char := range text {
  24. matchParentheses(stack, char)
  25. }
  26. after := stack.Size()
  27. fmtContent += strings.Repeat("\t", indent)
  28. if before == after {
  29. fmtContent += strings.Repeat("\t", stack.Size()) + text + "\n"
  30. } else {
  31. fmtContent += text + "\n"
  32. }
  33. }
  34. fmtContent = strings.Trim(fmtContent, "\n")
  35. return
  36. }