format.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. "strings"
  18. "devt.de/krotik/ecal/parser"
  19. )
  20. /*
  21. Format formats a given set of ECAL files.
  22. */
  23. func Format() error {
  24. var err error
  25. wd, _ := os.Getwd()
  26. dir := flag.String("dir", wd, "Root directory for ECAL files")
  27. ext := flag.String("ext", ".ecal", "Extension for ECAL files")
  28. showHelp := flag.Bool("help", false, "Show this help message")
  29. flag.Usage = func() {
  30. fmt.Fprintln(flag.CommandLine.Output())
  31. fmt.Fprintln(flag.CommandLine.Output(), fmt.Sprintf("Usage of %s format [options]", os.Args[0]))
  32. fmt.Fprintln(flag.CommandLine.Output())
  33. flag.PrintDefaults()
  34. fmt.Fprintln(flag.CommandLine.Output())
  35. fmt.Fprintln(flag.CommandLine.Output(), "This tool will format all ECAL files in a directory structure.")
  36. fmt.Fprintln(flag.CommandLine.Output())
  37. }
  38. if len(os.Args) >= 2 {
  39. flag.CommandLine.Parse(osArgs[2:])
  40. if *showHelp {
  41. flag.Usage()
  42. return nil
  43. }
  44. }
  45. fmt.Fprintln(flag.CommandLine.Output(), fmt.Sprintf("Formatting all %v files in %v", *ext, *dir))
  46. err = filepath.Walk(*dir,
  47. func(path string, i os.FileInfo, err error) error {
  48. if err == nil && !i.IsDir() {
  49. var data []byte
  50. var ast *parser.ASTNode
  51. var srcFormatted string
  52. if strings.HasSuffix(path, *ext) {
  53. if data, err = ioutil.ReadFile(path); err == nil {
  54. var ferr error
  55. if ast, ferr = parser.Parse(path, string(data)); ferr == nil {
  56. if srcFormatted, ferr = parser.PrettyPrint(ast); ferr == nil {
  57. ioutil.WriteFile(path, []byte(srcFormatted), i.Mode())
  58. }
  59. }
  60. if ferr != nil {
  61. fmt.Fprintln(flag.CommandLine.Output(), fmt.Sprintf("Could not format %v: %v", path, ferr))
  62. }
  63. }
  64. }
  65. }
  66. return err
  67. })
  68. return err
  69. }