mts2lua.go 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright 2023 prestidigitator (as registered on forum.minetest.net)
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package mts
  15. import (
  16. "io"
  17. "os"
  18. "strings"
  19. "github.com/spf13/cobra"
  20. "notabug.org/prestidigitator-mt/minetest-goutils/schematic"
  21. )
  22. var MTS2Lua = &cobra.Command{
  23. Use: "mts2lua [--indent=n] [--comments] [mstFile|-] [outFile|-]",
  24. Short: "Convert binary MTS schematic file to Lua chunk.",
  25. Long: "Read a binary mintest MTS schematic file and dump the output in "+
  26. "Lua source code format.",
  27. Args: cobra.MaximumNArgs(2),
  28. ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) (
  29. []string, cobra.ShellCompDirective,
  30. ) {
  31. switch len(args) {
  32. case 0:
  33. return []string{"mts"}, cobra.ShellCompDirectiveFilterFileExt
  34. case 1:
  35. return nil, cobra.ShellCompDirectiveDefault
  36. default:
  37. return nil, cobra.ShellCompDirectiveNoFileComp
  38. }
  39. },
  40. RunE: func(cmd *cobra.Command, args []string) error {
  41. flags := cmd.Flags()
  42. nIndent, err := flags.GetInt("indent"); if err != nil { return err }
  43. comments, err := flags.GetBool("comments"); if err != nil { return err }
  44. // Don't confuse the user: from this point on, errors are runtime errors.
  45. cmd.SilenceUsage = true
  46. indent := "\t"
  47. if nIndent >= 0 { indent = strings.Repeat(" ", nIndent) }
  48. var ins io.Reader = os.Stdin
  49. if len(args) > 0 && args[0] != "-" {
  50. file, err := os.Open(args[0])
  51. if err != nil { return err }
  52. defer file.Close()
  53. ins = file
  54. }
  55. var outs io.Writer = os.Stdout
  56. if len(args) > 1 && args[1] != "-" {
  57. file, err := os.Create(args[1])
  58. if err != nil { return err }
  59. defer file.Close()
  60. outs = file
  61. }
  62. s, err := schematic.FromMTSStream(ins)
  63. if err != nil { return err }
  64. return s.WriteLua(outs, indent, comments)
  65. },
  66. }
  67. func init() {
  68. MTS2Lua.Flags().Int("indent", -1, "N spaces to indent (<0 for tabs)")
  69. MTS2Lua.Flags().Bool("comments", false, "Include y, z comments (Lua format only).")
  70. }