ProvideCommand provides the config related command.
(command *cobra.Command)
| 67 | |
| 68 | // ProvideCommand provides the config related command. |
| 69 | func (m Module) ProvideCommand(command *cobra.Command) { |
| 70 | var ( |
| 71 | targetFilePath string |
| 72 | style string |
| 73 | ) |
| 74 | initCmd := &cobra.Command{ |
| 75 | Use: "init [module]", |
| 76 | Short: "export a copy of default config.", |
| 77 | Long: "export a default config for currently installed modules.", |
| 78 | RunE: func(cmd *cobra.Command, args []string) error { |
| 79 | var ( |
| 80 | handler handler |
| 81 | targetFile *os.File |
| 82 | exportedConfigs []ExportedConfig |
| 83 | confMap map[string]interface{} |
| 84 | err error |
| 85 | ) |
| 86 | handler, err = getHandler(style) |
| 87 | if err != nil { |
| 88 | return err |
| 89 | } |
| 90 | if len(args) == 0 { |
| 91 | exportedConfigs = m.exportedConfigs |
| 92 | } |
| 93 | if len(args) >= 1 { |
| 94 | copy := make([]ExportedConfig, 0) |
| 95 | for i := range m.exportedConfigs { |
| 96 | for j := 0; j < len(args); j++ { |
| 97 | if args[j] == m.exportedConfigs[i].Owner { |
| 98 | copy = append(copy, m.exportedConfigs[i]) |
| 99 | break |
| 100 | } |
| 101 | } |
| 102 | } |
| 103 | exportedConfigs = copy |
| 104 | } |
| 105 | os.MkdirAll(filepath.Dir(targetFilePath), os.ModePerm) |
| 106 | targetFile, err = os.OpenFile(targetFilePath, |
| 107 | handler.flags(), os.ModePerm) |
| 108 | if err != nil { |
| 109 | return errors.Wrap(err, "failed to open config file") |
| 110 | } |
| 111 | defer targetFile.Close() |
| 112 | bytes, err := ioutil.ReadAll(targetFile) |
| 113 | if err != nil { |
| 114 | return errors.Wrap(err, "failed to read config file") |
| 115 | } |
| 116 | err = handler.unmarshal(bytes, &confMap) |
| 117 | if err != nil { |
| 118 | return errors.Wrap(err, "failed to unmarshal config file") |
| 119 | } |
| 120 | err = handler.write(targetFile, exportedConfigs, confMap) |
| 121 | if err != nil { |
| 122 | return errors.Wrap(err, "failed to write config file") |
| 123 | } |
| 124 | return nil |
| 125 | }, |
| 126 | } |