format.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * ECAL
  3. *
  4. * Copyright 2020 Matthias Ladkau. All rights reserved.
  5. *
  6. * This Source Code Form is subject to the terms of the MIT
  7. * License, If a copy of the MIT License was not distributed with this
  8. * file, You can obtain one at https://opensource.org/licenses/MIT.
  9. */
  10. package tool
  11. import (
  12. "flag"
  13. "fmt"
  14. "io/ioutil"
  15. "os"
  16. "path/filepath"
  17. "devt.de/krotik/ecal/parser"
  18. )
  19. func Format() error {
  20. var err error
  21. wd, _ := os.Getwd()
  22. dir := flag.String("dir", wd, "Root directory for ECAL files")
  23. ext := flag.String("ext", ".ecal", "Extension for ECAL files")
  24. showHelp := flag.Bool("help", false, "Show this help message")
  25. flag.Usage = func() {
  26. fmt.Println()
  27. fmt.Println(fmt.Sprintf("Usage of %s format [options]", os.Args[0]))
  28. fmt.Println()
  29. flag.PrintDefaults()
  30. fmt.Println()
  31. fmt.Println("This tool will format all ECAL files in a directory structure.")
  32. fmt.Println()
  33. }
  34. if len(os.Args) >= 2 {
  35. flag.CommandLine.Parse(os.Args[2:])
  36. if *showHelp {
  37. flag.Usage()
  38. return nil
  39. }
  40. }
  41. fmt.Println(fmt.Sprintf("Formatting all %v files in %v", *ext, *dir))
  42. err = filepath.Walk(".",
  43. func(path string, i os.FileInfo, err error) error {
  44. if err == nil && !i.IsDir() {
  45. var data []byte
  46. var ast *parser.ASTNode
  47. var srcFormatted string
  48. if data, err = ioutil.ReadFile(path); err == nil {
  49. var ferr error
  50. if ast, ferr = parser.Parse(path, string(data)); ferr == nil {
  51. if srcFormatted, ferr = parser.PrettyPrint(ast); ferr == nil {
  52. ioutil.WriteFile(path, []byte(srcFormatted), i.Mode())
  53. }
  54. }
  55. if ferr != nil {
  56. fmt.Fprintln(os.Stderr, fmt.Sprintf("Could not format %v: %v", path, ferr))
  57. }
  58. }
  59. }
  60. return err
  61. })
  62. return err
  63. }