1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- // Copyright 2023 prestidigitator (as registered on forum.minetest.net)
- //
- // Licensed under the Apache License, Version 2.0 (the "License");
- // you may not use this file except in compliance with the License.
- // You may obtain a copy of the License at
- //
- // http://www.apache.org/licenses/LICENSE-2.0
- //
- // Unless required by applicable law or agreed to in writing, software
- // distributed under the License is distributed on an "AS IS" BASIS,
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- // See the License for the specific language governing permissions and
- // limitations under the License.
- package mts
- import (
- "bytes"
- "io"
- "os"
- "github.com/spf13/cobra"
- "notabug.org/prestidigitator-mt/minetest-goutils/schematic"
- )
- var YAML2MTS = &cobra.Command{
- Use: "yaml2mts [inFile|-] [outFile|-]",
- Aliases: []string{"json2mts"},
- Short: "Convert YAML to binary MTS schematic file.",
- Long: "Write a binary mintest MTS schematic file given a YAML or JSON input "+
- "definition.",
- Args: cobra.MaximumNArgs(2),
- ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) (
- []string, cobra.ShellCompDirective,
- ) {
- switch len(args) {
- case 0:
- return []string{"yaml", "json"}, cobra.ShellCompDirectiveFilterFileExt
- case 1:
- return []string{"mts"}, cobra.ShellCompDirectiveFilterFileExt
- default:
- return nil, cobra.ShellCompDirectiveNoFileComp
- }
- },
- RunE: func(cmd *cobra.Command, args []string) error {
- // Don't confuse the user: from this point on, errors are runtime errors.
- cmd.SilenceUsage = true
- var ins io.Reader = os.Stdin
- if len(args) > 0 && args[0] != "-" {
- file, err := os.Open(args[0])
- if err != nil { return err }
- defer file.Close()
- ins = file
- }
- // Eventually it might make sense to either have some predictive logic that can
- // determine the input type based on content (and/or file extension when
- // applicable), or still allow streaming when the input is a file rather than
- // stdin. But for now just gobble up the whole input and try to parse it
- // multiple times.
- inb, err := io.ReadAll(ins)
- if err != nil { return err }
- var outs io.Writer = os.Stdout
- if len(args) > 1 && args[1] != "-" {
- file, err := os.Create(args[1])
- if err != nil { return err }
- defer file.Close()
- outs = file
- }
- s, err := schematic.FromJSONStream(bytes.NewReader(inb))
- if err != nil {
- s, err = schematic.FromYAMLStream(bytes.NewReader(inb))
- if err != nil { return err }
- }
- return s.WriteMTS(outs)
- },
- }
|