format.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. wd, _ := os.Getwd()
  25. dir := flag.String("dir", wd, "Root directory for ECAL files")
  26. ext := flag.String("ext", ".ecal", "Extension for ECAL files")
  27. showHelp := flag.Bool("help", false, "Show this help message")
  28. flag.Usage = func() {
  29. fmt.Fprintln(flag.CommandLine.Output())
  30. fmt.Fprintln(flag.CommandLine.Output(), fmt.Sprintf("Usage of %s format [options]", os.Args[0]))
  31. fmt.Fprintln(flag.CommandLine.Output())
  32. flag.PrintDefaults()
  33. fmt.Fprintln(flag.CommandLine.Output())
  34. fmt.Fprintln(flag.CommandLine.Output(), "This tool will format all ECAL files in a directory structure.")
  35. fmt.Fprintln(flag.CommandLine.Output())
  36. }
  37. if len(os.Args) >= 2 {
  38. flag.CommandLine.Parse(osArgs[2:])
  39. if *showHelp {
  40. flag.Usage()
  41. return nil
  42. }
  43. }
  44. fmt.Fprintln(flag.CommandLine.Output(), fmt.Sprintf("Formatting all %v files in %v", *ext, *dir))
  45. return FormatFiles(*dir, *ext)
  46. }
  47. /*
  48. FormatFiles formats all ECAL files in a given directory with a given ending.
  49. */
  50. func FormatFiles(dir string, ext string) error {
  51. var err error
  52. // Try to resolve symbolic links
  53. scanDir, lerr := os.Readlink(dir)
  54. if lerr != nil {
  55. scanDir = dir
  56. }
  57. if err == nil {
  58. err = filepath.Walk(scanDir,
  59. func(path string, i os.FileInfo, err error) error {
  60. if err == nil && !i.IsDir() {
  61. var data []byte
  62. var ast *parser.ASTNode
  63. var srcFormatted string
  64. if strings.HasSuffix(path, ext) {
  65. if data, err = ioutil.ReadFile(path); err == nil {
  66. var ferr error
  67. if ast, ferr = parser.Parse(path, string(data)); ferr == nil {
  68. if srcFormatted, ferr = parser.PrettyPrint(ast); ferr == nil {
  69. ioutil.WriteFile(path, []byte(fmt.Sprintln(srcFormatted)), i.Mode())
  70. }
  71. }
  72. if ferr != nil {
  73. fmt.Fprintln(flag.CommandLine.Output(), fmt.Sprintf("Could not format %v: %v", path, ferr))
  74. }
  75. }
  76. }
  77. }
  78. return err
  79. })
  80. }
  81. return err
  82. }