mts2json.go 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 MTS2JSON = &cobra.Command{
  23. Use: "mts2json [--indent=n] [mstFile|-] [outFile|-]",
  24. Short: "Convert binary MTS schematic file to JSON.",
  25. Long: "Read a binary mintest MTS schematic file and dump the output in "+
  26. "human-readable JSON 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. // Don't confuse the user: from this point on, errors are runtime errors.
  44. cmd.SilenceUsage = true
  45. indent := "\t"
  46. if nIndent >= 0 { indent = strings.Repeat(" ", nIndent) }
  47. var ins io.Reader = os.Stdin
  48. if len(args) > 0 && args[0] != "-" {
  49. file, err := os.Open(args[0])
  50. if err != nil { return err }
  51. defer file.Close()
  52. ins = file
  53. }
  54. var outs io.Writer = os.Stdout
  55. if len(args) > 1 && args[1] != "-" {
  56. file, err := os.Create(args[1])
  57. if err != nil { return err }
  58. defer file.Close()
  59. outs = file
  60. }
  61. s, err := schematic.FromMTSStream(ins)
  62. if err != nil { return err }
  63. return s.WriteJSON(outs, indent)
  64. },
  65. }
  66. func init() {
  67. MTS2JSON.Flags().Int("indent", -1, "N spaces to indent (<0 for tabs)")
  68. }