graphql-engine/cli/commands/metadata.go

103 lines
2.3 KiB
Go
Raw Normal View History

2018-06-24 16:40:48 +03:00
package commands
import (
"encoding/json"
"io/ioutil"
"os"
"github.com/ghodss/yaml"
2018-06-24 16:40:48 +03:00
"github.com/hasura/graphql-engine/cli"
"github.com/hasura/graphql-engine/cli/migrate"
"github.com/pkg/errors"
2018-06-24 16:40:48 +03:00
"github.com/spf13/cobra"
)
func NewMetadataCmd(ec *cli.ExecutionContext) *cobra.Command {
2018-06-24 16:47:01 +03:00
metadataCmd := &cobra.Command{
2018-06-24 16:40:48 +03:00
Use: "metadata",
2018-10-20 06:23:20 +03:00
Short: "Manage Hasura GraphQL Engine metadata saved in the database",
2018-06-24 16:40:48 +03:00
SilenceUsage: true,
}
2018-06-24 16:47:01 +03:00
metadataCmd.AddCommand(
newMetadataExportCmd(ec),
newMetadataResetCmd(ec),
newMetadataReloadCmd(ec),
newMetadataApplyCmd(ec),
2018-06-24 16:40:48 +03:00
)
2018-06-24 16:47:01 +03:00
return metadataCmd
2018-06-24 16:40:48 +03:00
}
func executeMetadata(cmd string, t *migrate.Migrate, ec *cli.ExecutionContext) error {
switch cmd {
case "export":
metaData, err := t.ExportMetadata()
if err != nil {
return errors.Wrap(err, "cannot export metadata")
}
t, err := json.Marshal(metaData)
if err != nil {
return errors.Wrap(err, "cannot Marshal metadata")
}
data, err := yaml.JSONToYAML(t)
if err != nil {
return err
}
metadataPath, err := ec.GetMetadataFilePath("yaml")
if err != nil {
return errors.Wrap(err, "cannot save metadata")
}
err = ioutil.WriteFile(metadataPath, data, 0644)
if err != nil {
return errors.Wrap(err, "cannot save metadata")
}
case "reset":
err := t.ResetMetadata()
if err != nil {
return errors.Wrap(err, "cannot reset Metadata")
}
case "reload":
err := t.ReloadMetadata()
if err != nil {
return errors.Wrap(err, "cannot reload Metadata")
}
case "apply":
var data interface{}
var metadataContent []byte
for _, format := range []string{"yaml", "json"} {
metadataPath, err := ec.GetMetadataFilePath(format)
if err != nil {
return errors.Wrap(err, "cannot apply metadata")
}
metadataContent, err = ioutil.ReadFile(metadataPath)
if err != nil {
if os.IsNotExist(err) {
continue
}
return err
}
break
}
if metadataContent == nil {
return errors.New("Unable to locate metadata.[yaml|json] file under migrations directory")
}
err := yaml.Unmarshal(metadataContent, &data)
if err != nil {
return errors.Wrap(err, "cannot parse metadata file")
}
err = t.ApplyMetadata(data)
if err != nil {
return errors.Wrap(err, "cannot apply metadata on the database")
}
return nil
}
return nil
}